CaiWuXiTong/tests/Unit/Business/KukaPostingLabelImporterTest.php
chenxi 4f694f7333 feat(顾家过账): 支持按月导入过账标签 (#1216)
按源表行序定向更新过账标签,逐行校验订单身份,仅修改过账标签与 row_hash。

验证:新增单元测试 4 个、41 条断言通过;真实 13,949 行隔离导入通过。
2026-11-17 09:57:10 +08:00

403 lines
14 KiB
PHP

<?php
namespace Tests\Unit\Business;
use App\Business\KukaPostingBase\KukaPostingLabelImporter;
use App\Business\XlsxSheetReader;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use RuntimeException;
use Tests\TestCase;
use ZipArchive;
class KukaPostingLabelImporterTest extends TestCase
{
/**
* @var list<string>
*/
private array $temporaryFiles = [];
protected function setUp(): void
{
parent::setUp();
config([
'database.connections.business_mirror' => [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
],
'upstream_mirrors.connection' => 'business_mirror',
]);
DB::purge('business_mirror');
Schema::connection('business_mirror')->dropIfExists('kuka_posting_base_rows');
Schema::connection('business_mirror')->create('kuka_posting_base_rows', function (Blueprint $table): void {
$table->bigIncrements('id');
$table->unsignedBigInteger('company_id');
$table->char('period', 7);
$table->string('store_name', 191);
$table->string('internal_order_no', 191)->nullable();
$table->string('online_order_no', 191)->nullable();
$table->string('product_code', 191)->nullable();
$table->char('row_hash', 64);
$table->longText('source_values');
$table->unsignedInteger('source_row_number');
$table->timestamp('imported_at');
$table->unique(
['company_id', 'period', 'source_row_number'],
'kuka_posting_label_test_row_unique',
);
});
}
protected function tearDown(): void
{
foreach ($this->temporaryFiles as $file) {
@unlink($file);
}
parent::tearDown();
}
public function test_updates_only_posting_label_by_source_row_even_when_one_order_has_two_labels(): void
{
$this->seedBaseRows();
$before = $this->storedRows();
$path = $this->workbook([
$this->sourceRow('是', '天猫-HX旗舰店101', 'ORDER-1', 'ONLINE-1A', 'PRODUCT-1A', 'ORIGINAL-1A'),
$this->sourceRow(
'补单(订单四组)',
'天猫-HX旗舰店101',
'ORDER-1',
'ONLINE-1B',
'PRODUCT-1B',
'ORIGINAL-1B',
),
$this->sourceRow('是', '京东-HX旗舰店101', 'ORDER-2', 'ONLINE-2', 'PRODUCT-2', 'ORIGINAL-2'),
]);
$result = $this->importer()->import(
$path,
'2026-10',
'Sheet1',
null,
1,
);
$this->assertSame(3, $result['rows']);
$this->assertSame(2, $result['store_count']);
$this->assertSame(2, $result['stores']['天猫-HX旗舰店101']);
$this->assertSame(1, $result['stores']['京东-HX旗舰店101']);
$this->assertSame([
'是' => 2,
'补单(订单四组)' => 1,
], $result['labels']);
$this->assertSame(3, $result['updated']);
$this->assertSame(0, $result['unchanged']);
$after = $this->storedRows();
foreach ([2, 3, 4] as $sourceRowNumber) {
$this->assertSame($before[$sourceRowNumber]['id'], $after[$sourceRowNumber]['id']);
$this->assertSame(
$before[$sourceRowNumber]['imported_at'],
$after[$sourceRowNumber]['imported_at'],
);
$this->assertSame(
$before[$sourceRowNumber]['payload']['内部订单号'],
$after[$sourceRowNumber]['payload']['内部订单号'],
);
}
$this->assertSame('是', $after[2]['payload']['过账标签']);
$this->assertSame('补单(订单四组)', $after[3]['payload']['过账标签']);
$this->assertSame('是', $after[4]['payload']['过账标签']);
$this->assertSame($after[2]['payload']['内部订单号'], $after[3]['payload']['内部订单号']);
foreach ($after as $sourceRowNumber => $row) {
$expected = $before[$sourceRowNumber]['payload'];
$expected['过账标签'] = $row['payload']['过账标签'];
$this->assertSame($expected, $row['payload']);
$this->assertSame(
hash('sha256', (string) json_encode(
$row['payload'],
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR,
)),
$row['row_hash'],
);
}
$second = $this->importer()->import(
$path,
'2026-10',
'Sheet1',
null,
1,
);
$this->assertSame(0, $second['updated']);
$this->assertSame(3, $second['unchanged']);
$this->assertSame($after, $this->storedRows());
}
public function test_dry_run_reports_changes_without_writing_them(): void
{
$this->seedBaseRows();
$before = $this->storedRows();
$path = $this->workbook([
$this->sourceRow('补单(订单四组)', '天猫-HX旗舰店101', 'ORDER-1', 'ONLINE-1A', 'PRODUCT-1A', 'ORIGINAL-1A'),
$this->sourceRow('是', '天猫-HX旗舰店101', 'ORDER-1', 'ONLINE-1B', 'PRODUCT-1B', 'ORIGINAL-1B'),
$this->sourceRow('补单(订单四组)', '京东-HX旗舰店101', 'ORDER-2', 'ONLINE-2', 'PRODUCT-2', 'ORIGINAL-2'),
]);
$result = $this->importer()->import(
$path,
'2026-10',
'Sheet1',
null,
1,
true,
);
$this->assertTrue($result['dry_run']);
$this->assertSame(3, $result['updated']);
$this->assertSame($before, $this->storedRows());
}
public function test_identity_mismatch_rejects_the_whole_file_without_partial_updates(): void
{
$this->seedBaseRows();
$before = $this->storedRows();
$path = $this->workbook([
$this->sourceRow('是', '天猫-HX旗舰店101', 'ORDER-1', 'ONLINE-1A', 'PRODUCT-1A', 'ORIGINAL-1A'),
$this->sourceRow(
'补单(订单四组)',
'天猫-HX旗舰店101',
'ORDER-1',
'ONLINE-1B',
'PRODUCT-1B',
'ORIGINAL-1B',
),
$this->sourceRow('是', '京东-HX旗舰店101', 'ORDER-2', 'ONLINE-2', 'PRODUCT-2-CHANGED', 'ORIGINAL-2'),
]);
try {
$this->importer()->import($path, '2026-10', 'Sheet1');
$this->fail('身份字段不一致时不应写入过账标签。');
} catch (RuntimeException $exception) {
$this->assertStringContainsString('商品编码', $exception->getMessage());
$this->assertStringContainsString('未写入任何标签', $exception->getMessage());
}
$this->assertSame($before, $this->storedRows());
}
public function test_any_label_outside_the_month_confirmation_values_is_rejected(): void
{
$this->seedBaseRows();
$path = $this->workbook([
$this->sourceRow('是', '天猫-HX旗舰店101', 'ORDER-1', 'ONLINE-1A', 'PRODUCT-1A', 'ORIGINAL-1A'),
$this->sourceRow('待确认', '天猫-HX旗舰店101', 'ORDER-1', 'ONLINE-1B', 'PRODUCT-1B', 'ORIGINAL-1B'),
$this->sourceRow('是', '京东-HX旗舰店101', 'ORDER-2', 'ONLINE-2', 'PRODUCT-2', 'ORIGINAL-2'),
]);
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('只能为“是”或“补单(订单四组)”');
$this->importer()->import($path, '2026-10', 'Sheet1');
}
private function importer(): KukaPostingLabelImporter
{
return new KukaPostingLabelImporter(app('db'), new XlsxSheetReader());
}
private function seedBaseRows(): void
{
$this->insertBaseRow(2, [
'店铺' => '天猫-HX旗舰店101',
'内部订单号' => 'ORDER-1',
'线上订单号' => 'ONLINE-1A',
'商品编码' => 'PRODUCT-1A',
'原始线上订单号' => 'ORIGINAL-1A',
'款式编码' => 'STYLE-1',
'货号' => 'ITEM-1A',
'物料编号' => 'MAT-1A',
'物料描述' => '测试物料 A',
'成本' => '100.00',
'产品材质' => '板材',
'实发数量' => '1',
'发货金额' => '100.00',
'过账标签' => '原标签 A',
]);
$this->insertBaseRow(3, [
'店铺' => '天猫-HX旗舰店101',
'内部订单号' => 'ORDER-1',
'线上订单号' => 'ONLINE-1B',
'商品编码' => 'PRODUCT-1B',
'原始线上订单号' => 'ORIGINAL-1B',
'款式编码' => 'STYLE-1',
'货号' => 'ITEM-1B',
'物料编号' => 'MAT-1B',
'物料描述' => '测试物料 B',
'成本' => '200.00',
'产品材质' => '金属',
'实发数量' => '2',
'发货金额' => '400.00',
'过账标签' => '原标签 B',
]);
$this->insertBaseRow(4, [
'店铺' => '京东-HX旗舰店101',
'内部订单号' => 'ORDER-2',
'线上订单号' => 'ONLINE-2',
'商品编码' => 'PRODUCT-2',
'原始线上订单号' => 'ORIGINAL-2',
'款式编码' => 'STYLE-2',
'货号' => 'ITEM-2',
'物料编号' => 'MAT-2',
'物料描述' => '测试物料 C',
'成本' => '300.00',
'产品材质' => '玻璃',
'实发数量' => '3',
'发货金额' => '900.00',
'过账标签' => '原标签 C',
]);
}
/**
* @param array<string, string> $payload
*/
private function insertBaseRow(int $sourceRowNumber, array $payload): void
{
$encoded = json_encode(
$payload,
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR,
);
DB::connection('business_mirror')->table('kuka_posting_base_rows')->insert([
'company_id' => 1,
'period' => '2026-10',
'store_name' => $payload['店铺'],
'internal_order_no' => $payload['内部订单号'],
'online_order_no' => $payload['线上订单号'],
'product_code' => $payload['商品编码'],
'row_hash' => hash('sha256', $encoded),
'source_values' => $encoded,
'source_row_number' => $sourceRowNumber,
'imported_at' => now(),
]);
}
/**
* @return array<int, array{id: int, row_hash: string, imported_at: string, payload: array<string, string>}>
*/
private function storedRows(): array
{
return DB::connection('business_mirror')
->table('kuka_posting_base_rows')
->orderBy('source_row_number')
->get()
->mapWithKeys(static fn (object $row): array => [
(int) $row->source_row_number => [
'id' => (int) $row->id,
'row_hash' => (string) $row->row_hash,
'imported_at' => (string) $row->imported_at,
'payload' => json_decode(
(string) $row->source_values,
true,
512,
JSON_THROW_ON_ERROR,
),
],
])
->all();
}
/**
* @return array<string, string>
*/
private function sourceRow(
string $label,
string $store,
string $internalOrderNo,
string $onlineOrderNo,
string $productCode,
string $originalOnlineOrderNo,
): array {
return [
'2026年10月过账' => $label,
'店铺' => $store,
'内部订单号' => $internalOrderNo,
'线上订单号' => $onlineOrderNo,
'商品编码' => $productCode,
'原始线上订单号' => $originalOnlineOrderNo,
];
}
/**
* @param list<array<string, string>> $rows
*/
private function workbook(array $rows): string
{
$headers = [
'2026年10月过账',
'店铺',
'内部订单号',
'线上订单号',
'商品编码',
'原始线上订单号',
];
$path = tempnam(sys_get_temp_dir(), 'kuka-posting-label-').'.xlsx';
$this->temporaryFiles[] = $path;
$zip = new ZipArchive();
$this->assertTrue($zip->open($path, ZipArchive::CREATE | ZipArchive::OVERWRITE) === true);
$zip->addFromString(
'xl/worksheets/sheet1.xml',
$this->worksheetXml(array_merge([$headers], $rows), $headers),
);
$zip->close();
return $path;
}
/**
* @param list<array<int, string>|array<string, string>> $rows
* @param list<string> $headers
*/
private function worksheetXml(array $rows, array $headers): string
{
$xmlRows = [];
foreach ($rows as $rowIndex => $row) {
$values = array_is_list($row)
? $row
: array_map(static fn (string $header): string => $row[$header] ?? '', $headers);
$cells = [];
foreach ($values as $columnIndex => $value) {
$reference = $this->columnName($columnIndex + 1).($rowIndex + 1);
$cells[] = '<c r="'.$reference.'" t="inlineStr"><is><t>'
.htmlspecialchars((string) $value, ENT_XML1 | ENT_QUOTES, 'UTF-8')
.'</t></is></c>';
}
$xmlRows[] = '<row r="'.($rowIndex + 1).'">'.implode('', $cells).'</row>';
}
return '<?xml version="1.0" encoding="UTF-8"?>'
.'<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
.'<sheetData>'.implode('', $xmlRows).'</sheetData></worksheet>';
}
private function columnName(int $index): string
{
$name = '';
while ($index > 0) {
$index--;
$name = chr(65 + ($index % 26)).$name;
$index = intdiv($index, 26);
}
return $name;
}
}