feat(fulfillment): 收敛履约状态写入口并追加状态事件
This commit is contained in:
@@ -35,6 +35,13 @@ import { reconcilePendingCarriers } from './carrier-reconciliation-service.js'
|
||||
import { TASK_STATUS } from '../../domain/task-status.js'
|
||||
import { canonicalizeInternalSku, containsCjk } from './internal-sku-resolver.js'
|
||||
import { scheduleVoucherConsumeForOrderItems } from './voucher-consume-queue-service.js'
|
||||
import {
|
||||
assignFulfillmentChannelsWithExecutor,
|
||||
transitionFulfillmentState,
|
||||
transitionFulfillmentStateBatch,
|
||||
transitionFulfillmentStateBatchWithExecutor,
|
||||
transitionFulfillmentStateWithExecutor,
|
||||
} from './fulfillment-state-service.js'
|
||||
|
||||
/**
|
||||
* 管道 A:渠道判定。
|
||||
@@ -365,20 +372,19 @@ export async function assignPendingOrderItemChannels(
|
||||
if (decision.channel) affectedDates.add(item.basis_date)
|
||||
if (decision.conflict) {
|
||||
result.conflicted += 1
|
||||
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: {
|
||||
channels: decision.conflictChannels,
|
||||
ruleIds: decision.matchedRuleIds,
|
||||
}),
|
||||
],
|
||||
)
|
||||
},
|
||||
},
|
||||
eventType: 'routing_conflict_detected',
|
||||
reason: 'routing_conflict',
|
||||
})
|
||||
await upsertAggregatedException({
|
||||
reason: 'routing_conflict',
|
||||
scopeKey: `routing_conflict|-|-|${item.internal_sku}|-`,
|
||||
@@ -391,20 +397,18 @@ export async function assignPendingOrderItemChannels(
|
||||
result.stillPending += 1
|
||||
const pending = resolvePendingReason(item)
|
||||
result.pendingReasons[pending.reason] = (result.pendingReasons[pending.reason] || 0) + 1
|
||||
await query(
|
||||
`UPDATE order_items
|
||||
SET fulfillment_pending_reason = $2,
|
||||
fulfillment_pending_detail = CASE
|
||||
WHEN $2 = 'no_carrier'
|
||||
AND COALESCE(fulfillment_pending_detail->>'carrierIssue', '')
|
||||
NOT IN ('', 'carrier_not_attempted')
|
||||
THEN fulfillment_pending_detail
|
||||
ELSE $3::jsonb
|
||||
END,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1 AND fulfillment_status = 'pending'`,
|
||||
[item.id, pending.reason, JSON.stringify(pending.detail)],
|
||||
)
|
||||
await transitionFulfillmentState({
|
||||
orderItemId: Number(item.id),
|
||||
expected: { status: 'pending' },
|
||||
patch: {
|
||||
pendingReason: pending.reason,
|
||||
...(pending.reason === 'no_carrier'
|
||||
? { pendingDetailUnlessCarrierIssue: pending.detail }
|
||||
: { pendingDetail: pending.detail }),
|
||||
},
|
||||
eventType: 'routing_pending',
|
||||
reason: pending.reason,
|
||||
})
|
||||
continue
|
||||
}
|
||||
assignments.push({ id: item.id, channel: decision.channel, source: decision.source })
|
||||
@@ -412,32 +416,19 @@ export async function assignPendingOrderItemChannels(
|
||||
}
|
||||
|
||||
if (assignments.length > 0) {
|
||||
const updated = await query<{ id: number }>(
|
||||
`
|
||||
UPDATE order_items oi
|
||||
SET
|
||||
fulfillment_channel = input.channel,
|
||||
fulfillment_status = 'assigned',
|
||||
fulfillment_source = input.source,
|
||||
fulfillment_decided_at = NOW(),
|
||||
fulfillment_pending_reason = NULL,
|
||||
fulfillment_pending_detail = NULL,
|
||||
updated_at = NOW()
|
||||
FROM unnest($1::bigint[], $2::text[], $3::text[])
|
||||
AS input(id, channel, source)
|
||||
WHERE oi.id = input.id
|
||||
AND oi.fulfillment_status = 'pending'
|
||||
AND (oi.fulfillment_locked = FALSE OR $4::boolean)
|
||||
RETURNING oi.id
|
||||
`,
|
||||
[
|
||||
assignments.map((row) => row.id),
|
||||
assignments.map((row) => row.channel),
|
||||
assignments.map((row) => row.source),
|
||||
options.includeLocked === true,
|
||||
],
|
||||
const updated = await withTransaction((client) =>
|
||||
assignFulfillmentChannelsWithExecutor(client, {
|
||||
assignments: assignments.map((row) => ({
|
||||
orderItemId: row.id,
|
||||
channel: row.channel,
|
||||
source: row.source,
|
||||
})),
|
||||
includeLocked: options.includeLocked === true,
|
||||
eventType: 'routing_channel_assigned',
|
||||
reason: 'automatic_routing',
|
||||
}),
|
||||
)
|
||||
const assignedItemIds = updated.rows
|
||||
const assignedItemIds = updated
|
||||
.map((row) => Number(row.id))
|
||||
.filter((id) => id > 0)
|
||||
.slice(0, 2000)
|
||||
@@ -503,12 +494,13 @@ export async function assignOrderItemsAfterCarrierReady(input: {
|
||||
) {
|
||||
// 旧载体尚未撤销时禁止直接换渠道,否则会同时留下两个履约执行方。
|
||||
carrierFailed += 1
|
||||
await query(
|
||||
`UPDATE order_items
|
||||
SET fulfillment_reason = $2, updated_at = NOW()
|
||||
WHERE id = $1 AND fulfillment_status = 'assigned'`,
|
||||
[item.id, '切换渠道前需先撤销现有履约载体'],
|
||||
)
|
||||
await transitionFulfillmentState({
|
||||
orderItemId: Number(item.id),
|
||||
expected: { status: 'assigned' },
|
||||
patch: { reason: '切换渠道前需先撤销现有履约载体' },
|
||||
eventType: 'channel_switch_blocked_by_existing_carrier',
|
||||
reason: String(item.fulfillment_channel || ''),
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -538,77 +530,71 @@ export async function assignOrderItemsAfterCarrierReady(input: {
|
||||
})
|
||||
if (item.fulfillment_status === 'assigned') {
|
||||
// 运营切换渠道失败时恢复原渠道,宁可保留旧状态,也不制造渠道与载体不一致。
|
||||
await query(
|
||||
`UPDATE order_items
|
||||
SET fulfillment_channel = $2,
|
||||
fulfillment_status = $3,
|
||||
fulfillment_source = $4,
|
||||
fulfillment_locked = $5,
|
||||
fulfillment_reason = $6,
|
||||
fulfillment_pending_reason = $7,
|
||||
fulfillment_pending_detail = $8::jsonb,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1 AND fulfillment_status <> 'archived'`,
|
||||
[
|
||||
item.id,
|
||||
item.fulfillment_channel,
|
||||
item.fulfillment_status,
|
||||
item.fulfillment_source,
|
||||
item.fulfillment_locked,
|
||||
item.fulfillment_reason,
|
||||
item.fulfillment_pending_reason,
|
||||
JSON.stringify(item.fulfillment_pending_detail || null),
|
||||
],
|
||||
)
|
||||
await transitionFulfillmentState({
|
||||
orderItemId: Number(item.id),
|
||||
expected: { status: 'assigned' },
|
||||
patch: {
|
||||
channel: item.fulfillment_channel as FulfillmentChannel,
|
||||
status: 'assigned',
|
||||
source: item.fulfillment_source || '',
|
||||
locked: Boolean(item.fulfillment_locked),
|
||||
reason: item.fulfillment_reason || null,
|
||||
pendingReason: item.fulfillment_pending_reason || null,
|
||||
pendingDetail:
|
||||
item.fulfillment_pending_detail && typeof item.fulfillment_pending_detail === 'object'
|
||||
? (item.fulfillment_pending_detail as Record<string, unknown>)
|
||||
: null,
|
||||
},
|
||||
eventType: 'channel_switch_failed_existing_state_kept',
|
||||
reason: carrier.reason,
|
||||
})
|
||||
} else {
|
||||
await query(
|
||||
`UPDATE order_items
|
||||
SET fulfillment_channel = NULL,
|
||||
fulfillment_status = 'pending',
|
||||
fulfillment_source = 'operator_assigned',
|
||||
fulfillment_locked = TRUE,
|
||||
fulfillment_pending_reason = 'no_carrier',
|
||||
fulfillment_pending_detail = $2::jsonb,
|
||||
canonical_product_id = COALESCE($3, canonical_product_id),
|
||||
updated_at = NOW()
|
||||
WHERE id = $1 AND fulfillment_status <> 'archived'`,
|
||||
[
|
||||
item.id,
|
||||
JSON.stringify({
|
||||
await transitionFulfillmentState({
|
||||
orderItemId: Number(item.id),
|
||||
expected: { status: 'pending' },
|
||||
patch: {
|
||||
channel: null,
|
||||
status: 'pending',
|
||||
source: 'operator_assigned',
|
||||
locked: true,
|
||||
pendingReason: 'no_carrier',
|
||||
pendingDetail: {
|
||||
channel: input.channel,
|
||||
reason: carrier.reason,
|
||||
message: carrier.message,
|
||||
carrierIssue: carrier.reason,
|
||||
}),
|
||||
input.canonicalProductId || null,
|
||||
],
|
||||
)
|
||||
},
|
||||
...(input.canonicalProductId
|
||||
? { canonicalProductIdIfNull: Number(input.canonicalProductId) }
|
||||
: {}),
|
||||
},
|
||||
eventType: 'operator_channel_assign_missing_carrier',
|
||||
actor: { type: 'operator' },
|
||||
reason: carrier.reason,
|
||||
})
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
const updated = await query(
|
||||
`UPDATE order_items
|
||||
SET fulfillment_channel = $2,
|
||||
fulfillment_status = 'assigned',
|
||||
fulfillment_source = $3,
|
||||
fulfillment_locked = $4,
|
||||
canonical_product_id = COALESCE($6, canonical_product_id),
|
||||
fulfillment_reason = COALESCE(NULLIF($5, ''), fulfillment_reason),
|
||||
fulfillment_pending_reason = NULL,
|
||||
fulfillment_pending_detail = NULL,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1 AND fulfillment_status <> 'archived'`,
|
||||
[
|
||||
item.id,
|
||||
input.channel,
|
||||
input.source,
|
||||
input.lock,
|
||||
String(input.note || '').slice(0, 200),
|
||||
input.canonicalProductId || null,
|
||||
],
|
||||
)
|
||||
if ((updated.rowCount || 0) > 0) assignedIds.push(Number(item.id))
|
||||
const updated = await transitionFulfillmentState({
|
||||
orderItemId: Number(item.id),
|
||||
patch: {
|
||||
channel: input.channel,
|
||||
status: 'assigned',
|
||||
source: input.source,
|
||||
locked: input.lock,
|
||||
...(input.canonicalProductId
|
||||
? { canonicalProductIdIfNull: Number(input.canonicalProductId) }
|
||||
: {}),
|
||||
...(String(input.note || '').trim() ? { reason: String(input.note).slice(0, 200) } : {}),
|
||||
pendingReason: null,
|
||||
pendingDetail: null,
|
||||
},
|
||||
eventType: 'operator_carrier_ready',
|
||||
actor: { type: 'operator' },
|
||||
reason: input.note || '',
|
||||
})
|
||||
if (updated) assignedIds.push(Number(item.id))
|
||||
}
|
||||
|
||||
if (assignedIds.length > 0) {
|
||||
@@ -625,25 +611,22 @@ export async function assignOrderItemsAfterCarrierReady(input: {
|
||||
]
|
||||
await refreshFactsForDates(dates).catch(() => undefined)
|
||||
}
|
||||
const final = await query<{ count: number }>(
|
||||
`WITH updated AS (
|
||||
UPDATE order_items
|
||||
SET fulfillment_source = $3,
|
||||
fulfillment_locked = $4,
|
||||
fulfillment_pending_reason = NULL,
|
||||
fulfillment_pending_detail = NULL,
|
||||
updated_at = NOW()
|
||||
WHERE id = ANY($1::bigint[])
|
||||
AND fulfillment_status = 'assigned'
|
||||
AND fulfillment_channel = $2
|
||||
RETURNING id
|
||||
)
|
||||
SELECT count(*)::int AS count FROM updated`,
|
||||
[ids, input.channel, input.source, input.lock],
|
||||
)
|
||||
const finalized = await transitionFulfillmentStateBatch({
|
||||
orderItemIds: ids,
|
||||
expected: { status: 'assigned', channel: input.channel },
|
||||
patch: {
|
||||
source: input.source,
|
||||
locked: input.lock,
|
||||
pendingReason: null,
|
||||
pendingDetail: null,
|
||||
},
|
||||
eventType: 'assigned_channel_snapshot_updated',
|
||||
actor: { type: 'operator' },
|
||||
reason: input.note || '',
|
||||
})
|
||||
await syncAssignedChannelSnapshots(ids, input.channel, input.source)
|
||||
return {
|
||||
updated: Number(final.rows[0]?.count || assignedIds.length),
|
||||
updated: finalized.length || assignedIds.length,
|
||||
carrierFailed,
|
||||
carrierFailures,
|
||||
}
|
||||
@@ -867,24 +850,29 @@ export async function switchChannelForOrderItems(input: {
|
||||
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],
|
||||
)
|
||||
await transitionFulfillmentStateWithExecutor(client, {
|
||||
orderItemId: Number(item.id),
|
||||
expected: { status: item.fulfillment_status as 'pending' | 'assigned' | 'archived' },
|
||||
patch: {
|
||||
...(isFulfillmentChannel(item.fulfillment_channel)
|
||||
? { originalChannelIfNull: item.fulfillment_channel }
|
||||
: {}),
|
||||
channel: null,
|
||||
status: 'pending',
|
||||
source: 'operator_assigned',
|
||||
locked: false,
|
||||
reason: String(input.note || '运营切换履约渠道').slice(0, 200),
|
||||
switchReason: 'operator',
|
||||
switchedAt: now,
|
||||
canonicalProductId: null,
|
||||
configId: null,
|
||||
pendingReason: null,
|
||||
pendingDetail: null,
|
||||
},
|
||||
eventType: 'operator_channel_switched',
|
||||
actor: { type: 'operator', id: input.adminUserId },
|
||||
reason: input.note || '',
|
||||
})
|
||||
})
|
||||
|
||||
for (const workOrder of workOrders.rows) {
|
||||
@@ -925,12 +913,16 @@ export async function switchChannelForOrderItems(input: {
|
||||
note: input.note,
|
||||
canonicalProductId: draftProductId,
|
||||
})
|
||||
await query(
|
||||
`UPDATE order_items
|
||||
SET fulfillment_decided_by = $2, fulfillment_decided_at = NOW()
|
||||
WHERE id = ANY($1::bigint[])`,
|
||||
[readyIds, input.adminUserId],
|
||||
)
|
||||
await transitionFulfillmentStateBatch({
|
||||
orderItemIds: readyIds,
|
||||
patch: {
|
||||
decidedBy: input.adminUserId,
|
||||
decidedAt: nowIso(),
|
||||
},
|
||||
eventType: 'operator_channel_decision_recorded',
|
||||
actor: { type: 'operator', id: input.adminUserId },
|
||||
reason: input.note || '',
|
||||
})
|
||||
if (assigned.updated > 0) {
|
||||
const carrier = await resolveInternalSkuCarrierConfig(targetInternalSku, input.channel)
|
||||
await setInternalSkuPrimaryChannel({
|
||||
@@ -1000,11 +992,14 @@ export async function assignChannelToOrderItems(input: {
|
||||
export async function unlockChannel(orderItemIds: number[]): Promise<{ updated: number }> {
|
||||
const ids = [...new Set(orderItemIds.map(Number).filter((id) => Number.isInteger(id) && id > 0))]
|
||||
if (ids.length === 0) return { updated: 0 }
|
||||
const result = await query(
|
||||
`UPDATE order_items SET fulfillment_locked = FALSE, updated_at = NOW() WHERE id = ANY($1::bigint[])`,
|
||||
[ids],
|
||||
)
|
||||
return { updated: result.rowCount || 0 }
|
||||
const updated = await transitionFulfillmentStateBatch({
|
||||
orderItemIds: ids,
|
||||
expected: { locked: true },
|
||||
patch: { locked: false },
|
||||
eventType: 'fulfillment_unlocked',
|
||||
actor: { type: 'operator' },
|
||||
})
|
||||
return { updated: updated.length }
|
||||
}
|
||||
|
||||
export type PendingGroupRow = {
|
||||
@@ -1494,16 +1489,21 @@ export async function unlockPendingChannelGroup(input: {
|
||||
params.push(issueCategory)
|
||||
where.push(`state.issue_category = $${params.length}`)
|
||||
}
|
||||
const result = await query(
|
||||
`UPDATE order_items item
|
||||
SET fulfillment_locked = FALSE,
|
||||
updated_at = NOW()
|
||||
const matched = await query<{ order_item_id: number }>(
|
||||
`SELECT state.order_item_id
|
||||
FROM v_fulfillment_item_state state
|
||||
WHERE item.id = state.order_item_id
|
||||
AND ${where.join(' AND ')}`,
|
||||
WHERE ${where.join(' AND ')}
|
||||
ORDER BY state.order_item_id`,
|
||||
params,
|
||||
)
|
||||
return { updated: result.rowCount || 0 }
|
||||
const updated = await transitionFulfillmentStateBatch({
|
||||
orderItemIds: matched.rows.map((row) => Number(row.order_item_id)),
|
||||
expected: { status: 'pending', locked: true },
|
||||
patch: { locked: false },
|
||||
eventType: 'pending_group_unlocked',
|
||||
actor: { type: 'operator' },
|
||||
})
|
||||
return { updated: updated.length }
|
||||
}
|
||||
|
||||
export type DeletePendingChannelGroupResult = {
|
||||
@@ -1650,27 +1650,26 @@ export async function deletePendingChannelGroup(input: {
|
||||
[itemIds, exceptionIds],
|
||||
)
|
||||
|
||||
const archived = await client.query(
|
||||
`
|
||||
UPDATE order_items
|
||||
SET fulfillment_channel = NULL,
|
||||
fulfillment_status = 'archived',
|
||||
fulfillment_source = 'cutover_archive',
|
||||
fulfillment_locked = TRUE,
|
||||
fulfillment_reason = '运营从待分类队列删除',
|
||||
fulfillment_pending_reason = NULL,
|
||||
fulfillment_pending_detail = NULL,
|
||||
fulfillment_decided_by = $2,
|
||||
fulfillment_decided_at = NOW(),
|
||||
updated_at = NOW()
|
||||
WHERE id = ANY($1::bigint[])
|
||||
AND fulfillment_status = 'pending'
|
||||
`,
|
||||
[itemIds, input.adminUserId],
|
||||
)
|
||||
const archived = await transitionFulfillmentStateBatchWithExecutor(client, {
|
||||
orderItemIds: itemIds,
|
||||
expected: { status: 'pending' },
|
||||
patch: {
|
||||
channel: null,
|
||||
status: 'archived',
|
||||
source: 'cutover_archive',
|
||||
locked: true,
|
||||
reason: '运营从待分类队列删除',
|
||||
pendingReason: null,
|
||||
pendingDetail: null,
|
||||
decidedBy: input.adminUserId,
|
||||
decidedAt: nowIso(),
|
||||
},
|
||||
eventType: 'pending_group_archived',
|
||||
actor: { type: 'operator', id: input.adminUserId },
|
||||
})
|
||||
|
||||
return {
|
||||
archivedItems: archived.rowCount || 0,
|
||||
archivedItems: archived.length,
|
||||
preservedOrders: new Set(items.rows.map((row) => Number(row.order_id))).size,
|
||||
deletedCostSnapshots: snapshots.rowCount || 0,
|
||||
resolvedExceptions: resolved.rowCount || 0,
|
||||
@@ -1866,12 +1865,16 @@ export async function assignChannelByInternalSku(input: {
|
||||
note: input.note,
|
||||
canonicalProductId: draftProductId,
|
||||
})
|
||||
await query(
|
||||
`UPDATE order_items
|
||||
SET fulfillment_decided_by = $2, fulfillment_decided_at = NOW()
|
||||
WHERE id = ANY($1::bigint[])`,
|
||||
[ids, input.adminUserId],
|
||||
)
|
||||
await transitionFulfillmentStateBatch({
|
||||
orderItemIds: ids,
|
||||
patch: {
|
||||
decidedBy: input.adminUserId,
|
||||
decidedAt: nowIso(),
|
||||
},
|
||||
eventType: 'operator_channel_decision_recorded',
|
||||
actor: { type: 'operator', id: input.adminUserId },
|
||||
reason: input.note || '',
|
||||
})
|
||||
|
||||
return {
|
||||
...applied,
|
||||
|
||||
Reference in New Issue
Block a user