Files
order_site/apps/backend/src/services/scheduler/finance-pipeline-jobs.ts
T
yml2213 cf0d600c7d fix(cost): 快照新单优先、费用口径与回填健壮性
- 成本快照拆热/冷双通道:新单走热通道分钟级入账,历史项冷通道轮询重算
- 通用成本只允许平台费/支付费自动全量,售后损失/其他必须按商品配置
- 比例费用按扣除已确认退款后的净收入计算
- 已入账 actual 快照不再被后续预估覆盖
- 受影响日期超过 31 天时按整段重算,不再静默丢弃;关账跳过会提示
- 通用费用解析不到时计数告警;已入队的成本缺失不再重复 upsert
- 快照替换与写入放入同一事务,避免事实任务读到空窗
2026-11-01 14:46:08 +08:00

506 lines
18 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { JsonObject } from '../../types/json.js'
import { query } from '../../db/client.js'
import { assignPendingOrderItemChannels } from '../fulfillment/channel-assign-service.js'
import { resolveExceptionsForItemsByReason } from '../cost-center/cost-exception-service.js'
import { readWatermarkItemId } from '../watermark-store.js'
import { rebuildChannelSalesDailyFacts } from '../finance/sales-facts-channel-service.js'
import { syncFinanceLedgerFromFacts } from '../finance/finance-ledger-service.js'
import { normalizeOrderItemProducts } from '../cost-center/product-normalize-service.js'
import { syncChannelCostSnapshots } from '../cost-center/cost-snapshot-service.js'
import { upsertAggregatedException } from '../cost-center/cost-exception-service.js'
import { formatShanghaiDate, shiftDate } from '../../utils/finance-date-range.js'
import {
recordPipelineError,
touchWatermark,
type FinancePipelineName,
} from './finance-pipeline-status.js'
/**
* 财务与履约管道作业。
*
* 每个作业只做一件事、可单独重跑,彼此不共享事务:
* channel_assign → carrier_dispatch → product_normalize
* → cost_snapshot → sales_facts → ledger_post
*
* 与旧 `cost_finance_sync` 的区别:旧作业把六件事串在一个函数里,
* 任一步失败就半途,而且会顺手写履约字段;这里每个作业只碰自己那一列。
*/
function jobConfig(job: JsonObject): JsonObject {
return job.config && typeof job.config === 'object' ? (job.config as JsonObject) : {}
}
function clampInt(value: unknown, fallback: number, min: number, max: number): number {
const parsed = Number(value)
if (!Number.isInteger(parsed)) return fallback
return Math.min(max, Math.max(min, parsed))
}
export async function runChannelAssignJob(job: JsonObject = {}) {
const config = jobConfig(job)
const result = await assignPendingOrderItemChannels({
batchSize: clampInt(config.batchSize, 500, 1, 5000),
maxBatches: clampInt(config.maxBatches, 20, 1, 200),
...(config.afterId != null
? { afterId: clampInt(config.afterId, 0, 0, Number.MAX_SAFE_INTEGER) }
: {}),
})
await touchWatermark('channel_assign', { lastItemId: result.nextCursor })
const refreshed = await refreshFactsForDates(result.affectedDates)
return {
status: 'ok',
message:
`渠道判定:扫描 ${result.scanned},已定 ${result.assigned},` +
`冲突 ${result.conflicted},仍待定 ${result.stillPending},回填 ${refreshed.days} 天` +
(refreshed.skippedClosed > 0 ? `(${refreshed.skippedClosed} 天已关账跳过)` : ''),
...result,
refreshedDays: refreshed.days,
skippedClosedDays: refreshed.skippedClosed,
}
}
/**
* 渠道/成本变更后,按业务日回填销售事实与总账。
*
* 事实任务只回看最近几天;补配价格、迟到分类这类变更必须按受影响日期重算,
* 否则旧日期的毛利会一直停在缺失成本/未分类。
*/
async function refreshFactsForDates(
dates: string[],
): Promise<{ days: number; skippedClosed: number }> {
const unique = [...new Set(dates.filter(Boolean))].sort()
if (unique.length === 0) return { days: 0, skippedClosed: 0 }
// 日期过多时按整段重算,避免截断导致部分日期永远不更新。
if (unique.length > 31) {
const dateFrom = unique[0]!
const dateTo = unique[unique.length - 1]!
try {
const facts = await rebuildChannelSalesDailyFacts({ dateFrom, dateTo })
await syncFinanceLedgerFromFacts({ dateFrom, dateTo })
if (facts.skippedClosedPeriods.length > 0) {
console.warn('[finance-pipeline] 部分日期已关账,事实未回填', {
dateFrom,
dateTo,
skipped: facts.skippedClosedPeriods,
})
}
return { days: unique.length, skippedClosed: facts.skippedClosedPeriods.length }
} catch {
return { days: 0, skippedClosed: 0 }
}
}
let done = 0
let skippedClosed = 0
for (const date of unique) {
try {
const facts = await rebuildChannelSalesDailyFacts({ dateFrom: date, dateTo: date })
if (facts.skippedClosedPeriods.length > 0) {
skippedClosed += facts.skippedClosedPeriods.length
console.warn('[finance-pipeline] 日期已关账,事实未回填', { date })
continue
}
await syncFinanceLedgerFromFacts({ dateFrom: date, dateTo: date })
done += 1
} catch {
// 单日失败不影响管道本身,下一轮或人工重跑会再处理。
}
}
return { days: done, skippedClosed }
}
export async function runCarrierDispatchJob(job: JsonObject = {}) {
const config = jobConfig(job)
const limit = clampInt(config.limit, 200, 1, 2000)
const cursor =
config.afterId != null
? Math.max(0, Math.trunc(Number(config.afterId)))
: await readWatermarkItemId('carrier_dispatch')
let maxId = 0
const manual = await query<{ id: number; sku_key: string; config_id: number }>(
`
SELECT oi.id, oi.manual_sku_key AS sku_key, cfg.id AS config_id
FROM order_items oi
JOIN manual_fulfillment_configs cfg ON cfg.sku_key = oi.manual_sku_key AND cfg.enabled
WHERE oi.fulfillment_status = 'assigned'
AND oi.fulfillment_channel = 'manual'
AND oi.fulfillment_config_id IS NULL
AND oi.id > $2
ORDER BY oi.id
LIMIT $1
`,
[limit, cursor],
)
let attached = 0
for (const row of manual.rows) {
const updated = await query(
`
UPDATE order_items
SET fulfillment_config_id = $2, updated_at = NOW()
WHERE id = $1 AND fulfillment_config_id IS NULL
`,
[row.id, row.config_id],
)
attached += updated.rowCount || 0
}
// 人工渠道但没有配置:进「人工 SKU 未配置」队列。
const missingManual = await query<{ id: number; sku_key: string }>(
`
SELECT oi.id, oi.manual_sku_key AS sku_key
FROM order_items oi
WHERE oi.fulfillment_status = 'assigned'
AND oi.fulfillment_channel = 'manual'
AND oi.fulfillment_config_id IS NULL
AND NOT EXISTS (
SELECT 1 FROM manual_fulfillment_configs cfg
WHERE cfg.sku_key = oi.manual_sku_key AND cfg.enabled
)
AND NOT EXISTS (
SELECT 1
FROM cost_exception_items i
JOIN cost_exceptions ce ON ce.id = i.exception_id
WHERE i.order_item_id = oi.id
AND ce.reason = 'manual_config_missing'
AND ce.status <> 'resolved'
)
AND oi.id > $2
ORDER BY oi.id
LIMIT $1
`,
[limit, cursor],
)
for (const row of missingManual.rows) {
await upsertAggregatedException({
reason: 'manual_config_missing',
scopeKey: `manual_config_missing|-|-|${row.sku_key}|manual`,
orderItemId: row.id,
detail: { skuKey: row.sku_key },
})
}
// 已配置人工 SKU、但还没确认履约的单:进入「人工成本未记录」队列。
const pendingManualCost = await query<{ id: number; sku_key: string }>(
`
SELECT oi.id, oi.manual_sku_key AS sku_key
FROM order_items oi
WHERE oi.fulfillment_status = 'assigned'
AND oi.fulfillment_channel = 'manual'
AND oi.fulfillment_config_id IS NOT NULL
AND NOT EXISTS (
SELECT 1 FROM cost_snapshots cs
WHERE cs.subject_type = 'manual_case'
AND cs.order_item_id = oi.id
AND cs.superseded_at IS NULL
)
AND NOT EXISTS (
SELECT 1
FROM cost_exception_items i
JOIN cost_exceptions ce ON ce.id = i.exception_id
WHERE i.order_item_id = oi.id
AND ce.reason = 'manual_cost_missing'
AND ce.status <> 'resolved'
)
AND oi.id > $2
ORDER BY oi.id
LIMIT $1
`,
[limit, cursor],
)
for (const row of pendingManualCost.rows) {
await upsertAggregatedException({
reason: 'manual_cost_missing',
scopeKey: `manual_cost_missing|-|-|${row.sku_key}|manual`,
orderItemId: row.id,
detail: { skuKey: row.sku_key },
})
}
// 自动发货 / 接单平台被运营指定后却没有载体:不能静默卡住,进问题队列。
const missingCarrier = await query<{ id: number; channel: string; sku_code: string }>(
`
SELECT oi.id, oi.fulfillment_channel AS channel, oi.sku_code
FROM order_items oi
WHERE oi.fulfillment_status = 'assigned'
AND oi.fulfillment_channel IN ('affiliate_dash', 'work_order')
AND NOT EXISTS (
SELECT 1 FROM fulfillment_tasks ft
WHERE ft.order_item_id = oi.id
AND ft.executor_key IN ('affiliate_dash', 'third_party_voucher')
)
AND NOT EXISTS (
SELECT 1 FROM work_orders wo WHERE wo.order_item_id = oi.id
)
AND NOT EXISTS (
SELECT 1
FROM cost_exception_items i
JOIN cost_exceptions ce ON ce.id = i.exception_id
WHERE i.order_item_id = oi.id
AND ce.reason = 'carrier_missing'
AND ce.status <> 'resolved'
)
AND oi.id > $2
ORDER BY oi.id
LIMIT $1
`,
[limit, cursor],
)
for (const row of missingCarrier.rows) {
await upsertAggregatedException({
reason: 'carrier_missing',
scopeKey: `carrier_missing|${row.channel}|${row.sku_code}`,
orderItemId: row.id,
detail: { channel: row.channel, skuCode: row.sku_code },
})
}
for (const row of [
...manual.rows,
...missingManual.rows,
...pendingManualCost.rows,
...missingCarrier.rows,
]) {
maxId = Math.max(maxId, Number(row.id))
}
const resolved = await resolveCarrierDispatchExceptions()
const nextCursor = maxId === 0 ? 0 : maxId
await touchWatermark('carrier_dispatch', { lastItemId: nextCursor })
return {
status: 'ok',
message:
`人工载体挂载 ${attached},缺配置 ${missingManual.rows.length},` +
`缺履约载体 ${missingCarrier.rows.length},异常收口 ${resolved}`,
attached,
missingManual: missingManual.rows.length,
missingCarrier: missingCarrier.rows.length,
resolved,
}
}
/**
* 载体/配置补上后,把对应异常自动关掉(每轮最多处理 500 条)。
*/
async function resolveCarrierDispatchExceptions(): Promise<number> {
// 游标会跳过已扫过的订单项;配置是后来补的,这里兜底把配置挂上。
await query(
`
UPDATE order_items oi
SET fulfillment_config_id = cfg.id, updated_at = NOW()
FROM manual_fulfillment_configs cfg
WHERE cfg.sku_key = oi.manual_sku_key
AND cfg.enabled
AND oi.fulfillment_status = 'assigned'
AND oi.fulfillment_channel = 'manual'
AND oi.fulfillment_config_id IS NULL
AND EXISTS (
SELECT 1
FROM cost_exception_items i
JOIN cost_exceptions ce ON ce.id = i.exception_id
WHERE i.order_item_id = oi.id
AND ce.reason = 'manual_config_missing'
AND ce.status <> 'resolved'
)
`,
)
const [carrier, config, manualCost] = await Promise.all([
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
JOIN order_items oi ON oi.id = i.order_item_id
WHERE ce.reason = 'carrier_missing'
AND ce.status <> 'resolved'
AND (
EXISTS (SELECT 1 FROM work_orders wo WHERE wo.order_item_id = oi.id)
OR EXISTS (
SELECT 1 FROM fulfillment_tasks ft
WHERE ft.order_item_id = oi.id
AND ft.executor_key IN ('affiliate_dash', 'third_party_voucher')
)
)
LIMIT 500
`,
),
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
JOIN order_items oi ON oi.id = i.order_item_id
WHERE ce.reason = 'manual_config_missing'
AND ce.status <> 'resolved'
AND oi.fulfillment_config_id IS NOT NULL
LIMIT 500
`,
),
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 ce.reason = 'manual_cost_missing'
AND ce.status <> 'resolved'
AND EXISTS (
SELECT 1 FROM cost_snapshots cs
WHERE cs.subject_type = 'manual_case'
AND cs.order_item_id = i.order_item_id
AND cs.superseded_at IS NULL
)
LIMIT 500
`,
),
])
let resolved = 0
resolved += await resolveExceptionsForItemsByReason(
carrier.rows.map((row) => Number(row.order_item_id)),
'carrier_missing',
)
resolved += await resolveExceptionsForItemsByReason(
config.rows.map((row) => Number(row.order_item_id)),
'manual_config_missing',
)
resolved += await resolveExceptionsForItemsByReason(
manualCost.rows.map((row) => Number(row.order_item_id)),
'manual_cost_missing',
)
return resolved
}
export async function runProductNormalizeJob(job: JsonObject = {}) {
const config = jobConfig(job)
const result = await normalizeOrderItemProducts({
batchSize: clampInt(config.batchSize, 500, 1, 5000),
maxBatches: clampInt(config.maxBatches, 20, 1, 200),
})
await touchWatermark('product_normalize', { lastItemId: result.nextCursor })
return {
status: 'ok',
message: `商品归一:扫描 ${result.scanned},命中 ${result.matched},未命中 ${result.unmatched}`,
...result,
}
}
export async function runCostSnapshotJob(job: JsonObject = {}) {
const config = jobConfig(job)
const result = await syncChannelCostSnapshots({
batchSize: clampInt(config.batchSize, 500, 1, 5000),
maxBatches: clampInt(config.maxBatches, 20, 1, 200),
})
await touchWatermark('cost_snapshot', { lastItemId: result.nextCursor })
await touchWatermark('cost_snapshot_hot', { lastItemId: result.hotCursor })
const refreshed = await refreshFactsForDates(result.affectedDates)
return {
status: 'ok',
message:
`成本快照:扫描 ${result.scanned},生成 ${result.created},` +
`替换 ${result.superseded},缺失 ${result.missing},回填 ${refreshed.days} 天` +
(result.genericMissing > 0 ? `,通用费用未解析 ${result.genericMissing} 项` : '') +
(refreshed.skippedClosed > 0 ? `(${refreshed.skippedClosed} 天已关账跳过)` : ''),
...result,
refreshedDays: refreshed.days,
skippedClosedDays: refreshed.skippedClosed,
}
}
export async function runSalesFactsJob(job: JsonObject = {}) {
const config = jobConfig(job)
const days = clampInt(config.days, 3, 1, 60)
const dateTo = formatShanghaiDate(new Date())
const dateFrom = await resolveCatchUpStart('sales_facts', days, dateTo)
const result = await rebuildChannelSalesDailyFacts({ dateFrom, dateTo })
await touchWatermark('sales_facts', { lastStatDate: result.dateTo })
return {
status: 'ok',
message: `销售事实:${result.dateFrom}~${result.dateTo} 写入 ${result.inserted} 行`,
...result,
}
}
export async function runLedgerPostJob(job: JsonObject = {}) {
const config = jobConfig(job)
const days = clampInt(config.days, 3, 1, 60)
const dateTo = formatShanghaiDate(new Date())
const dateFrom = await resolveCatchUpStart('ledger_post', days, dateTo)
const result = await syncFinanceLedgerFromFacts({ dateFrom, dateTo })
await touchWatermark('ledger_post', { lastStatDate: dateTo })
return {
status: 'ok',
message: `总账:${dateFrom}~${dateTo} 新增 ${result.created} 条,跳过已关账 ${result.skipped}`,
...result,
}
}
/** 顺序执行全部管道,供管理端「一键重算」使用。 */
export async function runFinancePipelineOnce(input: { days?: number } = {}) {
const channel = await runChannelAssignJob({ config: { batchSize: 1000, maxBatches: 50 } })
const carrier = await runCarrierDispatchJob({ config: { limit: 500 } })
const product = await runProductNormalizeJob({ config: { batchSize: 1000, maxBatches: 50 } })
const cost = await runCostSnapshotJob({ config: { batchSize: 1000, maxBatches: 50 } })
const facts = await runSalesFactsJob({ config: { days: input.days ?? 3 } })
const ledger = await runLedgerPostJob({ config: { days: input.days ?? 3 } })
return { channel, carrier, product, cost, facts, ledger }
}
const PIPELINE_RUNNERS: Record<
FinancePipelineName,
(job?: JsonObject) => Promise<Record<string, unknown>>
> = {
channel_assign: runChannelAssignJob,
carrier_dispatch: runCarrierDispatchJob,
product_normalize: runProductNormalizeJob,
cost_snapshot: runCostSnapshotJob,
sales_facts: runSalesFactsJob,
ledger_post: runLedgerPostJob,
}
/** 单独执行一个管道(排障 / 补跑),失败时把原因写进水位表。 */
export async function runSingleFinancePipeline(
pipeline: FinancePipelineName,
job: JsonObject = {},
): Promise<Record<string, unknown>> {
try {
return await PIPELINE_RUNNERS[pipeline](job)
} catch (error) {
await recordPipelineError(pipeline, error)
throw error
}
}
/**
* 计算本轮起始日期:默认回看 N 天;若水位更早(例如停机数天),
* 从水位那天补起,最多补 90 天,避免一次扫描过长。
*/
async function resolveCatchUpStart(
pipeline: 'sales_facts' | 'ledger_post',
days: number,
dateTo: string,
): Promise<string> {
const windowStart = shiftDate(dateTo, -(days - 1))
const result = await query<{ last_stat_date: string | null }>(
`SELECT last_stat_date::text FROM finance_watermarks WHERE pipeline = $1`,
[pipeline],
)
const lastDate = result.rows[0]?.last_stat_date || ''
if (!lastDate) return windowStart
const earliest = shiftDate(dateTo, -89)
const candidate = lastDate < windowStart ? lastDate : windowStart
return candidate < earliest ? earliest : candidate
}