feat(fulfillment): 统一中文内部 SKU 履约路由
This commit is contained in:
@@ -14,13 +14,11 @@ import { orderItemBasisDates, refreshFactsForDates } from '../finance/refresh-fa
|
||||
import {
|
||||
FULFILLMENT_CHANNELS,
|
||||
INACTIVE_CARRIER_TASK_STATUSES,
|
||||
MATCH_KEY_TYPES,
|
||||
RULE_SOURCES,
|
||||
isFulfillmentChannel,
|
||||
isRuleSource,
|
||||
type FulfillmentChannel,
|
||||
type FulfillmentSource,
|
||||
type MatchKeyType,
|
||||
type RuleSource,
|
||||
} from './channel-types.js'
|
||||
import {
|
||||
@@ -33,6 +31,7 @@ import {
|
||||
} from './internal-sku-channel-service.js'
|
||||
import { ensureCarrierForOrderItem } from './carrier-creation-service.js'
|
||||
import { TASK_STATUS } from '../../domain/task-status.js'
|
||||
import { canonicalizeInternalSku, containsCjk } from './internal-sku-resolver.js'
|
||||
|
||||
/**
|
||||
* 管道 A:渠道判定。
|
||||
@@ -44,8 +43,7 @@ import { TASK_STATUS } from '../../domain/task-status.js'
|
||||
* 1. 运营锁定 → 跳过
|
||||
* 2. 已有且唯一的真实载体 → 直接按载体落渠道;多载体 → 冲突
|
||||
* 3. internal_sku_channels:一个主渠道 + 显式兜底;多主渠道 → 冲突
|
||||
* 4. 旧 sku_channel_rules 仅作兼容回退,且自动发货/接单仍必须有真实载体
|
||||
* 5. 都不满足 → 保留 pending 并写明确原因
|
||||
* 4. 没有统一配置或载体不满足 → 保留 pending 并写明确原因
|
||||
*/
|
||||
|
||||
/** 数据库函数 `resolve_internal_sku` 是订单项内部 SKU 的唯一 SQL 口径。 */
|
||||
@@ -54,13 +52,15 @@ const ACTIVE_CARRIER_TASK_SQL = `task.task_status NOT IN (${INACTIVE_CARRIER_TAS
|
||||
|
||||
export type ChannelRule = {
|
||||
id: number
|
||||
provider: string
|
||||
shop_id: string
|
||||
match_key_type: MatchKeyType
|
||||
match_key_type: 'internal_sku'
|
||||
match_key: string
|
||||
channel: FulfillmentChannel
|
||||
priority: number
|
||||
enabled: boolean
|
||||
is_fallback: boolean
|
||||
source: string
|
||||
config_json: Record<string, unknown>
|
||||
note: string
|
||||
}
|
||||
|
||||
export type ChannelRulePage = {
|
||||
@@ -96,22 +96,6 @@ export type ChannelDecision = {
|
||||
pendingReason: 'no_internal_sku' | 'no_channel_capability' | 'no_carrier' | ''
|
||||
}
|
||||
|
||||
function normalizeKey(value: unknown): string {
|
||||
return String(value ?? '').trim()
|
||||
}
|
||||
|
||||
function matchesScope(rule: ChannelRule, item: ChannelCandidateItem): boolean {
|
||||
if (rule.provider && rule.provider !== item.provider) return false
|
||||
if (rule.shop_id && rule.shop_id !== item.shop_id) return false
|
||||
return true
|
||||
}
|
||||
|
||||
function itemKey(item: ChannelCandidateItem, keyType: MatchKeyType): string {
|
||||
if (keyType === 'sku_code') return normalizeKey(item.sku_code)
|
||||
if (keyType === 'internal_sku') return normalizeKey(item.internal_sku || item.manual_sku_key)
|
||||
return normalizeKey(item.normalized_sku_name) || normalizeKey(item.sku_name).toLowerCase()
|
||||
}
|
||||
|
||||
function resolvePendingReason(item: ChannelCandidateItem): {
|
||||
reason: string
|
||||
detail: Record<string, unknown>
|
||||
@@ -155,10 +139,7 @@ function emptyDecision(pendingReason: ChannelDecision['pendingReason'] = '') {
|
||||
}
|
||||
|
||||
/** 纯函数:给定规则与订单项,得出渠道决策(便于单测与文档对照)。 */
|
||||
export function resolveChannelDecision(
|
||||
item: ChannelCandidateItem,
|
||||
rules: ChannelRule[],
|
||||
): ChannelDecision {
|
||||
export function resolveChannelDecision(item: ChannelCandidateItem): ChannelDecision {
|
||||
const carrierChannels: FulfillmentChannel[] = [
|
||||
...(item.has_work_order ? ['work_order' as const] : []),
|
||||
...(item.has_affiliate_task ? ['affiliate_dash' as const] : []),
|
||||
@@ -204,7 +185,21 @@ export function resolveChannelDecision(
|
||||
}
|
||||
|
||||
if (plan.primary) {
|
||||
if (plan.primary.channel === 'manual' || plan.primary.channel === 'third_party_voucher') {
|
||||
if (plan.primary.channel === 'manual') {
|
||||
if (!Number(plan.primary.config_json.manualConfigId || 0)) {
|
||||
return emptyDecision('no_carrier')
|
||||
}
|
||||
return {
|
||||
channel: plan.primary.channel,
|
||||
source: 'auto_mapping',
|
||||
conflict: false,
|
||||
conflictChannels: [],
|
||||
matchedRuleIds: [],
|
||||
pendingChannel: plan.primary.channel,
|
||||
pendingReason: '',
|
||||
}
|
||||
}
|
||||
if (plan.primary.channel === 'third_party_voucher') {
|
||||
return {
|
||||
channel: plan.primary.channel,
|
||||
source: 'auto_mapping',
|
||||
@@ -217,44 +212,6 @@ export function resolveChannelDecision(
|
||||
}
|
||||
return emptyDecision('no_carrier')
|
||||
}
|
||||
|
||||
const hits = rules.filter(
|
||||
(rule) =>
|
||||
rule.enabled &&
|
||||
matchesScope(rule, item) &&
|
||||
itemKey(item, rule.match_key_type) === normalizeKey(rule.match_key),
|
||||
)
|
||||
|
||||
if (hits.length > 0) {
|
||||
const minPriority = Math.min(...hits.map((rule) => rule.priority))
|
||||
const best = hits.filter((rule) => rule.priority === minPriority)
|
||||
const channels = [...new Set(best.map((rule) => rule.channel))]
|
||||
|
||||
if (channels.length > 1) {
|
||||
return {
|
||||
channel: null,
|
||||
source: '',
|
||||
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,
|
||||
source: 'auto_rule',
|
||||
conflict: false,
|
||||
conflictChannels: [],
|
||||
matchedRuleIds: best.map((rule) => rule.id),
|
||||
pendingChannel: channel,
|
||||
pendingReason: '',
|
||||
}
|
||||
}
|
||||
return emptyDecision('no_channel_capability')
|
||||
}
|
||||
|
||||
@@ -287,7 +244,6 @@ export async function assignPendingOrderItemChannels(
|
||||
: await readWatermarkItemId('channel_assign')
|
||||
let reachedEnd = false
|
||||
|
||||
const rules = await loadEnabledRules()
|
||||
const result: AssignChannelsResult = {
|
||||
scanned: 0,
|
||||
assigned: 0,
|
||||
@@ -362,9 +318,9 @@ export async function assignPendingOrderItemChannels(
|
||||
for (const row of rows.rows) {
|
||||
const item: ChannelCandidateItem = {
|
||||
...row,
|
||||
channels: channelsByInternalSku.get(normalizeKey(row.internal_sku)) || [],
|
||||
channels: channelsByInternalSku.get(canonicalizeInternalSku(row.internal_sku)) || [],
|
||||
}
|
||||
const decision = resolveChannelDecision(item, rules)
|
||||
const decision = resolveChannelDecision(item)
|
||||
if (decision.channel) affectedDates.add(item.basis_date)
|
||||
if (decision.conflict) {
|
||||
result.conflicted += 1
|
||||
@@ -384,7 +340,7 @@ export async function assignPendingOrderItemChannels(
|
||||
)
|
||||
await upsertAggregatedException({
|
||||
reason: 'routing_conflict',
|
||||
scopeKey: `routing_conflict|${item.provider}|${item.shop_id}|${item.sku_code}|-`,
|
||||
scopeKey: `routing_conflict|-|-|${item.internal_sku}|-`,
|
||||
orderItemId: item.id,
|
||||
detail: { channels: decision.conflictChannels, ruleIds: decision.matchedRuleIds },
|
||||
})
|
||||
@@ -630,6 +586,23 @@ export async function switchChannelForOrderItems(input: {
|
||||
throw createHttpError('请选择订单项', { statusCode: 400, errorCode: 'order_item_required' })
|
||||
}
|
||||
|
||||
const skuRows = await query<{ internal_sku: string }>(
|
||||
`SELECT DISTINCT resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code) AS internal_sku
|
||||
FROM order_items oi
|
||||
WHERE oi.id = ANY($1::bigint[])`,
|
||||
[ids],
|
||||
)
|
||||
const switchInternalSkus = skuRows.rows
|
||||
.map((row) => canonicalizeInternalSku(row.internal_sku))
|
||||
.filter(Boolean)
|
||||
if (switchInternalSkus.length !== 1) {
|
||||
throw createHttpError('切换渠道必须基于同一个中文内部 SKU', {
|
||||
statusCode: 400,
|
||||
errorCode:
|
||||
switchInternalSkus.length === 0 ? 'internal_sku_required' : 'multiple_internal_skus',
|
||||
})
|
||||
}
|
||||
|
||||
const items = (
|
||||
await query<OrderItemRow>(`SELECT * FROM order_items WHERE id = ANY($1::bigint[])`, [ids])
|
||||
).rows
|
||||
@@ -784,6 +757,19 @@ export async function switchChannelForOrderItems(input: {
|
||||
WHERE id = ANY($1::bigint[])`,
|
||||
[readyIds, input.adminUserId],
|
||||
)
|
||||
if (assigned.updated > 0) {
|
||||
const internalSku = switchInternalSkus[0]!
|
||||
const carrier = await resolveInternalSkuCarrierConfig(internalSku, input.channel)
|
||||
await setInternalSkuPrimaryChannel({
|
||||
internalSku,
|
||||
channel: input.channel,
|
||||
canonicalProductId: carrier.canonicalProductId,
|
||||
configJson: carrier.configJson,
|
||||
source: 'operator',
|
||||
note: input.note,
|
||||
adminUserId: input.adminUserId,
|
||||
})
|
||||
}
|
||||
return {
|
||||
switched: assigned.updated,
|
||||
failed: errors.length + assigned.carrierFailed,
|
||||
@@ -807,21 +793,34 @@ export async function assignChannelToOrderItems(input: {
|
||||
if (ids.length === 0) {
|
||||
throw createHttpError('请选择订单项', { statusCode: 400, errorCode: 'order_item_required' })
|
||||
}
|
||||
|
||||
const result = await assignOrderItemsAfterCarrierReady({
|
||||
orderItemIds: ids,
|
||||
const rows = await query<{ internal_sku: string }>(
|
||||
`SELECT resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code) AS internal_sku
|
||||
FROM order_items oi
|
||||
WHERE oi.id = ANY($1::bigint[])`,
|
||||
[ids],
|
||||
)
|
||||
const internalSkus = [
|
||||
...new Set(rows.rows.map((row) => canonicalizeInternalSku(row.internal_sku)).filter(Boolean)),
|
||||
]
|
||||
if (internalSkus.length === 0) {
|
||||
throw createHttpError('所选订单项没有中文内部 SKU', {
|
||||
statusCode: 400,
|
||||
errorCode: 'internal_sku_required',
|
||||
})
|
||||
}
|
||||
if (internalSkus.length > 1) {
|
||||
throw createHttpError('所选订单项包含多个内部 SKU,请按内部 SKU 指定渠道', {
|
||||
statusCode: 400,
|
||||
errorCode: 'multiple_internal_skus',
|
||||
})
|
||||
}
|
||||
const result = await assignChannelByInternalSku({
|
||||
internalSku: internalSkus[0]!,
|
||||
channel: input.channel,
|
||||
source: 'operator_assigned',
|
||||
lock: true,
|
||||
adminUserId: input.adminUserId,
|
||||
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 result
|
||||
return { updated: result.updated, carrierFailed: result.carrierFailed }
|
||||
}
|
||||
|
||||
/** 运营解锁:允许自动判定重新接管。 */
|
||||
@@ -836,10 +835,10 @@ export async function unlockChannel(orderItemIds: number[]): Promise<{ updated:
|
||||
}
|
||||
|
||||
export type PendingGroupRow = {
|
||||
provider: string
|
||||
shop_id: string
|
||||
internal_sku: string
|
||||
sku_name: string
|
||||
providers: string[]
|
||||
shop_ids: string[]
|
||||
sku_codes: string[]
|
||||
pending_reasons: string[]
|
||||
item_count: number
|
||||
@@ -848,7 +847,7 @@ export type PendingGroupRow = {
|
||||
last_seen_at: string
|
||||
}
|
||||
|
||||
/** 待分类队列:按内部 SKU 聚合(同一中文 SKU 的不同平台码合并为一行)。 */
|
||||
/** 待分类队列:按全局内部 SKU 聚合(跨平台、跨店铺合并为一行)。 */
|
||||
export async function listPendingChannelGroups(input: {
|
||||
page?: number
|
||||
pageSize?: number
|
||||
@@ -862,7 +861,7 @@ export async function listPendingChannelGroups(input: {
|
||||
if (keyword) {
|
||||
params.push(`%${keyword}%`)
|
||||
clauses.push(
|
||||
`(oi.sku_code ILIKE $${params.length} OR oi.sku_name ILIKE $${params.length} OR oi.manual_sku_key ILIKE $${params.length})`,
|
||||
`(${INTERNAL_SKU_SQL} ILIKE $${params.length} OR oi.sku_code ILIKE $${params.length} OR oi.sku_name ILIKE $${params.length} OR oi.manual_sku_key ILIKE $${params.length})`,
|
||||
)
|
||||
}
|
||||
const where = clauses.join(' AND ')
|
||||
@@ -874,7 +873,7 @@ export async function listPendingChannelGroups(input: {
|
||||
FROM order_items oi
|
||||
JOIN orders o ON o.id = oi.order_id
|
||||
WHERE ${where}
|
||||
GROUP BY o.provider, o.shop_id, ${INTERNAL_SKU_SQL}
|
||||
GROUP BY ${INTERNAL_SKU_SQL}
|
||||
) grouped
|
||||
`,
|
||||
params,
|
||||
@@ -884,10 +883,10 @@ export async function listPendingChannelGroups(input: {
|
||||
const rows = await query<PendingGroupRow>(
|
||||
`
|
||||
SELECT
|
||||
o.provider,
|
||||
o.shop_id,
|
||||
${INTERNAL_SKU_SQL} AS internal_sku,
|
||||
MIN(oi.sku_name) AS sku_name,
|
||||
array_agg(DISTINCT o.provider) AS providers,
|
||||
array_agg(DISTINCT o.shop_id) AS shop_ids,
|
||||
array_agg(DISTINCT oi.sku_code) AS sku_codes,
|
||||
array_remove(array_agg(DISTINCT oi.fulfillment_pending_reason), NULL) AS pending_reasons,
|
||||
COUNT(*)::int AS item_count,
|
||||
@@ -897,7 +896,7 @@ export async function listPendingChannelGroups(input: {
|
||||
FROM order_items oi
|
||||
JOIN orders o ON o.id = oi.order_id
|
||||
WHERE ${where}
|
||||
GROUP BY o.provider, o.shop_id, ${INTERNAL_SKU_SQL}
|
||||
GROUP BY ${INTERNAL_SKU_SQL}
|
||||
ORDER BY item_count DESC, internal_sku
|
||||
LIMIT $${params.length - 1} OFFSET $${params.length}
|
||||
`,
|
||||
@@ -909,8 +908,6 @@ export async function listPendingChannelGroups(input: {
|
||||
|
||||
/** 按内部 SKU 批量指定(同一中文 SKU 跨平台码一起分流)。 */
|
||||
export async function assignChannelByInternalSku(input: {
|
||||
provider: string
|
||||
shopId: string
|
||||
internalSku: string
|
||||
channel: string
|
||||
adminUserId: number | null
|
||||
@@ -920,9 +917,9 @@ export async function assignChannelByInternalSku(input: {
|
||||
if (!isFulfillmentChannel(input.channel)) {
|
||||
throw createHttpError('渠道无效', { statusCode: 400, errorCode: 'invalid_channel' })
|
||||
}
|
||||
const internalSku = String(input.internalSku || '').trim()
|
||||
if (!internalSku) {
|
||||
throw createHttpError('内部 SKU 不能为空', {
|
||||
const internalSku = canonicalizeInternalSku(input.internalSku)
|
||||
if (!internalSku || !containsCjk(internalSku)) {
|
||||
throw createHttpError('必须使用包含中文的内部 SKU', {
|
||||
statusCode: 400,
|
||||
errorCode: 'internal_sku_required',
|
||||
})
|
||||
@@ -940,29 +937,25 @@ export async function assignChannelByInternalSku(input: {
|
||||
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 ${INTERNAL_SKU_SQL} = $1
|
||||
AND (
|
||||
oi.fulfillment_status = 'pending'
|
||||
OR (oi.fulfillment_status = 'assigned' AND oi.fulfillment_channel = $4)
|
||||
OR (oi.fulfillment_status = 'assigned' AND oi.fulfillment_channel = $2)
|
||||
)
|
||||
`,
|
||||
[input.provider, input.shopId, internalSku, input.channel],
|
||||
[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],
|
||||
)
|
||||
const carrier = await resolveInternalSkuCarrierConfig(internalSku, input.channel)
|
||||
await setInternalSkuPrimaryChannel({
|
||||
internalSku,
|
||||
channel: input.channel,
|
||||
canonicalProductId: product.rows[0]?.id == null ? null : Number(product.rows[0].id),
|
||||
canonicalProductId: carrier.canonicalProductId,
|
||||
source: 'operator',
|
||||
configJson: { note: String(input.note || '').slice(0, 200) },
|
||||
configJson: {
|
||||
...carrier.configJson,
|
||||
note: String(input.note || '').slice(0, 200),
|
||||
},
|
||||
note: input.note,
|
||||
adminUserId: input.adminUserId,
|
||||
})
|
||||
@@ -987,7 +980,7 @@ export async function assignChannelByInternalSku(input: {
|
||||
return { ...applied, ruleCreated }
|
||||
}
|
||||
|
||||
/** 按 SKU 批量指定(待分类队列的主操作)。 */
|
||||
/** 按平台 SKU 定位内部 SKU 后全局指定渠道。 */
|
||||
export async function assignChannelBySku(input: {
|
||||
provider: string
|
||||
shopId: string
|
||||
@@ -1018,7 +1011,9 @@ export async function assignChannelBySku(input: {
|
||||
)
|
||||
|
||||
const internalSkus = [
|
||||
...new Set(idsResult.rows.map((row) => String(row.internal_sku || '').trim()).filter(Boolean)),
|
||||
...new Set(
|
||||
idsResult.rows.map((row) => canonicalizeInternalSku(row.internal_sku)).filter(Boolean),
|
||||
),
|
||||
]
|
||||
if (internalSkus.length === 0) {
|
||||
return { updated: 0, ruleCreated: false, carrierFailed: 0 }
|
||||
@@ -1030,8 +1025,6 @@ export async function assignChannelBySku(input: {
|
||||
})
|
||||
}
|
||||
return assignChannelByInternalSku({
|
||||
provider: input.provider,
|
||||
shopId: input.shopId,
|
||||
internalSku: internalSkus[0]!,
|
||||
channel: input.channel,
|
||||
adminUserId: input.adminUserId,
|
||||
@@ -1062,9 +1055,10 @@ function buildChannelRuleFilter(input: ChannelRuleFilterInput) {
|
||||
|
||||
const CHANNEL_RULE_FROM_SQL = `
|
||||
FROM (
|
||||
SELECT id, ''::text AS provider, ''::text AS shop_id,
|
||||
'internal_sku'::text AS match_key_type, internal_sku AS match_key,
|
||||
channel, priority, enabled
|
||||
SELECT id,
|
||||
'internal_sku'::text AS match_key_type,
|
||||
canonicalize_internal_sku(internal_sku) AS match_key,
|
||||
channel, priority, enabled, is_fallback, source, config_json, note
|
||||
FROM internal_sku_channels
|
||||
) internal_rules
|
||||
`
|
||||
@@ -1081,7 +1075,8 @@ export async function listChannelRules(input: ChannelRuleFilterInput = {}): Prom
|
||||
const { where, params } = buildChannelRuleFilter(input)
|
||||
const rows = await query<ChannelRule>(
|
||||
`
|
||||
SELECT id, provider, shop_id, match_key_type, match_key, channel, priority, enabled
|
||||
SELECT id, match_key_type, match_key, channel, priority, enabled,
|
||||
is_fallback, source, config_json, note
|
||||
${CHANNEL_RULE_FROM_SQL}
|
||||
${where}
|
||||
ORDER BY priority, channel, match_key, id
|
||||
@@ -1106,7 +1101,8 @@ export async function listChannelRulesPage(
|
||||
),
|
||||
query<ChannelRule>(
|
||||
`
|
||||
SELECT id, provider, shop_id, match_key_type, match_key, channel, priority, enabled
|
||||
SELECT id, match_key_type, match_key, channel, priority, enabled,
|
||||
is_fallback, source, config_json, note
|
||||
${CHANNEL_RULE_FROM_SQL}
|
||||
${where}
|
||||
ORDER BY priority, channel, match_key, id
|
||||
@@ -1123,6 +1119,56 @@ export async function listChannelRulesPage(
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveInternalSkuCarrierConfig(
|
||||
internalSku: string,
|
||||
channel: string,
|
||||
): Promise<{ canonicalProductId: number | null; configJson: Record<string, unknown> }> {
|
||||
const key = canonicalizeInternalSku(internalSku)
|
||||
if (!key) return { canonicalProductId: null, configJson: {} }
|
||||
|
||||
if (channel === 'manual') {
|
||||
const manual = await query<{ id: number; canonical_product_id: number | null }>(
|
||||
`SELECT id, canonical_product_id
|
||||
FROM manual_fulfillment_configs
|
||||
WHERE canonicalize_internal_sku(sku_key) = $1 AND enabled = TRUE
|
||||
ORDER BY id
|
||||
LIMIT 1`,
|
||||
[key],
|
||||
)
|
||||
return {
|
||||
canonicalProductId: Number(manual.rows[0]?.canonical_product_id || 0) || null,
|
||||
configJson: manual.rows[0] ? { manualConfigId: Number(manual.rows[0].id) } : {},
|
||||
}
|
||||
}
|
||||
|
||||
const prefixes =
|
||||
channel === 'affiliate_dash' ? ['aff:'] : channel === 'work_order' ? ['tpl:', 'wo:'] : ['tpv:']
|
||||
const product = await query<{ id: number; canonical_sku: string }>(
|
||||
`SELECT id, canonical_sku
|
||||
FROM product_catalog
|
||||
WHERE status = 'active'
|
||||
AND (canonical_sku LIKE $2 OR canonical_sku LIKE $3)
|
||||
AND canonicalize_internal_sku(canonical_name) = $1
|
||||
ORDER BY id
|
||||
LIMIT 1`,
|
||||
[key, `${prefixes[0]}%`, `${prefixes[1] || prefixes[0]}%`],
|
||||
)
|
||||
const row = product.rows[0]
|
||||
if (!row) return { canonicalProductId: null, configJson: {} }
|
||||
const rawSku = String(row.canonical_sku)
|
||||
const matchedPrefix = prefixes.find((prefix) => rawSku.startsWith(prefix)) || prefixes[0]!
|
||||
const carrierKey = rawSku.slice(matchedPrefix.length)
|
||||
return {
|
||||
canonicalProductId: Number(row.id),
|
||||
configJson:
|
||||
channel === 'affiliate_dash'
|
||||
? { affiliateSku: carrierKey }
|
||||
: channel === 'work_order'
|
||||
? { workRuleKey: carrierKey }
|
||||
: { voucherSku: carrierKey },
|
||||
}
|
||||
}
|
||||
|
||||
export async function upsertChannelRule(input: {
|
||||
id?: number
|
||||
matchKeyType: string
|
||||
@@ -1144,12 +1190,16 @@ export async function upsertChannelRule(input: {
|
||||
throw createHttpError('渠道无效', { statusCode: 400, errorCode: 'invalid_channel' })
|
||||
}
|
||||
const source: RuleSource = isRuleSource(input.source) ? input.source : 'operator'
|
||||
const matchKey = String(input.matchKey || '').trim()
|
||||
if (!matchKey) {
|
||||
throw createHttpError('匹配键不能为空', { statusCode: 400, errorCode: 'match_key_required' })
|
||||
const matchKey = canonicalizeInternalSku(input.matchKey)
|
||||
if (!matchKey || !containsCjk(matchKey)) {
|
||||
throw createHttpError('匹配键必须是包含中文的内部 SKU', {
|
||||
statusCode: 400,
|
||||
errorCode: 'internal_sku_required',
|
||||
})
|
||||
}
|
||||
|
||||
const priority = Math.trunc(Number(input.priority) || 100)
|
||||
const carrier = await resolveInternalSkuCarrierConfig(matchKey, input.channel)
|
||||
const id = await upsertInternalSkuChannel({
|
||||
internalSku: matchKey,
|
||||
channel: input.channel,
|
||||
@@ -1160,6 +1210,8 @@ export async function upsertChannelRule(input: {
|
||||
note: String(input.note || '').slice(0, 300),
|
||||
adminUserId: input.adminUserId,
|
||||
replacePriority: true,
|
||||
canonicalProductId: carrier.canonicalProductId,
|
||||
configJson: carrier.configJson,
|
||||
})
|
||||
return { id }
|
||||
}
|
||||
@@ -1169,6 +1221,7 @@ export async function deleteChannelRule(ruleId: number): Promise<{ deleted: bool
|
||||
if (id <= 0) {
|
||||
throw createHttpError('规则 id 无效', { statusCode: 400, errorCode: 'invalid_rule_id' })
|
||||
}
|
||||
await assertRulesDeletable([id])
|
||||
return { deleted: await deleteInternalSkuChannelById(id) }
|
||||
}
|
||||
|
||||
@@ -1183,29 +1236,34 @@ export async function deleteChannelRules(idsInput: number[]): Promise<{
|
||||
errorCode: 'channel_rule_ids_required',
|
||||
})
|
||||
}
|
||||
await assertRulesDeletable(idsInput)
|
||||
const result = await deleteInternalSkuChannelsByIds(idsInput)
|
||||
return { deletedCount: result.deletedIds.length, ...result }
|
||||
}
|
||||
|
||||
async function loadEnabledRules(): Promise<ChannelRule[]> {
|
||||
const rows = await query<ChannelRule>(
|
||||
`
|
||||
SELECT id, provider, shop_id, match_key_type, match_key, channel, priority, enabled
|
||||
FROM sku_channel_rules
|
||||
WHERE enabled = TRUE
|
||||
`,
|
||||
async function assertRulesDeletable(idsInput: number[]): Promise<void> {
|
||||
const ids = [...new Set(idsInput.map(Number).filter((id) => Number.isInteger(id) && id > 0))]
|
||||
if (ids.length === 0) return
|
||||
const rows = await query<{ id: number; source: string; match_key: string; channel: string }>(
|
||||
`SELECT id, source, canonicalize_internal_sku(internal_sku) AS match_key, channel
|
||||
FROM internal_sku_channels WHERE id = ANY($1::bigint[])`,
|
||||
[ids],
|
||||
)
|
||||
return rows.rows.map((row) => ({
|
||||
...row,
|
||||
id: Number(row.id),
|
||||
priority: Number(row.priority),
|
||||
}))
|
||||
const protectedRow = rows.rows.find(
|
||||
(row) => row.source !== 'operator' && !row.source.startsWith('rule:'),
|
||||
)
|
||||
if (protectedRow) {
|
||||
throw createHttpError(
|
||||
`「${protectedRow.match_key}」的 ${protectedRow.channel} 配置由 ${protectedRow.source} 生成,请到对应配置页停用,不能在渠道页直接删除`,
|
||||
{ statusCode: 409, errorCode: 'system_channel_rule_protected' },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
async function loadInternalSkuChannelsForKeys(
|
||||
keys: string[],
|
||||
): Promise<Map<string, InternalSkuChannelRow[]>> {
|
||||
const normalized = [...new Set(keys.map(normalizeKey).filter(Boolean))]
|
||||
const normalized = [...new Set(keys.map(canonicalizeInternalSku).filter(Boolean))]
|
||||
const result = new Map<string, InternalSkuChannelRow[]>()
|
||||
if (normalized.length === 0) return result
|
||||
|
||||
@@ -1214,13 +1272,13 @@ async function loadInternalSkuChannelsForKeys(
|
||||
SELECT id, internal_sku, channel, priority, is_fallback, enabled,
|
||||
canonical_product_id, config_json, source, note, created_by_admin_user_id
|
||||
FROM internal_sku_channels
|
||||
WHERE enabled = TRUE AND btrim(internal_sku) = ANY($1::text[])
|
||||
ORDER BY internal_sku, priority, channel
|
||||
WHERE enabled = TRUE AND canonicalize_internal_sku(internal_sku) = ANY($1::text[])
|
||||
ORDER BY canonicalize_internal_sku(internal_sku), priority, channel, id
|
||||
`,
|
||||
[normalized],
|
||||
)
|
||||
for (const row of rows.rows) {
|
||||
const key = normalizeKey(row.internal_sku)
|
||||
const key = canonicalizeInternalSku(row.internal_sku)
|
||||
const list = result.get(key) || []
|
||||
list.push(row)
|
||||
result.set(key, list)
|
||||
@@ -1228,13 +1286,13 @@ async function loadInternalSkuChannelsForKeys(
|
||||
return result
|
||||
}
|
||||
|
||||
export const CHANNEL_RULE_KEY_TYPES = MATCH_KEY_TYPES
|
||||
export const CHANNEL_RULE_KEY_TYPES = ['internal_sku'] as const
|
||||
export const CHANNEL_RULE_SOURCES = RULE_SOURCES
|
||||
export const CHANNEL_VALUES = FULFILLMENT_CHANNELS
|
||||
|
||||
/** 为单个卡券 SKU 建规则(商品创建时调用,幂等)。 */
|
||||
export async function ensureVoucherRuleForSku(skuCode: string): Promise<boolean> {
|
||||
const key = String(skuCode || '').trim()
|
||||
const key = canonicalizeInternalSku(skuCode)
|
||||
if (!key) return false
|
||||
const product = await query<{ id: number }>(
|
||||
`SELECT id FROM product_catalog
|
||||
@@ -1273,7 +1331,7 @@ export async function ensureVoucherChannelRules(): Promise<{
|
||||
FROM product_catalog product
|
||||
WHERE product.status = 'active'
|
||||
AND product.canonical_sku LIKE 'tpv:%'
|
||||
AND BTRIM(channel.internal_sku) = BTRIM(product.canonical_name)
|
||||
AND canonicalize_internal_sku(channel.internal_sku) = canonicalize_internal_sku(product.canonical_name)
|
||||
AND channel.channel <> 'third_party_voucher'
|
||||
AND channel.enabled = TRUE
|
||||
AND channel.is_fallback = FALSE`,
|
||||
@@ -1285,7 +1343,7 @@ export async function ensureVoucherChannelRules(): Promise<{
|
||||
canonical_product_id, config_json, source, created_at, updated_at
|
||||
)
|
||||
SELECT
|
||||
BTRIM(p.canonical_name), 'third_party_voucher', 10, FALSE, TRUE,
|
||||
canonicalize_internal_sku(p.canonical_name), 'third_party_voucher', 10, FALSE, TRUE,
|
||||
p.id, jsonb_build_object('voucherSku', substring(p.canonical_sku from 5)),
|
||||
'voucher', NOW(), NOW()
|
||||
FROM product_catalog p
|
||||
|
||||
Reference in New Issue
Block a user