From 204f728a4ab6e498e49009ce84307db4692114a9 Mon Sep 17 00:00:00 2001 From: chenxi Date: Tue, 27 Oct 2026 11:50:44 +0800 Subject: [PATCH] =?UTF-8?q?fix:=2091=20=E6=96=99=E5=8F=B7=E6=94=B9?= =?UTF-8?q?=E7=94=A8=E6=99=AE=E9=80=9A=E5=95=86=E5=93=81=E5=90=AF=E7=94=A8?= =?UTF-8?q?=E7=8A=B6=E6=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/商品成本占位行规则清单.md | 8 +- .../ProductCatalogMirrorRepository.php | 63 ++++++++++++++++ ...roductMaterialBarcodeMappingRepository.php | 74 ++++++++++++------- .../ProductCatalogMirrorRepositoryTest.php | 28 +++++++ ...ctMaterialBarcodeMappingRepositoryTest.php | 38 +++++++--- 5 files changed, 167 insertions(+), 44 deletions(-) diff --git a/docs/商品成本占位行规则清单.md b/docs/商品成本占位行规则清单.md index 015940fb..79f6a8f2 100644 --- a/docs/商品成本占位行规则清单.md +++ b/docs/商品成本占位行规则清单.md @@ -41,7 +41,7 @@ store-receipt:product-cost:sync YYYY-MM --remap-warehouses-only | MKH-运营组合套装 | 商品编码以 `MKH-运营组合套装` 开头 | 不进入中文后缀或通用父子别名清洗,交给组合装组件规则 | 组件缺失时待核验 | | 零值组合占位 | 主行数量和金额均为 0,且没有可对平组件 | 不生成商品成本行 | 组件若存在但金额无法对平,忽略空主行,组件按原价格路径计价 | | 人工可读配件 | `原木色广岛`、`原木色舒美特实木面1把`、`胡桃色舒美特实木面1把` | 保持原编码,按现有价格来源计价 | 无有效价格时待核验,禁止自动删中文 | -| 91. 基础料号 | 商品编码匹配 `91.C数字.数字`,可带规格尾缀,例如 `91.C46324.01-N1280` | 去掉尾缀后由 `materialNo` 找基础 SKU 及条码,再关联商品档案;仅保留商品状态为「销售」的条码,并按条码档案创建时间取最新。无条码记录时才回退基础 SKU | 无销售候选或最新时间并列时保留原编码并进入待核验 | +| 91. 基础料号 | 商品编码匹配 `91.C数字.数字`,可带规格尾缀,例如 `91.C46324.01-N1280` | 去掉尾缀后由 `materialNo` 找基础 SKU 及条码;条码和创建时间取外部条码库,启用状态取系统普通商品资料 `sku_type=normal AND enabled=1`。仅保留启用条码并按创建时间取最新;无条码记录时才回退基础 SKU | 无启用候选或最新时间并列时保留原编码并进入待核验 | | 其他中文别名 | 不属于上述分类,且找不到唯一正式编码或组件关系 | 不改写编码 | 保留原行待核验 | 中文后缀规则的严格匹配键为: @@ -111,13 +111,13 @@ store-receipt:product-cost:sync YYYY-MM --remap-warehouses-only 91.C49784.01-N1280-1 → 91.C49784.01 ``` -映射来源是只读来源 `product_barcode_catalog` 的 `public."BarcodePrintImportRecord"` 和 `public."SupplyChainProductArchive"`: +条码来源是只读来源 `product_barcode_catalog` 的 `public."BarcodePrintImportRecord"` 和 `public."SupplyChainProductArchive"`;启用状态来自系统普通商品资料共享镜像 `ops_jst_sku`: 1. 按 `updates->>'materialNo'` 匹配规范化基础料号; 2. 基础 SKU 优先取 `normalizedSku`,为空时回退 `skuCode`; 3. 目标商品编码优先取同一基础 SKU 的 `updates.barcode`;没有规格条码时才回退基础 SKU; -4. 条码或基础 SKU 必须能在商品档案找到 `productStatus = '销售'` 的记录,停产及无档案候选不参与映射; -5. 同一料号存在多个销售条码时,按商品档案的 `createdAt` 取最新;档案时间缺失时才使用条码导入记录 `createdAt`; +4. 条码或基础 SKU 必须在 `ops_jst_sku` 找到 `sku_type = 'normal' AND enabled = 1` 的记录,停用、非普通商品及普通商品排除清单中的候选不参与映射; +5. 同一料号存在多个启用条码时,按外部商品档案的 `createdAt` 取最新;档案时间缺失时才使用条码导入记录 `createdAt`; 6. 最新时间对应唯一商品编码时自动替换;最高时间并列多个编码时保留原编码并写入待核验,禁止随机选择; 7. 替换后仍按「月加权平均单价 → 线上代发价格 → 普通商品资料成本价」计算成本; 8. 不同尾缀映射到同一目标编码时,按「发货仓库 + 目标商品编码」合并数量,避免重复成本行。 diff --git a/modules/EcommerceFinance/Repositories/ProductCatalogMirrorRepository.php b/modules/EcommerceFinance/Repositories/ProductCatalogMirrorRepository.php index cf64df24..80339bc2 100644 --- a/modules/EcommerceFinance/Repositories/ProductCatalogMirrorRepository.php +++ b/modules/EcommerceFinance/Repositories/ProductCatalogMirrorRepository.php @@ -221,6 +221,69 @@ class ProductCatalogMirrorRepository ->all(); } + /** + * 商品成本 91 料号映射使用:返回普通商品资料中实际存在且启用的 SKU。 + * + * @param list $skuCodes + * @return array 以大写、去空格并还原 _X002B_ 的商品编码为键 + */ + public function enabledNormalSkuCodes(array $skuCodes): array + { + $lookupValues = []; + foreach ($skuCodes as $skuCode) { + $raw = trim((string) $skuCode); + if ($raw === '') { + continue; + } + $upper = mb_strtoupper($raw, 'UTF-8'); + $lower = mb_strtolower($raw, 'UTF-8'); + foreach ([$raw, $upper, $lower] as $value) { + $lookupValues[] = $value; + $lookupValues[] = str_replace('+', '_X002B_', $value); + $lookupValues[] = str_replace(['_X002B_', '_x002b_'], '+', $value); + } + } + $lookupValues = array_values(array_unique(array_filter( + $lookupValues, + static fn (string $value): bool => $value !== '', + ))); + + if ($lookupValues === []) { + return []; + } + + $productTable = $this->dataset()->targetTable(); + $query = $this->connection->table($productTable) + ->where('sku_type', 'normal') + ->where('enabled', 1) + ->whereIn('sku_id', $lookupValues) + ->select(['_mirror_key', 'sku_id']); + + if (Schema::connection($this->connection->getName())->hasTable('product_catalog_exclusions')) { + $normalizedSql = "REPLACE(UPPER(TRIM({$productTable}.sku_id)), '_X002B_', '+')"; + $query->whereNotExists(static function ($query) use ($productTable, $normalizedSql): void { + $query->selectRaw('1') + ->from('product_catalog_exclusions as product_exclusions') + ->whereColumn('product_exclusions.mirror_key', "{$productTable}._mirror_key") + ->whereRaw("product_exclusions.sku_id_normalized = {$normalizedSql}"); + }); + } + + $enabled = []; + foreach ($query->cursor() as $row) { + $sku = str_replace( + '_X002B_', + '+', + mb_strtoupper(trim((string) ($row->sku_id ?? '')), 'UTF-8'), + ); + if ($sku !== '') { + $enabled[$sku] = true; + } + } + + return $enabled; + } + /** * @param array $filters * @return Generator diff --git a/modules/EcommerceFinance/Repositories/ProductMaterialBarcodeMappingRepository.php b/modules/EcommerceFinance/Repositories/ProductMaterialBarcodeMappingRepository.php index b1ede6ca..6bb215cb 100644 --- a/modules/EcommerceFinance/Repositories/ProductMaterialBarcodeMappingRepository.php +++ b/modules/EcommerceFinance/Repositories/ProductMaterialBarcodeMappingRepository.php @@ -9,8 +9,7 @@ use Throwable; /** * 商品成本使用的基础料号 → 内部商品编码映射。 * - * 只读取条码打印导入记录和供应链商品档案的固定字段;数据库账号和连接参数由 - * 系统设置中的 product_barcode_catalog 来源提供,不进入仓库或业务数据。 + * 条码、创建时间读取 product_barcode_catalog;商品启用状态读取系统普通商品资料。 */ class ProductMaterialBarcodeMappingRepository { @@ -38,7 +37,11 @@ class ProductMaterialBarcodeMappingRepository * source_rows:int * } */ - public function resolve(array $materialCodes, ?UpstreamReadOnlyQuery $query = null): array + public function resolve( + array $materialCodes, + ?UpstreamReadOnlyQuery $query = null, + ?callable $enabledSkuLookup = null, + ): array { $normalized = []; foreach ($materialCodes as $code) { @@ -60,6 +63,9 @@ class ProductMaterialBarcodeMappingRepository } $query ??= new UpstreamReadOnlyQuery(self::SOURCE_KEY, 15); + $enabledSkuLookup ??= static fn (array $skuCodes): array => app( + ProductCatalogMirrorRepository::class, + )->enabledNormalSkuCodes($skuCodes); /** @var array> $candidates */ $candidates = []; $sourceRows = 0; @@ -84,47 +90,37 @@ class ProductMaterialBarcodeMappingRepository . 'ON COALESCE(NULLIF(BTRIM(product_rows."normalizedSku"), \'\'), ' . 'NULLIF(BTRIM(product_rows."skuCode"), \'\')) = material_skus.sku_code ' . "WHERE NULLIF(BTRIM(product_rows.updates->>'barcode'), '') IS NOT NULL" - . '), active_barcode_matches AS (' + . '), barcode_candidates AS (' . 'SELECT barcode_matches.material_no, barcode_matches.mapped_sku, ' - . 'archive."createdAt" AS candidate_created_at, ' - . 'archive."businessCreatedAt" AS business_created_at, ' - . 'archive."productStatus" AS product_status, ' - . 'barcode_matches.import_record_created_at ' + . 'COALESCE(archive."createdAt", barcode_matches.import_record_created_at) ' + . 'AS candidate_created_at ' . 'FROM barcode_matches ' - . 'JOIN public."SupplyChainProductArchive" archive ' + . 'LEFT JOIN public."SupplyChainProductArchive" archive ' . 'ON UPPER(BTRIM(archive.barcode)) = barcode_matches.mapped_sku ' - . "WHERE archive.\"productStatus\" = '销售'" - . '), base_sku_matches AS (' + . '), base_sku_candidates AS (' . 'SELECT material_skus.material_no, ' - . 'UPPER(BTRIM(archive.sku::text)) AS mapped_sku, ' - . 'archive."createdAt" AS candidate_created_at, ' - . 'archive."businessCreatedAt" AS business_created_at, ' - . 'archive."productStatus" AS product_status, ' - . 'NULL::timestamp AS import_record_created_at ' + . 'UPPER(BTRIM(material_skus.sku_code)) AS mapped_sku, ' + . 'archive."createdAt" AS candidate_created_at ' . 'FROM material_skus ' - . 'JOIN public."SupplyChainProductArchive" archive ' + . 'LEFT JOIN public."SupplyChainProductArchive" archive ' . 'ON UPPER(BTRIM(archive.sku::text)) = UPPER(BTRIM(material_skus.sku_code)) ' . 'WHERE NOT EXISTS (' . 'SELECT 1 FROM barcode_matches ' . 'WHERE barcode_matches.material_no = material_skus.material_no' + . ')' . ') ' - . "AND archive.\"productStatus\" = '销售'" - . ') ' - . 'SELECT material_no, mapped_sku, candidate_created_at, business_created_at, ' - . 'product_status, import_record_created_at ' - . 'FROM active_barcode_matches ' + . 'SELECT material_no, mapped_sku, candidate_created_at ' + . 'FROM barcode_candidates ' . 'UNION ' - . 'SELECT material_no, mapped_sku, candidate_created_at, business_created_at, ' - . 'product_status, import_record_created_at ' - . 'FROM base_sku_matches', + . 'SELECT material_no, mapped_sku, candidate_created_at ' + . 'FROM base_sku_candidates', $chunk, ); foreach ($rows as $row) { $sourceRows++; $materialCode = self::normalizeMaterialCode((string) ($row['material_no'] ?? '')); $mappedSku = mb_strtoupper(trim((string) ($row['mapped_sku'] ?? ''))); - $productStatus = trim((string) ($row['product_status'] ?? '')); - if ($materialCode === null || $mappedSku === '' || $productStatus !== '销售') { + if ($materialCode === null || $mappedSku === '') { continue; } $createdAt = trim((string) ( @@ -148,11 +144,33 @@ class ProductMaterialBarcodeMappingRepository ); } + $candidateSkus = []; + foreach ($candidates as $mappedCandidates) { + foreach (array_keys($mappedCandidates) as $mappedSku) { + $candidateSkus[(string) $mappedSku] = true; + } + } + ksort($candidateSkus, SORT_STRING); + + try { + $enabledSkus = $enabledSkuLookup(array_keys($candidateSkus)); + } catch (Throwable $exception) { + throw new RuntimeException( + '91 基础料号普通商品状态读取失败:' . $exception->getMessage(), + 0, + $exception, + ); + } + $unique = []; $ambiguous = []; $missing = []; foreach ($materialCodes as $materialCode) { - $mappedCandidates = $candidates[$materialCode] ?? []; + $mappedCandidates = array_filter( + $candidates[$materialCode] ?? [], + static fn (string $createdAt, string $mappedSku): bool => isset($enabledSkus[$mappedSku]), + ARRAY_FILTER_USE_BOTH, + ); if ($mappedCandidates === []) { $missing[] = $materialCode; continue; diff --git a/tests/Unit/EcommerceFinance/ProductCatalogMirrorRepositoryTest.php b/tests/Unit/EcommerceFinance/ProductCatalogMirrorRepositoryTest.php index 7e744bd2..254d3938 100644 --- a/tests/Unit/EcommerceFinance/ProductCatalogMirrorRepositoryTest.php +++ b/tests/Unit/EcommerceFinance/ProductCatalogMirrorRepositoryTest.php @@ -467,6 +467,34 @@ class ProductCatalogMirrorRepositoryTest extends TestCase $this->assertSame(['SKU-KEEP'], array_map(static fn (object $row): string => $row->sku_id, $export)); } + public function test_enabled_sku_lookup_only_returns_enabled_normal_non_excluded_products(): void + { + $this->markReady(4); + $this->insertProduct(10, ['sku_id' => 'SKU-KEEP']); + $this->insertProduct(20, ['sku_id' => 'SKU-OFF', 'enabled' => 0]); + $this->insertProduct(30, ['sku_id' => 'SKU-PACKAGE', 'sku_type' => 'package']); + $this->insertProduct(40, ['sku_id' => 'SKU-EXCLUDED']); + $this->createExclusionTable(); + DB::connection('business_mirror')->table('product_catalog_exclusions')->insert([ + 'mirror_key' => hash('sha256', '40'), + 'autoid' => 40, + 'sku_id' => 'SKU-EXCLUDED', + 'sku_id_normalized' => 'SKU-EXCLUDED', + 'source_generation' => '11111111-1111-4111-8111-111111111111', + 'excluded_at' => '2026-08-25 14:00:00', + ]); + + $this->assertSame( + ['SKU-KEEP' => true], + $this->repository->enabledNormalSkuCodes([ + 'SKU-KEEP', + 'SKU-OFF', + 'SKU-PACKAGE', + 'SKU-EXCLUDED', + ]), + ); + } + public function test_an_exclusion_does_not_hide_a_reused_mirror_key_after_the_sku_code_changes(): void { $this->markReady(1); diff --git a/tests/Unit/EcommerceFinance/ProductMaterialBarcodeMappingRepositoryTest.php b/tests/Unit/EcommerceFinance/ProductMaterialBarcodeMappingRepositoryTest.php index f8f5566c..5468d3cf 100644 --- a/tests/Unit/EcommerceFinance/ProductMaterialBarcodeMappingRepositoryTest.php +++ b/tests/Unit/EcommerceFinance/ProductMaterialBarcodeMappingRepositoryTest.php @@ -36,8 +36,8 @@ class ProductMaterialBarcodeMappingRepositoryTest extends TestCase $sql, 'FROM public."BarcodePrintImportRecord"', ) && str_contains($sql, "updates->>'barcode'") - && str_contains($sql, 'JOIN public."SupplyChainProductArchive"') - && str_contains($sql, "archive.\"productStatus\" = '销售'") + && str_contains($sql, 'LEFT JOIN public."SupplyChainProductArchive"') + && ! str_contains($sql, '"productStatus"') && str_contains($sql, 'archive."createdAt"') && substr_count($sql, '?') === 5), [ @@ -52,59 +52,59 @@ class ProductMaterialBarcodeMappingRepositoryTest extends TestCase [ 'material_no' => '91.C45340.01', 'mapped_sku' => 'GBGJ-SJ025102N09V01', - 'product_status' => '销售', 'candidate_created_at' => '2026-08-07 05:08:00', ], [ 'material_no' => '91.C45340.01', 'mapped_sku' => 'GBGJ-SJ025102N09V01', - 'product_status' => '销售', 'candidate_created_at' => '2026-08-07 05:09:00', ], [ 'material_no' => '91.C45438.01', 'mapped_sku' => 'GBGJ-DNZ036601N09V01', - 'product_status' => '销售', 'candidate_created_at' => '2026-08-07 05:08:56', ], [ 'material_no' => '91.C45438.01', 'mapped_sku' => 'MKHDNZ0409260601235', - 'product_status' => '销售', 'candidate_created_at' => '2026-08-07 05:11:13', ], [ 'material_no' => '91.C45438.01', 'mapped_sku' => 'GBGJ-DNZ036601N08V01', - 'product_status' => '停产', 'candidate_created_at' => '2026-08-07 05:12:00', ], [ 'material_no' => '91.C45492.01', 'mapped_sku' => 'GBGJ-CYJ005701N1282V01', - 'product_status' => '停产', 'candidate_created_at' => '2026-08-07 05:12:00', ], [ 'material_no' => '91.C45492.01', 'mapped_sku' => 'GBGJ-CYJ005701N1411V01', - 'product_status' => '销售', 'candidate_created_at' => '2026-08-07 05:09:31', ], [ 'material_no' => '91.C45493.01', 'mapped_sku' => 'SKU-TIE-A', - 'product_status' => '销售', 'candidate_created_at' => '2026-08-07 05:10:00', ], [ 'material_no' => '91.C45493.01', 'mapped_sku' => 'SKU-TIE-B', - 'product_status' => '销售', 'candidate_created_at' => '2026-08-07 05:10:00', ], ]); + $enabledSkus = [ + 'GBGJ-SJ025102N09V01' => true, + 'GBGJ-DNZ036601N09V01' => true, + 'MKHDNZ0409260601235' => true, + 'GBGJ-CYJ005701N1411V01' => true, + 'SKU-TIE-A' => true, + 'SKU-TIE-B' => true, + ]; + $lookupCalls = []; $result = (new ProductMaterialBarcodeMappingRepository())->resolve([ '91.C45340.01-N09', '91.C45438.01-N09', @@ -112,7 +112,10 @@ class ProductMaterialBarcodeMappingRepositoryTest extends TestCase '91.C45493.01-N01', '91.C49784.01-N1280-1', 'GBGJ-SJ025102', - ], $query); + ], $query, static function (array $skuCodes) use ($enabledSkus, &$lookupCalls): array { + $lookupCalls[] = $skuCodes; + return $enabledSkus; + }); $this->assertSame([ '91.C45340.01' => 'GBGJ-SJ025102N09V01', @@ -124,5 +127,16 @@ class ProductMaterialBarcodeMappingRepositoryTest extends TestCase ], $result['ambiguous']); $this->assertSame(['91.C49784.01'], $result['missing']); $this->assertSame(9, $result['source_rows']); + $this->assertCount(1, $lookupCalls); + $this->assertSame([ + 'GBGJ-CYJ005701N1282V01', + 'GBGJ-CYJ005701N1411V01', + 'GBGJ-DNZ036601N08V01', + 'GBGJ-DNZ036601N09V01', + 'GBGJ-SJ025102N09V01', + 'MKHDNZ0409260601235', + 'SKU-TIE-A', + 'SKU-TIE-B', + ], $lookupCalls[0]); } } -- 2.47.2