merge(douyu): 合入客户领取与直播账号履约
- 合入斗鱼客户资料收集、角色绑定和半自动履约工作台 - 合入事务 Outbox、签名 Webhook 与低频对账链路 - 合入双角色识别、绑定重置、取消释放账号和已分配状态修复 - 将斗鱼履约数据库变更合并为单个 171 迁移文件 - 更新拆分后的客户样式测试入口并适配最新 main 客户页样式
This commit is contained in:
@@ -115,6 +115,7 @@ type ManualSkuRow = {
|
||||
config_semi_auto_enabled: boolean | null
|
||||
config_semi_auto_platform: string | null
|
||||
config_semi_auto_config_json: unknown
|
||||
config_douyu_fulfillment_enabled: boolean | null
|
||||
}
|
||||
|
||||
type ManualChannelConfig = {
|
||||
@@ -353,7 +354,8 @@ export async function listManualSkus(input: Record<string, unknown> = {}) {
|
||||
cfg.channels_json AS config_channels_json,
|
||||
cfg.semi_auto_enabled AS config_semi_auto_enabled,
|
||||
cfg.semi_auto_platform AS config_semi_auto_platform,
|
||||
cfg.semi_auto_config_json AS config_semi_auto_config_json
|
||||
cfg.semi_auto_config_json AS config_semi_auto_config_json,
|
||||
cfg.douyu_fulfillment_enabled AS config_douyu_fulfillment_enabled
|
||||
FROM product_catalog p
|
||||
JOIN internal_skus product_sku ON product_sku.id = p.internal_sku_id
|
||||
LEFT JOIN LATERAL (
|
||||
@@ -468,6 +470,8 @@ export async function saveManualFulfillmentConfig(payload: JsonObject) {
|
||||
const enabled = payload.enabled === false ? false : true
|
||||
const note = optionalText(payload.note, 300)
|
||||
const semiAuto = normalizeSemiAutoConfig(payload)
|
||||
const douyuFulfillmentEnabled =
|
||||
payload.douyuFulfillmentEnabled === true || payload.douyu_fulfillment_enabled === true
|
||||
|
||||
// 消耗积分为 0 = 成本不固定,客服确认履约时手填。
|
||||
const costMode = primaryChannel.costMode
|
||||
@@ -560,7 +564,8 @@ export async function saveManualFulfillmentConfig(payload: JsonObject) {
|
||||
semi_auto_enabled = $10,
|
||||
semi_auto_platform = $11,
|
||||
semi_auto_config_json = $12::jsonb,
|
||||
updated_at = $13
|
||||
douyu_fulfillment_enabled = $13,
|
||||
updated_at = $14
|
||||
WHERE id = $1
|
||||
RETURNING *`,
|
||||
[
|
||||
@@ -576,6 +581,7 @@ export async function saveManualFulfillmentConfig(payload: JsonObject) {
|
||||
semiAuto.enabled,
|
||||
semiAuto.platform,
|
||||
JSON.stringify(semiAuto.config),
|
||||
douyuFulfillmentEnabled,
|
||||
now,
|
||||
],
|
||||
)
|
||||
@@ -584,10 +590,11 @@ export async function saveManualFulfillmentConfig(payload: JsonObject) {
|
||||
sku_key, canonical_product_id, platform_key, credit_quantity,
|
||||
cost_mode, enabled, note, channels_json,
|
||||
semi_auto_enabled, semi_auto_platform, semi_auto_config_json,
|
||||
douyu_fulfillment_enabled,
|
||||
created_at, updated_at
|
||||
) VALUES (
|
||||
$1, $2, $3, $4, $5, $6, $7, $8::jsonb,
|
||||
$9, $10, $11::jsonb, $12, $12
|
||||
$9, $10, $11::jsonb, $12, $13, $13
|
||||
)
|
||||
RETURNING *`,
|
||||
[
|
||||
@@ -602,6 +609,7 @@ export async function saveManualFulfillmentConfig(payload: JsonObject) {
|
||||
semiAuto.enabled,
|
||||
semiAuto.platform,
|
||||
JSON.stringify(semiAuto.config),
|
||||
douyuFulfillmentEnabled,
|
||||
now,
|
||||
],
|
||||
)
|
||||
@@ -1077,6 +1085,7 @@ export async function getManualFulfillmentConfig(skuKey: string) {
|
||||
semi_auto_enabled: boolean
|
||||
semi_auto_platform: string
|
||||
semi_auto_config_json: unknown
|
||||
douyu_fulfillment_enabled: boolean
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}>(
|
||||
@@ -1208,6 +1217,7 @@ function mapManualSku(row: ManualSkuRow, unitPrices: Record<ManualPlatformKey, n
|
||||
semiAutoEnabled: row.config_semi_auto_enabled === true,
|
||||
semiAutoPlatform: String(row.config_semi_auto_platform || ''),
|
||||
semiAutoConfig: normalizeStoredSemiAutoConfig(row.config_semi_auto_config_json),
|
||||
douyuFulfillmentEnabled: row.config_douyu_fulfillment_enabled === true,
|
||||
channels: mapConfiguredChannels(channels, unitPrices),
|
||||
}
|
||||
: null,
|
||||
@@ -1228,6 +1238,7 @@ function mapManualConfig(
|
||||
semi_auto_enabled: boolean
|
||||
semi_auto_platform: string
|
||||
semi_auto_config_json: unknown
|
||||
douyu_fulfillment_enabled: boolean
|
||||
created_at: string
|
||||
updated_at: string
|
||||
},
|
||||
@@ -1251,6 +1262,7 @@ function mapManualConfig(
|
||||
semiAutoEnabled: row.semi_auto_enabled === true,
|
||||
semiAutoPlatform: String(row.semi_auto_platform || ''),
|
||||
semiAutoConfig: normalizeStoredSemiAutoConfig(row.semi_auto_config_json),
|
||||
douyuFulfillmentEnabled: row.douyu_fulfillment_enabled === true,
|
||||
channels: mapConfiguredChannels(channels, unitPrices),
|
||||
note: row.note || '',
|
||||
createdAt: row.created_at,
|
||||
|
||||
@@ -93,6 +93,21 @@ 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
|
||||
customerPath: string
|
||||
adminPath: string
|
||||
tips: string[]
|
||||
}
|
||||
|
||||
export function getDevMockStatus() {
|
||||
const enabled = isDevMockEnabled()
|
||||
return {
|
||||
@@ -113,6 +128,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 +552,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 +614,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 +715,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 +888,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 +911,116 @@ 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:斗鱼直播账号履约',
|
||||
})
|
||||
await query(
|
||||
`UPDATE manual_fulfillment_configs
|
||||
SET douyu_fulfillment_enabled = TRUE, updated_at = NOW()
|
||||
WHERE id = $1`,
|
||||
[persisted.configId],
|
||||
)
|
||||
|
||||
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,
|
||||
customerPath: `/coll/d/${encodeURIComponent(persisted.orderNo)}`,
|
||||
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()
|
||||
|
||||
@@ -0,0 +1,871 @@
|
||||
import type { PoolClient } from 'pg'
|
||||
|
||||
import { query, withTransaction } from '../../db/client.js'
|
||||
import { publishRealtimeEvent } from '../realtime/realtime-event-service.js'
|
||||
import { nowIso } from '../../utils/time.js'
|
||||
import { createHttpError } from '../../utils/http.js'
|
||||
import { logWarn } from '../../utils/logger.js'
|
||||
|
||||
type DouyuTaskRow = {
|
||||
id: number
|
||||
order_id: number
|
||||
order_item_id: number
|
||||
fulfillment_id: number | null
|
||||
manual_fulfillment_config_id: number | null
|
||||
live_session_id: number | null
|
||||
status: string
|
||||
customer_role_name: string
|
||||
customer_platform: string
|
||||
customer_system: string
|
||||
binding_phase: string
|
||||
live_execution_status: string
|
||||
live_binding_status: string
|
||||
issue_code: string
|
||||
last_error: string
|
||||
bound_role_name: string
|
||||
bound_area_name: string
|
||||
bound_plat_name: string
|
||||
customer_link_opened_at: string | null
|
||||
binding_started_at: string | null
|
||||
bound_at: string | null
|
||||
completed_at: string | null
|
||||
last_synced_at: string | null
|
||||
qr_url: string
|
||||
qr_generated_at: string | null
|
||||
qr_expires_at: string | null
|
||||
created_at: string
|
||||
updated_at: string
|
||||
platform_order_id: string
|
||||
sku_code: string
|
||||
sku_name: string
|
||||
quantity: number
|
||||
product_name: string
|
||||
fulfillment_status: string
|
||||
}
|
||||
|
||||
type LiveBindingState = {
|
||||
sessionId: number
|
||||
platformOrderId: string
|
||||
sourceOrderItemId: string
|
||||
productName: string
|
||||
quantity: number
|
||||
executionStatus: string
|
||||
bindingStatus: string
|
||||
exchangeStatus: string
|
||||
issueCode: string
|
||||
message: string
|
||||
accountReady: boolean
|
||||
bindTaskId: number | null
|
||||
bindTaskStatus: string
|
||||
bindPhase: string
|
||||
qrUrl: string
|
||||
qrGeneratedAt: string
|
||||
qrExpiresAt: string
|
||||
roleName: string
|
||||
areaName: string
|
||||
platName: string
|
||||
bindReadyForConfirm: boolean
|
||||
bindConfirmed: boolean
|
||||
customerProfileReset?: boolean
|
||||
resetReason?: string
|
||||
completedAt: string | null
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
type LiveBindingBatchResponse = {
|
||||
items: LiveBindingState[]
|
||||
}
|
||||
|
||||
const AUTO_DISCOVERY_INTERVAL_MS = 15_000
|
||||
const LIVE_STATE_SYNC_INTERVAL_MS = 60_000
|
||||
const TERMINAL_TASK_STATUSES = new Set(['completed', 'cancelled'])
|
||||
|
||||
let lastAutomaticDiscoveryAt = 0
|
||||
let automaticDiscoveryInFlight: Promise<{ created: number; updated: number } | null> | null = null
|
||||
|
||||
const TASK_SELECT = `
|
||||
SELECT
|
||||
task.*,
|
||||
o.platform_order_id,
|
||||
oi.sku_code,
|
||||
oi.sku_name,
|
||||
oi.quantity,
|
||||
COALESCE(NULLIF(oi.sku_name, ''), NULLIF(oi.sku_code, ''), '订单商品') AS product_name,
|
||||
f.status AS fulfillment_status
|
||||
FROM douyu_fulfillment_tasks task
|
||||
JOIN orders o ON o.id = task.order_id
|
||||
JOIN order_items oi ON oi.id = task.order_item_id
|
||||
LEFT JOIN fulfillments f ON f.id = task.fulfillment_id
|
||||
`
|
||||
|
||||
function liveHubBaseUrl() {
|
||||
return String(process.env.LIVE_HUB_PLATFORM_FULFILLMENT_URL || 'http://127.0.0.1:8800')
|
||||
.trim()
|
||||
.replace(/\/+$/, '')
|
||||
}
|
||||
|
||||
function integrationKey() {
|
||||
const key = String(process.env.PLATFORM_FULFILLMENT_INTEGRATION_KEY || '').trim()
|
||||
if (!key) {
|
||||
throw createHttpError('直播账号履约集成密钥未配置', {
|
||||
statusCode: 503,
|
||||
errorCode: 'live_hub_integration_not_configured',
|
||||
})
|
||||
}
|
||||
return key
|
||||
}
|
||||
|
||||
async function liveHubRequest<T>(
|
||||
path: string,
|
||||
init: { method?: string; body?: Record<string, unknown> } = {},
|
||||
): Promise<T> {
|
||||
const response = await fetch(`${liveHubBaseUrl()}${path}`, {
|
||||
method: init.method || 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Integration-Key': integrationKey(),
|
||||
},
|
||||
...(init.body ? { body: JSON.stringify(init.body) } : {}),
|
||||
signal: AbortSignal.timeout(20_000),
|
||||
})
|
||||
const text = await response.text()
|
||||
let payload: unknown = null
|
||||
try {
|
||||
payload = text ? JSON.parse(text) : null
|
||||
} catch {
|
||||
payload = text
|
||||
}
|
||||
if (!response.ok) {
|
||||
const detail =
|
||||
payload && typeof payload === 'object' && 'detail' in payload
|
||||
? String((payload as { detail?: unknown }).detail || '')
|
||||
: String(payload || '')
|
||||
throw createHttpError(detail || '直播账号履约服务请求失败', {
|
||||
statusCode: response.status >= 500 ? 502 : response.status,
|
||||
errorCode: 'live_hub_fulfillment_request_failed',
|
||||
})
|
||||
}
|
||||
return payload as T
|
||||
}
|
||||
|
||||
async function appendEvent(
|
||||
client: Pick<PoolClient, 'query'>,
|
||||
taskId: number,
|
||||
eventType: string,
|
||||
actorType: 'system' | 'customer' | 'admin' | 'integration',
|
||||
detail: Record<string, unknown> = {},
|
||||
) {
|
||||
await client.query(
|
||||
`
|
||||
INSERT INTO douyu_fulfillment_events (
|
||||
task_id, event_type, actor_type, detail_json, created_at
|
||||
) VALUES ($1, $2, $3, $4::jsonb, NOW())
|
||||
`,
|
||||
[taskId, eventType, actorType, JSON.stringify(detail)],
|
||||
)
|
||||
}
|
||||
|
||||
export async function ensureDouyuFulfillmentTasks(orderNo = '') {
|
||||
const params: unknown[] = []
|
||||
let filter = ''
|
||||
const normalizedOrderNo = String(orderNo || '').trim()
|
||||
if (normalizedOrderNo) {
|
||||
params.push(normalizedOrderNo)
|
||||
filter = 'AND o.platform_order_id = $1'
|
||||
}
|
||||
const candidates = await query<{
|
||||
order_id: number
|
||||
order_item_id: number
|
||||
fulfillment_id: number
|
||||
config_id: number
|
||||
platform_order_id: string
|
||||
}>(
|
||||
`
|
||||
SELECT
|
||||
o.id AS order_id,
|
||||
oi.id AS order_item_id,
|
||||
f.id AS fulfillment_id,
|
||||
cfg.id AS config_id,
|
||||
o.platform_order_id
|
||||
FROM orders o
|
||||
JOIN order_items oi ON oi.order_id = o.id
|
||||
JOIN fulfillments f ON f.order_item_id = oi.id
|
||||
JOIN manual_fulfillment_configs cfg ON cfg.id = f.fulfillment_config_id
|
||||
WHERE cfg.enabled = TRUE
|
||||
AND cfg.douyu_fulfillment_enabled = TRUE
|
||||
AND f.channel = 'manual'
|
||||
AND f.status IN ('assigned', 'processing', 'completed')
|
||||
${filter}
|
||||
ORDER BY o.id DESC, oi.id ASC
|
||||
`,
|
||||
params,
|
||||
)
|
||||
if (candidates.rows.length === 0) return { created: 0, updated: 0 }
|
||||
|
||||
let created = 0
|
||||
await withTransaction(async (client) => {
|
||||
for (const row of candidates.rows) {
|
||||
const inserted = await client.query<{ id: number; inserted: boolean }>(
|
||||
`
|
||||
INSERT INTO douyu_fulfillment_tasks (
|
||||
order_id, order_item_id, fulfillment_id, manual_fulfillment_config_id,
|
||||
status, created_at, updated_at
|
||||
) VALUES ($1, $2, $3, $4, 'waiting_profile', NOW(), NOW())
|
||||
ON CONFLICT (order_item_id) DO UPDATE SET
|
||||
fulfillment_id = EXCLUDED.fulfillment_id,
|
||||
manual_fulfillment_config_id = EXCLUDED.manual_fulfillment_config_id,
|
||||
updated_at = CASE
|
||||
WHEN douyu_fulfillment_tasks.fulfillment_id IS DISTINCT FROM EXCLUDED.fulfillment_id
|
||||
OR douyu_fulfillment_tasks.manual_fulfillment_config_id
|
||||
IS DISTINCT FROM EXCLUDED.manual_fulfillment_config_id
|
||||
THEN NOW()
|
||||
ELSE douyu_fulfillment_tasks.updated_at
|
||||
END
|
||||
RETURNING id, (xmax = 0) AS inserted
|
||||
`,
|
||||
[row.order_id, row.order_item_id, row.fulfillment_id, row.config_id],
|
||||
)
|
||||
const taskId = Number(inserted.rows[0]?.id || 0)
|
||||
if (!taskId) continue
|
||||
if (inserted.rows[0]?.inserted) {
|
||||
created += 1
|
||||
await appendEvent(client, taskId, 'task_created', 'system', {
|
||||
platformOrderId: row.platform_order_id,
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
return { created, updated: candidates.rows.length - created }
|
||||
}
|
||||
|
||||
async function ensureDouyuFulfillmentTasksAutomatically() {
|
||||
if (automaticDiscoveryInFlight) return automaticDiscoveryInFlight
|
||||
if (Date.now() - lastAutomaticDiscoveryAt < AUTO_DISCOVERY_INTERVAL_MS) return null
|
||||
|
||||
lastAutomaticDiscoveryAt = Date.now()
|
||||
const run = ensureDouyuFulfillmentTasks()
|
||||
.catch((error) => {
|
||||
lastAutomaticDiscoveryAt = 0
|
||||
throw error
|
||||
})
|
||||
.finally(() => {
|
||||
automaticDiscoveryInFlight = null
|
||||
})
|
||||
automaticDiscoveryInFlight = run
|
||||
return run
|
||||
}
|
||||
|
||||
async function loadTaskByOrderNo(orderNo: string) {
|
||||
const normalized = String(orderNo || '').trim()
|
||||
if (!normalized) {
|
||||
throw createHttpError('订单号不能为空', {
|
||||
statusCode: 400,
|
||||
errorCode: 'douyu_order_no_required',
|
||||
})
|
||||
}
|
||||
await ensureDouyuFulfillmentTasks(normalized)
|
||||
const result = await query<DouyuTaskRow>(
|
||||
`${TASK_SELECT}
|
||||
WHERE o.platform_order_id = $1
|
||||
ORDER BY task.id ASC
|
||||
LIMIT 1`,
|
||||
[normalized],
|
||||
)
|
||||
const task = result.rows[0]
|
||||
if (!task) {
|
||||
throw createHttpError('订单不存在或尚未启用斗鱼领取', {
|
||||
statusCode: 404,
|
||||
errorCode: 'douyu_fulfillment_not_found',
|
||||
})
|
||||
}
|
||||
return task
|
||||
}
|
||||
|
||||
async function loadTask(taskId: number) {
|
||||
const result = await query<DouyuTaskRow>(`${TASK_SELECT} WHERE task.id = $1 LIMIT 1`, [taskId])
|
||||
const task = result.rows[0]
|
||||
if (!task) {
|
||||
throw createHttpError('斗鱼领取任务不存在', {
|
||||
statusCode: 404,
|
||||
errorCode: 'douyu_fulfillment_not_found',
|
||||
})
|
||||
}
|
||||
return task
|
||||
}
|
||||
|
||||
function normalizeText(value: unknown) {
|
||||
return String(value || '')
|
||||
.replace(/\s+/g, '')
|
||||
.toLowerCase()
|
||||
}
|
||||
|
||||
export function compareCustomerRole(task: DouyuTaskRow, live: LiveBindingState) {
|
||||
const roleMatched =
|
||||
Boolean(task.customer_role_name && live.roleName) &&
|
||||
normalizeText(task.customer_role_name) === normalizeText(live.roleName)
|
||||
const liveParts = new Set([normalizeText(live.areaName), normalizeText(live.platName)])
|
||||
const expected: string[] = []
|
||||
if (task.customer_platform === 'wechat') expected.push('微信')
|
||||
if (task.customer_platform === 'qq') expected.push('qq', '手q')
|
||||
if (task.customer_system === 'ios') expected.push('苹果', 'ios')
|
||||
if (task.customer_system === 'android') expected.push('安卓', 'android')
|
||||
const channelMatched = expected.every((item) =>
|
||||
[...liveParts].some((part) => part.includes(item) || item.includes(part)),
|
||||
)
|
||||
return {
|
||||
matched: roleMatched && channelMatched,
|
||||
roleMatched,
|
||||
channelMatched,
|
||||
message:
|
||||
roleMatched && channelMatched
|
||||
? '客户资料与平台识别角色一致'
|
||||
: '客户资料与平台识别角色不一致,请修改资料或联系客服',
|
||||
}
|
||||
}
|
||||
|
||||
const BINDING_FAILURE_ISSUES = new Set([
|
||||
'binding_failed',
|
||||
'account_role_cooldown',
|
||||
'customer_role_cooldown',
|
||||
])
|
||||
|
||||
export function statusForLive(live: LiveBindingState): string {
|
||||
if (live.customerProfileReset === true) return 'waiting_profile'
|
||||
if (live.executionStatus === 'completed') return 'completed'
|
||||
if (live.executionStatus === 'cancelled') return 'cancelled'
|
||||
if (live.bindingStatus === 'failed' || BINDING_FAILURE_ISSUES.has(live.issueCode)) {
|
||||
return 'failed'
|
||||
}
|
||||
if (live.executionStatus === 'manual_required') return 'manual_required'
|
||||
if (live.executionStatus === 'allocated') return 'allocated'
|
||||
if (live.bindConfirmed) return 'waiting_operator'
|
||||
if (live.bindReadyForConfirm) return 'role_ready'
|
||||
if (live.qrUrl) return 'qr_pending'
|
||||
if (
|
||||
live.issueCode === 'mapping_missing' ||
|
||||
live.issueCode === 'no_eligible_account' ||
|
||||
live.issueCode === 'elite_not_opened' ||
|
||||
live.issueCode === 'points_short' ||
|
||||
!live.accountReady
|
||||
) {
|
||||
return 'preparing'
|
||||
}
|
||||
if (live.issueCode) return 'failed'
|
||||
return 'preparing'
|
||||
}
|
||||
|
||||
async function updateTaskFromLiveState(
|
||||
client: Pick<PoolClient, 'query'>,
|
||||
task: DouyuTaskRow,
|
||||
live: LiveBindingState,
|
||||
now: string,
|
||||
) {
|
||||
const resetCustomerProfile = live.customerProfileReset === true
|
||||
const nextStatus = statusForLive(live)
|
||||
await client.query(
|
||||
`
|
||||
UPDATE douyu_fulfillment_tasks
|
||||
SET live_session_id = $2,
|
||||
status = $3,
|
||||
binding_phase = $4,
|
||||
live_execution_status = $5,
|
||||
live_binding_status = $6,
|
||||
issue_code = $7,
|
||||
last_error = $8,
|
||||
bound_role_name = $9,
|
||||
bound_area_name = $10,
|
||||
bound_plat_name = $11,
|
||||
binding_started_at = CASE
|
||||
WHEN $19 THEN NULL
|
||||
WHEN $12 <> '' THEN COALESCE(binding_started_at, NOW())
|
||||
ELSE binding_started_at
|
||||
END,
|
||||
bound_at = CASE
|
||||
WHEN $19 THEN NULL
|
||||
WHEN $13 THEN COALESCE(bound_at, NOW())
|
||||
ELSE bound_at
|
||||
END,
|
||||
completed_at = CASE
|
||||
WHEN $19 THEN NULL
|
||||
WHEN $14 THEN COALESCE(completed_at, NOW())
|
||||
ELSE completed_at
|
||||
END,
|
||||
customer_role_name = CASE WHEN $19 THEN '' ELSE customer_role_name END,
|
||||
customer_platform = CASE WHEN $19 THEN '' ELSE customer_platform END,
|
||||
customer_system = CASE WHEN $19 THEN '' ELSE customer_system END,
|
||||
qr_url = $15,
|
||||
qr_generated_at = NULLIF($16, '')::timestamptz,
|
||||
qr_expires_at = NULLIF($17, '')::timestamptz,
|
||||
last_synced_at = NOW(),
|
||||
updated_at = $18
|
||||
WHERE id = $1
|
||||
`,
|
||||
[
|
||||
task.id,
|
||||
live.sessionId,
|
||||
nextStatus,
|
||||
live.bindPhase,
|
||||
live.executionStatus,
|
||||
live.bindingStatus,
|
||||
live.issueCode,
|
||||
live.message,
|
||||
live.roleName,
|
||||
live.areaName,
|
||||
live.platName,
|
||||
live.qrUrl,
|
||||
live.bindConfirmed,
|
||||
live.executionStatus === 'completed',
|
||||
live.qrUrl,
|
||||
live.qrGeneratedAt,
|
||||
live.qrExpiresAt,
|
||||
now,
|
||||
resetCustomerProfile,
|
||||
],
|
||||
)
|
||||
if (nextStatus !== task.status) {
|
||||
await appendEvent(client, task.id, 'status_changed', 'integration', {
|
||||
fromStatus: task.status,
|
||||
toStatus: nextStatus,
|
||||
bindPhase: live.bindPhase,
|
||||
})
|
||||
}
|
||||
if (resetCustomerProfile) {
|
||||
await appendEvent(client, task.id, 'customer_profile_reset', 'integration', {
|
||||
reason: String(live.resetReason || ''),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async function applyLiveState(task: DouyuTaskRow, live: LiveBindingState) {
|
||||
await withTransaction(async (client) => {
|
||||
await updateTaskFromLiveState(client, task, live, nowIso())
|
||||
})
|
||||
const updated = await loadTask(task.id)
|
||||
return { task: updated, live, comparison: compareCustomerRole(updated, live) }
|
||||
}
|
||||
|
||||
async function applyLiveStates(entries: Array<{ task: DouyuTaskRow; live: LiveBindingState }>) {
|
||||
if (entries.length === 0) return
|
||||
const now = nowIso()
|
||||
await withTransaction(async (client) => {
|
||||
for (const entry of entries) {
|
||||
await updateTaskFromLiveState(client, entry.task, entry.live, now)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function isLiveBindingState(value: unknown): value is LiveBindingState {
|
||||
if (!value || typeof value !== 'object') return false
|
||||
const item = value as Partial<LiveBindingState>
|
||||
return (
|
||||
Number.isInteger(Number(item.sessionId)) &&
|
||||
Number(item.sessionId) > 0 &&
|
||||
typeof item.executionStatus === 'string' &&
|
||||
typeof item.bindingStatus === 'string' &&
|
||||
typeof item.exchangeStatus === 'string' &&
|
||||
typeof item.issueCode === 'string' &&
|
||||
typeof item.message === 'string'
|
||||
)
|
||||
}
|
||||
|
||||
function liveBindingStateFromTask(task: DouyuTaskRow): LiveBindingState {
|
||||
return {
|
||||
sessionId: Number(task.live_session_id),
|
||||
platformOrderId: task.platform_order_id,
|
||||
sourceOrderItemId: String(task.order_item_id),
|
||||
productName: task.product_name,
|
||||
quantity: Number(task.quantity || 1),
|
||||
executionStatus: task.live_execution_status || 'preparing',
|
||||
bindingStatus: task.live_binding_status || 'not_started',
|
||||
exchangeStatus: '',
|
||||
issueCode: task.issue_code || '',
|
||||
message: task.last_error || '',
|
||||
accountReady: !['waiting_profile', 'preparing'].includes(task.status),
|
||||
bindTaskId: null,
|
||||
bindTaskStatus: '',
|
||||
bindPhase: task.binding_phase || '',
|
||||
qrUrl: task.qr_url || '',
|
||||
qrGeneratedAt: task.qr_generated_at || '',
|
||||
qrExpiresAt: task.qr_expires_at || '',
|
||||
roleName: task.bound_role_name || '',
|
||||
areaName: task.bound_area_name || '',
|
||||
platName: task.bound_plat_name || '',
|
||||
bindReadyForConfirm: task.status === 'role_ready',
|
||||
bindConfirmed: ['bound', 'waiting_operator', 'processing', 'completed'].includes(task.status),
|
||||
completedAt: task.completed_at,
|
||||
updatedAt: task.updated_at,
|
||||
}
|
||||
}
|
||||
|
||||
export async function applyLiveBindingStateSnapshot(
|
||||
input: unknown,
|
||||
options: { eventId?: string; eventType?: string } = {},
|
||||
) {
|
||||
const rawItems =
|
||||
input && typeof input === 'object' && Array.isArray((input as { items?: unknown }).items)
|
||||
? (input as { items: unknown[] }).items
|
||||
: []
|
||||
const items = rawItems.filter(isLiveBindingState)
|
||||
if (items.length === 0) {
|
||||
return { received: rawItems.length, updated: 0 }
|
||||
}
|
||||
|
||||
const sessionIds = Array.from(
|
||||
new Set(items.map((item) => Number(item.sessionId)).filter((id) => id > 0)),
|
||||
)
|
||||
const orderNos = Array.from(
|
||||
new Set(items.map((item) => String(item.platformOrderId || '').trim()).filter(Boolean)),
|
||||
).slice(0, 50)
|
||||
const orderItemIds = Array.from(
|
||||
new Set(items.map((item) => String(item.sourceOrderItemId || '').trim()).filter(Boolean)),
|
||||
)
|
||||
if (sessionIds.length === 0 && orderNos.length === 0 && orderItemIds.length === 0) {
|
||||
return { received: rawItems.length, updated: 0 }
|
||||
}
|
||||
|
||||
// Webhook 可能先于客户首次打开领取页到达;先幂等补齐本地订单投影。
|
||||
for (const orderNo of orderNos) {
|
||||
await ensureDouyuFulfillmentTasks(orderNo)
|
||||
}
|
||||
|
||||
const result = await withTransaction(async (client) => {
|
||||
const eventId = String(options.eventId || '').trim()
|
||||
if (eventId) {
|
||||
const claimed = await client.query(
|
||||
`
|
||||
INSERT INTO integration_inbox (
|
||||
event_id, source, event_type, received_at, processed_at
|
||||
) VALUES ($1, 'live_hub', $2, NOW(), NOW())
|
||||
ON CONFLICT (event_id) DO NOTHING
|
||||
RETURNING event_id
|
||||
`,
|
||||
[eventId, String(options.eventType || '')],
|
||||
)
|
||||
if (claimed.rowCount === 0) {
|
||||
return { received: rawItems.length, updated: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
const tasks = await client.query<DouyuTaskRow>(
|
||||
`${TASK_SELECT}
|
||||
WHERE task.live_session_id = ANY($1::bigint[])
|
||||
OR CAST(task.order_item_id AS text) = ANY($2::text[])
|
||||
OR o.platform_order_id = ANY($3::text[])`,
|
||||
[sessionIds, orderItemIds, orderNos],
|
||||
)
|
||||
const taskBySessionId = new Map(
|
||||
tasks.rows
|
||||
.filter((task) => task.live_session_id)
|
||||
.map((task) => [Number(task.live_session_id), task]),
|
||||
)
|
||||
const taskByOrderItemId = new Map(tasks.rows.map((task) => [String(task.order_item_id), task]))
|
||||
const now = nowIso()
|
||||
const entries = items.flatMap((live) => {
|
||||
const task =
|
||||
taskBySessionId.get(Number(live.sessionId)) ||
|
||||
taskByOrderItemId.get(String(live.sourceOrderItemId || ''))
|
||||
return task ? [{ task, live }] : []
|
||||
})
|
||||
for (const entry of entries) {
|
||||
await updateTaskFromLiveState(client, entry.task, entry.live, now)
|
||||
}
|
||||
return { received: rawItems.length, updated: entries.length }
|
||||
})
|
||||
|
||||
if (result.updated > 0) {
|
||||
publishRealtimeEvent({
|
||||
type: 'order.changed',
|
||||
entityId: 0,
|
||||
scopes: ['admin_douyu_fulfillment'],
|
||||
operation: 'refresh',
|
||||
data: { douyuFulfillmentUpdated: true },
|
||||
admin: true,
|
||||
})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
async function ensureLiveSession(task: DouyuTaskRow) {
|
||||
const live = await liveHubRequest<LiveBindingState>(
|
||||
'/api/integration/platform-fulfillment/customer-sessions/ensure',
|
||||
{
|
||||
method: 'POST',
|
||||
body: {
|
||||
source_order_item_id: String(task.order_item_id),
|
||||
platform_order_id: task.platform_order_id,
|
||||
},
|
||||
},
|
||||
)
|
||||
return applyLiveState(task, live)
|
||||
}
|
||||
|
||||
export async function getCustomerDouyuFulfillment(orderNo: string) {
|
||||
const task = await loadTaskByOrderNo(orderNo)
|
||||
if (!task.customer_link_opened_at) {
|
||||
await withTransaction(async (client) => {
|
||||
await client.query(
|
||||
`UPDATE douyu_fulfillment_tasks
|
||||
SET customer_link_opened_at = COALESCE(customer_link_opened_at, NOW())
|
||||
WHERE id = $1`,
|
||||
[task.id],
|
||||
)
|
||||
await appendEvent(client, task.id, 'customer_link_opened', 'customer')
|
||||
})
|
||||
}
|
||||
const session = await ensureLiveSession(task)
|
||||
return {
|
||||
task: session.task,
|
||||
live: session.live,
|
||||
comparison: session.comparison,
|
||||
linkPath: `/coll/d/${encodeURIComponent(task.platform_order_id)}`,
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveDouyuCustomerProfile(
|
||||
orderNo: string,
|
||||
input: { roleName?: unknown; platform?: unknown; system?: unknown },
|
||||
) {
|
||||
const task = await loadTaskByOrderNo(orderNo)
|
||||
if (task.status === 'completed' || task.status === 'cancelled') {
|
||||
throw createHttpError('当前订单已结束,不能修改资料', {
|
||||
statusCode: 409,
|
||||
errorCode: 'douyu_fulfillment_closed',
|
||||
})
|
||||
}
|
||||
const roleName = String(input.roleName ?? '')
|
||||
.trim()
|
||||
.slice(0, 100)
|
||||
const platform = String(input.platform ?? '')
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
const system = String(input.system ?? '')
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
if (!roleName || !['wechat', 'qq'].includes(platform) || !['ios', 'android'].includes(system)) {
|
||||
throw createHttpError('请完整填写角色名、微信/QQ 和苹果/安卓', {
|
||||
statusCode: 400,
|
||||
errorCode: 'douyu_customer_profile_invalid',
|
||||
})
|
||||
}
|
||||
await withTransaction(async (client) => {
|
||||
await client.query(
|
||||
`
|
||||
UPDATE douyu_fulfillment_tasks
|
||||
SET customer_role_name = $2,
|
||||
customer_platform = $3,
|
||||
customer_system = $4,
|
||||
status = CASE WHEN status = 'waiting_profile' THEN 'preparing' ELSE status END,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[task.id, roleName, platform, system],
|
||||
)
|
||||
await appendEvent(client, task.id, 'customer_profile_saved', 'customer', {
|
||||
roleName,
|
||||
platform,
|
||||
system,
|
||||
})
|
||||
})
|
||||
return getCustomerDouyuFulfillment(orderNo)
|
||||
}
|
||||
|
||||
export async function startDouyuCustomerBinding(orderNo: string, forceRefresh = false) {
|
||||
let task = await loadTaskByOrderNo(orderNo)
|
||||
const session = await ensureLiveSession(task)
|
||||
task = session.task
|
||||
if (!task.live_session_id) {
|
||||
throw createHttpError('直播账号履约会话尚未准备完成', {
|
||||
statusCode: 409,
|
||||
errorCode: 'douyu_live_session_not_ready',
|
||||
})
|
||||
}
|
||||
const live = await liveHubRequest<LiveBindingState>(
|
||||
`/api/integration/platform-fulfillment/customer-sessions/${task.live_session_id}/binding/start`,
|
||||
{ method: 'POST', body: { force_refresh: forceRefresh } },
|
||||
)
|
||||
return applyLiveState(task, live)
|
||||
}
|
||||
|
||||
export async function refreshDouyuCustomerBinding(orderNo: string) {
|
||||
const task = await loadTaskByOrderNo(orderNo)
|
||||
if (!task.live_session_id) return ensureLiveSession(task)
|
||||
const live = await liveHubRequest<LiveBindingState>(
|
||||
`/api/integration/platform-fulfillment/customer-sessions/${task.live_session_id}/status`,
|
||||
)
|
||||
return applyLiveState(task, live)
|
||||
}
|
||||
|
||||
export async function getDouyuCustomerFulfillmentCached(orderNo: string) {
|
||||
let task = await loadTaskByOrderNo(orderNo)
|
||||
if (!task.live_session_id) {
|
||||
return ensureLiveSession(task)
|
||||
}
|
||||
task = await loadTask(task.id)
|
||||
const live = liveBindingStateFromTask(task)
|
||||
return {
|
||||
task,
|
||||
live,
|
||||
comparison: compareCustomerRole(task, live),
|
||||
linkPath: `/coll/d/${encodeURIComponent(task.platform_order_id)}`,
|
||||
}
|
||||
}
|
||||
|
||||
export async function confirmDouyuCustomerBinding(orderNo: string) {
|
||||
const refreshed = await refreshDouyuCustomerBinding(orderNo)
|
||||
if (!refreshed.comparison.matched) {
|
||||
throw createHttpError(refreshed.comparison.message, {
|
||||
statusCode: 409,
|
||||
errorCode: 'douyu_customer_role_mismatch',
|
||||
})
|
||||
}
|
||||
const task = refreshed.task
|
||||
if (!task.live_session_id) {
|
||||
throw createHttpError('直播账号履约会话尚未准备完成', {
|
||||
statusCode: 409,
|
||||
errorCode: 'douyu_live_session_not_ready',
|
||||
})
|
||||
}
|
||||
const live = await liveHubRequest<LiveBindingState>(
|
||||
`/api/integration/platform-fulfillment/customer-sessions/${task.live_session_id}/binding/confirm`,
|
||||
{ method: 'POST' },
|
||||
)
|
||||
return applyLiveState(task, live)
|
||||
}
|
||||
|
||||
async function syncLiveStatesForTasks(tasks: DouyuTaskRow[], force = false) {
|
||||
const now = Date.now()
|
||||
const candidates = tasks.filter((task) => {
|
||||
if (!task.live_session_id || TERMINAL_TASK_STATUSES.has(task.status)) return false
|
||||
if (force) return true
|
||||
const lastSyncedAt = Date.parse(task.last_synced_at || '')
|
||||
return !lastSyncedAt || now - lastSyncedAt >= LIVE_STATE_SYNC_INTERVAL_MS
|
||||
})
|
||||
if (candidates.length === 0) return
|
||||
|
||||
try {
|
||||
const response = await liveHubRequest<LiveBindingBatchResponse>(
|
||||
'/api/integration/platform-fulfillment/customer-sessions/status/batch',
|
||||
{
|
||||
method: 'POST',
|
||||
body: {
|
||||
task_ids: candidates.map((task) => Number(task.live_session_id)),
|
||||
},
|
||||
},
|
||||
)
|
||||
const taskBySessionId = new Map(candidates.map((task) => [Number(task.live_session_id), task]))
|
||||
const entries = response.items.flatMap((live) => {
|
||||
const task = taskBySessionId.get(Number(live.sessionId))
|
||||
return task ? [{ task, live }] : []
|
||||
})
|
||||
await applyLiveStates(entries)
|
||||
if (entries.length > 0) {
|
||||
publishRealtimeEvent({
|
||||
type: 'order.changed',
|
||||
entityId: 0,
|
||||
scopes: ['admin_douyu_fulfillment'],
|
||||
operation: 'refresh',
|
||||
data: { douyuFulfillmentUpdated: true },
|
||||
admin: true,
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
logWarn('[douyu-fulfillment]', '自动同步直播账号履约状态失败', { error })
|
||||
}
|
||||
}
|
||||
|
||||
export async function reconcileDouyuFulfillmentStates() {
|
||||
const rows = await query<DouyuTaskRow>(
|
||||
`${TASK_SELECT}
|
||||
WHERE task.live_session_id IS NOT NULL
|
||||
AND task.status NOT IN ('completed', 'cancelled')
|
||||
ORDER BY task.updated_at ASC, task.id ASC
|
||||
LIMIT 100`,
|
||||
)
|
||||
await syncLiveStatesForTasks(rows.rows, true)
|
||||
return { checked: rows.rows.length }
|
||||
}
|
||||
|
||||
export async function syncDouyuFulfillmentTasks() {
|
||||
const synced = await ensureDouyuFulfillmentTasks()
|
||||
const states = await reconcileDouyuFulfillmentStates()
|
||||
return { ...synced, checked: states.checked }
|
||||
}
|
||||
|
||||
export async function listDouyuFulfillmentTasks(
|
||||
input: {
|
||||
keyword?: unknown
|
||||
status?: unknown
|
||||
page?: unknown
|
||||
pageSize?: unknown
|
||||
} = {},
|
||||
) {
|
||||
await ensureDouyuFulfillmentTasksAutomatically()
|
||||
const page = Math.max(1, Number(input.page || 1))
|
||||
const pageSize = Math.max(1, Math.min(100, Number(input.pageSize || 20)))
|
||||
const keyword = String(input.keyword || '').trim()
|
||||
const status = String(input.status || '').trim()
|
||||
const params: unknown[] = []
|
||||
const filters: string[] = []
|
||||
if (keyword) {
|
||||
params.push(`%${keyword}%`)
|
||||
filters.push(`(
|
||||
o.platform_order_id ILIKE $${params.length}
|
||||
OR oi.sku_name ILIKE $${params.length}
|
||||
OR task.customer_role_name ILIKE $${params.length}
|
||||
)`)
|
||||
}
|
||||
if (status) {
|
||||
params.push(status)
|
||||
filters.push(`task.status = $${params.length}`)
|
||||
}
|
||||
const where = filters.length ? `WHERE ${filters.join(' AND ')}` : ''
|
||||
const count = await query<{ total: number }>(
|
||||
`SELECT COUNT(*)::int AS total
|
||||
FROM douyu_fulfillment_tasks task
|
||||
JOIN orders o ON o.id = task.order_id
|
||||
JOIN order_items oi ON oi.id = task.order_item_id
|
||||
${where}`,
|
||||
params,
|
||||
)
|
||||
params.push(pageSize, (page - 1) * pageSize)
|
||||
const rows = await query<DouyuTaskRow>(
|
||||
`${TASK_SELECT}
|
||||
${where}
|
||||
ORDER BY task.updated_at DESC, task.id DESC
|
||||
LIMIT $${params.length - 1} OFFSET $${params.length}`,
|
||||
params,
|
||||
)
|
||||
return {
|
||||
items: rows.rows.map((task) => ({
|
||||
...task,
|
||||
linkPath: `/coll/d/${encodeURIComponent(task.platform_order_id)}`,
|
||||
})),
|
||||
pagination: { page, pageSize, total: Number(count.rows[0]?.total || 0) },
|
||||
}
|
||||
}
|
||||
|
||||
export async function getDouyuFulfillmentDetail(orderNo: string) {
|
||||
const task = await loadTaskByOrderNo(orderNo)
|
||||
const [session, events] = await Promise.all([
|
||||
ensureLiveSession(task),
|
||||
query<{
|
||||
id: number
|
||||
event_type: string
|
||||
actor_type: string
|
||||
detail_json: Record<string, unknown>
|
||||
created_at: string
|
||||
}>(
|
||||
`SELECT id, event_type, actor_type, detail_json, created_at
|
||||
FROM douyu_fulfillment_events
|
||||
WHERE task_id = $1
|
||||
ORDER BY id DESC
|
||||
LIMIT 200`,
|
||||
[task.id],
|
||||
),
|
||||
])
|
||||
return {
|
||||
...session,
|
||||
linkPath: `/coll/d/${encodeURIComponent(task.platform_order_id)}`,
|
||||
events: events.rows,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import {
|
||||
applyLiveBindingStateSnapshot,
|
||||
compareCustomerRole,
|
||||
statusForLive,
|
||||
} from './douyu-fulfillment-service.js'
|
||||
|
||||
const task = {
|
||||
customer_role_name: '狗鼻子弗尼亚bd',
|
||||
customer_platform: 'wechat',
|
||||
customer_system: 'android',
|
||||
} as never
|
||||
|
||||
const live = {
|
||||
roleName: '狗鼻子弗尼亚bd',
|
||||
areaName: '微信',
|
||||
platName: '安卓(android)',
|
||||
} as never
|
||||
|
||||
test('斗鱼客户资料与平台角色一致', () => {
|
||||
const result = compareCustomerRole(task, live)
|
||||
assert.equal(result.matched, true)
|
||||
assert.equal(result.roleMatched, true)
|
||||
assert.equal(result.channelMatched, true)
|
||||
})
|
||||
|
||||
test('斗鱼客户资料平台或系统不一致时禁止确认', () => {
|
||||
const result = compareCustomerRole(task, {
|
||||
...live,
|
||||
areaName: 'QQ',
|
||||
platName: '苹果(iOS)',
|
||||
} as never)
|
||||
assert.equal(result.matched, false)
|
||||
assert.equal(result.channelMatched, false)
|
||||
})
|
||||
|
||||
test('斗鱼客户资料角色名不一致时禁止确认', () => {
|
||||
const result = compareCustomerRole(task, { ...live, roleName: '另一个角色' } as never)
|
||||
assert.equal(result.matched, false)
|
||||
assert.equal(result.roleMatched, false)
|
||||
})
|
||||
|
||||
test('绑定失败优先于旧角色确认标记', () => {
|
||||
const status = statusForLive({
|
||||
executionStatus: 'manual_required',
|
||||
bindingStatus: 'failed',
|
||||
issueCode: 'customer_role_cooldown',
|
||||
bindReadyForConfirm: true,
|
||||
bindConfirmed: false,
|
||||
qrUrl: 'https://example.com/old-qr',
|
||||
accountReady: true,
|
||||
} as never)
|
||||
assert.equal(status, 'failed')
|
||||
})
|
||||
|
||||
test('绑定失败代码优先于旧待确认状态', () => {
|
||||
const status = statusForLive({
|
||||
executionStatus: 'role_ready',
|
||||
bindingStatus: 'role_ready',
|
||||
issueCode: 'binding_failed',
|
||||
bindReadyForConfirm: true,
|
||||
bindConfirmed: false,
|
||||
qrUrl: '',
|
||||
accountReady: true,
|
||||
} as never)
|
||||
assert.equal(status, 'failed')
|
||||
})
|
||||
|
||||
test('已分配账号保持 allocated,不折叠成准备账号', () => {
|
||||
const status = statusForLive({
|
||||
executionStatus: 'allocated',
|
||||
bindingStatus: 'not_started',
|
||||
issueCode: '',
|
||||
bindReadyForConfirm: false,
|
||||
bindConfirmed: false,
|
||||
qrUrl: '',
|
||||
accountReady: true,
|
||||
} as never)
|
||||
assert.equal(status, 'allocated')
|
||||
})
|
||||
|
||||
test('直播账号状态推送忽略空数据和无效任务', async () => {
|
||||
assert.deepEqual(await applyLiveBindingStateSnapshot({ items: [] }), {
|
||||
received: 0,
|
||||
updated: 0,
|
||||
})
|
||||
assert.deepEqual(
|
||||
await applyLiveBindingStateSnapshot({
|
||||
items: [{ sessionId: 0 }, null, { sessionId: 'bad' }],
|
||||
}),
|
||||
{ received: 3, updated: 0 },
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,51 @@
|
||||
import { logWarn } from '../../utils/logger.js'
|
||||
import { reconcileDouyuFulfillmentStates } from './douyu-fulfillment-service.js'
|
||||
|
||||
const DEFAULT_RECONCILE_SECONDS = 900
|
||||
|
||||
let timer: NodeJS.Timeout | null = null
|
||||
let stopped = true
|
||||
|
||||
function intervalMs() {
|
||||
const value = Number(process.env.PLATFORM_FULFILLMENT_RECONCILE_SECONDS)
|
||||
const seconds =
|
||||
Number.isFinite(value) && value > 0
|
||||
? Math.max(60, Math.trunc(value))
|
||||
: DEFAULT_RECONCILE_SECONDS
|
||||
return seconds * 1000
|
||||
}
|
||||
|
||||
async function run() {
|
||||
if (stopped) return
|
||||
try {
|
||||
await reconcileDouyuFulfillmentStates()
|
||||
} catch (error) {
|
||||
logWarn('[douyu-fulfillment]', '低频对账失败', { error })
|
||||
} finally {
|
||||
if (!stopped) {
|
||||
timer = setTimeout(() => {
|
||||
void run()
|
||||
}, intervalMs())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function startDouyuFulfillmentReconciler() {
|
||||
if (timer || !stopped) return
|
||||
stopped = false
|
||||
// 启动后先让 Webhook 工作一分钟,再执行首轮兜底对账。
|
||||
timer = setTimeout(
|
||||
() => {
|
||||
void run()
|
||||
},
|
||||
Math.min(60_000, intervalMs()),
|
||||
)
|
||||
}
|
||||
|
||||
export function stopDouyuFulfillmentReconciler() {
|
||||
stopped = true
|
||||
if (timer) {
|
||||
clearTimeout(timer)
|
||||
timer = null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
|
||||
test('Outbox migration keeps header event id and payload eventId identical', () => {
|
||||
const sql = readFileSync(
|
||||
new URL('../../db/migrations/171_douyu_fulfillment_integration.sql', import.meta.url),
|
||||
'utf8',
|
||||
)
|
||||
|
||||
assert.match(sql, /'eventId', event_id::text/)
|
||||
assert.doesNotMatch(sql, /'eventId', gen_random_uuid\(\)::text/)
|
||||
assert.match(sql, /CREATE TABLE IF NOT EXISTS integration_outbox/)
|
||||
assert.match(sql, /CREATE TABLE IF NOT EXISTS integration_inbox/)
|
||||
})
|
||||
@@ -0,0 +1,209 @@
|
||||
import { query, withTransaction } from '../../db/client.js'
|
||||
import { logError, logInfo, logWarn } from '../../utils/logger.js'
|
||||
import { buildWebhookSignature } from './webhook-signature.js'
|
||||
|
||||
const DEFAULT_INTERVAL_MS = 1000
|
||||
const DEFAULT_BATCH_SIZE = 20
|
||||
const DEFAULT_MAX_ATTEMPTS = 12
|
||||
const REQUEST_TIMEOUT_MS = 5000
|
||||
const PROCESSING_STALE_SECONDS = 120
|
||||
|
||||
type OutboxRow = {
|
||||
id: string
|
||||
event_id: string
|
||||
payload_json: unknown
|
||||
attempts: number
|
||||
}
|
||||
|
||||
let timer: NodeJS.Timeout | null = null
|
||||
let running = false
|
||||
let stopped = true
|
||||
|
||||
function envInt(name: string, fallback: number, min: number, max: number) {
|
||||
const parsed = Number(process.env[name])
|
||||
if (!Number.isFinite(parsed)) return fallback
|
||||
return Math.max(min, Math.min(max, Math.trunc(parsed)))
|
||||
}
|
||||
|
||||
export function integrationOutboxConfigured() {
|
||||
return Boolean(
|
||||
String(process.env.LIVE_HUB_PLATFORM_FULFILLMENT_URL || '').trim() &&
|
||||
String(process.env.PLATFORM_FULFILLMENT_INTEGRATION_KEY || '').trim(),
|
||||
)
|
||||
}
|
||||
|
||||
export function integrationOutboxBackoffSeconds(attempts: number) {
|
||||
const normalized = Math.max(1, Math.trunc(Number(attempts) || 1))
|
||||
return Math.min(3600, 5 * 2 ** Math.min(normalized - 1, 10))
|
||||
}
|
||||
|
||||
async function claimDueEvents(limit: number): Promise<OutboxRow[]> {
|
||||
return withTransaction(async (client) => {
|
||||
await client.query(
|
||||
`
|
||||
UPDATE integration_outbox
|
||||
SET status = 'pending',
|
||||
locked_at = NULL,
|
||||
next_attempt_at = NOW()
|
||||
WHERE status = 'processing'
|
||||
AND locked_at < NOW() - ($1 * INTERVAL '1 second')
|
||||
`,
|
||||
[PROCESSING_STALE_SECONDS],
|
||||
)
|
||||
|
||||
const claimed = await client.query<OutboxRow>(
|
||||
`
|
||||
SELECT id, event_id, payload_json, attempts
|
||||
FROM integration_outbox
|
||||
WHERE status = 'pending'
|
||||
AND next_attempt_at <= NOW()
|
||||
ORDER BY id ASC
|
||||
LIMIT $1
|
||||
FOR UPDATE SKIP LOCKED
|
||||
`,
|
||||
[limit],
|
||||
)
|
||||
const ids = claimed.rows.map((row) => Number(row.id)).filter((id) => id > 0)
|
||||
if (ids.length === 0) return []
|
||||
|
||||
await client.query(
|
||||
`
|
||||
UPDATE integration_outbox
|
||||
SET status = 'processing',
|
||||
locked_at = NOW()
|
||||
WHERE id = ANY($1::bigint[])
|
||||
`,
|
||||
[ids],
|
||||
)
|
||||
return claimed.rows
|
||||
})
|
||||
}
|
||||
|
||||
async function deliverEvent(row: OutboxRow) {
|
||||
const baseUrl = String(process.env.LIVE_HUB_PLATFORM_FULFILLMENT_URL || '')
|
||||
.trim()
|
||||
.replace(/\/+$/, '')
|
||||
const integrationKey = String(process.env.PLATFORM_FULFILLMENT_INTEGRATION_KEY || '').trim()
|
||||
const endpoint = `${baseUrl}/api/integration/platform-fulfillment/events/order-sync`
|
||||
const rawBody =
|
||||
typeof row.payload_json === 'string' ? row.payload_json : JSON.stringify(row.payload_json)
|
||||
const timestamp = String(Math.floor(Date.now() / 1000))
|
||||
const signature = buildWebhookSignature(integrationKey, timestamp, rawBody)
|
||||
|
||||
const response = await fetch(endpoint, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Integration-Key': integrationKey,
|
||||
'X-Integration-Event-Id': row.event_id,
|
||||
'X-Integration-Timestamp': timestamp,
|
||||
'X-Integration-Signature': signature,
|
||||
},
|
||||
body: rawBody,
|
||||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
})
|
||||
if (!response.ok) {
|
||||
throw new Error(`live-hub 返回 HTTP ${response.status}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function markSent(eventId: string) {
|
||||
await query(
|
||||
`
|
||||
UPDATE integration_outbox
|
||||
SET status = 'sent',
|
||||
sent_at = NOW(),
|
||||
locked_at = NULL,
|
||||
last_error = ''
|
||||
WHERE event_id = $1
|
||||
`,
|
||||
[eventId],
|
||||
)
|
||||
}
|
||||
|
||||
async function markFailed(row: OutboxRow, error: unknown) {
|
||||
const attempts = Number(row.attempts || 0) + 1
|
||||
const maxAttempts = envInt('INTEGRATION_OUTBOX_MAX_ATTEMPTS', DEFAULT_MAX_ATTEMPTS, 1, 100)
|
||||
const dead = attempts >= maxAttempts
|
||||
const message = (error instanceof Error ? error.message : String(error)).slice(0, 2000)
|
||||
await query(
|
||||
`
|
||||
UPDATE integration_outbox
|
||||
SET status = $2,
|
||||
attempts = $3,
|
||||
locked_at = NULL,
|
||||
next_attempt_at = NOW() + ($4 * INTERVAL '1 second'),
|
||||
last_error = $5
|
||||
WHERE event_id = $1
|
||||
`,
|
||||
[
|
||||
row.event_id,
|
||||
dead ? 'dead' : 'pending',
|
||||
attempts,
|
||||
dead ? 0 : integrationOutboxBackoffSeconds(attempts),
|
||||
message,
|
||||
],
|
||||
)
|
||||
if (dead) {
|
||||
logError('[integration/outbox]', '事件超过最大重试次数,已进入 dead', {
|
||||
eventId: row.event_id,
|
||||
attempts,
|
||||
error: message,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async function publishDueEvents() {
|
||||
if (!integrationOutboxConfigured()) return
|
||||
const batchSize = envInt('INTEGRATION_OUTBOX_BATCH_SIZE', DEFAULT_BATCH_SIZE, 1, 100)
|
||||
const rows = await claimDueEvents(batchSize)
|
||||
for (const row of rows) {
|
||||
try {
|
||||
await deliverEvent(row)
|
||||
await markSent(row.event_id)
|
||||
} catch (error) {
|
||||
await markFailed(row, error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function runLoop() {
|
||||
if (stopped || running) return
|
||||
running = true
|
||||
try {
|
||||
await publishDueEvents()
|
||||
} catch (error) {
|
||||
logWarn('[integration/outbox]', '投递轮次失败', { error })
|
||||
} finally {
|
||||
running = false
|
||||
if (!stopped) {
|
||||
timer = setTimeout(
|
||||
() => {
|
||||
void runLoop()
|
||||
},
|
||||
envInt('INTEGRATION_OUTBOX_INTERVAL_MS', DEFAULT_INTERVAL_MS, 250, 60_000),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function startIntegrationOutboxWorker() {
|
||||
if (timer || !stopped) return
|
||||
stopped = false
|
||||
if (!integrationOutboxConfigured()) {
|
||||
logWarn('[integration/outbox]', '未配置 live-hub 地址或集成密钥,worker 仅保持待命')
|
||||
} else {
|
||||
logInfo('[integration/outbox]', '事务 Outbox worker 已启动')
|
||||
}
|
||||
timer = setTimeout(() => {
|
||||
void runLoop()
|
||||
}, 0)
|
||||
}
|
||||
|
||||
export function stopIntegrationOutboxWorker() {
|
||||
stopped = true
|
||||
if (timer) {
|
||||
clearTimeout(timer)
|
||||
timer = null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { buildWebhookSignature, verifyWebhookSignature } from './webhook-signature.js'
|
||||
|
||||
test('webhook signature binds timestamp and raw body', () => {
|
||||
const rawBody = '{"eventId":"evt-1","items":[]}'
|
||||
const timestamp = '1783394219'
|
||||
const signature = buildWebhookSignature('secret-key', timestamp, rawBody)
|
||||
|
||||
assert.equal(
|
||||
verifyWebhookSignature({
|
||||
secret: 'secret-key',
|
||||
timestamp,
|
||||
rawBody,
|
||||
signature,
|
||||
nowSeconds: Number(timestamp),
|
||||
}),
|
||||
true,
|
||||
)
|
||||
assert.equal(
|
||||
verifyWebhookSignature({
|
||||
secret: 'secret-key',
|
||||
timestamp,
|
||||
rawBody: `${rawBody} `,
|
||||
signature,
|
||||
nowSeconds: Number(timestamp),
|
||||
}),
|
||||
false,
|
||||
)
|
||||
})
|
||||
|
||||
test('webhook signature rejects expired timestamps', () => {
|
||||
const timestamp = '1783394219'
|
||||
const rawBody = '{}'
|
||||
const signature = buildWebhookSignature('secret-key', timestamp, rawBody)
|
||||
|
||||
assert.equal(
|
||||
verifyWebhookSignature({
|
||||
secret: 'secret-key',
|
||||
timestamp,
|
||||
rawBody,
|
||||
signature,
|
||||
toleranceSeconds: 300,
|
||||
nowSeconds: Number(timestamp) + 301,
|
||||
}),
|
||||
false,
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,45 @@
|
||||
import { createHmac, timingSafeEqual } from 'node:crypto'
|
||||
|
||||
const SIGNATURE_PREFIX = 'sha256='
|
||||
const DEFAULT_TOLERANCE_SECONDS = 300
|
||||
|
||||
export function buildWebhookSignature(secret: string, timestamp: string, rawBody: string) {
|
||||
return (
|
||||
SIGNATURE_PREFIX + createHmac('sha256', secret).update(`${timestamp}.${rawBody}`).digest('hex')
|
||||
)
|
||||
}
|
||||
|
||||
export function verifyWebhookSignature(input: {
|
||||
secret: string
|
||||
timestamp: string
|
||||
rawBody: string
|
||||
signature: string
|
||||
toleranceSeconds?: number
|
||||
nowSeconds?: number
|
||||
}) {
|
||||
const secret = String(input.secret || '').trim()
|
||||
const timestamp = String(input.timestamp || '').trim()
|
||||
const signature = String(input.signature || '').trim()
|
||||
if (!secret || !timestamp || !signature) return false
|
||||
|
||||
const timestampSeconds = Number(timestamp)
|
||||
if (!Number.isInteger(timestampSeconds) || timestampSeconds <= 0) return false
|
||||
|
||||
const tolerance = Math.max(
|
||||
1,
|
||||
Math.trunc(Number(input.toleranceSeconds) || DEFAULT_TOLERANCE_SECONDS),
|
||||
)
|
||||
const nowSeconds = Math.trunc(Number(input.nowSeconds) || Date.now() / 1000)
|
||||
if (Math.abs(nowSeconds - timestampSeconds) > tolerance) return false
|
||||
|
||||
const expected = buildWebhookSignature(secret, timestamp, String(input.rawBody || ''))
|
||||
const expectedBuffer = Buffer.from(expected)
|
||||
const providedBuffer = Buffer.from(signature)
|
||||
if (expectedBuffer.length !== providedBuffer.length) return false
|
||||
return timingSafeEqual(expectedBuffer, providedBuffer)
|
||||
}
|
||||
|
||||
export function webhookToleranceSeconds() {
|
||||
const value = Number(process.env.PLATFORM_FULFILLMENT_WEBHOOK_TOLERANCE_SECONDS || 300)
|
||||
return Number.isFinite(value) && value > 0 ? Math.trunc(value) : DEFAULT_TOLERANCE_SECONDS
|
||||
}
|
||||
@@ -902,3 +902,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()
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user