商品成本:支持稳定历史多组件映射 #539
@ -301,6 +301,12 @@ class SyncStoreReceiptProductCost extends Command
|
||||
$this->info('订单侧命中核心单号:' . count($lines));
|
||||
|
||||
$platformSkuMappings = $this->platformSkuMapper($mirror, $lines, $billByCore);
|
||||
$historyBundleMappings = $this->historyBundleComponentProfiles(
|
||||
$mirror,
|
||||
$lines,
|
||||
$billByCore,
|
||||
$platformSkuMappings['afs'],
|
||||
);
|
||||
$shortNames = $this->warehouseShortNames();
|
||||
$prices = $this->weightedAverageUnitPrices($mirror, $reportMonth);
|
||||
// 月加权平均单价匹配不到时,用「线上代发价格」(采购单价 / 钉钉代发单价)兜底。
|
||||
@ -363,7 +369,11 @@ class SyncStoreReceiptProductCost extends Command
|
||||
$displayOrderNo = $core;
|
||||
}
|
||||
$placeholderStats = [];
|
||||
$costLines = $this->costLines($lines[$core] ?? [], $placeholderStats);
|
||||
$costLines = $this->costLines(
|
||||
$lines[$core] ?? [],
|
||||
$placeholderStats,
|
||||
$historyBundleMappings['profiles'],
|
||||
);
|
||||
$placeholderExcludedRows += $placeholderStats['platform_placeholder_excluded_rows'];
|
||||
$bundleParentExcludedRows += $placeholderStats['bundle_parent_excluded_rows'];
|
||||
$plusParentExcludedRows += $placeholderStats['plus_parent_excluded_rows'];
|
||||
@ -434,7 +444,11 @@ class SyncStoreReceiptProductCost extends Command
|
||||
|
||||
$remarks = [];
|
||||
if ($forceBundlePending) {
|
||||
$remarks[] = ($line['bundle_resolution_status'] ?? '') === 'amount_mismatch'
|
||||
$remarks[] = in_array(
|
||||
($line['bundle_resolution_status'] ?? ''),
|
||||
['amount_mismatch', 'history_amount_mismatch'],
|
||||
true,
|
||||
)
|
||||
? '组合装组件金额不一致'
|
||||
: '组合装未找到可用组件';
|
||||
}
|
||||
@ -466,7 +480,11 @@ class SyncStoreReceiptProductCost extends Command
|
||||
'bundle_component_codes' => $line['bundle_component_codes'] ?? [],
|
||||
'product_quantity' => $quantity,
|
||||
'reason' => $forceBundlePending
|
||||
? (($line['bundle_resolution_status'] ?? '') === 'amount_mismatch'
|
||||
? (in_array(
|
||||
($line['bundle_resolution_status'] ?? ''),
|
||||
['amount_mismatch', 'history_amount_mismatch'],
|
||||
true,
|
||||
)
|
||||
? '组合装组件金额与主行金额不一致,组件行暂不计成本'
|
||||
: '组合装未找到可计价组件')
|
||||
: ($short === ''
|
||||
@ -477,7 +495,11 @@ class SyncStoreReceiptProductCost extends Command
|
||||
? '平台 shop_sku_id 未找到历史内部商品编码'
|
||||
: '仓库简称 + 商品编码在月加权、线上代发、普通商品资料中均无有效单价'))),
|
||||
'code_type' => $forceBundlePending
|
||||
? (($line['bundle_resolution_status'] ?? '') === 'amount_mismatch'
|
||||
? (in_array(
|
||||
($line['bundle_resolution_status'] ?? ''),
|
||||
['amount_mismatch', 'history_amount_mismatch'],
|
||||
true,
|
||||
)
|
||||
? '组合装组件金额不一致'
|
||||
: '组合装未找到可用组件')
|
||||
: $this->pendingCodeType((string) $line['sku']),
|
||||
@ -561,6 +583,15 @@ class SyncStoreReceiptProductCost extends Command
|
||||
$bundleRollup['held_component_rows'],
|
||||
$bundleRollup['zero_placeholder_ignored_groups'],
|
||||
));
|
||||
$this->info(sprintf(
|
||||
' 历史多组件映射:稳定画像 %d / 候选 %d;自动拆分 %d 组,剔除父行 %d 行,生成组件 %d 行;历史金额不一致 %d 组',
|
||||
$historyBundleMappings['summary']['profile_keys'],
|
||||
$historyBundleMappings['summary']['candidate_keys'],
|
||||
$bundleRollup['history_auto_split_groups'],
|
||||
$bundleRollup['history_auto_split_parent_rows'],
|
||||
$bundleRollup['history_auto_split_component_rows'],
|
||||
$bundleRollup['history_profile_amount_mismatch_groups'],
|
||||
));
|
||||
|
||||
$result = [
|
||||
'status' => 'success',
|
||||
@ -605,6 +636,17 @@ class SyncStoreReceiptProductCost extends Command
|
||||
'component_codes' => array_keys($bundleRollup['component_codes']),
|
||||
'unreconciled_parent_codes' => array_keys($bundleRollup['unreconciled_parent_codes']),
|
||||
],
|
||||
'history_component_mapping' => [
|
||||
'candidate_keys' => $historyBundleMappings['summary']['candidate_keys'],
|
||||
'stable_profiles' => $historyBundleMappings['summary']['profile_keys'],
|
||||
'historical_groups' => $historyBundleMappings['summary']['historical_groups'],
|
||||
'afs_keys' => $historyBundleMappings['summary']['afs_keys'],
|
||||
'auto_split_groups' => $bundleRollup['history_auto_split_groups'],
|
||||
'auto_split_parent_rows' => $bundleRollup['history_auto_split_parent_rows'],
|
||||
'auto_split_component_rows' => $bundleRollup['history_auto_split_component_rows'],
|
||||
'history_amount_mismatch_groups' => $bundleRollup['history_profile_amount_mismatch_groups'],
|
||||
'component_codes' => array_keys($bundleRollup['history_auto_split_component_codes']),
|
||||
],
|
||||
'auto_replaced_platform_sku_rows' => $autoReplacedRows,
|
||||
'afs_fallback_replaced_platform_sku_rows' => $afsReplacedRows,
|
||||
'platform_sku_mapping_ambiguous_rows' => $mappingAmbiguousRows,
|
||||
@ -674,19 +716,19 @@ class SyncStoreReceiptProductCost extends Command
|
||||
$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 === ''
|
||||
) {
|
||||
if ($shopSkuId === '' || $shopItemId === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$historyCandidates[$shopSkuId . "\0" . $shopItemId] = [
|
||||
'shop_sku_id' => $shopSkuId,
|
||||
'shop_i_id' => $shopItemId,
|
||||
];
|
||||
if ($shopName !== '') {
|
||||
$isPlatformSku = preg_match('/^\d+$/', $sku) === 1;
|
||||
$isBundleParent = self::isBundleParentRow($line);
|
||||
if ($isPlatformSku) {
|
||||
$historyCandidates[$shopSkuId . "\0" . $shopItemId] = [
|
||||
'shop_sku_id' => $shopSkuId,
|
||||
'shop_i_id' => $shopItemId,
|
||||
];
|
||||
}
|
||||
if ($shopName !== '' && ($isPlatformSku || $isBundleParent)) {
|
||||
$afsKey = self::afsPlatformSkuKey($shopName, $shopSkuId, $shopItemId);
|
||||
$afsCandidates[$afsKey] = [
|
||||
'shop_name' => $shopName,
|
||||
@ -774,6 +816,280 @@ class SyncStoreReceiptProductCost extends Command
|
||||
];
|
||||
}
|
||||
|
||||
private static function historyBundleProfileKey(
|
||||
string $source,
|
||||
string $storeName,
|
||||
string $shopSkuId,
|
||||
string $shopItemId,
|
||||
string $parentSku,
|
||||
): string {
|
||||
return trim($source)
|
||||
. "\0" . trim($storeName)
|
||||
. "\0" . trim($shopSkuId)
|
||||
. "\0" . trim($shopItemId)
|
||||
. "\0" . mb_strtoupper(trim($parentSku));
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $row */
|
||||
private static function historyBundleProfileKeyForRow(array $row, string $parentSku): ?string
|
||||
{
|
||||
$source = trim((string) ($row['source'] ?? ''));
|
||||
$storeName = trim((string) ($row['store_name'] ?? ''));
|
||||
$shopSkuId = trim((string) ($row['shop_sku_id'] ?? ''));
|
||||
$shopItemId = trim((string) ($row['shop_i_id'] ?? ''));
|
||||
if (in_array('', [$source, $storeName, $shopSkuId, $shopItemId], true)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return self::historyBundleProfileKey(
|
||||
$source,
|
||||
$storeName,
|
||||
$shopSkuId,
|
||||
$shopItemId,
|
||||
$parentSku,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 对上游未拆分的「组合」父行,从历史订单与售后镜像构造稳定组件画像。
|
||||
* 历史订单必须能按父行数量还原唯一组件集合和数量,售后镜像集合必须完全一致。
|
||||
*
|
||||
* @param array<string,list<array<string,mixed>>> $lines
|
||||
* @param array<string,object> $billByCore
|
||||
* @return array{profiles:array<string,array<string,mixed>>,summary:array<string,int>}
|
||||
*/
|
||||
private function historyBundleComponentProfiles(
|
||||
$mirror,
|
||||
array $lines,
|
||||
array $billByCore,
|
||||
array $afsMappings,
|
||||
): array
|
||||
{
|
||||
$candidates = [];
|
||||
foreach ($lines as $core => $orderLines) {
|
||||
$storeName = trim((string) ($billByCore[$core]->store_name ?? ''));
|
||||
if ($storeName === '') {
|
||||
continue;
|
||||
}
|
||||
$localComponentParents = [];
|
||||
foreach ($orderLines as $row) {
|
||||
$sourceParent = mb_strtoupper(trim((string) ($row['src_combine_sku_id'] ?? '')));
|
||||
if ($sourceParent !== '') {
|
||||
$localComponentParents[$sourceParent] = true;
|
||||
}
|
||||
}
|
||||
foreach ($orderLines as $row) {
|
||||
if (! self::isBundleParentRow($row)) {
|
||||
continue;
|
||||
}
|
||||
$parentSku = mb_strtoupper(trim((string) ($row['sku'] ?? '')));
|
||||
if (isset($localComponentParents[$parentSku])) {
|
||||
continue;
|
||||
}
|
||||
$key = self::historyBundleProfileKeyForRow($row, $parentSku);
|
||||
if ($key === null) {
|
||||
continue;
|
||||
}
|
||||
$candidates[$key] = [
|
||||
'key' => $key,
|
||||
'source' => trim((string) $row['source']),
|
||||
'store_name' => $storeName,
|
||||
'shop_sku_id' => trim((string) $row['shop_sku_id']),
|
||||
'shop_i_id' => trim((string) $row['shop_i_id']),
|
||||
'parent_sku' => $parentSku,
|
||||
];
|
||||
}
|
||||
}
|
||||
if ($candidates === []) {
|
||||
return [
|
||||
'profiles' => [],
|
||||
'summary' => [
|
||||
'candidate_keys' => 0,
|
||||
'profile_keys' => 0,
|
||||
'historical_groups' => 0,
|
||||
'afs_keys' => 0,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
$parentCodesBySource = [];
|
||||
foreach ($candidates as $candidate) {
|
||||
$parentCodesBySource[$candidate['source']][$candidate['parent_sku']] = true;
|
||||
}
|
||||
|
||||
$historyRows = [];
|
||||
foreach (self::SOURCES as $source) {
|
||||
$sourceKey = (string) $source['key'];
|
||||
$parentCodes = array_keys($parentCodesBySource[$sourceKey] ?? []);
|
||||
if ($parentCodes === []) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
$itemRows = [];
|
||||
foreach ([
|
||||
$mirror->table($source['items'])->whereIn('sku_id', $parentCodes)
|
||||
->get(['Id', 'o_id', 'sku_id', 'qty', 'amount', 'outer_oi_id', 'shop_sku_id', 'shop_i_id', 'src_combine_sku_id']),
|
||||
$mirror->table($source['items'])->whereIn('src_combine_sku_id', $parentCodes)
|
||||
->get(['Id', 'o_id', 'sku_id', 'qty', 'amount', 'outer_oi_id', 'shop_sku_id', 'shop_i_id', 'src_combine_sku_id']),
|
||||
] as $rows) {
|
||||
foreach ($rows as $row) {
|
||||
$itemRows[(string) $row->Id] = $row;
|
||||
}
|
||||
}
|
||||
$orderIds = array_values(array_unique(array_map(
|
||||
static fn ($row): string => (string) $row->o_id,
|
||||
$itemRows,
|
||||
)));
|
||||
$orders = $orderIds === [] ? [] : $mirror->table($source['orders'])
|
||||
->whereIn('o_id', $orderIds)
|
||||
->get(['o_id', 'shop_name', 'link_o_id'])
|
||||
->keyBy('o_id')
|
||||
->all();
|
||||
foreach ($itemRows as $row) {
|
||||
$order = $orders[(string) $row->o_id] ?? null;
|
||||
$historyRows[] = [
|
||||
'source' => $sourceKey,
|
||||
'store_name' => trim((string) ($order->shop_name ?? '')),
|
||||
'o_id' => (string) ($row->o_id ?? ''),
|
||||
'sku' => mb_strtoupper(trim((string) ($row->sku_id ?? ''))),
|
||||
'qty' => (float) ($row->qty ?? 0),
|
||||
'amount' => (float) ($row->amount ?? 0),
|
||||
'outer_oi_id' => trim((string) ($row->outer_oi_id ?? '')),
|
||||
'parent_o_id' => trim((string) ($order->link_o_id ?? '')),
|
||||
'shop_sku_id' => trim((string) ($row->shop_sku_id ?? '')),
|
||||
'shop_i_id' => trim((string) ($row->shop_i_id ?? '')),
|
||||
'src_combine_sku_id' => mb_strtoupper(trim((string) ($row->src_combine_sku_id ?? ''))),
|
||||
];
|
||||
}
|
||||
} catch (Throwable $exception) {
|
||||
$this->warn('历史组合组件读取失败(' . $source['items'] . '):' . $exception->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
$rowsByCandidate = [];
|
||||
$candidateByBase = [];
|
||||
foreach ($candidates as $key => $candidate) {
|
||||
$base = $candidate['source']
|
||||
. "\0" . $candidate['store_name']
|
||||
. "\0" . $candidate['shop_sku_id']
|
||||
. "\0" . $candidate['shop_i_id'];
|
||||
$candidateByBase[$base][$candidate['parent_sku']] = $key;
|
||||
}
|
||||
foreach ($historyRows as $row) {
|
||||
$base = $row['source']
|
||||
. "\0" . $row['store_name']
|
||||
. "\0" . $row['shop_sku_id']
|
||||
. "\0" . $row['shop_i_id'];
|
||||
foreach (array_unique([$row['sku'], $row['src_combine_sku_id']]) as $parentSku) {
|
||||
if ($parentSku === '' || ! isset($candidateByBase[$base][$parentSku])) {
|
||||
continue;
|
||||
}
|
||||
$rowsByCandidate[$candidateByBase[$base][$parentSku]][] = $row;
|
||||
}
|
||||
}
|
||||
|
||||
$afsProfiles = $afsMappings;
|
||||
|
||||
$profiles = [];
|
||||
$historicalGroupCount = 0;
|
||||
foreach ($candidates as $key => $candidate) {
|
||||
$candidateRows = $rowsByCandidate[$key] ?? [];
|
||||
$parentIds = [];
|
||||
foreach ($candidateRows as $row) {
|
||||
if ($row['parent_o_id'] !== '' && $row['parent_o_id'] !== '0') {
|
||||
$parentIds[$row['parent_o_id']] = true;
|
||||
}
|
||||
}
|
||||
$groups = [];
|
||||
foreach ($candidateRows as $row) {
|
||||
if (isset($parentIds[$row['o_id']]) && $row['sku'] !== $candidate['parent_sku']) {
|
||||
continue;
|
||||
}
|
||||
if ($row['outer_oi_id'] !== '') {
|
||||
$groups[$row['outer_oi_id']][] = $row;
|
||||
}
|
||||
}
|
||||
|
||||
$stableProfile = null;
|
||||
foreach ($groups as $groupRows) {
|
||||
$parentQuantity = 0.0;
|
||||
$components = [];
|
||||
foreach ($groupRows as $row) {
|
||||
if ($row['sku'] === $candidate['parent_sku']) {
|
||||
$parentQuantity += max($row['qty'], 0.0);
|
||||
continue;
|
||||
}
|
||||
if ($row['src_combine_sku_id'] !== $candidate['parent_sku'] || $row['qty'] <= 0) {
|
||||
continue;
|
||||
}
|
||||
$components[$row['sku']]['qty'] = ($components[$row['sku']]['qty'] ?? 0.0) + $row['qty'];
|
||||
$components[$row['sku']]['amount'] = ($components[$row['sku']]['amount'] ?? 0.0) + $row['amount'];
|
||||
}
|
||||
if ($parentQuantity <= 0 || count($components) < 2) {
|
||||
continue;
|
||||
}
|
||||
ksort($components, SORT_STRING);
|
||||
$normalized = [];
|
||||
foreach ($components as $code => $component) {
|
||||
$normalized[$code] = [
|
||||
'qty' => round($component['qty'] / $parentQuantity, 4),
|
||||
'amount' => round($component['amount'] / $parentQuantity, 2),
|
||||
];
|
||||
}
|
||||
$historicalGroupCount++;
|
||||
if ($stableProfile === null) {
|
||||
$stableProfile = $normalized;
|
||||
continue;
|
||||
}
|
||||
if (array_keys($stableProfile) !== array_keys($normalized)) {
|
||||
$stableProfile = false;
|
||||
break;
|
||||
}
|
||||
foreach ($normalized as $code => $component) {
|
||||
if (
|
||||
abs($stableProfile[$code]['qty'] - $component['qty']) > 0.0001
|
||||
|| abs($stableProfile[$code]['amount'] - $component['amount']) > 0.01
|
||||
) {
|
||||
$stableProfile = false;
|
||||
break 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (! is_array($stableProfile) || $stableProfile === []) {
|
||||
continue;
|
||||
}
|
||||
$afsKey = self::afsPlatformSkuKey(
|
||||
$candidate['store_name'],
|
||||
$candidate['shop_sku_id'],
|
||||
$candidate['shop_i_id'],
|
||||
);
|
||||
$mappedAfsCodes = $afsProfiles[$afsKey] ?? [];
|
||||
$afsCodes = array_is_list($mappedAfsCodes)
|
||||
? array_values($mappedAfsCodes)
|
||||
: array_keys($mappedAfsCodes);
|
||||
sort($afsCodes, SORT_STRING);
|
||||
$historyCodes = array_keys($stableProfile);
|
||||
sort($historyCodes, SORT_STRING);
|
||||
if ($afsCodes === [] || $afsCodes !== $historyCodes) {
|
||||
continue;
|
||||
}
|
||||
$profiles[$key] = [
|
||||
'components' => $stableProfile,
|
||||
'component_codes' => $historyCodes,
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'profiles' => $profiles,
|
||||
'summary' => [
|
||||
'candidate_keys' => count($candidates),
|
||||
'profile_keys' => count($profiles),
|
||||
'historical_groups' => $historicalGroupCount,
|
||||
'afs_keys' => count($afsProfiles),
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array<string,mixed>> $lines
|
||||
* @return array{
|
||||
@ -1056,6 +1372,7 @@ class SyncStoreReceiptProductCost extends Command
|
||||
'reconciled_groups' => 0,
|
||||
'missing_component_groups' => 0,
|
||||
'amount_mismatch_groups' => 0,
|
||||
'history_profile_amount_mismatch_groups' => 0,
|
||||
'zero_placeholder_ignored_groups' => 0,
|
||||
'component_rows' => 0,
|
||||
'explicit_component_rows' => 0,
|
||||
@ -1063,8 +1380,12 @@ class SyncStoreReceiptProductCost extends Command
|
||||
'held_component_rows' => 0,
|
||||
'reconciled_amount' => 0.0,
|
||||
'mismatch_amount' => 0.0,
|
||||
'history_auto_split_groups' => 0,
|
||||
'history_auto_split_parent_rows' => 0,
|
||||
'history_auto_split_component_rows' => 0,
|
||||
'component_codes' => [],
|
||||
'unreconciled_parent_codes' => [],
|
||||
'history_auto_split_component_codes' => [],
|
||||
],
|
||||
];
|
||||
}
|
||||
@ -1133,7 +1454,7 @@ class SyncStoreReceiptProductCost extends Command
|
||||
* @param array<string,array<string,mixed>> $unique
|
||||
* @param array<string,mixed> $stats
|
||||
*/
|
||||
private function resolveBundleParents(array &$unique, array &$stats): void
|
||||
private function resolveBundleParents(array &$unique, array &$stats, array $bundleProfiles = []): void
|
||||
{
|
||||
$parentGroups = [];
|
||||
foreach ($unique as $key => $row) {
|
||||
@ -1207,6 +1528,40 @@ class SyncStoreReceiptProductCost extends Command
|
||||
$basePrices[(string) round($basePrice, 4)] = $basePrice;
|
||||
}
|
||||
}
|
||||
$historyProfileUsed = false;
|
||||
$historyProfileKey = self::historyBundleProfileKeyForRow($firstParent, $parentSku);
|
||||
$historyProfile = $historyProfileKey === null
|
||||
? null
|
||||
: ($bundleProfiles[$historyProfileKey] ?? null);
|
||||
if ($children === [] && $parentQuantity > 0 && is_array($historyProfile)) {
|
||||
$children = [];
|
||||
foreach (($historyProfile['components'] ?? []) as $componentCode => $component) {
|
||||
$childKey = 'history-profile:'
|
||||
. md5($firstParent['row_key'] . "\0" . $parentSku . "\0" . $componentCode);
|
||||
$children[$childKey] = array_merge($firstParent, [
|
||||
'sku' => mb_strtoupper((string) $componentCode),
|
||||
'sku_type' => 'normal',
|
||||
'base_price' => 0.0,
|
||||
'item_name' => (string) $componentCode,
|
||||
'qty' => round((float) ($component['qty'] ?? 0) * $parentQuantity, 4),
|
||||
'amount' => round((float) ($component['amount'] ?? 0) * $parentQuantity, 2),
|
||||
'parent_o_id' => $parentOrderId,
|
||||
'row_key' => (string) $firstParent['row_key'] . ':history:' . $componentCode,
|
||||
'src_combine_sku_id' => $parentSku,
|
||||
'properties_value' => '',
|
||||
'bundle_component_source' => 'history_profile',
|
||||
]);
|
||||
}
|
||||
$historyProfileUsed = $children !== [];
|
||||
$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;
|
||||
}
|
||||
}
|
||||
$candidateTotals = [];
|
||||
if ($parentAmount > 0) {
|
||||
$candidateTotals[(string) round($parentAmount, 2)] = round($parentAmount, 2);
|
||||
@ -1256,10 +1611,23 @@ class SyncStoreReceiptProductCost extends Command
|
||||
$bundleStats['explicit_component_rows'] += count($explicitChildren);
|
||||
$bundleStats['inferred_component_rows'] += count($inferredChildren);
|
||||
$bundleStats['reconciled_amount'] += $componentAmount;
|
||||
if ($historyProfileUsed) {
|
||||
$bundleStats['history_auto_split_groups']++;
|
||||
$bundleStats['history_auto_split_parent_rows'] += count($parentKeys);
|
||||
$bundleStats['history_auto_split_component_rows'] += count($children);
|
||||
}
|
||||
foreach (array_keys($componentCodes) as $componentCode) {
|
||||
$bundleStats['component_codes'][$componentCode] = true;
|
||||
if ($historyProfileUsed) {
|
||||
$bundleStats['history_auto_split_component_codes'][$componentCode] = true;
|
||||
}
|
||||
}
|
||||
unset($bundleStats);
|
||||
if ($historyProfileUsed) {
|
||||
foreach ($children as $childKey => $child) {
|
||||
$unique[$childKey] = $child;
|
||||
}
|
||||
}
|
||||
foreach (array_keys($parentKeys) as $parentKey) {
|
||||
unset($unique[$parentKey]);
|
||||
}
|
||||
@ -1271,7 +1639,10 @@ class SyncStoreReceiptProductCost extends Command
|
||||
$bundleStats['explicit_component_rows'] += count($explicitChildren);
|
||||
$bundleStats['inferred_component_rows'] += count($inferredChildren);
|
||||
$bundleStats['unreconciled_parent_codes'][$parentSku] = true;
|
||||
if ($children === []) {
|
||||
if ($historyProfileUsed) {
|
||||
$bundleStats['history_profile_amount_mismatch_groups']++;
|
||||
$bundleStats['mismatch_amount'] += abs($difference);
|
||||
} elseif ($children === []) {
|
||||
$bundleStats['missing_component_groups']++;
|
||||
} else {
|
||||
$bundleStats['amount_mismatch_groups']++;
|
||||
@ -1288,9 +1659,9 @@ class SyncStoreReceiptProductCost extends Command
|
||||
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_resolution_status' => $historyProfileUsed
|
||||
? 'history_amount_mismatch'
|
||||
: ($children === [] ? 'missing_components' : 'amount_mismatch'),
|
||||
'bundle_component_rows' => count($children),
|
||||
'bundle_component_amount' => round($componentAmount, 2),
|
||||
'bundle_expected_amount' => round($expectedAmount, 2),
|
||||
@ -1322,7 +1693,7 @@ class SyncStoreReceiptProductCost extends Command
|
||||
* @param 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}> $rows
|
||||
* @return list<array{sku:string,qty:float,amount:float,warehouse:string,shop_i_id:string,shop_sku_id:string,properties_value:string}>
|
||||
*/
|
||||
private function costLines(array $rows, ?array &$stats = null): array
|
||||
private function costLines(array $rows, ?array &$stats = null, array $bundleProfiles = []): array
|
||||
{
|
||||
$stats = self::initialPlaceholderStats();
|
||||
if ($rows === []) {
|
||||
@ -1350,7 +1721,7 @@ class SyncStoreReceiptProductCost extends Command
|
||||
|
||||
// 3) 组合装主行先与拆分组件做金额对账;主行不计成本,
|
||||
// 只有组件金额能与主行金额对平时才剔除主行并保留组件。
|
||||
$this->resolveBundleParents($unique, $stats);
|
||||
$this->resolveBundleParents($unique, $stats, $bundleProfiles);
|
||||
|
||||
// 非中文「组合」编码继续沿用原有 src_combine_sku_id 父子去重逻辑,
|
||||
// 本次金额回溯不改变 ZH-/MKH- 等结构化组合的既有口径。
|
||||
|
||||
@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* 商品成本历史多组件画像按父编码查询订单明细。
|
||||
* 为普通订单与淘系订单的子商品表补上编码索引,避免每月扫描全表。
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
private const TABLES = [
|
||||
'ops_jst_order_item',
|
||||
'ops_jst_qmcust_order_items',
|
||||
];
|
||||
|
||||
public function up(): void
|
||||
{
|
||||
$schema = Schema::connection($this->connection());
|
||||
$connection = DB::connection($this->connection());
|
||||
foreach (self::TABLES as $tableName) {
|
||||
if (! $schema->hasTable($tableName)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$indexes = collect($schema->getIndexes($tableName))->keyBy('name');
|
||||
if (! $indexes->has('order_item_sku_combo_profile')) {
|
||||
$connection->statement(
|
||||
"CREATE INDEX `order_item_sku_combo_profile` ON `{$tableName}` (`sku_id`(128), `o_id`)",
|
||||
);
|
||||
}
|
||||
if (! $indexes->has('order_item_src_combo_profile')) {
|
||||
$connection->statement(
|
||||
"CREATE INDEX `order_item_src_combo_profile` ON `{$tableName}` (`src_combine_sku_id`(128), `o_id`)",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
$schema = Schema::connection($this->connection());
|
||||
$connection = DB::connection($this->connection());
|
||||
foreach (self::TABLES as $tableName) {
|
||||
if (! $schema->hasTable($tableName)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$indexes = collect($schema->getIndexes($tableName))->keyBy('name');
|
||||
if ($indexes->has('order_item_sku_combo_profile')) {
|
||||
$connection->statement(
|
||||
"DROP INDEX `order_item_sku_combo_profile` ON `{$tableName}`",
|
||||
);
|
||||
}
|
||||
if ($indexes->has('order_item_src_combo_profile')) {
|
||||
$connection->statement(
|
||||
"DROP INDEX `order_item_src_combo_profile` ON `{$tableName}`",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function connection(): string
|
||||
{
|
||||
return (string) config('upstream_mirrors.connection', 'business_mirror');
|
||||
}
|
||||
};
|
||||
@ -55,6 +55,20 @@
|
||||
|
||||
数量和金额均为 0 的主行只用于识别上游拆单结构,不会被当作新的成本异常;对平时剔除主行并保留组件,无法对平时忽略空主行,组件继续走原有价格匹配路径。
|
||||
|
||||
### 2.2 历史多组件映射
|
||||
|
||||
当前订单只有中文「组合」父行、没有本地组件行时,允许从同一平台 SKU 的历史订单补充组件画像。必须同时满足:
|
||||
|
||||
1. 历史订单按 `source + 店铺 + shop_sku_id + shop_i_id + 父编码` 分组;
|
||||
2. 先按订单 `link_o_id` 过滤父子重复层,只使用末级组件行;
|
||||
3. 每个历史组的组件集合、按父行数量归一化后的组件数量以及组件金额必须唯一稳定;
|
||||
4. 售后镜像对同一店铺和平台 SKU 返回的组件集合必须与历史集合完全一致;
|
||||
5. 当前父行数量大于 0,组件数量按父行数量放大后,组件金额合计与当前父行金额误差≤0.01 元。
|
||||
|
||||
全部满足时,删除父行并按画像生成多条组件成本行;当前金额不一致、售后集合不一致、历史数量或金额不稳定时,不自动拆分,父行继续待核验。
|
||||
|
||||
历史父编码查询使用订单明细的 `sku_id`、`src_combine_sku_id` 索引;平台 SKU 售后镜像查询与数字 SKU 映射合并执行。
|
||||
|
||||
## 3. 价格匹配
|
||||
|
||||
商品单价按以下顺序匹配:
|
||||
@ -93,6 +107,12 @@ bundle_backfill.component_rows
|
||||
bundle_backfill.explicit_component_rows
|
||||
bundle_backfill.inferred_component_rows
|
||||
bundle_backfill.held_component_rows
|
||||
history_component_mapping.candidate_keys
|
||||
history_component_mapping.stable_profiles
|
||||
history_component_mapping.auto_split_groups
|
||||
history_component_mapping.auto_split_parent_rows
|
||||
history_component_mapping.auto_split_component_rows
|
||||
history_component_mapping.history_amount_mismatch_groups
|
||||
plus_parent_excluded_rows
|
||||
pending_cost_rows
|
||||
pending_cost_quantity
|
||||
|
||||
@ -130,6 +130,8 @@
|
||||
明确指向主行的组件优先;没有标记时,仅接受 outer_oi_id、shop_sku_id、shop_i_id 一致的同订单组件。
|
||||
组包总额优先取主行 amount;拆单主行金额为 0 时取 base_price × 组件最大数量。非零主行找不到组件或金额不一致时,
|
||||
主行保留待核验,关联组件暂不计成本,避免重复计价;数量和金额均为 0 的空组合占位不生成新的待核验行。
|
||||
当前订单没有组件行时,可按同一店铺平台 SKU 的历史订单和售后镜像生成稳定组件画像;仅当组件集合一致、
|
||||
数量可按父行数量还原、组件金额合计与当前父行误差不超过 0.01 元时自动拆分,否则继续待核验。
|
||||
ZH-、MKH- 等结构化组合编码不在本次中文「组合」金额回溯范围内,继续沿用原有逻辑。
|
||||
「原木色广岛」「原木色舒美特实木面1把」「胡桃色舒美特实木面1把」保持原编码计价,禁止自动去掉中文。
|
||||
套餐/服务、运费及指定配件、组合装占位编码 TCXJ、FUWU、AZF、DF-PJZY0001、
|
||||
|
||||
@ -175,6 +175,88 @@ class StoreReceiptProductCostLineTest extends TestCase
|
||||
$this->assertSame(2, $stats['bundle_stats']['inferred_component_rows']);
|
||||
}
|
||||
|
||||
public function test_stable_history_components_are_expanded_when_parent_amount_matches(): void
|
||||
{
|
||||
$profileKey = "jst\0京东-HX旗舰店104\0"
|
||||
. "10227805997572\0"
|
||||
. "10035321954709\0"
|
||||
. 'MKH-运营组合套装260706009';
|
||||
[$lines, , $bundles, , , $stats] = $this->costLines([
|
||||
$this->row(
|
||||
'bundle-parent',
|
||||
'MKH-运营组合套装260706009',
|
||||
'10035321954709',
|
||||
1,
|
||||
2021,
|
||||
'',
|
||||
[
|
||||
'store_name' => '京东-HX旗舰店104',
|
||||
'shop_sku_id' => '10227805997572',
|
||||
'sku_type' => 'combine',
|
||||
],
|
||||
),
|
||||
], [
|
||||
$profileKey => [
|
||||
'components' => [
|
||||
'DNZ038572N1437V01' => ['qty' => 1, 'amount' => 357.84],
|
||||
'GBGJ-SJZ002103N1261V01' => ['qty' => 1, 'amount' => 935.82],
|
||||
'GBGJ-ZWJ024903AN1407V01' => ['qty' => 1, 'amount' => 363.67],
|
||||
'GBGJ-ZWJ024903BN1407V01' => ['qty' => 1, 'amount' => 363.67],
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
$this->assertSame(1, $bundles);
|
||||
$this->assertSame(
|
||||
[
|
||||
'DNZ038572N1437V01',
|
||||
'GBGJ-SJZ002103N1261V01',
|
||||
'GBGJ-ZWJ024903AN1407V01',
|
||||
'GBGJ-ZWJ024903BN1407V01',
|
||||
],
|
||||
array_column($lines, 'sku'),
|
||||
);
|
||||
$this->assertSame(1, $stats['bundle_stats']['history_auto_split_groups']);
|
||||
$this->assertSame(4, $stats['bundle_stats']['history_auto_split_component_rows']);
|
||||
}
|
||||
|
||||
public function test_history_components_remain_pending_when_parent_amount_differs(): void
|
||||
{
|
||||
$profileKey = "jst\0京东-HX旗舰店104\0"
|
||||
. "10227805997572\0"
|
||||
. "10035321954709\0"
|
||||
. 'MKH-运营组合套装260706009';
|
||||
[$lines, , $bundles, , , $stats] = $this->costLines([
|
||||
$this->row(
|
||||
'bundle-parent',
|
||||
'MKH-运营组合套装260706009',
|
||||
'10035321954709',
|
||||
1,
|
||||
2000,
|
||||
'',
|
||||
[
|
||||
'store_name' => '京东-HX旗舰店104',
|
||||
'shop_sku_id' => '10227805997572',
|
||||
'sku_type' => 'combine',
|
||||
],
|
||||
),
|
||||
], [
|
||||
$profileKey => [
|
||||
'components' => [
|
||||
'DNZ038572N1437V01' => ['qty' => 1, 'amount' => 357.84],
|
||||
'GBGJ-SJZ002103N1261V01' => ['qty' => 1, 'amount' => 935.82],
|
||||
'GBGJ-ZWJ024903AN1407V01' => ['qty' => 1, 'amount' => 363.67],
|
||||
'GBGJ-ZWJ024903BN1407V01' => ['qty' => 1, 'amount' => 363.67],
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
$this->assertSame(0, $bundles);
|
||||
$this->assertSame(['MKH-运营组合套装260706009'], array_column($lines, 'sku'));
|
||||
$this->assertSame('history_amount_mismatch', $lines[0]['bundle_resolution_status']);
|
||||
$this->assertSame(1, $stats['bundle_stats']['history_profile_amount_mismatch_groups']);
|
||||
}
|
||||
|
||||
public function test_plus_parent_is_removed_when_component_amounts_match(): void
|
||||
{
|
||||
[$lines, $placeholders, $bundles, $plusParents] = $this->costLines([
|
||||
@ -479,13 +561,13 @@ class StoreReceiptProductCostLineTest extends TestCase
|
||||
}
|
||||
|
||||
/** @return array{0:list<array<string,mixed>>,1:int,2:int,3:int,4:int,5:array<string,mixed>} */
|
||||
private function costLines(array $rows): array
|
||||
private function costLines(array $rows, array $bundleProfiles = []): array
|
||||
{
|
||||
$command = new SyncStoreReceiptProductCost();
|
||||
$method = new ReflectionMethod($command, 'costLines');
|
||||
$method->setAccessible(true);
|
||||
$stats = [];
|
||||
$lines = $method->invokeArgs($command, [$rows, &$stats]);
|
||||
$lines = $method->invokeArgs($command, [$rows, &$stats, $bundleProfiles]);
|
||||
|
||||
return [
|
||||
$lines,
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user