feat(semi-auto): 新增履约历史与全链路报文留痕
运营端历史抽屉展示状态流转与全链路报文:客户/运营接口入站 + 虎牙 WUP/livelink、外部 Connector 出站;轮询按状态变化采样,Cookie/Token/短信验证码不落库,报文保留 180 天。同步收敛登录/绑定事件,避免轮询重复写时间线。
This commit is contained in:
@@ -0,0 +1,33 @@
|
|||||||
|
-- 半自动履约:全链路报文留痕(原本系统入站请求 + 外部平台/Connector 出站调用)
|
||||||
|
-- Cookie / Token / 密钥一律不落库;报文按 180 天保留,由服务侧定期清理。
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS semi_auto_trace_logs (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
task_id BIGINT NOT NULL REFERENCES semi_auto_tasks(id) ON DELETE CASCADE,
|
||||||
|
order_no TEXT NOT NULL DEFAULT '',
|
||||||
|
request_id TEXT NOT NULL DEFAULT '',
|
||||||
|
direction TEXT NOT NULL CHECK (direction IN ('inbound', 'outbound')),
|
||||||
|
channel TEXT NOT NULL,
|
||||||
|
action TEXT NOT NULL,
|
||||||
|
status TEXT NOT NULL DEFAULT 'ok' CHECK (status IN ('ok', 'error')),
|
||||||
|
http_status INTEGER,
|
||||||
|
duration_ms INTEGER,
|
||||||
|
request_summary JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||||
|
request_body TEXT NOT NULL DEFAULT '',
|
||||||
|
response_summary JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||||
|
response_body TEXT NOT NULL DEFAULT '',
|
||||||
|
error_message TEXT NOT NULL DEFAULT '',
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_semi_auto_trace_task
|
||||||
|
ON semi_auto_trace_logs (task_id, id DESC);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_semi_auto_trace_request
|
||||||
|
ON semi_auto_trace_logs (request_id);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_semi_auto_trace_created
|
||||||
|
ON semi_auto_trace_logs (created_at);
|
||||||
|
|
||||||
|
COMMENT ON TABLE semi_auto_trace_logs IS
|
||||||
|
'半自动履约全链路报文;request_body/response_body 已脱敏(Cookie、Token、密钥不落库)';
|
||||||
@@ -4,6 +4,7 @@ import { createApp } from './app.js'
|
|||||||
import { runtimeConfig } from './config/runtime.js'
|
import { runtimeConfig } from './config/runtime.js'
|
||||||
import { assertRuntimeConfigValid } from './config/runtime-validation.js'
|
import { assertRuntimeConfigValid } from './config/runtime-validation.js'
|
||||||
import { bootstrapCoreServices } from './startup/bootstrap.js'
|
import { bootstrapCoreServices } from './startup/bootstrap.js'
|
||||||
|
import { startSemiAutoTraceCleanup } from './services/semi-auto/semi-auto-trace.js'
|
||||||
import { createShutdownController } from './startup/shutdown.js'
|
import { createShutdownController } from './startup/shutdown.js'
|
||||||
import { createStartupState, formatStartupError } from './startup/state.js'
|
import { createStartupState, formatStartupError } from './startup/state.js'
|
||||||
import { logError, logInfo } from './utils/logger.js'
|
import { logError, logInfo } from './utils/logger.js'
|
||||||
@@ -30,6 +31,8 @@ const app = createApp({
|
|||||||
const server = app.listen(port, host, () => {
|
const server = app.listen(port, host, () => {
|
||||||
logInfo('[startup]', `order-site-backend kuaishou-lite listening on http://${host}:${port}`)
|
logInfo('[startup]', `order-site-backend kuaishou-lite listening on http://${host}:${port}`)
|
||||||
void bootstrapCoreServices(startupState, () => shutdownController?.isShutdownStarted() || false)
|
void bootstrapCoreServices(startupState, () => shutdownController?.isShutdownStarted() || false)
|
||||||
|
// 半自动履约报文保留 180 天:启动先清一次,之后每 6 小时清理。
|
||||||
|
startSemiAutoTraceCleanup()
|
||||||
})
|
})
|
||||||
|
|
||||||
shutdownController = createShutdownController(server, startupState)
|
shutdownController = createShutdownController(server, startupState)
|
||||||
|
|||||||
@@ -0,0 +1,248 @@
|
|||||||
|
import crypto from 'node:crypto'
|
||||||
|
|
||||||
|
import type { NextFunction, Request, Response } from 'express'
|
||||||
|
|
||||||
|
import { query } from '../db/client.js'
|
||||||
|
import {
|
||||||
|
recordSemiAutoTrace,
|
||||||
|
runWithSemiAutoTrace,
|
||||||
|
traceFingerprint,
|
||||||
|
type SemiAutoTraceChannel,
|
||||||
|
} from '../services/semi-auto/semi-auto-trace.js'
|
||||||
|
import { logWarn } from '../utils/logger.js'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 半自动履约入站报文:以 `:taskId` 路由参数为锚点。
|
||||||
|
*
|
||||||
|
* 用法:`router.param('taskId', createSemiAutoTaskTraceHandler({ channel: 'customer_api' }))`。
|
||||||
|
* 命中后整条请求链路都在 AsyncLocalStorage 上下文里,外部 Connector / 虎牙 RPC 的出站报文
|
||||||
|
* 会自动复用同一个 requestId,前端即可按 requestId 串起「一次客户操作」。
|
||||||
|
*/
|
||||||
|
export type SemiAutoTaskTraceOptions = {
|
||||||
|
channel: SemiAutoTraceChannel
|
||||||
|
/** 轮询类请求:只有失败或响应状态变化才落库。 */
|
||||||
|
isPolling?: (req: Request) => boolean
|
||||||
|
/** 不记录本次请求(例如返回 CK 的导出接口、历史查询自身)。 */
|
||||||
|
skip?: (req: Request) => boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
const TASK_ORDER_CACHE_LIMIT = 800
|
||||||
|
const taskOrderCache = new Map<number, string>()
|
||||||
|
|
||||||
|
/** 响应里代表「状态」的字段:轮询指纹只取这些,时间戳/计数变化不算状态变化。 */
|
||||||
|
const TRACE_STATE_KEYS = [
|
||||||
|
'status',
|
||||||
|
'state',
|
||||||
|
'loginStatus',
|
||||||
|
'bindingStatus',
|
||||||
|
'executionStatus',
|
||||||
|
'displayStatus',
|
||||||
|
'message',
|
||||||
|
'msg',
|
||||||
|
'code',
|
||||||
|
'errorCode',
|
||||||
|
'ok',
|
||||||
|
'challenge',
|
||||||
|
'ready',
|
||||||
|
'pending',
|
||||||
|
'type',
|
||||||
|
'rebindUnchanged',
|
||||||
|
'rebindRequested',
|
||||||
|
'rebindConfirmState',
|
||||||
|
'rebindConfirmMessage',
|
||||||
|
'rebindCooldownDays',
|
||||||
|
'nextRebindAt',
|
||||||
|
'bindConfirmState',
|
||||||
|
'bindConfirmMessage',
|
||||||
|
'bindEffectDeadlineMs',
|
||||||
|
'bindGameRole',
|
||||||
|
'bindGameRoleId',
|
||||||
|
'huyaUid',
|
||||||
|
'lastError',
|
||||||
|
'isBindAccount',
|
||||||
|
'isBindRole',
|
||||||
|
]
|
||||||
|
|
||||||
|
/** 客户请求体里的凭据类字段:短信验证码等一律不落库。 */
|
||||||
|
const INBOUND_SECRET_KEYS = new Set([
|
||||||
|
'code',
|
||||||
|
'smscode',
|
||||||
|
'sms_code',
|
||||||
|
'password',
|
||||||
|
'token',
|
||||||
|
'cookie',
|
||||||
|
'qrcode',
|
||||||
|
'qrcode_token',
|
||||||
|
'qrcodetoken',
|
||||||
|
'ticket',
|
||||||
|
'sig',
|
||||||
|
])
|
||||||
|
|
||||||
|
function normalizeKey(key: string): string {
|
||||||
|
return key.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase()
|
||||||
|
}
|
||||||
|
|
||||||
|
function createTraceRequestId(): string {
|
||||||
|
return `req_${Date.now().toString(36)}_${crypto.randomBytes(4).toString('hex')}`
|
||||||
|
}
|
||||||
|
|
||||||
|
async function resolveTaskOrderNo(taskId: number): Promise<string> {
|
||||||
|
const cached = taskOrderCache.get(taskId)
|
||||||
|
if (cached !== undefined) return cached
|
||||||
|
try {
|
||||||
|
const result = await query<{ platform_order_id: string | null }>(
|
||||||
|
`SELECT o.platform_order_id
|
||||||
|
FROM semi_auto_tasks task
|
||||||
|
JOIN orders o ON o.id = task.order_id
|
||||||
|
WHERE task.id = $1
|
||||||
|
LIMIT 1`,
|
||||||
|
[taskId],
|
||||||
|
)
|
||||||
|
const orderNo = String(result.rows[0]?.platform_order_id || '')
|
||||||
|
if (taskOrderCache.size >= TASK_ORDER_CACHE_LIMIT) taskOrderCache.clear()
|
||||||
|
taskOrderCache.set(taskId, orderNo)
|
||||||
|
return orderNo
|
||||||
|
} catch (error) {
|
||||||
|
logWarn('[semi-auto/trace]', '解析任务订单号失败,报文将不带订单号', {
|
||||||
|
taskId,
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
})
|
||||||
|
return ''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function maskInboundRequestBody(value: unknown, depth = 0): unknown {
|
||||||
|
if (depth > 4) return '[max-depth]'
|
||||||
|
if (value === null || value === undefined) return value
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
return value.slice(0, 50).map((item) => maskInboundRequestBody(item, depth + 1))
|
||||||
|
}
|
||||||
|
if (typeof value !== 'object') return value
|
||||||
|
const source = value as Record<string, unknown>
|
||||||
|
const masked: Record<string, unknown> = {}
|
||||||
|
for (const [key, current] of Object.entries(source)) {
|
||||||
|
masked[key] = INBOUND_SECRET_KEYS.has(normalizeKey(key))
|
||||||
|
? '******'
|
||||||
|
: maskInboundRequestBody(current, depth + 1)
|
||||||
|
}
|
||||||
|
return masked
|
||||||
|
}
|
||||||
|
|
||||||
|
function pickTraceState(value: unknown, depth = 0): unknown {
|
||||||
|
if (!value || typeof value !== 'object' || depth > 3) return value
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
return value.slice(0, 20).map((item) => pickTraceState(item, depth + 1))
|
||||||
|
}
|
||||||
|
const source = value as Record<string, unknown>
|
||||||
|
const picked: Record<string, unknown> = {}
|
||||||
|
for (const key of TRACE_STATE_KEYS) {
|
||||||
|
if (key in source && source[key] !== undefined) picked[key] = source[key]
|
||||||
|
}
|
||||||
|
// 常见响应外壳:{ task, login, binding }
|
||||||
|
for (const key of ['task', 'login', 'binding', 'result']) {
|
||||||
|
const nested = source[key]
|
||||||
|
if (nested && typeof nested === 'object' && !Array.isArray(nested)) {
|
||||||
|
picked[key] = pickTraceState(nested, depth + 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Object.keys(picked).length > 0 ? picked : value
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildPollingFingerprint(payload: unknown): string {
|
||||||
|
const body = payload && typeof payload === 'object' ? (payload as Record<string, unknown>) : {}
|
||||||
|
return traceFingerprint({
|
||||||
|
code: body.code,
|
||||||
|
msg: body.msg,
|
||||||
|
errorCode: body.errorCode,
|
||||||
|
data: pickTraceState(body.data),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createSemiAutoTaskTraceHandler(options: SemiAutoTaskTraceOptions) {
|
||||||
|
return (req: Request, res: Response, next: NextFunction, taskIdInput: string): void => {
|
||||||
|
const taskId = Number(taskIdInput)
|
||||||
|
if (!Number.isInteger(taskId) || taskId <= 0) {
|
||||||
|
next()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (options.skip?.(req)) {
|
||||||
|
next()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const pathOrderNo = String(req.params?.orderNo || '').trim()
|
||||||
|
const startedAt = Date.now()
|
||||||
|
const requestId = createTraceRequestId()
|
||||||
|
const polling = options.isPolling?.(req) === true
|
||||||
|
const actionPath = String(req.originalUrl || req.url || '').split('?')[0]
|
||||||
|
const action = `${String(req.method || 'GET').toUpperCase()} ${actionPath}`
|
||||||
|
const requestSummary = {
|
||||||
|
method: req.method,
|
||||||
|
path: actionPath,
|
||||||
|
query: req.query || {},
|
||||||
|
ip: req.ip || '',
|
||||||
|
}
|
||||||
|
const requestBody =
|
||||||
|
req.body && typeof req.body === 'object' && Object.keys(req.body as object).length > 0
|
||||||
|
? maskInboundRequestBody(req.body)
|
||||||
|
: ''
|
||||||
|
let recorded = false
|
||||||
|
|
||||||
|
const record = (payload: unknown) => {
|
||||||
|
if (recorded) return
|
||||||
|
recorded = true
|
||||||
|
try {
|
||||||
|
const body =
|
||||||
|
payload && typeof payload === 'object' ? (payload as Record<string, unknown>) : {}
|
||||||
|
const code = Number(body.code)
|
||||||
|
const httpStatus = Number(res.statusCode || 200)
|
||||||
|
const failed = Number.isFinite(code) ? code !== 0 : httpStatus >= 400
|
||||||
|
const status = failed || httpStatus >= 400 ? 'error' : 'ok'
|
||||||
|
recordSemiAutoTrace({
|
||||||
|
taskId,
|
||||||
|
orderNo: pathOrderNo,
|
||||||
|
requestId,
|
||||||
|
direction: 'inbound',
|
||||||
|
channel: options.channel,
|
||||||
|
action,
|
||||||
|
status,
|
||||||
|
httpStatus,
|
||||||
|
durationMs: Date.now() - startedAt,
|
||||||
|
requestSummary,
|
||||||
|
requestBody,
|
||||||
|
responseSummary: {
|
||||||
|
code: body.code ?? null,
|
||||||
|
msg: body.msg ?? '',
|
||||||
|
errorCode: body.errorCode ?? '',
|
||||||
|
},
|
||||||
|
responseBody: payload,
|
||||||
|
errorMessage: status === 'error' ? String(body.msg || '') : '',
|
||||||
|
always: !polling,
|
||||||
|
fingerprint: polling ? buildPollingFingerprint(payload) : undefined,
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
logWarn('[semi-auto/trace]', '记录入站报文失败,已跳过', {
|
||||||
|
taskId,
|
||||||
|
action,
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const originalJson = res.json.bind(res)
|
||||||
|
res.json = ((payload: unknown) => {
|
||||||
|
record(payload)
|
||||||
|
return originalJson(payload as never)
|
||||||
|
}) as Response['json']
|
||||||
|
|
||||||
|
const start = (orderNo: string) => {
|
||||||
|
runWithSemiAutoTrace({ requestId, taskId, orderNo, source: options.channel }, () => next())
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pathOrderNo) {
|
||||||
|
start(pathOrderNo)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
void resolveTaskOrderNo(taskId).then(start, () => start(''))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,15 +8,27 @@ import {
|
|||||||
createAdminBrowserSession,
|
createAdminBrowserSession,
|
||||||
exportAdminSemiAutoCredential,
|
exportAdminSemiAutoCredential,
|
||||||
getAdminSemiAutoTask,
|
getAdminSemiAutoTask,
|
||||||
|
getAdminSemiAutoTaskHistory,
|
||||||
listAdminSemiAutoTasks,
|
listAdminSemiAutoTasks,
|
||||||
requestAdminSemiAutoCustomerReauth,
|
requestAdminSemiAutoCustomerReauth,
|
||||||
syncAdminSemiAutoTask,
|
syncAdminSemiAutoTask,
|
||||||
} from '../../services/semi-auto/semi-auto-task-service.js'
|
} from '../../services/semi-auto/semi-auto-task-service.js'
|
||||||
|
import { createSemiAutoTaskTraceHandler } from '../../middleware/semi-auto-trace.js'
|
||||||
import { bodyOf, sessionOf } from './request-helpers.js'
|
import { bodyOf, sessionOf } from './request-helpers.js'
|
||||||
import { createJsonHandler, requireAdminRoles } from './session.js'
|
import { createJsonHandler, requireAdminRoles } from './session.js'
|
||||||
|
|
||||||
const router = Router()
|
const router = Router()
|
||||||
|
|
||||||
|
// 运营端每次操作都会记录入站报文;详情每 3 秒刷新一次,GET 只在状态变化时落库。
|
||||||
|
router.param(
|
||||||
|
'taskId',
|
||||||
|
createSemiAutoTaskTraceHandler({
|
||||||
|
channel: 'admin_api',
|
||||||
|
isPolling: (req) => req.method === 'GET',
|
||||||
|
skip: (req) => req.path.endsWith('/history') || req.path.endsWith('/credential/export'),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
router.use('/semi-auto', requireAdminRoles(['admin', 'operator', 'support']))
|
router.use('/semi-auto', requireAdminRoles(['admin', 'operator', 'support']))
|
||||||
|
|
||||||
router.get(
|
router.get(
|
||||||
@@ -37,6 +49,18 @@ router.get(
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
router.get(
|
||||||
|
'/semi-auto/tasks/:taskId/history',
|
||||||
|
createJsonHandler(
|
||||||
|
(req) => getAdminSemiAutoTaskHistory(req.params.taskId, req.query as Record<string, unknown>),
|
||||||
|
{
|
||||||
|
successMessage: 'ok',
|
||||||
|
errorMessage: '读取半自动履约历史失败',
|
||||||
|
scope: '[admin/semi-auto/tasks/:taskId/history]',
|
||||||
|
},
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
router.post(
|
router.post(
|
||||||
'/semi-auto/tasks/:taskId/credential/export',
|
'/semi-auto/tasks/:taskId/credential/export',
|
||||||
createJsonHandler(
|
createJsonHandler(
|
||||||
|
|||||||
@@ -19,11 +19,21 @@ import {
|
|||||||
submitPublicRebind,
|
submitPublicRebind,
|
||||||
verifyPublicHuyaSmsChallenge,
|
verifyPublicHuyaSmsChallenge,
|
||||||
} from '../services/semi-auto/semi-auto-task-service.js'
|
} from '../services/semi-auto/semi-auto-task-service.js'
|
||||||
|
import { createSemiAutoTaskTraceHandler } from '../middleware/semi-auto-trace.js'
|
||||||
import { createRateLimitMiddleware, getParamRateLimitKey } from '../middleware/rate-limit.js'
|
import { createRateLimitMiddleware, getParamRateLimitKey } from '../middleware/rate-limit.js'
|
||||||
import { createRouteHandler } from '../utils/http.js'
|
import { createRouteHandler } from '../utils/http.js'
|
||||||
|
|
||||||
const router = Router()
|
const router = Router()
|
||||||
|
|
||||||
|
// 客户侧每次操作都会记录入站报文;2 秒一次的 /status 轮询只在状态变化或失败时落库。
|
||||||
|
router.param(
|
||||||
|
'taskId',
|
||||||
|
createSemiAutoTaskTraceHandler({
|
||||||
|
channel: 'customer_api',
|
||||||
|
isPolling: (req) => req.path.endsWith('/status'),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
const readLimit = createRateLimitMiddleware({
|
const readLimit = createRateLimitMiddleware({
|
||||||
scope: 'customer-fulfillment:read',
|
scope: 'customer-fulfillment:read',
|
||||||
windowMs: 60_000,
|
windowMs: 60_000,
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import {
|
|||||||
huyaNativeConnector,
|
huyaNativeConnector,
|
||||||
type HuyaStoredCredential,
|
type HuyaStoredCredential,
|
||||||
} from './huya-native/huya-native-connector.js'
|
} from './huya-native/huya-native-connector.js'
|
||||||
|
import { recordSemiAutoTrace, traceFingerprint } from './semi-auto-trace.js'
|
||||||
|
|
||||||
export type ConnectorLoginSession = {
|
export type ConnectorLoginSession = {
|
||||||
sessionId: string
|
sessionId: string
|
||||||
@@ -204,9 +205,11 @@ async function callConnector<T>(
|
|||||||
const timeoutMs = Math.max(1000, Number(runtimeConfig.semiAuto?.connectorTimeoutMs || 15_000))
|
const timeoutMs = Math.max(1000, Number(runtimeConfig.semiAuto?.connectorTimeoutMs || 15_000))
|
||||||
const controller = new AbortController()
|
const controller = new AbortController()
|
||||||
const timer = setTimeout(() => controller.abort(), timeoutMs)
|
const timer = setTimeout(() => controller.abort(), timeoutMs)
|
||||||
|
const method = String(options.method || 'GET').toUpperCase()
|
||||||
|
const startedAt = Date.now()
|
||||||
try {
|
try {
|
||||||
const requestInit: RequestInit = {
|
const requestInit: RequestInit = {
|
||||||
method: options.method || 'GET',
|
method,
|
||||||
headers: {
|
headers: {
|
||||||
Accept: 'application/json',
|
Accept: 'application/json',
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
@@ -223,6 +226,20 @@ async function callConnector<T>(
|
|||||||
} catch {
|
} catch {
|
||||||
payload = null
|
payload = null
|
||||||
}
|
}
|
||||||
|
recordSemiAutoTrace({
|
||||||
|
direction: 'outbound',
|
||||||
|
channel: 'external_connector',
|
||||||
|
action: `${method} ${path}`,
|
||||||
|
status: response.ok ? 'ok' : 'error',
|
||||||
|
httpStatus: response.status,
|
||||||
|
durationMs: Date.now() - startedAt,
|
||||||
|
requestSummary: { baseUrl: endpoint.baseUrl },
|
||||||
|
requestBody: options.body,
|
||||||
|
responseSummary: { bodyBytes: text.length },
|
||||||
|
responseBody: payload ?? text,
|
||||||
|
always: method !== 'GET',
|
||||||
|
fingerprint: method === 'GET' ? traceFingerprint(payload) : undefined,
|
||||||
|
})
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const detail =
|
const detail =
|
||||||
payload && typeof payload === 'object'
|
payload && typeof payload === 'object'
|
||||||
@@ -235,6 +252,19 @@ async function callConnector<T>(
|
|||||||
}
|
}
|
||||||
return payload as T
|
return payload as T
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
if (!(error && typeof error === 'object' && 'statusCode' in error)) {
|
||||||
|
recordSemiAutoTrace({
|
||||||
|
direction: 'outbound',
|
||||||
|
channel: 'external_connector',
|
||||||
|
action: `${method} ${path}`,
|
||||||
|
status: 'error',
|
||||||
|
durationMs: Date.now() - startedAt,
|
||||||
|
requestSummary: { baseUrl: endpoint.baseUrl },
|
||||||
|
requestBody: options.body,
|
||||||
|
always: true,
|
||||||
|
errorMessage: error instanceof Error ? error.message : String(error),
|
||||||
|
})
|
||||||
|
}
|
||||||
if (error && typeof error === 'object' && 'statusCode' in error) throw error
|
if (error && typeof error === 'object' && 'statusCode' in error) throw error
|
||||||
if (error instanceof Error && error.name === 'AbortError') {
|
if (error instanceof Error && error.name === 'AbortError') {
|
||||||
throw createHttpError('半自动履约 Connector 请求超时', {
|
throw createHttpError('半自动履约 Connector 请求超时', {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
import crypto from 'node:crypto'
|
import crypto from 'node:crypto'
|
||||||
|
|
||||||
|
import { recordSemiAutoTrace, traceFingerprint } from '../semi-auto-trace.js'
|
||||||
import { buildHuyaLoginContext, cookiePairs, cookieValue, normalizeCookiePairs } from './cookie.js'
|
import { buildHuyaLoginContext, cookiePairs, cookieValue, normalizeCookiePairs } from './cookie.js'
|
||||||
import {
|
import {
|
||||||
decodeWupResponse,
|
decodeWupResponse,
|
||||||
@@ -494,22 +495,67 @@ export class HuyaRpcClient {
|
|||||||
gid?: number
|
gid?: number
|
||||||
scene?: string
|
scene?: string
|
||||||
}): Promise<HuyaBindResponse | null> {
|
}): Promise<HuyaBindResponse | null> {
|
||||||
const response = await this.callRpc(
|
const startedAt = Date.now()
|
||||||
'webActUI',
|
const request = {
|
||||||
'checkUserBindGameAccount',
|
servant: 'webActUI',
|
||||||
input.uid,
|
func: 'checkUserBindGameAccount',
|
||||||
input.cookie,
|
uid: input.uid,
|
||||||
(writer) => {
|
gid: input.gid || 0,
|
||||||
this.writeActivityUser(writer, input.uid, input.cookie)
|
outerActId: input.outerActId || '',
|
||||||
writer.writeInt32(1, input.gid || 0)
|
bindActId: input.bindActId || 0,
|
||||||
writer.writeString(2, input.outerActId || '')
|
isUseOuterActId: input.isUseOuterActId ?? 1,
|
||||||
writer.writeInt32(3, 0)
|
scene: input.scene || '',
|
||||||
writer.writeString(4, input.scene || '')
|
}
|
||||||
writer.writeInt32(5, input.bindActId || 0)
|
try {
|
||||||
writer.writeInt32(6, input.isUseOuterActId ?? 1)
|
const response = await this.callRpc(
|
||||||
},
|
'webActUI',
|
||||||
)
|
'checkUserBindGameAccount',
|
||||||
return response ? readWupStruct(response, parseBindResponse) : null
|
input.uid,
|
||||||
|
input.cookie,
|
||||||
|
(writer) => {
|
||||||
|
this.writeActivityUser(writer, input.uid, input.cookie)
|
||||||
|
writer.writeInt32(1, input.gid || 0)
|
||||||
|
writer.writeString(2, input.outerActId || '')
|
||||||
|
writer.writeInt32(3, 0)
|
||||||
|
writer.writeString(4, input.scene || '')
|
||||||
|
writer.writeInt32(5, input.bindActId || 0)
|
||||||
|
writer.writeInt32(6, input.isUseOuterActId ?? 1)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
const parsed = response ? readWupStruct(response, parseBindResponse) : null
|
||||||
|
recordSemiAutoTrace({
|
||||||
|
direction: 'outbound',
|
||||||
|
channel: 'huya_wup',
|
||||||
|
action: 'webActUI.checkUserBindGameAccount',
|
||||||
|
status: parsed && parsed.status === 200 ? 'ok' : 'error',
|
||||||
|
durationMs: Date.now() - startedAt,
|
||||||
|
requestSummary: request,
|
||||||
|
responseSummary: { status: parsed?.status, msg: parsed?.msg },
|
||||||
|
responseBody: parsed,
|
||||||
|
// 绑定轮询:状态没变化就不落库。
|
||||||
|
fingerprint: traceFingerprint({
|
||||||
|
status: parsed?.status,
|
||||||
|
msg: parsed?.msg,
|
||||||
|
isBindAccount: parsed?.accountData?.isBindAccount,
|
||||||
|
isBindRole: parsed?.accountData?.isBindRole,
|
||||||
|
role: parsed?.accountData?.gameRole?.roleName,
|
||||||
|
roleId: parsed?.accountData?.gameRole?.roleId,
|
||||||
|
}),
|
||||||
|
errorMessage: parsed && parsed.status !== 200 ? String(parsed.msg || '') : '',
|
||||||
|
})
|
||||||
|
return parsed
|
||||||
|
} catch (error) {
|
||||||
|
recordSemiAutoTrace({
|
||||||
|
direction: 'outbound',
|
||||||
|
channel: 'huya_wup',
|
||||||
|
action: 'webActUI.checkUserBindGameAccount',
|
||||||
|
status: 'error',
|
||||||
|
durationMs: Date.now() - startedAt,
|
||||||
|
requestSummary: request,
|
||||||
|
errorMessage: error instanceof Error ? error.message : String(error),
|
||||||
|
})
|
||||||
|
throw error
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async confirmBindActAccount(input: {
|
async confirmBindActAccount(input: {
|
||||||
@@ -519,19 +565,55 @@ export class HuyaRpcClient {
|
|||||||
outerActId: string
|
outerActId: string
|
||||||
gid?: number
|
gid?: number
|
||||||
}): Promise<HuyaConfirmResponse | null> {
|
}): Promise<HuyaConfirmResponse | null> {
|
||||||
const response = await this.callRpc(
|
const startedAt = Date.now()
|
||||||
'webActUI',
|
const request = {
|
||||||
'confirmBindActAccount',
|
servant: 'webActUI',
|
||||||
input.uid,
|
func: 'confirmBindActAccount',
|
||||||
input.cookie,
|
uid: input.uid,
|
||||||
(writer) => {
|
gid: input.gid || 0,
|
||||||
this.writeActivityUser(writer, input.uid, input.cookie)
|
outerActId: input.outerActId || '',
|
||||||
writer.writeInt32(1, input.gid || 0)
|
bindActId: input.bindActId || 0,
|
||||||
writer.writeString(2, input.outerActId || '')
|
}
|
||||||
writer.writeInt32(3, input.bindActId || 0)
|
try {
|
||||||
},
|
const response = await this.callRpc(
|
||||||
)
|
'webActUI',
|
||||||
return response ? readWupStruct(response, parseConfirmResponse) : null
|
'confirmBindActAccount',
|
||||||
|
input.uid,
|
||||||
|
input.cookie,
|
||||||
|
(writer) => {
|
||||||
|
this.writeActivityUser(writer, input.uid, input.cookie)
|
||||||
|
writer.writeInt32(1, input.gid || 0)
|
||||||
|
writer.writeString(2, input.outerActId || '')
|
||||||
|
writer.writeInt32(3, input.bindActId || 0)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
const parsed = response ? readWupStruct(response, parseConfirmResponse) : null
|
||||||
|
recordSemiAutoTrace({
|
||||||
|
direction: 'outbound',
|
||||||
|
channel: 'huya_wup',
|
||||||
|
action: 'webActUI.confirmBindActAccount',
|
||||||
|
status: parsed && parsed.status === 200 ? 'ok' : 'error',
|
||||||
|
durationMs: Date.now() - startedAt,
|
||||||
|
requestSummary: request,
|
||||||
|
responseSummary: { status: parsed?.status, msg: parsed?.msg },
|
||||||
|
responseBody: parsed,
|
||||||
|
always: true,
|
||||||
|
errorMessage: parsed && parsed.status !== 200 ? String(parsed.msg || '') : '',
|
||||||
|
})
|
||||||
|
return parsed
|
||||||
|
} catch (error) {
|
||||||
|
recordSemiAutoTrace({
|
||||||
|
direction: 'outbound',
|
||||||
|
channel: 'huya_wup',
|
||||||
|
action: 'webActUI.confirmBindActAccount',
|
||||||
|
status: 'error',
|
||||||
|
durationMs: Date.now() - startedAt,
|
||||||
|
requestSummary: request,
|
||||||
|
always: true,
|
||||||
|
errorMessage: error instanceof Error ? error.message : String(error),
|
||||||
|
})
|
||||||
|
throw error
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async getLiveLinkParam(input: {
|
async getLiveLinkParam(input: {
|
||||||
@@ -541,21 +623,57 @@ export class HuyaRpcClient {
|
|||||||
outerActId: number
|
outerActId: number
|
||||||
gameAuthScene?: string
|
gameAuthScene?: string
|
||||||
}): Promise<HuyaLiveLinkResponse | null> {
|
}): Promise<HuyaLiveLinkResponse | null> {
|
||||||
const response = await this.callRpc(
|
const startedAt = Date.now()
|
||||||
'webActUI',
|
const request = {
|
||||||
'getLiveLinkParam',
|
servant: 'webActUI',
|
||||||
input.uid,
|
func: 'getLiveLinkParam',
|
||||||
input.cookie,
|
uid: input.uid,
|
||||||
(writer) => {
|
bindActId: input.bindActId || 0,
|
||||||
this.writeActivityUser(writer, input.uid, input.cookie)
|
outerActId: input.outerActId || 0,
|
||||||
writer.writeInt32(1, 0)
|
gameAuthScene: input.gameAuthScene || '',
|
||||||
writer.writeInt32(2, input.outerActId || 0)
|
}
|
||||||
writer.writeString(3, input.gameAuthScene || '')
|
try {
|
||||||
writer.writeString(4, '')
|
const response = await this.callRpc(
|
||||||
writer.writeInt32(5, input.bindActId || 0)
|
'webActUI',
|
||||||
},
|
'getLiveLinkParam',
|
||||||
)
|
input.uid,
|
||||||
return response ? readWupStruct(response, parseLiveLinkResponse) : null
|
input.cookie,
|
||||||
|
(writer) => {
|
||||||
|
this.writeActivityUser(writer, input.uid, input.cookie)
|
||||||
|
writer.writeInt32(1, 0)
|
||||||
|
writer.writeInt32(2, input.outerActId || 0)
|
||||||
|
writer.writeString(3, input.gameAuthScene || '')
|
||||||
|
writer.writeString(4, '')
|
||||||
|
writer.writeInt32(5, input.bindActId || 0)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
const parsed = response ? readWupStruct(response, parseLiveLinkResponse) : null
|
||||||
|
recordSemiAutoTrace({
|
||||||
|
direction: 'outbound',
|
||||||
|
channel: 'huya_wup',
|
||||||
|
action: 'webActUI.getLiveLinkParam',
|
||||||
|
status: parsed && parsed.status === 200 ? 'ok' : 'error',
|
||||||
|
durationMs: Date.now() - startedAt,
|
||||||
|
requestSummary: request,
|
||||||
|
responseSummary: { status: parsed?.status, msg: parsed?.msg },
|
||||||
|
responseBody: parsed,
|
||||||
|
always: true,
|
||||||
|
errorMessage: parsed && parsed.status !== 200 ? String(parsed.msg || '') : '',
|
||||||
|
})
|
||||||
|
return parsed
|
||||||
|
} catch (error) {
|
||||||
|
recordSemiAutoTrace({
|
||||||
|
direction: 'outbound',
|
||||||
|
channel: 'huya_wup',
|
||||||
|
action: 'webActUI.getLiveLinkParam',
|
||||||
|
status: 'error',
|
||||||
|
durationMs: Date.now() - startedAt,
|
||||||
|
requestSummary: request,
|
||||||
|
always: true,
|
||||||
|
errorMessage: error instanceof Error ? error.message : String(error),
|
||||||
|
})
|
||||||
|
throw error
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async getUserProfileBatch(input: {
|
async getUserProfileBatch(input: {
|
||||||
@@ -585,17 +703,53 @@ export class HuyaRpcClient {
|
|||||||
}): Promise<HuyaUserProfile | null> {
|
}): Promise<HuyaUserProfile | null> {
|
||||||
const targetUid = Math.trunc(input.targetUid)
|
const targetUid = Math.trunc(input.targetUid)
|
||||||
if (!(targetUid > 0)) return null
|
if (!(targetUid > 0)) return null
|
||||||
const response = await this.callRpc(
|
const startedAt = Date.now()
|
||||||
'huyauserui',
|
try {
|
||||||
'getUserProfile',
|
const response = await this.callRpc(
|
||||||
input.uid,
|
'huyauserui',
|
||||||
input.cookie,
|
'getUserProfile',
|
||||||
(writer) => {
|
input.uid,
|
||||||
this.writeActivityUser(writer, 0, input.cookie)
|
input.cookie,
|
||||||
writer.writeInt64(1, targetUid)
|
(writer) => {
|
||||||
},
|
this.writeActivityUser(writer, 0, input.cookie)
|
||||||
)
|
writer.writeInt64(1, targetUid)
|
||||||
return response ? readWupStruct(response, parseProfileResponse) : null
|
},
|
||||||
|
)
|
||||||
|
const parsed = response ? readWupStruct(response, parseProfileResponse) : null
|
||||||
|
recordSemiAutoTrace({
|
||||||
|
direction: 'outbound',
|
||||||
|
channel: 'huya_wup',
|
||||||
|
action: 'huyauserui.getUserProfile',
|
||||||
|
status: parsed ? 'ok' : 'error',
|
||||||
|
durationMs: Date.now() - startedAt,
|
||||||
|
requestSummary: {
|
||||||
|
servant: 'huyauserui',
|
||||||
|
func: 'getUserProfile',
|
||||||
|
uid: input.uid,
|
||||||
|
targetUid,
|
||||||
|
},
|
||||||
|
responseBody: parsed,
|
||||||
|
always: true,
|
||||||
|
})
|
||||||
|
return parsed
|
||||||
|
} catch (error) {
|
||||||
|
recordSemiAutoTrace({
|
||||||
|
direction: 'outbound',
|
||||||
|
channel: 'huya_wup',
|
||||||
|
action: 'huyauserui.getUserProfile',
|
||||||
|
status: 'error',
|
||||||
|
durationMs: Date.now() - startedAt,
|
||||||
|
requestSummary: {
|
||||||
|
servant: 'huyauserui',
|
||||||
|
func: 'getUserProfile',
|
||||||
|
uid: input.uid,
|
||||||
|
targetUid,
|
||||||
|
},
|
||||||
|
always: true,
|
||||||
|
errorMessage: error instanceof Error ? error.message : String(error),
|
||||||
|
})
|
||||||
|
throw error
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async callRpc(
|
private async callRpc(
|
||||||
@@ -715,6 +869,7 @@ export async function getLiveLinkMiniQrcode(
|
|||||||
).join('')
|
).join('')
|
||||||
const sessionId = `${Math.floor(Date.now() / 1000)}_${suffix}`
|
const sessionId = `${Math.floor(Date.now() / 1000)}_${suffix}`
|
||||||
const fetchImpl = options.fetchImpl || fetch
|
const fetchImpl = options.fetchImpl || fetch
|
||||||
|
const startedAt = Date.now()
|
||||||
const response = await fetchImpl(`${LIVELINK_BIND_API_BASE}/api/qrcode/getMiniAppQrcode`, {
|
const response = await fetchImpl(`${LIVELINK_BIND_API_BASE}/api/qrcode/getMiniAppQrcode`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
@@ -728,14 +883,41 @@ export async function getLiveLinkMiniQrcode(
|
|||||||
body: JSON.stringify({ queryString: `${query}&sessionId=${sessionId}` }),
|
body: JSON.stringify({ queryString: `${query}&sessionId=${sessionId}` }),
|
||||||
signal: AbortSignal.timeout(options.timeoutMs || 15_000),
|
signal: AbortSignal.timeout(options.timeoutMs || 15_000),
|
||||||
})
|
})
|
||||||
if (!response.ok) return null
|
const traceMiniQrcode = (status: 'ok' | 'error', extra: Record<string, unknown> = {}) => {
|
||||||
|
recordSemiAutoTrace({
|
||||||
|
direction: 'outbound',
|
||||||
|
channel: 'huya_http',
|
||||||
|
action: 'livelink.getMiniAppQrcode',
|
||||||
|
status,
|
||||||
|
durationMs: Date.now() - startedAt,
|
||||||
|
httpStatus: response.status,
|
||||||
|
requestSummary: { api: 'getMiniAppQrcode', queryLength: query.length },
|
||||||
|
responseSummary: extra,
|
||||||
|
always: true,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (!response.ok) {
|
||||||
|
traceMiniQrcode('error', { httpStatus: response.status })
|
||||||
|
return null
|
||||||
|
}
|
||||||
const payload = (await response.json().catch(() => null)) as {
|
const payload = (await response.json().catch(() => null)) as {
|
||||||
iRet?: number
|
iRet?: number
|
||||||
jData?: { qrcode?: string; qrcodeToken?: string }
|
jData?: { qrcode?: string; qrcodeToken?: string }
|
||||||
} | null
|
} | null
|
||||||
if (!payload || payload.iRet !== 0) return null
|
if (!payload || payload.iRet !== 0) {
|
||||||
|
traceMiniQrcode('error', { iRet: payload?.iRet ?? null })
|
||||||
|
return null
|
||||||
|
}
|
||||||
const image = livelinkQrcodeImageSrc(String(payload.jData?.qrcode || ''))
|
const image = livelinkQrcodeImageSrc(String(payload.jData?.qrcode || ''))
|
||||||
if (!image) return null
|
if (!image) {
|
||||||
|
traceMiniQrcode('error', { iRet: payload.iRet, hasImage: false })
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
traceMiniQrcode('ok', {
|
||||||
|
iRet: payload.iRet,
|
||||||
|
hasImage: true,
|
||||||
|
tokenLength: String(payload.jData?.qrcodeToken || '').length,
|
||||||
|
})
|
||||||
return { image, token: String(payload.jData?.qrcodeToken || '') }
|
return { image, token: String(payload.jData?.qrcodeToken || '') }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -751,6 +933,7 @@ export async function getLiveLinkQrcodeStatus(
|
|||||||
const normalized = String(token || '').trim()
|
const normalized = String(token || '').trim()
|
||||||
if (!normalized) return null
|
if (!normalized) return null
|
||||||
const fetchImpl = options.fetchImpl || fetch
|
const fetchImpl = options.fetchImpl || fetch
|
||||||
|
const startedAt = Date.now()
|
||||||
const response = await fetchImpl(`${LIVELINK_BIND_API_BASE}/api/qrcode/poolingQrcodeStatus`, {
|
const response = await fetchImpl(`${LIVELINK_BIND_API_BASE}/api/qrcode/poolingQrcodeStatus`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
@@ -764,7 +947,24 @@ export async function getLiveLinkQrcodeStatus(
|
|||||||
body: JSON.stringify({ qrcodeToken: normalized }),
|
body: JSON.stringify({ qrcodeToken: normalized }),
|
||||||
signal: AbortSignal.timeout(options.timeoutMs || 15_000),
|
signal: AbortSignal.timeout(options.timeoutMs || 15_000),
|
||||||
})
|
})
|
||||||
if (!response.ok) return null
|
const traceQrcodeStatus = (status: 'ok' | 'error', extra: Record<string, unknown> = {}) => {
|
||||||
|
recordSemiAutoTrace({
|
||||||
|
direction: 'outbound',
|
||||||
|
channel: 'huya_http',
|
||||||
|
action: 'livelink.poolingQrcodeStatus',
|
||||||
|
status,
|
||||||
|
durationMs: Date.now() - startedAt,
|
||||||
|
httpStatus: response.status,
|
||||||
|
requestSummary: { api: 'poolingQrcodeStatus', tokenLength: normalized.length },
|
||||||
|
responseSummary: extra,
|
||||||
|
// 二维码轮询:状态没变化就不落库。
|
||||||
|
fingerprint: traceFingerprint(extra),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (!response.ok) {
|
||||||
|
traceQrcodeStatus('error', { httpStatus: response.status })
|
||||||
|
return null
|
||||||
|
}
|
||||||
const payload = (await response.json().catch(() => null)) as {
|
const payload = (await response.json().catch(() => null)) as {
|
||||||
iRet?: number
|
iRet?: number
|
||||||
jData?: {
|
jData?: {
|
||||||
@@ -774,13 +974,18 @@ export async function getLiveLinkQrcodeStatus(
|
|||||||
isFailure?: boolean
|
isFailure?: boolean
|
||||||
}
|
}
|
||||||
} | null
|
} | null
|
||||||
if (!payload || payload.iRet !== 0) return null
|
if (!payload || payload.iRet !== 0) {
|
||||||
return {
|
traceQrcodeStatus('error', { iRet: payload?.iRet ?? null })
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
const result = {
|
||||||
isScan: Boolean(payload.jData?.isScan),
|
isScan: Boolean(payload.jData?.isScan),
|
||||||
isExpired: Boolean(payload.jData?.isExpired),
|
isExpired: Boolean(payload.jData?.isExpired),
|
||||||
isCompleted: Boolean(payload.jData?.isCompleted),
|
isCompleted: Boolean(payload.jData?.isCompleted),
|
||||||
isFailure: Boolean(payload.jData?.isFailure),
|
isFailure: Boolean(payload.jData?.isFailure),
|
||||||
}
|
}
|
||||||
|
traceQrcodeStatus('ok', { iRet: payload.iRet, ...result })
|
||||||
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
export function buildBindUrls(input: {
|
export function buildBindUrls(input: {
|
||||||
|
|||||||
@@ -55,6 +55,7 @@ import {
|
|||||||
markSemiAutoCredentialCheck,
|
markSemiAutoCredentialCheck,
|
||||||
upsertSemiAutoCredentialWithClient,
|
upsertSemiAutoCredentialWithClient,
|
||||||
} from './semi-auto-credential-service.js'
|
} from './semi-auto-credential-service.js'
|
||||||
|
import { querySemiAutoTraces } from './semi-auto-trace.js'
|
||||||
|
|
||||||
const SEMI_AUTO_PLATFORMS = new Set(['huya', 'weibo'])
|
const SEMI_AUTO_PLATFORMS = new Set(['huya', 'weibo'])
|
||||||
type SemiAutoPlatform = 'huya' | 'weibo'
|
type SemiAutoPlatform = 'huya' | 'weibo'
|
||||||
@@ -920,19 +921,22 @@ async function updateLoginTask(
|
|||||||
credentialId,
|
credentialId,
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
await appendTaskEvent(client, task.id, {
|
// 轮询会每 2 秒调用一次:状态与执行状态都没变时不写事件,避免时间线被重复项淹没。
|
||||||
eventType: 'login_status_changed',
|
if (mapped.status !== task.login_status || nextExecutionStatus !== task.execution_status) {
|
||||||
actorType,
|
await appendTaskEvent(client, task.id, {
|
||||||
fromLoginStatus: task.login_status,
|
eventType: 'login_status_changed',
|
||||||
toLoginStatus: mapped.status,
|
actorType,
|
||||||
fromExecutionStatus: task.execution_status,
|
fromLoginStatus: task.login_status,
|
||||||
toExecutionStatus: nextExecutionStatus,
|
toLoginStatus: mapped.status,
|
||||||
detail: {
|
fromExecutionStatus: task.execution_status,
|
||||||
hasCredential: mapped.hasCredential,
|
toExecutionStatus: nextExecutionStatus,
|
||||||
message: mapped.message,
|
detail: {
|
||||||
method: options.method || 'qr',
|
hasCredential: mapped.hasCredential,
|
||||||
},
|
message: mapped.message,
|
||||||
})
|
method: options.method || 'qr',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1130,32 +1134,40 @@ async function updateBindingTask(
|
|||||||
mapped.bindGameRoleId,
|
mapped.bindGameRoleId,
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
await appendTaskEvent(client, task.id, {
|
// 轮询会每 2 秒调用一次:只有状态/执行状态变化,或换绑被拒这类关键信号才写事件。
|
||||||
eventType: 'binding_status_changed',
|
const bindingChanged =
|
||||||
actorType,
|
mapped.status !== task.binding_status ||
|
||||||
fromBindingStatus: task.binding_status,
|
executionStatus !== task.execution_status ||
|
||||||
toBindingStatus: mapped.status,
|
mapped.rebindUnchanged ||
|
||||||
fromExecutionStatus: task.execution_status,
|
mapped.rebindConfirmState === 'rejected'
|
||||||
toExecutionStatus: executionStatus,
|
if (bindingChanged) {
|
||||||
detail: {
|
await appendTaskEvent(client, task.id, {
|
||||||
gameAccount: mapped.bindGameAccount,
|
eventType: 'binding_status_changed',
|
||||||
gameRole: mapped.bindGameRole,
|
actorType,
|
||||||
gameRoleId: mapped.bindGameRoleId,
|
fromBindingStatus: task.binding_status,
|
||||||
gameChannel: mapped.bindGameChannel,
|
toBindingStatus: mapped.status,
|
||||||
verdict: comparison.verdict,
|
fromExecutionStatus: task.execution_status,
|
||||||
rebindRequested: mapped.rebindRequested,
|
toExecutionStatus: executionStatus,
|
||||||
rebindUnchanged: mapped.rebindUnchanged,
|
detail: {
|
||||||
rebindConfirmState: mapped.rebindConfirmState,
|
gameAccount: mapped.bindGameAccount,
|
||||||
rebindConfirmMessage: mapped.rebindConfirmMessage,
|
gameRole: mapped.bindGameRole,
|
||||||
bindConfirmState: mapped.bindConfirmState,
|
gameRoleId: mapped.bindGameRoleId,
|
||||||
bindConfirmMessage: mapped.bindConfirmMessage,
|
gameChannel: mapped.bindGameChannel,
|
||||||
rebindCooldownDays: mapped.rebindCooldownDays,
|
verdict: comparison.verdict,
|
||||||
nextRebindAt: mapped.nextRebindAt,
|
rebindRequested: mapped.rebindRequested,
|
||||||
changeBindDay: mapped.platformChangeBindDay,
|
rebindUnchanged: mapped.rebindUnchanged,
|
||||||
changeBindTime: mapped.platformChangeBindTime,
|
rebindConfirmState: mapped.rebindConfirmState,
|
||||||
message: mapped.message,
|
rebindConfirmMessage: mapped.rebindConfirmMessage,
|
||||||
},
|
bindConfirmState: mapped.bindConfirmState,
|
||||||
})
|
bindConfirmMessage: mapped.bindConfirmMessage,
|
||||||
|
rebindCooldownDays: mapped.rebindCooldownDays,
|
||||||
|
nextRebindAt: mapped.nextRebindAt,
|
||||||
|
changeBindDay: mapped.platformChangeBindDay,
|
||||||
|
changeBindTime: mapped.platformChangeBindTime,
|
||||||
|
message: mapped.message,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
})
|
})
|
||||||
return {
|
return {
|
||||||
status: mapped.status,
|
status: mapped.status,
|
||||||
@@ -1916,6 +1928,78 @@ export async function getAdminSemiAutoTask(taskIdInput: unknown) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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) {
|
export async function exportAdminSemiAutoCredential(taskIdInput: unknown) {
|
||||||
const task = await loadTask(normalizeId(taskIdInput))
|
const task = await loadTask(normalizeId(taskIdInput))
|
||||||
if (!task.credential_id) {
|
if (!task.credential_id) {
|
||||||
|
|||||||
@@ -0,0 +1,326 @@
|
|||||||
|
import { AsyncLocalStorage } from 'node:async_hooks'
|
||||||
|
import crypto from 'node:crypto'
|
||||||
|
|
||||||
|
import { query } from '../../db/client.js'
|
||||||
|
import { logWarn } from '../../utils/logger.js'
|
||||||
|
|
||||||
|
/** 报文保留天数:180 天,由 startSemiAutoTraceCleanup 定时清理。 */
|
||||||
|
export const SEMI_AUTO_TRACE_RETENTION_DAYS = 180
|
||||||
|
const MAX_BODY_CHARS = 32_000
|
||||||
|
const MAX_REDACT_DEPTH = 6
|
||||||
|
const FINGERPRINT_LIMIT = 5_000
|
||||||
|
|
||||||
|
export type SemiAutoTraceChannel =
|
||||||
|
| 'customer_api'
|
||||||
|
| 'admin_api'
|
||||||
|
| 'huya_wup'
|
||||||
|
| 'huya_http'
|
||||||
|
| 'external_connector'
|
||||||
|
|
||||||
|
export type SemiAutoTraceContext = {
|
||||||
|
requestId: string
|
||||||
|
taskId?: number
|
||||||
|
orderNo?: string
|
||||||
|
source?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type SemiAutoTraceEntry = {
|
||||||
|
taskId?: number
|
||||||
|
orderNo?: string
|
||||||
|
requestId?: string
|
||||||
|
direction: 'inbound' | 'outbound'
|
||||||
|
channel: SemiAutoTraceChannel | string
|
||||||
|
action: string
|
||||||
|
status?: 'ok' | 'error'
|
||||||
|
httpStatus?: number
|
||||||
|
durationMs?: number
|
||||||
|
requestSummary?: Record<string, unknown>
|
||||||
|
requestBody?: unknown
|
||||||
|
responseSummary?: Record<string, unknown>
|
||||||
|
responseBody?: unknown
|
||||||
|
errorMessage?: string
|
||||||
|
/** 写操作/关键读:无条件记录(轮询类不要传)。 */
|
||||||
|
always?: boolean
|
||||||
|
/** 轮询类请求的状态指纹:与上次相同则不记录。 */
|
||||||
|
fingerprint?: string | undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
const traceStorage = new AsyncLocalStorage<SemiAutoTraceContext>()
|
||||||
|
const lastFingerprints = new Map<string, string>()
|
||||||
|
|
||||||
|
/** Cookie / Token / 密钥字段:一律不落库。 */
|
||||||
|
const SENSITIVE_KEYS = new Set([
|
||||||
|
'cookie',
|
||||||
|
'set-cookie',
|
||||||
|
'authorization',
|
||||||
|
'proxyauthorization',
|
||||||
|
'token',
|
||||||
|
'accesstoken',
|
||||||
|
'access_token',
|
||||||
|
'refreshtoken',
|
||||||
|
'refresh_token',
|
||||||
|
'biztoken',
|
||||||
|
'udb_biztoken',
|
||||||
|
'password',
|
||||||
|
'passwd',
|
||||||
|
'secret',
|
||||||
|
'apikey',
|
||||||
|
'api_key',
|
||||||
|
'x-semi-auto-key',
|
||||||
|
'sig',
|
||||||
|
'qrcodetoken',
|
||||||
|
'qrcode_token',
|
||||||
|
'qrcontent',
|
||||||
|
'qr_content',
|
||||||
|
'qrimage',
|
||||||
|
'qr_image',
|
||||||
|
'query_string',
|
||||||
|
'smscode',
|
||||||
|
'sms_code',
|
||||||
|
'sessionid',
|
||||||
|
'session_id',
|
||||||
|
'baseinfo',
|
||||||
|
'cookies',
|
||||||
|
'cookie_header',
|
||||||
|
'cookieheader',
|
||||||
|
'ticket',
|
||||||
|
'credential_payload_json',
|
||||||
|
])
|
||||||
|
|
||||||
|
export function runWithSemiAutoTrace<T>(context: SemiAutoTraceContext, fn: () => T): T {
|
||||||
|
return traceStorage.run(context, fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function currentSemiAutoTrace(): SemiAutoTraceContext | undefined {
|
||||||
|
return traceStorage.getStore()
|
||||||
|
}
|
||||||
|
|
||||||
|
function maskValue(value: unknown): unknown {
|
||||||
|
if (value === null || value === undefined) return value
|
||||||
|
if (typeof value !== 'string') return '******'
|
||||||
|
return value.length > 0 ? '******' : ''
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeKey(key: string): string {
|
||||||
|
return key.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 深度脱敏:Cookie / Token / 密钥字段直接替换为 ******。 */
|
||||||
|
export function redactTraceValue(value: unknown, depth = 0): 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))
|
||||||
|
}
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
return String(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function stringifyTraceBody(value: unknown): string {
|
||||||
|
if (value === undefined || value === null) return ''
|
||||||
|
if (typeof value === 'string') {
|
||||||
|
return value.length > MAX_BODY_CHARS
|
||||||
|
? `${value.slice(0, MAX_BODY_CHARS)}\n...[truncated]`
|
||||||
|
: value
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const text = JSON.stringify(redactTraceValue(value), 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function fingerprintKey(entry: SemiAutoTraceEntry): string {
|
||||||
|
return `${entry.taskId || 0}|${entry.channel}|${entry.action}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 采样:写操作与关键读一律记录;轮询类只在状态变化或失败时记录,避免每 2 秒一条。
|
||||||
|
*/
|
||||||
|
export function shouldRecordTrace(entry: SemiAutoTraceEntry): boolean {
|
||||||
|
if (entry.always) return true
|
||||||
|
if ((entry.status || 'ok') === 'error') return true
|
||||||
|
const fingerprint = String(entry.fingerprint || '')
|
||||||
|
if (!fingerprint) return true
|
||||||
|
const key = fingerprintKey(entry)
|
||||||
|
const previous = lastFingerprints.get(key)
|
||||||
|
if (previous === fingerprint) return false
|
||||||
|
lastFingerprints.set(key, fingerprint)
|
||||||
|
if (lastFingerprints.size > FINGERPRINT_LIMIT) lastFingerprints.clear()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 记录一条报文:异步落库,失败只记日志,绝不阻断主流程。 */
|
||||||
|
export function recordSemiAutoTrace(entry: SemiAutoTraceEntry): void {
|
||||||
|
const context = currentSemiAutoTrace()
|
||||||
|
const taskId = Number(entry.taskId || context?.taskId || 0)
|
||||||
|
if (!Number.isFinite(taskId) || taskId <= 0) return
|
||||||
|
if (!shouldRecordTrace(entry)) return
|
||||||
|
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 responseBody = stringifyTraceBody(entry.responseBody)
|
||||||
|
void query(
|
||||||
|
`INSERT INTO semi_auto_trace_logs (
|
||||||
|
task_id, order_no, request_id, direction, channel, action, status,
|
||||||
|
http_status, duration_ms, request_summary, request_body,
|
||||||
|
response_summary, response_body, error_message, created_at
|
||||||
|
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10::jsonb,$11,$12::jsonb,$13,$14,NOW())`,
|
||||||
|
[
|
||||||
|
taskId,
|
||||||
|
orderNo,
|
||||||
|
requestId,
|
||||||
|
entry.direction,
|
||||||
|
entry.channel,
|
||||||
|
entry.action,
|
||||||
|
status,
|
||||||
|
entry.httpStatus ?? null,
|
||||||
|
entry.durationMs ?? null,
|
||||||
|
JSON.stringify(redactTraceValue(entry.requestSummary || {})),
|
||||||
|
requestBody,
|
||||||
|
JSON.stringify(redactTraceValue(entry.responseSummary || {})),
|
||||||
|
responseBody,
|
||||||
|
String(entry.errorMessage || ''),
|
||||||
|
],
|
||||||
|
).catch((error) => {
|
||||||
|
logWarn('semi-auto/trace', '写入报文失败', {
|
||||||
|
taskId,
|
||||||
|
action: entry.action,
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 供调用方快速生成一个轮询指纹。 */
|
||||||
|
export function traceFingerprint(value: unknown): string {
|
||||||
|
if (value === null || value === undefined) return ''
|
||||||
|
let text = ''
|
||||||
|
if (typeof value === 'string') {
|
||||||
|
text = value
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
text = JSON.stringify(value)
|
||||||
|
} catch {
|
||||||
|
text = String(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return crypto.createHash('sha1').update(text).digest('hex')
|
||||||
|
}
|
||||||
|
|
||||||
|
export type SemiAutoTraceQuery = {
|
||||||
|
page?: number
|
||||||
|
pageSize?: number
|
||||||
|
channel?: string
|
||||||
|
status?: string
|
||||||
|
requestId?: string
|
||||||
|
keyword?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function querySemiAutoTraces(taskId: number, input: SemiAutoTraceQuery = {}) {
|
||||||
|
const page = Math.max(1, Math.floor(Number(input.page) || 1))
|
||||||
|
const pageSize = Math.min(200, Math.max(1, Math.floor(Number(input.pageSize) || 50)))
|
||||||
|
const conditions = ['task_id = $1']
|
||||||
|
const params: unknown[] = [taskId]
|
||||||
|
if (input.channel) {
|
||||||
|
params.push(String(input.channel))
|
||||||
|
conditions.push(`channel = $${params.length}`)
|
||||||
|
}
|
||||||
|
if (input.status) {
|
||||||
|
params.push(String(input.status))
|
||||||
|
conditions.push(`status = $${params.length}`)
|
||||||
|
}
|
||||||
|
if (input.requestId) {
|
||||||
|
params.push(String(input.requestId))
|
||||||
|
conditions.push(`request_id = $${params.length}`)
|
||||||
|
}
|
||||||
|
if (input.keyword) {
|
||||||
|
params.push(`%${String(input.keyword).trim()}%`)
|
||||||
|
conditions.push(
|
||||||
|
`(action ILIKE $${params.length} OR request_body ILIKE $${params.length} OR response_body ILIKE $${params.length})`,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
const where = conditions.join(' AND ')
|
||||||
|
const count = await query(
|
||||||
|
`SELECT COUNT(*)::int AS total FROM semi_auto_trace_logs WHERE ${where}`,
|
||||||
|
params,
|
||||||
|
)
|
||||||
|
const rows = await query(
|
||||||
|
`SELECT id, order_no, request_id, direction, channel, action, status,
|
||||||
|
http_status, duration_ms, request_summary, request_body,
|
||||||
|
response_summary, response_body, error_message, created_at
|
||||||
|
FROM semi_auto_trace_logs
|
||||||
|
WHERE ${where}
|
||||||
|
ORDER BY id DESC
|
||||||
|
LIMIT $${params.length + 1} OFFSET $${params.length + 2}`,
|
||||||
|
[...params, pageSize, (page - 1) * pageSize],
|
||||||
|
)
|
||||||
|
const summary = await query(
|
||||||
|
`SELECT channel, status, COUNT(*)::int AS total
|
||||||
|
FROM semi_auto_trace_logs
|
||||||
|
WHERE task_id = $1
|
||||||
|
GROUP BY channel, status`,
|
||||||
|
[taskId],
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
pagination: { page, pageSize, total: Number(count.rows[0]?.total || 0) },
|
||||||
|
summary: summary.rows,
|
||||||
|
items: rows.rows.map((row) => ({
|
||||||
|
id: Number(row.id),
|
||||||
|
orderNo: row.order_no,
|
||||||
|
requestId: row.request_id,
|
||||||
|
direction: row.direction,
|
||||||
|
channel: row.channel,
|
||||||
|
action: row.action,
|
||||||
|
status: row.status,
|
||||||
|
httpStatus: row.http_status,
|
||||||
|
durationMs: row.duration_ms,
|
||||||
|
requestSummary: row.request_summary || {},
|
||||||
|
requestBody: row.request_body || '',
|
||||||
|
responseSummary: row.response_summary || {},
|
||||||
|
responseBody: row.response_body || '',
|
||||||
|
errorMessage: row.error_message || '',
|
||||||
|
createdAt: row.created_at,
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function cleanupSemiAutoTraces(retentionDays = SEMI_AUTO_TRACE_RETENTION_DAYS) {
|
||||||
|
const days = Math.max(1, Math.floor(Number(retentionDays) || SEMI_AUTO_TRACE_RETENTION_DAYS))
|
||||||
|
const result = await query(
|
||||||
|
`DELETE FROM semi_auto_trace_logs WHERE created_at < NOW() - ($1 || ' days')::interval`,
|
||||||
|
[String(days)],
|
||||||
|
)
|
||||||
|
return result.rowCount || 0
|
||||||
|
}
|
||||||
|
|
||||||
|
let cleanupStarted = false
|
||||||
|
|
||||||
|
/** 启动时清一次,之后每 6 小时清理超过保留期的报文。 */
|
||||||
|
export function startSemiAutoTraceCleanup(): void {
|
||||||
|
if (cleanupStarted) return
|
||||||
|
cleanupStarted = true
|
||||||
|
const run = () => {
|
||||||
|
void cleanupSemiAutoTraces().catch((error) => {
|
||||||
|
logWarn('semi-auto/trace', '清理历史报文失败', {
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
run()
|
||||||
|
const timer = setInterval(run, 6 * 60 * 60 * 1000)
|
||||||
|
timer.unref?.()
|
||||||
|
}
|
||||||
@@ -0,0 +1,501 @@
|
|||||||
|
import { CopyOutlined, ReloadOutlined } from '@ant-design/icons'
|
||||||
|
import {
|
||||||
|
App,
|
||||||
|
Button,
|
||||||
|
Collapse,
|
||||||
|
Drawer,
|
||||||
|
Empty,
|
||||||
|
Input,
|
||||||
|
Pagination,
|
||||||
|
Select,
|
||||||
|
Space,
|
||||||
|
Tabs,
|
||||||
|
Tag,
|
||||||
|
theme,
|
||||||
|
Timeline,
|
||||||
|
Typography,
|
||||||
|
} from 'antd'
|
||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import { useEffect, useMemo, useState } from 'react'
|
||||||
|
import type { CSSProperties } from 'react'
|
||||||
|
|
||||||
|
import { fetchAdminSemiAutoTaskHistory } from '@/services/admin/semi-auto'
|
||||||
|
import type { SemiAutoTaskHistoryEvent, SemiAutoTraceItem } from '@/types/admin/semi-auto'
|
||||||
|
import { formatAdminDateTime } from '@/utils/admin-time'
|
||||||
|
import { useIsMobile } from '@/utils/use-is-mobile'
|
||||||
|
|
||||||
|
const { Text } = Typography
|
||||||
|
|
||||||
|
const EVENT_LABELS: Record<string, string> = {
|
||||||
|
task_created: '任务创建',
|
||||||
|
customer_link_opened: '客户打开链接',
|
||||||
|
customer_profile_saved: '客户保存角色资料',
|
||||||
|
login_started: '开始平台登录',
|
||||||
|
login_status_changed: '登录状态变更',
|
||||||
|
binding_status_changed: '绑定状态变更',
|
||||||
|
task_claimed: '客服领取',
|
||||||
|
customer_reauth_requested: '重新发起客户授权',
|
||||||
|
browser_session_opened: '生成浏览器注入票据',
|
||||||
|
credential_session_restored: '凭证恢复登录',
|
||||||
|
credential_invalidated: '凭证失效',
|
||||||
|
task_completed: '订单完成',
|
||||||
|
task_cancelled: '订单取消',
|
||||||
|
}
|
||||||
|
|
||||||
|
const CHANNEL_LABELS: Record<string, string> = {
|
||||||
|
customer_api: '客户接口',
|
||||||
|
admin_api: '运营接口',
|
||||||
|
huya_wup: '虎牙 WUP',
|
||||||
|
huya_http: '虎牙 HTTP',
|
||||||
|
external_connector: '外部 Connector',
|
||||||
|
}
|
||||||
|
|
||||||
|
const CHANNEL_OPTIONS = Object.keys(CHANNEL_LABELS).map((value) => ({
|
||||||
|
value,
|
||||||
|
label: CHANNEL_LABELS[value],
|
||||||
|
}))
|
||||||
|
|
||||||
|
const LOGIN_STATUS_LABELS: Record<string, string> = {
|
||||||
|
waiting_login: '等待登录',
|
||||||
|
qr_pending: '待扫码',
|
||||||
|
scanned: '已扫码',
|
||||||
|
authenticated: '已登录',
|
||||||
|
failed: '登录失败',
|
||||||
|
expired: '登录过期',
|
||||||
|
}
|
||||||
|
|
||||||
|
const BINDING_STATUS_LABELS: Record<string, string> = {
|
||||||
|
not_started: '未开始',
|
||||||
|
qr_pending: '待扫码',
|
||||||
|
scanned: '已扫码',
|
||||||
|
role_ready: '待确认角色',
|
||||||
|
confirmed: '已确认',
|
||||||
|
failed: '绑定失败',
|
||||||
|
expired: '已过期',
|
||||||
|
}
|
||||||
|
|
||||||
|
const EXECUTION_STATUS_LABELS: Record<string, string> = {
|
||||||
|
waiting_customer: '等待客户',
|
||||||
|
waiting_operator: '等待客服',
|
||||||
|
processing: '处理中',
|
||||||
|
completed: '已完成',
|
||||||
|
failed: '失败',
|
||||||
|
cancelled: '已取消',
|
||||||
|
}
|
||||||
|
|
||||||
|
type SemiAutoTaskHistoryDrawerProps = {
|
||||||
|
open: boolean
|
||||||
|
taskId: number | null
|
||||||
|
onClose: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function SemiAutoTaskHistoryDrawer({
|
||||||
|
open,
|
||||||
|
taskId,
|
||||||
|
onClose,
|
||||||
|
}: SemiAutoTaskHistoryDrawerProps) {
|
||||||
|
const { message } = App.useApp()
|
||||||
|
const isMobile = useIsMobile()
|
||||||
|
const { token } = theme.useToken()
|
||||||
|
const [tab, setTab] = useState('events')
|
||||||
|
const [channel, setChannel] = useState('')
|
||||||
|
const [status, setStatus] = useState('')
|
||||||
|
const [keywordDraft, setKeywordDraft] = useState('')
|
||||||
|
const [keyword, setKeyword] = useState('')
|
||||||
|
const [requestId, setRequestId] = useState('')
|
||||||
|
const [page, setPage] = useState(1)
|
||||||
|
const [pageSize, setPageSize] = useState(50)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return
|
||||||
|
setTab('events')
|
||||||
|
setChannel('')
|
||||||
|
setStatus('')
|
||||||
|
setKeywordDraft('')
|
||||||
|
setKeyword('')
|
||||||
|
setRequestId('')
|
||||||
|
setPage(1)
|
||||||
|
setPageSize(50)
|
||||||
|
}, [open, taskId])
|
||||||
|
|
||||||
|
const params = useMemo(
|
||||||
|
() => ({
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
channel: channel || undefined,
|
||||||
|
status: status || undefined,
|
||||||
|
keyword: keyword.trim() || undefined,
|
||||||
|
requestId: requestId || undefined,
|
||||||
|
}),
|
||||||
|
[channel, keyword, page, pageSize, requestId, status],
|
||||||
|
)
|
||||||
|
|
||||||
|
const historyQuery = useQuery({
|
||||||
|
queryKey: ['admin-semi-auto-task-history', taskId, params],
|
||||||
|
queryFn: () => fetchAdminSemiAutoTaskHistory(Number(taskId), params),
|
||||||
|
enabled: open && Boolean(taskId),
|
||||||
|
refetchInterval: open && Boolean(taskId) ? 8000 : false,
|
||||||
|
})
|
||||||
|
|
||||||
|
const history = historyQuery.data?.data
|
||||||
|
const events = history?.events || []
|
||||||
|
const traces = history?.traces
|
||||||
|
const traceItems = traces?.items || []
|
||||||
|
const preStyle: CSSProperties = {
|
||||||
|
margin: '6px 0 0',
|
||||||
|
padding: 10,
|
||||||
|
background: token.colorFillQuaternary,
|
||||||
|
border: `1px solid ${token.colorBorderSecondary}`,
|
||||||
|
borderRadius: token.borderRadius,
|
||||||
|
color: token.colorText,
|
||||||
|
fontSize: 12,
|
||||||
|
lineHeight: 1.55,
|
||||||
|
maxHeight: 320,
|
||||||
|
overflow: 'auto',
|
||||||
|
whiteSpace: 'pre-wrap',
|
||||||
|
wordBreak: 'break-all',
|
||||||
|
}
|
||||||
|
|
||||||
|
const copyText = (text: string, label: string) => {
|
||||||
|
if (!text) {
|
||||||
|
message.warning(`${label}为空`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
void navigator.clipboard
|
||||||
|
.writeText(text)
|
||||||
|
.then(() => message.success(`${label}已复制`))
|
||||||
|
.catch(() => message.error('复制失败,请手动选择文本复制'))
|
||||||
|
}
|
||||||
|
|
||||||
|
const eventsPanel = (
|
||||||
|
<Space direction="vertical" size={12} style={{ width: '100%' }}>
|
||||||
|
{history?.task ? (
|
||||||
|
<Space size={6} wrap>
|
||||||
|
<Tag color="blue">
|
||||||
|
登录:{LOGIN_STATUS_LABELS[history.task.loginStatus] || history.task.loginStatus}
|
||||||
|
</Tag>
|
||||||
|
<Tag color="gold">
|
||||||
|
绑定:
|
||||||
|
{history.task.platform === 'weibo'
|
||||||
|
? '登录即授权'
|
||||||
|
: BINDING_STATUS_LABELS[history.task.bindingStatus] || history.task.bindingStatus}
|
||||||
|
</Tag>
|
||||||
|
<Tag color="purple">
|
||||||
|
执行:
|
||||||
|
{EXECUTION_STATUS_LABELS[history.task.executionStatus] || history.task.executionStatus}
|
||||||
|
</Tag>
|
||||||
|
<Text type="secondary">创建 {formatAdminDateTime(history.task.createdAt)}</Text>
|
||||||
|
{history.task.completedAt ? (
|
||||||
|
<Text type="secondary">完成 {formatAdminDateTime(history.task.completedAt)}</Text>
|
||||||
|
) : null}
|
||||||
|
</Space>
|
||||||
|
) : null}
|
||||||
|
{history && history.eventTotal > events.length ? (
|
||||||
|
<Text type="secondary">
|
||||||
|
仅展示最近 {events.length} 条状态事件,共 {history.eventTotal} 条。
|
||||||
|
</Text>
|
||||||
|
) : null}
|
||||||
|
{historyQuery.isLoading ? (
|
||||||
|
<Text type="secondary">加载中...</Text>
|
||||||
|
) : events.length === 0 ? (
|
||||||
|
<Empty description="暂无状态流转记录" />
|
||||||
|
) : (
|
||||||
|
<Timeline
|
||||||
|
items={events.map((event) => ({
|
||||||
|
color: /fail|invalid|error|cancel/i.test(event.eventType) ? 'red' : 'blue',
|
||||||
|
children: <EventItem event={event} preStyle={preStyle} />,
|
||||||
|
}))}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</Space>
|
||||||
|
)
|
||||||
|
|
||||||
|
const tracesPanel = (
|
||||||
|
<Space direction="vertical" size={12} style={{ width: '100%' }}>
|
||||||
|
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, alignItems: 'center' }}>
|
||||||
|
<Select
|
||||||
|
allowClear
|
||||||
|
placeholder="全部渠道"
|
||||||
|
value={channel || undefined}
|
||||||
|
onChange={(value) => {
|
||||||
|
setChannel(value || '')
|
||||||
|
setPage(1)
|
||||||
|
}}
|
||||||
|
options={CHANNEL_OPTIONS}
|
||||||
|
style={isMobile ? { flex: '1 1 150px', minWidth: 120 } : { width: 160 }}
|
||||||
|
/>
|
||||||
|
<Select
|
||||||
|
allowClear
|
||||||
|
placeholder="全部结果"
|
||||||
|
value={status || undefined}
|
||||||
|
onChange={(value) => {
|
||||||
|
setStatus(value || '')
|
||||||
|
setPage(1)
|
||||||
|
}}
|
||||||
|
options={[
|
||||||
|
{ value: 'ok', label: '成功' },
|
||||||
|
{ value: 'error', label: '失败' },
|
||||||
|
]}
|
||||||
|
style={isMobile ? { flex: '1 1 110px', minWidth: 96 } : { width: 120 }}
|
||||||
|
/>
|
||||||
|
<Input.Search
|
||||||
|
allowClear
|
||||||
|
placeholder="动作 / 报文内容关键字"
|
||||||
|
value={keywordDraft}
|
||||||
|
onChange={(event) => setKeywordDraft(event.target.value)}
|
||||||
|
onSearch={(value) => {
|
||||||
|
setKeyword(value)
|
||||||
|
setPage(1)
|
||||||
|
}}
|
||||||
|
style={isMobile ? { flex: '1 1 220px' } : { width: 240 }}
|
||||||
|
/>
|
||||||
|
<Button icon={<ReloadOutlined />} onClick={() => void historyQuery.refetch()}>
|
||||||
|
刷新
|
||||||
|
</Button>
|
||||||
|
{requestId ? (
|
||||||
|
<Tag
|
||||||
|
closable
|
||||||
|
color="blue"
|
||||||
|
onClose={() => {
|
||||||
|
setRequestId('')
|
||||||
|
setPage(1)
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
同一请求:{requestId}
|
||||||
|
</Tag>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
{traces?.summary?.length ? (
|
||||||
|
<Space size={4} wrap>
|
||||||
|
{traces.summary.map((item) => (
|
||||||
|
<Tag
|
||||||
|
key={`${item.channel}-${item.status}`}
|
||||||
|
color={item.status === 'error' ? 'red' : 'default'}
|
||||||
|
>
|
||||||
|
{CHANNEL_LABELS[item.channel] || item.channel} ·{' '}
|
||||||
|
{item.status === 'error' ? '失败' : '成功'} {item.total}
|
||||||
|
</Tag>
|
||||||
|
))}
|
||||||
|
</Space>
|
||||||
|
) : null}
|
||||||
|
<Text type="secondary">报文保留 180 天;Cookie、Token、短信验证码和二维码内容不落库。</Text>
|
||||||
|
{historyQuery.isLoading ? (
|
||||||
|
<Text type="secondary">加载中...</Text>
|
||||||
|
) : traceItems.length === 0 ? (
|
||||||
|
<Empty description="暂无报文记录(当前只记录状态变化与失败,未变化的轮询不落库)" />
|
||||||
|
) : (
|
||||||
|
<Collapse
|
||||||
|
size="small"
|
||||||
|
items={traceItems.map((item) => ({
|
||||||
|
key: String(item.id),
|
||||||
|
label: <TraceLabel item={item} />,
|
||||||
|
children: (
|
||||||
|
<TracePayload
|
||||||
|
item={item}
|
||||||
|
preStyle={preStyle}
|
||||||
|
onCopy={copyText}
|
||||||
|
onFilterRequest={(value) => {
|
||||||
|
setRequestId(value)
|
||||||
|
setPage(1)
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
}))}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<Pagination
|
||||||
|
size={isMobile ? 'small' : undefined}
|
||||||
|
current={traces?.pagination.page || page}
|
||||||
|
pageSize={traces?.pagination.pageSize || pageSize}
|
||||||
|
total={traces?.pagination.total || 0}
|
||||||
|
showSizeChanger={!isMobile}
|
||||||
|
showTotal={(total) => `共 ${total} 条`}
|
||||||
|
onChange={(nextPage, nextPageSize) => {
|
||||||
|
setPage(nextPage)
|
||||||
|
setPageSize(nextPageSize)
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</Space>
|
||||||
|
)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Drawer
|
||||||
|
open={open}
|
||||||
|
width={isMobile ? '100%' : 960}
|
||||||
|
title={history?.task ? `履约历史 · ${history.task.orderNo}` : '履约历史'}
|
||||||
|
onClose={onClose}
|
||||||
|
extra={
|
||||||
|
<Button size="small" icon={<ReloadOutlined />} onClick={() => void historyQuery.refetch()}>
|
||||||
|
刷新
|
||||||
|
</Button>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Tabs
|
||||||
|
activeKey={tab}
|
||||||
|
onChange={setTab}
|
||||||
|
items={[
|
||||||
|
{
|
||||||
|
key: 'events',
|
||||||
|
label: `状态流转(${history?.eventTotal ?? 0})`,
|
||||||
|
children: eventsPanel,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'traces',
|
||||||
|
label: `全链路报文(${traces?.pagination.total ?? 0})`,
|
||||||
|
children: tracesPanel,
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</Drawer>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function EventItem({
|
||||||
|
event,
|
||||||
|
preStyle,
|
||||||
|
}: {
|
||||||
|
event: SemiAutoTaskHistoryEvent
|
||||||
|
preStyle: CSSProperties
|
||||||
|
}) {
|
||||||
|
const detail = event.detail || {}
|
||||||
|
const detailKeys = Object.keys(detail)
|
||||||
|
const transitions = [
|
||||||
|
{
|
||||||
|
label: '登录',
|
||||||
|
map: LOGIN_STATUS_LABELS,
|
||||||
|
from: event.fromLoginStatus,
|
||||||
|
to: event.toLoginStatus,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: '绑定',
|
||||||
|
map: BINDING_STATUS_LABELS,
|
||||||
|
from: event.fromBindingStatus,
|
||||||
|
to: event.toBindingStatus,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: '执行',
|
||||||
|
map: EXECUTION_STATUS_LABELS,
|
||||||
|
from: event.fromExecutionStatus,
|
||||||
|
to: event.toExecutionStatus,
|
||||||
|
},
|
||||||
|
].filter((item) => item.from !== item.to && Boolean(item.from || item.to))
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Space direction="vertical" size={2} style={{ width: '100%' }}>
|
||||||
|
<Text strong>{EVENT_LABELS[event.eventType] || event.eventType}</Text>
|
||||||
|
<Text type="secondary">
|
||||||
|
{formatAdminDateTime(event.createdAt)} · {event.actorType}
|
||||||
|
{event.actorId ? ` ${event.actorId}` : ''}
|
||||||
|
</Text>
|
||||||
|
{transitions.map((item) => (
|
||||||
|
<Text key={item.label} type="secondary">
|
||||||
|
{item.label}:{statusLabel(item.map, item.from)} → {statusLabel(item.map, item.to)}
|
||||||
|
</Text>
|
||||||
|
))}
|
||||||
|
{detailKeys.length > 0 ? <pre style={preStyle}>{JSON.stringify(detail, null, 2)}</pre> : null}
|
||||||
|
</Space>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function TraceLabel({ item }: { item: SemiAutoTraceItem }) {
|
||||||
|
return (
|
||||||
|
<Space direction="vertical" size={2} style={{ width: '100%' }}>
|
||||||
|
<Space size={6} wrap>
|
||||||
|
<Tag color={item.direction === 'inbound' ? 'blue' : 'purple'}>
|
||||||
|
{item.direction === 'inbound' ? '入站' : '出站'}
|
||||||
|
</Tag>
|
||||||
|
<Tag>{CHANNEL_LABELS[item.channel] || item.channel}</Tag>
|
||||||
|
<Tag color={item.status === 'ok' ? 'green' : 'red'}>
|
||||||
|
{item.status === 'ok' ? '成功' : '失败'}
|
||||||
|
</Tag>
|
||||||
|
{item.httpStatus ? <Text type="secondary">HTTP {item.httpStatus}</Text> : null}
|
||||||
|
{item.durationMs !== null && item.durationMs !== undefined ? (
|
||||||
|
<Text type="secondary">{item.durationMs}ms</Text>
|
||||||
|
) : null}
|
||||||
|
<Text type="secondary">{formatAdminDateTime(item.createdAt)}</Text>
|
||||||
|
</Space>
|
||||||
|
<Text code style={{ whiteSpace: 'break-all' }}>
|
||||||
|
{item.action}
|
||||||
|
</Text>
|
||||||
|
{item.errorMessage ? <Text type="danger">{item.errorMessage}</Text> : null}
|
||||||
|
</Space>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function TracePayload({
|
||||||
|
item,
|
||||||
|
preStyle,
|
||||||
|
onCopy,
|
||||||
|
onFilterRequest,
|
||||||
|
}: {
|
||||||
|
item: SemiAutoTraceItem
|
||||||
|
preStyle: CSSProperties
|
||||||
|
onCopy: (text: string, label: string) => void
|
||||||
|
onFilterRequest: (requestId: string) => void
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<Space direction="vertical" size={10} style={{ width: '100%' }}>
|
||||||
|
<PayloadBlock title="请求概要" value={item.requestSummary} preStyle={preStyle} />
|
||||||
|
<PayloadBlock title="请求报文" value={item.requestBody} preStyle={preStyle} />
|
||||||
|
<PayloadBlock title="响应概要" value={item.responseSummary} preStyle={preStyle} />
|
||||||
|
<PayloadBlock title="响应报文" value={item.responseBody} preStyle={preStyle} />
|
||||||
|
<Space size={6} wrap>
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
icon={<CopyOutlined />}
|
||||||
|
onClick={() =>
|
||||||
|
onCopy(
|
||||||
|
[
|
||||||
|
`动作:${item.action}`,
|
||||||
|
`requestId:${item.requestId}`,
|
||||||
|
'',
|
||||||
|
'# 请求',
|
||||||
|
item.requestBody,
|
||||||
|
'',
|
||||||
|
'# 响应',
|
||||||
|
item.responseBody,
|
||||||
|
].join('\n'),
|
||||||
|
'完整报文',
|
||||||
|
)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
复制完整报文
|
||||||
|
</Button>
|
||||||
|
{item.requestId ? (
|
||||||
|
<Button size="small" onClick={() => onFilterRequest(item.requestId)}>
|
||||||
|
只看同一请求
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
<Text type="secondary">requestId:{item.requestId || '-'}</Text>
|
||||||
|
</Space>
|
||||||
|
</Space>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function PayloadBlock({
|
||||||
|
title,
|
||||||
|
value,
|
||||||
|
preStyle,
|
||||||
|
}: {
|
||||||
|
title: string
|
||||||
|
value: unknown
|
||||||
|
preStyle: CSSProperties
|
||||||
|
}) {
|
||||||
|
const text =
|
||||||
|
value && typeof value === 'object'
|
||||||
|
? Object.keys(value as Record<string, unknown>).length > 0
|
||||||
|
? JSON.stringify(value, null, 2)
|
||||||
|
: ''
|
||||||
|
: String(value || '').trim()
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<Text strong>{title}</Text>
|
||||||
|
{text ? <pre style={preStyle}>{text}</pre> : <Text type="secondary">(空)</Text>}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function statusLabel(map: Record<string, string>, value: string | null) {
|
||||||
|
if (!value) return '—'
|
||||||
|
return map[value] || value
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ import {
|
|||||||
CheckCircleOutlined,
|
CheckCircleOutlined,
|
||||||
ChromeOutlined,
|
ChromeOutlined,
|
||||||
CopyOutlined,
|
CopyOutlined,
|
||||||
|
HistoryOutlined,
|
||||||
KeyOutlined,
|
KeyOutlined,
|
||||||
ReloadOutlined,
|
ReloadOutlined,
|
||||||
SendOutlined,
|
SendOutlined,
|
||||||
@@ -30,6 +31,7 @@ import { useEffect, useMemo, useState } from 'react'
|
|||||||
|
|
||||||
import ImageUpload from '@/components/files/ImageUpload'
|
import ImageUpload from '@/components/files/ImageUpload'
|
||||||
import PageHeader from '@/components/admin/PageHeader'
|
import PageHeader from '@/components/admin/PageHeader'
|
||||||
|
import SemiAutoTaskHistoryDrawer from '@/components/admin/SemiAutoTaskHistoryDrawer'
|
||||||
import PercentTable from '@/components/common/PercentTable'
|
import PercentTable from '@/components/common/PercentTable'
|
||||||
import {
|
import {
|
||||||
cancelAdminSemiAutoTask,
|
cancelAdminSemiAutoTask,
|
||||||
@@ -94,6 +96,7 @@ export default function AdminSemiAutoTasksPage() {
|
|||||||
const [page, setPage] = useState(1)
|
const [page, setPage] = useState(1)
|
||||||
const [pageSize, setPageSize] = useState(20)
|
const [pageSize, setPageSize] = useState(20)
|
||||||
const [detailTaskId, setDetailTaskId] = useState<number | null>(null)
|
const [detailTaskId, setDetailTaskId] = useState<number | null>(null)
|
||||||
|
const [historyTaskId, setHistoryTaskId] = useState<number | null>(null)
|
||||||
const [completeTask, setCompleteTask] = useState<SemiAutoTask | null>(null)
|
const [completeTask, setCompleteTask] = useState<SemiAutoTask | null>(null)
|
||||||
const [completeFiles, setCompleteFiles] = useState<UploadedFile[]>([])
|
const [completeFiles, setCompleteFiles] = useState<UploadedFile[]>([])
|
||||||
const [completeForm] = Form.useForm<CompleteFormValues>()
|
const [completeForm] = Form.useForm<CompleteFormValues>()
|
||||||
@@ -416,6 +419,13 @@ export default function AdminSemiAutoTasksPage() {
|
|||||||
<Button size="small" onClick={() => setDetailTaskId(task.id)}>
|
<Button size="small" onClick={() => setDetailTaskId(task.id)}>
|
||||||
详情
|
详情
|
||||||
</Button>
|
</Button>
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
icon={<HistoryOutlined />}
|
||||||
|
onClick={() => setHistoryTaskId(task.id)}
|
||||||
|
>
|
||||||
|
历史
|
||||||
|
</Button>
|
||||||
{taskNeedsCustomerReauth(task) ? (
|
{taskNeedsCustomerReauth(task) ? (
|
||||||
<Button
|
<Button
|
||||||
size="small"
|
size="small"
|
||||||
@@ -762,6 +772,12 @@ export default function AdminSemiAutoTasksPage() {
|
|||||||
)}
|
)}
|
||||||
</Drawer>
|
</Drawer>
|
||||||
|
|
||||||
|
<SemiAutoTaskHistoryDrawer
|
||||||
|
open={Boolean(historyTaskId)}
|
||||||
|
taskId={historyTaskId}
|
||||||
|
onClose={() => setHistoryTaskId(null)}
|
||||||
|
/>
|
||||||
|
|
||||||
<Modal
|
<Modal
|
||||||
open={Boolean(completeTask)}
|
open={Boolean(completeTask)}
|
||||||
title="确认完成半自动履约"
|
title="确认完成半自动履约"
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { apiGet, apiPost } from '@/lib/http'
|
|||||||
import type {
|
import type {
|
||||||
SemiAutoCredentialExport,
|
SemiAutoCredentialExport,
|
||||||
SemiAutoTaskDetail,
|
SemiAutoTaskDetail,
|
||||||
|
SemiAutoTaskHistory,
|
||||||
SemiAutoTaskListResult,
|
SemiAutoTaskListResult,
|
||||||
} from '@/types/admin/semi-auto'
|
} from '@/types/admin/semi-auto'
|
||||||
|
|
||||||
@@ -13,6 +14,13 @@ export function fetchAdminSemiAutoTask(taskId: number) {
|
|||||||
return apiGet<SemiAutoTaskDetail>(`/api/v1/admin/semi-auto/tasks/${taskId}`)
|
return apiGet<SemiAutoTaskDetail>(`/api/v1/admin/semi-auto/tasks/${taskId}`)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function fetchAdminSemiAutoTaskHistory(
|
||||||
|
taskId: number,
|
||||||
|
params: Record<string, unknown> = {},
|
||||||
|
) {
|
||||||
|
return apiGet<SemiAutoTaskHistory>(`/api/v1/admin/semi-auto/tasks/${taskId}/history`, params)
|
||||||
|
}
|
||||||
|
|
||||||
export function exportAdminSemiAutoCredential(taskId: number) {
|
export function exportAdminSemiAutoCredential(taskId: number) {
|
||||||
return apiPost<SemiAutoCredentialExport>(
|
return apiPost<SemiAutoCredentialExport>(
|
||||||
`/api/v1/admin/semi-auto/tasks/${taskId}/credential/export`,
|
`/api/v1/admin/semi-auto/tasks/${taskId}/credential/export`,
|
||||||
|
|||||||
@@ -81,6 +81,65 @@ export type SemiAutoTaskDetail = {
|
|||||||
events: SemiAutoTaskEvent[]
|
events: SemiAutoTaskEvent[]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type SemiAutoTaskHistoryEvent = {
|
||||||
|
id: number
|
||||||
|
eventType: string
|
||||||
|
actorType: string
|
||||||
|
actorId: string
|
||||||
|
fromLoginStatus: string | null
|
||||||
|
toLoginStatus: string | null
|
||||||
|
fromBindingStatus: string | null
|
||||||
|
toBindingStatus: string | null
|
||||||
|
fromExecutionStatus: string | null
|
||||||
|
toExecutionStatus: string | null
|
||||||
|
detail: Record<string, unknown>
|
||||||
|
createdAt: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type SemiAutoTraceItem = {
|
||||||
|
id: number
|
||||||
|
orderNo: string
|
||||||
|
requestId: string
|
||||||
|
direction: 'inbound' | 'outbound' | string
|
||||||
|
channel: string
|
||||||
|
action: string
|
||||||
|
status: 'ok' | 'error' | string
|
||||||
|
httpStatus: number | null
|
||||||
|
durationMs: number | null
|
||||||
|
requestSummary: Record<string, unknown>
|
||||||
|
requestBody: string
|
||||||
|
responseSummary: Record<string, unknown>
|
||||||
|
responseBody: string
|
||||||
|
errorMessage: string
|
||||||
|
createdAt: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type SemiAutoTraceSummaryItem = {
|
||||||
|
channel: string
|
||||||
|
status: string
|
||||||
|
total: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export type SemiAutoTraceQueryParams = {
|
||||||
|
page?: number
|
||||||
|
pageSize?: number
|
||||||
|
channel?: string
|
||||||
|
status?: string
|
||||||
|
requestId?: string
|
||||||
|
keyword?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type SemiAutoTaskHistory = {
|
||||||
|
task: SemiAutoTask
|
||||||
|
events: SemiAutoTaskHistoryEvent[]
|
||||||
|
eventTotal: number
|
||||||
|
traces: {
|
||||||
|
pagination: { page: number; pageSize: number; total: number }
|
||||||
|
summary: SemiAutoTraceSummaryItem[]
|
||||||
|
items: SemiAutoTraceItem[]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export type SemiAutoCredentialExport = {
|
export type SemiAutoCredentialExport = {
|
||||||
credentialId: number
|
credentialId: number
|
||||||
platform: SemiAutoPlatform
|
platform: SemiAutoPlatform
|
||||||
|
|||||||
Reference in New Issue
Block a user