@bams-app/store 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/user.js ADDED
@@ -0,0 +1,197 @@
1
+ import { defineStore } from "pinia";
2
+ import useAuthStore from "./auth";
3
+ import useRuntimeEnvStore from "./runtimeEnv";
4
+ import useTabsStore from "./tabs.js";
5
+ import useMenuStore from "./menu.js";
6
+ import { dacApi } from "@bams-app/api-model";
7
+
8
+ export default defineStore("user", {
9
+ state: () => ({
10
+ // 用户id
11
+ userId: null,
12
+ // 用户名
13
+ userName: "",
14
+ // 手机号
15
+ phone: "",
16
+ // 组织名称
17
+ orgName: "",
18
+ // 组织编码
19
+ orgCode: "",
20
+ // 用户认证信息
21
+ token: null,
22
+ // 会话id
23
+ sessionId: null,
24
+ // 菜单类型
25
+ menuType: null,
26
+ // 账号id
27
+ accountId: null,
28
+ // 用户角色
29
+ role: "user",
30
+ // 页面权限码配置
31
+ permissionMap: { workId: ["meter:export", "meter:config", "user:view"] },
32
+ // 登录时间
33
+ loginTime: null,
34
+ // 其他扩展数据
35
+ data: null,
36
+ }),
37
+ getters: {
38
+ userInfo: state => ({
39
+ userId: state.userId,
40
+ userName: state.userName,
41
+ phone: state.phone,
42
+ orgName: state.orgName,
43
+ orgCode: state.orgCode,
44
+ token: state.token,
45
+ sessionId: state.sessionId,
46
+ menuType: state.menuType,
47
+ accountId: state.accountId,
48
+ role: state.role,
49
+ permissionMap: state.permissionMap,
50
+ loginTime: state.loginTime,
51
+ data: state.data,
52
+ }),
53
+ isLoggedIn: state => {
54
+ const authStore = useAuthStore();
55
+ return !!(state.token && state.sessionId && authStore.isLoggedIn);
56
+ },
57
+ // 是否登陆
58
+ // 计算属性:用户是否为管理员
59
+ isAdmin: state => state.role === "admin",
60
+ // 计算属性:用户显示名称
61
+ displayName: state => state.userName || "未登录用户",
62
+ // 计算属性:登录时长(分钟)
63
+ loginDuration: state => {
64
+ if (!state.loginTime) return 0;
65
+ const now = new Date();
66
+ const duration = now - new Date(state.loginTime);
67
+ return Math.floor(duration / (1000 * 60));
68
+ },
69
+ },
70
+ actions: {
71
+ // 登录操作
72
+ login(userData) {
73
+ const authStore = useAuthStore();
74
+ this.userId = userData.userId;
75
+ this.userName = userData.userName;
76
+ this.phone = userData.phone;
77
+ this.orgName = userData.orgName || "";
78
+ this.orgCode = userData.orgCode || "";
79
+ this.token = userData.token || null;
80
+ this.sessionId = userData.sessionId || null;
81
+ this.menuType = userData.menuType || null;
82
+ this.accountId = userData.accountId || null;
83
+ this.role = userData.role || "user";
84
+ this.permissionMap = userData.permissionMap || {};
85
+ this.loginTime = new Date().toISOString();
86
+ this.data = userData.data || null;
87
+
88
+ // 调用 authStore 同步到本地存储
89
+ if (this.token || this.sessionId) {
90
+ authStore.login({
91
+ token: this.token,
92
+ sessionId: this.sessionId
93
+ });
94
+ }
95
+
96
+ // 登录成功后清除历史页签持久化缓存,避免上一会话的页签被恢复到新会话
97
+ useTabsStore().removePersistedCaches();
98
+ // 登录成功后清除上一账号的菜单缓存,避免新账号复用旧菜单(菜单由后端按用户权限返回)
99
+ useMenuStore().removePersistedCaches();
100
+ },
101
+ // 清空用户信息(仅清理自身状态,不联动清理 auth/runtimeEnv)
102
+ clearUserState() {
103
+ this.userId = null;
104
+ this.userName = "";
105
+ this.phone = "";
106
+ this.orgName = "";
107
+ this.orgCode = "";
108
+ this.token = null;
109
+ this.sessionId = null;
110
+ this.menuType = null;
111
+ this.accountId = null;
112
+ this.role = "user";
113
+ this.permissionMap = {};
114
+ this.loginTime = null;
115
+ this.data = null;
116
+ },
117
+
118
+ // 登出操作
119
+ logout() {
120
+ const authStore = useAuthStore();
121
+ this.clearUserState();
122
+
123
+ // 调用 authStore 清除本地存储
124
+ authStore.logout();
125
+ // 清除运行时环境变量持久化缓存,便于下次登录时重新获取最新配置
126
+ // 仅清除缓存、保留内存 config:退出后立即整页跳转/刷新,保留内存值可避免标题在跳转前回退为构建默认值而闪烁
127
+ useRuntimeEnvStore().removePersistedCaches();
128
+ },
129
+ // 更新用户信息
130
+ updateProfile(profileData) {
131
+ const authStore = useAuthStore();
132
+ if (profileData.userName !== undefined) this.userName = profileData.userName;
133
+ if (profileData.phone !== undefined) this.phone = profileData.phone;
134
+ if (profileData.orgName !== undefined) this.orgName = profileData.orgName;
135
+ if (profileData.orgCode !== undefined) this.orgCode = profileData.orgCode;
136
+ if (profileData.token !== undefined) this.token = profileData.token;
137
+ if (profileData.sessionId !== undefined) this.sessionId = profileData.sessionId;
138
+ if (profileData.menuType !== undefined) this.menuType = profileData.menuType;
139
+ if (profileData.accountId !== undefined) this.accountId = profileData.accountId;
140
+ if (profileData.role !== undefined) this.role = profileData.role;
141
+ if (profileData.permissionMap !== undefined) this.permissionMap = profileData.permissionMap;
142
+ if (profileData.data !== undefined) this.data = profileData.data;
143
+
144
+ // 同步到 authStore
145
+ if (profileData.token !== undefined || profileData.sessionId !== undefined) {
146
+ authStore.login({
147
+ token: this.token,
148
+ sessionId: this.sessionId,
149
+ });
150
+ }
151
+ },
152
+ // 设置用户角色
153
+ setRole(newRole) {
154
+ this.role = newRole;
155
+ },
156
+ // 设置权限列表
157
+ setPermissions(permissionMap) {
158
+ this.permissionMap = permissionMap || {};
159
+ },
160
+
161
+ /**
162
+ * 校验鉴权状态并同步
163
+ * @returns {boolean}
164
+ */
165
+ checkAuth() {
166
+ const authStore = useAuthStore();
167
+ const isValid = authStore.checkAuth();
168
+ if (!isValid) {
169
+ this.clearUserState();
170
+ } else {
171
+ // 同步最新的 token/sessionId 到 state
172
+ this.token = authStore.token;
173
+ this.sessionId = authStore.sessionId;
174
+ }
175
+ return isValid;
176
+ },
177
+
178
+ /**
179
+ * 检查是否已登录 (校验本地凭证)
180
+ * @returns {boolean}
181
+ */
182
+ checkLogin() {
183
+ return this.checkAuth();
184
+ },
185
+
186
+ // 初始化store
187
+ init() {
188
+ this.checkAuth();
189
+ }
190
+ },
191
+ // 持久化存储配置
192
+ persist: {
193
+ key: "[bams-app]-user",
194
+ storage: localStorage, // 使用localStorage持久化
195
+ pick: ["userId", "accountId", "userName", "phone", "orgName", "orgCode", "token", "sessionId", "menuType", "role", "permissionMap", "loginTime", "data"], // 只持久化用户相关数据
196
+ },
197
+ });
@@ -0,0 +1,186 @@
1
+ /**
2
+ * 菜单工具函数
3
+ * @module menuUtils
4
+ * @description 提供菜单相关的通用工具函数
5
+ */
6
+
7
+ /**
8
+ * 递归查找菜单项
9
+ * @param {Array} menuList - 菜单列表
10
+ * @param {string} targetPath - 目标路径
11
+ * @param {Array} parentKeys - 父菜单key数组
12
+ * @returns {Object|null} 查找结果
13
+ */
14
+ export const findMenuItemByPath = (menuList, targetPath, parentKeys = []) => {
15
+ if (!Array.isArray(menuList) || menuList.length === 0) {
16
+ return null;
17
+ }
18
+
19
+ for (const menu of menuList) {
20
+ if (menu.path === targetPath) {
21
+ return {
22
+ selectedKey: menu.id,
23
+ openKeys: parentKeys
24
+ };
25
+ }
26
+ if (menu.children && Array.isArray(menu.children) && menu.children.length > 0) {
27
+ const result = findMenuItemByPath(menu.children, targetPath, [...parentKeys, menu.id]);
28
+ if (result) {
29
+ return result;
30
+ }
31
+ }
32
+ }
33
+ return null;
34
+ };
35
+
36
+ /**
37
+ * 递归查找菜单项 (通过 key)
38
+ * @param {Array} menuList - 菜单列表
39
+ * @param {string} targetKey - 目标 key
40
+ * @returns {Object|null} 查找结果
41
+ */
42
+ export const findMenuItemByKey = (menuList, targetKey) => {
43
+ if (!Array.isArray(menuList) || menuList.length === 0) {
44
+ return null;
45
+ }
46
+
47
+ for (const item of menuList) {
48
+ if (item.id === targetKey) {
49
+ return item;
50
+ }
51
+ if (item.children && Array.isArray(item.children) && item.children.length > 0) {
52
+ const found = findMenuItemByKey(item.children, targetKey);
53
+ if (found) {
54
+ return found;
55
+ }
56
+ }
57
+ }
58
+ return null;
59
+ };
60
+
61
+ /**
62
+ * 递归过滤菜单树:移除 isEnable 为 0(停用)的菜单节点及其整棵子树
63
+ * 仅当节点 isEnable 明确等于 0(数字或字符串)时移除;未返回该字段(undefined/null/空串)按启用处理
64
+ * @param {Array} menuList - 菜单列表
65
+ * @returns {Array} 过滤后的菜单列表
66
+ */
67
+ export const filterEnabledMenus = (menuList) => {
68
+ if (!Array.isArray(menuList)) {
69
+ return [];
70
+ }
71
+ return menuList
72
+ .filter(menu => Number(menu?.isEnable) !== 0)
73
+ .map(menu => {
74
+ if (menu.children && Array.isArray(menu.children)) {
75
+ return {
76
+ ...menu,
77
+ children: filterEnabledMenus(menu.children),
78
+ };
79
+ }
80
+ return menu;
81
+ });
82
+ };
83
+
84
+ /**
85
+ * 递归平铺菜单列表为 Map
86
+ * @param {Array} menuList - 菜单列表
87
+ * @param {string} keyField - 作为 Map key 的字段名,默认为 'id'
88
+ * @param {Object} acc - 累加器对象
89
+ * @returns {Object} 平铺后的 Map
90
+ */
91
+ export const flattenMenuToMap = (menuList, keyField = 'id', acc = {}) => {
92
+ if (!Array.isArray(menuList)) return acc;
93
+
94
+ for (const item of menuList) {
95
+ if (item[keyField]) {
96
+ acc[item[keyField]] = item;
97
+ }
98
+ if (item.children && Array.isArray(item.children)) {
99
+ flattenMenuToMap(item.children, keyField, acc);
100
+ }
101
+ }
102
+ return acc;
103
+ };
104
+
105
+ /**
106
+ * 递归查找父菜单
107
+ * @param {Array} menuList - 菜单列表
108
+ * @param {Object} targetItem - 目标菜单项
109
+ * @param {Array} parentPath - 父菜单路径
110
+ * @returns {Array|null} 查找结果
111
+ */
112
+ export const findParentMenu = (menuList, targetItem, parentPath = []) => {
113
+ if (!Array.isArray(menuList) || menuList.length === 0) {
114
+ return null;
115
+ }
116
+
117
+ for (const menu of menuList) {
118
+ if (menu.id === targetItem.id) {
119
+ return [...parentPath, menu];
120
+ }
121
+ if (menu.children && Array.isArray(menu.children) && menu.children.length > 0) {
122
+ const result = findParentMenu(menu.children, targetItem, [...parentPath, menu]);
123
+ if (result) {
124
+ return result;
125
+ }
126
+ }
127
+ }
128
+ return null;
129
+ };
130
+
131
+ /**
132
+ * 创建面包屑导航项
133
+ * @param {string} menuName - 菜单名称
134
+ * @param {string} path - 菜单路径
135
+ * @param {string} id - 菜单ID
136
+ * @returns {Object} 面包屑导航项
137
+ */
138
+ export const createBreadcrumbItem = (menuName, path, id) => ({
139
+ menuName,
140
+ path,
141
+ id
142
+ });
143
+
144
+ /**
145
+ * 格式化面包屑导航数据
146
+ * @param {Array} breadcrumbs - 面包屑导航数据
147
+ * @returns {Array} 格式化后的面包屑导航数据
148
+ */
149
+ export const formatBreadcrumbs = (breadcrumbs) => {
150
+ return breadcrumbs.map(item => createBreadcrumbItem(item.menuName, item.path, item.id));
151
+ };
152
+
153
+ /**
154
+ * 解析工作路由路径
155
+ * @description 根据路径规则 /{渠道}/{应用编码}/{work|render}/{默认} 解析应用信息
156
+ * @param {string} pathname - 路径名称
157
+ * @returns {Object} 解析结果 { appCode, appChannel, isWorkRouter }
158
+ */
159
+ export const parseWorkRouterPath = (pathname) => {
160
+ const result = {
161
+ appCode: '',
162
+ appChannel: '',
163
+ isWorkRouter: false
164
+ };
165
+
166
+ const keywords = ['work', 'render', 'anon'];
167
+ for (const keyword of keywords) {
168
+ if (pathname.includes(`/${keyword}/`)) {
169
+ const pathSegments = pathname.split('/').filter(segment => segment);
170
+ const keywordIndex = pathSegments.indexOf(keyword);
171
+
172
+ if (keywordIndex > 0) {
173
+ result.appCode = pathSegments[keywordIndex - 1];
174
+ }
175
+
176
+ if (keywordIndex > 1) {
177
+ result.appChannel = pathSegments[keywordIndex - 2];
178
+ }
179
+
180
+ result.isWorkRouter = true;
181
+ break;
182
+ }
183
+ }
184
+
185
+ return result;
186
+ };
@@ -0,0 +1,35 @@
1
+ /**
2
+ * 版本变化本地缓存清理工具
3
+ * @module versionCacheCleanup
4
+ * @description 监听"立即刷新"确认事件,仅在用户点击版本更新弹窗刷新按钮时清理指定 store 的本地持久化缓存,
5
+ * 避免旧版本缓存污染新版本页面(版本检测到变化时不清除)
6
+ */
7
+ import { onVersionRefresh } from "@bams-app/version-check";
8
+
9
+ // 已注册的持久化 key 集合:同一 key 只注册一次,避免模块重复执行(如 HMR)时重复清理
10
+ const registeredKeys = new Set();
11
+
12
+ /** 解析持久化 key:兼容字符串与返回 key 的函数(用于 appCode 等动态计算) */
13
+ const resolvePersistKey = getPersistKey =>
14
+ typeof getPersistKey === "function" ? getPersistKey() : getPersistKey;
15
+
16
+ /**
17
+ * 注册"立即刷新"确认事件的本地缓存清理
18
+ * @param {string|Function} getPersistKey - 持久化 key 字符串,或返回 key 的函数(如 () => `[bams-app]-menu-${appCode}`)
19
+ * @returns {Function} 取消监听函数
20
+ */
21
+ export function registerVersionChangeCleanup(getPersistKey) {
22
+ if (typeof localStorage === "undefined") return () => { };
23
+
24
+ // 惰性解析持久化 key:注册时不调用 getPersistKey(此时 pinia 可能尚未初始化,
25
+ // 动态取 appCode 会抛错),仅在实际清理时解析,保证 useAppStore() 等取值可用
26
+ const cleanup = () => {
27
+ const key = resolvePersistKey(getPersistKey);
28
+ // 同一 key 只清理一次,防止模块重复注册(如 HMR)导致重复清理
29
+ if (key && registeredKeys.has(key)) return;
30
+ if (key) registeredKeys.add(key);
31
+ if (key) localStorage.removeItem(key);
32
+ };
33
+
34
+ return onVersionRefresh(cleanup);
35
+ }
package/vite.config.js ADDED
@@ -0,0 +1,7 @@
1
+ import { defineConfig } from 'vite'
2
+ import vue from '@vitejs/plugin-vue'
3
+
4
+ // https://vite.dev/config/
5
+ export default defineConfig({
6
+ plugins: [vue()],
7
+ })