- 新增 access 服务与 /api/access/context:按角色组权限判定集团 / 所在公司范围 - 菜单树按范围裁剪:所在公司范围仅保留「员工档案」,其余系统管理菜单隐藏 - 员工档案:角色组与所属公司必填;所在公司范围仅可见、仅可关联自己所属公司 - 创建者(所有者)行禁止编辑与解绑,且不可被移出主体;禁止新建所有者 - 所在公司范围禁止修改自己或他人的角色组、所属公司 - 新增员工时邮箱已注册则复用既有账号(reused),不再报「该邮箱已注册」 - 迁移:将所有者 role_id 统一指向系统管理员角色组 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
685 lines
24 KiB
JavaScript
685 lines
24 KiB
JavaScript
'use strict';
|
||
|
||
const { Controller } = require('egg');
|
||
const crypto = require('crypto');
|
||
const { generateSalt, hashPassword } = require('../lib/password');
|
||
const { parsePagination, buildPageResult } = require('../lib/pagination');
|
||
|
||
/**
|
||
* @controller PrincipalUserController 主体用户关联管理
|
||
*/
|
||
class PrincipalUserController extends Controller {
|
||
/**
|
||
* @summary 关联列表
|
||
* @description 分页查询主体与用户的关联关系,可按主体或用户过滤;
|
||
* 所在公司权限的账号仅返回自己所属公司范围内的员工
|
||
* @router get /api/principal-users
|
||
* @apikey
|
||
* @request query integer page 页码,默认 1
|
||
* @request query integer pageSize 每页条数,默认 20
|
||
* @request query integer principal_id 主体ID(必填,需当前账号已绑定该主体)
|
||
* @request query integer user_id 用户ID,不传则不过滤
|
||
* @request query string role 角色标识,精确匹配
|
||
* @request query integer role_id 角色组ID
|
||
* @request query integer status 状态:1启用 0禁用,不传则不过滤
|
||
* @response 200 principalUserListResponse success
|
||
*/
|
||
async index() {
|
||
const { ctx } = this;
|
||
const Op = this.app.Sequelize.Op;
|
||
const { page, pageSize, offset, limit } = parsePagination(ctx.query);
|
||
const { user_id: userId, role, role_id: roleId, status } = ctx.query;
|
||
const principalId = ctx.state.principalId;
|
||
|
||
const where = {};
|
||
where.principal_id = principalId;
|
||
if (userId) where.user_id = Number(userId);
|
||
if (role) where.role = role;
|
||
if (roleId !== undefined && roleId !== '') where.role_id = Number(roleId);
|
||
if (status !== undefined && status !== '') where.status = Number(status);
|
||
|
||
// 所在公司权限:仅可见自己所属公司的员工
|
||
const access = await ctx.service.access.resolve(ctx.userId, principalId);
|
||
if (!access.isGroup) {
|
||
const links = await ctx.model.PrincipalUserCompany.findAll({
|
||
where: { subsidiary_id: { [Op.in]: access.ownCompanyIds } },
|
||
attributes: [ 'principal_user_id' ],
|
||
raw: true,
|
||
});
|
||
where.id = { [Op.in]: links.map(row => Number(row.principal_user_id)) };
|
||
}
|
||
|
||
const { count, rows } = await ctx.model.PrincipalUser.findAndCountAll({
|
||
where,
|
||
offset,
|
||
limit,
|
||
// 员工与所属公司是一对多 join,需去重计数
|
||
distinct: true,
|
||
order: [[ 'id', 'DESC' ]],
|
||
include: [
|
||
{ model: ctx.model.User, as: 'user', attributes: { exclude: [ 'password', 'salt' ] } },
|
||
{ model: ctx.model.Role, as: 'roleGroup', attributes: [ 'id', 'name', 'code', 'is_system' ], required: false },
|
||
{
|
||
model: ctx.model.PrincipalUserCompany,
|
||
as: 'companies',
|
||
attributes: [ 'id', 'subsidiary_id' ],
|
||
required: false,
|
||
include: [
|
||
{ model: ctx.model.PrincipalSubsidiary, as: 'subsidiary', attributes: [ 'id', 'name' ], required: false },
|
||
],
|
||
},
|
||
],
|
||
});
|
||
|
||
const list = rows.map(row => {
|
||
const plain = row.toJSON();
|
||
plain.company_ids = (plain.companies || []).map(item => Number(item.subsidiary_id));
|
||
plain.companies = (plain.companies || []).map(item => ({
|
||
id: Number(item.id),
|
||
subsidiary_id: Number(item.subsidiary_id),
|
||
name: item.subsidiary ? item.subsidiary.name : '',
|
||
}));
|
||
return plain;
|
||
});
|
||
|
||
ctx.body = { code: 0, message: 'success', data: buildPageResult(list, count, { page, pageSize }) };
|
||
}
|
||
|
||
/**
|
||
* @summary 关联详情
|
||
* @description 按主键查询关联记录,并带出用户与主体信息
|
||
* @router get /api/principal-users/{id}
|
||
* @apikey
|
||
* @request path integer *id 关联记录主键ID
|
||
* @response 200 baseResponse success
|
||
*/
|
||
async show() {
|
||
const { ctx } = this;
|
||
const relation = await ctx.model.PrincipalUser.findByPk(ctx.params.id, {
|
||
include: [
|
||
{ model: ctx.model.User, as: 'user', attributes: { exclude: [ 'password', 'salt' ] } },
|
||
{ model: ctx.model.Principal, as: 'principal' },
|
||
{ model: ctx.model.Role, as: 'roleGroup', attributes: [ 'id', 'name', 'code', 'is_system' ], required: false },
|
||
{
|
||
model: ctx.model.PrincipalUserCompany,
|
||
as: 'companies',
|
||
attributes: [ 'id', 'subsidiary_id' ],
|
||
required: false,
|
||
include: [
|
||
{ model: ctx.model.PrincipalSubsidiary, as: 'subsidiary', attributes: [ 'id', 'name' ], required: false },
|
||
],
|
||
},
|
||
],
|
||
});
|
||
|
||
if (!relation) {
|
||
ctx.status = 404;
|
||
ctx.body = { code: 404, message: '关联记录不存在' };
|
||
return;
|
||
}
|
||
|
||
ctx.body = { code: 0, message: 'success', data: relation };
|
||
}
|
||
|
||
/**
|
||
* @summary 绑定用户到主体
|
||
* @description 建立主体与用户的关联;同一主体下同一用户仅允许一条记录
|
||
* @router post /api/principal-users
|
||
* @apikey
|
||
* @request body bindPrincipalUserRequest *body
|
||
* @response 200 baseResponse success
|
||
*/
|
||
async create() {
|
||
const { ctx } = this;
|
||
const body = ctx.request.body || {};
|
||
const { principal_id: principalId, user_id: userId } = body;
|
||
|
||
if (!principalId || !userId) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: 'principal_id 与 user_id 为必填项' };
|
||
return;
|
||
}
|
||
|
||
const exist = await ctx.model.PrincipalUser.findOne({
|
||
where: { principal_id: principalId, user_id: userId },
|
||
});
|
||
if (exist) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '该用户已绑定到该主体' };
|
||
return;
|
||
}
|
||
|
||
const role = body.role || 'member';
|
||
if (role === 'owner') {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '不能创建多个所有者(系统管理员)' };
|
||
return;
|
||
}
|
||
const companyIds = await this.resolveCompanyIds(body.company_ids, principalId);
|
||
// 所有者不参与公司关联,其余员工必须至少关联一家公司
|
||
if (role !== 'owner' && !companyIds.length) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '请为员工关联至少一家公司(下属公司)' };
|
||
return;
|
||
}
|
||
const allowed = await this.checkCompanyScope(principalId, companyIds);
|
||
if (!allowed.ok) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: allowed.message };
|
||
return;
|
||
}
|
||
|
||
const relation = await ctx.model.PrincipalUser.create({
|
||
principal_id: principalId,
|
||
user_id: userId,
|
||
name: body.name,
|
||
avatar: body.avatar,
|
||
role,
|
||
role_id: body.role_id == null || body.role_id === '' ? null : Number(body.role_id),
|
||
is_default: body.is_default === undefined ? 0 : Number(body.is_default),
|
||
status: body.status === undefined ? 1 : Number(body.status),
|
||
});
|
||
if (companyIds.length) await this.syncCompanies(relation, companyIds);
|
||
|
||
// 绑定关系变化:失效该用户缓存的主体ID列表与可选主体列表
|
||
await ctx.service.cache.invalidateUserPrincipals(userId);
|
||
ctx.body = { code: 0, message: 'success', data: { id: relation.id } };
|
||
}
|
||
|
||
/**
|
||
* @summary 邀请开通主体账号
|
||
* @description 传入邮箱、用户名称(写入主体账号关联表 principal_users.name)、主体ID、角色组与所属公司,
|
||
* 绑定到该主体;邮箱未注册时自动创建新用户(随机初始密码),已注册时复用现有账号并沿用原密码;
|
||
* 角色组必选,除所有者外必须至少关联一家公司(所在公司权限的账号只能关联自己所属的公司);
|
||
* 新建账号时返回明文随机密码,需由调用方妥善交付给被邀请人;同一邮箱不能在同一主体重复添加
|
||
* @router post /api/principal-users/invite
|
||
* @apikey
|
||
* @request body invitePrincipalUserRequest *body
|
||
* @response 200 invitePrincipalUserResponse success
|
||
*/
|
||
async invite() {
|
||
const { ctx } = this;
|
||
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||
const {
|
||
email,
|
||
name,
|
||
avatar,
|
||
principal_id: principalId,
|
||
role_id: bodyRoleId,
|
||
company_ids: bodyCompanyIds,
|
||
} = ctx.request.body;
|
||
|
||
if (!email || !EMAIL_REGEX.test(email)) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '请填写正确的邮箱地址' };
|
||
return;
|
||
}
|
||
if (!name) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '用户名称 name 为必填项' };
|
||
return;
|
||
}
|
||
if (!principalId) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '主体ID principal_id 为必填项' };
|
||
return;
|
||
}
|
||
|
||
// 主体必须存在,给出明确提示
|
||
const principal = await ctx.model.Principal.findByPk(principalId);
|
||
if (!principal) {
|
||
ctx.status = 404;
|
||
ctx.body = { code: 404, message: '主体不存在' };
|
||
return;
|
||
}
|
||
|
||
// 邮箱已注册时复用现有账号:只要该账号尚未属于当前主体,就直接新增主体关联(沿用原密码登录)
|
||
const existUser = await ctx.model.User.findOne({ where: { email } });
|
||
let existingUser = null;
|
||
if (existUser) {
|
||
const bound = await ctx.model.PrincipalUser.findOne({
|
||
where: { principal_id: principalId, user_id: existUser.id },
|
||
});
|
||
if (bound) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '该员工已在当前主体中(无需重复添加)' };
|
||
return;
|
||
}
|
||
existingUser = existUser;
|
||
}
|
||
|
||
// 角色组必选(员工档案创建时必须指定角色)
|
||
if (bodyRoleId == null || bodyRoleId === '') {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '请为员工选择角色组' };
|
||
return;
|
||
}
|
||
const role = await ctx.model.Role.findByPk(Number(bodyRoleId));
|
||
if (!role) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '角色组不存在' };
|
||
return;
|
||
}
|
||
const roleId = Number(role.id);
|
||
const roleAllowed = await this.checkRoleScope(principalId, roleId);
|
||
if (!roleAllowed.ok) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: roleAllowed.message };
|
||
return;
|
||
}
|
||
|
||
// 所属公司:仅下属公司中、属于当前主体的公司可关联;新建员工不是所有者,必须至少一家
|
||
const companyIds = await this.resolveCompanyIds(bodyCompanyIds, principalId);
|
||
if (!companyIds.length) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '请为员工关联至少一家公司(组织架构 → 下属公司)' };
|
||
return;
|
||
}
|
||
const allowed = await this.checkCompanyScope(principalId, companyIds);
|
||
if (!allowed.ok) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: allowed.message };
|
||
return;
|
||
}
|
||
|
||
// 已注册账号:只新增主体关联与所属公司,不改密码(沿用原账号密码登录)
|
||
if (existingUser) {
|
||
const transaction = await ctx.model.transaction();
|
||
try {
|
||
const relation = await ctx.model.PrincipalUser.create({
|
||
principal_id: principalId,
|
||
user_id: existingUser.id,
|
||
name: String(name).trim(),
|
||
avatar: avatar ? String(avatar).trim() : null,
|
||
role: 'member',
|
||
role_id: roleId,
|
||
is_default: 0,
|
||
status: 1,
|
||
}, { transaction });
|
||
|
||
await ctx.model.PrincipalUserCompany.bulkCreate(
|
||
companyIds.map(subsidiaryId => ({
|
||
principal_id: Number(principalId),
|
||
principal_user_id: relation.id,
|
||
subsidiary_id: subsidiaryId,
|
||
})),
|
||
{ transaction }
|
||
);
|
||
|
||
await transaction.commit();
|
||
await ctx.service.cache.invalidateUserPrincipals(existingUser.id);
|
||
|
||
ctx.body = {
|
||
code: 0,
|
||
message: 'success',
|
||
data: {
|
||
user_id: existingUser.id,
|
||
relation_id: relation.id,
|
||
email: existingUser.email,
|
||
username: existingUser.username,
|
||
nickname: relation.name,
|
||
password: null,
|
||
reused: true,
|
||
},
|
||
};
|
||
} catch (err) {
|
||
await transaction.rollback();
|
||
ctx.status = 500;
|
||
ctx.body = { code: 500, message: '关联已有账号失败,请稍后重试' };
|
||
}
|
||
return;
|
||
}
|
||
|
||
// 生成随机初始密码(明文仅此处返回一次)
|
||
const password = this.generateRandomPassword(12);
|
||
const salt = generateSalt();
|
||
const hashed = hashPassword(password, salt);
|
||
|
||
const transaction = await ctx.model.transaction();
|
||
try {
|
||
const user = await ctx.model.User.create({
|
||
username: email,
|
||
email,
|
||
salt,
|
||
password: hashed,
|
||
status: 1,
|
||
}, { transaction });
|
||
|
||
const relation = await ctx.model.PrincipalUser.create({
|
||
principal_id: principalId,
|
||
user_id: user.id,
|
||
// 账号显示名称/头像按主体维护(推送单据操作人取 name)
|
||
name: String(name).trim(),
|
||
avatar: avatar ? String(avatar).trim() : null,
|
||
role: 'member',
|
||
role_id: roleId,
|
||
is_default: 0,
|
||
status: 1,
|
||
}, { transaction });
|
||
|
||
// 员工所属公司(可多家)
|
||
await ctx.model.PrincipalUserCompany.bulkCreate(
|
||
companyIds.map(subsidiaryId => ({
|
||
principal_id: Number(principalId),
|
||
principal_user_id: relation.id,
|
||
subsidiary_id: subsidiaryId,
|
||
})),
|
||
{ transaction }
|
||
);
|
||
|
||
await transaction.commit();
|
||
|
||
await ctx.service.cache.invalidateUserPrincipals(user.id);
|
||
|
||
ctx.body = {
|
||
code: 0,
|
||
message: 'success',
|
||
data: {
|
||
user_id: user.id,
|
||
relation_id: relation.id,
|
||
email: user.email,
|
||
username: user.username,
|
||
nickname: relation.name,
|
||
password,
|
||
},
|
||
};
|
||
} catch (err) {
|
||
await transaction.rollback();
|
||
ctx.status = 500;
|
||
ctx.body = { code: 500, message: '开通账号失败,请稍后重试' };
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 生成随机密码:12 位,含大小写字母与数字(去除易混淆字符 0/O/1/l/I)
|
||
* @param {Number} len 长度,默认 12
|
||
* @return {String} 随机密码
|
||
*/
|
||
generateRandomPassword(len = 12) {
|
||
const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789';
|
||
const bytes = crypto.randomBytes(len);
|
||
let pwd = '';
|
||
for (let i = 0; i < len; i++) pwd += chars[bytes[i] % chars.length];
|
||
return pwd;
|
||
}
|
||
|
||
/**
|
||
* @summary 更新关联信息
|
||
* @description 可修改该账号在此主体下的名称(name)、头像(avatar)、角色组(role_id)、所属公司(company_ids)、
|
||
* 默认主体标识与状态;名称/头像即账号显示资料,推送单据的操作人取名称;
|
||
* 除所有者(role = owner)外,员工必须至少关联一家公司;不允许改归属(principal_id / user_id),非白名单字段一律忽略
|
||
* @router put /api/principal-users/{id}
|
||
* @apikey
|
||
* @request path integer *id 关联记录主键ID
|
||
* @request body bindPrincipalUserRequest *body
|
||
* @response 200 baseResponse success
|
||
*/
|
||
async update() {
|
||
const { ctx } = this;
|
||
const relation = await ctx.model.PrincipalUser.findByPk(ctx.params.id);
|
||
|
||
if (!relation) {
|
||
ctx.status = 404;
|
||
ctx.body = { code: 404, message: '关联记录不存在' };
|
||
return;
|
||
}
|
||
|
||
// 默认创建者(所有者)为系统管理员,禁止编辑,避免被误改或被他人提权/降权
|
||
if (relation.role === 'owner') {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '系统管理员(默认创建者)不可编辑' };
|
||
return;
|
||
}
|
||
|
||
const scope = await this.assertManageTarget(relation);
|
||
if (!scope.ok) {
|
||
ctx.status = 403;
|
||
ctx.body = { code: 403, message: scope.message };
|
||
return;
|
||
}
|
||
|
||
const body = ctx.request.body || {};
|
||
// 只接受名称/头像/角色/角色组/默认标识/状态,避免改归属或写入无关字段
|
||
const patch = {};
|
||
for (const key of [ 'name', 'avatar', 'role', 'role_id', 'is_default', 'status' ]) {
|
||
if (body[key] !== undefined) patch[key] = body[key];
|
||
}
|
||
|
||
// 所在公司权限:角色组与所属公司均不可修改(防止自我/他人提权、跨公司调配)
|
||
if (!scope.access.isGroup) {
|
||
if (patch.role !== undefined || body.role_id !== undefined) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '所在公司权限不可修改角色组' };
|
||
return;
|
||
}
|
||
if (body.company_ids !== undefined) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '所在公司权限不可修改所属公司' };
|
||
return;
|
||
}
|
||
}
|
||
|
||
if (patch.role_id !== undefined) {
|
||
if (patch.role_id == null || patch.role_id === '') {
|
||
patch.role_id = null;
|
||
} else {
|
||
const role = await ctx.model.Role.findByPk(Number(patch.role_id));
|
||
if (!role) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '角色组不存在' };
|
||
return;
|
||
}
|
||
patch.role_id = Number(patch.role_id);
|
||
}
|
||
}
|
||
if (patch.name !== undefined) {
|
||
const name = patch.name == null ? '' : String(patch.name).trim();
|
||
if (!name) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '名称 name 不能为空' };
|
||
return;
|
||
}
|
||
patch.name = name;
|
||
}
|
||
if (patch.avatar !== undefined) {
|
||
patch.avatar = patch.avatar == null || String(patch.avatar).trim() === ''
|
||
? null
|
||
: String(patch.avatar).trim();
|
||
}
|
||
|
||
// 所属公司:所有者不参与关联;其余员工必须至少一家
|
||
const finalRole = patch.role === undefined ? relation.role : patch.role;
|
||
if (patch.role_id) {
|
||
const roleAllowed = await this.checkRoleScope(relation.principal_id, patch.role_id);
|
||
if (!roleAllowed.ok) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: roleAllowed.message };
|
||
return;
|
||
}
|
||
}
|
||
let companyIds = null;
|
||
if (body.company_ids !== undefined) {
|
||
companyIds = await this.resolveCompanyIds(body.company_ids, relation.principal_id);
|
||
if (finalRole !== 'owner' && !companyIds.length) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '非所有者员工至少需要关联一家公司(下属公司)' };
|
||
return;
|
||
}
|
||
const allowed = await this.checkCompanyScope(relation.principal_id, companyIds);
|
||
if (!allowed.ok) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: allowed.message };
|
||
return;
|
||
}
|
||
} else if (finalRole !== 'owner') {
|
||
const companyCount = await ctx.model.PrincipalUserCompany.count({
|
||
where: { principal_user_id: relation.id },
|
||
});
|
||
if (!companyCount) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '非所有者员工至少需要关联一家公司(下属公司)' };
|
||
return;
|
||
}
|
||
}
|
||
|
||
await relation.update(patch);
|
||
if (companyIds) await this.syncCompanies(relation, companyIds);
|
||
await ctx.service.cache.invalidateUserPrincipals(relation.user_id);
|
||
ctx.body = {
|
||
code: 0,
|
||
message: 'success',
|
||
data: { id: relation.id, name: relation.name, avatar: relation.avatar },
|
||
};
|
||
}
|
||
|
||
/**
|
||
* @summary 解绑用户与主体
|
||
* @description 物理删除关联记录(同时清理员工所属公司关联)
|
||
* @router delete /api/principal-users/{id}
|
||
* @apikey
|
||
* @request path integer *id 关联记录主键ID
|
||
* @response 200 baseResponse success
|
||
*/
|
||
async destroy() {
|
||
const { ctx } = this;
|
||
const relation = await ctx.model.PrincipalUser.findByPk(ctx.params.id);
|
||
|
||
if (!relation) {
|
||
ctx.status = 404;
|
||
ctx.body = { code: 404, message: '关联记录不存在' };
|
||
return;
|
||
}
|
||
|
||
// 默认创建者(所有者)是主体的系统管理员,任何人(含其本人)都不能解绑,避免主体失去管理员
|
||
if (relation.role === 'owner') {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '系统管理员(默认创建者)不可解绑' };
|
||
return;
|
||
}
|
||
if (Number(relation.user_id) === Number(ctx.userId)) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '不能解绑自己' };
|
||
return;
|
||
}
|
||
|
||
const scope = await this.assertManageTarget(relation);
|
||
if (!scope.ok) {
|
||
ctx.status = 403;
|
||
ctx.body = { code: 403, message: scope.message };
|
||
return;
|
||
}
|
||
|
||
const relationUserId = relation.user_id;
|
||
await ctx.model.PrincipalUserCompany.destroy({ where: { principal_user_id: relation.id } });
|
||
await relation.destroy();
|
||
await ctx.service.cache.invalidateUserPrincipals(relationUserId);
|
||
ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } };
|
||
}
|
||
|
||
/**
|
||
* 校验当前账号能否管理(编辑/解绑)该员工:
|
||
* 集团权限不限;所在公司权限只能管理自己所属公司范围内的员工
|
||
* @param {object} relation 员工(主体账号关联记录)
|
||
* @return {Promise<{ok: boolean, message?: string, access: object}>} 校验结果
|
||
*/
|
||
async assertManageTarget(relation) {
|
||
const { ctx } = this;
|
||
const access = await ctx.service.access.resolve(ctx.userId, relation.principal_id);
|
||
if (access.isGroup) return { ok: true, access };
|
||
|
||
const links = await ctx.model.PrincipalUserCompany.findAll({
|
||
where: {
|
||
principal_user_id: relation.id,
|
||
subsidiary_id: { [ctx.app.Sequelize.Op.in]: access.ownCompanyIds },
|
||
},
|
||
attributes: [ 'id' ],
|
||
raw: true,
|
||
});
|
||
if (!links.length) return { ok: false, message: '无权操作该员工(不在自己所属公司范围内)', access };
|
||
return { ok: true, access };
|
||
}
|
||
|
||
/**
|
||
* 所在公司权限下,只能分配不含集团权限的角色组(避免自行提权)
|
||
* @param {number|string} principalId 主体ID
|
||
* @param {number|null} roleId 目标角色组ID
|
||
* @return {Promise<{ok: boolean, message?: string}>} 校验结果
|
||
*/
|
||
async checkRoleScope(principalId, roleId) {
|
||
const { ctx } = this;
|
||
if (!roleId) return { ok: true };
|
||
const access = await ctx.service.access.resolve(ctx.userId, principalId);
|
||
if (access.isGroup) return { ok: true };
|
||
|
||
const groupPermission = await ctx.model.Permission.findOne({
|
||
where: { scope: 1, status: 1 },
|
||
attributes: [ 'id' ],
|
||
include: [{
|
||
model: ctx.model.Role,
|
||
as: 'roles',
|
||
attributes: [ 'id' ],
|
||
where: { id: Number(roleId) },
|
||
through: { attributes: [] },
|
||
required: true,
|
||
}],
|
||
});
|
||
if (groupPermission) {
|
||
return { ok: false, message: '所在公司权限的账号只能分配「所在公司」权限的角色组' };
|
||
}
|
||
return { ok: true };
|
||
}
|
||
|
||
/**
|
||
* 所在公司权限下,员工只能关联自己所属的公司
|
||
* @param {number|string} principalId 主体ID
|
||
* @param {Array<number>} companyIds 目标公司ID列表
|
||
* @return {Promise<{ok: boolean, message?: string}>} 校验结果
|
||
*/
|
||
async checkCompanyScope(principalId, companyIds) {
|
||
const { ctx } = this;
|
||
if (!companyIds.length) return { ok: true };
|
||
const access = await ctx.service.access.resolve(ctx.userId, principalId);
|
||
if (access.isGroup) return { ok: true };
|
||
const own = new Set(access.ownCompanyIds);
|
||
const invalid = companyIds.filter(id => !own.has(Number(id)));
|
||
if (invalid.length) return { ok: false, message: '只能关联自己所属的公司' };
|
||
return { ok: true };
|
||
}
|
||
|
||
/**
|
||
* 校验并去重下属公司ID(只接受属于指定主体的公司,忽略不存在的ID)
|
||
* @param {Array<number|string>} input 公司ID列表
|
||
* @param {number|string} principalId 主体ID
|
||
* @return {Promise<Array<number>>} 有效公司ID
|
||
*/
|
||
async resolveCompanyIds(input, principalId) {
|
||
const ids = Array.isArray(input) ? [ ...new Set(input.map(Number).filter(id => id > 0)) ] : [];
|
||
if (!ids.length) return [];
|
||
const rows = await this.ctx.model.PrincipalSubsidiary.findAll({
|
||
where: { id: ids, principal_id: principalId },
|
||
attributes: [ 'id' ],
|
||
raw: true,
|
||
});
|
||
return rows.map(row => Number(row.id));
|
||
}
|
||
|
||
/**
|
||
* 覆盖式同步员工所属公司
|
||
* @param {object} relation 员工(主体账号关联记录)
|
||
* @param {Array<number>} companyIds 下属公司ID列表
|
||
* @return {Promise<void>} 无返回值
|
||
*/
|
||
async syncCompanies(relation, companyIds) {
|
||
const { ctx } = this;
|
||
await ctx.model.PrincipalUserCompany.destroy({ where: { principal_user_id: relation.id } });
|
||
if (!companyIds.length) return;
|
||
await ctx.model.PrincipalUserCompany.bulkCreate(companyIds.map(subsidiaryId => ({
|
||
principal_id: relation.principal_id,
|
||
principal_user_id: relation.id,
|
||
subsidiary_id: subsidiaryId,
|
||
})));
|
||
}
|
||
}
|
||
|
||
module.exports = PrincipalUserController;
|