feat(finance): 商品渠道能力、自动发货转人工与成本异常收口

- 商品可同时支持自动发货/人工,新增渠道能力与成本冲销字段
- 卡券缺商品时按内部中文 SKU 自动建 tpv: 商品并补渠道规则
- 自动发货失败转人工并冲销原渠道成本
- 配置成本后按最早缺失订单生效并立即补算、关闭异常
- tpv: 商品来源计入第三方卡券
This commit is contained in:
yml2213
2026-11-02 13:17:15 +08:00
parent 86b5347e40
commit 3c4c81003f
16 changed files with 532 additions and 34 deletions
@@ -0,0 +1,12 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { AFFILIATE_FAILURE_STATUSES } from './affiliate-fallback-service.js'
test('自动发货失败状态全部纳入转人工', () => {
for (const status of ['closed', 'expired', 'manual_review', 'retry_pending', 'cancelled']) {
assert.ok(AFFILIATE_FAILURE_STATUSES.includes(status as never))
}
assert.ok(!AFFILIATE_FAILURE_STATUSES.includes('redeemed' as never))
assert.ok(!AFFILIATE_FAILURE_STATUSES.includes('waiting_binding' as never))
})
@@ -0,0 +1,122 @@
import { query, withTransaction } from '../../db/client.js'
import { syncCostSnapshotsForItems } from '../cost-center/cost-snapshot-service.js'
import { refreshFactsForDates } from '../finance/refresh-facts.js'
/**
* 自动发货失败 → 人工兜底。
*
* 触发:该订单项最新一条 affiliate_dash 任务处于失败状态,且没有任何成功任务。
* 切换后:原渠道成本(sys_affiliate_purchase)冲销,人工成本等确认时再记;
* 自动任务本身不改状态,只记录订单项的切换原因,避免重复触发。
*/
export const AFFILIATE_FAILURE_STATUSES = [
'closed',
'expired',
'manual_review',
'retry_pending',
'cancelled',
] as const
const AFFILIATE_SUCCESS_STATUSES = ['redeemed', 'paid'] as const
export async function runAffiliateFallback(
options: { limit?: number } = {},
): Promise<{ scanned: number; switched: number }> {
const limit = Math.min(1000, Math.max(1, Math.trunc(options.limit || 200)))
const candidates = await query<{
id: number
order_item_id: number
provider: string
shop_id: string
manual_sku_key: string | null
sku_name: string
config_id: number | null
basis_date: string
}>(
`
SELECT
oi.id,
oi.id AS order_item_id,
o.provider,
o.shop_id,
oi.manual_sku_key,
oi.sku_name,
cfg.id AS config_id,
(COALESCE(o.paid_at, o.created_at) AT TIME ZONE 'Asia/Shanghai')::date::text AS basis_date
FROM order_items oi
JOIN orders o ON o.id = oi.order_id
LEFT 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 = 'affiliate_dash'
AND oi.fulfillment_locked = FALSE
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 = ANY($1::text[])
)
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 = ANY($2::text[])
)
ORDER BY oi.id
LIMIT $3
`,
[AFFILIATE_FAILURE_STATUSES, AFFILIATE_SUCCESS_STATUSES, limit],
)
const switchedIds: number[] = []
const affectedDates = new Set<string>()
for (const row of candidates.rows) {
const updated = await withTransaction(async (client) => {
const result = await client.query(
`
UPDATE order_items
SET
original_channel = COALESCE(original_channel, 'affiliate_dash'),
fulfillment_channel = 'manual',
fulfillment_status = 'assigned',
fulfillment_source = 'affiliate_fallback',
channel_switch_reason = 'affiliate_failed',
channel_switched_at = NOW(),
fulfillment_config_id = COALESCE(fulfillment_config_id, $2),
updated_at = NOW()
WHERE id = $1
AND fulfillment_status = 'assigned'
AND fulfillment_channel = 'affiliate_dash'
AND fulfillment_locked = FALSE
RETURNING id
`,
[row.id, row.config_id],
)
if ((result.rowCount || 0) === 0) return false
await client.query(
`
UPDATE cost_snapshots
SET reversed_at = NOW(), reversal_reason = 'affiliate_failed'
WHERE order_item_id = $1
AND cost_item_id = (SELECT id FROM cost_items WHERE code = 'sys_affiliate_purchase')
AND superseded_at IS NULL AND reversed_at IS NULL
AND reversed_at IS NULL
`,
[row.id],
)
return true
})
if (!updated) continue
switchedIds.push(Number(row.id))
affectedDates.add(row.basis_date)
}
for (const id of switchedIds) {
await syncCostSnapshotsForItems([id]).catch(() => undefined)
}
await refreshFactsForDates([...affectedDates]).catch(() => undefined)
return { scanned: candidates.rows.length, switched: switchedIds.length }
}