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,26 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Block\Adminhtml\Store;
use Magento\Backend\Block\Widget\Button;
class ErpSkuSyncButton extends Button
{
protected function _construct(): void
{
parent::_construct();
$url = $this->getUrl('esun_lingxing/sku/sync');
$message = (string)__('Fetch ERP SKUs for products in all configured Websites now?');
$this->setData([
'label' => __('Sync Product ERP SKUs'),
'class' => 'secondary',
'style' => 'margin-left: 12px;',
'onclick' => sprintf(
'confirmSetLocation(%s, %s)',
json_encode($message, JSON_HEX_APOS | JSON_HEX_QUOT),
json_encode($url, JSON_HEX_APOS | JSON_HEX_QUOT)
),
]);
}
}
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Block\Adminhtml\Store;
use Magento\Backend\Block\Widget\Button;
class SyncButton extends Button
{
protected function _construct(): void
{
parent::_construct();
$url = $this->getUrl('esun_lingxing/store/sync');
$message = (string)__('Fetch all stores from Lingxing now?');
$this->setData([
'label' => __('Sync Stores'),
'class' => 'primary',
'onclick' => sprintf(
'confirmSetLocation(%s, %s)',
json_encode($message, JSON_HEX_APOS | JSON_HEX_QUOT),
json_encode($url, JSON_HEX_APOS | JSON_HEX_QUOT)
),
]);
}
}
@@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Block\Adminhtml\Sync;
use Esun\LingxingErp\Model\Sync\DetailProvider;
use Magento\Backend\Block\Template;
use Magento\Backend\Block\Template\Context;
class Details extends Template
{
private ?array $record = null;
public function __construct(
Context $context,
private readonly DetailProvider $detailProvider,
array $data = []
) {
parent::__construct($context, $data);
}
public function getSyncType(): string
{
return (string)$this->getData('sync_type');
}
/** @return array<string, mixed> */
public function getRecord(): array
{
if ($this->record === null) {
$this->record = $this->detailProvider->getRecord(
$this->getSyncType(),
(int)$this->getRequest()->getParam('id')
) ?? [];
}
return $this->record;
}
/** @return array<int, array<string, mixed>> */
public function getLogs(): array
{
$record = $this->getRecord();
return $record === [] ? [] : $this->detailProvider->getLogs($this->getSyncType(), $record);
}
public function getBackUrl(): string
{
return $this->getUrl('esun_lingxing/' . $this->getSyncType() . '/index');
}
public function prettyPayload(mixed $payload): string
{
if ($payload === null || $payload === '') {
return (string)__('No data recorded.');
}
if (is_string($payload)) {
try {
$decoded = json_decode($payload, true, 512, JSON_THROW_ON_ERROR);
return (string)json_encode(
$decoded,
JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR
);
} catch (\JsonException) {
return $payload;
}
}
try {
return (string)json_encode(
$payload,
JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR
);
} catch (\JsonException) {
return (string)__('Unable to display data.');
}
}
}
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Block\Adminhtml\Warehouse;
use Magento\Backend\Block\Widget\Button;
class InventorySyncButton extends Button
{
protected function _construct(): void
{
parent::_construct();
$this->setData([
'label' => __('Sync Inventory'),
'class' => 'secondary',
'style' => 'margin-left: 12px;',
'onclick' => sprintf(
'confirmSetLocation(%s, %s)',
json_encode((string)__('Synchronize product_valid_num for Sources assigned to Website Stocks now?'), JSON_HEX_APOS | JSON_HEX_QUOT),
json_encode($this->getUrl('esun_lingxing/warehouse/syncInventory'), JSON_HEX_APOS | JSON_HEX_QUOT)
),
]);
}
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Block\Adminhtml\Warehouse;
use Magento\Backend\Block\Widget\Button;
class ManageSourcesButton extends Button
{
protected function _construct(): void
{
parent::_construct();
$this->setData([
'label' => __('Map Source Warehouses'),
'class' => 'secondary',
'style' => 'margin-left: 12px;',
'onclick' => sprintf('setLocation(%s)', json_encode(
$this->getUrl('inventory/source/index'),
JSON_HEX_APOS | JSON_HEX_QUOT
)),
]);
}
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Block\Adminhtml\Warehouse;
use Magento\Backend\Block\Widget\Button;
class ManageStocksButton extends Button
{
protected function _construct(): void
{
parent::_construct();
$this->setData([
'label' => __('Manage Stock Assignments'),
'class' => 'secondary',
'style' => 'margin-left: 12px;',
'onclick' => sprintf('setLocation(%s)', json_encode(
$this->getUrl('inventory/stock/index'),
JSON_HEX_APOS | JSON_HEX_QUOT
)),
]);
}
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Block\Adminhtml\Warehouse;
use Magento\Backend\Block\Widget\Button;
class SyncButton extends Button
{
protected function _construct(): void
{
parent::_construct();
$this->setData([
'label' => __('Sync Warehouses'),
'class' => 'primary',
'onclick' => sprintf(
'confirmSetLocation(%s, %s)',
json_encode((string)__('Fetch and cache Lingxing type 3 warehouses now? Magento Sources will not be changed.'), JSON_HEX_APOS | JSON_HEX_QUOT),
json_encode($this->getUrl('esun_lingxing/warehouse/sync'), JSON_HEX_APOS | JSON_HEX_QUOT)
),
]);
}
}
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Controller\Adminhtml\Log;
use Magento\Backend\App\Action;
use Magento\Framework\View\Result\PageFactory;
class Index extends Action
{
public const ADMIN_RESOURCE = 'Esun_LingxingErp::logs';
public function __construct(Action\Context $context, private readonly PageFactory $pageFactory)
{
parent::__construct($context);
}
public function execute()
{
$page = $this->pageFactory->create();
$page->setActiveMenu('Esun_LingxingErp::logs');
$page->getConfig()->getTitle()->prepend(__('Lingxing Synchronization Logs'));
return $page;
}
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Controller\Adminhtml\Log;
use Esun\LingxingErp\Model\Sync\DetailProvider;
use Magento\Backend\App\Action;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Framework\View\Result\Page;
use Magento\Framework\View\Result\PageFactory;
class View extends Action
{
public const ADMIN_RESOURCE = 'Esun_LingxingErp::logs';
public function __construct(
Action\Context $context,
private readonly PageFactory $pageFactory,
private readonly DetailProvider $detailProvider
) {
parent::__construct($context);
}
public function execute(): Page|Redirect
{
$record = $this->detailProvider->getRecord('log', (int)$this->getRequest()->getParam('id'));
if ($record === null) {
$this->messageManager->addErrorMessage(__('The synchronization log no longer exists.'));
return $this->resultRedirectFactory->create()->setPath('*/*/index');
}
$page = $this->pageFactory->create();
$page->setActiveMenu('Esun_LingxingErp::logs');
$page->getConfig()->getTitle()->prepend(__('Synchronization Log #%1', $record['entity_id']));
return $page;
}
}
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Controller\Adminhtml\Order;
use Magento\Backend\App\Action;
use Magento\Framework\View\Result\PageFactory;
class Index extends Action
{
public const ADMIN_RESOURCE = 'Esun_LingxingErp::orders';
public function __construct(Action\Context $context, private readonly PageFactory $pageFactory)
{
parent::__construct($context);
}
public function execute()
{
$page = $this->pageFactory->create();
$page->setActiveMenu('Esun_LingxingErp::orders');
$page->getConfig()->getTitle()->prepend(__('Lingxing Order Synchronization'));
return $page;
}
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Controller\Adminhtml\Order;
use Esun\LingxingErp\Model\Sync\DetailProvider;
use Magento\Backend\App\Action;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Framework\View\Result\Page;
use Magento\Framework\View\Result\PageFactory;
class View extends Action
{
public const ADMIN_RESOURCE = 'Esun_LingxingErp::orders';
public function __construct(
Action\Context $context,
private readonly PageFactory $pageFactory,
private readonly DetailProvider $detailProvider
) {
parent::__construct($context);
}
public function execute(): Page|Redirect
{
$record = $this->detailProvider->getRecord('order', (int)$this->getRequest()->getParam('id'));
if ($record === null) {
$this->messageManager->addErrorMessage(__('The order synchronization record no longer exists.'));
return $this->resultRedirectFactory->create()->setPath('*/*/index');
}
$page = $this->pageFactory->create();
$page->setActiveMenu('Esun_LingxingErp::orders');
$page->getConfig()->getTitle()->prepend(__('Order Synchronization #%1', $record['increment_id']));
return $page;
}
}
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Controller\Adminhtml\Shipment;
use Magento\Backend\App\Action;
use Magento\Framework\View\Result\PageFactory;
class Index extends Action
{
public const ADMIN_RESOURCE = 'Esun_LingxingErp::shipments';
public function __construct(Action\Context $context, private readonly PageFactory $pageFactory)
{
parent::__construct($context);
}
public function execute()
{
$page = $this->pageFactory->create();
$page->setActiveMenu('Esun_LingxingErp::shipments');
$page->getConfig()->getTitle()->prepend(__('Lingxing Shipment Synchronization'));
return $page;
}
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Controller\Adminhtml\Shipment;
use Esun\LingxingErp\Model\Sync\DetailProvider;
use Magento\Backend\App\Action;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Framework\View\Result\Page;
use Magento\Framework\View\Result\PageFactory;
class View extends Action
{
public const ADMIN_RESOURCE = 'Esun_LingxingErp::shipments';
public function __construct(
Action\Context $context,
private readonly PageFactory $pageFactory,
private readonly DetailProvider $detailProvider
) {
parent::__construct($context);
}
public function execute(): Page|Redirect
{
$record = $this->detailProvider->getRecord('shipment', (int)$this->getRequest()->getParam('id'));
if ($record === null) {
$this->messageManager->addErrorMessage(__('The shipment synchronization record no longer exists.'));
return $this->resultRedirectFactory->create()->setPath('*/*/index');
}
$page = $this->pageFactory->create();
$page->setActiveMenu('Esun_LingxingErp::shipments');
$page->getConfig()->getTitle()->prepend(__('Shipment Synchronization #%1', $record['wo_number']));
return $page;
}
}
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Controller\Adminhtml\Sku;
use Esun\LingxingErp\Model\Sku\SkuSynchronizer;
use Magento\Backend\App\Action;
use Magento\Framework\App\Action\HttpGetActionInterface;
class Sync extends Action implements HttpGetActionInterface
{
public const ADMIN_RESOURCE = 'Esun_LingxingErp::sync_sku_mappings';
public function __construct(Action\Context $context, private readonly SkuSynchronizer $synchronizer)
{
parent::__construct($context);
}
public function execute()
{
try {
$summary = $this->synchronizer->synchronizeAll();
if ($summary['errors'] !== []) {
$this->messageManager->addErrorMessage(__(
'ERP SKU synchronization completed with %1 Website error(s). Review Synchronization Logs.',
count($summary['errors'])
));
}
$this->messageManager->addSuccessMessage(__(
'Processed %1 Website(s) and %2 pair(s): %3 mapped, %4 products remain without an ERP SKU.',
$summary['websites'],
$summary['pairs'],
$summary['mapped'],
$summary['unmapped']
));
} catch (\Throwable $exception) {
$this->messageManager->addErrorMessage(__('ERP SKU synchronization failed: %1', $exception->getMessage()));
}
return $this->resultRedirectFactory->create()->setPath('esun_lingxing/store/index');
}
}
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Controller\Adminhtml\Store;
use Magento\Backend\App\Action;
use Magento\Framework\View\Result\PageFactory;
class Index extends Action
{
public const ADMIN_RESOURCE = 'Esun_LingxingErp::stores';
public function __construct(Action\Context $context, private readonly PageFactory $pageFactory)
{
parent::__construct($context);
}
public function execute()
{
$page = $this->pageFactory->create();
$page->setActiveMenu('Esun_LingxingErp::store_list');
$page->getConfig()->getTitle()->prepend(__('Lingxing Stores'));
return $page;
}
}
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Controller\Adminhtml\Store;
use Esun\LingxingErp\Model\Store\StoreSynchronizer;
use Magento\Backend\App\Action;
use Magento\Framework\App\Action\HttpGetActionInterface;
class Sync extends Action implements HttpGetActionInterface
{
public const ADMIN_RESOURCE = 'Esun_LingxingErp::sync_stores';
public function __construct(Action\Context $context, private readonly StoreSynchronizer $synchronizer)
{
parent::__construct($context);
}
public function execute()
{
try {
$count = $this->synchronizer->synchronize();
$this->messageManager->addSuccessMessage(__('Synchronized %1 Lingxing stores.', $count));
} catch (\Throwable $exception) {
$this->messageManager->addErrorMessage(__('Store synchronization failed: %1', $exception->getMessage()));
}
return $this->resultRedirectFactory->create()->setPath('*/*/index');
}
}
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Controller\Adminhtml\Sync;
use Esun\LingxingErp\Model\Sync\OrderSyncRepository;
use Esun\LingxingErp\Model\Sync\ShipmentSyncRepository;
use Magento\Backend\App\Action;
use Magento\Framework\Controller\Result\Redirect;
class Retry extends Action
{
public const ADMIN_RESOURCE = 'Esun_LingxingErp::retry';
public function __construct(
Action\Context $context,
private readonly OrderSyncRepository $orderRepository,
private readonly ShipmentSyncRepository $shipmentRepository
) {
parent::__construct($context);
}
public function execute(): Redirect
{
$id = (int)$this->getRequest()->getParam('id');
$type = (string)$this->getRequest()->getParam('type');
$retried = $type === 'order'
? $this->orderRepository->retry($id)
: ($type === 'shipment' && $this->shipmentRepository->retry($id));
if ($retried) {
$this->messageManager->addSuccessMessage(__('The synchronization was queued for retry.'));
} else {
$this->messageManager->addErrorMessage(__('This record cannot be retried in its current state.'));
}
return $this->resultRedirectFactory->create()->setRefererUrl();
}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Controller\Adminhtml\Warehouse;
use Magento\Backend\App\Action;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\View\Result\PageFactory;
class Index extends Action implements HttpGetActionInterface
{
public const ADMIN_RESOURCE = 'Esun_LingxingErp::warehouses';
public function __construct(Action\Context $context, private readonly PageFactory $pageFactory)
{
parent::__construct($context);
}
public function execute()
{
$page = $this->pageFactory->create();
$page->setActiveMenu('Esun_LingxingErp::warehouses');
$page->getConfig()->getTitle()->prepend(__('Lingxing Warehouses and Inventory'));
return $page;
}
}
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Controller\Adminhtml\Warehouse;
use Esun\LingxingErp\Model\Warehouse\WarehouseSynchronizer;
use Magento\Backend\App\Action;
use Magento\Framework\App\Action\HttpGetActionInterface;
class Sync extends Action implements HttpGetActionInterface
{
public const ADMIN_RESOURCE = 'Esun_LingxingErp::sync_warehouses';
public function __construct(Action\Context $context, private readonly WarehouseSynchronizer $synchronizer)
{
parent::__construct($context);
}
public function execute()
{
try {
$result = $this->synchronizer->synchronize();
$this->messageManager->addSuccessMessage(__(
'Synchronized %1 Lingxing type 3 warehouses. Magento Inventory Sources were not created or changed.',
$result['warehouses']
));
} catch (\Throwable $exception) {
$this->messageManager->addErrorMessage(__('Warehouse synchronization failed: %1', $exception->getMessage()));
}
return $this->resultRedirectFactory->create()->setPath('*/*/index');
}
}
@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Controller\Adminhtml\Warehouse;
use Esun\LingxingErp\Model\Inventory\InventorySynchronizer;
use Magento\Backend\App\Action;
use Magento\Framework\App\Action\HttpGetActionInterface;
class SyncInventory extends Action implements HttpGetActionInterface
{
public const ADMIN_RESOURCE = 'Esun_LingxingErp::sync_inventory';
public function __construct(Action\Context $context, private readonly InventorySynchronizer $synchronizer)
{
parent::__construct($context);
}
public function execute()
{
try {
$result = $this->synchronizer->synchronizeAll();
if ($result['errors'] !== []) {
$this->messageManager->addWarningMessage(__(
'Inventory synchronized for %1 warehouses and %2 items, with %3 warehouse errors. See Synchronization Logs.',
$result['warehouses'],
$result['items'],
count($result['errors'])
));
} else {
$this->messageManager->addSuccessMessage(__(
'Inventory synchronized for %1 warehouses and %2 items. Unmapped ERP SKUs: %3.',
$result['warehouses'],
$result['items'],
$result['unmapped']
));
}
} catch (\Throwable $exception) {
$this->messageManager->addErrorMessage(__('Inventory synchronization failed: %1', $exception->getMessage()));
}
return $this->resultRedirectFactory->create()->setPath('esun_lingxing/warehouse/index');
}
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Cron;
use Esun\LingxingErp\Model\Config;
use Magento\Framework\App\ResourceConnection;
class CleanSyncLogs
{
private const COMPACT_STATUSES = ['success', 'ignored'];
public function __construct(
private readonly Config $config,
private readonly ResourceConnection $resource
) {
}
public function execute(): int
{
$connection = $this->resource->getConnection();
$table = $this->resource->getTableName('esun_lingxing_sync_log');
$successCutoff = gmdate('Y-m-d H:i:s', time() - ($this->config->getSuccessLogRetentionDays() * 86400));
$errorCutoff = gmdate('Y-m-d H:i:s', time() - ($this->config->getErrorLogRetentionDays() * 86400));
$deleted = $connection->delete($table, [
'status IN (?)' => self::COMPACT_STATUSES,
'created_at < ?' => $successCutoff,
]);
$deleted += $connection->delete($table, [
'status NOT IN (?)' => self::COMPACT_STATUSES,
'created_at < ?' => $errorCutoff,
]);
return $deleted;
}
}
@@ -0,0 +1,95 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Cron;
use Esun\LingxingErp\Model\Api\ApiException;
use Esun\LingxingErp\Model\Config;
use Esun\LingxingErp\Model\Order\OrderExporter;
use Esun\LingxingErp\Model\Order\OrderPayloadBuilder;
use Esun\LingxingErp\Model\Sync\LogWriter;
use Esun\LingxingErp\Model\Sync\OrderSyncRepository;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Order;
use Psr\Log\LoggerInterface;
class ProcessOrders
{
public function __construct(
private readonly Config $config,
private readonly OrderSyncRepository $syncRepository,
private readonly OrderRepositoryInterface $orderRepository,
private readonly OrderPayloadBuilder $payloadBuilder,
private readonly OrderExporter $exporter,
private readonly LogWriter $logWriter,
private readonly LoggerInterface $logger
) {
}
public function execute(): void
{
if (!$this->config->isEnabled()) {
return;
}
foreach ($this->syncRepository->getDue($this->config->getOrderBatchSize()) as $row) {
$entityId = (int)$row['entity_id'];
if (!$this->syncRepository->claim($entityId)) {
continue;
}
$started = microtime(true);
$payload = [];
try {
$order = $this->orderRepository->get((int)$row['order_id']);
if ((string)$order->getState() === Order::STATE_CANCELED) {
$this->syncRepository->markCreationCanceled($entityId);
$this->logWriter->write([
'direction' => 'push', 'operation' => 'order_create', 'entity_type' => 'order',
'local_entity_id' => $entityId, 'increment_id' => (string)$row['increment_id'],
'status' => 'ignored', 'attempt_number' => (int)$row['attempt_count'] + 1,
'request_payload' => ['reason' => 'Magento order was canceled before export.'],
]);
continue;
}
// Capture the sanitized request in the attempt log even when Lingxing rejects the order.
$payload = $this->payloadBuilder->build($order);
$result = $this->exporter->export($order, $payload);
$requestId = (string)($result['response']['request_id'] ?? '');
$hash = hash('sha256', (string)json_encode($result['payload'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
$this->syncRepository->markSuccess($entityId, $result['global_order_no'], $requestId, $hash);
$this->logWriter->write([
'direction' => 'push', 'operation' => 'order_create', 'entity_type' => 'order',
'local_entity_id' => $entityId, 'increment_id' => (string)$row['increment_id'],
'external_id' => $result['global_order_no'], 'status' => 'success',
'attempt_number' => (int)$row['attempt_count'] + 1, 'request_id' => $requestId,
'request_payload' => $result['payload'], 'response_payload' => $result['response'],
'duration_ms' => (int)round((microtime(true) - $started) * 1000),
]);
} catch (\Throwable $exception) {
$code = $exception instanceof ApiException ? $exception->getErrorCode() : (string)$exception->getCode();
$response = $exception instanceof ApiException ? $exception->getResponse() : [];
$requestId = (string)($response['request_id'] ?? '');
$status = $this->syncRepository->markFailure(
$entityId,
(int)$row['attempt_count'],
$this->config->getOrderMaxAttempts(),
$code,
$exception->getMessage(),
$requestId
);
$this->logWriter->write([
'direction' => 'push', 'operation' => 'order_create', 'entity_type' => 'order',
'local_entity_id' => $entityId, 'increment_id' => (string)$row['increment_id'],
'external_id' => (string)($row['global_order_no'] ?? ''), 'status' => $status,
'attempt_number' => (int)$row['attempt_count'] + 1, 'error_code' => $code,
'error_message' => $exception->getMessage(), 'request_id' => $requestId,
'request_payload' => $payload,
'response_payload' => $response,
'duration_ms' => (int)round((microtime(true) - $started) * 1000),
]);
$this->logger->error('Lingxing order synchronization failed.', [
'order_id' => $row['order_id'], 'exception' => $exception,
]);
}
}
}
}
@@ -0,0 +1,71 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Cron;
use Esun\LingxingErp\Model\Config;
use Esun\LingxingErp\Model\Shipment\ShipmentImporter;
use Esun\LingxingErp\Model\Sync\LogWriter;
use Esun\LingxingErp\Model\Sync\ShipmentSyncRepository;
use Psr\Log\LoggerInterface;
class ProcessShipments
{
public function __construct(
private readonly Config $config,
private readonly ShipmentSyncRepository $repository,
private readonly ShipmentImporter $importer,
private readonly LogWriter $logWriter,
private readonly LoggerInterface $logger
) {
}
public function execute(): void
{
if (!$this->config->isEnabled()) {
return;
}
foreach ($this->repository->getDue(50) as $row) {
$entityId = (int)$row['entity_id'];
if (!$this->repository->claim($entityId)) {
continue;
}
$started = microtime(true);
$payload = [];
try {
$payload = json_decode((string)$row['payload_json'], true, 512, JSON_THROW_ON_ERROR);
$result = $this->importer->import($payload);
$this->repository->markSuccess($entityId, $result['order_id'], $result['increment_id'], $result['shipment_id']);
$this->logWriter->write([
'direction' => 'pull', 'operation' => 'shipment_import', 'entity_type' => 'shipment',
'local_entity_id' => $entityId, 'increment_id' => $result['increment_id'],
'external_id' => (string)$row['external_key'], 'status' => 'success',
'attempt_number' => (int)$row['attempt_count'] + 1, 'request_id' => (string)($row['request_id'] ?? ''),
'request_payload' => $payload,
'response_payload' => ['shipment_id' => $result['shipment_id']],
'duration_ms' => (int)round((microtime(true) - $started) * 1000),
]);
} catch (\Throwable $exception) {
$status = $this->repository->markFailure(
$entityId,
(int)$row['attempt_count'],
$this->config->getShipmentMaxAttempts(),
(string)$exception->getCode(),
$exception->getMessage()
);
$this->logWriter->write([
'direction' => 'pull', 'operation' => 'shipment_import', 'entity_type' => 'shipment',
'local_entity_id' => $entityId, 'increment_id' => (string)($row['increment_id'] ?? ''),
'external_id' => (string)$row['external_key'], 'status' => $status,
'attempt_number' => (int)$row['attempt_count'] + 1, 'error_code' => (string)$exception->getCode(),
'error_message' => $exception->getMessage(), 'request_id' => (string)($row['request_id'] ?? ''),
'request_payload' => $payload,
'duration_ms' => (int)round((microtime(true) - $started) * 1000),
]);
$this->logger->error('Unable to import Lingxing shipment.', [
'external_key' => $row['external_key'], 'exception' => $exception,
]);
}
}
}
}
@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Cron;
use Esun\LingxingErp\Model\Api\ApiException;
use Esun\LingxingErp\Model\Config;
use Esun\LingxingErp\Model\Shipment\ShipmentPuller;
use Esun\LingxingErp\Model\Sync\LogWriter;
use Psr\Log\LoggerInterface;
class PullShipments
{
public function __construct(
private readonly Config $config,
private readonly ShipmentPuller $puller,
private readonly LogWriter $logWriter,
private readonly LoggerInterface $logger
) {
}
public function execute(): void
{
if (!$this->config->isEnabled()) {
return;
}
$started = microtime(true);
try {
$this->puller->pull();
} catch (\Throwable $exception) {
$response = $exception instanceof ApiException ? $exception->getResponse() : [];
$this->logWriter->write([
'direction' => 'pull', 'operation' => 'shipment_pull', 'entity_type' => 'shipment',
'status' => 'failed', 'attempt_number' => 1,
'error_code' => $exception instanceof ApiException ? $exception->getErrorCode() : (string)$exception->getCode(),
'error_message' => $exception->getMessage(), 'request_id' => (string)($response['request_id'] ?? ''),
'response_payload' => $response,
'duration_ms' => (int)round((microtime(true) - $started) * 1000),
]);
$this->logger->error('Unable to pull Lingxing shipments.', ['exception' => $exception]);
}
}
}
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Cron;
use Esun\LingxingErp\Model\Config;
use Esun\LingxingErp\Model\Inventory\InventorySynchronizer;
use Psr\Log\LoggerInterface;
class SyncInventory
{
public function __construct(
private readonly Config $config,
private readonly InventorySynchronizer $synchronizer,
private readonly LoggerInterface $logger
) {
}
public function execute(): void
{
if (!$this->config->isEnabled()) {
return;
}
try {
$summary = $this->synchronizer->synchronizeAll();
if ($summary['errors'] !== []) {
$this->logger->error('Lingxing inventory synchronization completed with warehouse errors.', [
'errors' => $summary['errors'],
]);
}
} catch (\Throwable $exception) {
$this->logger->error('Lingxing inventory synchronization failed.', ['exception' => $exception]);
}
}
}
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Cron;
use Esun\LingxingErp\Model\Config;
use Esun\LingxingErp\Model\Sku\SkuSynchronizer;
use Psr\Log\LoggerInterface;
class SyncSkuMappings
{
public function __construct(
private readonly Config $config,
private readonly SkuSynchronizer $synchronizer,
private readonly LoggerInterface $logger
) {
}
public function execute(): void
{
if (!$this->config->isEnabled() || !$this->config->isSkuSyncEnabled()) {
return;
}
try {
$summary = $this->synchronizer->synchronizeAll();
if ($summary['errors'] !== []) {
$this->logger->error('Lingxing ERP SKU synchronization completed with Website errors.', [
'errors' => $summary['errors'],
]);
}
} catch (\Throwable $exception) {
$this->logger->error('Lingxing ERP SKU synchronization failed.', ['exception' => $exception]);
}
}
}
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Model\Api;
class ApiException extends \RuntimeException
{
public function __construct(
string $message,
private readonly string $errorCode = '',
private readonly array $response = []
) {
parent::__construct($message);
}
public function getErrorCode(): string
{
return $this->errorCode;
}
public function getResponse(): array
{
return $this->response;
}
}
@@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Model\Api;
use Esun\LingxingErp\Model\Config;
use Magento\Framework\HTTP\Client\CurlFactory;
class Client
{
public function __construct(
private readonly Config $config,
private readonly TokenProvider $tokenProvider,
private readonly Signer $signer,
private readonly CurlFactory $curlFactory
) {
}
public function post(string $path, array $businessParameters): array
{
$this->config->assertCredentialsReady();
$token = $this->tokenProvider->getAccessToken();
$timestamp = time();
$public = [
'access_token' => $token,
'timestamp' => $timestamp,
'app_key' => $this->config->getAppId(),
];
$signedParameters = array_merge($businessParameters, $public);
$query = $public + ['sign' => $this->signer->sign($signedParameters, $this->config->getAppId())];
$url = $this->config->getApiBaseUrl() . '/' . ltrim($path, '/') . '?' . http_build_query(
$query,
'',
'&',
PHP_QUERY_RFC3986
);
$curl = $this->curlFactory->create();
$curl->setTimeout(30);
$curl->addHeader('Content-Type', 'application/json');
$curl->addHeader('X-HTTP-Method-Override', 'POST');
$curl->post($url, (string)json_encode($signedParameters, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR));
$response = $this->decodeResponse($curl->getBody());
if ($curl->getStatus() < 200 || $curl->getStatus() >= 300 || (int)($response['code'] ?? -1) !== 0) {
throw new ApiException(
(string)($response['message'] ?? $response['msg'] ?? 'Lingxing API request failed.'),
(string)($response['code'] ?? $curl->getStatus()),
$response
);
}
return $response;
}
private function decodeResponse(string $body): array
{
try {
$decoded = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $exception) {
throw new ApiException('Lingxing returned invalid JSON: ' . $exception->getMessage(), 'invalid_json');
}
return is_array($decoded) ? $decoded : [];
}
}
@@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Model\Api;
class Endpoint
{
public const STORE_LIST = '/pb/mp/shop/v2/getSellerList';
public const ORDER_CREATE = '/pb/mp/order/v2/create';
public const ORDER_LIST = '/pb/mp/order/v2/list';
public const PAIR_LIST = '/pb/mp/listing/v2/getPairList';
public const WMS_ORDER_LIST = '/erp/sc/routing/wms/order/wmsOrderList';
public const WAREHOUSE_LIST = '/erp/sc/data/local_inventory/warehouse';
public const INVENTORY_DETAILS = '/erp/sc/routing/data/local_inventory/inventoryDetails';
private const BY_OPERATION = [
'store_sync' => self::STORE_LIST,
'order_create' => self::ORDER_CREATE,
'sku_pair_lookup' => self::PAIR_LIST,
'shipment_pull' => self::WMS_ORDER_LIST,
'warehouse_sync' => self::WAREHOUSE_LIST,
'inventory_pull' => self::INVENTORY_DETAILS,
'inventory_sync' => self::INVENTORY_DETAILS,
];
public static function forOperation(string $operation): string
{
return self::BY_OPERATION[$operation] ?? '';
}
}
@@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Model\Api;
class Signer
{
public function sign(array $parameters, string $appId): string
{
ksort($parameters);
$pairs = [];
foreach ($parameters as $key => $value) {
if (is_array($value)) {
$value = $this->removeNullArrayValues($value);
$pairs[] = $key . '=' . json_encode(
$value,
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR
);
continue;
}
if ($value === '') {
continue;
}
if (is_bool($value)) {
$value = $value ? 'true' : 'false';
} elseif ($value === null) {
$value = 'null';
}
$pairs[] = $key . '=' . $value;
}
// phpcs:ignore Magento2.Security.InsecureFunction.FoundWithAlternative -- Required by Lingxing's protocol.
$md5 = strtoupper(md5(implode('&', $pairs)));
$encrypted = openssl_encrypt($md5, 'AES-128-ECB', $appId, OPENSSL_RAW_DATA);
if ($encrypted === false) {
throw new \RuntimeException('Unable to generate Lingxing request signature.');
}
return base64_encode($encrypted);
}
private function removeNullArrayValues(array $value): array
{
foreach ($value as $key => $item) {
if (is_array($item)) {
$value[$key] = $this->removeNullArrayValues($item);
} elseif ($item === null) {
unset($value[$key]);
}
}
return $value;
}
}
@@ -0,0 +1,107 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Model\Api;
use Esun\LingxingErp\Model\Config;
use Magento\Framework\App\CacheInterface;
use Magento\Framework\HTTP\Client\CurlFactory;
use Magento\Framework\Lock\LockManagerInterface;
class TokenProvider
{
private const CACHE_KEY = 'esun_lingxing_access_token';
private const LOCK_NAME = 'esun_lingxing_access_token_lock';
public function __construct(
private readonly Config $config,
private readonly CacheInterface $cache,
private readonly CurlFactory $curlFactory,
private readonly LockManagerInterface $lockManager
) {
}
public function getAccessToken(): string
{
$cached = $this->loadCached();
if ($cached !== null) {
return $cached;
}
if (!$this->lockManager->lock(self::LOCK_NAME, 10)) {
throw new ApiException('Another process is refreshing the Lingxing access token.', 'token_locked');
}
try {
$cached = $this->loadCached();
return $cached ?? $this->generateToken();
} finally {
$this->lockManager->unlock(self::LOCK_NAME);
}
}
public function invalidate(): void
{
$this->cache->remove(self::CACHE_KEY);
}
private function loadCached(): ?string
{
$raw = $this->cache->load(self::CACHE_KEY);
if (!is_string($raw) || $raw === '') {
return null;
}
try {
$data = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException) {
return null;
}
if (empty($data['access_token']) || (int)($data['expires_at'] ?? 0) <= time() + 120) {
return null;
}
return (string)$data['access_token'];
}
private function generateToken(): string
{
$this->config->assertCredentialsReady();
$url = $this->config->getApiBaseUrl() . '/api/auth-server/oauth/access-token?' . http_build_query([
'appId' => $this->config->getAppId(),
'appSecret' => $this->config->getAppSecret(),
], '', '&', PHP_QUERY_RFC3986);
$curl = $this->curlFactory->create();
$curl->setTimeout(20);
$curl->post($url, '');
$response = $this->decodeResponse($curl->getBody());
$businessCode = (string)($response['code'] ?? '');
if ($curl->getStatus() < 200 || $curl->getStatus() >= 300
|| !in_array($businessCode, ['0', '200'], true)
) {
throw new ApiException(
(string)($response['message'] ?? $response['msg'] ?? 'Unable to obtain Lingxing access token.'),
(string)($response['code'] ?? $curl->getStatus()),
$response
);
}
$data = is_array($response['data'] ?? null) ? $response['data'] : [];
$token = (string)($data['access_token'] ?? '');
if ($token === '') {
throw new ApiException('Lingxing token response did not include access_token.', 'invalid_token_response');
}
$expiresIn = max(300, (int)($data['expires_in'] ?? 3600));
$this->cache->save((string)json_encode([
'access_token' => $token,
'expires_at' => time() + $expiresIn,
], JSON_THROW_ON_ERROR), self::CACHE_KEY, [], $expiresIn);
return $token;
}
private function decodeResponse(string $body): array
{
try {
$decoded = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $exception) {
throw new ApiException('Lingxing returned invalid JSON: ' . $exception->getMessage(), 'invalid_json');
}
return is_array($decoded) ? $decoded : [];
}
}
+169
View File
@@ -0,0 +1,169 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Model;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Encryption\EncryptorInterface;
use Magento\Store\Model\ScopeInterface;
class Config
{
private const BASE = 'esun_lingxing/';
public function __construct(
private readonly ScopeConfigInterface $scopeConfig,
private readonly EncryptorInterface $encryptor
) {
}
public function isEnabled(): bool
{
return $this->scopeConfig->isSetFlag(self::BASE . 'general/enabled');
}
public function getApiBaseUrl(): string
{
return rtrim((string)$this->scopeConfig->getValue(self::BASE . 'general/api_base_url'), '/');
}
public function getAppId(): string
{
return trim((string)$this->scopeConfig->getValue(self::BASE . 'general/app_id'));
}
public function getAppSecret(): string
{
$value = (string)$this->scopeConfig->getValue(self::BASE . 'general/app_secret');
return $value !== '' ? (string)$this->encryptor->decrypt($value) : '';
}
public function getPlatformCode(int $websiteId): int
{
return $this->getStoreMapping($websiteId)['platform_code'];
}
public function getLingxingStoreId(int $websiteId): string
{
return $this->getStoreMapping($websiteId)['store_id'];
}
public function getWarehouseId(int $websiteId = 0): string
{
return trim((string)$this->getWebsiteValue('general/warehouse_id', $websiteId));
}
public function getLogisticsTypeId(int $websiteId = 0): string
{
return trim((string)$this->getWebsiteValue('general/logistics_type_id', $websiteId));
}
/** @return string[] */
public function getEligibleStatuses(): array
{
$value = (string)$this->scopeConfig->getValue(self::BASE . 'general/eligible_statuses');
return array_values(array_filter(array_map('trim', explode(',', $value))));
}
public function getOrderBatchSize(): int
{
return min(100, max(1, (int)$this->scopeConfig->getValue(self::BASE . 'orders/batch_size')));
}
public function getOrderMaxAttempts(): int
{
return min(50, max(1, (int)$this->scopeConfig->getValue(self::BASE . 'orders/max_attempts')));
}
public function getStockDeductionType(): int
{
return (int)$this->scopeConfig->getValue(self::BASE . 'orders/stock_deduction_type') === 2 ? 2 : 1;
}
public function getShipmentPageSize(): int
{
return min(200, max(1, (int)$this->scopeConfig->getValue(self::BASE . 'shipments/page_size')));
}
public function getShipmentMaxPages(): int
{
return min(100, max(1, (int)$this->scopeConfig->getValue(self::BASE . 'shipments/max_pages')));
}
public function getShipmentMaxAttempts(): int
{
return min(50, max(1, (int)$this->scopeConfig->getValue(self::BASE . 'shipments/max_attempts')));
}
public function shouldNotifyCustomer(): bool
{
return $this->scopeConfig->isSetFlag(self::BASE . 'shipments/notify_customer');
}
public function isSkuSyncEnabled(): bool
{
return $this->scopeConfig->isSetFlag(self::BASE . 'sku_sync/enabled');
}
public function getSkuSyncPageSize(): int
{
return min(200, max(1, (int)$this->scopeConfig->getValue(self::BASE . 'sku_sync/page_size')));
}
public function getSuccessLogRetentionDays(): int
{
return min(365, max(1, (int)$this->scopeConfig->getValue(self::BASE . 'logging/success_retention_days')));
}
public function getErrorLogRetentionDays(): int
{
return min(730, max(1, (int)$this->scopeConfig->getValue(self::BASE . 'logging/error_retention_days')));
}
public function hasStoreMapping(int $websiteId): bool
{
$mapping = $this->getStoreMapping($websiteId);
return $mapping['platform_code'] > 0 && $mapping['store_id'] !== '';
}
public function assertCredentialsReady(): void
{
if ($this->getApiBaseUrl() === '' || $this->getAppId() === '' || $this->getAppSecret() === '') {
throw new \RuntimeException('Lingxing API base URL, App ID and App Secret must be configured.');
}
}
public function assertOrderMappingReady(int $websiteId): void
{
$mapping = $this->getStoreMapping($websiteId);
if ($mapping['platform_code'] <= 0 || $mapping['store_id'] === '') {
throw new \RuntimeException(sprintf(
'No Lingxing store is configured for Magento Website ID %d.',
$websiteId
));
}
if (($this->getWarehouseId($websiteId) === '') !== ($this->getLogisticsTypeId($websiteId) === '')) {
throw new \RuntimeException('Lingxing warehouse and logistics type must either both be set or both be blank.');
}
}
/** @return array{platform_code:int, store_id:string} */
private function getStoreMapping(int $websiteId): array
{
$value = trim((string)$this->scopeConfig->getValue(
self::BASE . 'general/store_mapping',
ScopeInterface::SCOPE_WEBSITE,
$websiteId
));
[$platformCode, $storeId] = array_pad(explode('|', $value, 2), 2, '');
return ['platform_code' => max(0, (int)$platformCode), 'store_id' => trim($storeId)];
}
private function getWebsiteValue(string $path, int $websiteId): mixed
{
if ($websiteId <= 0) {
return $this->scopeConfig->getValue(self::BASE . $path);
}
return $this->scopeConfig->getValue(self::BASE . $path, ScopeInterface::SCOPE_WEBSITE, $websiteId);
}
}
@@ -0,0 +1,89 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Model\Inventory;
use Esun\LingxingErp\Model\Api\ApiException;
use Esun\LingxingErp\Model\Api\Client;
use Esun\LingxingErp\Model\Api\Endpoint;
use Esun\LingxingErp\Model\Sync\LogWriter;
class InventoryFetcher
{
/**
* Lingxing API documentation:
* https://apidoc.lingxing.com/#/docs/Warehouse/InventoryDetails
*/
private const PAGE_SIZE = 800;
public function __construct(
private readonly Client $client,
private readonly LogWriter $logWriter
) {
}
/** @return array<int, array<string, mixed>> */
public function fetchAll(int $wid): array
{
$inventory = [];
$offset = 0;
do {
$request = [
'wid' => (string)$wid,
'offset' => $offset,
'length' => self::PAGE_SIZE,
];
$started = microtime(true);
$response = [];
try {
$response = $this->client->post(Endpoint::INVENTORY_DETAILS, $request);
$rows = $response['data'] ?? null;
if (!is_array($rows)) {
throw new \RuntimeException('Lingxing inventory response is missing data.');
}
$this->logWriter->write([
'direction' => 'pull',
'operation' => 'inventory_pull',
'entity_type' => 'inventory',
'external_id' => (string)$wid,
'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),
]);
} catch (\Throwable $exception) {
$apiResponse = $exception instanceof ApiException ? $exception->getResponse() : $response;
$this->logWriter->write([
'direction' => 'pull',
'operation' => 'inventory_pull',
'entity_type' => 'inventory',
'external_id' => (string)$wid,
'status' => 'failed',
'attempt_number' => 1,
'error_code' => $exception instanceof ApiException
? $exception->getErrorCode()
: (string)$exception->getCode(),
'error_message' => $exception->getMessage(),
'request_id' => (string)($apiResponse['request_id'] ?? ''),
'request_payload' => $request,
'response_payload' => $apiResponse,
'duration_ms' => (int)round((microtime(true) - $started) * 1000),
]);
throw $exception;
}
foreach ($rows as $row) {
if (is_array($row)) {
$inventory[] = $row;
}
}
$received = count($rows);
$offset += $received;
$total = max(0, (int)($response['total'] ?? $offset));
} while ($received > 0 && $offset < $total);
return $inventory;
}
}
@@ -0,0 +1,178 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Model\Inventory;
use Esun\LingxingErp\Model\Sku\ProductErpSkuRepository;
use Esun\LingxingErp\Model\Sync\LogWriter;
use Esun\LingxingErp\Model\Warehouse\WarehouseRepository;
use Magento\Framework\Lock\LockManagerInterface;
use Magento\InventoryApi\Api\Data\SourceItemInterface;
use Magento\InventoryApi\Api\Data\SourceItemInterfaceFactory;
use Magento\InventoryApi\Api\SourceItemsSaveInterface;
class InventorySynchronizer
{
private const LOCK_NAME = 'esun_lingxing_inventory_sync';
private const SAVE_BATCH_SIZE = 500;
public function __construct(
private readonly WarehouseRepository $warehouseRepository,
private readonly InventoryFetcher $fetcher,
private readonly ProductErpSkuRepository $productErpSkuRepository,
private readonly SourceItemInterfaceFactory $sourceItemFactory,
private readonly SourceItemsSaveInterface $sourceItemsSave,
private readonly LogWriter $logWriter,
private readonly LockManagerInterface $lockManager
) {
}
/** @return array{warehouses:int,items:int,unmapped:int,errors:array<int, string>} */
public function synchronizeAll(): array
{
if (!$this->lockManager->lock(self::LOCK_NAME, 0)) {
throw new \RuntimeException('Inventory synchronization is already running.');
}
$summary = ['warehouses' => 0, 'items' => 0, 'unmapped' => 0, 'errors' => []];
try {
foreach ($this->warehouseRepository->getInventoryTargets() as $warehouse) {
$wid = (int)$warehouse['wid'];
$started = microtime(true);
try {
$result = $this->synchronizeWarehouse($warehouse);
$summary['warehouses']++;
$summary['items'] += $result['items'];
$summary['unmapped'] += $result['unmapped'];
$this->warehouseRepository->markInventorySynchronized($wid);
$this->logWriter->write([
'direction' => 'pull',
'operation' => 'inventory_sync',
'entity_type' => 'inventory',
'external_id' => (string)$wid,
'status' => 'success',
'attempt_number' => 1,
'request_payload' => [
'wid' => $wid,
'source_code' => (string)$warehouse['source_code'],
'quantity_field' => 'product_valid_num',
],
'response_payload' => $result,
'duration_ms' => (int)round((microtime(true) - $started) * 1000),
]);
} catch (\Throwable $exception) {
$summary['errors'][$wid] = $exception->getMessage();
$this->logWriter->write([
'direction' => 'pull',
'operation' => 'inventory_sync',
'entity_type' => 'inventory',
'external_id' => (string)$wid,
'status' => 'failed',
'attempt_number' => 1,
'error_code' => (string)$exception->getCode(),
'error_message' => $exception->getMessage(),
'request_payload' => [
'wid' => $wid,
'source_code' => (string)$warehouse['source_code'],
'quantity_field' => 'product_valid_num',
],
'duration_ms' => (int)round((microtime(true) - $started) * 1000),
]);
}
}
} finally {
$this->lockManager->unlock(self::LOCK_NAME);
}
return $summary;
}
/**
* @param array<string, mixed> $warehouse
* @return array{items:int,unmapped:int,zeroed:int,preserved_without_erp_sku:int,unmapped_erp_skus:string[]}
*/
private function synchronizeWarehouse(array $warehouse): array
{
$wid = (int)$warehouse['wid'];
$sourceCode = (string)$warehouse['source_code'];
$websiteIds = $this->warehouseRepository->getWebsiteIdsForSource($sourceCode);
if ($websiteIds === []) {
throw new \RuntimeException(sprintf(
'Magento Source "%s" is not assigned to a Stock with a Website sales channel.',
$sourceCode
));
}
$rows = $this->fetcher->fetchAll($wid);
$quantitiesBySku = [];
$unmapped = [];
foreach ($rows as $row) {
$erpSku = trim((string)($row['sku'] ?? ''));
if ($erpSku === '') {
continue;
}
$magentoSkus = $this->resolveMagentoSkus($websiteIds, $erpSku);
if ($magentoSkus === []) {
$unmapped[$erpSku] = true;
continue;
}
$quantity = max(0.0, (float)($row['product_valid_num'] ?? 0));
foreach ($magentoSkus as $magentoSku) {
// The customer accepts that every Magento SKU paired to the ERP SKU receives the full ERP quantity.
$quantitiesBySku[$magentoSku] = $quantity;
}
}
$existingSkus = $this->warehouseRepository->getExistingSourceItemSkus($sourceCode);
$mappedSkus = $this->getMappedMagentoSkus($websiteIds);
$zeroCandidates = array_values(array_intersect($existingSkus, $mappedSkus));
$preservedWithoutErpSku = array_values(array_diff($existingSkus, $mappedSkus));
$zeroed = array_values(array_diff($zeroCandidates, array_keys($quantitiesBySku)));
foreach ($zeroed as $sku) {
$quantitiesBySku[$sku] = 0.0;
}
$sourceItems = [];
foreach ($quantitiesBySku as $sku => $quantity) {
$sourceItem = $this->sourceItemFactory->create();
$sourceItem->setSourceCode($sourceCode);
$sourceItem->setSku($sku);
$sourceItem->setQuantity($quantity);
$sourceItem->setStatus($quantity > 0
? SourceItemInterface::STATUS_IN_STOCK
: SourceItemInterface::STATUS_OUT_OF_STOCK);
$sourceItems[] = $sourceItem;
}
foreach (array_chunk($sourceItems, self::SAVE_BATCH_SIZE) as $batch) {
$this->sourceItemsSave->execute($batch);
}
return [
'items' => count($quantitiesBySku),
'unmapped' => count($unmapped),
'zeroed' => count($zeroed),
'preserved_without_erp_sku' => count($preservedWithoutErpSku),
'unmapped_erp_skus' => array_slice(array_keys($unmapped), 0, 200),
];
}
/** @param int[] $websiteIds */
private function resolveMagentoSkus(array $websiteIds, string $erpSku): array
{
$matches = [];
foreach ($websiteIds as $websiteId) {
foreach ($this->productErpSkuRepository->findMskusByErpSku($websiteId, $erpSku) as $sku) {
$matches[$sku] = true;
}
}
return array_map('strval', array_keys($matches));
}
/** @param int[] $websiteIds @return string[] */
private function getMappedMagentoSkus(array $websiteIds): array
{
$mapped = [];
foreach ($websiteIds as $websiteId) {
foreach ($this->productErpSkuRepository->getWebsiteProductSkusWithErpSku($websiteId) as $sku) {
$mapped[$sku] = true;
}
}
return array_map('strval', array_keys($mapped));
}
}
@@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Model\Order;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\App\State;
class CancellationSourceResolver
{
public const CUSTOMER = 'customer';
public const SCHEDULED_TASK = 'scheduled_task';
public const ADMINISTRATOR = 'administrator';
public const SYSTEM = 'system';
public function __construct(
private readonly State $appState,
private readonly RequestInterface $request
) {
}
public function resolve(): string
{
$areaCode = '';
try {
$areaCode = $this->appState->getAreaCode();
} catch (\Throwable) {
// Some programmatic cancellations run before an area is initialized.
}
if ($areaCode === 'crontab') {
return self::SCHEDULED_TASK;
}
$fullActionName = method_exists($this->request, 'getFullActionName')
? (string)$this->request->getFullActionName()
: '';
if ($fullActionName === 'esun_customer_order_cancel') {
return self::CUSTOMER;
}
if ($areaCode === 'adminhtml') {
return self::ADMINISTRATOR;
}
return self::SYSTEM;
}
public function getComment(string $source): string
{
return match ($source) {
self::CUSTOMER => 'The customer canceled this order from their account.',
self::SCHEDULED_TASK => 'A scheduled task canceled this order automatically.',
self::ADMINISTRATOR => 'An administrator canceled this order.',
default => 'A system process canceled this order.',
};
}
}
@@ -0,0 +1,88 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Model\Order;
use Esun\LingxingErp\Model\Api\ApiException;
use Esun\LingxingErp\Model\Api\Client;
use Esun\LingxingErp\Model\Api\Endpoint;
use Esun\LingxingErp\Model\Config;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Store\Model\StoreManagerInterface;
class OrderExporter
{
public function __construct(
private readonly Client $client,
private readonly Config $config,
private readonly OrderPayloadBuilder $payloadBuilder,
private readonly StoreManagerInterface $storeManager
) {
}
public function export(OrderInterface $order, ?array $payload = null): array
{
$payload ??= $this->payloadBuilder->build($order);
$websiteId = (int)$this->storeManager->getStore((int)$order->getStoreId())->getWebsiteId();
try {
$response = $this->client->post(Endpoint::ORDER_CREATE, $payload);
} catch (ApiException $exception) {
// The ERP may have committed the order even if the response was lost. Reconcile before retrying.
try {
$existing = $this->findExisting((string)$order->getIncrementId(), $websiteId);
} catch (\Throwable) {
throw $exception;
}
if ($existing !== null) {
return [
'payload' => $payload,
'response' => $exception->getResponse(),
'global_order_no' => $existing,
];
}
throw $exception;
}
$successes = $response['data']['success_details'] ?? [];
foreach (is_array($successes) ? $successes : [] as $success) {
if ((string)($success['platform_order_no'] ?? '') === (string)$order->getIncrementId()
&& (string)($success['global_order_no'] ?? '') !== '') {
return ['payload' => $payload, 'response' => $response, 'global_order_no' => (string)$success['global_order_no']];
}
}
$existing = $this->findExisting((string)$order->getIncrementId(), $websiteId);
if ($existing !== null) {
return ['payload' => $payload, 'response' => $response, 'global_order_no' => $existing];
}
$errors = $response['data']['error_details'] ?? [];
$message = is_array($errors) && $errors !== []
? implode('; ', array_filter(array_map(static fn(array $error): string => (string)($error['error_message'] ?? ''), $errors)))
: 'Lingxing did not return a success record for this order.';
throw new ApiException($message, 'order_not_created', $response);
}
private function findExisting(string $incrementId, int $websiteId): ?string
{
$response = $this->client->post(Endpoint::ORDER_LIST, [
'offset' => 0,
'length' => 20,
'store_id' => [$this->config->getLingxingStoreId($websiteId)],
'platform_code' => [$this->config->getPlatformCode($websiteId)],
'platform_order_nos' => [$incrementId],
]);
foreach (($response['data']['list'] ?? []) as $order) {
foreach (($order['platform_info'] ?? []) as $platformInfo) {
if ((string)($platformInfo['platform_order_no'] ?? '') === $incrementId) {
return (string)($order['global_order_no'] ?? '') ?: null;
}
}
foreach (($order['item_info'] ?? []) as $item) {
if ((string)($item['platform_order_no'] ?? '') === $incrementId) {
return (string)($order['global_order_no'] ?? '') ?: null;
}
}
}
return null;
}
}
@@ -0,0 +1,108 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Model\Order;
use Esun\LingxingErp\Model\Config;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Store\Model\StoreManagerInterface;
class OrderPayloadBuilder
{
/**
* Lingxing API documentation:
* https://apidoc.lingxing.com/#/docs/hide/CreateOrdersV2.md
*/
public function __construct(
private readonly Config $config,
private readonly StoreManagerInterface $storeManager
) {
}
public function build(OrderInterface $order): array
{
$websiteId = (int)$this->storeManager->getStore((int)$order->getStoreId())->getWebsiteId();
$this->config->assertOrderMappingReady($websiteId);
$address = $order->getShippingAddress() ?: $order->getBillingAddress();
if ($address === null) {
throw new \RuntimeException('Magento order has no shipping or billing address.');
}
$items = [];
foreach ($order->getAllVisibleItems() as $item) {
if ($item->getIsVirtual()) {
continue;
}
$sku = trim((string)$item->getSku());
if ($sku === '') {
throw new \RuntimeException('Magento order item has an empty SKU.');
}
$items[] = [
'msku' => $sku,
'quantity' => (int)$item->getQtyOrdered(),
'unit_price' => (float)$item->getPrice(),
'stock_deduction_type' => $this->config->getStockDeductionType(),
];
}
if ($items === []) {
throw new \RuntimeException('Magento order has no physical SKU to export.');
}
$street = $address->getStreet();
$streetLines = array_values(array_filter(array_map(
static fn ($line): string => trim((string)$line),
is_array($street) ? $street : [(string)$street]
), static fn (string $line): bool => $line !== ''));
$receiverName = trim((string)$address->getFirstname() . ' ' . (string)$address->getLastname());
$buyerName = trim(implode(' ', array_filter([
trim((string)$order->getCustomerFirstname()),
trim((string)$order->getCustomerMiddlename()),
trim((string)$order->getCustomerLastname()),
], static fn (string $part): bool => $part !== '')));
$buyerEmail = trim((string)$order->getCustomerEmail());
if ($buyerEmail === '') {
$buyerEmail = trim((string)$address->getEmail());
}
$orderData = [
'platform_order_no' => (string)$order->getIncrementId(),
'receiver_country_code' => (string)$address->getCountryId(),
'customer_shipping_amount' => (float)$order->getShippingAmount(),
'customer_tax_amount' => (float)$order->getTaxAmount(),
'order_total_amount' => (float)$order->getGrandTotal(),
'global_purchase_time' => (new \DateTimeImmutable((string)$order->getCreatedAt(), new \DateTimeZone('UTC')))->getTimestamp(),
'receiver_name' => $receiverName,
'receiver_company_name' => (string)$address->getCompany(),
'city' => (string)$address->getCity(),
'address_line1' => $streetLines[0] ?? '',
'amount_currency' => (string)$order->getOrderCurrencyCode(),
'items' => $items,
];
$optionalAddressData = [
'state_or_region' => trim((string)$address->getRegion()),
'postal_code' => trim((string)$address->getPostcode()),
'address_line2' => $streetLines[1] ?? '',
'address_line3' => count($streetLines) > 2 ? implode(' ', array_slice($streetLines, 2)) : '',
'receiver_mobile' => trim((string)$address->getTelephone()),
'buyer_email' => $buyerEmail,
'buyer_name' => $buyerName !== '' ? $buyerName : $receiverName,
];
foreach ($optionalAddressData as $field => $value) {
if ($value !== '') {
$orderData[$field] = $value;
}
}
if ((string)$order->getCustomerNote() !== '') {
$orderData['buyer_note'] = (string)$order->getCustomerNote();
}
if ($this->config->getWarehouseId($websiteId) !== '') {
$orderData['wid'] = $this->config->getWarehouseId($websiteId);
$orderData['logistics_type_id'] = $this->config->getLogisticsTypeId($websiteId);
}
return [
'platform_code' => $this->config->getPlatformCode($websiteId),
'store_id' => $this->config->getLingxingStoreId($websiteId),
'orders' => [$orderData],
];
}
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Model\Product\Attribute\Backend;
use Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend;
/**
* Normalizes ERP SKU values.
*
* The class name is retained because installed attributes reference it. Multiple Magento SKUs are intentionally
* allowed to use the same ERP SKU within one Website.
*/
class WebsiteUnique extends AbstractBackend
{
public function beforeSave($object): self
{
$attributeCode = (string)$this->getAttribute()->getAttributeCode();
$value = trim((string)$object->getData($attributeCode));
$object->setData($attributeCode, $value);
return parent::beforeSave($object);
}
}
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Model\ResourceModel\Log\Grid;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Data\Collection\Db\FetchStrategyInterface as FetchStrategy;
use Magento\Framework\Data\Collection\EntityFactoryInterface as EntityFactory;
use Magento\Framework\Event\ManagerInterface as EventManager;
use Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult;
use Psr\Log\LoggerInterface as Logger;
class Collection extends SearchResult
{
public function __construct(
EntityFactory $entityFactory,
Logger $logger,
FetchStrategy $fetchStrategy,
EventManager $eventManager,
RequestInterface $request,
$mainTable = 'esun_lingxing_sync_log',
$resourceModel = null,
$identifierName = null,
$connectionName = null
) {
parent::__construct(
$entityFactory,
$logger,
$fetchStrategy,
$eventManager,
$mainTable,
$resourceModel,
$identifierName,
$connectionName
);
$filters = (array)$request->getParam('filters', []);
if (!isset($filters['status']) || trim((string)$filters['status']) === '') {
$this->addFieldToFilter('status', ['in' => ['failed', 'retrying']]);
}
}
}
@@ -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;
}
}
@@ -0,0 +1,97 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Model\Sku;
use Esun\LingxingErp\Model\Api\ApiException;
use Esun\LingxingErp\Model\Api\Client;
use Esun\LingxingErp\Model\Api\Endpoint;
use Esun\LingxingErp\Model\Sync\LogWriter;
class PairFetcher
{
/**
* Lingxing API documentation:
* https://apidoc.lingxing.com/#/docs/MultiPlatform/V2/PairListV2
*/
private const MAX_PAGES = 10000;
private const MSKU_BATCH_SIZE = 200;
public function __construct(
private readonly Client $client,
private readonly LogWriter $logWriter
) {
}
/** @param string[] $mskus @return array<int, array<string, mixed>> */
public function fetchAll(int $platformCode, string $storeId, array $mskus, int $pageSize): array
{
$pairs = [];
foreach (array_chunk(array_values(array_unique($mskus)), self::MSKU_BATCH_SIZE) as $mskuBatch) {
$offset = 0;
for ($page = 1; $page <= self::MAX_PAGES; $page++) {
$request = [
'offset' => $offset,
'length' => $pageSize,
'msku' => $mskuBatch,
'platform_codes' => [(string)$platformCode],
'store_ids' => [$storeId],
];
$started = microtime(true);
$response = [];
try {
$response = $this->client->post(Endpoint::PAIR_LIST, $request);
$rows = $response['data']['list'] ?? null;
if (!is_array($rows)) {
throw new \RuntimeException('Lingxing PairListV2 response is missing data.list.');
}
$this->logWriter->write([
'direction' => 'pull',
'operation' => 'sku_pair_lookup',
'entity_type' => 'product',
'external_id' => $storeId,
'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),
]);
} catch (\Throwable $exception) {
$apiResponse = $exception instanceof ApiException ? $exception->getResponse() : $response;
$this->logWriter->write([
'direction' => 'pull',
'operation' => 'sku_pair_lookup',
'entity_type' => 'product',
'external_id' => $storeId,
'status' => 'failed',
'attempt_number' => 1,
'error_code' => $exception instanceof ApiException
? $exception->getErrorCode()
: (string)$exception->getCode(),
'error_message' => $exception->getMessage(),
'request_id' => (string)($apiResponse['request_id'] ?? ''),
'request_payload' => $request,
'response_payload' => $apiResponse,
'duration_ms' => (int)round((microtime(true) - $started) * 1000),
]);
throw $exception;
}
foreach ($rows as $row) {
if (is_array($row)) {
$pairs[] = $row;
}
}
$count = count($rows);
if ($count < $pageSize) {
break;
}
$offset += $count;
if ($page === self::MAX_PAGES) {
throw new \RuntimeException('Lingxing PairListV2 exceeded the maximum pagination limit.');
}
}
}
return $pairs;
}
}
@@ -0,0 +1,219 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Model\Sku;
use Magento\Catalog\Model\ResourceModel\Product\Action as ProductActionResource;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Model\Product;
use Magento\Eav\Model\Config as EavConfig;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\EntityManager\MetadataPool;
use Magento\Store\Model\StoreManagerInterface;
class ProductErpSkuRepository
{
public function __construct(
private readonly ResourceConnection $resource,
private readonly ProductActionResource $productActionResource,
private readonly StoreManagerInterface $storeManager,
private readonly EavConfig $eavConfig,
private readonly MetadataPool $metadataPool
) {
}
/** @return string[] */
public function getWebsiteProductSkus(int $websiteId): array
{
return array_keys($this->getWebsiteProductIdsBySku($websiteId));
}
/** @return string[] */
public function getWebsiteProductSkusWithErpSku(int $websiteId): array
{
$defaultStore = $this->getDefaultStore($websiteId);
$attributeId = (int)$this->eavConfig
->getAttribute(Product::ENTITY, 'erp_sku')
->getAttributeId();
if ($attributeId <= 0) {
throw new \RuntimeException('The erp_sku product attribute does not exist.');
}
$connection = $this->resource->getConnection();
$linkField = $this->metadataPool->getMetadata(ProductInterface::class)->getLinkField();
$select = $connection->select()
->distinct()
->from(
['product' => $this->resource->getTableName('catalog_product_entity')],
['sku']
)
->joinInner(
['website' => $this->resource->getTableName('catalog_product_website')],
'website.product_id = product.entity_id',
[]
)
->joinInner(
['erp_sku_value' => $this->resource->getTableName('catalog_product_entity_varchar')],
sprintf('erp_sku_value.%1$s = product.%1$s', $linkField),
[]
)
->where('website.website_id = ?', $websiteId)
->where('erp_sku_value.attribute_id = ?', $attributeId)
->where('erp_sku_value.store_id = ?', (int)$defaultStore->getId())
->where('erp_sku_value.value IS NOT NULL')
->where('TRIM(erp_sku_value.value) <> ?', '')
->order('product.entity_id ASC');
return array_map('strval', $connection->fetchCol($select));
}
/** @return string[] */
public function findMskusByErpSku(int $websiteId, string $erpSku): array
{
$erpSku = trim($erpSku);
if ($erpSku === '') {
return [];
}
$defaultStore = $this->getDefaultStore($websiteId);
$attributeId = (int)$this->eavConfig
->getAttribute(Product::ENTITY, 'erp_sku')
->getAttributeId();
if ($attributeId <= 0) {
throw new \RuntimeException('The erp_sku product attribute does not exist.');
}
$connection = $this->resource->getConnection();
$linkField = $this->metadataPool->getMetadata(ProductInterface::class)->getLinkField();
$select = $connection->select()
->from(
['product' => $this->resource->getTableName('catalog_product_entity')],
['sku']
)
->joinInner(
['website' => $this->resource->getTableName('catalog_product_website')],
'website.product_id = product.entity_id',
[]
)
->joinInner(
['erp_sku_value' => $this->resource->getTableName('catalog_product_entity_varchar')],
sprintf('erp_sku_value.%1$s = product.%1$s', $linkField),
[]
)
->where('website.website_id = ?', $websiteId)
->where('erp_sku_value.attribute_id = ?', $attributeId)
->where('erp_sku_value.store_id = ?', (int)$defaultStore->getId())
->where('erp_sku_value.value = ?', $erpSku)
->order('product.entity_id ASC');
return array_values(array_unique(array_map('strval', $connection->fetchCol($select))));
}
/**
* @param array<int, array<string, mixed>> $rawPairs
* @return array{requested:int,pairs:int,mapped:int,unmapped:int,unmapped_mskus:string[]}
*/
public function updateWebsiteErpSkus(
int $websiteId,
int $platformCode,
string $storeId,
array $rawPairs
): array {
$pairs = $this->normalizeAndValidate($platformCode, $storeId, $rawPairs);
$productIdsBySku = $this->getWebsiteProductIdsBySku($websiteId);
$defaultStore = $this->getDefaultStore($websiteId);
$storeViewId = (int)$defaultStore->getId();
if ($productIdsBySku !== []) {
$this->productActionResource->updateAttributes(
array_values($productIdsBySku),
['erp_sku' => null],
$storeViewId
);
}
$mappedMskus = [];
foreach ($pairs as $msku => $erpSku) {
if (!isset($productIdsBySku[$msku])) {
continue;
}
$this->productActionResource->updateAttributes(
[$productIdsBySku[$msku]],
['erp_sku' => $erpSku],
$storeViewId
);
$mappedMskus[$msku] = true;
}
$unmappedMskus = array_values(array_diff(array_keys($productIdsBySku), array_keys($mappedMskus)));
return [
'requested' => count($productIdsBySku),
'pairs' => count($pairs),
'mapped' => count($mappedMskus),
'unmapped' => count($unmappedMskus),
// Keep attempt logs useful without allowing one response to exceed the log column.
'unmapped_mskus' => array_slice($unmappedMskus, 0, 200),
];
}
/** @param array<int, array<string, mixed>> $rawPairs @return array<string, string> */
private function normalizeAndValidate(int $platformCode, string $storeId, array $rawPairs): array
{
$byMsku = [];
$erpSkuByNormalizedMsku = [];
foreach ($rawPairs as $row) {
if ((string)($row['platform_code'] ?? '') !== (string)$platformCode
|| (string)($row['store_id'] ?? '') !== $storeId
) {
continue;
}
$msku = trim((string)($row['msku'] ?? ''));
$erpSku = trim((string)($row['sku'] ?? ''));
if ($msku === '' || $erpSku === '') {
continue;
}
$normalizedMsku = mb_strtolower($msku);
if (isset($erpSkuByNormalizedMsku[$normalizedMsku])
&& $erpSkuByNormalizedMsku[$normalizedMsku] !== $erpSku
) {
throw new \RuntimeException(sprintf(
'Lingxing returned multiple ERP SKUs for MSKU "%s" in Website mapping %d/%s.',
$msku,
$platformCode,
$storeId
));
}
$byMsku[$msku] = $erpSku;
$erpSkuByNormalizedMsku[$normalizedMsku] = $erpSku;
}
return $byMsku;
}
/** @return array<string, int> */
private function getWebsiteProductIdsBySku(int $websiteId): array
{
$connection = $this->resource->getConnection();
$select = $connection->select()
->from(['product' => $this->resource->getTableName('catalog_product_entity')], ['sku', 'entity_id'])
->joinInner(
['website' => $this->resource->getTableName('catalog_product_website')],
'website.product_id = product.entity_id',
[]
)
->where('website.website_id = ?', $websiteId)
->where('product.sku <> ?', '')
->order('product.entity_id ASC');
$result = [];
foreach ($connection->fetchAll($select) as $row) {
$result[(string)$row['sku']] = (int)$row['entity_id'];
}
return $result;
}
private function getDefaultStore(int $websiteId): \Magento\Store\Api\Data\StoreInterface
{
$store = $this->storeManager->getWebsite($websiteId)->getDefaultStore();
if ($store === null) {
throw new \RuntimeException(sprintf('Magento Website ID %d has no default store view.', $websiteId));
}
return $store;
}
}
@@ -0,0 +1,96 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Model\Sku;
use Esun\LingxingErp\Model\Config;
use Esun\LingxingErp\Model\Sync\LogWriter;
use Magento\Framework\Lock\LockManagerInterface;
use Magento\Store\Model\StoreManagerInterface;
class SkuSynchronizer
{
private const LOCK_NAME = 'esun_lingxing_sku_sync';
public function __construct(
private readonly Config $config,
private readonly StoreManagerInterface $storeManager,
private readonly PairFetcher $pairFetcher,
private readonly ProductErpSkuRepository $repository,
private readonly LogWriter $logWriter,
private readonly LockManagerInterface $lockManager
) {
}
/** @return array{websites:int,pairs:int,mapped:int,unmapped:int,errors:array<int, string>} */
public function synchronizeAll(): array
{
if (!$this->lockManager->lock(self::LOCK_NAME, 0)) {
throw new \RuntimeException('ERP SKU synchronization is already running.');
}
$summary = ['websites' => 0, 'pairs' => 0, 'mapped' => 0, 'unmapped' => 0, 'errors' => []];
try {
foreach ($this->storeManager->getWebsites(false) as $website) {
$websiteId = (int)$website->getId();
if ($websiteId <= 0 || !$this->config->hasStoreMapping($websiteId)) {
continue;
}
$started = microtime(true);
$platformCode = $this->config->getPlatformCode($websiteId);
$storeId = $this->config->getLingxingStoreId($websiteId);
$request = [
'website_id' => $websiteId,
'platform_codes' => [(string)$platformCode],
'store_ids' => [$storeId],
];
try {
$mskus = $this->repository->getWebsiteProductSkus($websiteId);
$pairs = $this->pairFetcher->fetchAll(
$platformCode,
$storeId,
$mskus,
$this->config->getSkuSyncPageSize()
);
$result = $this->repository->updateWebsiteErpSkus(
$websiteId,
$platformCode,
$storeId,
$pairs
);
$summary['websites']++;
$summary['pairs'] += $result['pairs'];
$summary['mapped'] += $result['mapped'];
$summary['unmapped'] += $result['unmapped'];
$this->logWriter->write([
'direction' => 'pull',
'operation' => 'sku_sync',
'entity_type' => 'product',
'external_id' => $storeId,
'status' => 'success',
'attempt_number' => 1,
'request_payload' => $request,
'response_payload' => $result,
'duration_ms' => (int)round((microtime(true) - $started) * 1000),
]);
} catch (\Throwable $exception) {
$summary['errors'][$websiteId] = $exception->getMessage();
$this->logWriter->write([
'direction' => 'pull',
'operation' => 'sku_sync',
'entity_type' => 'product',
'external_id' => $storeId,
'status' => 'failed',
'attempt_number' => 1,
'error_code' => (string)$exception->getCode(),
'error_message' => $exception->getMessage(),
'request_payload' => $request,
'duration_ms' => (int)round((microtime(true) - $started) * 1000),
]);
}
}
} finally {
$this->lockManager->unlock(self::LOCK_NAME);
}
return $summary;
}
}
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Model\Source;
use Magento\Framework\Data\OptionSourceInterface;
class Direction implements OptionSourceInterface
{
public function toOptionArray(): array
{
return [
['value' => 'push', 'label' => __('Push to Lingxing')],
['value' => 'pull', 'label' => __('Pull from Lingxing')],
];
}
}
@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Model\Source;
use Esun\LingxingErp\Model\Store\StoreRepository;
use Magento\Framework\Data\OptionSourceInterface;
class LingxingStore implements OptionSourceInterface
{
public function __construct(
private readonly StoreRepository $repository
) {
}
public function toOptionArray(): array
{
$options = [['value' => '', 'label' => __('-- Select a Lingxing store --')]];
$stores = $this->repository->getAll();
if ($stores === []) {
$options[] = [
'value' => '',
'label' => __('No local stores. Use Esun > Lingxing ERP > Stores > Sync Stores.'),
'disabled' => true,
];
return $options;
}
foreach ($stores as $store) {
$platformCode = (int)$store['platform_code'];
$storeId = (string)$store['store_id'];
$active = (int)$store['is_sync'] === 1 && (int)$store['status'] === 1;
$options[] = [
'value' => $platformCode . '|' . $storeId,
'disabled' => !$active,
'label' => sprintf(
'%s[%s / %d] %s (%s)',
$active ? '' : (string)__('Inactive: '),
(string)($store['platform_name'] ?? 'Platform'),
$platformCode,
(string)($store['store_name'] ?? $storeId),
$storeId
),
];
}
return $options;
}
}
@@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Model\Source;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Data\OptionSourceInterface;
class LingxingWarehouse implements OptionSourceInterface
{
public function __construct(private readonly ResourceConnection $resource)
{
}
public function toOptionArray(): array
{
$options = [['value' => '', 'label' => __('Not mapped')]];
$connection = $this->resource->getConnection();
$table = $this->resource->getTableName('esun_lingxing_warehouse');
if (!$connection->isTableExists($table)) {
return $options;
}
$rows = $connection->fetchAll($connection->select()
->from($table, ['wid', 'warehouse_name', 'source_code'])
->where('warehouse_type = ?', 3)
->where('is_deleted = ?', 0)
->where('lingxing_status = ?', 1)
->order(['warehouse_type ASC', 'warehouse_name ASC']));
foreach ($rows as $row) {
$options[] = [
'value' => (string)$row['wid'],
'label' => sprintf(
'%s (WID %s%s)',
$row['warehouse_name'],
$row['wid'],
$row['source_code'] ? ' / mapped to ' . $row['source_code'] : ''
),
];
}
return $options;
}
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Model\Source;
use Magento\Framework\Data\OptionSourceInterface;
class SyncStatus implements OptionSourceInterface
{
public function toOptionArray(): array
{
return [
['value' => 'pending', 'label' => __('Pending')],
['value' => 'processing', 'label' => __('Processing')],
['value' => 'retrying', 'label' => __('Retrying')],
['value' => 'success', 'label' => __('Success')],
['value' => 'failed', 'label' => __('Failed')],
['value' => 'ignored', 'label' => __('Ignored')],
['value' => 'canceled', 'label' => __('Canceled')],
['value' => 'not_required', 'label' => __('Not Required')],
];
}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Model\Source;
use Magento\Framework\Data\OptionSourceInterface;
class WarehouseType implements OptionSourceInterface
{
public function toOptionArray(): array
{
return [
['value' => 1, 'label' => __('Local Warehouse')],
['value' => 3, 'label' => __('Overseas Warehouse')],
['value' => 4, 'label' => __('Platform Warehouse')],
['value' => 6, 'label' => __('AWD Warehouse')],
];
}
}
@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Model\Store;
use Esun\LingxingErp\Model\Api\ApiException;
use Esun\LingxingErp\Model\Api\Client;
use Esun\LingxingErp\Model\Api\Endpoint;
class StoreFetcher
{
private const PAGE_SIZE = 200;
private const PLATFORM_CODE = 10009;
public function __construct(private readonly Client $client)
{
}
/** @return array<int, array<string, mixed>> */
public function fetchAll(): array
{
$stores = [];
$offset = 0;
do {
$response = $this->client->post(Endpoint::STORE_LIST, [
'offset' => $offset,
'length' => self::PAGE_SIZE,
'platform_code' => [self::PLATFORM_CODE],
]);
$list = is_array($response['data']['list'] ?? null) ? $response['data']['list'] : [];
foreach ($list as $store) {
if (!is_array($store)) {
continue;
}
$platformCode = (int)($store['platform_code'] ?? 0);
$storeId = trim((string)($store['store_id'] ?? ''));
if ($platformCode <= 0 || $storeId === '') {
throw new ApiException('StoreInfoV2 returned a store without platform_code or store_id.', 'invalid_store_data');
}
$stores[] = $store;
}
$received = count($list);
$offset += $received;
$total = max(0, (int)($response['data']['total'] ?? $offset));
} while ($received > 0 && $offset < $total);
return $stores;
}
}
@@ -0,0 +1,78 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Model\Store;
use Magento\Framework\App\ResourceConnection;
class StoreRepository
{
public function __construct(private readonly ResourceConnection $resource)
{
}
/** @return array<int, array<string, mixed>> */
public function getAll(): array
{
$connection = $this->resource->getConnection();
$select = $connection->select()
->from($this->resource->getTableName('esun_lingxing_store'))
->order(['platform_name ASC', 'store_name ASC', 'store_id ASC']);
return $connection->fetchAll($select);
}
/** @return array<int, string> */
public function getActiveStoreNames(): array
{
$connection = $this->resource->getConnection();
$select = $connection->select()
->from($this->resource->getTableName('esun_lingxing_store'), ['store_name'])
->where('platform_code = ?', 10009)
->where('is_sync = ?', 1)
->where('status = ?', 1)
->order('store_name ASC');
return array_values(array_filter(array_map(
static fn ($name): string => trim((string)$name),
$connection->fetchCol($select)
)));
}
/** @param array<int, array<string, mixed>> $stores */
public function synchronize(array $stores): void
{
$connection = $this->resource->getConnection();
$table = $this->resource->getTableName('esun_lingxing_store');
$now = gmdate('Y-m-d H:i:s');
$rows = [];
foreach ($stores as $store) {
$rows[] = [
'platform_code' => (int)$store['platform_code'],
'platform_name' => trim((string)($store['platform_name'] ?? '')),
'store_id' => trim((string)$store['store_id']),
'sid' => trim((string)($store['sid'] ?? '')),
'store_name' => trim((string)($store['store_name'] ?? '')),
'currency' => trim((string)($store['currency'] ?? '')),
'is_sync' => (int)($store['is_sync'] ?? 0),
'status' => (int)($store['status'] ?? 0),
'last_synced_at' => $now,
];
}
$connection->beginTransaction();
try {
// Rows absent from a complete response remain visible, but cannot be selected as active stores.
$connection->update($table, ['is_sync' => 0, 'status' => 0]);
if ($rows !== []) {
$connection->insertOnDuplicate($table, $rows, [
'platform_code', 'platform_name', 'sid', 'store_name', 'currency',
'is_sync', 'status', 'last_synced_at',
]);
}
$connection->commit();
} catch (\Throwable $exception) {
$connection->rollBack();
throw $exception;
}
}
}
@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Model\Store;
use Esun\LingxingErp\Model\Api\ApiException;
use Esun\LingxingErp\Model\Sync\LogWriter;
class StoreSynchronizer
{
public function __construct(
private readonly StoreFetcher $fetcher,
private readonly StoreRepository $repository,
private readonly LogWriter $logWriter
) {
}
public function synchronize(): int
{
$started = microtime(true);
try {
$stores = $this->fetcher->fetchAll();
$this->repository->synchronize($stores);
$this->logWriter->write([
'direction' => 'pull',
'operation' => 'store_sync',
'entity_type' => 'store',
'status' => 'success',
'response_payload' => ['store_count' => count($stores)],
'duration_ms' => (int)round((microtime(true) - $started) * 1000),
]);
return count($stores);
} catch (\Throwable $exception) {
$code = $exception instanceof ApiException ? $exception->getErrorCode() : (string)$exception->getCode();
$response = $exception instanceof ApiException ? $exception->getResponse() : [];
$this->logWriter->write([
'direction' => 'pull',
'operation' => 'store_sync',
'entity_type' => 'store',
'status' => 'failed',
'error_code' => $code,
'error_message' => $exception->getMessage(),
'response_payload' => $response,
'duration_ms' => (int)round((microtime(true) - $started) * 1000),
]);
throw $exception;
}
}
}
@@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Model\Sync;
use Magento\Framework\App\ResourceConnection;
class DetailProvider
{
private const SYNC_TABLES = [
'order' => 'esun_lingxing_order_sync',
'shipment' => 'esun_lingxing_shipment_sync',
];
public function __construct(private readonly ResourceConnection $resource)
{
}
/** @return array<string, mixed>|null */
public function getRecord(string $type, int $id): ?array
{
$table = $type === 'log'
? 'esun_lingxing_sync_log'
: (self::SYNC_TABLES[$type] ?? '');
if ($table === '' || $id <= 0) {
return null;
}
$connection = $this->resource->getConnection();
$row = $connection->fetchRow(
$connection->select()
->from($this->resource->getTableName($table))
->where('entity_id = ?', $id)
->limit(1)
);
return is_array($row) && $row !== [] ? $row : null;
}
/** @return array<int, array<string, mixed>> */
public function getLogs(string $type, array $record): array
{
if ($type === 'log') {
return [$record];
}
if (!isset(self::SYNC_TABLES[$type])) {
return [];
}
$connection = $this->resource->getConnection();
$select = $connection->select()
->from($this->resource->getTableName('esun_lingxing_sync_log'))
->where('entity_type = ?', $type)
->order('entity_id DESC');
$localId = (int)($record['entity_id'] ?? 0);
$requestId = trim((string)($record['request_id'] ?? ''));
if ($requestId !== '') {
$select->where(sprintf(
'(%s OR %s)',
$connection->quoteInto('local_entity_id = ?', $localId),
$connection->quoteInto('request_id = ?', $requestId)
));
} else {
$select->where('local_entity_id = ?', $localId);
}
return $connection->fetchAll($select);
}
}
@@ -0,0 +1,92 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Model\Sync;
use Esun\LingxingErp\Model\Api\Endpoint;
use Magento\Framework\App\ResourceConnection;
class LogWriter
{
private const COMPACT_STATUSES = ['success', 'ignored'];
private const SUMMARY_SCALAR_KEYS = [
'code', 'message', 'request_id', 'store_count', 'shipment_id',
'pairs', 'mapped', 'unmapped', 'zeroed', 'preserved_without_erp_sku', 'total', 'count',
];
private const SENSITIVE_KEYS = [
'appsecret', 'app_secret', 'access_token', 'refresh_token', 'sign',
'receiver_name', 'receiver_company_name', 'address_line1', 'address_line2',
'address_line3', 'postal_code', 'postcode', 'receiver_mobile', 'buyer_email', 'buyer_name',
'phone', 'telephone', 'email', 'consignee', 'consignee_phone', 'consignee_address',
'consignee_full_address',
];
public function __construct(private readonly ResourceConnection $resource)
{
}
public function write(array $data): void
{
$data['api_path'] ??= Endpoint::forOperation((string)($data['operation'] ?? '')) ?: null;
$compactPayload = in_array((string)($data['status'] ?? ''), self::COMPACT_STATUSES, true);
foreach (['request_payload', 'response_payload'] as $field) {
if (!isset($data[$field])) {
continue;
}
if ($compactPayload) {
$data[$field] = $this->summarize($data[$field]);
}
if (is_array($data[$field])) {
$data[$field] = json_encode(
$this->sanitize($data[$field]),
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR
);
}
}
$data['created_at'] = gmdate('Y-m-d H:i:s');
$this->resource->getConnection()->insert(
$this->resource->getTableName('esun_lingxing_sync_log'),
$data
);
}
private function summarize(mixed $payload): array
{
$sanitized = is_array($payload) ? $this->sanitize($payload) : $payload;
$encoded = json_encode(
$sanitized,
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR
);
$summary = [
'_summary' => 'Success payload omitted by retention policy.',
'payload_sha256' => hash('sha256', $encoded),
'payload_bytes' => strlen($encoded),
];
if (!is_array($sanitized)) {
return $summary;
}
$summary['top_level_keys'] = array_values(array_map('strval', array_keys($sanitized)));
foreach ($sanitized as $key => $value) {
$normalized = strtolower((string)$key);
if (in_array($normalized, self::SUMMARY_SCALAR_KEYS, true) && is_scalar($value)) {
$summary[$key] = $value;
} elseif (is_array($value)) {
$summary[$key . '_count'] = count($value);
}
}
return $summary;
}
private function sanitize(array $data): array
{
foreach ($data as $key => $value) {
$normalized = strtolower((string)$key);
if (in_array($normalized, self::SENSITIVE_KEYS, true)) {
$data[$key] = '[REDACTED]';
} elseif (is_array($value)) {
$data[$key] = $this->sanitize($value);
}
}
return $data;
}
}
@@ -0,0 +1,146 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Model\Sync;
use Magento\Framework\App\ResourceConnection;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Model\Order;
class OrderSyncRepository
{
private string $table;
public function __construct(private readonly ResourceConnection $resource)
{
$this->table = $resource->getTableName('esun_lingxing_order_sync');
}
public function enqueue(OrderInterface $order): void
{
$connection = $this->resource->getConnection();
$exists = $connection->fetchOne(
$connection->select()->from($this->table, ['entity_id'])->where('order_id = ?', (int)$order->getEntityId())
);
if ($exists) {
return;
}
$now = gmdate('Y-m-d H:i:s');
$connection->insert($this->table, [
'order_id' => (int)$order->getEntityId(),
'increment_id' => (string)$order->getIncrementId(),
'platform_order_no' => (string)$order->getIncrementId(),
'status' => 'pending',
'created_at' => $now,
'updated_at' => $now,
]);
}
public function getDue(int $limit): array
{
$connection = $this->resource->getConnection();
return $connection->fetchAll($connection->select()->from($this->table)
->where('status IN (?)', ['pending', 'retrying'])
->where('next_retry_at IS NULL OR next_retry_at <= ?', gmdate('Y-m-d H:i:s'))
->order('entity_id ASC')->limit($limit));
}
public function claim(int $entityId): bool
{
return $this->resource->getConnection()->update(
$this->table,
['status' => 'processing', 'last_attempt_at' => gmdate('Y-m-d H:i:s')],
['entity_id = ?' => $entityId, 'status IN (?)' => ['pending', 'retrying']]
) === 1;
}
public function markSuccess(int $entityId, string $globalOrderNo, string $requestId, string $payloadHash): void
{
$now = gmdate('Y-m-d H:i:s');
$this->resource->getConnection()->update($this->table, [
'global_order_no' => $globalOrderNo,
'status' => 'success',
'request_id' => $requestId ?: null,
'payload_hash' => $payloadHash,
'last_error_code' => null,
'last_error_message' => null,
'next_retry_at' => null,
'synced_at' => $now,
'updated_at' => $now,
], ['entity_id = ?' => $entityId]);
}
public function markCreationCanceled(int $entityId): void
{
$now = gmdate('Y-m-d H:i:s');
$this->resource->getConnection()->update($this->table, [
'status' => 'canceled',
'next_retry_at' => null,
'updated_at' => $now,
], ['entity_id = ?' => $entityId]);
}
public function markFailure(int $entityId, int $attemptCount, int $maxAttempts, string $code, string $message, string $requestId = ''): string
{
$attemptCount++;
$status = $attemptCount >= $maxAttempts ? 'failed' : 'retrying';
$delay = min(3600, 30 * (2 ** min(7, max(0, $attemptCount - 1))));
$this->resource->getConnection()->update($this->table, [
'status' => $status,
'attempt_count' => $attemptCount,
'next_retry_at' => $status === 'retrying' ? gmdate('Y-m-d H:i:s', time() + $delay) : null,
'last_error_code' => $code ?: null,
'last_error_message' => mb_substr($message, 0, 65535),
'request_id' => $requestId ?: null,
'updated_at' => gmdate('Y-m-d H:i:s'),
], ['entity_id = ?' => $entityId]);
return $status;
}
public function findByGlobalOrderNo(string $globalOrderNo): ?array
{
$connection = $this->resource->getConnection();
$row = $connection->fetchRow($connection->select()->from($this->table)
->where('global_order_no = ?', $globalOrderNo)->limit(1));
return is_array($row) ? $row : null;
}
public function findByIncrementId(string $incrementId): ?array
{
$connection = $this->resource->getConnection();
$row = $connection->fetchRow($connection->select()->from($this->table)
->where('increment_id = ?', $incrementId)->limit(1));
return is_array($row) ? $row : null;
}
/** @return string[] */
public function getTrackablePlatformOrderNos(): array
{
$connection = $this->resource->getConnection();
$salesOrderTable = $this->resource->getTableName('sales_order');
$select = $connection->select()
->from(['sync' => $this->table], ['platform_order_no'])
->joinInner(['sales_order' => $salesOrderTable], 'sales_order.entity_id = sync.order_id', [])
->where('sync.status = ?', 'success')
->where('sync.platform_order_no <> ?', '')
->where('sales_order.state NOT IN (?)', [
Order::STATE_COMPLETE,
Order::STATE_CLOSED,
Order::STATE_CANCELED,
])
->order('sync.entity_id ASC');
return array_values(array_unique(array_map('strval', $connection->fetchCol($select))));
}
public function retry(int $entityId): bool
{
return $this->resource->getConnection()->update($this->table, [
'status' => 'pending',
'attempt_count' => 0,
'next_retry_at' => null,
'last_error_code' => null,
'last_error_message' => null,
'updated_at' => gmdate('Y-m-d H:i:s'),
], ['entity_id = ?' => $entityId, 'status IN (?)' => ['failed', 'retrying']]) === 1;
}
}
@@ -0,0 +1,107 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Model\Sync;
use Magento\Framework\App\ResourceConnection;
class ShipmentSyncRepository
{
private string $table;
public function __construct(private readonly ResourceConnection $resource)
{
$this->table = $resource->getTableName('esun_lingxing_shipment_sync');
}
public function enqueue(array $payload, string $requestId = ''): void
{
$connection = $this->resource->getConnection();
$externalKey = (string)$payload['external_key'];
$existing = $connection->fetchRow($connection->select()->from($this->table)
->where('external_key = ?', $externalKey)->limit(1));
$data = [
'global_order_no' => (string)($payload['global_order_no'] ?? ''),
'wo_id' => !empty($payload['wo_id']) ? (int)$payload['wo_id'] : null,
'wo_number' => (string)$payload['wo_number'],
'package_no' => (string)($payload['package_no'] ?? '') ?: null,
'tracking_no' => implode(',', array_values(array_filter(array_column($payload['tracks'] ?? [], 'number')))),
'request_id' => $requestId ?: null,
'payload_json' => (string)json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR),
'updated_at' => gmdate('Y-m-d H:i:s'),
];
if (!$existing) {
$data += [
'external_key' => $externalKey,
'status' => 'pending',
'created_at' => gmdate('Y-m-d H:i:s'),
];
$connection->insert($this->table, $data);
return;
}
if ((string)$existing['status'] !== 'success') {
$connection->update($this->table, $data, ['entity_id = ?' => (int)$existing['entity_id']]);
}
}
public function getDue(int $limit): array
{
$connection = $this->resource->getConnection();
return $connection->fetchAll($connection->select()->from($this->table)
->where('status IN (?)', ['pending', 'retrying'])
->where('next_retry_at IS NULL OR next_retry_at <= ?', gmdate('Y-m-d H:i:s'))
->order('entity_id ASC')->limit($limit));
}
public function claim(int $entityId): bool
{
return $this->resource->getConnection()->update($this->table, [
'status' => 'processing',
'last_attempt_at' => gmdate('Y-m-d H:i:s'),
], ['entity_id = ?' => $entityId, 'status IN (?)' => ['pending', 'retrying']]) === 1;
}
public function markSuccess(int $entityId, int $orderId, string $incrementId, int $shipmentId): void
{
$now = gmdate('Y-m-d H:i:s');
$this->resource->getConnection()->update($this->table, [
'order_id' => $orderId,
'increment_id' => $incrementId,
'shipment_id' => $shipmentId,
'status' => 'success',
'last_error_code' => null,
'last_error_message' => null,
'next_retry_at' => null,
'synced_at' => $now,
'updated_at' => $now,
], ['entity_id = ?' => $entityId]);
}
public function markFailure(int $entityId, int $attemptCount, int $maxAttempts, string $code, string $message): string
{
$attemptCount++;
$status = $attemptCount >= $maxAttempts ? 'failed' : 'retrying';
$delay = min(3600, 30 * (2 ** min(7, max(0, $attemptCount - 1))));
$this->resource->getConnection()->update($this->table, [
'status' => $status,
'attempt_count' => $attemptCount,
'next_retry_at' => $status === 'retrying' ? gmdate('Y-m-d H:i:s', time() + $delay) : null,
'last_error_code' => $code ?: null,
'last_error_message' => mb_substr($message, 0, 65535),
'updated_at' => gmdate('Y-m-d H:i:s'),
], ['entity_id = ?' => $entityId]);
return $status;
}
public function retry(int $entityId): bool
{
return $this->resource->getConnection()->update($this->table, [
'status' => 'pending',
'attempt_count' => 0,
'next_retry_at' => null,
'last_error_code' => null,
'last_error_message' => null,
'updated_at' => gmdate('Y-m-d H:i:s'),
], ['entity_id = ?' => $entityId, 'status IN (?)' => ['failed', 'retrying']]) === 1;
}
}
@@ -0,0 +1,93 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Model\Warehouse;
use Esun\LingxingErp\Model\Api\ApiException;
use Esun\LingxingErp\Model\Api\Client;
use Esun\LingxingErp\Model\Api\Endpoint;
use Esun\LingxingErp\Model\Sync\LogWriter;
class WarehouseFetcher
{
/**
* Lingxing API documentation:
* https://apidoc.lingxing.com/#/docs/Warehouse/WarehouseLists
*/
private const PAGE_SIZE = 1000;
private const WAREHOUSE_TYPE = 3;
public function __construct(
private readonly Client $client,
private readonly LogWriter $logWriter
) {
}
/** @return array<int, array<string, mixed>> */
public function fetchAll(): array
{
$warehouses = [];
$type = self::WAREHOUSE_TYPE;
$offset = 0;
do {
$request = [
'type' => $type,
'is_delete' => '0,1',
'offset' => $offset,
'length' => self::PAGE_SIZE,
];
$started = microtime(true);
$response = [];
try {
$response = $this->client->post(Endpoint::WAREHOUSE_LIST, $request);
$rows = $response['data'] ?? null;
if (!is_array($rows)) {
throw new \RuntimeException('Lingxing warehouse response is missing data.');
}
$this->logWriter->write([
'direction' => 'pull',
'operation' => 'warehouse_sync',
'entity_type' => 'warehouse',
'external_id' => (string)$type,
'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),
]);
} catch (\Throwable $exception) {
$apiResponse = $exception instanceof ApiException ? $exception->getResponse() : $response;
$this->logWriter->write([
'direction' => 'pull',
'operation' => 'warehouse_sync',
'entity_type' => 'warehouse',
'external_id' => (string)$type,
'status' => 'failed',
'attempt_number' => 1,
'error_code' => $exception instanceof ApiException
? $exception->getErrorCode()
: (string)$exception->getCode(),
'error_message' => $exception->getMessage(),
'request_id' => (string)($apiResponse['request_id'] ?? ''),
'request_payload' => $request,
'response_payload' => $apiResponse,
'duration_ms' => (int)round((microtime(true) - $started) * 1000),
]);
throw $exception;
}
foreach ($rows as $row) {
if (!is_array($row) || (int)($row['wid'] ?? 0) <= 0) {
continue;
}
$row['type'] = (int)($row['type'] ?? $type);
$warehouses[(int)$row['wid']] = $row;
}
$received = count($rows);
$offset += $received;
$total = max(0, (int)($response['total'] ?? $offset));
} while ($received > 0 && $offset < $total);
return array_values($warehouses);
}
}
@@ -0,0 +1,159 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Model\Warehouse;
use Magento\Framework\App\ResourceConnection;
class WarehouseRepository
{
public function __construct(private readonly ResourceConnection $resource)
{
}
/** @param array<string, mixed> $warehouse */
public function saveMetadata(array $warehouse): void
{
$now = gmdate('Y-m-d H:i:s');
$data = [
'wid' => (int)$warehouse['wid'],
'warehouse_name' => trim((string)($warehouse['name'] ?? '')),
'warehouse_type' => (int)($warehouse['type'] ?? 0),
'country_code' => trim((string)($warehouse['country_code'] ?? '')) ?: null,
'third_party_code' => trim((string)($warehouse['t_warehouse_code'] ?? '')) ?: null,
'third_party_name' => trim((string)($warehouse['t_warehouse_name'] ?? '')) ?: null,
'lingxing_status' => trim((string)($warehouse['t_status'] ?? '')) === ''
? 1
: (int)$warehouse['t_status'],
'is_deleted' => (int)($warehouse['is_delete'] ?? 0),
'last_synced_at' => $now,
'updated_at' => $now,
];
$this->resource->getConnection()->insertOnDuplicate(
$this->resource->getTableName('esun_lingxing_warehouse'),
$data,
array_keys(array_diff_key($data, ['wid' => true]))
);
}
public function assignSource(string $sourceCode, ?int $wid): void
{
$sourceCode = trim($sourceCode);
if ($sourceCode === '') {
throw new \InvalidArgumentException('Magento Source code is required.');
}
$connection = $this->resource->getConnection();
$table = $this->resource->getTableName('esun_lingxing_warehouse');
$connection->beginTransaction();
try {
$connection->update($table, ['source_code' => null], ['source_code = ?' => $sourceCode]);
if ($wid !== null) {
if ($wid <= 0) {
throw new \InvalidArgumentException('Lingxing warehouse ID must be positive.');
}
$updated = $connection->update(
$table,
['source_code' => $sourceCode],
['wid = ?' => $wid, 'warehouse_type = ?' => 3, 'is_deleted = ?' => 0]
);
if ($updated !== 1) {
throw new \RuntimeException(sprintf(
'Lingxing type 3 warehouse WID %d is not available. Synchronize warehouses first.',
$wid
));
}
}
$connection->commit();
} catch (\Throwable $exception) {
$connection->rollBack();
throw $exception;
}
}
public function getWidForSource(string $sourceCode): ?int
{
$connection = $this->resource->getConnection();
$value = $connection->fetchOne($connection->select()
->from($this->resource->getTableName('esun_lingxing_warehouse'), ['wid'])
->where('source_code = ?', $sourceCode)
->where('warehouse_type = ?', 3)
->limit(1));
return $value === false ? null : (int)$value;
}
/** @return array<int, array<string, mixed>> */
public function getInventoryTargets(): array
{
$connection = $this->resource->getConnection();
$warehouse = $this->resource->getTableName('esun_lingxing_warehouse');
$links = $this->resource->getTableName('inventory_source_stock_link');
return $connection->fetchAll($connection->select()
->distinct()
->from(['warehouse' => $warehouse])
->joinInner(['source_stock' => $links], 'source_stock.source_code = warehouse.source_code', [])
->where('warehouse.warehouse_type = ?', 3)
->where('warehouse.is_deleted = ?', 0)
->where('warehouse.lingxing_status = ?', 1)
->order('warehouse.wid ASC'));
}
/** @return int[] */
public function getWebsiteIdsForSource(string $sourceCode): array
{
$connection = $this->resource->getConnection();
$channelCondition = $connection->quoteInto(
'channel.stock_id = source_stock.stock_id AND channel.type = ?',
'website'
);
$select = $connection->select()
->distinct()
->from(['source_stock' => $this->resource->getTableName('inventory_source_stock_link')], [])
->joinInner(
['channel' => $this->resource->getTableName('inventory_stock_sales_channel')],
$channelCondition,
[]
)
->joinInner(
['website' => $this->resource->getTableName('store_website')],
'website.code = channel.code',
['website_id']
)
->where('source_stock.source_code = ?', $sourceCode)
->where('website.website_id > ?', 0);
return array_map('intval', $connection->fetchCol($select));
}
public function findSourceCodeByWid(int $wid): ?string
{
if ($wid <= 0) {
return null;
}
$connection = $this->resource->getConnection();
$value = $connection->fetchOne($connection->select()
->from($this->resource->getTableName('esun_lingxing_warehouse'), ['source_code'])
->where('wid = ?', $wid)
->where('is_deleted = ?', 0)
->limit(1));
return $value === false || trim((string)$value) === '' ? null : (string)$value;
}
/** @return string[] */
public function getExistingSourceItemSkus(string $sourceCode): array
{
$connection = $this->resource->getConnection();
return array_map('strval', $connection->fetchCol($connection->select()
->from($this->resource->getTableName('inventory_source_item'), ['sku'])
->where('source_code = ?', $sourceCode)));
}
public function markInventorySynchronized(int $wid): void
{
$now = gmdate('Y-m-d H:i:s');
$this->resource->getConnection()->update(
$this->resource->getTableName('esun_lingxing_warehouse'),
['last_inventory_synced_at' => $now, 'updated_at' => $now],
['wid = ?' => $wid]
);
}
}
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Model\Warehouse;
use Magento\Framework\Lock\LockManagerInterface;
class WarehouseSynchronizer
{
private const LOCK_NAME = 'esun_lingxing_warehouse_sync';
public function __construct(
private readonly WarehouseFetcher $fetcher,
private readonly WarehouseRepository $repository,
private readonly LockManagerInterface $lockManager
) {
}
/** @return array{warehouses:int} */
public function synchronize(): array
{
if (!$this->lockManager->lock(self::LOCK_NAME, 0)) {
throw new \RuntimeException('Warehouse synchronization is already running.');
}
try {
$warehouses = $this->fetcher->fetchAll();
foreach ($warehouses as $warehouse) {
$this->repository->saveMetadata($warehouse);
}
return ['warehouses' => count($warehouses)];
} finally {
$this->lockManager->unlock(self::LOCK_NAME);
}
}
}
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Observer;
use Esun\LingxingErp\Model\Config;
use Esun\LingxingErp\Model\Sync\OrderSyncRepository;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Psr\Log\LoggerInterface;
class EnqueueOrder implements ObserverInterface
{
public function __construct(
private readonly Config $config,
private readonly OrderSyncRepository $repository,
private readonly LoggerInterface $logger
) {
}
public function execute(Observer $observer): void
{
if (!$this->config->isEnabled()) {
return;
}
$order = $observer->getEvent()->getOrder();
if (!$order || !in_array((string)$order->getStatus(), $this->config->getEligibleStatuses(), true)) {
return;
}
try {
$this->repository->enqueue($order);
} catch (\Throwable $exception) {
$this->logger->error('Unable to enqueue Magento order for Lingxing.', [
'order_id' => $order->getEntityId(),
'exception' => $exception,
]);
}
}
}
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Observer;
use Esun\LingxingErp\Model\Order\CancellationSourceResolver;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Sales\Model\Order;
class RecordOrderCancellation implements ObserverInterface
{
public function __construct(private readonly CancellationSourceResolver $sourceResolver)
{
}
public function execute(Observer $observer): void
{
$order = $observer->getEvent()->getOrder();
if (!$order instanceof Order) {
return;
}
$source = $this->sourceResolver->resolve();
$order->addCommentToStatusHistory($this->sourceResolver->getComment($source));
}
}
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Observer;
use Esun\LingxingErp\Model\Warehouse\WarehouseRepository;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\InventoryApi\Api\Data\SourceInterface;
class SaveSourceWarehouseMapping implements ObserverInterface
{
public function __construct(private readonly WarehouseRepository $warehouseRepository)
{
}
public function execute(Observer $observer): void
{
$request = $observer->getData('request');
$source = $observer->getData('source');
if (!$source instanceof SourceInterface || !$request instanceof RequestInterface) {
return;
}
$general = $request->getParam('general');
if (!is_array($general) || !array_key_exists('lingxing_wid', $general)) {
return;
}
$value = trim((string)$general['lingxing_wid']);
$this->warehouseRepository->assignSource(
(string)$source->getSourceCode(),
$value === '' ? null : (int)$value
);
}
}
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Plugin\InventoryAdminUi;
use Esun\LingxingErp\Model\Warehouse\WarehouseRepository;
use Magento\InventoryAdminUi\Ui\DataProvider\SourceDataProvider;
class SourceDataProviderPlugin
{
public function __construct(private readonly WarehouseRepository $warehouseRepository)
{
}
/** @param array<string, mixed> $result */
public function afterGetData(SourceDataProvider $subject, array $result): array
{
if ($subject->getName() !== SourceDataProvider::SOURCE_FORM_NAME) {
return $result;
}
foreach ($result as $sourceCode => &$sourceData) {
if ($sourceCode === '' || !is_array($sourceData)) {
continue;
}
if (!isset($sourceData['general']) || !is_array($sourceData['general'])) {
continue;
}
if (array_key_exists('lingxing_wid', $sourceData['general'])) {
continue;
}
$wid = $this->warehouseRepository->getWidForSource((string)$sourceCode);
$sourceData['general']['lingxing_wid'] = $wid === null ? '' : (string)$wid;
}
unset($sourceData);
return $result;
}
}
+69
View File
@@ -0,0 +1,69 @@
# Esun_LingxingErp
Lingxing warehouse integration uses these official endpoints:
- Warehouse list: `POST /erp/sc/data/local_inventory/warehouse`
- https://apidoc.lingxing.com/#/docs/Warehouse/WarehouseLists
- Warehouse inventory details: `POST /erp/sc/routing/data/local_inventory/inventoryDetails`
- https://apidoc.lingxing.com/#/docs/Warehouse/InventoryDetails
`Sync Warehouses` uses the active platform `10009` records already cached under
**Lingxing ERP > Stores** to select only the required Lingxing warehouses:
- Store `Magento` -> warehouse `US Stock`
- Store `Magento-UK` -> warehouse `UK Stock`
- Store `Magento-EU` -> warehouse `EU Stock`
- Store `Magento-AU` -> warehouse `AU Stock`
No other Lingxing warehouses are persisted or turned into Magento Sources. Each
selected warehouse is represented by a Source with the stable code `lingxing_{wid}`.
Assign those Sources to Magento Stocks before running `Sync Inventory`. Inventory
quantity is sourced from Lingxing `product_valid_num`.
Magento-to-Lingxing order export and Lingxing-to-Magento shipment import.
## Scope
- Enqueues Magento orders when they enter a configured status (default: `processing`).
- Creates Lingxing custom-platform orders using Magento `increment_id` as the idempotency key.
- Queues `/basicOpen/wmsOrder/cancel` when a synchronized Magento order is canceled, records whether the cancellation came from the customer, a scheduled task, an administrator, or another system process, and retries failed cancellation submissions without blocking Magento cancellation.
- Pulls completed Lingxing sales outbound orders every three minutes.
- Creates one Magento shipment per Lingxing `wo_number`.
- Creates package-level shipments only when Lingxing supplies package-level item quantities; otherwise attaches all package tracking numbers to one shipment.
- Stores current order/shipment synchronization status and a sanitized attempt history.
- Persists Lingxing stores locally and refreshes them only when an administrator requests it.
- Pulls Lingxing PairListV2 mappings once per day for each configured Website and writes the returned local `sku` to the Website-scoped product `erp_sku` attribute.
- Sends each Website's Magento SKUs as `msku` together with its configured `platform_codes` and `store_ids` when querying PairListV2.
- Provides store, order, shipment and log grids plus retry actions under **Esun > Lingxing ERP**.
- Keeps full sanitized payloads for failed/retrying logs for 90 days. Successful/ignored logs contain compact hashes and counts only and are retained for 14 days; both windows are configurable. The log grid defaults to failed/retrying rows until a status filter is selected.
- Provides detail pages for order, shipment and attempt-log records with sanitized request and response payloads.
The `erp_sku` attribute is not exposed to storefront search. ERP SKU uniqueness is enforced within each Magento Website, while the same ERP SKU may be used by different Websites.
## Configuration
Configure under **Stores > Configuration > Esun > Lingxing ERP**:
- API Base URL
- App ID
- App Secret (encrypted and marked sensitive)
- a Lingxing store mapping selected separately at each Magento Website scope; options are read from the local store table
- optional warehouse and logistics type (both must be supplied together)
- Magento order statuses eligible for export
Do not put credentials in source code or logs. Production must whitelist the Magento server's public IP in Lingxing.
After saving the API credentials, open **Esun > Lingxing ERP > Stores** and click **Sync Stores** once. Repeat the manual synchronization only when the Lingxing store list changes. The system configuration page never calls Lingxing directly. Store API failures are recorded in **Synchronization Logs**.
Product ERP SKUs synchronize daily at 02:17 in the Magento cron timezone. Administrators can also run the synchronization immediately from **Esun > Lingxing ERP > Stores**. The Website-scoped product `erp_sku` attribute is the sole source of truth; no separate mapping table is maintained. PairListV2 request and response payloads are recorded under the `sku_pair_lookup` operation.
## Deployment
```bash
php bin/magento module:enable Esun_LingxingErp
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento cache:flush
```
Magento cron must be installed and running. API synchronization remains disabled until the configuration flag is enabled.
@@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Setup\Patch\Data;
use Esun\LingxingErp\Model\Product\Attribute\Backend\WebsiteUnique;
use Magento\Catalog\Model\Product;
use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;
class AddErpSkuProductAttribute implements DataPatchInterface
{
public function __construct(
private readonly ModuleDataSetupInterface $moduleDataSetup,
private readonly EavSetupFactory $eavSetupFactory
) {
}
public function apply(): self
{
$this->moduleDataSetup->getConnection()->startSetup();
$eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]);
$eavSetup->addAttribute(Product::ENTITY, 'erp_sku', [
'type' => 'varchar',
'label' => 'Lingxing ERP SKU',
'input' => 'text',
'backend' => WebsiteUnique::class,
'required' => false,
'user_defined' => true,
'global' => ScopedAttributeInterface::SCOPE_WEBSITE,
// One Lingxing ERP SKU may be paired with multiple Magento SKUs in the same Website.
'unique' => false,
'visible' => true,
'searchable' => false,
'filterable' => false,
'filterable_in_search' => false,
'visible_in_advanced_search' => false,
'visible_on_front' => false,
'used_for_sort_by' => false,
'used_in_product_listing' => true,
'is_used_in_grid' => true,
'is_visible_in_grid' => true,
'is_filterable_in_grid' => true,
'group' => 'General',
'sort_order' => 95,
]);
$this->moduleDataSetup->getConnection()->endSetup();
return $this;
}
public static function getDependencies(): array
{
return [];
}
public function getAliases(): array
{
return [];
}
}
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Setup\Patch\Data;
use Esun\LingxingErp\Model\Api\Endpoint;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;
class BackfillLogApiPath implements DataPatchInterface
{
public function __construct(private readonly ModuleDataSetupInterface $moduleDataSetup)
{
}
public function apply(): self
{
$connection = $this->moduleDataSetup->getConnection();
$table = $this->moduleDataSetup->getTable('esun_lingxing_sync_log');
$connection->startSetup();
foreach ([
'store_sync' => Endpoint::STORE_LIST,
'order_create' => Endpoint::ORDER_CREATE,
'sku_pair_lookup' => Endpoint::PAIR_LIST,
'shipment_pull' => Endpoint::WMS_ORDER_LIST,
] as $operation => $apiPath) {
$connection->update(
$table,
['api_path' => $apiPath],
['operation = ?' => $operation, 'api_path IS NULL']
);
}
$connection->endSetup();
return $this;
}
public static function getDependencies(): array
{
return [];
}
public function getAliases(): array
{
return [];
}
}
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Cron;
use Esun\LingxingErp\Cron\CleanSyncLogs;
use Esun\LingxingErp\Model\Config;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\DB\Adapter\AdapterInterface;
use PHPUnit\Framework\TestCase;
class CleanSyncLogsTest extends TestCase
{
public function testDeletesCompactAndErrorLogsUsingSeparateRetentionWindows(): void
{
$config = $this->createMock(Config::class);
$config->method('getSuccessLogRetentionDays')->willReturn(14);
$config->method('getErrorLogRetentionDays')->willReturn(90);
$calls = [];
$connection = $this->createMock(AdapterInterface::class);
$connection->expects(self::exactly(2))->method('delete')->willReturnCallback(
static function (string $table, array $where) use (&$calls): int {
$calls[] = [$table, $where];
return 2;
}
);
$resource = $this->createMock(ResourceConnection::class);
$resource->method('getConnection')->willReturn($connection);
$resource->method('getTableName')->willReturnArgument(0);
self::assertSame(4, (new CleanSyncLogs($config, $resource))->execute());
self::assertSame(['success', 'ignored'], $calls[0][1]['status IN (?)']);
self::assertArrayHasKey('created_at < ?', $calls[0][1]);
self::assertSame(['success', 'ignored'], $calls[1][1]['status NOT IN (?)']);
self::assertArrayHasKey('created_at < ?', $calls[1][1]);
}
}
@@ -0,0 +1,115 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Cron;
use Esun\LingxingErp\Cron\ProcessOrders;
use Esun\LingxingErp\Model\Api\ApiException;
use Esun\LingxingErp\Model\Config;
use Esun\LingxingErp\Model\Order\OrderExporter;
use Esun\LingxingErp\Model\Order\OrderPayloadBuilder;
use Esun\LingxingErp\Model\Sync\LogWriter;
use Esun\LingxingErp\Model\Sync\OrderSyncRepository;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Order;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
class ProcessOrdersTest extends TestCase
{
public function testCanceledOrderIsNeverExported(): void
{
$row = [
'entity_id' => 8,
'order_id' => 13,
'increment_id' => '100000013',
'attempt_count' => 0,
];
$config = $this->createMock(Config::class);
$config->method('isEnabled')->willReturn(true);
$config->method('getOrderBatchSize')->willReturn(10);
$syncRepository = $this->createMock(OrderSyncRepository::class);
$syncRepository->method('getDue')->willReturn([$row]);
$syncRepository->method('claim')->willReturn(true);
$syncRepository->expects(self::once())->method('markCreationCanceled')->with(8);
$order = $this->createMock(OrderInterface::class);
$order->method('getState')->willReturn(Order::STATE_CANCELED);
$orderRepository = $this->createMock(OrderRepositoryInterface::class);
$orderRepository->method('get')->willReturn($order);
$payloadBuilder = $this->createMock(OrderPayloadBuilder::class);
$payloadBuilder->expects(self::never())->method('build');
$exporter = $this->createMock(OrderExporter::class);
$exporter->expects(self::never())->method('export');
$logWriter = $this->createMock(LogWriter::class);
$logWriter->expects(self::once())->method('write')->with(self::callback(
static fn (array $data): bool => $data['status'] === 'ignored'
));
(new ProcessOrders(
$config,
$syncRepository,
$orderRepository,
$payloadBuilder,
$exporter,
$logWriter,
$this->createMock(LoggerInterface::class)
))->execute();
}
public function testFailedAttemptStillRecordsRequestPayload(): void
{
$row = [
'entity_id' => 7,
'order_id' => 12,
'increment_id' => '100000012',
'attempt_count' => 0,
'global_order_no' => null,
];
$payload = ['orders' => [['platform_order_no' => '100000012']]];
$config = $this->createMock(Config::class);
$config->method('isEnabled')->willReturn(true);
$config->method('getOrderBatchSize')->willReturn(10);
$config->method('getOrderMaxAttempts')->willReturn(8);
$syncRepository = $this->createMock(OrderSyncRepository::class);
$syncRepository->method('getDue')->willReturn([$row]);
$syncRepository->method('claim')->willReturn(true);
$syncRepository->method('markFailure')->willReturn('failed');
$order = $this->createMock(OrderInterface::class);
$orderRepository = $this->createMock(OrderRepositoryInterface::class);
$orderRepository->method('get')->willReturn($order);
$payloadBuilder = $this->createMock(OrderPayloadBuilder::class);
$payloadBuilder->expects(self::once())->method('build')->with($order)->willReturn($payload);
$exporter = $this->createMock(OrderExporter::class);
$exporter->expects(self::once())
->method('export')
->with($order, $payload)
->willThrowException(new ApiException('SKU missing', 'order_not_created', ['code' => 0]));
$logWriter = $this->createMock(LogWriter::class);
$logWriter->expects(self::once())->method('write')->with(self::callback(
static fn(array $data): bool => $data['status'] === 'failed'
&& $data['request_payload'] === $payload
&& $data['response_payload'] === ['code' => 0]
));
$cron = new ProcessOrders(
$config,
$syncRepository,
$orderRepository,
$payloadBuilder,
$exporter,
$logWriter,
$this->createMock(LoggerInterface::class)
);
$cron->execute();
}
}
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Model\Api;
use Esun\LingxingErp\Model\Api\Signer;
use PHPUnit\Framework\TestCase;
class SignerTest extends TestCase
{
public function testMatchesLingxingPhpSdkSerializationAndEncryption(): void
{
$parameters = [
'z' => null,
'items' => [['sku' => '测试/1', 'qty' => 2, 'drop' => null]],
'empty' => '',
'bool' => true,
'access_token' => 'token',
'app_key' => 'ak_test123456789',
'timestamp' => 1720408272,
];
self::assertSame(
'mR8XKYkL8QUYDIJmM75XAl3JGPuuDvzjsyr6LZ5nWocwCpgLHg5dzZDMNuiTX/Va',
(new Signer())->sign($parameters, 'ak_test123456789')
);
}
}
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Model\Api;
use Esun\LingxingErp\Model\Api\TokenProvider;
use Esun\LingxingErp\Model\Config;
use Magento\Framework\App\CacheInterface;
use Magento\Framework\HTTP\Client\Curl;
use Magento\Framework\HTTP\Client\CurlFactory;
use Magento\Framework\Lock\LockManagerInterface;
use PHPUnit\Framework\TestCase;
class TokenProviderTest extends TestCase
{
public function testAcceptsDocumentedHttpStyleBusinessCode(): void
{
$config = $this->createMock(Config::class);
$config->method('getApiBaseUrl')->willReturn('https://example.test');
$config->method('getAppId')->willReturn('app-id');
$config->method('getAppSecret')->willReturn('app-secret');
$cache = $this->createMock(CacheInterface::class);
$cache->method('load')->willReturn(false);
$cache->expects(self::once())->method('save');
$curl = $this->createMock(Curl::class);
$curl->method('getStatus')->willReturn(200);
$curl->method('getBody')->willReturn((string)json_encode([
'code' => '200',
'msg' => 'OK',
'data' => ['access_token' => 'token-value', 'expires_in' => 3600],
]));
$curlFactory = $this->createMock(CurlFactory::class);
$curlFactory->method('create')->willReturn($curl);
$lock = $this->createMock(LockManagerInterface::class);
$lock->method('lock')->willReturn(true);
$lock->expects(self::once())->method('unlock');
$provider = new TokenProvider($config, $cache, $curlFactory, $lock);
self::assertSame('token-value', $provider->getAccessToken());
}
}
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Model;
use Esun\LingxingErp\Model\Config;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Encryption\EncryptorInterface;
use Magento\Store\Model\ScopeInterface;
use PHPUnit\Framework\TestCase;
class ConfigTest extends TestCase
{
public function testStoreMappingIsResolvedPerWebsite(): void
{
$scopeConfig = $this->createMock(ScopeConfigInterface::class);
$scopeConfig->method('getValue')->willReturnCallback(
static function (string $path, string $scope = 'default', $scopeCode = null): string {
if ($path !== 'esun_lingxing/general/store_mapping' || $scope !== ScopeInterface::SCOPE_WEBSITE) {
return '';
}
return (int)$scopeCode === 1 ? '10009|STORE-US' : '10002|STORE-EU';
}
);
$config = new Config($scopeConfig, $this->createMock(EncryptorInterface::class));
self::assertSame(10009, $config->getPlatformCode(1));
self::assertSame('STORE-US', $config->getLingxingStoreId(1));
self::assertSame(10002, $config->getPlatformCode(2));
self::assertSame('STORE-EU', $config->getLingxingStoreId(2));
}
public function testSkuSyncPageSizeIsBounded(): void
{
$scopeConfig = $this->createMock(ScopeConfigInterface::class);
$scopeConfig->method('getValue')->with('esun_lingxing/sku_sync/page_size')->willReturn('500');
$config = new Config($scopeConfig, $this->createMock(EncryptorInterface::class));
self::assertSame(200, $config->getSkuSyncPageSize());
}
}
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Model\Inventory;
use Esun\LingxingErp\Model\Api\Client;
use Esun\LingxingErp\Model\Api\Endpoint;
use Esun\LingxingErp\Model\Inventory\InventoryFetcher;
use Esun\LingxingErp\Model\Sync\LogWriter;
use PHPUnit\Framework\TestCase;
class InventoryFetcherTest extends TestCase
{
public function testUsesProductInventoryEndpointAndWarehouseFilter(): void
{
$client = $this->createMock(Client::class);
$client->expects(self::once())
->method('post')
->with(Endpoint::INVENTORY_DETAILS, [
'wid' => '46133',
'offset' => 0,
'length' => 800,
])
->willReturn([
'code' => 0,
'data' => [['wid' => 46133, 'sku' => 'ERP-1', 'product_valid_num' => 12]],
'total' => 1,
]);
$logWriter = $this->createMock(LogWriter::class);
$logWriter->expects(self::once())->method('write');
$result = (new InventoryFetcher($client, $logWriter))->fetchAll(46133);
self::assertSame('ERP-1', $result[0]['sku']);
self::assertSame(12, $result[0]['product_valid_num']);
}
}
@@ -0,0 +1,147 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Model\Inventory;
use Esun\LingxingErp\Model\Inventory\InventoryFetcher;
use Esun\LingxingErp\Model\Inventory\InventorySynchronizer;
use Esun\LingxingErp\Model\Sku\ProductErpSkuRepository;
use Esun\LingxingErp\Model\Sync\LogWriter;
use Esun\LingxingErp\Model\Warehouse\WarehouseRepository;
use Magento\Framework\Lock\LockManagerInterface;
use Magento\InventoryApi\Api\Data\SourceItemInterface;
use Magento\InventoryApi\Api\Data\SourceItemInterfaceFactory;
use Magento\InventoryApi\Api\SourceItemsSaveInterface;
use PHPUnit\Framework\TestCase;
class InventorySynchronizerTest extends TestCase
{
public function testFullErpQuantityIsWrittenToEveryPairedMagentoSku(): void
{
$warehouseRepository = $this->createMock(WarehouseRepository::class);
$warehouseRepository->method('getWebsiteIdsForSource')->with('default')->willReturn([3]);
$warehouseRepository->method('getExistingSourceItemSkus')->with('default')->willReturn([]);
$fetcher = $this->createMock(InventoryFetcher::class);
$fetcher->method('fetchAll')->with(10)->willReturn([
['sku' => 'ERP-1', 'product_valid_num' => 30],
]);
$productRepository = $this->createMock(ProductErpSkuRepository::class);
$productRepository->method('findMskusByErpSku')->with(3, 'ERP-1')
->willReturn(['MAGENTO-A', 'MAGENTO-B']);
$productRepository->method('getWebsiteProductSkusWithErpSku')->with(3)
->willReturn(['MAGENTO-A', 'MAGENTO-B']);
$itemA = $this->createMock(SourceItemInterface::class);
$itemA->expects(self::once())->method('setSourceCode')->with('default');
$itemA->expects(self::once())->method('setSku')->with('MAGENTO-A');
$itemA->expects(self::once())->method('setQuantity')->with(30.0);
$itemA->expects(self::once())->method('setStatus')->with(SourceItemInterface::STATUS_IN_STOCK);
$itemB = $this->createMock(SourceItemInterface::class);
$itemB->expects(self::once())->method('setSourceCode')->with('default');
$itemB->expects(self::once())->method('setSku')->with('MAGENTO-B');
$itemB->expects(self::once())->method('setQuantity')->with(30.0);
$itemB->expects(self::once())->method('setStatus')->with(SourceItemInterface::STATUS_IN_STOCK);
$itemFactory = $this->createMock(SourceItemInterfaceFactory::class);
$itemFactory->expects(self::exactly(2))->method('create')->willReturn($itemA, $itemB);
$sourceItemsSave = $this->createMock(SourceItemsSaveInterface::class);
$sourceItemsSave->expects(self::once())->method('execute')->with([$itemA, $itemB]);
$synchronizer = new InventorySynchronizer(
$warehouseRepository,
$fetcher,
$productRepository,
$itemFactory,
$sourceItemsSave,
$this->createMock(LogWriter::class),
$this->createMock(LockManagerInterface::class)
);
$method = new \ReflectionMethod($synchronizer, 'synchronizeWarehouse');
self::assertSame(
[
'items' => 2,
'unmapped' => 0,
'zeroed' => 0,
'preserved_without_erp_sku' => 0,
'unmapped_erp_skus' => [],
],
$method->invoke($synchronizer, ['wid' => 10, 'source_code' => 'default'])
);
}
public function testDoesNotZeroExistingSourceItemsWithoutAnErpSkuMapping(): void
{
$warehouseRepository = $this->createMock(WarehouseRepository::class);
$warehouseRepository->method('getWebsiteIdsForSource')->with('default')->willReturn([3]);
$warehouseRepository->method('getExistingSourceItemSkus')->with('default')->willReturn([
'MAPPED-BUT-MISSING',
'NO-ERP-SKU',
]);
$fetcher = $this->createMock(InventoryFetcher::class);
$fetcher->method('fetchAll')->with(10)->willReturn([
['sku' => 'UNKNOWN-ERP-SKU', 'product_valid_num' => 50],
]);
$productRepository = $this->createMock(ProductErpSkuRepository::class);
$productRepository->method('findMskusByErpSku')->with(3, 'UNKNOWN-ERP-SKU')->willReturn([]);
$productRepository->method('getWebsiteProductSkusWithErpSku')->with(3)
->willReturn(['MAPPED-BUT-MISSING']);
$zeroedItem = $this->createMock(SourceItemInterface::class);
$zeroedItem->expects(self::once())->method('setSourceCode')->with('default');
$zeroedItem->expects(self::once())->method('setSku')->with('MAPPED-BUT-MISSING');
$zeroedItem->expects(self::once())->method('setQuantity')->with(0.0);
$zeroedItem->expects(self::once())->method('setStatus')->with(SourceItemInterface::STATUS_OUT_OF_STOCK);
$itemFactory = $this->createMock(SourceItemInterfaceFactory::class);
$itemFactory->expects(self::once())->method('create')->willReturn($zeroedItem);
$sourceItemsSave = $this->createMock(SourceItemsSaveInterface::class);
$sourceItemsSave->expects(self::once())->method('execute')->with([$zeroedItem]);
$synchronizer = new InventorySynchronizer(
$warehouseRepository,
$fetcher,
$productRepository,
$itemFactory,
$sourceItemsSave,
$this->createMock(LogWriter::class),
$this->createMock(LockManagerInterface::class)
);
$method = new \ReflectionMethod($synchronizer, 'synchronizeWarehouse');
self::assertSame(
[
'items' => 1,
'unmapped' => 1,
'zeroed' => 1,
'preserved_without_erp_sku' => 1,
'unmapped_erp_skus' => ['UNKNOWN-ERP-SKU'],
],
$method->invoke($synchronizer, ['wid' => 10, 'source_code' => 'default'])
);
}
public function testResolvesEveryMagentoSkuPairedToAnErpSku(): void
{
$productRepository = $this->createMock(ProductErpSkuRepository::class);
$productRepository->expects(self::exactly(2))
->method('findMskusByErpSku')
->willReturnMap([
[3, 'ERP-1', ['MAGENTO-A', 'MAGENTO-B']],
[8, 'ERP-1', ['MAGENTO-B', 'MAGENTO-C']],
]);
$synchronizer = new InventorySynchronizer(
$this->createMock(WarehouseRepository::class),
$this->createMock(InventoryFetcher::class),
$productRepository,
$this->createMock(SourceItemInterfaceFactory::class),
$this->createMock(SourceItemsSaveInterface::class),
$this->createMock(LogWriter::class),
$this->createMock(LockManagerInterface::class)
);
$method = new \ReflectionMethod($synchronizer, 'resolveMagentoSkus');
self::assertSame(
['MAGENTO-A', 'MAGENTO-B', 'MAGENTO-C'],
$method->invoke($synchronizer, [3, 8], 'ERP-1')
);
}
}
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Model\Order;
use Esun\LingxingErp\Model\Order\CancellationSourceResolver;
use Magento\Framework\App\Request\Http;
use Magento\Framework\App\State;
use PHPUnit\Framework\TestCase;
class CancellationSourceResolverTest extends TestCase
{
public function testIdentifiesCustomerCancellationRoute(): void
{
$state = $this->createMock(State::class);
$state->method('getAreaCode')->willReturn('frontend');
$request = $this->createMock(Http::class);
$request->method('getFullActionName')->willReturn('esun_customer_order_cancel');
self::assertSame(
CancellationSourceResolver::CUSTOMER,
(new CancellationSourceResolver($state, $request))->resolve()
);
}
public function testCronAreaTakesPriority(): void
{
$state = $this->createMock(State::class);
$state->method('getAreaCode')->willReturn('crontab');
$request = $this->createMock(Http::class);
self::assertSame(
CancellationSourceResolver::SCHEDULED_TASK,
(new CancellationSourceResolver($state, $request))->resolve()
);
}
}
@@ -0,0 +1,79 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Model\Order;
use Esun\LingxingErp\Model\Config;
use Esun\LingxingErp\Model\Order\OrderPayloadBuilder;
use Magento\Sales\Api\Data\OrderAddressInterface;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\Order\Item;
use Magento\Store\Api\Data\StoreInterface;
use Magento\Store\Model\StoreManagerInterface;
use PHPUnit\Framework\TestCase;
class OrderPayloadBuilderTest extends TestCase
{
public function testAddsAvailableMagentoAddressDataFromExtendedCreateOrderDocument(): void
{
$config = $this->createMock(Config::class);
$config->expects(self::once())->method('assertOrderMappingReady')->with(3);
$config->method('getStockDeductionType')->willReturn(1);
$config->method('getWarehouseId')->with(3)->willReturn('');
$config->method('getPlatformCode')->with(3)->willReturn(10009);
$config->method('getLingxingStoreId')->with(3)->willReturn('STORE-US');
$store = $this->createMock(StoreInterface::class);
$store->method('getWebsiteId')->willReturn(3);
$storeManager = $this->createMock(StoreManagerInterface::class);
$storeManager->method('getStore')->with(16)->willReturn($store);
$address = $this->createMock(OrderAddressInterface::class);
$address->method('getCountryId')->willReturn('US');
$address->method('getFirstname')->willReturn('Shipping');
$address->method('getLastname')->willReturn('Customer');
$address->method('getCompany')->willReturn('Example Inc.');
$address->method('getCity')->willReturn('Austin');
$address->method('getRegion')->willReturn('Texas');
$address->method('getPostcode')->willReturn('78701');
$address->method('getStreet')->willReturn(['100 Main St', 'Suite 20', 'Reception']);
$address->method('getTelephone')->willReturn('+1 555 0100');
$address->method('getEmail')->willReturn('shipping@example.com');
$item = $this->createMock(Item::class);
$item->method('getIsVirtual')->willReturn(false);
$item->method('getSku')->willReturn('MAGENTO-SKU');
$item->method('getQtyOrdered')->willReturn(2.0);
$item->method('getPrice')->willReturn(19.99);
$order = $this->createMock(Order::class);
$order->method('getStoreId')->willReturn(16);
$order->method('getShippingAddress')->willReturn($address);
$order->method('getAllVisibleItems')->willReturn([$item]);
$order->method('getIncrementId')->willReturn('esun100001');
$order->method('getShippingAmount')->willReturn(5.0);
$order->method('getTaxAmount')->willReturn(2.0);
$order->method('getGrandTotal')->willReturn(46.98);
$order->method('getCreatedAt')->willReturn('2026-09-09 00:00:00');
$order->method('getOrderCurrencyCode')->willReturn('USD');
$order->method('getCustomerFirstname')->willReturn('Buyer');
$order->method('getCustomerMiddlename')->willReturn('M');
$order->method('getCustomerLastname')->willReturn('Name');
$order->method('getCustomerEmail')->willReturn('buyer@example.com');
$order->method('getCustomerNote')->willReturn(null);
$payload = (new OrderPayloadBuilder($config, $storeManager))->build($order);
$orderData = $payload['orders'][0];
self::assertSame('100 Main St', $orderData['address_line1']);
self::assertSame('Suite 20', $orderData['address_line2']);
self::assertSame('Reception', $orderData['address_line3']);
self::assertSame('Texas', $orderData['state_or_region']);
self::assertSame('78701', $orderData['postal_code']);
self::assertSame('+1 555 0100', $orderData['receiver_mobile']);
self::assertSame('buyer@example.com', $orderData['buyer_email']);
self::assertSame('Buyer M Name', $orderData['buyer_name']);
self::assertArrayNotHasKey('district', $orderData);
self::assertArrayNotHasKey('doorplate_no', $orderData);
}
}
@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Model\Shipment;
use Esun\LingxingErp\Model\Shipment\FulfillmentNormalizer;
use PHPUnit\Framework\TestCase;
class FulfillmentNormalizerTest extends TestCase
{
public function testMultipleOutboundOrdersRemainIndependentShipments(): void
{
$result = (new FulfillmentNormalizer())->normalize([
'order_number' => 'ERP1',
'wo_number' => 'WO1',
'wid' => 46133,
'tracking_no' => 'TRACK1',
'product_info' => [['sku' => 'SKU1', 'count' => 2]],
]);
self::assertCount(1, $result);
self::assertSame('WO1', $result[0]['external_key']);
self::assertSame([['erp_sku' => 'SKU1', 'quantity' => 2.0]], $result[0]['products']);
self::assertSame('TRACK1', $result[0]['tracks'][0]['number']);
self::assertSame(46133, $result[0]['wid']);
}
public function testPackagesSplitOnlyWhenEveryPackageHasItemQuantities(): void
{
$result = (new FulfillmentNormalizer())->normalize([
'order_number' => 'ERP1',
'wo_number' => 'WO1',
'package_delivered_data' => [
['package_no' => 'P1', 'tracking_no' => 'T1', 'product_info' => [['sku' => 'A', 'count' => 1]]],
['package_no' => 'P2', 'tracking_no' => 'T2', 'product_info' => [['sku' => 'B', 'count' => 1]]],
],
]);
self::assertCount(2, $result);
self::assertSame('WO1|P1', $result[0]['external_key']);
self::assertSame('WO1|P2', $result[1]['external_key']);
}
public function testPackagesWithoutItemQuantitiesBecomeOneShipmentWithMultipleTracks(): void
{
$result = (new FulfillmentNormalizer())->normalize([
'order_number' => 'ERP1',
'wo_number' => 'WO1',
'product_info' => [['sku' => 'A', 'count' => 2]],
'package_delivered_data' => [
['package_no' => 'P1', 'tracking_no' => 'T1'],
['package_no' => 'P2', 'tracking_no' => 'T2'],
],
]);
self::assertCount(1, $result);
self::assertSame(['T1', 'T2'], array_column($result[0]['tracks'], 'number'));
}
}
@@ -0,0 +1,88 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Model\Shipment;
use Esun\LingxingErp\Model\Config;
use Esun\LingxingErp\Model\Shipment\ShipmentImporter;
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\Sales\Model\Order\Item;
use Magento\Store\Model\StoreManagerInterface;
use PHPUnit\Framework\TestCase;
class ShipmentImporterTest extends TestCase
{
public function testErpSkuIsResolvedToMagentoOrderItemSkuWithinWebsite(): void
{
$productErpSkuRepository = $this->createMock(ProductErpSkuRepository::class);
$productErpSkuRepository->expects(self::once())
->method('findMskusByErpSku')
->with(3, 'ERP-001')
->willReturn(['MAGENTO-001']);
$importer = $this->createImporter($productErpSkuRepository);
$item = $this->createOrderItem('MAGENTO-001', 17, 2.0);
$method = new \ReflectionMethod($importer, 'allocateQuantities');
$result = $method->invoke($importer, [$item], [['erp_sku' => 'ERP-001', 'quantity' => 2]], 3);
self::assertSame([17 => 2.0], $result);
}
public function testSharedErpSkuIsAllocatedAcrossMagentoItemsInOrderItemOrder(): void
{
$productErpSkuRepository = $this->createMock(ProductErpSkuRepository::class);
$productErpSkuRepository->expects(self::once())
->method('findMskusByErpSku')
->with(3, 'ERP-SHARED')
->willReturn(['MAGENTO-B', 'MAGENTO-A']);
$importer = $this->createImporter($productErpSkuRepository);
$first = $this->createOrderItem('MAGENTO-A', 17, 1.0);
$second = $this->createOrderItem('MAGENTO-B', 18, 2.0);
$method = new \ReflectionMethod($importer, 'allocateQuantities');
$result = $method->invoke(
$importer,
// Input order is intentionally reversed; allocation must follow the Magento order item IDs.
[$second, $first],
[['erp_sku' => 'ERP-SHARED', 'quantity' => 2]],
3
);
self::assertSame([17 => 1.0, 18 => 1.0], $result);
}
private function createImporter(ProductErpSkuRepository $productErpSkuRepository): ShipmentImporter
{
return new ShipmentImporter(
$this->createMock(OrderSyncRepository::class),
$this->createMock(OrderRepositoryInterface::class),
$this->createMock(ShipmentItemCreationInterfaceFactory::class),
$this->createMock(ShipmentTrackCreationInterfaceFactory::class),
$this->createMock(ShipOrderInterface::class),
$this->createMock(Config::class),
$productErpSkuRepository,
$this->createMock(StoreManagerInterface::class),
$this->createMock(WarehouseRepository::class),
$this->createMock(ShipmentCreationArgumentsInterfaceFactory::class),
$this->createMock(ShipmentCreationArgumentsExtensionInterfaceFactory::class)
);
}
private function createOrderItem(string $sku, int $itemId, float $qtyToShip): Item
{
$item = $this->createMock(Item::class);
$item->method('getIsVirtual')->willReturn(false);
$item->method('getQtyToShip')->willReturn($qtyToShip);
$item->method('getSku')->willReturn($sku);
$item->method('getItemId')->willReturn($itemId);
return $item;
}
}
@@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Model\Shipment;
use Esun\LingxingErp\Model\Api\Client;
use Esun\LingxingErp\Model\Config;
use Esun\LingxingErp\Model\Shipment\FulfillmentNormalizer;
use Esun\LingxingErp\Model\Shipment\ShipmentPuller;
use Esun\LingxingErp\Model\Sync\LogWriter;
use Esun\LingxingErp\Model\Sync\OrderSyncRepository;
use Esun\LingxingErp\Model\Sync\ShipmentSyncRepository;
use Magento\Framework\FlagManager;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
use PHPUnit\Framework\TestCase;
class ShipmentPullerTest extends TestCase
{
public function testLimitsRemoteRequestToTrackablePlatformOrderNumbers(): void
{
$config = $this->createMock(Config::class);
$config->method('getShipmentPageSize')->willReturn(200);
$config->method('getShipmentMaxPages')->willReturn(1);
$orderSyncRepository = $this->createMock(OrderSyncRepository::class);
$orderSyncRepository->method('getTrackablePlatformOrderNos')->willReturn(['100000001', '100000002']);
$client = $this->createMock(Client::class);
$client->expects(self::once())->method('post')->with(
'/erp/sc/routing/wms/order/wmsOrderList',
self::callback(static fn(array $request): bool =>
$request['platform_order_no_arr'] === ['100000001', '100000002']
&& !isset($request['sid_arr']))
)->willReturn(['code' => 0, 'data' => [], 'request_id' => 'request-id']);
$timezone = $this->createMock(TimezoneInterface::class);
$timezone->method('date')->willReturn(new \DateTime('2026-08-26 12:00:00'));
$flagManager = $this->createMock(FlagManager::class);
$flagManager->method('getFlagData')->willReturn(null);
$puller = new ShipmentPuller(
$client,
$config,
$timezone,
$flagManager,
$this->createMock(FulfillmentNormalizer::class),
$orderSyncRepository,
$this->createMock(ShipmentSyncRepository::class),
$this->createMock(LogWriter::class)
);
$puller->pull();
}
}
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Model\Sku;
use Esun\LingxingErp\Model\Api\Client;
use Esun\LingxingErp\Model\Sku\PairFetcher;
use Esun\LingxingErp\Model\Sync\LogWriter;
use PHPUnit\Framework\TestCase;
class PairFetcherTest extends TestCase
{
public function testFetchesAllPagesWithWebsiteStoreFilters(): void
{
$client = $this->createMock(Client::class);
$client->expects(self::exactly(2))->method('post')->willReturnCallback(
static function (string $path, array $request): array {
self::assertSame('/pb/mp/listing/v2/getPairList', $path);
self::assertSame(['10009'], $request['platform_codes']);
self::assertSame(['STORE-1'], $request['store_ids']);
self::assertSame(['M1', 'M2', 'M3'], $request['msku']);
self::assertSame(2, $request['length']);
if ($request['offset'] === 0) {
return ['code' => 0, 'request_id' => 'R1', 'data' => ['list' => [
['msku' => 'M1', 'sku' => 'E1'],
['msku' => 'M2', 'sku' => 'E2'],
]]];
}
self::assertSame(2, $request['offset']);
return ['code' => 0, 'request_id' => 'R2', 'data' => ['list' => [
['msku' => 'M3', 'sku' => 'E3'],
]]];
}
);
$logWriter = $this->createMock(LogWriter::class);
$logWriter->expects(self::exactly(2))->method('write')->with(self::callback(
static fn(array $data): bool => $data['operation'] === 'sku_pair_lookup'
&& $data['status'] === 'success'
&& isset($data['request_payload'], $data['response_payload'])
));
$result = (new PairFetcher($client, $logWriter))->fetchAll(
10009,
'STORE-1',
['M1', 'M2', 'M3'],
2
);
self::assertSame(['M1', 'M2', 'M3'], array_column($result, 'msku'));
}
}
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Model\Sku;
use Esun\LingxingErp\Model\Sku\ProductErpSkuRepository;
use Magento\Catalog\Model\ResourceModel\Product\Action as ProductActionResource;
use Magento\Eav\Model\Config as EavConfig;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\EntityManager\MetadataPool;
use Magento\Store\Model\StoreManagerInterface;
use PHPUnit\Framework\TestCase;
class ProductErpSkuRepositoryTest extends TestCase
{
public function testMultipleMskusMayShareOneErpSkuInWebsiteStoreMapping(): void
{
$repository = new ProductErpSkuRepository(
$this->createMock(ResourceConnection::class),
$this->createMock(ProductActionResource::class),
$this->createMock(StoreManagerInterface::class),
$this->createMock(EavConfig::class),
$this->createMock(MetadataPool::class)
);
$method = new \ReflectionMethod($repository, 'normalizeAndValidate');
$result = $method->invoke($repository, 10009, 'STORE-1', [
['platform_code' => 10009, 'store_id' => 'STORE-1', 'msku' => 'MAGENTO-A', 'sku' => 'ERP-1'],
['platform_code' => 10009, 'store_id' => 'STORE-1', 'msku' => 'MAGENTO-B', 'sku' => 'ERP-1'],
]);
self::assertSame(['MAGENTO-A' => 'ERP-1', 'MAGENTO-B' => 'ERP-1'], $result);
}
}
@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Model\Store;
use Esun\LingxingErp\Model\Api\ApiException;
use Esun\LingxingErp\Model\Api\Client;
use Esun\LingxingErp\Model\Store\StoreFetcher;
use PHPUnit\Framework\TestCase;
class StoreFetcherTest extends TestCase
{
public function testFetchesEveryPageWithoutStatusFilters(): void
{
$client = $this->createMock(Client::class);
$call = 0;
$client->expects(self::exactly(2))
->method('post')
->willReturnCallback(static function (string $path, array $parameters) use (&$call): array {
self::assertSame('/pb/mp/shop/v2/getSellerList', $path);
self::assertSame([
'offset' => $call,
'length' => 200,
'platform_code' => [10009],
], $parameters);
$response = ['data' => [
'total' => 2,
'list' => [[
'platform_code' => $call + 1,
'store_id' => $call === 0 ? 'A' : 'B',
]],
]];
$call++;
return $response;
});
self::assertSame(['A', 'B'], array_column((new StoreFetcher($client))->fetchAll(), 'store_id'));
}
public function testRejectsIncompleteStoreData(): void
{
$client = $this->createMock(Client::class);
$client->method('post')->willReturn([
'data' => ['total' => 1, 'list' => [['platform_code' => 1]]],
]);
$this->expectException(ApiException::class);
(new StoreFetcher($client))->fetchAll();
}
}
@@ -0,0 +1,94 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Model\Sync;
use Esun\LingxingErp\Model\Sync\LogWriter;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\DB\Adapter\AdapterInterface;
use PHPUnit\Framework\TestCase;
class LogWriterTest extends TestCase
{
public function testSuccessfulPayloadIsStoredAsCompactSummary(): void
{
$inserted = $this->captureInsert([
'status' => 'success',
'operation' => 'order_create',
'request_payload' => ['order_no' => '100001', 'items' => [['sku' => 'A'], ['sku' => 'B']]],
'response_payload' => ['code' => 0, 'request_id' => 'REQ-1', 'data' => ['id' => 99]],
]);
$request = json_decode((string)$inserted['request_payload'], true, 512, JSON_THROW_ON_ERROR);
$response = json_decode((string)$inserted['response_payload'], true, 512, JSON_THROW_ON_ERROR);
self::assertSame('Success payload omitted by retention policy.', $request['_summary']);
self::assertSame(2, $request['items_count']);
self::assertArrayNotHasKey('order_no', $request);
self::assertSame(0, $response['code']);
self::assertSame('REQ-1', $response['request_id']);
self::assertSame(1, $response['data_count']);
}
public function testFailedPayloadRemainsAvailableAndSanitized(): void
{
$inserted = $this->captureInsert([
'status' => 'failed',
'operation' => 'order_create',
'request_payload' => [
'order_no' => '100001',
'phone' => '123456',
'receiver_mobile' => '123456',
'postal_code' => '78701',
'buyer_email' => 'buyer@example.com',
'buyer_name' => 'Buyer Name',
],
]);
$request = json_decode((string)$inserted['request_payload'], true, 512, JSON_THROW_ON_ERROR);
self::assertSame('100001', $request['order_no']);
self::assertSame('[REDACTED]', $request['phone']);
self::assertSame('[REDACTED]', $request['receiver_mobile']);
self::assertSame('[REDACTED]', $request['postal_code']);
self::assertSame('[REDACTED]', $request['buyer_email']);
self::assertSame('[REDACTED]', $request['buyer_name']);
}
public function testInventoryProtectionCountsRemainInSuccessSummary(): void
{
$inserted = $this->captureInsert([
'status' => 'success',
'operation' => 'inventory_sync',
'response_payload' => [
'items' => 10,
'unmapped' => 2,
'zeroed' => 3,
'preserved_without_erp_sku' => 4,
],
]);
$response = json_decode((string)$inserted['response_payload'], true, 512, JSON_THROW_ON_ERROR);
self::assertSame(2, $response['unmapped']);
self::assertSame(3, $response['zeroed']);
self::assertSame(4, $response['preserved_without_erp_sku']);
}
/** @return array<string, mixed> */
private function captureInsert(array $data): array
{
$inserted = [];
$connection = $this->createMock(AdapterInterface::class);
$connection->expects(self::once())->method('insert')->willReturnCallback(
static function (string $table, array $row) use (&$inserted): int {
self::assertSame('esun_lingxing_sync_log', $table);
$inserted = $row;
return 1;
}
);
$resource = $this->createMock(ResourceConnection::class);
$resource->method('getConnection')->willReturn($connection);
$resource->method('getTableName')->willReturnArgument(0);
(new LogWriter($resource))->write($data);
return $inserted;
}
}
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Model\Warehouse;
use Esun\LingxingErp\Model\Api\Client;
use Esun\LingxingErp\Model\Api\Endpoint;
use Esun\LingxingErp\Model\Sync\LogWriter;
use Esun\LingxingErp\Model\Warehouse\WarehouseFetcher;
use PHPUnit\Framework\TestCase;
class WarehouseFetcherTest extends TestCase
{
public function testFetchesOnlyTypeThreeWarehouses(): void
{
$client = $this->createMock(Client::class);
$client->expects(self::once())
->method('post')
->willReturnCallback(function (string $path, array $request): array {
self::assertSame(Endpoint::WAREHOUSE_LIST, $path);
self::assertSame(3, $request['type']);
self::assertSame('0,1', $request['is_delete']);
return [
'code' => 0,
'data' => [[
'wid' => 200,
'name' => 'Warehouse ' . $request['type'],
'type' => $request['type'],
]],
'total' => 1,
];
});
$logWriter = $this->createMock(LogWriter::class);
$logWriter->expects(self::once())->method('write');
$result = (new WarehouseFetcher($client, $logWriter))->fetchAll();
self::assertCount(1, $result);
self::assertSame([200], array_column($result, 'wid'));
}
}
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Model\Warehouse;
use Esun\LingxingErp\Model\Warehouse\WarehouseFetcher;
use Esun\LingxingErp\Model\Warehouse\WarehouseRepository;
use Esun\LingxingErp\Model\Warehouse\WarehouseSynchronizer;
use Magento\Framework\Lock\LockManagerInterface;
use PHPUnit\Framework\TestCase;
class WarehouseSynchronizerTest extends TestCase
{
public function testCachesEveryFetchedTypeThreeWarehouseWithoutCreatingSources(): void
{
$fetcher = $this->createMock(WarehouseFetcher::class);
$fetcher->method('fetchAll')->willReturn([
['wid' => 10, 'name' => 'US Stock', 'type' => 3],
['wid' => 20, 'name' => 'UK Stock', 'type' => 3],
['wid' => 30, 'name' => 'Unused Warehouse', 'type' => 3],
]);
$repository = $this->createMock(WarehouseRepository::class);
$repository->expects(self::exactly(3))->method('saveMetadata');
$lockManager = $this->createMock(LockManagerInterface::class);
$lockManager->method('lock')->willReturn(true);
$lockManager->expects(self::once())->method('unlock');
$result = (new WarehouseSynchronizer(
$fetcher,
$repository,
$lockManager
))->synchronize();
self::assertSame(['warehouses' => 3], $result);
}
}
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Observer;
use Esun\LingxingErp\Model\Order\CancellationSourceResolver;
use Esun\LingxingErp\Observer\RecordOrderCancellation;
use Magento\Framework\Event;
use Magento\Framework\Event\Observer;
use Magento\Sales\Model\Order;
use PHPUnit\Framework\TestCase;
class RecordOrderCancellationTest extends TestCase
{
public function testAddsLocalCancellationSourceCommentOnly(): void
{
$sourceResolver = $this->createMock(CancellationSourceResolver::class);
$sourceResolver->expects(self::once())
->method('resolve')
->willReturn(CancellationSourceResolver::CUSTOMER);
$sourceResolver->expects(self::once())
->method('getComment')
->with(CancellationSourceResolver::CUSTOMER)
->willReturn('The customer canceled this order from their account.');
$order = $this->createMock(Order::class);
$order->expects(self::once())
->method('addCommentToStatusHistory')
->with('The customer canceled this order from their account.');
(new RecordOrderCancellation($sourceResolver))->execute(new Observer([
'event' => new Event(['order' => $order]),
]));
}
}
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Observer;
use Esun\LingxingErp\Model\Warehouse\WarehouseRepository;
use Esun\LingxingErp\Observer\SaveSourceWarehouseMapping;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Event\Observer;
use Magento\InventoryApi\Api\Data\SourceInterface;
use PHPUnit\Framework\TestCase;
class SaveSourceWarehouseMappingTest extends TestCase
{
public function testAssignsSelectedWarehouseAfterSourceSave(): void
{
$repository = $this->createMock(WarehouseRepository::class);
$repository->expects(self::once())->method('assignSource')->with('uk', 42);
$request = $this->createMock(RequestInterface::class);
$request->method('getParam')->with('general')->willReturn(['lingxing_wid' => '42']);
$source = $this->createMock(SourceInterface::class);
$source->method('getSourceCode')->willReturn('uk');
(new SaveSourceWarehouseMapping($repository))->execute(new Observer([
'request' => $request,
'source' => $source,
]));
}
public function testClearsMappingWhenEmptyOptionIsSelected(): void
{
$repository = $this->createMock(WarehouseRepository::class);
$repository->expects(self::once())->method('assignSource')->with('eu', null);
$request = $this->createMock(RequestInterface::class);
$request->method('getParam')->with('general')->willReturn(['lingxing_wid' => '']);
$source = $this->createMock(SourceInterface::class);
$source->method('getSourceCode')->willReturn('eu');
(new SaveSourceWarehouseMapping($repository))->execute(new Observer([
'request' => $request,
'source' => $source,
]));
}
}
@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Ui\Component\Listing\Column;
use Esun\LingxingErp\Ui\Component\Listing\Column\LogRetryActions;
use Esun\LingxingErp\Ui\Component\Listing\Column\RetryActions;
use Magento\Framework\UrlInterface;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Magento\Framework\View\Element\UiComponentFactory;
use PHPUnit\Framework\TestCase;
class DetailActionsTest extends TestCase
{
public function testOrderSuccessRecordContainsViewAction(): void
{
$column = new RetryActions(
$this->createMock(ContextInterface::class),
$this->createMock(UiComponentFactory::class),
$this->createUrlBuilder(),
[],
['name' => 'actions', 'config' => ['type' => 'order']]
);
$result = $column->prepareDataSource([
'data' => ['items' => [['entity_id' => 15, 'status' => 'success']]],
]);
self::assertSame('View Details', (string)$result['data']['items'][0]['actions']['view']['label']);
self::assertSame('/esun_lingxing/order/view?id=15', $result['data']['items'][0]['actions']['view']['href']);
}
public function testLogSuccessRecordContainsViewAction(): void
{
$column = new LogRetryActions(
$this->createMock(ContextInterface::class),
$this->createMock(UiComponentFactory::class),
$this->createUrlBuilder(),
[],
['name' => 'actions']
);
$result = $column->prepareDataSource([
'data' => ['items' => [['entity_id' => 52, 'status' => 'success', 'entity_type' => 'shipment']]],
]);
self::assertSame('View Details', (string)$result['data']['items'][0]['actions']['view']['label']);
self::assertSame('/esun_lingxing/log/view?id=52', $result['data']['items'][0]['actions']['view']['href']);
}
private function createUrlBuilder(): UrlInterface
{
$urlBuilder = $this->createMock(UrlInterface::class);
$urlBuilder->method('getUrl')->willReturnCallback(
static fn(string $route, array $parameters): string => '/' . $route . '?id=' . $parameters['id']
);
return $urlBuilder;
}
}
@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Ui\Component\Listing\Column;
use Magento\Framework\UrlInterface;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Ui\Component\Listing\Columns\Column;
class LogRetryActions extends Column
{
public function __construct(
ContextInterface $context,
UiComponentFactory $uiComponentFactory,
private readonly UrlInterface $urlBuilder,
array $components = [],
array $data = []
) {
parent::__construct($context, $uiComponentFactory, $components, $data);
}
public function prepareDataSource(array $dataSource): array
{
if (!isset($dataSource['data']['items']) || !is_array($dataSource['data']['items'])) {
return $dataSource;
}
foreach ($dataSource['data']['items'] as &$item) {
$item[$this->getData('name')]['view'] = [
'href' => $this->urlBuilder->getUrl(
'esun_lingxing/log/view',
['id' => (int)$item['entity_id']]
),
'label' => __('View Details'),
];
$type = (string)($item['entity_type'] ?? '');
$localId = (int)($item['local_entity_id'] ?? 0);
if (!in_array((string)($item['status'] ?? ''), ['failed', 'retrying'], true)
|| !in_array($type, ['order', 'shipment'], true)
|| $localId <= 0
) {
continue;
}
$item[$this->getData('name')]['retry'] = [
'href' => $this->urlBuilder->getUrl(
'esun_lingxing/sync/retry',
['id' => $localId, 'type' => $type]
),
'label' => __('Retry'),
'confirm' => [
'title' => __('Retry synchronization'),
'message' => __('Queue the underlying synchronization record for retry?'),
],
];
}
unset($item);
return $dataSource;
}
}
@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Ui\Component\Listing\Column;
use Magento\Framework\UrlInterface;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Ui\Component\Listing\Columns\Column;
class RetryActions extends Column
{
public function __construct(
ContextInterface $context,
UiComponentFactory $uiComponentFactory,
private readonly UrlInterface $urlBuilder,
array $components = [],
array $data = []
) {
parent::__construct($context, $uiComponentFactory, $components, $data);
}
public function prepareDataSource(array $dataSource): array
{
$type = (string)($this->getData('config/type') ?: 'order');
if (!isset($dataSource['data']['items']) || !is_array($dataSource['data']['items'])) {
return $dataSource;
}
foreach ($dataSource['data']['items'] as &$item) {
$item[$this->getData('name')]['view'] = [
'href' => $this->urlBuilder->getUrl(
'esun_lingxing/' . $type . '/view',
['id' => (int)$item['entity_id']]
),
'label' => __('View Details'),
];
if (!in_array((string)($item['status'] ?? ''), ['failed', 'retrying'], true)) {
continue;
}
$item[$this->getData('name')]['retry'] = [
'href' => $this->urlBuilder->getUrl('esun_lingxing/sync/retry', ['id' => (int)$item['entity_id'], 'type' => $type]),
'label' => __('Retry'),
'confirm' => ['title' => __('Retry synchronization'), 'message' => __('Queue this record for retry?')],
];
}
unset($item);
return $dataSource;
}
}
+10
View File
@@ -0,0 +1,10 @@
{
"name": "esun/module-lingxing-erp",
"description": "Lingxing ERP order and shipment integration for eSUN",
"type": "magento2-module",
"version": "1.0.0",
"autoload": {
"files": ["registration.php"],
"psr-4": {"Esun\\LingxingErp\\": ""}
}
}
+25
View File
@@ -0,0 +1,25 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd">
<acl>
<resources>
<resource id="Magento_Backend::admin">
<resource id="Esun_LingxingErp::root" title="Lingxing ERP" sortOrder="80">
<resource id="Esun_LingxingErp::stores" title="View Lingxing Stores" sortOrder="5">
<resource id="Esun_LingxingErp::sync_stores" title="Synchronize Lingxing Stores" sortOrder="10"/>
<resource id="Esun_LingxingErp::sync_sku_mappings" title="Synchronize Product ERP SKUs" sortOrder="20"/>
</resource>
<resource id="Esun_LingxingErp::orders" title="View Order Synchronization" sortOrder="10"/>
<resource id="Esun_LingxingErp::warehouses" title="View Lingxing Warehouses" sortOrder="15">
<resource id="Esun_LingxingErp::sync_warehouses" title="Synchronize Lingxing Warehouses" sortOrder="10"/>
<resource id="Esun_LingxingErp::sync_inventory" title="Synchronize Lingxing Inventory" sortOrder="20"/>
</resource>
<resource id="Esun_LingxingErp::shipments" title="View Shipment Synchronization" sortOrder="20"/>
<resource id="Esun_LingxingErp::logs" title="View Synchronization Logs" sortOrder="30"/>
<resource id="Esun_LingxingErp::retry" title="Retry Synchronization" sortOrder="40"/>
<resource id="Esun_LingxingErp::config" title="Configure Lingxing ERP" sortOrder="50"/>
</resource>
</resource>
</resources>
</acl>
</config>
@@ -0,0 +1,8 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\InventoryAdminUi\Ui\DataProvider\SourceDataProvider">
<plugin name="esun_lingxing_source_warehouse_data"
type="Esun\LingxingErp\Plugin\InventoryAdminUi\SourceDataProviderPlugin"/>
</type>
</config>
@@ -0,0 +1,8 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="controller_action_inventory_source_save_after">
<observer name="esun_lingxing_save_source_warehouse_mapping"
instance="Esun\LingxingErp\Observer\SaveSourceWarehouseMapping"/>
</event>
</config>
@@ -0,0 +1,23 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Backend:etc/menu.xsd">
<menu>
<add id="Esun_LingxingErp::root" title="Lingxing ERP" module="Esun_LingxingErp"
sortOrder="80" parent="Esun_ImageManager::esun" resource="Esun_LingxingErp::root"/>
<add id="Esun_LingxingErp::orders" title="Order Synchronization" module="Esun_LingxingErp"
sortOrder="20" parent="Esun_LingxingErp::root" action="esun_lingxing/order/index"
resource="Esun_LingxingErp::orders"/>
<add id="Esun_LingxingErp::store_list" title="Stores" module="Esun_LingxingErp"
sortOrder="10" parent="Esun_LingxingErp::root" action="esun_lingxing/store/index"
resource="Esun_LingxingErp::stores"/>
<add id="Esun_LingxingErp::shipments" title="Shipment Synchronization" module="Esun_LingxingErp"
sortOrder="30" parent="Esun_LingxingErp::root" action="esun_lingxing/shipment/index"
resource="Esun_LingxingErp::shipments"/>
<add id="Esun_LingxingErp::warehouses" title="Warehouses and Inventory" module="Esun_LingxingErp"
sortOrder="15" parent="Esun_LingxingErp::root" action="esun_lingxing/warehouse/index"
resource="Esun_LingxingErp::warehouses"/>
<add id="Esun_LingxingErp::logs" title="Synchronization Logs" module="Esun_LingxingErp"
sortOrder="40" parent="Esun_LingxingErp::root" action="esun_lingxing/log/index"
resource="Esun_LingxingErp::logs"/>
</menu>
</config>
@@ -0,0 +1,9 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="admin">
<route id="esun_lingxing" frontName="esun_lingxing">
<module name="Esun_LingxingErp" before="Magento_Backend"/>
</route>
</router>
</config>
@@ -0,0 +1,85 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
<system>
<tab id="esun" translate="label" sortOrder="300"><label>Esun</label></tab>
<section id="esun_lingxing" translate="label" sortOrder="160" showInDefault="1" showInWebsite="1" showInStore="0">
<label>Lingxing ERP</label>
<tab>esun</tab>
<resource>Esun_LingxingErp::config</resource>
<group id="general" translate="label" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="0">
<label>Connection and Order Mapping</label>
<field id="enabled" translate="label" type="select" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Enabled</label><source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
</field>
<field id="api_base_url" translate="label" type="text" sortOrder="20" showInDefault="1" showInWebsite="0" showInStore="0">
<label>API Base URL</label>
</field>
<field id="app_id" translate="label" type="text" sortOrder="30" showInDefault="1" showInWebsite="0" showInStore="0">
<label>App ID</label>
</field>
<field id="app_secret" translate="label" type="obscure" sortOrder="40" showInDefault="1" showInWebsite="0" showInStore="0">
<label>App Secret</label><backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model>
</field>
<field id="store_mapping" translate="label comment" type="select" sortOrder="50" showInDefault="0" showInWebsite="1" showInStore="0" canRestore="1">
<label>Lingxing Store</label>
<source_model>Esun\LingxingErp\Model\Source\LingxingStore</source_model>
<comment>Read from the locally synchronized store list. The selected option stores both Platform Code and Lingxing Store ID for this Magento Website.</comment>
</field>
<field id="warehouse_id" translate="label comment" type="select" sortOrder="70" showInDefault="1" showInWebsite="1" showInStore="0" canRestore="1">
<label>Default Lingxing Warehouse</label>
<source_model>Esun\LingxingErp\Model\Source\LingxingWarehouse</source_model>
<comment>Read from synchronized warehouses. Leave both warehouse and logistics type blank to let Lingxing route the order.</comment>
</field>
<field id="logistics_type_id" translate="label" type="text" sortOrder="80" showInDefault="1" showInWebsite="1" showInStore="0" canRestore="1">
<label>Default Logistics Type ID</label>
</field>
<field id="eligible_statuses" translate="label comment" type="text" sortOrder="90" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Order Statuses to Export</label><comment>Comma-separated Magento order status codes, for example: processing.</comment>
</field>
</group>
<group id="orders" translate="label" sortOrder="20" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Order Synchronization</label>
<field id="batch_size" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0"><label>Batch Size</label></field>
<field id="max_attempts" translate="label" type="text" sortOrder="20" showInDefault="1" showInWebsite="0" showInStore="0"><label>Maximum Attempts</label></field>
<field id="stock_deduction_type" translate="label comment" type="text" sortOrder="30" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Stock Deduction Type</label><comment>Lingxing value 1 means no store-specific stock dimension; 2 means SKU plus order store.</comment>
</field>
</group>
<group id="shipments" translate="label" sortOrder="30" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Shipment Synchronization</label>
<field id="page_size" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0"><label>Pull Page Size</label></field>
<field id="max_pages" translate="label" type="text" sortOrder="20" showInDefault="1" showInWebsite="0" showInStore="0"><label>Maximum Pages per Run</label></field>
<field id="max_attempts" translate="label" type="text" sortOrder="30" showInDefault="1" showInWebsite="0" showInStore="0"><label>Maximum Processing Attempts</label></field>
<field id="notify_customer" translate="label" type="select" sortOrder="40" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Email Shipment to Customer</label><source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
</field>
</group>
<group id="sku_sync" translate="label" sortOrder="40" showInDefault="1" showInWebsite="0" showInStore="0">
<label>ERP SKU Synchronization</label>
<field id="enabled" translate="label comment" type="select" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Daily Synchronization Enabled</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<comment>Runs once per day. Manual synchronization remains available under Esun &gt; Lingxing ERP &gt; Stores.</comment>
</field>
<field id="page_size" translate="label comment" type="text" sortOrder="20" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Pair List Page Size</label>
<comment>Number of Lingxing SKU pairs requested per API page, from 1 to 200.</comment>
</field>
</group>
<group id="logging" translate="label" sortOrder="50" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Synchronization Log Retention</label>
<field id="success_retention_days" translate="label comment" type="text" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Success Log Retention (Days)</label>
<validate>validate-number validate-greater-than-zero</validate>
<comment>Successful and ignored logs store compact summaries and are deleted after this many days.</comment>
</field>
<field id="error_retention_days" translate="label comment" type="text" sortOrder="20" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Error Log Retention (Days)</label>
<validate>validate-number validate-greater-than-zero</validate>
<comment>Failed and retrying logs retain sanitized request and response payloads for this many days.</comment>
</field>
</group>
</section>
</system>
</config>
+32
View File
@@ -0,0 +1,32 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
<default>
<esun_lingxing>
<general>
<enabled>0</enabled>
<api_base_url>https://openapi.lingxing.com</api_base_url>
<eligible_statuses>processing</eligible_statuses>
</general>
<orders>
<batch_size>20</batch_size>
<max_attempts>8</max_attempts>
<stock_deduction_type>1</stock_deduction_type>
</orders>
<shipments>
<page_size>200</page_size>
<max_pages>20</max_pages>
<max_attempts>8</max_attempts>
<notify_customer>0</notify_customer>
</shipments>
<sku_sync>
<enabled>1</enabled>
<page_size>200</page_size>
</sku_sync>
<logging>
<success_retention_days>14</success_retention_days>
<error_retention_days>90</error_retention_days>
</logging>
</esun_lingxing>
</default>
</config>
+24
View File
@@ -0,0 +1,24 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
<group id="default">
<job name="esun_lingxing_process_orders" instance="Esun\LingxingErp\Cron\ProcessOrders" method="execute">
<schedule>* * * * *</schedule>
</job>
<job name="esun_lingxing_pull_shipments" instance="Esun\LingxingErp\Cron\PullShipments" method="execute">
<schedule>*/3 * * * *</schedule>
</job>
<job name="esun_lingxing_process_shipments" instance="Esun\LingxingErp\Cron\ProcessShipments" method="execute">
<schedule>* * * * *</schedule>
</job>
<job name="esun_lingxing_sync_sku_mappings" instance="Esun\LingxingErp\Cron\SyncSkuMappings" method="execute">
<schedule>17 2 * * *</schedule>
</job>
<job name="esun_lingxing_sync_inventory" instance="Esun\LingxingErp\Cron\SyncInventory" method="execute">
<schedule>47 2 * * *</schedule>
</job>
<job name="esun_lingxing_clean_sync_logs" instance="Esun\LingxingErp\Cron\CleanSyncLogs" method="execute">
<schedule>23 3 * * *</schedule>
</job>
</group>
</config>
+132
View File
@@ -0,0 +1,132 @@
<?xml version="1.0"?>
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
<table name="esun_lingxing_store" resource="default" engine="innodb" comment="Lingxing ERP Stores">
<column xsi:type="int" name="entity_id" unsigned="true" nullable="false" identity="true" comment="Entity ID"/>
<column xsi:type="int" name="platform_code" unsigned="true" nullable="false" comment="Lingxing Platform Code"/>
<column xsi:type="varchar" name="platform_name" nullable="false" length="100" default="" comment="Platform Name"/>
<column xsi:type="varchar" name="store_id" nullable="false" length="100" comment="Lingxing Store ID"/>
<column xsi:type="varchar" name="sid" nullable="false" length="100" default="" comment="Lingxing Seller ID"/>
<column xsi:type="varchar" name="store_name" nullable="false" length="255" default="" comment="Lingxing Store Name"/>
<column xsi:type="varchar" name="currency" nullable="false" length="16" default="" comment="Store Currency"/>
<column xsi:type="smallint" name="is_sync" unsigned="true" nullable="false" default="0" comment="Store Sync Enabled"/>
<column xsi:type="smallint" name="status" unsigned="true" nullable="false" default="0" comment="Authorization Status"/>
<column xsi:type="timestamp" name="last_synced_at" nullable="false" on_update="false" comment="Last Synchronized At"/>
<column xsi:type="timestamp" name="created_at" nullable="false" default="CURRENT_TIMESTAMP" on_update="false" comment="Created At"/>
<column xsi:type="timestamp" name="updated_at" nullable="false" default="CURRENT_TIMESTAMP" on_update="true" comment="Updated At"/>
<constraint xsi:type="primary" referenceId="PRIMARY"><column name="entity_id"/></constraint>
<constraint xsi:type="unique" referenceId="ESUN_LINGXING_STORE_STORE_ID"><column name="store_id"/></constraint>
<index referenceId="ESUN_LINGXING_STORE_PLATFORM" indexType="btree"><column name="platform_code"/></index>
<index referenceId="ESUN_LINGXING_STORE_ACTIVE" indexType="btree"><column name="is_sync"/><column name="status"/></index>
</table>
<table name="esun_lingxing_warehouse" resource="default" engine="innodb" comment="Lingxing ERP Warehouses">
<column xsi:type="int" name="entity_id" unsigned="true" nullable="false" identity="true" comment="Entity ID"/>
<column xsi:type="bigint" name="wid" unsigned="true" nullable="false" comment="Lingxing Warehouse ID"/>
<column xsi:type="varchar" name="source_code" nullable="true" length="64" comment="Mapped Magento Inventory Source Code"/>
<column xsi:type="varchar" name="warehouse_name" nullable="false" length="255" comment="Lingxing Warehouse Name"/>
<column xsi:type="smallint" name="warehouse_type" unsigned="true" nullable="false" comment="Lingxing Warehouse Type"/>
<column xsi:type="varchar" name="country_code" nullable="true" length="8" comment="Country Code"/>
<column xsi:type="varchar" name="third_party_code" nullable="true" length="100" comment="Third-party Warehouse Code"/>
<column xsi:type="varchar" name="third_party_name" nullable="true" length="255" comment="Third-party Warehouse Name"/>
<column xsi:type="smallint" name="lingxing_status" unsigned="true" nullable="false" default="1" comment="Lingxing Enabled Status"/>
<column xsi:type="smallint" name="is_deleted" unsigned="true" nullable="false" default="0" comment="Lingxing Deleted Status"/>
<column xsi:type="timestamp" name="last_synced_at" nullable="true" on_update="false" comment="Last Warehouse Synchronization At"/>
<column xsi:type="timestamp" name="last_inventory_synced_at" nullable="true" on_update="false" comment="Last Inventory Synchronization At"/>
<column xsi:type="timestamp" name="created_at" nullable="false" default="CURRENT_TIMESTAMP" on_update="false" comment="Created At"/>
<column xsi:type="timestamp" name="updated_at" nullable="false" default="CURRENT_TIMESTAMP" on_update="true" comment="Updated At"/>
<constraint xsi:type="primary" referenceId="PRIMARY"><column name="entity_id"/></constraint>
<constraint xsi:type="unique" referenceId="ESUN_LINGXING_WAREHOUSE_WID"><column name="wid"/></constraint>
<constraint xsi:type="unique" referenceId="ESUN_LINGXING_WAREHOUSE_SOURCE"><column name="source_code"/></constraint>
<index referenceId="ESUN_LINGXING_WAREHOUSE_STATUS" indexType="btree"><column name="lingxing_status"/><column name="is_deleted"/></index>
</table>
<table name="esun_lingxing_order_sync" resource="default" engine="innodb" comment="Lingxing Order Synchronization">
<column xsi:type="int" name="entity_id" unsigned="true" nullable="false" identity="true" comment="Entity ID"/>
<column xsi:type="int" name="order_id" unsigned="true" nullable="false" comment="Magento Order ID"/>
<column xsi:type="varchar" name="increment_id" nullable="false" length="50" comment="Magento Order Number"/>
<column xsi:type="varchar" name="platform_order_no" nullable="false" length="100" comment="Lingxing Platform Order Number"/>
<column xsi:type="varchar" name="global_order_no" nullable="true" length="100" comment="Lingxing Global Order Number"/>
<column xsi:type="varchar" name="status" nullable="false" length="20" default="pending" comment="Sync Status"/>
<column xsi:type="int" name="attempt_count" unsigned="true" nullable="false" default="0" comment="Attempt Count"/>
<column xsi:type="timestamp" name="next_retry_at" nullable="true" on_update="false" comment="Next Retry At"/>
<column xsi:type="varchar" name="last_error_code" nullable="true" length="64" comment="Last Error Code"/>
<column xsi:type="text" name="last_error_message" nullable="true" comment="Last Error Message"/>
<column xsi:type="varchar" name="request_id" nullable="true" length="128" comment="Lingxing Request ID"/>
<column xsi:type="varchar" name="payload_hash" nullable="true" length="64" comment="Payload SHA256"/>
<column xsi:type="timestamp" name="last_attempt_at" nullable="true" on_update="false" comment="Last Attempt At"/>
<column xsi:type="timestamp" name="synced_at" nullable="true" on_update="false" comment="Synchronized At"/>
<column xsi:type="varchar" name="cancel_status" nullable="true" length="20" comment="Cancellation Sync Status"/>
<column xsi:type="varchar" name="cancel_source" nullable="true" length="24" comment="Magento Cancellation Source"/>
<column xsi:type="int" name="cancel_attempt_count" unsigned="true" nullable="false" default="0" comment="Cancellation Attempt Count"/>
<column xsi:type="timestamp" name="cancel_next_retry_at" nullable="true" on_update="false" comment="Cancellation Next Retry At"/>
<column xsi:type="varchar" name="cancel_error_code" nullable="true" length="64" comment="Cancellation Error Code"/>
<column xsi:type="text" name="cancel_error_message" nullable="true" comment="Cancellation Error Message"/>
<column xsi:type="varchar" name="cancel_request_id" nullable="true" length="128" comment="Cancellation Request ID"/>
<column xsi:type="timestamp" name="cancel_requested_at" nullable="true" on_update="false" comment="Cancellation Requested At"/>
<column xsi:type="timestamp" name="cancel_synced_at" nullable="true" on_update="false" comment="Cancellation Synchronized At"/>
<column xsi:type="timestamp" name="created_at" nullable="false" default="CURRENT_TIMESTAMP" on_update="false" comment="Created At"/>
<column xsi:type="timestamp" name="updated_at" nullable="false" default="CURRENT_TIMESTAMP" on_update="true" comment="Updated At"/>
<constraint xsi:type="primary" referenceId="PRIMARY"><column name="entity_id"/></constraint>
<constraint xsi:type="unique" referenceId="ESUN_LINGXING_ORDER_SYNC_ORDER_ID"><column name="order_id"/></constraint>
<constraint xsi:type="unique" referenceId="ESUN_LINGXING_ORDER_SYNC_PLATFORM_NO"><column name="platform_order_no"/></constraint>
<index referenceId="ESUN_LINGXING_ORDER_SYNC_GLOBAL_NO" indexType="btree"><column name="global_order_no"/></index>
<index referenceId="ESUN_LINGXING_ORDER_SYNC_STATUS_RETRY" indexType="btree"><column name="status"/><column name="next_retry_at"/></index>
<index referenceId="ESUN_LINGXING_ORDER_CANCEL_STATUS_RETRY" indexType="btree"><column name="cancel_status"/><column name="cancel_next_retry_at"/></index>
</table>
<table name="esun_lingxing_shipment_sync" resource="default" engine="innodb" comment="Lingxing Shipment Synchronization">
<column xsi:type="int" name="entity_id" unsigned="true" nullable="false" identity="true" comment="Entity ID"/>
<column xsi:type="varchar" name="external_key" nullable="false" length="191" comment="Idempotency Key"/>
<column xsi:type="int" name="order_id" unsigned="true" nullable="true" comment="Magento Order ID"/>
<column xsi:type="varchar" name="increment_id" nullable="true" length="50" comment="Magento Order Number"/>
<column xsi:type="varchar" name="global_order_no" nullable="true" length="100" comment="Lingxing Global Order Number"/>
<column xsi:type="bigint" name="wo_id" unsigned="true" nullable="true" comment="Lingxing Outbound ID"/>
<column xsi:type="varchar" name="wo_number" nullable="false" length="100" comment="Lingxing Outbound Number"/>
<column xsi:type="varchar" name="package_no" nullable="true" length="100" comment="Lingxing Package Number"/>
<column xsi:type="varchar" name="tracking_no" nullable="true" length="255" comment="Tracking Numbers"/>
<column xsi:type="int" name="shipment_id" unsigned="true" nullable="true" comment="Magento Shipment ID"/>
<column xsi:type="varchar" name="status" nullable="false" length="20" default="pending" comment="Sync Status"/>
<column xsi:type="int" name="attempt_count" unsigned="true" nullable="false" default="0" comment="Attempt Count"/>
<column xsi:type="timestamp" name="next_retry_at" nullable="true" on_update="false" comment="Next Retry At"/>
<column xsi:type="varchar" name="last_error_code" nullable="true" length="64" comment="Last Error Code"/>
<column xsi:type="text" name="last_error_message" nullable="true" comment="Last Error Message"/>
<column xsi:type="varchar" name="request_id" nullable="true" length="128" comment="Lingxing Request ID"/>
<column xsi:type="mediumtext" name="payload_json" nullable="false" comment="Normalized Fulfillment Payload"/>
<column xsi:type="timestamp" name="last_attempt_at" nullable="true" on_update="false" comment="Last Attempt At"/>
<column xsi:type="timestamp" name="synced_at" nullable="true" on_update="false" comment="Synchronized At"/>
<column xsi:type="timestamp" name="created_at" nullable="false" default="CURRENT_TIMESTAMP" on_update="false" comment="Created At"/>
<column xsi:type="timestamp" name="updated_at" nullable="false" default="CURRENT_TIMESTAMP" on_update="true" comment="Updated At"/>
<constraint xsi:type="primary" referenceId="PRIMARY"><column name="entity_id"/></constraint>
<constraint xsi:type="unique" referenceId="ESUN_LINGXING_SHIPMENT_EXTERNAL_KEY"><column name="external_key"/></constraint>
<index referenceId="ESUN_LINGXING_SHIPMENT_WO_NUMBER" indexType="btree"><column name="wo_number"/></index>
<index referenceId="ESUN_LINGXING_SHIPMENT_ORDER_ID" indexType="btree"><column name="order_id"/></index>
<index referenceId="ESUN_LINGXING_SHIPMENT_STATUS_RETRY" indexType="btree"><column name="status"/><column name="next_retry_at"/></index>
</table>
<table name="esun_lingxing_sync_log" resource="default" engine="innodb" comment="Lingxing Synchronization Attempts">
<column xsi:type="bigint" name="entity_id" unsigned="true" nullable="false" identity="true" comment="Entity ID"/>
<column xsi:type="varchar" name="direction" nullable="false" length="10" comment="Push or Pull"/>
<column xsi:type="varchar" name="operation" nullable="false" length="40" comment="Operation"/>
<column xsi:type="varchar" name="api_path" nullable="true" length="255" comment="Lingxing API Endpoint"/>
<column xsi:type="varchar" name="entity_type" nullable="false" length="20" comment="Entity Type"/>
<column xsi:type="int" name="local_entity_id" unsigned="true" nullable="true" comment="Local Sync Entity ID"/>
<column xsi:type="varchar" name="increment_id" nullable="true" length="50" comment="Magento Order Number"/>
<column xsi:type="varchar" name="external_id" nullable="true" length="191" comment="Lingxing External ID"/>
<column xsi:type="varchar" name="status" nullable="false" length="20" comment="Attempt Status"/>
<column xsi:type="int" name="attempt_number" unsigned="true" nullable="false" default="1" comment="Attempt Number"/>
<column xsi:type="varchar" name="error_code" nullable="true" length="64" comment="Error Code"/>
<column xsi:type="text" name="error_message" nullable="true" comment="Error Message"/>
<column xsi:type="varchar" name="request_id" nullable="true" length="128" comment="Lingxing Request ID"/>
<column xsi:type="mediumtext" name="request_payload" nullable="true" comment="Sanitized Request Payload"/>
<column xsi:type="mediumtext" name="response_payload" nullable="true" comment="Sanitized Response Payload"/>
<column xsi:type="int" name="duration_ms" unsigned="true" nullable="true" comment="Duration Milliseconds"/>
<column xsi:type="timestamp" name="created_at" nullable="false" default="CURRENT_TIMESTAMP" on_update="false" comment="Created At"/>
<constraint xsi:type="primary" referenceId="PRIMARY"><column name="entity_id"/></constraint>
<index referenceId="ESUN_LINGXING_LOG_STATUS_CREATED" indexType="btree"><column name="status"/><column name="created_at"/></index>
<index referenceId="ESUN_LINGXING_LOG_API_PATH" indexType="btree"><column name="api_path"/></index>
<index referenceId="ESUN_LINGXING_LOG_ORDER" indexType="btree"><column name="increment_id"/></index>
<index referenceId="ESUN_LINGXING_LOG_EXTERNAL" indexType="btree"><column name="external_id"/></index>
<index referenceId="ESUN_LINGXING_LOG_REQUEST_ID" indexType="btree"><column name="request_id"/></index>
</table>
</schema>

Some files were not shown because too many files have changed in this diff Show More