fix(finance): 收敛内部 SKU 履约路由与载体状态
统一内部 SKU 与渠道主/兜底解析,禁止并列主渠道。 运营指定渠道改为先创建真实载体,失败保持明确 pending。 历史缺载体、多载体冲突和自动发货兜底统一由管道修复。 迁移人工配置与旧 sku_code 规则,补充严格预检和集成测试。
This commit is contained in:
@@ -1,4 +1,6 @@
|
||||
import { query } from '../../db/client.js'
|
||||
import { getOrderById } from '../../repositories/order-repo.js'
|
||||
import type { OrderItemRow } from '../../types/repository/rows.js'
|
||||
import { createHttpError } from '../../utils/http.js'
|
||||
import { nowIso } from '../../utils/time.js'
|
||||
import { upsertAggregatedException } from '../cost-center/cost-exception-service.js'
|
||||
@@ -18,6 +20,14 @@ import {
|
||||
type MatchKeyType,
|
||||
type RuleSource,
|
||||
} from './channel-types.js'
|
||||
import {
|
||||
disableInternalSkuChannel,
|
||||
planInternalSkuChannels,
|
||||
setInternalSkuPrimaryChannel,
|
||||
upsertInternalSkuChannel,
|
||||
type InternalSkuChannelRow,
|
||||
} from './internal-sku-channel-service.js'
|
||||
import { ensureCarrierForOrderItem } from './carrier-creation-service.js'
|
||||
|
||||
/**
|
||||
* 管道 A:渠道判定。
|
||||
@@ -27,19 +37,14 @@ import {
|
||||
*
|
||||
* 判定顺序:
|
||||
* 1. 运营锁定 → 跳过
|
||||
* 2. 精确规则(sku_channel_rules,优先级升序);同优先级命中多渠道 → 冲突,保持 pending
|
||||
* 3. 载体证据:已有工单 → work_order;已有自动发货任务 → affiliate_dash
|
||||
* 4. 都没有 → 保持 pending(不再兜底成人工)
|
||||
* 2. 已有且唯一的真实载体 → 直接按载体落渠道;多载体 → 冲突
|
||||
* 3. internal_sku_channels:一个主渠道 + 显式兜底;多主渠道 → 冲突
|
||||
* 4. 旧 sku_channel_rules 仅作兼容回退,且自动发货/接单仍必须有真实载体
|
||||
* 5. 都不满足 → 保留 pending 并写明确原因
|
||||
*/
|
||||
|
||||
/** 内部 SKU:优先中文手动键,其次中文商品名,最后平台 SKU。 */
|
||||
const INTERNAL_SKU_SQL = `
|
||||
CASE
|
||||
WHEN btrim(COALESCE(oi.manual_sku_key, '')) ~ '[一-龥]' THEN btrim(oi.manual_sku_key)
|
||||
WHEN btrim(COALESCE(oi.sku_name, '')) ~ '[一-龥]' THEN btrim(oi.sku_name)
|
||||
ELSE COALESCE(NULLIF(btrim(oi.manual_sku_key), ''), NULLIF(btrim(oi.sku_name), ''), oi.sku_code)
|
||||
END
|
||||
`
|
||||
/** 数据库函数 `resolve_internal_sku` 是订单项内部 SKU 的唯一 SQL 口径。 */
|
||||
const INTERNAL_SKU_SQL = `resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code)`
|
||||
|
||||
export type ChannelRule = {
|
||||
id: number
|
||||
@@ -64,7 +69,7 @@ export type ChannelCandidateItem = {
|
||||
has_work_order: boolean
|
||||
has_affiliate_task: boolean
|
||||
has_manual_task: boolean
|
||||
capability_channel: FulfillmentChannel | null
|
||||
channels: InternalSkuChannelRow[]
|
||||
basis_date: string
|
||||
}
|
||||
|
||||
@@ -74,6 +79,8 @@ export type ChannelDecision = {
|
||||
conflict: boolean
|
||||
conflictChannels: FulfillmentChannel[]
|
||||
matchedRuleIds: number[]
|
||||
pendingChannel: FulfillmentChannel | null
|
||||
pendingReason: 'no_internal_sku' | 'no_channel_capability' | 'no_carrier' | ''
|
||||
}
|
||||
|
||||
function normalizeKey(value: unknown): string {
|
||||
@@ -99,7 +106,14 @@ function resolvePendingReason(item: ChannelCandidateItem): {
|
||||
if (!String(item.internal_sku || '').trim()) {
|
||||
return { reason: 'no_internal_sku', detail: { skuCode: item.sku_code } }
|
||||
}
|
||||
if (!item.capability_channel) {
|
||||
const plan = planInternalSkuChannels(item.channels || [])
|
||||
if (plan.conflicts.length > 0) {
|
||||
return {
|
||||
reason: 'routing_conflict',
|
||||
detail: { channels: plan.conflicts.map((channel) => channel.channel) },
|
||||
}
|
||||
}
|
||||
if (!plan.primary) {
|
||||
return {
|
||||
reason: 'no_channel_capability',
|
||||
detail: { internalSku: item.internal_sku },
|
||||
@@ -107,15 +121,90 @@ function resolvePendingReason(item: ChannelCandidateItem): {
|
||||
}
|
||||
return {
|
||||
reason: 'no_carrier',
|
||||
detail: { internalSku: item.internal_sku, channel: item.capability_channel },
|
||||
detail: {
|
||||
internalSku: item.internal_sku,
|
||||
channel: plan.primary.channel,
|
||||
fallbacks: plan.fallbacks.map((channel) => channel.channel),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function emptyDecision(pendingReason: ChannelDecision['pendingReason'] = '') {
|
||||
return {
|
||||
channel: null,
|
||||
source: '',
|
||||
conflict: false,
|
||||
conflictChannels: [],
|
||||
matchedRuleIds: [],
|
||||
pendingChannel: null,
|
||||
pendingReason,
|
||||
} satisfies ChannelDecision
|
||||
}
|
||||
|
||||
/** 纯函数:给定规则与订单项,得出渠道决策(便于单测与文档对照)。 */
|
||||
export function resolveChannelDecision(
|
||||
item: ChannelCandidateItem,
|
||||
rules: ChannelRule[],
|
||||
): ChannelDecision {
|
||||
const carrierChannels: FulfillmentChannel[] = [
|
||||
...(item.has_work_order ? ['work_order' as const] : []),
|
||||
...(item.has_affiliate_task ? ['affiliate_dash' as const] : []),
|
||||
...(item.has_manual_task ? ['manual' as const] : []),
|
||||
]
|
||||
if (carrierChannels.length > 1) {
|
||||
return {
|
||||
channel: null,
|
||||
source: '',
|
||||
conflict: true,
|
||||
conflictChannels: carrierChannels,
|
||||
matchedRuleIds: [],
|
||||
pendingChannel: carrierChannels[0] || null,
|
||||
pendingReason: 'no_carrier',
|
||||
}
|
||||
}
|
||||
|
||||
const plan = planInternalSkuChannels(item.channels || [])
|
||||
if (plan.conflicts.length > 0) {
|
||||
return {
|
||||
channel: null,
|
||||
source: '',
|
||||
conflict: true,
|
||||
conflictChannels: plan.conflicts.map((channel) => channel.channel),
|
||||
matchedRuleIds: [],
|
||||
pendingChannel: null,
|
||||
pendingReason: 'no_channel_capability',
|
||||
}
|
||||
}
|
||||
|
||||
// 真实载体是最终事实;配置只能决定准备创建哪个载体,不能覆盖已经存在的另一类载体。
|
||||
const evidence = carrierChannels[0]
|
||||
if (evidence) {
|
||||
return {
|
||||
channel: evidence,
|
||||
source: 'carrier_evidence',
|
||||
conflict: false,
|
||||
conflictChannels: [],
|
||||
matchedRuleIds: [],
|
||||
pendingChannel: evidence,
|
||||
pendingReason: '',
|
||||
}
|
||||
}
|
||||
|
||||
if (plan.primary) {
|
||||
if (plan.primary.channel === 'manual' || plan.primary.channel === 'third_party_voucher') {
|
||||
return {
|
||||
channel: plan.primary.channel,
|
||||
source: 'auto_mapping',
|
||||
conflict: false,
|
||||
conflictChannels: [],
|
||||
matchedRuleIds: [],
|
||||
pendingChannel: plan.primary.channel,
|
||||
pendingReason: '',
|
||||
}
|
||||
}
|
||||
return emptyDecision('no_carrier')
|
||||
}
|
||||
|
||||
const hits = rules.filter(
|
||||
(rule) =>
|
||||
rule.enabled &&
|
||||
@@ -135,58 +224,25 @@ export function resolveChannelDecision(
|
||||
conflict: true,
|
||||
conflictChannels: channels,
|
||||
matchedRuleIds: best.map((rule) => rule.id),
|
||||
pendingChannel: null,
|
||||
pendingReason: 'no_channel_capability',
|
||||
}
|
||||
}
|
||||
const channel = channels[0]!
|
||||
if (channel === 'affiliate_dash' || channel === 'work_order') {
|
||||
return emptyDecision('no_carrier')
|
||||
}
|
||||
return {
|
||||
channel: channels[0]!,
|
||||
channel,
|
||||
source: 'auto_rule',
|
||||
conflict: false,
|
||||
conflictChannels: [],
|
||||
matchedRuleIds: best.map((rule) => rule.id),
|
||||
pendingChannel: channel,
|
||||
pendingReason: '',
|
||||
}
|
||||
}
|
||||
|
||||
if (item.has_work_order) {
|
||||
return {
|
||||
channel: 'work_order',
|
||||
source: 'carrier_evidence',
|
||||
conflict: false,
|
||||
conflictChannels: [],
|
||||
matchedRuleIds: [],
|
||||
}
|
||||
}
|
||||
if (item.has_affiliate_task) {
|
||||
return {
|
||||
channel: 'affiliate_dash',
|
||||
source: 'carrier_evidence',
|
||||
conflict: false,
|
||||
conflictChannels: [],
|
||||
matchedRuleIds: [],
|
||||
}
|
||||
}
|
||||
if (item.has_manual_task) {
|
||||
return {
|
||||
channel: 'manual',
|
||||
source: 'carrier_evidence',
|
||||
conflict: false,
|
||||
conflictChannels: [],
|
||||
matchedRuleIds: [],
|
||||
}
|
||||
}
|
||||
|
||||
// 卡券/人工没有必须创建的履约任务,可直接用商品渠道能力兜底;
|
||||
// 自动发货/接单平台仍要求真实载体,避免只改口径不派单。
|
||||
if (item.capability_channel === 'third_party_voucher' || item.capability_channel === 'manual') {
|
||||
return {
|
||||
channel: item.capability_channel,
|
||||
source: 'auto_mapping',
|
||||
conflict: false,
|
||||
conflictChannels: [],
|
||||
matchedRuleIds: [],
|
||||
}
|
||||
}
|
||||
|
||||
return { channel: null, source: '', conflict: false, conflictChannels: [], matchedRuleIds: [] }
|
||||
return emptyDecision('no_channel_capability')
|
||||
}
|
||||
|
||||
export type AssignChannelsResult = {
|
||||
@@ -257,27 +313,9 @@ export async function assignPendingOrderItemChannels(
|
||||
EXISTS (
|
||||
SELECT 1 FROM fulfillment_tasks ft
|
||||
WHERE ft.order_item_id = oi.id AND ft.executor_key = 'manual_dispatch'
|
||||
) AS has_manual_task,
|
||||
cap.channel AS capability_channel
|
||||
) AS has_manual_task
|
||||
FROM order_items oi
|
||||
JOIN orders o ON o.id = oi.order_id
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT c.channel
|
||||
FROM internal_sku_channels c
|
||||
WHERE c.enabled = TRUE
|
||||
AND btrim(c.internal_sku) = ${INTERNAL_SKU_SQL}
|
||||
ORDER BY
|
||||
c.priority ASC,
|
||||
CASE c.channel
|
||||
WHEN 'affiliate_dash' THEN 1
|
||||
WHEN 'work_order' THEN 2
|
||||
WHEN 'third_party_voucher' THEN 3
|
||||
WHEN 'manual' THEN 4
|
||||
ELSE 9
|
||||
END,
|
||||
c.channel ASC
|
||||
LIMIT 1
|
||||
) cap ON TRUE
|
||||
WHERE oi.fulfillment_status = 'pending'
|
||||
AND oi.fulfillment_locked = FALSE
|
||||
AND oi.id > $1
|
||||
@@ -302,11 +340,33 @@ export async function assignPendingOrderItemChannels(
|
||||
source: FulfillmentSource
|
||||
}> = []
|
||||
|
||||
for (const item of rows.rows) {
|
||||
const channelsByInternalSku = await loadInternalSkuChannelsForKeys(
|
||||
rows.rows.map((item) => item.internal_sku),
|
||||
)
|
||||
|
||||
for (const row of rows.rows) {
|
||||
const item: ChannelCandidateItem = {
|
||||
...row,
|
||||
channels: channelsByInternalSku.get(normalizeKey(row.internal_sku)) || [],
|
||||
}
|
||||
const decision = resolveChannelDecision(item, rules)
|
||||
if (decision.channel) affectedDates.add(item.basis_date)
|
||||
if (decision.conflict) {
|
||||
result.conflicted += 1
|
||||
await query(
|
||||
`UPDATE order_items
|
||||
SET fulfillment_pending_reason = 'routing_conflict',
|
||||
fulfillment_pending_detail = $2::jsonb,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1 AND fulfillment_status = 'pending'`,
|
||||
[
|
||||
item.id,
|
||||
JSON.stringify({
|
||||
channels: decision.conflictChannels,
|
||||
ruleIds: decision.matchedRuleIds,
|
||||
}),
|
||||
],
|
||||
)
|
||||
await upsertAggregatedException({
|
||||
reason: 'routing_conflict',
|
||||
scopeKey: `routing_conflict|${item.provider}|${item.shop_id}|${item.sku_code}|-`,
|
||||
@@ -367,13 +427,163 @@ export async function assignPendingOrderItemChannels(
|
||||
return result
|
||||
}
|
||||
|
||||
/** 运营指定渠道:写入并锁定,自动判定不再覆盖。 */
|
||||
async function assignOrderItemsAfterCarrierReady(input: {
|
||||
orderItemIds: number[]
|
||||
channel: FulfillmentChannel
|
||||
source: FulfillmentSource
|
||||
lock: boolean
|
||||
note?: string | undefined
|
||||
}): Promise<{ updated: number; carrierFailed: number }> {
|
||||
const ids = [
|
||||
...new Set(input.orderItemIds.map(Number).filter((id) => Number.isInteger(id) && id > 0)),
|
||||
]
|
||||
if (ids.length === 0) return { updated: 0, carrierFailed: 0 }
|
||||
|
||||
const items = (
|
||||
await query<OrderItemRow>(`SELECT * FROM order_items WHERE id = ANY($1::bigint[])`, [ids])
|
||||
).rows
|
||||
const orderIds = [...new Set(items.map((item) => Number(item.order_id)))]
|
||||
const orders = new Map(
|
||||
(await Promise.all(orderIds.map((orderId) => getOrderById(orderId))))
|
||||
.filter((order): order is NonNullable<typeof order> => Boolean(order))
|
||||
.map((order) => [Number(order.id), order]),
|
||||
)
|
||||
const assignedIds: number[] = []
|
||||
let carrierFailed = 0
|
||||
|
||||
for (const item of items) {
|
||||
if (item.fulfillment_status === 'archived') continue
|
||||
const order = orders.get(Number(item.order_id))
|
||||
if (!order) continue
|
||||
|
||||
if (
|
||||
item.fulfillment_status === 'assigned' &&
|
||||
item.fulfillment_channel &&
|
||||
item.fulfillment_channel !== input.channel
|
||||
) {
|
||||
// 旧载体尚未撤销时禁止直接换渠道,否则会同时留下两个履约执行方。
|
||||
carrierFailed += 1
|
||||
await query(
|
||||
`UPDATE order_items
|
||||
SET fulfillment_reason = $2, updated_at = NOW()
|
||||
WHERE id = $1 AND fulfillment_status = 'assigned'`,
|
||||
[item.id, '切换渠道前需先撤销现有履约载体'],
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
let carrier
|
||||
try {
|
||||
carrier = await ensureCarrierForOrderItem({ order, item, channel: input.channel })
|
||||
} catch (error) {
|
||||
carrier = {
|
||||
ready: false,
|
||||
created: false,
|
||||
reason: 'exception',
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
}
|
||||
}
|
||||
|
||||
if (!carrier.ready) {
|
||||
carrierFailed += 1
|
||||
if (item.fulfillment_status === 'assigned') {
|
||||
// 运营切换渠道失败时恢复原渠道,宁可保留旧状态,也不制造渠道与载体不一致。
|
||||
await query(
|
||||
`UPDATE order_items
|
||||
SET fulfillment_channel = $2,
|
||||
fulfillment_status = $3,
|
||||
fulfillment_source = $4,
|
||||
fulfillment_locked = $5,
|
||||
fulfillment_reason = $6,
|
||||
fulfillment_pending_reason = $7,
|
||||
fulfillment_pending_detail = $8::jsonb,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1 AND fulfillment_status <> 'archived'`,
|
||||
[
|
||||
item.id,
|
||||
item.fulfillment_channel,
|
||||
item.fulfillment_status,
|
||||
item.fulfillment_source,
|
||||
item.fulfillment_locked,
|
||||
item.fulfillment_reason,
|
||||
item.fulfillment_pending_reason,
|
||||
JSON.stringify(item.fulfillment_pending_detail || null),
|
||||
],
|
||||
)
|
||||
} else {
|
||||
await query(
|
||||
`UPDATE order_items
|
||||
SET fulfillment_channel = NULL,
|
||||
fulfillment_status = 'pending',
|
||||
fulfillment_source = '',
|
||||
fulfillment_locked = TRUE,
|
||||
fulfillment_pending_reason = 'no_carrier',
|
||||
fulfillment_pending_detail = $2::jsonb,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1 AND fulfillment_status <> 'archived'`,
|
||||
[
|
||||
item.id,
|
||||
JSON.stringify({
|
||||
channel: input.channel,
|
||||
reason: carrier.reason,
|
||||
message: carrier.message,
|
||||
}),
|
||||
],
|
||||
)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
const updated = await query(
|
||||
`UPDATE order_items
|
||||
SET fulfillment_channel = $2,
|
||||
fulfillment_status = 'assigned',
|
||||
fulfillment_source = $3,
|
||||
fulfillment_locked = $4,
|
||||
fulfillment_reason = COALESCE(NULLIF($5, ''), fulfillment_reason),
|
||||
fulfillment_pending_reason = NULL,
|
||||
fulfillment_pending_detail = NULL,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1 AND fulfillment_status <> 'archived'`,
|
||||
[item.id, input.channel, input.source, input.lock, String(input.note || '').slice(0, 200)],
|
||||
)
|
||||
if ((updated.rowCount || 0) > 0) assignedIds.push(Number(item.id))
|
||||
}
|
||||
|
||||
if (assignedIds.length > 0) {
|
||||
await normalizeProductsForItems(assignedIds).catch(() => undefined)
|
||||
const cost = await syncCostSnapshotsForItems(assignedIds).catch(() => null)
|
||||
const dates = [
|
||||
...new Set([...(await orderItemBasisDates(assignedIds)), ...(cost?.affectedDates || [])]),
|
||||
]
|
||||
await refreshFactsForDates(dates).catch(() => undefined)
|
||||
}
|
||||
const final = await query<{ count: number }>(
|
||||
`WITH updated AS (
|
||||
UPDATE order_items
|
||||
SET fulfillment_source = $3,
|
||||
fulfillment_locked = $4,
|
||||
fulfillment_pending_reason = NULL,
|
||||
fulfillment_pending_detail = NULL,
|
||||
updated_at = NOW()
|
||||
WHERE id = ANY($1::bigint[])
|
||||
AND fulfillment_status = 'assigned'
|
||||
AND fulfillment_channel = $2
|
||||
RETURNING id
|
||||
)
|
||||
SELECT count(*)::int AS count FROM updated`,
|
||||
[ids, input.channel, input.source, input.lock],
|
||||
)
|
||||
return { updated: Number(final.rows[0]?.count || assignedIds.length), carrierFailed }
|
||||
}
|
||||
|
||||
/** 运营指定渠道:先保证真实载体,成功后才写入并锁定。 */
|
||||
export async function assignChannelToOrderItems(input: {
|
||||
orderItemIds: number[]
|
||||
channel: string
|
||||
adminUserId: number | null
|
||||
note?: string
|
||||
}): Promise<{ updated: number }> {
|
||||
}): Promise<{ updated: number; carrierFailed: number }> {
|
||||
if (!isFulfillmentChannel(input.channel)) {
|
||||
throw createHttpError('渠道无效', { statusCode: 400, errorCode: 'invalid_channel' })
|
||||
}
|
||||
@@ -384,35 +594,20 @@ export async function assignChannelToOrderItems(input: {
|
||||
throw createHttpError('请选择订单项', { statusCode: 400, errorCode: 'order_item_required' })
|
||||
}
|
||||
|
||||
const result = await query(
|
||||
`
|
||||
UPDATE order_items
|
||||
SET
|
||||
fulfillment_channel = $2,
|
||||
fulfillment_status = 'assigned',
|
||||
fulfillment_source = 'operator_assigned',
|
||||
fulfillment_locked = TRUE,
|
||||
fulfillment_decided_by = $3,
|
||||
fulfillment_decided_at = NOW(),
|
||||
fulfillment_reason = COALESCE(NULLIF($4, ''), fulfillment_reason),
|
||||
updated_at = NOW()
|
||||
WHERE id = ANY($1::bigint[])
|
||||
AND fulfillment_status <> 'archived'
|
||||
`,
|
||||
[ids, input.channel, input.adminUserId, String(input.note || '').slice(0, 200)],
|
||||
const result = await assignOrderItemsAfterCarrierReady({
|
||||
orderItemIds: ids,
|
||||
channel: input.channel,
|
||||
source: 'operator_assigned',
|
||||
lock: true,
|
||||
note: input.note,
|
||||
})
|
||||
await query(
|
||||
`UPDATE order_items
|
||||
SET fulfillment_decided_by = $2, fulfillment_decided_at = NOW()
|
||||
WHERE id = ANY($1::bigint[])`,
|
||||
[ids, input.adminUserId],
|
||||
)
|
||||
|
||||
const updated = result.rowCount || 0
|
||||
if (updated > 0) {
|
||||
// 运营指定后先归一商品,再立即算成本并回填事实,避免旧单等冷通道。
|
||||
await normalizeProductsForItems(ids).catch(() => undefined)
|
||||
const cost = await syncCostSnapshotsForItems(ids).catch(() => null)
|
||||
const dates = [
|
||||
...new Set([...(await orderItemBasisDates(ids)), ...(cost?.affectedDates || [])]),
|
||||
]
|
||||
await refreshFactsForDates(dates).catch(() => undefined)
|
||||
}
|
||||
return { updated }
|
||||
return result
|
||||
}
|
||||
|
||||
/** 运营解锁:允许自动判定重新接管。 */
|
||||
@@ -507,7 +702,7 @@ export async function assignChannelByInternalSku(input: {
|
||||
adminUserId: number | null
|
||||
note?: string
|
||||
createRule?: boolean
|
||||
}): Promise<{ updated: number; ruleCreated: boolean }> {
|
||||
}): Promise<{ updated: number; ruleCreated: boolean; carrierFailed: number }> {
|
||||
if (!isFulfillmentChannel(input.channel)) {
|
||||
throw createHttpError('渠道无效', { statusCode: 400, errorCode: 'invalid_channel' })
|
||||
}
|
||||
@@ -521,26 +716,35 @@ export async function assignChannelByInternalSku(input: {
|
||||
|
||||
const idsResult = await query<{ id: number }>(
|
||||
`
|
||||
UPDATE order_items oi
|
||||
SET
|
||||
fulfillment_channel = $4,
|
||||
fulfillment_status = 'assigned',
|
||||
fulfillment_source = 'operator_assigned',
|
||||
fulfillment_locked = TRUE,
|
||||
fulfillment_decided_by = $5,
|
||||
fulfillment_decided_at = NOW(),
|
||||
updated_at = NOW()
|
||||
SELECT oi.id
|
||||
FROM orders o
|
||||
JOIN order_items oi ON oi.order_id = o.id
|
||||
WHERE o.id = oi.order_id
|
||||
AND o.provider = $1
|
||||
AND o.shop_id = $2
|
||||
AND ${INTERNAL_SKU_SQL} = $3
|
||||
AND oi.fulfillment_status = 'pending'
|
||||
RETURNING oi.id
|
||||
AND (
|
||||
oi.fulfillment_status = 'pending'
|
||||
OR (oi.fulfillment_status = 'assigned' AND oi.fulfillment_channel = $4)
|
||||
)
|
||||
`,
|
||||
[input.provider, input.shopId, internalSku, input.channel, input.adminUserId],
|
||||
[input.provider, input.shopId, internalSku, input.channel],
|
||||
)
|
||||
|
||||
const product = await query<{ id: number | null }>(
|
||||
`SELECT MIN(id) AS id
|
||||
FROM product_catalog
|
||||
WHERE status = 'active' AND btrim(canonical_name) = $1`,
|
||||
[internalSku],
|
||||
)
|
||||
await setInternalSkuPrimaryChannel({
|
||||
internalSku,
|
||||
channel: input.channel,
|
||||
canonicalProductId: product.rows[0]?.id == null ? null : Number(product.rows[0].id),
|
||||
source: 'operator',
|
||||
configJson: { note: String(input.note || '').slice(0, 200) },
|
||||
})
|
||||
|
||||
let ruleCreated = false
|
||||
if (input.createRule !== false) {
|
||||
const rule = await upsertChannelRule({
|
||||
@@ -559,16 +763,21 @@ export async function assignChannelByInternalSku(input: {
|
||||
}
|
||||
|
||||
const ids = idsResult.rows.map((row) => Number(row.id))
|
||||
if (ids.length > 0) {
|
||||
await normalizeProductsForItems(ids).catch(() => undefined)
|
||||
const cost = await syncCostSnapshotsForItems(ids).catch(() => null)
|
||||
const dates = [
|
||||
...new Set([...(await orderItemBasisDates(ids)), ...(cost?.affectedDates || [])]),
|
||||
]
|
||||
await refreshFactsForDates(dates).catch(() => undefined)
|
||||
}
|
||||
const applied = await assignOrderItemsAfterCarrierReady({
|
||||
orderItemIds: ids,
|
||||
channel: input.channel,
|
||||
source: 'operator_assigned',
|
||||
lock: true,
|
||||
note: input.note,
|
||||
})
|
||||
await query(
|
||||
`UPDATE order_items
|
||||
SET fulfillment_decided_by = $2, fulfillment_decided_at = NOW()
|
||||
WHERE id = ANY($1::bigint[])`,
|
||||
[ids, input.adminUserId],
|
||||
)
|
||||
|
||||
return { updated: ids.length, ruleCreated }
|
||||
return { ...applied, ruleCreated }
|
||||
}
|
||||
|
||||
/** 按 SKU 批量指定(待分类队列的主操作)。 */
|
||||
@@ -580,31 +789,39 @@ export async function assignChannelBySku(input: {
|
||||
adminUserId: number | null
|
||||
note?: string
|
||||
createRule?: boolean
|
||||
}): Promise<{ updated: number; ruleCreated: boolean }> {
|
||||
}): Promise<{ updated: number; ruleCreated: boolean; carrierFailed: number }> {
|
||||
if (!isFulfillmentChannel(input.channel)) {
|
||||
throw createHttpError('渠道无效', { statusCode: 400, errorCode: 'invalid_channel' })
|
||||
}
|
||||
const result = await query(
|
||||
const idsResult = await query<{ id: number; internal_sku: string }>(
|
||||
`
|
||||
UPDATE order_items oi
|
||||
SET
|
||||
fulfillment_channel = $4,
|
||||
fulfillment_status = 'assigned',
|
||||
fulfillment_source = 'operator_assigned',
|
||||
fulfillment_locked = TRUE,
|
||||
fulfillment_decided_by = $5,
|
||||
fulfillment_decided_at = NOW(),
|
||||
updated_at = NOW()
|
||||
SELECT oi.id, ${INTERNAL_SKU_SQL} AS internal_sku
|
||||
FROM orders o
|
||||
JOIN order_items oi ON oi.order_id = o.id
|
||||
WHERE o.id = oi.order_id
|
||||
AND o.provider = $1
|
||||
AND o.shop_id = $2
|
||||
AND oi.sku_code = $3
|
||||
AND oi.fulfillment_status = 'pending'
|
||||
AND (
|
||||
oi.fulfillment_status = 'pending'
|
||||
OR (oi.fulfillment_status = 'assigned' AND oi.fulfillment_channel = $4)
|
||||
)
|
||||
`,
|
||||
[input.provider, input.shopId, input.skuCode, input.channel, input.adminUserId],
|
||||
[input.provider, input.shopId, input.skuCode, input.channel],
|
||||
)
|
||||
|
||||
const internalSkus = [
|
||||
...new Set(idsResult.rows.map((row) => String(row.internal_sku || '').trim()).filter(Boolean)),
|
||||
]
|
||||
if (internalSkus.length === 1) {
|
||||
await setInternalSkuPrimaryChannel({
|
||||
internalSku: internalSkus[0]!,
|
||||
channel: input.channel,
|
||||
source: 'operator',
|
||||
configJson: { note: String(input.note || '').slice(0, 200) },
|
||||
})
|
||||
}
|
||||
|
||||
// 默认同时落一条渠道规则:否则同 SKU 的下一单还是会进待分类。
|
||||
let ruleCreated = false
|
||||
if (input.createRule !== false) {
|
||||
@@ -623,7 +840,21 @@ export async function assignChannelBySku(input: {
|
||||
ruleCreated = rule.id > 0
|
||||
}
|
||||
|
||||
return { updated: result.rowCount || 0, ruleCreated }
|
||||
const ids = idsResult.rows.map((row) => Number(row.id))
|
||||
const applied = await assignOrderItemsAfterCarrierReady({
|
||||
orderItemIds: ids,
|
||||
channel: input.channel,
|
||||
source: 'operator_assigned',
|
||||
lock: true,
|
||||
note: input.note,
|
||||
})
|
||||
await query(
|
||||
`UPDATE order_items
|
||||
SET fulfillment_decided_by = $2, fulfillment_decided_at = NOW()
|
||||
WHERE id = ANY($1::bigint[])`,
|
||||
[ids, input.adminUserId],
|
||||
)
|
||||
return { ...applied, ruleCreated }
|
||||
}
|
||||
|
||||
export async function listChannelRules(
|
||||
@@ -712,6 +943,18 @@ export async function upsertChannelRule(input: {
|
||||
],
|
||||
)
|
||||
|
||||
if (input.matchKeyType === 'internal_sku') {
|
||||
await upsertInternalSkuChannel({
|
||||
internalSku: matchKey,
|
||||
channel: input.channel,
|
||||
priority: Math.trunc(Number(input.priority) || 100),
|
||||
isFallback: Math.trunc(Number(input.priority) || 100) >= 90,
|
||||
enabled: input.enabled !== false,
|
||||
source: source === 'operator' ? 'operator' : `rule:${source}`,
|
||||
replacePriority: true,
|
||||
})
|
||||
}
|
||||
|
||||
return { id: result.rows[0]!.id }
|
||||
}
|
||||
|
||||
@@ -720,8 +963,25 @@ export async function deleteChannelRule(ruleId: number): Promise<{ deleted: bool
|
||||
if (id <= 0) {
|
||||
throw createHttpError('规则 id 无效', { statusCode: 400, errorCode: 'invalid_rule_id' })
|
||||
}
|
||||
const result = await query(`DELETE FROM sku_channel_rules WHERE id = $1 RETURNING id`, [id])
|
||||
return { deleted: (result.rowCount || 0) > 0 }
|
||||
const result = await query<{
|
||||
id: number
|
||||
match_key_type: string
|
||||
match_key: string
|
||||
channel: string
|
||||
}>(
|
||||
`DELETE FROM sku_channel_rules
|
||||
WHERE id = $1
|
||||
RETURNING id, match_key_type, match_key, channel`,
|
||||
[id],
|
||||
)
|
||||
const deleted = result.rows[0]
|
||||
if (deleted?.match_key_type === 'internal_sku' && isFulfillmentChannel(deleted.channel)) {
|
||||
await disableInternalSkuChannel({
|
||||
internalSku: deleted.match_key,
|
||||
channel: deleted.channel,
|
||||
})
|
||||
}
|
||||
return { deleted: Boolean(deleted) }
|
||||
}
|
||||
|
||||
async function loadEnabledRules(): Promise<ChannelRule[]> {
|
||||
@@ -735,6 +995,32 @@ async function loadEnabledRules(): Promise<ChannelRule[]> {
|
||||
return rows.rows
|
||||
}
|
||||
|
||||
async function loadInternalSkuChannelsForKeys(
|
||||
keys: string[],
|
||||
): Promise<Map<string, InternalSkuChannelRow[]>> {
|
||||
const normalized = [...new Set(keys.map(normalizeKey).filter(Boolean))]
|
||||
const result = new Map<string, InternalSkuChannelRow[]>()
|
||||
if (normalized.length === 0) return result
|
||||
|
||||
const rows = await query<InternalSkuChannelRow>(
|
||||
`
|
||||
SELECT internal_sku, channel, priority, is_fallback, enabled,
|
||||
canonical_product_id, config_json, source
|
||||
FROM internal_sku_channels
|
||||
WHERE enabled = TRUE AND btrim(internal_sku) = ANY($1::text[])
|
||||
ORDER BY internal_sku, priority, channel
|
||||
`,
|
||||
[normalized],
|
||||
)
|
||||
for (const row of rows.rows) {
|
||||
const key = normalizeKey(row.internal_sku)
|
||||
const list = result.get(key) || []
|
||||
list.push(row)
|
||||
result.set(key, list)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
export const CHANNEL_RULE_KEY_TYPES = MATCH_KEY_TYPES
|
||||
export const CHANNEL_RULE_SOURCES = RULE_SOURCES
|
||||
export const CHANNEL_VALUES = FULFILLMENT_CHANNELS
|
||||
|
||||
Reference in New Issue
Block a user