diff --git a/backend/app/contract/index.js b/backend/app/contract/index.js index b8d7a00..471dfcb 100644 --- a/backend/app/contract/index.js +++ b/backend/app/contract/index.js @@ -284,6 +284,41 @@ module.exports = { remark: { type: 'string', description: '备注' }, }, + // ---------- 组织架构 · 下属公司 principal_subsidiaries ---------- + principalSubsidiaryItem: { + id: { type: 'integer', description: '主键' }, + principal_id: { type: 'integer', description: '所属主体(集团)ID' }, + name: { type: 'string', description: '公司名称' }, + credit_code: { type: 'string', description: '统一社会信用代码' }, + contact_name: { type: 'string', description: '联系人' }, + contact_phone: { type: 'string', description: '联系电话' }, + address: { type: 'string', description: '公司地址' }, + status: { type: 'integer', description: '状态:1启用 0禁用' }, + remark: { type: 'string', description: '备注' }, + created_at: { type: 'string', description: '创建时间' }, + updated_at: { type: 'string', description: '更新时间' }, + }, + principalSubsidiaryPage: buildPage('principalSubsidiaryItem', '下属公司列表'), + principalSubsidiaryListResponse: buildListResponse('principalSubsidiaryPage'), + createPrincipalSubsidiaryRequest: { + name: { type: 'string', required: true, description: '公司名称(同一主体下唯一)' }, + credit_code: { type: 'string', description: '统一社会信用代码' }, + contact_name: { type: 'string', description: '联系人' }, + contact_phone: { type: 'string', description: '联系电话' }, + address: { type: 'string', description: '公司地址' }, + status: { type: 'integer', description: '状态:1启用 0禁用,默认1' }, + remark: { type: 'string', description: '备注' }, + }, + updatePrincipalSubsidiaryRequest: { + name: { type: 'string', description: '公司名称(同一主体下唯一)' }, + credit_code: { type: 'string', description: '统一社会信用代码' }, + contact_name: { type: 'string', description: '联系人' }, + contact_phone: { type: 'string', description: '联系电话' }, + address: { type: 'string', description: '公司地址' }, + status: { type: 'integer', description: '状态:1启用 0禁用' }, + remark: { type: 'string', description: '备注' }, + }, + // ---------- 主体用户关联 principal_users ---------- principalUserItem: { id: { type: 'integer', description: '主键' }, @@ -292,27 +327,40 @@ module.exports = { name: { type: 'string', description: '该账号在此主体下的显示名称(推送单据操作人取此值)' }, avatar: { type: 'string', description: '该账号在此主体下的头像 URL' }, role: { type: 'string', description: '该主体下的角色标识' }, + role_id: { type: 'integer', description: '角色组ID(roles.id)' }, + roleGroup: { type: 'roleRef', description: '角色组信息' }, + company_ids: { type: 'array', itemType: 'integer', description: '所属公司(下属公司)ID列表' }, + companies: { type: 'array', itemType: 'principalUserCompanyItem', description: '所属公司明细' }, is_default: { type: 'integer', description: '是否默认主体:1是 0否' }, status: { type: 'integer', description: '状态:1启用 0禁用' }, created_at: { type: 'string', description: '创建时间' }, updated_at: { type: 'string', description: '更新时间' }, }, - principalUserPage: buildPage('principalUserItem', '关联记录列表'), + principalUserPage: buildPage('principalUserItem', '员工/关联记录列表'), principalUserListResponse: buildListResponse('principalUserPage'), + principalUserCompanyItem: { + id: { type: 'integer', description: '关联记录ID' }, + subsidiary_id: { type: 'integer', description: '下属公司ID' }, + name: { type: 'string', description: '下属公司名称' }, + }, bindPrincipalUserRequest: { principal_id: { type: 'integer', required: true, description: '主体ID' }, user_id: { type: 'integer', required: true, description: '用户ID' }, name: { type: 'string', description: '该账号在此主体下的显示名称' }, avatar: { type: 'string', description: '该账号在此主体下的头像 URL' }, role: { type: 'string', description: '角色标识,如 admin' }, + role_id: { type: 'integer', description: '角色组ID(roles.id),为空表示未分配' }, + company_ids: { type: 'array', itemType: 'integer', description: '所属公司(下属公司)ID列表;非所有者至少一家' }, is_default: { type: 'integer', description: '是否默认主体:1是 0否,默认0' }, status: { type: 'integer', description: '状态:1启用 0禁用,默认1' }, }, invitePrincipalUserRequest: { email: { type: 'string', required: true, description: '被邀请人邮箱,全局唯一,创建后作为登录账号' }, - name: { type: 'string', required: true, description: '该账号在此主体下的名称(推送单据操作人取此值)' }, - avatar: { type: 'string', description: '该账号在此主体下的头像 URL(选填)' }, + name: { type: 'string', required: true, description: '该员工在此主体下的名称(推送单据操作人取此值)' }, + avatar: { type: 'string', description: '该员工在此主体下的头像 URL(选填)' }, principal_id: { type: 'integer', required: true, description: '目标主体ID,需当前账号已绑定该主体' }, + role_id: { type: 'integer', required: true, description: '角色组ID(必选)' }, + company_ids: { type: 'array', itemType: 'integer', required: true, description: '所属公司(下属公司)ID列表,至少一家' }, }, invitePrincipalUserData: { user_id: { type: 'integer', description: '新建用户ID' }, @@ -328,6 +376,77 @@ module.exports = { data: { type: 'invitePrincipalUserData', description: '开通结果,含明文初始密码' }, }, + // ---------- 权限管理 permissions / roles ---------- + permissionMenuRef: { + id: { type: 'integer', description: '菜单ID' }, + name: { type: 'string', description: '菜单名称(权限分类)' }, + icon: { type: 'string', description: '菜单图标' }, + path: { type: 'string', description: '菜单路径' }, + }, + permissionItem: { + id: { type: 'integer', description: '主键' }, + menu_id: { type: 'integer', description: '所属菜单(权限分类)ID' }, + name: { type: 'string', description: '权限名称' }, + code: { type: 'string', description: '权限标识(全局唯一)' }, + scope: { type: 'integer', description: '权限范围:1集团全部 2所在公司' }, + status: { type: 'integer', description: '状态:1启用 0禁用' }, + remark: { type: 'string', description: '备注' }, + menu: { type: 'permissionMenuRef', description: '所属菜单(权限分类)' }, + created_at: { type: 'string', description: '创建时间' }, + updated_at: { type: 'string', description: '更新时间' }, + }, + permissionPage: buildPage('permissionItem', '权限列表'), + permissionListResponse: buildListResponse('permissionPage'), + createPermissionRequest: { + menu_id: { type: 'integer', required: true, description: '所属菜单(权限分类)ID' }, + scope: { type: 'integer', required: true, description: '权限范围:1集团全部 2所在公司' }, + name: { type: 'string', description: '权限名称,不传按「菜单名(范围)」生成' }, + code: { type: 'string', description: '权限标识,不传按 menu_{菜单ID}_{group|company} 生成' }, + status: { type: 'integer', description: '状态:1启用 0禁用,默认1' }, + remark: { type: 'string', description: '备注' }, + }, + updatePermissionRequest: { + menu_id: { type: 'integer', description: '所属菜单(权限分类)ID' }, + name: { type: 'string', description: '权限名称' }, + status: { type: 'integer', description: '状态:1启用 0禁用' }, + remark: { type: 'string', description: '备注' }, + }, + roleRef: { + id: { type: 'integer', description: '角色组ID' }, + name: { type: 'string', description: '角色名称' }, + code: { type: 'string', description: '角色标识' }, + is_system: { type: 'integer', description: '是否系统预设:1是 0否' }, + }, + roleItem: { + id: { type: 'integer', description: '主键' }, + name: { type: 'string', description: '角色名称' }, + code: { type: 'string', description: '角色标识(全局唯一)' }, + is_system: { type: 'integer', description: '是否系统预设:1是(不可修改/删除) 0自定义' }, + status: { type: 'integer', description: '状态:1启用 0禁用' }, + remark: { type: 'string', description: '备注' }, + permission_ids: { type: 'array', itemType: 'integer', description: '已绑定的权限ID列表' }, + permission_count: { type: 'integer', description: '已绑定的权限数量' }, + permissions: { type: 'array', itemType: 'permissionItem', description: '已绑定的权限明细' }, + created_at: { type: 'string', description: '创建时间' }, + updated_at: { type: 'string', description: '更新时间' }, + }, + rolePage: buildPage('roleItem', '角色组列表'), + roleListResponse: buildListResponse('rolePage'), + createRoleRequest: { + name: { type: 'string', required: true, description: '角色名称(全局唯一)' }, + code: { type: 'string', description: '角色标识(全局唯一),不传自动生成' }, + status: { type: 'integer', description: '状态:1启用 0禁用,默认1' }, + remark: { type: 'string', description: '备注' }, + permission_ids: { type: 'array', itemType: 'integer', description: '要绑定的权限ID列表' }, + }, + updateRoleRequest: { + name: { type: 'string', description: '角色名称(全局唯一)' }, + code: { type: 'string', description: '角色标识(全局唯一)' }, + status: { type: 'integer', description: '状态:1启用 0禁用' }, + remark: { type: 'string', description: '备注' }, + permission_ids: { type: 'array', itemType: 'integer', description: '要绑定的权限ID列表(覆盖式)' }, + }, + // ---------- 商品 products ---------- productItem: { id: { type: 'integer', description: '主键' }, diff --git a/backend/app/controller/permission.js b/backend/app/controller/permission.js new file mode 100644 index 0000000..3abd65d --- /dev/null +++ b/backend/app/controller/permission.js @@ -0,0 +1,295 @@ +'use strict'; + +const { Controller } = require('egg'); +const { parsePagination, buildPageResult } = require('../lib/pagination'); + +/** 权限范围:1集团全部 2所在公司 */ +const SCOPES = { 1: { suffix: 'group', label: '集团全部' }, 2: { suffix: 'company', label: '所在公司' } }; + +/** + * @controller PermissionController 权限管理 + * 权限以「菜单」作为分类(menus 顶级菜单),每个菜单下两种权限子类:集团全部 / 所在公司。 + */ +class PermissionController extends Controller { + /** + * @summary 权限列表 + * @description 分页查询权限,按菜单分类返回;支持按菜单、权限范围、状态与关键词过滤 + * @router get /api/permissions + * @apikey + * @request query integer page 页码,默认 1 + * @request query integer pageSize 每页条数,默认 20 + * @request query integer menu_id 菜单(权限分类)ID + * @request query integer scope 权限范围:1集团全部 2所在公司 + * @request query integer status 状态:1启用 0禁用 + * @request query string keyword 关键词,匹配权限名称 / 标识 + * @response 200 permissionListResponse success + */ + async index() { + const { ctx } = this; + const Op = this.app.Sequelize.Op; + const { page, pageSize, offset, limit } = parsePagination(ctx.query); + const { menu_id: menuId, scope, status } = ctx.query; + + const where = {}; + if (menuId) where.menu_id = Number(menuId); + if (scope !== undefined && scope !== '') where.scope = Number(scope); + if (status !== undefined && status !== '') where.status = Number(status); + const text = String(ctx.query.keyword || '').trim(); + if (text) { + where[Op.or] = [ + { name: { [Op.like]: `%${text}%` } }, + { code: { [Op.like]: `%${text}%` } }, + ]; + } + + const { count, rows } = await ctx.model.Permission.findAndCountAll({ + where, + offset, + limit, + order: [[{ model: ctx.model.Menu, as: 'menu' }, 'sort', 'DESC' ], [ 'scope', 'ASC' ], [ 'id', 'ASC' ]], + include: [ + { model: ctx.model.Menu, as: 'menu', attributes: [ 'id', 'name', 'icon', 'path' ], required: false }, + ], + }); + + ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) }; + } + + /** + * @summary 权限分类(菜单下拉) + * @description 返回可作为权限分类的顶级菜单 + * @router get /api/permissions/menus + * @apikey + * @response 200 baseResponse success + */ + async menus() { + const { ctx } = this; + const rows = await ctx.model.Menu.findAll({ + where: { parent_id: 0 }, + attributes: [ 'id', 'name', 'icon', 'path', 'sort' ], + order: [[ 'sort', 'DESC' ], [ 'id', 'ASC' ]], + raw: true, + }); + ctx.body = { code: 0, message: 'success', data: rows }; + } + + /** + * @summary 权限详情 + * @router get /api/permissions/{id} + * @apikey + * @request path integer *id 权限主键ID + * @response 200 baseResponse success + */ + async show() { + const { ctx } = this; + const item = await ctx.model.Permission.findByPk(ctx.params.id, { + include: [ + { model: ctx.model.Menu, as: 'menu', attributes: [ 'id', 'name', 'icon', 'path' ], required: false }, + ], + }); + if (!item) { + ctx.status = 404; + ctx.body = { code: 404, message: '权限不存在' }; + return; + } + ctx.body = { code: 0, message: 'success', data: item }; + } + + /** + * @summary 新增权限 + * @description 同一菜单 + 同一权限范围唯一;未传名称/标识时按菜单与范围自动生成 + * @router post /api/permissions + * @apikey + * @request body createPermissionRequest *body + * @response 200 baseResponse success + */ + async create() { + const { ctx } = this; + const body = ctx.request.body || {}; + const menuId = Number(body.menu_id); + const scope = Number(body.scope); + + if (!menuId) { + ctx.status = 400; + ctx.body = { code: 400, message: '请选择权限分类(菜单)' }; + return; + } + const scopeMeta = SCOPES[scope]; + if (!scopeMeta) { + ctx.status = 400; + ctx.body = { code: 400, message: '权限范围只能为:1集团全部 2所在公司' }; + return; + } + + const menu = await ctx.model.Menu.findByPk(menuId); + if (!menu) { + ctx.status = 404; + ctx.body = { code: 404, message: '菜单不存在' }; + return; + } + + const exist = await ctx.model.Permission.findOne({ where: { menu_id: menuId, scope } }); + if (exist) { + ctx.status = 400; + ctx.body = { code: 400, message: `「${menu.name}」下已存在${scopeMeta.label}权限` }; + return; + } + + const name = String(body.name || '').trim() || `${menu.name}(${scopeMeta.label})`; + const code = String(body.code || '').trim() || `menu_${menuId}_${scopeMeta.suffix}`; + const codeExist = await ctx.model.Permission.findOne({ where: { code } }); + if (codeExist) { + ctx.status = 400; + ctx.body = { code: 400, message: '权限标识已存在' }; + return; + } + + const item = await ctx.model.Permission.create({ + menu_id: menuId, + scope, + name, + code, + status: body.status === undefined ? 1 : Number(body.status) === 0 ? 0 : 1, + remark: body.remark == null ? null : String(body.remark).trim(), + }); + ctx.body = { code: 0, message: 'success', data: { id: item.id } }; + } + + /** + * @summary 更新权限 + * @description 未传入的字段保持原值;菜单 + 范围唯一 + * @router put /api/permissions/{id} + * @apikey + * @request path integer *id 权限主键ID + * @request body updatePermissionRequest *body + * @response 200 baseResponse success + */ + async update() { + const { ctx } = this; + const item = await ctx.model.Permission.findByPk(ctx.params.id); + if (!item) { + ctx.status = 404; + ctx.body = { code: 404, message: '权限不存在' }; + return; + } + + const body = ctx.request.body || {}; + const patch = {}; + for (const key of [ 'menu_id', 'name', 'status', 'remark' ]) { + if (body[key] !== undefined) patch[key] = body[key]; + } + if (patch.menu_id !== undefined) { + const menu = await ctx.model.Menu.findByPk(Number(patch.menu_id)); + if (!menu) { + ctx.status = 404; + ctx.body = { code: 404, message: '菜单不存在' }; + return; + } + patch.menu_id = Number(patch.menu_id); + } + if (patch.name !== undefined) { + const name = String(patch.name || '').trim(); + if (!name) { + ctx.status = 400; + ctx.body = { code: 400, message: '权限名称不能为空' }; + return; + } + patch.name = name; + } + if (patch.status !== undefined) patch.status = Number(patch.status) === 0 ? 0 : 1; + if (patch.remark !== undefined) { + patch.remark = patch.remark == null || String(patch.remark).trim() === '' + ? null + : String(patch.remark).trim(); + } + + const menuId = patch.menu_id === undefined ? Number(item.menu_id) : patch.menu_id; + if (patch.menu_id !== undefined) { + const exist = await ctx.model.Permission.findOne({ where: { menu_id: menuId, scope: item.scope } }); + if (exist && Number(exist.id) !== Number(item.id)) { + ctx.status = 400; + ctx.body = { code: 400, message: '该菜单下已存在相同范围的权限' }; + return; + } + } + + await item.update(patch); + ctx.body = { code: 0, message: 'success', data: { id: item.id } }; + } + + /** + * @summary 删除权限 + * @description 被系统预设角色使用的权限不可删除(可改为禁用);删除时同时解除自定义角色的绑定 + * @router delete /api/permissions/{id} + * @apikey + * @request path integer *id 权限主键ID + * @response 200 baseResponse success + */ + async destroy() { + const { ctx } = this; + const item = await ctx.model.Permission.findByPk(ctx.params.id); + if (!item) { + ctx.status = 404; + ctx.body = { code: 404, message: '权限不存在' }; + return; + } + + // 系统预设角色(系统管理员 / 货主权限)的权限集合固定,禁止删除其占用的权限 + const boundRows = await ctx.model.RolePermission.findAll({ + where: { permission_id: item.id }, + attributes: [ 'role_id' ], + raw: true, + }); + const boundSystem = boundRows.length + ? await ctx.model.Role.count({ where: { id: boundRows.map(row => row.role_id), is_system: 1 } }) + : 0; + if (boundSystem > 0) { + ctx.status = 400; + ctx.body = { code: 400, message: '该权限已被系统预设角色使用,无法删除;如需停用请改为禁用' }; + return; + } + + await ctx.model.RolePermission.destroy({ where: { permission_id: item.id } }); + await item.destroy(); + ctx.body = { code: 0, message: 'success', data: { id: Number(item.id) } }; + } + + /** + * @summary 同步菜单权限 + * @description 为每个顶级菜单补齐「集团全部 / 所在公司」两种权限,已存在的跳过;新菜单上线后可手动同步 + * @router post /api/permissions/sync + * @apikey + * @response 200 baseResponse success + */ + async sync() { + const { ctx } = this; + const menus = await ctx.model.Menu.findAll({ + where: { parent_id: 0 }, + attributes: [ 'id', 'name' ], + order: [[ 'sort', 'DESC' ], [ 'id', 'ASC' ]], + }); + const existRows = await ctx.model.Permission.findAll({ attributes: [ 'menu_id', 'scope' ], raw: true }); + const existKeys = new Set(existRows.map(row => `${Number(row.menu_id)}:${Number(row.scope)}`)); + + let created = 0; + for (const menu of menus) { + for (const scope of [ 1, 2 ]) { + const scopeMeta = SCOPES[scope]; + if (existKeys.has(`${Number(menu.id)}:${scope}`)) continue; + await ctx.model.Permission.create({ + menu_id: menu.id, + scope, + name: `${menu.name}(${scopeMeta.label})`, + code: `menu_${menu.id}_${scopeMeta.suffix}`, + status: 1, + remark: `菜单「${menu.name}」的${scopeMeta.label}权限`, + }); + created++; + } + } + + ctx.body = { code: 0, message: 'success', data: { created } }; + } +} + +module.exports = PermissionController; diff --git a/backend/app/controller/principal.js b/backend/app/controller/principal.js index 09fa77c..0c2577d 100644 --- a/backend/app/controller/principal.js +++ b/backend/app/controller/principal.js @@ -3,6 +3,9 @@ const { Controller } = require('egg'); const { parsePagination, buildPageResult } = require('../lib/pagination'); +/** 允许更新的主体字段,避免请求体覆盖 id 等主键信息 */ +const WRITABLE_FIELDS = [ 'name', 'type', 'contact_name', 'contact_phone', 'status', 'remark' ]; + /** * @controller PrincipalController 主体管理 */ @@ -71,6 +74,13 @@ class PrincipalController extends Controller { */ async show() { const { ctx } = this; + const bound = await this.isBound(ctx.params.id); + if (!bound) { + ctx.status = 403; + ctx.body = { code: 403, message: '无权查看该主体' }; + return; + } + const principal = await ctx.service.cache.getPrincipal(ctx.params.id); if (!principal) { @@ -130,6 +140,13 @@ class PrincipalController extends Controller { */ async update() { const { ctx } = this; + const bound = await this.isBound(ctx.params.id); + if (!bound) { + ctx.status = 403; + ctx.body = { code: 403, message: '无权操作该主体' }; + return; + } + const principal = await ctx.model.Principal.findByPk(ctx.params.id); if (!principal) { @@ -138,7 +155,12 @@ class PrincipalController extends Controller { return; } - await principal.update(ctx.request.body); + const data = {}; + WRITABLE_FIELDS.forEach(field => { + if (ctx.request.body[field] !== undefined) data[field] = ctx.request.body[field]; + }); + + await principal.update(data); // 主体信息变更:失效主体详情缓存及所有依赖主体信息的缓存(可选主体列表等) await ctx.service.cache.invalidatePrincipal(principal.id); @@ -183,6 +205,17 @@ class PrincipalController extends Controller { ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } }; } + + /** + * 校验当前账号是否绑定该主体(组织架构 → 集团设置只允许操作/查看自己所属主体) + * @param {number|string} principalId 主体ID + * @return {Promise} 是否已绑定 + */ + async isBound(principalId) { + const { ctx } = this; + const principalIds = ctx.state.principalIds || await ctx.service.cache.getUserPrincipalIds(ctx.userId); + return new Set((principalIds || []).map(Number)).has(Number(principalId)); + } } module.exports = PrincipalController; diff --git a/backend/app/controller/principalSubsidiary.js b/backend/app/controller/principalSubsidiary.js new file mode 100644 index 0000000..ece2527 --- /dev/null +++ b/backend/app/controller/principalSubsidiary.js @@ -0,0 +1,205 @@ +'use strict'; + +const { Controller } = require('egg'); +const { parsePagination, buildPageResult } = require('../lib/pagination'); + +/** 允许前端写入的字段,避免覆盖 principal_id 等归属信息 */ +const WRITABLE_FIELDS = [ 'name', 'credit_code', 'contact_name', 'contact_phone', 'address', 'status', 'remark' ]; + +/** 取请求体中的可写字段(未传的字段保持原值) + * @param {Object} body 请求体 + * @return {Object} 可写字段 + */ +function pickWritable(body) { + const data = {}; + WRITABLE_FIELDS.forEach(field => { + if (body[field] !== undefined) data[field] = body[field]; + }); + return data; +} + +/** + * @controller PrincipalSubsidiaryController 组织架构 → 下属公司 + * 数据按当前主体(ctx.state.principalId)隔离:集团主体下拉切换后只看到该主体下的公司档案。 + */ +class PrincipalSubsidiaryController extends Controller { + /** + * @summary 下属公司列表 + * @description 分页查询当前主体下的下属公司,支持关键词(公司名称/信用代码/联系人)与状态过滤 + * @router get /api/principal-subsidiaries + * @apikey + * @request query integer page 页码,默认 1 + * @request query integer pageSize 每页条数,默认 20 + * @request query string keyword 关键词,匹配公司名称 / 统一社会信用代码 / 联系人 + * @request query integer status 状态:1启用 0禁用,不传则不过滤 + * @response 200 principalSubsidiaryListResponse success + */ + async index() { + const { ctx } = this; + const Op = this.app.Sequelize.Op; + const { page, pageSize, offset, limit } = parsePagination(ctx.query); + const { keyword, status } = ctx.query; + + const where = { principal_id: ctx.state.principalId }; + const text = String(keyword || '').trim(); + if (text) { + where[Op.or] = [ + { name: { [Op.like]: `%${text}%` } }, + { credit_code: { [Op.like]: `%${text}%` } }, + { contact_name: { [Op.like]: `%${text}%` } }, + ]; + } + if (status !== undefined && status !== '') where.status = Number(status); + + const { count, rows } = await ctx.model.PrincipalSubsidiary.findAndCountAll({ + where, + offset, + limit, + order: [[ 'id', 'DESC' ]], + }); + + ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) }; + } + + /** + * @summary 下属公司下拉(仅启用) + * @description 供员工档案等页面选择所属公司,按当前主体隔离 + * @router get /api/principal-subsidiaries/select + * @apikey + * @response 200 baseResponse success + */ + async select() { + const { ctx } = this; + const rows = await ctx.model.PrincipalSubsidiary.findAll({ + where: { principal_id: ctx.state.principalId, status: 1 }, + attributes: [ 'id', 'name' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + ctx.body = { code: 0, message: 'success', data: rows }; + } + + /** + * @summary 下属公司详情 + * @router get /api/principal-subsidiaries/{id} + * @apikey + * @request path integer *id 下属公司主键ID + * @response 200 baseResponse success + */ + async show() { + const { ctx } = this; + const item = await this.findScoped(ctx.params.id); + if (!item) { + ctx.status = 404; + ctx.body = { code: 404, message: '下属公司不存在' }; + return; + } + ctx.body = { code: 0, message: 'success', data: item }; + } + + /** + * @summary 新增下属公司 + * @description 同一主体下公司名称唯一 + * @router post /api/principal-subsidiaries + * @apikey + * @request body createPrincipalSubsidiaryRequest *body + * @response 200 baseResponse success + */ + async create() { + const { ctx } = this; + const principalId = ctx.state.principalId; + const data = pickWritable(ctx.request.body || {}); + const name = String(data.name || '').trim(); + + if (!name) { + ctx.status = 400; + ctx.body = { code: 400, message: '公司名称为必填项' }; + return; + } + + const exist = await ctx.model.PrincipalSubsidiary.findOne({ where: { principal_id: principalId, name } }); + if (exist) { + ctx.status = 400; + ctx.body = { code: 400, message: '该主体下已存在同名公司' }; + return; + } + + const item = await ctx.model.PrincipalSubsidiary.create({ ...data, name, principal_id: principalId }); + ctx.body = { code: 0, message: 'success', data: { id: item.id } }; + } + + /** + * @summary 更新下属公司 + * @description 未传入的字段保持原值;同一主体下公司名称唯一 + * @router put /api/principal-subsidiaries/{id} + * @apikey + * @request path integer *id 下属公司主键ID + * @request body updatePrincipalSubsidiaryRequest *body + * @response 200 baseResponse success + */ + async update() { + const { ctx } = this; + const item = await this.findScoped(ctx.params.id); + if (!item) { + ctx.status = 404; + ctx.body = { code: 404, message: '下属公司不存在' }; + return; + } + + const data = pickWritable(ctx.request.body || {}); + if (data.name !== undefined) { + const name = String(data.name || '').trim(); + if (!name) { + ctx.status = 400; + ctx.body = { code: 400, message: '公司名称为必填项' }; + return; + } + const exist = await ctx.model.PrincipalSubsidiary.findOne({ + where: { principal_id: item.principal_id, name }, + }); + if (exist && Number(exist.id) !== Number(item.id)) { + ctx.status = 400; + ctx.body = { code: 400, message: '该主体下已存在同名公司' }; + return; + } + data.name = name; + } + + await item.update(data); + ctx.body = { code: 0, message: 'success', data: { id: item.id } }; + } + + /** + * @summary 删除下属公司 + * @router delete /api/principal-subsidiaries/{id} + * @apikey + * @request path integer *id 下属公司主键ID + * @response 200 baseResponse success + */ + async destroy() { + const { ctx } = this; + const item = await this.findScoped(ctx.params.id); + if (!item) { + ctx.status = 404; + ctx.body = { code: 404, message: '下属公司不存在' }; + return; + } + + await item.destroy(); + ctx.body = { code: 0, message: 'success', data: { id: Number(item.id) } }; + } + + /** + * 按当前主体取下属公司,避免同一账号切换主体后操作到其它主体(集团)的数据 + * @param {number|string} id 下属公司主键 + * @return {Promise} 下属公司记录 + */ + async findScoped(id) { + const { ctx } = this; + return await ctx.model.PrincipalSubsidiary.findOne({ + where: { id, principal_id: ctx.state.principalId }, + }); + } +} + +module.exports = PrincipalSubsidiaryController; diff --git a/backend/app/controller/principalUser.js b/backend/app/controller/principalUser.js index 63a8938..5fe95aa 100644 --- a/backend/app/controller/principalUser.js +++ b/backend/app/controller/principalUser.js @@ -19,32 +19,57 @@ class PrincipalUserController extends Controller { * @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, status } = 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 }, + ], + }, ], }); - ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) }; + 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 }) }; } /** @@ -61,6 +86,16 @@ class PrincipalUserController extends Controller { 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 }, + ], + }, ], }); @@ -83,7 +118,8 @@ class PrincipalUserController extends Controller { */ async create() { const { ctx } = this; - const { principal_id: principalId, user_id: userId } = ctx.request.body; + const body = ctx.request.body || {}; + const { principal_id: principalId, user_id: userId } = body; if (!principalId || !userId) { ctx.status = 400; @@ -100,7 +136,27 @@ class PrincipalUserController extends Controller { return; } - const relation = await ctx.model.PrincipalUser.create(ctx.request.body); + 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 } }; @@ -108,8 +164,8 @@ class PrincipalUserController extends Controller { /** * @summary 邀请开通主体账号 - * @description 传入邮箱、用户名称(写入主体账号关联表 principal_users.name)与主体ID, - * 自动创建新用户(随机初始密码)并绑定到该主体(角色 member); + * @description 传入邮箱、用户名称(写入主体账号关联表 principal_users.name)、主体ID、角色组与所属公司, + * 自动创建新用户(随机初始密码)并绑定到该主体;角色组必选,除所有者外必须至少关联一家公司; * 返回明文随机密码,需由调用方妥善交付给被邀请人;同一邮箱不可重复开通 * @router post /api/principal-users/invite * @apikey @@ -119,7 +175,14 @@ class PrincipalUserController extends Controller { async invite() { const { ctx } = this; const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; - const { email, name, avatar, principal_id: principalId } = ctx.request.body; + 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; @@ -153,6 +216,28 @@ class PrincipalUserController extends Controller { 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(); @@ -175,10 +260,21 @@ class PrincipalUserController extends Controller { 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); @@ -217,8 +313,9 @@ class PrincipalUserController extends Controller { /** * @summary 更新关联信息 - * @description 可修改该账号在此主体下的名称(name)、头像(avatar)、角色、默认主体标识与状态; - * 名称/头像即账号显示资料,推送单据的操作人取名称;不允许改归属(principal_id / user_id),非白名单字段一律忽略 + * @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 @@ -236,11 +333,24 @@ class PrincipalUserController extends Controller { } const body = ctx.request.body || {}; - // 只接受名称/头像/角色/默认标识/状态,避免改归属或写入无关字段 + // 只接受名称/头像/角色/角色组/默认标识/状态,避免改归属或写入无关字段 const patch = {}; - for (const key of [ 'name', 'avatar', 'role', 'is_default', 'status' ]) { + 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) { @@ -256,7 +366,29 @@ class PrincipalUserController extends Controller { : 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, @@ -267,7 +399,7 @@ class PrincipalUserController extends Controller { /** * @summary 解绑用户与主体 - * @description 物理删除关联记录 + * @description 物理删除关联记录(同时清理员工所属公司关联) * @router delete /api/principal-users/{id} * @apikey * @request path integer *id 关联记录主键ID @@ -284,10 +416,45 @@ class PrincipalUserController extends Controller { } 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; diff --git a/backend/app/controller/role.js b/backend/app/controller/role.js new file mode 100644 index 0000000..ba82b3e --- /dev/null +++ b/backend/app/controller/role.js @@ -0,0 +1,288 @@ +'use strict'; + +const { Controller } = require('egg'); +const { parsePagination, buildPageResult } = require('../lib/pagination'); + +/** + * @controller RoleController 角色组(权限管理) + * 角色组维护「权限集合」,账号通过 principal_users.role_id 关联角色组。 + * is_system=1 的系统预设角色(系统管理员 / 货主权限)只读,不可修改/删除。 + */ +class RoleController extends Controller { + /** + * @summary 角色组列表 + * @description 分页查询角色组,带出已绑定的权限;支持关键词、系统预设与状态过滤 + * @router get /api/roles + * @apikey + * @request query integer page 页码,默认 1 + * @request query integer pageSize 每页条数,默认 20 + * @request query string keyword 关键词,匹配角色名称 / 标识 + * @request query integer is_system 是否系统预设:1是 0否 + * @request query integer status 状态:1启用 0禁用 + * @response 200 roleListResponse success + */ + async index() { + const { ctx } = this; + const Op = this.app.Sequelize.Op; + const { page, pageSize, offset, limit } = parsePagination(ctx.query); + const { is_system: isSystem, status } = ctx.query; + + const where = {}; + if (isSystem !== undefined && isSystem !== '') where.is_system = Number(isSystem) === 1 ? 1 : 0; + if (status !== undefined && status !== '') where.status = Number(status) === 0 ? 0 : 1; + const text = String(ctx.query.keyword || '').trim(); + if (text) { + where[Op.or] = [ + { name: { [Op.like]: `%${text}%` } }, + { code: { [Op.like]: `%${text}%` } }, + ]; + } + + const { count, rows } = await ctx.model.Role.findAndCountAll({ + where, + offset, + limit, + // 角色与权限是一对多 join,需去重计数,否则总数按权限条数统计 + distinct: true, + order: [[ 'is_system', 'DESC' ], [ 'id', 'ASC' ]], + include: [ + { + model: ctx.model.Permission, + as: 'permissions', + attributes: [ 'id', 'menu_id', 'name', 'code', 'scope', 'status' ], + through: { attributes: [] }, + required: false, + }, + ], + }); + + const list = rows.map(row => { + const plain = row.toJSON(); + plain.permission_ids = (plain.permissions || []).map(item => Number(item.id)); + plain.permission_count = plain.permission_ids.length; + return plain; + }); + + ctx.body = { code: 0, message: 'success', data: buildPageResult(list, count, { page, pageSize }) }; + } + + /** + * @summary 角色组下拉 + * @description 返回启用的角色组,供「账号」页面分配角色组使用 + * @router get /api/roles/options + * @apikey + * @response 200 baseResponse success + */ + async options() { + const { ctx } = this; + const rows = await ctx.model.Role.findAll({ + where: { status: 1 }, + attributes: [ 'id', 'name', 'code', 'is_system' ], + order: [[ 'is_system', 'DESC' ], [ 'id', 'ASC' ]], + raw: true, + }); + ctx.body = { code: 0, message: 'success', data: rows }; + } + + /** + * @summary 角色组详情 + * @router get /api/roles/{id} + * @apikey + * @request path integer *id 角色组主键ID + * @response 200 baseResponse success + */ + async show() { + const { ctx } = this; + const role = await ctx.model.Role.findByPk(ctx.params.id, { + include: [ + { + model: ctx.model.Permission, + as: 'permissions', + attributes: [ 'id', 'menu_id', 'name', 'code', 'scope', 'status' ], + through: { attributes: [] }, + required: false, + }, + ], + }); + if (!role) { + ctx.status = 404; + ctx.body = { code: 404, message: '角色组不存在' }; + return; + } + ctx.body = { code: 0, message: 'success', data: role }; + } + + /** + * @summary 新增角色组 + * @description 名称与标识全局唯一;permission_ids 为要绑定的权限ID列表 + * @router post /api/roles + * @apikey + * @request body createRoleRequest *body + * @response 200 baseResponse success + */ + async create() { + const { ctx } = this; + const body = ctx.request.body || {}; + const name = String(body.name || '').trim(); + if (!name) { + ctx.status = 400; + ctx.body = { code: 400, message: '角色名称不能为空' }; + return; + } + + const nameExist = await ctx.model.Role.findOne({ where: { name } }); + if (nameExist) { + ctx.status = 400; + ctx.body = { code: 400, message: '角色名称已存在' }; + return; + } + + const code = String(body.code || '').trim() || `role_${Date.now().toString(36)}`; + const codeExist = await ctx.model.Role.findOne({ where: { code } }); + if (codeExist) { + ctx.status = 400; + ctx.body = { code: 400, message: '角色标识已存在' }; + return; + } + + const permissionIds = await this.resolvePermissionIds(body.permission_ids); + + const role = await ctx.model.Role.create({ + name, + code, + is_system: 0, + status: body.status === undefined ? 1 : Number(body.status) === 0 ? 0 : 1, + remark: body.remark == null ? null : String(body.remark).trim(), + }); + await this.syncPermissions(role.id, permissionIds); + + ctx.body = { code: 0, message: 'success', data: { id: role.id } }; + } + + /** + * @summary 更新角色组 + * @description 系统预设角色只读;未传入的字段保持原值 + * @router put /api/roles/{id} + * @apikey + * @request path integer *id 角色组主键ID + * @request body updateRoleRequest *body + * @response 200 baseResponse success + */ + async update() { + const { ctx } = this; + const role = await ctx.model.Role.findByPk(ctx.params.id); + if (!role) { + ctx.status = 404; + ctx.body = { code: 404, message: '角色组不存在' }; + return; + } + if (Number(role.is_system) === 1) { + ctx.status = 400; + ctx.body = { code: 400, message: '系统预设角色不可修改' }; + return; + } + + const body = ctx.request.body || {}; + const patch = {}; + if (body.name !== undefined) { + const name = String(body.name || '').trim(); + if (!name) { + ctx.status = 400; + ctx.body = { code: 400, message: '角色名称不能为空' }; + return; + } + const exist = await ctx.model.Role.findOne({ where: { name } }); + if (exist && Number(exist.id) !== Number(role.id)) { + ctx.status = 400; + ctx.body = { code: 400, message: '角色名称已存在' }; + return; + } + patch.name = name; + } + if (body.code !== undefined) { + const code = String(body.code || '').trim(); + if (!code) { + ctx.status = 400; + ctx.body = { code: 400, message: '角色标识不能为空' }; + return; + } + const exist = await ctx.model.Role.findOne({ where: { code } }); + if (exist && Number(exist.id) !== Number(role.id)) { + ctx.status = 400; + ctx.body = { code: 400, message: '角色标识已存在' }; + return; + } + patch.code = code; + } + if (body.status !== undefined) patch.status = Number(body.status) === 0 ? 0 : 1; + if (body.remark !== undefined) { + patch.remark = body.remark == null || String(body.remark).trim() === '' + ? null + : String(body.remark).trim(); + } + + await role.update(patch); + if (body.permission_ids !== undefined) { + const permissionIds = await this.resolvePermissionIds(body.permission_ids); + await this.syncPermissions(role.id, permissionIds); + } + + ctx.body = { code: 0, message: 'success', data: { id: role.id } }; + } + + /** + * @summary 删除角色组 + * @description 系统预设角色不可删除;删除后账号的角色组置空 + * @router delete /api/roles/{id} + * @apikey + * @request path integer *id 角色组主键ID + * @response 200 baseResponse success + */ + async destroy() { + const { ctx } = this; + const role = await ctx.model.Role.findByPk(ctx.params.id); + if (!role) { + ctx.status = 404; + ctx.body = { code: 404, message: '角色组不存在' }; + return; + } + if (Number(role.is_system) === 1) { + ctx.status = 400; + ctx.body = { code: 400, message: '系统预设角色不可删除' }; + return; + } + + await ctx.model.PrincipalUser.update({ role_id: null }, { where: { role_id: role.id } }); + await ctx.model.RolePermission.destroy({ where: { role_id: role.id } }); + await role.destroy(); + + ctx.body = { code: 0, message: 'success', data: { id: Number(role.id) } }; + } + + /** + * 校验并去重权限ID(忽略不存在的ID) + * @param {Array} input 权限ID列表 + * @return {Promise>} 有效权限ID + */ + async resolvePermissionIds(input) { + const ids = Array.isArray(input) ? [ ...new Set(input.map(Number).filter(id => id > 0)) ] : []; + if (!ids.length) return []; + const rows = await this.ctx.model.Permission.findAll({ where: { id: ids }, attributes: [ 'id' ], raw: true }); + return rows.map(row => Number(row.id)); + } + + /** + * 覆盖式同步角色权限 + * @param {number} roleId 角色ID + * @param {Array} permissionIds 权限ID列表 + * @return {Promise} 无返回值 + */ + async syncPermissions(roleId, permissionIds) { + const { ctx } = this; + await ctx.model.RolePermission.destroy({ where: { role_id: roleId } }); + if (!permissionIds.length) return; + await ctx.model.RolePermission.bulkCreate(permissionIds.map(permissionId => ({ role_id: roleId, permission_id: permissionId }))); + } +} + +module.exports = RoleController; diff --git a/backend/app/model/permission.js b/backend/app/model/permission.js new file mode 100644 index 0000000..0455d86 --- /dev/null +++ b/backend/app/model/permission.js @@ -0,0 +1,41 @@ +'use strict'; + +/** + * 权限模型,对应 permissions 表。 + * + * 以「菜单」作为权限分类,每个菜单下两种权限子类: + * - scope=1 集团全部:该菜单下的能力对整个集团(全部主体)生效 + * - scope=2 所在公司:该菜单下的能力仅对当前所在公司(当前主体)生效 + * @param {Egg.Application} app egg application + * @return {object} permission model + */ +module.exports = app => { + const { BIGINT, STRING, TINYINT, DATE } = app.Sequelize; + + const Permission = app.model.define('permission', { + id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' }, + menu_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属菜单(权限分类)ID' }, + name: { type: STRING(100), allowNull: false, comment: '权限名称' }, + code: { type: STRING(100), allowNull: false, comment: '权限标识(全局唯一)' }, + scope: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '权限范围:1集团全部 2所在公司' }, + status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' }, + remark: { type: STRING(255), comment: '备注' }, + created_at: { type: DATE, comment: '创建时间' }, + updated_at: { type: DATE, comment: '更新时间' }, + }, { + tableName: 'permissions', + comment: '权限表', + }); + + Permission.associate = () => { + app.model.Permission.belongsTo(app.model.Menu, { foreignKey: 'menu_id', as: 'menu' }); + app.model.Permission.belongsToMany(app.model.Role, { + through: app.model.RolePermission, + foreignKey: 'permission_id', + otherKey: 'role_id', + as: 'roles', + }); + }; + + return Permission; +}; diff --git a/backend/app/model/principal.js b/backend/app/model/principal.js index 3df44b7..680fb79 100644 --- a/backend/app/model/principal.js +++ b/backend/app/model/principal.js @@ -34,6 +34,7 @@ module.exports = app => { app.model.Principal.hasMany(app.model.Shop, { foreignKey: 'principal_id', as: 'shops' }); app.model.Principal.hasMany(app.model.Warehouse, { foreignKey: 'principal_id', as: 'warehouses' }); app.model.Principal.hasMany(app.model.WarehouseApi, { foreignKey: 'principal_id', as: 'warehouseApis' }); + app.model.Principal.hasMany(app.model.PrincipalSubsidiary, { foreignKey: 'principal_id', as: 'subsidiaries' }); }; return Principal; diff --git a/backend/app/model/principalSubsidiary.js b/backend/app/model/principalSubsidiary.js new file mode 100644 index 0000000..b6dabbb --- /dev/null +++ b/backend/app/model/principalSubsidiary.js @@ -0,0 +1,36 @@ +'use strict'; + +/** + * 下属公司模型,对应 principal_subsidiaries 表(按主体隔离)。 + * + * 组织架构 → 下属公司:登记集团(当前主体)下属的公司档案, + * 仅用于档案维护,不参与商品/订单等业务数据归属。 + * @param {Egg.Application} app egg application + * @return {object} principalSubsidiary model + */ +module.exports = app => { + const { BIGINT, STRING, TINYINT, DATE } = app.Sequelize; + + const PrincipalSubsidiary = app.model.define('principal_subsidiary', { + id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' }, + principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体(集团)ID' }, + name: { type: STRING(100), allowNull: false, comment: '公司名称' }, + credit_code: { type: STRING(50), comment: '统一社会信用代码' }, + contact_name: { type: STRING(50), comment: '联系人' }, + contact_phone: { type: STRING(20), comment: '联系电话' }, + address: { type: STRING(255), comment: '公司地址' }, + status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' }, + remark: { type: STRING(255), comment: '备注' }, + created_at: { type: DATE, comment: '创建时间' }, + updated_at: { type: DATE, comment: '更新时间' }, + }, { + tableName: 'principal_subsidiaries', + comment: '下属公司', + }); + + PrincipalSubsidiary.associate = () => { + app.model.PrincipalSubsidiary.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' }); + }; + + return PrincipalSubsidiary; +}; diff --git a/backend/app/model/principalUser.js b/backend/app/model/principalUser.js index c92db5d..3dc83b8 100644 --- a/backend/app/model/principalUser.js +++ b/backend/app/model/principalUser.js @@ -15,6 +15,7 @@ module.exports = app => { name: { type: STRING(50), allowNull: true, comment: '该账号在此主体下的显示名称(推送单据操作人取此值)' }, avatar: { type: STRING(255), allowNull: true, comment: '该账号在此主体下的头像 URL' }, role: { type: STRING(50), comment: '该主体下的角色标识' }, + role_id: { type: BIGINT.UNSIGNED, allowNull: true, comment: '角色组ID(roles.id)' }, is_default: { type: TINYINT, allowNull: false, defaultValue: 0, comment: '是否默认主体:1是 0否' }, status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' }, created_at: { type: DATE, comment: '创建时间' }, @@ -24,6 +25,8 @@ module.exports = app => { PrincipalUser.associate = () => { app.model.PrincipalUser.belongsTo(app.model.User, { foreignKey: 'user_id', as: 'user' }); app.model.PrincipalUser.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' }); + app.model.PrincipalUser.belongsTo(app.model.Role, { foreignKey: 'role_id', as: 'roleGroup' }); + app.model.PrincipalUser.hasMany(app.model.PrincipalUserCompany, { foreignKey: 'principal_user_id', as: 'companies' }); }; return PrincipalUser; diff --git a/backend/app/model/principalUserCompany.js b/backend/app/model/principalUserCompany.js new file mode 100644 index 0000000..79da7fe --- /dev/null +++ b/backend/app/model/principalUserCompany.js @@ -0,0 +1,29 @@ +'use strict'; + +/** + * 员工所属公司关联模型,对应 principal_user_companies 表。 + * @param {Egg.Application} app egg application + * @return {object} principalUserCompany model + */ +module.exports = app => { + const { BIGINT, DATE } = app.Sequelize; + + const PrincipalUserCompany = app.model.define('principal_user_company', { + id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' }, + principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体(集团)ID' }, + principal_user_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '员工(主体账号关联记录)ID' }, + subsidiary_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '下属公司ID' }, + created_at: { type: DATE, comment: '创建时间' }, + updated_at: { type: DATE, comment: '更新时间' }, + }, { + tableName: 'principal_user_companies', + comment: '员工所属公司关联', + }); + + PrincipalUserCompany.associate = () => { + app.model.PrincipalUserCompany.belongsTo(app.model.PrincipalUser, { foreignKey: 'principal_user_id', as: 'principalUser' }); + app.model.PrincipalUserCompany.belongsTo(app.model.PrincipalSubsidiary, { foreignKey: 'subsidiary_id', as: 'subsidiary' }); + }; + + return PrincipalUserCompany; +}; diff --git a/backend/app/model/role.js b/backend/app/model/role.js new file mode 100644 index 0000000..35e6083 --- /dev/null +++ b/backend/app/model/role.js @@ -0,0 +1,39 @@ +'use strict'; + +/** + * 角色组模型,对应 roles 表。 + * + * is_system=1 为系统预设角色(当前为「系统管理员」「货主权限」),不可删除; + * 角色与权限为多对多(role_permissions),账号通过 principal_users.role_id 关联角色组。 + * @param {Egg.Application} app egg application + * @return {object} role model + */ +module.exports = app => { + const { BIGINT, STRING, TINYINT, DATE } = app.Sequelize; + + const Role = app.model.define('role', { + id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' }, + name: { type: STRING(50), allowNull: false, comment: '角色名称' }, + code: { type: STRING(50), allowNull: false, comment: '角色标识(全局唯一)' }, + is_system: { type: TINYINT, allowNull: false, defaultValue: 0, comment: '是否系统预设:1是(不可删除) 0自定义' }, + status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' }, + remark: { type: STRING(255), comment: '备注' }, + created_at: { type: DATE, comment: '创建时间' }, + updated_at: { type: DATE, comment: '更新时间' }, + }, { + tableName: 'roles', + comment: '角色组', + }); + + Role.associate = () => { + app.model.Role.belongsToMany(app.model.Permission, { + through: app.model.RolePermission, + foreignKey: 'role_id', + otherKey: 'permission_id', + as: 'permissions', + }); + app.model.Role.hasMany(app.model.PrincipalUser, { foreignKey: 'role_id', as: 'principalUsers' }); + }; + + return Role; +}; diff --git a/backend/app/model/rolePermission.js b/backend/app/model/rolePermission.js new file mode 100644 index 0000000..78bf55b --- /dev/null +++ b/backend/app/model/rolePermission.js @@ -0,0 +1,23 @@ +'use strict'; + +/** + * 角色权限关联模型,对应 role_permissions 表。 + * @param {Egg.Application} app egg application + * @return {object} rolePermission model + */ +module.exports = app => { + const { BIGINT, DATE } = app.Sequelize; + + const RolePermission = app.model.define('role_permission', { + id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' }, + role_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '角色ID' }, + permission_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '权限ID' }, + created_at: { type: DATE, comment: '创建时间' }, + updated_at: { type: DATE, comment: '更新时间' }, + }, { + tableName: 'role_permissions', + comment: '角色权限关联', + }); + + return RolePermission; +}; diff --git a/backend/app/router.js b/backend/app/router.js index 01c24a2..a254178 100644 --- a/backend/app/router.js +++ b/backend/app/router.js @@ -50,8 +50,20 @@ module.exports = app => { router.get('/api/principals/options', jwtAuth, controller.principal.options); // 管理端主体列表(不缓存,保证分页与筛选实时) router.resources('principals', '/api/principals', jwtAuth, controller.principal); + // 组织架构 → 下属公司:按当前主体隔离(列表/新增取入参主体,详情/更新/删除按记录所属主体鉴权) + // select 需在 resources 之前注册,避免被 /:id 误匹配 + router.get('/api/principal-subsidiaries/select', jwtAuth, principalCheck(), controller.principalSubsidiary.select); + router.resources('principalSubsidiaries', '/api/principal-subsidiaries', jwtAuth, principalCheck({ model: 'PrincipalSubsidiary' }), controller.principalSubsidiary); // 主体用户关联:需校验主体绑定关系 router.resources('principalUsers', '/api/principal-users', jwtAuth, principalCheck({ model: 'PrincipalUser' }), controller.principalUser); + // 权限管理:权限表(按菜单分类,每个菜单含集团全部/所在公司两种权限) + // menus / sync 需在 resources 之前注册,避免被 /:id 误匹配 + router.get('/api/permissions/menus', jwtAuth, controller.permission.menus); + router.post('/api/permissions/sync', jwtAuth, controller.permission.sync); + router.resources('permissions', '/api/permissions', jwtAuth, controller.permission); + // 角色组:选项需在 resources 之前注册;系统预设角色后端只读 + router.get('/api/roles/options', jwtAuth, controller.role.options); + router.resources('roles', '/api/roles', jwtAuth, controller.role); // 邀请开通主体账号:创建新用户(随机密码)并绑定到指定主体 router.post('/api/principal-users/invite', jwtAuth, principalCheck({ model: 'PrincipalUser' }), controller.principalUser.invite); // 商品快速搜索(聚合:商品编码/货品编码/条码/商品名称),需在 resources('products') 之前注册避免被 :id 误匹配 diff --git a/backend/app/utils/exportDefs.js b/backend/app/utils/exportDefs.js index 29788eb..7fb3cb2 100644 --- a/backend/app/utils/exportDefs.js +++ b/backend/app/utils/exportDefs.js @@ -481,6 +481,16 @@ const PRINCIPAL_USER_COLUMNS = [ }, { key: 'nickname', header: '用户昵称', expr: '(SELECT u.nickname FROM users u WHERE u.id = t.user_id)' }, { key: 'role', header: '角色', format: labels(ROLE_MAP) }, + { + key: 'role_group', + header: '角色组', + expr: '(SELECT r.name FROM roles r WHERE r.id = t.role_id)', + }, + { + key: 'companies', + header: '所属公司', + expr: "(SELECT GROUP_CONCAT(s.name SEPARATOR '、') FROM principal_user_companies puc JOIN principal_subsidiaries s ON s.id = puc.subsidiary_id WHERE puc.principal_user_id = t.id)", + }, { key: 'is_default', header: '默认主体', format: yesNo }, { key: 'status', header: '状态', format: labels(ENABLE_MAP) }, { key: 'created_at', header: '创建时间' }, @@ -877,13 +887,15 @@ const EXPORT_TYPES = { principal_user: { label: '账号', filters: [ - { key: 'role', label: '角色', type: 'select', options: ROLE_OPTIONS }, + { key: 'role_id', label: '角色组ID', type: 'number' }, + { key: 'role', label: '角色标识', type: 'select', options: ROLE_OPTIONS }, { key: 'status', label: '状态', type: 'select', options: ENABLE_OPTIONS }, { key: 'user_id', label: '用户ID', type: 'number' }, ], build: (f, ctx) => { const wh = makeWhere(); wh.eq('t.principal_id', ctx.principalId) + .eq('t.role_id', f.role_id) .eq('t.role', f.role) .eq('t.status', f.status) .eq('t.user_id', f.user_id); diff --git a/backend/database/migrations/20261104070000-create-principal-subsidiaries.js b/backend/database/migrations/20261104070000-create-principal-subsidiaries.js new file mode 100644 index 0000000..74a083f --- /dev/null +++ b/backend/database/migrations/20261104070000-create-principal-subsidiaries.js @@ -0,0 +1,57 @@ +'use strict'; + +/** + * 下属公司表:组织架构 → 下属公司。 + * + * 每条记录归属于一个主体(principal_id,即顶部下拉选中的集团主体), + * 仅用于维护集团下的公司档案,不参与业务数据(商品/订单)归属。 + */ +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.createTable( + 'principal_subsidiaries', + { + id: { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: false, + autoIncrement: true, + primaryKey: true, + }, + principal_id: { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: false, + comment: '所属主体(集团)ID', + references: { model: 'principals', key: 'id' }, + }, + name: { type: Sequelize.STRING(100), allowNull: false, comment: '公司名称' }, + credit_code: { type: Sequelize.STRING(50), allowNull: true, comment: '统一社会信用代码' }, + contact_name: { type: Sequelize.STRING(50), allowNull: true, comment: '联系人' }, + contact_phone: { type: Sequelize.STRING(20), allowNull: true, comment: '联系电话' }, + address: { type: Sequelize.STRING(255), allowNull: true, comment: '公司地址' }, + status: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' }, + remark: { type: Sequelize.STRING(255), allowNull: true, comment: '备注' }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + }, + }, + { charset: 'utf8mb4', collate: 'utf8mb4_unicode_ci', comment: '下属公司表' } + ); + + await queryInterface.addIndex('principal_subsidiaries', { + fields: [ 'principal_id', 'name' ], + unique: true, + name: 'uk_principal_subsidiaries_principal_name', + }); + }, + + async down(queryInterface) { + await queryInterface.dropTable('principal_subsidiaries'); + }, +}; diff --git a/backend/database/migrations/20261104070100-rename-principal-menu-to-organization.js b/backend/database/migrations/20261104070100-rename-principal-menu-to-organization.js new file mode 100644 index 0000000..394293f --- /dev/null +++ b/backend/database/migrations/20261104070100-rename-principal-menu-to-organization.js @@ -0,0 +1,31 @@ +'use strict'; + +/** + * 菜单调整:系统管理下的「主体管理」改为「组织架构」。 + * + * 页面改为左右 tab 结构(集团设置 / 下属公司),主体列表不再单独成页, + * 主体切换统一走顶部下拉,故 path 与 component 同步指向新页面; + * 权限标识沿用 principal:list,避免重复授权。 + */ +module.exports = { + async up(queryInterface) { + await queryInterface.sequelize.query( + `UPDATE menus SET name = ?, path = ?, component = ? + WHERE name = ? AND path = ? AND type = 2`, + { + replacements: [ '组织架构', '/system/organization', 'views/Organization/Index.vue', '主体管理', '/system/principal' ], + } + ); + }, + + async down(queryInterface) { + // 仅回滚菜单元数据:旧页面 views/Principal/Index.vue 已随本次改版删除,回滚需同时恢复代码 + await queryInterface.sequelize.query( + `UPDATE menus SET name = ?, path = ?, component = ? + WHERE name = ? AND path = ? AND type = 2`, + { + replacements: [ '主体管理', '/system/principal', 'views/Principal/Index.vue', '组织架构', '/system/organization' ], + } + ); + }, +}; diff --git a/backend/database/migrations/20261104070200-create-permission-tables.js b/backend/database/migrations/20261104070200-create-permission-tables.js new file mode 100644 index 0000000..a7e2a60 --- /dev/null +++ b/backend/database/migrations/20261104070200-create-permission-tables.js @@ -0,0 +1,146 @@ +'use strict'; + +/** + * 权限管理相关表: + * - permissions:权限表,按「菜单」作为分类,每个菜单下两种权限子类(1 集团全部 / 2 所在公司) + * - roles:角色组(角色表),is_system=1 为系统预设角色(不可删除) + * - role_permissions:角色与权限的关联 + * - principal_users.role_id:账号在当前主体下所属的角色组 + */ +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.createTable( + 'permissions', + { + id: { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: false, + autoIncrement: true, + primaryKey: true, + }, + menu_id: { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: false, + comment: '所属菜单(权限分类)ID', + references: { model: 'menus', key: 'id' }, + }, + name: { type: Sequelize.STRING(100), allowNull: false, comment: '权限名称' }, + code: { type: Sequelize.STRING(100), allowNull: false, comment: '权限标识(全局唯一)' }, + scope: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 1, comment: '权限范围:1集团全部 2所在公司' }, + status: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' }, + remark: { type: Sequelize.STRING(255), allowNull: true, comment: '备注' }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + }, + }, + { charset: 'utf8mb4', collate: 'utf8mb4_unicode_ci', comment: '权限表' } + ); + + await queryInterface.addIndex('permissions', { + fields: [ 'menu_id', 'scope' ], + unique: true, + name: 'uk_permissions_menu_scope', + }); + await queryInterface.addIndex('permissions', { + fields: [ 'code' ], + unique: true, + name: 'uk_permissions_code', + }); + + await queryInterface.createTable( + 'roles', + { + id: { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: false, + autoIncrement: true, + primaryKey: true, + }, + name: { type: Sequelize.STRING(50), allowNull: false, comment: '角色名称' }, + code: { type: Sequelize.STRING(50), allowNull: false, comment: '角色标识(全局唯一)' }, + is_system: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 0, comment: '是否系统预设:1是(不可删除) 0自定义' }, + status: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' }, + remark: { type: Sequelize.STRING(255), allowNull: true, comment: '备注' }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + }, + }, + { charset: 'utf8mb4', collate: 'utf8mb4_unicode_ci', comment: '角色组表' } + ); + + await queryInterface.addIndex('roles', { fields: [ 'name' ], unique: true, name: 'uk_roles_name' }); + await queryInterface.addIndex('roles', { fields: [ 'code' ], unique: true, name: 'uk_roles_code' }); + + await queryInterface.createTable( + 'role_permissions', + { + id: { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: false, + autoIncrement: true, + primaryKey: true, + }, + role_id: { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: false, + comment: '角色ID', + references: { model: 'roles', key: 'id' }, + }, + permission_id: { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: false, + comment: '权限ID', + references: { model: 'permissions', key: 'id' }, + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + }, + }, + { charset: 'utf8mb4', collate: 'utf8mb4_unicode_ci', comment: '角色权限关联表' } + ); + + await queryInterface.addIndex('role_permissions', { + fields: [ 'role_id', 'permission_id' ], + unique: true, + name: 'uk_role_permissions_role_permission', + }); + + await queryInterface.addColumn('principal_users', 'role_id', { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: true, + comment: '角色组ID(roles.id),为空表示未分配角色组', + references: { model: 'roles', key: 'id' }, + after: 'user_id', + }); + await queryInterface.addIndex('principal_users', { fields: [ 'role_id' ], name: 'idx_principal_users_role_id' }); + }, + + async down(queryInterface) { + await queryInterface.removeIndex('principal_users', 'idx_principal_users_role_id'); + await queryInterface.removeColumn('principal_users', 'role_id'); + await queryInterface.dropTable('role_permissions'); + await queryInterface.dropTable('roles'); + await queryInterface.dropTable('permissions'); + }, +}; diff --git a/backend/database/migrations/20261104070300-seed-permissions-and-roles.js b/backend/database/migrations/20261104070300-seed-permissions-and-roles.js new file mode 100644 index 0000000..d5955e4 --- /dev/null +++ b/backend/database/migrations/20261104070300-seed-permissions-and-roles.js @@ -0,0 +1,86 @@ +'use strict'; + +/** + * 权限 / 角色组初始数据: + * 1. 以现有菜单作为分类,为每个顶级菜单生成两种权限:集团全部(scope=1)、所在公司(scope=2) + * 2. 预置系统角色:系统管理员(全部「集团全部」权限)、货主权限(全部「所在公司」权限) + * 3. 按原有 principal_users.role 回填角色组:owner → 货主权限,admin → 系统管理员 + */ +module.exports = { + async up(queryInterface) { + const sequelize = queryInterface.sequelize; + const [ menus ] = await sequelize.query( + 'SELECT id, name FROM menus WHERE parent_id = 0 ORDER BY sort DESC, id ASC' + ); + + for (const menu of menus) { + const rows = [ + { scope: 1, suffix: 'group', label: '集团全部' }, + { scope: 2, suffix: 'company', label: '所在公司' }, + ]; + for (const row of rows) { + await sequelize.query( + `INSERT INTO permissions (menu_id, name, code, scope, status, remark, created_at, updated_at) + VALUES (?, ?, ?, ?, 1, ?, NOW(), NOW())`, + { + replacements: [ + menu.id, + `${menu.name}(${row.label})`, + `menu_${menu.id}_${row.suffix}`, + row.scope, + `菜单「${menu.name}」的${row.label}权限`, + ], + } + ); + } + } + + const roles = [ + { name: '系统管理员', code: 'super_admin', remark: '系统预设:拥有全部菜单的集团权限' }, + { name: '货主权限', code: 'owner', remark: '系统预设:拥有全部菜单的所在公司权限' }, + ]; + for (const role of roles) { + await sequelize.query( + `INSERT INTO roles (name, code, is_system, status, remark, created_at, updated_at) + VALUES (?, ?, 1, 1, ?, NOW(), NOW())`, + { replacements: [ role.name, role.code, role.remark ] } + ); + } + + const [ roleRows ] = await sequelize.query('SELECT id, code FROM roles WHERE is_system = 1'); + const roleIdByCode = new Map(roleRows.map(row => [ row.code, Number(row.id) ])); + const scopeByRoleCode = { super_admin: 1, owner: 2 }; + + for (const [ code, scope ] of Object.entries(scopeByRoleCode)) { + const roleId = roleIdByCode.get(code); + if (!roleId) continue; + await sequelize.query( + `INSERT INTO role_permissions (role_id, permission_id, created_at, updated_at) + SELECT ?, p.id, NOW(), NOW() FROM permissions p WHERE p.scope = ?`, + { replacements: [ roleId, scope ] } + ); + } + + // 旧角色字段回填:owner → 货主权限,admin → 系统管理员(member 保持未分配) + if (roleIdByCode.get('owner')) { + await sequelize.query( + 'UPDATE principal_users SET role_id = ? WHERE role_id IS NULL AND role = ?', + { replacements: [ roleIdByCode.get('owner'), 'owner' ] } + ); + } + if (roleIdByCode.get('super_admin')) { + await sequelize.query( + 'UPDATE principal_users SET role_id = ? WHERE role_id IS NULL AND role = ?', + { replacements: [ roleIdByCode.get('super_admin'), 'admin' ] } + ); + } + }, + + async down(queryInterface) { + const sequelize = queryInterface.sequelize; + await sequelize.query('UPDATE principal_users SET role_id = NULL'); + await sequelize.query('DELETE FROM role_permissions'); + await sequelize.query('DELETE FROM roles'); + await sequelize.query('DELETE FROM permissions'); + }, +}; diff --git a/backend/database/migrations/20261104070400-seed-permission-menu.js b/backend/database/migrations/20261104070400-seed-permission-menu.js new file mode 100644 index 0000000..aa5bffc --- /dev/null +++ b/backend/database/migrations/20261104070400-seed-permission-menu.js @@ -0,0 +1,60 @@ +'use strict'; + +/** + * 新增「权限管理」菜单:挂在「系统管理」目录下(组织架构与账号之间)。 + * 按 name + parent_id 判重,可重复执行。 + */ +const PARENT_NAME = '系统管理'; +const MENU = { + name: '权限管理', + type: 2, + path: '/system/permission', + icon: 'Lock', + permission: 'permission:list', + component: 'views/Permission/Index.vue', + sort: 75, +}; + +module.exports = { + async up(queryInterface) { + const sequelize = queryInterface.sequelize; + + const parent = await sequelize.query( + 'SELECT id FROM menus WHERE name = ? AND parent_id = 0 LIMIT 1', + { replacements: [ PARENT_NAME ], type: sequelize.QueryTypes.SELECT } + ); + const parentRow = parent[0]; + if (!parentRow) return; + const parentId = Number(parentRow.id); + + const exist = await sequelize.query( + 'SELECT id FROM menus WHERE name = ? AND parent_id = ? LIMIT 1', + { replacements: [ MENU.name, parentId ], type: sequelize.QueryTypes.SELECT } + ); + if (exist[0]) return; + + await sequelize.query( + `INSERT INTO menus + (parent_id, name, type, path, icon, permission, component, sort, status, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, NOW(), NOW())`, + { + replacements: [ + parentId, + MENU.name, + MENU.type, + MENU.path, + MENU.icon, + MENU.permission, + MENU.component, + MENU.sort, + ], + } + ); + }, + + async down(queryInterface) { + await queryInterface.sequelize.query('DELETE FROM menus WHERE name = ? AND path = ?', { + replacements: [ MENU.name, MENU.path ], + }); + }, +}; diff --git a/backend/database/migrations/20261104070500-create-principal-user-companies.js b/backend/database/migrations/20261104070500-create-principal-user-companies.js new file mode 100644 index 0000000..45af556 --- /dev/null +++ b/backend/database/migrations/20261104070500-create-principal-user-companies.js @@ -0,0 +1,69 @@ +'use strict'; + +/** + * 员工所属公司关联表:员工档案(principal_users)可关联多个下属公司。 + * + * - principal_user_id:员工(账号在当前主体下的关联记录) + * - subsidiary_id:下属公司(principal_subsidiaries.id) + * - principal_id:冗余主体ID,便于按当前主体隔离查询 + * + * 所有者(principal_users.role = owner)不参与公司关联;其余员工创建时必须至少关联一家公司。 + */ +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.createTable( + 'principal_user_companies', + { + id: { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: false, + autoIncrement: true, + primaryKey: true, + }, + principal_id: { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: false, + comment: '所属主体(集团)ID', + references: { model: 'principals', key: 'id' }, + }, + principal_user_id: { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: false, + comment: '员工(主体账号关联记录)ID', + references: { model: 'principal_users', key: 'id' }, + }, + subsidiary_id: { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: false, + comment: '下属公司ID', + references: { model: 'principal_subsidiaries', key: 'id' }, + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + }, + }, + { charset: 'utf8mb4', collate: 'utf8mb4_unicode_ci', comment: '员工所属公司关联表' } + ); + + await queryInterface.addIndex('principal_user_companies', { + fields: [ 'principal_user_id', 'subsidiary_id' ], + unique: true, + name: 'uk_principal_user_companies_user_subsidiary', + }); + await queryInterface.addIndex('principal_user_companies', { + fields: [ 'principal_id', 'subsidiary_id' ], + name: 'idx_principal_user_companies_principal_subsidiary', + }); + }, + + async down(queryInterface) { + await queryInterface.dropTable('principal_user_companies'); + }, +}; diff --git a/backend/database/migrations/20261104070600-rename-account-menu-to-employee.js b/backend/database/migrations/20261104070600-rename-account-menu-to-employee.js new file mode 100644 index 0000000..8c8db60 --- /dev/null +++ b/backend/database/migrations/20261104070600-rename-account-menu-to-employee.js @@ -0,0 +1,23 @@ +'use strict'; + +/** + * 菜单改名:「账号」改为「员工档案」。 + * + * 页面升级为员工档案管理(角色组必选、非所有者需关联下属公司), + * path 同步改为 /system/employee,component 仍指向 views/PrincipalUser/Index.vue。 + */ +module.exports = { + async up(queryInterface) { + await queryInterface.sequelize.query( + 'UPDATE menus SET name = ?, path = ? WHERE name = ? AND path = ? AND type = 2', + { replacements: [ '员工档案', '/system/employee', '账号', '/system/principal-user' ] } + ); + }, + + async down(queryInterface) { + await queryInterface.sequelize.query( + 'UPDATE menus SET name = ?, path = ? WHERE name = ? AND path = ? AND type = 2', + { replacements: [ '账号', '/system/principal-user', '员工档案', '/system/employee' ] } + ); + }, +}; diff --git a/frontend/src/api/permission.ts b/frontend/src/api/permission.ts new file mode 100644 index 0000000..ca5b72f --- /dev/null +++ b/frontend/src/api/permission.ts @@ -0,0 +1,76 @@ +import { get, post, put, del } from '@/utils/request' + +/** 权限范围:1集团全部 2所在公司 */ +export type PermissionScope = 1 | 2 + +export const PERMISSION_SCOPE_LABELS: Record = { + 1: '集团全部', + 2: '所在公司', +} + +/** 权限(以菜单为分类,每个菜单含集团全部 / 所在公司两种权限) */ +export interface PermissionItem { + id: number + /** 所属菜单(权限分类)ID */ + menu_id: number + name: string + code: string + scope: PermissionScope + status: number + remark: string | null + /** 所属菜单(列表接口附带) */ + menu?: { id: number; name: string; icon: string | null; path: string | null } | null + created_at?: string + updated_at?: string +} + +/** 可作为权限分类的菜单 */ +export interface PermissionMenuOption { + id: number + name: string + icon: string | null + path: string | null + sort: number +} + +export interface PermissionPayload { + menu_id: number + scope: PermissionScope + name?: string + code?: string + status?: number + remark?: string | null +} + +/** 权限列表 */ +export function getPermissions(params?: object) { + return get<{ list: PermissionItem[]; total: number; page: number; pageSize: number }>( + '/permissions', + params, + ) +} + +/** 权限分类(顶级菜单)下拉 */ +export function getPermissionMenus() { + return get('/permissions/menus') +} + +export function createPermission(data: PermissionPayload) { + return post<{ id: number }>('/permissions', data) +} + +export function updatePermission( + id: number, + data: { menu_id?: number; name?: string; status?: number; remark?: string | null }, +) { + return put<{ id: number }>(`/permissions/${id}`, data) +} + +export function deletePermission(id: number) { + return del<{ id: number }>(`/permissions/${id}`) +} + +/** 为新菜单补齐两种权限(已存在的跳过) */ +export function syncPermissions() { + return post<{ created: number }>('/permissions/sync') +} diff --git a/frontend/src/api/principal.ts b/frontend/src/api/principal.ts index 91db9bc..61758ab 100644 --- a/frontend/src/api/principal.ts +++ b/frontend/src/api/principal.ts @@ -1,4 +1,4 @@ -import { post, get } from '@/utils/request' +import { post, get, put } from '@/utils/request' export interface PrincipalPayload { name: string @@ -24,6 +24,16 @@ export function createPrincipal(data: PrincipalPayload) { return post<{ id: number }>('/principals', data) } +/** 主体详情(组织架构 → 集团设置读取当前主体) */ +export function getPrincipal(id: number) { + return get(`/principals/${id}`) +} + +/** 更新主体(组织架构 → 集团设置保存当前主体) */ +export function updatePrincipal(id: number, data: Partial & { status?: number }) { + return put<{ id: number }>(`/principals/${id}`, data) +} + /** 主体列表 */ export function getPrincipals(params?: object) { return get<{ list: PrincipalItem[]; total: number; page: number; pageSize: number }>( diff --git a/frontend/src/api/principalSubsidiary.ts b/frontend/src/api/principalSubsidiary.ts new file mode 100644 index 0000000..b63ce48 --- /dev/null +++ b/frontend/src/api/principalSubsidiary.ts @@ -0,0 +1,58 @@ +import { get, post, put, del } from '@/utils/request' + +/** 下属公司(组织架构 → 下属公司,按当前主体隔离) */ +export interface PrincipalSubsidiaryItem { + id: number + principal_id: number + /** 公司名称(同一主体下唯一) */ + name: string + /** 统一社会信用代码 */ + credit_code: string | null + contact_name: string | null + contact_phone: string | null + address: string | null + status: number + remark: string | null + created_at?: string + updated_at?: string +} + +export interface PrincipalSubsidiaryPayload { + name: string + credit_code?: string | null + contact_name?: string | null + contact_phone?: string | null + address?: string | null + status?: number + remark?: string | null +} + +/** 下属公司下拉(仅启用,供员工档案选择所属公司) */ +export interface PrincipalSubsidiaryOption { + id: number + name: string +} + +export function getPrincipalSubsidiaryOptions() { + return get('/principal-subsidiaries/select') +} + +/** 当前主体下的下属公司列表(principal_id 由请求拦截器自动注入) */ +export function getPrincipalSubsidiaries(params?: object) { + return get<{ list: PrincipalSubsidiaryItem[]; total: number; page: number; pageSize: number }>( + '/principal-subsidiaries', + params, + ) +} + +export function createPrincipalSubsidiary(data: PrincipalSubsidiaryPayload) { + return post<{ id: number }>('/principal-subsidiaries', data) +} + +export function updatePrincipalSubsidiary(id: number, data: Partial) { + return put<{ id: number }>(`/principal-subsidiaries/${id}`, data) +} + +export function deletePrincipalSubsidiary(id: number) { + return del<{ id: number }>(`/principal-subsidiaries/${id}`) +} diff --git a/frontend/src/api/principalUser.ts b/frontend/src/api/principalUser.ts index bb66e67..5f67bd7 100644 --- a/frontend/src/api/principalUser.ts +++ b/frontend/src/api/principalUser.ts @@ -9,6 +9,14 @@ export interface PrincipalUserItem { /** 该账号在此主体下的头像 URL */ avatar: string | null role: string | null + /** 角色组ID(权限管理 → 角色组) */ + role_id: number | null + /** 角色组信息(列表接口附带) */ + roleGroup?: { id: number; name: string; code: string; is_system: number } | null + /** 所属公司(下属公司)ID列表 */ + company_ids?: number[] + /** 所属公司明细(列表接口附带) */ + companies?: { id: number; subsidiary_id: number; name: string }[] is_default: number status: number created_at?: string @@ -37,15 +45,28 @@ export function getPrincipalUsers(params?: object) { ) } -/** 邀请开通主体账号:创建新用户(随机初始密码)并绑定到当前主体 */ -export function invitePrincipalUser(data: { email: string; name: string; avatar?: string | null }) { +/** 新增员工:创建用户(随机初始密码)并绑定到当前主体,角色组与所属公司必填 */ +export function invitePrincipalUser(data: { + email: string + name: string + avatar?: string | null + role_id: number + company_ids: number[] +}) { return post('/principal-users/invite', data) } -/** 更新关联(名称 / 头像 / 角色 / 状态) */ +/** 更新关联(名称 / 头像 / 角色组 / 所属公司 / 状态) */ export function updatePrincipalUser( id: number, - data: { name?: string; avatar?: string | null; role?: string; status?: number }, + data: { + name?: string + avatar?: string | null + role?: string + role_id?: number | null + company_ids?: number[] + status?: number + }, ) { return put<{ id: number }>(`/principal-users/${id}`, data) } diff --git a/frontend/src/api/role.ts b/frontend/src/api/role.ts new file mode 100644 index 0000000..1807357 --- /dev/null +++ b/frontend/src/api/role.ts @@ -0,0 +1,60 @@ +import { get, post, put, del } from '@/utils/request' +import type { PermissionItem } from '@/api/permission' + +/** 角色组(权限集合),系统预设角色只读 */ +export interface RoleItem { + id: number + name: string + code: string + /** 1系统预设(不可修改/删除) 0自定义 */ + is_system: number + status: number + remark: string | null + permission_ids?: number[] + permission_count?: number + permissions?: PermissionItem[] + created_at?: string + updated_at?: string +} + +/** 角色组下拉项 */ +export interface RoleOption { + id: number + name: string + code: string + is_system: number +} + +export interface RolePayload { + name: string + code?: string + status?: number + remark?: string | null + permission_ids?: number[] +} + +/** 角色组列表 */ +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 getRole(id: number) { + return get(`/roles/${id}`) +} + +export function createRole(data: RolePayload) { + return post<{ id: number }>('/roles', data) +} + +export function updateRole(id: number, data: Partial) { + return put<{ id: number }>(`/roles/${id}`, data) +} + +export function deleteRole(id: number) { + return del<{ id: number }>(`/roles/${id}`) +} diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts index f077fbb..7af3e25 100644 --- a/frontend/src/router/index.ts +++ b/frontend/src/router/index.ts @@ -29,6 +29,10 @@ const router = createRouter({ // 老发货单入口已并入「订单」页(数据已迁入新表,能力均已在新表实现) { path: 'order-create', redirect: { path: '/order' } }, { path: 'order-delivery', redirect: { path: '/order' } }, + // 「主体管理」已改为「组织架构」:旧地址重定向到新页面 + { path: 'system/principal', redirect: { path: '/system/organization' } }, + // 「账号」已改为「员工档案」:旧地址重定向到新页面 + { path: 'system/principal-user', redirect: { path: '/system/employee' } }, ], }, ], diff --git a/frontend/src/store/menu.ts b/frontend/src/store/menu.ts index 71bb2a5..74da28a 100644 --- a/frontend/src/store/menu.ts +++ b/frontend/src/store/menu.ts @@ -59,8 +59,9 @@ const defaultMenus: MenuItem[] = [ id: 2, parent_id: 0, name: '系统管理', type: 1, icon: 'Setting', sort: 70, status: 1, children: [ { id: 21, parent_id: 2, name: '我的', type: 2, path: '/system/user', icon: 'User', permission: null, component: 'views/User/Profile.vue', sort: 90, status: 1 }, - { id: 22, parent_id: 2, name: '主体管理', type: 2, path: '/system/principal', icon: 'OfficeBuilding', permission: 'principal:list', component: 'views/Principal/Index.vue', sort: 80, status: 1 }, - { id: 23, parent_id: 2, name: '账号', type: 2, path: '/system/principal-user', icon: 'Connection', permission: 'principalUser:list', component: 'views/PrincipalUser/Index.vue', sort: 70, status: 1 }, + { id: 22, parent_id: 2, name: '组织架构', type: 2, path: '/system/organization', icon: 'OfficeBuilding', permission: 'principal:list', component: 'views/Organization/Index.vue', sort: 80, status: 1 }, + { id: 23, parent_id: 2, name: '员工档案', type: 2, path: '/system/employee', icon: 'Connection', permission: 'principalUser:list', component: 'views/PrincipalUser/Index.vue', sort: 70, status: 1 }, + { id: 26, parent_id: 2, name: '权限管理', type: 2, path: '/system/permission', icon: 'Lock', permission: 'permission:list', component: 'views/Permission/Index.vue', sort: 75, status: 1 }, { id: 24, parent_id: 2, name: '自定义快递编码', type: 2, path: '/system/custom-express', icon: 'Van', permission: null, component: 'views/CustomExpress/Index.vue', sort: 60, status: 1 }, ], }, diff --git a/frontend/src/views/Organization/GroupSettings.vue b/frontend/src/views/Organization/GroupSettings.vue new file mode 100644 index 0000000..d73341d --- /dev/null +++ b/frontend/src/views/Organization/GroupSettings.vue @@ -0,0 +1,164 @@ + + + + + diff --git a/frontend/src/views/Organization/Index.vue b/frontend/src/views/Organization/Index.vue new file mode 100644 index 0000000..1f7ca30 --- /dev/null +++ b/frontend/src/views/Organization/Index.vue @@ -0,0 +1,61 @@ + + + + + diff --git a/frontend/src/views/Organization/Subsidiaries.vue b/frontend/src/views/Organization/Subsidiaries.vue new file mode 100644 index 0000000..95aab8f --- /dev/null +++ b/frontend/src/views/Organization/Subsidiaries.vue @@ -0,0 +1,267 @@ + + + + + diff --git a/frontend/src/views/Permission/Index.vue b/frontend/src/views/Permission/Index.vue new file mode 100644 index 0000000..5649645 --- /dev/null +++ b/frontend/src/views/Permission/Index.vue @@ -0,0 +1,40 @@ + + + + + diff --git a/frontend/src/views/Permission/RoleGroups.vue b/frontend/src/views/Permission/RoleGroups.vue new file mode 100644 index 0000000..c22fd2d --- /dev/null +++ b/frontend/src/views/Permission/RoleGroups.vue @@ -0,0 +1,350 @@ + + + + + diff --git a/frontend/src/views/Principal/Index.vue b/frontend/src/views/Principal/Index.vue deleted file mode 100644 index ba96fc7..0000000 --- a/frontend/src/views/Principal/Index.vue +++ /dev/null @@ -1,194 +0,0 @@ - - - - - diff --git a/frontend/src/views/PrincipalUser/Index.vue b/frontend/src/views/PrincipalUser/Index.vue index e344e50..df289c5 100644 --- a/frontend/src/views/PrincipalUser/Index.vue +++ b/frontend/src/views/PrincipalUser/Index.vue @@ -15,18 +15,46 @@ import ListPager from '@/components/ListPager.vue' 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 { getPrincipalSubsidiaryOptions, type PrincipalSubsidiaryOption } from '@/api/principalSubsidiary' const query = reactive({ page: 1, pageSize: DEFAULT_PAGE_SIZE, - role: '', + role_id: '' as string | number, status: '' as string | number, }) -const ROLE_LABELS: Record = { owner: '所有者', admin: '管理员', member: '成员' } +/** 角色组下拉(权限管理 → 角色组维护) */ +const roles = ref([]) -function roleText(role: string | null | undefined) { - return (role && ROLE_LABELS[role]) || role || '-' +async function fetchRoles() { + try { + roles.value = await getRoleOptions() + } catch { + roles.value = [] + } +} + +/** 下属公司下拉(组织架构 → 下属公司,员工可关联多家) */ +const companies = ref([]) + +async function fetchCompanies() { + try { + companies.value = await getPrincipalSubsidiaryOptions() + } catch { + companies.value = [] + } +} + +function roleGroupText(row: PrincipalUserItem) { + return row.roleGroup?.name || '-' +} + +/** 所属公司展示文案:多家用顿号连接 */ +function companyText(row: PrincipalUserItem) { + const names = (row.companies || []).map(item => item.name).filter(Boolean) + return names.length ? names.join('、') : '-' } function userLabel(row: PrincipalUserItem) { @@ -45,29 +73,35 @@ const { loading, list, total, elapsed, fetchList, search, handlePageChange, hand query, fetcher: () => { const params: Record = { ...query } - if (params.role === '') delete params.role + if (params.role_id === '') delete params.role_id if (params.status === '') delete params.status return getPrincipalUsers(params) }, }) function reset() { - query.role = '' + query.role_id = '' query.status = '' search() } /** 导出筛选条件(与列表筛选同源) */ const exportFilters = computed(() => ({ - role: query.role, + role_id: query.role_id, status: query.status, })) -// 邀请用户 +// 新增员工 const inviteVisible = ref(false) const inviteSubmitting = ref(false) const inviteFormRef = ref() -const inviteForm = reactive({ email: '', name: '', avatar: null as string | null }) +const inviteForm = reactive({ + email: '', + name: '', + avatar: null as string | null, + role_id: '' as string | number, + company_ids: [] as number[], +}) /** 头像上传组件的 model 为 string[](单张) */ const inviteAvatarList = computed({ get: () => (inviteForm.avatar ? [ inviteForm.avatar ] : []), @@ -79,9 +113,11 @@ const inviteRules: FormRules = { { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }, ], name: [{ required: true, message: '请输入名称', trigger: 'blur' }], + role_id: [{ required: true, message: '请选择角色组', trigger: 'change' }], + company_ids: [{ required: true, type: 'array', min: 1, message: '请至少关联一家公司', trigger: 'change' }], } -/** 邀请成功后返回的账号信息(初始密码仅返回一次) */ +/** 新增成功后返回的账号信息(初始密码仅返回一次) */ const inviteResult = ref<{ username: string; password: string } | null>(null) const inviteResultVisible = ref(false) @@ -117,6 +153,9 @@ function openInvite() { inviteForm.email = '' inviteForm.name = '' inviteForm.avatar = null + // 默认「货主权限」(所在公司),与权限管理的系统预设角色保持一致 + inviteForm.role_id = roles.value.find(r => r.code === 'owner')?.id || '' + inviteForm.company_ids = [] inviteVisible.value = true } @@ -126,9 +165,15 @@ async function submitInvite() { if (!valid) return inviteSubmitting.value = true try { - const res = await invitePrincipalUser({ ...inviteForm }) + const res = await invitePrincipalUser({ + email: inviteForm.email, + name: inviteForm.name, + avatar: inviteForm.avatar, + role_id: Number(inviteForm.role_id), + company_ids: inviteForm.company_ids, + }) inviteVisible.value = false - ElMessage.success('邀请成功') + ElMessage.success('员工创建成功') // 账号与初始密码仅返回一次,展示在结果弹窗中并支持一键复制 inviteResult.value = { username: res.username, password: res.password } inviteResultVisible.value = true @@ -141,26 +186,46 @@ async function submitInvite() { }) } -// 编辑角色 / 状态 +// 编辑员工(名称 / 头像 / 角色组 / 所属公司 / 状态) const editVisible = ref(false) const editSubmitting = ref(false) const editFormRef = ref() const editId = ref(null) -const editForm = reactive({ name: '', avatar: null as string | null, role: 'member', status: 1 }) +const editForm = reactive({ + name: '', + avatar: null as string | null, + role_id: '' as string | number, + company_ids: [] as number[], + status: 1, +}) const editAvatarList = computed({ get: () => (editForm.avatar ? [ editForm.avatar ] : []), set: (value: string[]) => { editForm.avatar = value[0] || null }, }) +/** 当前编辑对象是否为主体所有者:所有者不参与公司关联 */ +const editIsOwner = ref(false) const editRules: FormRules = { name: [{ required: true, message: '请输入名称', trigger: 'blur' }], - role: [{ required: true, message: '请选择角色', trigger: 'change' }], + role_id: [{ required: true, message: '请选择角色组', trigger: 'change' }], + company_ids: [ + { + validator: (_rule, value: number[], callback) => { + if (editIsOwner.value) return callback() + if (!Array.isArray(value) || !value.length) return callback(new Error('请至少关联一家公司')) + callback() + }, + trigger: 'change', + }, + ], } function openEdit(row: PrincipalUserItem) { editId.value = row.id + editIsOwner.value = row.role === 'owner' editForm.name = row.name || row.user?.nickname || row.user?.username || '' editForm.avatar = row.avatar || null - editForm.role = row.role || 'member' + editForm.role_id = row.role_id ?? '' + editForm.company_ids = (row.companies || []).map(item => Number(item.subsidiary_id)) editForm.status = row.status editVisible.value = true } @@ -174,7 +239,8 @@ async function submitEdit() { await updatePrincipalUser(editId.value as number, { name: editForm.name, avatar: editForm.avatar, - role: editForm.role, + role_id: Number(editForm.role_id), + company_ids: editForm.company_ids, status: editForm.status, }) ElMessage.success('保存成功') @@ -207,27 +273,28 @@ async function handleUnbind(row: PrincipalUserItem) { } } -onMounted(fetchList) +onMounted(async () => { + await Promise.all([ fetchRoles(), fetchCompanies() ]) + await fetchList() +}) - - + + + + + @@ -287,13 +357,29 @@ onMounted(fetchList) @size-change="handleSizeChange" /> - + - + - - + + + + + + + + + + + + @@ -301,25 +387,35 @@ onMounted(fetchList) - + - - + + - - - - - + + + + + + + +
主体所有者无需关联公司
+
@@ -414,4 +510,9 @@ onMounted(fetchList) flex-shrink: 0; color: #606266; } +.form-hint { + font-size: 12px; + color: var(--el-text-color-secondary); + line-height: 1.6; +}