I’ve created a module to notify the customer when a custom carrier has been added. I’ve used an observer on the sales_order_shipment_save_after
event but the tracking info and items ordered are empty in the shipment email. I’m guessing I need to load the tracking info and order items into the $shipment
object?
Example/SendShipmentTracking/Observer/SendShipmentTrackingProcessor.php
<?php
namespace ExampleSendShipmentTrackingObserver;
use ExampleSendShipmentTrackingHelperData;
use MagentoFrameworkEventObserver;
use MagentoFrameworkEventObserverInterface;
use MagentoFrameworkSerializeSerializerJson;
use MagentoSalesModelOrderShipmentNotifier;
use PsrLogLoggerInterface;
class SendShipmentTrackingProcessor implements ObserverInterface
{
/**
* @var LoggerInterface
*/
protected LoggerInterface $logger;
/**
* @var Json
*/
protected Json $jsonHelper;
/**
* @var Data
*/
protected Data $helperData;
/**
* @var Notifier
*/
protected Notifier $shipmentNotifier;
/**
* @param LoggerInterface $logger
* @param Json $jsonHelper
* @param Data $helperData
* @param Notifier $shipmentNotifier
*/
public function __construct(
LoggerInterface $logger,
Json $jsonHelper,
Data $helperData,
Notifier $shipmentNotifier
) {
$this->logger = $logger;
$this->jsonHelper = $jsonHelper;
$this->helperData = $helperData;
$this->shipmentNotifier = $shipmentNotifier;
}
/**
* @param Observer $observer
* @return void
*/
public function execute(Observer $observer)
{
if ($this->helperData->isEnabled()) {
try {
$shipment = $observer->getEvent()->getShipment();
if ($shipment && $this->hasShipmentTracking($shipment)) {
$order = $shipment->getOrder();
$this->logger->debug('shipment data ' . $this->jsonHelper->serialize($shipment->getData()));
$this->shipmentNotifier->notify($order, $shipment);
}
} catch (Exception $e) {
$this->logger->error($e->getMessage());
}
}
}
/**
* @param $shipment
* @return bool
*/
private function hasShipmentTracking($shipment): bool
{
$tracksCollection = $shipment->getTracksCollection();
$trackingNumber = [];
foreach ($tracksCollection->getItems() as $track) {
if ($track->isCustom()) {
$trackTile = $track->getTitle();
$carrierServices = $this->helperData->getCarriers();
if (in_array($trackTile, $carrierServices) && $track->getTrackNumber()) {
$trackingNumber[] = $track->getTrackNumber();
}
}
}
return count($trackingNumber) > 0;
}
}