feat(douyin-mashida): 皮肤自动发货(按内部 SKU 分流 + 领取链接 + 买家领取接口)
抖音码速达的皮肤类商品改为「自动发货 + 领取链接」:买家不用输订单号,点链接直接领。
**分流(按内部 SKU)**
- 平台闸门放行 `provider='douyin_mashida' && platform='doudian'`,走**独立分支**
(原有 91/快手路径一行未动,避免外溢)
- 判据:内部 SKU(`sku_order_list[].code`,即 order_items.sku_code)命中权威表
`AFFILIATE_DASH_SKU_MAPPING` → 新执行器 `douyin_mashida_skin`;未命中 → `manual_dispatch`
- 皮肤判定与商品图同源(都用那张权威表),保证「能路由 ⇒ 有图」
- 履约路由新增 `internal_sku` 匹配维度(`rules[].internalSku`,NFKC+去空白+小写,exact/contains);
旧规则缺 `matchField` 时默认 `product_name`,**归一化/优先级/回退顺序完全不变**
**执行器与领取 token**
- 新增 `douyin-mashida-skin-executor`:建 claim token、置 `link_generated/pending_claim`,
`resolveDeliveryLink` 返回本站路径式领取链接;注册进 registry、planner 分支、
bootstrap 种子 profile(`抖音皮肤自动发货`);进 `ROUTABLE_EXECUTOR_KEYS`
- token 粒度 = 一个履约单元一个(`claim_tokens.task_id` 唯一);一单多项时
cert_link/买家消息取 task id 最小的那个并告警
**cert_link 与发消息**
- 皮肤订单且该订单项已有 token 且配了 `claimLinkBase` → `cert_link = claimLinkBase/token`;
其它情况一律用 `certLink`(老行为不变)
- 领取链接**只认** `claimLinkBase`,绝不回退 `buildClaimUrl`/`orders.claimBaseUrl`
(那是 hash 形式的打手领取页,语义不同)
- 付款建单+发券成功后按 `messageTemplate`(`{link}/{sku}/{orderNo}/{productTitle}`)
经 `order.message` 发给买家;best-effort,失败只记 warn
**买家领取接口**
- `GET/POST /api/v1/claim-skin/:token`(限流、公开);详情含内部SKU/引流标题/商品图/
数量/金额/支付时间/动态表单字段;token 失效给明确 errorCode(404/410/409),不打 500
- 提交账号:先核销平台券再落记录(避免「记账了但券没核销」的资损),已提交幂等
**隐私**
- 买家游戏账号落 `fulfillment_tasks.claim_submission_json`(迁移 096),
**不进** `work_orders.material_json`(那是发给打手的素材);详情接口不返回券码明文/手机号/地址/open_id
This commit is contained in:
@@ -0,0 +1,157 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import {
|
||||
douyinMashidaSkinExecutor,
|
||||
resolveSkinTaskClaimToken,
|
||||
} from './douyin-mashida-skin-executor.js'
|
||||
import { getFulfillmentExecutor } from './registry.js'
|
||||
import type { FulfillmentPrepareDeps } from './types.js'
|
||||
import type { TaskRow } from '../../../types/repository/rows.js'
|
||||
|
||||
const FIXED_NOW = '2026-10-10T00:00:00.000Z'
|
||||
|
||||
function createTask(overrides: Partial<TaskRow> = {}): TaskRow {
|
||||
return {
|
||||
id: 9,
|
||||
order_id: 1,
|
||||
order_item_id: 11,
|
||||
unit_index: 1,
|
||||
platform_order_id: '6930318258716179555',
|
||||
profile_id: 3,
|
||||
task_no: 'DT-1',
|
||||
executor_key: 'douyin_mashida_skin',
|
||||
task_status: 'paid',
|
||||
delivery_status: 'pending',
|
||||
result_code: '',
|
||||
result_message: '',
|
||||
automation_mode: 'manual',
|
||||
requires_claim: true,
|
||||
user_action_status: 'pending_claim',
|
||||
attempt_count: 0,
|
||||
runtime_session_id: '',
|
||||
login_type: '',
|
||||
nickname: '',
|
||||
role_name: '',
|
||||
role_id: '',
|
||||
area: '',
|
||||
partition_name: '',
|
||||
claim_token: '',
|
||||
claim_expires_at: null,
|
||||
primary_claim_token: '',
|
||||
primary_claim_token_id: null,
|
||||
primary_claim_token_status: '',
|
||||
primary_claim_expires_at: null,
|
||||
artifacts_json: {},
|
||||
context_json: {},
|
||||
screenshot_path: '',
|
||||
last_error: '',
|
||||
retry_count: 0,
|
||||
created_at: FIXED_NOW,
|
||||
updated_at: FIXED_NOW,
|
||||
claimed_at: null,
|
||||
role_confirmed_at: null,
|
||||
redeemed_at: null,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function createDeps(overrides: Partial<FulfillmentPrepareDeps> = {}) {
|
||||
const updates: Array<{ taskId: number | string; patch: Record<string, unknown> }> = []
|
||||
const tokenRequests: Array<number | string> = []
|
||||
|
||||
const deps: FulfillmentPrepareDeps = {
|
||||
updateTask: async (taskId, patch) => {
|
||||
updates.push({ taskId, patch: { ...patch } })
|
||||
return { ...createTask(), ...patch }
|
||||
},
|
||||
createTaskClaimToken: async (taskId) => {
|
||||
tokenRequests.push(taskId)
|
||||
return { token: 'skin-token', expired_at: null }
|
||||
},
|
||||
notifyTaskAutoManualReview: async () => null,
|
||||
nowIso: () => FIXED_NOW,
|
||||
...overrides,
|
||||
}
|
||||
|
||||
return { deps, updates, tokenRequests }
|
||||
}
|
||||
|
||||
test('皮肤执行器已注册到 registry', () => {
|
||||
assert.equal(getFulfillmentExecutor('douyin_mashida_skin'), douyinMashidaSkinExecutor)
|
||||
})
|
||||
|
||||
test('preparePaidTask:无 token 时生成 claim token 并置为待领取', async () => {
|
||||
const { deps, updates, tokenRequests } = createDeps()
|
||||
|
||||
const result = await douyinMashidaSkinExecutor.preparePaidTask?.(createTask(), deps)
|
||||
|
||||
assert.deepEqual(tokenRequests, [9])
|
||||
assert.equal(updates.length, 2)
|
||||
assert.deepEqual(updates[0]?.patch, {
|
||||
claim_token: 'skin-token',
|
||||
claim_expires_at: null,
|
||||
updated_at: FIXED_NOW,
|
||||
})
|
||||
assert.deepEqual(updates[1]?.patch, {
|
||||
task_status: 'link_generated',
|
||||
user_action_status: 'pending_claim',
|
||||
last_error: '',
|
||||
updated_at: FIXED_NOW,
|
||||
})
|
||||
assert.equal(result?.task_status, 'link_generated')
|
||||
})
|
||||
|
||||
test('preparePaidTask:已有 token 且已是待领取时完全幂等(不重复建 token)', async () => {
|
||||
const { deps, updates, tokenRequests } = createDeps()
|
||||
|
||||
const result = await douyinMashidaSkinExecutor.preparePaidTask?.(
|
||||
createTask({
|
||||
claim_token: 'skin-token',
|
||||
primary_claim_token: 'skin-token',
|
||||
primary_claim_token_id: 5,
|
||||
task_status: 'link_generated',
|
||||
user_action_status: 'pending_claim',
|
||||
}),
|
||||
deps,
|
||||
)
|
||||
|
||||
assert.deepEqual(tokenRequests, [])
|
||||
assert.deepEqual(updates, [])
|
||||
assert.equal(result?.task_status, 'link_generated')
|
||||
})
|
||||
|
||||
test('preparePaidTask:已有 token 但状态未就绪时只补状态', async () => {
|
||||
const { deps, updates, tokenRequests } = createDeps()
|
||||
|
||||
await douyinMashidaSkinExecutor.preparePaidTask?.(
|
||||
createTask({ claim_token: 'skin-token', primary_claim_token: 'skin-token' }),
|
||||
deps,
|
||||
)
|
||||
|
||||
assert.deepEqual(tokenRequests, [])
|
||||
assert.equal(updates.length, 1)
|
||||
assert.equal(updates[0]?.patch.task_status, 'link_generated')
|
||||
})
|
||||
|
||||
test('preparePaidTask:买家已领取的任务不会被降级回待领取', async () => {
|
||||
const { deps, updates, tokenRequests } = createDeps()
|
||||
|
||||
const claimed = createTask({
|
||||
claim_token: 'skin-token',
|
||||
primary_claim_token: 'skin-token',
|
||||
task_status: 'claimed',
|
||||
user_action_status: 'not_required',
|
||||
})
|
||||
const result = await douyinMashidaSkinExecutor.preparePaidTask?.(claimed, deps)
|
||||
|
||||
assert.deepEqual(tokenRequests, [])
|
||||
assert.deepEqual(updates, [])
|
||||
assert.equal(result?.task_status, 'claimed')
|
||||
})
|
||||
|
||||
test('resolveSkinTaskClaimToken 优先 primary_claim_token', () => {
|
||||
assert.equal(resolveSkinTaskClaimToken({ claim_token: 'a' }), 'a')
|
||||
assert.equal(resolveSkinTaskClaimToken({ claim_token: 'a', primary_claim_token: 'b' }), 'b')
|
||||
assert.equal(resolveSkinTaskClaimToken(null), '')
|
||||
})
|
||||
@@ -0,0 +1,134 @@
|
||||
import { TASK_STATUS } from '../../../domain/task-status.js'
|
||||
import { listTasksByOrderId } from '../../../repositories/task-repo.js'
|
||||
import { logWarn } from '../../../utils/logger.js'
|
||||
import { resolveDouyinMashidaSkinClaimUrl } from '../../platforms/douyin-mashida/claim-link.js'
|
||||
import type { DouyinMashidaSourceConfig } from '../../platforms/douyin-mashida/source-config-service.js'
|
||||
import {
|
||||
FULFILLMENT_EXECUTOR_KEYS,
|
||||
type FulfillmentDeliveryLink,
|
||||
type FulfillmentExecutor,
|
||||
type FulfillmentPrepareDeps,
|
||||
} from './types.js'
|
||||
import type { TaskRow } from '../../../types/repository/rows.js'
|
||||
|
||||
/**
|
||||
* 抖音码速达「皮肤自动发货」执行器。
|
||||
*
|
||||
* 与 affiliate-dash 执行器的最大区别:**不打任何外部平台**。
|
||||
* 付款后我们只需要「确保任务有 claim token」并把任务置为待领取(`link_generated` + `pending_claim`),
|
||||
* 领取链接(`claimLinkBase/token`)由调用方拿去做两件事:
|
||||
* 1. 写进 `coupons.syncV2` 的 `cert_link`(见 redeem/certificate-service.ts);
|
||||
* 2. 通过 `order.message` 按模板发给买家(见 douyin-mashida/notify-service.ts)。
|
||||
*/
|
||||
export const douyinMashidaSkinExecutor: FulfillmentExecutor = {
|
||||
key: FULFILLMENT_EXECUTOR_KEYS.DOUYIN_MASHIDA_SKIN,
|
||||
preparePaidTask,
|
||||
resolveDeliveryLink,
|
||||
}
|
||||
|
||||
export function resolveSkinTaskClaimToken(task: Partial<TaskRow> | null | undefined): string {
|
||||
return String(task?.primary_claim_token || task?.claim_token || '').trim()
|
||||
}
|
||||
|
||||
export type OrderItemSkinClaimLink = {
|
||||
/** 领取链接;未配置 claimLinkBase、或该订单项没有皮肤任务/token 时为空串 */
|
||||
claimUrl: string
|
||||
token: string
|
||||
/** 该订单项下的皮肤履约单元数量(数量 > 1 时会有多个 token) */
|
||||
taskCount: number
|
||||
pickedTaskId: number | null
|
||||
}
|
||||
|
||||
/**
|
||||
* 取某订单项的皮肤领取链接。
|
||||
*
|
||||
* 一个订单项按数量会拆成 N 个履约单元(`fulfillment_tasks`),每个单元一个 token
|
||||
* (`claim_tokens.task_id` 唯一);这里固定取 task id 最小的那个,保证同一张券每次解析结果一致。
|
||||
* 调用方(certificate-service / notify-service)据 `taskCount` 打 warn 留痕。
|
||||
*/
|
||||
export async function resolveOrderItemSkinClaimLink(input: {
|
||||
orderId: number | string
|
||||
orderItemId: number | string
|
||||
config?: DouyinMashidaSourceConfig | undefined
|
||||
}): Promise<OrderItemSkinClaimLink> {
|
||||
const skinTasks = (await listTasksByOrderId(input.orderId))
|
||||
.filter(
|
||||
(task) =>
|
||||
Number(task.order_item_id) === Number(input.orderItemId) &&
|
||||
String(task.executor_key || '').trim() === FULFILLMENT_EXECUTOR_KEYS.DOUYIN_MASHIDA_SKIN,
|
||||
)
|
||||
.sort((left, right) => Number(left.id) - Number(right.id))
|
||||
|
||||
const pickedTask = skinTasks[0] || null
|
||||
const token = resolveSkinTaskClaimToken(pickedTask)
|
||||
|
||||
return {
|
||||
claimUrl: resolveDouyinMashidaSkinClaimUrl(token, input.config),
|
||||
token,
|
||||
taskCount: skinTasks.length,
|
||||
pickedTaskId: pickedTask ? Number(pickedTask.id) : null,
|
||||
}
|
||||
}
|
||||
|
||||
async function preparePaidTask(
|
||||
task: TaskRow,
|
||||
deps: FulfillmentPrepareDeps,
|
||||
): Promise<TaskRow | null> {
|
||||
let workingTask = task
|
||||
|
||||
// 幂等:已有 token 不重复生成(claim_tokens.task_id 唯一,重复插入只会覆盖)。
|
||||
if (!resolveSkinTaskClaimToken(task)) {
|
||||
const claimToken = await deps.createTaskClaimToken(task.id)
|
||||
workingTask =
|
||||
(await deps.updateTask(task.id, {
|
||||
claim_token: claimToken.token,
|
||||
claim_expires_at: claimToken.expired_at,
|
||||
updated_at: deps.nowIso(),
|
||||
})) || task
|
||||
}
|
||||
|
||||
// 买家已提交过(claimed)的任务不允许被降级回待领取。
|
||||
if (
|
||||
workingTask.task_status === TASK_STATUS.CLAIMED ||
|
||||
workingTask.task_status === TASK_STATUS.REDEEMED ||
|
||||
workingTask.task_status === TASK_STATUS.COMPLETED
|
||||
) {
|
||||
return workingTask
|
||||
}
|
||||
|
||||
if (
|
||||
workingTask.task_status !== TASK_STATUS.LINK_GENERATED ||
|
||||
workingTask.user_action_status !== 'pending_claim'
|
||||
) {
|
||||
workingTask =
|
||||
(await deps.updateTask(task.id, {
|
||||
task_status: TASK_STATUS.LINK_GENERATED,
|
||||
user_action_status: 'pending_claim',
|
||||
last_error: '',
|
||||
updated_at: deps.nowIso(),
|
||||
})) || workingTask
|
||||
}
|
||||
|
||||
return workingTask
|
||||
}
|
||||
|
||||
/** 对外统一返回本站皮肤领取链接;基址未配置时返回 null(不猜、不回退 hash 版领取页)。 */
|
||||
async function resolveDeliveryLink(task: TaskRow): Promise<FulfillmentDeliveryLink | null> {
|
||||
const token = resolveSkinTaskClaimToken(task)
|
||||
if (!token) {
|
||||
return null
|
||||
}
|
||||
|
||||
const claimUrl = resolveDouyinMashidaSkinClaimUrl(token)
|
||||
if (!claimUrl) {
|
||||
logWarn('[douyin-mashida/skin]', '未配置领取链接基址(claimLinkBase),无法生成皮肤领取链接', {
|
||||
taskId: task.id,
|
||||
taskNo: task.task_no,
|
||||
platformOrderId: task.platform_order_id,
|
||||
})
|
||||
return null
|
||||
}
|
||||
|
||||
const expireTime = String(task.primary_claim_expires_at || task.claim_expires_at || '').trim()
|
||||
return expireTime ? { claimUrl, expireTime } : { claimUrl }
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { isPaidPreparationStableStatus } from '../../../domain/task-status.js'
|
||||
import { affiliateDashExecutor } from './affiliate-dash-executor.js'
|
||||
import { douyinMashidaSkinExecutor } from './douyin-mashida-skin-executor.js'
|
||||
import { legacyFeifeiExecutor, legacyLewanExecutor } from './legacy-retired-executor.js'
|
||||
import { manualDispatchExecutor } from './manual-executor.js'
|
||||
import {
|
||||
@@ -14,6 +15,7 @@ import type { TaskRow } from '../../../types/repository/rows.js'
|
||||
|
||||
const EXECUTORS = new Map<string, FulfillmentExecutor>([
|
||||
[FULFILLMENT_EXECUTOR_KEYS.AFFILIATE_DASH, affiliateDashExecutor],
|
||||
[FULFILLMENT_EXECUTOR_KEYS.DOUYIN_MASHIDA_SKIN, douyinMashidaSkinExecutor],
|
||||
[FULFILLMENT_EXECUTOR_KEYS.MANUAL_DISPATCH, manualDispatchExecutor],
|
||||
[FULFILLMENT_EXECUTOR_KEYS.KUAISHOU_CLOUD, legacyLewanExecutor],
|
||||
[FULFILLMENT_EXECUTOR_KEYS.KUAISHOU_FEIFEI, legacyFeifeiExecutor],
|
||||
|
||||
@@ -4,6 +4,8 @@ import type { TaskRow } from '../../../types/repository/rows.js'
|
||||
export const FULFILLMENT_EXECUTOR_KEYS = {
|
||||
MANUAL_DISPATCH: 'manual_dispatch',
|
||||
AFFILIATE_DASH: 'affiliate_dash',
|
||||
/** 抖音码速达「皮肤自动发货」:只发本站领取链接,不打 affiliate-dash 平台 */
|
||||
DOUYIN_MASHIDA_SKIN: 'douyin_mashida_skin',
|
||||
/** @deprecated 已下线,仅历史任务 / stub 识别 */
|
||||
KUAISHOU_CLOUD: 'kuaishou_ct_assisted',
|
||||
/** @deprecated 已下线,仅历史任务识别 */
|
||||
@@ -68,6 +70,10 @@ export function isManualDispatchExecutor(value: unknown): boolean {
|
||||
return normalizeExecutorKey(value) === FULFILLMENT_EXECUTOR_KEYS.MANUAL_DISPATCH
|
||||
}
|
||||
|
||||
export function isDouyinMashidaSkinExecutor(value: unknown): boolean {
|
||||
return normalizeExecutorKey(value) === FULFILLMENT_EXECUTOR_KEYS.DOUYIN_MASHIDA_SKIN
|
||||
}
|
||||
|
||||
export function isRetiredFulfillmentExecutor(value: unknown): boolean {
|
||||
const executorKey = normalizeExecutorKey(value)
|
||||
return (
|
||||
|
||||
@@ -109,6 +109,66 @@ test('planFulfillmentTaskForOrderItem affiliate 缺 sku 时返回 null', async (
|
||||
assert.equal(plan, null)
|
||||
})
|
||||
|
||||
test('planFulfillmentTaskForOrderItem 为抖音皮肤商品生成领取链接履约计划', async () => {
|
||||
const plan = await planFulfillmentTaskForOrderItem({
|
||||
order: createOrder({ provider: 'douyin_mashida', platform: 'doudian' }),
|
||||
item: createOrderItem({
|
||||
sku_code: '幸运币2个',
|
||||
sku_name: '【测试专用】和平精英皮肤小店入口',
|
||||
item_snapshot_json: {
|
||||
fulfillmentRoute: { selectedExecutorKey: 'douyin_mashida_skin' },
|
||||
douyinSkin: {
|
||||
internalSku: '幸运币2个',
|
||||
sku: 'lucky_coin_x2',
|
||||
productTitle: '【测试专用】和平精英皮肤小店入口',
|
||||
},
|
||||
},
|
||||
}),
|
||||
getProfileByKey: async (profileKey) => ({
|
||||
id: 21,
|
||||
profile_key: profileKey,
|
||||
name: '抖音皮肤自动发货',
|
||||
executor_key: profileKey,
|
||||
requires_claim: false,
|
||||
auto_dispatch: false,
|
||||
}),
|
||||
})
|
||||
|
||||
assert.ok(plan)
|
||||
assert.equal(plan.executorKey, 'douyin_mashida_skin')
|
||||
assert.equal(plan.profileKey, 'douyin_mashida_skin')
|
||||
assert.equal(plan.requiresClaim, true)
|
||||
assert.equal(plan.autoDispatch, false)
|
||||
assert.equal(plan.context.affiliateDash, null)
|
||||
|
||||
const douyinSkin = plan.context.douyinSkin as Record<string, unknown> | null
|
||||
assert.ok(douyinSkin)
|
||||
assert.equal(douyinSkin.internalSku, '幸运币2个')
|
||||
assert.equal(douyinSkin.sku, 'lucky_coin_x2')
|
||||
assert.equal(douyinSkin.imageUrl, '/images/products/lucky_coin_x2.webp')
|
||||
})
|
||||
|
||||
test('planFulfillmentTaskForOrderItem 抖音皮肤缺内部 SKU 时返回 null', async () => {
|
||||
const plan = await planFulfillmentTaskForOrderItem({
|
||||
order: createOrder({ provider: 'douyin_mashida', platform: 'doudian' }),
|
||||
item: createOrderItem({
|
||||
sku_code: '',
|
||||
sku_name: '无内部 SKU',
|
||||
item_snapshot_json: {
|
||||
fulfillmentRoute: { selectedExecutorKey: 'douyin_mashida_skin' },
|
||||
},
|
||||
}),
|
||||
getProfileByKey: async (profileKey) => ({
|
||||
id: 21,
|
||||
profile_key: profileKey,
|
||||
name: '抖音皮肤自动发货',
|
||||
executor_key: profileKey,
|
||||
}),
|
||||
})
|
||||
|
||||
assert.equal(plan, null)
|
||||
})
|
||||
|
||||
function createOrder(patch: Partial<OrderRow> = {}): OrderRow {
|
||||
return {
|
||||
id: 1,
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import { getFulfillmentProfileByKey } from '../../repositories/fulfillment-profile-repo.js'
|
||||
import { resolveProductImageUrl } from '../platforms/affiliate-dash/product-image.js'
|
||||
import type { JsonObject } from '../../types/json.js'
|
||||
import type { OrderItemRow, OrderRow } from '../../types/repository/rows.js'
|
||||
import { FULFILLMENT_EXECUTOR_KEYS, isAffiliateDashExecutor } from './executors/types.js'
|
||||
import {
|
||||
FULFILLMENT_EXECUTOR_KEYS,
|
||||
isAffiliateDashExecutor,
|
||||
isDouyinMashidaSkinExecutor,
|
||||
} from './executors/types.js'
|
||||
|
||||
export type FulfillmentBindingLike = {
|
||||
id: number
|
||||
@@ -91,6 +96,7 @@ function buildFulfillmentTaskContext({
|
||||
fulfillmentConfig: JsonObject
|
||||
}) {
|
||||
const affiliateDashConfig = parseJsonObject(fulfillmentConfig.affiliateDash)
|
||||
const douyinSkinConfig = parseJsonObject(fulfillmentConfig.douyinSkin)
|
||||
|
||||
return {
|
||||
profileKey,
|
||||
@@ -122,6 +128,17 @@ function buildFulfillmentTaskContext({
|
||||
lastSyncedAt: null,
|
||||
}
|
||||
: null,
|
||||
// 皮肤自动发货:任务上下文只放「怎么发货」的静态信息;买家提交的游戏账号
|
||||
// 属于隐私数据,落在 fulfillment_tasks.claim_submission_json,不进这里、更不进打手工单。
|
||||
douyinSkin: isDouyinMashidaSkinExecutor(executorKey)
|
||||
? {
|
||||
flowType: 'douyin_mashida_skin',
|
||||
internalSku: String(douyinSkinConfig.internalSku || item.sku_code || '').trim(),
|
||||
sku: String(douyinSkinConfig.sku || '').trim(),
|
||||
productTitle: String(douyinSkinConfig.productTitle || item.sku_name || '').trim(),
|
||||
imageUrl: resolveProductImageUrl(douyinSkinConfig.internalSku || item.sku_code),
|
||||
}
|
||||
: null,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,6 +151,10 @@ async function resolveDynamicFulfillmentProfile(
|
||||
return resolveDynamicAffiliateDashProfile(item, getProfileByKey)
|
||||
}
|
||||
|
||||
if (selectedExecutorKey === FULFILLMENT_EXECUTOR_KEYS.DOUYIN_MASHIDA_SKIN) {
|
||||
return resolveDynamicDouyinMashidaSkinProfile(item, getProfileByKey)
|
||||
}
|
||||
|
||||
if (selectedExecutorKey === FULFILLMENT_EXECUTOR_KEYS.MANUAL_DISPATCH) {
|
||||
return resolveDynamicManualDispatchProfile(item, getProfileByKey)
|
||||
}
|
||||
@@ -180,6 +201,47 @@ async function resolveDynamicAffiliateDashProfile(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 皮肤自动发货:内部 SKU 命中权威映射表时使用。
|
||||
* `requires_claim=true` 让任务要求领取链接;`auto_dispatch=false` 表示不需要打手抢单。
|
||||
*/
|
||||
async function resolveDynamicDouyinMashidaSkinProfile(
|
||||
item: OrderItemRow,
|
||||
getProfileByKey: FulfillmentProfileResolver,
|
||||
): Promise<FulfillmentBindingLike | null> {
|
||||
const snapshot = parseJsonObject(item.item_snapshot_json)
|
||||
const douyinSkin = parseJsonObject(snapshot.douyinSkin)
|
||||
const internalSku = String(douyinSkin.internalSku || item.sku_code || '').trim()
|
||||
if (!internalSku) {
|
||||
return null
|
||||
}
|
||||
|
||||
const profile = await getProfileByKey(FULFILLMENT_EXECUTOR_KEYS.DOUYIN_MASHIDA_SKIN)
|
||||
if (!profile) {
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
...profile,
|
||||
profile_id: Number(profile.id || profile.profile_id || 0),
|
||||
profile_key: FULFILLMENT_EXECUTOR_KEYS.DOUYIN_MASHIDA_SKIN,
|
||||
profile_name: String(profile.profile_name || profile.name || '抖音皮肤自动发货').trim(),
|
||||
executor_key: FULFILLMENT_EXECUTOR_KEYS.DOUYIN_MASHIDA_SKIN,
|
||||
requires_claim: true,
|
||||
auto_dispatch: false,
|
||||
config_json: {
|
||||
flowType: 'douyin_mashida_skin',
|
||||
configId: `${FULFILLMENT_EXECUTOR_KEYS.DOUYIN_MASHIDA_SKIN}:${internalSku}`,
|
||||
douyinSkin: {
|
||||
internalSku,
|
||||
sku: String(douyinSkin.sku || '').trim(),
|
||||
productTitle: String(douyinSkin.productTitle || item.sku_name || '').trim(),
|
||||
},
|
||||
notes: '抖音码速达皮肤商品自动发货(本站领取链接)',
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveDynamicManualDispatchProfile(
|
||||
item: OrderItemRow,
|
||||
getProfileByKey: FulfillmentProfileResolver,
|
||||
|
||||
@@ -4,7 +4,9 @@ import test from 'node:test'
|
||||
import {
|
||||
matchAffiliateDashSku,
|
||||
matchAffiliateDashSkuPassthrough,
|
||||
matchDouyinMashidaSkinSku,
|
||||
normalizeAffiliateDashMappingKey,
|
||||
resolveOrderItemForFulfillment,
|
||||
} from './product-resolution-service.js'
|
||||
import {
|
||||
AFFILIATE_DASH_SKU_MAPPING,
|
||||
@@ -12,6 +14,7 @@ import {
|
||||
resolveAffiliateDashDisplayProductName,
|
||||
reverseAffiliateDashSkuToProductNo,
|
||||
} from '../platforms/affiliate-dash/sku-mapping.js'
|
||||
import { resolveProductImageUrl } from '../platforms/affiliate-dash/product-image.js'
|
||||
|
||||
test('权威表覆盖核心中文商品', () => {
|
||||
assert.equal(AFFILIATE_DASH_SKU_MAPPING['幸运币90个'], 'lucky_coin_x90')
|
||||
@@ -96,3 +99,100 @@ test('reverseAffiliateDashSkuToProductNo 未命中返回空串', () => {
|
||||
assert.equal(reverseAffiliateDashSkuToProductNo('not_a_real_sku'), '')
|
||||
assert.equal(reverseAffiliateDashSkuToProductNo(''), '')
|
||||
})
|
||||
|
||||
// ---- 抖音码速达(抖店)皮肤商品分流 ----
|
||||
|
||||
const DOUYIN_SKIN_TITLE = '【测试专用】和平精英皮肤小店入口出售返场吃鸡皮肤浪漫天命专用'
|
||||
|
||||
function buildDouyinItem(internalSku: string, productName = DOUYIN_SKIN_TITLE) {
|
||||
return {
|
||||
itemId: '6930318258716179555',
|
||||
externalItemId: '6930318258716179555',
|
||||
externalSkuCode: internalSku,
|
||||
externalSkuName: productName,
|
||||
skuCode: internalSku,
|
||||
skuName: productName,
|
||||
quantity: 1,
|
||||
}
|
||||
}
|
||||
|
||||
function selectedExecutorKeyOf(
|
||||
item: Awaited<ReturnType<typeof resolveOrderItemForFulfillment>>,
|
||||
): string {
|
||||
const route = item.snapshot.fulfillmentRoute as
|
||||
| { selectedExecutorKey?: string }
|
||||
| null
|
||||
| undefined
|
||||
return String(route?.selectedExecutorKey || '')
|
||||
}
|
||||
|
||||
test('matchDouyinMashidaSkinSku 只认权威映射表并做归一化', () => {
|
||||
assert.equal(matchDouyinMashidaSkinSku('幸运币2个'), 'lucky_coin_x2')
|
||||
assert.equal(matchDouyinMashidaSkinSku(' 幸运币2个 '), 'lucky_coin_x2')
|
||||
assert.equal(matchDouyinMashidaSkinSku('不存在的皮肤'), '')
|
||||
assert.equal(matchDouyinMashidaSkinSku(''), '')
|
||||
})
|
||||
|
||||
test('抖音订单:内部 SKU 命中映射表 → 皮肤自动发货', async () => {
|
||||
const item = await resolveOrderItemForFulfillment({
|
||||
provider: 'douyin_mashida',
|
||||
platform: 'doudian',
|
||||
item: buildDouyinItem('幸运币2个'),
|
||||
})
|
||||
|
||||
assert.equal(item.isConfigured, true)
|
||||
assert.equal(selectedExecutorKeyOf(item), 'douyin_mashida_skin')
|
||||
assert.equal(item.skuCode, '幸运币2个')
|
||||
assert.equal(item.skuName, DOUYIN_SKIN_TITLE)
|
||||
assert.deepEqual(item.snapshot.douyinSkin, {
|
||||
matchMode: 'affiliate_dash_sku_mapping',
|
||||
internalSku: '幸运币2个',
|
||||
sku: 'lucky_coin_x2',
|
||||
productTitle: DOUYIN_SKIN_TITLE,
|
||||
})
|
||||
assert.equal(resolveProductImageUrl(item.skuCode), '/images/products/lucky_coin_x2.webp')
|
||||
})
|
||||
|
||||
test('抖音订单:内部 SKU 未命中映射表 → 回退 manual_dispatch', async () => {
|
||||
const item = await resolveOrderItemForFulfillment({
|
||||
provider: 'douyin_mashida',
|
||||
platform: 'doudian',
|
||||
item: buildDouyinItem('不存在的皮肤'),
|
||||
})
|
||||
|
||||
assert.equal(selectedExecutorKeyOf(item), 'manual_dispatch')
|
||||
assert.equal(item.snapshot.douyinSkin, null)
|
||||
// 引流长标题作为 skuName,内部 SKU 作为 skuCode
|
||||
assert.equal(item.skuCode, '不存在的皮肤')
|
||||
assert.equal(item.skuName, DOUYIN_SKIN_TITLE)
|
||||
})
|
||||
|
||||
test('抖音订单:平台闸门只认 douyin_mashida + doudian,其它组合仍不配置', async () => {
|
||||
const wrongPlatform = await resolveOrderItemForFulfillment({
|
||||
provider: 'douyin_mashida',
|
||||
platform: 'kuaishou',
|
||||
item: buildDouyinItem('幸运币2个'),
|
||||
})
|
||||
assert.equal(wrongPlatform.isConfigured, false)
|
||||
assert.equal(wrongPlatform.snapshot.fulfillmentRoute, null)
|
||||
|
||||
const wrongProvider = await resolveOrderItemForFulfillment({
|
||||
provider: 'other',
|
||||
platform: 'doudian',
|
||||
item: buildDouyinItem('幸运币2个'),
|
||||
})
|
||||
assert.equal(wrongProvider.isConfigured, false)
|
||||
assert.equal(wrongProvider.snapshot.fulfillmentRoute, null)
|
||||
})
|
||||
|
||||
test('抖音订单:不触发 affiliate-dash 平台的 sku 透传(严格按内部 SKU 分流)', async () => {
|
||||
const item = await resolveOrderItemForFulfillment({
|
||||
provider: 'douyin_mashida',
|
||||
platform: 'doudian',
|
||||
item: buildDouyinItem('lucky_coin_x2'),
|
||||
})
|
||||
|
||||
// 英文 sku 不是内部 SKU,抖音侧不做透传匹配,走人工
|
||||
assert.equal(selectedExecutorKeyOf(item), 'manual_dispatch')
|
||||
assert.equal(item.snapshot.affiliateDash, null)
|
||||
})
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
import { resolveFulfillmentRoute, type FulfillmentRouteResult } from './routing-config-service.js'
|
||||
import {
|
||||
normalizeInternalSkuMatchKey,
|
||||
resolveFulfillmentRoute,
|
||||
type FulfillmentRouteResult,
|
||||
} from './routing-config-service.js'
|
||||
import { getAffiliateDashConfig } from '../platforms/affiliate-dash/config.js'
|
||||
import { listAllAffiliateDashProducts } from '../platforms/affiliate-dash/product-service.js'
|
||||
import { mergeAffiliateDashSkuMapping } from '../platforms/affiliate-dash/sku-mapping.js'
|
||||
import {
|
||||
AFFILIATE_DASH_SKU_MAPPING,
|
||||
mergeAffiliateDashSkuMapping,
|
||||
} from '../platforms/affiliate-dash/sku-mapping.js'
|
||||
import type { AffiliateDashSkuMapping } from '../../types/runtime-config.js'
|
||||
import { FULFILLMENT_EXECUTOR_KEYS } from './executors/types.js'
|
||||
import { normalizeProductMatchName } from '../order/product-match-utils.js'
|
||||
@@ -37,6 +44,14 @@ export type AffiliateDashSkuMatch = {
|
||||
matchMode: 'affiliate_dash_sku_mapping' | 'affiliate_dash_sku_passthrough'
|
||||
}
|
||||
|
||||
/** 抖音码速达「皮肤」命中信息:内部 SKU → 英文 sku(图片文件名同一套映射)。 */
|
||||
export type DouyinMashidaSkinMatch = {
|
||||
sku: string
|
||||
internalSku: string
|
||||
productTitle: string
|
||||
matchMode: 'affiliate_dash_sku_mapping'
|
||||
}
|
||||
|
||||
type FulfillmentItemCandidate = {
|
||||
externalItemId: string
|
||||
externalSkuCode: string
|
||||
@@ -44,6 +59,7 @@ type FulfillmentItemCandidate = {
|
||||
externalSkuNameNormalized: string
|
||||
resolvedSkuCode: string
|
||||
affiliateDashMatch: AffiliateDashSkuMatch | null
|
||||
douyinSkinMatch: DouyinMashidaSkinMatch | null
|
||||
fulfillmentRoute: FulfillmentRouteResult | null
|
||||
isConfigured: boolean
|
||||
}
|
||||
@@ -75,6 +91,7 @@ export async function resolveOrderItemForFulfillment({
|
||||
externalSkuName,
|
||||
externalSkuNameNormalized,
|
||||
affiliateDashMatch,
|
||||
douyinSkinMatch,
|
||||
fulfillmentRoute,
|
||||
} = candidate
|
||||
|
||||
@@ -113,6 +130,14 @@ export async function resolveOrderItemForFulfillment({
|
||||
skuName: affiliateDashMatch.skuName,
|
||||
}
|
||||
: null,
|
||||
douyinSkin: douyinSkinMatch
|
||||
? {
|
||||
matchMode: douyinSkinMatch.matchMode,
|
||||
internalSku: douyinSkinMatch.internalSku,
|
||||
sku: douyinSkinMatch.sku,
|
||||
productTitle: douyinSkinMatch.productTitle,
|
||||
}
|
||||
: null,
|
||||
isConfigured: candidate.isConfigured,
|
||||
}
|
||||
|
||||
@@ -206,11 +231,22 @@ async function resolveConfiguredItemCandidate({
|
||||
externalSkuNameNormalized,
|
||||
resolvedSkuCode,
|
||||
affiliateDashMatch,
|
||||
douyinSkinMatch: null,
|
||||
fulfillmentRoute,
|
||||
isConfigured: Boolean(selectedExecutorKey),
|
||||
}
|
||||
}
|
||||
|
||||
if (isDouyinMashidaOrder(provider, platform)) {
|
||||
return resolveDouyinMashidaItemCandidate({
|
||||
item,
|
||||
externalItemId,
|
||||
externalSkuCode,
|
||||
externalSkuName,
|
||||
externalSkuNameNormalized,
|
||||
})
|
||||
}
|
||||
|
||||
const resolvedSkuCode = pickFirstNonEmpty([externalSkuCode, externalItemId])
|
||||
|
||||
return {
|
||||
@@ -220,11 +256,84 @@ async function resolveConfiguredItemCandidate({
|
||||
externalSkuNameNormalized,
|
||||
resolvedSkuCode,
|
||||
affiliateDashMatch: null,
|
||||
douyinSkinMatch: null,
|
||||
fulfillmentRoute: null,
|
||||
isConfigured: false,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 抖音码速达(抖店)订单分流。
|
||||
*
|
||||
* 平台字段口径:`sku_order_list[].code` = **内部 SKU**(如「幸运币2个」,才是真正的商品),
|
||||
* `product_name` = 引流长标题(如「【测试专用】和平精英皮肤小店入口…」)。
|
||||
* 因此分流与图片都按内部 SKU 走:
|
||||
* - 内部 SKU 命中权威表 `AFFILIATE_DASH_SKU_MAPPING` → 皮肤自动发货(本站领取链接);
|
||||
* - 未命中 → 显式映射拿不到通道,按现有语义回退 `manual_dispatch`(接单平台/人工)。
|
||||
*/
|
||||
function resolveDouyinMashidaItemCandidate({
|
||||
item,
|
||||
externalItemId,
|
||||
externalSkuCode,
|
||||
externalSkuName,
|
||||
externalSkuNameNormalized,
|
||||
}: {
|
||||
item: FulfillmentItem
|
||||
externalItemId: string
|
||||
externalSkuCode: string
|
||||
externalSkuName: string
|
||||
externalSkuNameNormalized: string
|
||||
}): FulfillmentItemCandidate {
|
||||
const internalSku = pickFirstNonEmpty([externalSkuCode, externalItemId])
|
||||
const productTitle = pickFirstNonEmpty([externalSkuName, internalSku])
|
||||
const skinSku = matchDouyinMashidaSkinSku(internalSku)
|
||||
const douyinSkinMatch: DouyinMashidaSkinMatch | null = skinSku
|
||||
? {
|
||||
sku: skinSku,
|
||||
internalSku,
|
||||
productTitle,
|
||||
matchMode: 'affiliate_dash_sku_mapping',
|
||||
}
|
||||
: null
|
||||
const fulfillmentRoute = resolveFulfillmentRoute({
|
||||
productName: productTitle,
|
||||
internalSku,
|
||||
preferredExecutorKey: douyinSkinMatch ? FULFILLMENT_EXECUTOR_KEYS.DOUYIN_MASHIDA_SKIN : '',
|
||||
candidates: [
|
||||
{
|
||||
executorKey: FULFILLMENT_EXECUTOR_KEYS.DOUYIN_MASHIDA_SKIN,
|
||||
available: Boolean(douyinSkinMatch),
|
||||
reason: douyinSkinMatch ? '' : '内部 SKU 未命中皮肤商品映射',
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
return {
|
||||
externalItemId,
|
||||
externalSkuCode,
|
||||
externalSkuName,
|
||||
externalSkuNameNormalized,
|
||||
// 内部 SKU 就是「商品」:保留中文内部 SKU 作为 skuCode,领取页图片与展示都靠它。
|
||||
resolvedSkuCode: internalSku || pickFirstNonEmpty([externalItemId, item.itemId]),
|
||||
affiliateDashMatch: null,
|
||||
douyinSkinMatch,
|
||||
fulfillmentRoute,
|
||||
isConfigured: Boolean(fulfillmentRoute.selectedExecutorKey),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 内部 SKU → 英文 sku:只查权威表(与领取页图片 `resolveProductImageUrl` 同一套来源),
|
||||
* 保证「能路由到皮肤执行器」与「能取到商品图」永远一致。
|
||||
*/
|
||||
export function matchDouyinMashidaSkinSku(internalSku: unknown): string {
|
||||
const raw = String(internalSku ?? '').trim()
|
||||
if (!raw) {
|
||||
return ''
|
||||
}
|
||||
return matchAffiliateDashSku(AFFILIATE_DASH_SKU_MAPPING, raw)
|
||||
}
|
||||
|
||||
async function resolveAffiliateDashSkuByProductNo(
|
||||
item: FulfillmentItem,
|
||||
): Promise<AffiliateDashSkuMatch | null> {
|
||||
@@ -337,10 +446,7 @@ export function matchAffiliateDashSku(mapping: AffiliateDashSkuMapping, productN
|
||||
}
|
||||
|
||||
export function normalizeAffiliateDashMappingKey(value: unknown): string {
|
||||
return String(value || '')
|
||||
.normalize('NFKC')
|
||||
.replace(/\s+/g, '')
|
||||
.toLowerCase()
|
||||
return normalizeInternalSkuMatchKey(value)
|
||||
}
|
||||
|
||||
function isOpen91KuaishouOrder(provider: unknown, platform: unknown) {
|
||||
@@ -349,6 +455,14 @@ function isOpen91KuaishouOrder(provider: unknown, platform: unknown) {
|
||||
)
|
||||
}
|
||||
|
||||
/** 抖音码速达:provider=douyin_mashida / platform=doudian(见 douyin-mashida/order-mapper.ts)。 */
|
||||
function isDouyinMashidaOrder(provider: unknown, platform: unknown) {
|
||||
return (
|
||||
String(provider || '').trim() === 'douyin_mashida' &&
|
||||
String(platform || '').trim() === 'doudian'
|
||||
)
|
||||
}
|
||||
|
||||
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
||||
return Object.prototype.toString.call(value) === '[object Object]'
|
||||
}
|
||||
|
||||
@@ -12,7 +12,11 @@ test('normalizeFulfillmentRoutingConfig drops retired executors and keeps affili
|
||||
})
|
||||
|
||||
assert.deepEqual(config.defaultExecutorPriority, ['affiliate_dash'])
|
||||
assert.deepEqual(Object.keys(config.executors).sort(), ['affiliate_dash', 'manual_dispatch'])
|
||||
assert.deepEqual(Object.keys(config.executors).sort(), [
|
||||
'affiliate_dash',
|
||||
'douyin_mashida_skin',
|
||||
'manual_dispatch',
|
||||
])
|
||||
assert.equal(config.unmatchedExecutorKey, 'manual_dispatch')
|
||||
})
|
||||
|
||||
@@ -176,3 +180,100 @@ test('resolveFulfillmentRoute 无指定匹配时按全局优先级选择', () =>
|
||||
assert.equal(result.selectedExecutorKey, 'affiliate_dash')
|
||||
assert.equal(result.reason, '按全局优先级命中')
|
||||
})
|
||||
|
||||
test('normalizeFulfillmentRoutingConfig 支持按内部 SKU 的规则维度', () => {
|
||||
const config = normalizeFulfillmentRoutingConfig({
|
||||
rules: [
|
||||
{
|
||||
internalSku: '幸运币2个',
|
||||
executorKey: 'douyin_mashida_skin',
|
||||
priority: 500,
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
assert.equal(config.rules.length, 1)
|
||||
const rule = config.rules[0]
|
||||
assert.ok(rule)
|
||||
assert.equal(rule.matchField, 'internal_sku')
|
||||
// 展示字段沿用 productName(值为内部 SKU),但商品名匹配键留空,避免被商品名规则误命中
|
||||
assert.equal(rule.productName, '幸运币2个')
|
||||
assert.equal(rule.normalizedProductName, '')
|
||||
assert.equal(rule.internalSku, '幸运币2个')
|
||||
assert.equal(rule.normalizedInternalSku, '幸运币2个')
|
||||
assert.equal(rule.id, '幸运币2个:douyin_mashida_skin')
|
||||
})
|
||||
|
||||
test('旧商品名规则归一化后带 matchField=product_name,语义不变', () => {
|
||||
const config = normalizeFulfillmentRoutingConfig({
|
||||
rules: [{ productName: '荣耀套装', executorKey: 'affiliate_dash', priority: 200 }],
|
||||
})
|
||||
|
||||
const rule = config.rules[0]
|
||||
assert.ok(rule)
|
||||
assert.equal(rule.matchField, 'product_name')
|
||||
assert.equal(rule.normalizedProductName, '荣耀套装')
|
||||
assert.equal(rule.internalSku, '')
|
||||
assert.equal(rule.id, '荣耀套装:affiliate_dash')
|
||||
})
|
||||
|
||||
test('resolveFulfillmentRoute 命中内部 SKU 规则', () => {
|
||||
const result = resolveFulfillmentRoute({
|
||||
productName: '【测试专用】和平精英皮肤小店入口',
|
||||
internalSku: '幸运币2个',
|
||||
candidates: [{ executorKey: 'douyin_mashida_skin', available: true }],
|
||||
config: normalizeFulfillmentRoutingConfig({
|
||||
rules: [{ internalSku: '幸运币2个', executorKey: 'douyin_mashida_skin', priority: 500 }],
|
||||
}),
|
||||
})
|
||||
|
||||
assert.equal(result.selectedExecutorKey, 'douyin_mashida_skin')
|
||||
assert.equal(result.reason, '命中商品路由规则')
|
||||
assert.equal(result.matchedRule?.productName, '幸运币2个')
|
||||
})
|
||||
|
||||
test('resolveFulfillmentRoute 内部 SKU 规则支持归一化与 contains', () => {
|
||||
const config = normalizeFulfillmentRoutingConfig({
|
||||
rules: [
|
||||
{
|
||||
internalSku: '幸运币',
|
||||
matchType: 'contains',
|
||||
executorKey: 'douyin_mashida_skin',
|
||||
priority: 500,
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
const exactFullWidth = resolveFulfillmentRoute({
|
||||
productName: '',
|
||||
internalSku: ' 幸运币2个 ',
|
||||
candidates: [{ executorKey: 'douyin_mashida_skin', available: true }],
|
||||
config,
|
||||
})
|
||||
assert.equal(exactFullWidth.selectedExecutorKey, 'douyin_mashida_skin')
|
||||
|
||||
const miss = resolveFulfillmentRoute({
|
||||
productName: '',
|
||||
internalSku: '荣耀勋章2个',
|
||||
candidates: [{ executorKey: 'douyin_mashida_skin', available: true }],
|
||||
config,
|
||||
})
|
||||
assert.equal(miss.selectedExecutorKey, 'manual_dispatch')
|
||||
})
|
||||
|
||||
test('resolveFulfillmentRoute 未命中内部 SKU 规则时商品名规则仍然优先生效', () => {
|
||||
const result = resolveFulfillmentRoute({
|
||||
productName: '荣耀套装',
|
||||
internalSku: '荣耀勋章2个',
|
||||
candidates: [{ executorKey: 'affiliate_dash', available: true }],
|
||||
config: normalizeFulfillmentRoutingConfig({
|
||||
rules: [
|
||||
{ productName: '荣耀套装', executorKey: 'affiliate_dash', priority: 200 },
|
||||
{ internalSku: '幸运币2个', executorKey: 'douyin_mashida_skin', priority: 900 },
|
||||
],
|
||||
}),
|
||||
})
|
||||
|
||||
assert.equal(result.selectedExecutorKey, 'affiliate_dash')
|
||||
assert.equal(result.matchedRule?.productName, '荣耀套装')
|
||||
})
|
||||
|
||||
@@ -9,6 +9,15 @@ import { FULFILLMENT_EXECUTOR_KEYS } from './executors/types.js'
|
||||
|
||||
export type FulfillmentRoutingRuleMatchType = 'exact' | 'contains'
|
||||
|
||||
/**
|
||||
* 规则匹配维度:
|
||||
* - `product_name`:按**商品名**匹配(历史规则,语义完全不变);
|
||||
* - `internal_sku`:按**内部 SKU**匹配(如抖店 `sku_order_list[].code` = 「幸运币2个」)。
|
||||
* 内部 SKU 用 `normalizeInternalSkuMatchKey` 归一(NFKC + 去空白 + 小写),
|
||||
* 这样全角数字/多余空格也能命中权威映射表里的写法。
|
||||
*/
|
||||
export type FulfillmentRoutingRuleMatchField = 'product_name' | 'internal_sku'
|
||||
|
||||
export type FulfillmentRoutingExecutorConfig = {
|
||||
enabled: boolean
|
||||
}
|
||||
@@ -16,8 +25,11 @@ export type FulfillmentRoutingExecutorConfig = {
|
||||
export type FulfillmentRoutingRule = {
|
||||
id: string
|
||||
enabled: boolean
|
||||
matchField: FulfillmentRoutingRuleMatchField
|
||||
productName: string
|
||||
normalizedProductName: string
|
||||
internalSku: string
|
||||
normalizedInternalSku: string
|
||||
matchType: FulfillmentRoutingRuleMatchType
|
||||
executorKey: string
|
||||
priority: number
|
||||
@@ -63,6 +75,7 @@ const FULFILLMENT_ROUTING_CONFIG_FILE_PATH = path.join(
|
||||
|
||||
const ROUTABLE_EXECUTOR_KEYS: string[] = [
|
||||
FULFILLMENT_EXECUTOR_KEYS.AFFILIATE_DASH,
|
||||
FULFILLMENT_EXECUTOR_KEYS.DOUYIN_MASHIDA_SKIN,
|
||||
FULFILLMENT_EXECUTOR_KEYS.MANUAL_DISPATCH,
|
||||
]
|
||||
|
||||
@@ -131,11 +144,13 @@ export function normalizeFulfillmentRoutingConfig(rawValue: unknown): Fulfillmen
|
||||
|
||||
export function resolveFulfillmentRoute({
|
||||
productName,
|
||||
internalSku = '',
|
||||
candidates,
|
||||
config = getFulfillmentRoutingConfig(),
|
||||
preferredExecutorKey = '',
|
||||
}: {
|
||||
productName: unknown
|
||||
internalSku?: unknown
|
||||
candidates: FulfillmentRoutingCandidate[]
|
||||
config?: FulfillmentRoutingConfig
|
||||
preferredExecutorKey?: string
|
||||
@@ -167,7 +182,10 @@ export function resolveFulfillmentRoute({
|
||||
}
|
||||
}
|
||||
|
||||
const matchedRule = findMatchedRoutingRule(productName, normalizedConfig.rules)
|
||||
// 匹配顺序刻意保持:先按商品名(历史规则,行为完全不变),再按内部 SKU(新增维度)。
|
||||
const matchedRule =
|
||||
findMatchedRoutingRule(productName, normalizedConfig.rules) ||
|
||||
findMatchedInternalSkuRoutingRule(internalSku, normalizedConfig.rules)
|
||||
if (matchedRule) {
|
||||
const selected = resolveExecutorSelection({
|
||||
executorKey: matchedRule.executorKey,
|
||||
@@ -381,7 +399,10 @@ function findMatchedRoutingRule(productName: unknown, rules: FulfillmentRoutingR
|
||||
|
||||
return (
|
||||
rules.find((rule) => {
|
||||
if (rule.enabled === false || !rule.normalizedProductName) {
|
||||
if (rule.enabled === false || rule.matchField !== 'product_name') {
|
||||
return false
|
||||
}
|
||||
if (!rule.normalizedProductName) {
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -394,13 +415,87 @@ function findMatchedRoutingRule(productName: unknown, rules: FulfillmentRoutingR
|
||||
)
|
||||
}
|
||||
|
||||
/** 内部 SKU 维度的规则匹配:与商品名规则同样的 exact/contains 语义。 */
|
||||
function findMatchedInternalSkuRoutingRule(internalSku: unknown, rules: FulfillmentRoutingRule[]) {
|
||||
const normalizedInternalSku = normalizeInternalSkuMatchKey(internalSku)
|
||||
if (!normalizedInternalSku) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
rules.find((rule) => {
|
||||
if (rule.enabled === false || rule.matchField !== 'internal_sku') {
|
||||
return false
|
||||
}
|
||||
if (!rule.normalizedInternalSku) {
|
||||
return false
|
||||
}
|
||||
|
||||
if (rule.matchType === 'contains') {
|
||||
return normalizedInternalSku.includes(rule.normalizedInternalSku)
|
||||
}
|
||||
|
||||
return normalizedInternalSku === rule.normalizedInternalSku
|
||||
}) || null
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 内部 SKU 归一化:NFKC(全角→半角)→ 去所有空白 → 小写。
|
||||
* 与权威映射表 `AFFILIATE_DASH_SKU_MAPPING` 的查询归一化保持同一套语义。
|
||||
*/
|
||||
export function normalizeInternalSkuMatchKey(value: unknown): string {
|
||||
return String(value || '')
|
||||
.normalize('NFKC')
|
||||
.replace(/\s+/g, '')
|
||||
.toLowerCase()
|
||||
}
|
||||
|
||||
/**
|
||||
* 规则归一化。
|
||||
*
|
||||
* 兼容旧配置:没有 `matchField` / `internalSku` 的规则一律视为**商品名**规则,行为与之前完全一致
|
||||
* (id、归一化键、matchType、priority 的算法都没动)。
|
||||
* 新维度通过 `internalSku`(或显式 `matchField: 'internal_sku'`)声明。
|
||||
*/
|
||||
function normalizeFulfillmentRoutingRule(rawValue: unknown): FulfillmentRoutingRule | null {
|
||||
const source = isPlainObject(rawValue) ? rawValue : {}
|
||||
const matchField = resolveRuleMatchField(source)
|
||||
const executorKey = normalizeExecutorKey(source.executorKey)
|
||||
|
||||
if (matchField === 'internal_sku') {
|
||||
const internalSku = String(source.internalSku ?? source.sku ?? '').trim()
|
||||
const normalizedInternalSku =
|
||||
normalizeInternalSkuMatchKey(source.normalizedInternalSku) ||
|
||||
normalizeInternalSkuMatchKey(internalSku)
|
||||
|
||||
if (!internalSku || !normalizedInternalSku || !executorKey) {
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
id:
|
||||
String(source.id || `${normalizedInternalSku}:${executorKey}`).trim() ||
|
||||
`${normalizedInternalSku}:${executorKey}`,
|
||||
enabled: source.enabled !== false,
|
||||
matchField: 'internal_sku',
|
||||
// 展示与诊断仍走 productName 字段(值为内部 SKU);normalizedProductName 留空,
|
||||
// 保证商品名匹配器永远不会把它当成商品名规则命中。
|
||||
productName: internalSku,
|
||||
normalizedProductName: '',
|
||||
internalSku,
|
||||
normalizedInternalSku,
|
||||
matchType: source.matchType === 'contains' ? 'contains' : 'exact',
|
||||
executorKey,
|
||||
priority: normalizeInteger(source.priority, 100),
|
||||
notes: String(source.notes || '').trim(),
|
||||
}
|
||||
}
|
||||
|
||||
const productName = String(source.productName || source.name || '').trim()
|
||||
const normalizedProductName =
|
||||
normalizeProductMatchName(source.normalizedProductName) ||
|
||||
normalizeProductMatchName(productName)
|
||||
const executorKey = normalizeExecutorKey(source.executorKey)
|
||||
|
||||
if (!productName || !normalizedProductName || !executorKey) {
|
||||
return null
|
||||
@@ -411,8 +506,11 @@ function normalizeFulfillmentRoutingRule(rawValue: unknown): FulfillmentRoutingR
|
||||
String(source.id || `${normalizedProductName}:${executorKey}`).trim() ||
|
||||
`${normalizedProductName}:${executorKey}`,
|
||||
enabled: source.enabled !== false,
|
||||
matchField: 'product_name',
|
||||
productName,
|
||||
normalizedProductName,
|
||||
internalSku: '',
|
||||
normalizedInternalSku: '',
|
||||
matchType: source.matchType === 'contains' ? 'contains' : 'exact',
|
||||
executorKey,
|
||||
priority: normalizeInteger(source.priority, 100),
|
||||
@@ -420,6 +518,16 @@ function normalizeFulfillmentRoutingRule(rawValue: unknown): FulfillmentRoutingR
|
||||
}
|
||||
}
|
||||
|
||||
function resolveRuleMatchField(source: JsonObject): FulfillmentRoutingRuleMatchField {
|
||||
if (String(source.matchField || '').trim() === 'internal_sku') {
|
||||
return 'internal_sku'
|
||||
}
|
||||
|
||||
const hasProductName = Boolean(String(source.productName || source.name || '').trim())
|
||||
const hasInternalSku = Boolean(String(source.internalSku ?? source.sku ?? '').trim())
|
||||
return !hasProductName && hasInternalSku ? 'internal_sku' : 'product_name'
|
||||
}
|
||||
|
||||
function normalizeRoutingCandidates(candidates: FulfillmentRoutingCandidate[]) {
|
||||
const result = new Map<string, FulfillmentRoutingCandidate>()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user