feat: refine setting role/account/permission auth and tests

This commit is contained in:
liufumingren 2026-03-31 00:35:53 +08:00
parent 2f838186de
commit 26af1a7039
24 changed files with 5108 additions and 487 deletions

View File

@ -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`,避免运行时自动写库。

View File

@ -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' ],
},
],
});

View File

@ -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;

View File

@ -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<boolean>}
* @return {Promise<boolean>} 是否有权限
*/
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) {

View File

@ -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,
});
}
}
/**

View File

@ -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;

View File

@ -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;

View File

@ -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);

File diff suppressed because it is too large Load Diff

View File

@ -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)),
},
};
}
}

View File

@ -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;

View File

@ -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;

View File

@ -172,6 +172,7 @@ module.exports = appInfo => {
config.poloapi ={
}
config.debug = false; // 生成环境默认关闭 debug,开发环境通过 config.local.js 开启
config.printService = {
url: 'http://printer.wms.gztbyc.com',
};

View File

@ -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": "该仓库下打印台名称已存在且可用"
}
]
}
]
}
]
}

File diff suppressed because it is too large Load Diff

View File

@ -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"
},

View File

@ -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);
});

View File

@ -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`)

View File

@ -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 || ''), '');
});
});

View File

@ -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);
}
}
});
});

View File

@ -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');
});
});

View File

@ -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 || ''), /登录码不存在|登录失败/);
});
});

View File

@ -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;
}
});
});

View File

@ -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 || ''), /客户端编码/);
});
});