AddComment.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Sales\Controller\Adminhtml\Order;
  7. use Magento\Framework\App\Action\HttpPostActionInterface;
  8. use Magento\Sales\Model\Order\Email\Sender\OrderCommentSender;
  9. /**
  10. * Class AddComment
  11. */
  12. class AddComment extends \Magento\Sales\Controller\Adminhtml\Order implements HttpPostActionInterface
  13. {
  14. /**
  15. * Authorization level of a basic admin session
  16. *
  17. * @see _isAllowed()
  18. */
  19. const ADMIN_RESOURCE = 'Magento_Sales::comment';
  20. /**
  21. * ACL resource needed to send comment email notification
  22. */
  23. const ADMIN_SALES_EMAIL_RESOURCE = 'Magento_Sales::emails';
  24. /**
  25. * Add order comment action
  26. *
  27. * @return \Magento\Framework\Controller\ResultInterface
  28. */
  29. public function execute()
  30. {
  31. $order = $this->_initOrder();
  32. if ($order) {
  33. try {
  34. $data = $this->getRequest()->getPost('history');
  35. if (empty($data['comment']) && $data['status'] == $order->getDataByKey('status')) {
  36. throw new \Magento\Framework\Exception\LocalizedException(
  37. __('The comment is missing. Enter and try again.')
  38. );
  39. }
  40. $notify = $data['is_customer_notified'] ?? false;
  41. $visible = $data['is_visible_on_front'] ?? false;
  42. if ($notify && !$this->_authorization->isAllowed(self::ADMIN_SALES_EMAIL_RESOURCE)) {
  43. $notify = false;
  44. }
  45. $history = $order->addStatusHistoryComment($data['comment'], $data['status']);
  46. $history->setIsVisibleOnFront($visible);
  47. $history->setIsCustomerNotified($notify);
  48. $history->save();
  49. $comment = trim(strip_tags($data['comment']));
  50. $order->save();
  51. /** @var OrderCommentSender $orderCommentSender */
  52. $orderCommentSender = $this->_objectManager
  53. ->create(\Magento\Sales\Model\Order\Email\Sender\OrderCommentSender::class);
  54. $orderCommentSender->send($order, $notify, $comment);
  55. return $this->resultPageFactory->create();
  56. } catch (\Magento\Framework\Exception\LocalizedException $e) {
  57. $response = ['error' => true, 'message' => $e->getMessage()];
  58. } catch (\Exception $e) {
  59. $response = ['error' => true, 'message' => __('We cannot add order history.')];
  60. }
  61. if (is_array($response)) {
  62. $resultJson = $this->resultJsonFactory->create();
  63. $resultJson->setData($response);
  64. return $resultJson;
  65. }
  66. }
  67. return $this->resultRedirectFactory->create()->setPath('sales/*/');
  68. }
  69. }