feat(fulfillment): 收敛履约状态写入口并追加状态事件
This commit is contained in:
@@ -0,0 +1,454 @@
|
||||
import type { PoolClient, QueryResult, QueryResultRow } from 'pg'
|
||||
|
||||
import { query, withTransaction } from '../../db/client.js'
|
||||
import type { JsonObject } from '../../types/json.js'
|
||||
import type { OrderItemRow } from '../../types/repository/rows.js'
|
||||
import {
|
||||
isFulfillmentChannel,
|
||||
type FulfillmentChannel,
|
||||
type FulfillmentSource,
|
||||
type FulfillmentStatus,
|
||||
} from './channel-types.js'
|
||||
|
||||
export type FulfillmentStateExecutor = {
|
||||
query: <T extends QueryResultRow = QueryResultRow>(
|
||||
text: string,
|
||||
params?: unknown[],
|
||||
) => Promise<QueryResult<T>>
|
||||
}
|
||||
|
||||
export type FulfillmentStateActor = {
|
||||
type?: 'system' | 'operator' | 'worker' | 'finance' | 'api'
|
||||
id?: number | string | null
|
||||
}
|
||||
|
||||
export type FulfillmentStatePatch = {
|
||||
status?: FulfillmentStatus
|
||||
channel?: FulfillmentChannel | null
|
||||
source?: FulfillmentSource | string
|
||||
locked?: boolean
|
||||
pendingReason?: string | null
|
||||
pendingDetail?: JsonObject | null
|
||||
pendingDetailUnlessCarrierIssue?: JsonObject
|
||||
reason?: string | null
|
||||
decidedBy?: number | null
|
||||
decidedAt?: string | null
|
||||
originalChannelIfNull?: FulfillmentChannel
|
||||
switchReason?: string | null
|
||||
switchedAt?: string | null
|
||||
configId?: number | null
|
||||
configIdIfNull?: number
|
||||
canonicalProductId?: number | null
|
||||
canonicalProductIdIfNull?: number
|
||||
itemSnapshotJson?: JsonObject
|
||||
itemSnapshotPatch?: JsonObject
|
||||
}
|
||||
|
||||
export type FulfillmentStateExpected = {
|
||||
status?: FulfillmentStatus | null
|
||||
channel?: FulfillmentChannel | null
|
||||
source?: string | null
|
||||
sourceNotIn?: string[]
|
||||
locked?: boolean | null
|
||||
}
|
||||
|
||||
export type FulfillmentStateTransition = {
|
||||
orderItemId: number
|
||||
patch: FulfillmentStatePatch
|
||||
expected?: FulfillmentStateExpected
|
||||
eventType: string
|
||||
actor?: FulfillmentStateActor
|
||||
reason?: string
|
||||
}
|
||||
|
||||
export type FulfillmentStateEventRow = {
|
||||
[column: string]: unknown
|
||||
id: number
|
||||
order_item_id: number
|
||||
order_id: number
|
||||
event_type: string
|
||||
actor_type: string
|
||||
actor_id: string
|
||||
reason: string
|
||||
previous_status: string | null
|
||||
next_status: string | null
|
||||
previous_channel: string | null
|
||||
next_channel: string | null
|
||||
previous_source: string | null
|
||||
next_source: string | null
|
||||
previous_locked: boolean | null
|
||||
next_locked: boolean | null
|
||||
previous_pending_reason: string | null
|
||||
next_pending_reason: string | null
|
||||
previous_pending_detail: JsonObject | null
|
||||
next_pending_detail: JsonObject | null
|
||||
payload_json: JsonObject
|
||||
created_at: string
|
||||
}
|
||||
|
||||
type StateColumn = {
|
||||
column: string
|
||||
value: unknown
|
||||
cast?: 'jsonb'
|
||||
mergeSnapshot?: boolean
|
||||
coalesceCurrent?: boolean
|
||||
preserveCarrierIssue?: boolean
|
||||
}
|
||||
|
||||
function normalizeId(value: unknown): number {
|
||||
const id = Number(value)
|
||||
if (!Number.isInteger(id) || id <= 0) {
|
||||
throw new TypeError('orderItemId must be a positive integer')
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
function buildPatchColumns(patch: FulfillmentStatePatch): StateColumn[] {
|
||||
if (!patch || typeof patch !== 'object') {
|
||||
throw new TypeError('fulfillment state patch is required')
|
||||
}
|
||||
const columns: StateColumn[] = []
|
||||
if (patch.status !== undefined) {
|
||||
if (!['pending', 'assigned', 'archived'].includes(patch.status)) {
|
||||
throw new TypeError(`invalid fulfillment status: ${patch.status}`)
|
||||
}
|
||||
columns.push({ column: 'fulfillment_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 })
|
||||
}
|
||||
if (patch.source !== undefined) {
|
||||
columns.push({ column: 'fulfillment_source', value: patch.source })
|
||||
}
|
||||
if (patch.locked !== undefined) {
|
||||
columns.push({ column: 'fulfillment_locked', value: Boolean(patch.locked) })
|
||||
}
|
||||
if (patch.pendingReason !== undefined) {
|
||||
columns.push({ column: 'fulfillment_pending_reason', value: patch.pendingReason || null })
|
||||
}
|
||||
if (patch.pendingDetail !== undefined) {
|
||||
columns.push({
|
||||
column: 'fulfillment_pending_detail',
|
||||
value: patch.pendingDetail,
|
||||
cast: 'jsonb',
|
||||
})
|
||||
}
|
||||
if (patch.pendingDetailUnlessCarrierIssue !== undefined) {
|
||||
columns.push({
|
||||
column: 'fulfillment_pending_detail',
|
||||
value: patch.pendingDetailUnlessCarrierIssue,
|
||||
cast: 'jsonb',
|
||||
preserveCarrierIssue: true,
|
||||
})
|
||||
}
|
||||
if (patch.reason !== undefined) {
|
||||
columns.push({ column: 'fulfillment_reason', value: patch.reason || null })
|
||||
}
|
||||
if (patch.decidedBy !== undefined) {
|
||||
columns.push({ column: 'fulfillment_decided_by', value: patch.decidedBy })
|
||||
}
|
||||
if (patch.decidedAt !== undefined) {
|
||||
columns.push({ column: 'fulfillment_decided_at', value: patch.decidedAt })
|
||||
}
|
||||
if (patch.originalChannelIfNull !== undefined) {
|
||||
if (!isFulfillmentChannel(patch.originalChannelIfNull)) {
|
||||
throw new TypeError(`invalid original fulfillment channel: ${patch.originalChannelIfNull}`)
|
||||
}
|
||||
columns.push({
|
||||
column: 'original_channel',
|
||||
value: patch.originalChannelIfNull,
|
||||
coalesceCurrent: true,
|
||||
})
|
||||
}
|
||||
if (patch.switchReason !== undefined) {
|
||||
columns.push({ column: 'channel_switch_reason', value: patch.switchReason || null })
|
||||
}
|
||||
if (patch.switchedAt !== undefined) {
|
||||
columns.push({ column: 'channel_switched_at', value: patch.switchedAt })
|
||||
}
|
||||
if (patch.configId !== undefined) {
|
||||
columns.push({ column: 'fulfillment_config_id', value: patch.configId })
|
||||
}
|
||||
if (patch.configIdIfNull !== undefined) {
|
||||
columns.push({
|
||||
column: 'fulfillment_config_id',
|
||||
value: patch.configIdIfNull,
|
||||
coalesceCurrent: true,
|
||||
})
|
||||
}
|
||||
if (patch.canonicalProductId !== undefined) {
|
||||
columns.push({ column: 'canonical_product_id', value: patch.canonicalProductId })
|
||||
}
|
||||
if (patch.canonicalProductIdIfNull !== undefined) {
|
||||
columns.push({
|
||||
column: 'canonical_product_id',
|
||||
value: patch.canonicalProductIdIfNull,
|
||||
coalesceCurrent: true,
|
||||
})
|
||||
}
|
||||
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) {
|
||||
throw new TypeError('fulfillment state patch must change at least one column')
|
||||
}
|
||||
return columns
|
||||
}
|
||||
|
||||
async function setEventContext(
|
||||
executor: FulfillmentStateExecutor,
|
||||
transition: Pick<FulfillmentStateTransition, 'eventType'> & {
|
||||
actor?: FulfillmentStateActor
|
||||
reason?: string
|
||||
},
|
||||
) {
|
||||
const eventType = String(transition.eventType || '').trim()
|
||||
if (!eventType) throw new TypeError('fulfillment state eventType is required')
|
||||
await executor.query(
|
||||
`SELECT
|
||||
set_config('app.fulfillment_event_type', $1, TRUE),
|
||||
set_config('app.fulfillment_actor_type', $2, TRUE),
|
||||
set_config('app.fulfillment_actor_id', $3, TRUE),
|
||||
set_config('app.fulfillment_reason', $4, TRUE)`,
|
||||
[
|
||||
eventType,
|
||||
transition.actor?.type || 'system',
|
||||
String(transition.actor?.id ?? ''),
|
||||
String(transition.reason || '').slice(0, 500),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
async function clearEventContext(executor: FulfillmentStateExecutor) {
|
||||
await executor
|
||||
.query(
|
||||
`SELECT
|
||||
set_config('app.fulfillment_event_type', '', TRUE),
|
||||
set_config('app.fulfillment_actor_type', '', TRUE),
|
||||
set_config('app.fulfillment_actor_id', '', TRUE),
|
||||
set_config('app.fulfillment_reason', '', TRUE)`,
|
||||
)
|
||||
.catch(() => undefined)
|
||||
}
|
||||
|
||||
export async function transitionFulfillmentStateWithExecutor(
|
||||
executor: FulfillmentStateExecutor,
|
||||
input: FulfillmentStateTransition,
|
||||
): Promise<OrderItemRow | null> {
|
||||
const orderItemId = normalizeId(input.orderItemId)
|
||||
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`,
|
||||
[orderItemId],
|
||||
)
|
||||
const current = lockResult.rows[0]
|
||||
if (!current) return null
|
||||
|
||||
if (
|
||||
input.expected?.status !== undefined &&
|
||||
current.fulfillment_status !== input.expected.status
|
||||
) {
|
||||
return null
|
||||
}
|
||||
if (
|
||||
input.expected?.channel !== undefined &&
|
||||
(current.fulfillment_channel ?? null) !== input.expected.channel
|
||||
) {
|
||||
return null
|
||||
}
|
||||
if (
|
||||
input.expected?.source !== undefined &&
|
||||
(current.fulfillment_source || '') !== (input.expected.source || '')
|
||||
) {
|
||||
return null
|
||||
}
|
||||
if (
|
||||
input.expected?.sourceNotIn &&
|
||||
input.expected.sourceNotIn.includes(String(current.fulfillment_source || ''))
|
||||
) {
|
||||
return null
|
||||
}
|
||||
if (
|
||||
input.expected?.locked !== undefined &&
|
||||
Boolean(current.fulfillment_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)
|
||||
|
||||
const updated = await executor.query<OrderItemRow>(
|
||||
`UPDATE order_items
|
||||
SET ${assignments.join(', ')}
|
||||
WHERE id = $${params.length}
|
||||
RETURNING *`,
|
||||
params,
|
||||
)
|
||||
return updated.rows[0] || null
|
||||
} finally {
|
||||
await clearEventContext(executor)
|
||||
}
|
||||
}
|
||||
|
||||
export async function transitionFulfillmentState(
|
||||
input: FulfillmentStateTransition,
|
||||
): Promise<OrderItemRow | null> {
|
||||
return withTransaction((client) =>
|
||||
transitionFulfillmentStateWithExecutor(client as FulfillmentStateExecutor, input),
|
||||
)
|
||||
}
|
||||
|
||||
export async function transitionFulfillmentStateBatchWithExecutor(
|
||||
executor: FulfillmentStateExecutor,
|
||||
input: {
|
||||
orderItemIds: number[]
|
||||
patch: FulfillmentStatePatch
|
||||
expected?: FulfillmentStateExpected
|
||||
eventType: string
|
||||
actor?: FulfillmentStateActor
|
||||
reason?: string
|
||||
},
|
||||
): Promise<OrderItemRow[]> {
|
||||
const ids = [
|
||||
...new Set(
|
||||
(input.orderItemIds || []).map(Number).filter((id) => Number.isInteger(id) && id > 0),
|
||||
),
|
||||
]
|
||||
const results: OrderItemRow[] = []
|
||||
for (const orderItemId of ids) {
|
||||
const updated = await transitionFulfillmentStateWithExecutor(executor, {
|
||||
orderItemId,
|
||||
patch: input.patch,
|
||||
eventType: input.eventType,
|
||||
...(input.expected ? { expected: input.expected } : {}),
|
||||
...(input.actor ? { actor: input.actor } : {}),
|
||||
...(input.reason ? { reason: input.reason } : {}),
|
||||
})
|
||||
if (updated) results.push(updated)
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
export async function transitionFulfillmentStateBatch(
|
||||
input: Parameters<typeof transitionFulfillmentStateBatchWithExecutor>[1],
|
||||
): Promise<OrderItemRow[]> {
|
||||
return withTransaction((client) =>
|
||||
transitionFulfillmentStateBatchWithExecutor(client as FulfillmentStateExecutor, input),
|
||||
)
|
||||
}
|
||||
|
||||
export async function assignFulfillmentChannelsWithExecutor(
|
||||
executor: FulfillmentStateExecutor,
|
||||
input: {
|
||||
assignments: Array<{
|
||||
orderItemId: number
|
||||
channel: FulfillmentChannel
|
||||
source: FulfillmentSource | string
|
||||
}>
|
||||
includeLocked?: boolean
|
||||
eventType?: string
|
||||
actor?: FulfillmentStateActor
|
||||
reason?: string
|
||||
},
|
||||
): Promise<OrderItemRow[]> {
|
||||
const assignments = (input.assignments || [])
|
||||
.map((row) => ({
|
||||
orderItemId: normalizeId(row.orderItemId),
|
||||
channel: row.channel,
|
||||
source: row.source,
|
||||
}))
|
||||
.filter((row) => isFulfillmentChannel(row.channel))
|
||||
if (assignments.length === 0) return []
|
||||
|
||||
await setEventContext(executor, {
|
||||
eventType: input.eventType || 'fulfillment_channel_assigned',
|
||||
...(input.actor ? { actor: input.actor } : {}),
|
||||
...(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,
|
||||
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.*`,
|
||||
[
|
||||
assignments.map((row) => row.orderItemId),
|
||||
assignments.map((row) => row.channel),
|
||||
assignments.map((row) => row.source),
|
||||
input.includeLocked === true,
|
||||
],
|
||||
)
|
||||
return result.rows
|
||||
} finally {
|
||||
await clearEventContext(executor)
|
||||
}
|
||||
}
|
||||
|
||||
export async function listFulfillmentStateEvents(
|
||||
orderItemId: number | string,
|
||||
options: { limit?: number } = {},
|
||||
): Promise<FulfillmentStateEventRow[]> {
|
||||
const id = normalizeId(orderItemId)
|
||||
const limit = Math.min(500, Math.max(1, Math.trunc(Number(options.limit) || 100)))
|
||||
const result = await query<FulfillmentStateEventRow>(
|
||||
`SELECT *
|
||||
FROM fulfillment_state_events
|
||||
WHERE order_item_id = $1
|
||||
ORDER BY id DESC
|
||||
LIMIT $2`,
|
||||
[id, limit],
|
||||
)
|
||||
return result.rows
|
||||
}
|
||||
|
||||
export async function runWithFulfillmentStateTransaction<T>(
|
||||
fn: (client: PoolClient) => Promise<T>,
|
||||
): Promise<T> {
|
||||
return withTransaction(fn)
|
||||
}
|
||||
Reference in New Issue
Block a user