重构:硬切履约状态唯一真源
This commit is contained in:
@@ -97,7 +97,6 @@ type StateColumn = {
|
||||
column: string
|
||||
value: unknown
|
||||
cast?: 'jsonb'
|
||||
mergeSnapshot?: boolean
|
||||
coalesceCurrent?: boolean
|
||||
preserveCarrierIssue?: boolean
|
||||
}
|
||||
@@ -119,46 +118,46 @@ function buildPatchColumns(patch: FulfillmentStatePatch): StateColumn[] {
|
||||
if (!['pending', 'assigned', 'archived'].includes(patch.status)) {
|
||||
throw new TypeError(`invalid fulfillment status: ${patch.status}`)
|
||||
}
|
||||
columns.push({ column: 'fulfillment_status', value: patch.status })
|
||||
columns.push({ column: 'status', value: patch.status })
|
||||
}
|
||||
if (patch.channel !== undefined) {
|
||||
if (patch.channel !== null && !isFulfillmentChannel(patch.channel)) {
|
||||
throw new TypeError(`invalid fulfillment channel: ${patch.channel}`)
|
||||
}
|
||||
columns.push({ column: 'fulfillment_channel', value: patch.channel })
|
||||
columns.push({ column: 'channel', value: patch.channel })
|
||||
}
|
||||
if (patch.source !== undefined) {
|
||||
columns.push({ column: 'fulfillment_source', value: patch.source })
|
||||
columns.push({ column: 'source', value: patch.source })
|
||||
}
|
||||
if (patch.locked !== undefined) {
|
||||
columns.push({ column: 'fulfillment_locked', value: Boolean(patch.locked) })
|
||||
columns.push({ column: 'locked', value: Boolean(patch.locked) })
|
||||
}
|
||||
if (patch.pendingReason !== undefined) {
|
||||
columns.push({ column: 'fulfillment_pending_reason', value: patch.pendingReason || null })
|
||||
columns.push({ column: 'pending_reason', value: patch.pendingReason || null })
|
||||
}
|
||||
if (patch.pendingDetail !== undefined) {
|
||||
columns.push({
|
||||
column: 'fulfillment_pending_detail',
|
||||
column: 'pending_detail',
|
||||
value: patch.pendingDetail,
|
||||
cast: 'jsonb',
|
||||
})
|
||||
}
|
||||
if (patch.pendingDetailUnlessCarrierIssue !== undefined) {
|
||||
columns.push({
|
||||
column: 'fulfillment_pending_detail',
|
||||
column: 'pending_detail',
|
||||
value: patch.pendingDetailUnlessCarrierIssue,
|
||||
cast: 'jsonb',
|
||||
preserveCarrierIssue: true,
|
||||
})
|
||||
}
|
||||
if (patch.reason !== undefined) {
|
||||
columns.push({ column: 'fulfillment_reason', value: patch.reason || null })
|
||||
columns.push({ column: 'reason', value: patch.reason || null })
|
||||
}
|
||||
if (patch.decidedBy !== undefined) {
|
||||
columns.push({ column: 'fulfillment_decided_by', value: patch.decidedBy })
|
||||
columns.push({ column: 'decided_by', value: patch.decidedBy })
|
||||
}
|
||||
if (patch.decidedAt !== undefined) {
|
||||
columns.push({ column: 'fulfillment_decided_at', value: patch.decidedAt })
|
||||
columns.push({ column: 'decided_at', value: patch.decidedAt })
|
||||
}
|
||||
if (patch.originalChannelIfNull !== undefined) {
|
||||
if (!isFulfillmentChannel(patch.originalChannelIfNull)) {
|
||||
@@ -197,26 +196,49 @@ function buildPatchColumns(patch: FulfillmentStatePatch): StateColumn[] {
|
||||
})
|
||||
}
|
||||
if (patch.itemSnapshotJson !== undefined) {
|
||||
columns.push({
|
||||
column: 'item_snapshot_json',
|
||||
value: patch.itemSnapshotJson,
|
||||
cast: 'jsonb',
|
||||
})
|
||||
// 原订单项快照属于订单事实,不进入履约状态表。
|
||||
}
|
||||
if (patch.itemSnapshotPatch !== undefined) {
|
||||
columns.push({
|
||||
column: 'item_snapshot_json',
|
||||
value: patch.itemSnapshotPatch,
|
||||
cast: 'jsonb',
|
||||
mergeSnapshot: true,
|
||||
})
|
||||
// 同上,在状态更新后单独合并。
|
||||
}
|
||||
if (columns.length === 0) {
|
||||
if (
|
||||
columns.length === 0 &&
|
||||
patch.itemSnapshotJson === undefined &&
|
||||
patch.itemSnapshotPatch === undefined
|
||||
) {
|
||||
throw new TypeError('fulfillment state patch must change at least one column')
|
||||
}
|
||||
return columns
|
||||
}
|
||||
|
||||
async function applyOrderItemSnapshotPatch(
|
||||
executor: FulfillmentStateExecutor,
|
||||
orderItemId: number,
|
||||
patch: FulfillmentStatePatch,
|
||||
) {
|
||||
if (patch.itemSnapshotJson === undefined && patch.itemSnapshotPatch === undefined) {
|
||||
return
|
||||
}
|
||||
if (patch.itemSnapshotJson !== undefined) {
|
||||
await executor.query(
|
||||
`UPDATE order_items
|
||||
SET item_snapshot_json = $2::jsonb,
|
||||
updated_at = $3::timestamptz
|
||||
WHERE id = $1`,
|
||||
[orderItemId, patch.itemSnapshotJson, new Date().toISOString()],
|
||||
)
|
||||
return
|
||||
}
|
||||
await executor.query(
|
||||
`UPDATE order_items
|
||||
SET item_snapshot_json =
|
||||
COALESCE(item_snapshot_json, '{}'::jsonb) || $2::jsonb,
|
||||
updated_at = $3::timestamptz
|
||||
WHERE id = $1`,
|
||||
[orderItemId, patch.itemSnapshotPatch, new Date().toISOString()],
|
||||
)
|
||||
}
|
||||
|
||||
async function setEventContext(
|
||||
executor: FulfillmentStateExecutor,
|
||||
transition: Pick<FulfillmentStateTransition, 'eventType'> & {
|
||||
@@ -261,71 +283,84 @@ export async function transitionFulfillmentStateWithExecutor(
|
||||
const columns = buildPatchColumns(input.patch)
|
||||
await setEventContext(executor, input)
|
||||
try {
|
||||
const lockResult = await executor.query<OrderItemRow>(
|
||||
`SELECT * FROM order_items WHERE id = $1 FOR UPDATE`,
|
||||
const lockResult = await executor.query<{
|
||||
id: number
|
||||
order_item_id: number
|
||||
status: string
|
||||
channel: string | null
|
||||
source: string
|
||||
locked: boolean
|
||||
}>(
|
||||
`SELECT id, order_item_id, status, channel, source, locked
|
||||
FROM fulfillments
|
||||
WHERE order_item_id = $1
|
||||
FOR UPDATE`,
|
||||
[orderItemId],
|
||||
)
|
||||
const current = lockResult.rows[0]
|
||||
if (!current) return null
|
||||
|
||||
if (
|
||||
input.expected?.status !== undefined &&
|
||||
current.fulfillment_status !== input.expected.status
|
||||
) {
|
||||
if (input.expected?.status !== undefined && current.status !== input.expected.status) {
|
||||
return null
|
||||
}
|
||||
if (
|
||||
input.expected?.channel !== undefined &&
|
||||
(current.fulfillment_channel ?? null) !== input.expected.channel
|
||||
(current.channel ?? null) !== input.expected.channel
|
||||
) {
|
||||
return null
|
||||
}
|
||||
if (
|
||||
input.expected?.source !== undefined &&
|
||||
(current.fulfillment_source || '') !== (input.expected.source || '')
|
||||
(current.source || '') !== (input.expected.source || '')
|
||||
) {
|
||||
return null
|
||||
}
|
||||
if (
|
||||
input.expected?.sourceNotIn &&
|
||||
input.expected.sourceNotIn.includes(String(current.fulfillment_source || ''))
|
||||
input.expected.sourceNotIn.includes(String(current.source || ''))
|
||||
) {
|
||||
return null
|
||||
}
|
||||
if (
|
||||
input.expected?.locked !== undefined &&
|
||||
Boolean(current.fulfillment_locked) !== Boolean(input.expected.locked)
|
||||
Boolean(current.locked) !== Boolean(input.expected.locked)
|
||||
) {
|
||||
return null
|
||||
}
|
||||
|
||||
const params: unknown[] = []
|
||||
const assignments = columns.map((entry) => {
|
||||
params.push(entry.value)
|
||||
let expression = `$${params.length}`
|
||||
if (entry.cast) expression += `::${entry.cast}`
|
||||
if (entry.mergeSnapshot) {
|
||||
expression = `COALESCE(item_snapshot_json, '{}'::jsonb) || ${expression}`
|
||||
} else if (entry.preserveCarrierIssue) {
|
||||
expression =
|
||||
`CASE WHEN COALESCE(fulfillment_pending_detail->>'carrierIssue', '') ` +
|
||||
`NOT IN ('', 'carrier_not_attempted') ` +
|
||||
`THEN fulfillment_pending_detail ELSE ${expression} END`
|
||||
} else if (entry.coalesceCurrent) {
|
||||
expression = `COALESCE(${entry.column}, ${expression})`
|
||||
}
|
||||
return `${entry.column} = ${expression}`
|
||||
})
|
||||
params.push(new Date().toISOString())
|
||||
assignments.push(`updated_at = $${params.length}::timestamptz`)
|
||||
params.push(orderItemId)
|
||||
if (columns.length > 0) {
|
||||
const params: unknown[] = []
|
||||
const assignments = columns.map((entry) => {
|
||||
params.push(entry.value)
|
||||
let expression = `$${params.length}`
|
||||
if (entry.cast) expression += `::${entry.cast}`
|
||||
if (entry.preserveCarrierIssue) {
|
||||
expression =
|
||||
`CASE WHEN COALESCE(pending_detail->>'carrierIssue', '') ` +
|
||||
`NOT IN ('', 'carrier_not_attempted') ` +
|
||||
`THEN pending_detail ELSE ${expression} END`
|
||||
} else if (entry.coalesceCurrent) {
|
||||
expression = `COALESCE(${entry.column}, ${expression})`
|
||||
}
|
||||
return `${entry.column} = ${expression}`
|
||||
})
|
||||
params.push(new Date().toISOString())
|
||||
assignments.push(`updated_at = $${params.length}::timestamptz`)
|
||||
params.push(current.id)
|
||||
|
||||
await executor.query(
|
||||
`UPDATE fulfillments
|
||||
SET ${assignments.join(', ')}
|
||||
WHERE id = $${params.length}`,
|
||||
params,
|
||||
)
|
||||
}
|
||||
|
||||
await applyOrderItemSnapshotPatch(executor, orderItemId, input.patch)
|
||||
await executor.query(`SELECT refresh_fulfillment_derived($1)`, [orderItemId])
|
||||
const updated = await executor.query<OrderItemRow>(
|
||||
`UPDATE order_items
|
||||
SET ${assignments.join(', ')}
|
||||
WHERE id = $${params.length}
|
||||
RETURNING *`,
|
||||
params,
|
||||
`SELECT * FROM v_order_item_current WHERE id = $1`,
|
||||
[orderItemId],
|
||||
)
|
||||
return updated.rows[0] || null
|
||||
} finally {
|
||||
@@ -409,21 +444,21 @@ export async function assignFulfillmentChannelsWithExecutor(
|
||||
...(input.reason ? { reason: input.reason } : {}),
|
||||
})
|
||||
try {
|
||||
const result = await executor.query<OrderItemRow>(
|
||||
`UPDATE order_items item
|
||||
SET fulfillment_channel = input.channel,
|
||||
fulfillment_status = 'assigned',
|
||||
fulfillment_source = input.source,
|
||||
fulfillment_decided_at = NOW(),
|
||||
fulfillment_pending_reason = NULL,
|
||||
fulfillment_pending_detail = NULL,
|
||||
const result = await executor.query<{ order_item_id: number }>(
|
||||
`UPDATE fulfillments fulfillment
|
||||
SET channel = input.channel,
|
||||
status = 'assigned',
|
||||
source = input.source,
|
||||
decided_at = NOW(),
|
||||
pending_reason = NULL,
|
||||
pending_detail = NULL,
|
||||
updated_at = NOW()
|
||||
FROM unnest($1::bigint[], $2::text[], $3::text[])
|
||||
AS input(order_item_id, channel, source)
|
||||
WHERE item.id = input.order_item_id
|
||||
AND item.fulfillment_status = 'pending'
|
||||
AND (item.fulfillment_locked = FALSE OR $4::boolean)
|
||||
RETURNING item.*`,
|
||||
WHERE fulfillment.order_item_id = input.order_item_id
|
||||
AND fulfillment.status = 'pending'
|
||||
AND (fulfillment.locked = FALSE OR $4::boolean)
|
||||
RETURNING fulfillment.order_item_id`,
|
||||
[
|
||||
assignments.map((row) => row.orderItemId),
|
||||
assignments.map((row) => row.channel),
|
||||
@@ -431,7 +466,21 @@ export async function assignFulfillmentChannelsWithExecutor(
|
||||
input.includeLocked === true,
|
||||
],
|
||||
)
|
||||
return result.rows
|
||||
const updatedIds = result.rows.map((row) => Number(row.order_item_id))
|
||||
if (updatedIds.length === 0) return []
|
||||
await executor.query(
|
||||
`SELECT refresh_fulfillment_derived(order_item_id)
|
||||
FROM fulfillments
|
||||
WHERE order_item_id = ANY($1::bigint[])`,
|
||||
[updatedIds],
|
||||
)
|
||||
const updated = await executor.query<OrderItemRow>(
|
||||
`SELECT * FROM v_order_item_current
|
||||
WHERE id = ANY($1::bigint[])
|
||||
ORDER BY id`,
|
||||
[updatedIds],
|
||||
)
|
||||
return updated.rows
|
||||
} finally {
|
||||
await clearEventContext(executor)
|
||||
}
|
||||
@@ -487,14 +536,14 @@ export async function attachFulfillmentConfigurationsWithExecutor(
|
||||
mappings.map((row) => row.requireExpectedProduct),
|
||||
mappings.map((row) => row.expectedCanonicalProductId),
|
||||
]
|
||||
const where = ['item.id = input.order_item_id']
|
||||
const where = ['item.order_item_id = input.order_item_id']
|
||||
if (input.expected?.status !== undefined) {
|
||||
params.push(input.expected.status)
|
||||
where.push(`item.fulfillment_status IS NOT DISTINCT FROM $${params.length}`)
|
||||
where.push(`item.status IS NOT DISTINCT FROM $${params.length}`)
|
||||
}
|
||||
if (input.expected?.channel !== undefined) {
|
||||
params.push(input.expected.channel)
|
||||
where.push(`item.fulfillment_channel IS NOT DISTINCT FROM $${params.length}`)
|
||||
where.push(`item.channel IS NOT DISTINCT FROM $${params.length}`)
|
||||
}
|
||||
if (input.onlyWhenConfigNull) {
|
||||
where.push('item.fulfillment_config_id IS NULL')
|
||||
@@ -514,8 +563,8 @@ export async function attachFulfillmentConfigurationsWithExecutor(
|
||||
params.push(new Date().toISOString())
|
||||
const updatedAtParam = params.length
|
||||
|
||||
const result = await executor.query<OrderItemRow>(
|
||||
`UPDATE order_items item
|
||||
const updatedIds = await executor.query<{ order_item_id: number }>(
|
||||
`UPDATE fulfillments item
|
||||
SET fulfillment_config_id = CASE
|
||||
WHEN input.set_config THEN input.config_id
|
||||
ELSE item.fulfillment_config_id
|
||||
@@ -545,9 +594,23 @@ export async function attachFulfillmentConfigurationsWithExecutor(
|
||||
expected_canonical_product_id
|
||||
)
|
||||
WHERE ${where.join(' AND ')}
|
||||
RETURNING item.*`,
|
||||
RETURNING item.order_item_id`,
|
||||
params,
|
||||
)
|
||||
const ids = updatedIds.rows.map((row) => Number(row.order_item_id))
|
||||
if (ids.length === 0) return []
|
||||
await executor.query(
|
||||
`SELECT refresh_fulfillment_derived(order_item_id)
|
||||
FROM fulfillments
|
||||
WHERE order_item_id = ANY($1::bigint[])`,
|
||||
[ids],
|
||||
)
|
||||
const result = await executor.query<OrderItemRow>(
|
||||
`SELECT * FROM v_order_item_current
|
||||
WHERE id = ANY($1::bigint[])
|
||||
ORDER BY id`,
|
||||
[ids],
|
||||
)
|
||||
return result.rows
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user