【问题标题】:Add Username to Order Comment History将用户名添加到订单评论历史记录
【发布时间】:2011-06-02 19:51:26
【问题描述】:

有没有一种简单的方法可以将在管理历史记录中发表评论的人的用户名添加到订单的评论线程中?

-- 编辑--

询问这个问题的另一种方法是如何向评论历史模型添加一个额外的字段,以便我可以覆盖将数据插入数据结构的适当模型和模板。

【问题讨论】:

  • 第一个问题的答案是否定的:)

标签: magento magento-1.4


【解决方案1】:

如果您想添加当前登录的用户名并更改订单或评论订单。你需要给magento添加一个属性。

创建一个模块说审计 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>

然后在您的命名空间中创建一个文件夹 Audit 并创建配置文件。这样做的目的是重写核心类并扩展修改方法

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>`

创建设置以在数据库中创建新属性 本地/命名空间/审计/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();
`

现在扩展现有的类。创建一个类文件History.php

命名空间/审核/块/销售/订单/视图/选项卡/历史记录

并复制其中的功能

` 公共函数 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            
        );
    }

扩展类 order.php 并添加此方法来设置评论以更新数据库。 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;

        }

终于更新了 phtml 文件。 app/design/adminhtml/default/default/template/sales/order/view/history.phtml 将此代码放置在您要显示用户名的任何位置

<?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; ?>

这就是所有人..

维普尔·达迪奇

【讨论】:

  • 感谢您对此的帮助。我不得不做一些调整,但你的代码几乎已经死了。
  • 我发现的一个大问题是 Mage::getSingleton('admin/session')->getUser();在前端不可用并导致我的正常结帐失败。你遇到过这个吗?你是怎么克服的?
  • 我找到了解决方法,您需要在模型上执行此操作 $UserInfo = Mage::getSingleton('admin/session')->getUser(); if ($UserInfo) $UserName = $UserInfo->getUsername();
  • if() { // 如果以管理员身份登录 } else { if(Mage::getSingleton('customer/session')->isLoggedIn()) { $UserId=Mage::getSingleton( '客户/会话')->getCustomer()->getId(); $UserName='Customer'.Mage::getSingleton('customer/session')->getCustomer()->getName(); } else { $UserId="商店购买"; $UserName="前端";} }
【解决方案2】:

通过观察事件 *sales_order_status_history_save_before* 获得不同的看法

在您的配置中定义设置和观察者:

<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 ->

在您的 module_setup 文件 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();

然后在 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
        }            
    }
}  

【讨论】:

  • 不错,简单干净的方式。谢谢朋友。
  • 您好,如何在 magento 1 中获取订单 cmets 历史记录? @kiatng
  • 要获取订单的所有评论历史记录,请尝试$historyCollection = Mage::getModel('sales/order')-&gt;load($orderId)-&gt;getStatusHistoryCollection();
【解决方案3】:

在 Magento 2 中

您需要覆盖vendor/magento/module-sales中的AddComment.php文件

如果您想编辑核心文件AddComment.php,那么您可以将以下代码添加到您的AddComment.php 文件中

$username = $this->authSession->getUser()->getUsername();
$append = " (by ".$username.")";
$history = $order->addStatusHistoryComment($data['comment'].$append, $data['status']);

但这不是直接修改核心文件的好习惯。您需要制作新模块并覆盖

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/*/');
}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-30
    • 2017-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多