'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 { 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 { 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'; const companyIds = await this.resolveCompanyIds(body.company_ids, principalId); // 所有者不参与公司关联,其余员工必须至少关联一家公司 if (role !== 'owner' && !companyIds.length) { ctx.status = 400; ctx.body = { code: 400, 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 emailExist = await ctx.model.User.findOne({ where: { email } }); if (emailExist) { ctx.status = 400; ctx.body = { code: 400, message: '该邮箱已注册' }; return; } // 角色组必选(员工档案创建时必须指定角色) 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 companyIds = await this.resolveCompanyIds(bodyCompanyIds, principalId); if (!companyIds.length) { ctx.status = 400; ctx.body = { code: 400, 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; } 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 (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; 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; } } 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; } 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) } }; } /** * 校验并去重下属公司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;