Files
order_site/apps/backend/src/services/fulfillment/carrier-creation-service.ts
T
yml2213 cb9538a775 新增:半自动履约工作台与虎牙客户授权流程
- 新增 153 半自动履约迁移、后台任务接口与客户履约接口
- 接入虎牙 Connector 登录会话、绑定与一次性 CK 注入票据
- 新增后台半自动履约页面和客户履约入口
- 完善手工履约配置、成本确认事务与运行时连接器配置
- 同步权威文档、环境示例、部署脚本和迁移展示逻辑
2026-11-09 15:29:20 +08:00

401 lines
13 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 { canonicalizeInternalSku, resolveInternalSkuKey } from './internal-sku-resolver.js'
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)) {
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
}
const BLOCKED_WORK_ORDER_STATUSES = new Set(['closed', 'cancelled', 'manual_review'])
const HARD_BLOCKED_INACTIVE_REASONS = new Set([
'carrier_task_user_refund',
'carrier_task_cancelled',
])
async function findBlockingInactiveCarrier(input: {
orderItemId: number
channel: FulfillmentChannel
}): Promise<{ status: string; reason: string; message: string } | null> {
if (input.channel !== 'affiliate_dash' && input.channel !== 'work_order') return null
const result =
input.channel === 'affiliate_dash'
? await query<{ status: string; result_code: string }>(
`SELECT task_status AS status, result_code
FROM fulfillment_tasks
WHERE order_item_id = $1 AND executor_key = 'affiliate_dash'
ORDER BY id DESC
LIMIT 1`,
[input.orderItemId],
)
: await query<{ status: string; result_code: string }>(
`SELECT status, '' AS result_code
FROM work_orders
WHERE order_item_id = $1
ORDER BY id DESC
LIMIT 1`,
[input.orderItemId],
)
const status = String(result.rows[0]?.status || '')
const resultCode = String(result.rows[0]?.result_code || '')
const shouldBlock =
input.channel === 'affiliate_dash'
? INACTIVE_CARRIER_TASK_STATUSES.includes(
status as (typeof INACTIVE_CARRIER_TASK_STATUSES)[number],
)
: BLOCKED_WORK_ORDER_STATUSES.has(status)
if (!shouldBlock) return null
if (status === 'manual_review') {
return {
status,
reason: 'carrier_task_manual_review',
message: '已有履约载体进入人工复核,需先处理后再重试',
}
}
if (status === 'retry_pending' || status === 'failed') {
return {
status,
reason: 'carrier_task_retry_pending',
message: '已有履约任务失败待重试,需由运营确认后重新创建',
}
}
if (status === 'expired') {
return {
status,
reason: 'carrier_task_expired',
message: '已有履约任务已过期,需由运营确认后重新创建',
}
}
if (resultCode === 'USER_APPLY_REFUND') {
return {
status,
reason: 'carrier_task_user_refund',
message: '用户已申请退款,不能自动重新发货',
}
}
if (resultCode === 'affiliate_dash_cancelled') {
return {
status,
reason: 'carrier_task_cancelled',
message: '上游履约订单已取消,不能自动重新发货',
}
}
return {
status,
reason: 'carrier_task_closed',
message:
status === 'cancelled'
? '已有履约载体已取消,需由运营确认后重新创建'
: '已有履约载体已关闭,需由运营确认后重新创建',
}
}
function shouldBlockInactiveCarrier(
inactiveCarrier: { reason: string } | null,
retryInactiveCarrier: boolean,
): inactiveCarrier is { status: string; reason: string; message: string } {
if (!inactiveCarrier) return false
return !retryInactiveCarrier || HARD_BLOCKED_INACTIVE_REASONS.has(inactiveCarrier.reason)
}
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
retryInactiveCarrier?: boolean
}): Promise<EnsureCarrierResult> {
const { order, item, channel, retryInactiveCarrier = false } = input
const existingCarrier = findConflictingCarrier(
await loadActiveCarrierEvidenceForItem(Number(item.id)),
channel,
)
if (existingCarrier) {
return {
ready: false,
created: false,
reason: 'existing_carrier_conflict',
message: `订单项已有其它真实载体:${existingCarrier}`,
}
}
if (channel === 'manual') {
const config = await query<{
id: number
canonical_product_id: number | null
semi_auto_enabled: boolean
semi_auto_platform: string
}>(
`SELECT id, canonical_product_id, semi_auto_enabled, semi_auto_platform
FROM manual_fulfillment_configs
WHERE canonicalize_internal_sku(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 attachFulfillmentConfigurations({
mappings: [
{
orderItemId: Number(item.id),
configId: Number(row.id),
...(row.canonical_product_id
? { canonicalProductId: Number(row.canonical_product_id) }
: {}),
},
],
onlyWhenCanonicalProductNull: true,
})
if (
row.semi_auto_enabled === true &&
['huya', 'weibo'].includes(String(row.semi_auto_platform || ''))
) {
const { ensureSemiAutoTasksForOrder } =
await import('../semi-auto/semi-auto-task-service.js')
await ensureSemiAutoTasksForOrder(order.platform_order_id)
}
return { ready: true, created: false, reason: 'manual_config_ready', message: '' }
}
return {
ready: false,
created: false,
reason: 'manual_config_missing',
message: '人工渠道已指定,但该内部 SKU 尚未配置人工履约',
}
}
if (channel === 'third_party_voucher') {
return { ready: true, created: false, reason: 'carrier_not_required', message: '' }
}
if (channel === 'on_account') {
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 inactiveCarrier = await findBlockingInactiveCarrier({
orderItemId: Number(item.id),
channel,
})
if (shouldBlockInactiveCarrier(inactiveCarrier, retryInactiveCarrier)) {
return {
ready: false,
created: false,
reason: inactiveCarrier.reason,
message: inactiveCarrier.message,
}
}
const internalSku = canonicalizeInternalSku(
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 route.carrier_config_json AS config_json
FROM sku_channel_routes route
JOIN internal_skus sku ON sku.id = route.internal_sku_id
WHERE sku.internal_sku_key = $1
AND route.channel = 'work_order'
AND route.enabled = TRUE
LIMIT 1`,
[internalSku],
)
const preferredWorkRuleKey = String(
channelConfig.rows[0]?.config_json?.workRuleKey || '',
).trim()
if (!preferredWorkRuleKey) {
return {
ready: false,
created: false,
reason: 'work_rule_missing',
message: '接单平台渠道缺少 workRuleKey,请先补全统一 SKU 配置',
}
}
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,
retryCancelledWorkOrder: retryInactiveCarrier,
})
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 inactiveCarrier = await findBlockingInactiveCarrier({
orderItemId: Number(item.id),
channel,
})
if (shouldBlockInactiveCarrier(inactiveCarrier, retryInactiveCarrier)) {
return {
ready: false,
created: false,
reason: inactiveCarrier.reason,
message: inactiveCarrier.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,
],
{ allowInactiveTaskRetry: retryInactiveCarrier },
)
}
const ready = await hasAffiliateTask(Number(item.id))
return {
ready,
created: ready && !before,
reason: ready ? 'affiliate_task_created' : 'affiliate_task_planning_failed',
message: ready ? '' : '自动发货任务规划失败',
}
}