init
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\LingxingErp\Model\Order;
|
||||
|
||||
use Magento\Framework\App\RequestInterface;
|
||||
use Magento\Framework\App\State;
|
||||
|
||||
class CancellationSourceResolver
|
||||
{
|
||||
public const CUSTOMER = 'customer';
|
||||
public const SCHEDULED_TASK = 'scheduled_task';
|
||||
public const ADMINISTRATOR = 'administrator';
|
||||
public const SYSTEM = 'system';
|
||||
|
||||
public function __construct(
|
||||
private readonly State $appState,
|
||||
private readonly RequestInterface $request
|
||||
) {
|
||||
}
|
||||
|
||||
public function resolve(): string
|
||||
{
|
||||
$areaCode = '';
|
||||
try {
|
||||
$areaCode = $this->appState->getAreaCode();
|
||||
} catch (\Throwable) {
|
||||
// Some programmatic cancellations run before an area is initialized.
|
||||
}
|
||||
if ($areaCode === 'crontab') {
|
||||
return self::SCHEDULED_TASK;
|
||||
}
|
||||
|
||||
$fullActionName = method_exists($this->request, 'getFullActionName')
|
||||
? (string)$this->request->getFullActionName()
|
||||
: '';
|
||||
if ($fullActionName === 'esun_customer_order_cancel') {
|
||||
return self::CUSTOMER;
|
||||
}
|
||||
if ($areaCode === 'adminhtml') {
|
||||
return self::ADMINISTRATOR;
|
||||
}
|
||||
return self::SYSTEM;
|
||||
}
|
||||
|
||||
public function getComment(string $source): string
|
||||
{
|
||||
return match ($source) {
|
||||
self::CUSTOMER => 'The customer canceled this order from their account.',
|
||||
self::SCHEDULED_TASK => 'A scheduled task canceled this order automatically.',
|
||||
self::ADMINISTRATOR => 'An administrator canceled this order.',
|
||||
default => 'A system process canceled this order.',
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\LingxingErp\Model\Order;
|
||||
|
||||
use Esun\LingxingErp\Model\Api\ApiException;
|
||||
use Esun\LingxingErp\Model\Api\Client;
|
||||
use Esun\LingxingErp\Model\Api\Endpoint;
|
||||
use Esun\LingxingErp\Model\Config;
|
||||
use Magento\Sales\Api\Data\OrderInterface;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
|
||||
class OrderExporter
|
||||
{
|
||||
public function __construct(
|
||||
private readonly Client $client,
|
||||
private readonly Config $config,
|
||||
private readonly OrderPayloadBuilder $payloadBuilder,
|
||||
private readonly StoreManagerInterface $storeManager
|
||||
) {
|
||||
}
|
||||
|
||||
public function export(OrderInterface $order, ?array $payload = null): array
|
||||
{
|
||||
$payload ??= $this->payloadBuilder->build($order);
|
||||
$websiteId = (int)$this->storeManager->getStore((int)$order->getStoreId())->getWebsiteId();
|
||||
try {
|
||||
$response = $this->client->post(Endpoint::ORDER_CREATE, $payload);
|
||||
} catch (ApiException $exception) {
|
||||
// The ERP may have committed the order even if the response was lost. Reconcile before retrying.
|
||||
try {
|
||||
$existing = $this->findExisting((string)$order->getIncrementId(), $websiteId);
|
||||
} catch (\Throwable) {
|
||||
throw $exception;
|
||||
}
|
||||
if ($existing !== null) {
|
||||
return [
|
||||
'payload' => $payload,
|
||||
'response' => $exception->getResponse(),
|
||||
'global_order_no' => $existing,
|
||||
];
|
||||
}
|
||||
throw $exception;
|
||||
}
|
||||
$successes = $response['data']['success_details'] ?? [];
|
||||
foreach (is_array($successes) ? $successes : [] as $success) {
|
||||
if ((string)($success['platform_order_no'] ?? '') === (string)$order->getIncrementId()
|
||||
&& (string)($success['global_order_no'] ?? '') !== '') {
|
||||
return ['payload' => $payload, 'response' => $response, 'global_order_no' => (string)$success['global_order_no']];
|
||||
}
|
||||
}
|
||||
|
||||
$existing = $this->findExisting((string)$order->getIncrementId(), $websiteId);
|
||||
if ($existing !== null) {
|
||||
return ['payload' => $payload, 'response' => $response, 'global_order_no' => $existing];
|
||||
}
|
||||
|
||||
$errors = $response['data']['error_details'] ?? [];
|
||||
$message = is_array($errors) && $errors !== []
|
||||
? implode('; ', array_filter(array_map(static fn(array $error): string => (string)($error['error_message'] ?? ''), $errors)))
|
||||
: 'Lingxing did not return a success record for this order.';
|
||||
throw new ApiException($message, 'order_not_created', $response);
|
||||
}
|
||||
|
||||
private function findExisting(string $incrementId, int $websiteId): ?string
|
||||
{
|
||||
$response = $this->client->post(Endpoint::ORDER_LIST, [
|
||||
'offset' => 0,
|
||||
'length' => 20,
|
||||
'store_id' => [$this->config->getLingxingStoreId($websiteId)],
|
||||
'platform_code' => [$this->config->getPlatformCode($websiteId)],
|
||||
'platform_order_nos' => [$incrementId],
|
||||
]);
|
||||
foreach (($response['data']['list'] ?? []) as $order) {
|
||||
foreach (($order['platform_info'] ?? []) as $platformInfo) {
|
||||
if ((string)($platformInfo['platform_order_no'] ?? '') === $incrementId) {
|
||||
return (string)($order['global_order_no'] ?? '') ?: null;
|
||||
}
|
||||
}
|
||||
foreach (($order['item_info'] ?? []) as $item) {
|
||||
if ((string)($item['platform_order_no'] ?? '') === $incrementId) {
|
||||
return (string)($order['global_order_no'] ?? '') ?: null;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\LingxingErp\Model\Order;
|
||||
|
||||
use Esun\LingxingErp\Model\Config;
|
||||
use Magento\Sales\Api\Data\OrderInterface;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
|
||||
class OrderPayloadBuilder
|
||||
{
|
||||
/**
|
||||
* Lingxing API documentation:
|
||||
* https://apidoc.lingxing.com/#/docs/hide/CreateOrdersV2.md
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly Config $config,
|
||||
private readonly StoreManagerInterface $storeManager
|
||||
) {
|
||||
}
|
||||
|
||||
public function build(OrderInterface $order): array
|
||||
{
|
||||
$websiteId = (int)$this->storeManager->getStore((int)$order->getStoreId())->getWebsiteId();
|
||||
$this->config->assertOrderMappingReady($websiteId);
|
||||
$address = $order->getShippingAddress() ?: $order->getBillingAddress();
|
||||
if ($address === null) {
|
||||
throw new \RuntimeException('Magento order has no shipping or billing address.');
|
||||
}
|
||||
|
||||
$items = [];
|
||||
foreach ($order->getAllVisibleItems() as $item) {
|
||||
if ($item->getIsVirtual()) {
|
||||
continue;
|
||||
}
|
||||
$sku = trim((string)$item->getSku());
|
||||
if ($sku === '') {
|
||||
throw new \RuntimeException('Magento order item has an empty SKU.');
|
||||
}
|
||||
$items[] = [
|
||||
'msku' => $sku,
|
||||
'quantity' => (int)$item->getQtyOrdered(),
|
||||
'unit_price' => (float)$item->getPrice(),
|
||||
'stock_deduction_type' => $this->config->getStockDeductionType(),
|
||||
];
|
||||
}
|
||||
if ($items === []) {
|
||||
throw new \RuntimeException('Magento order has no physical SKU to export.');
|
||||
}
|
||||
|
||||
$street = $address->getStreet();
|
||||
$streetLines = array_values(array_filter(array_map(
|
||||
static fn ($line): string => trim((string)$line),
|
||||
is_array($street) ? $street : [(string)$street]
|
||||
), static fn (string $line): bool => $line !== ''));
|
||||
$receiverName = trim((string)$address->getFirstname() . ' ' . (string)$address->getLastname());
|
||||
$buyerName = trim(implode(' ', array_filter([
|
||||
trim((string)$order->getCustomerFirstname()),
|
||||
trim((string)$order->getCustomerMiddlename()),
|
||||
trim((string)$order->getCustomerLastname()),
|
||||
], static fn (string $part): bool => $part !== '')));
|
||||
$buyerEmail = trim((string)$order->getCustomerEmail());
|
||||
if ($buyerEmail === '') {
|
||||
$buyerEmail = trim((string)$address->getEmail());
|
||||
}
|
||||
$orderData = [
|
||||
'platform_order_no' => (string)$order->getIncrementId(),
|
||||
'receiver_country_code' => (string)$address->getCountryId(),
|
||||
'customer_shipping_amount' => (float)$order->getShippingAmount(),
|
||||
'customer_tax_amount' => (float)$order->getTaxAmount(),
|
||||
'order_total_amount' => (float)$order->getGrandTotal(),
|
||||
'global_purchase_time' => (new \DateTimeImmutable((string)$order->getCreatedAt(), new \DateTimeZone('UTC')))->getTimestamp(),
|
||||
'receiver_name' => $receiverName,
|
||||
'receiver_company_name' => (string)$address->getCompany(),
|
||||
'city' => (string)$address->getCity(),
|
||||
'address_line1' => $streetLines[0] ?? '',
|
||||
'amount_currency' => (string)$order->getOrderCurrencyCode(),
|
||||
'items' => $items,
|
||||
];
|
||||
$optionalAddressData = [
|
||||
'state_or_region' => trim((string)$address->getRegion()),
|
||||
'postal_code' => trim((string)$address->getPostcode()),
|
||||
'address_line2' => $streetLines[1] ?? '',
|
||||
'address_line3' => count($streetLines) > 2 ? implode(' ', array_slice($streetLines, 2)) : '',
|
||||
'receiver_mobile' => trim((string)$address->getTelephone()),
|
||||
'buyer_email' => $buyerEmail,
|
||||
'buyer_name' => $buyerName !== '' ? $buyerName : $receiverName,
|
||||
];
|
||||
foreach ($optionalAddressData as $field => $value) {
|
||||
if ($value !== '') {
|
||||
$orderData[$field] = $value;
|
||||
}
|
||||
}
|
||||
if ((string)$order->getCustomerNote() !== '') {
|
||||
$orderData['buyer_note'] = (string)$order->getCustomerNote();
|
||||
}
|
||||
if ($this->config->getWarehouseId($websiteId) !== '') {
|
||||
$orderData['wid'] = $this->config->getWarehouseId($websiteId);
|
||||
$orderData['logistics_type_id'] = $this->config->getLogisticsTypeId($websiteId);
|
||||
}
|
||||
|
||||
return [
|
||||
'platform_code' => $this->config->getPlatformCode($websiteId),
|
||||
'store_id' => $this->config->getLingxingStoreId($websiteId),
|
||||
'orders' => [$orderData],
|
||||
];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user