feat:修改客服报错问题

This commit is contained in:
李伊帆
2026-10-16 13:32:40 +08:00
parent 03839624ed
commit a4fa65de31
19 changed files with 291 additions and 89 deletions

View File

@@ -1,27 +1,40 @@
import { getStoredToken } from '@/utils/auth-token'
import type { CsChatWsPayload, CsMessageVo, CsSessionVo } from './support.types'
const HEARTBEAT_INTERVAL_MS = 25000
const RECONNECT_DELAY_MS = 25000
const RECONNECT_DELAY_MS = 2000
let socketTask: UniApp.SocketTask | null = null
let heartbeatTimer: ReturnType<typeof setInterval> | null = null
let reconnectTimer: ReturnType<typeof setTimeout> | null = null
let connecting = false
let manualClosed = false
let activeSessionId = ''
let socketOpened = false
/** 每次 connect / disconnect 递增,忽略已废弃连接的 onClose */
let connectionSeq = 0
const listeners = new Set<(payload: CsChatWsPayload) => void>()
function isH5Dev(): boolean {
return import.meta.env.DEV && typeof window !== 'undefined' && !!window.location?.host
}
function resolveCsChatWsBase(): string {
const configured = import.meta.env.VITE_CS_CHAT_WS_URL?.trim()
const forceDirect =
String(import.meta.env.VITE_CS_CHAT_WS_DIRECT ?? '').toLowerCase() === 'true'
if (isH5Dev() && !forceDirect) {
const proto = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
return `${proto}//${window.location.host}/app/cs/chat`
}
if (configured) {
return configured.replace(/[?#].*$/, '').replace(/\/$/, '')
}
const envBase = import.meta.env.VITE_API_BASE_URL?.trim() || ''
const fallback = import.meta.env.VITE_API_PROXY_TARGET?.trim() || 'http://192.168.0.212:8082'
const fallback =
import.meta.env.VITE_API_PROXY_TARGET?.trim() || 'http://192.168.0.222:8082'
const httpBase = envBase || fallback
const wsBase = httpBase.replace(/^https/i, 'wss').replace(/^http/i, 'ws')
return `${wsBase}/app/cs/chat`
@@ -32,16 +45,21 @@ function resolveCsChatWsUrl(sessionId: string, token: string): string {
return `${base}?token=${encodeURIComponent(token)}&sessionId=${encodeURIComponent(sessionId)}`
}
function stopHeartbeat() {
if (heartbeatTimer) clearInterval(heartbeatTimer)
heartbeatTimer = null
function normalizeWsType(type: string): string {
const t = type.toLowerCase().trim()
if (!t) return ''
if (t === 'cserror' || t === 'cs:error' || t === 'error') return 'error'
if (t === 'csping' || t === 'cs:ping') return 'ping'
if (t === 'cspong' || t === 'cs:pong') return 'pong'
if (t === 'csmessage' || t === 'cs:message') return 'message'
if (t === 'cssession' || t === 'cs:session') return 'session'
if (t === 'message' || t === 'session') return t
return t.replace(/^cs:/, '')
}
function startHeartbeat() {
stopHeartbeat()
heartbeatTimer = setInterval(() => {
socketTask?.send({ data: 'ping' })
}, HEARTBEAT_INTERVAL_MS)
function sendCsChatPong(task: UniApp.SocketTask) {
if (!socketOpened) return
task.send({ data: JSON.stringify({ type: 'cs:pong' }) })
}
function clearReconnectTimer() {
@@ -57,8 +75,7 @@ function scheduleReconnect() {
}, RECONNECT_DELAY_MS)
}
function cleanupSocketTask() {
stopHeartbeat()
function resetSocketState() {
socketTask = null
socketOpened = false
connecting = false
@@ -68,13 +85,19 @@ export function parseCsChatPayload(raw: string): CsChatWsPayload | null {
if (!raw || raw === 'ping' || raw === 'pong') return null
try {
const parsed = JSON.parse(raw) as Record<string, unknown>
const type = String(parsed.type ?? '').toLowerCase()
const norm = normalizeWsType(String(parsed.type ?? ''))
if (type === 'message' && parsed.data && typeof parsed.data === 'object') {
return { type: 'message', message: parsed.data as CsMessageVo }
if (norm === 'message') {
const data = parsed.data ?? parsed.message
if (data && typeof data === 'object') {
return { type: 'message', message: data as CsMessageVo }
}
}
if (type === 'session' && parsed.data && typeof parsed.data === 'object') {
return { type: 'session', session: parsed.data as CsSessionVo }
if (norm === 'session') {
const data = parsed.data ?? parsed.session
if (data && typeof data === 'object') {
return { type: 'session', session: data as CsSessionVo }
}
}
if (parsed.message && typeof parsed.message === 'object') {
return { type: 'message', message: parsed.message as CsMessageVo }
@@ -88,13 +111,37 @@ export function parseCsChatPayload(raw: string): CsChatWsPayload | null {
if (parsed.status !== undefined || parsed.sessionStatus !== undefined) {
return { type: 'session', session: parsed as CsSessionVo }
}
return { type: type || 'unknown', raw: parsed }
return { type: norm || 'unknown', raw: parsed }
} catch {
return null
}
}
function handleSocketMessage(raw: string) {
function handleSocketMessage(task: UniApp.SocketTask, raw: string) {
if (!raw) return
if (raw === 'ping') {
sendCsChatPong(task)
return
}
if (raw === 'pong') return
try {
const parsed = JSON.parse(raw) as Record<string, unknown>
const norm = normalizeWsType(String(parsed.type ?? ''))
if (norm === 'ping') {
sendCsChatPong(task)
return
}
if (norm === 'pong' || norm === 'error') {
if (norm === 'error' && import.meta.env.DEV) {
console.warn('[CS Chat WS] server error:', parsed.msg ?? parsed.message ?? parsed)
}
return
}
} catch {
// fall through
}
const payload = parseCsChatPayload(raw)
if (!payload) return
listeners.forEach((listener) => listener(payload))
@@ -109,61 +156,104 @@ export function isCsChatSocketConnected(): boolean {
return socketOpened
}
function bindSocketTask(task: UniApp.SocketTask, seq: number) {
socketTask = task
task.onOpen(() => {
if (seq !== connectionSeq) return
socketOpened = true
connecting = false
if (import.meta.env.DEV) console.log('[CS Chat WS] connected')
})
task.onMessage((res) => {
if (seq !== connectionSeq) return
const raw = typeof res.data === 'string' ? res.data : ''
handleSocketMessage(task, raw)
})
task.onClose((res) => {
if (seq !== connectionSeq) return
if (import.meta.env.DEV) {
const code = (res as { code?: number })?.code
const reason = (res as { reason?: string })?.reason
console.log('[CS Chat WS] closed', code ?? '', reason ?? '')
}
resetSocketState()
scheduleReconnect()
})
task.onError(() => {
if (seq !== connectionSeq) return
if (import.meta.env.DEV) console.log('[CS Chat WS] error')
resetSocketState()
scheduleReconnect()
})
}
export function connectCsChatSocket(sessionId: string) {
const token = getStoredToken()
if (!token || !sessionId) return
if (connecting) return
if (socketOpened && socketTask && activeSessionId === sessionId) return
if (socketTask) {
manualClosed = true
socketTask.close({})
cleanupSocketTask()
}
activeSessionId = sessionId
manualClosed = false
connecting = true
activeSessionId = sessionId
const seq = ++connectionSeq
clearReconnectTimer()
const previousTask = socketTask
socketTask = null
socketOpened = false
if (previousTask) {
try {
previousTask.close({})
} catch {
// ignore
}
}
connecting = true
const url = resolveCsChatWsUrl(sessionId, token)
if (import.meta.env.DEV) {
console.log('[CS Chat WS] connect', url.replace(/token=[^&]+/, 'token=***'))
}
// H5:必须带 fail/success 之一,否则返回 Promise 无 onOpen(见 message-socket.ts)
const task = uni.connectSocket({
url: resolveCsChatWsUrl(sessionId, token),
complete: () => {
connecting = false
url,
fail: (err) => {
if (seq !== connectionSeq) return
if (import.meta.env.DEV) console.log('[CS Chat WS] connect fail', err)
resetSocketState()
scheduleReconnect()
},
})
socketTask = task
task.onOpen(() => {
socketOpened = true
startHeartbeat()
})
task.onMessage((res) => {
const raw = typeof res.data === 'string' ? res.data : ''
handleSocketMessage(raw)
})
task.onClose(() => {
cleanupSocketTask()
if (!task || typeof task.onOpen !== 'function') {
connecting = false
if (import.meta.env.DEV) console.warn('[CS Chat WS] invalid SocketTask')
scheduleReconnect()
})
return
}
task.onError(() => {
cleanupSocketTask()
scheduleReconnect()
})
bindSocketTask(task, seq)
}
export function disconnectCsChatSocket() {
manualClosed = true
connectionSeq += 1
activeSessionId = ''
clearReconnectTimer()
stopHeartbeat()
if (socketTask) {
socketTask.close({})
}
const task = socketTask
socketTask = null
socketOpened = false
connecting = false
if (task) {
try {
task.close({})
} catch {
// ignore
}
}
}

View File

@@ -116,7 +116,8 @@
</view>
</view>
<view v-else-if="item.type === 'queue'" class="support-page__card">
<view v-else-if="item.type === 'queue'" class="support-page__queue-wrap">
<view class="support-page__card support-page__card--queue">
<view class="support-page__queue-head">
<view class="support-page__queue-title-wrap">
<text class="support-page__queue-icon">🎧</text>
@@ -150,6 +151,7 @@
</text>
<text class="support-page__queue-cancel" @tap="onCancelQueue">取消排队</text>
</view>
</view>
</view>
<view v-else-if="item.type === 'diagnosis'" class="support-page__card">

View File

@@ -86,10 +86,10 @@ export function fetchCsSessionList(query: CsSessionListQuery = {}) {
/** GET /app/cs/session/{sessionId} — 查询会话详情 */
export function fetchCsSessionDetail(sessionId: string) {
return request<CsSessionVo>({
return request<CsAppActionVo | CsSessionVo | string | null>({
url: buildSessionPath(sessionId),
method: 'GET',
})
}).then((data) => normalizeSessionResponse(unwrapCsActionResponse(data).session))
}
/** GET /app/cs/session/{sessionId}/messages — 拉取会话消息 */
@@ -112,7 +112,7 @@ export function sendCsMessage(sessionId: string, data: CsSendMessageBody) {
/** POST /app/cs/session/{sessionId}/transfer — 转人工 */
export function transferCsSession(sessionId: string) {
return request<void>({
return request<CsAppActionVo | CsSessionVo | null>({
url: buildSessionPath(sessionId, '/transfer'),
method: 'POST',
})

View File

@@ -294,6 +294,19 @@ $support-danger: #f04438;
box-shadow: 0 2rpx 16rpx rgba(16, 24, 40, 0.04);
}
.support-page__queue-wrap {
width: 100%;
margin-bottom: 28rpx;
box-sizing: border-box;
}
.support-page__card.support-page__card--queue {
margin: 0 auto;
width: calc(100% - 48rpx);
max-width: 686rpx;
box-sizing: border-box;
}
.support-page__card-title {
font-size: 30rpx;
font-weight: 600;
@@ -433,6 +446,7 @@ $support-danger: #f04438;
border-top: 1rpx solid #f0f0f0;
border-bottom: 1rpx solid #f0f0f0;
margin-bottom: 20rpx;
text-align: center;
}
.support-page__queue-info-text {
@@ -442,12 +456,15 @@ $support-danger: #f04438;
color: $support-text;
line-height: 1.5;
margin-bottom: 8rpx;
text-align: center;
}
.support-page__queue-estimate {
display: block;
font-size: 24rpx;
color: $support-text-secondary;
line-height: 1.4;
text-align: center;
}
.support-page__queue-actions {

View File

@@ -89,6 +89,7 @@ export interface CsResolvedSession {
export interface CsSendMessageBody {
content: string
msgType?: 'text' | 'image' | string
messageType?: 'text' | 'image' | string
clientMsgId: string
}

View File

@@ -64,20 +64,42 @@ export function normalizeSessionId(session: CsSessionVo | string | null | undefi
}
export function getSessionStatus(session: CsSessionVo): string {
return String(session.status ?? session.sessionStatus ?? '')
const raw = session.status ?? session.sessionStatus
if (raw === undefined || raw === null || raw === '') return ''
return String(raw).trim()
}
function normalizeStatusToken(status: string): string {
const s = status.toLowerCase()
if (!s) return ''
if (s === '0' || s.includes('bot') || s.includes('robot')) return CS_SESSION_STATUS.bot
if (s === '1' || s.includes('queue') || s.includes('wait')) return CS_SESSION_STATUS.queue
if (s === '2' || s.includes('human') || s.includes('agent') || s.includes('serv')) {
return CS_SESSION_STATUS.human
}
if (s === '3' || s.includes('close') || s.includes('end')) return CS_SESSION_STATUS.closed
return s
}
export function hasAssignedAgent(session: CsSessionVo): boolean {
const id = session.agentId
if (id === undefined || id === null || id === '') return false
const text = String(id).trim()
return !!text && text !== '0'
}
export function isSessionEnded(session: CsSessionVo): boolean {
if (session.ended === true || session.ended === 'true' || session.ended === '1') return true
const status = getSessionStatus(session)
const status = normalizeStatusToken(getSessionStatus(session))
return status === CS_SESSION_STATUS.closed || status === 'ended' || status === 'closed'
}
export function resolvePhaseFromSession(session: CsSessionVo): SupportPhase {
if (isSessionEnded(session)) return 'bot'
const status = getSessionStatus(session)
if (status === CS_SESSION_STATUS.queue || status === '1') return 'queue'
if (status === CS_SESSION_STATUS.human || status === '2') return 'human'
if (hasAssignedAgent(session)) return 'human'
const status = normalizeStatusToken(getSessionStatus(session))
if (status === CS_SESSION_STATUS.queue) return 'queue'
if (status === CS_SESSION_STATUS.human) return 'human'
return 'bot'
}

View File

@@ -154,6 +154,9 @@ export function useSupport() {
message?: Parameters<typeof mapCsMessage>[0]
session?: CsSessionVo
}) {
if (payload.session) {
applySessionState(payload.session)
}
if (!isSupportPageActive()) return
if (payload.message) {
const mapped = mapCsMessage(payload.message)
@@ -162,16 +165,17 @@ export function useSupport() {
lastSeq.value = getMaxSeq(apiMessages.value)
}
}
if (payload.session) {
applySessionState(payload.session)
}
}
function bindChatSocket(session: string) {
unsubscribeChatPush?.()
function ensureChatPushListener() {
if (unsubscribeChatPush) return
unsubscribeChatPush = onCsChatPush((payload) => {
handleChatPush(payload)
})
}
function bindChatSocket(session: string) {
ensureChatPushListener()
connectCsChatSocket(session)
}
@@ -200,7 +204,8 @@ export function useSupport() {
humanHeader.value = buildHumanHeader(session)
phase.value = 'human'
clearQueueTimer()
updateQueuePolling()
stopSupportPollTimer()
void syncMessages(false, true)
return
}
@@ -217,12 +222,12 @@ export function useSupport() {
updateQueuePolling()
}
async function syncMessages(reset = false) {
async function syncMessages(reset = false, force = false) {
if (!isSupportPageActive() || !sessionId.value || syncingMessages) return
if (isCsChatSocketConnected() && !reset) return
if (isCsChatSocketConnected() && !reset && !force) return
const now = Date.now()
if (!reset && now - lastMessageSyncAt < MESSAGE_SYNC_MIN_GAP_MS) return
if (!reset && !force && now - lastMessageSyncAt < MESSAGE_SYNC_MIN_GAP_MS) return
syncingMessages = true
try {
@@ -253,10 +258,14 @@ export function useSupport() {
}
}
function teardownPage() {
function pausePage() {
markSupportPageActive(false)
stopSupportPollTimer()
stopSupportQueueTimer()
}
function teardownPage() {
pausePage()
unbindChatSocket()
clearQueueTimer()
}
@@ -326,6 +335,7 @@ export function useSupport() {
const action = unwrapCsActionResponse(await sendCsMessage(sessionId.value, {
content: text,
msgType: 'text',
messageType: 'text',
clientMsgId: createClientMsgId(),
}))
if (action.session) {
@@ -354,9 +364,13 @@ export function useSupport() {
sending.value = true
try {
await transferCsSession(sessionId.value)
const action = unwrapCsActionResponse(await transferCsSession(sessionId.value))
if (action.session) applySessionState(action.session)
if (action.messages?.length) applyActionMessages(action)
ensureChatPushListener()
connectCsChatSocket(sessionId.value)
await refreshSession()
await syncMessages()
await syncMessages(false, true)
} catch (err) {
uni.showToast({ title: getErrorMessage(err, '转人工失败'), icon: 'none' })
} finally {
@@ -464,7 +478,7 @@ export function useSupport() {
}
onShow(activatePage)
onHide(teardownPage)
onHide(pausePage)
onUnload(teardownPage)
onBeforeUnmount(teardownPage)