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,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);
}
}
}