Files
order_site/apps/backend/src/services/fulfillment/carrier-creation-service.ts
T
yml2213 6bf28489e0 fix(finance): 重写履约路由迁移与统一渠道配置
重写 120/121 迁移,统一内部 SKU、渠道 id、config_json 和旧规则转换。

后台渠道配置改读统一渠道表,卡券与人工配置不再写旧规则。

增加安全渠道切换,并排除已关闭、失败或过期的历史任务载体。

按生产 119 基线重跑迁移、完整履约财务链路和严格预检。
2026-11-02 15:29:13 +08:00

225 lines
7.4 KiB
TypeScript

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 { INACTIVE_CARRIER_TASK_STATUSES, type FulfillmentChannel } from './channel-types.js'
import { applyIntakeChannelDecision } from './intake-channel-decision-service.js'
import type { ResolvedFulfillmentItem } from './product-resolution-service.js'
import { resolveInternalSkuKey } from './internal-sku-resolver.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 AND status <> 'cancelled'
) 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'
AND task_status <> ALL($2::text[])
) AS exists`,
[orderItemId, INACTIVE_CARRIER_TASK_STATUSES],
)
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 internalSku = resolveInternalSkuKey({
manualSkuKey: item.manual_sku_key,
skuCode: item.sku_code,
skuName: item.sku_name,
spec: parseObject(item.spec_json),
snapshot: parseObject(item.item_snapshot_json),
})
const channelConfig = await query<{ config_json: Record<string, unknown> }>(
`SELECT config_json
FROM internal_sku_channels
WHERE btrim(internal_sku) = $1 AND channel = 'work_order' AND enabled = TRUE
LIMIT 1`,
[internalSku],
)
const preferredWorkRuleKey = String(
channelConfig.rows[0]?.config_json?.workRuleKey || '',
).trim()
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,
...(preferredWorkRuleKey ? { preferredWorkRuleKey } : {}),
})
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 ? '' : '自动发货任务规划失败',
}
}