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

This commit is contained in:
chenxi 2026-11-05 18:13:44 +08:00
parent ad0b6d43d3
commit 3bf02cb95c
6 changed files with 211 additions and 88 deletions

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

@ -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