feat(douyu): 新增客户领取与角色绑定工作台
This commit is contained in:
@@ -12,6 +12,8 @@ HTTP_TRUST_PROXY=1
|
|||||||
|
|
||||||
# Claim Links
|
# Claim Links
|
||||||
CLAIM_BASE_URL=http://localhost/h5
|
CLAIM_BASE_URL=http://localhost/h5
|
||||||
|
LIVE_HUB_PLATFORM_FULFILLMENT_URL=http://host.docker.internal:8800
|
||||||
|
PLATFORM_FULFILLMENT_INTEGRATION_KEY=
|
||||||
|
|
||||||
# Database
|
# Database
|
||||||
POSTGRES_DB=order_site
|
POSTGRES_DB=order_site
|
||||||
|
|||||||
@@ -24,6 +24,8 @@ HTTP_TRUST_PROXY=1
|
|||||||
|
|
||||||
# Claim Links
|
# Claim Links
|
||||||
CLAIM_BASE_URL=https://order.khhao.com/h5
|
CLAIM_BASE_URL=https://order.khhao.com/h5
|
||||||
|
LIVE_HUB_PLATFORM_FULFILLMENT_URL=https://live.khhao.com
|
||||||
|
PLATFORM_FULFILLMENT_INTEGRATION_KEY=
|
||||||
CLAIM_TOKEN_TTL_HOURS=0
|
CLAIM_TOKEN_TTL_HOURS=0
|
||||||
|
|
||||||
# Database
|
# Database
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import customerFulfillmentRouter from './routes/customer-fulfillment.js'
|
|||||||
import devMockConnectorRouter from './routes/dev-mock-connector.js'
|
import devMockConnectorRouter from './routes/dev-mock-connector.js'
|
||||||
import dcAuthRouter from './routes/dcauth.js'
|
import dcAuthRouter from './routes/dcauth.js'
|
||||||
import douyinMashidaRouter from './routes/douyin-mashida.js'
|
import douyinMashidaRouter from './routes/douyin-mashida.js'
|
||||||
|
import douyuFulfillmentRouter from './routes/douyu-fulfillment.js'
|
||||||
import kuaishouIndustryRouter from './routes/kuaishou-industry.js'
|
import kuaishouIndustryRouter from './routes/kuaishou-industry.js'
|
||||||
import open91Router from './routes/open-91.js'
|
import open91Router from './routes/open-91.js'
|
||||||
import pddExtensionRouter from './routes/pdd-extension.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/redeem', redeemRouter)
|
||||||
app.use('/api/v1/claim', claimsRouter)
|
app.use('/api/v1/claim', claimsRouter)
|
||||||
app.use('/api/v1/customer-fulfillment', customerFulfillmentRouter)
|
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/semi-auto/injections', semiAutoInjectionsRouter)
|
||||||
app.use('/api/v1/o', orderServiceRouter)
|
app.use('/api/v1/o', orderServiceRouter)
|
||||||
app.use('/api/v1/pdd/extension', pddExtensionRouter)
|
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 BACKEND_ROOT = path.resolve(CURRENT_DIR, '../..')
|
||||||
const WORKSPACE_ROOT = process.env.WORKSPACE_ROOT || path.resolve(BACKEND_ROOT, '../..')
|
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 = [
|
const DEPLOYMENT_ONLY_ENV_NAMES = [
|
||||||
'APP_DOMAIN',
|
'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 dashboardRouter from './admin/dashboard.js'
|
||||||
import devMockRouter from './admin/dev-mock.js'
|
import devMockRouter from './admin/dev-mock.js'
|
||||||
import douyinMashidaRouter from './admin/douyin-mashida.js'
|
import douyinMashidaRouter from './admin/douyin-mashida.js'
|
||||||
|
import douyuFulfillmentRouter from './admin/douyu-fulfillment.js'
|
||||||
import financeRouter from './admin/finance.js'
|
import financeRouter from './admin/finance.js'
|
||||||
import fulfillmentChannelRouter from './admin/fulfillment-channel.js'
|
import fulfillmentChannelRouter from './admin/fulfillment-channel.js'
|
||||||
import financeLedgerRouter from './admin/finance-ledger.js'
|
import financeLedgerRouter from './admin/finance-ledger.js'
|
||||||
@@ -38,6 +39,7 @@ router.use(fundRouter)
|
|||||||
router.use(usersRouter)
|
router.use(usersRouter)
|
||||||
router.use(rbacRouter)
|
router.use(rbacRouter)
|
||||||
router.use(semiAutoRouter)
|
router.use(semiAutoRouter)
|
||||||
|
router.use(douyuFulfillmentRouter)
|
||||||
router.use(auditLogsRouter)
|
router.use(auditLogsRouter)
|
||||||
router.use(platformConfigRouter)
|
router.use(platformConfigRouter)
|
||||||
router.use(kuaishouIndustryRouter)
|
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_enabled: boolean | null
|
||||||
config_semi_auto_platform: string | null
|
config_semi_auto_platform: string | null
|
||||||
config_semi_auto_config_json: unknown
|
config_semi_auto_config_json: unknown
|
||||||
|
config_douyu_fulfillment_enabled: boolean | null
|
||||||
}
|
}
|
||||||
|
|
||||||
type ManualChannelConfig = {
|
type ManualChannelConfig = {
|
||||||
@@ -353,7 +354,8 @@ export async function listManualSkus(input: Record<string, unknown> = {}) {
|
|||||||
cfg.channels_json AS config_channels_json,
|
cfg.channels_json AS config_channels_json,
|
||||||
cfg.semi_auto_enabled AS config_semi_auto_enabled,
|
cfg.semi_auto_enabled AS config_semi_auto_enabled,
|
||||||
cfg.semi_auto_platform AS config_semi_auto_platform,
|
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
|
FROM product_catalog p
|
||||||
JOIN internal_skus product_sku ON product_sku.id = p.internal_sku_id
|
JOIN internal_skus product_sku ON product_sku.id = p.internal_sku_id
|
||||||
LEFT JOIN LATERAL (
|
LEFT JOIN LATERAL (
|
||||||
@@ -468,6 +470,8 @@ export async function saveManualFulfillmentConfig(payload: JsonObject) {
|
|||||||
const enabled = payload.enabled === false ? false : true
|
const enabled = payload.enabled === false ? false : true
|
||||||
const note = optionalText(payload.note, 300)
|
const note = optionalText(payload.note, 300)
|
||||||
const semiAuto = normalizeSemiAutoConfig(payload)
|
const semiAuto = normalizeSemiAutoConfig(payload)
|
||||||
|
const douyuFulfillmentEnabled =
|
||||||
|
payload.douyuFulfillmentEnabled === true || payload.douyu_fulfillment_enabled === true
|
||||||
|
|
||||||
// 消耗积分为 0 = 成本不固定,客服确认履约时手填。
|
// 消耗积分为 0 = 成本不固定,客服确认履约时手填。
|
||||||
const costMode = primaryChannel.costMode
|
const costMode = primaryChannel.costMode
|
||||||
@@ -560,7 +564,8 @@ export async function saveManualFulfillmentConfig(payload: JsonObject) {
|
|||||||
semi_auto_enabled = $10,
|
semi_auto_enabled = $10,
|
||||||
semi_auto_platform = $11,
|
semi_auto_platform = $11,
|
||||||
semi_auto_config_json = $12::jsonb,
|
semi_auto_config_json = $12::jsonb,
|
||||||
updated_at = $13
|
douyu_fulfillment_enabled = $13,
|
||||||
|
updated_at = $14
|
||||||
WHERE id = $1
|
WHERE id = $1
|
||||||
RETURNING *`,
|
RETURNING *`,
|
||||||
[
|
[
|
||||||
@@ -576,6 +581,7 @@ export async function saveManualFulfillmentConfig(payload: JsonObject) {
|
|||||||
semiAuto.enabled,
|
semiAuto.enabled,
|
||||||
semiAuto.platform,
|
semiAuto.platform,
|
||||||
JSON.stringify(semiAuto.config),
|
JSON.stringify(semiAuto.config),
|
||||||
|
douyuFulfillmentEnabled,
|
||||||
now,
|
now,
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
@@ -584,10 +590,11 @@ export async function saveManualFulfillmentConfig(payload: JsonObject) {
|
|||||||
sku_key, canonical_product_id, platform_key, credit_quantity,
|
sku_key, canonical_product_id, platform_key, credit_quantity,
|
||||||
cost_mode, enabled, note, channels_json,
|
cost_mode, enabled, note, channels_json,
|
||||||
semi_auto_enabled, semi_auto_platform, semi_auto_config_json,
|
semi_auto_enabled, semi_auto_platform, semi_auto_config_json,
|
||||||
|
douyu_fulfillment_enabled,
|
||||||
created_at, updated_at
|
created_at, updated_at
|
||||||
) VALUES (
|
) VALUES (
|
||||||
$1, $2, $3, $4, $5, $6, $7, $8::jsonb,
|
$1, $2, $3, $4, $5, $6, $7, $8::jsonb,
|
||||||
$9, $10, $11::jsonb, $12, $12
|
$9, $10, $11::jsonb, $12, $13, $13
|
||||||
)
|
)
|
||||||
RETURNING *`,
|
RETURNING *`,
|
||||||
[
|
[
|
||||||
@@ -602,6 +609,7 @@ export async function saveManualFulfillmentConfig(payload: JsonObject) {
|
|||||||
semiAuto.enabled,
|
semiAuto.enabled,
|
||||||
semiAuto.platform,
|
semiAuto.platform,
|
||||||
JSON.stringify(semiAuto.config),
|
JSON.stringify(semiAuto.config),
|
||||||
|
douyuFulfillmentEnabled,
|
||||||
now,
|
now,
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
@@ -1077,6 +1085,7 @@ export async function getManualFulfillmentConfig(skuKey: string) {
|
|||||||
semi_auto_enabled: boolean
|
semi_auto_enabled: boolean
|
||||||
semi_auto_platform: string
|
semi_auto_platform: string
|
||||||
semi_auto_config_json: unknown
|
semi_auto_config_json: unknown
|
||||||
|
douyu_fulfillment_enabled: boolean
|
||||||
created_at: string
|
created_at: string
|
||||||
updated_at: string
|
updated_at: string
|
||||||
}>(
|
}>(
|
||||||
@@ -1208,6 +1217,7 @@ function mapManualSku(row: ManualSkuRow, unitPrices: Record<ManualPlatformKey, n
|
|||||||
semiAutoEnabled: row.config_semi_auto_enabled === true,
|
semiAutoEnabled: row.config_semi_auto_enabled === true,
|
||||||
semiAutoPlatform: String(row.config_semi_auto_platform || ''),
|
semiAutoPlatform: String(row.config_semi_auto_platform || ''),
|
||||||
semiAutoConfig: normalizeStoredSemiAutoConfig(row.config_semi_auto_config_json),
|
semiAutoConfig: normalizeStoredSemiAutoConfig(row.config_semi_auto_config_json),
|
||||||
|
douyuFulfillmentEnabled: row.config_douyu_fulfillment_enabled === true,
|
||||||
channels: mapConfiguredChannels(channels, unitPrices),
|
channels: mapConfiguredChannels(channels, unitPrices),
|
||||||
}
|
}
|
||||||
: null,
|
: null,
|
||||||
@@ -1228,6 +1238,7 @@ function mapManualConfig(
|
|||||||
semi_auto_enabled: boolean
|
semi_auto_enabled: boolean
|
||||||
semi_auto_platform: string
|
semi_auto_platform: string
|
||||||
semi_auto_config_json: unknown
|
semi_auto_config_json: unknown
|
||||||
|
douyu_fulfillment_enabled: boolean
|
||||||
created_at: string
|
created_at: string
|
||||||
updated_at: string
|
updated_at: string
|
||||||
},
|
},
|
||||||
@@ -1251,6 +1262,7 @@ function mapManualConfig(
|
|||||||
semiAutoEnabled: row.semi_auto_enabled === true,
|
semiAutoEnabled: row.semi_auto_enabled === true,
|
||||||
semiAutoPlatform: String(row.semi_auto_platform || ''),
|
semiAutoPlatform: String(row.semi_auto_platform || ''),
|
||||||
semiAutoConfig: normalizeStoredSemiAutoConfig(row.semi_auto_config_json),
|
semiAutoConfig: normalizeStoredSemiAutoConfig(row.semi_auto_config_json),
|
||||||
|
douyuFulfillmentEnabled: row.douyu_fulfillment_enabled === true,
|
||||||
channels: mapConfiguredChannels(channels, unitPrices),
|
channels: mapConfiguredChannels(channels, unitPrices),
|
||||||
note: row.note || '',
|
note: row.note || '',
|
||||||
createdAt: row.created_at,
|
createdAt: row.created_at,
|
||||||
|
|||||||
@@ -103,6 +103,7 @@ export type DevDouyuFulfillmentMockResult = {
|
|||||||
configId: number
|
configId: number
|
||||||
mappingId: number
|
mappingId: number
|
||||||
skuKey: string
|
skuKey: string
|
||||||
|
customerPath: string
|
||||||
adminPath: string
|
adminPath: string
|
||||||
tips: string[]
|
tips: string[]
|
||||||
}
|
}
|
||||||
@@ -976,6 +977,12 @@ export async function createDouyuFulfillmentMock(
|
|||||||
},
|
},
|
||||||
configNote: '开发 Mock:斗鱼直播账号履约',
|
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<{
|
const verification = await query<{
|
||||||
semi_auto_task_count: number
|
semi_auto_task_count: number
|
||||||
@@ -1004,6 +1011,7 @@ export async function createDouyuFulfillmentMock(
|
|||||||
platform: 'douyu',
|
platform: 'douyu',
|
||||||
pipeline: 'order_service',
|
pipeline: 'order_service',
|
||||||
...persisted,
|
...persisted,
|
||||||
|
customerPath: `/coll/d/${encodeURIComponent(persisted.orderNo)}`,
|
||||||
adminPath: `/admin/orders/${persisted.orderId}`,
|
adminPath: `/admin/orders/${persisted.orderId}`,
|
||||||
tips: [
|
tips: [
|
||||||
'订单已通过 upsertOrderFromSource 正式入库。',
|
'订单已通过 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)
|
||||||
|
})
|
||||||
@@ -12,7 +12,10 @@ import {
|
|||||||
|
|
||||||
import { getAdminRole, hasAdminSession } from '@/utils/admin-auth'
|
import { getAdminRole, hasAdminSession } from '@/utils/admin-auth'
|
||||||
import { isClaimPath, isH5ClaimPath } from '@/utils/claim-path'
|
import { isClaimPath, isH5ClaimPath } from '@/utils/claim-path'
|
||||||
import { isCustomerFulfillmentPath } from '@/utils/customer-fulfillment-link'
|
import {
|
||||||
|
isCustomerFulfillmentPath,
|
||||||
|
isDouyuFulfillmentPath,
|
||||||
|
} from '@/utils/customer-fulfillment-link'
|
||||||
import {
|
import {
|
||||||
isLegacySupplementPath,
|
isLegacySupplementPath,
|
||||||
isOrderServicePath,
|
isOrderServicePath,
|
||||||
@@ -44,6 +47,7 @@ const AdminPlatformShopsPage = lazy(() => import('@/pages/admin/platform/AdminPl
|
|||||||
const AdminTaskDetailPage = lazy(() => import('@/pages/admin/AdminTaskDetailPage'))
|
const AdminTaskDetailPage = lazy(() => import('@/pages/admin/AdminTaskDetailPage'))
|
||||||
const AdminTasksPage = lazy(() => import('@/pages/admin/AdminTasksPage'))
|
const AdminTasksPage = lazy(() => import('@/pages/admin/AdminTasksPage'))
|
||||||
const AdminSemiAutoTasksPage = lazy(() => import('@/pages/admin/AdminSemiAutoTasksPage'))
|
const AdminSemiAutoTasksPage = lazy(() => import('@/pages/admin/AdminSemiAutoTasksPage'))
|
||||||
|
const AdminDouyuFulfillmentPage = lazy(() => import('@/pages/admin/AdminDouyuFulfillmentPage'))
|
||||||
const AdminUsersPage = lazy(() => import('@/pages/admin/AdminUsersPage'))
|
const AdminUsersPage = lazy(() => import('@/pages/admin/AdminUsersPage'))
|
||||||
const AdminDevMockPage = lazy(() => import('@/pages/admin/AdminDevMockPage'))
|
const AdminDevMockPage = lazy(() => import('@/pages/admin/AdminDevMockPage'))
|
||||||
const AdminWorkerPlatformPage = lazy(() => import('@/pages/admin/AdminWorkerPlatformPage'))
|
const AdminWorkerPlatformPage = lazy(() => import('@/pages/admin/AdminWorkerPlatformPage'))
|
||||||
@@ -53,6 +57,7 @@ const OrderServicePage = lazy(() => import('@/pages/public/OrderServicePage'))
|
|||||||
const CustomerFulfillmentPage = lazy(
|
const CustomerFulfillmentPage = lazy(
|
||||||
() => import('@/pages/customer-fulfillment/CustomerFulfillmentPage'),
|
() => import('@/pages/customer-fulfillment/CustomerFulfillmentPage'),
|
||||||
)
|
)
|
||||||
|
const DouyuFulfillmentPage = lazy(() => import('@/pages/douyu-fulfillment/DouyuFulfillmentPage'))
|
||||||
const NotFoundPage = lazy(() => import('@/pages/NotFoundPage'))
|
const NotFoundPage = lazy(() => import('@/pages/NotFoundPage'))
|
||||||
const RedeemPage = lazy(() => import('@/pages/redeem/RedeemPage'))
|
const RedeemPage = lazy(() => import('@/pages/redeem/RedeemPage'))
|
||||||
const WorkerHallPage = lazy(() => import('@/pages/worker/WorkerHallPage'))
|
const WorkerHallPage = lazy(() => import('@/pages/worker/WorkerHallPage'))
|
||||||
@@ -136,6 +141,10 @@ export default function App() {
|
|||||||
return <OrderServiceApplication />
|
return <OrderServiceApplication />
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (isDouyuFulfillmentPath(window.location.pathname)) {
|
||||||
|
return <DouyuFulfillmentApplication />
|
||||||
|
}
|
||||||
|
|
||||||
if (isCustomerFulfillmentPath(window.location.pathname)) {
|
if (isCustomerFulfillmentPath(window.location.pathname)) {
|
||||||
return <CustomerFulfillmentApplication />
|
return <CustomerFulfillmentApplication />
|
||||||
}
|
}
|
||||||
@@ -152,6 +161,20 @@ export default function App() {
|
|||||||
return <AdminApplication />
|
return <AdminApplication />
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function DouyuFulfillmentApplication() {
|
||||||
|
useClearStrayHash()
|
||||||
|
return (
|
||||||
|
<BrowserRouter>
|
||||||
|
<Suspense fallback={<RouteLoading />}>
|
||||||
|
<Routes>
|
||||||
|
<Route path="/coll/d/:orderNo" element={<DouyuFulfillmentPage />} />
|
||||||
|
<Route path="*" element={<DouyuFulfillmentPage />} />
|
||||||
|
</Routes>
|
||||||
|
</Suspense>
|
||||||
|
</BrowserRouter>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
function OrderServiceApplication() {
|
function OrderServiceApplication() {
|
||||||
useClearStrayHash()
|
useClearStrayHash()
|
||||||
return (
|
return (
|
||||||
@@ -214,6 +237,7 @@ function AdminApplication() {
|
|||||||
<Route path="tasks" element={<AdminTasksPage />} />
|
<Route path="tasks" element={<AdminTasksPage />} />
|
||||||
<Route path="tasks/:taskId" element={<AdminTaskDetailPage />} />
|
<Route path="tasks/:taskId" element={<AdminTaskDetailPage />} />
|
||||||
<Route path="semi-auto-tasks" element={<AdminSemiAutoTasksPage />} />
|
<Route path="semi-auto-tasks" element={<AdminSemiAutoTasksPage />} />
|
||||||
|
<Route path="douyu-fulfillment" element={<AdminDouyuFulfillmentPage />} />
|
||||||
</Route>
|
</Route>
|
||||||
<Route element={<RequireRole roles={['admin', 'operator', 'support', 'finance']} />}>
|
<Route element={<RequireRole roles={['admin', 'operator', 'support', 'finance']} />}>
|
||||||
<Route path="orders" element={<AdminOrdersPage />} />
|
<Route path="orders" element={<AdminOrdersPage />} />
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import {
|
|||||||
SettingOutlined,
|
SettingOutlined,
|
||||||
SoundOutlined,
|
SoundOutlined,
|
||||||
TeamOutlined,
|
TeamOutlined,
|
||||||
|
ThunderboltOutlined,
|
||||||
TrophyOutlined,
|
TrophyOutlined,
|
||||||
UnorderedListOutlined,
|
UnorderedListOutlined,
|
||||||
UserOutlined,
|
UserOutlined,
|
||||||
@@ -252,6 +253,11 @@ export default function AdminLayout() {
|
|||||||
icon: <RobotOutlined />,
|
icon: <RobotOutlined />,
|
||||||
label: '半自动履约',
|
label: '半自动履约',
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
key: '/admin/douyu-fulfillment',
|
||||||
|
icon: <ThunderboltOutlined />,
|
||||||
|
label: '斗鱼领取',
|
||||||
|
},
|
||||||
{ key: '/admin/worker-platform', icon: <TrophyOutlined />, label: '接单平台' },
|
{ key: '/admin/worker-platform', icon: <TrophyOutlined />, label: '接单平台' },
|
||||||
{
|
{
|
||||||
key: '/admin/kuaishou-industry',
|
key: '/admin/kuaishou-industry',
|
||||||
@@ -274,6 +280,11 @@ export default function AdminLayout() {
|
|||||||
icon: <RobotOutlined />,
|
icon: <RobotOutlined />,
|
||||||
label: '半自动履约',
|
label: '半自动履约',
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
key: '/admin/douyu-fulfillment',
|
||||||
|
icon: <ThunderboltOutlined />,
|
||||||
|
label: '斗鱼领取',
|
||||||
|
},
|
||||||
{ key: '/admin/worker-platform', icon: <TrophyOutlined />, label: '接单平台' },
|
{ key: '/admin/worker-platform', icon: <TrophyOutlined />, label: '接单平台' },
|
||||||
{
|
{
|
||||||
key: '/admin/kuaishou-industry',
|
key: '/admin/kuaishou-industry',
|
||||||
|
|||||||
@@ -551,6 +551,8 @@ function AffiliateDashResultCard({ result }: { result: DevMockCreateResult }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function DouyuFulfillmentResultCard({ result }: { result: DevDouyuFulfillmentMockResult }) {
|
function DouyuFulfillmentResultCard({ result }: { result: DevDouyuFulfillmentMockResult }) {
|
||||||
|
const { message } = App.useApp()
|
||||||
|
const customerUrl = `${window.location.origin}${result.customerPath}`
|
||||||
return (
|
return (
|
||||||
<Card size="small" title="最近结果" extra={<Link to={result.adminPath}>打开订单</Link>}>
|
<Card size="small" title="最近结果" extra={<Link to={result.adminPath}>打开订单</Link>}>
|
||||||
<Row gutter={[12, 12]}>
|
<Row gutter={[12, 12]}>
|
||||||
@@ -576,6 +578,14 @@ function DouyuFulfillmentResultCard({ result }: { result: DevDouyuFulfillmentMoc
|
|||||||
<Typography.Text type="secondary">履约单</Typography.Text>
|
<Typography.Text type="secondary">履约单</Typography.Text>
|
||||||
<div>#{result.fulfillmentId}</div>
|
<div>#{result.fulfillmentId}</div>
|
||||||
</Col>
|
</Col>
|
||||||
|
<Col span={24}>
|
||||||
|
<Typography.Text type="secondary">客户领取链接</Typography.Text>
|
||||||
|
<Typography.Paragraph style={{ margin: '4px 0 0' }}>
|
||||||
|
<Typography.Link href={customerUrl} target="_blank" rel="noreferrer">
|
||||||
|
<LinkOutlined /> {customerUrl}
|
||||||
|
</Typography.Link>
|
||||||
|
</Typography.Paragraph>
|
||||||
|
</Col>
|
||||||
<Col span={24}>
|
<Col span={24}>
|
||||||
<Alert
|
<Alert
|
||||||
type="success"
|
type="success"
|
||||||
@@ -590,6 +600,22 @@ function DouyuFulfillmentResultCard({ result }: { result: DevDouyuFulfillmentMoc
|
|||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
</Col>
|
</Col>
|
||||||
|
<Col span={24}>
|
||||||
|
<Space wrap>
|
||||||
|
<Button
|
||||||
|
icon={<CopyOutlined />}
|
||||||
|
onClick={async () => {
|
||||||
|
await navigator.clipboard.writeText(customerUrl)
|
||||||
|
message.success('斗鱼客户领取链接已复制')
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
复制客户链接
|
||||||
|
</Button>
|
||||||
|
<Button type="primary" href={customerUrl} target="_blank">
|
||||||
|
打开客户领取页
|
||||||
|
</Button>
|
||||||
|
</Space>
|
||||||
|
</Col>
|
||||||
</Row>
|
</Row>
|
||||||
</Card>
|
</Card>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,390 @@
|
|||||||
|
import {
|
||||||
|
CopyOutlined,
|
||||||
|
LinkOutlined,
|
||||||
|
ReloadOutlined,
|
||||||
|
SyncOutlined,
|
||||||
|
ThunderboltOutlined,
|
||||||
|
} from '@ant-design/icons'
|
||||||
|
import {
|
||||||
|
Alert,
|
||||||
|
App,
|
||||||
|
Button,
|
||||||
|
Card,
|
||||||
|
Descriptions,
|
||||||
|
Drawer,
|
||||||
|
Input,
|
||||||
|
Select,
|
||||||
|
Space,
|
||||||
|
Tag,
|
||||||
|
Timeline,
|
||||||
|
Typography,
|
||||||
|
} from 'antd'
|
||||||
|
import type { TableColumnsType } from 'antd'
|
||||||
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { useState } from 'react'
|
||||||
|
|
||||||
|
import PageHeader from '@/components/admin/PageHeader'
|
||||||
|
import PercentTable from '@/components/common/PercentTable'
|
||||||
|
import {
|
||||||
|
fetchAdminDouyuFulfillmentDetail,
|
||||||
|
fetchAdminDouyuFulfillmentTasks,
|
||||||
|
refreshAdminDouyuBinding,
|
||||||
|
restartAdminDouyuBinding,
|
||||||
|
syncAdminDouyuFulfillmentTasks,
|
||||||
|
} from '@/services/admin'
|
||||||
|
import type { DouyuFulfillmentTask } from '@/types/douyu-fulfillment'
|
||||||
|
import { formatAdminDateTime } from '@/utils/admin-time'
|
||||||
|
|
||||||
|
const { Text } = Typography
|
||||||
|
|
||||||
|
const STATUS_LABELS: Record<string, string> = {
|
||||||
|
waiting_profile: '待客户填资料',
|
||||||
|
preparing: '准备账号',
|
||||||
|
qr_pending: '待扫码',
|
||||||
|
role_ready: '待确认角色',
|
||||||
|
bound: '角色已绑定',
|
||||||
|
waiting_operator: '待运营处理',
|
||||||
|
processing: '处理中',
|
||||||
|
completed: '已完成',
|
||||||
|
failed: '失败',
|
||||||
|
manual_required: '人工处理',
|
||||||
|
cancelled: '已取消',
|
||||||
|
}
|
||||||
|
|
||||||
|
const STATUS_COLORS: Record<string, string> = {
|
||||||
|
waiting_profile: 'blue',
|
||||||
|
preparing: 'gold',
|
||||||
|
qr_pending: 'cyan',
|
||||||
|
role_ready: 'orange',
|
||||||
|
bound: 'green',
|
||||||
|
waiting_operator: 'volcano',
|
||||||
|
processing: 'processing',
|
||||||
|
completed: 'success',
|
||||||
|
failed: 'error',
|
||||||
|
manual_required: 'warning',
|
||||||
|
cancelled: 'default',
|
||||||
|
}
|
||||||
|
|
||||||
|
const PLATFORM_LABELS: Record<string, string> = {
|
||||||
|
wechat: '微信',
|
||||||
|
qq: 'QQ',
|
||||||
|
}
|
||||||
|
|
||||||
|
const SYSTEM_LABELS: Record<string, string> = {
|
||||||
|
ios: '苹果',
|
||||||
|
android: '安卓',
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function AdminDouyuFulfillmentPage() {
|
||||||
|
const { message } = App.useApp()
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
const [keyword, setKeyword] = useState('')
|
||||||
|
const [status, setStatus] = useState('')
|
||||||
|
const [page, setPage] = useState(1)
|
||||||
|
const [pageSize, setPageSize] = useState(20)
|
||||||
|
const [detailOrderNo, setDetailOrderNo] = useState('')
|
||||||
|
|
||||||
|
const listQuery = useQuery({
|
||||||
|
queryKey: ['admin-douyu-fulfillment', keyword, status, page, pageSize],
|
||||||
|
queryFn: () =>
|
||||||
|
fetchAdminDouyuFulfillmentTasks({
|
||||||
|
keyword: keyword.trim() || undefined,
|
||||||
|
status: status || undefined,
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
}),
|
||||||
|
refetchInterval: 5000,
|
||||||
|
})
|
||||||
|
const detailQuery = useQuery({
|
||||||
|
queryKey: ['admin-douyu-fulfillment-detail', detailOrderNo],
|
||||||
|
queryFn: () => fetchAdminDouyuFulfillmentDetail(detailOrderNo),
|
||||||
|
enabled: Boolean(detailOrderNo),
|
||||||
|
refetchInterval: detailOrderNo ? 3000 : false,
|
||||||
|
})
|
||||||
|
|
||||||
|
const list = listQuery.data?.data.items || []
|
||||||
|
const pagination = listQuery.data?.data.pagination
|
||||||
|
const detail = detailQuery.data?.data
|
||||||
|
|
||||||
|
async function refreshAll() {
|
||||||
|
await Promise.all([
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['admin-douyu-fulfillment'] }),
|
||||||
|
detailOrderNo
|
||||||
|
? queryClient.invalidateQueries({
|
||||||
|
queryKey: ['admin-douyu-fulfillment-detail', detailOrderNo],
|
||||||
|
})
|
||||||
|
: Promise.resolve(),
|
||||||
|
])
|
||||||
|
}
|
||||||
|
|
||||||
|
const syncMutation = useMutation({
|
||||||
|
mutationFn: syncAdminDouyuFulfillmentTasks,
|
||||||
|
onSuccess: async (response) => {
|
||||||
|
message.success(`同步完成:新增 ${response.data.created},更新 ${response.data.updated}`)
|
||||||
|
await refreshAll()
|
||||||
|
},
|
||||||
|
onError: (error) => message.error(error instanceof Error ? error.message : '同步失败'),
|
||||||
|
})
|
||||||
|
const refreshMutation = useMutation({
|
||||||
|
mutationFn: refreshAdminDouyuBinding,
|
||||||
|
onSuccess: async () => {
|
||||||
|
message.success('绑定状态已刷新')
|
||||||
|
await refreshAll()
|
||||||
|
},
|
||||||
|
onError: (error) => message.error(error instanceof Error ? error.message : '刷新失败'),
|
||||||
|
})
|
||||||
|
const restartMutation = useMutation({
|
||||||
|
mutationFn: restartAdminDouyuBinding,
|
||||||
|
onSuccess: async () => {
|
||||||
|
message.success('已重新生成绑定二维码')
|
||||||
|
await refreshAll()
|
||||||
|
},
|
||||||
|
onError: (error) => message.error(error instanceof Error ? error.message : '重新生成失败'),
|
||||||
|
})
|
||||||
|
|
||||||
|
async function copyLink(task: DouyuFulfillmentTask) {
|
||||||
|
const url = `${window.location.origin}${task.linkPath}`
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(url)
|
||||||
|
message.success('客户领取链接已复制')
|
||||||
|
} catch {
|
||||||
|
message.error('复制失败,请手动复制')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const columns: TableColumnsType<DouyuFulfillmentTask> = [
|
||||||
|
{
|
||||||
|
title: '订单 / 商品',
|
||||||
|
key: 'order',
|
||||||
|
width: 280,
|
||||||
|
render: (_, task) => (
|
||||||
|
<Space direction="vertical" size={2}>
|
||||||
|
<Text strong>{task.platform_order_id}</Text>
|
||||||
|
<Text>{task.product_name || task.sku_name || task.sku_code}</Text>
|
||||||
|
<Text type="secondary">订单项 #{task.order_item_id}</Text>
|
||||||
|
</Space>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '客户资料',
|
||||||
|
key: 'profile',
|
||||||
|
width: 220,
|
||||||
|
render: (_, task) =>
|
||||||
|
task.customer_role_name ? (
|
||||||
|
<Space direction="vertical" size={2}>
|
||||||
|
<Text strong>{task.customer_role_name}</Text>
|
||||||
|
<Text type="secondary">
|
||||||
|
{PLATFORM_LABELS[task.customer_platform] || '-'} ·{' '}
|
||||||
|
{SYSTEM_LABELS[task.customer_system] || '-'}
|
||||||
|
</Text>
|
||||||
|
</Space>
|
||||||
|
) : (
|
||||||
|
<Text type="secondary">待客户填写</Text>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '绑定角色',
|
||||||
|
key: 'boundRole',
|
||||||
|
width: 220,
|
||||||
|
render: (_, task) =>
|
||||||
|
task.bound_role_name ? (
|
||||||
|
<Space direction="vertical" size={2}>
|
||||||
|
<Text strong>{task.bound_role_name}</Text>
|
||||||
|
<Text type="secondary">
|
||||||
|
{[task.bound_area_name, task.bound_plat_name].filter(Boolean).join(' · ') || '-'}
|
||||||
|
</Text>
|
||||||
|
</Space>
|
||||||
|
) : (
|
||||||
|
<Text type="secondary">未识别</Text>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '状态',
|
||||||
|
dataIndex: 'status',
|
||||||
|
width: 140,
|
||||||
|
render: (value: string) => (
|
||||||
|
<Tag color={STATUS_COLORS[value] || 'default'}>{STATUS_LABELS[value] || value}</Tag>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '更新时间',
|
||||||
|
dataIndex: 'updated_at',
|
||||||
|
width: 165,
|
||||||
|
render: (value: string) => formatAdminDateTime(value),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '操作',
|
||||||
|
key: 'actions',
|
||||||
|
width: 360,
|
||||||
|
render: (_, task) => (
|
||||||
|
<Space wrap>
|
||||||
|
<Button size="small" onClick={() => setDetailOrderNo(task.platform_order_id)}>
|
||||||
|
详情
|
||||||
|
</Button>
|
||||||
|
<Button size="small" icon={<CopyOutlined />} onClick={() => void copyLink(task)}>
|
||||||
|
客户链接
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
icon={<ReloadOutlined />}
|
||||||
|
loading={refreshMutation.isPending}
|
||||||
|
onClick={() => refreshMutation.mutate(task.platform_order_id)}
|
||||||
|
>
|
||||||
|
刷新绑定
|
||||||
|
</Button>
|
||||||
|
</Space>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="page-stack">
|
||||||
|
<PageHeader
|
||||||
|
title="斗鱼领取工作台"
|
||||||
|
description="客户提交游戏资料并完成角色绑定;内部账号与兑换仍在直播账号履约工作台处理。"
|
||||||
|
/>
|
||||||
|
<Alert
|
||||||
|
type="info"
|
||||||
|
showIcon
|
||||||
|
message="客户领取链接格式"
|
||||||
|
description="域名/coll/d/订单号。客户资料和绑定状态会同步到 live-hub,但不会向客户展示 CK、积分或账号信息。"
|
||||||
|
/>
|
||||||
|
<Card size="small">
|
||||||
|
<Space wrap style={{ marginBottom: 16 }}>
|
||||||
|
<Input.Search
|
||||||
|
allowClear
|
||||||
|
placeholder="订单号 / 商品 / 角色名"
|
||||||
|
value={keyword}
|
||||||
|
onChange={(event) => {
|
||||||
|
setKeyword(event.target.value)
|
||||||
|
setPage(1)
|
||||||
|
}}
|
||||||
|
style={{ width: 300 }}
|
||||||
|
/>
|
||||||
|
<Select
|
||||||
|
allowClear
|
||||||
|
placeholder="全部状态"
|
||||||
|
value={status || undefined}
|
||||||
|
onChange={(value) => {
|
||||||
|
setStatus(value || '')
|
||||||
|
setPage(1)
|
||||||
|
}}
|
||||||
|
options={Object.entries(STATUS_LABELS).map(([value, label]) => ({
|
||||||
|
value,
|
||||||
|
label,
|
||||||
|
}))}
|
||||||
|
style={{ width: 160 }}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
type="primary"
|
||||||
|
icon={<SyncOutlined />}
|
||||||
|
loading={syncMutation.isPending}
|
||||||
|
onClick={() => syncMutation.mutate()}
|
||||||
|
>
|
||||||
|
同步斗鱼订单
|
||||||
|
</Button>
|
||||||
|
<Button icon={<ReloadOutlined />} onClick={() => void listQuery.refetch()}>
|
||||||
|
刷新
|
||||||
|
</Button>
|
||||||
|
</Space>
|
||||||
|
<PercentTable<DouyuFulfillmentTask>
|
||||||
|
rowKey="id"
|
||||||
|
loading={listQuery.isLoading}
|
||||||
|
columns={columns}
|
||||||
|
dataSource={list}
|
||||||
|
scroll={{ x: 1250 }}
|
||||||
|
pagination={{
|
||||||
|
current: pagination?.page || page,
|
||||||
|
pageSize: pagination?.pageSize || pageSize,
|
||||||
|
total: pagination?.total || 0,
|
||||||
|
showSizeChanger: true,
|
||||||
|
onChange: (nextPage, nextPageSize) => {
|
||||||
|
setPage(nextPage)
|
||||||
|
setPageSize(nextPageSize)
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Drawer
|
||||||
|
open={Boolean(detailOrderNo)}
|
||||||
|
width="min(980px, 94vw)"
|
||||||
|
title={detail ? `斗鱼领取详情 · ${detail.task.platform_order_id}` : '斗鱼领取详情'}
|
||||||
|
onClose={() => setDetailOrderNo('')}
|
||||||
|
>
|
||||||
|
{detailQuery.isLoading || !detail ? (
|
||||||
|
<Text type="secondary">加载中...</Text>
|
||||||
|
) : (
|
||||||
|
<Space direction="vertical" size={16} style={{ width: '100%' }}>
|
||||||
|
<Alert
|
||||||
|
type={detail.comparison.matched ? 'success' : 'warning'}
|
||||||
|
showIcon
|
||||||
|
message={STATUS_LABELS[detail.task.status] || detail.task.status}
|
||||||
|
description={detail.comparison.message || detail.live.message}
|
||||||
|
/>
|
||||||
|
<Descriptions bordered size="small" column={2}>
|
||||||
|
<Descriptions.Item label="订单号" span={2}>
|
||||||
|
{detail.task.platform_order_id}
|
||||||
|
</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="商品" span={2}>
|
||||||
|
{detail.task.product_name || detail.task.sku_name}
|
||||||
|
</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="客户角色">
|
||||||
|
{detail.task.customer_role_name || '-'}
|
||||||
|
</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="客户平台">
|
||||||
|
{PLATFORM_LABELS[detail.task.customer_platform] || '-'} ·{' '}
|
||||||
|
{SYSTEM_LABELS[detail.task.customer_system] || '-'}
|
||||||
|
</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="平台角色">{detail.live.roleName || '-'}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="平台渠道">
|
||||||
|
{[detail.live.areaName, detail.live.platName].filter(Boolean).join(' · ') || '-'}
|
||||||
|
</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="绑定阶段" span={2}>
|
||||||
|
{detail.task.binding_phase || '-'}
|
||||||
|
</Descriptions.Item>
|
||||||
|
</Descriptions>
|
||||||
|
<Space wrap>
|
||||||
|
<Button icon={<CopyOutlined />} onClick={() => void copyLink(detail.task)}>
|
||||||
|
复制客户链接
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
icon={<ReloadOutlined />}
|
||||||
|
loading={refreshMutation.isPending}
|
||||||
|
onClick={() => refreshMutation.mutate(detail.task.platform_order_id)}
|
||||||
|
>
|
||||||
|
刷新绑定
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="primary"
|
||||||
|
icon={<ThunderboltOutlined />}
|
||||||
|
loading={restartMutation.isPending}
|
||||||
|
onClick={() => restartMutation.mutate(detail.task.platform_order_id)}
|
||||||
|
>
|
||||||
|
重新生成二维码
|
||||||
|
</Button>
|
||||||
|
<Button icon={<LinkOutlined />} href={detail.linkPath} target="_blank">
|
||||||
|
打开客户页
|
||||||
|
</Button>
|
||||||
|
</Space>
|
||||||
|
<Card size="small" title="事件时间线">
|
||||||
|
<Timeline
|
||||||
|
items={detail.events.map((event) => ({
|
||||||
|
color: event.event_type.includes('failed') ? 'red' : 'blue',
|
||||||
|
children: (
|
||||||
|
<Space direction="vertical" size={2}>
|
||||||
|
<Text strong>{event.event_type}</Text>
|
||||||
|
<Text type="secondary">
|
||||||
|
{formatAdminDateTime(event.created_at)} · {event.actor_type}
|
||||||
|
</Text>
|
||||||
|
</Space>
|
||||||
|
),
|
||||||
|
}))}
|
||||||
|
/>
|
||||||
|
</Card>
|
||||||
|
</Space>
|
||||||
|
)}
|
||||||
|
</Drawer>
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -68,6 +68,7 @@ type ConfigFormValues = {
|
|||||||
note?: string
|
note?: string
|
||||||
semiAutoEnabled?: boolean
|
semiAutoEnabled?: boolean
|
||||||
semiAutoPlatform?: '' | 'huya' | 'weibo'
|
semiAutoPlatform?: '' | 'huya' | 'weibo'
|
||||||
|
douyuFulfillmentEnabled?: boolean
|
||||||
semiAutoConfig?: {
|
semiAutoConfig?: {
|
||||||
pageTitle?: string
|
pageTitle?: string
|
||||||
pageDescription?: string
|
pageDescription?: string
|
||||||
@@ -153,6 +154,7 @@ export function ManualSkuConfigPanel() {
|
|||||||
semiAutoEnabled: values.semiAutoEnabled === true,
|
semiAutoEnabled: values.semiAutoEnabled === true,
|
||||||
semiAutoPlatform: values.semiAutoEnabled ? values.semiAutoPlatform || '' : '',
|
semiAutoPlatform: values.semiAutoEnabled ? values.semiAutoPlatform || '' : '',
|
||||||
semiAutoConfig: values.semiAutoConfig || {},
|
semiAutoConfig: values.semiAutoConfig || {},
|
||||||
|
douyuFulfillmentEnabled: values.douyuFulfillmentEnabled === true,
|
||||||
}),
|
}),
|
||||||
onSuccess: (response) => {
|
onSuccess: (response) => {
|
||||||
const summary = response.data.syncSummary
|
const summary = response.data.syncSummary
|
||||||
@@ -215,6 +217,7 @@ export function ManualSkuConfigPanel() {
|
|||||||
semiAutoEnabled: item.config?.semiAutoEnabled === true,
|
semiAutoEnabled: item.config?.semiAutoEnabled === true,
|
||||||
semiAutoPlatform: item.config?.semiAutoPlatform || '',
|
semiAutoPlatform: item.config?.semiAutoPlatform || '',
|
||||||
semiAutoConfig: item.config?.semiAutoConfig || {},
|
semiAutoConfig: item.config?.semiAutoConfig || {},
|
||||||
|
douyuFulfillmentEnabled: item.config?.douyuFulfillmentEnabled === true,
|
||||||
})
|
})
|
||||||
setModalOpen(true)
|
setModalOpen(true)
|
||||||
}
|
}
|
||||||
@@ -229,6 +232,7 @@ export function ManualSkuConfigPanel() {
|
|||||||
semiAutoEnabled: false,
|
semiAutoEnabled: false,
|
||||||
semiAutoPlatform: '',
|
semiAutoPlatform: '',
|
||||||
semiAutoConfig: {},
|
semiAutoConfig: {},
|
||||||
|
douyuFulfillmentEnabled: false,
|
||||||
})
|
})
|
||||||
setModalOpen(true)
|
setModalOpen(true)
|
||||||
}
|
}
|
||||||
@@ -697,6 +701,14 @@ export function ManualSkuConfigPanel() {
|
|||||||
) : null
|
) : null
|
||||||
}
|
}
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
|
<Form.Item
|
||||||
|
name="douyuFulfillmentEnabled"
|
||||||
|
label="启用斗鱼精英宝典领取"
|
||||||
|
valuePropName="checked"
|
||||||
|
extra="客户通过 域名/coll/d/订单号 提交资料并扫码绑定角色;内部账号和兑换仍在直播账号履约工作台处理。"
|
||||||
|
>
|
||||||
|
<Switch />
|
||||||
|
</Form.Item>
|
||||||
</Card>
|
</Card>
|
||||||
<Form.Item name="note" label="备注">
|
<Form.Item name="note" label="备注">
|
||||||
<Input.TextArea rows={2} maxLength={300} showCount />
|
<Input.TextArea rows={2} maxLength={300} showCount />
|
||||||
|
|||||||
@@ -0,0 +1,492 @@
|
|||||||
|
import {
|
||||||
|
CheckCircleFilled,
|
||||||
|
ExclamationCircleOutlined,
|
||||||
|
LoadingOutlined,
|
||||||
|
QrcodeOutlined,
|
||||||
|
ReloadOutlined,
|
||||||
|
} from '@ant-design/icons'
|
||||||
|
import { Alert, App, Button, Image, Input, Progress, Segmented, Space, Spin } from 'antd'
|
||||||
|
import QRCode from 'qrcode'
|
||||||
|
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
|
||||||
|
import { useParams } from 'react-router'
|
||||||
|
|
||||||
|
import {
|
||||||
|
confirmDouyuBinding,
|
||||||
|
fetchDouyuFulfillment,
|
||||||
|
pollDouyuBinding,
|
||||||
|
saveDouyuProfile,
|
||||||
|
startDouyuBinding,
|
||||||
|
} from '@/services/douyu-fulfillment'
|
||||||
|
import type {
|
||||||
|
DouyuCustomerFulfillment,
|
||||||
|
DouyuCustomerPlatform,
|
||||||
|
DouyuCustomerSystem,
|
||||||
|
} from '@/types/douyu-fulfillment'
|
||||||
|
import { formatAdminDateTime } from '@/utils/admin-time'
|
||||||
|
|
||||||
|
const POLL_INTERVAL_MS = 3000
|
||||||
|
|
||||||
|
const STATUS_LABELS: Record<string, string> = {
|
||||||
|
waiting_profile: '等待填写资料',
|
||||||
|
preparing: '正在准备账号',
|
||||||
|
qr_pending: '等待扫码绑定',
|
||||||
|
role_ready: '请确认游戏角色',
|
||||||
|
bound: '角色已绑定',
|
||||||
|
waiting_operator: '等待运营处理',
|
||||||
|
processing: '正在兑换',
|
||||||
|
completed: '领取完成',
|
||||||
|
failed: '处理失败',
|
||||||
|
manual_required: '等待人工处理',
|
||||||
|
cancelled: '订单已取消',
|
||||||
|
}
|
||||||
|
|
||||||
|
function platformLabel(value: string) {
|
||||||
|
if (value === 'wechat') return '微信'
|
||||||
|
if (value === 'qq') return 'QQ'
|
||||||
|
return '未填写'
|
||||||
|
}
|
||||||
|
|
||||||
|
function systemLabel(value: string) {
|
||||||
|
if (value === 'ios') return '苹果'
|
||||||
|
if (value === 'android') return '安卓'
|
||||||
|
return '未填写'
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function DouyuFulfillmentPage() {
|
||||||
|
const { message } = App.useApp()
|
||||||
|
const { orderNo = '' } = useParams<{ orderNo: string }>()
|
||||||
|
const [data, setData] = useState<DouyuCustomerFulfillment | null>(null)
|
||||||
|
const [loading, setLoading] = useState(true)
|
||||||
|
const [loadError, setLoadError] = useState('')
|
||||||
|
const [saving, setSaving] = useState(false)
|
||||||
|
const [bindingLoading, setBindingLoading] = useState(false)
|
||||||
|
const [roleName, setRoleName] = useState('')
|
||||||
|
const [platform, setPlatform] = useState<DouyuCustomerPlatform>('wechat')
|
||||||
|
const [system, setSystem] = useState<DouyuCustomerSystem>('android')
|
||||||
|
const [qrImage, setQrImage] = useState('')
|
||||||
|
const [nowMs, setNowMs] = useState(0)
|
||||||
|
const autoStartRef = useRef('')
|
||||||
|
|
||||||
|
const applyData = useCallback((next: DouyuCustomerFulfillment) => {
|
||||||
|
setData(next)
|
||||||
|
setRoleName((current) => current || next.task.customer_role_name || '')
|
||||||
|
if (next.task.customer_platform === 'qq' || next.task.customer_platform === 'wechat') {
|
||||||
|
setPlatform(next.task.customer_platform)
|
||||||
|
}
|
||||||
|
if (next.task.customer_system === 'ios' || next.task.customer_system === 'android') {
|
||||||
|
setSystem(next.task.customer_system)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const load = useCallback(
|
||||||
|
async (silent = false) => {
|
||||||
|
if (!orderNo) {
|
||||||
|
setLoadError('订单号无效')
|
||||||
|
setLoading(false)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!silent) setLoading(true)
|
||||||
|
try {
|
||||||
|
const response = await fetchDouyuFulfillment(orderNo)
|
||||||
|
applyData(response.data)
|
||||||
|
setLoadError('')
|
||||||
|
} catch (error) {
|
||||||
|
if (!silent) {
|
||||||
|
setLoadError(error instanceof Error ? error.message : '读取订单失败')
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if (!silent) setLoading(false)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[applyData, orderNo],
|
||||||
|
)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void load()
|
||||||
|
}, [load])
|
||||||
|
|
||||||
|
const task = data?.task
|
||||||
|
const live = data?.live
|
||||||
|
const needsProfile = Boolean(task && !task.customer_role_name)
|
||||||
|
const activeBinding = Boolean(
|
||||||
|
task &&
|
||||||
|
!needsProfile &&
|
||||||
|
!['completed', 'cancelled'].includes(task.status) &&
|
||||||
|
!live?.bindConfirmed,
|
||||||
|
)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!activeBinding || !orderNo) return
|
||||||
|
const timer = window.setInterval(() => {
|
||||||
|
void pollDouyuBinding(orderNo)
|
||||||
|
.then((response) => applyData(response.data))
|
||||||
|
.catch(() => undefined)
|
||||||
|
}, POLL_INTERVAL_MS)
|
||||||
|
return () => window.clearInterval(timer)
|
||||||
|
}, [activeBinding, applyData, orderNo])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const url = live?.qrUrl || ''
|
||||||
|
if (!url) {
|
||||||
|
setQrImage('')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
void QRCode.toDataURL(url, {
|
||||||
|
width: 320,
|
||||||
|
margin: 2,
|
||||||
|
color: { dark: '#111827', light: '#ffffff' },
|
||||||
|
}).then(setQrImage)
|
||||||
|
}, [live?.qrUrl])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const tick = () => setNowMs(Date.now())
|
||||||
|
tick()
|
||||||
|
const timer = window.setInterval(tick, 1000)
|
||||||
|
return () => window.clearInterval(timer)
|
||||||
|
}, [live?.qrExpiresAt])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!task || !live || needsProfile || live.qrUrl || live.bindConfirmed) return
|
||||||
|
if (!live.accountReady) return
|
||||||
|
if (task.status !== 'preparing' && task.status !== 'waiting_profile') return
|
||||||
|
if (autoStartRef.current === orderNo) return
|
||||||
|
autoStartRef.current = orderNo
|
||||||
|
let cancelled = false
|
||||||
|
setBindingLoading(true)
|
||||||
|
void startDouyuBinding(orderNo)
|
||||||
|
.then((response) => {
|
||||||
|
if (!cancelled) applyData(response.data)
|
||||||
|
})
|
||||||
|
.catch(() => undefined)
|
||||||
|
.finally(() => {
|
||||||
|
if (!cancelled) setBindingLoading(false)
|
||||||
|
})
|
||||||
|
return () => {
|
||||||
|
cancelled = true
|
||||||
|
}
|
||||||
|
}, [applyData, live, needsProfile, orderNo, task])
|
||||||
|
|
||||||
|
const expiresInSeconds = useMemo(() => {
|
||||||
|
const raw = live?.qrExpiresAt || ''
|
||||||
|
const expiresAt = raw ? Date.parse(raw) : 0
|
||||||
|
if (!expiresAt || Number.isNaN(expiresAt)) return 0
|
||||||
|
return Math.max(0, Math.floor((expiresAt - nowMs) / 1000))
|
||||||
|
}, [live?.qrExpiresAt, nowMs])
|
||||||
|
|
||||||
|
async function submitProfile() {
|
||||||
|
if (!roleName.trim()) {
|
||||||
|
message.warning('请输入游戏角色名')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
setSaving(true)
|
||||||
|
try {
|
||||||
|
const response = await saveDouyuProfile(orderNo, {
|
||||||
|
roleName: roleName.trim(),
|
||||||
|
platform,
|
||||||
|
system,
|
||||||
|
})
|
||||||
|
applyData(response.data)
|
||||||
|
message.success('资料已提交,正在准备绑定二维码')
|
||||||
|
} catch (error) {
|
||||||
|
message.error(error instanceof Error ? error.message : '提交资料失败')
|
||||||
|
} finally {
|
||||||
|
setSaving(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function startBinding(forceRefresh = false) {
|
||||||
|
setBindingLoading(true)
|
||||||
|
try {
|
||||||
|
const response = await startDouyuBinding(orderNo, forceRefresh)
|
||||||
|
applyData(response.data)
|
||||||
|
message.success(forceRefresh ? '二维码已刷新' : '绑定流程已继续')
|
||||||
|
} catch (error) {
|
||||||
|
message.error(error instanceof Error ? error.message : '生成绑定二维码失败')
|
||||||
|
} finally {
|
||||||
|
setBindingLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function confirmBinding() {
|
||||||
|
setBindingLoading(true)
|
||||||
|
try {
|
||||||
|
const response = await confirmDouyuBinding(orderNo)
|
||||||
|
applyData(response.data)
|
||||||
|
message.success('角色绑定已确认,等待运营处理')
|
||||||
|
} catch (error) {
|
||||||
|
message.error(error instanceof Error ? error.message : '确认角色绑定失败')
|
||||||
|
} finally {
|
||||||
|
setBindingLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<CustomerFrame title="斗鱼精英宝典领取">
|
||||||
|
<div className="customer-auth-loading">
|
||||||
|
<Spin indicator={<LoadingOutlined spin />} />
|
||||||
|
<span>正在读取订单...</span>
|
||||||
|
</div>
|
||||||
|
</CustomerFrame>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loadError || !data || !task) {
|
||||||
|
return (
|
||||||
|
<CustomerFrame title="斗鱼精英宝典领取">
|
||||||
|
<div className="customer-auth-state is-error">
|
||||||
|
<h2>暂时无法打开订单</h2>
|
||||||
|
<p>{loadError || '订单信息不存在'}</p>
|
||||||
|
</div>
|
||||||
|
</CustomerFrame>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (task.status === 'completed') {
|
||||||
|
return (
|
||||||
|
<CustomerFrame title="斗鱼精英宝典领取">
|
||||||
|
<OrderCard data={data} />
|
||||||
|
<div className="customer-auth-state is-success">
|
||||||
|
<div className="customer-auth-state-icon">
|
||||||
|
<CheckCircleFilled />
|
||||||
|
</div>
|
||||||
|
<h2>领取已完成</h2>
|
||||||
|
<p>运营已完成本订单兑换,请到和平精英账号中确认。</p>
|
||||||
|
{task.completed_at ? (
|
||||||
|
<span className="customer-auth-state-time">
|
||||||
|
完成时间:{formatAdminDateTime(task.completed_at)}
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</CustomerFrame>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (task.status === 'cancelled') {
|
||||||
|
return (
|
||||||
|
<CustomerFrame title="斗鱼精英宝典领取">
|
||||||
|
<OrderCard data={data} />
|
||||||
|
<Alert
|
||||||
|
type="warning"
|
||||||
|
showIcon
|
||||||
|
message="订单领取已关闭"
|
||||||
|
description="如订单发生退款或取消,请联系客服确认。"
|
||||||
|
/>
|
||||||
|
</CustomerFrame>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<CustomerFrame title="斗鱼精英宝典领取">
|
||||||
|
<OrderCard data={data} />
|
||||||
|
|
||||||
|
{needsProfile ? (
|
||||||
|
<section className="customer-auth-section">
|
||||||
|
<div className="customer-auth-section-heading">
|
||||||
|
<div>
|
||||||
|
<h2>填写游戏角色</h2>
|
||||||
|
<p>资料用于核对扫码绑定的和平精英角色。</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="customer-collect-body">
|
||||||
|
<label className="customer-collect-label">登录方式</label>
|
||||||
|
<Segmented
|
||||||
|
block
|
||||||
|
value={platform}
|
||||||
|
onChange={(value) => setPlatform(value as DouyuCustomerPlatform)}
|
||||||
|
options={[
|
||||||
|
{ label: '微信', value: 'wechat' },
|
||||||
|
{ label: 'QQ', value: 'qq' },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
<label className="customer-collect-label">设备系统</label>
|
||||||
|
<Segmented
|
||||||
|
block
|
||||||
|
value={system}
|
||||||
|
onChange={(value) => setSystem(value as DouyuCustomerSystem)}
|
||||||
|
options={[
|
||||||
|
{ label: '安卓', value: 'android' },
|
||||||
|
{ label: '苹果', value: 'ios' },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
<label className="customer-collect-label">游戏角色名</label>
|
||||||
|
<Input
|
||||||
|
className="customer-collect-input"
|
||||||
|
value={roleName}
|
||||||
|
onChange={(event) => setRoleName(event.target.value)}
|
||||||
|
placeholder="请输入和平精英角色名"
|
||||||
|
maxLength={100}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
block
|
||||||
|
size="large"
|
||||||
|
className="customer-collect-submit"
|
||||||
|
loading={saving}
|
||||||
|
onClick={() => void submitProfile()}
|
||||||
|
>
|
||||||
|
提交资料并继续
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
) : (
|
||||||
|
<section className="customer-binding-stage">
|
||||||
|
<Alert
|
||||||
|
type={live?.bindConfirmed ? 'success' : 'info'}
|
||||||
|
showIcon
|
||||||
|
message={STATUS_LABELS[task.status] || '等待处理'}
|
||||||
|
description={
|
||||||
|
live?.message ||
|
||||||
|
'请使用微信扫描下方二维码,按提示选择和平精英角色。二维码仅用于本次订单。'
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{!live?.qrUrl && task.status !== 'completed' ? (
|
||||||
|
<div className="customer-binding-qr-card">
|
||||||
|
<h3>游戏角色绑定二维码</h3>
|
||||||
|
<div className="customer-auth-qr-placeholder">
|
||||||
|
<Spin />
|
||||||
|
<span>正在准备绑定二维码...</span>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
block
|
||||||
|
size="large"
|
||||||
|
loading={bindingLoading}
|
||||||
|
onClick={() => void startBinding(false)}
|
||||||
|
>
|
||||||
|
继续准备
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{live?.qrUrl && !live.bindConfirmed ? (
|
||||||
|
<div className="customer-binding-qr-card">
|
||||||
|
<h3>游戏角色绑定二维码</h3>
|
||||||
|
{qrImage ? (
|
||||||
|
<Image src={qrImage} alt="和平精英角色绑定二维码" width={260} preview={false} />
|
||||||
|
) : (
|
||||||
|
<div className="customer-auth-qr-placeholder">
|
||||||
|
<Spin />
|
||||||
|
<span>正在生成二维码图片...</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<p className="customer-binding-qr-hint">
|
||||||
|
请使用微信扫码,并选择与资料一致的和平精英角色。
|
||||||
|
</p>
|
||||||
|
{expiresInSeconds > 0 ? (
|
||||||
|
<div className="customer-binding-qr-countdown">
|
||||||
|
二维码剩余 {Math.ceil(expiresInSeconds / 60)} 分钟
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
<Progress percent={Math.min(100, (expiresInSeconds / 600) * 100)} showInfo={false} />
|
||||||
|
<div className="customer-binding-qr-actions">
|
||||||
|
<Button
|
||||||
|
icon={<ReloadOutlined />}
|
||||||
|
loading={bindingLoading}
|
||||||
|
onClick={() => void startBinding(true)}
|
||||||
|
>
|
||||||
|
刷新二维码
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
icon={<QrcodeOutlined />}
|
||||||
|
loading={bindingLoading}
|
||||||
|
onClick={() =>
|
||||||
|
void pollDouyuBinding(orderNo).then((response) => applyData(response.data))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
刷新状态
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{live?.bindReadyForConfirm ? (
|
||||||
|
<div className="customer-binding-qr-card">
|
||||||
|
<h3>核对绑定角色</h3>
|
||||||
|
<p className="customer-binding-qr-hint">
|
||||||
|
平台识别角色:{live.roleName || '-'} · {live.areaName || '-'} ·{' '}
|
||||||
|
{live.platName || '-'}
|
||||||
|
</p>
|
||||||
|
<p className="customer-binding-qr-hint">
|
||||||
|
已填资料:{task.customer_role_name} · {platformLabel(task.customer_platform)} ·{' '}
|
||||||
|
{systemLabel(task.customer_system)}
|
||||||
|
</p>
|
||||||
|
<Alert
|
||||||
|
type={data.comparison.matched ? 'success' : 'warning'}
|
||||||
|
showIcon
|
||||||
|
message={data.comparison.matched ? '角色信息一致' : '角色信息不一致'}
|
||||||
|
description={data.comparison.message}
|
||||||
|
/>
|
||||||
|
<Space direction="vertical" size={10} style={{ width: '100%' }}>
|
||||||
|
<Button
|
||||||
|
block
|
||||||
|
size="large"
|
||||||
|
type="primary"
|
||||||
|
disabled={!data.comparison.matched}
|
||||||
|
loading={bindingLoading}
|
||||||
|
onClick={() => void confirmBinding()}
|
||||||
|
>
|
||||||
|
确认绑定角色
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
block
|
||||||
|
danger
|
||||||
|
icon={<ExclamationCircleOutlined />}
|
||||||
|
onClick={() => {
|
||||||
|
setData({ ...data, task: { ...task, customer_role_name: '' } })
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
修改资料
|
||||||
|
</Button>
|
||||||
|
</Space>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="customer-auth-privacy">
|
||||||
|
资料仅用于本次订单履约。内部账号和登录凭证不会展示给客户。
|
||||||
|
</div>
|
||||||
|
</CustomerFrame>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CustomerFrame({ title, children }: { title: string; children: ReactNode }) {
|
||||||
|
return (
|
||||||
|
<div className="customer-auth-page is-huya">
|
||||||
|
<div className="customer-auth-shell">
|
||||||
|
<header className="customer-auth-hero">
|
||||||
|
<div className="customer-auth-brand">
|
||||||
|
<div>
|
||||||
|
<h1>{title}</h1>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
<main className="customer-auth-main">{children}</main>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function OrderCard({ data }: { data: DouyuCustomerFulfillment }) {
|
||||||
|
return (
|
||||||
|
<section className="customer-order-card">
|
||||||
|
<h3>订单信息</h3>
|
||||||
|
<div>
|
||||||
|
<span>订单号</span>
|
||||||
|
<strong>{data.task.platform_order_id}</strong>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<span>商品</span>
|
||||||
|
<strong>
|
||||||
|
{data.task.product_name || data.task.sku_name} × {data.task.quantity}
|
||||||
|
</strong>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<span>状态</span>
|
||||||
|
<strong className="customer-order-status">
|
||||||
|
{STATUS_LABELS[data.task.status] || data.task.status}
|
||||||
|
</strong>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -365,6 +365,7 @@ export function saveAdminManualConfig(payload: {
|
|||||||
semiAutoEnabled?: boolean
|
semiAutoEnabled?: boolean
|
||||||
semiAutoPlatform?: '' | 'huya' | 'weibo'
|
semiAutoPlatform?: '' | 'huya' | 'weibo'
|
||||||
semiAutoConfig?: Record<string, unknown>
|
semiAutoConfig?: Record<string, unknown>
|
||||||
|
douyuFulfillmentEnabled?: boolean
|
||||||
}) {
|
}) {
|
||||||
return apiPost<ManualFulfillmentConfig>('/api/v1/admin/cost-center/manual-configs', payload)
|
return apiPost<ManualFulfillmentConfig>('/api/v1/admin/cost-center/manual-configs', payload)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -83,6 +83,7 @@ export type DevDouyuFulfillmentMockResult = {
|
|||||||
configId: number
|
configId: number
|
||||||
mappingId: number
|
mappingId: number
|
||||||
skuKey: string
|
skuKey: string
|
||||||
|
customerPath: string
|
||||||
adminPath: string
|
adminPath: string
|
||||||
tips: string[]
|
tips: string[]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { apiGet, apiPost } from '@/lib/http'
|
||||||
|
import type { DouyuFulfillmentDetail, DouyuFulfillmentTask } from '@/types/douyu-fulfillment'
|
||||||
|
|
||||||
|
export function fetchAdminDouyuFulfillmentTasks(params: {
|
||||||
|
keyword?: string
|
||||||
|
status?: string
|
||||||
|
page?: number
|
||||||
|
pageSize?: number
|
||||||
|
}) {
|
||||||
|
return apiGet<{
|
||||||
|
items: DouyuFulfillmentTask[]
|
||||||
|
pagination: { page: number; pageSize: number; total: number }
|
||||||
|
}>('/api/v1/admin/douyu-fulfillment/tasks', { params })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function syncAdminDouyuFulfillmentTasks() {
|
||||||
|
return apiPost<{ created: number; updated: number }>('/api/v1/admin/douyu-fulfillment/sync', {})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fetchAdminDouyuFulfillmentDetail(orderNo: string) {
|
||||||
|
return apiGet<DouyuFulfillmentDetail>(
|
||||||
|
`/api/v1/admin/douyu-fulfillment/tasks/${encodeURIComponent(orderNo)}`,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function refreshAdminDouyuBinding(orderNo: string) {
|
||||||
|
return apiPost<DouyuFulfillmentDetail>(
|
||||||
|
`/api/v1/admin/douyu-fulfillment/tasks/${encodeURIComponent(orderNo)}/binding/refresh`,
|
||||||
|
{},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function restartAdminDouyuBinding(orderNo: string) {
|
||||||
|
return apiPost<DouyuFulfillmentDetail>(
|
||||||
|
`/api/v1/admin/douyu-fulfillment/tasks/${encodeURIComponent(orderNo)}/binding/start`,
|
||||||
|
{ forceRefresh: true },
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -15,3 +15,4 @@ export * from './tasks'
|
|||||||
export * from './dev-mock'
|
export * from './dev-mock'
|
||||||
export * from './notifications'
|
export * from './notifications'
|
||||||
export * from './worker-platform'
|
export * from './worker-platform'
|
||||||
|
export * from './douyu-fulfillment'
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import { apiGet, apiPost } from '@/lib/http'
|
||||||
|
import type {
|
||||||
|
DouyuCustomerFulfillment,
|
||||||
|
DouyuCustomerPlatform,
|
||||||
|
DouyuCustomerSystem,
|
||||||
|
} from '@/types/douyu-fulfillment'
|
||||||
|
|
||||||
|
export function fetchDouyuFulfillment(orderNo: string) {
|
||||||
|
return apiGet<DouyuCustomerFulfillment>(
|
||||||
|
`/api/v1/douyu-fulfillment/${encodeURIComponent(orderNo)}`,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function saveDouyuProfile(
|
||||||
|
orderNo: string,
|
||||||
|
input: {
|
||||||
|
roleName: string
|
||||||
|
platform: DouyuCustomerPlatform
|
||||||
|
system: DouyuCustomerSystem
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
return apiPost<DouyuCustomerFulfillment>(
|
||||||
|
`/api/v1/douyu-fulfillment/${encodeURIComponent(orderNo)}/profile`,
|
||||||
|
input,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function startDouyuBinding(orderNo: string, forceRefresh = false) {
|
||||||
|
return apiPost<DouyuCustomerFulfillment>(
|
||||||
|
`/api/v1/douyu-fulfillment/${encodeURIComponent(orderNo)}/binding/start`,
|
||||||
|
{ forceRefresh },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function pollDouyuBinding(orderNo: string) {
|
||||||
|
return apiGet<DouyuCustomerFulfillment>(
|
||||||
|
`/api/v1/douyu-fulfillment/${encodeURIComponent(orderNo)}/binding/status`,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function confirmDouyuBinding(orderNo: string) {
|
||||||
|
return apiPost<DouyuCustomerFulfillment>(
|
||||||
|
`/api/v1/douyu-fulfillment/${encodeURIComponent(orderNo)}/binding/confirm`,
|
||||||
|
{},
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -432,6 +432,7 @@ export interface ManualFulfillmentConfig {
|
|||||||
enabled: boolean
|
enabled: boolean
|
||||||
semiAutoEnabled: boolean
|
semiAutoEnabled: boolean
|
||||||
semiAutoPlatform: '' | 'huya' | 'weibo'
|
semiAutoPlatform: '' | 'huya' | 'weibo'
|
||||||
|
douyuFulfillmentEnabled: boolean
|
||||||
semiAutoConfig: {
|
semiAutoConfig: {
|
||||||
pageTitle?: string
|
pageTitle?: string
|
||||||
pageDescription?: string
|
pageDescription?: string
|
||||||
|
|||||||
@@ -0,0 +1,89 @@
|
|||||||
|
export type DouyuCustomerPlatform = 'wechat' | 'qq'
|
||||||
|
export type DouyuCustomerSystem = 'ios' | 'android'
|
||||||
|
|
||||||
|
export type DouyuFulfillmentTask = {
|
||||||
|
id: number
|
||||||
|
order_id: number
|
||||||
|
order_item_id: number
|
||||||
|
fulfillment_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
|
||||||
|
linkPath: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type DouyuLiveBindingState = {
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
export type DouyuRoleComparison = {
|
||||||
|
matched: boolean
|
||||||
|
roleMatched: boolean
|
||||||
|
channelMatched: boolean
|
||||||
|
message: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type DouyuCustomerFulfillment = {
|
||||||
|
task: DouyuFulfillmentTask
|
||||||
|
live: DouyuLiveBindingState
|
||||||
|
comparison: DouyuRoleComparison
|
||||||
|
linkPath: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type DouyuFulfillmentEvent = {
|
||||||
|
id: number
|
||||||
|
event_type: string
|
||||||
|
actor_type: string
|
||||||
|
detail_json: Record<string, unknown>
|
||||||
|
created_at: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type DouyuFulfillmentDetail = DouyuCustomerFulfillment & {
|
||||||
|
events: DouyuFulfillmentEvent[]
|
||||||
|
}
|
||||||
@@ -20,6 +20,21 @@ export function isCustomerFulfillmentPath(pathname: unknown): boolean {
|
|||||||
return first === 'c' || first === 'd'
|
return first === 'c' || first === 'd'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 斗鱼客户领取入口:/coll/d/:orderNo。 */
|
||||||
|
export function buildDouyuFulfillmentPath(orderNo: unknown): string {
|
||||||
|
const normalizedOrderNo = String(orderNo || '').trim()
|
||||||
|
return normalizedOrderNo ? `/coll/d/${encodeURIComponent(normalizedOrderNo)}` : ''
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isDouyuFulfillmentPath(pathname: unknown): boolean {
|
||||||
|
const parts = String(pathname || '')
|
||||||
|
.trim()
|
||||||
|
.split(/[?#]/)[0]
|
||||||
|
.split('/')
|
||||||
|
.filter(Boolean)
|
||||||
|
return parts[0] === 'coll' && parts[1] === 'd'
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 严格绑定下的自动归一化:当前路径对应平台没有任务、但订单只有另一个平台任务时,
|
* 严格绑定下的自动归一化:当前路径对应平台没有任务、但订单只有另一个平台任务时,
|
||||||
* 返回应跳转的平台;双平台订单返回 null(各路径只展示自己的任务),
|
* 返回应跳转的平台;双平台订单返回 null(各路径只展示自己的任务),
|
||||||
|
|||||||
@@ -3,8 +3,10 @@ import { readFile } from 'node:fs/promises'
|
|||||||
import test from 'node:test'
|
import test from 'node:test'
|
||||||
|
|
||||||
import {
|
import {
|
||||||
|
buildDouyuFulfillmentPath,
|
||||||
buildCustomerFulfillmentPath,
|
buildCustomerFulfillmentPath,
|
||||||
isCustomerFulfillmentPath,
|
isCustomerFulfillmentPath,
|
||||||
|
isDouyuFulfillmentPath,
|
||||||
resolveCustomerPlatformRedirect,
|
resolveCustomerPlatformRedirect,
|
||||||
} from '../src/utils/customer-fulfillment-link.ts'
|
} from '../src/utils/customer-fulfillment-link.ts'
|
||||||
|
|
||||||
@@ -29,6 +31,15 @@ test('客户半自动履约入口不误伤相似前缀和其他路径', () => {
|
|||||||
assert.equal(isCustomerFulfillmentPath('d/1'), false)
|
assert.equal(isCustomerFulfillmentPath('d/1'), false)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('斗鱼领取入口固定为 /coll/d/订单号', () => {
|
||||||
|
assert.equal(buildDouyuFulfillmentPath('DY-001'), '/coll/d/DY-001')
|
||||||
|
assert.equal(buildDouyuFulfillmentPath(''), '')
|
||||||
|
assert.equal(isDouyuFulfillmentPath('/coll/d/DY-001'), true)
|
||||||
|
assert.equal(isDouyuFulfillmentPath('/coll/d/DY-001?from=chat'), true)
|
||||||
|
assert.equal(isDouyuFulfillmentPath('/coll/other/DY-001'), false)
|
||||||
|
assert.equal(isDouyuFulfillmentPath('/admin/coll/d/DY-001'), false)
|
||||||
|
})
|
||||||
|
|
||||||
test('按平台生成客户链接:虎牙 /c、微博 /d', () => {
|
test('按平台生成客户链接:虎牙 /c、微博 /d', () => {
|
||||||
assert.equal(
|
assert.equal(
|
||||||
buildCustomerFulfillmentPath('INTSA1794902905684_360848', 'huya'),
|
buildCustomerFulfillmentPath('INTSA1794902905684_360848', 'huya'),
|
||||||
@@ -80,6 +91,7 @@ test('客户页路由与严格绑定接线', async () => {
|
|||||||
assert.match(page, /resolveCustomerPlatformRedirect/)
|
assert.match(page, /resolveCustomerPlatformRedirect/)
|
||||||
assert.match(page, /buildCustomerFulfillmentPath/)
|
assert.match(page, /buildCustomerFulfillmentPath/)
|
||||||
assert.match(page, /task\.platform === expectedPlatform/)
|
assert.match(page, /task\.platform === expectedPlatform/)
|
||||||
|
assert.match(app, /path="\/coll\/d\/:orderNo"/)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('开发 Mock 页按平台重新生成客户路径', async () => {
|
test('开发 Mock 页按平台重新生成客户路径', async () => {
|
||||||
|
|||||||
@@ -141,6 +141,8 @@ services:
|
|||||||
SEMI_AUTO_CONNECTOR_API_KEY: ${SEMI_AUTO_CONNECTOR_API_KEY:-}
|
SEMI_AUTO_CONNECTOR_API_KEY: ${SEMI_AUTO_CONNECTOR_API_KEY:-}
|
||||||
SEMI_AUTO_DEFAULT_CONNECTOR_MODE: ${SEMI_AUTO_DEFAULT_CONNECTOR_MODE:-embedded}
|
SEMI_AUTO_DEFAULT_CONNECTOR_MODE: ${SEMI_AUTO_DEFAULT_CONNECTOR_MODE:-embedded}
|
||||||
SEMI_AUTO_CONNECTOR_TIMEOUT_MS: ${SEMI_AUTO_CONNECTOR_TIMEOUT_MS:-15000}
|
SEMI_AUTO_CONNECTOR_TIMEOUT_MS: ${SEMI_AUTO_CONNECTOR_TIMEOUT_MS:-15000}
|
||||||
|
LIVE_HUB_PLATFORM_FULFILLMENT_URL: ${LIVE_HUB_PLATFORM_FULFILLMENT_URL:-http://host.docker.internal:8800}
|
||||||
|
PLATFORM_FULFILLMENT_INTEGRATION_KEY: ${PLATFORM_FULFILLMENT_INTEGRATION_KEY:-}
|
||||||
logging: *json-log-rotation
|
logging: *json-log-rotation
|
||||||
volumes:
|
volumes:
|
||||||
- ./apps/backend/data:/app/data
|
- ./apps/backend/data:/app/data
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
# 斗鱼客户领取与角色绑定
|
||||||
|
|
||||||
|
更新时间:2026-11-17
|
||||||
|
|
||||||
|
## 入口
|
||||||
|
|
||||||
|
客户领取链接固定为:
|
||||||
|
|
||||||
|
```text
|
||||||
|
<域名>/coll/d/<订单号>
|
||||||
|
```
|
||||||
|
|
||||||
|
例如:
|
||||||
|
|
||||||
|
```text
|
||||||
|
https://order.khhao.com/coll/d/COLLD-E2E-001
|
||||||
|
```
|
||||||
|
|
||||||
|
## 职责
|
||||||
|
|
||||||
|
- `order_site`:订单读取、客户资料、客户领取页、运营工作台和状态时间线。
|
||||||
|
- `live-hub`:内部斗鱼账号、CK、二维码生成、角色识别、绑定确认、积分和兑换。
|
||||||
|
- 客户不提交 CK,也不会看到内部账号、积分、租约或限兑信息。
|
||||||
|
|
||||||
|
## 客户流程
|
||||||
|
|
||||||
|
1. 打开 `/coll/d/<订单号>`。
|
||||||
|
2. 填写游戏角色名、微信/QQ、苹果/安卓。
|
||||||
|
3. `order_site` 通过服务端接口通知 live-hub 准备订单和内部账号。
|
||||||
|
4. live-hub 返回安全绑定状态和二维码。
|
||||||
|
5. 客户微信扫码选择和平精英角色。
|
||||||
|
6. 平台角色与客户资料一致后,客户确认绑定。
|
||||||
|
7. 绑定完成后等待运营在 live-hub 人工兑换。
|
||||||
|
|
||||||
|
斗鱼接口没有游戏 UID / 角色 ID。资料核对只使用角色名、平台和系统区服。
|
||||||
|
|
||||||
|
## 状态
|
||||||
|
|
||||||
|
```text
|
||||||
|
waiting_profile
|
||||||
|
preparing
|
||||||
|
qr_pending
|
||||||
|
role_ready
|
||||||
|
bound
|
||||||
|
waiting_operator
|
||||||
|
processing
|
||||||
|
completed
|
||||||
|
failed
|
||||||
|
manual_required
|
||||||
|
cancelled
|
||||||
|
```
|
||||||
|
|
||||||
|
最终绑定只认 `bindAct=1`。`bindRole=1, bindAct=0` 表示已识别角色但尚未最终确认。
|
||||||
|
|
||||||
|
## 环境变量
|
||||||
|
|
||||||
|
`order_site`:
|
||||||
|
|
||||||
|
```env
|
||||||
|
LIVE_HUB_PLATFORM_FULFILLMENT_URL=http://127.0.0.1:8800
|
||||||
|
PLATFORM_FULFILLMENT_INTEGRATION_KEY=<共享密钥>
|
||||||
|
```
|
||||||
|
|
||||||
|
`live-hub`:
|
||||||
|
|
||||||
|
```env
|
||||||
|
PLATFORM_FULFILLMENT_INTEGRATION_KEY=<共享密钥>
|
||||||
|
PLATFORM_FULFILLMENT_INTEGRATION_ACTOR_ID=
|
||||||
|
PLATFORM_BINDING_QR_TTL_SECONDS=600
|
||||||
|
```
|
||||||
|
|
||||||
|
集成操作人不填时,live-hub 使用最早创建的有效超级管理员。
|
||||||
|
|
||||||
|
## 数据边界
|
||||||
|
|
||||||
|
- `douyu_fulfillment_tasks` 只保存客户资料和 live-hub 安全状态投影。
|
||||||
|
- `live_session_id` 指向 live-hub 履约任务。
|
||||||
|
- 二维码原始 URL 由 live-hub 返回,不在 order_site 数据库长期保存。
|
||||||
|
- 内部账号、Cookie、积分和租约不得进入 order_site 客户接口。
|
||||||
Reference in New Issue
Block a user