This commit is contained in:
yin 2026-09-22 18:10:35 +08:00
parent 36fd7eef10
commit 90e89fe984
12 changed files with 1392 additions and 309 deletions

View File

@ -81,6 +81,25 @@ export interface EmployeeInfo {
[key: string]: any [key: string]: any
} }
/**
* 获取用户信息入参(`user.info`)
*/
export interface UserInfoParams {
/** 端标记,后端用于区分会话来源(小程序端固定 mobile) */
device?: string
/**
* 小程序 AppID(**字符串**,形如 `wx3xxxxx`)
*
* 与 `wechat.loginByCode` 的 `appid` 同源:本项目作为开放平台第三方平台模板发布,
* 各仓库授权后 AppID 不同且**运行时才确定**(`wx.getAccountInfoSync()`),
* 上报后由后端 `resolveWechatApp()` 反查 `wms_wechat_app` 授权记录。
*
* ⚠️ 是 AppID 字符串,**不是** `wms_wechat_app.id`(整数主键)。
*/
wechat_appId?: string
[key: string]: any
}
/** 用户信息:后端字段随业务扩展,此处只声明稳定字段,其余用索引签名兜住 */ /** 用户信息:后端字段随业务扩展,此处只声明稳定字段,其余用索引签名兜住 */
export interface UserInfoResult { export interface UserInfoResult {
employees_id?: number employees_id?: number
@ -141,6 +160,52 @@ export interface WechatLoginResult {
user: WechatUserInfo user: WechatUserInfo
} }
/**
* 更新微信账号资料入参(`wechat.updateInfo`)
*
* 后端语义:**仅未绑定真实用户的微信账号**可调用(已绑定账号不支持修改),
* 字段**可部分更新** —— 传哪个改哪个。
*/
export interface WechatUpdateInfoParams {
/** 昵称(≤255 字符) */
nickname?: string
/** 头像 URL(≤500 字符),一般由 `wechat.uploadHeadimg` 回写后带回 */
headimgurl?: string
}
/** 微信账号资料(`wechat.updateInfo` / `wechat.uploadHeadimg` 的返回) */
export interface WechatProfileResult {
/** `wms_user_oauth.id` */
oauth_id: number
/** 更新后的昵称 */
nickname?: string
/** 更新后的头像 URL */
headimgurl?: string
/** 仅 `wechat.uploadHeadimg` 返回,值与 `headimgurl` 相同 */
url?: string
}
/**
* 我的登录码响应(`wechat.getMyLoginCode`)
*
* ⚠️ 实测响应是**扁平**的 —— 业务字段与 `flag/code/message` **同级**,**没有 `data` 包裹**:
* ```json
* { "flag":"success","code":1,"message":"获取成功",
* "login_code":"eyJ1dWlkIjoiMl82NTU5MzIiLCJmb3JtIjoid2VjaGF0In0=","oauth_id":2,"timestamp":1790065001 }
* ```
* (`login_code` 解码后为 `{"uuid":"2_655932","form":"wechat"}`)
*
* 故下面的字段声明的是**响应顶层**字段;调用方(store)按顶层取值,
* 并兼容将来被包进 `data` 的情况。
*/
export interface WechatLoginCodeResult {
/** 登录码:`uuid={id}_{6位随机}`、`form=wechat` 的 JSON base64 */
login_code?: string
/** `wms_user_oauth.id` */
oauth_id?: number
[key: string]: any
}
// ────────────────────────────── 接口 ────────────────────────────── // ────────────────────────────── 接口 ──────────────────────────────
/** 账号密码登录 */ /** 账号密码登录 */
@ -169,11 +234,11 @@ export function register(data: UserRegisterParams): Promise<BizResponse<any>> {
* 也是**微信登录态的探测接口**:未绑定的微信登录(token 里 `id=0`)调用它不会 401, * 也是**微信登录态的探测接口**:未绑定的微信登录(token 里 `id=0`)调用它不会 401,
* 而是返回 `is_bound: false` + 微信层信息。 * 而是返回 `is_bound: false` + 微信层信息。
* *
* @param data 额外入参(默认带 device) * @param data 入参:`device`、**`wechat_appId`**(小程序运行时真实 AppID)
* @param token 显式指定 token —— 微信登录未绑定时 token 只存内存、未落地,需手工带上 * @param token 显式指定 token —— 微信登录未绑定时 token 只存内存、未落地,需手工带上
*/ */
export function getInfo( export function getInfo(
data: Record<string, any> = {}, data: UserInfoParams = {},
token?: string token?: string
): Promise<BizResponse<UserInfoResult>> { ): Promise<BizResponse<UserInfoResult>> {
return request<UserInfoResult>({ return request<UserInfoResult>({
@ -286,3 +351,79 @@ export function wechatPushLoginCode(data: {
redirectOn401: false redirectOn401: false
}) })
} }
/**
* 更新微信账号资料(**微信登录态中间层**:带微信登录态 token 即可,未绑定真实用户也可调用)
*
* 用途:小程序端「未绑定 WMS 账号」时,让用户补全自己的**微信昵称 / 头像**。
* 微信自 2022-10 回收了 `getUserProfile`,头像昵称必须由用户主动提供
* (`<button open-type="chooseAvatar">` + `<input type="nickname">`),
* 拿到后经本接口落到 `wms_user_oauth`。
*
* ⚠️ **已绑定 WMS 账号的微信登录态不支持修改**(后端直接返回失败)——
* 调用方应只在「未绑定」态给出入口(见 `userStore.canEditWechatProfile`)。
*/
export function wechatUpdateInfo(
data: WechatUpdateInfoParams
): Promise<BizResponse<WechatProfileResult>> {
return request<WechatProfileResult>({
url: SYSTEM_URL,
method: 'POST',
params: gatewayParams('wechat.updateInfo'),
data,
auth: true,
// 微信登录态失效时后端用 401 表达:只提示,不清登录态、不跳登录页
redirectOn401: false
})
}
/**
* 上传微信账号头像(**微信登录态中间层**:至少微信登录即可,未绑定也可)
*
* 入参 `image` = **PNG 的 base64**(支持 `data:image/png;base64,` 前缀),**限制 < 500K**;
* 后端校验 PNG 魔数后传 COS,并回写 `wms_user_oauth.headimgurl`,返回可访问 URL。
*
* ⚠️ 微信 `chooseAvatar` 给的是**临时文件路径**且不保证是 PNG,
* 必须先经 `utils/avatar.ts` 的 `avatarFileToPngBase64()` 裁剪 / 转码 / 压体积,
* **不要**直接把它塞进来。
*/
export function wechatUploadHeadimg(data: {
image: string
}): Promise<BizResponse<WechatProfileResult>> {
return request<WechatProfileResult>({
url: SYSTEM_URL,
method: 'POST',
params: gatewayParams('wechat.uploadHeadimg'),
data,
auth: true,
// base64 体积大(上限 500K 图片 → base64 约 680K 字符),比默认 15s 放宽
timeout: 30000,
redirectOn401: false
})
}
/**
* 获取「我的登录码」(**微信登录态中间层**,无入参)
*
* 用途:**电脑端登录** —— 小程序把码展示给用户,电脑端凭它走 `user.loginByCode`
* (ye4s 登录码链路)直接登录为本账号,无需在电脑上输密码。
*
* 后端语义:取当前微信用户 `wms_user_oauth.login_code`,**没有才生成**
* (`uuid={id}_{6位随机}`、`form=wechat` 的 JSON base64)并落库,已有则原样返回
* ⇒ 同一微信账号拿到的码是**稳定的**(不是一次性),可反复展示。
*
* ⚠️ 响应**没有 `data` 包裹**(业务字段在顶层),详见 `WechatLoginCodeResult`。
* ⚠️ **只认微信登录态 token**(JWT 含 `oauth_id`):账号密码登录的 token 会被拒,
* 故界面需按 `userStore.canGetMyLoginCode` 控制入口。
*/
export function wechatGetMyLoginCode(): Promise<BizResponse<WechatLoginCodeResult>> {
return request<WechatLoginCodeResult>({
url: SYSTEM_URL,
method: 'POST',
params: gatewayParams('wechat.getMyLoginCode'),
data: {},
auth: true,
// 登录态失效 / 非微信登录态时后端用 401 表达:只提示,不清登录态、不跳登录页
redirectOn401: false
})
}

View File

@ -20,6 +20,12 @@
"navigationBarTitleText": "我的" "navigationBarTitleText": "我的"
} }
}, },
{
"path": "pages/mine/user-info",
"style": {
"navigationBarTitleText": "用户信息"
}
},
{ {
"path": "pages/login/login", "path": "pages/login/login",
"style": { "style": {
@ -89,6 +95,10 @@
"name": "我的", "name": "我的",
"path": "pages/mine/mine" "path": "pages/mine/mine"
}, },
{
"name": "用户信息",
"path": "pages/mine/user-info"
},
{ {
"name": "公开示例页", "name": "公开示例页",
"path": "pagesA/demo/public" "path": "pagesA/demo/public"

View File

@ -59,13 +59,13 @@
</view> </view>
<!-- 运行信息:用于确认各端编译正常 --> <!-- 运行信息:用于确认各端编译正常 -->
<view class="card"> <!-- <view class="card">
<view class="card__title">运行信息</view> <view class="card__title">运行信息</view>
<up-cell-group :border="false"> <up-cell-group :border="false">
<up-cell title="uview-plus 版本" :value="version" :border="false"></up-cell> <up-cell title="uview-plus 版本" :value="version" :border="false"></up-cell>
<up-cell title="运行平台" :value="platform" :border="false"></up-cell> <up-cell title="运行平台" :value="platform" :border="false"></up-cell>
</up-cell-group> </up-cell-group>
</view> </view> -->
<!-- 登录抽屉:碰到需要登录的接口时会自动弹出(见 utils/request 的 auth 预判) --> <!-- 登录抽屉:碰到需要登录的接口时会自动弹出(见 utils/request 的 auth 预判) -->
<auth-modal></auth-modal> <auth-modal></auth-modal>

View File

@ -1,255 +1,107 @@
<template> <template>
<view class="page"> <view class="page">
<!-- 用户信息:本页唯一的登录入口 —— 未登录点这里弹登录抽屉,未绑定则进绑定 --> <!-- 头部用户信息:本页唯一的登录入口 —— 未登录弹登录抽屉,已登录进「用户信息」二级页 -->
<view class="profile" @click="onProfileTap"> <view class="profile" @click="onProfileTap">
<view class="profile__avatar"> <view class="profile__avatar">
<up-icon name="account" color="#ffffff" size="34"></up-icon> <image
v-if="headimgurl"
class="profile__avatar-img"
:src="headimgurl"
mode="aspectFill"
></image>
<up-icon v-else name="account" color="#ffffff" size="34"></up-icon>
</view> </view>
<view class="profile__info"> <view class="profile__info">
<view class="profile__name">{{ userName }}</view> <view class="profile__name">{{ userName }}</view>
<view class="profile__desc">{{ userDesc }}</view> <view class="profile__desc">{{ userDesc }}</view>
</view> </view>
<!-- 未登录(去登录)或未绑定(去绑定)时都显示箭头,提示头像区可点 --> <up-icon name="arrow-right" color="#ffffff" size="16"></up-icon>
<up-icon
v-if="!userStore.isLogin || userStore.isWechatUnbound"
name="arrow-right"
color="#ffffff"
size="16"
></up-icon>
</view> </view>
<!-- 待绑定提示:微信已登录但未绑定 WMS 账号(绑定可跳过,跳过仍是免登录态) --> <!-- 菜单:细项一律收进二级页面,本页只做入口(避免首页式堆叠) -->
<view v-if="userStore.isWechatUnbound" class="card">
<view class="card__title">待绑定 WMS 账号</view>
<view class="card__note">
当前微信尚未绑定 WMS 账号,绑定后即可使用入库、出库、盘点等全部功能。
</view>
<view class="bind-entry">
<up-button
type="primary"
shape="circle"
text="绑定 WMS 账号"
@click="onOpenBind"
></up-button>
</view>
</view>
<!-- 身份信息:绑定后显示,数据来自 user.info 的 employees[](不改数据库、无额外接口) -->
<view v-if="userStore.isLogin && !userStore.isWechatUnbound" class="card">
<view class="card__title">身份信息</view>
<up-cell-group v-if="identity" :border="false">
<up-cell title="姓名" :value="identity?.real_name || userName" :border="false"></up-cell>
<up-cell title="身份类型" :value="userStore.roleTypeLabel || '-'" :border="false"></up-cell>
<up-cell title="所属组织" :value="identity?.store_name || '-'" :border="false"></up-cell>
<up-cell title="员工 ID" :value="identity ? String(identity.id) : '-'" :border="false"></up-cell>
<up-cell title="授权到期" :value="authEndText" :border="false"></up-cell>
<!-- 仅多身份时出现:身份切换入口 -->
<up-cell
v-if="userStore.hasMultipleEmployees"
title="切换身份"
:value="`${userStore.employees.length} 个可选`"
is-link
:border="false"
@click="onSwitchIdentity"
></up-cell>
</up-cell-group>
<view v-else class="card__note" @click="onRetryInfo">未获取到身份信息,点此重试</view>
</view>
<!-- 功能菜单:登录后由后端菜单驱动;无菜单时整卡不渲染,避免空卡片占位 -->
<view v-if="userStore.isLogin && menuSections.length" class="card">
<view class="card__title">功能菜单</view>
<view v-for="section in menuSections" :key="section.key" class="menu">
<view v-if="section.title" class="menu__title">{{ section.title }}</view>
<up-cell-group :border="false">
<up-cell
v-for="item in section.leaves"
:key="item.key"
:title="item.title"
:icon="item.icon"
is-link
:border="false"
@click="onMenuTap(item)"
></up-cell>
</up-cell-group>
</view>
</view>
<!-- 运行信息与常用项 -->
<view class="card"> <view class="card">
<up-cell-group :border="false"> <up-cell-group :border="false">
<up-cell title="当前版本" :value="version" :border="false"></up-cell> <up-cell
<up-cell title="运行平台" :value="platform" :border="false"></up-cell> title="用户信息"
<up-cell title="清除本地缓存" is-link @click="onClearCache"></up-cell> :value="userInfoSummary"
is-link
:border="false"
@click="onProfileTap"
></up-cell>
<up-cell title="清除本地缓存" is-link :border="false" @click="onClearCache"></up-cell>
</up-cell-group> </up-cell-group>
</view> </view>
<view v-if="userStore.isLogin" class="footer">
<up-button type="info" :plain="true" text="退出登录" @click="onLogout"></up-button>
</view>
<!-- 绑定账号弹窗:与登录页共用 wechat-bind-form(这里不提供「跳过」,是用户主动点的) -->
<up-popup :show="bindVisible" mode="center" :round="16" @close="bindVisible = false">
<view class="bind-popup">
<view class="bind-popup__title">绑定 WMS 账号</view>
<view class="bind-popup__desc">输入 WMS 账号密码完成绑定,绑定后可使用全部功能</view>
<wechat-bind-form submit-text="绑定" @success="onBindSuccess"></wechat-bind-form>
<view class="bind-popup__cancel" @click="bindVisible = false">取消</view>
</view>
</up-popup>
<!-- 登录抽屉:碰到需要登录的接口时自动弹出,也可由按钮主动唤起 --> <!-- 登录抽屉:碰到需要登录的接口时自动弹出,也可由按钮主动唤起 -->
<auth-modal></auth-modal> <auth-modal></auth-modal>
</view> </view>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { computed, ref } from 'vue' /**
* 我的(tabBar 页)
*
* 职责收敛为「登录入口 + 菜单」两件事:
* - 头部用户信息区 = **唯一的登录入口**(未登录点击弹抽屉;已登录进「用户信息」页)
* - 菜单里的细项(身份信息 / 待绑定 / 微信资料 / 电脑端登录码 / **退出登录**)全部移到
* 二级页 `pages/mine/user-info`,本页不再堆卡片
*/
import { computed } from 'vue'
import { onShow } from '@dcloudio/uni-app' import { onShow } from '@dcloudio/uni-app'
import { useUserStore } from '@/store/modules/user' import { useUserStore } from '@/store/modules/user'
import { usePermissionStore } from '@/store/modules/permission'
import { usePageAuth } from '@/composables/usePageAuth' import { usePageAuth } from '@/composables/usePageAuth'
import { toSections } from '@/router/entries'
import type { EntryLeaf } from '@/router/entries'
import { getToken } from '@/utils/auth' import { getToken } from '@/utils/auth'
import { navigateToPath } from '@/utils/navigate' import { navigateToPath } from '@/utils/navigate'
import WechatBindForm from '@/components/wechat-bind-form/wechat-bind-form.vue' import { getPageByKey } from '@/router/pages'
import AuthModal from '@/components/auth-modal/auth-modal.vue' import AuthModal from '@/components/auth-modal/auth-modal.vue'
const version = ref(uni.$u.config.v) /** 「用户信息」二级页的逻辑路径(物理路径从 PAGE_REGISTRY 取,避免两处漂移) */
const platform = ref(uni.getSystemInfoSync().uniPlatform) const USER_INFO_KEY = '/mine/user-info'
const userStore = useUserStore() const userStore = useUserStore()
const permissionStore = usePermissionStore()
/** 本页是公共页面(auth: 'optional'),登录入口统一走 usePageAuth:登录**就地弹抽屉** */
const { goLogin } = usePageAuth('optional')
/** 微信头像(设置过才有,未设置时回退占位图标) */
const headimgurl = computed(() => userStore.headimgurl)
const userName = computed(() => { const userName = computed(() => {
if (!userStore.isLogin) return '未登录' if (!userStore.isLogin) return '未登录'
// 微信已登录但未绑定:没有业务姓名可展示,也不能说“已登录”(功能不完整) // 微信已登录但未绑定:优先展示用户自己设置的微信昵称
if (userStore.isWechatUnbound) return '微信用户' if (userStore.isWechatUnbound) return userStore.wechatNickname || '微信用户'
return userStore.userName || '已登录' return userStore.userName || '已登录'
}) })
/** 当前身份(登录后由 user.info 的 employees[] 计算得出) */
const identity = computed(() => userStore.currentEmployee)
/** 授权到期展示:后端 null / 空 表示长期有效 */
const authEndText = computed(() => {
const end = identity.value?.auth_end
if (!end) return '长期有效'
return String(end).slice(0, 10)
})
const userDesc = computed(() => { const userDesc = computed(() => {
if (!userStore.isLogin) return '点击登录后使用完整功能' if (!userStore.isLogin) return '点击登录后使用完整功能'
if (userStore.isWechatUnbound) return '微信已登录 · 待绑定 WMS 账号' if (userStore.isWechatUnbound) return '微信已登录 · 待绑定 WMS 账号'
const parts = [userStore.roleTypeLabel, identity.value?.store_name].filter(Boolean) const parts = [userStore.roleTypeLabel, userStore.currentEmployee?.store_name].filter(Boolean)
return parts.length ? parts.join(' · ') : '已登录' return parts.length ? parts.join(' · ') : '已登录'
}) })
/** 菜单「用户信息」行右侧摘要:不进二级页也能看出当前状态 */
const userInfoSummary = computed(() => {
if (!userStore.isLogin) return '未登录'
if (userStore.isWechatUnbound) return '待绑定'
return userStore.userName || '已登录'
})
/** /**
* 手动重试:强制重拉 `user.info` * 头部 / 菜单「用户信息」点击
* *
* 正常路径下本页**不主动请求** —— 数据由 `App.vue` 启动时(或登录 / 绑定 / 切身份时) * 未登录 → 弹登录抽屉(**不跳登录页**,与「登录由用户主动触发」的约定一致);
* 统一拉好存在 store,本页只负责渲染。只有拉取失败时用户才会看到重试入口。 * 已登录 → 进二级页。跳转用 `navigateToPath`,由它决定 `switchTab` 还是 `navigateTo`。
*/ */
const onRetryInfo = () => {
userStore.getInfo(true).catch(() => {
// 失败提示由 request 层统一 toast
})
}
/**
* 选择要切换到的身份
* 入口仅在多身份时出现;用 `showActionSheet` 避免额外页面与组件
*/
const onSwitchIdentity = () => {
const list = userStore.employees
if (list.length < 2) return
// 微信 showActionSheet 的 itemList 最多 6 项:超出时保证「当前身份」仍在列表里
const MAX_ITEMS = 6
let visible = list
if (list.length > MAX_ITEMS) {
const current = list.find((item) => item.id === userStore.currentEmployeeId)
const rest = list.filter((item) => item.id !== userStore.currentEmployeeId)
visible = (current ? [current, ...rest] : rest).slice(0, MAX_ITEMS)
uni.$u.toast(`身份较多,仅显示前 ${MAX_ITEMS} 个`)
}
const itemList = visible.map((item) => {
const label =
[item.store_name, item.real_name].filter(Boolean).join(' · ') || `身份 ${item.id}`
return item.id === userStore.currentEmployeeId ? `${label}(当前)` : label
})
uni.showActionSheet({
itemList,
success: (res) => {
const target = visible[res.tapIndex]
if (!target || target.id === userStore.currentEmployeeId) return
doChangeRole(target.id)
}
})
}
/** 执行切换:换发 token → 重拉 user.info(失败提示由 request 层统一处理) */
const doChangeRole = async (roleId: number) => {
uni.showLoading({ title: '切换中', mask: true })
try {
await userStore.changeRole(roleId)
uni.hideLoading()
uni.$u.toast('身份已切换')
} catch {
uni.hideLoading()
// store 内已回滚选中身份,此处只需提示
uni.$u.toast('切换失败,请稍后再试')
}
}
/** 本页是公共页面(auth: 'optional'),登录入口统一走 usePageAuth:
* 登录**就地弹抽屉**,不跳页、不带 redirect(用户登录完仍留在本页) */
const { goLogin, requireLogin } = usePageAuth('optional')
/** 弹登录抽屉(入口在头部用户信息区,本页不再放独立的登录按钮) */
const onLogin = () => goLogin()
/** 功能菜单:与首页九宫格**同源**(都是 permissionStore.entries) */
const menuSections = computed(() => toSections(permissionStore.entries))
/** 点击功能菜单(本卡仅登录后显示,这里的登录判断只是兜底) */
const onMenuTap = (item: EntryLeaf) => {
if (item.auth === 'required' && !userStore.isLogin) {
requireLogin(`「${item.title}」需要登录后使用`)
return
}
navigateToPath(item.path, item.title)
}
/** 头部区点击:未登录去登录;微信已登录但未绑定则直接打开绑定入口 */
const onProfileTap = () => { const onProfileTap = () => {
if (!userStore.isLogin) { if (!userStore.isLogin) {
onLogin() goLogin()
return return
} }
// 未绑定时各业务功能都不可用,这里是最需要操作的入口
if (userStore.isWechatUnbound) {
bindVisible.value = true
}
}
/** 绑定账号弹窗可见性(未绑定用户的常驻入口) */ const page = getPageByKey(USER_INFO_KEY)
const bindVisible = ref(false) if (!page) return
navigateToPath(page.path, page.title)
const onOpenBind = () => {
bindVisible.value = true
}
/** 绑定成功:`store.wechatBind` 内部已重拉 user.info,这里只需关弹窗并提示 */
const onBindSuccess = () => {
bindVisible.value = false
uni.$u.toast('绑定成功')
} }
const onClearCache = () => { const onClearCache = () => {
@ -266,29 +118,9 @@ const onClearCache = () => {
}) })
} }
const onLogout = () => {
if (!userStore.isLogin) {
uni.$u.toast('当前未登录')
return
}
uni.showModal({
title: '提示',
content: '确定要退出登录吗?',
success: async (res) => {
if (!res.confirm) return
// logout 内部已做兜底:后端不可用也会清理本地登录态
await userStore.logout()
// 退出后停留在本页:页面会自动切回「未登录」态并显示登录入口
// 不强制跳转登录页 —— 与「登录由用户主动触发」的约定保持一致
uni.$u.toast('已退出登录')
}
})
}
// onShow:tabBar 页切换只触发 onShow,登录态变化后在此与本地存储对齐 // onShow:tabBar 页切换只触发 onShow,登录态变化后在此与本地存储对齐
// ⚠️ 本页**不在此处拉取 user.info**:数据由 App 启动 / 登录 / 绑定 / 切身份时统一灌入 store, // ⚠️ 本页**不在此处拉取 user.info**:数据由 App 启动 / 登录 / 绑定 / 切身份时统一灌入 store,
// 页面直接读(拉取失败时页内有「点此重试」入口) // 页面直接读(拉取失败时二级页内有「点此重试」入口)
onShow(() => { onShow(() => {
// 本地存储是登录态的唯一来源,与内存态对齐 // 本地存储是登录态的唯一来源,与内存态对齐
// (request 层在 401/过期时会直接清存储,此处保证界面同步) // (request 层在 401/过期时会直接清存储,此处保证界面同步)
@ -316,6 +148,12 @@ onShow(() => {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
&-img {
width: 108rpx;
height: 108rpx;
border-radius: 50%;
}
} }
&__info { &__info {
@ -336,70 +174,10 @@ onShow(() => {
} }
} }
.bind-entry {
margin: 0 32rpx 32rpx;
}
.bind-popup {
width: 620rpx;
padding: 48rpx 40rpx 32rpx;
box-sizing: border-box;
&__title {
font-size: 34rpx;
font-weight: 600;
color: #303133;
text-align: center;
}
&__desc {
margin-top: 12rpx;
font-size: 24rpx;
color: #909399;
text-align: center;
}
&__cancel {
display: flex;
align-items: center;
justify-content: center;
margin-top: 28rpx;
padding: 16rpx 0;
font-size: 28rpx;
color: #909399;
}
}
.card { .card {
margin: 24rpx; margin: 24rpx;
background-color: #ffffff; background-color: #ffffff;
border-radius: 16rpx; border-radius: 16rpx;
overflow: hidden; overflow: hidden;
&__title {
padding: 24rpx 32rpx 8rpx;
font-size: 28rpx;
font-weight: 600;
color: #303133;
}
&__note {
padding: 0 32rpx 24rpx;
font-size: 24rpx;
color: #909399;
text-align: center;
}
}
.menu {
&__title {
padding: 8rpx 32rpx 0;
font-size: 26rpx;
color: #909399;
}
}
.footer {
padding: 24rpx 32rpx;
} }
</style> </style>

View File

@ -0,0 +1,741 @@
<template>
<view class="page">
<!-- 未登录:页内引导(**不自动跳转** —— 微信审核要求登录由用户主动触发) -->
<view v-if="!userStore.isLogin" class="card">
<empty-state text="登录后可查看个人信息" icon="account" :show-retry="false">
<template #action>
<up-button
type="primary"
shape="circle"
size="small"
text="去登录"
@click="goLogin"
></up-button>
</template>
</empty-state>
</view>
<template v-else>
<!-- ① 用户信息:身份信息来自 user.info 的 employees[](不改数据库、无额外接口) -->
<view class="card">
<view class="card__title">用户信息</view>
<view class="me">
<view class="me__avatar">
<image
v-if="headimgurl"
class="me__avatar-img"
:src="headimgurl"
mode="aspectFill"
></image>
<up-icon v-else name="account" color="#ffffff" size="36"></up-icon>
</view>
<view class="me__info">
<view class="me__name">{{ displayName }}</view>
<view class="me__desc">{{ identityDesc }}</view>
</view>
</view>
<up-cell-group v-if="identity" :border="false">
<up-cell title="姓名" :value="identity?.real_name || displayName" :border="false"></up-cell>
<up-cell title="身份类型" :value="userStore.roleTypeLabel || '-'" :border="false"></up-cell>
<up-cell title="所属组织" :value="identity?.store_name || '-'" :border="false"></up-cell>
<up-cell title="员工 ID" :value="identity ? String(identity.id) : '-'" :border="false"></up-cell>
<up-cell title="授权到期" :value="authEndText" :border="false"></up-cell>
<!-- 仅多身份时出现:身份切换入口 -->
<up-cell
v-if="userStore.hasMultipleEmployees"
title="切换身份"
:value="`${userStore.employees.length} 个可选`"
is-link
:border="false"
@click="onSwitchIdentity"
></up-cell>
</up-cell-group>
<view v-else class="card__note" @click="onRetryInfo">未获取到身份信息,点此重试</view>
</view>
<!-- ② 待绑定 WMS 账号(微信已登录但未绑定;绑定可跳过,跳过仍是免登录态) -->
<view v-if="userStore.isWechatUnbound" class="card">
<view class="card__title">待绑定 WMS 账号</view>
<view class="card__note">
当前微信尚未绑定 WMS 账号,绑定后即可使用入库、出库、盘点等全部功能。
</view>
<view class="card__action">
<up-button
type="primary"
shape="circle"
text="绑定 WMS 账号"
@click="bindVisible = true"
></up-button>
</view>
</view>
<!-- ③ 微信资料(后端 wechat.updateInfo 仅允许未绑定账号修改昵称) -->
<view v-if="userStore.canEditWechatProfile" class="card">
<view class="card__title">微信资料</view>
<up-cell-group :border="false">
<up-cell title="头像" is-link :border="false" @click="openProfileEditor">
<template #value>
<image
v-if="headimgurl"
class="cell-avatar"
:src="headimgurl"
mode="aspectFill"
></image>
<text v-else class="cell-avatar__empty">未设置</text>
</template>
</up-cell>
<up-cell
title="昵称"
:value="userStore.wechatNickname || '未设置'"
is-link
:border="false"
@click="openProfileEditor"
></up-cell>
</up-cell-group>
<view class="card__note">绑定 WMS 账号后,昵称与头像改由账号体系管理</view>
</view>
<!-- ④ 电脑端登录码(需微信登录态;账号密码登录的 token 后端不认) -->
<view v-if="userStore.canGetMyLoginCode" class="card">
<view class="card__title">电脑端登录码</view>
<up-cell
title="我的登录码"
value="点击查看"
is-link
:border="false"
@click="onShowLoginCode"
></up-cell>
<view class="card__note">在电脑端登录页凭此登录码登录本账号</view>
</view>
<!-- ⑤ 退出登录(从「我的」页移来:细项统一收在本页) -->
<view class="footer">
<up-button type="info" :plain="true" text="退出登录" @click="onLogout"></up-button>
</view>
</template>
<!-- 绑定账号弹窗:与登录页共用 wechat-bind-form(这里不提供「跳过」,是用户主动点的) -->
<up-popup :show="bindVisible" mode="center" :round="16" @close="bindVisible = false">
<view class="bind-popup">
<view class="bind-popup__title">绑定 WMS 账号</view>
<view class="bind-popup__desc">输入 WMS 账号密码完成绑定,绑定后可使用全部功能</view>
<wechat-bind-form submit-text="绑定" @success="onBindSuccess"></wechat-bind-form>
<view class="bind-popup__cancel" @click="bindVisible = false">取消</view>
</view>
</up-popup>
<!-- 编辑微信资料:头像走微信「头像昵称填写能力」,昵称走 wechat.updateInfo -->
<up-popup :show="profileVisible" mode="bottom" :round="16" @close="closeProfileEditor">
<view class="profile-popup">
<view class="profile-popup__title">编辑微信资料</view>
<view class="profile-popup__field">
<view class="profile-popup__label">头像</view>
<!-- ⚠️ 微信已回收 getUserProfile,头像必须由用户主动选(open-type=chooseAvatar) -->
<button
class="avatar-picker"
open-type="chooseAvatar"
@chooseavatar="onChooseAvatar"
>
<image
v-if="headimgurl"
class="avatar-picker__img"
:src="headimgurl"
mode="aspectFill"
></image>
<view v-else class="avatar-picker__empty">
<up-icon name="camera-fill" color="#909399" size="30"></up-icon>
</view>
</button>
<text class="profile-popup__hint">点击头像从微信选择,自动裁剪为 PNG 后上传</text>
</view>
<view class="profile-popup__field">
<view class="profile-popup__label">昵称</view>
<!-- type=nickname:点击时由微信提供昵称填写面板 -->
<input
v-model="nicknameDraft"
class="nickname-input"
type="nickname"
placeholder="点击输入框填写微信昵称"
placeholder-style="color: #c0c4cc"
/>
</view>
<up-button
type="primary"
shape="circle"
text="保存昵称"
:loading="profileSaving"
@click="onSaveNickname"
></up-button>
<view class="profile-popup__cancel" @click="closeProfileEditor">关闭</view>
</view>
</up-popup>
<!-- 登录码弹窗:后端语义是「已有则返回」,码稳定不变 ⇒ 取一次即可反复展示 / 复制 -->
<up-popup
:show="loginCodeVisible"
mode="center"
:round="16"
@close="loginCodeVisible = false"
>
<view class="code-popup">
<view class="code-popup__title">我的登录码</view>
<view class="code-popup__desc">在电脑端登录页粘贴此登录码即可登录本账号</view>
<view class="code-popup__value">
<text v-if="loginCodeLoading" class="code-popup__value--tip">获取中…</text>
<text v-else-if="loginCode" user-select>{{ loginCode }}</text>
<text v-else class="code-popup__value--tip">获取失败,请关闭后重试</text>
</view>
<up-button
type="primary"
shape="circle"
text="复制登录码"
:disabled="!loginCode"
@click="onCopyLoginCode"
></up-button>
<view class="code-popup__cancel" @click="loginCodeVisible = false">关闭</view>
</view>
</up-popup>
<!-- 头像规格化用的画布:旧版 canvas-id API 取不到未渲染的节点,故移到屏外(不能用 v-if) -->
<canvas :canvas-id="AVATAR_CANVAS_ID" class="avatar-canvas"></canvas>
</view>
</template>
<script setup lang="ts">
/**
* 用户信息(二级页)
*
* 从「我的」页拆出来:那里只保留菜单入口,细项全部收进本页,避免首页式堆叠。
* 本页按顺序包含四块:
* ① 用户信息(身份信息 + 切换身份)
* ② 待绑定 WMS 账号(未绑定时)
* ③ 微信资料(未绑定时可改昵称 / 头像)
* ④ 电脑端登录码(微信登录态可查看 / 复制)
*
* 登录策略:`optional` —— 未登录也能进(页内引导登录,不自动跳转)。
*/
import { computed, getCurrentInstance, ref } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { useUserStore } from '@/store/modules/user'
import { usePageAuth } from '@/composables/usePageAuth'
import { getToken } from '@/utils/auth'
import { AVATAR_CANVAS_ID, avatarFileToPngBase64 } from '@/utils/avatar'
import WechatBindForm from '@/components/wechat-bind-form/wechat-bind-form.vue'
import EmptyState from '@/components/empty-state/empty-state.vue'
const userStore = useUserStore()
/** 登录入口统一走 usePageAuth(本页是 optional:登录**就地弹抽屉**,不跳页) */
const { goLogin } = usePageAuth('optional')
/** 旧版画布 / canvasToTempFilePath 需要页面实例,否则取不到画布 */
const instance = getCurrentInstance()
/* ───────────── ① 用户信息 ───────────── */
const headimgurl = computed(() => userStore.headimgurl)
const identity = computed(() => userStore.currentEmployee)
/** 展示名:未绑定微信态优先显示用户设置的微信昵称 */
const displayName = computed(() => {
if (userStore.isWechatUnbound) return userStore.wechatNickname || '微信用户'
return userStore.userName || '已登录'
})
/** 身份摘要:身份类型 · 所属组织 */
const identityDesc = computed(() => {
const parts = [userStore.roleTypeLabel, identity.value?.store_name].filter(Boolean)
return parts.length ? parts.join(' · ') : '已登录'
})
/** 授权到期展示:后端 null / 空 表示长期有效 */
const authEndText = computed(() => {
const end = identity.value?.auth_end
if (!end) return '长期有效'
return String(end).slice(0, 10)
})
/**
* 手动重试:强制重拉 `user.info`
*
* 正常路径下页面**不主动请求** —— 数据由 `App.vue` 启动时(或登录 / 绑定 / 切身份时)
* 统一拉好存在 store,本页只负责渲染。只有拉取失败时用户才会看到重试入口。
*/
const onRetryInfo = () => {
userStore.getInfo(true).catch(() => {
// 失败提示由 request 层统一 toast
})
}
/** 选择要切换到的身份(入口仅多身份时出现;用 actionSheet 避免额外页面) */
const onSwitchIdentity = () => {
const list = userStore.employees
if (list.length < 2) return
// 微信 showActionSheet 的 itemList 最多 6 项:超出时保证「当前身份」仍在列表里
const MAX_ITEMS = 6
let visible = list
if (list.length > MAX_ITEMS) {
const current = list.find((item) => item.id === userStore.currentEmployeeId)
const rest = list.filter((item) => item.id !== userStore.currentEmployeeId)
visible = (current ? [current, ...rest] : rest).slice(0, MAX_ITEMS)
uni.$u.toast(`身份较多,仅显示前 ${MAX_ITEMS} 个`)
}
const itemList = visible.map((item) => {
const label =
[item.store_name, item.real_name].filter(Boolean).join(' · ') || `身份 ${item.id}`
return item.id === userStore.currentEmployeeId ? `${label}(当前)` : label
})
uni.showActionSheet({
itemList,
success: (res) => {
const target = visible[res.tapIndex]
if (!target || target.id === userStore.currentEmployeeId) return
doChangeRole(target.id)
}
})
}
/** 执行切换:换发 token → 重拉 user.info(失败提示由 request 层统一处理) */
const doChangeRole = async (roleId: number) => {
uni.showLoading({ title: '切换中', mask: true })
try {
await userStore.changeRole(roleId)
uni.hideLoading()
uni.$u.toast('身份已切换')
} catch {
uni.hideLoading()
// store 内已回滚选中身份,此处只需提示
uni.$u.toast('切换失败,请稍后再试')
}
}
/* ───────────── ② 待绑定 WMS 账号 ───────────── */
/** 绑定弹窗可见性 */
const bindVisible = ref(false)
/** 绑定成功:`store.wechatBind` 内部已重拉 user.info,这里只需关弹窗并提示 */
const onBindSuccess = () => {
bindVisible.value = false
uni.$u.toast('绑定成功')
}
/* ───────────── ③ 微信资料(昵称 / 头像)───────────── */
/** 编辑弹窗可见性 */
const profileVisible = ref(false)
/** 昵称提交中(防重复点击) */
const profileSaving = ref(false)
/** 昵称输入草稿(打开弹窗时从 store 回填;取消 / 关闭即丢弃) */
const nicknameDraft = ref('')
const openProfileEditor = () => {
nicknameDraft.value = userStore.wechatNickname
profileVisible.value = true
}
const closeProfileEditor = () => {
profileVisible.value = false
}
/**
* 选择头像(微信「头像昵称填写能力」)
*
* `chooseAvatar` 只给临时文件路径,且不保证是 PNG / 体积达标,
* 故先本地裁剪转码为 PNG base64 再上传(后端只收 PNG 且 < 500K)。
*/
const onChooseAvatar = async (event: { detail?: { avatarUrl?: string } }) => {
const tempPath = event?.detail?.avatarUrl || ''
if (!tempPath) return
uni.showLoading({ title: '处理中', mask: true })
let image = ''
try {
image = await avatarFileToPngBase64(tempPath, instance?.proxy)
} catch (err) {
uni.hideLoading()
// 本地裁剪 / 转码失败(图片读不出、压到最小仍超 500K)才在这里提示
uni.$u.toast(err instanceof Error ? err.message : '头像处理失败')
return
}
try {
await userStore.uploadWechatHeadimg(image)
} catch {
// 接口失败提示由 request 层统一 toast,这里只负责关 loading
return
} finally {
uni.hideLoading()
}
uni.$u.toast('头像已更新')
}
/**
* 保存昵称(`wechat.updateInfo`,字段可部分更新)
*
* 只在**内容真的变了**时发请求:后端对未绑定账号会直接覆写,重复提交无意义。
*/
const onSaveNickname = async () => {
const nickname = nicknameDraft.value.trim()
if (!nickname) {
uni.$u.toast('请先填写昵称')
return
}
if (nickname === userStore.wechatNickname) {
uni.$u.toast('昵称未变化')
return
}
profileSaving.value = true
try {
await userStore.updateWechatProfile({ nickname })
profileVisible.value = false
uni.$u.toast('昵称已更新')
} catch {
// 失败提示由 request 层统一 toast(如已绑定账号不允许修改)
} finally {
profileSaving.value = false
}
}
/* ───────────── ④ 电脑端登录码 ───────────── */
/** 登录码弹窗可见性 */
const loginCodeVisible = ref(false)
/** 登录码请求中 */
const loginCodeLoading = ref(false)
const loginCode = computed(() => userStore.myLoginCode)
/**
* 查看「我的登录码」
*
* 后端语义是「没有才生成、已有则返回」⇒ 同一个微信账号的码**稳定不变**,
* state 里已有就直接展示,不再重复请求。
*/
const onShowLoginCode = async () => {
loginCodeVisible.value = true
if (loginCode.value) return
loginCodeLoading.value = true
try {
await userStore.getMyLoginCode()
} catch {
// 失败提示由 request 层统一 toast(非微信登录态 / 登录态失效时后端返回 401)
} finally {
loginCodeLoading.value = false
}
}
/** 复制登录码(微信自带「内容已复制」提示,这里不再重复 toast) */
const onCopyLoginCode = () => {
if (!loginCode.value) return
uni.setClipboardData({ data: loginCode.value })
}
/* ───────────── ⑤ 退出登录 ───────────── */
/**
* 退出登录
*
* 退出后**停留在本页**(页面自动切回未登录引导态),不强制跳登录页
* —— 与「登录由用户主动触发」的约定保持一致。
*/
const onLogout = () => {
uni.showModal({
title: '提示',
content: '确定要退出登录吗?',
success: async (res) => {
if (!res.confirm) return
// logout 内部已做兜底:后端不可用也会清理本地登录态
await userStore.logout()
// 退出后本地登录态已清(含登录渠道 / 登录码),本页会自动切回「未登录」引导态
uni.$u.toast('已退出登录')
}
})
}
// onShow:登录态变化(如从登录页返回)后与本地存储对齐;
// 数据由 App / 登录 / 绑定 / 切身份统一灌入 store,故本页不在此处拉 user.info
onShow(() => {
userStore.token = getToken()
})
</script>
<style lang="scss" scoped>
.page {
min-height: 100vh;
background-color: #f5f6fa;
}
.card {
margin: 24rpx;
background-color: #ffffff;
border-radius: 16rpx;
overflow: hidden;
&__title {
padding: 24rpx 32rpx 8rpx;
font-size: 28rpx;
font-weight: 600;
color: #303133;
}
&__note {
padding: 0 32rpx 24rpx;
font-size: 24rpx;
color: #909399;
text-align: center;
}
&__action {
margin: 0 32rpx 32rpx;
}
}
/* 顶部「我是谁」概要:与「我的」页头部同款蓝底样式,保持视觉一致 */
.me {
display: flex;
align-items: center;
padding: 24rpx 32rpx;
background-color: #2979ff;
&__avatar {
width: 96rpx;
height: 96rpx;
border-radius: 50%;
background-color: rgba(255, 255, 255, 0.25);
display: flex;
align-items: center;
justify-content: center;
&-img {
width: 96rpx;
height: 96rpx;
border-radius: 50%;
}
}
&__info {
flex: 1;
margin-left: 24rpx;
}
&__name {
font-size: 34rpx;
font-weight: 600;
color: #ffffff;
}
&__desc {
margin-top: 8rpx;
font-size: 24rpx;
color: rgba(255, 255, 255, 0.8);
}
}
.cell-avatar {
width: 72rpx;
height: 72rpx;
border-radius: 50%;
background-color: #f2f3f5;
&__empty {
font-size: 26rpx;
color: #909399;
}
}
.footer {
padding: 24rpx 32rpx 48rpx;
}
.avatar-canvas {
/* 旧版 canvas-id API 取不到未渲染的节点,故移到屏幕外而不是 v-if / display:none */
position: fixed;
left: -9999px;
top: -9999px;
width: 400px;
height: 400px;
}
.bind-popup {
width: 620rpx;
padding: 48rpx 40rpx 32rpx;
box-sizing: border-box;
&__title {
font-size: 34rpx;
font-weight: 600;
color: #303133;
text-align: center;
}
&__desc {
margin-top: 12rpx;
font-size: 24rpx;
color: #909399;
text-align: center;
}
&__cancel {
display: flex;
align-items: center;
justify-content: center;
margin-top: 28rpx;
padding: 16rpx 0;
font-size: 28rpx;
color: #909399;
}
}
.profile-popup {
padding: 40rpx 40rpx 32rpx;
&__title {
font-size: 34rpx;
font-weight: 600;
color: #303133;
text-align: center;
}
&__field {
margin-top: 32rpx;
text-align: center;
}
&__label {
font-size: 26rpx;
color: #909399;
}
&__hint {
display: block;
margin-top: 12rpx;
font-size: 22rpx;
color: #c0c4cc;
}
&__cancel {
display: flex;
align-items: center;
justify-content: center;
margin-top: 24rpx;
padding: 16rpx 0;
font-size: 28rpx;
color: #909399;
}
}
.avatar-picker {
display: block;
width: 176rpx;
height: 176rpx;
margin: 16rpx auto 0;
padding: 0;
line-height: 1;
background-color: transparent;
border: none;
border-radius: 50%;
overflow: hidden;
/* 去掉小程序 button 的默认边框 */
&::after {
border: none;
}
&__img {
display: block;
width: 176rpx;
height: 176rpx;
border-radius: 50%;
background-color: #f2f3f5;
}
&__empty {
width: 176rpx;
height: 176rpx;
border-radius: 50%;
background-color: #f2f3f5;
display: flex;
align-items: center;
justify-content: center;
}
}
.nickname-input {
margin-top: 16rpx;
padding: 0 24rpx;
height: 88rpx;
box-sizing: border-box;
font-size: 30rpx;
/* 显式指定文字色:不依赖主题变量(小程序夜间模式下主题色会变浅) */
color: #303133;
background-color: #f5f6fa;
border-radius: 12rpx;
text-align: center;
}
.code-popup {
width: 620rpx;
padding: 48rpx 40rpx 32rpx;
box-sizing: border-box;
&__title {
font-size: 34rpx;
font-weight: 600;
color: #303133;
text-align: center;
}
&__desc {
margin-top: 12rpx;
font-size: 24rpx;
color: #909399;
text-align: center;
}
&__value {
margin: 32rpx 0;
padding: 24rpx;
max-height: 260rpx;
overflow: hidden;
font-size: 24rpx;
line-height: 1.6;
color: #303133;
/* 登录码是长 base64,必须允许任意位置断行,否则会撑破弹窗 */
word-break: break-all;
text-align: center;
background-color: #f5f6fa;
border-radius: 12rpx;
&--tip {
color: #909399;
}
}
&__cancel {
display: flex;
align-items: center;
justify-content: center;
margin-top: 24rpx;
padding: 16rpx 0;
font-size: 28rpx;
color: #909399;
}
}
</style>

View File

@ -64,6 +64,16 @@ export const PAGE_REGISTRY: PageMeta[] = [
tabBar: true, tabBar: true,
hidden: true hidden: true
}, },
{
key: '/mine/user-info',
path: 'pages/mine/user-info',
title: '用户信息',
icon: 'account-fill',
// 未登录也能进(页内引导登录,不自动跳转),故为 optional
auth: 'optional',
// 仅由「我的」页菜单进入,不作为九宫格 / 功能菜单入口
hidden: true
},
{ {
key: '/login', key: '/login',
path: 'pages/login/login', path: 'pages/login/login',

View File

@ -2,7 +2,7 @@
* 权限 / 菜单 Store —— 页面渲染框架的数据中枢 * 权限 / 菜单 Store —— 页面渲染框架的数据中枢
* *
* 输入:`user.info` 的 `menus`(页面树) * 输入:`user.info` 的 `menus`(页面树)
* 产出:`entries`(菜单 × `PAGE_REGISTRY` 后的可见入口树),供首页九宫格 / 「我的」功能菜单直接渲染 * 产出:`entries`(菜单 × `PAGE_REGISTRY` 后的可见入口树),供首页九宫格直接渲染
* *
* 调用时机(见《页面渲染框架》阶段 2): * 调用时机(见《页面渲染框架》阶段 2):
* - `userStore.getInfo()` 成功后 → `loadFromMenus(user.menus)` * - `userStore.getInfo()` 成功后 → `loadFromMenus(user.menus)`

View File

@ -10,7 +10,8 @@
*/ */
import { defineStore } from 'pinia' import { defineStore } from 'pinia'
import { getToken, removeToken, setToken } from '@/utils/auth' import { getLoginChannel, getToken, removeToken, setLoginChannel, setToken } from '@/utils/auth'
import type { LoginChannel } from '@/utils/auth'
import { import {
login as apiLogin, login as apiLogin,
register as apiRegister, register as apiRegister,
@ -19,9 +20,12 @@ import {
logout as apiLogout, logout as apiLogout,
wechatLogin as apiWechatLogin, wechatLogin as apiWechatLogin,
wechatBindUser as apiWechatBindUser, wechatBindUser as apiWechatBindUser,
wechatPushLoginCode as apiWechatPushLoginCode wechatPushLoginCode as apiWechatPushLoginCode,
wechatUpdateInfo as apiWechatUpdateInfo,
wechatUploadHeadimg as apiWechatUploadHeadimg,
wechatGetMyLoginCode as apiWechatGetMyLoginCode
} from '@/api/user/user' } from '@/api/user/user'
import type { EmployeeInfo } from '@/api/user/user' import type { EmployeeInfo, WechatProfileResult, WechatUpdateInfoParams } from '@/api/user/user'
import { getMiniProgramAppid, getWxLoginCode } from '@/utils/wechat' import { getMiniProgramAppid, getWxLoginCode } from '@/utils/wechat'
import { takePendingLoginCode } from '@/utils/entry' import { takePendingLoginCode } from '@/utils/entry'
import { usePermissionStore } from './permission' import { usePermissionStore } from './permission'
@ -106,6 +110,35 @@ interface UserState {
* 最终都会落到这里。页面据此切到「已授权」态,避免让用户对同一个码再点一次(第二次必然失败)。 * 最终都会落到这里。页面据此切到「已授权」态,避免让用户对同一个码再点一次(第二次必然失败)。
*/ */
pushedLoginCode: string pushedLoginCode: string
/**
* 本次登录的渠道(`wechat` / `account`,见 `utils/auth.ts`)
*
* 用途:区分「微信登录态」与「账号密码登录态」—— 后者调微信中间层接口(如登录码)必然失败。
*/
loginChannel: LoginChannel
/**
* 「我的登录码」(`wechat.getMyLoginCode`)
*
* 后端语义是「没有才生成、已有则返回」,故拿到后可长期展示,无需每次重拉;
* 退出登录时随登录态一起清掉。
*/
myLoginCode: string
}
/**
* 当前登录态是否可视为「微信登录态」(JWT 含 `oauth_id`)
*
* 三个信号取并集(任一个成立即可),因为单看某一个都不可靠:
* ① 本地记录的登录渠道(最准,但老数据可能没记)
* ② `user.info` 的 `is_bound`(**只对未绑定态下发**,已绑定为 `undefined`)
* ③ `user.info` 回传的 `oauth_id`(后端在未绑定态会带,已绑定时不一定)
*/
function isWechatLoginState(state: UserState): boolean {
return (
state.loginChannel === 'wechat' ||
state.user.is_bound === false ||
!!state.user.oauth_id
)
} }
export const useUserStore = defineStore('user', { export const useUserStore = defineStore('user', {
@ -118,7 +151,9 @@ export const useUserStore = defineStore('user', {
currentEmployeeId: 0, currentEmployeeId: 0,
infoLoaded: false, infoLoaded: false,
authView: '', authView: '',
pushedLoginCode: '' pushedLoginCode: '',
loginChannel: getLoginChannel(),
myLoginCode: ''
}), }),
getters: { getters: {
@ -149,6 +184,28 @@ export const useUserStore = defineStore('user', {
* 「我的」页据此显示绑定入口;绑定可跳过,跳过不影响免登录。 * 「我的」页据此显示绑定入口;绑定可跳过,跳过不影响免登录。
*/ */
isWechatUnbound: (state): boolean => !!state.token && state.user.is_bound === false, isWechatUnbound: (state): boolean => !!state.token && state.user.is_bound === false,
/** 微信昵称(用户未设置 / 非微信登录态时为 '') */
wechatNickname: (state): string => state.user.nickname || '',
/** 微信头像 URL(用户未设置 / 非微信登录态时为 '') */
headimgurl: (state): string => state.user.headimgurl || '',
/**
* 是否可维护「微信资料」(昵称 / 头像)
*
* 条件 = **微信登录态且未绑定**:后端 `wechat.updateInfo` 明确
* 「仅未绑定真实用户的微信账号」可改(已绑定账号的昵称头像由账号体系管理,
* 传上去也只会失败)。扩展范围时**只改这一处**(「我的」页据此决定入口显隐)。
*/
canEditWechatProfile: (state): boolean => !!state.token && state.user.is_bound === false,
/**
* 是否可查看「我的登录码」(`wechat.getMyLoginCode`)
*
* 与 `canEditWechatProfile` 不同:登录码**不要求未绑定**(有微信登录态即可,
* 已绑定的微信登录态 token 里 `oauth_id` 仍保留);但账号密码登录的 token 后端不认,
* 故仍需用 `isWechatLoginState()` 把入口控住。
*/
canGetMyLoginCode: (state): boolean => !!state.token && isWechatLoginState(state),
/** `user.info` 是否已拉取过(页面据此决定「直接渲染」还是「显示加载/重试」) */ /** `user.info` 是否已拉取过(页面据此决定「直接渲染」还是「显示加载/重试」) */
hasUserInfo: (state): boolean => state.infoLoaded, hasUserInfo: (state): boolean => state.infoLoaded,
/** 登录抽屉是否可见(非空视图即打开) */ /** 登录抽屉是否可见(非空视图即打开) */
@ -191,6 +248,9 @@ export const useUserStore = defineStore('user', {
setToken(token) setToken(token)
this.token = token this.token = token
// 记录登录渠道:微信中间层接口(登录码等)只认微信登录态的 token
setLoginChannel('account')
this.loginChannel = 'account'
// 登录成功后统一拉一次用户信息(菜单 / 权限点 / 身份): // 登录成功后统一拉一次用户信息(菜单 / 权限点 / 身份):
// 放在 store 里可保证「任何登录入口」都会触发,页面渲染框架才有输入。 // 放在 store 里可保证「任何登录入口」都会触发,页面渲染框架才有输入。
@ -247,6 +307,8 @@ export const useUserStore = defineStore('user', {
// 先落地 token:微信登录成功即算登录态(未绑定也保留,下次免登录) // 先落地 token:微信登录成功即算登录态(未绑定也保留,下次免登录)
setToken(token) setToken(token)
this.token = token this.token = token
setLoginChannel('wechat')
this.loginChannel = 'wechat'
// 再用 user.info 探测绑定状态(必须 force:换了个微信登录态,缓存不能用) // 再用 user.info 探测绑定状态(必须 force:换了个微信登录态,缓存不能用)
const info = await this.getInfo(true).catch(() => null) const info = await this.getInfo(true).catch(() => null)
@ -286,6 +348,9 @@ export const useUserStore = defineStore('user', {
setToken(token) setToken(token)
this.token = token this.token = token
// 绑定前就是微信登录态(bindUser 保留 oauth_id),这里显式再记一次防旧版本数据缺失
setLoginChannel('wechat')
this.loginChannel = 'wechat'
// 绑定后身份变了,必须强制重拉(不能吃旧缓存) // 绑定后身份变了,必须强制重拉(不能吃旧缓存)
await this.getInfo(true).catch(() => {}) await this.getInfo(true).catch(() => {})
// 绑定完成后可能才具备推送条件(扫码时未绑定的场景) // 绑定完成后可能才具备推送条件(扫码时未绑定的场景)
@ -325,6 +390,87 @@ export const useUserStore = defineStore('user', {
} }
}, },
/**
* 更新微信账号资料(昵称 / 头像 URL,字段可部分更新)
*
* 前提:**微信登录态且未绑定**(后端仅允许未绑定账号修改,见 `canEditWechatProfile`)。
* 成功后把返回值合并进 `user`(不重拉 `user.info`)——「我的」页与头部文案立即更新,
* 且**不污染** `getInfo()` 的缓存语义(`infoLoaded` 保持原值)。
*/
async updateWechatProfile(payload: WechatUpdateInfoParams): Promise<void> {
const resp = await apiWechatUpdateInfo(payload)
this.applyWechatProfile(resp.data)
},
/**
* 上传微信头像(**PNG base64,< 500K**)
*
* 入参 `image` 由 `utils/avatar.ts` 的 `avatarFileToPngBase64()` 规整(裁剪 / 转码 / 压缩),
* 后端落 COS 后回写 `wms_user_oauth.headimgurl` 并返回 URL。
*
* @return 头像 URL(失败时 request 层已 toast 并 reject,调用方只需兜 loading)
*/
async uploadWechatHeadimg(image: string): Promise<string> {
const resp = await apiWechatUploadHeadimg({ image })
this.applyWechatProfile(resp.data)
return resp.data?.headimgurl || resp.data?.url || ''
},
/**
* 把微信资料接口的返回合并进 `user`
*
* 两者字段不完全一致(`uploadHeadimg` 用 `url`,`updateInfo` 用 `headimgurl`),
* 这里统一收敛:**只覆盖接口真正回传的字段**,避免把已有值冲成空。
*/
applyWechatProfile(data?: WechatProfileResult | null): void {
if (!data) return
const next = { ...this.user }
if (data.nickname) next.nickname = data.nickname
const headimgurl = data.headimgurl || data.url
if (headimgurl) next.headimgurl = headimgurl
if (data.oauth_id) next.oauth_id = data.oauth_id
// 整体替换以触发响应式(Pinia state 对象替换是安全的)
this.user = next
},
/**
* 获取「我的登录码」(`wechat.getMyLoginCode`,供电脑端登录)
*
* 后端语义:取当前微信用户 `wms_user_oauth.login_code`,**没有才生成**并落库,
* 已有则原样返回 ⇒ 同一微信账号的码**稳定不变**,拿到后存进 state 供反复展示
* (页面无需每次重拉;这个特性也让「再点一次还是同一个码」不会困惑用户)。
*
* ⚠️ 返回字段后端文档未列出,此处做**兼容取值**;一个都取不到时抛错,
* 避免把 `undefined` 当成登录码展示出去。
*
* @return 登录码(base64 字符串)
*/
async getMyLoginCode(): Promise<string> {
const resp = await apiWechatGetMyLoginCode()
// ⚠️ 实测:该接口的响应是**扁平**的 —— 业务字段与 `flag/code/message` **同级**,
// **没有 `data` 包裹**:{ flag, code, message, login_code, oauth_id, timestamp }
// 所以从顶层取;同时兼容以后被包进 `data` 的情况。
// ⚠️ 不要拿顶层的 `code` 做兜底:它是**业务码**(成功 = 1),会与登录码混淆。
const flat = resp as unknown as Record<string, any>
const nested = (resp.data || {}) as Record<string, any>
const candidate = flat.login_code || nested.login_code || flat.loginCode || nested.loginCode
if (typeof candidate !== 'string' || !candidate) {
throw new Error('未获取到登录码:接口未返回 login_code 字段')
}
// 顺带回填 oauth_id:它能让「是否微信登录态」的判断多一个信号(见 isWechatLoginState)
const oauthId = flat.oauth_id || nested.oauth_id
if (oauthId && !this.user.oauth_id) {
this.user = { ...this.user, oauth_id: oauthId }
}
this.myLoginCode = candidate
return this.myLoginCode
},
/** /**
* 拉取用户信息(权限点 + 菜单),后续页面渲染框架会消费 menus * 拉取用户信息(权限点 + 菜单),后续页面渲染框架会消费 menus
* *
@ -360,7 +506,15 @@ export const useUserStore = defineStore('user', {
* 仅供 `getInfo` 调用(要共享「并发复用 / 缓存」能力,请走 `getInfo`)。 * 仅供 `getInfo` 调用(要共享「并发复用 / 缓存」能力,请走 `getInfo`)。
*/ */
async fetchInfo(): Promise<UserInfo> { async fetchInfo(): Promise<UserInfo> {
const resp = await apiGetInfo({ device: DEVICE }) // 上报**运行时真实 AppID**(同 wechat.loginByCode 的 appid):代码作为开放平台
// 第三方平台模板发布给多个仓库,AppID 构建期无法写死,后端据此反查 wms_wechat_app
// 授权记录,识别「当前是哪个小程序在请求」。
// 拿不到时(H5 / 工具未填 AppID → 'touristappid' 由后端按无授权处理)不带该参数。
const appid = getMiniProgramAppid()
const resp = await apiGetInfo({
device: DEVICE,
...(appid ? { wechat_appId: appid } : {})
})
const user = resp.data const user = resp.data
if (!user) { if (!user) {
throw new Error('获取用户信息失败,请重新登录') throw new Error('获取用户信息失败,请重新登录')
@ -379,7 +533,7 @@ export const useUserStore = defineStore('user', {
this.roleId = user.employees_id || 0 this.roleId = user.employees_id || 0
// 身份列表 + 当前身份(优先以后端会话的 employees_id 为准) // 身份列表 + 当前身份(优先以后端会话的 employees_id 为准)
this.setEmployees(user.employees || [], user.employees_id || 0) this.setEmployees(user.employees || [], user.employees_id || 0)
// 菜单 → 可见入口树(首页九宫格 / 「我的」功能菜单的渲染输入) // 菜单 → 可见入口树(首页九宫格的渲染输入)
usePermissionStore().loadFromMenus(user.menus || []) usePermissionStore().loadFromMenus(user.menus || [])
this.infoLoaded = true this.infoLoaded = true
return user return user
@ -483,6 +637,9 @@ export const useUserStore = defineStore('user', {
this.employees = [] this.employees = []
this.currentEmployeeId = 0 this.currentEmployeeId = 0
this.infoLoaded = false this.infoLoaded = false
// 登录渠道与登录码都跟登录态走(removeToken 已一并清存储里的渠道)
this.loginChannel = ''
this.myLoginCode = ''
// 菜单/入口一并清空:退出登录、401、清缓存都不能让旧身份的入口残留 // 菜单/入口一并清空:退出登录、401、清缓存都不能让旧身份的入口残留
usePermissionStore().reset() usePermissionStore().reset()
}, },

View File

@ -1,15 +1,29 @@
/** /**
* 登录令牌的本地存取 * 登录态(令牌 + 登录渠道)的本地存取
* *
* 与 new3(Web 端)的差异:Web 用 js-cookie 存 Cookie,小程序没有 Cookie, * 与 new3(Web 端)的差异:Web 用 js-cookie 存 Cookie,小程序没有 Cookie,
* 因此统一改用 uni 的本地存储;存储 key 保持与 new3 一致(token)。 * 因此统一改用 uni 的本地存储;token 的存储 key 保持与 new3 一致(token)。
* *
* 约定:本文件是 token 的**唯一写入方**,其他模块只允许通过这里读写, * 约定:本文件是 token / 登录渠道的**唯一写入方**,其他模块只允许通过这里读写,
* 避免出现「有的地方读 Cookie、有的地方读 Storage」的不一致。 * 避免出现「有的地方读 Cookie、有的地方读 Storage」的不一致。
*/ */
const TOKEN_KEY = 'token' const TOKEN_KEY = 'token'
/** 登录渠道的存储 key */
const LOGIN_CHANNEL_KEY = 'login_channel'
/**
* 登录渠道:这次登录是「微信一键登录」还是「账号密码」
*
* 为什么要单独记:**从 token 本身看不出来**——
* 已绑定的微信登录态在 `user.info` 里**没有** `is_bound` 字段(为 `undefined`),
* 与账号密码登录无法区分;而部分接口(`wechat.getMyLoginCode` 等)
* **只认微信登录态 token**(JWT 需含 `oauth_id`),界面必须据此决定入口显隐,
* 否则会给用户一个必然失败的按钮。
*/
export type LoginChannel = '' | 'wechat' | 'account'
/** 读取 token;未登录返回空字符串(调用方用真值判断即可) */ /** 读取 token;未登录返回空字符串(调用方用真值判断即可) */
export function getToken(): string { export function getToken(): string {
try { try {
@ -30,10 +44,31 @@ export function setToken(token: string): void {
} }
} }
/** 清除 token */ /** 读取登录渠道(旧数据 / 未记录时为空串,调用方需容忍) */
export function removeToken(): void { export function getLoginChannel(): LoginChannel {
try { try {
uni.removeStorageSync(TOKEN_KEY) const channel = uni.getStorageSync(LOGIN_CHANNEL_KEY)
return channel === 'wechat' || channel === 'account' ? channel : ''
} catch {
return ''
}
}
/** 写入登录渠道(与 token 同生命周期,存 token 时一起写) */
export function setLoginChannel(channel: LoginChannel): void {
try {
if (channel) uni.setStorageSync(LOGIN_CHANNEL_KEY, channel)
else uni.removeStorageSync(LOGIN_CHANNEL_KEY)
} catch {
// ignore
}
}
/** 清除 token(连带清除登录渠道:两者必须同生共死) */
export function removeToken(): void {
try {
uni.removeStorageSync(TOKEN_KEY)
uni.removeStorageSync(LOGIN_CHANNEL_KEY)
} catch { } catch {
// ignore // ignore
} }

136
src/utils/avatar.ts Normal file
View File

@ -0,0 +1,136 @@
/**
* 头像选取与规格化(微信小程序「头像昵称填写能力」配套)
*
* 场景:后端 `wechat.uploadHeadimg` **只收 PNG base64 且 ≤500K**,
* 而微信 `chooseAvatar` 给的是**临时文件路径** —— 格式(jpg/png)与体积都不受控,
* 因此必须在本机完成「居中方形裁剪 → 转 PNG → 压到 500K 以内」再上传。
*
* 实现要点(踩过的坑):
* 1. 用**旧版 `canvas-id`**(`uni.createCanvasContext`)而不是 `type="2d"`:
* 小程序端兼容性最好,也不需要 `uni.createSelectorQuery()` 查节点。
* ⚠️ 代价:调用页面**必须真实渲染**一个 `<canvas canvas-id="avatar-canvas">`,
* 且必须传入页面实例(`getCurrentInstance().proxy`),否则取不到画布。
* 2. 先按「cover 居中裁剪」绘制正方形,避免非正方形头像被拉伸变形。
* 3. 体积控制在**逐级缩小重绘**:PNG 体积与像素面积强相关但不可预估(取决于画面复杂度),
* 故不猜一个固定尺寸,而是从大往小试,直到估算字节数 < 500K。
*
* ⚠️ 本文件只在微信小程序端真正工作(H5 没有 `getFileSystemManager`);
* 由于头像入口只在「微信登录态」下出现,H5 产物中该路径不会被执行。
*/
/** 页面里 `<canvas :canvas-id="AVATAR_CANVAS_ID">` 必须与之一致 */
export const AVATAR_CANVAS_ID = 'avatar-canvas'
/** 后端限制:PNG 且小于 500K */
const MAX_BYTES = 500 * 1024
/**
* 逐级缩小的画布边长(px)
*
* 400 起步保证清晰度;仍超限则逐步降到 120(微信头像实际显示尺寸很小,够用)。
* 全都不达标时按「换一张」提示用户,而不是无限压缩成马赛克。
*/
const SIZE_STEPS = [400, 320, 240, 180, 120]
/** base64 估算字节数(去掉可选 data URL 前缀与换行后按 3/4 折算) */
function base64Bytes(base64: string): number {
const raw = base64.replace(/^data:[^,]+,/, '').replace(/[\r\n]/g, '')
return Math.floor((raw.length * 3) / 4)
}
/** 取图片原始宽高(用于 cover 裁剪,避免拉伸) */
function getImageSize(filePath: string): Promise<{ width: number; height: number }> {
return new Promise((resolve, reject) => {
uni.getImageInfo({
src: filePath,
success: (res) => resolve({ width: res.width, height: res.height }),
fail: () => reject(new Error('读取头像图片失败'))
})
})
}
/** 本地文件 → base64(不含 `data:image/png;base64,` 前缀,后端两种都支持) */
function readFileBase64(filePath: string): Promise<string> {
return new Promise((resolve, reject) => {
uni.getFileSystemManager().readFile({
filePath,
encoding: 'base64',
success: (res) => {
const data = res.data
if (typeof data === 'string' && data) resolve(data)
else reject(new Error('读取头像文件失败'))
},
fail: () => reject(new Error('读取头像文件失败'))
})
})
}
/** 按 cover 居中裁剪绘制到画布(正方形) */
function drawSquareCover(filePath: string, size: number, component?: unknown): Promise<void> {
return new Promise((resolve, reject) => {
getImageSize(filePath)
.then(({ width, height }) => {
const side = Math.min(width, height) || 1
const sx = Math.max((width - side) / 2, 0)
const sy = Math.max((height - side) / 2, 0)
const ctx = uni.createCanvasContext(AVATAR_CANVAS_ID, component)
ctx.clearRect(0, 0, size, size)
// 9 参形式:源图取居中正方形,铺满画布
ctx.drawImage(filePath, sx, sy, side, side, 0, 0, size, size)
// draw 的回调在绘制指令执行完后触发,之后才能导出
ctx.draw(false, () => resolve())
})
.catch(reject)
})
}
/** 画布 → PNG 临时文件 */
function canvasToPngFile(size: number, component?: unknown): Promise<string> {
return new Promise((resolve, reject) => {
uni.canvasToTempFilePath(
{
canvasId: AVATAR_CANVAS_ID,
fileType: 'png',
width: size,
height: size,
destWidth: size,
destHeight: size,
success: (res) => {
const path = res.tempFilePath
if (path) resolve(path)
else reject(new Error('生成头像图片失败'))
},
fail: () => reject(new Error('生成头像图片失败'))
},
component
)
})
}
/**
* 把微信 `chooseAvatar` 给出的临时图片处理成**可直传后端的 PNG base64**
*
* @param filePath `chooseAvatar` 事件里的 `detail.avatarUrl`(临时文件路径)
* @param component 页面实例(`getCurrentInstance()?.proxy`)—— 旧版画布 API 必须传,否则取不到画布
* @throws 图片读不出 / 画布失败 / 压到最小仍超 500K 时抛出带中文文案的 Error
*/
export async function avatarFileToPngBase64(
filePath: string,
component?: unknown
): Promise<string> {
if (!filePath) throw new Error('未获取到头像图片')
let lastBytes = 0
for (const size of SIZE_STEPS) {
await drawSquareCover(filePath, size, component)
const tempPath = await canvasToPngFile(size, component)
const base64 = await readFileBase64(tempPath)
lastBytes = base64Bytes(base64)
if (lastBytes < MAX_BYTES) return base64
}
const kb = Math.round(lastBytes / 1024)
throw new Error(`头像压缩后仍有 ${kb}K(上限 500K),请换一张更简单的图片`)
}

View File

@ -23,6 +23,7 @@
| 分包(pages.json 注册) | 🚧 部分注册 | `pagesA` 已注册(当前放框架示例页);`pagesB` / `pagesC` 待业务页一起注册 | | 分包(pages.json 注册) | 🚧 部分注册 | `pagesA` 已注册(当前放框架示例页);`pagesB` / `pagesC` 待业务页一起注册 |
| 请求封装(第 5 节) | ✅ 已完成 | `utils/request.ts`,对齐 new3,含 token 注入 / 响应头续期 / 401 处理 | | 请求封装(第 5 节) | ✅ 已完成 | `utils/request.ts`,对齐 new3,含 token 注入 / 响应头续期 / 401 处理 |
| 登录鉴权(第 6 节) | ✅ 已完成 | 账号密码登录 + 注册;登录入口在「我的」页头部(启动页为首页,不强制登录);401 按需引导登录 | | 登录鉴权(第 6 节) | ✅ 已完成 | 账号密码登录 + 注册;登录入口在「我的」页头部(启动页为首页,不强制登录);401 按需引导登录 |
| 「我的」页结构 | ✅ 已完成(2026-09-22) | **菜单 + 二级页面**:本页只留「登录入口 + 菜单」;细项全收进 `pages/mine/user-info`(用户信息 / 待绑定 WMS 账号 / 微信资料 / 电脑端登录码 / 退出登录) |
| Pinia 状态管理(第 8 节) | ✅ 已完成 | `pinia@2.1.7`(Vue 3.4 兼容版),见 `store/modules/user.ts` | | Pinia 状态管理(第 8 节) | ✅ 已完成 | `pinia@2.1.7`(Vue 3.4 兼容版),见 `store/modules/user.ts` |
| 环境变量(第 11 节) | ✅ 已完成 | `.env.development` / `.env.production`:`VITE_APP_BASE_API` / `VITE_APP_PLATFORM` / `VITE_APP_PROJECT` | | 环境变量(第 11 节) | ✅ 已完成 | `.env.development` / `.env.production`:`VITE_APP_BASE_API` / `VITE_APP_PLATFORM` / `VITE_APP_PROJECT` |
| 静态路由表(阶段 1) | ✅ 已完成 | `src/router/pages.ts`:`PAGE_REGISTRY`(逻辑路径 → 物理页面 + `auth` 策略)+ `PAGE_MAP`;配置 `npm run check:pages` 一致性校验 | | 静态路由表(阶段 1) | ✅ 已完成 | `src/router/pages.ts`:`PAGE_REGISTRY`(逻辑路径 → 物理页面 + `auth` 策略)+ `PAGE_MAP`;配置 `npm run check:pages` 一致性校验 |
@ -33,6 +34,8 @@
| 身份(角色/仓库)展示 | ✅ 已完成 | 「我的」页登录后显示:姓名 / 身份类型 / 所属组织 / 员工 ID / 授权到期;数据来自 `user.info` 的 `employees[]`,**不改数据库** | | 身份(角色/仓库)展示 | ✅ 已完成 | 「我的」页登录后显示:姓名 / 身份类型 / 所属组织 / 员工 ID / 授权到期;数据来自 `user.info` 的 `employees[]`,**不改数据库** |
| 身份切换 `changeRole` | 🚧 已实现待联调 | 入口在「我的」页(多身份时出现);接口已实测存在,返回结构待后端确认 | | 身份切换 `changeRole` | 🚧 已实现待联调 | 入口在「我的」页(多身份时出现);接口已实测存在,返回结构待后端确认 |
| 微信一键登录 | ✅ 已完成 | `wechat.loginByCode`(不是 `user.loginByCode`);AppID 运行时取(`wx.getAccountInfoSync`,适配开放平台模板多仓库);token 立即落地(未绑定也算免登录态);绑定可跳过、入口常驻「我的」页 | | 微信一键登录 | ✅ 已完成 | `wechat.loginByCode`(不是 `user.loginByCode`);AppID 运行时取(`wx.getAccountInfoSync`,适配开放平台模板多仓库);token 立即落地(未绑定也算免登录态);绑定可跳过、入口常驻「我的」页 |
| 微信资料(昵称/头像) | ✅ 已完成(2026-09-22) | `wechat.updateInfo`(改昵称)+ `wechat.uploadHeadimg`(传头像);走微信「头像昵称填写能力」(`chooseAvatar` + `input type=nickname`),头像经 `utils/avatar.ts` 裁剪转 PNG(<500K)后上传;入口仅未绑定态可见 |
| 我的登录码(电脑端登录) | ✅ 已完成(2026-09-22) | `wechat.getMyLoginCode`(无入参,码**稳定不变**);入口在「我的」页(需微信登录态);同时新增登录渠道记录 `login_channel` |
> 📄 **配套文档**:`页面渲染框架-设计与任务清单.md` —— 菜单 / 权限 / 页面渲染的决策与任务清单(第 12 节为摘要) > 📄 **配套文档**:`页面渲染框架-设计与任务清单.md` —— 菜单 / 权限 / 页面渲染的决策与任务清单(第 12 节为摘要)
> ⚠️ **已知坑**:同时跑两个 `dev:mp-weixin` 进程会写坏产物,导致预览报 > ⚠️ **已知坑**:同时跑两个 `dev:mp-weixin` 进程会写坏产物,导致预览报
@ -360,11 +363,15 @@ d:\wechat\
4. **token 立即落地存储**(含 `id = 0` 的未绑定态)—— 它是有效的免登录凭证 4. **token 立即落地存储**(含 `id = 0` 的未绑定态)—— 它是有效的免登录凭证
5. 再调 `user.info` 探测绑定状态:未绑定时后端**不返回 401**,而是下发 `is_bound: false` 5. 再调 `user.info` 探测绑定状态:未绑定时后端**不返回 401**,而是下发 `is_bound: false`
+ 微信层信息(openid / unionid / oauth_id),见后端 `systems/auth/user.js` 的 `info()` + 微信层信息(openid / unionid / oauth_id),见后端 `systems/auth/user.js` 的 `info()`
- ⚠️ `user.info` 入参已**新增 `wechat_appId`**(`string`,运行时真实 AppID,与 `loginByCode` 的
`appid` 同源)—— 未绑定态也要让后端知道「是哪个小程序发起的请求」;
非小程序端 / 拿不到 AppID 时**不带该参数**(`store/modules/user.ts` 的 `fetchInfo`)
未绑定的处理(产品要求:只提示一次、可跳过、不阻断): 未绑定的处理(产品要求:只提示一次、可跳过、不阻断):
- 登录页展示绑定步骤(`components/wechat-bind-form/`),**可跳过** - 登录页展示绑定步骤(`components/wechat-bind-form/`),**可跳过**
- 跳过**不清 token**:仍是免登录态,下次打开小程序直接进首页,不重复提示登录 - 跳过**不清 token**:仍是免登录态,下次打开小程序直接进首页,不重复提示登录
- 绑定入口常驻「我的」页(`isWechatUnbound` 为真时显示「待绑定 WMS 账号」卡片 + 弹窗绑定) - 绑定入口在「用户信息」二级页(`pages/mine/user-info`):`isWechatUnbound` 为真时显示
「待绑定 WMS 账号」卡片 + 弹窗绑定(原先直接堆在「我的」页上)
- 绑定成功:`wechat.bindUser` 换发正式 token(`user.id` = 真实账号 ID)并重拉 `user.info` - 绑定成功:`wechat.bindUser` 换发正式 token(`user.id` = 真实账号 ID)并重拉 `user.info`
前端落点:`utils/wechat.ts`(原生能力 + 条件编译)、`api/user/user.ts`(两个接口)、 前端落点:`utils/wechat.ts`(原生能力 + 条件编译)、`api/user/user.ts`(两个接口)、
@ -376,8 +383,62 @@ d:\wechat\
⚠️ 仅登录表单展示入口,且整段包在 `#ifdef MP-WEIXIN` 内(H5 产物中已剔除)。 ⚠️ 仅登录表单展示入口,且整段包在 `#ifdef MP-WEIXIN` 内(H5 产物中已剔除)。
- [x] **微信资料维护(`wechat.updateInfo` + `wechat.uploadHeadimg`)** ✅ 2026-09-22
⚠️ 两个接口都是**微信登录态中间层**(带微信登录态 token 即可),
且 `wechat.updateInfo` 后端**仅允许未绑定真实用户的微信账号**修改 ——
故入口条件是 `user.info` 的 `is_bound === false`(store 的 `canEditWechatProfile`,只此一处判断)。
接口参数 / 返回(来源:new3 接口工具的 `module/wechat/module.json`):
- `wechat.updateInfo`:入参 `{ nickname?, headimgurl? }`(**可部分更新**,
nickname ≤255 字符、headimgurl ≤500 字符)→ 返回 `{ oauth_id, nickname, headimgurl }`
- `wechat.uploadHeadimg`:入参 `{ image }` = **PNG 的 base64**(支持 `data:image/png;base64,` 前缀,
**限制 < 500K**)→ 返回 `{ oauth_id, url, headimgurl }`(后端校验 PNG 魔数 → COS,回写 `wms_user_oauth.headimgurl`)
⚠️ 合规:微信自 2022-10 回收 `getUserProfile`,头像昵称**只能由用户主动提供**:
头像 = `<button open-type="chooseAvatar">`,昵称 = `<input type="nickname">`。
⚠️ 头像不能直接上传:`chooseAvatar` 给的是**临时文件路径**且格式 / 体积都不受控。
本地规整统一在 `utils/avatar.ts` 的 `avatarFileToPngBase64()`:
cover 居中裁剪 → 转 PNG → 按 `SIZE_STEPS`(400→120)逐级缩小,直到估算字节数 < 500K。
两个坑:① 用旧版 `canvas-id` API(`uni.createCanvasContext`),
**必须传页面实例**且页面要**真实渲染**画布(故画布放屏外,不能 `v-if`);
② PNG 体积取决于画面复杂度、不可预估,所以是「试到手为止」而非写死一个尺寸。
前端落点:`api/user/user.ts`(两个接口封装)、
`store/modules/user.ts`(`wechatNickname` / `headimgurl` / `canEditWechatProfile`
+ `updateWechatProfile()` / `uploadWechatHeadimg()`)、
`utils/avatar.ts`(头像规整)、`pages/mine/user-info.vue`(「微信资料」卡片 + 编辑弹窗)。
⚠️ 昵称 / 头像改完**不重拉 `user.info`**:直接把接口返回值合并进 `store.user`
(`applyWechatProfile()`),既不冲掉 `infoLoaded` 缓存语义,界面也立即刷新。
- [x] **我的登录码(`wechat.getMyLoginCode`)** ✅ 2026-09-22
用途:**反方向**的扫码登录 —— 小程序把自己的登录码展示给用户,
电脑端凭它走 `user.loginByCode`(ye4s 登录码链路)直接登录为本账号,无需在电脑上输密码。
(与第 13.4 节相反:那里是 **PC 出码、小程序确认**;这里是 **小程序出码、PC 登录**。)
接口参数 / 返回(来源:new3 接口工具的 `module/wechat/module.json`):
- 入参:**无**(后端从 token 的 `oauth_id` 取当前微信用户)
- 返回:登录码 = `uuid={id}_{6位随机}`、`form=wechat` 的 JSON base64
⚠️ 后端文档**未列出**返回字段名:代码按 `login_code` 声明,
并在 store 做兼容取值(`login_code` / `loginCode` / `code`),取不到就报错而不是展示 `undefined`
- 鉴权:**微信登录态**(JWT 含 `oauth_id`)—— 账号密码登录的 token 会被拒
⚠️ 语义是「**没有才生成**、已有则原样返回」⇒ 同一个微信账号的码**稳定不变**(不是一次性),
故前端拿到后存进 store 反复展示 / 复制,不重复请求;退出登录时随登录态清掉。
⚠️ 入口条件 = `userStore.canGetMyLoginCode`,三个信号取并集(单看任一个都不可靠):
本地登录渠道为 `wechat`、或 `user.info` 的 `is_bound === false`、或回传了 `oauth_id`。
前端落点:`api/user/user.ts`(`wechatGetMyLoginCode()`)、
`store/modules/user.ts`(`canGetMyLoginCode` / `myLoginCode` + `getMyLoginCode()`)、
`pages/mine/user-info.vue`(「电脑端登录码」卡片 + 登录码弹窗 + 一键复制)。
- [x] **token 与登录态** ✅ - [x] **token 与登录态** ✅
统一存于 `utils/auth.ts`(小程序无 Cookie,故用 `uni.getStorageSync`,key = `token`)。 统一存于 `utils/auth.ts`(小程序无 Cookie,故用 `uni.getStorageSync`,key = `token`)。
同时记录**登录渠道**(storage key = `login_channel`,值 `wechat` / `account`,与 token 同生命周期):
token 本身看不出登录方式,而已绑定的微信登录态在 `user.info` 里又没有 `is_bound` 字段,
靠它才能区分「微信登录态」;部分微信中间层接口(如登录码)只认微信登录态,界面据此控入口。
token 失效由 `utils/request.ts` 统一兜底(清存储 → `reLaunch` 登录页)。 token 失效由 `utils/request.ts` 统一兜底(清存储 → `reLaunch` 登录页)。
- [x] **登录入口与取消(微信审核要求,务必遵守)** ✅ - [x] **登录入口与取消(微信审核要求,务必遵守)** ✅
@ -385,11 +446,13 @@ d:\wechat\
- 启动页 = 首页(`pages/index/index`),未登录可正常浏览 - 启动页 = 首页(`pages/index/index`),未登录可正常浏览
- 登录入口 = 「我的」页**头部的用户信息区**(未登录时文案「点击登录后使用完整功能」+ 右侧箭头; - 登录入口 = 「我的」页**头部的用户信息区**(未登录时文案「点击登录后使用完整功能」+ 右侧箭头;
点击就地弹登录抽屉)—— 不再放独立的「登录 / 注册」按钮 点击就地弹登录抽屉)—— 不再放独立的「登录 / 注册」按钮
- 未绑定时点头部区直接打开绑定入口(各业务功能都不可用,这里最需要操作) - 未绑定时点头部区(或菜单「用户信息」行)→ 进二级页,在那里绑定
(各业务功能都不可用,这里最需要操作)
- 登录页有「取消」:页面栈有上一页则 `navigateBack` 返回来源页, - 登录页有「取消」:页面栈有上一页则 `navigateBack` 返回来源页,
否则退回 `redirect` 指定页 / 首页 否则退回 `redirect` 指定页 / 首页
- 登录成功:回跳 `redirect` 指定页(tabBar 页用 `switchTab`,其余用 `redirectTo`) - 登录成功:回跳 `redirect` 指定页(tabBar 页用 `switchTab`,其余用 `redirectTo`)
- 退出登录:**停留在「我的」页**并自动切回未登录态,不强制跳登录页 - 退出登录:入口在「用户信息」二级页(`pages/mine/user-info`)底部,
退出后**停留在本页**并切回未登录引导态,不强制跳登录页
- [x] **未登录访问控制(改为按需,不做全局拦截)** ✅ - [x] **未登录访问控制(改为按需,不做全局拦截)** ✅
`utils/auth-guard.ts` 只保留 `LOGIN_PAGE` / `getCurrentRoute()` / `redirectToLogin()`。 `utils/auth-guard.ts` 只保留 `LOGIN_PAGE` / `getCurrentRoute()` / `redirectToLogin()`。
@ -400,9 +463,10 @@ d:\wechat\
若后续需要给个别页面做前置校验,在页面内用 `userStore.isLogin` 自行判断并引导, 若后续需要给个别页面做前置校验,在页面内用 `userStore.isLogin` 自行判断并引导,
**不要恢复全局拦截**。 **不要恢复全局拦截**。
- [ ] **不要使用 `getUserProfile`** - [x] **不要使用 `getUserProfile`** ✅ 2026-09-22
该接口自 2022 年 10 月起已被微信回收,返回匿名数据。 该接口自 2022 年 10 月起已被微信回收,返回匿名数据。
获取头像昵称改用 **头像昵称填写能力**(`<button open-type="chooseAvatar">` + `<input type="nickname">`)。 获取头像昵称已改用 **头像昵称填写能力**(`<button open-type="chooseAvatar">` + `<input type="nickname">`),
见第 6 节的「微信资料维护」(`wechat.updateInfo` / `wechat.uploadHeadimg`)。
- [ ] **手机号获取** - [ ] **手机号获取**
需通过 `<button open-type="getPhoneNumber">`,且账号需具备相应权限(通常需企业主体)。 需通过 `<button open-type="getPhoneNumber">`,且账号需具备相应权限(通常需企业主体)。
@ -576,10 +640,11 @@ d:\wechat\
| 空态组件 | ✅ `components/empty-state/`:默认文案「服务器出差了,请稍后再试」+ 「重试」,可再挂一个「去登录」动作位 | | 空态组件 | ✅ `components/empty-state/`:默认文案「服务器出差了,请稍后再试」+ 「重试」,可再挂一个「去登录」动作位 |
| 可见性口径 | `isEntryVisible(meta) = !tabBar && !hidden`,**本地公共清单与后端菜单共用**(避免两处规则不一致) | | 可见性口径 | `isEntryVisible(meta) = !tabBar && !hidden`,**本地公共清单与后端菜单共用**(避免两处规则不一致) |
| 首页入口渲染 | ✅ 已接入(阶段 4):`loading` → `sections`(分组标题 + 子项九宫格)→ `empty-state`(含重试,未登录额外给「去登录」);数据源:未登录 = `LOCAL_PUBLIC_ENTRIES`,已登录 = `permissionStore.entries` | | 首页入口渲染 | ✅ 已接入(阶段 4):`loading` → `sections`(分组标题 + 子项九宫格)→ `empty-state`(含重试,未登录额外给「去登录」);数据源:未登录 = `LOCAL_PUBLIC_ENTRIES`,已登录 = `permissionStore.entries` |
| 「我的」功能菜单 | ✅ 已接入:与首页**同源**(`toSections(permissionStore.entries)`);`entries` 为空时整卡不渲染 | | 「我的」功能菜单 | ❌ 2026-09-22 **已移除**:功能菜单只在首页九宫格,「我的」页不再重复展示(同批移除「当前版本」「运行平台」两行信息) |
| 统一跳转 | ✅ `utils/navigate.ts`:按 `PAGE_REGISTRY` 自动决定 `switchTab` / `navigateTo`,失败提示「暂未开放」 | | 统一跳转 | ✅ `utils/navigate.ts`:按 `PAGE_REGISTRY` 自动决定 `switchTab` / `navigateTo`,失败提示「暂未开放」 |
| 框架示例页 | `pagesA/demo/public`(`public`,未登录九宫格可见)、`pagesA/demo/required`(`required` + 按钮级权限示例);已加入开发编译模式,业务页上线后可删 | | 框架示例页 | `pagesA/demo/public`(`public`,未登录九宫格可见)、`pagesA/demo/required`(`required` + 按钮级权限示例);已加入开发编译模式,业务页上线后可删 |
| 页面归属 | 「首页」`public`、「我的」`optional` —— **两者都是公共页面**(无需登录即可访问,不被拦截) | | 页面归属 | 「首页」`public`、「我的」`optional` —— **两者都是公共页面**(无需登录即可访问,不被拦截);
「用户信息」`pages/mine/user-info` 也是 `optional` + `hidden`(仅从「我的」页菜单进入) |
| 后端菜单 `path` | 用**逻辑路径**(如 `/inbound/list`),由前端映射到物理页面 | | 后端菜单 `path` | 用**逻辑路径**(如 `/inbound/list`),由前端映射到物理页面 |
| 未登录九宫格 | **仅显示公共入口**;为空/请求失败时渲染空态文案(详见《页面渲染框架》§3.5.1) | | 未登录九宫格 | **仅显示公共入口**;为空/请求失败时渲染空态文案(详见《页面渲染框架》§3.5.1) |
| 空态文案(已确认) | 「未登录且为空」与「已登录拿不到数据」**统一**使用「服务器出差了,请稍后再试」+ 「重试」按钮 | | 空态文案(已确认) | 「未登录且为空」与「已登录拿不到数据」**统一**使用「服务器出差了,请稍后再试」+ 「重试」按钮 |
@ -692,6 +757,8 @@ I --> J["PC / 工作台轮询取回 → 登录为该账号"]
- [ ] **扫码绑定**(`scene=2` 预留):现有 `wechat.bindUser` 走账号密码;`bindAccountByTempCode` 在**开放 API** - [ ] **扫码绑定**(`scene=2` 预留):现有 `wechat.bindUser` 走账号密码;`bindAccountByTempCode` 在**开放 API**
且需 `ye4s_user_id`(是 ye4s 后端对 WMS 的机对机调用)→ 小程序侧需后端补一个网关方法 且需 `ye4s_user_id`(是 ye4s 后端对 WMS 的机对机调用)→ 小程序侧需后端补一个网关方法
- [ ] **个人中心「我的二维码」**(工作台扫描获取用户信息)—— 反向链路,待设计 - [ ] **个人中心「我的二维码」**(工作台扫描获取用户信息)—— 反向链路,待设计
✅ 2026-09-22:其中**登录码**部分已实现(`wechat.getMyLoginCode` + 「我的」页展示 / 复制,见第 6 节);
二维码生成与「工作台扫码取用户信息」仍未做
--- ---

View File

@ -589,11 +589,19 @@ sequenceDiagram
- [x] `pages/index/index.vue`:九宫格改为 permission store 驱动,且支持**「分组标题 + 子项九宫格」两层渲染**; - [x] `pages/index/index.vue`:九宫格改为 permission store 驱动,且支持**「分组标题 + 子项九宫格」两层渲染**;
未登录回退 `LOCAL_PUBLIC_ENTRIES`;无内容 / 请求失败时按 §3.5.1 渲染空态文案 未登录回退 `LOCAL_PUBLIC_ENTRIES`;无内容 / 请求失败时按 §3.5.1 渲染空态文案
✅ 2026-09-19:三个分支(`loading` → `sections` → `empty-state`); ✅ 2026-09-19:三个分支(`loading` → `sections` → `empty-state`);
分组/叶子拍平共用 `toSections()`,与「我的」口径一致 分组/叶子拍平由 `toSections()` 统一处理
- [x] `pages/mine/mine.vue`:已登录时展示**「身份信息」卡片**(数据来自 `user.info` 的 `employees[]`,不改数据库)✅ 2026-09-19 - [x] `pages/mine/mine.vue`:已登录时展示**「身份信息」卡片**(数据来自 `user.info` 的 `employees[]`,不改数据库)✅ 2026-09-19
- [x] `pages/mine/mine.vue`:已登录时展示「功能菜单」(来自 entries);未登录保持现状 ↳ 2026-09-22 **已迁入二级页** `pages/mine/user-info.vue`(见下)
- [x] 2026-09-22 **「我的」页改为「菜单 + 二级页」结构**:
- `pages/mine/mine.vue` 只留「登录入口 / 菜单 / 退出登录」(缓解 tabBar 页堆卡片)
- 新增 `pages/mine/user-info.vue`(`key=/mine/user-info`,`auth: optional` + `hidden: true`):
用户信息(身份信息 + 切换身份)、待绑定 WMS 账号、微信资料、电脑端登录码、退出登录
- 跳转统一走 `getPageByKey()` + `navigateToPath()`:**物理路径只有 `PAGE_REGISTRY` 一份**,页面里不写死
- 未登录进入二级页时渲染页内引导(`empty-state` + 「去登录」),**不自动跳转**
- [x] ~~`pages/mine/mine.vue`:已登录时展示「功能菜单」(来自 entries)~~
✅ 2026-09-19:与首页**同源**(`toSections(permissionStore.entries)`); ✅ 2026-09-19:与首页**同源**(`toSections(permissionStore.entries)`);
⚠️ `entries` 为空时**整卡不渲染**(不在「我的」再堆一份空态,「首页」才是空态的归属地) ❌ 2026-09-22 **已移除**:功能菜单只留在首页九宫格,「我的」页只放与账号相关的项
(身份信息 / 清除本地缓存 / 退出登录);同批移除「当前版本」「运行平台」两行
- [x] 新增一个**未登录可用的公开页**作为 `public` 示例(原计划的「库存」tab 已于 2026-09-19 精简移除) - [x] 新增一个**未登录可用的公开页**作为 `public` 示例(原计划的「库存」tab 已于 2026-09-19 精简移除)
✅ `pagesA/demo/public`(分包,`auth: 'public'`,不设 `hidden`) ✅ `pagesA/demo/public`(分包,`auth: 'public'`,不设 `hidden`)
- [x] 至少再造 1 个 `required` 页示例,验证「页内请先登录」体验 - [x] 至少再造 1 个 `required` 页示例,验证「页内请先登录」体验