fix:bug解决

This commit is contained in:
李伊帆
2026-10-28 10:36:39 +08:00
parent c369127166
commit 91bca314ba
57 changed files with 2839 additions and 384 deletions

View File

@@ -1,13 +1,11 @@
<script setup lang="ts"> <script setup lang="ts">
import { onLaunch, onShow } from '@dcloudio/uni-app' import { onLaunch, onShow } from '@dcloudio/uni-app'
import { setupMessageInbox } from '@/hooks/use-message-inbox' import { setupMessageInbox } from '@/hooks/use-message-inbox'
import { ensureLoggedInOnForeground, LOGIN_ROUTE } from '@/utils/auth-session'
import { getStoredToken } from '@/utils/auth-token' import { getStoredToken } from '@/utils/auth-token'
import { installLocalizedToast } from '@/utils/localized-toast' import { installLocalizedToast } from '@/utils/localized-toast'
import { staticAssets } from '@/utils/static-assets' import { staticAssets } from '@/utils/static-assets'
const HOME_ROUTE = '/pages/device/index'
const LOGIN_ROUTE = '/pages/login/index'
function applyH5Favicon() { function applyH5Favicon() {
// #ifdef H5 // #ifdef H5
if (typeof document === 'undefined') return if (typeof document === 'undefined') return
@@ -41,7 +39,9 @@ onLaunch(() => {
onShow(() => { onShow(() => {
if (getStoredToken()) { if (getStoredToken()) {
setupMessageInbox() setupMessageInbox()
return
} }
ensureLoggedInOnForeground()
}) })
</script> </script>
<style lang="scss"> <style lang="scss">

View File

@@ -14,6 +14,7 @@ import {
getStoredToken, getStoredToken,
saveStoredToken, saveStoredToken,
} from '@/utils/auth-token' } from '@/utils/auth-token'
import { isAuthSessionExpiredError, notifyAuthSessionExpired } from '@/utils/auth-session'
import { ApiError, isApiSuccess, normalizeNetworkErrorMessage, unwrapApiData } from '@/utils/api-error' import { ApiError, isApiSuccess, normalizeNetworkErrorMessage, unwrapApiData } from '@/utils/api-error'
/** RuoYi-Vue-Plus App 端 clientId(登录等 JSON 接口) */ /** RuoYi-Vue-Plus App 端 clientId(登录等 JSON 接口) */
@@ -135,9 +136,7 @@ export function buildCsAppAuthHeaders(extra?: Record<string, unknown>): Record<s
} }
export function isCsAuthError(err: unknown): boolean { export function isCsAuthError(err: unknown): boolean {
if (!(err instanceof ApiError)) return false return isAuthSessionExpiredError(err)
if (err.code === 401) return true
return /登录状态|未登录|重新登录/i.test(err.message)
} }
export type UploadAuthMode = 'default' | 'cs' export type UploadAuthMode = 'default' | 'cs'
@@ -160,12 +159,22 @@ function isUploadTransportError(rawData: string, errMsg?: string): boolean {
return /uploadFile:fail|downloadFile:fail|request:fail|statusCode:\s*null/i.test(payload) return /uploadFile:fail|downloadFile:fail|request:fail|statusCode:\s*null/i.test(payload)
} }
function rejectRequestError(
err: ApiError,
requestPath: string,
reject: (reason: ApiError) => void,
) {
notifyAuthSessionExpired(err, requestPath)
reject(err)
}
function handleUploadSuccess<T>( function handleUploadSuccess<T>(
statusCode: number | undefined, statusCode: number | undefined,
rawData: string, rawData: string,
resolve: (value: T) => void, resolve: (value: T) => void,
reject: (reason: ApiError) => void, reject: (reason: ApiError) => void,
errMsg?: string, errMsg?: string,
requestPath = '',
) { ) {
if (isUploadTransportError(rawData, errMsg)) { if (isUploadTransportError(rawData, errMsg)) {
reject(new ApiError(UPLOAD_NETWORK_ERROR)) reject(new ApiError(UPLOAD_NETWORK_ERROR))
@@ -182,10 +191,10 @@ function handleUploadSuccess<T>(
if (apiMessage && !/^[a-z0-9_.\-:()\s]+$/i.test(apiMessage)) { if (apiMessage && !/^[a-z0-9_.\-:()\s]+$/i.test(apiMessage)) {
message = apiMessage message = apiMessage
} }
reject(new ApiError(message, body.code ?? statusCode)) rejectRequestError(new ApiError(message, body.code ?? statusCode), requestPath, reject)
return return
} catch { } catch {
reject(new ApiError(message, statusCode)) rejectRequestError(new ApiError(message, statusCode), requestPath, reject)
return return
} }
} }
@@ -198,7 +207,11 @@ function handleUploadSuccess<T>(
return return
} }
if (!isApiSuccess(body)) { if (!isApiSuccess(body)) {
reject(new ApiError(body.msg || body.message || '上传失败', body.code)) rejectRequestError(
new ApiError(body.msg || body.message || '上传失败', body.code),
requestPath,
reject,
)
return return
} }
const data = unwrapApiData<T>(body as ApiResponse<T> & Record<string, unknown>) const data = unwrapApiData<T>(body as ApiResponse<T> & Record<string, unknown>)
@@ -214,6 +227,7 @@ function uploadViaUniMultipart<T>(
filePath: string, filePath: string,
fieldName: string, fieldName: string,
authMode: UploadAuthMode, authMode: UploadAuthMode,
requestPath: string,
): Promise<T> { ): Promise<T> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
uni.uploadFile({ uni.uploadFile({
@@ -228,6 +242,7 @@ function uploadViaUniMultipart<T>(
resolve, resolve,
reject, reject,
res.errMsg, res.errMsg,
requestPath,
) )
}, },
fail: (err) => { fail: (err) => {
@@ -244,10 +259,13 @@ function uploadViaPlusUploader<T>(
filePath: string, filePath: string,
fieldName: string, fieldName: string,
authMode: UploadAuthMode, authMode: UploadAuthMode,
requestPath: string,
): Promise<T> { ): Promise<T> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (typeof plus === 'undefined' || typeof plus.uploader?.createUpload !== 'function') { if (typeof plus === 'undefined' || typeof plus.uploader?.createUpload !== 'function') {
uploadViaUniMultipart<T>(targetUrl, filePath, fieldName, authMode).then(resolve).catch(reject) uploadViaUniMultipart<T>(targetUrl, filePath, fieldName, authMode, requestPath)
.then(resolve)
.catch(reject)
return return
} }
@@ -260,7 +278,7 @@ function uploadViaPlusUploader<T>(
reject(new ApiError(UPLOAD_NETWORK_ERROR)) reject(new ApiError(UPLOAD_NETWORK_ERROR))
return return
} }
handleUploadSuccess<T>(status, rawData, resolve, reject) handleUploadSuccess<T>(status, rawData, resolve, reject, undefined, requestPath)
}, },
) )
@@ -280,6 +298,7 @@ async function uploadViaFetchH5<T>(
filePath: string, filePath: string,
fieldName: string, fieldName: string,
authMode: UploadAuthMode, authMode: UploadAuthMode,
requestPath: string,
): Promise<T> { ): Promise<T> {
try { try {
const blobRes = await fetch(filePath) const blobRes = await fetch(filePath)
@@ -295,7 +314,7 @@ async function uploadViaFetchH5<T>(
}) })
const rawData = await response.text() const rawData = await response.text()
return await new Promise<T>((resolve, reject) => { return await new Promise<T>((resolve, reject) => {
handleUploadSuccess<T>(response.status, rawData, resolve, reject) handleUploadSuccess<T>(response.status, rawData, resolve, reject, undefined, requestPath)
}) })
} catch (err) { } catch (err) {
const message = err instanceof Error ? err.message : String(err) const message = err instanceof Error ? err.message : String(err)
@@ -308,16 +327,17 @@ async function runUpload<T>(
filePath: string, filePath: string,
fieldName: string, fieldName: string,
authMode: UploadAuthMode, authMode: UploadAuthMode,
requestPath: string,
): Promise<T> { ): Promise<T> {
// #ifdef H5 // #ifdef H5
return uploadViaFetchH5<T>(targetUrl, filePath, fieldName, authMode) return uploadViaFetchH5<T>(targetUrl, filePath, fieldName, authMode, requestPath)
// #endif // #endif
// #ifdef APP-PLUS // #ifdef APP-PLUS
return uploadViaPlusUploader<T>(targetUrl, filePath, fieldName, authMode) return uploadViaPlusUploader<T>(targetUrl, filePath, fieldName, authMode, requestPath)
// #endif // #endif
return uploadViaUniMultipart<T>(targetUrl, filePath, fieldName, authMode) return uploadViaUniMultipart<T>(targetUrl, filePath, fieldName, authMode, requestPath)
} }
/** multipart/form-data 上传;H5 走 fetch 确保 Bearer token 发出 */ /** multipart/form-data 上传;H5 走 fetch 确保 Bearer token 发出 */
@@ -330,11 +350,13 @@ export function uploadAppFile<T>(
const targetUrl = resolveUploadUrl(url) const targetUrl = resolveUploadUrl(url)
const hadCsToken = authMode === 'cs' && !!getStoredCsToken() const hadCsToken = authMode === 'cs' && !!getStoredCsToken()
return runUpload<T>(targetUrl, filePath, fieldName, authMode).catch((err) => { const requestPath = url.startsWith('/') ? url : `/${url}`
return runUpload<T>(targetUrl, filePath, fieldName, authMode, requestPath).catch((err) => {
if (authMode !== 'cs' || !isCsAuthError(err)) throw err if (authMode !== 'cs' || !isCsAuthError(err)) throw err
if (!hadCsToken) throw err if (!hadCsToken) throw err
clearStoredCsToken() clearStoredCsToken()
return runUpload<T>(targetUrl, filePath, fieldName, authMode) return runUpload<T>(targetUrl, filePath, fieldName, authMode, requestPath)
}) })
} }
@@ -343,21 +365,28 @@ function handleSuccess<T>(
resolve: (value: T) => void, resolve: (value: T) => void,
reject: (reason: ApiError) => void, reject: (reason: ApiError) => void,
saveTokenFromBody = false, saveTokenFromBody = false,
requestPath = '',
) { ) {
if (res.statusCode < 200 || res.statusCode >= 300) { if (res.statusCode < 200 || res.statusCode >= 300) {
const body = parseResponseBody(res.data) as ApiResponse | undefined const body = parseResponseBody(res.data) as ApiResponse | undefined
reject( rejectRequestError(
new ApiError( new ApiError(
body?.msg || body?.message || `请求失败(${res.statusCode})`, body?.msg || body?.message || `请求失败(${res.statusCode})`,
body?.code ?? res.statusCode, body?.code ?? res.statusCode,
), ),
requestPath,
reject,
) )
return return
} }
const body = parseResponseBody(res.data) as ApiResponse<T> & Record<string, unknown> const body = parseResponseBody(res.data) as ApiResponse<T> & Record<string, unknown>
if (!isApiSuccess(body)) { if (!isApiSuccess(body)) {
reject(new ApiError(body.msg || body.message || '请求失败', body.code)) rejectRequestError(
new ApiError(body.msg || body.message || '请求失败', body.code),
requestPath,
reject,
)
return return
} }
@@ -375,6 +404,7 @@ function runRequest<T>(
buildHeaders: (extra?: Record<string, unknown>) => Record<string, string>, buildHeaders: (extra?: Record<string, unknown>) => Record<string, string>,
saveTokenFromBody = false, saveTokenFromBody = false,
): Promise<T> { ): Promise<T> {
const requestPath = options.url
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
try { try {
assertRequestUrl(url) assertRequestUrl(url)
@@ -387,7 +417,7 @@ function runRequest<T>(
url, url,
header: buildHeaders(options.header), header: buildHeaders(options.header),
dataType: 'text', dataType: 'text',
success: (res) => handleSuccess<T>(res, resolve, reject, saveTokenFromBody), success: (res) => handleSuccess<T>(res, resolve, reject, saveTokenFromBody, requestPath),
fail: (err) => { fail: (err) => {
reject(new ApiError(normalizeNetworkErrorMessage(err.errMsg))) reject(new ApiError(normalizeNetworkErrorMessage(err.errMsg)))
}, },
@@ -437,7 +467,7 @@ export function requestLogin<T = unknown>(options: RequestOptions): Promise<T> {
url, url,
header: buildAuthHeaders(options.header), header: buildAuthHeaders(options.header),
dataType: 'text', dataType: 'text',
success: (res) => handleSuccess<T>(res, resolve, reject, true), success: (res) => handleSuccess<T>(res, resolve, reject, true, options.url),
fail: (err) => { fail: (err) => {
reject(new ApiError(normalizeNetworkErrorMessage(err.errMsg))) reject(new ApiError(normalizeNetworkErrorMessage(err.errMsg)))
}, },

View File

@@ -35,5 +35,6 @@ const mergedStyle = computed<CSSProperties>(() => props.scrollStyle ?? defaultSc
<style lang="scss" scoped> <style lang="scss" scoped>
.page-scroll-view { .page-scroll-view {
flex-shrink: 0; flex-shrink: 0;
-webkit-overflow-scrolling: touch;
} }
</style> </style>

View File

@@ -0,0 +1,20 @@
import { onShow } from '@dcloudio/uni-app'
/**
* 页面再次显示时执行刷新(从子页返回、切换 Tab 等)。
* skipInitialShow:首屏由 onLoad 加载时设为 true,避免与 onLoad 重复请求。
*/
export function usePageShowRefresh(
handler: () => void | Promise<void>,
options?: { skipInitialShow?: boolean },
) {
let skipFirst = Boolean(options?.skipInitialShow)
onShow(() => {
if (skipFirst) {
skipFirst = false
return
}
void handler()
})
}

View File

@@ -2,7 +2,7 @@
"name" : "虫子智家", "name" : "虫子智家",
"appid" : "__UNI__925D0CC", "appid" : "__UNI__925D0CC",
"description" : "", "description" : "",
"versionName" : "1.1.6", "versionName" : "1.1.9",
"versionCode" : "100", "versionCode" : "100",
"transformPx" : false, "transformPx" : false,
/* 5+App特有相关 */ /* 5+App特有相关 */
@@ -21,8 +21,7 @@
"Bluetooth" : {}, "Bluetooth" : {},
"Camera" : {}, "Camera" : {},
"Push" : {}, "Push" : {},
"Maps" : {}, "Maps" : {}
"Geolocation" : {}
}, },
/* 应用发布信息 */ /* 应用发布信息 */
"distribute" : { "distribute" : {
@@ -41,7 +40,6 @@
"<uses-permission android:name=\"android.permission.READ_LOGS\"/>", "<uses-permission android:name=\"android.permission.READ_LOGS\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_WIFI_STATE\"/>", "<uses-permission android:name=\"android.permission.ACCESS_WIFI_STATE\"/>",
"<uses-feature android:name=\"android.hardware.camera.autofocus\"/>", "<uses-feature android:name=\"android.hardware.camera.autofocus\"/>",
"<uses-permission android:name=\"android.permission.INTERNET\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\"/>", "<uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\"/>",
"<uses-permission android:name=\"android.permission.CAMERA\"/>", "<uses-permission android:name=\"android.permission.CAMERA\"/>",
"<uses-permission android:name=\"android.permission.RECORD_AUDIO\"/>", "<uses-permission android:name=\"android.permission.RECORD_AUDIO\"/>",
@@ -56,11 +54,7 @@
}, },
/* ios打包配置 */ /* ios打包配置 */
"ios" : { "ios" : {
"dSYMs" : false, "dSYMs" : false
"privacyDescription" : {
"NSLocationWhenInUseUsageDescription" : "你的位置信息将用于在地图上选择家庭位置",
"NSLocationAlwaysAndWhenInUseUsageDescription" : "你的位置信息将用于在地图上选择家庭位置"
}
}, },
/* SDK配置 */ /* SDK配置 */
"sdkConfigs" : { "sdkConfigs" : {

View File

@@ -10,7 +10,10 @@ function normalizeProductOption(item: ProductOption): ProductOption {
} }
} }
/** GET /app/device/productOptions — 获取产品型号下拉列表 */ /**
* GET /app/device/productOptions
* 返回所有启用状态的产品型号,供添加设备页下拉选择;无需再传 status。
*/
export function fetchProductOptions() { export function fetchProductOptions() {
return request<ProductOption[]>({ return request<ProductOption[]>({
url: '/app/device/productOptions', url: '/app/device/productOptions',

View File

@@ -1,11 +1,6 @@
/** POST /app/device/productOptions 返回项 */ /** GET /app/device/productOptions — 启用状态产品型号(AppProductOptionVo) */
export interface ProductOption { export interface ProductOption {
productId?: string | number productId?: string | number
model?: string model?: string
name?: string name?: string
category?: string
connectTypes?: string
filterEnabled?: boolean
filterTotalDays?: number
capabilities?: string[]
} }

View File

@@ -4,13 +4,12 @@ import { resolveValidHomeId } from '@/api/home'
import { getErrorMessage } from '@/utils/api-error' import { getErrorMessage } from '@/utils/api-error'
import { fetchRoomList } from '@/api/location' import { fetchRoomList } from '@/api/location'
import type { RoomOption } from '@/types/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 { updateDeviceRuntime } from '@/pages/device/detail/device-detail.api'
import { updateDeviceSettings } from '@/pages/device/settings/device-settings.api' import { updateDeviceSettings } from '@/pages/device/settings/device-settings.api'
import { buildBleDeviceName, isStandardBleDeviceName } from '@/utils/ble-device-name' import { buildBleDeviceName, isStandardBleDeviceName } from '@/utils/ble-device-name'
import { releaseBleDevice } from '@/utils/bluetooth' import { releaseBleDevice } from '@/utils/bluetooth'
import { clearZ2BleHandleCache, sendZ2BleRenameCommand } from '@/utils/z2-ble' import { clearZ2BleHandleCache, sendZ2BleRenameCommand } from '@/utils/z2-ble'
import { getZ2RenameProgressLabel } from '@/utils/z2-ble-protocol'
import { bindDevice } from '../add-device.api' import { bindDevice } from '../add-device.api'
import { parseId, sameId } from '@/utils/device-id' import { parseId, sameId } from '@/utils/device-id'
import { readStoredHomeId, saveSelectedHomeId } from '@/utils/selected-home' import { readStoredHomeId, saveSelectedHomeId } from '@/utils/selected-home'
@@ -22,6 +21,8 @@ export function useCompleteDevice() {
const currentStep = 4 const currentStep = 4
const deviceNo = ref('') const deviceNo = ref('')
const deviceName = ref('Z2 空气净化器') const deviceName = ref('Z2 空气净化器')
/** 配对时读到的 BLE 广播名,与用户可改的云端显示名无关 */
const pairedBleName = ref('')
const serialMasked = ref('****A3B2') const serialMasked = ref('****A3B2')
const productId = ref('') const productId = ref('')
const model = ref('') const model = ref('')
@@ -142,7 +143,10 @@ export function useCompleteDevice() {
function applyQuery(query: Record<string, string | undefined>) { function applyQuery(query: Record<string, string | undefined>) {
const ctx = readBindDeviceContext(query) const ctx = readBindDeviceContext(query)
if (ctx.deviceNo) deviceNo.value = ctx.deviceNo 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 if (ctx.serialMasked) serialMasked.value = ctx.serialMasked
const parsedProductId = parseId(ctx.productId) const parsedProductId = parseId(ctx.productId)
if (parsedProductId) productId.value = parsedProductId if (parsedProductId) productId.value = parsedProductId
@@ -246,23 +250,15 @@ export function useCompleteDevice() {
try { try {
if (bleDeviceId.value && bluetoothConnected.value && mac.value) { if (bleDeviceId.value && bluetoothConnected.value && mac.value) {
const bleName = buildBleDeviceName(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) { if (needRename) {
uni.showLoading({ title: '正在同步蓝牙名称…', mask: true })
try { try {
await sendZ2BleRenameCommand(bleDeviceId.value, bleName, { await sendZ2BleRenameCommand(bleDeviceId.value, bleName, {
timeoutMs: 25000, timeoutMs: 25000,
onProgress: (progress) => {
uni.showLoading({
title: getZ2RenameProgressLabel(progress) || '正在同步蓝牙名称…',
mask: true,
})
},
}) })
} catch { } catch {
// 蓝牙名称同步失败不影响云端绑定,静默继续 // 蓝牙名称同步失败不影响云端绑定,静默继续
} finally {
uni.hideLoading()
} }
} }
} }
@@ -281,7 +277,7 @@ export function useCompleteDevice() {
...(locationId.value ? { locationId: locationId.value } : {}), ...(locationId.value ? { locationId: locationId.value } : {}),
}) })
const list = await fetchDeviceList() const list = await fetchAllDeviceList()
const bound = list?.find((item) => item.deviceNo === deviceNo.value.trim()) const bound = list?.find((item) => item.deviceNo === deviceNo.value.trim())
if (bound?.deviceId != null) { if (bound?.deviceId != null) {
const boundName = bound.name?.trim() const boundName = bound.name?.trim()

View File

@@ -1,38 +1,39 @@
import { onLoad } from '@dcloudio/uni-app' import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue' import { ref } from 'vue'
import { teardownMessageInbox } from '@/hooks/use-message-inbox' import { getErrorMessage } from '@/utils/api-error'
import { ApiError, getErrorMessage } from '@/utils/api-error' import {
import { clearStoredToken } from '@/utils/auth-token' handleAuthSessionExpired,
import { markPasswordModified } from '@/utils/password-modified-at' isAuthSessionExpiredError,
} from '@/utils/auth-session'
import { markPasswordModifiedPendingForPhone } from '@/utils/password-modified-at'
import { isValidStrongPassword, PASSWORD_INVALID_TOAST } from '@/utils/validate' import { isValidStrongPassword, PASSWORD_INVALID_TOAST } from '@/utils/validate'
import { resetPasswordByToken } from './change-password.api' import { resetPasswordByToken } from './change-password.api'
const LOGIN_ROUTE = '/pages/login/index' function redirectToLoginAfterPasswordChange(toastTitle = '密码修改成功,请重新登录') {
handleAuthSessionExpired({
function isSessionInvalidError(err: unknown): boolean { message: toastTitle,
if (!(err instanceof ApiError)) return false forceNavigateToLogin: true,
if (err.code === 401) return true })
return /登录|token|认证|授权/i.test(err.message)
} }
function redirectToLoginAfterPasswordChange(toastTitle = '密码修改成功,请重新登录') { /** 改密后勿再请求 profile,避免 401 触发全局踢登抢占跳转 */
teardownMessageInbox() function recordPasswordModifiedAfterReset(fallbackPhone: string) {
clearStoredToken() if (!fallbackPhone.trim()) return
uni.showToast({ title: toastTitle, icon: 'none' }) markPasswordModifiedPendingForPhone(fallbackPhone)
setTimeout(() => {
uni.reLaunch({ url: LOGIN_ROUTE })
}, 800)
} }
export function useChangePassword() { export function useChangePassword() {
const password = ref('') const password = ref('')
const confirmPassword = ref('') const confirmPassword = ref('')
const resetToken = ref('') const resetToken = ref('')
const boundPhone = ref('')
const loading = ref(false) const loading = ref(false)
onLoad((query) => { onLoad((query) => {
const raw = (query?.resetToken as string) || '' const raw = (query?.resetToken as string) || ''
resetToken.value = raw ? decodeURIComponent(raw) : '' resetToken.value = raw ? decodeURIComponent(raw) : ''
const phoneRaw = (query?.phone as string) || ''
boundPhone.value = phoneRaw ? decodeURIComponent(phoneRaw) : ''
if (!resetToken.value) { if (!resetToken.value) {
uni.showToast({ title: '请先完成验证码校验', icon: 'none' }) uni.showToast({ title: '请先完成验证码校验', icon: 'none' })
setTimeout(() => uni.navigateBack(), 1500) setTimeout(() => uni.navigateBack(), 1500)
@@ -60,11 +61,11 @@ export function useChangePassword() {
newPassword: password.value, newPassword: password.value,
confirmPassword: confirmPassword.value, confirmPassword: confirmPassword.value,
}) })
markPasswordModified() recordPasswordModifiedAfterReset(boundPhone.value)
redirectToLoginAfterPasswordChange() redirectToLoginAfterPasswordChange()
} catch (err) { } catch (err) {
if (isSessionInvalidError(err)) { if (isAuthSessionExpiredError(err)) {
markPasswordModified() recordPasswordModifiedAfterReset(boundPhone.value)
redirectToLoginAfterPasswordChange('登录状态已失效,请使用新密码重新登录') redirectToLoginAfterPasswordChange('登录状态已失效,请使用新密码重新登录')
return return
} }

View File

@@ -21,8 +21,15 @@
v-if="pickerOpen" v-if="pickerOpen"
class="device-header__mask" class="device-header__mask"
@tap="closePicker" @tap="closePicker"
@touchmove.stop.prevent="preventTouchMove"
/> />
<view v-if="pickerOpen" class="device-header__dropdown"> <view v-if="pickerOpen" class="device-header__dropdown">
<scroll-view
class="device-header__dropdown-scroll"
scroll-y
:show-scrollbar="false"
:style="dropdownScrollStyle"
>
<view <view
v-for="home in homes" v-for="home in homes"
:key="String(home.id)" :key="String(home.id)"
@@ -43,6 +50,7 @@
mode="aspectFit" mode="aspectFit"
/> />
</view> </view>
</scroll-view>
<view class="device-header__option device-header__option--manage" @tap.stop="selectManage"> <view class="device-header__option device-header__option--manage" @tap.stop="selectManage">
<text class="device-header__option-text">家庭管理</text> <text class="device-header__option-text">家庭管理</text>
</view> </view>
@@ -79,7 +87,7 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ref } from 'vue' import { computed, ref, watch } from 'vue'
import { hasUnreadMessages } from '@/hooks/use-message-inbox' import { hasUnreadMessages } from '@/hooks/use-message-inbox'
import type { AppHomeVo } from '@/types/location' import type { AppHomeVo } from '@/types/location'
import { parseId, sameId } from '@/utils/device-id' import { parseId, sameId } from '@/utils/device-id'
@@ -97,12 +105,29 @@ const emit = defineEmits<{
scan: [] scan: []
manage: [] manage: []
'select-home': [home: AppHomeVo] 'select-home': [home: AppHomeVo]
'picker-open-change': [open: boolean]
}>() }>()
/** 单行选项约 88rpx,列表最多展示约 8 行高度 */
const DROPDOWN_ITEM_RPX = 88
const DROPDOWN_LIST_MAX_RPX = 704
const dropdownScrollStyle = computed(() => {
const count = Math.max(props.homes.length, 1)
const heightRpx = Math.min(count * DROPDOWN_ITEM_RPX, DROPDOWN_LIST_MAX_RPX)
return { height: `${uni.upx2px(heightRpx)}px` }
})
const pickerOpen = ref(false) const pickerOpen = ref(false)
const addMenuOpen = ref(false) const addMenuOpen = ref(false)
const hasUnreadNotify = hasUnreadMessages const hasUnreadNotify = hasUnreadMessages
watch(pickerOpen, (open) => {
emit('picker-open-change', open)
})
function preventTouchMove() {}
const sys = uni.getSystemInfoSync() const sys = uni.getSystemInfoSync()
const statusBarHeight = sys.statusBarHeight ?? 0 const statusBarHeight = sys.statusBarHeight ?? 0
const headerPaddingTop = const headerPaddingTop =
@@ -225,6 +250,13 @@ function onScan() {
background: #fff; background: #fff;
box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1); box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
z-index: 300; z-index: 300;
display: flex;
flex-direction: column;
}
.device-header__dropdown-scroll {
flex-shrink: 0;
width: 100%;
} }
.device-header__option { .device-header__option {

View File

@@ -153,8 +153,13 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
if (!foundDevice) { if (!foundDevice) {
setSyncText('未找到设备,请确认已开机并靠近手机') setSyncText('未找到设备,请确认已开机并靠近手机')
if (!tearingDown) { if (!tearingDown) {
if (hadSuccessfulSync) {
hadSuccessfulSync = false
void reportBleDisconnected()
} else {
reportBleLinkLostLocal() reportBleLinkLostLocal()
} }
}
return false return false
} }
@@ -184,8 +189,13 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
if (!tearingDown) { if (!tearingDown) {
bleDeviceId.value = undefined bleDeviceId.value = undefined
clearZ2BleHandleCache(targetBleId) clearZ2BleHandleCache(targetBleId)
if (hadSuccessfulSync) {
hadSuccessfulSync = false
void reportBleDisconnected()
} else {
reportBleLinkLostLocal() reportBleLinkLostLocal()
} }
}
return false return false
} finally { } finally {
syncing.value = false syncing.value = false

View File

@@ -1,10 +1,12 @@
import { onLoad } from '@dcloudio/uni-app' import { onLoad } from '@dcloudio/uni-app'
import { usePageShowRefresh } from '@/hooks/use-page-show-refresh'
import { computed, ref } from 'vue' import { computed, ref } from 'vue'
import { fetchRoomList } from '@/api/location' import { fetchRoomList } from '@/api/location'
import { getErrorMessage } from '@/utils/api-error' import { getErrorMessage } from '@/utils/api-error'
import { parseDeviceId, parseId, sameId } from '@/utils/device-id' import { parseDeviceId, parseId, sameId } from '@/utils/device-id'
import { fetchProductOptions } from '@/pages/add-device/complete/complete.api' import { fetchProductOptions } from '@/pages/add-device/complete/complete.api'
import { fetchDeviceList } from '../device.api' import { fetchAllDeviceList } from '../device.api'
import { findPatchedDeviceName } from '../device-list-patch'
import { fetchDeviceRuntime, updateDeviceRuntime } from './device-detail.api' import { fetchDeviceRuntime, updateDeviceRuntime } from './device-detail.api'
import type { AppDeviceRuntimeVo, DeviceDetailRouteQuery, FanLevel, RunMode } from './device-detail.types' import type { AppDeviceRuntimeVo, DeviceDetailRouteQuery, FanLevel, RunMode } from './device-detail.types'
import { import {
@@ -33,6 +35,8 @@ import {
import type { BleRuntimePatch } from './device-bluetooth-read' import type { BleRuntimePatch } from './device-bluetooth-read'
import { useDeviceBluetoothSync } from './use-device-bluetooth-sync' import { useDeviceBluetoothSync } from './use-device-bluetooth-sync'
const DEVICE_CONTROL_WAIT_TOAST = '设备连接中,请稍候'
export function useDeviceDetail() { export function useDeviceDetail() {
const deviceId = ref('') const deviceId = ref('')
const deviceNo = ref('') const deviceNo = ref('')
@@ -156,13 +160,16 @@ export function useDeviceDetail() {
async function refreshDeviceMeta() { async function refreshDeviceMeta() {
if (!deviceId.value) return if (!deviceId.value) return
const bleConnectedLocally = bluetoothConnected.value const bleConnectedLocally = bluetoothConnected.value
const patchedName = findPatchedDeviceName(deviceId.value)
if (patchedName) deviceName.value = patchedName
try { try {
const list = await fetchDeviceList() const list = await fetchAllDeviceList()
const device = list?.find((item) => String(item.deviceId) === deviceId.value) const device = list?.find((item) => String(item.deviceId) === deviceId.value)
if (!device) return if (!device) return
if (device.deviceId != null) deviceId.value = String(device.deviceId) if (device.deviceId != null) deviceId.value = String(device.deviceId)
if (device.deviceNo) deviceNo.value = device.deviceNo if (device.deviceNo) deviceNo.value = device.deviceNo
if (device.mac) deviceMac.value = device.mac if (device.mac) deviceMac.value = device.mac
if (device.name) deviceName.value = device.name
const parsedLocationId = parseId(device.locationId) const parsedLocationId = parseId(device.locationId)
if (parsedLocationId) locationId.value = parsedLocationId if (parsedLocationId) locationId.value = parsedLocationId
const parsedHomeId = parseId(device.homeId) const parsedHomeId = parseId(device.homeId)
@@ -201,10 +208,17 @@ export function useDeviceDetail() {
} }
} }
function promptWaitForDeviceOnline(): boolean {
if (bluetoothConnected.value) return true
uni.showToast({ title: DEVICE_CONTROL_WAIT_TOAST, icon: 'none' })
return false
}
async function patchRuntime(patch: { runMode?: RunMode; fanLevel?: FanLevel }) { async function patchRuntime(patch: { runMode?: RunMode; fanLevel?: FanLevel }) {
if (!deviceId.value) return if (!deviceId.value) return
if (patch.runMode != null && runMode.value === patch.runMode) return if (patch.runMode != null && runMode.value === patch.runMode) return
if (patch.fanLevel != null && fanLevel.value === patch.fanLevel) return if (patch.fanLevel != null && fanLevel.value === patch.fanLevel) return
if (!promptWaitForDeviceOnline()) return
const snapshot = { runMode: runMode.value, fanLevel: fanLevel.value } const snapshot = { runMode: runMode.value, fanLevel: fanLevel.value }
if (patch.runMode != null) runMode.value = patch.runMode if (patch.runMode != null) runMode.value = patch.runMode
@@ -232,7 +246,11 @@ export function useDeviceDetail() {
} catch (err) { } catch (err) {
runMode.value = snapshot.runMode runMode.value = snapshot.runMode
fanLevel.value = snapshot.fanLevel fanLevel.value = snapshot.fanLevel
uni.showToast({ title: getErrorMessage(err, '设置失败'), icon: 'none' }) const fallback = bluetoothConnected.value ? '设置失败' : DEVICE_CONTROL_WAIT_TOAST
const message = bluetoothConnected.value
? getErrorMessage(err, fallback)
: DEVICE_CONTROL_WAIT_TOAST
uni.showToast({ title: message, icon: 'none' })
} }
} }
@@ -271,7 +289,15 @@ export function useDeviceDetail() {
} }
async function onConfirmFilterReplace() { async function onConfirmFilterReplace() {
await sendBleCommand(Z2_BLE_CMD.FILTER_RESET) if (!promptWaitForDeviceOnline()) return
const ok = await sendBleCommand(Z2_BLE_CMD.FILTER_RESET)
if (!ok) {
uni.showToast({
title: bluetoothConnected.value ? '操作失败,请重试' : DEVICE_CONTROL_WAIT_TOAST,
icon: 'none',
})
return
}
filterReplaced.value = true filterReplaced.value = true
filterLife.value = 100 filterLife.value = 100
updateFilterRemainText() updateFilterRemainText()
@@ -328,6 +354,8 @@ export function useDeviceDetail() {
}) })
}) })
usePageShowRefresh(() => refreshDeviceMeta(), { skipInitialShow: true })
return { return {
deviceName, deviceName,
connectionText, connectionText,

View File

@@ -0,0 +1,67 @@
import type { DeviceListItem } from './device.types'
/** 设置页改名等本地补丁:首页列表在接口尚未返回新值时也能立刻展示 */
const namePatches = new Map<string, string>()
export function rememberDeviceNamePatch(deviceId: string | number, name: string) {
const id = String(deviceId).trim()
const trimmed = name.trim()
if (!id || !trimmed) return
namePatches.set(id, trimmed)
}
export function clearDeviceNamePatch(deviceId: string | number) {
namePatches.delete(String(deviceId).trim())
}
export function applyDeviceListPatches(devices: DeviceListItem[]): DeviceListItem[] {
if (!namePatches.size) return devices
return devices.map((device) => {
if (device.deviceId == null) return device
const patched = namePatches.get(String(device.deviceId))
if (!patched) return device
if (device.name === patched) {
namePatches.delete(String(device.deviceId))
return device
}
return { ...device, name: patched }
})
}
/** 在线扫描结果只合并在线相关字段,避免用旧快照整表覆盖名称等元数据 */
export function mergeDevicePresenceFields(
current: DeviceListItem[],
scanned: DeviceListItem[],
): DeviceListItem[] {
if (!scanned.length) return current
const byId = new Map(
scanned
.filter((item) => item.deviceId != null)
.map((item) => [String(item.deviceId), item]),
)
return current.map((device) => {
if (device.deviceId == null) return device
const next = byId.get(String(device.deviceId))
if (!next) return device
if (
device.status === next.status
&& device.bluetoothConnected === next.bluetoothConnected
&& device.isOnline === next.isOnline
) {
return device
}
return {
...device,
status: next.status,
bluetoothConnected: next.bluetoothConnected,
isOnline: next.isOnline,
}
})
}
export function findPatchedDeviceName(
deviceId: string | number | undefined,
): string | undefined {
if (deviceId == null) return undefined
return namePatches.get(String(deviceId))
}

View File

@@ -1,10 +1,12 @@
const missCounts = new Map<string, number>() const missCounts = new Map<string, number>()
const lastSeenAt = new Map<string, number>() const lastSeenAt = new Map<string, number>()
/** 已向云端上报离线的设备,避免轮询重复写库 */
const cloudOfflineReported = new Set<string>()
/** 连续扫描未命中次数达到该值后才判定离线 */ /** 连续扫描未命中次数达到该值后才判定离线 */
const OFFLINE_AFTER_MISSES = 2 const OFFLINE_AFTER_MISSES = 2
/** 最近一次 BLE 命中后的宽限期(避免切换页面时瞬时扫不到) */ /** 最近一次 BLE 命中后的宽限期(避免切换页面时瞬时扫不到) */
const ONLINE_GRACE_MS = 45_000 const ONLINE_GRACE_MS = 25_000
function deviceKey(deviceId: string | number | undefined): string { function deviceKey(deviceId: string | number | undefined): string {
return deviceId != null ? String(deviceId) : '' return deviceId != null ? String(deviceId) : ''
@@ -15,6 +17,7 @@ export function recordPresenceHit(deviceId: string | number) {
if (!key) return if (!key) return
missCounts.set(key, 0) missCounts.set(key, 0)
lastSeenAt.set(key, Date.now()) lastSeenAt.set(key, Date.now())
cloudOfflineReported.delete(key)
} }
export function recordPresenceMiss(deviceId: string | number) { export function recordPresenceMiss(deviceId: string | number) {
@@ -44,9 +47,23 @@ export function resetPresenceState(deviceId?: string | number) {
if (deviceId == null) { if (deviceId == null) {
missCounts.clear() missCounts.clear()
lastSeenAt.clear() lastSeenAt.clear()
cloudOfflineReported.clear()
return return
} }
const key = deviceKey(deviceId) const key = deviceKey(deviceId)
missCounts.delete(key) missCounts.delete(key)
lastSeenAt.delete(key) lastSeenAt.delete(key)
cloudOfflineReported.delete(key)
}
export function shouldReportPresenceOfflineToCloud(deviceId: string | number): boolean {
const key = deviceKey(deviceId)
if (!key) return false
return !cloudOfflineReported.has(key)
}
export function markPresenceOfflineReportedToCloud(deviceId: string | number) {
const key = deviceKey(deviceId)
if (!key) return
cloudOfflineReported.add(key)
} }

View File

@@ -6,9 +6,11 @@ import {
} from '@/utils/bluetooth' } from '@/utils/bluetooth'
import { sameId } from '@/utils/device-id' import { sameId } from '@/utils/device-id'
import { import {
markPresenceOfflineReportedToCloud,
recordPresenceHit, recordPresenceHit,
recordPresenceMiss, recordPresenceMiss,
shouldMarkDeviceOffline, shouldMarkDeviceOffline,
shouldReportPresenceOfflineToCloud,
} from './device-presence-state' } from './device-presence-state'
import { updateDeviceRuntime } from './detail/device-detail.api' import { updateDeviceRuntime } from './detail/device-detail.api'
import type { DeviceListItem } from './device.types' import type { DeviceListItem } from './device.types'
@@ -29,6 +31,10 @@ function logPresence(message: string, payload?: unknown) {
console.log(`[Device Presence] ${message}`) console.log(`[Device Presence] ${message}`)
} }
function wasDeviceOnlineInCloud(device: DeviceListItem): boolean {
return device.status === '1' && device.bluetoothConnected === '1'
}
function applyPresence( function applyPresence(
device: DeviceListItem, device: DeviceListItem,
blePresent: boolean, blePresent: boolean,
@@ -58,7 +64,6 @@ function applyPresence(
} }
} }
/** 列表页仅上报「确认在线」,不因单次扫描未命中把云端写成离线 */
async function reportPresenceOnlineToCloud(device: DeviceListItem) { async function reportPresenceOnlineToCloud(device: DeviceListItem) {
if (!device.deviceId) return if (!device.deviceId) return
if (device.status === '1' && device.bluetoothConnected === '1') return if (device.status === '1' && device.bluetoothConnected === '1') return
@@ -69,10 +74,35 @@ async function reportPresenceOnlineToCloud(device: DeviceListItem) {
bluetoothConnected: '1', bluetoothConnected: '1',
}) })
} catch (err) { } catch (err) {
logPresence('updateRuntime failed', err) logPresence('online updateRuntime failed', err)
} }
} }
async function reportPresenceOfflineToCloud(device: DeviceListItem) {
if (!device.deviceId) return
if (!shouldReportPresenceOfflineToCloud(device.deviceId)) return
try {
await updateDeviceRuntime({
deviceId: device.deviceId,
status: '2',
bluetoothConnected: '0',
signalLevel: '0',
})
markPresenceOfflineReportedToCloud(device.deviceId)
logPresence('reported offline to cloud', { deviceId: device.deviceId })
} catch (err) {
logPresence('offline updateRuntime failed', err)
}
}
function shouldSyncOfflineToCloud(before: DeviceListItem, after: DeviceListItem): boolean {
if (!after.deviceId) return false
if (after.status !== '2' || after.bluetoothConnected !== '0') return false
if (!after.isOnline && before.isOnline) return true
if (wasDeviceOnlineInCloud(before) && !wasDeviceOnlineInCloud(after)) return true
return false
}
/** 通过 BLE 扫描刷新设备在线状态(仅 MAC 精确匹配,不用缓存广播) */ /** 通过 BLE 扫描刷新设备在线状态(仅 MAC 精确匹配,不用缓存广播) */
export async function refreshDevicePresence( export async function refreshDevicePresence(
devices: DeviceListItem[], devices: DeviceListItem[],
@@ -95,6 +125,8 @@ export async function refreshDevicePresence(
names: scanned.map((item) => item.name || item.localName || item.deviceId), names: scanned.map((item) => item.name || item.localName || item.deviceId),
}) })
const offlineReports: DeviceListItem[] = []
const nextDevices = devices.map((device) => { const nextDevices = devices.map((device) => {
if (!device.deviceId) return device if (!device.deviceId) return device
const isTarget = targets.some((item) => sameId(item.deviceId, device.deviceId)) const isTarget = targets.some((item) => sameId(item.deviceId, device.deviceId))
@@ -111,7 +143,11 @@ export async function refreshDevicePresence(
foundId: found?.deviceId, foundId: found?.deviceId,
bleName: device.mac ? buildBleDeviceName(device.mac) : '', bleName: device.mac ? buildBleDeviceName(device.mac) : '',
}) })
return applyPresence(device, present) const next = applyPresence(device, present)
if (shouldSyncOfflineToCloud(device, next)) {
offlineReports.push(next)
}
return next
}) })
void Promise.allSettled( void Promise.allSettled(
@@ -125,6 +161,8 @@ export async function refreshDevicePresence(
}), }),
) )
void Promise.allSettled(offlineReports.map((device) => reportPresenceOfflineToCloud(device)))
return nextDevices return nextDevices
} catch (err) { } catch (err) {
logPresence('scan failed', err) logPresence('scan failed', err)

View File

@@ -1,7 +1,7 @@
import { request } from '@/api/request' import { request } from '@/api/request'
import type { AppDeviceVo, DeviceQueryBody } from './device.types' import type { AppDeviceVo, DeviceQueryBody } from './device.types'
/** POST /app/device/list — 查询当前用户的设备列表 */ /** POST /app/device/list — 按家庭/房间查询设备(首页设备 Tab 等) */
export function fetchDeviceList(query: DeviceQueryBody = {}) { export function fetchDeviceList(query: DeviceQueryBody = {}) {
return request<AppDeviceVo[]>({ return request<AppDeviceVo[]>({
url: '/app/device/list', url: '/app/device/list',
@@ -9,3 +9,12 @@ export function fetchDeviceList(query: DeviceQueryBody = {}) {
data: query, data: query,
}) })
} }
/** POST /app/device/listAll — 当前用户绑定的全部设备(选择设备、我的设备等跨家庭场景) */
export function fetchAllDeviceList() {
return request<AppDeviceVo[]>({
url: '/app/device/listAll',
method: 'GET',
data: {},
})
}

View File

@@ -6,6 +6,11 @@
overflow-x: hidden; overflow-x: hidden;
} }
.device-page--scroll-lock {
overflow: hidden;
height: 100vh;
}
.device-page__loading { .device-page__loading {
display: flex; display: flex;
align-items: center; align-items: center;

View File

@@ -10,12 +10,14 @@ export interface HotDeviceItem {
desc: string desc: string
} }
/** POST /app/device/list 查询参数 */ /** POST /app/device/list 查询参数(按家庭/房间筛选) */
export interface DeviceQueryBody { export interface DeviceQueryBody {
homeId?: string | number homeId?: string | number
locationId?: string | number locationId?: string | number
} }
/** POST /app/device/listAll — 无筛选参数,返回当前用户全部绑定设备 */
/** 设备状态:0未激活 1在线 2离线 */ /** 设备状态:0未激活 1在线 2离线 */
export type DeviceStatus = '0' | '1' | '2' export type DeviceStatus = '0' | '1' | '2'

View File

@@ -1,5 +1,5 @@
<template> <template>
<view class="device-page"> <view class="device-page" :class="{ 'device-page--scroll-lock': homePickerOpen }">
<device-header <device-header
:home-name="homeName" :home-name="homeName"
:home-id="homeId" :home-id="homeId"
@@ -9,6 +9,7 @@
@notify="onNotify" @notify="onNotify"
@add-device="onStartBind" @add-device="onStartBind"
@scan="onScan" @scan="onScan"
@picker-open-change="homePickerOpen = $event"
/> />
<room-tabs <room-tabs
:rooms="rooms" :rooms="rooms"
@@ -43,6 +44,7 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ref } from 'vue'
import { useTabPage } from '@/hooks/use-tab-page' import { useTabPage } from '@/hooks/use-tab-page'
import DeviceEmpty from './components/device-empty/index.vue' import DeviceEmpty from './components/device-empty/index.vue'
import DeviceHeader from './components/device-header/index.vue' import DeviceHeader from './components/device-header/index.vue'
@@ -54,6 +56,7 @@ import RoomTabs from './components/room-tabs/index.vue'
import { useDevice } from './use-device' import { useDevice } from './use-device'
const { tabCurrent } = useTabPage('device') const { tabCurrent } = useTabPage('device')
const homePickerOpen = ref(false)
const { const {
homeName, homeName,

View File

@@ -2,15 +2,16 @@ import { onLoad } from '@dcloudio/uni-app'
import { computed, ref } from 'vue' import { computed, ref } from 'vue'
import { usePageShowRefresh } from '@/hooks/use-page-show-refresh'
import { getErrorMessage } from '@/utils/api-error' import { getErrorMessage } from '@/utils/api-error'
import { resolveValidHomeId } from '@/api/home' import { resolveValidHomeId } from '@/api/home'
import { isValidDeviceId, parseDeviceId, parseId } from '@/utils/device-id' import { fetchRoomList } from '@/api/location'
import { isValidDeviceId, parseDeviceId, parseId, sameId } from '@/utils/device-id'
import { fetchDeviceList } from '../device.api'
import { fetchAllDeviceList } from '../device.api'
import { rememberDeviceNamePatch } from '../device-list-patch'
import { isBluetoothConnected } from '../detail/device-detail.utils' import { isBluetoothConnected } from '../detail/device-detail.utils'
import { unbindDevice, updateDeviceSettings } from './device-settings.api' import { unbindDevice, updateDeviceSettings } from './device-settings.api'
import type { DeviceSettingsRouteQuery } from './device-settings.types' import type { DeviceSettingsRouteQuery } from './device-settings.types'
@@ -87,7 +88,7 @@ export function useDeviceSettings() {
async function syncDeviceFromList() { async function syncDeviceFromList() {
const list = await fetchDeviceList() const list = await fetchAllDeviceList()
const device = list?.find((item) => { const device = list?.find((item) => {
@@ -121,6 +122,16 @@ export function useDeviceSettings() {
const parsedLocationId = parseId(device.locationId) const parsedLocationId = parseId(device.locationId)
if (parsedLocationId) locationId.value = parsedLocationId if (parsedLocationId) locationId.value = parsedLocationId
if (parsedHomeId && parsedLocationId) {
try {
const locations = await fetchRoomList(parsedHomeId)
const matched = locations.find((item) => sameId(item.locationId, parsedLocationId))
if (matched?.name) locationName.value = matched.name
} catch {
// 房间列表失败时保留当前展示
}
}
return true return true
} }
@@ -233,6 +244,7 @@ export function useDeviceSettings() {
await updateDeviceSettings({ deviceId: deviceId.value, name: trimmed }) await updateDeviceSettings({ deviceId: deviceId.value, name: trimmed })
deviceName.value = trimmed deviceName.value = trimmed
rememberDeviceNamePatch(deviceId.value, trimmed)
uni.showToast({ title: '修改成功', icon: 'success' }) uni.showToast({ title: '修改成功', icon: 'success' })
@@ -302,18 +314,17 @@ export function useDeviceSettings() {
onLoad((query?: DeviceSettingsRouteQuery) => { async function reloadFromServer() {
applyQuery(query)
void (async () => {
await syncDeviceFromList() await syncDeviceFromList()
homeId.value = await resolveValidHomeId(homeId.value) homeId.value = await resolveValidHomeId(homeId.value)
})() }
onLoad((query?: DeviceSettingsRouteQuery) => {
applyQuery(query)
void reloadFromServer()
}) })
usePageShowRefresh(() => reloadFromServer(), { skipInitialShow: true })
return { return {

View File

@@ -19,6 +19,10 @@ import type { DeviceListItem, HotDeviceItem, RoomTab } from './device.types'
import type { LocationMap } from './device.utils' import type { LocationMap } from './device.utils'
import { readStoredHomeId, saveSelectedHomeId } from '@/utils/selected-home' import { readStoredHomeId, saveSelectedHomeId } from '@/utils/selected-home'
import { refreshDevicePresence } from './device-presence' import { refreshDevicePresence } from './device-presence'
import {
applyDeviceListPatches,
mergeDevicePresenceFields,
} from './device-list-patch'
import { import {
buildRoomTabs, buildRoomTabs,
countOnlineDevices, countOnlineDevices,
@@ -119,6 +123,12 @@ export function useDevice() {
applyCurrentHome(homes.value) applyCurrentHome(homes.value)
} }
let presenceEpoch = 0
function commitDevices(next: DeviceListItem[]) {
devices.value = applyDeviceListPatches(next)
}
async function loadDevicesForHome(targetHomeId?: string) { async function loadDevicesForHome(targetHomeId?: string) {
if (targetHomeId) homeId.value = targetHomeId if (targetHomeId) homeId.value = targetHomeId
if (!homeId.value) { if (!homeId.value) {
@@ -130,19 +140,24 @@ export function useDevice() {
const list = await fetchDeviceList({ homeId: homeId.value }) ?? [] const list = await fetchDeviceList({ homeId: homeId.value }) ?? []
applyRoomTabs(locationMap) applyRoomTabs(locationMap)
const mapped = list.map((item) => mapDeviceItem(item, locationMap)) const mapped = list.map((item) => mapDeviceItem(item, locationMap))
devices.value = await refreshDevicePresence(mapped) // 先写入接口数据(含最新名称),再异步合并在线状态,避免 BLE 扫描旧快照覆盖改名
commitDevices(mapped)
const epoch = ++presenceEpoch
const presence = await refreshDevicePresence(mapped)
if (epoch !== presenceEpoch) return
commitDevices(mergeDevicePresenceFields(devices.value, presence))
} }
async function loadDevices() { async function loadDevices(silent = false) {
if (loading.value) return if (loading.value) return
loading.value = true if (!silent) loading.value = true
try { try {
await loadHomeList() await loadHomeList()
await loadDevicesForHome() await loadDevicesForHome()
} catch (err) { } catch (err) {
uni.showToast({ title: getErrorMessage(err, '加载设备失败'), icon: 'none' }) uni.showToast({ title: getErrorMessage(err, '加载设备失败'), icon: 'none' })
} finally { } finally {
loading.value = false if (!silent) loading.value = false
} }
} }
@@ -167,7 +182,11 @@ export function useDevice() {
async function refreshPresenceOnly() { async function refreshPresenceOnly() {
if (!devices.value.length || loading.value) return if (!devices.value.length || loading.value) return
devices.value = await refreshDevicePresence(devices.value) const snapshot = devices.value
const epoch = ++presenceEpoch
const presence = await refreshDevicePresence(snapshot)
if (epoch !== presenceEpoch) return
commitDevices(mergeDevicePresenceFields(devices.value, presence))
} }
function startPresencePolling() { function startPresencePolling() {
@@ -187,11 +206,7 @@ export function useDevice() {
uni.reLaunch({ url: '/pages/login/index' }) uni.reLaunch({ url: '/pages/login/index' })
return return
} }
if (devices.value.length) { void loadDevices(devices.value.length > 0)
void refreshPresenceOnly()
} else {
void loadDevices()
}
void refreshUnreadMessageCount() void refreshUnreadMessageCount()
startPresencePolling() startPresencePolling()
}) })

View File

@@ -57,7 +57,7 @@ export function useForgotPassword() {
return return
} }
uni.navigateTo({ uni.navigateTo({
url: `/pages/change-password/index?resetToken=${encodeURIComponent(res.resetToken)}&from=${fromPrivacy.value ? 'privacy' : 'login'}`, url: `/pages/change-password/index?resetToken=${encodeURIComponent(res.resetToken)}&phone=${encodeURIComponent(phone.value)}&from=${fromPrivacy.value ? 'privacy' : 'login'}`,
}) })
} catch (err) { } catch (err) {
uni.showToast({ title: getErrorMessage(err, '验证失败,请重试'), icon: 'none' }) uni.showToast({ title: getErrorMessage(err, '验证失败,请重试'), icon: 'none' })

View File

@@ -1,10 +1,16 @@
import { onShow } from '@dcloudio/uni-app' import { onShow } from '@dcloudio/uni-app'
import { ref } from 'vue' import { ref } from 'vue'
import { useSmsCode } from '@/hooks/use-sms-code' import { useSmsCode } from '@/hooks/use-sms-code'
import { isValidPassword, isValidPhone, isValidSmsCode } from '@/utils/validate' import {
isValidPassword,
isValidPhone,
isValidSmsCode,
LOGIN_PASSWORD_EMPTY_TOAST,
} from '@/utils/validate'
import { getErrorMessage } from '@/utils/api-error' import { getErrorMessage } from '@/utils/api-error'
import { setupMessageInbox } from '@/hooks/use-message-inbox' import { setupMessageInbox } from '@/hooks/use-message-inbox'
import { getStoredToken } from '@/utils/auth-token' import { getStoredToken } from '@/utils/auth-token'
import { clearLocalUserDataPreservingAuth } from '@/utils/clear-local-user-data'
import { SMS_CODE_SCENE } from '@/types/api' import { SMS_CODE_SCENE } from '@/types/api'
import { syncCsAuthByPassword, syncCsAuthBySms } from '@/api/cs-auth' import { syncCsAuthByPassword, syncCsAuthBySms } from '@/api/cs-auth'
import { loginByPassword, loginBySms } from './login.api' import { loginByPassword, loginBySms } from './login.api'
@@ -54,6 +60,10 @@ export function useLogin() {
uni.showToast({ title: '请输入账号', icon: 'none' }) uni.showToast({ title: '请输入账号', icon: 'none' })
return return
} }
if (!password.value.trim()) {
uni.showToast({ title: LOGIN_PASSWORD_EMPTY_TOAST, icon: 'none' })
return
}
if (!isValidPassword(password.value)) { if (!isValidPassword(password.value)) {
uni.showToast({ title: '密码至少 6 位', icon: 'none' }) uni.showToast({ title: '密码至少 6 位', icon: 'none' })
return return
@@ -68,6 +78,7 @@ export function useLogin() {
uni.showToast({ title: '登录失败,未获取到令牌', icon: 'none' }) uni.showToast({ title: '登录失败,未获取到令牌', icon: 'none' })
return return
} }
clearLocalUserDataPreservingAuth()
setupMessageInbox() setupMessageInbox()
uni.showToast({ title: '登录成功', icon: 'success' }) uni.showToast({ title: '登录成功', icon: 'success' })
uni.reLaunch({ url: '/pages/device/index' }) uni.reLaunch({ url: '/pages/device/index' })

View File

@@ -1,15 +1,17 @@
import { onLoad } from '@dcloudio/uni-app' import { onLoad, onShow } from '@dcloudio/uni-app'
import { ref } from 'vue' import { ref } from 'vue'
import { fetchProfile } from '@/api/profile'
import { useSmsCode } from '@/hooks/use-sms-code' import { useSmsCode } from '@/hooks/use-sms-code'
import { SMS_CODE_SCENE } from '@/types/api' import { SMS_CODE_SCENE } from '@/types/api'
import { getErrorMessage } from '@/utils/api-error' import { getErrorMessage } from '@/utils/api-error'
import { isValidPhone, isValidSmsCode } from '@/utils/validate' import { isSamePhone, isValidPhone, isValidSmsCode } from '@/utils/validate'
import { verifyNewPhone } from '../change-phone.api' import { verifyNewPhone } from '../change-phone.api'
export function useChangePhoneBind() { export function useChangePhoneBind() {
const phone = ref('') const phone = ref('')
const code = ref('') const code = ref('')
const changeToken = ref('') const changeToken = ref('')
const boundPhone = 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, {
@@ -28,7 +30,30 @@ export function useChangePhoneBind() {
} }
}) })
async function loadBoundPhone() {
try {
const profile = await fetchProfile()
boundPhone.value = profile?.phonenumber || profile?.userName || ''
} catch {
// 新号校验依赖当前绑定号;加载失败时仍走格式校验
}
}
function ensureNewPhoneDiffersFromBound(): boolean {
if (!isValidPhone(phone.value)) {
uni.showToast({ title: '请输入正确手机号', icon: 'none' })
return false
}
const bound = boundPhone.value.trim()
if (bound && isSamePhone(phone.value, bound)) {
uni.showToast({ title: '新手机号不能与当前手机号相同', icon: 'none' })
return false
}
return true
}
function onSendCode() { function onSendCode() {
if (!ensureNewPhoneDiffersFromBound()) return
sendCode(phone.value) sendCode(phone.value)
} }
@@ -37,10 +62,7 @@ export function useChangePhoneBind() {
uni.showToast({ title: '换绑令牌无效,请重新验证', icon: 'none' }) uni.showToast({ title: '换绑令牌无效,请重新验证', icon: 'none' })
return return
} }
if (!isValidPhone(phone.value)) { if (!ensureNewPhoneDiffersFromBound()) return
uni.showToast({ title: '请输入正确手机号', icon: 'none' })
return
}
if (!isValidSmsCode(code.value)) { if (!isValidSmsCode(code.value)) {
uni.showToast({ title: '请输入验证码', icon: 'none' }) uni.showToast({ title: '请输入验证码', icon: 'none' })
return return
@@ -61,6 +83,10 @@ export function useChangePhoneBind() {
} }
} }
onShow(() => {
void loadBoundPhone()
})
return { return {
phone, phone,
code, code,

View File

@@ -33,17 +33,6 @@
margin-top: 16rpx; margin-top: 16rpx;
} }
.change-phone-page__link-row {
display: flex;
justify-content: flex-end;
margin-top: 24rpx;
}
.change-phone-page__link {
font-size: 26rpx;
color: $color-primary;
}
.change-phone-page__form :deep(.base-input) { .change-phone-page__form :deep(.base-input) {
border: none; border: none;
box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04); box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);

View File

@@ -17,10 +17,6 @@
<view class="change-phone-page__btn"> <view class="change-phone-page__btn">
<primary-button text="下一步" @click="nextStep" /> <primary-button text="下一步" @click="nextStep" />
</view> </view>
<view class="change-phone-page__link-row">
<text class="change-phone-page__link" @tap="onUnavailablePhone">原手机号码已不可用?</text>
</view>
</view> </view>
</view> </view>
</template> </template>
@@ -28,8 +24,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { useChangePhoneVerify } from './use-change-phone-verify' import { useChangePhoneVerify } from './use-change-phone-verify'
const { phone, code, counting, seconds, subtitle, onSendCode, onUnavailablePhone, nextStep } = const { phone, code, counting, seconds, subtitle, onSendCode, nextStep } = useChangePhoneVerify()
useChangePhoneVerify()
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>

View File

@@ -4,11 +4,11 @@ import { fetchProfile } from '@/api/profile'
import { useSmsCode } from '@/hooks/use-sms-code' import { useSmsCode } from '@/hooks/use-sms-code'
import { SMS_CODE_SCENE } from '@/types/api' import { SMS_CODE_SCENE } from '@/types/api'
import { getErrorMessage } from '@/utils/api-error' import { getErrorMessage } from '@/utils/api-error'
import { isValidPhone, isValidSmsCode } from '@/utils/validate' import { isSamePhone, isValidPhone, isValidSmsCode, normalizePhoneDigits } from '@/utils/validate'
import { verifyOldPhone } from './change-phone.api' import { verifyOldPhone } from './change-phone.api'
function maskPhone(phone: string): string { function maskPhone(phone: string): string {
const digits = phone.replace(/\D/g, '') const digits = normalizePhoneDigits(phone)
if (digits.length < 7) return phone if (digits.length < 7) return phone
return digits.replace(/(\d{3})\d{4}(\d+)/, '$1****$2') return digits.replace(/(\d{3})\d{4}(\d+)/, '$1****$2')
} }
@@ -38,27 +38,31 @@ export function useChangePhoneVerify() {
} }
} }
function ensureInputMatchesBoundPhone(): boolean {
const bound = boundPhone.value.trim()
if (!bound) {
uni.showToast({ title: '正在加载账号手机号,请稍后', icon: 'none' })
void loadBoundPhone()
return false
}
if (!isValidPhone(phone.value)) {
uni.showToast({ title: '请输入正确手机号', icon: 'none' })
return false
}
if (!isSamePhone(phone.value, bound)) {
uni.showToast({ title: '请输入当前账号绑定的原手机号', icon: 'none' })
return false
}
return true
}
function onSendCode() { function onSendCode() {
if (!ensureInputMatchesBoundPhone()) return
sendCode(phone.value) sendCode(phone.value)
} }
function onUnavailablePhone() {
uni.showModal({
title: '原手机号不可用',
content: '如原手机号已停用,请联系在线客服协助处理。',
confirmText: '联系客服',
success: (res) => {
if (!res.confirm) return
uni.navigateTo({ url: '/pages/mine/support/index' })
},
})
}
async function nextStep() { async function nextStep() {
if (!isValidPhone(phone.value)) { if (!ensureInputMatchesBoundPhone()) return
uni.showToast({ title: '请输入正确手机号', icon: 'none' })
return
}
if (!isValidSmsCode(code.value)) { if (!isValidSmsCode(code.value)) {
uni.showToast({ title: '请输入验证码', icon: 'none' }) uni.showToast({ title: '请输入验证码', icon: 'none' })
return return
@@ -93,7 +97,6 @@ export function useChangePhoneVerify() {
seconds, seconds,
subtitle, subtitle,
onSendCode, onSendCode,
onUnavailablePhone,
nextStep, nextStep,
} }
} }

View File

@@ -1,13 +1,29 @@
import { resolveValidHomeId } from '@/api/home'
import { fetchProfile } from '@/api/profile' import { fetchProfile } from '@/api/profile'
import { fetchDeviceList } from '../device/device.api' import { fetchAllDeviceList, fetchDeviceList } from '../device/device.api'
async function fetchDeviceCountForMine(): Promise<number> {
try {
const devices = await fetchAllDeviceList()
return devices?.length ?? 0
} catch {
try {
const homeId = await resolveValidHomeId()
if (!homeId) return 0
const devices = await fetchDeviceList({ homeId })
return devices?.length ?? 0
} catch {
return 0
}
}
}
/** 我的页概览:资料与设备数分开拉取,避免 listAll 失败导致头像昵称不展示 */
export async function fetchMineOverview() { export async function fetchMineOverview() {
const [profile, devices] = await Promise.all([ const profile = await fetchProfile()
fetchProfile(), const deviceCount = await fetchDeviceCountForMine()
fetchDeviceList(),
])
return { return {
profile, profile,
deviceCount: devices?.length ?? 0, deviceCount,
} }
} }

View File

@@ -1,38 +1,90 @@
<template> <template>
<view class="notify-page"> <view class="notify-page">
<app-navbar title="通知"> <view class="notify-page__top">
<template #right> <app-navbar title="通知" />
<view class="notify-page__mark-all" @tap="onMarkAllRead">
<text class="notify-page__mark-all-text">全部已读</text> <view class="notify-page__filter-wrap">
<view class="notify-page__filter" @tap.stop="toggleHomePicker">
<text class="notify-page__filter-text">{{ selectedHomeLabel }}</text>
<image
class="notify-page__filter-arrow"
:class="{ 'notify-page__filter-arrow--open': homePickerOpen }"
:src="staticAssets.iconNotifyFilterArrow"
mode="aspectFit"
/>
</view>
<view
v-if="homePickerOpen"
class="notify-page__picker-mask"
@tap="closeHomePicker"
@touchmove.stop.prevent
/>
<view v-if="homePickerOpen" class="notify-page__picker" @tap.stop>
<view
class="notify-page__picker-item"
:class="{ 'notify-page__picker-item--active': !selectedHomeId }"
@tap="onSelectHome(allHomesId)"
>
<text>全部家庭</text>
</view>
<view
v-for="home in homes"
:key="String(home.id)"
class="notify-page__picker-item"
:class="{ 'notify-page__picker-item--active': isHomeOptionActive(home) }"
@tap="onSelectHome(parseHomeId(home) || '')"
>
<text>{{ home.homeName || '我的家' }}</text>
</view>
</view>
</view>
</view> </view>
</template>
</app-navbar>
<page-scroll-view <page-scroll-view
class="notify-page__scroll" class="notify-page__scroll"
top-selector=".notify-page__top"
refresher-enabled refresher-enabled
:refresher-triggered="loading" :refresher-triggered="refreshing"
:lower-threshold="120"
@refresherrefresh="onRefresh" @refresherrefresh="onRefresh"
@scrolltolower="onLoadMore" @scrolltolower="onLoadMore"
> >
<view class="notify-page__body"> <view class="notify-page__body">
<text class="notify-page__section">{{ sectionTitle }}</text> <view class="notify-page__card">
<view class="notify-page__card-head">
<text class="notify-page__unread">{{ unreadCountText }}</text>
<view class="notify-page__mark-all" @tap="onMarkAllRead">
<text class="notify-page__mark-all-text">全部已读</text>
</view>
</view>
<view v-if="messages.length" class="notify-page__list"> <view v-if="messageRows.length" class="notify-page__list">
<view <view
v-for="item in messages" v-for="row in messageRows"
:key="normalizeId(item)" :key="row.id"
class="notify-page__item" class="notify-page__item"
@tap="onItemTap(item)" @tap="onItemTap(row.raw)"
> >
<view class="notify-page__thumb-wrap">
<view
class="notify-page__thumb"
:style="{ backgroundImage: `url(${staticAssets.logo})` }"
/>
<view v-if="row.unread" class="notify-page__thumb-dot" />
</view>
<view class="notify-page__item-main">
<view class="notify-page__item-head"> <view class="notify-page__item-head">
<view class="notify-page__title-wrap"> <view class="notify-page__title-wrap">
<view v-if="isUnreadMessage(item)" class="notify-page__dot" /> <text class="notify-page__title">{{ row.title }}</text>
<text class="notify-page__title">{{ item.title || '系统通知' }}</text>
</view> </view>
<text class="notify-page__time">{{ formatNotifyTime(item) }}</text> <text class="notify-page__time">{{ row.timeText }}</text>
</view>
<text v-if="row.locationText" class="notify-page__location">
{{ row.locationText }}
</text>
<text class="notify-page__content">{{ row.content }}</text>
</view> </view>
<text class="notify-page__content">{{ item.content || '暂无详情' }}</text>
</view> </view>
</view> </view>
@@ -40,38 +92,44 @@
暂无通知消息 暂无通知消息
</view> </view>
<view v-if="loading && !messages.length" class="notify-page__loading"> <view v-if="loading && !messageRows.length" class="notify-page__loading">
加载中... 加载中...
</view> </view>
<view v-else-if="messages.length && !hasMore" class="notify-page__footer-tip"> <view v-else-if="messageRows.length && !hasMore" class="notify-page__footer-tip">
没有更多了 没有更多了
</view> </view>
</view>
</view> </view>
</page-scroll-view> </page-scroll-view>
</view> </view>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import type { AppMessageVo } from '@/types/message' import { staticAssets } from '@/utils/static-assets'
import { formatNotifyTime, isUnreadMessage, normalizeMessageId } from './notify.utils'
import { useNotify } from './use-notify' import { useNotify } from './use-notify'
const { const {
messages, messageRows,
homes,
selectedHomeId,
selectedHomeLabel,
homePickerOpen,
unreadCountText,
loading, loading,
refreshing,
hasMore, hasMore,
sectionTitle, toggleHomePicker,
closeHomePicker,
onSelectHome,
isHomeOptionActive,
onRefresh, onRefresh,
onLoadMore, onLoadMore,
onItemTap, onItemTap,
onMarkAllRead, onMarkAllRead,
allHomesId,
parseHomeId,
} = useNotify() } = useNotify()
function normalizeId(item: AppMessageVo) {
return normalizeMessageId(item) || `${item.title}-${item.timestamp}`
}
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>

View File

@@ -1,24 +1,111 @@
.notify-page { .notify-page {
min-height: 100vh; height: 100vh;
background: #fff; background: #f7f8fa;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
overflow: hidden;
}
.notify-page__top {
flex-shrink: 0;
} }
.notify-page__scroll { .notify-page__scroll {
width: 100%; width: 100%;
flex: 1;
min-height: 0;
} }
.notify-page__body { .notify-page__body {
min-height: 100%; min-height: 100%;
padding: 0 24rpx 32rpx;
} }
.notify-page__section { .notify-page__filter-wrap {
display: block; position: relative;
padding: 16rpx 32rpx 8rpx; z-index: 30;
padding: 8rpx 32rpx 16rpx;
background: #f7f8fa;
}
.notify-page__filter {
display: inline-flex;
align-items: center;
gap: 8rpx;
}
.notify-page__filter-text {
font-size: 30rpx;
font-weight: 600;
color: #1a1a1a;
}
.notify-page__filter-arrow {
width: 24rpx;
height: 24rpx;
flex-shrink: 0;
transition: transform 0.2s ease;
&--open {
transform: rotate(180deg);
}
}
.notify-page__picker-mask {
position: fixed;
inset: 0;
z-index: 40;
background: transparent;
}
.notify-page__picker {
position: absolute;
left: 24rpx;
right: 24rpx;
top: 100%;
margin-top: 8rpx;
z-index: 50;
background: #fff;
border-radius: 16rpx;
box-shadow: 0 12rpx 40rpx rgba(16, 24, 40, 0.12);
max-height: 480rpx;
overflow-y: auto;
}
.notify-page__picker-item {
padding: 28rpx 32rpx;
font-size: 28rpx;
color: #344054;
border-bottom: 1rpx solid #f2f4f7;
&:last-child {
border-bottom: none;
}
&--active {
color: #1ec671;
font-weight: 600;
}
}
.notify-page__card {
background: #fff;
border-radius: 24rpx;
overflow: hidden;
box-shadow: 0 2rpx 12rpx rgba(16, 24, 40, 0.04);
}
.notify-page__card-head {
display: flex;
align-items: center;
justify-content: space-between;
padding: 24rpx 28rpx;
border-bottom: 1rpx solid #f2f4f7;
}
.notify-page__unread {
font-size: 26rpx; font-size: 26rpx;
color: #98a2b3; color: #667085;
line-height: 1.4;
} }
.notify-page__list { .notify-page__list {
@@ -26,34 +113,66 @@
} }
.notify-page__item { .notify-page__item {
padding: 28rpx 32rpx; display: flex;
gap: 20rpx;
padding: 28rpx;
border-bottom: 1rpx solid #f2f4f7; border-bottom: 1rpx solid #f2f4f7;
} }
.notify-page__thumb-wrap {
position: relative;
width: 96rpx;
height: 96rpx;
flex-shrink: 0;
}
.notify-page__thumb {
width: 96rpx;
height: 96rpx;
border-radius: 12rpx;
background-color: #f2f4f7;
background-repeat: no-repeat;
background-position: center;
background-size: 72%;
}
.notify-page__thumb-dot {
position: absolute;
top: -4rpx;
right: -4rpx;
width: 16rpx;
height: 16rpx;
border-radius: 50%;
background: #f04438;
border: 2rpx solid #fff;
}
.notify-page__item-main {
flex: 1;
min-width: 0;
}
.notify-page__item-head { .notify-page__item-head {
display: flex; display: flex;
align-items: flex-start; align-items: flex-start;
justify-content: space-between; justify-content: space-between;
gap: 24rpx; gap: 16rpx;
width: 100%;
min-width: 0;
} }
.notify-page__title-wrap { .notify-page__title-wrap {
flex: 1; flex: 1;
min-width: 0; min-width: 0;
display: flex; overflow: hidden;
align-items: center;
gap: 12rpx;
}
.notify-page__dot {
width: 12rpx;
height: 12rpx;
border-radius: 50%;
background: #1ec671;
flex-shrink: 0;
} }
.notify-page__title { .notify-page__title {
display: block;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 30rpx; font-size: 30rpx;
font-weight: 600; font-weight: 600;
color: #1a1a1a; color: #1a1a1a;
@@ -61,7 +180,16 @@
} }
.notify-page__time { .notify-page__time {
flex-shrink: 0; flex: 0 0 auto;
font-size: 24rpx;
color: #98a2b3;
line-height: 1.4;
white-space: nowrap;
}
.notify-page__location {
display: block;
margin-top: 8rpx;
font-size: 24rpx; font-size: 24rpx;
color: #98a2b3; color: #98a2b3;
line-height: 1.4; line-height: 1.4;
@@ -71,36 +199,37 @@
display: block; display: block;
margin-top: 12rpx; margin-top: 12rpx;
font-size: 26rpx; font-size: 26rpx;
color: #98a2b3; color: #667085;
line-height: 1.55; line-height: 1.55;
} }
.notify-page__empty, .notify-page__empty,
.notify-page__loading { .notify-page__loading {
margin: 32rpx; margin: 32rpx 28rpx;
padding: 24rpx; padding: 24rpx;
border-radius: 16rpx; border-radius: 16rpx;
background: #f7f8fa; background: #f7f8fa;
text-align: center; text-align: center;
font-size: 26rpx;
color: #98a2b3;
} }
.notify-page__footer-tip { .notify-page__footer-tip {
padding: 80rpx 32rpx; padding: 48rpx 32rpx;
text-align: center; text-align: center;
font-size: 26rpx; font-size: 26rpx;
color: #98a2b3; color: #98a2b3;
} }
.notify-page__mark-all { .notify-page__mark-all {
display: flex; padding: 8rpx 20rpx;
align-items: center; border: 1rpx solid #93c5fd;
justify-content: flex-end; border-radius: 28rpx;
padding: 8rpx 0;
} }
.notify-page__mark-all-text { .notify-page__mark-all-text {
font-size: 26rpx; font-size: 24rpx;
color: #1ec671; color: #3b82f6;
white-space: nowrap; white-space: nowrap;
line-height: 1; line-height: 1;
} }

View File

@@ -1,8 +1,28 @@
import type { AppMessageVo } from '@/types/message' import type { AppMessageVo } from '@/types/message'
import { buildMessageFromPush, normalizeMessageId } from '@/utils/message-push' import { buildMessageFromPush, normalizeMessageId } from '@/utils/message-push'
import { sameId } from '@/utils/device-id'
export { buildMessageFromPush, normalizeMessageId } export { buildMessageFromPush, normalizeMessageId }
export function messageMatchesHome(
message: AppMessageVo,
homeId: string,
homeName: string,
): boolean {
if (!homeId) return true
if (message.homeId != null && sameId(message.homeId, homeId)) return true
const msgHome = message.homeName?.trim()
if (msgHome && homeName && msgHome === homeName) return true
return false
}
export function formatNotifyLocation(message: AppMessageVo): string {
const home = message.homeName?.trim()
const room = message.locationName?.trim()
if (home && room) return `${home} | ${room}`
return home || room || ''
}
export function isUnreadMessage(message: AppMessageVo): boolean { export function isUnreadMessage(message: AppMessageVo): boolean {
const flag = message.readFlag const flag = message.readFlag
return flag === 0 || flag === '0' return flag === 0 || flag === '0'

View File

@@ -1,5 +1,6 @@
import { onShow, onUnload } from '@dcloudio/uni-app' import { onShow, onUnload } from '@dcloudio/uni-app'
import { computed, ref } from 'vue' import { computed, ref } from 'vue'
import { fetchHomeList, getHomeId } from '@/api/home'
import { import {
fetchMessagePage, fetchMessagePage,
markAllMessagesRead, markAllMessagesRead,
@@ -7,6 +8,7 @@ import {
} from '@/api/message' } from '@/api/message'
import { refreshUnreadMessageCount } from '@/hooks/use-message-inbox' import { refreshUnreadMessageCount } from '@/hooks/use-message-inbox'
import { getErrorMessage } from '@/utils/api-error' import { getErrorMessage } from '@/utils/api-error'
import { sameId } from '@/utils/device-id'
import { onMessagePush } from '@/utils/message-socket' import { onMessagePush } from '@/utils/message-socket'
import { import {
clearPushCache, clearPushCache,
@@ -15,42 +17,107 @@ import {
rememberPushPayload, rememberPushPayload,
} from '@/utils/message-push-cache' } from '@/utils/message-push-cache'
import type { AppMessageVo } from '@/types/message' import type { AppMessageVo } from '@/types/message'
import type { AppHomeVo } from '@/types/location'
import { import {
formatNotifyLocation,
formatNotifyTime, formatNotifyTime,
isUnreadMessage, isUnreadMessage,
messageMatchesHome,
normalizeMessageId, normalizeMessageId,
} from './notify.utils' } from './notify.utils'
export interface NotifyListRow {
id: string
raw: AppMessageVo
title: string
timeText: string
locationText: string
content: string
unread: boolean
}
const PAGE_SIZE = 20 const PAGE_SIZE = 20
const ALL_HOMES_ID = ''
export function useNotify() { export function useNotify() {
const messages = ref<AppMessageVo[]>([]) const messages = ref<AppMessageVo[]>([])
const homes = ref<AppHomeVo[]>([])
const selectedHomeId = ref(ALL_HOMES_ID)
const homePickerOpen = ref(false)
const loading = ref(false) const loading = ref(false)
const refreshing = ref(false)
const loadingMore = ref(false) const loadingMore = ref(false)
const pageNum = ref(1) const pageNum = ref(1)
const total = ref(0) const total = ref(0)
const sectionTitle = ref('全部家庭')
const hasMore = computed(() => messages.value.length < total.value) const hasMore = computed(() => messages.value.length < total.value)
const selectedHome = computed(() =>
homes.value.find((home) => sameId(getHomeId(home), selectedHomeId.value)),
)
const selectedHomeLabel = computed(() => {
if (!selectedHomeId.value) return '全部家庭'
return selectedHome.value?.homeName?.trim() || '我的家'
})
const unreadCount = computed(
() => messages.value.filter((item) => isUnreadMessage(item)).length,
)
const unreadCountText = computed(() => `${unreadCount.value}条未读`)
const messageRows = computed<NotifyListRow[]>(() =>
messages.value.map((item) => {
const id = normalizeMessageId(item) || `${item.title}-${item.timestamp}`
return {
id,
raw: item,
title: item.deviceName || item.title || '系统通知',
timeText: formatNotifyTime(item),
locationText: formatNotifyLocation(item),
content: item.content || '暂无详情',
unread: isUnreadMessage(item),
}
}),
)
let unsubscribePush: (() => void) | null = null let unsubscribePush: (() => void) | null = null
async function loadHomes() {
try {
homes.value = await fetchHomeList() ?? []
} catch {
homes.value = []
}
}
function filterMessagesForHome(rows: AppMessageVo[]): AppMessageVo[] {
if (!selectedHomeId.value) return rows
const homeName = selectedHome.value?.homeName?.trim() || ''
return rows.filter((item) => messageMatchesHome(item, selectedHomeId.value, homeName))
}
async function loadMessages(reset = false) { async function loadMessages(reset = false) {
if (loading.value || loadingMore.value) return if (loading.value || loadingMore.value) return
if (reset) { if (reset) {
pageNum.value = 1 pageNum.value = 1
if (!messages.value.length) {
loading.value = true loading.value = true
}
} else { } else {
if (!hasMore.value && messages.value.length > 0) return if (!hasMore.value && messages.value.length > 0) return
loadingMore.value = true loadingMore.value = true
} }
try { try {
const { rows, total: nextTotal } = await fetchMessagePage({ const query = {
pageNum: pageNum.value, pageNum: pageNum.value,
pageSize: PAGE_SIZE, pageSize: PAGE_SIZE,
}) ...(selectedHomeId.value ? { homeId: selectedHomeId.value } : {}),
const mergedRows = mergeCachedMessages(rows) }
const { rows, total: nextTotal } = await fetchMessagePage(query)
const mergedRows = filterMessagesForHome(mergeCachedMessages(rows))
if (reset) { if (reset) {
messages.value = mergedRows messages.value = mergedRows
} else { } else {
@@ -62,8 +129,6 @@ export function useNotify() {
messages.value = Array.from(map.values()) messages.value = Array.from(map.values())
} }
total.value = Math.max(nextTotal, messages.value.length) total.value = Math.max(nextTotal, messages.value.length)
const homeName = rows.find((item) => item.homeName)?.homeName
if (homeName) sectionTitle.value = homeName
if (rows.length > 0) { if (rows.length > 0) {
pageNum.value += 1 pageNum.value += 1
} }
@@ -75,12 +140,38 @@ export function useNotify() {
} }
} }
async function onRefresh() { function toggleHomePicker() {
homePickerOpen.value = !homePickerOpen.value
}
function closeHomePicker() {
homePickerOpen.value = false
}
async function onSelectHome(homeId: string) {
if (sameId(selectedHomeId.value, homeId)) {
closeHomePicker()
return
}
selectedHomeId.value = homeId
closeHomePicker()
await loadMessages(true) await loadMessages(true)
await refreshUnreadMessageCount() await refreshUnreadMessageCount()
} }
async function onRefresh() {
if (refreshing.value) return
refreshing.value = true
try {
await loadMessages(true)
await refreshUnreadMessageCount()
} finally {
refreshing.value = false
}
}
async function onLoadMore() { async function onLoadMore() {
if (loadingMore.value || !hasMore.value) return
await loadMessages(false) await loadMessages(false)
} }
@@ -125,6 +216,9 @@ export function useNotify() {
const incoming = rememberPushPayload(payload) const incoming = rememberPushPayload(payload)
if (!incoming) return if (!incoming) return
const homeName = selectedHome.value?.homeName?.trim() || ''
if (!messageMatchesHome(incoming, selectedHomeId.value, homeName)) return
const incomingId = normalizeMessageId(incoming) const incomingId = normalizeMessageId(incoming)
const exists = messages.value.some((item) => normalizeMessageId(item) === incomingId) const exists = messages.value.some((item) => normalizeMessageId(item) === incomingId)
if (exists) return if (exists) return
@@ -133,12 +227,20 @@ export function useNotify() {
total.value = messages.value.length total.value = messages.value.length
} }
function isHomeOptionActive(home: AppHomeVo): boolean {
return sameId(getHomeId(home), selectedHomeId.value)
}
onShow(() => { onShow(() => {
unsubscribePush?.() unsubscribePush?.()
unsubscribePush = onMessagePush((payload) => { unsubscribePush = onMessagePush((payload) => {
prependPushMessage(payload) prependPushMessage(payload)
}) })
void onRefresh() void loadHomes()
void (async () => {
await loadMessages(true)
await refreshUnreadMessageCount()
})()
}) })
onUnload(() => { onUnload(() => {
@@ -148,15 +250,25 @@ export function useNotify() {
return { return {
messages, messages,
messageRows,
homes,
selectedHomeId,
selectedHomeLabel,
homePickerOpen,
unreadCountText,
loading, loading,
refreshing,
loadingMore, loadingMore,
hasMore, hasMore,
sectionTitle, toggleHomePicker,
formatNotifyTime, closeHomePicker,
isUnreadMessage, onSelectHome,
isHomeOptionActive,
onRefresh, onRefresh,
onLoadMore, onLoadMore,
onItemTap, onItemTap,
onMarkAllRead, onMarkAllRead,
allHomesId: ALL_HOMES_ID,
parseHomeId: getHomeId,
} }
} }

View File

@@ -4,8 +4,10 @@ import { cancelAccount, logout } from '@/api/auth'
import { fetchProfile } from '@/api/profile' import { fetchProfile } from '@/api/profile'
import { getErrorMessage } from '@/utils/api-error' import { getErrorMessage } from '@/utils/api-error'
import { teardownMessageInbox } from '@/hooks/use-message-inbox' import { teardownMessageInbox } from '@/hooks/use-message-inbox'
import { clearStoredToken } from '@/utils/auth-token' import { clearLocalUserData } from '@/utils/clear-local-user-data'
import { clearAppFileCacheOnDevice } from '@/pages/mine/storage/storage.utils'
import { import {
adoptPendingPasswordModifiedForUser,
formatPasswordModifiedDesc, formatPasswordModifiedDesc,
getPasswordModifiedAt, getPasswordModifiedAt,
} from '@/utils/password-modified-at' } from '@/utils/password-modified-at'
@@ -58,8 +60,12 @@ export function usePrivacy() {
try { try {
const profile = await fetchProfile() const profile = await fetchProfile()
phone.value = profile?.phonenumber || profile?.userName || '' phone.value = profile?.phonenumber || profile?.userName || ''
const boundPhone = profile?.phonenumber || profile?.userName || ''
passwordModifiedAt.value = getPasswordModifiedAt(profile?.userId)
?? adoptPendingPasswordModifiedForUser(profile?.userId ?? '', boundPhone)
} catch (err) { } catch (err) {
uni.showToast({ title: getErrorMessage(err, '加载账号信息失败'), icon: 'none' }) uni.showToast({ title: getErrorMessage(err, '加载账号信息失败'), icon: 'none' })
passwordModifiedAt.value = null
} }
} }
@@ -83,7 +89,12 @@ export function usePrivacy() {
try { try {
await cancelAccount() await cancelAccount()
teardownMessageInbox() teardownMessageInbox()
clearStoredToken() clearLocalUserData()
try {
await clearAppFileCacheOnDevice()
} catch {
// 非 App 或清理失败不阻断注销流程
}
uni.showToast({ title: '账号已注销', icon: 'success' }) uni.showToast({ title: '账号已注销', icon: 'success' })
uni.reLaunch({ url: '/pages/login/index' }) uni.reLaunch({ url: '/pages/login/index' })
} catch (err) { } catch (err) {
@@ -109,7 +120,7 @@ export function usePrivacy() {
}) })
} finally { } finally {
teardownMessageInbox() teardownMessageInbox()
clearStoredToken() clearLocalUserData()
uni.reLaunch({ url: '/pages/login/index' }) uni.reLaunch({ url: '/pages/login/index' })
} }
})() })()
@@ -117,12 +128,7 @@ export function usePrivacy() {
}) })
} }
function loadPasswordModifiedAt() {
passwordModifiedAt.value = getPasswordModifiedAt()
}
onShow(() => { onShow(() => {
loadPasswordModifiedAt()
void loadProfile() void loadProfile()
}) })

View File

@@ -145,7 +145,8 @@ function clearLocalCacheExceptAuth(): void {
} }
} }
function clearAppFileCache(): Promise<void> { /** App 端清理图片/文件缓存(H5 等环境直接 resolve) */
export function clearAppFileCacheOnDevice(): Promise<void> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
// #ifdef APP-PLUS // #ifdef APP-PLUS
if (typeof plus !== 'undefined' && plus.cache?.clear) { if (typeof plus !== 'undefined' && plus.cache?.clear) {
@@ -167,7 +168,7 @@ export async function clearDeviceCache(): Promise<void> {
if (!isStorageManagedOnDevice()) { if (!isStorageManagedOnDevice()) {
throw new Error('请在手机 App 中清理储存空间') throw new Error('请在手机 App 中清理储存空间')
} }
await clearAppFileCache() await clearAppFileCacheOnDevice()
clearLocalCacheExceptAuth() clearLocalCacheExceptAuth()
} }

View File

@@ -0,0 +1,341 @@
<template>
<view v-if="visible" class="device-consult-picker">
<view class="device-consult-picker__mask" @tap="onCancel" />
<view class="device-consult-picker__panel" @tap.stop>
<view class="device-consult-picker__header">
<text class="device-consult-picker__title">选择设备咨询</text>
<view class="device-consult-picker__close" @tap="onCancel">
<text class="device-consult-picker__close-icon">×</text>
</view>
</view>
<view class="device-consult-picker__search">
<input
class="device-consult-picker__search-input"
type="text"
:value="keyword"
placeholder="搜索设备名称 / 型号 / SN 编号"
placeholder-class="device-consult-picker__search-placeholder"
confirm-type="search"
@input="onKeywordInput"
/>
</view>
<view class="device-consult-picker__section-head">
<view class="device-consult-picker__section-title">
<view class="device-consult-picker__section-bar" />
<text>全部设备</text>
</view>
<text class="device-consult-picker__section-count">{{ deviceCountText }}</text>
</view>
<scroll-view class="device-consult-picker__list" scroll-y>
<view v-if="loading" class="device-consult-picker__state">
<text>加载中…</text>
</view>
<view v-else-if="!filteredDevices.length" class="device-consult-picker__state">
<text>{{ keyword.trim() ? '未找到匹配设备' : '暂无绑定设备' }}</text>
</view>
<view
v-for="item in filteredDevices"
:key="item.deviceId"
class="device-consult-picker__item"
:class="{ 'device-consult-picker__item--active': item.deviceId === selectedDeviceId }"
@tap="emit('select', item.deviceId)"
>
<image
class="device-consult-picker__thumb"
:src="staticAssets.logo"
mode="aspectFill"
/>
<view class="device-consult-picker__item-main">
<text class="device-consult-picker__item-name">{{ item.name }}</text>
<text class="device-consult-picker__item-sub">
型号 {{ item.modelText }} · SN {{ item.snText }}
</text>
<text
class="device-consult-picker__item-status"
:class="item.isOnline ? 'device-consult-picker__item-status--online' : ''"
>
{{ item.isOnline ? '在线' : '离线' }}
</text>
</view>
<view
class="device-consult-picker__radio"
:class="{ 'device-consult-picker__radio--checked': item.deviceId === selectedDeviceId }"
/>
</view>
</scroll-view>
<view class="device-consult-picker__footer">
<view class="device-consult-picker__btn device-consult-picker__btn--ghost" @tap="onCancel">
<text>取消</text>
</view>
<view
class="device-consult-picker__btn device-consult-picker__btn--primary"
:class="{ 'device-consult-picker__btn--disabled': !selectedDeviceId || loading }"
@tap="onConfirm"
>
<text>确认咨询</text>
</view>
</view>
</view>
</view>
</template>
<script setup lang="ts">
import { staticAssets } from '@/utils/static-assets'
import type { SupportConsultDeviceItem } from '../../support-device-consult.types'
const props = defineProps<{
visible: boolean
loading: boolean
keyword: string
filteredDevices: SupportConsultDeviceItem[]
deviceCountText: string
selectedDeviceId: string
}>()
const emit = defineEmits<{
'update:visible': [value: boolean]
'update:keyword': [value: string]
select: [deviceId: string]
confirm: []
cancel: []
}>()
function onCancel() {
emit('cancel')
emit('update:visible', false)
}
function onConfirm() {
if (props.loading || !props.selectedDeviceId) return
emit('confirm')
}
function onKeywordInput(event: { detail: { value: string } }) {
emit('update:keyword', event.detail.value ?? '')
}
</script>
<style lang="scss" scoped>
.device-consult-picker {
position: fixed;
inset: 0;
z-index: 600;
display: flex;
align-items: center;
justify-content: center;
padding: 48rpx 32rpx;
box-sizing: border-box;
}
.device-consult-picker__mask {
position: absolute;
inset: 0;
background: rgba(0, 0, 0, 0.45);
}
.device-consult-picker__panel {
position: relative;
width: 100%;
max-width: 640rpx;
max-height: 88vh;
background: #fff;
border-radius: 24rpx;
overflow: hidden;
display: flex;
flex-direction: column;
}
.device-consult-picker__header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 28rpx 32rpx;
background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
}
.device-consult-picker__title {
font-size: 34rpx;
font-weight: 600;
color: #fff;
}
.device-consult-picker__close {
width: 56rpx;
height: 56rpx;
display: flex;
align-items: center;
justify-content: center;
}
.device-consult-picker__close-icon {
font-size: 44rpx;
line-height: 1;
color: #fff;
}
.device-consult-picker__search {
padding: 24rpx 28rpx 8rpx;
}
.device-consult-picker__search-input {
height: 72rpx;
padding: 0 24rpx;
background: #f3f4f6;
border-radius: 16rpx;
font-size: 26rpx;
color: #111827;
}
.device-consult-picker__search-placeholder {
color: #9ca3af;
font-size: 26rpx;
}
.device-consult-picker__section-head {
display: flex;
align-items: center;
justify-content: space-between;
padding: 20rpx 28rpx 12rpx;
}
.device-consult-picker__section-title {
display: flex;
align-items: center;
gap: 12rpx;
font-size: 28rpx;
font-weight: 600;
color: #111827;
}
.device-consult-picker__section-bar {
width: 6rpx;
height: 28rpx;
border-radius: 4rpx;
background: #3b82f6;
}
.device-consult-picker__section-count {
font-size: 24rpx;
color: #9ca3af;
}
.device-consult-picker__list {
flex: 1;
min-height: 200rpx;
max-height: 52vh;
padding: 0 28rpx;
box-sizing: border-box;
}
.device-consult-picker__state {
padding: 48rpx 0;
text-align: center;
font-size: 26rpx;
color: #9ca3af;
}
.device-consult-picker__item {
display: flex;
align-items: center;
gap: 20rpx;
padding: 20rpx;
margin-bottom: 16rpx;
border: 2rpx solid #e5e7eb;
border-radius: 16rpx;
background: #fff;
&--active {
border-color: #3b82f6;
background: #f8fbff;
}
}
.device-consult-picker__thumb {
width: 96rpx;
height: 96rpx;
border-radius: 12rpx;
background: #f3f4f6;
flex-shrink: 0;
}
.device-consult-picker__item-main {
flex: 1;
min-width: 0;
}
.device-consult-picker__item-name {
display: block;
font-size: 28rpx;
font-weight: 600;
color: #111827;
margin-bottom: 6rpx;
}
.device-consult-picker__item-sub {
display: block;
font-size: 22rpx;
color: #6b7280;
margin-bottom: 8rpx;
}
.device-consult-picker__item-status {
font-size: 22rpx;
color: #9ca3af;
&--online {
color: #16a34a;
}
}
.device-consult-picker__radio {
width: 36rpx;
height: 36rpx;
border-radius: 50%;
border: 2rpx solid #d1d5db;
flex-shrink: 0;
box-sizing: border-box;
&--checked {
border-color: #3b82f6;
background: #3b82f6;
box-shadow: inset 0 0 0 6rpx #fff;
}
}
.device-consult-picker__footer {
display: flex;
gap: 20rpx;
padding: 24rpx 28rpx calc(24rpx + env(safe-area-inset-bottom));
border-top: 1rpx solid #f0f0f0;
}
.device-consult-picker__btn {
flex: 1;
height: 80rpx;
border-radius: 16rpx;
display: flex;
align-items: center;
justify-content: center;
font-size: 30rpx;
font-weight: 500;
&--ghost {
border: 2rpx solid #e5e7eb;
color: #374151;
background: #fff;
}
&--primary {
background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
color: #fff;
}
&--disabled {
opacity: 0.45;
}
}
</style>

View File

@@ -1,4 +1,4 @@
<template> <template>
<view class="support-page"> <view class="support-page">
<view class="support-page__top"> <view class="support-page__top">
<app-navbar title="在线客服"> <app-navbar title="在线客服">
@@ -53,7 +53,14 @@
<view class="support-page__chat-inner"> <view class="support-page__chat-inner">
<template v-for="item in messages" :key="item.id"> <template v-for="item in messages" :key="item.id">
<view v-if="item.type === 'time'" class="support-page__time"> <view v-if="item.type === 'time'" class="support-page__time">
<text class="support-page__time-pill">🕐 {{ item.text }}</text> <view class="support-page__time-pill">
<image
class="support-page__time-icon"
:src="staticAssets.iconSupportTime"
mode="aspectFit"
/>
<text class="support-page__time-text">{{ item.text }}</text>
</view>
</view> </view>
<view <view
@@ -86,7 +93,12 @@
class="support-page__bubble" class="support-page__bubble"
:class="`support-page__bubble--${item.role}`" :class="`support-page__bubble--${item.role}`"
> >
<text>{{ item.content }}</text> <rich-text
v-if="item.richHtml"
class="support-page__rich"
:nodes="item.richHtml"
/>
<text v-else>{{ item.content }}</text>
</view> </view>
</view> </view>
@@ -101,15 +113,19 @@
</view> </view>
</view> </view>
<view v-else-if="item.type === 'quick-actions'" class="support-page__quick"> <view
v-else-if="item.type === 'quick-actions' && item.actions?.length"
class="support-page__quick"
>
<view <view
v-for="action in item.actions" v-for="action in item.actions"
:key="action.id" :key="action.id"
class="support-page__quick-item" class="support-page__quick-item"
@tap="onQuickAction(action)" hover-class="support-page__quick-item--active"
@tap.stop="onQuickAction(action)"
> >
<text class="support-page__quick-dot">●</text> <text class="support-page__quick-dot">●</text>
<text>{{ action.label }}</text> <text class="support-page__quick-label">{{ action.label }}</text>
</view> </view>
</view> </view>
@@ -236,6 +252,7 @@
:src="chatImageDisplaySrc(item)" :src="chatImageDisplaySrc(item)"
mode="aspectFill" mode="aspectFill"
@error="onChatImageError(item)" @error="onChatImageError(item)"
@load="onChatImageLoad"
@tap="onPreviewImage(chatImageDisplaySrc(item))" @tap="onPreviewImage(chatImageDisplaySrc(item))"
/> />
</view> </view>
@@ -264,14 +281,28 @@
本次会话已加密,客服不会向您索要密码或验证码 本次会话已加密,客服不会向您索要密码或验证码
</text> </text>
<view class="support-page__footer-shortcuts"> <view class="support-page__footer-shortcuts">
<text <view
v-for="shortcut in footerShortcuts" v-for="shortcut in footerShortcuts"
:key="shortcut" :key="shortcut"
class="support-page__footer-shortcut" class="support-page__footer-shortcut"
@tap="onFooterShortcut(shortcut)" :class="{ 'support-page__footer-shortcut--active': shortcut === '常见问题' && faqPanelVisible }"
hover-class="support-page__footer-shortcut--pressed"
@tap.stop="handleFooterShortcut(shortcut)"
> >
{{ shortcut }} <text>{{ shortcut }}</text>
</text> </view>
</view>
<view v-if="faqPanelVisible" class="support-page__footer-faq">
<button
v-for="action in faqActions"
:key="action.id"
class="support-page__footer-faq-item"
hover-class="support-page__footer-faq-item--active"
plain
@tap.stop="onQuickAction(action)"
>
{{ action.label }}
</button>
</view> </view>
<view class="support-page__input-row"> <view class="support-page__input-row">
<view class="support-page__input-wrap"> <view class="support-page__input-wrap">
@@ -305,6 +336,18 @@
</view> </view>
</view> </view>
</view> </view>
<device-consult-picker
v-model:visible="deviceConsultVisible"
v-model:keyword="deviceConsultKeyword"
:loading="deviceConsultLoading"
:filtered-devices="deviceConsultFilteredDevices"
:device-count-text="deviceConsultDeviceCountText"
:selected-device-id="deviceConsultSelectedDeviceId"
@select="onDeviceConsultSelect"
@confirm="onConfirmDeviceConsult"
@cancel="onDeviceConsultCancel"
/>
</view> </view>
</template> </template>
@@ -313,6 +356,7 @@ import { computed, watch } from 'vue'
import { staticAssets } from '@/utils/static-assets' import { staticAssets } from '@/utils/static-assets'
import { useCsChatImage } from './use-cs-chat-image' import { useCsChatImage } from './use-cs-chat-image'
import { useSupportChatScroll } from './use-support-chat-scroll' import { useSupportChatScroll } from './use-support-chat-scroll'
import DeviceConsultPicker from './components/device-consult-picker/index.vue'
import { useSupport } from './use-support' import { useSupport } from './use-support'
import type { DiagnosisItem } from './support.types' import type { DiagnosisItem } from './support.types'
@@ -326,6 +370,8 @@ const {
sessionEnded, sessionEnded,
formattedQueueWait, formattedQueueWait,
footerShortcuts, footerShortcuts,
faqPanelVisible,
faqActions,
onQuickAction, onQuickAction,
onTransferHuman, onTransferHuman,
onEndSession, onEndSession,
@@ -335,14 +381,34 @@ const {
onDiagnosisSuggestion, onDiagnosisSuggestion,
onSend, onSend,
onPickImage, onPickImage,
deviceConsultVisible,
deviceConsultLoading,
deviceConsultKeyword,
deviceConsultFilteredDevices,
deviceConsultDeviceCountText,
deviceConsultSelectedDeviceId,
onDeviceConsultSelect,
onConfirmDeviceConsult,
onDeviceConsultCancel,
} = useSupport() } = useSupport()
const { scrollTop, scrollIntoView, scrollToBottom } = useSupportChatScroll(messages) const { scrollTop, scrollIntoView, scrollToBottom, scrollToBottomSequence } = useSupportChatScroll(messages)
let chatImageScrollTimer: ReturnType<typeof setTimeout> | null = null
function onChatImageLoad() {
if (chatImageScrollTimer) clearTimeout(chatImageScrollTimer)
chatImageScrollTimer = setTimeout(() => {
chatImageScrollTimer = null
scrollToBottomSequence()
}, 60)
}
const humanAvatarText = computed(() => headerInfo.value.avatarText || '服') const humanAvatarText = computed(() => headerInfo.value.avatarText || '服')
const { displaySrc: chatImageDisplaySrc, onImageError: onChatImageError } = useCsChatImage( const { displaySrc: chatImageDisplaySrc, onImageError: onChatImageError } = useCsChatImage(
() => messages.value, () => messages.value,
{ onDisplayUpdate: () => scrollToBottomSequence() },
) )
watch(sessionEnded, (ended) => { watch(sessionEnded, (ended) => {
@@ -362,6 +428,14 @@ function handleSend() {
void scrollToBottom(400) void scrollToBottom(400)
} }
function handleFooterShortcut(label: string) {
onFooterShortcut(label)
if (label === '常见问题' || label === '订单咨询') {
void scrollToBottom(80)
void scrollToBottom(280)
}
}
function diagnosisStatusText(status: DiagnosisItem['status']): string { function diagnosisStatusText(status: DiagnosisItem['status']): string {
if (status === 'done') return '已完成' if (status === 'done') return '已完成'
if (status === 'running') return '进行中' if (status === 'running') return '进行中'

View File

@@ -0,0 +1,8 @@
/** 客服「订单咨询」设备选择项 */
export interface SupportConsultDeviceItem {
deviceId: string
name: string
modelText: string
snText: string
isOnline: boolean
}

View File

@@ -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)
}

View File

@@ -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<string, CacheEntry>
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
}
}

View File

@@ -169,9 +169,21 @@ $support-danger: #f04438;
} }
.support-page__time-pill { .support-page__time-pill {
display: inline-flex;
align-items: center;
gap: 8rpx;
padding: 8rpx 20rpx; padding: 8rpx 20rpx;
border-radius: 20rpx; border-radius: 20rpx;
background: #eef1f5; background: #eef1f5;
}
.support-page__time-icon {
width: 28rpx;
height: 28rpx;
flex-shrink: 0;
}
.support-page__time-text {
font-size: 22rpx; font-size: 22rpx;
color: $support-text-secondary; color: $support-text-secondary;
line-height: 1.4; 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 { .support-page__bubble {
max-width: 100%; max-width: 100%;
padding: 20rpx 24rpx; padding: 20rpx 24rpx;
@@ -302,6 +322,17 @@ $support-danger: #f04438;
background: #fff; background: #fff;
border: 1rpx solid #e4e7ec; border: 1rpx solid #e4e7ec;
border-radius: 32rpx; 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; font-size: 26rpx;
color: #3b82f6; color: #3b82f6;
line-height: 1.3; line-height: 1.3;
@@ -664,6 +695,42 @@ $support-danger: #f04438;
font-size: 24rpx; font-size: 24rpx;
color: $support-text-muted; color: $support-text-muted;
line-height: 1.3; 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 { .support-page__input-row {

View File

@@ -55,7 +55,7 @@ export interface CsMessageVo {
fileUrl?: string fileUrl?: string
clientMsgId?: string clientMsgId?: string
createTime?: string createTime?: string
extra?: Record<string, unknown> extra?: Record<string, unknown> | string
} }
/** WebSocket /app/cs/chat 推送 */ /** WebSocket /app/cs/chat 推送 */
@@ -73,12 +73,29 @@ export interface CsCreateSessionBody {
accessType?: 'bot' | 'human' 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 { export interface CsRobotVo {
kbId?: number | string kbId?: number | string
title?: string title?: string
content?: string content?: string
matched?: boolean 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 */ /** POST /app/cs/session 及发消息等操作返回 data */
@@ -149,6 +166,8 @@ export type SupportMessage =
type: 'text' type: 'text'
role: ChatRole role: ChatRole
content: string content: string
/** 知识库富文本回复(HTML) */
richHtml?: string
createTime?: string createTime?: string
} }
| { | {

View File

@@ -9,6 +9,12 @@ import type {
SupportPhase, SupportPhase,
} from './support.types' } from './support.types'
import { CS_IMAGE_MESSAGE_PLACEHOLDER, CS_SESSION_STATUS } 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 时展示 */ /** 上传成功后缓存 ossId → 可访问地址,用于消息列表尚未带 url 时展示 */
const csImageUrlCache = new Map<string, string>() const csImageUrlCache = new Map<string, string>()
@@ -74,22 +80,208 @@ export function createClientMsgId(): string {
return `${Date.now()}-${Math.random().toString(36).slice(2, 10)}` return `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`
} }
const ROBOT_BUTTON_LABELS: Record<string, string> = {
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<string>()
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<QuickActionItem & { sort?: number }> = []
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<string, unknown>
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<string, unknown>
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<string, unknown>
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( export function unwrapCsActionResponse(
data: CsAppActionVo | CsSessionVo | string | null | undefined, data: CsAppActionVo | CsSessionVo | string | null | undefined,
): { session: CsSessionVo; messages?: CsMessageVo[]; robot?: CsRobotVo } { ): { session: CsSessionVo; messages?: CsMessageVo[]; robot?: CsRobotVo } {
if (!data) return { session: {} } const payload = unwrapCsActionPayload(data)
if (typeof data === 'string') { if (!payload) return { session: {} }
return { session: normalizeSessionResponse(data) } if (typeof payload === 'string') {
return { session: normalizeSessionResponse(payload) }
} }
if (data.session) { const record = payload as Record<string, unknown>
const robot = normalizeCsRobotVo(
record.robot ?? record.robotReply ?? record.robotVo ?? record.kbReply,
)
if (payload.session) {
return { return {
session: normalizeSessionResponse(data.session), session: normalizeSessionResponse(payload.session),
messages: data.messages, messages: payload.messages,
robot: data.robot, robot,
} }
} }
const record = data as CsSessionVo & CsAppActionVo const merged = payload as CsSessionVo & CsAppActionVo
const { messages, robot, ...session } = record const { messages, ...session } = merged
return { return {
session: normalizeSessionResponse(session), session: normalizeSessionResponse(session),
messages, 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(/<script[\s\S]*?<\/script>/gi, '')
.replace(/\son\w+="[^"]*"/gi, '')
.replace(/\son\w+='[^']*'/gi, '')
// 后台富文本里可能预览/占位快捷按钮,App 用接口 buttons 单独渲染,避免空白条
out = out
.replace(/<div[^>]*class="[^"]*kb[^"]*button[^"]*"[^>]*>[\s\S]*?<\/div>/gi, '')
.replace(/<div[^>]*data-kb-buttons[^>]*>[\s\S]*?<\/div>/gi, '')
.replace(/<p[^>]*>\s*(?:&nbsp;|\u00a0|\s|<br\s*\/?>)*\s*<\/p>/gi, '')
out = out.replace(/<img\b([^>]*)>/gi, (_, attrs: string) => {
if (/style\s*=/i.test(attrs)) {
return `<img${attrs.replace(
/style\s*=\s*(["'])([^"']*)\1/i,
(_m, q: string, style: string) => ` style=${q}${style};max-width:100%;height:auto;display:block;${q}`,
)}>`
}
return `<img${attrs} style="max-width:100%;height:auto;display:block;">`
})
return out.trim()
}
function stripHtmlToText(html: string): string {
return html
.replace(/<img[^>]*>/gi, '[图片]')
.replace(/<br\s*\/?>/gi, '\n')
.replace(/<\/p>/gi, '\n')
.replace(/<[^>]+>/g, '')
.replace(/\u00a0/g, ' ')
.replace(/\n{3,}/g, '\n\n')
.trim()
}
function formatBotTextFields(text: string): { content: string; richHtml?: string } {
const raw = text.trim()
if (!raw) return { content: '' }
if (!isHtmlLike(raw)) return { content: raw }
const richHtml = sanitizeSupportHtml(raw)
const plain = stripHtmlToText(richHtml)
return {
content: plain || '请查看图文回复',
richHtml,
}
}
function parseMessageExtra(message?: CsMessageVo): Record<string, unknown> | null {
const extra = message?.extra
if (!extra) return null
if (typeof extra === 'string') {
try {
return JSON.parse(extra) as Record<string, unknown>
} catch {
return null
}
}
return extra
}
function buildBotTextMessage(
id: string,
seq: number | undefined,
text: string,
createTime?: string,
): SupportMessage {
const formatted = formatBotTextFields(text)
return {
id,
seq,
type: 'text',
role: 'bot',
content: formatted.content,
richHtml: formatted.richHtml,
createTime,
}
}
function buildQuickActionsMessageFromButtons(
id: string,
buttons: QuickActionItem[],
seq?: number,
): SupportMessage | null {
const actions = dedupeQuickActionItems(buttons)
if (!actions.length) return null
return {
id,
seq,
type: 'quick-actions',
actions,
}
}
/** 将发消息接口返回的 robot 字段转为可展示消息 */ /** 将发消息接口返回的 robot 字段转为可展示消息 */
export function mapRobotReplyToMessages(robot?: CsRobotVo): SupportMessage[] { export function mapRobotReplyToMessages(
robot?: CsRobotVo,
options?: { skipText?: boolean; botSeq?: number },
): SupportMessage[] {
if (!robot) return [] if (!robot) return []
const result: SupportMessage[] = [] const result: SupportMessage[] = []
@@ -108,33 +398,194 @@ export function mapRobotReplyToMessages(robot?: CsRobotVo): SupportMessage[] {
? `${title}\n${content}` ? `${title}\n${content}`
: (content || title || '') : (content || title || '')
if (text) { if (text && !options?.skipText) {
const formatted = formatBotTextFields(text)
result.push({ result.push({
id: `robot-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`, id: `robot-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
type: 'text', type: 'text',
role: 'bot', role: 'bot',
content: text, content: formatted.content,
richHtml: formatted.richHtml,
}) })
} }
const actions = (robot.buttons ?? []) const actions = resolveKbButtonsFromRobot(robot)
.map((item, index) => ({ const actionMsg = buildQuickActionsMessageFromButtons(
id: item.buttonCode?.trim() || `robot-btn-${index}`, `robot-actions-${Date.now()}`,
label: item.label?.trim() || '',
}))
.filter((item) => item.label)
if (actions.length) {
result.push({
id: `robot-actions-${Date.now()}`,
type: 'quick-actions',
actions, actions,
}) options?.botSeq,
} )
if (actionMsg) result.push(actionMsg)
return result return result
} }
function extractMessageButtons(message: CsMessageVo, sessionId?: string): QuickActionItem[] {
const sid = sessionId?.trim() ?? ''
const extra = parseMessageExtra(message)
if (extra) {
const extraFlags = [extra.showButtons, extra.buttonEnabled, extra.enableButtons]
if (extraFlags.some((item) => isExplicitlyDisabled(item))) {
if (sid) markKbButtonsDisabledForMessage(sid, message, extra.kbId as string | number | undefined)
return []
}
}
const robot = normalizeCsRobotVo(
extra?.robot ?? extra?.robotReply ?? extra?.kbReply ?? extra?.kbMatch,
)
if (robot) {
const fromRobot = resolveKbButtonsFromRobot(robot)
if (fromRobot.length) {
if (sid) persistKbButtonsForMessage(sid, message, fromRobot, robot.kbId)
return fromRobot
}
if (!isRobotShortcutButtonsEnabled(robot)) {
if (sid) markKbButtonsDisabledForMessage(sid, message, robot.kbId)
return []
}
}
const buttons = mapRobotButtons(
extra?.buttons ?? extra?.buttonList ?? extra?.shortcutButtons,
)
if (buttons.length) {
const kbId = extra?.kbId ?? extra?.id
if (sid) persistKbButtonsForMessage(sid, message, buttons, kbId as string | number | undefined)
return buttons
}
const content = message.content?.trim() ?? ''
if (content.startsWith('{') && content.endsWith('}')) {
try {
const payload = JSON.parse(content) as Record<string, unknown>
const fromJson = mapRobotButtons(
payload.buttons ?? payload.buttonList ?? payload.shortcutButtons,
)
if (fromJson.length) {
if (sid) persistKbButtonsForMessage(sid, message, fromJson)
return fromJson
}
} catch {
// ignore invalid json content
}
}
if (!sid) return []
if (isKbButtonsDisabledInCache(sid, message)) return []
return loadKbButtonsForMessage(sid, message)
}
export function mapCsMessageWithFollowups(
message: CsMessageVo,
sessionId?: string,
options?: { skipButtons?: boolean },
): SupportMessage[] {
const main = mapCsMessage(message)
if (!main) return []
const list: SupportMessage[] = [main]
const buttons = options?.skipButtons
? []
: extractMessageButtons(message, sessionId)
if (buttons.length && main.type === 'text' && (main.role === 'bot' || main.role === 'agent')) {
const actionMsg = buildQuickActionsMessageFromButtons(
`${main.id}-kb-actions`,
buttons,
main.seq,
)
if (actionMsg) list.push(actionMsg)
}
return list
}
function appendKbShortcutsAfterLastBot(
list: SupportMessage[],
buttons: QuickActionItem[],
): SupportMessage[] {
if (!buttons.length) return list
let lastBotIndex = -1
for (let i = list.length - 1; i >= 0; i -= 1) {
const item = list[i]
if (item.type === 'text' && item.role === 'bot') {
lastBotIndex = i
break
}
}
if (lastBotIndex < 0) return list
const nextItem = list[lastBotIndex + 1]
if (nextItem?.type === 'quick-actions') return list
const actionMsg = buildQuickActionsMessageFromButtons(
`kb-actions-${Date.now()}`,
buttons,
list[lastBotIndex]?.seq,
)
if (!actionMsg) return list
const next = [...list]
next.splice(lastBotIndex + 1, 0, actionMsg)
return next
}
function findLastBotTextMessage(list: SupportMessage[]): SupportMessage | undefined {
for (let i = list.length - 1; i >= 0; i -= 1) {
const item = list[i]
if (item.type === 'text' && item.role === 'bot') return item
}
return undefined
}
/** 同一机器人回复下重复的快捷按钮行只保留一条 */
export function dedupeKbQuickActionRows(messages: SupportMessage[]): SupportMessage[] {
const result: SupportMessage[] = []
for (const item of messages) {
if (item.type !== 'quick-actions') {
result.push(item)
continue
}
const actions = dedupeQuickActionItems(item.actions)
if (!actions.length) continue
const normalized: SupportMessage = { ...item, actions }
const prev = result[result.length - 1]
const prev2 = result[result.length - 2]
if (
prev?.type === 'quick-actions'
&& (prev.seq ?? normalized.seq) === (normalized.seq ?? prev.seq)
) {
continue
}
if (
prev?.type === 'quick-actions'
&& prev2?.type === 'text'
&& (prev2.role === 'bot' || prev2.role === 'agent')
&& (prev2.seq ?? normalized.seq) === (normalized.seq ?? prev2.seq)
) {
continue
}
result.push(normalized)
}
return result
}
export function mapActionToSupportMessages(
action: { messages?: CsMessageVo[]; robot?: CsRobotVo },
sessionId?: string,
): SupportMessage[] {
const skipButtonsOnMessages = resolveKbButtonsFromRobot(action.robot).length > 0
const mapped = (action.messages ?? []).flatMap((item) =>
mapCsMessageWithFollowups(item, sessionId, { skipButtons: skipButtonsOnMessages }))
const hasBotText = mapped.some((item) => item.type === 'text' && item.role === 'bot')
const lastBot = findLastBotTextMessage(mapped)
const robotMsgs = mapRobotReplyToMessages(action.robot, {
skipText: hasBotText,
botSeq: lastBot?.seq,
})
const merged = [...mapped, ...robotMsgs]
if (robotMsgs.some((item) => item.type === 'quick-actions')) {
return dedupeKbQuickActionRows(merged)
}
const fallbackButtons = resolveKbButtonsFromRobot(action.robot)
return dedupeKbQuickActionRows(appendKbShortcutsAfterLastBot(merged, fallbackButtons))
}
export function normalizeSessionResponse( export function normalizeSessionResponse(
data: CsSessionVo | string | null | undefined, data: CsSessionVo | string | null | undefined,
): CsSessionVo { ): CsSessionVo {
@@ -471,19 +922,26 @@ function mapStructuredMessage(message: CsMessageVo, payload: Record<string, unkn
const seq = message.seq const seq = message.seq
if (type === 'quick-actions' || type === 'quick_actions') { if (type === 'quick-actions' || type === 'quick_actions') {
const actions = Array.isArray(payload.actions) ? payload.actions : QUICK_ACTIONS const actions = mapRobotButtons(
payload.actions ?? payload.buttons ?? payload.buttonList ?? QUICK_ACTIONS,
)
if (!actions.length) return null
return { return {
id, id,
seq, seq,
type: 'quick-actions', type: 'quick-actions',
actions: actions.map((item, index) => { actions,
if (typeof item === 'string') return { id: `action-${index}`, label: item }
const record = item as { id?: string; label?: string }
return { id: record.id || `action-${index}`, label: record.label || '' }
}).filter((item) => item.label),
} }
} }
if (type === 'kb_reply' || type === 'kb' || type === 'robot' || type === 'knowledge') {
const reply = String(
payload.content ?? payload.reply ?? payload.answer ?? payload.text ?? '',
).trim()
if (!reply) return null
return buildBotTextMessage(id, seq, reply, message.createTime)
}
if (type === 'wifi-help' || type === 'wifi_help') { if (type === 'wifi-help' || type === 'wifi_help') {
const steps = Array.isArray(payload.steps) ? payload.steps.map(String) : [] const steps = Array.isArray(payload.steps) ? payload.steps.map(String) : []
return { return {
@@ -569,6 +1027,19 @@ export function mapCsMessage(message: CsMessageVo): SupportMessage | null {
const role = resolveSenderRole(message.senderType) const role = resolveSenderRole(message.senderType)
if (!role || !content) return null if (!role || !content) return null
if (role === 'bot' || role === 'agent') {
const formatted = formatBotTextFields(content)
return {
id: createMessageId(message),
seq: message.seq,
type: 'text',
role,
content: formatted.content,
richHtml: formatted.richHtml,
createTime: message.createTime,
}
}
return { return {
id: createMessageId(message), id: createMessageId(message),
seq: message.seq, seq: message.seq,
@@ -594,7 +1065,17 @@ export function mergeSupportMessages(
} }
map.set(item.id, item) map.set(item.id, item)
} }
return Array.from(map.values()).sort((a, b) => (a.seq ?? 0) - (b.seq ?? 0)) const messageRank = (item: SupportMessage): number => {
if (item.type === 'quick-actions') return 1
return 0
}
const sorted = Array.from(map.values()).sort((a, b) => {
const sa = a.seq ?? 0
const sb = b.seq ?? 0
if (sa !== sb) return sa - sb
return messageRank(a) - messageRank(b)
})
return dedupeKbQuickActionRows(sorted)
} }
export function getMaxSeq(messages: SupportMessage[]): number { export function getMaxSeq(messages: SupportMessage[]): number {

View File

@@ -27,7 +27,10 @@ function resolveFetchUrl(src: string): string {
return normalized return normalized
} }
export function useCsChatImage(getMessages: () => SupportMessage[]) { export function useCsChatImage(
getMessages: () => SupportMessage[],
options?: { onDisplayUpdate?: () => void },
) {
const displaySrcMap = ref<Record<string, string>>({}) const displaySrcMap = ref<Record<string, string>>({})
function displaySrc(item: { id: string; src: string }): string { function displaySrc(item: { id: string; src: string }): string {
@@ -43,6 +46,7 @@ export function useCsChatImage(getMessages: () => SupportMessage[]) {
if (!response.ok) return if (!response.ok) return
const blob = await response.blob() const blob = await response.blob()
displaySrcMap.value = { ...displaySrcMap.value, [id]: URL.createObjectURL(blob) } displaySrcMap.value = { ...displaySrcMap.value, [id]: URL.createObjectURL(blob) }
options?.onDisplayUpdate?.()
} catch { } catch {
// ignore // ignore
} }

View File

@@ -1,10 +1,14 @@
import { onShow } from '@dcloudio/uni-app'
import { getCurrentInstance, nextTick, onMounted, ref, watch, type Ref } from 'vue' import { getCurrentInstance, nextTick, onMounted, ref, watch, type Ref } from 'vue'
import type { SupportMessage } from './support.types' import type { SupportMessage } from './support.types'
const BOTTOM_SCROLL_DELAYS_MS = [0, 80, 200, 400, 700, 1100, 1600, 2200]
export function useSupportChatScroll(messages: Ref<readonly SupportMessage[]>) { export function useSupportChatScroll(messages: Ref<readonly SupportMessage[]>) {
const scrollTop = ref(0) const scrollTop = ref(0)
const scrollIntoView = ref('') const scrollIntoView = ref('')
let scrollJob = 0 let scrollJob = 0
let scrollSequenceToken = 0
function queryChatInnerHeight(): Promise<number> { function queryChatInnerHeight(): Promise<number> {
return new Promise((resolve) => { return new Promise((resolve) => {
@@ -24,6 +28,23 @@ export function useSupportChatScroll(messages: Ref<readonly SupportMessage[]>) {
}) })
} }
async function applyScrollToBottom(scrollTopSalt: number) {
await nextTick()
const innerHeight = await queryChatInnerHeight()
scrollIntoView.value = ''
await nextTick()
if (innerHeight > 0) {
// 递增 scrollTop,确保 H5 scroll-view 在内容变高后仍能滚到底
scrollTop.value = innerHeight + scrollTopSalt
}
await nextTick()
scrollIntoView.value = 'chat-bottom'
}
async function scrollToBottom(delayMs = 0) { async function scrollToBottom(delayMs = 0) {
const job = ++scrollJob const job = ++scrollJob
if (delayMs > 0) { if (delayMs > 0) {
@@ -32,43 +53,52 @@ export function useSupportChatScroll(messages: Ref<readonly SupportMessage[]>) {
}) })
} }
if (job !== scrollJob) return if (job !== scrollJob) return
await applyScrollToBottom(job + 1)
scrollIntoView.value = ''
await nextTick()
const innerHeight = await queryChatInnerHeight()
if (job !== scrollJob) return
if (innerHeight > 0) {
scrollTop.value = innerHeight + job
} }
scrollIntoView.value = 'chat-bottom' function scrollToBottomSequence() {
await nextTick() const token = ++scrollSequenceToken
scrollIntoView.value = '' for (const delayMs of BOTTOM_SCROLL_DELAYS_MS) {
await nextTick() setTimeout(() => {
scrollIntoView.value = 'chat-bottom' if (token !== scrollSequenceToken) return
void applyScrollToBottom(token * 1000 + delayMs)
}, delayMs)
}
}
let scrollDebounceTimer: ReturnType<typeof setTimeout> | null = null
function scheduleScrollToBottom() {
if (scrollDebounceTimer) clearTimeout(scrollDebounceTimer)
scrollDebounceTimer = setTimeout(() => {
scrollDebounceTimer = null
scrollToBottomSequence()
}, 80)
} }
watch( watch(
messages, () => messages.value.length,
() => { (len, prev) => {
void scrollToBottom() if (len > 0 && len !== prev) {
void scrollToBottom(120) scrollToBottomSequence()
void scrollToBottom(320) }
void scrollToBottom(600)
}, },
{ deep: true },
) )
watch(messages, scheduleScrollToBottom, { deep: true })
onMounted(() => { onMounted(() => {
void scrollToBottom(80) scrollToBottomSequence()
void scrollToBottom(400) })
onShow(() => {
scrollToBottomSequence()
}) })
return { return {
scrollTop, scrollTop,
scrollIntoView, scrollIntoView,
scrollToBottom, scrollToBottom,
scrollToBottomSequence,
} }
} }

View File

@@ -0,0 +1,80 @@
import { computed, ref } from 'vue'
import { fetchAllDeviceList } from '@/pages/device/device.api'
import { getErrorMessage } from '@/utils/api-error'
import type { SupportConsultDeviceItem } from './support-device-consult.types'
import {
mapVoToConsultDevice,
matchConsultDeviceKeyword,
} from './support-device-consult.utils'
export function useSupportDeviceConsult() {
const visible = ref(false)
const loading = ref(false)
const keyword = ref('')
const devices = ref<SupportConsultDeviceItem[]>([])
const selectedDeviceId = ref('')
const filteredDevices = computed(() => {
const list = devices.value
const q = keyword.value
if (!q.trim()) return list
return list.filter((item) => matchConsultDeviceKeyword(item, q))
})
const deviceCountText = computed(() => `${devices.value.length} 台`)
async function loadDevices() {
loading.value = true
try {
const rows = await fetchAllDeviceList() ?? []
devices.value = rows
.map((item) => mapVoToConsultDevice(item))
.filter((item): item is SupportConsultDeviceItem => Boolean(item))
if (!selectedDeviceId.value && devices.value.length) {
selectedDeviceId.value = devices.value[0].deviceId
} else if (
selectedDeviceId.value
&& !devices.value.some((item) => item.deviceId === selectedDeviceId.value)
) {
selectedDeviceId.value = devices.value[0]?.deviceId ?? ''
}
} catch (err) {
uni.showToast({ title: getErrorMessage(err, '加载设备失败'), icon: 'none' })
devices.value = []
selectedDeviceId.value = ''
} finally {
loading.value = false
}
}
function openPicker() {
keyword.value = ''
visible.value = true
void loadDevices()
}
function closePicker() {
visible.value = false
}
function selectDevice(deviceId: string) {
selectedDeviceId.value = deviceId
}
function getSelectedDevice(): SupportConsultDeviceItem | undefined {
return devices.value.find((item) => item.deviceId === selectedDeviceId.value)
}
return {
visible,
loading,
keyword,
filteredDevices,
deviceCountText,
selectedDeviceId,
openPicker,
closePicker,
selectDevice,
getSelectedDevice,
}
}

View File

@@ -45,22 +45,31 @@ import {
stopSupportQueueTimer, stopSupportQueueTimer,
} from './support-runtime' } from './support-runtime'
import type { import type {
CsMessageVo,
CsSessionVo, CsSessionVo,
QuickActionItem, QuickActionItem,
SupportHeaderInfo, SupportHeaderInfo,
SupportMessage, SupportMessage,
SupportPhase, SupportPhase,
} from './support.types' } from './support.types'
import {
markKbButtonsDisabledForMessage,
persistKbButtonsForMessage,
} from './support-kb-buttons-cache'
import { import {
createClientMsgId, createClientMsgId,
DEFAULT_QUICK_ACTIONS,
buildQuickActionsMessage, buildQuickActionsMessage,
getMaxSeq, getMaxSeq,
getQueueEstimate, getQueueEstimate,
getQueuePosition, getQueuePosition,
injectTimeDividers, injectTimeDividers,
mapCsMessage, mapActionToSupportMessages,
mapRobotReplyToMessages, mapCsMessageWithFollowups,
mergeSupportMessages, mergeSupportMessages,
normalizeCsRobotVo,
resolveKbButtonsFromRobot,
resolveRobotShortcutAction,
cacheSentImageRefs, cacheSentImageRefs,
normalizeCsMediaUrl, normalizeCsMediaUrl,
normalizeSessionId, normalizeSessionId,
@@ -69,6 +78,8 @@ import {
resolvePhaseFromSession, resolvePhaseFromSession,
unwrapCsActionResponse, unwrapCsActionResponse,
} from './support.utils' } from './support.utils'
import { buildDeviceConsultMessage } from './support-device-consult.utils'
import { useSupportDeviceConsult } from './use-support-device-consult'
const BOT_HEADER: SupportHeaderInfo = { const BOT_HEADER: SupportHeaderInfo = {
name: '智能客服 · 小智', name: '智能客服 · 小智',
@@ -88,6 +99,38 @@ const HUMAN_HEADER: SupportHeaderInfo = {
avatarShape: 'square', avatarShape: 'square',
} }
function isCsBotMessage(message: CsMessageVo): boolean {
const value = String(message.senderType ?? '').toLowerCase()
if (!value) return true
if (
value === '0'
|| value.includes('user')
|| value.includes('app')
|| value.includes('customer')
) {
return false
}
return value === '1' || value.includes('bot') || value.includes('robot')
}
function rememberKbButtonsFromAction(
sessionId: string,
action: { messages?: CsMessageVo[]; robot?: unknown },
) {
const sid = sessionId.trim()
if (!sid) return
const robot = normalizeCsRobotVo(action.robot)
const botMessages = (action.messages ?? []).filter((item) => isCsBotMessage(item))
const target = botMessages[botMessages.length - 1]
if (!target) return
const buttons = resolveKbButtonsFromRobot(robot)
if (!buttons.length) {
markKbButtonsDisabledForMessage(sid, target, robot?.kbId)
return
}
persistKbButtonsForMessage(sid, target, buttons, robot?.kbId)
}
const ENDED_HEADER: SupportHeaderInfo = { const ENDED_HEADER: SupportHeaderInfo = {
name: '智能客服 · 小智', name: '智能客服 · 小智',
badgeText: '已结束', badgeText: '已结束',
@@ -97,7 +140,7 @@ const ENDED_HEADER: SupportHeaderInfo = {
serviceHours: '7×24 小时', serviceHours: '7×24 小时',
} }
const FOOTER_SHORTCUTS = ['常见问题'] const FOOTER_SHORTCUTS = ['常见问题', '订单咨询']
const MESSAGE_SYNC_MIN_GAP_MS = 1500 const MESSAGE_SYNC_MIN_GAP_MS = 1500
@@ -129,6 +172,8 @@ export function useSupport() {
const sending = ref(false) const sending = ref(false)
const lastSeq = ref(0) const lastSeq = ref(0)
const userAvatarUrl = ref('') const userAvatarUrl = ref('')
const faqPanelVisible = ref(false)
const deviceConsult = useSupportDeviceConsult()
let unsubscribeChatPush: (() => void) | null = null let unsubscribeChatPush: (() => void) | null = null
let ensureSessionPromise: Promise<void> | null = null let ensureSessionPromise: Promise<void> | null = null
@@ -230,16 +275,19 @@ export function useSupport() {
} }
function handleChatPush(payload: { function handleChatPush(payload: {
message?: Parameters<typeof mapCsMessage>[0] message?: import('./support.types').CsMessageVo
session?: CsSessionVo session?: CsSessionVo
}) { }) {
if (payload.session && isSupportPageActive()) { if (payload.session && isSupportPageActive()) {
applySessionState(payload.session) applySessionState(payload.session)
} }
if (payload.message) { if (payload.message) {
const mapped = mapCsMessage(payload.message) const mapped = mapCsMessageWithFollowups(
if (mapped) { payload.message,
apiMessages.value = mergeSupportMessages(apiMessages.value, [mapped]) sessionId.value || getCachedCsSessionId(),
)
if (mapped.length) {
apiMessages.value = mergeSupportMessages(apiMessages.value, mapped)
lastSeq.value = getMaxSeq(apiMessages.value) lastSeq.value = getMaxSeq(apiMessages.value)
lastMessageSyncAt = Date.now() lastMessageSyncAt = Date.now()
} }
@@ -264,14 +312,30 @@ export function useSupport() {
disconnectCsChatSocket() disconnectCsChatSocket()
} }
function syncKbButtonsCacheFromAction(
sid: string,
action: ReturnType<typeof unwrapCsActionResponse>,
mapped: SupportMessage[],
) {
rememberKbButtonsFromAction(sid, action)
const robot = normalizeCsRobotVo(action.robot)
const rawBots = (action.messages ?? []).filter((item) => isCsBotMessage(item))
for (let i = 0; i < mapped.length - 1; i += 1) {
const item = mapped[i]
const next = mapped[i + 1]
if (item.type !== 'text' || item.role !== 'bot' || next.type !== 'quick-actions') continue
const raw = rawBots.find((row) => row.seq === item.seq)
if (!raw) continue
persistKbButtonsForMessage(sid, raw, next.actions, robot?.kbId)
}
}
function applyActionMessages(action: ReturnType<typeof unwrapCsActionResponse>) { function applyActionMessages(action: ReturnType<typeof unwrapCsActionResponse>) {
const mapped = [ const mapped = mapActionToSupportMessages(action, sessionId.value)
...(action.messages ?? [])
.map(mapCsMessage)
.filter((item): item is SupportMessage => !!item),
...mapRobotReplyToMessages(action.robot),
]
if (!mapped.length) return if (!mapped.length) return
if (sessionId.value) {
syncKbButtonsCacheFromAction(sessionId.value, action, mapped)
}
apiMessages.value = mergeSupportMessages(apiMessages.value, mapped) apiMessages.value = mergeSupportMessages(apiMessages.value, mapped)
lastSeq.value = getMaxSeq(apiMessages.value) lastSeq.value = getMaxSeq(apiMessages.value)
} }
@@ -326,7 +390,7 @@ export function useSupport() {
const rows = reset const rows = reset
? await fetchAllCsMessages(sid) ? await fetchAllCsMessages(sid)
: await fetchCsMessages(sid, lastSeq.value) : await fetchCsMessages(sid, lastSeq.value)
const mapped = rows.map(mapCsMessage).filter((item): item is SupportMessage => !!item) const mapped = rows.flatMap((row) => mapCsMessageWithFollowups(row, sid))
if (reset) { if (reset) {
apiMessages.value = mapped apiMessages.value = mapped
} else { } else {
@@ -595,8 +659,7 @@ export function useSupport() {
if (action.session) { if (action.session) {
applySessionState(action.session) applySessionState(action.session)
} }
const hasInlineReply = (action.messages?.length ?? 0) > 0 const hasInlineReply = mapActionToSupportMessages(action).length > 0
|| mapRobotReplyToMessages(action.robot).length > 0
if (hasInlineReply) { if (hasInlineReply) {
applyActionMessages(action) applyActionMessages(action)
} else if (!isCsChatSocketConnected()) { } else if (!isCsChatSocketConnected()) {
@@ -613,9 +676,60 @@ export function useSupport() {
} }
} }
function appendLocalUserText(content: string) {
const text = content.trim()
if (!text) return
apiMessages.value = mergeSupportMessages(apiMessages.value, [{
id: `local-text-${createClientMsgId()}`,
type: 'text',
role: 'user',
content: text,
createTime: new Date().toISOString(),
}])
}
async function onRobotShortcutButton(buttonCode: 'resolved' | 'transfer_human') {
if (buttonCode === 'transfer_human') {
await onTransferHuman()
return
}
if (!sessionId.value) {
uni.showToast({ title: '会话未就绪,请稍后重试', icon: 'none' })
return
}
if (sending.value) return
sending.value = true
try {
await clickCsButton(sessionId.value, { buttonCode: 'resolved' })
uni.showToast({ title: '感谢反馈', icon: 'none' })
await syncMessages(false, true)
} catch (err) {
uni.showToast({ title: getErrorMessage(err, '操作失败'), icon: 'none' })
} finally {
sending.value = false
}
}
function onQuickAction(action: QuickActionItem) { function onQuickAction(action: QuickActionItem) {
if (phase.value !== 'bot') return const label = action.label?.trim()
void sendUserMessage(action.label) if (!label) return
if (phase.value === 'queue' || phase.value === 'human') {
uni.showToast({ title: '人工服务中,请直接输入问题', icon: 'none' })
return
}
const shortcut = resolveRobotShortcutAction(action)
if (shortcut) {
faqPanelVisible.value = false
void onRobotShortcutButton(shortcut)
return
}
faqPanelVisible.value = false
if (sending.value) {
uni.showToast({ title: '正在发送,请稍候', icon: 'none' })
return
}
appendLocalUserText(label)
void sendUserMessage(label)
} }
async function onTransferHuman() { async function onTransferHuman() {
@@ -647,7 +761,11 @@ export function useSupport() {
} }
async function startNewSession(keepHistory = false) { async function startNewSession(keepHistory = false) {
if (sending.value || sessionInitializing.value) return if (sending.value) return
if (sessionInitializing.value) {
if (ensureSessionPromise) await ensureSessionPromise
if (sessionInitializing.value) return
}
stopSessionTransport() stopSessionTransport()
clearCachedCsSessionId() clearCachedCsSessionId()
@@ -720,7 +838,10 @@ export function useSupport() {
} }
function appendFaqQuickActions() { function appendFaqQuickActions() {
if (phase.value !== 'bot') return if (phase.value === 'queue' || phase.value === 'human') {
uni.showToast({ title: '人工服务中,请直接输入问题', icon: 'none' })
return
}
const ts = Date.now() const ts = Date.now()
const next: SupportMessage[] = [ const next: SupportMessage[] = [
{ {
@@ -737,12 +858,34 @@ export function useSupport() {
function onFooterShortcut(label: string) { function onFooterShortcut(label: string) {
if (label === '常见问题') { if (label === '常见问题') {
if (phase.value === 'queue' || phase.value === 'human') {
uni.showToast({ title: '人工服务中,请直接输入问题', icon: 'none' })
return
}
faqPanelVisible.value = !faqPanelVisible.value
if (faqPanelVisible.value) {
appendFaqQuickActions() appendFaqQuickActions()
}
return
}
if (label === '订单咨询') {
faqPanelVisible.value = false
deviceConsult.openPicker()
return return
} }
void sendUserMessage(label) void sendUserMessage(label)
} }
function onConfirmDeviceConsult() {
const item = deviceConsult.getSelectedDevice()
if (!item) {
uni.showToast({ title: '请选择要咨询的设备', icon: 'none' })
return
}
deviceConsult.closePicker()
void sendUserMessage(buildDeviceConsultMessage(item))
}
function onDiagnosisSuggestion(label: string) { function onDiagnosisSuggestion(label: string) {
void sendUserMessage(label) void sendUserMessage(label)
} }
@@ -757,7 +900,8 @@ export function useSupport() {
return return
} }
if (text === '常见问题' && phase.value === 'bot') { if (text === '常见问题') {
faqPanelVisible.value = true
appendFaqQuickActions() appendFaqQuickActions()
return return
} }
@@ -825,6 +969,8 @@ export function useSupport() {
sessionEnded, sessionEnded,
formattedQueueWait, formattedQueueWait,
footerShortcuts: FOOTER_SHORTCUTS, footerShortcuts: FOOTER_SHORTCUTS,
faqPanelVisible,
faqActions: DEFAULT_QUICK_ACTIONS,
onQuickAction, onQuickAction,
onTransferHuman, onTransferHuman,
onEndSession, onEndSession,
@@ -835,5 +981,14 @@ export function useSupport() {
onSend, onSend,
onPickImage, onPickImage,
sending, sending,
deviceConsultVisible: deviceConsult.visible,
deviceConsultLoading: deviceConsult.loading,
deviceConsultKeyword: deviceConsult.keyword,
deviceConsultFilteredDevices: deviceConsult.filteredDevices,
deviceConsultDeviceCountText: deviceConsult.deviceCountText,
deviceConsultSelectedDeviceId: deviceConsult.selectedDeviceId,
onDeviceConsultSelect: deviceConsult.selectDevice,
onConfirmDeviceConsult,
onDeviceConsultCancel: deviceConsult.closePicker,
} }
} }

View File

@@ -1,6 +1,7 @@
import { onShow } from '@dcloudio/uni-app' import { onShow } from '@dcloudio/uni-app'
import { computed, ref } from 'vue' import { computed, ref } from 'vue'
import { getErrorMessage } from '@/utils/api-error' import { getErrorMessage } from '@/utils/api-error'
import { ensureLoggedInOnForeground, isAuthSessionExpiredError } from '@/utils/auth-session'
import { fetchMineOverview } from './mine.api' import { fetchMineOverview } from './mine.api'
import type { MineMenuItem } from './mine.types' import type { MineMenuItem } from './mine.types'
@@ -38,6 +39,7 @@ export function useMine() {
phone.value = profile?.phonenumber || profile?.userName || '' phone.value = profile?.phonenumber || profile?.userName || ''
avatarUrl.value = profile?.avatarUrl || '' avatarUrl.value = profile?.avatarUrl || ''
} catch (err) { } catch (err) {
if (isAuthSessionExpiredError(err)) return
uni.showToast({ title: getErrorMessage(err, '加载资料失败'), icon: 'none' }) uni.showToast({ title: getErrorMessage(err, '加载资料失败'), icon: 'none' })
} finally { } finally {
loading.value = false loading.value = false
@@ -67,6 +69,7 @@ export function useMine() {
} }
onShow(() => { onShow(() => {
if (!ensureLoggedInOnForeground()) return
const sys = uni.getSystemInfoSync() const sys = uni.getSystemInfoSync()
statusBarHeight.value = sys.statusBarHeight ?? 0 statusBarHeight.value = sys.statusBarHeight ?? 0
void loadOverview() void loadOverview()

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

View File

@@ -20,7 +20,10 @@ export interface AppMessageVo {
timestamp?: string timestamp?: string
createTime?: string createTime?: string
readFlag?: string | number readFlag?: string | number
homeId?: number | string
homeName?: string homeName?: string
locationName?: string
deviceName?: string
} }
export interface MessageListQuery { export interface MessageListQuery {
@@ -30,6 +33,7 @@ export interface MessageListQuery {
isAsc?: string isAsc?: string
/** 不传-全部,0-未读 */ /** 不传-全部,0-未读 */
readFlag?: string readFlag?: string
homeId?: string | number
} }
export interface MessageTableData<T> { export interface MessageTableData<T> {

View File

@@ -66,9 +66,18 @@ function isAmapOk(status?: string | number): boolean {
return String(status) === '1' return String(status) === '1'
} }
function parseAmapLocation(location?: string): { longitude: number; latitude: number } | null { /** 高德部分字段在 JSON 里会是 [] 而非字符串,需统一转成文本再解析 */
if (!location || location === '[]') return null function amapFieldText(value: unknown): string {
const [lngText, latText] = location.split(',') if (value == null) return ''
if (Array.isArray(value)) return ''
const text = String(value).trim()
return text === '[]' ? '' : text
}
function parseAmapLocation(location?: unknown): { longitude: number; latitude: number } | null {
const text = amapFieldText(location)
if (!text) return null
const [lngText, latText] = text.split(',')
const longitude = Number(lngText) const longitude = Number(lngText)
const latitude = Number(latText) const latitude = Number(latText)
if (!Number.isFinite(longitude) || !Number.isFinite(latitude)) return null if (!Number.isFinite(longitude) || !Number.isFinite(latitude)) return null
@@ -116,12 +125,15 @@ function mapPois(pois: AmapPoi[] | undefined): MapLocationPoint[] {
if (!Array.isArray(pois)) return [] if (!Array.isArray(pois)) return []
const results: MapLocationPoint[] = [] const results: MapLocationPoint[] = []
for (const poi of pois) { for (const poi of pois) {
const name = poi.name?.trim() const name = amapFieldText(poi.name)
if (!name) continue if (!name) continue
const coords = parseAmapLocation(poi.location) const coords = parseAmapLocation(poi.location)
if (!coords) continue if (!coords) continue
const region = [poi.pname, poi.cityname, poi.adname].filter(Boolean).join('') const region = [poi.pname, poi.cityname, poi.adname]
const address = poi.address?.trim() || region || name .map((part) => amapFieldText(part))
.filter(Boolean)
.join('')
const address = amapFieldText(poi.address) || region || name
results.push({ results.push({
name, name,
address, address,
@@ -136,11 +148,11 @@ function mapInputTips(body: AmapInputTipsResponse | null): MapLocationPoint[] {
if (!body || !isAmapOk(body.status) || !Array.isArray(body.tips)) return [] if (!body || !isAmapOk(body.status) || !Array.isArray(body.tips)) return []
const results: MapLocationPoint[] = [] const results: MapLocationPoint[] = []
for (const tip of body.tips) { for (const tip of body.tips) {
const name = tip.name?.trim() const name = amapFieldText(tip.name)
if (!name) continue if (!name) continue
const coords = parseAmapLocation(tip.location) const coords = parseAmapLocation(tip.location)
if (!coords) continue if (!coords) continue
const address = tip.address?.trim() || tip.district?.trim() || name const address = amapFieldText(tip.address) || amapFieldText(tip.district) || name
results.push({ results.push({
name, name,
address, address,
@@ -264,7 +276,8 @@ export async function searchAmapPlaces(
} }
if (city) { if (city) {
textData.city = city textData.city = city
textData.citylimit = 'true' // 仅作范围偏好,避免严格 citylimit 导致模糊词搜不到
textData.citylimit = 'false'
} }
const [aroundBody, tipsBody, textBody] = await Promise.all([ const [aroundBody, tipsBody, textBody] = await Promise.all([
@@ -293,6 +306,29 @@ export async function searchAmapPlaces(
return { places } return { places }
} }
if (city) {
const [fallbackTips, fallbackText] = await Promise.all([
requestAmap<AmapInputTipsResponse>('/v3/assistant/inputtips', {
keywords: trimmed,
datatype: 'all',
...(location ? { location } : {}),
}),
requestAmap<AmapPlaceSearchResponse>('/v3/place/text', {
keywords: trimmed,
offset: '20',
page: '1',
extensions: 'base',
}),
])
const fallbackPlaces = dedupePlaces([
...mapInputTips(fallbackTips),
...mapPois(fallbackText?.pois),
])
if (fallbackPlaces.length) {
return { places: fallbackPlaces }
}
}
const failed = [aroundBody, tipsBody, textBody].find((item) => item && !isAmapOk(item.status)) const failed = [aroundBody, tipsBody, textBody].find((item) => item && !isAmapOk(item.status))
if (failed) { if (failed) {
return { places: [], error: mapAmapError(failed) } return { places: [], error: mapAmapError(failed) }

119
src/utils/auth-session.ts Normal file
View File

@@ -0,0 +1,119 @@
import { teardownMessageInbox } from '@/hooks/use-message-inbox'
import { ApiError } from '@/utils/api-error'
import { clearLocalUserData } from '@/utils/clear-local-user-data'
import { getStoredToken } from '@/utils/auth-token'
export const LOGIN_ROUTE = '/pages/login/index'
const DEFAULT_SESSION_EXPIRED_TOAST = '登录状态异常,请重新登录'
/** 未登录也可访问的页面(忘记密码、协议等) */
const GUEST_ROUTE_PREFIXES = [
'pages/login/',
'pages/register/',
'pages/forgot-password/',
'pages/change-password/',
'pages/agreement/',
]
/** 这些接口的鉴权失败由页面自行处理,不做全局踢登 */
const PUBLIC_AUTH_API_PREFIXES = [
'/app/auth/login/',
'/app/auth/sendSmsCode',
'/app/auth/agreements',
'/app/auth/agreement/detail',
'/app/auth/register',
]
let sessionRedirecting = false
export function isGuestAllowedRoute(route: string): boolean {
const normalized = route.replace(/^\//, '')
return GUEST_ROUTE_PREFIXES.some((prefix) => normalized.startsWith(prefix))
}
export function isPublicAuthApi(path: string): boolean {
const normalized = path.split('?')[0]
return PUBLIC_AUTH_API_PREFIXES.some((prefix) => normalized.startsWith(prefix))
}
export function isAuthSessionExpiredError(err: unknown): boolean {
if (!(err instanceof ApiError)) return false
if (err.code === 401) return true
const message = err.message?.trim() ?? ''
if (!message) return false
return /登录状态|未登录|重新登录|token\s*无效|token\s*过期|认证失败|授权失败|令牌已失效|请先登录/i.test(message)
}
export function resolveAuthSessionExpiredMessage(err: unknown): string {
if (err instanceof ApiError) {
const message = err.message?.trim()
if (message && isAuthSessionExpiredError(err)) return message
}
return DEFAULT_SESSION_EXPIRED_TOAST
}
export function shouldForceLoginOnAuthError(requestPath: string, err: unknown): boolean {
if (!isAuthSessionExpiredError(err)) return false
if (isPublicAuthApi(requestPath)) return false
return true
}
/**
* 清理本地登录态并回到登录页(改密 / 后台重置密码后 token 失效等场景)
*/
export function handleAuthSessionExpired(options?: {
message?: string
requestPath?: string
/** 改密成功等场景:即使当前在忘记密码/设置密码页也强制进入登录页 */
forceNavigateToLogin?: boolean
}): void {
if (options?.requestPath && isPublicAuthApi(options.requestPath)) return
const forceLogin = Boolean(options?.forceNavigateToLogin)
if (sessionRedirecting && !forceLogin) return
sessionRedirecting = true
teardownMessageInbox()
clearLocalUserData({ preservePasswordRecord: true })
const toastTitle = options?.message?.trim() || DEFAULT_SESSION_EXPIRED_TOAST
uni.showToast({ title: toastTitle, icon: 'none', duration: 2000 })
setTimeout(() => {
const pages = getCurrentPages()
const route = pages[pages.length - 1]?.route || ''
if (forceLogin || !isGuestAllowedRoute(route)) {
uni.reLaunch({ url: LOGIN_ROUTE })
}
setTimeout(() => {
sessionRedirecting = false
}, 500)
}, 600)
}
export function notifyAuthSessionExpired(err: unknown, requestPath: string): void {
if (!shouldForceLoginOnAuthError(requestPath, err)) return
handleAuthSessionExpired({
message: resolveAuthSessionExpiredMessage(err),
requestPath,
})
}
/** App 从后台回到前台:无 token 且不在访客页时强制登录 */
export function ensureLoggedInOnForeground(): boolean {
if (getStoredToken()) return true
const pages = getCurrentPages()
const route = pages[pages.length - 1]?.route || ''
if (isGuestAllowedRoute(route)) return false
if (!sessionRedirecting) {
sessionRedirecting = true
uni.reLaunch({ url: LOGIN_ROUTE })
setTimeout(() => {
sessionRedirecting = false
}, 500)
}
return false
}

View File

@@ -0,0 +1,73 @@
import { clearStoredCsToken, clearStoredToken, getStoredCsToken, getStoredToken, saveStoredCsToken, saveStoredToken } from '@/utils/auth-token'
import {
clearPasswordModifiedAt,
exportPasswordModifiedRecord,
PASSWORD_MODIFIED_RECORD_KEY,
restorePasswordModifiedRecord,
} from '@/utils/password-modified-at'
import { clearPushCache } from '@/utils/message-push-cache'
import { clearKbButtonsCache } from '@/pages/mine/support/support-kb-buttons-cache'
import {
clearCachedCsSessionId,
clearCachedHistorySessionId,
resetQueueWaitTracking,
stopSupportMessagePollTimer,
stopSupportPollTimer,
stopSupportQueueTimer,
} from '@/pages/mine/support/support-runtime'
const PENDING_PASSWORD_PHONE_KEY = 'czzj_password_modified_pending_phone'
function clearAllUniStorage(preserveKeys: string[] = []): void {
try {
const { keys = [] } = uni.getStorageInfoSync()
for (const key of keys) {
if (preserveKeys.includes(key)) continue
uni.removeStorageSync(key)
}
} catch {
// ignore
}
}
export interface ClearLocalUserDataOptions {
/** 改密后踢登、同账号重新登录时保留「上次修改」记录 */
preservePasswordRecord?: boolean
}
/** 登出 / 注销 / 登录态失效:清空本地用户数据(含密码修改时间、家庭/geo 缓存等) */
export function clearLocalUserData(options?: ClearLocalUserDataOptions): void {
const preservePassword = Boolean(options?.preservePasswordRecord)
const passwordRecord = preservePassword ? exportPasswordModifiedRecord() : null
const preserveKeys = preservePassword
? [PASSWORD_MODIFIED_RECORD_KEY, PENDING_PASSWORD_PHONE_KEY]
: []
stopSupportPollTimer()
stopSupportMessagePollTimer()
stopSupportQueueTimer()
clearCachedCsSessionId()
clearCachedHistorySessionId()
clearKbButtonsCache()
resetQueueWaitTracking()
clearPushCache()
if (!preservePassword) {
clearPasswordModifiedAt()
}
clearAllUniStorage(preserveKeys)
clearStoredToken()
if (preservePassword) {
restorePasswordModifiedRecord(passwordRecord)
}
}
/**
* 新账号登录成功:清空上一账号本地残留,但保留当前已写入的登录令牌。
*/
export function clearLocalUserDataPreservingAuth(): void {
const token = getStoredToken()
const csToken = getStoredCsToken()
clearLocalUserData({ preservePasswordRecord: true })
if (token) saveStoredToken(token)
if (csToken) saveStoredCsToken(csToken)
}

View File

@@ -1,17 +1,123 @@
const STORAGE_KEY = 'czzj_password_modified_at' import { isSamePhone, normalizePhoneDigits } from '@/utils/validate'
/** 密码修改成功后记录时间戳 */ const LEGACY_STORAGE_KEY = 'czzj_password_modified_at'
export function markPasswordModified(at = Date.now()): void { export const PASSWORD_MODIFIED_RECORD_KEY = 'czzj_password_modified_record'
uni.setStorageSync(STORAGE_KEY, at) const PENDING_BY_PHONE_KEY = 'czzj_password_modified_pending_phone'
const STORAGE_KEY = PASSWORD_MODIFIED_RECORD_KEY
interface PasswordModifiedRecord {
userId: string
at: number
} }
export function getPasswordModifiedAt(): number | null { interface PendingPasswordModifiedRecord {
const value = uni.getStorageSync(STORAGE_KEY) phone: string
if (typeof value === 'number' && value > 0) return value at: number
if (typeof value === 'string' && /^\d+$/.test(value)) return Number(value) }
function readRecord(): PasswordModifiedRecord | null {
try {
const raw = uni.getStorageSync(STORAGE_KEY) as PasswordModifiedRecord | string | number
if (raw && typeof raw === 'object' && 'userId' in raw && 'at' in raw) {
const userId = String((raw as PasswordModifiedRecord).userId).trim()
const at = Number((raw as PasswordModifiedRecord).at)
if (userId && at > 0) return { userId, at }
}
} catch {
// ignore
}
return null return null
} }
/** 移除旧版全局时间戳(不区分账号,会导致注销后新账号误读) */
export function purgeLegacyPasswordModifiedStorage(): void {
try {
uni.removeStorageSync(LEGACY_STORAGE_KEY)
} catch {
// ignore
}
}
/** 密码修改成功后记录时间戳(必须绑定当前 userId) */
export function markPasswordModified(userId: string | number, at = Date.now()): void {
const id = String(userId).trim()
if (!id) return
purgeLegacyPasswordModifiedStorage()
uni.setStorageSync(STORAGE_KEY, { userId: id, at })
}
export function clearPasswordModifiedAt(): void {
purgeLegacyPasswordModifiedStorage()
try {
uni.removeStorageSync(STORAGE_KEY)
uni.removeStorageSync(PENDING_BY_PHONE_KEY)
} catch {
// ignore
}
}
export function exportPasswordModifiedRecord(): PasswordModifiedRecord | null {
return readRecord()
}
export function restorePasswordModifiedRecord(record: PasswordModifiedRecord | null): void {
if (!record?.userId || !record.at) return
uni.setStorageSync(STORAGE_KEY, record)
}
function readPendingByPhone(): PendingPasswordModifiedRecord | null {
try {
const raw = uni.getStorageSync(PENDING_BY_PHONE_KEY) as PendingPasswordModifiedRecord
if (raw && typeof raw === 'object' && raw.phone && raw.at > 0) {
return { phone: normalizePhoneDigits(String(raw.phone)), at: Number(raw.at) }
}
} catch {
// ignore
}
return null
}
/** 未登录改密时先按手机号暂存,登录后由 adoptPendingPasswordModifiedForUser 写入 userId */
export function markPasswordModifiedPendingForPhone(phone: string, at = Date.now()): void {
const normalized = normalizePhoneDigits(phone)
if (!normalized) return
purgeLegacyPasswordModifiedStorage()
uni.setStorageSync(PENDING_BY_PHONE_KEY, { phone: normalized, at })
}
export function adoptPendingPasswordModifiedForUser(
userId: string | number,
phone?: string,
): number | null {
const pending = readPendingByPhone()
const boundPhone = phone?.trim() ? normalizePhoneDigits(phone) : ''
if (!pending || !boundPhone || !isSamePhone(pending.phone, boundPhone)) return null
markPasswordModified(userId, pending.at)
try {
uni.removeStorageSync(PENDING_BY_PHONE_KEY)
} catch {
// ignore
}
return pending.at
}
/** 仅返回与当前 userId 匹配的记录;不匹配则视为残留并清除 */
export function getPasswordModifiedAt(userId?: string | number | null): number | null {
purgeLegacyPasswordModifiedStorage()
const currentUserId = userId != null ? String(userId).trim() : ''
if (!currentUserId) return null
const record = readRecord()
if (!record) return null
if (record.userId !== currentUserId) {
clearPasswordModifiedAt()
return null
}
return record.at
}
/** 展示「上次修改:刚刚 / 3天前」等文案 */ /** 展示「上次修改:刚刚 / 3天前」等文案 */
export function formatPasswordModifiedDesc(at: number | null): string { export function formatPasswordModifiedDesc(at: number | null): string {
if (!at) return '上次修改:暂无记录' if (!at) return '上次修改:暂无记录'

View File

@@ -34,6 +34,8 @@ import iconMineNotify from '@/static/icon-mine-notify@2x.png'
import iconMineOrder from '@/static/icon-mine-order@2x.png' import iconMineOrder from '@/static/icon-mine-order@2x.png'
import iconMineCoupon from '@/static/icon-mine-coupon@2x.png' import iconMineCoupon from '@/static/icon-mine-coupon@2x.png'
import iconMineAddress from '@/static/icon-mine-address@2x.png' import iconMineAddress from '@/static/icon-mine-address@2x.png'
import iconNotifyFilterArrow from '@/static/icon-notify-filter-arrow.png'
import iconSupportTime from '@/static/icon-support-time.png'
export const staticAssets = { export const staticAssets = {
logo: logoCenter, logo: logoCenter,
@@ -71,4 +73,6 @@ export const staticAssets = {
iconMineOrder, iconMineOrder,
iconMineCoupon, iconMineCoupon,
iconMineAddress, iconMineAddress,
iconNotifyFilterArrow,
iconSupportTime,
} as const } as const

View File

@@ -1,11 +1,26 @@
export function normalizePhoneDigits(phone: string): string {
return phone.replace(/\D/g, '')
}
export function isValidPhone(phone: string): boolean { export function isValidPhone(phone: string): boolean {
return /^1\d{10}$/.test(phone.trim()) return /^1\d{10}$/.test(normalizePhoneDigits(phone))
}
/** 比较两个手机号是否相同(忽略空格、分隔符) */
export function isSamePhone(a: string, b: string): boolean {
const left = normalizePhoneDigits(a)
const right = normalizePhoneDigits(b)
if (!left || !right) return false
return left === right
} }
export function isValidSmsCode(code: string): boolean { export function isValidSmsCode(code: string): boolean {
return /^\d{4,6}$/.test(code.trim()) return /^\d{4,6}$/.test(code.trim())
} }
/** 登录页密码为空时的提示 */
export const LOGIN_PASSWORD_EMPTY_TOAST = '密码应为至少8位的数字、字母、特殊符号的组合'
/** 登录时输入校验(兼容历史短密码账号) */ /** 登录时输入校验(兼容历史短密码账号) */
export function isValidPassword(password: string): boolean { export function isValidPassword(password: string): boolean {
return password.length >= 6 && password.length <= 32 return password.length >= 6 && password.length <= 32

12
tmp-peek-product.mjs Normal file
View File

@@ -0,0 +1,12 @@
import fs from 'fs'
const s = fs.readFileSync('tmp-api-docs.json', 'utf8')
for (const k of ['productOptions', 'ProductOption', 'product/list', '/app/device/product', 'CzDeviceProduct', '产品型号']) {
let idx = 0
let n = 0
while (n < 6 && (idx = s.indexOf(k, idx)) !== -1) {
console.log('\n---', k, '@', idx)
console.log(s.slice(Math.max(0, idx - 40), idx + 500))
idx += k.length
n++
}
}