171 lines
7.3 KiB
PHP
171 lines
7.3 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace Esun\LingxingErp\Model\Shipment;
|
|
|
|
use Esun\LingxingErp\Model\Config;
|
|
use Esun\LingxingErp\Model\Sku\ProductErpSkuRepository;
|
|
use Esun\LingxingErp\Model\Sync\OrderSyncRepository;
|
|
use Esun\LingxingErp\Model\Warehouse\WarehouseRepository;
|
|
use Magento\Sales\Api\Data\ShipmentCreationArgumentsExtensionInterfaceFactory;
|
|
use Magento\Sales\Api\Data\ShipmentCreationArgumentsInterfaceFactory;
|
|
use Magento\Sales\Api\Data\ShipmentItemCreationInterfaceFactory;
|
|
use Magento\Sales\Api\Data\ShipmentTrackCreationInterfaceFactory;
|
|
use Magento\Sales\Api\OrderRepositoryInterface;
|
|
use Magento\Sales\Api\ShipOrderInterface;
|
|
use Magento\Store\Model\StoreManagerInterface;
|
|
|
|
class ShipmentImporter
|
|
{
|
|
public function __construct(
|
|
private readonly OrderSyncRepository $orderSyncRepository,
|
|
private readonly OrderRepositoryInterface $orderRepository,
|
|
private readonly ShipmentItemCreationInterfaceFactory $itemFactory,
|
|
private readonly ShipmentTrackCreationInterfaceFactory $trackFactory,
|
|
private readonly ShipOrderInterface $shipOrder,
|
|
private readonly Config $config,
|
|
private readonly ProductErpSkuRepository $productErpSkuRepository,
|
|
private readonly StoreManagerInterface $storeManager,
|
|
private readonly WarehouseRepository $warehouseRepository,
|
|
private readonly ShipmentCreationArgumentsInterfaceFactory $shipmentArgumentsFactory,
|
|
private readonly ShipmentCreationArgumentsExtensionInterfaceFactory $shipmentArgumentsExtensionFactory
|
|
) {
|
|
}
|
|
|
|
public function import(array $payload): array
|
|
{
|
|
$mapping = null;
|
|
if ((string)($payload['global_order_no'] ?? '') !== '') {
|
|
$mapping = $this->orderSyncRepository->findByGlobalOrderNo((string)$payload['global_order_no']);
|
|
}
|
|
if ($mapping === null) {
|
|
foreach (($payload['platform_order_nos'] ?? []) as $incrementId) {
|
|
$mapping = $this->orderSyncRepository->findByIncrementId((string)$incrementId);
|
|
if ($mapping !== null) {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
if ($mapping === null || (string)$mapping['status'] !== 'success') {
|
|
throw new \RuntimeException('No successfully synchronized Magento order matches the Lingxing outbound order.');
|
|
}
|
|
|
|
$order = $this->orderRepository->get((int)$mapping['order_id']);
|
|
if (!$order->canShip()) {
|
|
throw new \RuntimeException('Magento order cannot be shipped or is already fully shipped.');
|
|
}
|
|
|
|
$websiteId = (int)$this->storeManager->getStore((int)$order->getStoreId())->getWebsiteId();
|
|
$quantities = $this->allocateQuantities($order->getAllItems(), $payload['products'] ?? [], $websiteId);
|
|
if ($quantities === []) {
|
|
throw new \RuntimeException('Lingxing outbound data contains no Magento order item quantity to ship.');
|
|
}
|
|
$items = [];
|
|
foreach ($quantities as $orderItemId => $quantity) {
|
|
$item = $this->itemFactory->create();
|
|
$item->setOrderItemId((int)$orderItemId);
|
|
$item->setQty($quantity);
|
|
$items[] = $item;
|
|
}
|
|
$tracks = [];
|
|
foreach (($payload['tracks'] ?? []) as $trackData) {
|
|
$track = $this->trackFactory->create();
|
|
$track->setCarrierCode('custom');
|
|
$track->setTitle((string)($trackData['title'] ?? $payload['carrier'] ?? 'Lingxing'));
|
|
$track->setTrackNumber((string)$trackData['number']);
|
|
$tracks[] = $track;
|
|
}
|
|
|
|
$wid = (int)($payload['wid'] ?? 0);
|
|
$sourceCode = $this->warehouseRepository->findSourceCodeByWid($wid);
|
|
if ($sourceCode === null) {
|
|
throw new \RuntimeException(sprintf(
|
|
'Lingxing warehouse WID %d is not mapped to a Magento Inventory Source.',
|
|
$wid
|
|
));
|
|
}
|
|
$argumentsExtension = $this->shipmentArgumentsExtensionFactory->create();
|
|
$argumentsExtension->setSourceCode($sourceCode);
|
|
$arguments = $this->shipmentArgumentsFactory->create();
|
|
$arguments->setExtensionAttributes($argumentsExtension);
|
|
|
|
$shipmentId = (int)$this->shipOrder->execute(
|
|
(int)$order->getEntityId(),
|
|
$items,
|
|
$this->config->shouldNotifyCustomer(),
|
|
false,
|
|
null,
|
|
$tracks,
|
|
[],
|
|
$arguments
|
|
);
|
|
return ['order_id' => (int)$order->getEntityId(), 'increment_id' => (string)$order->getIncrementId(), 'shipment_id' => $shipmentId];
|
|
}
|
|
|
|
private function allocateQuantities(array $orderItems, array $products, int $websiteId): array
|
|
{
|
|
$shippableItems = [];
|
|
foreach ($orderItems as $item) {
|
|
if ($item->getIsVirtual() || (float)$item->getQtyToShip() <= 0) {
|
|
continue;
|
|
}
|
|
$shippableItems[] = $item;
|
|
}
|
|
usort(
|
|
$shippableItems,
|
|
static fn($left, $right): int => (int)$left->getItemId() <=> (int)$right->getItemId()
|
|
);
|
|
$result = [];
|
|
foreach ($products as $product) {
|
|
// New tasks carry erp_sku; sku remains supported for tasks queued before this upgrade.
|
|
$erpSku = trim((string)($product['erp_sku'] ?? $product['sku'] ?? ''));
|
|
$candidateSkus = $this->productErpSkuRepository->findMskusByErpSku($websiteId, $erpSku);
|
|
if ($candidateSkus === [] && $this->containsSku($shippableItems, $erpSku)) {
|
|
// Backward-compatible self-mapping when Lingxing and Magento use the same SKU.
|
|
$candidateSkus = [$erpSku];
|
|
}
|
|
$remaining = (float)($product['quantity'] ?? 0);
|
|
$candidateLookup = array_fill_keys($candidateSkus, true);
|
|
$matchedItems = [];
|
|
foreach ($shippableItems as $item) {
|
|
if (isset($candidateLookup[(string)$item->getSku()])) {
|
|
$matchedItems[] = $item;
|
|
}
|
|
}
|
|
if ($remaining <= 0 || $matchedItems === []) {
|
|
throw new \RuntimeException(sprintf(
|
|
'Lingxing ERP SKU "%s" cannot be matched to a shippable Magento order item in Website ID %d.',
|
|
$erpSku,
|
|
$websiteId
|
|
));
|
|
}
|
|
foreach ($matchedItems as $item) {
|
|
$alreadyAllocated = (float)($result[(int)$item->getItemId()] ?? 0);
|
|
$available = max(0.0, (float)$item->getQtyToShip() - $alreadyAllocated);
|
|
$allocated = min($remaining, $available);
|
|
if ($allocated > 0) {
|
|
$result[(int)$item->getItemId()] = $alreadyAllocated + $allocated;
|
|
$remaining -= $allocated;
|
|
}
|
|
if ($remaining <= 0.00001) {
|
|
break;
|
|
}
|
|
}
|
|
if ($remaining > 0.00001) {
|
|
throw new \RuntimeException(sprintf('Lingxing quantity for ERP SKU "%s" exceeds Magento quantity available to ship.', $erpSku));
|
|
}
|
|
}
|
|
return $result;
|
|
}
|
|
|
|
private function containsSku(array $items, string $sku): bool
|
|
{
|
|
foreach ($items as $item) {
|
|
if ((string)$item->getSku() === $sku) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
}
|