fix(finance): 重写履约路由迁移与统一渠道配置

重写 120/121 迁移,统一内部 SKU、渠道 id、config_json 和旧规则转换。

后台渠道配置改读统一渠道表,卡券与人工配置不再写旧规则。

增加安全渠道切换,并排除已关闭、失败或过期的历史任务载体。

按生产 119 基线重跑迁移、完整履约财务链路和严格预检。
This commit is contained in:
yml2213
2026-11-02 15:29:13 +08:00
parent 2f87445ed9
commit 6bf28489e0
31 changed files with 958 additions and 464 deletions
@@ -1,5 +1,8 @@
import { query } from '../../db/client.js'
import { query, withTransaction } from '../../db/client.js'
import { closeClaimTokensByTaskId } from '../../repositories/claim-token-repo.js'
import { getOrderById } from '../../repositories/order-repo.js'
import { createTaskEvent } from '../../repositories/task-event-repo.js'
import { createWorkOrderEvent } from '../../repositories/worker-platform/work-order-event-repo.js'
import type { OrderItemRow } from '../../types/repository/rows.js'
import { createHttpError } from '../../utils/http.js'
import { nowIso } from '../../utils/time.js'
@@ -10,10 +13,10 @@ import { normalizeProductsForItems } from '../cost-center/product-normalize-serv
import { orderItemBasisDates, refreshFactsForDates } from '../finance/refresh-facts.js'
import {
FULFILLMENT_CHANNELS,
INACTIVE_CARRIER_TASK_STATUSES,
MATCH_KEY_TYPES,
RULE_SOURCES,
isFulfillmentChannel,
isMatchKeyType,
isRuleSource,
type FulfillmentChannel,
type FulfillmentSource,
@@ -21,13 +24,14 @@ import {
type RuleSource,
} from './channel-types.js'
import {
disableInternalSkuChannel,
deleteInternalSkuChannelById,
planInternalSkuChannels,
setInternalSkuPrimaryChannel,
upsertInternalSkuChannel,
type InternalSkuChannelRow,
} from './internal-sku-channel-service.js'
import { ensureCarrierForOrderItem } from './carrier-creation-service.js'
import { TASK_STATUS } from '../../domain/task-status.js'
/**
* 管道 A:渠道判定。
@@ -45,6 +49,7 @@ import { ensureCarrierForOrderItem } from './carrier-creation-service.js'
/** 数据库函数 `resolve_internal_sku` 是订单项内部 SKU 的唯一 SQL 口径。 */
const INTERNAL_SKU_SQL = `resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code)`
const ACTIVE_CARRIER_TASK_SQL = `task.task_status NOT IN (${INACTIVE_CARRIER_TASK_STATUSES.map((status) => `'${status}'`).join(', ')})`
export type ChannelRule = {
id: number
@@ -304,15 +309,17 @@ export async function assignPendingOrderItemChannels(
(COALESCE(o.paid_at, o.created_at) AT TIME ZONE 'Asia/Shanghai')::date::text
AS basis_date,
EXISTS (
SELECT 1 FROM work_orders wo WHERE wo.order_item_id = oi.id
SELECT 1 FROM work_orders wo WHERE wo.order_item_id = oi.id AND wo.status <> 'cancelled'
) AS has_work_order,
EXISTS (
SELECT 1 FROM fulfillment_tasks ft
WHERE ft.order_item_id = oi.id AND ft.executor_key = 'affiliate_dash'
SELECT 1 FROM fulfillment_tasks task
WHERE task.order_item_id = oi.id AND task.executor_key = 'affiliate_dash'
AND ${ACTIVE_CARRIER_TASK_SQL}
) AS has_affiliate_task,
EXISTS (
SELECT 1 FROM fulfillment_tasks ft
WHERE ft.order_item_id = oi.id AND ft.executor_key = 'manual_dispatch'
SELECT 1 FROM fulfillment_tasks task
WHERE task.order_item_id = oi.id AND task.executor_key = 'manual_dispatch'
AND ${ACTIVE_CARRIER_TASK_SQL}
) AS has_manual_task
FROM order_items oi
JOIN orders o ON o.id = oi.order_id
@@ -577,6 +584,205 @@ async function assignOrderItemsAfterCarrierReady(input: {
return { updated: Number(final.rows[0]?.count || assignedIds.length), carrierFailed }
}
const WORK_ORDER_SWITCH_BLOCKED = new Set([
'open',
'in_progress',
'pending_acceptance',
'problem',
'accepted',
])
const TASK_SWITCH_BLOCKED = new Set<string>([
TASK_STATUS.REDEEMING,
TASK_STATUS.DISPATCHED_PENDING_RETURN,
TASK_STATUS.COMPLETED,
TASK_STATUS.REDEEMED,
])
/**
* 显式切换渠道:先取消尚未实际履约的旧载体,再创建新载体。
* 已经成功或进入实际交付阶段的订单不允许自动切换。
*/
export async function switchChannelForOrderItems(input: {
orderItemIds: number[]
channel: string
adminUserId: number | null
note?: string
}): Promise<{
switched: number
failed: number
errors: Array<{ orderItemId: number; reason: string }>
}> {
if (!isFulfillmentChannel(input.channel)) {
throw createHttpError('渠道无效', { statusCode: 400, errorCode: 'invalid_channel' })
}
const ids = [
...new Set(input.orderItemIds.map(Number).filter((id) => Number.isInteger(id) && id > 0)),
]
if (ids.length === 0) {
throw createHttpError('请选择订单项', { statusCode: 400, errorCode: 'order_item_required' })
}
const items = (
await query<OrderItemRow>(`SELECT * FROM order_items WHERE id = ANY($1::bigint[])`, [ids])
).rows
const orderIds = [...new Set(items.map((item) => Number(item.order_id)))]
const orders = new Map(
(await Promise.all(orderIds.map((orderId) => getOrderById(orderId))))
.filter((order): order is NonNullable<typeof order> => Boolean(order))
.map((order) => [Number(order.id), order]),
)
const readyIds: number[] = []
const errors: Array<{ orderItemId: number; reason: string }> = []
for (const item of items) {
const order = orders.get(Number(item.order_id))
if (!order) {
errors.push({ orderItemId: Number(item.id), reason: 'order_not_found' })
continue
}
if (item.fulfillment_status === 'archived') {
errors.push({ orderItemId: Number(item.id), reason: 'archived' })
continue
}
if (item.fulfillment_channel === input.channel) {
readyIds.push(Number(item.id))
continue
}
try {
const workOrders = await query<{ id: number; status: string }>(
`SELECT id, status FROM work_orders
WHERE order_item_id = $1 AND status <> 'cancelled'`,
[item.id],
)
const blockedWorkOrder = workOrders.rows.find((row) =>
WORK_ORDER_SWITCH_BLOCKED.has(String(row.status)),
)
if (blockedWorkOrder) {
throw createHttpError('旧接单工单已进入履约阶段,不能自动切换渠道', {
statusCode: 409,
errorCode: 'channel_switch_work_order_active',
})
}
const tasks = await query<{ id: number; task_status: string }>(
`SELECT id, task_status FROM fulfillment_tasks WHERE order_item_id = $1`,
[item.id],
)
const blockedTask = tasks.rows.find((row) => TASK_SWITCH_BLOCKED.has(String(row.task_status)))
if (blockedTask) {
throw createHttpError('旧履约任务已进入实际交付阶段,不能自动切换渠道', {
statusCode: 409,
errorCode: 'channel_switch_task_active',
})
}
const now = nowIso()
await withTransaction(async (client) => {
const locked = await client.query<OrderItemRow>(
`SELECT * FROM order_items WHERE id = $1 FOR UPDATE`,
[item.id],
)
if (!locked.rows[0] || locked.rows[0].fulfillment_status === 'archived') {
throw createHttpError('订单项状态已变化', {
statusCode: 409,
errorCode: 'channel_switch_order_item_changed',
})
}
for (const workOrder of workOrders.rows) {
await client.query(
`UPDATE work_orders
SET status = 'cancelled', assigned_worker_id = NULL, assigned_at = NULL,
deadline_at = NULL, published_at = NULL, updated_at = $2
WHERE id = $1 AND status <> 'cancelled'`,
[workOrder.id, now],
)
}
for (const task of tasks.rows) {
await client.query(
`UPDATE fulfillment_tasks
SET task_status = $2, delivery_status = 'closed', result_code = 'closed_by_channel_switch',
result_message = $3, user_action_status = 'closed', claim_expires_at = $4,
updated_at = $4
WHERE id = $1`,
[task.id, TASK_STATUS.CLOSED, '履约渠道已切换,原任务关闭', now],
)
}
await client.query(
`UPDATE cost_snapshots
SET superseded_at = $2
WHERE order_item_id = $1 AND superseded_at IS NULL AND reversed_at IS NULL`,
[item.id, now],
)
await client.query(
`UPDATE order_items
SET original_channel = COALESCE(original_channel, fulfillment_channel),
fulfillment_channel = NULL,
fulfillment_status = 'pending',
fulfillment_source = 'operator_assigned',
fulfillment_locked = FALSE,
fulfillment_reason = $2,
channel_switch_reason = 'operator',
channel_switched_at = $3,
canonical_product_id = NULL,
fulfillment_config_id = NULL,
fulfillment_pending_reason = NULL,
fulfillment_pending_detail = NULL,
updated_at = $3
WHERE id = $1`,
[item.id, String(input.note || '运营切换履约渠道').slice(0, 200), now],
)
})
for (const workOrder of workOrders.rows) {
await createWorkOrderEvent({
workOrderId: Number(workOrder.id),
actorType: 'admin',
actorId: String(input.adminUserId || ''),
eventType: 'cancelled_by_channel_switch',
fromStatus: workOrder.status,
toStatus: 'cancelled',
payloadJson: JSON.stringify({ channel: input.channel, note: input.note || '' }),
now,
})
}
for (const task of tasks.rows) {
await closeClaimTokensByTaskId(Number(task.id), now)
await createTaskEvent(
Number(task.id),
'task_closed_by_channel_switch',
{ channel: input.channel, note: input.note || '', previousStatus: task.task_status },
now,
)
}
readyIds.push(Number(item.id))
} catch (error) {
errors.push({
orderItemId: Number(item.id),
reason: error instanceof Error ? error.message : String(error),
})
}
}
const assigned = await assignOrderItemsAfterCarrierReady({
orderItemIds: readyIds,
channel: input.channel,
source: 'operator_assigned',
lock: true,
note: input.note,
})
await query(
`UPDATE order_items
SET fulfillment_decided_by = $2, fulfillment_decided_at = NOW()
WHERE id = ANY($1::bigint[])`,
[readyIds, input.adminUserId],
)
return {
switched: assigned.updated,
failed: errors.length + assigned.carrierFailed,
errors,
}
}
/** 运营指定渠道:先保证真实载体,成功后才写入并锁定。 */
export async function assignChannelToOrderItems(input: {
orderItemIds: number[]
@@ -700,8 +906,8 @@ export async function assignChannelByInternalSku(input: {
internalSku: string
channel: string
adminUserId: number | null
note?: string
createRule?: boolean
note?: string | undefined
createRule?: boolean | undefined
}): Promise<{ updated: number; ruleCreated: boolean; carrierFailed: number }> {
if (!isFulfillmentChannel(input.channel)) {
throw createHttpError('渠道无效', { statusCode: 400, errorCode: 'invalid_channel' })
@@ -713,6 +919,12 @@ export async function assignChannelByInternalSku(input: {
errorCode: 'internal_sku_required',
})
}
if (input.createRule === false) {
throw createHttpError('内部 SKU 渠道配置必须持久化,不能只改当前订单', {
statusCode: 400,
errorCode: 'persistent_channel_rule_required',
})
}
const idsResult = await query<{ id: number }>(
`
@@ -743,24 +955,11 @@ export async function assignChannelByInternalSku(input: {
canonicalProductId: product.rows[0]?.id == null ? null : Number(product.rows[0].id),
source: 'operator',
configJson: { note: String(input.note || '').slice(0, 200) },
note: input.note,
adminUserId: input.adminUserId,
})
let ruleCreated = false
if (input.createRule !== false) {
const rule = await upsertChannelRule({
provider: input.provider,
shopId: input.shopId,
matchKeyType: 'internal_sku',
matchKey: internalSku,
channel: input.channel,
priority: 10,
source: 'operator',
enabled: true,
note: `运营在待分类队列指定:${String(input.note || '').slice(0, 120)}`,
adminUserId: input.adminUserId,
})
ruleCreated = rule.id > 0
}
const ruleCreated = true
const ids = idsResult.rows.map((row) => Number(row.id))
const applied = await assignOrderItemsAfterCarrierReady({
@@ -787,8 +986,8 @@ export async function assignChannelBySku(input: {
skuCode: string
channel: string
adminUserId: number | null
note?: string
createRule?: boolean
note?: string | undefined
createRule?: boolean | undefined
}): Promise<{ updated: number; ruleCreated: boolean; carrierFailed: number }> {
if (!isFulfillmentChannel(input.channel)) {
throw createHttpError('渠道无效', { statusCode: 400, errorCode: 'invalid_channel' })
@@ -813,48 +1012,24 @@ export async function assignChannelBySku(input: {
const internalSkus = [
...new Set(idsResult.rows.map((row) => String(row.internal_sku || '').trim()).filter(Boolean)),
]
if (internalSkus.length === 1) {
await setInternalSkuPrimaryChannel({
internalSku: internalSkus[0]!,
channel: input.channel,
source: 'operator',
configJson: { note: String(input.note || '').slice(0, 200) },
if (internalSkus.length === 0) {
return { updated: 0, ruleCreated: false, carrierFailed: 0 }
}
if (internalSkus.length > 1) {
throw createHttpError('同一平台 SKU 对应多个内部 SKU,请按内部 SKU 指定渠道', {
statusCode: 409,
errorCode: 'sku_code_ambiguous_internal_sku',
})
}
// 默认同时落一条渠道规则:否则同 SKU 的下一单还是会进待分类。
let ruleCreated = false
if (input.createRule !== false) {
const rule = await upsertChannelRule({
provider: input.provider,
shopId: input.shopId,
matchKeyType: 'sku_code',
matchKey: input.skuCode,
channel: input.channel,
priority: 10,
source: 'operator',
enabled: true,
note: `运营在待分类队列指定:${String(input.note || '').slice(0, 120)}`,
adminUserId: input.adminUserId,
})
ruleCreated = rule.id > 0
}
const ids = idsResult.rows.map((row) => Number(row.id))
const applied = await assignOrderItemsAfterCarrierReady({
orderItemIds: ids,
return assignChannelByInternalSku({
provider: input.provider,
shopId: input.shopId,
internalSku: internalSkus[0]!,
channel: input.channel,
source: 'operator_assigned',
lock: true,
adminUserId: input.adminUserId,
note: input.note,
createRule: input.createRule,
})
await query(
`UPDATE order_items
SET fulfillment_decided_by = $2, fulfillment_decided_at = NOW()
WHERE id = ANY($1::bigint[])`,
[ids, input.adminUserId],
)
return { ...applied, ruleCreated }
}
export async function listChannelRules(
@@ -877,19 +1052,26 @@ export async function listChannelRules(
const rows = await query<ChannelRule>(
`
SELECT id, provider, shop_id, match_key_type, match_key, channel, priority, enabled
FROM sku_channel_rules
FROM (
SELECT id, ''::text AS provider, ''::text AS shop_id,
'internal_sku'::text AS match_key_type, internal_sku AS match_key,
channel, priority, enabled
FROM internal_sku_channels
) internal_rules
${where}
ORDER BY priority, channel, match_key
`,
params,
)
return rows.rows
return rows.rows.map((row) => ({
...row,
id: Number(row.id),
priority: Number(row.priority),
}))
}
export async function upsertChannelRule(input: {
id?: number
provider?: string
shopId?: string
matchKeyType: string
matchKey: string
channel: string
@@ -899,8 +1081,8 @@ export async function upsertChannelRule(input: {
note?: string
adminUserId: number | null
}): Promise<{ id: number }> {
if (!isMatchKeyType(input.matchKeyType)) {
throw createHttpError('匹配键类型无效', {
if (input.matchKeyType !== 'internal_sku') {
throw createHttpError('渠道配置只接受内部 SKU;旧 sku_code 规则仅用于一次性迁移', {
statusCode: 400,
errorCode: 'invalid_match_key_type',
})
@@ -914,48 +1096,19 @@ export async function upsertChannelRule(input: {
throw createHttpError('匹配键不能为空', { statusCode: 400, errorCode: 'match_key_required' })
}
const result = await query<{ id: number }>(
`
INSERT INTO sku_channel_rules (
provider, shop_id, match_key_type, match_key, channel, priority,
source, enabled, note, created_by_admin_user_id, created_at, updated_at
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, NOW(), NOW())
ON CONFLICT (provider, shop_id, match_key_type, match_key, channel)
DO UPDATE SET
priority = EXCLUDED.priority,
enabled = EXCLUDED.enabled,
note = EXCLUDED.note,
updated_at = NOW()
RETURNING id
`,
[
String(input.provider || '').trim(),
String(input.shopId || '').trim(),
input.matchKeyType,
matchKey,
input.channel,
Math.trunc(Number(input.priority) || 100),
source,
input.enabled !== false,
String(input.note || '').slice(0, 200),
input.adminUserId,
],
)
if (input.matchKeyType === 'internal_sku') {
await upsertInternalSkuChannel({
internalSku: matchKey,
channel: input.channel,
priority: Math.trunc(Number(input.priority) || 100),
isFallback: Math.trunc(Number(input.priority) || 100) >= 90,
enabled: input.enabled !== false,
source: source === 'operator' ? 'operator' : `rule:${source}`,
replacePriority: true,
})
}
return { id: result.rows[0]!.id }
const priority = Math.trunc(Number(input.priority) || 100)
const id = await upsertInternalSkuChannel({
internalSku: matchKey,
channel: input.channel,
priority,
isFallback: priority >= 90,
enabled: input.enabled !== false,
source: source === 'operator' ? 'operator' : `rule:${source}`,
note: String(input.note || '').slice(0, 300),
adminUserId: input.adminUserId,
replacePriority: true,
})
return { id }
}
export async function deleteChannelRule(ruleId: number): Promise<{ deleted: boolean }> {
@@ -963,25 +1116,7 @@ export async function deleteChannelRule(ruleId: number): Promise<{ deleted: bool
if (id <= 0) {
throw createHttpError('规则 id 无效', { statusCode: 400, errorCode: 'invalid_rule_id' })
}
const result = await query<{
id: number
match_key_type: string
match_key: string
channel: string
}>(
`DELETE FROM sku_channel_rules
WHERE id = $1
RETURNING id, match_key_type, match_key, channel`,
[id],
)
const deleted = result.rows[0]
if (deleted?.match_key_type === 'internal_sku' && isFulfillmentChannel(deleted.channel)) {
await disableInternalSkuChannel({
internalSku: deleted.match_key,
channel: deleted.channel,
})
}
return { deleted: Boolean(deleted) }
return { deleted: await deleteInternalSkuChannelById(id) }
}
async function loadEnabledRules(): Promise<ChannelRule[]> {
@@ -992,7 +1127,11 @@ async function loadEnabledRules(): Promise<ChannelRule[]> {
WHERE enabled = TRUE
`,
)
return rows.rows
return rows.rows.map((row) => ({
...row,
id: Number(row.id),
priority: Number(row.priority),
}))
}
async function loadInternalSkuChannelsForKeys(
@@ -1004,8 +1143,8 @@ async function loadInternalSkuChannelsForKeys(
const rows = await query<InternalSkuChannelRow>(
`
SELECT internal_sku, channel, priority, is_fallback, enabled,
canonical_product_id, config_json, source
SELECT id, internal_sku, channel, priority, is_fallback, enabled,
canonical_product_id, config_json, source, note, created_by_admin_user_id
FROM internal_sku_channels
WHERE enabled = TRUE AND btrim(internal_sku) = ANY($1::text[])
ORDER BY internal_sku, priority, channel
@@ -1029,19 +1168,23 @@ export const CHANNEL_VALUES = FULFILLMENT_CHANNELS
export async function ensureVoucherRuleForSku(skuCode: string): Promise<boolean> {
const key = String(skuCode || '').trim()
if (!key) return false
const result = await query<{ id: number }>(
`
INSERT INTO sku_channel_rules (
provider, shop_id, match_key_type, match_key, channel, priority,
source, enabled, note, created_at, updated_at
)
VALUES ('', '', 'sku_code', $1, 'third_party_voucher', 70, 'voucher', TRUE, '卡券商品自动生成', NOW(), NOW())
ON CONFLICT (provider, shop_id, match_key_type, match_key, channel) DO NOTHING
RETURNING id
`,
[key],
const product = await query<{ id: number }>(
`SELECT id FROM product_catalog
WHERE canonical_sku = $1 AND status = 'active'
LIMIT 1`,
[`tpv:${key}`],
)
return (result.rowCount || 0) > 0
await upsertInternalSkuChannel({
internalSku: key,
channel: 'third_party_voucher',
priority: 10,
isFallback: false,
enabled: true,
canonicalProductId: Number(product.rows[0]?.id || 0) || null,
configJson: { voucherSku: key },
source: 'voucher',
})
return true
}
/**
@@ -1054,28 +1197,38 @@ export async function ensureVoucherChannelRules(): Promise<{
created: number
productCount: number
}> {
await query(
`UPDATE internal_sku_channels channel
SET is_fallback = TRUE,
priority = GREATEST(priority, 90),
updated_at = NOW()
FROM product_catalog product
WHERE product.status = 'active'
AND product.canonical_sku LIKE 'tpv:%'
AND BTRIM(channel.internal_sku) = BTRIM(product.canonical_name)
AND channel.channel <> 'third_party_voucher'
AND channel.enabled = TRUE
AND channel.is_fallback = FALSE`,
)
const created = await query<{ id: number }>(
`
INSERT INTO sku_channel_rules (
provider, shop_id, match_key_type, match_key, channel, priority,
source, enabled, note, created_at, updated_at
INSERT INTO internal_sku_channels (
internal_sku, channel, priority, is_fallback, enabled,
canonical_product_id, config_json, source, created_at, updated_at
)
SELECT
'', '', 'sku_code', substring(p.canonical_sku from 5), 'third_party_voucher', 70,
'voucher', TRUE, '卡券商品自动生成', NOW(), NOW()
BTRIM(p.canonical_name), 'third_party_voucher', 10, FALSE, TRUE,
p.id, jsonb_build_object('voucherSku', substring(p.canonical_sku from 5)),
'voucher', NOW(), NOW()
FROM product_catalog p
WHERE p.status = 'active'
AND p.canonical_sku LIKE 'tpv:%'
AND btrim(substring(p.canonical_sku from 5)) <> ''
AND NOT EXISTS (
SELECT 1 FROM sku_channel_rules r
WHERE r.provider = ''
AND r.shop_id = ''
AND r.match_key_type = 'sku_code'
AND r.match_key = substring(p.canonical_sku from 5)
AND r.channel = 'third_party_voucher'
)
ON CONFLICT DO NOTHING
AND BTRIM(COALESCE(p.canonical_name, '')) <> ''
ON CONFLICT (internal_sku, channel) DO UPDATE SET
enabled = TRUE,
canonical_product_id = COALESCE(EXCLUDED.canonical_product_id, internal_sku_channels.canonical_product_id),
config_json = internal_sku_channels.config_json || EXCLUDED.config_json,
updated_at = NOW()
RETURNING id
`,
)