feat(douyu): 新增客户领取与角色绑定工作台
This commit is contained in:
@@ -11,6 +11,7 @@ import customerFulfillmentRouter from './routes/customer-fulfillment.js'
|
||||
import devMockConnectorRouter from './routes/dev-mock-connector.js'
|
||||
import dcAuthRouter from './routes/dcauth.js'
|
||||
import douyinMashidaRouter from './routes/douyin-mashida.js'
|
||||
import douyuFulfillmentRouter from './routes/douyu-fulfillment.js'
|
||||
import kuaishouIndustryRouter from './routes/kuaishou-industry.js'
|
||||
import open91Router from './routes/open-91.js'
|
||||
import pddExtensionRouter from './routes/pdd-extension.js'
|
||||
@@ -119,6 +120,7 @@ export function createApp({ startupState, isShutdownStarted, config }: CreateApp
|
||||
app.use('/api/v1/redeem', redeemRouter)
|
||||
app.use('/api/v1/claim', claimsRouter)
|
||||
app.use('/api/v1/customer-fulfillment', customerFulfillmentRouter)
|
||||
app.use('/api/v1/douyu-fulfillment', douyuFulfillmentRouter)
|
||||
app.use('/api/v1/semi-auto/injections', semiAutoInjectionsRouter)
|
||||
app.use('/api/v1/o', orderServiceRouter)
|
||||
app.use('/api/v1/pdd/extension', pddExtensionRouter)
|
||||
|
||||
@@ -10,7 +10,12 @@ const CURRENT_DIR = path.dirname(fileURLToPath(import.meta.url))
|
||||
const BACKEND_ROOT = path.resolve(CURRENT_DIR, '../..')
|
||||
const WORKSPACE_ROOT = process.env.WORKSPACE_ROOT || path.resolve(BACKEND_ROOT, '../..')
|
||||
|
||||
const SPECIAL_RUNTIME_ENV_NAMES = ['APP_BASE_URL', 'CLAIM_BASE_URL']
|
||||
const SPECIAL_RUNTIME_ENV_NAMES = [
|
||||
'APP_BASE_URL',
|
||||
'CLAIM_BASE_URL',
|
||||
'LIVE_HUB_PLATFORM_FULFILLMENT_URL',
|
||||
'PLATFORM_FULFILLMENT_INTEGRATION_KEY',
|
||||
]
|
||||
|
||||
const DEPLOYMENT_ONLY_ENV_NAMES = [
|
||||
'APP_DOMAIN',
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
-- 171_douyu_customer_fulfillment.sql
|
||||
--
|
||||
-- 斗鱼精英宝典客户领取:
|
||||
-- 1. 人工 SKU 配置可显式启用斗鱼客户绑定;
|
||||
-- 2. order_site 保存客户资料和 live-hub 安全状态投影;
|
||||
-- 3. 内部账号、CK、积分、二维码原始协议仍由 live-hub 负责。
|
||||
|
||||
ALTER TABLE manual_fulfillment_configs
|
||||
ADD COLUMN IF NOT EXISTS douyu_fulfillment_enabled BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
|
||||
COMMENT ON COLUMN manual_fulfillment_configs.douyu_fulfillment_enabled IS
|
||||
'是否启用斗鱼精英宝典客户领取与角色绑定';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS douyu_fulfillment_tasks (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
order_id BIGINT NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
|
||||
order_item_id BIGINT NOT NULL UNIQUE REFERENCES order_items(id) ON DELETE CASCADE,
|
||||
fulfillment_id BIGINT REFERENCES fulfillments(id) ON DELETE SET NULL,
|
||||
manual_fulfillment_config_id BIGINT
|
||||
REFERENCES manual_fulfillment_configs(id) ON DELETE SET NULL,
|
||||
live_session_id BIGINT,
|
||||
status TEXT NOT NULL DEFAULT 'waiting_profile'
|
||||
CHECK (status IN (
|
||||
'waiting_profile',
|
||||
'preparing',
|
||||
'qr_pending',
|
||||
'role_ready',
|
||||
'bound',
|
||||
'waiting_operator',
|
||||
'processing',
|
||||
'completed',
|
||||
'failed',
|
||||
'manual_required',
|
||||
'cancelled'
|
||||
)),
|
||||
customer_role_name TEXT NOT NULL DEFAULT '',
|
||||
customer_platform TEXT NOT NULL DEFAULT ''
|
||||
CHECK (customer_platform IN ('', 'wechat', 'qq')),
|
||||
customer_system TEXT NOT NULL DEFAULT ''
|
||||
CHECK (customer_system IN ('', 'ios', 'android')),
|
||||
binding_phase TEXT NOT NULL DEFAULT '',
|
||||
live_execution_status TEXT NOT NULL DEFAULT '',
|
||||
live_binding_status TEXT NOT NULL DEFAULT '',
|
||||
issue_code TEXT NOT NULL DEFAULT '',
|
||||
last_error TEXT NOT NULL DEFAULT '',
|
||||
bound_role_name TEXT NOT NULL DEFAULT '',
|
||||
bound_area_name TEXT NOT NULL DEFAULT '',
|
||||
bound_plat_name TEXT NOT NULL DEFAULT '',
|
||||
customer_link_opened_at TIMESTAMPTZ,
|
||||
binding_started_at TIMESTAMPTZ,
|
||||
bound_at TIMESTAMPTZ,
|
||||
completed_at TIMESTAMPTZ,
|
||||
last_synced_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_douyu_fulfillment_tasks_status
|
||||
ON douyu_fulfillment_tasks (status, updated_at DESC, id DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_douyu_fulfillment_tasks_order
|
||||
ON douyu_fulfillment_tasks (order_id, id);
|
||||
CREATE INDEX IF NOT EXISTS idx_douyu_fulfillment_tasks_live
|
||||
ON douyu_fulfillment_tasks (live_session_id)
|
||||
WHERE live_session_id IS NOT NULL;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS douyu_fulfillment_events (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
task_id BIGINT NOT NULL REFERENCES douyu_fulfillment_tasks(id) ON DELETE CASCADE,
|
||||
event_type TEXT NOT NULL,
|
||||
actor_type TEXT NOT NULL DEFAULT 'system'
|
||||
CHECK (actor_type IN ('system', 'customer', 'admin', 'integration')),
|
||||
actor_id TEXT NOT NULL DEFAULT '',
|
||||
detail_json JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_douyu_fulfillment_events_task
|
||||
ON douyu_fulfillment_events (task_id, id DESC);
|
||||
|
||||
COMMENT ON TABLE douyu_fulfillment_tasks IS
|
||||
'斗鱼精英宝典客户领取任务;客户资料以本表为准,绑定状态为 live-hub 安全投影';
|
||||
COMMENT ON COLUMN douyu_fulfillment_tasks.live_session_id IS
|
||||
'live-hub platform_fulfillment_tasks.id;不得保存内部账号或 CK';
|
||||
@@ -6,6 +6,7 @@ import costCenterRouter from './admin/cost-center.js'
|
||||
import dashboardRouter from './admin/dashboard.js'
|
||||
import devMockRouter from './admin/dev-mock.js'
|
||||
import douyinMashidaRouter from './admin/douyin-mashida.js'
|
||||
import douyuFulfillmentRouter from './admin/douyu-fulfillment.js'
|
||||
import financeRouter from './admin/finance.js'
|
||||
import fulfillmentChannelRouter from './admin/fulfillment-channel.js'
|
||||
import financeLedgerRouter from './admin/finance-ledger.js'
|
||||
@@ -38,6 +39,7 @@ router.use(fundRouter)
|
||||
router.use(usersRouter)
|
||||
router.use(rbacRouter)
|
||||
router.use(semiAutoRouter)
|
||||
router.use(douyuFulfillmentRouter)
|
||||
router.use(auditLogsRouter)
|
||||
router.use(platformConfigRouter)
|
||||
router.use(kuaishouIndustryRouter)
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { Router } from 'express'
|
||||
|
||||
import {
|
||||
ensureDouyuFulfillmentTasks,
|
||||
getDouyuFulfillmentDetail,
|
||||
listDouyuFulfillmentTasks,
|
||||
refreshDouyuCustomerBinding,
|
||||
startDouyuCustomerBinding,
|
||||
} from '../../services/douyu-fulfillment/douyu-fulfillment-service.js'
|
||||
import { createJsonHandler, requireAdminRoles } from './session.js'
|
||||
|
||||
const router = Router()
|
||||
|
||||
router.use('/douyu-fulfillment', requireAdminRoles(['admin', 'operator', 'support']))
|
||||
|
||||
router.get(
|
||||
'/douyu-fulfillment/tasks',
|
||||
createJsonHandler((req) => listDouyuFulfillmentTasks(req.query as Record<string, unknown>), {
|
||||
successMessage: 'ok',
|
||||
errorMessage: '读取斗鱼领取任务失败',
|
||||
scope: '[admin/douyu-fulfillment/tasks]',
|
||||
}),
|
||||
)
|
||||
|
||||
router.post(
|
||||
'/douyu-fulfillment/sync',
|
||||
createJsonHandler(() => ensureDouyuFulfillmentTasks(), {
|
||||
successMessage: '斗鱼领取任务已同步',
|
||||
errorMessage: '同步斗鱼领取任务失败',
|
||||
scope: '[admin/douyu-fulfillment/sync]',
|
||||
audit: () => ({
|
||||
action: 'douyu_fulfillment_synced',
|
||||
targetType: 'douyu_fulfillment_task',
|
||||
targetId: 'all',
|
||||
data: {},
|
||||
}),
|
||||
}),
|
||||
)
|
||||
|
||||
router.get(
|
||||
'/douyu-fulfillment/tasks/:orderNo',
|
||||
createJsonHandler((req) => getDouyuFulfillmentDetail(String(req.params.orderNo || '')), {
|
||||
successMessage: 'ok',
|
||||
errorMessage: '读取斗鱼领取详情失败',
|
||||
scope: '[admin/douyu-fulfillment/tasks/:orderNo]',
|
||||
}),
|
||||
)
|
||||
|
||||
router.post(
|
||||
'/douyu-fulfillment/tasks/:orderNo/binding/refresh',
|
||||
createJsonHandler((req) => refreshDouyuCustomerBinding(String(req.params.orderNo || '')), {
|
||||
successMessage: '绑定状态已刷新',
|
||||
errorMessage: '刷新斗鱼绑定状态失败',
|
||||
scope: '[admin/douyu-fulfillment/tasks/:orderNo/binding/refresh]',
|
||||
}),
|
||||
)
|
||||
|
||||
router.post(
|
||||
'/douyu-fulfillment/tasks/:orderNo/binding/start',
|
||||
createJsonHandler(
|
||||
(req) =>
|
||||
startDouyuCustomerBinding(String(req.params.orderNo || ''), req.body?.forceRefresh === true),
|
||||
{
|
||||
successMessage: '绑定二维码已重新准备',
|
||||
errorMessage: '重新生成斗鱼绑定二维码失败',
|
||||
scope: '[admin/douyu-fulfillment/tasks/:orderNo/binding/start]',
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
export default router
|
||||
@@ -0,0 +1,64 @@
|
||||
import { Router } from 'express'
|
||||
|
||||
import {
|
||||
confirmDouyuCustomerBinding,
|
||||
getCustomerDouyuFulfillment,
|
||||
refreshDouyuCustomerBinding,
|
||||
saveDouyuCustomerProfile,
|
||||
startDouyuCustomerBinding,
|
||||
} from '../services/douyu-fulfillment/douyu-fulfillment-service.js'
|
||||
import { createRouteHandler } from '../utils/http.js'
|
||||
|
||||
const router = Router()
|
||||
|
||||
router.get(
|
||||
'/:orderNo',
|
||||
createRouteHandler((req) => getCustomerDouyuFulfillment(String(req.params.orderNo || '')), {
|
||||
errorMessage: '读取斗鱼领取信息失败',
|
||||
scope: '[douyu-fulfillment/:orderNo]',
|
||||
}),
|
||||
)
|
||||
|
||||
router.post(
|
||||
'/:orderNo/profile',
|
||||
createRouteHandler(
|
||||
(req) => saveDouyuCustomerProfile(String(req.params.orderNo || ''), req.body || {}),
|
||||
{
|
||||
successMessage: '游戏资料已保存',
|
||||
errorMessage: '保存游戏资料失败',
|
||||
scope: '[douyu-fulfillment/:orderNo/profile]',
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
router.post(
|
||||
'/:orderNo/binding/start',
|
||||
createRouteHandler(
|
||||
(req) =>
|
||||
startDouyuCustomerBinding(String(req.params.orderNo || ''), req.body?.forceRefresh === true),
|
||||
{
|
||||
successMessage: '绑定二维码已准备',
|
||||
errorMessage: '生成绑定二维码失败',
|
||||
scope: '[douyu-fulfillment/:orderNo/binding/start]',
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
router.get(
|
||||
'/:orderNo/binding/status',
|
||||
createRouteHandler((req) => refreshDouyuCustomerBinding(String(req.params.orderNo || '')), {
|
||||
errorMessage: '刷新绑定状态失败',
|
||||
scope: '[douyu-fulfillment/:orderNo/binding/status]',
|
||||
}),
|
||||
)
|
||||
|
||||
router.post(
|
||||
'/:orderNo/binding/confirm',
|
||||
createRouteHandler((req) => confirmDouyuCustomerBinding(String(req.params.orderNo || '')), {
|
||||
successMessage: '角色绑定已确认',
|
||||
errorMessage: '确认角色绑定失败',
|
||||
scope: '[douyu-fulfillment/:orderNo/binding/confirm]',
|
||||
}),
|
||||
)
|
||||
|
||||
export default router
|
||||
@@ -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