diff --git a/backend/app/contract/index.js b/backend/app/contract/index.js index f8072a2..7224337 100644 --- a/backend/app/contract/index.js +++ b/backend/app/contract/index.js @@ -366,12 +366,13 @@ module.exports = { company_ids: { type: 'array', itemType: 'integer', required: true, description: '所属公司(下属公司)ID列表,至少一家' }, }, invitePrincipalUserData: { - user_id: { type: 'integer', description: '新建用户ID' }, + user_id: { type: 'integer', description: '新建/复用的用户ID' }, relation_id: { type: 'integer', description: '主体用户关联记录ID' }, email: { type: 'string', description: '邮箱(即登录账号)' }, username: { type: 'string', description: '登录账号(此处为邮箱)' }, nickname: { type: 'string', description: '用户名称' }, - password: { type: 'string', description: '随机生成的初始密码(明文,仅返回一次,需妥善交付)' }, + password: { type: 'string', description: '随机生成的初始密码(仅新建账号时返回一次);复用已有账号时为 null' }, + reused: { type: 'boolean', description: '是否复用已有账号(邮箱已注册,沿用原密码登录)' }, }, invitePrincipalUserResponse: { code: { type: 'integer', description: '业务状态码,0 成功' }, diff --git a/backend/app/controller/access.js b/backend/app/controller/access.js new file mode 100644 index 0000000..24fdeab --- /dev/null +++ b/backend/app/controller/access.js @@ -0,0 +1,42 @@ +'use strict'; + +const { Controller } = require('egg'); + +/** + * @controller AccessController 当前账号权限范围 + */ +class AccessController extends Controller { + /** + * @summary 当前账号在指定主体下的权限范围 + * @description 供前端按权限收窄操作入口(如所在公司权限不可修改角色组/所属公司) + * @router get /api/access/context + * @apikey + * @request query integer principal_id 主体ID(必填) + * @response 200 baseResponse success + */ + async context() { + const { ctx } = this; + const principalId = ctx.query.principal_id; + if (principalId === undefined || principalId === '') { + ctx.status = 400; + ctx.body = { code: 400, message: '缺少主体ID(principal_id)' }; + return; + } + + const access = await ctx.service.access.resolve(ctx.userId, principalId); + ctx.body = { + code: 0, + message: 'success', + data: { + is_group: access.isGroup, + scope: access.scope, + company_ids: access.ownCompanyIds, + role: access.role, + role_id: access.roleId, + relation_id: access.relationId, + }, + }; + } +} + +module.exports = AccessController; diff --git a/backend/app/controller/menu.js b/backend/app/controller/menu.js index fcd9349..7a8a71c 100644 --- a/backend/app/controller/menu.js +++ b/backend/app/controller/menu.js @@ -3,6 +3,9 @@ const { Controller } = require('egg'); const { parsePagination, buildPageResult } = require('../lib/pagination'); +/** 所在公司权限可访问的系统管理菜单(员工档案) */ +const EMPLOYEE_MENU_PATH = '/system/employee'; + /** * @controller MenuController 菜单管理 */ @@ -41,10 +44,13 @@ class MenuController extends Controller { /** * @summary 菜单树 - * @description 一次性返回全部菜单并按 parent_id 组装为树形结构 + * @description 一次性返回全部菜单并按 parent_id 组装为树形结构; + * 传入 principal_id 且当前账号在该主体下仅为「所在公司」权限时, + * 系统管理下仅保留「员工档案」(其余菜单需集团权限) * @router get /api/menus/tree * @apikey * @request query integer status 状态:1启用 0禁用,不传则返回全部 + * @request query integer principal_id 当前主体ID(用于判定权限范围) * @response 200 baseResponse success */ async tree() { @@ -59,7 +65,12 @@ class MenuController extends Controller { order: [[ 'sort', 'DESC' ], [ 'id', 'ASC' ]], }); - const rows = list.map(item => item.toJSON()); + let rows = list.map(item => item.toJSON()); + if (ctx.query.principal_id) { + const access = await ctx.service.access.resolve(ctx.userId, ctx.query.principal_id); + if (!access.isGroup) rows = this.filterCompanyScopeMenus(rows); + } + const map = new Map(); const tree = []; @@ -79,6 +90,36 @@ class MenuController extends Controller { ctx.body = { code: 0, message: 'success', data: tree }; } + /** + * 所在公司权限的菜单收束:系统管理目录下仅保留「员工档案」 + * @param {Array} rows 菜单行 + * @return {Array} 过滤后的菜单行 + */ + filterCompanyScopeMenus(rows) { + const employee = rows.find(row => row.path === EMPLOYEE_MENU_PATH && Number(row.type) === 2); + if (!employee) return rows; + + const systemId = Number(employee.parent_id); + const removedIds = new Set( + rows + .filter(row => Number(row.parent_id) === systemId && Number(row.id) !== Number(employee.id)) + .map(row => Number(row.id)) + ); + // 父级被移除的子级一并移除,避免孤儿节点被挂到根节点 + let changed = true; + while (changed) { + changed = false; + for (const row of rows) { + if (removedIds.has(Number(row.id))) continue; + if (removedIds.has(Number(row.parent_id))) { + removedIds.add(Number(row.id)); + changed = true; + } + } + } + return rows.filter(row => !removedIds.has(Number(row.id))); + } + /** * @summary 菜单详情 * @description 按主键查询菜单 diff --git a/backend/app/controller/principalSubsidiary.js b/backend/app/controller/principalSubsidiary.js index ece2527..ff45b74 100644 --- a/backend/app/controller/principalSubsidiary.js +++ b/backend/app/controller/principalSubsidiary.js @@ -63,15 +63,26 @@ class PrincipalSubsidiaryController extends Controller { /** * @summary 下属公司下拉(仅启用) - * @description 供员工档案等页面选择所属公司,按当前主体隔离 + * @description 供员工档案/商品等页面选择公司,按当前主体隔离; + * mine=1 时仅返回当前账号自己关联的公司(集团权限返回全部) * @router get /api/principal-subsidiaries/select * @apikey + * @request query integer mine 是否仅返回自己所属的公司:1是 * @response 200 baseResponse success */ async select() { const { ctx } = this; + const Op = this.app.Sequelize.Op; + const principalId = ctx.state.principalId; + + const where = { principal_id: principalId, status: 1 }; + if (String(ctx.query.mine || '') === '1') { + const access = await ctx.service.access.resolve(ctx.userId, principalId); + if (!access.isGroup) where.id = { [Op.in]: access.ownCompanyIds }; + } + const rows = await ctx.model.PrincipalSubsidiary.findAll({ - where: { principal_id: ctx.state.principalId, status: 1 }, + where, attributes: [ 'id', 'name' ], order: [[ 'id', 'ASC' ]], raw: true, diff --git a/backend/app/controller/principalUser.js b/backend/app/controller/principalUser.js index 5fe95aa..67fc03e 100644 --- a/backend/app/controller/principalUser.js +++ b/backend/app/controller/principalUser.js @@ -11,7 +11,8 @@ const { parsePagination, buildPageResult } = require('../lib/pagination'); class PrincipalUserController extends Controller { /** * @summary 关联列表 - * @description 分页查询主体与用户的关联关系,可按主体或用户过滤 + * @description 分页查询主体与用户的关联关系,可按主体或用户过滤; + * 所在公司权限的账号仅返回自己所属公司范围内的员工 * @router get /api/principal-users * @apikey * @request query integer page 页码,默认 1 @@ -25,6 +26,7 @@ class PrincipalUserController extends Controller { */ 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; @@ -36,6 +38,17 @@ class PrincipalUserController extends Controller { 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, @@ -137,6 +150,11 @@ class PrincipalUserController extends Controller { } 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) { @@ -144,6 +162,12 @@ class PrincipalUserController extends Controller { 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, @@ -165,8 +189,9 @@ class PrincipalUserController extends Controller { /** * @summary 邀请开通主体账号 * @description 传入邮箱、用户名称(写入主体账号关联表 principal_users.name)、主体ID、角色组与所属公司, - * 自动创建新用户(随机初始密码)并绑定到该主体;角色组必选,除所有者外必须至少关联一家公司; - * 返回明文随机密码,需由调用方妥善交付给被邀请人;同一邮箱不可重复开通 + * 绑定到该主体;邮箱未注册时自动创建新用户(随机初始密码),已注册时复用现有账号并沿用原密码; + * 角色组必选,除所有者外必须至少关联一家公司(所在公司权限的账号只能关联自己所属的公司); + * 新建账号时返回明文随机密码,需由调用方妥善交付给被邀请人;同一邮箱不能在同一主体重复添加 * @router post /api/principal-users/invite * @apikey * @request body invitePrincipalUserRequest *body @@ -208,12 +233,19 @@ class PrincipalUserController extends Controller { return; } - // 邮箱全局唯一 - const emailExist = await ctx.model.User.findOne({ where: { email } }); - if (emailExist) { - ctx.status = 400; - ctx.body = { code: 400, 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; } // 角色组必选(员工档案创建时必须指定角色) @@ -229,6 +261,12 @@ class PrincipalUserController extends Controller { 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); @@ -237,6 +275,60 @@ class PrincipalUserController extends Controller { 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); @@ -332,12 +424,41 @@ class PrincipalUserController extends Controller { 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; @@ -368,6 +489,14 @@ class PrincipalUserController extends Controller { // 所属公司:所有者不参与关联;其余员工必须至少一家 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); @@ -376,6 +505,12 @@ class PrincipalUserController extends Controller { 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 }, @@ -415,6 +550,25 @@ class PrincipalUserController extends Controller { 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(); @@ -422,6 +576,76 @@ class PrincipalUserController extends Controller { 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列表 diff --git a/backend/app/controller/role.js b/backend/app/controller/role.js index ba82b3e..0929731 100644 --- a/backend/app/controller/role.js +++ b/backend/app/controller/role.js @@ -68,9 +68,11 @@ class RoleController extends Controller { /** * @summary 角色组下拉 - * @description 返回启用的角色组,供「账号」页面分配角色组使用 + * @description 返回启用的角色组,供「员工档案」页面分配角色组使用; + * mine=1 时对「所在公司」权限的账号只返回不含集团权限的角色组,避免越权分配 * @router get /api/roles/options * @apikey + * @request query integer mine 是否按当前账号权限收窄:1是 * @response 200 baseResponse success */ async options() { @@ -81,7 +83,30 @@ class RoleController extends Controller { order: [[ 'is_system', 'DESC' ], [ 'id', 'ASC' ]], raw: true, }); - ctx.body = { code: 0, message: 'success', data: rows }; + + let list = rows; + if (String(ctx.query.mine || '') === '1' && ctx.query.principal_id) { + const access = await ctx.service.access.resolve(ctx.userId, ctx.query.principal_id); + if (!access.isGroup) { + const groupPermissions = await ctx.model.Permission.findAll({ + where: { scope: 1, status: 1 }, + attributes: [ 'id' ], + include: [{ + model: ctx.model.Role, + as: 'roles', + attributes: [ 'id' ], + through: { attributes: [] }, + required: true, + }], + }); + const blocked = new Set( + groupPermissions.flatMap(item => (item.roles || []).map(role => Number(role.id))) + ); + list = rows.filter(row => !blocked.has(Number(row.id))); + } + } + + ctx.body = { code: 0, message: 'success', data: list }; } /** diff --git a/backend/app/router.js b/backend/app/router.js index ad7656d..e9b2584 100644 --- a/backend/app/router.js +++ b/backend/app/router.js @@ -48,6 +48,8 @@ module.exports = app => { router.resources('users', '/api/users', jwtAuth, controller.user); // 头部主体切换下拉(带缓存),需在 /api/principals/:id 之前注册,避免 options 被当作 id 匹配 router.get('/api/principals/options', jwtAuth, controller.principal.options); + // 当前账号在主体下的权限范围(集团权限 / 所在公司权限),供前端收窄操作入口 + router.get('/api/access/context', jwtAuth, controller.access.context); // 管理端主体列表(不缓存,保证分页与筛选实时) router.resources('principals', '/api/principals', jwtAuth, controller.principal); // 组织架构 → 下属公司:按当前主体隔离(列表/新增取入参主体,详情/更新/删除按记录所属主体鉴权) diff --git a/backend/app/service/access.js b/backend/app/service/access.js new file mode 100644 index 0000000..bfb45f4 --- /dev/null +++ b/backend/app/service/access.js @@ -0,0 +1,76 @@ +'use strict'; + +const { Service } = require('egg'); + +/** 菜单权限范围:1集团全部 2所在公司 */ +const SCOPE_GROUP = 1; + +/** + * 权限范围判定服务 + * + * 依据当前账号在指定主体下的角色组(roles → permissions.scope)判断权限范围: + * - 所有者(principal_users.role = owner)视为集团权限 + * - 角色组内含任一「集团全部」权限 → group(可操作该主体全部公司) + * - 其余(仅「所在公司」权限或未分配角色组)→ company(只能操作自己关联的公司) + */ +class AccessService extends Service { + /** + * 解析账号在主体下的权限范围 + * @param {number} userId 用户ID + * @param {number|string} principalId 主体ID + * @return {Promise<{isGroup: boolean, scope: string, relationId: number|null, role: string|null, roleId: number|null, ownCompanyIds: Array}>} 权限上下文 + */ + async resolve(userId, principalId) { + const empty = { + isGroup: false, + scope: 'company', + relationId: null, + role: null, + roleId: null, + ownCompanyIds: [], + }; + if (!userId || principalId == null || principalId === '') return empty; + + const relation = await this.ctx.model.PrincipalUser.findOne({ + where: { user_id: userId, principal_id: Number(principalId) }, + attributes: [ 'id', 'role', 'role_id' ], + }); + if (!relation) return empty; + + const companyRows = await this.ctx.model.PrincipalUserCompany.findAll({ + where: { principal_user_id: relation.id }, + attributes: [ 'subsidiary_id' ], + raw: true, + }); + const ownCompanyIds = companyRows.map(row => Number(row.subsidiary_id)); + + let isGroup = relation.role === 'owner'; + if (!isGroup && relation.role_id) { + const groupPermission = await this.ctx.model.Permission.findOne({ + where: { scope: SCOPE_GROUP, status: 1 }, + attributes: [ 'id' ], + include: [{ + model: this.ctx.model.Role, + as: 'roles', + attributes: [ 'id' ], + where: { id: Number(relation.role_id) }, + required: true, + through: { attributes: [] }, + }], + }); + isGroup = !!groupPermission; + } + + return { + isGroup, + scope: isGroup ? 'group' : 'company', + relationId: Number(relation.id), + role: relation.role, + roleId: relation.role_id == null ? null : Number(relation.role_id), + ownCompanyIds, + }; + } +} + +module.exports = AccessService; +module.exports.SCOPE_GROUP = SCOPE_GROUP; diff --git a/backend/database/migrations/20261104070800-owner-role-to-super-admin.js b/backend/database/migrations/20261104070800-owner-role-to-super-admin.js new file mode 100644 index 0000000..01affa0 --- /dev/null +++ b/backend/database/migrations/20261104070800-owner-role-to-super-admin.js @@ -0,0 +1,28 @@ +'use strict'; + +/** + * 所有者(默认创建者/系统管理员)的角色组统一为「系统管理员」。 + * + * 所有者账号在界面上已禁止编辑,若角色组仍是「货主权限」会造成展示歧义, + * 这里把 role = owner 的关联记录统一指向系统管理员角色组。 + */ +module.exports = { + async up(queryInterface) { + const sequelize = queryInterface.sequelize; + const admins = await sequelize.query( + "SELECT id FROM roles WHERE code = 'super_admin' LIMIT 1", + { type: sequelize.QueryTypes.SELECT } + ); + const admin = admins[0]; + if (!admin) return; + + await sequelize.query( + 'UPDATE principal_users SET role_id = ? WHERE role = ? AND (role_id IS NULL OR role_id <> ?)', + { replacements: [ Number(admin.id), 'owner', Number(admin.id) ] } + ); + }, + + async down() { + // 数据修正类迁移,不回滚 + }, +}; diff --git a/frontend/src/api/access.ts b/frontend/src/api/access.ts new file mode 100644 index 0000000..324fe00 --- /dev/null +++ b/frontend/src/api/access.ts @@ -0,0 +1,19 @@ +import { get } from '@/utils/request' + +/** 当前账号在主体下的权限范围(集团权限 / 所在公司权限) */ +export interface AccessContext { + /** 是否集团权限(所有者或角色组含集团权限) */ + is_group: boolean + /** group 集团权限 / company 所在公司权限 */ + scope: 'group' | 'company' + /** 自己关联的下属公司ID */ + company_ids: number[] + role: string | null + role_id: number | null + relation_id: number | null +} + +/** 获取当前账号在主体下的权限范围(principal_id 由请求拦截器注入) */ +export function getAccessContext() { + return get('/access/context') +} diff --git a/frontend/src/api/principalSubsidiary.ts b/frontend/src/api/principalSubsidiary.ts index b63ce48..106ef8a 100644 --- a/frontend/src/api/principalSubsidiary.ts +++ b/frontend/src/api/principalSubsidiary.ts @@ -33,8 +33,8 @@ export interface PrincipalSubsidiaryOption { name: string } -export function getPrincipalSubsidiaryOptions() { - return get('/principal-subsidiaries/select') +export function getPrincipalSubsidiaryOptions(params?: { mine?: number }) { + return get('/principal-subsidiaries/select', params) } /** 当前主体下的下属公司列表(principal_id 由请求拦截器自动注入) */ diff --git a/frontend/src/api/principalUser.ts b/frontend/src/api/principalUser.ts index 5f67bd7..36eead0 100644 --- a/frontend/src/api/principalUser.ts +++ b/frontend/src/api/principalUser.ts @@ -34,7 +34,10 @@ export interface InviteResult { email: string username: string nickname: string - password: string + /** 初始密码(仅新建账号返回一次;复用已有账号为 null) */ + password: string | null + /** 是否复用已有账号(邮箱已注册,沿用原密码登录) */ + reused?: boolean } /** 当前主体下的用户关联列表(principal_id 由请求拦截器自动注入) */ diff --git a/frontend/src/api/role.ts b/frontend/src/api/role.ts index 1807357..5309bc3 100644 --- a/frontend/src/api/role.ts +++ b/frontend/src/api/role.ts @@ -38,9 +38,9 @@ export function getRoles(params?: object) { return get<{ list: RoleItem[]; total: number; page: number; pageSize: number }>('/roles', params) } -/** 角色组下拉(启用) */ -export function getRoleOptions() { - return get('/roles/options') +/** 角色组下拉 */ +export function getRoleOptions(params?: { mine?: number }) { + return get('/roles/options', params) } export function getRole(id: number) { diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts index 7af3e25..40f3019 100644 --- a/frontend/src/router/index.ts +++ b/frontend/src/router/index.ts @@ -63,8 +63,12 @@ router.beforeEach(async (to) => { await menuStore.fetchMenus() } // 动态路由是运行期注册的,深链接刷新时早于匹配阶段: - // 当前 to 尚未匹配到任何路由 → 用新的路由表重新解析当前目标 + // 当前 to 尚未匹配到任何路由 → 用新的路由表重新解析当前目标; + // 重新解析后仍无匹配(地址不存在或当前权限不可见)则回首页,避免反复重定向 if (to.matched.length === 0) { + if (to.redirectedFrom && to.redirectedFrom.matched.length === 0) { + return { path: '/dashboard' } + } return to.fullPath } // 已登录但无主体:强制停留在创建主体面板,隐藏其余菜单 diff --git a/frontend/src/views/PrincipalUser/Index.vue b/frontend/src/views/PrincipalUser/Index.vue index df289c5..69cb3e0 100644 --- a/frontend/src/views/PrincipalUser/Index.vue +++ b/frontend/src/views/PrincipalUser/Index.vue @@ -16,6 +16,7 @@ import { DEFAULT_PAGE_SIZE, useListPage } from '@/composables/useListPage' import { formatDateTime } from '@/utils/datetime' import { mediaUrl } from '@/utils/media' import { getRoleOptions, type RoleOption } from '@/api/role' +import { getAccessContext } from '@/api/access' import { getPrincipalSubsidiaryOptions, type PrincipalSubsidiaryOption } from '@/api/principalSubsidiary' const query = reactive({ @@ -30,23 +31,41 @@ const roles = ref([]) async function fetchRoles() { try { - roles.value = await getRoleOptions() + // mine=1:所在公司权限的账号只返回所在公司权限的角色组,避免越权分配 + roles.value = await getRoleOptions({ mine: 1 }) } catch { roles.value = [] } } -/** 下属公司下拉(组织架构 → 下属公司,员工可关联多家) */ +/** 下属公司下拉(组织架构 → 下属公司):onlyMine 时仅返回自己所属的公司(集团权限返回全部) */ const companies = ref([]) async function fetchCompanies() { try { - companies.value = await getPrincipalSubsidiaryOptions() + companies.value = await getPrincipalSubsidiaryOptions({ mine: 1 }) } catch { companies.value = [] } } +/** 当前账号在本主体下是否仅为「所在公司」权限:此时角色组与所属公司只读 */ +const isCompanyScope = ref(false) + +async function fetchAccessContext() { + try { + const ctx = await getAccessContext() + isCompanyScope.value = !ctx.is_group + } catch { + isCompanyScope.value = false + } +} + +/** 所有者(默认创建者/系统管理员)不可编辑与解绑 */ +function isOwnerRow(row: PrincipalUserItem) { + return row.role === 'owner' +} + function roleGroupText(row: PrincipalUserItem) { return row.roleGroup?.name || '-' } @@ -118,7 +137,7 @@ const inviteRules: FormRules = { } /** 新增成功后返回的账号信息(初始密码仅返回一次) */ -const inviteResult = ref<{ username: string; password: string } | null>(null) +const inviteResult = ref<{ username: string; password: string; reused: boolean } | null>(null) const inviteResultVisible = ref(false) /** 复制文本:优先 Clipboard API,非安全上下文回退到 execCommand */ @@ -173,9 +192,18 @@ async function submitInvite() { company_ids: inviteForm.company_ids, }) inviteVisible.value = false - ElMessage.success('员工创建成功') - // 账号与初始密码仅返回一次,展示在结果弹窗中并支持一键复制 - inviteResult.value = { username: res.username, password: res.password } + // 复用已有账号时不返回密码(沿用原密码登录),只提示已关联 + if (res.reused) { + ElMessage.success('该邮箱已有账号,已关联到当前主体(沿用原密码登录)') + } else { + ElMessage.success('员工创建成功') + } + // 初始密码仅返回一次,展示在结果弹窗中并支持一键复制 + inviteResult.value = { + username: res.username, + password: res.password || '', + reused: !!res.reused, + } inviteResultVisible.value = true await fetchList() } catch { @@ -236,13 +264,17 @@ async function submitEdit() { if (!valid) return editSubmitting.value = true try { - await updatePrincipalUser(editId.value as number, { + // 所在公司权限不可改角色组与所属公司,只提交名称/头像/状态 + const payload: Parameters[1] = { name: editForm.name, avatar: editForm.avatar, - role_id: Number(editForm.role_id), - company_ids: editForm.company_ids, status: editForm.status, - }) + } + if (!isCompanyScope.value) { + payload.role_id = Number(editForm.role_id) + payload.company_ids = editForm.company_ids + } + await updatePrincipalUser(editId.value as number, payload) ElMessage.success('保存成功') editVisible.value = false await fetchList() @@ -274,7 +306,7 @@ async function handleUnbind(row: PrincipalUserItem) { } onMounted(async () => { - await Promise.all([ fetchRoles(), fetchCompanies() ]) + await Promise.all([ fetchRoles(), fetchCompanies(), fetchAccessContext() ]) await fetchList() }) @@ -341,8 +373,13 @@ onMounted(async () => { @@ -400,9 +437,15 @@ onMounted(async () => { - + +
所在公司权限不可修改角色组
{ multiple filterable placeholder="可关联多家公司" + :disabled="isCompanyScope" style="width: 100%" > +
所在公司权限不可修改所属公司
主体所有者无需关联公司
@@ -429,8 +474,16 @@ onMounted(async () => { - + + { -
+
初始密码