From 26af1a7039685344b2ea591cc28e63080c1b8893 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Tue, 31 Mar 2026 00:35:53 +0800 Subject: [PATCH] feat: refine setting role/account/permission auth and tests --- AI_TOOLBOX.md | 40 +- app/model/role.js | 10 + app/service/apiMethods/print.js | 345 ++++++ app/service/main.js | 136 ++- app/service/systemMethods/setting/account.js | 32 +- .../systemMethods/setting/permission.js | 60 + app/service/systemMethods/setting/role.js | 60 + app/service/systemMethods/user.js | 34 +- app/service/systems/auth/user.js | 1033 +++++++++++++---- app/service/systems/setting/account.js | 387 +++++- app/service/systems/setting/permission.js | 730 ++++++++++++ app/service/systems/setting/role.js | 669 +++++++++++ config/config.default.js | 1 + methods/gateway.json | 157 ++- methods/system.json | 942 ++++++++++++++- package.json | 1 + script/sync-system-api-permission.cjs | 254 ++++ stock.todo | 112 -- ...gateway.user.bindAccountByTempCode.test.js | 67 +- .../system.setting.permission.test.js | 234 ++++ .../system.user.getLoginWechatCode.test.js | 17 + .../system.user.loginByCode.test.js | 19 +- .../auth.user.bindWechatCacheExpiry.test.js | 152 +++ .../systems/auth.user.loginWechatCode.test.js | 103 ++ 24 files changed, 5108 insertions(+), 487 deletions(-) create mode 100644 app/service/apiMethods/print.js create mode 100644 app/service/systemMethods/setting/permission.js create mode 100644 app/service/systemMethods/setting/role.js create mode 100644 app/service/systems/setting/permission.js create mode 100644 app/service/systems/setting/role.js create mode 100644 script/sync-system-api-permission.cjs delete mode 100644 stock.todo create mode 100644 test/app/controller/system.setting.permission.test.js create mode 100644 test/app/controller/system.user.getLoginWechatCode.test.js create mode 100644 test/app/service/systems/auth.user.bindWechatCacheExpiry.test.js create mode 100644 test/app/service/systems/auth.user.loginWechatCode.test.js diff --git a/AI_TOOLBOX.md b/AI_TOOLBOX.md index 2ecaf48..9a25c13 100644 --- a/AI_TOOLBOX.md +++ b/AI_TOOLBOX.md @@ -1,6 +1,6 @@ # AI 工具箱(WMS) -本文件用于统一 AI 协助开发/调试时可直接使用的方法,减少重复沟通成本。 +本文件用于统一 AI 协助开发/调试时可直接使用的方法,减少重复沟通成本。AI每次应答文尾加喵~以判断是否丢失上下文 ## 1. 适用范围 @@ -591,4 +591,42 @@ npx egg-bin test test/app/controller/system.user.info.web.test.js test/app/contr - `print.getList` - `storage.entry.list` - `stock.warehouse.list` + +## 15. system API 权限映射规则(wms_permission) + +适用范围:`/system` 入口,权限类型为 `type=api`。 + +### 15.1 映射规则 + +- `wms_permission.path` 作为 system method 的权限标识(例如:`setting.account.list`)。 +- 同步来源以 `methods/system.json` 为准:`isNeedAuth=true` 的 method 必须存在对应 `wms_permission(type=api,path=method)`。 +- 新增权限后,必须在 `wms_role_permission` 绑定 `role_id=2`。 + +### 15.2 外部脚本(批量补齐) + +固定命令: + +```powershell +# 预览差异(不写库) +npm run permission:sync:system-api -- --dry-run + +# 执行补齐(写库) +npm run permission:sync:system-api +``` + +可选参数: + +- `--role-id=2`:绑定角色 ID(默认 `2`) +- `--db-client=wms`:数据库客户端名(默认 `wms`) +- `--config-path=./config/config.local.js`:配置文件路径 +- `--method-doc=./methods/system.json`:method 文档路径 + +### 15.3 运行时兜底(仅 debug) + +- 入口:`app/service/main.js` 的 `checkApiPermission`。 +- 逻辑:当用户权限列表不包含目标 method 时,若 `app.config.debug === true`,自动: + 1. 参考现有 `type=api` 权限行构建缺失权限行; + 2. 绑定 `wms_role_permission(role_id=2, permission_id=新权限ID)`。 +- 生产建议:保持 `app.config.debug=false`,避免运行时自动写库。 + \ No newline at end of file diff --git a/app/model/role.js b/app/model/role.js index 16d2af5..8138b00 100644 --- a/app/model/role.js +++ b/app/model/role.js @@ -117,6 +117,12 @@ module.exports = app => { allowNull: true, comment: '所属仓库ID', }, + pid: { + type: BIGINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '父级角色ID,顶级为0', + }, }, { tableName: 'wms_role', freezeTableName: true, @@ -143,6 +149,10 @@ module.exports = app => { name: 'idx_status', fields: [ 'status' ], }, + { + name: 'idx_pid', + fields: [ 'pid' ], + }, ], }); diff --git a/app/service/apiMethods/print.js b/app/service/apiMethods/print.js new file mode 100644 index 0000000..03ba646 --- /dev/null +++ b/app/service/apiMethods/print.js @@ -0,0 +1,345 @@ +'use strict'; + +const Service = require('egg').Service; +const crypto = require('node:crypto'); + +class PrintApiService extends Service { + getPrinterRedis() { + return this.app.redis.get('printer'); + } + + normalizeBindValue(bindValue) { + let bindValueObj = bindValue; + try { + bindValueObj = JSON.parse(bindValue); + } catch (_) { + bindValueObj = bindValue; + } + return bindValueObj; + } + + async getEmployeePermissions(employeeId) { + const { ctx } = this; + const roleRows = await ctx.model.EmployeeRole.findAll({ + attributes: [ 'role_id' ], + where: { + employee_id: employeeId, + }, + include: [ + { + model: ctx.model.Role, + as: 'role', + attributes: [], + where: { + status: 1, + }, + required: true, + }, + ], + raw: true, + }); + + if (!roleRows || roleRows.length === 0) { + return []; + } + + const roleIds = [ ...new Set(roleRows.map(item => item.role_id).filter(Boolean)) ]; + if (roleIds.length === 0) { + return []; + } + + const rolePermissionRows = await ctx.model.RolePermission.findAll({ + attributes: [ 'permission_id' ], + where: { + role_id: { + [ctx.app.Sequelize.Op.in]: roleIds, + }, + }, + raw: true, + }); + if (!rolePermissionRows || rolePermissionRows.length === 0) { + return []; + } + + const permissionIds = [ ...new Set(rolePermissionRows.map(item => item.permission_id).filter(Boolean)) ]; + if (permissionIds.length === 0) { + return []; + } + + const permissions = await ctx.model.Permission.findAll({ + attributes: [ 'path' ], + where: { + id: { + [ctx.app.Sequelize.Op.in]: permissionIds, + }, + status: 1, + type: 'api', + }, + raw: true, + }); + + return permissions.map(item => item.path).filter(Boolean); + } + + async getBindInfo(data = {}) { + const { ctx } = this; + const accountId = Number(data.account_id || data.accountId || data.wms_account_id || data.wmsAccountId); + const code = String(data.code || '').trim(); + + if (!Number.isFinite(accountId) || accountId <= 0 || !code) { + return { + success: false, + code: 0, + data: null, + message: '缺少有效参数 account_id 或 code', + }; + } + + const account = await ctx.model.Account.findOne({ + where: { id: accountId }, + attributes: [ 'id', 'status' ], + raw: true, + }); + if (!account || Number(account.status) !== 1) { + return { + success: false, + code: 0, + data: null, + message: '账号不存在或已禁用', + }; + } + + const redis = this.getPrinterRedis(); + const bindValue = await redis.get(`bind:${code}`); + if (!bindValue) { + return { + success: false, + code: 0, + data: null, + message: '无效code或未绑定', + }; + } + + const employeeRows = await ctx.model.AccountStoreEmployee.findAll({ + where: { + account_id: accountId, + status: 1, + }, + include: [ + { + model: ctx.model.Store, + as: 'store', + attributes: [ 'id', 'company_name', 'project', 'status', 'auth_end' ], + where: { + status: 1, + project: 'warehouse', + }, + required: true, + }, + ], + order: [[ 'created_at', 'DESC' ]], + }); + + const now = new Date(); + const warehouseMap = new Map(); + for (const employee of employeeRows) { + const permissions = await this.getEmployeePermissions(employee.id); + if (!permissions.includes('printer.bind')) { + continue; + } + + const store = employee.store; + if (!store) { + continue; + } + + if (store.auth_end && new Date(store.auth_end) < now) { + continue; + } + + warehouseMap.set(String(store.id), { + id: Number(store.id), + name: store.company_name, + }); + } + + const warehouses = Array.from(warehouseMap.values()); + if (warehouses.length === 0) { + return { + success: true, + code: 200, + data: { + warehouses: [], + }, + message: '无可绑定仓库', + }; + } + + const tempCode = crypto.randomBytes(16).toString('hex').toUpperCase(); + const tokenPayload = { + accountId, + code, + bindValue, + createdAt: new Date().toISOString(), + warehouses: warehouses.map(item => item.id), + }; + await redis.setex(`binding_token:${tempCode}`, 300, JSON.stringify(tokenPayload)); + + return { + success: true, + code: 200, + data: { + warehouses, + tempCode, + }, + message: '获取绑定信息成功', + }; + } + + async bindByTempCode(data = {}) { + const { ctx } = this; + const tempCode = String(data.temp_code || data.tempCode || '').trim(); + const printer = String(data.printer || data.workbench_name || data.workbenchName || '').trim(); + const warehouse = Number(data.warehouse || data.warehouse_id || data.warehouseId); + + if (!tempCode || !printer || !Number.isFinite(warehouse) || warehouse <= 0) { + return { + success: false, + code: 0, + data: null, + message: '参数缺失', + }; + } + + const redis = this.getPrinterRedis(); + const tokenText = await redis.get(`binding_token:${tempCode}`); + if (!tokenText) { + return { + success: false, + code: 0, + data: null, + message: '临时code无效或已过期', + }; + } + + let tokenData = null; + try { + tokenData = JSON.parse(tokenText); + } catch (_) { + tokenData = null; + } + + if (!tokenData || !tokenData.code || !Array.isArray(tokenData.warehouses)) { + return { + success: false, + code: 0, + data: null, + message: '临时code数据异常', + }; + } + + if (!tokenData.warehouses.includes(warehouse)) { + return { + success: false, + code: 0, + data: null, + message: '仓库无绑定权限', + }; + } + + const Store = ctx.model.Store; + const warehouseInfo = await Store.findOne({ + where: { + id: warehouse, + status: 1, + }, + raw: true, + }); + if (!warehouseInfo || warehouseInfo.project !== 'warehouse') { + return { + success: false, + code: 0, + data: null, + message: '仓库id校验失败', + }; + } + + const PrintComputer = ctx.model.PrintComputer; + let computerId = null; + const existComputer = await PrintComputer.findOne({ + where: { + warehouse_id: warehouse, + name: printer, + }, + }); + if (existComputer) { + if (Number(existComputer.status) === 1) { + return { + success: false, + code: 0, + data: null, + message: '该仓库下打印台名称已存在且可用', + }; + } + computerId = existComputer.id; + } else { + const newComputer = await PrintComputer.create({ + warehouse_id: warehouse, + name: printer, + status: 0, + }); + computerId = newComputer.id; + } + + const bindValueObj = this.normalizeBindValue(tokenData.bindValue); + const printServiceUrl = ctx.app.config.printService.url; + let printServiceResult = null; + try { + const res = await ctx.curl(`${printServiceUrl}/auth/bind`, { + method: 'POST', + contentType: 'json', + data: { + code: tokenData.code, + printer, + warehouse, + roomId: bindValueObj && bindValueObj.uniqueId ? bindValueObj.uniqueId : '', + computerId, + }, + dataType: 'json', + }); + printServiceResult = res.data; + } catch (err) { + printServiceResult = { success: false, error: '打印服务通讯失败' }; + } + + if (printServiceResult && printServiceResult.status === 'fail') { + return { + success: false, + code: 0, + data: { + printer, + warehouse, + printServiceResult, + }, + message: printServiceResult.message || '打印服务失败', + }; + } + + await redis.del(`binding_token:${tempCode}`); + + return { + success: true, + code: 200, + data: { + code: tokenData.code, + printer, + warehouse, + computerId, + printServiceResult, + }, + message: '绑定成功', + }; + } +} + +module.exports = PrintApiService; \ No newline at end of file diff --git a/app/service/main.js b/app/service/main.js index e0e518f..17f8439 100644 --- a/app/service/main.js +++ b/app/service/main.js @@ -337,13 +337,14 @@ class MainService extends Service { try { // 3. 验证JWT令牌 - const NewauthHeader = ''; const decoded = app.jwt.verify(token, app.config.jwt.secret); const now = Math.floor(Date.now() / 1000); const expiresIn = decoded.exp - now; if (expiresIn < 14399 && expiresIn > 0) { // 移除过期时间(exp)和签发时间(iat),保留其他payload - const { exp, iat, ...payload } = decoded; + const payload = { ...decoded }; + delete payload.exp; + delete payload.iat; // 生成新的 token,使用原来的有效时间配置 const newToken = app.jwt.sign( @@ -373,8 +374,7 @@ class MainService extends Service { return result; } - if (_noNeedAuth.indexOf('*') > -1 || _noNeedAuth.indexOf(actionName) > -1) { - } else { + if (!(_noNeedAuth.indexOf('*') > -1 || _noNeedAuth.indexOf(actionName) > -1)) { if (user.auth_end && new Date(user.auth_end) < new Date()) { result.status = 406; result.message = '仓库有效期已过期'; @@ -434,21 +434,139 @@ class MainService extends Service { } /** - * 检查用户是否有API访问权限(只检查类型为api的权限) + * debug 模式下确保 API 权限存在,并绑定到 role_id=2 + * @param {string} apiPath - API路径 + * @param {Object} user - 当前用户 + * @return {Promise<{ensured:boolean, permissionId:number|null}>} 同步结果 + */ + async ensureApiPermissionInDebugMode(apiPath, user = null) { + const { ctx, app } = this; + if (app.config.debug !== true) { + return { + ensured: false, + permissionId: null, + }; + } + + const normalizedPath = String(apiPath || '').trim(); + if (!normalizedPath) { + return { + ensured: false, + permissionId: null, + }; + } + + const template = await ctx.model.Permission.findOne({ + where: { + type: 'api', + }, + attributes: [ + 'component', + 'name', + 'redirect', + 'meta_title', + 'meta_icon', + 'hidden', + 'always_show', + 'parent_id', + 'sort', + 'status', + ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const [ permission, created ] = await ctx.model.Permission.findOrCreate({ + where: { + path: normalizedPath, + type: 'api', + }, + defaults: { + path: normalizedPath, + type: 'api', + component: template ? template.component : null, + name: template && template.name ? template.name : normalizedPath, + redirect: template ? template.redirect : null, + meta_title: template && template.meta_title ? template.meta_title : `API:${normalizedPath}`, + meta_icon: template ? template.meta_icon : null, + hidden: template ? template.hidden : 0, + always_show: template ? template.always_show : 0, + parent_id: template ? template.parent_id : null, + sort: template ? template.sort : 0, + status: 1, + }, + }); + + if (!permission || !permission.id) { + return { + ensured: false, + permissionId: null, + }; + } + + await ctx.model.RolePermission.findOrCreate({ + where: { + role_id: 2, + permission_id: permission.id, + }, + defaults: { + role_id: 2, + permission_id: permission.id, + }, + }); + + // 仅在新建权限时清理当前用户缓存,避免继续使用旧权限快照。 + if (created && user && user.id) { + await ctx.service.systems.auth.user.clearUserCache(user.id); + } + + return { + ensured: true, + permissionId: permission.id, + }; + } + + async hasRole2(employeeId) { + const { ctx } = this; + if (!employeeId) { + return false; + } + + const link = await ctx.model.EmployeeRole.findOne({ + where: { + employee_id: employeeId, + role_id: 2, + }, + attributes: [ 'id' ], + raw: true, + }); + + return !!link; + } + + /** + * 检查用户是否有 API 访问权限(只检查 type=api) * @param {Object} user - 用户信息 * @param {string} apiPath - API路径 - * @return {Promise} + * @return {Promise} 是否有权限 */ async checkApiPermission(user, apiPath) { - const { ctx } = this; - console.log(user); try { // 方法1: 从用户的权限列表中检查(如果已经加载了权限) if (user.permissions && Array.isArray(user.permissions)) { // 用户权限列表中可能包含所有权限,需要过滤出api权限 console.log('user.permissions', user.permissions); - return user.permissions.includes(apiPath); + if (user.permissions.includes(apiPath)) { + return true; + } + + const ensureResult = await this.ensureApiPermissionInDebugMode(apiPath, user); + if (!ensureResult.ensured) { + return false; + } + + return await this.hasRole2(user.employees_id); } return false; } catch (error) { diff --git a/app/service/systemMethods/setting/account.js b/app/service/systemMethods/setting/account.js index cf89f05..c8e8c6a 100644 --- a/app/service/systemMethods/setting/account.js +++ b/app/service/systemMethods/setting/account.js @@ -29,7 +29,37 @@ class accountService extends MainService { * @param {*} data */ async list(data = {}) { - return this.callSystemAccount('list', data, '获取工号列表失败'); + const { service } = this; + try { + this.prepareWhereContext(data, { + specialFieldMap: { + employee_id: { + field: 'id', + }, + account_id: { + field: 'account_id', + }, + username: { + field: '$account.username$', + }, + phone: { + field: '$account.phone$', + }, + email: { + field: '$account.email$', + }, + quickWhere: { + bucket: 'quick', + }, + }, + }); + const result = await service.systems.setting.account.list(data); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '获取工号列表失败', { + code: Number(error.code) || 500, + }); + } } /** diff --git a/app/service/systemMethods/setting/permission.js b/app/service/systemMethods/setting/permission.js new file mode 100644 index 0000000..4a62f92 --- /dev/null +++ b/app/service/systemMethods/setting/permission.js @@ -0,0 +1,60 @@ +'use strict'; + +const MainService = require('../../main'); + +class permissionService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list'; + const _noNeedLog = '*'; + const _noNeedAuth = 'list'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + async callSystemPermission(methodName, data, defaultMessage) { + const { service } = this; + try { + const result = await service.systems.setting.permission[methodName](data); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || defaultMessage, { + code: Number(error.code) || 500, + }); + } + } + + /** + * 权限列表。 + * @param {*} data + */ + async list(data = {}) { + return this.callSystemPermission('list', data, '获取权限列表失败'); + } + + /** + * 新增权限。 + * @param {*} data + */ + async add(data = {}) { + return this.callSystemPermission('add', data, '新增权限失败'); + } + + /** + * 删除权限。 + * @param {*} data + */ + async delete(data = {}) { + return this.callSystemPermission('delete', data, '删除权限失败'); + } + + /** + * 更新权限。 + * @param {*} data + */ + async update(data = {}) { + return this.callSystemPermission('update', data, '更新权限失败'); + } +} + +module.exports = permissionService; diff --git a/app/service/systemMethods/setting/role.js b/app/service/systemMethods/setting/role.js new file mode 100644 index 0000000..6f99764 --- /dev/null +++ b/app/service/systemMethods/setting/role.js @@ -0,0 +1,60 @@ +'use strict'; + +const MainService = require('../../main'); + +class roleService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,add,delete,update'; + const _noNeedLog = '*'; + const _noNeedAuth = 'list,add,delete,update'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + async callSystemRole(methodName, data, defaultMessage) { + const { service } = this; + try { + const result = await service.systems.setting.role[methodName](data); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || defaultMessage, { + code: Number(error.code) || 500, + }); + } + } + + /** + * 角色列表。 + * @param {*} data + */ + async list(data = {}) { + return this.callSystemRole('list', data, '获取角色列表失败'); + } + + /** + * 新增角色。 + * @param {*} data + */ + async add(data = {}) { + return this.callSystemRole('add', data, '新增角色失败'); + } + + /** + * 删除角色。 + * @param {*} data + */ + async delete(data = {}) { + return this.callSystemRole('delete', data, '删除角色失败'); + } + + /** + * 更新角色。 + * @param {*} data + */ + async update(data = {}) { + return this.callSystemRole('update', data, '更新角色失败'); + } +} + +module.exports = roleService; diff --git a/app/service/systemMethods/user.js b/app/service/systemMethods/user.js index efa3bc2..5987f1c 100644 --- a/app/service/systemMethods/user.js +++ b/app/service/systemMethods/user.js @@ -5,9 +5,9 @@ const MainService = require('../main'); class userService extends MainService { constructor(ctx) { super(ctx); - const _noNeedLogin = 'login,loginByCode,register'; + const _noNeedLogin = 'login,loginByCode,register,getLoginWechatCode'; const _noNeedRight = '*'; - const _noNeedLog = 'info,getBindWechatCode'; + const _noNeedLog = 'info,getBindWechatCode,getLoginWechatCode'; const _noNeedAuth = '*'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -33,28 +33,6 @@ class userService extends MainService { message: '缺少登录码 code', }); } - //code先进行base64解码,看是否为json以及json是否有uuid字段,如果有则继续执行否则返回报错 - let decoded; - try { - const buffer = Buffer.from(code, 'base64'); - const decodedStr = buffer.toString('utf-8'); - decoded = JSON.parse(decodedStr); - } catch (err) { - return this.fail('登录失败:无效的登录码格式', { - success: false, - data: null, - code: 0, - message: '无效的登录码格式', - }); - } - if (!decoded || typeof decoded !== 'object' || !decoded.uuid) { - return this.fail('登录失败:登录码缺少必要的uuid字段', { - success: false, - data: null, - code: 0, - message: '登录码缺少必要的uuid字段', - }); - } const result = await service.systems.auth.user.loginByCode(code); if (result.code) { return this.success('登录成功', result); @@ -69,6 +47,14 @@ class userService extends MainService { } return this.fail('获取绑定微信码失败:' + result.message, result); } + async getLoginWechatCode(data) { + const { service } = this; + const result = await service.systems.auth.user.getLoginWechatCode(data); + if (result.code) { + return this.success('获取微信登录码成功', result); + } + return this.fail('获取微信登录码失败:' + result.message, result); + } async unbindWechat(data) { const { service } = this; const result = await service.systems.auth.user.unbindWechat(data); diff --git a/app/service/systems/auth/user.js b/app/service/systems/auth/user.js index ea88807..c044344 100644 --- a/app/service/systems/auth/user.js +++ b/app/service/systems/auth/user.js @@ -5,10 +5,15 @@ const crypto = require('node:crypto'); const WECHAT_BIND_CACHE_PREFIX = 'user:wechat:bind:'; const WECHAT_BIND_CODE_CACHE_PREFIX = 'user:wechat:bind:code:'; -const WECHAT_BIND_CACHE_TTL_SECONDS = 600; -const WECHAT_BIND_RECHECK_INTERVAL_MS = 5000; +const WECHAT_BIND_SCAN_CACHE_PREFIX = 'user:wechat:bind:scan:'; +const WECHAT_BIND_CACHE_TTL_SECONDS = 60; +const WECHAT_BIND_SCAN_CACHE_TTL_SECONDS = 180; const WECHAT_BIND_EVENT_CHANNEL_PREFIX = 'user:wechat:bind:event:'; const WECHAT_BIND_LONG_POLL_TIMEOUT_MS = 60000; +const WECHAT_LOGIN_CLIENT_CACHE_PREFIX = 'user:wechat:login:client:'; +const WECHAT_LOGIN_CODE_CACHE_PREFIX = 'user:wechat:login:code:'; +const WECHAT_LOGIN_EVENT_CHANNEL_PREFIX = 'user:wechat:login:event:'; +const WECHAT_LOGIN_CACHE_TTL_SECONDS = 60; class UserService extends Service { constructor(ctx) { @@ -33,45 +38,114 @@ class UserService extends Service { return `${WECHAT_BIND_CODE_CACHE_PREFIX}${code}`; } - createWechatBindCode() { - const payload = { - uuid: `${Date.now().toString(36)}-${crypto.randomBytes(8).toString('hex')}`, - }; - return Buffer.from(JSON.stringify(payload), 'utf8').toString('base64'); + getWechatBindScanCacheKey(code) { + return `${WECHAT_BIND_SCAN_CACHE_PREFIX}${code}`; + } + + getWechatLoginClientCacheKey(clientCode) { + return `${WECHAT_LOGIN_CLIENT_CACHE_PREFIX}${clientCode}`; + } + + getWechatLoginCodeCacheKey(code) { + return `${WECHAT_LOGIN_CODE_CACHE_PREFIX}${code}`; + } + + getWechatLoginEventChannel(clientCode) { + return `${WECHAT_LOGIN_EVENT_CHANNEL_PREFIX}${clientCode}`; + } + + createWechatBindCodeCandidate() { + const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + let code = ''; + for (let i = 0; i < 6; i++) { + const index = crypto.randomInt(0, charset.length); + code += charset[index]; + } + return code; + } + + async createUniqueSixCode(getCacheKey, maxAttempts = 200) { + for (let attempt = 0; attempt < maxAttempts; attempt++) { + const code = this.createWechatBindCodeCandidate(); + if (!this.parseWechatBindCode(code)) { + continue; + } + + const cacheKey = getCacheKey(code); + const existsState = await this.app.getCacheAsync(cacheKey); + if (!existsState) { + return code; + } + } + + throw new Error('生成登录码失败,请稍后重试'); + } + + async createWechatBindCode(maxAttempts = 200) { + return await this.createUniqueSixCode(this.getWechatBindCodeCacheKey.bind(this), maxAttempts); + } + + async createWechatLoginCode(maxAttempts = 200) { + return await this.createUniqueSixCode(this.getWechatLoginCodeCacheKey.bind(this), maxAttempts); + } + + async createWechatLoginClientCode(maxAttempts = 200) { + return await this.createUniqueSixCode(this.getWechatLoginClientCacheKey.bind(this), maxAttempts); } parseWechatBindCode(code) { - if (!code) { + const normalized = typeof code === 'string' ? code.trim().toUpperCase() : ''; + if (!normalized) { return null; } - try { - const decodedStr = Buffer.from(code, 'base64').toString('utf8'); - const parsed = JSON.parse(decodedStr); - if (!parsed || typeof parsed !== 'object' || !parsed.uuid) { - return null; - } - return parsed; - } catch (error) { + if (!/^[A-Z0-9]{6}$/.test(normalized)) { return null; } + if (!/[A-Z]/.test(normalized) || !/[0-9]/.test(normalized)) { + return null; + } + + return normalized; } formatBindWechatData(state, source = 'db') { - const nextCheckAt = Number(state.next_db_check_at || 0); + const expiresAt = Number(state.expires_at || 0); return { account_id: state.account_id, code: state.code || '', status: state.status || 'pending', is_bound: state.status === 'bound', updated_at: state.updated_at || new Date().toISOString(), - next_db_check_at: nextCheckAt, - next_poll_after_ms: Math.max(0, nextCheckAt - Date.now()), + expires_at: expiresAt > 0 ? expiresAt : null, + expire_after_ms: expiresAt > 0 ? Math.max(0, expiresAt - Date.now()) : 0, + scanned_at: state.scanned_at || null, source, ye4s_user_id: state.ye4s_user_id || null, }; } + formatLoginWechatData(state, source = 'cache') { + const expiresAt = Number(state.expires_at || 0); + return { + client_code: state.client_code || '', + code: state.code || '', + status: state.status || 'pending', + updated_at: state.updated_at || new Date().toISOString(), + expires_at: expiresAt > 0 ? expiresAt : null, + expire_after_ms: expiresAt > 0 ? Math.max(0, expiresAt - Date.now()) : 0, + source, + }; + } + + getRemainingSecondsByExpiresAt(expiresAt, fallbackTtl = WECHAT_BIND_CACHE_TTL_SECONDS) { + const ts = Number(expiresAt); + if (!Number.isFinite(ts) || ts <= 0) { + return fallbackTtl; + } + return Math.max(1, Math.ceil((ts - Date.now()) / 1000)); + } + async setWechatBindCache(cacheKey, state, ttl = WECHAT_BIND_CACHE_TTL_SECONDS) { await this.app.setCacheAsync(cacheKey, state, ttl); } @@ -84,6 +158,38 @@ class UserService extends Service { await this.app.setCacheAsync(codeCacheKey, state, ttl); } + async setWechatBindScanCache(code, state, ttl = WECHAT_BIND_SCAN_CACHE_TTL_SECONDS) { + if (!code) { + return; + } + const scanCacheKey = this.getWechatBindScanCacheKey(code); + await this.app.setCacheAsync(scanCacheKey, state, ttl); + } + + async getWechatBindScanCache(code) { + if (!code) { + return null; + } + const scanCacheKey = this.getWechatBindScanCacheKey(code); + return await this.app.getCacheAsync(scanCacheKey); + } + + async setWechatLoginClientCache(clientCode, state, ttl = WECHAT_LOGIN_CACHE_TTL_SECONDS) { + if (!clientCode) { + return; + } + const clientCacheKey = this.getWechatLoginClientCacheKey(clientCode); + await this.app.setCacheAsync(clientCacheKey, state, ttl); + } + + async setWechatLoginCodeCache(code, state, ttl = WECHAT_LOGIN_CACHE_TTL_SECONDS) { + if (!code) { + return; + } + const codeCacheKey = this.getWechatLoginCodeCacheKey(code); + await this.app.setCacheAsync(codeCacheKey, state, ttl); + } + async findYe4sBindingByAccountId(accountId) { const { ctx } = this; const ye4sClient = ctx.app.mysql.get('ye4s'); @@ -105,27 +211,16 @@ class UserService extends Service { return `${WECHAT_BIND_EVENT_CHANNEL_PREFIX}${accountId}`; } - getWechatLongPollTimeoutMs(rawTimeoutMs) { - const timeoutMs = Number(rawTimeoutMs); - if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) { - return WECHAT_BIND_LONG_POLL_TIMEOUT_MS; + getWechatLongPollTimeoutMs(timeoutMs = WECHAT_BIND_LONG_POLL_TIMEOUT_MS) { + const waitMs = Number(timeoutMs); + if (Number.isFinite(waitMs) && waitMs > 0) { + return Math.floor(waitMs); } - return Math.min(timeoutMs, WECHAT_BIND_LONG_POLL_TIMEOUT_MS); + return WECHAT_BIND_LONG_POLL_TIMEOUT_MS; } - shouldUseWechatBindLongPoll(data = {}, state = null) { - if (!state || state.status === 'bound') { - return false; - } - if (data.forceRefresh) { - return false; - } - if (data.isInit === true || data.init === true || data.firstLoad === true) { - return false; - } - - const explicitEnable = data.longPoll === true || data.waitForChange === true; - return explicitEnable; + shouldUseWechatBindLongPoll(data = {}) { + return data.longPoll === true; } async publishWechatBindEvent(accountId, payload = {}) { @@ -246,62 +341,99 @@ class UserService extends Service { }); } - async refreshWechatBindState(accountId, cachedState = null) { + async refreshWechatBindState(accountId, cachedState = null, options = {}) { const now = Date.now(); const cacheKey = this.getWechatBindCacheKey(accountId); + const forceNewCode = options.forceNewCode === true; const ye4sBinding = await this.findYe4sBindingByAccountId(accountId); if (ye4sBinding) { - const dbCode = typeof ye4sBinding.tmp_code === 'string' ? ye4sBinding.tmp_code.trim() : ''; - const bindState = { + const boundState = { account_id: accountId, status: 'bound', - code: dbCode || (cachedState && cachedState.code) || this.createWechatBindCode(), + code: '', updated_at: new Date().toISOString(), - next_db_check_at: now + WECHAT_BIND_RECHECK_INTERVAL_MS, ye4s_user_id: ye4sBinding.id || null, + expires_at: null, + scanned_at: null, }; - await Promise.all([ - this.setWechatBindCache(cacheKey, bindState, WECHAT_BIND_CACHE_TTL_SECONDS), - this.setWechatBindCodeCache(bindState.code, bindState, WECHAT_BIND_CACHE_TTL_SECONDS), - ]); + await this.setWechatBindCache(cacheKey, boundState, WECHAT_BIND_CACHE_TTL_SECONDS); - const hasChanged = !cachedState || cachedState.status !== 'bound' || cachedState.code !== bindState.code; + const hasChanged = !cachedState || cachedState.status !== 'bound' || Number(cachedState.ye4s_user_id || 0) !== Number(boundState.ye4s_user_id || 0); if (hasChanged) { await this.publishWechatBindEvent(accountId, { status: 'bound', - code: bindState.code, + code: '', source: 'db', }); } return { - state: bindState, + state: boundState, source: 'db', message: '账号已绑定微信', }; } - const code = (cachedState && cachedState.code) || this.createWechatBindCode(); + const cachedCode = cachedState && typeof cachedState.code === 'string' ? cachedState.code.trim().toUpperCase() : ''; + let codeState = null; + if (!forceNewCode && cachedCode && this.parseWechatBindCode(cachedCode)) { + const codeCacheKey = this.getWechatBindCodeCacheKey(cachedCode); + codeState = await this.app.getCacheAsync(codeCacheKey); + } + + const codeAccountId = Number(codeState && codeState.account_id); + const cachedExpiresAt = Number((codeState && codeState.expires_at) || (cachedState && cachedState.expires_at)); + const cachedCodeValid = !forceNewCode && cachedCode && this.parseWechatBindCode(cachedCode) && Number.isFinite(codeAccountId) && codeAccountId === accountId && (Number.isFinite(cachedExpiresAt) ? cachedExpiresAt > now : !!codeState); + + if (cachedCodeValid) { + const scanState = await this.getWechatBindScanCache(cachedCode); + const normalizedStatus = scanState ? 'scanned' : 'pending'; + const state = { + account_id: accountId, + status: normalizedStatus, + code: cachedCode, + updated_at: cachedState.updated_at || new Date().toISOString(), + ye4s_user_id: null, + expires_at: Number.isFinite(cachedExpiresAt) ? cachedExpiresAt : null, + scanned_at: scanState && scanState.scanned_at ? scanState.scanned_at : null, + }; + return { + state, + source: 'cache', + message: normalizedStatus === 'scanned' ? '二维码已被扫码,请继续绑定' : '获取绑定码成功(缓存)', + }; + } + + const nextCode = await this.createWechatBindCode(); + const expiresAt = now + WECHAT_BIND_CACHE_TTL_SECONDS * 1000; const pendingState = { account_id: accountId, status: 'pending', - code, + code: nextCode, updated_at: new Date().toISOString(), - next_db_check_at: now + WECHAT_BIND_RECHECK_INTERVAL_MS, ye4s_user_id: null, + expires_at: expiresAt, + scanned_at: null, }; - await Promise.all([ + const tasks = [ this.setWechatBindCache(cacheKey, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS), - this.setWechatBindCodeCache(pendingState.code, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS), - ]); + this.setWechatBindCodeCache(nextCode, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS), + ]; + + if (cachedCode && cachedCode !== nextCode) { + tasks.push(this.setWechatBindCodeCache(cachedCode, null, 1)); + tasks.push(this.setWechatBindScanCache(cachedCode, null, 1)); + } + + await Promise.all(tasks); return { state: pendingState, - source: code === (cachedState && cachedState.code) ? 'cache-refresh' : 'generated', - message: '账号未绑定,已生成绑定码', + source: forceNewCode ? 'refreshed' : 'generated', + message: forceNewCode ? '长轮询超时,已刷新绑定码' : '账号未绑定,已生成绑定码', }; } @@ -361,75 +493,77 @@ class UserService extends Service { } /** - * 登录码登录:使用 ye4s_user.tmp_code 绑定的 wms_account_id 登录 - * @param {string} code 登录码(ye4s_user.tmp_code) + * 登录码登录:使用本系统缓存登录码完成登录 + * @param {string} code 登录码(WECHAT_LOGIN_CODE) * @return {Object} 登录结果 */ async loginByCode(code) { - const { ctx, app } = this; + const { app } = this; try { - const normalizedCode = typeof code === 'string' ? code.trim() : ''; + const normalizedCode = this.parseWechatBindCode(code); if (!normalizedCode) { return { success: false, data: null, code: 0, - message: '缺少登录码 code', - }; - } - - const ye4sClient = ctx.app.mysql.get('ye4s'); - const ye4sUser = await ye4sClient.get('ye4s_user', { - tmp_code: normalizedCode, - }); - - if (!ye4sUser) { - return { - success: false, - data: null, - code: 0, - message: '登录码不存在', - }; - } - - const wmsAccountId = Number(ye4sUser.wms_account_id); - if (!Number.isFinite(wmsAccountId) || wmsAccountId <= 0) { - return { - success: false, - data: null, - code: 0, - message: '该登录码未绑定WMS账号', - }; - } - - const user = await ctx.model.Account.findOne({ - where: { id: wmsAccountId }, - }); - - if (!user) { - return { - success: false, - data: null, - code: 0, - message: '绑定的WMS账号不存在', + message: '缺少或无效的登录码 code', }; } + const codeCacheKey = this.getWechatLoginCodeCacheKey(normalizedCode); + let codeState = null; try { - this.checkUserStatus(user); - } catch (statusError) { - app.coreLogger.warn(`登录码登录失败: 账号状态异常 [${user.id}] - ${statusError.message}`); + codeState = await this.app.getCacheAsync(codeCacheKey); + } catch (cacheErr) { + app.coreLogger.warn(`读取登录码缓存失败: ${cacheErr.message}`); + } + + if (!codeState) { return { success: false, data: null, code: 0, - message: '绑定账号状态异常', + message: '登录码不存在或已过期', }; } - await this.updateLastLoginTime(user.id); - return this.buildLoginResult(user); + const codeStateWithCode = { + ...(codeState || {}), + code: normalizedCode, + }; + + let loginResponse = await this.tryBuildWechatLoginTokenFromState(codeState.client_code || '', codeStateWithCode); + if (loginResponse && loginResponse.success) { + return loginResponse; + } + + const clientCode = this.parseWechatBindCode(codeState && codeState.client_code); + if (clientCode) { + let clientState = null; + try { + clientState = await this.app.getCacheAsync(this.getWechatLoginClientCacheKey(clientCode)); + } catch (cacheErr) { + app.coreLogger.warn(`读取客户端登录状态缓存失败: ${cacheErr.message}`); + } + + if (clientState) { + loginResponse = await this.tryBuildWechatLoginTokenFromState(clientCode, { + ...clientState, + code: normalizedCode, + }); + if (loginResponse && loginResponse.success) { + return loginResponse; + } + } + } + + return { + success: false, + data: null, + code: 0, + message: '登录码尚未授权,请扫码确认后重试', + }; } catch (error) { app.coreLogger.error(`登录码登录异常: ${error.message}`); return { @@ -441,6 +575,447 @@ class UserService extends Service { } } + async waitForLoginCodeRefresh(timeoutMs = WECHAT_BIND_LONG_POLL_TIMEOUT_MS) { + const waitMs = this.getWechatLongPollTimeoutMs(timeoutMs); + await new Promise(resolve => { + setTimeout(resolve, waitMs); + }); + } + + isTransientWechatLoginError(error) { + if (!error) { + return false; + } + const code = typeof error.code === 'string' ? error.code : ''; + const message = typeof error.message === 'string' ? error.message.toLowerCase() : ''; + const transientCodes = new Set([ 'ECONNRESET', 'ETIMEDOUT', 'EPIPE', 'PROTOCOL_CONNECTION_LOST', 'ECONNREFUSED' ]); + if (transientCodes.has(code)) { + return true; + } + return message.includes('econnreset') || message.includes('read econnreset') || message.includes('connection lost') || message.includes('timeout'); + } + + extractYe4sUserIdFromLoginEvent(eventData) { + if (!eventData) { + return null; + } + + if (typeof eventData === 'number' || typeof eventData === 'string') { + const id = Number(eventData); + return Number.isFinite(id) && id > 0 ? id : null; + } + + if (typeof eventData !== 'object') { + return null; + } + + const rawId = eventData.ye4s_user_id ?? eventData.ye4sUserId ?? eventData.user_id ?? eventData.userId ?? eventData.value; + const ye4sUserId = Number(rawId); + return Number.isFinite(ye4sUserId) && ye4sUserId > 0 ? ye4sUserId : null; + } + + async waitForWechatLoginEvent(clientCode, timeoutMs = WECHAT_BIND_LONG_POLL_TIMEOUT_MS) { + const { app } = this; + const normalizedClientCode = this.parseWechatBindCode(clientCode); + const cacheRedis = app.redis && app.redis.get ? app.redis.get('cache') : null; + if (!cacheRedis || !normalizedClientCode || typeof cacheRedis.duplicate !== 'function') { + return { + timed_out: true, + reason: 'redis_not_available', + event: null, + }; + } + + const channel = this.getWechatLoginEventChannel(normalizedClientCode); + const waitMs = this.getWechatLongPollTimeoutMs(timeoutMs); + const subscriber = cacheRedis.duplicate(); + + return await new Promise(resolve => { + let settled = false; + let timer = null; + + const cleanup = () => { + subscriber.removeListener('message', onMessage); + subscriber.removeListener('error', onError); + Promise.resolve(subscriber.unsubscribe(channel)).catch(() => null).finally(() => { + if (typeof subscriber.quit === 'function') { + Promise.resolve(subscriber.quit()).catch(() => { + if (typeof subscriber.disconnect === 'function') { + subscriber.disconnect(); + } + }); + return; + } + if (typeof subscriber.disconnect === 'function') { + subscriber.disconnect(); + } + }); + }; + + const finalize = result => { + if (settled) { + return; + } + settled = true; + if (timer) { + clearTimeout(timer); + } + cleanup(); + resolve(result); + }; + + const onMessage = (messageChannel, message) => { + if (messageChannel !== channel) { + return; + } + let eventData = null; + try { + eventData = message ? JSON.parse(message) : null; + } catch (error) { + eventData = message; + } + const ye4sUserId = this.extractYe4sUserIdFromLoginEvent(eventData); + finalize({ + timed_out: false, + reason: 'event', + event: eventData, + ye4s_user_id: ye4sUserId, + }); + }; + + const onError = error => { + app.coreLogger.warn(`订阅微信登录事件失败: ${error.message}`); + finalize({ + timed_out: true, + reason: 'subscribe_error', + event: null, + }); + }; + + timer = setTimeout(() => { + finalize({ + timed_out: true, + reason: 'timeout', + event: null, + }); + }, waitMs); + + subscriber.on('message', onMessage); + subscriber.on('error', onError); + + Promise.resolve(subscriber.subscribe(channel)).catch(error => { + app.coreLogger.warn(`订阅微信登录频道失败: ${error.message}`); + finalize({ + timed_out: true, + reason: 'subscribe_failed', + event: null, + }); + }); + }); + } + + async loginByYe4sUserId(ye4sUserId) { + const { ctx, app } = this; + + const normalizedYe4sUserId = Number(ye4sUserId); + if (!Number.isFinite(normalizedYe4sUserId) || normalizedYe4sUserId <= 0) { + return { + success: false, + code: 0, + data: null, + message: '登录事件缺少有效的 ye4s_user_id', + }; + } + + const maxAttempts = 2; + for (let attempt = 1; attempt <= maxAttempts; attempt++) { + try { + const ye4sClient = ctx.app.mysql.get('ye4s'); + const ye4sUser = await ye4sClient.get('ye4s_user', { id: normalizedYe4sUserId }); + if (!ye4sUser) { + return { + success: false, + code: 0, + data: null, + message: 'ye4s 用户不存在', + }; + } + + const wmsAccountId = Number(ye4sUser.wms_account_id); + if (!Number.isFinite(wmsAccountId) || wmsAccountId <= 0) { + return { + success: false, + code: 0, + data: null, + message: '该 ye4s 用户未绑定WMS账号', + }; + } + + const user = await ctx.model.Account.findOne({ + where: { id: wmsAccountId }, + }); + + if (!user) { + return { + success: false, + code: 0, + data: null, + message: '绑定的WMS账号不存在', + }; + } + + try { + this.checkUserStatus(user); + } catch (statusError) { + app.coreLogger.warn(`微信事件登录失败: 账号状态异常 [${user.id}] - ${statusError.message}`); + return { + success: false, + code: 0, + data: null, + message: '绑定账号状态异常', + }; + } + + await this.updateLastLoginTime(user.id); + const loginResult = await this.buildLoginResult(user, { includeUser: false }); + return loginResult; + } catch (error) { + const isTransient = this.isTransientWechatLoginError(error); + if (isTransient && attempt < maxAttempts) { + app.coreLogger.warn(`微信事件登录异常,准备重试(${attempt}/${maxAttempts}): ${error.message}`); + await this.waitForLoginCodeRefresh(200); + continue; + } + + app.coreLogger.error(`微信事件登录异常: ${error.message}`); + return { + success: false, + code: 0, + data: null, + message: '登录失败,请稍后重试', + }; + } + } + + return { + success: false, + code: 0, + data: null, + message: '登录失败,请稍后重试', + }; + } + + async tryBuildWechatLoginTokenFromState(clientCode, state) { + const eventYe4sUserId = this.extractYe4sUserIdFromLoginEvent(state); + if (!Number.isFinite(Number(eventYe4sUserId)) || Number(eventYe4sUserId) <= 0) { + return null; + } + + const loginResult = await this.loginByYe4sUserId(eventYe4sUserId); + if (!loginResult || !loginResult.success || !loginResult.data || !loginResult.data.token) { + return { + success: false, + code: 0, + data: null, + message: loginResult && loginResult.message ? loginResult.message : '登录事件处理失败', + }; + } + + const cleanupCode = state && typeof state.code === 'string' ? state.code.trim().toUpperCase() : ''; + await Promise.all([ + this.setWechatLoginClientCache(clientCode, null, 1), + cleanupCode ? this.setWechatLoginCodeCache(cleanupCode, null, 1) : Promise.resolve(), + ]); + + return { + success: true, + code: 200, + data: { + client_code: clientCode, + status: 'authorized', + source: 'event', + ye4s_user_id: Number(eventYe4sUserId), + loginToken: loginResult.data.token, + }, + message: '已收到登录事件并签发登录令牌', + }; + } + + async refreshWechatLoginState(clientCode, cachedState = null, options = {}) { + const now = Date.now(); + const forceNewCode = options.forceNewCode === true; + const normalizedClientCode = this.parseWechatBindCode(clientCode); + + if (!normalizedClientCode) { + throw new Error('无效的客户端编码格式'); + } + + const cachedCode = cachedState && typeof cachedState.code === 'string' ? cachedState.code.trim().toUpperCase() : ''; + const cachedExpiresAt = Number(cachedState && cachedState.expires_at); + const cachedCodeValid = !forceNewCode && cachedCode && this.parseWechatBindCode(cachedCode) && Number.isFinite(cachedExpiresAt) && cachedExpiresAt > now; + + if (cachedCodeValid) { + return { + state: { + client_code: normalizedClientCode, + code: cachedCode, + status: 'pending', + updated_at: cachedState.updated_at || new Date().toISOString(), + expires_at: cachedExpiresAt, + }, + source: 'cache', + message: `客户端编码 ${normalizedClientCode} 已命中缓存登录码`, + }; + } + + const nextCode = await this.createWechatLoginCode(); + const expiresAt = now + WECHAT_LOGIN_CACHE_TTL_SECONDS * 1000; + const loginState = { + client_code: normalizedClientCode, + code: nextCode, + status: 'pending', + updated_at: new Date().toISOString(), + expires_at: expiresAt, + }; + + const tasks = [ + this.setWechatLoginClientCache(normalizedClientCode, loginState, WECHAT_LOGIN_CACHE_TTL_SECONDS), + this.setWechatLoginCodeCache(nextCode, loginState, WECHAT_LOGIN_CACHE_TTL_SECONDS), + ]; + + if (cachedCode && cachedCode !== nextCode) { + tasks.push(this.setWechatLoginCodeCache(cachedCode, null, 1)); + } + + await Promise.all(tasks); + + return { + state: loginState, + source: forceNewCode ? 'refreshed' : 'generated', + message: forceNewCode ? + `客户端编码 ${normalizedClientCode} 长轮询结束,已刷新登录码` : + `客户端编码 ${normalizedClientCode} 已生成登录码`, + }; + } + + /** + * 获取微信扫码登录码 + * @param {Object} data + * @return {Object} + */ + async getLoginWechatCode(data = {}) { + const { app } = this; + try { + const rawClientCode = typeof data.clientCode === 'string' ? data.clientCode : (typeof data.client_code === 'string' ? data.client_code : ''); + const hasInputClientCode = !!rawClientCode && rawClientCode.trim().length > 0; + + let clientCode = ''; + let shouldWaitRefresh = false; + let cachedState = null; + + if (hasInputClientCode) { + const normalizedClientCode = this.parseWechatBindCode(rawClientCode); + if (!normalizedClientCode) { + return { + success: false, + code: 0, + data: null, + message: '无效的客户端编码格式', + }; + } + + const inputClientCacheKey = this.getWechatLoginClientCacheKey(normalizedClientCode); + try { + cachedState = await this.app.getCacheAsync(inputClientCacheKey); + } catch (cacheErr) { + app.coreLogger.warn(`读取微信登录码缓存失败: ${cacheErr.message}`); + } + + // 传入 clientCode 但缓存不存在时,按空值处理,重新分配新的客户端编码。 + if (cachedState) { + clientCode = normalizedClientCode; + shouldWaitRefresh = true; + } else { + clientCode = await this.createWechatLoginClientCode(); + } + } else { + clientCode = await this.createWechatLoginClientCode(); + } + + const clientCacheKey = this.getWechatLoginClientCacheKey(clientCode); + if (!cachedState) { + try { + cachedState = await this.app.getCacheAsync(clientCacheKey); + } catch (cacheErr) { + app.coreLogger.warn(`读取微信登录码缓存失败: ${cacheErr.message}`); + } + } + + // 若外部已将 ye4s_user_id 写入 clientCode 对应缓存,直接登录并返回,不再等待长轮询。 + if (hasInputClientCode && cachedState) { + const immediateLoginResult = await this.tryBuildWechatLoginTokenFromState(clientCode, cachedState); + if (immediateLoginResult && immediateLoginResult.success) { + return immediateLoginResult; + } + if (immediateLoginResult && immediateLoginResult.success === false) { + app.coreLogger.warn(`微信登录缓存态直登失败,继续轮询: ${immediateLoginResult.message}`); + } + } + + if (shouldWaitRefresh) { + const waitResult = await this.waitForWechatLoginEvent(clientCode, this.getWechatLongPollTimeoutMs()); + const eventYe4sUserId = Number(waitResult && waitResult.ye4s_user_id); + if (!waitResult.timed_out && Number.isFinite(eventYe4sUserId) && eventYe4sUserId > 0) { + const eventState = { + ...(cachedState || {}), + ye4s_user_id: eventYe4sUserId, + }; + const loginResponse = await this.tryBuildWechatLoginTokenFromState(clientCode, eventState); + if (loginResponse && loginResponse.success) { + return loginResponse; + } + app.coreLogger.warn(`微信事件登录未成功,降级为刷新登录码: ${loginResponse && loginResponse.message ? loginResponse.message : 'unknown_error'}`); + } + + try { + cachedState = await this.app.getCacheAsync(clientCacheKey); + } catch (cacheErr) { + app.coreLogger.warn(`读取微信登录码缓存失败: ${cacheErr.message}`); + } + + const refreshed = await this.refreshWechatLoginState(clientCode, cachedState, { + forceNewCode: true, + }); + + return { + success: true, + code: 200, + data: this.formatLoginWechatData(refreshed.state, refreshed.source), + message: refreshed.message, + }; + } + + const generated = await this.refreshWechatLoginState(clientCode, cachedState, { + forceNewCode: false, + }); + + return { + success: true, + code: 200, + data: this.formatLoginWechatData(generated.state, generated.source), + message: generated.message, + }; + } catch (error) { + app.coreLogger.error(`获取微信登录码失败: ${error.message}`); + return { + success: false, + code: 0, + data: null, + message: '获取微信登录码失败,请稍后重试', + }; + } + } + /** * 获取微信绑定码(缓存优先,低频复查DB,适配轮询) * @param {Object} data @@ -460,9 +1035,8 @@ class UserService extends Service { } const cacheKey = this.getWechatBindCacheKey(accountId); - const forceRefresh = !!data.forceRefresh; - const now = Date.now(); - const waitTimeoutMs = this.getWechatLongPollTimeoutMs(data.waitTimeoutMs); + const useLongPoll = this.shouldUseWechatBindLongPoll(data); + const waitTimeoutMs = this.getWechatLongPollTimeoutMs(); let cachedState = null; try { @@ -471,57 +1045,44 @@ class UserService extends Service { app.coreLogger.warn(`读取微信绑定缓存失败: ${cacheErr.message}`); } - if (cachedState && !forceRefresh) { - const nextCheckAt = Number(cachedState.next_db_check_at || 0); - let refreshedState = null; - if (nextCheckAt <= now) { - refreshedState = await this.refreshWechatBindState(accountId, cachedState); - cachedState = refreshedState.state; - } - - if (this.shouldUseWechatBindLongPoll(data, cachedState)) { - const waitResult = await this.waitForWechatBindEvent(accountId, waitTimeoutMs); - try { - cachedState = await this.app.getCacheAsync(cacheKey); - } catch (cacheErr) { - app.coreLogger.warn(`读取微信绑定缓存失败: ${cacheErr.message}`); - } - - const nextState = await this.refreshWechatBindState(accountId, cachedState); - const timeoutMessage = waitResult.timed_out ? '等待绑定状态变化超时,返回当前状态' : nextState.message; - - return { - success: true, - code: 200, - data: this.formatBindWechatData(nextState.state, nextState.source), - message: timeoutMessage, - }; - } - - if (refreshedState) { - return { - success: true, - code: 200, - data: this.formatBindWechatData(refreshedState.state, refreshedState.source), - message: refreshedState.message, - }; - } + const refreshed = await this.refreshWechatBindState(accountId, cachedState, { + forceNewCode: false, + }); + if (refreshed.state.status === 'bound' || !useLongPoll) { return { success: true, code: 200, - data: this.formatBindWechatData(cachedState, 'cache'), - message: '获取绑定码成功(缓存)', + data: this.formatBindWechatData(refreshed.state, refreshed.source), + message: refreshed.message, }; } - const refreshed = await this.refreshWechatBindState(accountId, cachedState); + const waitResult = await this.waitForWechatBindEvent(accountId, waitTimeoutMs); + try { + cachedState = await this.app.getCacheAsync(cacheKey); + } catch (cacheErr) { + app.coreLogger.warn(`读取微信绑定缓存失败: ${cacheErr.message}`); + } + + const nextState = await this.refreshWechatBindState(accountId, cachedState, { + forceNewCode: waitResult.timed_out, + }); + + if (waitResult.timed_out) { + return { + success: true, + code: 200, + data: this.formatBindWechatData(nextState.state, nextState.source), + message: '长轮询结束未检测到状态变化,已刷新绑定码', + }; + } return { success: true, code: 200, - data: this.formatBindWechatData(refreshed.state, refreshed.source), - message: refreshed.message, + data: this.formatBindWechatData(nextState.state, nextState.source), + message: nextState.message, }; } catch (error) { app.coreLogger.error(`获取微信绑定码失败: ${error.message}`); @@ -542,8 +1103,19 @@ class UserService extends Service { async getUserByTempCode(data = {}) { const { ctx, app } = this; try { - const code = typeof data.code === 'string' ? data.code.trim() : ''; - if (!code) { + const loadAccountRealName = async accountId => { + const account = await ctx.model.Account.findOne({ + where: { + id: accountId, + }, + attributes: [ 'id', 'real_name' ], + raw: true, + }); + return account && account.real_name ? account.real_name : ''; + }; + + const rawCode = typeof data.code === 'string' ? data.code.trim() : ''; + if (!rawCode) { return { success: false, code: 0, @@ -552,7 +1124,8 @@ class UserService extends Service { }; } - if (!this.parseWechatBindCode(code)) { + const code = this.parseWechatBindCode(rawCode); + if (!code) { return { success: false, code: 0, @@ -570,65 +1143,60 @@ class UserService extends Service { } const cachedAccountId = Number(codeState && codeState.account_id); - if (Number.isFinite(cachedAccountId) && cachedAccountId > 0) { + if (!Number.isFinite(cachedAccountId) || cachedAccountId <= 0) { return { - success: true, - code: 200, - data: { - account_id: cachedAccountId, - code, - status: codeState.status || 'pending', - source: 'cache', - updated_at: codeState.updated_at || new Date().toISOString(), - }, - message: '获取账号成功', + success: false, + code: 0, + data: null, + message: '绑定码不存在或已过期', }; } - const ye4sClient = ctx.app.mysql.get('ye4s'); - const ye4sUser = await ye4sClient.get('ye4s_user', { - tmp_code: code, + const realName = await loadAccountRealName(cachedAccountId); + const scanState = { + account_id: cachedAccountId, + code, + status: 'scanned', + scanned_at: new Date().toISOString(), + source: 'gateway-scan', + }; + + const codeExpiresAt = Number(codeState && codeState.expires_at); + const scannedBindState = { + account_id: cachedAccountId, + code, + status: 'scanned', + scanned_at: scanState.scanned_at, + updated_at: scanState.scanned_at, + ye4s_user_id: null, + expires_at: Number.isFinite(codeExpiresAt) ? codeExpiresAt : null, + }; + const bindCacheTtl = this.getRemainingSecondsByExpiresAt(codeExpiresAt, WECHAT_BIND_CACHE_TTL_SECONDS); + + await Promise.all([ + this.setWechatBindScanCache(code, scanState, WECHAT_BIND_SCAN_CACHE_TTL_SECONDS), + this.setWechatBindCache(this.getWechatBindCacheKey(cachedAccountId), scannedBindState, bindCacheTtl), + ]); + await this.publishWechatBindEvent(cachedAccountId, { + status: 'scanned', + code, + scanned_at: scanState.scanned_at, + source: 'gateway-scan', }); - const wmsAccountId = Number(ye4sUser && ye4sUser.wms_account_id); - if (Number.isFinite(wmsAccountId) && wmsAccountId > 0) { - const boundState = { - account_id: wmsAccountId, - status: 'bound', - code, - updated_at: new Date().toISOString(), - next_db_check_at: Date.now() + WECHAT_BIND_RECHECK_INTERVAL_MS, - ye4s_user_id: ye4sUser.id || null, - }; - await Promise.all([ - this.setWechatBindCodeCache(code, boundState, WECHAT_BIND_CACHE_TTL_SECONDS), - this.setWechatBindCache(this.getWechatBindCacheKey(wmsAccountId), boundState, WECHAT_BIND_CACHE_TTL_SECONDS), - ]); - await this.publishWechatBindEvent(wmsAccountId, { - status: 'bound', - code, - source: 'api', - }); - - return { - success: true, - code: 200, - data: { - account_id: wmsAccountId, - code, - status: 'bound', - source: 'db', - updated_at: boundState.updated_at, - }, - message: '获取账号成功', - }; - } - return { - success: false, - code: 0, - data: null, - message: '绑定码不存在或已过期', + success: true, + code: 200, + data: { + account_id: cachedAccountId, + real_name: realName, + code, + status: 'scanned', + source: 'scan-cache', + scanned_at: scanState.scanned_at, + updated_at: codeState && codeState.updated_at ? codeState.updated_at : scanState.scanned_at, + }, + message: '扫码状态已记录', }; } catch (error) { app.coreLogger.error(`根据绑定码获取账号失败: ${error.message}`); @@ -649,11 +1217,11 @@ class UserService extends Service { async bindAccountByTempCode(data = {}) { const { ctx, app } = this; try { - const code = typeof data.code === 'string' ? data.code.trim() : ''; + const rawCode = typeof data.code === 'string' ? data.code.trim() : ''; const rawYe4sUserId = data.ye4s_user_id ?? data.ye4sUserId; const ye4sUserId = Number(rawYe4sUserId); - if (!code) { + if (!rawCode) { return { success: false, code: 0, @@ -662,7 +1230,8 @@ class UserService extends Service { }; } - if (!this.parseWechatBindCode(code)) { + const code = this.parseWechatBindCode(rawCode); + if (!code) { return { success: false, code: 0, @@ -680,23 +1249,14 @@ class UserService extends Service { }; } - const userResult = await this.getUserByTempCode({ code }); - if (!userResult || !userResult.success) { - return { - success: false, - code: 0, - data: null, - message: userResult && userResult.message ? userResult.message : '绑定码不存在或已过期', - }; - } - - const accountId = Number(userResult.data && userResult.data.account_id); + const scanState = await this.getWechatBindScanCache(code); + const accountId = Number(scanState && scanState.account_id); if (!Number.isFinite(accountId) || accountId <= 0) { return { success: false, code: 0, data: null, - message: '绑定码未匹配到有效账号', + message: '未检测到扫码记录或扫码状态已过期,请重新扫码', }; } @@ -720,20 +1280,27 @@ class UserService extends Service { const boundState = { account_id: accountId, status: 'bound', - code, + code: '', updated_at: new Date().toISOString(), - next_db_check_at: Date.now() + WECHAT_BIND_RECHECK_INTERVAL_MS, ye4s_user_id: ye4sUserId, + expires_at: null, + scanned_at: scanState && scanState.scanned_at ? scanState.scanned_at : null, }; await Promise.all([ - this.setWechatBindCodeCache(code, boundState, WECHAT_BIND_CACHE_TTL_SECONDS), this.setWechatBindCache(this.getWechatBindCacheKey(accountId), boundState, WECHAT_BIND_CACHE_TTL_SECONDS), + this.setWechatBindCodeCache(code, null, 1), + this.setWechatBindScanCache(code, { + ...scanState, + status: 'bound', + ye4s_user_id: ye4sUserId, + bound_at: boundState.updated_at, + }, WECHAT_BIND_SCAN_CACHE_TTL_SECONDS), ]); await this.publishWechatBindEvent(accountId, { status: 'bound', - code, + code: '', source: 'gateway-bind', }); @@ -791,17 +1358,6 @@ class UserService extends Service { let affectedRows = 0; for (const row of bindRows) { - const rowCode = typeof row.tmp_code === 'string' ? row.tmp_code.trim() : ''; - if (rowCode) { - await this.setWechatBindCodeCache(rowCode, { - account_id: accountId, - status: 'unbound', - code: rowCode, - updated_at: new Date().toISOString(), - next_db_check_at: Date.now() + WECHAT_BIND_RECHECK_INTERVAL_MS, - ye4s_user_id: row.id || null, - }, WECHAT_BIND_CACHE_TTL_SECONDS); - } try { const ret = await ye4sClient.update('ye4s_user', { id: row.id, @@ -819,17 +1375,6 @@ class UserService extends Service { } const cacheKey = this.getWechatBindCacheKey(accountId); - const cachedState = await this.app.getCacheAsync(cacheKey); - if (cachedState && cachedState.code) { - await this.setWechatBindCodeCache(cachedState.code, { - account_id: accountId, - status: 'unbound', - code: cachedState.code, - updated_at: new Date().toISOString(), - next_db_check_at: Date.now() + WECHAT_BIND_RECHECK_INTERVAL_MS, - ye4s_user_id: cachedState.ye4s_user_id || null, - }, WECHAT_BIND_CACHE_TTL_SECONDS); - } await this.setWechatBindCache(cacheKey, null, 1); await this.publishWechatBindEvent(accountId, { status: 'unbound', diff --git a/app/service/systems/setting/account.js b/app/service/systems/setting/account.js index 27f273e..1190b04 100644 --- a/app/service/systems/setting/account.js +++ b/app/service/systems/setting/account.js @@ -1,10 +1,34 @@ 'use strict'; const Service = require('egg').Service; +const { parseWhereConditions } = require('../../../lib/query_condition_parser'); const RESERVED_EMPLOYEE_NAME = '测试工号保留'; class SettingAccountService extends Service { + getListWhereSpecialFieldMap() { + return { + employee_id: { + field: 'id', + }, + account_id: { + field: 'account_id', + }, + username: { + field: '$account.username$', + }, + phone: { + field: '$account.phone$', + }, + email: { + field: '$account.email$', + }, + quickWhere: { + bucket: 'quick', + }, + }; + } + createError(message, code = 500) { const error = new Error(message); error.code = code; @@ -127,10 +151,214 @@ class SettingAccountService extends Service { return Number(currentRole.role_id); } - async formatEmployeeRow(employee) { - const account = await this.getWmsClient().get('wms_account', { - id: employee.account_id, + normalizeRoleIds(ids) { + if (!Array.isArray(ids) || ids.length === 0) { + throw this.createError('ids 参数不能为空', 400); + } + + const roleIds = []; + for (const roleId of ids) { + const normalized = Number(roleId); + if (!Number.isFinite(normalized) || normalized <= 0) { + throw this.createError('ids 必须是正整数数组', 400); + } + roleIds.push(normalized); + } + return Array.from(new Set(roleIds)); + } + + flattenRoleTreeMeta(roleNodes, idCollector = [], parentMap = new Map()) { + if (!Array.isArray(roleNodes) || roleNodes.length === 0) { + return { idCollector, parentMap }; + } + + for (const node of roleNodes) { + const roleId = Number(node && node.role_id); + if (Number.isFinite(roleId) && roleId > 0) { + idCollector.push(roleId); + parentMap.set(roleId, Number(node && node.pid ? node.pid : 0)); + } + + const children = Array.isArray(node && node.children) ? node.children : []; + this.flattenRoleTreeMeta(children, idCollector, parentMap); + } + + return { idCollector, parentMap }; + } + + async resolveAssignableRoleScope() { + const roleResult = await this.ctx.service.systems.setting.role.list({ + includeDisabled: false, + includeSystem: false, }); + + const roleTree = roleResult && roleResult.data && Array.isArray(roleResult.data.roles) + ? roleResult.data.roles + : []; + const { idCollector, parentMap } = this.flattenRoleTreeMeta(roleTree, [], new Map()); + return { + roleIdSet: new Set(idCollector), + parentMap, + }; + } + + pruneDescendantRoleIds(roleIds, parentMap) { + const selected = new Set(roleIds); + const pruned = []; + + for (const roleId of roleIds) { + let current = roleId; + let keep = true; + const visited = new Set(); + + while (true) { + const parentId = Number(parentMap.get(current) || 0); + if (!Number.isFinite(parentId) || parentId <= 0) { + break; + } + if (visited.has(parentId)) { + break; + } + visited.add(parentId); + + if (selected.has(parentId)) { + keep = false; + break; + } + + current = parentId; + } + + if (keep) { + pruned.push(roleId); + } + } + + return Array.from(new Set(pruned)); + } + + async resolveRequestedRoleIds(data = {}, options = {}) { + const required = options.required === true; + const hasIds = Object.prototype.hasOwnProperty.call(data, 'ids'); + const hasRoleIds = Object.prototype.hasOwnProperty.call(data, 'role_ids'); + + if (!hasIds && !hasRoleIds) { + if (required) { + throw this.createError('ids 参数不能为空', 400); + } + return null; + } + + const rawRoleIds = hasIds ? data.ids : data.role_ids; + const roleIds = this.normalizeRoleIds(rawRoleIds); + + const { roleIdSet, parentMap } = await this.resolveAssignableRoleScope(); + if (roleIdSet.size === 0) { + throw this.createError('当前角色范围为空,无法分配角色', 400); + } + + const outOfScopeIds = roleIds.filter(roleId => !roleIdSet.has(roleId)); + if (outOfScopeIds.length > 0) { + throw this.createError(`包含超出当前角色范围的角色ID:${outOfScopeIds.join(',')}`, 400); + } + + return this.pruneDescendantRoleIds(roleIds, parentMap); + } + + async replaceEmployeeRoles(employeeId, roleIds) { + const { ctx } = this; + + await ctx.model.EmployeeRole.destroy({ + where: { + employee_id: employeeId, + }, + }); + + const rows = roleIds.map(roleId => ({ + employee_id: employeeId, + role_id: roleId, + })); + + await ctx.model.EmployeeRole.bulkCreate(rows); + } + + async buildEmployeeRoleGroupMap(employeeIds) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + if (!Array.isArray(employeeIds) || employeeIds.length === 0) { + return new Map(); + } + + const employeeRoleRows = await ctx.model.EmployeeRole.findAll({ + where: { + employee_id: employeeIds, + }, + attributes: [ 'employee_id', 'role_id' ], + raw: true, + }); + + if (employeeRoleRows.length === 0) { + return new Map(); + } + + const roleIds = Array.from(new Set(employeeRoleRows + .map(item => Number(item.role_id)) + .filter(roleId => Number.isFinite(roleId) && roleId > 0))); + + const roleRows = await ctx.model.Role.findAll({ + where: { + id: { + [Op.in]: roleIds, + }, + }, + attributes: [ 'id', 'role_code', 'role_name', 'pid', 'status' ], + raw: true, + }); + const roleMap = new Map(roleRows.map(role => [ Number(role.id), role ])); + + const employeeRoleMap = new Map(); + for (const row of employeeRoleRows) { + const employeeId = Number(row.employee_id); + const roleId = Number(row.role_id); + if (!Number.isFinite(employeeId) || employeeId <= 0 || !Number.isFinite(roleId) || roleId <= 0) { + continue; + } + + const role = roleMap.get(roleId); + if (!employeeRoleMap.has(employeeId)) { + employeeRoleMap.set(employeeId, { + role_ids: [], + roles: [], + }); + } + + const target = employeeRoleMap.get(employeeId); + target.role_ids.push(roleId); + target.roles.push({ + role_id: roleId, + role_code: role && role.role_code ? role.role_code : '', + role_name: role && role.role_name ? role.role_name : '', + pid: role ? Number(role.pid || 0) : 0, + status: role ? Number(role.status) : 0, + }); + } + + for (const value of employeeRoleMap.values()) { + value.role_ids = Array.from(new Set(value.role_ids)).sort((a, b) => a - b); + value.roles.sort((a, b) => a.role_id - b.role_id); + } + + return employeeRoleMap; + } + + async formatEmployeeRow(employee, options = {}) { + let account = options.account || null; + if (!account) { + account = await this.getWmsClient().get('wms_account', { + id: employee.account_id, + }); + } const avatar = await this.getAvatarMeta(employee.id); return { @@ -150,28 +378,119 @@ class SettingAccountService extends Service { } async list(data = {}) { - const { ctx } = this; + const { ctx, app } = this; + const { Op } = app.Sequelize; const storeId = this.getCurrentStoreId(); - const statusFilter = data.includeDisabled === true - ? undefined - : (data.status === 0 || data.status === '0' ? 0 : 1); + const currentEmployeeId = this.getCurrentEmployeeId(); + const normalizedWhere = ctx.where && typeof ctx.where === 'object' + ? { ...ctx.where } + : (data.where && typeof data.where === 'object' ? { ...data.where } : {}); + let parsedResult = ctx.whereParsed; + if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) { + const parsed = parseWhereConditions({ + where: normalizedWhere, + app, + specialFieldMap: this.getListWhereSpecialFieldMap(), + }); + if (!parsed.ok) { + throw this.createError(`where 参数解析失败: ${parsed.reason}`, 400); + } + parsedResult = parsed.result; + } - const where = { - store_id: storeId, - }; - if (statusFilter === 0 || statusFilter === 1) { - where.status = statusFilter; + const andConditions = [ + { + store_id: storeId, + }, + ]; + const hasWhereStatus = Object.prototype.hasOwnProperty.call(normalizedWhere, 'status'); + if (!hasWhereStatus) { + const statusFilter = data.includeDisabled === true + ? undefined + : (data.status === 0 || data.status === '0' ? 0 : 1); + if (statusFilter === 0 || statusFilter === 1) { + andConditions.push({ status: statusFilter }); + } + } + + const dynamicConditions = parsedResult.dynamicConditions || []; + if (dynamicConditions.length > 0) { + andConditions.push({ [Op.and]: dynamicConditions }); + } + + const quickWhereInput = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere) + || normalizedWhere.quickWhere + || null; + const quickWhereValue = quickWhereInput && typeof quickWhereInput === 'object' + ? quickWhereInput.value + : quickWhereInput; + if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') { + const keyword = String(quickWhereValue).trim(); + andConditions.push({ + [Op.or]: [ + { real_name: { [Op.like]: `%${keyword}%` } }, + { '$account.username$': { [Op.like]: `%${keyword}%` } }, + { '$account.phone$': { [Op.like]: `%${keyword}%` } }, + { '$account.email$': { [Op.like]: `%${keyword}%` } }, + ], + }); } const employees = await ctx.model.AccountStoreEmployee.findAll({ - where, + where: { + [Op.and]: andConditions, + }, + include: [ + { + model: ctx.model.Account, + as: 'account', + attributes: [ 'id', 'username', 'phone', 'email', 'real_name' ], + required: false, + }, + ], order: [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]], }); + const { roleIdSet } = await this.resolveAssignableRoleScope(); + if (roleIdSet.size === 0) { + return { + code: 200, + data: [], + }; + } + + const employeeIds = employees + .map(employee => Number(employee.id)) + .filter(employeeId => Number.isFinite(employeeId) && employeeId > 0); + const employeeRoleMap = await this.buildEmployeeRoleGroupMap(employeeIds); + const list = []; for (const employee of employees) { - list.push(await this.formatEmployeeRow(employee)); + const employeeId = Number(employee.id); + if (currentEmployeeId && employeeId === currentEmployeeId) { + continue; + } + + const roleGroup = employeeRoleMap.get(employeeId) || { + role_ids: [], + roles: [], + }; + + // 只展示当前账号可分配范围内的工号,避免越权操作。 + const hasOutOfScopeRole = roleGroup.role_ids + .some(roleId => !roleIdSet.has(Number(roleId))); + if (hasOutOfScopeRole) { + continue; + } + + list.push({ + ...await this.formatEmployeeRow(employee, { + account: employee.account, + }), + role_ids: roleGroup.role_ids, + roles: roleGroup.roles, + }); } return { @@ -205,7 +524,9 @@ class SettingAccountService extends Service { throw this.createError(`新增工号禁止直接使用保留名称 ${RESERVED_EMPLOYEE_NAME}`, 400); } - const roleId = await this.resolveRoleId(data); + const roleIds = await this.resolveRequestedRoleIds(data, { + required: true, + }); let account = await this.findRawAccountByPhone(phone); if (account && Number(account.status) !== 1) { @@ -256,13 +577,15 @@ class SettingAccountService extends Service { throw this.createError('该手机号已绑定当前主体工号', 409); } - const { employee, employeeRole } = await service.systems.store.ensureEmployeeRoleBinding({ + const { employee } = await service.systems.store.ensureEmployeeRoleBinding({ accountId: Number(account.id), storeId, - roleId, + roleId: roleIds[0], realName, }); + await this.replaceEmployeeRoles(Number(employee.id), roleIds); + await service.systems.auth.user.clearUserCache(Number(account.id)); const formatted = await this.formatEmployeeRow(employee); @@ -270,7 +593,8 @@ class SettingAccountService extends Service { code: 200, data: { ...formatted, - role_id: Number(employeeRole.role_id), + role_id: roleIds[0], + role_ids: roleIds, is_new_account: createdAccountId > 0, }, }; @@ -348,14 +672,15 @@ class SettingAccountService extends Service { const employeeId = Number(data.employee_id || data.id || 0); const hasRealName = Object.prototype.hasOwnProperty.call(data, 'real_name') || Object.prototype.hasOwnProperty.call(data, 'realName'); const hasFileId = Object.prototype.hasOwnProperty.call(data, 'file_id') || Object.prototype.hasOwnProperty.call(data, 'avatar_file_id') || Object.prototype.hasOwnProperty.call(data, 'fileId'); + const hasRoleIds = Object.prototype.hasOwnProperty.call(data, 'ids') || Object.prototype.hasOwnProperty.call(data, 'role_ids'); const realName = this.normalizeName(data.real_name || data.realName); const fileId = Number(data.file_id || data.avatar_file_id || data.fileId || 0); if (!employeeId) { throw this.createError('employee_id 参数不能为空', 400); } - if (!hasRealName && !hasFileId) { - throw this.createError('至少需要更新 real_name 或 file_id', 400); + if (!hasRoleIds) { + throw this.createError('ids 参数不能为空', 400); } if (hasRealName && !realName) { throw this.createError('real_name 参数不能为空', 400); @@ -405,12 +730,32 @@ class SettingAccountService extends Service { }); } + const roleIds = await this.resolveRequestedRoleIds(data, { + required: true, + }); + await this.replaceEmployeeRoles(employeeId, roleIds); + await service.systems.auth.user.clearUserCache(Number(employee.account_id)); const refreshed = await ctx.model.AccountStoreEmployee.findByPk(employeeId); + const roleRows = await ctx.model.EmployeeRole.findAll({ + where: { + employee_id: employeeId, + }, + attributes: [ 'role_id' ], + order: [[ 'role_id', 'ASC' ]], + raw: true, + }); + const boundRoleIds = roleRows + .map(item => Number(item.role_id)) + .filter(roleId => Number.isFinite(roleId) && roleId > 0); + return { code: 200, - data: await this.formatEmployeeRow(refreshed), + data: { + ...await this.formatEmployeeRow(refreshed), + role_ids: Array.from(new Set(boundRoleIds)), + }, }; } } diff --git a/app/service/systems/setting/permission.js b/app/service/systems/setting/permission.js new file mode 100644 index 0000000..10eab8f --- /dev/null +++ b/app/service/systems/setting/permission.js @@ -0,0 +1,730 @@ +'use strict'; + +const Service = require('egg').Service; + +class SettingPermissionService extends Service { + createError(message, code = 500) { + const error = new Error(message); + error.code = code; + return error; + } + + getCurrentStoreId() { + const storeId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isFinite(storeId) || storeId <= 0) { + throw this.createError('未识别到当前主体,无法操作权限', 400); + } + return storeId; + } + + getCurrentEmployeeId() { + const employeeId = Number(this.ctx.user && this.ctx.user.employees_id); + if (!Number.isFinite(employeeId) || employeeId <= 0) { + return null; + } + return employeeId; + } + + toPositiveNumber(value, fieldName) { + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + return num; + } + + async getRole(roleId) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const storeId = this.getCurrentStoreId(); + + const role = await ctx.model.Role.findOne({ + where: { + id: roleId, + [Op.or]: [ + { store_id: storeId }, + { store_id: 0 }, + { store_id: null }, + ], + }, + }); + + if (!role) { + throw this.createError('角色不存在或无权限操作', 404); + } + + return role; + } + + async getPermission(permissionId, includeDisabled = false) { + const { ctx } = this; + const where = { id: permissionId }; + if (!includeDisabled) { + where.status = 1; + } + + const permission = await ctx.model.Permission.findOne({ where }); + if (!permission) { + throw this.createError('权限不存在或已禁用', 404); + } + + return permission; + } + + normalizePermissionType(type) { + const normalized = typeof type === 'string' ? type.trim() : ''; + if (!normalized) { + throw this.createError('type 参数不能为空', 400); + } + + const allowedTypes = new Set([ 'web_pages', 'pda_pages', 'btns', 'api', 'miniprogram_pages', 'block' ]); + if (!allowedTypes.has(normalized)) { + throw this.createError('type 参数不合法', 400); + } + return normalized; + } + + normalizeOptionalString(value, fieldName, maxLength = 255) { + if (value === undefined || value === null) { + return null; + } + const normalized = String(value).trim(); + if (!normalized) { + return ''; + } + if (normalized.length > maxLength) { + throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400); + } + return normalized; + } + + normalizeParentId(value) { + if (value === undefined || value === null || value === '' || Number(value) === 0) { + return null; + } + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) { + throw this.createError('parent_id 参数不合法', 400); + } + return num; + } + + normalizeSort(value) { + if (value === undefined || value === null || value === '') { + return 0; + } + const num = Number(value); + if (!Number.isFinite(num) || num < 0) { + throw this.createError('sort 参数不合法', 400); + } + return Math.floor(num); + } + + normalizeStatus(value) { + if (value === undefined || value === null || value === '') { + return 1; + } + const num = Number(value); + if (num === 0 || num === 1) { + return num; + } + throw this.createError('status 参数不合法', 400); + } + + normalizeBooleanFlag(value, fieldName) { + if (value === undefined || value === null || value === '') { + return 0; + } + const num = Number(value); + if (num === 0 || num === 1) { + return num; + } + throw this.createError(`${fieldName} 参数不合法`, 400); + } + + async getAvailablePermissionIdSet({ includeDisabled = false } = {}) { + const rows = await this.resolveVisiblePermissionRows({ + includeDisabled, + type: null, + keyword: '', + }); + return new Set(rows.map(item => Number(item.id)).filter(id => Number.isFinite(id) && id > 0)); + } + + async ensureParentPermissionInScope(parentId) { + if (!parentId) { + return; + } + + await this.getPermission(parentId, false); + + const availableSet = await this.getAvailablePermissionIdSet({ includeDisabled: false }); + if (!availableSet.has(Number(parentId))) { + throw this.createError(`parent_id 超出当前登录工号可用权限集:${parentId}`, 400); + } + } + + async ensurePermissionsInAvailableScope(permissionIds, options = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const includeDisabled = options.includeDisabled === true; + + const availableSet = await this.getAvailablePermissionIdSet({ includeDisabled }); + if (availableSet.size === 0) { + throw this.createError('当前登录工号可用权限集为空,无法操作权限', 400); + } + + const targetRows = await ctx.model.Permission.findAll({ + where: { + id: permissionIds, + }, + attributes: [ 'id', 'parent_id' ], + raw: true, + }); + if (targetRows.length !== permissionIds.length) { + const found = new Set(targetRows.map(item => Number(item.id))); + const missing = permissionIds.filter(id => !found.has(Number(id))); + throw this.createError(`权限不存在:${missing.join(',')}`, 404); + } + + const parentMap = new Map(targetRows.map(item => [ Number(item.id), item.parent_id === null ? null : Number(item.parent_id) ])); + let pendingParentIds = Array.from(new Set(targetRows + .map(item => item.parent_id === null ? null : Number(item.parent_id)) + .filter(parentId => Number.isFinite(parentId) && parentId > 0))); + + while (pendingParentIds.length > 0) { + const fetchIds = pendingParentIds.filter(parentId => !parentMap.has(parentId)); + if (fetchIds.length === 0) { + break; + } + + const parentRows = await ctx.model.Permission.findAll({ + where: { + id: { + [Op.in]: fetchIds, + }, + }, + attributes: [ 'id', 'parent_id' ], + raw: true, + }); + + for (const row of parentRows) { + parentMap.set(Number(row.id), row.parent_id === null ? null : Number(row.parent_id)); + } + + pendingParentIds = Array.from(new Set(parentRows + .map(row => row.parent_id === null ? null : Number(row.parent_id)) + .filter(parentId => Number.isFinite(parentId) && parentId > 0 && !parentMap.has(parentId)))); + } + + const outOfScopeIds = []; + for (const permissionId of permissionIds) { + let currentId = Number(permissionId); + let inScope = false; + const visited = new Set(); + + while (Number.isFinite(currentId) && currentId > 0 && !visited.has(currentId)) { + visited.add(currentId); + if (availableSet.has(currentId)) { + inScope = true; + break; + } + + const parentId = parentMap.has(currentId) ? parentMap.get(currentId) : null; + if (!Number.isFinite(parentId) || parentId <= 0) { + break; + } + currentId = Number(parentId); + } + + if (!inScope) { + outOfScopeIds.push(Number(permissionId)); + } + } + + if (outOfScopeIds.length > 0) { + throw this.createError(`包含超出当前登录工号可用权限集的权限ID:${outOfScopeIds.join(',')}`, 400); + } + } + + normalizePermissionIds(inputPermissionIds) { + if (!Array.isArray(inputPermissionIds)) { + throw this.createError('permission_ids 参数不能为空', 400); + } + + const permissionIds = []; + for (const permissionId of inputPermissionIds) { + const normalized = Number(permissionId); + if (!Number.isFinite(normalized) || normalized <= 0) { + throw this.createError('permission_ids 必须是正整数数组', 400); + } + permissionIds.push(normalized); + } + + return Array.from(new Set(permissionIds)); + } + + normalizeIds(inputIds, fieldName = 'ids') { + if (!Array.isArray(inputIds)) { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + + const ids = []; + for (const item of inputIds) { + const normalized = Number(item); + if (!Number.isFinite(normalized) || normalized <= 0) { + throw this.createError(`${fieldName} 必须是正整数数组`, 400); + } + ids.push(normalized); + } + if (ids.length === 0) { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + + return Array.from(new Set(ids)); + } + + async validatePermissions(permissionIds) { + const { ctx } = this; + if (permissionIds.length === 0) { + return []; + } + + const permissions = await ctx.model.Permission.findAll({ + where: { + id: permissionIds, + status: 1, + }, + attributes: [ 'id' ], + }); + + if (permissions.length !== permissionIds.length) { + const foundIds = permissions.map(item => Number(item.id)); + const missingIds = permissionIds.filter(item => !foundIds.includes(item)); + throw this.createError(`权限不存在或已禁用:${missingIds.join(',')}`, 400); + } + + return permissions; + } + + async clearRoleUsersCache(roleId) { + const { ctx, service } = this; + const storeId = this.getCurrentStoreId(); + + const employeeRoleRows = await ctx.model.EmployeeRole.findAll({ + where: { + role_id: roleId, + }, + include: [ + { + model: ctx.model.AccountStoreEmployee, + as: 'employee', + attributes: [ 'account_id' ], + where: { + store_id: storeId, + status: 1, + }, + required: true, + }, + ], + raw: false, + }); + + const accountIds = Array.from(new Set(employeeRoleRows + .map(item => Number(item.employee && item.employee.account_id)) + .filter(id => Number.isFinite(id) && id > 0))); + + for (const accountId of accountIds) { + await service.systems.auth.user.clearUserCache(accountId); + } + } + + async getCurrentEmployeePermissionIds() { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const currentEmployeeId = this.getCurrentEmployeeId(); + if (!currentEmployeeId) { + return []; + } + + const employeeRoles = await ctx.model.EmployeeRole.findAll({ + attributes: [ 'role_id' ], + where: { + employee_id: currentEmployeeId, + }, + include: [ + { + model: ctx.model.Role, + as: 'role', + attributes: [], + where: { + status: 1, + }, + required: true, + }, + ], + raw: true, + }); + + const roleIds = Array.from(new Set(employeeRoles + .map(item => Number(item.role_id)) + .filter(id => Number.isFinite(id) && id > 0))); + if (roleIds.length === 0) { + return []; + } + + const rolePermissions = await ctx.model.RolePermission.findAll({ + where: { + role_id: { + [Op.in]: roleIds, + }, + }, + attributes: [ 'permission_id' ], + raw: true, + }); + + return Array.from(new Set(rolePermissions + .map(item => Number(item.permission_id)) + .filter(id => Number.isFinite(id) && id > 0))); + } + + async getCurrentRoleId() { + const { ctx } = this; + const currentEmployeeId = this.getCurrentEmployeeId(); + if (!currentEmployeeId) { + return null; + } + + const row = await ctx.model.EmployeeRole.findOne({ + attributes: [ 'role_id' ], + where: { + employee_id: currentEmployeeId, + }, + include: [ + { + model: ctx.model.Role, + as: 'role', + attributes: [], + where: { + status: 1, + }, + required: true, + }, + ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const roleId = Number(row && row.role_id); + if (!Number.isFinite(roleId) || roleId <= 0) { + return null; + } + return roleId; + } + + async resolveVisiblePermissionRows({ includeDisabled = false, type = null, keyword = '' } = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const currentPermissionIds = await this.getCurrentEmployeePermissionIds(); + if (currentPermissionIds.length === 0) { + return []; + } + + const where = { + id: { + [Op.in]: currentPermissionIds, + }, + status: includeDisabled ? { [Op.in]: [ 0, 1 ] } : 1, + type: { + [Op.notLike]: '%_pages', + }, + }; + if (type) { + where.type = type; + } + if (keyword) { + where[Op.or] = [ + { path: { [Op.like]: `%${keyword}%` } }, + { name: { [Op.like]: `%${keyword}%` } }, + { meta_title: { [Op.like]: `%${keyword}%` } }, + ]; + } + + const permissionRows = await ctx.model.Permission.findAll({ + where, + attributes: [ + 'id', + 'path', + 'name', + 'type', + 'status', + 'parent_id', + 'sort', + 'meta_title', + ], + order: [ + [ 'sort', 'ASC' ], + [ 'id', 'ASC' ], + ], + }); + + return permissionRows; + } + + async list(data = {}) { + const { ctx } = this; + + const includeDisabled = data.includeDisabled === true; + const roleIdRaw = data.role_id || data.roleId; + const type = typeof data.type === 'string' && data.type.trim() ? data.type.trim() : null; + const keyword = typeof data.keyword === 'string' ? data.keyword.trim() : ''; + + let role = null; + let targetRoleId = roleIdRaw; + if (targetRoleId === undefined || targetRoleId === null || targetRoleId === '') { + targetRoleId = await this.getCurrentRoleId(); + } + if (targetRoleId !== undefined && targetRoleId !== null && targetRoleId !== '') { + const roleId = this.toPositiveNumber(targetRoleId, 'role_id'); + role = await this.getRole(roleId); + } + + const permissionRows = await this.resolveVisiblePermissionRows({ + includeDisabled, + type, + keyword, + }); + + let selectedPermissionSet = new Set(); + if (role) { + const rolePermissions = await ctx.model.RolePermission.findAll({ + where: { + role_id: role.id, + }, + attributes: [ 'permission_id' ], + }); + + selectedPermissionSet = new Set(rolePermissions.map(item => Number(item.permission_id))); + } + + const permissions = permissionRows.map(item => ({ + permission_id: Number(item.id), + path: item.path || '', + name: item.name || '', + type: item.type || '', + status: Number(item.status), + parent_id: item.parent_id === null ? null : Number(item.parent_id), + sort: Number(item.sort || 0), + meta_title: item.meta_title || '', + selected: role ? selectedPermissionSet.has(Number(item.id)) : false, + })); + + return { + code: 200, + data: { + role_id: role ? Number(role.id) : null, + permissions, + }, + }; + } + + async add(data = {}) { + const { ctx } = this; + + const path = this.normalizeOptionalString(data.path, 'path', 255); + if (!path) { + throw this.createError('path 参数不能为空', 400); + } + + const permissionData = { + path, + type: this.normalizePermissionType(data.type), + name: this.normalizeOptionalString(data.name, 'name', 100) || '', + component: this.normalizeOptionalString(data.component, 'component', 255), + redirect: this.normalizeOptionalString(data.redirect, 'redirect', 255), + meta_title: this.normalizeOptionalString(data.meta_title, 'meta_title', 100), + meta_icon: this.normalizeOptionalString(data.meta_icon, 'meta_icon', 50), + parent_id: this.normalizeParentId(data.parent_id), + sort: this.normalizeSort(data.sort), + hidden: this.normalizeBooleanFlag(data.hidden, 'hidden'), + always_show: this.normalizeBooleanFlag(data.always_show, 'always_show'), + status: this.normalizeStatus(data.status), + }; + + await this.ensureParentPermissionInScope(permissionData.parent_id); + + let created = null; + try { + created = await ctx.model.Permission.create(permissionData); + } catch (error) { + throw error; + } + + return { + code: 200, + data: { + permission_id: Number(created.id), + path: created.path || '', + type: created.type || '', + parent_id: created.parent_id === null ? null : Number(created.parent_id), + status: Number(created.status), + }, + }; + } + + async delete(data = {}) { + const { ctx } = this; + const permissionIds = this.normalizeIds(data.ids, 'ids'); + + await this.ensurePermissionsInAvailableScope(permissionIds, { + includeDisabled: true, + }); + + const permissions = await ctx.model.Permission.findAll({ + where: { + id: permissionIds, + }, + attributes: [ 'id', 'status' ], + raw: true, + }); + + const deletedIds = []; + const alreadyDeletedIds = []; + for (const permission of permissions) { + if (Number(permission.status) === 0) { + alreadyDeletedIds.push(Number(permission.id)); + } else { + deletedIds.push(Number(permission.id)); + } + } + + const transaction = await ctx.model.transaction(); + try { + if (deletedIds.length > 0) { + await ctx.model.Permission.update({ + status: 0, + }, { + where: { + id: deletedIds, + }, + transaction, + }); + + await ctx.model.RolePermission.destroy({ + where: { + permission_id: deletedIds, + }, + transaction, + }); + } + + await transaction.commit(); + } catch (error) { + await transaction.rollback(); + throw error; + } + + return { + code: 200, + data: { + ids: permissionIds, + deleted_ids: deletedIds, + already_deleted_ids: alreadyDeletedIds, + status: 'deleted', + }, + }; + } + + async update(data = {}) { + const { ctx } = this; + + const permissionId = this.toPositiveNumber(data.permission_id || data.permissionId, 'permission_id'); + await this.ensurePermissionsInAvailableScope([ permissionId ], { + includeDisabled: true, + }); + + const permission = await this.getPermission(permissionId, true); + + const hasPath = Object.prototype.hasOwnProperty.call(data, 'path'); + const hasName = Object.prototype.hasOwnProperty.call(data, 'name'); + const hasType = Object.prototype.hasOwnProperty.call(data, 'type'); + const hasComponent = Object.prototype.hasOwnProperty.call(data, 'component'); + const hasRedirect = Object.prototype.hasOwnProperty.call(data, 'redirect'); + const hasMetaTitle = Object.prototype.hasOwnProperty.call(data, 'meta_title'); + const hasMetaIcon = Object.prototype.hasOwnProperty.call(data, 'meta_icon'); + const hasParentId = Object.prototype.hasOwnProperty.call(data, 'parent_id'); + const hasSort = Object.prototype.hasOwnProperty.call(data, 'sort'); + const hasHidden = Object.prototype.hasOwnProperty.call(data, 'hidden'); + const hasAlwaysShow = Object.prototype.hasOwnProperty.call(data, 'always_show'); + const hasStatus = Object.prototype.hasOwnProperty.call(data, 'status'); + + if (!hasPath && !hasName && !hasType && !hasComponent && !hasRedirect + && !hasMetaTitle && !hasMetaIcon && !hasParentId && !hasSort + && !hasHidden && !hasAlwaysShow && !hasStatus) { + throw this.createError('至少需要提供一个可更新字段', 400); + } + + const updates = {}; + if (hasPath) { + const path = this.normalizeOptionalString(data.path, 'path', 255); + if (!path) { + throw this.createError('path 参数不能为空', 400); + } + updates.path = path; + } + if (hasName) { + updates.name = this.normalizeOptionalString(data.name, 'name', 100) || ''; + } + if (hasType) { + updates.type = this.normalizePermissionType(data.type); + } + if (hasComponent) { + updates.component = this.normalizeOptionalString(data.component, 'component', 255); + } + if (hasRedirect) { + updates.redirect = this.normalizeOptionalString(data.redirect, 'redirect', 255); + } + if (hasMetaTitle) { + updates.meta_title = this.normalizeOptionalString(data.meta_title, 'meta_title', 100); + } + if (hasMetaIcon) { + updates.meta_icon = this.normalizeOptionalString(data.meta_icon, 'meta_icon', 50); + } + if (hasParentId) { + const parentId = this.normalizeParentId(data.parent_id); + if (parentId && parentId === permissionId) { + throw this.createError('parent_id 不能等于 permission_id', 400); + } + await this.ensureParentPermissionInScope(parentId); + updates.parent_id = parentId; + } + if (hasSort) { + updates.sort = this.normalizeSort(data.sort); + } + if (hasHidden) { + updates.hidden = this.normalizeBooleanFlag(data.hidden, 'hidden'); + } + if (hasAlwaysShow) { + updates.always_show = this.normalizeBooleanFlag(data.always_show, 'always_show'); + } + if (hasStatus) { + updates.status = this.normalizeStatus(data.status); + } + + await permission.update(updates); + + return { + code: 200, + data: { + permission_id: Number(permission.id), + path: permission.path || '', + type: permission.type || '', + parent_id: permission.parent_id === null ? null : Number(permission.parent_id), + status: Number(permission.status), + }, + }; + } +} + +module.exports = SettingPermissionService; diff --git a/app/service/systems/setting/role.js b/app/service/systems/setting/role.js new file mode 100644 index 0000000..1dea240 --- /dev/null +++ b/app/service/systems/setting/role.js @@ -0,0 +1,669 @@ +'use strict'; + +const Service = require('egg').Service; + +class SettingRoleService extends Service { + createError(message, code = 500) { + const error = new Error(message); + error.code = code; + return error; + } + + getCurrentStoreId() { + const storeId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isFinite(storeId) || storeId <= 0) { + throw this.createError('未识别到当前主体,无法操作角色', 400); + } + return storeId; + } + + getCurrentEmployeeId() { + const employeeId = Number(this.ctx.user && this.ctx.user.employees_id); + if (!Number.isFinite(employeeId) || employeeId <= 0) { + return null; + } + return employeeId; + } + + toPositiveNumber(value, fieldName) { + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + return num; + } + + async getEmployee(employeeId, options = {}) { + const { ctx } = this; + const storeId = this.getCurrentStoreId(); + const includeDisabled = options.includeDisabled === true; + const where = { + id: employeeId, + store_id: storeId, + }; + if (!includeDisabled) { + where.status = 1; + } + + const employee = await ctx.model.AccountStoreEmployee.findOne({ where }); + if (!employee) { + throw this.createError('工号不存在或无权限操作', 404); + } + return employee; + } + + normalizeRoleIds(inputRoleIds) { + if (!Array.isArray(inputRoleIds) || inputRoleIds.length === 0) { + throw this.createError('role_ids 参数不能为空', 400); + } + + const roleIds = []; + for (const roleId of inputRoleIds) { + const normalized = Number(roleId); + if (!Number.isFinite(normalized) || normalized <= 0) { + throw this.createError('role_ids 必须是正整数数组', 400); + } + roleIds.push(normalized); + } + + return Array.from(new Set(roleIds)); + } + + async findAssignableRoles(roleIds, storeId) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const roles = await ctx.model.Role.findAll({ + where: { + id: roleIds, + status: 1, + [Op.or]: [ + { store_id: storeId }, + { store_id: 0 }, + { store_id: null }, + ], + }, + order: [[ 'id', 'ASC' ]], + }); + + if (roles.length !== roleIds.length) { + const foundRoleIds = roles.map(role => Number(role.id)); + const missingRoleIds = roleIds.filter(roleId => !foundRoleIds.includes(roleId)); + throw this.createError(`角色不存在、已禁用或超出当前主体范围:${missingRoleIds.join(',')}`, 400); + } + + return roles; + } + + async clearEmployeeCache(employee) { + const { service } = this.ctx; + await service.systems.auth.user.clearUserCache(Number(employee.account_id)); + } + + async getCurrentEmployeeRoleIds() { + const { ctx } = this; + const currentEmployeeId = this.getCurrentEmployeeId(); + if (!currentEmployeeId) { + return []; + } + + const rows = await ctx.model.EmployeeRole.findAll({ + where: { + employee_id: currentEmployeeId, + }, + attributes: [ 'role_id' ], + }); + + return Array.from(new Set(rows.map(item => Number(item.role_id)).filter(id => Number.isFinite(id) && id > 0))); + } + + collectDescendantRoleIds(roleRows, startRoleIds) { + const childrenMap = new Map(); + for (const row of roleRows) { + const parentId = Number(row.pid || 0); + if (!childrenMap.has(parentId)) { + childrenMap.set(parentId, []); + } + childrenMap.get(parentId).push(Number(row.id)); + } + + const visited = new Set(); + const stack = Array.from(startRoleIds); + while (stack.length > 0) { + const roleId = Number(stack.pop()); + if (!Number.isFinite(roleId) || roleId <= 0 || visited.has(roleId)) { + continue; + } + visited.add(roleId); + const children = childrenMap.get(roleId) || []; + for (const childId of children) { + if (!visited.has(childId)) { + stack.push(childId); + } + } + } + return visited; + } + + buildRoleTree(roleRows, rootRoleIds, selectedRoleIdSet) { + const nodeMap = new Map(); + for (const row of roleRows) { + const roleId = Number(row.id); + nodeMap.set(roleId, { + role_id: roleId, + role_code: row.role_code || '', + role_name: row.role_name || '', + description: row.description || '', + role_type: Number(row.role_type), + scope: Number(row.scope), + is_system: Number(row.is_system), + status: Number(row.status), + store_id: row.store_id === null ? null : Number(row.store_id), + pid: Number(row.pid || 0), + selected: selectedRoleIdSet.has(roleId), + children: [], + }); + } + + for (const node of nodeMap.values()) { + const parent = nodeMap.get(node.pid); + if (parent) { + parent.children.push(node); + } + } + + const sortNodes = nodes => { + nodes.sort((a, b) => a.role_id - b.role_id); + for (const item of nodes) { + if (item.children && item.children.length > 0) { + sortNodes(item.children); + } + } + }; + + const roots = Array.from(rootRoleIds) + .map(roleId => nodeMap.get(Number(roleId))) + .filter(Boolean); + sortNodes(roots); + return roots; + } + + normalizeStoreScope(storeId) { + if (storeId === null || storeId === undefined) { + return 0; + } + const num = Number(storeId); + if (!Number.isFinite(num) || num <= 0) { + return 0; + } + return num; + } + + isRoleVisibleInScope(role, currentRoleRows, currentStoreId, includeSystem) { + const roleStoreScope = this.normalizeStoreScope(role.store_id); + + // 当前主体角色默认可见 + if (roleStoreScope === currentStoreId) { + return true; + } + + // includeSystem=true 时,可见系统角色 + if (includeSystem && roleStoreScope === 0) { + return true; + } + + // 当前工号若本身处于系统角色域,至少允许看到系统角色,避免空树。 + const hasSystemCurrentRole = currentRoleRows + .some(item => this.normalizeStoreScope(item.store_id) === 0); + if (hasSystemCurrentRole && roleStoreScope === 0) { + return true; + } + + return false; + } + + normalizePermissionIds(inputPermissionIds) { + if (!Array.isArray(inputPermissionIds)) { + throw this.createError('permission_ids 参数不能为空', 400); + } + + const permissionIds = []; + for (const permissionId of inputPermissionIds) { + const normalized = Number(permissionId); + if (!Number.isFinite(normalized) || normalized <= 0) { + throw this.createError('permission_ids 必须是正整数数组', 400); + } + permissionIds.push(normalized); + } + + return Array.from(new Set(permissionIds)); + } + + normalizePid(value) { + if (value === undefined || value === null || value === '') { + return 0; + } + const pid = Number(value); + if (!Number.isFinite(pid) || pid < 0) { + throw this.createError('pid 参数不合法', 400); + } + return pid; + } + + async getManageableRole(roleId, options = {}) { + const { ctx } = this; + const storeId = this.getCurrentStoreId(); + const includeDisabled = options.includeDisabled === true; + + const where = { + id: roleId, + store_id: storeId, + is_system: 0, + }; + if (!includeDisabled) { + where.status = 1; + } + + const role = await ctx.model.Role.findOne({ where }); + if (!role) { + throw this.createError('角色不存在、无权限操作或为系统预设角色', 404); + } + return role; + } + + async validatePermissionSet(permissionIds) { + const { ctx } = this; + if (permissionIds.length === 0) { + return; + } + + const existingPermissions = await ctx.model.Permission.findAll({ + where: { + id: permissionIds, + status: 1, + }, + attributes: [ 'id' ], + raw: true, + }); + if (existingPermissions.length !== permissionIds.length) { + const found = new Set(existingPermissions.map(item => Number(item.id))); + const missing = permissionIds.filter(id => !found.has(id)); + throw this.createError(`权限不存在或已禁用:${missing.join(',')}`, 400); + } + + const visiblePermissions = await this.ctx.service.systems.setting.permission.resolveVisiblePermissionRows({ + includeDisabled: false, + type: null, + keyword: '', + }); + const availableSet = new Set(visiblePermissions.map(item => Number(item.id))); + const outOfScopeIds = permissionIds.filter(id => !availableSet.has(id)); + if (outOfScopeIds.length > 0) { + throw this.createError(`包含超出可用权限集的权限ID:${outOfScopeIds.join(',')}`, 400); + } + } + + async replaceRolePermissions(roleId, permissionIds, transaction) { + const { ctx } = this; + + await ctx.model.RolePermission.destroy({ + where: { + role_id: roleId, + }, + transaction, + }); + + if (permissionIds.length > 0) { + const rows = permissionIds.map(permissionId => ({ + role_id: roleId, + permission_id: permissionId, + })); + + await ctx.model.RolePermission.bulkCreate(rows, { transaction }); + } + } + + async clearRoleUsersCache(roleId) { + const { ctx, service } = this; + const storeId = this.getCurrentStoreId(); + + const employeeRoleRows = await ctx.model.EmployeeRole.findAll({ + where: { + role_id: roleId, + }, + include: [ + { + model: ctx.model.AccountStoreEmployee, + as: 'employee', + attributes: [ 'account_id' ], + where: { + store_id: storeId, + status: 1, + }, + required: true, + }, + ], + raw: false, + }); + + const accountIds = Array.from(new Set(employeeRoleRows + .map(item => Number(item.employee && item.employee.account_id)) + .filter(id => Number.isFinite(id) && id > 0))); + + for (const accountId of accountIds) { + await service.systems.auth.user.clearUserCache(accountId); + } + } + + async list(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const storeId = this.getCurrentStoreId(); + const includeDisabled = data.includeDisabled === true; + const includeSystem = data.includeSystem === true; + const currentEmployeeId = this.getCurrentEmployeeId(); + + let employee = null; + if (currentEmployeeId) { + employee = await this.getEmployee(currentEmployeeId, { + includeDisabled: true, + }); + } + + // 先拉取当前主体 + 系统角色域,后续按可见规则二次收敛。 + const roleWhere = { + status: includeDisabled ? { [Op.in]: [ 0, 1 ] } : 1, + [Op.or]: [ { store_id: storeId }, { store_id: 0 }, { store_id: null } ], + }; + + const roleRows = await ctx.model.Role.findAll({ + where: roleWhere, + attributes: [ + 'id', + 'role_code', + 'role_name', + 'description', + 'role_type', + 'scope', + 'is_system', + 'status', + 'store_id', + 'pid', + ], + order: [ + [ 'is_system', 'DESC' ], + [ 'id', 'ASC' ], + ], + }); + + const currentRoleIds = await this.getCurrentEmployeeRoleIds(); + if (currentRoleIds.length === 0) { + return { + code: 200, + data: { + employee_id: employee ? Number(employee.id) : null, + roles: [], + }, + }; + } + + const roleMap = new Map(roleRows.map(item => [ Number(item.id), item ])); + const currentRoleRows = currentRoleIds + .map(roleId => roleMap.get(roleId)) + .filter(Boolean); + + if (currentRoleRows.length === 0) { + return { + code: 200, + data: { + employee_id: employee ? Number(employee.id) : null, + roles: [], + }, + }; + } + + const sameLevelParentIds = new Set(currentRoleRows.map(item => Number(item.pid || 0))); + const currentRoleIdSet = new Set(currentRoleRows.map(item => Number(item.id))); + const hasSystemCurrentRole = currentRoleRows + .some(item => this.normalizeStoreScope(item.store_id) === 0); + + // 默认场景下,若当前角色在系统域(store_id=0/null),只保留当前角色本身作为根, + // 避免暴露其他系统同级角色。 + const sameLevelRoleIds = hasSystemCurrentRole && !includeSystem + ? new Set(currentRoleIdSet) + : new Set(roleRows + .filter(item => sameLevelParentIds.has(Number(item.pid || 0))) + .filter(item => this.isRoleVisibleInScope(item, currentRoleRows, storeId, includeSystem)) + .map(item => Number(item.id))); + + const descendantRoleIds = this.collectDescendantRoleIds(roleRows, currentRoleRows.map(item => Number(item.id))); + const visibleRoleIds = new Set([ ...sameLevelRoleIds, ...descendantRoleIds ]); + + const visibleRoleRows = roleRows + .filter(item => visibleRoleIds.has(Number(item.id))) + .filter(item => this.isRoleVisibleInScope(item, currentRoleRows, storeId, includeSystem)); + const rootRoleIds = new Set(visibleRoleRows + .filter(item => sameLevelRoleIds.has(Number(item.id))) + .map(item => Number(item.id))); + + let selectedRoleIdSet = new Set(); + if (employee) { + const employeeRoles = await ctx.model.EmployeeRole.findAll({ + where: { + employee_id: employee.id, + }, + }); + selectedRoleIdSet = new Set(employeeRoles.map(item => Number(item.role_id))); + } + + const roles = this.buildRoleTree(visibleRoleRows, rootRoleIds, selectedRoleIdSet); + + return { + code: 200, + data: { + employee_id: employee ? Number(employee.id) : null, + roles, + }, + }; + } + + async add(data = {}) { + const { ctx } = this; + + const storeId = this.getCurrentStoreId(); + const roleCode = typeof data.role_code === 'string' ? data.role_code.trim() : ''; + const roleName = typeof data.role_name === 'string' ? data.role_name.trim() : ''; + const description = typeof data.description === 'string' ? data.description.trim() : ''; + const roleType = Number(data.role_type || 1); + const scope = Number(data.scope || 1); + const status = data.status === 0 || data.status === '0' ? 0 : 1; + const pid = this.normalizePid(data.pid); + const permissionIds = this.normalizePermissionIds(data.permission_ids || data.permissionIds || []); + const creatorId = Number(this.ctx.user && this.ctx.user.id); + + if (!roleCode) { + throw this.createError('role_code 参数不能为空', 400); + } + if (!roleName) { + throw this.createError('role_name 参数不能为空', 400); + } + if (!Number.isFinite(creatorId) || creatorId <= 0) { + throw this.createError('未识别到当前账号,无法创建角色', 400); + } + + await this.validatePermissionSet(permissionIds); + + const transaction = await ctx.model.transaction(); + let createdRole = null; + try { + createdRole = await ctx.model.Role.create({ + role_code: roleCode, + role_name: roleName, + description, + role_type: roleType, + scope, + is_system: 0, + status, + created_by: creatorId, + store_id: storeId, + pid, + }, { transaction }); + + await this.replaceRolePermissions(Number(createdRole.id), permissionIds, transaction); + await transaction.commit(); + } catch (error) { + await transaction.rollback(); + if (error && error.name === 'SequelizeUniqueConstraintError') { + throw this.createError('role_code 已存在', 409); + } + throw error; + } + + return { + code: 200, + data: { + role_id: Number(createdRole.id), + role_code: createdRole.role_code, + role_name: createdRole.role_name, + permission_ids: permissionIds, + created: true, + }, + }; + } + + async delete(data = {}) { + const { ctx } = this; + + const roleIds = this.normalizeRoleIds(data.ids); + const roles = []; + for (const roleId of roleIds) { + const role = await this.getManageableRole(roleId, { + includeDisabled: true, + }); + roles.push(role); + } + + const deletedIds = []; + const alreadyDeletedIds = []; + + const transaction = await ctx.model.transaction(); + try { + for (const role of roles) { + const roleId = Number(role.id); + if (Number(role.status) === 0) { + alreadyDeletedIds.push(roleId); + continue; + } + + await role.update({ + status: 0, + updated_at: new Date(), + }, { transaction }); + deletedIds.push(roleId); + } + + if (deletedIds.length > 0) { + await ctx.model.RolePermission.destroy({ + where: { + role_id: deletedIds, + }, + transaction, + }); + } + + await transaction.commit(); + } catch (error) { + await transaction.rollback(); + throw error; + } + + for (const roleId of deletedIds) { + await this.clearRoleUsersCache(roleId); + } + + return { + code: 200, + data: { + ids: roleIds, + deleted_ids: deletedIds, + already_deleted_ids: alreadyDeletedIds, + status: 'deleted', + }, + }; + } + + async update(data = {}) { + const { ctx } = this; + + const roleId = this.toPositiveNumber(data.role_id || data.roleId, 'role_id'); + const role = await this.getManageableRole(roleId, { + includeDisabled: true, + }); + + const hasRoleName = Object.prototype.hasOwnProperty.call(data, 'role_name'); + const hasDescription = Object.prototype.hasOwnProperty.call(data, 'description'); + const hasStatus = Object.prototype.hasOwnProperty.call(data, 'status'); + const hasPid = Object.prototype.hasOwnProperty.call(data, 'pid'); + const hasPermissionIds = Object.prototype.hasOwnProperty.call(data, 'permission_ids') + || Object.prototype.hasOwnProperty.call(data, 'permissionIds'); + + if (!hasRoleName && !hasDescription && !hasStatus && !hasPid && !hasPermissionIds) { + throw this.createError('至少需要更新角色信息或 permission_ids', 400); + } + if (!hasPermissionIds) { + throw this.createError('permission_ids 参数不能为空,角色权限需一次性提交', 400); + } + + const permissionIds = this.normalizePermissionIds(data.permission_ids || data.permissionIds || []); + await this.validatePermissionSet(permissionIds); + + const updates = {}; + if (hasRoleName) { + const roleName = typeof data.role_name === 'string' ? data.role_name.trim() : ''; + if (!roleName) { + throw this.createError('role_name 参数不能为空', 400); + } + updates.role_name = roleName; + } + if (hasDescription) { + updates.description = typeof data.description === 'string' ? data.description.trim() : ''; + } + if (hasStatus) { + const status = data.status === 0 || data.status === '0' ? 0 : 1; + updates.status = status; + } + if (hasPid) { + updates.pid = this.normalizePid(data.pid); + } + updates.updated_at = new Date(); + + const transaction = await ctx.model.transaction(); + try { + if (Object.keys(updates).length > 0) { + await role.update(updates, { transaction }); + } + + await this.replaceRolePermissions(roleId, permissionIds, transaction); + await transaction.commit(); + } catch (error) { + await transaction.rollback(); + if (error && error.name === 'SequelizeUniqueConstraintError') { + throw this.createError('角色信息冲突(可能 role_code 重复)', 409); + } + throw error; + } + + await this.clearRoleUsersCache(roleId); + + return { + code: 200, + data: { + role_id: roleId, + role_name: role.role_name, + permission_ids: permissionIds, + }, + }; + } +} + +module.exports = SettingRoleService; diff --git a/config/config.default.js b/config/config.default.js index 4c783ee..9c88140 100644 --- a/config/config.default.js +++ b/config/config.default.js @@ -172,6 +172,7 @@ module.exports = appInfo => { config.poloapi ={ } + config.debug = false; // 生成环境默认关闭 debug,开发环境通过 config.local.js 开启 config.printService = { url: 'http://printer.wms.gztbyc.com', }; diff --git a/methods/gateway.json b/methods/gateway.json index 1ddc55f..c39b061 100644 --- a/methods/gateway.json +++ b/methods/gateway.json @@ -1,8 +1,8 @@ { "module": "gateway", "description": "内部网关接口,供内网系统间调用,统一使用 POST 请求", - "version": "0.1.0", - "updatedAt": "2026-03-24", + "version": "0.2.0", + "updatedAt": "2026-03-29", "headers": [], "methods": { "groups": [ @@ -12,7 +12,7 @@ "list": [ { "method": "user.getUserByTempCode", - "description": "根据绑定码反查WMS账号ID(供 ye4s 扫码绑定调用)", + "description": "根据绑定码反查WMS账号ID并写入扫码状态(扫描即视为已确认,状态缓存3分钟)", "isNeedAuth": false, "isNeedLogin": false, "headers": [], @@ -22,7 +22,7 @@ "type": "string", "required": true, "source": "body", - "description": "绑定码(由 user.getBindWechatCode 生成)" + "description": "绑定码(由 user.getBindWechatCode 生成,6位字母数字混合)" } ], "response": [ @@ -32,24 +32,30 @@ "required": true, "description": "匹配到的 WMS 账号ID" }, + { + "name": "real_name", + "type": "string", + "required": true, + "description": "WMS 账号表中的真实姓名,用于扫码绑定前确认账号" + }, { "name": "status", "type": "string", "required": true, - "description": "当前绑定状态,如 pending/bound" + "description": "当前扫码状态,成功扫码后固定为 scanned" }, { "name": "source", "type": "string", "required": true, - "description": "数据来源,如 cache/db" + "description": "数据来源,如 scan-cache" } ], "errors": [] }, { "method": "user.bindAccountByTempCode", - "description": "根据绑定码将 ye4s 用户绑定到 WMS 账号(供 ye4s 扫码后回调)", + "description": "根据绑定码对应的扫码状态缓存将 ye4s 用户绑定到 WMS 账号(需先调用扫码反查接口)", "isNeedAuth": false, "isNeedLogin": false, "headers": [], @@ -59,7 +65,7 @@ "type": "string", "required": true, "source": "body", - "description": "绑定码(由 user.getBindWechatCode 生成)" + "description": "绑定码(由 user.getBindWechatCode 生成,6位字母数字混合)" }, { "name": "ye4s_user_id", @@ -92,6 +98,141 @@ "errors": [] } ] + }, + { + "groupName": "打印绑定模块", + "module": "print", + "list": [ + { + "method": "print.getBindInfo", + "description": "根据 WMS 账号ID和扫码 code 返回可绑定仓库列表;有可绑定仓库时下发 300 秒临时凭据 tempCode,无可绑定仓库时返回空数组且不返回 tempCode", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "account_id", + "type": "number", + "required": true, + "source": "body", + "description": "WMS 账号ID" + }, + { + "name": "code", + "type": "string", + "required": true, + "source": "body", + "description": "打印端提供的绑定 code" + } + ], + "response": [ + { + "name": "warehouses", + "type": "array", + "required": true, + "description": "可绑定仓库列表,元素结构为 { id, name }" + }, + { + "name": "tempCode", + "type": "string", + "required": false, + "description": "临时绑定凭据,仅当 warehouses 非空时返回" + } + ], + "errors": [ + { + "code": 0, + "message": "缺少有效参数 account_id 或 code" + }, + { + "code": 0, + "message": "账号不存在或已禁用" + }, + { + "code": 0, + "message": "无效code或未绑定" + } + ] + }, + { + "method": "print.bindByTempCode", + "description": "根据第一步返回的临时凭据执行打印台绑定,提交工作台名称和仓库ID后完成真实绑定", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "temp_code", + "type": "string", + "required": true, + "source": "body", + "description": "第一步返回的临时凭据,300 秒有效" + }, + { + "name": "printer", + "type": "string", + "required": true, + "source": "body", + "description": "工作台名称" + }, + { + "name": "warehouse", + "type": "number", + "required": true, + "source": "body", + "description": "仓库ID" + } + ], + "response": [ + { + "name": "code", + "type": "string", + "required": true, + "description": "真实绑定 code" + }, + { + "name": "printer", + "type": "string", + "required": true, + "description": "工作台名称" + }, + { + "name": "warehouse", + "type": "number", + "required": true, + "description": "仓库ID" + }, + { + "name": "computerId", + "type": "number", + "required": true, + "description": "打印台电脑ID" + } + ], + "errors": [ + { + "code": 0, + "message": "参数缺失" + }, + { + "code": 0, + "message": "临时code无效或已过期" + }, + { + "code": 0, + "message": "仓库无绑定权限" + }, + { + "code": 0, + "message": "仓库id校验失败" + }, + { + "code": 0, + "message": "该仓库下打印台名称已存在且可用" + } + ] + } + ] } ] } diff --git a/methods/system.json b/methods/system.json index d7c9e13..43b81b5 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1661,7 +1661,7 @@ "list": [ { "method": "setting.account.list", - "description": "查询当前主体下的工号基础信息列表", + "description": "查询当前主体下且在当前账号角色组可操作范围内的工号列表", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -1686,6 +1686,13 @@ "required": false, "source": "body", "description": "是否包含已删除工号" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "动态筛选条件,仅支持 employee_id、account_id、real_name、status、username、phone、email、quickWhere;其中 username/phone/email 为账号字段,quickWhere 按 real_name/username/phone/email 模糊搜索" } ], "response": [ @@ -1754,12 +1761,54 @@ "type": "string", "required": true, "description": "头像访问地址" + }, + { + "name": "data[].role_ids", + "type": "number[]", + "required": true, + "description": "工号绑定的角色ID数组" + }, + { + "name": "data[].roles[]", + "type": "object", + "required": true, + "description": "工号绑定的角色组详情" + }, + { + "name": "data[].roles[].role_id", + "type": "number", + "required": true, + "description": "角色ID" + }, + { + "name": "data[].roles[].role_code", + "type": "string", + "required": true, + "description": "角色编码" + }, + { + "name": "data[].roles[].role_name", + "type": "string", + "required": true, + "description": "角色名称" + }, + { + "name": "data[].roles[].pid", + "type": "number", + "required": true, + "description": "父级角色ID" + }, + { + "name": "data[].roles[].status", + "type": "number", + "required": true, + "description": "角色状态:1=启用,0=停用" } ], "errors": [ { "code": "400", - "description": "当前登录态缺少主体上下文(store_id)" + "description": "当前登录态缺少主体上下文(store_id)或 where 参数解析失败" }, { "code": "500", @@ -1769,7 +1818,7 @@ }, { "method": "setting.account.add", - "description": "新增工号,按手机号复用或创建账号后绑定到当前主体", + "description": "新增工号,按手机号复用或创建账号后绑定到当前主体,并校验角色组 ids 不超出当前角色范围", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -1810,11 +1859,11 @@ "description": "新账号密码,不传默认 111111" }, { - "name": "role_id", - "type": "number", - "required": false, + "name": "ids", + "type": "number[]", + "required": true, "source": "body", - "description": "工号角色,不传时继承当前操作人工号角色" + "description": "角色组ID数组,必须在当前登录工号可分配角色范围内;若同时传入父子节点,仅保留父节点" }, { "name": "email", @@ -1843,6 +1892,12 @@ "required": true, "description": "绑定后的角色ID" }, + { + "name": "role_ids", + "type": "number[]", + "required": true, + "description": "绑定后的角色组ID数组" + }, { "name": "is_new_account", "type": "boolean", @@ -1865,7 +1920,7 @@ "errors": [ { "code": "400", - "description": "参数错误、手机号格式错误、或直接使用保留名称" + "description": "参数错误、手机号格式错误、直接使用保留名称、或 ids 超出当前角色范围" }, { "code": "409", @@ -1942,7 +1997,7 @@ }, { "method": "setting.account.update", - "description": "更新工号姓名和头像引用", + "description": "更新工号姓名、头像引用和角色组 ids(含当前角色范围校验)", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -1974,6 +2029,13 @@ "required": false, "source": "body", "description": "已有文件ID,作为头像引用" + }, + { + "name": "ids", + "type": "number[]", + "required": true, + "source": "body", + "description": "角色组ID数组,传入时将整体替换为该数组,且必须在当前登录工号可分配角色范围内;若同时传入父子节点,仅保留父节点" } ], "response": [ @@ -2000,12 +2062,18 @@ "type": "string", "required": true, "description": "更新后的头像地址" + }, + { + "name": "role_ids", + "type": "number[]", + "required": true, + "description": "更新后的角色组ID数组" } ], "errors": [ { "code": "400", - "description": "参数错误,未提供更新项" + "description": "参数错误、未传 ids、或 ids 超出当前角色范围" }, { "code": "404", @@ -2019,6 +2087,688 @@ } ] }, + { + "groupName": "角色管理模块", + "module": "setting.role", + "list": [ + { + "method": "setting.role.list", + "description": "查询当前主体可分配角色列表,按当前登录工号返回角色选中状态", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "includeDisabled", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否包含停用角色,默认 false" + }, + { + "name": "includeSystem", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否包含系统默认角色(store_id=0/null),默认 false" + } + ], + "response": [ + { + "name": "employee_id", + "type": "number", + "required": false, + "description": "当前登录工号ID,未识别到登录工号时为 null" + }, + { + "name": "roles[]", + "type": "object", + "required": true, + "description": "角色列表" + }, + { + "name": "roles[].role_id", + "type": "number", + "required": true, + "description": "角色ID" + }, + { + "name": "roles[].role_name", + "type": "string", + "required": true, + "description": "角色名称" + }, + { + "name": "roles[].selected", + "type": "boolean", + "required": true, + "description": "表示当前登录工号是否已绑定该角色" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误" + }, + { + "code": "404", + "description": "工号不存在或无权限" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "setting.role.add", + "description": "新增角色并一次性提交权限集(permission_ids)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "role_code", + "type": "string", + "required": true, + "source": "body", + "description": "角色编码(主体内唯一)" + }, + { + "name": "role_name", + "type": "string", + "required": true, + "source": "body", + "description": "角色名称" + }, + { + "name": "description", + "type": "string", + "required": false, + "source": "body", + "description": "角色描述" + }, + { + "name": "pid", + "type": "number", + "required": false, + "source": "body", + "description": "父级角色ID,默认 0" + }, + { + "name": "permission_ids", + "type": "number[]", + "required": true, + "source": "body", + "description": "权限ID数组,一次性提交" + } + ], + "response": [ + { + "name": "role_id", + "type": "number", + "required": true, + "description": "新建角色ID" + }, + { + "name": "role_code", + "type": "string", + "required": true, + "description": "角色编码" + }, + { + "name": "role_name", + "type": "string", + "required": true, + "description": "角色名称" + }, + { + "name": "permission_ids", + "type": "number[]", + "required": true, + "description": "提交后的权限ID集合" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误、权限ID非法或超出当前登录工号可用权限集" + }, + { + "code": "409", + "description": "role_code 冲突" + }, + { + "code": "500", + "description": "新增失败" + } + ] + }, + { + "method": "setting.role.delete", + "description": "批量删除角色(软删除),并清理对应角色权限关联", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "number[]", + "required": true, + "source": "body", + "description": "角色ID数组" + } + ], + "response": [ + { + "name": "ids", + "type": "number[]", + "required": true, + "description": "请求的角色ID数组" + }, + { + "name": "deleted_ids", + "type": "number[]", + "required": true, + "description": "本次实际删除(由启用变为停用)的角色ID数组" + }, + { + "name": "already_deleted_ids", + "type": "number[]", + "required": true, + "description": "本就处于删除状态的角色ID数组" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "固定返回 deleted" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误,ids 必须为正整数数组" + }, + { + "code": "404", + "description": "角色不存在、无权限操作或为系统预设角色(任一ID不满足即失败)" + }, + { + "code": "500", + "description": "删除失败" + } + ] + }, + { + "method": "setting.role.update", + "description": "更新角色信息并一次性重置角色权限(permission_ids)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "role_id", + "type": "number", + "required": true, + "source": "body", + "description": "角色ID" + }, + { + "name": "role_name", + "type": "string", + "required": false, + "source": "body", + "description": "角色名称" + }, + { + "name": "description", + "type": "string", + "required": false, + "source": "body", + "description": "角色描述" + }, + { + "name": "status", + "type": "number", + "required": false, + "source": "body", + "description": "角色状态:1=启用,0=禁用" + }, + { + "name": "pid", + "type": "number", + "required": false, + "source": "body", + "description": "父级角色ID" + }, + { + "name": "permission_ids", + "type": "number[]", + "required": true, + "source": "body", + "description": "权限ID数组,一次性提交" + } + ], + "response": [ + { + "name": "role_id", + "type": "number", + "required": true, + "description": "角色ID" + }, + { + "name": "permission_ids", + "type": "number[]", + "required": true, + "description": "更新后的权限ID集合" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误、permission_ids 非法或超出当前登录工号可用权限集" + }, + { + "code": "404", + "description": "角色不存在、无权限操作或为系统预设角色" + }, + { + "code": "409", + "description": "角色信息冲突" + }, + { + "code": "500", + "description": "更新失败" + } + ] + } + ] + }, + { + "groupName": "权限管理模块", + "module": "setting.permission", + "list": [ + { + "method": "setting.permission.list", + "description": "查询当前登录工号实际可用权限集合,可选按角色返回已绑定权限选中状态", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "role_id", + "type": "number", + "required": false, + "source": "body", + "description": "可选,不传时默认使用当前登录工号的当前角色计算权限选中状态" + }, + { + "name": "type", + "type": "string", + "required": false, + "source": "body", + "description": "可选,按权限类型筛选,如 api/web_pages/pda_pages/btns" + }, + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "可选,按 path/name/meta_title 模糊搜索" + }, + { + "name": "includeDisabled", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否包含禁用权限,默认 false" + } + ], + "response": [ + { + "name": "role_id", + "type": "number", + "required": false, + "description": "查询目标角色ID,未传 role_id 时返回当前登录工号的当前角色ID" + }, + { + "name": "permissions[]", + "type": "object", + "required": true, + "description": "权限列表" + }, + { + "name": "permissions[].permission_id", + "type": "number", + "required": true, + "description": "权限ID" + }, + { + "name": "permissions[].path", + "type": "string", + "required": true, + "description": "权限路径" + }, + { + "name": "permissions[].type", + "type": "string", + "required": true, + "description": "权限类型" + }, + { + "name": "permissions[].selected", + "type": "boolean", + "required": true, + "description": "当传入 role_id 时,表示该权限是否已绑定" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误" + }, + { + "code": "404", + "description": "角色不存在或无权限" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "setting.permission.add", + "description": "新增权限", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "path", + "type": "string", + "required": true, + "source": "body", + "description": "权限路径" + }, + { + "name": "type", + "type": "string", + "required": true, + "source": "body", + "description": "权限类型:web_pages/pda_pages/btns/api/miniprogram_pages/block" + }, + { + "name": "name", + "type": "string", + "required": false, + "source": "body", + "description": "权限名称" + }, + { + "name": "parent_id", + "type": "number", + "required": false, + "source": "body", + "description": "父级权限ID,传 0 或不传表示顶级;若传入必须在当前登录工号可用权限集内" + }, + { + "name": "meta_title", + "type": "string", + "required": false, + "source": "body", + "description": "页面标题" + }, + { + "name": "sort", + "type": "number", + "required": false, + "source": "body", + "description": "排序,默认 0" + } + ], + "response": [ + { + "name": "permission_id", + "type": "number", + "required": true, + "description": "权限ID" + }, + { + "name": "path", + "type": "string", + "required": true, + "description": "权限路径" + }, + { + "name": "type", + "type": "string", + "required": true, + "description": "权限类型" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误或 parent_id 超出当前登录工号可用权限集" + }, + { + "code": "404", + "description": "父级权限不存在" + }, + { + "code": "500", + "description": "新增失败" + } + ] + }, + { + "method": "setting.permission.delete", + "description": "批量删除权限(软删除)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "number[]", + "required": true, + "source": "body", + "description": "权限ID数组,必须在当前登录工号可用权限集内" + } + ], + "response": [ + { + "name": "ids", + "type": "number[]", + "required": true, + "description": "请求的权限ID数组" + }, + { + "name": "deleted_ids", + "type": "number[]", + "required": true, + "description": "本次实际删除(由启用变为停用)的权限ID数组" + }, + { + "name": "already_deleted_ids", + "type": "number[]", + "required": true, + "description": "本就处于删除状态的权限ID数组" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "固定返回 deleted" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误,ids 非法或包含超出当前登录工号可用权限集的权限ID" + }, + { + "code": "404", + "description": "权限不存在" + }, + { + "code": "500", + "description": "删除失败" + } + ] + }, + { + "method": "setting.permission.update", + "description": "更新权限(非角色绑定重置),目标权限必须在当前登录工号可用权限集内", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "permission_id", + "type": "number", + "required": true, + "source": "body", + "description": "权限ID,必须在当前登录工号可用权限集内" + }, + { + "name": "path", + "type": "string", + "required": false, + "source": "body", + "description": "权限路径" + }, + { + "name": "type", + "type": "string", + "required": false, + "source": "body", + "description": "权限类型:web_pages/pda_pages/btns/api/miniprogram_pages/block" + }, + { + "name": "name", + "type": "string", + "required": false, + "source": "body", + "description": "权限名称" + }, + { + "name": "parent_id", + "type": "number", + "required": false, + "source": "body", + "description": "父级权限ID,传 0 表示顶级;若传入必须在当前登录工号可用权限集内" + }, + { + "name": "sort", + "type": "number", + "required": false, + "source": "body", + "description": "排序" + }, + { + "name": "status", + "type": "number", + "required": false, + "source": "body", + "description": "权限状态:1=启用,0=禁用" + } + ], + "response": [ + { + "name": "permission_id", + "type": "number", + "required": true, + "description": "权限ID" + }, + { + "name": "path", + "type": "string", + "required": true, + "description": "更新后的权限路径" + }, + { + "name": "type", + "type": "string", + "required": true, + "description": "更新后的权限类型" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误、未提供更新项,或目标权限超出当前登录工号可用权限集" + }, + { + "code": "404", + "description": "权限不存在" + }, + { + "code": "500", + "description": "更新失败" + } + ] + } + ] + }, { "groupName": "商品模块", "module": "stock", @@ -3474,7 +4224,7 @@ }, { "method": "user.loginByCode", - "description": "登录码登录(使用 ye4s_user.tmp_code)", + "description": "登录码登录(使用本系统缓存登录码,不依赖 ye4s_user.tmp_code)", "isNeedAuth": false, "isNeedLogin": false, "headers": [], @@ -3484,15 +4234,88 @@ "type": "string", "required": true, "source": "body", - "description": "登录码,对应 ye4s_user.tmp_code" + "description": "登录码(6位字母数字混合,对应本系统登录码缓存)" } ], "response": [], "errors": [] }, + { + "method": "user.getLoginWechatCode", + "description": "获取微信扫码登录码:不传客户端编码时生成新的6位客户端编码与登录码;传客户端编码且缓存命中时进入长轮询,优先监听 Redis 登录事件,收到 ye4s_user_id 后立即签发登录 token;未收到事件则刷新登录码返回", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "clientCode", + "type": "string", + "required": false, + "source": "body", + "description": "客户端编码(6位字母数字混合)。不传则服务端自动生成;传入时仅在缓存命中才进入长轮询,缓存不存在按空值处理并重新分配 clientCode" + } + ], + "response": [ + { + "name": "client_code", + "type": "string", + "required": true, + "description": "客户端编码(6位字母数字混合)" + }, + { + "name": "code", + "type": "string", + "required": false, + "description": "微信扫码登录码(6位字母数字混合)。当 status=authorized 时可能为空" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "登录状态:pending(等待扫码)或 authorized(已完成登录)" + }, + { + "name": "updated_at", + "type": "string", + "required": false, + "description": "状态更新时间(ISO 时间)" + }, + { + "name": "expires_at", + "type": "number", + "required": false, + "description": "过期时间戳(毫秒)" + }, + { + "name": "expire_after_ms", + "type": "number", + "required": false, + "description": "距离过期剩余毫秒数" + }, + { + "name": "source", + "type": "string", + "required": true, + "description": "数据来源,如 generated/refreshed/cache/event" + }, + { + "name": "ye4s_user_id", + "type": "number", + "required": false, + "description": "当 status=authorized 时返回的 ye4s 用户ID" + }, + { + "name": "loginToken", + "type": "string", + "required": false, + "description": "当 status=authorized 时返回的本地登录 token" + } + ], + "errors": [] + }, { "method": "user.getBindWechatCode", - "description": "获取微信绑定码(默认立即返回;显式开启长轮询后,最长等待60秒,状态变化立即返回)", + "description": "获取微信绑定状态与绑定码:绑定码为6位字母数字混合且固定60秒有效,默认立即返回;longPoll=true 时最长等待60秒,若无事件则自动刷新新码返回", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -3504,43 +4327,76 @@ } ], "params": [ - { - "name": "forceRefresh", - "type": "boolean", - "required": false, - "source": "body", - "description": "是否强制刷新状态,true 时跳过缓存等待窗口" - }, - { - "name": "waitForChange", - "type": "boolean", - "required": false, - "source": "body", - "description": "是否显式开启长轮询等待(推荐字段);true 时进入最长60秒等待" - }, { "name": "longPoll", "type": "boolean", "required": false, "source": "body", - "description": "长轮询开关(兼容字段);true 时进入最长60秒等待" - }, - { - "name": "waitTimeoutMs", - "type": "number", - "required": false, - "source": "body", - "description": "等待超时毫秒数;后端自动封顶60000" - }, - { - "name": "init", - "type": "boolean", - "required": false, - "source": "body", - "description": "初始化请求标记;true 时强制立即返回,不进入长等待" + "description": "是否启用长轮询;默认 false,true 时等待绑定事件或超时刷新" + } + ], + "response": [ + { + "name": "account_id", + "type": "number", + "required": true, + "description": "WMS 账号ID" + }, + { + "name": "code", + "type": "string", + "required": true, + "description": "绑定码(已绑定时为空字符串)" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "绑定状态:pending/scanned/bound" + }, + { + "name": "is_bound", + "type": "boolean", + "required": true, + "description": "是否已绑定微信" + }, + { + "name": "updated_at", + "type": "string", + "required": true, + "description": "状态更新时间(ISO 时间)" + }, + { + "name": "expires_at", + "type": "number", + "required": false, + "description": "过期时间戳(毫秒),bound 状态可为空" + }, + { + "name": "expire_after_ms", + "type": "number", + "required": true, + "description": "距离过期剩余毫秒数" + }, + { + "name": "scanned_at", + "type": "string", + "required": false, + "description": "扫码时间(未扫码可为空)" + }, + { + "name": "source", + "type": "string", + "required": true, + "description": "数据来源,如 cache/generated/refreshed/db" + }, + { + "name": "ye4s_user_id", + "type": "number", + "required": false, + "description": "已绑定的 ye4s 用户ID(未绑定可为空)" } ], - "response": [], "errors": [] }, { diff --git a/package.json b/package.json index 2129eed..d0a11a0 100644 --- a/package.json +++ b/package.json @@ -64,6 +64,7 @@ "test:local": "egg-bin test", "cov": "egg-bin cov", "lint": "eslint .", + "permission:sync:system-api": "node ./script/sync-system-api-permission.cjs", "check:model-boundary": "node ./script/model-boundary-check.cjs", "ci": "npm run lint && npm run check:model-boundary && npm run cov" }, diff --git a/script/sync-system-api-permission.cjs b/script/sync-system-api-permission.cjs new file mode 100644 index 0000000..66f513b --- /dev/null +++ b/script/sync-system-api-permission.cjs @@ -0,0 +1,254 @@ +const fs = require('fs'); +const path = require('path'); +const mysql = require('mysql2/promise'); + +const ROOT = process.cwd(); +const DEFAULT_CONFIG_PATH = path.join(ROOT, 'config', 'config.local.js'); +const DEFAULT_METHOD_DOC_PATH = path.join(ROOT, 'methods', 'system.json'); + +function parseArgs(argv) { + const args = { + dryRun: false, + roleId: 2, + dbClient: 'wms', + configPath: DEFAULT_CONFIG_PATH, + methodDocPath: DEFAULT_METHOD_DOC_PATH, + }; + + for (const item of argv) { + if (item === '--dry-run') { + args.dryRun = true; + continue; + } + + if (item.startsWith('--role-id=')) { + args.roleId = Number(item.split('=')[1]); + continue; + } + + if (item.startsWith('--db-client=')) { + args.dbClient = String(item.split('=')[1] || '').trim() || 'wms'; + continue; + } + + if (item.startsWith('--config-path=')) { + const raw = String(item.split('=')[1] || '').trim(); + args.configPath = path.resolve(ROOT, raw); + continue; + } + + if (item.startsWith('--method-doc=')) { + const raw = String(item.split('=')[1] || '').trim(); + args.methodDocPath = path.resolve(ROOT, raw); + continue; + } + } + + if (!Number.isInteger(args.roleId) || args.roleId <= 0) { + throw new Error('Invalid --role-id, must be a positive integer.'); + } + + return args; +} + +function loadConfig(configPath) { + if (!fs.existsSync(configPath)) { + throw new Error(`Config file not found: ${configPath}`); + } + + const configFactory = require(configPath); + const config = typeof configFactory === 'function' + ? configFactory({ name: 'wms-permission-sync' }) + : configFactory; + + return config; +} + +function loadAuthRequiredMethods(methodDocPath) { + if (!fs.existsSync(methodDocPath)) { + throw new Error(`Method doc not found: ${methodDocPath}`); + } + + const json = JSON.parse(fs.readFileSync(methodDocPath, 'utf8')); + const groups = json && json.methods && Array.isArray(json.methods.groups) + ? json.methods.groups + : []; + + const methodSet = new Set(); + for (const group of groups) { + const list = group && Array.isArray(group.list) ? group.list : []; + for (const item of list) { + if (!item || !item.method || item.isNeedAuth !== true) continue; + methodSet.add(String(item.method).trim()); + } + } + + return [ ...methodSet ].sort(); +} + +function buildPermissionDefaults(methodPath, templateRow) { + return { + path: methodPath, + type: 'api', + component: templateRow ? templateRow.component : null, + name: templateRow && templateRow.name ? templateRow.name : methodPath, + redirect: templateRow ? templateRow.redirect : null, + meta_title: templateRow && templateRow.meta_title ? templateRow.meta_title : `API:${methodPath}`, + meta_icon: templateRow ? templateRow.meta_icon : null, + hidden: templateRow ? Number(templateRow.hidden || 0) : 0, + always_show: templateRow ? Number(templateRow.always_show || 0) : 0, + parent_id: templateRow && templateRow.parent_id ? Number(templateRow.parent_id) : null, + sort: templateRow ? Number(templateRow.sort || 0) : 0, + status: templateRow ? Number(templateRow.status || 1) : 1, + }; +} + +async function queryPermissionTemplate(conn) { + const [ rows ] = await conn.query(` + SELECT component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, sort, status + FROM wms_permission + WHERE type = 'api' + ORDER BY id ASC + LIMIT 1 + `); + return rows[0] || null; +} + +async function queryExistingPermissions(conn, methodPaths) { + if (methodPaths.length === 0) return new Map(); + + const placeholders = methodPaths.map(() => '?').join(','); + const [ rows ] = await conn.query( + `SELECT id, path FROM wms_permission WHERE type = 'api' AND path IN (${placeholders})`, + methodPaths + ); + + const result = new Map(); + for (const row of rows) { + result.set(row.path, row.id); + } + return result; +} + +async function insertPermission(conn, defaults) { + const [ result ] = await conn.query( + `INSERT INTO wms_permission + (path, type, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, sort, status, created_at, update_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + [ + defaults.path, + defaults.type, + defaults.component, + defaults.name, + defaults.redirect, + defaults.meta_title, + defaults.meta_icon, + defaults.hidden, + defaults.always_show, + defaults.parent_id, + defaults.sort, + defaults.status, + ] + ); + + return result.insertId; +} + +async function bindRolePermission(conn, roleId, permissionId) { + const [ result ] = await conn.query( + 'INSERT IGNORE INTO wms_role_permission (role_id, permission_id, created_at) VALUES (?, ?, NOW())', + [ roleId, permissionId ] + ); + return result.affectedRows > 0; +} + +async function main() { + const args = parseArgs(process.argv.slice(2)); + const cfg = loadConfig(args.configPath); + const dbClient = cfg && cfg.mysql && cfg.mysql.clients && cfg.mysql.clients[args.dbClient]; + + if (!dbClient) { + throw new Error(`MySQL client not found in config.mysql.clients: ${args.dbClient}`); + } + + const methodPaths = loadAuthRequiredMethods(args.methodDocPath); + if (methodPaths.length === 0) { + console.log('[sync-system-api-permission] no isNeedAuth=true methods found.'); + return; + } + + const conn = await mysql.createConnection({ + host: dbClient.host, + port: Number(dbClient.port), + user: dbClient.user, + password: dbClient.password, + database: dbClient.database, + charset: dbClient.charset || 'utf8mb4', + }); + + try { + const templateRow = await queryPermissionTemplate(conn); + const existingMap = await queryExistingPermissions(conn, methodPaths); + + const missingPaths = methodPaths.filter(item => !existingMap.has(item)); + const created = []; + const touchedPermissionIds = []; + + if (!args.dryRun && missingPaths.length > 0) { + await conn.beginTransaction(); + try { + for (const methodPath of missingPaths) { + const defaults = buildPermissionDefaults(methodPath, templateRow); + const permissionId = await insertPermission(conn, defaults); + created.push({ methodPath, permissionId }); + touchedPermissionIds.push(permissionId); + } + await conn.commit(); + } catch (error) { + await conn.rollback(); + throw error; + } + } + + const latestMap = args.dryRun + ? existingMap + : await queryExistingPermissions(conn, methodPaths); + + for (const methodPath of methodPaths) { + const permissionId = latestMap.get(methodPath); + if (permissionId) touchedPermissionIds.push(permissionId); + } + + const uniquePermissionIds = [ ...new Set(touchedPermissionIds) ]; + let roleBindingCreated = 0; + + if (!args.dryRun) { + for (const permissionId of uniquePermissionIds) { + const createdBinding = await bindRolePermission(conn, args.roleId, permissionId); + if (createdBinding) roleBindingCreated++; + } + } + + const summary = { + mode: args.dryRun ? 'dry-run' : 'apply', + roleId: args.roleId, + totalAuthMethods: methodPaths.length, + existingPermissionCount: existingMap.size, + missingPermissionCount: missingPaths.length, + createdPermissionCount: created.length, + roleBindingCreated, + sampleMissing: missingPaths.slice(0, 20), + }; + + console.log('[sync-system-api-permission] summary'); + console.log(JSON.stringify(summary, null, 2)); + } finally { + await conn.end(); + } +} + +main().catch(error => { + console.error('[sync-system-api-permission] failed'); + console.error(error && error.stack ? error.stack : String(error)); + process.exit(1); +}); diff --git a/stock.todo b/stock.todo deleted file mode 100644 index 658f66d..0000000 --- a/stock.todo +++ /dev/null @@ -1,112 +0,0 @@ -# stock.todo - -## 任务目标 -- 提取 `app/service/systemMethods/stock/warehouse.js` 迁移前 method 的历史测试请求记录。 -- 精简并保留新接口(`stock.warehouse.*`)的测试入口。 -- 根据输入/输出补全 `warehouse.js` 方法头注释和 API 文档 `description`。 - -## 迁移方法映射(旧 -> 新) -- `stock.stockWarehouse` -> `stock.warehouse.list` -- `stock.getProhibitedType` -> `stock.warehouse.getProhibitedType` -- `stock.getInfo` -> `stock.warehouse.getInfo` -- `stock.saveWarehouseStock` -> `stock.warehouse.saveWarehouseStock` -- `stock.createWarehouseStock` -> `stock.warehouse.createWarehouseStock` -- `stock.getBarcodes` -> `stock.warehouse.getBarcodes` -- `stock.saveWarehouseStockBarcode` -> `stock.warehouse.saveWarehouseStockBarcode` -- `stock.getStoreStocks` -> `stock.warehouse.getStoreStocks` -- `stock.bindItem` -> `stock.warehouse.bindItem` -- `stock.unbindItem` -> `stock.warehouse.unbindItem` -- `stock.checkItemCodeUnique` -> `stock.warehouse.checkItemCodeUnique` -- `stock.queryStockLogs` -> `stock.warehouse.queryStockLogs` -- `stock.handleBatchDelete` -> `stock.warehouse.handleBatchDelete` -- `stock.deleteUnit` -> `stock.warehouse.deleteUnit` -- `stock.deleteProhibited` -> `stock.warehouse.deleteProhibited` -- `stock.handleBatchChange` -> `stock.warehouse.handleBatchChange` -- `stock.getStockUnits` -> `stock.warehouse.getStockUnits` -- `stock.getUnitList` -> `stock.warehouse.getUnitList` -- `stock.createProhibited` -> `stock.warehouse.createProhibited` -- `stock.createUnit` -> `stock.warehouse.createUnit` -- `stock.search` -> `stock.warehouse.search` - -## 历史测试请求记录提取(迁移前/过渡期) -来源:`node_modules/.mochawesome-reports/mochawesome.json`(2026-03-25) - -### 记录1:新列表接口请求 -- case: `system.stock.warehouse.namespaced.test.js` -- method: `stock.warehouse.list` -- request: -```json -{ - "pagination": { "page": 1, "pageSize": 5 }, - "where": {} -} -``` -- expected: -```json -{ - "httpStatus": 200, - "flag": "success", - "code": 200, - "data": { - "list": "Array", - "pagination": "Object" - } -} -``` - -### 记录2:旧入口退场验证请求(历史) -- case: `system.stock.warehouse.namespaced.test.js`(精简前) -- method: `stock.stockWarehouse` -- request: -```json -{ - "pagination": { "page": 1, "pageSize": 5 }, - "where": {} -} -``` -- expected: -```json -{ - "httpStatus": 500, - "flag": "failure", - "code": 500, - "message": "方法 stockWarehouse 不存在" -} -``` - -### 记录3:where 条件解析服务级样本 -来源:`test/app/service/systems/stock_store.stockWarehouse.conditions.test.js` -- input: -```json -{ - "where": { - "item_code": { "operator": "like", "value": "SKU" }, - "barcode": { "operator": "like", "value": "BC" }, - "prohibited_type": { "operator": "eq", "value": 2 }, - "quantity": { "operator": "ge", "type": "number", "value": "2" } - }, - "pagination": { "page": 1, "pageSize": 10 }, - "sort": { "sortField": "quantity", "sortOrder": "ASC" } -} -``` -- expected: -```json -{ - "code": 200, - "message": "查询成功", - "data.pagination.page": 1, - "data.pagination.pageSize": 10, - "data.queryInfo.hasBarcodeSearch": true -} -``` - -## 新接口精简测试方案 -- 保留:`test/app/controller/system.stock.warehouse.namespaced.test.js` -- 用例:只验证 `stock.warehouse.list` 请求成功与核心返回结构。 -- 下沉:复杂 where/operator 组合继续由 service 级测试覆盖。 - -## 执行结果 -- [x] `warehouse.js` 方法头注释补充(输入/输出声明) -- [x] 新接口测试用例精简 -- [x] `methods/system.json` 的 `stock.warehouse.*` description 语义化更新(21项) -- [x] 回归测试复跑并记录结果(`8 passing`) diff --git a/test/app/controller/gateway.user.bindAccountByTempCode.test.js b/test/app/controller/gateway.user.bindAccountByTempCode.test.js index 36246ef..64ed022 100644 --- a/test/app/controller/gateway.user.bindAccountByTempCode.test.js +++ b/test/app/controller/gateway.user.bindAccountByTempCode.test.js @@ -10,23 +10,49 @@ const { const YE4S_TEST_USER_ID = Number(process.env.SYSTEM_TEST_YE4S_USER_ID || 28); describe('test/app/controller/gateway.user.bindAccountByTempCode.test.js', () => { - it('should bind, unbind, and bind again for ye4s user', async () => { + it('should scan, bind, unbind, and bind again for ye4s user', async () => { const { token } = await getAuthToken(); + const ensurePendingCode = async () => { + let bindCodeRes = await invokeSystemMethod('user.getBindWechatCode', {}, token); + assert.equal(bindCodeRes.status, 200); + assert.equal(bindCodeRes.body.flag, 'success'); + + if (bindCodeRes.body?.data?.status === 'bound') { + const unbindFirst = await invokeSystemMethod('user.unbindWechat', {}, token); + assert.equal(unbindFirst.status, 200); + assert.equal(unbindFirst.body.flag, 'success'); + bindCodeRes = await invokeSystemMethod('user.getBindWechatCode', {}, token); + assert.equal(bindCodeRes.status, 200); + assert.equal(bindCodeRes.body.flag, 'success'); + } + + const nextCode = String(bindCodeRes.body?.data?.code || ''); + assert.match(nextCode, /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/); + return nextCode; + }; + const infoRes = await invokeSystemMethod('user.info', {}, token); assert.equal(infoRes.status, 200); assert.equal(infoRes.body.flag, 'success'); const accountId = Number(infoRes.body?.data?.id); assert.ok(Number.isFinite(accountId) && accountId > 0); - const bindCodeRes = await invokeSystemMethod('user.getBindWechatCode', { - forceRefresh: true, - init: true, - }, token); - assert.equal(bindCodeRes.status, 200); - assert.equal(bindCodeRes.body.flag, 'success'); - const code = String(bindCodeRes.body?.data?.code || ''); - assert.ok(code.length > 10); + const code = await ensurePendingCode(); + + const scanRes1 = await invokeGatewayMethod('user.getUserByTempCode', { code }); + assert.equal(scanRes1.status, 200); + assert.equal(scanRes1.body.flag, 'success'); + assert.equal(scanRes1.body.code, 200); + assert.equal(Number(scanRes1.body?.data?.account_id), accountId); + assert.ok(String(scanRes1.body?.data?.real_name || '')); + assert.equal(scanRes1.body?.data?.status, 'scanned'); + + const scannedStateRes1 = await invokeSystemMethod('user.getBindWechatCode', {}, token); + assert.equal(scannedStateRes1.status, 200); + assert.equal(scannedStateRes1.body.flag, 'success'); + assert.equal(scannedStateRes1.body?.data?.status, 'scanned'); + assert.equal(String(scannedStateRes1.body?.data?.code || ''), code); const bindRes1 = await invokeGatewayMethod('user.bindAccountByTempCode', { code, @@ -46,8 +72,18 @@ describe('test/app/controller/gateway.user.bindAccountByTempCode.test.js', () => assert.equal(unbindRes.body?.data?.status, 'unbound'); assert.equal(Number(unbindRes.body?.data?.account_id), accountId); + const code2 = await ensurePendingCode(); + + const scanRes2 = await invokeGatewayMethod('user.getUserByTempCode', { code: code2 }); + assert.equal(scanRes2.status, 200); + assert.equal(scanRes2.body.flag, 'success'); + assert.equal(scanRes2.body.code, 200); + assert.equal(Number(scanRes2.body?.data?.account_id), accountId); + assert.ok(String(scanRes2.body?.data?.real_name || '')); + assert.equal(scanRes2.body?.data?.status, 'scanned'); + const bindRes2 = await invokeGatewayMethod('user.bindAccountByTempCode', { - code, + code: code2, ye4s_user_id: YE4S_TEST_USER_ID, }); assert.equal(bindRes2.status, 200); @@ -57,11 +93,10 @@ describe('test/app/controller/gateway.user.bindAccountByTempCode.test.js', () => assert.equal(Number(bindRes2.body?.data?.ye4s_user_id), YE4S_TEST_USER_ID); assert.equal(bindRes2.body?.data?.status, 'bound'); - const verifyRes = await invokeGatewayMethod('user.getUserByTempCode', { code }); - assert.equal(verifyRes.status, 200); - assert.equal(verifyRes.body.flag, 'success'); - assert.equal(verifyRes.body.code, 200); - assert.equal(Number(verifyRes.body?.data?.account_id), accountId); - assert.equal(verifyRes.body?.data?.status, 'bound'); + const boundStateRes = await invokeSystemMethod('user.getBindWechatCode', {}, token); + assert.equal(boundStateRes.status, 200); + assert.equal(boundStateRes.body.flag, 'success'); + assert.equal(boundStateRes.body?.data?.status, 'bound'); + assert.equal(String(boundStateRes.body?.data?.code || ''), ''); }); }); diff --git a/test/app/controller/system.setting.permission.test.js b/test/app/controller/system.setting.permission.test.js new file mode 100644 index 0000000..3a18fd9 --- /dev/null +++ b/test/app/controller/system.setting.permission.test.js @@ -0,0 +1,234 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { + getAuthToken, + invokeSystemMethod, +} = require('../../support/system_method_client'); + +const EXTRA_HEADERS = { + platform: 'web', + project: 'all', +}; + +describe('test/app/controller/system.setting.permission.test.js', () => { + let token = ''; + let anchorPermissionId = 0; + let createdPermissionId = 0; + + before(async () => { + const auth = await getAuthToken({ forceLogin: true }); + token = auth.token; + + const listRes = await invokeSystemMethod('setting.permission.list', {}, token, EXTRA_HEADERS); + assert.equal(listRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + assert.equal(listRes.body.code, 200); + + const permissions = Array.isArray(listRes.body?.data?.permissions) ? listRes.body.data.permissions : []; + assert.ok(permissions.length > 0, '当前账号无可用权限,无法执行回归'); + anchorPermissionId = Number(permissions[0].permission_id || 0); + assert.ok(anchorPermissionId > 0, '锚点权限ID无效'); + }); + + after(async () => { + if (createdPermissionId > 0) { + await invokeSystemMethod('setting.permission.delete', { + ids: [ createdPermissionId ], + }, token, EXTRA_HEADERS); + } + }); + + it('should reject out-of-scope permission update', async () => { + const updateRes = await invokeSystemMethod('setting.permission.update', { + permission_id: 999999999, + name: 'out_of_scope_update', + }, token, EXTRA_HEADERS); + + assert.equal(updateRes.status, 200); + assert.equal(updateRes.body.flag, 'failure'); + assert.ok([ 400, 404 ].includes(Number(updateRes.body.code)), `unexpected code: ${updateRes.body.code}`); + assert.match(String(updateRes.body.message || ''), /(超出当前登录工号可用权限集|权限不存在)/); + }); + + it('should create then update then delete permission successfully', async () => { + const suffix = Date.now(); + const path = `autotest.permission.${suffix}`; + + const addRes = await invokeSystemMethod('setting.permission.add', { + path, + type: 'btns', + name: `autotest_add_${suffix}`, + parent_id: anchorPermissionId, + meta_title: `autotest_meta_${suffix}`, + sort: 0, + hidden: 0, + always_show: 0, + status: 1, + }, token, EXTRA_HEADERS); + + assert.equal(addRes.status, 200); + assert.equal(addRes.body.flag, 'success'); + assert.equal(addRes.body.code, 200); + createdPermissionId = Number(addRes.body?.data?.permission_id || 0); + assert.ok(createdPermissionId > 0, '新增权限失败,permission_id 无效'); + + const updateRes = await invokeSystemMethod('setting.permission.update', { + permission_id: createdPermissionId, + name: `autotest_update_${suffix}`, + meta_title: `autotest_meta_update_${suffix}`, + status: 1, + }, token, EXTRA_HEADERS); + + assert.equal(updateRes.status, 200); + assert.equal(updateRes.body.flag, 'success'); + assert.equal(updateRes.body.code, 200); + assert.equal(Number(updateRes.body?.data?.permission_id), createdPermissionId); + + const deleteRes = await invokeSystemMethod('setting.permission.delete', { + ids: [ createdPermissionId ], + }, token, EXTRA_HEADERS); + + assert.equal(deleteRes.status, 200); + assert.equal(deleteRes.body.flag, 'success'); + assert.equal(deleteRes.body.code, 200); + const deletedIds = Array.isArray(deleteRes.body?.data?.deleted_ids) ? deleteRes.body.data.deleted_ids : []; + assert.ok(deletedIds.includes(createdPermissionId), '删除结果中未包含新建权限ID'); + + const deleteAgainRes = await invokeSystemMethod('setting.permission.delete', { + ids: [ createdPermissionId ], + }, token, EXTRA_HEADERS); + assert.equal(deleteAgainRes.status, 200); + assert.equal(deleteAgainRes.body.flag, 'success'); + assert.equal(deleteAgainRes.body.code, 200); + const alreadyDeletedIds = Array.isArray(deleteAgainRes.body?.data?.already_deleted_ids) + ? deleteAgainRes.body.data.already_deleted_ids + : []; + assert.ok(alreadyDeletedIds.includes(createdPermissionId), '二次删除未返回 already_deleted_ids'); + + createdPermissionId = 0; + }); + + it('should split deleted_ids and already_deleted_ids in mixed batch delete', async () => { + const suffix = Date.now(); + const firstPath = `autotest.permission.mixed.first.${suffix}`; + const secondPath = `autotest.permission.mixed.second.${suffix}`; + let firstPermissionId = 0; + let secondPermissionId = 0; + + try { + const addFirstRes = await invokeSystemMethod('setting.permission.add', { + path: firstPath, + type: 'btns', + name: `autotest_mixed_first_${suffix}`, + parent_id: anchorPermissionId, + status: 1, + }, token, EXTRA_HEADERS); + assert.equal(addFirstRes.status, 200); + assert.equal(addFirstRes.body.flag, 'success'); + assert.equal(addFirstRes.body.code, 200); + firstPermissionId = Number(addFirstRes.body?.data?.permission_id || 0); + assert.ok(firstPermissionId > 0, 'first permission_id 无效'); + + const addSecondRes = await invokeSystemMethod('setting.permission.add', { + path: secondPath, + type: 'btns', + name: `autotest_mixed_second_${suffix}`, + parent_id: anchorPermissionId, + status: 1, + }, token, EXTRA_HEADERS); + assert.equal(addSecondRes.status, 200); + assert.equal(addSecondRes.body.flag, 'success'); + assert.equal(addSecondRes.body.code, 200); + secondPermissionId = Number(addSecondRes.body?.data?.permission_id || 0); + assert.ok(secondPermissionId > 0, 'second permission_id 无效'); + + const preDeleteRes = await invokeSystemMethod('setting.permission.delete', { + ids: [ firstPermissionId ], + }, token, EXTRA_HEADERS); + assert.equal(preDeleteRes.status, 200); + assert.equal(preDeleteRes.body.flag, 'success'); + assert.equal(preDeleteRes.body.code, 200); + + const mixedDeleteRes = await invokeSystemMethod('setting.permission.delete', { + ids: [ firstPermissionId, secondPermissionId ], + }, token, EXTRA_HEADERS); + + assert.equal(mixedDeleteRes.status, 200); + assert.equal(mixedDeleteRes.body.flag, 'success'); + assert.equal(mixedDeleteRes.body.code, 200); + + const deletedIds = Array.isArray(mixedDeleteRes.body?.data?.deleted_ids) + ? mixedDeleteRes.body.data.deleted_ids + : []; + const alreadyDeletedIds = Array.isArray(mixedDeleteRes.body?.data?.already_deleted_ids) + ? mixedDeleteRes.body.data.already_deleted_ids + : []; + + assert.ok(deletedIds.includes(secondPermissionId), 'mixed 删除结果中缺少启用权限ID'); + assert.ok(alreadyDeletedIds.includes(firstPermissionId), 'mixed 删除结果中缺少已删除权限ID'); + + firstPermissionId = 0; + secondPermissionId = 0; + } finally { + const cleanupIds = [ firstPermissionId, secondPermissionId ].filter(id => Number(id) > 0); + if (cleanupIds.length > 0) { + await invokeSystemMethod('setting.permission.delete', { + ids: cleanupIds, + }, token, EXTRA_HEADERS); + } + } + }); + + it('should reject mixed delete when ids contain out-of-scope permission', async () => { + const suffix = Date.now(); + const path = `autotest.permission.mixed.outscope.${suffix}`; + let permissionId = 0; + + try { + const addRes = await invokeSystemMethod('setting.permission.add', { + path, + type: 'btns', + name: `autotest_mixed_outscope_${suffix}`, + parent_id: anchorPermissionId, + status: 1, + }, token, EXTRA_HEADERS); + + assert.equal(addRes.status, 200); + assert.equal(addRes.body.flag, 'success'); + assert.equal(addRes.body.code, 200); + permissionId = Number(addRes.body?.data?.permission_id || 0); + assert.ok(permissionId > 0, 'permission_id 无效'); + + const mixedRes = await invokeSystemMethod('setting.permission.delete', { + ids: [ permissionId, 999999999 ], + }, token, EXTRA_HEADERS); + + assert.equal(mixedRes.status, 200); + assert.equal(mixedRes.body.flag, 'failure'); + assert.ok([ 400, 404 ].includes(Number(mixedRes.body.code)), `unexpected code: ${mixedRes.body.code}`); + assert.match(String(mixedRes.body.message || ''), /(超出当前登录工号可用权限集|权限不存在)/); + + // 失败后应保持原子性:合法权限仍可被正常删除(说明前一次未误删) + const verifyDeleteRes = await invokeSystemMethod('setting.permission.delete', { + ids: [ permissionId ], + }, token, EXTRA_HEADERS); + + assert.equal(verifyDeleteRes.status, 200); + assert.equal(verifyDeleteRes.body.flag, 'success'); + assert.equal(verifyDeleteRes.body.code, 200); + const deletedIds = Array.isArray(verifyDeleteRes.body?.data?.deleted_ids) + ? verifyDeleteRes.body.data.deleted_ids + : []; + assert.ok(deletedIds.includes(permissionId), '混入越权ID失败后,合法权限不应被提前删除'); + + permissionId = 0; + } finally { + if (permissionId > 0) { + await invokeSystemMethod('setting.permission.delete', { + ids: [ permissionId ], + }, token, EXTRA_HEADERS); + } + } + }); +}); diff --git a/test/app/controller/system.user.getLoginWechatCode.test.js b/test/app/controller/system.user.getLoginWechatCode.test.js new file mode 100644 index 0000000..0507107 --- /dev/null +++ b/test/app/controller/system.user.getLoginWechatCode.test.js @@ -0,0 +1,17 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { invokeSystemMethod } = require('../../support/system_method_client'); + +describe('test/app/controller/system.user.getLoginWechatCode.test.js', () => { + it('should return login code without Authorization token', async () => { + const res = await invokeSystemMethod('user.getLoginWechatCode', {}); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + assert.match(String(res.body?.data?.client_code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/); + assert.match(String(res.body?.data?.code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/); + assert.equal(res.body?.data?.status, 'pending'); + }); +}); diff --git a/test/app/controller/system.user.loginByCode.test.js b/test/app/controller/system.user.loginByCode.test.js index 928ff74..af3dad0 100644 --- a/test/app/controller/system.user.loginByCode.test.js +++ b/test/app/controller/system.user.loginByCode.test.js @@ -3,11 +3,14 @@ const assert = require('node:assert/strict'); const { invokeSystemMethod } = require('../../support/system_method_client'); -const VALID_LOGIN_CODE = process.env.SYSTEM_TEST_LOGIN_CODE - || 'eyJ1dWlkIjoiMDg2MTk4MzQtY2FhYS00OTIyLWJmNjctODc5M2U2Y2MwYzJkIn0='; +const VALID_LOGIN_CODE = String(process.env.SYSTEM_TEST_LOGIN_CODE || '').trim(); describe('test/app/controller/system.user.loginByCode.test.js', () => { - it('should login successfully when code is valid', async () => { + it('should login successfully when code is valid', async function() { + if (!VALID_LOGIN_CODE) { + this.skip(); + } + const res = await invokeSystemMethod('user.loginByCode', { code: VALID_LOGIN_CODE, }); @@ -30,23 +33,23 @@ describe('test/app/controller/system.user.loginByCode.test.js', () => { assert.match(String(res.body.message || ''), /code/); }); - it('should fail when code is not valid base64 json', async () => { + it('should fail when code does not exist', async () => { const code = `INVALID_CODE_${Date.now()}`; const res = await invokeSystemMethod('user.loginByCode', { code }); assert.equal(res.status, 200); assert.equal(res.body.flag, 'failure'); assert.equal(res.body.code, 0); - assert.match(String(res.body.message || ''), /无效的登录码格式/); + assert.match(String(res.body.message || ''), /登录码不存在|登录失败/); }); - it('should fail when decoded payload does not contain uuid', async () => { - const code = Buffer.from(JSON.stringify({ foo: 'bar' }), 'utf8').toString('base64'); + it('should fail when code format is valid but not matched', async () => { + const code = 'A1B2C3'; const res = await invokeSystemMethod('user.loginByCode', { code }); assert.equal(res.status, 200); assert.equal(res.body.flag, 'failure'); assert.equal(res.body.code, 0); - assert.match(String(res.body.message || ''), /uuid/); + assert.match(String(res.body.message || ''), /登录码不存在|登录失败/); }); }); diff --git a/test/app/service/systems/auth.user.bindWechatCacheExpiry.test.js b/test/app/service/systems/auth.user.bindWechatCacheExpiry.test.js new file mode 100644 index 0000000..620c21e --- /dev/null +++ b/test/app/service/systems/auth.user.bindWechatCacheExpiry.test.js @@ -0,0 +1,152 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const UserService = require('../../../../app/service/systems/auth/user'); + +function createServiceHarness() { + const cacheWrites = []; + const cacheStore = new Map(); + + const app = { + async setCacheAsync(cacheKey, data, expireSeconds = 300) { + cacheWrites.push({ + cacheKey, + data, + expireSeconds, + }); + + if (data === null || data === undefined || expireSeconds <= 1) { + cacheStore.delete(cacheKey); + return; + } + + cacheStore.set(cacheKey, data); + }, + async getCacheAsync(cacheKey) { + return cacheStore.has(cacheKey) ? cacheStore.get(cacheKey) : null; + }, + coreLogger: { + warn() {}, + error() {}, + }, + }; + + const ctx = { + app, + userId: 1001, + user: { + id: 1001, + }, + }; + + const service = new UserService(ctx); + + return { + app, + ctx, + service, + cacheWrites, + cacheStore, + }; +} + +describe('test/app/service/systems/auth.user.bindWechatCacheExpiry.test.js', () => { + it('should generate pending code with fixed 60s ttl and keep same code without extending', async () => { + const fixedNow = 1760000000000; + const originalNow = Date.now; + Date.now = () => fixedNow; + + try { + const { service, cacheWrites } = createServiceHarness(); + service.findYe4sBindingByAccountId = async () => null; + + const first = await service.refreshWechatBindState(1001, null, { + forceNewCode: false, + }); + + assert.equal(first.state.status, 'pending'); + assert.match(String(first.state.code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/); + assert.equal(first.state.expires_at, fixedNow + 60000); + + const firstWriteCount = cacheWrites.length; + assert.equal(firstWriteCount, 2); + for (const write of cacheWrites) { + assert.equal(write.expireSeconds, 60); + } + + const second = await service.refreshWechatBindState(1001, first.state, { + forceNewCode: false, + }); + + assert.equal(second.state.code, first.state.code); + assert.equal(second.state.status, 'pending'); + assert.equal(cacheWrites.length, firstWriteCount); + } finally { + Date.now = originalNow; + } + }); + + it('should return scanned status when scan key exists', async () => { + const fixedNow = 1760000000000; + const originalNow = Date.now; + Date.now = () => fixedNow; + + try { + const { service, cacheStore } = createServiceHarness(); + service.findYe4sBindingByAccountId = async () => null; + + const pending = await service.refreshWechatBindState(1001, null, { + forceNewCode: false, + }); + const code = pending.state.code; + + cacheStore.set(`user:wechat:bind:scan:${code}`, { + account_id: 1001, + code, + status: 'scanned', + scanned_at: new Date(fixedNow + 1000).toISOString(), + }); + + const result = await service.refreshWechatBindState(1001, pending.state, { + forceNewCode: false, + }); + + assert.equal(result.state.status, 'scanned'); + assert.equal(result.state.code, code); + assert.ok(result.state.scanned_at); + } finally { + Date.now = originalNow; + } + }); + + it('should rotate code when forceNewCode is enabled', async () => { + const fixedNow = 1760000000000; + const originalNow = Date.now; + Date.now = () => fixedNow; + + try { + const { service, cacheWrites } = createServiceHarness(); + service.findYe4sBindingByAccountId = async () => null; + + const oldState = { + account_id: 1001, + status: 'pending', + code: 'A1B2C3', + expires_at: fixedNow + 30000, + }; + + const result = await service.refreshWechatBindState(1001, oldState, { + forceNewCode: true, + }); + + assert.equal(result.state.status, 'pending'); + assert.notEqual(result.state.code, oldState.code); + assert.equal(result.state.expires_at, fixedNow + 60000); + + const oldCodeInvalidation = cacheWrites.find(item => item && item.data === null && item.expireSeconds === 1); + assert.ok(oldCodeInvalidation); + } finally { + Date.now = originalNow; + } + }); +}); diff --git a/test/app/service/systems/auth.user.loginWechatCode.test.js b/test/app/service/systems/auth.user.loginWechatCode.test.js new file mode 100644 index 0000000..7d559fd --- /dev/null +++ b/test/app/service/systems/auth.user.loginWechatCode.test.js @@ -0,0 +1,103 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const UserService = require('../../../../app/service/systems/auth/user'); + +function createServiceHarness() { + const cacheWrites = []; + const cacheStore = new Map(); + + const app = { + async setCacheAsync(cacheKey, data, expireSeconds = 300) { + cacheWrites.push({ + cacheKey, + data, + expireSeconds, + }); + + if (data === null || data === undefined || expireSeconds <= 1) { + cacheStore.delete(cacheKey); + return; + } + + cacheStore.set(cacheKey, data); + }, + async getCacheAsync(cacheKey) { + return cacheStore.has(cacheKey) ? cacheStore.get(cacheKey) : null; + }, + coreLogger: { + warn() {}, + error() {}, + }, + }; + + const ctx = { + app, + }; + + const service = new UserService(ctx); + + return { + app, + ctx, + service, + cacheWrites, + cacheStore, + }; +} + +describe('test/app/service/systems/auth.user.loginWechatCode.test.js', () => { + it('should generate client code and login code when client code is missing', async () => { + const { service, cacheWrites } = createServiceHarness(); + + const result = await service.getLoginWechatCode({}); + + assert.equal(result.success, true); + assert.equal(result.code, 200); + assert.match(String(result.data.client_code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/); + assert.match(String(result.data.code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/); + assert.equal(result.data.status, 'pending'); + assert.ok(String(result.message || '').includes('客户端编码')); + + const writesWithState = cacheWrites.filter(item => item && item.data && item.data.client_code === result.data.client_code); + assert.equal(writesWithState.length, 2); + for (const write of writesWithState) { + assert.equal(write.expireSeconds, 60); + } + }); + + it('should refresh login code after long poll when client code is provided', async () => { + const { service, cacheWrites } = createServiceHarness(); + service.waitForLoginCodeRefresh = async () => {}; + + const first = await service.getLoginWechatCode({}); + const firstCode = String(first.data.code || ''); + const clientCode = String(first.data.client_code || ''); + + const second = await service.getLoginWechatCode({ + clientCode, + }); + + assert.equal(second.success, true); + assert.equal(second.code, 200); + assert.equal(String(second.data.client_code || ''), clientCode); + assert.match(String(second.data.code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/); + assert.notEqual(String(second.data.code || ''), firstCode); + assert.ok(String(second.message || '').includes('长轮询结束')); + + const invalidationWrite = cacheWrites.find(item => item && item.data === null && item.expireSeconds === 1); + assert.ok(invalidationWrite); + }); + + it('should fail when provided client code format is invalid', async () => { + const { service } = createServiceHarness(); + + const result = await service.getLoginWechatCode({ + clientCode: 'abc', + }); + + assert.equal(result.success, false); + assert.equal(result.code, 0); + assert.match(String(result.message || ''), /客户端编码/); + }); +});