fix(finance): 收敛内部 SKU 履约路由与载体状态
统一内部 SKU 与渠道主/兜底解析,禁止并列主渠道。 运营指定渠道改为先创建真实载体,失败保持明确 pending。 历史缺载体、多载体冲突和自动发货兜底统一由管道修复。 迁移人工配置与旧 sku_code 规则,补充严格预检和集成测试。
This commit is contained in:
@@ -0,0 +1,202 @@
|
||||
import { query } from '../../db/client.js'
|
||||
import type { OrderItemRow, OrderRow } from '../../types/repository/rows.js'
|
||||
import { syncDeliveryTasksForOrder } from '../order/delivery-task-service.js'
|
||||
import { syncWorkerOrdersForSourceOrder } from '../worker-platform/sync-worker-orders-service.js'
|
||||
import type { FulfillmentChannel } from './channel-types.js'
|
||||
import { applyIntakeChannelDecision } from './intake-channel-decision-service.js'
|
||||
import type { ResolvedFulfillmentItem } from './product-resolution-service.js'
|
||||
|
||||
function parseObject(value: unknown): Record<string, unknown> {
|
||||
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
||||
return value as Record<string, unknown>
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(String(value || '{}'))
|
||||
return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
|
||||
? (parsed as Record<string, unknown>)
|
||||
: {}
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
export type EnsureCarrierResult = {
|
||||
ready: boolean
|
||||
created: boolean
|
||||
reason: string
|
||||
message: string
|
||||
}
|
||||
|
||||
async function hasWorkOrder(orderItemId: number): Promise<boolean> {
|
||||
const result = await query<{ exists: boolean }>(
|
||||
`SELECT EXISTS (SELECT 1 FROM work_orders WHERE order_item_id = $1) AS exists`,
|
||||
[orderItemId],
|
||||
)
|
||||
return result.rows[0]?.exists === true
|
||||
}
|
||||
|
||||
async function hasAffiliateTask(orderItemId: number): Promise<boolean> {
|
||||
const result = await query<{ exists: boolean }>(
|
||||
`SELECT EXISTS (
|
||||
SELECT 1 FROM fulfillment_tasks
|
||||
WHERE order_item_id = $1 AND executor_key = 'affiliate_dash'
|
||||
) AS exists`,
|
||||
[orderItemId],
|
||||
)
|
||||
return result.rows[0]?.exists === true
|
||||
}
|
||||
|
||||
function toResolvedItem(item: OrderItemRow): ResolvedFulfillmentItem {
|
||||
return {
|
||||
...item,
|
||||
itemId: String(item.id),
|
||||
externalItemId: String(item.id),
|
||||
externalSkuCode: item.sku_code,
|
||||
externalSkuName: item.sku_name,
|
||||
skuCode: item.sku_code,
|
||||
skuName: item.sku_name,
|
||||
spec: parseObject(item.spec_json),
|
||||
snapshot: parseObject(item.item_snapshot_json),
|
||||
isConfigured: false,
|
||||
} as ResolvedFulfillmentItem
|
||||
}
|
||||
|
||||
/**
|
||||
* 幂等创建指定渠道的真实载体。
|
||||
*
|
||||
* 自动发货成功标准是存在 affiliate_dash 任务;接单成功标准是存在 work_order。
|
||||
* manual/voucher 不需要执行载体,直接视为 ready。
|
||||
*/
|
||||
export async function ensureCarrierForOrderItem(input: {
|
||||
order: OrderRow
|
||||
item: OrderItemRow
|
||||
channel: FulfillmentChannel
|
||||
}): Promise<EnsureCarrierResult> {
|
||||
const { order, item, channel } = input
|
||||
|
||||
if (channel === 'manual') {
|
||||
const config = await query<{ id: number; canonical_product_id: number | null }>(
|
||||
`SELECT id, canonical_product_id
|
||||
FROM manual_fulfillment_configs
|
||||
WHERE sku_key = resolve_internal_sku($1, $2, $3) AND enabled = TRUE
|
||||
LIMIT 1`,
|
||||
[item.manual_sku_key || '', item.sku_name, item.sku_code],
|
||||
)
|
||||
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],
|
||||
)
|
||||
return { ready: true, created: false, reason: 'manual_config_ready', message: '' }
|
||||
}
|
||||
return {
|
||||
ready: true,
|
||||
created: false,
|
||||
reason: 'manual_config_missing',
|
||||
message: '人工渠道已选定,但缺少人工履约配置',
|
||||
}
|
||||
}
|
||||
|
||||
if (channel === 'third_party_voucher') {
|
||||
return { ready: true, created: false, reason: 'carrier_not_required', message: '' }
|
||||
}
|
||||
|
||||
if (channel === 'work_order') {
|
||||
if (await hasWorkOrder(Number(item.id))) {
|
||||
return { ready: true, created: false, reason: 'work_order_exists', message: '' }
|
||||
}
|
||||
const snapshot = parseObject(item.item_snapshot_json)
|
||||
const classification = parseObject(snapshot.classification)
|
||||
const route = parseObject(snapshot.fulfillmentRoute)
|
||||
const workOrderSnapshot = {
|
||||
...snapshot,
|
||||
classification: { ...classification, channel: 'work_order' },
|
||||
fulfillmentRoute: {
|
||||
...route,
|
||||
selectedExecutorKey: '',
|
||||
reason: '内部 SKU 渠道指定接单平台',
|
||||
},
|
||||
}
|
||||
const workOrderItem = {
|
||||
...item,
|
||||
item_snapshot_json: workOrderSnapshot,
|
||||
} as OrderItemRow
|
||||
const result = await syncWorkerOrdersForSourceOrder(order, [workOrderItem], {
|
||||
source: 'carrier_creation',
|
||||
autoOnly: true,
|
||||
skipChannelAssign: true,
|
||||
})
|
||||
const ready = (await hasWorkOrder(Number(item.id))) || result.created.length > 0
|
||||
if (ready) {
|
||||
await query(
|
||||
`UPDATE order_items SET item_snapshot_json = $2::jsonb, updated_at = NOW() WHERE id = $1`,
|
||||
[item.id, JSON.stringify(workOrderSnapshot)],
|
||||
)
|
||||
}
|
||||
return {
|
||||
ready,
|
||||
created: result.created.length > 0,
|
||||
reason: ready ? 'work_order_created' : result.skipped[0]?.reason || 'work_order_unmatched',
|
||||
message: ready ? '' : '未匹配到可自动创建的接单模板',
|
||||
}
|
||||
}
|
||||
|
||||
if (await hasAffiliateTask(Number(item.id))) {
|
||||
return { ready: true, created: false, reason: 'affiliate_task_exists', message: '' }
|
||||
}
|
||||
|
||||
const resolved = await applyIntakeChannelDecision(
|
||||
toResolvedItem(item),
|
||||
{
|
||||
provider: order.provider,
|
||||
platform: order.platform,
|
||||
shopId: order.shop_id,
|
||||
},
|
||||
{ preferredChannel: 'affiliate_dash' },
|
||||
)
|
||||
const snapshot = parseObject(resolved.snapshot)
|
||||
const route = parseObject(snapshot.fulfillmentRoute)
|
||||
if (route.selectedExecutorKey !== 'affiliate_dash') {
|
||||
return {
|
||||
ready: false,
|
||||
created: false,
|
||||
reason: 'affiliate_mapping_missing',
|
||||
message: '自动发货映射缺失',
|
||||
}
|
||||
}
|
||||
|
||||
await query(
|
||||
`UPDATE order_items
|
||||
SET sku_code = $2, spec_json = $3::jsonb, item_snapshot_json = $4::jsonb, updated_at = NOW()
|
||||
WHERE id = $1`,
|
||||
[
|
||||
item.id,
|
||||
String(resolved.skuCode || item.sku_code),
|
||||
JSON.stringify(resolved.spec || {}),
|
||||
JSON.stringify(snapshot),
|
||||
],
|
||||
)
|
||||
const before = await hasAffiliateTask(Number(item.id))
|
||||
if (!before) {
|
||||
await syncDeliveryTasksForOrder(order, [
|
||||
{
|
||||
...item,
|
||||
sku_code: String(resolved.skuCode || item.sku_code),
|
||||
spec_json: resolved.spec || {},
|
||||
item_snapshot_json: snapshot,
|
||||
} as OrderItemRow,
|
||||
])
|
||||
}
|
||||
const ready = await hasAffiliateTask(Number(item.id))
|
||||
return {
|
||||
ready,
|
||||
created: ready && !before,
|
||||
reason: ready ? 'affiliate_task_created' : 'affiliate_task_planning_failed',
|
||||
message: ready ? '' : '自动发货任务规划失败',
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user