diff --git a/src/App.vue b/src/App.vue
index 9e62649..367cb56 100644
--- a/src/App.vue
+++ b/src/App.vue
@@ -1,13 +1,11 @@
diff --git a/src/hooks/use-page-show-refresh.ts b/src/hooks/use-page-show-refresh.ts
new file mode 100644
index 0000000..8c309f9
--- /dev/null
+++ b/src/hooks/use-page-show-refresh.ts
@@ -0,0 +1,20 @@
+import { onShow } from '@dcloudio/uni-app'
+
+/**
+ * 页面再次显示时执行刷新(从子页返回、切换 Tab 等)。
+ * skipInitialShow:首屏由 onLoad 加载时设为 true,避免与 onLoad 重复请求。
+ */
+export function usePageShowRefresh(
+ handler: () => void | Promise,
+ options?: { skipInitialShow?: boolean },
+) {
+ let skipFirst = Boolean(options?.skipInitialShow)
+
+ onShow(() => {
+ if (skipFirst) {
+ skipFirst = false
+ return
+ }
+ void handler()
+ })
+}
diff --git a/src/manifest.json b/src/manifest.json
index 64fc1e0..fa7c96f 100644
--- a/src/manifest.json
+++ b/src/manifest.json
@@ -2,7 +2,7 @@
"name" : "虫子智家",
"appid" : "__UNI__925D0CC",
"description" : "",
- "versionName" : "1.1.6",
+ "versionName" : "1.1.9",
"versionCode" : "100",
"transformPx" : false,
/* 5+App特有相关 */
@@ -21,8 +21,7 @@
"Bluetooth" : {},
"Camera" : {},
"Push" : {},
- "Maps" : {},
- "Geolocation" : {}
+ "Maps" : {}
},
/* 应用发布信息 */
"distribute" : {
@@ -41,7 +40,6 @@
"",
"",
"",
- "",
"",
"",
"",
@@ -56,11 +54,7 @@
},
/* ios打包配置 */
"ios" : {
- "dSYMs" : false,
- "privacyDescription" : {
- "NSLocationWhenInUseUsageDescription" : "你的位置信息将用于在地图上选择家庭位置",
- "NSLocationAlwaysAndWhenInUseUsageDescription" : "你的位置信息将用于在地图上选择家庭位置"
- }
+ "dSYMs" : false
},
/* SDK配置 */
"sdkConfigs" : {
diff --git a/src/pages/add-device/complete/complete.api.ts b/src/pages/add-device/complete/complete.api.ts
index 155767c..d982673 100644
--- a/src/pages/add-device/complete/complete.api.ts
+++ b/src/pages/add-device/complete/complete.api.ts
@@ -10,7 +10,10 @@ function normalizeProductOption(item: ProductOption): ProductOption {
}
}
-/** GET /app/device/productOptions — 获取产品型号下拉列表 */
+/**
+ * GET /app/device/productOptions
+ * 返回所有启用状态的产品型号,供添加设备页下拉选择;无需再传 status。
+ */
export function fetchProductOptions() {
return request({
url: '/app/device/productOptions',
diff --git a/src/pages/add-device/complete/complete.types.ts b/src/pages/add-device/complete/complete.types.ts
index b2c8603..2039666 100644
--- a/src/pages/add-device/complete/complete.types.ts
+++ b/src/pages/add-device/complete/complete.types.ts
@@ -1,11 +1,6 @@
-/** POST /app/device/productOptions 返回项 */
+/** GET /app/device/productOptions — 启用状态产品型号(AppProductOptionVo) */
export interface ProductOption {
productId?: string | number
model?: string
name?: string
- category?: string
- connectTypes?: string
- filterEnabled?: boolean
- filterTotalDays?: number
- capabilities?: string[]
}
diff --git a/src/pages/add-device/complete/use-complete-device.ts b/src/pages/add-device/complete/use-complete-device.ts
index 96d2f64..fd6e03b 100644
--- a/src/pages/add-device/complete/use-complete-device.ts
+++ b/src/pages/add-device/complete/use-complete-device.ts
@@ -4,13 +4,12 @@ import { resolveValidHomeId } from '@/api/home'
import { getErrorMessage } from '@/utils/api-error'
import { fetchRoomList } from '@/api/location'
import type { RoomOption } from '@/types/location'
-import { fetchDeviceList } from '@/pages/device/device.api'
+import { fetchAllDeviceList } from '@/pages/device/device.api'
import { updateDeviceRuntime } from '@/pages/device/detail/device-detail.api'
import { updateDeviceSettings } from '@/pages/device/settings/device-settings.api'
import { buildBleDeviceName, isStandardBleDeviceName } from '@/utils/ble-device-name'
import { releaseBleDevice } from '@/utils/bluetooth'
import { clearZ2BleHandleCache, sendZ2BleRenameCommand } from '@/utils/z2-ble'
-import { getZ2RenameProgressLabel } from '@/utils/z2-ble-protocol'
import { bindDevice } from '../add-device.api'
import { parseId, sameId } from '@/utils/device-id'
import { readStoredHomeId, saveSelectedHomeId } from '@/utils/selected-home'
@@ -22,6 +21,8 @@ export function useCompleteDevice() {
const currentStep = 4
const deviceNo = ref('')
const deviceName = ref('Z2 空气净化器')
+ /** 配对时读到的 BLE 广播名,与用户可改的云端显示名无关 */
+ const pairedBleName = ref('')
const serialMasked = ref('****A3B2')
const productId = ref('')
const model = ref('')
@@ -142,7 +143,10 @@ export function useCompleteDevice() {
function applyQuery(query: Record) {
const ctx = readBindDeviceContext(query)
if (ctx.deviceNo) deviceNo.value = ctx.deviceNo
- if (ctx.name) deviceName.value = ctx.name
+ if (ctx.name) {
+ deviceName.value = ctx.name
+ pairedBleName.value = ctx.name
+ }
if (ctx.serialMasked) serialMasked.value = ctx.serialMasked
const parsedProductId = parseId(ctx.productId)
if (parsedProductId) productId.value = parsedProductId
@@ -246,23 +250,15 @@ export function useCompleteDevice() {
try {
if (bleDeviceId.value && bluetoothConnected.value && mac.value) {
const bleName = buildBleDeviceName(mac.value)
- const needRename = !isStandardBleDeviceName(mac.value, deviceName.value)
+ const needRename = pairedBleName.value
+ && !isStandardBleDeviceName(mac.value, pairedBleName.value)
if (needRename) {
- uni.showLoading({ title: '正在同步蓝牙名称…', mask: true })
try {
await sendZ2BleRenameCommand(bleDeviceId.value, bleName, {
timeoutMs: 25000,
- onProgress: (progress) => {
- uni.showLoading({
- title: getZ2RenameProgressLabel(progress) || '正在同步蓝牙名称…',
- mask: true,
- })
- },
})
} catch {
// 蓝牙名称同步失败不影响云端绑定,静默继续
- } finally {
- uni.hideLoading()
}
}
}
@@ -281,7 +277,7 @@ export function useCompleteDevice() {
...(locationId.value ? { locationId: locationId.value } : {}),
})
- const list = await fetchDeviceList()
+ const list = await fetchAllDeviceList()
const bound = list?.find((item) => item.deviceNo === deviceNo.value.trim())
if (bound?.deviceId != null) {
const boundName = bound.name?.trim()
diff --git a/src/pages/change-password/use-change-password.ts b/src/pages/change-password/use-change-password.ts
index f9007c7..045dd86 100644
--- a/src/pages/change-password/use-change-password.ts
+++ b/src/pages/change-password/use-change-password.ts
@@ -1,38 +1,39 @@
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
-import { teardownMessageInbox } from '@/hooks/use-message-inbox'
-import { ApiError, getErrorMessage } from '@/utils/api-error'
-import { clearStoredToken } from '@/utils/auth-token'
-import { markPasswordModified } from '@/utils/password-modified-at'
+import { getErrorMessage } from '@/utils/api-error'
+import {
+ handleAuthSessionExpired,
+ isAuthSessionExpiredError,
+} from '@/utils/auth-session'
+import { markPasswordModifiedPendingForPhone } from '@/utils/password-modified-at'
import { isValidStrongPassword, PASSWORD_INVALID_TOAST } from '@/utils/validate'
import { resetPasswordByToken } from './change-password.api'
-const LOGIN_ROUTE = '/pages/login/index'
-
-function isSessionInvalidError(err: unknown): boolean {
- if (!(err instanceof ApiError)) return false
- if (err.code === 401) return true
- return /登录|token|认证|授权/i.test(err.message)
+function redirectToLoginAfterPasswordChange(toastTitle = '密码修改成功,请重新登录') {
+ handleAuthSessionExpired({
+ message: toastTitle,
+ forceNavigateToLogin: true,
+ })
}
-function redirectToLoginAfterPasswordChange(toastTitle = '密码修改成功,请重新登录') {
- teardownMessageInbox()
- clearStoredToken()
- uni.showToast({ title: toastTitle, icon: 'none' })
- setTimeout(() => {
- uni.reLaunch({ url: LOGIN_ROUTE })
- }, 800)
+/** 改密后勿再请求 profile,避免 401 触发全局踢登抢占跳转 */
+function recordPasswordModifiedAfterReset(fallbackPhone: string) {
+ if (!fallbackPhone.trim()) return
+ markPasswordModifiedPendingForPhone(fallbackPhone)
}
export function useChangePassword() {
const password = ref('')
const confirmPassword = ref('')
const resetToken = ref('')
+ const boundPhone = ref('')
const loading = ref(false)
onLoad((query) => {
const raw = (query?.resetToken as string) || ''
resetToken.value = raw ? decodeURIComponent(raw) : ''
+ const phoneRaw = (query?.phone as string) || ''
+ boundPhone.value = phoneRaw ? decodeURIComponent(phoneRaw) : ''
if (!resetToken.value) {
uni.showToast({ title: '请先完成验证码校验', icon: 'none' })
setTimeout(() => uni.navigateBack(), 1500)
@@ -60,11 +61,11 @@ export function useChangePassword() {
newPassword: password.value,
confirmPassword: confirmPassword.value,
})
- markPasswordModified()
+ recordPasswordModifiedAfterReset(boundPhone.value)
redirectToLoginAfterPasswordChange()
} catch (err) {
- if (isSessionInvalidError(err)) {
- markPasswordModified()
+ if (isAuthSessionExpiredError(err)) {
+ recordPasswordModifiedAfterReset(boundPhone.value)
redirectToLoginAfterPasswordChange('登录状态已失效,请使用新密码重新登录')
return
}
diff --git a/src/pages/device/components/device-header/index.vue b/src/pages/device/components/device-header/index.vue
index d806b94..d4ceeaa 100644
--- a/src/pages/device/components/device-header/index.vue
+++ b/src/pages/device/components/device-header/index.vue
@@ -21,28 +21,36 @@
v-if="pickerOpen"
class="device-header__mask"
@tap="closePicker"
+ @touchmove.stop.prevent="preventTouchMove"
/>
+
@@ -79,7 +87,7 @@
diff --git a/src/pages/mine/support/index.vue b/src/pages/mine/support/index.vue
index e9567f0..430031e 100644
--- a/src/pages/mine/support/index.vue
+++ b/src/pages/mine/support/index.vue
@@ -1,4 +1,4 @@
-
+
@@ -53,7 +53,14 @@
- 🕐 {{ item.text }}
+
+
+ {{ item.text }}
+
- {{ item.content }}
+
+ {{ item.content }}
@@ -101,15 +113,19 @@
-
+
●
- {{ action.label }}
+ {{ action.label }}
@@ -236,6 +252,7 @@
:src="chatImageDisplaySrc(item)"
mode="aspectFill"
@error="onChatImageError(item)"
+ @load="onChatImageLoad"
@tap="onPreviewImage(chatImageDisplaySrc(item))"
/>
@@ -264,14 +281,28 @@
本次会话已加密,客服不会向您索要密码或验证码
+
+
@@ -305,6 +336,18 @@
+
+
@@ -313,6 +356,7 @@ import { computed, watch } from 'vue'
import { staticAssets } from '@/utils/static-assets'
import { useCsChatImage } from './use-cs-chat-image'
import { useSupportChatScroll } from './use-support-chat-scroll'
+import DeviceConsultPicker from './components/device-consult-picker/index.vue'
import { useSupport } from './use-support'
import type { DiagnosisItem } from './support.types'
@@ -326,6 +370,8 @@ const {
sessionEnded,
formattedQueueWait,
footerShortcuts,
+ faqPanelVisible,
+ faqActions,
onQuickAction,
onTransferHuman,
onEndSession,
@@ -335,14 +381,34 @@ const {
onDiagnosisSuggestion,
onSend,
onPickImage,
+ deviceConsultVisible,
+ deviceConsultLoading,
+ deviceConsultKeyword,
+ deviceConsultFilteredDevices,
+ deviceConsultDeviceCountText,
+ deviceConsultSelectedDeviceId,
+ onDeviceConsultSelect,
+ onConfirmDeviceConsult,
+ onDeviceConsultCancel,
} = useSupport()
-const { scrollTop, scrollIntoView, scrollToBottom } = useSupportChatScroll(messages)
+const { scrollTop, scrollIntoView, scrollToBottom, scrollToBottomSequence } = useSupportChatScroll(messages)
+
+let chatImageScrollTimer: ReturnType | null = null
+
+function onChatImageLoad() {
+ if (chatImageScrollTimer) clearTimeout(chatImageScrollTimer)
+ chatImageScrollTimer = setTimeout(() => {
+ chatImageScrollTimer = null
+ scrollToBottomSequence()
+ }, 60)
+}
const humanAvatarText = computed(() => headerInfo.value.avatarText || '服')
const { displaySrc: chatImageDisplaySrc, onImageError: onChatImageError } = useCsChatImage(
() => messages.value,
+ { onDisplayUpdate: () => scrollToBottomSequence() },
)
watch(sessionEnded, (ended) => {
@@ -362,6 +428,14 @@ function handleSend() {
void scrollToBottom(400)
}
+function handleFooterShortcut(label: string) {
+ onFooterShortcut(label)
+ if (label === '常见问题' || label === '订单咨询') {
+ void scrollToBottom(80)
+ void scrollToBottom(280)
+ }
+}
+
function diagnosisStatusText(status: DiagnosisItem['status']): string {
if (status === 'done') return '已完成'
if (status === 'running') return '进行中'
diff --git a/src/pages/mine/support/support-device-consult.types.ts b/src/pages/mine/support/support-device-consult.types.ts
new file mode 100644
index 0000000..0404fe8
--- /dev/null
+++ b/src/pages/mine/support/support-device-consult.types.ts
@@ -0,0 +1,8 @@
+/** 客服「订单咨询」设备选择项 */
+export interface SupportConsultDeviceItem {
+ deviceId: string
+ name: string
+ modelText: string
+ snText: string
+ isOnline: boolean
+}
diff --git a/src/pages/mine/support/support-device-consult.utils.ts b/src/pages/mine/support/support-device-consult.utils.ts
new file mode 100644
index 0000000..c096222
--- /dev/null
+++ b/src/pages/mine/support/support-device-consult.utils.ts
@@ -0,0 +1,55 @@
+import type { AppDeviceVo } from '@/pages/device/device.types'
+import { resolveDeviceListOnline } from '@/pages/device/device-online'
+import type { SupportConsultDeviceItem } from './support-device-consult.types'
+
+function formatSnSegment(value: string): string {
+ const compact = value.replace(/[^a-zA-Z0-9]/g, '').toUpperCase()
+ if (compact.length >= 8) {
+ return `${compact.slice(0, 4)}-${compact.slice(4, 8)}`
+ }
+ return compact || value
+}
+
+function resolveSn(device: AppDeviceVo): string {
+ const raw = device.deviceNo?.trim() || device.mac?.trim() || device.imei?.trim()
+ if (raw) return formatSnSegment(raw)
+ if (device.deviceId != null) return String(device.deviceId)
+ return '--'
+}
+
+/** 列表无产品型号字段时,用设备名后缀或默认占位 */
+function resolveModelLabel(device: AppDeviceVo): string {
+ const name = device.name?.trim() || ''
+ const match = name.match(/\b([A-Z]{1,3}[- ]?[A-Z0-9]{2,})\b/i)
+ if (match?.[1]) return match[1].replace(/\s+/g, '-')
+ return '--'
+}
+
+export function mapVoToConsultDevice(device: AppDeviceVo): SupportConsultDeviceItem | null {
+ if (device.deviceId == null || device.deviceId === '') return null
+ const name = device.name?.trim() || '未命名设备'
+ const modelText = resolveModelLabel(device)
+ const snText = resolveSn(device)
+ return {
+ deviceId: String(device.deviceId),
+ name,
+ modelText,
+ snText,
+ isOnline: resolveDeviceListOnline(device),
+ }
+}
+
+export function buildDeviceConsultMessage(item: SupportConsultDeviceItem): string {
+ const modelPart = item.modelText !== '--' ? `型号 ${item.modelText}` : '型号未登记'
+ return `【订单咨询】${item.name}\n${modelPart} · SN ${item.snText}`
+}
+
+export function matchConsultDeviceKeyword(
+ item: SupportConsultDeviceItem,
+ keyword: string,
+): boolean {
+ const q = keyword.trim().toLowerCase()
+ if (!q) return true
+ const haystack = `${item.name} ${item.modelText} ${item.snText}`.toLowerCase()
+ return haystack.includes(q)
+}
diff --git a/src/pages/mine/support/support-kb-buttons-cache.ts b/src/pages/mine/support/support-kb-buttons-cache.ts
new file mode 100644
index 0000000..a26e41d
--- /dev/null
+++ b/src/pages/mine/support/support-kb-buttons-cache.ts
@@ -0,0 +1,126 @@
+import type { CsMessageVo, QuickActionItem } from './support.types'
+
+const STORAGE_KEY = 'czzj_cs_kb_message_buttons_v2'
+const MAX_ENTRIES = 400
+
+type CacheEntry = {
+ buttons: QuickActionItem[]
+ /** false 表示该条知识库明确不带按钮,避免误用旧缓存 */
+ enabled: boolean
+ kbId?: string
+ updatedAt: number
+}
+
+type CacheStore = Record
+
+function readStore(): CacheStore {
+ try {
+ const raw = uni.getStorageSync(STORAGE_KEY)
+ if (!raw || typeof raw !== 'object') return {}
+ return raw as CacheStore
+ } catch {
+ return {}
+ }
+}
+
+function writeStore(store: CacheStore) {
+ const entries = Object.entries(store).sort((a, b) => b[1].updatedAt - a[1].updatedAt)
+ const trimmed: CacheStore = {}
+ for (const [key, value] of entries.slice(0, MAX_ENTRIES)) {
+ trimmed[key] = value
+ }
+ try {
+ uni.setStorageSync(STORAGE_KEY, trimmed)
+ } catch {
+ // ignore quota errors
+ }
+}
+
+function cacheKeys(sessionId: string, message: CsMessageVo): string[] {
+ const sid = sessionId.trim()
+ if (!sid) return []
+ const keys: string[] = []
+ if (message.messageId != null && message.messageId !== '') {
+ keys.push(`${sid}:mid:${message.messageId}`)
+ }
+ if (message.seq != null) {
+ keys.push(`${sid}:seq:${message.seq}`)
+ }
+ return keys
+}
+
+function writeEntry(sessionId: string, message: CsMessageVo, entry: CacheEntry) {
+ const keys = cacheKeys(sessionId, message)
+ if (!keys.length) return
+ const store = readStore()
+ for (const key of keys) {
+ store[key] = entry
+ }
+ writeStore(store)
+}
+
+export function persistKbButtonsForMessage(
+ sessionId: string,
+ message: CsMessageVo,
+ buttons: QuickActionItem[],
+ kbId?: string | number,
+) {
+ if (!buttons.length) return
+ writeEntry(sessionId, message, {
+ buttons,
+ enabled: true,
+ kbId: kbId != null && kbId !== '' ? String(kbId) : undefined,
+ updatedAt: Date.now(),
+ })
+}
+
+export function markKbButtonsDisabledForMessage(
+ sessionId: string,
+ message: CsMessageVo,
+ kbId?: string | number,
+) {
+ writeEntry(sessionId, message, {
+ buttons: [],
+ enabled: false,
+ kbId: kbId != null && kbId !== '' ? String(kbId) : undefined,
+ updatedAt: Date.now(),
+ })
+}
+
+function readEntry(sessionId: string, message: CsMessageVo): CacheEntry | undefined {
+ const keys = cacheKeys(sessionId, message)
+ if (!keys.length) return undefined
+ const store = readStore()
+ const midKey = keys.find((key) => key.includes(':mid:'))
+ if (midKey && store[midKey]) return store[midKey]
+ const hasMessageId = message.messageId != null && message.messageId !== ''
+ if (hasMessageId) return undefined
+ const seqKey = keys.find((key) => key.includes(':seq:'))
+ if (seqKey && store[seqKey]) return store[seqKey]
+ return undefined
+}
+
+export function isKbButtonsDisabledInCache(
+ sessionId: string,
+ message: CsMessageVo,
+): boolean {
+ const entry = readEntry(sessionId, message)
+ return entry?.enabled === false
+}
+
+export function loadKbButtonsForMessage(
+ sessionId: string,
+ message: CsMessageVo,
+): QuickActionItem[] {
+ const entry = readEntry(sessionId, message)
+ if (!entry || entry.enabled === false) return []
+ return entry.buttons?.length ? entry.buttons : []
+}
+
+export function clearKbButtonsCache() {
+ try {
+ uni.removeStorageSync(STORAGE_KEY)
+ } catch {
+ // ignore
+ }
+}
diff --git a/src/pages/mine/support/support.scss b/src/pages/mine/support/support.scss
index 5d925e7..ee34ee4 100644
--- a/src/pages/mine/support/support.scss
+++ b/src/pages/mine/support/support.scss
@@ -169,9 +169,21 @@ $support-danger: #f04438;
}
.support-page__time-pill {
+ display: inline-flex;
+ align-items: center;
+ gap: 8rpx;
padding: 8rpx 20rpx;
border-radius: 20rpx;
background: #eef1f5;
+}
+
+.support-page__time-icon {
+ width: 28rpx;
+ height: 28rpx;
+ flex-shrink: 0;
+}
+
+.support-page__time-text {
font-size: 22rpx;
color: $support-text-secondary;
line-height: 1.4;
@@ -253,6 +265,14 @@ $support-danger: #f04438;
}
}
+.support-page__rich {
+ display: block;
+ max-width: 100%;
+ font-size: 28rpx;
+ line-height: 1.55;
+ word-break: break-word;
+}
+
.support-page__bubble {
max-width: 100%;
padding: 20rpx 24rpx;
@@ -302,6 +322,17 @@ $support-danger: #f04438;
background: #fff;
border: 1rpx solid #e4e7ec;
border-radius: 32rpx;
+ line-height: 1.3;
+ position: relative;
+ z-index: 2;
+
+ &--active {
+ background: #eff6ff;
+ border-color: #93c5fd;
+ }
+}
+
+.support-page__quick-label {
font-size: 26rpx;
color: #3b82f6;
line-height: 1.3;
@@ -664,6 +695,42 @@ $support-danger: #f04438;
font-size: 24rpx;
color: $support-text-muted;
line-height: 1.3;
+
+ &--active {
+ color: $support-green;
+ background: rgba(30, 198, 113, 0.1);
+ }
+
+ &--pressed {
+ background: #eef1f5;
+ }
+}
+
+.support-page__footer-faq {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 16rpx;
+ margin-bottom: 16rpx;
+}
+
+.support-page__footer-faq-item {
+ margin: 0;
+ padding: 12rpx 20rpx;
+ border-radius: 28rpx;
+ background: #fff;
+ border: 1rpx solid #e4e7ec !important;
+ font-size: 24rpx;
+ color: #3b82f6;
+ line-height: 1.35;
+
+ &::after {
+ display: none;
+ }
+
+ &--active {
+ background: #eff6ff;
+ border-color: #93c5fd !important;
+ }
}
.support-page__input-row {
diff --git a/src/pages/mine/support/support.types.ts b/src/pages/mine/support/support.types.ts
index 79e15e9..0fe5d73 100644
--- a/src/pages/mine/support/support.types.ts
+++ b/src/pages/mine/support/support.types.ts
@@ -55,7 +55,7 @@ export interface CsMessageVo {
fileUrl?: string
clientMsgId?: string
createTime?: string
- extra?: Record
+ extra?: Record | string
}
/** WebSocket /app/cs/chat 推送 */
@@ -73,12 +73,29 @@ export interface CsCreateSessionBody {
accessType?: 'bot' | 'human'
}
+export interface CsRobotButtonVo {
+ buttonId?: number | string
+ buttonCode?: string
+ code?: string
+ label?: string
+ buttonName?: string
+ name?: string
+ text?: string
+ sort?: number
+}
+
export interface CsRobotVo {
kbId?: number | string
title?: string
content?: string
matched?: boolean
- buttons?: Array<{ buttonCode?: string; label?: string }>
+ /** 后台是否勾选展示快捷按钮(未勾选时应为 false/0,且 buttons 为空) */
+ showButtons?: boolean | string | number
+ buttonEnabled?: boolean | string | number
+ enableButtons?: boolean | string | number
+ buttons?: CsRobotButtonVo[] | string[] | null
+ buttonList?: CsRobotButtonVo[] | string[]
+ shortcutButtons?: CsRobotButtonVo[] | string[]
}
/** POST /app/cs/session 及发消息等操作返回 data */
@@ -149,6 +166,8 @@ export type SupportMessage =
type: 'text'
role: ChatRole
content: string
+ /** 知识库富文本回复(HTML) */
+ richHtml?: string
createTime?: string
}
| {
diff --git a/src/pages/mine/support/support.utils.ts b/src/pages/mine/support/support.utils.ts
index 40b91ae..c1cb159 100644
--- a/src/pages/mine/support/support.utils.ts
+++ b/src/pages/mine/support/support.utils.ts
@@ -9,6 +9,12 @@ import type {
SupportPhase,
} from './support.types'
import { CS_IMAGE_MESSAGE_PLACEHOLDER, CS_SESSION_STATUS } from './support.types'
+import {
+ isKbButtonsDisabledInCache,
+ loadKbButtonsForMessage,
+ markKbButtonsDisabledForMessage,
+ persistKbButtonsForMessage,
+} from './support-kb-buttons-cache'
/** 上传成功后缓存 ossId → 可访问地址,用于消息列表尚未带 url 时展示 */
const csImageUrlCache = new Map()
@@ -74,22 +80,208 @@ export function createClientMsgId(): string {
return `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`
}
+const ROBOT_BUTTON_LABELS: Record = {
+ resolved: '已解决',
+ transfer_human: '转人工',
+ transferhuman: '转人工',
+}
+
+function isTruthyMatched(value: unknown): boolean {
+ return value === true || value === 1 || value === '1' || value === 'true'
+}
+
+function isExplicitlyDisabled(value: unknown): boolean {
+ return value === false || value === 0 || value === '0' || value === 'false'
+}
+
+/** 知识库条目是否开启快捷按钮(与后台勾选一致;未返回开关时以 buttons 是否非空为准) */
+export function isRobotShortcutButtonsEnabled(robot?: CsRobotVo): boolean {
+ if (!robot) return false
+ const flags = [robot.showButtons, robot.buttonEnabled, robot.enableButtons]
+ if (flags.some((item) => isExplicitlyDisabled(item))) return false
+ const raw = robot.buttons ?? robot.buttonList ?? robot.shortcutButtons
+ if (raw === null) return false
+ const parsed = mapRobotButtons(raw)
+ if (!parsed.length) return false
+ if (flags.some((item) => isTruthyMatched(item))) return true
+ // 未返回开关时:仅当 buttons 非空才展示(与后台「勾选带按钮」且配置了按钮一致)
+ return parsed.length > 0
+}
+
+export function resolveKbButtonsFromRobot(robot?: CsRobotVo): QuickActionItem[] {
+ if (!robot) return []
+ if (robot.matched === false || robot.matched === 'false' || robot.matched === 0) {
+ return []
+ }
+ if (!isRobotShortcutButtonsEnabled(robot)) return []
+ return mapRobotButtons(robot.buttons ?? robot.buttonList ?? robot.shortcutButtons)
+}
+
+/** 知识库回复底部「已解决 / 转人工」等快捷按钮 */
+export function resolveRobotShortcutAction(
+ action: QuickActionItem,
+): 'resolved' | 'transfer_human' | null {
+ const id = action.id.trim().toLowerCase().replace(/-/g, '_')
+ const label = action.label.trim()
+ if (id === 'resolved' || label === '已解决') return 'resolved'
+ if (id === 'transfer_human' || id === 'transferhuman' || label === '转人工') {
+ return 'transfer_human'
+ }
+ return null
+}
+
+function normalizeRobotButtonCode(raw: string): string {
+ const code = raw.trim().toLowerCase().replace(/-/g, '_')
+ if (code === 'transferhuman') return 'transfer_human'
+ return code
+}
+
+function resolveQuickActionDedupeKey(item: QuickActionItem): string {
+ const id = normalizeRobotButtonCode(item.id || '')
+ if (id && !id.startsWith('robot-btn')) return id
+ const label = item.label.trim()
+ if (label === '已解决') return 'resolved'
+ if (label === '转人工') return 'transfer_human'
+ const fromLabel = normalizeRobotButtonCode(label)
+ if (fromLabel && (ROBOT_BUTTON_LABELS[fromLabel.replace(/_/g, '')] || ROBOT_BUTTON_LABELS[fromLabel])) {
+ return fromLabel
+ }
+ return label.toLowerCase()
+}
+
+/** 后台可能重复下发同一 buttonCode,合并为一项 */
+export function dedupeQuickActionItems(items: QuickActionItem[]): QuickActionItem[] {
+ const seen = new Set()
+ const result: QuickActionItem[] = []
+ for (const item of items) {
+ const key = resolveQuickActionDedupeKey(item)
+ if (!key || seen.has(key)) continue
+ seen.add(key)
+ const mappedLabel = ROBOT_BUTTON_LABELS[key.replace(/_/g, '')] || ROBOT_BUTTON_LABELS[key]
+ const label = item.label.trim() || mappedLabel || item.label
+ result.push({
+ id: key.startsWith('robot-btn') ? (item.id || key) : key,
+ label,
+ })
+ }
+ return result
+}
+
+export function mapRobotButtons(raw: unknown): QuickActionItem[] {
+ if (typeof raw === 'string') {
+ const text = raw.trim()
+ if (!text) return []
+ if (text.startsWith('[')) {
+ try {
+ return mapRobotButtons(JSON.parse(text) as unknown)
+ } catch {
+ return []
+ }
+ }
+ const split = text.split(/[,,|]/).map((part, index) => {
+ const label = part.trim()
+ if (!label) return null
+ const code = normalizeRobotButtonCode(label)
+ const mappedLabel = ROBOT_BUTTON_LABELS[code.replace(/_/g, '')] || ROBOT_BUTTON_LABELS[code] || label
+ return { id: code || `robot-btn-${index}`, label: mappedLabel }
+ }).filter((item): item is QuickActionItem => !!item)
+ return dedupeQuickActionItems(split)
+ }
+ if (!Array.isArray(raw)) return []
+ if (raw.every((item) => item && typeof item === 'object' && 'label' in item && 'id' in item)) {
+ return dedupeQuickActionItems(raw as QuickActionItem[])
+ }
+ const result: Array = []
+ raw.forEach((item, index) => {
+ if (typeof item === 'string') {
+ const label = item.trim()
+ if (!label) return
+ result.push({ id: `robot-btn-${index}`, label })
+ return
+ }
+ if (!item || typeof item !== 'object') return
+ const record = item as Record
+ const codeRaw = String(
+ record.buttonCode ?? record.code ?? record.buttonType ?? record.type ?? '',
+ ).trim()
+ const code = codeRaw ? normalizeRobotButtonCode(codeRaw) : ''
+ const label = String(
+ record.label ?? record.buttonName ?? record.name ?? record.text ?? '',
+ ).trim() || (code ? ROBOT_BUTTON_LABELS[code.replace(/_/g, '')] || ROBOT_BUTTON_LABELS[code] : '')
+ if (!label) return
+ result.push({
+ id: code || `robot-btn-${index}`,
+ label,
+ sort: typeof record.sort === 'number' ? record.sort : undefined,
+ })
+ })
+ result.sort((a, b) => {
+ const sa = a.sort ?? Number.MAX_SAFE_INTEGER
+ const sb = b.sort ?? Number.MAX_SAFE_INTEGER
+ return sa - sb
+ })
+ return dedupeQuickActionItems(result)
+}
+
+export function normalizeCsRobotVo(raw: unknown): CsRobotVo | undefined {
+ if (!raw || typeof raw !== 'object') return undefined
+ const record = raw as Record
+ return {
+ kbId: (record.kbId ?? record.id) as string | number | undefined,
+ title: String(record.title ?? record.questionTitle ?? '').trim() || undefined,
+ content: String(record.content ?? record.replyContent ?? record.answer ?? '').trim() || undefined,
+ matched: isTruthyMatched(record.matched)
+ ? true
+ : (record.matched === false || record.matched === 'false' || record.matched === 0
+ ? false
+ : record.matched as boolean | undefined),
+ showButtons: (record.showButtons ?? record.showButton ?? record.enableShortcut) as CsRobotVo['showButtons'],
+ buttonEnabled: record.buttonEnabled as CsRobotVo['buttonEnabled'],
+ enableButtons: (record.enableButtons ?? record.withButtons) as CsRobotVo['enableButtons'],
+ buttons: (record.buttons ?? record.buttonList ?? record.shortcutButtons) as CsRobotVo['buttons'],
+ buttonList: record.buttonList as CsRobotVo['buttonList'],
+ shortcutButtons: record.shortcutButtons as CsRobotVo['shortcutButtons'],
+ }
+}
+
+function unwrapCsActionPayload(
+ data: CsAppActionVo | CsSessionVo | string | null | undefined,
+): CsAppActionVo | CsSessionVo | string | null | undefined {
+ if (!data || typeof data !== 'object') return data
+ const record = data as Record
+ const hasActionFields = record.session != null
+ || Array.isArray(record.messages)
+ || record.robot != null
+ || record.robotReply != null
+ if (hasActionFields) return data
+ const nested = record.data
+ if (nested && typeof nested === 'object') {
+ return nested as CsAppActionVo
+ }
+ return data
+}
+
export function unwrapCsActionResponse(
data: CsAppActionVo | CsSessionVo | string | null | undefined,
): { session: CsSessionVo; messages?: CsMessageVo[]; robot?: CsRobotVo } {
- if (!data) return { session: {} }
- if (typeof data === 'string') {
- return { session: normalizeSessionResponse(data) }
+ const payload = unwrapCsActionPayload(data)
+ if (!payload) return { session: {} }
+ if (typeof payload === 'string') {
+ return { session: normalizeSessionResponse(payload) }
}
- if (data.session) {
+ const record = payload as Record
+ const robot = normalizeCsRobotVo(
+ record.robot ?? record.robotReply ?? record.robotVo ?? record.kbReply,
+ )
+ if (payload.session) {
return {
- session: normalizeSessionResponse(data.session),
- messages: data.messages,
- robot: data.robot,
+ session: normalizeSessionResponse(payload.session),
+ messages: payload.messages,
+ robot,
}
}
- const record = data as CsSessionVo & CsAppActionVo
- const { messages, robot, ...session } = record
+ const merged = payload as CsSessionVo & CsAppActionVo
+ const { messages, ...session } = merged
return {
session: normalizeSessionResponse(session),
messages,
@@ -97,8 +289,106 @@ export function unwrapCsActionResponse(
}
}
+function isHtmlLike(text: string): boolean {
+ return /<[a-z][\s\S]*?>/i.test(text)
+}
+
+function sanitizeSupportHtml(html: string): string {
+ let out = html
+ .replace(/