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

@@ -18,6 +18,9 @@ VITE_MESSAGE_WS_URL=ws://192.168.0.222:8082/app/ws/message
# RuoYi-Vue-Plus App 端 clientId(请求头 clientId) # RuoYi-Vue-Plus App 端 clientId(请求头 clientId)
VITE_API_CLIENT_ID=428a8310cd442757ae699df5d894f051 VITE_API_CLIENT_ID=428a8310cd442757ae699df5d894f051
# H5 唤起 App 的 URL Scheme(与 App 打包 scheme 一致,默认 czzj)
# VITE_APP_SCHEME=czzj
# Z2 BLE UUID(嵌入式文档默认 FFF2 写 / FFF1 通知,已内置,一般无需配置) # Z2 BLE UUID(嵌入式文档默认 FFF2 写 / FFF1 通知,已内置,一般无需配置)
# VITE_BLE_SERVICE_UUID=0000ffe0-0000-1000-8000-00805f9b34fb # VITE_BLE_SERVICE_UUID=0000ffe0-0000-1000-8000-00805f9b34fb
# VITE_BLE_WRITE_CHAR_UUID=0000fff2-0000-1000-8000-00805f9b34fb # VITE_BLE_WRITE_CHAR_UUID=0000fff2-0000-1000-8000-00805f9b34fb

View File

@@ -1,22 +1,23 @@
import { request } from './request' import { request } from './request'
import type { AuthTokenResult, SendSmsCodeBody, SmsCodeScene } from '@/types/api' import type { AuthTokenResult, SendSmsCodeBody, SmsCodeScene } from '@/types/api'
import { ApiError } from '@/utils/api-error' import { ApiError } from '@/utils/api-error'
import { extractFlowToken } from '@/utils/api-flow-token'
import { extractAuthToken, saveStoredToken } from '@/utils/auth-token' import { extractAuthToken, saveStoredToken } from '@/utils/auth-token'
export type SendSmsCodeOptions = Pick<SendSmsCodeBody, 'changeToken'> export type SendSmsCodeOptions = Pick<SendSmsCodeBody, 'changeToken'>
/** POST /app/auth/sendSmsCode */ /** POST /app/auth/sendSmsCode — 换绑新号场景可能在响应 msg 中返回新的 changeToken */
export function sendSmsCode(phone: string, scene: SmsCodeScene, options?: SendSmsCodeOptions) { 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() } : {}), ...(options?.changeToken ? { changeToken: options.changeToken.trim() } : {}),
} }
return request<void>({ return request<unknown>({
url: '/app/auth/sendSmsCode', url: '/app/auth/sendSmsCode',
method: 'POST', method: 'POST',
data, data,
}) }).then((payload) => extractFlowToken(payload) || undefined)
} }
export function saveAuthToken(data: AuthTokenResult | unknown) { export function saveAuthToken(data: AuthTokenResult | unknown) {

View File

@@ -7,6 +7,8 @@ import { useCountdown } from './use-countdown'
export interface UseSmsCodeOptions { export interface UseSmsCodeOptions {
/** 换绑新手机号发码时携带第一步返回的 changeToken */ /** 换绑新手机号发码时携带第一步返回的 changeToken */
getChangeToken?: () => string | undefined getChangeToken?: () => string | undefined
/** 发码接口在 msg 中返回新 changeToken 时回调 */
onChangeToken?: (token: string) => void
} }
export function useSmsCode(scene: SmsCodeScene, options?: UseSmsCodeOptions) { export function useSmsCode(scene: SmsCodeScene, options?: UseSmsCodeOptions) {
@@ -25,7 +27,10 @@ export function useSmsCode(scene: SmsCodeScene, options?: UseSmsCodeOptions) {
return return
} }
try { try {
await sendSmsCode(phone, scene, changeToken ? { changeToken } : undefined) const nextToken = await sendSmsCode(phone, scene, changeToken ? { changeToken } : undefined)
if (nextToken && scene === SMS_CODE_SCENE.changePhoneNew) {
options?.onChangeToken?.(nextToken)
}
uni.showToast({ title: '验证码已发送', icon: 'none' }) uni.showToast({ title: '验证码已发送', icon: 'none' })
start() start()
} catch (err) { } catch (err) {

View File

@@ -14,6 +14,9 @@ export function useChangePhoneBind() {
const { counting, seconds, sendCode } = useSmsCode(SMS_CODE_SCENE.changePhoneNew, { const { counting, seconds, sendCode } = useSmsCode(SMS_CODE_SCENE.changePhoneNew, {
getChangeToken: () => changeToken.value, getChangeToken: () => changeToken.value,
onChangeToken: (token) => {
changeToken.value = token
},
}) })
onLoad((query) => { onLoad((query) => {

View File

@@ -1,4 +1,6 @@
import { request } from '@/api/request' import { request } from '@/api/request'
import { ApiError } from '@/utils/api-error'
import { extractFlowToken } from '@/utils/api-flow-token'
import type { import type {
ChangePhoneBindForm, ChangePhoneBindForm,
ChangePhoneVerifyForm, ChangePhoneVerifyForm,
@@ -6,24 +8,23 @@ 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<VerifyOldPhoneData>({ return request<unknown>({
url: '/app/auth/changePhone/verifyOld', url: '/app/auth/changePhone/verifyOld',
method: 'POST', method: 'POST',
data: body, data: body,
}).then(normalizeChangeToken) }).then((payload) => {
const changeToken = extractFlowToken(payload)
if (!changeToken) {
throw new ApiError('验证失败,未获取换绑令牌')
}
return changeToken
})
} }
/** POST /app/auth/changePhone/verifyNew — 校验新手机号验证码并完成换绑 */ /** POST /app/auth/changePhone/verifyNew — 校验新手机号验证码并完成换绑 */

View File

@@ -6,7 +6,13 @@
<view class="storage-page__body"> <view class="storage-page__body">
<text class="storage-page__section-label">储存空间</text> <text class="storage-page__section-label">储存空间</text>
<view class="storage-page__ring-wrap"> <view v-if="requiresApp" class="storage-page__tip">
<text class="storage-page__tip-text">
储存空间需在手机「虫子智家」App 中查看与管理,浏览器无法读取本机占用。
</text>
</view>
<view v-if="!requiresApp" class="storage-page__ring-wrap">
<view class="storage-page__ring" :style="ringStyle"> <view class="storage-page__ring" :style="ringStyle">
<view class="storage-page__ring-inner"> <view class="storage-page__ring-inner">
<text class="storage-page__ring-value">{{ usedPercent }}%</text> <text class="storage-page__ring-value">{{ usedPercent }}%</text>
@@ -35,11 +41,25 @@
</view> </view>
<view class="storage-page__footer"> <view class="storage-page__footer">
<view class="storage-page__clear-btn" @tap="onClearAll"> <template v-if="requiresApp">
<text class="storage-page__clear-text"> <view class="storage-page__clear-btn" @tap="onOpenMobileApp">
一键清理全部缓存({{ totalCacheMb }}MB) <text class="storage-page__clear-text">打开手机 App 管理储存空间</text>
</text> </view>
</view> </template>
<template v-else>
<view
class="storage-page__clear-btn"
:class="{ 'storage-page__clear-btn--disabled': clearing }"
@tap="onClearAll"
>
<text class="storage-page__clear-text">
{{ clearing ? '清理中…' : `一键清理全部缓存(${totalCacheMb}MB)` }}
</text>
</view>
<view class="storage-page__settings-btn" @tap="onOpenSystemSettings">
<text class="storage-page__settings-text">前往手机系统设置管理</text>
</view>
</template>
</view> </view>
</view> </view>
</scroll-view> </scroll-view>
@@ -54,7 +74,11 @@ const {
usedPercent, usedPercent,
totalCacheMb, totalCacheMb,
ringStyle, ringStyle,
requiresApp,
clearing,
onClearAll, onClearAll,
onOpenSystemSettings,
onOpenMobileApp,
} = useStorage() } = useStorage()
function formatSize(sizeMb: number): string { function formatSize(sizeMb: number): string {

View File

@@ -14,6 +14,20 @@
padding: 8rpx 24rpx calc(32rpx + env(safe-area-inset-bottom)); padding: 8rpx 24rpx calc(32rpx + env(safe-area-inset-bottom));
} }
.storage-page__tip {
margin-bottom: 24rpx;
padding: 20rpx 24rpx;
border-radius: 16rpx;
background: #fff8e6;
border: 1rpx solid #ffe4a8;
}
.storage-page__tip-text {
font-size: 26rpx;
color: #8a6d3b;
line-height: 1.5;
}
.storage-page__section-label { .storage-page__section-label {
display: block; display: block;
padding: 8rpx 8rpx 24rpx; padding: 8rpx 8rpx 24rpx;
@@ -111,6 +125,9 @@
.storage-page__footer { .storage-page__footer {
padding: 0 8rpx; padding: 0 8rpx;
display: flex;
flex-direction: column;
gap: 20rpx;
} }
.storage-page__clear-btn { .storage-page__clear-btn {
@@ -123,8 +140,31 @@
justify-content: center; justify-content: center;
} }
.storage-page__clear-btn--disabled {
opacity: 0.45;
}
.storage-page__clear-text { .storage-page__clear-text {
font-size: 30rpx; font-size: 30rpx;
color: #1a1a1a; color: #1a1a1a;
line-height: 1.3; line-height: 1.3;
} }
.storage-page__settings-btn {
height: 88rpx;
border-radius: 20rpx;
background: #f5f7fa;
display: flex;
align-items: center;
justify-content: center;
}
.storage-page__settings-btn--disabled {
opacity: 0.45;
}
.storage-page__settings-text {
font-size: 28rpx;
color: #3d5a80;
line-height: 1.3;
}

View File

@@ -0,0 +1,214 @@
import type { StorageCacheItem } from './storage.types'
const TOKEN_STORAGE_KEY = 'token'
const STORAGE_APP_PATH = '/pages/mine/storage/index'
export interface StorageOverview {
usedPercent: number
items: StorageCacheItem[]
totalCacheMb: number
/** 是否需在手机 App 端操作(H5 等) */
requiresApp: boolean
}
function kbToMb(kb: number): number {
return Math.round((kb / 1024) * 10) / 10
}
function bytesToMb(bytes: number): number {
return Math.round((bytes / (1024 * 1024)) * 10) / 10
}
export function isH5Platform(): boolean {
try {
const { uniPlatform } = uni.getSystemInfoSync()
return uniPlatform === 'web' || uniPlatform === 'h5'
} catch {
return typeof window !== 'undefined'
}
}
export function isStorageManagedOnDevice(): boolean {
if (isH5Platform()) return false
try {
const { uniPlatform } = uni.getSystemInfoSync()
return uniPlatform === 'app' || uniPlatform === 'app-plus'
} catch {
return false
}
}
function resolveAppDeepLink(path = STORAGE_APP_PATH): string {
const scheme = (import.meta.env.VITE_APP_SCHEME as string | undefined)?.trim() || 'czzj'
const normalized = path.replace(/^\//, '')
return `${scheme}://${normalized}`
}
/** H5:尝试唤起已安装的「虫子智家」App 并打开储存空间页 */
export function openMobileAppForStorage(): boolean {
if (!isH5Platform()) return false
const url = resolveAppDeepLink()
// #ifdef H5
if (typeof window !== 'undefined') {
window.location.href = url
return true
}
// #endif
return false
}
function readLocalStorageKb(): { currentKb: number; limitKb: number } {
try {
const info = uni.getStorageInfoSync()
return {
currentKb: Number(info.currentSize) || 0,
limitKb: Number(info.limitSize) || 0,
}
} catch {
return { currentKb: 0, limitKb: 0 }
}
}
function measureAppFileCacheBytes(): Promise<number> {
return new Promise((resolve) => {
// #ifdef APP-PLUS
if (typeof plus !== 'undefined' && plus.cache?.calculate) {
plus.cache.calculate((size: number) => {
resolve(Number(size) || 0)
})
return
}
// #endif
resolve(0)
})
}
function buildItemPercents(items: StorageCacheItem[]): StorageCacheItem[] {
const total = items.reduce((sum, item) => sum + item.sizeMb, 0)
if (total <= 0) {
return items.map((item) => ({ ...item, percent: 0 }))
}
return items.map((item) => ({
...item,
percent: Math.min(100, Math.round((item.sizeMb / total) * 100)),
}))
}
/** 读取本机 App 储存占用 */
export async function fetchStorageOverview(): Promise<StorageOverview> {
const requiresApp = !isStorageManagedOnDevice()
if (requiresApp) {
return {
usedPercent: 0,
items: [],
totalCacheMb: 0,
requiresApp: true,
}
}
const { currentKb, limitKb } = readLocalStorageKb()
const fileCacheBytes = await measureAppFileCacheBytes()
const localMb = kbToMb(currentKb)
const fileCacheMb = bytesToMb(fileCacheBytes)
const items: StorageCacheItem[] = []
if (fileCacheMb > 0) {
items.push({ id: 'file-cache', label: '图片与文件缓存', sizeMb: fileCacheMb, percent: 0 })
}
items.push({ id: 'local-data', label: '应用本地数据', sizeMb: localMb, percent: 0 })
const totalCacheMb = Math.round((localMb + fileCacheMb) * 10) / 10
const usedPercent =
limitKb > 0
? Math.min(100, Math.round((currentKb / limitKb) * 100))
: totalCacheMb > 0
? 1
: 0
return {
usedPercent,
items: buildItemPercents(items),
totalCacheMb,
requiresApp: false,
}
}
function clearLocalCacheExceptAuth(): void {
try {
const { keys = [] } = uni.getStorageInfoSync()
for (const key of keys) {
if (key === TOKEN_STORAGE_KEY) continue
uni.removeStorageSync(key)
}
} catch {
// ignore
}
}
function clearAppFileCache(): Promise<void> {
return new Promise((resolve, reject) => {
// #ifdef APP-PLUS
if (typeof plus !== 'undefined' && plus.cache?.clear) {
plus.cache.clear(
() => resolve(),
(err: { message?: string }) => {
reject(new Error(err?.message || '清理失败'))
},
)
return
}
// #endif
resolve()
})
}
/** 清理可安全删除的缓存(保留登录令牌) */
export async function clearDeviceCache(): Promise<void> {
if (!isStorageManagedOnDevice()) {
throw new Error('请在手机 App 中清理储存空间')
}
await clearAppFileCache()
clearLocalCacheExceptAuth()
}
/** 打开系统「应用详情 / 储存」设置(仅 App) */
export function openSystemAppStorageSettings(): boolean {
if (!isStorageManagedOnDevice()) {
return false
}
// #ifdef APP-PLUS
try {
const platform = uni.getSystemInfoSync().platform
if (platform === 'ios') {
plus.runtime.openURL('app-settings:')
return true
}
if (platform === 'android') {
const main = plus.android.runtimeMainActivity()
const Intent = plus.android.importClass('android.content.Intent') as {
new (action: string): PlusAndroidInstanceObject
}
const Settings = plus.android.importClass('android.provider.Settings') as {
ACTION_APPLICATION_DETAILS_SETTINGS: string
}
const Uri = plus.android.importClass('android.net.Uri') as {
fromParts: (scheme: string, path: string, fragment: string | null) => PlusAndroidInstanceObject
}
const intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
const uri = Uri.fromParts('package', main.getPackageName(), null)
intent.setData(uri)
main.startActivity(intent)
return true
}
} catch {
return false
}
// #endif
return false
}
export function getStorageAppDeepLink(): string {
return resolveAppDeepLink()
}

View File

@@ -1,20 +1,22 @@
import { onShow } from '@dcloudio/uni-app'
import { computed, ref } from 'vue' import { computed, ref } from 'vue'
import { getErrorMessage } from '@/utils/api-error'
import type { StorageCacheItem } from './storage.types' import type { StorageCacheItem } from './storage.types'
import {
const DEFAULT_ITEMS: StorageCacheItem[] = [ clearDeviceCache,
{ id: 'image', label: '图片缓存', sizeMb: 12.8, percent: 72 }, fetchStorageOverview,
{ id: 'doc', label: '文档数据', sizeMb: 12.8, percent: 58 }, getStorageAppDeepLink,
{ id: 'health', label: '健康数据', sizeMb: 12.8, percent: 45 }, isStorageManagedOnDevice,
{ id: 'video', label: '视频缓存', sizeMb: 12.8, percent: 36 }, openMobileAppForStorage,
{ id: 'other', label: '其他数据', sizeMb: 12.8, percent: 28 }, openSystemAppStorageSettings,
] } from './storage.utils'
const USAGE_PERCENT = 25
export function useStorage() { export function useStorage() {
const items = ref<StorageCacheItem[]>(DEFAULT_ITEMS.map((item) => ({ ...item }))) const items = ref<StorageCacheItem[]>([])
const usedPercent = ref(0)
const usedPercent = ref(USAGE_PERCENT) const requiresApp = ref(!isStorageManagedOnDevice())
const loading = ref(false)
const clearing = ref(false)
const totalCacheMb = computed(() => { const totalCacheMb = computed(() => {
const sum = items.value.reduce((acc, item) => acc + item.sizeMb, 0) const sum = items.value.reduce((acc, item) => acc + item.sizeMb, 0)
@@ -25,28 +27,99 @@ export function useStorage() {
background: `conic-gradient(#6ea8ff 0% ${usedPercent.value}%, #e8ecf3 ${usedPercent.value}% 100%)`, background: `conic-gradient(#6ea8ff 0% ${usedPercent.value}%, #e8ecf3 ${usedPercent.value}% 100%)`,
})) }))
function onClearAll() { async function refresh() {
loading.value = true
try {
const overview = await fetchStorageOverview()
requiresApp.value = overview.requiresApp
items.value = overview.items
usedPercent.value = overview.usedPercent
} catch (err) {
uni.showToast({ title: getErrorMessage(err, '读取储存信息失败'), icon: 'none' })
} finally {
loading.value = false
}
}
function promptOpenMobileApp() {
uni.showModal({ uni.showModal({
title: '清理缓存', title: '储存空间',
content: `确定清理全部缓存(${totalCacheMb.value}MB)吗?`, content:
'查看与清理储存空间需在手机「虫子智家」App 中进行。若未自动跳转,请手动打开 App 后进入「我的 → 储存空间」。',
confirmText: '打开手机 App',
cancelText: '知道了',
success: (res) => { success: (res) => {
if (!res.confirm) return if (!res.confirm) return
items.value = items.value.map((item) => ({ const opened = openMobileAppForStorage()
...item, if (!opened) {
sizeMb: 0, uni.setClipboardData({
percent: 0, data: getStorageAppDeepLink(),
})) success: () => {
usedPercent.value = 0 uni.showToast({ title: '已复制打开链接', icon: 'none' })
uni.showToast({ title: '清理完成', icon: 'success' }) },
})
}
}, },
}) })
} }
function onClearAll() {
if (requiresApp.value) {
promptOpenMobileApp()
return
}
if (totalCacheMb.value <= 0) {
uni.showToast({ title: '暂无可清理缓存', icon: 'none' })
return
}
uni.showModal({
title: '清理缓存',
content: `确定清理全部缓存(约 ${totalCacheMb.value}MB)吗?登录状态将保留。`,
success: (res) => {
if (!res.confirm) return
void (async () => {
clearing.value = true
try {
await clearDeviceCache()
uni.showToast({ title: '清理完成', icon: 'success' })
await refresh()
} catch (err) {
uni.showToast({ title: getErrorMessage(err, '清理失败'), icon: 'none' })
} finally {
clearing.value = false
}
})()
},
})
}
function onOpenSystemSettings() {
if (requiresApp.value) {
promptOpenMobileApp()
return
}
const ok = openSystemAppStorageSettings()
if (!ok) {
uni.showToast({ title: '当前环境无法打开系统设置', icon: 'none' })
}
}
onShow(() => {
void refresh()
})
return { return {
items, items,
usedPercent, usedPercent,
totalCacheMb, totalCacheMb,
ringStyle, ringStyle,
requiresApp,
loading,
clearing,
onClearAll, onClearAll,
onOpenSystemSettings,
onOpenMobileApp: promptOpenMobileApp,
refresh,
} }
} }

View File

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

View File

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

View File

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

View File

@@ -1,5 +1,7 @@
import { request } from '@/api/request' import { API_CLIENT_ID, request } from '@/api/request'
import { ApiError } from '@/utils/api-error' import type { ApiResponse } from '@/types/api'
import { getStoredToken } from '@/utils/auth-token'
import { ApiError, isApiSuccess, unwrapApiData } from '@/utils/api-error'
import { import {
isSessionEnded, isSessionEnded,
normalizeSessionId, normalizeSessionId,
@@ -9,6 +11,8 @@ import {
import type { import type {
CsAppActionVo, CsAppActionVo,
CsClickButtonBody, CsClickButtonBody,
CsChatImageUploadVo,
CzCsUploadVo,
CsCreateSessionBody, CsCreateSessionBody,
CsMessageVo, CsMessageVo,
CsResolvedSession, CsResolvedSession,
@@ -22,6 +26,31 @@ function buildSessionPath(sessionId: string, suffix = '') {
return `/app/cs/session/${encodeURIComponent(sessionId)}${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[] { function unwrapRows<T>(data: T[] | CsTableData<T> | undefined): T[] {
if (!data) return [] if (!data) return []
if (Array.isArray(data)) return data if (Array.isArray(data)) return data
@@ -101,6 +130,47 @@ export function fetchCsMessages(sessionId: string, afterSeq = 0) {
}).then(unwrapRows) }).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 — 发送消息 */ /** POST /app/cs/session/{sessionId}/message — 发送消息 */
export function sendCsMessage(sessionId: string, data: CsSendMessageBody) { export function sendCsMessage(sessionId: string, data: CsSendMessageBody) {
return request<CsAppActionVo>({ return request<CsAppActionVo>({

View File

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

View File

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

View File

@@ -181,6 +181,33 @@ function resolveSenderRole(senderType?: string | number): ChatRole | null {
return 'bot' 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 { function createMessageId(message: CsMessageVo): string {
if (message.messageId !== undefined && message.messageId !== null && message.messageId !== '') { if (message.messageId !== undefined && message.messageId !== null && message.messageId !== '') {
return String(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 { 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 id = createMessageId(message)
const seq = message.seq const seq = message.seq
@@ -265,16 +292,18 @@ function mapStructuredMessage(message: CsMessageVo, payload: Record<string, unkn
export function mapCsMessage(message: CsMessageVo): SupportMessage | null { export function mapCsMessage(message: CsMessageVo): SupportMessage | null {
const content = message.content?.trim() ?? '' const content = message.content?.trim() ?? ''
const messageType = String(message.messageType ?? '').toLowerCase() const messageType = resolveMessageType(message)
if (messageType === 'image') { if (messageType === 'image') {
if (!content) return null const src = resolveImageSrc(message)
if (!src) return null
const role = resolveSenderRole(message.senderType) || 'user'
return { return {
id: createMessageId(message), id: createMessageId(message),
seq: message.seq, seq: message.seq,
type: 'image', type: 'image',
role: 'user', role,
src: content, src,
createTime: message.createTime, createTime: message.createTime,
} }
} }

View File

@@ -11,6 +11,7 @@ import {
resolveCsSession, resolveCsSession,
sendCsMessage, sendCsMessage,
transferCsSession, transferCsSession,
uploadCsChatImage,
} from './support.api' } from './support.api'
import { import {
connectCsChatSocket, connectCsChatSocket,
@@ -21,8 +22,10 @@ import {
import { import {
isSupportPageActive, isSupportPageActive,
markSupportPageActive, markSupportPageActive,
startSupportMessagePolling,
startSupportQueuePolling, startSupportQueuePolling,
startSupportQueueWaitTimer, startSupportQueueWaitTimer,
stopSupportMessagePollTimer,
stopSupportPollTimer, stopSupportPollTimer,
stopSupportQueueTimer, stopSupportQueueTimer,
} from './support-runtime' } from './support-runtime'
@@ -150,19 +153,29 @@ export function useSupport() {
} }
} }
function updateMessagePolling() {
if (!isSupportPageActive() || !sessionId.value) {
stopSupportMessagePollTimer()
return
}
startSupportMessagePolling(() => {
void syncMessages()
})
}
function handleChatPush(payload: { function handleChatPush(payload: {
message?: Parameters<typeof mapCsMessage>[0] message?: Parameters<typeof mapCsMessage>[0]
session?: CsSessionVo session?: CsSessionVo
}) { }) {
if (payload.session) { if (payload.session && isSupportPageActive()) {
applySessionState(payload.session) applySessionState(payload.session)
} }
if (!isSupportPageActive()) return
if (payload.message) { if (payload.message) {
const mapped = mapCsMessage(payload.message) const mapped = mapCsMessage(payload.message)
if (mapped) { if (mapped) {
apiMessages.value = mergeSupportMessages(apiMessages.value, [mapped]) apiMessages.value = mergeSupportMessages(apiMessages.value, [mapped])
lastSeq.value = getMaxSeq(apiMessages.value) lastSeq.value = getMaxSeq(apiMessages.value)
lastMessageSyncAt = Date.now()
} }
} }
} }
@@ -205,6 +218,7 @@ export function useSupport() {
phase.value = 'human' phase.value = 'human'
clearQueueTimer() clearQueueTimer()
stopSupportPollTimer() stopSupportPollTimer()
updateMessagePolling()
void syncMessages(false, true) void syncMessages(false, true)
return return
} }
@@ -213,6 +227,7 @@ export function useSupport() {
phase.value = 'queue' phase.value = 'queue'
if (queueWaitSeconds.value === 0) startQueueTimer() if (queueWaitSeconds.value === 0) startQueueTimer()
updateQueuePolling() updateQueuePolling()
updateMessagePolling()
return return
} }
@@ -220,11 +235,11 @@ export function useSupport() {
humanHeader.value = HUMAN_HEADER humanHeader.value = HUMAN_HEADER
clearQueueTimer() clearQueueTimer()
updateQueuePolling() updateQueuePolling()
updateMessagePolling()
} }
async function syncMessages(reset = false, force = false) { async function syncMessages(reset = false, force = false) {
if (!isSupportPageActive() || !sessionId.value || syncingMessages) return if (!isSupportPageActive() || !sessionId.value || syncingMessages) return
if (isCsChatSocketConnected() && !reset && !force) return
const now = Date.now() const now = Date.now()
if (!reset && !force && now - lastMessageSyncAt < MESSAGE_SYNC_MIN_GAP_MS) return if (!reset && !force && now - lastMessageSyncAt < MESSAGE_SYNC_MIN_GAP_MS) return
@@ -261,6 +276,7 @@ export function useSupport() {
function pausePage() { function pausePage() {
markSupportPageActive(false) markSupportPageActive(false)
stopSupportPollTimer() stopSupportPollTimer()
stopSupportMessagePollTimer()
stopSupportQueueTimer() stopSupportQueueTimer()
} }
@@ -304,6 +320,7 @@ export function useSupport() {
bindChatSocket(nextSessionId) bindChatSocket(nextSessionId)
updateQueuePolling() updateQueuePolling()
updateMessagePolling()
} catch (err) { } catch (err) {
uni.showToast({ title: getErrorMessage(err, '客服会话创建失败'), icon: 'none' }) uni.showToast({ title: getErrorMessage(err, '客服会话创建失败'), icon: 'none' })
} finally { } 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) { async function sendUserMessage(content: string) {
const text = content.trim() const text = content.trim()
if (!text || sending.value) return if (!text || sending.value) return
@@ -472,9 +555,8 @@ export function useSupport() {
} }
bindChatSocket(sessionId.value) bindChatSocket(sessionId.value)
updateQueuePolling() updateQueuePolling()
if (!isCsChatSocketConnected()) { updateMessagePolling()
void syncMessages() void syncMessages(false, true)
}
} }
onShow(activatePage) onShow(activatePage)
@@ -500,5 +582,7 @@ export function useSupport() {
onFooterShortcut, onFooterShortcut,
onDiagnosisSuggestion, onDiagnosisSuggestion,
onSend, onSend,
onPickImage,
sending,
} }
} }

BIN
src/static/图片.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

BIN
src/static/组 98@2x.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 681 B

View File

@@ -0,0 +1,46 @@
/** 判断是否为接口返回的 opaque 令牌(非中文提示文案) */
function isOpaqueToken(value: string): boolean {
if (!value) return false
if (/[\u4e00-\u9fa5,。!?;:]/.test(value)) return false
return value.length >= 8
}
/**
* 从 request 解包结果或完整 ApiResponse 中提取流程令牌。
* 部分 RuoYi 接口在 data 为空时把 changeToken / resetToken 放在 msg。
*/
export function extractFlowToken(data: unknown): string {
if (typeof data === 'string') {
const text = data.trim()
return isOpaqueToken(text) ? text : ''
}
if (!data || typeof data !== 'object') return ''
const record = data as Record<string, unknown>
for (const key of ['changeToken', 'resetToken', 'token']) {
const direct = record[key]
if (direct != null && String(direct).trim()) {
return String(direct).trim()
}
}
if (typeof record.data === 'string' && record.data.trim()) {
return record.data.trim()
}
if (record.data && typeof record.data === 'object') {
const nested = record.data as Record<string, unknown>
for (const key of ['changeToken', 'resetToken', 'token']) {
const v = nested[key]
if (v != null && String(v).trim()) return String(v).trim()
}
}
const msg = typeof record.msg === 'string' ? record.msg.trim() : ''
if (msg && (record.data === null || record.data === undefined) && isOpaqueToken(msg)) {
return msg
}
return ''
}

View File

@@ -27,8 +27,9 @@ import tabMine from '@/static/tab-mine-active.png'
import tabMineActive from '@/static/tab-mine.png' import tabMineActive from '@/static/tab-mine.png'
import iconChevronLeft from '@/static/chevron.left.png' import iconChevronLeft from '@/static/chevron.left.png'
import iconSupportMic from '@/static/组 134.png' import iconSupportMic from '@/static/组 134.png'
import iconSupportTag from '@/static/图标 13.png' import iconSupportPhoto from '@/static/图片.png'
import iconSupportSend from '@/static/图标 14.png' import iconSupportSend from '@/static/图标 14.png'
import iconSupportQueue from '@/static/组 98@2x.png'
import iconMineNotify from '@/static/组 14919@2x.png' import iconMineNotify from '@/static/组 14919@2x.png'
import iconMineOrder from '@/static/订单@2x.png' import iconMineOrder from '@/static/订单@2x.png'
import iconMineCoupon from '@/static/优惠券@2x.png' import iconMineCoupon from '@/static/优惠券@2x.png'
@@ -87,10 +88,12 @@ export const staticAssets = {
iconChevronLeft, iconChevronLeft,
/** 组 134.png — 在线客服页麦克风 */ /** 组 134.png — 在线客服页麦克风 */
iconSupportMic, iconSupportMic,
/** 图标 13.png — 在线客服页输入框旁标签 */ /** 图片.png — 在线客服页发送图片 */
iconSupportTag, iconSupportPhoto,
/** 图标 14.png — 在线客服页发送 */ /** 图标 14.png — 在线客服页发送 */
iconSupportSend, iconSupportSend,
/** 组 98@2x.png — 在线客服排队卡片标题图标 */
iconSupportQueue,
/** 组 14919@2x.png — 我的页消息通知 */ /** 组 14919@2x.png — 我的页消息通知 */
iconMineNotify, iconMineNotify,
/** 订单@2x.png — 我的页我的订单 */ /** 订单@2x.png — 我的页我的订单 */

1
tmp-fetched-openapi.json Normal file

File diff suppressed because one or more lines are too long

1
tmp-live-api.json Normal file

File diff suppressed because one or more lines are too long

1
tmp-live-now.json Normal file

File diff suppressed because one or more lines are too long

1
tmp-live-openapi.json Normal file

File diff suppressed because one or more lines are too long