fix(fulfillment): 收口渠道商品与统一结算边界

This commit is contained in:
yml2213
2026-11-06 17:12:44 +08:00
parent e6b3835c9f
commit a333c05df4
23 changed files with 1113 additions and 106 deletions
@@ -1,3 +1,5 @@
import type { PoolClient } from 'pg'
import { query } from '../../db/client.js'
import { nowIso } from '../../utils/time.js'
@@ -19,6 +21,7 @@ export const COST_EXCEPTION_REASONS = [
'cost_missing',
'manual_config_missing',
'manual_cost_missing',
'on_account_cost_pending',
'carrier_missing',
] as const
@@ -29,14 +32,16 @@ export type UpsertExceptionInput = {
scopeKey: string
orderItemId: number
detail?: Record<string, unknown>
client?: Pick<PoolClient, 'query'>
}
/** 幂等上浮一条聚合问题:已存在则累加明细并刷新 last_seen。 */
export async function upsertAggregatedException(input: UpsertExceptionInput): Promise<void> {
const now = nowIso()
const detail = JSON.stringify(input.detail || {})
const run = input.client ? input.client.query.bind(input.client) : query
const result = await query<{ id: number }>(
const result = await run<{ id: number }>(
`
INSERT INTO cost_exceptions (
subject_type, subject_id, order_item_id, reason, status, detail_json,
@@ -55,7 +60,7 @@ export async function upsertAggregatedException(input: UpsertExceptionInput): Pr
const exceptionId = result.rows[0]?.id
if (!exceptionId) return
await query(
await run(
`
INSERT INTO cost_exception_items (exception_id, order_item_id, created_at)
VALUES ($1, $2, $3)
@@ -64,7 +69,7 @@ export async function upsertAggregatedException(input: UpsertExceptionInput): Pr
[exceptionId, input.orderItemId, now],
)
await query(
await run(
`
UPDATE cost_exceptions ce
SET item_count = (
@@ -468,6 +468,26 @@ export async function saveManualFulfillmentConfig(payload: JsonObject) {
const existingId = Number(existing.rows[0]?.id || 0)
let resolvedProductId = canonicalProductId
if (resolvedProductId) {
const product = await client.query<{ canonical_sku: string; status: string }>(
`SELECT canonical_sku, status
FROM product_catalog
WHERE id = $1
LIMIT 1`,
[resolvedProductId],
)
if (
!product.rows[0] ||
product.rows[0].status !== 'active' ||
!String(product.rows[0].canonical_sku || '').startsWith('man:')
) {
throw createHttpError('人工履约配置只能关联有效的 man: 标准商品', {
statusCode: 400,
errorCode: 'manual_config_product_source_invalid',
})
}
}
// 人工配置本身就是该 SKU 的标准商品声明。没有显式关联时自动创建/复用
// man:<内部 SKU>,避免运营再去「标准商品」手工建一次。
if (!resolvedProductId) {
@@ -1,4 +1,5 @@
import assert from 'node:assert/strict'
import { readFile } from 'node:fs/promises'
import test from 'node:test'
import {
@@ -63,9 +64,11 @@ function item(patch: Record<string, unknown> = {}) {
sku_name: '任意',
normalized_sku_name: null as string | null,
normalized_sku_series: null as string | null,
fulfillment_channel: 'work_order' as string | null,
fulfillment_channel: null as string | null,
canonical_product_id: null as number | null,
work_rule_key: null as string | null,
manual_config_product_id: null as number | null,
manual_config_product_sku: null as string | null,
...patch,
}
}
@@ -123,6 +126,7 @@ test('商品归一:人工渠道直接使用配置里指定的商品', () => {
fulfillment_channel: 'manual',
sku_code: 'unknown',
manual_config_product_id: 44,
manual_config_product_sku: 'man:配置商品',
}),
index,
),
@@ -157,11 +161,52 @@ test('商品归一:第三方卡券缺少 tpv 商品时不能串到同名人工
)
})
test('商品归一:其他已确定渠道也不能借用同名其他来源商品', () => {
for (const fulfillmentChannel of ['manual', 'on_account', 'affiliate_dash', 'work_order']) {
assert.equal(
resolveProductId(
item({
fulfillment_channel: fulfillmentChannel,
sku_code: 'unknown',
internal_sku: '套装-测试',
}),
index,
),
null,
)
}
})
test('商品归一:人工配置也只能挂载 man: 商品', () => {
assert.equal(
resolveProductId(
item({
fulfillment_channel: 'manual',
manual_config_product_id: 99,
manual_config_product_sku: 'aff:错误商品',
}),
index,
),
null,
)
assert.equal(
resolveProductId(
item({
fulfillment_channel: 'on_account',
manual_config_product_id: 99,
manual_config_product_sku: 'man:正确商品',
}),
index,
),
99,
)
})
test('商品归一:中文内部 SKU 命中标准商品,不依赖平台 SKU', () => {
assert.equal(
resolveProductId(
item({
fulfillment_channel: 'affiliate_dash',
fulfillment_channel: null,
sku_code: 'unknown',
internal_sku: '套装-测试',
}),
@@ -191,3 +236,14 @@ test('三方卡券自动建商品时优先使用内部中文 SKU', () => {
assert.equal(voucherCanonicalSku({ manual_sku_key: '', sku_name: '', sku_code: 'x' }), null)
assert.equal(voucherCanonicalSku({}), null)
})
test('商品归一扫描会纠正所有渠道的错误来源商品', async () => {
const source = await readFile(new URL('./product-normalize-service.ts', import.meta.url), 'utf8')
assert.ok(source.includes("current_product.canonical_sku NOT LIKE 'aff:%'"))
assert.ok(source.includes("current_product.canonical_sku NOT LIKE 'man:%'"))
assert.ok(source.includes("current_product.canonical_sku NOT LIKE 'tpl:%'"))
assert.ok(source.includes("current_product.canonical_sku NOT LIKE 'tpv:%'"))
assert.ok(source.includes('canonicalProductId: null'))
assert.ok(source.includes('onlyWhenCanonicalProductDifferent: true'))
})
@@ -3,7 +3,10 @@ import { resolveExceptionsForItems, upsertAggregatedException } from './cost-exc
import { readWatermarkItemId } from '../watermark-store.js'
import { upsertInternalSkuChannel } from '../fulfillment/internal-sku-channel-service.js'
import { canonicalizeInternalSku, containsCjk } from '../fulfillment/internal-sku-resolver.js'
import { attachFulfillmentConfigurations } from '../fulfillment/fulfillment-state-service.js'
import {
attachFulfillmentConfigurations,
transitionFulfillmentState,
} from '../fulfillment/fulfillment-state-service.js'
/**
* 管道 B:商品归一。
@@ -51,8 +54,10 @@ type ItemRow = {
normalized_sku_name: string | null
normalized_sku_series: string | null
fulfillment_channel: string | null
canonical_product_id?: number | null
work_rule_key: string | null
manual_config_product_id: number | null
manual_config_product_sku?: string | null
}
function key(...parts: string[]): string {
@@ -145,6 +150,17 @@ export function voucherCanonicalSku(item: {
return internal ? `tpv:${internal}` : null
}
async function clearMismatchedProduct(item: ItemRow) {
if (!item.fulfillment_channel || !item.canonical_product_id) return
await transitionFulfillmentState({
orderItemId: Number(item.id),
expected: { status: 'assigned' },
patch: { canonicalProductId: null },
eventType: 'product_source_cleared',
reason: `渠道 ${item.fulfillment_channel} 与当前标准商品来源不一致`,
})
}
/**
* 三方卡券没有预先建库时,按内部 SKU 自动建 `tpv:` 商品并补渠道规则。
* 建完后该商品会出现在「商品与成本中心 → 第三方卡券」,运营直接设采购价。
@@ -225,20 +241,23 @@ export function resolveProductId(item: ItemRow, index: MappingIndex): number | n
const seriesKey = String(item.normalized_sku_series || '').trim()
const internalSku = canonicalizeInternalSku(item.internal_sku || item.manual_sku_key)
// 人工渠道:配置里已经指定商品,直接用,不需要再建映射。
if (item.fulfillment_channel === 'manual' && item.manual_config_product_id) {
return Number(item.manual_config_product_id)
// 已确定渠道必须命中本渠道商品,不能借用同名的其他来源商品。
if (item.fulfillment_channel === 'manual' || item.fulfillment_channel === 'on_account') {
return item.manual_config_product_id &&
String(item.manual_config_product_sku || '').startsWith('man:')
? Number(item.manual_config_product_id)
: null
}
// 接单平台:模板即商品来源(tpl:<rule_key>),无需渠道映射。
if (item.fulfillment_channel === 'work_order' && item.work_rule_key) {
if (item.fulfillment_channel === 'work_order') {
if (!item.work_rule_key) return null
const templateProduct = index.templateRules.get(String(item.work_rule_key).trim())
if (templateProduct) return templateProduct
return templateProduct || null
}
if (item.fulfillment_channel === 'affiliate_dash' && skuCode) {
const aff = index.affSkus.get(skuCode)
if (aff) return aff
if (item.fulfillment_channel === 'affiliate_dash') {
return skuCode ? index.affSkus.get(skuCode) || null : null
}
// 第三方卡券:与自动发货同构,商品编码 tpv:<sku>。
@@ -325,13 +344,16 @@ export async function normalizeOrderItemProducts(
oi.normalized_sku_name,
oi.normalized_sku_series,
oi.fulfillment_channel,
oi.canonical_product_id,
wpr.rule_key AS work_rule_key,
cfg.canonical_product_id AS manual_config_product_id
cfg.canonical_product_id AS manual_config_product_id,
cfg_product.canonical_sku AS manual_config_product_sku
FROM order_items oi
JOIN orders o ON o.id = oi.order_id
LEFT JOIN work_orders wo ON wo.order_item_id = oi.id AND wo.status <> 'cancelled'
LEFT JOIN work_product_rules wpr ON wpr.id = wo.product_rule_id
LEFT JOIN manual_fulfillment_configs cfg ON cfg.id = oi.fulfillment_config_id
LEFT JOIN product_catalog cfg_product ON cfg_product.id = cfg.canonical_product_id
LEFT JOIN product_catalog current_product ON current_product.id = oi.canonical_product_id
WHERE oi.fulfillment_status = 'assigned'
AND (
@@ -343,6 +365,30 @@ export async function normalizeOrderItemProducts(
OR current_product.canonical_sku NOT LIKE 'tpv:%'
)
)
OR (
oi.fulfillment_channel = 'affiliate_dash'
AND (
current_product.id IS NULL
OR current_product.canonical_sku NOT LIKE 'aff:%'
)
)
OR (
oi.fulfillment_channel IN ('manual', 'on_account')
AND (
current_product.id IS NULL
OR current_product.canonical_sku NOT LIKE 'man:%'
)
)
OR (
oi.fulfillment_channel = 'work_order'
AND (
current_product.id IS NULL
OR (
current_product.canonical_sku NOT LIKE 'tpl:%'
AND current_product.canonical_sku NOT LIKE 'wo:%'
)
)
)
)
AND oi.id > $1
ORDER BY oi.id
@@ -369,6 +415,7 @@ export async function normalizeOrderItemProducts(
}
if (!productId) {
result.unmatched += 1
await clearMismatchedProduct(item)
await upsertAggregatedException({
reason: 'product_mapping_missing',
scopeKey: `product_mapping_missing|-|-|${canonicalizeInternalSku(item.internal_sku || item.manual_sku_key || item.sku_code)}|${item.fulfillment_channel || '-'}`,
@@ -487,13 +534,16 @@ export async function normalizeProductsForItems(itemIds: number[]): Promise<{
oi.normalized_sku_name,
oi.normalized_sku_series,
oi.fulfillment_channel,
oi.canonical_product_id,
wpr.rule_key AS work_rule_key,
cfg.canonical_product_id AS manual_config_product_id
cfg.canonical_product_id AS manual_config_product_id,
cfg_product.canonical_sku AS manual_config_product_sku
FROM order_items oi
JOIN orders o ON o.id = oi.order_id
LEFT JOIN work_orders wo ON wo.order_item_id = oi.id AND wo.status <> 'cancelled'
LEFT JOIN work_product_rules wpr ON wpr.id = wo.product_rule_id
LEFT JOIN manual_fulfillment_configs cfg ON cfg.id = oi.fulfillment_config_id
LEFT JOIN product_catalog cfg_product ON cfg_product.id = cfg.canonical_product_id
LEFT JOIN product_catalog current_product ON current_product.id = oi.canonical_product_id
WHERE oi.fulfillment_status = 'assigned'
AND (
@@ -505,6 +555,30 @@ export async function normalizeProductsForItems(itemIds: number[]): Promise<{
OR current_product.canonical_sku NOT LIKE 'tpv:%'
)
)
OR (
oi.fulfillment_channel = 'affiliate_dash'
AND (
current_product.id IS NULL
OR current_product.canonical_sku NOT LIKE 'aff:%'
)
)
OR (
oi.fulfillment_channel IN ('manual', 'on_account')
AND (
current_product.id IS NULL
OR current_product.canonical_sku NOT LIKE 'man:%'
)
)
OR (
oi.fulfillment_channel = 'work_order'
AND (
current_product.id IS NULL
OR (
current_product.canonical_sku NOT LIKE 'tpl:%'
AND current_product.canonical_sku NOT LIKE 'wo:%'
)
)
)
)
AND oi.id = ANY($1::bigint[])
`,
@@ -519,6 +593,7 @@ export async function normalizeProductsForItems(itemIds: number[]): Promise<{
}
if (!productId) {
unmatched += 1
await clearMismatchedProduct(item)
await upsertAggregatedException({
reason: 'product_mapping_missing',
scopeKey: `product_mapping_missing|-|-|${canonicalizeInternalSku(item.internal_sku || item.manual_sku_key || item.sku_code)}|${item.fulfillment_channel || '-'}`,