802 lines
23 KiB
JavaScript
802 lines
23 KiB
JavaScript
'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;
|
||
}
|
||
|
||
<<<<<<< HEAD
|
||
async buildRolePermissionMap(roleRows) {
|
||
const { service } = this.ctx;
|
||
const rows = Array.isArray(roleRows) ? roleRows : [];
|
||
const permissionMap = new Map();
|
||
|
||
for (const row of rows) {
|
||
const roleId = Number(row && row.id);
|
||
if (!Number.isFinite(roleId) || roleId <= 0) {
|
||
continue;
|
||
}
|
||
|
||
const directPermissionIds = service.systems.auth.rolePermission.toApiPermissionIds(row.permissions);
|
||
permissionMap.set(roleId, directPermissionIds);
|
||
}
|
||
|
||
return permissionMap;
|
||
}
|
||
|
||
buildRoleTree(roleRows, rootRoleIds, selectedRoleIdSet, rolePermissionMap = new Map()) {
|
||
=======
|
||
buildRoleTree(roleRows, rootRoleIds, selectedRoleIdSet) {
|
||
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
|
||
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),
|
||
<<<<<<< HEAD
|
||
permission_ids: rolePermissionMap.get(roleId) || [],
|
||
=======
|
||
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
|
||
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) {
|
||
<<<<<<< HEAD
|
||
if (inputPermissionIds === '*') {
|
||
return [ '*' ];
|
||
}
|
||
|
||
if (typeof inputPermissionIds === 'string') {
|
||
const trimmed = inputPermissionIds.trim();
|
||
if (!trimmed) {
|
||
throw this.createError('permission_ids 参数不能为空', 400);
|
||
}
|
||
if (trimmed === '*') {
|
||
return [ '*' ];
|
||
}
|
||
|
||
try {
|
||
const parsed = JSON.parse(trimmed);
|
||
return this.normalizePermissionIds(parsed);
|
||
} catch (_) {
|
||
if (trimmed.includes(',')) {
|
||
return this.normalizePermissionIds(trimmed.split(','));
|
||
}
|
||
throw this.createError('permission_ids 必须是正整数数组或 ["*"]', 400);
|
||
}
|
||
}
|
||
|
||
=======
|
||
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
|
||
if (!Array.isArray(inputPermissionIds)) {
|
||
throw this.createError('permission_ids 参数不能为空', 400);
|
||
}
|
||
|
||
<<<<<<< HEAD
|
||
if (inputPermissionIds.some(item => typeof item === 'string' && item.trim() === '*')) {
|
||
return [ '*' ];
|
||
}
|
||
|
||
=======
|
||
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
|
||
const permissionIds = [];
|
||
for (const permissionId of inputPermissionIds) {
|
||
const normalized = Number(permissionId);
|
||
if (!Number.isFinite(normalized) || normalized <= 0) {
|
||
<<<<<<< HEAD
|
||
throw this.createError('permission_ids 必须是正整数数组或 ["*"]', 400);
|
||
}
|
||
permissionIds.push(Math.floor(normalized));
|
||
=======
|
||
throw this.createError('permission_ids 必须是正整数数组', 400);
|
||
}
|
||
permissionIds.push(normalized);
|
||
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
|
||
}
|
||
|
||
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;
|
||
<<<<<<< HEAD
|
||
if (!Array.isArray(permissionIds) || permissionIds.length === 0) {
|
||
return;
|
||
}
|
||
|
||
if (permissionIds.includes('*')) {
|
||
=======
|
||
if (permissionIds.length === 0) {
|
||
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
|
||
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);
|
||
}
|
||
<<<<<<< HEAD
|
||
}
|
||
|
||
async replaceRolePermissions(roleId, permissionIds, transaction) {
|
||
return await this.ctx.service.systems.auth.rolePermission.assignPermissions(roleId, permissionIds, {
|
||
transaction,
|
||
});
|
||
=======
|
||
|
||
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 });
|
||
}
|
||
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
|
||
}
|
||
|
||
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 = {
|
||
<<<<<<< HEAD
|
||
status: includeDisabled ? { [Op.in]: [0, 1] } : 1,
|
||
=======
|
||
status: includeDisabled ? { [Op.in]: [ 0, 1 ] } : 1,
|
||
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
|
||
[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',
|
||
<<<<<<< HEAD
|
||
'permissions',
|
||
=======
|
||
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
|
||
],
|
||
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: [],
|
||
},
|
||
};
|
||
}
|
||
|
||
<<<<<<< HEAD
|
||
const currentRoleIdSet = new Set(currentRoleRows.map(item => Number(item.id)));
|
||
|
||
// 仅返回当前角色的下级角色树,不返回自己及同级角色。
|
||
const subordinateRootRoleIds = new Set(roleRows
|
||
.filter(item => currentRoleIdSet.has(Number(item.pid || 0)))
|
||
.filter(item => this.isRoleVisibleInScope(item, currentRoleRows, storeId, includeSystem))
|
||
.map(item => Number(item.id)));
|
||
|
||
if (subordinateRootRoleIds.size === 0) {
|
||
return {
|
||
code: 200,
|
||
data: {
|
||
employee_id: employee ? Number(employee.id) : null,
|
||
roles: [],
|
||
},
|
||
};
|
||
}
|
||
|
||
const visibleRoleIds = this.collectDescendantRoleIds(roleRows, Array.from(subordinateRootRoleIds));
|
||
=======
|
||
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 ]);
|
||
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
|
||
|
||
const visibleRoleRows = roleRows
|
||
.filter(item => visibleRoleIds.has(Number(item.id)))
|
||
.filter(item => this.isRoleVisibleInScope(item, currentRoleRows, storeId, includeSystem));
|
||
const rootRoleIds = new Set(visibleRoleRows
|
||
<<<<<<< HEAD
|
||
.filter(item => subordinateRootRoleIds.has(Number(item.id)))
|
||
=======
|
||
.filter(item => sameLevelRoleIds.has(Number(item.id)))
|
||
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
|
||
.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)));
|
||
}
|
||
|
||
<<<<<<< HEAD
|
||
const rolePermissionMap = await this.buildRolePermissionMap(visibleRoleRows);
|
||
const roles = this.buildRoleTree(visibleRoleRows, rootRoleIds, selectedRoleIdSet, rolePermissionMap);
|
||
=======
|
||
const roles = this.buildRoleTree(visibleRoleRows, rootRoleIds, selectedRoleIdSet);
|
||
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
|
||
|
||
return {
|
||
code: 200,
|
||
data: {
|
||
employee_id: employee ? Number(employee.id) : null,
|
||
roles,
|
||
},
|
||
};
|
||
}
|
||
|
||
<<<<<<< HEAD
|
||
async permission(data = {}) {
|
||
return this.ctx.service.systems.setting.permission.list(data);
|
||
}
|
||
|
||
=======
|
||
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
|
||
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);
|
||
}
|
||
|
||
<<<<<<< HEAD
|
||
=======
|
||
if (deletedIds.length > 0) {
|
||
await ctx.model.RolePermission.destroy({
|
||
where: {
|
||
role_id: deletedIds,
|
||
},
|
||
transaction,
|
||
});
|
||
}
|
||
|
||
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
|
||
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;
|