diff --git a/app/Console/Commands/SyncStoreReceiptProductCost.php b/app/Console/Commands/SyncStoreReceiptProductCost.php index 7c8bfed7..a6c0f73f 100644 --- a/app/Console/Commands/SyncStoreReceiptProductCost.php +++ b/app/Console/Commands/SyncStoreReceiptProductCost.php @@ -19,6 +19,7 @@ use Throwable; * * 发货仓库取订单上的 wms_co_id 对应的聚水潭仓库名称;仓库简称查仓库映射表; * 商品单价按「仓库简称 + 商品编码」取商品月加权平均单价里的加权平均价;商品成本 = 商品数量 × 商品单价。 + * 商品实时价独立按普通商品资料成本价、线上代发价格顺序取数;商品实时成本 = 商品数量 × 商品实时价。 */ class SyncStoreReceiptProductCost extends Command { @@ -27,6 +28,7 @@ class SyncStoreReceiptProductCost extends Command {--platform= : 只重建某个平台页签,留空表示全部} {--chunk=1000 : 临时表批量写入行数} {--remap-warehouses-only : 只按最新仓库映射表刷新仓库简称,不重算其他字段} + {--refresh-realtime-prices-only : 只刷新商品实时价与商品实时成本,不重算其他字段} {--result-json= : 将结果统计和待核验清单写入指定 JSON 文件}'; protected $description = '展开业绩明细对应的订单商品行,计算商品成本(发货仓库 → 仓库简称 → 商品单价 → 商品成本)'; @@ -168,6 +170,9 @@ class SyncStoreReceiptProductCost extends Command if ($this->option('remap-warehouses-only')) { return $this->remapWarehouseShortNames($connection, $reportMonth, $platform); } + if ($this->option('refresh-realtime-prices-only')) { + return $this->refreshRealtimePricesOnly($connection, $reportMonth, $platform); + } // 账单侧取数:业绩明细里本月(可按平台限定)的账单行,一行 = 一个店铺的一个订单。 // 收入为 0 的补行没有对应的收款商品,不参与商品成本。 @@ -392,6 +397,9 @@ class SyncStoreReceiptProductCost extends Command $missingWarehouseRows = 0; $fallbackPriceRows = 0; $catalogPriceRows = 0; + $realtimeCatalogPriceRows = 0; + $realtimeFallbackPriceRows = 0; + $realtimeMissingPriceRows = 0; $matchedPriceRows = 0; $placeholderExcludedRows = 0; $bundleParentExcludedRows = 0; @@ -525,6 +533,19 @@ class SyncStoreReceiptProductCost extends Command $quantity = $priced['quantity']; $unitPrice = $priced['unit_price']; $cost = $priced['cost']; + $realtimeUnitPrice = self::realtimeUnitPrice( + (string) $line['sku'], + $catalogPrices, + $fallbackPrices, + ); + $realtimePriced = $this->calculateLineCost((float) $line['qty'], $realtimeUnitPrice); + if ($realtimeUnitPrice === null) { + $realtimeMissingPriceRows++; + } elseif (isset($catalogPrices[$line['sku']])) { + $realtimeCatalogPriceRows++; + } else { + $realtimeFallbackPriceRows++; + } $remarks = []; if ($forceBundlePending) { @@ -623,6 +644,8 @@ class SyncStoreReceiptProductCost extends Command 'unit_price' => $unitPrice, 'price_source' => $priceSource, 'product_cost' => $cost, + 'realtime_unit_price' => $realtimePriced['unit_price'], + 'realtime_product_cost' => $realtimePriced['cost'], 'remark' => $remarks === [] ? null : implode(' / ', $remarks), 'imported_at' => $now, ]; @@ -650,6 +673,12 @@ class SyncStoreReceiptProductCost extends Command $catalogPriceRows, $missingPriceRows, )); + $this->info(sprintf( + ' 商品实时价:商品资料成本价 %d 行;线上代发价格兜底 %d 行;未匹配 %d 行', + $realtimeCatalogPriceRows, + $realtimeFallbackPriceRows, + $realtimeMissingPriceRows, + )); $pendingCostQuantity = array_sum(array_column($pendingCostRows, 'product_quantity')); $this->info(sprintf( ' 正常匹配单价:%d 行;排除平台占位行:%d 行;排除组合装主行:%d 行;排除加号组合父行:%d 行;排除父子前缀占位行:%d 行;中文别名替换:%d 行;排除种菜前缀:%d 行;待核验成本:%d 行 / %s 件', @@ -822,6 +851,9 @@ class SyncStoreReceiptProductCost extends Command 'missing_warehouse_rows' => $missingWarehouseRows, 'fallback_purchase_price_rows' => $fallbackPriceRows, 'fallback_catalog_price_rows' => $catalogPriceRows, + 'realtime_catalog_price_rows' => $realtimeCatalogPriceRows, + 'realtime_fallback_price_rows' => $realtimeFallbackPriceRows, + 'realtime_missing_price_rows' => $realtimeMissingPriceRows, 'matched_quantity' => round($quantityTotal, 4), 'matched_cost' => round($costTotal, 2), 'pending_cost' => $pendingCostRows, @@ -1881,6 +1913,31 @@ class SyncStoreReceiptProductCost extends Command ]; } + /** + * 商品实时价使用独立口径:普通商品资料成本价优先,匹配不到时用线上代发价格。 + * + * @param array $catalogPrices + * @param array $fallbackPrices + */ + private static function realtimeUnitPrice( + string $sku, + array $catalogPrices, + array $fallbackPrices, + ): ?float { + $sku = mb_strtoupper(trim($sku)); + if ($sku === '') { + return null; + } + + if (isset($catalogPrices[$sku])) { + return (float) $catalogPrices[$sku]; + } + + return isset($fallbackPrices[$sku]['price']) + ? (float) $fallbackPrices[$sku]['price'] + : null; + } + /** @param array $row */ private function plusCombinationGroupKey(array $row): ?string { @@ -3834,6 +3891,151 @@ class SyncStoreReceiptProductCost extends Command $query->delete(); } + /** + * 只根据现有商品编码和数量刷新两列实时价格口径,不触碰历史商品单价、成本、备注或拆单结果。 + */ + private function refreshRealtimePricesOnly( + string $connection, + string $reportMonth, + string $platform, + ): int { + $mirror = DB::connection($connection); + $fallbackPrices = $this->onlineDaifaUnitPrices($mirror); + $catalogPrices = $this->catalogCostPrices($mirror); + $query = $mirror->table(self::TARGET_TABLE)->where('report_month', $reportMonth); + $driver = $mirror->getDriverName(); + $tempTable = 'tmp_product_cost_realtime_prices'; + $grammar = $mirror->getQueryGrammar(); + $tempTableSql = $grammar->wrapTable($tempTable); + if ($platform !== '') { + $query->where('platform', $platform); + } + + $totalRows = 0; + $updatedRows = 0; + $catalogRows = 0; + $fallbackRows = 0; + $missingRows = 0; + $batchSize = max((int) $this->option('chunk'), 500); + + if ($driver === 'mysql') { + $mirror->statement("DROP TEMPORARY TABLE IF EXISTS {$tempTableSql}"); + $mirror->statement( + "CREATE TEMPORARY TABLE {$tempTableSql} (" + . 'row_key char(64) NOT NULL PRIMARY KEY, ' + . 'realtime_unit_price decimal(20,4) NULL, ' + . 'realtime_product_cost decimal(20,4) NULL' + . ') ENGINE=InnoDB', + ); + } + + try { + $query->select(['row_key', 'product_code', 'product_quantity']) + ->orderBy('row_key') + ->chunkById($batchSize, function ($rows) use ( + $driver, + $mirror, + $tempTable, + $reportMonth, + &$totalRows, + &$updatedRows, + &$catalogRows, + &$fallbackRows, + &$missingRows, + $catalogPrices, + $fallbackPrices, + ): void { + $updates = []; + foreach ($rows as $row) { + $totalRows++; + $sku = mb_strtoupper(trim((string) ($row->product_code ?? ''))); + $realtimePrice = self::realtimeUnitPrice($sku, $catalogPrices, $fallbackPrices); + $priced = $this->calculateLineCost((float) ($row->product_quantity ?? 0), $realtimePrice); + if ($realtimePrice === null) { + $missingRows++; + } elseif (isset($catalogPrices[$sku])) { + $catalogRows++; + } else { + $fallbackRows++; + } + $updates[] = [ + 'row_key' => $row->row_key, + 'realtime_unit_price' => $priced['unit_price'], + 'realtime_product_cost' => $priced['cost'], + ]; + } + + if ($updates === []) { + return; + } + if ($driver === 'mysql') { + $mirror->table($tempTable)->insertOrIgnore($updates); + } else { + foreach ($updates as $update) { + $mirror->table(self::TARGET_TABLE) + ->where('report_month', $reportMonth) + ->where('row_key', $update['row_key']) + ->update([ + 'realtime_unit_price' => $update['realtime_unit_price'], + 'realtime_product_cost' => $update['realtime_product_cost'], + ]); + } + } + $updatedRows += count($updates); + }, 'row_key'); + + if ($driver === 'mysql') { + $targetTableSql = $grammar->wrapTable(self::TARGET_TABLE); + $mirror->update( + "UPDATE {$targetTableSql} cost " + . "JOIN {$tempTableSql} realtime ON realtime.row_key = cost.row_key " + . 'SET cost.realtime_unit_price = realtime.realtime_unit_price, ' + . 'cost.realtime_product_cost = realtime.realtime_product_cost ' + . 'WHERE cost.report_month = ?', + [$reportMonth], + ); + } + } finally { + if ($driver === 'mysql') { + $mirror->statement("DROP TEMPORARY TABLE IF EXISTS {$tempTableSql}"); + } + } + + $result = [ + 'status' => 'success', + 'operation' => 'refresh_realtime_prices_only', + 'report_month' => $reportMonth, + 'platform' => $platform !== '' ? $platform : '全部', + 'total_rows' => $totalRows, + 'updated_rows' => $updatedRows, + 'catalog_price_rows' => $catalogRows, + 'fallback_price_rows' => $fallbackRows, + 'missing_price_rows' => $missingRows, + 'generated_at' => now()->toDateTimeString(), + ]; + $resultPath = trim((string) $this->option('result-json')); + if ($resultPath !== '') { + File::ensureDirectoryExists(dirname($resultPath)); + File::put( + $resultPath, + json_encode( + $result, + JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT, + ) . PHP_EOL, + ); + } + + $this->info(sprintf( + '商品实时价刷新完成:共 %d 行;商品资料成本价 %d 行;线上代发价格兜底 %d 行;未匹配 %d 行。', + $updatedRows, + $catalogRows, + $fallbackRows, + $missingRows, + )); + + return self::SUCCESS; + } + /** * 订单号清洗沿用业绩明细的同一套口径(去日期前缀 / 空格 / 各类横杠,统一大写)。 */ diff --git a/app/Http/Controllers/Business/Pages.php b/app/Http/Controllers/Business/Pages.php index fb669654..e00dd173 100644 --- a/app/Http/Controllers/Business/Pages.php +++ b/app/Http/Controllers/Business/Pages.php @@ -3601,6 +3601,8 @@ class Pages extends Controller ['product_quantity', '商品数量'], ['unit_price', '商品单价'], ['product_cost', '商品成本'], + ['realtime_unit_price', '商品实时价'], + ['realtime_product_cost', '商品实时成本'], ]; $monthInput = trim((string) $request->query('month', '')); @@ -3642,7 +3644,13 @@ class Pages extends Controller $line = []; foreach ($columns as [$key]) { $value = $row->{$key} ?? ''; - if (in_array($key, ['product_quantity', 'unit_price', 'product_cost'], true)) { + 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; diff --git a/database/migrations/2026_11_05_100000_add_realtime_prices_to_store_receipt_product_cost_rows.php b/database/migrations/2026_11_05_100000_add_realtime_prices_to_store_receipt_product_cost_rows.php new file mode 100644 index 00000000..4d57d3f8 --- /dev/null +++ b/database/migrations/2026_11_05_100000_add_realtime_prices_to_store_receipt_product_cost_rows.php @@ -0,0 +1,65 @@ +connection()); + if (! $schema->hasTable('store_receipt_product_cost_rows')) { + return; + } + + $missing = []; + foreach (['realtime_unit_price', 'realtime_product_cost'] as $column) { + if (! $schema->hasColumn('store_receipt_product_cost_rows', $column)) { + $missing[] = $column; + } + } + if ($missing === []) { + return; + } + + $schema->table('store_receipt_product_cost_rows', function (Blueprint $table) use ($missing): void { + if (in_array('realtime_unit_price', $missing, true)) { + $table->decimal('realtime_unit_price', 20, 4)->nullable()->after('product_cost'); + } + if (in_array('realtime_product_cost', $missing, true)) { + $table->decimal('realtime_product_cost', 20, 4)->nullable()->after('realtime_unit_price'); + } + }); + } + + public function down(): void + { + $schema = Schema::connection($this->connection()); + if (! $schema->hasTable('store_receipt_product_cost_rows')) { + return; + } + + $existing = []; + foreach (['realtime_product_cost', 'realtime_unit_price'] as $column) { + if ($schema->hasColumn('store_receipt_product_cost_rows', $column)) { + $existing[] = $column; + } + } + if ($existing === []) { + return; + } + + $schema->table('store_receipt_product_cost_rows', function (Blueprint $table) use ($existing): void { + $table->dropColumn($existing); + }); + } +}; 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 8386941e..7cb19562 100644 --- a/resources/views/business/pages/financial-operations/product-costs.blade.php +++ b/resources/views/business/pages/financial-operations/product-costs.blade.php @@ -51,6 +51,8 @@ 'product_quantity' => '商品数量', 'unit_price' => '商品单价', 'product_cost' => '商品成本', + 'realtime_unit_price' => '商品实时价', + 'realtime_product_cost' => '商品实时成本', ]; $pendingQuery = array_merge( ['company_id' => company_id()], @@ -1169,6 +1171,8 @@ 常州简尚家居有限公司对应映射表里的「配件单仓」行), 商品单价按「仓库简称 + 商品编码」取「商品月加权平均单价」里的加权平均价;匹配不到时退回「线上代发价格」 (采购单价优先、其次钉钉代发单价),仍匹配不到时用「普通商品资料」里的商品成本价兜底;商品成本 = 商品数量 × 商品单价。 + 商品实时价与历史商品单价分开计算:优先取「普通商品资料」里的成本价,匹配不到时取「线上代发价格」; + 商品实时成本 = 商品数量 × 商品实时价。实时成本仅作辅助核对,不并入商品成本合计,也不改变待核验判定。 平台数字 SKU 会按平台 SKU ID + 商品 ID 回查历史已拆分订单;历史无结果时,再按店铺名称 + 店铺商品编码 + 店铺款式编码 回查订单售后费用镜像,仅唯一内部编码自动替换;多候选保持待核验。 同一订单下已有内部商品编码时,平台数字商品占位行不参与成本;商品编码含中文「组合」的主行与同一 o_id 下的组件先做金额对账, @@ -1309,7 +1313,7 @@ id="product-cost-table" aria-label="商品成本明细" data-product-cost-table-card - data-storage-key="product-cost-columns:v2:{{ auth()->id() }}" + data-storage-key="product-cost-columns:v3:{{ auth()->id() }}" >
@@ -1363,6 +1367,8 @@ 商品数量 商品单价 商品成本 + 商品实时价 + 商品实时成本 @@ -1382,10 +1388,12 @@ {{ $qty($row->product_quantity) }} {{ $money($row->unit_price) }} {{ $money($row->product_cost) }} + {{ $money($row->realtime_unit_price) }} + {{ $money($row->realtime_product_cost) }} @empty - +
{{ $error ? '镜像读取失败,请稍后重试。' : '暂无符合条件的商品成本数据;生成完成后会自动显示。' }}
@@ -1393,7 +1401,7 @@ @endforelse - 当前页没有匹配的数据。 + 当前页没有匹配的数据。 diff --git a/tests/Feature/Business/ProductCostPageLayoutTest.php b/tests/Feature/Business/ProductCostPageLayoutTest.php index 9735b7de..2efc3c2a 100644 --- a/tests/Feature/Business/ProductCostPageLayoutTest.php +++ b/tests/Feature/Business/ProductCostPageLayoutTest.php @@ -26,6 +26,8 @@ class ProductCostPageLayoutTest extends TestCase 'product_quantity' => 1, 'unit_price' => 10, 'product_cost' => 10, + 'realtime_unit_price' => 12, + 'realtime_product_cost' => 12, ]; $html = view('business.pages.financial-operations.product-costs', [ 'section' => ['slug' => 'financial-operations'], @@ -100,7 +102,7 @@ class ProductCostPageLayoutTest extends TestCase $this->assertStringNotContainsString('线上代发价兜底', $html); $this->assertStringNotContainsString('商品资料成本兜底', $html); $this->assertStringContainsString('class="product-cost-filter-form"', $html); - $this->assertStringContainsString('product-cost-columns:v2:', $html); + $this->assertStringContainsString('product-cost-columns:v3:', $html); $this->assertStringContainsString('搜索当前页数据', $html); $this->assertStringContainsString('列设置', $html); $this->assertStringContainsString('全部筛选结果', $html); @@ -119,6 +121,10 @@ class ProductCostPageLayoutTest extends TestCase $this->assertStringContainsString('data-column-key="category">测试类目', $html); $this->assertStringContainsString('data-column-key="supplier_name">测试供应商', $html); $this->assertStringContainsString('data-column-key="free_shipping_manufacturer">包邮', $html); + $this->assertStringContainsString('data-column-key="realtime_unit_price">商品实时价', $html); + $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); } } diff --git a/tests/Feature/Console/StoreReceiptProductCostRealtimePriceTest.php b/tests/Feature/Console/StoreReceiptProductCostRealtimePriceTest.php new file mode 100644 index 00000000..ae974db0 --- /dev/null +++ b/tests/Feature/Console/StoreReceiptProductCostRealtimePriceTest.php @@ -0,0 +1,166 @@ +createPriceSources($schema); + + $mirror->table('ops_jst_sku')->insert([ + ['sku_id' => 'SKU-CATALOG', 'sku_type' => 'normal', 'cost_price' => 12], + ['sku_id' => 'SKU-PURCHASE', 'sku_type' => 'normal', 'cost_price' => 0], + ]); + $mirror->table('product_purchase_price_mirror_rows')->insert([ + [ + 'item_id' => 1, + 'sku_id' => 'SKU-CATALOG', + 'unit_price' => 20, + 'document_status' => 'Finished', + 'finished_at' => '2026-09-10 10:00:00', + 'created_at' => '2026-09-10 10:00:00', + 'updated_at' => '2026-09-10 10:00:00', + ], + [ + 'item_id' => 2, + 'sku_id' => 'SKU-PURCHASE', + 'unit_price' => 5.5, + 'document_status' => 'Finished', + 'finished_at' => '2026-09-11 10:00:00', + 'created_at' => '2026-09-11 10:00:00', + 'updated_at' => '2026-09-11 10:00:00', + ], + ]); + $mirror->table('ding_online_daifa_price_mirror')->insert([ + 'process_instance_id' => 'PROC-1', + 'detail_index' => 0, + 'product_id' => '9001', + 'ship_qty' => 3, + 'daifa_amount' => 21, + 'workflow_created_at' => '2026-09-12 10:00:00', + ]); + $mirror->table('ops_jst_sku_map')->insert([ + 'shop_i_id' => '9001', + 'sku_id' => 'SKU-DING', + ]); + $mirror->table('store_receipt_product_cost_rows')->insert([ + $this->row('catalog', 'SKU-CATALOG', 2, 9, 18), + $this->row('purchase', 'SKU-PURCHASE', 3, 8, 24), + $this->row('ding', 'SKU-DING', 4, 7, 28), + $this->row('missing', 'SKU-MISSING', 5, 6, 30), + ]); + + $this->artisan('store-receipt:product-cost:sync', [ + 'month' => '2026-09', + '--refresh-realtime-prices-only' => true, + ])->assertExitCode(Command::SUCCESS); + + $rows = $mirror->table('store_receipt_product_cost_rows') + ->orderBy('row_key') + ->get() + ->keyBy('row_key'); + + $this->assertSame(12.0, (float) $rows['catalog']->realtime_unit_price); + $this->assertSame(24.0, (float) $rows['catalog']->realtime_product_cost); + $this->assertSame(5.5, (float) $rows['purchase']->realtime_unit_price); + $this->assertSame(16.5, (float) $rows['purchase']->realtime_product_cost); + $this->assertSame(7.0, (float) $rows['ding']->realtime_unit_price); + $this->assertSame(28.0, (float) $rows['ding']->realtime_product_cost); + $this->assertNull($rows['missing']->realtime_unit_price); + $this->assertNull($rows['missing']->realtime_product_cost); + + $historical = [ + 'catalog' => [9.0, 18.0], + 'purchase' => [8.0, 24.0], + 'ding' => [7.0, 28.0], + 'missing' => [6.0, 30.0], + ]; + foreach ($rows as $key => $row) { + $this->assertSame($historical[$key][0], (float) $row->unit_price, $key); + $this->assertSame($historical[$key][1], (float) $row->product_cost, $key); + $this->assertSame('保留历史口径', $row->remark, $key); + } + + $csv = $this->loginAs()->get(route( + 'business.financial-operations.product-costs.export', + ['month' => '2026-09'], + ))->assertOk()->streamedContent(); + $this->assertStringContainsString('商品单价,商品成本,商品实时价,商品实时成本', $csv); + $this->assertStringContainsString(',12.00,24.00', $csv); + } + + private function createPriceSources($schema): void + { + if (! $schema->hasTable('ops_jst_sku')) { + $schema->create('ops_jst_sku', function (Blueprint $table): void { + $table->string('sku_id'); + $table->string('sku_type')->nullable(); + $table->decimal('cost_price', 20, 4)->nullable(); + }); + } + if (! $schema->hasTable('ops_jst_sku_map')) { + $schema->create('ops_jst_sku_map', function (Blueprint $table): void { + $table->string('shop_i_id'); + $table->string('sku_id'); + }); + } + if (! $schema->hasTable('product_purchase_price_mirror_rows')) { + $schema->create('product_purchase_price_mirror_rows', function (Blueprint $table): void { + $table->unsignedBigInteger('item_id')->primary(); + $table->string('sku_id')->nullable(); + $table->decimal('unit_price', 20, 4)->nullable(); + $table->string('document_status')->nullable(); + $table->dateTime('finished_at')->nullable(); + $table->dateTime('document_created_at')->nullable(); + $table->dateTime('purchase_updated_at')->nullable(); + $table->timestamps(); + }); + } + if (! $schema->hasTable('ding_online_daifa_price_mirror')) { + $schema->create('ding_online_daifa_price_mirror', function (Blueprint $table): void { + $table->string('process_instance_id'); + $table->unsignedTinyInteger('detail_index')->default(0); + $table->string('product_id')->nullable(); + $table->unsignedInteger('ship_qty')->nullable(); + $table->decimal('daifa_amount', 14, 2)->nullable(); + $table->string('workflow_created_at')->nullable(); + $table->primary(['process_instance_id', 'detail_index']); + }); + } + } + + /** @return array */ + private function row( + string $rowKey, + string $productCode, + int $quantity, + float $historicalUnitPrice, + float $historicalCost, + ): array { + return [ + 'report_month' => '2026-09-01', + 'row_key' => $rowKey, + 'platform' => '京东账单', + 'occurred_date' => '2026-09-01', + 'store_name' => '测试店铺', + 'online_order_no' => 'ORDER-' . $rowKey, + 'warehouse' => '简尚-崔桥工厂仓', + 'warehouse_short_name' => '崔桥工厂仓', + 'product_code' => $productCode, + 'product_quantity' => $quantity, + 'unit_price' => $historicalUnitPrice, + 'product_cost' => $historicalCost, + 'remark' => '保留历史口径', + 'imported_at' => now(), + ]; + } +}