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

536 lines
16 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 { generateSalt, hashPassword } = require('../lib/password');
const { CODE_TTL, sendCode, verifyCode } = require('../lib/emailCode');
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
/**
* @controller AuthController 登录鉴权
*/
class AuthController extends Controller {
/**
* @summary 发送邮箱验证码
* @description 注册前置步骤:校验邮箱格式与唯一性后,发送 6 位验证码(10 分钟内有效);
* 受频率限制:同一邮箱 60 秒一次、每日上限 10 次,超限返回 429
* @router post /api/auth/email-code
* @request body sendEmailCodeRequest *body
* @response 200 baseResponse success
*/
async sendEmailCode() {
const { ctx, app } = this;
const { email } = ctx.request.body;
if (!email || !EMAIL_REGEX.test(email)) {
ctx.status = 400;
ctx.body = { code: 400, message: '请填写正确的邮箱地址' };
return;
}
const exist = await ctx.model.User.findOne({ where: { email } });
if (exist) {
ctx.status = 400;
ctx.body = { code: 400, message: '邮箱已被注册' };
return;
}
const result = await sendCode(app, email, { ip: ctx.ip, scene: 'register' });
if (!result.ok) {
ctx.status = 429;
ctx.body = { code: 429, message: result.message };
return;
}
ctx.body = {
code: 0,
message: 'success',
data: { email, expires_in: CODE_TTL },
};
}
/**
* @summary 账号密码登录(支持用户名或邮箱)
* @description 校验登录账号或邮箱(account 字段)与加盐密码,成功后签发 JWT;token 载荷仅包含 user_id,不含敏感信息
* @router post /api/auth/login
* @request body loginRequest *body
* @response 200 loginResponse success
*/
async login() {
const { ctx, app } = this;
const { account, password } = ctx.request.body;
if (!account || !password) {
ctx.status = 400;
ctx.body = { code: 400, message: 'account 与 password 为必填项' };
return;
}
const user = await ctx.model.User.findOne({
where: {
[app.Sequelize.Op.or]: [{ username: account }, { email: account }],
},
});
if (!user) {
ctx.status = 401;
ctx.body = { code: 401, message: '账号或密码错误' };
return;
}
if (Number(user.status) !== 1) {
ctx.status = 403;
ctx.body = { code: 403, message: '账号已禁用' };
return;
}
if (hashPassword(password, user.salt) !== user.password) {
ctx.status = 401;
ctx.body = { code: 401, message: '账号或密码错误' };
return;
}
const expiresIn = app.config.jwt.expiresIn || '2h';
const token = app.jwt.sign({ user_id: user.id }, app.config.jwt.secret, { expiresIn });
await user.update({ last_login_at: new Date() });
// 登录时间变更,失效用户缓存,下次请求重新加载
await ctx.service.cache.invalidateUser(user.id);
ctx.body = {
code: 0,
message: 'success',
data: {
token,
user_id: user.id,
expires_in: this.parseExpiresIn(expiresIn),
},
};
}
/**
* @summary 用户注册
* @description 公开接口,无需登录;需先调用发送邮箱验证码接口完成邮箱认证,邮箱全局唯一;
* 密码加盐存储,注册成功后直接返回 token
* @router post /api/auth/register
* @request body registerRequest *body
* @response 200 loginResponse success
*/
async register() {
const { ctx, app } = this;
const { username, password, email, code, phone } = ctx.request.body;
if (!username || !password || !email || !code) {
ctx.status = 400;
ctx.body = { code: 400, message: 'username、password、email、code 为必填项' };
return;
}
if (String(password).length < 6) {
ctx.status = 400;
ctx.body = { code: 400, message: '密码长度不能少于 6 位' };
return;
}
if (!EMAIL_REGEX.test(email)) {
ctx.status = 400;
ctx.body = { code: 400, message: '请填写正确的邮箱地址' };
return;
}
const usernameExist = await ctx.model.User.findOne({ where: { username } });
if (usernameExist) {
ctx.status = 400;
ctx.body = { code: 400, message: '账号已存在' };
return;
}
const emailExist = await ctx.model.User.findOne({ where: { email } });
if (emailExist) {
ctx.status = 400;
ctx.body = { code: 400, message: '邮箱已被注册' };
return;
}
// 邮箱认证:校验验证码,通过后该验证码立即失效
const verified = await verifyCode(app, email, code);
if (!verified) {
ctx.status = 400;
ctx.body = { code: 400, message: '邮箱验证码错误或已过期' };
return;
}
const salt = generateSalt();
const user = await ctx.model.User.create({
username,
// 注册不再填写昵称:账号显示名称改到主体账号关联表(principal_users.name)维护
nickname: null,
email,
phone,
salt,
password: hashPassword(password, salt),
status: 1,
});
const expiresIn = app.config.jwt.expiresIn || '2h';
const token = app.jwt.sign({ user_id: user.id }, app.config.jwt.secret, { expiresIn });
ctx.body = {
code: 0,
message: 'success',
data: {
token,
user_id: user.id,
expires_in: this.parseExpiresIn(expiresIn),
},
};
}
/**
* @summary 当前登录用户信息
* @description 需要登录:请求头 Authorization: Bearer <token>
* @router get /api/auth/profile
* @apikey
* @response 200 baseResponse success
*/
async profile() {
const { ctx } = this;
// JWT 中间件已从缓存加载用户,这里不再查库
const user = ctx.user || await ctx.service.cache.getUser(ctx.userId);
if (!user) {
ctx.status = 404;
ctx.body = { code: 404, message: '用户不存在' };
return;
}
// 返回用户所属主体列表,供前端判断是否已创建主体(多租户隔离);走缓存的可选主体列表
// 同时带出当前账号在每个主体下的名称/头像(principal_users.name / avatar),供右上角展示
const options = await ctx.service.cache.getUserPrincipalOptions(ctx.userId);
const relations = await ctx.model.PrincipalUser.findAll({
where: { user_id: ctx.userId },
attributes: [ 'principal_id', 'name', 'avatar' ],
});
const relationMap = new Map(relations.map(r => [ Number(r.principal_id), r ]));
const principals = options.map(item => {
const relation = relationMap.get(Number(item.id));
return {
id: item.id,
name: item.name,
account_name: (relation && relation.name) || null,
account_avatar: (relation && relation.avatar) || null,
};
});
ctx.body = { code: 0, message: 'success', data: { ...user, principals } };
}
/**
* @summary 发送邮箱登录验证码
* @description 公开接口,无需登录:邮箱必须已注册,发送 6 位数字验证码(10 分钟有效);
* 受频率限制:同一邮箱 60 秒一次、每日上限 10 次,超限返回 429
* @router post /api/auth/email-login/code
* @request body sendLoginCodeRequest *body
* @response 200 baseResponse success
*/
async sendLoginCode() {
const { ctx, app } = this;
const { email } = ctx.request.body;
if (!email || !EMAIL_REGEX.test(email)) {
ctx.status = 400;
ctx.body = { code: 400, message: '请填写正确的邮箱地址' };
return;
}
const user = await ctx.model.User.findOne({ where: { email } });
if (!user) {
ctx.status = 400;
ctx.body = { code: 400, message: '该邮箱未注册,请先注册账号' };
return;
}
const result = await sendCode(app, email, {
userId: user.id,
ip: ctx.ip,
scene: 'login',
length: 6,
subject: 'OMS 邮箱登录验证码',
});
if (!result.ok) {
ctx.status = 429;
ctx.body = { code: 429, message: result.message };
return;
}
ctx.body = {
code: 0,
message: 'success',
data: { email, expires_in: CODE_TTL },
};
}
/**
* @summary 邮箱验证码登录
* @description 公开接口,无需登录:校验 6 位验证码(通过后立即失效),
* 校验通过后直接签发 JWT;账号被禁用时返回 403
* @router post /api/auth/email-login
* @request body emailLoginRequest *body
* @response 200 loginResponse success
*/
async loginByEmailCode() {
const { ctx, app } = this;
const { email, code } = ctx.request.body;
if (!email || !EMAIL_REGEX.test(email)) {
ctx.status = 400;
ctx.body = { code: 400, message: '请填写正确的邮箱地址' };
return;
}
if (!code) {
ctx.status = 400;
ctx.body = { code: 400, message: 'email 与 code 为必填项' };
return;
}
const user = await ctx.model.User.findOne({ where: { email } });
if (!user) {
ctx.status = 400;
ctx.body = { code: 400, message: '该邮箱未注册,请先注册账号' };
return;
}
if (Number(user.status) !== 1) {
ctx.status = 403;
ctx.body = { code: 403, message: '账号已禁用' };
return;
}
const verified = await verifyCode(app, email, code, 'login');
if (!verified) {
ctx.status = 400;
ctx.body = { code: 400, message: '验证码错误或已过期' };
return;
}
const expiresIn = app.config.jwt.expiresIn || '2h';
const token = app.jwt.sign({ user_id: user.id }, app.config.jwt.secret, { expiresIn });
await user.update({ last_login_at: new Date() });
ctx.body = {
code: 0,
message: 'success',
data: {
token,
user_id: user.id,
expires_in: this.parseExpiresIn(expiresIn),
},
};
}
/**
* @summary 发送密码重置验证码
* @description 公开接口,无需登录:邮箱必须已注册,发送 4 位数字验证码(10 分钟有效);
* 受频率限制:同一邮箱 60 秒一次、每日上限 10 次,超限返回 429
* @router post /api/auth/reset-password/code
* @request body sendResetCodeRequest *body
* @response 200 baseResponse success
*/
async sendResetCode() {
const { ctx, app } = this;
const { email } = ctx.request.body;
if (!email || !EMAIL_REGEX.test(email)) {
ctx.status = 400;
ctx.body = { code: 400, message: '请填写正确的邮箱地址' };
return;
}
// 找回密码:邮箱必须已注册
const user = await ctx.model.User.findOne({ where: { email } });
if (!user) {
ctx.status = 400;
ctx.body = { code: 400, message: '该邮箱未注册' };
return;
}
const result = await sendCode(app, email, {
userId: user.id,
ip: ctx.ip,
scene: 'reset-password',
length: 4,
subject: 'OMS 密码重置验证码',
});
if (!result.ok) {
ctx.status = 429;
ctx.body = { code: 429, message: result.message };
return;
}
ctx.body = {
code: 0,
message: 'success',
data: { email, expires_in: CODE_TTL },
};
}
/**
* @summary 通过邮箱验证码重置密码
* @description 公开接口,无需登录:校验 4 位验证码(通过后立即失效),
* 然后重新生成盐值并更新加盐哈希密码;新密码不少于 6 位
* @router post /api/auth/reset-password
* @request body resetPasswordByCodeRequest *body
* @response 200 baseResponse success
*/
async resetPasswordByCode() {
const { ctx, app } = this;
const { email, code, password } = ctx.request.body;
if (!email || !EMAIL_REGEX.test(email)) {
ctx.status = 400;
ctx.body = { code: 400, message: '请填写正确的邮箱地址' };
return;
}
if (!code || !password) {
ctx.status = 400;
ctx.body = { code: 400, message: '验证码与新密码均为必填项' };
return;
}
if (String(password).length < 6) {
ctx.status = 400;
ctx.body = { code: 400, message: '新密码长度不能少于 6 位' };
return;
}
const user = await ctx.model.User.findOne({ where: { email } });
if (!user) {
ctx.status = 400;
ctx.body = { code: 400, message: '该邮箱未注册' };
return;
}
const verified = await verifyCode(app, email, code, 'reset-password');
if (!verified) {
ctx.status = 400;
ctx.body = { code: 400, message: '验证码错误或已过期' };
return;
}
const salt = generateSalt();
await user.update({ salt, password: hashPassword(password, salt) });
await ctx.service.cache.invalidateUser(user.id);
ctx.body = { code: 0, message: 'success', data: { id: user.id } };
}
/**
* @summary 修改当前登录用户资料
* @description 自助服务:仅可修改邮箱与手机号,不涉及密码、账号与状态;
* 昵称/头像已改到「账号(主体账号关联)」处按主体维护(principal_users.name / avatar),
* 本接口不再接受 nickname / avatar
* @router put /api/auth/profile
* @apikey
* @request body updateProfileRequest *body
* @response 200 baseResponse success
*/
async updateProfile() {
const { ctx } = this;
const user = await ctx.model.User.findByPk(ctx.userId);
if (!user) {
ctx.status = 404;
ctx.body = { code: 404, message: '用户不存在' };
return;
}
const { email, phone } = ctx.request.body;
if (email && !EMAIL_REGEX.test(email)) {
ctx.status = 400;
ctx.body = { code: 400, message: '邮箱格式不正确' };
return;
}
if (email) {
const exist = await ctx.model.User.findOne({ where: { email } });
if (exist && Number(exist.id) !== Number(user.id)) {
ctx.status = 400;
ctx.body = { code: 400, message: '该邮箱已被使用' };
return;
}
}
// 昵称/头像不再通过「我的」维护(改到账号处按主体设置),此处忽略传入值
const patch = {};
if (email !== undefined) patch.email = email;
if (phone !== undefined) patch.phone = phone;
await user.update(patch);
await ctx.service.cache.invalidateUser(user.id);
const updated = await ctx.model.User.findByPk(user.id, {
attributes: { exclude: [ 'password', 'salt' ] },
});
ctx.body = { code: 0, message: 'success', data: updated };
}
/**
* @summary 修改当前登录用户密码
* @description 自助服务:需校验原密码,通过后重新生成盐值并更新加盐哈希密码;新密码不少于 6 位且不能与原密码相同
* @router put /api/auth/password
* @apikey
* @request body changePasswordRequest *body
* @response 200 baseResponse success
*/
async changePassword() {
const { ctx } = this;
const { old_password: oldPassword, password } = ctx.request.body;
if (!oldPassword || !password) {
ctx.status = 400;
ctx.body = { code: 400, message: '原密码与新密码均为必填项' };
return;
}
if (String(password).length < 6) {
ctx.status = 400;
ctx.body = { code: 400, message: '新密码长度不少于 6 位' };
return;
}
const user = await ctx.model.User.findByPk(ctx.userId);
if (!user) {
ctx.status = 404;
ctx.body = { code: 404, message: '用户不存在' };
return;
}
if (hashPassword(oldPassword, user.salt) !== user.password) {
ctx.status = 400;
ctx.body = { code: 400, message: '原密码不正确' };
return;
}
if (oldPassword === password) {
ctx.status = 400;
ctx.body = { code: 400, message: '新密码不能与原密码相同' };
return;
}
const salt = generateSalt();
await user.update({ salt, password: hashPassword(password, salt) });
await ctx.service.cache.invalidateUser(user.id);
ctx.body = { code: 0, message: 'success', data: { id: user.id } };
}
/**
* 将有效期配置转换为秒数(如 2h => 7200)
* @param {String|Number} expiresIn 有效期,如 2h / 7200
* @return {Number} 有效秒数
*/
parseExpiresIn(expiresIn) {
if (typeof expiresIn === 'number') return expiresIn;
const matched = /^(\d+)([smhd])$/.exec(expiresIn);
if (!matched) return 0;
const units = { s: 1, m: 60, h: 3600, d: 86400 };
return Number(matched[1]) * units[matched[2]];
}
}
module.exports = AuthController;