feat: 微信扫码登录 + 半屏登录抽屉(接口级鉴权)

微信登录与绑定、spm 场景解析、确认登录页;登录入口改为半屏抽屉并做接口级鉴权;协议勾选必须滑到底部;账号/注册表单去 label、tab 靠左等排版调整;打开抽屉时隐藏原生 tabBar
This commit is contained in:
liufumingren 2026-09-22 02:18:38 +08:00
parent e1b2641e49
commit 36fd7eef10
25 changed files with 7927 additions and 422 deletions

5241
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,24 +1,86 @@
<script setup lang="ts"> <script setup lang="ts">
import { onLaunch, onShow, onHide } from "@dcloudio/uni-app"; import { onLaunch, onShow, onHide } from "@dcloudio/uni-app";
import { watch } from "vue";
import { useUserStore } from "@/store/modules/user"; import { useUserStore } from "@/store/modules/user";
import { getToken } from "@/utils/auth"; import { getToken } from "@/utils/auth";
import { normalizeEntry, savePendingEntry, hasEntryAction } from "@/utils/entry";
import type { EntryLaunchOptions } from "@/utils/entry";
import { setUnauthorizedHandler } from "@/utils/auth-notify";
onLaunch(() => { /**
* 捕获入口参数(扫码 / 链接 / 分享进入)
*
* 只**捕获并暂存**,不在这里处理跳转:
* - `onLaunch` 时页面栈还没就绪,`navigateTo` 会失败
* - 真正处理交给页面(首页 `useEntryScene()`),保证跳转时机安全
*
* 冷启动走 `onLaunch`,热启动(小程序在后台时被扫码 / 链接唤起)走 `onShow`,
* 两处都要接,否则热启动的入口会被丢掉。
*/
function captureEntry(options?: EntryLaunchOptions) {
const entry = normalizeEntry(options);
if (!hasEntryAction(entry)) return;
console.log("[entry] 捕获入口参数", entry);
savePendingEntry(entry);
}
/**
* 按登录抽屉的开合状态同步原生 tabBar
*
* 为什么必须手动藏:微信小程序的 tabBar 是**原生组件**,层级恒在 `position: fixed` 的
* popup 之上 —— 抽屉弹出时会被它切掉一截(看起来没贴到屏幕底部)。这是原生层的限制,
* 改 z-index 无用,只能打开时把它隐藏掉。
*
* ⚠️ 非 tabBar 页面调用 hideTabBar 会 fail(page is not tabBar page),
* 这里的空 `fail` 就是用来吞掉它的。
*/
function syncTabBar(visible: boolean) {
const options = { animation: false, fail: () => {} };
if (visible) uni.hideTabBar(options);
else uni.showTabBar(options);
}
// 抽屉开 → 藏 tabBar;抽屉关 → 恢复(H5 / 小程序共用同一套逻辑)
watch(
() => useUserStore().authVisible,
(visible) => syncTabBar(visible)
);
onLaunch((options) => {
// ⚠️ 这里**不要**做「未登录就跳登录页」的判断。 // ⚠️ 这里**不要**做「未登录就跳登录页」的判断。
// 微信审核要求:打开小程序不能直接强制登录,登录入口必须由用户主动触发 // 微信审核要求:打开小程序不能直接强制登录,登录入口必须由用户主动触发
// (本项目放在「我的」页的「登录 / 注册」按钮)。 // (现在登录入口统一是**半屏抽屉**,见 store 的 `showAuthModal`)。
// 登录态兜底统一由 utils/request.ts 在收到 HTTP 401 时处理(带来源页跳登录)。 captureEntry(options as EntryLaunchOptions);
// 启动时若本地已有 token(上次登录且未失效)→ 统一拉一次用户信息, // 未授权(未登录 / token 失效)时的统一处理:**弹登录抽屉**,而不是跳登录页
// 让首页九宫格 / 「我的」在进入任何页面之前就拿到 menus + permissions。 // —— 用户正浏览到哪儿就地弹出,登录完继续留在原页面,不打断浏览。
// 注册在这里(而不是在 request 里直接调 store)是为了避开 request ↔ store 循环依赖。
setUnauthorizedHandler(() => {
useUserStore().showAuthModal();
});
// 启动时若本地已有 token(上次登录且未失效)→ 统一拉一次 user.info 灌进 store,
// 作为**全局唯一的用户信息来源**:首页九宫格 / 「我的」/ 其它页面只读 store,不各自发请求。
// 失败不提示:token 真失效时由 request 层的 401 兜底(清登录态 + 带 redirect 跳登录)。 // 失败不提示:token 真失效时由 request 层的 401 兜底(清登录态 + 带 redirect 跳登录)。
if (!getToken()) return; if (!getToken()) return;
useUserStore() useUserStore()
.getInfo() .getInfo()
.catch(() => {}); .catch(() => {});
}); });
onShow(() => { /**
console.log("App Show"); * uni-app 的组合式 `onShow` 类型签名是不带参数的,但**微信端运行时会传启动参数**
* (热启动被扫码 / 链接唤起时,入口参数只在这里给到;类型声明里 `App.onShow(options?)` 也有该参数)。
* 故此处按运行时真实行为做一次类型断言,行为与 `onLaunch` 保持一致。
*/
const onAppShow = onShow as unknown as (
handler: (options: EntryLaunchOptions) => void
) => void;
onAppShow((options) => {
// 热启动同样可能带参(后台被扫码唤起),必须一并捕获
captureEntry(options);
// 兜底:回前台时按当前状态再同步一次,避免出现「抽屉已经关了、tabBar 却没回来」
syncTabBar(useUserStore().authVisible);
}); });
onHide(() => { onHide(() => {
console.log("App Hide"); console.log("App Hide");

View File

@ -85,6 +85,14 @@ export interface EmployeeInfo {
export interface UserInfoResult { export interface UserInfoResult {
employees_id?: number employees_id?: number
employees_name?: string employees_name?: string
/**
* 是否已绑定真实账号
*
* **仅微信登录态中间层会下发**:未绑定微信登录(token 里 `id=0`)时后端返回
* `is_bound: false` + 微信层信息(openid / unionid / oauth_id),**不返回 401**。
* 正常账号登录的信息里没有该字段(`undefined`)。
*/
is_bound?: boolean
/** 该账号的全部可用身份 */ /** 该账号的全部可用身份 */
employees?: EmployeeInfo[] employees?: EmployeeInfo[]
permissions?: string[] permissions?: string[]
@ -93,6 +101,46 @@ export interface UserInfoResult {
[key: string]: any [key: string]: any
} }
/**
* 微信小程序登录入参(`wechat.loginByCode`)
*
* `app_id` / `appid` **二选一,至少传一个**:
* - `app_id`:`wms_wechat_app.id`(整数主键)—— PC 端后台等已知业务库的场景
* - `appid` :小程序真实 AppID(`wx.getAccountInfoSync().miniProgram.appId`)
* —— **本项目用这个**:代码作为开放平台模板发布给多个仓库,
* 各仓库 AppID 不同且运行时才确定,构建期无法写死
*/
export interface WechatLoginParams {
/** `uni.login` 取得的临时 code(一次性,5 分钟有效) */
code: string
/** `wms_wechat_app.id`(整数主键) */
app_id?: number | string
/** 小程序真实 AppID(字符串,非主键);后端反查授权记录 */
appid?: string
}
/** 微信登录 / 绑定返回的用户信息 */
export interface WechatUserInfo {
/** WMS 账号 ID;**0 = 该微信尚未绑定 WMS 账号**(仅有微信登录态) */
id: number
/** `wms_user_oauth.id`:微信登录态主键,绑定接口靠它定位记录 */
oauth_id: number
openid?: string
unionid?: string
nickname?: string
headimgurl?: string
username?: string
real_name?: string
phone?: string
[key: string]: any
}
/** 微信登录 / 绑定的返回结构(参考 `auth.login`) */
export interface WechatLoginResult {
token: string
user: WechatUserInfo
}
// ────────────────────────────── 接口 ────────────────────────────── // ────────────────────────────── 接口 ──────────────────────────────
/** 账号密码登录 */ /** 账号密码登录 */
@ -115,13 +163,27 @@ export function register(data: UserRegisterParams): Promise<BizResponse<any>> {
}) })
} }
/** 获取用户信息(含权限点与菜单) */ /**
export function getInfo(data: Record<string, any> = {}): Promise<BizResponse<UserInfoResult>> { * 获取用户信息(含权限点与菜单)
*
* 也是**微信登录态的探测接口**:未绑定的微信登录(token 里 `id=0`)调用它不会 401,
* 而是返回 `is_bound: false` + 微信层信息。
*
* @param data 额外入参(默认带 device)
* @param token 显式指定 token —— 微信登录未绑定时 token 只存内存、未落地,需手工带上
*/
export function getInfo(
data: Record<string, any> = {},
token?: string
): Promise<BizResponse<UserInfoResult>> {
return request<UserInfoResult>({ return request<UserInfoResult>({
url: SYSTEM_URL, url: SYSTEM_URL,
method: 'POST', method: 'POST',
params: gatewayParams('user.info'), params: gatewayParams('user.info'),
data data,
// 需要登录:未登录时连请求都不发,直接弹登录抽屉(省一次无意义的 401 往返)
auth: true,
...(token ? { header: { Authorization: `Bearer ${token}` } } : {})
}) })
} }
@ -138,7 +200,8 @@ export function changeRole(
url: SYSTEM_URL, url: SYSTEM_URL,
method: 'POST', method: 'POST',
params: gatewayParams('user.changeRole'), params: gatewayParams('user.changeRole'),
data data,
auth: true
}) })
} }
@ -148,6 +211,78 @@ export function logout(data: Record<string, any> = {}): Promise<BizResponse<any>
url: SYSTEM_URL, url: SYSTEM_URL,
method: 'POST', method: 'POST',
params: gatewayParams('user.logout'), params: gatewayParams('user.logout'),
data,
auth: true
})
}
/**
* 微信小程序一键登录(**免登录接口**)
*
* `uni.login` 的 code → 后端 `jscode2session` 换 openid/session_key → 查/建 `wms_user_oauth`
* → 签发 token。
*
* ⚠️ 该接口**不代表业务登录成功**:微信首次登录时后端返回的 token 里 `id = 0`
* (尚未绑定 WMS 账号),此时需再调 `wechatBindUser` 完成绑定。
*/
export function wechatLogin(
data: WechatLoginParams
): Promise<BizResponse<WechatLoginResult>> {
return request<WechatLoginResult>({
url: SYSTEM_URL,
method: 'POST',
params: gatewayParams('wechat.loginByCode'),
data data
}) })
} }
/**
* 绑定 WMS 账号(微信登录态中间层接口,未绑定也可访问)
*
* 后端从**请求头里的 token** 取 `oauth_id` 定位 `wms_user_oauth` 记录;
* 该 token 在微信登录时已写入本地存储,`request` 会自动带上,一般无需传 `token`。
* 绑定成功后返回换发的正式 token(`user.id` 为真实账号 ID)。
*
* @param data 账号密码
* @param token 可选:显式指定微信登录 token(缺省用本地存储里的)
*/
export function wechatBindUser(
data: { username: string; password: string },
token?: string
): Promise<BizResponse<WechatLoginResult>> {
return request<WechatLoginResult>({
url: SYSTEM_URL,
method: 'POST',
params: gatewayParams('wechat.bindUser'),
data,
// 微信登录态失效时后端用业务码 401 表达:不要跟着全局逻辑清登录态 + 跳登录页,
// 否则用户会被踢出页面、输入丢失 —— 只 toast「微信登录态不存在」由用户重新微信登录
redirectOn401: false,
...(token ? { header: { Authorization: `Bearer ${token}` } } : {})
})
}
/**
* 确认登录码(**需登录**,扫码登录链路的「小程序侧确认」)
*
* 后端语义(见 `D:\wms\app\service\systems\wechat.js` 的 `pushLoginCode`):
* 用**当前鉴权用户**标记登录码为 success,展示该码的一方(PC / 工作台)
* 轮询取回后即登录为本账号。
*
* 入参 `code` = 二维码里 spm 的第 3 段(6 位数字登录码)。
* ⚠️ 登录码有 TTL(生成 300s / 确认后 120s),过期后需重新出码。
*/
export function wechatPushLoginCode(data: {
code: string
}): Promise<BizResponse<{ code: string; status: string }>> {
return request<{ code: string; status: string }>({
url: SYSTEM_URL,
method: 'POST',
params: gatewayParams('wechat.pushLoginCode'),
data,
// 需要**业务登录**:未登录时不发请求,直接弹登录抽屉
auth: true,
// 未登录时后端返回业务码 401,这里只提示、不触发全局跳登录(由调用方引导登录)
redirectOn401: false
})
}

View File

@ -0,0 +1,73 @@
<template>
<!--
半屏登录抽屉
为什么用抽屉而不是跳登录页(这是「只在需要时才要求登录」的关键):
- 用户在哪个页面需要登录,就地弹出来,**不打断浏览**,登录完继续留在原页面
- 页面级不拦(`PAGE_REGISTRY.auth` 只声明),真正触发点是「碰到需要登录的接口」
- 状态由 store 的 `authView` 一个字段管(开 / 切视图 / 关),任意页面都能唤起
⚠️ uni-app 的 `App.vue` 没有模板,挂不了全局组件 → 需要在页面里各引一次:
`<auth-modal />`(同一时刻只有当前页面的那个可见,靠 store 共享状态)
-->
<up-popup
:show="userStore.authVisible"
mode="bottom"
:round="24"
:safeAreaInsetBottom="true"
@close="userStore.closeAuthModal()"
>
<view class="auth-modal">
<!-- v-if 让每次打开都重新挂载:视图与「协议勾选」状态自动复位(每次都要重新勾选) -->
<login-panel
v-if="userStore.authVisible"
:initial-view="initialView"
show-cancel
@success="onSuccess"
@cancel="userStore.closeAuthModal()"
></login-panel>
</view>
</up-popup>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { useUserStore } from '@/store/modules/user'
import LoginPanel from '@/components/login-panel/login-panel.vue'
const userStore = useUserStore()
/**
* 抽屉打开时落到哪个视图
*
* store 里的 `authView` 既是开关也是视图选择器:
* `showAuthModal()` → 'wechat'(默认,占用空间最小)
* `showAuthModal('account')` → 直接落到账号登录
* `showAuthModal('register')`→ 直接落到注册
*/
const initialView = computed(
() => (userStore.authView || 'wechat') as 'wechat' | 'account' | 'register'
)
/**
* 登录 / 绑定成功
*
* 只关抽屉、不跳页 —— 用户留在原来所在的页面;
* 页面数据(`permissions` / `menus` / 身份)在 store 里已是响应式的,会自动刷新。
*
* 如果用户是从某个「需要登录的按钮」点进来的,重新点一次即可(与 `G:\uni\数据` 行为一致,
* 不做自动重放请求:原请求的参数可能已失效,静默重放反而容易出意外)。
*/
const onSuccess = () => {
userStore.closeAuthModal()
uni.showToast({ title: '登录成功', icon: 'none' })
}
</script>
<style lang="scss" scoped>
.auth-modal {
/* 抽屉自带底部安全区适配(up-popup 的 safeAreaInsetBottom),这里只保证最小高度 */
min-height: 400rpx;
background-color: #ffffff;
}
</style>

View File

@ -1,120 +1,61 @@
<template> <template>
<view class="login-panel"> <view class="login-panel">
<!-- ── 品牌区 ── --> <!-- ═══════════ 头部:tab 靠左 / 关闭在右 ═══════════ -->
<view class="login-panel__brand"> <view class="login-panel__bar">
<view class="login-panel__logo"> <!-- 登录视图:微信 / 账号 两个 tab(微信在前,占用空间小) -->
<image v-if="logo" class="login-panel__logo-img" :src="logo" mode="aspectFit"></image> <view
<up-icon v-else name="server-man" color="#ffffff" size="46"></up-icon> v-if="!wxBinding && (view === 'wechat' || view === 'account')"
</view> class="login-panel__tabs"
<text class="login-panel__brand-title">{{ title }}</text>
<text class="login-panel__brand-desc">{{ desc }}</text>
</view>
<!-- ── 表单卡片 ── -->
<view class="login-panel__card">
<view class="login-panel__head">
<text class="login-panel__head-title">{{ isRegister ? '注册账号' : '账号登录' }}</text>
<text class="login-panel__head-sub">
{{ isRegister ? '开启您的管理之旅' : '欢迎回来,请登录您的账户' }}
</text>
</view>
<!-- ========== 注册表单 ========== -->
<up-form
v-if="isRegister"
ref="registerFormRef"
:model="registerForm"
:rules="registerRules"
labelPosition="top"
> >
<up-form-item label="账号" prop="username" required> <view
<up-input class="login-panel__tab"
v-model="registerForm.username" :class="{ 'login-panel__tab--active': view === 'wechat' }"
:color="INPUT_COLOR" @click="view = 'wechat'"
:placeholder-style="PLACEHOLDER_STYLE" >
placeholder="请输入账号" 微信登录
prefixIcon="account" </view>
clearable <view
maxlength="30" class="login-panel__tab"
></up-input> :class="{ 'login-panel__tab--active': view === 'account' }"
</up-form-item> @click="view = 'account'"
>
账号登录
</view>
</view>
<up-form-item label="邮箱" prop="email"> <!-- 注册 / 绑定视图:显示标题 -->
<up-input <view v-else class="login-panel__bar-title">
v-model="registerForm.email" {{ wxBinding ? '绑定 WMS 账号' : '注册账号' }}
:color="INPUT_COLOR" </view>
:placeholder-style="PLACEHOLDER_STYLE"
placeholder="请输入邮箱"
prefixIcon="email"
clearable
maxlength="50"
></up-input>
</up-form-item>
<up-form-item label="姓名" prop="real_name"> <!-- 关闭(右上角,替代原来占一整行的「取消」) -->
<up-input <view v-if="showCancel" class="login-panel__close" @click="emit('cancel')">
v-model="registerForm.real_name" <up-icon name="close" color="#c0c4cc" size="20"></up-icon>
:color="INPUT_COLOR" </view>
:placeholder-style="PLACEHOLDER_STYLE" </view>
placeholder="请输入真实姓名"
prefixIcon="account-fill"
clearable
maxlength="20"
></up-input>
</up-form-item>
<up-form-item label="密码" prop="password" required> <!-- ═══════════ 1. 微信登录 ═══════════ -->
<up-input <view v-if="view === 'wechat' && !wxBinding" class="login-panel__body">
v-model="registerForm.password" <view class="login-panel__desc">使用微信一键登录,无需记住密码</view>
type="password"
:color="INPUT_COLOR"
:placeholder-style="PLACEHOLDER_STYLE"
placeholder="请输入密码(不少于 6 位)"
prefixIcon="lock"
clearable
maxlength="30"
></up-input>
</up-form-item>
<up-form-item label="确认密码" prop="confirmPassword" required>
<up-input
v-model="registerForm.confirmPassword"
type="password"
:color="INPUT_COLOR"
:placeholder-style="PLACEHOLDER_STYLE"
placeholder="请再次输入密码"
prefixIcon="lock"
clearable
maxlength="30"
@confirm="handleRegister"
></up-input>
</up-form-item>
<view class="login-panel__submit">
<up-button <up-button
type="primary" icon="weixin-fill"
color="#07c160"
shape="circle" shape="circle"
:loading="loading" :loading="wxLoading"
:text="loading ? '注册中...' : '注 册'" :text="wxLoading ? '正在登录...' : '微信一键登录'"
@click="handleRegister" @click="handleWechatLogin"
></up-button> ></up-button>
</view> </view>
<view class="login-panel__foot"> <!-- ═══════════ 2. 账号密码登录 ═══════════ -->
<text class="login-panel__foot-text">已有账号?</text> <!-- 不写 label:「账号:」「密码:」会各自占掉一整行,靠 placeholder 已足够区分 -->
<text class="login-panel__link" @click="switchMode(false)">立即登录</text>
</view>
</up-form>
<!-- ========== 登录表单 ========== -->
<up-form <up-form
v-else v-else-if="view === 'account' && !wxBinding"
ref="loginFormRef" ref="loginFormRef"
:model="loginForm" :model="loginForm"
:rules="loginRules" :rules="loginRules"
labelPosition="top"
> >
<up-form-item label="账号" prop="username" required> <up-form-item prop="username">
<up-input <up-input
v-model="loginForm.username" v-model="loginForm.username"
:color="INPUT_COLOR" :color="INPUT_COLOR"
@ -126,7 +67,7 @@
></up-input> ></up-input>
</up-form-item> </up-form-item>
<up-form-item label="密码" prop="password" required> <up-form-item prop="password">
<up-input <up-input
v-model="loginForm.password" v-model="loginForm.password"
type="password" type="password"
@ -139,8 +80,94 @@
@confirm="handleLogin" @confirm="handleLogin"
></up-input> ></up-input>
</up-form-item> </up-form-item>
</up-form>
<view class="login-panel__submit"> <!-- ═══════════ 3. 注册 ═══════════ -->
<!--
同样不写 label:字段虽多,但「placeholder + 左侧图标」已足够区分,
label 会凭空多占 5 行高度(这是注册表单最大的一笔浪费)。
-->
<up-form
v-else-if="view === 'register'"
ref="registerFormRef"
:model="registerForm"
:rules="registerRules"
>
<up-form-item prop="username">
<up-input
v-model="registerForm.username"
:color="INPUT_COLOR"
:placeholder-style="PLACEHOLDER_STYLE"
placeholder="请输入账号"
prefixIcon="account"
clearable
maxlength="30"
></up-input>
</up-form-item>
<up-form-item prop="real_name">
<up-input
v-model="registerForm.real_name"
:color="INPUT_COLOR"
:placeholder-style="PLACEHOLDER_STYLE"
placeholder="请输入真实姓名"
prefixIcon="account-fill"
clearable
maxlength="20"
></up-input>
</up-form-item>
<up-form-item prop="email">
<up-input
v-model="registerForm.email"
:color="INPUT_COLOR"
:placeholder-style="PLACEHOLDER_STYLE"
placeholder="请输入邮箱"
prefixIcon="email"
clearable
maxlength="50"
></up-input>
</up-form-item>
<up-form-item prop="password">
<up-input
v-model="registerForm.password"
type="password"
:color="INPUT_COLOR"
:placeholder-style="PLACEHOLDER_STYLE"
placeholder="设置密码(不少于 6 位)"
prefixIcon="lock"
clearable
maxlength="30"
></up-input>
</up-form-item>
<up-form-item prop="confirmPassword">
<up-input
v-model="registerForm.confirmPassword"
type="password"
:color="INPUT_COLOR"
:placeholder-style="PLACEHOLDER_STYLE"
placeholder="再次输入密码"
prefixIcon="lock-fill"
clearable
maxlength="30"
@confirm="handleRegister"
></up-input>
</up-form-item>
</up-form>
<!-- ═══════════ 4. 微信登录后尚未绑定账号 ═══════════ -->
<wechat-bind-form
v-else-if="wxBinding"
show-skip
submit-text="绑定并登录"
@success="emit('success')"
@skip="emit('success')"
></wechat-bind-form>
<!-- ═══════════ 主按钮(微信 tab 的按钮在上面,这里只服务账号 / 注册)═══════════ -->
<view v-if="view === 'account' && !wxBinding" class="login-panel__submit">
<up-button <up-button
type="primary" type="primary"
shape="circle" shape="circle"
@ -150,37 +177,104 @@
></up-button> ></up-button>
</view> </view>
<view class="login-panel__foot"> <view v-if="view === 'register'" class="login-panel__submit">
<text class="login-panel__foot-text">还没有账号?</text> <up-button
<text class="login-panel__link" @click="switchMode(true)">立即注册</text> type="primary"
shape="circle"
:loading="loading"
:text="loading ? '注册中...' : '注 册'"
@click="handleRegister"
></up-button>
</view> </view>
</up-form>
<!-- 取消:文字链形式(不用按钮样式,避免与主按钮「登录 / 注册」争夺视觉权重) <!-- ═══════════ 协议勾选(微信登录 / 账号登录 / 注册都要求;绑定步骤不需要)═══════════ -->
放在两个表单之外只需一处;具体返回哪里由使用方决定 --> <!--
<view v-if="showCancel" class="login-panel__cancel" @click="emit('cancel')"> 协议勾选:整块**任何位置点击都只是「打开用户须知」**,不能直接把勾打上 ——
<text class="login-panel__cancel-text">取消</text> 必须点开、滑读到底部、在弹窗里点「我已知晓并同意」,勾才会置上(合规更稳)
-->
<view v-if="!wxBinding" class="login-panel__agree" @click="openAgreement">
<view class="login-panel__checkbox">
<up-icon
:name="agreed ? 'checkmark-circle-fill' : 'checkmark-circle'"
:color="agreed ? '#2979ff' : '#c0c4cc'"
size="18"
></up-icon>
</view>
<text class="login-panel__agree-text">我已阅读并同意</text>
<text class="login-panel__agree-link">《用户须知》</text>
</view>
<!-- ═══════════ 底部链接(绑定步骤不显示)═══════════ -->
<view v-if="!wxBinding" class="login-panel__foot">
<template v-if="view === 'account' || view === 'wechat'">
<text class="login-panel__foot-text">还没有账号?</text>
<text class="login-panel__link" @click="view = 'register'">注册账号</text>
</template>
<template v-else-if="view === 'register'">
<text class="login-panel__foot-text">已有账号?</text>
<text class="login-panel__link" @click="view = 'account'">返回登录</text>
</template>
</view>
<!--
用户须知弹窗
必须滑动到底部才能同意:`scrolltolower` 到底 → `agreementRead` 置真。
(内容不足一屏时会在打开后自动置真,否则用户永远滚不到底也就永远点不了)
-->
<up-popup :show="showAgreement" mode="center" :round="16" @close="showAgreement = false">
<view class="agreement">
<view class="agreement__title">用户须知</view>
<scroll-view
class="agreement__body"
scroll-y
:lower-threshold="16"
@scrolltolower="onAgreementLower"
>
<view class="agreement__inner">
<text class="agreement__text">{{ AGREEMENT_TEXT }}</text>
</view>
</scroll-view>
<view class="agreement__action">
<view v-if="!agreementRead" class="agreement__tip">
<up-icon name="arrow-downward" color="#f0a020" size="14"></up-icon>
<text>请向下滑动阅读至底部</text>
</view>
<up-button
type="primary"
shape="circle"
text="我已知晓并同意"
:class="{ 'is-disabled': !agreementRead }"
@click="onAgreeConfirm"
></up-button>
</view> </view>
</view> </view>
</up-popup>
</view> </view>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
/** /**
* 登录 / 注册面板 * 登录面板(微信登录 / 账号登录 / 注册 / 绑定账号)
* *
* 与 new3(Web 端)`src/views/login/index.vue` 的账号密码登录 + 注册部分对齐。 * 一套内容同时服务两个容器:
* 已裁剪:微信扫码登录(小程序端不适用,小程序自身的微信登录属于另一条链路)。 * 1. `components/auth-modal/` —— 半屏抽屉(主入口,任意页面可就地唤起)
* 2. `pages/login/login.vue` —— 独立页面(401 兜底、直接访问)
*
* 排版约定:
* - **头部一行**:tab 靠左(微信登录在前,空间占用小),关闭图标靠右 —— 不再占一整行放「取消」
* - **账号登录不写 label**:靠 placeholder 区分,省掉两行高度,与微信登录高度接近
* - **注册也不写 label**:字段虽多,但 placeholder + 左侧图标已足够区分,省掉 5 行
* - 微信登录 / 账号登录 / 注册**都必须勾选**《用户须知》,未勾选点按钮会先提示
* *
* 设计约定: * 设计约定:
* - 组件只负责「表单 + 校验 + 调接口」,登录成功只抛 success 事件; * - 组件只负责「表单 + 校验 + 调接口」,登录成功只抛 `success` 事件;
* 跳转策略(回跳来源页 / 进首页)由使用方决定,方便在弹窗等场景复用。 * 关不关抽屉、跳不跳页由使用方决定(保证抽屉 / 页面两种容器都能复用)。
* - 「取消」同理:传 `show-cancel` 才显示取消按钮,点击只抛 cancel 事件。 * - 失败提示由 `utils/request` 统一 toast,组件内不重复提示。
* - 失败提示由 `utils/request` 统一 toast,组件内不再重复提示。
*/ */
import { reactive, ref } from 'vue' import { getCurrentInstance, reactive, ref } from 'vue'
import { useUserStore } from '@/store/modules/user' import { useUserStore } from '@/store/modules/user'
import WechatBindForm from '@/components/wechat-bind-form/wechat-bind-form.vue'
/** u-form 实例上本项目实际用到的方法 */ /** u-form 实例上本项目实际用到的方法 */
interface FormInstance { interface FormInstance {
@ -190,51 +284,137 @@ interface FormInstance {
const props = withDefaults( const props = withDefaults(
defineProps<{ defineProps<{
/** 品牌 Logo,传空串则退化为内置图标 */ /** 初始视图(抽屉打开时想直接落到账号登录 / 注册就传对应值) */
logo?: string initialView?: 'wechat' | 'account' | 'register'
title?: string /** 是否显示右上角关闭(抽屉里必须给,否则用户只能点遮罩退出) */
desc?: string
/** 初始模式 */
initialMode?: 'login' | 'register'
/** 是否显示「取消」按钮(由使用方决定点击后去哪) */
showCancel?: boolean showCancel?: boolean
}>(), }>(),
{ {
logo: '', initialView: 'wechat',
title: 'WMS 小程序',
desc: '仓储管理系统 · 微信小程序端',
initialMode: 'login',
showCancel: false showCancel: false
} }
) )
const emit = defineEmits<{ const emit = defineEmits<{
(e: 'success'): void (e: 'success'): void
(e: 'change', mode: 'login' | 'register'): void
(e: 'cancel'): void (e: 'cancel'): void
}>() }>()
const userStore = useUserStore() const userStore = useUserStore()
/** 当前组件实例:`createSelectorQuery().in()` 查子节点尺寸时要用 */
const instance = getCurrentInstance()
/**
* 用户须知
*
* 目前是前端静态文案;如果后续要由后端下发(可配置、可审计),
* 换成请求接口即可,弹窗结构与勾选逻辑都不用动。
*/
const AGREEMENT_TEXT = `欢迎使用 WMS 仓储管理系统小程序。
一、账号与权限
1. 本小程序仅供仓库工作人员及经授权的用户使用,账号由管理员统一分配。
2. 请妥善保管账号与密码,勿转借他人;因账号外借、泄露造成的操作记录与损失,由账号持有人承担。
3. 您有多个身份(仓库 / 货主 / 平台)时,请确认当前身份后再操作,切换身份后的操作记录同样计入对应身份。
二、数据与操作记录
4. 登录后产生的操作记录(入库、出库、盘点、调拨等)将作为业务凭据留存,请如实操作。
5. 为保证数据准确,请勿在未授权设备上登录;发现账号异常请及时联系管理员。
三、个人信息
6. 为完成登录与身份识别,我们会获取您的微信授权标识、账号、姓名及所属组织信息,仅用于本系统内的身份校验与业务处理。
7. 我们不会将上述信息用于本系统以外的用途,也不会向无关第三方提供。
四、其他
8. 使用中如遇权限不足、功能异常,请联系所属仓库主管或系统管理员。
9. 本须知的解释权归系统运营方所有,内容如有调整将在本小程序内公示。
继续使用即表示您已阅读并同意上述全部内容。`
/** 当前视图:'wechat' | 'account' | 'register' */
const view = ref<'wechat' | 'account' | 'register'>(props.initialView)
/** 是否已勾选《用户须知》 */
const agreed = ref(false)
/** 用户须知弹窗 */
const showAgreement = ref(false)
/** 用户须知是否已滑到【底部】(没滑到底就不允许同意) */
const agreementRead = ref(false)
/** 微信登录后尚未绑定 WMS 账号 → 面板切到绑定步骤 */
const wxBinding = ref(false)
const loading = ref(false)
const wxLoading = ref(false)
const loginFormRef = ref<FormInstance | null>(null) const loginFormRef = ref<FormInstance | null>(null)
const registerFormRef = ref<FormInstance | null>(null) const registerFormRef = ref<FormInstance | null>(null)
const isRegister = ref(props.initialMode === 'register')
const loading = ref(false)
/** /**
* 输入文字 / 占位符颜色(必须显式指定) * 输入文字 / 占位符颜色(必须显式指定)
* *
* `up-input` 的文字色实现为:`color: this.color || 主题变量 --up-main-color`, * `up-input` 的文字色实现为 `color: this.color || 主题变量 --up-main-color`,
* 而 uview-plus 在暗色主题下把 `--up-main-color` 定义为 `#f5f5f5`(近白), * uview-plus 暗色主题下 `--up-main-color` 是近白色,白底上几乎看不见;
* 白底卡片上几乎看不见输入内容。 * 它是**内联样式**(JS 计算后写到 style),CSS 盖不住,只能用 `color` 属性指定。
* 它是**内联样式**(JS 计算后写到 style 上),CSS 盖不住,只能用 `color` 属性指定。
* 占位符同理,显式给一个明显更浅的灰,与已输入文字形成对比。
*/ */
const INPUT_COLOR = '#303133' const INPUT_COLOR = '#303133'
const PLACEHOLDER_STYLE = 'color: #c0c4cc' const PLACEHOLDER_STYLE = 'color: #c0c4cc'
// ──────────────────────── 登录表单 ──────────────────────── // ────────────────────────── 协议勾选 ──────────────────────────
const openAgreement = () => {
// 已经同意过就不必再逼着滑一遍(只有「还没同意」时才要求读到最底部)
agreementRead.value = agreed.value
showAgreement.value = true
// 弹窗有约 300ms 进场动画,等渲染完再量内容高度
setTimeout(measureAgreement, 350)
}
/** 滑到底部(`scroll-view` 的 scrolltolower)→ 视为已读完 */
const onAgreementLower = () => {
agreementRead.value = true
}
/**
* 量一下内容高度:不足一屏时直接算已读
*
* 否则短文案永远触发不了 `scrolltolower`,用户会被卡在「点不动同意」上。
*/
const measureAgreement = () => {
uni
.createSelectorQuery()
.in(instance?.proxy as never)
.select('.agreement__body')
.boundingClientRect()
.select('.agreement__inner')
.boundingClientRect()
.exec((res) => {
const body = res?.[0] as { height?: number } | null
const inner = res?.[1] as { height?: number } | null
if (!body?.height || !inner?.height) return
if (inner.height <= body.height + 2) agreementRead.value = true
})
}
/** 弹窗里点「我已知晓并同意」→ 勾上并关闭(没滑到底则只提示,不置勾) */
const onAgreeConfirm = () => {
if (!agreementRead.value) {
uni.$u.toast('请滑动阅读至底部后再同意')
return
}
agreed.value = true
showAgreement.value = false
}
/** 未同意协议时的统一拦截(微信登录 / 账号登录 / 注册都走这里) */
const ensureAgreed = (): boolean => {
if (agreed.value) return true
uni.$u.toast('请先阅读并同意《用户须知》')
return false
}
// ────────────────────────── 账号密码登录 ──────────────────────────
const loginForm = reactive({ const loginForm = reactive({
username: '', username: '',
@ -246,7 +426,62 @@ const loginRules = {
password: [{ required: true, message: '请输入密码', trigger: ['blur', 'change'] }] password: [{ required: true, message: '请输入密码', trigger: ['blur', 'change'] }]
} }
// ──────────────────────── 注册表单 ──────────────────────── const handleLogin = () => {
if (loading.value) return
if (!ensureAgreed()) return
loginFormRef.value
?.validate()
.then(async () => {
loading.value = true
try {
await userStore.login({
username: loginForm.username,
password: loginForm.password
})
emit('success')
} catch {
// 失败提示已由 request 层统一 toast
} finally {
loading.value = false
}
})
.catch(() => {
// 表单校验失败:错误文案已展示在对应表单项上
})
}
// ────────────────────────── 微信一键登录 ──────────────────────────
/**
* 微信一键登录
*
* - 已绑定微信 → 抛 success,由使用方决定后续(关抽屉 / 跳页)
* - 未绑定 → token 已落地(有效免登录态),切到绑定步骤让用户选择
*
* 同样要求先勾选《用户须知》。
*/
const handleWechatLogin = async () => {
if (wxLoading.value) return
if (!ensureAgreed()) return
wxLoading.value = true
try {
const { bound } = await userStore.wechatLogin()
if (bound) {
emit('success')
return
}
wxBinding.value = true
} catch (err) {
const message = err instanceof Error ? err.message : ''
if (message) uni.$u.toast(message)
} finally {
wxLoading.value = false
}
}
// ────────────────────────── 注册 ──────────────────────────
const registerForm = reactive({ const registerForm = reactive({
username: '', username: '',
@ -256,7 +491,7 @@ const registerForm = reactive({
confirmPassword: '' confirmPassword: ''
}) })
/** 二次密码一致性校验(async-validator 标准签名,与 new3 的 el-form 写法一致) */ /** 二次密码一致性校验(async-validator 标准签名) */
const validateConfirmPassword = ( const validateConfirmPassword = (
_rule: unknown, _rule: unknown,
value: string, value: string,
@ -282,42 +517,14 @@ const registerRules = {
email: [{ type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change'] }] email: [{ type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change'] }]
} }
// ──────────────────────── 交互 ──────────────────────── /**
* 注册:勾选协议 → 校验 → `user.register` → 回账号登录并回填账号
/** 登录 / 注册模式切换 */ * (与 Web 端一致:注册成功**不自动登录**,需用户手动登录)
const switchMode = (register: boolean) => { */
if (isRegister.value === register) return
isRegister.value = register
emit('change', register ? 'register' : 'login')
}
/** 登录:校验通过 → store.login → 通知使用方跳转 */
const handleLogin = () => {
if (loading.value) return
loginFormRef.value
?.validate()
.then(async () => {
loading.value = true
try {
await userStore.login({
username: loginForm.username,
password: loginForm.password
})
emit('success')
} catch {
// 失败提示已由 request 层统一 toast
} finally {
loading.value = false
}
})
.catch(() => {
// 表单校验失败:错误文案已展示在对应表单项上
})
}
/** 注册:校验通过 → store.register → 回到登录页并回填账号(与 new3 一致,不自动登录) */
const handleRegister = () => { const handleRegister = () => {
if (loading.value) return if (loading.value) return
if (!ensureAgreed()) return
registerFormRef.value registerFormRef.value
?.validate() ?.validate()
.then(async () => { .then(async () => {
@ -331,7 +538,7 @@ const handleRegister = () => {
}) })
uni.$u.toast('注册成功,请登录') uni.$u.toast('注册成功,请登录')
loginForm.username = registerForm.username.trim() loginForm.username = registerForm.username.trim()
switchMode(false) view.value = 'account'
} catch { } catch {
// 失败提示已由 request 层统一 toast // 失败提示已由 request 层统一 toast
} finally { } finally {
@ -346,112 +553,130 @@ const handleRegister = () => {
<style lang="scss" scoped> <style lang="scss" scoped>
.login-panel { .login-panel {
padding: 0 48rpx; padding: 0 40rpx 32rpx;
/*
* 注册视图有 5 个输入框,小屏(iPhone SE 等)下整块会接近甚至超过一屏。
* 超过 82vh 时面板内部滚动,保证「注册」按钮和协议勾选始终可达。
*/
max-height: 82vh;
overflow-y: auto;
box-sizing: border-box;
/* 兜底:显式锁定浅色主题色板 /* 兜底:显式锁定浅色主题色板(uview-plus 暗色主题下变量会变成近白色) */
uview-plus 在 @media (prefers-color-scheme: dark) 下会把 --up-main-color 改为 #f5f5f5,
白底卡片上文字会变得几乎看不见。
注意:`up-input` 的文字色是 JS 读主题变量后写成**内联样式**,CSS 盖不住,
故输入框另用 :color 属性显式指定(见 script 顶部 INPUT_COLOR);
这里的变量覆盖是为了让卡片内其它 uview-plus 组件也保持足够对比度。 */
--up-main-color: #303133; --up-main-color: #303133;
--up-content-color: #303133; --up-content-color: #303133;
--up-tips-color: #909399; --up-tips-color: #909399;
--up-border-color: #dadbde; --up-border-color: #dadbde;
&__brand { /* ── 头部一行:tab 靠左 + 关闭靠右 ── */
display: flex; &__bar {
flex-direction: column;
align-items: center;
padding: 72rpx 0 48rpx;
}
&__logo {
width: 140rpx;
height: 140rpx;
border-radius: 32rpx;
background-color: rgba(255, 255, 255, 0.18);
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: space-between;
overflow: hidden; height: 100rpx;
} }
&__logo-img { &__tabs {
width: 140rpx; display: flex;
height: 140rpx; align-items: center;
} }
&__brand-title { &__tab {
margin-top: 24rpx; position: relative;
font-size: 44rpx; height: 100rpx;
line-height: 100rpx;
margin-right: 48rpx;
font-size: 30rpx;
color: #909399;
&--active {
color: #303133;
font-weight: 600; font-weight: 600;
color: #ffffff;
letter-spacing: 2rpx; /* 选中下划线(靠左对齐,不再居中) */
&::after {
content: '';
position: absolute;
left: 0;
bottom: 14rpx;
width: 44rpx;
height: 6rpx;
border-radius: 6rpx;
background-color: #2979ff;
}
}
} }
&__brand-desc { &__bar-title {
margin-top: 12rpx; font-size: 32rpx;
font-size: 26rpx;
color: rgba(255, 255, 255, 0.75);
}
&__card {
background-color: #ffffff;
border-radius: 24rpx;
padding: 40rpx 32rpx 32rpx;
box-shadow: 0 12rpx 40rpx rgba(0, 0, 0, 0.08);
}
&__head {
display: flex;
flex-direction: column;
align-items: center;
margin-bottom: 24rpx;
}
&__head-title {
font-size: 36rpx;
font-weight: 600; font-weight: 600;
color: #303133; color: #303133;
} }
&__head-sub { &__close {
margin-top: 10rpx; /* 左侧留出热区,视觉上仍贴着右边 */
font-size: 24rpx; padding: 20rpx 0 20rpx 24rpx;
color: #909399;
}
&__submit {
margin-top: 48rpx;
}
&__foot {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center;
margin-top: 28rpx;
} }
&__foot-text { /* ── 微信登录区 ── */
&__body {
width: 100%;
/* 与「账号登录」两个输入框的高度对齐,切换 tab 时面板高度不跳动 */
min-height: 370rpx;
display: flex;
flex-direction: column;
justify-content: center;
}
&__desc {
margin-bottom: 28rpx;
font-size: 26rpx; font-size: 26rpx;
color: #909399; color: #909399;
} }
&__cancel { /* ── 提交按钮 ── */
&__submit {
margin-top: 32rpx;
}
/* ── 协议勾选 ── */
&__agree {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
margin-top: 36rpx; flex-wrap: wrap;
padding-top: 24rpx; margin-top: 32rpx;
/* 极细分隔线,避免与底部「立即注册」文字链混作一堆 */
border-top: 1rpx solid #f0f0f0;
} }
&__cancel-text { &__checkbox {
/* 撑开点击热区,视觉上仍是轻量文字 */ /* 扩大点击热区,视觉上仍是小图标 */
padding: 10rpx 40rpx; padding: 8rpx 8rpx 8rpx 0;
font-size: 28rpx; display: flex;
align-items: center;
}
&__agree-text {
font-size: 24rpx;
color: #909399;
}
&__agree-link {
font-size: 24rpx;
color: #2979ff;
}
/* ── 底部链接 ── */
&__foot {
display: flex;
align-items: center;
justify-content: center;
margin-top: 24rpx;
}
&__foot-text {
font-size: 26rpx;
color: #909399; color: #909399;
} }
@ -461,4 +686,54 @@ const handleRegister = () => {
color: #2979ff; color: #2979ff;
} }
} }
/* ── 用户须知弹窗 ── */
.agreement {
width: 620rpx;
padding: 40rpx 36rpx 32rpx;
box-sizing: border-box;
&__title {
font-size: 34rpx;
font-weight: 600;
color: #303133;
text-align: center;
}
&__body {
/* 固定高度 + 内部滚动:长文本不会把弹窗撑出屏幕,同时强迫滑到底才能同意 */
height: 460rpx;
margin-top: 24rpx;
padding: 24rpx;
box-sizing: border-box;
border-radius: 12rpx;
background-color: #f7fafd;
}
&__text {
font-size: 26rpx;
line-height: 44rpx;
color: #5d6f82;
/* 保留换行(文案里的 \n) */
white-space: pre-wrap;
}
&__tip {
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 16rpx;
font-size: 24rpx;
color: #f0a020;
}
&__action {
margin-top: 32rpx;
/* 未滑到底:按钮灰态。仍可点,点了会提示原因 —— 比 disabled 更好定位 */
.is-disabled {
opacity: 0.5;
}
}
}
</style> </style>

View File

@ -0,0 +1,152 @@
<template>
<up-form ref="formRef" :model="form" :rules="rules" labelPosition="top">
<up-form-item label="账号" prop="username" required>
<up-input
v-model="form.username"
:color="INPUT_COLOR"
:placeholder-style="PLACEHOLDER_STYLE"
placeholder="请输入 WMS 账号"
prefixIcon="account"
clearable
maxlength="30"
></up-input>
</up-form-item>
<up-form-item label="密码" prop="password" required>
<up-input
v-model="form.password"
type="password"
:color="INPUT_COLOR"
:placeholder-style="PLACEHOLDER_STYLE"
placeholder="请输入密码"
prefixIcon="lock"
clearable
maxlength="30"
@confirm="handleSubmit"
></up-input>
</up-form-item>
<view class="wechat-bind-form__submit">
<up-button
type="primary"
shape="circle"
:loading="loading"
:text="loading ? '绑定中...' : submitText"
@click="handleSubmit"
></up-button>
</view>
<view v-if="showSkip" class="wechat-bind-form__foot">
<text class="wechat-bind-form__foot-text">暂时不绑定?</text>
<text class="wechat-bind-form__link" @click="emit('skip')">跳过</text>
</view>
</up-form>
</template>
<script setup lang="ts">
/**
* 微信绑定 WMS 账号表单
*
* 抽成独立组件的原因:**两个地方都要用**
* 1. 登录页(`login-panel`):微信一键登录后尚未绑定 → 内联展示,可跳过
* 2. 「我的」页:未绑定用户的常驻绑定入口 → 放在弹窗里,不提供跳过(是用户主动点的)
*
* 后端 `wechat.bindUser` 凭**请求头里的微信 token** 取 `oauth_id` 定位记录,
* 校验账号密码后签发正式 token。token 在微信登录时已落地存储,故由 `request` 自动带上。
*
* 风格约定:输入文字 / 占位符颜色必须显式指定(uview-plus 暗色主题下
* `--up-main-color` 是近白色,白底卡片上会看不清,且它是内联样式,CSS 盖不住)。
*/
import { reactive, ref } from 'vue'
import { useUserStore } from '@/store/modules/user'
/** u-form 实例上本项目实际用到的方法 */
interface FormInstance {
validate: () => Promise<unknown>
clearValidate: (props?: string | string[]) => void
}
const props = withDefaults(
defineProps<{
/** 提交按钮文案 */
submitText?: string
/** 是否显示「跳过」(登录页给,绑定入口页不给) */
showSkip?: boolean
}>(),
{
submitText: '绑定并登录',
showSkip: false
}
)
const emit = defineEmits<{
(e: 'success'): void
(e: 'skip'): void
}>()
const userStore = useUserStore()
const formRef = ref<FormInstance | null>(null)
const loading = ref(false)
const form = reactive({
username: '',
password: ''
})
const rules = {
username: [{ required: true, message: '请输入账号', trigger: ['blur', 'change'] }],
password: [{ required: true, message: '请输入密码', trigger: ['blur', 'change'] }]
}
const INPUT_COLOR = '#303133'
const PLACEHOLDER_STYLE = 'color: #c0c4cc'
/** 提交绑定:成功抛 success;失败提示(账号密码错误等)由 request 层统一处理 */
const handleSubmit = () => {
if (loading.value) return
formRef.value
?.validate()
.then(async () => {
loading.value = true
try {
await userStore.wechatBind({
username: form.username,
password: form.password
})
emit('success')
} catch {
// 失败提示已由 request 层统一 toast
} finally {
loading.value = false
}
})
.catch(() => {
// 表单校验失败:错误文案已展示在对应表单项上
})
}
</script>
<style lang="scss" scoped>
.wechat-bind-form__submit {
margin-top: 48rpx;
}
.wechat-bind-form__foot {
display: flex;
align-items: center;
justify-content: center;
margin-top: 28rpx;
}
.wechat-bind-form__foot-text {
font-size: 26rpx;
color: #909399;
}
.wechat-bind-form__link {
margin-left: 8rpx;
font-size: 26rpx;
color: #2979ff;
}
</style>

View File

@ -0,0 +1,31 @@
/**
* 页面级「入口场景」消费
*
* 为什么需要:`App.onLaunch` / `onShow` 触发时页面栈可能还没就绪,
* 那时 `navigateTo` 会失败。所以 `App.vue` 只负责**捕获**入口参数并存起来,
* 由真正就绪的页面来**消费**(见 `App.vue` 的 captureEntry)。
*
* 用法:在页面 `<script setup>` 顶层调用一次,该页面每次显示时都会检查
* 有没有待处理的扫码 / 链接入口,有就执行(同一入口只消费一次)。
*
* 目前挂在首页 —— 扫码进入的落地页通常就是首页。
* 若某些页面也需要响应(例如热启动时用户正停在那页扫码进来),
* 在那个页面里同样调用一次即可,无需额外配置。
*/
import { onShow } from '@dcloudio/uni-app'
import { takePendingEntry } from '@/utils/entry'
import { handleEntryScene } from '@/router/scenes'
export function useEntryScene(): void {
onShow(() => {
const entry = takePendingEntry()
if (!entry) return
console.log('[entry] 消费待处理入口', entry)
handleEntryScene(entry).catch((err) => {
// 入口处理失败不能影响页面正常渲染
console.warn('[entry] 入口场景处理失败', err)
})
})
}

View File

@ -20,7 +20,7 @@ import type { ComputedRef } from 'vue'
import { useUserStore } from '@/store/modules/user' import { useUserStore } from '@/store/modules/user'
import { getPageByPath } from '@/router/pages' import { getPageByPath } from '@/router/pages'
import type { AuthMode } from '@/router/pages' import type { AuthMode } from '@/router/pages'
import { LOGIN_PAGE, getCurrentRoute } from '@/utils/auth-guard' import { getCurrentRoute } from '@/utils/auth-guard'
export interface UsePageAuthReturn { export interface UsePageAuthReturn {
/** 解析后的登录策略 */ /** 解析后的登录策略 */
@ -61,15 +61,17 @@ export function usePageAuth(auth?: AuthMode): UsePageAuthReturn {
const needLogin = computed<boolean>(() => mode.value === 'required' && !isLogin.value) const needLogin = computed<boolean>(() => mode.value === 'required' && !isLogin.value)
const canRender = computed<boolean>(() => !needLogin.value) const canRender = computed<boolean>(() => !needLogin.value)
/** 跳登录页,带 `redirect` 回本页(复用 `LOGIN_PAGE`,不新造路径) */ /**
* 唤起登录(**半屏抽屉**,不跳页)
*
* 为什么不跳登录页:登录完用户就留在当前页面,页面数据(权限 / 菜单 / 身份)
* 在 store 里是响应式的会自动刷新,不用带 `redirect` 来回跳。
*/
const goLogin = (): void => { const goLogin = (): void => {
const current = getCurrentRoute() userStore.showAuthModal()
const query =
current && current !== LOGIN_PAGE ? `?redirect=${encodeURIComponent(current)}` : ''
uni.navigateTo({ url: `${LOGIN_PAGE}${query}` })
} }
/** 未登录时弹确认框引导登录(用户确认后才跳,不自动跳转) */ /** 未登录时弹确认框引导登录(确认后弹出抽屉,仍是用户主动触发) */
const requireLogin = (tips = '该功能需要登录后使用'): void => { const requireLogin = (tips = '该功能需要登录后使用'): void => {
if (isLogin.value) return if (isLogin.value) return
uni.showModal({ uni.showModal({

View File

@ -50,8 +50,13 @@
"quickapp" : {}, "quickapp" : {},
/* 小程序特有相关 */ /* 小程序特有相关 */
"mp-weixin" : { "mp-weixin" : {
/* 微信小程序 AppID(公众平台 → 开发管理 → 开发设置) */ /* 微信小程序 AppID(公众平台 → 开发管理 → 开发设置)
"appid" : "wx31f8d1ee127bc64b", ⚠️ 这里填的是**开发调试用**的小程序:wx528af80241d633e1
原因:微信登录(wechat.loginByCode)取的是**运行时真实 AppID**
(wx.getAccountInfoSync),且要求该 AppID 在 wms_wechat_app 里
有启用中的授权记录 —— 授权是按小程序维度的,必须用已授权的那一个。
上传模板代码 / 作为开放平台模板发布时,记得切回模板小程序 AppID。 */
"appid" : "wx528af80241d633e1",
"projectname" : "wms_mp_weixin", "projectname" : "wms_mp_weixin",
/* 微信开发者工具项目设置 */ /* 微信开发者工具项目设置 */
"setting" : { "setting" : {

View File

@ -25,6 +25,12 @@
"style": { "style": {
"navigationBarTitleText": "登录" "navigationBarTitleText": "登录"
} }
},
{
"path": "pages/login/confirm-login",
"style": {
"navigationBarTitleText": "确认登录"
}
} }
], ],
"subPackages": [ "subPackages": [

View File

@ -34,7 +34,8 @@
</view> </view>
<!-- 无内容 / 接口失败:统一空态文案,不白屏(§3.5.1) --> <!-- 无内容 / 接口失败:统一空态文案,不白屏(§3.5.1) -->
<empty-state v-else @retry="loadEntries(true)"> <empty-state v-else v-bind="emptyStateProps" @retry="loadEntries(true)">
<!-- 未登录 → 去登录 -->
<template v-if="!isLogin" #action> <template v-if="!isLogin" #action>
<up-button <up-button
type="primary" type="primary"
@ -44,6 +45,16 @@
@click="goLogin" @click="goLogin"
></up-button> ></up-button>
</template> </template>
<!-- 微信已登录但未绑定账号 → 引导去「我的」页绑定(绑定表单不放首页) -->
<template v-else-if="userStore.isWechatUnbound" #action>
<up-button
type="primary"
shape="circle"
size="small"
text="去绑定账号"
@click="goBind"
></up-button>
</template>
</empty-state> </empty-state>
</view> </view>
@ -55,6 +66,9 @@
<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 预判) -->
<auth-modal></auth-modal>
</view> </view>
</template> </template>
@ -64,6 +78,8 @@ 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 { usePermissionStore } from '@/store/modules/permission'
import { usePageAuth } from '@/composables/usePageAuth' import { usePageAuth } from '@/composables/usePageAuth'
import { useEntryScene } from '@/composables/useEntryScene'
import AuthModal from '@/components/auth-modal/auth-modal.vue'
import { LOCAL_PUBLIC_ENTRIES, toSections } from '@/router/entries' import { LOCAL_PUBLIC_ENTRIES, toSections } from '@/router/entries'
import type { EntryLeaf } from '@/router/entries' import type { EntryLeaf } from '@/router/entries'
import { navigateToPath } from '@/utils/navigate' import { navigateToPath } from '@/utils/navigate'
@ -89,6 +105,8 @@ const sections = computed(() =>
const heroDesc = computed(() => { const heroDesc = computed(() => {
if (!isLogin.value) return 'WMS 仓储管理 · 微信小程序端' if (!isLogin.value) return 'WMS 仓储管理 · 微信小程序端'
// 微信已登录但未绑定:别显示“已登录”这么含糊的文案
if (userStore.isWechatUnbound) return '微信已登录 · 待绑定 WMS 账号'
const parts = [ const parts = [
userStore.userName, userStore.userName,
userStore.roleTypeLabel, userStore.roleTypeLabel,
@ -97,17 +115,37 @@ const heroDesc = computed(() => {
return parts.length ? parts.join(' · ') : 'WMS 仓储管理 · 微信小程序端' return parts.length ? parts.join(' · ') : 'WMS 仓储管理 · 微信小程序端'
}) })
/**
* 空态文案 / 图标:未绑定与接口失败必须区分
*
* 返回空对象时不覆盖 `empty-state` 的默认值(默认是「服务器出差了,请稍后再试」),
* 否则未绑定用户会误以为是网络故障。
*/
const emptyStateProps = computed(() =>
userStore.isWechatUnbound
? { text: '微信已登录,绑定 WMS 账号后即可使用各功能', icon: 'account' }
: {}
)
/** 引导去「我的」页绑定(那里是常驻的绑定入口;登录页因已有 token 会直接放行) */
const goBind = () => {
uni.switchTab({ url: '/pages/mine/mine' })
}
/** /**
* 拉取用户信息(= 菜单 + 权限点,失败提示由 request 层统一 toast) * 拉取用户信息(= 菜单 + 权限点,失败提示由 request 层统一 toast)
* @param force 是否强制刷新(“重试”按钮用;onShow 不传,避免切 Tab 就重拉) * @param force 是否强制刷新(“重试”按钮用;onShow 不传,避免切 Tab 就重拉)
*/ */
const loadEntries = async (force = false) => { const loadEntries = async (force = false) => {
if (!userStore.isLogin) return if (!userStore.isLogin) return
if (permissionStore.loaded && !force) return // `user.info` 已由 App 启动统一拉取并存在 store;这里只在没有数据时补拉或显式重试
if (userStore.hasUserInfo && !force) return
// 未绑定的微信登录态没有菜单可拉(绑定后 user.info 会重新灌菜单)
if (userStore.isWechatUnbound && !force) return
loading.value = true loading.value = true
try { try {
await userStore.getInfo() await userStore.getInfo(force)
} catch { } catch {
// 失败 → sections 为空 → 走空态文案 + 「重试」 // 失败 → sections 为空 → 走空态文案 + 「重试」
} finally { } finally {
@ -129,6 +167,9 @@ const onEntry = (item: EntryLeaf) => {
onShow(() => { onShow(() => {
loadEntries() loadEntries()
}) })
// 消费扫码 / 链接入口(spm → 扫码登录 / 扫码绑定 / 打开指定页)
useEntryScene()
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>

View File

@ -0,0 +1,359 @@
<template>
<view class="confirm">
<view class="confirm__card">
<!-- 图标:正常 / 已授权 / 失败三态 -->
<view
class="confirm__icon"
:class="{ 'confirm__icon--fail': failed, 'confirm__icon--done': done }"
>
<up-icon :name="headIcon" :color="headIconColor" size="40"></up-icon>
</view>
<view class="confirm__title">{{ headTitle }}</view>
<view class="confirm__desc">{{ headDesc }}</view>
<!-- 待授权信息:已登录且已绑定时展示,让用户确认「授权的是哪个账号」 -->
<view v-if="canConfirm" class="confirm__info">
<view class="confirm__row">
<text class="confirm__label">授权账号</text>
<text class="confirm__value">{{ accountText }}</text>
</view>
<view class="confirm__row">
<text class="confirm__label">登录码</text>
<text class="confirm__value">{{ code }}</text>
</view>
</view>
<view class="confirm__actions">
<!-- 条件具备:显式授权(防误扫的核心 —— 不点就不推) -->
<up-button
v-if="canConfirm"
type="primary"
shape="circle"
:loading="loading"
:text="loading ? '授权中...' : '确认授权登录'"
@click="onConfirm"
></up-button>
<!-- 未登录 / 未绑定:先引导登录,登录成功后自动补推送 -->
<up-button
v-else-if="needLogin"
type="primary"
shape="circle"
text="去登录"
@click="onGoLogin"
></up-button>
<!-- 已授权(用户点了确认,或登录成功后自动补推送)→ 给一个明确的「完成」出口 -->
<template v-if="done">
<up-button type="primary" shape="circle" text="返回首页" @click="backHome"></up-button>
<!-- #ifdef MP-WEIXIN -->
<up-button
type="info"
:plain="true"
shape="circle"
text="退回微信"
@click="onExit"
></up-button>
<!-- #endif -->
</template>
<!-- 失败态(登录码无效 / 已过期):退回微信重扫,或回首页 -->
<template v-else-if="failed">
<up-button type="primary" shape="circle" text="返回首页" @click="backHome"></up-button>
<!-- #ifdef MP-WEIXIN -->
<up-button
type="info"
:plain="true"
shape="circle"
text="退回微信"
@click="onExit"
></up-button>
<!-- #endif -->
</template>
<!-- 正常态:始终可取消(不授权 → 不会推送任何东西) -->
<up-button
v-else
type="info"
:plain="true"
shape="circle"
text="取消"
@click="backHome"
></up-button>
</view>
</view>
<!--
登录抽屉:点「去登录」就地弹出,而不是跳登录页
(跳走之后要一路返回才能回到本页;抽屉关掉仍停在本页,`canConfirm` 会自动变成 true)
-->
<auth-modal></auth-modal>
</view>
</template>
<script setup lang="ts">
/**
* 扫码确认登录页(spm 场景 4 的落地页)
*
* 为什么要有这一页(而不是扫码后直接推送):
* 扫码是**误触高发**动作(用户可能只是随手扫了一下),
* 直接把当前账号授权出去风险太大。所以扫码只负责**跳到这里**,
* 由用户在页面上看清楚「授权的是哪个账号」并显式点击确认。
* 与 `G:\uni\数据`(shopro)的做法一致:spm 只解析 + 跳页,业务动作由页面里的用户操作触发。
*
* 接口只用已调通的那两个:
* - `wechat.pushLoginCode`:确认授权(需登录且已绑定,后端取当前鉴权用户)
* - 登录 / 绑定成功后由 store 的 `flushPendingLoginCode()` 自动补推送
*
* ⚠️ 登录码 TTL:生成 300s、确认后待领取 120s → 过期会提示「登录码不存在或已过期」。
*/
import { computed, ref, watch } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useUserStore } from '@/store/modules/user'
import AuthModal from '@/components/auth-modal/auth-modal.vue'
import { savePendingLoginCode } from '@/utils/entry'
/** 首页(tabBar 页,返回时用 switchTab) */
const HOME_PAGE = '/pages/index/index'
const userStore = useUserStore()
/** 二维码里带过来的登录码(spm 第 3 段) */
const code = ref('')
/** 参数缺失 / 登录码过期导致无法授权 */
const failed = ref(false)
/** 授权请求中 */
const loading = ref(false)
/**
* 已成功授权
*
* 两条路径都会走到这里:
* 1. 用户在本页点了「确认授权登录」
* 2. 未登录时点了「去登录」→ 抽屉里登录 / 绑定成功 → store 的 `flushPendingLoginCode()` 自动补推送
*
* 第 2 种情况下 `isLogin` 也会变 true,若不识别就会重新渲染出「确认授权登录」按钮,
* 让用户对**同一个码**再点一次(而那时码已被消费,必然报「不存在或已过期」)。
* 所以以 store 里记的「已推送的码」为准。
*/
const done = computed(() => !!code.value && userStore.pushedLoginCode === code.value)
/** 条件具备:有登录码 + 未失效 + 未推过 + 已登录 + 已绑定 → 可授权 */
const canConfirm = computed(
() =>
!!code.value &&
!failed.value &&
!done.value &&
userStore.isLogin &&
!userStore.isWechatUnbound
)
/** 需要先登录 / 绑定 */
const needLogin = computed(
() => !!code.value && !failed.value && !done.value && !canConfirm.value
)
const headTitle = computed(() => {
if (failed.value) return '登录码已失效'
if (done.value) return '已授权登录'
return '确认登录'
})
const headDesc = computed(() => {
if (failed.value) return '登录码无效或已过期,请退回微信重新扫码'
if (done.value) return '已为电脑端确认登录,可回到电脑端继续操作'
if (canConfirm.value) return '是否授权当前设备使用该账号登录 WMS?'
if (userStore.isLogin) return '请先绑定 WMS 账号,绑定后将自动为电脑端确认登录'
return '请先登录 WMS 账号,登录后将自动为电脑端确认登录'
})
/** 图标:已授权用勾(绿),失败用叉(红),其余用用户图标(蓝) */
const headIcon = computed(() => {
if (failed.value) return 'close-circle'
if (done.value) return 'checkmark-circle'
return 'account'
})
const headIconColor = computed(() => {
if (failed.value) return '#f56c6c'
if (done.value) return '#07c160'
return '#2979ff'
})
/** 授权账号展示:优先姓名,其次账号名 */
const accountText = computed(() => userStore.userName || userStore.user?.username || '当前账号')
onLoad((options) => {
const raw = String(options?.code ?? '')
try {
code.value = decodeURIComponent(raw)
} catch {
code.value = raw
}
console.log('[confirm-login] 登录码 =', code.value)
if (!code.value) failed.value = true
})
/** 确认授权:唯一的推送入口(用户显式点击才会触发) */
const onConfirm = async () => {
if (loading.value || !canConfirm.value) return
loading.value = true
try {
await userStore.pushLoginCode(code.value)
// 成功后的 toast 与返回首页统一交给 `done` 的 watch(避免两处 toast 打架)
} catch (err) {
// 失败原因由 request 层已 toast;这里额外识别「登录码失效」→ 切失败态,
// 避免用户对着一个已经无效的码反复点确认(页面会变成「返回首页 / 退出小程序」)
//
// 必须同时带「登录码」三个字:否则未绑定时后端返回的「用户不存在或已被删除」
// 会命中「不存在」,把页面误判成登录码失效
const message = err instanceof Error ? err.message : ''
if (/登录码/.test(message) && /过期|不存在|无效|失效|使用/.test(message)) {
failed.value = true
}
} finally {
loading.value = false
}
}
/**
* 去登录:**弹抽屉**,不跳登录页
*
* 为什么不跳页:本页本身就是被扫码「带进来」的,跳走之后用户要一路返回才能回到这里;
* 抽屉就地弹、就地关,登录完仍停在本页,`canConfirm` 会自动变成 true。
*
* 先把登录码暂存:登录 / 绑定成功后 store 的 `flushPendingLoginCode()` 会自动补推送,
* 用户不用再回到电脑端重扫一次。
*/
const onGoLogin = () => {
savePendingLoginCode(code.value)
userStore.showAuthModal('wechat')
}
/**
* 授权成功:提示 + 稍后回首页
*
* `onConfirm`(本页显式确认)与自动补推送(抽屉里登录成功)两条路径共用,
* 所以放在 watch 里而不是各自的回调里。
*/
watch(done, (value) => {
if (!value) return
uni.showToast({ title: '已为电脑端确认登录', icon: 'none' })
setTimeout(backHome, 900)
})
/**
* 退回微信(失败态的出口之一)
*
* 登录码已失效,而用户是被扫码「带进来」的 —— 正确做法是退出小程序回到微信里重新扫。
* `wx.exitMiniProgram` 必须由用户点击触发;失败时兜底回首页。
*/
const onExit = () => {
// #ifdef MP-WEIXIN
wx.exitMiniProgram({ fail: () => backHome() })
// #endif
// #ifndef MP-WEIXIN
backHome()
// #endif
}
/** 回首页(首页是 tabBar 页,必须用 switchTab) */
function backHome() {
uni.switchTab({ url: HOME_PAGE })
}
</script>
<style lang="scss" scoped>
.confirm {
min-height: 100vh;
padding: 64rpx 36rpx;
box-sizing: border-box;
background: linear-gradient(165deg, #eef5ff 0%, #edf4f8 52%, #e9f0f5 100%);
&__card {
background-color: #ffffff;
border-radius: 24rpx;
padding: 48rpx 36rpx;
border: 2rpx solid #e7edf4;
box-shadow: 0 14rpx 36rpx rgba(12, 36, 62, 0.08);
}
&__icon {
width: 120rpx;
height: 120rpx;
margin: 0 auto 24rpx;
border-radius: 50%;
background-color: rgba(41, 121, 255, 0.1);
display: flex;
align-items: center;
justify-content: center;
&--fail {
background-color: rgba(245, 108, 108, 0.1);
}
&--done {
background-color: rgba(7, 193, 96, 0.1);
}
}
&__title {
font-size: 40rpx;
font-weight: 700;
color: #1f2d3d;
text-align: center;
}
&__desc {
margin-top: 18rpx;
font-size: 28rpx;
line-height: 40rpx;
color: #5d6f82;
text-align: center;
}
&__info {
margin-top: 32rpx;
padding: 24rpx;
border-radius: 16rpx;
background-color: #f7fafd;
border: 2rpx dashed #c5d3e2;
}
&__row {
display: flex;
align-items: center;
justify-content: space-between;
& + & {
margin-top: 16rpx;
}
}
&__label {
font-size: 26rpx;
color: #909399;
}
&__value {
font-size: 28rpx;
font-weight: 600;
color: #17314b;
/* 登录码可能较长,避免撑破卡片 */
max-width: 60%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
&__actions {
margin-top: 44rpx;
display: flex;
flex-direction: column;
gap: 20rpx;
}
}
</style>

View File

@ -1,16 +1,7 @@
<template> <template>
<view class="login-page"> <view class="login-page">
<scroll-view class="login-page__scroll" scroll-y> <scroll-view class="login-page__scroll" scroll-y>
<login-panel <login-panel show-cancel @success="onLoginSuccess" @cancel="onCancel"></login-panel>
:logo="logo"
title="WMS 小程序"
desc="仓储管理系统 · 微信小程序端"
show-cancel
@success="onLoginSuccess"
@cancel="onCancel"
></login-panel>
<view class="login-page__tip">登录后可使用入库、出库、盘点等全部功能</view>
</scroll-view> </scroll-view>
</view> </view>
</template> </template>
@ -27,6 +18,17 @@
* - 取消 → 有来源页则返回上一页;无来源页则退回 redirect 指定页 / 首页 * - 取消 → 有来源页则返回上一页;无来源页则退回 redirect 指定页 / 首页
* - 登录成功 → 回跳 redirect 指定的来源页,缺省进首页 * - 登录成功 → 回跳 redirect 指定的来源页,缺省进首页
* - 已登录进入本页 → 直接放行,不停留在登录表单 * - 已登录进入本页 → 直接放行,不停留在登录表单
*
* 登录方式(两种,均由 `login-panel` 内部完成):
* 1. 账号密码 / 注册
* 2. 微信一键登录(仅微信小程序端):已绑微信直接登录;未绑定则页内引导绑定 WMS 账号,
* **可跳过**。token 一律落地存储(未绑定也是有效的免登录凭证),下次打开小程序
* 直接进首页、不再提示登录;绑定入口常驻「我的」页。
* 因此本页 `onShow` 的 `getToken()` 判定对未绑定用户同样放行 —— 这是预期行为。
*
* ⚠️ 本页**不是启动页**,也不会在打开小程序时被自动跳转
* (微信审核要求:登录必须由用户主动触发)。
* 当前入口:`pages/mine/mine` 的「登录 / 注册」按钮(或点击头像区)。
*/ */
import { ref } from 'vue' import { ref } from 'vue'
@ -41,8 +43,6 @@ const HOME_PAGE = '/pages/index/index'
/** tabBar 页面清单:这些页面只能用 switchTab 进入 */ /** tabBar 页面清单:这些页面只能用 switchTab 进入 */
const TAB_PAGES = [HOME_PAGE, '/pages/mine/mine'] const TAB_PAGES = [HOME_PAGE, '/pages/mine/mine']
const logo = ref('/static/logo.png')
/** 登录成功后要回跳的目标页,由 auth-guard 通过 redirect 参数带入 */ /** 登录成功后要回跳的目标页,由 auth-guard 通过 redirect 参数带入 */
const redirect = ref('') const redirect = ref('')
@ -94,18 +94,14 @@ onShow(() => {
<style lang="scss" scoped> <style lang="scss" scoped>
.login-page { .login-page {
min-height: 100vh; min-height: 100vh;
/* 上半屏品牌蓝,下半屏浅灰,与白卡片形成层次 */ /*
background: linear-gradient(180deg, #2979ff 0%, #1a5fd0 40%, #f5f6fa 40%, #f5f6fa 100%); * 纯白底:本页已精简为「全屏登录面板」(方案与半屏抽屉一致,只是容器不同)。
* 去掉了品牌蓝底 / logo / 底部功能说明 —— 那些信息对登录本身没有帮助。
*/
background-color: #ffffff;
} }
.login-page__scroll { .login-page__scroll {
height: 100vh; height: 100vh;
} }
.login-page__tip {
padding: 40rpx 48rpx 60rpx;
text-align: center;
font-size: 24rpx;
color: #a8abb2;
}
</style> </style>

View File

@ -1,6 +1,6 @@
<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> <up-icon name="account" color="#ffffff" size="34"></up-icon>
@ -9,16 +9,33 @@
<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 v-if="!userStore.isLogin" 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.isLogin" class="entry"> <view v-if="userStore.isWechatUnbound" class="card">
<up-button type="primary" shape="circle" text="登录 / 注册" @click="onLogin"></up-button> <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> </view>
<!-- 身份信息:登录后显示,数据来自 user.info 的 employees[](不改数据库、无额外接口) --> <!-- 身份信息:绑定后显示,数据来自 user.info 的 employees[](不改数据库、无额外接口) -->
<view v-if="userStore.isLogin" class="card"> <view v-if="userStore.isLogin && !userStore.isWechatUnbound" class="card">
<view class="card__title">身份信息</view> <view class="card__title">身份信息</view>
<up-cell-group v-if="identity" :border="false"> <up-cell-group v-if="identity" :border="false">
@ -38,7 +55,7 @@
></up-cell> ></up-cell>
</up-cell-group> </up-cell-group>
<view v-else class="card__note" @click="loadIdentity">身份信息加载中…点此重试</view> <view v-else class="card__note" @click="onRetryInfo">未获取到身份信息,点此重试</view>
</view> </view>
<!-- 功能菜单:登录后由后端菜单驱动;无菜单时整卡不渲染,避免空卡片占位 --> <!-- 功能菜单:登录后由后端菜单驱动;无菜单时整卡不渲染,避免空卡片占位 -->
@ -72,6 +89,19 @@
<view v-if="userStore.isLogin" class="footer"> <view v-if="userStore.isLogin" class="footer">
<up-button type="info" :plain="true" text="退出登录" @click="onLogout"></up-button> <up-button type="info" :plain="true" text="退出登录" @click="onLogout"></up-button>
</view> </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>
</view> </view>
</template> </template>
@ -85,6 +115,8 @@ import { toSections } from '@/router/entries'
import type { EntryLeaf } 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 AuthModal from '@/components/auth-modal/auth-modal.vue'
const version = ref(uni.$u.config.v) const version = ref(uni.$u.config.v)
const platform = ref(uni.getSystemInfoSync().uniPlatform) const platform = ref(uni.getSystemInfoSync().uniPlatform)
@ -94,6 +126,8 @@ const permissionStore = usePermissionStore()
const userName = computed(() => { const userName = computed(() => {
if (!userStore.isLogin) return '未登录' if (!userStore.isLogin) return '未登录'
// 微信已登录但未绑定:没有业务姓名可展示,也不能说“已登录”(功能不完整)
if (userStore.isWechatUnbound) return '微信用户'
return userStore.userName || '已登录' return userStore.userName || '已登录'
}) })
@ -109,13 +143,19 @@ const authEndText = computed(() => {
const userDesc = computed(() => { const userDesc = computed(() => {
if (!userStore.isLogin) return '点击登录后使用完整功能' if (!userStore.isLogin) return '点击登录后使用完整功能'
if (userStore.isWechatUnbound) return '微信已登录 · 待绑定 WMS 账号'
const parts = [userStore.roleTypeLabel, identity.value?.store_name].filter(Boolean) const parts = [userStore.roleTypeLabel, identity.value?.store_name].filter(Boolean)
return parts.length ? parts.join(' · ') : '已登录' return parts.length ? parts.join(' · ') : '已登录'
}) })
/** 拉取 / 重试用户信息(身份信息来源于 user.info,无额外接口) */ /**
const loadIdentity = () => { * 手动重试:强制重拉 `user.info`
userStore.getInfo().catch(() => { *
* 正常路径下本页**不主动请求** —— 数据由 `App.vue` 启动时(或登录 / 绑定 / 切身份时)
* 统一拉好存在 store,本页只负责渲染。只有拉取失败时用户才会看到重试入口。
*/
const onRetryInfo = () => {
userStore.getInfo(true).catch(() => {
// 失败提示由 request 层统一 toast // 失败提示由 request 层统一 toast
}) })
} }
@ -168,11 +208,11 @@ const doChangeRole = async (roleId: number) => {
} }
} }
/** 本页是公共页面(auth: 'optional'),登录跳转统一走 usePageAuth: /** 本页是公共页面(auth: 'optional'),登录入口统一走 usePageAuth:
* 会自动带 redirect 回本页(同时作为「取消」与「登录成功」的回跳目标) */ * 登录**就地弹抽屉**,不跳页、不带 redirect(用户登录完仍留在本页) */
const { goLogin, requireLogin } = usePageAuth('optional') const { goLogin, requireLogin } = usePageAuth('optional')
/** 进入登录页 */ /** 弹登录抽屉(入口在头部用户信息区,本页不再放独立的登录按钮) */
const onLogin = () => goLogin() const onLogin = () => goLogin()
/** 功能菜单:与首页九宫格**同源**(都是 permissionStore.entries) */ /** 功能菜单:与首页九宫格**同源**(都是 permissionStore.entries) */
@ -187,10 +227,29 @@ const onMenuTap = (item: EntryLeaf) => {
navigateToPath(item.path, item.title) navigateToPath(item.path, item.title)
} }
/** 未登录时点击头部同样进登录页(已登录则不做任何事) */ /** 头部区点击:未登录去登录;微信已登录但未绑定则直接打开绑定入口 */
const onProfileTap = () => { const onProfileTap = () => {
if (userStore.isLogin) return if (!userStore.isLogin) {
onLogin() onLogin()
return
}
// 未绑定时各业务功能都不可用,这里是最需要操作的入口
if (userStore.isWechatUnbound) {
bindVisible.value = true
}
}
/** 绑定账号弹窗可见性(未绑定用户的常驻入口) */
const bindVisible = ref(false)
const onOpenBind = () => {
bindVisible.value = true
}
/** 绑定成功:`store.wechatBind` 内部已重拉 user.info,这里只需关弹窗并提示 */
const onBindSuccess = () => {
bindVisible.value = false
uni.$u.toast('绑定成功')
} }
const onClearCache = () => { const onClearCache = () => {
@ -227,16 +286,13 @@ const onLogout = () => {
}) })
} }
// onShow:tabBar 页切换只触发 onShow,登录态变化后需在此刷新 // onShow:tabBar 页切换只触发 onShow,登录态变化后在此与本地存储对齐
// ⚠️ 本页**不在此处拉取 user.info**:数据由 App 启动 / 登录 / 绑定 / 切身份时统一灌入 store,
// 页面直接读(拉取失败时页内有「点此重试」入口)
onShow(() => { onShow(() => {
// 本地存储是登录态的唯一来源,先与内存态对齐 // 本地存储是登录态的唯一来源,与内存态对齐
// (request 层在 401/过期时会直接清存储,此处保证界面同步) // (request 层在 401/过期时会直接清存储,此处保证界面同步)
userStore.token = getToken() userStore.token = getToken()
if (!userStore.isLogin) return
// 已拉到用户信息(含身份列表)则跳过,避免每次切 Tab 都发请求
if (userStore.userName || userStore.employees.length) return
loadIdentity()
}) })
</script> </script>
@ -280,8 +336,38 @@ onShow(() => {
} }
} }
.entry { .bind-entry {
margin: 24rpx; 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 {

View File

@ -44,6 +44,9 @@
</view> </view>
</template> </template>
</auth-gate> </auth-gate>
<!-- 登录抽屉:点「去登录」或碰需要登录的接口时就地弹出(不跳页) -->
<auth-modal></auth-modal>
</view> </view>
</template> </template>
@ -58,6 +61,7 @@
*/ */
import { computed } from 'vue' import { computed } from 'vue'
import { useUserStore } from '@/store/modules/user' import { useUserStore } from '@/store/modules/user'
import AuthModal from '@/components/auth-modal/auth-modal.vue'
const userStore = useUserStore() const userStore = useUserStore()

View File

@ -1,5 +1,8 @@
<template> <template>
<view class="page"> <view class="page">
<!-- 登录抽屉:点「去登录」或碰需要登录的接口时就地弹出(不跳页) -->
<auth-modal></auth-modal>
<auth-gate auth="required"> <auth-gate auth="required">
<template #default> <template #default>
<view class="card"> <view class="card">
@ -88,6 +91,7 @@
*/ */
import { computed } from 'vue' import { computed } from 'vue'
import { useUserStore } from '@/store/modules/user' import { useUserStore } from '@/store/modules/user'
import AuthModal from '@/components/auth-modal/auth-modal.vue'
import { usePermissionStore } from '@/store/modules/permission' import { usePermissionStore } from '@/store/modules/permission'
import type { MenuNode } from '@/router/entries' import type { MenuNode } from '@/router/entries'

View File

@ -73,6 +73,16 @@ export const PAGE_REGISTRY: PageMeta[] = [
// 由「我的」页主动进入,不作为入口展示 // 由「我的」页主动进入,不作为入口展示
hidden: true hidden: true
}, },
{
key: '/login/confirm-login',
path: 'pages/login/confirm-login',
title: '确认登录',
icon: 'checkmark-circle',
// 未登录也能进(页内引导登录),故为 public
auth: 'public',
// 仅由扫码入口(spm 场景 4)navigateTo 进入,不作为入口展示
hidden: true
},
// ──────── 框架示例页(分包 pagesA):验证三态渲染与权限,业务页上线后可删 ──────── // ──────── 框架示例页(分包 pagesA):验证三态渲染与权限,业务页上线后可删 ────────
{ {

134
src/router/scenes.ts Normal file
View File

@ -0,0 +1,134 @@
/**
* 入口场景分发(扫码 / 链接进入后「该干什么」)
*
* 与 `utils/entry.ts` 分工:entry 负责**解析**(把 q / scene / spm 归一化成
* `{ userId, scene, code, platform, from, extra }`),这里负责**执行**(按场景码分发)并负责跳转。
*
* spm 约定(与后端对齐用,段位含义见 `utils/entry.ts` 文件头):
* spm = [userId].[scene].[code].[platform].[from].[extra...]
*
* 场景码(第 2 段) 第 3 段(code) 落地
* ───────────────────── ───────────────────────────────── ────────────────────────────
* 3 打开页面 目标页逻辑路径(PAGE_REGISTRY.key) 查静态路由表跳转
* 4 确认登录 6 位登录码(PC / 工作台展示的二维码) 调 `wechat.pushLoginCode`
* 1、2、5、6… 预留,按需继续编号(格式不用改)
*
* 为什么用数字而不是语义名:二维码参数长度敏感(B 码 `scene` 上限 31 字符),
* 且与 `G:\uni\数据`(shopro)的 spm 段位方案保持一致。
*/
import { getPageByKey } from '@/router/pages'
import { navigateToPath } from '@/utils/navigate'
import type { EntryInfo } from '@/utils/entry'
/** 场景处理函数签名 */
type SceneHandler = (entry: EntryInfo) => Promise<void> | void
/**
* 场景码 → 处理方式
*
* **后续新增场景在后面继续编号:4、5、6…**
* 后端只需按新编号生成 spm,前端在这里加一行即可(格式不用动,
* 用不上的段位填 `0` 占位)。
*/
const SCENE_TABLE: Record<string, { name: string; handle: SceneHandler }> = {
'3': { name: '打开页面', handle: handleOpenPage },
'4': { name: '确认登录', handle: handleConfirmLogin }
// '1'、'2'、'5'、'6'… 预留,按需继续编号
}
/** 解析场景码(无法识别返回 null) */
export function resolveScene(scene: string) {
if (!scene) return null
return SCENE_TABLE[scene.trim()] || null
}
/**
* 按逻辑路径跳转(`PAGE_REGISTRY.key` → 物理页面)
*
* 走静态路由表查表而不是直接拼路径:页面挪分包 / 改目录只需改一处,
* 且能复用 `navigateToPath` 的 tabBar 判断(tabBar 页必须用 `switchTab`)。
*/
function navigateByLogicalPath(target: string): void {
const key = target.startsWith('/') ? target : `/${target}`
const page = getPageByKey(key)
if (!page) {
// 最常见原因:目标页没登记到 PAGE_REGISTRY,或 spm 里的路径写错
console.warn(`[entry] 目标页未登记到 PAGE_REGISTRY:${target}(跑 npm run check:pages 排查)`)
uni.$u.toast('未找到要打开的页面')
return
}
navigateToPath(page.path, page.title)
}
/**
* 处理入口场景
*
* 由首页在取到「待处理入口」时调用(见 `App.vue` 的捕获 + 首页的消费)。
* 解析失败 / 未识别的场景只告警不抛错,避免影响正常启动。
*/
export async function handleEntryScene(entry: EntryInfo): Promise<void> {
// 服务端直接指定的落地页优先级最高(如订阅消息、后台下发)
if (entry.page) {
navigateByLogicalPath(entry.page)
return
}
const scene = resolveScene(entry.scene)
if (!scene) {
console.warn('[entry] 未识别的场景码:', entry.scene, '| spm =', entry.spm)
return
}
console.log(
`[entry] ${scene.name}:code =`,
entry.code,
'| userId =',
entry.userId,
'| extra =',
entry.extra
)
await scene.handle(entry)
}
/**
* 场景 3:打开指定页面
*
* 约定第 3 段(`code`)放**目标页逻辑路径**(`PAGE_REGISTRY.key`);
* 目标页若有业务参数,从第 6 段起的 `extra` 里按位取。
*/
function handleOpenPage(entry: EntryInfo): void {
if (!entry.code) {
console.warn('[entry] 打开页面缺少目标路径(第 3 段)')
return
}
navigateByLogicalPath(entry.code)
}
/** 扫码确认登录页(防误扫:扫码后必须由用户在本页显式授权) */
export const CONFIRM_LOGIN_PAGE = '/pages/login/confirm-login'
/**
* 场景 4:确认登录(二维码格式 `0.4.{登录码}.{platform}.{from}`)
*
* ⚠️ **扫码后不直接推送**(防误扫),而是跳到确认页由用户显式授权:
* 确认页 → 用户点「确认授权登录」→ `wechat.pushLoginCode` → 对方轮询取回完成登录。
*
* 与 `G:\uni\数据`(shopro)的做法一致:spm 只负责**解析参数并跳页**,
* 真正的业务动作交给落地页面里的用户操作。
*
* ⏳ 待对接:扫码绑定(scene 编号待定),需要后端补一个网关方法
* (现有 `wechat.bindUser` 只支持账号密码)。
*/
async function handleConfirmLogin(entry: EntryInfo): Promise<void> {
if (!entry.code) {
uni.$u.toast('二维码缺少登录码')
return
}
// 只跳页,不推送:真正的授权动作在确认页里由用户显式点击触发
uni.navigateTo({
url: `${CONFIRM_LOGIN_PAGE}?code=${encodeURIComponent(entry.code)}`,
fail: () => uni.$u.toast('确认页打开失败,请重试')
})
}

48
src/shims-wx.d.ts vendored Normal file
View File

@ -0,0 +1,48 @@
/**
* 微信小程序原生 API 类型补充
*
* 为什么需要本文件:
* `@dcloudio/types` 的 `uni-app/uni-patches/wx/index.d.ts` 只声明了 `UniNamespace`
* 命名空间,**未**在编译单元内声明全局 `wx`,因此 uni-app 项目里直接写 `wx.xxx`
* 会报 `TS2304: Cannot find name 'wx'`。
* 这里按需声明本项目用到的原生 API(目前只有 `wx.getAccountInfoSync`)。
*
* 后续若原生调用变多,建议安装 `miniprogram-api-typings` 并加入 tsconfig 的 `types`,
* 然后删除本文件。
*
* ⚠️ `wx` 只在微信小程序端存在,调用处必须配合条件编译 `#ifdef MP-WEIXIN`
* (否则 H5 / App 端会在运行时抛 "wx is not defined")。
*/
/** 全局 wx 对象 */
declare const wx: {
/**
* 获取当前账号信息(基础库 2.2.2+)
* @see https://developers.weixin.qq.com/miniprogram/dev/api/open-api/account-info/wx.getAccountInfoSync.html
*/
getAccountInfoSync(): {
/** 小程序信息 */
miniProgram: {
/** 当前小程序 AppID(开放平台授权产生的小程序返回其真实 AppID) */
appId: string
/** 运行环境版本:develop / trial / release */
envVersion: string
/** 线上小程序版本号(仅 release 环境有值) */
version: string
}
/** 插件信息 */
plugin?: Array<{ appId: string; version: string }>
}
/**
* 退出小程序(基础库 2.17.3+)
*
* ⚠️ 必须由**用户点击**触发,且只能在非分享/非扫码直达等限定场景下生效;
* 失败时用 `fail` 兜底(如回首页)。
*/
exitMiniProgram(options?: {
success?: () => void
fail?: () => void
complete?: () => void
}): void
}

View File

@ -16,9 +16,14 @@ import {
register as apiRegister, register as apiRegister,
getInfo as apiGetInfo, getInfo as apiGetInfo,
changeRole as apiChangeRole, changeRole as apiChangeRole,
logout as apiLogout logout as apiLogout,
wechatLogin as apiWechatLogin,
wechatBindUser as apiWechatBindUser,
wechatPushLoginCode as apiWechatPushLoginCode
} from '@/api/user/user' } from '@/api/user/user'
import type { EmployeeInfo } from '@/api/user/user' import type { EmployeeInfo } from '@/api/user/user'
import { getMiniProgramAppid, getWxLoginCode } from '@/utils/wechat'
import { takePendingLoginCode } from '@/utils/entry'
import { usePermissionStore } from './permission' import { usePermissionStore } from './permission'
/** 登录请求携带的端标记:与 Web 端(desktop / mobile)区分,小程序端固定 mobile */ /** 登录请求携带的端标记:与 Web 端(desktop / mobile)区分,小程序端固定 mobile */
@ -58,6 +63,23 @@ interface UserInfo {
[key: string]: any [key: string]: any
} }
/**
* 进行中的 `user.info` 请求(位于 store 外,不进 state、不需要响应式)
*
* 作用:**并发复用**。小程序启动时 `App.vue` 的 `onLaunch` 与首页 / 「我的」的 `onShow`
* 会几乎同时触发拉取,若不管控就会重复发请求;这里保证同一时刻只有一个在飞,
* 其余调用直接复用它。
*/
let infoRequest: Promise<UserInfo> | null = null
/**
* 登录抽屉的视图类型
*
* 一个字段既当**开关**又当**视图选择器**(参考 `G:\uni\数据` 的 `authType` 设计):
* 空串 = 关闭;其余值 = 打开并显示对应视图。
*/
export type AuthView = '' | 'wechat' | 'account' | 'register'
interface UserState { interface UserState {
token: string token: string
user: UserInfo user: UserInfo
@ -67,6 +89,23 @@ interface UserState {
employees: EmployeeInfo[] employees: EmployeeInfo[]
/** 当前选中身份 = `employees[].id`;0 表示尚未确定 */ /** 当前选中身份 = `employees[].id`;0 表示尚未确定 */
currentEmployeeId: number currentEmployeeId: number
/**
* `user.info` 是否已成功拉取过(含未绑定的微信层信息)
*
* 用途:让 `getInfo()` 默认走缓存,页面只管读 store,不再各自发请求。
* 退出登录 / 清缓存时重置。
*/
infoLoaded: boolean
/** 登录抽屉当前视图(`''` = 关闭) */
authView: AuthView
/**
* 最近一次**成功推送**的登录码
*
* 用途:确认登录页(`pages/login/confirm-login`)拿它判断「当前这个码是不是已经推过了」——
* 无论是用户在本页显式点「确认授权」,还是登录 / 绑定成功后由 `flushPendingLoginCode()` 自动补推送,
* 最终都会落到这里。页面据此切到「已授权」态,避免让用户对同一个码再点一次(第二次必然失败)。
*/
pushedLoginCode: string
} }
export const useUserStore = defineStore('user', { export const useUserStore = defineStore('user', {
@ -76,7 +115,10 @@ export const useUserStore = defineStore('user', {
roleId: 0, roleId: 0,
permissions: [], permissions: [],
employees: [], employees: [],
currentEmployeeId: 0 currentEmployeeId: 0,
infoLoaded: false,
authView: '',
pushedLoginCode: ''
}), }),
getters: { getters: {
@ -98,10 +140,42 @@ export const useUserStore = defineStore('user', {
return ROLE_TYPE_LABEL[type] || type return ROLE_TYPE_LABEL[type] || type
}, },
/** 是否拥有多个身份(为后续 `changeRole` 切换做准备) */ /** 是否拥有多个身份(为后续 `changeRole` 切换做准备) */
hasMultipleEmployees: (state): boolean => state.employees.length > 1 hasMultipleEmployees: (state): boolean => state.employees.length > 1,
/**
* 是否处于「微信已登录、但未绑定 WMS 账号」状态
*
* 后端对未绑定的微信登录态会在 `user.info` 下发 `is_bound: false`
* (已绑定的正常用户信息里**没有**这个字段,故为 `undefined`)。
* 「我的」页据此显示绑定入口;绑定可跳过,跳过不影响免登录。
*/
isWechatUnbound: (state): boolean => !!state.token && state.user.is_bound === false,
/** `user.info` 是否已拉取过(页面据此决定「直接渲染」还是「显示加载/重试」) */
hasUserInfo: (state): boolean => state.infoLoaded,
/** 登录抽屉是否可见(非空视图即打开) */
authVisible: (state): boolean => !!state.authView
}, },
actions: { actions: {
/**
* 打开登录抽屉 / 切换视图
*
* 设计成**同一个方法管开、切、关**(参照 shopro):
* - `showAuthModal()` → 打开,默认微信登录视图
* - `showAuthModal('account')` → 打开并切到账号登录
* - `showAuthModal('')` → 关闭(等价于 `closeAuthModal()`)
*
* 登录交互统一走**抽屉**而不是跳页:用户在哪个页面需要登录,就地弹出来,
* 登录完继续留在原页面(不打断浏览),这是「只在需要时才要求登录」的关键。
*/
showAuthModal(view: AuthView = 'wechat'): void {
this.authView = view
},
/** 关闭登录抽屉 */
closeAuthModal(): void {
this.authView = ''
},
/** 账号密码登录:成功后写入 token(与 new3 相同,登录不立即拉用户信息) */ /** 账号密码登录:成功后写入 token(与 new3 相同,登录不立即拉用户信息) */
async login(payload: { username: string; password: string }): Promise<true> { async login(payload: { username: string; password: string }): Promise<true> {
const resp = await apiLogin({ const resp = await apiLogin({
@ -121,7 +195,10 @@ export const useUserStore = defineStore('user', {
// 登录成功后统一拉一次用户信息(菜单 / 权限点 / 身份): // 登录成功后统一拉一次用户信息(菜单 / 权限点 / 身份):
// 放在 store 里可保证「任何登录入口」都会触发,页面渲染框架才有输入。 // 放在 store 里可保证「任何登录入口」都会触发,页面渲染框架才有输入。
// 失败不阻塞登录 —— token 已到手,菜单为空时 UI 走空态文案并支持重试。 // 失败不阻塞登录 —— token 已到手,菜单为空时 UI 走空态文案并支持重试。
await this.getInfo().catch(() => {}) // 必须 force:换账号后不能吃上一个账号的缓存。
await this.getInfo(true).catch(() => {})
// 若此前是扫码进入(暂存了登录码),登录成功后自动补推送,用户无需再扫一次
await this.flushPendingLoginCode()
return true return true
}, },
@ -140,14 +217,163 @@ export const useUserStore = defineStore('user', {
}) })
}, },
/** 拉取用户信息(权限点 + 菜单),后续页面渲染框架会消费 menus */ /**
async getInfo(): Promise<UserInfo> { * 微信小程序一键登录
*
* 流程:`uni.login` 取临时 code → `wechat.loginByCode`(带运行时真实 AppID)
* → **token 立即落地存储** → `user.info` 探测是否已绑定 WMS 账号。
*
* 关键设计(重要):
* - **token 一律写入本地存储**,包括 `id = 0` 的未绑定微信登录态:
* 它是有效的免登录凭证,下次打开小程序直接进首页,不重复提示登录。
* - 未绑定**不是错误状态**,而是「登录态可用、业务身份待绑定」,
* 绑定入口保留在「我的」页,绑定过程可跳过。
*
* @return `{ bound }`:false 表示需提示用户在「我的」页或登录页绑定账号
*/
async wechatLogin(): Promise<{ bound: boolean }> {
const appid = getMiniProgramAppid()
if (!appid) {
throw new Error('未获取到小程序 AppID,微信登录不可用')
}
const code = await getWxLoginCode()
const resp = await apiWechatLogin({ code, appid })
const token = resp.data?.token || ''
if (!token) {
throw new Error('微信登录失败:未获取到 token')
}
// 先落地 token:微信登录成功即算登录态(未绑定也保留,下次免登录)
setToken(token)
this.token = token
// 再用 user.info 探测绑定状态(必须 force:换了个微信登录态,缓存不能用)
const info = await this.getInfo(true).catch(() => null)
const bound = info?.is_bound !== false
// 已登录且已绑定 → 具备推送登录码的条件(扫码进入时可能暂存过)
if (bound) await this.flushPendingLoginCode()
return { bound }
},
/**
* 绑定 WMS 账号(把微信登录态升级为正式业务登录态)
*
* 后端 `wechat.bindUser` 凭**请求头里的微信 token** 取 `oauth_id` 定位记录,
* 校验账号密码后签发正式 token(`id` = 真实账号 ID)。
* token 已在存储里(`wechatLogin` 时就落地了),故由 `request` 自动带上。
* 失败(账号密码错误等)由 request 层统一 toast。
*/
async wechatBind(payload: { username: string; password: string }): Promise<void> {
const current = getToken()
// 调试日志:确认「请求带了 token」(绑定失败最常见的原因是登录态丢了)
console.log('[wechat] bindUser 发起', {
username: payload.username.trim(),
hasToken: !!current,
tokenHead: current ? `${current.slice(0, 20)}...` : '(空)'
})
const resp = await apiWechatBindUser({
username: payload.username.trim(),
password: payload.password
})
console.log('[wechat] bindUser 返回', { flag: resp.flag, code: resp.code, user: resp.data?.user })
const token = resp.data?.token || ''
if (!token) {
throw new Error('绑定失败:未获取到 token')
}
setToken(token)
this.token = token
// 绑定后身份变了,必须强制重拉(不能吃旧缓存)
await this.getInfo(true).catch(() => {})
// 绑定完成后可能才具备推送条件(扫码时未绑定的场景)
await this.flushPendingLoginCode()
},
/**
* 推送登录码(场景 4「确认登录」)
*
* 前置条件:**已登录且已绑定**(后端取当前鉴权用户作为要登录的账号)。
* 成功后展示该码的一方(PC / 工作台)轮询取回即登录为本账号。
* 未登录时后端返回业务码 401,api 层已关掉全局跳转,只提示不踢页面。
*/
async pushLoginCode(code: string): Promise<void> {
await apiWechatPushLoginCode({ code })
// 记下已推送的码,给确认登录页判断「是否已授权」(见 UserState.pushedLoginCode)
this.pushedLoginCode = code
},
/**
* 消费「暂存的登录码」(扫码时未登录 / 未绑定而先存下的)
*
* 在登录 / 绑定成功之后调用:条件满足才推送,用户无需再扫一次码。
* 无暂存码或条件不足时静默返回;推送失败(码过期等)也不阻断登录流程。
*/
async flushPendingLoginCode(): Promise<void> {
if (!this.isLogin || this.isWechatUnbound) return
const code = takePendingLoginCode()
if (!code) return
try {
await this.pushLoginCode(code)
uni.showToast({ title: '已为电脑端确认登录', icon: 'none' })
} catch {
// 失败提示由 request 层统一 toast(如登录码已过期)
}
},
/**
* 拉取用户信息(权限点 + 菜单),后续页面渲染框架会消费 menus
*
* **调用时机已收口,页面不再各自请求**:
* ① 小程序启动且本地有 token → `App.vue` 的 `onLaunch` 拉一次(全局备用)
* ② 登录成功后(账号密码 / 微信 / 绑定)→ 登录动作内拉一次
* ③ 切换身份后 → `changeRole` 内重拉
* 其余场景(首页 / 「我的」页渲染)**直接读 store**,需要强刷时传 `force = true`。
*
* 也是微信绑定状态的探测入口:未绑定微信账号时后端返回 `is_bound: false`,
* 此时只记录**微信层信息**(openid / unionid / oauth_id)供「我的」页显示绑定入口,
* 菜单 / 身份 / 权限一概不灌(未绑定账号本就没有这些数据)。
*
* @param force 强制重新请求(默认走缓存:已成功拉过就直接返回 store 里的数据)
*/
async getInfo(force = false): Promise<UserInfo> {
if (this.infoLoaded && !force) return this.user
// 并发复用:启动拉取与页面 onShow 可能同时触发,只发一次请求。
// force 不复用 —— 换账号 / 绑定时要的是最新数据,不能吃到上一个身份的响应。
if (infoRequest && !force) return infoRequest
infoRequest = this.fetchInfo()
try {
return await infoRequest
} finally {
infoRequest = null
}
},
/**
* 真正发出 `user.info` 请求并写入 state
*
* 仅供 `getInfo` 调用(要共享「并发复用 / 缓存」能力,请走 `getInfo`)。
*/
async fetchInfo(): Promise<UserInfo> {
const resp = await apiGetInfo({ device: DEVICE }) const resp = await apiGetInfo({ device: DEVICE })
const user = resp.data const user = resp.data
if (!user) { if (!user) {
throw new Error('获取用户信息失败,请重新登录') throw new Error('获取用户信息失败,请重新登录')
} }
// 未绑定的微信登录态:只存微信层信息(is_bound=false / id=0),
// 不灌菜单 / 身份 / 权限 —— 但必须写 user,供 isWechatUnbound 判定
if (user.is_bound === false) {
this.user = user
this.infoLoaded = true
return user
}
this.user = user this.user = user
this.permissions = user.permissions || [] this.permissions = user.permissions || []
this.roleId = user.employees_id || 0 this.roleId = user.employees_id || 0
@ -155,6 +381,7 @@ export const useUserStore = defineStore('user', {
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
return user return user
}, },
@ -232,7 +459,7 @@ export const useUserStore = defineStore('user', {
if (user.permissions) this.permissions = user.permissions if (user.permissions) this.permissions = user.permissions
} }
await this.getInfo() await this.getInfo(true)
}, },
/** 退出登录:先通知后端,无论成功与否都要清掉本地登录态 */ /** 退出登录:先通知后端,无论成功与否都要清掉本地登录态 */
@ -255,6 +482,7 @@ export const useUserStore = defineStore('user', {
this.permissions = [] this.permissions = []
this.employees = [] this.employees = []
this.currentEmployeeId = 0 this.currentEmployeeId = 0
this.infoLoaded = false
// 菜单/入口一并清空:退出登录、401、清缓存都不能让旧身份的入口残留 // 菜单/入口一并清空:退出登录、401、清缓存都不能让旧身份的入口残留
usePermissionStore().reset() usePermissionStore().reset()
}, },

48
src/utils/auth-notify.ts Normal file
View File

@ -0,0 +1,48 @@
/**
* 未授权事件(未登录 / 登录态失效)的统一通知通道
*
* 为什么不直接在 `request.ts` 里调 store:
* `request → store/modules/user → api/* → request` 会形成**循环依赖**。
* 所以这里做一个最小的发布/订阅:`request` 层负责**发布**,
* 应用启动时注册**谁来处理**(当前实现是「弹半屏登录抽屉」,兜底「跳登录页」)。
*
* 典型触发场景:
* ① 接口标记了 `auth: true` 但本地没有 token → 请求根本不发,直接通知(省一次往返)
* ② 服务端返回 HTTP 401 / 业务码 401(token 过期)→ 清登录态后通知
*/
/** 未授权处理器:`reason` 为可选说明(用于日志/提示) */
type UnauthorizedHandler = (reason: string) => void
let handler: UnauthorizedHandler | null = null
/**
* 注册未授权处理器(应用启动时调用一次即可,重复注册会覆盖)
*
* 例如在 `App.vue` 的 `onLaunch` 里:
* ```ts
* setUnauthorizedHandler(() => useUserStore().showAuthModal())
* ```
*/
export function setUnauthorizedHandler(fn: UnauthorizedHandler): void {
handler = fn
}
/** 清空处理器(一般不需要,测试或热重载时可用来复位) */
export function clearUnauthorizedHandler(): void {
handler = null
}
/**
* 通知发生了未授权(仅供 request 层调用)
*
* 没有注册处理器时静默返回 —— 调用方(request)会自行走兜底逻辑(跳登录页)。
*/
export function notifyUnauthorized(reason = ''): void {
if (handler) handler(reason)
}
/** 是否已注册处理器(request 层据此决定是否需要自己兜底) */
export function hasUnauthorizedHandler(): boolean {
return !!handler
}

316
src/utils/entry.ts Normal file
View File

@ -0,0 +1,316 @@
/**
* 小程序入口参数解析(扫码 / 链接 / 分享进入)
*
* 为什么需要它:微信把「扫码进入」的原始链接塞在 `options.q` 里(**URL 编码的完整路径**),
* 小程序码带参会放在 `options.scene` 里(**最长 31 字符**,约定成 `k=v` 形式),
* 普通链接 / 分享则是 `options.xxx` 平铺。三者形态不同但语义相同,
* 必须在这一层归一化,业务侧才不用关心「用户是从哪儿点进来的」。
*
* ─────────────── spm:场景参数约定(与后端对齐用)───────────────
*
* 沿用 `G:\uni\数据`(shopro)的点分段位方案:**全数字、位置表意、可无限往后加段**,
* 参数最短(小程序码 `scene` 上限 31 字符),新增场景不用改格式。
*
* spm = [userId].[scene].[code].[platform].[from].[extra...]
*
* 段位 名称 本项语义 特殊值
* ──────── ────────── ───────────────────────────────────────── ───────────
* 第 1 段 userId 发起方用户 ID(PC / 工作台的操作账号) `0` = 无
* 第 2 段 scene **场景码**(数字,见 `router/scenes.ts`) 1=扫码登录
* 2=扫码绑定
* 3=打开页面
* 4、5、6…后续继续编号
* 第 3 段 code **随机码**(登录码 / 绑定码)/ 业务标识 `0` = 无
* 第 4 段 platform 渠道:1=H5 2=公众号 3=小程序 4=App(同 shopro)
* 第 5 段 from 来源:1=直接转发 2=海报 3=链接(同 shopro)
* 第 6 段起 extra 预留扩展,按场景解释
*
* ⚠️ `code` 段**约定不含 `.`**,否则会破坏段位切分
* (base64 的字符集 `A-Za-z0-9+/=` 是安全的)
*
* 例:`spm=0.1.a1b2c3d4e5f6.3.2`
* = 无发起人 · 扫码登录 · 随机码 a1b2c3d4e5f6 · 小程序 · 二维码
*/
/** spm 段位分隔符 */
const SPM_SEPARATOR = '.'
/** App.onLaunch / onShow 收到的启动参数(`query` / `scene` / `q` 为微信端特有) */
export interface EntryLaunchOptions {
/** 进入的页面路径(不含前导 `/`) */
path?: string
/** 页面参数(扫码进入时 `q` 也在这里) */
query?: Record<string, any>
/** 小程序码携带的参数(原始字符串,可能形如 `k=v`) */
scene?: string | number
/** 扫码进入时的原始链接(URL 编码) */
q?: string
/** 场景参数 */
spm?: string
[key: string]: any
}
/** 归一化后的入口信息 */
export interface EntryInfo {
/** 原始 spm(未解析时为空串) */
spm: string
/** spm 全部段位(原样保留,取后续扩展段时用) */
segments: string[]
/** 第 1 段:发起方用户 ID(`'0'` / 空段 → 空串) */
userId: string
/** 第 2 段:场景码(数字,空串表示未给) */
scene: string
/** 第 3 段:随机码 / 业务标识(`'0'` / 空段 → 空串) */
code: string
/** 第 4 段:渠道(1=H5 2=公众号 3=小程序 4=App) */
platform: string
/** 第 5 段:来源(1=直接转发 2=海报 3=链接) */
from: string
/** 第 6 段起:预留扩展段 */
extra: string[]
/** 直接指定的落地页(`options.page`,多为服务端下发) */
page: string
/** 其余平铺参数(如 `id` / `custom_id`),供业务按需取用 */
rest: Record<string, string>
}
/** 空入口(无任何参数时) */
export function emptyEntry(): EntryInfo {
return {
spm: '',
segments: [],
userId: '',
scene: '',
code: '',
platform: '',
from: '',
extra: [],
page: '',
rest: {}
}
}
/** `decodeURIComponent` 容错版:非法编码时原样返回,绝不抛异常 */
function decodeSafe(value: string): string {
try {
return decodeURIComponent(value)
} catch {
return value
}
}
/**
* 从 URL(或 `q` 的原始值)里抠出 `spm` 参数
*
* ⚠️ 扫码进入时 `q` 是**整条 URL 编码过的链接**,所以「原文」和「解码后」两个候选都要试:
* 有的是 `q=pages%2Findex%2Findex%3Fspm%3Dlogin.abc`(整体编码),
* 有的只是参数值被编码。少试一种就会漏掉。
*/
export function extractSpmFromUrl(url: string): string {
if (!url) return ''
const candidates = [url]
const decoded = decodeSafe(url)
if (decoded !== url) candidates.push(decoded)
for (const item of candidates) {
const matched = item.match(/[?&]spm=([^&#]+)/)
if (matched && matched[1]) return decodeSafe(matched[1])
}
return ''
}
/**
* spm 段位下标(0-based,含义见文件头注释)
*
* 直接用常量下标而不是解构:段位顺序是**对外约定**,摊开后一目了然,
* 以后要加第 6、7 段只需在 `extra` 里按位取。
*/
const SEG = {
userId: 0,
scene: 1,
code: 2,
platform: 3,
from: 4,
extra: 5
} as const
/** 段位取值:`'0'` 与空段都视为「无值」(与 shopro 的约定一致) */
function segValue(value?: string): string {
const item = (value ?? '').trim()
return item === '0' ? '' : item
}
/**
* 解析 spm → 按段位取出各字段
*
* 段位不足时(如只给了 `0.1`)后面的段留空,合法性交给场景表判断;
* 完全为空时返回 `emptyEntry()`。
*/
export function parseSpm(spm: string): EntryInfo {
const entry = emptyEntry()
const raw = decodeSafe(String(spm || '')).trim()
if (!raw) return entry
const parts = raw.split(SPM_SEPARATOR).map((item) => item.trim())
if (!parts.length) return entry
entry.spm = raw
entry.segments = parts
entry.userId = segValue(parts[SEG.userId])
entry.scene = segValue(parts[SEG.scene])
entry.code = segValue(parts[SEG.code])
entry.platform = segValue(parts[SEG.platform])
entry.from = segValue(parts[SEG.from])
entry.extra = parts.slice(SEG.extra).map((item) => decodeSafe(item))
return entry
}
/**
* 把启动参数归一化成入口信息
*
* 优先级:`q` 里的 spm(扫码进入) > 平铺的 `spm` > `scene`(小程序码带参)。
* 三者同源,取到即用,避免同一次进入被处理两遍。
*/
export function normalizeEntry(options?: EntryLaunchOptions | null): EntryInfo {
if (!options) return emptyEntry()
const query = (options.query || {}) as Record<string, any>
// ① spm:优先从 `q`(扫码原始链接)里抠,其次平铺参数
const spmFromQ = extractSpmFromUrl(String(options.q ?? query.q ?? ''))
const spm = spmFromQ || decodeSafe(String(options.spm ?? query.spm ?? '')).trim()
const entry = spm ? parseSpm(spm) : emptyEntry()
// ② scene:小程序码带参,约定 `k=v`(31 字符限制下的标准做法)
//
// ⚠️ 坑:**只认 `options.query.scene`**。
// `options.scene` 是微信的**场景值**(纯数字,如 1001 = 发现栏主入口、1011 = 扫描二维码),
// 没有任何业务含义;把它当场景码会导致启动时报「未识别的场景码:1001」。
const rawScene = query.scene
if (rawScene !== undefined && rawScene !== null && String(rawScene).trim() !== '') {
const scene = decodeSafe(String(rawScene).trim())
if (!entry.scene && scene.includes('=')) {
// `k=v` 形式:键当场景码、值当随机码
const [key, value = ''] = scene.split('=')
if (key) {
entry.scene = key
entry.code = value
}
} else if (!entry.scene && scene.includes('.')) {
// 整串就是 spm 的形式(如 `scene=0.4.123456.3.2`)—— 直接按 spm 解析
const fromScene = parseSpm(scene)
if (fromScene.scene) Object.assign(entry, fromScene)
} else if (scene && !(scene in entry.rest)) {
// 其它形态:当普通参数留存,交业务按需取
entry.rest.scene = scene
}
}
// ③ 服务端直接指定落地页(如订阅消息场景)
const page = decodeSafe(String(options.page ?? query.page ?? '')).trim()
if (page) entry.page = page
// ④ 其余平铺参数(跳过已消费的键,避免业务重复处理)
const CONSUMED = new Set(['q', 'scene', 'spm', 'page'])
const merged: Record<string, any> = { ...query, ...options }
Object.keys(merged).forEach((key) => {
if (CONSUMED.has(key)) return
const value = merged[key]
if (value === undefined || value === null || typeof value === 'object') return
entry.rest[key] = String(value)
})
return entry
}
/** 入口信息是否有可处理的内容 */
export function hasEntryAction(entry: EntryInfo): boolean {
return !!(entry.scene || entry.page)
}
// ──────────────────────── 待处理入口的暂存 ────────────────────────
/**
* 为什么需要暂存:`App.onLaunch` 触发时页面栈还没就绪,此时 `navigateTo` 会失败;
* 正确做法是先记下来,等页面(首页)`onShow` 时再消费。
* 用本地存储而不是内存变量:热启动(小程序在后台时扫码进入)可能不经过 `onLaunch`,
* 且冷启动时 `App` 与页面的初始化顺序不可控,持久化更稳。
*/
const PENDING_ENTRY_KEY = 'entry_pending'
/** 暂存待处理的入口 */
export function savePendingEntry(entry: EntryInfo): void {
if (!hasEntryAction(entry)) return
try {
uni.setStorageSync(PENDING_ENTRY_KEY, JSON.stringify(entry))
} catch {
// 存储失败只影响「进入时自动处理」,不阻断启动
}
}
/** 取出并清空待处理入口(保证同一入口只被消费一次) */
export function takePendingEntry(): EntryInfo | null {
try {
const raw = uni.getStorageSync(PENDING_ENTRY_KEY)
if (!raw) return null
uni.removeStorageSync(PENDING_ENTRY_KEY)
const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw
if (!parsed || typeof parsed !== 'object') return null
return { ...emptyEntry(), ...(parsed as EntryInfo) }
} catch {
return null
}
}
/** 丢弃待处理入口 */
export function clearPendingEntry(): void {
try {
uni.removeStorageSync(PENDING_ENTRY_KEY)
} catch {
// 忽略
}
}
// ──────────────────── 待推送的登录码(场景 4:确认登录)────────────────────
/**
* 扫码确认登录时,若小程序端**未登录 / 未绑定**,先把登录码暂存下来,
* 引导用户完成登录,登录成功后再自动推送(见 store 的 `flushPendingLoginCode`)。
*
* 为什么与入口暂存(`PENDING_ENTRY_KEY`)分开存:两者生命周期不同 ——
* 入口在页面显示、场景分发时就被消费掉了;登录码要一直留到**登录完成**那一刻。
*/
const PENDING_LOGIN_CODE_KEY = 'entry_pending_login_code'
/** 暂存待推送的登录码 */
export function savePendingLoginCode(code: string): void {
if (!code) return
try {
uni.setStorageSync(PENDING_LOGIN_CODE_KEY, code)
} catch {
// 存储失败不影响主流程
}
}
/** 取出并清空待推送的登录码(保证只推一次) */
export function takePendingLoginCode(): string {
try {
const code = uni.getStorageSync(PENDING_LOGIN_CODE_KEY)
if (!code) return ''
uni.removeStorageSync(PENDING_LOGIN_CODE_KEY)
return String(code)
} catch {
return ''
}
}
/** 丢弃待推送的登录码 */
export function clearPendingLoginCode(): void {
try {
uni.removeStorageSync(PENDING_LOGIN_CODE_KEY)
} catch {
// 忽略
}
}

View File

@ -30,6 +30,7 @@
import { getToken, removeToken, setToken } from './auth' import { getToken, removeToken, setToken } from './auth'
import { redirectToLogin } from './auth-guard' import { redirectToLogin } from './auth-guard'
import { notifyUnauthorized, hasUnauthorizedHandler } from './auth-notify'
import { usePermissionStore } from '@/store/modules/permission' import { usePermissionStore } from '@/store/modules/permission'
/** 接口根地址,来自 .env.[mode] */ /** 接口根地址,来自 .env.[mode] */
@ -135,6 +136,22 @@ export interface RequestOptions {
loading?: string loading?: string
/** 失败时是否自动 toast,默认 true */ /** 失败时是否自动 toast,默认 true */
toastError?: boolean toastError?: boolean
/**
* 该接口**是否要求登录**,默认 false
*
* 传 true 时:未登录**根本不会发请求**,直接唤起登录(弹半屏抽屉),
* 省一次无意义的往返,也让「未登录」的反馈更快。
* 参照 `G:\uni\数据` 的 `apis.js` 里每个接口的 `auth` 标记。
*/
auth?: boolean
/**
* 401(token 失效)时是否自动处理(清登录态 + 弹登录 / 跳登录页),默认 true
*
* 微信绑定、确认登录这类**中间态接口**必须传 false:
* 它们的 token 是微信登录态(`id=0`),失效时后端也用 401 表达,
* 若跟着全局逻辑走,用户会被踢出页面、输入丢失。
*/
redirectOn401?: boolean
} }
/** 统一提示:优先用 uview-plus 的 toast,保证与页面内提示风格一致 */ /** 统一提示:优先用 uview-plus 的 toast,保证与页面内提示风格一致 */
@ -213,11 +230,24 @@ export default function request<T = any>(options: RequestOptions): Promise<BizRe
header, header,
timeout = 15000, timeout = 15000,
loading, loading,
toastError = true toastError = true,
auth = false,
redirectOn401 = true
} = options } = options
const token = getToken() const token = getToken()
// ── 请求前预判:需要登录的接口,未登录就不发请求 ──
// 直接唤起登录(弹抽屉,不打断浏览);没注册处理器时退回跳登录页
if (auth && !token) {
if (hasUnauthorizedHandler()) {
notifyUnauthorized('未登录')
} else {
redirectToLogin()
}
return Promise.reject(new Error('未登录,请先登录'))
}
if (loading) { if (loading) {
uni.showLoading({ title: loading, mask: true }) uni.showLoading({ title: loading, mask: true })
} }
@ -244,9 +274,23 @@ export default function request<T = any>(options: RequestOptions): Promise<BizRe
// ── HTTP 层:非 2xx ── // ── HTTP 层:非 2xx ──
if (status < 200 || status >= 300) { if (status < 200 || status >= 300) {
if (status === 401) { if (status === 401) {
// 网关的登录中间件用 **HTTP 401** 表达未登录,响应体里通常带具体原因
// (如「用户不存在或已被删除」),优先用它做提示
const reason =
(res.data as BizResponse<T> | undefined)?.message || '未授权,请重新登录'
if (redirectOn401) {
clearSession() clearSession()
// 优先弹登录抽屉(不打断浏览);没注册处理器时退回跳登录页
if (hasUnauthorizedHandler()) {
notifyUnauthorized(reason)
} else {
redirectToLogin() redirectToLogin()
reject(new Error('未授权,请重新登录')) }
} else if (toastError) {
// 中间态接口(微信绑定 / 确认登录等):只提示,不清登录态、不跳登录页
toast(reason)
}
reject(new Error(reason))
return return
} }
const message = HTTP_STATUS_MAP[status] || `连接错误 ${status}` const message = HTTP_STATUS_MAP[status] || `连接错误 ${status}`
@ -269,8 +313,16 @@ export default function request<T = any>(options: RequestOptions): Promise<BizRe
body.message || body.msg || ERROR_CODE_MAP[body.code] || '请求失败' body.message || body.msg || ERROR_CODE_MAP[body.code] || '请求失败'
if (TOKEN_EXPIRED_CODES.includes(body.code)) { if (TOKEN_EXPIRED_CODES.includes(body.code)) {
if (redirectOn401) {
clearSession() clearSession()
if (hasUnauthorizedHandler()) {
notifyUnauthorized(message)
} else {
redirectToLogin() redirectToLogin()
}
} else if (toastError) {
toast(message)
}
reject(new Error(message)) reject(new Error(message))
return return
} }

63
src/utils/wechat.ts Normal file
View File

@ -0,0 +1,63 @@
/**
* 微信小程序平台能力封装
*
* 只放「必须调用原生 `wx.*`、且需要条件编译」的能力:
* 通用请求逻辑在 `utils/request.ts`,登录业务编排在 `store/modules/user.ts`。
*/
/**
* 取当前小程序的真实 AppID(非微信小程序平台返回空串)
*
* 为什么不写进 `.env`:
* 本项目要作为**微信开放平台第三方平台的模板小程序**发布,各仓库授权后会生成
* 不同 AppID 的小程序,构建期无法预知;`wx.getAccountInfoSync()` 返回的是
* 运行时的真实 AppID(普通小程序 / 平台授权小程序均适用)。
*
* ⚠️ 该 AppID 是**字符串**(形如 `wx3xxxxx`),与后端 `wms_wechat_app.id`(整数主键)
* 不是一回事。后端 `systems/wechat.js` 的 `resolveWechatApp()` 已支持按该字符串
* 反查授权记录,故小程序端只需上报真实 AppID。
*
* 开发者工具中若项目未填 AppID,这里会拿到 `touristappid`(调用方按「拿不到」处理即可)。
*/
export function getMiniProgramAppid(): string {
let appid = ''
// #ifdef MP-WEIXIN
try {
const accountInfo = wx.getAccountInfoSync()
// 调试输出:在微信开发者工具控制台核对运行时真实 AppID
// (重点看 miniProgram.appId;envVersion=develop/trial/release 可确认当前环境)
console.log('[wechat] wx.getAccountInfoSync() =', accountInfo)
console.log('[wechat] 小程序 AppID =', accountInfo.miniProgram.appId, '环境 =', accountInfo.miniProgram.envVersion)
appid = accountInfo.miniProgram.appId || ''
} catch (err) {
// 极早期调用或工具异常时按「拿不到」处理,由调用方给出提示
console.warn('[wechat] wx.getAccountInfoSync() 调用失败', err)
appid = ''
}
// #endif
return appid
}
/**
* 取微信登录临时 code(等价于 `wx.login`)
*
* ⚠️ code 只能使用一次且 5 分钟内有效,必须**立即**交给后端换 openid
* (后端 `systems/wechat.js` 的 `loginByCode` 内部走 jscode2session)。
*/
export function getWxLoginCode(): Promise<string> {
return new Promise<string>((resolve, reject) => {
uni.login({
provider: 'weixin',
success: (res) => {
const code = (res as { code?: string } | undefined)?.code || ''
if (code) {
resolve(code)
} else {
reject(new Error('微信登录失败:未获取到登录码'))
}
},
fail: () => reject(new Error('微信登录失败:请确认已安装微信并允许授权'))
})
})
}

View File

@ -22,7 +22,7 @@
| tabBar 图标 | ❌ 待补充 | 需本地图片 ≤ 40KB、81×81px | | tabBar 图标 | ❌ 待补充 | 需本地图片 ≤ 40KB、81×81px |
| 分包(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 按需引导登录 |
| 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` 一致性校验 |
@ -32,7 +32,7 @@
| 页面渲染框架 | 🚧 开发中(阶段 1、2、2.5、3、4 已完成) | 见第 12 节与《页面渲染框架-设计与任务清单.md》 | | 页面渲染框架 | 🚧 开发中(阶段 1、2、2.5、3、4 已完成) | 见第 12 节与《页面渲染框架-设计与任务清单.md》 |
| 身份(角色/仓库)展示 | ✅ 已完成 | 「我的」页登录后显示:姓名 / 身份类型 / 所属组织 / 员工 ID / 授权到期;数据来自 `user.info` 的 `employees[]`,**不改数据库** | | 身份(角色/仓库)展示 | ✅ 已完成 | 「我的」页登录后显示:姓名 / 身份类型 / 所属组织 / 员工 ID / 授权到期;数据来自 `user.info` 的 `employees[]`,**不改数据库** |
| 身份切换 `changeRole` | 🚧 已实现待联调 | 入口在「我的」页(多身份时出现);接口已实测存在,返回结构待后端确认 | | 身份切换 `changeRole` | 🚧 已实现待联调 | 入口在「我的」页(多身份时出现);接口已实测存在,返回结构待后端确认 |
| 微信一键登录 / 扫码登录 | ❌ 未做 | 属另一条链路(`uni.login` → `user.loginByCode`),本次范围外 | | 微信一键登录 | ✅ 已完成 | `wechat.loginByCode`(不是 `user.loginByCode`);AppID 运行时取(`wx.getAccountInfoSync`,适配开放平台模板多仓库);token 立即落地(未绑定也算免登录态);绑定可跳过、入口常驻「我的」页 |
> 📄 **配套文档**:`页面渲染框架-设计与任务清单.md` —— 菜单 / 权限 / 页面渲染的决策与任务清单(第 12 节为摘要) > 📄 **配套文档**:`页面渲染框架-设计与任务清单.md` —— 菜单 / 权限 / 页面渲染的决策与任务清单(第 12 节为摘要)
> ⚠️ **已知坑**:同时跑两个 `dev:mp-weixin` 进程会写坏产物,导致预览报 > ⚠️ **已知坑**:同时跑两个 `dev:mp-weixin` 进程会写坏产物,导致预览报
@ -137,7 +137,7 @@ d:\wechat\
│ ├── empty-state/empty-state.vue # 统一空态/失败提示 + 「重试」 │ ├── empty-state/empty-state.vue # 统一空态/失败提示 + 「重试」
│ └── login-panel/login-panel.vue # 登录 / 注册面板组件 │ └── login-panel/login-panel.vue # 登录 / 注册面板组件
├── composables/ # 组合式函数 ├── composables/ # 组合式函数
│ └── usePageAuth.ts # 页面登录策略与「去登录」跳转 │ └── usePageAuth.ts # 页面登录策略与「去登录」(弹登录抽屉)
├── router/ # 静态路由表与入口树生成 ├── router/ # 静态路由表与入口树生成
│ ├── pages.ts # PAGE_REGISTRY / PAGE_MAP / PAGE_BY_PATH / isTabBarPage │ ├── pages.ts # PAGE_REGISTRY / PAGE_MAP / PAGE_BY_PATH / isTabBarPage
│ └── entries.ts # generateEntries():菜单 × 路由表 → 可见入口树(纯函数) │ └── entries.ts # generateEntries():菜单 × 路由表 → 可见入口树(纯函数)
@ -149,7 +149,7 @@ d:\wechat\
│ ├── navigate.ts # 统一跳转(自动区分 switchTab / navigateTo) │ ├── navigate.ts # 统一跳转(自动区分 switchTab / navigateTo)
│ └── request.ts # uni.request 封装 │ └── request.ts # uni.request 封装
├── pages/ # 主包页面(启动页 + tabBar 页) ├── pages/ # 主包页面(启动页 + tabBar 页)
│ ├── login/login.vue # 登录 / 注册页(非启动页,由「我的」页主动进入) │ ├── login/login.vue # 登录 / 注册页(非启动页,仅 401 兜底 / 直接访问)
│ ├── index/index.vue # 首页(启动页):入口由 permissionStore / 本地公共清单驱动 │ ├── index/index.vue # 首页(启动页):入口由 permissionStore / 本地公共清单驱动
│ └── mine/mine.vue # 我的 │ └── mine/mine.vue # 我的
├── pagesA/ # 分包 A(已注册;当前放框架示例页) ├── pagesA/ # 分包 A(已注册;当前放框架示例页)
@ -237,7 +237,7 @@ d:\wechat\
| Tab | 页面路径 | 页面内容 | | Tab | 页面路径 | 页面内容 |
|---|---|---| |---|---|---|
| 首页 | `pages/index/index` | 业务入口九宫格(未登录取本地公共入口;登录后取后端菜单,支持「分组标题 + 子项」两层)+ 运行信息 | | 首页 | `pages/index/index` | 业务入口九宫格(未登录取本地公共入口;登录后取后端菜单,支持「分组标题 + 子项」两层)+ 运行信息 |
| 我的 | `pages/mine/mine` | 未登录:「登录 / 注册」按钮;已登录:登录态展示 + 退出登录;另有运行信息 + 清除缓存 | | 我的 | `pages/mine/mine` | 未登录:点头部用户信息区弹登录抽屉;已登录:登录态展示 + 退出登录;另有运行信息 + 清除缓存 |
约定(务必遵守): 约定(务必遵守):
- `list` 最少 2 个、最多 5 个;**tabBar 页必须在主包**,不能放分包 - `list` 最少 2 个、最多 5 个;**tabBar 页必须在主包**,不能放分包
@ -338,16 +338,43 @@ d:\wechat\
## 6. 登录、鉴权与用户信息 ## 6. 登录、鉴权与用户信息
- [x] **登录流程(账号密码版,对齐 new3)** ✅ - [x] **登录流程(账号密码版,对齐 new3)** ✅
入口 `pages/login/login`(**非启动页**,由「我的」页主动进入)→ 组件 `components/login-panel/` → 入口:任意页面**就地弹登录抽屉**(`components/auth-modal/`,内容 `components/login-panel/`)→
`store/modules/user.ts` 的 `login()` → `api/user/user.ts` 的 `user.login` `store/modules/user.ts` 的 `login()` → `api/user/user.ts` 的 `user.login`
(`POST /system?method=user.login&v=1.0&timestamp=...`,body `{ username, password, device }`) (`POST /system?method=user.login&v=1.0&timestamp=...`,body `{ username, password, device }`)
→ 响应 `data.token` 写入 `utils/auth.ts`。 → 响应 `data.token` 写入 `utils/auth.ts`。
注册走同一网关的 `user.register`(`username` / `email` / `real_name` / `password`), 注册走同一网关的 `user.register`(`username` / `email` / `real_name` / `password`),
成功后回到登录页并回填账号(与 new3 一致,不自动登录)。 成功后回到登录页并回填账号(与 new3 一致,不自动登录)。
- [ ] **微信一键登录(`uni.login` → `user.loginByCode`)** - [x] **微信一键登录(`uni.login` → `wechat.loginByCode`)** ✅
`uni.login` 取临时 `code` → 后端换 `openid` / `session_key` → 颁发业务 token。 ⚠️ **接口是 `wechat.loginByCode`,不是 `user.loginByCode`**(后者接的是 ye4s base64 登录码,
本次未做:属独立链路,接口已具备(new3 有 `user.loginByCode`),后续按需补。 走 `loginByYe4sCode`,与小程序无关)—— 已核对后端 `app/service/systems/wechat.js`。
链路:
1. `uni.login({ provider: 'weixin' })` 取临时 `code`(一次性,5 分钟有效)
2. `wechat.loginByCode`,入参 `{ code, appid }`
- `appid` = **运行时**真实 AppID(`wx.getAccountInfoSync().miniProgram.appId`)
- 不写进 `.env`:代码作为**开放平台第三方平台模板**发布,各仓库授权后 AppID 不同
- 后端 `resolveWechatApp()` 按 appid 反查 `wms_wechat_app` 授权记录(已支持 app_id 主键 / appid 字符串两种入参)
3. 后端 `jscode2session` 换 openid/session_key → 查/建 `wms_user_oauth` → 签发 token
(`id = 0` 表示该微信尚未绑定 WMS 账号)
4. **token 立即落地存储**(含 `id = 0` 的未绑定态)—— 它是有效的免登录凭证
5. 再调 `user.info` 探测绑定状态:未绑定时后端**不返回 401**,而是下发 `is_bound: false`
+ 微信层信息(openid / unionid / oauth_id),见后端 `systems/auth/user.js` 的 `info()`
未绑定的处理(产品要求:只提示一次、可跳过、不阻断):
- 登录页展示绑定步骤(`components/wechat-bind-form/`),**可跳过**
- 跳过**不清 token**:仍是免登录态,下次打开小程序直接进首页,不重复提示登录
- 绑定入口常驻「我的」页(`isWechatUnbound` 为真时显示「待绑定 WMS 账号」卡片 + 弹窗绑定)
- 绑定成功:`wechat.bindUser` 换发正式 token(`user.id` = 真实账号 ID)并重拉 `user.info`
前端落点:`utils/wechat.ts`(原生能力 + 条件编译)、`api/user/user.ts`(两个接口)、
`store/modules/user.ts`(`wechatLogin` / `wechatBind` / `getInfo` / `isWechatUnbound`)、
`components/wechat-bind-form/`(绑定表单,登录页与「我的」页共用)、`components/login-panel/`(按钮)。
⚠️ 绑定状态的判定依据是 `user.info` 的 **`is_bound`**,不是 `wechat.loginByCode` 返回的 `user.id`
(后者只是签发那一刻的快照;已绑定用户的 `user.info` 里**没有** `is_bound` 字段,为 `undefined`)。
⚠️ 仅登录表单展示入口,且整段包在 `#ifdef MP-WEIXIN` 内(H5 产物中已剔除)。
- [x] **token 与登录态** ✅ - [x] **token 与登录态** ✅
统一存于 `utils/auth.ts`(小程序无 Cookie,故用 `uni.getStorageSync`,key = `token`)。 统一存于 `utils/auth.ts`(小程序无 Cookie,故用 `uni.getStorageSync`,key = `token`)。
@ -356,7 +383,9 @@ d:\wechat\
- [x] **登录入口与取消(微信审核要求,务必遵守)** ✅ - [x] **登录入口与取消(微信审核要求,务必遵守)** ✅
⚠️ **打开小程序不得直接跳登录页**,登录必须由用户主动触发: ⚠️ **打开小程序不得直接跳登录页**,登录必须由用户主动触发:
- 启动页 = 首页(`pages/index/index`),未登录可正常浏览 - 启动页 = 首页(`pages/index/index`),未登录可正常浏览
- 登录入口 = 「我的」页的「登录 / 注册」按钮(点头像区同样可进入) - 登录入口 = 「我的」页**头部的用户信息区**(未登录时文案「点击登录后使用完整功能」+ 右侧箭头;
点击就地弹登录抽屉)—— 不再放独立的「登录 / 注册」按钮
- 未绑定时点头部区直接打开绑定入口(各业务功能都不可用,这里最需要操作)
- 登录页有「取消」:页面栈有上一页则 `navigateBack` 返回来源页, - 登录页有「取消」:页面栈有上一页则 `navigateBack` 返回来源页,
否则退回 `redirect` 指定页 / 首页 否则退回 `redirect` 指定页 / 首页
- 登录成功:回跳 `redirect` 指定页(tabBar 页用 `switchTab`,其余用 `redirectTo`) - 登录成功:回跳 `redirect` 指定页(tabBar 页用 `switchTab`,其余用 `redirectTo`)
@ -542,7 +571,7 @@ d:\wechat\
| 入口树生成 | ✅ 已实现:`src/router/entries.ts` 的 `generateEntries()`;未命中路由表的菜单项忽略并计入 `missing`,分组无子项则整组丢弃,输出**固定两层** | | 入口树生成 | ✅ 已实现:`src/router/entries.ts` 的 `generateEntries()`;未命中路由表的菜单项忽略并计入 `missing`,分组无子项则整组丢弃,输出**固定两层** |
| `getInfo()` 触发时机 | ✅ 已收口:登录成功(`login()`)/ 启动带 token(`App.onLaunch`)/ 切换身份(`changeRole()`);`resetToken()` 联动清空权限 store | | `getInfo()` 触发时机 | ✅ 已收口:登录成功(`login()`)/ 启动带 token(`App.onLaunch`)/ 切换身份(`changeRole()`);`resetToken()` 联动清空权限 store |
| 三态渲染 | ✅ 已实现(阶段 3):页面用 `<auth-gate auth="...">` 包裹即可,页面内不再写 `if (isLogin)`;`usePageAuth()` 的 `auth` 参数可省略(自动按当前页从 `PAGE_REGISTRY` 取) | | 三态渲染 | ✅ 已实现(阶段 3):页面用 `<auth-gate auth="...">` 包裹即可,页面内不再写 `if (isLogin)`;`usePageAuth()` 的 `auth` 参数可省略(自动按当前页从 `PAGE_REGISTRY` 取) |
| 「去登录」唯一实现 | ✅ `usePageAuth.goLogin()`:复用 `LOGIN_PAGE` + 自动带 `redirect` 回本页;**未登录一律不自动跳转** | | 「去登录」唯一实现 | ✅ `usePageAuth.goLogin()`:**弹登录抽屉**(不跳页、不带 `redirect`);**未登录一律不自动跳转** |
| 本地公共入口 | `LOCAL_PUBLIC_ENTRIES`(`router/entries.ts`)= `auth === 'public' && !tabBar && !hidden`;当前为空数组 → 首页走空态文案(预期) | | 本地公共入口 | `LOCAL_PUBLIC_ENTRIES`(`router/entries.ts`)= `auth === 'public' && !tabBar && !hidden`;当前为空数组 → 首页走空态文案(预期) |
| 空态组件 | ✅ `components/empty-state/`:默认文案「服务器出差了,请稍后再试」+ 「重试」,可再挂一个「去登录」动作位 | | 空态组件 | ✅ `components/empty-state/`:默认文案「服务器出差了,请稍后再试」+ 「重试」,可再挂一个「去登录」动作位 |
| 可见性口径 | `isEntryVisible(meta) = !tabBar && !hidden`,**本地公共清单与后端菜单共用**(避免两处规则不一致) | | 可见性口径 | `isEntryVisible(meta) = !tabBar && !hidden`,**本地公共清单与后端菜单共用**(避免两处规则不一致) |
@ -563,6 +592,185 @@ d:\wechat\
--- ---
## 13. 扫码入口与场景参数(spm)
小程序被**扫码 / 链接 / 分享**唤起时,微信给的入口参数形态各不相同,必须在一层归一化后再分发。
实现:`src/utils/entry.ts`(解析)+ `src/router/scenes.ts`(分发)+ `composables/useEntryScene.ts`(消费)。
### 13.1 三种入口来源(都要处理,少一种就漏)
| 来源 | 参数位置 | 特点 |
|---|---|---|
| 扫普通链接二维码 | `options.q` | **URL 编码的完整路径**;要正则抠参,且「原文 / 解码后」**两个候选都要试** |
| 小程序码带参 | `options.scene` | **最长 31 字符**,约定 `k=v` 形式,需 `split('=')` 拆解 |
> ⚠️ **坑**:只能认 `options.query.scene`。`options.scene` 是微信的**场景值**(纯数字,如 1001 = 发现栏主入口、1011 = 扫描二维码),没有业务含义;把它当场景码会在启动时报「未识别的场景码:1001」。
| 分享 / 后台下发 | `options.xxx` 平铺 | 直接取;`options.page` 为服务端指定的落地页 |
### 13.2 spm 约定(与后端对齐用)
沿用 `G:\uni\数据`(shopro)的**点分段位**方案:全数字、位置表意、可无限往后加段。
```
spm = [userId].[scene].[code].[platform].[from].[extra...]
```
| 段 | 名称 | 本项语义 | 特殊值 |
|---|---|---|---|
| 第 1 段 | `userId` | 发起方用户 ID(PC / 工作台的操作账号) | `0` = 无 |
| 第 2 段 | **`scene`** | **场景码**(数字):`3`=打开页面 `4`=确认登录(`wechat.pushLoginCode`);`1`、`2`、`5`、`6`… 预留,后续继续编号 | — |
| 第 3 段 | `code` | **随机码**(登录码 / 绑定码)/ 业务标识 | `0` = 无 |
| 第 4 段 | `platform` | 渠道:`1`=H5 `2`=公众号 `3`=小程序 `4`=App | 同 shopro |
| 第 5 段 | `from` | 来源:`1`=直接转发 `2`=海报 `3`=链接 | 同 shopro |
| 第 6 段起 | `extra` | 预留扩展,按场景解释 | — |
- **全数字 + `0` 占位**:用不上的段填 `0`,参数最短(B 码 `scene` 上限 31 字符)
- `code` **约定不含 `.`**(否则破坏段位切分;base64 字符集 `A-Za-z0-9+/=` 是安全的)
- **新增场景只需在 `router/scenes.ts` 的 `SCENE_TABLE` 加一行**(继续编号),后端不用改格式
示例:`spm=0.4.989432.3.2`
= 无发起人 · **确认登录** · 登录码 `989432` · 小程序 · 二维码
### 13.3 时序(为什么「捕获」与「消费」要分开)
```mermaid
graph LR
A["App.onLaunch / onShow<br/>只捕获 + 暂存"] -->|storage| B["首页 onShow<br/>useEntryScene 消费"]
B --> C["解析场景 → 调接口 / 查表跳转"]
```
- 捕获点放在 App:`onLaunch` 时页面栈还没就绪,`navigateTo` 会失败
- **冷启动走 `onLaunch`,热启动(后台被扫码唤起)走 `onShow`** —— 两处都必须接
- 暂存用 storage 而非内存变量:热启动不经过 `onLaunch`,且 App / 页面的初始化顺序不可控
- 同一入口只消费一次(取出即清)
> ⚠️ 组合式 `onShow` 的类型声明**不带参数**(uni-app 类型未跟上微信的实际行为),
> `App.vue` 里做了一次类型断言 —— 见该文件注释。
### 13.4 场景 4「确认登录」流程(已实现)
⚠️ **扫码后不直接推送**:扫码是误触高发动作,直接把账号授权出去风险太大。
所以 spm 只负责**解析参数 + 跳页**,真正的授权由用户在确认页显式点击触发 —— **防误扫**。
这与 `G:\uni\数据`(shopro)的做法一致(它的 spm 也只解析参数 + `router.replace(page)`)。
```mermaid
graph TD
A["PC / 工作台<br/>展示二维码 spm=0.4.{登录码}"] --> B["用户微信扫码"]
B --> C["跳转确认页<br/>pages/login/confirm-login?code=xxx"]
C --> D{"已登录且已绑定?"}
D -->|是| E["展示「授权账号 + 登录码」<br/>用户点「确认授权登录」"]
D -->|否| F["提示先登录<br/>用户点「去登录」→ 弹抽屉"]
E --> G["wechat.pushLoginCode({code})"]
F --> H["暂存登录码<br/>→ 登录 / 绑定成功后自动补推送"] --> G
G --> I["后端标记 success + 记录当前账号"]
I --> J["PC / 工作台轮询取回 → 登录为该账号"]
```
关键实现点:
- 确认页 `pages/login/confirm-login`:`PAGE_REGISTRY` 登记为 `auth: 'public'` + `hidden`
(未登录也能进、页内引导登录,但不作为任何菜单入口)
- **不点「确认授权登录」→ 不会有任何推送**(防误扫的核心)
- **未登录 / 未绑定**时点「去登录」:**就地弹登录抽屉**(`showAuthModal('wechat')`),
不跳登录页 —— 本页是扫码「带进来」的,跳走之后要一路返回才能回来;抽屉关掉仍停留本页,
登录成功后 `canConfirm` 会自动变为 true
- 登录码先暂存(`utils/entry.ts` 的 `savePendingLoginCode`),登录 / 绑定成功后由 store 的
`flushPendingLoginCode()` **自动补推送**,用户无需回到确认页
- **自动补推送后不会重复引导**:`pushLoginCode` 成功会把码记到 store 的 `pushedLoginCode`,
页面据此切到「已授权」态;否则登录后 `isLogin` 变 true 会重新渲染出「确认授权登录」按钮,
而同一个码再推一次必然报「不存在或已过期」
- 失败态判定必须同时命中「登录码 + 过期/不存在」两个特征:否则未绑定时后端返回的
「用户不存在或已被删除」会误触发失败态
- `pushLoginCode` **需登录**(网关用 **HTTP 401** 表达),故 api 层为其关掉了 `redirectOn401`,
避免用户点一下就被踢到登录页;失败只 toast 后端原因
- 登录码 TTL:生成后 **300s**、确认后待领取 **120s**
(后端 `LOGIN_CODE_TTL_SECONDS` / `LOGIN_CODE_SUCCESS_TTL_SECONDS`)
- 接口只用已调通的两个:`wechat.pushLoginCode`(确认授权)、`wechat.getLoginWechatCode`(生成 / 轮询)
### 13.5 其它待办
- [ ] **扫码绑定**(`scene=2` 预留):现有 `wechat.bindUser` 走账号密码;`bindAccountByTempCode` 在**开放 API**
且需 `ye4s_user_id`(是 ye4s 后端对 WMS 的机对机调用)→ 小程序侧需后端补一个网关方法
- [ ] **个人中心「我的二维码」**(工作台扫描获取用户信息)—— 反向链路,待设计
---
## 14. 登录交互:半屏抽屉 + 接口级鉴权
### 14.1 为什么用抽屉而不是跳登录页
| | 跳登录页 | 半屏抽屉(现方案) |
|---|---|---|
| 触发 | 页面级拦截 / 401 跳转 | **碰到需要登录的接口 / 用户主动点按钮** |
| 浏览 | 被打断,登录完要回跳(`redirect`) | **不打断**,登录完留在原页面 |
| 状态 | 页面栈变化 | store 一个字段(`authView`) |
参照 `G:\uni\数据`(shopro):用**一个字段**既当开关又当视图选择器。
### 14.2 三层结构
| 层 | 位置 | 职责 |
|---|---|---|
| 状态 | `store/modules/user.ts`:`authView` + `showAuthModal()` / `closeAuthModal()` | `''` = 关闭;`'wechat' \| 'account' \| 'register'` = 打开并指定视图 |
| 容器 | `components/auth-modal/`(`up-popup mode="bottom"`) | 半屏抽屉;`v-if` 让每次打开**重新挂载**(视图与协议勾选自动复位) |
| 内容 | `components/login-panel/` | tab(**第一个是微信登录**)+ 协议勾选 + 注册视图 + 绑定步骤 |
**挂载**:uni-app 的 `App.vue` 没有模板 → 需在页面里各引一次 `<auth-modal />`
(当前:首页、「我的」、`pagesA/demo/required`、`pagesA/test/index`)。
⚠️ **原生 tabBar 必须手动藏**:微信小程序的 tabBar 是**原生组件**,层级恒在
`position: fixed` 之上 —— 抽屉弹出时会被它切掉一截(看起来没贴到屏幕底部),改 `z-index` 无效。
`App.vue` 里 watch `authVisible` → 打开时 `uni.hideTabBar()` / 关闭时 `uni.showTabBar()`
(非 tabBar 页面调用会 fail,用空 `fail` 吞掉);`onShow` 再兜底同步一次,
避免出现「抽屉已关、tabBar 没回来」。
### 14.3 接口级鉴权(“克制”的关键)
| 能力 | 实现 |
|---|---|
| 接口声明 | `RequestOptions.auth`:需登录的接口传 `true`(`user.info` / `user.changeRole` / `user.logout` / `wechat.pushLoginCode`) |
| 请求前预判 | `request.ts`:`auth && !token` → **不发请求**,直接弹抽屉(省一次无意义往返) |
| 响应兜底 | HTTP 401 / 业务码 401 → 清登录态 + **弹抽屉**(不再跳页) |
| 解耦 | `utils/auth-notify.ts`:request 层**发布**、`App.vue` **注册处理**(避开 `request → store → api → request` 循环依赖) |
| 中间态例外 | 微信绑定 / 确认登录传 `redirectOn401: false`:只提示,不清登录态、不弹抽屉 |
### 14.4 协议勾选
- 微信登录 / 账号登录 / **注册**都必须同意《用户须知》才能提交,否则 toast「请先阅读并同意《用户须知》」
- 每次打开抽屉**重新挂载** → 同意状态自动复位(**不记忆**,合规更稳)
- **勾选区任何位置(checkbox / 「我已阅读并同意」/《用户须知》)点击都只做一件事:打开须知弹窗** ——
不能直接打勾;勾只能在弹窗里「滑到底 + 点同意」之后才置上
- **必须滑到最底部才能同意**:靠 `scroll-view` 的 `scrolltolower` 到底才放行;
没到底时按钮呈灰态(`is-disabled`,仍可点,点了会 toast 说明原因)+ 橙色 ↓ 提示「请向下滑动阅读至底部」
- 内容不足一屏时(`.agreement__inner` 高度 ≤ `.agreement__body`)在打开后**自动算已读** ——
否则短文案永远触发不了 `scrolltolower`,用户会被卡在「点不了同意」上
- **已同意过**再打开则不要求再滑一遍(`agreementRead = agreed`)
- 文案是前端静态常量(`login-panel` 的 `AGREEMENT_TEXT`),后端下发时替换即可
(弹窗高度固定 460rpx + 内部滚动,文案变长变短都不用改结构)
### 14.5 登录页保留
`pages/login/login` 仍保留(401 兜底 + 直接访问),内容已精简为「全屏登录面板」
(与抽屉共用 `login-panel`),去掉了品牌区 / logo / 底部功能说明。
> 注:`usePageAuth` 的 `goLogin()` 已改为**弹抽屉**(不再跳页、不再带 `redirect`);
> `requlreLogin()` 仍先弹确认框(用户确认后再弹抽屉),保持“登录由用户主动触发”。
### 14.6 面板排版约定(`login-panel`)
| 元素 | 位置 / 处理 | 原因 |
|---|---|---|
| tab(微信登录 / 账号登录) | 头部**靠左** | 拇指热区,且关闭按钮独占右侧 |
| 关闭按钮 | 头部**靠右**(`showCancel` 时显示) | 符合系统弹窗习惯 |
| 取消按钮 | **已移除**底部取消,仅保留右上关闭 | 减少一屏内两个“退出”入口 |
| 账号密码表单 | **无 `label`**,只用 placeholder(`请输入账号` / `请输入密码`) | 省两行高度 |
| 注册表单 | **同样无 `label`**,5 个字段靠 placeholder + 左侧图标区分(`account` / `account-fill` / `email` / `lock` / `lock-fill`) | 省掉 5 行;label 是注册表单最大的一笔高度浪费 |
| 两个 tab 的高度 | `.login-panel__body { min-height: 370rpx }` + 居中 | 切换 tab 时抽屉高度不跳动(实测差 ≤2px) |
| 面板最大高度 | `.login-panel { max-height: 82vh; overflow-y: auto }` | 注册字段多,小屏(如 560px 高)下内部滚动,保证「注册」按钮与协议勾选始终可达 |
| 绑定时 | 头部显示标题(`绑定 WMS 账号` / `注册账号`)而非 tab;隐藏协议勾选与底部“注册账号”链接 | 绑定是**中间步骤**,不该给“换个方式登录”的出口 |
---
## 附录 A:常用命令 ## 附录 A:常用命令
| 命令 | 作用 | | 命令 | 作用 |