Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 549
Chris Avatar asked Jun 02 '11 19:06

Chris


Video Answer


2 Answers

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/*/');
}
}
like image 74
Muhammad Hasham Avatar answered Nov 30 '22 14:11

Muhammad Hasham


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
        }            
    }
}  
like image 31
kiatng Avatar answered Nov 30 '22 15:11

kiatng