diff --git a/app/Business/KukaPostingBase/KukaPostingBasePageData.php b/app/Business/KukaPostingBase/KukaPostingBasePageData.php index a2aed7ec..c8d97ee3 100644 --- a/app/Business/KukaPostingBase/KukaPostingBasePageData.php +++ b/app/Business/KukaPostingBase/KukaPostingBasePageData.php @@ -130,9 +130,9 @@ class KukaPostingBasePageData $storedMaterialDescription = ''; } $mappedMaterialNumber = trim((string) ($maps[$row['item_number']]->material_number ?? '')); - $materialNumber = $mappedMaterialNumber !== '' - ? $mappedMaterialNumber - : ($usesRepairedMaterial ? $storedMaterialNumber : ''); + $materialNumber = $usesRepairedMaterial && $storedMaterialNumber !== '' + ? $storedMaterialNumber + : $mappedMaterialNumber; $quotation = $materialNumber === '' ? null : ($quotations[$materialNumber] ?? null); $brandItemNumber = trim((string) ( $brandItems[$row['style_code']]->brand_item_number ?? '' diff --git a/app/Business/KukaPostingBase/KukaPostingMaterialRepairImporter.php b/app/Business/KukaPostingBase/KukaPostingMaterialRepairImporter.php index bb09849a..f27b336c 100644 --- a/app/Business/KukaPostingBase/KukaPostingMaterialRepairImporter.php +++ b/app/Business/KukaPostingBase/KukaPostingMaterialRepairImporter.php @@ -45,6 +45,109 @@ class KukaPostingMaterialRepairImporter ) { } + /** + * @return array{ + * period: string, + * dry_run: bool, + * rows: int, + * valid_rows: int, + * skipped_unmapped_rows: int, + * materials: int, + * stores: array, + * updated: int, + * unchanged: int, + * file_sha256: string + * } + */ + public function importSource( + string $mappingPath, + string $period, + ?string $sheetName = null, + int $companyId = 1, + bool $dryRun = false, + ): array { + if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) !== 1) { + throw new InvalidArgumentException('账期格式必须为 YYYY-MM。'); + } + if (! is_file($mappingPath) || ! is_readable($mappingPath)) { + throw new InvalidArgumentException('物料源文件不存在或不可读:' . $mappingPath); + } + + $connection = $this->connection(); + if (! Schema::connection($this->connectionName())->hasTable('kuka_posting_base_rows')) { + throw new RuntimeException('顾家过账基础数据表尚未建立,请先执行数据库迁移。'); + } + + $allowedStores = array_values(array_filter(array_map( + static fn (mixed $store): string => trim((string) $store), + (array) config('kuka_posting.stores', []), + ))); + if ($allowedStores === []) { + throw new RuntimeException('顾家过账基础数据店铺范围未配置。'); + } + + $sheetName = trim((string) ($sheetName ?? '')); + if ($sheetName === '') { + $sheetName = 'Sheet1'; + } + $fileHash = hash_file('sha256', $mappingPath); + if (! is_string($fileHash)) { + throw new RuntimeException('无法计算物料源文件摘要。'); + } + + $sourceRows = $this->readSourceRows($mappingPath, $sheetName, $allowedStores); + $validMaterials = []; + foreach ($sourceRows as $row) { + if ($row['material_number'] !== '') { + $validMaterials[$row['material_number']] = true; + } + } + $quotations = $this->loadQuotations( + $connection, + $companyId, + array_keys($validMaterials), + ); + + if ($dryRun) { + $collected = $this->collectSourceTargets( + $connection, + $sourceRows, + $quotations, + $period, + $companyId, + false, + ); + $result = $collected['result']; + } else { + $result = []; + $connection->transaction(function () use ( + &$result, + $connection, + $sourceRows, + $quotations, + $period, + $companyId, + ): void { + $targets = $this->collectSourceTargets( + $connection, + $sourceRows, + $quotations, + $period, + $companyId, + true, + ); + $result = $targets['result']; + $this->applyMaterials($connection, $targets['targets'], $period, $companyId); + }); + } + + return $result + [ + 'period' => $period, + 'dry_run' => $dryRun, + 'file_sha256' => strtolower($fileHash), + ]; + } + /** * @return array{ * period: string, @@ -272,6 +375,233 @@ class KukaPostingMaterialRepairImporter return $records; } + /** + * @param list $allowedStores + * @return list + */ + private function readSourceRows( + string $path, + string $sheetName, + array $allowedStores, + ): array { + $records = []; + $excelRowNumber = 1; + + foreach ($this->reader->rows( + $path, + array_merge(self::IDENTITY_FIELDS, [ + self::MATERIAL_NUMBER_FIELD, + self::MATERIAL_DESCRIPTION_SOURCE_FIELD, + ]), + [], + $sheetName, + ) as $values) { + $excelRowNumber++; + $store = trim((string) ($values['店铺'] ?? '')); + if (! in_array($store, $allowedStores, true)) { + throw new RuntimeException(sprintf( + '表二第 %d 行的店铺“%s”不在顾家过账基础数据范围内。', + $excelRowNumber, + $store, + )); + } + + $quantity = $this->normalizeDecimal($values['实发数量'] ?? ''); + if ($quantity === null) { + throw new RuntimeException(sprintf( + '表二第 %d 行的实发数量格式无效。', + $excelRowNumber, + )); + } + if ($quantity === '') { + $quantity = '0'; + } + + $materialNumber = trim((string) ($values[self::MATERIAL_NUMBER_FIELD] ?? '')); + $description = trim((string) ( + $values[self::MATERIAL_DESCRIPTION_SOURCE_FIELD] ?? '' + )); + $materialMissing = $this->isUnmappedMaterialValue($materialNumber); + $descriptionMissing = $this->isUnmappedMaterialValue($description); + if ($materialMissing !== $descriptionMissing) { + throw new RuntimeException(sprintf( + '表二第 %d 行的物料编号和物料描述一个有效、一个无效。', + $excelRowNumber, + )); + } + if ($materialMissing) { + $materialNumber = ''; + $description = ''; + } + + $records[] = [ + 'excel_row_number' => $excelRowNumber, + 'key' => $this->sourceIdentityKey($values, $quantity), + 'quantity' => $quantity, + 'material_number' => $materialNumber, + 'description' => $description, + ]; + } + + if ($records === []) { + throw new RuntimeException('表二没有发货明细数据。'); + } + + return $records; + } + + /** + * @param list $sourceRows + * @param array $quotations + * @return array{ + * result: array{ + * rows: int, + * valid_rows: int, + * skipped_unmapped_rows: int, + * materials: int, + * stores: array, + * updated: int, + * unchanged: int + * }, + * targets: list> + * } + */ + private function collectSourceTargets( + ConnectionInterface $connection, + array $sourceRows, + array $quotations, + string $period, + int $companyId, + bool $lockRows, + ): array { + $databaseRows = $this->baseRowsQuery($connection, $period, $companyId)->count(); + if ($databaseRows !== count($sourceRows)) { + throw new RuntimeException(sprintf( + '表二有 %s 行,但共享镜像 %s 有 %s 行,行数不一致,未写入任何物料信息。', + number_format(count($sourceRows)), + $period, + number_format($databaseRows), + )); + } + + $query = $this->baseRowsQuery($connection, $period, $companyId) + ->orderBy('source_row_number'); + if ($lockRows) { + $query->lockForUpdate(); + } + + $targets = []; + $stores = []; + $materials = []; + $updated = 0; + $unchanged = 0; + $validRows = 0; + $skippedRows = 0; + $index = 0; + + foreach ($query->cursor() as $row) { + $source = $sourceRows[$index] ?? null; + if ($source === null) { + throw new RuntimeException('共享镜像行数多于表二,未写入任何物料信息。'); + } + + $values = $this->decodeSourceValues($row); + $databaseQuantity = $this->normalizeDecimal($values['实发数量'] ?? ''); + $databaseQuantity = $databaseQuantity === null || $databaseQuantity === '' + ? '0' + : $databaseQuantity; + if ($this->sourceIdentityKey($values, $databaseQuantity) !== $source['key']) { + throw new RuntimeException(sprintf( + '表二第 %d 行与共享镜像 source_row_number=%d 的业务字段不一致,未写入任何物料信息。', + $source['excel_row_number'], + (int) $row->source_row_number, + )); + } + $index++; + + if ($source['material_number'] === '') { + $skippedRows++; + + continue; + } + + $validRows++; + $materials[$source['material_number']] = true; + $quote = $quotations[$source['material_number']]; + $expectedCost = $quote['price']; + $expectedAmount = $this->multiplyDecimal($expectedCost, $source['quantity']); + $currentMaterial = trim((string) ( + $values[self::MATERIAL_NUMBER_FIELD] ?? '' + )); + $currentDescription = trim((string) ( + $values[self::MATERIAL_DESCRIPTION_DATABASE_FIELD] ?? '' + )); + $currentCost = trim((string) ($values[self::COST_FIELD] ?? '')); + $currentAmount = trim((string) ( + $values[self::SHIPPING_AMOUNT_FIELD] ?? '' + )); + $isMarked = trim((string) ($values[self::REPAIR_MARKER_FIELD] ?? '')) === '是'; + $materialMatches = $currentMaterial === $source['material_number'] + && $currentDescription === $source['description']; + $financialMatches = $this->decimalEquals($currentCost, $expectedCost) + && $this->decimalEquals($currentAmount, $expectedAmount); + $changed = ! $materialMatches || ! $isMarked || ! $financialMatches; + + $store = $source['material_number'] === '' + ? '' + : trim((string) ($values['店铺'] ?? '')); + if ($store !== '') { + $stores[$store] = ($stores[$store] ?? 0) + 1; + } + if ($changed) { + $updated++; + } else { + $unchanged++; + } + + $targets[] = [ + 'row' => $row, + 'values' => $values, + 'material_number' => $source['material_number'], + 'description' => $source['description'], + 'cost' => $expectedCost, + 'shipping_amount' => $expectedAmount, + 'changed' => $changed, + ]; + } + + if ($index !== count($sourceRows)) { + throw new RuntimeException('共享镜像行数少于表二,未写入任何物料信息。'); + } + + ksort($stores); + + return [ + 'result' => [ + 'rows' => count($sourceRows), + 'valid_rows' => $validRows, + 'skipped_unmapped_rows' => $skippedRows, + 'materials' => count($materials), + 'stores' => $stores, + 'updated' => $updated, + 'unchanged' => $unchanged, + ], + 'targets' => $targets, + ]; + } + /** * @param list $materialNumbers * @return array @@ -536,6 +866,52 @@ class KukaPostingMaterialRepairImporter return implode("\x1F", $parts); } + /** + * @param array $values + */ + private function sourceIdentityKey(array $values, string $quantity): string + { + $parts = []; + foreach (self::IDENTITY_FIELDS as $field) { + if ($field === '实发数量') { + $parts[] = $quantity; + + continue; + } + + $value = trim((string) ($values[$field] ?? '')); + $parts[] = $field === '发货日期' + ? $this->normalizeDateTime($value) + : $value; + } + + return implode("\x1F", $parts); + } + + private function normalizeDateTime(string $value): string + { + if (is_numeric($value) && (float) $value > 20000 && (float) $value < 90000) { + return gmdate('Y-m-d H:i:s', (int) round(((float) $value - 25569) * 86400)); + } + if (preg_match( + '/^(\d{4})[\/-](\d{1,2})[\/-](\d{1,2})[ T](\d{1,2}):(\d{2}):(\d{2})/', + $value, + $matches, + ) === 1) { + return sprintf( + '%04d-%02d-%02d %02d:%s:%s', + (int) $matches[1], + (int) $matches[2], + (int) $matches[3], + (int) $matches[4], + $matches[5], + $matches[6], + ); + } + + return $this->normalizeDate($value); + } + private function normalizeDate(string $value): string { if (is_numeric($value) && (float) $value > 20000 && (float) $value < 90000) { @@ -558,6 +934,16 @@ class KukaPostingMaterialRepairImporter return in_array(trim($value), self::MISSING_VALUES, true); } + private function isUnmappedMaterialValue(string $value): bool + { + return $this->isMissingMaterialValue($value) + || in_array( + strtoupper(trim($value)), + ['#N/A', '#REF!', '#VALUE!', '#NAME?', '#NUM!'], + true, + ); + } + private function normalizeDecimal(mixed $value): ?string { $normalized = str_replace(',', '', trim((string) $value)); diff --git a/app/Console/Commands/ImportKukaPostingMaterialSource.php b/app/Console/Commands/ImportKukaPostingMaterialSource.php new file mode 100644 index 00000000..40e4f8e8 --- /dev/null +++ b/app/Console/Commands/ImportKukaPostingMaterialSource.php @@ -0,0 +1,64 @@ +option('month')); + if ($period === '') { + $this->error('必须指定 --month=YYYY-MM。'); + + return self::FAILURE; + } + + try { + $result = $importer->importSource( + (string) $this->argument('path'), + $period, + (string) ($this->option('sheet') ?: 'Sheet1'), + max(1, (int) $this->option('company')), + (bool) $this->option('dry-run'), + ); + } catch (Throwable $exception) { + $this->error('顾家过账物料源修正未导入,原有数据未改变。' . $exception->getMessage()); + + return self::FAILURE; + } + + $storeRows = []; + foreach ($result['stores'] as $store => $count) { + $storeRows[] = [$store, number_format($count)]; + } + + $this->table(['项目', '值'], [ + ['模式', $result['dry_run'] ? '仅校验' : '正式导入'], + ['账期', $result['period']], + ['源文件行数', number_format($result['rows'])], + ['有效物料行数', number_format($result['valid_rows'])], + ['#N/A 等跳过行数', number_format($result['skipped_unmapped_rows'])], + ['物料编号数', number_format($result['materials'])], + ['需要更新', number_format($result['updated'])], + ['已一致', number_format($result['unchanged'])], + ['文件 SHA-256', $result['file_sha256']], + ]); + $this->table(['店铺', '有效物料行数'], $storeRows); + $this->info($result['dry_run'] ? '顾家过账整表物料校验完成。' : '顾家过账整表物料已修正。'); + + return self::SUCCESS; + } +} diff --git a/deploy/finance-batch-imports.json b/deploy/finance-batch-imports.json index e1fc0fe6..5da449bd 100644 --- a/deploy/finance-batch-imports.json +++ b/deploy/finance-batch-imports.json @@ -14,6 +14,7 @@ "business-mirror:import-kuka-posting-base", "business-mirror:import-kuka-posting-labels", "business-mirror:import-kuka-posting-material-repair", + "business-mirror:import-kuka-posting-material-source", "business-mirror:import-kuka-posting-quotation", "finance-ledger:import-company-alipay", "finance-ledger:import-wangshang-bank", diff --git a/tests/Feature/Business/KukaPostingBasePageTest.php b/tests/Feature/Business/KukaPostingBasePageTest.php index 82662bbe..d49f890d 100644 --- a/tests/Feature/Business/KukaPostingBasePageTest.php +++ b/tests/Feature/Business/KukaPostingBasePageTest.php @@ -285,6 +285,16 @@ class KukaPostingBasePageTest extends FeatureTestCase 'source_row_number' => 6, 'imported_at' => now(), ]); + $connection->table('kuka_posting_material_map_rows')->insert([ + 'company_id' => $this->company->id, + 'item_number' => 'ITEM-00', + 'material_number' => '91.DYNAMIC.00', + 'match_status' => 'matched', + 'match_source' => 'barcode_material_no', + 'candidate_count' => 1, + 'candidate_materials' => '["91.DYNAMIC.00"]', + 'synced_at' => now(), + ]); $this->loginAs() ->get(route('business.pages.show', [ @@ -297,6 +307,7 @@ class KukaPostingBasePageTest extends FeatureTestCase ->assertSeeText('DS-MANUAL~异常数据修正物料') ->assertSeeText('125.50') ->assertSeeText('251.00') + ->assertDontSeeText('91.DYNAMIC.00') ->assertDontSeeText('199.00'); @unlink($file); diff --git a/tests/Unit/Business/KukaPostingMaterialRepairImporterTest.php b/tests/Unit/Business/KukaPostingMaterialRepairImporterTest.php index 239909d0..03fdb1d9 100644 --- a/tests/Unit/Business/KukaPostingMaterialRepairImporterTest.php +++ b/tests/Unit/Business/KukaPostingMaterialRepairImporterTest.php @@ -178,6 +178,49 @@ class KukaPostingMaterialRepairImporterTest extends TestCase $this->assertSame($before, $this->storedRows()); } + public function test_source_import_updates_valid_rows_in_order_and_skips_na_rows(): void + { + $this->seedBaseRows(); + $before = $this->storedRows(); + $source = $this->workbook([ + $this->row('O-1', 'P-1', 'W-1', '是', '91.M1', 'DS-M1~物料一'), + $this->row('O-1', 'P-1', 'W-1', '是', '#N/A', '#N/A'), + $this->row('O-2', 'P-2', 'W-2', '补单(订单四组)', '91.M2', 'DS-M2~物料二', '2'), + $this->row('O-1', 'P-1', 'W-OTHER', '是', '91.M1', 'DS-M1~物料一'), + ]); + + $result = $this->importer()->importSource( + $source, + '2026-10', + 'Sheet1', + 1, + ); + + $this->assertSame(4, $result['rows']); + $this->assertSame(3, $result['valid_rows']); + $this->assertSame(1, $result['skipped_unmapped_rows']); + $this->assertSame(2, $result['materials']); + $this->assertSame(3, $result['updated']); + $this->assertSame(0, $result['unchanged']); + + $after = $this->storedRows(); + $this->assertSame($before[3], $after[3]); + foreach ([2, 4, 5] as $sourceRowNumber) { + $payload = $before[$sourceRowNumber]['payload']; + $payload['物料编号'] = $sourceRowNumber === 4 ? '91.M2' : '91.M1'; + $payload['型号'] = $sourceRowNumber === 4 ? 'DS-M2~物料二' : 'DS-M1~物料一'; + $payload['成本'] = $sourceRowNumber === 4 ? '300.0000' : '125.5000'; + $payload['发货金额'] = $sourceRowNumber === 4 ? '600.0000' : '125.5000'; + $payload['物料信息修正'] = '是'; + $this->assertSame($payload, $after[$sourceRowNumber]['payload']); + } + + $second = $this->importer()->importSource($source, '2026-10', 'Sheet1'); + $this->assertSame(0, $second['updated']); + $this->assertSame(3, $second['unchanged']); + $this->assertSame($after, $this->storedRows()); + } + public function test_conflicting_material_mapping_rejects_the_file_before_writing(): void { $this->seedBaseRows(); @@ -337,7 +380,7 @@ class KukaPostingMaterialRepairImporterTest extends TestCase string $quantity = '1', ): array { return [ - '发货日期' => '46326', + '发货日期' => '46326.6756365741', '线上订单号' => $onlineOrderNo, '商品编码' => $productCode, '订单状态' => '已发货',