merge(douyu): 合入客户领取与直播账号履约

- 合入斗鱼客户资料收集、角色绑定和半自动履约工作台
- 合入事务 Outbox、签名 Webhook 与低频对账链路
- 合入双角色识别、绑定重置、取消释放账号和已分配状态修复
- 将斗鱼履约数据库变更合并为单个 171 迁移文件
- 更新拆分后的客户样式测试入口并适配最新 main 客户页样式
This commit is contained in:
yml
2026-11-18 11:10:04 +08:00
67 changed files with 8854 additions and 3980 deletions
+60
View File
@@ -4,6 +4,7 @@ import test from 'node:test'
import { createApp } from './app.js'
import { createDefaultRuntimeConfig } from './config/defaults.js'
import { buildWebhookSignature } from './services/integration/webhook-signature.js'
import { createStartupState } from './startup/state.js'
test('HTTP health route and explicit CORS preflight', async () => {
@@ -38,3 +39,62 @@ test('HTTP health route and explicit CORS preflight', async () => {
await once(server, 'close')
}
})
test('履约状态集成接口要求密钥并接受空快照', async () => {
const previousKey = process.env.PLATFORM_FULFILLMENT_INTEGRATION_KEY
process.env.PLATFORM_FULFILLMENT_INTEGRATION_KEY = 'integration-test-key'
const startupState = createStartupState()
startupState.core.ready = true
const config = createDefaultRuntimeConfig('/tmp/order-site')
const server = createApp({
startupState,
isShutdownStarted: () => false,
config,
}).listen(0, '127.0.0.1')
await once(server, 'listening')
try {
const address = server.address()
assert.ok(address && typeof address === 'object')
const endpoint = `http://127.0.0.1:${address.port}/api/integration/platform-fulfillment/binding-state`
const unauthorized = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ items: [] }),
})
assert.equal(unauthorized.status, 401)
const rawBody = JSON.stringify({
eventId: '8a8da35c-46c3-45a8-a914-3d7f28ee91ca',
eventType: 'platform_fulfillment.binding_state_changed',
items: [],
})
const timestamp = String(Math.floor(Date.now() / 1000))
const accepted = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Integration-Key': 'integration-test-key',
'X-Integration-Event-Id': '8a8da35c-46c3-45a8-a914-3d7f28ee91ca',
'X-Integration-Timestamp': timestamp,
'X-Integration-Signature': buildWebhookSignature(
'integration-test-key',
timestamp,
rawBody,
),
},
body: rawBody,
})
assert.equal(accepted.status, 200)
assert.deepEqual((await accepted.json()).data, { received: 0, updated: 0 })
} finally {
if (previousKey === undefined) {
delete process.env.PLATFORM_FULFILLMENT_INTEGRATION_KEY
} else {
process.env.PLATFORM_FULFILLMENT_INTEGRATION_KEY = previousKey
}
server.close()
await once(server, 'close')
}
})
+4
View File
@@ -11,9 +11,11 @@ import customerFulfillmentRouter from './routes/customer-fulfillment.js'
import devMockConnectorRouter from './routes/dev-mock-connector.js'
import dcAuthRouter from './routes/dcauth.js'
import douyinMashidaRouter from './routes/douyin-mashida.js'
import douyuFulfillmentRouter from './routes/douyu-fulfillment.js'
import kuaishouIndustryRouter from './routes/kuaishou-industry.js'
import open91Router from './routes/open-91.js'
import pddExtensionRouter from './routes/pdd-extension.js'
import platformFulfillmentIntegrationRouter from './routes/platform-fulfillment-integration.js'
import redeemRouter from './routes/redeem.js'
import shortLinksRouter from './routes/short-links.js'
import semiAutoInjectionsRouter from './routes/semi-auto-injections.js'
@@ -116,9 +118,11 @@ export function createApp({ startupState, isShutdownStarted, config }: CreateApp
app.use('/api/v1/open/affiliate-dash', affiliateDashRouter)
app.use('/api/v1/open/91', open91Router)
app.use('/api/v1/open/kuaishou-industry', kuaishouIndustryRouter)
app.use('/api/integration', platformFulfillmentIntegrationRouter)
app.use('/api/v1/redeem', redeemRouter)
app.use('/api/v1/claim', claimsRouter)
app.use('/api/v1/customer-fulfillment', customerFulfillmentRouter)
app.use('/api/v1/douyu-fulfillment', douyuFulfillmentRouter)
app.use('/api/v1/semi-auto/injections', semiAutoInjectionsRouter)
app.use('/api/v1/o', orderServiceRouter)
app.use('/api/v1/pdd/extension', pddExtensionRouter)
@@ -10,7 +10,17 @@ const CURRENT_DIR = path.dirname(fileURLToPath(import.meta.url))
const BACKEND_ROOT = path.resolve(CURRENT_DIR, '../..')
const WORKSPACE_ROOT = process.env.WORKSPACE_ROOT || path.resolve(BACKEND_ROOT, '../..')
const SPECIAL_RUNTIME_ENV_NAMES = ['APP_BASE_URL', 'CLAIM_BASE_URL']
const SPECIAL_RUNTIME_ENV_NAMES = [
'APP_BASE_URL',
'CLAIM_BASE_URL',
'INTEGRATION_OUTBOX_BATCH_SIZE',
'INTEGRATION_OUTBOX_INTERVAL_MS',
'INTEGRATION_OUTBOX_MAX_ATTEMPTS',
'LIVE_HUB_PLATFORM_FULFILLMENT_URL',
'PLATFORM_FULFILLMENT_INTEGRATION_KEY',
'PLATFORM_FULFILLMENT_RECONCILE_SECONDS',
'PLATFORM_FULFILLMENT_WEBHOOK_TOLERANCE_SECONDS',
]
const DEPLOYMENT_ONLY_ENV_NAMES = [
'APP_DOMAIN',
+30 -1
View File
@@ -1,7 +1,10 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { planLegacyConsignmentMigrationCleanup } from './migrate.js'
import {
planLegacyConsignmentMigrationCleanup,
planLegacyDouyuFulfillmentMigrationCleanup,
} from './migrate.js'
const MAIN_MIGRATIONS = [
'147_internal_sku_product_routing',
@@ -91,6 +94,32 @@ test('迁移归一化:main 已执行、只剩旧寄卖记录时只清理旧名
assert.deepEqual(stale, ['147_consignment_platform', '148_consignment_sms_logs'])
})
test('迁移归一化:拆分版斗鱼履约迁移记录全部清理,由合并版重跑', () => {
const stale = planLegacyDouyuFulfillmentMigrationCleanup([
'170_semi_auto_trace_logs',
'171_douyu_customer_fulfillment',
'172_platform_fulfillment_outbox',
'173_douyu_fulfillment_cached_binding',
'174_douyu_fulfillment_allocated_status',
])
assert.deepEqual(stale, [
'171_douyu_customer_fulfillment',
'172_platform_fulfillment_outbox',
'173_douyu_fulfillment_cached_binding',
'174_douyu_fulfillment_allocated_status',
])
})
test('迁移归一化:只剩合并版斗鱼履约记录时不清理', () => {
const stale = planLegacyDouyuFulfillmentMigrationCleanup([
'170_semi_auto_trace_logs',
'171_douyu_fulfillment_integration',
])
assert.deepEqual(stale, [])
})
test('迁移归一化:159 已登记但 main 147–151 缺失时,159 也要重跑', () => {
const stale = planLegacyConsignmentMigrationCleanup([
'001_init',
+30
View File
@@ -27,6 +27,7 @@ const MIGRATION_FILE_PATTERN = /^(\d{3})_.+\.sql$/i
/** 合并后的寄卖迁移文件名(不含 .sql);main 的 147–152、158 保持原编号,寄卖合并文件顺延到 159。 */
const CONSOLIDATED_CONSIGNMENT_MIGRATION = '159_consignment_platform'
const CONSOLIDATED_DOUYU_FULFILLMENT_MIGRATION = '171_douyu_fulfillment_integration'
const MAIN_MIGRATIONS_BEFORE_CONSIGNMENT = [
'147_internal_sku_product_routing',
'148_fulfillment_execution_truth',
@@ -59,10 +60,18 @@ const LEGACY_CONSIGNMENT_MIGRATION_NAMES = [
'158_consignment_match_log_snapshot',
] as const
const LEGACY_DOUYU_FULFILLMENT_MIGRATION_NAMES = [
'171_douyu_customer_fulfillment',
'172_platform_fulfillment_outbox',
'173_douyu_fulfillment_cached_binding',
'174_douyu_fulfillment_allocated_status',
] as const
export async function runDatabaseMigrations() {
assertMigrationFilesOrdered()
await ensureNodePgMigrateMetadataCompatibility()
await normalizeLegacyConsignmentMigrationNames()
await normalizeLegacyDouyuFulfillmentMigrationNames()
console.info(`[db:migrate] 迁移目录: ${MIGRATIONS_DIR}`)
@@ -190,6 +199,13 @@ export function planLegacyConsignmentMigrationCleanup(appliedNames: readonly str
return staleNames
}
export function planLegacyDouyuFulfillmentMigrationCleanup(
appliedNames: readonly string[],
): string[] {
const applied = new Set(appliedNames)
return LEGACY_DOUYU_FULFILLMENT_MIGRATION_NAMES.filter((name) => applied.has(name))
}
async function normalizeLegacyConsignmentMigrationNames() {
const { rows } = await query<{ name: string }>(`SELECT name FROM ${MIGRATIONS_TABLE}`)
const staleNames = planLegacyConsignmentMigrationCleanup(rows.map((row) => row.name))
@@ -204,6 +220,20 @@ async function normalizeLegacyConsignmentMigrationNames() {
)
}
async function normalizeLegacyDouyuFulfillmentMigrationNames() {
const { rows } = await query<{ name: string }>(`SELECT name FROM ${MIGRATIONS_TABLE}`)
const staleNames = planLegacyDouyuFulfillmentMigrationCleanup(rows.map((row) => row.name))
if (staleNames.length === 0) {
return
}
await query(`DELETE FROM ${MIGRATIONS_TABLE} WHERE name = ANY($1::text[])`, [staleNames])
console.warn(
`[db:migrate] 检测到拆分版斗鱼履约迁移,已清理 ${staleNames.length} 条记录: ${staleNames.join(', ')};` +
`将由合并迁移 ${CONSOLIDATED_DOUYU_FULFILLMENT_MIGRATION} 幂等重跑`,
)
}
async function ensureNodePgMigrateMetadataCompatibility() {
await query(`
CREATE TABLE IF NOT EXISTS ${MIGRATIONS_TABLE} (
@@ -0,0 +1,337 @@
-- 171_douyu_fulfillment_integration.sql
--
-- 斗鱼精英宝典半自动履约:
-- 1. 人工 SKU 配置可显式启用斗鱼客户领取;
-- 2. order_site 保存客户资料、绑定状态和 live-hub 安全投影;
-- 3. 事务 Outbox 保证订单与履约状态可靠同步到 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 integration_outbox (
id BIGSERIAL PRIMARY KEY,
event_id UUID NOT NULL UNIQUE,
destination TEXT NOT NULL DEFAULT 'live_hub',
event_type TEXT NOT NULL,
dedupe_key TEXT UNIQUE,
payload_json JSONB NOT NULL,
status TEXT NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending', 'processing', 'sent', 'dead')),
attempts INTEGER NOT NULL DEFAULT 0,
next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
locked_at TIMESTAMPTZ,
sent_at TIMESTAMPTZ,
last_error TEXT NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_integration_outbox_due
ON integration_outbox (status, next_attempt_at, id);
CREATE INDEX IF NOT EXISTS idx_integration_outbox_destination
ON integration_outbox (destination, status, id);
CREATE TABLE IF NOT EXISTS integration_inbox (
event_id UUID PRIMARY KEY,
source TEXT NOT NULL DEFAULT '',
event_type TEXT NOT NULL DEFAULT '',
received_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
processed_at TIMESTAMPTZ
);
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',
'allocated',
'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 '',
qr_url TEXT NOT NULL DEFAULT '',
qr_generated_at TIMESTAMPTZ,
qr_expires_at TIMESTAMPTZ,
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);
CREATE OR REPLACE FUNCTION enqueue_live_hub_platform_fulfillment_event(
p_order_id BIGINT,
p_order_item_id BIGINT,
p_fulfillment_id BIGINT,
p_reason TEXT
) RETURNS VOID
LANGUAGE plpgsql
AS $$
DECLARE
v_event_id UUID := gen_random_uuid();
v_platform_order_id TEXT := '';
v_dedupe_key TEXT;
BEGIN
SELECT platform_order_id
INTO v_platform_order_id
FROM orders
WHERE id = p_order_id;
IF COALESCE(v_platform_order_id, '') = '' THEN
RETURN;
END IF;
v_dedupe_key := CONCAT(
'platform-fulfillment-order:',
COALESCE(p_order_item_id, 0),
':',
p_reason
);
INSERT INTO integration_outbox (
event_id, destination, event_type, dedupe_key, payload_json, status, created_at
) VALUES (
v_event_id,
'live_hub',
'platform_fulfillment.order_changed',
v_dedupe_key,
jsonb_build_object(
'eventId', v_event_id::text,
'eventType', 'platform_fulfillment.order_changed',
'occurredAt', to_char(
clock_timestamp() AT TIME ZONE 'UTC',
'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'
),
'data', jsonb_build_object(
'orderId', p_order_id,
'orderItemId', p_order_item_id,
'fulfillmentId', p_fulfillment_id,
'platformOrderId', v_platform_order_id,
'reason', p_reason
)
),
'pending',
NOW()
)
ON CONFLICT (dedupe_key) DO NOTHING;
END;
$$;
CREATE OR REPLACE FUNCTION enqueue_platform_fulfillment_from_order()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
DECLARE
v_row RECORD;
BEGIN
FOR v_row IN
SELECT oi.id AS order_item_id, f.id AS fulfillment_id
FROM order_items oi
JOIN fulfillments f ON f.order_item_id = oi.id
JOIN manual_fulfillment_configs cfg ON cfg.id = f.fulfillment_config_id
WHERE oi.order_id = NEW.id
AND cfg.douyu_fulfillment_enabled = TRUE
AND f.channel = 'manual'
AND f.status IN ('assigned', 'processing', 'completed')
LOOP
PERFORM enqueue_live_hub_platform_fulfillment_event(
NEW.id,
v_row.order_item_id,
v_row.fulfillment_id,
CONCAT('order:', NEW.pay_status, ':', NEW.order_status)
);
END LOOP;
RETURN NEW;
END;
$$;
CREATE OR REPLACE FUNCTION enqueue_platform_fulfillment_from_fulfillment()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
DECLARE
v_order_id BIGINT;
v_enabled BOOLEAN := FALSE;
BEGIN
SELECT oi.order_id
INTO v_order_id
FROM order_items oi
WHERE oi.id = NEW.order_item_id;
SELECT cfg.douyu_fulfillment_enabled
INTO v_enabled
FROM manual_fulfillment_configs cfg
WHERE cfg.id = NEW.fulfillment_config_id;
IF v_order_id IS NOT NULL
AND v_enabled = TRUE
AND NEW.channel = 'manual'
AND NEW.status IN ('assigned', 'processing', 'completed') THEN
PERFORM enqueue_live_hub_platform_fulfillment_event(
v_order_id,
NEW.order_item_id,
NEW.id,
CONCAT('fulfillment:', NEW.status)
);
END IF;
RETURN NEW;
END;
$$;
CREATE OR REPLACE FUNCTION enqueue_platform_fulfillment_from_config()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
DECLARE
v_row RECORD;
BEGIN
IF NEW.douyu_fulfillment_enabled = TRUE THEN
FOR v_row IN
SELECT o.id AS order_id, oi.id AS order_item_id, f.id AS fulfillment_id
FROM order_items oi
JOIN orders o ON o.id = oi.order_id
JOIN fulfillments f ON f.order_item_id = oi.id
WHERE f.fulfillment_config_id = NEW.id
AND f.channel = 'manual'
AND f.status IN ('assigned', 'processing', 'completed')
LOOP
PERFORM enqueue_live_hub_platform_fulfillment_event(
v_row.order_id,
v_row.order_item_id,
v_row.fulfillment_id,
'config_enabled'
);
END LOOP;
END IF;
RETURN NEW;
END;
$$;
DROP TRIGGER IF EXISTS trg_platform_fulfillment_order_sync ON orders;
CREATE TRIGGER trg_platform_fulfillment_order_sync
AFTER INSERT OR UPDATE OF pay_status, order_status ON orders
FOR EACH ROW
EXECUTE FUNCTION enqueue_platform_fulfillment_from_order();
DROP TRIGGER IF EXISTS trg_platform_fulfillment_fulfillment_sync ON fulfillments;
CREATE TRIGGER trg_platform_fulfillment_fulfillment_sync
AFTER INSERT OR UPDATE OF channel, status, fulfillment_config_id ON fulfillments
FOR EACH ROW
EXECUTE FUNCTION enqueue_platform_fulfillment_from_fulfillment();
DROP TRIGGER IF EXISTS trg_platform_fulfillment_config_sync
ON manual_fulfillment_configs;
CREATE TRIGGER trg_platform_fulfillment_config_sync
AFTER UPDATE OF douyu_fulfillment_enabled ON manual_fulfillment_configs
FOR EACH ROW
WHEN (OLD.douyu_fulfillment_enabled IS DISTINCT FROM NEW.douyu_fulfillment_enabled)
EXECUTE FUNCTION enqueue_platform_fulfillment_from_config();
-- 上线时补一次存量待履约订单;之后全部由业务写入同事务触发。
INSERT INTO integration_outbox (
event_id, destination, event_type, dedupe_key, payload_json, status, created_at
)
SELECT
event_id,
'live_hub',
'platform_fulfillment.order_changed',
CONCAT('platform-fulfillment-backfill:', candidate.order_item_id),
jsonb_build_object(
'eventId', event_id::text,
'eventType', 'platform_fulfillment.order_changed',
'occurredAt', to_char(
clock_timestamp() AT TIME ZONE 'UTC',
'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'
),
'data', jsonb_build_object(
'orderId', candidate.order_id,
'orderItemId', candidate.order_item_id,
'fulfillmentId', candidate.fulfillment_id,
'platformOrderId', candidate.platform_order_id,
'reason', 'migration_backfill'
)
),
'pending',
NOW()
FROM (
SELECT
gen_random_uuid() AS event_id,
o.id AS order_id,
oi.id AS order_item_id,
f.id AS fulfillment_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.douyu_fulfillment_enabled = TRUE
AND f.channel = 'manual'
AND f.status = 'assigned'
AND o.pay_status = 'paid'
AND o.order_status NOT IN ('refunded', 'cancelled', 'closed')
AND oi.quantity = 1
) candidate
ON CONFLICT (dedupe_key) DO NOTHING;
COMMENT ON TABLE integration_outbox IS
'order_site 事务 Outbox;业务提交与待发送事件同事务,worker 负责签名投递';
COMMENT ON TABLE integration_inbox IS
'order_site 入站 Webhook 幂等表;event_id 全局唯一';
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';
COMMENT ON COLUMN douyu_fulfillment_tasks.qr_url IS
'live-hub 绑定二维码的客户页投影;仅用于展示,不包含内部账号或 CK';
+2
View File
@@ -6,6 +6,7 @@ import costCenterRouter from './admin/cost-center.js'
import dashboardRouter from './admin/dashboard.js'
import devMockRouter from './admin/dev-mock.js'
import douyinMashidaRouter from './admin/douyin-mashida.js'
import douyuFulfillmentRouter from './admin/douyu-fulfillment.js'
import financeRouter from './admin/finance.js'
import fulfillmentChannelRouter from './admin/fulfillment-channel.js'
import financeLedgerRouter from './admin/finance-ledger.js'
@@ -38,6 +39,7 @@ router.use(fundRouter)
router.use(usersRouter)
router.use(rbacRouter)
router.use(semiAutoRouter)
router.use(douyuFulfillmentRouter)
router.use(auditLogsRouter)
router.use(platformConfigRouter)
router.use(kuaishouIndustryRouter)
+22
View File
@@ -3,6 +3,7 @@ import { Router } from 'express'
import {
buildOpen91QueryMock,
createAffiliateDashMockClaim,
createDouyuFulfillmentMock,
createKuaishouIndustryVoucherMockData,
createSemiAutoIntegrationMock,
createSemiAutoMock,
@@ -77,6 +78,27 @@ router.post(
}),
)
router.post(
'/dev-mock/douyu-fulfillment',
createJsonHandler((req) => createDouyuFulfillmentMock(req.body || {}), {
successMessage: '斗鱼直播账号履约测试单已生成',
errorMessage: '生成斗鱼直播账号履约测试单失败',
scope: '[admin/dev-mock/douyu-fulfillment]',
audit: (_req, data) => ({
action: 'dev_mock_create_douyu_fulfillment',
targetType: 'dev_mock',
targetId: String((data as { orderNo?: string })?.orderNo || ''),
data: {
platform: 'douyu',
pipeline: 'order_service',
orderNo: (data as { orderNo?: string })?.orderNo,
orderItemId: (data as { orderItemId?: number })?.orderItemId,
skuKey: (data as { skuKey?: string })?.skuKey,
},
}),
}),
)
router.post(
'/dev-mock/semi-auto',
createJsonHandler((req) => createSemiAutoMock(req.body || {}), {
@@ -0,0 +1,71 @@
import { Router } from 'express'
import {
getDouyuFulfillmentDetail,
listDouyuFulfillmentTasks,
refreshDouyuCustomerBinding,
startDouyuCustomerBinding,
syncDouyuFulfillmentTasks,
} 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(() => syncDouyuFulfillmentTasks(), {
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,
getDouyuCustomerFulfillmentCached,
getCustomerDouyuFulfillment,
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) => getDouyuCustomerFulfillmentCached(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
@@ -0,0 +1,88 @@
import { timingSafeEqual } from 'node:crypto'
import { Router } from 'express'
import { applyLiveBindingStateSnapshot } from '../services/douyu-fulfillment/douyu-fulfillment-service.js'
import {
verifyWebhookSignature,
webhookToleranceSeconds,
} from '../services/integration/webhook-signature.js'
import { createHttpError, createRouteHandler } from '../utils/http.js'
const router = Router()
router.use('/platform-fulfillment', (req, res, next) => {
const expected = String(process.env.PLATFORM_FULFILLMENT_INTEGRATION_KEY || '').trim()
if (!expected) {
res.status(503).json({
code: 1,
msg: '直播账号履约集成密钥未配置',
errorCode: 'integration_not_configured',
time: Math.floor(Date.now() / 1000),
data: null,
})
return
}
const provided = String(req.header('x-integration-key') || '').trim()
const expectedBuffer = Buffer.from(expected)
const providedBuffer = Buffer.from(provided)
if (
expectedBuffer.length !== providedBuffer.length ||
!timingSafeEqual(expectedBuffer, providedBuffer)
) {
res.status(401).json({
code: 1,
msg: '直播账号履约集成鉴权失败',
errorCode: 'integration_unauthorized',
time: Math.floor(Date.now() / 1000),
data: null,
})
return
}
next()
})
router.post(
'/platform-fulfillment/binding-state',
createRouteHandler(
(req) => {
const integrationKey = String(process.env.PLATFORM_FULFILLMENT_INTEGRATION_KEY || '').trim()
const eventId = String(req.header('x-integration-event-id') || '').trim()
const timestamp = String(req.header('x-integration-timestamp') || '').trim()
const signature = String(req.header('x-integration-signature') || '').trim()
const body = req.body as Record<string, unknown> | undefined
if (
!verifyWebhookSignature({
secret: integrationKey,
timestamp,
rawBody: req.rawBody || '',
signature,
toleranceSeconds: webhookToleranceSeconds(),
})
) {
throw createHttpError('履约 Webhook 签名无效', {
statusCode: 401,
errorCode: 'integration_signature_invalid',
})
}
if (!body || String(body.eventId || '').trim() !== eventId) {
throw createHttpError('履约 Webhook 事件编号不一致', {
statusCode: 400,
errorCode: 'integration_event_id_mismatch',
})
}
return applyLiveBindingStateSnapshot(body, {
eventId,
eventType: String(body.eventType || ''),
})
},
{
successMessage: '履约状态已同步',
errorMessage: '同步履约状态失败',
scope: '[integration/platform-fulfillment/binding-state]',
},
),
)
export default router
@@ -115,6 +115,7 @@ type ManualSkuRow = {
config_semi_auto_enabled: boolean | null
config_semi_auto_platform: string | null
config_semi_auto_config_json: unknown
config_douyu_fulfillment_enabled: boolean | null
}
type ManualChannelConfig = {
@@ -353,7 +354,8 @@ export async function listManualSkus(input: Record<string, unknown> = {}) {
cfg.channels_json AS config_channels_json,
cfg.semi_auto_enabled AS config_semi_auto_enabled,
cfg.semi_auto_platform AS config_semi_auto_platform,
cfg.semi_auto_config_json AS config_semi_auto_config_json
cfg.semi_auto_config_json AS config_semi_auto_config_json,
cfg.douyu_fulfillment_enabled AS config_douyu_fulfillment_enabled
FROM product_catalog p
JOIN internal_skus product_sku ON product_sku.id = p.internal_sku_id
LEFT JOIN LATERAL (
@@ -468,6 +470,8 @@ export async function saveManualFulfillmentConfig(payload: JsonObject) {
const enabled = payload.enabled === false ? false : true
const note = optionalText(payload.note, 300)
const semiAuto = normalizeSemiAutoConfig(payload)
const douyuFulfillmentEnabled =
payload.douyuFulfillmentEnabled === true || payload.douyu_fulfillment_enabled === true
// 消耗积分为 0 = 成本不固定,客服确认履约时手填。
const costMode = primaryChannel.costMode
@@ -560,7 +564,8 @@ export async function saveManualFulfillmentConfig(payload: JsonObject) {
semi_auto_enabled = $10,
semi_auto_platform = $11,
semi_auto_config_json = $12::jsonb,
updated_at = $13
douyu_fulfillment_enabled = $13,
updated_at = $14
WHERE id = $1
RETURNING *`,
[
@@ -576,6 +581,7 @@ export async function saveManualFulfillmentConfig(payload: JsonObject) {
semiAuto.enabled,
semiAuto.platform,
JSON.stringify(semiAuto.config),
douyuFulfillmentEnabled,
now,
],
)
@@ -584,10 +590,11 @@ export async function saveManualFulfillmentConfig(payload: JsonObject) {
sku_key, canonical_product_id, platform_key, credit_quantity,
cost_mode, enabled, note, channels_json,
semi_auto_enabled, semi_auto_platform, semi_auto_config_json,
douyu_fulfillment_enabled,
created_at, updated_at
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8::jsonb,
$9, $10, $11::jsonb, $12, $12
$9, $10, $11::jsonb, $12, $13, $13
)
RETURNING *`,
[
@@ -602,6 +609,7 @@ export async function saveManualFulfillmentConfig(payload: JsonObject) {
semiAuto.enabled,
semiAuto.platform,
JSON.stringify(semiAuto.config),
douyuFulfillmentEnabled,
now,
],
)
@@ -1077,6 +1085,7 @@ export async function getManualFulfillmentConfig(skuKey: string) {
semi_auto_enabled: boolean
semi_auto_platform: string
semi_auto_config_json: unknown
douyu_fulfillment_enabled: boolean
created_at: string
updated_at: string
}>(
@@ -1208,6 +1217,7 @@ function mapManualSku(row: ManualSkuRow, unitPrices: Record<ManualPlatformKey, n
semiAutoEnabled: row.config_semi_auto_enabled === true,
semiAutoPlatform: String(row.config_semi_auto_platform || ''),
semiAutoConfig: normalizeStoredSemiAutoConfig(row.config_semi_auto_config_json),
douyuFulfillmentEnabled: row.config_douyu_fulfillment_enabled === true,
channels: mapConfiguredChannels(channels, unitPrices),
}
: null,
@@ -1228,6 +1238,7 @@ function mapManualConfig(
semi_auto_enabled: boolean
semi_auto_platform: string
semi_auto_config_json: unknown
douyu_fulfillment_enabled: boolean
created_at: string
updated_at: string
},
@@ -1251,6 +1262,7 @@ function mapManualConfig(
semiAutoEnabled: row.semi_auto_enabled === true,
semiAutoPlatform: String(row.semi_auto_platform || ''),
semiAutoConfig: normalizeStoredSemiAutoConfig(row.semi_auto_config_json),
douyuFulfillmentEnabled: row.douyu_fulfillment_enabled === true,
channels: mapConfiguredChannels(channels, unitPrices),
note: row.note || '',
createdAt: row.created_at,
@@ -93,6 +93,21 @@ export type DevSemiAutoIntegrationResult = DevMockSemiAutoResult & {
mappingId: number
}
export type DevDouyuFulfillmentMockResult = {
platform: 'douyu'
pipeline: 'order_service'
orderId: number
orderNo: string
orderItemId: number
fulfillmentId: number
configId: number
mappingId: number
skuKey: string
customerPath: string
adminPath: string
tips: string[]
}
export function getDevMockStatus() {
const enabled = isDevMockEnabled()
return {
@@ -113,6 +128,12 @@ export function getDevMockStatus() {
'创建人工渠道半自动测试单;可选择仅 Mock 订单,登录、绑定和票据注入走真实 Connector',
steps: ['create_order', 'login', 'binding', 'browser_ticket', 'complete'],
},
{
key: 'douyu_fulfillment',
name: '斗鱼直播账号履约',
description: '创建正式人工渠道测试单,供 live-hub 直播账号履约工作台读取',
steps: ['create_order', 'sync_livehub', 'map_commodity'],
},
]
: [],
defaultUid: '10001',
@@ -531,86 +552,59 @@ export async function createSemiAutoMock(
}
}
/**
* 真实履约链路集成测试单。
*
* 订单必须通过正式 upsertOrderFromSource 入库,再走 SKU 映射、渠道判定和
* Carrier 补偿;不直接写 order/order_item/fulfillment。
*/
export async function createSemiAutoIntegrationMock(
input: {
platform?: unknown
orderNo?: unknown
skuName?: unknown
quantity?: unknown
pageTitle?: unknown
browserTargetUrl?: unknown
connectorMode?: unknown
} = {},
): Promise<DevSemiAutoIntegrationResult> {
assertDevMockEnabled()
const platform = normalizeMockSemiAutoPlatform(input.platform)
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
const orderNo = String(
input.orderNo || `${platform === 'weibo' ? 'INTWB' : 'INTSA'}${suffix}`,
).trim()
const skuKey = normalizeMockSemiAutoSku(
input.skuName || `${platform === 'weibo' ? '微博' : '虎牙'}真实链路测试-${suffix}`,
platform,
)
const quantity = normalizeMockSemiAutoQuantity(input.quantity)
const connectorMode =
platform === 'weibo' ? 'embedded' : normalizeMockSemiAutoConnectorMode(input.connectorMode)
const provider = 'dev_integration'
const sourcePlatform = 'internal_test'
const shopId = 'dev-integration-shop'
const externalSkuCode = `INTEGRATION-${suffix}`
const pageTitle = String(
input.pageTitle || (platform === 'weibo' ? '微博账号登录授权' : '虎牙账号登录授权'),
)
.trim()
.slice(0, 60)
const browserTargetUrl = String(
input.browserTargetUrl ||
(platform === 'weibo' ? 'https://weibo.com/' : 'https://www.huya.com/'),
)
.trim()
.slice(0, 1000)
const existing = await findOrderByPlatformOrderId({
provider,
platform: sourcePlatform,
shopId,
platformOrderId: orderNo,
})
if (existing) {
throw createHttpError(`订单号已存在:${orderNo},请换一个或留空自动生成`, {
statusCode: 409,
errorCode: 'dev_integration_order_exists',
})
type PersistManualIntegrationOrderInput = {
orderNo: string
skuKey: string
externalSkuCode: string
provider: string
sourcePlatform: string
shopId: string
shopName: string
buyerId: string
buyerName: string
sourceTag: string
rawPayload: Record<string, unknown>
itemSnapshot: Record<string, unknown>
configNote: string
quantity?: number
semiAuto?: {
platform: 'huya' | 'weibo'
config: Record<string, unknown>
}
}
type PersistManualIntegrationOrderResult = {
orderId: number
orderNo: string
orderItemId: number
fulfillmentId: number
configId: number
mappingId: number
skuKey: string
}
/**
* 通过正式订单入口创建人工渠道测试单。
*
* 是否生成旧半自动任务由 semi_auto_enabled 决定,调用方无需直接写订单、
* 履约或任务表。
*/
async function persistManualIntegrationOrder(
input: PersistManualIntegrationOrderInput,
): Promise<PersistManualIntegrationOrderResult> {
const quantity = normalizeMockSemiAutoQuantity(input.quantity)
const config = await saveManualFulfillmentConfig({
skuKey,
skuKey: input.skuKey,
enabled: true,
note: '开发集成测试:真实订单履约链路',
note: input.configNote,
channels: [{ platformKey: 'fund_cash', creditQuantity: 100, enabled: true }],
semiAutoEnabled: true,
semiAutoPlatform: platform,
semiAutoConfig: {
pageTitle,
pageDescription: '真实入库链路测试订单:登录与 CK 获取使用当前 Connector。',
loginInstructions: '请使用本人账号完成登录授权,客服后续人工处理。',
loginMethods: ['sms', 'qr'],
browserTargets: [
{
key: platform,
label: platform === 'weibo' ? '微博' : '虎牙',
url: browserTargetUrl,
},
],
},
semiAutoEnabled: Boolean(input.semiAuto),
...(input.semiAuto
? {
semiAutoPlatform: input.semiAuto.platform,
semiAutoConfig: input.semiAuto.config,
}
: {}),
})
const configId = Number(config.id || 0)
if (!configId) {
@@ -620,53 +614,47 @@ export async function createSemiAutoIntegrationMock(
})
}
const mappingId = await upsertInternalSkuMapping({
provider,
shopId,
provider: input.provider,
shopId: input.shopId,
matchType: 'sku_code',
matchValue: externalSkuCode,
internalSku: skuKey,
matchValue: input.externalSkuCode,
internalSku: input.skuKey,
priority: 1000,
source: 'dev_integration',
note: `订单 ${orderNo}`,
source: input.sourceTag,
note: `订单 ${input.orderNo}`,
})
const now = nowIso()
const upserted = await upsertOrderFromSource(
{
provider,
platform: sourcePlatform,
shopId,
shopName: '半自动真实链路测试店',
platformOrderId: orderNo,
provider: input.provider,
platform: input.sourcePlatform,
shopId: input.shopId,
shopName: input.shopName,
platformOrderId: input.orderNo,
orderStatus: 'paid',
payStatus: 'paid',
buyerId: `integration-buyer-${suffix}`,
buyerName: '集成测试客户',
buyerId: input.buyerId,
buyerName: input.buyerName,
receiverContact: '',
totalAmount: 100 * quantity,
currency: 'CNY',
rawPayload: {
source: 'dev_integration',
orderNo,
skuKey,
platform,
...input.rawPayload,
createdAt: now,
},
paidAt: now,
items: [
{
quantity,
skuCode: externalSkuCode,
skuName: skuKey,
skuCode: input.externalSkuCode,
skuName: input.skuKey,
spec: {},
snapshot: {
source: 'dev_integration',
semiAuto: { platform },
},
snapshot: input.itemSnapshot,
},
],
},
{ sourceLabel: 'dev_semi_auto_integration' },
{ sourceLabel: input.sourceTag },
)
if (upserted.ignored || !upserted.order) {
throw createHttpError(upserted.ignoreReason || '真实链路订单入库失败', {
@@ -727,38 +715,167 @@ export async function createSemiAutoIntegrationMock(
expected: { status: 'assigned', channel: 'manual' },
onlyWhenConfigNull: true,
})
await ensureSemiAutoTasksForOrderItems([orderItemId])
const resolved = await query<{
fulfillment_id: number
fulfillment_channel: string
fulfillment_status: string
task_id: number
}>(
`
SELECT
f.id AS fulfillment_id,
f.channel AS fulfillment_channel,
f.status AS fulfillment_status,
f.status AS fulfillment_status
FROM fulfillments f
WHERE f.order_item_id = $1
LIMIT 1
`,
[orderItemId],
)
const fulfillment = resolved.rows[0]
if (
!fulfillment ||
fulfillment.fulfillment_channel !== 'manual' ||
fulfillment.fulfillment_status !== 'assigned'
) {
throw createHttpError(
`真实链路未生成人工履约:channel=${fulfillment?.fulfillment_channel || ''}, status=${fulfillment?.fulfillment_status || ''}`,
{ statusCode: 500, errorCode: 'dev_integration_manual_fulfillment_failed' },
)
}
return {
orderId: Number(upserted.order.id),
orderNo: input.orderNo,
orderItemId,
fulfillmentId: Number(fulfillment.fulfillment_id),
configId,
mappingId,
skuKey: input.skuKey,
}
}
/**
* 真实履约链路集成测试单。
*
* 订单必须通过正式 upsertOrderFromSource 入库,再走 SKU 映射、渠道判定和
* Carrier 补偿;不直接写 order/order_item/fulfillment。
*/
export async function createSemiAutoIntegrationMock(
input: {
platform?: unknown
orderNo?: unknown
skuName?: unknown
quantity?: unknown
pageTitle?: unknown
browserTargetUrl?: unknown
connectorMode?: unknown
} = {},
): Promise<DevSemiAutoIntegrationResult> {
assertDevMockEnabled()
const platform = normalizeMockSemiAutoPlatform(input.platform)
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
const orderNo = String(
input.orderNo || `${platform === 'weibo' ? 'INTWB' : 'INTSA'}${suffix}`,
).trim()
const skuKey = normalizeMockSemiAutoSku(
input.skuName || `${platform === 'weibo' ? '微博' : '虎牙'}真实链路测试-${suffix}`,
platform,
)
const quantity = normalizeMockSemiAutoQuantity(input.quantity)
const connectorMode =
platform === 'weibo' ? 'embedded' : normalizeMockSemiAutoConnectorMode(input.connectorMode)
const provider = 'dev_integration'
const sourcePlatform = 'internal_test'
const shopId = 'dev-integration-shop'
const externalSkuCode = `INTEGRATION-${suffix}`
const pageTitle = String(
input.pageTitle || (platform === 'weibo' ? '微博账号登录授权' : '虎牙账号登录授权'),
)
.trim()
.slice(0, 60)
const browserTargetUrl = String(
input.browserTargetUrl ||
(platform === 'weibo' ? 'https://weibo.com/' : 'https://www.huya.com/'),
)
.trim()
.slice(0, 1000)
const existing = await findOrderByPlatformOrderId({
provider,
platform: sourcePlatform,
shopId,
platformOrderId: orderNo,
})
if (existing) {
throw createHttpError(`订单号已存在:${orderNo},请换一个或留空自动生成`, {
statusCode: 409,
errorCode: 'dev_integration_order_exists',
})
}
const persisted = await persistManualIntegrationOrder({
orderNo,
skuKey,
externalSkuCode,
provider,
sourcePlatform,
shopId,
shopName: '半自动真实链路测试店',
buyerId: `integration-buyer-${suffix}`,
buyerName: '集成测试客户',
sourceTag: 'dev_semi_auto_integration',
rawPayload: {
source: 'dev_integration',
orderNo,
skuKey,
platform,
},
itemSnapshot: {
source: 'dev_integration',
semiAuto: { platform },
},
configNote: '开发集成测试:真实订单履约链路',
quantity,
semiAuto: {
platform,
config: {
pageTitle,
pageDescription: '真实入库链路测试订单:登录与 CK 获取使用当前 Connector。',
loginInstructions: '请使用本人账号完成登录授权,客服后续人工处理。',
loginMethods: ['sms', 'qr'],
browserTargets: [
{
key: platform,
label: platform === 'weibo' ? '微博' : '虎牙',
url: browserTargetUrl,
},
],
},
},
})
await ensureSemiAutoTasksForOrderItems([persisted.orderItemId])
const resolved = await query<{
task_id: number
}>(
`
SELECT
task.id AS task_id
FROM fulfillments f
LEFT JOIN semi_auto_tasks task ON task.order_item_id = f.order_item_id
WHERE f.order_item_id = $1
LIMIT 1
`,
[orderItemId],
[persisted.orderItemId],
)
const row = resolved.rows[0]
if (
!row ||
row.fulfillment_channel !== 'manual' ||
row.fulfillment_status !== 'assigned' ||
!Number(row.task_id)
) {
throw createHttpError(
`真实链路未生成半自动任务:channel=${row?.fulfillment_channel || ''}, status=${row?.fulfillment_status || ''}, task=${row?.task_id || 0}`,
{ statusCode: 500, errorCode: 'dev_integration_semi_auto_task_failed' },
)
if (!row || !Number(row.task_id)) {
throw createHttpError('真实链路未生成半自动任务', {
statusCode: 500,
errorCode: 'dev_integration_semi_auto_task_failed',
})
}
await query('UPDATE semi_auto_tasks SET connector_mode = $2, updated_at = NOW() WHERE id = $1', [
@@ -771,17 +888,17 @@ export async function createSemiAutoIntegrationMock(
platform: 'semi_auto',
semiAutoPlatform: platform,
pipeline: 'order_service',
orderId: Number(upserted.order.id),
orderNo,
orderItemId,
fulfillmentId: Number(row.fulfillment_id),
configId,
orderId: persisted.orderId,
orderNo: persisted.orderNo,
orderItemId: persisted.orderItemId,
fulfillmentId: persisted.fulfillmentId,
configId: persisted.configId,
taskId: Number(row.task_id),
skuKey,
skuKey: persisted.skuKey,
connectorMode,
connectorConfigured,
mappingId,
customerPath: buildMockCustomerPath(platform, orderNo),
mappingId: persisted.mappingId,
customerPath: buildMockCustomerPath(platform, persisted.orderNo),
adminPath: `/admin/semi-auto-tasks?keyword=${encodeURIComponent(orderNo)}`,
tips: [
'订单通过正式 upsertOrderFromSource 入库。',
@@ -794,6 +911,116 @@ export async function createSemiAutoIntegrationMock(
}
}
/**
* 斗鱼直播账号履约专用测试单。
*
* 只生成 live-hub 工作台需要的正式人工履约数据,不启用 order_site 的
* huya/weibo 半自动任务。
*/
export async function createDouyuFulfillmentMock(
input: {
orderNo?: unknown
skuName?: unknown
} = {},
): Promise<DevDouyuFulfillmentMockResult> {
assertDevMockEnabled()
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
const orderNo = String(input.orderNo || `LIVEHUBDOUYU${suffix}`).trim()
const requestedSkuKey = String(input.skuName || `斗鱼精英宝典联调-${suffix}`)
.trim()
.slice(0, 48)
if (!requestedSkuKey || !containsCjk(requestedSkuKey)) {
throw createHttpError('内部 SKU 名称必须包含中文', {
statusCode: 400,
errorCode: 'dev_douyu_fulfillment_sku_invalid',
})
}
const provider = 'livehub_douyu_dev'
const sourcePlatform = 'internal_test'
const shopId = 'livehub-douyu-dev-shop'
const existing = await findOrderByPlatformOrderId({
provider,
platform: sourcePlatform,
shopId,
platformOrderId: orderNo,
})
if (existing) {
throw createHttpError(`订单号已存在:${orderNo},请换一个或留空自动生成`, {
statusCode: 409,
errorCode: 'dev_douyu_fulfillment_order_exists',
})
}
const persisted = await persistManualIntegrationOrder({
orderNo,
skuKey: requestedSkuKey,
externalSkuCode: `DOUYU-FULFILLMENT-${suffix}`,
provider,
sourcePlatform,
shopId,
shopName: '直播账号履约联调店',
buyerId: `douyu-fulfillment-buyer-${suffix}`,
buyerName: '斗鱼履约联调客户',
sourceTag: 'dev_douyu_fulfillment',
rawPayload: {
source: 'dev_douyu_fulfillment',
orderNo,
skuKey: requestedSkuKey,
targetPlatform: 'douyu',
},
itemSnapshot: {
source: 'dev_douyu_fulfillment',
targetPlatform: 'douyu',
scope: 'elite',
},
configNote: '开发 Mock:斗鱼直播账号履约',
})
await query(
`UPDATE manual_fulfillment_configs
SET douyu_fulfillment_enabled = TRUE, updated_at = NOW()
WHERE id = $1`,
[persisted.configId],
)
const verification = await query<{
semi_auto_task_count: number
semi_auto_enabled: boolean
}>(
`
SELECT
COUNT(task.id)::int AS semi_auto_task_count,
BOOL_OR(cfg.semi_auto_enabled) AS semi_auto_enabled
FROM fulfillments f
JOIN manual_fulfillment_configs cfg ON cfg.id = f.fulfillment_config_id
LEFT JOIN semi_auto_tasks task ON task.order_item_id = f.order_item_id
WHERE f.id = $1
`,
[persisted.fulfillmentId],
)
const row = verification.rows[0]
if (Number(row?.semi_auto_task_count || 0) > 0 || row?.semi_auto_enabled === true) {
throw createHttpError('斗鱼专用 Mock 不应生成半自动任务', {
statusCode: 500,
errorCode: 'dev_douyu_fulfillment_semi_auto_conflict',
})
}
return {
platform: 'douyu',
pipeline: 'order_service',
...persisted,
customerPath: `/coll/d/${encodeURIComponent(persisted.orderNo)}`,
adminPath: `/admin/orders/${persisted.orderId}`,
tips: [
'订单已通过 upsertOrderFromSource 正式入库。',
'履约渠道为 manual,状态为 assigned,且不会生成 huya/weibo 半自动任务。',
`在 live-hub 直播账号履约工作台同步后,用内部 SKU「${persisted.skuKey}」配置斗鱼商品映射。`,
],
}
}
function normalizeMockSemiAutoPlatform(value: unknown): 'huya' | 'weibo' {
return String(value || '')
.trim()
@@ -0,0 +1,871 @@
import type { PoolClient } from 'pg'
import { query, withTransaction } from '../../db/client.js'
import { publishRealtimeEvent } from '../realtime/realtime-event-service.js'
import { nowIso } from '../../utils/time.js'
import { createHttpError } from '../../utils/http.js'
import { logWarn } from '../../utils/logger.js'
type DouyuTaskRow = {
id: number
order_id: number
order_item_id: number
fulfillment_id: number | null
manual_fulfillment_config_id: number | null
live_session_id: number | null
status: string
customer_role_name: string
customer_platform: string
customer_system: string
binding_phase: string
live_execution_status: string
live_binding_status: string
issue_code: string
last_error: string
bound_role_name: string
bound_area_name: string
bound_plat_name: string
customer_link_opened_at: string | null
binding_started_at: string | null
bound_at: string | null
completed_at: string | null
last_synced_at: string | null
qr_url: string
qr_generated_at: string | null
qr_expires_at: string | null
created_at: string
updated_at: string
platform_order_id: string
sku_code: string
sku_name: string
quantity: number
product_name: string
fulfillment_status: string
}
type LiveBindingState = {
sessionId: number
platformOrderId: string
sourceOrderItemId: string
productName: string
quantity: number
executionStatus: string
bindingStatus: string
exchangeStatus: string
issueCode: string
message: string
accountReady: boolean
bindTaskId: number | null
bindTaskStatus: string
bindPhase: string
qrUrl: string
qrGeneratedAt: string
qrExpiresAt: string
roleName: string
areaName: string
platName: string
bindReadyForConfirm: boolean
bindConfirmed: boolean
customerProfileReset?: boolean
resetReason?: string
completedAt: string | null
updatedAt: string
}
type LiveBindingBatchResponse = {
items: LiveBindingState[]
}
const AUTO_DISCOVERY_INTERVAL_MS = 15_000
const LIVE_STATE_SYNC_INTERVAL_MS = 60_000
const TERMINAL_TASK_STATUSES = new Set(['completed', 'cancelled'])
let lastAutomaticDiscoveryAt = 0
let automaticDiscoveryInFlight: Promise<{ created: number; updated: number } | null> | null = null
const TASK_SELECT = `
SELECT
task.*,
o.platform_order_id,
oi.sku_code,
oi.sku_name,
oi.quantity,
COALESCE(NULLIF(oi.sku_name, ''), NULLIF(oi.sku_code, ''), '订单商品') AS product_name,
f.status AS fulfillment_status
FROM douyu_fulfillment_tasks task
JOIN orders o ON o.id = task.order_id
JOIN order_items oi ON oi.id = task.order_item_id
LEFT JOIN fulfillments f ON f.id = task.fulfillment_id
`
function liveHubBaseUrl() {
return String(process.env.LIVE_HUB_PLATFORM_FULFILLMENT_URL || 'http://127.0.0.1:8800')
.trim()
.replace(/\/+$/, '')
}
function integrationKey() {
const key = String(process.env.PLATFORM_FULFILLMENT_INTEGRATION_KEY || '').trim()
if (!key) {
throw createHttpError('直播账号履约集成密钥未配置', {
statusCode: 503,
errorCode: 'live_hub_integration_not_configured',
})
}
return key
}
async function liveHubRequest<T>(
path: string,
init: { method?: string; body?: Record<string, unknown> } = {},
): Promise<T> {
const response = await fetch(`${liveHubBaseUrl()}${path}`, {
method: init.method || 'GET',
headers: {
'Content-Type': 'application/json',
'X-Integration-Key': integrationKey(),
},
...(init.body ? { body: JSON.stringify(init.body) } : {}),
signal: AbortSignal.timeout(20_000),
})
const text = await response.text()
let payload: unknown = null
try {
payload = text ? JSON.parse(text) : null
} catch {
payload = text
}
if (!response.ok) {
const detail =
payload && typeof payload === 'object' && 'detail' in payload
? String((payload as { detail?: unknown }).detail || '')
: String(payload || '')
throw createHttpError(detail || '直播账号履约服务请求失败', {
statusCode: response.status >= 500 ? 502 : response.status,
errorCode: 'live_hub_fulfillment_request_failed',
})
}
return payload as T
}
async function appendEvent(
client: Pick<PoolClient, 'query'>,
taskId: number,
eventType: string,
actorType: 'system' | 'customer' | 'admin' | 'integration',
detail: Record<string, unknown> = {},
) {
await client.query(
`
INSERT INTO douyu_fulfillment_events (
task_id, event_type, actor_type, detail_json, created_at
) VALUES ($1, $2, $3, $4::jsonb, NOW())
`,
[taskId, eventType, actorType, JSON.stringify(detail)],
)
}
export async function ensureDouyuFulfillmentTasks(orderNo = '') {
const params: unknown[] = []
let filter = ''
const normalizedOrderNo = String(orderNo || '').trim()
if (normalizedOrderNo) {
params.push(normalizedOrderNo)
filter = 'AND o.platform_order_id = $1'
}
const candidates = await query<{
order_id: number
order_item_id: number
fulfillment_id: number
config_id: number
platform_order_id: string
}>(
`
SELECT
o.id AS order_id,
oi.id AS order_item_id,
f.id AS fulfillment_id,
cfg.id AS config_id,
o.platform_order_id
FROM orders o
JOIN order_items oi ON oi.order_id = o.id
JOIN fulfillments f ON f.order_item_id = oi.id
JOIN manual_fulfillment_configs cfg ON cfg.id = f.fulfillment_config_id
WHERE cfg.enabled = TRUE
AND cfg.douyu_fulfillment_enabled = TRUE
AND f.channel = 'manual'
AND f.status IN ('assigned', 'processing', 'completed')
${filter}
ORDER BY o.id DESC, oi.id ASC
`,
params,
)
if (candidates.rows.length === 0) return { created: 0, updated: 0 }
let created = 0
await withTransaction(async (client) => {
for (const row of candidates.rows) {
const inserted = await client.query<{ id: number; inserted: boolean }>(
`
INSERT INTO douyu_fulfillment_tasks (
order_id, order_item_id, fulfillment_id, manual_fulfillment_config_id,
status, created_at, updated_at
) VALUES ($1, $2, $3, $4, 'waiting_profile', NOW(), NOW())
ON CONFLICT (order_item_id) DO UPDATE SET
fulfillment_id = EXCLUDED.fulfillment_id,
manual_fulfillment_config_id = EXCLUDED.manual_fulfillment_config_id,
updated_at = CASE
WHEN douyu_fulfillment_tasks.fulfillment_id IS DISTINCT FROM EXCLUDED.fulfillment_id
OR douyu_fulfillment_tasks.manual_fulfillment_config_id
IS DISTINCT FROM EXCLUDED.manual_fulfillment_config_id
THEN NOW()
ELSE douyu_fulfillment_tasks.updated_at
END
RETURNING id, (xmax = 0) AS inserted
`,
[row.order_id, row.order_item_id, row.fulfillment_id, row.config_id],
)
const taskId = Number(inserted.rows[0]?.id || 0)
if (!taskId) continue
if (inserted.rows[0]?.inserted) {
created += 1
await appendEvent(client, taskId, 'task_created', 'system', {
platformOrderId: row.platform_order_id,
})
}
}
})
return { created, updated: candidates.rows.length - created }
}
async function ensureDouyuFulfillmentTasksAutomatically() {
if (automaticDiscoveryInFlight) return automaticDiscoveryInFlight
if (Date.now() - lastAutomaticDiscoveryAt < AUTO_DISCOVERY_INTERVAL_MS) return null
lastAutomaticDiscoveryAt = Date.now()
const run = ensureDouyuFulfillmentTasks()
.catch((error) => {
lastAutomaticDiscoveryAt = 0
throw error
})
.finally(() => {
automaticDiscoveryInFlight = null
})
automaticDiscoveryInFlight = run
return run
}
async function loadTaskByOrderNo(orderNo: string) {
const normalized = String(orderNo || '').trim()
if (!normalized) {
throw createHttpError('订单号不能为空', {
statusCode: 400,
errorCode: 'douyu_order_no_required',
})
}
await ensureDouyuFulfillmentTasks(normalized)
const result = await query<DouyuTaskRow>(
`${TASK_SELECT}
WHERE o.platform_order_id = $1
ORDER BY task.id ASC
LIMIT 1`,
[normalized],
)
const task = result.rows[0]
if (!task) {
throw createHttpError('订单不存在或尚未启用斗鱼领取', {
statusCode: 404,
errorCode: 'douyu_fulfillment_not_found',
})
}
return task
}
async function loadTask(taskId: number) {
const result = await query<DouyuTaskRow>(`${TASK_SELECT} WHERE task.id = $1 LIMIT 1`, [taskId])
const task = result.rows[0]
if (!task) {
throw createHttpError('斗鱼领取任务不存在', {
statusCode: 404,
errorCode: 'douyu_fulfillment_not_found',
})
}
return task
}
function normalizeText(value: unknown) {
return String(value || '')
.replace(/\s+/g, '')
.toLowerCase()
}
export function compareCustomerRole(task: DouyuTaskRow, live: LiveBindingState) {
const roleMatched =
Boolean(task.customer_role_name && live.roleName) &&
normalizeText(task.customer_role_name) === normalizeText(live.roleName)
const liveParts = new Set([normalizeText(live.areaName), normalizeText(live.platName)])
const expected: string[] = []
if (task.customer_platform === 'wechat') expected.push('微信')
if (task.customer_platform === 'qq') expected.push('qq', '手q')
if (task.customer_system === 'ios') expected.push('苹果', 'ios')
if (task.customer_system === 'android') expected.push('安卓', 'android')
const channelMatched = expected.every((item) =>
[...liveParts].some((part) => part.includes(item) || item.includes(part)),
)
return {
matched: roleMatched && channelMatched,
roleMatched,
channelMatched,
message:
roleMatched && channelMatched
? '客户资料与平台识别角色一致'
: '客户资料与平台识别角色不一致,请修改资料或联系客服',
}
}
const BINDING_FAILURE_ISSUES = new Set([
'binding_failed',
'account_role_cooldown',
'customer_role_cooldown',
])
export function statusForLive(live: LiveBindingState): string {
if (live.customerProfileReset === true) return 'waiting_profile'
if (live.executionStatus === 'completed') return 'completed'
if (live.executionStatus === 'cancelled') return 'cancelled'
if (live.bindingStatus === 'failed' || BINDING_FAILURE_ISSUES.has(live.issueCode)) {
return 'failed'
}
if (live.executionStatus === 'manual_required') return 'manual_required'
if (live.executionStatus === 'allocated') return 'allocated'
if (live.bindConfirmed) return 'waiting_operator'
if (live.bindReadyForConfirm) return 'role_ready'
if (live.qrUrl) return 'qr_pending'
if (
live.issueCode === 'mapping_missing' ||
live.issueCode === 'no_eligible_account' ||
live.issueCode === 'elite_not_opened' ||
live.issueCode === 'points_short' ||
!live.accountReady
) {
return 'preparing'
}
if (live.issueCode) return 'failed'
return 'preparing'
}
async function updateTaskFromLiveState(
client: Pick<PoolClient, 'query'>,
task: DouyuTaskRow,
live: LiveBindingState,
now: string,
) {
const resetCustomerProfile = live.customerProfileReset === true
const nextStatus = statusForLive(live)
await client.query(
`
UPDATE douyu_fulfillment_tasks
SET live_session_id = $2,
status = $3,
binding_phase = $4,
live_execution_status = $5,
live_binding_status = $6,
issue_code = $7,
last_error = $8,
bound_role_name = $9,
bound_area_name = $10,
bound_plat_name = $11,
binding_started_at = CASE
WHEN $19 THEN NULL
WHEN $12 <> '' THEN COALESCE(binding_started_at, NOW())
ELSE binding_started_at
END,
bound_at = CASE
WHEN $19 THEN NULL
WHEN $13 THEN COALESCE(bound_at, NOW())
ELSE bound_at
END,
completed_at = CASE
WHEN $19 THEN NULL
WHEN $14 THEN COALESCE(completed_at, NOW())
ELSE completed_at
END,
customer_role_name = CASE WHEN $19 THEN '' ELSE customer_role_name END,
customer_platform = CASE WHEN $19 THEN '' ELSE customer_platform END,
customer_system = CASE WHEN $19 THEN '' ELSE customer_system END,
qr_url = $15,
qr_generated_at = NULLIF($16, '')::timestamptz,
qr_expires_at = NULLIF($17, '')::timestamptz,
last_synced_at = NOW(),
updated_at = $18
WHERE id = $1
`,
[
task.id,
live.sessionId,
nextStatus,
live.bindPhase,
live.executionStatus,
live.bindingStatus,
live.issueCode,
live.message,
live.roleName,
live.areaName,
live.platName,
live.qrUrl,
live.bindConfirmed,
live.executionStatus === 'completed',
live.qrUrl,
live.qrGeneratedAt,
live.qrExpiresAt,
now,
resetCustomerProfile,
],
)
if (nextStatus !== task.status) {
await appendEvent(client, task.id, 'status_changed', 'integration', {
fromStatus: task.status,
toStatus: nextStatus,
bindPhase: live.bindPhase,
})
}
if (resetCustomerProfile) {
await appendEvent(client, task.id, 'customer_profile_reset', 'integration', {
reason: String(live.resetReason || ''),
})
}
}
async function applyLiveState(task: DouyuTaskRow, live: LiveBindingState) {
await withTransaction(async (client) => {
await updateTaskFromLiveState(client, task, live, nowIso())
})
const updated = await loadTask(task.id)
return { task: updated, live, comparison: compareCustomerRole(updated, live) }
}
async function applyLiveStates(entries: Array<{ task: DouyuTaskRow; live: LiveBindingState }>) {
if (entries.length === 0) return
const now = nowIso()
await withTransaction(async (client) => {
for (const entry of entries) {
await updateTaskFromLiveState(client, entry.task, entry.live, now)
}
})
}
function isLiveBindingState(value: unknown): value is LiveBindingState {
if (!value || typeof value !== 'object') return false
const item = value as Partial<LiveBindingState>
return (
Number.isInteger(Number(item.sessionId)) &&
Number(item.sessionId) > 0 &&
typeof item.executionStatus === 'string' &&
typeof item.bindingStatus === 'string' &&
typeof item.exchangeStatus === 'string' &&
typeof item.issueCode === 'string' &&
typeof item.message === 'string'
)
}
function liveBindingStateFromTask(task: DouyuTaskRow): LiveBindingState {
return {
sessionId: Number(task.live_session_id),
platformOrderId: task.platform_order_id,
sourceOrderItemId: String(task.order_item_id),
productName: task.product_name,
quantity: Number(task.quantity || 1),
executionStatus: task.live_execution_status || 'preparing',
bindingStatus: task.live_binding_status || 'not_started',
exchangeStatus: '',
issueCode: task.issue_code || '',
message: task.last_error || '',
accountReady: !['waiting_profile', 'preparing'].includes(task.status),
bindTaskId: null,
bindTaskStatus: '',
bindPhase: task.binding_phase || '',
qrUrl: task.qr_url || '',
qrGeneratedAt: task.qr_generated_at || '',
qrExpiresAt: task.qr_expires_at || '',
roleName: task.bound_role_name || '',
areaName: task.bound_area_name || '',
platName: task.bound_plat_name || '',
bindReadyForConfirm: task.status === 'role_ready',
bindConfirmed: ['bound', 'waiting_operator', 'processing', 'completed'].includes(task.status),
completedAt: task.completed_at,
updatedAt: task.updated_at,
}
}
export async function applyLiveBindingStateSnapshot(
input: unknown,
options: { eventId?: string; eventType?: string } = {},
) {
const rawItems =
input && typeof input === 'object' && Array.isArray((input as { items?: unknown }).items)
? (input as { items: unknown[] }).items
: []
const items = rawItems.filter(isLiveBindingState)
if (items.length === 0) {
return { received: rawItems.length, updated: 0 }
}
const sessionIds = Array.from(
new Set(items.map((item) => Number(item.sessionId)).filter((id) => id > 0)),
)
const orderNos = Array.from(
new Set(items.map((item) => String(item.platformOrderId || '').trim()).filter(Boolean)),
).slice(0, 50)
const orderItemIds = Array.from(
new Set(items.map((item) => String(item.sourceOrderItemId || '').trim()).filter(Boolean)),
)
if (sessionIds.length === 0 && orderNos.length === 0 && orderItemIds.length === 0) {
return { received: rawItems.length, updated: 0 }
}
// Webhook 可能先于客户首次打开领取页到达;先幂等补齐本地订单投影。
for (const orderNo of orderNos) {
await ensureDouyuFulfillmentTasks(orderNo)
}
const result = await withTransaction(async (client) => {
const eventId = String(options.eventId || '').trim()
if (eventId) {
const claimed = await client.query(
`
INSERT INTO integration_inbox (
event_id, source, event_type, received_at, processed_at
) VALUES ($1, 'live_hub', $2, NOW(), NOW())
ON CONFLICT (event_id) DO NOTHING
RETURNING event_id
`,
[eventId, String(options.eventType || '')],
)
if (claimed.rowCount === 0) {
return { received: rawItems.length, updated: 0 }
}
}
const tasks = await client.query<DouyuTaskRow>(
`${TASK_SELECT}
WHERE task.live_session_id = ANY($1::bigint[])
OR CAST(task.order_item_id AS text) = ANY($2::text[])
OR o.platform_order_id = ANY($3::text[])`,
[sessionIds, orderItemIds, orderNos],
)
const taskBySessionId = new Map(
tasks.rows
.filter((task) => task.live_session_id)
.map((task) => [Number(task.live_session_id), task]),
)
const taskByOrderItemId = new Map(tasks.rows.map((task) => [String(task.order_item_id), task]))
const now = nowIso()
const entries = items.flatMap((live) => {
const task =
taskBySessionId.get(Number(live.sessionId)) ||
taskByOrderItemId.get(String(live.sourceOrderItemId || ''))
return task ? [{ task, live }] : []
})
for (const entry of entries) {
await updateTaskFromLiveState(client, entry.task, entry.live, now)
}
return { received: rawItems.length, updated: entries.length }
})
if (result.updated > 0) {
publishRealtimeEvent({
type: 'order.changed',
entityId: 0,
scopes: ['admin_douyu_fulfillment'],
operation: 'refresh',
data: { douyuFulfillmentUpdated: true },
admin: true,
})
}
return result
}
async function ensureLiveSession(task: DouyuTaskRow) {
const live = await liveHubRequest<LiveBindingState>(
'/api/integration/platform-fulfillment/customer-sessions/ensure',
{
method: 'POST',
body: {
source_order_item_id: String(task.order_item_id),
platform_order_id: task.platform_order_id,
},
},
)
return applyLiveState(task, live)
}
export async function getCustomerDouyuFulfillment(orderNo: string) {
const task = await loadTaskByOrderNo(orderNo)
if (!task.customer_link_opened_at) {
await withTransaction(async (client) => {
await client.query(
`UPDATE douyu_fulfillment_tasks
SET customer_link_opened_at = COALESCE(customer_link_opened_at, NOW())
WHERE id = $1`,
[task.id],
)
await appendEvent(client, task.id, 'customer_link_opened', 'customer')
})
}
const session = await ensureLiveSession(task)
return {
task: session.task,
live: session.live,
comparison: session.comparison,
linkPath: `/coll/d/${encodeURIComponent(task.platform_order_id)}`,
}
}
export async function saveDouyuCustomerProfile(
orderNo: string,
input: { roleName?: unknown; platform?: unknown; system?: unknown },
) {
const task = await loadTaskByOrderNo(orderNo)
if (task.status === 'completed' || task.status === 'cancelled') {
throw createHttpError('当前订单已结束,不能修改资料', {
statusCode: 409,
errorCode: 'douyu_fulfillment_closed',
})
}
const roleName = String(input.roleName ?? '')
.trim()
.slice(0, 100)
const platform = String(input.platform ?? '')
.trim()
.toLowerCase()
const system = String(input.system ?? '')
.trim()
.toLowerCase()
if (!roleName || !['wechat', 'qq'].includes(platform) || !['ios', 'android'].includes(system)) {
throw createHttpError('请完整填写角色名、微信/QQ 和苹果/安卓', {
statusCode: 400,
errorCode: 'douyu_customer_profile_invalid',
})
}
await withTransaction(async (client) => {
await client.query(
`
UPDATE douyu_fulfillment_tasks
SET customer_role_name = $2,
customer_platform = $3,
customer_system = $4,
status = CASE WHEN status = 'waiting_profile' THEN 'preparing' ELSE status END,
updated_at = NOW()
WHERE id = $1
`,
[task.id, roleName, platform, system],
)
await appendEvent(client, task.id, 'customer_profile_saved', 'customer', {
roleName,
platform,
system,
})
})
return getCustomerDouyuFulfillment(orderNo)
}
export async function startDouyuCustomerBinding(orderNo: string, forceRefresh = false) {
let task = await loadTaskByOrderNo(orderNo)
const session = await ensureLiveSession(task)
task = session.task
if (!task.live_session_id) {
throw createHttpError('直播账号履约会话尚未准备完成', {
statusCode: 409,
errorCode: 'douyu_live_session_not_ready',
})
}
const live = await liveHubRequest<LiveBindingState>(
`/api/integration/platform-fulfillment/customer-sessions/${task.live_session_id}/binding/start`,
{ method: 'POST', body: { force_refresh: forceRefresh } },
)
return applyLiveState(task, live)
}
export async function refreshDouyuCustomerBinding(orderNo: string) {
const task = await loadTaskByOrderNo(orderNo)
if (!task.live_session_id) return ensureLiveSession(task)
const live = await liveHubRequest<LiveBindingState>(
`/api/integration/platform-fulfillment/customer-sessions/${task.live_session_id}/status`,
)
return applyLiveState(task, live)
}
export async function getDouyuCustomerFulfillmentCached(orderNo: string) {
let task = await loadTaskByOrderNo(orderNo)
if (!task.live_session_id) {
return ensureLiveSession(task)
}
task = await loadTask(task.id)
const live = liveBindingStateFromTask(task)
return {
task,
live,
comparison: compareCustomerRole(task, live),
linkPath: `/coll/d/${encodeURIComponent(task.platform_order_id)}`,
}
}
export async function confirmDouyuCustomerBinding(orderNo: string) {
const refreshed = await refreshDouyuCustomerBinding(orderNo)
if (!refreshed.comparison.matched) {
throw createHttpError(refreshed.comparison.message, {
statusCode: 409,
errorCode: 'douyu_customer_role_mismatch',
})
}
const task = refreshed.task
if (!task.live_session_id) {
throw createHttpError('直播账号履约会话尚未准备完成', {
statusCode: 409,
errorCode: 'douyu_live_session_not_ready',
})
}
const live = await liveHubRequest<LiveBindingState>(
`/api/integration/platform-fulfillment/customer-sessions/${task.live_session_id}/binding/confirm`,
{ method: 'POST' },
)
return applyLiveState(task, live)
}
async function syncLiveStatesForTasks(tasks: DouyuTaskRow[], force = false) {
const now = Date.now()
const candidates = tasks.filter((task) => {
if (!task.live_session_id || TERMINAL_TASK_STATUSES.has(task.status)) return false
if (force) return true
const lastSyncedAt = Date.parse(task.last_synced_at || '')
return !lastSyncedAt || now - lastSyncedAt >= LIVE_STATE_SYNC_INTERVAL_MS
})
if (candidates.length === 0) return
try {
const response = await liveHubRequest<LiveBindingBatchResponse>(
'/api/integration/platform-fulfillment/customer-sessions/status/batch',
{
method: 'POST',
body: {
task_ids: candidates.map((task) => Number(task.live_session_id)),
},
},
)
const taskBySessionId = new Map(candidates.map((task) => [Number(task.live_session_id), task]))
const entries = response.items.flatMap((live) => {
const task = taskBySessionId.get(Number(live.sessionId))
return task ? [{ task, live }] : []
})
await applyLiveStates(entries)
if (entries.length > 0) {
publishRealtimeEvent({
type: 'order.changed',
entityId: 0,
scopes: ['admin_douyu_fulfillment'],
operation: 'refresh',
data: { douyuFulfillmentUpdated: true },
admin: true,
})
}
} catch (error) {
logWarn('[douyu-fulfillment]', '自动同步直播账号履约状态失败', { error })
}
}
export async function reconcileDouyuFulfillmentStates() {
const rows = await query<DouyuTaskRow>(
`${TASK_SELECT}
WHERE task.live_session_id IS NOT NULL
AND task.status NOT IN ('completed', 'cancelled')
ORDER BY task.updated_at ASC, task.id ASC
LIMIT 100`,
)
await syncLiveStatesForTasks(rows.rows, true)
return { checked: rows.rows.length }
}
export async function syncDouyuFulfillmentTasks() {
const synced = await ensureDouyuFulfillmentTasks()
const states = await reconcileDouyuFulfillmentStates()
return { ...synced, checked: states.checked }
}
export async function listDouyuFulfillmentTasks(
input: {
keyword?: unknown
status?: unknown
page?: unknown
pageSize?: unknown
} = {},
) {
await ensureDouyuFulfillmentTasksAutomatically()
const page = Math.max(1, Number(input.page || 1))
const pageSize = Math.max(1, Math.min(100, Number(input.pageSize || 20)))
const keyword = String(input.keyword || '').trim()
const status = String(input.status || '').trim()
const params: unknown[] = []
const filters: string[] = []
if (keyword) {
params.push(`%${keyword}%`)
filters.push(`(
o.platform_order_id ILIKE $${params.length}
OR oi.sku_name ILIKE $${params.length}
OR task.customer_role_name ILIKE $${params.length}
)`)
}
if (status) {
params.push(status)
filters.push(`task.status = $${params.length}`)
}
const where = filters.length ? `WHERE ${filters.join(' AND ')}` : ''
const count = await query<{ total: number }>(
`SELECT COUNT(*)::int AS total
FROM douyu_fulfillment_tasks task
JOIN orders o ON o.id = task.order_id
JOIN order_items oi ON oi.id = task.order_item_id
${where}`,
params,
)
params.push(pageSize, (page - 1) * pageSize)
const rows = await query<DouyuTaskRow>(
`${TASK_SELECT}
${where}
ORDER BY task.updated_at DESC, task.id DESC
LIMIT $${params.length - 1} OFFSET $${params.length}`,
params,
)
return {
items: rows.rows.map((task) => ({
...task,
linkPath: `/coll/d/${encodeURIComponent(task.platform_order_id)}`,
})),
pagination: { page, pageSize, total: Number(count.rows[0]?.total || 0) },
}
}
export async function getDouyuFulfillmentDetail(orderNo: string) {
const task = await loadTaskByOrderNo(orderNo)
const [session, events] = await Promise.all([
ensureLiveSession(task),
query<{
id: number
event_type: string
actor_type: string
detail_json: Record<string, unknown>
created_at: string
}>(
`SELECT id, event_type, actor_type, detail_json, created_at
FROM douyu_fulfillment_events
WHERE task_id = $1
ORDER BY id DESC
LIMIT 200`,
[task.id],
),
])
return {
...session,
linkPath: `/coll/d/${encodeURIComponent(task.platform_order_id)}`,
events: events.rows,
}
}
@@ -0,0 +1,95 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import {
applyLiveBindingStateSnapshot,
compareCustomerRole,
statusForLive,
} from './douyu-fulfillment-service.js'
const task = {
customer_role_name: '狗鼻子弗尼亚bd',
customer_platform: 'wechat',
customer_system: 'android',
} as never
const live = {
roleName: '狗鼻子弗尼亚bd',
areaName: '微信',
platName: '安卓(android)',
} as never
test('斗鱼客户资料与平台角色一致', () => {
const result = compareCustomerRole(task, live)
assert.equal(result.matched, true)
assert.equal(result.roleMatched, true)
assert.equal(result.channelMatched, true)
})
test('斗鱼客户资料平台或系统不一致时禁止确认', () => {
const result = compareCustomerRole(task, {
...live,
areaName: 'QQ',
platName: '苹果(iOS)',
} as never)
assert.equal(result.matched, false)
assert.equal(result.channelMatched, false)
})
test('斗鱼客户资料角色名不一致时禁止确认', () => {
const result = compareCustomerRole(task, { ...live, roleName: '另一个角色' } as never)
assert.equal(result.matched, false)
assert.equal(result.roleMatched, false)
})
test('绑定失败优先于旧角色确认标记', () => {
const status = statusForLive({
executionStatus: 'manual_required',
bindingStatus: 'failed',
issueCode: 'customer_role_cooldown',
bindReadyForConfirm: true,
bindConfirmed: false,
qrUrl: 'https://example.com/old-qr',
accountReady: true,
} as never)
assert.equal(status, 'failed')
})
test('绑定失败代码优先于旧待确认状态', () => {
const status = statusForLive({
executionStatus: 'role_ready',
bindingStatus: 'role_ready',
issueCode: 'binding_failed',
bindReadyForConfirm: true,
bindConfirmed: false,
qrUrl: '',
accountReady: true,
} as never)
assert.equal(status, 'failed')
})
test('已分配账号保持 allocated,不折叠成准备账号', () => {
const status = statusForLive({
executionStatus: 'allocated',
bindingStatus: 'not_started',
issueCode: '',
bindReadyForConfirm: false,
bindConfirmed: false,
qrUrl: '',
accountReady: true,
} as never)
assert.equal(status, 'allocated')
})
test('直播账号状态推送忽略空数据和无效任务', async () => {
assert.deepEqual(await applyLiveBindingStateSnapshot({ items: [] }), {
received: 0,
updated: 0,
})
assert.deepEqual(
await applyLiveBindingStateSnapshot({
items: [{ sessionId: 0 }, null, { sessionId: 'bad' }],
}),
{ received: 3, updated: 0 },
)
})
@@ -0,0 +1,51 @@
import { logWarn } from '../../utils/logger.js'
import { reconcileDouyuFulfillmentStates } from './douyu-fulfillment-service.js'
const DEFAULT_RECONCILE_SECONDS = 900
let timer: NodeJS.Timeout | null = null
let stopped = true
function intervalMs() {
const value = Number(process.env.PLATFORM_FULFILLMENT_RECONCILE_SECONDS)
const seconds =
Number.isFinite(value) && value > 0
? Math.max(60, Math.trunc(value))
: DEFAULT_RECONCILE_SECONDS
return seconds * 1000
}
async function run() {
if (stopped) return
try {
await reconcileDouyuFulfillmentStates()
} catch (error) {
logWarn('[douyu-fulfillment]', '低频对账失败', { error })
} finally {
if (!stopped) {
timer = setTimeout(() => {
void run()
}, intervalMs())
}
}
}
export function startDouyuFulfillmentReconciler() {
if (timer || !stopped) return
stopped = false
// 启动后先让 Webhook 工作一分钟,再执行首轮兜底对账。
timer = setTimeout(
() => {
void run()
},
Math.min(60_000, intervalMs()),
)
}
export function stopDouyuFulfillmentReconciler() {
stopped = true
if (timer) {
clearTimeout(timer)
timer = null
}
}
@@ -0,0 +1,15 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
test('Outbox migration keeps header event id and payload eventId identical', () => {
const sql = readFileSync(
new URL('../../db/migrations/171_douyu_fulfillment_integration.sql', import.meta.url),
'utf8',
)
assert.match(sql, /'eventId', event_id::text/)
assert.doesNotMatch(sql, /'eventId', gen_random_uuid\(\)::text/)
assert.match(sql, /CREATE TABLE IF NOT EXISTS integration_outbox/)
assert.match(sql, /CREATE TABLE IF NOT EXISTS integration_inbox/)
})
@@ -0,0 +1,209 @@
import { query, withTransaction } from '../../db/client.js'
import { logError, logInfo, logWarn } from '../../utils/logger.js'
import { buildWebhookSignature } from './webhook-signature.js'
const DEFAULT_INTERVAL_MS = 1000
const DEFAULT_BATCH_SIZE = 20
const DEFAULT_MAX_ATTEMPTS = 12
const REQUEST_TIMEOUT_MS = 5000
const PROCESSING_STALE_SECONDS = 120
type OutboxRow = {
id: string
event_id: string
payload_json: unknown
attempts: number
}
let timer: NodeJS.Timeout | null = null
let running = false
let stopped = true
function envInt(name: string, fallback: number, min: number, max: number) {
const parsed = Number(process.env[name])
if (!Number.isFinite(parsed)) return fallback
return Math.max(min, Math.min(max, Math.trunc(parsed)))
}
export function integrationOutboxConfigured() {
return Boolean(
String(process.env.LIVE_HUB_PLATFORM_FULFILLMENT_URL || '').trim() &&
String(process.env.PLATFORM_FULFILLMENT_INTEGRATION_KEY || '').trim(),
)
}
export function integrationOutboxBackoffSeconds(attempts: number) {
const normalized = Math.max(1, Math.trunc(Number(attempts) || 1))
return Math.min(3600, 5 * 2 ** Math.min(normalized - 1, 10))
}
async function claimDueEvents(limit: number): Promise<OutboxRow[]> {
return withTransaction(async (client) => {
await client.query(
`
UPDATE integration_outbox
SET status = 'pending',
locked_at = NULL,
next_attempt_at = NOW()
WHERE status = 'processing'
AND locked_at < NOW() - ($1 * INTERVAL '1 second')
`,
[PROCESSING_STALE_SECONDS],
)
const claimed = await client.query<OutboxRow>(
`
SELECT id, event_id, payload_json, attempts
FROM integration_outbox
WHERE status = 'pending'
AND next_attempt_at <= NOW()
ORDER BY id ASC
LIMIT $1
FOR UPDATE SKIP LOCKED
`,
[limit],
)
const ids = claimed.rows.map((row) => Number(row.id)).filter((id) => id > 0)
if (ids.length === 0) return []
await client.query(
`
UPDATE integration_outbox
SET status = 'processing',
locked_at = NOW()
WHERE id = ANY($1::bigint[])
`,
[ids],
)
return claimed.rows
})
}
async function deliverEvent(row: OutboxRow) {
const baseUrl = String(process.env.LIVE_HUB_PLATFORM_FULFILLMENT_URL || '')
.trim()
.replace(/\/+$/, '')
const integrationKey = String(process.env.PLATFORM_FULFILLMENT_INTEGRATION_KEY || '').trim()
const endpoint = `${baseUrl}/api/integration/platform-fulfillment/events/order-sync`
const rawBody =
typeof row.payload_json === 'string' ? row.payload_json : JSON.stringify(row.payload_json)
const timestamp = String(Math.floor(Date.now() / 1000))
const signature = buildWebhookSignature(integrationKey, timestamp, rawBody)
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Integration-Key': integrationKey,
'X-Integration-Event-Id': row.event_id,
'X-Integration-Timestamp': timestamp,
'X-Integration-Signature': signature,
},
body: rawBody,
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
})
if (!response.ok) {
throw new Error(`live-hub 返回 HTTP ${response.status}`)
}
}
async function markSent(eventId: string) {
await query(
`
UPDATE integration_outbox
SET status = 'sent',
sent_at = NOW(),
locked_at = NULL,
last_error = ''
WHERE event_id = $1
`,
[eventId],
)
}
async function markFailed(row: OutboxRow, error: unknown) {
const attempts = Number(row.attempts || 0) + 1
const maxAttempts = envInt('INTEGRATION_OUTBOX_MAX_ATTEMPTS', DEFAULT_MAX_ATTEMPTS, 1, 100)
const dead = attempts >= maxAttempts
const message = (error instanceof Error ? error.message : String(error)).slice(0, 2000)
await query(
`
UPDATE integration_outbox
SET status = $2,
attempts = $3,
locked_at = NULL,
next_attempt_at = NOW() + ($4 * INTERVAL '1 second'),
last_error = $5
WHERE event_id = $1
`,
[
row.event_id,
dead ? 'dead' : 'pending',
attempts,
dead ? 0 : integrationOutboxBackoffSeconds(attempts),
message,
],
)
if (dead) {
logError('[integration/outbox]', '事件超过最大重试次数,已进入 dead', {
eventId: row.event_id,
attempts,
error: message,
})
}
}
async function publishDueEvents() {
if (!integrationOutboxConfigured()) return
const batchSize = envInt('INTEGRATION_OUTBOX_BATCH_SIZE', DEFAULT_BATCH_SIZE, 1, 100)
const rows = await claimDueEvents(batchSize)
for (const row of rows) {
try {
await deliverEvent(row)
await markSent(row.event_id)
} catch (error) {
await markFailed(row, error)
}
}
}
async function runLoop() {
if (stopped || running) return
running = true
try {
await publishDueEvents()
} catch (error) {
logWarn('[integration/outbox]', '投递轮次失败', { error })
} finally {
running = false
if (!stopped) {
timer = setTimeout(
() => {
void runLoop()
},
envInt('INTEGRATION_OUTBOX_INTERVAL_MS', DEFAULT_INTERVAL_MS, 250, 60_000),
)
}
}
}
export function startIntegrationOutboxWorker() {
if (timer || !stopped) return
stopped = false
if (!integrationOutboxConfigured()) {
logWarn('[integration/outbox]', '未配置 live-hub 地址或集成密钥,worker 仅保持待命')
} else {
logInfo('[integration/outbox]', '事务 Outbox worker 已启动')
}
timer = setTimeout(() => {
void runLoop()
}, 0)
}
export function stopIntegrationOutboxWorker() {
stopped = true
if (timer) {
clearTimeout(timer)
timer = null
}
}
@@ -0,0 +1,49 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { buildWebhookSignature, verifyWebhookSignature } from './webhook-signature.js'
test('webhook signature binds timestamp and raw body', () => {
const rawBody = '{"eventId":"evt-1","items":[]}'
const timestamp = '1783394219'
const signature = buildWebhookSignature('secret-key', timestamp, rawBody)
assert.equal(
verifyWebhookSignature({
secret: 'secret-key',
timestamp,
rawBody,
signature,
nowSeconds: Number(timestamp),
}),
true,
)
assert.equal(
verifyWebhookSignature({
secret: 'secret-key',
timestamp,
rawBody: `${rawBody} `,
signature,
nowSeconds: Number(timestamp),
}),
false,
)
})
test('webhook signature rejects expired timestamps', () => {
const timestamp = '1783394219'
const rawBody = '{}'
const signature = buildWebhookSignature('secret-key', timestamp, rawBody)
assert.equal(
verifyWebhookSignature({
secret: 'secret-key',
timestamp,
rawBody,
signature,
toleranceSeconds: 300,
nowSeconds: Number(timestamp) + 301,
}),
false,
)
})
@@ -0,0 +1,45 @@
import { createHmac, timingSafeEqual } from 'node:crypto'
const SIGNATURE_PREFIX = 'sha256='
const DEFAULT_TOLERANCE_SECONDS = 300
export function buildWebhookSignature(secret: string, timestamp: string, rawBody: string) {
return (
SIGNATURE_PREFIX + createHmac('sha256', secret).update(`${timestamp}.${rawBody}`).digest('hex')
)
}
export function verifyWebhookSignature(input: {
secret: string
timestamp: string
rawBody: string
signature: string
toleranceSeconds?: number
nowSeconds?: number
}) {
const secret = String(input.secret || '').trim()
const timestamp = String(input.timestamp || '').trim()
const signature = String(input.signature || '').trim()
if (!secret || !timestamp || !signature) return false
const timestampSeconds = Number(timestamp)
if (!Number.isInteger(timestampSeconds) || timestampSeconds <= 0) return false
const tolerance = Math.max(
1,
Math.trunc(Number(input.toleranceSeconds) || DEFAULT_TOLERANCE_SECONDS),
)
const nowSeconds = Math.trunc(Number(input.nowSeconds) || Date.now() / 1000)
if (Math.abs(nowSeconds - timestampSeconds) > tolerance) return false
const expected = buildWebhookSignature(secret, timestamp, String(input.rawBody || ''))
const expectedBuffer = Buffer.from(expected)
const providedBuffer = Buffer.from(signature)
if (expectedBuffer.length !== providedBuffer.length) return false
return timingSafeEqual(expectedBuffer, providedBuffer)
}
export function webhookToleranceSeconds() {
const value = Number(process.env.PLATFORM_FULFILLMENT_WEBHOOK_TOLERANCE_SECONDS || 300)
return Number.isFinite(value) && value > 0 ? Math.trunc(value) : DEFAULT_TOLERANCE_SECONDS
}
@@ -902,3 +902,93 @@ test(
}
},
)
test(
'斗鱼直播账号履约 Mock 只生成正式人工履约,不生成半自动任务',
{ skip: !TEST_DATABASE_URL ? '未设置 SEMI_AUTO_TASK_TEST_DATABASE_URL' : false },
async () => {
process.env.DATABASE_URL = TEST_DATABASE_URL
process.env.ENABLE_DEV_MOCK = '1'
const { closeDb, query, withTransaction } = await import('../../db/client.js')
const { createDouyuFulfillmentMock } = await import('../dev-mock/dev-mock-service.js')
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
const orderNo = `IT-DOUYU-FULFILLMENT-${suffix}`
const skuKey = `斗鱼精英宝典联调-${suffix}`
let orderId = 0
let configId = 0
let mappingId = 0
try {
const result = await createDouyuFulfillmentMock({
orderNo,
skuName: skuKey,
})
orderId = result.orderId
configId = result.configId
mappingId = result.mappingId
assert.equal(result.platform, 'douyu')
assert.equal(result.pipeline, 'order_service')
assert.equal(result.orderNo, orderNo)
assert.equal(result.skuKey, skuKey)
assert.ok(result.orderItemId > 0)
assert.ok(result.fulfillmentId > 0)
const stored = await query<{
channel: string
fulfillment_status: string
fulfillment_config_id: number
semi_auto_enabled: boolean
semi_auto_task_count: number
internal_sku: string
}>(
`
SELECT
f.channel,
f.status AS fulfillment_status,
f.fulfillment_config_id,
cfg.semi_auto_enabled,
(
SELECT COUNT(*)::int
FROM semi_auto_tasks task
WHERE task.order_item_id = f.order_item_id
) AS semi_auto_task_count,
resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code) AS internal_sku
FROM fulfillments f
JOIN order_items oi ON oi.id = f.order_item_id
JOIN manual_fulfillment_configs cfg ON cfg.id = f.fulfillment_config_id
WHERE f.id = $1
`,
[result.fulfillmentId],
)
assert.equal(stored.rows[0]?.channel, 'manual')
assert.equal(stored.rows[0]?.fulfillment_status, 'assigned')
assert.equal(Number(stored.rows[0]?.fulfillment_config_id), result.configId)
assert.equal(stored.rows[0]?.semi_auto_enabled, false)
assert.equal(Number(stored.rows[0]?.semi_auto_task_count), 0)
assert.equal(stored.rows[0]?.internal_sku, skuKey)
const mapping = await query<{ internal_sku: string }>(
'SELECT internal_sku FROM internal_sku_mappings WHERE id = $1',
[result.mappingId],
)
assert.equal(mapping.rows[0]?.internal_sku, skuKey)
} finally {
await withTransaction(async (client) => {
await client.query("SET LOCAL session_replication_role = 'replica'")
if (configId > 0) {
await client.query('DELETE FROM manual_fulfillment_configs WHERE id = $1', [configId])
}
if (orderId > 0) {
await client.query('DELETE FROM order_source_snapshots WHERE order_id = $1', [orderId])
await client.query('DELETE FROM orders WHERE id = $1', [orderId])
}
if (mappingId > 0) {
await client.query('DELETE FROM internal_sku_mappings WHERE id = $1', [mappingId])
}
})
delete process.env.ENABLE_DEV_MOCK
await closeDb()
}
},
)
+4
View File
@@ -1,8 +1,10 @@
import { runDatabaseMigrations } from '../db/migrate.js'
import { startIntegrationOutboxWorker } from '../services/integration/outbox-worker.js'
import { ensureAdminUsersBootstrapped } from '../services/admin/admin-auth-service.js'
import { ensureFulfillmentCatalogBootstrapped } from '../services/bootstrap/fulfillment-bootstrap-service.js'
import { migrateJsonConfigFilesToDatabase } from '../services/config/json-config-migration-service.js'
import { startKuaishouIndustrySendCallbackRetryWorker } from '../services/platforms/kuaishou-industry/send-code-service.js'
import { startDouyuFulfillmentReconciler } from '../services/douyu-fulfillment/fulfillment-reconciler.js'
import { startScheduledJobs } from '../services/scheduler/scheduler-service.js'
import { logError, logInfo } from '../utils/logger.js'
import { startMemoryReporter } from './memory-reporter.js'
@@ -46,6 +48,8 @@ export async function bootstrapCoreServices(
startScheduledJobs()
startKuaishouIndustrySendCallbackRetryWorker()
startIntegrationOutboxWorker()
startDouyuFulfillmentReconciler()
startMemoryReporter()
break
} catch (error) {
+4
View File
@@ -1,6 +1,8 @@
import type { Server } from 'node:http'
import { stopKuaishouIndustrySendCallbackRetryWorker } from '../services/platforms/kuaishou-industry/send-code-service.js'
import { stopIntegrationOutboxWorker } from '../services/integration/outbox-worker.js'
import { stopDouyuFulfillmentReconciler } from '../services/douyu-fulfillment/fulfillment-reconciler.js'
import { stopScheduledJobs } from '../services/scheduler/scheduler-service.js'
import { closeDb } from '../db/client.js'
import { logError, logInfo } from '../utils/logger.js'
@@ -28,6 +30,8 @@ export function createShutdownController(
stopScheduledJobs()
stopKuaishouIndustrySendCallbackRetryWorker()
stopIntegrationOutboxWorker()
stopDouyuFulfillmentReconciler()
if (server.listening) {
await new Promise<void>((resolve) => {