优化寄售仓库现货统计与可匹配矩阵

This commit is contained in:
2026-11-22 15:20:25 +08:00
parent dbf3c9daf1
commit f5ef500708
8 changed files with 913 additions and 22 deletions
@@ -0,0 +1,209 @@
/**
* 寄售仓库统计口径集成测试(仅隔离库)。
*
* 运行:
* CONSIGNMENT_MATCHING_TEST_DATABASE_URL=postgres://.../order_site_ctest \
* DATABASE_URL=postgres://.../order_site_ctest \
* node --import tsx --test src/repositories/worker-platform/consignment-inventory-stats.integration.test.ts
*/
import assert from 'node:assert/strict'
import test from 'node:test'
import { closeDb, query } from '../../db/client.js'
import { resolveIntegrationDatabaseOrThrow } from '../../test-support/integration-db-guard.js'
import { getConsignmentInventoryStats } from './consignment-repo.js'
const TEST_DATABASE_URL = String(process.env.CONSIGNMENT_MATCHING_TEST_DATABASE_URL || '').trim()
const suffix = `${Date.now().toString(36)}${Math.floor(Math.random() * 1000)}`
const statsDate = '2099-01-15'
const inventoryNos = [
`CSTATS-${suffix}-A`,
`CSTATS-${suffix}-B`,
`CSTATS-${suffix}-C`,
`CSTATS-${suffix}-D`,
`CSTATS-${suffix}-E`,
`CSTATS-${suffix}-F`,
]
async function insertInventory(input: {
inventoryNo: string
system: string
series: string
diamondLevel: number
brillianceCount: number
quantity: number
remainingQuantity: number
costPriceFen: number
status: 'in_stock' | 'consumed' | 'archived'
buyerName: string
specValuesJson: Record<string, string>
allowMatching?: boolean
}) {
await query(
`
INSERT INTO consignment_inventories (
inventory_no, item_name, system, server_zone, series, diamond_level,
brilliance_count, cost_price_fen, buyer_name, inbound_batch,
quantity, remaining_quantity, sale_price_fen, listed_at,
spec_values_json, status, source_type, inbound_at, created_at, updated_at,
allow_matching
) VALUES (
$1, $2, $3, '互通', $4, $5,
$6, $7, $8, '统计测试',
$9, $10, $7, $11,
$12::jsonb, $13, 'manual', $11, $11, $11,
$14
)
`,
[
input.inventoryNo,
`${input.system}${input.series}${input.diamondLevel}钻 统计测试`,
input.system,
input.series,
input.diamondLevel,
input.brillianceCount,
input.costPriceFen,
input.buyerName,
input.quantity,
input.remainingQuantity,
`${statsDate}T12:00:00+08:00`,
JSON.stringify(input.specValuesJson),
input.status,
input.allowMatching ?? true,
],
)
}
test(
'寄售仓库统计:按剩余件数、成本乘数量,并按系统+系列+钻级汇总现货',
{
skip: TEST_DATABASE_URL ? false : '未设置 CONSIGNMENT_MATCHING_TEST_DATABASE_URL',
},
async () => {
assert(resolveIntegrationDatabaseOrThrow('CONSIGNMENT_MATCHING_TEST_DATABASE_URL'))
try {
await insertInventory({
inventoryNo: inventoryNos[0]!,
system: '苹果',
series: '暗潮',
diamondLevel: 2,
brillianceCount: 0,
quantity: 3,
remainingQuantity: 2,
costPriceFen: 100,
status: 'in_stock',
buyerName: '小明',
specValuesJson: { system: '苹果', series: '暗潮', diamondLevel: '2' },
})
await insertInventory({
inventoryNo: inventoryNos[1]!,
system: '苹果',
series: '暗潮',
diamondLevel: 2,
brillianceCount: 2,
quantity: 1,
remainingQuantity: 1,
costPriceFen: 100,
status: 'in_stock',
buyerName: '小明',
specValuesJson: { system: '苹果', series: '暗潮', diamondLevel: '2' },
})
await insertInventory({
inventoryNo: inventoryNos[2]!,
system: '安卓',
series: '怒嚎',
diamondLevel: 3,
brillianceCount: 5,
quantity: 2,
remainingQuantity: 2,
costPriceFen: 200,
status: 'in_stock',
buyerName: '小红',
specValuesJson: { system: '安卓', series: '怒嚎', diamondLevel: '3' },
})
await insertInventory({
inventoryNo: inventoryNos[3]!,
system: '苹果',
series: '暗潮',
diamondLevel: 2,
brillianceCount: 1,
quantity: 4,
remainingQuantity: 0,
costPriceFen: 100,
status: 'consumed',
buyerName: '小明',
specValuesJson: { system: '苹果', series: '暗潮', diamondLevel: '2' },
})
await insertInventory({
inventoryNo: inventoryNos[4]!,
system: '苹果',
series: '暗潮',
diamondLevel: 2,
brillianceCount: 0,
quantity: 2,
remainingQuantity: 0,
costPriceFen: 100,
status: 'archived',
buyerName: '小明',
specValuesJson: { system: '苹果', series: '暗潮', diamondLevel: '2' },
})
// 历史库存没有动态规格值:统计必须回退旧列,不能丢货。
await insertInventory({
inventoryNo: inventoryNos[5]!,
system: '苹果',
series: '暗潮',
diamondLevel: 2,
brillianceCount: 0,
quantity: 1,
remainingQuantity: 1,
costPriceFen: 50,
status: 'in_stock',
buyerName: '小明',
specValuesJson: {},
allowMatching: false,
})
const stats = await getConsignmentInventoryStats({
dateFrom: statsDate,
dateTo: statsDate,
})
assert.equal(
stats.totalInStockCount,
6,
'顶部在库数量必须按全部在库 remaining_quantity 汇总,不排除禁止匹配库存',
)
assert.equal(
stats.totalInStockCostFen,
750,
'顶部在库成本必须按 单价 × 剩余数量 汇总,不排除禁止匹配库存',
)
assert.equal(stats.totalConsumedCount, 4, '已出库数量必须按 quantity 汇总')
assert.equal(stats.totalConsumedCostFen, 400, '已出库成本必须按 单价 × quantity 汇总')
assert.deepEqual(stats.byStockSpec, [
{ system: '苹果', series: '暗潮', diamond_level: 2, quantity: 3 },
{ system: '安卓', series: '怒嚎', diamond_level: 3, quantity: 2 },
])
const buyer = stats.byBuyer.find((item) => item.buyer_name === '小明')
assert.equal(buyer?.count, 4, '收购人分布展示全部当前在库件数')
assert.equal(buyer?.total_cost_fen, 350, '收购人成本按剩余数量计算')
assert.equal(buyer?.consumed_count, 4, '收购人已出库件数按 quantity 计算')
const appleOnly = await getConsignmentInventoryStats({
dateFrom: statsDate,
dateTo: statsDate,
specFilters: [{ key: 'system', value: '苹果' }],
})
assert.equal(appleOnly.totalInStockCount, 4)
assert.deepEqual(appleOnly.byStockSpec, [
{ system: '苹果', series: '暗潮', diamond_level: 2, quantity: 3 },
])
} finally {
await query('DELETE FROM consignment_inventories WHERE inventory_no = ANY($1::text[])', [
inventoryNos,
])
await closeDb().catch(() => undefined)
}
},
)
@@ -166,6 +166,13 @@ export type ConsignmentStatsSummary = {
byShop: Array<{ shop_name: string; count: number }>
byBatch: Array<{ inbound_batch: string; count: number; total_cost_fen: number }>
bySeries: Array<{ series: string; diamond_level: number; count: number }>
/** 现货分布:system + series + diamondLevel -> 剩余可匹配件数;璀璨数不参与分组。 */
byStockSpec: Array<{
system: string
series: string
diamond_level: number
quantity: number
}>
}
/** 寄售仓库按寄卖配置动态规格筛选:key 走白名单,值一律参数绑定。 */
@@ -448,10 +455,24 @@ export async function getConsignmentInventoryStats(
const totalsSql = `
SELECT
COALESCE(SUM(CASE WHEN ci.status = 'in_stock' THEN 1 ELSE 0 END), 0)::integer AS in_stock_count,
COALESCE(SUM(CASE WHEN ci.status = 'in_stock' THEN ci.cost_price_fen ELSE 0 END), 0)::integer AS in_stock_cost_fen,
COALESCE(SUM(CASE WHEN ci.status = 'consumed' THEN 1 ELSE 0 END), 0)::integer AS consumed_count,
COALESCE(SUM(CASE WHEN ci.status = 'consumed' THEN ci.cost_price_fen ELSE 0 END), 0)::integer AS consumed_cost_fen
COALESCE(SUM(
CASE WHEN ci.status = 'in_stock' THEN GREATEST(ci.remaining_quantity, 0) ELSE 0 END
), 0)::integer AS in_stock_count,
COALESCE(SUM(
CASE WHEN ci.status = 'in_stock'
THEN ci.cost_price_fen::bigint * GREATEST(ci.remaining_quantity, 0)
ELSE 0
END
), 0)::integer AS in_stock_cost_fen,
COALESCE(SUM(
CASE WHEN ci.status = 'consumed' THEN GREATEST(ci.quantity, 0) ELSE 0 END
), 0)::integer AS consumed_count,
COALESCE(SUM(
CASE WHEN ci.status = 'consumed'
THEN ci.cost_price_fen::bigint * GREATEST(ci.quantity, 0)
ELSE 0
END
), 0)::integer AS consumed_cost_fen
FROM consignment_inventories ci
${whereWith()}
`
@@ -471,12 +492,24 @@ export async function getConsignmentInventoryStats(
const buyerSql = `
SELECT
COALESCE(NULLIF(ci.buyer_name, ''), '未知') AS buyer_name,
COUNT(*)::integer AS count,
SUM(ci.cost_price_fen)::integer AS total_cost_fen,
COUNT(CASE WHEN ci.status = 'consumed' THEN 1 END)::integer AS consumed_count
COALESCE(SUM(
CASE WHEN ci.status = 'in_stock' THEN GREATEST(ci.remaining_quantity, 0) ELSE 0 END
), 0)::integer AS count,
COALESCE(SUM(
CASE WHEN ci.status = 'in_stock'
THEN ci.cost_price_fen::bigint * GREATEST(ci.remaining_quantity, 0)
ELSE 0
END
), 0)::integer AS total_cost_fen,
COALESCE(SUM(
CASE WHEN ci.status = 'consumed' THEN GREATEST(ci.quantity, 0) ELSE 0 END
), 0)::integer AS consumed_count
FROM consignment_inventories ci
${whereWith()}
${whereWith(`ci.status IN ('in_stock', 'consumed')`)}
GROUP BY ci.buyer_name
HAVING SUM(
CASE WHEN ci.status = 'in_stock' THEN GREATEST(ci.remaining_quantity, 0) ELSE 0 END
) > 0
ORDER BY count DESC
LIMIT 20
`
@@ -490,7 +523,7 @@ export async function getConsignmentInventoryStats(
const shopSql = `
SELECT
COALESCE(NULLIF(ci.shop_name, ''), '其他') AS shop_name,
COUNT(*)::integer AS count
COALESCE(SUM(GREATEST(ci.quantity, 0)), 0)::integer AS count
FROM consignment_inventories ci
${whereWith(`ci.status = 'consumed'`, `ci.shop_name <> ''`)}
GROUP BY ci.shop_name
@@ -502,10 +535,12 @@ export async function getConsignmentInventoryStats(
const batchSql = `
SELECT
COALESCE(NULLIF(ci.inbound_batch, ''), '未分类') AS inbound_batch,
COUNT(*)::integer AS count,
SUM(ci.cost_price_fen)::integer AS total_cost_fen
COALESCE(SUM(GREATEST(ci.remaining_quantity, 0)), 0)::integer AS count,
COALESCE(SUM(
ci.cost_price_fen::bigint * GREATEST(ci.remaining_quantity, 0)
), 0)::integer AS total_cost_fen
FROM consignment_inventories ci
${whereWith()}
${whereWith(`ci.status = 'in_stock'`)}
GROUP BY ci.inbound_batch
ORDER BY count DESC
LIMIT 20
@@ -519,7 +554,7 @@ export async function getConsignmentInventoryStats(
SELECT
COALESCE(NULLIF(ci.series, ''), '未注明') AS series,
ci.diamond_level,
COUNT(*)::integer AS count
COALESCE(SUM(GREATEST(ci.remaining_quantity, 0)), 0)::integer AS count
FROM consignment_inventories ci
${whereWith(`ci.status = 'in_stock'`)}
GROUP BY ci.series, ci.diamond_level
@@ -531,6 +566,37 @@ export async function getConsignmentInventoryStats(
values,
)
const stockSpecSql = `
SELECT
COALESCE(
NULLIF(BTRIM(ci.spec_values_json ->> 'system'), ''),
NULLIF(BTRIM(ci.system), ''),
'未注明'
) AS system,
COALESCE(
NULLIF(BTRIM(ci.spec_values_json ->> 'series'), ''),
NULLIF(BTRIM(ci.series), ''),
'未注明'
) AS series,
CASE
WHEN BTRIM(COALESCE(ci.spec_values_json ->> 'diamondLevel', '')) ~ '^[0-9]+$'
THEN BTRIM(ci.spec_values_json ->> 'diamondLevel')::integer
ELSE ci.diamond_level
END AS diamond_level,
COALESCE(SUM(GREATEST(ci.remaining_quantity, 0)), 0)::integer AS quantity
FROM consignment_inventories ci
${whereWith(`ci.status = 'in_stock'`, `ci.allow_matching = TRUE`, `ci.remaining_quantity > 0`)}
GROUP BY 1, 2, 3
ORDER BY quantity DESC, system ASC, series ASC, diamond_level ASC
LIMIT 100
`
const stockSpecRes = await query<{
system: string
series: string
diamond_level: number
quantity: number
}>(stockSpecSql, values)
return {
totalInStockCount: totals.in_stock_count,
totalInStockCostFen: totals.in_stock_cost_fen,
@@ -540,6 +606,7 @@ export async function getConsignmentInventoryStats(
byShop: shopRes.rows,
byBatch: batchRes.rows,
bySeries: seriesRes.rows,
byStockSpec: stockSpecRes.rows,
}
}
@@ -210,3 +210,33 @@ test('筛选项排序:苏尔南手枪固定排第一,其余保持配置顺
['苏尔南手枪', '密钥', '其它'],
)
})
test('现货统计:按 remaining_quantity 汇总,成本乘数量,并输出系统+系列+钻级汇总', async () => {
const source = await readFile(
new URL('../../repositories/worker-platform/consignment-repo.ts', import.meta.url),
'utf8',
)
const totalsSql = source.slice(
source.indexOf('const totalsSql'),
source.indexOf('const buyerSql'),
)
assert.ok(!totalsSql.includes('ci.allow_matching'), '顶部在库统计保持全部在库口径')
assert.ok(totalsSql.includes('GREATEST(ci.remaining_quantity, 0)'), '在库件数必须按剩余数量')
assert.ok(
totalsSql.includes('ci.cost_price_fen::bigint * GREATEST(ci.remaining_quantity, 0)'),
'在库成本必须乘剩余数量',
)
assert.ok(source.includes('byStockSpec: stockSpecRes.rows'), '统计结果必须返回现货分布字段')
const stockSpecSql = source.slice(
source.indexOf('const stockSpecSql'),
source.indexOf('const stockSpecRes'),
)
assert.ok(stockSpecSql.includes("ci.spec_values_json ->> 'system'"), '现货分布必须优先读动态规格')
assert.ok(stockSpecSql.includes("ci.spec_values_json ->> 'series'"), '现货分布必须优先读动态规格')
assert.ok(
stockSpecSql.includes("ci.spec_values_json ->> 'diamondLevel'"),
'现货分布必须优先读动态规格',
)
assert.ok(stockSpecSql.includes('ci.allow_matching = TRUE'), '现货分布必须只包含允许匹配的库存')
assert.ok(!stockSpecSql.includes('brillianceCount'), '璀璨数不参与分组')
})