This commit is contained in:
2026-11-25 10:54:46 +08:00
9 changed files with 529 additions and 5 deletions
@@ -1,6 +1,13 @@
import type { PoolClient } from 'pg'
import { runtimeConfig } from '../../config/runtime.js'
import { query, withTransaction } from '../../db/client.js'
import { getFileAssetByObjectKey } from '../../repositories/file-asset-repo.js'
import {
ORDER_SERVICE_SCREENSHOT_CONTENT_TYPES,
buildFileUrl,
uploadFileAsset,
} from '../file-storage/file-storage-service.js'
import {
publishCustomerOrderRealtimeChange,
publishRealtimeEvent,
@@ -26,6 +33,11 @@ type DouyuTaskRow = {
customer_role_name: string
customer_platform: string
customer_system: string
customer_homepage_screenshot_object_key: string
customer_homepage_screenshot_url: string
customer_homepage_screenshot_thumbnail_url: string
customer_homepage_screenshot_filename: string
customer_homepage_screenshot_uploaded_at: string | null
binding_phase: string
live_execution_status: string
live_binding_status: string
@@ -99,6 +111,8 @@ type DouyuFulfillmentSettingsRow = {
const AUTO_DISCOVERY_INTERVAL_MS = 15_000
const LIVE_STATE_SYNC_INTERVAL_MS = 60_000
const TERMINAL_TASK_STATUSES = new Set(['completed', 'cancelled'])
const DOUYU_HOMEPAGE_SCREENSHOT_SCENE = 'douyu-homepage-screenshot'
const DOUYU_HOMEPAGE_UPLOADER_TYPE = 'douyu-customer'
let lastAutomaticDiscoveryAt = 0
let automaticDiscoveryInFlight: Promise<{ created: number; updated: number } | null> | null = null
@@ -124,6 +138,36 @@ function liveHubBaseUrl() {
.replace(/\/+$/, '')
}
function douyuHomepageScreenshotUploaderId(taskId: number) {
return `douyu-task-${taskId}`
}
function absoluteOrderSiteFileUrl(pathname: string) {
const normalizedPath = String(pathname || '').trim()
if (!normalizedPath) return ''
try {
return new URL(normalizedPath, new URL(runtimeConfig.orders.claimBaseUrl).origin).toString()
} catch {
return normalizedPath
}
}
export function hasDouyuCustomerProfile(input: {
customer_role_name?: string
customer_platform?: string
customer_system?: string
customer_homepage_screenshot_object_key?: string
customer_homepage_screenshot_url?: string
}) {
return Boolean(
String(input.customer_role_name || '').trim() &&
['wechat', 'qq'].includes(String(input.customer_platform || '').trim()) &&
['ios', 'android'].includes(String(input.customer_system || '').trim()) &&
String(input.customer_homepage_screenshot_object_key || '').trim() &&
String(input.customer_homepage_screenshot_url || '').trim(),
)
}
export async function getDouyuFulfillmentSettings() {
const result = await query<DouyuFulfillmentSettingsRow>(
`
@@ -417,7 +461,18 @@ export function statusForLive(live: LiveBindingState): string {
if (live.customerProfileReset === true) return 'waiting_profile'
if (live.executionStatus === 'completed') return 'completed'
if (live.executionStatus === 'cancelled') return 'cancelled'
if (live.bindingStatus === 'failed' || BINDING_FAILURE_ISSUES.has(live.issueCode)) {
const bindTaskFailed = ['failed', 'error', 'stopped'].includes(live.bindTaskStatus)
const bindingStarted =
live.bindingStatus !== 'not_started' ||
Boolean(live.bindTaskId) ||
Boolean(live.qrUrl) ||
live.bindReadyForConfirm ||
live.bindConfirmed
if (
live.bindingStatus === 'failed' ||
bindTaskFailed ||
(BINDING_FAILURE_ISSUES.has(live.issueCode) && bindingStarted)
) {
return 'failed'
}
if (live.executionStatus === 'manual_required') return 'manual_required'
@@ -504,6 +559,26 @@ async function updateTaskFromLiveState(
customer_role_name = CASE WHEN $19 THEN '' ELSE customer_role_name END,
customer_platform = CASE WHEN $19 THEN '' ELSE customer_platform END,
customer_system = CASE WHEN $19 THEN '' ELSE customer_system END,
customer_homepage_screenshot_object_key = CASE
WHEN $19 THEN ''
ELSE customer_homepage_screenshot_object_key
END,
customer_homepage_screenshot_url = CASE
WHEN $19 THEN ''
ELSE customer_homepage_screenshot_url
END,
customer_homepage_screenshot_thumbnail_url = CASE
WHEN $19 THEN ''
ELSE customer_homepage_screenshot_thumbnail_url
END,
customer_homepage_screenshot_filename = CASE
WHEN $19 THEN ''
ELSE customer_homepage_screenshot_filename
END,
customer_homepage_screenshot_uploaded_at = CASE
WHEN $19 THEN NULL
ELSE customer_homepage_screenshot_uploaded_at
END,
qr_url = $15,
qr_generated_at = NULLIF($16, '')::timestamptz,
qr_expires_at = NULLIF($17, '')::timestamptz,
@@ -787,9 +862,34 @@ export async function getCustomerDouyuFulfillment(orderNo: string) {
return localCustomerFulfillment(task)
}
export async function uploadDouyuCustomerHomepageScreenshot(
orderNo: string,
file: Express.Multer.File | null | undefined,
) {
const task = await loadTaskByOrderNo(orderNo)
if (task.status === 'completed' || task.status === 'cancelled') {
throw createHttpError('当前订单已结束,不能上传资料', {
statusCode: 409,
errorCode: 'douyu_fulfillment_closed',
})
}
return uploadFileAsset({
file,
scene: DOUYU_HOMEPAGE_SCREENSHOT_SCENE,
uploaderType: DOUYU_HOMEPAGE_UPLOADER_TYPE,
uploaderId: douyuHomepageScreenshotUploaderId(task.id),
allowedContentTypes: ORDER_SERVICE_SCREENSHOT_CONTENT_TYPES,
})
}
export async function saveDouyuCustomerProfile(
orderNo: string,
input: { roleName?: unknown; platform?: unknown; system?: unknown },
input: {
roleName?: unknown
platform?: unknown
system?: unknown
homepageScreenshotObjectKey?: unknown
},
) {
const task = await loadTaskByOrderNo(orderNo)
if (task.status === 'completed' || task.status === 'cancelled') {
@@ -807,29 +907,70 @@ export async function saveDouyuCustomerProfile(
const system = String(input.system ?? '')
.trim()
.toLowerCase()
const homepageScreenshotObjectKey = String(input.homepageScreenshotObjectKey ?? '')
.trim()
.slice(0, 512)
if (!roleName || !['wechat', 'qq'].includes(platform) || !['ios', 'android'].includes(system)) {
throw createHttpError('请完整填写角色名、微信/QQ 和苹果/安卓', {
statusCode: 400,
errorCode: 'douyu_customer_profile_invalid',
})
}
if (!homepageScreenshotObjectKey) {
throw createHttpError('请上传游戏主页截图', {
statusCode: 400,
errorCode: 'douyu_customer_homepage_screenshot_required',
})
}
await withTransaction(async (client) => {
const asset = await getFileAssetByObjectKey(homepageScreenshotObjectKey, client)
if (
!asset ||
asset.uploader_type !== DOUYU_HOMEPAGE_UPLOADER_TYPE ||
asset.uploader_id !== douyuHomepageScreenshotUploaderId(task.id) ||
asset.scene !== DOUYU_HOMEPAGE_SCREENSHOT_SCENE ||
!ORDER_SERVICE_SCREENSHOT_CONTENT_TYPES.has(String(asset.content_type || '').trim())
) {
throw createHttpError('主页截图无效,请重新上传', {
statusCode: 400,
errorCode: 'douyu_customer_homepage_screenshot_invalid',
})
}
const screenshotUrl = absoluteOrderSiteFileUrl(buildFileUrl(asset.object_key))
const thumbnailUrl = absoluteOrderSiteFileUrl(
buildFileUrl(asset.thumbnail_object_key || asset.object_key),
)
await client.query(
`
UPDATE douyu_fulfillment_tasks
SET customer_role_name = $2,
customer_platform = $3,
customer_system = $4,
customer_homepage_screenshot_object_key = $5,
customer_homepage_screenshot_url = $6,
customer_homepage_screenshot_thumbnail_url = $7,
customer_homepage_screenshot_filename = $8,
customer_homepage_screenshot_uploaded_at = NOW(),
status = CASE WHEN status = 'waiting_profile' THEN 'preparing' ELSE status END,
updated_at = NOW()
WHERE id = $1
`,
[task.id, roleName, platform, system],
[
task.id,
roleName,
platform,
system,
asset.object_key,
screenshotUrl,
thumbnailUrl,
asset.original_filename,
],
)
await appendEvent(client, task.id, 'customer_profile_saved', 'customer', {
roleName,
platform,
system,
homepageScreenshotObjectKey: asset.object_key,
})
})
return getCustomerDouyuFulfillment(orderNo)
@@ -837,6 +978,12 @@ export async function saveDouyuCustomerProfile(
export async function startDouyuCustomerBinding(orderNo: string, forceRefresh = false) {
let task = await loadTaskByOrderNo(orderNo)
if (!hasDouyuCustomerProfile(task)) {
throw createHttpError('请先提交游戏角色和游戏主页截图,再开始绑定', {
statusCode: 409,
errorCode: 'douyu_customer_profile_required',
})
}
if (!task.live_session_id) {
const session = await ensureLiveSession(task)
task = session.task
@@ -43,6 +43,20 @@ test('斗鱼客户资料角色名不一致时禁止确认', () => {
assert.equal(result.roleMatched, false)
})
test('账号换绑冷却但尚未开始绑定,不应显示角色绑定失败', () => {
const status = statusForLive({
executionStatus: 'ready',
bindingStatus: 'not_started',
issueCode: 'account_role_cooldown',
bindTaskId: null,
qrUrl: '',
bindReadyForConfirm: false,
bindConfirmed: false,
accountReady: false,
} as never)
assert.equal(status, 'preparing')
})
test('绑定失败优先于旧角色确认标记', () => {
const status = statusForLive({
executionStatus: 'manual_required',