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,52 @@
<?php
declare(strict_types=1);
namespace Esun\SeventeenTrack\Block\Adminhtml\Log;
use Esun\SeventeenTrack\Model\ApiLogFactory;
use Magento\Backend\Block\Template;
use Magento\Backend\Block\Template\Context;
class View extends Template
{
private ?array $record = null;
public function __construct(
Context $context,
private readonly ApiLogFactory $apiLogFactory,
array $data = []
) {
parent::__construct($context, $data);
}
/** @return array<string, mixed> */
public function getRecord(): array
{
if ($this->record === null) {
$model = $this->apiLogFactory->create()->load((int)$this->getRequest()->getParam('id'));
$this->record = $model->getId() ? $model->getData() : [];
}
return $this->record;
}
public function getBackUrl(): string
{
return $this->getUrl('esun_seventeen_track/log/index');
}
public function prettyPayload(mixed $payload): string
{
if ($payload === null || $payload === '') {
return (string)__('No data recorded.');
}
try {
$decoded = is_string($payload) ? json_decode($payload, true, 512, JSON_THROW_ON_ERROR) : $payload;
return (string)json_encode(
$decoded,
JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR
);
} catch (\JsonException) {
return is_string($payload) ? $payload : (string)__('Unable to display data.');
}
}
}
@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
namespace Esun\SeventeenTrack\Block\Order;
use Esun\SeventeenTrack\Model\Config;
use Magento\Framework\Locale\ResolverInterface;
use Magento\Framework\Registry;
use Magento\Framework\View\Element\Template;
use Magento\Sales\Model\Order;
class Tracking extends Template
{
public function __construct(
Template\Context $context,
private readonly Registry $registry,
private readonly Config $config,
private readonly ResolverInterface $localeResolver,
array $data = []
) {
parent::__construct($context, $data);
}
public function canDisplay(): bool
{
return $this->config->isWidgetEnabled() && $this->getTracks() !== [];
}
public function getTracks(): array
{
$order = $this->registry->registry('current_order');
if (!$order instanceof Order) {
return [];
}
$tracks = [];
foreach ($order->getShipmentsCollection() as $shipment) {
foreach ($shipment->getAllTracks() as $track) {
$number = trim((string)$track->getTrackNumber());
if ($number !== '') {
$tracks[$number] = [
'number' => $number,
'title' => (string)($track->getTitle() ?: __('Shipment')),
];
}
}
}
return array_values($tracks);
}
public function getWidgetHeight(): int
{
return $this->config->getWidgetHeight();
}
public function getWidgetLanguage(): string
{
$locale = str_replace('_', '-', $this->localeResolver->getLocale());
$map = ['zh-CN' => 'zh-cn', 'zh-HK' => 'zh-hk', 'zh-TW' => 'zh-tw', 'pt-BR' => 'pt'];
return $map[$locale] ?? strtolower(substr($locale, 0, 2));
}
}
@@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace Esun\SeventeenTrack\Console\Command;
use Esun\SeventeenTrack\Cron\SyncTracking;
use Esun\SeventeenTrack\Model\Config;
use Magento\Framework\Console\Cli;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class SyncCommand extends Command
{
public function __construct(
private readonly SyncTracking $sync,
private readonly Config $config
) {
parent::__construct('esun:17track:sync');
}
protected function configure(): void
{
$this->setDescription('Register shipment numbers and synchronize delivery status with 17TRACK.');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
if (!$this->config->isEnabled() || $this->config->getApiKey() === '') {
$output->writeln('<error>17TRACK is disabled or the API key is missing.</error>');
return Cli::RETURN_FAILURE;
}
try {
$this->sync->execute();
$output->writeln('<info>17TRACK synchronization completed successfully.</info>');
return Cli::RETURN_SUCCESS;
} catch (\Throwable $exception) {
$output->writeln('<error>' . $exception->getMessage() . '</error>');
return Cli::RETURN_FAILURE;
}
}
}
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace Esun\SeventeenTrack\Controller\Adminhtml\Log;
use Magento\Backend\App\Action;
use Magento\Framework\View\Result\PageFactory;
class Index extends Action
{
public const ADMIN_RESOURCE = 'Esun_SeventeenTrack::logs';
public function __construct(Action\Context $context, private readonly PageFactory $pageFactory)
{
parent::__construct($context);
}
public function execute()
{
$page = $this->pageFactory->create();
$page->setActiveMenu(self::ADMIN_RESOURCE);
$page->getConfig()->getTitle()->prepend(__('17TRACK API Logs'));
return $page;
}
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace Esun\SeventeenTrack\Controller\Adminhtml\Log;
use Esun\SeventeenTrack\Model\ApiLogFactory;
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_SeventeenTrack::logs';
public function __construct(
Action\Context $context,
private readonly PageFactory $pageFactory,
private readonly ApiLogFactory $apiLogFactory
) {
parent::__construct($context);
}
public function execute(): Page|Redirect
{
$log = $this->apiLogFactory->create()->load((int)$this->getRequest()->getParam('id'));
if (!$log->getId()) {
$this->messageManager->addErrorMessage(__('The 17TRACK API log no longer exists.'));
return $this->resultRedirectFactory->create()->setPath('*/*/index');
}
$page = $this->pageFactory->create();
$page->setActiveMenu(self::ADMIN_RESOURCE);
$page->getConfig()->getTitle()->prepend(__('17TRACK API Log #%1', $log->getId()));
return $page;
}
}
@@ -0,0 +1,104 @@
<?php
declare(strict_types=1);
namespace Esun\SeventeenTrack\Controller\Webhook;
use Esun\SeventeenTrack\Model\ApiLogWriter;
use Esun\SeventeenTrack\Model\WebhookProcessor;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\App\CsrfAwareActionInterface;
use Magento\Framework\App\Request\Http;
use Magento\Framework\App\Request\InvalidRequestException;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Controller\Result\Json;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Framework\Exception\InputException;
use Psr\Log\LoggerInterface;
class Index implements HttpPostActionInterface, CsrfAwareActionInterface
{
public function __construct(
private readonly Http $request,
private readonly JsonFactory $jsonFactory,
private readonly WebhookProcessor $processor,
private readonly ApiLogWriter $apiLog,
private readonly LoggerInterface $logger
) {
}
public function execute(): Json
{
$result = $this->jsonFactory->create();
$rawBody = (string)$this->request->getContent();
$startedAt = microtime(true);
$context = $this->apiLog->getWebhookContext($rawBody);
try {
$processingResult = $this->processor->execute(
$rawBody,
(string)$this->request->getHeader('sign')
);
$this->writeWebhookLog($context + $processingResult, $rawBody, 200, $startedAt);
return $result->setData(['success' => true]);
} catch (AuthenticationException $exception) {
$this->logger->warning('Rejected a 17TRACK webhook with an invalid signature.');
$this->writeWebhookLog($context + [
'status' => 'error',
'message' => $exception->getMessage(),
], $rawBody, 401, $startedAt);
return $result->setHttpResponseCode(401)->setData([
'success' => false,
'message' => $exception->getMessage(),
]);
} catch (InputException $exception) {
$this->writeWebhookLog($context + [
'status' => 'error',
'message' => $exception->getMessage(),
], $rawBody, 400, $startedAt);
return $result->setHttpResponseCode(400)->setData([
'success' => false,
'message' => $exception->getMessage(),
]);
} catch (\Throwable $exception) {
$this->logger->critical('Unable to process a 17TRACK webhook.', ['exception' => $exception]);
$this->writeWebhookLog($context + [
'status' => 'error',
'message' => $exception->getMessage(),
], $rawBody, 500, $startedAt);
return $result->setHttpResponseCode(500)->setData([
'success' => false,
'message' => (string)__('Unable to process the webhook.'),
]);
}
}
public function createCsrfValidationException(RequestInterface $request): ?InvalidRequestException
{
return null;
}
public function validateForCsrf(RequestInterface $request): ?bool
{
// 17TRACK cannot know Magento's form key; authenticity is verified with its signed raw request body.
return true;
}
private function writeWebhookLog(array $data, string $rawBody, int $httpStatus, float $startedAt): void
{
$this->apiLog->write([
'direction' => 'inbound',
'operation' => 'webhook',
'api_path' => $this->apiLog->getWebhookPath(),
'order_id' => $data['order_id'] ?? null,
'order_number' => $data['order_number'] ?? null,
'tracking_number' => $data['tracking_number'] ?? null,
'event' => $data['event'] ?? null,
'status' => (string)($data['status'] ?? 'error'),
'http_status' => $httpStatus,
'message' => (string)($data['message'] ?? ''),
'request_data' => $rawBody,
'response_data' => ['success' => $httpStatus === 200],
'duration_ms' => max(0, (int)round((microtime(true) - $startedAt) * 1000)),
]);
}
}
@@ -0,0 +1,336 @@
<?php
declare(strict_types=1);
namespace Esun\SeventeenTrack\Cron;
use Esun\SeventeenTrack\Model\Api\Client;
use Esun\SeventeenTrack\Model\ApiLogWriter;
use Esun\SeventeenTrack\Model\Config;
use Esun\SeventeenTrack\Model\DeliveryStatusUpdater;
use Esun\SeventeenTrack\Model\SyncFailureNotifier;
use Esun\SeventeenTrack\Model\TrackingRepository;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Sales\Api\OrderRepositoryInterface;
use Psr\Log\LoggerInterface;
class SyncTracking
{
private const TRANSIENT_RETRY_MINUTES = 30;
private const QUOTA_RETRY_MINUTES = 360;
public function __construct(
private readonly Config $config,
private readonly Client $client,
private readonly ApiLogWriter $apiLog,
private readonly TrackingRepository $tracking,
private readonly SyncFailureNotifier $notifier,
private readonly DeliveryStatusUpdater $deliveryStatusUpdater,
private readonly OrderRepositoryInterface $orders,
private readonly Json $json,
private readonly LoggerInterface $logger
) {
}
public function execute(): void
{
if (!$this->config->isEnabled() || $this->config->getApiKey() === '') {
return;
}
try {
$this->tracking->backfill();
$failures = array_merge($this->registerPending(), $this->refreshTracking());
} catch (\Throwable $exception) {
$this->logger->error('17TRACK synchronization failed.', ['exception' => $exception]);
$this->notifySafely($this->getApiErrorCode($exception), $exception->getMessage());
throw $exception;
}
if ($failures !== []) {
foreach ($failures as $failure) {
$this->notifySafely($failure['code'], $failure['message']);
}
$message = sprintf(
'17TRACK synchronization completed with %d failed tracking number(s): %s',
count($failures),
implode(', ', array_unique(array_column($failures, 'number')))
);
$this->logger->error($message, ['failures' => $failures]);
throw new \RuntimeException($message);
}
}
private function registerPending(): array
{
$rows = $this->tracking->getPending($this->config->getBatchSize());
if (!$rows) {
return [];
}
$failures = [];
$payload = array_map(fn(array $row): array => $this->buildRegistrationPayload($row), $rows);
$payloadByNumber = [];
foreach ($payload as $item) {
$payloadByNumber[(string)$item['number']] = $item;
}
$batchId = bin2hex(random_bytes(8));
$startedAt = microtime(true);
try {
$response = $this->client->register($payload);
} catch (\Throwable $exception) {
$code = $this->getApiErrorCode($exception);
foreach ($rows as $row) {
$this->tracking->markError(
(string)$row['tracking_number'],
$exception->getMessage(),
$code,
$this->retryAt($this->getRetryMinutes($code))
);
$number = (string)$row['tracking_number'];
$this->writeRegistrationLog(
$row,
$payloadByNumber[$number] ?? ['number' => $number],
$this->client->getLastBody(),
'error',
$batchId,
$startedAt,
$exception->getMessage(),
$code
);
}
throw $exception;
}
$handled = [];
foreach ((array)($response['data']['accepted'] ?? []) as $accepted) {
$number = trim((string)($accepted['number'] ?? ''));
if ($number === '') {
continue;
}
$this->tracking->markRegistered($number, isset($accepted['carrier']) ? (int)$accepted['carrier'] : null);
$handled[$number] = true;
$row = $this->findRow($rows, $number);
$this->writeRegistrationLog(
$row,
$payloadByNumber[$number] ?? ['number' => $number],
$accepted,
'success',
$batchId,
$startedAt,
'Tracking number registered.'
);
}
foreach ((array)($response['data']['rejected'] ?? []) as $rejected) {
$message = (string)($rejected['error']['message'] ?? 'Tracking number registration was rejected.');
$code = (int)($rejected['error']['code'] ?? 0);
$number = trim((string)($rejected['number'] ?? ''));
if ($number === '') {
continue;
}
$handled[$number] = true;
$status = 'error';
if ($code === -18019901) {
// Existing registrations can be queried normally.
$carrier = isset($rejected['carrier']) ? (int)$rejected['carrier'] : null;
$this->tracking->markRegistered($number, $carrier);
$status = 'success';
} elseif (in_array($code, [-18010003, -18019907, -18019908], true)) {
$minutes = $this->getRetryMinutes($code);
$this->tracking->markError($number, $message, $code, $this->retryAt($minutes));
$failures[] = ['number' => $number, 'code' => $code, 'message' => $message];
} else {
$this->tracking->markRejected($number, $message, $code);
$failures[] = ['number' => $number, 'code' => $code, 'message' => $message];
}
$this->writeRegistrationLog(
$this->findRow($rows, $number),
$payloadByNumber[$number] ?? ['number' => $number],
$rejected,
$status,
$batchId,
$startedAt,
$message,
$code
);
}
foreach ($rows as $row) {
$number = (string)$row['tracking_number'];
if (isset($handled[$number])) {
continue;
}
$message = '17TRACK registration response did not contain this tracking number.';
$this->tracking->markError($number, $message, null, $this->retryAt(self::TRANSIENT_RETRY_MINUTES));
$failures[] = ['number' => $number, 'code' => null, 'message' => $message];
$this->writeRegistrationLog(
$row,
$payloadByNumber[$number] ?? ['number' => $number],
$response,
'error',
$batchId,
$startedAt,
$message
);
}
return $failures;
}
private function refreshTracking(): array
{
$rows = $this->tracking->getTracking($this->config->getBatchSize());
if (!$rows) {
return [];
}
$failures = [];
$payload = [];
foreach ($rows as $row) {
$item = ['number' => (string)$row['tracking_number']];
if ((int)$row['carrier_code'] > 0) {
$item['carrier'] = (int)$row['carrier_code'];
}
$payload[] = $item;
}
try {
$response = $this->client->getTrackInfo($payload);
} catch (\Throwable $exception) {
$code = $this->getApiErrorCode($exception);
foreach ($rows as $row) {
$this->tracking->markQueryError(
(string)$row['tracking_number'],
$exception->getMessage(),
$code,
$this->retryAt($this->getRetryMinutes($code))
);
}
throw $exception;
}
$orderIds = [];
foreach ((array)($response['data']['accepted'] ?? []) as $info) {
if (empty($info['number'])) {
continue;
}
$ids = $this->tracking->saveTrackingInfo(
(string)$info['number'],
$info,
$this->json->serialize($info)
);
$orderIds = array_merge($orderIds, $ids);
}
foreach ((array)($response['data']['rejected'] ?? []) as $rejected) {
$number = (string)($rejected['number'] ?? '');
$message = (string)($rejected['error']['message'] ?? 'Tracking query was rejected.');
$code = (int)($rejected['error']['code'] ?? 0);
if ($code === -18019902) {
$this->tracking->markPending(
$number,
$message,
$code,
$this->retryAt(self::TRANSIENT_RETRY_MINUTES)
);
$failures[] = ['number' => $number, 'code' => $code, 'message' => $message];
} else {
$minutes = $this->getRetryMinutes($code);
$this->tracking->markQueryError($number, $message, $code, $this->retryAt($minutes));
if ($code !== -18019909) {
$failures[] = ['number' => $number, 'code' => $code, 'message' => $message];
}
}
}
$this->deliveryStatusUpdater->execute($orderIds);
return $failures;
}
private function buildRegistrationPayload(array $row): array
{
$payload = ['number' => (string)$row['tracking_number'], 'tag' => (string)$row['order_id']];
try {
$order = $this->orders->get((int)$row['order_id']);
$payload['tag'] = (string)$order->getIncrementId();
$payload['order_no'] = (string)$order->getIncrementId();
$payload['order_time'] = (string)$order->getCreatedAt();
$address = $order->getShippingAddress();
if ($address) {
$optional = [
'destination_country' => strtoupper((string)$address->getCountryId()),
'destination_postal_code' => (string)$address->getPostcode(),
'destination_city' => (string)$address->getCity(),
];
$phone = preg_replace('/\D+/', '', (string)$address->getTelephone()) ?: '';
if ($phone !== '') {
$optional['phone_number_last_4'] = substr($phone, -4);
}
foreach ($optional as $key => $value) {
if ($value !== '') {
$payload[$key] = $value;
}
}
}
} catch (\Throwable $exception) {
$this->logger->warning('Could not add order metadata to a 17TRACK registration.', [
'order_id' => (int)$row['order_id'],
'exception' => $exception,
]);
}
return $payload;
}
private function retryAt(int $minutes): string
{
return gmdate('Y-m-d H:i:s', time() + ($minutes * 60));
}
private function getApiErrorCode(\Throwable $exception): ?int
{
$code = (int)$exception->getCode();
return $code !== 0 ? $code : null;
}
private function getRetryMinutes(?int $code): int
{
return in_array($code, [-18019907, -18019908], true)
? self::QUOTA_RETRY_MINUTES
: self::TRANSIENT_RETRY_MINUTES;
}
private function notifySafely(?int $code, string $message): void
{
try {
$this->notifier->notify($code, $message);
} catch (\Throwable $exception) {
$this->logger->warning('Unable to create a 17TRACK admin notification.', ['exception' => $exception]);
}
}
private function findRow(array $rows, string $number): array
{
foreach ($rows as $row) {
if ((string)($row['tracking_number'] ?? '') === $number) {
return $row;
}
}
return ['tracking_number' => $number];
}
private function writeRegistrationLog(
array $row,
array $request,
mixed $response,
string $status,
string $batchId,
float $startedAt,
string $message,
?int $errorCode = null
): void {
$this->apiLog->write([
'direction' => 'outbound',
'operation' => 'register',
'api_path' => $this->apiLog->getRegistrationPath(),
'batch_id' => $batchId,
'order_id' => isset($row['order_id']) ? (int)$row['order_id'] : null,
'order_number' => isset($request['order_no']) ? (string)$request['order_no'] : null,
'tracking_number' => isset($request['number']) ? (string)$request['number'] : null,
'status' => $status,
'http_status' => $this->client->getLastStatus(),
'error_code' => $errorCode,
'message' => $message,
'request_data' => $request,
'response_data' => $response,
'duration_ms' => max(0, (int)round((microtime(true) - $startedAt) * 1000)),
]);
}
}
@@ -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.'));
}
}
}
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace Esun\SeventeenTrack\Observer;
use Esun\SeventeenTrack\Model\TrackingRepository;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Sales\Model\Order\Shipment\Track;
class EnqueueTrack implements ObserverInterface
{
public function __construct(private readonly TrackingRepository $tracking)
{
}
public function execute(Observer $observer): void
{
$track = $observer->getEvent()->getTrack();
if ($track instanceof Track) {
$this->tracking->enqueue($track);
}
}
}
+54
View File
@@ -0,0 +1,54 @@
# Esun_SeventeenTrack
Magento 2 integration for 17TRACK v2.4.
## Behavior
- The customer order detail page calls `YQV5.trackSingle()` for each Magento shipment tracking number. There is no search input.
- Every ten minutes, cron registers new and existing Magento shipment tracking numbers in batches of at most 40, then calls `gettrackinfo`.
- A shipment is signed for when `track_info.latest_status.status` is `Delivered`.
- If automatic receipt is enabled, a `shipped` order changes to `received` only after all of its tracking numbers are delivered.
- Rejected API rows make the Magento cron record fail instead of appearing successful. Transient failures retry after 30 minutes; quota failures retry after six hours and create a deduplicated critical admin notification.
- Query failures keep an already registered number in the tracking state. Error `-18019902` moves it back to registration instead of leaving it in a query-error loop.
- Signed Webhook notifications update the same tracking table immediately; cron remains as a recovery path when a push is delayed or missed.
- Every registration result and every incoming webhook outcome is written to `esun_seventeen_track_api_log`. API keys, signatures, phone numbers, postal codes, addresses, and similar sensitive fields are redacted before storage.
## Configuration
On a new environment, enable and install the module first:
```bash
php bin/magento module:enable Esun_SeventeenTrack
php bin/magento setup:upgrade --keep-generated
php bin/magento cache:flush
```
Go to **Stores > Configuration > Esun > 17TRACK**:
1. Enter the API key. Magento stores it through the encrypted configuration backend.
2. Set **Enabled** to Yes.
3. Leave **Mark Orders Received Automatically** enabled to update delivered orders.
The customer widget is independent of the server API toggle and can be enabled or disabled separately.
In the 17TRACK API dashboard, set **Small package tracking push > URL** to:
```text
https://www.esun3d.com/seventeentrack/webhook/index
```
The endpoint accepts POST requests only, verifies the `sign` header against the exact raw body and encrypted API key, and returns HTTP 200 after successful processing.
## Operations
Run one synchronization manually and receive a non-zero exit status when any tracking number fails:
```bash
php bin/magento esun:17track:sync
```
Inspect `esun_seventeen_track.error_code`, `attempt_count`, `next_attempt_at`, and `last_error` when diagnosing a number. A quota error must be resolved in the 17TRACK account before a later retry can register the shipment.
Go to **Esun > 17TRACK > API Logs** in Magento Admin to filter logs by time, direction, operation, status, order number, tracking number, webhook event, HTTP status, or error code. Use **View Details** to inspect the sanitized request and response. Registration rows from the same API batch share a batch ID.
The customer-facing widget is a cross-origin 17TRACK iframe. If Chrome DevTools has **Pause on caught exceptions** enabled, Chrome can pause inside 17TRACK, Cloudflare, or another third-party script even though this module contains no `debugger` statement. Disable that DevTools option or add the third-party script to the Ignore List; this cannot be reliably controlled by Magento code inside the parent page.
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace Esun\SeventeenTrack\Test\Unit\Model;
use Esun\SeventeenTrack\Model\Config;
use Esun\SeventeenTrack\Model\DeliveryStatusUpdater;
use Esun\SeventeenTrack\Model\TrackingRepository;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Order;
use PHPUnit\Framework\TestCase;
class DeliveryStatusUpdaterTest extends TestCase
{
public function testMarksShippedOrderReceivedWhenEveryPackageIsDelivered(): void
{
$config = $this->createMock(Config::class);
$config->method('shouldAutoReceive')->willReturn(true);
$tracking = $this->createMock(TrackingRepository::class);
$tracking->expects(self::once())->method('isOrderDelivered')->with(29)->willReturn(true);
$order = $this->createMock(Order::class);
$order->method('getStatus')->willReturn('shipped');
$order->expects(self::once())->method('setStatus')->with('received')->willReturnSelf();
$order->expects(self::once())->method('addCommentToStatusHistory')->willReturnSelf();
$orders = $this->createMock(OrderRepositoryInterface::class);
$orders->method('get')->with(29)->willReturn($order);
$orders->expects(self::once())->method('save')->with($order)->willReturn($order);
(new DeliveryStatusUpdater($config, $tracking, $orders))->execute([29, 29]);
}
public function testDoesNotLoadOrderUntilEveryPackageIsDelivered(): void
{
$config = $this->createMock(Config::class);
$config->method('shouldAutoReceive')->willReturn(true);
$tracking = $this->createMock(TrackingRepository::class);
$tracking->method('isOrderDelivered')->with(29)->willReturn(false);
$orders = $this->createMock(OrderRepositoryInterface::class);
$orders->expects(self::never())->method('get');
$orders->expects(self::never())->method('save');
(new DeliveryStatusUpdater($config, $tracking, $orders))->execute([29]);
}
}
@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
namespace Esun\SeventeenTrack\Test\Unit\Model;
use Esun\SeventeenTrack\Model\Config;
use Esun\SeventeenTrack\Model\DeliveryStatusUpdater;
use Esun\SeventeenTrack\Model\TrackingRepository;
use Esun\SeventeenTrack\Model\WebhookProcessor;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Framework\Serialize\Serializer\Json;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
class WebhookProcessorTest extends TestCase
{
private const KEY = 'test-key';
private Config&MockObject $config;
private TrackingRepository&MockObject $tracking;
private DeliveryStatusUpdater&MockObject $deliveryStatusUpdater;
private WebhookProcessor $processor;
protected function setUp(): void
{
$this->config = $this->createMock(Config::class);
$this->config->method('isEnabled')->willReturn(true);
$this->config->method('getApiKey')->willReturn(self::KEY);
$this->tracking = $this->createMock(TrackingRepository::class);
$this->deliveryStatusUpdater = $this->createMock(DeliveryStatusUpdater::class);
$this->processor = new WebhookProcessor(
$this->config,
$this->tracking,
$this->deliveryStatusUpdater,
new Json(),
new NullLogger()
);
}
public function testProcessesSignedTrackingUpdate(): void
{
$body = '{"event":"TRACKING_UPDATED","data":{"number":"TEST123","track_info":{"latest_status":{"status":"Delivered"}}}}';
$this->tracking->expects(self::once())->method('saveTrackingInfo')
->with('TEST123', self::isType('array'), self::isType('string'))
->willReturn([29]);
$this->deliveryStatusUpdater->expects(self::once())->method('execute')->with([29]);
$result = $this->processor->execute($body, $this->sign($body));
self::assertSame('success', $result['status']);
self::assertSame('TEST123', $result['tracking_number']);
}
public function testRejectsInvalidSignatureBeforeUpdatingTracking(): void
{
$body = '{"event":"TRACKING_UPDATED","data":{"number":"TEST123"}}';
$this->tracking->expects(self::never())->method('saveTrackingInfo');
$this->expectException(AuthenticationException::class);
$this->processor->execute($body, str_repeat('0', 64));
}
public function testProcessesTrackingStoppedEvent(): void
{
$body = '{"event":"TRACKING_STOPPED","data":{"number":"TEST123","carrier":3011}}';
$this->tracking->expects(self::once())->method('saveStoppedInfo')
->with('TEST123', self::isType('string'));
$this->deliveryStatusUpdater->expects(self::never())->method('execute');
$result = $this->processor->execute($body, $this->sign($body));
self::assertSame('success', $result['status']);
self::assertSame('TRACKING_STOPPED', $result['event']);
}
private function sign(string $body): string
{
return hash('sha256', $body . '/' . self::KEY);
}
}
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace Esun\SeventeenTrack\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 LogActions 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_seventeen_track/log/view', [
'id' => (int)$item['entity_id'],
]),
'label' => __('View Details'),
];
}
unset($item);
return $dataSource;
}
}
@@ -0,0 +1,10 @@
{
"name": "esun/module-seventeen-track",
"description": "17TRACK widget and delivery status synchronization",
"type": "magento2-module",
"version": "1.0.0",
"autoload": {
"files": ["registration.php"],
"psr-4": {"Esun\\SeventeenTrack\\": ""}
}
}
+12
View File
@@ -0,0 +1,12 @@
<?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_SeventeenTrack::config" title="Configure 17TRACK" sortOrder="90"/>
<resource id="Esun_SeventeenTrack::logs" title="View 17TRACK API Logs" sortOrder="91"/>
</resource>
</resources>
</acl>
</config>
@@ -0,0 +1,11 @@
<?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_SeventeenTrack::root" title="17TRACK" module="Esun_SeventeenTrack"
sortOrder="90" parent="Esun_ImageManager::esun" resource="Esun_SeventeenTrack::logs"/>
<add id="Esun_SeventeenTrack::logs" title="API Logs" module="Esun_SeventeenTrack"
sortOrder="10" parent="Esun_SeventeenTrack::root" action="esun_seventeen_track/log/index"
resource="Esun_SeventeenTrack::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_seventeen_track" frontName="esun_seventeen_track">
<module name="Esun_SeventeenTrack" before="Magento_Backend"/>
</route>
</router>
</config>
@@ -0,0 +1,25 @@
<?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>
<section id="esun_seventeen_track" translate="label" sortOrder="170" showInDefault="1" showInWebsite="0" showInStore="0">
<label>17TRACK</label><tab>esun</tab><resource>Esun_SeventeenTrack::config</resource>
<group id="general" translate="label" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">
<label>API Connection</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_url" translate="label" type="text" sortOrder="20" showInDefault="1" showInWebsite="0" showInStore="0"><label>API Base URL</label></field>
<field id="api_key" translate="label comment" type="obscure" sortOrder="30" showInDefault="1" showInWebsite="0" showInStore="0"><label>API Key</label><backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model><comment>Stored encrypted. It is only sent to api.17track.net in the 17token request header.</comment></field>
</group>
<group id="sync" translate="label" sortOrder="20" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Delivery Synchronization</label>
<field id="batch_size" translate="label comment" type="text" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0"><label>Batch Size</label><comment>Maximum 40, matching the 17TRACK API limit.</comment></field>
<field id="auto_receive" translate="label comment" type="select" sortOrder="20" showInDefault="1" showInWebsite="0" showInStore="0"><label>Mark Orders Received Automatically</label><source_model>Magento\Config\Model\Config\Source\Yesno</source_model><comment>When every tracking number on a shipped order is Delivered, change its status to Received.</comment></field>
</group>
<group id="widget" translate="label" sortOrder="30" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Customer Order Widget</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="height" translate="label comment" type="text" sortOrder="20" showInDefault="1" showInWebsite="0" showInStore="0"><label>Widget Height</label><comment>From 200 to 800 pixels.</comment></field>
</group>
</section>
</system>
</config>
@@ -0,0 +1,11 @@
<?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_seventeen_track>
<general><enabled>0</enabled><api_url>https://api.17track.net/track/v2.4</api_url></general>
<sync><batch_size>40</batch_size><auto_receive>1</auto_receive></sync>
<widget><enabled>1</enabled><height>560</height></widget>
</esun_seventeen_track>
</default>
</config>
@@ -0,0 +1,6 @@
<?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_seventeen_track_sync" instance="Esun\SeventeenTrack\Cron\SyncTracking" method="execute"><schedule>*/10 * * * *</schedule></job>
</group>
</config>
@@ -0,0 +1,9 @@
<?xml version="1.0"?>
<csp_whitelist xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Csp:etc/csp_whitelist.xsd">
<policies>
<policy id="script-src"><values><value id="17track-script" type="host">https://www.17track.net</value></values></policy>
<policy id="frame-src"><values><value id="17track-frame" type="host">https://*.17track.net</value></values></policy>
<policy id="connect-src"><values><value id="17track-connect" type="host">https://*.17track.net</value></values></policy>
<policy id="style-src"><values><value id="17track-style" type="host">https://*.17track.net</value></values></policy>
</policies>
</csp_whitelist>
@@ -0,0 +1,58 @@
<?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_seventeen_track" resource="sales" engine="innodb" comment="17TRACK Shipment Status">
<column xsi:type="int" name="entity_id" unsigned="true" nullable="false" identity="true" comment="ID"/>
<column xsi:type="int" name="shipment_track_id" unsigned="true" nullable="false" comment="Magento Shipment Track ID"/>
<column xsi:type="int" name="shipment_id" unsigned="true" nullable="false" comment="Shipment ID"/>
<column xsi:type="int" name="order_id" unsigned="true" nullable="false" comment="Order ID"/>
<column xsi:type="varchar" name="tracking_number" nullable="false" length="50" comment="Tracking Number"/>
<column xsi:type="int" name="carrier_code" unsigned="true" nullable="true" comment="17TRACK Carrier Code"/>
<column xsi:type="varchar" name="sync_status" nullable="false" length="20" default="pending" comment="Sync Status"/>
<column xsi:type="int" name="error_code" nullable="true" comment="Last 17TRACK Error Code"/>
<column xsi:type="smallint" name="attempt_count" unsigned="true" nullable="false" default="0" comment="Consecutive Failure Count"/>
<column xsi:type="timestamp" name="next_attempt_at" nullable="true" on_update="false" comment="Next Attempt Time"/>
<column xsi:type="varchar" name="package_status" nullable="true" length="40" comment="17TRACK Package Status"/>
<column xsi:type="varchar" name="latest_event" nullable="true" length="1024" comment="Latest Tracking Event"/>
<column xsi:type="timestamp" name="delivered_at" nullable="true" on_update="false" comment="Delivery Time"/>
<column xsi:type="text" name="last_error" nullable="true" comment="Last Error"/>
<column xsi:type="mediumtext" name="response_data" nullable="true" comment="Last API Response"/>
<column xsi:type="timestamp" name="last_synced_at" nullable="true" on_update="false" comment="Last Sync Time"/>
<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_17TRACK_SHIPMENT_TRACK_UNQ"><column name="shipment_track_id"/></constraint>
<constraint xsi:type="foreign" referenceId="ESUN_17TRACK_SHIPMENT_TRACK_FK" table="esun_seventeen_track" column="shipment_track_id" referenceTable="sales_shipment_track" referenceColumn="entity_id" onDelete="CASCADE"/>
<constraint xsi:type="foreign" referenceId="ESUN_17TRACK_SHIPMENT_FK" table="esun_seventeen_track" column="shipment_id" referenceTable="sales_shipment" referenceColumn="entity_id" onDelete="CASCADE"/>
<constraint xsi:type="foreign" referenceId="ESUN_17TRACK_ORDER_FK" table="esun_seventeen_track" column="order_id" referenceTable="sales_order" referenceColumn="entity_id" onDelete="CASCADE"/>
<index referenceId="ESUN_17TRACK_SYNC_STATUS" indexType="btree"><column name="sync_status"/></index>
<index referenceId="ESUN_17TRACK_NEXT_ATTEMPT" indexType="btree"><column name="next_attempt_at"/></index>
<index referenceId="ESUN_17TRACK_ORDER_STATUS" indexType="btree"><column name="order_id"/><column name="package_status"/></index>
</table>
<table name="esun_seventeen_track_api_log" resource="sales" engine="innodb" comment="17TRACK API Audit Log">
<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="Inbound or Outbound"/>
<column xsi:type="varchar" name="operation" nullable="false" length="30" comment="API Operation"/>
<column xsi:type="varchar" name="api_path" nullable="true" length="255" comment="API Endpoint"/>
<column xsi:type="varchar" name="batch_id" nullable="true" length="32" comment="Batch Correlation ID"/>
<column xsi:type="int" name="order_id" unsigned="true" nullable="true" comment="Magento Order ID"/>
<column xsi:type="varchar" name="order_number" nullable="true" length="50" comment="Magento Order Number"/>
<column xsi:type="varchar" name="tracking_number" nullable="true" length="50" comment="Tracking Number"/>
<column xsi:type="varchar" name="event" nullable="true" length="50" comment="Webhook Event"/>
<column xsi:type="varchar" name="status" nullable="false" length="20" comment="Result Status"/>
<column xsi:type="smallint" name="http_status" unsigned="true" nullable="true" comment="HTTP Status"/>
<column xsi:type="int" name="error_code" nullable="true" comment="17TRACK Error Code"/>
<column xsi:type="text" name="message" nullable="true" comment="Result or Error Message"/>
<column xsi:type="mediumtext" name="request_data" nullable="true" comment="Sanitized Request Data"/>
<column xsi:type="mediumtext" name="response_data" nullable="true" comment="Sanitized Response Data"/>
<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_17TRACK_API_LOG_STATUS_CREATED" indexType="btree"><column name="status"/><column name="created_at"/></index>
<index referenceId="ESUN_17TRACK_API_LOG_OPERATION_CREATED" indexType="btree"><column name="operation"/><column name="created_at"/></index>
<index referenceId="ESUN_17TRACK_API_LOG_ORDER" indexType="btree"><column name="order_number"/></index>
<index referenceId="ESUN_17TRACK_API_LOG_TRACKING" indexType="btree"><column name="tracking_number"/></index>
<index referenceId="ESUN_17TRACK_API_LOG_BATCH" indexType="btree"><column name="batch_id"/></index>
</table>
</schema>
@@ -0,0 +1 @@
{"esun_seventeen_track":{"column":{"entity_id":true,"shipment_track_id":true,"shipment_id":true,"order_id":true,"tracking_number":true,"carrier_code":true,"sync_status":true,"error_code":true,"attempt_count":true,"next_attempt_at":true,"package_status":true,"latest_event":true,"delivered_at":true,"last_error":true,"response_data":true,"last_synced_at":true,"created_at":true,"updated_at":true},"constraint":{"PRIMARY":true,"ESUN_17TRACK_SHIPMENT_TRACK_UNQ":true,"ESUN_17TRACK_SHIPMENT_TRACK_FK":true,"ESUN_17TRACK_SHIPMENT_FK":true,"ESUN_17TRACK_ORDER_FK":true},"index":{"ESUN_17TRACK_SYNC_STATUS":true,"ESUN_17TRACK_NEXT_ATTEMPT":true,"ESUN_17TRACK_ORDER_STATUS":true}},"esun_seventeen_track_api_log":{"column":{"entity_id":true,"direction":true,"operation":true,"api_path":true,"batch_id":true,"order_id":true,"order_number":true,"tracking_number":true,"event":true,"status":true,"http_status":true,"error_code":true,"message":true,"request_data":true,"response_data":true,"duration_ms":true,"created_at":true},"constraint":{"PRIMARY":true},"index":{"ESUN_17TRACK_API_LOG_STATUS_CREATED":true,"ESUN_17TRACK_API_LOG_OPERATION_CREATED":true,"ESUN_17TRACK_API_LOG_ORDER":true,"ESUN_17TRACK_API_LOG_TRACKING":true,"ESUN_17TRACK_API_LOG_BATCH":true}}}
+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:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Framework\Console\CommandListInterface">
<arguments>
<argument name="commands" xsi:type="array">
<item name="esunSeventeenTrackSync" xsi:type="object">Esun\SeventeenTrack\Console\Command\SyncCommand</item>
</argument>
</arguments>
</type>
<type name="Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory">
<arguments>
<argument name="collections" xsi:type="array">
<item name="esun_seventeen_track_log_listing_data_source" xsi:type="string">EsunSeventeenTrackLogGridCollection</item>
</argument>
</arguments>
</type>
<virtualType name="EsunSeventeenTrackLogGridCollection" type="Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult">
<arguments>
<argument name="mainTable" xsi:type="string">esun_seventeen_track_api_log</argument>
<argument name="resourceModel" xsi:type="string">Esun\SeventeenTrack\Model\ResourceModel\ApiLog</argument>
</arguments>
</virtualType>
</config>
@@ -0,0 +1,4 @@
<?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="sales_order_shipment_track_save_after"><observer name="esun_seventeen_track_enqueue" instance="Esun\SeventeenTrack\Observer\EnqueueTrack"/></event>
</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="standard">
<route id="seventeentrack" frontName="seventeentrack">
<module name="Esun_SeventeenTrack"/>
</route>
</router>
</config>
@@ -0,0 +1,13 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Esun_SeventeenTrack">
<sequence>
<module name="Magento_Sales"/>
<module name="Magento_Config"/>
<module name="Magento_AdminNotification"/>
<module name="Esun_Customer"/>
<module name="Esun_ImageManager"/>
</sequence>
</module>
</config>
@@ -0,0 +1,37 @@
"Logistics Tracking","物流轨迹"
"Tracking Number: %1","运单号:%1"
"Loading tracking information...","正在加载物流信息……"
"Tracking information is temporarily unavailable.","物流信息暂时不可用。"
"17TRACK confirmed that every shipment was delivered and signed for.","17TRACK 已确认该订单的全部包裹均已投递并签收。"
"API Logs","API 日志"
"17TRACK API Logs","17TRACK API 日志"
"17TRACK API Log #%1","17TRACK API 日志 #%1"
"View 17TRACK API Logs","查看 17TRACK API 日志"
"View Details","查看详情"
"Created At","创建时间"
"Direction","方向"
"Operation","操作"
"Status","状态"
"Order Number","订单号"
"Tracking Number","运单号"
"Webhook Event","推送事件"
"HTTP Status","HTTP 状态"
"Error Code","错误码"
"Message","信息"
"Batch ID","批次 ID"
"API Endpoint","API 地址"
"Duration (ms)","耗时(毫秒)"
"Outbound (Registration)","出站(注册运单)"
"Inbound (Webhook)","入站(物流推送)"
"Tracking Registration","运单注册"
"Webhook Push","物流推送"
"Success","成功"
"Ignored","已忽略"
"Error","错误"
"API Result","接口结果"
"Request Data (sanitized)","请求数据(已脱敏)"
"Response Data (sanitized)","响应数据(已脱敏)"
"No data recorded.","未记录数据。"
"Unable to display data.","无法显示数据。"
"Back","返回"
"The 17TRACK API log no longer exists.","该 17TRACK API 日志已不存在。"
1 Logistics Tracking 物流轨迹
2 Tracking Number: %1 运单号:%1
3 Loading tracking information... 正在加载物流信息……
4 Tracking information is temporarily unavailable. 物流信息暂时不可用。
5 17TRACK confirmed that every shipment was delivered and signed for. 17TRACK 已确认该订单的全部包裹均已投递并签收。
6 API Logs API 日志
7 17TRACK API Logs 17TRACK API 日志
8 17TRACK API Log #%1 17TRACK API 日志 #%1
9 View 17TRACK API Logs 查看 17TRACK API 日志
10 View Details 查看详情
11 Created At 创建时间
12 Direction 方向
13 Operation 操作
14 Status 状态
15 Order Number 订单号
16 Tracking Number 运单号
17 Webhook Event 推送事件
18 HTTP Status HTTP 状态
19 Error Code 错误码
20 Message 信息
21 Batch ID 批次 ID
22 API Endpoint API 地址
23 Duration (ms) 耗时(毫秒)
24 Outbound (Registration) 出站(注册运单)
25 Inbound (Webhook) 入站(物流推送)
26 Tracking Registration 运单注册
27 Webhook Push 物流推送
28 Success 成功
29 Ignored 已忽略
30 Error 错误
31 API Result 接口结果
32 Request Data (sanitized) 请求数据(已脱敏)
33 Response Data (sanitized) 响应数据(已脱敏)
34 No data recorded. 未记录数据。
35 Unable to display data. 无法显示数据。
36 Back 返回
37 The 17TRACK API log no longer exists. 该 17TRACK API 日志已不存在。
@@ -0,0 +1,4 @@
<?php
use Magento\Framework\Component\ComponentRegistrar;
ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Esun_SeventeenTrack', __DIR__);
@@ -0,0 +1,9 @@
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<uiComponent name="esun_seventeen_track_log_listing"/>
</referenceContainer>
</body>
</page>
@@ -0,0 +1,10 @@
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<block class="Esun\SeventeenTrack\Block\Adminhtml\Log\View" name="esun.seventeen.track.log.view"
template="Esun_SeventeenTrack::log/view.phtml"/>
</referenceContainer>
</body>
</page>
@@ -0,0 +1,28 @@
<?php
/** @var \Esun\SeventeenTrack\Block\Adminhtml\Log\View $block */
$record = $block->getRecord();
$payloadFields = ['request_data', 'response_data'];
?>
<div class="admin__page-section">
<div class="admin__page-section-title"><span class="title"><?= $block->escapeHtml(__('API Result')) ?></span></div>
<div class="admin__page-section-content">
<table class="admin__table-secondary">
<?php foreach ($record as $key => $value): ?>
<?php if (in_array($key, $payloadFields, true)) { continue; } ?>
<tr>
<th><?= $block->escapeHtml((string)$key) ?></th>
<td><?= $block->escapeHtml($value === null || $value === '' ? '—' : (string)$value) ?></td>
</tr>
<?php endforeach; ?>
</table>
</div>
</div>
<div class="admin__page-section">
<div class="admin__page-section-title"><span class="title"><?= $block->escapeHtml(__('Request Data (sanitized)')) ?></span></div>
<div class="admin__page-section-content"><pre><?= $block->escapeHtml($block->prettyPayload($record['request_data'] ?? null)) ?></pre></div>
</div>
<div class="admin__page-section">
<div class="admin__page-section-title"><span class="title"><?= $block->escapeHtml(__('Response Data (sanitized)')) ?></span></div>
<div class="admin__page-section-content"><pre><?= $block->escapeHtml($block->prettyPayload($record['response_data'] ?? null)) ?></pre></div>
</div>
<a class="action-default" href="<?= $block->escapeUrl($block->getBackUrl()) ?>"><span><?= $block->escapeHtml(__('Back')) ?></span></a>
@@ -0,0 +1,51 @@
<?xml version="1.0"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<argument name="data" xsi:type="array">
<item name="js_config" xsi:type="array">
<item name="provider" xsi:type="string">esun_seventeen_track_log_listing.esun_seventeen_track_log_listing_data_source</item>
</item>
</argument>
<settings>
<spinner>columns</spinner>
<deps><dep>esun_seventeen_track_log_listing.esun_seventeen_track_log_listing_data_source</dep></deps>
</settings>
<dataSource name="esun_seventeen_track_log_listing_data_source" component="Magento_Ui/js/grid/provider">
<settings>
<storageConfig><param name="indexField" xsi:type="string">entity_id</param></storageConfig>
<updateUrl path="mui/index/render"/>
</settings>
<aclResource>Esun_SeventeenTrack::logs</aclResource>
<dataProvider class="Magento\Framework\View\Element\UiComponent\DataProvider\DataProvider" name="esun_seventeen_track_log_listing_data_source">
<settings><requestFieldName>id</requestFieldName><primaryFieldName>entity_id</primaryFieldName></settings>
</dataProvider>
</dataSource>
<listingToolbar name="listing_top">
<settings><sticky>true</sticky></settings>
<bookmark name="bookmarks"/>
<columnsControls name="columns_controls"/>
<filters name="listing_filters"/>
<paging name="listing_paging"/>
</listingToolbar>
<columns name="columns">
<column name="entity_id"><settings><filter>textRange</filter><label>ID</label><sorting>desc</sorting></settings></column>
<column name="created_at" class="Magento\Ui\Component\Listing\Columns\Date">
<settings><filter>dateRange</filter><dataType>date</dataType><label>Created At</label></settings>
</column>
<column name="direction"><settings><filter>select</filter><options class="Esun\SeventeenTrack\Model\Source\LogDirection"/><label>Direction</label></settings></column>
<column name="operation"><settings><filter>select</filter><options class="Esun\SeventeenTrack\Model\Source\LogOperation"/><label>Operation</label></settings></column>
<column name="status"><settings><filter>select</filter><options class="Esun\SeventeenTrack\Model\Source\LogStatus"/><label>Status</label></settings></column>
<column name="order_number"><settings><filter>text</filter><label>Order Number</label></settings></column>
<column name="tracking_number"><settings><filter>text</filter><label>Tracking Number</label></settings></column>
<column name="event"><settings><filter>text</filter><label>Webhook Event</label></settings></column>
<column name="http_status"><settings><filter>textRange</filter><label>HTTP Status</label></settings></column>
<column name="error_code"><settings><filter>text</filter><label>Error Code</label></settings></column>
<column name="message"><settings><filter>text</filter><label>Message</label></settings></column>
<column name="batch_id"><settings><filter>text</filter><label>Batch ID</label><visible>false</visible></settings></column>
<column name="api_path"><settings><filter>text</filter><label>API Endpoint</label><visible>false</visible></settings></column>
<column name="duration_ms"><settings><filter>textRange</filter><label>Duration (ms)</label><visible>false</visible></settings></column>
<actionsColumn name="actions" class="Esun\SeventeenTrack\Ui\Component\Listing\Column\LogActions">
<settings><indexField>entity_id</indexField></settings>
</actionsColumn>
</columns>
</listing>
@@ -0,0 +1,9 @@
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head><script src="https://www.17track.net/externalcall.js" src_type="url"/></head>
<body>
<referenceBlock name="esun.sales.order.detail">
<block class="Esun\SeventeenTrack\Block\Order\Tracking" name="esun.order.17track" as="seventeen_track" template="Esun_SeventeenTrack::order/tracking.phtml" cacheable="false"/>
</referenceBlock>
</body>
</page>
@@ -0,0 +1,31 @@
<?php
/** @var \Esun\SeventeenTrack\Block\Order\Tracking $block */
/** @var \Magento\Framework\Escaper $escaper */
$tracks = $block->getTracks();
?>
<?php if ($block->canDisplay()): ?>
<section class="esun-order-detail__panel esun-order-tracking">
<h2><?= $escaper->escapeHtml(__('Logistics Tracking')) ?></h2>
<?php foreach ($tracks as $index => $track): ?>
<?php $containerId = 'YQContainer-' . $index; ?>
<div class="esun-order-tracking__shipment">
<div class="esun-order-tracking__meta">
<strong><?= $escaper->escapeHtml($track['title']) ?></strong>
<span><?= $escaper->escapeHtml(__('Tracking Number: %1', $track['number'])) ?></span>
</div>
<div id="<?= $escaper->escapeHtmlAttr($containerId) ?>"
class="esun-order-tracking__widget"
data-mage-init='<?= /* @noEscape */ json_encode([
'Esun_SeventeenTrack/js/tracking-widget' => [
'containerId' => $containerId,
'number' => $track['number'],
'height' => $block->getWidgetHeight(),
'language' => $block->getWidgetLanguage(),
],
], JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) ?>'>
<p><?= $escaper->escapeHtml(__('Loading tracking information...')) ?></p>
</div>
</div>
<?php endforeach; ?>
</section>
<?php endif; ?>
@@ -0,0 +1,33 @@
define(['mage/translate'], function ($t) {
'use strict';
return function (config, element) {
var attempts = 0,
timer;
function render() {
attempts += 1;
if (window.YQV5 && typeof window.YQV5.trackSingle === 'function') {
element.innerHTML = '';
window.YQV5.trackSingle({
YQ_ContainerId: config.containerId,
YQ_Height: config.height,
YQ_Fc: '0',
YQ_Lang: config.language,
YQ_Num: config.number
});
return;
}
if (attempts < 100) {
timer = window.setTimeout(render, 100);
} else {
element.innerHTML = '<p>' + $t('Tracking information is temporarily unavailable.') + '</p>';
}
}
render();
return function () {
window.clearTimeout(timer);
};
};
});