refactor(fulfillment): 收敛配置与商品关联写入
This commit is contained in:
@@ -10,6 +10,7 @@ import {
|
||||
findConflictingCarrier,
|
||||
loadActiveCarrierEvidenceForItem,
|
||||
} from './carrier-evidence-service.js'
|
||||
import { attachFulfillmentConfigurations } from './fulfillment-state-service.js'
|
||||
|
||||
function parseObject(value: unknown): Record<string, unknown> {
|
||||
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
||||
@@ -200,14 +201,18 @@ export async function ensureCarrierForOrderItem(input: {
|
||||
)
|
||||
const row = config.rows[0]
|
||||
if (row) {
|
||||
await query(
|
||||
`UPDATE order_items
|
||||
SET fulfillment_config_id = $2,
|
||||
canonical_product_id = COALESCE(canonical_product_id, $3),
|
||||
updated_at = NOW()
|
||||
WHERE id = $1`,
|
||||
[item.id, row.id, row.canonical_product_id],
|
||||
)
|
||||
await attachFulfillmentConfigurations({
|
||||
mappings: [
|
||||
{
|
||||
orderItemId: Number(item.id),
|
||||
configId: Number(row.id),
|
||||
...(row.canonical_product_id
|
||||
? { canonicalProductId: Number(row.canonical_product_id) }
|
||||
: {}),
|
||||
},
|
||||
],
|
||||
onlyWhenCanonicalProductNull: true,
|
||||
})
|
||||
return { ready: true, created: false, reason: 'manual_config_ready', message: '' }
|
||||
}
|
||||
return {
|
||||
|
||||
@@ -37,6 +37,7 @@ import { canonicalizeInternalSku, containsCjk } from './internal-sku-resolver.js
|
||||
import { scheduleVoucherConsumeForOrderItems } from './voucher-consume-queue-service.js'
|
||||
import {
|
||||
assignFulfillmentChannelsWithExecutor,
|
||||
attachFulfillmentConfigurations,
|
||||
transitionFulfillmentState,
|
||||
transitionFulfillmentStateBatch,
|
||||
transitionFulfillmentStateBatchWithExecutor,
|
||||
@@ -1421,20 +1422,39 @@ export async function retryPendingCarrierGroup(input: {
|
||||
assignedItemIds.push(...applied.assignedItemIds)
|
||||
}
|
||||
|
||||
await query(
|
||||
`UPDATE order_items oi
|
||||
SET fulfillment_config_id = cfg.id,
|
||||
canonical_product_id = COALESCE(oi.canonical_product_id, cfg.canonical_product_id),
|
||||
updated_at = NOW()
|
||||
FROM manual_fulfillment_configs cfg
|
||||
const manualConfigs = await query<{
|
||||
order_item_id: number
|
||||
config_id: number
|
||||
canonical_product_id: number | null
|
||||
}>(
|
||||
`SELECT DISTINCT ON (oi.id)
|
||||
oi.id AS order_item_id,
|
||||
cfg.id AS config_id,
|
||||
cfg.canonical_product_id
|
||||
FROM order_items oi
|
||||
JOIN manual_fulfillment_configs cfg
|
||||
ON canonicalize_internal_sku(cfg.sku_key) =
|
||||
resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code)
|
||||
AND cfg.enabled = TRUE
|
||||
WHERE oi.id = ANY($1::bigint[])
|
||||
AND oi.fulfillment_status = 'assigned'
|
||||
AND oi.fulfillment_channel = 'manual'
|
||||
AND cfg.enabled = TRUE
|
||||
AND canonicalize_internal_sku(cfg.sku_key) =
|
||||
resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code)`,
|
||||
ORDER BY oi.id, cfg.id`,
|
||||
[ids],
|
||||
)
|
||||
if (manualConfigs.rows.length > 0) {
|
||||
await attachFulfillmentConfigurations({
|
||||
mappings: manualConfigs.rows.map((row) => ({
|
||||
orderItemId: Number(row.order_item_id),
|
||||
configId: Number(row.config_id),
|
||||
...(row.canonical_product_id
|
||||
? { canonicalProductId: Number(row.canonical_product_id) }
|
||||
: {}),
|
||||
})),
|
||||
expected: { status: 'assigned', channel: 'manual' },
|
||||
onlyWhenCanonicalProductNull: true,
|
||||
})
|
||||
}
|
||||
if (assignedItemIds.length > 0) {
|
||||
await normalizeProductsForItems(assignedItemIds).catch(() => undefined)
|
||||
const cost = await syncCostSnapshotsForItems(assignedItemIds).catch(() => null)
|
||||
|
||||
@@ -17,6 +17,7 @@ test(
|
||||
const { closeDb, query } = await import('../../db/client.js')
|
||||
const {
|
||||
assignFulfillmentChannelsWithExecutor,
|
||||
attachFulfillmentConfigurations,
|
||||
listFulfillmentStateEvents,
|
||||
runWithFulfillmentStateTransaction,
|
||||
transitionFulfillmentState,
|
||||
@@ -24,6 +25,8 @@ test(
|
||||
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
|
||||
let orderId = 0
|
||||
let orderItemId = 0
|
||||
let manualConfigId = 0
|
||||
let productId = 0
|
||||
|
||||
try {
|
||||
const order = await query<{ id: number }>(
|
||||
@@ -143,6 +146,53 @@ test(
|
||||
assert.equal(events[0]?.previous_channel, null)
|
||||
assert.equal(events[0]?.next_channel, 'third_party_voucher')
|
||||
|
||||
const product = await query<{ id: number }>(
|
||||
`INSERT INTO product_catalog (
|
||||
canonical_sku, canonical_name, category, unit_name, status,
|
||||
attributes_json, created_at, updated_at
|
||||
) VALUES ($1, $2, '测试', '件', 'active', '{}'::jsonb, NOW(), NOW())
|
||||
RETURNING id`,
|
||||
[`test:ff-state-${suffix}`, `状态事件商品-${suffix}`],
|
||||
)
|
||||
productId = Number(product.rows[0]!.id)
|
||||
const config = await query<{ id: number }>(
|
||||
`INSERT INTO manual_fulfillment_configs (
|
||||
sku_key, canonical_product_id, platform_key, credit_quantity,
|
||||
cost_mode, enabled, note, created_at, updated_at
|
||||
) VALUES ($1, $2, 'nanhang', 1, 'fixed', TRUE, 'integration_test', NOW(), NOW())
|
||||
RETURNING id`,
|
||||
[`状态事件测试-${suffix}`, productId],
|
||||
)
|
||||
manualConfigId = Number(config.rows[0]!.id)
|
||||
const staleConfig = await attachFulfillmentConfigurations({
|
||||
mappings: [
|
||||
{
|
||||
orderItemId,
|
||||
configId: manualConfigId,
|
||||
canonicalProductId: productId,
|
||||
expectedCanonicalProductId: manualConfigId,
|
||||
},
|
||||
],
|
||||
onlyWhenCanonicalProductNull: true,
|
||||
})
|
||||
assert.equal(staleConfig.length, 0, '原商品值已变化时不能覆盖并发结果')
|
||||
|
||||
const configured = await attachFulfillmentConfigurations({
|
||||
mappings: [
|
||||
{
|
||||
orderItemId,
|
||||
configId: manualConfigId,
|
||||
canonicalProductId: productId,
|
||||
},
|
||||
],
|
||||
expected: { status: 'assigned', channel: 'third_party_voucher' },
|
||||
onlyWhenConfigNull: true,
|
||||
onlyWhenCanonicalProductNull: true,
|
||||
})
|
||||
assert.equal(configured.length, 1)
|
||||
assert.equal(Number(configured[0]?.fulfillment_config_id), manualConfigId)
|
||||
assert.equal(Number(configured[0]?.canonical_product_id), productId)
|
||||
|
||||
await assert.rejects(
|
||||
query(`UPDATE fulfillment_state_events SET reason = 'tampered' WHERE order_item_id = $1`, [
|
||||
orderItemId,
|
||||
@@ -153,6 +203,12 @@ test(
|
||||
if (orderItemId > 0) {
|
||||
await query(`DELETE FROM order_items WHERE id = $1`, [orderItemId])
|
||||
}
|
||||
if (manualConfigId > 0) {
|
||||
await query(`DELETE FROM manual_fulfillment_configs WHERE id = $1`, [manualConfigId])
|
||||
}
|
||||
if (productId > 0) {
|
||||
await query(`DELETE FROM product_catalog WHERE id = $1`, [productId])
|
||||
}
|
||||
if (orderId > 0) {
|
||||
await query(`DELETE FROM orders WHERE id = $1`, [orderId])
|
||||
}
|
||||
|
||||
@@ -11,6 +11,15 @@ const stateService = read('./fulfillment-state-service.ts')
|
||||
const channelAssign = read('./channel-assign-service.ts')
|
||||
const carrierReconciliation = read('./carrier-reconciliation-service.ts')
|
||||
const affiliateFallback = read('./affiliate-fallback-service.ts')
|
||||
const carrierCreation = read('./carrier-creation-service.ts')
|
||||
const manualFulfillment = read('../finance/manual-fulfillment-service.ts')
|
||||
const manualConfig = read('../cost-center/manual-fulfillment-config-service.ts')
|
||||
const productNormalize = read('../cost-center/product-normalize-service.ts')
|
||||
const productCatalog = read('../cost-center/product-catalog-service.ts')
|
||||
const affiliateProduct = read('../cost-center/affiliate-product-service.ts')
|
||||
const workOrderProduct = read('../cost-center/work-order-product-service.ts')
|
||||
const templateBootstrap = read('../cost-center/template-bootstrap-service.ts')
|
||||
const schedulerJobs = read('../scheduler/finance-pipeline-jobs.ts')
|
||||
const taskRepo = read('../../repositories/task-repo.ts')
|
||||
|
||||
test('履约状态事件表记录前后状态并禁止应用修改', () => {
|
||||
@@ -40,6 +49,26 @@ test('高风险履约流程统一通过状态服务写入', () => {
|
||||
}
|
||||
})
|
||||
|
||||
test('履约配置和标准商品关联统一通过状态服务的映射接口写入', () => {
|
||||
for (const source of [
|
||||
carrierCreation,
|
||||
manualFulfillment,
|
||||
manualConfig,
|
||||
productNormalize,
|
||||
productCatalog,
|
||||
affiliateProduct,
|
||||
workOrderProduct,
|
||||
templateBootstrap,
|
||||
schedulerJobs,
|
||||
]) {
|
||||
assert.ok(source.includes('fulfillment-state-service'))
|
||||
assert.doesNotMatch(source, /UPDATE\s+order_items\b[\s\S]{0,300}?\bfulfillment_config_id\s*=/i)
|
||||
assert.doesNotMatch(source, /UPDATE\s+order_items\b[\s\S]{0,300}?\bcanonical_product_id\s*=/i)
|
||||
}
|
||||
assert.ok(stateService.includes('attachFulfillmentConfigurationsWithExecutor'))
|
||||
assert.ok(stateService.includes('onlyWhenCanonicalProductNull'))
|
||||
})
|
||||
|
||||
test('任务创建先锁订单项并复用已有活跃尝试', () => {
|
||||
assert.ok(taskRepo.includes('SELECT id FROM order_items WHERE id = $1 FOR UPDATE'))
|
||||
assert.ok(taskRepo.includes('task_status NOT IN ('))
|
||||
|
||||
@@ -86,6 +86,13 @@ export type FulfillmentStateEventRow = {
|
||||
created_at: string
|
||||
}
|
||||
|
||||
export type FulfillmentConfigurationMapping = {
|
||||
orderItemId: number
|
||||
configId?: number | null
|
||||
canonicalProductId?: number | null
|
||||
expectedCanonicalProductId?: number | null
|
||||
}
|
||||
|
||||
type StateColumn = {
|
||||
column: string
|
||||
value: unknown
|
||||
@@ -430,6 +437,132 @@ export async function assignFulfillmentChannelsWithExecutor(
|
||||
}
|
||||
}
|
||||
|
||||
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.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}`)
|
||||
}
|
||||
if (input.expected?.channel !== undefined) {
|
||||
params.push(input.expected.channel)
|
||||
where.push(`item.fulfillment_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 result = await executor.query<OrderItemRow>(
|
||||
`UPDATE order_items 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.*`,
|
||||
params,
|
||||
)
|
||||
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 } = {},
|
||||
|
||||
Reference in New Issue
Block a user