feat(backend): 用户鉴权、菜单权限、主体与系统基础模块
- 登录/邮箱验证码/密码流程(controller/auth.js、lib/emailCode.js、middleware/jwt_auth.js) - 主体(principal)隔离与主体用户、对外接口配置模块及 principalCheck 中间件 - 菜单、用户、文件上传、快递公司字典(express_companies)等基础模块 - 通用工具:分页(lib/pagination.js)、缓存(service/cache.js) - 全量接口契约(contract/index.js)与路由注册(router.js)、config.default.js 配置 - 相关迁移:菜单组件调整与菜单种子、创建 files 表
This commit is contained in:
parent
b246cd44ec
commit
8597cf5ac9
File diff suppressed because it is too large
Load Diff
@ -92,6 +92,8 @@ class AuthController extends Controller {
|
||||
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,
|
||||
@ -190,9 +192,8 @@ class AuthController extends Controller {
|
||||
*/
|
||||
async profile() {
|
||||
const { ctx } = this;
|
||||
const user = await ctx.model.User.findByPk(ctx.userId, {
|
||||
attributes: { exclude: [ 'password', 'salt' ] },
|
||||
});
|
||||
// JWT 中间件已从缓存加载用户,这里不再查库
|
||||
const user = ctx.user || await ctx.service.cache.getUser(ctx.userId);
|
||||
|
||||
if (!user) {
|
||||
ctx.status = 404;
|
||||
@ -200,7 +201,306 @@ class AuthController extends Controller {
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: user };
|
||||
// 返回用户所属主体列表,供前端判断是否已创建主体(多租户隔离);走缓存的可选主体列表
|
||||
const options = await ctx.service.cache.getUserPrincipalOptions(ctx.userId);
|
||||
const principals = options.map(item => ({ id: item.id, name: item.name }));
|
||||
|
||||
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 自助服务:仅可修改昵称、邮箱、手机号与头像,不涉及密码、账号与状态;
|
||||
* 邮箱需校验格式与全局唯一性(排除自身)
|
||||
* @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 { nickname, email, phone, avatar } = 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 (nickname !== undefined) patch.nickname = nickname;
|
||||
if (email !== undefined) patch.email = email;
|
||||
if (phone !== undefined) patch.phone = phone;
|
||||
if (avatar !== undefined) patch.avatar = avatar;
|
||||
|
||||
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 } };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
170
backend/app/controller/expressCompany.js
Normal file
170
backend/app/controller/expressCompany.js
Normal file
@ -0,0 +1,170 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
const { parsePagination, buildPageResult } = require('../lib/pagination');
|
||||
|
||||
/**
|
||||
* @controller ExpressCompanyController 快递公司字典管理
|
||||
* 通用字典(不区分主体),供发货单等单据选择物流公司;code 为行业/WMS 标准编码
|
||||
*/
|
||||
class ExpressCompanyController extends Controller {
|
||||
/**
|
||||
* @summary 快递公司列表
|
||||
* @description 分页查询快递公司字典,支持按编码、名称与状态过滤
|
||||
* @router get /api/express-companies
|
||||
* @apikey
|
||||
* @request query integer page 页码,默认 1
|
||||
* @request query integer pageSize 每页条数,默认 20
|
||||
* @request query string code 快递编码,支持模糊匹配
|
||||
* @request query string name 快递公司名称,支持模糊匹配
|
||||
* @request query integer status 状态:1启用 0禁用
|
||||
* @response 200 expressCompanyListResponse success
|
||||
*/
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const Op = this.app.Sequelize.Op;
|
||||
const { page, pageSize, offset, limit } = parsePagination(ctx.query);
|
||||
const { code, name, status } = ctx.query;
|
||||
|
||||
const where = {};
|
||||
if (code) where.code = { [Op.like]: `%${String(code).trim().toUpperCase()}%` };
|
||||
if (name) where.name = { [Op.like]: `%${name}%` };
|
||||
if (status !== undefined && status !== '') where.status = Number(status);
|
||||
|
||||
const { count, rows } = await ctx.model.ExpressCompany.findAndCountAll({
|
||||
where,
|
||||
offset,
|
||||
limit,
|
||||
order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]],
|
||||
});
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 快递公司下拉(仅启用)
|
||||
* @description 供发货单等表单选择物流公司,按 sort 升序返回
|
||||
* @router get /api/express-companies/select
|
||||
* @apikey
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async select() {
|
||||
const { ctx } = this;
|
||||
const rows = await ctx.model.ExpressCompany.findAll({
|
||||
where: { status: 1 },
|
||||
attributes: [ 'id', 'code', 'name' ],
|
||||
order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]],
|
||||
});
|
||||
ctx.body = { code: 0, message: 'success', data: rows };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 快递公司详情
|
||||
* @router get /api/express-companies/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 快递公司主键ID
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async show() {
|
||||
const { ctx } = this;
|
||||
const item = await ctx.model.ExpressCompany.findByPk(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/express-companies
|
||||
* @apikey
|
||||
* @request body createExpressCompanyRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async create() {
|
||||
const { ctx } = this;
|
||||
const body = ctx.request.body || {};
|
||||
const code = String(body.code || '').trim().toUpperCase();
|
||||
const name = String(body.name || '').trim();
|
||||
|
||||
if (!code || !name) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: 'code(快递编码)与 name(快递公司名称)为必填项' };
|
||||
return;
|
||||
}
|
||||
|
||||
const exist = await ctx.model.ExpressCompany.findOne({ where: { code } });
|
||||
if (exist) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: `快递编码 ${code} 已存在` };
|
||||
return;
|
||||
}
|
||||
|
||||
const item = await ctx.model.ExpressCompany.create({ ...body, code, name });
|
||||
ctx.body = { code: 0, message: 'success', data: { id: item.id } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 更新快递公司
|
||||
* @description 未传入的字段保持原值;编码唯一(统一转大写)
|
||||
* @router put /api/express-companies/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 快递公司主键ID
|
||||
* @request body updateExpressCompanyRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async update() {
|
||||
const { ctx } = this;
|
||||
const item = await ctx.model.ExpressCompany.findByPk(ctx.params.id);
|
||||
if (!item) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '快递公司不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
const body = { ...(ctx.request.body || {}) };
|
||||
if (body.code !== undefined) {
|
||||
const code = String(body.code).trim().toUpperCase();
|
||||
if (!code) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: 'code(快递编码)不能为空' };
|
||||
return;
|
||||
}
|
||||
const exist = await ctx.model.ExpressCompany.findOne({ where: { code } });
|
||||
if (exist && Number(exist.id) !== Number(item.id)) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: `快递编码 ${code} 已存在` };
|
||||
return;
|
||||
}
|
||||
body.code = code;
|
||||
}
|
||||
|
||||
await item.update(body);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: item.id } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 删除快递公司
|
||||
* @description 物理删除字典项;如已停用建议改用 status=0 而非删除
|
||||
* @router delete /api/express-companies/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 快递公司主键ID
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async destroy() {
|
||||
const { ctx } = this;
|
||||
const item = await ctx.model.ExpressCompany.findByPk(ctx.params.id);
|
||||
if (!item) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '快递公司不存在' };
|
||||
return;
|
||||
}
|
||||
await item.destroy();
|
||||
ctx.body = { code: 0, message: 'success' };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ExpressCompanyController;
|
||||
231
backend/app/controller/file.js
Normal file
231
backend/app/controller/file.js
Normal file
@ -0,0 +1,231 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const fsp = require('fs/promises');
|
||||
const path = require('path');
|
||||
const { parsePagination, buildPageResult } = require('../lib/pagination');
|
||||
|
||||
/** 允许上传的图片扩展名(与 config.multipart.whitelist 保持一致) */
|
||||
const ALLOWED_EXT = [ '.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg' ];
|
||||
|
||||
/** 扩展名 -> Content-Type,供 raw 接口回写响应头 */
|
||||
const MIME = {
|
||||
'.jpg': 'image/jpeg',
|
||||
'.jpeg': 'image/jpeg',
|
||||
'.png': 'image/png',
|
||||
'.gif': 'image/gif',
|
||||
'.bmp': 'image/bmp',
|
||||
'.webp': 'image/webp',
|
||||
'.svg': 'image/svg+xml',
|
||||
};
|
||||
|
||||
/** raw 访问路径必须形如「主体ID/年/月/日/hash.ext」,非法路径(含 .. 穿越)一律拒绝 */
|
||||
const RAW_PATH_RE = /^\d+\/\d{4}\/\d{2}\/\d{2}\/[a-f0-9]{64}\.[a-z0-9]+$/;
|
||||
|
||||
const pad2 = num => String(num).padStart(2, '0');
|
||||
|
||||
/** 流式计算文件 SHA256,避免大图整块读入内存 */
|
||||
function sha256File(filepath) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const hash = crypto.createHash('sha256');
|
||||
fs.createReadStream(filepath)
|
||||
.on('data', chunk => hash.update(chunk))
|
||||
.on('end', () => resolve(hash.digest('hex')))
|
||||
.on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
/** 临时目录与上传目录可能不在同一磁盘(EXDEV),先尝试 rename,失败再复制 */
|
||||
async function moveFile(from, to) {
|
||||
try {
|
||||
await fsp.rename(from, to);
|
||||
} catch (err) {
|
||||
if (err.code !== 'EXDEV') throw err;
|
||||
await fsp.copyFile(from, to);
|
||||
await fsp.unlink(from);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @controller FileController 文件资源管理
|
||||
*/
|
||||
class FileController extends Controller {
|
||||
/**
|
||||
* @summary 文件列表
|
||||
* @description 分页查询当前主体已上传的文件资源
|
||||
* @router get /api/files
|
||||
* @apikey
|
||||
* @request query integer page 页码,默认 1
|
||||
* @request query integer pageSize 每页条数,默认 20
|
||||
* @request query integer principal_id 所属主体ID(必填,需当前账号已绑定该主体)
|
||||
* @request query string keyword 关键词,模糊匹配原始文件名
|
||||
* @response 200 fileListResponse success
|
||||
*/
|
||||
async index() {
|
||||
const { ctx, app } = this;
|
||||
const Op = app.Sequelize.Op;
|
||||
const { page, pageSize, offset, limit } = parsePagination(ctx.query);
|
||||
const keyword = (ctx.query.keyword || '').trim();
|
||||
|
||||
const where = { principal_id: ctx.state.principalId };
|
||||
if (keyword) where.name = { [Op.like]: `%${keyword}%` };
|
||||
|
||||
const { count, rows } = await ctx.model.File.findAndCountAll({
|
||||
where,
|
||||
offset,
|
||||
limit,
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
});
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 文件去重预检
|
||||
* @description 上传前按内容 SHA256 批量查验,命中的文件直接复用已有 URL,无需重复上传
|
||||
* @router post /api/files/check
|
||||
* @apikey
|
||||
* @request body checkFilesRequest *body
|
||||
* @response 200 fileCheckResponse success
|
||||
*/
|
||||
async check() {
|
||||
const { ctx } = this;
|
||||
const hashes = ctx.request.body.hashes;
|
||||
|
||||
if (!Array.isArray(hashes) || !hashes.length) {
|
||||
ctx.body = { code: 0, message: 'success', data: [] };
|
||||
return;
|
||||
}
|
||||
|
||||
const rows = await ctx.model.File.findAll({
|
||||
where: {
|
||||
principal_id: ctx.state.principalId,
|
||||
hash: hashes.slice(0, 100).map(String),
|
||||
},
|
||||
});
|
||||
ctx.body = { code: 0, message: 'success', data: rows };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 上传文件
|
||||
* @description 单文件上传(表单字段 file,仅图片)。按内容 SHA256 在当前主体内去重:
|
||||
* 命中已有记录直接返回其 URL,不重复落盘;未命中则按「主体ID/年/月/日」分目录存储,文件名为内容 hash
|
||||
* @router post /api/files/upload
|
||||
* @apikey
|
||||
* @request formData file *file 图片文件
|
||||
* @request formData integer principal_id 所属主体ID(必填,需当前账号已绑定该主体)
|
||||
* @response 200 fileUploadResponse success
|
||||
*/
|
||||
async upload() {
|
||||
const { ctx, app } = this;
|
||||
const principalId = ctx.state.principalId;
|
||||
const files = ctx.request.files || [];
|
||||
|
||||
if (!files.length) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '未接收到上传文件(表单字段名 file)' };
|
||||
return;
|
||||
}
|
||||
|
||||
const file = files.find(item => item.field === 'file') || files[0];
|
||||
const originalName = file.filename || path.basename(file.filepath);
|
||||
const ext = path.extname(originalName).toLowerCase();
|
||||
|
||||
if (!ALLOWED_EXT.includes(ext)) {
|
||||
await ctx.cleanupRequestFiles();
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: `仅支持上传图片:${ALLOWED_EXT.join('、')}` };
|
||||
return;
|
||||
}
|
||||
|
||||
// 1) 内容 hash:既是去重依据,也是落盘文件名
|
||||
const hash = await sha256File(file.filepath);
|
||||
const stat = await fsp.stat(file.filepath);
|
||||
|
||||
// 2) 主体内已存在同一份文件:直接复用,丢弃临时文件
|
||||
const exist = await ctx.model.File.findOne({
|
||||
where: { principal_id: principalId, hash },
|
||||
});
|
||||
if (exist) {
|
||||
await ctx.cleanupRequestFiles();
|
||||
ctx.body = { code: 0, message: 'success', data: { ...exist.toJSON(), deduped: true } };
|
||||
return;
|
||||
}
|
||||
|
||||
// 3) 未命中:按上传时间(年/月/日)分目录,并挂在主体目录下实现资源隔离
|
||||
const now = new Date();
|
||||
const relDir = path.posix.join(
|
||||
String(principalId),
|
||||
String(now.getFullYear()),
|
||||
pad2(now.getMonth() + 1),
|
||||
pad2(now.getDate())
|
||||
);
|
||||
const relPath = path.posix.join(relDir, `${hash}${ext}`);
|
||||
|
||||
await fsp.mkdir(path.join(app.config.upload.dir, relDir), { recursive: true });
|
||||
await moveFile(file.filepath, path.join(app.config.upload.dir, relPath));
|
||||
await ctx.cleanupRequestFiles();
|
||||
|
||||
const payload = {
|
||||
principal_id: principalId,
|
||||
hash,
|
||||
name: originalName,
|
||||
ext,
|
||||
mime: file.mime || file.mimeType || '',
|
||||
size: stat.size,
|
||||
path: relPath,
|
||||
url: `${app.config.upload.urlPrefix}/${relPath}`,
|
||||
};
|
||||
|
||||
try {
|
||||
const saved = await ctx.model.File.create(payload);
|
||||
ctx.body = { code: 0, message: 'success', data: { ...saved.toJSON(), deduped: false } };
|
||||
} catch (err) {
|
||||
// 并发上传同一文件时唯一索引冲突,回读已有记录返回
|
||||
if (err.name === 'SequelizeUniqueConstraintError') {
|
||||
const record = await ctx.model.File.findOne({
|
||||
where: { principal_id: principalId, hash },
|
||||
});
|
||||
ctx.body = { code: 0, message: 'success', data: { ...record.toJSON(), deduped: true } };
|
||||
return;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 读取文件
|
||||
* @description 按存储相对路径读取文件内容。路径形如「主体ID/年/月/日/hash.ext」,
|
||||
* 由上传接口返回,URL 不可枚举;公开读取便于 img 标签直接引用
|
||||
* @router get /api/files/raw/{path}
|
||||
* @request path string *path 存储相对路径,形如 1/2026/09/11/{hash}.png
|
||||
* @response 200 baseResponse 文件二进制流,Content-Type 由扩展名决定
|
||||
*/
|
||||
async raw() {
|
||||
const { ctx, app } = this;
|
||||
const relPath = String(ctx.params[0] || '');
|
||||
|
||||
if (!RAW_PATH_RE.test(relPath)) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '文件路径不合法' };
|
||||
return;
|
||||
}
|
||||
|
||||
const rootDir = path.resolve(app.config.upload.dir);
|
||||
const absFile = path.resolve(rootDir, relPath);
|
||||
if (!absFile.startsWith(rootDir + path.sep) || !fs.existsSync(absFile)) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '文件不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.type = MIME[path.extname(absFile).toLowerCase()] || 'application/octet-stream';
|
||||
// 文件名即内容 hash,内容永不变化,可长期强缓存
|
||||
ctx.set('Cache-Control', 'public, max-age=31536000, immutable');
|
||||
ctx.body = fs.createReadStream(absFile);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = FileController;
|
||||
@ -1,6 +1,7 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
const { parsePagination, buildPageResult } = require('../lib/pagination');
|
||||
|
||||
/**
|
||||
* @controller MenuController 菜单管理
|
||||
@ -20,8 +21,7 @@ class MenuController extends Controller {
|
||||
*/
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const page = Number(ctx.query.page || 1);
|
||||
const pageSize = Number(ctx.query.pageSize || 20);
|
||||
const { page, pageSize, offset, limit } = parsePagination(ctx.query);
|
||||
const { parent_id: parentId, type, status } = ctx.query;
|
||||
|
||||
const where = {};
|
||||
@ -31,12 +31,12 @@ class MenuController extends Controller {
|
||||
|
||||
const { count, rows } = await ctx.model.Menu.findAndCountAll({
|
||||
where,
|
||||
offset: (page - 1) * pageSize,
|
||||
limit: pageSize,
|
||||
offset,
|
||||
limit,
|
||||
order: [[ 'sort', 'DESC' ], [ 'id', 'ASC' ]],
|
||||
});
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: { list: rows, total: count, page, pageSize } };
|
||||
ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
const { parsePagination, buildPageResult } = require('../lib/pagination');
|
||||
|
||||
/**
|
||||
* @controller PrincipalController 主体管理
|
||||
@ -13,7 +14,7 @@ class PrincipalController extends Controller {
|
||||
* @apikey
|
||||
* @request query integer page 页码,默认 1
|
||||
* @request query integer pageSize 每页条数,默认 20
|
||||
* @request query string keyword 关键词,匹配主体编码或名称
|
||||
* @request query string keyword 关键词,匹配主体名称
|
||||
* @request query integer type 主体类型:1自营 2加盟 3外部,不传则不过滤
|
||||
* @request query integer status 状态:1启用 0禁用,不传则不过滤
|
||||
* @response 200 principalListResponse success
|
||||
@ -21,33 +22,48 @@ class PrincipalController extends Controller {
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const Op = this.app.Sequelize.Op;
|
||||
const page = Number(ctx.query.page || 1);
|
||||
const pageSize = Number(ctx.query.pageSize || 20);
|
||||
const { page, pageSize, offset, limit } = parsePagination(ctx.query);
|
||||
const { keyword, type, status } = ctx.query;
|
||||
|
||||
const where = {};
|
||||
if (keyword) {
|
||||
where[Op.or] = [
|
||||
{ code: { [Op.like]: `%${keyword}%` } },
|
||||
{ name: { [Op.like]: `%${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: (page - 1) * pageSize,
|
||||
limit: pageSize,
|
||||
offset,
|
||||
limit,
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
});
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: { list: rows, total: count, page, pageSize } };
|
||||
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 按主键查询主体
|
||||
* @description 按主键查询主体(走缓存,主体更新/删除时自动失效)
|
||||
* @router get /api/principals/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 主体主键ID
|
||||
@ -55,7 +71,7 @@ class PrincipalController extends Controller {
|
||||
*/
|
||||
async show() {
|
||||
const { ctx } = this;
|
||||
const principal = await ctx.model.Principal.findByPk(ctx.params.id);
|
||||
const principal = await ctx.service.cache.getPrincipal(ctx.params.id);
|
||||
|
||||
if (!principal) {
|
||||
ctx.status = 404;
|
||||
@ -68,7 +84,7 @@ class PrincipalController extends Controller {
|
||||
|
||||
/**
|
||||
* @summary 新增主体
|
||||
* @description 主体编码 code 全局唯一
|
||||
* @description 主体名称 name 必填;创建者自动关联为该主体 owner(多租户隔离)
|
||||
* @router post /api/principals
|
||||
* @apikey
|
||||
* @request body createPrincipalRequest *body
|
||||
@ -76,22 +92,30 @@ class PrincipalController extends Controller {
|
||||
*/
|
||||
async create() {
|
||||
const { ctx } = this;
|
||||
const { code, name } = ctx.request.body;
|
||||
const { name } = ctx.request.body;
|
||||
|
||||
if (!code || !name) {
|
||||
if (!name) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: 'code 与 name 为必填项' };
|
||||
return;
|
||||
}
|
||||
|
||||
const exist = await ctx.model.Principal.findOne({ where: { code } });
|
||||
if (exist) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '主体编码已存在' };
|
||||
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 } };
|
||||
}
|
||||
|
||||
@ -115,12 +139,16 @@ class PrincipalController extends Controller {
|
||||
}
|
||||
|
||||
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 物理删除主体;存在关联商品/订单时需先清理关联数据
|
||||
* @description 物理删除主体;存在关联商品/订单时拒绝删除并提示先清理;删除前自动解除主体与用户的绑定关系
|
||||
* @router delete /api/principals/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 主体主键ID
|
||||
@ -136,7 +164,23 @@ class PrincipalController extends Controller {
|
||||
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) } };
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
const { parsePagination, buildPageResult } = require('../lib/pagination');
|
||||
|
||||
/**
|
||||
* @controller PrincipalExternalApiController 主体外部接口管理
|
||||
@ -20,8 +21,7 @@ class PrincipalExternalApiController extends Controller {
|
||||
*/
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const page = Number(ctx.query.page || 1);
|
||||
const pageSize = Number(ctx.query.pageSize || 20);
|
||||
const { page, pageSize, offset, limit } = parsePagination(ctx.query);
|
||||
const { code, status } = ctx.query;
|
||||
const principalId = ctx.state.principalId;
|
||||
|
||||
@ -32,12 +32,12 @@ class PrincipalExternalApiController extends Controller {
|
||||
|
||||
const { count, rows } = await ctx.model.PrincipalExternalApi.findAndCountAll({
|
||||
where,
|
||||
offset: (page - 1) * pageSize,
|
||||
limit: pageSize,
|
||||
offset,
|
||||
limit,
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
});
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: { list: rows, total: count, page, pageSize } };
|
||||
ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@ -1,6 +1,9 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
const crypto = require('crypto');
|
||||
const { generateSalt, hashPassword } = require('../lib/password');
|
||||
const { parsePagination, buildPageResult } = require('../lib/pagination');
|
||||
|
||||
/**
|
||||
* @controller PrincipalUserController 主体用户关联管理
|
||||
@ -21,8 +24,7 @@ class PrincipalUserController extends Controller {
|
||||
*/
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const page = Number(ctx.query.page || 1);
|
||||
const pageSize = Number(ctx.query.pageSize || 20);
|
||||
const { page, pageSize, offset, limit } = parsePagination(ctx.query);
|
||||
const { user_id: userId, role, status } = ctx.query;
|
||||
const principalId = ctx.state.principalId;
|
||||
|
||||
@ -34,12 +36,15 @@ class PrincipalUserController extends Controller {
|
||||
|
||||
const { count, rows } = await ctx.model.PrincipalUser.findAndCountAll({
|
||||
where,
|
||||
offset: (page - 1) * pageSize,
|
||||
limit: pageSize,
|
||||
offset,
|
||||
limit,
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
include: [
|
||||
{ model: ctx.model.User, as: 'user', attributes: { exclude: [ 'password', 'salt' ] } },
|
||||
],
|
||||
});
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: { list: rows, total: count, page, pageSize } };
|
||||
ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) };
|
||||
}
|
||||
|
||||
/**
|
||||
@ -96,9 +101,117 @@ class PrincipalUserController extends Controller {
|
||||
}
|
||||
|
||||
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 传入邮箱、用户名称与主体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, 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,
|
||||
nickname: name,
|
||||
email,
|
||||
salt,
|
||||
password: hashed,
|
||||
status: 1,
|
||||
}, { transaction });
|
||||
|
||||
const relation = await ctx.model.PrincipalUser.create({
|
||||
principal_id: principalId,
|
||||
user_id: user.id,
|
||||
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: user.nickname,
|
||||
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 可修改角色、默认主体标识与状态
|
||||
@ -120,6 +233,7 @@ class PrincipalUserController extends Controller {
|
||||
|
||||
delete ctx.request.body.principal_id;
|
||||
await relation.update(ctx.request.body);
|
||||
await ctx.service.cache.invalidateUserPrincipals(relation.user_id);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: relation.id } };
|
||||
}
|
||||
|
||||
@ -141,7 +255,9 @@ class PrincipalUserController extends Controller {
|
||||
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) } };
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
|
||||
const { Controller } = require('egg');
|
||||
const { generateSalt, hashPassword } = require('../lib/password');
|
||||
const { parsePagination, buildPageResult } = require('../lib/pagination');
|
||||
|
||||
/**
|
||||
* @controller UserController 用户管理
|
||||
@ -21,8 +22,7 @@ class UserController extends Controller {
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const Op = this.app.Sequelize.Op;
|
||||
const page = Number(ctx.query.page || 1);
|
||||
const pageSize = Number(ctx.query.pageSize || 20);
|
||||
const { page, pageSize, offset, limit } = parsePagination(ctx.query);
|
||||
const { keyword, status } = ctx.query;
|
||||
|
||||
const where = {};
|
||||
@ -36,13 +36,13 @@ class UserController extends Controller {
|
||||
|
||||
const { count, rows } = await ctx.model.User.findAndCountAll({
|
||||
where,
|
||||
offset,
|
||||
limit,
|
||||
attributes: { exclude: [ 'password', 'salt' ] },
|
||||
offset: (page - 1) * pageSize,
|
||||
limit: pageSize,
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
});
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: { list: rows, total: count, page, pageSize } };
|
||||
ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) };
|
||||
}
|
||||
|
||||
/**
|
||||
@ -122,7 +122,10 @@ class UserController extends Controller {
|
||||
return;
|
||||
}
|
||||
|
||||
// 请求拦截器会注入 principal_id,而 users 表无该字段,更新前剔除避免脏字段写入
|
||||
delete ctx.request.body.principal_id;
|
||||
await user.update(ctx.request.body);
|
||||
await ctx.service.cache.invalidateUser(user.id);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: user.id } };
|
||||
}
|
||||
|
||||
@ -154,6 +157,7 @@ class UserController extends Controller {
|
||||
|
||||
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 } };
|
||||
}
|
||||
|
||||
@ -176,6 +180,7 @@ class UserController extends Controller {
|
||||
}
|
||||
|
||||
await user.destroy();
|
||||
await ctx.service.cache.invalidateUser(user.id);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } };
|
||||
}
|
||||
}
|
||||
|
||||
@ -6,16 +6,17 @@ const nodemailer = require('nodemailer');
|
||||
const CODE_TTL = 10 * 60;
|
||||
/** 每日计数缓存时间:24 小时 */
|
||||
const DAY_TTL = 24 * 60 * 60;
|
||||
/** 邮件主题 */
|
||||
/** 默认邮件主题(注册场景) */
|
||||
const SUBJECT = 'OMS 注册邮箱验证码';
|
||||
|
||||
/**
|
||||
* 验证码在 Redis 中的 key
|
||||
* 验证码在 Redis 中的 key(按场景隔离,避免注册与找回密码互串)
|
||||
* @param {String} email 邮箱
|
||||
* @param {String} scene 场景:register 注册 / reset-password 找回密码
|
||||
* @return {String} redis key
|
||||
*/
|
||||
function codeKey(email) {
|
||||
return `oms:email:code:${email}`;
|
||||
function codeKey(email, scene = 'register') {
|
||||
return `oms:email:code:${scene}:${email}`;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -39,11 +40,14 @@ function dailyKey(email) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成 6 位数字验证码
|
||||
* 生成指定位数的数字验证码
|
||||
* @param {Number} len 位数,默认 6(找回密码场景为 4 位)
|
||||
* @return {String} 验证码
|
||||
*/
|
||||
function generateCode() {
|
||||
return String(Math.floor(100000 + Math.random() * 900000));
|
||||
function generateCode(len = 6) {
|
||||
const min = 10 ** (len - 1);
|
||||
const max = 10 ** len - 1;
|
||||
return String(Math.floor(min + Math.random() * (max - min + 1)));
|
||||
}
|
||||
|
||||
/**
|
||||
@ -101,18 +105,24 @@ async function markSent(app, email) {
|
||||
* 未配置 SMTP(config.mailer.host 为空)时仅记录日志,便于本地开发调试
|
||||
* @param {Egg.Application} app egg application
|
||||
* @param {String} email 目标邮箱
|
||||
* @param {Object} options 附加信息:userId(注册场景为空)、ip、scene
|
||||
* @param {Object} options 附加信息:userId、ip、scene、length(验证码位数,默认6)、subject
|
||||
* @return {Promise<Object>} { ok: 是否发送成功, message: 失败原因 }
|
||||
*/
|
||||
async function sendCode(app, email, options = {}) {
|
||||
const { userId = null, ip = '', scene = 'register' } = options;
|
||||
const {
|
||||
userId = null,
|
||||
ip = '',
|
||||
scene = 'register',
|
||||
length = 6,
|
||||
subject = SUBJECT,
|
||||
} = options;
|
||||
|
||||
const limitMessage = await checkLimit(app, email);
|
||||
if (limitMessage) {
|
||||
await writeLog(app, {
|
||||
scene,
|
||||
to_email: email,
|
||||
subject: SUBJECT,
|
||||
subject,
|
||||
content: '',
|
||||
user_id: userId,
|
||||
ip,
|
||||
@ -122,9 +132,9 @@ async function sendCode(app, email, options = {}) {
|
||||
return { ok: false, message: limitMessage };
|
||||
}
|
||||
|
||||
const code = generateCode();
|
||||
const content = `您的注册验证码为:${code},${CODE_TTL / 60} 分钟内有效。`;
|
||||
await app.redis.set(codeKey(email), code, 'EX', CODE_TTL);
|
||||
const code = generateCode(length);
|
||||
const content = `您的验证码为:${code},${CODE_TTL / 60} 分钟内有效。`;
|
||||
await app.redis.set(codeKey(email, scene), code, 'EX', CODE_TTL);
|
||||
|
||||
let errorMsg = '';
|
||||
const mailer = app.config.mailer;
|
||||
@ -143,7 +153,7 @@ async function sendCode(app, email, options = {}) {
|
||||
await transporter.sendMail({
|
||||
from: mailer.from,
|
||||
to: email,
|
||||
subject: SUBJECT,
|
||||
subject,
|
||||
text: content,
|
||||
});
|
||||
} catch (err) {
|
||||
@ -155,7 +165,7 @@ async function sendCode(app, email, options = {}) {
|
||||
await writeLog(app, {
|
||||
scene,
|
||||
to_email: email,
|
||||
subject: SUBJECT,
|
||||
subject,
|
||||
content,
|
||||
user_id: userId,
|
||||
ip,
|
||||
@ -174,13 +184,14 @@ async function sendCode(app, email, options = {}) {
|
||||
* @param {Egg.Application} app egg application
|
||||
* @param {String} email 邮箱
|
||||
* @param {String} code 验证码
|
||||
* @param {String} scene 场景:register 注册 / reset-password 找回密码
|
||||
* @return {Promise<Boolean>} 校验是否通过
|
||||
*/
|
||||
async function verifyCode(app, email, code) {
|
||||
const cached = await app.redis.get(codeKey(email));
|
||||
async function verifyCode(app, email, code, scene = 'register') {
|
||||
const cached = await app.redis.get(codeKey(email, scene));
|
||||
if (!cached || cached !== String(code)) return false;
|
||||
|
||||
await app.redis.del(codeKey(email));
|
||||
await app.redis.del(codeKey(email, scene));
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
63
backend/app/lib/pagination.js
Normal file
63
backend/app/lib/pagination.js
Normal file
@ -0,0 +1,63 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 列表分页统一封装
|
||||
* - 所有列表接口统一用 parsePagination 解析 page / pageSize,避免各控制器各写一套
|
||||
* - pageSize 做了上限保护(默认 200),防止前端传入超大值把整表拉到内存
|
||||
* - 列表响应体统一用 buildPageResult 组装,保证 { list, total, page, pageSize } 结构一致
|
||||
*/
|
||||
|
||||
/** 默认每页条数 */
|
||||
const DEFAULT_PAGE_SIZE = 20;
|
||||
/** 每页条数上限 */
|
||||
const MAX_PAGE_SIZE = 200;
|
||||
|
||||
/**
|
||||
* 转为整数,非法值返回兜底值
|
||||
* @param {*} value 原始值
|
||||
* @param {Number} fallback 兜底值
|
||||
* @return {Number} 整数
|
||||
*/
|
||||
function toInt(value, fallback) {
|
||||
const num = Number.parseInt(value, 10);
|
||||
return Number.isFinite(num) ? num : fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析分页参数
|
||||
* @param {Object} query ctx.query
|
||||
* @param {Object} [options] defaultPageSize 默认每页条数(默认 20)、maxPageSize 上限(默认 200)
|
||||
* @return {{page: Number, pageSize: Number, offset: Number, limit: Number}} 分页参数
|
||||
*/
|
||||
function parsePagination(query = {}, options = {}) {
|
||||
const defaultPageSize = options.defaultPageSize || DEFAULT_PAGE_SIZE;
|
||||
const maxPageSize = options.maxPageSize || MAX_PAGE_SIZE;
|
||||
|
||||
const page = Math.max(1, toInt(query.page, 1));
|
||||
const pageSize = Math.min(maxPageSize, Math.max(1, toInt(query.pageSize, defaultPageSize)));
|
||||
|
||||
return { page, pageSize, offset: (page - 1) * pageSize, limit: pageSize };
|
||||
}
|
||||
|
||||
/**
|
||||
* 组装统一的分页响应数据
|
||||
* @param {Array} rows 当前页数据
|
||||
* @param {Number} total 总条数
|
||||
* @param {Object} pageInfo 分页参数(parsePagination 的返回值或 { page, pageSize })
|
||||
* @return {{list: Array, total: Number, page: Number, pageSize: Number}} 响应数据
|
||||
*/
|
||||
function buildPageResult(rows, total, pageInfo = {}) {
|
||||
return {
|
||||
list: rows,
|
||||
total,
|
||||
page: pageInfo.page,
|
||||
pageSize: pageInfo.pageSize,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
DEFAULT_PAGE_SIZE,
|
||||
MAX_PAGE_SIZE,
|
||||
parsePagination,
|
||||
buildPageResult,
|
||||
};
|
||||
@ -4,7 +4,8 @@ const TOKEN_PREFIX = 'Bearer ';
|
||||
|
||||
/**
|
||||
* JWT 鉴权中间件
|
||||
* 校验请求头 Authorization: Bearer <token>,解析后仅取 user_id 挂载到 ctx.userId
|
||||
* 校验请求头 Authorization: Bearer <token>,解析出 user_id 后加载用户信息(Redis 缓存优先,避免频繁查库),
|
||||
* 并把用户信息与其可用主体ID列表挂载到 ctx,供控制器与后续中间件复用
|
||||
* @return {Function} koa 中间件
|
||||
*/
|
||||
module.exports = () => {
|
||||
@ -19,15 +20,43 @@ module.exports = () => {
|
||||
return;
|
||||
}
|
||||
|
||||
// 仅校验 token 本身,不要把控制器(await next)抛出的业务异常也吞成 401
|
||||
let decoded;
|
||||
try {
|
||||
// token 载荷仅包含 user_id,不含任何敏感信息
|
||||
const decoded = app.jwt.verify(token, app.config.jwt.secret);
|
||||
ctx.userId = decoded.user_id;
|
||||
ctx.state.userId = decoded.user_id;
|
||||
await next();
|
||||
decoded = app.jwt.verify(token, app.config.jwt.secret);
|
||||
} catch (err) {
|
||||
ctx.status = 401;
|
||||
ctx.body = { code: 401, message: '登录凭证无效或已过期' };
|
||||
return;
|
||||
}
|
||||
|
||||
const userId = decoded.user_id;
|
||||
|
||||
// 用户信息与可用主体ID均走缓存,命中时不再查库
|
||||
const [ user, principalIds ] = await Promise.all([
|
||||
ctx.service.cache.getUser(userId),
|
||||
ctx.service.cache.getUserPrincipalIds(userId),
|
||||
]);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
ctx.userId = userId;
|
||||
ctx.state.userId = userId;
|
||||
ctx.user = user;
|
||||
ctx.state.user = user;
|
||||
ctx.userPrincipalIds = principalIds || [];
|
||||
ctx.state.principalIds = principalIds || [];
|
||||
|
||||
await next();
|
||||
};
|
||||
};
|
||||
|
||||
@ -56,11 +56,9 @@ module.exports = (options = {}) => {
|
||||
}
|
||||
principalId = Number(principalId);
|
||||
|
||||
// 校验账号与主体的绑定关系
|
||||
const bound = await ctx.model.PrincipalUser.findOne({
|
||||
where: { user_id: userId, principal_id: principalId },
|
||||
attributes: [ 'id' ],
|
||||
});
|
||||
// 校验账号与主体的绑定关系:主体ID列表来自缓存(JWT 中间件已加载),避免每次请求查关联表
|
||||
const principalIds = ctx.state.principalIds || await ctx.service.cache.getUserPrincipalIds(userId);
|
||||
const bound = new Set((principalIds || []).map(Number)).has(principalId);
|
||||
if (!bound) {
|
||||
ctx.status = 403;
|
||||
ctx.body = { code: 403, message: '无权操作该主体下的数据' };
|
||||
|
||||
29
backend/app/model/expressCompany.js
Normal file
29
backend/app/model/expressCompany.js
Normal file
@ -0,0 +1,29 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 快递公司字典模型,对应 express_companies 表(通用字典,不区分主体)
|
||||
*
|
||||
* 供发货单等单据选择物流公司:code 使用行业/WMS 标准编码(SF/YTO/ZTO...),
|
||||
* 选择后写入单据的 logistics_code / logistics_name。
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} expressCompany model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, TINYINT, INTEGER, DATE } = app.Sequelize;
|
||||
|
||||
const ExpressCompany = app.model.define('express_company', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
code: { type: STRING(50), allowNull: false, comment: '快递公司编码(行业/WMS 标准编码,如 SF/YTO/ZTO)' },
|
||||
name: { type: STRING(100), allowNull: false, comment: '快递公司名称(如 顺丰速运)' },
|
||||
status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' },
|
||||
sort: { type: INTEGER, allowNull: false, defaultValue: 0, comment: '排序(下拉展示顺序,越小越靠前)' },
|
||||
remark: { type: STRING(255), comment: '备注' },
|
||||
created_at: { type: DATE, comment: '创建时间' },
|
||||
updated_at: { type: DATE, comment: '更新时间' },
|
||||
}, {
|
||||
tableName: 'express_companies',
|
||||
comment: '快递公司字典',
|
||||
});
|
||||
|
||||
return ExpressCompany;
|
||||
};
|
||||
35
backend/app/model/file.js
Normal file
35
backend/app/model/file.js
Normal file
@ -0,0 +1,35 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 文件资源模型,对应 files 表
|
||||
* 同一主体下按内容 hash 去重(uk_files_principal_hash),磁盘路径按「主体ID/年/月/日」分层
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} file model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, INTEGER, DATE } = app.Sequelize;
|
||||
|
||||
const File = app.model.define('file', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' },
|
||||
hash: { type: STRING(64), allowNull: false, comment: '文件内容 SHA256,用于去重' },
|
||||
name: { type: STRING(255), allowNull: false, comment: '原始文件名' },
|
||||
ext: { type: STRING(20), allowNull: false, comment: '扩展名(小写,含点,如 .png)' },
|
||||
mime: { type: STRING(100), comment: 'MIME 类型' },
|
||||
size: { type: INTEGER.UNSIGNED, allowNull: false, defaultValue: 0, comment: '文件大小(字节)' },
|
||||
path: { type: STRING(255), allowNull: false, comment: '相对存储路径:主体ID/年/月/日/hash.ext' },
|
||||
url: { type: STRING(500), allowNull: false, comment: '访问地址' },
|
||||
created_at: { type: DATE, comment: '创建时间' },
|
||||
updated_at: { type: DATE, comment: '更新时间' },
|
||||
deleted_at: { type: DATE, comment: '软删除时间' },
|
||||
}, {
|
||||
paranoid: true,
|
||||
deletedAt: 'deleted_at',
|
||||
});
|
||||
|
||||
File.associate = () => {
|
||||
app.model.File.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' });
|
||||
};
|
||||
|
||||
return File;
|
||||
};
|
||||
@ -16,6 +16,7 @@ module.exports = app => {
|
||||
path: { type: STRING(200), comment: '前端路由/地址' },
|
||||
icon: { type: STRING(100), comment: '图标' },
|
||||
permission: { type: STRING(100), comment: '权限标识,如 order:create' },
|
||||
component: { type: STRING(200), comment: '前端组件路径,如 views/system/user/index.vue' },
|
||||
sort: { type: INTEGER, allowNull: false, defaultValue: 0, comment: '排序' },
|
||||
status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' },
|
||||
created_at: { type: DATE, comment: '创建时间' },
|
||||
|
||||
@ -10,7 +10,6 @@ module.exports = app => {
|
||||
|
||||
const Principal = app.model.define('principal', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
code: { type: STRING(50), allowNull: false, comment: '主体编码' },
|
||||
name: { type: STRING(100), allowNull: false, comment: '主体名称' },
|
||||
type: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '主体类型:1自营 2加盟 3外部' },
|
||||
contact_name: { type: STRING(50), comment: '联系人' },
|
||||
@ -32,6 +31,9 @@ module.exports = app => {
|
||||
app.model.Principal.hasMany(app.model.ComboProduct, { foreignKey: 'principal_id', as: 'comboProducts' });
|
||||
app.model.Principal.hasMany(app.model.Order, { foreignKey: 'principal_id', as: 'orders' });
|
||||
app.model.Principal.hasMany(app.model.PrincipalExternalApi, { foreignKey: 'principal_id', as: 'externalApis' });
|
||||
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' });
|
||||
};
|
||||
|
||||
return Principal;
|
||||
|
||||
@ -12,10 +12,19 @@ module.exports = app => {
|
||||
|
||||
// 注册、登录、邮箱验证码接口无需鉴权
|
||||
router.post('/api/auth/email-code', controller.auth.sendEmailCode);
|
||||
// 邮箱验证码登录:发送登录验证码 + 校验验证码直接登录(公开接口,无需登录)
|
||||
router.post('/api/auth/email-login/code', controller.auth.sendLoginCode);
|
||||
router.post('/api/auth/email-login', controller.auth.loginByEmailCode);
|
||||
// 忘记密码:发送 4 位重置验证码 + 校验验证码重置密码(公开接口,无需登录)
|
||||
router.post('/api/auth/reset-password/code', controller.auth.sendResetCode);
|
||||
router.post('/api/auth/reset-password', controller.auth.resetPasswordByCode);
|
||||
router.post('/api/auth/register', controller.auth.register);
|
||||
router.post('/api/auth/login', controller.auth.login);
|
||||
// 以下接口需要登录:请求头 Authorization: Bearer <token>
|
||||
router.get('/api/auth/profile', jwtAuth, controller.auth.profile);
|
||||
// 自助服务:修改当前登录用户自己的资料与密码,所有登录账号均可访问
|
||||
router.put('/api/auth/profile', jwtAuth, controller.auth.updateProfile);
|
||||
router.put('/api/auth/password', jwtAuth, controller.auth.changePassword);
|
||||
|
||||
// 菜单树需在 /api/menus/:id 之前注册,避免 tree 被当作 id 匹配
|
||||
router.get('/api/menus/tree', jwtAuth, controller.menu.tree);
|
||||
@ -26,13 +35,108 @@ module.exports = app => {
|
||||
|
||||
// RESTful 资源路由:index / show / create / update / destroy(均需鉴权)
|
||||
router.resources('users', '/api/users', jwtAuth, controller.user);
|
||||
// 头部主体切换下拉(带缓存),需在 /api/principals/:id 之前注册,避免 options 被当作 id 匹配
|
||||
router.get('/api/principals/options', jwtAuth, controller.principal.options);
|
||||
// 管理端主体列表(不缓存,保证分页与筛选实时)
|
||||
router.resources('principals', '/api/principals', jwtAuth, controller.principal);
|
||||
// 主体用户关联:需校验主体绑定关系
|
||||
router.resources('principalUsers', '/api/principal-users', jwtAuth, principalCheck({ model: 'PrincipalUser' }), controller.principalUser);
|
||||
// 邀请开通主体账号:创建新用户(随机密码)并绑定到指定主体
|
||||
router.post('/api/principal-users/invite', jwtAuth, principalCheck({ model: 'PrincipalUser' }), controller.principalUser.invite);
|
||||
// 商品快速搜索(聚合:商品编码/货品编码/条码/商品名称),需在 resources('products') 之前注册避免被 :id 误匹配
|
||||
router.get('/api/products/search', jwtAuth, principalCheck({ model: 'Product' }), controller.product.search);
|
||||
// 以下资源均归属某个主体,需做主体校验与数据隔离,防止跨主体操作
|
||||
router.resources('products', '/api/products', jwtAuth, principalCheck({ model: 'Product' }), controller.product);
|
||||
router.resources('comboProducts', '/api/combo-products', jwtAuth, principalCheck({ model: 'ComboProduct' }), controller.comboProduct);
|
||||
router.resources('menus', '/api/menus', jwtAuth, controller.menu);
|
||||
router.resources('principalExternalApis', '/api/principal-external-apis', jwtAuth, principalCheck({ model: 'PrincipalExternalApi' }), controller.principalExternalApi);
|
||||
// 仓库(仅基础信息)与仓库接口配置(一个仓库可有多条接口配置)
|
||||
router.get('/api/warehouses/select', jwtAuth, principalCheck({ model: 'Warehouse' }), controller.warehouse.select);
|
||||
// 仓库下的商品(是否已推送到该仓库):需在 resources('warehouses') 之前注册,避免 /products 被当作 :id
|
||||
router.get('/api/warehouses/:id/products', jwtAuth, principalCheck({ model: 'Warehouse' }), controller.warehouseProduct.index);
|
||||
// 仓库商品推送(商品资料推送到仓库 WMS):需在 resources('warehouses') 之前注册
|
||||
router.post('/api/warehouses/:id/products/push', jwtAuth, principalCheck({ model: 'Warehouse' }), controller.warehouseProduct.push);
|
||||
// 仓库商品 WMS 库存查询(按已推送商品的 WMS itemId 批量查询库存数量):需在 resources('warehouses') 之前注册
|
||||
router.post('/api/warehouses/:id/products/wms-inventory', jwtAuth, principalCheck({ model: 'Warehouse' }), controller.warehouseProduct.wmsInventory);
|
||||
// 库存同步:用外部 WMS 库存覆盖系统库存(差异以完成的出入库单平衡)
|
||||
router.post('/api/warehouses/:id/inventory/sync', jwtAuth, principalCheck({ model: 'Warehouse' }), controller.warehouseProduct.syncInventory);
|
||||
router.resources('warehouses', '/api/warehouses', jwtAuth, principalCheck({ model: 'Warehouse' }), controller.warehouse);
|
||||
// 仓库接口配置项:定义(硬编码)与配置项值分开维护,需在 resources('warehouse-apis') 之前注册
|
||||
router.get('/api/warehouse-api-fields', jwtAuth, controller.warehouseApiField.index);
|
||||
router.get('/api/warehouse-apis/:id/fields', jwtAuth, principalCheck({ model: 'WarehouseApi' }), controller.warehouseApiField.show);
|
||||
router.put('/api/warehouse-apis/:id/fields', jwtAuth, principalCheck({ model: 'WarehouseApi' }), controller.warehouseApiField.update);
|
||||
// 接口连通性测试(index.ping),需在 resources('warehouseApis') 之前注册
|
||||
router.post('/api/warehouse-apis/:id/test', jwtAuth, principalCheck({ model: 'WarehouseApi' }), controller.warehouseApi.test);
|
||||
router.resources('warehouseApis', '/api/warehouse-apis', jwtAuth, principalCheck({ model: 'WarehouseApi' }), controller.warehouseApi);
|
||||
// 对外 API 调用日志(OMS → 外部 WMS 的请求记录),按主体隔离(principal_id 由前端拦截器注入 query)
|
||||
router.get('/api/outbound-logs', jwtAuth, principalCheck(), controller.apiOutboundLog.index);
|
||||
// 订单整单解析需在 resources('orders') 之前注册,避免被 /api/orders/:id 误匹配
|
||||
router.post('/api/orders/:id/parse-items', jwtAuth, principalCheck({ model: 'Order' }), controller.order.parseItems);
|
||||
router.resources('orders', '/api/orders', jwtAuth, principalCheck({ model: 'Order' }), controller.order);
|
||||
// 订单明细(订单副表):详情解析需在 resources('orderItems') 之前注册
|
||||
router.post('/api/order-items/:id/parse', jwtAuth, principalCheck({ model: 'OrderItem' }), controller.orderItem.parse);
|
||||
router.resources('orderItems', '/api/order-items', jwtAuth, principalCheck({ model: 'OrderItem' }), controller.orderItem);
|
||||
// 店铺与店铺商品(采集的商品可绑定到系统商品或组合商品)
|
||||
router.resources('shops', '/api/shops', jwtAuth, principalCheck({ model: 'Shop' }), controller.shop);
|
||||
router.resources('shopProducts', '/api/shop-products', jwtAuth, principalCheck({ model: 'ShopProduct' }), controller.shopProduct);
|
||||
router.post('/api/shop-products/:id/bind', jwtAuth, principalCheck({ model: 'ShopProduct' }), controller.shopProduct.bind);
|
||||
// 出入库单与明细(明细共用 stock_items 表,以 bill_type 区分:1入库 2出库)
|
||||
// 单据状态由业务事务推动(审核/推送/完成/驳回/作废/取消/恢复),不提供直接修改状态的接口
|
||||
// 状态流转(按序校验):审核 / 推送 / 完成 / 取消 / 恢复 / 作废,需在 resources 之前注册避免被 :id 误匹配
|
||||
router.post('/api/inbound-orders/:id/audit', jwtAuth, principalCheck({ model: 'InboundOrder' }), controller.inboundOrder.audit);
|
||||
router.post('/api/inbound-orders/:id/push', jwtAuth, principalCheck({ model: 'InboundOrder' }), controller.inboundOrder.push);
|
||||
router.post('/api/inbound-orders/:id/complete', jwtAuth, principalCheck({ model: 'InboundOrder' }), controller.inboundOrder.complete);
|
||||
router.post('/api/inbound-orders/:id/cancel', jwtAuth, principalCheck({ model: 'InboundOrder' }), controller.inboundOrder.cancel);
|
||||
router.post('/api/inbound-orders/:id/restore', jwtAuth, principalCheck({ model: 'InboundOrder' }), controller.inboundOrder.restore);
|
||||
// 作废:已审核(2) 的单据只能作废(禁止删除),记录作废人/时间/原因
|
||||
router.post('/api/inbound-orders/:id/void', jwtAuth, principalCheck({ model: 'InboundOrder' }), controller.inboundOrder.voidOrder);
|
||||
// 驳回:已审核(2)/已推送(3) 且未完成,驳回后回到待处理(1);已推送的先走接口取消外部单据
|
||||
router.post('/api/inbound-orders/:id/reject', jwtAuth, principalCheck({ model: 'InboundOrder' }), controller.inboundOrder.reject);
|
||||
router.post('/api/outbound-orders/:id/audit', jwtAuth, principalCheck({ model: 'OutboundOrder' }), controller.outboundOrder.audit);
|
||||
router.post('/api/outbound-orders/:id/push', jwtAuth, principalCheck({ model: 'OutboundOrder' }), controller.outboundOrder.push);
|
||||
router.post('/api/outbound-orders/:id/complete', jwtAuth, principalCheck({ model: 'OutboundOrder' }), controller.outboundOrder.complete);
|
||||
router.post('/api/outbound-orders/:id/cancel', jwtAuth, principalCheck({ model: 'OutboundOrder' }), controller.outboundOrder.cancel);
|
||||
router.post('/api/outbound-orders/:id/restore', jwtAuth, principalCheck({ model: 'OutboundOrder' }), controller.outboundOrder.restore);
|
||||
router.post('/api/outbound-orders/:id/void', jwtAuth, principalCheck({ model: 'OutboundOrder' }), controller.outboundOrder.voidOrder);
|
||||
// 驳回:已审核(2)/已推送(3) 且未完成,驳回后回到待处理(1);已推送的先走接口取消外部单据
|
||||
router.post('/api/outbound-orders/:id/reject', jwtAuth, principalCheck({ model: 'OutboundOrder' }), controller.outboundOrder.reject);
|
||||
router.resources('inboundOrders', '/api/inbound-orders', jwtAuth, principalCheck({ model: 'InboundOrder' }), controller.inboundOrder);
|
||||
router.resources('outboundOrders', '/api/outbound-orders', jwtAuth, principalCheck({ model: 'OutboundOrder' }), controller.outboundOrder);
|
||||
router.resources('stockItems', '/api/stock-items', jwtAuth, principalCheck({ model: 'StockItem' }), controller.stockItem);
|
||||
// 快递公司字典(通用字典,不区分主体):下拉需在 resources 之前注册,避免 /select 被当作 :id
|
||||
router.get('/api/express-companies/select', jwtAuth, controller.expressCompany.select);
|
||||
router.resources('expressCompanies', '/api/express-companies', jwtAuth, controller.expressCompany);
|
||||
|
||||
// 收件人信息智能识别(通用能力,仅需登录):需在 resources 之前注册,避免被 /:id 误匹配
|
||||
router.post('/api/order-deliveries/parse-receiver', jwtAuth, controller.orderDelivery.parseReceiver);
|
||||
|
||||
// 批量切换发货仓库(按勾选 ids 或筛选条件;dry_run=true 仅预览影响范围)
|
||||
router.post('/api/order-deliveries/change-warehouse', jwtAuth, principalCheck({ model: 'OrderDelivery' }), controller.orderDelivery.changeWarehouse);
|
||||
// 发货单(订单):字段口径对齐 WMS 发货单(wms_order_delivery)与奇门 deliveryOrder,独立于出库单
|
||||
// 状态流转专用动作需在 resources 之前注册,避免被 /api/order-deliveries/:id 误匹配
|
||||
router.post('/api/order-deliveries/audit-batch', jwtAuth, principalCheck({ model: 'OrderDelivery' }), controller.orderDelivery.auditBatch);
|
||||
router.post('/api/order-deliveries/push-batch', jwtAuth, principalCheck({ model: 'OrderDelivery' }), controller.orderDelivery.pushBatch);
|
||||
router.post('/api/order-deliveries/:id/audit', jwtAuth, principalCheck({ model: 'OrderDelivery' }), controller.orderDelivery.audit);
|
||||
router.post('/api/order-deliveries/:id/push', jwtAuth, principalCheck({ model: 'OrderDelivery' }), controller.orderDelivery.push);
|
||||
router.post('/api/order-deliveries/:id/reject', jwtAuth, principalCheck({ model: 'OrderDelivery' }), controller.orderDelivery.reject);
|
||||
router.post('/api/order-deliveries/:id/cancel', jwtAuth, principalCheck({ model: 'OrderDelivery' }), controller.orderDelivery.cancel);
|
||||
router.post('/api/order-deliveries/:id/restore', jwtAuth, principalCheck({ model: 'OrderDelivery' }), controller.orderDelivery.restore);
|
||||
router.post('/api/order-deliveries/:id/void', jwtAuth, principalCheck({ model: 'OrderDelivery' }), controller.orderDelivery.voidOrder);
|
||||
router.resources('orderDeliveries', '/api/order-deliveries', jwtAuth, principalCheck({ model: 'OrderDelivery' }), controller.orderDelivery);
|
||||
// 发货单明细(子表商品明细,对应奇门 orderLines):明细锁定校验在控制器内按单据状态判断
|
||||
router.resources('orderDeliveryItems', '/api/order-delivery-items', jwtAuth, principalCheck({ model: 'OrderDeliveryItem' }), controller.orderDeliveryItem);
|
||||
|
||||
// 文件资源:check/upload 需登录并按主体隔离;raw 为公开读取(URL 含内容 hash,不可枚举)
|
||||
// raw 通配路由需在 resources('files') 之前注册,避免被 /api/files/:id 误匹配
|
||||
router.post('/api/files/check', jwtAuth, principalCheck(), controller.file.check);
|
||||
router.post('/api/files/upload', jwtAuth, principalCheck(), controller.file.upload);
|
||||
router.get('/api/files/raw/(.*)', controller.file.raw);
|
||||
router.resources('files', '/api/files', jwtAuth, principalCheck({ model: 'File' }), controller.file);
|
||||
|
||||
// WMS 出站通知回调(公开接口,无需登录):按 app_key 校验仓库接口配置 + MD5 签名校验
|
||||
router.post('/wms/notify', controller.wmsNotify.handle);
|
||||
|
||||
// 对外通用回调接口(公开接口,无需登录):外部系统以 method/app_key/v/timestamp/sign 调用,
|
||||
// 按 app_key 定位仓库接口配置与仓库后按 method 分发;协议与 WMS /openapi 对齐,已暴露 index.ping
|
||||
router.post('/openapi', controller.openapi.index);
|
||||
};
|
||||
|
||||
234
backend/app/service/cache.js
Normal file
234
backend/app/service/cache.js
Normal file
@ -0,0 +1,234 @@
|
||||
'use strict';
|
||||
|
||||
const { Service } = require('egg');
|
||||
|
||||
/** 业务缓存 key 统一前缀(与邮箱验证码 oms:email:* 区分) */
|
||||
const PREFIX = 'oms:cache';
|
||||
|
||||
/** 各类缓存的 key 构造器 */
|
||||
const KEYS = {
|
||||
user: userId => `${PREFIX}:user:${userId}`,
|
||||
userPrincipals: userId => `${PREFIX}:user-principals:${userId}`,
|
||||
principalOptions: userId => `${PREFIX}:principal-options:${userId}`,
|
||||
principal: principalId => `${PREFIX}:principal:${principalId}`,
|
||||
};
|
||||
|
||||
/**
|
||||
* 业务缓存服务
|
||||
* 缓存登录用户信息、用户可用主体列表、主体详情,避免高频请求反复查库。
|
||||
* Redis 异常时全部降级为直接查库(只告警不抛错),保证可用性。
|
||||
*/
|
||||
class CacheService extends Service {
|
||||
/** @return {Object} redis 客户端 */
|
||||
get redis() {
|
||||
return this.app.redis;
|
||||
}
|
||||
|
||||
/** @return {Object} 缓存有效期配置(秒) */
|
||||
get ttls() {
|
||||
return this.config.cache;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取缓存(Redis 异常时返回 null,降级为查库)
|
||||
* @param {String} key 缓存 key
|
||||
* @return {Promise<any>} 缓存值,不存在为 null
|
||||
*/
|
||||
async read(key) {
|
||||
try {
|
||||
const raw = await this.redis.get(key);
|
||||
return raw ? JSON.parse(raw) : null;
|
||||
} catch (err) {
|
||||
this.logger.warn(`[cache] 读取失败,key=${key}:${err.message}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入缓存(值为空时不写入,避免缓存穿透到空数据)
|
||||
* @param {String} key 缓存 key
|
||||
* @param {any} value 缓存值
|
||||
* @param {Number} ttl 有效秒数
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async write(key, value, ttl = 300) {
|
||||
if (value === null || value === undefined) return;
|
||||
try {
|
||||
await this.redis.set(key, JSON.stringify(value), 'EX', ttl);
|
||||
} catch (err) {
|
||||
this.logger.warn(`[cache] 写入失败,key=${key}:${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除若干 key
|
||||
* @param {Array<String>} keys 缓存 key 列表
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async forget(...keys) {
|
||||
const valid = keys.filter(Boolean);
|
||||
if (!valid.length) return;
|
||||
try {
|
||||
await this.redis.del(...valid);
|
||||
} catch (err) {
|
||||
this.logger.warn(`[cache] 删除失败,key=${valid.join(',')}:${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 按前缀批量删除(SCAN + DEL,用于“某类缓存全部失效”)
|
||||
* @param {String} prefix key 前缀
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async forgetByPrefix(prefix) {
|
||||
try {
|
||||
let cursor = '0';
|
||||
do {
|
||||
const [ next, keys ] = await this.redis.scan(cursor, 'MATCH', `${prefix}*`, 'COUNT', 200);
|
||||
cursor = next;
|
||||
if (keys && keys.length) await this.redis.del(...keys);
|
||||
} while (cursor !== '0');
|
||||
} catch (err) {
|
||||
this.logger.warn(`[cache] 按前缀删除失败,prefix=${prefix}:${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 缓存优先取值:命中直接返回,未命中执行 loader 查库并回写缓存
|
||||
* @param {String} key 缓存 key
|
||||
* @param {Number} ttl 有效秒数
|
||||
* @param {Function} loader 未命中时的数据加载函数
|
||||
* @return {Promise<any>} 数据
|
||||
*/
|
||||
async remember(key, ttl, loader) {
|
||||
const cached = await this.read(key);
|
||||
if (cached !== null) return cached;
|
||||
|
||||
const value = await loader();
|
||||
await this.write(key, value, ttl);
|
||||
return value;
|
||||
}
|
||||
|
||||
// ---------- 用户信息 ----------
|
||||
|
||||
/**
|
||||
* 登录用户信息(不含 password / salt)
|
||||
* @param {Number} userId 用户ID
|
||||
* @return {Promise<Object>} 用户信息,不存在为 null
|
||||
*/
|
||||
async getUser(userId) {
|
||||
return await this.remember(KEYS.user(userId), this.ttls.user, async () => {
|
||||
const user = await this.ctx.model.User.findByPk(userId, {
|
||||
attributes: { exclude: [ 'password', 'salt' ] },
|
||||
});
|
||||
return user ? user.toJSON() : null;
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- 用户与主体的关联 ----------
|
||||
|
||||
/**
|
||||
* 用户已绑定的主体ID列表(用于多租户数据隔离)
|
||||
* @param {Number} userId 用户ID
|
||||
* @return {Promise<Array<Number>>} 主体ID数组
|
||||
*/
|
||||
async getUserPrincipalIds(userId) {
|
||||
return await this.remember(KEYS.userPrincipals(userId), this.ttls.principal, async () => {
|
||||
const rows = await this.ctx.model.PrincipalUser.findAll({
|
||||
where: { user_id: userId },
|
||||
attributes: [ 'principal_id' ],
|
||||
});
|
||||
return rows.map(row => Number(row.principal_id));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户可选主体列表(头部主体切换/下拉选择用,含该主体下的角色与默认标识)
|
||||
* @param {Number} userId 用户ID
|
||||
* @return {Promise<Array<Object>>} 主体选项列表
|
||||
*/
|
||||
async getUserPrincipalOptions(userId) {
|
||||
return await this.remember(KEYS.principalOptions(userId), this.ttls.principalOptions, async () => {
|
||||
const relations = await this.ctx.model.PrincipalUser.findAll({
|
||||
where: { user_id: userId },
|
||||
attributes: [ 'id', 'principal_id', 'role', 'is_default', 'status' ],
|
||||
order: [[ 'is_default', 'DESC' ], [ 'id', 'ASC' ]],
|
||||
});
|
||||
if (!relations.length) return [];
|
||||
|
||||
const principals = await this.ctx.model.Principal.findAll({
|
||||
where: { id: relations.map(item => item.principal_id) },
|
||||
attributes: [ 'id', 'name', 'type', 'status', 'contact_name', 'contact_phone' ],
|
||||
});
|
||||
const principalMap = new Map(principals.map(item => [ Number(item.id), item ]));
|
||||
|
||||
return relations.map(item => {
|
||||
const principal = principalMap.get(Number(item.principal_id));
|
||||
if (!principal) return null;
|
||||
return {
|
||||
id: Number(principal.id),
|
||||
name: principal.name,
|
||||
type: principal.type,
|
||||
status: principal.status,
|
||||
contact_name: principal.contact_name,
|
||||
contact_phone: principal.contact_phone,
|
||||
role: item.role,
|
||||
is_default: item.is_default,
|
||||
relation_status: item.status,
|
||||
};
|
||||
}).filter(Boolean);
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- 主体信息 ----------
|
||||
|
||||
/**
|
||||
* 主体详情
|
||||
* @param {Number} principalId 主体ID
|
||||
* @return {Promise<Object>} 主体信息,不存在为 null
|
||||
*/
|
||||
async getPrincipal(principalId) {
|
||||
return await this.remember(KEYS.principal(principalId), this.ttls.principal, async () => {
|
||||
const principal = await this.ctx.model.Principal.findByPk(principalId);
|
||||
return principal ? principal.toJSON() : null;
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- 失效 ----------
|
||||
|
||||
/**
|
||||
* 用户资料/状态变更后失效:用户缓存 + 该用户的主体相关缓存
|
||||
* @param {Number} userId 用户ID
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async invalidateUser(userId) {
|
||||
await this.forget(
|
||||
KEYS.user(userId),
|
||||
KEYS.userPrincipals(userId),
|
||||
KEYS.principalOptions(userId)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户与主体的绑定关系变更后失效:主体ID列表 + 可选主体列表
|
||||
* @param {Number} userId 用户ID
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async invalidateUserPrincipals(userId) {
|
||||
await this.forget(KEYS.userPrincipals(userId), KEYS.principalOptions(userId));
|
||||
}
|
||||
|
||||
/**
|
||||
* 主体新增/更新/删除后失效:主体详情 + 所有依赖主体信息的缓存
|
||||
* (主体名称与状态变化会影响任意用户的可选主体列表,故按前缀整体失效)
|
||||
* @param {Number} principalId 主体ID
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async invalidatePrincipal(principalId) {
|
||||
await this.forget(KEYS.principal(principalId));
|
||||
await this.forgetByPrefix(`${PREFIX}:principal-options:`);
|
||||
await this.forgetByPrefix(`${PREFIX}:user-principals:`);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = CacheService;
|
||||
@ -3,6 +3,7 @@
|
||||
// 加载项目根目录 .env(敏感配置不入库);文件不存在时自动忽略
|
||||
require('dotenv').config();
|
||||
|
||||
const path = require('path');
|
||||
const db = require('../database/config').development;
|
||||
|
||||
/**
|
||||
@ -25,8 +26,30 @@ module.exports = appInfo => {
|
||||
config.requestLog = {
|
||||
keepDays: Number(process.env.REQUEST_LOG_KEEP_DAYS || 60),
|
||||
maxBodyLength: Number(process.env.REQUEST_LOG_MAX_BODY || 2000),
|
||||
// 不记录的路径前缀(Swagger 静态资源等)
|
||||
excludePaths: [ '/swagger' ],
|
||||
// 不记录的路径前缀(Swagger 静态资源、图片读取等)
|
||||
excludePaths: [ '/swagger', '/api/files/raw' ],
|
||||
};
|
||||
|
||||
// 文件上传:使用 file 模式(先落临时文件再由控制器处理),仅允许图片
|
||||
config.multipart = {
|
||||
mode: 'file',
|
||||
fileSize: '20mb',
|
||||
files: 10,
|
||||
whitelist: [ '.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg' ],
|
||||
};
|
||||
|
||||
// 文件资源存储:按「主体ID/年/月/日」分层,由上传时间决定(见 app/controller/file.js)
|
||||
config.upload = {
|
||||
dir: process.env.UPLOAD_DIR || path.join(appInfo.baseDir, 'uploads'),
|
||||
// 访问前缀,与 router.js 中 /api/files/raw 保持一致
|
||||
urlPrefix: '/api/files/raw',
|
||||
};
|
||||
|
||||
// 对外通用回调接口(POST /openapi):展示给外部系统配置的回调服务地址前缀
|
||||
// 未配置时按请求访问地址(ctx.protocol + ctx.host)动态生成,便于本地联调;
|
||||
// 部署在网关/Nginx 后请用 OMS_CALLBACK_BASE_URL 指定对外可访问的地址
|
||||
config.omsCallback = {
|
||||
baseUrl: (process.env.OMS_CALLBACK_BASE_URL || '').replace(/\/+$/, ''),
|
||||
};
|
||||
|
||||
// close csrf for easy debugging, please enable it in production if needed
|
||||
@ -65,6 +88,14 @@ module.exports = appInfo => {
|
||||
from: process.env.SMTP_FROM || 'noreply@oms.local',
|
||||
};
|
||||
|
||||
// AI 智能识别(收件人信息解析):与 WMS 复用同一套配置
|
||||
// 配置项与 WMS 保持一致(config.deepseek = { apiKey, baseUrl }),密钥走 .env 的 DEEPSEEK_API_KEY
|
||||
// 未配置 apiKey 时相关接口返回 400 并提示配置,不影响其它功能
|
||||
config.deepseek = {
|
||||
apiKey: process.env.DEEPSEEK_API_KEY || '',
|
||||
baseUrl: 'https://api.deepseek.com',
|
||||
};
|
||||
|
||||
// Redis 配置:缓存邮箱验证码等数据,敏感信息建议用环境变量覆盖
|
||||
config.redis = {
|
||||
client: {
|
||||
@ -75,6 +106,14 @@ module.exports = appInfo => {
|
||||
},
|
||||
};
|
||||
|
||||
// 业务缓存有效期(秒):用户信息、主体信息、可选主体列表
|
||||
// 主体/用户发生新增或更新时,相关缓存会被主动失效,这里的 TTL 仅作为兜底
|
||||
config.cache = {
|
||||
user: Number(process.env.CACHE_TTL_USER || 600),
|
||||
principal: Number(process.env.CACHE_TTL_PRINCIPAL || 600),
|
||||
principalOptions: Number(process.env.CACHE_TTL_PRINCIPAL_OPTIONS || 600),
|
||||
};
|
||||
|
||||
// 邮箱验证码限流:同一邮箱发送间隔(秒)与每日发送上限
|
||||
config.emailCode = {
|
||||
interval: Number(process.env.EMAIL_CODE_INTERVAL || 60),
|
||||
|
||||
@ -0,0 +1,23 @@
|
||||
'use strict';
|
||||
|
||||
/** 6.1 菜单表补充 component 字段:用于前端动态路由映射到具体页面组件 */
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
const exists = await queryInterface
|
||||
.describeTable('menus')
|
||||
.then((cols) => Boolean(cols.component))
|
||||
.catch(() => false);
|
||||
|
||||
if (exists) return;
|
||||
|
||||
await queryInterface.addColumn('menus', 'component', {
|
||||
type: Sequelize.STRING(200),
|
||||
allowNull: true,
|
||||
comment: '前端组件路径,如 views/system/user/index.vue',
|
||||
});
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.removeColumn('menus', 'component');
|
||||
},
|
||||
};
|
||||
87
backend/database/migrations/20260909000700-seed-menus.js
Normal file
87
backend/database/migrations/20260909000700-seed-menus.js
Normal file
@ -0,0 +1,87 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 7. 种子菜单:依据后端已有功能模块设计菜单树,供前端通过 /api/menus/tree 拉取并动态生成侧边栏与路由。
|
||||
* 菜单 component 字段指向前端 views 下的页面(默认统一指向 views/Generic.vue 占位页)。
|
||||
* 仅在 menus 表为空时插入,避免重复。
|
||||
*/
|
||||
const seedMenus = [
|
||||
{
|
||||
name: '仪表盘', type: 2, path: '/dashboard', icon: 'HomeFilled',
|
||||
component: 'views/Home.vue', sort: 100,
|
||||
},
|
||||
{
|
||||
name: '系统管理', type: 1, icon: 'Setting', sort: 90,
|
||||
children: [
|
||||
{ name: '用户管理', type: 2, path: '/system/user', icon: 'User', permission: 'user:list', component: 'views/Generic.vue', sort: 90 },
|
||||
{ name: '主体管理', type: 2, path: '/system/principal', icon: 'OfficeBuilding', permission: 'principal:list', component: 'views/Principal/Index.vue', sort: 80 },
|
||||
{ name: '主体用户', type: 2, path: '/system/principal-user', icon: 'Connection', permission: 'principalUser:list', component: 'views/Generic.vue', sort: 70 },
|
||||
{ name: '菜单管理', type: 2, path: '/system/menu', icon: 'Menu', permission: 'menu:list', component: 'views/Generic.vue', sort: 60 },
|
||||
{ name: '外部API', type: 2, path: '/system/external-api', icon: 'Link', permission: 'principalExternalApi:list', component: 'views/Generic.vue', sort: 50 },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: '商品管理', type: 1, icon: 'Goods', sort: 80,
|
||||
children: [
|
||||
{ name: '商品', type: 2, path: '/product', icon: 'Box', permission: 'product:list', component: 'views/Generic.vue', sort: 80 },
|
||||
{ name: '组合商品', type: 2, path: '/combo-product', icon: 'Files', permission: 'comboProduct:list', component: 'views/Generic.vue', sort: 70 },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: '订单管理', type: 1, icon: 'List', sort: 70,
|
||||
children: [
|
||||
{ name: '订单', type: 2, path: '/order', icon: 'Tickets', permission: 'order:list', component: 'views/Generic.vue', sort: 70 },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
const sequelize = queryInterface.sequelize;
|
||||
|
||||
const [rows] = await sequelize.query('SELECT COUNT(*) AS count FROM menus', {
|
||||
type: sequelize.QueryTypes.SELECT,
|
||||
});
|
||||
if (Number(rows.count) > 0) return; // 已存在菜单数据,跳过种子
|
||||
|
||||
async function insertMenu(m, parentId) {
|
||||
await sequelize.query(
|
||||
`INSERT INTO menus
|
||||
(parent_id, name, type, path, icon, permission, component, sort, status, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`,
|
||||
{
|
||||
replacements: [
|
||||
parentId,
|
||||
m.name,
|
||||
m.type,
|
||||
m.path || null,
|
||||
m.icon || null,
|
||||
m.permission || null,
|
||||
m.component || null,
|
||||
m.sort || 0,
|
||||
1,
|
||||
],
|
||||
}
|
||||
);
|
||||
const [idRows] = await sequelize.query('SELECT LAST_INSERT_ID() AS id', {
|
||||
type: sequelize.QueryTypes.SELECT,
|
||||
});
|
||||
return Number(idRows.id);
|
||||
}
|
||||
|
||||
async function insertTree(list, parentId) {
|
||||
for (const m of list) {
|
||||
const id = await insertMenu(m, parentId);
|
||||
if (m.children && m.children.length) {
|
||||
await insertTree(m.children, id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await insertTree(seedMenus, 0);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.sequelize.query('DELETE FROM menus');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,34 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 将已存在的“主体管理”菜单 component 由占位页 views/Generic.vue
|
||||
* 修正为真实页面 views/Principal/Index.vue(前端已实现主体列表管理页)。
|
||||
* 幂等:仅当 component 仍为占位页时才更新。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
const sequelize = queryInterface.sequelize;
|
||||
await sequelize.query(
|
||||
`UPDATE menus SET component = ?
|
||||
WHERE name = ? AND path = ? AND type = 2 AND component = ?`,
|
||||
{
|
||||
replacements: [
|
||||
'views/Principal/Index.vue',
|
||||
'主体管理',
|
||||
'/system/principal',
|
||||
'views/Generic.vue',
|
||||
],
|
||||
}
|
||||
);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
const sequelize = queryInterface.sequelize;
|
||||
await sequelize.query(
|
||||
`UPDATE menus SET component = ? WHERE name = ? AND path = ? AND type = 2`,
|
||||
{
|
||||
replacements: ['views/Generic.vue', '主体管理', '/system/principal'],
|
||||
}
|
||||
);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,18 @@
|
||||
'use strict';
|
||||
|
||||
/** 移除主体编码字段(code)及其唯一索引 */
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
await queryInterface.removeIndex('principals', 'uk_principals_code');
|
||||
await queryInterface.removeColumn('principals', 'code');
|
||||
},
|
||||
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.addColumn('principals', 'code', {
|
||||
type: Sequelize.STRING(50),
|
||||
allowNull: false,
|
||||
comment: '主体编码',
|
||||
});
|
||||
await queryInterface.addIndex('principals', { fields: [ 'code' ], unique: true, name: 'uk_principals_code' });
|
||||
},
|
||||
};
|
||||
51
backend/database/migrations/20260909000900-adjust-menus.js
Normal file
51
backend/database/migrations/20260909000900-adjust-menus.js
Normal file
@ -0,0 +1,51 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 调整菜单顺序:订单管理置顶(sort 100),系统管理置底(sort 70);
|
||||
* 并将“主体用户”菜单由占位页 views/Generic.vue 指向真实页面 views/PrincipalUser/Index.vue。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
const sequelize = queryInterface.sequelize;
|
||||
// 根菜单(parent_id=0,含目录与仪表盘这种根级菜单)重排:订单管理第一、系统管理最后
|
||||
await sequelize.query(
|
||||
`UPDATE menus SET sort = CASE name
|
||||
WHEN '订单管理' THEN 100
|
||||
WHEN '商品管理' THEN 90
|
||||
WHEN '仪表盘' THEN 80
|
||||
WHEN '系统管理' THEN 70
|
||||
ELSE sort END
|
||||
WHERE parent_id = 0`,
|
||||
);
|
||||
// 主体用户菜单指向真实页面(仅当仍指向占位页时更新,幂等)
|
||||
await sequelize.query(
|
||||
`UPDATE menus SET component = ?
|
||||
WHERE name = ? AND path = ? AND type = 2 AND component = ?`,
|
||||
{
|
||||
replacements: [
|
||||
'views/PrincipalUser/Index.vue',
|
||||
'主体用户',
|
||||
'/system/principal-user',
|
||||
'views/Generic.vue',
|
||||
],
|
||||
},
|
||||
);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
const sequelize = queryInterface.sequelize;
|
||||
await sequelize.query(
|
||||
`UPDATE menus SET sort = CASE name
|
||||
WHEN '订单管理' THEN 70
|
||||
WHEN '商品管理' THEN 80
|
||||
WHEN '仪表盘' THEN 100
|
||||
WHEN '系统管理' THEN 90
|
||||
ELSE sort END
|
||||
WHERE parent_id = 0`,
|
||||
);
|
||||
await sequelize.query(
|
||||
`UPDATE menus SET component = ? WHERE name = ? AND path = ? AND type = 2`,
|
||||
{ replacements: ['views/Generic.vue', '主体用户', '/system/principal-user'] },
|
||||
);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,22 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 菜单改名:系统管理下的“主体用户”改为“账号”。
|
||||
* 仅修改展示名,path 与 component 保持不变;内部标识(principal_users 表、
|
||||
* PrincipalUser 模型与 /api/principal-users 接口)不受影响。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE menus SET name = ? WHERE name = ? AND path = ? AND type = 2`,
|
||||
{ replacements: ['账号', '主体用户', '/system/principal-user'] },
|
||||
);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE menus SET name = ? WHERE name = ? AND path = ? AND type = 2`,
|
||||
{ replacements: ['主体用户', '账号', '/system/principal-user'] },
|
||||
);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,42 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 移除侧边栏「系统管理 → 菜单管理」菜单项。
|
||||
* 注意:仅删除菜单记录,后端 /api/menus 接口(尤其 /api/menus/tree)必须保留,
|
||||
* 它是前端动态菜单与路由的数据来源。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
await queryInterface.sequelize.query(
|
||||
`DELETE FROM menus WHERE name = ? AND path = ? AND type = 2`,
|
||||
{ replacements: ['菜单管理', '/system/menu'] },
|
||||
);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
const sequelize = queryInterface.sequelize;
|
||||
// 回滚时重新挂回「系统管理」目录下
|
||||
const [parent] = await sequelize.query(
|
||||
`SELECT id FROM menus WHERE name = ? AND parent_id = 0 AND type = 1 LIMIT 1`,
|
||||
{ replacements: ['系统管理'], type: sequelize.QueryTypes.SELECT },
|
||||
);
|
||||
if (!parent) return;
|
||||
|
||||
await sequelize.query(
|
||||
`INSERT INTO menus
|
||||
(parent_id, name, type, path, icon, permission, component, sort, status, created_at, updated_at)
|
||||
VALUES (?, ?, 2, ?, ?, ?, ?, ?, 1, NOW(), NOW())`,
|
||||
{
|
||||
replacements: [
|
||||
parent.id,
|
||||
'菜单管理',
|
||||
'/system/menu',
|
||||
'Menu',
|
||||
'menu:list',
|
||||
'views/Generic.vue',
|
||||
60,
|
||||
],
|
||||
},
|
||||
);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,22 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 菜单改名:系统管理下的「外部API」改为「外部仓库」。
|
||||
* 仅修改展示名,path、权限标识与组件保持不变;
|
||||
* 后端模块 principal_external_apis 与 /api/principal-external-apis 接口不受影响。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE menus SET name = ? WHERE name = ? AND path = ? AND type = 2`,
|
||||
{ replacements: ['外部仓库', '外部API', '/system/external-api'] },
|
||||
);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE menus SET name = ? WHERE name = ? AND path = ? AND type = 2`,
|
||||
{ replacements: ['外部API', '外部仓库', '/system/external-api'] },
|
||||
);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,30 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 将「外部仓库」由「系统管理」的子菜单提升为独立根菜单(parent_id = 0)。
|
||||
* sort 设为 75:排在仪表盘(80)之后、系统管理(70)之前,
|
||||
* 从而保持「订单管理第一、系统管理最后」的整体顺序。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE menus SET parent_id = 0, sort = 75 WHERE name = ? AND path = ? AND type = 2`,
|
||||
{ replacements: ['外部仓库', '/system/external-api'] },
|
||||
);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
const sequelize = queryInterface.sequelize;
|
||||
// 回滚:重新挂回「系统管理」目录下,恢复原排序
|
||||
const [parent] = await sequelize.query(
|
||||
`SELECT id FROM menus WHERE name = ? AND parent_id = 0 AND type = 1 LIMIT 1`,
|
||||
{ replacements: ['系统管理'], type: sequelize.QueryTypes.SELECT },
|
||||
);
|
||||
if (!parent) return;
|
||||
|
||||
await sequelize.query(
|
||||
`UPDATE menus SET parent_id = ?, sort = 50 WHERE name = ? AND path = ? AND type = 2`,
|
||||
{ replacements: [parent.id, '外部仓库', '/system/external-api'] },
|
||||
);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,33 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 菜单顺序调整:仪表盘固定在第一位,系统管理保持最后一位。
|
||||
* 根菜单排序(sort DESC):仪表盘 100 > 订单管理 90 > 商品管理 80 > 外部仓库 75 > 系统管理 70。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE menus SET sort = CASE name
|
||||
WHEN '仪表盘' THEN 100
|
||||
WHEN '订单管理' THEN 90
|
||||
WHEN '商品管理' THEN 80
|
||||
WHEN '外部仓库' THEN 75
|
||||
WHEN '系统管理' THEN 70
|
||||
ELSE sort END
|
||||
WHERE parent_id = 0`,
|
||||
);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE menus SET sort = CASE name
|
||||
WHEN '仪表盘' THEN 80
|
||||
WHEN '订单管理' THEN 100
|
||||
WHEN '商品管理' THEN 90
|
||||
WHEN '外部仓库' THEN 75
|
||||
WHEN '系统管理' THEN 70
|
||||
ELSE sort END
|
||||
WHERE parent_id = 0`,
|
||||
);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,29 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 将「用户管理」菜单由占位页 views/Generic.vue
|
||||
* 指向真实页面 views/User/Index.vue(前端已实现用户管理页:列表/修改资料/修改密码)。
|
||||
* 幂等:仅当 component 仍为占位页时才更新。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE menus SET component = ? WHERE name = ? AND path = ? AND type = 2 AND component = ?`,
|
||||
{
|
||||
replacements: [
|
||||
'views/User/Index.vue',
|
||||
'用户管理',
|
||||
'/system/user',
|
||||
'views/Generic.vue',
|
||||
],
|
||||
},
|
||||
);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE menus SET component = ? WHERE name = ? AND path = ? AND type = 2`,
|
||||
{ replacements: ['views/Generic.vue', '用户管理', '/system/user'] },
|
||||
);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,41 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 「用户管理」改为「我的」:自助的个人中心页(修改自己的资料 / 修改自己的密码),
|
||||
* 不再管理全部用户。
|
||||
* - name: 用户管理 -> 我的
|
||||
* - component: views/User/Profile.vue
|
||||
* - permission: 置空,所有登录账号均可见(前端未做权限拦截,仅作标记)
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE menus SET name = ?, component = ?, permission = NULL
|
||||
WHERE name = ? AND path = ? AND type = 2`,
|
||||
{
|
||||
replacements: [
|
||||
'我的',
|
||||
'views/User/Profile.vue',
|
||||
'用户管理',
|
||||
'/system/user',
|
||||
],
|
||||
},
|
||||
);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE menus SET name = ?, component = ?, permission = ?
|
||||
WHERE name = ? AND path = ? AND type = 2`,
|
||||
{
|
||||
replacements: [
|
||||
'用户管理',
|
||||
'views/User/Index.vue',
|
||||
'user:list',
|
||||
'我的',
|
||||
'/system/user',
|
||||
],
|
||||
},
|
||||
);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,29 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 将「外部仓库」菜单由占位页 views/Generic.vue
|
||||
* 指向真实页面 views/ExternalApi/Index.vue(前端已实现外部仓库配置管理页)。
|
||||
* 幂等:仅当 component 仍为占位页时才更新。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE menus SET component = ? WHERE name = ? AND path = ? AND type = 2 AND component = ?`,
|
||||
{
|
||||
replacements: [
|
||||
'views/ExternalApi/Index.vue',
|
||||
'外部仓库',
|
||||
'/system/external-api',
|
||||
'views/Generic.vue',
|
||||
],
|
||||
},
|
||||
);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE menus SET component = ? WHERE name = ? AND path = ? AND type = 2`,
|
||||
{ replacements: ['views/Generic.vue', '外部仓库', '/system/external-api'] },
|
||||
);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,39 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 将「商品管理」下的「商品」「组合商品」菜单由占位页 views/Generic.vue
|
||||
* 分别指向真实页面 views/Product/Index.vue 与 views/ComboProduct/Index.vue。
|
||||
* 幂等:仅当 component 仍为占位页时才更新。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE menus SET component = ? WHERE name = ? AND path = ? AND type = 2 AND component = ?`,
|
||||
{
|
||||
replacements: ['views/Product/Index.vue', '商品', '/product', 'views/Generic.vue'],
|
||||
},
|
||||
);
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE menus SET component = ? WHERE name = ? AND path = ? AND type = 2 AND component = ?`,
|
||||
{
|
||||
replacements: [
|
||||
'views/ComboProduct/Index.vue',
|
||||
'组合商品',
|
||||
'/combo-product',
|
||||
'views/Generic.vue',
|
||||
],
|
||||
},
|
||||
);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE menus SET component = ? WHERE name = ? AND path = ? AND type = 2`,
|
||||
{ replacements: ['views/Generic.vue', '商品', '/product'] },
|
||||
);
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE menus SET component = ? WHERE name = ? AND path = ? AND type = 2`,
|
||||
{ replacements: ['views/Generic.vue', '组合商品', '/combo-product'] },
|
||||
);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,24 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 将「订单管理 → 订单」菜单由占位页 views/Generic.vue
|
||||
* 指向真实页面 views/Order/Index.vue(前端已实现订单列表/编辑/状态流转)。
|
||||
* 幂等:仅当 component 仍为占位页时才更新。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE menus SET component = ? WHERE name = ? AND path = ? AND type = 2 AND component = ?`,
|
||||
{
|
||||
replacements: ['views/Order/Index.vue', '订单', '/order', 'views/Generic.vue'],
|
||||
},
|
||||
);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE menus SET component = ? WHERE name = ? AND path = ? AND type = 2`,
|
||||
{ replacements: ['views/Generic.vue', '订单', '/order'] },
|
||||
);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,86 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 13. 新增「店铺管理」菜单(店铺页面)。「店铺商品」菜单见后续迁移,挂在「商品管理」下。
|
||||
* 按 name 判重,重复执行不会插入多条。
|
||||
*/
|
||||
const menus = [
|
||||
{
|
||||
name: '店铺管理',
|
||||
type: 1,
|
||||
icon: 'Shop',
|
||||
sort: 85,
|
||||
children: [
|
||||
{
|
||||
name: '店铺',
|
||||
type: 2,
|
||||
path: '/shop',
|
||||
icon: 'Shop',
|
||||
permission: 'shop:list',
|
||||
component: 'views/Shop/Index.vue',
|
||||
sort: 80,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
const sequelize = queryInterface.sequelize;
|
||||
|
||||
async function findMenu(name, parentId) {
|
||||
const [ rows ] = await sequelize.query(
|
||||
'SELECT id FROM menus WHERE name = ? AND parent_id = ? LIMIT 1',
|
||||
{ replacements: [ name, parentId ], type: sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
return rows ? Number(rows.id) : null;
|
||||
}
|
||||
|
||||
async function insertMenu(m, parentId) {
|
||||
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,
|
||||
m.name,
|
||||
m.type,
|
||||
m.path || null,
|
||||
m.icon || null,
|
||||
m.permission || null,
|
||||
m.component || null,
|
||||
m.sort || 0,
|
||||
],
|
||||
}
|
||||
);
|
||||
const [ idRows ] = await sequelize.query('SELECT LAST_INSERT_ID() AS id', {
|
||||
type: sequelize.QueryTypes.SELECT,
|
||||
});
|
||||
return Number(idRows.id);
|
||||
}
|
||||
|
||||
async function upsertTree(list, parentId) {
|
||||
for (const m of list) {
|
||||
let id = await findMenu(m.name, parentId);
|
||||
if (!id) id = await insertMenu(m, parentId);
|
||||
if (m.children && m.children.length) await upsertTree(m.children, id);
|
||||
}
|
||||
}
|
||||
|
||||
await upsertTree(menus, 0);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
const sequelize = queryInterface.sequelize;
|
||||
const [ rows ] = await sequelize.query(
|
||||
"SELECT id FROM menus WHERE name = '店铺管理' AND parent_id = 0 LIMIT 1",
|
||||
{ type: sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
if (!rows) return;
|
||||
|
||||
await sequelize.query('DELETE FROM menus WHERE parent_id = ? OR id = ?', {
|
||||
replacements: [ Number(rows.id), Number(rows.id) ],
|
||||
});
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,52 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 14. 将「店铺商品」菜单挂在「商品管理」下(与商品、组合商品并列)。
|
||||
* 兼容两种情况:全新库(尚未插入)或已有库(曾挂在店铺管理下,需移动到商品管理)。
|
||||
* 按 name 定位节点,幂等可重跑。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
const sequelize = queryInterface.sequelize;
|
||||
|
||||
const [ goods ] = await sequelize.query(
|
||||
"SELECT id FROM menus WHERE name = '商品管理' AND parent_id = 0 LIMIT 1",
|
||||
{ type: sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
if (!goods) return; // 商品管理节点不存在则跳过(理论上不应发生)
|
||||
const goodsId = Number(goods.id);
|
||||
|
||||
const [ exist ] = await sequelize.query(
|
||||
"SELECT id, parent_id FROM menus WHERE name = '店铺商品' LIMIT 1",
|
||||
{ type: sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
|
||||
if (exist) {
|
||||
if (Number(exist.parent_id) === goodsId) return; // 已正确挂接,无需处理
|
||||
await sequelize.query(
|
||||
'UPDATE menus SET parent_id = ?, sort = ? WHERE id = ?',
|
||||
{ replacements: [ goodsId, 65, Number(exist.id) ] }
|
||||
);
|
||||
} else {
|
||||
await sequelize.query(
|
||||
`INSERT INTO menus
|
||||
(parent_id, name, type, path, icon, permission, component, sort, status, created_at, updated_at)
|
||||
VALUES (?, '店铺商品', 2, '/shop-product', 'GoodsFilled', 'shopProduct:list', 'views/ShopProduct/Index.vue', 65, 1, NOW(), NOW())`,
|
||||
{ replacements: [ goodsId ] }
|
||||
);
|
||||
}
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
const sequelize = queryInterface.sequelize;
|
||||
const [ goods ] = await sequelize.query(
|
||||
"SELECT id FROM menus WHERE name = '商品管理' AND parent_id = 0 LIMIT 1",
|
||||
{ type: sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
if (!goods) return;
|
||||
await sequelize.query(
|
||||
"DELETE FROM menus WHERE name = '店铺商品' AND parent_id = ?",
|
||||
{ replacements: [ Number(goods.id) ] }
|
||||
);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,95 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 24. 新增「库存管理」菜单:入库单、出库单两个页面(component 指向前端 views)。
|
||||
* 按 name + parent_id 判重,重复执行不会插入多条。
|
||||
*/
|
||||
const menus = [
|
||||
{
|
||||
name: '库存管理',
|
||||
type: 1,
|
||||
icon: 'Box',
|
||||
sort: 82,
|
||||
children: [
|
||||
{
|
||||
name: '入库单',
|
||||
type: 2,
|
||||
path: '/inbound-order',
|
||||
icon: 'Bottom',
|
||||
permission: 'inboundOrder:list',
|
||||
component: 'views/InboundOrder/Index.vue',
|
||||
sort: 75,
|
||||
},
|
||||
{
|
||||
name: '出库单',
|
||||
type: 2,
|
||||
path: '/outbound-order',
|
||||
icon: 'Top',
|
||||
permission: 'outboundOrder:list',
|
||||
component: 'views/OutboundOrder/Index.vue',
|
||||
sort: 70,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
const sequelize = queryInterface.sequelize;
|
||||
|
||||
async function findMenu(name, parentId) {
|
||||
const [ rows ] = await sequelize.query(
|
||||
'SELECT id FROM menus WHERE name = ? AND parent_id = ? LIMIT 1',
|
||||
{ replacements: [ name, parentId ], type: sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
return rows ? Number(rows.id) : null;
|
||||
}
|
||||
|
||||
async function insertMenu(m, parentId) {
|
||||
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,
|
||||
m.name,
|
||||
m.type,
|
||||
m.path || null,
|
||||
m.icon || null,
|
||||
m.permission || null,
|
||||
m.component || null,
|
||||
m.sort || 0,
|
||||
],
|
||||
}
|
||||
);
|
||||
const [ idRows ] = await sequelize.query('SELECT LAST_INSERT_ID() AS id', {
|
||||
type: sequelize.QueryTypes.SELECT,
|
||||
});
|
||||
return Number(idRows.id);
|
||||
}
|
||||
|
||||
async function upsertTree(list, parentId) {
|
||||
for (const m of list) {
|
||||
let id = await findMenu(m.name, parentId);
|
||||
if (!id) id = await insertMenu(m, parentId);
|
||||
if (m.children && m.children.length) await upsertTree(m.children, id);
|
||||
}
|
||||
}
|
||||
|
||||
await upsertTree(menus, 0);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
const sequelize = queryInterface.sequelize;
|
||||
const [ rows ] = await sequelize.query(
|
||||
"SELECT id FROM menus WHERE name = '库存管理' AND parent_id = 0 LIMIT 1",
|
||||
{ type: sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
if (!rows) return;
|
||||
|
||||
await sequelize.query('DELETE FROM menus WHERE parent_id = ? OR id = ?', {
|
||||
replacements: [ Number(rows.id), Number(rows.id) ],
|
||||
});
|
||||
},
|
||||
};
|
||||
47
backend/database/migrations/20260911000100-create-files.js
Normal file
47
backend/database/migrations/20260911000100-create-files.js
Normal file
@ -0,0 +1,47 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 文件资源表 files:
|
||||
* 1) 记录上传文件的大小、原始名称、内容 hash 与存储路径,便于按 hash 去重与审计
|
||||
* 2) 文件按主体区分:同一主体下 hash 唯一(uk_files_principal_hash),不同主体互不影响
|
||||
* 3) 磁盘目录按「主体ID/年/月/日」分层,由上传时间决定(见 app/controller/file.js)
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.createTable(
|
||||
'files',
|
||||
{
|
||||
id: { type: Sequelize.BIGINT.UNSIGNED, autoIncrement: true, primaryKey: true, comment: '主键' },
|
||||
principal_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '所属主体ID',
|
||||
references: { model: 'principals', key: 'id' },
|
||||
onDelete: 'CASCADE',
|
||||
},
|
||||
hash: { type: Sequelize.STRING(64), allowNull: false, comment: '文件内容 SHA256,用于去重' },
|
||||
name: { type: Sequelize.STRING(255), allowNull: false, comment: '原始文件名' },
|
||||
ext: { type: Sequelize.STRING(20), allowNull: false, comment: '扩展名(小写,含点,如 .png)' },
|
||||
mime: { type: Sequelize.STRING(100), comment: 'MIME 类型' },
|
||||
size: { type: Sequelize.INTEGER.UNSIGNED, allowNull: false, defaultValue: 0, comment: '文件大小(字节)' },
|
||||
path: { type: Sequelize.STRING(255), allowNull: false, comment: '相对存储路径:主体ID/年/月/日/hash.ext' },
|
||||
url: { type: Sequelize.STRING(500), allowNull: false, comment: '访问地址' },
|
||||
deleted_at: { type: Sequelize.DATE, 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: '文件资源' }
|
||||
);
|
||||
|
||||
// 主体内按内容去重:同一份文件重复上传时直接复用已有记录与 URL
|
||||
await queryInterface.addIndex('files', {
|
||||
fields: [ 'principal_id', 'hash' ],
|
||||
unique: true,
|
||||
name: 'uk_files_principal_hash',
|
||||
});
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.dropTable('files');
|
||||
},
|
||||
};
|
||||
Loading…
x
Reference in New Issue
Block a user