Magento module add rows to totals in pdf invoice - magento

I'm trying to write module for add item to row totals in pdf invoice. This is my modules config.xml:
<?xml version="1.0"?>
<config>
<modules>
<Devpassion_Rowtotal>
<version>0.0.1</version>
</Devpassion_Rowtotal>
</modules>
<global>
<pdf>
<totals>
<rowtotal translate="title">
<title>Subtotal less discount</title>
<source_field>rowtotal</source_field>
<model>rowtotal_pdf_model_totalpdf</model>
<font_size>7</font_size>
<display_zero>1</display_zero>
<sort_order>200</sort_order>
</rowtotal>
</totals>
</pdf>
And this is my model class:
class Devpassion_Rowtotal_Pdf_Model_Totalpdf extends Mage_Sales_Model_Order_Pdf_Total_Default {
public function getTotalsForDisplay () {
$order = $this->getOrder();
$item = $this->getItem();
$subtotaldisc = $item->getRowTotal() + $item->getTaxAmount() + $item->getHiddenTaxAmount() ; - $item->getDiscountAmount();
$result = $order->formatPriceTxt($subtotaldisc) ;
$totals = array(array(
'label' => 'Cijena sa popustom',
'amount' => $result,
'font_size' => $fontSize,
)
);
return $totals;
}
}
And nothing shows up on pdf invoice. Can anybody advice please what can be wrong here. Thanks.

I solved my problem, after I looked at my code, there is some mistakes. But my problem is not like yours.
I noticed that you have incorrect code in your config.xml and also in your model class. Try this.
config.xml
<global>
<pdf>
<totals>
<rowtotal translate="title">
<title>Subtotal less discount</title>
<source_field>rowtotal</source_field>
<model>Devpassion_Rowtotal_Pdf_Model_Totalpdf</model>
<font_size>7</font_size>
<display_zero>1</display_zero>
<sort_order>200</sort_order>
</rowtotal>
</totals>
</pdf>
</global>
Model class, Totalpdf.php
class Devpassion_Rowtotal_Pdf_Model_Totalpdf extends Mage_Sales_Model_Order_Pdf_Total_Default {
public function getTotalsForDisplay() {
$order = $this->getOrder();
$item = $this->getItem();
$subtotaldisc = $item->getRowTotal() + $item->getTaxAmount() + $item->getHiddenTaxAmount() - $item->getDiscountAmount();
$result = $order->formatPriceTxt($subtotaldisc);
if($this->getAmountPrefix()){
$result= $this->getAmountPrefix().$result;
}
$fontSize = $this->getFontSize() ? $this->getFontSize() : 7;
$totals = array(array(
'label' => 'Cijena sa popustom:',
'amount' => $result,
'font_size' => $fontSize,
)
);
return $totals;
}
}

I have tried the above code, it doesn't get the value of $item. I have get the subtotal value and discount value from $order object and it worked.
$order = $this->getOrder ();
$subtotaldisc = $order ['subtotal'] + $order ['discount_amount']; //discount amount returns negative value, so add
$result = $order->formatPriceTxt ( $subtotaldisc );
$fontSize = $this->getFontSize () ? $this->getFontSize () : 10;
$totals = array (
array (
'label' => 'Subtotal with Discount',
'amount' => $result,
'font_size' => $fontSize
)
);
return $totals;

I follow #Wakanina answer and change config.xml - path to pdf mode:
<pdf>
<totals>
<rowtotalbezpdv translate="title">
<title>Ukupno s popustom</title>
<source_field>rowtot_alamount</source_field>
<model>Devpassion_Rowtotalbezpdv_Model_Pdf_Total_Totalbezpdf</model>
<font_size>7</font_size>
<display_zero>0</display_zero>
<sort_order>300</sort_order>
</rowtotalbezpdv>
</totals>
</pdf>
And totalpdf Model class:
class Devpassion_Rowtotalbezpdv_Model_Pdf_Total_Totalbezpdf extends Mage_Sales_Model_Order_Pdf_Total_Default
{
public function getTotalsForDisplay(){
$amount = $this->getAmount();
$fontSize = $this->getFontSize() ? $this->getFontSize() : 7;
if(floatval($amount)){
$amount = $this->getOrder()->formatPriceTxt($amount);
$totals = array(
array(
'label' => 'Cijena knjige/a s popustom bez PDV-a',
'amount' => $amount,
'font_size' => $fontSize,
)
);
return $totals;
}
}
public function getAmount(){
$order = $this->getOrder();
$subtotaldiscnopdv = 0;
foreach ($order->getAllItems() as $item) {
$subtotaldiscnopdv += $item->getRowTotal() - $item->getDiscountAmount();
}
return $subtotaldiscnopdv;
}
}
This helps me out and solve my issue.

Related

Implement discounts in magento 1.9 with magento wallet functionality

I am have implemented custom discounts in magento which is working properly.But, when discount is implemented and someone is trying to pay from magento wallet balance, wallet seems to stop working and the amount paid from wallet does not get deducted from the grand total of the cart.
Discount is applied as follows:
config.xml-
<sales>
<quote>
<totals>
<discount>
<class>Uf_Rewards_Model_Discount</class>
<after>subtotal</after>
</discount>
</totals>
</quote>
</sales>
Discount.php:
class Uf_Rewards_Model_Discount extends Mage_SalesRule_Model_Quote_Discount {
public function collect(Mage_Sales_Model_Quote_Address $address) {
if ($address->getData('address_type') == 'billing')
return $this;
$discount = 10; //your discount percent
$grandTotal = $address->getGrandTotal();
$baseGrandTotal = $address->getBaseGrandTotal();
$totals = array_sum($address->getAllTotalAmounts());
$baseTotals = array_sum($address->getAllBaseTotalAmounts());
$address->setFeeAmount(-$discount);
$address->setBaseFeeAmount(-$discount);
$address->setGrandTotal($grandTotal + $address->getFeeAmount());
$address->setBaseGrandTotal($baseGrandTotal + $address->getBaseFeeAmount());
$address->setDiscountAmount(-$discount);
$address->setBaseDiscountAmount(-$discount);
return $this;
}
public function fetch(Mage_Sales_Model_Quote_Address $address) {
if ($address->getData('address_type') == 'billing')
return $this;
$amt = $address->getFeeAmount();
// $amt=300;
if ($amt != 0) {
Mage::log($amt, NULL, 'obsrvr.log');
$address->addTotal(array(
'code' => 'Discount',
'title' => 'Discount',
'value' => $amt
));
}
return $this;
}
}

Add multiple products to cart in magento 1.7.0.2

I add new module in magento 1.7.0.2.I have done according to the article. http://www.magentocommerce.com/boards/viewthread/9797/P30/.
When I added three products at the same time,but only one product can show correct price,others is $0.00 and Subiotal is wrong in it.Then I click on top of "My Cart" page,The price of correct in "My Cart" on the sidebar.
app/code/local/Perpetual/MultiAdd/controllers/Checkout/CartController.php
require_once('Mage/Checkout/controllers/CartController.php');
class Perpetual_MultiAdd_Checkout_CartController extends Mage_Checkout_CartController
{
/**
* Adding multiple products to shopping cart action
* based on Mage_Checkout_CartController::addAction()
* see also http://www.magentocommerce.com/boards/viewthread/8610/
* and http://www.magentocommerce.com/wiki/how_to_overload_a_controller
*/
public function addmultipleAction()
{
$productIds = $this->getRequest()->getParam('products');
if (!is_array($productIds)) {
$this->_goBack();
return;
}
foreach( $productIds as $productId) {
try {
$qty = $this->getRequest()->getParam('qty' . $productId, 0);
if ($qty <= 0) continue; // nothing to add
$cart = $this->_getCart();
$cart->init();
//$cart = Mage::getModel('checkout/cart')->init();
$product = Mage::getModel('catalog/product')
->setStoreId(Mage::app()->getStore()->getId())
->load($productId)
->setConfiguredAttributes($this->getRequest()->getParam('super_attribute'))
->setGroupedProducts($this->getRequest()->getParam('super_group', array()));
$eventArgs = array(
'product' => $product,
'qty' => $qty,
'request' => $this->getRequest(),
'response' => $this->getResponse(),
);
Mage::dispatchEvent('checkout_cart_before_add', $eventArgs);
$cart->addProduct($product, $qty);
Mage::dispatchEvent('checkout_cart_after_add', $eventArgs);
$cart->save();
Mage::dispatchEvent('checkout_cart_add_product', array('product'=>$product));
$message = $this->__('%s was successfully added to your shopping cart.', $product->getName());
Mage::getSingleton('checkout/session')->addSuccess($message);
}
catch (Mage_Core_Exception $e) {
if (Mage::getSingleton('checkout/session')->getUseNotice(true)) {
Mage::getSingleton('checkout/session')->addNotice($product->getName() . ': ' . $e->getMessage());
}
else {
Mage::getSingleton('checkout/session')->addError($product->getName() . ': ' . $e->getMessage());
}
}
catch (Exception $e) {
Mage::getSingleton('checkout/session')->addException($e, $this->__('Can not add item to shopping cart'));
}
}
$this->_goBack();
}
}
my template:
...
<form action="<?php echo $this->helper('multiadd/cart')->getAddToCartUrl() ?>" method="post" id="productAddToCartForm">
...
<label for="qty<?php echo $_product->getId()?>"><?php echo $this->__('Qty') ?>:</label>
<input type="text" name="qty<?php echo $_product->getId()?>" id="qty<?php echo $_product->getId()?>" maxlength="12" value="<?php echo ($this->getMinimalQty($_product)?$this->getMinimalQty($_product):0) ?>" class="input-text qty" />
...
<button class="button btn-cart" type="button" onclick="productAddToCartForm.submit()"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button>
</form>
...
app\code\local\Perpetual\MultiAdd\etc\config.xml
<?xml version="1.0"?>
<config>
<modules>
<Perpetual_MultiAdd>
<version>0.1.0</version>
</Perpetual_MultiAdd>
</modules>
<global>
<rewrite>
<perpetual_multiadd_checkout_cart>
<from><![CDATA[#^/checkout/cart/addmultiple/.*$#]]></from>
<to>/multiadd/checkout_cart/addmultiple/</to>
</perpetual_multiadd_checkout_cart>
</rewrite>
<helpers>
<multiadd>
<class>Perpetual_MultiAdd_Helper</class>
</multiadd>
</helpers>
</global>
<frontend>
<routers>
<perpetual_multiadd>
<use>standard</use>
<args>
<module>Perpetual_MultiAdd</module>
<frontName>multiadd</frontName>
</args>
</perpetual_multiadd>
</routers>
</frontend>
</config>
app\code\local\Perpetual\MultiAdd\Helper\Cart.php
<?php
class Perpetual_MultiAdd_Helper_Cart extends Mage_Core_Helper_Url
{
/**
* Return url to add multiple items to the cart
* #return url
*/
public function getAddToCartUrl()
{
if ($currentCategory = Mage::registry('current_category')) {
$continueShoppingUrl = $currentCategory->getUrl();
} else {
$continueShoppingUrl = $this->_getUrl('*/*/*', array('_current'=>true));
}
$params = array(
Mage_Core_Controller_Front_Action::PARAM_NAME_URL_ENCODED => Mage::helper('core')->urlEncode($continueShoppingUrl)
);
if ($this->_getRequest()->getModuleName() == 'checkout'
&& $this->_getRequest()->getControllerName() == 'cart') {
$params['in_cart'] = 1;
}
return $this->_getUrl('checkout/cart/addmultiple', $params);
}
}
?>
app\etc\modules\Perpetual_MultiAdd.xml
<?xml version="1.0"?>
<config>
<modules>
<Perpetual_MultiAdd>
<active>true</active>
<codePool>local</codePool>
<version>0.1.0</version>
</Perpetual_MultiAdd>
</modules>
</config>
How to fix the wrong price in "My Cart" on the sidebar?
I'm sorry for my English,it's not my home language.
Put $cart = $this->_getCart(); and $cart->save(); outside foreach.
require_once('Mage/Checkout/controllers/CartController.php');
class Perpetual_MultiAdd_Checkout_CartController extends Mage_Checkout_CartController
{
/**
* Adding multiple products to shopping cart action
* based on Mage_Checkout_CartController::addAction()
* see also http://www.magentocommerce.com/boards/viewthread/8610/
* and http://www.magentocommerce.com/wiki/how_to_overload_a_controller
*/
public function addmultipleAction()
{
$productIds = $this->getRequest()->getParam('products');
if (!is_array($productIds)) {
$this->_goBack();
return;
}
$cart = $this->_getCart();
foreach( $productIds as $productId) {
try {
$qty = $this->getRequest()->getParam('qty' . $productId, 0);
if ($qty <= 0) continue; // nothing to add
//$cart = $this->_getCart();
$product = Mage::getModel('catalog/product')
->setStoreId(Mage::app()->getStore()->getId())
->load($productId)
->setConfiguredAttributes($this->getRequest()->getParam('super_attribute'))
->setGroupedProducts($this->getRequest()->getParam('super_group', array()));
$eventArgs = array(
'product' => $product,
'qty' => $qty,
'request' => $this->getRequest(),
'response' => $this->getResponse(),
);
Mage::dispatchEvent('checkout_cart_before_add', $eventArgs);
//$cart = Mage::getModel('checkout/cart')->init();
$cart->addProduct($product, $qty);
Mage::dispatchEvent('checkout_cart_after_add', $eventArgs);
//$cart->save();
Mage::dispatchEvent('checkout_cart_add_product', array('product'=>$product));
$message = $this->__('%s was successfully added to your shopping cart.', $product->getName());
Mage::getSingleton('checkout/session')->addSuccess($message);
}
catch (Mage_Core_Exception $e) {
if (Mage::getSingleton('checkout/session')->getUseNotice(true)) {
Mage::getSingleton('checkout/session')->addNotice($product->getName() . ': ' . $e->getMessage());
}
else {
Mage::getSingleton('checkout/session')->addError($product->getName() . ': ' . $e->getMessage());
}
}
catch (Exception $e) {
Mage::getSingleton('checkout/session')->addException($e, $this->__('Can not add item to shopping cart'));
}
}
$cart->save();
$this->_goBack();
}
}
Found it! Put this anywhere after your cart save. It will reset your cart and reload your quote to recalculate the prices of all products.
Mage::unregister('_singleton/checkout/cart');
Mage::unregister('_singleton/checkout/session');
$cart = $this->_getCart();
$this->_getQuote();
if ($cart->getQuote()->getItemsCount()) {
$cart->init();
$cart->save();
}
May be this one will help:
http://deepakbhatta.com/magento-add-multiple-items-to-cart/
Overview is:
$cart = Mage::helper('checkout/cart')->getCart();
$ms="";
foreach($validProducts as $sku => $qty) {
$params = array('qty' => $qty);
$id = Mage::getModel('catalog/product')->getIdBySku($sku);
$product = Mage::getModel('catalog/product')->load($id);;
$cart->addProduct($product, $params);
$msg .= $product->getName(). " is successfully added into cart<br>";
}
$cart->save();
Recently, we have launched a free top-notch extension - Add Multiple Products to Cart for Magento to improve the online shopping experience of customers.
This extension allows users to add multiple products and add all to the cart with a single click. More importantly, it will allow the customers to enter the Quantity from category page itself.
http://www.magentocommerce.com/magento-connect/add-multiple-products-to-cart.html
This is exactly what you need.

Magento Override Model Mage_Catalog_Model_Product_Attribute_Backend_Media

I use magento 1.7 and i try to override the model Model Mage_Catalog_Model_Product_Attribute_Backend_Media but this doesn't work.
My class :
class Mycompany_Mymodule_Model_Catalog_Product_Attribute_Backend_Media extends Mage_Catalog_Model_Product_Attribute_Backend_Media
My config :
...
<model>
<catalog>
<rewrite> <product_attribute_backend_media>Mycompany_Mymodule_Model_Catalog_Product_Attribute_Backend_Media</product_attribute_backend_media>
</rewrite>
</catalog>
</model>
Can you help me ?
Thx
You do not need to over write any core files at all.
What you need to do is create 1 new files:
[Namespace]/[Module]/Block/[Adminhtml]/template/grid/renderer/Image.php
For the Image.php
class [Namespace]_[Module]_Block_[Adminhtml]_Template_Grid_Renderer_Image extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Action {
public function render(Varien_Object $row)
{
return $this->_getValue($row);
}
public function _getValue(Varien_Object $row)
{
if ($getter = $this->getColumn()->getGetter()) {
$val = $row->$getter();
}
$val = $row->getData($this->getColumn()->getIndex());
$val = str_replace("no_selection", "", $val);
$url = Mage::getBaseUrl('media') . DS . $val;
$out = $val. '<center><a href="'.$_url.'" target="_blank" id="imageurl">';
$out .= "<img src=". $url ." width='60px' ";
$out .=" />";
$out .= '</a></center>';
return $out;
}
}
change code in the function as required to get to your folder, and error checking.
For the Grid.php add the following to one of your addColumns like below
$this->addColumn('image1', array(
'header' => Mage::helper('attributeimages')->__('Image 1'),
'align' => 'left',
'index' => 'image1',
'renderer' => '[module]/[adminhtml]_template_grid_renderer_image',));
Notice the ‘renderer’ option!
customize as you will

Showing Product Options (upsells and freebies) in the sales order grid

Hello The Great Developers,
I want to customize the sales order Grid.
currently several product options are added when ever the product is added to the cart.
and they are showing up in the Order detail page in the admin panel.
but i want to make it show up in the Sales order grid.
and if i made a join query to show the product options from the sales_flat_order_item table, it is showing php array string in the serialized form which is unreadable. looks like json string.
I have been working on this issue from the past 2 days but haven't got any proper solution for this.
Your help will be fully appreciated.
Create a custom module...
read more http://tutorials.slcdev.com/2012/04/magento-extend-order-grid/ or http://inchoo.net/ecommerce/magento/how-to-extend-magento-order-grid/
In app/code/local/RWS/OrderGridOptions/etc/config.xml
<global>
<blocks>
<adminhtml>
<rewrite>
<sales_order_grid>RWS_OrderGridOptions_Block_Adminhtml_Sales_Order_Grid</sales_order_grid>
</rewrite>
</adminhtml>
</blocks>
</global>
Create in app/code/local/RWS/OrderGridOptions/Block/Adminhtml/Sales/Order/Grid.php
(see app/code/core/Mage/Adminhtml/Block/Sales/Order/Grid.php)
create function _prepareColumns()
$this->addColumn('product_options', array(
'header' => Mage::helper('order')->__('Options'),
'width' => '150',
'index' => 'product_options'
'renderer' = new RWS_OrderGridOptions_Block_Adminhtml_Renderer_Data() // added this line
));
Read more # http://www.magentocommerce.com/boards/viewthread/192232/#t239222
in app/code/local/RWS/OrderGridOptions/Block/Adminhtml/Renderer/Data.php
class RWS_OrderGridOptions_Block_Adminhtml_Renderer_Data extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Action
{
public function render(Varien_Object $row)
{
return $this->_getValue($row);
}
public function _getValue(Varien_Object $row)
{
$val = $row->getData($this->getColumn()->getIndex()); // row value
$array = unserialize($val);
//loop thru the $array and create a format string
//
$format_val = $array['xyx'] . ' ' . $array['abc'];
return $format_val;
}
}
I followed the code #R.S s with the following modifications to the renderer out more user friendly:
public function render(Varien_Object $row)
{
return $this->_getValue($row);
}
public function _getValue(Varien_Object $row)
{
$codeIndex = $row->getData($this->getColumn()->getIndex()); // row value
$prodOpUns = unserialize($codeIndex);
$dataOpt = $prodOpUns['options'];
$returnHtml = '<dl class="item-options">';
for ($i=0; $i<count($dataOpt); $i++){
$value = str_replace(array("<", ">"), array("<", ">"), htmlspecialchars($dataOpt[$i]['print_value'], ENT_COMPAT, "UTF-8", false));
$returnHtml .= '<dt>'.strtolower($dataOpt[$i]['label']) .'</dt>' . '<dd>' . $value . '</dd>';
}
$returnHtml .= '</dl>';
return $returnHtml;
}

Add Username to Order Comment History

Is there a simple way to add the username of the person who is making the comment in the admin history to the comment thread on the order?
-- edit --
Another way of asking this would be how do I add an additional field to the comment history model so that I can override the appropriate models and templates inserting that data into the data structure.
If you want to add the username who is currently logged in and making change in order or commenting on order. you need to add an attribute to magento.
Create a Module say Audit
app / etc / modules / Namespace_Audit.xml
<?xml version="1.0"?>
<config>
<modules>
<Namespace_Audit>
<active>true</active>
<codePool>local</codePool>
<depends>
<Mage_Sales/>
</depends>
</Namespace_Audit>
</modules>
</config>
then Create a folder Audit in you namespace and create the config file. purpose of this is to rewrite the core class and extending for modified method
app / code / local / Namespace / Audit / etc / config.xml
`<?xml version="1.0"?>
<config>
<modules>
<Namespace_Audit>
<version>0.1.0</version>
</Namespace_Audit>
</modules>
<global>
<blocks>
<adminhtml>
<rewrite>
<sales_order_view_tab_history before="Mage_Adminhtml_Block">Namespace_Audit_Block_Sales_Order_View_Tab_History<sales_order_view_tab_history>
</rewrite>
</adminhtml>
</blocks>
<global>
<models>
<audit>
<class>Bigadda_Audit_Model</class>
</audit>
</models>
<resources>
<audit_setup>
<setup>
<module>Bigadda_Audit</module>
</setup>
<connection>
<use>core_setup</use>
</connection>
</audit_setup>
<audit_write>
<connection>
<use>core_write</use>
</connection>
</audit_write>
<audit_read>
<connection>
<use>core_read</use>
</connection>
</audit_read>
</resources>
</global>
</global>
</config>`
create a setup to make a new attribute in database
local / Namespace / Audit / sql / audit_setup / mysql4-install-0.1.0.php
`
<?php
$installer = $this;
$installer->startSetup();
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$setup->addAttribute('order_status_history', 'track_user', array('type' => 'varchar'));
$installer->endSetup();
`
Now extending the existing class . create a class file History.php
Namespace/Audit/Block/Sales/Order/View/Tab/History
and copy the functions in that
`
public function getFullHistory()
{
$order = $this->getOrder();
$history = array();
foreach ($order->getAllStatusHistory() as $orderComment){
$history[$orderComment->getEntityId()] = $this->_prepareHistoryItem(
$orderComment->getStatusLabel(),
$orderComment->getIsCustomerNotified(),
$orderComment->getCreatedAtDate(),
$orderComment->getComment(),
$orderComment->getTrackUser(),
$orderComment->getTrackUserName()
);
}
foreach ($order->getCreditmemosCollection() as $_memo){
$history[$_memo->getEntityId()] =
$this->_prepareHistoryItem($this->__('Credit Memo #%s created', $_memo->getIncrementId()),
$_memo->getEmailSent(), $_memo->getCreatedAtDate());
foreach ($_memo->getCommentsCollection() as $_comment){
$history[$_comment->getEntityId()] =
$this->_prepareHistoryItem($this->__('Credit Memo #%s comment added', $_memo->getIncrementId()),
$_comment->getIsCustomerNotified(), $_comment->getCreatedAtDate(), $_comment->getComment(),$_comment->getTrackUser(),$_comment->getTrackUserName());
}
}
foreach ($order->getShipmentsCollection() as $_shipment){
$history[$_shipment->getEntityId()] =
$this->_prepareHistoryItem($this->__('Shipment #%s created', $_shipment->getIncrementId()),
$_shipment->getEmailSent(), $_shipment->getCreatedAtDate());
foreach ($_shipment->getCommentsCollection() as $_comment){
$history[$_comment->getEntityId()] =
$this->_prepareHistoryItem($this->__('Shipment #%s comment added', $_shipment->getIncrementId()),
$_comment->getIsCustomerNotified(), $_comment->getCreatedAtDate(), $_comment->getComment(),$_comment->getTrackUser(),$_comment->getTrackUserName());
}
}
foreach ($order->getInvoiceCollection() as $_invoice){
$history[$_invoice->getEntityId()] =
$this->_prepareHistoryItem($this->__('Invoice #%s created', $_invoice->getIncrementId()),
$_invoice->getEmailSent(), $_invoice->getCreatedAtDate());
foreach ($_invoice->getCommentsCollection() as $_comment){
$history[$_comment->getEntityId()] =
$this->_prepareHistoryItem($this->__('Invoice #%s comment added', $_invoice->getIncrementId()),
$_comment->getIsCustomerNotified(), $_comment->getCreatedAtDate(), $_comment->getComment(),$_comment->getTrackUser(),$_comment->getTrackUserName());
}
}
foreach ($order->getTracksCollection() as $_track){
$history[$_track->getEntityId()] =
$this->_prepareHistoryItem($this->__('Tracking number %s for %s assigned', $_track->getNumber(), $_track->getTitle()),
false, $_track->getCreatedAtDate());
}
krsort($history);
return $history;
}`
protected function _prepareHistoryItem($label, $notified, $created, $comment = '' , $trackUser = '' , $trackUserName ='')
{
return array(
'title' => $label,
'notified' => $notified,
'track_user' => $trackUser,
'track_user_name' => $trackUserName,
'comment' => $comment,
'created_at' => $created
);
}
extend the class order.php and add this method to set the comment to update the database.
app / code / local / Mynamespace / Sales / Model / Order.php
public function addStatusHistoryComment($comment, $status = false)
{
if (false === $status) {
$status = $this->getStatus();
} elseif (true === $status) {
$status = $this->getConfig()->getStateDefaultStatus($this->getState());
} else {
$this->setStatus($status);
}
$UserInfo = Mage::getSingleton('admin/session')->getUser();
$UserName='';
$UserName=$UserInfo->getUsername();
$history = Mage::getModel('sales/order_status_history')
->setStatus($status)
->setComment($comment)
->setTrackUser($UserName); //added by vipul dadhich to add audits in the
$this->addStatusHistory($history);
return $history;
}
finally updating the phtml files.
app / design / adminhtml / default / default / template / sales / order / view / history.phtml
place this code wherever u want to show the username
<?php if ($_item->getTrackUser()): ?>
<br/><?php echo "<b>Updated By ( User ) :- </b>".$this->htmlEscape($_item->getTrackUser(), array('b','br','strong','i','u')) ?>
<?php endif; ?>
app / design / adminhtml / default / default / template / sales / order / view / tab / history.phtml
<?php if ($_comment = $this->getItemTrackUser($_item)): ?>
<br/><?php echo "<b>Updated By (User) :- </b>".$_comment ?>
<?php endif; ?>
Thats All folks..
Vipul Dadhich
A different take by observing the event *sales_order_status_history_save_before*
Define the setup and observer in your config:
<config>
<modules>
<Name_Module>
<version>0.0.1</version>
</Name_Module>
</modules>
<global>
<resources>
<module_setup>
<setup>
<module>Name_Module</module>
</setup>
<connection>
<use>core_setup</use>
</connection>
</module_setup>
</resources>
<events>
<sales_order_status_history_save_before>
<observers>
<sales_order_status_history_save_before_observer>
<type>singleton</type>
<class>Name_Module_Model_Observer</class>
<method>orderStatusHistorySaveBefore</method>
</sales_order_status_history_save_before_observer>
</observers>
</sales_order_status_history_save_before>
</events>
<!-- and so on ->
In your module_setup file app\code\local\Name\Module\sql\module_setup\install-0.0.1.php
$installer = $this;
$installer->startSetup();
$table = $installer->getTable('sales/order_status_history');
$installer->getConnection()
->addColumn($table, 'username', array(
'type' => Varien_Db_Ddl_Table::TYPE_TEXT,
'length' => 40,
'nullable' => true,
'comment' => 'Admin user name'
));
$installer->getConnection()
->addColumn($table, 'userrole', array(
'type' => Varien_Db_Ddl_Table::TYPE_TEXT,
'length' => 50,
'nullable' => true,
'comment' => 'Admin user role'
));
$installer->endSetup();
Then in Name_Module_Model_Observer:
public function orderStatusHistorySaveBefore($observer)
{
$session = Mage::getSingleton('admin/session');
if ($session->isLoggedIn()) { //only for login admin user
$user = $session->getUser();
$history = $observer->getEvent()->getStatusHistory();
if (!$history->getId()) { //only for new entry
$history->setData('username', $user->getUsername());
$role = $user->getRole(); //if you have the column userrole
$history->setData('userrole', $role->getRoleName()); //you can save it too
}
}
}
In Magento 2
You need to override the AddComment.php file in vendor/magento/module-sales
If you want to edit the core file AddComment.php then you can add the following code to your AddComment.php file
$username = $this->authSession->getUser()->getUsername();
$append = " (by ".$username.")";
$history = $order->addStatusHistoryComment($data['comment'].$append, $data['status']);
But this is not a good practice to modify core files directly. You need to make your new module and override
Vendor/Module/etc/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Sales\Controller\Adminhtml\Order\AddComment" type="Vendor\Module\Controller\Adminhtml\Order\AddComment" />
</config>
Vendor\Module\Controller\Adminhtml\Order\AddComment.php
<?php
namespace Vendor\Module\Controller\Adminhtml\Order;
use Magento\Backend\App\Action;
use Magento\Sales\Model\Order\Email\Sender\OrderCommentSender;
use Magento\Sales\Api\OrderManagementInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Exception\InputException;
use Psr\Log\LoggerInterface;
class AddComment extends \Magento\Sales\Controller\Adminhtml\Order
{
/**
* Authorization level of a basic admin session
*
* #see _isAllowed()
*/
const ADMIN_RESOURCE = 'Magento_Sales::comment';
/**
* Core registry
*
* #var \Magento\Framework\Registry
*/
protected $_coreRegistry = null;
/**
* #var \Magento\Framework\App\Response\Http\FileFactory
*/
protected $_fileFactory;
/**
* #var \Magento\Framework\Translate\InlineInterface
*/
protected $_translateInline;
/**
* #var \Magento\Framework\View\Result\PageFactory
*/
protected $resultPageFactory;
/**
* #var \Magento\Framework\Controller\Result\JsonFactory
*/
protected $resultJsonFactory;
/**
* #var \Magento\Framework\View\Result\LayoutFactory
*/
protected $resultLayoutFactory;
/**
* #var \Magento\Framework\Controller\Result\RawFactory
*/
protected $resultRawFactory;
/**
* #var OrderManagementInterface
*/
protected $orderManagement;
/**
* #var OrderRepositoryInterface
*/
protected $orderRepository;
/**
* #var LoggerInterface
*/
protected $logger;
protected $authSession;
public function __construct(
Action\Context $context,
\Magento\Framework\Registry $coreRegistry,
\Magento\Framework\App\Response\Http\FileFactory $fileFactory,
\Magento\Framework\Translate\InlineInterface $translateInline,
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
\Magento\Framework\View\Result\LayoutFactory $resultLayoutFactory,
\Magento\Framework\Controller\Result\RawFactory $resultRawFactory,
OrderManagementInterface $orderManagement,
OrderRepositoryInterface $orderRepository,
LoggerInterface $logger,
\Magento\Backend\Model\Auth\Session $authSession
) {
$this->authSession = $authSession;
parent::__construct($context, $coreRegistry,$fileFactory,$translateInline,$resultPageFactory,$resultJsonFactory,$resultLayoutFactory,$resultRawFactory,$orderManagement,$orderRepository,$logger);
}
/**
* Add order comment action
*
* #return \Magento\Framework\Controller\ResultInterface
*/
public function execute()
{
$order = $this->_initOrder();
if ($order) {
try {
$data = $this->getRequest()->getPost('history');
if (empty($data['comment']) && $data['status'] == $order->getDataByKey('status')) {
throw new \Magento\Framework\Exception\LocalizedException(__('Please enter a comment.'));
}
$notify = isset($data['is_customer_notified']) ? $data['is_customer_notified'] : false;
$visible = isset($data['is_visible_on_front']) ? $data['is_visible_on_front'] : false;
$username = $this->authSession->getUser()->getUsername();
$append = " (by ".$username.")";
$history = $order->addStatusHistoryComment($data['comment'].$append, $data['status']);
$history->setIsVisibleOnFront($visible);
$history->setIsCustomerNotified($notify);
$history->save();
$comment = trim(strip_tags($data['comment']));
$order->save();
/** #var OrderCommentSender $orderCommentSender */
$orderCommentSender = $this->_objectManager
->create(\Magento\Sales\Model\Order\Email\Sender\OrderCommentSender::class);
$orderCommentSender->send($order, $notify, $comment);
return $this->resultPageFactory->create();
} catch (\Magento\Framework\Exception\LocalizedException $e) {
$response = ['error' => true, 'message' => $e->getMessage()];
} catch (\Exception $e) {
$response = ['error' => true, 'message' => __('We cannot add order history.')];
}
if (is_array($response)) {
$resultJson = $this->resultJsonFactory->create();
$resultJson->setData($response);
return $resultJson;
}
}
return $this->resultRedirectFactory->create()->setPath('sales/*/');
}
}

Resources