feat(douyu): 新增客户领取与角色绑定工作台
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,
|
||||
|
||||
@@ -103,6 +103,7 @@ export type DevDouyuFulfillmentMockResult = {
|
||||
configId: number
|
||||
mappingId: number
|
||||
skuKey: string
|
||||
customerPath: string
|
||||
adminPath: string
|
||||
tips: string[]
|
||||
}
|
||||
@@ -976,6 +977,12 @@ export async function createDouyuFulfillmentMock(
|
||||
},
|
||||
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
|
||||
@@ -1004,6 +1011,7 @@ export async function createDouyuFulfillmentMock(
|
||||
platform: 'douyu',
|
||||
pipeline: 'order_service',
|
||||
...persisted,
|
||||
customerPath: `/coll/d/${encodeURIComponent(persisted.orderNo)}`,
|
||||
adminPath: `/admin/orders/${persisted.orderId}`,
|
||||
tips: [
|
||||
'订单已通过 upsertOrderFromSource 正式入库。',
|
||||
|
||||
@@ -0,0 +1,584 @@
|
||||
import type { PoolClient } from 'pg'
|
||||
|
||||
import { query, withTransaction } from '../../db/client.js'
|
||||
import { nowIso } from '../../utils/time.js'
|
||||
import { createHttpError } from '../../utils/http.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
|
||||
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
|
||||
completedAt: string | null
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
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 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
|
||||
? '客户资料与平台识别角色一致'
|
||||
: '客户资料与平台识别角色不一致,请修改资料或联系客服',
|
||||
}
|
||||
}
|
||||
|
||||
function statusForLive(live: LiveBindingState): string {
|
||||
if (live.executionStatus === 'completed') return 'completed'
|
||||
if (live.executionStatus === 'cancelled') return 'cancelled'
|
||||
if (live.bindConfirmed) return 'waiting_operator'
|
||||
if (live.bindReadyForConfirm) return 'role_ready'
|
||||
if (live.qrUrl) return 'qr_pending'
|
||||
if (live.executionStatus === 'manual_required') return 'manual_required'
|
||||
if (live.issueCode === 'binding_failed') return 'failed'
|
||||
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 applyLiveState(task: DouyuTaskRow, live: LiveBindingState) {
|
||||
const nextStatus = statusForLive(live)
|
||||
const now = nowIso()
|
||||
await withTransaction(async (client) => {
|
||||
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 $12 <> '' THEN COALESCE(binding_started_at, NOW())
|
||||
ELSE binding_started_at
|
||||
END,
|
||||
bound_at = CASE
|
||||
WHEN $13 THEN COALESCE(bound_at, NOW())
|
||||
ELSE bound_at
|
||||
END,
|
||||
completed_at = CASE
|
||||
WHEN $14 THEN COALESCE(completed_at, NOW())
|
||||
ELSE completed_at
|
||||
END,
|
||||
last_synced_at = NOW(),
|
||||
updated_at = $15
|
||||
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',
|
||||
now,
|
||||
],
|
||||
)
|
||||
if (nextStatus !== task.status) {
|
||||
await appendEvent(client, task.id, 'status_changed', 'integration', {
|
||||
fromStatus: task.status,
|
||||
toStatus: nextStatus,
|
||||
bindPhase: live.bindPhase,
|
||||
})
|
||||
}
|
||||
})
|
||||
const updated = await loadTask(task.id)
|
||||
return { task: updated, live, comparison: compareCustomerRole(updated, live) }
|
||||
}
|
||||
|
||||
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 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)
|
||||
}
|
||||
|
||||
export async function listDouyuFulfillmentTasks(
|
||||
input: {
|
||||
keyword?: unknown
|
||||
status?: unknown
|
||||
page?: unknown
|
||||
pageSize?: unknown
|
||||
} = {},
|
||||
) {
|
||||
await ensureDouyuFulfillmentTasks()
|
||||
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,39 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { compareCustomerRole } 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)
|
||||
})
|
||||
Reference in New Issue
Block a user