- 迁移 191:semi_auto_tasks 增加客户游戏主页截图 5 个正式字段
(object_key / url / thumbnail_url / filename / uploaded_at)。
- 新增 POST /customer-fulfillment/:orderNo/tasks/:taskId/homepage-screenshot
(writeLimit + 单文件上传),场景 semi-auto-homepage-screenshot、
归属 semi-auto-task-{taskId},与斗鱼同一套 file_assets 校验口径。
- 保存资料改为四要素必填:区服 / 游戏角色 UID / 角色名 / 游戏主页截图;
截图须在同一事务内校验归属与类型,缺失或越权直接 400。
- 游戏角色 UID 改为 1..20 位纯数字校验(semi_auto_profile_role_id_invalid);
角色名新增「不得混入 UID/区服/登录方式」校验,规则与斗鱼一致并在后端再实现一份。
- 客户页:UID 提示改为「请输入游戏角色 UID,纯数字uid」、只接受数字输入并实时提示;
角色名加斗鱼同款提示与混入警告;新增「游戏主页截图(必填)」上传区 + 示例图 + 说明文案;
已保存截图按 DTO 的 objectKey 回填预览,不再从文件链接反解。
- 角色名规则收敛到共享 game-role-name(删除 douyu-role-name 转发层,斗鱼页面与文案不变)。
- 「资料已完成」判断仍只看已保存三要素:截图在保存时强制,
避免本次改造前已填好资料的历史任务被卡回第一步。
- 权威文档同步虎牙资料四要素、UID 纯数字、角色名混入校验与截图用途,并补迁移 191 记录。
1882 lines
71 KiB
TypeScript
1882 lines
71 KiB
TypeScript
/**
|
|
* 半自动任务真实 PostgreSQL 集成测试。
|
|
*
|
|
* SEMI_AUTO_TASK_TEST_DATABASE_URL=postgres://... \
|
|
* npx tsx --test src/services/semi-auto/semi-auto-task.integration.test.ts
|
|
*/
|
|
import assert from 'node:assert/strict'
|
|
import { randomUUID } from 'node:crypto'
|
|
import test from 'node:test'
|
|
|
|
const TEST_DATABASE_URL = String(process.env.SEMI_AUTO_TASK_TEST_DATABASE_URL || '').trim()
|
|
|
|
/** 断言领域服务抛出指定错误码,避免只匹配中文提示。 */
|
|
async function expectErrorCode(fn: () => Promise<unknown>, errorCode: string) {
|
|
await assert.rejects(fn, (error: { errorCode?: string }) => {
|
|
assert.equal(error.errorCode, errorCode)
|
|
return true
|
|
})
|
|
}
|
|
|
|
/** 1x1 PNG:集成测试只需要合法图片内容,不需要真实截图。 */
|
|
const TEST_SCREENSHOT_PNG = Buffer.from(
|
|
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',
|
|
'base64',
|
|
)
|
|
|
|
/**
|
|
* 造一张合法的客户游戏主页截图资产。
|
|
*
|
|
* 优先走生产同一条 `uploadFileAsset`;集成测试环境没有对象存储时,退化为直接写同一张
|
|
* `file_assets` 台账行——被测路径是资料保存时的台账归属校验,不是对象存储可用性。
|
|
*/
|
|
async function createHomepageScreenshotAsset(
|
|
taskId: number,
|
|
options: { uploaderId?: string } = {},
|
|
) {
|
|
const { createFileAsset } = await import('../../repositories/file-asset-repo.js')
|
|
const { ORDER_SERVICE_SCREENSHOT_CONTENT_TYPES, buildFileUrl, uploadFileAsset } =
|
|
await import('../file-storage/file-storage-service.js')
|
|
const uploaderId = options.uploaderId || `semi-auto-task-${taskId}`
|
|
const file = {
|
|
buffer: TEST_SCREENSHOT_PNG,
|
|
mimetype: 'image/png',
|
|
originalname: 'game-home.png',
|
|
size: TEST_SCREENSHOT_PNG.length,
|
|
} as Express.Multer.File
|
|
try {
|
|
const uploaded = await uploadFileAsset({
|
|
file,
|
|
scene: 'semi-auto-homepage-screenshot',
|
|
uploaderType: 'semi-auto-customer',
|
|
uploaderId,
|
|
allowedContentTypes: ORDER_SERVICE_SCREENSHOT_CONTENT_TYPES,
|
|
})
|
|
return uploaded.file.objectKey
|
|
} catch (error) {
|
|
console.warn(
|
|
'[semi-auto integration] 对象存储不可用,改为直接写 file_assets 台账行',
|
|
error instanceof Error ? error.message : error,
|
|
)
|
|
const objectKey = `semi-auto-homepage-screenshot/${randomUUID()}.png`
|
|
const now = new Date().toISOString()
|
|
await createFileAsset({
|
|
objectKey,
|
|
scene: 'semi-auto-homepage-screenshot',
|
|
originalFilename: 'game-home.png',
|
|
contentType: 'image/png',
|
|
sizeBytes: TEST_SCREENSHOT_PNG.length,
|
|
thumbnailObjectKey: '',
|
|
mediumObjectKey: '',
|
|
url: buildFileUrl(objectKey),
|
|
thumbnailUrl: buildFileUrl(objectKey),
|
|
mediumUrl: buildFileUrl(objectKey),
|
|
uploaderType: 'semi-auto-customer',
|
|
uploaderId,
|
|
metadataJson: JSON.stringify({ source: 'integration-test' }),
|
|
now,
|
|
})
|
|
return objectKey
|
|
}
|
|
}
|
|
|
|
test(
|
|
'人工渠道半自动任务可由客户入口和后台列表幂等回填',
|
|
{ skip: !TEST_DATABASE_URL ? '未设置 SEMI_AUTO_TASK_TEST_DATABASE_URL' : false },
|
|
async () => {
|
|
process.env.DATABASE_URL = TEST_DATABASE_URL
|
|
const { closeDb, query, withTransaction } = await import('../../db/client.js')
|
|
const {
|
|
applySemiAutoTaskStateSnapshot,
|
|
confirmPublicBinding,
|
|
ensureSemiAutoTasksForOrder,
|
|
exportAdminSemiAutoCredential,
|
|
listAdminSemiAutoTasks,
|
|
listPublicSemiAutoTasks,
|
|
requestAdminSemiAutoCustomerReauth,
|
|
resetPublicBinding,
|
|
savePublicTaskProfile,
|
|
startPublicBinding,
|
|
} = await import('./semi-auto-task-service.js')
|
|
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
|
|
const orderNo = `IT-SEMI-AUTO-${suffix}`
|
|
const skuKey = `半自动测试-${suffix}`
|
|
let orderId = 0
|
|
let configId = 0
|
|
let credentialId = 0
|
|
try {
|
|
const order = await query<{ id: number }>(
|
|
`
|
|
INSERT INTO orders (
|
|
provider, platform, shop_id, shop_name, platform_order_id,
|
|
order_status, pay_status, total_amount, paid_at, created_at, updated_at
|
|
) VALUES (
|
|
'91kaquan', 'kuaishou-91', $1, '半自动测试店', $2,
|
|
'paid', 'paid', 1000, NOW(), NOW(), NOW()
|
|
) RETURNING id
|
|
`,
|
|
[`semi-auto-shop-${suffix}`, orderNo],
|
|
)
|
|
orderId = Number(order.rows[0]?.id || 0)
|
|
assert.ok(orderId > 0)
|
|
const item = await query<{ id: number }>(
|
|
`
|
|
INSERT INTO order_items (
|
|
order_id, sku_code, sku_name, quantity, spec_json, item_snapshot_json,
|
|
revenue_amount_fen, revenue_basis, created_at, updated_at
|
|
) VALUES (
|
|
$1, $2, $3, 1, $4::jsonb, $4::jsonb,
|
|
1000, 'order_total', NOW(), NOW()
|
|
) RETURNING id
|
|
`,
|
|
[orderId, `semi-${suffix}`, skuKey, JSON.stringify({ skuNick: skuKey })],
|
|
)
|
|
const orderItemId = Number(item.rows[0]?.id || 0)
|
|
assert.ok(orderItemId > 0)
|
|
const fulfillment = await query<{ id: number }>(
|
|
'SELECT id FROM fulfillments WHERE order_item_id = $1 LIMIT 1',
|
|
[orderItemId],
|
|
)
|
|
const fulfillmentId = Number(fulfillment.rows[0]?.id || 0)
|
|
assert.ok(fulfillmentId > 0)
|
|
|
|
const config = await query<{ id: number }>(
|
|
`
|
|
INSERT INTO manual_fulfillment_configs (
|
|
sku_key, platform_key, credit_quantity, cost_mode, enabled, note,
|
|
channels_json, semi_auto_enabled, semi_auto_platform,
|
|
semi_auto_config_json, created_at, updated_at
|
|
) VALUES (
|
|
$1, 'fund_cash', 100, 'fixed', TRUE, '集成测试',
|
|
'[{"platformKey":"fund_cash","creditQuantity":100,"costMode":"fixed","enabled":true}]'::jsonb,
|
|
TRUE, 'huya', '{"pageTitle":"虎牙授权测试"}'::jsonb,
|
|
NOW(), NOW()
|
|
) RETURNING id
|
|
`,
|
|
[skuKey],
|
|
)
|
|
configId = Number(config.rows[0]?.id || 0)
|
|
assert.ok(configId > 0)
|
|
await query(
|
|
`
|
|
UPDATE fulfillments
|
|
SET channel = 'manual', status = 'assigned', fulfillment_config_id = $2,
|
|
source = 'manual_confirm', updated_at = NOW()
|
|
WHERE id = $1
|
|
`,
|
|
[fulfillmentId, configId],
|
|
)
|
|
|
|
// 客服工作台先打开时也必须看到任务,不能依赖客户先访问 `/c/订单号` 或 `/d/订单号`。
|
|
const adminList = await listAdminSemiAutoTasks({ keyword: orderNo })
|
|
assert.equal(adminList.pagination.total, 1)
|
|
assert.equal(adminList.items[0]?.orderNo, orderNo)
|
|
|
|
const first = await ensureSemiAutoTasksForOrder(orderNo)
|
|
const second = await ensureSemiAutoTasksForOrder(orderNo)
|
|
assert.equal(first.createdIds.length, 0)
|
|
assert.equal(second.createdIds.length, 0)
|
|
|
|
const tasks = await listPublicSemiAutoTasks(orderNo)
|
|
assert.equal(tasks.length, 1)
|
|
assert.equal(tasks[0]?.orderItemId, orderItemId)
|
|
assert.equal(tasks[0]?.platform, 'huya')
|
|
assert.equal(tasks[0]?.orderNo, orderNo)
|
|
assert.equal(tasks[0]?.quantity, 1)
|
|
assert.equal(tasks[0]?.semiAutoConfig.pageTitle, '虎牙授权测试')
|
|
|
|
const taskId = Number(tasks[0]?.id || 0)
|
|
// 客户页流程固定为「填写资料 → 登录 → 绑定角色」:资料可先保存,绑定仍要求登录。
|
|
const homepageScreenshotObjectKey = await createHomepageScreenshotAsset(taskId)
|
|
const savedProfile = await savePublicTaskProfile(orderNo, taskId, {
|
|
roleName: '集成测试角色',
|
|
roleId: '1192083858',
|
|
serverZone: '安卓V区',
|
|
homepageScreenshotObjectKey,
|
|
})
|
|
assert.equal(savedProfile.task.customerGameRoleName, '集成测试角色')
|
|
assert.equal(savedProfile.task.homepageScreenshotFilename, 'game-home.png')
|
|
assert.ok(savedProfile.task.homepageScreenshotUrl)
|
|
assert.ok(savedProfile.task.homepageScreenshotUploadedAt)
|
|
assert.equal(savedProfile.task.customerGameRoleId, '1192083858')
|
|
assert.equal(savedProfile.task.customerServerZone, '安卓V区')
|
|
await expectErrorCode(() => startPublicBinding(orderNo, taskId), 'semi_auto_login_required')
|
|
const credential = await query<{ id: number }>(
|
|
`
|
|
INSERT INTO semi_auto_credentials (
|
|
platform, platform_uid, platform_nickname, credential_payload_json,
|
|
credential_source, credential_status, credential_updated_at,
|
|
last_checked_at, last_check_error, created_at, updated_at
|
|
) VALUES (
|
|
'huya', $1, '集成测试虎牙', '{"cookies":[]}',
|
|
'qr', 'valid', NOW(), NOW(), '', NOW(), NOW()
|
|
) RETURNING id
|
|
`,
|
|
[`it-huya-${suffix}`],
|
|
)
|
|
credentialId = Number(credential.rows[0]?.id || 0)
|
|
await query(
|
|
`
|
|
UPDATE semi_auto_tasks
|
|
SET credential_id = $2,
|
|
connector_session_id = $3,
|
|
login_status = 'authenticated',
|
|
binding_status = 'not_started',
|
|
execution_status = 'waiting_operator',
|
|
customer_link_opened_at = NOW(),
|
|
authenticated_at = NOW(),
|
|
updated_at = NOW()
|
|
WHERE id = $1
|
|
`,
|
|
[taskId, credentialId, `it-huya-session-${suffix}`],
|
|
)
|
|
const authenticatedList = await listAdminSemiAutoTasks({ keyword: orderNo })
|
|
assert.equal(authenticatedList.items[0]?.loginStatus, 'authenticated')
|
|
assert.equal(authenticatedList.items[0]?.displayStatus.label, '等待客户绑定角色')
|
|
const exported = await exportAdminSemiAutoCredential(taskId)
|
|
assert.equal(exported.credentialId, credentialId)
|
|
assert.equal(exported.platform, 'huya')
|
|
|
|
// 换绑失败后客户点「上一步修改资料」:清空绑定/换绑状态,保留登录与已填资料。
|
|
await query(
|
|
`
|
|
UPDATE semi_auto_tasks
|
|
SET binding_status = 'role_ready',
|
|
bind_game_role = '平台原角色',
|
|
bind_game_role_id = '99887766',
|
|
bind_game_channel = '微信',
|
|
binding_started_at = NOW(),
|
|
bound_at = NOW(),
|
|
last_error = '虎牙未接受本次换绑',
|
|
updated_at = NOW()
|
|
WHERE id = $1
|
|
`,
|
|
[taskId],
|
|
)
|
|
const reset = await resetPublicBinding(orderNo, taskId)
|
|
assert.equal(reset.task.bindingStatus, 'not_started')
|
|
assert.equal(reset.binding, null)
|
|
assert.equal(reset.task.customerGameRoleName, '集成测试角色')
|
|
assert.equal(reset.task.customerGameRoleId, '1192083858')
|
|
assert.equal(reset.task.customerServerZone, '安卓V区')
|
|
const resetRow = await query<{
|
|
binding_status: string
|
|
bind_game_role: string
|
|
bind_game_role_id: string
|
|
bind_game_channel: string
|
|
binding_started_at: string | null
|
|
bound_at: string | null
|
|
login_status: string
|
|
credential_id: number | null
|
|
connector_session_id: string
|
|
customer_game_role_name: string
|
|
customer_game_role_id: string
|
|
customer_game_server_zone: string
|
|
last_error: string
|
|
execution_status: string
|
|
}>(
|
|
`
|
|
SELECT binding_status, bind_game_role, bind_game_role_id, bind_game_channel,
|
|
binding_started_at, bound_at, login_status, credential_id,
|
|
connector_session_id, customer_game_role_name, customer_game_role_id,
|
|
customer_game_server_zone, last_error, execution_status
|
|
FROM semi_auto_tasks
|
|
WHERE id = $1
|
|
`,
|
|
[taskId],
|
|
)
|
|
const resetState = resetRow.rows[0]
|
|
assert.equal(resetState?.binding_status, 'not_started')
|
|
assert.equal(resetState?.bind_game_role, '')
|
|
assert.equal(resetState?.bind_game_role_id, '')
|
|
assert.equal(resetState?.bind_game_channel, '')
|
|
assert.equal(resetState?.binding_started_at, null)
|
|
assert.equal(resetState?.bound_at, null)
|
|
assert.equal(resetState?.last_error, '')
|
|
assert.equal(resetState?.execution_status, 'waiting_customer')
|
|
assert.equal(resetState?.login_status, 'authenticated')
|
|
assert.equal(Number(resetState?.credential_id), credentialId)
|
|
assert.equal(resetState?.connector_session_id, `it-huya-session-${suffix}`)
|
|
assert.equal(resetState?.customer_game_role_name, '集成测试角色')
|
|
assert.equal(resetState?.customer_game_role_id, '1192083858')
|
|
assert.equal(resetState?.customer_game_server_zone, '安卓V区')
|
|
const resetEvents = await query<{ detail_json: { reason?: string } | null }>(
|
|
`
|
|
SELECT detail_json
|
|
FROM semi_auto_task_events
|
|
WHERE task_id = $1 AND event_type = 'binding_reset'
|
|
ORDER BY id DESC
|
|
LIMIT 1
|
|
`,
|
|
[taskId],
|
|
)
|
|
assert.equal(resetEvents.rows[0]?.detail_json?.reason, 'customer_profile_edit')
|
|
|
|
// 已确认绑定后的重新授权必须完整退出已授权状态,不能只清登录状态。
|
|
await query(
|
|
`
|
|
UPDATE semi_auto_tasks
|
|
SET binding_status = 'confirmed',
|
|
bind_game_account = '集成测试虎牙账号',
|
|
bind_game_role = '集成测试角色',
|
|
bind_game_role_id = '1192083858',
|
|
bind_game_channel = '安卓(iOS) · QQ',
|
|
binding_started_at = NOW(),
|
|
bound_at = NOW(),
|
|
execution_status = 'waiting_operator',
|
|
updated_at = NOW()
|
|
WHERE id = $1
|
|
`,
|
|
[taskId],
|
|
)
|
|
const reauthorized = await requestAdminSemiAutoCustomerReauth(taskId, {
|
|
userId: 1,
|
|
role: 'support',
|
|
displayName: '集成测试客服',
|
|
} as never)
|
|
assert.equal(reauthorized.task.loginStatus, 'waiting_login')
|
|
assert.equal(reauthorized.task.bindingStatus, 'not_started')
|
|
assert.equal(reauthorized.task.executionStatus, 'waiting_customer')
|
|
assert.equal(reauthorized.task.customerLinkOpenedAt, null)
|
|
assert.equal(reauthorized.task.bindGameAccount, '')
|
|
assert.equal(reauthorized.task.bindGameRole, '')
|
|
assert.equal(reauthorized.task.bindGameRoleId, '')
|
|
assert.equal(reauthorized.task.bindGameChannel, '')
|
|
assert.equal(reauthorized.task.boundAt, null)
|
|
const retainedCredential = await query<{ credential_id: number }>(
|
|
'SELECT credential_id FROM semi_auto_tasks WHERE id = $1',
|
|
[taskId],
|
|
)
|
|
assert.equal(Number(retainedCredential.rows[0]?.credential_id), credentialId)
|
|
assert.ok(
|
|
reauthorized.events.some((event) => event.eventType === 'customer_reauth_requested'),
|
|
)
|
|
|
|
const missingVersionEventId = randomUUID()
|
|
await expectErrorCode(
|
|
() =>
|
|
applySemiAutoTaskStateSnapshot(
|
|
{
|
|
eventId: missingVersionEventId,
|
|
taskId,
|
|
orderNo,
|
|
loginStatus: 'authenticated',
|
|
bindingStatus: 'not_started',
|
|
},
|
|
{ eventId: missingVersionEventId, eventType: 'semi_auto.task_state' },
|
|
),
|
|
'semi_auto_snapshot_state_version_required',
|
|
)
|
|
|
|
const snapshotEventId = randomUUID()
|
|
const snapshot = await applySemiAutoTaskStateSnapshot(
|
|
{
|
|
eventId: snapshotEventId,
|
|
stateVersion: 2,
|
|
taskId,
|
|
orderNo,
|
|
loginStatus: 'authenticated',
|
|
bindingStatus: 'confirmed',
|
|
huyaUid: `it-huya-${suffix}`,
|
|
bindGameAccount: '集成测试虎牙账号',
|
|
bindGameRole: '集成测试角色',
|
|
bindGameRoleToken: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
|
|
bindGameChannel: '安卓(android) · 微信',
|
|
isBindAccount: true,
|
|
isBindRole: true,
|
|
roleIdentitySource: 'huya_outer_current',
|
|
verificationBasis: 'role_name_zone',
|
|
},
|
|
{ eventId: snapshotEventId, eventType: 'semi_auto.task_state' },
|
|
)
|
|
assert.equal(snapshot.applied, true)
|
|
const reusedUidEventId = randomUUID()
|
|
await expectErrorCode(
|
|
() =>
|
|
applySemiAutoTaskStateSnapshot(
|
|
{
|
|
eventId: reusedUidEventId,
|
|
stateVersion: 3,
|
|
taskId,
|
|
orderNo,
|
|
loginStatus: 'authenticated',
|
|
bindingStatus: 'role_ready',
|
|
huyaUid: '1199664118656',
|
|
platformGameRoleUid: '1199664118656',
|
|
bindGameRole: '集成测试角色',
|
|
bindGameChannel: '安卓(android) · QQ',
|
|
},
|
|
{ eventId: reusedUidEventId, eventType: 'semi_auto.task_state' },
|
|
),
|
|
'semi_auto_snapshot_platform_role_uid_reused',
|
|
)
|
|
const duplicateSnapshot = await applySemiAutoTaskStateSnapshot(
|
|
{
|
|
eventId: snapshotEventId,
|
|
stateVersion: 2,
|
|
taskId,
|
|
orderNo,
|
|
loginStatus: 'authenticated',
|
|
bindingStatus: 'confirmed',
|
|
},
|
|
{ eventId: snapshotEventId, eventType: 'semi_auto.task_state' },
|
|
)
|
|
assert.equal(duplicateSnapshot.applied, false)
|
|
const synced = await query<{
|
|
login_status: string
|
|
binding_status: string
|
|
execution_status: string
|
|
bind_game_role_token: string
|
|
role_identity_source: string
|
|
verification_basis: string
|
|
}>(
|
|
`SELECT login_status, binding_status, execution_status,
|
|
bind_game_role_token, role_identity_source, verification_basis
|
|
FROM semi_auto_tasks WHERE id = $1`,
|
|
[taskId],
|
|
)
|
|
assert.deepEqual(synced.rows[0], {
|
|
login_status: 'authenticated',
|
|
binding_status: 'confirmed',
|
|
execution_status: 'waiting_operator',
|
|
bind_game_role_token: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
|
|
role_identity_source: 'huya_outer_current',
|
|
verification_basis: 'role_name_zone',
|
|
})
|
|
|
|
const staleConfirmEventId = randomUUID()
|
|
await applySemiAutoTaskStateSnapshot(
|
|
{
|
|
eventId: staleConfirmEventId,
|
|
stateVersion: 3,
|
|
taskId,
|
|
orderNo,
|
|
loginStatus: 'authenticated',
|
|
bindingStatus: 'confirmed',
|
|
huyaUid: `it-huya-${suffix}`,
|
|
bindGameAccount: '集成测试虎牙账号',
|
|
bindGameRole: '错误角色',
|
|
bindGameRoleToken: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',
|
|
bindGameChannel: '安卓(android) · 微信',
|
|
isBindAccount: true,
|
|
isBindRole: true,
|
|
roleIdentitySource: 'huya_outer_current',
|
|
verificationBasis: 'role_name_zone',
|
|
},
|
|
{ eventId: staleConfirmEventId, eventType: 'semi_auto.task_state' },
|
|
)
|
|
const decisionGated = await query<{
|
|
execution_status: string
|
|
binding_flow_state: string
|
|
}>(
|
|
`SELECT execution_status, binding_flow_state
|
|
FROM semi_auto_tasks WHERE id = $1`,
|
|
[taskId],
|
|
)
|
|
assert.deepEqual(decisionGated.rows[0], {
|
|
execution_status: 'waiting_customer',
|
|
binding_flow_state: 'rebind_required',
|
|
})
|
|
const outOfOrderEventId = randomUUID()
|
|
const outOfOrder = await applySemiAutoTaskStateSnapshot(
|
|
{
|
|
eventId: outOfOrderEventId,
|
|
stateVersion: 2,
|
|
taskId,
|
|
orderNo,
|
|
loginStatus: 'authenticated',
|
|
bindingStatus: 'confirmed',
|
|
huyaUid: `it-huya-${suffix}`,
|
|
bindGameAccount: '集成测试虎牙账号',
|
|
bindGameRole: '集成测试角色',
|
|
bindGameRoleToken: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
|
|
bindGameChannel: '安卓(android) · 微信',
|
|
isBindAccount: true,
|
|
isBindRole: true,
|
|
roleIdentitySource: 'huya_outer_current',
|
|
verificationBasis: 'role_name_zone',
|
|
},
|
|
{ eventId: outOfOrderEventId, eventType: 'semi_auto.task_state' },
|
|
)
|
|
assert.equal(outOfOrder.applied, false)
|
|
assert.equal(outOfOrder.stale, true)
|
|
const afterOutOfOrder = await query<{ binding_flow_state: string; execution_status: string }>(
|
|
`SELECT binding_flow_state, execution_status FROM semi_auto_tasks WHERE id = $1`,
|
|
[taskId],
|
|
)
|
|
assert.deepEqual(afterOutOfOrder.rows[0], {
|
|
binding_flow_state: 'rebind_required',
|
|
execution_status: 'waiting_customer',
|
|
})
|
|
} finally {
|
|
if (orderId > 0) {
|
|
await query('DELETE FROM order_source_snapshots WHERE order_id = $1', [orderId])
|
|
await query('DELETE FROM orders WHERE id = $1', [orderId])
|
|
}
|
|
if (credentialId > 0) {
|
|
await query('DELETE FROM semi_auto_credentials WHERE id = $1', [credentialId])
|
|
}
|
|
if (configId > 0) {
|
|
await query('DELETE FROM manual_fulfillment_configs WHERE id = $1', [configId])
|
|
}
|
|
await closeDb()
|
|
}
|
|
},
|
|
)
|
|
|
|
test(
|
|
'半自动完成失败会连同财务确认一起回滚,成功后重复完成不重复扣成本',
|
|
{ skip: !TEST_DATABASE_URL ? '未设置 SEMI_AUTO_TASK_TEST_DATABASE_URL' : false },
|
|
async () => {
|
|
process.env.DATABASE_URL = TEST_DATABASE_URL
|
|
const { closeDb, query } = await import('../../db/client.js')
|
|
const { completeAdminSemiAutoTask, ensureSemiAutoTasksForOrder } =
|
|
await import('./semi-auto-task-service.js')
|
|
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
|
|
const orderNo = `IT-SEMI-AUTO-ATOMIC-${suffix}`
|
|
const skuKey = `半自动原子性-${suffix}`
|
|
const triggerName = `trg_semi_auto_atomic_${suffix}`
|
|
const functionName = `fn_semi_auto_atomic_${suffix}`
|
|
let orderId = 0
|
|
let configId = 0
|
|
let adminId = 0
|
|
let credentialId = 0
|
|
let triggerCreated = false
|
|
try {
|
|
const admin = await query<{ id: number }>(
|
|
`INSERT INTO admin_users (username, password_hash, role, status, created_at, updated_at)
|
|
VALUES ($1, 'x', 'support', 'active', NOW(), NOW()) RETURNING id`,
|
|
[`it_semi_auto_admin_${suffix}`],
|
|
)
|
|
adminId = Number(admin.rows[0]?.id || 0)
|
|
assert.ok(adminId > 0)
|
|
|
|
const order = await query<{ id: number }>(
|
|
`
|
|
INSERT INTO orders (
|
|
provider, platform, shop_id, shop_name, platform_order_id,
|
|
order_status, pay_status, total_amount, paid_at, created_at, updated_at
|
|
) VALUES (
|
|
'91kaquan', 'kuaishou-91', $1, '半自动原子性测试店', $2,
|
|
'paid', 'paid', 1000, NOW(), NOW(), NOW()
|
|
) RETURNING id
|
|
`,
|
|
[`semi-auto-atomic-shop-${suffix}`, orderNo],
|
|
)
|
|
orderId = Number(order.rows[0]?.id || 0)
|
|
assert.ok(orderId > 0)
|
|
const item = await query<{ id: number }>(
|
|
`
|
|
INSERT INTO order_items (
|
|
order_id, sku_code, sku_name, quantity, spec_json, item_snapshot_json,
|
|
revenue_amount_fen, revenue_basis, created_at, updated_at
|
|
) VALUES (
|
|
$1, $2, $3, 1, $4::jsonb, $4::jsonb,
|
|
1000, 'order_total', NOW(), NOW()
|
|
) RETURNING id
|
|
`,
|
|
[orderId, `semi-atomic-${suffix}`, skuKey, JSON.stringify({ skuNick: skuKey })],
|
|
)
|
|
const orderItemId = Number(item.rows[0]?.id || 0)
|
|
assert.ok(orderItemId > 0)
|
|
const fulfillment = await query<{ id: number }>(
|
|
'SELECT id FROM fulfillments WHERE order_item_id = $1 LIMIT 1',
|
|
[orderItemId],
|
|
)
|
|
const fulfillmentId = Number(fulfillment.rows[0]?.id || 0)
|
|
assert.ok(fulfillmentId > 0)
|
|
|
|
const config = await query<{ id: number }>(
|
|
`
|
|
INSERT INTO manual_fulfillment_configs (
|
|
sku_key, platform_key, credit_quantity, cost_mode, enabled, note,
|
|
channels_json, semi_auto_enabled, semi_auto_platform,
|
|
semi_auto_config_json, created_at, updated_at
|
|
) VALUES (
|
|
$1, 'on_account', 0, 'variable', TRUE, '原子性集成测试',
|
|
'[{"platformKey":"on_account","creditQuantity":0,"costMode":"variable","enabled":true}]'::jsonb,
|
|
TRUE, 'huya', '{}'::jsonb, NOW(), NOW()
|
|
) RETURNING id
|
|
`,
|
|
[skuKey],
|
|
)
|
|
configId = Number(config.rows[0]?.id || 0)
|
|
assert.ok(configId > 0)
|
|
await query(
|
|
`
|
|
UPDATE fulfillments
|
|
SET channel = 'manual', status = 'assigned', fulfillment_config_id = $2,
|
|
source = 'manual_confirm', updated_at = NOW()
|
|
WHERE id = $1
|
|
`,
|
|
[fulfillmentId, configId],
|
|
)
|
|
|
|
const ensured = await ensureSemiAutoTasksForOrder(orderNo)
|
|
const taskId = Number(ensured.createdIds[0] || 0)
|
|
assert.ok(taskId > 0)
|
|
const credential = await query<{ id: number }>(
|
|
`
|
|
INSERT INTO semi_auto_credentials (
|
|
platform, platform_uid, platform_nickname, credential_payload_json,
|
|
credential_source, credential_status, credential_updated_at,
|
|
last_checked_at, last_check_error, created_at, updated_at
|
|
) VALUES (
|
|
'huya', $1, '半自动原子性账号', '{"cookies":[]}',
|
|
'qr', 'valid', NOW(), NOW(), '', NOW(), NOW()
|
|
) RETURNING id
|
|
`,
|
|
[`it-atomic-huya-${suffix}`],
|
|
)
|
|
credentialId = Number(credential.rows[0]?.id || 0)
|
|
assert.ok(credentialId > 0)
|
|
await query(
|
|
`
|
|
UPDATE semi_auto_tasks
|
|
SET credential_id = $2,
|
|
login_status = 'authenticated',
|
|
binding_status = 'confirmed',
|
|
binding_flow_state = 'confirmed',
|
|
execution_status = 'waiting_operator',
|
|
customer_game_role_name = '半自动原子性角色',
|
|
customer_game_role_id = '1192083858',
|
|
customer_game_server_zone = '安卓V区',
|
|
bind_game_role = '半自动原子性角色',
|
|
bind_game_role_token = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
|
|
bind_game_channel = '安卓(android) · 微信',
|
|
is_bind_account = TRUE,
|
|
is_bind_role = TRUE,
|
|
bound_at = NOW(),
|
|
authenticated_at = NOW(),
|
|
updated_at = NOW()
|
|
WHERE id = $1
|
|
`,
|
|
[taskId, credentialId],
|
|
)
|
|
|
|
await query(
|
|
`
|
|
CREATE OR REPLACE FUNCTION ${functionName}() RETURNS trigger
|
|
LANGUAGE plpgsql AS $$
|
|
BEGIN
|
|
IF NEW.execution_status = 'completed' THEN
|
|
RAISE EXCEPTION 'forced semi auto completion failure';
|
|
END IF;
|
|
RETURN NEW;
|
|
END;
|
|
$$
|
|
`,
|
|
)
|
|
await query(
|
|
`
|
|
CREATE TRIGGER ${triggerName}
|
|
BEFORE UPDATE OF execution_status ON semi_auto_tasks
|
|
FOR EACH ROW EXECUTE FUNCTION ${functionName}()
|
|
`,
|
|
)
|
|
triggerCreated = true
|
|
|
|
const session = {
|
|
userId: adminId,
|
|
role: 'support',
|
|
displayName: '半自动原子性客服',
|
|
} as never
|
|
await assert.rejects(
|
|
() =>
|
|
completeAdminSemiAutoTask(
|
|
taskId,
|
|
{ costFen: 123, note: '触发任务更新失败以验证回滚' },
|
|
session,
|
|
),
|
|
/forced semi auto completion failure/,
|
|
)
|
|
|
|
const rolledBack = await query<{
|
|
execution_status: string
|
|
snapshot_count: number
|
|
bill_count: number
|
|
fulfillment_channel: string
|
|
}>(
|
|
`
|
|
SELECT
|
|
task.execution_status,
|
|
(SELECT COUNT(*)::int FROM cost_snapshots cs WHERE cs.order_item_id = $2) AS snapshot_count,
|
|
(SELECT COUNT(*)::int FROM on_account_bills oab WHERE oab.order_item_id = $2) AS bill_count,
|
|
f.channel AS fulfillment_channel
|
|
FROM semi_auto_tasks task
|
|
JOIN fulfillments f ON f.id = task.fulfillment_id
|
|
WHERE task.id = $1
|
|
`,
|
|
[taskId, orderItemId],
|
|
)
|
|
assert.equal(rolledBack.rows[0]?.execution_status, 'waiting_operator')
|
|
assert.equal(Number(rolledBack.rows[0]?.snapshot_count), 0)
|
|
assert.equal(Number(rolledBack.rows[0]?.bill_count), 0)
|
|
assert.equal(rolledBack.rows[0]?.fulfillment_channel, 'manual')
|
|
|
|
await query(`DROP TRIGGER ${triggerName} ON semi_auto_tasks`)
|
|
triggerCreated = false
|
|
await query(`DROP FUNCTION ${functionName}()`)
|
|
|
|
const completed = await completeAdminSemiAutoTask(
|
|
taskId,
|
|
{ costFen: 123, note: '事务重试成功' },
|
|
session,
|
|
)
|
|
assert.equal(completed.task.executionStatus, 'completed')
|
|
const afterCompletion = await query<{ snapshot_count: number; bill_count: number }>(
|
|
`
|
|
SELECT
|
|
(SELECT COUNT(*)::int FROM cost_snapshots cs WHERE cs.order_item_id = $1) AS snapshot_count,
|
|
(SELECT COUNT(*)::int FROM on_account_bills oab WHERE oab.order_item_id = $1) AS bill_count
|
|
`,
|
|
[orderItemId],
|
|
)
|
|
assert.equal(Number(afterCompletion.rows[0]?.snapshot_count), 1)
|
|
assert.equal(Number(afterCompletion.rows[0]?.bill_count), 1)
|
|
|
|
await completeAdminSemiAutoTask(taskId, { costFen: 123 }, session)
|
|
const afterDuplicate = await query<{ snapshot_count: number }>(
|
|
'SELECT COUNT(*)::int AS snapshot_count FROM cost_snapshots WHERE order_item_id = $1',
|
|
[orderItemId],
|
|
)
|
|
assert.equal(Number(afterDuplicate.rows[0]?.snapshot_count), 1)
|
|
} finally {
|
|
if (triggerCreated) {
|
|
await query(`DROP TRIGGER IF EXISTS ${triggerName} ON semi_auto_tasks`)
|
|
}
|
|
await query(`DROP FUNCTION IF EXISTS ${functionName}()`)
|
|
if (orderId > 0) {
|
|
await query(
|
|
'DELETE FROM cost_snapshots WHERE order_item_id IN (SELECT id FROM order_items WHERE order_id = $1)',
|
|
[orderId],
|
|
)
|
|
await query(
|
|
'DELETE FROM on_account_bills WHERE order_item_id IN (SELECT id FROM order_items WHERE order_id = $1)',
|
|
[orderId],
|
|
)
|
|
await query(
|
|
'DELETE FROM cost_exceptions WHERE subject_id IN (SELECT id FROM order_items WHERE order_id = $1)',
|
|
[orderId],
|
|
)
|
|
await query('DELETE FROM orders WHERE id = $1', [orderId])
|
|
}
|
|
// 已过账总账凭证按财务规则不可物理删除;测试只清理可重建销售投影。
|
|
await query(
|
|
`DELETE FROM sales_daily_facts
|
|
WHERE stat_date = (NOW() AT TIME ZONE 'Asia/Shanghai')::date`,
|
|
)
|
|
if (configId > 0) {
|
|
await query('DELETE FROM manual_fulfillment_configs WHERE id = $1', [configId])
|
|
}
|
|
if (credentialId > 0) {
|
|
await query('DELETE FROM semi_auto_credentials WHERE id = $1', [credentialId])
|
|
}
|
|
if (adminId > 0) {
|
|
await query('DELETE FROM admin_users WHERE id = $1', [adminId])
|
|
}
|
|
await closeDb()
|
|
}
|
|
},
|
|
)
|
|
|
|
test(
|
|
'人工配置切换半自动平台会终止旧任务并创建新的活动任务',
|
|
{ skip: !TEST_DATABASE_URL ? '未设置 SEMI_AUTO_TASK_TEST_DATABASE_URL' : false },
|
|
async () => {
|
|
process.env.DATABASE_URL = TEST_DATABASE_URL
|
|
process.env.ENABLE_DEV_MOCK = '1'
|
|
const { closeDb, query } = await import('../../db/client.js')
|
|
const { createSemiAutoMock } = await import('../dev-mock/dev-mock-service.js')
|
|
const { reconcileSemiAutoTasksForManualConfig } = await import('./semi-auto-task-service.js')
|
|
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
|
|
const orderNo = `IT-SEMI-AUTO-PLATFORM-SWITCH-${suffix}`
|
|
let orderId = 0
|
|
let configId = 0
|
|
try {
|
|
const result = await createSemiAutoMock({
|
|
orderNo,
|
|
skuName: `半自动平台切换-${suffix}`,
|
|
quantity: 1,
|
|
connectorMode: 'embedded',
|
|
})
|
|
orderId = result.orderId
|
|
configId = result.configId
|
|
await query(
|
|
`UPDATE manual_fulfillment_configs
|
|
SET semi_auto_platform = 'weibo', updated_at = NOW()
|
|
WHERE id = $1`,
|
|
[configId],
|
|
)
|
|
const reconciled = await reconcileSemiAutoTasksForManualConfig(configId)
|
|
assert.equal(reconciled.createdIds.length, 1)
|
|
|
|
const tasks = await query<{
|
|
id: number
|
|
platform: string
|
|
execution_status: string
|
|
last_error: string
|
|
}>(
|
|
`SELECT id, platform, execution_status, last_error
|
|
FROM semi_auto_tasks
|
|
WHERE order_id = $1
|
|
ORDER BY id`,
|
|
[orderId],
|
|
)
|
|
assert.equal(tasks.rows.length, 2)
|
|
assert.equal(tasks.rows[0]?.platform, 'huya')
|
|
assert.equal(tasks.rows[0]?.execution_status, 'cancelled')
|
|
assert.match(tasks.rows[0]?.last_error || '', /切换半自动平台/)
|
|
assert.equal(tasks.rows[1]?.platform, 'weibo')
|
|
assert.equal(tasks.rows[1]?.execution_status, 'waiting_customer')
|
|
|
|
await query(
|
|
`UPDATE manual_fulfillment_configs
|
|
SET semi_auto_enabled = FALSE, updated_at = NOW()
|
|
WHERE id = $1`,
|
|
[configId],
|
|
)
|
|
await reconcileSemiAutoTasksForManualConfig(configId)
|
|
const disabled = await query<{ platform: string; execution_status: string }>(
|
|
`SELECT platform, execution_status
|
|
FROM semi_auto_tasks
|
|
WHERE order_id = $1
|
|
ORDER BY id`,
|
|
[orderId],
|
|
)
|
|
assert.deepEqual(disabled.rows, [
|
|
{ platform: 'huya', execution_status: 'cancelled' },
|
|
{ platform: 'weibo', execution_status: 'cancelled' },
|
|
])
|
|
} finally {
|
|
if (orderId > 0) await query('DELETE FROM orders WHERE id = $1', [orderId])
|
|
if (configId > 0) {
|
|
await query('DELETE FROM manual_fulfillment_configs WHERE id = $1', [configId])
|
|
}
|
|
delete process.env.ENABLE_DEV_MOCK
|
|
await closeDb()
|
|
}
|
|
},
|
|
)
|
|
|
|
test(
|
|
'虎牙确认状态可从数据库恢复并在回查角色一致后收敛为已确认',
|
|
{ skip: !TEST_DATABASE_URL ? '未设置 SEMI_AUTO_TASK_TEST_DATABASE_URL' : false },
|
|
async () => {
|
|
process.env.DATABASE_URL = TEST_DATABASE_URL
|
|
process.env.ENABLE_DEV_MOCK = '1'
|
|
const { closeDb, query, withTransaction } = await import('../../db/client.js')
|
|
const { createSemiAutoMock } = await import('../dev-mock/dev-mock-service.js')
|
|
const { loadTask, updateBindingTaskWithClient } = await import('./semi-auto-task-core.js')
|
|
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
|
|
const orderNo = `IT-HUYA-CONFIRM-RECOVERY-${suffix}`
|
|
const targetRoleToken = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'
|
|
let orderId = 0
|
|
let configId = 0
|
|
try {
|
|
const result = await createSemiAutoMock({
|
|
orderNo,
|
|
skuName: `虎牙确认恢复-${suffix}`,
|
|
quantity: 1,
|
|
connectorMode: 'embedded',
|
|
})
|
|
orderId = result.orderId
|
|
configId = result.configId
|
|
await query(
|
|
`
|
|
UPDATE semi_auto_tasks
|
|
SET login_status = 'authenticated',
|
|
customer_game_role_name = '恢复目标角色',
|
|
customer_game_role_id = '1192083858',
|
|
customer_game_server_zone = '安卓V区',
|
|
binding_status = 'scanned',
|
|
bind_game_role = '旧角色',
|
|
bind_game_role_token = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
|
|
bind_game_channel = '安卓(android) · 微信',
|
|
is_bind_account = TRUE,
|
|
is_bind_role = TRUE,
|
|
pending_bind_game_role = '恢复目标角色',
|
|
pending_bind_game_role_token = $2,
|
|
pending_bind_game_channel = '安卓(android) · 微信',
|
|
bind_confirm_state = 'accepted',
|
|
binding_effect_deadline_at = NOW() + INTERVAL '1 minute',
|
|
execution_status = 'waiting_customer',
|
|
updated_at = NOW()
|
|
WHERE id = $1
|
|
`,
|
|
[result.taskId, targetRoleToken],
|
|
)
|
|
const task = await loadTask(result.taskId)
|
|
await withTransaction((client) =>
|
|
updateBindingTaskWithClient(
|
|
client,
|
|
task.id,
|
|
{
|
|
sessionId: task.connector_session_id,
|
|
status: 'role_ready',
|
|
qrImage: '',
|
|
qrExpiresAt: '',
|
|
qrUrl: '',
|
|
bindGameAccount: '恢复目标账号',
|
|
bindGameRole: '恢复目标角色',
|
|
bindGameRoleId: targetRoleToken,
|
|
bindGameRoleToken: targetRoleToken,
|
|
bindGameChannel: '安卓(android) · 微信',
|
|
currentRole: {
|
|
isBindAccount: true,
|
|
isBindRole: true,
|
|
roleName: '恢复目标角色',
|
|
roleToken: targetRoleToken,
|
|
channel: '安卓(android) · 微信',
|
|
changeBindTime: 0,
|
|
changeBindDay: 7,
|
|
},
|
|
pendingRole: null,
|
|
hasExistingBinding: true,
|
|
rebindRequested: false,
|
|
message: '平台角色已生效',
|
|
},
|
|
'connector',
|
|
),
|
|
)
|
|
const recovered = await loadTask(result.taskId)
|
|
assert.equal(recovered.binding_status, 'confirmed')
|
|
assert.equal(recovered.binding_flow_state, 'confirmed')
|
|
assert.equal(recovered.execution_status, 'waiting_operator')
|
|
assert.equal(recovered.bind_confirm_state, 'idle')
|
|
assert.equal(recovered.pending_bind_game_role, '')
|
|
assert.ok(recovered.bound_at)
|
|
} finally {
|
|
if (orderId > 0) await query('DELETE FROM orders WHERE id = $1', [orderId])
|
|
if (configId > 0) {
|
|
await query('DELETE FROM manual_fulfillment_configs WHERE id = $1', [configId])
|
|
}
|
|
delete process.env.ENABLE_DEV_MOCK
|
|
await closeDb()
|
|
}
|
|
},
|
|
)
|
|
|
|
test(
|
|
'半自动后台列表按任务创建顺序稳定分页,状态刷新不会导致行跳位',
|
|
{ skip: !TEST_DATABASE_URL ? '未设置 SEMI_AUTO_TASK_TEST_DATABASE_URL' : false },
|
|
async () => {
|
|
process.env.DATABASE_URL = TEST_DATABASE_URL
|
|
process.env.ENABLE_DEV_MOCK = '1'
|
|
const { closeDb, query } = await import('../../db/client.js')
|
|
const { createSemiAutoMock } = await import('../dev-mock/dev-mock-service.js')
|
|
const { listAdminSemiAutoTasks } = await import('./semi-auto-task-service.js')
|
|
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
|
|
const keyword = `IT-SEMI-AUTO-STABLE-${suffix}`
|
|
const created: Array<{ orderId: number; configId: number; taskId: number }> = []
|
|
try {
|
|
for (const label of ['A', 'B']) {
|
|
const result = await createSemiAutoMock({
|
|
orderNo: `${keyword}-${label}`,
|
|
skuName: `半自动稳定排序-${suffix}-${label}`,
|
|
quantity: 1,
|
|
connectorMode: 'embedded',
|
|
})
|
|
created.push({
|
|
orderId: result.orderId,
|
|
configId: result.configId,
|
|
taskId: result.taskId,
|
|
})
|
|
}
|
|
const first = created[0]!
|
|
const second = created[1]!
|
|
await query(
|
|
`
|
|
UPDATE semi_auto_tasks
|
|
SET created_at = NOW() - INTERVAL '2 minutes',
|
|
updated_at = NOW() + INTERVAL '2 minutes',
|
|
execution_status = 'waiting_operator'
|
|
WHERE id = $1
|
|
`,
|
|
[first.taskId],
|
|
)
|
|
await query(
|
|
`
|
|
UPDATE semi_auto_tasks
|
|
SET created_at = NOW() - INTERVAL '1 minute',
|
|
updated_at = NOW() - INTERVAL '1 minute',
|
|
execution_status = 'waiting_customer'
|
|
WHERE id = $1
|
|
`,
|
|
[second.taskId],
|
|
)
|
|
|
|
const result = await listAdminSemiAutoTasks({ keyword, page: 1, pageSize: 20 })
|
|
assert.deepEqual(
|
|
result.items.map((item) => item.id),
|
|
[second.taskId, first.taskId],
|
|
)
|
|
} finally {
|
|
for (const item of created.reverse()) {
|
|
await query('DELETE FROM orders WHERE id = $1', [item.orderId])
|
|
await query('DELETE FROM manual_fulfillment_configs WHERE id = $1', [item.configId])
|
|
}
|
|
delete process.env.ENABLE_DEV_MOCK
|
|
await closeDb()
|
|
}
|
|
},
|
|
)
|
|
|
|
test(
|
|
'微博账号 CK 以账号级 Cookie JSON 保存并可加载',
|
|
{ skip: !TEST_DATABASE_URL ? '未设置 SEMI_AUTO_TASK_TEST_DATABASE_URL' : false },
|
|
async () => {
|
|
process.env.DATABASE_URL = TEST_DATABASE_URL
|
|
const { closeDb, query, withTransaction } = await import('../../db/client.js')
|
|
const { loadSemiAutoCredential, upsertSemiAutoCredentialWithClient } =
|
|
await import('./semi-auto-credential-service.js')
|
|
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
|
|
let credentialId = 0
|
|
try {
|
|
credentialId = await withTransaction((client) =>
|
|
upsertSemiAutoCredentialWithClient(client, {
|
|
platform: 'weibo',
|
|
source: 'sms',
|
|
payload: {
|
|
platformUid: `it-weibo-${suffix}`,
|
|
nickname: '集成测试微博',
|
|
cookies: [
|
|
{
|
|
name: 'SUB',
|
|
value: `secret-sub-${suffix}`,
|
|
domain: '.weibo.com',
|
|
path: '/',
|
|
secure: true,
|
|
httpOnly: true,
|
|
},
|
|
],
|
|
},
|
|
}),
|
|
)
|
|
const raw = await query<{
|
|
credential_payload_json: string
|
|
credential_source: string
|
|
credential_status: string
|
|
}>(
|
|
`SELECT credential_payload_json, credential_source, credential_status
|
|
FROM semi_auto_credentials WHERE id = $1`,
|
|
[credentialId],
|
|
)
|
|
assert.equal(raw.rows[0]?.credential_source, 'sms')
|
|
assert.equal(raw.rows[0]?.credential_status, 'valid')
|
|
assert.match(raw.rows[0]?.credential_payload_json || '', /"cookies"/)
|
|
|
|
const credential = await loadSemiAutoCredential(credentialId)
|
|
assert.equal(credential?.platformUid, `it-weibo-${suffix}`)
|
|
assert.equal(credential?.cookies[0]?.value, `secret-sub-${suffix}`)
|
|
} finally {
|
|
if (credentialId > 0) {
|
|
await query('DELETE FROM semi_auto_credentials WHERE id = $1', [credentialId])
|
|
}
|
|
await closeDb()
|
|
}
|
|
},
|
|
)
|
|
|
|
test(
|
|
'开发 Mock 可生成半自动履约测试单并回填任务',
|
|
{ skip: !TEST_DATABASE_URL ? '未设置 SEMI_AUTO_TASK_TEST_DATABASE_URL' : false },
|
|
async () => {
|
|
process.env.DATABASE_URL = TEST_DATABASE_URL
|
|
process.env.ENABLE_DEV_MOCK = '1'
|
|
const { closeDb, query } = await import('../../db/client.js')
|
|
const { createSemiAutoMock } = await import('../dev-mock/dev-mock-service.js')
|
|
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
|
|
const orderNo = `IT-MOCK-SA-${suffix}`
|
|
const skuKey = `半自动Mock-${suffix}`
|
|
let orderId = 0
|
|
let configId = 0
|
|
try {
|
|
const result = await createSemiAutoMock({
|
|
orderNo,
|
|
skuName: skuKey,
|
|
quantity: 1,
|
|
pageTitle: 'Mock 集成测试',
|
|
connectorMode: 'embedded',
|
|
})
|
|
orderId = result.orderId
|
|
configId = result.configId
|
|
assert.ok(result.orderItemId > 0)
|
|
assert.ok(result.fulfillmentId > 0)
|
|
assert.ok(result.taskId > 0)
|
|
assert.equal(result.connectorMode, 'embedded')
|
|
assert.equal(result.customerPath, `/c/${encodeURIComponent(orderNo)}`)
|
|
|
|
const row = await query<{
|
|
channel: string
|
|
fulfillment_status: string
|
|
fulfillment_config_id: number
|
|
semi_auto_enabled: boolean
|
|
semi_auto_platform: string
|
|
connector_mode: string
|
|
login_status: string
|
|
binding_status: string
|
|
execution_status: string
|
|
}>(
|
|
`
|
|
SELECT
|
|
f.channel,
|
|
f.status AS fulfillment_status,
|
|
f.fulfillment_config_id,
|
|
cfg.semi_auto_enabled,
|
|
cfg.semi_auto_platform,
|
|
task.connector_mode,
|
|
task.login_status,
|
|
task.binding_status,
|
|
task.execution_status
|
|
FROM semi_auto_tasks task
|
|
JOIN fulfillments f ON f.id = task.fulfillment_id
|
|
JOIN manual_fulfillment_configs cfg ON cfg.id = task.manual_fulfillment_config_id
|
|
WHERE task.order_item_id = $1
|
|
`,
|
|
[result.orderItemId],
|
|
)
|
|
assert.equal(row.rows[0]?.channel, 'manual')
|
|
assert.equal(row.rows[0]?.fulfillment_status, 'assigned')
|
|
assert.equal(Number(row.rows[0]?.fulfillment_config_id), result.configId)
|
|
assert.equal(row.rows[0]?.semi_auto_enabled, true)
|
|
assert.equal(row.rows[0]?.semi_auto_platform, 'huya')
|
|
assert.equal(row.rows[0]?.connector_mode, 'embedded')
|
|
assert.equal(row.rows[0]?.login_status, 'waiting_login')
|
|
assert.equal(row.rows[0]?.binding_status, 'not_started')
|
|
assert.equal(row.rows[0]?.execution_status, 'waiting_customer')
|
|
} finally {
|
|
if (orderId > 0) await query('DELETE FROM orders WHERE id = $1', [orderId])
|
|
if (configId > 0) {
|
|
await query('DELETE FROM manual_fulfillment_configs WHERE id = $1', [configId])
|
|
}
|
|
delete process.env.ENABLE_DEV_MOCK
|
|
await closeDb()
|
|
}
|
|
},
|
|
)
|
|
|
|
test(
|
|
'虎牙数据库 CK 可在进程会话丢失后恢复并直接下发浏览器登录态',
|
|
{ skip: !TEST_DATABASE_URL ? '未设置 SEMI_AUTO_TASK_TEST_DATABASE_URL' : false },
|
|
async () => {
|
|
process.env.DATABASE_URL = TEST_DATABASE_URL
|
|
process.env.ENABLE_DEV_MOCK = '1'
|
|
const { closeDb, query, withTransaction } = await import('../../db/client.js')
|
|
const { createSemiAutoMock } = await import('../dev-mock/dev-mock-service.js')
|
|
const { upsertSemiAutoCredentialWithClient } = await import('./semi-auto-credential-service.js')
|
|
const { createAdminBrowserSession } = await import('./semi-auto-task-service.js')
|
|
const { huyaNativeConnector } = await import('./huya-native/huya-native-connector.js')
|
|
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
|
|
const orderNo = `IT-HUYA-RESTORE-${suffix}`
|
|
const platformUid = '1686664168'
|
|
let orderId = 0
|
|
let configId = 0
|
|
let credentialId = 0
|
|
let adminId = 0
|
|
let restoredSessionId = ''
|
|
try {
|
|
const admin = await query<{ id: number }>(
|
|
`INSERT INTO admin_users (username, password_hash, role, status, created_at, updated_at)
|
|
VALUES ($1, 'x', 'support', 'active', NOW(), NOW()) RETURNING id`,
|
|
[`it_huya_restore_admin_${suffix}`],
|
|
)
|
|
adminId = Number(admin.rows[0]?.id || 0)
|
|
const result = await createSemiAutoMock({
|
|
orderNo,
|
|
skuName: `虎牙CK恢复-${suffix}`,
|
|
quantity: 1,
|
|
pageTitle: '虎牙CK恢复集成测试',
|
|
connectorMode: 'embedded',
|
|
})
|
|
orderId = result.orderId
|
|
configId = result.configId
|
|
credentialId = await withTransaction((client) =>
|
|
upsertSemiAutoCredentialWithClient(client, {
|
|
platform: 'huya',
|
|
source: 'sms',
|
|
payload: {
|
|
platformUid,
|
|
nickname: '虎牙恢复测试',
|
|
cookies: [
|
|
{
|
|
name: 'yyuid',
|
|
value: platformUid,
|
|
domain: '.huya.com',
|
|
path: '/',
|
|
secure: true,
|
|
httpOnly: false,
|
|
expiresAt: null,
|
|
},
|
|
{
|
|
name: 'udb_uid',
|
|
value: platformUid,
|
|
domain: '.huya.com',
|
|
path: '/',
|
|
secure: true,
|
|
httpOnly: false,
|
|
expiresAt: null,
|
|
},
|
|
{
|
|
name: 'udb_cred',
|
|
value: `restored-${suffix}`,
|
|
domain: '.huya.com',
|
|
path: '/',
|
|
secure: true,
|
|
httpOnly: false,
|
|
expiresAt: null,
|
|
},
|
|
],
|
|
},
|
|
}),
|
|
)
|
|
await query(
|
|
`UPDATE semi_auto_tasks
|
|
SET credential_id = $2,
|
|
connector_session_id = $3,
|
|
huya_uid = $4,
|
|
login_status = 'authenticated',
|
|
binding_status = 'not_started',
|
|
execution_status = 'waiting_operator',
|
|
updated_at = NOW()
|
|
WHERE id = $1`,
|
|
[result.taskId, credentialId, `missing-session-${suffix}`, platformUid],
|
|
)
|
|
|
|
const injection = await createAdminBrowserSession(result.taskId, 'https://www.huya.com/', {
|
|
userId: adminId,
|
|
role: 'support',
|
|
displayName: '集成测试客服',
|
|
} as never)
|
|
|
|
// 后台没有「领取」动作:另一个客服也能直接操作同一任务,不会被领取人挡住。
|
|
const secondAdmin = await query<{ id: number }>(
|
|
`INSERT INTO admin_users (username, password_hash, role, status, created_at, updated_at)
|
|
VALUES ($1, 'x', 'support', 'active', NOW(), NOW()) RETURNING id`,
|
|
[`it_huya_restore_admin2_${suffix}`],
|
|
)
|
|
const secondAdminId = Number(secondAdmin.rows[0]?.id || 0)
|
|
const secondInjection = await createAdminBrowserSession(
|
|
result.taskId,
|
|
'https://www.huya.com/',
|
|
{ userId: secondAdminId, role: 'support', displayName: '另一个客服' } as never,
|
|
)
|
|
assert.equal(secondInjection.cookies.length > 0, true)
|
|
const operator = await query<{ assigned_admin_user_id: number | null }>(
|
|
'SELECT assigned_admin_user_id FROM semi_auto_tasks WHERE id = $1',
|
|
[result.taskId],
|
|
)
|
|
// 只记录最近操作人,不构成门禁。
|
|
assert.equal(Number(operator.rows[0]?.assigned_admin_user_id), secondAdminId)
|
|
const restored = await query<{
|
|
connector_session_id: string
|
|
credential_session_restored: number
|
|
}>(
|
|
`SELECT task.connector_session_id,
|
|
COUNT(event.id) FILTER (
|
|
WHERE event.event_type = 'credential_session_restored'
|
|
)::int AS credential_session_restored
|
|
FROM semi_auto_tasks task
|
|
LEFT JOIN semi_auto_task_events event ON event.task_id = task.id
|
|
WHERE task.id = $1
|
|
GROUP BY task.connector_session_id`,
|
|
[result.taskId],
|
|
)
|
|
restoredSessionId = String(restored.rows[0]?.connector_session_id || '')
|
|
assert.ok(restoredSessionId)
|
|
assert.notEqual(restoredSessionId, `missing-session-${suffix}`)
|
|
assert.equal(Number(restored.rows[0]?.credential_session_restored), 1)
|
|
|
|
// 直接下发账号级 CK:没有票据、没有 TTL,权限靠后台登录态 + 领取人 + 审计。
|
|
assert.equal(injection.platform, 'huya')
|
|
// 传平台首页等于「没指定落地页」,必须回落到策略默认的兑换入口页。
|
|
assert.match(injection.targetUrl, /^https:\/\/m-shop\.huya\.com\/points\.html\?/)
|
|
assert.equal(
|
|
injection.cookies.find((cookie) => cookie.name === 'udb_cred')?.value,
|
|
`restored-${suffix}`,
|
|
)
|
|
assert.equal('ticket' in injection, false)
|
|
} finally {
|
|
if (restoredSessionId) {
|
|
await huyaNativeConnector.revokeSession(restoredSessionId).catch(() => undefined)
|
|
}
|
|
if (orderId > 0) await query('DELETE FROM orders WHERE id = $1', [orderId])
|
|
if (credentialId > 0) {
|
|
await query('DELETE FROM semi_auto_credentials WHERE id = $1', [credentialId])
|
|
}
|
|
if (adminId > 0) {
|
|
await query('DELETE FROM admin_users WHERE id = $1', [adminId])
|
|
}
|
|
if (configId > 0) {
|
|
await query('DELETE FROM manual_fulfillment_configs WHERE id = $1', [configId])
|
|
}
|
|
delete process.env.ENABLE_DEV_MOCK
|
|
await closeDb()
|
|
}
|
|
},
|
|
)
|
|
|
|
test(
|
|
'微博平台角色绑定事实收敛为等待客服处理',
|
|
{ skip: !TEST_DATABASE_URL ? '未设置 SEMI_AUTO_TASK_TEST_DATABASE_URL' : false },
|
|
async () => {
|
|
process.env.DATABASE_URL = TEST_DATABASE_URL
|
|
process.env.ENABLE_DEV_MOCK = '1'
|
|
const { closeDb, query, withTransaction } = await import('../../db/client.js')
|
|
const { createSemiAutoIntegrationMock } = await import('../dev-mock/dev-mock-service.js')
|
|
const { loadTask, updateBindingTask } = await import('./semi-auto-task-core.js')
|
|
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
|
|
const orderNo = `IT-WEIBO-BINDING-${suffix}`
|
|
let orderId = 0
|
|
let configId = 0
|
|
let mappingId = 0
|
|
try {
|
|
const result = await createSemiAutoIntegrationMock({
|
|
platform: 'weibo',
|
|
orderNo,
|
|
skuName: `微博绑定真实链路-${suffix}`,
|
|
quantity: 1,
|
|
connectorMode: 'embedded',
|
|
})
|
|
orderId = result.orderId
|
|
configId = result.configId
|
|
mappingId = result.mappingId
|
|
assert.equal(result.semiAutoPlatform, 'weibo')
|
|
assert.ok(result.taskId > 0)
|
|
|
|
await query(
|
|
`
|
|
UPDATE semi_auto_tasks
|
|
SET connector_session_id = $2,
|
|
login_status = 'authenticated',
|
|
execution_status = 'waiting_customer',
|
|
authenticated_at = NOW(),
|
|
updated_at = NOW()
|
|
WHERE id = $1
|
|
`,
|
|
[result.taskId, `it-weibo-session-${suffix}`],
|
|
)
|
|
const task = await loadTask(result.taskId)
|
|
const binding = await updateBindingTask(
|
|
task,
|
|
{
|
|
sessionId: `it-weibo-session-${suffix}`,
|
|
status: 'confirmed',
|
|
qrImage: '',
|
|
qrExpiresAt: '',
|
|
qrUrl: '',
|
|
bindGameAccount: '集成测试微博',
|
|
bindGameRole: '微博游戏角色',
|
|
bindGameRoleId: '',
|
|
bindGameChannel: '微信',
|
|
hasExistingBinding: true,
|
|
rebindRequested: false,
|
|
rebindCooldownDays: 0,
|
|
nextRebindAt: '',
|
|
message: '微博账号已绑定角色',
|
|
},
|
|
'connector',
|
|
)
|
|
|
|
assert.equal(binding.status, 'confirmed')
|
|
assert.equal(binding.comparison.verdict, 'unknown')
|
|
assert.equal(binding.comparison.message, '当前不是虎牙绑定任务')
|
|
const stored = await query<{
|
|
binding_status: string
|
|
execution_status: string
|
|
bind_game_role: string
|
|
bind_game_channel: string
|
|
}>(
|
|
`SELECT binding_status, execution_status, bind_game_role, bind_game_channel
|
|
FROM semi_auto_tasks WHERE id = $1`,
|
|
[result.taskId],
|
|
)
|
|
assert.equal(stored.rows[0]?.binding_status, 'confirmed')
|
|
assert.equal(stored.rows[0]?.execution_status, 'waiting_operator')
|
|
assert.equal(stored.rows[0]?.bind_game_role, '微博游戏角色')
|
|
assert.equal(stored.rows[0]?.bind_game_channel, '微信')
|
|
} finally {
|
|
await withTransaction(async (client) => {
|
|
await client.query("SET LOCAL session_replication_role = 'replica'")
|
|
if (configId > 0) {
|
|
await client.query('DELETE FROM manual_fulfillment_configs WHERE id = $1', [configId])
|
|
}
|
|
if (orderId > 0) {
|
|
await client.query('DELETE FROM order_source_snapshots WHERE order_id = $1', [orderId])
|
|
await client.query('DELETE FROM orders WHERE id = $1', [orderId])
|
|
}
|
|
if (mappingId > 0) {
|
|
await client.query('DELETE FROM internal_sku_mappings WHERE id = $1', [mappingId])
|
|
}
|
|
})
|
|
delete process.env.ENABLE_DEV_MOCK
|
|
await closeDb()
|
|
}
|
|
},
|
|
)
|
|
|
|
test(
|
|
'开发 Mock 可显式选择内置 Mock Connector',
|
|
{ skip: !TEST_DATABASE_URL ? '未设置 SEMI_AUTO_TASK_TEST_DATABASE_URL' : false },
|
|
async () => {
|
|
process.env.DATABASE_URL = TEST_DATABASE_URL
|
|
process.env.ENABLE_DEV_MOCK = '1'
|
|
const { closeDb, query } = await import('../../db/client.js')
|
|
const { createSemiAutoMock } = await import('../dev-mock/dev-mock-service.js')
|
|
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
|
|
const orderNo = `IT-MOCK-SA-MOCK-${suffix}`
|
|
let orderId = 0
|
|
let configId = 0
|
|
try {
|
|
const result = await createSemiAutoMock({
|
|
orderNo,
|
|
skuName: `半自动Mock连接器-${suffix}`,
|
|
quantity: 1,
|
|
connectorMode: 'mock',
|
|
})
|
|
orderId = result.orderId
|
|
configId = result.configId
|
|
assert.equal(result.connectorMode, 'mock')
|
|
|
|
const row = await query<{ connector_mode: string }>(
|
|
'SELECT connector_mode FROM semi_auto_tasks WHERE id = $1',
|
|
[result.taskId],
|
|
)
|
|
assert.equal(row.rows[0]?.connector_mode, 'mock')
|
|
} finally {
|
|
if (orderId > 0) await query('DELETE FROM orders WHERE id = $1', [orderId])
|
|
if (configId > 0) {
|
|
await query('DELETE FROM manual_fulfillment_configs WHERE id = $1', [configId])
|
|
}
|
|
delete process.env.ENABLE_DEV_MOCK
|
|
await closeDb()
|
|
}
|
|
},
|
|
)
|
|
|
|
test(
|
|
'客户先保存虎牙角色资料,再完成短信登录并保存 CK',
|
|
{ skip: !TEST_DATABASE_URL ? '未设置 SEMI_AUTO_TASK_TEST_DATABASE_URL' : false },
|
|
async () => {
|
|
process.env.DATABASE_URL = TEST_DATABASE_URL
|
|
process.env.ENABLE_DEV_MOCK = '1'
|
|
const { closeDb, query } = await import('../../db/client.js')
|
|
const { createSemiAutoMock } = await import('../dev-mock/dev-mock-service.js')
|
|
const { resetMockSessions } = await import('../dev-mock/mock-semi-auto-connector.js')
|
|
const {
|
|
listPublicSemiAutoTasks,
|
|
loginPublicHuyaSms,
|
|
savePublicTaskProfile,
|
|
sendPublicHuyaSmsCode,
|
|
} = await import('./semi-auto-task-service.js')
|
|
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
|
|
const orderNo = `IT-HUYA-SMS-${suffix}`
|
|
let orderId = 0
|
|
let configId = 0
|
|
let credentialId = 0
|
|
try {
|
|
const result = await createSemiAutoMock({
|
|
orderNo,
|
|
skuName: `虎牙短信登录-${suffix}`,
|
|
quantity: 1,
|
|
connectorMode: 'mock',
|
|
})
|
|
orderId = result.orderId
|
|
configId = result.configId
|
|
|
|
await expectErrorCode(
|
|
() =>
|
|
savePublicTaskProfile(orderNo, result.taskId, {
|
|
roleName: 'Mock虎牙角色',
|
|
serverZone: '安卓V区',
|
|
}),
|
|
'semi_auto_profile_required',
|
|
)
|
|
const saved = await savePublicTaskProfile(orderNo, result.taskId, {
|
|
roleName: 'Mock虎牙角色',
|
|
roleId: '4212063544',
|
|
serverZone: '安卓V区',
|
|
homepageScreenshotObjectKey: await createHomepageScreenshotAsset(result.taskId),
|
|
})
|
|
assert.equal(saved.task.customerGameRoleId, '4212063544')
|
|
assert.equal(saved.task.loginStatus, 'waiting_login')
|
|
assert.equal(saved.task.displayStatus.label, '等待客户授权')
|
|
|
|
const sent = await sendPublicHuyaSmsCode(orderNo, result.taskId, '13800138000')
|
|
assert.equal(sent.ok, true)
|
|
const waiting = await query<{
|
|
connector_session_id: string
|
|
login_status: string
|
|
execution_status: string
|
|
}>(
|
|
`SELECT connector_session_id, login_status, execution_status
|
|
FROM semi_auto_tasks WHERE id = $1`,
|
|
[result.taskId],
|
|
)
|
|
assert.ok(waiting.rows[0]?.connector_session_id)
|
|
assert.equal(waiting.rows[0]?.login_status, 'waiting_login')
|
|
assert.equal(waiting.rows[0]?.execution_status, 'waiting_customer')
|
|
|
|
await loginPublicHuyaSms(orderNo, result.taskId, {
|
|
mobile: '13800138000',
|
|
code: '123456',
|
|
})
|
|
const tasks = await listPublicSemiAutoTasks(orderNo)
|
|
assert.equal(tasks[0]?.loginStatus, 'authenticated')
|
|
// 虎牙登录成功只代表取得 CK,仍需完成角色绑定,不能直接进入等待客服。
|
|
assert.equal(tasks[0]?.executionStatus, 'waiting_customer')
|
|
assert.equal(tasks[0]?.displayStatus.label, '等待客户绑定角色')
|
|
assert.equal(tasks[0]?.customerGameRoleName, 'Mock虎牙角色')
|
|
assert.equal(tasks[0]?.customerGameRoleId, '4212063544')
|
|
assert.equal(tasks[0]?.credentialSource, 'sms')
|
|
assert.ok(tasks[0]?.huyaUid)
|
|
assert.equal(tasks[0]?.platformNickname, 'Mock虎牙用户')
|
|
|
|
const stored = await query<{
|
|
id: number
|
|
credential_source: string
|
|
credential_payload_json: string
|
|
platform_nickname: string
|
|
huya_uid: string
|
|
}>(
|
|
`SELECT credential.id, credential.credential_source,
|
|
credential.credential_payload_json,
|
|
task.platform_nickname, task.huya_uid
|
|
FROM semi_auto_tasks task
|
|
JOIN semi_auto_credentials credential ON credential.id = task.credential_id
|
|
WHERE task.id = $1`,
|
|
[result.taskId],
|
|
)
|
|
credentialId = Number(stored.rows[0]?.id || 0)
|
|
assert.ok(credentialId > 0)
|
|
assert.equal(stored.rows[0]?.credential_source, 'sms')
|
|
assert.match(stored.rows[0]?.credential_payload_json || '', /mock_huya_session/)
|
|
assert.equal(stored.rows[0]?.platform_nickname, 'Mock虎牙用户')
|
|
assert.equal(stored.rows[0]?.huya_uid, tasks[0]?.huyaUid)
|
|
} finally {
|
|
if (orderId > 0) await query('DELETE FROM orders WHERE id = $1', [orderId])
|
|
if (configId > 0) {
|
|
await query('DELETE FROM manual_fulfillment_configs WHERE id = $1', [configId])
|
|
}
|
|
if (credentialId > 0) {
|
|
await query('DELETE FROM semi_auto_credentials WHERE id = $1', [credentialId])
|
|
}
|
|
resetMockSessions()
|
|
delete process.env.ENABLE_DEV_MOCK
|
|
await closeDb()
|
|
}
|
|
},
|
|
)
|
|
|
|
test(
|
|
'真实订单入口可生成 manual 履约和半自动任务',
|
|
{ skip: !TEST_DATABASE_URL ? '未设置 SEMI_AUTO_TASK_TEST_DATABASE_URL' : false },
|
|
async () => {
|
|
process.env.DATABASE_URL = TEST_DATABASE_URL
|
|
process.env.ENABLE_DEV_MOCK = '1'
|
|
const { closeDb, query, withTransaction } = await import('../../db/client.js')
|
|
const { createSemiAutoIntegrationMock } = await import('../dev-mock/dev-mock-service.js')
|
|
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
|
|
const orderNo = `IT-INTEGRATION-SA-${suffix}`
|
|
let orderId = 0
|
|
let configId = 0
|
|
let mappingId = 0
|
|
try {
|
|
const result = await createSemiAutoIntegrationMock({
|
|
platform: 'huya',
|
|
orderNo,
|
|
skuName: `真实链路虎牙测试-${suffix}`,
|
|
quantity: 1,
|
|
connectorMode: 'embedded',
|
|
})
|
|
orderId = result.orderId
|
|
configId = result.configId
|
|
mappingId = result.mappingId
|
|
assert.equal(result.pipeline, 'order_service')
|
|
assert.equal(result.orderNo, orderNo)
|
|
assert.ok(result.orderItemId > 0)
|
|
assert.ok(result.fulfillmentId > 0)
|
|
assert.ok(result.taskId > 0)
|
|
|
|
const stored = await query<{
|
|
channel: string
|
|
fulfillment_status: string
|
|
login_status: string
|
|
execution_status: string
|
|
config_id: number
|
|
}>(
|
|
`
|
|
SELECT
|
|
f.channel,
|
|
f.status AS fulfillment_status,
|
|
task.login_status,
|
|
task.execution_status,
|
|
task.manual_fulfillment_config_id AS config_id
|
|
FROM semi_auto_tasks task
|
|
JOIN fulfillments f ON f.id = task.fulfillment_id
|
|
WHERE task.id = $1
|
|
`,
|
|
[result.taskId],
|
|
)
|
|
assert.equal(stored.rows[0]?.channel, 'manual')
|
|
assert.equal(stored.rows[0]?.fulfillment_status, 'assigned')
|
|
assert.equal(stored.rows[0]?.login_status, 'waiting_login')
|
|
assert.equal(stored.rows[0]?.execution_status, 'waiting_customer')
|
|
assert.equal(Number(stored.rows[0]?.config_id), result.configId)
|
|
|
|
const mapping = await query<{ internal_sku: string }>(
|
|
'SELECT internal_sku FROM internal_sku_mappings WHERE id = $1',
|
|
[result.mappingId],
|
|
)
|
|
assert.equal(mapping.rows[0]?.internal_sku, result.skuKey)
|
|
} finally {
|
|
await withTransaction(async (client) => {
|
|
await client.query("SET LOCAL session_replication_role = 'replica'")
|
|
if (configId > 0) {
|
|
await client.query('DELETE FROM manual_fulfillment_configs WHERE id = $1', [configId])
|
|
}
|
|
if (orderId > 0) {
|
|
await client.query('DELETE FROM order_source_snapshots WHERE order_id = $1', [orderId])
|
|
await client.query('DELETE FROM orders WHERE id = $1', [orderId])
|
|
}
|
|
if (mappingId > 0) {
|
|
await client.query('DELETE FROM internal_sku_mappings WHERE id = $1', [mappingId])
|
|
}
|
|
})
|
|
delete process.env.ENABLE_DEV_MOCK
|
|
await closeDb()
|
|
}
|
|
},
|
|
)
|
|
|
|
test(
|
|
'斗鱼直播账号履约 Mock 只生成正式人工履约,不生成半自动任务',
|
|
{ skip: !TEST_DATABASE_URL ? '未设置 SEMI_AUTO_TASK_TEST_DATABASE_URL' : false },
|
|
async () => {
|
|
process.env.DATABASE_URL = TEST_DATABASE_URL
|
|
process.env.ENABLE_DEV_MOCK = '1'
|
|
const { closeDb, query, withTransaction } = await import('../../db/client.js')
|
|
const { createDouyuFulfillmentMock } = await import('../dev-mock/dev-mock-service.js')
|
|
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
|
|
const orderNo = `IT-DOUYU-FULFILLMENT-${suffix}`
|
|
const skuKey = `斗鱼精英宝典联调-${suffix}`
|
|
let orderId = 0
|
|
let configId = 0
|
|
let mappingId = 0
|
|
|
|
try {
|
|
const result = await createDouyuFulfillmentMock({
|
|
orderNo,
|
|
skuName: skuKey,
|
|
})
|
|
orderId = result.orderId
|
|
configId = result.configId
|
|
mappingId = result.mappingId
|
|
|
|
assert.equal(result.platform, 'douyu')
|
|
assert.equal(result.pipeline, 'order_service')
|
|
assert.equal(result.orderNo, orderNo)
|
|
assert.equal(result.skuKey, skuKey)
|
|
assert.ok(result.orderItemId > 0)
|
|
assert.ok(result.fulfillmentId > 0)
|
|
|
|
const stored = await query<{
|
|
channel: string
|
|
fulfillment_status: string
|
|
fulfillment_config_id: number
|
|
semi_auto_enabled: boolean
|
|
semi_auto_task_count: number
|
|
internal_sku: string
|
|
}>(
|
|
`
|
|
SELECT
|
|
f.channel,
|
|
f.status AS fulfillment_status,
|
|
f.fulfillment_config_id,
|
|
cfg.semi_auto_enabled,
|
|
(
|
|
SELECT COUNT(*)::int
|
|
FROM semi_auto_tasks task
|
|
WHERE task.order_item_id = f.order_item_id
|
|
) AS semi_auto_task_count,
|
|
resolve_internal_sku(oi.manual_sku_key, oi.sku_name, oi.sku_code) AS internal_sku
|
|
FROM fulfillments f
|
|
JOIN order_items oi ON oi.id = f.order_item_id
|
|
JOIN manual_fulfillment_configs cfg ON cfg.id = f.fulfillment_config_id
|
|
WHERE f.id = $1
|
|
`,
|
|
[result.fulfillmentId],
|
|
)
|
|
assert.equal(stored.rows[0]?.channel, 'manual')
|
|
assert.equal(stored.rows[0]?.fulfillment_status, 'assigned')
|
|
assert.equal(Number(stored.rows[0]?.fulfillment_config_id), result.configId)
|
|
assert.equal(stored.rows[0]?.semi_auto_enabled, false)
|
|
assert.equal(Number(stored.rows[0]?.semi_auto_task_count), 0)
|
|
assert.equal(stored.rows[0]?.internal_sku, skuKey)
|
|
|
|
const mapping = await query<{ internal_sku: string }>(
|
|
'SELECT internal_sku FROM internal_sku_mappings WHERE id = $1',
|
|
[result.mappingId],
|
|
)
|
|
assert.equal(mapping.rows[0]?.internal_sku, skuKey)
|
|
} finally {
|
|
await withTransaction(async (client) => {
|
|
await client.query("SET LOCAL session_replication_role = 'replica'")
|
|
if (configId > 0) {
|
|
await client.query('DELETE FROM manual_fulfillment_configs WHERE id = $1', [configId])
|
|
}
|
|
if (orderId > 0) {
|
|
await client.query('DELETE FROM order_source_snapshots WHERE order_id = $1', [orderId])
|
|
await client.query('DELETE FROM orders WHERE id = $1', [orderId])
|
|
}
|
|
if (mappingId > 0) {
|
|
await client.query('DELETE FROM internal_sku_mappings WHERE id = $1', [mappingId])
|
|
}
|
|
})
|
|
delete process.env.ENABLE_DEV_MOCK
|
|
await closeDb()
|
|
}
|
|
},
|
|
)
|
|
|
|
test(
|
|
'虎牙客户资料必须带归属本人的游戏主页截图',
|
|
{ skip: !TEST_DATABASE_URL ? '未设置 SEMI_AUTO_TASK_TEST_DATABASE_URL' : false },
|
|
async () => {
|
|
process.env.DATABASE_URL = TEST_DATABASE_URL
|
|
process.env.ENABLE_DEV_MOCK = '1'
|
|
const { closeDb, query } = await import('../../db/client.js')
|
|
const { createSemiAutoMock } = await import('../dev-mock/dev-mock-service.js')
|
|
const { resetMockSessions } = await import('../dev-mock/mock-semi-auto-connector.js')
|
|
const { savePublicTaskProfile } = await import('./semi-auto-task-service.js')
|
|
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
|
|
const orderNo = `IT-HUYA-SCREENSHOT-${suffix}`
|
|
let orderId = 0
|
|
let configId = 0
|
|
let taskId = 0
|
|
try {
|
|
const result = await createSemiAutoMock({
|
|
orderNo,
|
|
skuName: `虎牙主页截图-${suffix}`,
|
|
quantity: 1,
|
|
connectorMode: 'mock',
|
|
})
|
|
orderId = result.orderId
|
|
configId = result.configId
|
|
taskId = result.taskId
|
|
|
|
// 1. 合法截图资产 → 保存资料成功并落库。
|
|
const objectKey = await createHomepageScreenshotAsset(taskId)
|
|
const saved = await savePublicTaskProfile(orderNo, taskId, {
|
|
roleName: '截图测试角色',
|
|
roleId: '4212063544',
|
|
serverZone: '安卓Q区',
|
|
homepageScreenshotObjectKey: objectKey,
|
|
})
|
|
assert.equal(saved.task.customerGameRoleName, '截图测试角色')
|
|
assert.equal(saved.task.customerGameRoleId, '4212063544')
|
|
assert.equal(saved.task.customerServerZone, '安卓Q区')
|
|
assert.ok(saved.task.homepageScreenshotUrl)
|
|
assert.ok(saved.task.homepageScreenshotThumbnailUrl)
|
|
assert.equal(saved.task.homepageScreenshotFilename, 'game-home.png')
|
|
assert.ok(saved.task.homepageScreenshotUploadedAt)
|
|
|
|
const stored = await query<{
|
|
object_key: string
|
|
url: string
|
|
thumbnail_url: string
|
|
filename: string
|
|
uploaded_at: string | null
|
|
}>(
|
|
`SELECT customer_homepage_screenshot_object_key AS object_key,
|
|
customer_homepage_screenshot_url AS url,
|
|
customer_homepage_screenshot_thumbnail_url AS thumbnail_url,
|
|
customer_homepage_screenshot_filename AS filename,
|
|
customer_homepage_screenshot_uploaded_at AS uploaded_at
|
|
FROM semi_auto_tasks
|
|
WHERE id = $1`,
|
|
[taskId],
|
|
)
|
|
assert.equal(stored.rows[0]?.object_key, objectKey)
|
|
assert.ok(stored.rows[0]?.url)
|
|
assert.ok(stored.rows[0]?.thumbnail_url)
|
|
assert.equal(stored.rows[0]?.filename, 'game-home.png')
|
|
assert.ok(stored.rows[0]?.uploaded_at)
|
|
|
|
const event = await query<{ detail_json: { homepageScreenshotObjectKey?: string } }>(
|
|
`SELECT detail_json
|
|
FROM semi_auto_task_events
|
|
WHERE task_id = $1 AND event_type = 'customer_profile_saved'
|
|
ORDER BY id DESC
|
|
LIMIT 1`,
|
|
[taskId],
|
|
)
|
|
assert.equal(event.rows[0]?.detail_json?.homepageScreenshotObjectKey, objectKey)
|
|
|
|
// 2. 缺少截图 → 明确要求先上传。
|
|
await expectErrorCode(
|
|
() =>
|
|
savePublicTaskProfile(orderNo, taskId, {
|
|
roleName: '截图测试角色',
|
|
roleId: '4212063544',
|
|
serverZone: '安卓Q区',
|
|
}),
|
|
'semi_auto_homepage_screenshot_required',
|
|
)
|
|
|
|
// 3. 截图属于其它任务 → 归属校验失败。
|
|
const foreignObjectKey = await createHomepageScreenshotAsset(taskId, {
|
|
uploaderId: `semi-auto-task-${taskId + 999_999}`,
|
|
})
|
|
await expectErrorCode(
|
|
() =>
|
|
savePublicTaskProfile(orderNo, taskId, {
|
|
roleName: '截图测试角色',
|
|
roleId: '4212063544',
|
|
serverZone: '安卓Q区',
|
|
homepageScreenshotObjectKey: foreignObjectKey,
|
|
}),
|
|
'semi_auto_homepage_screenshot_invalid',
|
|
)
|
|
|
|
// 4. 游戏角色 UID 非纯数字 → 资料校验失败。
|
|
await expectErrorCode(
|
|
() =>
|
|
savePublicTaskProfile(orderNo, taskId, {
|
|
roleName: '截图测试角色',
|
|
roleId: 'UID-not-number',
|
|
serverZone: '安卓Q区',
|
|
homepageScreenshotObjectKey: objectKey,
|
|
}),
|
|
'semi_auto_profile_role_id_invalid',
|
|
)
|
|
|
|
// 5. 角色名混入 UID / 区服 → 资料校验失败。
|
|
await expectErrorCode(
|
|
() =>
|
|
savePublicTaskProfile(orderNo, taskId, {
|
|
roleName: '截图测试角色 4212063544',
|
|
roleId: '4212063544',
|
|
serverZone: '安卓Q区',
|
|
homepageScreenshotObjectKey: objectKey,
|
|
}),
|
|
'semi_auto_profile_role_name_invalid',
|
|
)
|
|
} finally {
|
|
if (taskId > 0) {
|
|
await query('DELETE FROM file_assets WHERE uploader_id = $1', [`semi-auto-task-${taskId}`])
|
|
await query('DELETE FROM file_assets WHERE uploader_id = $1', [
|
|
`semi-auto-task-${taskId + 999_999}`,
|
|
])
|
|
}
|
|
if (orderId > 0) await query('DELETE FROM orders WHERE id = $1', [orderId])
|
|
if (configId > 0) {
|
|
await query('DELETE FROM manual_fulfillment_configs WHERE id = $1', [configId])
|
|
}
|
|
resetMockSessions()
|
|
delete process.env.ENABLE_DEV_MOCK
|
|
await closeDb()
|
|
}
|
|
},
|
|
)
|