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
+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';