商品成本新增商品与供应商属性列 #576

Merged
chenxi merged 3 commits from feature/chenxi-product-cost-product-attributes into main 2026-10-26 09:53:30 +08:00
8 changed files with 392 additions and 4 deletions

View File

@ -65,6 +65,7 @@ use Modules\EcommerceFinance\Repositories\PinduoduoSpreadBillRepository;
use Modules\EcommerceFinance\Repositories\ProductCatalogMirrorRepository;
use Modules\EcommerceFinance\Repositories\ProductPriceMirrorRepository;
use Modules\EcommerceFinance\Repositories\RawBoardPayablesRepository;
use Modules\EcommerceFinance\Repositories\SupplierManagementMirrorRepository;
use Modules\EcommerceFinance\Repositories\DingPayableWorkflowMirrorRepository;
use Modules\EcommerceFinance\Repositories\DingOnlineDaifaPriceMirrorRepository;
use Modules\EcommerceFinance\Repositories\SmallPaymentWorkOrderMirrorRepository;
@ -80,6 +81,7 @@ use Modules\EcommerceFinance\Services\UpstreamQueryCacheFactory;
use Modules\EcommerceFinance\Services\SupplierPayableMaintenanceRegistry;
use Modules\EcommerceFinance\Services\PayablesFinalRegistry;
use Modules\EcommerceFinance\Services\SupplierPayableOverrideStore;
use Modules\EcommerceFinance\Services\SupplierFreeShippingStore;
use Modules\EcommerceFinance\View\PlatformPromotionAccountPageData;
use Modules\EcommerceFinance\View\OrderDataPageData;
use RuntimeException;
@ -899,6 +901,8 @@ class Pages extends Controller
private readonly WithdrawalManagementReport $withdrawalManagementReport,
private readonly CourierSurchargeSettlementMirrorRepository $courierSurchargeSettlements,
private readonly ShippingOrderRepository $shippingOrders,
private readonly SupplierManagementMirrorRepository $supplierManagement,
private readonly SupplierFreeShippingStore $supplierFreeShipping,
) {
$this->middleware('auth');
$this->middleware('company.identify');
@ -2783,6 +2787,7 @@ class Pages extends Controller
->orderBy('product_code')
->forPage($page, $limit)
->get();
$this->attachProductCostProductAttributes($items);
return [
'view' => 'business.pages.financial-operations.product-costs',
@ -2811,6 +2816,112 @@ class Pages extends Controller
];
}
/**
* 商品成本页面按商品编码补充品牌、类目、供应商,并按供应商补充是否包邮厂家。
*
* @param Collection<int,object> $rows
*/
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')
);
$productByCode = collect();
try {
if ($this->productCatalog->available() && $this->productCatalog->ready()) {
$productByCode = collect($this->productCatalog->normalProductsBySkuCodes(
$rows->pluck('product_code')->filter()->values()->all()
))->groupBy('_sku_attribute_key')->map(
static fn (Collection $matches): object => $matches->first(
static fn (object $product): bool => (int) ($product->enabled ?? 0) === 1
) ?: $matches->first()
);
}
} catch (Throwable) {
// 商品资料异常时仍展示商品成本主表,新增属性留空。
}
$supplierIdsByName = collect();
$flagsById = [];
$flagsReady = false;
$supplierNames = $productByCode
->pluck('supplier_name')
->map(static fn (mixed $value): string => trim((string) $value))
->filter()
->unique()
->values();
if ($supplierNames->isNotEmpty()) {
try {
if ($this->supplierManagement->ready()) {
$supplierIdsByName = collect($this->supplierManagement->suppliersByNames(
$supplierNames->all()
))->groupBy(
static fn (object $supplier): string => trim((string) ($supplier->scmname ?? ''))
)->map(
static fn (Collection $suppliers): array => $suppliers
->pluck('Id')
->map(static fn (mixed $id): int => (int) $id)
->filter()
->unique()
->values()
->all()
);
$flagsById = $this->supplierFreeShipping->flagsBySupplierIds(
$supplierIdsByName->flatten()->map(static fn (mixed $id): int => (int) $id)->all(),
(int) (company_id() ?: 1),
);
$flagsReady = true;
}
} catch (Throwable) {
// 包邮维护记录不可读时保留待确认状态,不把未知值误判为“否”。
$flagsReady = false;
}
}
foreach ($rows as $row) {
$product = $productByCode->get($codeKey($row->product_code));
if ($product === null) {
continue;
}
$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;
if (! $flagsReady || $supplierName === '') {
continue;
}
$supplierIds = $supplierIdsByName->get($supplierName, []);
if ($supplierIds === []) {
continue;
}
$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();
}
}
}
/**
* 商品成本合计明细:与页面成本合计使用同一有效单价口径,
* 按发货仓库透视商品数量与商品成本。

View File

@ -153,6 +153,74 @@ class ProductCatalogMirrorRepository
];
}
/**
* 商品成本页面按商品编码补充品牌、类目、供应商。
*
* @param list<string> $skuCodes
* @return list<object>
*/
public function normalProductsBySkuCodes(array $skuCodes): array
{
if (! $this->ready()) {
throw new RuntimeException('business_mirror_dataset_not_ready');
}
$lookupValues = [];
foreach ($skuCodes as $skuCode) {
$raw = trim((string) $skuCode);
if ($raw === '') {
continue;
}
$upper = mb_strtoupper($raw, 'UTF-8');
$lower = mb_strtolower($raw, 'UTF-8');
foreach ([$raw, $upper, $lower] as $value) {
$lookupValues[] = $value;
$lookupValues[] = str_replace('+', '_X002B_', $value);
$lookupValues[] = str_replace(['_X002B_', '_x002b_'], '+', $value);
}
}
$lookupValues = array_values(array_unique(array_filter(
$lookupValues,
static fn (string $value): bool => $value !== '',
)));
if ($lookupValues === []) {
return [];
}
$productTable = $this->dataset()->targetTable();
$query = $this->connection->table($productTable)
->where('sku_type', 'normal')
->whereIn('sku_id', $lookupValues)
->select([
'autoid',
'sku_id',
'brand',
'category',
'supplier_name',
'enabled',
]);
if (Schema::connection($this->connection->getName())->hasTable('product_catalog_exclusions')) {
$normalizedSql = "REPLACE(UPPER(TRIM({$productTable}.sku_id)), '_X002B_', '+')";
$query->whereNotExists(static function ($query) use ($productTable, $normalizedSql): void {
$query->selectRaw('1')
->from('product_catalog_exclusions as product_exclusions')
->whereColumn('product_exclusions.mirror_key', "{$productTable}._mirror_key")
->whereRaw("product_exclusions.sku_id_normalized = {$normalizedSql}");
});
}
return $query
->orderByDesc('autoid')
->get()
->each(static function (object $row): void {
$normalized = mb_strtoupper((string) ($row->sku_id ?? ''), 'UTF-8');
$row->_sku_attribute_key = str_replace('_X002B_', '+', $normalized);
})
->all();
}
/**
* @param array<string,mixed> $filters
* @return Generator<int,object>

View File

@ -42,6 +42,21 @@ class SupplierFreeShippingStore
return $row;
}
/**
* @param list<int> $supplierIds
* @return array<int,bool>
*/
public function flagsBySupplierIds(array $supplierIds, int $companyId): array
{
$values = $this->values($companyId);
$flags = [];
foreach (array_unique(array_filter($supplierIds, static fn (int $id): bool => $id > 0)) as $supplierId) {
$flags[$supplierId] = (bool) ($values[$this->key($supplierId)][self::FIELD] ?? false);
}
return $flags;
}
/** @return array{created:int,updated:int} */
public function save(int $supplierId, bool $isFreeShipping, int $companyId, ?int $userId, string $source = 'manual'): array
{

View File

@ -43,6 +43,10 @@
'online_order_no' => '线上单号',
'warehouse' => '发货仓库',
'warehouse_short_name' => '仓库简称',
'brand' => '品牌',
'category' => '类目',
'supplier_name' => '供应商',
'free_shipping_manufacturer' => '是否包邮厂家',
'product_code' => '商品编码',
'product_quantity' => '商品数量',
'unit_price' => '商品单价',
@ -562,7 +566,7 @@
.product-cost-table {
width: 100%;
min-width: 84rem;
min-width: 112rem;
border-collapse: separate;
border-spacing: 0;
font-size: .75rem;
@ -1305,7 +1309,7 @@
id="product-cost-table"
aria-label="商品成本明细"
data-product-cost-table-card
data-storage-key="product-cost-columns:{{ auth()->id() }}"
data-storage-key="product-cost-columns:v2:{{ auth()->id() }}"
>
<div class="product-cost-table-toolbar">
<label class="sr-only" for="product-cost-page-search">搜索当前页商品成本数据</label>
@ -1351,6 +1355,10 @@
<th data-column-key="online_order_no">线上单号</th>
<th data-column-key="warehouse">发货仓库</th>
<th data-column-key="warehouse_short_name">仓库简称</th>
<th data-column-key="brand">品牌</th>
<th data-column-key="category">类目</th>
<th data-column-key="supplier_name">供应商</th>
<th data-column-key="free_shipping_manufacturer">是否包邮厂家</th>
<th data-column-key="product_code">商品编码</th>
<th class="num" data-column-key="product_quantity">商品数量</th>
<th class="num" data-column-key="unit_price">商品单价</th>
@ -1366,6 +1374,10 @@
<td data-column-key="online_order_no">{{ $text($row->online_order_no) }}</td>
<td data-column-key="warehouse">{{ $text($row->warehouse) }}</td>
<td data-column-key="warehouse_short_name" class="{{ $warehouseMissing($row->product_code, $row->warehouse_short_name) ? 'missing' : '' }}">{{ $text($row->warehouse_short_name) }}</td>
<td data-column-key="brand">{{ $text($row->brand) }}</td>
<td data-column-key="category">{{ $text($row->category) }}</td>
<td data-column-key="supplier_name">{{ $text($row->supplier_name) }}</td>
<td data-column-key="free_shipping_manufacturer">{{ $row->free_shipping_manufacturer === true ? '包邮' : '-' }}</td>
<td data-column-key="product_code">{{ $text($row->product_code) }}</td>
<td class="num" data-column-key="product_quantity">{{ $qty($row->product_quantity) }}</td>
<td class="num {{ $row->unit_price === null ? 'missing' : '' }}" data-column-key="unit_price">{{ $money($row->unit_price) }}</td>
@ -1373,7 +1385,7 @@
</tr>
@empty
<tr>
<td colspan="10">
<td colspan="14">
<div class="product-cost-empty">
{{ $error ? '镜像读取失败,请稍后重试。' : '暂无符合条件的商品成本数据;生成完成后会自动显示。' }}
</div>
@ -1381,7 +1393,7 @@
</tr>
@endforelse
<tr class="product-cost-search-empty" data-product-cost-search-empty hidden>
<td colspan="10">当前页没有匹配的数据。</td>
<td colspan="14">当前页没有匹配的数据。</td>
</tr>
</tbody>
</table>

View File

@ -18,6 +18,10 @@ class ProductCostPageLayoutTest extends TestCase
'online_order_no' => 'ORDER-1',
'warehouse' => '简尚-崔桥工厂仓',
'warehouse_short_name' => '崔桥工厂仓',
'brand' => '测试品牌',
'category' => '测试类目',
'supplier_name' => '测试供应商',
'free_shipping_manufacturer' => true,
'product_code' => 'SKU-1',
'product_quantity' => 1,
'unit_price' => 10,
@ -96,6 +100,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('搜索当前页数据', $html);
$this->assertStringContainsString('列设置', $html);
$this->assertStringContainsString('全部筛选结果', $html);
@ -106,6 +111,14 @@ class ProductCostPageLayoutTest extends TestCase
strpos($html, 'data-column-key="platform">平台')
);
$this->assertStringContainsString('data-column-key="platform">京东账单</td>', $html);
$this->assertLessThan(
strpos($html, 'data-column-key="product_code">商品编码'),
strpos($html, 'data-column-key="brand">品牌')
);
$this->assertStringContainsString('data-column-key="brand">测试品牌</td>', $html);
$this->assertStringContainsString('data-column-key="category">测试类目</td>', $html);
$this->assertStringContainsString('data-column-key="supplier_name">测试供应商</td>', $html);
$this->assertStringContainsString('data-column-key="free_shipping_manufacturer">包邮</td>', $html);
$this->assertStringContainsString('导出当前筛选结果', $html);
}
}

View File

@ -0,0 +1,130 @@
<?php
namespace Tests\Feature\Business;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Modules\EcommerceFinance\Repositories\ProductCatalogMirrorRepository;
use Modules\EcommerceFinance\Repositories\SupplierManagementMirrorRepository;
use Modules\EcommerceFinance\Services\SupplierFreeShippingStore;
use Tests\Feature\FeatureTestCase;
class ProductCostProductAttributesTest extends FeatureTestCase
{
public function test_product_cost_rows_are_enriched_from_catalog_and_supplier_management(): void
{
$mirror = DB::connection('business_mirror');
$this->createMirrorTables();
$this->markReady(ProductCatalogMirrorRepository::DATASET_KEY, 'operations_replica', 'rpt.jst_sku', 'ops_jst_sku');
$this->markReady(SupplierManagementMirrorRepository::DATASET, 'jiansun', 'dbo.js_supplier_View', 'js_supplier_management');
$mirror->table('store_receipt_product_cost_rows')->insert([
'report_month' => '2026-09-01',
'row_key' => 'attribute-row',
'platform' => '京东账单',
'occurred_date' => '2026-09-01',
'store_name' => '京东-HX旗舰店101',
'online_order_no' => 'ORDER-ATTRIBUTE',
'warehouse' => '简尚-崔桥工厂仓',
'warehouse_short_name' => '崔桥工厂仓',
'product_code' => 'SKU-ATTRIBUTE',
'product_quantity' => 1,
'unit_price' => 10,
'product_cost' => 10,
'remark' => null,
'imported_at' => now(),
]);
$mirror->table('ops_jst_sku')->insert([
'autoid' => 1001,
'sku_id' => 'SKU-ATTRIBUTE',
'sku_type' => 'normal',
'brand' => '测试品牌',
'category' => '测试类目',
'supplier_name' => '测试供应商',
'enabled' => 1,
]);
$mirror->table('js_supplier_management')->insert([
'Id' => 2001,
'scmcode' => 'N2001',
'scmname' => '测试供应商',
]);
app(SupplierFreeShippingStore::class)->save(
2001,
true,
(int) $this->company->id,
(int) $this->user->id,
);
$response = $this->loginAs()->get(route('business.pages.show', [
'section' => 'financial-operations',
'page' => 'product-costs',
'month' => '2026-09',
]));
$response
->assertOk()
->assertSee('测试品牌')
->assertSee('测试类目')
->assertSee('测试供应商')
->assertSee('包邮');
}
private function createMirrorTables(): void
{
$schema = Schema::connection('business_mirror');
if (! $schema->hasTable('business_mirror_table_states')) {
$schema->create('business_mirror_table_states', function (Blueprint $table): void {
$table->string('dataset_key')->primary();
$table->string('source_key');
$table->string('source_object');
$table->string('target_table');
$table->string('status')->default('pending');
$table->dateTime('initial_completed_at')->nullable();
$table->dateTime('last_succeeded_at')->nullable();
$table->unsignedBigInteger('mirror_row_count')->default(0);
$table->timestamps();
});
}
if (! $schema->hasTable('ops_jst_sku')) {
$schema->create('ops_jst_sku', function (Blueprint $table): void {
$table->unsignedBigInteger('autoid');
$table->string('sku_id')->nullable();
$table->string('sku_type')->nullable();
$table->string('brand')->nullable();
$table->string('category')->nullable();
$table->string('supplier_name')->nullable();
$table->integer('enabled')->nullable();
});
}
if (! $schema->hasTable('js_supplier_management')) {
$schema->create('js_supplier_management', function (Blueprint $table): void {
$table->unsignedBigInteger('Id')->primary();
$table->string('scmcode')->nullable();
$table->string('scmname')->nullable();
});
}
}
private function markReady(
string $datasetKey,
string $sourceKey,
string $sourceObject,
string $targetTable
): void {
DB::connection('business_mirror')->table('business_mirror_table_states')->updateOrInsert(
['dataset_key' => $datasetKey],
[
'source_key' => $sourceKey,
'source_object' => $sourceObject,
'target_table' => $targetTable,
'status' => 'succeeded',
'initial_completed_at' => now(),
'last_succeeded_at' => now(),
'mirror_row_count' => 1,
'created_at' => now(),
'updated_at' => now(),
],
);
}
}

View File

@ -23,6 +23,11 @@ class SupplierFreeShippingStoreTest extends FeatureTestCase
$this->assertTrue($rows[0]->free_shipping_manufacturer);
$this->assertFalse($rows[1]->free_shipping_manufacturer);
$this->assertFalse($rows[2]->free_shipping_manufacturer);
$this->assertSame([
9 => true,
11 => false,
12 => false,
], $store->flagsBySupplierIds([9, 11, 12], $companyId));
$otherCompanyRows = $store->decorateRows([(object) ['Id' => 9]], $companyId + 1);
$this->assertFalse($otherCompanyRows[0]->free_shipping_manufacturer);

View File

@ -72,6 +72,40 @@ class ProductCatalogMirrorRepositoryTest extends TestCase
$this->assertSame('succeeded', $this->repository->state()['status']);
}
public function test_it_finds_product_attributes_by_normalized_sku_code(): void
{
$this->markReady(3);
$this->insertProduct(10, [
'sku_id' => 'SKU-KEEP',
'brand' => '测试品牌',
'category' => '测试类目',
'supplier_name' => '测试供应商',
]);
$this->insertProduct(20, [
'sku_id' => 'CODE_X002B_PLUS',
'brand' => '加号品牌',
'category' => '加号类目',
'supplier_name' => '加号供应商',
]);
$this->insertProduct(30, [
'sku_type' => 'package',
'sku_id' => 'PACKAGE-SKU',
'brand' => '套餐品牌',
]);
$rows = $this->repository->normalProductsBySkuCodes([
'SKU-KEEP',
'code+plus',
'PACKAGE-SKU',
]);
$byKey = collect($rows)->keyBy('_sku_attribute_key');
$this->assertCount(2, $rows);
$this->assertSame('测试品牌', $byKey['SKU-KEEP']->brand);
$this->assertSame('加号供应商', $byKey['CODE+PLUS']->supplier_name);
$this->assertArrayNotHasKey('PACKAGE-SKU', $byKey->all());
}
public function test_it_applies_codes_keywords_status_supplier_and_price_filters(): void
{
$this->markReady(2);