From c8c71fb9219a003cad999672938b6e7d4112f63a Mon Sep 17 00:00:00 2001 From: chenxi Date: Mon, 26 Oct 2026 20:32:55 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=95=86=E5=93=81=E6=88=90?= =?UTF-8?q?=E6=9C=AC=E5=8F=91=E8=B4=A7=E4=BB=93=E5=BA=93=E7=BB=A7=E6=89=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Commands/SyncStoreReceiptProductCost.php | 282 +++++++++++++++++- .../Unit/StoreReceiptProductCostLineTest.php | 185 ++++++++++++ 2 files changed, 460 insertions(+), 7 deletions(-) diff --git a/app/Console/Commands/SyncStoreReceiptProductCost.php b/app/Console/Commands/SyncStoreReceiptProductCost.php index 6e9ff39a..7f6bc1bd 100644 --- a/app/Console/Commands/SyncStoreReceiptProductCost.php +++ b/app/Console/Commands/SyncStoreReceiptProductCost.php @@ -6,6 +6,7 @@ use App\Business\StoreReceiptPlatformSkuMapper; use Illuminate\Console\Command; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\File; +use Illuminate\Support\Facades\Schema; use InvalidArgumentException; use Modules\EcommerceFinance\Repositories\AfterSalesCostRowRepository; use Modules\EcommerceFinance\Repositories\GoodsProfitAfsRepository; @@ -282,6 +283,7 @@ class SyncStoreReceiptProductCost extends Command $lineStoreName = (string) ($billByCore[$core]->store_name ?? ''); $lines[$core][] = [ 'source' => (string) $row->source_key, + 'so_id' => (string) $row->so_id, 'platform' => $linePlatform, 'store_name' => $lineStoreName, // 月加权平均单价表里的商品编码统一大写,订单侧可能小写,统一成大写再比。 @@ -324,6 +326,18 @@ class SyncStoreReceiptProductCost extends Command )); $bundleProfiles = $historyBundleMappings['profiles'] + $importedBundleMappings['profiles']; $shortNames = $this->warehouseShortNames(); + $warehouseFallback = $this->inheritWarehouseFromLinkedOrders( + $mirror, + $lines, + $shortNames, + ); + $this->info(sprintf( + '订单仓库回填:候选订单 %d 个,发货明细回填 %d 行,同单唯一仓库回填 %d 行,多仓保留 %d 行', + $warehouseFallback['candidate_orders'], + $warehouseFallback['shipment_rows'], + $warehouseFallback['order_node_rows'], + $warehouseFallback['ambiguous_rows'], + )); $prices = $this->weightedAverageUnitPrices($mirror, $reportMonth); // 月加权平均单价匹配不到时,用「线上代发价格」(采购单价 / 钉钉代发单价)兜底。 $fallbackPrices = $this->onlineDaifaUnitPrices($mirror); @@ -483,7 +497,7 @@ class SyncStoreReceiptProductCost extends Command $costLines = $filteredCostLines; foreach ($costLines as $line) { - $short = $shortNames['by_provider'][$line['warehouse']] ?? ''; + $short = self::warehouseShortNameFor((string) $line['warehouse'], $shortNames); $forceBundlePending = ! empty($line['force_cost_pending']); $price = ! $forceBundlePending && $short !== '' ? ($prices[$short . "\0" . $line['sku']] ?? null) @@ -802,6 +816,7 @@ class SyncStoreReceiptProductCost extends Command 'mapped_quantity' => round($materialMappedQuantity, 4), 'mapped_cost' => round($materialMappedCost, 2), ], + 'warehouse_fallback' => $warehouseFallback, 'pending_cost_rows' => $missingPriceRows, 'pending_cost_quantity' => round((float) $pendingCostQuantity, 4), 'missing_warehouse_rows' => $missingWarehouseRows, @@ -1021,7 +1036,7 @@ class SyncStoreReceiptProductCost extends Command * * @param array>> $lines * @param array $billByCore - * @param array{by_provider:array,by_warehouse:array} $shortNames + * @param array{by_provider:array,by_provider_normalized:array} $shortNames * @param array $prices * @param array $fallbackPrices * @param array $catalogPrices @@ -1074,7 +1089,7 @@ class SyncStoreReceiptProductCost extends Command $groups[$profileKey]['quantity'] += (float) ($row['qty'] ?? 0); $groups[$profileKey]['amount'] += (float) ($row['amount'] ?? 0); - $short = $shortNames['by_provider'][(string) ($row['warehouse'] ?? '')] ?? ''; + $short = self::warehouseShortNameFor((string) ($row['warehouse'] ?? ''), $shortNames); $weighted = $short === '' ? null : ($prices[$short . "\0" . $sku] ?? null); $fallback = $fallbackPrices[$sku] ?? null; $fallbackPrice = is_array($fallback) ? ($fallback['price'] ?? null) : $fallback; @@ -3270,17 +3285,240 @@ class SyncStoreReceiptProductCost extends Command return $expanded === [] ? [] : $expanded; } + /** + * 拆分、合并或售后子单的订单头仓库为 0 时,按同单节点和实际发货明细回填。 + * + * 只处理同一订单在其它节点已经有仓库的记录;整单所有节点都没有仓库时保持原样, + * 避免把“上游仓库未分配”误判成可自动修复。 + * + * @param list> $lines + * @param array{by_provider:array,by_provider_normalized:array} $shortNames + * @return array{candidate_orders:int,shipment_rows:int,order_node_rows:int,ambiguous_rows:int} + */ + private function inheritWarehouseFromLinkedOrders( + $mirror, + array &$lines, + array $shortNames, + ): array + { + $orders = []; + foreach ($lines as $orderLines) { + foreach ($orderLines as $line) { + if (trim((string) ($line['warehouse'] ?? '')) !== '') { + continue; + } + $source = trim((string) ($line['source'] ?? '')); + $soId = trim((string) ($line['so_id'] ?? '')); + if ($source !== '' && $soId !== '') { + $orders[$source][$soId] = true; + } + } + } + + $stats = [ + 'candidate_orders' => array_sum(array_map('count', $orders)), + 'shipment_rows' => 0, + 'order_node_rows' => 0, + 'ambiguous_rows' => 0, + ]; + if ($orders === []) { + return $stats; + } + + $nodeWarehouses = []; + $shippingWarehouses = []; + $mirror->statement('DROP TEMPORARY TABLE IF EXISTS tmp_cost_missing_wh_orders'); + $mirror->statement( + 'CREATE TEMPORARY TABLE tmp_cost_missing_wh_orders (' + . 'source_key varchar(16) NOT NULL, ' + . 'so_id varchar(191) NOT NULL, ' + . 'PRIMARY KEY (source_key, so_id)' + . ') ENGINE=InnoDB' + ); + + try { + foreach ($orders as $sourceKey => $sourceOrders) { + foreach (array_chunk(array_keys($sourceOrders), 500) as $chunk) { + $mirror->table('tmp_cost_missing_wh_orders')->insertOrIgnore( + array_map( + static fn (string $soId): array => [ + 'source_key' => $sourceKey, + 'so_id' => $soId, + ], + $chunk, + ) + ); + } + } + + foreach (self::SOURCES as $source) { + $sourceKey = (string) $source['key']; + if (! isset($orders[$sourceKey])) { + continue; + } + $rows = $mirror->select( + 'SELECT o.so_id, o.o_id, o.link_o_id, o.status, o.wms_co_id, ' + . 'COALESCE(wh.name, \'\') AS warehouse_name ' + . 'FROM tmp_cost_missing_wh_orders t ' + . 'STRAIGHT_JOIN ' . $source['orders'] . ' o ON o.so_id = t.so_id ' + . 'LEFT JOIN ops_jst_warehouse_info wh ON wh.wms_co_id = o.wms_co_id ' + . 'WHERE t.source_key = ?', + [$sourceKey], + ); + foreach ($rows as $row) { + if (strtoupper(trim((string) ($row->status ?? ''))) === 'CANCELLED') { + continue; + } + $warehouse = trim((string) ($row->warehouse_name ?? '')); + if ($warehouse === '' || $warehouse === '0') { + continue; + } + $nodeWarehouses[$sourceKey][trim((string) $row->so_id)][$warehouse] = true; + } + } + + if (Schema::connection((string) config('upstream_mirrors.connection', 'business_mirror')) + ->hasTable('js_jst_send_data_view_extension')) { + $rows = $mirror->select( + 'SELECT DISTINCT v.so_id, v.sku_ids, v.wareHoursName ' + . 'FROM tmp_cost_missing_wh_orders t ' + . 'STRAIGHT_JOIN js_jst_send_data_view_extension v ON v.so_id = t.so_id' + ); + foreach ($rows as $row) { + $soId = trim((string) $row->so_id); + $warehouse = trim((string) ($row->wareHoursName ?? '')); + if ($soId === '' || $warehouse === '' || $warehouse === '{未指定发货仓}') { + continue; + } + $skus = preg_split('/[,,;;]+/u', (string) ($row->sku_ids ?? '')) ?: []; + foreach ($skus as $sku) { + $sku = mb_strtoupper(trim($sku)); + if ($sku !== '') { + $shippingWarehouses[$soId][$sku][$warehouse] = true; + } + } + } + } + } finally { + $mirror->statement('DROP TEMPORARY TABLE IF EXISTS tmp_cost_missing_wh_orders'); + } + + $result = $this->applyWarehouseFallbacksToLines( + $lines, + $nodeWarehouses, + $shippingWarehouses, + $shortNames, + ); + + return array_merge($stats, $result); + } + + /** + * @param list> $lines + * @param array>> $nodeWarehouses + * @param array>> $shippingWarehouses + * @param array{by_provider:array,by_provider_normalized:array} $shortNames + * @return array{shipment_rows:int,order_node_rows:int,ambiguous_rows:int} + */ + private function applyWarehouseFallbacksToLines( + array &$lines, + array $nodeWarehouses, + array $shippingWarehouses, + array $shortNames, + ): array { + $shipmentRows = 0; + $orderNodeRows = 0; + $ambiguousRows = 0; + + foreach ($lines as &$orderLines) { + foreach ($orderLines as &$line) { + if (trim((string) ($line['warehouse'] ?? '')) !== '') { + continue; + } + $source = trim((string) ($line['source'] ?? '')); + $soId = trim((string) ($line['so_id'] ?? '')); + $sku = mb_strtoupper(trim((string) ($line['sku'] ?? ''))); + if ($source === '' || $soId === '' || $sku === '') { + continue; + } + + $nodeCandidates = array_keys($nodeWarehouses[$source][$soId] ?? []); + if ($nodeCandidates === []) { + continue; + } + + $shippingCandidates = array_keys($shippingWarehouses[$soId][$sku] ?? []); + if ($shippingCandidates === []) { + $expandedComponents = self::expandComboSku($sku, (float) ($line['qty'] ?? 0)); + if (count($expandedComponents) > 1) { + $componentWarehouses = []; + $resolvedComponents = 0; + $componentAmbiguous = false; + foreach ($expandedComponents as [$componentSku]) { + $componentSku = mb_strtoupper(trim((string) $componentSku)); + $candidates = array_keys($shippingWarehouses[$soId][$componentSku] ?? []); + if (count($candidates) === 1) { + $componentWarehouses[(string) $candidates[0]] = true; + $resolvedComponents++; + } elseif (count($candidates) > 1) { + $componentAmbiguous = true; + break; + } + } + if (! $componentAmbiguous && $resolvedComponents === count($expandedComponents)) { + $shippingCandidates = array_keys($componentWarehouses); + } elseif ($componentAmbiguous) { + $ambiguousRows++; + continue; + } + } + } + if (count($shippingCandidates) === 1) { + $warehouse = (string) $shippingCandidates[0]; + if (self::warehouseShortNameFor($warehouse, $shortNames) !== '') { + $line['warehouse'] = $warehouse; + $line['warehouse_fallback_source'] = 'shipment'; + $shipmentRows++; + continue; + } + } elseif (count($shippingCandidates) > 1) { + $ambiguousRows++; + continue; + } + + if (count($nodeCandidates) === 1) { + $warehouse = (string) $nodeCandidates[0]; + if (self::warehouseShortNameFor($warehouse, $shortNames) !== '') { + $line['warehouse'] = $warehouse; + $line['warehouse_fallback_source'] = 'linked_order'; + $orderNodeRows++; + } + } elseif (count($nodeCandidates) > 1) { + $ambiguousRows++; + } + } + } + unset($orderLines, $line); + + return [ + 'shipment_rows' => $shipmentRows, + 'order_node_rows' => $orderNodeRows, + 'ambiguous_rows' => $ambiguousRows, + ]; + } + /** * 仓库映射表:发货仓库 → 仓库简称。 * * 映射表按「仓储方 + 仓库」登记,仓库名带「主仓」的那条代表该仓储方的正式出货仓, * 因此优先用它作为发货仓库对应的简称;同时保留「完整仓库名 → 简称」的精确匹配。 * - * @return array{by_provider:array,by_warehouse:array} + * @return array{by_provider:array,by_provider_normalized:array} */ private function warehouseShortNames(): array { $byProvider = []; + $byProviderNormalized = []; foreach (DB::table(self::WAREHOUSE_MAPPING_TABLE) ->get(['warehouse_provider', 'warehouse', 'warehouse_short_name']) as $mapping) { $provider = trim((string) $mapping->warehouse_provider); @@ -3297,22 +3535,52 @@ class SyncStoreReceiptProductCost extends Command $isMain = str_contains($warehouse, '主仓'); if ($isMain) { $byProvider[$provider] = $short; + $byProviderNormalized[self::normalizeWarehouseLookupKey($provider)] = $short; continue; } // 映射表没有主仓行时,仅接受「仓库名 = 仓储方名」这种同名仓库(如重庆渝北仓), // 其余(次品仓、配件单仓等)不再兜底,避免把主仓订单误判成不看仓。 if ($warehouse === $provider && ! isset($byProvider[$provider])) { $byProvider[$provider] = $short; + $byProviderNormalized[self::normalizeWarehouseLookupKey($provider)] = $short; continue; } // 业务确认:常州简尚家居有限公司的发货仓对应映射表里的「配件单仓」行 // (仓储方=常州简尚家居有限公司 / 仓库=配件单仓 → 配件单仓-不看)。 if (str_contains($warehouse, '配件单仓') && ! isset($byProvider[$provider])) { $byProvider[$provider] = $short; + $byProviderNormalized[self::normalizeWarehouseLookupKey($provider)] = $short; } } - return ['by_provider' => $byProvider]; + return [ + 'by_provider' => $byProvider, + 'by_provider_normalized' => $byProviderNormalized, + ]; + } + + /** @param array{by_provider:array,by_provider_normalized:array} $shortNames */ + private static function warehouseShortNameFor(string $warehouse, array $shortNames): string + { + $warehouse = trim($warehouse); + if ($warehouse === '') { + return ''; + } + + return (string) ( + $shortNames['by_provider'][$warehouse] + ?? $shortNames['by_provider_normalized'][self::normalizeWarehouseLookupKey($warehouse)] + ?? '' + ); + } + + private static function normalizeWarehouseLookupKey(string $value): string + { + $value = str_replace(["\u{3000}", "\u{00A0}", "\u{200B}"], '', trim($value)); + $value = preg_replace('/[\x{FF0D}\x{2014}\x{2013}\x{2010}]/u', '-', $value) ?? $value; + $value = preg_replace('/\s+/u', '', $value) ?? $value; + + return mb_strtoupper($value); } /** @@ -3321,7 +3589,7 @@ class SyncStoreReceiptProductCost extends Command */ private function remapWarehouseShortNames(string $connection, string $reportMonth, string $platform): int { - $mapping = $this->warehouseShortNames()['by_provider']; + $shortNames = $this->warehouseShortNames(); $base = DB::connection($connection)->table(self::TARGET_TABLE) ->where('report_month', $reportMonth); if ($platform !== '') { @@ -3338,7 +3606,7 @@ class SyncStoreReceiptProductCost extends Command $unmatchedWarehouses = 0; foreach ($warehouses as $warehouseValue) { $warehouse = trim((string) $warehouseValue); - $short = trim((string) ($mapping[$warehouse] ?? '')); + $short = self::warehouseShortNameFor($warehouse, $shortNames); if ($short === '') { $unmatchedWarehouses++; continue; diff --git a/tests/Unit/StoreReceiptProductCostLineTest.php b/tests/Unit/StoreReceiptProductCostLineTest.php index 7350f4f1..b1cf720b 100644 --- a/tests/Unit/StoreReceiptProductCostLineTest.php +++ b/tests/Unit/StoreReceiptProductCostLineTest.php @@ -1000,6 +1000,191 @@ class StoreReceiptProductCostLineTest extends TestCase $this->assertSame(['91.C45340.01', '91.C46324.01'], $codes); } + public function test_warehouse_fallback_uses_sku_specific_shipment_warehouse(): void + { + $command = new SyncStoreReceiptProductCost(); + $method = new ReflectionMethod($command, 'applyWarehouseFallbacksToLines'); + $method->setAccessible(true); + $lines = [ + [ + ['source' => 'jst', 'so_id' => 'ORDER-1', 'sku' => 'SKU-A', 'warehouse' => ''], + ['source' => 'jst', 'so_id' => 'ORDER-1', 'sku' => 'SKU-B', 'warehouse' => ''], + ], + ]; + $shortNames = [ + 'by_provider' => ['仓库一' => '一号仓', '仓库二' => '二号仓'], + 'by_provider_normalized' => ['仓库一' => '一号仓', '仓库二' => '二号仓'], + ]; + $stats = $method->invokeArgs($command, [ + &$lines, + ['jst' => ['ORDER-1' => ['仓库一' => true, '仓库二' => true]]], + ['ORDER-1' => ['SKU-A' => ['仓库一' => true], 'SKU-B' => ['仓库二' => true]]], + $shortNames, + ]); + + $this->assertSame('仓库一', $lines[0][0]['warehouse']); + $this->assertSame('仓库二', $lines[0][1]['warehouse']); + $this->assertSame('shipment', $lines[0][0]['warehouse_fallback_source']); + $this->assertSame(2, $stats['shipment_rows']); + $this->assertSame(0, $stats['ambiguous_rows']); + } + + public function test_warehouse_fallback_uses_unique_linked_order_warehouse(): void + { + $command = new SyncStoreReceiptProductCost(); + $method = new ReflectionMethod($command, 'applyWarehouseFallbacksToLines'); + $method->setAccessible(true); + $lines = [[ + ['source' => 'qmcust', 'so_id' => 'ORDER-2', 'sku' => 'SKU-C', 'warehouse' => ''], + ]]; + $shortNames = [ + 'by_provider' => ['仓库三' => '三号仓'], + 'by_provider_normalized' => ['仓库三' => '三号仓'], + ]; + $stats = $method->invokeArgs($command, [ + &$lines, + ['qmcust' => ['ORDER-2' => ['仓库三' => true]]], + [], + $shortNames, + ]); + + $this->assertSame('仓库三', $lines[0][0]['warehouse']); + $this->assertSame('linked_order', $lines[0][0]['warehouse_fallback_source']); + $this->assertSame(1, $stats['order_node_rows']); + } + + public function test_warehouse_fallback_uses_shared_component_shipment_warehouse_for_combo_parent(): void + { + $command = new SyncStoreReceiptProductCost(); + $method = new ReflectionMethod($command, 'applyWarehouseFallbacksToLines'); + $method->setAccessible(true); + $lines = [[ + [ + 'source' => 'jst', + 'so_id' => 'ORDER-COMBO', + 'sku' => 'ZH-SKU-A-1-SKU-B-1', + 'qty' => 1, + 'warehouse' => '', + ], + ]]; + $shortNames = [ + 'by_provider' => ['仓库四' => '四号仓'], + 'by_provider_normalized' => ['仓库四' => '四号仓'], + ]; + $stats = $method->invokeArgs($command, [ + &$lines, + ['jst' => ['ORDER-COMBO' => ['仓库四' => true, '仓库五' => true]]], + ['ORDER-COMBO' => [ + 'SKU-A' => ['仓库四' => true], + 'SKU-B' => ['仓库四' => true], + ]], + $shortNames, + ]); + + $this->assertSame('仓库四', $lines[0][0]['warehouse']); + $this->assertSame('shipment', $lines[0][0]['warehouse_fallback_source']); + $this->assertSame(1, $stats['shipment_rows']); + } + + public function test_structured_combo_expansion_preserves_inherited_warehouse(): void + { + [$lines] = $this->costLines([ + $this->row( + 'structured-combo', + 'ZH-GBJP-XG023009BN1241V01-1-GBJP-XG023009AN1241V01-1', + 'STRUCTURED-COMBO-ITEM', + 1, + 656, + '', + ['warehouse' => '简尚-横林二仓'], + ), + ]); + + $codes = array_column($lines, 'sku'); + sort($codes, SORT_STRING); + $this->assertSame([ + 'GBJP-XG023009AN1241V01', + 'GBJP-XG023009BN1241V01', + ], $codes); + $this->assertSame( + ['简尚-横林二仓'], + array_values(array_unique(array_column($lines, 'warehouse'))), + ); + } + + public function test_goods_profit_split_preserves_combo_and_accessory_warehouses(): void + { + $profileKey = "jst\0" . "9137685\0" . "10225748028159\0" . "10035143770956"; + [$lines] = $this->costLines([ + $this->row('accessory', 'AD021301N486V01', '10035122472678', 1, 0, '', [ + 'o_id' => '9137685', + 'shop_sku_id' => '10225462581437', + 'warehouse' => '工厂-山东菏泽森美代发仓', + ]), + $this->row( + 'combo', + 'ZH-GBJP-XG023009BN1241V01-1-GBJP-XG023009AN1241V01-1', + '10035143770956', + 1, + 656, + '', + [ + 'o_id' => '9137685', + 'shop_sku_id' => '10225748028159', + 'warehouse' => '简尚-横林二仓', + ], + ), + ], [], [ + $profileKey => [ + 'source' => 'goods_profit_current_order', + 'components' => [ + 'GBJP-XG023009AN1241V01' => ['qty' => 1, 'amount' => 328.00], + 'GBJP-XG023009BN1241V01' => ['qty' => 1, 'amount' => 328.00], + ], + ], + ]); + + $bySku = collect($lines)->keyBy('sku'); + $this->assertSame('工厂-山东菏泽森美代发仓', $bySku['AD021301N486V01']['warehouse']); + $this->assertSame('简尚-横林二仓', $bySku['GBJP-XG023009AN1241V01']['warehouse']); + $this->assertSame('简尚-横林二仓', $bySku['GBJP-XG023009BN1241V01']['warehouse']); + } + + public function test_warehouse_fallback_keeps_whole_order_without_warehouse_unchanged(): void + { + $command = new SyncStoreReceiptProductCost(); + $method = new ReflectionMethod($command, 'applyWarehouseFallbacksToLines'); + $method->setAccessible(true); + $lines = [[ + ['source' => 'jst', 'so_id' => 'ORDER-3', 'sku' => 'SKU-D', 'warehouse' => ''], + ]]; + $stats = $method->invokeArgs($command, [ + &$lines, + [], + [], + ['by_provider' => [], 'by_provider_normalized' => []], + ]); + + $this->assertSame('', $lines[0][0]['warehouse']); + $this->assertSame(0, $stats['shipment_rows']); + $this->assertSame(0, $stats['order_node_rows']); + $this->assertSame(0, $stats['ambiguous_rows']); + } + + public function test_warehouse_short_name_normalizes_lookup_key(): void + { + $command = new SyncStoreReceiptProductCost(); + $method = new ReflectionMethod($command, 'warehouseShortNameFor'); + $method->setAccessible(true); + + $short = $method->invoke($command, "工厂-广东健荣代发仓\u{3000}", [ + 'by_provider' => [], + 'by_provider_normalized' => ['工厂-广东健荣代发仓' => '代发仓'], + ]); + + $this->assertSame('代发仓', $short); + } + /** @return array{0:list>,1:int,2:int,3:int,4:int,5:array} */ private function costLines( array $rows, -- 2.47.2