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