713 lines
22 KiB
TypeScript
713 lines
22 KiB
TypeScript
import type { PoolClient } from 'pg'
|
|
|
|
import { query, withTransaction } from '../../db/client.js'
|
|
import { nowIso } from '../../utils/time.js'
|
|
import { createHttpError } from '../../utils/http.js'
|
|
import { logWarn } from '../../utils/logger.js'
|
|
import { notifyLiveHubOrderSyncAsync } from './live-hub-notifier.js'
|
|
|
|
type DouyuTaskRow = {
|
|
id: number
|
|
order_id: number
|
|
order_item_id: number
|
|
fulfillment_id: number | null
|
|
manual_fulfillment_config_id: number | null
|
|
live_session_id: number | null
|
|
status: string
|
|
customer_role_name: string
|
|
customer_platform: string
|
|
customer_system: string
|
|
binding_phase: string
|
|
live_execution_status: string
|
|
live_binding_status: string
|
|
issue_code: string
|
|
last_error: string
|
|
bound_role_name: string
|
|
bound_area_name: string
|
|
bound_plat_name: string
|
|
customer_link_opened_at: string | null
|
|
binding_started_at: string | null
|
|
bound_at: string | null
|
|
completed_at: string | null
|
|
last_synced_at: string | null
|
|
created_at: string
|
|
updated_at: string
|
|
platform_order_id: string
|
|
sku_code: string
|
|
sku_name: string
|
|
quantity: number
|
|
product_name: string
|
|
fulfillment_status: string
|
|
}
|
|
|
|
type LiveBindingState = {
|
|
sessionId: number
|
|
platformOrderId: string
|
|
sourceOrderItemId: string
|
|
productName: string
|
|
quantity: number
|
|
executionStatus: string
|
|
bindingStatus: string
|
|
exchangeStatus: string
|
|
issueCode: string
|
|
message: string
|
|
accountReady: boolean
|
|
bindTaskId: number | null
|
|
bindTaskStatus: string
|
|
bindPhase: string
|
|
qrUrl: string
|
|
qrGeneratedAt: string
|
|
qrExpiresAt: string
|
|
roleName: string
|
|
areaName: string
|
|
platName: string
|
|
bindReadyForConfirm: boolean
|
|
bindConfirmed: boolean
|
|
completedAt: string | null
|
|
updatedAt: string
|
|
}
|
|
|
|
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,
|
|
})
|
|
}
|
|
}
|
|
})
|
|
if (created > 0) {
|
|
notifyLiveHubOrderSyncAsync({ created, updated: candidates.rows.length - created })
|
|
}
|
|
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
|
|
? '客户资料与平台识别角色一致'
|
|
: '客户资料与平台识别角色不一致,请修改资料或联系客服',
|
|
}
|
|
}
|
|
|
|
function statusForLive(live: LiveBindingState): string {
|
|
if (live.executionStatus === 'completed') return 'completed'
|
|
if (live.executionStatus === 'cancelled') return 'cancelled'
|
|
if (live.bindConfirmed) return 'waiting_operator'
|
|
if (live.bindReadyForConfirm) return 'role_ready'
|
|
if (live.qrUrl) return 'qr_pending'
|
|
if (live.executionStatus === 'manual_required') return 'manual_required'
|
|
if (live.issueCode === 'binding_failed') return 'failed'
|
|
if (
|
|
live.issueCode === 'mapping_missing' ||
|
|
live.issueCode === 'no_eligible_account' ||
|
|
live.issueCode === 'elite_not_opened' ||
|
|
live.issueCode === 'points_short' ||
|
|
!live.accountReady
|
|
) {
|
|
return 'preparing'
|
|
}
|
|
if (live.issueCode) return 'failed'
|
|
return 'preparing'
|
|
}
|
|
|
|
async function updateTaskFromLiveState(
|
|
client: Pick<PoolClient, 'query'>,
|
|
task: DouyuTaskRow,
|
|
live: LiveBindingState,
|
|
now: string,
|
|
) {
|
|
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 $12 <> '' THEN COALESCE(binding_started_at, NOW())
|
|
ELSE binding_started_at
|
|
END,
|
|
bound_at = CASE
|
|
WHEN $13 THEN COALESCE(bound_at, NOW())
|
|
ELSE bound_at
|
|
END,
|
|
completed_at = CASE
|
|
WHEN $14 THEN COALESCE(completed_at, NOW())
|
|
ELSE completed_at
|
|
END,
|
|
last_synced_at = NOW(),
|
|
updated_at = $15
|
|
WHERE id = $1
|
|
`,
|
|
[
|
|
task.id,
|
|
live.sessionId,
|
|
nextStatus,
|
|
live.bindPhase,
|
|
live.executionStatus,
|
|
live.bindingStatus,
|
|
live.issueCode,
|
|
live.message,
|
|
live.roleName,
|
|
live.areaName,
|
|
live.platName,
|
|
live.qrUrl,
|
|
live.bindConfirmed,
|
|
live.executionStatus === 'completed',
|
|
now,
|
|
],
|
|
)
|
|
if (nextStatus !== task.status) {
|
|
await appendEvent(client, task.id, 'status_changed', 'integration', {
|
|
fromStatus: task.status,
|
|
toStatus: nextStatus,
|
|
bindPhase: live.bindPhase,
|
|
})
|
|
}
|
|
}
|
|
|
|
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'
|
|
)
|
|
}
|
|
|
|
export async function applyLiveBindingStateSnapshot(input: unknown) {
|
|
const rawItems =
|
|
input && typeof input === 'object' && Array.isArray((input as { items?: unknown }).items)
|
|
? (input as { items: unknown[] }).items
|
|
: []
|
|
const items = rawItems.filter(isLiveBindingState)
|
|
const sessionIds = Array.from(
|
|
new Set(items.map((item) => Number(item.sessionId)).filter((id) => id > 0)),
|
|
)
|
|
if (sessionIds.length === 0) return { received: rawItems.length, updated: 0 }
|
|
|
|
const tasks = await query<DouyuTaskRow>(
|
|
`${TASK_SELECT}
|
|
WHERE task.live_session_id = ANY($1::bigint[])`,
|
|
[sessionIds],
|
|
)
|
|
const taskBySessionId = new Map(tasks.rows.map((task) => [Number(task.live_session_id), task]))
|
|
const entries = items.flatMap((live) => {
|
|
const task = taskBySessionId.get(Number(live.sessionId))
|
|
return task ? [{ task, live }] : []
|
|
})
|
|
await applyLiveStates(entries)
|
|
return { received: rawItems.length, updated: entries.length }
|
|
}
|
|
|
|
async function ensureLiveSession(task: DouyuTaskRow) {
|
|
const live = await liveHubRequest<LiveBindingState>(
|
|
'/api/integration/platform-fulfillment/customer-sessions/ensure',
|
|
{
|
|
method: 'POST',
|
|
body: {
|
|
source_order_item_id: String(task.order_item_id),
|
|
platform_order_id: task.platform_order_id,
|
|
},
|
|
},
|
|
)
|
|
return applyLiveState(task, live)
|
|
}
|
|
|
|
export async function getCustomerDouyuFulfillment(orderNo: string) {
|
|
const task = await loadTaskByOrderNo(orderNo)
|
|
if (!task.customer_link_opened_at) {
|
|
await withTransaction(async (client) => {
|
|
await client.query(
|
|
`UPDATE douyu_fulfillment_tasks
|
|
SET customer_link_opened_at = COALESCE(customer_link_opened_at, NOW())
|
|
WHERE id = $1`,
|
|
[task.id],
|
|
)
|
|
await appendEvent(client, task.id, 'customer_link_opened', 'customer')
|
|
})
|
|
}
|
|
const session = await ensureLiveSession(task)
|
|
return {
|
|
task: session.task,
|
|
live: session.live,
|
|
comparison: session.comparison,
|
|
linkPath: `/coll/d/${encodeURIComponent(task.platform_order_id)}`,
|
|
}
|
|
}
|
|
|
|
export async function saveDouyuCustomerProfile(
|
|
orderNo: string,
|
|
input: { roleName?: unknown; platform?: unknown; system?: unknown },
|
|
) {
|
|
const task = await loadTaskByOrderNo(orderNo)
|
|
if (task.status === 'completed' || task.status === 'cancelled') {
|
|
throw createHttpError('当前订单已结束,不能修改资料', {
|
|
statusCode: 409,
|
|
errorCode: 'douyu_fulfillment_closed',
|
|
})
|
|
}
|
|
const roleName = String(input.roleName ?? '')
|
|
.trim()
|
|
.slice(0, 100)
|
|
const platform = String(input.platform ?? '')
|
|
.trim()
|
|
.toLowerCase()
|
|
const system = String(input.system ?? '')
|
|
.trim()
|
|
.toLowerCase()
|
|
if (!roleName || !['wechat', 'qq'].includes(platform) || !['ios', 'android'].includes(system)) {
|
|
throw createHttpError('请完整填写角色名、微信/QQ 和苹果/安卓', {
|
|
statusCode: 400,
|
|
errorCode: 'douyu_customer_profile_invalid',
|
|
})
|
|
}
|
|
await withTransaction(async (client) => {
|
|
await client.query(
|
|
`
|
|
UPDATE douyu_fulfillment_tasks
|
|
SET customer_role_name = $2,
|
|
customer_platform = $3,
|
|
customer_system = $4,
|
|
status = CASE WHEN status = 'waiting_profile' THEN 'preparing' ELSE status END,
|
|
updated_at = NOW()
|
|
WHERE id = $1
|
|
`,
|
|
[task.id, roleName, platform, system],
|
|
)
|
|
await appendEvent(client, task.id, 'customer_profile_saved', 'customer', {
|
|
roleName,
|
|
platform,
|
|
system,
|
|
})
|
|
})
|
|
return getCustomerDouyuFulfillment(orderNo)
|
|
}
|
|
|
|
export async function startDouyuCustomerBinding(orderNo: string, forceRefresh = false) {
|
|
let task = await loadTaskByOrderNo(orderNo)
|
|
const session = await ensureLiveSession(task)
|
|
task = session.task
|
|
if (!task.live_session_id) {
|
|
throw createHttpError('直播账号履约会话尚未准备完成', {
|
|
statusCode: 409,
|
|
errorCode: 'douyu_live_session_not_ready',
|
|
})
|
|
}
|
|
const live = await liveHubRequest<LiveBindingState>(
|
|
`/api/integration/platform-fulfillment/customer-sessions/${task.live_session_id}/binding/start`,
|
|
{ method: 'POST', body: { force_refresh: forceRefresh } },
|
|
)
|
|
return applyLiveState(task, live)
|
|
}
|
|
|
|
export async function refreshDouyuCustomerBinding(orderNo: string) {
|
|
const task = await loadTaskByOrderNo(orderNo)
|
|
if (!task.live_session_id) return ensureLiveSession(task)
|
|
const live = await liveHubRequest<LiveBindingState>(
|
|
`/api/integration/platform-fulfillment/customer-sessions/${task.live_session_id}/status`,
|
|
)
|
|
return applyLiveState(task, live)
|
|
}
|
|
|
|
export async function confirmDouyuCustomerBinding(orderNo: string) {
|
|
const refreshed = await refreshDouyuCustomerBinding(orderNo)
|
|
if (!refreshed.comparison.matched) {
|
|
throw createHttpError(refreshed.comparison.message, {
|
|
statusCode: 409,
|
|
errorCode: 'douyu_customer_role_mismatch',
|
|
})
|
|
}
|
|
const task = refreshed.task
|
|
if (!task.live_session_id) {
|
|
throw createHttpError('直播账号履约会话尚未准备完成', {
|
|
statusCode: 409,
|
|
errorCode: 'douyu_live_session_not_ready',
|
|
})
|
|
}
|
|
const live = await liveHubRequest<LiveBindingState>(
|
|
`/api/integration/platform-fulfillment/customer-sessions/${task.live_session_id}/binding/confirm`,
|
|
{ method: 'POST' },
|
|
)
|
|
return applyLiveState(task, live)
|
|
}
|
|
|
|
async function syncLiveStatesForTasks(tasks: DouyuTaskRow[]) {
|
|
const now = Date.now()
|
|
const candidates = tasks.filter((task) => {
|
|
if (!task.live_session_id || TERMINAL_TASK_STATUSES.has(task.status)) return false
|
|
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)
|
|
} catch (error) {
|
|
logWarn('[douyu-fulfillment]', '自动同步直播账号履约状态失败', { error })
|
|
}
|
|
}
|
|
|
|
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)
|
|
let rows = await query<DouyuTaskRow>(
|
|
`${TASK_SELECT}
|
|
${where}
|
|
ORDER BY task.updated_at DESC, task.id DESC
|
|
LIMIT $${params.length - 1} OFFSET $${params.length}`,
|
|
params,
|
|
)
|
|
await syncLiveStatesForTasks(rows.rows)
|
|
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,
|
|
}
|
|
}
|