725 lines
25 KiB
TypeScript
725 lines
25 KiB
TypeScript
import { query, withTransaction } from '../../db/client.js'
|
|
import type { PoolClient } from 'pg'
|
|
import { nowIso } from '../../utils/time.js'
|
|
import { GENERIC_COST_MODELS } from './cost-center-constants.js'
|
|
import {
|
|
resolveExceptionsForItems,
|
|
resolveExceptionsForItemsByReason,
|
|
upsertAggregatedExceptionsBatch,
|
|
type AggregatedExceptionEntry,
|
|
} from './cost-exception-service.js'
|
|
import { readWatermarkItemId } from '../watermark-store.js'
|
|
|
|
/**
|
|
* 管道 C1:成本快照(唯一入口)。
|
|
*
|
|
* 旧实现有三条路径(预估 / 工单实际 / 自动发货专用),互相叠加;
|
|
* 这里统一成一条:按渠道取成本项 → 解析版本 → 写不可变快照。
|
|
*
|
|
* 渠道 → 成本项:
|
|
* affiliate_dash → sys_affiliate_purchase(按商品)
|
|
* third_party_voucher → sys_third_party_voucher_cost(按商品)
|
|
* work_order → sys_work_order_reward(优先按接单规则,其次按商品;已接单按实际奖励)
|
|
* manual → 不写渠道成本(确认履约时按实际录入)
|
|
*
|
|
* 通用成本模型(platform_fee / payment_fee / after_sales_loss)对所有渠道生效,
|
|
* 与渠道成本项各写一条快照;解析不到版本时静默跳过,不进异常队列。
|
|
*
|
|
* 快照不是「一次性」:每轮对比当前解析结果与已有有效快照,金额/版本/阶段变化时
|
|
* 先 supersede 旧行再写新行,保证「预估 → 实际」「补配价格」都能被纠正。
|
|
*/
|
|
|
|
const CHANNEL_COST_CODE: Record<string, string> = {
|
|
affiliate_dash: 'sys_affiliate_purchase',
|
|
third_party_voucher: 'sys_third_party_voucher_cost',
|
|
work_order: 'sys_work_order_reward',
|
|
}
|
|
|
|
export type CostItemRow = {
|
|
id: number
|
|
code: string
|
|
pricing_mode: string
|
|
cost_model: string
|
|
}
|
|
|
|
export type CostVersionRow = {
|
|
id: number
|
|
cost_item_id: number
|
|
scope_type: string
|
|
canonical_product_id: number | null
|
|
work_product_rule_id: number | null
|
|
amount_fen: number
|
|
rate_bps: number
|
|
effective_from: string
|
|
}
|
|
|
|
export type CostCandidateItem = {
|
|
id: number
|
|
order_id: number
|
|
fulfillment_channel: string | null
|
|
canonical_product_id: number | null
|
|
quantity: number
|
|
basis_at: string
|
|
work_order_id: number | null
|
|
work_product_rule_id: number | null
|
|
work_product_rule_pricing_mode?: 'fixed' | 'unit' | null
|
|
work_order_status: string | null
|
|
reward_amount: number | null
|
|
revenue_fen: number
|
|
refund_fen: number
|
|
basis_date: string
|
|
}
|
|
|
|
export type CostResolution = {
|
|
costItemId: number
|
|
costVersionId: number
|
|
unitAmountFen: number
|
|
totalAmountFen: number
|
|
stage: 'estimated' | 'actual'
|
|
} | null
|
|
|
|
function toTime(value: unknown): number {
|
|
const parsed = new Date(String(value)).getTime()
|
|
return Number.isFinite(parsed) ? parsed : 0
|
|
}
|
|
|
|
function isEffective(version: CostVersionRow, basisAt: string): boolean {
|
|
return toTime(version.effective_from) <= toTime(basisAt)
|
|
}
|
|
|
|
/** 纯函数:按「规则 > 商品 > 全局」优先级取最新有效版本。 */
|
|
export function selectCostVersion(
|
|
versions: CostVersionRow[],
|
|
input: { costItemId: number; productId: number | null; ruleId: number | null; basisAt: string },
|
|
): CostVersionRow | null {
|
|
const candidates = versions.filter(
|
|
(version) =>
|
|
Number(version.cost_item_id) === Number(input.costItemId) &&
|
|
isEffective(version, input.basisAt) &&
|
|
(version.scope_type === 'global' ||
|
|
(version.scope_type === 'product' &&
|
|
input.productId != null &&
|
|
Number(version.canonical_product_id) === Number(input.productId)) ||
|
|
(version.scope_type === 'rule' &&
|
|
input.ruleId != null &&
|
|
Number(version.work_product_rule_id) === Number(input.ruleId))),
|
|
)
|
|
if (candidates.length === 0) return null
|
|
|
|
const rank = (version: CostVersionRow) =>
|
|
version.scope_type === 'rule' ? 3 : version.scope_type === 'product' ? 2 : 1
|
|
|
|
return candidates.sort((left, right) => {
|
|
const byRank = rank(right) - rank(left)
|
|
if (byRank !== 0) return byRank
|
|
return toTime(right.effective_from) - toTime(left.effective_from)
|
|
})[0]!
|
|
}
|
|
|
|
/** 纯函数:结合订单项与版本得到快照金额。 */
|
|
export function resolveCost(
|
|
item: CostCandidateItem,
|
|
costItems: Map<string, CostItemRow>,
|
|
versions: CostVersionRow[],
|
|
pricingModeByItemId: Map<number, string>,
|
|
): CostResolution {
|
|
const code = CHANNEL_COST_CODE[String(item.fulfillment_channel || '')]
|
|
if (!code) return null
|
|
const costItem = costItems.get(code)
|
|
if (!costItem) return null
|
|
|
|
// 工单已结算:直接按实际奖励金额记 actual,不依赖版本价格。
|
|
if (
|
|
String(item.fulfillment_channel) === 'work_order' &&
|
|
String(item.work_order_status || '') === 'accepted' &&
|
|
Number(item.reward_amount || 0) > 0
|
|
) {
|
|
const version = selectCostVersion(versions, {
|
|
costItemId: costItem.id,
|
|
productId: item.canonical_product_id,
|
|
ruleId: item.work_product_rule_id,
|
|
basisAt: item.basis_at,
|
|
})
|
|
if (!version) return null
|
|
return {
|
|
costItemId: costItem.id,
|
|
costVersionId: version.id,
|
|
unitAmountFen: Number(item.reward_amount),
|
|
totalAmountFen: Number(item.reward_amount),
|
|
stage: 'actual',
|
|
}
|
|
}
|
|
|
|
const version = selectCostVersion(versions, {
|
|
costItemId: costItem.id,
|
|
productId: item.canonical_product_id,
|
|
ruleId: item.work_product_rule_id,
|
|
basisAt: item.basis_at,
|
|
})
|
|
if (!version) return null
|
|
|
|
const pricingMode =
|
|
item.fulfillment_channel === 'work_order' &&
|
|
costItem.code === 'sys_work_order_reward' &&
|
|
item.work_product_rule_pricing_mode
|
|
? item.work_product_rule_pricing_mode === 'unit'
|
|
? 'per_item'
|
|
: 'per_order'
|
|
: pricingModeByItemId.get(costItem.id) || costItem.pricing_mode
|
|
const amount = Number(version.amount_fen) || 0
|
|
const quantity = Math.max(1, Number(item.quantity) || 1)
|
|
|
|
if (pricingMode === 'percent_of_revenue') {
|
|
const rate = Number(version.rate_bps) || 0
|
|
// 比例成本只看费率:费率为 0 说明还没配价,不能当 0 元成本入账。
|
|
if (rate <= 0) return null
|
|
const netRevenue = Math.max(0, (Number(item.revenue_fen) || 0) - (Number(item.refund_fen) || 0))
|
|
const total = Math.round(netRevenue * (rate / 10000))
|
|
return {
|
|
costItemId: costItem.id,
|
|
costVersionId: version.id,
|
|
unitAmountFen: total,
|
|
totalAmountFen: total,
|
|
stage: 'estimated',
|
|
}
|
|
}
|
|
|
|
// 全局 0 元是占位版本,不是真实成本;否则毛利会被静默抬高。
|
|
if (amount <= 0) return null
|
|
const total = pricingMode === 'per_item' ? amount * quantity : amount
|
|
return {
|
|
costItemId: costItem.id,
|
|
costVersionId: version.id,
|
|
unitAmountFen: amount,
|
|
totalAmountFen: total,
|
|
stage: 'estimated',
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 通用成本模型:平台费/支付费/售后损失等,对所有渠道生效。
|
|
* 只按商品或全局版本解析,不挂接单规则。
|
|
*/
|
|
const AUTO_GENERIC_MODELS = new Set(['platform_fee', 'payment_fee'])
|
|
|
|
export function resolveGenericCosts(
|
|
item: CostCandidateItem,
|
|
genericItems: CostItemRow[],
|
|
versions: CostVersionRow[],
|
|
pricingModeByItemId: Map<number, string>,
|
|
): Array<NonNullable<CostResolution>> {
|
|
const result: Array<NonNullable<CostResolution>> = []
|
|
for (const costItem of genericItems) {
|
|
const version = selectCostVersion(versions, {
|
|
costItemId: costItem.id,
|
|
productId: item.canonical_product_id,
|
|
ruleId: null,
|
|
basisAt: item.basis_at,
|
|
})
|
|
if (!version) continue
|
|
// 平台费/支付费是「每单都会发生」的通用费用,可按 global/product 自动计;
|
|
// 售后损失与其他成本必须显式按商品配置,避免一条 global 版本套到所有订单。
|
|
if (!AUTO_GENERIC_MODELS.has(costItem.cost_model) && version.scope_type !== 'product') {
|
|
continue
|
|
}
|
|
const pricingMode = pricingModeByItemId.get(costItem.id) || costItem.pricing_mode
|
|
const amount = Number(version.amount_fen) || 0
|
|
|
|
if (pricingMode === 'percent_of_revenue') {
|
|
const rate = Number(version.rate_bps) || 0
|
|
if (rate <= 0) continue
|
|
const netRevenue = Math.max(
|
|
0,
|
|
(Number(item.revenue_fen) || 0) - (Number(item.refund_fen) || 0),
|
|
)
|
|
const total = Math.round(netRevenue * (rate / 10000))
|
|
result.push({
|
|
costItemId: costItem.id,
|
|
costVersionId: version.id,
|
|
unitAmountFen: total,
|
|
totalAmountFen: total,
|
|
stage: 'estimated',
|
|
})
|
|
continue
|
|
}
|
|
if (amount <= 0) continue
|
|
const quantity = Math.max(1, Number(item.quantity) || 1)
|
|
const total = pricingMode === 'per_item' ? amount * quantity : amount
|
|
result.push({
|
|
costItemId: costItem.id,
|
|
costVersionId: version.id,
|
|
unitAmountFen: amount,
|
|
totalAmountFen: total,
|
|
stage: 'estimated',
|
|
})
|
|
}
|
|
return result
|
|
}
|
|
|
|
/**
|
|
* 历史订单成本固化:已有快照不再因成本版本变更而替换。
|
|
* 唯一允许的变化是「预估 → 实际」的履约结算升级。
|
|
*/
|
|
export function shouldSupersedeSnapshot(
|
|
currentStage: string | null | undefined,
|
|
nextStage: string,
|
|
mutableEstimated = false,
|
|
): boolean {
|
|
if (!currentStage) return true
|
|
if (currentStage === 'estimated' && nextStage === 'actual') return true
|
|
// 平台费/支付费是随收入变化的派生费用,退款后允许按净收入重算;
|
|
// 采购成本、打手报酬等成交成本仍保持固化。
|
|
if (currentStage === 'estimated' && nextStage === 'estimated' && mutableEstimated) return true
|
|
return false
|
|
}
|
|
|
|
export type SyncCostSnapshotsResult = {
|
|
scanned: number
|
|
created: number
|
|
superseded: number
|
|
missing: number
|
|
/** 通用费用已配置、但该订单项解析不到通用版本的条数(仅提示,不建异常)。 */
|
|
genericMissing: number
|
|
lastId: number
|
|
nextCursor: number
|
|
/** 热通道游标:本轮之后新增订单的处理起点。 */
|
|
hotCursor: number
|
|
/** 发生过快照新增/替换的业务日,供事实与总账按日回填。 */
|
|
affectedDates: string[]
|
|
}
|
|
|
|
type CostContext = {
|
|
channelCostItems: Map<string, CostItemRow>
|
|
genericCostItems: CostItemRow[]
|
|
versions: CostVersionRow[]
|
|
pricingModeByItemId: Map<number, string>
|
|
costModelByItemId: Map<number, string>
|
|
genericConfigured: boolean
|
|
}
|
|
|
|
const CANDIDATE_SQL = `
|
|
SELECT
|
|
oi.id,
|
|
oi.order_id,
|
|
oi.fulfillment_channel,
|
|
oi.canonical_product_id,
|
|
GREATEST(COALESCE(oi.normalized_quantity, oi.quantity, 1), 1)::int AS quantity,
|
|
COALESCE(o.paid_at, o.created_at) AS basis_at,
|
|
(COALESCE(o.paid_at, o.created_at) AT TIME ZONE 'Asia/Shanghai')::date::text
|
|
AS basis_date,
|
|
COALESCE(oi.revenue_amount_fen, 0)::bigint AS revenue_fen,
|
|
COALESCE((
|
|
SELECT SUM(r.amount_fen) FROM order_refunds r
|
|
WHERE r.order_item_id = oi.id AND r.status = 'confirmed'
|
|
), 0)::bigint AS refund_fen,
|
|
wo.id AS work_order_id,
|
|
wo.product_rule_id AS work_product_rule_id,
|
|
wpr.pricing_mode AS work_product_rule_pricing_mode,
|
|
wo.status AS work_order_status,
|
|
wo.reward_amount
|
|
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
|
|
WHERE oi.fulfillment_status = 'assigned'
|
|
AND oi.fulfillment_channel IN (
|
|
'affiliate_dash', 'third_party_voucher', 'work_order', 'manual', 'on_account'
|
|
)
|
|
`
|
|
|
|
function emptyResult(lastId = 0, nextCursor = 0, hotCursor = 0): SyncCostSnapshotsResult {
|
|
return {
|
|
scanned: 0,
|
|
created: 0,
|
|
superseded: 0,
|
|
missing: 0,
|
|
genericMissing: 0,
|
|
lastId,
|
|
nextCursor,
|
|
hotCursor,
|
|
affectedDates: [],
|
|
}
|
|
}
|
|
|
|
async function loadCostContext(): Promise<CostContext> {
|
|
const allCostItems = await loadCostItems()
|
|
const channelCostItems = new Map<string, CostItemRow>()
|
|
const genericCostItems: CostItemRow[] = []
|
|
for (const item of allCostItems) {
|
|
if ((GENERIC_COST_MODELS as readonly string[]).includes(item.cost_model)) {
|
|
genericCostItems.push(item)
|
|
} else if (item.code) {
|
|
channelCostItems.set(item.code, item)
|
|
}
|
|
}
|
|
const versions = await loadActiveVersions()
|
|
const pricingModeByItemId = new Map<number, string>()
|
|
const costModelByItemId = new Map<number, string>()
|
|
for (const item of allCostItems) {
|
|
pricingModeByItemId.set(item.id, item.pricing_mode)
|
|
costModelByItemId.set(Number(item.id), item.cost_model)
|
|
}
|
|
return {
|
|
channelCostItems,
|
|
genericCostItems,
|
|
versions,
|
|
pricingModeByItemId,
|
|
costModelByItemId,
|
|
genericConfigured: hasConfiguredGeneric(genericCostItems, versions),
|
|
}
|
|
}
|
|
|
|
async function processCostRows(
|
|
rows: CostCandidateItem[],
|
|
ctx: CostContext,
|
|
result: SyncCostSnapshotsResult,
|
|
affectedDates: Set<string>,
|
|
): Promise<void> {
|
|
if (rows.length === 0) return
|
|
result.scanned += rows.length
|
|
const existingMap = await loadActiveSnapshots(rows.map((row) => row.id))
|
|
const openMissing = await loadOpenMissingItems(rows.map((row) => row.id))
|
|
const inserts: Array<{ item: CostCandidateItem; resolution: NonNullable<CostResolution> }> = []
|
|
const supersedeIds: number[] = []
|
|
const missingEntries: AggregatedExceptionEntry[] = []
|
|
const resolvedMissingIds: number[] = []
|
|
|
|
for (const item of rows) {
|
|
const desired: Array<NonNullable<CostResolution>> = []
|
|
const code = CHANNEL_COST_CODE[String(item.fulfillment_channel || '')]
|
|
const channelResolution = code
|
|
? resolveCost(item, ctx.channelCostItems, ctx.versions, ctx.pricingModeByItemId)
|
|
: null
|
|
if (channelResolution) {
|
|
desired.push(channelResolution)
|
|
} else if (code) {
|
|
// 历史版本可能已 retired,但订单已有不可变快照:这单不算缺成本,
|
|
// 否则“改价后旧订单快照还在、异常却重新冒出来”。
|
|
const channelCostItem = ctx.channelCostItems.get(code)
|
|
const hasActiveChannelSnapshot = channelCostItem
|
|
? existingMap.get(Number(item.id))?.has(Number(channelCostItem.id))
|
|
: false
|
|
if (hasActiveChannelSnapshot) {
|
|
resolvedMissingIds.push(Number(item.id))
|
|
} else {
|
|
result.missing += 1
|
|
// 已在队列里的缺失项不再重复写三条 SQL,等价格补齐后自然收口。
|
|
if (!openMissing.has(Number(item.id))) {
|
|
missingEntries.push({
|
|
reason: 'cost_missing',
|
|
scopeKey: `cost_missing|${item.fulfillment_channel}|${item.canonical_product_id}|${item.work_product_rule_id ?? '-'}`,
|
|
orderItemId: Number(item.id),
|
|
detail: { channel: item.fulfillment_channel },
|
|
})
|
|
}
|
|
}
|
|
}
|
|
|
|
if (ctx.genericCostItems.length > 0) {
|
|
const generic = resolveGenericCosts(
|
|
item,
|
|
ctx.genericCostItems,
|
|
ctx.versions,
|
|
ctx.pricingModeByItemId,
|
|
)
|
|
desired.push(...generic)
|
|
if (generic.length === 0 && ctx.genericConfigured) result.genericMissing += 1
|
|
}
|
|
|
|
const existing = existingMap.get(Number(item.id)) || new Map<number, ExistingSnapshot>()
|
|
for (const resolution of desired) {
|
|
const current = existing.get(Number(resolution.costItemId))
|
|
if (
|
|
current &&
|
|
Number(current.cost_version_id) === Number(resolution.costVersionId) &&
|
|
Number(current.total_amount_fen) === Number(resolution.totalAmountFen) &&
|
|
current.snapshot_stage === resolution.stage
|
|
) {
|
|
continue
|
|
}
|
|
if (current) {
|
|
const model = ctx.costModelByItemId.get(Number(resolution.costItemId)) || ''
|
|
const mutableEstimated = AUTO_GENERIC_MODELS.has(model)
|
|
if (!shouldSupersedeSnapshot(current.snapshot_stage, resolution.stage, mutableEstimated)) {
|
|
continue
|
|
}
|
|
supersedeIds.push(Number(current.id))
|
|
result.superseded += 1
|
|
}
|
|
inserts.push({ item, resolution })
|
|
affectedDates.add(item.basis_date)
|
|
}
|
|
}
|
|
|
|
if (resolvedMissingIds.length > 0) {
|
|
await resolveExceptionsForItemsByReason(resolvedMissingIds, 'cost_missing').catch(
|
|
() => undefined,
|
|
)
|
|
}
|
|
if (missingEntries.length > 0) {
|
|
await upsertAggregatedExceptionsBatch(missingEntries)
|
|
}
|
|
if (supersedeIds.length === 0 && inserts.length === 0) return
|
|
// 替换与写入放在同一事务里,避免事实任务读到「旧行已过期、新行未写入」的空窗。
|
|
const created = await withTransaction(async (client) => {
|
|
if (supersedeIds.length > 0) await supersedeSnapshots(supersedeIds, client)
|
|
if (inserts.length === 0) return 0
|
|
return insertSnapshots(inserts, client)
|
|
})
|
|
result.created += created
|
|
if (inserts.length > 0) {
|
|
await resolveExceptionsForItems(inserts.map((row) => row.item.id))
|
|
}
|
|
}
|
|
|
|
export async function syncChannelCostSnapshots(
|
|
options: { batchSize?: number; maxBatches?: number; afterId?: number } = {},
|
|
): Promise<SyncCostSnapshotsResult> {
|
|
const batchSize = Math.min(5000, Math.max(1, Math.trunc(options.batchSize || 500)))
|
|
const maxBatches = Math.min(200, Math.max(1, Math.trunc(options.maxBatches || 20)))
|
|
const singleItem = options.afterId != null
|
|
|
|
let coldCursor = singleItem
|
|
? Math.max(0, Math.trunc(options.afterId!))
|
|
: await readWatermarkItemId('cost_snapshot')
|
|
let hotCursor = singleItem ? 0 : await readWatermarkItemId('cost_snapshot_hot')
|
|
const coldBound = hotCursor
|
|
let coldReachedEnd = false
|
|
|
|
const ctx = await loadCostContext()
|
|
const result = emptyResult(coldCursor, coldCursor, hotCursor)
|
|
const affectedDates = new Set<string>()
|
|
|
|
if (singleItem) {
|
|
const rows = await query<CostCandidateItem>(
|
|
`${CANDIDATE_SQL} AND oi.id > $1 ORDER BY oi.id LIMIT $2`,
|
|
[coldCursor, Math.min(batchSize, 1)],
|
|
)
|
|
await processCostRows(rows.rows, ctx, result, affectedDates)
|
|
if (rows.rows.length > 0) {
|
|
const last = Number(rows.rows[rows.rows.length - 1]!.id)
|
|
result.lastId = last
|
|
result.nextCursor = last
|
|
}
|
|
result.affectedDates = [...affectedDates].sort()
|
|
return result
|
|
}
|
|
|
|
// 热通道:只处理上次运行之后新增的订单项,保证新单分钟级入账。
|
|
let hotBatches = 0
|
|
for (let batch = 0; batch < maxBatches; batch += 1) {
|
|
const rows = await query<CostCandidateItem>(
|
|
`${CANDIDATE_SQL} AND oi.id > $1 ORDER BY oi.id LIMIT $2`,
|
|
[hotCursor, batchSize],
|
|
)
|
|
if (rows.rows.length === 0) break
|
|
hotBatches += 1
|
|
hotCursor = Number(rows.rows[rows.rows.length - 1]!.id)
|
|
await processCostRows(rows.rows, ctx, result, affectedDates)
|
|
if (rows.rows.length < batchSize) break
|
|
}
|
|
result.hotCursor = hotCursor
|
|
|
|
// 冷通道:从旧游标开始回扫历史订单项,处理补配价格等后置变更。
|
|
const remaining = Math.max(0, maxBatches - hotBatches)
|
|
for (let batch = 0; batch < remaining; batch += 1) {
|
|
const rows = await query<CostCandidateItem>(
|
|
`${CANDIDATE_SQL} AND oi.id > $1 AND oi.id <= $3 ORDER BY oi.id LIMIT $2`,
|
|
[coldCursor, batchSize, coldBound],
|
|
)
|
|
if (rows.rows.length === 0) {
|
|
coldReachedEnd = true
|
|
break
|
|
}
|
|
coldCursor = Number(rows.rows[rows.rows.length - 1]!.id)
|
|
result.lastId = coldCursor
|
|
await processCostRows(rows.rows, ctx, result, affectedDates)
|
|
if (rows.rows.length < batchSize) {
|
|
coldReachedEnd = true
|
|
break
|
|
}
|
|
}
|
|
|
|
result.nextCursor = coldReachedEnd ? 0 : coldCursor
|
|
result.affectedDates = [...affectedDates].sort()
|
|
return result
|
|
}
|
|
|
|
/**
|
|
* 指定订单项立即算成本(渠道判定完成后调用,避免等冷通道扫到)。
|
|
*/
|
|
export async function syncCostSnapshotsForItems(itemIds: number[]): Promise<{
|
|
created: number
|
|
superseded: number
|
|
missing: number
|
|
affectedDates: string[]
|
|
}> {
|
|
const ids = [
|
|
...new Set(itemIds.map(Number).filter((id) => Number.isInteger(id) && id > 0)),
|
|
].slice(0, 2000)
|
|
if (ids.length === 0) return { created: 0, superseded: 0, missing: 0, affectedDates: [] }
|
|
const ctx = await loadCostContext()
|
|
const result = emptyResult(0, 0, 0)
|
|
const affectedDates = new Set<string>()
|
|
const rows = await query<CostCandidateItem>(`${CANDIDATE_SQL} AND oi.id = ANY($1::bigint[])`, [
|
|
ids,
|
|
])
|
|
await processCostRows(rows.rows, ctx, result, affectedDates)
|
|
return {
|
|
created: result.created,
|
|
superseded: result.superseded,
|
|
missing: result.missing,
|
|
affectedDates: [...affectedDates].sort(),
|
|
}
|
|
}
|
|
|
|
type ExistingSnapshot = {
|
|
id: number
|
|
cost_item_id: number
|
|
cost_version_id: number
|
|
total_amount_fen: number
|
|
snapshot_stage: string
|
|
}
|
|
|
|
/** 批量查已入队的成本缺失项,避免每轮重复 upsert。 */
|
|
async function loadOpenMissingItems(itemIds: number[]): Promise<Set<number>> {
|
|
const set = new Set<number>()
|
|
if (itemIds.length === 0) return set
|
|
const rows = await query<{ order_item_id: number }>(
|
|
`
|
|
SELECT DISTINCT i.order_item_id
|
|
FROM cost_exception_items i
|
|
JOIN cost_exceptions ce ON ce.id = i.exception_id
|
|
WHERE i.order_item_id = ANY($1::bigint[])
|
|
AND ce.reason = 'cost_missing'
|
|
AND ce.status <> 'resolved'
|
|
`,
|
|
[itemIds],
|
|
)
|
|
for (const row of rows.rows) set.add(Number(row.order_item_id))
|
|
return set
|
|
}
|
|
|
|
/** 批量读取候选订单项当前有效快照,按订单项分组。 */
|
|
async function loadActiveSnapshots(
|
|
itemIds: number[],
|
|
): Promise<Map<number, Map<number, ExistingSnapshot>>> {
|
|
const map = new Map<number, Map<number, ExistingSnapshot>>()
|
|
if (itemIds.length === 0) return map
|
|
const rows = await query<ExistingSnapshot & { order_item_id: number }>(
|
|
`
|
|
SELECT id, order_item_id, cost_item_id, cost_version_id, total_amount_fen, snapshot_stage
|
|
FROM cost_snapshots
|
|
WHERE superseded_at IS NULL AND reversed_at IS NULL
|
|
AND order_item_id = ANY($1::bigint[])
|
|
`,
|
|
[itemIds],
|
|
)
|
|
for (const row of rows.rows) {
|
|
let perItem = map.get(Number(row.order_item_id))
|
|
if (!perItem) {
|
|
perItem = new Map<number, ExistingSnapshot>()
|
|
map.set(Number(row.order_item_id), perItem)
|
|
}
|
|
perItem.set(Number(row.cost_item_id), row)
|
|
}
|
|
return map
|
|
}
|
|
|
|
function hasConfiguredGeneric(genericItems: CostItemRow[], versions: CostVersionRow[]): boolean {
|
|
return genericItems.some((item) =>
|
|
versions.some((version) => Number(version.cost_item_id) === Number(item.id)),
|
|
)
|
|
}
|
|
|
|
async function supersedeSnapshots(ids: number[], client?: PoolClient): Promise<void> {
|
|
if (ids.length === 0) return
|
|
const run = client ? client.query.bind(client) : query
|
|
await run('UPDATE cost_snapshots SET superseded_at = $1 WHERE id = ANY($2::bigint[])', [
|
|
nowIso(),
|
|
ids,
|
|
])
|
|
}
|
|
|
|
async function insertSnapshots(
|
|
rows: Array<{ item: CostCandidateItem; resolution: NonNullable<CostResolution> }>,
|
|
client?: PoolClient,
|
|
): Promise<number> {
|
|
const now = nowIso()
|
|
const run = client ? client.query.bind(client) : query
|
|
const result = await run(
|
|
`
|
|
INSERT INTO cost_snapshots (
|
|
subject_type, subject_id, order_id, order_item_id, work_order_id,
|
|
cost_item_id, cost_version_id, canonical_product_id,
|
|
quantity, unit_amount_fen, total_amount_fen,
|
|
snapshot_stage, source, metadata_json, cost_basis_at, resolved_at, created_at
|
|
)
|
|
SELECT
|
|
'order_item',
|
|
input.item_id,
|
|
input.order_id,
|
|
input.item_id,
|
|
NULLIF(input.work_order_id, 0),
|
|
input.cost_item_id,
|
|
input.cost_version_id,
|
|
NULLIF(input.product_id, 0),
|
|
input.quantity,
|
|
input.unit_amount_fen,
|
|
input.total_amount_fen,
|
|
input.stage,
|
|
'resolved',
|
|
jsonb_build_object('channel', input.channel, 'pipeline', 'cost_snapshot'),
|
|
input.basis_at,
|
|
$1,
|
|
$1
|
|
FROM unnest(
|
|
$2::bigint[], $3::bigint[], $4::bigint[], $5::bigint[], $6::bigint[],
|
|
$7::bigint[], $8::numeric[], $9::bigint[], $10::bigint[],
|
|
$11::text[], $12::text[], $13::timestamptz[]
|
|
) AS input(
|
|
item_id, order_id, work_order_id, cost_item_id, cost_version_id,
|
|
product_id, quantity, unit_amount_fen, total_amount_fen, stage,
|
|
channel, basis_at
|
|
)
|
|
ON CONFLICT (subject_type, subject_id, cost_item_id) WHERE superseded_at IS NULL AND reversed_at IS NULL
|
|
DO NOTHING
|
|
`,
|
|
[
|
|
now,
|
|
rows.map((row) => row.item.id),
|
|
rows.map((row) => row.item.order_id),
|
|
rows.map((row) => row.item.work_order_id ?? 0),
|
|
rows.map((row) => row.resolution.costItemId),
|
|
rows.map((row) => row.resolution.costVersionId),
|
|
rows.map((row) => row.item.canonical_product_id ?? 0),
|
|
rows.map((row) => row.item.quantity),
|
|
rows.map((row) => row.resolution.unitAmountFen),
|
|
rows.map((row) => row.resolution.totalAmountFen),
|
|
rows.map((row) => row.resolution.stage),
|
|
rows.map((row) => String(row.item.fulfillment_channel || '')),
|
|
rows.map((row) => row.item.basis_at),
|
|
],
|
|
)
|
|
return result.rowCount || 0
|
|
}
|
|
|
|
async function loadCostItems(): Promise<CostItemRow[]> {
|
|
const rows = await query<CostItemRow>(
|
|
`SELECT id, code, pricing_mode, cost_model FROM cost_items WHERE status = 'active'`,
|
|
)
|
|
return rows.rows
|
|
}
|
|
|
|
async function loadActiveVersions(): Promise<CostVersionRow[]> {
|
|
const rows = await query<CostVersionRow>(
|
|
`
|
|
SELECT id, cost_item_id, scope_type, canonical_product_id,
|
|
work_product_rule_id, amount_fen, rate_bps, effective_from
|
|
FROM cost_versions
|
|
WHERE status = 'active'
|
|
`,
|
|
)
|
|
return rows.rows
|
|
}
|