'use strict'; const { Controller } = require('egg'); const { parsePagination, buildPageResult } = require('../lib/pagination'); /** * @controller PrincipalController 主体管理 */ class PrincipalController extends Controller { /** * @summary 主体列表 * @description 分页查询主体,支持名称/编码模糊搜索、类型与状态过滤 * @router get /api/principals * @apikey * @request query integer page 页码,默认 1 * @request query integer pageSize 每页条数,默认 20 * @request query string keyword 关键词,匹配主体名称 * @request query integer type 主体类型:1自营 2加盟 3外部,不传则不过滤 * @request query integer status 状态:1启用 0禁用,不传则不过滤 * @response 200 principalListResponse success */ async index() { const { ctx } = this; const Op = this.app.Sequelize.Op; const { page, pageSize, offset, limit } = parsePagination(ctx.query); const { keyword, type, status } = ctx.query; const where = {}; if (keyword) { where.name = { [Op.like]: `%${keyword}%` }; } if (type !== undefined && type !== '') where.type = Number(type); if (status !== undefined && status !== '') where.status = Number(status); // 按当前登录账号所属主体隔离(多租户):仅返回通过该账号 principal_users 关联的主体 // 主体ID列表由 JWT 中间件从缓存加载,列表本身不做缓存(分页/筛选要求实时) const principalIds = ctx.state.principalIds || await ctx.service.cache.getUserPrincipalIds(ctx.userId); where.id = { [Op.in]: principalIds }; const { count, rows } = await ctx.model.Principal.findAndCountAll({ where, offset, limit, order: [[ 'id', 'DESC' ]], }); ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) }; } /** * @summary 我的可选主体(头部主体切换下拉) * @description 返回当前登录账号已绑定的主体列表,用于页面头部切换/选择主体; * 该接口走 Redis 缓存(主体新增、更新、删除或绑定关系变更时自动失效),管理端列表接口 /api/principals 不缓存 * @router get /api/principals/options * @apikey * @response 200 principalOptionsResponse success */ async options() { const { ctx } = this; const list = await ctx.service.cache.getUserPrincipalOptions(ctx.userId); ctx.body = { code: 0, message: 'success', data: { list } }; } /** * @summary 主体详情 * @description 按主键查询主体(走缓存,主体更新/删除时自动失效) * @router get /api/principals/{id} * @apikey * @request path integer *id 主体主键ID * @response 200 baseResponse success */ async show() { const { ctx } = this; const principal = await ctx.service.cache.getPrincipal(ctx.params.id); if (!principal) { ctx.status = 404; ctx.body = { code: 404, message: '主体不存在' }; return; } ctx.body = { code: 0, message: 'success', data: principal }; } /** * @summary 新增主体 * @description 主体名称 name 必填;创建者自动关联为该主体 owner(多租户隔离) * @router post /api/principals * @apikey * @request body createPrincipalRequest *body * @response 200 baseResponse success */ async create() { const { ctx } = this; const { name } = ctx.request.body; if (!name) { ctx.status = 400; ctx.body = { code: 400, message: 'name 为必填项' }; return; } const principal = await ctx.model.Principal.create(ctx.request.body); // 将创建者关联为该主体的默认用户(owner),建立多租户归属关系 if (ctx.userId) { await ctx.model.PrincipalUser.create({ principal_id: principal.id, user_id: ctx.userId, role: 'owner', is_default: 1, status: 1, }); } // 新增主体后,创建者立即可见:失效其主体ID列表与可选主体缓存 await ctx.service.cache.invalidateUserPrincipals(ctx.userId); ctx.body = { code: 0, message: 'success', data: { id: principal.id } }; } /** * @summary 更新主体 * @description 未传入的字段保持原值 * @router put /api/principals/{id} * @apikey * @request path integer *id 主体主键ID * @request body updatePrincipalRequest *body * @response 200 baseResponse success */ async update() { const { ctx } = this; const principal = await ctx.model.Principal.findByPk(ctx.params.id); if (!principal) { ctx.status = 404; ctx.body = { code: 404, message: '主体不存在' }; return; } await principal.update(ctx.request.body); // 主体信息变更:失效主体详情缓存及所有依赖主体信息的缓存(可选主体列表等) await ctx.service.cache.invalidatePrincipal(principal.id); ctx.body = { code: 0, message: 'success', data: { id: principal.id } }; } /** * @summary 删除主体 * @description 物理删除主体;存在关联商品/订单时拒绝删除并提示先清理;删除前自动解除主体与用户的绑定关系 * @router delete /api/principals/{id} * @apikey * @request path integer *id 主体主键ID * @response 200 baseResponse success */ async destroy() { const { ctx } = this; const principal = await ctx.model.Principal.findByPk(ctx.params.id); if (!principal) { ctx.status = 404; ctx.body = { code: 404, message: '主体不存在' }; return; } // 业务数据受外键约束,先提示清理,避免直接删除报数据库错误 const [ productCount, orderCount ] = await Promise.all([ ctx.model.Product.count({ where: { principal_id: principal.id } }), ctx.model.Order.count({ where: { principal_id: principal.id } }), ]); if (productCount || orderCount) { ctx.status = 400; ctx.body = { code: 400, message: `该主体下仍有 ${productCount} 个商品、${orderCount} 个订单,请先清理后再删除` }; return; } // 主体与用户的绑定关系含外键,需先解除,否则删除会因约束失败 await ctx.model.PrincipalUser.destroy({ where: { principal_id: principal.id } }); await principal.destroy(); await ctx.service.cache.invalidatePrincipal(principal.id); ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } }; } } module.exports = PrincipalController;