oms/backend/app/controller/principal.js
liufumingren 137a3ed1f3 feat(principal): 主体启用/停用改为仅数据库维护,页面与接口不可操作
- PUT /api/principals/{id} 不再接受 status 变更(变更时返回 403「主体的启用/停用只能由平台运维在数据库中维护」)
- POST /api/principals 状态固定为启用,创建时传 status=0 直接 403;其它非白名单字段忽略
- 集团设置页面状态改为只读展示并提示由平台运维维护(去掉启用/禁用开关)
- 前端 updatePrincipal 类型移除 status,接口契约说明同步更新

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-06 00:21:52 +08:00

243 lines
8.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const { Controller } = require('egg');
const { parsePagination, buildPageResult } = require('../lib/pagination');
/** 允许更新的主体字段,避免请求体覆盖 id 等主键信息
* 注意:不含 status —— 主体的启用/停用只能由平台运维直接在数据库中维护,
* 页面与接口都不允许普通用户自行启用或停用集团(否则会把自己锁死或被绕过)。
*/
const WRITABLE_FIELDS = [ 'name', 'type', 'contact_name', 'contact_phone', 'remark' ];
/**
* @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 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) {
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;
}
// 状态不接受入参:主体启用/停用只能由平台运维在数据库中维护
if (ctx.request.body.status !== undefined && Number(ctx.request.body.status) !== 1) {
ctx.status = 403;
ctx.body = { code: 403, message: '主体的启用/停用只能由平台运维在数据库中维护' };
return;
}
const payload = { status: 1 };
WRITABLE_FIELDS.forEach(field => {
if (ctx.request.body[field] !== undefined) payload[field] = ctx.request.body[field];
});
const principal = await ctx.model.Principal.create(payload);
// 将创建者关联为该主体的默认用户(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 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) {
ctx.status = 404;
ctx.body = { code: 404, message: '主体不存在' };
return;
}
// 状态不通过接口维护:避免普通用户自行启用/停用集团(停用后自身也会被锁在外面)
if (ctx.request.body.status !== undefined && Number(ctx.request.body.status) !== Number(principal.status)) {
ctx.status = 403;
ctx.body = { code: 403, message: '主体的启用/停用只能由平台运维在数据库中维护' };
return;
}
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);
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) } };
}
/**
* 校验当前账号是否绑定该主体(组织架构 → 集团设置只允许操作/查看自己所属主体)
* @param {number|string} principalId 主体ID
* @return {Promise<boolean>} 是否已绑定
*/
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;