fix(finance): 收敛内部 SKU 履约路由与载体状态
统一内部 SKU 与渠道主/兜底解析,禁止并列主渠道。 运营指定渠道改为先创建真实载体,失败保持明确 pending。 历史缺载体、多载体冲突和自动发货兜底统一由管道修复。 迁移人工配置与旧 sku_code 规则,补充严格预检和集成测试。
This commit is contained in:
@@ -1,178 +1,323 @@
|
||||
import { query } from '../../db/client.js'
|
||||
import { getOrderById } from '../../repositories/order-repo.js'
|
||||
import { syncDeliveryTasksForOrder } from '../order/delivery-task-service.js'
|
||||
import { syncWorkerOrdersForSourceOrder } from '../worker-platform/sync-worker-orders-service.js'
|
||||
import { applyIntakeChannelDecision } from './intake-channel-decision-service.js'
|
||||
import type { ResolvedFulfillmentItem } from './product-resolution-service.js'
|
||||
import type { OrderItemRow } from '../../types/repository/rows.js'
|
||||
import { logWarn } from '../../utils/logger.js'
|
||||
import { FULFILLMENT_CHANNELS, type FulfillmentChannel } from './channel-types.js'
|
||||
import { ensureCarrierForOrderItem } from './carrier-creation-service.js'
|
||||
import {
|
||||
planInternalSkuChannels,
|
||||
type InternalSkuChannelRow,
|
||||
} from './internal-sku-channel-service.js'
|
||||
|
||||
type PendingCarrierItem = {
|
||||
type CarrierCandidate = {
|
||||
id: number
|
||||
order_id: number
|
||||
sku_code: string
|
||||
sku_name: string
|
||||
quantity: number
|
||||
item_snapshot_json: unknown
|
||||
spec_json: unknown
|
||||
channel: 'affiliate_dash' | 'work_order'
|
||||
internal_sku: string
|
||||
channels: InternalSkuChannelRow[]
|
||||
}
|
||||
|
||||
function parseObject(value: unknown): Record<string, unknown> {
|
||||
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
||||
return value as Record<string, unknown>
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(String(value || '{}'))
|
||||
return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
|
||||
? (parsed as Record<string, unknown>)
|
||||
: {}
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
function normalizeChannels(value: unknown): InternalSkuChannelRow[] {
|
||||
if (!Array.isArray(value)) return []
|
||||
return value
|
||||
.filter((row): row is Record<string, unknown> => Boolean(row) && typeof row === 'object')
|
||||
.map((row) => ({
|
||||
internal_sku: String(row.internal_sku || '').trim(),
|
||||
channel: String(row.channel || '') as FulfillmentChannel,
|
||||
priority: Number(row.priority || 100),
|
||||
is_fallback: row.is_fallback === true,
|
||||
enabled: row.enabled !== false,
|
||||
canonical_product_id:
|
||||
row.canonical_product_id == null ? null : Number(row.canonical_product_id),
|
||||
config_json:
|
||||
row.config_json && typeof row.config_json === 'object'
|
||||
? (row.config_json as Record<string, unknown>)
|
||||
: {},
|
||||
source: String(row.source || ''),
|
||||
}))
|
||||
.filter((row) => FULFILLMENT_CHANNELS.includes(row.channel))
|
||||
}
|
||||
|
||||
/**
|
||||
* 为“内部 SKU 有渠道能力、但还没有载体”的 pending 单补载体。
|
||||
*
|
||||
* - 接单平台:走现有工单匹配器,能匹配模板就建工单;
|
||||
* - 自动发货:补 fulfillmentRoute/affiliateDash 后建任务;
|
||||
* - 补不出来的继续保留 no_carrier,等运营补模板/映射。
|
||||
*
|
||||
* 财务渠道判定不在本服务内做;调用方在补完载体后再跑一次 channel_assign。
|
||||
*/
|
||||
export async function reconcilePendingCarriers(input: { limit?: number } = {}): Promise<{
|
||||
scanned: number
|
||||
workOrdersCreated: number
|
||||
affiliateTasksCreated: number
|
||||
remaining: number
|
||||
}> {
|
||||
const limit = Math.min(500, Math.max(1, Math.trunc(Number(input.limit) || 200)))
|
||||
const rows = await query<PendingCarrierItem>(
|
||||
async function loadCandidateItems(input: {
|
||||
limit: number
|
||||
orderItemIds?: number[]
|
||||
assignedMissingCarrier?: boolean
|
||||
}): Promise<CarrierCandidate[]> {
|
||||
const ids = (input.orderItemIds || [])
|
||||
.map(Number)
|
||||
.filter((value) => Number.isInteger(value) && value > 0)
|
||||
const idFilter = ids.length > 0 ? 'AND oi.id = ANY($2::bigint[])' : ''
|
||||
const statusFilter = input.assignedMissingCarrier
|
||||
? `oi.fulfillment_status = 'assigned'
|
||||
AND oi.fulfillment_channel IN ('affiliate_dash', 'work_order')
|
||||
AND NOT EXISTS (SELECT 1 FROM work_orders wo WHERE wo.order_item_id = oi.id)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM fulfillment_tasks ft
|
||||
WHERE ft.order_item_id = oi.id AND ft.executor_key = 'affiliate_dash'
|
||||
)`
|
||||
: `oi.fulfillment_status = 'pending' AND oi.fulfillment_locked = FALSE`
|
||||
|
||||
const params: unknown[] = [input.limit]
|
||||
if (ids.length > 0) params.push(ids)
|
||||
const result = await query<CarrierCandidate>(
|
||||
`
|
||||
SELECT oi.id, oi.order_id, oi.sku_code, oi.sku_name, oi.quantity,
|
||||
oi.item_snapshot_json, oi.spec_json,
|
||||
cap.channel
|
||||
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 order_items oi
|
||||
JOIN LATERAL (
|
||||
SELECT c.channel
|
||||
FROM internal_sku_channels c
|
||||
WHERE c.enabled = TRUE
|
||||
AND c.channel IN ('affiliate_dash', 'work_order')
|
||||
AND btrim(c.internal_sku) = COALESCE(NULLIF(btrim(oi.manual_sku_key), ''), btrim(oi.sku_name))
|
||||
ORDER BY
|
||||
c.priority ASC,
|
||||
CASE c.channel
|
||||
WHEN 'affiliate_dash' THEN 1
|
||||
WHEN 'work_order' THEN 2
|
||||
ELSE 9
|
||||
END,
|
||||
c.channel ASC
|
||||
LIMIT 1
|
||||
) cap ON TRUE
|
||||
WHERE oi.fulfillment_status = 'pending'
|
||||
AND oi.fulfillment_locked = FALSE
|
||||
AND NOT EXISTS (SELECT 1 FROM work_orders wo WHERE wo.order_item_id = oi.id)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM fulfillment_tasks ft
|
||||
WHERE ft.order_item_id = oi.id AND ft.executor_key = 'affiliate_dash'
|
||||
)
|
||||
SELECT COALESCE(
|
||||
jsonb_agg(
|
||||
jsonb_build_object(
|
||||
'internal_sku', channel.internal_sku,
|
||||
'channel', channel.channel,
|
||||
'priority', channel.priority,
|
||||
'is_fallback', channel.is_fallback,
|
||||
'enabled', channel.enabled,
|
||||
'canonical_product_id', channel.canonical_product_id,
|
||||
'config_json', channel.config_json,
|
||||
'source', channel.source
|
||||
)
|
||||
ORDER BY channel.priority, channel.channel
|
||||
),
|
||||
'[]'::jsonb
|
||||
) AS channels
|
||||
FROM internal_sku_channels channel
|
||||
WHERE channel.enabled = TRUE
|
||||
AND btrim(channel.internal_sku) = resolve_internal_sku(
|
||||
oi.manual_sku_key, oi.sku_name, oi.sku_code
|
||||
)
|
||||
) capability ON jsonb_array_length(capability.channels) > 0
|
||||
WHERE ${statusFilter}
|
||||
${idFilter}
|
||||
ORDER BY oi.id
|
||||
LIMIT $1
|
||||
`,
|
||||
[limit],
|
||||
params,
|
||||
)
|
||||
return result.rows.map((row) => ({ ...row, channels: normalizeChannels(row.channels) }))
|
||||
}
|
||||
|
||||
async function markPendingWithoutCarrier(input: {
|
||||
itemId: number
|
||||
internalSku: string
|
||||
attempts: Array<{ channel: FulfillmentChannel; reason: string; message: string }>
|
||||
}): Promise<void> {
|
||||
await query(
|
||||
`
|
||||
UPDATE order_items
|
||||
SET fulfillment_pending_reason = 'no_carrier',
|
||||
fulfillment_pending_detail = $2::jsonb,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1 AND fulfillment_status = 'pending'
|
||||
`,
|
||||
[
|
||||
input.itemId,
|
||||
JSON.stringify({
|
||||
internalSku: input.internalSku,
|
||||
attempts: input.attempts,
|
||||
}),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
async function selectSafeFallback(input: {
|
||||
orderItemId: number
|
||||
channel: FulfillmentChannel
|
||||
primaryChannel: FulfillmentChannel
|
||||
reason: string
|
||||
includeAssignedMissingCarrier: boolean
|
||||
}): Promise<boolean> {
|
||||
const result = await query(
|
||||
`
|
||||
UPDATE order_items
|
||||
SET fulfillment_channel = $2,
|
||||
fulfillment_status = 'assigned',
|
||||
fulfillment_source = 'auto_mapping',
|
||||
fulfillment_reason = $3,
|
||||
channel_switch_reason = $3,
|
||||
channel_switched_at = NOW(),
|
||||
fulfillment_pending_reason = NULL,
|
||||
fulfillment_pending_detail = NULL,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
AND (
|
||||
(fulfillment_status = 'pending' AND fulfillment_locked = FALSE)
|
||||
OR (
|
||||
$4::boolean
|
||||
AND fulfillment_status = 'assigned'
|
||||
AND fulfillment_locked = FALSE
|
||||
AND fulfillment_source NOT IN ('operator_assigned', 'manual_confirm')
|
||||
)
|
||||
)
|
||||
`,
|
||||
[
|
||||
input.orderItemId,
|
||||
input.channel,
|
||||
`主渠道 ${input.primaryChannel} 无法创建载体:${input.reason}`,
|
||||
input.includeAssignedMissingCarrier,
|
||||
],
|
||||
)
|
||||
return (result.rowCount || 0) > 0
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 internal_sku_channels 的明确优先级补载体。
|
||||
*
|
||||
* 主渠道是 affiliate/work_order 但载体暂时创建失败时,只有显式 is_fallback 的
|
||||
* manual/voucher 才能接管。所有结果都落 pending 明细,不再静默卡住。
|
||||
*/
|
||||
export async function reconcilePendingCarriers(
|
||||
input: {
|
||||
limit?: number
|
||||
orderItemIds?: number[]
|
||||
includeAssignedMissingCarrier?: boolean
|
||||
allowFallback?: boolean
|
||||
} = {},
|
||||
): Promise<{
|
||||
scanned: number
|
||||
workOrdersCreated: number
|
||||
affiliateTasksCreated: number
|
||||
fallbacksSelected: number
|
||||
failed: number
|
||||
remaining: number
|
||||
}> {
|
||||
const limit = Math.min(500, Math.max(1, Math.trunc(Number(input.limit) || 200)))
|
||||
const rows = await loadCandidateItems({
|
||||
limit,
|
||||
assignedMissingCarrier: input.includeAssignedMissingCarrier === true,
|
||||
...(input.orderItemIds ? { orderItemIds: input.orderItemIds } : {}),
|
||||
})
|
||||
|
||||
let workOrdersCreated = 0
|
||||
let affiliateTasksCreated = 0
|
||||
const byOrder = new Map<number, PendingCarrierItem[]>()
|
||||
for (const row of rows.rows) {
|
||||
let fallbacksSelected = 0
|
||||
let failed = 0
|
||||
const byOrder = new Map<number, CarrierCandidate[]>()
|
||||
for (const row of rows) {
|
||||
const list = byOrder.get(Number(row.order_id)) || []
|
||||
list.push(row)
|
||||
byOrder.set(Number(row.order_id), list)
|
||||
}
|
||||
|
||||
for (const [orderId, items] of byOrder) {
|
||||
for (const [orderId, candidates] of byOrder) {
|
||||
const order = await getOrderById(orderId)
|
||||
if (!order) continue
|
||||
const itemRows = await query<{
|
||||
id: number
|
||||
order_id: number
|
||||
sku_code: string
|
||||
sku_name: string
|
||||
quantity: number
|
||||
item_snapshot_json: unknown
|
||||
spec_json: unknown
|
||||
}>(
|
||||
`SELECT id, order_id, sku_code, sku_name, quantity, item_snapshot_json, spec_json
|
||||
FROM order_items WHERE order_id = $1`,
|
||||
[orderId],
|
||||
)
|
||||
const itemRows = await query<OrderItemRow>(`SELECT * FROM order_items WHERE order_id = $1`, [
|
||||
orderId,
|
||||
])
|
||||
const itemById = new Map(itemRows.rows.map((item) => [Number(item.id), item]))
|
||||
|
||||
for (const target of items) {
|
||||
const item = itemById.get(Number(target.id))
|
||||
for (const candidate of candidates) {
|
||||
const item = itemById.get(Number(candidate.id))
|
||||
if (!item) continue
|
||||
|
||||
try {
|
||||
if (target.channel === 'work_order') {
|
||||
const result = await syncWorkerOrdersForSourceOrder(order, [item as never], {
|
||||
source: 'carrier_reconcile',
|
||||
autoOnly: true,
|
||||
})
|
||||
workOrdersCreated += result.created.length
|
||||
continue
|
||||
const assignedChannel = String(item.fulfillment_channel || '') as FulfillmentChannel
|
||||
const plan = planInternalSkuChannels(candidate.channels)
|
||||
const exactOnly =
|
||||
input.includeAssignedMissingCarrier === true &&
|
||||
(item.fulfillment_locked === true ||
|
||||
item.fulfillment_source === 'operator_assigned' ||
|
||||
item.fulfillment_source === 'manual_confirm')
|
||||
const attempts =
|
||||
input.includeAssignedMissingCarrier && exactOnly
|
||||
? FULFILLMENT_CHANNELS.includes(assignedChannel)
|
||||
? candidate.channels.filter((row) => row.channel === assignedChannel)
|
||||
: []
|
||||
: plan.attempts
|
||||
if (attempts.length === 0) {
|
||||
failed += 1
|
||||
if (!input.includeAssignedMissingCarrier) {
|
||||
await query(
|
||||
`UPDATE order_items
|
||||
SET fulfillment_pending_reason = 'routing_conflict',
|
||||
fulfillment_pending_detail = $2::jsonb,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1 AND fulfillment_status = 'pending'`,
|
||||
[
|
||||
item.id,
|
||||
JSON.stringify({
|
||||
internalSku: candidate.internal_sku,
|
||||
channels: plan.conflicts.map((channel) => channel.channel),
|
||||
}),
|
||||
],
|
||||
)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
const resolved = {
|
||||
...item,
|
||||
itemId: String(item.id),
|
||||
externalItemId: String(item.id),
|
||||
externalSkuCode: item.sku_code,
|
||||
externalSkuName: item.sku_name,
|
||||
skuCode: item.sku_code,
|
||||
skuName: item.sku_name,
|
||||
spec: parseObject(item.spec_json),
|
||||
snapshot: parseObject(item.item_snapshot_json),
|
||||
isConfigured: false,
|
||||
} as unknown as ResolvedFulfillmentItem
|
||||
const enriched = await applyIntakeChannelDecision(resolved, {
|
||||
provider: order.provider,
|
||||
platform: order.platform,
|
||||
shopId: order.shop_id,
|
||||
})
|
||||
const snapshot = parseObject(enriched.snapshot)
|
||||
const route = parseObject(snapshot.fulfillmentRoute)
|
||||
if (route.selectedExecutorKey !== 'affiliate_dash') continue
|
||||
const failures: Array<{ channel: FulfillmentChannel; reason: string; message: string }> = []
|
||||
let resolved = false
|
||||
for (let index = 0; index < attempts.length; index += 1) {
|
||||
const attempt = attempts[index]!
|
||||
try {
|
||||
const carrier = await ensureCarrierForOrderItem({
|
||||
order,
|
||||
item,
|
||||
channel: attempt.channel,
|
||||
})
|
||||
if (!carrier.ready) {
|
||||
failures.push({
|
||||
channel: attempt.channel,
|
||||
reason: carrier.reason,
|
||||
message: carrier.message,
|
||||
})
|
||||
const canFallback =
|
||||
input.allowFallback !== false &&
|
||||
!exactOnly &&
|
||||
index === 0 &&
|
||||
(attempt.channel === 'affiliate_dash' || attempt.channel === 'work_order')
|
||||
if (canFallback) continue
|
||||
break
|
||||
}
|
||||
|
||||
await query(
|
||||
`UPDATE order_items
|
||||
SET sku_code = $2,
|
||||
spec_json = $3,
|
||||
item_snapshot_json = $4,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1`,
|
||||
[
|
||||
item.id,
|
||||
String(enriched.skuCode || item.sku_code),
|
||||
JSON.stringify(enriched.spec || {}),
|
||||
JSON.stringify(snapshot),
|
||||
],
|
||||
)
|
||||
const tasks = await syncDeliveryTasksForOrder(order, [
|
||||
{
|
||||
...item,
|
||||
sku_code: String(enriched.skuCode || item.sku_code),
|
||||
spec_json: enriched.spec || {},
|
||||
item_snapshot_json: snapshot,
|
||||
} as never,
|
||||
])
|
||||
affiliateTasksCreated += tasks.length
|
||||
} catch (error) {
|
||||
logWarn('[carrier-reconciliation]', '补履约载体失败', {
|
||||
orderItemId: target.id,
|
||||
channel: target.channel,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
if (carrier.created && attempt.channel === 'work_order') workOrdersCreated += 1
|
||||
if (carrier.created && attempt.channel === 'affiliate_dash') affiliateTasksCreated += 1
|
||||
|
||||
const isFallbackAttempt = index > 0
|
||||
if (
|
||||
!exactOnly &&
|
||||
(attempt.channel === 'manual' ||
|
||||
attempt.channel === 'third_party_voucher' ||
|
||||
isFallbackAttempt)
|
||||
) {
|
||||
const primaryChannel = plan.primary?.channel || attempts[0]!.channel
|
||||
if (
|
||||
await selectSafeFallback({
|
||||
orderItemId: Number(item.id),
|
||||
channel: attempt.channel,
|
||||
primaryChannel,
|
||||
reason: failures[0]?.reason || 'fallback',
|
||||
includeAssignedMissingCarrier: input.includeAssignedMissingCarrier === true,
|
||||
})
|
||||
) {
|
||||
fallbacksSelected += 1
|
||||
}
|
||||
}
|
||||
resolved = true
|
||||
break
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
failures.push({ channel: attempt.channel, reason: 'exception', message })
|
||||
logWarn('[carrier-reconciliation]', '补履约载体失败', {
|
||||
orderItemId: item.id,
|
||||
channel: attempt.channel,
|
||||
error: message,
|
||||
})
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if (!resolved) {
|
||||
failed += 1
|
||||
if (!input.includeAssignedMissingCarrier) {
|
||||
await markPendingWithoutCarrier({
|
||||
itemId: Number(item.id),
|
||||
internalSku: candidate.internal_sku,
|
||||
attempts: failures,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -181,15 +326,22 @@ export async function reconcilePendingCarriers(input: { limit?: number } = {}):
|
||||
`
|
||||
SELECT count(*)::int AS count
|
||||
FROM order_items oi
|
||||
WHERE oi.fulfillment_status = 'pending'
|
||||
AND oi.fulfillment_pending_reason = 'no_carrier'
|
||||
WHERE oi.fulfillment_status IN ('pending', 'assigned')
|
||||
AND oi.fulfillment_channel IN ('affiliate_dash', 'work_order')
|
||||
AND NOT EXISTS (SELECT 1 FROM work_orders wo WHERE wo.order_item_id = oi.id)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM fulfillment_tasks ft
|
||||
WHERE ft.order_item_id = oi.id AND ft.executor_key = 'affiliate_dash'
|
||||
)
|
||||
`,
|
||||
)
|
||||
|
||||
return {
|
||||
scanned: rows.rows.length,
|
||||
scanned: rows.length,
|
||||
workOrdersCreated,
|
||||
affiliateTasksCreated,
|
||||
fallbacksSelected,
|
||||
failed,
|
||||
remaining: Number(remainingResult.rows[0]?.count || 0),
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user