feat:修改客服报错问题
This commit is contained in:
@@ -1,5 +1,7 @@
|
|||||||
VITE_API_BASE_URL=http://192.168.0.222:8082
|
VITE_API_BASE_URL=http://192.168.0.222:8082
|
||||||
VITE_API_PROXY_TARGET=http://192.168.0.222:8082
|
VITE_API_PROXY_TARGET=http://192.168.0.222:8082
|
||||||
VITE_MESSAGE_WS_URL=ws://192.168.0.222:8082/app/ws/message
|
VITE_MESSAGE_WS_URL=ws://192.168.0.222:8082/app/ws/message
|
||||||
VITE_CS_CHAT_WS_URL=ws://192.168.0.212:8082/app/cs/chat
|
# H5 开发:客服 WS 走本地 Vite 代理 → VITE_API_PROXY_TARGET(勿配 212 直连)
|
||||||
|
# 若必须直连 212,取消下行并设 VITE_CS_CHAT_WS_DIRECT=true
|
||||||
|
# VITE_CS_CHAT_WS_URL=ws://192.168.0.212:8082/app/cs/chat
|
||||||
VITE_API_CLIENT_ID=428a8310cd442757ae699df5d894f051
|
VITE_API_CLIENT_ID=428a8310cd442757ae699df5d894f051
|
||||||
|
|||||||
@@ -4,11 +4,16 @@ VITE_API_BASE_URL=http://192.168.0.222:8082
|
|||||||
# H5 开发:BASE_URL 留空时可走 vite 代理 /app
|
# H5 开发:BASE_URL 留空时可走 vite 代理 /app
|
||||||
VITE_API_PROXY_TARGET=http://192.168.0.222:8082
|
VITE_API_PROXY_TARGET=http://192.168.0.222:8082
|
||||||
|
|
||||||
|
# H5 开发服务端口(局域网访问:http://<本机IP>:端口,需 vite server.host)
|
||||||
|
# VITE_DEV_SERVER_PORT=5173
|
||||||
|
|
||||||
# 消息推送 WebSocket(不含 token,连接时自动拼接 ?token=)
|
# 消息推送 WebSocket(不含 token,连接时自动拼接 ?token=)
|
||||||
VITE_MESSAGE_WS_URL=ws://192.168.0.222:8082/app/ws/message
|
VITE_MESSAGE_WS_URL=ws://192.168.0.222:8082/app/ws/message
|
||||||
|
|
||||||
# 在线客服 WebSocket(不含 token/sessionId,连接时自动拼接)
|
# 在线客服 WebSocket(App/小程序直连;H5 开发默认走 Vite 代理,可不配此项)
|
||||||
VITE_CS_CHAT_WS_URL=ws://192.168.0.212:8082/app/cs/chat
|
# VITE_CS_CHAT_WS_URL=ws://192.168.0.222:8082/app/cs/chat
|
||||||
|
# H5 仍要直连内网 IP 时设为 true(如客服 WS 只在 212 上)
|
||||||
|
# VITE_CS_CHAT_WS_DIRECT=true
|
||||||
|
|
||||||
# RuoYi-Vue-Plus App 端 clientId(请求头 clientId)
|
# RuoYi-Vue-Plus App 端 clientId(请求头 clientId)
|
||||||
VITE_API_CLIENT_ID=428a8310cd442757ae699df5d894f051
|
VITE_API_CLIENT_ID=428a8310cd442757ae699df5d894f051
|
||||||
|
|||||||
@@ -9,7 +9,8 @@
|
|||||||
'<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' +
|
'<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' +
|
||||||
(coverSupport ? ', viewport-fit=cover' : '') + '" />')
|
(coverSupport ? ', viewport-fit=cover' : '') + '" />')
|
||||||
</script>
|
</script>
|
||||||
<title></title>
|
<title>虫子智家</title>
|
||||||
|
<link rel="icon" type="image/png" href="/src/static/logo-center@2x.png" />
|
||||||
<!--preload-links-->
|
<!--preload-links-->
|
||||||
<!--app-context-->
|
<!--app-context-->
|
||||||
</head>
|
</head>
|
||||||
|
|||||||
18
src/App.vue
18
src/App.vue
@@ -7,8 +7,26 @@ import {
|
|||||||
isMessageSocketConnecting,
|
isMessageSocketConnecting,
|
||||||
} from '@/utils/message-socket'
|
} from '@/utils/message-socket'
|
||||||
import { getStoredToken } from '@/utils/auth-token'
|
import { getStoredToken } from '@/utils/auth-token'
|
||||||
|
import { staticAssets } from '@/utils/static-assets'
|
||||||
|
|
||||||
|
function applyH5Favicon() {
|
||||||
|
// #ifdef H5
|
||||||
|
if (typeof document === 'undefined') return
|
||||||
|
const href = staticAssets.logo
|
||||||
|
if (!href) return
|
||||||
|
let link = document.querySelector<HTMLLinkElement>('link[rel="icon"]')
|
||||||
|
if (!link) {
|
||||||
|
link = document.createElement('link')
|
||||||
|
link.rel = 'icon'
|
||||||
|
document.head.appendChild(link)
|
||||||
|
}
|
||||||
|
link.type = 'image/png'
|
||||||
|
link.href = href
|
||||||
|
// #endif
|
||||||
|
}
|
||||||
|
|
||||||
onLaunch(() => {
|
onLaunch(() => {
|
||||||
|
applyH5Favicon()
|
||||||
if (getStoredToken()) {
|
if (getStoredToken()) {
|
||||||
setupMessageInbox()
|
setupMessageInbox()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,11 +3,14 @@ import type { AuthTokenResult, SendSmsCodeBody, SmsCodeScene } from '@/types/api
|
|||||||
import { ApiError } from '@/utils/api-error'
|
import { ApiError } from '@/utils/api-error'
|
||||||
import { extractAuthToken, saveStoredToken } from '@/utils/auth-token'
|
import { extractAuthToken, saveStoredToken } from '@/utils/auth-token'
|
||||||
|
|
||||||
|
export type SendSmsCodeOptions = Pick<SendSmsCodeBody, 'changeToken'>
|
||||||
|
|
||||||
/** POST /app/auth/sendSmsCode */
|
/** POST /app/auth/sendSmsCode */
|
||||||
export function sendSmsCode(phone: string, scene: SmsCodeScene) {
|
export function sendSmsCode(phone: string, scene: SmsCodeScene, options?: SendSmsCodeOptions) {
|
||||||
const data: SendSmsCodeBody = {
|
const data: SendSmsCodeBody = {
|
||||||
phonenumber: phone.trim(),
|
phonenumber: phone.trim(),
|
||||||
scene,
|
scene,
|
||||||
|
...(options?.changeToken ? { changeToken: options.changeToken.trim() } : {}),
|
||||||
}
|
}
|
||||||
return request<void>({
|
return request<void>({
|
||||||
url: '/app/auth/sendSmsCode',
|
url: '/app/auth/sendSmsCode',
|
||||||
|
|||||||
@@ -1,10 +1,15 @@
|
|||||||
import { sendSmsCode } from '@/api/auth'
|
import { sendSmsCode } from '@/api/auth'
|
||||||
import type { SmsCodeScene } from '@/types/api'
|
import { SMS_CODE_SCENE, type SmsCodeScene } from '@/types/api'
|
||||||
import { getErrorMessage } from '@/utils/api-error'
|
import { getErrorMessage } from '@/utils/api-error'
|
||||||
import { isValidPhone } from '@/utils/validate'
|
import { isValidPhone } from '@/utils/validate'
|
||||||
import { useCountdown } from './use-countdown'
|
import { useCountdown } from './use-countdown'
|
||||||
|
|
||||||
export function useSmsCode(scene: SmsCodeScene) {
|
export interface UseSmsCodeOptions {
|
||||||
|
/** 换绑新手机号发码时携带第一步返回的 changeToken */
|
||||||
|
getChangeToken?: () => string | undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useSmsCode(scene: SmsCodeScene, options?: UseSmsCodeOptions) {
|
||||||
const { counting, seconds, start } = useCountdown(60)
|
const { counting, seconds, start } = useCountdown(60)
|
||||||
|
|
||||||
async function sendCode(phone: string) {
|
async function sendCode(phone: string) {
|
||||||
@@ -13,8 +18,14 @@ export function useSmsCode(scene: SmsCodeScene) {
|
|||||||
uni.showToast({ title: '请输入正确手机号', icon: 'none' })
|
uni.showToast({ title: '请输入正确手机号', icon: 'none' })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
const changeToken =
|
||||||
|
scene === SMS_CODE_SCENE.changePhoneNew ? options?.getChangeToken?.()?.trim() : undefined
|
||||||
|
if (scene === SMS_CODE_SCENE.changePhoneNew && !changeToken) {
|
||||||
|
uni.showToast({ title: '换绑令牌无效,请重新验证', icon: 'none' })
|
||||||
|
return
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
await sendSmsCode(phone, scene)
|
await sendSmsCode(phone, scene, changeToken ? { changeToken } : undefined)
|
||||||
uni.showToast({ title: '验证码已发送', icon: 'none' })
|
uni.showToast({ title: '验证码已发送', icon: 'none' })
|
||||||
start()
|
start()
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|||||||
@@ -12,7 +12,9 @@ export function useChangePhoneBind() {
|
|||||||
const changeToken = ref('')
|
const changeToken = ref('')
|
||||||
const loading = ref(false)
|
const loading = ref(false)
|
||||||
|
|
||||||
const { counting, seconds, sendCode } = useSmsCode(SMS_CODE_SCENE.changePhoneNew)
|
const { counting, seconds, sendCode } = useSmsCode(SMS_CODE_SCENE.changePhoneNew, {
|
||||||
|
getChangeToken: () => changeToken.value,
|
||||||
|
})
|
||||||
|
|
||||||
onLoad((query) => {
|
onLoad((query) => {
|
||||||
const raw = (query?.changeToken as string) || ''
|
const raw = (query?.changeToken as string) || ''
|
||||||
|
|||||||
@@ -6,17 +6,24 @@ import type {
|
|||||||
VerifyOldPhoneBody,
|
VerifyOldPhoneBody,
|
||||||
} from './change-phone.types'
|
} from './change-phone.types'
|
||||||
|
|
||||||
|
type VerifyOldPhoneData = string | { changeToken: string }
|
||||||
|
|
||||||
|
function normalizeChangeToken(data: VerifyOldPhoneData): string {
|
||||||
|
if (typeof data === 'string') return data
|
||||||
|
return data.changeToken
|
||||||
|
}
|
||||||
|
|
||||||
/** POST /app/auth/changePhone/verifyOld — 校验原手机号验证码,返回换绑令牌 */
|
/** POST /app/auth/changePhone/verifyOld — 校验原手机号验证码,返回换绑令牌 */
|
||||||
export function verifyOldPhone(data: ChangePhoneVerifyForm) {
|
export function verifyOldPhone(data: ChangePhoneVerifyForm) {
|
||||||
const body: VerifyOldPhoneBody = {
|
const body: VerifyOldPhoneBody = {
|
||||||
oldPhonenumber: data.phone.trim(),
|
oldPhonenumber: data.phone.trim(),
|
||||||
oldSmsCode: data.code.trim(),
|
oldSmsCode: data.code.trim(),
|
||||||
}
|
}
|
||||||
return request<string>({
|
return request<VerifyOldPhoneData>({
|
||||||
url: '/app/auth/changePhone/verifyOld',
|
url: '/app/auth/changePhone/verifyOld',
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
data: body,
|
data: body,
|
||||||
})
|
}).then(normalizeChangeToken)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** POST /app/auth/changePhone/verifyNew — 校验新手机号验证码并完成换绑 */
|
/** POST /app/auth/changePhone/verifyNew — 校验新手机号验证码并完成换绑 */
|
||||||
|
|||||||
@@ -1,27 +1,40 @@
|
|||||||
import { getStoredToken } from '@/utils/auth-token'
|
import { getStoredToken } from '@/utils/auth-token'
|
||||||
import type { CsChatWsPayload, CsMessageVo, CsSessionVo } from './support.types'
|
import type { CsChatWsPayload, CsMessageVo, CsSessionVo } from './support.types'
|
||||||
|
|
||||||
const HEARTBEAT_INTERVAL_MS = 25000
|
const RECONNECT_DELAY_MS = 2000
|
||||||
const RECONNECT_DELAY_MS = 25000
|
|
||||||
|
|
||||||
let socketTask: UniApp.SocketTask | null = null
|
let socketTask: UniApp.SocketTask | null = null
|
||||||
let heartbeatTimer: ReturnType<typeof setInterval> | null = null
|
|
||||||
let reconnectTimer: ReturnType<typeof setTimeout> | null = null
|
let reconnectTimer: ReturnType<typeof setTimeout> | null = null
|
||||||
let connecting = false
|
let connecting = false
|
||||||
let manualClosed = false
|
let manualClosed = false
|
||||||
let activeSessionId = ''
|
let activeSessionId = ''
|
||||||
let socketOpened = false
|
let socketOpened = false
|
||||||
|
/** 每次 connect / disconnect 递增,忽略已废弃连接的 onClose */
|
||||||
|
let connectionSeq = 0
|
||||||
|
|
||||||
const listeners = new Set<(payload: CsChatWsPayload) => void>()
|
const listeners = new Set<(payload: CsChatWsPayload) => void>()
|
||||||
|
|
||||||
|
function isH5Dev(): boolean {
|
||||||
|
return import.meta.env.DEV && typeof window !== 'undefined' && !!window.location?.host
|
||||||
|
}
|
||||||
|
|
||||||
function resolveCsChatWsBase(): string {
|
function resolveCsChatWsBase(): string {
|
||||||
const configured = import.meta.env.VITE_CS_CHAT_WS_URL?.trim()
|
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) {
|
if (configured) {
|
||||||
return configured.replace(/[?#].*$/, '').replace(/\/$/, '')
|
return configured.replace(/[?#].*$/, '').replace(/\/$/, '')
|
||||||
}
|
}
|
||||||
|
|
||||||
const envBase = import.meta.env.VITE_API_BASE_URL?.trim() || ''
|
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 httpBase = envBase || fallback
|
||||||
const wsBase = httpBase.replace(/^https/i, 'wss').replace(/^http/i, 'ws')
|
const wsBase = httpBase.replace(/^https/i, 'wss').replace(/^http/i, 'ws')
|
||||||
return `${wsBase}/app/cs/chat`
|
return `${wsBase}/app/cs/chat`
|
||||||
@@ -32,16 +45,21 @@ function resolveCsChatWsUrl(sessionId: string, token: string): string {
|
|||||||
return `${base}?token=${encodeURIComponent(token)}&sessionId=${encodeURIComponent(sessionId)}`
|
return `${base}?token=${encodeURIComponent(token)}&sessionId=${encodeURIComponent(sessionId)}`
|
||||||
}
|
}
|
||||||
|
|
||||||
function stopHeartbeat() {
|
function normalizeWsType(type: string): string {
|
||||||
if (heartbeatTimer) clearInterval(heartbeatTimer)
|
const t = type.toLowerCase().trim()
|
||||||
heartbeatTimer = null
|
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() {
|
function sendCsChatPong(task: UniApp.SocketTask) {
|
||||||
stopHeartbeat()
|
if (!socketOpened) return
|
||||||
heartbeatTimer = setInterval(() => {
|
task.send({ data: JSON.stringify({ type: 'cs:pong' }) })
|
||||||
socketTask?.send({ data: 'ping' })
|
|
||||||
}, HEARTBEAT_INTERVAL_MS)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function clearReconnectTimer() {
|
function clearReconnectTimer() {
|
||||||
@@ -57,8 +75,7 @@ function scheduleReconnect() {
|
|||||||
}, RECONNECT_DELAY_MS)
|
}, RECONNECT_DELAY_MS)
|
||||||
}
|
}
|
||||||
|
|
||||||
function cleanupSocketTask() {
|
function resetSocketState() {
|
||||||
stopHeartbeat()
|
|
||||||
socketTask = null
|
socketTask = null
|
||||||
socketOpened = false
|
socketOpened = false
|
||||||
connecting = false
|
connecting = false
|
||||||
@@ -68,13 +85,19 @@ export function parseCsChatPayload(raw: string): CsChatWsPayload | null {
|
|||||||
if (!raw || raw === 'ping' || raw === 'pong') return null
|
if (!raw || raw === 'ping' || raw === 'pong') return null
|
||||||
try {
|
try {
|
||||||
const parsed = JSON.parse(raw) as Record<string, unknown>
|
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') {
|
if (norm === 'message') {
|
||||||
return { type: 'message', message: parsed.data as CsMessageVo }
|
const data = parsed.data ?? parsed.message
|
||||||
|
if (data && typeof data === 'object') {
|
||||||
|
return { type: 'message', message: data as CsMessageVo }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (norm === 'session') {
|
||||||
|
const data = parsed.data ?? parsed.session
|
||||||
|
if (data && typeof data === 'object') {
|
||||||
|
return { type: 'session', session: data as CsSessionVo }
|
||||||
}
|
}
|
||||||
if (type === 'session' && parsed.data && typeof parsed.data === 'object') {
|
|
||||||
return { type: 'session', session: parsed.data as CsSessionVo }
|
|
||||||
}
|
}
|
||||||
if (parsed.message && typeof parsed.message === 'object') {
|
if (parsed.message && typeof parsed.message === 'object') {
|
||||||
return { type: 'message', message: parsed.message as CsMessageVo }
|
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) {
|
if (parsed.status !== undefined || parsed.sessionStatus !== undefined) {
|
||||||
return { type: 'session', session: parsed as CsSessionVo }
|
return { type: 'session', session: parsed as CsSessionVo }
|
||||||
}
|
}
|
||||||
return { type: type || 'unknown', raw: parsed }
|
return { type: norm || 'unknown', raw: parsed }
|
||||||
} catch {
|
} catch {
|
||||||
return null
|
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)
|
const payload = parseCsChatPayload(raw)
|
||||||
if (!payload) return
|
if (!payload) return
|
||||||
listeners.forEach((listener) => listener(payload))
|
listeners.forEach((listener) => listener(payload))
|
||||||
@@ -109,61 +156,104 @@ export function isCsChatSocketConnected(): boolean {
|
|||||||
return socketOpened
|
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) {
|
export function connectCsChatSocket(sessionId: string) {
|
||||||
const token = getStoredToken()
|
const token = getStoredToken()
|
||||||
if (!token || !sessionId) return
|
if (!token || !sessionId) return
|
||||||
if (connecting) return
|
if (connecting) return
|
||||||
if (socketOpened && socketTask && activeSessionId === sessionId) return
|
if (socketOpened && socketTask && activeSessionId === sessionId) return
|
||||||
|
|
||||||
if (socketTask) {
|
|
||||||
manualClosed = true
|
|
||||||
socketTask.close({})
|
|
||||||
cleanupSocketTask()
|
|
||||||
}
|
|
||||||
|
|
||||||
activeSessionId = sessionId
|
|
||||||
manualClosed = false
|
manualClosed = false
|
||||||
connecting = true
|
activeSessionId = sessionId
|
||||||
|
const seq = ++connectionSeq
|
||||||
clearReconnectTimer()
|
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({
|
const task = uni.connectSocket({
|
||||||
url: resolveCsChatWsUrl(sessionId, token),
|
url,
|
||||||
complete: () => {
|
fail: (err) => {
|
||||||
connecting = false
|
if (seq !== connectionSeq) return
|
||||||
|
if (import.meta.env.DEV) console.log('[CS Chat WS] connect fail', err)
|
||||||
|
resetSocketState()
|
||||||
|
scheduleReconnect()
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
socketTask = task
|
if (!task || typeof task.onOpen !== 'function') {
|
||||||
|
connecting = false
|
||||||
task.onOpen(() => {
|
if (import.meta.env.DEV) console.warn('[CS Chat WS] invalid SocketTask')
|
||||||
socketOpened = true
|
|
||||||
startHeartbeat()
|
|
||||||
})
|
|
||||||
|
|
||||||
task.onMessage((res) => {
|
|
||||||
const raw = typeof res.data === 'string' ? res.data : ''
|
|
||||||
handleSocketMessage(raw)
|
|
||||||
})
|
|
||||||
|
|
||||||
task.onClose(() => {
|
|
||||||
cleanupSocketTask()
|
|
||||||
scheduleReconnect()
|
scheduleReconnect()
|
||||||
})
|
return
|
||||||
|
}
|
||||||
|
|
||||||
task.onError(() => {
|
bindSocketTask(task, seq)
|
||||||
cleanupSocketTask()
|
|
||||||
scheduleReconnect()
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function disconnectCsChatSocket() {
|
export function disconnectCsChatSocket() {
|
||||||
manualClosed = true
|
manualClosed = true
|
||||||
|
connectionSeq += 1
|
||||||
activeSessionId = ''
|
activeSessionId = ''
|
||||||
clearReconnectTimer()
|
clearReconnectTimer()
|
||||||
stopHeartbeat()
|
const task = socketTask
|
||||||
if (socketTask) {
|
|
||||||
socketTask.close({})
|
|
||||||
}
|
|
||||||
socketTask = null
|
socketTask = null
|
||||||
|
socketOpened = false
|
||||||
connecting = false
|
connecting = false
|
||||||
|
if (task) {
|
||||||
|
try {
|
||||||
|
task.close({})
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -116,7 +116,8 @@
|
|||||||
</view>
|
</view>
|
||||||
</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-head">
|
||||||
<view class="support-page__queue-title-wrap">
|
<view class="support-page__queue-title-wrap">
|
||||||
<text class="support-page__queue-icon">🎧</text>
|
<text class="support-page__queue-icon">🎧</text>
|
||||||
@@ -151,6 +152,7 @@
|
|||||||
<text class="support-page__queue-cancel" @tap="onCancelQueue">取消排队</text>
|
<text class="support-page__queue-cancel" @tap="onCancelQueue">取消排队</text>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
|
</view>
|
||||||
|
|
||||||
<view v-else-if="item.type === 'diagnosis'" class="support-page__card">
|
<view v-else-if="item.type === 'diagnosis'" class="support-page__card">
|
||||||
<view class="support-page__diagnosis-head">
|
<view class="support-page__diagnosis-head">
|
||||||
|
|||||||
@@ -86,10 +86,10 @@ export function fetchCsSessionList(query: CsSessionListQuery = {}) {
|
|||||||
|
|
||||||
/** GET /app/cs/session/{sessionId} — 查询会话详情 */
|
/** GET /app/cs/session/{sessionId} — 查询会话详情 */
|
||||||
export function fetchCsSessionDetail(sessionId: string) {
|
export function fetchCsSessionDetail(sessionId: string) {
|
||||||
return request<CsSessionVo>({
|
return request<CsAppActionVo | CsSessionVo | string | null>({
|
||||||
url: buildSessionPath(sessionId),
|
url: buildSessionPath(sessionId),
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
})
|
}).then((data) => normalizeSessionResponse(unwrapCsActionResponse(data).session))
|
||||||
}
|
}
|
||||||
|
|
||||||
/** GET /app/cs/session/{sessionId}/messages — 拉取会话消息 */
|
/** GET /app/cs/session/{sessionId}/messages — 拉取会话消息 */
|
||||||
@@ -112,7 +112,7 @@ export function sendCsMessage(sessionId: string, data: CsSendMessageBody) {
|
|||||||
|
|
||||||
/** POST /app/cs/session/{sessionId}/transfer — 转人工 */
|
/** POST /app/cs/session/{sessionId}/transfer — 转人工 */
|
||||||
export function transferCsSession(sessionId: string) {
|
export function transferCsSession(sessionId: string) {
|
||||||
return request<void>({
|
return request<CsAppActionVo | CsSessionVo | null>({
|
||||||
url: buildSessionPath(sessionId, '/transfer'),
|
url: buildSessionPath(sessionId, '/transfer'),
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -294,6 +294,19 @@ $support-danger: #f04438;
|
|||||||
box-shadow: 0 2rpx 16rpx rgba(16, 24, 40, 0.04);
|
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 {
|
.support-page__card-title {
|
||||||
font-size: 30rpx;
|
font-size: 30rpx;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
@@ -433,6 +446,7 @@ $support-danger: #f04438;
|
|||||||
border-top: 1rpx solid #f0f0f0;
|
border-top: 1rpx solid #f0f0f0;
|
||||||
border-bottom: 1rpx solid #f0f0f0;
|
border-bottom: 1rpx solid #f0f0f0;
|
||||||
margin-bottom: 20rpx;
|
margin-bottom: 20rpx;
|
||||||
|
text-align: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
.support-page__queue-info-text {
|
.support-page__queue-info-text {
|
||||||
@@ -442,12 +456,15 @@ $support-danger: #f04438;
|
|||||||
color: $support-text;
|
color: $support-text;
|
||||||
line-height: 1.5;
|
line-height: 1.5;
|
||||||
margin-bottom: 8rpx;
|
margin-bottom: 8rpx;
|
||||||
|
text-align: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
.support-page__queue-estimate {
|
.support-page__queue-estimate {
|
||||||
|
display: block;
|
||||||
font-size: 24rpx;
|
font-size: 24rpx;
|
||||||
color: $support-text-secondary;
|
color: $support-text-secondary;
|
||||||
line-height: 1.4;
|
line-height: 1.4;
|
||||||
|
text-align: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
.support-page__queue-actions {
|
.support-page__queue-actions {
|
||||||
|
|||||||
@@ -89,6 +89,7 @@ export interface CsResolvedSession {
|
|||||||
export interface CsSendMessageBody {
|
export interface CsSendMessageBody {
|
||||||
content: string
|
content: string
|
||||||
msgType?: 'text' | 'image' | string
|
msgType?: 'text' | 'image' | string
|
||||||
|
messageType?: 'text' | 'image' | string
|
||||||
clientMsgId: string
|
clientMsgId: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -64,20 +64,42 @@ export function normalizeSessionId(session: CsSessionVo | string | null | undefi
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function getSessionStatus(session: CsSessionVo): string {
|
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 {
|
export function isSessionEnded(session: CsSessionVo): boolean {
|
||||||
if (session.ended === true || session.ended === 'true' || session.ended === '1') return true
|
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'
|
return status === CS_SESSION_STATUS.closed || status === 'ended' || status === 'closed'
|
||||||
}
|
}
|
||||||
|
|
||||||
export function resolvePhaseFromSession(session: CsSessionVo): SupportPhase {
|
export function resolvePhaseFromSession(session: CsSessionVo): SupportPhase {
|
||||||
if (isSessionEnded(session)) return 'bot'
|
if (isSessionEnded(session)) return 'bot'
|
||||||
const status = getSessionStatus(session)
|
if (hasAssignedAgent(session)) return 'human'
|
||||||
if (status === CS_SESSION_STATUS.queue || status === '1') return 'queue'
|
const status = normalizeStatusToken(getSessionStatus(session))
|
||||||
if (status === CS_SESSION_STATUS.human || status === '2') return 'human'
|
if (status === CS_SESSION_STATUS.queue) return 'queue'
|
||||||
|
if (status === CS_SESSION_STATUS.human) return 'human'
|
||||||
return 'bot'
|
return 'bot'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -154,6 +154,9 @@ export function useSupport() {
|
|||||||
message?: Parameters<typeof mapCsMessage>[0]
|
message?: Parameters<typeof mapCsMessage>[0]
|
||||||
session?: CsSessionVo
|
session?: CsSessionVo
|
||||||
}) {
|
}) {
|
||||||
|
if (payload.session) {
|
||||||
|
applySessionState(payload.session)
|
||||||
|
}
|
||||||
if (!isSupportPageActive()) return
|
if (!isSupportPageActive()) return
|
||||||
if (payload.message) {
|
if (payload.message) {
|
||||||
const mapped = mapCsMessage(payload.message)
|
const mapped = mapCsMessage(payload.message)
|
||||||
@@ -162,16 +165,17 @@ export function useSupport() {
|
|||||||
lastSeq.value = getMaxSeq(apiMessages.value)
|
lastSeq.value = getMaxSeq(apiMessages.value)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (payload.session) {
|
|
||||||
applySessionState(payload.session)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function bindChatSocket(session: string) {
|
function ensureChatPushListener() {
|
||||||
unsubscribeChatPush?.()
|
if (unsubscribeChatPush) return
|
||||||
unsubscribeChatPush = onCsChatPush((payload) => {
|
unsubscribeChatPush = onCsChatPush((payload) => {
|
||||||
handleChatPush(payload)
|
handleChatPush(payload)
|
||||||
})
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function bindChatSocket(session: string) {
|
||||||
|
ensureChatPushListener()
|
||||||
connectCsChatSocket(session)
|
connectCsChatSocket(session)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -200,7 +204,8 @@ export function useSupport() {
|
|||||||
humanHeader.value = buildHumanHeader(session)
|
humanHeader.value = buildHumanHeader(session)
|
||||||
phase.value = 'human'
|
phase.value = 'human'
|
||||||
clearQueueTimer()
|
clearQueueTimer()
|
||||||
updateQueuePolling()
|
stopSupportPollTimer()
|
||||||
|
void syncMessages(false, true)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -217,12 +222,12 @@ export function useSupport() {
|
|||||||
updateQueuePolling()
|
updateQueuePolling()
|
||||||
}
|
}
|
||||||
|
|
||||||
async function syncMessages(reset = false) {
|
async function syncMessages(reset = false, force = false) {
|
||||||
if (!isSupportPageActive() || !sessionId.value || syncingMessages) return
|
if (!isSupportPageActive() || !sessionId.value || syncingMessages) return
|
||||||
if (isCsChatSocketConnected() && !reset) return
|
if (isCsChatSocketConnected() && !reset && !force) return
|
||||||
|
|
||||||
const now = Date.now()
|
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
|
syncingMessages = true
|
||||||
try {
|
try {
|
||||||
@@ -253,10 +258,14 @@ export function useSupport() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function teardownPage() {
|
function pausePage() {
|
||||||
markSupportPageActive(false)
|
markSupportPageActive(false)
|
||||||
stopSupportPollTimer()
|
stopSupportPollTimer()
|
||||||
stopSupportQueueTimer()
|
stopSupportQueueTimer()
|
||||||
|
}
|
||||||
|
|
||||||
|
function teardownPage() {
|
||||||
|
pausePage()
|
||||||
unbindChatSocket()
|
unbindChatSocket()
|
||||||
clearQueueTimer()
|
clearQueueTimer()
|
||||||
}
|
}
|
||||||
@@ -326,6 +335,7 @@ export function useSupport() {
|
|||||||
const action = unwrapCsActionResponse(await sendCsMessage(sessionId.value, {
|
const action = unwrapCsActionResponse(await sendCsMessage(sessionId.value, {
|
||||||
content: text,
|
content: text,
|
||||||
msgType: 'text',
|
msgType: 'text',
|
||||||
|
messageType: 'text',
|
||||||
clientMsgId: createClientMsgId(),
|
clientMsgId: createClientMsgId(),
|
||||||
}))
|
}))
|
||||||
if (action.session) {
|
if (action.session) {
|
||||||
@@ -354,9 +364,13 @@ export function useSupport() {
|
|||||||
|
|
||||||
sending.value = true
|
sending.value = true
|
||||||
try {
|
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 refreshSession()
|
||||||
await syncMessages()
|
await syncMessages(false, true)
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
uni.showToast({ title: getErrorMessage(err, '转人工失败'), icon: 'none' })
|
uni.showToast({ title: getErrorMessage(err, '转人工失败'), icon: 'none' })
|
||||||
} finally {
|
} finally {
|
||||||
@@ -464,7 +478,7 @@ export function useSupport() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
onShow(activatePage)
|
onShow(activatePage)
|
||||||
onHide(teardownPage)
|
onHide(pausePage)
|
||||||
onUnload(teardownPage)
|
onUnload(teardownPage)
|
||||||
onBeforeUnmount(teardownPage)
|
onBeforeUnmount(teardownPage)
|
||||||
|
|
||||||
|
|||||||
@@ -20,6 +20,8 @@ export interface ApiResponse<T = unknown> {
|
|||||||
export interface SendSmsCodeBody {
|
export interface SendSmsCodeBody {
|
||||||
phonenumber: string
|
phonenumber: string
|
||||||
scene: SmsCodeScene
|
scene: SmsCodeScene
|
||||||
|
/** 换绑第二步 scene=change_phone_new 时必填 */
|
||||||
|
changeToken?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface LoginSmsBody {
|
export interface LoginSmsBody {
|
||||||
|
|||||||
1
tmp-api-docs.json
Normal file
1
tmp-api-docs.json
Normal file
File diff suppressed because one or more lines are too long
@@ -7,9 +7,13 @@ export default defineConfig(({ mode }) => {
|
|||||||
const proxyTarget =
|
const proxyTarget =
|
||||||
env.VITE_API_PROXY_TARGET || "http://192.168.0.222:8082";
|
env.VITE_API_PROXY_TARGET || "http://192.168.0.222:8082";
|
||||||
|
|
||||||
|
const devPort = Number(env.VITE_DEV_SERVER_PORT) || 5173;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
plugins: [uni()],
|
plugins: [uni()],
|
||||||
server: {
|
server: {
|
||||||
|
host: true,
|
||||||
|
port: devPort,
|
||||||
proxy: {
|
proxy: {
|
||||||
"/app": {
|
"/app": {
|
||||||
target: proxyTarget,
|
target: proxyTarget,
|
||||||
|
|||||||
Reference in New Issue
Block a user