This commit is contained in:
2026-09-15 10:35:56 +08:00
commit 782f8ea7aa
4086 changed files with 631288 additions and 0 deletions
@@ -0,0 +1,115 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Model\Shipment;
class FulfillmentNormalizer
{
/**
* A Lingxing order can have multiple wo_number records. If package-level item quantities
* are present, each package becomes a Magento shipment; otherwise one outbound record
* becomes one shipment with all tracking numbers attached.
*/
public function normalize(array $outbound): array
{
$woNumber = (string)($outbound['wo_number'] ?? $outbound['woNumber'] ?? '');
if ($woNumber === '') {
throw new \RuntimeException('Lingxing outbound data is missing wo_number.');
}
$packages = $outbound['package_delivered_data'] ?? $outbound['packageDeliveredData'] ?? [];
if (is_array($packages) && count($packages) > 1 && $this->allPackagesHaveProducts($packages)) {
$result = [];
foreach (array_values($packages) as $index => $package) {
$packageNo = (string)($package['package_no'] ?? $package['packageNo'] ?? '');
$tracks = $this->extractTracks($package, $outbound);
$packageIdentity = $packageNo ?: (($tracks[0]['number'] ?? '') ?: (string)($index + 1));
$result[] = $this->makePayload(
$outbound,
$woNumber . '|' . $packageIdentity,
$packageNo,
$package['product_info'] ?? $package['productInfo'],
$tracks
);
}
return $result;
}
$tracks = $this->extractTracks($outbound);
foreach (is_array($packages) ? $packages : [] as $package) {
foreach ($this->extractTracks($package) as $track) {
$tracks[] = $track;
}
}
$tracks = $this->uniqueTracks($tracks);
return [$this->makePayload(
$outbound,
$woNumber,
(string)($outbound['package_no'] ?? $outbound['packageNo'] ?? ''),
$outbound['product_info'] ?? $outbound['productInfo'] ?? [],
$tracks
)];
}
private function allPackagesHaveProducts(array $packages): bool
{
foreach ($packages as $package) {
$products = $package['product_info'] ?? $package['productInfo'] ?? null;
if (!is_array($products) || $products === []) {
return false;
}
}
return true;
}
private function makePayload(array $outbound, string $externalKey, string $packageNo, array $products, array $tracks): array
{
$normalizedProducts = [];
foreach ($products as $product) {
$sku = trim((string)($product['sku'] ?? ''));
$quantity = (float)($product['count'] ?? $product['quantity'] ?? 0);
if ($sku === '' || $quantity <= 0 || (int)($product['bundle_type'] ?? 0) === 2) {
continue;
}
$normalizedProducts[] = ['erp_sku' => $sku, 'quantity' => $quantity];
}
return [
'external_key' => mb_substr($externalKey, 0, 191),
'global_order_no' => (string)($outbound['order_number'] ?? $outbound['orderNumber'] ?? ''),
'platform_order_nos' => array_values(array_filter((array)($outbound['platform_order_no'] ?? [$outbound['amazonOrderId'] ?? '']))),
'wo_id' => (int)($outbound['wo_id'] ?? $outbound['woId'] ?? 0),
'wid' => (int)($outbound['wid'] ?? $outbound['warehouse_id'] ?? $outbound['warehouseId'] ?? 0),
'wo_number' => (string)($outbound['wo_number'] ?? $outbound['woNumber'] ?? ''),
'package_no' => $packageNo,
'carrier' => (string)($outbound['logistics_provider_name'] ?? $outbound['actualCarrier'] ?? ''),
'products' => $normalizedProducts,
'tracks' => $this->uniqueTracks($tracks),
];
}
private function extractTracks(array $primary, array $fallback = []): array
{
$tracks = [];
foreach ([
$primary['tracking_no'] ?? $primary['trackingNo'] ?? '',
$primary['waybill_no'] ?? $primary['waybillNo'] ?? '',
] as $number) {
$number = trim((string)$number);
if ($number !== '') {
$tracks[] = ['number' => $number, 'title' => (string)($primary['logistics_provider_name'] ?? $primary['actualCarrier'] ?? $fallback['logistics_provider_name'] ?? 'Lingxing')];
}
}
return $tracks;
}
private function uniqueTracks(array $tracks): array
{
$result = [];
foreach ($tracks as $track) {
$number = trim((string)($track['number'] ?? ''));
if ($number !== '') {
$result[$number] = ['number' => $number, 'title' => (string)($track['title'] ?? 'Lingxing')];
}
}
return array_values($result);
}
}
@@ -0,0 +1,170 @@
<?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;
}
}
@@ -0,0 +1,142 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Model\Shipment;
use Esun\LingxingErp\Model\Api\Client;
use Esun\LingxingErp\Model\Api\Endpoint;
use Esun\LingxingErp\Model\Config;
use Esun\LingxingErp\Model\Sync\LogWriter;
use Esun\LingxingErp\Model\Sync\OrderSyncRepository;
use Esun\LingxingErp\Model\Sync\ShipmentSyncRepository;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
use Magento\Framework\FlagManager;
class ShipmentPuller
{
/**
* Lingxing API documentation:
* https://apidoc.lingxing.com/#/docs/Warehouse/WmsOrderList
*/
private const ORDER_FILTER_BATCH_SIZE = 100;
public function __construct(
private readonly Client $client,
private readonly Config $config,
private readonly TimezoneInterface $timezone,
private readonly FlagManager $flagManager,
private readonly FulfillmentNormalizer $normalizer,
private readonly OrderSyncRepository $orderSyncRepository,
private readonly ShipmentSyncRepository $repository,
private readonly LogWriter $logWriter
) {
}
public function pull(): void
{
$now = $this->timezone->date();
$lastSuccess = (string)$this->flagManager->getFlagData('esun_lingxing_shipment_last_success_date');
$earliest = (clone $now)->modify('-30 days')->format('Y-m-d');
$start = $lastSuccess !== '' && $lastSuccess >= $earliest
? $lastSuccess
: (clone $now)->modify('-1 day')->format('Y-m-d');
$end = $now->format('Y-m-d');
$pageSize = $this->config->getShipmentPageSize();
$platformOrderNos = $this->orderSyncRepository->getTrackablePlatformOrderNos();
if ($platformOrderNos === []) {
return;
}
$completedRange = true;
foreach (array_chunk($platformOrderNos, self::ORDER_FILTER_BATCH_SIZE) as $orderNumberBatch) {
if (!$this->pullOrderNumberBatch($orderNumberBatch, $pageSize, $start, $end)) {
$completedRange = false;
break;
}
}
if ($completedRange) {
$this->flagManager->saveFlag('esun_lingxing_shipment_last_success_date', $end);
}
}
/** @param string[] $platformOrderNos */
private function pullOrderNumberBatch(
array $platformOrderNos,
int $pageSize,
string $start,
string $end
): bool {
for ($page = 1; $page <= $this->config->getShipmentMaxPages(); $page++) {
$request = [
'page' => $page,
'page_size' => $pageSize,
'platform_order_no_arr' => $platformOrderNos,
'status_arr' => [3],
'time_type' => 'update_at',
'start_date' => $start,
'end_date' => $end,
];
$started = microtime(true);
$response = $this->client->post(Endpoint::WMS_ORDER_LIST, $request);
$rows = is_array($response['data'] ?? null) ? $response['data'] : [];
$this->enqueueOutbounds($rows, $response);
$this->logWriter->write([
'direction' => 'pull', 'operation' => 'shipment_pull', 'entity_type' => 'shipment',
'status' => 'success', 'attempt_number' => 1,
'request_id' => (string)($response['request_id'] ?? ''),
'request_payload' => $request,
'response_payload' => $response,
'duration_ms' => (int)round((microtime(true) - $started) * 1000),
]);
if (count($rows) < $pageSize) {
return true;
}
}
return false;
}
/** @param array<int, array<string, mixed>> $outbounds */
private function enqueueOutbounds(array $outbounds, array $response): void
{
foreach ($outbounds as $outbound) {
if (!$this->belongsToSynchronizedMagentoOrder($outbound)) {
continue;
}
try {
foreach ($this->normalizer->normalize($outbound) as $payload) {
$this->repository->enqueue($payload, (string)($response['request_id'] ?? ''));
}
} catch (\Throwable $exception) {
$this->logWriter->write([
'direction' => 'pull',
'operation' => 'shipment_normalize',
'entity_type' => 'shipment',
'external_id' => (string)($outbound['wo_number'] ?? ''),
'status' => 'failed',
'attempt_number' => 1,
'error_code' => (string)$exception->getCode(),
'error_message' => $exception->getMessage(),
'request_id' => (string)($response['request_id'] ?? ''),
'response_payload' => $outbound,
]);
}
}
}
private function belongsToSynchronizedMagentoOrder(array $outbound): bool
{
$globalOrderNo = (string)($outbound['order_number'] ?? $outbound['orderNumber'] ?? '');
if ($globalOrderNo !== '' && $this->orderSyncRepository->findByGlobalOrderNo($globalOrderNo) !== null) {
return true;
}
$platformOrderNos = (array)($outbound['platform_order_no'] ?? [$outbound['amazonOrderId'] ?? '']);
foreach ($platformOrderNos as $incrementId) {
if ((string)$incrementId !== ''
&& $this->orderSyncRepository->findByIncrementId((string)$incrementId) !== null
) {
return true;
}
}
return false;
}
}