feat:客服

This commit is contained in:
李伊帆
2026-10-16 08:53:45 +08:00
parent e22ebd6bef
commit 03839624ed
42 changed files with 1375 additions and 483 deletions

16
package-lock.json generated
View File

@@ -24,6 +24,7 @@
"@dcloudio/uni-mp-weixin": "3.0.0-5020420260813003", "@dcloudio/uni-mp-weixin": "3.0.0-5020420260813003",
"@dcloudio/uni-mp-xhs": "3.0.0-5020420260813003", "@dcloudio/uni-mp-xhs": "3.0.0-5020420260813003",
"@dcloudio/uni-quickapp-webview": "3.0.0-5020420260813003", "@dcloudio/uni-quickapp-webview": "3.0.0-5020420260813003",
"element-china-area-data": "^6.1.0",
"vue": "^3.4.21", "vue": "^3.4.21",
"vue-i18n": "^9.1.9" "vue-i18n": "^9.1.9"
}, },
@@ -6856,6 +6857,12 @@
"node": ">=10" "node": ">=10"
} }
}, },
"node_modules/china-division": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/china-division/-/china-division-2.7.0.tgz",
"integrity": "sha512-4uUPAT+1WfqDh5jytq7omdCmHNk3j+k76zEG/2IqaGcYB90c2SwcixttcypdsZ3T/9tN1TTpBDoeZn+Yw/qBEA==",
"license": "MIT"
},
"node_modules/chokidar": { "node_modules/chokidar": {
"version": "3.6.0", "version": "3.6.0",
"resolved": "https://registry.npmmirror.com/chokidar/-/chokidar-3.6.0.tgz", "resolved": "https://registry.npmmirror.com/chokidar/-/chokidar-3.6.0.tgz",
@@ -7413,6 +7420,15 @@
"integrity": "sha512-vUNKPrUzw8ByEMOxloq0a71iD/mPuPxVkbDm3G5YhnxTzOw/I6qAg2MUS0cYj/c267lWmw26yW4Vv7foxTxPLg==", "integrity": "sha512-vUNKPrUzw8ByEMOxloq0a71iD/mPuPxVkbDm3G5YhnxTzOw/I6qAg2MUS0cYj/c267lWmw26yW4Vv7foxTxPLg==",
"license": "ISC" "license": "ISC"
}, },
"node_modules/element-china-area-data": {
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/element-china-area-data/-/element-china-area-data-6.1.0.tgz",
"integrity": "sha512-IkpcjwQv2A/2AxFiSoaISZ+oMw1rZCPUSOg5sOCwT5jKc96TaawmKZeY81xfxXsO0QbKxU5LLc6AirhG52hUmg==",
"license": "MIT",
"dependencies": {
"china-division": "^2.7.0"
}
},
"node_modules/emittery": { "node_modules/emittery": {
"version": "0.8.1", "version": "0.8.1",
"resolved": "https://registry.npmmirror.com/emittery/-/emittery-0.8.1.tgz", "resolved": "https://registry.npmmirror.com/emittery/-/emittery-0.8.1.tgz",

View File

@@ -53,6 +53,7 @@
"@dcloudio/uni-mp-weixin": "3.0.0-5020420260813003", "@dcloudio/uni-mp-weixin": "3.0.0-5020420260813003",
"@dcloudio/uni-mp-xhs": "3.0.0-5020420260813003", "@dcloudio/uni-mp-xhs": "3.0.0-5020420260813003",
"@dcloudio/uni-quickapp-webview": "3.0.0-5020420260813003", "@dcloudio/uni-quickapp-webview": "3.0.0-5020420260813003",
"element-china-area-data": "^6.1.0",
"vue": "^3.4.21", "vue": "^3.4.21",
"vue-i18n": "^9.1.9" "vue-i18n": "^9.1.9"
}, },

View File

@@ -1,6 +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 {
connectMessageSocket,
isMessageSocketConnected,
isMessageSocketConnecting,
} from '@/utils/message-socket'
import { getStoredToken } from '@/utils/auth-token' import { getStoredToken } from '@/utils/auth-token'
onLaunch(() => { onLaunch(() => {
@@ -10,8 +15,9 @@ onLaunch(() => {
}) })
onShow(() => { onShow(() => {
if (getStoredToken()) { if (!getStoredToken()) return
setupMessageInbox() if (!isMessageSocketConnected() && !isMessageSocketConnecting()) {
connectMessageSocket()
} }
}) })
</script> </script>

View File

@@ -31,3 +31,11 @@ export function logout() {
method: 'POST', method: 'POST',
}) })
} }
/** POST /app/auth/cancelAccount — 注销账号 */
export function cancelAccount() {
return request<void>({
url: '/app/auth/cancelAccount',
method: 'POST',
})
}

View File

@@ -1,14 +1,30 @@
import { ref } from 'vue' import { computed, ref } from 'vue'
import { fetchUnreadMessageCount } from '@/api/message' import { fetchUnreadMessageCount } from '@/api/message'
import { connectMessageSocket, disconnectMessageSocket, onMessagePush } from '@/utils/message-socket' import {
connectMessageSocket,
disconnectMessageSocket,
isMessageSocketConnected,
isMessageSocketConnecting,
onMessagePush,
} from '@/utils/message-socket'
import {
clearPushCache,
getCachedPushCount,
pushCacheCount,
rememberPushPayload,
} from '@/utils/message-push-cache'
export const unreadMessageCount = ref(0) export const unreadMessageCount = ref(0)
export const hasUnreadMessages = computed(
() => unreadMessageCount.value > 0 || pushCacheCount.value > 0,
)
let inboxInitialized = false let inboxInitialized = false
let refreshingUnread = false let refreshingUnread = false
let lastUnreadRefreshAt = 0 let lastUnreadRefreshAt = 0
let pendingPushUnread = 0
const UNREAD_REFRESH_MIN_GAP_MS = 5000 const UNREAD_REFRESH_MIN_GAP_MS = 15000
export async function refreshUnreadMessageCount(force = false): Promise<number> { export async function refreshUnreadMessageCount(force = false): Promise<number> {
const now = Date.now() const now = Date.now()
@@ -19,30 +35,48 @@ export async function refreshUnreadMessageCount(force = false): Promise<number>
refreshingUnread = true refreshingUnread = true
try { try {
const count = await fetchUnreadMessageCount() const count = await fetchUnreadMessageCount()
unreadMessageCount.value = typeof count === 'number' ? count : Number(count) || 0 const serverCount = typeof count === 'number' ? count : Number(count) || 0
const cached = getCachedPushCount()
if (serverCount > 0) {
pendingPushUnread = 0
unreadMessageCount.value = serverCount
} else {
pendingPushUnread = cached
unreadMessageCount.value = Math.max(serverCount, cached)
}
lastUnreadRefreshAt = Date.now() lastUnreadRefreshAt = Date.now()
} catch { } catch {
unreadMessageCount.value = 0 unreadMessageCount.value = pendingPushUnread
} finally { } finally {
refreshingUnread = false refreshingUnread = false
} }
return unreadMessageCount.value return unreadMessageCount.value
} }
function handleIncomingPush(payload: Parameters<typeof rememberPushPayload>[0]) {
if (!rememberPushPayload(payload)) return
pendingPushUnread = getCachedPushCount()
unreadMessageCount.value = Math.max(unreadMessageCount.value, pendingPushUnread)
}
export function setupMessageInbox() { export function setupMessageInbox() {
connectMessageSocket()
if (!inboxInitialized) { if (!inboxInitialized) {
inboxInitialized = true inboxInitialized = true
onMessagePush(() => { onMessagePush((payload) => {
void refreshUnreadMessageCount() handleIncomingPush(payload)
}) })
void refreshUnreadMessageCount(true) void refreshUnreadMessageCount(true)
return }
if (!isMessageSocketConnected() && !isMessageSocketConnecting()) {
connectMessageSocket()
} }
} }
export function teardownMessageInbox() { export function teardownMessageInbox() {
disconnectMessageSocket() disconnectMessageSocket()
clearPushCache()
unreadMessageCount.value = 0 unreadMessageCount.value = 0
pendingPushUnread = 0
inboxInitialized = false inboxInitialized = false
} }

View File

@@ -39,6 +39,7 @@
"<uses-feature android:name=\"android.hardware.camera.autofocus\"/>", "<uses-feature android:name=\"android.hardware.camera.autofocus\"/>",
"<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.GET_ACCOUNTS\"/>", "<uses-permission android:name=\"android.permission.GET_ACCOUNTS\"/>",
"<uses-permission android:name=\"android.permission.READ_PHONE_STATE\"/>", "<uses-permission android:name=\"android.permission.READ_PHONE_STATE\"/>",
"<uses-permission android:name=\"android.permission.CHANGE_WIFI_STATE\"/>", "<uses-permission android:name=\"android.permission.CHANGE_WIFI_STATE\"/>",
@@ -69,6 +70,9 @@
}, },
"scope.userLocation" : { "scope.userLocation" : {
"desc" : "你的位置信息将用于在地图上选择家庭位置" "desc" : "你的位置信息将用于在地图上选择家庭位置"
},
"scope.record" : {
"desc" : "你的麦克风将用于在线客服语音输入"
} }
}, },
"requiredPrivateInfos" : [ "requiredPrivateInfos" : [

View File

@@ -7,6 +7,8 @@
<base-input v-model="password" icon="lock" type="password" placeholder="请输入密码" /> <base-input v-model="password" icon="lock" type="password" placeholder="请输入密码" />
<base-input v-model="confirmPassword" icon="lock" type="password" placeholder="确认密码" /> <base-input v-model="confirmPassword" icon="lock" type="password" placeholder="确认密码" />
<text class="auth-form-page__hint">8-20位字符,须包含字母、数字、符号中的至少2种。</text>
<view class="auth-form-page__btn"> <view class="auth-form-page__btn">
<primary-button text="确认修改" @click="submit" /> <primary-button text="确认修改" @click="submit" />
</view> </view>
@@ -38,6 +40,14 @@ const { password, confirmPassword, submit } = useChangePassword()
margin-bottom: 48rpx; margin-bottom: 48rpx;
} }
.auth-form-page__hint {
display: block;
margin-top: 16rpx;
font-size: 24rpx;
color: $color-text-secondary;
line-height: 1.5;
}
.auth-form-page__btn { .auth-form-page__btn {
margin-top: 16rpx; margin-top: 16rpx;
} }

View File

@@ -1,18 +1,20 @@
import { onLoad } from '@dcloudio/uni-app' import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue' import { ref } from 'vue'
import { getErrorMessage } from '@/utils/api-error' import { getErrorMessage } from '@/utils/api-error'
import { isValidPassword } from '@/utils/validate' import { isValidStrongPassword } from '@/utils/validate'
import { resetPasswordByToken } from './change-password.api' import { resetPasswordByToken } from './change-password.api'
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 fromPrivacy = ref(false)
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) : ''
fromPrivacy.value = query?.from === 'privacy'
if (!resetToken.value) { if (!resetToken.value) {
uni.showToast({ title: '请先完成验证码校验', icon: 'none' }) uni.showToast({ title: '请先完成验证码校验', icon: 'none' })
setTimeout(() => uni.navigateBack(), 1500) setTimeout(() => uni.navigateBack(), 1500)
@@ -24,8 +26,11 @@ export function useChangePassword() {
uni.showToast({ title: '重置令牌无效', icon: 'none' }) uni.showToast({ title: '重置令牌无效', icon: 'none' })
return return
} }
if (!isValidPassword(password.value)) { if (!isValidStrongPassword(password.value)) {
uni.showToast({ title: '密码至少 6 位', icon: 'none' }) uni.showToast({
title: '密码需8-20位,且包含字母、数字、符号中至少2种',
icon: 'none',
})
return return
} }
if (password.value !== confirmPassword.value) { if (password.value !== confirmPassword.value) {
@@ -40,8 +45,12 @@ export function useChangePassword() {
newPassword: password.value, newPassword: password.value,
confirmPassword: confirmPassword.value, confirmPassword: confirmPassword.value,
}) })
uni.showToast({ title: '修改成功', icon: 'success' }) uni.showToast({ title: '密码修改成功', icon: 'success' })
setTimeout(() => { setTimeout(() => {
if (fromPrivacy.value) {
uni.navigateBack({ delta: 2 })
return
}
uni.reLaunch({ url: '/pages/login/index' }) uni.reLaunch({ url: '/pages/login/index' })
}, 800) }, 800)
} catch (err) { } catch (err) {

View File

@@ -49,6 +49,7 @@
:src="staticAssets.iconNotify" :src="staticAssets.iconNotify"
mode="aspectFit" mode="aspectFit"
/> />
<view v-if="hasUnreadNotify" class="device-header__notify-badge" />
</view> </view>
<view class="device-header__add-wrap"> <view class="device-header__add-wrap">
<view class="device-header__add-btn" @tap.stop="toggleAddMenu"> <view class="device-header__add-btn" @tap.stop="toggleAddMenu">
@@ -72,6 +73,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref } from 'vue' import { ref } from 'vue'
import { hasUnreadMessages } from '@/hooks/use-message-inbox'
import { staticAssets } from '@/utils/static-assets' import { staticAssets } from '@/utils/static-assets'
defineProps<{ defineProps<{
@@ -87,6 +89,7 @@ const emit = defineEmits<{
const pickerOpen = ref(false) const pickerOpen = ref(false)
const addMenuOpen = ref(false) const addMenuOpen = ref(false)
const hasUnreadNotify = hasUnreadMessages
const sys = uni.getSystemInfoSync() const sys = uni.getSystemInfoSync()
const statusBarHeight = sys.statusBarHeight ?? 0 const statusBarHeight = sys.statusBarHeight ?? 0
@@ -242,10 +245,31 @@ function onScan() {
gap: 16rpx; gap: 16rpx;
} }
.device-header__notify-icon { .device-header__notify-wrap {
position: relative;
width: 72rpx; width: 72rpx;
height: 72rpx; height: 72rpx;
flex-shrink: 0; flex-shrink: 0;
display: flex;
align-items: center;
justify-content: center;
}
.device-header__notify-icon {
width: 33rpx;
height: 33rpx;
flex-shrink: 0;
}
.device-header__notify-badge {
position: absolute;
top: 12rpx;
right: 12rpx;
width: 16rpx;
height: 16rpx;
border-radius: 50%;
background: #ff4d4f;
z-index: 2;
} }
.device-header__add-wrap { .device-header__add-wrap {

View File

@@ -1,5 +1,6 @@
import { onUnload } from '@dcloudio/uni-app' import { onUnload } from '@dcloudio/uni-app'
import { ref } from 'vue' import { ref } from 'vue'
import { getErrorMessage } from '@/utils/api-error'
import { import {
closeBleConnection, closeBleConnection,
ensureBleConnection, ensureBleConnection,
@@ -130,22 +131,32 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
const runtimePatch = context.getRuntimePatch() const runtimePatch = context.getRuntimePatch()
const signalLevel = rssiToSignalLevel(foundDevice?.RSSI) const signalLevel = rssiToSignalLevel(foundDevice?.RSSI)
const hasBleData = Object.keys(blePayload).length > 0
await updateDeviceRuntime({ try {
deviceId, await updateDeviceRuntime({
...runtimePatch, deviceId,
...blePayload, ...runtimePatch,
status: '1', ...blePayload,
bluetoothConnected: '1', status: '1',
signalLevel, bluetoothConnected: '1',
}) signalLevel,
})
if (!Object.keys(blePayload).length) { if (!hasBleData) {
setSyncText('蓝牙已连接,等待设备上报数据…') setSyncText('蓝牙已连接,等待设备上报数据…')
} else { } else {
setSyncText('刚刚更新 · 数据实时同步中') setSyncText('刚刚更新 · 数据实时同步中')
}
await context.onSynced?.()
} catch (apiErr) {
if (hasBleData) {
setSyncText('蓝牙已连接 · 本地数据已更新,云端同步失败')
} else {
setSyncText(
`蓝牙已连接 · 云端同步失败:${getErrorMessage(apiErr, '请检查网络')}`,
)
}
} }
await context.onSynced?.()
return true return true
} catch (err) { } catch (err) {
setSyncText(getBluetoothErrorMessage(err)) setSyncText(getBluetoothErrorMessage(err))

View File

@@ -1,7 +1,6 @@
import { import {
findDeviceInBleScan, findDeviceInBleScan,
isBluetoothApiSupported, isBluetoothApiSupported,
rssiToSignalLevel,
scanBluetoothDevices, scanBluetoothDevices,
} from '@/utils/bluetooth' } from '@/utils/bluetooth'
import { sameId } from '@/utils/device-id' import { sameId } from '@/utils/device-id'
@@ -79,26 +78,28 @@ export async function refreshDevicePresence(
}) })
void Promise.allSettled( void Promise.allSettled(
nextDevices targets.map(async (device) => {
.filter((device) => device.deviceId && targets.some((item) => sameId(item.deviceId, device.deviceId))) const found = findDeviceInBleScan(
.map(async (device) => { { mac: device.mac, name: device.name },
const found = findDeviceInBleScan( scanned,
{ mac: device.mac, name: device.name }, { strictName: true },
scanned, )
{ strictName: true }, const present = !!found
) const nextStatus = present ? '1' : '2'
const present = !!found const nextBluetooth = present ? '1' : '0'
try { if (device.status === nextStatus && device.bluetoothConnected === nextBluetooth) {
await updateDeviceRuntime({ return
deviceId: device.deviceId!, }
status: present ? '1' : '2', try {
bluetoothConnected: present ? '1' : '0', await updateDeviceRuntime({
signalLevel: present ? rssiToSignalLevel(found?.RSSI) : '0', deviceId: device.deviceId!,
}) status: nextStatus,
} catch (err) { bluetoothConnected: nextBluetooth,
logPresence('updateRuntime failed', err) })
} } catch (err) {
}), logPresence('updateRuntime failed', err)
}
}),
) )
return nextDevices return nextDevices

View File

@@ -1,5 +1,6 @@
import { onShow } from '@dcloudio/uni-app' import { onShow } from '@dcloudio/uni-app'
import { computed, ref } from 'vue' import { computed, ref } from 'vue'
import { refreshUnreadMessageCount } from '@/hooks/use-message-inbox'
import { fetchHomeList, resolveValidHomeId } from '@/api/home' import { fetchHomeList, resolveValidHomeId } from '@/api/home'
import { parseId, sameId } from '@/utils/device-id' import { parseId, sameId } from '@/utils/device-id'
import { createLocation } from '@/api/location' import { createLocation } from '@/api/location'
@@ -109,6 +110,7 @@ export function useDevice() {
onShow(() => { onShow(() => {
void loadDevices() void loadDevices()
void refreshUnreadMessageCount()
}) })
function showOperationSuccess() { function showOperationSuccess() {

View File

@@ -1,8 +1,8 @@
<template> <template>
<view class="auth-form-page"> <view class="auth-form-page">
<app-navbar title="忘记密码" /> <app-navbar :title="pageTitle" />
<view class="auth-form-page__body"> <view class="auth-form-page__body">
<text class="auth-form-page__heading">忘记密码</text> <text class="auth-form-page__heading">{{ pageTitle }}</text>
<base-input v-model="phone" icon="phone" type="number" placeholder="请输入手机号" :maxlength="11" /> <base-input v-model="phone" icon="phone" type="number" placeholder="请输入手机号" :maxlength="11" />
<base-input v-model="code" icon="shield" type="number" placeholder="请输入验证码" :maxlength="6"> <base-input v-model="code" icon="shield" type="number" placeholder="请输入验证码" :maxlength="6">
@@ -21,7 +21,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { useForgotPassword } from './use-forgot-password' import { useForgotPassword } from './use-forgot-password'
const { phone, code, counting, seconds, onSendCode, nextStep } = useForgotPassword() const { phone, code, counting, seconds, pageTitle, onSendCode, nextStep } = useForgotPassword()
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>

View File

@@ -1,6 +1,9 @@
import { ref } from 'vue' import { onLoad, onShow } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import { fetchProfile } from '@/api/profile'
import { useSmsCode } from '@/hooks/use-sms-code' import { useSmsCode } from '@/hooks/use-sms-code'
import { getErrorMessage } from '@/utils/api-error' import { getErrorMessage } from '@/utils/api-error'
import { getStoredToken } from '@/utils/auth-token'
import { isValidPhone, isValidSmsCode } from '@/utils/validate' import { isValidPhone, isValidSmsCode } from '@/utils/validate'
import { SMS_CODE_SCENE } from '@/types/api' import { SMS_CODE_SCENE } from '@/types/api'
import { verifyForgetPasswordCode } from './forgot-password.api' import { verifyForgetPasswordCode } from './forgot-password.api'
@@ -9,9 +12,29 @@ export function useForgotPassword() {
const phone = ref('') const phone = ref('')
const code = ref('') const code = ref('')
const loading = ref(false) const loading = ref(false)
const fromPrivacy = ref(false)
const { counting, seconds, sendCode } = useSmsCode(SMS_CODE_SCENE.reset) const { counting, seconds, sendCode } = useSmsCode(SMS_CODE_SCENE.reset)
const pageTitle = computed(() => (fromPrivacy.value ? '修改登录密码' : '忘记密码'))
onLoad((query) => {
fromPrivacy.value = query?.from === 'privacy'
})
async function loadBoundPhone() {
if (!getStoredToken()) return
try {
const profile = await fetchProfile()
const bound = profile?.phonenumber || profile?.userName || ''
if (bound) {
phone.value = bound
}
} catch {
// 未登录或加载失败时保持手动输入
}
}
function onSendCode() { function onSendCode() {
sendCode(phone.value) sendCode(phone.value)
} }
@@ -34,7 +57,7 @@ export function useForgotPassword() {
return return
} }
uni.navigateTo({ uni.navigateTo({
url: `/pages/change-password/index?resetToken=${encodeURIComponent(res.resetToken)}`, url: `/pages/change-password/index?resetToken=${encodeURIComponent(res.resetToken)}&from=${fromPrivacy.value ? 'privacy' : 'login'}`,
}) })
} catch (err) { } catch (err) {
uni.showToast({ title: getErrorMessage(err, '验证失败,请重试'), icon: 'none' }) uni.showToast({ title: getErrorMessage(err, '验证失败,请重试'), icon: 'none' })
@@ -43,5 +66,9 @@ export function useForgotPassword() {
} }
} }
return { phone, code, counting, seconds, onSendCode, nextStep } onShow(() => {
void loadBoundPhone()
})
return { phone, code, counting, seconds, pageTitle, onSendCode, nextStep }
} }

View File

@@ -0,0 +1,180 @@
<template>
<view v-if="visible" class="region-picker">
<view class="region-picker__mask" @tap="onCancel" />
<view class="region-picker__panel" @tap.stop>
<view class="region-picker__toolbar">
<text class="region-picker__action" @tap="onCancel">取消</text>
<text class="region-picker__title">选择所在地</text>
<text class="region-picker__action region-picker__action--primary" @tap="onConfirm">
确定
</text>
</view>
<picker-view
class="region-picker__view"
:value="pickerIndexes"
indicator-style="height: 88rpx;"
@change="onPickerChange"
>
<picker-view-column>
<view
v-for="item in provinceList"
:key="`p-${item}`"
class="region-picker__item"
>
{{ item }}
</view>
</picker-view-column>
<picker-view-column>
<view
v-for="item in cityList"
:key="`c-${item}`"
class="region-picker__item"
>
{{ item }}
</view>
</picker-view-column>
<picker-view-column>
<view
v-for="item in districtList"
:key="`d-${item}`"
class="region-picker__item"
>
{{ item }}
</view>
</picker-view-column>
</picker-view>
</view>
</view>
</template>
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import {
findRegionIndexes,
getCityList,
getDistrictList,
getProvinceList,
getRegionByIndexes,
} from './region-data'
const props = defineProps<{
visible: boolean
province: string
city: string
district: string
}>()
const emit = defineEmits<{
'update:visible': [value: boolean]
confirm: [value: { province: string; city: string; district: string }]
}>()
const pickerIndexes = ref<[number, number, number]>([0, 0, 0])
const provinceList = computed(() => getProvinceList())
const cityList = computed(() => getCityList(pickerIndexes.value[0]))
const districtList = computed(() => getDistrictList(pickerIndexes.value[0], pickerIndexes.value[1]))
watch(
() => props.visible,
(show) => {
if (!show) return
pickerIndexes.value = findRegionIndexes(props.province, props.city, props.district)
},
)
function onPickerChange(e: { detail: { value: number[] } }) {
const [provinceIndex, cityIndex, districtIndex] = e.detail.value as [number, number, number]
const [prevProvinceIndex, prevCityIndex] = pickerIndexes.value
if (provinceIndex !== prevProvinceIndex) {
pickerIndexes.value = [provinceIndex, 0, 0]
return
}
if (cityIndex !== prevCityIndex) {
pickerIndexes.value = [provinceIndex, cityIndex, 0]
return
}
pickerIndexes.value = [provinceIndex, cityIndex, districtIndex]
}
function onCancel() {
emit('update:visible', false)
}
function onConfirm() {
emit('confirm', getRegionByIndexes(pickerIndexes.value))
emit('update:visible', false)
}
</script>
<style lang="scss" scoped>
.region-picker {
position: fixed;
inset: 0;
z-index: 600;
display: flex;
flex-direction: column;
justify-content: flex-end;
}
.region-picker__mask {
position: absolute;
inset: 0;
background: rgba(0, 0, 0, 0.55);
}
.region-picker__panel {
position: relative;
background: #fff;
border-radius: 24rpx 24rpx 0 0;
overflow: hidden;
z-index: 1;
padding-bottom: env(safe-area-inset-bottom);
}
.region-picker__toolbar {
display: flex;
align-items: center;
justify-content: space-between;
height: 96rpx;
padding: 0 32rpx;
border-bottom: 1rpx solid #f0f0f0;
}
.region-picker__action {
min-width: 96rpx;
font-size: 30rpx;
color: $color-text-secondary;
line-height: 1;
}
.region-picker__action--primary {
color: $color-primary;
font-weight: 500;
text-align: right;
}
.region-picker__title {
font-size: 32rpx;
font-weight: 600;
color: $color-text;
line-height: 1.2;
}
.region-picker__view {
width: 100%;
height: 480rpx;
}
.region-picker__item {
display: flex;
align-items: center;
justify-content: center;
height: 88rpx;
font-size: 30rpx;
color: $color-text;
line-height: 1.2;
}
</style>

View File

@@ -0,0 +1,61 @@
import { regionData } from 'element-china-area-data'
export interface RegionNode {
label: string
children?: RegionNode[]
}
export const CHINA_REGION_TREE: RegionNode[] = regionData.map((province) => ({
label: province.label,
children: province.children?.map((city) => ({
label: city.label,
children: city.children?.map((district) => ({
label: district.label,
})),
})),
}))
export function getProvinceList(tree: RegionNode[] = CHINA_REGION_TREE): string[] {
return tree.map((item) => item.label)
}
export function getCityList(provinceIndex: number, tree: RegionNode[] = CHINA_REGION_TREE): string[] {
return tree[provinceIndex]?.children?.map((item) => item.label) ?? []
}
export function getDistrictList(
provinceIndex: number,
cityIndex: number,
tree: RegionNode[] = CHINA_REGION_TREE,
): string[] {
return tree[provinceIndex]?.children?.[cityIndex]?.children?.map((item) => item.label) ?? []
}
export function findRegionIndexes(
province: string,
city: string,
district: string,
tree: RegionNode[] = CHINA_REGION_TREE,
): [number, number, number] {
const provinceIndex = Math.max(
0,
tree.findIndex((item) => item.label === province),
)
const cities = tree[provinceIndex]?.children ?? []
const cityIndex = Math.max(0, cities.findIndex((item) => item.label === city))
const districts = cities[cityIndex]?.children ?? []
const districtIndex = Math.max(0, districts.findIndex((item) => item.label === district))
return [provinceIndex, cityIndex, districtIndex]
}
export function getRegionByIndexes(
indexes: [number, number, number],
tree: RegionNode[] = CHINA_REGION_TREE,
): { province: string; city: string; district: string } {
const [provinceIndex, cityIndex, districtIndex] = indexes
const province = tree[provinceIndex]?.label ?? ''
const city = tree[provinceIndex]?.children?.[cityIndex]?.label ?? ''
const district =
tree[provinceIndex]?.children?.[cityIndex]?.children?.[districtIndex]?.label ?? ''
return { province, city, district }
}

View File

@@ -84,26 +84,24 @@
<view class="edit-profile-page__divider" /> <view class="edit-profile-page__divider" />
<picker mode="region" :value="regionValue" @change="onRegionChange"> <view class="edit-profile-page__item" @tap="onOpenRegionPicker">
<view class="edit-profile-page__item"> <text class="edit-profile-page__label">所在地</text>
<text class="edit-profile-page__label">所在地</text> <view class="edit-profile-page__right">
<view class="edit-profile-page__right"> <text
<text class="edit-profile-page__value"
class="edit-profile-page__value" :class="{
:class="{ 'edit-profile-page__value--placeholder': locationText === '未设置',
'edit-profile-page__value--placeholder': locationText === '未设置', }"
}" >
> {{ locationText }}
{{ locationText }} </text>
</text> <image
<image class="edit-profile-page__arrow"
class="edit-profile-page__arrow" :src="staticAssets.iconChevronLeft"
:src="staticAssets.iconChevronLeft" mode="aspectFit"
mode="aspectFit" />
/>
</view>
</view> </view>
</picker> </view>
<view class="edit-profile-page__divider" /> <view class="edit-profile-page__divider" />
@@ -144,6 +142,14 @@
:value="form.nickName" :value="form.nickName"
@confirm="onConfirmNickname" @confirm="onConfirmNickname"
/> />
<region-picker
v-model:visible="regionPickerVisible"
:province="form.province"
:city="form.city"
:district="form.district"
@confirm="onConfirmRegion"
/>
</view> </view>
</template> </template>
@@ -151,6 +157,7 @@
import { staticAssets } from '@/utils/static-assets' import { staticAssets } from '@/utils/static-assets'
import AvatarActionSheet from './components/avatar-action-sheet/index.vue' import AvatarActionSheet from './components/avatar-action-sheet/index.vue'
import NicknameDialog from './components/nickname-dialog/index.vue' import NicknameDialog from './components/nickname-dialog/index.vue'
import RegionPicker from './components/region-picker/index.vue'
import { useEditProfile } from './use-edit-profile' import { useEditProfile } from './use-edit-profile'
const today = new Date().toISOString().slice(0, 10) const today = new Date().toISOString().slice(0, 10)
@@ -162,7 +169,7 @@ const {
maskedPhone, maskedPhone,
genderText, genderText,
locationText, locationText,
regionValue, regionPickerVisible,
avatarSheetVisible, avatarSheetVisible,
nicknameDialogVisible, nicknameDialogVisible,
onOpenAvatarSheet, onOpenAvatarSheet,
@@ -173,7 +180,8 @@ const {
onConfirmNickname, onConfirmNickname,
onPickGender, onPickGender,
onBirthdayChange, onBirthdayChange,
onRegionChange, onOpenRegionPicker,
onConfirmRegion,
onChangePhone, onChangePhone,
onSave, onSave,
} = useEditProfile() } = useEditProfile()

View File

@@ -49,18 +49,13 @@ export function useEditProfile() {
const form = ref<ProfileFormState>(createEmptyForm()) const form = ref<ProfileFormState>(createEmptyForm())
const avatarSheetVisible = ref(false) const avatarSheetVisible = ref(false)
const nicknameDialogVisible = ref(false) const nicknameDialogVisible = ref(false)
const regionPickerVisible = ref(false)
const maskedPhone = computed(() => maskPhone(form.value.phonenumber)) const maskedPhone = computed(() => maskPhone(form.value.phonenumber))
const genderText = computed(() => GENDER_LABELS[form.value.gender] || '未知') const genderText = computed(() => GENDER_LABELS[form.value.gender] || '未知')
const locationText = computed(() => const locationText = computed(() =>
formatLocation(form.value.province, form.value.city, form.value.district), formatLocation(form.value.province, form.value.city, form.value.district),
) )
const regionValue = computed(() => {
const { province, city, district } = form.value
if (province && city && district) return [province, city, district]
return []
})
async function loadProfile() { async function loadProfile() {
if (loading.value) return if (loading.value) return
loading.value = true loading.value = true
@@ -158,11 +153,14 @@ export function useEditProfile() {
form.value.birthday = e.detail.value form.value.birthday = e.detail.value
} }
function onRegionChange(e: { detail: { value: string[] } }) { function onOpenRegionPicker() {
const [province, city, district] = e.detail.value regionPickerVisible.value = true
form.value.province = province || '' }
form.value.city = city || ''
form.value.district = district || '' function onConfirmRegion(value: { province: string; city: string; district: string }) {
form.value.province = value.province
form.value.city = value.city
form.value.district = value.district
} }
function onChangePhone() { function onChangePhone() {
@@ -214,7 +212,7 @@ export function useEditProfile() {
maskedPhone, maskedPhone,
genderText, genderText,
locationText, locationText,
regionValue, regionPickerVisible,
avatarSheetVisible, avatarSheetVisible,
nicknameDialogVisible, nicknameDialogVisible,
onOpenAvatarSheet, onOpenAvatarSheet,
@@ -225,7 +223,8 @@ export function useEditProfile() {
onConfirmNickname, onConfirmNickname,
onPickGender, onPickGender,
onBirthdayChange, onBirthdayChange,
onRegionChange, onOpenRegionPicker,
onConfirmRegion,
onChangePhone, onChangePhone,
onSave, onSave,
} }

View File

@@ -27,35 +27,6 @@
</view> </view>
</view> </view>
<view class="mine-page__stats">
<view
v-for="item in stats"
:key="item.label"
class="mine-page__stat-item"
>
<text class="mine-page__stat-value">{{ item.value }}</text>
<text class="mine-page__stat-label">{{ item.label }}</text>
</view>
</view>
<view class="mine-page__quick">
<view
v-for="action in quickActions"
:key="action.id"
class="mine-page__quick-item"
@tap="onQuickAction(action)"
>
<view class="mine-page__quick-icon">
<image
class="mine-page__quick-icon-img"
:src="action.icon"
mode="aspectFit"
/>
</view>
<text class="mine-page__quick-label">{{ action.label }}</text>
</view>
</view>
<view class="mine-page__menu"> <view class="mine-page__menu">
<template v-for="(item, index) in menuList" :key="item.id"> <template v-for="(item, index) in menuList" :key="item.id">
<view <view
@@ -93,11 +64,8 @@ const {
nickName, nickName,
phone, phone,
avatarUrl, avatarUrl,
stats,
quickActions,
menuList, menuList,
onEditNickname, onEditNickname,
onQuickAction,
onMenuTap, onMenuTap,
} = useMine() } = useMine()
</script> </script>

View File

@@ -1,57 +1,55 @@
.mine-page { .mine-page {
min-height: 100vh; min-height: 100vh;
background: #f5f5f5; background: #fff;
padding-bottom: calc(120rpx + env(safe-area-inset-bottom)); padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
box-sizing: border-box; box-sizing: border-box;
} }
.mine-page__content { .mine-page__content {
padding: 0 24rpx 24rpx; padding: 0 32rpx 24rpx;
} }
.mine-page__profile { .mine-page__profile {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 24rpx; gap: 24rpx;
padding: 16rpx 8rpx 32rpx; padding: 16rpx 0 40rpx;
} }
.mine-page__avatar-wrap { .mine-page__avatar-wrap {
width: 128rpx; width: 120rpx;
height: 128rpx; height: 120rpx;
border: 2rpx dashed #d9d9d9; border-radius: 50%;
border-radius: 20rpx;
padding: 8rpx;
box-sizing: border-box;
flex-shrink: 0; flex-shrink: 0;
background: #fff; overflow: hidden;
background: #f0f0f0;
} }
.mine-page__avatar { .mine-page__avatar {
width: 100%; width: 100%;
height: 100%; height: 100%;
border-radius: 12rpx; border-radius: 50%;
background: #f0f0f0; background: #f0f0f0;
} }
.mine-page__avatar-placeholder { .mine-page__avatar-placeholder {
width: 100%; width: 100%;
height: 100%; height: 100%;
border-radius: 12rpx; border-radius: 50%;
background: #ececec; background: #ececec;
} }
.mine-page__profile-meta { .mine-page__profile-meta {
flex: 1; flex: 1;
min-width: 0; min-width: 0;
padding-top: 8rpx; padding-top: 4rpx;
} }
.mine-page__name-row { .mine-page__name-row {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 10rpx; gap: 10rpx;
margin-bottom: 12rpx; margin-bottom: 10rpx;
} }
.mine-page__nickname { .mine-page__nickname {
@@ -81,82 +79,16 @@
line-height: 1.4; line-height: 1.4;
} }
.mine-page__stats {
display: flex;
background: #fff;
border-radius: 20rpx;
padding: 36rpx 0 32rpx;
margin-bottom: 20rpx;
}
.mine-page__stat-item {
flex: 1;
text-align: center;
}
.mine-page__stat-value {
display: block;
font-size: 44rpx;
font-weight: 600;
color: $color-text;
line-height: 1.1;
margin-bottom: 12rpx;
}
.mine-page__stat-label {
display: block;
font-size: 24rpx;
color: #999;
line-height: 1.3;
}
.mine-page__quick {
display: flex;
background: #fff;
border-radius: 20rpx;
padding: 32rpx 8rpx 28rpx;
margin-bottom: 20rpx;
}
.mine-page__quick-item {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
gap: 16rpx;
}
.mine-page__quick-icon {
width: 48rpx;
height: 48rpx;
display: flex;
align-items: center;
justify-content: center;
}
.mine-page__quick-icon-img {
width: 48rpx;
height: 48rpx;
}
.mine-page__quick-label {
font-size: 24rpx;
color: $color-text;
line-height: 1.3;
}
.mine-page__menu { .mine-page__menu {
background: #fff; background: #fff;
border-radius: 20rpx;
overflow: hidden;
} }
.mine-page__menu-item { .mine-page__menu-item {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
min-height: 108rpx; min-height: 112rpx;
padding: 0 28rpx 0 32rpx; padding: 0 8rpx;
box-sizing: border-box; box-sizing: border-box;
} }
@@ -188,5 +120,4 @@
.mine-page__menu-divider { .mine-page__menu-divider {
height: 1rpx; height: 1rpx;
background: #f0f0f0; background: #f0f0f0;
margin-left: 32rpx;
} }

View File

@@ -48,6 +48,7 @@
<view v-else-if="messages.length && !hasMore" class="notify-page__footer-tip"> <view v-else-if="messages.length && !hasMore" class="notify-page__footer-tip">
没有更多了 没有更多了
</view> </view>
</view> </view>
</scroll-view> </scroll-view>
</view> </view>

View File

@@ -77,7 +77,14 @@
} }
.notify-page__empty, .notify-page__empty,
.notify-page__loading, .notify-page__loading {
margin: 32rpx;
padding: 24rpx;
border-radius: 16rpx;
background: #f7f8fa;
text-align: center;
}
.notify-page__footer-tip { .notify-page__footer-tip {
padding: 80rpx 32rpx; padding: 80rpx 32rpx;
text-align: center; text-align: center;

View File

@@ -1,14 +1,11 @@
import type { AppMessageVo } from '@/types/message' import type { AppMessageVo } from '@/types/message'
import { buildMessageFromPush, normalizeMessageId } from '@/utils/message-push'
export function normalizeMessageId(message: AppMessageVo): string { export { buildMessageFromPush, normalizeMessageId }
const raw = message.messageId
if (raw === undefined || raw === null || raw === '') return ''
return String(raw)
}
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' || flag === false return flag === 0 || flag === '0'
} }
export function formatNotifyTime(message: AppMessageVo): string { export function formatNotifyTime(message: AppMessageVo): string {
@@ -16,7 +13,9 @@ export function formatNotifyTime(message: AppMessageVo): string {
if (!raw) return '' if (!raw) return ''
const text = String(raw).trim() const text = String(raw).trim()
if (/^\d{2}:\d{2}$/.test(text)) return text if (/^\d{2}:\d{2}$/.test(text)) return text
const date = new Date(text)
const date = /^\d{13,}$/.test(text) ? new Date(Number(text)) : new Date(text)
if (Number.isNaN(date.getTime())) return text if (Number.isNaN(date.getTime())) return text
return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}` return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
} }

View File

@@ -1,11 +1,25 @@
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 { fetchMessagePage, markAllMessagesRead, markMessageRead } from '@/api/message' import {
fetchMessagePage,
markAllMessagesRead,
markMessageRead,
} 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 { onMessagePush } from '@/utils/message-socket' import { onMessagePush } from '@/utils/message-socket'
import {
clearPushCache,
forgetCachedMessage,
mergeCachedMessages,
rememberPushPayload,
} from '@/utils/message-push-cache'
import type { AppMessageVo } from '@/types/message' import type { AppMessageVo } from '@/types/message'
import { formatNotifyTime, isUnreadMessage, normalizeMessageId } from './notify.utils' import {
formatNotifyTime,
isUnreadMessage,
normalizeMessageId,
} from './notify.utils'
const PAGE_SIZE = 20 const PAGE_SIZE = 20
@@ -36,17 +50,18 @@ export function useNotify() {
pageNum: pageNum.value, pageNum: pageNum.value,
pageSize: PAGE_SIZE, pageSize: PAGE_SIZE,
}) })
total.value = nextTotal const mergedRows = mergeCachedMessages(rows)
if (reset) { if (reset) {
messages.value = rows messages.value = mergedRows
} else { } else {
const map = new Map<string, AppMessageVo>() const map = new Map<string, AppMessageVo>()
for (const item of [...messages.value, ...rows]) { for (const item of [...messages.value, ...mergedRows]) {
const id = normalizeMessageId(item) const id = normalizeMessageId(item)
if (id) map.set(id, item) if (id) map.set(id, item)
} }
messages.value = Array.from(map.values()) messages.value = Array.from(map.values())
} }
total.value = Math.max(nextTotal, messages.value.length)
const homeName = rows.find((item) => item.homeName)?.homeName const homeName = rows.find((item) => item.homeName)?.homeName
if (homeName) sectionTitle.value = homeName if (homeName) sectionTitle.value = homeName
if (rows.length > 0) { if (rows.length > 0) {
@@ -76,10 +91,11 @@ export function useNotify() {
if (isUnreadMessage(message)) { if (isUnreadMessage(message)) {
try { try {
await markMessageRead(messageId) await markMessageRead(messageId)
forgetCachedMessage(messageId)
messages.value = messages.value.map((item) => messages.value = messages.value.map((item) =>
normalizeMessageId(item) === messageId ? { ...item, readFlag: '1' } : item, normalizeMessageId(item) === messageId ? { ...item, readFlag: '1' } : item,
) )
await refreshUnreadMessageCount() await refreshUnreadMessageCount(true)
} catch (err) { } catch (err) {
uni.showToast({ title: getErrorMessage(err, '标记已读失败'), icon: 'none' }) uni.showToast({ title: getErrorMessage(err, '标记已读失败'), icon: 'none' })
} }
@@ -96,19 +112,33 @@ export function useNotify() {
async function onMarkAllRead() { async function onMarkAllRead() {
try { try {
await markAllMessagesRead() await markAllMessagesRead()
clearPushCache()
messages.value = messages.value.map((item) => ({ ...item, readFlag: '1' })) messages.value = messages.value.map((item) => ({ ...item, readFlag: '1' }))
await refreshUnreadMessageCount() await refreshUnreadMessageCount(true)
uni.showToast({ title: '已全部标为已读', icon: 'none' }) uni.showToast({ title: '已全部标为已读', icon: 'none' })
} catch (err) { } catch (err) {
uni.showToast({ title: getErrorMessage(err, '操作失败'), icon: 'none' }) uni.showToast({ title: getErrorMessage(err, '操作失败'), icon: 'none' })
} }
} }
function prependPushMessage(payload: Parameters<typeof rememberPushPayload>[0]) {
const incoming = rememberPushPayload(payload)
if (!incoming) return
const incomingId = normalizeMessageId(incoming)
const exists = messages.value.some((item) => normalizeMessageId(item) === incomingId)
if (exists) return
messages.value = mergeCachedMessages(messages.value)
total.value = messages.value.length
}
onShow(() => { onShow(() => {
void onRefresh() unsubscribePush?.()
unsubscribePush = onMessagePush(() => { unsubscribePush = onMessagePush((payload) => {
void onRefresh() prependPushMessage(payload)
}) })
void onRefresh()
}) })
onUnload(() => { onUnload(() => {

View File

@@ -1,6 +1,6 @@
import { onShow } from '@dcloudio/uni-app' import { onShow } from '@dcloudio/uni-app'
import { computed, ref } from 'vue' import { computed, ref } from 'vue'
import { logout } from '@/api/auth' 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'
@@ -58,7 +58,7 @@ export function usePrivacy() {
function onItemTap(itemId: string) { function onItemTap(itemId: string) {
if (itemId === 'password') { if (itemId === 'password') {
uni.navigateTo({ url: '/pages/mine/set-password/verify/index' }) uni.navigateTo({ url: '/pages/forgot-password/index?from=privacy' })
return return
} }
if (itemId === 'phone') { if (itemId === 'phone') {
@@ -72,7 +72,17 @@ export function usePrivacy() {
confirmColor: '#f04438', confirmColor: '#f04438',
success: (res) => { success: (res) => {
if (!res.confirm) return if (!res.confirm) return
uni.showToast({ title: '注销功能待对接', icon: 'none' }) void (async () => {
try {
await cancelAccount()
teardownMessageInbox()
clearStoredToken()
uni.showToast({ title: '账号已注销', icon: 'success' })
uni.reLaunch({ url: '/pages/login/index' })
} catch (err) {
uni.showToast({ title: getErrorMessage(err, '注销失败'), icon: 'none' })
}
})()
}, },
}) })
} }

View File

@@ -1,85 +1,18 @@
import { onShow } from '@dcloudio/uni-app' import { onLoad } from '@dcloudio/uni-app'
import { computed, ref } from 'vue' import { ref } from 'vue'
import { fetchProfile } from '@/api/profile'
import { useSmsCode } from '@/hooks/use-sms-code'
import { SMS_CODE_SCENE } from '@/types/api'
import { getErrorMessage } from '@/utils/api-error'
import { isValidSmsCode } from '@/utils/validate'
import { verifySetPasswordCode } from '../set-password.api'
function maskPhone(phone: string): string {
const digits = phone.replace(/\D/g, '')
if (digits.length < 7) return phone
return digits.replace(/(\d{3})\d{4}(\d+)/, '$1****$2')
}
/** 兼容旧入口,统一跳转到忘记密码流程 */
export function useSetPasswordPhone() { export function useSetPasswordPhone() {
const boundPhone = ref('') onLoad(() => {
const code = ref('') uni.redirectTo({ url: '/pages/forgot-password/index?from=privacy' })
const loading = ref(false)
const { counting, seconds, sendCode } = useSmsCode(SMS_CODE_SCENE.reset)
const maskedPhone = computed(() => maskPhone(boundPhone.value))
async function loadBoundPhone() {
try {
const profile = await fetchProfile()
boundPhone.value = profile?.phonenumber || profile?.userName || ''
if (!boundPhone.value) {
uni.showToast({ title: '未绑定手机号', icon: 'none' })
}
} catch (err) {
uni.showToast({ title: getErrorMessage(err, '加载账号信息失败'), icon: 'none' })
}
}
function onSendCode() {
if (!boundPhone.value) {
uni.showToast({ title: '未绑定手机号', icon: 'none' })
return
}
sendCode(boundPhone.value)
}
async function nextStep() {
if (!boundPhone.value) {
uni.showToast({ title: '未绑定手机号', icon: 'none' })
return
}
if (!isValidSmsCode(code.value)) {
uni.showToast({ title: '请输入验证码', icon: 'none' })
return
}
if (loading.value) return
loading.value = true
try {
const res = await verifySetPasswordCode({ phone: boundPhone.value, code: code.value })
if (!res.resetToken) {
uni.showToast({ title: '验证失败,未获取重置令牌', icon: 'none' })
return
}
uni.navigateTo({
url: `/pages/mine/set-password/index?resetToken=${encodeURIComponent(res.resetToken)}`,
})
} catch (err) {
uni.showToast({ title: getErrorMessage(err, '验证失败,请重试'), icon: 'none' })
} finally {
loading.value = false
}
}
onShow(() => {
void loadBoundPhone()
}) })
return { return {
code, code: ref(''),
maskedPhone, maskedPhone: ref(''),
counting, counting: ref(false),
seconds, seconds: ref(0),
onSendCode, onSendCode: () => {},
nextStep, nextStep: () => {},
} }
} }

View File

@@ -1,63 +1,26 @@
import { onLoad } from '@dcloudio/uni-app' import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue' import { ref } from 'vue'
import { getErrorMessage } from '@/utils/api-error'
import { isValidStrongPassword } from '@/utils/validate'
import { resetPasswordByToken } from './set-password.api'
/** 兼容旧入口,统一跳转到忘记密码流程 */
export function useSetPassword() { export function useSetPassword() {
const password = ref('')
const confirmPassword = ref('')
const resetToken = ref('')
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) : '' const resetToken = raw ? decodeURIComponent(raw) : ''
if (!resetToken.value) { if (resetToken) {
uni.showToast({ title: '请先完成身份验证', icon: 'none' }) uni.redirectTo({
setTimeout(() => uni.navigateBack(), 1500) url: `/pages/change-password/index?resetToken=${encodeURIComponent(resetToken)}&from=privacy`,
})
return
} }
uni.redirectTo({ url: '/pages/forgot-password/index?from=privacy' })
}) })
function onForgotPassword() { return {
uni.navigateTo({ url: '/pages/forgot-password/index' }) password: ref(''),
confirmPassword: ref(''),
onForgotPassword: () => {
uni.navigateTo({ url: '/pages/forgot-password/index?from=privacy' })
},
submit: () => {},
} }
async function submit() {
if (!resetToken.value) {
uni.showToast({ title: '重置令牌无效', icon: 'none' })
return
}
if (!isValidStrongPassword(password.value)) {
uni.showToast({
title: '密码需8-20位,且包含字母、数字、符号中至少2种',
icon: 'none',
})
return
}
if (password.value !== confirmPassword.value) {
uni.showToast({ title: '两次密码不一致', icon: 'none' })
return
}
if (loading.value) return
loading.value = true
try {
await resetPasswordByToken({
resetToken: resetToken.value,
newPassword: password.value,
confirmPassword: confirmPassword.value,
})
uni.showToast({ title: '密码修改成功', icon: 'success' })
setTimeout(() => {
uni.navigateBack({ delta: 3 })
}, 1200)
} catch (err) {
uni.showToast({ title: getErrorMessage(err, '修改失败,请重试'), icon: 'none' })
} finally {
loading.value = false
}
}
return { password, confirmPassword, onForgotPassword, submit }
} }

View File

@@ -1,6 +1,13 @@
import { onLoad } from '@dcloudio/uni-app'
/** 兼容旧入口,统一跳转到忘记密码流程 */
export function useSetPasswordVerify() { export function useSetPasswordVerify() {
onLoad(() => {
uni.redirectTo({ url: '/pages/forgot-password/index?from=privacy' })
})
function onPhoneVerify() { function onPhoneVerify() {
uni.navigateTo({ url: '/pages/mine/set-password/phone/index' }) uni.redirectTo({ url: '/pages/forgot-password/index?from=privacy' })
} }
return { onPhoneVerify } return { onPhoneVerify }

View File

@@ -85,9 +85,6 @@
> >
<text>{{ item.content }}</text> <text>{{ item.content }}</text>
</view> </view>
<text v-if="item.time" class="support-page__bubble-time">
{{ item.time }}
</text>
</view> </view>
<view v-if="item.role === 'user'" class="support-page__msg-avatar support-page__msg-avatar--user"> <view v-if="item.role === 'user'" class="support-page__msg-avatar support-page__msg-avatar--user">
@@ -205,7 +202,6 @@
> >
<view class="support-page__image-wrap"> <view class="support-page__image-wrap">
<image class="support-page__image" :src="item.src" mode="aspectFill" /> <image class="support-page__image" :src="item.src" mode="aspectFill" />
<text v-if="item.time" class="support-page__bubble-time">{{ item.time }}</text>
</view> </view>
<view class="support-page__msg-avatar support-page__msg-avatar--user">我</view> <view class="support-page__msg-avatar support-page__msg-avatar--user">我</view>
</view> </view>
@@ -215,6 +211,9 @@
</scroll-view> </scroll-view>
<view class="support-page__footer"> <view class="support-page__footer">
<text class="support-page__secure">
本次会话已加密,客服不会向您索要密码或验证码
</text>
<view class="support-page__footer-shortcuts"> <view class="support-page__footer-shortcuts">
<text <text
v-for="shortcut in footerShortcuts" v-for="shortcut in footerShortcuts"
@@ -226,14 +225,17 @@
</text> </text>
</view> </view>
<view class="support-page__input-row"> <view class="support-page__input-row">
<view class="support-page__mic"> <view class="support-page__mic" @tap="toggleInputMode">
<image <image
v-if="inputMode === 'text'"
class="support-page__mic-icon" class="support-page__mic-icon"
:src="staticAssets.iconSupportMic" :src="staticAssets.iconSupportMic"
mode="aspectFit" mode="aspectFit"
/> />
<text v-else class="support-page__keyboard-icon">⌨</text>
</view> </view>
<view class="support-page__input-wrap">
<view v-if="inputMode === 'text'" class="support-page__input-wrap">
<input <input
v-model="inputValue" v-model="inputValue"
class="support-page__input" class="support-page__input"
@@ -244,24 +246,39 @@
@confirm="onSend" @confirm="onSend"
/> />
</view> </view>
<view class="support-page__tag"> <view
<image v-else
class="support-page__tag-icon" class="support-page__voice-btn"
:src="staticAssets.iconSupportTag" :class="{
mode="aspectFit" 'support-page__voice-btn--holding': voiceHolding,
/> 'support-page__voice-btn--recognizing': voiceRecognizing,
</view> }"
<view class="support-page__send" @tap="onSend"> @touchstart.prevent="onVoiceTouchStart"
<image @touchend.prevent="onVoiceTouchEnd"
class="support-page__send-icon" @touchcancel.prevent="onVoiceTouchCancel"
:src="staticAssets.iconSupportSend" >
mode="aspectFit" <text class="support-page__voice-btn-text">
/> {{ voiceButtonText }}
</text>
</view> </view>
<template v-if="inputMode === 'text'">
<view class="support-page__tag">
<image
class="support-page__tag-icon"
:src="staticAssets.iconSupportTag"
mode="aspectFit"
/>
</view>
<view class="support-page__send" @tap="onSend">
<image
class="support-page__send-icon"
:src="staticAssets.iconSupportSend"
mode="aspectFit"
/>
</view>
</template>
</view> </view>
<text class="support-page__secure">
本次会话已加密,客服不会向您索要密码或验证码
</text>
</view> </view>
</view> </view>
</template> </template>
@@ -270,6 +287,7 @@
import { computed, nextTick, ref, watch } from 'vue' import { computed, nextTick, ref, watch } from 'vue'
import { staticAssets } from '@/utils/static-assets' import { staticAssets } from '@/utils/static-assets'
import { useSupport } from './use-support' import { useSupport } from './use-support'
import { useSupportVoice } from './use-support-voice'
import type { DiagnosisItem } from './support.types' import type { DiagnosisItem } from './support.types'
const { const {
@@ -290,8 +308,29 @@ const {
onSend, onSend,
} = useSupport() } = useSupport()
const {
inputMode,
voiceHolding,
voiceRecognizing,
toggleInputMode,
onVoiceTouchStart,
onVoiceTouchEnd,
onVoiceTouchCancel,
} = useSupportVoice({
onRecognized: (text) => {
inputValue.value = text
onSend()
},
})
const humanAvatarText = computed(() => headerInfo.value.avatarText || '服') const humanAvatarText = computed(() => headerInfo.value.avatarText || '服')
const voiceButtonText = computed(() => {
if (voiceRecognizing.value && !voiceHolding.value) return '识别中...'
if (voiceHolding.value) return '松手 发送'
return '按住 说话'
})
const scrollIntoView = ref('chat-bottom') const scrollIntoView = ref('chat-bottom')
watch( watch(

View File

@@ -209,7 +209,7 @@ $support-danger: #f04438;
} }
&--user { &--user {
border-radius: 16rpx; border-radius: 50%;
background: #d0d5dd; background: #d0d5dd;
color: #fff; color: #fff;
} }
@@ -259,13 +259,6 @@ $support-danger: #f04438;
} }
} }
.support-page__bubble-time {
margin-top: 8rpx;
font-size: 22rpx;
color: $support-text-secondary;
line-height: 1.2;
}
.support-page__quick { .support-page__quick {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
@@ -637,6 +630,34 @@ $support-danger: #f04438;
height: 56rpx; height: 56rpx;
} }
.support-page__keyboard-icon {
font-size: 40rpx;
line-height: 1;
color: $support-text-muted;
}
.support-page__voice-btn {
flex: 1;
height: 72rpx;
border-radius: 36rpx;
background: #f5f6f8;
display: flex;
align-items: center;
justify-content: center;
user-select: none;
&--holding,
&--recognizing {
background: rgba(30, 198, 113, 0.12);
}
}
.support-page__voice-btn-text {
font-size: 28rpx;
color: $support-text;
line-height: 1;
}
.support-page__input-wrap { .support-page__input-wrap {
flex: 1; flex: 1;
height: 72rpx; height: 72rpx;
@@ -687,7 +708,9 @@ $support-danger: #f04438;
} }
.support-page__secure { .support-page__secure {
margin-top: 12rpx; display: block;
margin: 0 0 16rpx;
padding: 0 16rpx;
text-align: center; text-align: center;
font-size: 22rpx; font-size: 22rpx;
color: $support-text-secondary; color: $support-text-secondary;

View File

@@ -128,7 +128,7 @@ export type SupportMessage =
type: 'text' type: 'text'
role: ChatRole role: ChatRole
content: string content: string
time?: string createTime?: string
} }
| { | {
id: string id: string
@@ -165,7 +165,7 @@ export type SupportMessage =
type: 'image' type: 'image'
role: 'user' role: 'user'
src: string src: string
time?: string createTime?: string
} }
export interface SupportHeaderInfo { export interface SupportHeaderInfo {

View File

@@ -91,11 +91,62 @@ export function getQueueEstimate(session: CsSessionVo): string {
return session.estimateWaitTime?.trim() || '正在为您分配人工客服' return session.estimateWaitTime?.trim() || '正在为您分配人工客服'
} }
function formatMessageTime(value?: string): string | undefined { const TIME_DIVIDER_GAP_MS = 5 * 60 * 1000
if (!value) return undefined
function parseMessageTimestamp(value?: string): number | null {
if (!value) return null
const date = new Date(value) const date = new Date(value)
if (Number.isNaN(date.getTime())) return undefined const ts = date.getTime()
return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}` return Number.isNaN(ts) ? null : ts
}
function formatTimeDividerText(value: string): string {
const date = new Date(value)
if (Number.isNaN(date.getTime())) return ''
const hm = `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
const now = new Date()
if (date.toDateString() === now.toDateString()) return hm
const yesterday = new Date(now)
yesterday.setDate(now.getDate() - 1)
if (date.toDateString() === yesterday.toDateString()) return `昨天 ${hm}`
return `${date.getMonth() + 1}月${date.getDate()}日 ${hm}`
}
function getMessageCreateTime(item: SupportMessage): string | undefined {
if (item.type === 'text' || item.type === 'image') return item.createTime
return undefined
}
export function injectTimeDividers(messages: SupportMessage[]): SupportMessage[] {
const result: SupportMessage[] = []
let lastTimestamp = 0
for (const item of messages) {
const createTime = getMessageCreateTime(item)
const timestamp = parseMessageTimestamp(createTime)
const shouldInsertDivider = timestamp !== null
&& (lastTimestamp === 0 || timestamp - lastTimestamp >= TIME_DIVIDER_GAP_MS)
if (shouldInsertDivider && createTime) {
const text = formatTimeDividerText(createTime)
if (text) {
result.push({
id: `time-${timestamp}`,
type: 'time',
text,
})
}
lastTimestamp = timestamp
} else if (timestamp !== null) {
lastTimestamp = timestamp
}
result.push(item)
}
return result
} }
function resolveSenderRole(senderType?: string | number): ChatRole | null { function resolveSenderRole(senderType?: string | number): ChatRole | null {
@@ -183,7 +234,7 @@ function mapStructuredMessage(message: CsMessageVo, payload: Record<string, unkn
type: 'image', type: 'image',
role: 'user', role: 'user',
src, src,
time: formatMessageTime(message.createTime), createTime: message.createTime,
} }
} }
@@ -202,7 +253,7 @@ export function mapCsMessage(message: CsMessageVo): SupportMessage | null {
type: 'image', type: 'image',
role: 'user', role: 'user',
src: content, src: content,
time: formatMessageTime(message.createTime), createTime: message.createTime,
} }
} }
@@ -225,7 +276,7 @@ export function mapCsMessage(message: CsMessageVo): SupportMessage | null {
type: 'text', type: 'text',
role, role,
content, content,
time: formatMessageTime(message.createTime), createTime: message.createTime,
} }
} }

View File

@@ -0,0 +1,336 @@
import { onBeforeUnmount, ref } from 'vue'
type InputMode = 'text' | 'voice'
interface UseSupportVoiceOptions {
onRecognized: (text: string) => void
}
interface SpeechRecognitionInstance {
lang: string
continuous: boolean
interimResults: boolean
start: () => void
stop: () => void
abort: () => void
onresult: ((event: { results: Array<Array<{ transcript?: string }>> }) => void) | null
onerror: ((event: { error?: string }) => void) | null
onend: (() => void) | null
}
const MAX_VOICE_DURATION_MS = 60000
export function useSupportVoice(options: UseSupportVoiceOptions) {
const inputMode = ref<InputMode>('text')
const voiceHolding = ref(false)
const voiceRecognizing = ref(false)
let touchCanceled = false
let recordStopTimer: ReturnType<typeof setTimeout> | null = null
let h5Recognition: SpeechRecognitionInstance | null = null
// #ifdef MP-WEIXIN
let mpRecoManager: {
start: (opts: { duration: number; lang: string }) => void
stop: () => void
onStop?: (res: { result?: string }) => void
onError?: () => void
} | null = null
try {
const plugin = requirePlugin('WechatSI') as {
getRecordRecognitionManager: () => NonNullable<typeof mpRecoManager>
}
mpRecoManager = plugin.getRecordRecognitionManager()
mpRecoManager.onStop = (res) => {
voiceRecognizing.value = false
const text = res.result?.trim()
if (text) {
options.onRecognized(text)
return
}
uni.showToast({ title: '未识别到语音内容', icon: 'none' })
}
mpRecoManager.onError = () => {
voiceRecognizing.value = false
uni.showToast({ title: '语音识别失败', icon: 'none' })
}
} catch {
mpRecoManager = null
}
// #endif
function clearRecordStopTimer() {
if (recordStopTimer) clearTimeout(recordStopTimer)
recordStopTimer = null
}
function resetVoiceState() {
voiceHolding.value = false
voiceRecognizing.value = false
touchCanceled = false
clearRecordStopTimer()
}
function isVoiceSupported(): boolean {
// #ifdef H5
const win = window as Window & {
SpeechRecognition?: new () => SpeechRecognitionInstance
webkitSpeechRecognition?: new () => SpeechRecognitionInstance
}
return !!(win.SpeechRecognition || win.webkitSpeechRecognition)
// #endif
// #ifdef APP-PLUS
return typeof plus !== 'undefined' && !!plus.speech
// #endif
// #ifdef MP-WEIXIN
return !!mpRecoManager
// #endif
return false
}
function ensureRecordPermission(): Promise<boolean> {
return new Promise((resolve) => {
uni.getSetting({
success: (res) => {
if (res.authSetting['scope.record']) {
resolve(true)
return
}
uni.authorize({
scope: 'scope.record',
success: () => resolve(true),
fail: () => {
uni.showModal({
title: '需要麦克风权限',
content: '请在设置中开启麦克风权限后使用语音输入',
confirmText: '去设置',
success: (modalRes) => {
if (modalRes.confirm) {
uni.openSetting({})
}
},
})
resolve(false)
},
})
},
fail: () => resolve(false),
})
})
}
function cleanupH5Recognition() {
if (!h5Recognition) return
try {
h5Recognition.abort()
} catch {
// ignore
}
h5Recognition.onresult = null
h5Recognition.onerror = null
h5Recognition.onend = null
h5Recognition = null
}
async function startH5Voice() {
const win = window as Window & {
SpeechRecognition?: new () => SpeechRecognitionInstance
webkitSpeechRecognition?: new () => SpeechRecognitionInstance
}
const Ctor = win.SpeechRecognition || win.webkitSpeechRecognition
if (!Ctor) {
uni.showToast({ title: '当前浏览器不支持语音输入', icon: 'none' })
resetVoiceState()
return
}
cleanupH5Recognition()
const recognition = new Ctor()
h5Recognition = recognition
recognition.lang = 'zh-CN'
recognition.continuous = false
recognition.interimResults = false
voiceRecognizing.value = true
recognition.onresult = (event) => {
const text = event.results[0]?.[0]?.transcript?.trim()
if (text) options.onRecognized(text)
}
recognition.onerror = (event) => {
if (event.error !== 'aborted') {
uni.showToast({ title: '语音识别失败', icon: 'none' })
}
}
recognition.onend = () => {
voiceRecognizing.value = false
h5Recognition = null
}
try {
recognition.start()
} catch {
voiceRecognizing.value = false
h5Recognition = null
uni.showToast({ title: '无法启动语音识别', icon: 'none' })
}
}
function stopH5Voice() {
if (!h5Recognition) return
try {
h5Recognition.stop()
} catch {
h5Recognition.abort()
}
}
function startAppVoice() {
if (!plus.speech) {
uni.showToast({ title: '当前环境不支持语音输入', icon: 'none' })
return
}
voiceRecognizing.value = true
plus.speech.startRecognize(
{
engine: 'baidu',
lang: 'zh-cn',
punctuation: false,
timeout: 10000,
},
(text) => {
voiceRecognizing.value = false
const result = String(text || '').trim()
if (result) {
options.onRecognized(result)
return
}
uni.showToast({ title: '未识别到语音内容', icon: 'none' })
},
() => {
voiceRecognizing.value = false
uni.showToast({ title: '语音识别失败', icon: 'none' })
},
)
}
async function startMpVoice() {
if (!mpRecoManager) {
uni.showToast({ title: '未配置同声传译插件,暂无法使用语音输入', icon: 'none' })
resetVoiceState()
return
}
const granted = await ensureRecordPermission()
if (!granted) {
resetVoiceState()
return
}
voiceRecognizing.value = true
mpRecoManager.start({ duration: MAX_VOICE_DURATION_MS, lang: 'zh_CN' })
}
function stopMpVoice() {
mpRecoManager?.stop()
}
function cancelVoiceCapture() {
// #ifdef H5
cleanupH5Recognition()
// #endif
// #ifdef APP-PLUS
if (voiceRecognizing.value) {
plus.speech.stopRecognize()
}
// #endif
// #ifdef MP-WEIXIN
mpRecoManager?.stop()
// #endif
voiceRecognizing.value = false
}
function toggleInputMode() {
if (inputMode.value === 'text') {
if (!isVoiceSupported()) {
uni.showToast({ title: '当前环境不支持语音输入', icon: 'none' })
return
}
inputMode.value = 'voice'
return
}
cancelVoiceCapture()
resetVoiceState()
inputMode.value = 'text'
}
async function onVoiceTouchStart() {
if (voiceRecognizing.value) return
touchCanceled = false
voiceHolding.value = true
// #ifdef H5
await startH5Voice()
// #endif
// #ifdef MP-WEIXIN
await startMpVoice()
// #endif
clearRecordStopTimer()
recordStopTimer = setTimeout(() => {
if (voiceHolding.value) {
onVoiceTouchEnd()
}
}, MAX_VOICE_DURATION_MS)
}
function onVoiceTouchEnd() {
if (!voiceHolding.value) return
voiceHolding.value = false
clearRecordStopTimer()
if (touchCanceled) {
cancelVoiceCapture()
return
}
// #ifdef H5
stopH5Voice()
// #endif
// #ifdef APP-PLUS
startAppVoice()
// #endif
// #ifdef MP-WEIXIN
stopMpVoice()
// #endif
}
function onVoiceTouchCancel() {
touchCanceled = true
voiceHolding.value = false
clearRecordStopTimer()
cancelVoiceCapture()
}
onBeforeUnmount(() => {
cancelVoiceCapture()
clearRecordStopTimer()
})
return {
inputMode,
voiceHolding,
voiceRecognizing,
toggleInputMode,
onVoiceTouchStart,
onVoiceTouchEnd,
onVoiceTouchCancel,
}
}

View File

@@ -39,6 +39,7 @@ import {
getMaxSeq, getMaxSeq,
getQueueEstimate, getQueueEstimate,
getQueuePosition, getQueuePosition,
injectTimeDividers,
mapCsMessage, mapCsMessage,
mergeSupportMessages, mergeSupportMessages,
normalizeSessionId, normalizeSessionId,
@@ -124,7 +125,7 @@ export function useSupport() {
estimateText: queueEstimate.value, estimateText: queueEstimate.value,
}) })
} }
return list return injectTimeDividers(list)
}) })
function clearQueueTimer() { function clearQueueTimer() {

View File

@@ -1,29 +1,14 @@
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 { staticAssets } from '@/utils/static-assets'
import { fetchMineOverview } from './mine.api' import { fetchMineOverview } from './mine.api'
import type { MineMenuItem, MineQuickAction } from './mine.types' import type { MineMenuItem } from './mine.types'
const APP_VERSION = 'v3.2.0'
const QUICK_ACTIONS: MineQuickAction[] = [
{ id: 'notify', label: '消息通知', icon: staticAssets.iconMineNotify },
{ id: 'order', label: '我的订单', icon: staticAssets.iconMineOrder },
{ id: 'coupon', label: '优惠券', icon: staticAssets.iconMineCoupon },
{ id: 'address', label: '收货地址', icon: staticAssets.iconMineAddress },
]
const MENU_ITEMS: MineMenuItem[] = [ const MENU_ITEMS: MineMenuItem[] = [
{ id: 'devices', title: '我的设备' }, { id: 'devices', title: '我的设备' },
{ id: 'members', title: '家庭成员' },
{ id: 'scene', title: '场景与自动化' },
{ id: 'service', title: '售后服务' },
{ id: 'support', title: '在线客服' }, { id: 'support', title: '在线客服' },
{ id: 'feedback', title: '帮助与反馈' }, { id: 'storage', title: '储存空间' },
{ id: 'settings', title: '通用设置' },
{ id: 'privacy', title: '隐私与安全' }, { id: 'privacy', title: '隐私与安全' },
{ id: 'about', title: '关于我们', value: APP_VERSION },
] ]
export function useMine() { export function useMine() {
@@ -32,32 +17,13 @@ export function useMine() {
const phone = ref('') const phone = ref('')
const avatarUrl = ref('') const avatarUrl = ref('')
const deviceCount = ref(0) const deviceCount = ref(0)
const memberCount = ref(0)
const warrantyCount = ref(0)
const sceneCount = ref(0)
const statusBarHeight = ref(0) const statusBarHeight = ref(0)
const stats = computed(() => [
{ label: '我的设备', value: deviceCount.value },
{ label: '家庭成员', value: memberCount.value },
{ label: '保修中', value: warrantyCount.value },
])
const menuList = computed(() => const menuList = computed(() =>
MENU_ITEMS.map((item) => { MENU_ITEMS.map((item) => {
if (item.id === 'devices') { if (item.id === 'devices') {
return { ...item, value: `已绑定 ${deviceCount.value} 台` } return { ...item, value: `已绑定 ${deviceCount.value} 台` }
} }
if (item.id === 'members') {
return { ...item, value: `${memberCount.value} 位成员` }
}
if (item.id === 'scene') {
return { ...item, value: `${sceneCount.value} 个场景` }
}
if (item.id === 'service') {
return { ...item, value: '报修 / 退换' }
}
return item return item
}), }),
) )
@@ -82,14 +48,6 @@ export function useMine() {
uni.navigateTo({ url: '/pages/mine/edit/index' }) uni.navigateTo({ url: '/pages/mine/edit/index' })
} }
function onQuickAction(action: MineQuickAction) {
if (action.id === 'notify') {
uni.navigateTo({ url: '/pages/mine/notify/index' })
return
}
uni.showToast({ title: `${action.label}功能开发中`, icon: 'none' })
}
function onMenuTap(item: MineMenuItem) { function onMenuTap(item: MineMenuItem) {
if (item.id === 'devices') { if (item.id === 'devices') {
uni.reLaunch({ url: '/pages/device/index' }) uni.reLaunch({ url: '/pages/device/index' })
@@ -99,16 +57,13 @@ export function useMine() {
uni.navigateTo({ url: '/pages/mine/support/index' }) uni.navigateTo({ url: '/pages/mine/support/index' })
return return
} }
if (item.id === 'settings') { if (item.id === 'storage') {
uni.navigateTo({ url: '/pages/mine/storage/index' }) uni.navigateTo({ url: '/pages/mine/storage/index' })
return return
} }
if (item.id === 'privacy') { if (item.id === 'privacy') {
uni.navigateTo({ url: '/pages/mine/privacy/index' }) uni.navigateTo({ url: '/pages/mine/privacy/index' })
return
} }
if (item.id === 'about') return
uni.showToast({ title: `${item.title}功能开发中`, icon: 'none' })
} }
onShow(() => { onShow(() => {
@@ -122,11 +77,8 @@ export function useMine() {
nickName, nickName,
phone, phone,
avatarUrl, avatarUrl,
stats,
quickActions: QUICK_ACTIONS,
menuList, menuList,
onEditNickname, onEditNickname,
onQuickAction,
onMenuTap, onMenuTap,
} }
} }

BIN
src/static/通知 (1).png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

View File

@@ -0,0 +1,58 @@
import { ref } from 'vue'
import type { AppMessageVo, MessagePushPayload } from '@/types/message'
import { buildMessageFromPush, normalizeMessageId } from '@/utils/message-push'
const cachedPushes = new Map<string, AppMessageVo>()
export const pushCacheCount = ref(0)
function syncCacheCount() {
pushCacheCount.value = cachedPushes.size
}
function resolveCacheId(payload: MessagePushPayload, message: AppMessageVo): string {
const messageId = normalizeMessageId(message)
if (messageId) return messageId
if (payload.alertId != null && payload.alertId !== '') return String(payload.alertId)
const stamp = payload.timestamp || Date.now()
const title = payload.title || payload.content || 'push'
return `${title}-${stamp}`
}
export function rememberPushPayload(payload: MessagePushPayload): AppMessageVo | null {
if (!payload.title && !payload.content && payload.messageId == null && payload.alertId == null) {
return null
}
const message = buildMessageFromPush(payload)
const id = resolveCacheId(payload, message)
message.messageId = id
cachedPushes.set(id, message)
syncCacheCount()
return message
}
export function mergeCachedMessages(rows: AppMessageVo[]): AppMessageVo[] {
const map = new Map<string, AppMessageVo>()
for (const item of rows) {
const id = normalizeMessageId(item)
if (id) map.set(id, item)
}
for (const [id, item] of cachedPushes) {
if (!map.has(id)) map.set(id, item)
}
return Array.from(map.values())
}
export function forgetCachedMessage(messageId: string) {
cachedPushes.delete(messageId)
syncCacheCount()
}
export function clearPushCache() {
cachedPushes.clear()
syncCacheCount()
}
export function getCachedPushCount(): number {
return pushCacheCount.value
}

114
src/utils/message-push.ts Normal file
View File

@@ -0,0 +1,114 @@
import type { AppMessageVo, MessagePushPayload } from '@/types/message'
export function normalizeMessageId(message: AppMessageVo): string {
const raw = message.messageId
if (raw === undefined || raw === null || raw === '') return ''
return String(raw)
}
export function buildMessageFromPush(payload: MessagePushPayload): AppMessageVo {
return {
messageId: payload.messageId,
alertId: payload.alertId,
alertType: payload.alertType,
title: payload.title,
content: payload.content,
deviceId: payload.deviceId,
timestamp: payload.timestamp,
readFlag: '0',
}
}
function asRecord(value: unknown): Record<string, unknown> | null {
if (!value || typeof value !== 'object' || Array.isArray(value)) return null
return value as Record<string, unknown>
}
function pickString(obj: Record<string, unknown>, keys: string[]): string | undefined {
for (const key of keys) {
const value = obj[key]
if (value !== undefined && value !== null && value !== '') {
return String(value)
}
}
return undefined
}
function pickId(obj: Record<string, unknown>, keys: string[]): string | number | undefined {
for (const key of keys) {
const value = obj[key]
if (value !== undefined && value !== null && value !== '') {
return typeof value === 'number' ? value : String(value)
}
}
return undefined
}
export function normalizeMessagePushPayload(
source: Record<string, unknown>,
): MessagePushPayload {
return {
messageId: pickId(source, ['messageId', 'id', 'msgId']),
alertId: pickId(source, ['alertId', 'alert_id']),
alertType: pickString(source, ['alertType', 'alert_type', 'type']),
title: pickString(source, ['title', 'msgTitle', 'subject']),
content: pickString(source, ['content', 'msgContent', 'body', 'message']),
deviceId: pickId(source, ['deviceId', 'device_id']),
timestamp: pickString(source, ['timestamp', 'createTime', 'time']),
}
}
export function parseMessagePushPayload(raw: string): MessagePushPayload | null {
if (!raw || raw === 'ping' || raw === 'pong') return null
try {
const parsed = JSON.parse(raw) as Record<string, unknown>
const type = String(parsed.type ?? '').toLowerCase()
if (type === 'message' || type === 'push' || type === 'notify') {
const nested = asRecord(parsed.data) ?? asRecord(parsed.message) ?? asRecord(parsed.msg)
if (nested) return normalizeMessagePushPayload(nested)
}
const nested = asRecord(parsed.data) ?? asRecord(parsed.message) ?? asRecord(parsed.msg)
if (nested) {
const payload = normalizeMessagePushPayload(nested)
if (payload.title || payload.content || payload.messageId) return payload
}
const direct = normalizeMessagePushPayload(parsed)
if (direct.title || direct.content || direct.messageId || direct.alertId) {
return direct
}
if (import.meta.env.DEV) {
console.log('[Message WS] unknown payload', parsed)
}
return null
} catch {
if (import.meta.env.DEV) {
console.log('[Message WS] invalid json', raw)
}
return null
}
}
export function decodeSocketMessageData(data: unknown): string {
if (typeof data === 'string') return data
if (data instanceof ArrayBuffer) {
return new TextDecoder('utf-8').decode(data)
}
if (ArrayBuffer.isView(data)) {
return new TextDecoder('utf-8').decode(data.buffer)
}
return ''
}
export function getMessagePushToastText(payload: MessagePushPayload): string | null {
const title = payload.title?.trim()
if (title) return title
const content = payload.content?.trim()
if (content) return content.length > 30 ? `${content.slice(0, 30)}...` : content
if (payload.messageId || payload.alertId) return '您有新消息'
return null
}

View File

@@ -1,4 +1,9 @@
import { getStoredToken } from '@/utils/auth-token' import { getStoredToken } from '@/utils/auth-token'
import {
decodeSocketMessageData,
getMessagePushToastText,
parseMessagePushPayload,
} from '@/utils/message-push'
import type { MessagePushPayload } from '@/types/message' import type { MessagePushPayload } from '@/types/message'
const HEARTBEAT_INTERVAL_MS = 25000 const HEARTBEAT_INTERVAL_MS = 25000
@@ -9,6 +14,8 @@ let heartbeatTimer: ReturnType<typeof setInterval> | null = null
let reconnectTimer: ReturnType<typeof setTimeout> | null = null let reconnectTimer: ReturnType<typeof setTimeout> | null = null
let connecting = false let connecting = false
let manualClosed = false let manualClosed = false
let socketOpened = false
let disconnectHandled = false
const listeners = new Set<(payload: MessagePushPayload) => void>() const listeners = new Set<(payload: MessagePushPayload) => void>()
@@ -35,11 +42,15 @@ function stopHeartbeat() {
heartbeatTimer = null heartbeatTimer = null
} }
function sendPing() {
if (!socketOpened || !socketTask) return
socketTask.send({ data: 'ping' })
}
function startHeartbeat() { function startHeartbeat() {
stopHeartbeat() stopHeartbeat()
heartbeatTimer = setInterval(() => { sendPing()
socketTask?.send({ data: 'ping' }) heartbeatTimer = setInterval(sendPing, HEARTBEAT_INTERVAL_MS)
}, HEARTBEAT_INTERVAL_MS)
} }
function clearReconnectTimer() { function clearReconnectTimer() {
@@ -58,20 +69,45 @@ function scheduleReconnect() {
function cleanupSocketTask() { function cleanupSocketTask() {
stopHeartbeat() stopHeartbeat()
socketTask = null socketTask = null
socketOpened = false
connecting = false connecting = false
disconnectHandled = false
}
function handleDisconnect(reason: string) {
if (disconnectHandled) return
disconnectHandled = true
if (import.meta.env.DEV) {
console.log(`[Message WS] ${reason}`)
}
cleanupSocketTask()
if (!manualClosed) {
scheduleReconnect()
}
} }
function handleSocketMessage(raw: string) { function handleSocketMessage(raw: string) {
if (!raw || raw === 'ping' || raw === 'pong') return const payload = parseMessagePushPayload(raw)
try { if (!payload) return
const data = JSON.parse(raw) as MessagePushPayload
listeners.forEach((listener) => listener(data)) if (import.meta.env.DEV) {
if (data.title) { console.log('[Message WS] push', payload)
uni.showToast({ title: data.title, icon: 'none' })
}
} catch {
// ignore invalid payload
} }
listeners.forEach((listener) => listener(payload))
const toastText = getMessagePushToastText(payload)
if (toastText) {
uni.showToast({ title: toastText, icon: 'none' })
}
}
export function isMessageSocketConnected(): boolean {
return socketOpened && !!socketTask
}
export function isMessageSocketConnecting(): boolean {
return connecting || (!!socketTask && !socketOpened)
} }
export function onMessagePush(listener: (payload: MessagePushPayload) => void) { export function onMessagePush(listener: (payload: MessagePushPayload) => void) {
@@ -81,38 +117,47 @@ export function onMessagePush(listener: (payload: MessagePushPayload) => void) {
export function connectMessageSocket() { export function connectMessageSocket() {
const token = getStoredToken() const token = getStoredToken()
if (!token || connecting || socketTask) return if (!token || manualClosed) return
if (socketOpened && socketTask) return
// 握手进行中:不要 close,否则 DevTools 会报 "closed before connection is established"
if (isMessageSocketConnecting()) return
manualClosed = false manualClosed = false
connecting = true connecting = true
disconnectHandled = false
clearReconnectTimer() clearReconnectTimer()
const task = uni.connectSocket({ const task = uni.connectSocket({
url: resolveMessageWsUrl(token), url: resolveMessageWsUrl(token),
complete: () => { fail: (err) => {
connecting = false if (import.meta.env.DEV) {
console.log('[Message WS] connect fail', err)
}
handleDisconnect('connect fail')
}, },
}) })
socketTask = task socketTask = task
task.onOpen(() => { task.onOpen(() => {
socketOpened = true
connecting = false
if (import.meta.env.DEV) {
console.log('[Message WS] connected')
}
startHeartbeat() startHeartbeat()
}) })
task.onMessage((res) => { task.onMessage((res) => {
const raw = typeof res.data === 'string' ? res.data : '' handleSocketMessage(decodeSocketMessageData(res.data))
handleSocketMessage(raw)
}) })
task.onClose(() => { task.onClose(() => {
cleanupSocketTask() handleDisconnect('closed')
scheduleReconnect()
}) })
task.onError(() => { task.onError(() => {
cleanupSocketTask() handleDisconnect('error')
scheduleReconnect()
}) })
} }
@@ -120,9 +165,15 @@ export function disconnectMessageSocket() {
manualClosed = true manualClosed = true
clearReconnectTimer() clearReconnectTimer()
stopHeartbeat() stopHeartbeat()
disconnectHandled = true
if (socketTask) { if (socketTask) {
socketTask.close({}) try {
socketTask.close({})
} catch {
// ignore
}
} }
socketTask = null socketTask = null
socketOpened = false
connecting = false connecting = false
} }

View File

@@ -10,7 +10,7 @@ import iconRunModeInfo from '@/static/组 15227@2x.png'
import iconHomeSelector from '@/static/图标 4.png' import iconHomeSelector from '@/static/图标 4.png'
import iconHomeArrow from '@/static/组 9.png' import iconHomeArrow from '@/static/组 9.png'
import iconHomeSelected from '@/static/完成@2x.png' import iconHomeSelected from '@/static/完成@2x.png'
import iconNotify from '@/static/组 27.png' import iconNotify from '@/static/通知 (1).png'
import iconDeviceEmpty from '@/static/图标 8.png' import iconDeviceEmpty from '@/static/图标 8.png'
import iconDeviceNameEdit from '@/static/图标 9.png' import iconDeviceNameEdit from '@/static/图标 9.png'
import iconBindComplete from '@/static/组 41@2x.png' import iconBindComplete from '@/static/组 41@2x.png'
@@ -57,7 +57,7 @@ export const staticAssets = {
iconHomeArrow, iconHomeArrow,
/** 完成@2x.png — 「我的家」下拉选中图标 */ /** 完成@2x.png — 「我的家」下拉选中图标 */
iconHomeSelected, iconHomeSelected,
/** 组 27.png — 设备页右上角通知 */ /** 通知 (1).png — 设备页右上角通知 */
iconNotify, iconNotify,
/** 图标 8.png — 设备空状态中心图标 */ /** 图标 8.png — 设备空状态中心图标 */
iconDeviceEmpty, iconDeviceEmpty,

View File

@@ -100,6 +100,11 @@ export function splitZ2NotifyRecords(raw: string): string[] {
return [text] return [text]
} }
// 实机单包 Q 应答(含 M= 与 B=)整条解析,避免误拆成碎片
if (text.startsWith('Q;') && /;M=/i.test(text)) {
return [text]
}
// 仅标准多包应答(Q; 开头或独立 FL=/FILTER= 行)才拆分 // 仅标准多包应答(Q; 开头或独立 FL=/FILTER= 行)才拆分
const isMultiRecord = text.startsWith('Q;') const isMultiRecord = text.startsWith('Q;')
|| /(?:^|;)FL=|(?:^|;)FILTER=/.test(text) || /(?:^|;)FL=|(?:^|;)FILTER=/.test(text)
@@ -196,10 +201,9 @@ function parseBatteryValue(value: string): number | undefined {
const raw = Number(matched[1]) const raw = Number(matched[1])
if (!Number.isFinite(raw)) return undefined if (!Number.isFinite(raw)) return undefined
if (raw <= 100) return clampPercent(raw) if (raw <= 100) return clampPercent(raw)
// 实机可能上报 731 表示 73.1% // 实机可能上报 731 表示 73.1%,800 表示 80.0%
const scaled = Math.round(raw / 10) if (raw <= 1000) return clampPercent(Math.round(raw / 10))
if (scaled <= 100) return clampPercent(scaled) return undefined
return clampPercent(raw % 100)
} }
/** 解析单行 Notify,如 `Q;M=L;W=C;A=G` 或 `B=34;P=B` */ /** 解析单行 Notify,如 `Q;M=L;W=C;A=G` 或 `B=34;P=B` */
@@ -269,11 +273,21 @@ export function mergeZ2DeviceState(
export function parseZ2NotifyPayload(lines: string[]): Z2DeviceState { export function parseZ2NotifyPayload(lines: string[]): Z2DeviceState {
let state: Z2DeviceState = {} let state: Z2DeviceState = {}
let batteryFromMainLine: number | undefined
for (const line of lines) { for (const line of lines) {
for (const record of splitZ2NotifyRecords(line)) { for (const record of splitZ2NotifyRecords(line)) {
state = mergeZ2DeviceState(state, parseZ2NotifyLine(record)) const patch = parseZ2NotifyLine(record)
if (/M=/i.test(record) && patch.battery != null) {
batteryFromMainLine = patch.battery
}
state = mergeZ2DeviceState(state, patch)
} }
} }
if (batteryFromMainLine != null) {
state.battery = batteryFromMainLine
}
return state return state
} }

View File

@@ -291,9 +291,12 @@ function writeBleAscii(
function appendNotifyText(buffer: string, chunk: string): string { function appendNotifyText(buffer: string, chunk: string): string {
if (!chunk) return buffer if (!chunk) return buffer
if (!buffer) return chunk const next = chunk.trim()
const needsSeparator = !/[;\r\n]$/.test(buffer) && !/^(B=\d|T=\d|FL=|FILTER=|Q;)/.test(chunk) if (!next) return buffer
return needsSeparator ? `${buffer}${chunk}` : `${buffer}${chunk}` if (!buffer) return next
if (/[;\r\n]$/.test(buffer)) return `${buffer}${next}`
// 分包粘连时补分隔符,避免 B=8 + 0... 被拼成 B=80
return `${buffer};${next}`
} }
function resolveNotifyRecords(buffer: string): string[] { function resolveNotifyRecords(buffer: string): string[] {
@@ -307,7 +310,7 @@ async function collectNotifyLines(
options: { maxWaitMs?: number; idleMs?: number } = {}, options: { maxWaitMs?: number; idleMs?: number } = {},
): Promise<string[]> { ): Promise<string[]> {
const maxWaitMs = options.maxWaitMs ?? 6000 const maxWaitMs = options.maxWaitMs ?? 6000
const idleMs = options.idleMgs ?? 400 const idleMs = options.idleMs ?? 400
let buffer = '' let buffer = ''
let settled = false let settled = false