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,28 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Model\Api;
use Esun\LingxingErp\Model\Api\Signer;
use PHPUnit\Framework\TestCase;
class SignerTest extends TestCase
{
public function testMatchesLingxingPhpSdkSerializationAndEncryption(): void
{
$parameters = [
'z' => null,
'items' => [['sku' => '测试/1', 'qty' => 2, 'drop' => null]],
'empty' => '',
'bool' => true,
'access_token' => 'token',
'app_key' => 'ak_test123456789',
'timestamp' => 1720408272,
];
self::assertSame(
'mR8XKYkL8QUYDIJmM75XAl3JGPuuDvzjsyr6LZ5nWocwCpgLHg5dzZDMNuiTX/Va',
(new Signer())->sign($parameters, 'ak_test123456789')
);
}
}
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Model\Api;
use Esun\LingxingErp\Model\Api\TokenProvider;
use Esun\LingxingErp\Model\Config;
use Magento\Framework\App\CacheInterface;
use Magento\Framework\HTTP\Client\Curl;
use Magento\Framework\HTTP\Client\CurlFactory;
use Magento\Framework\Lock\LockManagerInterface;
use PHPUnit\Framework\TestCase;
class TokenProviderTest extends TestCase
{
public function testAcceptsDocumentedHttpStyleBusinessCode(): void
{
$config = $this->createMock(Config::class);
$config->method('getApiBaseUrl')->willReturn('https://example.test');
$config->method('getAppId')->willReturn('app-id');
$config->method('getAppSecret')->willReturn('app-secret');
$cache = $this->createMock(CacheInterface::class);
$cache->method('load')->willReturn(false);
$cache->expects(self::once())->method('save');
$curl = $this->createMock(Curl::class);
$curl->method('getStatus')->willReturn(200);
$curl->method('getBody')->willReturn((string)json_encode([
'code' => '200',
'msg' => 'OK',
'data' => ['access_token' => 'token-value', 'expires_in' => 3600],
]));
$curlFactory = $this->createMock(CurlFactory::class);
$curlFactory->method('create')->willReturn($curl);
$lock = $this->createMock(LockManagerInterface::class);
$lock->method('lock')->willReturn(true);
$lock->expects(self::once())->method('unlock');
$provider = new TokenProvider($config, $cache, $curlFactory, $lock);
self::assertSame('token-value', $provider->getAccessToken());
}
}
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Model;
use Esun\LingxingErp\Model\Config;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Encryption\EncryptorInterface;
use Magento\Store\Model\ScopeInterface;
use PHPUnit\Framework\TestCase;
class ConfigTest extends TestCase
{
public function testStoreMappingIsResolvedPerWebsite(): void
{
$scopeConfig = $this->createMock(ScopeConfigInterface::class);
$scopeConfig->method('getValue')->willReturnCallback(
static function (string $path, string $scope = 'default', $scopeCode = null): string {
if ($path !== 'esun_lingxing/general/store_mapping' || $scope !== ScopeInterface::SCOPE_WEBSITE) {
return '';
}
return (int)$scopeCode === 1 ? '10009|STORE-US' : '10002|STORE-EU';
}
);
$config = new Config($scopeConfig, $this->createMock(EncryptorInterface::class));
self::assertSame(10009, $config->getPlatformCode(1));
self::assertSame('STORE-US', $config->getLingxingStoreId(1));
self::assertSame(10002, $config->getPlatformCode(2));
self::assertSame('STORE-EU', $config->getLingxingStoreId(2));
}
public function testSkuSyncPageSizeIsBounded(): void
{
$scopeConfig = $this->createMock(ScopeConfigInterface::class);
$scopeConfig->method('getValue')->with('esun_lingxing/sku_sync/page_size')->willReturn('500');
$config = new Config($scopeConfig, $this->createMock(EncryptorInterface::class));
self::assertSame(200, $config->getSkuSyncPageSize());
}
}
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Model\Inventory;
use Esun\LingxingErp\Model\Api\Client;
use Esun\LingxingErp\Model\Api\Endpoint;
use Esun\LingxingErp\Model\Inventory\InventoryFetcher;
use Esun\LingxingErp\Model\Sync\LogWriter;
use PHPUnit\Framework\TestCase;
class InventoryFetcherTest extends TestCase
{
public function testUsesProductInventoryEndpointAndWarehouseFilter(): void
{
$client = $this->createMock(Client::class);
$client->expects(self::once())
->method('post')
->with(Endpoint::INVENTORY_DETAILS, [
'wid' => '46133',
'offset' => 0,
'length' => 800,
])
->willReturn([
'code' => 0,
'data' => [['wid' => 46133, 'sku' => 'ERP-1', 'product_valid_num' => 12]],
'total' => 1,
]);
$logWriter = $this->createMock(LogWriter::class);
$logWriter->expects(self::once())->method('write');
$result = (new InventoryFetcher($client, $logWriter))->fetchAll(46133);
self::assertSame('ERP-1', $result[0]['sku']);
self::assertSame(12, $result[0]['product_valid_num']);
}
}
@@ -0,0 +1,147 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Model\Inventory;
use Esun\LingxingErp\Model\Inventory\InventoryFetcher;
use Esun\LingxingErp\Model\Inventory\InventorySynchronizer;
use Esun\LingxingErp\Model\Sku\ProductErpSkuRepository;
use Esun\LingxingErp\Model\Sync\LogWriter;
use Esun\LingxingErp\Model\Warehouse\WarehouseRepository;
use Magento\Framework\Lock\LockManagerInterface;
use Magento\InventoryApi\Api\Data\SourceItemInterface;
use Magento\InventoryApi\Api\Data\SourceItemInterfaceFactory;
use Magento\InventoryApi\Api\SourceItemsSaveInterface;
use PHPUnit\Framework\TestCase;
class InventorySynchronizerTest extends TestCase
{
public function testFullErpQuantityIsWrittenToEveryPairedMagentoSku(): void
{
$warehouseRepository = $this->createMock(WarehouseRepository::class);
$warehouseRepository->method('getWebsiteIdsForSource')->with('default')->willReturn([3]);
$warehouseRepository->method('getExistingSourceItemSkus')->with('default')->willReturn([]);
$fetcher = $this->createMock(InventoryFetcher::class);
$fetcher->method('fetchAll')->with(10)->willReturn([
['sku' => 'ERP-1', 'product_valid_num' => 30],
]);
$productRepository = $this->createMock(ProductErpSkuRepository::class);
$productRepository->method('findMskusByErpSku')->with(3, 'ERP-1')
->willReturn(['MAGENTO-A', 'MAGENTO-B']);
$productRepository->method('getWebsiteProductSkusWithErpSku')->with(3)
->willReturn(['MAGENTO-A', 'MAGENTO-B']);
$itemA = $this->createMock(SourceItemInterface::class);
$itemA->expects(self::once())->method('setSourceCode')->with('default');
$itemA->expects(self::once())->method('setSku')->with('MAGENTO-A');
$itemA->expects(self::once())->method('setQuantity')->with(30.0);
$itemA->expects(self::once())->method('setStatus')->with(SourceItemInterface::STATUS_IN_STOCK);
$itemB = $this->createMock(SourceItemInterface::class);
$itemB->expects(self::once())->method('setSourceCode')->with('default');
$itemB->expects(self::once())->method('setSku')->with('MAGENTO-B');
$itemB->expects(self::once())->method('setQuantity')->with(30.0);
$itemB->expects(self::once())->method('setStatus')->with(SourceItemInterface::STATUS_IN_STOCK);
$itemFactory = $this->createMock(SourceItemInterfaceFactory::class);
$itemFactory->expects(self::exactly(2))->method('create')->willReturn($itemA, $itemB);
$sourceItemsSave = $this->createMock(SourceItemsSaveInterface::class);
$sourceItemsSave->expects(self::once())->method('execute')->with([$itemA, $itemB]);
$synchronizer = new InventorySynchronizer(
$warehouseRepository,
$fetcher,
$productRepository,
$itemFactory,
$sourceItemsSave,
$this->createMock(LogWriter::class),
$this->createMock(LockManagerInterface::class)
);
$method = new \ReflectionMethod($synchronizer, 'synchronizeWarehouse');
self::assertSame(
[
'items' => 2,
'unmapped' => 0,
'zeroed' => 0,
'preserved_without_erp_sku' => 0,
'unmapped_erp_skus' => [],
],
$method->invoke($synchronizer, ['wid' => 10, 'source_code' => 'default'])
);
}
public function testDoesNotZeroExistingSourceItemsWithoutAnErpSkuMapping(): void
{
$warehouseRepository = $this->createMock(WarehouseRepository::class);
$warehouseRepository->method('getWebsiteIdsForSource')->with('default')->willReturn([3]);
$warehouseRepository->method('getExistingSourceItemSkus')->with('default')->willReturn([
'MAPPED-BUT-MISSING',
'NO-ERP-SKU',
]);
$fetcher = $this->createMock(InventoryFetcher::class);
$fetcher->method('fetchAll')->with(10)->willReturn([
['sku' => 'UNKNOWN-ERP-SKU', 'product_valid_num' => 50],
]);
$productRepository = $this->createMock(ProductErpSkuRepository::class);
$productRepository->method('findMskusByErpSku')->with(3, 'UNKNOWN-ERP-SKU')->willReturn([]);
$productRepository->method('getWebsiteProductSkusWithErpSku')->with(3)
->willReturn(['MAPPED-BUT-MISSING']);
$zeroedItem = $this->createMock(SourceItemInterface::class);
$zeroedItem->expects(self::once())->method('setSourceCode')->with('default');
$zeroedItem->expects(self::once())->method('setSku')->with('MAPPED-BUT-MISSING');
$zeroedItem->expects(self::once())->method('setQuantity')->with(0.0);
$zeroedItem->expects(self::once())->method('setStatus')->with(SourceItemInterface::STATUS_OUT_OF_STOCK);
$itemFactory = $this->createMock(SourceItemInterfaceFactory::class);
$itemFactory->expects(self::once())->method('create')->willReturn($zeroedItem);
$sourceItemsSave = $this->createMock(SourceItemsSaveInterface::class);
$sourceItemsSave->expects(self::once())->method('execute')->with([$zeroedItem]);
$synchronizer = new InventorySynchronizer(
$warehouseRepository,
$fetcher,
$productRepository,
$itemFactory,
$sourceItemsSave,
$this->createMock(LogWriter::class),
$this->createMock(LockManagerInterface::class)
);
$method = new \ReflectionMethod($synchronizer, 'synchronizeWarehouse');
self::assertSame(
[
'items' => 1,
'unmapped' => 1,
'zeroed' => 1,
'preserved_without_erp_sku' => 1,
'unmapped_erp_skus' => ['UNKNOWN-ERP-SKU'],
],
$method->invoke($synchronizer, ['wid' => 10, 'source_code' => 'default'])
);
}
public function testResolvesEveryMagentoSkuPairedToAnErpSku(): void
{
$productRepository = $this->createMock(ProductErpSkuRepository::class);
$productRepository->expects(self::exactly(2))
->method('findMskusByErpSku')
->willReturnMap([
[3, 'ERP-1', ['MAGENTO-A', 'MAGENTO-B']],
[8, 'ERP-1', ['MAGENTO-B', 'MAGENTO-C']],
]);
$synchronizer = new InventorySynchronizer(
$this->createMock(WarehouseRepository::class),
$this->createMock(InventoryFetcher::class),
$productRepository,
$this->createMock(SourceItemInterfaceFactory::class),
$this->createMock(SourceItemsSaveInterface::class),
$this->createMock(LogWriter::class),
$this->createMock(LockManagerInterface::class)
);
$method = new \ReflectionMethod($synchronizer, 'resolveMagentoSkus');
self::assertSame(
['MAGENTO-A', 'MAGENTO-B', 'MAGENTO-C'],
$method->invoke($synchronizer, [3, 8], 'ERP-1')
);
}
}
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Model\Order;
use Esun\LingxingErp\Model\Order\CancellationSourceResolver;
use Magento\Framework\App\Request\Http;
use Magento\Framework\App\State;
use PHPUnit\Framework\TestCase;
class CancellationSourceResolverTest extends TestCase
{
public function testIdentifiesCustomerCancellationRoute(): void
{
$state = $this->createMock(State::class);
$state->method('getAreaCode')->willReturn('frontend');
$request = $this->createMock(Http::class);
$request->method('getFullActionName')->willReturn('esun_customer_order_cancel');
self::assertSame(
CancellationSourceResolver::CUSTOMER,
(new CancellationSourceResolver($state, $request))->resolve()
);
}
public function testCronAreaTakesPriority(): void
{
$state = $this->createMock(State::class);
$state->method('getAreaCode')->willReturn('crontab');
$request = $this->createMock(Http::class);
self::assertSame(
CancellationSourceResolver::SCHEDULED_TASK,
(new CancellationSourceResolver($state, $request))->resolve()
);
}
}
@@ -0,0 +1,79 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Model\Order;
use Esun\LingxingErp\Model\Config;
use Esun\LingxingErp\Model\Order\OrderPayloadBuilder;
use Magento\Sales\Api\Data\OrderAddressInterface;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\Order\Item;
use Magento\Store\Api\Data\StoreInterface;
use Magento\Store\Model\StoreManagerInterface;
use PHPUnit\Framework\TestCase;
class OrderPayloadBuilderTest extends TestCase
{
public function testAddsAvailableMagentoAddressDataFromExtendedCreateOrderDocument(): void
{
$config = $this->createMock(Config::class);
$config->expects(self::once())->method('assertOrderMappingReady')->with(3);
$config->method('getStockDeductionType')->willReturn(1);
$config->method('getWarehouseId')->with(3)->willReturn('');
$config->method('getPlatformCode')->with(3)->willReturn(10009);
$config->method('getLingxingStoreId')->with(3)->willReturn('STORE-US');
$store = $this->createMock(StoreInterface::class);
$store->method('getWebsiteId')->willReturn(3);
$storeManager = $this->createMock(StoreManagerInterface::class);
$storeManager->method('getStore')->with(16)->willReturn($store);
$address = $this->createMock(OrderAddressInterface::class);
$address->method('getCountryId')->willReturn('US');
$address->method('getFirstname')->willReturn('Shipping');
$address->method('getLastname')->willReturn('Customer');
$address->method('getCompany')->willReturn('Example Inc.');
$address->method('getCity')->willReturn('Austin');
$address->method('getRegion')->willReturn('Texas');
$address->method('getPostcode')->willReturn('78701');
$address->method('getStreet')->willReturn(['100 Main St', 'Suite 20', 'Reception']);
$address->method('getTelephone')->willReturn('+1 555 0100');
$address->method('getEmail')->willReturn('shipping@example.com');
$item = $this->createMock(Item::class);
$item->method('getIsVirtual')->willReturn(false);
$item->method('getSku')->willReturn('MAGENTO-SKU');
$item->method('getQtyOrdered')->willReturn(2.0);
$item->method('getPrice')->willReturn(19.99);
$order = $this->createMock(Order::class);
$order->method('getStoreId')->willReturn(16);
$order->method('getShippingAddress')->willReturn($address);
$order->method('getAllVisibleItems')->willReturn([$item]);
$order->method('getIncrementId')->willReturn('esun100001');
$order->method('getShippingAmount')->willReturn(5.0);
$order->method('getTaxAmount')->willReturn(2.0);
$order->method('getGrandTotal')->willReturn(46.98);
$order->method('getCreatedAt')->willReturn('2026-09-09 00:00:00');
$order->method('getOrderCurrencyCode')->willReturn('USD');
$order->method('getCustomerFirstname')->willReturn('Buyer');
$order->method('getCustomerMiddlename')->willReturn('M');
$order->method('getCustomerLastname')->willReturn('Name');
$order->method('getCustomerEmail')->willReturn('buyer@example.com');
$order->method('getCustomerNote')->willReturn(null);
$payload = (new OrderPayloadBuilder($config, $storeManager))->build($order);
$orderData = $payload['orders'][0];
self::assertSame('100 Main St', $orderData['address_line1']);
self::assertSame('Suite 20', $orderData['address_line2']);
self::assertSame('Reception', $orderData['address_line3']);
self::assertSame('Texas', $orderData['state_or_region']);
self::assertSame('78701', $orderData['postal_code']);
self::assertSame('+1 555 0100', $orderData['receiver_mobile']);
self::assertSame('buyer@example.com', $orderData['buyer_email']);
self::assertSame('Buyer M Name', $orderData['buyer_name']);
self::assertArrayNotHasKey('district', $orderData);
self::assertArrayNotHasKey('doorplate_no', $orderData);
}
}
@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Model\Shipment;
use Esun\LingxingErp\Model\Shipment\FulfillmentNormalizer;
use PHPUnit\Framework\TestCase;
class FulfillmentNormalizerTest extends TestCase
{
public function testMultipleOutboundOrdersRemainIndependentShipments(): void
{
$result = (new FulfillmentNormalizer())->normalize([
'order_number' => 'ERP1',
'wo_number' => 'WO1',
'wid' => 46133,
'tracking_no' => 'TRACK1',
'product_info' => [['sku' => 'SKU1', 'count' => 2]],
]);
self::assertCount(1, $result);
self::assertSame('WO1', $result[0]['external_key']);
self::assertSame([['erp_sku' => 'SKU1', 'quantity' => 2.0]], $result[0]['products']);
self::assertSame('TRACK1', $result[0]['tracks'][0]['number']);
self::assertSame(46133, $result[0]['wid']);
}
public function testPackagesSplitOnlyWhenEveryPackageHasItemQuantities(): void
{
$result = (new FulfillmentNormalizer())->normalize([
'order_number' => 'ERP1',
'wo_number' => 'WO1',
'package_delivered_data' => [
['package_no' => 'P1', 'tracking_no' => 'T1', 'product_info' => [['sku' => 'A', 'count' => 1]]],
['package_no' => 'P2', 'tracking_no' => 'T2', 'product_info' => [['sku' => 'B', 'count' => 1]]],
],
]);
self::assertCount(2, $result);
self::assertSame('WO1|P1', $result[0]['external_key']);
self::assertSame('WO1|P2', $result[1]['external_key']);
}
public function testPackagesWithoutItemQuantitiesBecomeOneShipmentWithMultipleTracks(): void
{
$result = (new FulfillmentNormalizer())->normalize([
'order_number' => 'ERP1',
'wo_number' => 'WO1',
'product_info' => [['sku' => 'A', 'count' => 2]],
'package_delivered_data' => [
['package_no' => 'P1', 'tracking_no' => 'T1'],
['package_no' => 'P2', 'tracking_no' => 'T2'],
],
]);
self::assertCount(1, $result);
self::assertSame(['T1', 'T2'], array_column($result[0]['tracks'], 'number'));
}
}
@@ -0,0 +1,88 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Model\Shipment;
use Esun\LingxingErp\Model\Config;
use Esun\LingxingErp\Model\Shipment\ShipmentImporter;
use Esun\LingxingErp\Model\Sku\ProductErpSkuRepository;
use Esun\LingxingErp\Model\Sync\OrderSyncRepository;
use Esun\LingxingErp\Model\Warehouse\WarehouseRepository;
use Magento\Sales\Api\Data\ShipmentCreationArgumentsExtensionInterfaceFactory;
use Magento\Sales\Api\Data\ShipmentCreationArgumentsInterfaceFactory;
use Magento\Sales\Api\Data\ShipmentItemCreationInterfaceFactory;
use Magento\Sales\Api\Data\ShipmentTrackCreationInterfaceFactory;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Api\ShipOrderInterface;
use Magento\Sales\Model\Order\Item;
use Magento\Store\Model\StoreManagerInterface;
use PHPUnit\Framework\TestCase;
class ShipmentImporterTest extends TestCase
{
public function testErpSkuIsResolvedToMagentoOrderItemSkuWithinWebsite(): void
{
$productErpSkuRepository = $this->createMock(ProductErpSkuRepository::class);
$productErpSkuRepository->expects(self::once())
->method('findMskusByErpSku')
->with(3, 'ERP-001')
->willReturn(['MAGENTO-001']);
$importer = $this->createImporter($productErpSkuRepository);
$item = $this->createOrderItem('MAGENTO-001', 17, 2.0);
$method = new \ReflectionMethod($importer, 'allocateQuantities');
$result = $method->invoke($importer, [$item], [['erp_sku' => 'ERP-001', 'quantity' => 2]], 3);
self::assertSame([17 => 2.0], $result);
}
public function testSharedErpSkuIsAllocatedAcrossMagentoItemsInOrderItemOrder(): void
{
$productErpSkuRepository = $this->createMock(ProductErpSkuRepository::class);
$productErpSkuRepository->expects(self::once())
->method('findMskusByErpSku')
->with(3, 'ERP-SHARED')
->willReturn(['MAGENTO-B', 'MAGENTO-A']);
$importer = $this->createImporter($productErpSkuRepository);
$first = $this->createOrderItem('MAGENTO-A', 17, 1.0);
$second = $this->createOrderItem('MAGENTO-B', 18, 2.0);
$method = new \ReflectionMethod($importer, 'allocateQuantities');
$result = $method->invoke(
$importer,
// Input order is intentionally reversed; allocation must follow the Magento order item IDs.
[$second, $first],
[['erp_sku' => 'ERP-SHARED', 'quantity' => 2]],
3
);
self::assertSame([17 => 1.0, 18 => 1.0], $result);
}
private function createImporter(ProductErpSkuRepository $productErpSkuRepository): ShipmentImporter
{
return new ShipmentImporter(
$this->createMock(OrderSyncRepository::class),
$this->createMock(OrderRepositoryInterface::class),
$this->createMock(ShipmentItemCreationInterfaceFactory::class),
$this->createMock(ShipmentTrackCreationInterfaceFactory::class),
$this->createMock(ShipOrderInterface::class),
$this->createMock(Config::class),
$productErpSkuRepository,
$this->createMock(StoreManagerInterface::class),
$this->createMock(WarehouseRepository::class),
$this->createMock(ShipmentCreationArgumentsInterfaceFactory::class),
$this->createMock(ShipmentCreationArgumentsExtensionInterfaceFactory::class)
);
}
private function createOrderItem(string $sku, int $itemId, float $qtyToShip): Item
{
$item = $this->createMock(Item::class);
$item->method('getIsVirtual')->willReturn(false);
$item->method('getQtyToShip')->willReturn($qtyToShip);
$item->method('getSku')->willReturn($sku);
$item->method('getItemId')->willReturn($itemId);
return $item;
}
}
@@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Model\Shipment;
use Esun\LingxingErp\Model\Api\Client;
use Esun\LingxingErp\Model\Config;
use Esun\LingxingErp\Model\Shipment\FulfillmentNormalizer;
use Esun\LingxingErp\Model\Shipment\ShipmentPuller;
use Esun\LingxingErp\Model\Sync\LogWriter;
use Esun\LingxingErp\Model\Sync\OrderSyncRepository;
use Esun\LingxingErp\Model\Sync\ShipmentSyncRepository;
use Magento\Framework\FlagManager;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
use PHPUnit\Framework\TestCase;
class ShipmentPullerTest extends TestCase
{
public function testLimitsRemoteRequestToTrackablePlatformOrderNumbers(): void
{
$config = $this->createMock(Config::class);
$config->method('getShipmentPageSize')->willReturn(200);
$config->method('getShipmentMaxPages')->willReturn(1);
$orderSyncRepository = $this->createMock(OrderSyncRepository::class);
$orderSyncRepository->method('getTrackablePlatformOrderNos')->willReturn(['100000001', '100000002']);
$client = $this->createMock(Client::class);
$client->expects(self::once())->method('post')->with(
'/erp/sc/routing/wms/order/wmsOrderList',
self::callback(static fn(array $request): bool =>
$request['platform_order_no_arr'] === ['100000001', '100000002']
&& !isset($request['sid_arr']))
)->willReturn(['code' => 0, 'data' => [], 'request_id' => 'request-id']);
$timezone = $this->createMock(TimezoneInterface::class);
$timezone->method('date')->willReturn(new \DateTime('2026-08-26 12:00:00'));
$flagManager = $this->createMock(FlagManager::class);
$flagManager->method('getFlagData')->willReturn(null);
$puller = new ShipmentPuller(
$client,
$config,
$timezone,
$flagManager,
$this->createMock(FulfillmentNormalizer::class),
$orderSyncRepository,
$this->createMock(ShipmentSyncRepository::class),
$this->createMock(LogWriter::class)
);
$puller->pull();
}
}
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Model\Sku;
use Esun\LingxingErp\Model\Api\Client;
use Esun\LingxingErp\Model\Sku\PairFetcher;
use Esun\LingxingErp\Model\Sync\LogWriter;
use PHPUnit\Framework\TestCase;
class PairFetcherTest extends TestCase
{
public function testFetchesAllPagesWithWebsiteStoreFilters(): void
{
$client = $this->createMock(Client::class);
$client->expects(self::exactly(2))->method('post')->willReturnCallback(
static function (string $path, array $request): array {
self::assertSame('/pb/mp/listing/v2/getPairList', $path);
self::assertSame(['10009'], $request['platform_codes']);
self::assertSame(['STORE-1'], $request['store_ids']);
self::assertSame(['M1', 'M2', 'M3'], $request['msku']);
self::assertSame(2, $request['length']);
if ($request['offset'] === 0) {
return ['code' => 0, 'request_id' => 'R1', 'data' => ['list' => [
['msku' => 'M1', 'sku' => 'E1'],
['msku' => 'M2', 'sku' => 'E2'],
]]];
}
self::assertSame(2, $request['offset']);
return ['code' => 0, 'request_id' => 'R2', 'data' => ['list' => [
['msku' => 'M3', 'sku' => 'E3'],
]]];
}
);
$logWriter = $this->createMock(LogWriter::class);
$logWriter->expects(self::exactly(2))->method('write')->with(self::callback(
static fn(array $data): bool => $data['operation'] === 'sku_pair_lookup'
&& $data['status'] === 'success'
&& isset($data['request_payload'], $data['response_payload'])
));
$result = (new PairFetcher($client, $logWriter))->fetchAll(
10009,
'STORE-1',
['M1', 'M2', 'M3'],
2
);
self::assertSame(['M1', 'M2', 'M3'], array_column($result, 'msku'));
}
}
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Model\Sku;
use Esun\LingxingErp\Model\Sku\ProductErpSkuRepository;
use Magento\Catalog\Model\ResourceModel\Product\Action as ProductActionResource;
use Magento\Eav\Model\Config as EavConfig;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\EntityManager\MetadataPool;
use Magento\Store\Model\StoreManagerInterface;
use PHPUnit\Framework\TestCase;
class ProductErpSkuRepositoryTest extends TestCase
{
public function testMultipleMskusMayShareOneErpSkuInWebsiteStoreMapping(): void
{
$repository = new ProductErpSkuRepository(
$this->createMock(ResourceConnection::class),
$this->createMock(ProductActionResource::class),
$this->createMock(StoreManagerInterface::class),
$this->createMock(EavConfig::class),
$this->createMock(MetadataPool::class)
);
$method = new \ReflectionMethod($repository, 'normalizeAndValidate');
$result = $method->invoke($repository, 10009, 'STORE-1', [
['platform_code' => 10009, 'store_id' => 'STORE-1', 'msku' => 'MAGENTO-A', 'sku' => 'ERP-1'],
['platform_code' => 10009, 'store_id' => 'STORE-1', 'msku' => 'MAGENTO-B', 'sku' => 'ERP-1'],
]);
self::assertSame(['MAGENTO-A' => 'ERP-1', 'MAGENTO-B' => 'ERP-1'], $result);
}
}
@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Model\Store;
use Esun\LingxingErp\Model\Api\ApiException;
use Esun\LingxingErp\Model\Api\Client;
use Esun\LingxingErp\Model\Store\StoreFetcher;
use PHPUnit\Framework\TestCase;
class StoreFetcherTest extends TestCase
{
public function testFetchesEveryPageWithoutStatusFilters(): void
{
$client = $this->createMock(Client::class);
$call = 0;
$client->expects(self::exactly(2))
->method('post')
->willReturnCallback(static function (string $path, array $parameters) use (&$call): array {
self::assertSame('/pb/mp/shop/v2/getSellerList', $path);
self::assertSame([
'offset' => $call,
'length' => 200,
'platform_code' => [10009],
], $parameters);
$response = ['data' => [
'total' => 2,
'list' => [[
'platform_code' => $call + 1,
'store_id' => $call === 0 ? 'A' : 'B',
]],
]];
$call++;
return $response;
});
self::assertSame(['A', 'B'], array_column((new StoreFetcher($client))->fetchAll(), 'store_id'));
}
public function testRejectsIncompleteStoreData(): void
{
$client = $this->createMock(Client::class);
$client->method('post')->willReturn([
'data' => ['total' => 1, 'list' => [['platform_code' => 1]]],
]);
$this->expectException(ApiException::class);
(new StoreFetcher($client))->fetchAll();
}
}
@@ -0,0 +1,94 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Model\Sync;
use Esun\LingxingErp\Model\Sync\LogWriter;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\DB\Adapter\AdapterInterface;
use PHPUnit\Framework\TestCase;
class LogWriterTest extends TestCase
{
public function testSuccessfulPayloadIsStoredAsCompactSummary(): void
{
$inserted = $this->captureInsert([
'status' => 'success',
'operation' => 'order_create',
'request_payload' => ['order_no' => '100001', 'items' => [['sku' => 'A'], ['sku' => 'B']]],
'response_payload' => ['code' => 0, 'request_id' => 'REQ-1', 'data' => ['id' => 99]],
]);
$request = json_decode((string)$inserted['request_payload'], true, 512, JSON_THROW_ON_ERROR);
$response = json_decode((string)$inserted['response_payload'], true, 512, JSON_THROW_ON_ERROR);
self::assertSame('Success payload omitted by retention policy.', $request['_summary']);
self::assertSame(2, $request['items_count']);
self::assertArrayNotHasKey('order_no', $request);
self::assertSame(0, $response['code']);
self::assertSame('REQ-1', $response['request_id']);
self::assertSame(1, $response['data_count']);
}
public function testFailedPayloadRemainsAvailableAndSanitized(): void
{
$inserted = $this->captureInsert([
'status' => 'failed',
'operation' => 'order_create',
'request_payload' => [
'order_no' => '100001',
'phone' => '123456',
'receiver_mobile' => '123456',
'postal_code' => '78701',
'buyer_email' => 'buyer@example.com',
'buyer_name' => 'Buyer Name',
],
]);
$request = json_decode((string)$inserted['request_payload'], true, 512, JSON_THROW_ON_ERROR);
self::assertSame('100001', $request['order_no']);
self::assertSame('[REDACTED]', $request['phone']);
self::assertSame('[REDACTED]', $request['receiver_mobile']);
self::assertSame('[REDACTED]', $request['postal_code']);
self::assertSame('[REDACTED]', $request['buyer_email']);
self::assertSame('[REDACTED]', $request['buyer_name']);
}
public function testInventoryProtectionCountsRemainInSuccessSummary(): void
{
$inserted = $this->captureInsert([
'status' => 'success',
'operation' => 'inventory_sync',
'response_payload' => [
'items' => 10,
'unmapped' => 2,
'zeroed' => 3,
'preserved_without_erp_sku' => 4,
],
]);
$response = json_decode((string)$inserted['response_payload'], true, 512, JSON_THROW_ON_ERROR);
self::assertSame(2, $response['unmapped']);
self::assertSame(3, $response['zeroed']);
self::assertSame(4, $response['preserved_without_erp_sku']);
}
/** @return array<string, mixed> */
private function captureInsert(array $data): array
{
$inserted = [];
$connection = $this->createMock(AdapterInterface::class);
$connection->expects(self::once())->method('insert')->willReturnCallback(
static function (string $table, array $row) use (&$inserted): int {
self::assertSame('esun_lingxing_sync_log', $table);
$inserted = $row;
return 1;
}
);
$resource = $this->createMock(ResourceConnection::class);
$resource->method('getConnection')->willReturn($connection);
$resource->method('getTableName')->willReturnArgument(0);
(new LogWriter($resource))->write($data);
return $inserted;
}
}
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Model\Warehouse;
use Esun\LingxingErp\Model\Api\Client;
use Esun\LingxingErp\Model\Api\Endpoint;
use Esun\LingxingErp\Model\Sync\LogWriter;
use Esun\LingxingErp\Model\Warehouse\WarehouseFetcher;
use PHPUnit\Framework\TestCase;
class WarehouseFetcherTest extends TestCase
{
public function testFetchesOnlyTypeThreeWarehouses(): void
{
$client = $this->createMock(Client::class);
$client->expects(self::once())
->method('post')
->willReturnCallback(function (string $path, array $request): array {
self::assertSame(Endpoint::WAREHOUSE_LIST, $path);
self::assertSame(3, $request['type']);
self::assertSame('0,1', $request['is_delete']);
return [
'code' => 0,
'data' => [[
'wid' => 200,
'name' => 'Warehouse ' . $request['type'],
'type' => $request['type'],
]],
'total' => 1,
];
});
$logWriter = $this->createMock(LogWriter::class);
$logWriter->expects(self::once())->method('write');
$result = (new WarehouseFetcher($client, $logWriter))->fetchAll();
self::assertCount(1, $result);
self::assertSame([200], array_column($result, 'wid'));
}
}
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Test\Unit\Model\Warehouse;
use Esun\LingxingErp\Model\Warehouse\WarehouseFetcher;
use Esun\LingxingErp\Model\Warehouse\WarehouseRepository;
use Esun\LingxingErp\Model\Warehouse\WarehouseSynchronizer;
use Magento\Framework\Lock\LockManagerInterface;
use PHPUnit\Framework\TestCase;
class WarehouseSynchronizerTest extends TestCase
{
public function testCachesEveryFetchedTypeThreeWarehouseWithoutCreatingSources(): void
{
$fetcher = $this->createMock(WarehouseFetcher::class);
$fetcher->method('fetchAll')->willReturn([
['wid' => 10, 'name' => 'US Stock', 'type' => 3],
['wid' => 20, 'name' => 'UK Stock', 'type' => 3],
['wid' => 30, 'name' => 'Unused Warehouse', 'type' => 3],
]);
$repository = $this->createMock(WarehouseRepository::class);
$repository->expects(self::exactly(3))->method('saveMetadata');
$lockManager = $this->createMock(LockManagerInterface::class);
$lockManager->method('lock')->willReturn(true);
$lockManager->expects(self::once())->method('unlock');
$result = (new WarehouseSynchronizer(
$fetcher,
$repository,
$lockManager
))->synchronize();
self::assertSame(['warehouses' => 3], $result);
}
}