AddShipmentTrack.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. /**
  3. * Refer to LICENSE.txt distributed with the Temando Shipping module for notice of license
  4. */
  5. namespace Temando\Shipping\Model\Sales\Service\Operation;
  6. use Magento\Framework\Exception\LocalizedException;
  7. use Magento\Sales\Api\Data\ShipmentTrackInterfaceFactory;
  8. use Magento\Sales\Api\ShipmentRepositoryInterface;
  9. use Temando\Shipping\Model\ShipmentInterface;
  10. use Temando\Shipping\Model\Shipping\Carrier;
  11. /**
  12. * Temando Shipment Operation: Add Track.
  13. *
  14. * @package Temando\Shipping\Model
  15. * @author Christoph Aßmann <christoph.assmann@netresearch.de>
  16. * @license https://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
  17. * @link https://www.temando.com/
  18. */
  19. class AddShipmentTrack implements ShipmentOperationInterface
  20. {
  21. /**
  22. * @var ShipmentRepositoryInterface
  23. */
  24. private $shipmentRepository;
  25. /**
  26. * @var ShipmentTrackInterfaceFactory
  27. */
  28. private $trackUpdateFactory;
  29. /**
  30. * AddShipmentTrack constructor.
  31. * @param ShipmentRepositoryInterface $shipmentRepository
  32. * @param ShipmentTrackInterfaceFactory $trackUpdateFactory
  33. */
  34. public function __construct(
  35. ShipmentRepositoryInterface $shipmentRepository,
  36. ShipmentTrackInterfaceFactory $trackUpdateFactory
  37. ) {
  38. $this->shipmentRepository = $shipmentRepository;
  39. $this->trackUpdateFactory = $trackUpdateFactory;
  40. }
  41. /**
  42. * Add tracking reference to local shipment.
  43. *
  44. * @param ShipmentInterface $shipment
  45. * @param int $salesShipmentId
  46. * @throws LocalizedException
  47. */
  48. public function execute(ShipmentInterface $shipment, int $salesShipmentId): void
  49. {
  50. $fulfillment = $shipment->getFulfillment();
  51. if (!$fulfillment || !$fulfillment->getTrackingReference()) {
  52. // no fulfillment with tracking number available, nothing to add.
  53. return;
  54. }
  55. /** @var \Magento\Sales\Model\Order\Shipment $salesShipment */
  56. $salesShipment = $this->shipmentRepository->get($salesShipmentId);
  57. $tracks = $salesShipment->getTracksCollection();
  58. foreach ($tracks as $track) {
  59. if ($track->getTrackNumber() === $fulfillment->getTrackingReference()) {
  60. // tracking number already exists, nothing to do.
  61. return;
  62. }
  63. }
  64. /** @var \Magento\Sales\Model\Order\Shipment\Track $tracking */
  65. $tracking = $this->trackUpdateFactory->create();
  66. $tracking->setCarrierCode(Carrier::CODE);
  67. $tracking->setTitle($fulfillment->getServiceName());
  68. $tracking->setTrackNumber($fulfillment->getTrackingReference());
  69. $salesShipment->addTrack($tracking);
  70. $this->shipmentRepository->save($salesShipment);
  71. }
  72. }