72 lines
3.2 KiB
PHP
72 lines
3.2 KiB
PHP
<?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,
|
|
]);
|
|
}
|
|
}
|
|
}
|
|
}
|