InvoiceShippingProcessor.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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\Model\Api\Data\InvoiceRequestBuilder;
  7. use Magento\Sales\Api\Data\InvoiceInterface;
  8. use Magento\Sales\Api\Data\InvoiceItemInterface;
  9. use Vertex\Services\Invoice\RequestInterface;
  10. /**
  11. * Processes Shipping on an Invoice and adds it to a Vertex Invoice's LineItems
  12. */
  13. class InvoiceShippingProcessor implements InvoiceProcessorInterface
  14. {
  15. /** @var ShippingProcessor */
  16. private $shippingProcessor;
  17. /**
  18. * @param ShippingProcessor $shippingProcessor
  19. */
  20. public function __construct(ShippingProcessor $shippingProcessor)
  21. {
  22. $this->shippingProcessor = $shippingProcessor;
  23. }
  24. /**
  25. * @inheritdoc
  26. */
  27. public function process(RequestInterface $request, InvoiceInterface $invoice)
  28. {
  29. if (!$invoice->getBaseShippingAmount()) {
  30. return $request;
  31. }
  32. $request->setLineItems(
  33. array_merge(
  34. $request->getLineItems(),
  35. $this->shippingProcessor->getShippingLineItems(
  36. $invoice->getOrderId(),
  37. $invoice->getBaseShippingAmount() - $this->getBaseShippingDiscountAmount($invoice)
  38. )
  39. )
  40. );
  41. return $request;
  42. }
  43. /**
  44. * Retrieve total discount less line item discounts
  45. *
  46. * At the time of this writing, Magento only applies discounts to line items
  47. * and to the shipping. Unfortunately for invoices and creditmemos it does
  48. * not record the amount of shipping being discounted at the time of invoice
  49. * or credit. As such, to attempt to figure out what that is, we have to
  50. * remove the line item discounts from the total discount.
  51. *
  52. * This code will break if Magento ever allows discounts to apply to other
  53. * items like Giftwrapping and Printed Cards
  54. *
  55. * @param InvoiceInterface $invoice
  56. * @return float
  57. */
  58. private function getBaseShippingDiscountAmount(InvoiceInterface $invoice)
  59. {
  60. $totalDiscount = $invoice->getBaseDiscountAmount() * -1; // discount is stored as a negative here
  61. $lineItemDiscount = 0;
  62. foreach ($invoice->getItems() as $item) {
  63. $lineItemDiscount += (float)$item->getDiscountAmount();
  64. }
  65. return $totalDiscount - $lineItemDiscount;
  66. }
  67. }