refactor(finance)!: 事实维度与接口字段统一改名 channel

- migration 114 将 sales_daily_facts.fulfillment_mode 重命名为 channel
- DTO/查询参数/前端类型从 fulfillmentMode 统一为 channel
- 成本中心类型 FulfillmentMode 更名为 FulfillmentChannel,并补齐卡券/待分类/归档取值
- 销售事实响应分组改为 byChannel
This commit is contained in:
yml2213
2026-10-31 20:26:15 +08:00
parent 657e49f324
commit 6cd6401eca
38 changed files with 220 additions and 208 deletions
@@ -59,13 +59,23 @@ export const COST_MODEL_CODE_BASE: Record<string, string> = {
}
/** 履约渠道:唯一真源是 order_items.fulfillment_channel + fulfillment_status。 */
export type FulfillmentMode = 'work_order' | 'affiliate_dash' | 'legacy_platform' | 'manual'
export type FulfillmentChannel =
| 'work_order'
| 'affiliate_dash'
| 'third_party_voucher'
| 'manual'
| 'pending'
| 'archived'
| 'unclassified'
export const FULFILLMENT_MODES = new Set<string>([
export const FULFILLMENT_CHANNELS = new Set<string>([
'work_order',
'affiliate_dash',
'legacy_platform',
'third_party_voucher',
'manual',
'pending',
'archived',
'unclassified',
])
/**
@@ -4,7 +4,7 @@
* 把数据库行映射成接口 DTO,并提供「成本模型是否适用于履约方式」这类口径函数。
*/
import { GENERIC_COST_MODELS, PRODUCT_SOURCE_PREFIXES } from './cost-center-constants.js'
import type { FulfillmentMode } from './cost-center-constants.js'
import type { FulfillmentChannel } from './cost-center-constants.js'
import { parseJsonObject } from './cost-center-normalizers.js'
import type {
CostExceptionDraft,
@@ -49,12 +49,12 @@ export function productSourceFilterSql(paramIndex: number, column = 'p.canonical
* 专属模型只对对应履约方式生效;通用模型(平台费/支付费/售后损失/其他)
* 对所有履约方式生效。
*/
export function costModelAppliesTo(costModel: string, fulfillmentMode: string) {
export function costModelAppliesTo(costModel: string, channel: string) {
if ((GENERIC_COST_MODELS as readonly string[]).includes(costModel)) return true
if (costModel === 'affiliate_purchase') return fulfillmentMode === 'affiliate_dash'
if (costModel === 'work_order_reward') return fulfillmentMode === 'work_order'
if (costModel === 'third_party_voucher_cost') return fulfillmentMode === 'third_party_voucher'
if (costModel === 'manual_actual') return fulfillmentMode === 'manual'
if (costModel === 'affiliate_purchase') return channel === 'affiliate_dash'
if (costModel === 'work_order_reward') return channel === 'work_order'
if (costModel === 'third_party_voucher_cost') return channel === 'third_party_voucher'
if (costModel === 'manual_actual') return channel === 'manual'
return false
}
@@ -62,17 +62,17 @@ export function costModelAppliesTo(costModel: string, fulfillmentMode: string) {
* 成本模型适用范围的 SQL 片段。
* 参数是「履约方式」的 SQL 表达式(可以是占位符 $n,也可以是列引用)。
*/
export function costModelScopeSql(fulfillmentModeExpression: string): string {
export function costModelScopeSql(channelExpression: string): string {
return `(
ci.cost_model IN (${GENERIC_COST_MODELS.map((model) => `'${model}'`).join(', ')})
OR (ci.cost_model = 'affiliate_purchase'
AND ${fulfillmentModeExpression} = 'affiliate_dash')
AND ${channelExpression} = 'affiliate_dash')
OR (ci.cost_model = 'work_order_reward'
AND ${fulfillmentModeExpression} = 'work_order')
AND ${channelExpression} = 'work_order')
OR (ci.cost_model = 'third_party_voucher_cost'
AND ${fulfillmentModeExpression} = 'third_party_voucher')
AND ${channelExpression} = 'third_party_voucher')
OR (ci.cost_model = 'manual_actual'
AND ${fulfillmentModeExpression} = 'manual')
AND ${channelExpression} = 'manual')
)`
}
@@ -225,7 +225,7 @@ export function mapCostException(row: CostExceptionRow) {
subjectId: Number(row.subject_id),
orderItemId: row.order_item_id ? Number(row.order_item_id) : null,
workOrderId: row.work_order_id ? Number(row.work_order_id) : null,
fulfillmentMode: row.fulfillment_mode || '',
channel: row.channel || '',
reason: row.reason,
status: row.status,
detail: parseJsonObject(row.detail_json),
@@ -246,7 +246,7 @@ export type CostPreview = {
shopId: string
skuCode: string
skuName: string
fulfillmentMode: FulfillmentMode
channel: FulfillmentChannel
quantity: number
normalizedQuantity: number
revenueFen: number
@@ -1,7 +1,7 @@
/**
* 成本中心共享层 · 行结构与 DTO 类型。
*/
import type { CostModel, FulfillmentMode } from './cost-center-constants.js'
import type { CostModel, FulfillmentChannel } from './cost-center-constants.js'
// ---------------------------------------------------------------------------
// 行类型
@@ -135,7 +135,7 @@ export type CostExceptionRow = {
subject_id: number
order_item_id: number | null
work_order_id: number | null
fulfillment_mode: string | null
channel: string | null
reason: string
status: string
detail_json: unknown
@@ -161,7 +161,7 @@ export type OrderItemCostContext = {
basisAt: string
workOrderId: number | null
workProductRuleId: number | null
fulfillmentMode: FulfillmentMode
channel: FulfillmentChannel
}
export type CostLine = {
@@ -17,7 +17,7 @@ import {
COST_VERSION_SCOPES,
COST_VERSION_SOURCES,
COST_VERSION_STATUSES,
FULFILLMENT_MODES,
FULFILLMENT_CHANNELS,
PRICING_MODES,
PRODUCT_STATUSES,
assertKnownProvider,
@@ -73,10 +73,10 @@ export async function listAdminCostItems(payload: JsonObject = {}) {
clauses.push(`ci.status = $${params.length}`)
}
// 按履约方式筛选:只返回适用于该履约方式的成本模型。
const fulfillmentMode = text(payload.fulfillmentMode ?? payload.fulfillment_mode)
if (fulfillmentMode) {
assertOneOf(fulfillmentMode, FULFILLMENT_MODES, '履约方式无效')
params.push(fulfillmentMode)
const channel = text(payload.channel ?? payload.channel)
if (channel) {
assertOneOf(channel, FULFILLMENT_CHANNELS, '履约方式无效')
params.push(channel)
clauses.push(costModelScopeSql(`$${params.length}`))
}
@@ -283,10 +283,10 @@ export async function listAdminCostVersions(payload: JsonObject = {}) {
clauses.push(`ci.cost_model = $${params.length}`)
}
// 按履约方式筛选:只返回适用于该履约方式的成本模型。
const fulfillmentMode = text(payload.fulfillmentMode ?? payload.fulfillment_mode)
if (fulfillmentMode) {
assertOneOf(fulfillmentMode, FULFILLMENT_MODES, '履约方式无效')
params.push(fulfillmentMode)
const channel = text(payload.channel ?? payload.channel)
if (channel) {
assertOneOf(channel, FULFILLMENT_CHANNELS, '履约方式无效')
params.push(channel)
clauses.push(costModelScopeSql(`$${params.length}`))
}
const keyword = text(payload.keyword)
@@ -570,10 +570,10 @@ export async function listAdminCostExceptions(payload: JsonObject = {}) {
// 履约渠道筛选:异常表不存渠道,改为 join order_items 读 channel/status。
// 用 IN 半连接而不是 EXISTS:248k 异常 × 316k 订单项下,EXISTS 会逐行回表,
// 半连接能一次物化候选集合(实测 2.7s -> 0.4s)。
const fulfillmentMode = text(payload.fulfillmentMode ?? payload.fulfillment_mode)
if (fulfillmentMode) {
assertOneOf(fulfillmentMode, FULFILLMENT_MODES, '履约方式无效')
params.push(fulfillmentMode)
const channel = text(payload.channel ?? payload.channel)
if (channel) {
assertOneOf(channel, FULFILLMENT_CHANNELS, '履约方式无效')
params.push(channel)
clauses.push(
`ce.order_item_id IN (
SELECT oi.id FROM order_items oi WHERE COALESCE(oi.fulfillment_channel, CASE WHEN oi.fulfillment_status = 'archived' THEN 'archived' ELSE 'pending' END) = $${params.length}
@@ -591,7 +591,7 @@ export async function listAdminCostExceptions(payload: JsonObject = {}) {
`
SELECT
ce.*,
COALESCE(oi.fulfillment_channel, CASE WHEN oi.fulfillment_status = 'archived' THEN 'archived' ELSE 'pending' END) AS fulfillment_mode
COALESCE(oi.fulfillment_channel, CASE WHEN oi.fulfillment_status = 'archived' THEN 'archived' ELSE 'pending' END) AS channel
FROM cost_exceptions ce
LEFT JOIN order_items oi ON oi.id = ce.order_item_id
${where}
@@ -629,10 +629,10 @@ export async function summarizeAdminCostExceptions(
const params: unknown[] = []
const clauses: string[] = []
const fulfillmentMode = text(payload.fulfillmentMode ?? payload.fulfillment_mode)
if (fulfillmentMode) {
assertOneOf(fulfillmentMode, FULFILLMENT_MODES, '履约方式无效')
params.push(fulfillmentMode)
const channel = text(payload.channel ?? payload.channel)
if (channel) {
assertOneOf(channel, FULFILLMENT_CHANNELS, '履约方式无效')
params.push(channel)
clauses.push(
`ce.order_item_id IN (
SELECT oi.id FROM order_items oi WHERE COALESCE(oi.fulfillment_channel, CASE WHEN oi.fulfillment_status = 'archived' THEN 'archived' ELSE 'pending' END) = $${params.length}
@@ -14,7 +14,7 @@ import type { AdminSession } from '../admin/admin-auth-service.js'
import { normalizeMatchText, normalizeSkuSeriesEquivalence } from '../product-match/normalize.js'
import { resolveSkuNameQuantity } from '../product-match/pricing.js'
import {
FULFILLMENT_MODES,
FULFILLMENT_CHANNELS,
costModelScopeSql,
mapCostVersion,
mapMapping,
@@ -32,7 +32,7 @@ import type {
CostPreview,
CostResolution,
CostVersionRow,
FulfillmentMode,
FulfillmentChannel,
MappingRow,
MissingCostItem,
OrderItemCostContext,
@@ -49,7 +49,7 @@ export async function previewAdminCost(payload: JsonObject = {}) {
? await resolveCostLines({
provider: context.provider,
shopId: context.shopId,
fulfillmentMode: context.fulfillmentMode,
channel: context.channel,
canonicalProductId: productId,
workProductRuleId: context.workProductRuleId,
quantity: context.normalizedQuantity,
@@ -76,22 +76,22 @@ export async function previewAdminCost(payload: JsonObject = {}) {
.map((item) => `${item.costItemName}(${item.costItemCode})`)
.join('、')}`,
detail: {
fulfillmentMode: context.fulfillmentMode,
channel: context.channel,
costItemIds: resolution.missingCostItems.map((item) => item.costItemId),
},
})
} else if (resolution.applicableCostItemCount === 0) {
exceptions.push({
reason: 'cost_missing',
message: `没有配置适用于「${context.fulfillmentMode}」的成本项`,
detail: { fulfillmentMode: context.fulfillmentMode },
message: `没有配置适用于「${context.channel}」的成本项`,
detail: { channel: context.channel },
})
}
// 人工履约的成本来自「人工 SKU 配置的消耗积分 × 平台换算率」,版本金额只是占位;
// 这里单独给出提示,并从成本行里剔掉 0 元占位,避免预览与实际扣款对不上。
const manualCost =
context.fulfillmentMode === 'manual' ? await resolveManualCostHint(context.orderItemId) : null
context.channel === 'manual' ? await resolveManualCostHint(context.orderItemId) : null
const lines = manualCost
? resolution.lines.filter((line) => line.costItemCode !== 'sys_manual_service')
: resolution.lines
@@ -233,7 +233,7 @@ export async function createAdminCostSnapshot(payload: JsonObject = {}, _session
provider: preview.context.provider,
shopId: preview.context.shopId,
normalizedQuantity: preview.context.normalizedQuantity,
fulfillmentMode: preview.context.fulfillmentMode,
channel: preview.context.channel,
basisAt: preview.context.basisAt,
}),
preview.context.basisAt,
@@ -296,7 +296,7 @@ async function resolveCostContext(payload: JsonObject): Promise<OrderItemCostCon
basis_at: string
work_order_id: number | null
work_product_rule_id: number | null
fulfillment_mode: string | null
channel: string | null
}>(
`
SELECT
@@ -315,7 +315,7 @@ async function resolveCostContext(payload: JsonObject): Promise<OrderItemCostCon
COALESCE(o.paid_at, o.created_at) AS basis_at,
wo.id AS work_order_id,
wo.product_rule_id AS work_product_rule_id,
COALESCE(oi.fulfillment_channel, CASE WHEN oi.fulfillment_status = 'archived' THEN 'archived' ELSE 'pending' END) AS fulfillment_mode
COALESCE(oi.fulfillment_channel, CASE WHEN oi.fulfillment_status = 'archived' THEN 'archived' ELSE 'pending' END) AS channel
FROM order_items oi
JOIN orders o ON o.id = oi.order_id
LEFT JOIN LATERAL (
@@ -358,7 +358,7 @@ async function resolveCostContext(payload: JsonObject): Promise<OrderItemCostCon
basisAt: new Date(row.basis_at).toISOString(),
workOrderId: row.work_order_id ? Number(row.work_order_id) : null,
workProductRuleId: row.work_product_rule_id ? Number(row.work_product_rule_id) : null,
fulfillmentMode: resolveFulfillmentMode(row.fulfillment_mode),
channel: resolveFulfillmentMode(row.channel),
}
}
@@ -366,9 +366,7 @@ async function resolveCostContext(payload: JsonObject): Promise<OrderItemCostCon
const skuCode = normalizeRequiredText(payload.skuCode ?? payload.sku_code, '平台 SKU', 120)
const quantity = Math.max(1, Math.trunc(Number(payload.quantity) || 1))
const skuName = normalizeOptionalText(payload.skuName ?? payload.sku_name, 200)
const fulfillmentMode = resolveFulfillmentMode(
payload.fulfillmentMode ?? payload.fulfillment_mode,
)
const channel = resolveFulfillmentMode(payload.channel ?? payload.channel)
return {
orderItemId: 0,
orderId: 0,
@@ -390,7 +388,7 @@ async function resolveCostContext(payload: JsonObject): Promise<OrderItemCostCon
workProductRuleId: normalizeOptionalId(
payload.workProductRuleId ?? payload.work_product_rule_id,
),
fulfillmentMode,
channel,
}
}
@@ -398,9 +396,9 @@ async function resolveCostContext(payload: JsonObject): Promise<OrderItemCostCon
* 履约渠道只读 order_items.fulfillment_channel / fulfillment_status。
* 订单项还没判定时按人工处理,不允许用 provider 或核销码兜底。
*/
function resolveFulfillmentMode(value: unknown): FulfillmentMode {
function resolveFulfillmentMode(value: unknown): FulfillmentChannel {
const normalized = text(value)
if (normalized && FULFILLMENT_MODES.has(normalized)) return normalized as FulfillmentMode
if (normalized && FULFILLMENT_CHANNELS.has(normalized)) return normalized as FulfillmentChannel
return 'manual'
}
@@ -455,7 +453,7 @@ async function findMappingForContext(context: OrderItemCostContext) {
async function resolveCostLines(input: {
provider: string
shopId: string
fulfillmentMode: FulfillmentMode
channel: FulfillmentChannel
canonicalProductId: number
workProductRuleId: number | null
quantity: number
@@ -514,7 +512,7 @@ WHERE ci.status = 'active'
input.shopId,
input.canonicalProductId,
input.workProductRuleId,
input.fulfillmentMode,
input.channel,
],
)
@@ -19,7 +19,7 @@ import { setAdminAffiliateProductPrice } from './affiliate-product-service.js'
import { syncAdminWorkProductRulePrice } from '../worker-platform/admin-worker-catalog-service.js'
import {
AFFILIATE_TASK_AGG_JOIN,
FULFILLMENT_MODES,
FULFILLMENT_CHANNELS,
MAPPING_CONFIDENCES,
MAPPING_SOURCES,
PRODUCT_CATEGORY_JOINS,
@@ -583,8 +583,8 @@ export async function listAdminChannelMappings(payload: JsonObject = {}) {
export async function getAdminChannelMappingDiagnostics(payload: JsonObject = {}) {
const source = text(payload.carrierType ?? payload.carrier_type ?? payload.source)
if (source) assertOneOf(source, PRODUCT_SOURCE_FILTERS, '商品来源无效')
const fulfillmentMode = text(payload.fulfillmentMode ?? payload.fulfillment_mode)
if (fulfillmentMode) assertOneOf(fulfillmentMode, FULFILLMENT_MODES, '履约方式无效')
const channel = text(payload.channel ?? payload.channel)
if (channel) assertOneOf(channel, FULFILLMENT_CHANNELS, '履约方式无效')
const productParams: unknown[] = []
let sourceSql = 'TRUE'
@@ -627,7 +627,7 @@ export async function getAdminChannelMappingDiagnostics(payload: JsonObject = {}
ce.detail_json->>'provider' AS provider,
ce.detail_json->>'shopId' AS shop_id,
COALESCE(ce.detail_json->>'skuCode', '') AS sku_code,
COALESCE(oi.fulfillment_channel, CASE WHEN oi.fulfillment_status = 'archived' THEN 'archived' ELSE 'pending' END) AS fulfillment_mode,
COALESCE(oi.fulfillment_channel, CASE WHEN oi.fulfillment_status = 'archived' THEN 'archived' ELSE 'pending' END) AS channel,
COUNT(*)::int AS item_count
FROM cost_exceptions ce
JOIN order_items oi ON oi.id = ce.order_item_id
@@ -649,9 +649,7 @@ export async function getAdminChannelMappingDiagnostics(payload: JsonObject = {}
}
}
const modes = fulfillmentMode
? [fulfillmentMode]
: ['work_order', 'affiliate_dash', 'legacy_platform', 'manual']
const modes = channel ? [channel] : ['work_order', 'affiliate_dash', 'legacy_platform', 'manual']
// 顺序跑:并行会同时扫 cost_exceptions,实测 4 路并发比串行更慢(I/O 争抢)。
const aggregates: Array<{ groupTotal: number; itemTotal: number }> = []
for (const mode of modes) {
@@ -661,7 +659,7 @@ export async function getAdminChannelMappingDiagnostics(payload: JsonObject = {}
const unmappedItemTotal = aggregates.reduce((sum, item) => sum + item.itemTotal, 0)
return {
fulfillmentMode: fulfillmentMode || null,
channel: channel || null,
productTotal: toNumber(counts.rows[0]?.product_total),
mappingTotal: toNumber(counts.rows[0]?.mapping_total),
mappedProductTotal: toNumber(counts.rows[0]?.mapping_product_total),
@@ -682,8 +680,8 @@ export async function listAdminUnmappedMappingGroups(payload: JsonObject = {}) {
const params: unknown[] = []
const clauses = [`ce.reason = 'product_mapping_missing'`, `ce.status = 'open'`]
const fulfillmentMode = text(payload.fulfillmentMode ?? payload.fulfillment_mode)
if (fulfillmentMode) assertOneOf(fulfillmentMode, FULFILLMENT_MODES, '履约方式无效')
const channel = text(payload.channel ?? payload.channel)
if (channel) assertOneOf(channel, FULFILLMENT_CHANNELS, '履约方式无效')
const provider = text(payload.provider)
if (provider) {
params.push(normalizeProviderKey(provider))
@@ -701,9 +699,7 @@ export async function listAdminUnmappedMappingGroups(payload: JsonObject = {}) {
// 分组总数单独算:SQL 守卫禁止窗口函数分页(会在 LIMIT 前消费全部候选行)。
// 按履约方式拆开统计:命中索引,单模式约 90ms;「全部」时顺序跑四种模式。
const modes = fulfillmentMode
? [fulfillmentMode]
: ['work_order', 'affiliate_dash', 'legacy_platform', 'manual']
const modes = channel ? [channel] : ['work_order', 'affiliate_dash', 'legacy_platform', 'manual']
const totals: Array<{ groupTotal: number; itemTotal: number }> = []
for (const mode of modes) {
const totalParams = [...params, mode]
@@ -742,10 +738,10 @@ export async function listAdminUnmappedMappingGroups(payload: JsonObject = {}) {
}
}
const modeIndex = fulfillmentMode ? params.length + 1 : null
const modeIndex = channel ? params.length + 1 : null
const pageIndex = params.length + (modeIndex ? 2 : 1)
const offsetIndex = pageIndex + 1
const listParams = [...params, ...(fulfillmentMode ? [fulfillmentMode] : []), pageSize, offset]
const listParams = [...params, ...(channel ? [channel] : []), pageSize, offset]
const modeClause = modeIndex
? `AND COALESCE(oi.fulfillment_channel, CASE WHEN oi.fulfillment_status = 'archived' THEN 'archived' ELSE 'pending' END) = $${modeIndex}`
: ''
@@ -754,7 +750,7 @@ export async function listAdminUnmappedMappingGroups(payload: JsonObject = {}) {
shop_id: string
sku_code: string
sku_name: string
fulfillment_mode: string
channel: string
item_count: number
last_seen_at: string | null
}>(
@@ -764,7 +760,7 @@ export async function listAdminUnmappedMappingGroups(payload: JsonObject = {}) {
ce.detail_json->>'provider' AS provider,
ce.detail_json->>'shopId' AS shop_id,
COALESCE(ce.detail_json->>'skuCode', '') AS sku_code,
COALESCE(oi.fulfillment_channel, CASE WHEN oi.fulfillment_status = 'archived' THEN 'archived' ELSE 'pending' END) AS fulfillment_mode,
COALESCE(oi.fulfillment_channel, CASE WHEN oi.fulfillment_status = 'archived' THEN 'archived' ELSE 'pending' END) AS channel,
MAX(ce.detail_json->>'skuName') AS sku_name,
MAX(NULLIF(ce.detail_json->>'basisAt', '')) AS last_seen_at,
COUNT(*)::int AS item_count
@@ -788,7 +784,7 @@ export async function listAdminUnmappedMappingGroups(payload: JsonObject = {}) {
shopId: row.shop_id || '',
skuCode: row.sku_code || '',
skuName: row.sku_name || '',
fulfillmentMode: row.fulfillment_mode || '',
channel: row.channel || '',
itemCount: toNumber(row.item_count),
lastSeenAt: row.last_seen_at || null,
})),