Files
order_site/apps/backend/src/services/fulfillment/fulfillment-state-service.ts
T

651 lines
20 KiB
TypeScript

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
}
export type FulfillmentConfigurationMapping = {
orderItemId: number
configId?: number | null
canonicalProductId?: number | null
expectedCanonicalProductId?: number | null
}
type StateColumn = {
column: string
value: unknown
cast?: 'jsonb'
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: '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: 'channel', value: patch.channel })
}
if (patch.source !== undefined) {
columns.push({ column: 'source', value: patch.source })
}
if (patch.locked !== undefined) {
columns.push({ column: 'locked', value: Boolean(patch.locked) })
}
if (patch.pendingReason !== undefined) {
columns.push({ column: 'pending_reason', value: patch.pendingReason || null })
}
if (patch.pendingDetail !== undefined) {
columns.push({
column: 'pending_detail',
value: patch.pendingDetail,
cast: 'jsonb',
})
}
if (patch.pendingDetailUnlessCarrierIssue !== undefined) {
columns.push({
column: 'pending_detail',
value: patch.pendingDetailUnlessCarrierIssue,
cast: 'jsonb',
preserveCarrierIssue: true,
})
}
if (patch.reason !== undefined) {
columns.push({ column: 'reason', value: patch.reason || null })
}
if (patch.decidedBy !== undefined) {
columns.push({ column: 'decided_by', value: patch.decidedBy })
}
if (patch.decidedAt !== undefined) {
columns.push({ column: '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) {
// 原订单项快照属于订单事实,不进入履约状态表。
}
if (patch.itemSnapshotPatch !== undefined) {
// 同上,在状态更新后单独合并。
}
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'> & {
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<{
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.status !== input.expected.status) {
return null
}
if (
input.expected?.channel !== undefined &&
(current.channel ?? null) !== input.expected.channel
) {
return null
}
if (
input.expected?.source !== undefined &&
(current.source || '') !== (input.expected.source || '')
) {
return null
}
if (
input.expected?.sourceNotIn &&
input.expected.sourceNotIn.includes(String(current.source || ''))
) {
return null
}
if (
input.expected?.locked !== undefined &&
Boolean(current.locked) !== Boolean(input.expected.locked)
) {
return null
}
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>(
`SELECT * FROM v_order_item_current WHERE id = $1`,
[orderItemId],
)
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<{ 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 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),
assignments.map((row) => row.source),
input.includeLocked === true,
],
)
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)
}
}
export async function attachFulfillmentConfigurationsWithExecutor(
executor: FulfillmentStateExecutor,
input: {
mappings: FulfillmentConfigurationMapping[]
expected?: Pick<FulfillmentStateExpected, 'status' | 'channel'>
onlyWhenConfigNull?: boolean
onlyWhenCanonicalProductNull?: boolean
onlyWhenCanonicalProductDifferent?: boolean
},
): Promise<OrderItemRow[]> {
const mappings = (input.mappings || []).map((row) => {
const setConfig = row.configId !== undefined
const setProduct = row.canonicalProductId !== undefined
const requireExpectedProduct = row.expectedCanonicalProductId !== undefined
if (!setConfig && !setProduct) {
throw new TypeError(
'fulfillment configuration mapping must set configId or canonicalProductId',
)
}
return {
orderItemId: normalizeId(row.orderItemId),
setConfig,
configId:
row.configId === null || row.configId === undefined ? null : normalizeId(row.configId),
setProduct,
canonicalProductId:
row.canonicalProductId === null || row.canonicalProductId === undefined
? null
: normalizeId(row.canonicalProductId),
requireExpectedProduct,
expectedCanonicalProductId:
row.expectedCanonicalProductId === null || row.expectedCanonicalProductId === undefined
? null
: normalizeId(row.expectedCanonicalProductId),
}
})
if (mappings.length === 0) return []
if (new Set(mappings.map((row) => row.orderItemId)).size !== mappings.length) {
throw new TypeError('fulfillment configuration mappings must contain unique orderItemId')
}
const params: unknown[] = [
mappings.map((row) => row.orderItemId),
mappings.map((row) => row.setConfig),
mappings.map((row) => row.configId),
mappings.map((row) => row.setProduct),
mappings.map((row) => row.canonicalProductId),
mappings.map((row) => row.requireExpectedProduct),
mappings.map((row) => row.expectedCanonicalProductId),
]
const where = ['item.order_item_id = input.order_item_id']
if (input.expected?.status !== undefined) {
params.push(input.expected.status)
where.push(`item.status IS NOT DISTINCT FROM $${params.length}`)
}
if (input.expected?.channel !== undefined) {
params.push(input.expected.channel)
where.push(`item.channel IS NOT DISTINCT FROM $${params.length}`)
}
if (input.onlyWhenConfigNull) {
where.push('item.fulfillment_config_id IS NULL')
}
if (input.onlyWhenCanonicalProductDifferent) {
where.push(
'(NOT input.set_product OR item.canonical_product_id IS DISTINCT FROM input.canonical_product_id)',
)
}
where.push(
'(NOT input.require_expected_product ' +
'OR item.canonical_product_id IS NOT DISTINCT FROM input.expected_canonical_product_id)',
)
const canonicalProductIfNull = input.onlyWhenCanonicalProductNull === true
params.push(canonicalProductIfNull)
const canonicalProductIfNullParam = params.length
params.push(new Date().toISOString())
const updatedAtParam = params.length
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
END,
canonical_product_id = CASE
WHEN NOT input.set_product THEN item.canonical_product_id
WHEN $${canonicalProductIfNullParam}::boolean
THEN COALESCE(item.canonical_product_id, input.canonical_product_id)
ELSE input.canonical_product_id
END,
updated_at = $${updatedAtParam}::timestamptz
FROM unnest(
$1::bigint[],
$2::boolean[],
$3::bigint[],
$4::boolean[],
$5::bigint[],
$6::boolean[],
$7::bigint[]
) AS input(
order_item_id,
set_config,
config_id,
set_product,
canonical_product_id,
require_expected_product,
expected_canonical_product_id
)
WHERE ${where.join(' AND ')}
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
}
export async function attachFulfillmentConfigurations(input: {
mappings: FulfillmentConfigurationMapping[]
expected?: Pick<FulfillmentStateExpected, 'status' | 'channel'>
onlyWhenConfigNull?: boolean
onlyWhenCanonicalProductNull?: boolean
onlyWhenCanonicalProductDifferent?: boolean
}): Promise<OrderItemRow[]> {
return withTransaction((client) =>
attachFulfillmentConfigurationsWithExecutor(client as FulfillmentStateExecutor, input),
)
}
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)
}