重构:前端架构优化 - 消灭巨石文件,统一代码规范

Phase 1 - 消灭巨石页面:
- 拆分 AdminKuaishouCloudFulfillmentView (1,224行→kuaishou-cloud/子目录)
- 拆分 AdminFulfillmentBindingsView (989行→bindings/子目录)
- 拆分 AdminTaskDetailView (1,007行→9个子组件+2个composable)
- 合并去重 useClaimPage + useAdminManualRedeemPage (1,554行→共享模块+差异化薄层)
- 拆分 services/admin/platform-config.ts (477行→8个领域子模块)

Phase 2 - 架构收口:
- 拆分 types/admin.ts (925行→13个子文件+platform-config/子目录)
- 统一 API code 检查(http.ts拦截器统一处理业务错误)
- 修改 apiPost 签名消除 as unknown as 类型断言(6处)
- 新增 BusinessError 类型便于错误分类处理

所有改动通过 vue-tsc --noEmit 零错误和 vite build 验证
This commit is contained in:
yml2213
2026-05-17 09:26:13 +08:00
parent d8c411d67f
commit a77198b218
81 changed files with 6498 additions and 5248 deletions
@@ -19,22 +19,33 @@ import type { AdminInventorySkuSuggestion, AdminManualRedeemDetail } from '@/typ
import type { TencentLoginType } from '@/types/tencent/session'
import { notifyTencentActionError } from './tencent/session-errors'
const DEFAULT_LOGIN_TYPE: TencentLoginType = 'qq'
const POLL_INTERVAL_MS = 2500
const POLL_FAILURE_LIMIT = 3
const ACTIVE_TASK_STATUSES = new Set(['claimed', 'role_confirmed', 'redeeming'])
import {
useSessionPolling,
useSessionQrDisplay,
useSessionRoleFacts,
useSessionResultFacts,
buildRedeemBlockedReason,
resolveTaskStatusLabel,
syncLoginTypeFromDetail,
mergeSessionDetail,
shouldRefreshQrImage,
shouldKeepPolling,
DEFAULT_LOGIN_TYPE,
} from './shared'
export function useAdminManualRedeemPage() {
const route = useRoute()
const router = useRouter()
// ── Form state (admin-only) ────────────────────────────────────────
const form = reactive({
proofValue: '',
skuCode: '',
remark: '',
})
const suggestions = ref<AdminInventorySkuSuggestion[]>([])
// ── Core state ────────────────────────────────────────────────────
const detail = ref<AdminManualRedeemDetail | null>(null)
const detailLoading = ref(false)
const createLoading = ref(false)
@@ -42,17 +53,14 @@ export function useAdminManualRedeemPage() {
const roleConfirmLoading = ref(false)
const redeemLoading = ref(false)
const closeLoading = ref(false)
const pollWarningMessage = ref('')
const qrImageNaturalWidth = ref(0)
const loginType = ref<TencentLoginType>(DEFAULT_LOGIN_TYPE)
// ── Screenshot state (admin-only) ──────────────────────────────────
const screenshotBlob = ref<Blob | null>(null)
const screenshotUrl = ref('')
const screenshotLoading = ref(false)
const loginType = ref<TencentLoginType>(DEFAULT_LOGIN_TYPE)
let pollTimer: ReturnType<typeof setTimeout> | null = null
let pollToken = 0
let pollFailureCount = 0
// ── Derived state ──────────────────────────────────────────────────
const session = computed(() => detail.value?.session || null)
const task = computed(() => detail.value?.task || null)
const order = computed(() => detail.value?.order || null)
@@ -66,12 +74,6 @@ export function useAdminManualRedeemPage() {
)
const hasSession = computed(() => Boolean(session.value?.sessionId))
const loginTypeLabel = computed(() => (loginType.value === 'wx' ? '微信' : 'QQ'))
const sessionNotice = computed(
() => pollWarningMessage.value || session.value?.notice || task.value?.lastError || '',
)
const qrImage = computed(() =>
session.value?.qrImageBase64 ? `data:image/png;base64,${session.value.qrImageBase64}` : '',
)
const currentTaskId = computed(() => Number(task.value?.taskId || route.query.taskId || 0) || 0)
const reviewReady = computed(
() => Boolean(session.value?.review?.capturedAt) && task.value?.status !== 'redeemed',
@@ -79,19 +81,67 @@ export function useAdminManualRedeemPage() {
const resultReady = computed(
() => Boolean(result.value?.screenshotReady) && task.value?.status === 'redeemed',
)
// ── Polling ────────────────────────────────────────────────────────
const {
pollWarningMessage,
startPolling,
resetPolling,
resetPollingWarning,
handleSilentPollingError,
} = useSessionPolling({
hasSession: computed(() => Boolean(task.value?.taskId && hasSession.value)),
shouldKeepPolling: computed(() => shouldKeepPolling(detail.value)),
onPollTick: () => refreshSessionSummary({ silent: true }),
pollWarningPrefix: '人工兑换状态刷新失败',
})
const sessionNotice = computed(
() => pollWarningMessage.value || session.value?.notice || task.value?.lastError || '',
)
// ── QR display ─────────────────────────────────────────────────────
const {
qrImage,
qrFigureStyle,
qrPreviewWidth,
handleQrImageLoad,
} = useSessionQrDisplay({ session })
// ── Presentation ───────────────────────────────────────────────────
const loginTabs = [
{ value: 'qq' as const, label: 'QQ账号登录' },
{ value: 'wx' as const, label: '微信账号登录' },
]
const statusLabel = computed(() =>
resolveTaskStatusLabel(task.value?.status, session.value?.status),
resolveTaskStatusLabel(task.value?.status, session.value?.status, 'admin'),
)
const initButtonLabel = computed(() => `生成${loginTypeLabel.value}二维码`)
const scanInstruction = computed(
() => `请让客户使用${loginTypeLabel.value}扫码,并在手机上确认登录`,
)
const roleFacts = computed(() => [
const { roleFacts } = useSessionRoleFacts({
activityInfo,
statusLabel,
roleFactDefaults: { nickname: '等待客户登录' },
})
const proofValue = computed(() => manualRequest.value?.proofValue || order.value?.platformOrderId || '-')
const { resultFacts } = useSessionResultFacts({
order,
orderItem,
result,
resultFactOverrides: {
firstLabel: '唯一凭据',
firstValue: proofValue,
},
})
// Admin overrides roleFacts to include "所在大区" and exclude "任务状态"
const adminRoleFacts = computed(() => [
{
label: '登录昵称',
value: activityInfo.value?.nickname || '等待客户登录',
@@ -110,24 +160,7 @@ export function useAdminManualRedeemPage() {
value: activityInfo.value?.role?.area || '未识别',
},
])
const resultFacts = computed(() => [
{
label: '唯一凭据',
value: manualRequest.value?.proofValue || order.value?.platformOrderId || '-',
},
{
label: '商品',
value: orderItem.value?.skuName || '-',
},
{
label: '业务返回码',
value: result.value?.resultCode || '-',
},
{
label: '业务消息',
value: result.value?.resultMessage || '尚未兑换',
},
])
const canConfirmRole = computed(() =>
Boolean(
task.value &&
@@ -144,29 +177,18 @@ export function useAdminManualRedeemPage() {
!redeemLoading.value,
),
)
const redeemBlockedReason = computed(() => {
if (!task.value) {
return '请先创建人工兑换任务并预占库存'
}
if (!hasSession.value) {
return `请先生成${loginTypeLabel.value}二维码并等待客户登录`
}
if (redeemLoading.value) {
return '兑换任务正在执行中'
}
if (!roleReady.value) {
return sessionNotice.value || '客户登录后,系统会自动同步角色和大区信息'
}
if (!roleConfirmed.value) {
return '请先让客户确认角色截图,再点击确认当前角色'
}
return ''
})
const redeemBlockedReason = computed(() =>
buildRedeemBlockedReason({
detail,
hasSession,
loginTypeLabel,
redeemLoading,
roleReady,
roleConfirmed,
sessionNotice,
context: 'admin',
}),
)
const redeemButtonLabel = computed(() => (redeemLoading.value ? '兑换中...' : '开始兑换'))
const screenshotEmptyTitle = computed(() =>
task.value?.status === 'redeemed' ? '未获取到结果图' : '等待角色截图',
@@ -181,8 +203,9 @@ export function useAdminManualRedeemPage() {
)
const hasActiveTask = computed(() => Boolean(task.value?.taskId))
// ── Watchers ───────────────────────────────────────────────────────
watch(qrImage, () => {
qrImageNaturalWidth.value = 0
// QR image natural width reset handled by useSessionQrDisplay
})
watch(
@@ -206,6 +229,85 @@ export function useAdminManualRedeemPage() {
clearScreenshotPreview()
})
// ── Helpers ────────────────────────────────────────────────────────
function applyLoginTypeFromDetail(nextDetail: AdminManualRedeemDetail) {
loginType.value = syncLoginTypeFromDetail(nextDetail, loginType.value)
}
function restartPollingIfNeeded(nextDetail = detail.value) {
resetPolling()
if (shouldKeepPolling(nextDetail)) {
startPolling()
}
}
function resolveSkuName(skuCode: string) {
const normalized = String(skuCode || '').trim()
const matched = suggestions.value.find(
(item) => String(item.skuCode || '').trim() === normalized,
)
return matched?.skuCode || normalized
}
// ── Screenshot helpers (admin-only) ───────────────────────────────
async function loadScreenshotPreview(nextDetail = detail.value) {
const taskId = Number(nextDetail?.task?.taskId || 0)
const shouldFetch = Boolean(
taskId && (nextDetail?.session?.review?.capturedAt || nextDetail?.result?.screenshotReady),
)
if (!shouldFetch) {
clearScreenshotPreview()
return
}
screenshotLoading.value = true
try {
const blob = await fetchAdminTaskScreenshot(taskId)
clearScreenshotPreview()
screenshotBlob.value = blob
screenshotUrl.value = URL.createObjectURL(blob)
} catch {
clearScreenshotPreview()
} finally {
screenshotLoading.value = false
}
}
function clearScreenshotPreview() {
screenshotBlob.value = null
if (screenshotUrl.value) {
URL.revokeObjectURL(screenshotUrl.value)
screenshotUrl.value = ''
}
}
async function writeImageBlobToClipboard(blob: Blob, fallbackMessage: string) {
if (
typeof navigator === 'undefined' ||
!navigator.clipboard ||
typeof window === 'undefined' ||
!('ClipboardItem' in window)
) {
throw new Error('当前浏览器不支持直接复制图片,请改用截图发送或下载')
}
try {
const ClipboardItemCtor = window.ClipboardItem as typeof ClipboardItem
await navigator.clipboard.write([
new ClipboardItemCtor({
[blob.type || 'image/png']: blob,
}),
])
} catch (error) {
throw error instanceof Error ? error : new Error(fallbackMessage)
}
}
// ── API flows ─────────────────────────────────────────────────────
async function loadSkuSuggestions(keyword = '') {
try {
const response = await fetchAdminManualRedeemSkuSuggestions({
@@ -375,12 +477,24 @@ export function useAdminManualRedeemPage() {
try {
const currentSession = detail.value?.session || null
const response = await fetchAdminManualRedeemSessionSummary(task.value.taskId)
detail.value = mergeDetail(detail.value, response.data)
detail.value = mergeSessionDetail(
detail.value,
response.data,
(currentSession, nextSession) => ({
review: nextSession.review ?? currentSession.review ?? null,
}),
)
loginType.value = syncLoginTypeFromDetail(response.data, loginType.value)
if (shouldRefreshQrImage(currentSession, response.data.session)) {
const fullResponse = await fetchAdminManualRedeemDetail(task.value.taskId)
detail.value = mergeDetail(detail.value, fullResponse.data)
const fullResponse = await fetchAdminManualRedeemDetail(task.value.taskId!)
detail.value = mergeSessionDetail(
detail.value,
fullResponse.data,
(currentSession, nextSession) => ({
review: nextSession.review ?? currentSession.review ?? null,
}),
)
loginType.value = syncLoginTypeFromDetail(fullResponse.data, loginType.value)
}
@@ -503,16 +617,6 @@ export function useAdminManualRedeemPage() {
})
}
function handleQrImageLoad(event: Event) {
const target = event.target
if (!(target instanceof HTMLImageElement)) {
return
}
qrImageNaturalWidth.value = target.naturalWidth || 0
}
async function copyQrImage() {
if (!qrImage.value) {
return false
@@ -560,151 +664,6 @@ export function useAdminManualRedeemPage() {
return true
}
async function writeImageBlobToClipboard(blob: Blob, fallbackMessage: string) {
if (
typeof navigator === 'undefined' ||
!navigator.clipboard ||
typeof window === 'undefined' ||
!('ClipboardItem' in window)
) {
throw new Error('当前浏览器不支持直接复制图片,请改用截图发送或下载')
}
try {
const ClipboardItemCtor = window.ClipboardItem as typeof ClipboardItem
await navigator.clipboard.write([
new ClipboardItemCtor({
[blob.type || 'image/png']: blob,
}),
])
} catch (error) {
throw error instanceof Error ? error : new Error(fallbackMessage)
}
}
async function loadScreenshotPreview(nextDetail = detail.value) {
const taskId = Number(nextDetail?.task?.taskId || 0)
const shouldFetch = Boolean(
taskId && (nextDetail?.session?.review?.capturedAt || nextDetail?.result?.screenshotReady),
)
if (!shouldFetch) {
clearScreenshotPreview()
return
}
screenshotLoading.value = true
try {
const blob = await fetchAdminTaskScreenshot(taskId)
clearScreenshotPreview()
screenshotBlob.value = blob
screenshotUrl.value = URL.createObjectURL(blob)
} catch {
clearScreenshotPreview()
} finally {
screenshotLoading.value = false
}
}
function clearScreenshotPreview() {
screenshotBlob.value = null
if (screenshotUrl.value) {
URL.revokeObjectURL(screenshotUrl.value)
screenshotUrl.value = ''
}
}
function resolveSkuName(skuCode: string) {
const normalized = String(skuCode || '').trim()
const matched = suggestions.value.find(
(item) => String(item.skuCode || '').trim() === normalized,
)
return matched?.skuCode || normalized
}
function startPolling() {
const tokenId = ++pollToken
const loop = async () => {
if (tokenId !== pollToken || !task.value?.taskId) {
return
}
await refreshSessionSummary({ silent: true })
if (tokenId !== pollToken || !shouldKeepPolling(detail.value)) {
return
}
pollTimer = setTimeout(() => {
void loop()
}, POLL_INTERVAL_MS)
}
pollTimer = setTimeout(() => {
void loop()
}, POLL_INTERVAL_MS)
}
function restartPollingIfNeeded(nextDetail = detail.value) {
resetPolling()
if (shouldKeepPolling(nextDetail)) {
startPolling()
}
}
function resetPolling() {
pollToken += 1
if (pollTimer) {
clearTimeout(pollTimer)
pollTimer = null
}
}
function resetPollingWarning() {
pollFailureCount = 0
pollWarningMessage.value = ''
}
function handleSilentPollingError(error: unknown) {
console.error(error)
pollFailureCount += 1
if (pollFailureCount < POLL_FAILURE_LIMIT) {
return
}
pollWarningMessage.value = '人工兑换状态刷新失败,已暂停自动轮询,请手动刷新。'
resetPolling()
}
const qrDisplayWidth = computed(() => {
const naturalWidth = qrImageNaturalWidth.value
if (!naturalWidth) {
return 220
}
if (naturalWidth < 160) {
return Math.min(naturalWidth * 2, 220)
}
return Math.min(naturalWidth, 240)
})
const qrFigureStyle = computed(() => ({
width: `${qrDisplayWidth.value}px`,
maxWidth: '100%',
}))
const qrPreviewWidth = computed(
() => `${Math.min(Math.max(qrDisplayWidth.value + 120, 360), 480)}px`,
)
return {
form,
suggestions,
@@ -732,7 +691,7 @@ export function useAdminManualRedeemPage() {
qrPreviewWidth,
statusLabel,
sessionNotice,
roleFacts,
roleFacts: adminRoleFacts,
resultFacts,
canConfirmRole,
canRedeem,
@@ -764,100 +723,3 @@ export function useAdminManualRedeemPage() {
downloadScreenshot,
}
}
function syncLoginTypeFromDetail(
detail: AdminManualRedeemDetail,
fallback: TencentLoginType = DEFAULT_LOGIN_TYPE,
) {
const nextLoginType = String(detail.session?.loginType || detail.task.loginType || '').trim()
if (nextLoginType === 'wx') {
return 'wx'
}
if (nextLoginType === 'qq') {
return 'qq'
}
return fallback
}
function shouldKeepPolling(detail: AdminManualRedeemDetail | null) {
if (!detail?.task?.taskId || !detail.session?.sessionId) {
return false
}
return ACTIVE_TASK_STATUSES.has(String(detail.task.status || '').trim())
}
function resolveTaskStatusLabel(taskStatus?: string, sessionStatus?: string) {
switch (taskStatus) {
case 'link_generated':
return '待生成二维码'
case 'claimed':
if (sessionStatus === 'scanned') {
return '客户待确认'
}
if (sessionStatus === 'logged_in' || sessionStatus === 'ready_to_redeem') {
return '已登录待复核'
}
return '等待客户登录'
case 'role_confirmed':
return '角色已确认'
case 'redeeming':
return '正在兑换'
case 'redeemed':
return '兑换完成'
case 'waiting_inventory':
return '等待库存'
case 'retry_pending':
return '等待重试'
case 'closed':
return '任务已关闭'
default:
return sessionStatus || taskStatus || '等待中'
}
}
function mergeDetail(current: AdminManualRedeemDetail | null, next: AdminManualRedeemDetail) {
if (next.session === null) {
return {
...next,
session: null,
}
}
if (!current?.session) {
return next
}
return {
...next,
session: {
...current.session,
...next.session,
qrImageBase64:
typeof next.session.qrImageBase64 === 'string'
? next.session.qrImageBase64
: current.session.qrImageBase64,
activityInfo: next.session.activityInfo ?? current.session.activityInfo ?? null,
review: next.session.review ?? current.session.review ?? null,
redeem: next.session.redeem ?? current.session.redeem ?? null,
artifacts: next.session.artifacts || current.session.artifacts,
},
}
}
function shouldRefreshQrImage(
currentSession: AdminManualRedeemDetail['session'],
nextSession: AdminManualRedeemDetail['session'],
) {
if (!currentSession || !nextSession || !nextSession.artifacts?.hasQrImage) {
return false
}
if (!currentSession.qrImageBase64) {
return true
}
return Boolean(nextSession.qrUpdatedAt && nextSession.qrUpdatedAt !== currentSession.qrUpdatedAt)
}