fix: 完善商品成本全字段导出 #897

Merged
chenxi merged 5 commits from feature/codex-product-cost-full-export into main 2026-11-05 18:14:57 +08:00
11 changed files with 432 additions and 136 deletions

View File

@ -29,6 +29,7 @@ class SyncStoreReceiptProductCost extends Command
{--chunk=1000 : 临时表批量写入行数}
{--remap-warehouses-only : 只按最新仓库映射表刷新仓库简称,不重算其他字段}
{--refresh-realtime-prices-only : 只刷新商品实时价与商品实时成本,不重算其他字段}
{--realtime-only : 重建本月商品明细,仅写商品实时价与商品实时成本,商品单价和商品成本留空}
{--result-json= : 将结果统计和待核验清单写入指定 JSON 文件}';
protected $description = '展开业绩明细对应的订单商品行,计算商品成本(发货仓库 → 仓库简称 → 商品单价 → 商品成本)';
@ -73,6 +74,14 @@ class SyncStoreReceiptProductCost extends Command
'JIAXIANGJIANCAIJIAJUZIZHUANG964A',
'YUNFEI',
'BCJ',
'信息说明',
'GG003-SZ',
'10237635142166',
'10237635142167',
'10228923011349',
'10230781002185',
'10230781002760',
'10230780802455',
];
/** 组合装条码前缀;条码结构为「前缀-组件条码-数量-组件条码-数量」。 */
@ -164,6 +173,15 @@ class SyncStoreReceiptProductCost extends Command
$platformInput = trim((string) $this->option('platform'));
$platform = self::PLATFORM_LABELS[$platformInput] ?? $platformInput;
$chunkSize = max((int) $this->option('chunk'), 100);
$realtimeOnly = (bool) $this->option('realtime-only');
$exclusiveModes = array_filter([
'remap-warehouses-only' => (bool) $this->option('remap-warehouses-only'),
'refresh-realtime-prices-only' => (bool) $this->option('refresh-realtime-prices-only'),
'realtime-only' => $realtimeOnly,
]);
if (count($exclusiveModes) > 1) {
throw new InvalidArgumentException('仓库简称刷新、实时价刷新和仅实时价重建只能选择一个。');
}
$connection = (string) config('upstream_mirrors.connection', 'business_mirror');
$mirror = DB::connection($connection);
@ -343,7 +361,8 @@ class SyncStoreReceiptProductCost extends Command
$warehouseFallback['order_node_rows'],
$warehouseFallback['ambiguous_rows'],
));
$prices = $this->weightedAverageUnitPrices($mirror, $reportMonth);
// 仅实时价模式不使用月加权平均价,正式商品单价、价格来源和商品成本保持为空。
$prices = $realtimeOnly ? [] : $this->weightedAverageUnitPrices($mirror, $reportMonth);
// 月加权平均单价匹配不到时,用「线上代发价格」(采购单价 / 钉钉代发单价)兜底。
$fallbackPrices = $this->onlineDaifaUnitPrices($mirror);
// 代发价格也没有时,再用普通商品资料里的商品成本价兜底。
@ -393,6 +412,8 @@ class SyncStoreReceiptProductCost extends Command
$imported = 0;
$quantityTotal = 0.0;
$costTotal = 0.0;
$realtimeQuantityTotal = 0.0;
$realtimeCostTotal = 0.0;
$missingPriceRows = 0;
$missingWarehouseRows = 0;
$fallbackPriceRows = 0;
@ -507,26 +528,30 @@ class SyncStoreReceiptProductCost extends Command
foreach ($costLines as $line) {
$short = self::warehouseShortNameFor((string) $line['warehouse'], $shortNames);
$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 (! $forceBundlePending && $price === null) {
$fallback = $fallbackPrices[$line['sku']] ?? null;
if ($fallback !== null) {
$price = $fallback['price'];
$priceSource = $fallback['source'];
$fallbackPriceRows++;
$price = null;
$priceSource = null;
if (! $realtimeOnly) {
$price = ! $forceBundlePending && $short !== ''
? ($prices[$short . "\0" . $line['sku']] ?? null)
: null;
$priceSource = $price === null ? null : self::PRICE_SOURCE_WEIGHTED;
// 月加权平均单价按「仓库简称 + 商品编码」匹配不到时,退回线上代发价格(按商品编码)。
if (! $forceBundlePending && $price === null) {
$fallback = $fallbackPrices[$line['sku']] ?? null;
if ($fallback !== null) {
$price = $fallback['price'];
$priceSource = $fallback['source'];
$fallbackPriceRows++;
}
}
}
// 线上代发价格也没有时,最后用普通商品资料的商品成本价兜底。
if (! $forceBundlePending && $price === null) {
$catalogPrice = $catalogPrices[$line['sku']] ?? null;
if ($catalogPrice !== null) {
$price = $catalogPrice;
$priceSource = self::PRICE_SOURCE_CATALOG;
$catalogPriceRows++;
// 线上代发价格也没有时,最后用普通商品资料的商品成本价兜底。
if (! $forceBundlePending && $price === null) {
$catalogPrice = $catalogPrices[$line['sku']] ?? null;
if ($catalogPrice !== null) {
$price = $catalogPrice;
$priceSource = self::PRICE_SOURCE_CATALOG;
$catalogPriceRows++;
}
}
}
$priced = $this->calculateLineCost((float) $line['qty'], $price);
@ -543,25 +568,31 @@ class SyncStoreReceiptProductCost extends Command
$realtimeMissingPriceRows++;
} elseif (isset($catalogPrices[$line['sku']])) {
$realtimeCatalogPriceRows++;
$realtimeQuantityTotal += $quantity;
$realtimeCostTotal += (float) $realtimePriced['cost'];
} else {
$realtimeFallbackPriceRows++;
$realtimeQuantityTotal += $quantity;
$realtimeCostTotal += (float) $realtimePriced['cost'];
}
$remarks = [];
if ($forceBundlePending) {
$remarks[] = in_array(
($line['bundle_resolution_status'] ?? ''),
['amount_mismatch', 'history_amount_mismatch', 'imported_amount_mismatch'],
true,
)
? '组合装组件金额不一致'
: '组合装未找到可用组件';
if (! $realtimeOnly) {
if ($forceBundlePending) {
$remarks[] = in_array(
($line['bundle_resolution_status'] ?? ''),
['amount_mismatch', 'history_amount_mismatch', 'imported_amount_mismatch'],
true,
)
? '组合装组件金额不一致'
: '组合装未找到可用组件';
}
if ($short === '') {
$remarks[] = self::REMARK_NO_WAREHOUSE;
$missingWarehouseRows++;
}
}
if ($short === '') {
$remarks[] = self::REMARK_NO_WAREHOUSE;
$missingWarehouseRows++;
}
if ($unitPrice === null) {
if (! $realtimeOnly && $unitPrice === null) {
$remarks[] = self::REMARK_NO_PRICE;
$missingPriceRows++;
$pendingCostRows[] = [
@ -620,7 +651,7 @@ class SyncStoreReceiptProductCost extends Command
$line['material_mapping_status'] ?? null,
),
];
} else {
} elseif (! $realtimeOnly) {
$matchedPriceRows++;
$quantityTotal += $quantity;
$costTotal += (float) $cost;
@ -664,8 +695,17 @@ class SyncStoreReceiptProductCost extends Command
}
$this->info(sprintf('写入完成,共 %d 行。', $imported));
$this->info(sprintf(' 商品数量合计:%s', number_format($quantityTotal, 2)));
$this->info(sprintf(' 商品成本合计:%s', number_format($costTotal, 2)));
if ($realtimeOnly) {
$this->info(' 本次仅重建商品实时价与商品实时成本;商品单价、价格来源和商品成本保持为空。');
$this->info(sprintf(
' 商品实时数量合计:%s;商品实时成本合计:%s',
number_format($realtimeQuantityTotal, 2),
number_format($realtimeCostTotal, 2),
));
} else {
$this->info(sprintf(' 商品数量合计:%s', number_format($quantityTotal, 2)));
$this->info(sprintf(' 商品成本合计:%s', number_format($costTotal, 2)));
}
$this->info(sprintf(
' 未匹配仓库简称:%d 行;线上代发价格兜底:%d 行;商品资料成本价兜底:%d 行;仍未匹配商品单价:%d 行',
$missingWarehouseRows,
@ -753,6 +793,8 @@ class SyncStoreReceiptProductCost extends Command
$result = [
'status' => 'success',
'operation' => $realtimeOnly ? 'realtime_only' : 'full_sync',
'formal_cost_generated' => ! $realtimeOnly,
'report_month' => $reportMonth,
'platform' => $platform !== '' ? $platform : '全部',
'source_bill_rows' => $bills->count(),
@ -854,6 +896,8 @@ class SyncStoreReceiptProductCost extends Command
'realtime_catalog_price_rows' => $realtimeCatalogPriceRows,
'realtime_fallback_price_rows' => $realtimeFallbackPriceRows,
'realtime_missing_price_rows' => $realtimeMissingPriceRows,
'realtime_quantity' => round($realtimeQuantityTotal, 4),
'realtime_cost' => round($realtimeCostTotal, 2),
'matched_quantity' => round($quantityTotal, 4),
'matched_cost' => round($costTotal, 2),
'pending_cost' => $pendingCostRows,
@ -3008,6 +3052,10 @@ class SyncStoreReceiptProductCost extends Command
// 2) 种菜商品整行排除,不尝试把它替换成去掉「种菜」前缀后的正式编码。
foreach ($unique as $key => $row) {
$sku = mb_strtoupper(trim((string) $row['sku']));
if (in_array($sku, self::EXCLUDED_SKUS, true)) {
unset($unique[$key]);
continue;
}
if (! self::isPlantingSku($sku)) {
continue;
}
@ -3051,8 +3099,8 @@ class SyncStoreReceiptProductCost extends Command
}
// 4) 上游有些平台组合会同时返回「+ 拼接父行」和多条组件行。
// 只有同一订单、outer_oi_id、shop_sku_id 下至少有两条组件,且组件金额
// 合计与父行一致时,父行才是可确认的汇总占位,才允许排除。
// 同一订单、outer_oi_id、shop_sku_id 下至少有两条组件,或存在一条可完整解析为
// 多个组件的 MKH-/ZH- 结构子行,且合计金额与父行一致时,才允许排除父行。
$plusParents = [];
$plusComponents = [];
foreach ($unique as $key => $row) {
@ -3067,12 +3115,21 @@ class SyncStoreReceiptProductCost extends Command
$plusComponents[$groupKey]['rows'] = ($plusComponents[$groupKey]['rows'] ?? 0) + 1;
$plusComponents[$groupKey]['amount'] = ($plusComponents[$groupKey]['amount'] ?? 0.0)
+ (float) $row['amount'];
if (count(self::expandComboSku((string) $row['sku'], (float) $row['qty'])) >= 2) {
$plusComponents[$groupKey]['structured_rows']
= ($plusComponents[$groupKey]['structured_rows'] ?? 0) + 1;
}
}
foreach ($plusParents as $key => $groupKey) {
$component = $plusComponents[$groupKey] ?? null;
$hasComponentDetail = $component !== null
&& (
$component['rows'] >= 2
|| ($component['rows'] === 1 && ($component['structured_rows'] ?? 0) === 1)
);
if (
$component !== null
&& $component['rows'] >= 2
&& $hasComponentDetail
&& abs(round((float) $component['amount'], 2) - round((float) $unique[$key]['amount'], 2)) <= 0.01
) {
$stats['plus_parent_excluded_rows']++;

View File

@ -2916,26 +2916,49 @@ class Pages extends Controller
*/
private function attachProductCostProductAttributes(Collection $rows): void
{
foreach ($rows as $row) {
$row->brand = null;
$row->category = null;
$row->supplier_name = null;
$row->free_shipping_manufacturer = null;
}
if ($rows->isEmpty()) {
return;
}
$codeKey = static fn (mixed $value): string => str_replace(
'_X002B_',
'+',
mb_strtoupper(trim((string) $value), 'UTF-8')
);
$attributesByCode = $this->productCostProductAttributeMap(
$rows->pluck('product_code')->filter()->values()->all()
);
foreach ($rows as $row) {
$attributes = $attributesByCode[$codeKey($row->product_code)] ?? [];
$row->brand = $attributes['brand'] ?? null;
$row->category = $attributes['category'] ?? null;
$row->supplier_name = $attributes['supplier_name'] ?? null;
$row->free_shipping_manufacturer = $attributes['free_shipping_manufacturer'] ?? null;
}
}
/**
* 商品成本列表和全量导出共用的商品属性缓存。
*
* @param list<mixed> $productCodes
* @return array<string,array{brand:?string,category:?string,supplier_name:?string,free_shipping_manufacturer:?bool}>
*/
private function productCostProductAttributeMap(array $productCodes): array
{
$codeKey = static fn (mixed $value): string => str_replace(
'_X002B_',
'+',
mb_strtoupper(trim((string) $value), 'UTF-8')
);
$productCodes = array_values(array_unique(array_filter(
array_map(static fn (mixed $value): string => trim((string) $value), $productCodes),
static fn (string $value): bool => $value !== '',
)));
if ($productCodes === []) {
return [];
}
$productByCode = collect();
try {
if ($this->productCatalog->available() && $this->productCatalog->ready()) {
$productByCode = collect($this->productCatalog->normalProductsBySkuCodes(
$rows->pluck('product_code')->filter()->values()->all()
$productCodes
))->groupBy('_sku_attribute_key')->map(
static fn (Collection $matches): object => $matches->first(
static fn (object $product): bool => (int) ($product->enabled ?? 0) === 1
@ -2984,35 +3007,36 @@ class Pages extends Controller
}
}
foreach ($rows as $row) {
$product = $productByCode->get($codeKey($row->product_code));
if ($product === null) {
continue;
}
$attributes = [];
foreach ($productByCode as $key => $product) {
$brand = trim((string) ($product->brand ?? ''));
$category = trim((string) ($product->category ?? ''));
$supplierName = trim((string) ($product->supplier_name ?? ''));
$row->brand = $brand !== '' ? $brand : null;
$row->category = $category !== '' ? $category : null;
$row->supplier_name = $supplierName !== '' ? $supplierName : null;
$freeShipping = null;
if (! $flagsReady || $supplierName === '') {
continue;
}
$supplierIds = $supplierIdsByName->get($supplierName, []);
if ($supplierIds === []) {
continue;
$freeShipping = null;
} else {
$supplierIds = $supplierIdsByName->get($supplierName, []);
if ($supplierIds !== []) {
$flags = collect($supplierIds)
->map(static fn (int $id): bool => (bool) ($flagsById[$id] ?? false))
->unique()
->values();
if ($flags->count() === 1) {
$freeShipping = $flags->first();
}
}
}
$flags = collect($supplierIds)
->map(static fn (int $id): bool => (bool) ($flagsById[$id] ?? false))
->unique()
->values();
if ($flags->count() === 1) {
$row->free_shipping_manufacturer = $flags->first();
}
$attributes[$key] = [
'brand' => $brand !== '' ? $brand : null,
'category' => $category !== '' ? $category : null,
'supplier_name' => $supplierName !== '' ? $supplierName : null,
'free_shipping_manufacturer' => $freeShipping,
];
}
return $attributes;
}
/**
@ -3591,19 +3615,12 @@ class Pages extends Controller
public function exportProductCosts(Request $request): StreamedResponse
{
$connection = (string) config('upstream_mirrors.connection', 'business_mirror');
$columns = [
['occurred_date', '发生时间'],
['store_name', '店铺名称'],
['online_order_no', '线上单号'],
['warehouse', '发货仓库'],
['warehouse_short_name', '仓库简称'],
['product_code', '商品编码'],
['product_quantity', '商品数量'],
['unit_price', '商品单价'],
['product_cost', '商品成本'],
['realtime_unit_price', '商品实时价'],
['realtime_product_cost', '商品实时成本'],
];
$columns = (array) config('product_cost_columns', []);
$requestedColumns = array_filter(explode(',', (string) $request->query('columns', '')));
$selectedColumns = array_values(array_intersect($requestedColumns, array_keys($columns)));
if ($selectedColumns === []) {
$selectedColumns = array_keys($columns);
}
$monthInput = trim((string) $request->query('month', ''));
$month = preg_match('/^\d{4}-\d{2}$/', $monthInput) === 1 ? $monthInput . '-01' : null;
@ -3628,36 +3645,87 @@ class Pages extends Controller
$query->where('warehouse_short_name', $warehouse);
}
// 导出与页面一致:全部数据(含未匹配单价与「-不看」仓)。
$productAttributeColumns = [
'brand',
'category',
'supplier_name',
'free_shipping_manufacturer',
];
$productAttributes = array_intersect($selectedColumns, $productAttributeColumns) === []
? []
: $this->productCostProductAttributeMap(
(clone $query)->whereNotNull('product_code')->distinct()
->orderBy('product_code')->pluck('product_code')->all()
);
$filename = '商品成本_' . ($month === null ? 'all' : substr($month, 0, 7)) . '.csv';
return response()->streamDownload(function () use ($query, $columns): void {
return response()->streamDownload(function () use (
$query,
$columns,
$selectedColumns,
$productAttributes,
): void {
@set_time_limit(0);
$out = fopen('php://output', 'w');
fwrite($out, "\xEF\xBB\xBF");
fputcsv($out, array_map(static fn (array $column): string => $column[1], $columns));
fputcsv($out, array_map(
static fn (string $key): string => (string) $columns[$key],
$selectedColumns,
));
$rows = $query->orderBy('occurred_date')->orderBy('store_name')
->orderBy('online_order_no')->orderBy('warehouse_short_name')->orderBy('product_code')
->cursor();
foreach ($rows as $row) {
$line = [];
foreach ($columns as [$key]) {
$value = $row->{$key} ?? '';
if (in_array($key, [
'product_quantity',
'unit_price',
'product_cost',
'realtime_unit_price',
'realtime_product_cost',
], true)) {
$line[] = $value === null || $value === '' ? '' : number_format((float) $value, 2, '.', '');
continue;
$codeKey = static fn (mixed $value): string => str_replace(
'_X002B_',
'+',
mb_strtoupper(trim((string) $value), 'UTF-8')
);
$writeRows = function (Collection $rows) use (
$out,
$selectedColumns,
$productAttributes,
$codeKey,
): void {
foreach ($rows as $row) {
$attributes = $productAttributes[$codeKey($row->product_code)] ?? [];
$line = [];
foreach ($selectedColumns as $key) {
$value = array_key_exists($key, $attributes)
? $attributes[$key]
: ($row->{$key} ?? '');
if (in_array($key, [
'product_quantity',
'unit_price',
'product_cost',
'realtime_unit_price',
'realtime_product_cost',
], true)) {
$line[] = $value === null || $value === ''
? ''
: number_format((float) $value, 2, '.', '');
continue;
}
if ($key === 'free_shipping_manufacturer') {
$line[] = $value === true ? '包邮' : '-';
continue;
}
$line[] = is_string($value) ? $value : (string) $value;
}
$line[] = is_string($value) ? $value : (string) $value;
fputcsv($out, $line);
}
fputcsv($out, $line);
};
$batch = [];
foreach ($query->orderBy('occurred_date')->orderBy('store_name')
->orderBy('online_order_no')->orderBy('warehouse_short_name')->orderBy('product_code')
->cursor() as $row) {
$batch[] = $row;
if (count($batch) >= 500) {
$writeRows(collect($batch));
$batch = [];
}
}
if ($batch !== []) {
$writeRows(collect($batch));
}
fclose($out);
}, $filename, ['Content-Type' => 'text/csv; charset=UTF-8']);

View File

@ -0,0 +1,29 @@
<?php
/*
|--------------------------------------------------------------------------
| 商品成本业务字段
|--------------------------------------------------------------------------
|
| 页面列设置和 CSV 导出共用这份顺序与中文表头,避免两处字段清单不一致。
|
*/
return [
'platform' => '平台',
'occurred_date' => '发生时间',
'store_name' => '店铺名称',
'online_order_no' => '线上单号',
'warehouse' => '发货仓库',
'warehouse_short_name' => '仓库简称',
'brand' => '品牌',
'category' => '类目',
'supplier_name' => '供应商',
'free_shipping_manufacturer' => '是否包邮厂家',
'product_code' => '商品编码',
'product_quantity' => '商品数量',
'unit_price' => '商品单价',
'product_cost' => '商品成本',
'realtime_unit_price' => '商品实时价',
'realtime_product_cost' => '商品实时成本',
];

View File

@ -20,7 +20,7 @@ store-receipt:product-cost:sync YYYY-MM --remap-warehouses-only
1. 业绩明细只取收入金额非空且不为 0 的账单行。
2. 种菜金额非空,或种菜标签为「种菜报销 / 种菜未报销」的账单行整行排除。
3. 商品编码为 `TCXJ`、`FUWU`、`AZF`、`DF-PJZY0001`、`JIAXIANGJIANCAIJIAJUZIZHUANG964A`、`YUNFEI`、`BCJ` 的订单行全局排除;组合装拆出的这些编码同样排除。
3. 商品编码为 `TCXJ`、`FUWU`、`AZF`、`DF-PJZY0001`、`JIAXIANGJIANCAIJIAJUZIZHUANG964A`、`YUNFEI`、`BCJ`、`信息说明`、`GG003-SZ`、`10237635142166`、`10237635142167`、`10228923011349`、`10230781002185`、`10230781002760`、`10230780802455` 的订单行全局排除;组合装拆出的这些编码同样排除。
4. 商品编码以「种菜」开头的订单行整行排除,不尝试去掉前缀后计价。
5. 发货仓库以 `配件-` 开头时整仓排除,不核算商品成本;发货仓库为「常州简尚家居有限公司」「简尚-苏州福利品仓」「简尚-自动发货仓」时也排除,仅「常州简尚家居有限公司」中以 `DF-` 开头的商品行例外保留。
6. 完成上述过滤后,再执行占位行去重、组合装展开、叶子行和已取消订单处理。
@ -31,7 +31,7 @@ store-receipt:product-cost:sync YYYY-MM --remap-warehouses-only
| 类型 | 识别条件 | 自动处理 | 无法唯一确认时 |
| --- | --- | --- | --- |
| 平台数字编码 | 同一订单、同一 `shop_i_id` 已有内部商品编码,当前编码为纯数字 | 数字平台占位行不参与成本 | 没有内部兄弟行时进入待核验 |
| 加号组合父行 | 同一订单、`outer_oi_id`、`shop_sku_id` 下至少两条组件,组件金额合计与父行一致 | 剔除带 `+` 的组合父行,只保留组件 | 保留父行待核验 |
| 加号组合父行 | 同一订单、`outer_oi_id`、`shop_sku_id` 下至少两条组件,或一条可完整解析为多个组件的 `MKH-` / `ZH-` 结构子行,组件金额合计与父行一致 | 剔除带 `+` 的组合父行,只保留组件 | 保留父行待核验 |
| 中文后缀别名 | 占位编码以白名单后缀结尾,当前白名单仅「非」;必须同数据源、平台、店铺、订单、子订单、`shop_sku_id`、`shop_i_id`、仓库 | 正式编码与占位编码各唯一,且数量和金额完全一致时,保留正式编码、剔除占位行 | 任一关系不唯一或数量、金额不一致,两个编码都保留 |
| 父子前缀占位 | 同一订单内只有一个严格扩展编码的子商品,且平台商品、规格、子订单和仓库一致 | 数量、金额一致时剔除较短父行,保留明细编码,例如 `CTG022516` 类父行 | 多子编码或任一字段不一致时保留父行 |
| 中文「组合」主行 | 商品编码包含中文「组合」;同一 `o_id` 下,组件 `src_combine_sku_id` 指向源组合装编码;没有显式标记时,组件须与主行 `outer_oi_id + shop_sku_id + shop_i_id` 一致 | 组件金额合计与组包总额误差≤0.01 元时剔除主行,只计组件 | 非零主行找不到组件或金额不一致时保留主行待核验,组件暂不计成本 |
@ -99,6 +99,9 @@ store-receipt:product-cost:sync YYYY-MM --remap-warehouses-only
4. 组件商品金额合计与基础码金额误差≤0.01 元;
5. 多个组件时生成多条成本行,数量和金额使用商品利润明细;单组件时直接替换基础码。
同一内部订单、线上订单、子订单号、店铺商品编码、店铺款式编码、商品编码、数量和金额完全相同,
仅在镜像表中主键或导入时间不同的组件行只计一次;子订单号不同的组件仍分别保留。
多基础码或金额不一致时不做替换,继续沿用原组合装、历史画像、订单售后导入明细和三级价格匹配逻辑。
### 2.5 91. 基础料号映射

View File

@ -221,7 +221,8 @@ class GoodsProfitAfsRepository
$columns = $this->fieldColumns();
foreach ([
'online_order_no', 'shop_name', 'shop_product_code', 'shop_style_code',
'internal_order_no', 'online_order_no', 'sub_order_no', 'shop_name',
'shop_product_code', 'shop_style_code',
'product_code', 'product_quantity', 'product_amount',
] as $field) {
if (! isset($columns[$field])) {
@ -232,10 +233,23 @@ class GoodsProfitAfsRepository
$select = array_values(array_unique(array_values(array_intersect_key(
$columns,
array_flip([
'online_order_no', 'shop_name', 'shop_product_code', 'shop_style_code',
'internal_order_no', 'online_order_no', 'sub_order_no', 'shop_name',
'shop_product_code', 'shop_style_code',
'product_code', 'product_quantity', 'product_amount',
]),
))));
$dedupeFields = array_values(array_intersect(array_keys($columns), [
'internal_order_no',
'online_order_no',
'sub_order_no',
'shop_name',
'shop_product_code',
'shop_style_code',
'product_code',
'product_quantity',
'product_amount',
]));
$seenComponentRows = [];
foreach (array_chunk($onlineOrderNos, 500) as $chunk) {
foreach ($this->connection()->table(self::MAIN_TABLE)
->whereIn($columns['online_order_no'], $chunk)
@ -247,7 +261,8 @@ class GoodsProfitAfsRepository
if ($productQuantity <= 0 || $productAmount <= 0 || $productCode === '') {
continue;
}
yield [
$row = [
'online_order_no' => trim((string) ($record->{$columns['online_order_no']} ?? '')),
'shop_name' => trim((string) ($record->{$columns['shop_name']} ?? '')),
'shop_sku_id' => trim((string) ($record->{$columns['shop_product_code']} ?? '')),
@ -256,6 +271,26 @@ class GoodsProfitAfsRepository
'product_quantity' => $productQuantity,
'product_amount' => $productAmount,
];
// 上游同一业务行可能在不同导出批次获得新的主键并再次落入镜像。
// 仅主键不同的相同组件行在这里合并一次;子订单号不同则仍分别保留。
$identity = [];
foreach ($dedupeFields as $field) {
$identity[$field] = trim((string) (
$record->{$columns[$field]}
?? ($row[$field] ?? '')
));
}
$identityKey = hash(
'sha256',
json_encode($identity, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
);
if (isset($seenComponentRows[$identityKey])) {
continue;
}
$seenComponentRows[$identityKey] = true;
yield $row;
}
}
}

View File

@ -36,24 +36,7 @@
'dialog' => 'pending',
],
];
$tableColumns = [
'platform' => '平台',
'occurred_date' => '发生时间',
'store_name' => '店铺名称',
'online_order_no' => '线上单号',
'warehouse' => '发货仓库',
'warehouse_short_name' => '仓库简称',
'brand' => '品牌',
'category' => '类目',
'supplier_name' => '供应商',
'free_shipping_manufacturer' => '是否包邮厂家',
'product_code' => '商品编码',
'product_quantity' => '商品数量',
'unit_price' => '商品单价',
'product_cost' => '商品成本',
'realtime_unit_price' => '商品实时价',
'realtime_product_cost' => '商品实时成本',
];
$tableColumns = config('product_cost_columns', []);
$pendingQuery = array_merge(
['company_id' => company_id()],
request()->except(['page', 'pending_page', 'per_page']),
@ -1344,8 +1327,10 @@
<span class="scope">当前显示列及顺序</span>
<a
href="{{ route('business.financial-operations.product-costs.export', array_merge(['company_id' => company_id()], request()->except('page'))) }}"
data-product-cost-export
data-product-cost-export-url="{{ route('business.financial-operations.product-costs.export', array_merge(['company_id' => company_id()], request()->except(['page', 'columns']))) }}"
aria-label="导出当前筛选结果"
title="导出全部筛选结果"
title="导出当前筛选结果(按当前显示列)"
>导出</a>
</div>
</div>
@ -1622,8 +1607,23 @@
var empty = card.querySelector('[data-product-cost-search-empty]');
var checks = Array.prototype.slice.call(card.querySelectorAll('[data-product-cost-column]'));
var reset = card.querySelector('[data-product-cost-column-reset]');
var exportLink = card.querySelector('[data-product-cost-export]');
var storageKey = card.getAttribute('data-storage-key') || 'product-cost-columns';
function updateExportLink(selected) {
if (!exportLink) { return; }
var url = new URL(
exportLink.getAttribute('data-product-cost-export-url'),
window.location.origin
);
if (selected.length === defaults.length) {
url.searchParams.delete('columns');
} else {
url.searchParams.set('columns', selected.join(','));
}
exportLink.href = url.toString();
}
function applyColumns(selected, persist) {
var visible = {};
checks.forEach(function (checkbox) {
@ -1637,6 +1637,7 @@
if (empty && empty.firstElementChild) {
empty.firstElementChild.colSpan = Math.max(Object.keys(visible).length, 1);
}
updateExportLink(selected);
if (persist) {
localStorage.setItem(storageKey, JSON.stringify(Object.keys(visible)));
}

View File

@ -125,6 +125,9 @@ class ProductCostPageLayoutTest extends TestCase
$this->assertStringContainsString('data-column-key="realtime_product_cost">商品实时成本', $html);
$this->assertStringContainsString('data-column-key="realtime_unit_price">12.00</td>', $html);
$this->assertStringContainsString('data-column-key="realtime_product_cost">12.00</td>', $html);
$this->assertStringContainsString('导出当前筛选结果', $html);
$this->assertStringContainsString('data-product-cost-export', $html);
$this->assertStringContainsString('data-product-cost-export-url=', $html);
$this->assertStringContainsString("url.searchParams.set('columns', selected.join(','));", $html);
$this->assertStringContainsString('导出当前筛选结果(按当前显示列)', $html);
}
}

View File

@ -68,6 +68,14 @@ class ProductCostProductAttributesTest extends FeatureTestCase
->assertSee('测试类目')
->assertSee('测试供应商')
->assertSee('包邮');
$csv = $this->get(route('business.financial-operations.product-costs.export', [
'month' => '2026-09',
]))->assertOk()->streamedContent();
$this->assertStringContainsString(
'京东账单,2026-09-01,京东-HX旗舰店101,ORDER-ATTRIBUTE,简尚-崔桥工厂仓,崔桥工厂仓,测试品牌,测试类目,测试供应商,包邮,SKU-ATTRIBUTE,1.00,10.00,10.00,,',
$csv,
);
}
private function createMirrorTables(): void

View File

@ -94,8 +94,22 @@ class StoreReceiptProductCostRealtimePriceTest extends FeatureTestCase
'business.financial-operations.product-costs.export',
['month' => '2026-09'],
))->assertOk()->streamedContent();
$this->assertStringContainsString('商品单价,商品成本,商品实时价,商品实时成本', $csv);
$this->assertStringContainsString(
'平台,发生时间,店铺名称,线上单号,发货仓库,仓库简称,品牌,类目,供应商,是否包邮厂家,商品编码,商品数量,商品单价,商品成本,商品实时价,商品实时成本',
$csv,
);
$this->assertStringContainsString(',12.00,24.00', $csv);
$selectedCsv = $this->get(route(
'business.financial-operations.product-costs.export',
[
'month' => '2026-09',
'columns' => 'platform,product_code,realtime_unit_price',
],
))->assertOk()->streamedContent();
$this->assertStringContainsString("平台,商品编码,商品实时价\n", $selectedCsv);
$this->assertStringContainsString('京东账单,SKU-CATALOG,12.00', $selectedCsv);
$this->assertStringNotContainsString('店铺名称', $selectedCsv);
}
private function createPriceSources($schema): void

View File

@ -22,7 +22,7 @@ class GoodsProfitAfsRepositoryTest extends TestCase
$schema->create(GoodsProfitAfsLookupSchema::TABLE, function (Blueprint $table): void {
$table->integer('id')->primary();
foreach ([
'undefined1', 'undefined2', 'undefined7', 'undefined8', 'undefined10',
'undefined1', 'undefined2', 'undefined3', 'undefined7', 'undefined8', 'undefined10',
'undefined12', 'undefined13', 'undefined20', 'undefined21', 'undefined25',
'_mirror_afs_order_time',
] as $column) {
@ -40,7 +40,8 @@ class GoodsProfitAfsRepositoryTest extends TestCase
'dataset_key' => GoodsProfitAfsRepository::MAIN_DATASET, 'initial_completed_at' => '2026-10-01 00:00:00',
]);
foreach ([
'undefined1' => '内部订单号', 'undefined2' => '线上订单号', 'undefined7' => '订单时间',
'undefined1' => '内部订单号', 'undefined2' => '线上订单号', 'undefined3' => '子订单号',
'undefined7' => '订单时间',
'undefined8' => '店铺名称', 'undefined10' => '商品编码',
'undefined12' => '店铺商品编码', 'undefined13' => '店铺款式编码',
'undefined20' => '商品数量', 'undefined25' => '商品金额',
@ -139,6 +140,7 @@ class GoodsProfitAfsRepositoryTest extends TestCase
'id' => 100,
'undefined1' => 'ORDER-100',
'undefined2' => 'ONLINE-100',
'undefined3' => 'SUB-100-A',
'undefined7' => '2026/9/1 10:00:00',
'undefined8' => '测试店铺',
'undefined10' => 'INTERNAL-COMPONENT',
@ -151,6 +153,7 @@ class GoodsProfitAfsRepositoryTest extends TestCase
'id' => 101,
'undefined1' => 'ORDER-100',
'undefined2' => 'ONLINE-100',
'undefined3' => 'SUB-100-A',
'undefined7' => '',
'undefined8' => '测试店铺',
'undefined10' => 'ZERO-PLACEHOLDER',
@ -159,13 +162,39 @@ class GoodsProfitAfsRepositoryTest extends TestCase
'undefined20' => '0',
'undefined25' => '0',
]);
$db->table(GoodsProfitAfsLookupSchema::TABLE)->insert([
'id' => 102,
'undefined1' => 'ORDER-100',
'undefined2' => 'ONLINE-100',
'undefined3' => 'SUB-100-A',
'undefined7' => '2026/9/1 10:05:00',
'undefined8' => '测试店铺',
'undefined10' => 'INTERNAL-COMPONENT',
'undefined12' => 'SHOP-SKU',
'undefined13' => 'SHOP-ITEM',
'undefined20' => '2',
'undefined25' => '199.98',
]);
$db->table(GoodsProfitAfsLookupSchema::TABLE)->insert([
'id' => 103,
'undefined1' => 'ORDER-100',
'undefined2' => 'ONLINE-100',
'undefined3' => 'SUB-100-B',
'undefined7' => '2026/9/1 10:06:00',
'undefined8' => '测试店铺',
'undefined10' => 'INTERNAL-COMPONENT',
'undefined12' => 'SHOP-SKU',
'undefined13' => 'SHOP-ITEM',
'undefined20' => '2',
'undefined25' => '199.98',
]);
$stream = (new GoodsProfitAfsRepository())
->streamPositiveComponentRowsForOrders(['ONLINE-100']);
$this->assertInstanceOf(\Generator::class, $stream);
$rows = iterator_to_array($stream, false);
$this->assertSame([[
$expected = [
'online_order_no' => 'ONLINE-100',
'shop_name' => '测试店铺',
'shop_sku_id' => 'SHOP-SKU',
@ -173,6 +202,7 @@ class GoodsProfitAfsRepositoryTest extends TestCase
'product_code' => 'INTERNAL-COMPONENT',
'product_quantity' => 2.0,
'product_amount' => 199.98,
]], $rows);
];
$this->assertSame([$expected, $expected], $rows);
}
}

View File

@ -419,6 +419,54 @@ class StoreReceiptProductCostLineTest extends TestCase
$this->assertContains('GBGJ-A+V01+GBGJ-B+V01', array_column($lines, 'sku'));
}
public function test_plus_parent_is_removed_when_single_structured_mkh_child_matches(): void
{
[$lines, , , $plusParents] = $this->costLines([
$this->row(
'plus-parent',
'DNZ038522N1280V01+GBGJ-DNZ038401N1440V01',
'993830851777',
1,
1161,
),
$this->row(
'structured-child',
'MKH-DNZ038522N1280V01-1-GBGJ-DNZ038401N1440V01-1',
'993830851777',
1,
1161,
),
]);
$this->assertSame(1, $plusParents);
$this->assertSame(
['DNZ038522N1280V01', 'GBGJ-DNZ038401N1440V01'],
array_column($lines, 'sku'),
);
}
public function test_confirmed_non_product_placeholder_codes_are_excluded(): void
{
$codes = [
'信息说明',
'GG003-SZ',
'10237635142166',
'10237635142167',
'10228923011349',
'10230781002185',
'10230781002760',
'10230780802455',
];
$rows = [];
foreach ($codes as $index => $code) {
$rows[] = $this->row('placeholder-' . $index, $code, '3200000000000', 1, 100);
}
[$lines] = $this->costLines($rows);
$this->assertSame([], $lines);
}
public function test_non_numeric_variant_parent_is_removed_when_quantity_and_amount_match(): void
{
[$lines, $placeholders, $bundles, $plusParents, $variantParents] = $this->costLines([