fix:客服和绑定手机号问题修复

This commit is contained in:
李伊帆
2026-10-16 16:37:07 +08:00
parent a76aa9044c
commit 4b93b50e50
25 changed files with 744 additions and 71 deletions

View File

@@ -208,8 +208,8 @@ export function connectCsChatSocket(sessionId: string) {
if (previousTask) {
try {
previousTask.close({})
} catch {
// ignore
} catch {
// ignore
}
}

View File

@@ -120,7 +120,11 @@
<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>
<image
class="support-page__queue-icon"
:src="staticAssets.iconSupportQueue"
mode="aspectFit"
/>
<text class="support-page__queue-title">转换人工客服</text>
</view>
<text class="support-page__queue-tag">分配中</text>
@@ -200,12 +204,35 @@
<view
v-else-if="item.type === 'image'"
class="support-page__msg support-page__msg--user"
class="support-page__msg"
:class="`support-page__msg--${item.role}`"
>
<view class="support-page__image-wrap">
<image class="support-page__image" :src="item.src" mode="aspectFill" />
<view
v-if="item.role === 'bot' || item.role === 'agent'"
class="support-page__msg-avatar"
:class="`support-page__msg-avatar--${item.role}`"
>
{{ item.role === 'bot' ? '智' : humanAvatarText }}
</view>
<view
class="support-page__msg-body"
:class="{ 'support-page__msg-body--user': item.role === 'user' }"
>
<view
class="support-page__image-wrap"
:class="`support-page__image-wrap--${item.role}`"
>
<image
class="support-page__image"
:src="item.src"
mode="aspectFill"
@tap="onPreviewImage(item.src)"
/>
</view>
</view>
<view v-if="item.role === 'user'" class="support-page__msg-avatar support-page__msg-avatar--user">
我
</view>
<view class="support-page__msg-avatar support-page__msg-avatar--user">我</view>
</view>
</template>
<view id="chat-bottom" />
@@ -265,10 +292,10 @@
</view>
<template v-if="inputMode === 'text'">
<view class="support-page__tag">
<view class="support-page__tag" @tap="onPickImage">
<image
class="support-page__tag-icon"
:src="staticAssets.iconSupportTag"
:src="staticAssets.iconSupportPhoto"
mode="aspectFit"
/>
</view>
@@ -308,6 +335,7 @@ const {
onFooterShortcut,
onDiagnosisSuggestion,
onSend,
onPickImage,
} = useSupport()
const {
@@ -348,6 +376,11 @@ function diagnosisStatusText(status: DiagnosisItem['status']): string {
if (status === 'running') return '进行中'
return '等待中'
}
function onPreviewImage(src: string) {
if (!src) return
uni.previewImage({ urls: [src], current: src })
}
</script>
<style lang="scss" scoped>

View File

@@ -1,9 +1,11 @@
/** 客服页运行时状态(模块级,确保离开页面后定时器可被彻底清理) */
let pageActive = false
let pollTimer: ReturnType<typeof setInterval> | null = null
let messagePollTimer: ReturnType<typeof setInterval> | null = null
let queueTimer: ReturnType<typeof setInterval> | null = null
const QUEUE_POLL_INTERVAL_MS = 5000
const MESSAGE_POLL_INTERVAL_MS = 5000
export function isSupportPageActive(): boolean {
return pageActive
@@ -18,6 +20,11 @@ export function stopSupportPollTimer() {
pollTimer = null
}
export function stopSupportMessagePollTimer() {
if (messagePollTimer) clearInterval(messagePollTimer)
messagePollTimer = null
}
export function stopSupportQueueTimer() {
if (queueTimer) clearInterval(queueTimer)
queueTimer = null
@@ -26,9 +33,19 @@ export function stopSupportQueueTimer() {
export function teardownSupportRuntime() {
markSupportPageActive(false)
stopSupportPollTimer()
stopSupportMessagePollTimer()
stopSupportQueueTimer()
}
/** 定时增量拉消息(WebSocket 漏推时的兜底) */
export function startSupportMessagePolling(onTick: () => void) {
stopSupportMessagePollTimer()
messagePollTimer = setInterval(() => {
if (!pageActive) return
onTick()
}, MESSAGE_POLL_INTERVAL_MS)
}
export function startSupportQueuePolling(onTick: () => void) {
stopSupportPollTimer()
pollTimer = setInterval(() => {

View File

@@ -1,5 +1,7 @@
import { request } from '@/api/request'
import { ApiError } from '@/utils/api-error'
import { API_CLIENT_ID, request } from '@/api/request'
import type { ApiResponse } from '@/types/api'
import { getStoredToken } from '@/utils/auth-token'
import { ApiError, isApiSuccess, unwrapApiData } from '@/utils/api-error'
import {
isSessionEnded,
normalizeSessionId,
@@ -9,6 +11,8 @@ import {
import type {
CsAppActionVo,
CsClickButtonBody,
CsChatImageUploadVo,
CzCsUploadVo,
CsCreateSessionBody,
CsMessageVo,
CsResolvedSession,
@@ -22,6 +26,31 @@ function buildSessionPath(sessionId: string, suffix = '') {
return `/app/cs/session/${encodeURIComponent(sessionId)}${suffix}`
}
function resolveUploadBaseUrl(): string {
const envUrl = import.meta.env.VITE_API_BASE_URL ?? ''
// #ifdef H5
if (import.meta.env.DEV) return ''
// #endif
return envUrl
}
function normalizeCsUploadVo(data: unknown): CzCsUploadVo {
const raw = data && typeof data === 'object' ? (data as Record<string, unknown>) : {}
const ossId = raw.ossId
const url = raw.url != null ? String(raw.url).trim() : ''
if (ossId === undefined || ossId === null || ossId === '') {
throw new ApiError('上传失败,未返回 ossId')
}
if (!url) {
throw new ApiError('上传失败,未返回访问地址')
}
return {
ossId: typeof ossId === 'number' ? String(ossId) : String(ossId),
url,
fileName: raw.fileName != null ? String(raw.fileName) : undefined,
}
}
function unwrapRows<T>(data: T[] | CsTableData<T> | undefined): T[] {
if (!data) return []
if (Array.isArray(data)) return data
@@ -101,6 +130,47 @@ export function fetchCsMessages(sessionId: string, afterSeq = 0) {
}).then(unwrapRows)
}
/** POST /app/cs/upload — 上传聊天图片 */
export function uploadCsChatImage(filePath: string): Promise<CsChatImageUploadVo> {
return new Promise((resolve, reject) => {
const token = getStoredToken()
uni.uploadFile({
url: `${resolveUploadBaseUrl()}/app/cs/upload`,
filePath,
name: 'file',
header: {
clientId: API_CLIENT_ID,
...(token ? { Authorization: `Bearer ${token}` } : {}),
},
success: (res) => {
if (res.statusCode < 200 || res.statusCode >= 300) {
reject(new ApiError(`上传失败(${res.statusCode})`, res.statusCode))
return
}
let body: ApiResponse<CzCsUploadVo>
try {
body = JSON.parse(res.data) as ApiResponse<CzCsUploadVo>
} catch {
reject(new ApiError('上传响应解析失败'))
return
}
if (!isApiSuccess(body)) {
reject(new ApiError(body.msg || body.message || '上传失败', body.code))
return
}
try {
resolve(normalizeCsUploadVo(unwrapApiData(body)))
} catch (err) {
reject(err instanceof ApiError ? err : new ApiError('上传响应无效'))
}
},
fail: (err) => {
reject(new ApiError(err.errMsg || '上传失败'))
},
})
})
}
/** POST /app/cs/session/{sessionId}/message — 发送消息 */
export function sendCsMessage(sessionId: string, data: CsSendMessageBody) {
return request<CsAppActionVo>({

View File

@@ -360,8 +360,9 @@ $support-danger: #f04438;
}
.support-page__queue-icon {
font-size: 30rpx;
line-height: 1;
width: 36rpx;
height: 36rpx;
flex-shrink: 0;
}
.support-page__queue-title {
@@ -594,7 +595,16 @@ $support-danger: #f04438;
.support-page__image-wrap {
display: flex;
flex-direction: column;
align-items: flex-end;
&--user {
align-items: flex-end;
}
&--bot,
&--agent,
&--system {
align-items: flex-start;
}
}
.support-page__image {

View File

@@ -46,8 +46,11 @@ export interface CsMessageVo {
seq?: number
sessionId?: number | string
senderType?: string | number
/** 接口字段为 msgType;部分响应仍带 messageType */
msgType?: string
messageType?: string
content?: string
ossId?: number | string
createTime?: string
extra?: Record<string, unknown>
}
@@ -85,12 +88,22 @@ export interface CsResolvedSession {
messages?: CsMessageVo[]
}
/** POST /app/cs/upload 返回 data(CzCsUploadVo) */
export interface CzCsUploadVo {
ossId?: number | string
url?: string
fileName?: string
}
export type CsChatImageUploadVo = CzCsUploadVo
/** POST /app/cs/session/{sessionId}/message */
export interface CsSendMessageBody {
content: string
msgType?: 'text' | 'image' | string
messageType?: 'text' | 'image' | string
clientMsgId: string
ossId?: number | string
}
/** POST /app/cs/session/{sessionId}/button */
@@ -164,7 +177,7 @@ export type SupportMessage =
id: string
seq?: number
type: 'image'
role: 'user'
role: ChatRole
src: string
createTime?: string
}

View File

@@ -181,6 +181,33 @@ function resolveSenderRole(senderType?: string | number): ChatRole | null {
return 'bot'
}
function resolveMessageType(message: CsMessageVo): string {
return String(message.msgType ?? message.messageType ?? '').toLowerCase()
}
function resolveImageSrc(message: CsMessageVo): string {
const extra = message.extra
if (extra && typeof extra === 'object') {
const fromExtra = extra.url ?? extra.src ?? extra.link
if (fromExtra != null && String(fromExtra).trim()) {
return String(fromExtra).trim()
}
}
const content = message.content?.trim() ?? ''
if (!content) return ''
if (/^https?:\/\//i.test(content)) return content
if (content.startsWith('{') && content.endsWith('}')) {
try {
const payload = JSON.parse(content) as Record<string, unknown>
const url = payload.url ?? payload.src ?? payload.link ?? payload.fileUrl
if (url != null && String(url).trim()) return String(url).trim()
} catch {
// ignore
}
}
return content
}
function createMessageId(message: CsMessageVo): string {
if (message.messageId !== undefined && message.messageId !== null && message.messageId !== '') {
return String(message.messageId)
@@ -192,7 +219,7 @@ function createMessageId(message: CsMessageVo): string {
}
function mapStructuredMessage(message: CsMessageVo, payload: Record<string, unknown>): SupportMessage | null {
const type = String(payload.type ?? message.messageType ?? '').toLowerCase()
const type = String(payload.type ?? message.msgType ?? message.messageType ?? '').toLowerCase()
const id = createMessageId(message)
const seq = message.seq
@@ -265,16 +292,18 @@ function mapStructuredMessage(message: CsMessageVo, payload: Record<string, unkn
export function mapCsMessage(message: CsMessageVo): SupportMessage | null {
const content = message.content?.trim() ?? ''
const messageType = String(message.messageType ?? '').toLowerCase()
const messageType = resolveMessageType(message)
if (messageType === 'image') {
if (!content) return null
const src = resolveImageSrc(message)
if (!src) return null
const role = resolveSenderRole(message.senderType) || 'user'
return {
id: createMessageId(message),
seq: message.seq,
type: 'image',
role: 'user',
src: content,
role,
src,
createTime: message.createTime,
}
}

View File

@@ -11,6 +11,7 @@ import {
resolveCsSession,
sendCsMessage,
transferCsSession,
uploadCsChatImage,
} from './support.api'
import {
connectCsChatSocket,
@@ -21,8 +22,10 @@ import {
import {
isSupportPageActive,
markSupportPageActive,
startSupportMessagePolling,
startSupportQueuePolling,
startSupportQueueWaitTimer,
stopSupportMessagePollTimer,
stopSupportPollTimer,
stopSupportQueueTimer,
} from './support-runtime'
@@ -150,19 +153,29 @@ export function useSupport() {
}
}
function updateMessagePolling() {
if (!isSupportPageActive() || !sessionId.value) {
stopSupportMessagePollTimer()
return
}
startSupportMessagePolling(() => {
void syncMessages()
})
}
function handleChatPush(payload: {
message?: Parameters<typeof mapCsMessage>[0]
session?: CsSessionVo
}) {
if (payload.session) {
if (payload.session && isSupportPageActive()) {
applySessionState(payload.session)
}
if (!isSupportPageActive()) return
if (payload.message) {
const mapped = mapCsMessage(payload.message)
if (mapped) {
apiMessages.value = mergeSupportMessages(apiMessages.value, [mapped])
lastSeq.value = getMaxSeq(apiMessages.value)
lastMessageSyncAt = Date.now()
}
}
}
@@ -205,6 +218,7 @@ export function useSupport() {
phase.value = 'human'
clearQueueTimer()
stopSupportPollTimer()
updateMessagePolling()
void syncMessages(false, true)
return
}
@@ -213,6 +227,7 @@ export function useSupport() {
phase.value = 'queue'
if (queueWaitSeconds.value === 0) startQueueTimer()
updateQueuePolling()
updateMessagePolling()
return
}
@@ -220,11 +235,11 @@ export function useSupport() {
humanHeader.value = HUMAN_HEADER
clearQueueTimer()
updateQueuePolling()
updateMessagePolling()
}
async function syncMessages(reset = false, force = false) {
if (!isSupportPageActive() || !sessionId.value || syncingMessages) return
if (isCsChatSocketConnected() && !reset && !force) return
const now = Date.now()
if (!reset && !force && now - lastMessageSyncAt < MESSAGE_SYNC_MIN_GAP_MS) return
@@ -261,6 +276,7 @@ export function useSupport() {
function pausePage() {
markSupportPageActive(false)
stopSupportPollTimer()
stopSupportMessagePollTimer()
stopSupportQueueTimer()
}
@@ -304,6 +320,7 @@ export function useSupport() {
bindChatSocket(nextSessionId)
updateQueuePolling()
updateMessagePolling()
} catch (err) {
uni.showToast({ title: getErrorMessage(err, '客服会话创建失败'), icon: 'none' })
} finally {
@@ -318,6 +335,72 @@ export function useSupport() {
}
}
async function sendUserImageMessage(ossId: string | number, imageUrl: string) {
const url = imageUrl.trim()
if (!url || !ossId || sending.value) return
if (!sessionId.value) {
await ensureSession()
if (!sessionId.value) {
uni.showToast({ title: '会话未就绪,请稍后重试', icon: 'none' })
return
}
}
sending.value = true
try {
const action = unwrapCsActionResponse(await sendCsMessage(sessionId.value, {
content: url,
msgType: 'image',
ossId: String(ossId),
clientMsgId: createClientMsgId(),
}))
if (action.session) {
applySessionState(action.session)
}
if (action.messages?.length) {
applyActionMessages(action)
} else if (!isCsChatSocketConnected()) {
await syncMessages()
}
await refreshSession()
} catch (err) {
uni.showToast({ title: getErrorMessage(err, '发送失败'), icon: 'none' })
} finally {
sending.value = false
}
}
function onPickImage() {
if (sending.value) return
uni.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: (res) => {
const filePath = res.tempFilePaths?.[0]
if (!filePath) return
void (async () => {
uni.showLoading({ title: '上传中…', mask: true })
try {
const uploaded = await uploadCsChatImage(filePath)
const ossId = uploaded.ossId
const imageUrl = uploaded.url?.trim() || ''
if (!ossId || !imageUrl) {
uni.showToast({ title: '上传失败,未获取图片信息', icon: 'none' })
return
}
await sendUserImageMessage(ossId, imageUrl)
} catch (err) {
uni.showToast({ title: getErrorMessage(err, '图片上传失败'), icon: 'none' })
} finally {
uni.hideLoading()
}
})()
},
})
}
async function sendUserMessage(content: string) {
const text = content.trim()
if (!text || sending.value) return
@@ -472,9 +555,8 @@ export function useSupport() {
}
bindChatSocket(sessionId.value)
updateQueuePolling()
if (!isCsChatSocketConnected()) {
void syncMessages()
}
updateMessagePolling()
void syncMessages(false, true)
}
onShow(activatePage)
@@ -500,5 +582,7 @@ export function useSupport() {
onFooterShortcut,
onDiagnosisSuggestion,
onSend,
onPickImage,
sending,
}
}