重构(半自动履约): 收敛状态同步并拆分任务服务
This commit is contained in:
@@ -66,6 +66,7 @@ export function createDefaultRuntimeConfig(projectRoot: string): RuntimeConfig {
|
||||
connectorBaseUrl: '',
|
||||
connectorApiKey: '',
|
||||
connectorTimeoutMs: 15_000,
|
||||
reconcileSeconds: 900,
|
||||
huya: {
|
||||
bindActId: 9271,
|
||||
outerActId: '17096',
|
||||
|
||||
@@ -54,6 +54,7 @@ export const ENV_OVERRIDES: readonly EnvOverride[] = [
|
||||
stringEnv('SEMI_AUTO_CONNECTOR_BASE_URL', ['semiAuto', 'connectorBaseUrl']),
|
||||
stringEnv('SEMI_AUTO_CONNECTOR_API_KEY', ['semiAuto', 'connectorApiKey']),
|
||||
integerEnv('SEMI_AUTO_CONNECTOR_TIMEOUT_MS', ['semiAuto', 'connectorTimeoutMs']),
|
||||
integerEnv('SEMI_AUTO_RECONCILE_SECONDS', ['semiAuto', 'reconcileSeconds']),
|
||||
stringEnv('SEMI_AUTO_DEFAULT_CONNECTOR_MODE', ['semiAuto', 'defaultConnectorMode']),
|
||||
integerEnv('HUYA_BIND_ACT_ID', ['semiAuto', 'huya', 'bindActId']),
|
||||
stringEnv('HUYA_OUTER_ACT_ID', ['semiAuto', 'huya', 'outerActId']),
|
||||
|
||||
@@ -91,6 +91,9 @@ export function validateRuntimeConfig(
|
||||
config.semiAuto?.connectorTimeoutMs,
|
||||
{ min: 1 },
|
||||
)
|
||||
requireOptionalInteger(issues, 'semiAuto.reconcileSeconds', config.semiAuto?.reconcileSeconds, {
|
||||
min: 60,
|
||||
})
|
||||
requireInteger(issues, 'storage.maxUploadSizeMb', config.storage?.maxUploadSizeMb, {
|
||||
min: 1,
|
||||
max: 100,
|
||||
|
||||
@@ -3,6 +3,7 @@ import { timingSafeEqual } from 'node:crypto'
|
||||
import { Router } from 'express'
|
||||
|
||||
import { applyLiveBindingStateSnapshot } from '../services/douyu-fulfillment/douyu-fulfillment-service.js'
|
||||
import { applySemiAutoTaskStateSnapshot } from '../services/semi-auto/semi-auto-task-service.js'
|
||||
import {
|
||||
verifyWebhookSignature,
|
||||
webhookToleranceSeconds,
|
||||
@@ -85,4 +86,46 @@ router.post(
|
||||
),
|
||||
)
|
||||
|
||||
router.post(
|
||||
'/platform-fulfillment/semi-auto/task-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 applySemiAutoTaskStateSnapshot(body, {
|
||||
eventId,
|
||||
eventType: String(body.eventType || ''),
|
||||
})
|
||||
},
|
||||
{
|
||||
successMessage: '半自动履约状态已同步',
|
||||
errorMessage: '同步半自动履约状态失败',
|
||||
scope: '[integration/platform-fulfillment/semi-auto/task-state]',
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
export default router
|
||||
|
||||
@@ -239,6 +239,7 @@ async function callConnector<T>(
|
||||
durationMs: Date.now() - startedAt,
|
||||
requestSummary: { baseUrl: endpoint.baseUrl },
|
||||
requestBody: options.body,
|
||||
maskRequestCode: true,
|
||||
responseSummary: { bodyBytes: text.length },
|
||||
responseBody: payload ?? text,
|
||||
always: method !== 'GET',
|
||||
@@ -265,6 +266,7 @@ async function callConnector<T>(
|
||||
durationMs: Date.now() - startedAt,
|
||||
requestSummary: { baseUrl: endpoint.baseUrl },
|
||||
requestBody: options.body,
|
||||
maskRequestCode: true,
|
||||
always: true,
|
||||
errorMessage: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
|
||||
@@ -0,0 +1,898 @@
|
||||
import { query, withTransaction } from '../../db/client.js'
|
||||
import { getFileAssetByObjectKey } from '../../repositories/file-asset-repo.js'
|
||||
import { createHttpError } from '../../utils/http.js'
|
||||
import type { AdminSession } from '../admin/admin-auth-service.js'
|
||||
import { safeParseJson } from '../admin/admin-query-utils.js'
|
||||
import {
|
||||
confirmManualFulfillment,
|
||||
runManualFulfillmentPostCommit,
|
||||
} from '../finance/manual-fulfillment-service.js'
|
||||
import {
|
||||
buildFileUrl,
|
||||
ORDER_SERVICE_SCREENSHOT_CONTENT_TYPES,
|
||||
type UploadedFileDto,
|
||||
} from '../file-storage/file-storage-service.js'
|
||||
import { publishAdminOrderRealtimeChange } from '../realtime/realtime-event-service.js'
|
||||
import {
|
||||
consumeHuyaBrowserTicket,
|
||||
createHuyaBrowserTicket,
|
||||
revokeHuyaSession,
|
||||
type ConnectorInjectionPayload,
|
||||
type SemiAutoConnectorMode,
|
||||
} from './huya-connector-client.js'
|
||||
import {
|
||||
buildSemiAutoCredentialCookieHeader,
|
||||
loadSemiAutoCredential,
|
||||
} from './semi-auto-credential-service.js'
|
||||
import {
|
||||
consumeWeiboBrowserTicket,
|
||||
createWeiboBrowserTicket,
|
||||
revokeWeiboSession,
|
||||
} from './weibo-connector-client.js'
|
||||
import { WEIBO_TICKET_PREFIX } from './weibo-native/weibo-native-connector.js'
|
||||
import { querySemiAutoTraces } from './semi-auto-trace.js'
|
||||
import {
|
||||
appendTaskEvent,
|
||||
compareBindingRole,
|
||||
ensureConnectorSessionForTask,
|
||||
ensureSemiAutoTasksForAdminList,
|
||||
getBindingForTask,
|
||||
getLoginSessionForTask,
|
||||
loadTask,
|
||||
loadTaskForUpdateWithClient,
|
||||
mapTask,
|
||||
normalizeId,
|
||||
normalizeOrderNo,
|
||||
publishSemiAutoTaskRealtimeChange,
|
||||
resetTaskForCustomerLogin,
|
||||
revokeSessionForTask,
|
||||
TASK_SELECT,
|
||||
updateBindingTask,
|
||||
type BindingStatus,
|
||||
type ExecutionStatus,
|
||||
type LoginStatus,
|
||||
type SemiAutoPlatform,
|
||||
type TaskRow,
|
||||
} from './semi-auto-task-core.js'
|
||||
import { updateLoginTask } from './semi-auto-customer-service.js'
|
||||
|
||||
export async function listAdminSemiAutoTasks(input: Record<string, unknown> = {}) {
|
||||
await ensureSemiAutoTasksForAdminList()
|
||||
const page = Math.max(1, Math.trunc(Number(input.page) || 1))
|
||||
const pageSize = Math.min(100, Math.max(1, Math.trunc(Number(input.pageSize) || 20)))
|
||||
const platform = String(input.platform || '').trim()
|
||||
const status = String(input.status || '').trim()
|
||||
const keyword = String(input.keyword || '').trim()
|
||||
const conditions = ['1 = 1']
|
||||
const params: unknown[] = []
|
||||
if (platform === 'huya' || platform === 'weibo') {
|
||||
params.push(platform)
|
||||
conditions.push(`task.platform = $${params.length}`)
|
||||
}
|
||||
if (
|
||||
[
|
||||
'waiting_customer',
|
||||
'waiting_operator',
|
||||
'processing',
|
||||
'completed',
|
||||
'failed',
|
||||
'cancelled',
|
||||
].includes(status)
|
||||
) {
|
||||
params.push(status)
|
||||
conditions.push(`task.execution_status = $${params.length}`)
|
||||
}
|
||||
if (keyword) {
|
||||
params.push(`%${keyword.replace(/[\\%_]/g, '\\$&')}%`)
|
||||
const p = `$${params.length}`
|
||||
conditions.push(
|
||||
`(o.platform_order_id ILIKE ${p} OR oi.sku_name ILIKE ${p} OR oi.sku_code ILIKE ${p} OR task.huya_uid ILIKE ${p} OR task.bind_game_role ILIKE ${p})`,
|
||||
)
|
||||
}
|
||||
const where = conditions.join(' AND ')
|
||||
const count = await query<{ total: number }>(
|
||||
`SELECT COUNT(*)::int AS total
|
||||
FROM semi_auto_tasks task
|
||||
JOIN orders o ON o.id = task.order_id
|
||||
JOIN order_items oi ON oi.id = task.order_item_id
|
||||
WHERE ${where}`,
|
||||
params,
|
||||
)
|
||||
const listParams = [...params, pageSize, (page - 1) * pageSize]
|
||||
const result = await query<TaskRow>(
|
||||
`${TASK_SELECT}
|
||||
WHERE ${where}
|
||||
ORDER BY
|
||||
CASE task.execution_status
|
||||
WHEN 'waiting_operator' THEN 0
|
||||
WHEN 'waiting_customer' THEN 1
|
||||
WHEN 'processing' THEN 2
|
||||
WHEN 'failed' THEN 3
|
||||
ELSE 4
|
||||
END,
|
||||
task.updated_at DESC,
|
||||
task.id DESC
|
||||
LIMIT $${listParams.length - 1} OFFSET $${listParams.length}`,
|
||||
listParams,
|
||||
)
|
||||
return {
|
||||
items: result.rows.map(mapTask),
|
||||
pagination: { page, pageSize, total: Number(count.rows[0]?.total || 0) },
|
||||
}
|
||||
}
|
||||
|
||||
export async function getAdminSemiAutoTask(taskIdInput: unknown) {
|
||||
const task = await loadTask(normalizeId(taskIdInput))
|
||||
const events = await query<{
|
||||
id: number
|
||||
event_type: string
|
||||
actor_type: string
|
||||
actor_id: string
|
||||
detail_json: Record<string, unknown>
|
||||
created_at: string
|
||||
}>(
|
||||
`SELECT id, event_type, actor_type, actor_id, detail_json, created_at
|
||||
FROM semi_auto_task_events
|
||||
WHERE task_id = $1
|
||||
ORDER BY id DESC
|
||||
LIMIT 200`,
|
||||
[task.id],
|
||||
)
|
||||
return {
|
||||
task: mapTask(task),
|
||||
// 管理端详情直接复用与客户页相同的三项比对口径,避免出现第二套判定。
|
||||
comparison: compareBindingRole(task, {
|
||||
bindGameRole: task.bind_game_role,
|
||||
bindGameRoleId: task.bind_game_role_id,
|
||||
bindGameChannel: task.bind_game_channel,
|
||||
}),
|
||||
events: events.rows.map((event) => ({
|
||||
id: Number(event.id),
|
||||
eventType: event.event_type,
|
||||
actorType: event.actor_type,
|
||||
actorId: event.actor_id,
|
||||
detail: event.detail_json || {},
|
||||
createdAt: event.created_at,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
type SemiAutoTaskEventRow = {
|
||||
id: number
|
||||
event_type: string
|
||||
actor_type: string
|
||||
actor_id: string
|
||||
from_login_status: string | null
|
||||
to_login_status: string | null
|
||||
from_binding_status: string | null
|
||||
to_binding_status: string | null
|
||||
from_execution_status: string | null
|
||||
to_execution_status: string | null
|
||||
detail_json: Record<string, unknown>
|
||||
created_at: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 运营端「历史」:任务状态流转事件 + 全链路报文(本系统入站 + 外部平台出站)。
|
||||
* 报文只读,不做任何写操作;Cookie / Token 已在落库前脱敏。
|
||||
*/
|
||||
export async function getAdminSemiAutoTaskHistory(
|
||||
taskIdInput: unknown,
|
||||
input: Record<string, unknown> = {},
|
||||
) {
|
||||
const task = await loadTask(normalizeId(taskIdInput))
|
||||
const eventCount = await query<{ total: number }>(
|
||||
`SELECT COUNT(*)::int AS total FROM semi_auto_task_events WHERE task_id = $1`,
|
||||
[task.id],
|
||||
)
|
||||
const events = await query<SemiAutoTaskEventRow>(
|
||||
`SELECT * FROM (
|
||||
SELECT id, event_type, actor_type, actor_id,
|
||||
from_login_status, to_login_status,
|
||||
from_binding_status, to_binding_status,
|
||||
from_execution_status, to_execution_status,
|
||||
detail_json, created_at
|
||||
FROM semi_auto_task_events
|
||||
WHERE task_id = $1
|
||||
ORDER BY id DESC
|
||||
LIMIT 500
|
||||
) recent
|
||||
ORDER BY id ASC`,
|
||||
[task.id],
|
||||
)
|
||||
const traces = await querySemiAutoTraces(task.id, {
|
||||
page: Number(input.page) || 1,
|
||||
pageSize: Number(input.pageSize) || 50,
|
||||
channel: String(input.channel || '').trim(),
|
||||
status: String(input.status || '').trim(),
|
||||
requestId: String(input.requestId || '').trim(),
|
||||
keyword: String(input.keyword || '').trim(),
|
||||
})
|
||||
return {
|
||||
task: mapTask(task),
|
||||
events: events.rows.map((event) => ({
|
||||
id: Number(event.id),
|
||||
eventType: event.event_type,
|
||||
actorType: event.actor_type,
|
||||
actorId: event.actor_id,
|
||||
fromLoginStatus: event.from_login_status,
|
||||
toLoginStatus: event.to_login_status,
|
||||
fromBindingStatus: event.from_binding_status,
|
||||
toBindingStatus: event.to_binding_status,
|
||||
fromExecutionStatus: event.from_execution_status,
|
||||
toExecutionStatus: event.to_execution_status,
|
||||
detail: event.detail_json || {},
|
||||
createdAt: event.created_at,
|
||||
})),
|
||||
eventTotal: Number(eventCount.rows[0]?.total || 0),
|
||||
traces,
|
||||
}
|
||||
}
|
||||
|
||||
export async function exportAdminSemiAutoCredential(taskIdInput: unknown) {
|
||||
const task = await loadTask(normalizeId(taskIdInput))
|
||||
if (!task.credential_id) {
|
||||
throw createHttpError('当前任务尚未保存账号 CK', {
|
||||
statusCode: 404,
|
||||
errorCode: 'semi_auto_credential_not_found',
|
||||
})
|
||||
}
|
||||
const credential = await loadSemiAutoCredential(task.credential_id)
|
||||
if (!credential || credential.platform !== task.platform) {
|
||||
throw createHttpError('账号 CK 不存在或与任务平台不一致', {
|
||||
statusCode: 404,
|
||||
errorCode: 'semi_auto_credential_not_found',
|
||||
})
|
||||
}
|
||||
const config = safeParseJson(task.semi_auto_config_json)
|
||||
const targets = Array.isArray(config.browserTargets) ? config.browserTargets : []
|
||||
const configuredTarget = String(
|
||||
targets.find((item): item is { url?: string } => Boolean(item && typeof item === 'object'))
|
||||
?.url || '',
|
||||
).trim()
|
||||
const targetUrl = /^https:\/\//i.test(configuredTarget)
|
||||
? configuredTarget
|
||||
: credential.platform === 'weibo'
|
||||
? 'https://weibo.com/'
|
||||
: 'https://www.huya.com/'
|
||||
const cookieHeader = targetUrl
|
||||
? buildSemiAutoCredentialCookieHeader(credential.cookies, targetUrl)
|
||||
: ''
|
||||
return {
|
||||
credentialId: credential.id,
|
||||
platform: credential.platform,
|
||||
platformUid: credential.platformUid,
|
||||
nickname: credential.nickname,
|
||||
source: credential.source,
|
||||
status: credential.status,
|
||||
updatedAt: credential.updatedAt,
|
||||
targetUrl,
|
||||
cookieHeader,
|
||||
cookies: credential.cookies,
|
||||
}
|
||||
}
|
||||
|
||||
export async function claimAdminSemiAutoTask(taskIdInput: unknown, session: AdminSession) {
|
||||
const taskId = normalizeId(taskIdInput)
|
||||
const adminUserId = Number(session.userId || 0)
|
||||
let orderId = 0
|
||||
await withTransaction(async (client) => {
|
||||
const task = await loadTaskForUpdateWithClient(client, taskId)
|
||||
if (task.execution_status === 'completed' || task.execution_status === 'cancelled') {
|
||||
throw createHttpError('当前任务已结束,不能领取', {
|
||||
statusCode: 409,
|
||||
errorCode:
|
||||
task.execution_status === 'completed'
|
||||
? 'semi_auto_task_completed'
|
||||
: 'semi_auto_task_cancelled',
|
||||
})
|
||||
}
|
||||
if (task.assigned_admin_user_id && Number(task.assigned_admin_user_id) !== adminUserId) {
|
||||
throw createHttpError('该任务已被其他客服领取', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_task_claimed',
|
||||
})
|
||||
}
|
||||
orderId = Number(task.order_id)
|
||||
await client.query(
|
||||
`UPDATE semi_auto_tasks
|
||||
SET assigned_admin_user_id = $2, updated_at = NOW()
|
||||
WHERE id = $1`,
|
||||
[taskId, adminUserId],
|
||||
)
|
||||
await appendTaskEvent(client, taskId, {
|
||||
eventType: 'task_claimed',
|
||||
actorType: 'admin',
|
||||
actorId: String(adminUserId),
|
||||
})
|
||||
})
|
||||
publishSemiAutoTaskRealtimeChange(taskId, orderId)
|
||||
return getAdminSemiAutoTask(taskId)
|
||||
}
|
||||
|
||||
export async function syncAdminSemiAutoTask(taskIdInput: unknown) {
|
||||
const taskId = normalizeId(taskIdInput)
|
||||
let task = await ensureConnectorSessionForTask(await loadTask(taskId))
|
||||
if (!task.connector_session_id) return getAdminSemiAutoTask(taskId)
|
||||
if (
|
||||
task.login_status !== 'authenticated' &&
|
||||
task.login_status !== 'failed' &&
|
||||
task.login_status !== 'expired'
|
||||
) {
|
||||
const login = await getLoginSessionForTask(task, task.connector_session_id)
|
||||
await updateLoginTask(task, login, 'connector')
|
||||
task = await loadTask(taskId)
|
||||
}
|
||||
return getAdminSemiAutoTask(taskId)
|
||||
}
|
||||
|
||||
/**
|
||||
* 低频兜底对账:只处理活跃且有 Connector 会话的任务,并且每次限量。
|
||||
* 正常状态变化由客户操作、Connector 回调和后台操作即时推进,这里只补漏。
|
||||
*/
|
||||
export async function reconcileSemiAutoTaskStates(limitInput = 100) {
|
||||
const limit = Math.min(500, Math.max(1, Math.trunc(Number(limitInput) || 100)))
|
||||
const candidates = await query<TaskRow>(
|
||||
`${TASK_SELECT}
|
||||
WHERE task.execution_status NOT IN ('completed', 'cancelled')
|
||||
AND task.connector_session_id <> ''
|
||||
ORDER BY task.updated_at ASC, task.id ASC
|
||||
LIMIT $1`,
|
||||
[limit],
|
||||
)
|
||||
let checked = 0
|
||||
let updated = 0
|
||||
for (const candidate of candidates.rows) {
|
||||
try {
|
||||
let task = await ensureConnectorSessionForTask(candidate)
|
||||
if (!task.connector_session_id) continue
|
||||
checked += 1
|
||||
if (
|
||||
task.login_status !== 'authenticated' &&
|
||||
task.login_status !== 'failed' &&
|
||||
task.login_status !== 'expired'
|
||||
) {
|
||||
const login = await getLoginSessionForTask(task, task.connector_session_id)
|
||||
await updateLoginTask(task, login, 'connector')
|
||||
task = await loadTask(task.id)
|
||||
updated += 1
|
||||
}
|
||||
if (
|
||||
task.platform === 'huya' &&
|
||||
task.login_status === 'authenticated' &&
|
||||
['qr_pending', 'scanned', 'role_ready'].includes(task.binding_status)
|
||||
) {
|
||||
const binding = await getBindingForTask(task, task.connector_session_id)
|
||||
await updateBindingTask(task, binding, 'connector')
|
||||
updated += 1
|
||||
}
|
||||
} catch (error) {
|
||||
const detail = error instanceof Error ? error.message : String(error)
|
||||
await query(
|
||||
`UPDATE semi_auto_tasks
|
||||
SET last_error = $2, updated_at = NOW()
|
||||
WHERE id = $1
|
||||
AND execution_status NOT IN ('completed', 'cancelled')`,
|
||||
[candidate.id, detail.slice(0, 1000)],
|
||||
).catch(() => undefined)
|
||||
}
|
||||
}
|
||||
return { checked, updated }
|
||||
}
|
||||
|
||||
const LOGIN_STATUSES = new Set<LoginStatus>([
|
||||
'waiting_login',
|
||||
'qr_pending',
|
||||
'scanned',
|
||||
'authenticated',
|
||||
'failed',
|
||||
'expired',
|
||||
])
|
||||
const BINDING_STATUSES = new Set<BindingStatus>([
|
||||
'not_started',
|
||||
'qr_pending',
|
||||
'scanned',
|
||||
'role_ready',
|
||||
'confirmed',
|
||||
'failed',
|
||||
'expired',
|
||||
])
|
||||
|
||||
function parseSnapshotStatus<T extends string>(value: unknown, allowed: Set<T>, label: string): T {
|
||||
const status = String(value || '').trim() as T
|
||||
if (!allowed.has(status)) {
|
||||
throw createHttpError(`${label}无效`, {
|
||||
statusCode: 400,
|
||||
errorCode: 'semi_auto_snapshot_status_invalid',
|
||||
})
|
||||
}
|
||||
return status
|
||||
}
|
||||
|
||||
/**
|
||||
* 外部 Connector 的幂等状态快照入口。
|
||||
*
|
||||
* Connector 只提交登录/绑定观察结果,不直接声明业务执行完成;执行状态仍由订单系统
|
||||
* 根据登录、绑定和人工确认规则推导。重复 eventId 由 integration_inbox 去重。
|
||||
*/
|
||||
export async function applySemiAutoTaskStateSnapshot(
|
||||
input: Record<string, unknown>,
|
||||
options: { eventId?: string; eventType?: string } = {},
|
||||
) {
|
||||
const eventId = String(options.eventId || input.eventId || '').trim()
|
||||
const taskId = normalizeId(input.taskId ?? input.task_id)
|
||||
const orderNo = normalizeOrderNo(input.orderNo ?? input.order_no)
|
||||
const loginStatus = parseSnapshotStatus(
|
||||
input.loginStatus ?? input.login_status,
|
||||
LOGIN_STATUSES,
|
||||
'登录状态',
|
||||
)
|
||||
const bindingStatus = parseSnapshotStatus(
|
||||
input.bindingStatus ?? input.binding_status,
|
||||
BINDING_STATUSES,
|
||||
'绑定状态',
|
||||
)
|
||||
if (!eventId) {
|
||||
throw createHttpError('状态快照事件编号不能为空', {
|
||||
statusCode: 400,
|
||||
errorCode: 'semi_auto_snapshot_event_id_required',
|
||||
})
|
||||
}
|
||||
|
||||
const result = await withTransaction(async (client) => {
|
||||
const claimed = await client.query(
|
||||
`INSERT INTO integration_inbox (event_id, source, event_type, received_at, processed_at)
|
||||
VALUES ($1, 'semi_auto_connector', $2, NOW(), NOW())
|
||||
ON CONFLICT (event_id) DO NOTHING
|
||||
RETURNING event_id`,
|
||||
[eventId, String(options.eventType || 'semi_auto.task_state')],
|
||||
)
|
||||
if (claimed.rowCount === 0) return { applied: false, terminal: false }
|
||||
|
||||
const task = await loadTaskForUpdateWithClient(client, taskId)
|
||||
if (task.platform_order_id !== orderNo) {
|
||||
throw createHttpError('状态快照与任务订单号不一致', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_snapshot_order_mismatch',
|
||||
})
|
||||
}
|
||||
if (task.execution_status === 'completed' || task.execution_status === 'cancelled') {
|
||||
return { applied: false, terminal: true }
|
||||
}
|
||||
|
||||
const executionStatus: ExecutionStatus =
|
||||
loginStatus === 'authenticated' &&
|
||||
(task.platform === 'weibo' || bindingStatus === 'confirmed')
|
||||
? 'waiting_operator'
|
||||
: 'waiting_customer'
|
||||
const uid = String(input.huyaUid ?? input.huya_uid ?? '').trim()
|
||||
const nickname = String(input.platformNickname ?? input.platform_nickname ?? '').trim()
|
||||
const bindGameAccount = String(input.bindGameAccount ?? input.bind_game_account ?? '').trim()
|
||||
const bindGameRole = String(input.bindGameRole ?? input.bind_game_role ?? '').trim()
|
||||
const bindGameRoleId = String(input.bindGameRoleId ?? input.bind_game_role_id ?? '').trim()
|
||||
const bindGameChannel = String(input.bindGameChannel ?? input.bind_game_channel ?? '').trim()
|
||||
const message = String(input.message ?? input.lastError ?? input.last_error ?? '')
|
||||
.trim()
|
||||
.slice(0, 1000)
|
||||
|
||||
await client.query(
|
||||
`UPDATE semi_auto_tasks
|
||||
SET login_status = $2,
|
||||
binding_status = $3,
|
||||
execution_status = $4,
|
||||
huya_uid = CASE WHEN $5 <> '' THEN $5 ELSE huya_uid END,
|
||||
platform_nickname = CASE WHEN $6 <> '' THEN $6 ELSE platform_nickname END,
|
||||
bind_game_account = CASE WHEN $7 <> '' THEN $7 ELSE bind_game_account END,
|
||||
bind_game_role = CASE WHEN $8 <> '' THEN $8 ELSE bind_game_role END,
|
||||
bind_game_role_id = CASE WHEN $9 <> '' THEN $9 ELSE bind_game_role_id END,
|
||||
bind_game_channel = CASE WHEN $10 <> '' THEN $10 ELSE bind_game_channel END,
|
||||
authenticated_at = CASE
|
||||
WHEN $2 = 'authenticated' THEN COALESCE(authenticated_at, NOW())
|
||||
ELSE authenticated_at
|
||||
END,
|
||||
bound_at = CASE
|
||||
WHEN $3 IN ('role_ready', 'confirmed') THEN COALESCE(bound_at, NOW())
|
||||
ELSE bound_at
|
||||
END,
|
||||
last_error = CASE WHEN $2 IN ('failed', 'expired') OR $3 IN ('failed', 'expired')
|
||||
THEN $11 ELSE '' END,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1`,
|
||||
[
|
||||
task.id,
|
||||
loginStatus,
|
||||
bindingStatus,
|
||||
executionStatus,
|
||||
uid,
|
||||
nickname,
|
||||
bindGameAccount,
|
||||
bindGameRole,
|
||||
bindGameRoleId,
|
||||
bindGameChannel,
|
||||
message,
|
||||
],
|
||||
)
|
||||
if (
|
||||
loginStatus !== task.login_status ||
|
||||
bindingStatus !== task.binding_status ||
|
||||
executionStatus !== task.execution_status
|
||||
) {
|
||||
await appendTaskEvent(client, task.id, {
|
||||
eventType: 'connector_state_synced',
|
||||
actorType: 'connector',
|
||||
fromLoginStatus: task.login_status,
|
||||
toLoginStatus: loginStatus,
|
||||
fromBindingStatus: task.binding_status,
|
||||
toBindingStatus: bindingStatus,
|
||||
fromExecutionStatus: task.execution_status,
|
||||
toExecutionStatus: executionStatus,
|
||||
detail: {
|
||||
eventId,
|
||||
source: 'semi_auto_connector',
|
||||
message,
|
||||
},
|
||||
})
|
||||
}
|
||||
return {
|
||||
applied: true,
|
||||
terminal: false,
|
||||
taskId: task.id,
|
||||
orderId: task.order_id,
|
||||
}
|
||||
})
|
||||
if (result.applied && result.taskId && result.orderId) {
|
||||
publishSemiAutoTaskRealtimeChange(result.taskId, result.orderId)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
export async function requestAdminSemiAutoCustomerReauth(
|
||||
taskIdInput: unknown,
|
||||
session: AdminSession,
|
||||
) {
|
||||
const taskId = normalizeId(taskIdInput)
|
||||
const task = await loadTask(taskId)
|
||||
if (task.execution_status === 'completed') {
|
||||
throw createHttpError('已完成任务不能重新授权', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_task_completed',
|
||||
})
|
||||
}
|
||||
if (task.execution_status === 'cancelled') {
|
||||
throw createHttpError('已取消任务不能重新授权', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_task_cancelled',
|
||||
})
|
||||
}
|
||||
const adminUserId = Number(session.userId || 0)
|
||||
if (task.assigned_admin_user_id && Number(task.assigned_admin_user_id) !== adminUserId) {
|
||||
throw createHttpError('该任务已被其他客服领取', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_task_claimed',
|
||||
})
|
||||
}
|
||||
if (task.connector_session_id) {
|
||||
await revokeSessionForTask(task, task.connector_session_id).catch(() => undefined)
|
||||
}
|
||||
await resetTaskForCustomerLogin(task, {
|
||||
actorType: 'admin',
|
||||
actorId: String(adminUserId),
|
||||
reason: '客服已重新发送授权链接,等待客户重新登录',
|
||||
eventType: 'customer_reauth_requested',
|
||||
})
|
||||
return getAdminSemiAutoTask(taskId)
|
||||
}
|
||||
|
||||
export async function createAdminBrowserSession(
|
||||
taskIdInput: unknown,
|
||||
targetUrlInput: unknown,
|
||||
session: AdminSession,
|
||||
) {
|
||||
const taskId = normalizeId(taskIdInput)
|
||||
const task = await ensureConnectorSessionForTask(await loadTask(taskId))
|
||||
const adminUserId = Number(session.userId || 0)
|
||||
if (task.assigned_admin_user_id && Number(task.assigned_admin_user_id) !== adminUserId) {
|
||||
throw createHttpError('该任务已被其他客服领取', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_task_claimed',
|
||||
})
|
||||
}
|
||||
if (!task.connector_session_id || task.login_status !== 'authenticated') {
|
||||
throw createHttpError('客户尚未完成登录,或登录会话已失效', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_login_required',
|
||||
})
|
||||
}
|
||||
const config = safeParseJson(task.semi_auto_config_json)
|
||||
const targets = Array.isArray(config.browserTargets) ? config.browserTargets : []
|
||||
const explicitTarget = String(targetUrlInput || '').trim()
|
||||
const fallbackTarget = targets.find((item): item is { url?: string } =>
|
||||
Boolean(item && typeof item === 'object'),
|
||||
)?.url
|
||||
const targetUrl = explicitTarget || String(fallbackTarget || '')
|
||||
const ticket =
|
||||
task.platform === 'weibo'
|
||||
? await createWeiboBrowserTicket(
|
||||
{ sessionId: task.connector_session_id, targetUrl },
|
||||
task.connector_mode,
|
||||
)
|
||||
: await createHuyaBrowserTicket(
|
||||
{
|
||||
sessionId: task.connector_session_id,
|
||||
targetUrl,
|
||||
},
|
||||
task.connector_mode,
|
||||
)
|
||||
await withTransaction(async (client) => {
|
||||
await client.query(
|
||||
`UPDATE semi_auto_tasks
|
||||
SET assigned_admin_user_id = COALESCE(assigned_admin_user_id, $2),
|
||||
execution_status = CASE WHEN execution_status = 'waiting_operator' THEN 'processing' ELSE execution_status END,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1`,
|
||||
[taskId, adminUserId],
|
||||
)
|
||||
await appendTaskEvent(client, taskId, {
|
||||
eventType: 'browser_session_opened',
|
||||
actorType: 'admin',
|
||||
actorId: String(adminUserId),
|
||||
detail: { targetUrl },
|
||||
})
|
||||
})
|
||||
publishSemiAutoTaskRealtimeChange(taskId, task.order_id)
|
||||
return ticket
|
||||
}
|
||||
|
||||
/**
|
||||
* 票据内的 targetUrl 只服务于创建阶段的 Cookie 序列化与审计;
|
||||
* 下发给扩展时清空,指定平台页统一由前端占位页在注入成功后打开,
|
||||
* 这样扩展只写 Cookie,不会再额外打开一个目标页标签。
|
||||
*/
|
||||
export function buildExtensionInjectionPayload(
|
||||
payload: ConnectorInjectionPayload,
|
||||
): ConnectorInjectionPayload {
|
||||
return { ...payload, targetUrl: '' }
|
||||
}
|
||||
|
||||
export async function consumeSemiAutoInjectionTicket(ticketInput: unknown) {
|
||||
const ticket = String(ticketInput || '').trim()
|
||||
if (!ticket) {
|
||||
throw createHttpError('注入票据无效', {
|
||||
statusCode: 400,
|
||||
errorCode: 'semi_auto_injection_ticket_invalid',
|
||||
})
|
||||
}
|
||||
const payload = ticket.startsWith(WEIBO_TICKET_PREFIX)
|
||||
? await consumeWeiboBrowserTicket(ticket)
|
||||
: await consumeHuyaBrowserTicket(ticket)
|
||||
return buildExtensionInjectionPayload(payload)
|
||||
}
|
||||
|
||||
async function resolveCompletionEvidence(
|
||||
screenshots: unknown,
|
||||
session: AdminSession,
|
||||
): Promise<UploadedFileDto[]> {
|
||||
const files = Array.isArray(screenshots) ? screenshots : []
|
||||
const uploaderId = String(session.userId || session.username || '')
|
||||
const result: UploadedFileDto[] = []
|
||||
for (const item of files.slice(0, 10)) {
|
||||
const source = item && typeof item === 'object' ? (item as Record<string, unknown>) : {}
|
||||
const objectKey = String(source.objectKey || source.object_key || '').trim()
|
||||
if (!objectKey) continue
|
||||
const asset = await getFileAssetByObjectKey(objectKey)
|
||||
if (
|
||||
!asset ||
|
||||
asset.status !== 'active' ||
|
||||
asset.uploader_type !== 'admin' ||
|
||||
asset.uploader_id !== uploaderId ||
|
||||
asset.scene !== 'semi-auto-evidence' ||
|
||||
!ORDER_SERVICE_SCREENSHOT_CONTENT_TYPES.has(String(asset.content_type || ''))
|
||||
) {
|
||||
throw createHttpError('完成截图无效,请重新上传', {
|
||||
statusCode: 400,
|
||||
errorCode: 'semi_auto_evidence_invalid',
|
||||
})
|
||||
}
|
||||
result.push({
|
||||
objectKey: asset.object_key,
|
||||
url: buildFileUrl(asset.object_key),
|
||||
thumbnailUrl: buildFileUrl(asset.thumbnail_object_key || asset.object_key),
|
||||
mediumUrl: buildFileUrl(asset.medium_object_key || asset.object_key),
|
||||
filename: asset.original_filename,
|
||||
contentType: asset.content_type,
|
||||
size: Number(asset.size_bytes || 0),
|
||||
})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
export async function completeAdminSemiAutoTask(
|
||||
taskIdInput: unknown,
|
||||
payload: Record<string, unknown>,
|
||||
session: AdminSession,
|
||||
) {
|
||||
const taskId = normalizeId(taskIdInput)
|
||||
let current = await loadTask(taskId)
|
||||
if (current.execution_status === 'completed') return getAdminSemiAutoTask(taskId)
|
||||
current = await ensureConnectorSessionForTask(current)
|
||||
if (current.execution_status === 'completed') return getAdminSemiAutoTask(taskId)
|
||||
if (current.execution_status === 'cancelled') {
|
||||
throw createHttpError('任务已取消,不能完成', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_task_cancelled',
|
||||
})
|
||||
}
|
||||
const screenshots = await resolveCompletionEvidence(payload.screenshots || [], session)
|
||||
const note = String(payload.note || '')
|
||||
.trim()
|
||||
.slice(0, 1000)
|
||||
const externalOrderNo = String(payload.externalOrderNo || payload.external_order_no || '')
|
||||
.trim()
|
||||
.slice(0, 200)
|
||||
const costFenRaw = Number(payload.costFen ?? payload.cost_fen)
|
||||
const costFen =
|
||||
Number.isFinite(costFenRaw) && costFenRaw >= 0 ? Math.trunc(costFenRaw) : undefined
|
||||
const completionNote = [note, externalOrderNo ? `外部单号:${externalOrderNo}` : '']
|
||||
.filter(Boolean)
|
||||
.join(';')
|
||||
const adminUserId = Number(session.userId || 0)
|
||||
|
||||
// 人工财务确认、履约状态和半自动任务完成必须同事务提交:
|
||||
// 任何任务更新失败都会回滚成本快照、钱包扣减和履约状态,避免“已扣钱但任务未完成”。
|
||||
const completion = await withTransaction(async (client) => {
|
||||
const task = await loadTaskForUpdateWithClient(client, taskId)
|
||||
if (task.execution_status === 'completed') {
|
||||
return { task, completedNow: false }
|
||||
}
|
||||
if (task.execution_status === 'cancelled') {
|
||||
throw createHttpError('任务已取消,不能完成', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_task_cancelled',
|
||||
})
|
||||
}
|
||||
if (
|
||||
task.login_status !== 'authenticated' ||
|
||||
!task.credential_id ||
|
||||
task.credential_status === 'invalid' ||
|
||||
task.credential_status === 'error'
|
||||
) {
|
||||
throw createHttpError('客户账号 CK 尚未就绪或已失效,不能完成履约', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_credential_required',
|
||||
})
|
||||
}
|
||||
if (task.assigned_admin_user_id && Number(task.assigned_admin_user_id) !== adminUserId) {
|
||||
throw createHttpError('该任务已被其他客服领取', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_task_claimed',
|
||||
})
|
||||
}
|
||||
|
||||
await confirmManualFulfillment(
|
||||
{
|
||||
orderItemId: task.order_item_id,
|
||||
platformKey: task.manual_platform_key,
|
||||
...(costFen !== undefined ? { costFen } : {}),
|
||||
note: completionNote || '半自动履约完成',
|
||||
},
|
||||
session,
|
||||
{ client },
|
||||
)
|
||||
|
||||
const updated = await client.query<{ id: number }>(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET assigned_admin_user_id = COALESCE(assigned_admin_user_id, $2),
|
||||
execution_status = 'completed',
|
||||
completed_quantity = target_quantity,
|
||||
completed_at = NOW(),
|
||||
completion_note = $3,
|
||||
external_order_no = $4,
|
||||
completion_evidence_json = $5::jsonb,
|
||||
last_error = '',
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
RETURNING id
|
||||
`,
|
||||
[taskId, adminUserId, note, externalOrderNo, JSON.stringify({ screenshots })],
|
||||
)
|
||||
if (!updated.rows[0]) {
|
||||
throw createHttpError('半自动履约任务状态更新失败', {
|
||||
statusCode: 500,
|
||||
errorCode: 'semi_auto_task_completion_failed',
|
||||
})
|
||||
}
|
||||
await appendTaskEvent(client, taskId, {
|
||||
eventType: 'task_completed',
|
||||
actorType: 'admin',
|
||||
actorId: String(adminUserId),
|
||||
fromExecutionStatus: task.execution_status,
|
||||
toExecutionStatus: 'completed',
|
||||
detail: {
|
||||
note,
|
||||
externalOrderNo,
|
||||
screenshotCount: screenshots.length,
|
||||
},
|
||||
})
|
||||
return { task, completedNow: true }
|
||||
})
|
||||
|
||||
if (!completion.completedNow) {
|
||||
return getAdminSemiAutoTask(taskId)
|
||||
}
|
||||
await runManualFulfillmentPostCommit(completion.task.order_item_id)
|
||||
if (completion.task.connector_session_id) {
|
||||
await revokeSessionForTask(completion.task, completion.task.connector_session_id).catch(
|
||||
() => undefined,
|
||||
)
|
||||
}
|
||||
publishAdminOrderRealtimeChange(Number(completion.task.order_id))
|
||||
publishSemiAutoTaskRealtimeChange(taskId, completion.task.order_id)
|
||||
return getAdminSemiAutoTask(taskId)
|
||||
}
|
||||
|
||||
export async function cancelAdminSemiAutoTask(
|
||||
taskIdInput: unknown,
|
||||
payload: Record<string, unknown>,
|
||||
session: AdminSession,
|
||||
) {
|
||||
const taskId = normalizeId(taskIdInput)
|
||||
const reason = String(payload.reason || '')
|
||||
.trim()
|
||||
.slice(0, 500)
|
||||
const adminUserId = Number(session.userId || 0)
|
||||
let orderId = 0
|
||||
const connector: {
|
||||
sessionId: string
|
||||
mode: SemiAutoConnectorMode
|
||||
platform: SemiAutoPlatform
|
||||
} = {
|
||||
sessionId: '',
|
||||
mode: 'embedded',
|
||||
platform: 'huya',
|
||||
}
|
||||
await withTransaction(async (client) => {
|
||||
const task = await loadTaskForUpdateWithClient(client, taskId)
|
||||
orderId = Number(task.order_id)
|
||||
connector.sessionId = task.connector_session_id
|
||||
connector.mode = task.connector_mode
|
||||
connector.platform = task.platform
|
||||
if (task.execution_status === 'completed') {
|
||||
throw createHttpError('已完成任务不能取消', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_task_completed',
|
||||
})
|
||||
}
|
||||
if (task.execution_status === 'cancelled') {
|
||||
return
|
||||
}
|
||||
await client.query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET execution_status = 'cancelled',
|
||||
last_error = $2,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[taskId, reason],
|
||||
)
|
||||
await appendTaskEvent(client, taskId, {
|
||||
eventType: 'task_cancelled',
|
||||
actorType: 'admin',
|
||||
actorId: String(adminUserId),
|
||||
fromExecutionStatus: task.execution_status,
|
||||
toExecutionStatus: 'cancelled',
|
||||
detail: { reason },
|
||||
})
|
||||
})
|
||||
if (connector.sessionId) {
|
||||
const revoke =
|
||||
connector.platform === 'weibo'
|
||||
? revokeWeiboSession(connector.sessionId, connector.mode)
|
||||
: revokeHuyaSession(connector.sessionId, connector.mode)
|
||||
await revoke.catch(() => undefined)
|
||||
}
|
||||
publishAdminOrderRealtimeChange(orderId)
|
||||
publishSemiAutoTaskRealtimeChange(taskId, orderId)
|
||||
return getAdminSemiAutoTask(taskId)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,53 @@
|
||||
import { backfillSemiAutoTasks, reconcileSemiAutoTaskStates } from './semi-auto-task-service.js'
|
||||
import { runtimeConfig } from '../../config/runtime.js'
|
||||
import { logWarn } from '../../utils/logger.js'
|
||||
|
||||
const DEFAULT_RECONCILE_SECONDS = 900
|
||||
|
||||
let timer: NodeJS.Timeout | null = null
|
||||
let stopped = true
|
||||
|
||||
function intervalMs() {
|
||||
const value = Number(runtimeConfig.semiAuto?.reconcileSeconds)
|
||||
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 {
|
||||
const createdAfter = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString()
|
||||
await backfillSemiAutoTasks({ createdAfter, limit: 500 })
|
||||
await reconcileSemiAutoTaskStates(100)
|
||||
} catch (error) {
|
||||
logWarn('[semi-auto]', '低频对账失败', { error })
|
||||
} finally {
|
||||
if (!stopped) {
|
||||
timer = setTimeout(() => {
|
||||
void run()
|
||||
}, intervalMs())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function startSemiAutoTaskReconciler() {
|
||||
if (timer || !stopped) return
|
||||
stopped = false
|
||||
timer = setTimeout(
|
||||
() => {
|
||||
void run()
|
||||
},
|
||||
Math.min(60_000, intervalMs()),
|
||||
)
|
||||
}
|
||||
|
||||
export function stopSemiAutoTaskReconciler() {
|
||||
stopped = true
|
||||
if (timer) {
|
||||
clearTimeout(timer)
|
||||
timer = null
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -5,6 +5,7 @@
|
||||
* npx tsx --test src/services/semi-auto/semi-auto-task.integration.test.ts
|
||||
*/
|
||||
import assert from 'node:assert/strict'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import test from 'node:test'
|
||||
|
||||
const TEST_DATABASE_URL = String(process.env.SEMI_AUTO_TASK_TEST_DATABASE_URL || '').trim()
|
||||
@@ -24,6 +25,7 @@ test(
|
||||
process.env.DATABASE_URL = TEST_DATABASE_URL
|
||||
const { closeDb, query, withTransaction } = await import('../../db/client.js')
|
||||
const {
|
||||
applySemiAutoTaskStateSnapshot,
|
||||
confirmPublicBinding,
|
||||
ensureSemiAutoTasksForOrder,
|
||||
exportAdminSemiAutoCredential,
|
||||
@@ -268,6 +270,23 @@ test(
|
||||
)
|
||||
assert.equal(resetEvents.rows[0]?.detail_json?.reason, 'customer_profile_edit')
|
||||
|
||||
// 已确认绑定后的重新授权必须完整退出已授权状态,不能只清登录状态。
|
||||
await query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET binding_status = 'confirmed',
|
||||
bind_game_account = '集成测试虎牙账号',
|
||||
bind_game_role = '集成测试角色',
|
||||
bind_game_role_id = '1192083858',
|
||||
bind_game_channel = '安卓(iOS) · QQ',
|
||||
binding_started_at = NOW(),
|
||||
bound_at = NOW(),
|
||||
execution_status = 'waiting_operator',
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[taskId],
|
||||
)
|
||||
const reauthorized = await requestAdminSemiAutoCustomerReauth(taskId, {
|
||||
userId: 1,
|
||||
role: 'support',
|
||||
@@ -277,6 +296,11 @@ test(
|
||||
assert.equal(reauthorized.task.bindingStatus, 'not_started')
|
||||
assert.equal(reauthorized.task.executionStatus, 'waiting_customer')
|
||||
assert.equal(reauthorized.task.customerLinkOpenedAt, null)
|
||||
assert.equal(reauthorized.task.bindGameAccount, '')
|
||||
assert.equal(reauthorized.task.bindGameRole, '')
|
||||
assert.equal(reauthorized.task.bindGameRoleId, '')
|
||||
assert.equal(reauthorized.task.bindGameChannel, '')
|
||||
assert.equal(reauthorized.task.boundAt, null)
|
||||
const retainedCredential = await query<{ credential_id: number }>(
|
||||
'SELECT credential_id FROM semi_auto_tasks WHERE id = $1',
|
||||
[taskId],
|
||||
@@ -285,6 +309,49 @@ test(
|
||||
assert.ok(
|
||||
reauthorized.events.some((event) => event.eventType === 'customer_reauth_requested'),
|
||||
)
|
||||
|
||||
const snapshotEventId = randomUUID()
|
||||
const snapshot = await applySemiAutoTaskStateSnapshot(
|
||||
{
|
||||
eventId: snapshotEventId,
|
||||
taskId,
|
||||
orderNo,
|
||||
loginStatus: 'authenticated',
|
||||
bindingStatus: 'confirmed',
|
||||
huyaUid: `it-huya-${suffix}`,
|
||||
bindGameAccount: '集成测试虎牙账号',
|
||||
bindGameRole: '集成测试角色',
|
||||
bindGameRoleId: '1192083858',
|
||||
bindGameChannel: '安卓(android) · QQ',
|
||||
},
|
||||
{ eventId: snapshotEventId, eventType: 'semi_auto.task_state' },
|
||||
)
|
||||
assert.equal(snapshot.applied, true)
|
||||
const duplicateSnapshot = await applySemiAutoTaskStateSnapshot(
|
||||
{
|
||||
eventId: snapshotEventId,
|
||||
taskId,
|
||||
orderNo,
|
||||
loginStatus: 'authenticated',
|
||||
bindingStatus: 'confirmed',
|
||||
},
|
||||
{ eventId: snapshotEventId, eventType: 'semi_auto.task_state' },
|
||||
)
|
||||
assert.equal(duplicateSnapshot.applied, false)
|
||||
const synced = await query<{
|
||||
login_status: string
|
||||
binding_status: string
|
||||
execution_status: string
|
||||
}>(
|
||||
`SELECT login_status, binding_status, execution_status
|
||||
FROM semi_auto_tasks WHERE id = $1`,
|
||||
[taskId],
|
||||
)
|
||||
assert.deepEqual(synced.rows[0], {
|
||||
login_status: 'authenticated',
|
||||
binding_status: 'confirmed',
|
||||
execution_status: 'waiting_operator',
|
||||
})
|
||||
} finally {
|
||||
if (orderId > 0) {
|
||||
await query('DELETE FROM order_source_snapshots WHERE order_id = $1', [orderId])
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { stringifyTraceBody } from './semi-auto-trace.js'
|
||||
|
||||
test('半自动请求报文脱敏通用 code、mfa_id 和 rid', () => {
|
||||
const body = stringifyTraceBody(
|
||||
{
|
||||
code: '123456',
|
||||
mfa_id: 'mfa-secret',
|
||||
rid: 'request-secret',
|
||||
mobile: '13800138000',
|
||||
},
|
||||
{ maskRequestCode: true },
|
||||
)
|
||||
|
||||
assert.doesNotMatch(body, /123456|mfa-secret|request-secret/)
|
||||
assert.match(body, /13800138000/)
|
||||
assert.match(body, /"code": "\*\*\*\*\*\*"/)
|
||||
})
|
||||
|
||||
test('半自动响应报文保留业务 code,只屏蔽既有敏感键', () => {
|
||||
const body = stringifyTraceBody({
|
||||
code: 0,
|
||||
message: 'ok',
|
||||
cookie: 'SUB=secret',
|
||||
})
|
||||
|
||||
assert.match(body, /"code": 0/)
|
||||
assert.doesNotMatch(body, /SUB=secret/)
|
||||
})
|
||||
@@ -36,6 +36,8 @@ export type SemiAutoTraceEntry = {
|
||||
durationMs?: number
|
||||
requestSummary?: Record<string, unknown>
|
||||
requestBody?: unknown
|
||||
/** 请求体里的通用 `code` 字段按验证码处理;响应体中的业务 code 保持原样。 */
|
||||
maskRequestCode?: boolean
|
||||
responseSummary?: Record<string, unknown>
|
||||
responseBody?: unknown
|
||||
errorMessage?: string
|
||||
@@ -86,6 +88,7 @@ const SENSITIVE_KEYS = new Set([
|
||||
'ticket',
|
||||
'credential_payload_json',
|
||||
])
|
||||
const REQUEST_ONLY_SENSITIVE_KEYS = new Set(['code', 'rid', 'mfa_id'])
|
||||
|
||||
export function runWithSemiAutoTrace<T>(context: SemiAutoTraceContext, fn: () => T): T {
|
||||
return traceStorage.run(context, fn)
|
||||
@@ -106,29 +109,39 @@ function normalizeKey(key: string): string {
|
||||
}
|
||||
|
||||
/** 深度脱敏:Cookie / Token / 密钥字段直接替换为 ******。 */
|
||||
export function redactTraceValue(value: unknown, depth = 0): unknown {
|
||||
export function redactTraceValue(
|
||||
value: unknown,
|
||||
depth = 0,
|
||||
options: { maskRequestCode?: boolean } = {},
|
||||
): unknown {
|
||||
if (depth > MAX_REDACT_DEPTH) return '[max-depth]'
|
||||
if (value === null || value === undefined) return value
|
||||
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
|
||||
return value
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
return value.slice(0, 50).map((item) => redactTraceValue(item, depth + 1))
|
||||
return value.slice(0, 50).map((item) => redactTraceValue(item, depth + 1, options))
|
||||
}
|
||||
if (typeof value === 'object') {
|
||||
const source = value as Record<string, unknown>
|
||||
const result: Record<string, unknown> = {}
|
||||
for (const [key, current] of Object.entries(source)) {
|
||||
result[key] = SENSITIVE_KEYS.has(normalizeKey(key))
|
||||
? maskValue(current)
|
||||
: redactTraceValue(current, depth + 1)
|
||||
const normalizedKey = normalizeKey(key)
|
||||
result[key] =
|
||||
SENSITIVE_KEYS.has(normalizedKey) ||
|
||||
(options.maskRequestCode === true && REQUEST_ONLY_SENSITIVE_KEYS.has(normalizedKey))
|
||||
? maskValue(current)
|
||||
: redactTraceValue(current, depth + 1, options)
|
||||
}
|
||||
return result
|
||||
}
|
||||
return String(value)
|
||||
}
|
||||
|
||||
export function stringifyTraceBody(value: unknown): string {
|
||||
export function stringifyTraceBody(
|
||||
value: unknown,
|
||||
options: { maskRequestCode?: boolean } = {},
|
||||
): string {
|
||||
if (value === undefined || value === null) return ''
|
||||
if (typeof value === 'string') {
|
||||
return value.length > MAX_BODY_CHARS
|
||||
@@ -136,7 +149,7 @@ export function stringifyTraceBody(value: unknown): string {
|
||||
: value
|
||||
}
|
||||
try {
|
||||
const text = JSON.stringify(redactTraceValue(value), null, 2)
|
||||
const text = JSON.stringify(redactTraceValue(value, 0, options), null, 2)
|
||||
return text.length > MAX_BODY_CHARS ? `${text.slice(0, MAX_BODY_CHARS)}\n...[truncated]` : text
|
||||
} catch {
|
||||
return String(value).slice(0, MAX_BODY_CHARS)
|
||||
@@ -172,7 +185,9 @@ export function recordSemiAutoTrace(entry: SemiAutoTraceEntry): void {
|
||||
const orderNo = entry.orderNo || context?.orderNo || ''
|
||||
const requestId = entry.requestId || context?.requestId || ''
|
||||
const status = entry.status === 'error' ? 'error' : 'ok'
|
||||
const requestBody = stringifyTraceBody(entry.requestBody)
|
||||
const requestBody = stringifyTraceBody(entry.requestBody, {
|
||||
maskRequestCode: entry.maskRequestCode === true,
|
||||
})
|
||||
const responseBody = stringifyTraceBody(entry.responseBody)
|
||||
void query(
|
||||
`INSERT INTO semi_auto_trace_logs (
|
||||
|
||||
@@ -5,6 +5,7 @@ import { ensureFulfillmentCatalogBootstrapped } from '../services/bootstrap/fulf
|
||||
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 { startSemiAutoTaskReconciler } from '../services/semi-auto/semi-auto-task-reconciler.js'
|
||||
import { startScheduledJobs } from '../services/scheduler/scheduler-service.js'
|
||||
import { logError, logInfo } from '../utils/logger.js'
|
||||
import { startMemoryReporter } from './memory-reporter.js'
|
||||
@@ -50,6 +51,7 @@ export async function bootstrapCoreServices(
|
||||
startKuaishouIndustrySendCallbackRetryWorker()
|
||||
startIntegrationOutboxWorker()
|
||||
startDouyuFulfillmentReconciler()
|
||||
startSemiAutoTaskReconciler()
|
||||
startMemoryReporter()
|
||||
break
|
||||
} catch (error) {
|
||||
|
||||
@@ -3,6 +3,7 @@ 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 { stopSemiAutoTaskReconciler } from '../services/semi-auto/semi-auto-task-reconciler.js'
|
||||
import { stopScheduledJobs } from '../services/scheduler/scheduler-service.js'
|
||||
import { closeDb } from '../db/client.js'
|
||||
import { logError, logInfo } from '../utils/logger.js'
|
||||
@@ -32,6 +33,7 @@ export function createShutdownController(
|
||||
stopKuaishouIndustrySendCallbackRetryWorker()
|
||||
stopIntegrationOutboxWorker()
|
||||
stopDouyuFulfillmentReconciler()
|
||||
stopSemiAutoTaskReconciler()
|
||||
|
||||
if (server.listening) {
|
||||
await new Promise<void>((resolve) => {
|
||||
|
||||
@@ -67,6 +67,7 @@ export type RuntimeConfig = {
|
||||
connectorBaseUrl: string
|
||||
connectorApiKey: string
|
||||
connectorTimeoutMs: number
|
||||
reconcileSeconds: number
|
||||
huya: {
|
||||
bindActId: number
|
||||
outerActId: string
|
||||
|
||||
@@ -526,6 +526,10 @@ function applyAdminRealtimeEvent(
|
||||
if (event.type === 'order.changed' && event.scopes.includes('admin_douyu_fulfillment')) {
|
||||
void queryClient.invalidateQueries({ queryKey: ['admin-douyu-fulfillment'] })
|
||||
}
|
||||
if (event.type === 'order.changed' && event.scopes.includes('admin_semi_auto_tasks')) {
|
||||
void queryClient.invalidateQueries({ queryKey: ['admin-semi-auto-tasks'] })
|
||||
void queryClient.invalidateQueries({ queryKey: ['admin-semi-auto-task'] })
|
||||
}
|
||||
|
||||
if (event.type === 'admin_notification.changed' && isRecord(event.data)) {
|
||||
queryClient.setQueryData(['admin-notifications'], (current: unknown) => {
|
||||
|
||||
@@ -128,13 +128,11 @@ export default function AdminSemiAutoTasksPage() {
|
||||
const listQuery = useQuery({
|
||||
queryKey: ['admin-semi-auto-tasks', params],
|
||||
queryFn: () => fetchAdminSemiAutoTasks(params),
|
||||
refetchInterval: 3000,
|
||||
})
|
||||
const detailQuery = useQuery({
|
||||
queryKey: ['admin-semi-auto-task', detailTaskId],
|
||||
queryFn: () => fetchAdminSemiAutoTask(Number(detailTaskId)),
|
||||
enabled: Boolean(detailTaskId),
|
||||
refetchInterval: detailTaskId ? 3000 : false,
|
||||
})
|
||||
const list = listQuery.data?.data?.items || []
|
||||
const pagination = listQuery.data?.data?.pagination
|
||||
@@ -479,6 +477,7 @@ export default function AdminSemiAutoTasksPage() {
|
||||
render: (_, task) => (
|
||||
<Space direction="vertical" size={2}>
|
||||
<Tag>{task.displayStatus.label}</Tag>
|
||||
<Text type="secondary">{task.displayStatus.nextAction}</Text>
|
||||
<Text type="secondary">{task.huyaUid ? `UID ${task.huyaUid}` : '未获取 UID'}</Text>
|
||||
<Text type="secondary">
|
||||
{task.platform === 'huya'
|
||||
|
||||
@@ -194,11 +194,25 @@ export default function CustomerFulfillmentPage({
|
||||
) {
|
||||
return
|
||||
}
|
||||
const dedicatedLoginPoll =
|
||||
selectedTask.loginStatus === 'qr_pending' || selectedTask.loginStatus === 'scanned'
|
||||
const dedicatedBindingPoll =
|
||||
selectedTask.platform === 'huya' &&
|
||||
(selectedTask.bindingStatus === 'qr_pending' || selectedTask.bindingStatus === 'scanned')
|
||||
if (dedicatedLoginPoll || dedicatedBindingPoll) return
|
||||
const timer = window.setInterval(() => {
|
||||
void load(true)
|
||||
}, POLL_INTERVAL_MS)
|
||||
}, 10_000)
|
||||
return () => window.clearInterval(timer)
|
||||
}, [load, orderNo, selectedTask?.executionStatus, selectedTask?.id])
|
||||
}, [
|
||||
load,
|
||||
orderNo,
|
||||
selectedTask?.bindingStatus,
|
||||
selectedTask?.executionStatus,
|
||||
selectedTask?.id,
|
||||
selectedTask?.loginStatus,
|
||||
selectedTask?.platform,
|
||||
])
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedTask) return
|
||||
@@ -725,19 +739,6 @@ export default function CustomerFulfillmentPage({
|
||||
}
|
||||
}
|
||||
|
||||
/** 资料变更后重新打开核对弹窗:只有三项完全一致才让客户直接提交平台绑定。 */
|
||||
function reopenBindingConfirm(
|
||||
nextTask: CustomerSemiAutoTask,
|
||||
nextBinding: CustomerBindingInfo | null | undefined,
|
||||
) {
|
||||
if (nextTask.bindingStatus !== 'role_ready') return false
|
||||
if (!nextBinding?.comparison || nextBinding.rebindUnchanged) return false
|
||||
if (nextBinding.comparison.verdict !== 'match') return false
|
||||
autoOpenedRoleRef.current = `${nextTask.id}:${nextBinding.bindGameRoleId || ''}`
|
||||
setBindingConfirmOpen(true)
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回第二步修改资料:
|
||||
* 立即切回资料表单(步骤条高亮第 2 步、隐藏绑定/换绑结果),同时调后端清空虎牙
|
||||
@@ -802,15 +803,7 @@ export default function CustomerFulfillmentPage({
|
||||
current.map((task) => (task.id === response.data.task.id ? response.data.task : task)),
|
||||
)
|
||||
setProfileEditing(false)
|
||||
let reopened = false
|
||||
try {
|
||||
const bindingResponse = await pollCustomerBinding(orderNo, selectedTask.id)
|
||||
if (bindingResponse.data.binding) setBindingInfo(bindingResponse.data.binding)
|
||||
reopened = reopenBindingConfirm(bindingResponse.data.task, bindingResponse.data.binding)
|
||||
} catch {
|
||||
// 绑定尚未开始时没有 binding,可忽略。
|
||||
}
|
||||
message.success(reopened ? '资料已保存且与平台角色一致,请提交平台绑定' : '资料已保存')
|
||||
message.success('资料已保存,正在重新核对平台角色')
|
||||
} catch (error) {
|
||||
message.error(error instanceof Error ? error.message : '保存角色资料失败')
|
||||
} finally {
|
||||
@@ -1460,6 +1453,15 @@ export default function CustomerFulfillmentPage({
|
||||
<span>
|
||||
三项完全一致才能提交平台绑定;请重新扫码换绑,或上一步修改资料。
|
||||
</span>
|
||||
{nextRebindText ? (
|
||||
<span>平台预计下次允许换绑:{nextRebindText}</span>
|
||||
) : null}
|
||||
{Number(bindingInfo?.rebindCooldownDays || 0) > 0 ? (
|
||||
<span>
|
||||
当前仍处于虎牙换绑冷却期,剩余约{' '}
|
||||
{Number(bindingInfo?.rebindCooldownDays || 0)} 天。
|
||||
</span>
|
||||
) : null}
|
||||
</Space>
|
||||
}
|
||||
/>
|
||||
|
||||
@@ -3,6 +3,8 @@ export type SemiAutoPlatform = 'huya' | 'weibo'
|
||||
export type SemiAutoDisplayStatus = {
|
||||
key: string
|
||||
label: string
|
||||
owner: 'none' | 'customer' | 'operator' | 'system'
|
||||
nextAction: string
|
||||
}
|
||||
|
||||
export type SemiAutoTask = {
|
||||
|
||||
@@ -21,7 +21,12 @@ export type CustomerSemiAutoTask = {
|
||||
loginStatus: string
|
||||
bindingStatus: string
|
||||
executionStatus: string
|
||||
displayStatus: { key: string; label: string }
|
||||
displayStatus: {
|
||||
key: string
|
||||
label: string
|
||||
owner: 'none' | 'customer' | 'operator' | 'system'
|
||||
nextAction: string
|
||||
}
|
||||
huyaUid: string
|
||||
platformNickname: string
|
||||
bindGameAccount: string
|
||||
|
||||
@@ -29,12 +29,21 @@ test('资料不一致时固定提供重新扫码换绑与上一步修改资料',
|
||||
assert.ok(styles.includes('.customer-binding-role-actions'))
|
||||
})
|
||||
|
||||
test('保存资料后只有三项一致才重新打开核对弹窗', () => {
|
||||
assert.ok(source.includes('function reopenBindingConfirm('))
|
||||
assert.ok(source.includes("if (nextTask.bindingStatus !== 'role_ready') return false"))
|
||||
assert.ok(source.includes("if (nextBinding.comparison.verdict !== 'match') return false"))
|
||||
assert.ok(source.includes('reopened = reopenBindingConfirm('))
|
||||
assert.ok(source.includes('资料已保存且与平台角色一致,请提交平台绑定'))
|
||||
test('保存资料后只由单一自动绑定流程推进,不再并发轮询', () => {
|
||||
assert.ok(!source.includes('function reopenBindingConfirm('))
|
||||
const saveStart = source.indexOf('async function handleSaveProfile()')
|
||||
assert.ok(saveStart > 0)
|
||||
const saveBody = source.slice(saveStart, saveStart + 1800)
|
||||
assert.ok(!saveBody.includes('pollCustomerBinding('))
|
||||
assert.ok(source.includes("message.success('资料已保存,正在重新核对平台角色')"))
|
||||
assert.ok(source.includes("if (selectedTask.bindingStatus !== 'not_started'"))
|
||||
})
|
||||
|
||||
test('登录和绑定专用同步阶段暂停整单轮询', () => {
|
||||
assert.ok(source.includes('const dedicatedLoginPoll ='))
|
||||
assert.ok(source.includes('const dedicatedBindingPoll ='))
|
||||
assert.ok(source.includes('if (dedicatedLoginPoll || dedicatedBindingPoll) return'))
|
||||
assert.ok(source.includes('}, 10_000)'))
|
||||
})
|
||||
|
||||
test('三项一致才出现提交平台绑定,不一致时展示原因', () => {
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import test from 'node:test'
|
||||
|
||||
const root = dirname(fileURLToPath(import.meta.url))
|
||||
const adminPage = readFileSync(join(root, '../src/pages/admin/AdminSemiAutoTasksPage.tsx'), 'utf8')
|
||||
const adminLayout = readFileSync(join(root, '../src/layouts/AdminLayout.tsx'), 'utf8')
|
||||
|
||||
test('半自动履约后台由 SSE 刷新,不再定时轮询列表和详情', () => {
|
||||
assert.ok(!adminPage.includes('refetchInterval: 3000'))
|
||||
assert.ok(adminLayout.includes("event.scopes.includes('admin_semi_auto_tasks')"))
|
||||
assert.ok(adminLayout.includes("queryKey: ['admin-semi-auto-tasks']"))
|
||||
assert.ok(adminLayout.includes("queryKey: ['admin-semi-auto-task']"))
|
||||
})
|
||||
|
||||
test('后台状态列展示统一的后端下一步动作', () => {
|
||||
assert.ok(adminPage.includes('task.displayStatus.nextAction'))
|
||||
})
|
||||
Reference in New Issue
Block a user