455 lines
15 KiB
TypeScript
455 lines
15 KiB
TypeScript
import { query, withTransaction } from '../../db/client.js'
|
|
import { getOrderById } from '../../repositories/order-repo.js'
|
|
import type { OrderItemRow } from '../../types/repository/rows.js'
|
|
import { logWarn } from '../../utils/logger.js'
|
|
import {
|
|
FULFILLMENT_CHANNELS,
|
|
INACTIVE_CARRIER_TASK_STATUSES,
|
|
type FulfillmentChannel,
|
|
} from './channel-types.js'
|
|
import { ensureCarrierForOrderItem } from './carrier-creation-service.js'
|
|
import {
|
|
transitionFulfillmentState,
|
|
transitionFulfillmentStateWithExecutor,
|
|
} from './fulfillment-state-service.js'
|
|
import {
|
|
planInternalSkuChannels,
|
|
type InternalSkuChannelRow,
|
|
} from './internal-sku-channel-service.js'
|
|
import { scheduleVoucherConsumeForOrderItems } from './voucher-consume-queue-service.js'
|
|
|
|
type CarrierCandidate = {
|
|
id: number
|
|
order_id: number
|
|
internal_sku: string
|
|
channels: InternalSkuChannelRow[]
|
|
}
|
|
|
|
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) => ({
|
|
id: Number(row.id || 0),
|
|
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 || ''),
|
|
note: String(row.note || ''),
|
|
created_by_admin_user_id:
|
|
row.created_by_admin_user_id == null ? null : Number(row.created_by_admin_user_id),
|
|
}))
|
|
.filter((row) => FULFILLMENT_CHANNELS.includes(row.channel))
|
|
}
|
|
|
|
async function loadCandidateItems(input: {
|
|
limit: number
|
|
orderItemIds?: number[]
|
|
assignedMissingCarrier?: boolean
|
|
afterId?: number
|
|
includeLocked?: boolean
|
|
cutoffCreatedAt?: string
|
|
}): Promise<CarrierCandidate[]> {
|
|
const ids = (input.orderItemIds || [])
|
|
.map(Number)
|
|
.filter((value) => Number.isInteger(value) && value > 0)
|
|
const params: unknown[] = [input.limit]
|
|
let idFilter = ''
|
|
if (ids.length > 0) {
|
|
params.push(ids)
|
|
idFilter = `AND oi.id = ANY($${params.length}::bigint[])`
|
|
} else if (Number(input.afterId || 0) > 0) {
|
|
params.push(Math.max(0, Math.trunc(Number(input.afterId))))
|
|
idFilter = `AND oi.id > $${params.length}`
|
|
}
|
|
const cutoffCreatedAt = String(input.cutoffCreatedAt || '').trim()
|
|
let cutoffFilter = ''
|
|
if (cutoffCreatedAt && Number.isFinite(Date.parse(cutoffCreatedAt))) {
|
|
params.push(cutoffCreatedAt)
|
|
cutoffFilter = `AND oi.created_at >= $${params.length}::timestamptz`
|
|
}
|
|
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 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'
|
|
${input.includeLocked ? '' : 'AND oi.fulfillment_locked = FALSE'}`
|
|
|
|
const result = await query<CarrierCandidate>(
|
|
`
|
|
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 COALESCE(
|
|
jsonb_agg(
|
|
jsonb_build_object(
|
|
'id', channel.id,
|
|
'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
|
|
,'note', channel.note
|
|
,'created_by_admin_user_id', channel.created_by_admin_user_id
|
|
)
|
|
ORDER BY channel.priority, channel.channel
|
|
),
|
|
'[]'::jsonb
|
|
) AS channels
|
|
FROM internal_sku_channels channel
|
|
WHERE channel.enabled = TRUE
|
|
AND canonicalize_internal_sku(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}
|
|
${cutoffFilter}
|
|
ORDER BY oi.id
|
|
LIMIT $1
|
|
`,
|
|
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> {
|
|
const carrierIssue = input.attempts[0]?.reason || 'carrier_attempt_failed'
|
|
await transitionFulfillmentState({
|
|
orderItemId: input.itemId,
|
|
expected: { status: 'pending' },
|
|
patch: {
|
|
pendingReason: 'no_carrier',
|
|
pendingDetail: {
|
|
internalSku: input.internalSku,
|
|
carrierIssue,
|
|
carrierMessage: input.attempts[0]?.message || '',
|
|
attempts: input.attempts,
|
|
},
|
|
},
|
|
eventType: 'carrier_attempt_failed',
|
|
reason: carrierIssue,
|
|
})
|
|
}
|
|
|
|
async function markAssignedMissingCarrierPending(input: {
|
|
itemId: number
|
|
previousChannel: string
|
|
internalSku: string
|
|
attempts: Array<{ channel: FulfillmentChannel; reason: string; message: string }>
|
|
}): Promise<void> {
|
|
const carrierIssue = input.attempts[0]?.reason || 'carrier_attempt_failed'
|
|
await transitionFulfillmentState({
|
|
orderItemId: input.itemId,
|
|
expected: { status: 'assigned' },
|
|
patch: {
|
|
status: 'pending',
|
|
channel: null,
|
|
source: 'auto_mapping',
|
|
locked: false,
|
|
pendingReason: 'no_carrier',
|
|
pendingDetail: {
|
|
internalSku: input.internalSku,
|
|
previousChannel: input.previousChannel,
|
|
carrierIssue,
|
|
carrierMessage: input.attempts[0]?.message || '',
|
|
attempts: input.attempts,
|
|
},
|
|
},
|
|
eventType: 'assigned_carrier_missing',
|
|
reason: carrierIssue,
|
|
})
|
|
}
|
|
|
|
async function selectSafeFallback(input: {
|
|
orderItemId: number
|
|
channel: FulfillmentChannel
|
|
primaryChannel: FulfillmentChannel
|
|
reason: string
|
|
includeAssignedMissingCarrier: boolean
|
|
}): Promise<boolean> {
|
|
const reason = `主渠道 ${input.primaryChannel} 无法创建载体:${input.reason}`
|
|
const updated = await withTransaction(async (client) => {
|
|
const common = {
|
|
orderItemId: input.orderItemId,
|
|
patch: {
|
|
status: 'assigned' as const,
|
|
channel: input.channel,
|
|
source: 'auto_mapping',
|
|
reason,
|
|
switchReason: reason,
|
|
switchedAt: new Date().toISOString(),
|
|
canonicalProductId: null,
|
|
configId: null,
|
|
pendingReason: null,
|
|
pendingDetail: null,
|
|
},
|
|
eventType: 'fallback_carrier_selected',
|
|
reason,
|
|
}
|
|
const pending = await transitionFulfillmentStateWithExecutor(client, {
|
|
...common,
|
|
expected: { status: 'pending', locked: false },
|
|
})
|
|
if (pending) return true
|
|
if (!input.includeAssignedMissingCarrier) return false
|
|
const assigned = await transitionFulfillmentStateWithExecutor(client, {
|
|
...common,
|
|
expected: {
|
|
status: 'assigned',
|
|
locked: false,
|
|
sourceNotIn: ['operator_assigned', 'manual_confirm'],
|
|
},
|
|
})
|
|
return Boolean(assigned)
|
|
})
|
|
if (updated) {
|
|
await scheduleVoucherConsumeForOrderItems([input.orderItemId], 'order_received').catch(
|
|
() => undefined,
|
|
)
|
|
}
|
|
return updated
|
|
}
|
|
|
|
/**
|
|
* 按 internal_sku_channels 的明确优先级补载体。
|
|
*
|
|
* 主渠道是 affiliate/work_order 但载体暂时创建失败时,只有显式 is_fallback 的
|
|
* manual/voucher 才能接管。所有结果都落 pending 明细,不再静默卡住。
|
|
*/
|
|
export async function reconcilePendingCarriers(
|
|
input: {
|
|
limit?: number
|
|
orderItemIds?: number[]
|
|
includeAssignedMissingCarrier?: boolean
|
|
allowFallback?: boolean
|
|
afterId?: number
|
|
includeLocked?: boolean
|
|
retryInactiveCarrier?: boolean
|
|
cutoffCreatedAt?: string
|
|
} = {},
|
|
): Promise<{
|
|
scanned: number
|
|
workOrdersCreated: number
|
|
affiliateTasksCreated: number
|
|
fallbacksSelected: number
|
|
failed: number
|
|
remaining: number
|
|
nextCursor: 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.afterId != null ? { afterId: input.afterId } : {}),
|
|
...(input.includeLocked ? { includeLocked: true } : {}),
|
|
...(input.cutoffCreatedAt ? { cutoffCreatedAt: input.cutoffCreatedAt } : {}),
|
|
...(input.orderItemIds ? { orderItemIds: input.orderItemIds } : {}),
|
|
})
|
|
|
|
let workOrdersCreated = 0
|
|
let affiliateTasksCreated = 0
|
|
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, candidates] of byOrder) {
|
|
const order = await getOrderById(orderId)
|
|
if (!order) continue
|
|
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 candidate of candidates) {
|
|
const item = itemById.get(Number(candidate.id))
|
|
if (!item) 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 transitionFulfillmentState({
|
|
orderItemId: Number(item.id),
|
|
expected: { status: 'pending' },
|
|
patch: {
|
|
pendingReason: 'routing_conflict',
|
|
pendingDetail: {
|
|
internalSku: candidate.internal_sku,
|
|
channels: plan.conflicts.map((channel) => channel.channel),
|
|
},
|
|
},
|
|
eventType: 'carrier_routing_conflict',
|
|
reason: 'routing_conflict',
|
|
})
|
|
}
|
|
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,
|
|
retryInactiveCarrier: input.retryInactiveCarrier === true,
|
|
})
|
|
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
|
|
}
|
|
|
|
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,
|
|
})
|
|
} else {
|
|
await markAssignedMissingCarrierPending({
|
|
itemId: Number(item.id),
|
|
previousChannel: assignedChannel,
|
|
internalSku: candidate.internal_sku,
|
|
attempts: failures,
|
|
})
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
const remainingResult = await query<{ count: number }>(
|
|
`
|
|
SELECT count(*)::int AS count
|
|
FROM order_items oi
|
|
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 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(', ')})
|
|
)
|
|
`,
|
|
)
|
|
|
|
return {
|
|
scanned: rows.length,
|
|
workOrdersCreated,
|
|
affiliateTasksCreated,
|
|
fallbacksSelected,
|
|
failed,
|
|
remaining: Number(remainingResult.rows[0]?.count || 0),
|
|
nextCursor: input.orderItemIds?.length
|
|
? 0
|
|
: rows.length < limit
|
|
? 0
|
|
: Number(rows[rows.length - 1]?.id || 0),
|
|
}
|
|
}
|