From 3bf02cb95c2a7fb4b520475b375ddcc48f1295b5 Mon Sep 17 00:00:00 2001 From: chenxi Date: Thu, 5 Nov 2026 18:13:44 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E5=AE=8C=E5=96=84=E5=95=86=E5=93=81?= =?UTF-8?q?=E6=88=90=E6=9C=AC=E5=85=A8=E5=AD=97=E6=AE=B5=E5=AF=BC=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Http/Controllers/Business/Pages.php | 202 ++++++++++++------ config/product_cost_columns.php | 29 +++ .../product-costs.blade.php | 39 ++-- .../Business/ProductCostPageLayoutTest.php | 5 +- .../ProductCostProductAttributesTest.php | 8 + ...oreReceiptProductCostRealtimePriceTest.php | 16 +- 6 files changed, 211 insertions(+), 88 deletions(-) create mode 100644 config/product_cost_columns.php diff --git a/app/Http/Controllers/Business/Pages.php b/app/Http/Controllers/Business/Pages.php index e00dd173..855166a6 100644 --- a/app/Http/Controllers/Business/Pages.php +++ b/app/Http/Controllers/Business/Pages.php @@ -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 $productCodes + * @return array + */ + 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']); diff --git a/config/product_cost_columns.php b/config/product_cost_columns.php new file mode 100644 index 00000000..65d9c39d --- /dev/null +++ b/config/product_cost_columns.php @@ -0,0 +1,29 @@ + '平台', + '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' => '商品实时成本', +]; diff --git a/resources/views/business/pages/financial-operations/product-costs.blade.php b/resources/views/business/pages/financial-operations/product-costs.blade.php index 7cb19562..61b472e2 100644 --- a/resources/views/business/pages/financial-operations/product-costs.blade.php +++ b/resources/views/business/pages/financial-operations/product-costs.blade.php @@ -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 @@ 当前显示列及顺序 导出 @@ -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))); } diff --git a/tests/Feature/Business/ProductCostPageLayoutTest.php b/tests/Feature/Business/ProductCostPageLayoutTest.php index 2efc3c2a..5980aba4 100644 --- a/tests/Feature/Business/ProductCostPageLayoutTest.php +++ b/tests/Feature/Business/ProductCostPageLayoutTest.php @@ -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', $html); $this->assertStringContainsString('data-column-key="realtime_product_cost">12.00', $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); } } diff --git a/tests/Feature/Business/ProductCostProductAttributesTest.php b/tests/Feature/Business/ProductCostProductAttributesTest.php index 8116bc7a..36c673c5 100644 --- a/tests/Feature/Business/ProductCostProductAttributesTest.php +++ b/tests/Feature/Business/ProductCostProductAttributesTest.php @@ -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 diff --git a/tests/Feature/Console/StoreReceiptProductCostRealtimePriceTest.php b/tests/Feature/Console/StoreReceiptProductCostRealtimePriceTest.php index ae974db0..5a766ada 100644 --- a/tests/Feature/Console/StoreReceiptProductCostRealtimePriceTest.php +++ b/tests/Feature/Console/StoreReceiptProductCostRealtimePriceTest.php @@ -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