商品成本:回溯组合套装组件并对账金额 #536

Merged
chenxi merged 1 commits from fix/chenxi-product-cost-bundle-backfill into main 2026-10-24 23:47:24 +08:00
4 changed files with 504 additions and 41 deletions

View File

@ -201,7 +201,7 @@ class SyncStoreReceiptProductCost extends Command
}
$this->info('订单侧候选单号:' . count($candidates));
/** @var array<string,list<array{source:string,sku:string,qty:float,amount:float,warehouse:string,o_id:string,parent_o_id:string,row_key:string,status:string,shop_i_id:string,shop_sku_id:string,outer_oi_id:string,properties_value:string,src_combine_sku_id:string}>> $lines */
/** @var array<string,list<array<string,mixed>>> $lines */
$lines = [];
$excludedSkuSql = "'" . implode("','", self::EXCLUDED_SKUS) . "'";
foreach (self::SOURCES as $source) {
@ -213,7 +213,8 @@ class SyncStoreReceiptProductCost extends Command
. " COALESCE(wh.name, '') as warehouse_name, "
. " o.o_id as o_id, o.link_o_id as parent_o_id, "
. " CONCAT(o.o_id, '-', i.oi_id) as row_key, "
. " i.sku_id as sku_id, i.qty as qty, i.amount as amount, o.status as status, "
. " i.sku_id as sku_id, i.sku_type as sku_type, i.base_price as base_price, "
. " i.name as item_name, i.qty as qty, i.amount as amount, o.status as status, "
. " i.shop_i_id as shop_i_id, i.shop_sku_id as shop_sku_id, "
. " i.outer_oi_id as outer_oi_id, "
. " i.properties_value as properties_value, i.src_combine_sku_id as src_combine_sku_id
@ -241,8 +242,13 @@ class SyncStoreReceiptProductCost extends Command
}
$qty = (float) $row->qty;
$amount = (float) $row->amount;
// 数量与金额都为 0 的行是拆单/换货留下的占位行,不是真实发货商品。
if ($qty == 0.0 && $amount == 0.0) {
// 数量与金额都为 0 的普通行是拆单/换货占位;组合装主行即使已清零,
// 仍需保留用于与拆分组件对账,不能在这里提前丢弃。
if (
$qty == 0.0
&& $amount == 0.0
&& ! self::isBundleParentSku($sku, (string) ($row->sku_type ?? ''))
) {
continue;
}
$warehouse = trim((string) $row->warehouse_name);
@ -273,6 +279,9 @@ class SyncStoreReceiptProductCost extends Command
'store_name' => $lineStoreName,
// 月加权平均单价表里的商品编码统一大写,订单侧可能小写,统一成大写再比。
'sku' => mb_strtoupper($sku),
'sku_type' => mb_strtolower(trim((string) ($row->sku_type ?? ''))),
'base_price' => (float) ($row->base_price ?? 0),
'item_name' => trim((string) ($row->item_name ?? '')),
'qty' => $qty,
'amount' => $amount,
'warehouse' => $warehouse,
@ -345,6 +354,7 @@ class SyncStoreReceiptProductCost extends Command
'plus_parent_code_rows' => [],
'planting_prefix_code_rows' => [],
];
$bundleRollup = self::initialPlaceholderStats()['bundle_stats'];
foreach ($billByCore as $core => $bill) {
// 展示单号与业绩明细完全一致;$core 只用于订单侧清洗后匹配。
@ -371,6 +381,15 @@ class SyncStoreReceiptProductCost extends Command
+ (int) $rowCount;
}
}
foreach (($placeholderStats['bundle_stats'] ?? []) as $bundleMetric => $bundleValue) {
if (is_array($bundleValue)) {
foreach ($bundleValue as $code => $_) {
$bundleRollup[$bundleMetric][$code] = true;
}
} else {
$bundleRollup[$bundleMetric] += $bundleValue;
}
}
$mapped = $this->mapPlatformSkus(
$costLines,
$platformSkuMappings['history'],
@ -385,10 +404,13 @@ class SyncStoreReceiptProductCost extends Command
foreach ($costLines as $line) {
$short = $shortNames['by_provider'][$line['warehouse']] ?? '';
$price = $short !== '' ? ($prices[$short . "\0" . $line['sku']] ?? null) : null;
$forceBundlePending = ! empty($line['force_cost_pending']);
$price = ! $forceBundlePending && $short !== ''
? ($prices[$short . "\0" . $line['sku']] ?? null)
: null;
$priceSource = $price === null ? null : self::PRICE_SOURCE_WEIGHTED;
// 月加权平均单价按「仓库简称 + 商品编码」匹配不到时,退回线上代发价格(按商品编码)。
if ($price === null) {
if (! $forceBundlePending && $price === null) {
$fallback = $fallbackPrices[$line['sku']] ?? null;
if ($fallback !== null) {
$price = $fallback['price'];
@ -397,7 +419,7 @@ class SyncStoreReceiptProductCost extends Command
}
}
// 线上代发价格也没有时,最后用普通商品资料的商品成本价兜底。
if ($price === null) {
if (! $forceBundlePending && $price === null) {
$catalogPrice = $catalogPrices[$line['sku']] ?? null;
if ($catalogPrice !== null) {
$price = $catalogPrice;
@ -411,6 +433,11 @@ class SyncStoreReceiptProductCost extends Command
$cost = $priced['cost'];
$remarks = [];
if ($forceBundlePending) {
$remarks[] = ($line['bundle_resolution_status'] ?? '') === 'amount_mismatch'
? '组合装组件金额不一致'
: '组合装未找到可用组件';
}
if ($short === '') {
$remarks[] = self::REMARK_NO_WAREHOUSE;
$missingWarehouseRows++;
@ -431,15 +458,29 @@ class SyncStoreReceiptProductCost extends Command
'properties_value' => $line['properties_value'] ?? null,
'mapping_status' => $line['platform_mapping_status'] ?? null,
'mapping_candidates' => $line['platform_mapping_candidates'] ?? [],
'bundle_resolution_status' => $line['bundle_resolution_status'] ?? null,
'bundle_component_rows' => (int) ($line['bundle_component_rows'] ?? 0),
'bundle_component_amount' => $line['bundle_component_amount'] ?? null,
'bundle_expected_amount' => $line['bundle_expected_amount'] ?? null,
'bundle_amount_difference' => $line['bundle_amount_difference'] ?? null,
'bundle_component_codes' => $line['bundle_component_codes'] ?? [],
'product_quantity' => $quantity,
'reason' => $short === ''
'reason' => $forceBundlePending
? (($line['bundle_resolution_status'] ?? '') === 'amount_mismatch'
? '组合装组件金额与主行金额不一致,组件行暂不计成本'
: '组合装未找到可计价组件')
: ($short === ''
? '未匹配仓库简称'
: (in_array(($line['platform_mapping_status'] ?? null), ['ambiguous', 'ambiguous_afs'], true)
? '平台 shop_sku_id 在历史订单或售后镜像中对应多个内部商品编码'
: (($line['platform_mapping_status'] ?? null) === 'missing'
? '平台 shop_sku_id 未找到历史内部商品编码'
: '仓库简称 + 商品编码在月加权、线上代发、普通商品资料中均无有效单价')),
'code_type' => $this->pendingCodeType((string) $line['sku']),
: '仓库简称 + 商品编码在月加权、线上代发、普通商品资料中均无有效单价'))),
'code_type' => $forceBundlePending
? (($line['bundle_resolution_status'] ?? '') === 'amount_mismatch'
? '组合装组件金额不一致'
: '组合装未找到可用组件')
: $this->pendingCodeType((string) $line['sku']),
];
} else {
$matchedPriceRows++;
@ -508,6 +549,18 @@ class SyncStoreReceiptProductCost extends Command
$mappingAmbiguousRows,
$mappingMissingRows,
));
$this->info(sprintf(
' 组合装回溯:对平 %d 组,剔除主行 %d 行,保留组件 %d 行(识别明确指向 %d 行、同规格兼容 %d 行);缺组件 %d 组,金额不一致 %d 组,暂不计组件 %d 行,忽略零值空占位 %d 组',
$bundleRollup['reconciled_groups'],
$bundleParentExcludedRows,
$bundleRollup['component_rows'] - $bundleRollup['held_component_rows'],
$bundleRollup['explicit_component_rows'],
$bundleRollup['inferred_component_rows'],
$bundleRollup['missing_component_groups'],
$bundleRollup['amount_mismatch_groups'],
$bundleRollup['held_component_rows'],
$bundleRollup['zero_placeholder_ignored_groups'],
));
$result = [
'status' => 'success',
@ -526,7 +579,8 @@ class SyncStoreReceiptProductCost extends Command
'planting_prefix_excluded_rows' => $plantingPrefixExcludedRows,
'excluded_rows' => $placeholderExcludedRows + $bundleParentExcludedRows
+ $plusParentExcludedRows + $variantParentExcludedRows
+ $chineseAliasReplacedRows + $plantingPrefixExcludedRows,
+ $chineseAliasReplacedRows + $plantingPrefixExcludedRows
+ $bundleRollup['held_component_rows'],
'placeholder_rule_codes' => array_map(
static function (array $codes): array {
$codes = array_keys($codes);
@ -537,6 +591,20 @@ class SyncStoreReceiptProductCost extends Command
$placeholderCodeSets,
),
'placeholder_rule_code_rows' => $placeholderCodeRows,
'bundle_backfill' => [
'reconciled_groups' => $bundleRollup['reconciled_groups'],
'missing_component_groups' => $bundleRollup['missing_component_groups'],
'amount_mismatch_groups' => $bundleRollup['amount_mismatch_groups'],
'zero_placeholder_ignored_groups' => $bundleRollup['zero_placeholder_ignored_groups'],
'component_rows' => $bundleRollup['component_rows'],
'explicit_component_rows' => $bundleRollup['explicit_component_rows'],
'inferred_component_rows' => $bundleRollup['inferred_component_rows'],
'held_component_rows' => $bundleRollup['held_component_rows'],
'reconciled_amount' => round((float) $bundleRollup['reconciled_amount'], 2),
'mismatch_amount' => round((float) $bundleRollup['mismatch_amount'], 2),
'component_codes' => array_keys($bundleRollup['component_codes']),
'unreconciled_parent_codes' => array_keys($bundleRollup['unreconciled_parent_codes']),
],
'auto_replaced_platform_sku_rows' => $autoReplacedRows,
'afs_fallback_replaced_platform_sku_rows' => $afsReplacedRows,
'platform_sku_mapping_ambiguous_rows' => $mappingAmbiguousRows,
@ -782,6 +850,19 @@ class SyncStoreReceiptProductCost extends Command
$mappedLines[$key]['platform_mapping_candidates'] = $line['platform_mapping_candidates'];
$mappedLines[$key]['platform_mapping_source'] = $line['platform_mapping_source'] ?? null;
}
foreach ([
'force_cost_pending',
'bundle_resolution_status',
'bundle_component_rows',
'bundle_component_amount',
'bundle_expected_amount',
'bundle_amount_difference',
'bundle_component_codes',
] as $bundleField) {
if (! empty($line[$bundleField])) {
$mappedLines[$key][$bundleField] = $line[$bundleField];
}
}
}
$autoReplacedRows = 0;
@ -971,6 +1052,20 @@ class SyncStoreReceiptProductCost extends Command
'bundle_parent_code_rows' => [],
'plus_parent_code_rows' => [],
'planting_prefix_code_rows' => [],
'bundle_stats' => [
'reconciled_groups' => 0,
'missing_component_groups' => 0,
'amount_mismatch_groups' => 0,
'zero_placeholder_ignored_groups' => 0,
'component_rows' => 0,
'explicit_component_rows' => 0,
'inferred_component_rows' => 0,
'held_component_rows' => 0,
'reconciled_amount' => 0.0,
'mismatch_amount' => 0.0,
'component_codes' => [],
'unreconciled_parent_codes' => [],
],
];
}
@ -996,6 +1091,239 @@ class SyncStoreReceiptProductCost extends Command
return '内部商品编码缺少有效价格';
}
private static function isBundleParentSku(string $sku, string $skuType = ''): bool
{
$sku = mb_strtoupper(trim($sku));
if ($sku === '') {
return false;
}
if (in_array(mb_strtolower(trim($skuType)), ['combine', '组合'], true)) {
return true;
}
if (str_contains($sku, '组合')) {
return true;
}
foreach (self::COMBO_PREFIXES as $prefix) {
if (str_starts_with($sku, $prefix)) {
return true;
}
}
return false;
}
/** @param array<string,mixed> $row */
private static function isBundleParentRow(array $row): bool
{
if (trim((string) ($row['src_combine_sku_id'] ?? '')) !== '') {
return false;
}
return self::isBundleParentSku(
(string) ($row['sku'] ?? ''),
(string) ($row['sku_type'] ?? ''),
);
}
/** @param array<string,mixed> $row */
private function bundleContextKey(array $row): ?string
{
$parts = [
trim((string) ($row['source'] ?? '')),
trim((string) ($row['o_id'] ?? '')),
trim((string) ($row['outer_oi_id'] ?? '')),
trim((string) ($row['shop_sku_id'] ?? '')),
trim((string) ($row['shop_i_id'] ?? '')),
];
if (in_array('', $parts, true)) {
return null;
}
return implode("\0", $parts);
}
/**
* 先对组合装主行和组件做金额对账,再允许后续成本计算。
* 明确 src_combine_sku_id 指向父行的组件优先;同一订单、规格和仓库下
* 没有标记但金额可与主行对平的组件作为兼容路径。
*
* @param array<string,array<string,mixed>> $unique
* @param array<string,mixed> $stats
*/
private function resolveBundleParents(array &$unique, array &$stats): void
{
$parentGroups = [];
foreach ($unique as $key => $row) {
if (! self::isBundleParentRow($row)) {
continue;
}
$context = $this->bundleContextKey($row);
if ($context === null) {
continue;
}
$parentSku = mb_strtoupper(trim((string) $row['sku']));
$parentGroups[$context][$parentSku][$key] = $row;
}
$heldComponents = [];
foreach ($parentGroups as $context => $groups) {
foreach ($groups as $parentSku => $parentRows) {
$parentKeys = array_fill_keys(array_keys($parentRows), true);
$firstParent = reset($parentRows);
$parentSource = (string) ($firstParent['source'] ?? '');
$parentOrderId = (string) ($firstParent['o_id'] ?? '');
$explicitChildren = [];
$inferredChildren = [];
foreach ($unique as $childKey => $child) {
if (isset($parentKeys[$childKey])) {
continue;
}
if (
(string) ($child['source'] ?? '') !== $parentSource
|| (string) ($child['o_id'] ?? '') !== $parentOrderId
) {
continue;
}
$childSku = mb_strtoupper(trim((string) ($child['sku'] ?? '')));
$sourceParent = mb_strtoupper(trim((string) ($child['src_combine_sku_id'] ?? '')));
if ($sourceParent === $parentSku) {
$explicitChildren[$childKey] = $child;
continue;
}
if (
self::isBundleParentRow($child)
|| $this->bundleContextKey($child) !== $context
|| (
abs((float) ($child['qty'] ?? 0)) <= 0.0001
&& abs((float) ($child['amount'] ?? 0)) <= 0.005
)
) {
continue;
}
$inferredChildren[$childKey] = $child;
}
$children = $explicitChildren + $inferredChildren;
$componentAmount = 0.0;
$maxComponentQty = 0.0;
$componentCodes = [];
foreach ($children as $child) {
$componentAmount += (float) ($child['amount'] ?? 0);
$maxComponentQty = max($maxComponentQty, (float) ($child['qty'] ?? 0));
$componentCodes[mb_strtoupper(trim((string) ($child['sku'] ?? '')))] = true;
}
$parentAmount = 0.0;
$parentQuantity = 0.0;
$basePrices = [];
foreach ($parentRows as $parent) {
$parentAmount += (float) ($parent['amount'] ?? 0);
$parentQuantity += (float) ($parent['qty'] ?? 0);
$basePrice = max((float) ($parent['base_price'] ?? 0), 0.0);
if ($basePrice > 0) {
$basePrices[(string) round($basePrice, 4)] = $basePrice;
}
}
$candidateTotals = [];
if ($parentAmount > 0) {
$candidateTotals[(string) round($parentAmount, 2)] = round($parentAmount, 2);
}
foreach ($basePrices as $basePrice) {
if ($maxComponentQty > 0) {
$candidateTotals[(string) round($basePrice * $maxComponentQty, 2)]
= round($basePrice * $maxComponentQty, 2);
}
$candidateTotals[(string) round($basePrice, 2)] = round($basePrice, 2);
}
$expectedAmount = $candidateTotals === [] ? 0.0 : reset($candidateTotals);
foreach ($candidateTotals as $candidate) {
if (
abs((float) $candidate - $componentAmount)
< abs((float) $expectedAmount - $componentAmount)
) {
$expectedAmount = (float) $candidate;
}
}
$difference = round($componentAmount - $expectedAmount, 2);
$reconciled = $children !== []
&& $candidateTotals !== []
&& abs($difference) <= 0.01;
$zeroPlaceholder = abs($parentAmount) <= 0.005
&& abs($parentQuantity) <= 0.0001;
// 数量、金额均为 0 的组合主行原本就不进入成本表。对平后仍按
// 正常组合规则只计组件;没有组件或无法对平时忽略该空占位,
// 组件保持原有计价路径,避免凭空产生新的主行待核验。
if ($zeroPlaceholder && ($children === [] || ! $reconciled)) {
$stats['bundle_stats']['zero_placeholder_ignored_groups']++;
foreach (array_keys($parentKeys) as $parentKey) {
unset($unique[$parentKey]);
}
continue;
}
if ($reconciled) {
$stats['bundle_parent_excluded_rows'] += count($parentKeys);
$stats['bundle_parent_codes'][$parentSku] = true;
$stats['bundle_parent_code_rows'][$parentSku]
= ($stats['bundle_parent_code_rows'][$parentSku] ?? 0) + count($parentKeys);
$bundleStats = &$stats['bundle_stats'];
$bundleStats['reconciled_groups']++;
$bundleStats['component_rows'] += count($children);
$bundleStats['explicit_component_rows'] += count($explicitChildren);
$bundleStats['inferred_component_rows'] += count($inferredChildren);
$bundleStats['reconciled_amount'] += $componentAmount;
foreach (array_keys($componentCodes) as $componentCode) {
$bundleStats['component_codes'][$componentCode] = true;
}
unset($bundleStats);
foreach (array_keys($parentKeys) as $parentKey) {
unset($unique[$parentKey]);
}
continue;
}
$bundleStats = &$stats['bundle_stats'];
$bundleStats['component_rows'] += count($children);
$bundleStats['explicit_component_rows'] += count($explicitChildren);
$bundleStats['inferred_component_rows'] += count($inferredChildren);
$bundleStats['unreconciled_parent_codes'][$parentSku] = true;
if ($children === []) {
$bundleStats['missing_component_groups']++;
} else {
$bundleStats['amount_mismatch_groups']++;
$bundleStats['mismatch_amount'] += abs($difference);
foreach (array_keys($children) as $childKey) {
$heldComponents[$childKey] = true;
}
}
foreach (array_keys($componentCodes) as $componentCode) {
$bundleStats['component_codes'][$componentCode] = true;
}
unset($bundleStats);
foreach (array_keys($parentKeys) as $parentKey) {
$unique[$parentKey] = array_merge($unique[$parentKey], [
'force_cost_pending' => true,
'bundle_resolution_status' => $children === []
? 'missing_components'
: 'amount_mismatch',
'bundle_component_rows' => count($children),
'bundle_component_amount' => round($componentAmount, 2),
'bundle_expected_amount' => round($expectedAmount, 2),
'bundle_amount_difference' => $difference,
'bundle_component_codes' => array_keys($componentCodes),
]);
}
}
}
$stats['bundle_stats']['held_component_rows'] += count($heldComponents);
foreach (array_keys($heldComponents) as $childKey) {
unset($unique[$childKey]);
}
}
/**
* 拆单取数:聚水潭拆单后,主单/中间汇总单(被其他行 link 到的 o_id)只是汇总记录,
* 最末级订单行(没有任何下级)才是实际发货行。
@ -1037,7 +1365,11 @@ class SyncStoreReceiptProductCost extends Command
unset($unique[$key]);
}
// 3) 上游有些平台组合会同时返回「+ 拼接父行」和多条组件行。
// 3) 组合装主行先与拆分组件做金额对账;主行不计成本,
// 只有组件金额能与主行金额对平时才剔除主行并保留组件。
$this->resolveBundleParents($unique, $stats);
// 4) 上游有些平台组合会同时返回「+ 拼接父行」和多条组件行。
// 只有同一订单、outer_oi_id、shop_sku_id 下至少有两条组件,且组件金额
// 合计与父行一致时,父行才是可确认的汇总占位,才允许排除。
$plusParents = [];
@ -1070,7 +1402,7 @@ class SyncStoreReceiptProductCost extends Command
}
}
// 4) 中文占位后缀只允许明确白名单(当前为「非」)。
// 5) 中文占位后缀只允许明确白名单(当前为「非」)。
// 必须同数据源、平台、店铺、子订单、shop_sku_id、shop_i_id、仓库,
// 且占位行与正式编码行各自唯一、数量和金额完全一致,才保留正式编码。
$aliasGroups = [];
@ -1112,7 +1444,7 @@ class SyncStoreReceiptProductCost extends Command
}
}
// 5) 非纯数字父行:同一订单、平台商品、平台规格、子订单和发货仓内,
// 6) 非纯数字父行:同一订单、平台商品、平台规格、子订单和发货仓内,
// 如果只有一个严格扩展编码的子商品,且父子数量、金额都一致,则父行是可核对的别名占位。
// 只依赖编码前缀会误删正常的相似商品,因此任一项不一致都保留父行待核验。
$variantGroups = [];
@ -1178,28 +1510,6 @@ class SyncStoreReceiptProductCost extends Command
unset($unique[$key]);
}
// 6) 组合装拆分后的组件会记录 src_combine_sku_id。源订单上的组合装主行
// 只是汇总占位,不能与组件同时计入成本。
$bundleParents = [];
foreach ($unique as $row) {
$parentSku = mb_strtoupper(trim((string) ($row['src_combine_sku_id'] ?? '')));
if ($parentSku !== '') {
$bundleParents[$row['source'] . "\0" . $row['o_id'] . "\0" . $parentSku] = true;
}
}
if ($bundleParents !== []) {
foreach ($unique as $key => $row) {
if (isset($bundleParents[$row['source'] . "\0" . $row['o_id'] . "\0" . $row['sku']])) {
$stats['bundle_parent_excluded_rows']++;
$bundleSku = mb_strtoupper(trim((string) $row['sku']));
$stats['bundle_parent_codes'][$bundleSku] = true;
$stats['bundle_parent_code_rows'][$bundleSku]
= ($stats['bundle_parent_code_rows'][$bundleSku] ?? 0) + 1;
unset($unique[$key]);
}
}
}
// 7) 平台原始商品编码通常是一长串数字。同一订单、同一 shop_i_id
// 如果已经有内部商品编码,则数字行只是平台占位,不参与成本。
$internalSiblings = [];
@ -1228,7 +1538,10 @@ class SyncStoreReceiptProductCost extends Command
// 解析不了的组合条码(条码被截断等)保持原样,避免丢行。
$expanded = [];
foreach ($unique as $row) {
foreach (self::expandComboSku((string) $row['sku'], (float) $row['qty']) as [$code, $codeQty, $isComponent]) {
$expandedCodes = ! empty($row['force_cost_pending'])
? [[(string) $row['sku'], (float) $row['qty'], false]]
: self::expandComboSku((string) $row['sku'], (float) $row['qty']);
foreach ($expandedCodes as [$code, $codeQty, $isComponent]) {
$expanded[] = array_merge($row, [
'sku' => mb_strtoupper($code),
'qty' => $codeQty,
@ -1295,6 +1608,13 @@ class SyncStoreReceiptProductCost extends Command
'shop_i_id' => (string) ($row['shop_i_id'] ?? ''),
'shop_sku_id' => (string) ($row['shop_sku_id'] ?? ''),
'properties_value' => (string) ($row['properties_value'] ?? ''),
'force_cost_pending' => ! empty($row['force_cost_pending']),
'bundle_resolution_status' => $row['bundle_resolution_status'] ?? null,
'bundle_component_rows' => (int) ($row['bundle_component_rows'] ?? 0),
'bundle_component_amount' => $row['bundle_component_amount'] ?? null,
'bundle_expected_amount' => $row['bundle_expected_amount'] ?? null,
'bundle_amount_difference' => $row['bundle_amount_difference'] ?? null,
'bundle_component_codes' => $row['bundle_component_codes'] ?? [],
'qty' => ($aggregated[$key]['qty'] ?? 0.0) + $row['qty'],
'amount' => ($aggregated[$key]['amount'] ?? 0.0) + $row['amount'],
];

View File

@ -23,11 +23,12 @@
| 加号组合父行 | 同一订单、`outer_oi_id`、`shop_sku_id` 下至少两条组件,组件金额合计与父行一致 | 剔除带 `+` 的组合父行,只保留组件 | 保留父行待核验 |
| 中文后缀别名 | 占位编码以白名单后缀结尾,当前白名单仅「非」;必须同数据源、平台、店铺、订单、子订单、`shop_sku_id`、`shop_i_id`、仓库 | 正式编码与占位编码各唯一,且数量和金额完全一致时,保留正式编码、剔除占位行 | 任一关系不唯一或数量、金额不一致,两个编码都保留 |
| 父子前缀占位 | 同一订单内只有一个严格扩展编码的子商品,且平台商品、规格、子订单和仓库一致 | 数量、金额一致时剔除较短父行,保留明细编码,例如 `CTG022516` 类父行 | 多子编码或任一字段不一致时保留父行 |
| 组合装主行 | 组件行的 `src_combine_sku_id` 指向同一订单的源组合装编码 | 剔除源组合装主行,只计拆分后的组件 | 找不到组件时保留主行并进入待核验 |
| 组合装主行 | 同一 `o_id` 下,组件 `src_combine_sku_id` 指向源组合装编码;没有显式标记时,组件须与主行 `outer_oi_id + shop_sku_id + shop_i_id` 一致 | 组件金额合计与组包总额误差≤0.01 元时剔除主行,只计组件 | 非零主行找不到组件或金额不一致时保留主行待核验,组件暂不计成本 |
| 结构化组合条码 | `ZH-`、`MKH-` 开头,并按「组件编码 + 数量」完整解析 | 按组件及倍数展开;一个订单有几个仓库、商品编码和数量就分几行 | 条码无法完整解析时保留原编码 |
| 种菜前缀 | 商品编码以「种菜」开头 | 整行排除 | 不进入替换或价格匹配 |
| 运营组合套装 | 商品编码以「运营组合套装」开头 | 不进入中文后缀或通用父子别名清洗,交给组合装组件规则 | 组件缺失时待核验 |
| MKH-运营组合套装 | 商品编码以 `MKH-运营组合套装` 开头 | 不进入中文后缀或通用父子别名清洗,交给组合装组件规则 | 组件缺失时待核验 |
| 零值组合占位 | 主行数量和金额均为 0,且没有可对平组件 | 不生成商品成本行 | 组件若存在但金额无法对平,忽略空主行,组件按原价格路径计价 |
| 人工可读配件 | `原木色广岛`、`原木色舒美特实木面1把`、`胡桃色舒美特实木面1把` | 保持原编码,按现有价格来源计价 | 无有效价格时待核验,禁止自动删中文 |
| 其他中文别名 | 不属于上述分类,且找不到唯一正式编码或组件关系 | 不改写编码 | 保留原行待核验 |
@ -40,6 +41,18 @@
占位编码和正式编码必须各自只有一条命中记录,正式编码还必须唯一存在。禁止按包含关系、相似度或随机候选自动替换。
### 2.1 组合装金额对账
组合装主行与组件必须限定在同一数据源、同一 `o_id`;兼容推断时还须满足 `outer_oi_id`、`shop_sku_id`、`shop_i_id` 一致。组包总额按以下可用口径依次核对:
1. 主行数量和金额大于 0 时,优先使用主行 `amount`;
2. 拆单主行金额为 0 时,使用 `base_price × 组件最大数量`;
3. 单组件组包可使用主行 `base_price`。
组件 `amount` 合计与任一可用组包总额的差额绝对值不超过 0.01 元时视为对平。非零主行对不平或找不到组件时,主行保留在成本表中待核验,关联组件暂不写入成本,避免主行和组件重复计价。
数量和金额均为 0 的主行只用于识别上游拆单结构,不会被当作新的成本异常;对平时剔除主行并保留组件,无法对平时忽略空主行,组件继续走原有价格匹配路径。
## 3. 价格匹配
商品单价按以下顺序匹配:
@ -70,6 +83,14 @@ placeholder_rule_codes
placeholder_rule_code_rows
variant_parent_excluded_rows
bundle_parent_excluded_rows
bundle_backfill.reconciled_groups
bundle_backfill.missing_component_groups
bundle_backfill.amount_mismatch_groups
bundle_backfill.zero_placeholder_ignored_groups
bundle_backfill.component_rows
bundle_backfill.explicit_component_rows
bundle_backfill.inferred_component_rows
bundle_backfill.held_component_rows
plus_parent_excluded_rows
pending_cost_rows
pending_cost_quantity
@ -82,6 +103,8 @@ pending_cost_quantity
- 同组出现多条占位行或多个正式候选时,不自动替换。
- 种菜前缀行不出现于成本结果,也不会被转成去掉前缀的正式编码。
- 运营组合套装和 `MKH-运营组合套装` 只走组件规则,不进入中文别名清洗。
- 组合主行与组件金额误差超过 0.01 元时,主行保留待核验,组件不同时计入正常成本。
- 数量和金额均为 0 的空组合占位不得生成新的待核验行。
- 人工可读配件编码保持原样。
- 找不到唯一正式编码、仓库或组件关系的行继续进入待核验清单。

View File

@ -115,7 +115,8 @@
(采购单价优先、其次钉钉代发单价),仍匹配不到时用「普通商品资料」里的商品成本价兜底;商品成本 = 商品数量 × 商品单价。
平台数字 SKU 会按平台 SKU ID + 商品 ID 回查历史已拆分订单;历史无结果时,再按店铺名称 + 店铺商品编码 + 店铺款式编码
回查订单售后费用镜像,仅唯一内部编码自动替换;多候选保持待核验。
同一订单下已有内部商品编码时,平台数字商品占位行不参与成本;组合装拆分后,组合装主行不参与成本,只取组件行。
同一订单下已有内部商品编码时,平台数字商品占位行不参与成本;组合装拆分后,主行与同一 o_id 下的组件先做金额对账,
组件金额合计与组包总额误差不超过 0.01 元时,主行不参与成本,只取组件行。
拆单只取最末级订单行(没有任何下级的叶子行),主单和中间汇总层不参与、避免重复计数;
同一单分多仓发货的按末级实际仓库分行;虚拟条码(X0000x)不计入;
ZH-、MKH- 开头的组合装按「组件条码 + 数量」拆分,无法解析的组合装保留原编码;
@ -126,6 +127,9 @@
「正式编码 + 非」等白名单占位后缀只在平台、店铺、子订单、平台 SKU、商品 ID、仓库、数量和金额全部一致,
且正式编码与占位编码各唯一时自动保留正式编码;关系不唯一继续待核验。
运营组合套装、MKH-运营组合套装和「运营自行组合替换」不参与中文别名清洗,分别交给组合装组件规则或人工占位核验;
明确指向主行的组件优先;没有标记时,仅接受 outer_oi_id、shop_sku_id、shop_i_id 一致的同订单组件。
组包总额优先取主行 amount;拆单主行金额为 0 时取 base_price × 组件最大数量。非零主行找不到组件或金额不一致时,
主行保留待核验,关联组件暂不计成本,避免重复计价;数量和金额均为 0 的空组合占位不生成新的待核验行。
「原木色广岛」「原木色舒美特实木面1把」「胡桃色舒美特实木面1把」保持原编码计价,禁止自动去掉中文。
套餐/服务、运费及指定配件、组合装占位编码 TCXJ、FUWU、AZF、DF-PJZY0001、
JIAXIANGJIANCAIJIAJUZIZHUANG964A、YUNFEI、BCJ 全局不取数(组合装里拆出的这些编码同样剔除)。

View File

@ -22,10 +22,10 @@ class StoreReceiptProductCostLineTest extends TestCase
$this->assertSame(20.0, $lines[0]['qty']);
}
public function test_bundle_parent_is_removed_but_component_remains(): void
public function test_bundle_parent_is_removed_when_component_amount_matches(): void
{
[$lines, $placeholders, $bundles] = $this->costLines([
$this->row('bundle-parent', '运营组合套装12994', '3832980288011632985', 2, 696),
$this->row('bundle-parent', '运营组合套装12994', '3832980288011632985', 2, 625.26),
$this->row(
'bundle-child',
'SJ038017N1410V02',
@ -42,6 +42,119 @@ class StoreReceiptProductCostLineTest extends TestCase
$this->assertSame(2.0, $lines[0]['qty']);
}
public function test_bundle_amount_difference_of_one_cent_is_reconciled(): void
{
[$lines, , $bundles] = $this->costLines([
$this->row('bundle-parent', '运营组合套装12994', '3832980288011632985', 1, 100),
$this->row(
'bundle-child',
'SJ038017N1410V02',
'3832980288011632985',
1,
100.01,
'运营组合套装12994',
),
]);
$this->assertSame(1, $bundles);
$this->assertSame('SJ038017N1410V02', $lines[0]['sku']);
}
public function test_bundle_parent_remains_and_components_are_held_when_amount_does_not_match(): void
{
[$lines, , $bundles, , , $stats] = $this->costLines([
$this->row('bundle-parent', '运营组合套装12994', '3832980288011632985', 2, 696),
$this->row(
'bundle-child',
'SJ038017N1410V02',
'3832980288011632985',
2,
625.26,
'运营组合套装12994',
),
]);
$this->assertSame(0, $bundles);
$this->assertSame(['运营组合套装12994'], array_column($lines, 'sku'));
$this->assertTrue($lines[0]['force_cost_pending']);
$this->assertSame('amount_mismatch', $lines[0]['bundle_resolution_status']);
$this->assertSame(1, $stats['bundle_stats']['amount_mismatch_groups']);
$this->assertSame(1, $stats['bundle_stats']['held_component_rows']);
}
public function test_bundle_parent_without_components_remains_pending(): void
{
[$lines, , , , , $stats] = $this->costLines([
$this->row('bundle-parent', 'MKH-运营组合套装260706009', '3832980288011632985', 1, 2021),
]);
$this->assertSame(['MKH-运营组合套装260706009'], array_column($lines, 'sku'));
$this->assertTrue($lines[0]['force_cost_pending']);
$this->assertSame('missing_components', $lines[0]['bundle_resolution_status']);
$this->assertSame(1, $stats['bundle_stats']['missing_component_groups']);
}
public function test_zero_bundle_placeholder_without_components_is_dropped(): void
{
[$lines, , , , , $stats] = $this->costLines([
$this->row(
'bundle-placeholder',
'ZH-SJ038009N1410V01-1-SJ038057N1410V01-1',
'3832980288011632985',
0,
0,
'',
['sku_type' => 'combine', 'base_price' => 398],
),
]);
$this->assertSame([], $lines);
$this->assertSame(0, $stats['bundle_stats']['missing_component_groups']);
}
public function test_zero_bundle_placeholder_with_mismatched_components_keeps_components_priced(): void
{
[$lines, , , , , $stats] = $this->costLines([
$this->row(
'bundle-placeholder',
'运营组合套装13011',
'3832980288011632985',
0,
0,
'',
['sku_type' => 'combine', 'base_price' => 899],
),
$this->row('bundle-child', 'SJ038016N1410V01', '3832980288011632985', 1, 420),
]);
$this->assertSame(['SJ038016N1410V01'], array_column($lines, 'sku'));
$this->assertSame(1, $stats['bundle_stats']['zero_placeholder_ignored_groups']);
$this->assertSame(0, $stats['bundle_stats']['amount_mismatch_groups']);
$this->assertSame(0, $stats['bundle_stats']['held_component_rows']);
}
public function test_inferred_bundle_components_reconcile_against_parent_base_amount(): void
{
[$lines, , $bundles, , , $stats] = $this->costLines([
$this->row(
'bundle-parent',
'运营自行组合替换',
'3832980288011632985',
0,
0,
'',
['sku_type' => 'normal', 'base_price' => 559.88],
),
$this->row('bundle-child-a', '34093J', '3832980288011632985', 5, 1314.87),
$this->row('bundle-child-b', 'CZ002625N68V01', '3832980288011632985', 5, 1484.53),
]);
$this->assertSame(1, $bundles);
$this->assertSame(['34093J', 'CZ002625N68V01'], array_column($lines, 'sku'));
$this->assertSame(1, $stats['bundle_stats']['reconciled_groups']);
$this->assertSame(2, $stats['bundle_stats']['inferred_component_rows']);
}
public function test_plus_parent_is_removed_when_component_amounts_match(): void
{
[$lines, $placeholders, $bundles, $plusParents] = $this->costLines([
@ -379,6 +492,9 @@ class StoreReceiptProductCostLineTest extends TestCase
'platform' => '京喜账单',
'store_name' => '京喜-八方进宝工厂店',
'sku' => $sku,
'sku_type' => str_contains($sku, '组合') ? 'combine' : 'normal',
'base_price' => $amount,
'item_name' => $sku,
'qty' => $quantity,
'amount' => $amount,
'warehouse' => '简尚-新苏北仓',