重构(半自动履约): 收敛状态同步并拆分任务服务
This commit is contained in:
@@ -0,0 +1,898 @@
|
||||
import { query, withTransaction } from '../../db/client.js'
|
||||
import { getFileAssetByObjectKey } from '../../repositories/file-asset-repo.js'
|
||||
import { createHttpError } from '../../utils/http.js'
|
||||
import type { AdminSession } from '../admin/admin-auth-service.js'
|
||||
import { safeParseJson } from '../admin/admin-query-utils.js'
|
||||
import {
|
||||
confirmManualFulfillment,
|
||||
runManualFulfillmentPostCommit,
|
||||
} from '../finance/manual-fulfillment-service.js'
|
||||
import {
|
||||
buildFileUrl,
|
||||
ORDER_SERVICE_SCREENSHOT_CONTENT_TYPES,
|
||||
type UploadedFileDto,
|
||||
} from '../file-storage/file-storage-service.js'
|
||||
import { publishAdminOrderRealtimeChange } from '../realtime/realtime-event-service.js'
|
||||
import {
|
||||
consumeHuyaBrowserTicket,
|
||||
createHuyaBrowserTicket,
|
||||
revokeHuyaSession,
|
||||
type ConnectorInjectionPayload,
|
||||
type SemiAutoConnectorMode,
|
||||
} from './huya-connector-client.js'
|
||||
import {
|
||||
buildSemiAutoCredentialCookieHeader,
|
||||
loadSemiAutoCredential,
|
||||
} from './semi-auto-credential-service.js'
|
||||
import {
|
||||
consumeWeiboBrowserTicket,
|
||||
createWeiboBrowserTicket,
|
||||
revokeWeiboSession,
|
||||
} from './weibo-connector-client.js'
|
||||
import { WEIBO_TICKET_PREFIX } from './weibo-native/weibo-native-connector.js'
|
||||
import { querySemiAutoTraces } from './semi-auto-trace.js'
|
||||
import {
|
||||
appendTaskEvent,
|
||||
compareBindingRole,
|
||||
ensureConnectorSessionForTask,
|
||||
ensureSemiAutoTasksForAdminList,
|
||||
getBindingForTask,
|
||||
getLoginSessionForTask,
|
||||
loadTask,
|
||||
loadTaskForUpdateWithClient,
|
||||
mapTask,
|
||||
normalizeId,
|
||||
normalizeOrderNo,
|
||||
publishSemiAutoTaskRealtimeChange,
|
||||
resetTaskForCustomerLogin,
|
||||
revokeSessionForTask,
|
||||
TASK_SELECT,
|
||||
updateBindingTask,
|
||||
type BindingStatus,
|
||||
type ExecutionStatus,
|
||||
type LoginStatus,
|
||||
type SemiAutoPlatform,
|
||||
type TaskRow,
|
||||
} from './semi-auto-task-core.js'
|
||||
import { updateLoginTask } from './semi-auto-customer-service.js'
|
||||
|
||||
export async function listAdminSemiAutoTasks(input: Record<string, unknown> = {}) {
|
||||
await ensureSemiAutoTasksForAdminList()
|
||||
const page = Math.max(1, Math.trunc(Number(input.page) || 1))
|
||||
const pageSize = Math.min(100, Math.max(1, Math.trunc(Number(input.pageSize) || 20)))
|
||||
const platform = String(input.platform || '').trim()
|
||||
const status = String(input.status || '').trim()
|
||||
const keyword = String(input.keyword || '').trim()
|
||||
const conditions = ['1 = 1']
|
||||
const params: unknown[] = []
|
||||
if (platform === 'huya' || platform === 'weibo') {
|
||||
params.push(platform)
|
||||
conditions.push(`task.platform = $${params.length}`)
|
||||
}
|
||||
if (
|
||||
[
|
||||
'waiting_customer',
|
||||
'waiting_operator',
|
||||
'processing',
|
||||
'completed',
|
||||
'failed',
|
||||
'cancelled',
|
||||
].includes(status)
|
||||
) {
|
||||
params.push(status)
|
||||
conditions.push(`task.execution_status = $${params.length}`)
|
||||
}
|
||||
if (keyword) {
|
||||
params.push(`%${keyword.replace(/[\\%_]/g, '\\$&')}%`)
|
||||
const p = `$${params.length}`
|
||||
conditions.push(
|
||||
`(o.platform_order_id ILIKE ${p} OR oi.sku_name ILIKE ${p} OR oi.sku_code ILIKE ${p} OR task.huya_uid ILIKE ${p} OR task.bind_game_role ILIKE ${p})`,
|
||||
)
|
||||
}
|
||||
const where = conditions.join(' AND ')
|
||||
const count = await query<{ total: number }>(
|
||||
`SELECT COUNT(*)::int AS total
|
||||
FROM semi_auto_tasks task
|
||||
JOIN orders o ON o.id = task.order_id
|
||||
JOIN order_items oi ON oi.id = task.order_item_id
|
||||
WHERE ${where}`,
|
||||
params,
|
||||
)
|
||||
const listParams = [...params, pageSize, (page - 1) * pageSize]
|
||||
const result = await query<TaskRow>(
|
||||
`${TASK_SELECT}
|
||||
WHERE ${where}
|
||||
ORDER BY
|
||||
CASE task.execution_status
|
||||
WHEN 'waiting_operator' THEN 0
|
||||
WHEN 'waiting_customer' THEN 1
|
||||
WHEN 'processing' THEN 2
|
||||
WHEN 'failed' THEN 3
|
||||
ELSE 4
|
||||
END,
|
||||
task.updated_at DESC,
|
||||
task.id DESC
|
||||
LIMIT $${listParams.length - 1} OFFSET $${listParams.length}`,
|
||||
listParams,
|
||||
)
|
||||
return {
|
||||
items: result.rows.map(mapTask),
|
||||
pagination: { page, pageSize, total: Number(count.rows[0]?.total || 0) },
|
||||
}
|
||||
}
|
||||
|
||||
export async function getAdminSemiAutoTask(taskIdInput: unknown) {
|
||||
const task = await loadTask(normalizeId(taskIdInput))
|
||||
const events = await query<{
|
||||
id: number
|
||||
event_type: string
|
||||
actor_type: string
|
||||
actor_id: string
|
||||
detail_json: Record<string, unknown>
|
||||
created_at: string
|
||||
}>(
|
||||
`SELECT id, event_type, actor_type, actor_id, detail_json, created_at
|
||||
FROM semi_auto_task_events
|
||||
WHERE task_id = $1
|
||||
ORDER BY id DESC
|
||||
LIMIT 200`,
|
||||
[task.id],
|
||||
)
|
||||
return {
|
||||
task: mapTask(task),
|
||||
// 管理端详情直接复用与客户页相同的三项比对口径,避免出现第二套判定。
|
||||
comparison: compareBindingRole(task, {
|
||||
bindGameRole: task.bind_game_role,
|
||||
bindGameRoleId: task.bind_game_role_id,
|
||||
bindGameChannel: task.bind_game_channel,
|
||||
}),
|
||||
events: events.rows.map((event) => ({
|
||||
id: Number(event.id),
|
||||
eventType: event.event_type,
|
||||
actorType: event.actor_type,
|
||||
actorId: event.actor_id,
|
||||
detail: event.detail_json || {},
|
||||
createdAt: event.created_at,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
type SemiAutoTaskEventRow = {
|
||||
id: number
|
||||
event_type: string
|
||||
actor_type: string
|
||||
actor_id: string
|
||||
from_login_status: string | null
|
||||
to_login_status: string | null
|
||||
from_binding_status: string | null
|
||||
to_binding_status: string | null
|
||||
from_execution_status: string | null
|
||||
to_execution_status: string | null
|
||||
detail_json: Record<string, unknown>
|
||||
created_at: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 运营端「历史」:任务状态流转事件 + 全链路报文(本系统入站 + 外部平台出站)。
|
||||
* 报文只读,不做任何写操作;Cookie / Token 已在落库前脱敏。
|
||||
*/
|
||||
export async function getAdminSemiAutoTaskHistory(
|
||||
taskIdInput: unknown,
|
||||
input: Record<string, unknown> = {},
|
||||
) {
|
||||
const task = await loadTask(normalizeId(taskIdInput))
|
||||
const eventCount = await query<{ total: number }>(
|
||||
`SELECT COUNT(*)::int AS total FROM semi_auto_task_events WHERE task_id = $1`,
|
||||
[task.id],
|
||||
)
|
||||
const events = await query<SemiAutoTaskEventRow>(
|
||||
`SELECT * FROM (
|
||||
SELECT id, event_type, actor_type, actor_id,
|
||||
from_login_status, to_login_status,
|
||||
from_binding_status, to_binding_status,
|
||||
from_execution_status, to_execution_status,
|
||||
detail_json, created_at
|
||||
FROM semi_auto_task_events
|
||||
WHERE task_id = $1
|
||||
ORDER BY id DESC
|
||||
LIMIT 500
|
||||
) recent
|
||||
ORDER BY id ASC`,
|
||||
[task.id],
|
||||
)
|
||||
const traces = await querySemiAutoTraces(task.id, {
|
||||
page: Number(input.page) || 1,
|
||||
pageSize: Number(input.pageSize) || 50,
|
||||
channel: String(input.channel || '').trim(),
|
||||
status: String(input.status || '').trim(),
|
||||
requestId: String(input.requestId || '').trim(),
|
||||
keyword: String(input.keyword || '').trim(),
|
||||
})
|
||||
return {
|
||||
task: mapTask(task),
|
||||
events: events.rows.map((event) => ({
|
||||
id: Number(event.id),
|
||||
eventType: event.event_type,
|
||||
actorType: event.actor_type,
|
||||
actorId: event.actor_id,
|
||||
fromLoginStatus: event.from_login_status,
|
||||
toLoginStatus: event.to_login_status,
|
||||
fromBindingStatus: event.from_binding_status,
|
||||
toBindingStatus: event.to_binding_status,
|
||||
fromExecutionStatus: event.from_execution_status,
|
||||
toExecutionStatus: event.to_execution_status,
|
||||
detail: event.detail_json || {},
|
||||
createdAt: event.created_at,
|
||||
})),
|
||||
eventTotal: Number(eventCount.rows[0]?.total || 0),
|
||||
traces,
|
||||
}
|
||||
}
|
||||
|
||||
export async function exportAdminSemiAutoCredential(taskIdInput: unknown) {
|
||||
const task = await loadTask(normalizeId(taskIdInput))
|
||||
if (!task.credential_id) {
|
||||
throw createHttpError('当前任务尚未保存账号 CK', {
|
||||
statusCode: 404,
|
||||
errorCode: 'semi_auto_credential_not_found',
|
||||
})
|
||||
}
|
||||
const credential = await loadSemiAutoCredential(task.credential_id)
|
||||
if (!credential || credential.platform !== task.platform) {
|
||||
throw createHttpError('账号 CK 不存在或与任务平台不一致', {
|
||||
statusCode: 404,
|
||||
errorCode: 'semi_auto_credential_not_found',
|
||||
})
|
||||
}
|
||||
const config = safeParseJson(task.semi_auto_config_json)
|
||||
const targets = Array.isArray(config.browserTargets) ? config.browserTargets : []
|
||||
const configuredTarget = String(
|
||||
targets.find((item): item is { url?: string } => Boolean(item && typeof item === 'object'))
|
||||
?.url || '',
|
||||
).trim()
|
||||
const targetUrl = /^https:\/\//i.test(configuredTarget)
|
||||
? configuredTarget
|
||||
: credential.platform === 'weibo'
|
||||
? 'https://weibo.com/'
|
||||
: 'https://www.huya.com/'
|
||||
const cookieHeader = targetUrl
|
||||
? buildSemiAutoCredentialCookieHeader(credential.cookies, targetUrl)
|
||||
: ''
|
||||
return {
|
||||
credentialId: credential.id,
|
||||
platform: credential.platform,
|
||||
platformUid: credential.platformUid,
|
||||
nickname: credential.nickname,
|
||||
source: credential.source,
|
||||
status: credential.status,
|
||||
updatedAt: credential.updatedAt,
|
||||
targetUrl,
|
||||
cookieHeader,
|
||||
cookies: credential.cookies,
|
||||
}
|
||||
}
|
||||
|
||||
export async function claimAdminSemiAutoTask(taskIdInput: unknown, session: AdminSession) {
|
||||
const taskId = normalizeId(taskIdInput)
|
||||
const adminUserId = Number(session.userId || 0)
|
||||
let orderId = 0
|
||||
await withTransaction(async (client) => {
|
||||
const task = await loadTaskForUpdateWithClient(client, taskId)
|
||||
if (task.execution_status === 'completed' || task.execution_status === 'cancelled') {
|
||||
throw createHttpError('当前任务已结束,不能领取', {
|
||||
statusCode: 409,
|
||||
errorCode:
|
||||
task.execution_status === 'completed'
|
||||
? 'semi_auto_task_completed'
|
||||
: 'semi_auto_task_cancelled',
|
||||
})
|
||||
}
|
||||
if (task.assigned_admin_user_id && Number(task.assigned_admin_user_id) !== adminUserId) {
|
||||
throw createHttpError('该任务已被其他客服领取', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_task_claimed',
|
||||
})
|
||||
}
|
||||
orderId = Number(task.order_id)
|
||||
await client.query(
|
||||
`UPDATE semi_auto_tasks
|
||||
SET assigned_admin_user_id = $2, updated_at = NOW()
|
||||
WHERE id = $1`,
|
||||
[taskId, adminUserId],
|
||||
)
|
||||
await appendTaskEvent(client, taskId, {
|
||||
eventType: 'task_claimed',
|
||||
actorType: 'admin',
|
||||
actorId: String(adminUserId),
|
||||
})
|
||||
})
|
||||
publishSemiAutoTaskRealtimeChange(taskId, orderId)
|
||||
return getAdminSemiAutoTask(taskId)
|
||||
}
|
||||
|
||||
export async function syncAdminSemiAutoTask(taskIdInput: unknown) {
|
||||
const taskId = normalizeId(taskIdInput)
|
||||
let task = await ensureConnectorSessionForTask(await loadTask(taskId))
|
||||
if (!task.connector_session_id) return getAdminSemiAutoTask(taskId)
|
||||
if (
|
||||
task.login_status !== 'authenticated' &&
|
||||
task.login_status !== 'failed' &&
|
||||
task.login_status !== 'expired'
|
||||
) {
|
||||
const login = await getLoginSessionForTask(task, task.connector_session_id)
|
||||
await updateLoginTask(task, login, 'connector')
|
||||
task = await loadTask(taskId)
|
||||
}
|
||||
return getAdminSemiAutoTask(taskId)
|
||||
}
|
||||
|
||||
/**
|
||||
* 低频兜底对账:只处理活跃且有 Connector 会话的任务,并且每次限量。
|
||||
* 正常状态变化由客户操作、Connector 回调和后台操作即时推进,这里只补漏。
|
||||
*/
|
||||
export async function reconcileSemiAutoTaskStates(limitInput = 100) {
|
||||
const limit = Math.min(500, Math.max(1, Math.trunc(Number(limitInput) || 100)))
|
||||
const candidates = await query<TaskRow>(
|
||||
`${TASK_SELECT}
|
||||
WHERE task.execution_status NOT IN ('completed', 'cancelled')
|
||||
AND task.connector_session_id <> ''
|
||||
ORDER BY task.updated_at ASC, task.id ASC
|
||||
LIMIT $1`,
|
||||
[limit],
|
||||
)
|
||||
let checked = 0
|
||||
let updated = 0
|
||||
for (const candidate of candidates.rows) {
|
||||
try {
|
||||
let task = await ensureConnectorSessionForTask(candidate)
|
||||
if (!task.connector_session_id) continue
|
||||
checked += 1
|
||||
if (
|
||||
task.login_status !== 'authenticated' &&
|
||||
task.login_status !== 'failed' &&
|
||||
task.login_status !== 'expired'
|
||||
) {
|
||||
const login = await getLoginSessionForTask(task, task.connector_session_id)
|
||||
await updateLoginTask(task, login, 'connector')
|
||||
task = await loadTask(task.id)
|
||||
updated += 1
|
||||
}
|
||||
if (
|
||||
task.platform === 'huya' &&
|
||||
task.login_status === 'authenticated' &&
|
||||
['qr_pending', 'scanned', 'role_ready'].includes(task.binding_status)
|
||||
) {
|
||||
const binding = await getBindingForTask(task, task.connector_session_id)
|
||||
await updateBindingTask(task, binding, 'connector')
|
||||
updated += 1
|
||||
}
|
||||
} catch (error) {
|
||||
const detail = error instanceof Error ? error.message : String(error)
|
||||
await query(
|
||||
`UPDATE semi_auto_tasks
|
||||
SET last_error = $2, updated_at = NOW()
|
||||
WHERE id = $1
|
||||
AND execution_status NOT IN ('completed', 'cancelled')`,
|
||||
[candidate.id, detail.slice(0, 1000)],
|
||||
).catch(() => undefined)
|
||||
}
|
||||
}
|
||||
return { checked, updated }
|
||||
}
|
||||
|
||||
const LOGIN_STATUSES = new Set<LoginStatus>([
|
||||
'waiting_login',
|
||||
'qr_pending',
|
||||
'scanned',
|
||||
'authenticated',
|
||||
'failed',
|
||||
'expired',
|
||||
])
|
||||
const BINDING_STATUSES = new Set<BindingStatus>([
|
||||
'not_started',
|
||||
'qr_pending',
|
||||
'scanned',
|
||||
'role_ready',
|
||||
'confirmed',
|
||||
'failed',
|
||||
'expired',
|
||||
])
|
||||
|
||||
function parseSnapshotStatus<T extends string>(value: unknown, allowed: Set<T>, label: string): T {
|
||||
const status = String(value || '').trim() as T
|
||||
if (!allowed.has(status)) {
|
||||
throw createHttpError(`${label}无效`, {
|
||||
statusCode: 400,
|
||||
errorCode: 'semi_auto_snapshot_status_invalid',
|
||||
})
|
||||
}
|
||||
return status
|
||||
}
|
||||
|
||||
/**
|
||||
* 外部 Connector 的幂等状态快照入口。
|
||||
*
|
||||
* Connector 只提交登录/绑定观察结果,不直接声明业务执行完成;执行状态仍由订单系统
|
||||
* 根据登录、绑定和人工确认规则推导。重复 eventId 由 integration_inbox 去重。
|
||||
*/
|
||||
export async function applySemiAutoTaskStateSnapshot(
|
||||
input: Record<string, unknown>,
|
||||
options: { eventId?: string; eventType?: string } = {},
|
||||
) {
|
||||
const eventId = String(options.eventId || input.eventId || '').trim()
|
||||
const taskId = normalizeId(input.taskId ?? input.task_id)
|
||||
const orderNo = normalizeOrderNo(input.orderNo ?? input.order_no)
|
||||
const loginStatus = parseSnapshotStatus(
|
||||
input.loginStatus ?? input.login_status,
|
||||
LOGIN_STATUSES,
|
||||
'登录状态',
|
||||
)
|
||||
const bindingStatus = parseSnapshotStatus(
|
||||
input.bindingStatus ?? input.binding_status,
|
||||
BINDING_STATUSES,
|
||||
'绑定状态',
|
||||
)
|
||||
if (!eventId) {
|
||||
throw createHttpError('状态快照事件编号不能为空', {
|
||||
statusCode: 400,
|
||||
errorCode: 'semi_auto_snapshot_event_id_required',
|
||||
})
|
||||
}
|
||||
|
||||
const result = await withTransaction(async (client) => {
|
||||
const claimed = await client.query(
|
||||
`INSERT INTO integration_inbox (event_id, source, event_type, received_at, processed_at)
|
||||
VALUES ($1, 'semi_auto_connector', $2, NOW(), NOW())
|
||||
ON CONFLICT (event_id) DO NOTHING
|
||||
RETURNING event_id`,
|
||||
[eventId, String(options.eventType || 'semi_auto.task_state')],
|
||||
)
|
||||
if (claimed.rowCount === 0) return { applied: false, terminal: false }
|
||||
|
||||
const task = await loadTaskForUpdateWithClient(client, taskId)
|
||||
if (task.platform_order_id !== orderNo) {
|
||||
throw createHttpError('状态快照与任务订单号不一致', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_snapshot_order_mismatch',
|
||||
})
|
||||
}
|
||||
if (task.execution_status === 'completed' || task.execution_status === 'cancelled') {
|
||||
return { applied: false, terminal: true }
|
||||
}
|
||||
|
||||
const executionStatus: ExecutionStatus =
|
||||
loginStatus === 'authenticated' &&
|
||||
(task.platform === 'weibo' || bindingStatus === 'confirmed')
|
||||
? 'waiting_operator'
|
||||
: 'waiting_customer'
|
||||
const uid = String(input.huyaUid ?? input.huya_uid ?? '').trim()
|
||||
const nickname = String(input.platformNickname ?? input.platform_nickname ?? '').trim()
|
||||
const bindGameAccount = String(input.bindGameAccount ?? input.bind_game_account ?? '').trim()
|
||||
const bindGameRole = String(input.bindGameRole ?? input.bind_game_role ?? '').trim()
|
||||
const bindGameRoleId = String(input.bindGameRoleId ?? input.bind_game_role_id ?? '').trim()
|
||||
const bindGameChannel = String(input.bindGameChannel ?? input.bind_game_channel ?? '').trim()
|
||||
const message = String(input.message ?? input.lastError ?? input.last_error ?? '')
|
||||
.trim()
|
||||
.slice(0, 1000)
|
||||
|
||||
await client.query(
|
||||
`UPDATE semi_auto_tasks
|
||||
SET login_status = $2,
|
||||
binding_status = $3,
|
||||
execution_status = $4,
|
||||
huya_uid = CASE WHEN $5 <> '' THEN $5 ELSE huya_uid END,
|
||||
platform_nickname = CASE WHEN $6 <> '' THEN $6 ELSE platform_nickname END,
|
||||
bind_game_account = CASE WHEN $7 <> '' THEN $7 ELSE bind_game_account END,
|
||||
bind_game_role = CASE WHEN $8 <> '' THEN $8 ELSE bind_game_role END,
|
||||
bind_game_role_id = CASE WHEN $9 <> '' THEN $9 ELSE bind_game_role_id END,
|
||||
bind_game_channel = CASE WHEN $10 <> '' THEN $10 ELSE bind_game_channel END,
|
||||
authenticated_at = CASE
|
||||
WHEN $2 = 'authenticated' THEN COALESCE(authenticated_at, NOW())
|
||||
ELSE authenticated_at
|
||||
END,
|
||||
bound_at = CASE
|
||||
WHEN $3 IN ('role_ready', 'confirmed') THEN COALESCE(bound_at, NOW())
|
||||
ELSE bound_at
|
||||
END,
|
||||
last_error = CASE WHEN $2 IN ('failed', 'expired') OR $3 IN ('failed', 'expired')
|
||||
THEN $11 ELSE '' END,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1`,
|
||||
[
|
||||
task.id,
|
||||
loginStatus,
|
||||
bindingStatus,
|
||||
executionStatus,
|
||||
uid,
|
||||
nickname,
|
||||
bindGameAccount,
|
||||
bindGameRole,
|
||||
bindGameRoleId,
|
||||
bindGameChannel,
|
||||
message,
|
||||
],
|
||||
)
|
||||
if (
|
||||
loginStatus !== task.login_status ||
|
||||
bindingStatus !== task.binding_status ||
|
||||
executionStatus !== task.execution_status
|
||||
) {
|
||||
await appendTaskEvent(client, task.id, {
|
||||
eventType: 'connector_state_synced',
|
||||
actorType: 'connector',
|
||||
fromLoginStatus: task.login_status,
|
||||
toLoginStatus: loginStatus,
|
||||
fromBindingStatus: task.binding_status,
|
||||
toBindingStatus: bindingStatus,
|
||||
fromExecutionStatus: task.execution_status,
|
||||
toExecutionStatus: executionStatus,
|
||||
detail: {
|
||||
eventId,
|
||||
source: 'semi_auto_connector',
|
||||
message,
|
||||
},
|
||||
})
|
||||
}
|
||||
return {
|
||||
applied: true,
|
||||
terminal: false,
|
||||
taskId: task.id,
|
||||
orderId: task.order_id,
|
||||
}
|
||||
})
|
||||
if (result.applied && result.taskId && result.orderId) {
|
||||
publishSemiAutoTaskRealtimeChange(result.taskId, result.orderId)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
export async function requestAdminSemiAutoCustomerReauth(
|
||||
taskIdInput: unknown,
|
||||
session: AdminSession,
|
||||
) {
|
||||
const taskId = normalizeId(taskIdInput)
|
||||
const task = await loadTask(taskId)
|
||||
if (task.execution_status === 'completed') {
|
||||
throw createHttpError('已完成任务不能重新授权', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_task_completed',
|
||||
})
|
||||
}
|
||||
if (task.execution_status === 'cancelled') {
|
||||
throw createHttpError('已取消任务不能重新授权', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_task_cancelled',
|
||||
})
|
||||
}
|
||||
const adminUserId = Number(session.userId || 0)
|
||||
if (task.assigned_admin_user_id && Number(task.assigned_admin_user_id) !== adminUserId) {
|
||||
throw createHttpError('该任务已被其他客服领取', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_task_claimed',
|
||||
})
|
||||
}
|
||||
if (task.connector_session_id) {
|
||||
await revokeSessionForTask(task, task.connector_session_id).catch(() => undefined)
|
||||
}
|
||||
await resetTaskForCustomerLogin(task, {
|
||||
actorType: 'admin',
|
||||
actorId: String(adminUserId),
|
||||
reason: '客服已重新发送授权链接,等待客户重新登录',
|
||||
eventType: 'customer_reauth_requested',
|
||||
})
|
||||
return getAdminSemiAutoTask(taskId)
|
||||
}
|
||||
|
||||
export async function createAdminBrowserSession(
|
||||
taskIdInput: unknown,
|
||||
targetUrlInput: unknown,
|
||||
session: AdminSession,
|
||||
) {
|
||||
const taskId = normalizeId(taskIdInput)
|
||||
const task = await ensureConnectorSessionForTask(await loadTask(taskId))
|
||||
const adminUserId = Number(session.userId || 0)
|
||||
if (task.assigned_admin_user_id && Number(task.assigned_admin_user_id) !== adminUserId) {
|
||||
throw createHttpError('该任务已被其他客服领取', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_task_claimed',
|
||||
})
|
||||
}
|
||||
if (!task.connector_session_id || task.login_status !== 'authenticated') {
|
||||
throw createHttpError('客户尚未完成登录,或登录会话已失效', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_login_required',
|
||||
})
|
||||
}
|
||||
const config = safeParseJson(task.semi_auto_config_json)
|
||||
const targets = Array.isArray(config.browserTargets) ? config.browserTargets : []
|
||||
const explicitTarget = String(targetUrlInput || '').trim()
|
||||
const fallbackTarget = targets.find((item): item is { url?: string } =>
|
||||
Boolean(item && typeof item === 'object'),
|
||||
)?.url
|
||||
const targetUrl = explicitTarget || String(fallbackTarget || '')
|
||||
const ticket =
|
||||
task.platform === 'weibo'
|
||||
? await createWeiboBrowserTicket(
|
||||
{ sessionId: task.connector_session_id, targetUrl },
|
||||
task.connector_mode,
|
||||
)
|
||||
: await createHuyaBrowserTicket(
|
||||
{
|
||||
sessionId: task.connector_session_id,
|
||||
targetUrl,
|
||||
},
|
||||
task.connector_mode,
|
||||
)
|
||||
await withTransaction(async (client) => {
|
||||
await client.query(
|
||||
`UPDATE semi_auto_tasks
|
||||
SET assigned_admin_user_id = COALESCE(assigned_admin_user_id, $2),
|
||||
execution_status = CASE WHEN execution_status = 'waiting_operator' THEN 'processing' ELSE execution_status END,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1`,
|
||||
[taskId, adminUserId],
|
||||
)
|
||||
await appendTaskEvent(client, taskId, {
|
||||
eventType: 'browser_session_opened',
|
||||
actorType: 'admin',
|
||||
actorId: String(adminUserId),
|
||||
detail: { targetUrl },
|
||||
})
|
||||
})
|
||||
publishSemiAutoTaskRealtimeChange(taskId, task.order_id)
|
||||
return ticket
|
||||
}
|
||||
|
||||
/**
|
||||
* 票据内的 targetUrl 只服务于创建阶段的 Cookie 序列化与审计;
|
||||
* 下发给扩展时清空,指定平台页统一由前端占位页在注入成功后打开,
|
||||
* 这样扩展只写 Cookie,不会再额外打开一个目标页标签。
|
||||
*/
|
||||
export function buildExtensionInjectionPayload(
|
||||
payload: ConnectorInjectionPayload,
|
||||
): ConnectorInjectionPayload {
|
||||
return { ...payload, targetUrl: '' }
|
||||
}
|
||||
|
||||
export async function consumeSemiAutoInjectionTicket(ticketInput: unknown) {
|
||||
const ticket = String(ticketInput || '').trim()
|
||||
if (!ticket) {
|
||||
throw createHttpError('注入票据无效', {
|
||||
statusCode: 400,
|
||||
errorCode: 'semi_auto_injection_ticket_invalid',
|
||||
})
|
||||
}
|
||||
const payload = ticket.startsWith(WEIBO_TICKET_PREFIX)
|
||||
? await consumeWeiboBrowserTicket(ticket)
|
||||
: await consumeHuyaBrowserTicket(ticket)
|
||||
return buildExtensionInjectionPayload(payload)
|
||||
}
|
||||
|
||||
async function resolveCompletionEvidence(
|
||||
screenshots: unknown,
|
||||
session: AdminSession,
|
||||
): Promise<UploadedFileDto[]> {
|
||||
const files = Array.isArray(screenshots) ? screenshots : []
|
||||
const uploaderId = String(session.userId || session.username || '')
|
||||
const result: UploadedFileDto[] = []
|
||||
for (const item of files.slice(0, 10)) {
|
||||
const source = item && typeof item === 'object' ? (item as Record<string, unknown>) : {}
|
||||
const objectKey = String(source.objectKey || source.object_key || '').trim()
|
||||
if (!objectKey) continue
|
||||
const asset = await getFileAssetByObjectKey(objectKey)
|
||||
if (
|
||||
!asset ||
|
||||
asset.status !== 'active' ||
|
||||
asset.uploader_type !== 'admin' ||
|
||||
asset.uploader_id !== uploaderId ||
|
||||
asset.scene !== 'semi-auto-evidence' ||
|
||||
!ORDER_SERVICE_SCREENSHOT_CONTENT_TYPES.has(String(asset.content_type || ''))
|
||||
) {
|
||||
throw createHttpError('完成截图无效,请重新上传', {
|
||||
statusCode: 400,
|
||||
errorCode: 'semi_auto_evidence_invalid',
|
||||
})
|
||||
}
|
||||
result.push({
|
||||
objectKey: asset.object_key,
|
||||
url: buildFileUrl(asset.object_key),
|
||||
thumbnailUrl: buildFileUrl(asset.thumbnail_object_key || asset.object_key),
|
||||
mediumUrl: buildFileUrl(asset.medium_object_key || asset.object_key),
|
||||
filename: asset.original_filename,
|
||||
contentType: asset.content_type,
|
||||
size: Number(asset.size_bytes || 0),
|
||||
})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
export async function completeAdminSemiAutoTask(
|
||||
taskIdInput: unknown,
|
||||
payload: Record<string, unknown>,
|
||||
session: AdminSession,
|
||||
) {
|
||||
const taskId = normalizeId(taskIdInput)
|
||||
let current = await loadTask(taskId)
|
||||
if (current.execution_status === 'completed') return getAdminSemiAutoTask(taskId)
|
||||
current = await ensureConnectorSessionForTask(current)
|
||||
if (current.execution_status === 'completed') return getAdminSemiAutoTask(taskId)
|
||||
if (current.execution_status === 'cancelled') {
|
||||
throw createHttpError('任务已取消,不能完成', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_task_cancelled',
|
||||
})
|
||||
}
|
||||
const screenshots = await resolveCompletionEvidence(payload.screenshots || [], session)
|
||||
const note = String(payload.note || '')
|
||||
.trim()
|
||||
.slice(0, 1000)
|
||||
const externalOrderNo = String(payload.externalOrderNo || payload.external_order_no || '')
|
||||
.trim()
|
||||
.slice(0, 200)
|
||||
const costFenRaw = Number(payload.costFen ?? payload.cost_fen)
|
||||
const costFen =
|
||||
Number.isFinite(costFenRaw) && costFenRaw >= 0 ? Math.trunc(costFenRaw) : undefined
|
||||
const completionNote = [note, externalOrderNo ? `外部单号:${externalOrderNo}` : '']
|
||||
.filter(Boolean)
|
||||
.join(';')
|
||||
const adminUserId = Number(session.userId || 0)
|
||||
|
||||
// 人工财务确认、履约状态和半自动任务完成必须同事务提交:
|
||||
// 任何任务更新失败都会回滚成本快照、钱包扣减和履约状态,避免“已扣钱但任务未完成”。
|
||||
const completion = await withTransaction(async (client) => {
|
||||
const task = await loadTaskForUpdateWithClient(client, taskId)
|
||||
if (task.execution_status === 'completed') {
|
||||
return { task, completedNow: false }
|
||||
}
|
||||
if (task.execution_status === 'cancelled') {
|
||||
throw createHttpError('任务已取消,不能完成', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_task_cancelled',
|
||||
})
|
||||
}
|
||||
if (
|
||||
task.login_status !== 'authenticated' ||
|
||||
!task.credential_id ||
|
||||
task.credential_status === 'invalid' ||
|
||||
task.credential_status === 'error'
|
||||
) {
|
||||
throw createHttpError('客户账号 CK 尚未就绪或已失效,不能完成履约', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_credential_required',
|
||||
})
|
||||
}
|
||||
if (task.assigned_admin_user_id && Number(task.assigned_admin_user_id) !== adminUserId) {
|
||||
throw createHttpError('该任务已被其他客服领取', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_task_claimed',
|
||||
})
|
||||
}
|
||||
|
||||
await confirmManualFulfillment(
|
||||
{
|
||||
orderItemId: task.order_item_id,
|
||||
platformKey: task.manual_platform_key,
|
||||
...(costFen !== undefined ? { costFen } : {}),
|
||||
note: completionNote || '半自动履约完成',
|
||||
},
|
||||
session,
|
||||
{ client },
|
||||
)
|
||||
|
||||
const updated = await client.query<{ id: number }>(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET assigned_admin_user_id = COALESCE(assigned_admin_user_id, $2),
|
||||
execution_status = 'completed',
|
||||
completed_quantity = target_quantity,
|
||||
completed_at = NOW(),
|
||||
completion_note = $3,
|
||||
external_order_no = $4,
|
||||
completion_evidence_json = $5::jsonb,
|
||||
last_error = '',
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
RETURNING id
|
||||
`,
|
||||
[taskId, adminUserId, note, externalOrderNo, JSON.stringify({ screenshots })],
|
||||
)
|
||||
if (!updated.rows[0]) {
|
||||
throw createHttpError('半自动履约任务状态更新失败', {
|
||||
statusCode: 500,
|
||||
errorCode: 'semi_auto_task_completion_failed',
|
||||
})
|
||||
}
|
||||
await appendTaskEvent(client, taskId, {
|
||||
eventType: 'task_completed',
|
||||
actorType: 'admin',
|
||||
actorId: String(adminUserId),
|
||||
fromExecutionStatus: task.execution_status,
|
||||
toExecutionStatus: 'completed',
|
||||
detail: {
|
||||
note,
|
||||
externalOrderNo,
|
||||
screenshotCount: screenshots.length,
|
||||
},
|
||||
})
|
||||
return { task, completedNow: true }
|
||||
})
|
||||
|
||||
if (!completion.completedNow) {
|
||||
return getAdminSemiAutoTask(taskId)
|
||||
}
|
||||
await runManualFulfillmentPostCommit(completion.task.order_item_id)
|
||||
if (completion.task.connector_session_id) {
|
||||
await revokeSessionForTask(completion.task, completion.task.connector_session_id).catch(
|
||||
() => undefined,
|
||||
)
|
||||
}
|
||||
publishAdminOrderRealtimeChange(Number(completion.task.order_id))
|
||||
publishSemiAutoTaskRealtimeChange(taskId, completion.task.order_id)
|
||||
return getAdminSemiAutoTask(taskId)
|
||||
}
|
||||
|
||||
export async function cancelAdminSemiAutoTask(
|
||||
taskIdInput: unknown,
|
||||
payload: Record<string, unknown>,
|
||||
session: AdminSession,
|
||||
) {
|
||||
const taskId = normalizeId(taskIdInput)
|
||||
const reason = String(payload.reason || '')
|
||||
.trim()
|
||||
.slice(0, 500)
|
||||
const adminUserId = Number(session.userId || 0)
|
||||
let orderId = 0
|
||||
const connector: {
|
||||
sessionId: string
|
||||
mode: SemiAutoConnectorMode
|
||||
platform: SemiAutoPlatform
|
||||
} = {
|
||||
sessionId: '',
|
||||
mode: 'embedded',
|
||||
platform: 'huya',
|
||||
}
|
||||
await withTransaction(async (client) => {
|
||||
const task = await loadTaskForUpdateWithClient(client, taskId)
|
||||
orderId = Number(task.order_id)
|
||||
connector.sessionId = task.connector_session_id
|
||||
connector.mode = task.connector_mode
|
||||
connector.platform = task.platform
|
||||
if (task.execution_status === 'completed') {
|
||||
throw createHttpError('已完成任务不能取消', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_task_completed',
|
||||
})
|
||||
}
|
||||
if (task.execution_status === 'cancelled') {
|
||||
return
|
||||
}
|
||||
await client.query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET execution_status = 'cancelled',
|
||||
last_error = $2,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[taskId, reason],
|
||||
)
|
||||
await appendTaskEvent(client, taskId, {
|
||||
eventType: 'task_cancelled',
|
||||
actorType: 'admin',
|
||||
actorId: String(adminUserId),
|
||||
fromExecutionStatus: task.execution_status,
|
||||
toExecutionStatus: 'cancelled',
|
||||
detail: { reason },
|
||||
})
|
||||
})
|
||||
if (connector.sessionId) {
|
||||
const revoke =
|
||||
connector.platform === 'weibo'
|
||||
? revokeWeiboSession(connector.sessionId, connector.mode)
|
||||
: revokeHuyaSession(connector.sessionId, connector.mode)
|
||||
await revoke.catch(() => undefined)
|
||||
}
|
||||
publishAdminOrderRealtimeChange(orderId)
|
||||
publishSemiAutoTaskRealtimeChange(taskId, orderId)
|
||||
return getAdminSemiAutoTask(taskId)
|
||||
}
|
||||
Reference in New Issue
Block a user