OrderCreateTotalsPlugin.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. /**
  3. * @copyright Vertex. All rights reserved. https://www.vertexinc.com/
  4. * @author Mediotype https://www.mediotype.com/
  5. */
  6. namespace Vertex\Tax\Block\Plugin;
  7. use Vertex\Tax\Model\Calculation\VertexCalculator;
  8. use Vertex\Tax\Model\TaxRegistry;
  9. use Magento\Sales\Block\Adminhtml\Order\Create\Totals;
  10. use Magento\Framework\Message\ManagerInterface;
  11. use Magento\Framework\View\Element\BlockInterface;
  12. /**
  13. * Prepare tax service errors.
  14. *
  15. * During admin order management, tax calculation errors must be given where possible.
  16. * This plugin transfers those error messages to the message block before it is rendered.
  17. */
  18. class OrderCreateTotalsPlugin
  19. {
  20. /** @var ManagerInterface */
  21. private $messageManager;
  22. /** @var TaxRegistry */
  23. private $taxRegistry;
  24. /** @var boolean A state flag to ensure that errors are only dispatched once. */
  25. private $hasNotified = false;
  26. /**
  27. * @param ManagerInterface $messageManager
  28. * @param TaxRegistry $taxRegistry
  29. */
  30. public function __construct(ManagerInterface $messageManager, TaxRegistry $taxRegistry)
  31. {
  32. $this->messageManager = $messageManager;
  33. $this->taxRegistry = $taxRegistry;
  34. }
  35. /**
  36. * Resend data from the message manager to the target message block pre-render.
  37. *
  38. * @param Totals $subject
  39. * @return void
  40. */
  41. private function updateMessageBlock(Totals $context)
  42. {
  43. /** @var \Magento\Sales\Block\Adminhtml\Order\Create\Messages|bool $block */
  44. $block = $context->getLayout()->getBlock('message');
  45. if ($block instanceof BlockInterface) {
  46. $block->addMessages($this->messageManager->getMessages(true));
  47. }
  48. }
  49. /**
  50. * Add tax service errors after totals collection.
  51. *
  52. * @param Totals $subject
  53. * @param array $results
  54. * @return array
  55. */
  56. public function afterGetTotals(Totals $subject, array $results)
  57. {
  58. if (!$this->hasNotified) {
  59. $error = $this->taxRegistry->lookup(TaxRegistry::KEY_ERROR_GENERIC);
  60. if (!empty($error)) {
  61. $this->updateMessageBlock($subject);
  62. $this->hasNotified = true;
  63. }
  64. }
  65. return $results;
  66. }
  67. }