重写 120/121 迁移,统一内部 SKU、渠道 id、config_json 和旧规则转换。 后台渠道配置改读统一渠道表,卡券与人工配置不再写旧规则。 增加安全渠道切换,并排除已关闭、失败或过期的历史任务载体。 按生产 119 基线重跑迁移、完整履约财务链路和严格预检。
553 lines
21 KiB
TypeScript
553 lines
21 KiB
TypeScript
import type { JsonObject } from '../../types/json.js'
|
||
import { query } from '../../db/client.js'
|
||
import { assignPendingOrderItemChannels } from '../fulfillment/channel-assign-service.js'
|
||
import { runAffiliateFallback } from '../fulfillment/affiliate-fallback-service.js'
|
||
import { reconcilePendingCarriers } from '../fulfillment/carrier-reconciliation-service.js'
|
||
import {
|
||
resolveExceptionsForItemsByReason,
|
||
resolveOrphanCostExceptions,
|
||
upsertAggregatedExceptionsBatch,
|
||
type AggregatedExceptionEntry,
|
||
} from '../cost-center/cost-exception-service.js'
|
||
import { readWatermarkItemId } from '../watermark-store.js'
|
||
import { refreshFactsForDates } from '../finance/refresh-facts.js'
|
||
import { rebuildChannelSalesDailyFacts } from '../finance/sales-facts-channel-service.js'
|
||
import { syncFinanceLedgerFromFacts } from '../finance/finance-ledger-service.js'
|
||
import {
|
||
normalizeOrderItemProducts,
|
||
normalizeProductsForItems,
|
||
} from '../cost-center/product-normalize-service.js'
|
||
import {
|
||
syncChannelCostSnapshots,
|
||
syncCostSnapshotsForItems,
|
||
} from '../cost-center/cost-snapshot-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 })
|
||
|
||
// 刚判定渠道的订单项立刻算成本,不等冷通道扫到。
|
||
let costDates: string[] = []
|
||
if (result.assignedItemIds.length > 0) {
|
||
// 先归一商品,再算成本:卡券/自动发货没有商品就无法解析采购价。
|
||
await normalizeProductsForItems(result.assignedItemIds).catch(() => undefined)
|
||
const cost = await syncCostSnapshotsForItems(result.assignedItemIds).catch(() => null)
|
||
costDates = cost?.affectedDates || []
|
||
}
|
||
const refreshed = await refreshFactsForDates([...result.affectedDates, ...costDates])
|
||
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,
|
||
}
|
||
}
|
||
|
||
export async function runCarrierDispatchJob(job: JsonObject = {}) {
|
||
const config = jobConfig(job)
|
||
const limit = clampInt(config.limit, 200, 1, 2000)
|
||
const reconciled = await reconcilePendingCarriers({ limit: Math.min(limit, 200) })
|
||
const repairedAssigned = await reconcilePendingCarriers({
|
||
limit: Math.min(limit, 200),
|
||
includeAssignedMissingCarrier: true,
|
||
})
|
||
await assignPendingOrderItemChannels({ batchSize: 500, maxBatches: 1 }).catch(() => undefined)
|
||
const cursor =
|
||
config.afterId != null
|
||
? Math.max(0, Math.trunc(Number(config.afterId)))
|
||
: await readWatermarkItemId('carrier_dispatch')
|
||
let maxId = 0
|
||
const configKeysResult = await query<{ sku_key: string }>(
|
||
'SELECT sku_key FROM manual_fulfillment_configs WHERE enabled',
|
||
)
|
||
const configKeys = configKeysResult.rows.map((row) => row.sku_key)
|
||
|
||
const manual = await query<{ id: number; sku_key: string; config_id: number }>(
|
||
`
|
||
SELECT oi.id,
|
||
resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code) AS sku_key,
|
||
cfg.id AS config_id
|
||
FROM order_items oi
|
||
JOIN manual_fulfillment_configs cfg
|
||
ON cfg.sku_key = resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code)
|
||
AND cfg.enabled
|
||
WHERE oi.fulfillment_status = 'assigned'
|
||
AND oi.fulfillment_channel = 'manual'
|
||
AND oi.fulfillment_config_id IS NULL
|
||
AND resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code) = ANY($3::text[])
|
||
AND oi.id > $2
|
||
ORDER BY oi.id
|
||
LIMIT $1
|
||
`,
|
||
[limit, cursor, configKeys],
|
||
)
|
||
|
||
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,
|
||
resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code) 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 (resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code) = ANY($3::text[]))
|
||
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, configKeys],
|
||
)
|
||
|
||
const exceptionEntries: AggregatedExceptionEntry[] = []
|
||
for (const row of missingManual.rows) {
|
||
exceptionEntries.push({
|
||
reason: 'manual_config_missing',
|
||
scopeKey: `manual_config_missing|-|-|${row.sku_key}|manual`,
|
||
orderItemId: Number(row.id),
|
||
detail: { skuKey: row.sku_key },
|
||
})
|
||
}
|
||
|
||
// 已配置人工 SKU、但还没确认履约的单:进入「人工成本未记录」队列。
|
||
const pendingManualCost = await query<{ id: number; sku_key: string }>(
|
||
`
|
||
SELECT oi.id,
|
||
resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code) 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 reversed_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) {
|
||
exceptionEntries.push({
|
||
reason: 'manual_cost_missing',
|
||
scopeKey: `manual_cost_missing|-|-|${row.sku_key}|manual`,
|
||
orderItemId: Number(row.id),
|
||
detail: { skuKey: row.sku_key },
|
||
})
|
||
}
|
||
|
||
// 自动发货 / 接单平台被运营指定后却没有载体:不能静默卡住,进问题队列。
|
||
const missingCarrierRaw = await query<{ id: number; channel: string; sku_code: string }>(
|
||
`
|
||
SELECT oi.id, oi.fulfillment_channel AS channel, oi.sku_code
|
||
FROM order_items oi
|
||
LEFT JOIN work_orders wo ON wo.order_item_id = oi.id AND wo.status <> 'cancelled'
|
||
WHERE oi.fulfillment_status = 'assigned'
|
||
AND oi.fulfillment_channel IN ('affiliate_dash', 'work_order')
|
||
AND wo.id IS NULL
|
||
AND NOT EXISTS (
|
||
SELECT 1 FROM fulfillment_tasks ft
|
||
WHERE ft.order_item_id = oi.id
|
||
AND ft.executor_key = 'affiliate_dash'
|
||
AND ft.task_status NOT IN ('closed', 'expired', 'failed', 'manual_review', 'retry_pending', 'cancelled')
|
||
)
|
||
AND oi.id > $2
|
||
ORDER BY oi.id
|
||
LIMIT $1
|
||
`,
|
||
[limit, cursor],
|
||
)
|
||
|
||
const queuedCarrier = 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 = 'carrier_missing'
|
||
AND ce.status <> 'resolved'
|
||
`,
|
||
[missingCarrierRaw.rows.map((row) => row.id)],
|
||
)
|
||
const queuedSet = new Set(queuedCarrier.rows.map((row) => Number(row.order_item_id)))
|
||
const missingCarrier = {
|
||
rows: missingCarrierRaw.rows.filter((row) => !queuedSet.has(Number(row.id))),
|
||
}
|
||
|
||
for (const row of missingCarrier.rows) {
|
||
exceptionEntries.push({
|
||
reason: 'carrier_missing',
|
||
scopeKey: `carrier_missing|${row.channel}|${row.sku_code}`,
|
||
orderItemId: Number(row.id),
|
||
detail: { channel: row.channel, skuCode: row.sku_code },
|
||
})
|
||
}
|
||
|
||
// 已分配订单出现两个真实执行方时不能继续算正常渠道,必须进冲突队列人工处置。
|
||
const conflictingCarriers = 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 (
|
||
EXISTS (SELECT 1 FROM work_orders wo WHERE wo.order_item_id = oi.id AND wo.status <> 'cancelled')
|
||
)::int + (
|
||
EXISTS (
|
||
SELECT 1 FROM fulfillment_tasks ft
|
||
WHERE ft.order_item_id = oi.id AND ft.executor_key = 'affiliate_dash'
|
||
AND ft.task_status NOT IN ('closed', 'expired', 'failed', 'manual_review', 'retry_pending', 'cancelled')
|
||
)
|
||
)::int + (
|
||
EXISTS (
|
||
SELECT 1 FROM fulfillment_tasks ft
|
||
WHERE ft.order_item_id = oi.id AND ft.executor_key = 'manual_dispatch'
|
||
AND ft.task_status NOT IN ('closed', 'expired', 'failed', 'manual_review', 'retry_pending', 'cancelled')
|
||
)
|
||
)::int > 1
|
||
ORDER BY oi.id
|
||
LIMIT $1
|
||
`,
|
||
[limit],
|
||
)
|
||
for (const row of conflictingCarriers.rows) {
|
||
exceptionEntries.push({
|
||
reason: 'routing_conflict',
|
||
scopeKey: `routing_conflict|${row.channel}|${row.sku_code}|carrier`,
|
||
orderItemId: Number(row.id),
|
||
detail: { channel: row.channel, skuCode: row.sku_code, issue: 'multiple_carriers' },
|
||
})
|
||
}
|
||
if (exceptionEntries.length > 0) {
|
||
await upsertAggregatedExceptionsBatch(exceptionEntries)
|
||
}
|
||
|
||
for (const row of [
|
||
...manual.rows,
|
||
...missingManual.rows,
|
||
...pendingManualCost.rows,
|
||
...missingCarrier.rows,
|
||
...conflictingCarriers.rows,
|
||
]) {
|
||
maxId = Math.max(maxId, Number(row.id))
|
||
}
|
||
|
||
const resolved = await resolveCarrierDispatchExceptions()
|
||
const fallback = await runAffiliateFallback({ limit: 200 }).catch(() => ({
|
||
scanned: 0,
|
||
switched: 0,
|
||
}))
|
||
const nextCursor = maxId === 0 ? 0 : maxId
|
||
await touchWatermark('carrier_dispatch', { lastItemId: nextCursor })
|
||
return {
|
||
status: 'ok',
|
||
message:
|
||
`人工载体挂载 ${attached},缺配置 ${missingManual.rows.length},` +
|
||
`缺履约载体 ${missingCarrier.rows.length},多载体冲突 ${conflictingCarriers.rows.length},异常收口 ${resolved},` +
|
||
`自动转人工 ${fallback.switched},链路补载体 ${reconciled.workOrdersCreated + reconciled.affiliateTasksCreated + repairedAssigned.workOrdersCreated + repairedAssigned.affiliateTasksCreated},` +
|
||
`兜底 ${reconciled.fallbacksSelected + repairedAssigned.fallbacksSelected}`,
|
||
attached,
|
||
missingManual: missingManual.rows.length,
|
||
missingCarrier: missingCarrier.rows.length,
|
||
conflictingCarriers: conflictingCarriers.rows.length,
|
||
resolved,
|
||
affiliateFallback: fallback.switched,
|
||
carrierReconciliation: reconciled,
|
||
assignedCarrierRepair: repairedAssigned,
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 载体/配置补上后,把对应异常自动关掉(每轮最多处理 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 = resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code)
|
||
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 (
|
||
(oi.fulfillment_channel = 'work_order'
|
||
AND EXISTS (SELECT 1 FROM work_orders wo WHERE wo.order_item_id = oi.id AND wo.status <> 'cancelled'))
|
||
OR (oi.fulfillment_channel = 'affiliate_dash' AND EXISTS (
|
||
SELECT 1 FROM fulfillment_tasks ft
|
||
WHERE ft.order_item_id = oi.id
|
||
AND ft.executor_key = 'affiliate_dash'
|
||
AND ft.task_status NOT IN ('closed', 'expired', 'failed', 'manual_review', 'retry_pending', 'cancelled')
|
||
))
|
||
)
|
||
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 AND reversed_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)
|
||
await resolveOrphanCostExceptions().catch(() => undefined)
|
||
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 } = {}) {
|
||
// 先保证载体,再让财务镜像真实渠道;避免规则先把订单写成 assigned 却永远没有派单。
|
||
const carrier = await runCarrierDispatchJob({ config: { limit: 500 } })
|
||
const channel = await runChannelAssignJob({ config: { batchSize: 1000, maxBatches: 50 } })
|
||
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
|
||
}
|