init
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\SeventeenTrack\Model\Api;
|
||||
|
||||
use Esun\SeventeenTrack\Model\Config;
|
||||
use Magento\Framework\HTTP\Client\Curl;
|
||||
use Magento\Framework\Serialize\Serializer\Json;
|
||||
|
||||
class Client
|
||||
{
|
||||
private ?int $lastStatus = null;
|
||||
private ?string $lastBody = null;
|
||||
|
||||
public function __construct(
|
||||
private readonly Config $config,
|
||||
private readonly Curl $curl,
|
||||
private readonly Json $json
|
||||
) {
|
||||
}
|
||||
|
||||
public function register(array $shipments): array
|
||||
{
|
||||
return $this->post('register', $shipments);
|
||||
}
|
||||
|
||||
public function getTrackInfo(array $shipments): array
|
||||
{
|
||||
return $this->post('gettrackinfo', $shipments);
|
||||
}
|
||||
|
||||
public function getLastStatus(): ?int
|
||||
{
|
||||
return $this->lastStatus;
|
||||
}
|
||||
|
||||
public function getLastBody(): ?string
|
||||
{
|
||||
return $this->lastBody;
|
||||
}
|
||||
|
||||
private function post(string $endpoint, array $payload): array
|
||||
{
|
||||
$this->lastStatus = null;
|
||||
$this->lastBody = null;
|
||||
$key = $this->config->getApiKey();
|
||||
if (!$this->config->isEnabled() || $key === '') {
|
||||
throw new \RuntimeException('17TRACK is disabled or the API key is missing.');
|
||||
}
|
||||
|
||||
$this->curl->setTimeout(30);
|
||||
$this->curl->setHeaders(['Content-Type' => 'application/json', '17token' => $key]);
|
||||
$this->curl->post($this->config->getApiUrl() . '/' . $endpoint, $this->json->serialize($payload));
|
||||
$status = $this->curl->getStatus();
|
||||
$body = $this->curl->getBody();
|
||||
$this->lastStatus = $status;
|
||||
$this->lastBody = $body;
|
||||
if ($status !== 200) {
|
||||
throw new \RuntimeException(sprintf('17TRACK returned HTTP %d.', $status));
|
||||
}
|
||||
|
||||
try {
|
||||
$response = $this->json->unserialize($body);
|
||||
} catch (\InvalidArgumentException $exception) {
|
||||
throw new \RuntimeException('17TRACK returned invalid JSON.', 0, $exception);
|
||||
}
|
||||
if (!is_array($response) || (int)($response['code'] ?? -1) !== 0) {
|
||||
$code = is_array($response) && isset($response['code']) ? (int)$response['code'] : 0;
|
||||
throw new \RuntimeException(
|
||||
(string)($response['message'] ?? '17TRACK request failed.'),
|
||||
$code
|
||||
);
|
||||
}
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\SeventeenTrack\Model;
|
||||
|
||||
use Magento\Framework\Model\AbstractModel;
|
||||
|
||||
class ApiLog extends AbstractModel
|
||||
{
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_init(\Esun\SeventeenTrack\Model\ResourceModel\ApiLog::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\SeventeenTrack\Model;
|
||||
|
||||
use Magento\Framework\App\ResourceConnection;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
class ApiLogWriter
|
||||
{
|
||||
private const TABLE = 'esun_seventeen_track_api_log';
|
||||
private const MAX_TEXT_LENGTH = 16777215;
|
||||
private const SENSITIVE_KEYS = [
|
||||
'17token', 'api_key', 'apikey', 'token', 'sign', 'signature',
|
||||
'phone', 'telephone', 'phone_number', 'phone_number_last_4',
|
||||
'email', 'address', 'address_line1', 'address_line2', 'street',
|
||||
'postal_code', 'destination_postal_code', 'consignee', 'shipper',
|
||||
'cpf_or_cnpj',
|
||||
];
|
||||
|
||||
public function __construct(
|
||||
private readonly ResourceConnection $resource,
|
||||
private readonly Config $config,
|
||||
private readonly LoggerInterface $logger
|
||||
) {
|
||||
}
|
||||
|
||||
/** Log without allowing a logging failure to interrupt synchronization or webhook acknowledgement. */
|
||||
public function write(array $data): void
|
||||
{
|
||||
try {
|
||||
foreach (['request_data', 'response_data'] as $field) {
|
||||
if (array_key_exists($field, $data)) {
|
||||
$data[$field] = $this->encode($data[$field]);
|
||||
}
|
||||
}
|
||||
if (isset($data['message'])) {
|
||||
$data['message'] = mb_substr((string)$data['message'], 0, 65535);
|
||||
}
|
||||
$data['created_at'] = gmdate('Y-m-d H:i:s');
|
||||
$this->resource->getConnection('sales')->insert(
|
||||
$this->resource->getTableName(self::TABLE),
|
||||
$data
|
||||
);
|
||||
} catch (\Throwable $exception) {
|
||||
$this->logger->error('Unable to write a 17TRACK API audit log.', [
|
||||
'operation' => (string)($data['operation'] ?? ''),
|
||||
'tracking_number' => (string)($data['tracking_number'] ?? ''),
|
||||
'exception' => $exception,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array{order_id:?int,order_number:?string,tracking_number:?string,event:?string} */
|
||||
public function getWebhookContext(string $rawBody): array
|
||||
{
|
||||
$context = ['order_id' => null, 'order_number' => null, 'tracking_number' => null, 'event' => null];
|
||||
try {
|
||||
$payload = json_decode($rawBody, true, 512, JSON_THROW_ON_ERROR);
|
||||
if (!is_array($payload)) {
|
||||
return $context;
|
||||
}
|
||||
$context['event'] = isset($payload['event']) ? mb_substr((string)$payload['event'], 0, 50) : null;
|
||||
$number = trim((string)($payload['data']['number'] ?? ''));
|
||||
$context['tracking_number'] = $number !== '' ? mb_substr($number, 0, 50) : null;
|
||||
if ($number === '') {
|
||||
return $context;
|
||||
}
|
||||
$connection = $this->resource->getConnection('sales');
|
||||
$trackingTable = $this->resource->getTableName('esun_seventeen_track');
|
||||
$orderTable = $this->resource->getTableName('sales_order');
|
||||
$row = $connection->fetchRow(
|
||||
$connection->select()
|
||||
->from(['tracking' => $trackingTable], ['order_id'])
|
||||
->joinLeft(['orders' => $orderTable], 'orders.entity_id = tracking.order_id', ['order_number' => 'increment_id'])
|
||||
->where('tracking.tracking_number = ?', $number)
|
||||
->limit(1)
|
||||
);
|
||||
if (is_array($row)) {
|
||||
$context['order_id'] = isset($row['order_id']) ? (int)$row['order_id'] : null;
|
||||
$context['order_number'] = isset($row['order_number']) ? (string)$row['order_number'] : null;
|
||||
}
|
||||
} catch (\Throwable) {
|
||||
// Invalid JSON and unavailable order context are captured by the processing result itself.
|
||||
}
|
||||
return $context;
|
||||
}
|
||||
|
||||
public function getWebhookPath(): string
|
||||
{
|
||||
return '/seventeentrack/webhook/index';
|
||||
}
|
||||
|
||||
public function getRegistrationPath(): string
|
||||
{
|
||||
return rtrim($this->config->getApiUrl(), '/') . '/register';
|
||||
}
|
||||
|
||||
private function encode(mixed $value): ?string
|
||||
{
|
||||
if ($value === null || $value === '') {
|
||||
return null;
|
||||
}
|
||||
if (is_string($value)) {
|
||||
try {
|
||||
$decoded = json_decode($value, true, 512, JSON_THROW_ON_ERROR);
|
||||
$value = is_array($decoded) ? $decoded : $value;
|
||||
} catch (\JsonException) {
|
||||
return mb_substr($value, 0, self::MAX_TEXT_LENGTH);
|
||||
}
|
||||
}
|
||||
$encoded = json_encode(
|
||||
is_array($value) ? $this->sanitize($value) : $value,
|
||||
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR
|
||||
);
|
||||
return mb_substr($encoded, 0, self::MAX_TEXT_LENGTH);
|
||||
}
|
||||
|
||||
private function sanitize(array $data): array
|
||||
{
|
||||
foreach ($data as $key => $value) {
|
||||
$normalized = strtolower((string)$key);
|
||||
if (in_array($normalized, self::SENSITIVE_KEYS, true)
|
||||
|| str_contains($normalized, 'password')
|
||||
|| str_contains($normalized, 'secret')
|
||||
) {
|
||||
$data[$key] = '[REDACTED]';
|
||||
} elseif (is_array($value)) {
|
||||
$data[$key] = $this->sanitize($value);
|
||||
}
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\SeventeenTrack\Model;
|
||||
|
||||
use Magento\Framework\App\Config\ScopeConfigInterface;
|
||||
use Magento\Framework\Encryption\EncryptorInterface;
|
||||
|
||||
class Config
|
||||
{
|
||||
private const BASE = 'esun_seventeen_track/';
|
||||
|
||||
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 getApiUrl(): string
|
||||
{
|
||||
return rtrim((string)$this->scopeConfig->getValue(self::BASE . 'general/api_url'), '/');
|
||||
}
|
||||
|
||||
public function getApiKey(): string
|
||||
{
|
||||
$value = (string)$this->scopeConfig->getValue(self::BASE . 'general/api_key');
|
||||
return $value !== '' ? (string)$this->encryptor->decrypt($value) : '';
|
||||
}
|
||||
|
||||
public function getBatchSize(): int
|
||||
{
|
||||
return min(40, max(1, (int)$this->scopeConfig->getValue(self::BASE . 'sync/batch_size')));
|
||||
}
|
||||
|
||||
public function shouldAutoReceive(): bool
|
||||
{
|
||||
return $this->scopeConfig->isSetFlag(self::BASE . 'sync/auto_receive');
|
||||
}
|
||||
|
||||
public function isWidgetEnabled(): bool
|
||||
{
|
||||
return $this->scopeConfig->isSetFlag(self::BASE . 'widget/enabled');
|
||||
}
|
||||
|
||||
public function getWidgetHeight(): int
|
||||
{
|
||||
return min(800, max(200, (int)$this->scopeConfig->getValue(self::BASE . 'widget/height')));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\SeventeenTrack\Model;
|
||||
|
||||
use Magento\Sales\Api\OrderRepositoryInterface;
|
||||
|
||||
class DeliveryStatusUpdater
|
||||
{
|
||||
public function __construct(
|
||||
private readonly Config $config,
|
||||
private readonly TrackingRepository $tracking,
|
||||
private readonly OrderRepositoryInterface $orders
|
||||
) {
|
||||
}
|
||||
|
||||
public function execute(array $orderIds): void
|
||||
{
|
||||
if (!$this->config->shouldAutoReceive()) {
|
||||
return;
|
||||
}
|
||||
foreach (array_unique(array_map('intval', $orderIds)) as $orderId) {
|
||||
if (!$this->tracking->isOrderDelivered($orderId)) {
|
||||
continue;
|
||||
}
|
||||
$order = $this->orders->get($orderId);
|
||||
if ((string)$order->getStatus() !== 'shipped') {
|
||||
continue;
|
||||
}
|
||||
$order->setStatus('received');
|
||||
$order->addCommentToStatusHistory(
|
||||
__('17TRACK confirmed that every shipment was delivered and signed for.'),
|
||||
'received',
|
||||
false
|
||||
);
|
||||
$this->orders->save($order);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\SeventeenTrack\Model\ResourceModel;
|
||||
|
||||
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
|
||||
|
||||
class ApiLog extends AbstractDb
|
||||
{
|
||||
protected $_connectionName = 'sales';
|
||||
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_init('esun_seventeen_track_api_log', 'entity_id');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\SeventeenTrack\Model\ResourceModel\ApiLog;
|
||||
|
||||
use Esun\SeventeenTrack\Model\ApiLog as ApiLogModel;
|
||||
use Esun\SeventeenTrack\Model\ResourceModel\ApiLog as ApiLogResource;
|
||||
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
|
||||
|
||||
class Collection extends AbstractCollection
|
||||
{
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_init(ApiLogModel::class, ApiLogResource::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\SeventeenTrack\Model\Source;
|
||||
|
||||
use Magento\Framework\Data\OptionSourceInterface;
|
||||
|
||||
class LogDirection implements OptionSourceInterface
|
||||
{
|
||||
public function toOptionArray(): array
|
||||
{
|
||||
return [
|
||||
['value' => 'outbound', 'label' => __('Outbound (Registration)')],
|
||||
['value' => 'inbound', 'label' => __('Inbound (Webhook)')],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\SeventeenTrack\Model\Source;
|
||||
|
||||
use Magento\Framework\Data\OptionSourceInterface;
|
||||
|
||||
class LogOperation implements OptionSourceInterface
|
||||
{
|
||||
public function toOptionArray(): array
|
||||
{
|
||||
return [
|
||||
['value' => 'register', 'label' => __('Tracking Registration')],
|
||||
['value' => 'webhook', 'label' => __('Webhook Push')],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\SeventeenTrack\Model\Source;
|
||||
|
||||
use Magento\Framework\Data\OptionSourceInterface;
|
||||
|
||||
class LogStatus implements OptionSourceInterface
|
||||
{
|
||||
public function toOptionArray(): array
|
||||
{
|
||||
return [
|
||||
['value' => 'success', 'label' => __('Success')],
|
||||
['value' => 'ignored', 'label' => __('Ignored')],
|
||||
['value' => 'error', 'label' => __('Error')],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\SeventeenTrack\Model;
|
||||
|
||||
use Magento\AdminNotification\Model\Inbox;
|
||||
use Magento\Framework\App\CacheInterface;
|
||||
|
||||
class SyncFailureNotifier
|
||||
{
|
||||
private const CACHE_PREFIX = 'esun_17track_notification_';
|
||||
private const CACHE_LIFETIME = 86400;
|
||||
|
||||
public function __construct(
|
||||
private readonly Inbox $inbox,
|
||||
private readonly CacheInterface $cache
|
||||
) {
|
||||
}
|
||||
|
||||
public function notify(?int $code, string $message): void
|
||||
{
|
||||
$identifier = self::CACHE_PREFIX . hash('sha256', (string)$code . '|' . $message);
|
||||
if ($this->cache->load($identifier) !== false) {
|
||||
return;
|
||||
}
|
||||
$title = in_array($code, [-18019907, -18019908], true)
|
||||
? (string)__('17TRACK quota is exhausted')
|
||||
: (string)__('17TRACK synchronization requires attention');
|
||||
$this->inbox->addCritical(
|
||||
$title,
|
||||
(string)__('%1 Check Stores > Configuration > Esun > 17TRACK.', $message)
|
||||
);
|
||||
$this->cache->save('1', $identifier, [], self::CACHE_LIFETIME);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\SeventeenTrack\Model;
|
||||
|
||||
use Magento\Framework\App\ResourceConnection;
|
||||
use Magento\Sales\Model\Order\Shipment\Track;
|
||||
|
||||
class TrackingRepository
|
||||
{
|
||||
private const TABLE = 'esun_seventeen_track';
|
||||
|
||||
public function __construct(private readonly ResourceConnection $resource)
|
||||
{
|
||||
}
|
||||
|
||||
public function enqueue(Track $track): void
|
||||
{
|
||||
if (!$track->getId() || !$track->getTrackNumber() || !$track->getParentId() || !$track->getOrderId()) {
|
||||
return;
|
||||
}
|
||||
$connection = $this->connection();
|
||||
$existing = $connection->fetchRow($connection->select()->from($this->table())
|
||||
->where('shipment_track_id = ?', (int)$track->getId())->limit(1));
|
||||
$number = trim((string)$track->getTrackNumber());
|
||||
$data = [
|
||||
'shipment_track_id' => (int)$track->getId(),
|
||||
'shipment_id' => (int)$track->getParentId(),
|
||||
'order_id' => (int)$track->getOrderId(),
|
||||
'tracking_number' => $number,
|
||||
];
|
||||
if ($existing && (string)$existing['tracking_number'] !== $number) {
|
||||
$data += [
|
||||
'carrier_code' => null,
|
||||
'sync_status' => 'pending',
|
||||
'error_code' => null,
|
||||
'attempt_count' => 0,
|
||||
'next_attempt_at' => null,
|
||||
'package_status' => null,
|
||||
'latest_event' => null,
|
||||
'delivered_at' => null,
|
||||
'last_error' => null,
|
||||
'response_data' => null,
|
||||
'last_synced_at' => null,
|
||||
];
|
||||
}
|
||||
$connection->insertOnDuplicate($this->table(), $data, array_keys($data));
|
||||
}
|
||||
|
||||
public function backfill(): void
|
||||
{
|
||||
$connection = $this->connection();
|
||||
$track = $this->resource->getTableName('sales_shipment_track');
|
||||
$select = $connection->select()->from(['track' => $track], [
|
||||
'shipment_track_id' => 'entity_id',
|
||||
'shipment_id' => 'parent_id',
|
||||
'order_id' => 'order_id',
|
||||
'tracking_number' => 'track_number',
|
||||
])->where('track.track_number IS NOT NULL')->where('track.track_number != ?', '');
|
||||
$connection->query($connection->insertFromSelect(
|
||||
$select,
|
||||
$this->table(),
|
||||
['shipment_track_id', 'shipment_id', 'order_id', 'tracking_number'],
|
||||
\Magento\Framework\DB\Adapter\AdapterInterface::INSERT_IGNORE
|
||||
));
|
||||
}
|
||||
|
||||
public function getPending(int $limit): array
|
||||
{
|
||||
return $this->connection()->fetchAll($this->connection()->select()->from($this->table())
|
||||
->where('sync_status IN (?)', ['pending', 'error'])
|
||||
->where('next_attempt_at IS NULL OR next_attempt_at <= UTC_TIMESTAMP()')
|
||||
->order('updated_at ASC')->limit($limit));
|
||||
}
|
||||
|
||||
public function getTracking(int $limit): array
|
||||
{
|
||||
return $this->connection()->fetchAll($this->connection()->select()->from($this->table())
|
||||
->where('sync_status = ?', 'tracking')->where('package_status IS NULL OR package_status != ?', 'Delivered')
|
||||
->where('next_attempt_at IS NULL OR next_attempt_at <= UTC_TIMESTAMP()')
|
||||
->order('last_synced_at ASC')->limit($limit));
|
||||
}
|
||||
|
||||
public function markRegistered(string $number, ?int $carrier): void
|
||||
{
|
||||
$this->connection()->update($this->table(), [
|
||||
'sync_status' => 'tracking',
|
||||
'carrier_code' => $carrier,
|
||||
'error_code' => null,
|
||||
'attempt_count' => 0,
|
||||
'next_attempt_at' => null,
|
||||
'last_error' => null,
|
||||
], ['tracking_number = ?' => $number]);
|
||||
}
|
||||
|
||||
public function markError(string $number, string $message, ?int $code, string $nextAttemptAt): void
|
||||
{
|
||||
$this->connection()->update($this->table(), [
|
||||
'sync_status' => 'error',
|
||||
'error_code' => $code,
|
||||
'attempt_count' => new \Zend_Db_Expr('attempt_count + 1'),
|
||||
'next_attempt_at' => $nextAttemptAt,
|
||||
'last_error' => mb_substr($message, 0, 2000),
|
||||
], ['tracking_number = ?' => $number]);
|
||||
}
|
||||
|
||||
public function markQueryError(string $number, string $message, ?int $code, string $nextAttemptAt): void
|
||||
{
|
||||
$this->connection()->update($this->table(), [
|
||||
'sync_status' => 'tracking',
|
||||
'error_code' => $code,
|
||||
'attempt_count' => new \Zend_Db_Expr('attempt_count + 1'),
|
||||
'next_attempt_at' => $nextAttemptAt,
|
||||
'last_error' => mb_substr($message, 0, 2000),
|
||||
], ['tracking_number = ?' => $number]);
|
||||
}
|
||||
|
||||
public function markPending(string $number, string $message, ?int $code, string $nextAttemptAt): void
|
||||
{
|
||||
$this->connection()->update($this->table(), [
|
||||
'sync_status' => 'pending',
|
||||
'carrier_code' => null,
|
||||
'error_code' => $code,
|
||||
'attempt_count' => new \Zend_Db_Expr('attempt_count + 1'),
|
||||
'next_attempt_at' => $nextAttemptAt,
|
||||
'last_error' => mb_substr($message, 0, 2000),
|
||||
], ['tracking_number = ?' => $number]);
|
||||
}
|
||||
|
||||
public function markRejected(string $number, string $message, ?int $code): void
|
||||
{
|
||||
$this->connection()->update($this->table(), [
|
||||
'sync_status' => 'rejected',
|
||||
'error_code' => $code,
|
||||
'attempt_count' => new \Zend_Db_Expr('attempt_count + 1'),
|
||||
'next_attempt_at' => null,
|
||||
'last_error' => mb_substr($message, 0, 2000),
|
||||
], ['tracking_number = ?' => $number]);
|
||||
}
|
||||
|
||||
public function saveTrackingInfo(string $number, array $info, string $serialized): array
|
||||
{
|
||||
$trackInfo = (array)($info['track_info'] ?? []);
|
||||
$latestStatus = (array)($trackInfo['latest_status'] ?? []);
|
||||
$latestEvent = (array)($trackInfo['latest_event'] ?? []);
|
||||
$status = (string)($latestStatus['status'] ?? $info['package_status'] ?? '');
|
||||
$event = (string)($latestEvent['description'] ?? $latestEvent['event_description'] ?? $info['latest_event_info'] ?? '');
|
||||
$deliveredAt = null;
|
||||
if ($status === 'Delivered') {
|
||||
$deliveredAt = $trackInfo['time_metrics']['delivery_time']
|
||||
?? $trackInfo['time_metrics']['delievery_time']
|
||||
?? $latestEvent['time_utc'] ?? gmdate('Y-m-d H:i:s');
|
||||
}
|
||||
$rows = $this->connection()->fetchAll($this->connection()->select()->from($this->table(), ['entity_id', 'order_id'])
|
||||
->where('tracking_number = ?', $number));
|
||||
$this->connection()->update($this->table(), [
|
||||
'carrier_code' => isset($info['carrier']) ? (int)$info['carrier'] : null,
|
||||
'sync_status' => 'tracking',
|
||||
'error_code' => null,
|
||||
'attempt_count' => 0,
|
||||
'next_attempt_at' => null,
|
||||
'package_status' => $status !== '' ? $status : null,
|
||||
'latest_event' => $event !== '' ? mb_substr($event, 0, 1024) : null,
|
||||
'delivered_at' => $deliveredAt ? $this->toMysqlDate((string)$deliveredAt) : null,
|
||||
'response_data' => $serialized,
|
||||
'last_error' => null,
|
||||
'last_synced_at' => gmdate('Y-m-d H:i:s'),
|
||||
], ['tracking_number = ?' => $number]);
|
||||
return array_values(array_unique(array_map('intval', array_column($rows, 'order_id'))));
|
||||
}
|
||||
|
||||
public function saveStoppedInfo(string $number, string $serialized): void
|
||||
{
|
||||
$this->connection()->update($this->table(), [
|
||||
'sync_status' => 'stopped',
|
||||
'error_code' => null,
|
||||
'next_attempt_at' => null,
|
||||
'response_data' => $serialized,
|
||||
'last_error' => null,
|
||||
'last_synced_at' => gmdate('Y-m-d H:i:s'),
|
||||
], ['tracking_number = ?' => $number]);
|
||||
}
|
||||
|
||||
public function isOrderDelivered(int $orderId): bool
|
||||
{
|
||||
$select = $this->connection()->select()->from($this->table(), [
|
||||
'total' => new \Zend_Db_Expr('COUNT(*)'),
|
||||
'delivered' => new \Zend_Db_Expr("SUM(package_status = 'Delivered')"),
|
||||
])->where('order_id = ?', $orderId);
|
||||
$row = $this->connection()->fetchRow($select) ?: [];
|
||||
return (int)($row['total'] ?? 0) > 0 && (int)($row['total'] ?? 0) === (int)($row['delivered'] ?? 0);
|
||||
}
|
||||
|
||||
private function toMysqlDate(string $value): string
|
||||
{
|
||||
try {
|
||||
return (new \DateTimeImmutable($value))->setTimezone(new \DateTimeZone('UTC'))->format('Y-m-d H:i:s');
|
||||
} catch (\Throwable) {
|
||||
return gmdate('Y-m-d H:i:s');
|
||||
}
|
||||
}
|
||||
|
||||
private function connection(): \Magento\Framework\DB\Adapter\AdapterInterface
|
||||
{
|
||||
return $this->resource->getConnection('sales');
|
||||
}
|
||||
|
||||
private function table(): string
|
||||
{
|
||||
return $this->resource->getTableName(self::TABLE);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\SeventeenTrack\Model;
|
||||
|
||||
use Magento\Framework\Exception\AuthenticationException;
|
||||
use Magento\Framework\Exception\InputException;
|
||||
use Magento\Framework\Serialize\Serializer\Json;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
class WebhookProcessor
|
||||
{
|
||||
private const MAX_BODY_BYTES = 2097152;
|
||||
|
||||
public function __construct(
|
||||
private readonly Config $config,
|
||||
private readonly TrackingRepository $tracking,
|
||||
private readonly DeliveryStatusUpdater $deliveryStatusUpdater,
|
||||
private readonly Json $json,
|
||||
private readonly LoggerInterface $logger
|
||||
) {
|
||||
}
|
||||
|
||||
/** @return array{event:string,tracking_number:string,status:string,message:string} */
|
||||
public function execute(string $rawBody, string $signature): array
|
||||
{
|
||||
$apiKey = $this->config->getApiKey();
|
||||
if (!$this->config->isEnabled() || $apiKey === '') {
|
||||
throw new \RuntimeException('17TRACK is disabled or the API key is missing.');
|
||||
}
|
||||
if ($rawBody === '' || strlen($rawBody) > self::MAX_BODY_BYTES) {
|
||||
throw new InputException(__('The 17TRACK webhook body is empty or too large.'));
|
||||
}
|
||||
$this->verifySignature($rawBody, $signature, $apiKey);
|
||||
|
||||
try {
|
||||
$payload = $this->json->unserialize($rawBody);
|
||||
} catch (\InvalidArgumentException $exception) {
|
||||
throw new InputException(__('The 17TRACK webhook body is not valid JSON.'), $exception);
|
||||
}
|
||||
if (!is_array($payload) || !is_array($payload['data'] ?? null)) {
|
||||
throw new InputException(__('The 17TRACK webhook payload is missing data.'));
|
||||
}
|
||||
|
||||
$event = (string)($payload['event'] ?? '');
|
||||
$data = $payload['data'];
|
||||
$number = trim((string)($data['number'] ?? ''));
|
||||
if ($number === '') {
|
||||
throw new InputException(__('The 17TRACK webhook payload is missing a tracking number.'));
|
||||
}
|
||||
|
||||
if ($event === 'TRACKING_UPDATED') {
|
||||
$orderIds = $this->tracking->saveTrackingInfo(
|
||||
$number,
|
||||
$data,
|
||||
$this->json->serialize($data)
|
||||
);
|
||||
if ($orderIds === []) {
|
||||
$this->logger->warning('Ignored a 17TRACK webhook for an unknown tracking number.', [
|
||||
'tracking_number' => $number,
|
||||
]);
|
||||
return [
|
||||
'event' => $event,
|
||||
'tracking_number' => $number,
|
||||
'status' => 'ignored',
|
||||
'message' => 'Unknown tracking number.',
|
||||
];
|
||||
}
|
||||
$this->deliveryStatusUpdater->execute($orderIds);
|
||||
return [
|
||||
'event' => $event,
|
||||
'tracking_number' => $number,
|
||||
'status' => 'success',
|
||||
'message' => 'Tracking update processed.',
|
||||
];
|
||||
}
|
||||
|
||||
if ($event === 'TRACKING_STOPPED') {
|
||||
$this->tracking->saveStoppedInfo($number, $this->json->serialize($data));
|
||||
return [
|
||||
'event' => $event,
|
||||
'tracking_number' => $number,
|
||||
'status' => 'success',
|
||||
'message' => 'Tracking stopped event processed.',
|
||||
];
|
||||
}
|
||||
|
||||
$this->logger->info('Ignored an unsupported 17TRACK webhook event.', [
|
||||
'event' => $event,
|
||||
'tracking_number' => $number,
|
||||
]);
|
||||
return [
|
||||
'event' => $event,
|
||||
'tracking_number' => $number,
|
||||
'status' => 'ignored',
|
||||
'message' => 'Unsupported webhook event.',
|
||||
];
|
||||
}
|
||||
|
||||
private function verifySignature(string $rawBody, string $signature, string $apiKey): void
|
||||
{
|
||||
$signature = strtolower(trim($signature));
|
||||
if (!preg_match('/^[a-f0-9]{64}$/', $signature)) {
|
||||
throw new AuthenticationException(__('The 17TRACK webhook signature is missing or invalid.'));
|
||||
}
|
||||
$expected = hash('sha256', $rawBody . '/' . $apiKey);
|
||||
if (!hash_equals($expected, $signature)) {
|
||||
throw new AuthenticationException(__('The 17TRACK webhook signature is missing or invalid.'));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user