现象:后台半自动履约列表按创建时间倒序,而页面展示的是「更新时间」,两者不一致; 系统对账还会把没有状态变化的行也推进 updated_at,导致列表看起来乱序且每次刷新都重排。 生产只读核对(2026-12-03 13:04):一次 Connector 对账推进了 18 条任务的 updated_at, 其中只有 2 条产生真实状态变化事件;5578 条任务里 5436 条是「客户从未开始」, 原来的排序会把这类从未开始的新任务盖在真正等客服处理的任务上面。 改动: - semi_auto_tasks.updated_at 收敛为「最近一次真实状态变更」:唯一写入口 convergeSemiAutoTaskState 先逐列比较补丁与库内值(空串与 NULL 同义、JSON 按键排序比较、 coalesce_now 已有值不算变化),完全相同就整条 UPDATE 都不执行。 轮询、Connector 对账、绑定决策重算不再制造假更新。 - 列表排序改为待办队列桶序:等客服履约 → 客服处理中 → 需客服修复 → 客户处理中 → 客户未开始 → 已完成 → 已取消;同桶按 updated_at 倒序并以 id 兜底。 分桶只读 execution_status / login_status / binding_status / customer_link_opened_at 这些正式字段,待办文案仍由 displayStatus 单点输出。 - 页面补一行排序口径说明,说明系统轮询不会刷新「更新时间」。 - 权威文档 3.4.2 记录队列排序与 updated_at 语义。 - 测试:新增无变化不推进 updated_at 的集成用例;排序集成用例改为覆盖桶序优先于时间; 单测覆盖空串/NULL、bigint 字符串、JSON 键序、coalesce_now 四类比较。 验证:backend check 通过(1564 用例 / fail 0),frontend check 通过, 半自动履约真实 PostgreSQL 集成测试 15/15 通过。
1087 lines
39 KiB
TypeScript
1087 lines
39 KiB
TypeScript
import { query, withTransaction } from '../../db/client.js'
|
||
import { getFileAssetByObjectKey } from '../../repositories/file-asset-repo.js'
|
||
import { createHttpError } from '../../utils/http.js'
|
||
import { SEMI_AUTO_CATEGORY_KEYS } from '../cost-center/manual-fulfillment-config-service.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 {
|
||
revokeHuyaSession,
|
||
type ConnectorBindingSession,
|
||
type SemiAutoConnectorMode,
|
||
} from './huya-connector-client.js'
|
||
import {
|
||
buildSemiAutoCredentialCookieHeader,
|
||
loadSemiAutoCredential,
|
||
selectSemiAutoCredentialCookies,
|
||
} from './semi-auto-credential-service.js'
|
||
import { revokeWeiboSession } from './weibo-connector-client.js'
|
||
import { querySemiAutoTraces } from './semi-auto-trace.js'
|
||
import { isHuyaRoleToken } from './binding-role-id.js'
|
||
import {
|
||
getAccountBindingPolicy,
|
||
resolveBrowserTargetUrl,
|
||
} from '../account-binding/platform-policy.js'
|
||
import {
|
||
ensureConnectorSessionForTask,
|
||
ensureSemiAutoTasksForAdminList,
|
||
getBindingForTask,
|
||
getLoginSessionForTask,
|
||
isTaskBindingConfirmed,
|
||
loadTask,
|
||
loadTaskForUpdateWithClient,
|
||
mapTask,
|
||
normalizeId,
|
||
normalizeOrderNo,
|
||
publishSemiAutoTaskRealtimeChange,
|
||
resolveTaskHuyaBindingDecision,
|
||
resetTaskForCustomerLogin,
|
||
revokeSessionForTask,
|
||
TASK_SELECT,
|
||
updateBindingTask,
|
||
updateBindingTaskWithClient,
|
||
type BindingStatus,
|
||
type LoginStatus,
|
||
type SemiAutoPlatform,
|
||
type TaskRow,
|
||
} from './semi-auto-task-core.js'
|
||
import { updateLoginTask } from './semi-auto-customer-service.js'
|
||
import { ACTIVE_EXECUTION_STATUSES } from './task-state-rules.js'
|
||
import {
|
||
convergeSemiAutoTaskState,
|
||
SEMI_AUTO_COALESCE_NOW,
|
||
SEMI_AUTO_NOW,
|
||
} from './semi-auto-task-state-service.js'
|
||
|
||
/**
|
||
* 后台半自动任务列表的队列顺序。
|
||
*
|
||
* 这是运营待办队列,不是审计流水:先按「谁在等我」分桶,同桶内按最近一次真实状态变更倒序。
|
||
* 分桶只读正式状态字段(execution_status / login_status / binding_status /
|
||
* customer_link_opened_at),不复制 displayStatus 的判定链;具体待办文案仍由
|
||
* displayStatus 单点输出,页面不重新解释状态。
|
||
*
|
||
* 之前按 `created_at DESC` 排序,而页面展示的是「更新时间」,且 `updated_at` 会被
|
||
* 无变化的轮询/对账推进,导致列表既与展示列不一致、又每次刷新都重排;
|
||
* `updated_at` 已在写入口收敛为「真实状态变更」,可以直接作为同桶排序键。
|
||
*/
|
||
const SEMI_AUTO_TASK_QUEUE_ORDER_SQL = `
|
||
ORDER BY
|
||
CASE
|
||
WHEN task.execution_status = 'waiting_operator' THEN 0
|
||
WHEN task.execution_status = 'processing' THEN 1
|
||
WHEN task.execution_status = 'failed' THEN 2
|
||
WHEN task.execution_status = 'waiting_customer'
|
||
AND (
|
||
task.login_status <> 'waiting_login'
|
||
OR task.binding_status <> 'not_started'
|
||
OR task.customer_link_opened_at IS NOT NULL
|
||
) THEN 3
|
||
WHEN task.execution_status = 'waiting_customer' THEN 4
|
||
WHEN task.execution_status = 'completed' THEN 8
|
||
WHEN task.execution_status = 'cancelled' THEN 9
|
||
ELSE 5
|
||
END,
|
||
task.updated_at DESC,
|
||
task.id DESC`
|
||
|
||
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()
|
||
// 分类筛选必须区分「参数缺失」与「显式空串」:
|
||
// 缺失 = 全部(不筛选),空串 = 未分类(semi_auto_category = '')。
|
||
const hasCategoryFilter = input.category !== undefined && input.category !== null
|
||
const category = hasCategoryFilter ? String(input.category).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 (hasCategoryFilter && (SEMI_AUTO_CATEGORY_KEYS as readonly string[]).includes(category)) {
|
||
params.push(category)
|
||
conditions.push(`task.semi_auto_category = $${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} OR task.pending_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}
|
||
${SEMI_AUTO_TASK_QUEUE_ORDER_SQL}
|
||
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 bindingDecision = resolveTaskHuyaBindingDecision(task)
|
||
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: bindingDecision?.comparison || null,
|
||
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 = resolveBrowserTargetUrl(credential.platform, [configuredTarget])
|
||
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 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)
|
||
}
|
||
if (
|
||
task.platform === 'huya' &&
|
||
task.login_status === 'authenticated' &&
|
||
!isTaskBindingConfirmed(task)
|
||
) {
|
||
const binding = await getBindingForTask(task, task.connector_session_id)
|
||
await updateBindingTask(task, binding, 'connector')
|
||
}
|
||
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
|
||
}
|
||
const bindingPolicy = getAccountBindingPolicy(task.platform)
|
||
if (
|
||
bindingPolicy.bindingRequired &&
|
||
bindingPolicy.queryOwner === 'order_site' &&
|
||
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 withTransaction(async (client) => {
|
||
await convergeSemiAutoTaskState(client, Number(candidate.id), {
|
||
reason: 'semi_auto_reconcile_failed',
|
||
actor: 'system',
|
||
patch: { lastError: detail.slice(0, 1000) },
|
||
expected: { executionStatus: [...ACTIVE_EXECUTION_STATUSES] },
|
||
event: null,
|
||
})
|
||
}).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',
|
||
])
|
||
const ROLE_IDENTITY_SOURCES = new Set([
|
||
'',
|
||
'huya_outer_current',
|
||
'huya_inner_pending',
|
||
'legacy_account_uid_fallback',
|
||
'manual',
|
||
])
|
||
const VERIFICATION_BASES = new Set(['', 'role_name_zone', 'platform_numeric_uid', 'manual'])
|
||
const CONFIRM_STATES = new Set<'idle' | 'submitting' | 'accepted' | 'rejected'>([
|
||
'idle',
|
||
'submitting',
|
||
'accepted',
|
||
'rejected',
|
||
])
|
||
|
||
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
|
||
}
|
||
|
||
function parseSnapshotBoolean(value: unknown): boolean | undefined {
|
||
if (value === undefined || value === null || value === '') return undefined
|
||
if (typeof value === 'boolean') return value
|
||
if (typeof value === 'number') return value !== 0
|
||
const text = String(value).trim().toLowerCase()
|
||
if (['true', '1', 'yes'].includes(text)) return true
|
||
if (['false', '0', 'no'].includes(text)) return false
|
||
return undefined
|
||
}
|
||
|
||
function parseSnapshotNumber(value: unknown): number {
|
||
const number = Number(value)
|
||
return Number.isFinite(number) && number > 0 ? number : 0
|
||
}
|
||
|
||
/**
|
||
* 外部 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,
|
||
'绑定状态',
|
||
)
|
||
const stateVersionRaw = input.stateVersion ?? input.state_version
|
||
const stateVersion = Number(stateVersionRaw)
|
||
if (
|
||
stateVersionRaw === undefined ||
|
||
stateVersionRaw === null ||
|
||
String(stateVersionRaw).trim() === '' ||
|
||
!Number.isSafeInteger(stateVersion) ||
|
||
stateVersion <= 0
|
||
) {
|
||
throw createHttpError('状态快照版本必须为正整数', {
|
||
statusCode: 400,
|
||
errorCode: 'semi_auto_snapshot_state_version_required',
|
||
})
|
||
}
|
||
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 }
|
||
}
|
||
if (stateVersion <= Number(task.connector_state_version || 0)) {
|
||
return { applied: false, stale: true, stateVersion }
|
||
}
|
||
|
||
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 legacyRoleId = String(input.bindGameRoleId ?? input.bind_game_role_id ?? '').trim()
|
||
const bindGameRoleToken = String(
|
||
input.bindGameRoleToken ??
|
||
input.bind_game_role_token ??
|
||
(isHuyaRoleToken(legacyRoleId) ? legacyRoleId : ''),
|
||
).trim()
|
||
const platformGameRoleUid = String(
|
||
input.platformGameRoleUid ?? input.platform_game_role_uid ?? '',
|
||
).trim()
|
||
const bindGameChannel = String(input.bindGameChannel ?? input.bind_game_channel ?? '').trim()
|
||
const pendingBindGameAccount = String(
|
||
input.pendingBindGameAccount ?? input.pending_bind_game_account ?? '',
|
||
).trim()
|
||
const pendingBindGameRole = String(
|
||
input.pendingBindGameRole ?? input.pending_bind_game_role ?? '',
|
||
).trim()
|
||
const pendingBindGameRoleToken = String(
|
||
input.pendingBindGameRoleToken ?? input.pending_bind_game_role_token ?? '',
|
||
).trim()
|
||
const pendingPlatformGameRoleUid = String(
|
||
input.pendingPlatformGameRoleUid ?? input.pending_platform_game_role_uid ?? '',
|
||
).trim()
|
||
const pendingBindGameChannel = String(
|
||
input.pendingBindGameChannel ?? input.pending_bind_game_channel ?? '',
|
||
).trim()
|
||
const roleIdentitySource = String(
|
||
input.roleIdentitySource ?? input.role_identity_source ?? '',
|
||
).trim()
|
||
const verificationBasis = String(
|
||
input.verificationBasis ?? input.verification_basis ?? '',
|
||
).trim()
|
||
if (bindGameRoleToken && !isHuyaRoleToken(bindGameRoleToken)) {
|
||
throw createHttpError('虎牙平台角色 token 格式无效', {
|
||
statusCode: 400,
|
||
errorCode: 'semi_auto_snapshot_role_token_invalid',
|
||
})
|
||
}
|
||
if (pendingBindGameRoleToken && !isHuyaRoleToken(pendingBindGameRoleToken)) {
|
||
throw createHttpError('虎牙待确认角色 token 格式无效', {
|
||
statusCode: 400,
|
||
errorCode: 'semi_auto_snapshot_pending_role_token_invalid',
|
||
})
|
||
}
|
||
if (platformGameRoleUid && !/^\d+$/.test(platformGameRoleUid)) {
|
||
throw createHttpError('平台游戏角色 UID 格式无效', {
|
||
statusCode: 400,
|
||
errorCode: 'semi_auto_snapshot_platform_role_uid_invalid',
|
||
})
|
||
}
|
||
if (pendingPlatformGameRoleUid && !/^\d+$/.test(pendingPlatformGameRoleUid)) {
|
||
throw createHttpError('待确认平台游戏角色 UID 格式无效', {
|
||
statusCode: 400,
|
||
errorCode: 'semi_auto_snapshot_pending_platform_role_uid_invalid',
|
||
})
|
||
}
|
||
const effectiveHuyaUid = uid || task.huya_uid
|
||
if (platformGameRoleUid && effectiveHuyaUid && platformGameRoleUid === effectiveHuyaUid) {
|
||
throw createHttpError('平台游戏角色 UID 不能复用虎牙账号 UID', {
|
||
statusCode: 400,
|
||
errorCode: 'semi_auto_snapshot_platform_role_uid_reused',
|
||
})
|
||
}
|
||
if (
|
||
pendingPlatformGameRoleUid &&
|
||
effectiveHuyaUid &&
|
||
pendingPlatformGameRoleUid === effectiveHuyaUid
|
||
) {
|
||
throw createHttpError('待确认平台游戏角色 UID 不能复用虎牙账号 UID', {
|
||
statusCode: 400,
|
||
errorCode: 'semi_auto_snapshot_pending_platform_role_uid_reused',
|
||
})
|
||
}
|
||
if (!ROLE_IDENTITY_SOURCES.has(roleIdentitySource)) {
|
||
throw createHttpError('角色身份来源无效', {
|
||
statusCode: 400,
|
||
errorCode: 'semi_auto_snapshot_role_source_invalid',
|
||
})
|
||
}
|
||
if (!VERIFICATION_BASES.has(verificationBasis)) {
|
||
throw createHttpError('角色核验依据无效', {
|
||
statusCode: 400,
|
||
errorCode: 'semi_auto_snapshot_verification_basis_invalid',
|
||
})
|
||
}
|
||
const message = String(input.message ?? input.lastError ?? input.last_error ?? '')
|
||
.trim()
|
||
.slice(0, 1000)
|
||
const isBindAccount = parseSnapshotBoolean(input.isBindAccount ?? input.is_bind_account)
|
||
const isBindRole = parseSnapshotBoolean(input.isBindRole ?? input.is_bind_role)
|
||
const accountChangeBindTime = parseSnapshotNumber(
|
||
input.accountChangeBindTime ?? input.account_change_bind_time,
|
||
)
|
||
const accountChangeBindDay = parseSnapshotNumber(
|
||
input.accountChangeBindDay ?? input.account_change_bind_day,
|
||
)
|
||
const pendingChangeBindTime = parseSnapshotNumber(
|
||
input.pendingChangeBindTime ??
|
||
input.pending_bind_game_change_bind_time ??
|
||
input.pendingBindGameChangeBindTime,
|
||
)
|
||
const pendingChangeBindDay = parseSnapshotNumber(
|
||
input.pendingChangeBindDay ??
|
||
input.pending_bind_game_change_bind_day ??
|
||
input.pendingBindGameChangeBindDay,
|
||
)
|
||
const rebindConfirmState = parseSnapshotStatus(
|
||
input.rebindConfirmState ?? input.rebind_confirm_state ?? 'idle',
|
||
CONFIRM_STATES,
|
||
'换绑确认状态',
|
||
)
|
||
const bindConfirmState = parseSnapshotStatus(
|
||
input.bindConfirmState ?? input.bind_confirm_state ?? 'idle',
|
||
CONFIRM_STATES,
|
||
'绑定确认状态',
|
||
)
|
||
const accountFactsObserved =
|
||
bindGameRole ||
|
||
bindGameRoleToken ||
|
||
platformGameRoleUid ||
|
||
isBindAccount !== undefined ||
|
||
isBindRole !== undefined
|
||
const currentRole = accountFactsObserved
|
||
? {
|
||
isBindAccount: isBindAccount ?? Boolean(bindGameRole),
|
||
isBindRole: isBindRole ?? Boolean(bindGameRole),
|
||
roleName: bindGameRole,
|
||
roleToken: bindGameRoleToken,
|
||
platformRoleUid: platformGameRoleUid,
|
||
channel: bindGameChannel,
|
||
changeBindTime: accountChangeBindTime,
|
||
changeBindDay: accountChangeBindDay,
|
||
}
|
||
: null
|
||
const pendingRole = pendingBindGameRole
|
||
? {
|
||
isBindAccount: false,
|
||
isBindRole: false,
|
||
roleName: pendingBindGameRole,
|
||
roleToken: pendingBindGameRoleToken,
|
||
platformRoleUid: pendingPlatformGameRoleUid,
|
||
channel: pendingBindGameChannel,
|
||
changeBindTime: pendingChangeBindTime,
|
||
changeBindDay: pendingChangeBindDay,
|
||
}
|
||
: null
|
||
const bindingSession: ConnectorBindingSession = {
|
||
sessionId: task.connector_session_id,
|
||
status: bindingStatus,
|
||
qrImage: '',
|
||
qrExpiresAt: '',
|
||
qrUrl: '',
|
||
bindGameAccount,
|
||
bindGameRole,
|
||
bindGameRoleId: legacyRoleId,
|
||
bindGameRoleToken,
|
||
platformGameRoleUid,
|
||
bindGameChannel,
|
||
...(accountFactsObserved && currentRole ? { currentRole } : {}),
|
||
pendingRole,
|
||
pendingBindGameAccount,
|
||
pendingBindGameRole,
|
||
pendingBindGameRoleToken,
|
||
pendingPlatformGameRoleUid,
|
||
pendingBindGameChannel,
|
||
pendingChangeBindTime,
|
||
pendingChangeBindDay,
|
||
roleIdentitySource: roleIdentitySource as NonNullable<
|
||
ConnectorBindingSession['roleIdentitySource']
|
||
>,
|
||
verificationBasis: verificationBasis as NonNullable<
|
||
ConnectorBindingSession['verificationBasis']
|
||
>,
|
||
...(accountFactsObserved ? { hasExistingBinding: currentRole?.isBindAccount === true } : {}),
|
||
rebindRequested:
|
||
parseSnapshotBoolean(input.rebindRequested ?? input.rebind_requested) === true,
|
||
rebindUnchanged:
|
||
parseSnapshotBoolean(input.rebindUnchanged ?? input.rebind_unchanged) === true,
|
||
rebindConfirmState,
|
||
rebindConfirmMessage: String(
|
||
input.rebindConfirmMessage ?? input.rebind_confirm_message ?? '',
|
||
).trim(),
|
||
bindConfirmState,
|
||
bindConfirmMessage: String(
|
||
input.bindConfirmMessage ?? input.bind_confirm_message ?? '',
|
||
).trim(),
|
||
bindEffectDeadlineAt: String(
|
||
input.bindEffectDeadlineAt ?? input.binding_effect_deadline_at ?? '',
|
||
).trim(),
|
||
message,
|
||
}
|
||
|
||
await convergeSemiAutoTaskState(client, task.id, {
|
||
reason: 'connector_login_state_synced',
|
||
actor: 'connector',
|
||
patch: {
|
||
loginStatus,
|
||
// 空值不覆盖已有账号信息(原 CASE WHEN <> '' 语义)。
|
||
...(uid ? { huyaUid: uid } : {}),
|
||
...(nickname ? { platformNickname: nickname } : {}),
|
||
...(loginStatus === 'authenticated' ? { authenticatedAt: SEMI_AUTO_COALESCE_NOW } : {}),
|
||
...(['failed', 'expired'].includes(loginStatus) ? { lastError: message } : {}),
|
||
connectorStateVersion: stateVersion,
|
||
},
|
||
event: {
|
||
eventType: 'connector_login_state_synced',
|
||
emit:
|
||
loginStatus !== task.login_status ||
|
||
uid !== task.huya_uid ||
|
||
nickname !== task.platform_nickname,
|
||
detail: {
|
||
eventId,
|
||
source: 'semi_auto_connector',
|
||
message,
|
||
},
|
||
},
|
||
})
|
||
const bindingResult = await updateBindingTaskWithClient(
|
||
client,
|
||
task.id,
|
||
bindingSession,
|
||
'connector',
|
||
{
|
||
eventType: 'connector_state_synced',
|
||
eventDetail: { eventId, source: 'semi_auto_connector', message },
|
||
},
|
||
)
|
||
return {
|
||
applied: true,
|
||
terminal: false,
|
||
taskId: task.id,
|
||
orderId: task.order_id,
|
||
stateVersion,
|
||
executionStatus: bindingResult.executionStatus,
|
||
}
|
||
})
|
||
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.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.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
|
||
// 平台首页占位值(历史 Mock/配置默认)视为「未配置」,回落到策略默认落地页。
|
||
const targetUrl = resolveBrowserTargetUrl(task.platform, [
|
||
explicitTarget,
|
||
String(fallbackTarget || ''),
|
||
])
|
||
|
||
// 直接下发账号级 CK:不再签发一次性票据,也不做额外的 TTL。
|
||
// 权限边界是后台登录态 + 任务领取人 + 审计日志,与「导出 CK」同一级。
|
||
// 平台与账号必须双重对齐,避免把其它账号的 CK 写进客服浏览器。
|
||
const credential = task.credential_id ? await loadSemiAutoCredential(task.credential_id) : null
|
||
if (credential && credential.platform !== task.platform) {
|
||
throw createHttpError('账号凭证与任务平台不一致,禁止下发', {
|
||
statusCode: 409,
|
||
errorCode: 'semi_auto_credential_platform_mismatch',
|
||
})
|
||
}
|
||
const taskUid = String(task.huya_uid || '').trim()
|
||
const credentialUid = String(credential?.platformUid || '').trim()
|
||
if (taskUid && credentialUid && taskUid !== credentialUid) {
|
||
throw createHttpError('账号凭证与任务账号不一致,请客户重新登录后再注入', {
|
||
statusCode: 409,
|
||
errorCode: 'semi_auto_credential_account_mismatch',
|
||
})
|
||
}
|
||
const cookies = credential ? selectSemiAutoCredentialCookies(credential.cookies, targetUrl) : []
|
||
if (cookies.length === 0) {
|
||
throw createHttpError('账号 CK 不可用,请客户重新登录后再注入浏览器', {
|
||
statusCode: 409,
|
||
errorCode: 'semi_auto_credential_required',
|
||
})
|
||
}
|
||
const payload = {
|
||
platform: task.platform,
|
||
targetUrl,
|
||
cookies: cookies.map((cookie) => ({
|
||
name: cookie.name,
|
||
value: cookie.value,
|
||
domain: cookie.domain,
|
||
path: cookie.path,
|
||
secure: cookie.secure,
|
||
// 平台给出的过期时间要原样带给扩展,不能由扩展统一延成长期有效。
|
||
expiresAt: cookie.expiresAt,
|
||
})),
|
||
}
|
||
|
||
await withTransaction(async (client) => {
|
||
const current = await loadTaskForUpdateWithClient(client, taskId)
|
||
await convergeSemiAutoTaskState(client, taskId, {
|
||
reason: 'browser_session_opened',
|
||
actor: 'admin',
|
||
actorId: String(adminUserId),
|
||
patch: {
|
||
// 不设领取人:任何客服都能操作,这里只记录最近一次操作人。
|
||
assignedAdminUserId: adminUserId,
|
||
executionStatus:
|
||
current.execution_status === 'waiting_operator' ? 'processing' : current.execution_status,
|
||
},
|
||
event: { eventType: 'browser_session_opened', detail: { targetUrl } },
|
||
})
|
||
})
|
||
publishSemiAutoTaskRealtimeChange(taskId, task.order_id)
|
||
return 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',
|
||
})
|
||
}
|
||
const bindingDecision = resolveTaskHuyaBindingDecision(task)
|
||
if (task.platform === 'huya' && !bindingDecision?.canCompleteTask) {
|
||
throw createHttpError('虎牙角色绑定尚未确认,不能完成履约', {
|
||
statusCode: 409,
|
||
errorCode: 'huya_binding_not_confirmed',
|
||
})
|
||
}
|
||
if (task.platform === 'weibo' && !isTaskBindingConfirmed(task)) {
|
||
throw createHttpError('微博角色绑定尚未确认,不能完成履约', {
|
||
statusCode: 409,
|
||
errorCode: 'weibo_binding_not_confirmed',
|
||
})
|
||
}
|
||
|
||
await confirmManualFulfillment(
|
||
{
|
||
orderItemId: task.order_item_id,
|
||
platformKey: task.manual_platform_key,
|
||
...(costFen !== undefined ? { costFen } : {}),
|
||
note: completionNote || '半自动履约完成',
|
||
},
|
||
session,
|
||
{ client },
|
||
)
|
||
|
||
await convergeSemiAutoTaskState(client, taskId, {
|
||
reason: 'task_completed',
|
||
actor: 'admin',
|
||
actorId: String(adminUserId),
|
||
patch: {
|
||
// 不设领取人:任何客服都能完成,这里只记录最近一次操作人。
|
||
assignedAdminUserId: adminUserId,
|
||
executionStatus: 'completed',
|
||
completedQuantity: Number(task.target_quantity || 0),
|
||
completedAt: SEMI_AUTO_NOW,
|
||
completionNote: note,
|
||
externalOrderNo,
|
||
completionEvidence: { screenshots },
|
||
lastError: '',
|
||
},
|
||
event: {
|
||
eventType: 'task_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 convergeSemiAutoTaskState(client, taskId, {
|
||
reason: reason || 'admin_cancelled_without_reason',
|
||
actor: 'admin',
|
||
actorId: String(adminUserId),
|
||
patch: { executionStatus: 'cancelled', lastError: reason },
|
||
event: { eventType: 'task_cancelled' },
|
||
})
|
||
})
|
||
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)
|
||
}
|