修复(履约): 优化斗鱼纯读列表、同轮配置挂载与热路径有界扫描

This commit is contained in:
yml
2026-11-28 18:52:41 +08:00
parent 8a67d724c4
commit 2ec5ff7af5
14 changed files with 826 additions and 120 deletions
@@ -146,3 +146,122 @@ test(
}
},
)
test(
'已分配缺载体窄基表扫描能退回 pending/no_carrier',
{ skip: !TEST_DATABASE_URL ? '未设置 CARRIER_DISPATCH_TEST_DATABASE_URL' : false },
async () => {
process.env.DATABASE_URL = TEST_DATABASE_URL
const { closeDb, query } = await import('../../db/client.js')
const { reconcilePendingCarriers } = await import('./carrier-reconciliation-service.js')
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
const skuName = `集成已分配缺载体-${suffix}`
const missingChannelSku = `集成缺渠道阻塞-${suffix}`
let orderId = 0
let ruleId = 0
try {
const order = await query<{ id: number }>(
`INSERT INTO orders (
provider, platform, shop_id, shop_name, platform_order_id,
order_status, pay_status, total_amount, paid_at, created_at, updated_at
) VALUES (
'integration-test', 'integration-test', $1, '集成缺载体测试店', $2,
'paid', 'paid', 1000, NOW(), NOW(), NOW()
) RETURNING id`,
[`shop-${suffix}`, `IT-ASSIGNED-MISSING-${suffix}`],
)
orderId = Number(order.rows[0]!.id)
const missingChannelItem = await query<{ id: number }>(
`INSERT INTO order_items (
order_id, sku_code, sku_name, quantity, created_at, updated_at
) VALUES ($1, $2, $3, 1, NOW(), NOW())
RETURNING id`,
[orderId, `sku-missing-${suffix}`, missingChannelSku],
)
const missingChannelItemId = Number(missingChannelItem.rows[0]!.id)
const item = await query<{ id: number }>(
`INSERT INTO order_items (
order_id, sku_code, sku_name, quantity, created_at, updated_at
) VALUES ($1, $2, $3, 1, NOW(), NOW())
RETURNING id`,
[orderId, `sku-${suffix}`, skuName],
)
const orderItemId = Number(item.rows[0]!.id)
const { upsertChannelRule } = await import('./channel-assign-service.js')
const rule = await upsertChannelRule({
matchKeyType: 'internal_sku',
matchKey: skuName,
channel: 'work_order',
priority: 10,
adminUserId: null,
})
ruleId = Number(rule.id)
await query(
`UPDATE fulfillments
SET internal_sku = CASE WHEN order_item_id = $1 THEN $3 ELSE $4 END,
route_status = 'configured',
channel = 'work_order',
status = 'assigned',
carrier_status = 'missing',
issue_code = '',
issue_category = '',
pending_reason = NULL,
source = 'integration_test',
updated_at = NOW()
WHERE order_item_id = ANY($2::bigint[])`,
[missingChannelItemId, [missingChannelItemId, orderItemId], missingChannelSku, skuName],
)
// 批大小为 1 且首条无可用渠道路由时,游标仍必须前进而非重置为 0
const batch1 = await reconcilePendingCarriers({
limit: 1,
afterId: missingChannelItemId - 1,
includeAssignedMissingCarrier: true,
allowFallback: false,
})
assert.equal(batch1.scanned, 1)
assert.equal(batch1.nextCursor, missingChannelItemId)
const result = await reconcilePendingCarriers({
limit: 1,
afterId: batch1.nextCursor,
includeAssignedMissingCarrier: true,
allowFallback: false,
})
assert.equal(result.scanned, 1)
assert.equal(result.failed, 1)
const state = await query<{
status: string
channel: string | null
pending_reason: string | null
}>(`SELECT status, channel, pending_reason FROM fulfillments WHERE order_item_id = $1`, [
orderItemId,
])
assert.equal(state.rows[0]?.status, 'pending')
assert.equal(state.rows[0]?.channel, null)
assert.equal(state.rows[0]?.pending_reason, 'no_carrier')
const events = await query<{ event_type: string }>(
`SELECT event_type
FROM fulfillment_state_events
WHERE order_item_id = $1 AND event_type = 'assigned_carrier_missing'`,
[orderItemId],
)
assert.ok(events.rows.length >= 1)
} finally {
if (orderId > 0) {
await query('DELETE FROM orders WHERE id = $1', [orderId]).catch(() => undefined)
}
if (ruleId > 0) {
await query('DELETE FROM sku_channel_routes WHERE id = $1', [ruleId]).catch(() => undefined)
}
await closeDb()
}
},
)
@@ -90,81 +90,147 @@ async function loadCandidateItems(input: {
params.push(createdBefore)
cutoffFilter += ` AND oi.created_at < $${params.length}::timestamptz`
}
const statusFilter = input.assignedMissingCarrier
? `oi.fulfillment_status = 'assigned'
AND oi.stored_channel IN ('affiliate_dash', 'work_order')
AND oi.queue_bucket = 'actionable'
AND oi.pay_status = 'paid'
AND oi.order_status NOT IN ('refunded', 'cancelled', 'closed')
AND NOT EXISTS (
SELECT 1 FROM work_orders wo
WHERE wo.order_item_id = oi.id AND wo.status <> 'cancelled'
)
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 (${INACTIVE_CARRIER_TASK_STATUSES.map((status) => `'${status}'`).join(', ')})
)
AND COALESCE((
SELECT ft.result_code
FROM fulfillment_tasks ft
WHERE ft.order_item_id = oi.id AND ft.executor_key = 'affiliate_dash'
ORDER BY ft.id DESC
LIMIT 1
), '') NOT IN ('USER_APPLY_REFUND', 'affiliate_dash_cancelled')`
: `oi.fulfillment_status = 'pending'
AND oi.carrier_queue_candidate = TRUE
${
input.includeNonActionable
? `AND oi.queue_bucket IN ('actionable', 'configuration', 'operator_review')`
: `AND oi.queue_bucket = 'actionable'`
}
${input.includeLocked ? '' : 'AND oi.fulfillment_locked = FALSE'}`
const orderDirection = input.orderDirection === 'desc' ? 'DESC' : 'ASC'
const result = await query<CarrierCandidate>(
const lateralChannelsSelect = `
SELECT COALESCE(
jsonb_agg(
jsonb_build_object(
'id', route.id,
'internal_sku', sku.internal_sku_key,
'channel', route.channel,
'priority', route.priority,
'is_fallback', route.route_role = 'fallback',
'enabled', route.enabled,
'canonical_product_id', route.canonical_product_id,
'config_json', route.carrier_config_json,
'source', route.source,
'note', route.note,
'created_by_admin_user_id', route.created_by_admin_user_id
)
ORDER BY route.priority, route.channel
),
'[]'::jsonb
) AS channels
FROM sku_channel_routes route
JOIN internal_skus sku ON sku.id = route.internal_sku_id
WHERE route.enabled = TRUE
AND sku.internal_sku_key = resolve_internal_sku(
oi.manual_sku_key, oi.sku_name, oi.sku_code
)
`
const lateralChannelsSql = `
JOIN LATERAL (${lateralChannelsSelect}) capability ON jsonb_array_length(capability.channels) > 0
`
// assignedMissingCarrier 的 CTE 先 LIMIT $1;必须 LEFT JOIN 保留无渠道行以推进游标并转异常。
const assignedMissingLateralSql = `
LEFT JOIN LATERAL (${lateralChannelsSelect}) capability ON TRUE
`
const sql = input.assignedMissingCarrier
? `
WITH candidate_items AS (
SELECT
oi.id,
oi.order_id,
oi.manual_sku_key,
oi.sku_name,
oi.sku_code
FROM fulfillments f
JOIN order_items oi ON oi.id = f.order_item_id
JOIN orders o ON o.id = f.order_id
WHERE f.status = 'assigned'
AND f.channel IN ('affiliate_dash', 'work_order')
AND f.locked = FALSE
AND o.pay_status = 'paid'
AND o.order_status NOT IN ('refunded', 'cancelled', 'closed')
AND COALESCE(f.issue_code, '') NOT IN (
'user_refund',
'platform_cancelled',
'missing_internal_sku',
'missing_channel',
'manual_config_missing',
'work_rule_missing',
'affiliate_mapping_missing',
'carrier_manual_review',
'carrier_retry_pending',
'carrier_expired',
'carrier_closed'
)
AND COALESCE(f.issue_category, '') NOT IN ('configuration', 'classification', 'manual_review')
AND COALESCE(f.pending_detail ->> 'carrierIssue', '') NOT IN (
'manual_config_missing',
'work_rule_missing',
'affiliate_mapping_missing',
'missing_internal_sku',
'missing_channel',
'carrier_task_closed',
'carrier_task_user_refund',
'carrier_task_retry_pending',
'carrier_task_cancelled',
'carrier_task_expired',
'carrier_task_manual_review'
)
AND (
COALESCE(f.issue_category, '') <> 'system'
OR (
f.issue_code = 'state_inconsistent'
AND COALESCE(f.pending_detail ->> 'carrierIssue', '') IN ('', 'carrier_not_attempted')
)
)
AND NOT EXISTS (
SELECT 1 FROM work_orders wo
WHERE wo.order_item_id = f.order_item_id AND wo.status <> 'cancelled'
)
AND NOT EXISTS (
SELECT 1 FROM fulfillment_tasks ft
WHERE ft.order_item_id = f.order_item_id AND ft.executor_key = 'affiliate_dash'
AND ft.task_status NOT IN (${INACTIVE_CARRIER_TASK_STATUSES.map((status) => `'${status}'`).join(', ')})
)
AND COALESCE((
SELECT ft.result_code
FROM fulfillment_tasks ft
WHERE ft.order_item_id = f.order_item_id AND ft.executor_key = 'affiliate_dash'
ORDER BY ft.id DESC
LIMIT 1
), '') NOT IN ('USER_APPLY_REFUND', 'affiliate_dash_cancelled')
${idFilter}
${cutoffFilter}
ORDER BY oi.id ${orderDirection}
LIMIT $1
)
SELECT
oi.id,
oi.order_id,
resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code) AS internal_sku,
capability.channels
FROM candidate_items oi
${assignedMissingLateralSql}
ORDER BY oi.id ${orderDirection}
`
: `
SELECT
oi.id,
oi.order_id,
resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code) AS internal_sku,
capability.channels
FROM v_fulfillment_queue oi
JOIN LATERAL (
SELECT COALESCE(
jsonb_agg(
jsonb_build_object(
'id', route.id,
'internal_sku', sku.internal_sku_key,
'channel', route.channel,
'priority', route.priority,
'is_fallback', route.route_role = 'fallback',
'enabled', route.enabled,
'canonical_product_id', route.canonical_product_id,
'config_json', route.carrier_config_json,
'source', route.source,
'note', route.note,
'created_by_admin_user_id', route.created_by_admin_user_id
)
ORDER BY route.priority, route.channel
),
'[]'::jsonb
) AS channels
FROM sku_channel_routes route
JOIN internal_skus sku ON sku.id = route.internal_sku_id
WHERE route.enabled = TRUE
AND sku.internal_sku_key = resolve_internal_sku(
oi.manual_sku_key, oi.sku_name, oi.sku_code
)
) capability ON jsonb_array_length(capability.channels) > 0
WHERE ${statusFilter}
${lateralChannelsSql}
WHERE oi.fulfillment_status = 'pending'
AND oi.carrier_queue_candidate = TRUE
${
input.includeNonActionable
? `AND oi.queue_bucket IN ('actionable', 'configuration', 'operator_review')`
: `AND oi.queue_bucket = 'actionable'`
}
${input.includeLocked ? '' : 'AND oi.fulfillment_locked = FALSE'}
${idFilter}
${cutoffFilter}
ORDER BY oi.id ${orderDirection}
LIMIT $1
`,
params,
)
`
const result = await query<CarrierCandidate>(sql, params)
return result.rows.map((row) => ({ ...row, channels: normalizeChannels(row.channels) }))
}
@@ -367,6 +433,29 @@ export async function reconcilePendingCarriers(
eventType: 'carrier_routing_conflict',
reason: 'routing_conflict',
})
} else {
const emptyReason = !candidate.internal_sku
? 'missing_internal_sku'
: candidate.channels.length === 0
? 'missing_channel'
: 'routing_conflict'
const emptyMessage = !candidate.internal_sku
? '订单项缺少内部 SKU'
: candidate.channels.length === 0
? '未匹配到可用的启用的渠道路由规则'
: '存在多个冲突渠道,需人工核对'
await markAssignedMissingCarrierPending({
itemId: Number(item.id),
previousChannel: assignedChannel,
internalSku: candidate.internal_sku,
attempts: [
{
channel: assignedChannel,
reason: emptyReason,
message: emptyMessage,
},
],
})
}
continue
}
@@ -454,14 +543,18 @@ export async function reconcilePendingCarriers(
}
}
const remainingResult = await query<{ count: number }>(
`
SELECT count(*)::int AS count
FROM v_fulfillment_queue oi
WHERE oi.fulfillment_status = 'pending'
AND oi.carrier_queue_candidate = TRUE
`,
)
const skipRemainingCount =
input.includeAssignedMissingCarrier === true || Boolean(input.orderItemIds?.length)
const remainingResult = skipRemainingCount
? { rows: [{ count: 0 }] }
: await query<{ count: number }>(
`
SELECT count(*)::int AS count
FROM v_fulfillment_queue oi
WHERE oi.fulfillment_status = 'pending'
AND oi.carrier_queue_candidate = TRUE
`,
)
return {
scanned: rows.length,
@@ -261,6 +261,54 @@ export type AssignChannelsResult = {
pendingReasons: Record<string, number>
}
/**
* 为已进入 manual 渠道但尚未绑定人工配置的订单项同轮挂载配置。
*
* 必须先于半自动/斗鱼任务物化执行,避免刚判定为 manual 的新单因
* fulfillment_config_id 为空而错过当次物化、被迫等待定时 carrier-dispatch。
*/
async function attachManualConfigsForAssignedItems(orderItemIdsInput: number[]): Promise<number[]> {
const ids = [
...new Set(orderItemIdsInput.map(Number).filter((id) => Number.isInteger(id) && id > 0)),
]
if (ids.length === 0) return []
const matched = await query<{
order_item_id: number
config_id: number
canonical_product_id: number | null
}>(
`SELECT DISTINCT ON (oi.id)
oi.id AS order_item_id,
cfg.id AS config_id,
cfg.canonical_product_id
FROM v_order_item_current oi
JOIN manual_fulfillment_configs cfg
ON canonicalize_internal_sku(cfg.sku_key) =
resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code)
AND cfg.enabled = TRUE
WHERE oi.id = ANY($1::bigint[])
AND oi.fulfillment_status = 'assigned'
AND oi.fulfillment_channel = 'manual'
AND oi.fulfillment_config_id IS NULL
ORDER BY oi.id, cfg.id`,
[ids],
)
if (matched.rows.length === 0) return []
const configured = await attachFulfillmentConfigurations({
mappings: matched.rows.map((row) => ({
orderItemId: Number(row.order_item_id),
configId: Number(row.config_id),
...(row.canonical_product_id ? { canonicalProductId: Number(row.canonical_product_id) } : {}),
})),
expected: { status: 'assigned', channel: 'manual' },
onlyWhenConfigNull: true,
onlyWhenCanonicalProductNull: true,
})
return configured.map((row) => Number(row.id)).filter((id) => id > 0)
}
/** 批量判定:默认只扫 pending 且未锁定的订单项。 */
export async function assignPendingOrderItemChannels(
options: {
@@ -454,6 +502,12 @@ export async function assignPendingOrderItemChannels(
const affectedOrderIds = [
...new Set(updated.map((row) => Number(row.order_id)).filter((id) => id > 0)),
]
await attachManualConfigsForAssignedItems(assignedItemIds).catch((error) => {
logWarn('[channel-assign]', '人工配置同轮挂载失败,等待兜底补配', {
orderItemIds: assignedItemIds,
error: error instanceof Error ? error.message : String(error),
})
})
await ensureSemiAutoTasksForOrderItems(assignedItemIds).catch((error) => {
logWarn('[channel-assign]', '半自动任务主动物化失败,等待后台回填', {
orderItemIds: assignedItemIds,
@@ -529,6 +583,21 @@ export async function advanceFulfillmentForOrderItems(orderItemIdsInput: number[
batchSize: Math.min(500, orderItemIds.length),
maxBatches: 1,
})
const newlyConfiguredIds = await attachManualConfigsForAssignedItems(orderItemIds).catch(() => [])
if (newlyConfiguredIds.length > 0) {
await ensureSemiAutoTasksForOrderItems(newlyConfiguredIds).catch((error) => {
logWarn('[channel-assign]', '定向推进挂载配置后物化半自动任务失败', {
orderItemIds: newlyConfiguredIds,
error: error instanceof Error ? error.message : String(error),
})
})
await ensureDouyuFulfillmentTasksForOrderItems(newlyConfiguredIds).catch((error) => {
logWarn('[channel-assign]', '定向推进挂载配置后物化斗鱼领取任务失败', {
orderItemIds: newlyConfiguredIds,
error: error instanceof Error ? error.message : String(error),
})
})
}
return {
assigned: initial.assigned + final.assigned,
carrierAttempts:
@@ -58,7 +58,7 @@ test('斗鱼客户读取不再阻塞调用 live-hub,状态由 Webhook 收敛',
assert.ok(!cachedRead.includes('ensureLiveSession'))
})
test('斗鱼任务由配置挂载事件主动物化,列表只做有界缺失回填', () => {
test('斗鱼任务由配置挂载事件主动物化,列表保持纯只读不触发写入回填', () => {
const douyuService = source('../douyu-fulfillment/douyu-fulfillment-service.ts')
const financeJobs = source('../scheduler/finance-pipeline-jobs.ts')
const channelAssign = source('./channel-assign-service.ts')
@@ -71,17 +71,53 @@ test('斗鱼任务由配置挂载事件主动物化,列表只做有界缺失
douyuService.indexOf('export async function getDouyuFulfillmentSettings'),
douyuService.indexOf('export async function updateDouyuFulfillmentSettings'),
)
const webhookApply = douyuService.slice(
douyuService.indexOf('export async function applyLiveBindingStateSnapshot'),
douyuService.indexOf('function normalizeLiveTimestamp'),
)
assert.ok(listRead.includes('backfillDouyuFulfillmentTasksAutomatically'))
assert.ok(!listRead.includes('await ensureDouyuFulfillmentTasks()'))
assert.ok(!listRead.includes('backfillDouyuFulfillmentTasks'))
assert.ok(!listRead.includes('ensureDouyuFulfillmentTasks'))
assert.ok(listRead.includes('loadPendingDouyuOrderHints'))
assert.ok(settingsRead.includes('SELECT order_match_started_at'))
assert.ok(!settingsRead.includes('INSERT INTO douyu_fulfillment_settings'))
assert.ok(
webhookApply.indexOf('FROM integration_inbox') <
webhookApply.indexOf('ensureDouyuFulfillmentTasks'),
)
assert.ok(douyuService.includes('onlyMissing: true'))
assert.ok(channelAssign.includes('attachManualConfigsForAssignedItems'))
assert.ok(financeJobs.includes('ensureDouyuFulfillmentTasksForOrderItems'))
assert.ok(channelAssign.includes('ensureDouyuFulfillmentTasksForOrderItems'))
assert.ok(carrierCreation.includes('ensureDouyuFulfillmentTasksForOrderItems'))
})
test('carrier-dispatch 已分配缺载体扫描绕过 v_fulfillment_queue 宽视图直接走窄基表', () => {
const carrierReconciliation = source('./carrier-reconciliation-service.ts')
const financeJobs = source('../scheduler/finance-pipeline-jobs.ts')
const candidateSection = carrierReconciliation.slice(
carrierReconciliation.indexOf('async function loadCandidateItems'),
carrierReconciliation.indexOf('async function markPendingWithoutCarrier'),
)
assert.ok(candidateSection.includes('WITH candidate_items AS'))
assert.ok(candidateSection.includes('FROM fulfillments f'))
assert.ok(candidateSection.includes('LEFT JOIN LATERAL'))
assert.ok(carrierReconciliation.includes('emptyMessage'))
assert.ok(financeJobs.includes('carrier_assigned_repair'))
})
test('斗鱼预检提示严格要求命中 enabled 且 douyu_fulfillment_enabled=true 的人工配置', () => {
const douyuService = source('../douyu-fulfillment/douyu-fulfillment-service.ts')
const hintsSection = douyuService.slice(
douyuService.indexOf('async function loadPendingDouyuOrderHints'),
douyuService.indexOf('async function loadTaskByOrderNo'),
)
assert.ok(hintsSection.includes('matched_config_id'))
assert.ok(hintsSection.includes('if (!configMatched || !douyuEnabled) continue'))
})
test('载体冲突检查从活跃载体候选集反查,不逐订单项执行三次全表探测', () => {
const financeJobs = source('../scheduler/finance-pipeline-jobs.ts')
const conflictQuery = financeJobs.slice(