feat(dev-mock): 新增斗鱼履约 Mock 与分页控制台

- 增加斗鱼客户履约 Mock 订单与角色绑定联调能力
- 重构开发 Mock 控制台为可切换分页界面
- 补充斗鱼履约 Mock 集成测试
This commit is contained in:
yml
2026-11-18 11:00:28 +08:00
parent 4abc8b39d0
commit d0ec21ce16
6 changed files with 1076 additions and 410 deletions
+22
View File
@@ -3,6 +3,7 @@ import { Router } from 'express'
import {
buildOpen91QueryMock,
createAffiliateDashMockClaim,
createDouyuFulfillmentMock,
createKuaishouIndustryVoucherMockData,
createSemiAutoIntegrationMock,
createSemiAutoMock,
@@ -77,6 +78,27 @@ router.post(
}),
)
router.post(
'/dev-mock/douyu-fulfillment',
createJsonHandler((req) => createDouyuFulfillmentMock(req.body || {}), {
successMessage: '斗鱼直播账号履约测试单已生成',
errorMessage: '生成斗鱼直播账号履约测试单失败',
scope: '[admin/dev-mock/douyu-fulfillment]',
audit: (_req, data) => ({
action: 'dev_mock_create_douyu_fulfillment',
targetType: 'dev_mock',
targetId: String((data as { orderNo?: string })?.orderNo || ''),
data: {
platform: 'douyu',
pipeline: 'order_service',
orderNo: (data as { orderNo?: string })?.orderNo,
orderItemId: (data as { orderItemId?: number })?.orderItemId,
skuKey: (data as { skuKey?: string })?.skuKey,
},
}),
}),
)
router.post(
'/dev-mock/semi-auto',
createJsonHandler((req) => createSemiAutoMock(req.body || {}), {
@@ -93,6 +93,20 @@ export type DevSemiAutoIntegrationResult = DevMockSemiAutoResult & {
mappingId: number
}
export type DevDouyuFulfillmentMockResult = {
platform: 'douyu'
pipeline: 'order_service'
orderId: number
orderNo: string
orderItemId: number
fulfillmentId: number
configId: number
mappingId: number
skuKey: string
adminPath: string
tips: string[]
}
export function getDevMockStatus() {
const enabled = isDevMockEnabled()
return {
@@ -113,6 +127,12 @@ export function getDevMockStatus() {
'创建人工渠道半自动测试单;可选择仅 Mock 订单,登录、绑定和票据注入走真实 Connector',
steps: ['create_order', 'login', 'binding', 'browser_ticket', 'complete'],
},
{
key: 'douyu_fulfillment',
name: '斗鱼直播账号履约',
description: '创建正式人工渠道测试单,供 live-hub 直播账号履约工作台读取',
steps: ['create_order', 'sync_livehub', 'map_commodity'],
},
]
: [],
defaultUid: '10001',
@@ -531,86 +551,59 @@ export async function createSemiAutoMock(
}
}
/**
* 真实履约链路集成测试单。
*
* 订单必须通过正式 upsertOrderFromSource 入库,再走 SKU 映射、渠道判定和
* Carrier 补偿;不直接写 order/order_item/fulfillment。
*/
export async function createSemiAutoIntegrationMock(
input: {
platform?: unknown
orderNo?: unknown
skuName?: unknown
quantity?: unknown
pageTitle?: unknown
browserTargetUrl?: unknown
connectorMode?: unknown
} = {},
): Promise<DevSemiAutoIntegrationResult> {
assertDevMockEnabled()
const platform = normalizeMockSemiAutoPlatform(input.platform)
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
const orderNo = String(
input.orderNo || `${platform === 'weibo' ? 'INTWB' : 'INTSA'}${suffix}`,
).trim()
const skuKey = normalizeMockSemiAutoSku(
input.skuName || `${platform === 'weibo' ? '微博' : '虎牙'}真实链路测试-${suffix}`,
platform,
)
const quantity = normalizeMockSemiAutoQuantity(input.quantity)
const connectorMode =
platform === 'weibo' ? 'embedded' : normalizeMockSemiAutoConnectorMode(input.connectorMode)
const provider = 'dev_integration'
const sourcePlatform = 'internal_test'
const shopId = 'dev-integration-shop'
const externalSkuCode = `INTEGRATION-${suffix}`
const pageTitle = String(
input.pageTitle || (platform === 'weibo' ? '微博账号登录授权' : '虎牙账号登录授权'),
)
.trim()
.slice(0, 60)
const browserTargetUrl = String(
input.browserTargetUrl ||
(platform === 'weibo' ? 'https://weibo.com/' : 'https://www.huya.com/'),
)
.trim()
.slice(0, 1000)
const existing = await findOrderByPlatformOrderId({
provider,
platform: sourcePlatform,
shopId,
platformOrderId: orderNo,
})
if (existing) {
throw createHttpError(`订单号已存在:${orderNo},请换一个或留空自动生成`, {
statusCode: 409,
errorCode: 'dev_integration_order_exists',
})
type PersistManualIntegrationOrderInput = {
orderNo: string
skuKey: string
externalSkuCode: string
provider: string
sourcePlatform: string
shopId: string
shopName: string
buyerId: string
buyerName: string
sourceTag: string
rawPayload: Record<string, unknown>
itemSnapshot: Record<string, unknown>
configNote: string
quantity?: number
semiAuto?: {
platform: 'huya' | 'weibo'
config: Record<string, unknown>
}
}
type PersistManualIntegrationOrderResult = {
orderId: number
orderNo: string
orderItemId: number
fulfillmentId: number
configId: number
mappingId: number
skuKey: string
}
/**
* 通过正式订单入口创建人工渠道测试单。
*
* 是否生成旧半自动任务由 semi_auto_enabled 决定,调用方无需直接写订单、
* 履约或任务表。
*/
async function persistManualIntegrationOrder(
input: PersistManualIntegrationOrderInput,
): Promise<PersistManualIntegrationOrderResult> {
const quantity = normalizeMockSemiAutoQuantity(input.quantity)
const config = await saveManualFulfillmentConfig({
skuKey,
skuKey: input.skuKey,
enabled: true,
note: '开发集成测试:真实订单履约链路',
note: input.configNote,
channels: [{ platformKey: 'fund_cash', creditQuantity: 100, enabled: true }],
semiAutoEnabled: true,
semiAutoPlatform: platform,
semiAutoConfig: {
pageTitle,
pageDescription: '真实入库链路测试订单:登录与 CK 获取使用当前 Connector。',
loginInstructions: '请使用本人账号完成登录授权,客服后续人工处理。',
loginMethods: ['sms', 'qr'],
browserTargets: [
{
key: platform,
label: platform === 'weibo' ? '微博' : '虎牙',
url: browserTargetUrl,
},
],
},
semiAutoEnabled: Boolean(input.semiAuto),
...(input.semiAuto
? {
semiAutoPlatform: input.semiAuto.platform,
semiAutoConfig: input.semiAuto.config,
}
: {}),
})
const configId = Number(config.id || 0)
if (!configId) {
@@ -620,53 +613,47 @@ export async function createSemiAutoIntegrationMock(
})
}
const mappingId = await upsertInternalSkuMapping({
provider,
shopId,
provider: input.provider,
shopId: input.shopId,
matchType: 'sku_code',
matchValue: externalSkuCode,
internalSku: skuKey,
matchValue: input.externalSkuCode,
internalSku: input.skuKey,
priority: 1000,
source: 'dev_integration',
note: `订单 ${orderNo}`,
source: input.sourceTag,
note: `订单 ${input.orderNo}`,
})
const now = nowIso()
const upserted = await upsertOrderFromSource(
{
provider,
platform: sourcePlatform,
shopId,
shopName: '半自动真实链路测试店',
platformOrderId: orderNo,
provider: input.provider,
platform: input.sourcePlatform,
shopId: input.shopId,
shopName: input.shopName,
platformOrderId: input.orderNo,
orderStatus: 'paid',
payStatus: 'paid',
buyerId: `integration-buyer-${suffix}`,
buyerName: '集成测试客户',
buyerId: input.buyerId,
buyerName: input.buyerName,
receiverContact: '',
totalAmount: 100 * quantity,
currency: 'CNY',
rawPayload: {
source: 'dev_integration',
orderNo,
skuKey,
platform,
...input.rawPayload,
createdAt: now,
},
paidAt: now,
items: [
{
quantity,
skuCode: externalSkuCode,
skuName: skuKey,
skuCode: input.externalSkuCode,
skuName: input.skuKey,
spec: {},
snapshot: {
source: 'dev_integration',
semiAuto: { platform },
},
snapshot: input.itemSnapshot,
},
],
},
{ sourceLabel: 'dev_semi_auto_integration' },
{ sourceLabel: input.sourceTag },
)
if (upserted.ignored || !upserted.order) {
throw createHttpError(upserted.ignoreReason || '真实链路订单入库失败', {
@@ -727,38 +714,167 @@ export async function createSemiAutoIntegrationMock(
expected: { status: 'assigned', channel: 'manual' },
onlyWhenConfigNull: true,
})
await ensureSemiAutoTasksForOrderItems([orderItemId])
const resolved = await query<{
fulfillment_id: number
fulfillment_channel: string
fulfillment_status: string
task_id: number
}>(
`
SELECT
f.id AS fulfillment_id,
f.channel AS fulfillment_channel,
f.status AS fulfillment_status,
f.status AS fulfillment_status
FROM fulfillments f
WHERE f.order_item_id = $1
LIMIT 1
`,
[orderItemId],
)
const fulfillment = resolved.rows[0]
if (
!fulfillment ||
fulfillment.fulfillment_channel !== 'manual' ||
fulfillment.fulfillment_status !== 'assigned'
) {
throw createHttpError(
`真实链路未生成人工履约:channel=${fulfillment?.fulfillment_channel || ''}, status=${fulfillment?.fulfillment_status || ''}`,
{ statusCode: 500, errorCode: 'dev_integration_manual_fulfillment_failed' },
)
}
return {
orderId: Number(upserted.order.id),
orderNo: input.orderNo,
orderItemId,
fulfillmentId: Number(fulfillment.fulfillment_id),
configId,
mappingId,
skuKey: input.skuKey,
}
}
/**
* 真实履约链路集成测试单。
*
* 订单必须通过正式 upsertOrderFromSource 入库,再走 SKU 映射、渠道判定和
* Carrier 补偿;不直接写 order/order_item/fulfillment。
*/
export async function createSemiAutoIntegrationMock(
input: {
platform?: unknown
orderNo?: unknown
skuName?: unknown
quantity?: unknown
pageTitle?: unknown
browserTargetUrl?: unknown
connectorMode?: unknown
} = {},
): Promise<DevSemiAutoIntegrationResult> {
assertDevMockEnabled()
const platform = normalizeMockSemiAutoPlatform(input.platform)
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
const orderNo = String(
input.orderNo || `${platform === 'weibo' ? 'INTWB' : 'INTSA'}${suffix}`,
).trim()
const skuKey = normalizeMockSemiAutoSku(
input.skuName || `${platform === 'weibo' ? '微博' : '虎牙'}真实链路测试-${suffix}`,
platform,
)
const quantity = normalizeMockSemiAutoQuantity(input.quantity)
const connectorMode =
platform === 'weibo' ? 'embedded' : normalizeMockSemiAutoConnectorMode(input.connectorMode)
const provider = 'dev_integration'
const sourcePlatform = 'internal_test'
const shopId = 'dev-integration-shop'
const externalSkuCode = `INTEGRATION-${suffix}`
const pageTitle = String(
input.pageTitle || (platform === 'weibo' ? '微博账号登录授权' : '虎牙账号登录授权'),
)
.trim()
.slice(0, 60)
const browserTargetUrl = String(
input.browserTargetUrl ||
(platform === 'weibo' ? 'https://weibo.com/' : 'https://www.huya.com/'),
)
.trim()
.slice(0, 1000)
const existing = await findOrderByPlatformOrderId({
provider,
platform: sourcePlatform,
shopId,
platformOrderId: orderNo,
})
if (existing) {
throw createHttpError(`订单号已存在:${orderNo},请换一个或留空自动生成`, {
statusCode: 409,
errorCode: 'dev_integration_order_exists',
})
}
const persisted = await persistManualIntegrationOrder({
orderNo,
skuKey,
externalSkuCode,
provider,
sourcePlatform,
shopId,
shopName: '半自动真实链路测试店',
buyerId: `integration-buyer-${suffix}`,
buyerName: '集成测试客户',
sourceTag: 'dev_semi_auto_integration',
rawPayload: {
source: 'dev_integration',
orderNo,
skuKey,
platform,
},
itemSnapshot: {
source: 'dev_integration',
semiAuto: { platform },
},
configNote: '开发集成测试:真实订单履约链路',
quantity,
semiAuto: {
platform,
config: {
pageTitle,
pageDescription: '真实入库链路测试订单:登录与 CK 获取使用当前 Connector。',
loginInstructions: '请使用本人账号完成登录授权,客服后续人工处理。',
loginMethods: ['sms', 'qr'],
browserTargets: [
{
key: platform,
label: platform === 'weibo' ? '微博' : '虎牙',
url: browserTargetUrl,
},
],
},
},
})
await ensureSemiAutoTasksForOrderItems([persisted.orderItemId])
const resolved = await query<{
task_id: number
}>(
`
SELECT
task.id AS task_id
FROM fulfillments f
LEFT JOIN semi_auto_tasks task ON task.order_item_id = f.order_item_id
WHERE f.order_item_id = $1
LIMIT 1
`,
[orderItemId],
[persisted.orderItemId],
)
const row = resolved.rows[0]
if (
!row ||
row.fulfillment_channel !== 'manual' ||
row.fulfillment_status !== 'assigned' ||
!Number(row.task_id)
) {
throw createHttpError(
`真实链路未生成半自动任务:channel=${row?.fulfillment_channel || ''}, status=${row?.fulfillment_status || ''}, task=${row?.task_id || 0}`,
{ statusCode: 500, errorCode: 'dev_integration_semi_auto_task_failed' },
)
if (!row || !Number(row.task_id)) {
throw createHttpError('真实链路未生成半自动任务', {
statusCode: 500,
errorCode: 'dev_integration_semi_auto_task_failed',
})
}
await query('UPDATE semi_auto_tasks SET connector_mode = $2, updated_at = NOW() WHERE id = $1', [
@@ -771,17 +887,17 @@ export async function createSemiAutoIntegrationMock(
platform: 'semi_auto',
semiAutoPlatform: platform,
pipeline: 'order_service',
orderId: Number(upserted.order.id),
orderNo,
orderItemId,
fulfillmentId: Number(row.fulfillment_id),
configId,
orderId: persisted.orderId,
orderNo: persisted.orderNo,
orderItemId: persisted.orderItemId,
fulfillmentId: persisted.fulfillmentId,
configId: persisted.configId,
taskId: Number(row.task_id),
skuKey,
skuKey: persisted.skuKey,
connectorMode,
connectorConfigured,
mappingId,
customerPath: buildMockCustomerPath(platform, orderNo),
mappingId: persisted.mappingId,
customerPath: buildMockCustomerPath(platform, persisted.orderNo),
adminPath: `/admin/semi-auto-tasks?keyword=${encodeURIComponent(orderNo)}`,
tips: [
'订单通过正式 upsertOrderFromSource 入库。',
@@ -794,6 +910,109 @@ export async function createSemiAutoIntegrationMock(
}
}
/**
* 斗鱼直播账号履约专用测试单。
*
* 只生成 live-hub 工作台需要的正式人工履约数据,不启用 order_site 的
* huya/weibo 半自动任务。
*/
export async function createDouyuFulfillmentMock(
input: {
orderNo?: unknown
skuName?: unknown
} = {},
): Promise<DevDouyuFulfillmentMockResult> {
assertDevMockEnabled()
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
const orderNo = String(input.orderNo || `LIVEHUBDOUYU${suffix}`).trim()
const requestedSkuKey = String(input.skuName || `斗鱼精英宝典联调-${suffix}`)
.trim()
.slice(0, 48)
if (!requestedSkuKey || !containsCjk(requestedSkuKey)) {
throw createHttpError('内部 SKU 名称必须包含中文', {
statusCode: 400,
errorCode: 'dev_douyu_fulfillment_sku_invalid',
})
}
const provider = 'livehub_douyu_dev'
const sourcePlatform = 'internal_test'
const shopId = 'livehub-douyu-dev-shop'
const existing = await findOrderByPlatformOrderId({
provider,
platform: sourcePlatform,
shopId,
platformOrderId: orderNo,
})
if (existing) {
throw createHttpError(`订单号已存在:${orderNo},请换一个或留空自动生成`, {
statusCode: 409,
errorCode: 'dev_douyu_fulfillment_order_exists',
})
}
const persisted = await persistManualIntegrationOrder({
orderNo,
skuKey: requestedSkuKey,
externalSkuCode: `DOUYU-FULFILLMENT-${suffix}`,
provider,
sourcePlatform,
shopId,
shopName: '直播账号履约联调店',
buyerId: `douyu-fulfillment-buyer-${suffix}`,
buyerName: '斗鱼履约联调客户',
sourceTag: 'dev_douyu_fulfillment',
rawPayload: {
source: 'dev_douyu_fulfillment',
orderNo,
skuKey: requestedSkuKey,
targetPlatform: 'douyu',
},
itemSnapshot: {
source: 'dev_douyu_fulfillment',
targetPlatform: 'douyu',
scope: 'elite',
},
configNote: '开发 Mock:斗鱼直播账号履约',
})
const verification = await query<{
semi_auto_task_count: number
semi_auto_enabled: boolean
}>(
`
SELECT
COUNT(task.id)::int AS semi_auto_task_count,
BOOL_OR(cfg.semi_auto_enabled) AS semi_auto_enabled
FROM fulfillments f
JOIN manual_fulfillment_configs cfg ON cfg.id = f.fulfillment_config_id
LEFT JOIN semi_auto_tasks task ON task.order_item_id = f.order_item_id
WHERE f.id = $1
`,
[persisted.fulfillmentId],
)
const row = verification.rows[0]
if (Number(row?.semi_auto_task_count || 0) > 0 || row?.semi_auto_enabled === true) {
throw createHttpError('斗鱼专用 Mock 不应生成半自动任务', {
statusCode: 500,
errorCode: 'dev_douyu_fulfillment_semi_auto_conflict',
})
}
return {
platform: 'douyu',
pipeline: 'order_service',
...persisted,
adminPath: `/admin/orders/${persisted.orderId}`,
tips: [
'订单已通过 upsertOrderFromSource 正式入库。',
'履约渠道为 manual,状态为 assigned,且不会生成 huya/weibo 半自动任务。',
`在 live-hub 直播账号履约工作台同步后,用内部 SKU「${persisted.skuKey}」配置斗鱼商品映射。`,
],
}
}
function normalizeMockSemiAutoPlatform(value: unknown): 'huya' | 'weibo' {
return String(value || '')
.trim()
@@ -766,3 +766,93 @@ test(
}
},
)
test(
'斗鱼直播账号履约 Mock 只生成正式人工履约,不生成半自动任务',
{ skip: !TEST_DATABASE_URL ? '未设置 SEMI_AUTO_TASK_TEST_DATABASE_URL' : false },
async () => {
process.env.DATABASE_URL = TEST_DATABASE_URL
process.env.ENABLE_DEV_MOCK = '1'
const { closeDb, query, withTransaction } = await import('../../db/client.js')
const { createDouyuFulfillmentMock } = await import('../dev-mock/dev-mock-service.js')
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
const orderNo = `IT-DOUYU-FULFILLMENT-${suffix}`
const skuKey = `斗鱼精英宝典联调-${suffix}`
let orderId = 0
let configId = 0
let mappingId = 0
try {
const result = await createDouyuFulfillmentMock({
orderNo,
skuName: skuKey,
})
orderId = result.orderId
configId = result.configId
mappingId = result.mappingId
assert.equal(result.platform, 'douyu')
assert.equal(result.pipeline, 'order_service')
assert.equal(result.orderNo, orderNo)
assert.equal(result.skuKey, skuKey)
assert.ok(result.orderItemId > 0)
assert.ok(result.fulfillmentId > 0)
const stored = await query<{
channel: string
fulfillment_status: string
fulfillment_config_id: number
semi_auto_enabled: boolean
semi_auto_task_count: number
internal_sku: string
}>(
`
SELECT
f.channel,
f.status AS fulfillment_status,
f.fulfillment_config_id,
cfg.semi_auto_enabled,
(
SELECT COUNT(*)::int
FROM semi_auto_tasks task
WHERE task.order_item_id = f.order_item_id
) AS semi_auto_task_count,
resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code) AS internal_sku
FROM fulfillments f
JOIN order_items oi ON oi.id = f.order_item_id
JOIN manual_fulfillment_configs cfg ON cfg.id = f.fulfillment_config_id
WHERE f.id = $1
`,
[result.fulfillmentId],
)
assert.equal(stored.rows[0]?.channel, 'manual')
assert.equal(stored.rows[0]?.fulfillment_status, 'assigned')
assert.equal(Number(stored.rows[0]?.fulfillment_config_id), result.configId)
assert.equal(stored.rows[0]?.semi_auto_enabled, false)
assert.equal(Number(stored.rows[0]?.semi_auto_task_count), 0)
assert.equal(stored.rows[0]?.internal_sku, skuKey)
const mapping = await query<{ internal_sku: string }>(
'SELECT internal_sku FROM internal_sku_mappings WHERE id = $1',
[result.mappingId],
)
assert.equal(mapping.rows[0]?.internal_sku, skuKey)
} finally {
await withTransaction(async (client) => {
await client.query("SET LOCAL session_replication_role = 'replica'")
if (configId > 0) {
await client.query('DELETE FROM manual_fulfillment_configs WHERE id = $1', [configId])
}
if (orderId > 0) {
await client.query('DELETE FROM order_source_snapshots WHERE order_id = $1', [orderId])
await client.query('DELETE FROM orders WHERE id = $1', [orderId])
}
if (mappingId > 0) {
await client.query('DELETE FROM internal_sku_mappings WHERE id = $1', [mappingId])
}
})
delete process.env.ENABLE_DEV_MOCK
await closeDb()
}
},
)