feat(fulfillment): 收敛履约状态写入口并追加状态事件

This commit is contained in:
yml2213
2026-11-05 20:52:22 +08:00
parent ca214854bb
commit fcd0c137d5
16 changed files with 1386 additions and 402 deletions
@@ -1,4 +1,4 @@
import { query } from '../../db/client.js'
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'
@@ -8,6 +8,10 @@ import {
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,
@@ -145,24 +149,21 @@ async function markPendingWithoutCarrier(input: {
attempts: Array<{ channel: FulfillmentChannel; reason: string; message: string }>
}): Promise<void> {
const carrierIssue = input.attempts[0]?.reason || 'carrier_attempt_failed'
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({
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: {
@@ -172,29 +173,26 @@ async function markAssignedMissingCarrierPending(input: {
attempts: Array<{ channel: FulfillmentChannel; reason: string; message: string }>
}): Promise<void> {
const carrierIssue = input.attempts[0]?.reason || 'carrier_attempt_failed'
await query(
`
UPDATE order_items
SET fulfillment_channel = NULL,
fulfillment_status = 'pending',
fulfillment_source = 'auto_mapping',
fulfillment_locked = FALSE,
fulfillment_pending_reason = 'no_carrier',
fulfillment_pending_detail = $2::jsonb,
updated_at = NOW()
WHERE id = $1 AND fulfillment_status = 'assigned'
`,
[
input.itemId,
JSON.stringify({
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: {
@@ -204,39 +202,41 @@ async function selectSafeFallback(input: {
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(),
canonical_product_id = NULL,
fulfillment_config_id = NULL,
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,
],
)
const updated = (result.rowCount || 0) > 0
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,
@@ -320,20 +320,19 @@ export async function reconcilePendingCarriers(
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({
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
}