oms/backend/app/controller/principalUser.js
liufumingren 489563a4b2 feat(backend): 仪表盘报表接口、配置裁剪、单号 5 位与账号名称/头像
- 仪表盘报表:新增 app/service/dashboard.js + app/controller/dashboard.js +
  app/lib/billStatus.js,注册 GET /api/dashboard/report(jwtAuth + principalCheck),
  一次聚合返回概览指标、发货单/入库单/出库单状态分布与待办、近 N 天单据量与
  出入库数量趋势、库存 Top 商品、最近出入库流水;warehouse_id 只过滤单据与流水
  (product_stocks 无仓库维度);契约 dashboard* 同步到 swagger
- 接口配置裁剪:仓库接口配置只保留 api_version 与 item_name_with_spec;
  历史 warehouse_apis.extra 冗余键、owner_code 配置、递交/回传设置一并清理
  (迁移 20260915002400~02800)
- 入库/出库/发货单报文与字段对齐 WMS 标准:去掉 ownerCode、operatorCode 等多余字段,
  入库明细补 itemId;发货单明细去掉无意义的 owner_code(迁移 20260915002600)
- 单号 5 位起:四张单据表 AUTO_INCREMENT 提到 10000(迁移 20260915002900)
- 账号名称/头像按主体维护:principal_users 增 name/avatar 并回填(迁移 20260915003000/03100),
  新增 app/lib/accountProfile.js(关联表名称/头像 → users 兜底);审核人写入 operator/operator_name;
  register 不再写 nickname、updateProfile 仅接受邮箱/手机号
- 出库单推送/锁库存链路的配套调整(outboundOrderPush、订单与发货单控制器)

Co-Authored-By: GitHub Copilot <noreply@github.com>
2026-09-14 16:09:35 +08:00

294 lines
9.6 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 crypto = require('crypto');
const { generateSalt, hashPassword } = require('../lib/password');
const { parsePagination, buildPageResult } = require('../lib/pagination');
/**
* @controller PrincipalUserController 主体用户关联管理
*/
class PrincipalUserController extends Controller {
/**
* @summary 关联列表
* @description 分页查询主体与用户的关联关系,可按主体或用户过滤
* @router get /api/principal-users
* @apikey
* @request query integer page 页码,默认 1
* @request query integer pageSize 每页条数,默认 20
* @request query integer principal_id 主体ID(必填,需当前账号已绑定该主体)
* @request query integer user_id 用户ID,不传则不过滤
* @request query string role 角色标识,精确匹配
* @request query integer 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 principalId = ctx.state.principalId;
const where = {};
where.principal_id = principalId;
if (userId) where.user_id = Number(userId);
if (role) where.role = role;
if (status !== undefined && status !== '') where.status = Number(status);
const { count, rows } = await ctx.model.PrincipalUser.findAndCountAll({
where,
offset,
limit,
order: [[ 'id', 'DESC' ]],
include: [
{ model: ctx.model.User, as: 'user', attributes: { exclude: [ 'password', 'salt' ] } },
],
});
ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) };
}
/**
* @summary 关联详情
* @description 按主键查询关联记录,并带出用户与主体信息
* @router get /api/principal-users/{id}
* @apikey
* @request path integer *id 关联记录主键ID
* @response 200 baseResponse success
*/
async show() {
const { ctx } = this;
const relation = await ctx.model.PrincipalUser.findByPk(ctx.params.id, {
include: [
{ model: ctx.model.User, as: 'user', attributes: { exclude: [ 'password', 'salt' ] } },
{ model: ctx.model.Principal, as: 'principal' },
],
});
if (!relation) {
ctx.status = 404;
ctx.body = { code: 404, message: '关联记录不存在' };
return;
}
ctx.body = { code: 0, message: 'success', data: relation };
}
/**
* @summary 绑定用户到主体
* @description 建立主体与用户的关联;同一主体下同一用户仅允许一条记录
* @router post /api/principal-users
* @apikey
* @request body bindPrincipalUserRequest *body
* @response 200 baseResponse success
*/
async create() {
const { ctx } = this;
const { principal_id: principalId, user_id: userId } = ctx.request.body;
if (!principalId || !userId) {
ctx.status = 400;
ctx.body = { code: 400, message: 'principal_id 与 user_id 为必填项' };
return;
}
const exist = await ctx.model.PrincipalUser.findOne({
where: { principal_id: principalId, user_id: userId },
});
if (exist) {
ctx.status = 400;
ctx.body = { code: 400, message: '该用户已绑定到该主体' };
return;
}
const relation = await ctx.model.PrincipalUser.create(ctx.request.body);
// 绑定关系变化:失效该用户缓存的主体ID列表与可选主体列表
await ctx.service.cache.invalidateUserPrincipals(userId);
ctx.body = { code: 0, message: 'success', data: { id: relation.id } };
}
/**
* @summary 邀请开通主体账号
* @description 传入邮箱、用户名称(写入主体账号关联表 principal_users.name)与主体ID,
* 自动创建新用户(随机初始密码)并绑定到该主体(角色 member);
* 返回明文随机密码,需由调用方妥善交付给被邀请人;同一邮箱不可重复开通
* @router post /api/principal-users/invite
* @apikey
* @request body invitePrincipalUserRequest *body
* @response 200 invitePrincipalUserResponse success
*/
async invite() {
const { ctx } = this;
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const { email, name, avatar, principal_id: principalId } = ctx.request.body;
if (!email || !EMAIL_REGEX.test(email)) {
ctx.status = 400;
ctx.body = { code: 400, message: '请填写正确的邮箱地址' };
return;
}
if (!name) {
ctx.status = 400;
ctx.body = { code: 400, message: '用户名称 name 为必填项' };
return;
}
if (!principalId) {
ctx.status = 400;
ctx.body = { code: 400, message: '主体ID principal_id 为必填项' };
return;
}
// 主体必须存在,给出明确提示
const principal = await ctx.model.Principal.findByPk(principalId);
if (!principal) {
ctx.status = 404;
ctx.body = { code: 404, message: '主体不存在' };
return;
}
// 邮箱全局唯一
const emailExist = await ctx.model.User.findOne({ where: { email } });
if (emailExist) {
ctx.status = 400;
ctx.body = { code: 400, message: '该邮箱已注册' };
return;
}
// 生成随机初始密码(明文仅此处返回一次)
const password = this.generateRandomPassword(12);
const salt = generateSalt();
const hashed = hashPassword(password, salt);
const transaction = await ctx.model.transaction();
try {
const user = await ctx.model.User.create({
username: email,
email,
salt,
password: hashed,
status: 1,
}, { transaction });
const relation = await ctx.model.PrincipalUser.create({
principal_id: principalId,
user_id: user.id,
// 账号显示名称/头像按主体维护(推送单据操作人取 name)
name: String(name).trim(),
avatar: avatar ? String(avatar).trim() : null,
role: 'member',
is_default: 0,
status: 1,
}, { transaction });
await transaction.commit();
await ctx.service.cache.invalidateUserPrincipals(user.id);
ctx.body = {
code: 0,
message: 'success',
data: {
user_id: user.id,
relation_id: relation.id,
email: user.email,
username: user.username,
nickname: relation.name,
password,
},
};
} catch (err) {
await transaction.rollback();
ctx.status = 500;
ctx.body = { code: 500, message: '开通账号失败,请稍后重试' };
}
}
/**
* 生成随机密码:12 位,含大小写字母与数字(去除易混淆字符 0/O/1/l/I)
* @param {Number} len 长度,默认 12
* @return {String} 随机密码
*/
generateRandomPassword(len = 12) {
const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789';
const bytes = crypto.randomBytes(len);
let pwd = '';
for (let i = 0; i < len; i++) pwd += chars[bytes[i] % chars.length];
return pwd;
}
/**
* @summary 更新关联信息
* @description 可修改该账号在此主体下的名称(name)、头像(avatar)、角色、默认主体标识与状态;
* 名称/头像即账号显示资料,推送单据的操作人取名称;不允许改归属(principal_id / user_id),非白名单字段一律忽略
* @router put /api/principal-users/{id}
* @apikey
* @request path integer *id 关联记录主键ID
* @request body bindPrincipalUserRequest *body
* @response 200 baseResponse success
*/
async update() {
const { ctx } = this;
const relation = await ctx.model.PrincipalUser.findByPk(ctx.params.id);
if (!relation) {
ctx.status = 404;
ctx.body = { code: 404, message: '关联记录不存在' };
return;
}
const body = ctx.request.body || {};
// 只接受名称/头像/角色/默认标识/状态,避免改归属或写入无关字段
const patch = {};
for (const key of [ 'name', 'avatar', 'role', 'is_default', 'status' ]) {
if (body[key] !== undefined) patch[key] = body[key];
}
if (patch.name !== undefined) {
const name = patch.name == null ? '' : String(patch.name).trim();
if (!name) {
ctx.status = 400;
ctx.body = { code: 400, message: '名称 name 不能为空' };
return;
}
patch.name = name;
}
if (patch.avatar !== undefined) {
patch.avatar = patch.avatar == null || String(patch.avatar).trim() === ''
? null
: String(patch.avatar).trim();
}
await relation.update(patch);
await ctx.service.cache.invalidateUserPrincipals(relation.user_id);
ctx.body = {
code: 0,
message: 'success',
data: { id: relation.id, name: relation.name, avatar: relation.avatar },
};
}
/**
* @summary 解绑用户与主体
* @description 物理删除关联记录
* @router delete /api/principal-users/{id}
* @apikey
* @request path integer *id 关联记录主键ID
* @response 200 baseResponse success
*/
async destroy() {
const { ctx } = this;
const relation = await ctx.model.PrincipalUser.findByPk(ctx.params.id);
if (!relation) {
ctx.status = 404;
ctx.body = { code: 404, message: '关联记录不存在' };
return;
}
const relationUserId = relation.user_id;
await relation.destroy();
await ctx.service.cache.invalidateUserPrincipals(relationUserId);
ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } };
}
}
module.exports = PrincipalUserController;