'use strict'; const { Controller } = require('egg'); const crypto = require('crypto'); const { generateSalt, hashPassword } = require('../lib/password'); const { parsePagination, buildPageResult } = require('../lib/pagination'); const { SCENE_BIND, bindKey, clearState, createTempCode, maskOpenid, newState, readState, saveState, takeResult, WechatGatewayError, } = require('../lib/wechatGateway'); /** * @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; }); await this.attachWechatBind(list); ctx.body = { code: 0, message: 'success', data: buildPageResult(list, count, { page, pageSize }) }; } /** * 给员工列表补上微信绑定信息(是否绑定 / 脱敏 openid / 绑定时间) * * 微信绑定按系统账号(users.id)建立,而员工是「主体 + 账号」的关联, * 因此这里按 user_id 批量查一次 user_wechat_binds 再回填,避免 N+1。 * @param {Array} list 员工列表(会被就地补充字段) * @return {Promise} 无返回值 */ async attachWechatBind(list) { const { ctx } = this; const items = Array.isArray(list) ? list : []; if (!items.length) return; const userIds = [ ...new Set(items.map(item => Number(item.user_id)).filter(id => id > 0)) ]; if (!userIds.length) return; const rows = await ctx.model.UserWechatBind.findAll({ where: { user_id: { [ctx.app.Sequelize.Op.in]: userIds } }, attributes: [ 'user_id', 'openid', 'bind_scene', 'created_at', 'last_login_at' ], raw: true, }); const byUser = new Map(rows.map(row => [ Number(row.user_id), row ])); for (const item of items) { const bind = byUser.get(Number(item.user_id)); item.wechat_bound = Boolean(bind); item.wechat_openid = bind ? maskOpenid(bind.openid) : ''; item.wechat_bind_scene = bind ? bind.bind_scene : ''; item.wechat_bound_at = bind ? bind.created_at : null; item.wechat_last_login_at = bind ? bind.last_login_at : null; } } /** * 取员工记录并校验当前账号能否管理(用于微信绑定类操作) * @param {number|string} id 员工(主体账号关联)主键ID * @return {Promise<{ok: boolean, relation?: Object, message?: string, status?: number}>} 校验结果 */ async loadManageableRelation(id) { const { ctx } = this; const relation = await ctx.model.PrincipalUser.findByPk(id); if (!relation) return { ok: false, status: 404, message: '员工不存在' }; if (relation.role === 'owner') { return { ok: false, status: 400, message: '系统管理员(默认创建者)不可操作微信绑定' }; } const scope = await this.assertManageTarget(relation); if (!scope.ok) return { ok: false, status: 403, message: scope.message }; return { ok: true, relation }; } /** * @summary 拉取员工的微信绑定二维码 * @description 为指定员工申请一次性扫码会话(scene=bind,绑定目标为该员工的系统账号); * 员工用微信扫码确认后,其账号即与本系统账号建立绑定,可用于微信扫码登录 * @router post /api/principal-users/{id}/wechat/bind-code * @apikey * @request path integer *id 员工(主体账号关联)主键ID * @response 200 wechatQrcodeResponse success */ async wechatBindCode() { const { ctx, app } = this; const target = await this.loadManageableRelation(ctx.params.id); if (!target.ok) { ctx.status = target.status; ctx.body = { code: target.status, message: target.message }; return; } const state = newState(); try { // 绑定目标是员工账号(不是当前操作人),并记录操作人用于轮询校验 await saveState(app, state, { scene: SCENE_BIND, user_id: Number(target.relation.user_id), operator_id: Number(ctx.userId), principal_user_id: Number(target.relation.id), }); const data = await createTempCode(app, { scene: SCENE_BIND, state }); const { stateTtl } = app.config.wechatGateway; ctx.body = { code: 0, message: 'success', data: { scene: SCENE_BIND, state, temp_code: data.tempCode, page_url: data.pageUrl, expires_in: Number(data.expiresIn) || stateTtl, }, }; } catch (err) { const status = err instanceof WechatGatewayError ? err.status : 502; ctx.status = status; ctx.body = { code: status, message: err.message }; } } /** * @summary 轮询员工微信绑定结果 * @description pending 待扫码确认;success 绑定成功;conflict 该微信已绑定其他账号;failed 账号不存在或已禁用 * @router get /api/principal-users/{id}/wechat/bind-status * @apikey * @request path integer *id 员工(主体账号关联)主键ID * @request query string state 扫码会话标识 * @response 200 wechatBindStatusResponse success */ async wechatBindStatus() { const { ctx, app } = this; const target = await this.loadManageableRelation(ctx.params.id); if (!target.ok) { ctx.status = target.status; ctx.body = { code: target.status, message: target.message }; return; } const state = String(ctx.query.state || ''); const record = await readState(app, state); if ( !record || record.scene !== SCENE_BIND || Number(record.operator_id) !== Number(ctx.userId) || Number(record.principal_user_id) !== Number(target.relation.id) ) { ctx.status = 400; ctx.body = { code: 400, message: '二维码已失效,请刷新后重试' }; return; } const result = await takeResult(app, bindKey(state)); if (!result) { ctx.body = { code: 0, message: 'success', data: { status: 'pending' } }; return; } await clearState(app, state); ctx.body = { code: 0, message: 'success', data: { status: result.status, message: result.message || '' } }; } /** * @summary 解绑员工的微信 * @description 删除该员工系统账号的微信绑定;解绑后该员工不能再使用微信扫码登录 * @router delete /api/principal-users/{id}/wechat/bind * @apikey * @request path integer *id 员工(主体账号关联)主键ID * @response 200 baseResponse success */ async wechatUnbind() { const { ctx } = this; const target = await this.loadManageableRelation(ctx.params.id); if (!target.ok) { ctx.status = target.status; ctx.body = { code: target.status, message: target.message }; return; } const count = await ctx.model.UserWechatBind.destroy({ where: { user_id: Number(target.relation.user_id) }, }); if (!count) { ctx.status = 404; ctx.body = { code: 404, message: '该员工尚未绑定微信' }; return; } ctx.body = { code: 0, message: 'success', data: { unbound: true } }; } /** * @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; // 邮箱选填:留空表示先建临时账号(自动生成账号名,后续微信扫码绑定或补填邮箱) const emailInput = String(email == null ? '' : email).trim(); if (emailInput && !EMAIL_REGEX.test(emailInput)) { 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 = emailInput ? await ctx.model.User.findOne({ where: { email: emailInput } }) : null; 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 username = emailInput || await this.nextTempUsername(); const transaction = await ctx.model.transaction(); try { const user = await ctx.model.User.create({ username, email: emailInput || null, nickname: String(name).trim(), 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, // 临时账号:邮箱为空,可用微信扫码绑定(已有微信账号时直接绑定到该账号) temporary: !user.email, }, }; } catch (err) { await transaction.rollback(); ctx.status = 500; ctx.body = { code: 500, message: '开通账号失败,请稍后重试' }; } } /** * 生成临时账号的登录名(未填邮箱时使用):tmp_ + 8 位随机字符,保证全局唯一 * @return {Promise} 未被占用的登录名 */ async nextTempUsername() { const { ctx } = this; const chars = 'abcdefghijkmnopqrstuvwxyz23456789'; for (let i = 0; i < 10; i++) { const bytes = crypto.randomBytes(8); let name = 'tmp_'; for (let j = 0; j < 8; j++) name += chars[bytes[j] % chars.length]; const exist = await ctx.model.User.findOne({ where: { username: name }, attributes: [ 'id' ] }); if (!exist) return name; } // 极端情况下兜底:带时间戳,仍保证唯一性检查 return `tmp_${Date.now().toString(36)}`; } /** * 生成随机密码: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]; } // 邮箱维护:临时账号(邮箱为空)可由管理员补填;已绑定邮箱的账号需员工在「个人设置」自行修改 let emailPatch = null; if (body.email !== undefined) { const email = String(body.email == null ? '' : body.email).trim(); const account = await ctx.model.User.findByPk(relation.user_id, { attributes: [ 'id', 'email' ] }); if (!account) { ctx.status = 404; ctx.body = { code: 404, message: '员工账号不存在' }; return; } if (email) { if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { ctx.status = 400; ctx.body = { code: 400, message: '邮箱格式不正确' }; return; } if (account.email && String(account.email) !== email) { ctx.status = 400; ctx.body = { code: 400, message: '该账号已绑定邮箱,如需修改请让员工在「个人设置」中维护' }; return; } const exist = await ctx.model.User.findOne({ where: { email }, attributes: [ 'id' ] }); if (exist && Number(exist.id) !== Number(relation.user_id)) { ctx.status = 400; ctx.body = { code: 400, message: '该邮箱已被其他账号使用' }; return; } if (!account.email) emailPatch = email; } } // 所在公司权限:角色组与所属公司均不可修改(防止自我/他人提权、跨公司调配) 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 (emailPatch) { await ctx.model.User.update({ email: emailPatch }, { where: { id: relation.user_id } }); await ctx.service.cache.invalidateUser(relation.user_id); } 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, email: emailPatch || undefined }, }; } /** * @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} 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} input 公司ID列表 * @param {number|string} principalId 主体ID * @return {Promise>} 有效公司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} companyIds 下属公司ID列表 * @return {Promise} 无返回值 */ 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;