diff --git a/app/Console/Commands/SyncStoreReceiptProductCost.php b/app/Console/Commands/SyncStoreReceiptProductCost.php index b8494cf2..a2ff7fa7 100644 --- a/app/Console/Commands/SyncStoreReceiptProductCost.php +++ b/app/Console/Commands/SyncStoreReceiptProductCost.php @@ -7,6 +7,7 @@ use Illuminate\Console\Command; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\File; use InvalidArgumentException; +use Modules\EcommerceFinance\Repositories\GoodsProfitAfsRepository; use Throwable; /** @@ -266,7 +267,7 @@ class SyncStoreReceiptProductCost extends Command } $this->info('订单侧命中核心单号:' . count($lines)); - $platformSkuMapper = $this->platformSkuMapper($mirror, $lines); + $platformSkuMappings = $this->platformSkuMapper($mirror, $lines, $billByCore); $shortNames = $this->warehouseShortNames(); $prices = $this->weightedAverageUnitPrices($mirror, $reportMonth); // 月加权平均单价匹配不到时,用「线上代发价格」(采购单价 / 钉钉代发单价)兜底。 @@ -299,6 +300,7 @@ class SyncStoreReceiptProductCost extends Command $plusParentExcludedRows = 0; $variantParentExcludedRows = 0; $autoReplacedRows = 0; + $afsReplacedRows = 0; $mappingAmbiguousRows = 0; $mappingMissingRows = 0; $pendingCostRows = []; @@ -324,9 +326,15 @@ class SyncStoreReceiptProductCost extends Command $bundleParentExcludedRows += $excludedBundleParents; $plusParentExcludedRows += $excludedPlusParents; $variantParentExcludedRows += $excludedVariantParents; - $mapped = $this->mapPlatformSkus($costLines, $platformSkuMapper); + $mapped = $this->mapPlatformSkus( + $costLines, + $platformSkuMappings['history'], + $platformSkuMappings['afs'], + (string) $bill->store_name, + ); $costLines = $mapped['lines']; $autoReplacedRows += $mapped['auto_replaced_rows']; + $afsReplacedRows += $mapped['afs_replaced_rows']; $mappingAmbiguousRows += $mapped['ambiguous_rows']; $mappingMissingRows += $mapped['missing_rows']; @@ -381,8 +389,8 @@ class SyncStoreReceiptProductCost extends Command 'product_quantity' => $quantity, 'reason' => $short === '' ? '未匹配仓库简称' - : (($line['platform_mapping_status'] ?? null) === 'ambiguous' - ? '平台 shop_sku_id 对应多个历史内部商品编码' + : (in_array(($line['platform_mapping_status'] ?? null), ['ambiguous', 'ambiguous_afs'], true) + ? '平台 shop_sku_id 在历史订单或售后镜像中对应多个内部商品编码' : (($line['platform_mapping_status'] ?? null) === 'missing' ? '平台 shop_sku_id 未找到历史内部商品编码' : '仓库简称 + 商品编码在月加权、线上代发、普通商品资料中均无有效单价')), @@ -447,8 +455,9 @@ class SyncStoreReceiptProductCost extends Command number_format((float) $pendingCostQuantity, 2), )); $this->info(sprintf( - ' 平台数字 SKU 自动替换:%d 行;多候选保留:%d 行;无历史映射保留:%d 行', + ' 平台数字 SKU 自动替换:%d 行(售后镜像补充:%d 行);多候选保留:%d 行;无可用映射保留:%d 行', $autoReplacedRows, + $afsReplacedRows, $mappingAmbiguousRows, $mappingMissingRows, )); @@ -469,6 +478,7 @@ class SyncStoreReceiptProductCost extends Command 'excluded_rows' => $placeholderExcludedRows + $bundleParentExcludedRows + $plusParentExcludedRows + $variantParentExcludedRows, 'auto_replaced_platform_sku_rows' => $autoReplacedRows, + 'afs_fallback_replaced_platform_sku_rows' => $afsReplacedRows, 'platform_sku_mapping_ambiguous_rows' => $mappingAmbiguousRows, 'platform_sku_mapping_missing_rows' => $mappingMissingRows, 'pending_cost_rows' => $missingPriceRows, @@ -520,21 +530,38 @@ class SyncStoreReceiptProductCost extends Command /** * @param array>> $lines + * @param array $billByCore + * @return array{ + * history:StoreReceiptPlatformSkuMapper, + * afs:array> + * } */ - private function platformSkuMapper($mirror, array $lines): StoreReceiptPlatformSkuMapper + private function platformSkuMapper($mirror, array $lines, array $billByCore): array { - $candidates = []; - foreach ($lines as $orderLines) { + $historyCandidates = []; + $afsCandidates = []; + foreach ($lines as $core => $orderLines) { + $shopName = trim((string) ($billByCore[$core]->store_name ?? '')); foreach ($orderLines as $line) { $sku = mb_strtoupper(trim((string) ($line['sku'] ?? ''))); $shopSkuId = trim((string) ($line['shop_sku_id'] ?? '')); $shopItemId = trim((string) ($line['shop_i_id'] ?? '')); if ( - preg_match('/^\d+$/', $sku) === 1 - && $shopSkuId !== '' - && $shopItemId !== '' + preg_match('/^\d+$/', $sku) !== 1 + || $shopSkuId === '' + || $shopItemId === '' ) { - $candidates[$shopSkuId . "\0" . $shopItemId] = [ + continue; + } + + $historyCandidates[$shopSkuId . "\0" . $shopItemId] = [ + 'shop_sku_id' => $shopSkuId, + 'shop_i_id' => $shopItemId, + ]; + if ($shopName !== '') { + $afsKey = self::afsPlatformSkuKey($shopName, $shopSkuId, $shopItemId); + $afsCandidates[$afsKey] = [ + 'shop_name' => $shopName, 'shop_sku_id' => $shopSkuId, 'shop_i_id' => $shopItemId, ]; @@ -542,52 +569,81 @@ class SyncStoreReceiptProductCost extends Command } } - if ($candidates === []) { - return new StoreReceiptPlatformSkuMapper([]); - } - - $mirror->statement('DROP TEMPORARY TABLE IF EXISTS tmp_platform_sku_keys'); - $mirror->statement( - 'CREATE TEMPORARY TABLE tmp_platform_sku_keys (' - . 'shop_sku_id varchar(255) NOT NULL, ' - . 'shop_i_id varchar(255) NOT NULL, ' - . 'PRIMARY KEY (shop_sku_id, shop_i_id)' - . ') ENGINE=InnoDB', - ); - $historyRows = []; - try { - foreach (array_chunk(array_values($candidates), 500) as $chunk) { - $mirror->table('tmp_platform_sku_keys')->insertOrIgnore($chunk); - } - - foreach (self::SOURCES as $source) { - $rows = $mirror->select( - "SELECT i.shop_sku_id, i.shop_i_id, i.sku_id, i.i_id, i.properties_value - FROM {$source['items']} i - STRAIGHT_JOIN tmp_platform_sku_keys k - ON k.shop_sku_id = i.shop_sku_id - AND k.shop_i_id = i.shop_i_id - WHERE COALESCE(i.i_id, '') <> '' - AND i.i_id <> i.shop_i_id", - ); - foreach ($rows as $row) { - $historyRows[] = $row; - } - } - } catch (Throwable $exception) { - $this->warn('平台 SKU 历史映射读取失败,本批数字 SKU 保持待核验:' . $exception->getMessage()); - } finally { + if ($historyCandidates !== []) { $mirror->statement('DROP TEMPORARY TABLE IF EXISTS tmp_platform_sku_keys'); + $mirror->statement( + 'CREATE TEMPORARY TABLE tmp_platform_sku_keys (' + . 'shop_sku_id varchar(255) NOT NULL, ' + . 'shop_i_id varchar(255) NOT NULL, ' + . 'PRIMARY KEY (shop_sku_id, shop_i_id)' + . ') ENGINE=InnoDB', + ); + + try { + foreach (array_chunk(array_values($historyCandidates), 500) as $chunk) { + $mirror->table('tmp_platform_sku_keys')->insertOrIgnore($chunk); + } + + foreach (self::SOURCES as $source) { + $rows = $mirror->select( + "SELECT i.shop_sku_id, i.shop_i_id, i.sku_id, i.i_id, i.properties_value + FROM {$source['items']} i + STRAIGHT_JOIN tmp_platform_sku_keys k + ON k.shop_sku_id = i.shop_sku_id + AND k.shop_i_id = i.shop_i_id + WHERE COALESCE(i.i_id, '') <> '' + AND i.i_id <> i.shop_i_id", + ); + foreach ($rows as $row) { + $historyRows[] = $row; + } + } + } catch (Throwable $exception) { + $this->warn('平台 SKU 历史映射读取失败,将尝试订单售后镜像:' . $exception->getMessage()); + } finally { + $mirror->statement('DROP TEMPORARY TABLE IF EXISTS tmp_platform_sku_keys'); + } } + $afsMappings = []; + if ($afsCandidates !== []) { + try { + $rows = app(GoodsProfitAfsRepository::class) + ->platformSkuMappings(array_values($afsCandidates)); + foreach ($rows as $row) { + $productCode = mb_strtoupper(trim((string) ($row['product_code'] ?? ''))); + if ($productCode === '') { + continue; + } + $key = self::afsPlatformSkuKey( + (string) ($row['shop_name'] ?? ''), + (string) ($row['shop_sku_id'] ?? ''), + (string) ($row['shop_i_id'] ?? ''), + ); + $afsMappings[$key][$productCode] = true; + } + } catch (Throwable $exception) { + $this->warn('订单售后镜像平台 SKU 映射读取失败,相关数字 SKU 保持待核验:' . $exception->getMessage()); + } + } + foreach ($afsMappings as &$codes) { + $codes = array_keys($codes); + sort($codes); + } + unset($codes); + $this->info(sprintf( - '平台数字 SKU 候选:%d 个;历史内部商品映射记录:%d 条', - count($candidates), + '平台数字 SKU 候选:%d 个;历史内部商品映射:%d 条;售后镜像映射键:%d 个', + count($historyCandidates), count($historyRows), + count($afsMappings), )); - return new StoreReceiptPlatformSkuMapper($historyRows); + return [ + 'history' => new StoreReceiptPlatformSkuMapper($historyRows), + 'afs' => $afsMappings, + ]; } /** @@ -595,13 +651,17 @@ class SyncStoreReceiptProductCost extends Command * @return array{ * lines:list>, * auto_replaced_rows:int, + * afs_replaced_rows:int, * ambiguous_rows:int, * missing_rows:int * } + * @param array> $afsMappings */ private function mapPlatformSkus( array $lines, StoreReceiptPlatformSkuMapper $mapper, + array $afsMappings = [], + string $storeName = '', ): array { $mappedLines = []; foreach ($lines as $line) { @@ -618,12 +678,32 @@ class SyncStoreReceiptProductCost extends Command && $shopItemId !== '' ) { $resolution = $mapper->resolve($shopSkuId, $shopItemId); - $line['platform_mapping_status'] = $resolution['status']; - $line['platform_mapping_candidates'] = $resolution['candidates']; + $mappingStatus = $resolution['status']; + $mappingCandidates = $resolution['candidates']; + $internalSku = $resolution['internal_sku']; + if ($mappingStatus === 'missing') { + $afsCandidates = $afsMappings[self::afsPlatformSkuKey($storeName, $shopSkuId, $shopItemId)] ?? []; + if (count($afsCandidates) === 1) { + $mappingStatus = 'unique_afs'; + $mappingCandidates = $afsCandidates; + $internalSku = $afsCandidates[0]; + } elseif (count($afsCandidates) > 1) { + $mappingStatus = 'ambiguous_afs'; + $mappingCandidates = $afsCandidates; + $internalSku = null; + } + } + + $line['platform_mapping_status'] = $mappingStatus; + $line['platform_mapping_candidates'] = $mappingCandidates; $line['original_platform_sku'] = $sku; - if ($resolution['status'] === 'unique' && $resolution['internal_sku'] !== null) { - $line['sku'] = mb_strtoupper($resolution['internal_sku']); + if ( + in_array($mappingStatus, ['unique', 'unique_afs'], true) + && $internalSku !== null + ) { + $line['sku'] = mb_strtoupper($internalSku); $line['auto_mapped_platform_sku'] = true; + $line['platform_mapping_source'] = $mappingStatus === 'unique_afs' ? 'afs' : 'history'; } } @@ -638,18 +718,23 @@ class SyncStoreReceiptProductCost extends Command if (! empty($line['auto_mapped_platform_sku'])) { $mappedLines[$key]['auto_mapped_platform_sku'] = true; $mappedLines[$key]['original_platform_sku'] = $line['original_platform_sku']; - $mappedLines[$key]['platform_mapping_status'] = 'unique'; + $mappedLines[$key]['platform_mapping_status'] = $line['platform_mapping_status']; $mappedLines[$key]['platform_mapping_candidates'] = $line['platform_mapping_candidates']; + $mappedLines[$key]['platform_mapping_source'] = $line['platform_mapping_source'] ?? null; } } $autoReplacedRows = 0; + $afsReplacedRows = 0; $ambiguousRows = 0; $missingRows = 0; foreach ($mappedLines as $line) { if (! empty($line['auto_mapped_platform_sku'])) { $autoReplacedRows++; - } elseif (($line['platform_mapping_status'] ?? null) === 'ambiguous') { + if (($line['platform_mapping_source'] ?? null) === 'afs') { + $afsReplacedRows++; + } + } elseif (in_array(($line['platform_mapping_status'] ?? null), ['ambiguous', 'ambiguous_afs'], true)) { $ambiguousRows++; } elseif (($line['platform_mapping_status'] ?? null) === 'missing') { $missingRows++; @@ -659,6 +744,7 @@ class SyncStoreReceiptProductCost extends Command return [ 'lines' => array_values($mappedLines), 'auto_replaced_rows' => $autoReplacedRows, + 'afs_replaced_rows' => $afsReplacedRows, 'ambiguous_rows' => $ambiguousRows, 'missing_rows' => $missingRows, ]; @@ -694,6 +780,14 @@ class SyncStoreReceiptProductCost extends Command . "\0" . $shopSkuId; } + private static function afsPlatformSkuKey( + string $shopName, + string $shopSkuId, + string $shopItemId, + ): string { + return trim($shopName) . "\0" . trim($shopSkuId) . "\0" . trim($shopItemId); + } + /** * 非数字父行先限定到同一订单、平台商品和发货仓,再比较可用的平台规格维度。 * diff --git a/modules/EcommerceFinance/Repositories/GoodsProfitAfsRepository.php b/modules/EcommerceFinance/Repositories/GoodsProfitAfsRepository.php index 0106d199..d6c2a90e 100644 --- a/modules/EcommerceFinance/Repositories/GoodsProfitAfsRepository.php +++ b/modules/EcommerceFinance/Repositories/GoodsProfitAfsRepository.php @@ -83,6 +83,93 @@ class GoodsProfitAfsRepository return $this->fieldColumns = $map; } + /** + * 按「店铺 + 店铺商品编码 + 店铺款式编码」批量读取售后镜像中的内部商品编码。 + * + * 仅作为商品成本历史拆分映射失败后的补充证据,不直接修改售后页面数据。 + * + * @param list $candidates + * @return list + */ + public function platformSkuMappings(array $candidates): array + { + $keys = []; + foreach ($candidates as $candidate) { + $shopName = trim((string) ($candidate['shop_name'] ?? '')); + $shopSkuId = trim((string) ($candidate['shop_sku_id'] ?? '')); + $shopItemId = trim((string) ($candidate['shop_i_id'] ?? '')); + if ($shopName === '' || $shopSkuId === '' || $shopItemId === '') { + continue; + } + $keys[$shopName . "\0" . $shopSkuId . "\0" . $shopItemId] = [ + 'shop_name' => $shopName, + 'shop_sku_id' => $shopSkuId, + 'shop_i_id' => $shopItemId, + ]; + } + if ($keys === []) { + return []; + } + + $columns = $this->fieldColumns(); + foreach (['shop_name', 'shop_product_code', 'shop_style_code', 'product_code'] as $field) { + if (! isset($columns[$field]) + || preg_match('/^[A-Za-z0-9_]+$/', (string) $columns[$field]) !== 1) { + return []; + } + } + + $connection = $this->connection(); + $table = '`' . self::MAIN_TABLE . '`'; + $shopName = '`' . $columns['shop_name'] . '`'; + $shopProductCode = '`' . $columns['shop_product_code'] . '`'; + $shopStyleCode = '`' . $columns['shop_style_code'] . '`'; + $productCode = '`' . $columns['product_code'] . '`'; + + $connection->statement('DROP TEMPORARY TABLE IF EXISTS tmp_cost_afs_sku_keys'); + $connection->statement( + 'CREATE TEMPORARY TABLE tmp_cost_afs_sku_keys (' + . 'shop_name varchar(191) NOT NULL, ' + . 'shop_sku_id varchar(128) NOT NULL, ' + . 'shop_i_id varchar(128) NOT NULL, ' + . 'PRIMARY KEY (shop_name, shop_sku_id, shop_i_id)' + . ') ENGINE=InnoDB', + ); + + $rows = []; + try { + foreach (array_chunk(array_values($keys), 500) as $chunk) { + $connection->table('tmp_cost_afs_sku_keys')->insertOrIgnore($chunk); + } + + $records = $connection->select( + "SELECT DISTINCT + m.{$shopName} AS shop_name, + m.{$shopProductCode} AS shop_sku_id, + m.{$shopStyleCode} AS shop_i_id, + m.{$productCode} AS product_code + FROM {$table} m + STRAIGHT_JOIN tmp_cost_afs_sku_keys k + ON k.shop_name = m.{$shopName} + AND k.shop_sku_id = m.{$shopProductCode} + AND k.shop_i_id = m.{$shopStyleCode} + WHERE COALESCE(TRIM(m.{$productCode}), '') <> ''", + ); + foreach ($records as $record) { + $rows[] = [ + 'shop_name' => trim((string) $record->shop_name), + 'shop_sku_id' => trim((string) $record->shop_sku_id), + 'shop_i_id' => trim((string) $record->shop_i_id), + 'product_code' => mb_strtoupper(trim((string) $record->product_code)), + ]; + } + } finally { + $connection->statement('DROP TEMPORARY TABLE IF EXISTS tmp_cost_afs_sku_keys'); + } + + return $rows; + } + /** @param array $filters */ public function covers(array $filters): bool { diff --git a/resources/views/business/pages/financial-operations/product-costs.blade.php b/resources/views/business/pages/financial-operations/product-costs.blade.php index ff9fedb0..f48b3102 100644 --- a/resources/views/business/pages/financial-operations/product-costs.blade.php +++ b/resources/views/business/pages/financial-operations/product-costs.blade.php @@ -112,7 +112,8 @@ 常州简尚家居有限公司对应映射表里的「配件单仓」行), 商品单价按「仓库简称 + 商品编码」取「商品月加权平均单价」里的加权平均价;匹配不到时退回「线上代发价格」 (采购单价优先、其次钉钉代发单价),仍匹配不到时用「普通商品资料」里的商品成本价兜底;商品成本 = 商品数量 × 商品单价。 - 平台数字 SKU 会按平台 SKU ID + 商品 ID 回查历史已拆分订单,仅唯一内部编码自动替换;多候选保持待核验。 + 平台数字 SKU 会按平台 SKU ID + 商品 ID 回查历史已拆分订单;历史无结果时,再按店铺名称 + 店铺商品编码 + 店铺款式编码 + 回查订单售后费用镜像,仅唯一内部编码自动替换;多候选保持待核验。 同一订单下已有内部商品编码时,平台数字商品占位行不参与成本;组合装拆分后,组合装主行不参与成本,只取组件行。 拆单只取最末级订单行(没有任何下级的叶子行),主单和中间汇总层不参与、避免重复计数; 同一单分多仓发货的按末级实际仓库分行;虚拟条码(X0000x)不计入; diff --git a/tests/Unit/StoreReceiptProductCostLineTest.php b/tests/Unit/StoreReceiptProductCostLineTest.php index f59560d3..27b888f7 100644 --- a/tests/Unit/StoreReceiptProductCostLineTest.php +++ b/tests/Unit/StoreReceiptProductCostLineTest.php @@ -137,6 +137,85 @@ class StoreReceiptProductCostLineTest extends TestCase $this->assertSame('SG006367N1028V01', $result['lines'][0]['sku']); $this->assertSame('958530694526', $result['lines'][0]['original_platform_sku']); $this->assertSame('unique', $result['lines'][0]['platform_mapping_status']); + $this->assertSame(0, $result['afs_replaced_rows']); + } + + public function test_afs_mapping_is_used_when_history_has_no_internal_sku(): void + { + [$lines] = $this->costLines([ + $this->row('platform', '905560897216', '3779397502214734671', 1, 297.52), + ]); + $command = new SyncStoreReceiptProductCost(); + $method = new ReflectionMethod($command, 'mapPlatformSkus'); + $method->setAccessible(true); + $afsMappings = [ + "抖音-佰汇家具店\0" . "3533103677164802\0" . '3779397502214734671' => [ + 'SG009135N1063V01', + ], + ]; + + $result = $method->invoke( + $command, + $lines, + new StoreReceiptPlatformSkuMapper([]), + $afsMappings, + '抖音-佰汇家具店', + ); + + $this->assertSame(1, $result['auto_replaced_rows']); + $this->assertSame(1, $result['afs_replaced_rows']); + $this->assertSame('SG009135N1063V01', $result['lines'][0]['sku']); + $this->assertSame('unique_afs', $result['lines'][0]['platform_mapping_status']); + $this->assertSame('afs', $result['lines'][0]['platform_mapping_source']); + } + + public function test_afs_multiple_candidates_remain_pending_and_history_ambiguity_is_not_overridden(): void + { + [$lines] = $this->costLines([ + $this->row('platform', '905560897216', '3779397502214734671', 1, 297.52), + ]); + $command = new SyncStoreReceiptProductCost(); + $method = new ReflectionMethod($command, 'mapPlatformSkus'); + $method->setAccessible(true); + $key = "抖音-佰汇家具店\0" . "3533103677164802\0" . '3779397502214734671'; + + $ambiguousAfs = $method->invoke( + $command, + $lines, + new StoreReceiptPlatformSkuMapper([]), + [$key => ['SG009105N1063V01', 'SG009135N1063V01']], + '抖音-佰汇家具店', + ); + $this->assertSame(0, $ambiguousAfs['auto_replaced_rows']); + $this->assertSame(1, $ambiguousAfs['ambiguous_rows']); + $this->assertSame('905560897216', $ambiguousAfs['lines'][0]['sku']); + $this->assertSame('ambiguous_afs', $ambiguousAfs['lines'][0]['platform_mapping_status']); + + $history = new StoreReceiptPlatformSkuMapper([ + [ + 'shop_sku_id' => '3533103677164802', + 'shop_i_id' => '3779397502214734671', + 'sku_id' => 'SG009105N1063V01', + 'i_id' => 'SG0091', + 'properties_value' => '', + ], + [ + 'shop_sku_id' => '3533103677164802', + 'shop_i_id' => '3779397502214734671', + 'sku_id' => 'SG009135N1063V01', + 'i_id' => 'SG0091', + 'properties_value' => '', + ], + ]); + $historyWins = $method->invoke( + $command, + $lines, + $history, + [$key => ['SG009135N1063V01']], + '抖音-佰汇家具店', + ); + $this->assertSame(0, $historyWins['auto_replaced_rows']); + $this->assertSame('ambiguous', $historyWins['lines'][0]['platform_mapping_status']); } public function test_yunfei_and_bcj_are_excluded_globally_and_from_bundle_components(): void