feat: 收件任务体系(return_received_task)与退回权限调整
- 新增收件任务表 wms_return_received_task(自增 id 从 10000 起、批次号服务端自动生成 RT+日期+序号) - 系统预设 id=1 历史收件;收件登记 wms_return_received 增加 return_received_task_id(缓存校验,未命中穿透建缓存) - 任务接口:create/list/batchDelete/delete(有登记不可删、跨仓保护、has_register 筛选、register_count 统计) - 移除 returnwaybill/returnReceived/returnUnpack 页面权限及角色组引用;权限标题「运单退回登记」改「未退登记」
This commit is contained in:
parent
5cd1479a92
commit
6ac3441109
@ -55,6 +55,12 @@ module.exports = app => {
|
||||
allowNull: true,
|
||||
comment: '货主ID,原单退回时回填,用于查货主备注 wms_store_warehouse.store_remask',
|
||||
},
|
||||
return_received_task_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '收件任务ID,关联 wms_return_received_task.id;默认 1=系统预设「历史收件」',
|
||||
},
|
||||
remark: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
@ -80,6 +86,7 @@ module.exports = app => {
|
||||
{ name: 'idx_scanner_id', fields: [ 'scanner_id' ] },
|
||||
{ name: 'idx_order_express_id', fields: [ 'order_express_id' ] },
|
||||
{ name: 'idx_store_id', fields: [ 'store_id' ] },
|
||||
{ name: 'idx_return_received_task_id', fields: [ 'return_received_task_id' ] },
|
||||
],
|
||||
});
|
||||
|
||||
|
||||
70
app/model/return_received_task.js
Normal file
70
app/model/return_received_task.js
Normal file
@ -0,0 +1,70 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 收件任务 Model(退回收件任务分组)。
|
||||
* 记录批次号、仓库ID、创建人、创建时间;主键 id 自增从 10000 开始(由迁移设置 AUTO_INCREMENT)。
|
||||
* @param {Object} app Egg.js Application 实例。
|
||||
* @return {Object} Sequelize Model 定义。
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, DATE } = app.Sequelize;
|
||||
|
||||
const ReturnReceivedTask = app.model.define('return_received_task', {
|
||||
id: {
|
||||
type: BIGINT.UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID(自增从10000开始)',
|
||||
},
|
||||
batch_no: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '批次号',
|
||||
},
|
||||
title: {
|
||||
type: STRING(100),
|
||||
allowNull: false,
|
||||
defaultValue: '',
|
||||
comment: '标题(任务名称,如系统预设「历史收件」)',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '仓库ID(数据隔离维度)',
|
||||
},
|
||||
creator_id: {
|
||||
type: BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '创建人账户ID',
|
||||
},
|
||||
creator_name: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '创建人名称快照',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '更新时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_return_received_task',
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
// 表无 deleted_at 列,必须显式关闭全局 define 的 paranoid 默认值,
|
||||
// 否则 findAll/findOne 会拼出 deleted_at 字段导致 Unknown column 报错
|
||||
paranoid: false,
|
||||
comment: '收件任务表(批次号、仓库ID、创建人、创建时间)',
|
||||
});
|
||||
|
||||
return ReturnReceivedTask;
|
||||
};
|
||||
@ -51,11 +51,17 @@ class ReturnReceivedMethodService extends MainService {
|
||||
* @param {Object} data 请求体。
|
||||
* @param {string} data.waybill_code 退回收件运单号。
|
||||
* @param {string} [data.remark] 备注。
|
||||
* @param {number|string} [data.return_received_task_id] 收件任务ID,不传默认 1(系统预设「历史收件」);
|
||||
* 兼容旧字段 receiving_task_id(新字段优先)。
|
||||
* @return {Promise<Object>} 统一 success 包装。
|
||||
*/
|
||||
async create(data = {}) {
|
||||
const { waybill_code, remark } = data;
|
||||
return this._call(() => this.service.systems.returnReceived.create({ waybill_code, remark }), '扫码登记失败');
|
||||
const { waybill_code, remark, return_received_task_id, receiving_task_id } = data;
|
||||
// 新字段 return_received_task_id 优先,兼容旧字段 receiving_task_id
|
||||
const taskId = return_received_task_id !== undefined && return_received_task_id !== null && return_received_task_id !== ''
|
||||
? return_received_task_id
|
||||
: receiving_task_id;
|
||||
return this._call(() => this.service.systems.returnReceived.create({ waybill_code, remark, return_received_task_id: taskId }), '扫码登记失败');
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
166
app/service/systemMethods/returnReceivedTask.js
Normal file
166
app/service/systemMethods/returnReceivedTask.js
Normal file
@ -0,0 +1,166 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../main');
|
||||
|
||||
/**
|
||||
* 系统方法层:returnReceivedTask(收件任务模块接口包装层,退回收件任务分组)。
|
||||
* 主要职责:统一包装系统方法接口,处理权限、日志等公共逻辑,
|
||||
* 将具体业务逻辑下沉到 systems.returnReceivedTask 中。
|
||||
*
|
||||
* 权限口径:create/delete 需要登录、免 API 权限校验(无需 wms_permission 记录);
|
||||
* 仓库与创建人均由服务端从登录上下文自动注入,禁止前端传入。
|
||||
*/
|
||||
class ReturnReceivedTaskMethodService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
// 免登录方法列表:空(全部需要登录)
|
||||
const _noNeedLogin = '';
|
||||
// 免权限方法列表:create/delete/batchDelete/list 免 API 权限校验(仅需登录)
|
||||
const _noNeedRight = 'create,delete,batchDelete,list';
|
||||
// 免日志方法列表:list(查询类不记录操作日志)
|
||||
const _noNeedLog = 'list';
|
||||
// 免鉴权(仓库有效期检查)方法列表:空(全部检查有效期)
|
||||
const _noNeedAuth = '';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一调用收件任务业务服务,并捕获业务错误码。
|
||||
*
|
||||
* @param {Function} fn 业务调用函数。
|
||||
* @param {string} fallbackMessage 兜底错误文案。
|
||||
* @return {Promise<Object>} 统一 success/fail 包装。
|
||||
*/
|
||||
async _call(fn, fallbackMessage) {
|
||||
try {
|
||||
const result = await fn();
|
||||
return this.success('ok', result);
|
||||
} catch (error) {
|
||||
const code = Number(error && error.code);
|
||||
if (Number.isInteger(code) && code >= 400 && code < 600) {
|
||||
return this.fail(error.message || fallbackMessage, {}, code);
|
||||
}
|
||||
this.ctx.logger.error(`[returnReceivedTask] ${fallbackMessage}: ${error && error.message ? error.message : error}`);
|
||||
return this.fail('服务器内部错误', {}, 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建收件任务(增)。
|
||||
* warehouse_id / creator_id / creator_name 由服务端从当前登录上下文自动注入,前端无需传递;
|
||||
* 批次号一律由服务端自动生成(RT+YYYYMMDD+5位序号,参考波次号取号机制),不接收外部输入。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {string} [data.title] 标题(任务名称)。
|
||||
* @return {Promise<Object>} 统一 success 包装,返回新建的收件任务行。
|
||||
*/
|
||||
async create(data = {}) {
|
||||
const { ctx } = this;
|
||||
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
|
||||
const creatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0;
|
||||
const creatorName = ctx.user ? (ctx.user.employees_name || ctx.user.real_name || '') : '';
|
||||
const { title } = data || {};
|
||||
|
||||
return this._call(
|
||||
() => this.service.systems.returnReceivedTask.create({
|
||||
warehouseId,
|
||||
title,
|
||||
creatorId,
|
||||
creatorName,
|
||||
}),
|
||||
'创建收件任务失败'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询收件任务列表(查)。
|
||||
* warehouse_id 由服务端从当前登录上下文自动注入(含系统级任务 warehouse_id=0),禁止前端传入。
|
||||
* 搜索关键词 where.quickWhere:在 title(标题)/batch_no(编号)/creator_name(创建人)三个字段中模糊匹配
|
||||
* (OR 关系);title/batch_no/creator_name 也支持 {operator,value} 标准结构(like/eq/in 等)。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {Object} [data.where] 筛选条件(含 has_register:是否有登记,true/false)。
|
||||
* @param {Object} [data.pagination] 分页参数。
|
||||
* @param {Object} [data.sort] 排序参数(sortField: id/batch_no/created_at/updated_at,默认 id desc)。
|
||||
* @return {Promise<Object>} 统一 success 包装,返回 { list, pagination }。
|
||||
*/
|
||||
async list(data = {}) {
|
||||
const { service } = this;
|
||||
const { pagination, sort } = data;
|
||||
const { where } = this.prepareWhereContext(data, {
|
||||
specialFieldMap: {
|
||||
quickWhere: {
|
||||
bucket: 'quick',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// 仓库隔离:由服务端从当前上下文自动注入(含系统级任务 warehouse_id=0),禁止前端传入
|
||||
const warehouseId = Number(this.ctx.user && this.ctx.user.store_id || 0);
|
||||
const enforcedWhere = { ...where };
|
||||
if (warehouseId > 0) {
|
||||
enforcedWhere.warehouse_id = { operator: 'in', value: [ 0, warehouseId ] };
|
||||
}
|
||||
|
||||
return this._call(
|
||||
() => service.systems.returnReceivedTask.list(enforcedWhere, pagination, sort, warehouseId),
|
||||
'查询列表失败'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量删除收件任务(删,硬删除)。
|
||||
* 逐条分流:不存在/系统预设(id=1)/非本仓库/已有收件登记的任务计入 skipped_ids 不报错;
|
||||
* 其余硬删除并清理缓存。warehouse_id 由服务端从当前登录上下文自动注入,前端无需传递。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {Array<number>|number} data.ids 收件任务ID(数组或单值,单次上限 200)。
|
||||
* @return {Promise<Object>} 统一 success 包装,返回
|
||||
* { total, deleted_count, skipped_count, deleted_ids, skipped_ids }。
|
||||
*/
|
||||
async batchDelete(data = {}) {
|
||||
const { ctx } = this;
|
||||
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
|
||||
const { ids } = data || {};
|
||||
|
||||
return this._call(
|
||||
() => this.service.systems.returnReceivedTask.batchDelete({ warehouseId, ids }),
|
||||
'批量删除收件任务失败'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除收件任务(删,硬删除)。
|
||||
* 兼容两种入参:
|
||||
* - ids(数组或单值):批量删除,逐条分流,不存在/系统预设/非本仓库/已有登记的任务
|
||||
* 计入 skipped_ids 不报错,返回 { total, deleted_count, skipped_count, deleted_ids, skipped_ids };
|
||||
* - id(单值):单值删除,不满足条件抛 404/409。
|
||||
* warehouse_id 由服务端从当前登录上下文自动注入,前端无需传递。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {Array<number>|number} [data.ids] 收件任务ID(数组或单值,单次上限 200,优先于 id)。
|
||||
* @param {number|string} [data.id] 收件任务ID(单值删除)。
|
||||
* @return {Promise<Object>} 统一包装:单值删除返回 { id, deleted };
|
||||
* 批量删除返回 { total, deleted_count, skipped_count, deleted_ids, skipped_ids }。
|
||||
*/
|
||||
async delete(data = {}) {
|
||||
const { ctx } = this;
|
||||
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
|
||||
const { id, ids } = data || {};
|
||||
|
||||
// 批量删除:传 ids 时走批量分流语义
|
||||
if (ids !== undefined && ids !== null) {
|
||||
return this._call(
|
||||
() => this.service.systems.returnReceivedTask.batchDelete({ warehouseId, ids }),
|
||||
'批量删除收件任务失败'
|
||||
);
|
||||
}
|
||||
|
||||
return this._call(
|
||||
() => this.service.systems.returnReceivedTask.delete(id, warehouseId),
|
||||
'删除收件任务失败'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ReturnReceivedTaskMethodService;
|
||||
@ -3,7 +3,7 @@
|
||||
const MainService = require('../main');
|
||||
|
||||
/**
|
||||
* 系统方法层:returnWaybill(运单退回登记模块接口包装层)。
|
||||
* 系统方法层:returnWaybill(未退登记模块接口包装层)。
|
||||
* 主要职责:统一包装系统方法接口,处理权限、where 解析等公共逻辑,
|
||||
* 将具体业务逻辑下沉到 systems.return_waybill 中。
|
||||
*/
|
||||
@ -22,7 +22,7 @@ class ReturnWaybillMethodService extends MainService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一调用运单退回登记业务服务,并捕获业务错误码。
|
||||
* 统一调用未退登记业务服务,并捕获业务错误码。
|
||||
*
|
||||
* @param {Function} fn 业务调用函数。
|
||||
* @param {string} fallbackMessage 兜底错误文案。
|
||||
@ -43,7 +43,7 @@ class ReturnWaybillMethodService extends MainService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 运单退回登记(增)。
|
||||
* 未退登记(增)。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {string} data.waybill_code 运单号。
|
||||
|
||||
@ -11,6 +11,13 @@ const Service = require('egg').Service;
|
||||
/** 退回收到导出分页拉取大小 */
|
||||
const RETURN_RECEIVED_EXPORT_PAGE_SIZE = 500;
|
||||
|
||||
/** 收件任务缓存键前缀(任务ID → 任务元信息) */
|
||||
const RETURN_RECEIVED_TASK_CACHE_KEY_PREFIX = 'return_received_task:';
|
||||
/** 收件任务缓存过期秒数(10 分钟) */
|
||||
const RETURN_RECEIVED_TASK_CACHE_TTL_SECONDS = 600;
|
||||
/** 系统预设「历史收件」任务ID(未传任务ID时的默认值) */
|
||||
const DEFAULT_RETURN_RECEIVED_TASK_ID = 1;
|
||||
|
||||
/**
|
||||
* 退回收到模块业务逻辑层。
|
||||
* 负责 wms_return_received 的增删查,以及原单反查、货主备注、30 日幂等等核心操作。
|
||||
@ -37,9 +44,10 @@ class ReturnReceivedService extends Service {
|
||||
* @param {Object} params 登记参数。
|
||||
* @param {string} params.waybill_code 退回收件运单号。
|
||||
* @param {string} [params.remark] 备注。
|
||||
* @param {number|string} [params.return_received_task_id] 收件任务ID,不传默认 1(系统预设「历史收件」)。
|
||||
* @return {Promise<Object>} 登记结果,含 record、is_original_return、store_remark、is_urgent、duplicated。
|
||||
*/
|
||||
async create({ waybill_code, remark }) {
|
||||
async create({ waybill_code, remark, return_received_task_id }) {
|
||||
const { ctx, app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
|
||||
@ -62,6 +70,9 @@ class ReturnReceivedService extends Service {
|
||||
throw this.createBusinessError('缺少扫描人员工号上下文', 400);
|
||||
}
|
||||
|
||||
// 收件任务ID校验(缓存优先,未命中穿透数据库建立缓存)
|
||||
const returnReceivedTaskId = await this._validateReturnReceivedTask(return_received_task_id, warehouseId);
|
||||
|
||||
// 30 日幂等窗口:同仓库 + 同单号,扫描日期在最近 30 天内则视为重复
|
||||
const now = new Date();
|
||||
const thirtyDaysAgo = new Date(now.getTime());
|
||||
@ -150,6 +161,7 @@ class ReturnReceivedService extends Service {
|
||||
order_express_id: orderExpressId,
|
||||
order_id: orderId,
|
||||
store_id: storeId,
|
||||
return_received_task_id: returnReceivedTaskId,
|
||||
remark: remark ? String(remark).slice(0, 500) : null,
|
||||
});
|
||||
|
||||
@ -189,6 +201,59 @@ class ReturnReceivedService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验收件任务ID(缓存优先,未命中穿透数据库建立缓存)。
|
||||
*
|
||||
* 规则:
|
||||
* 1. 未传任务ID时默认 1(系统预设「历史收件」);
|
||||
* 2. 任务ID必须为正整数;
|
||||
* 3. 缓存键 return_received_task:{id} 命中直接使用;未命中查 wms_return_received_task,
|
||||
* 存在则写缓存(TTL 10 分钟),不存在报错;
|
||||
* 4. 任务必须属于当前仓库或系统级(warehouse_id=0)。
|
||||
*
|
||||
* @param {number|string|undefined} rawTaskId 入参任务ID。
|
||||
* @param {number} warehouseId 当前仓库ID。
|
||||
* @return {Promise<number>} 校验通过的任务ID。
|
||||
*/
|
||||
async _validateReturnReceivedTask(rawTaskId, warehouseId) {
|
||||
const { ctx, app } = this;
|
||||
|
||||
const taskId = rawTaskId === undefined || rawTaskId === null || rawTaskId === ''
|
||||
? DEFAULT_RETURN_RECEIVED_TASK_ID
|
||||
: Number(rawTaskId);
|
||||
|
||||
if (!Number.isInteger(taskId) || taskId <= 0) {
|
||||
throw this.createBusinessError('收件任务ID不合法', 400);
|
||||
}
|
||||
|
||||
const cacheKey = RETURN_RECEIVED_TASK_CACHE_KEY_PREFIX + taskId;
|
||||
let task = await app.getCacheAsync(cacheKey);
|
||||
if (!task) {
|
||||
// 缓存未命中:穿透数据库查询并建立缓存
|
||||
task = await ctx.model.ReturnReceivedTask.findOne({
|
||||
where: { id: taskId },
|
||||
attributes: [ 'id', 'warehouse_id', 'title' ],
|
||||
raw: true,
|
||||
});
|
||||
if (!task) {
|
||||
throw this.createBusinessError(`收件任务不存在: ${taskId}`, 400);
|
||||
}
|
||||
await app.setCacheAsync(cacheKey, {
|
||||
id: Number(task.id),
|
||||
warehouse_id: Number(task.warehouse_id || 0),
|
||||
title: String(task.title || ''),
|
||||
}, RETURN_RECEIVED_TASK_CACHE_TTL_SECONDS);
|
||||
}
|
||||
|
||||
// 仓库归属校验:系统级(warehouse_id=0)或当前仓库任务才允许使用
|
||||
const taskWarehouseId = Number(task.warehouse_id || 0);
|
||||
if (taskWarehouseId !== 0 && taskWarehouseId !== Number(warehouseId)) {
|
||||
throw this.createBusinessError('收件任务不属于当前仓库', 400);
|
||||
}
|
||||
|
||||
return taskId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断运单是否存在退回查询记录(加急标记判定口径)。
|
||||
* 判定标准:wms_return_query_log 中存在 warehouse_id = 当前仓库 且 waybill_code = 登记运单号(精确匹配)的记录。
|
||||
@ -924,6 +989,7 @@ class ReturnReceivedService extends Service {
|
||||
const directFields = [
|
||||
'warehouse_id', 'scanner_id', 'store_id', 'order_express_id', 'order_id',
|
||||
'waybill_code', 'scan_date', 'created_at', 'updated_at', 'scanner_name',
|
||||
'return_received_task_id',
|
||||
];
|
||||
|
||||
for (const field of directFields) {
|
||||
|
||||
535
app/service/systems/return_received_task.js
Normal file
535
app/service/systems/return_received_task.js
Normal file
@ -0,0 +1,535 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
|
||||
/** 批次号前缀(RT=Return(Received) Task) */
|
||||
const BATCH_NO_PREFIX = 'RT';
|
||||
/** 批次号当日序号位宽(5 位补零) */
|
||||
const BATCH_NO_SEQUENCE_WIDTH = 5;
|
||||
/** 序列表业务类型(wms_number_sequence.biz_type,全局维度 warehouse_id=0) */
|
||||
const BATCH_NO_BIZ_TYPE = 'return_received_task_batch_no';
|
||||
|
||||
/**
|
||||
* 收件任务模块业务逻辑层(退回收件任务分组)。
|
||||
* 负责 wms_return_received_task(收件任务表)的创建与删除。
|
||||
* 所有数据库交互集中在此层,供 systemMethods/returnReceivedTask.js 调用。
|
||||
*/
|
||||
class ReturnReceivedTaskService extends Service {
|
||||
/**
|
||||
* 创建带业务错误码的异常对象。
|
||||
* @param {string} message 错误信息。
|
||||
* @param {number} [code=400] 业务错误码。
|
||||
* @return {Error} 包含 code 的异常对象。
|
||||
*/
|
||||
createBusinessError(message, code = 400) {
|
||||
const error = new Error(`${message}`);
|
||||
error.code = code;
|
||||
return error;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建收件任务。
|
||||
* 仓库与创建人均由方法层从登录上下文注入,前端不传;
|
||||
* 批次号一律由服务端自动生成(RT+YYYYMMDD+5位序号,参考波次号取号机制),
|
||||
* 不接收外部输入。
|
||||
*
|
||||
* @param {Object} params 创建参数。
|
||||
* @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。
|
||||
* @param {string} [params.title] 标题(任务名称),缺省为空串。
|
||||
* @param {number} params.creatorId 创建人账户ID(由方法层从上下文注入)。
|
||||
* @param {string} [params.creatorName] 创建人名称快照(由方法层从上下文注入)。
|
||||
* @return {Promise<Object>} 新建的收件任务行(时间字段为格式化字符串)。
|
||||
* @throws {Error} 参数非法时抛出业务错误(错误码 400)。
|
||||
*/
|
||||
async create({ warehouseId, title, creatorId, creatorName }) {
|
||||
const { ctx, app } = this;
|
||||
|
||||
const normalizedWarehouseId = Number(warehouseId);
|
||||
if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
|
||||
throw this.createBusinessError('无法获取当前仓库上下文');
|
||||
}
|
||||
|
||||
const normalizedTitle = title ? String(title).trim() : '';
|
||||
if (normalizedTitle.length > 100) {
|
||||
throw this.createBusinessError('标题过长(最多100字符)');
|
||||
}
|
||||
|
||||
const record = await ctx.model.ReturnReceivedTask.create({
|
||||
batch_no: await this.generateBatchNo(),
|
||||
title: normalizedTitle,
|
||||
warehouse_id: normalizedWarehouseId,
|
||||
creator_id: creatorId ? Number(creatorId) : 0,
|
||||
creator_name: creatorName ? String(creatorName).trim() : '',
|
||||
});
|
||||
|
||||
const row = record.get({ plain: true });
|
||||
return {
|
||||
...row,
|
||||
created_at: row.created_at ? app.formatDate(row.created_at, 'YYYY-MM-DD HH:mm:ss') : '',
|
||||
updated_at: row.updated_at ? app.formatDate(row.updated_at, 'YYYY-MM-DD HH:mm:ss') : '',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询收件任务列表(仓库隔离由方法层注入 warehouse_id,系统级任务 warehouse_id=0 一并可见)。
|
||||
*
|
||||
* 搜索关键词(where 直接传字符串默认模糊匹配,也支持 {operator, value} 标准结构):
|
||||
* title(标题)、batch_no(编号)、creator_name(创建人)。
|
||||
* 其他字段:id/creator_id/warehouse_id 等值或 in、created_at/updated_at 范围;
|
||||
* has_register(是否有登记):true=仅看有登记任务,false=仅看无登记任务(按 wms_return_received 引用判定)。
|
||||
*
|
||||
* @param {Object} where 标准化 where 条件对象。
|
||||
* @param {Object} [pagination] 分页参数。
|
||||
* @param {number} [pagination.page=1] 页码。
|
||||
* @param {number} [pagination.pageSize=20] 每页数量。
|
||||
* @param {Object} [sort] 排序参数。
|
||||
* @param {string} [sort.sortField] 排序字段。
|
||||
* @param {string} [sort.sortOrder] 排序顺序(asc/desc)。
|
||||
* @param {number} [warehouseId=0] 当前仓库ID(由方法层从上下文注入)。
|
||||
* 用于把登记数量与「是否有登记」统计限定在当前仓库:系统级任务(如「历史收件」id=1)
|
||||
* 被各仓库共用,register_count/has_register 只统计当前仓库的登记行,避免跨仓。
|
||||
* @return {Promise<Object>} { list: Array, pagination: Object },
|
||||
* list 每行含 register_count(该任务在当前仓库下的退回收件登记数量,无登记为 0)。
|
||||
*/
|
||||
async list(where = {}, pagination = {}, sort = {}, warehouseId = 0) {
|
||||
const { ctx, app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
|
||||
const page = Math.max(1, parseInt(pagination.page) || 1);
|
||||
const pageSize = Math.min(500, Math.max(1, parseInt(pagination.pageSize) || 20));
|
||||
const normalizedWarehouseId = Number(warehouseId);
|
||||
const statWarehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 ? normalizedWarehouseId : 0;
|
||||
|
||||
const queryWhere = this._buildTaskListWhere(where, Op, statWarehouseId);
|
||||
const order = this._buildTaskListOrder(sort);
|
||||
|
||||
const { count, rows } = await ctx.model.ReturnReceivedTask.findAndCountAll({
|
||||
where: queryWhere,
|
||||
order,
|
||||
offset: (page - 1) * pageSize,
|
||||
limit: pageSize,
|
||||
raw: true,
|
||||
});
|
||||
|
||||
// 任务登记数量:按任务ID分组统计当前仓库的登记行数(一次分组查询,避免系统级任务跨仓统计)
|
||||
const taskIds = rows.map(row => Number(row.id)).filter(id => id > 0);
|
||||
const registerCountMap = new Map();
|
||||
if (taskIds.length > 0) {
|
||||
const statWhere = { return_received_task_id: { [Op.in]: taskIds } };
|
||||
if (statWarehouseId > 0) {
|
||||
statWhere.warehouse_id = statWarehouseId;
|
||||
}
|
||||
const statRows = await ctx.model.ReturnReceived.findAll({
|
||||
attributes: [
|
||||
'return_received_task_id',
|
||||
[ app.Sequelize.fn('COUNT', app.Sequelize.col('return_received_task_id')), 'register_count' ],
|
||||
],
|
||||
where: statWhere,
|
||||
group: [ 'return_received_task_id' ],
|
||||
raw: true,
|
||||
});
|
||||
for (const stat of statRows) {
|
||||
registerCountMap.set(Number(stat.return_received_task_id), Number(stat.register_count || 0));
|
||||
}
|
||||
}
|
||||
|
||||
const list = rows.map(row => ({
|
||||
...row,
|
||||
register_count: registerCountMap.get(Number(row.id)) || 0,
|
||||
created_at: row.created_at ? app.formatDate(row.created_at, 'YYYY-MM-DD HH:mm:ss') : '',
|
||||
updated_at: row.updated_at ? app.formatDate(row.updated_at, 'YYYY-MM-DD HH:mm:ss') : '',
|
||||
}));
|
||||
|
||||
return {
|
||||
list,
|
||||
pagination: {
|
||||
page,
|
||||
pageSize,
|
||||
total: count,
|
||||
totalPages: Math.ceil(count / pageSize),
|
||||
hasPrevious: page > 1,
|
||||
hasNext: page * pageSize < count,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据标准化 where 条件构建收件任务列表查询条件。
|
||||
*
|
||||
* @param {Object} where 标准化 where 条件对象。
|
||||
* @param {Object} Op Sequelize Op 对象。
|
||||
* @param {number} [warehouseId=0] 当前仓库ID(has_register 判定按当前仓库过滤,避免跨仓)。
|
||||
* @return {Object} Sequelize where 条件。
|
||||
*/
|
||||
_buildTaskListWhere(where = {}, Op, warehouseId = 0) {
|
||||
const { app } = this;
|
||||
const queryWhere = {};
|
||||
|
||||
// 搜索关键词字段:标题/编号/创建人,支持 {operator,value} 标准结构(like 模糊/eq 精确等)
|
||||
for (const field of [ 'title', 'batch_no', 'creator_name' ]) {
|
||||
const raw = where[field];
|
||||
if (raw === undefined || raw === null) {
|
||||
continue;
|
||||
}
|
||||
queryWhere[field] = this._resolveTaskConditionValue(raw, Op);
|
||||
}
|
||||
|
||||
// 快捷搜索关键词:在 title/batch_no/creator_name 三个字段中 OR 模糊匹配
|
||||
if (where.quickWhere !== undefined && where.quickWhere !== null) {
|
||||
const quickRaw = this._extractTaskConditionValue(where.quickWhere);
|
||||
const quickValue = this._extractTaskConditionValue(quickRaw);
|
||||
if (quickValue !== undefined && quickValue !== null && String(quickValue).trim() !== '') {
|
||||
const likePattern = { [Op.like]: `%${String(quickValue).trim()}%` };
|
||||
queryWhere[Op.or] = [
|
||||
{ title: likePattern },
|
||||
{ batch_no: likePattern },
|
||||
{ creator_name: likePattern },
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
// 是否有登记(派生筛选):true=仅看有登记的任务,false=仅看无登记的任务;按当前仓库过滤,避免跨仓
|
||||
if (where.has_register !== undefined && where.has_register !== null) {
|
||||
const hasValue = this._extractTaskConditionValue(where.has_register);
|
||||
const flag = hasValue === true || hasValue === 1 || hasValue === '1' || hasValue === 'true';
|
||||
const registerSubSql = warehouseId > 0
|
||||
? `(SELECT DISTINCT return_received_task_id FROM wms_return_received WHERE warehouse_id = ${Number(warehouseId)})`
|
||||
: '(SELECT DISTINCT return_received_task_id FROM wms_return_received)';
|
||||
queryWhere.id = flag
|
||||
? { [Op.in]: app.Sequelize.literal(registerSubSql) }
|
||||
: { [Op.notIn]: app.Sequelize.literal(registerSubSql) };
|
||||
}
|
||||
|
||||
// 数值字段:等值/in/范围
|
||||
for (const field of [ 'id', 'creator_id', 'warehouse_id' ]) {
|
||||
if (where[field] !== undefined && where[field] !== null) {
|
||||
queryWhere[field] = this._resolveTaskConditionValue(where[field], Op);
|
||||
}
|
||||
}
|
||||
|
||||
// 时间字段
|
||||
for (const field of [ 'created_at', 'updated_at' ]) {
|
||||
if (where[field] !== undefined && where[field] !== null) {
|
||||
queryWhere[field] = this._resolveTaskConditionValue(where[field], Op);
|
||||
}
|
||||
}
|
||||
|
||||
return queryWhere;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析标准化条件值为 Sequelize 可用的条件对象。
|
||||
*
|
||||
* @param {*} condition 标准化条件(可能是 {operator, value} 或直接值)。
|
||||
* @param {Object} Op Sequelize Op 对象。
|
||||
* @return {*} Sequelize 条件。
|
||||
*/
|
||||
_resolveTaskConditionValue(condition, Op) {
|
||||
if (condition && typeof condition === 'object' && !Array.isArray(condition)) {
|
||||
const operator = condition.operator;
|
||||
const value = condition.value;
|
||||
|
||||
if (!operator) {
|
||||
return value;
|
||||
}
|
||||
|
||||
switch (operator) {
|
||||
case 'eq':
|
||||
return value;
|
||||
case 'ne':
|
||||
return { [Op.ne]: value };
|
||||
case 'in':
|
||||
return { [Op.in]: Array.isArray(value) ? value : [ value ] };
|
||||
case 'notin':
|
||||
return { [Op.notIn]: Array.isArray(value) ? value : [ value ] };
|
||||
case 'like':
|
||||
return { [Op.like]: `%${value}%` };
|
||||
case 'gt':
|
||||
return { [Op.gt]: value };
|
||||
case 'gte':
|
||||
return { [Op.gte]: value };
|
||||
case 'lt':
|
||||
return { [Op.lt]: value };
|
||||
case 'lte':
|
||||
return { [Op.lte]: value };
|
||||
case 'between':
|
||||
return { [Op.between]: Array.isArray(value) ? value : [ value ] };
|
||||
default:
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
return condition;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 sort 参数构建 Sequelize 排序数组。
|
||||
*
|
||||
* @param {Object} sort 排序参数。
|
||||
* @return {Array<Array<string>>} Sequelize order 数组。
|
||||
*/
|
||||
_buildTaskListOrder(sort = {}) {
|
||||
const sortField = sort.sortField || sort.sort_field || 'id';
|
||||
const sortOrderRaw = (sort.sortOrder || sort.sort_order || 'desc').toLowerCase();
|
||||
const sortOrder = sortOrderRaw === 'asc' ? 'ASC' : 'DESC';
|
||||
|
||||
const allowedSortFields = new Set([ 'id', 'batch_no', 'created_at', 'updated_at' ]);
|
||||
const safeSortField = allowedSortFields.has(sortField) ? sortField : 'id';
|
||||
|
||||
return [[ safeSortField, sortOrder ]];
|
||||
}
|
||||
|
||||
/**
|
||||
* 从条件对象中提取原始 value。
|
||||
*
|
||||
* @param {*} condition 标准化条件。
|
||||
* @return {*} 原始值。
|
||||
*/
|
||||
_extractTaskConditionValue(condition) {
|
||||
if (condition && typeof condition === 'object' && !Array.isArray(condition)) {
|
||||
if ('value' in condition) {
|
||||
return condition.value;
|
||||
}
|
||||
}
|
||||
return condition;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前日期片段(YYYYMMDD)。
|
||||
*
|
||||
* @return {string} 当前日期片段。
|
||||
*/
|
||||
getCurrentDatePart() {
|
||||
const now = new Date();
|
||||
const year = now.getFullYear();
|
||||
const month = String(now.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(now.getDate()).padStart(2, '0');
|
||||
return `${year}${month}${day}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成收件任务批次号(原子取号,参考波次号 getNextWaveNoSequence 口径)。
|
||||
*
|
||||
* 格式:RT + YYYYMMDD + 5位序号(如 RT2026100500001)。
|
||||
* 基于序列表 wms_number_sequence 的 upsert 原子递增(唯一键 uk_warehouse_biz_date
|
||||
* 串行化并发事务,biz_type=return_received_task_batch_no,全局维度 warehouse_id=0),
|
||||
* 并对齐当日主表已有最大序号(历史编号不跳号);
|
||||
* upsert 后通过带锁当前读(SELECT ... FOR UPDATE)回读 current_seq,
|
||||
* 避免 REPEATABLE READ 快照读读到旧值。
|
||||
*
|
||||
* @return {Promise<string>} 批次号。
|
||||
*/
|
||||
async generateBatchNo() {
|
||||
const { ctx } = this;
|
||||
const datePart = this.getCurrentDatePart();
|
||||
const pattern = `${BATCH_NO_PREFIX}${datePart}%`;
|
||||
const prefixDatePartLength = BATCH_NO_PREFIX.length + datePart.length;
|
||||
|
||||
// 历史对齐种子:当日主表已有最大序号(无则为 0)
|
||||
const seedRows = await ctx.model.query(
|
||||
`SELECT IFNULL(MAX(CAST(SUBSTRING(batch_no, :startPos) AS UNSIGNED)), 0) AS max_seq
|
||||
FROM wms_return_received_task
|
||||
WHERE batch_no LIKE :pattern`,
|
||||
{
|
||||
replacements: {
|
||||
pattern,
|
||||
startPos: prefixDatePartLength + 1,
|
||||
},
|
||||
type: ctx.model.QueryTypes.SELECT,
|
||||
}
|
||||
);
|
||||
const seed = Number(seedRows && seedRows[0] && seedRows[0].max_seq || 0);
|
||||
|
||||
// 原子取号:全局维度(warehouse_id=0)按「业务类型+日期」递增,唯一键串行化并发事务
|
||||
await ctx.model.query(
|
||||
`INSERT INTO wms_number_sequence (warehouse_id, biz_type, date_part, current_seq, created_at, updated_at)
|
||||
VALUES (0, :bizType, :datePart, :seed + 1, NOW(), NOW())
|
||||
ON DUPLICATE KEY UPDATE current_seq = GREATEST(current_seq, :seed) + 1, updated_at = NOW()`,
|
||||
{
|
||||
replacements: {
|
||||
bizType: BATCH_NO_BIZ_TYPE,
|
||||
datePart,
|
||||
seed,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
// 带锁当前读回读:同事务已通过 upsert 持有该行排他锁(或经唯一键冲突等待串行化),
|
||||
// FOR UPDATE 返回最新提交版本,不受旧快照影响
|
||||
const seqRows = await ctx.model.query(
|
||||
`SELECT current_seq
|
||||
FROM wms_number_sequence
|
||||
WHERE warehouse_id = 0 AND biz_type = :bizType AND date_part = :datePart
|
||||
FOR UPDATE`,
|
||||
{
|
||||
replacements: {
|
||||
bizType: BATCH_NO_BIZ_TYPE,
|
||||
datePart,
|
||||
},
|
||||
type: ctx.model.QueryTypes.SELECT,
|
||||
}
|
||||
);
|
||||
const sequence = Number(seqRows && seqRows[0] && seqRows[0].current_seq || 0);
|
||||
const safeSequence = Number.isInteger(sequence) && sequence > 0 ? sequence : 1;
|
||||
|
||||
return `${BATCH_NO_PREFIX}${datePart}${String(safeSequence).padStart(BATCH_NO_SEQUENCE_WIDTH, '0')}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量删除收件任务(硬删除)。
|
||||
*
|
||||
* 规则(逐条分流,不整体报错):
|
||||
* 1. 任务不存在、系统预设(id=1「历史收件」)、非当前仓库任务 → 计入 skipped_ids;
|
||||
* 2. 任务下已有收件登记(wms_return_received.return_received_task_id 引用)→ 409 口径计入 skipped_ids;
|
||||
* 3. 其余任务硬删除,并清理任务缓存 return_received_task:{id}。
|
||||
*
|
||||
* @param {Object} params 批量删除参数。
|
||||
* @param {number} params.warehouseId 当前仓库ID(由方法层从上下文注入)。
|
||||
* @param {Array<number>|number} params.ids 收件任务ID(数组或单个数值,单次上限 200)。
|
||||
* @return {Promise<Object>} { total, deleted_count, skipped_count, deleted_ids, skipped_ids },
|
||||
* deleted_ids/skipped_ids 保持入参顺序。
|
||||
* @throws {Error} 仓库上下文缺失、ids 为空或超过上限时抛出业务错误(错误码 400)。
|
||||
*/
|
||||
async batchDelete(params = {}) {
|
||||
const { warehouseId, ids } = params;
|
||||
const { ctx, app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
|
||||
const normalizedWarehouseId = Number(warehouseId);
|
||||
if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
|
||||
throw this.createBusinessError('无法获取当前仓库上下文');
|
||||
}
|
||||
|
||||
// ids 归一化:单值转数组、去重、只保留正整数
|
||||
const idSource = Array.isArray(ids) ? ids : [ ids ];
|
||||
const numericIds = [ ...new Set(idSource.map(value => Number(value)).filter(value => Number.isInteger(value) && value > 0)) ];
|
||||
if (numericIds.length === 0) {
|
||||
throw this.createBusinessError('ids 不能为空');
|
||||
}
|
||||
if (numericIds.length > 200) {
|
||||
throw this.createBusinessError('单次最多删除 200 个收件任务');
|
||||
}
|
||||
|
||||
// 查询任务(不限定仓库,便于区分「不存在/系统预设/无权」三种跳过原因)
|
||||
const taskRows = await ctx.model.ReturnReceivedTask.findAll({
|
||||
where: { id: { [Op.in]: numericIds } },
|
||||
attributes: [ 'id', 'warehouse_id', 'title' ],
|
||||
raw: true,
|
||||
});
|
||||
const taskMap = new Map(taskRows.map(row => [ Number(row.id), row ]));
|
||||
|
||||
// 登记引用计数(本仓库口径一致:普通任务登记都在本仓库)
|
||||
const usedRows = await ctx.model.ReturnReceived.findAll({
|
||||
attributes: [
|
||||
'return_received_task_id',
|
||||
[ app.Sequelize.fn('COUNT', app.Sequelize.col('return_received_task_id')), 'register_count' ],
|
||||
],
|
||||
where: { return_received_task_id: { [Op.in]: numericIds } },
|
||||
group: [ 'return_received_task_id' ],
|
||||
raw: true,
|
||||
});
|
||||
const usedCountMap = new Map();
|
||||
for (const stat of usedRows) {
|
||||
usedCountMap.set(Number(stat.return_received_task_id), Number(stat.register_count || 0));
|
||||
}
|
||||
|
||||
// 逐条分流(保持入参顺序)
|
||||
const deletedIds = [];
|
||||
const skippedIds = [];
|
||||
for (const taskId of numericIds) {
|
||||
const row = taskMap.get(taskId);
|
||||
if (!row) {
|
||||
skippedIds.push(taskId);
|
||||
continue;
|
||||
}
|
||||
if (Number(row.id) === 1) {
|
||||
skippedIds.push(taskId); // 系统预设不可删除
|
||||
continue;
|
||||
}
|
||||
if (Number(row.warehouse_id) !== normalizedWarehouseId) {
|
||||
skippedIds.push(taskId); // 非本仓库无权操作
|
||||
continue;
|
||||
}
|
||||
if ((usedCountMap.get(taskId) || 0) > 0) {
|
||||
skippedIds.push(taskId); // 已有收件登记不可删除
|
||||
continue;
|
||||
}
|
||||
deletedIds.push(taskId);
|
||||
}
|
||||
|
||||
if (deletedIds.length > 0) {
|
||||
await ctx.model.ReturnReceivedTask.destroy({ where: { id: { [Op.in]: deletedIds } } });
|
||||
|
||||
// 清理任务缓存(登记校验缓存 return_received_task:{id})
|
||||
for (const taskId of deletedIds) {
|
||||
await app.delCacheAsync(`return_received_task:${taskId}`);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
total: numericIds.length,
|
||||
deleted_count: deletedIds.length,
|
||||
skipped_count: skippedIds.length,
|
||||
deleted_ids: deletedIds,
|
||||
skipped_ids: skippedIds,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除单个收件任务(兼容入口,硬删除)。
|
||||
* 单值语义与批量删除一致:不满足删除条件时抛出对应业务错误(不静默跳过)。
|
||||
*
|
||||
* @param {number|string} taskId 收件任务ID。
|
||||
* @param {number} warehouseId 当前仓库ID(由方法层从上下文注入)。
|
||||
* @return {Promise<Object>} { id, deleted: true }。
|
||||
*/
|
||||
async delete(taskId, warehouseId) {
|
||||
const { ctx, app } = this;
|
||||
|
||||
const normalizedId = Number(taskId);
|
||||
if (!Number.isInteger(normalizedId) || normalizedId <= 0) {
|
||||
throw this.createBusinessError('收件任务ID不合法');
|
||||
}
|
||||
|
||||
const normalizedWarehouseId = Number(warehouseId);
|
||||
if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
|
||||
throw this.createBusinessError('无法获取当前仓库上下文');
|
||||
}
|
||||
|
||||
const task = await ctx.model.ReturnReceivedTask.findOne({
|
||||
where: { id: normalizedId },
|
||||
attributes: [ 'id', 'warehouse_id', 'title' ],
|
||||
raw: true,
|
||||
});
|
||||
if (!task) {
|
||||
throw this.createBusinessError('收件任务不存在', 404);
|
||||
}
|
||||
|
||||
// 系统预设「历史收件」不可删除
|
||||
if (Number(task.id) === 1) {
|
||||
throw this.createBusinessError('系统预设任务不可删除', 404);
|
||||
}
|
||||
|
||||
// 归属校验:任务必须属于当前仓库
|
||||
if (Number(task.warehouse_id) !== normalizedWarehouseId) {
|
||||
throw this.createBusinessError('收件任务不存在或无权操作', 404);
|
||||
}
|
||||
|
||||
// 已有登记不可删除
|
||||
const usedCount = await ctx.model.ReturnReceived.count({
|
||||
where: { return_received_task_id: normalizedId },
|
||||
});
|
||||
if (usedCount > 0) {
|
||||
throw this.createBusinessError('该任务已有收件登记,无法删除', 409);
|
||||
}
|
||||
|
||||
await ctx.model.ReturnReceivedTask.destroy({ where: { id: normalizedId } });
|
||||
|
||||
// 清理任务缓存(登记校验缓存 return_received_task:{id})
|
||||
await app.delCacheAsync(`return_received_task:${normalizedId}`);
|
||||
|
||||
return { id: normalizedId, deleted: true };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ReturnReceivedTaskService;
|
||||
@ -3,8 +3,8 @@
|
||||
const Service = require('egg').Service;
|
||||
|
||||
/**
|
||||
* 运单退回登记模块业务逻辑层。
|
||||
* 复用 wms_return_query_log 表,提供「货主 + 运单号」退回登记的增删查改。
|
||||
* 未退登记模块业务逻辑层。
|
||||
* 复用 wms_return_query_log 表,提供「货主 + 运单号」未退登记的增删查改。
|
||||
* 所有数据库交互集中在此层,供 systemMethods/returnWaybill.js 调用。
|
||||
*/
|
||||
class ReturnWaybillService extends Service {
|
||||
@ -22,7 +22,7 @@ class ReturnWaybillService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 运单退回登记(增)。入参:运单号 + 货主ID。
|
||||
* 未退登记(增)。入参:运单号 + 货主ID。
|
||||
* 同 warehouse_id + store_id + waybill_code 已存在时返回已有记录(幂等)。
|
||||
*
|
||||
* @param {Object} params 登记参数。
|
||||
|
||||
@ -0,0 +1,69 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 创建收件任务表 wms_receiving_task。
|
||||
*
|
||||
* 字段:批次号 batch_no、仓库ID warehouse_id(数据隔离维度)、
|
||||
* 创建人 creator_id/creator_name、创建时间 created_at。
|
||||
* 主键 id 自增从 10000 开始(建表后设置 AUTO_INCREMENT = 10000)。
|
||||
*
|
||||
* 索引:
|
||||
* idx_warehouse_id(按仓库查询)
|
||||
* idx_batch_no(按批次号查询)
|
||||
* idx_creator_id(按创建人查询)
|
||||
*/
|
||||
|
||||
const TABLE_NAME = 'wms_receiving_task';
|
||||
const AUTO_INCREMENT_START = 10000;
|
||||
|
||||
module.exports = {
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
async up(queryInterface, Sequelize) {
|
||||
const { BIGINT, STRING, DATE } = Sequelize;
|
||||
await queryInterface.createTable(TABLE_NAME, {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID(自增从10000开始)',
|
||||
},
|
||||
batch_no: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '批次号',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '仓库ID(数据隔离维度)',
|
||||
},
|
||||
creator_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '创建人账户ID',
|
||||
},
|
||||
creator_name: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '创建人名称快照',
|
||||
},
|
||||
created_at: { type: DATE, allowNull: false, comment: '创建时间' },
|
||||
updated_at: { type: DATE, allowNull: false, comment: '更新时间' },
|
||||
});
|
||||
|
||||
// 自增ID从 10000 开始
|
||||
await queryInterface.sequelize.query(
|
||||
`ALTER TABLE ${TABLE_NAME} AUTO_INCREMENT = ${AUTO_INCREMENT_START}`
|
||||
);
|
||||
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id' ], { name: 'idx_warehouse_id' });
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'batch_no' ], { name: 'idx_batch_no' });
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'creator_id' ], { name: 'idx_creator_id' });
|
||||
},
|
||||
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.dropTable(TABLE_NAME);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,48 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 收件任务表补「标题」字段,并播种系统预设行(幂等)。
|
||||
*
|
||||
* - addColumn title(标题,NOT NULL 默认空串)
|
||||
* - 幂等插入系统预设:id=1、warehouse_id=0、title='历史收件',
|
||||
* 用于处理历史(旧流程)收货任务;batch_no 同步填 '历史收件',creator_id=0(系统)。
|
||||
*
|
||||
* 显式插入 id=1 不会影响 AUTO_INCREMENT=10000 的水位(1 < 10000)。
|
||||
*/
|
||||
|
||||
const TABLE_NAME = 'wms_receiving_task';
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
const { STRING } = Sequelize;
|
||||
|
||||
const tableInfo = await queryInterface.describeTable(TABLE_NAME);
|
||||
if (!tableInfo.title) {
|
||||
await queryInterface.addColumn(TABLE_NAME, 'title', {
|
||||
type: STRING(100),
|
||||
allowNull: false,
|
||||
defaultValue: '',
|
||||
comment: '标题(任务名称,如系统预设「历史收件」)',
|
||||
});
|
||||
}
|
||||
|
||||
const { sequelize } = queryInterface;
|
||||
const [ rows ] = await sequelize.query(
|
||||
'SELECT id FROM `' + TABLE_NAME + '` WHERE id = 1 LIMIT 1'
|
||||
);
|
||||
if (!rows || rows.length === 0) {
|
||||
await sequelize.query(
|
||||
'INSERT INTO `' + TABLE_NAME + '` (id, batch_no, warehouse_id, creator_id, creator_name, title, created_at, updated_at) VALUES (1, :b, 0, 0, :c, :t, NOW(), NOW())',
|
||||
{ replacements: { b: '历史收件', c: '系统', t: '历史收件' } }
|
||||
);
|
||||
}
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
const { sequelize } = queryInterface;
|
||||
await sequelize.query(
|
||||
'DELETE FROM `' + TABLE_NAME + '` WHERE id = 1 AND warehouse_id = 0'
|
||||
);
|
||||
await queryInterface.removeColumn(TABLE_NAME, 'title');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,47 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 收件登记表 wms_return_received 增加收件任务ID。
|
||||
*
|
||||
* - addColumn receiving_task_id(BIGINT UNSIGNED NOT NULL DEFAULT 1,关联 wms_receiving_task.id)
|
||||
* - 回填:所有现有行 receiving_task_id 统一更新为 1(即系统预设「历史收件」任务)
|
||||
* - 索引 idx_receiving_task_id(按收件任务查询)
|
||||
*/
|
||||
|
||||
const TABLE_NAME = 'wms_return_received';
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
const { BIGINT } = Sequelize;
|
||||
|
||||
const tableInfo = await queryInterface.describeTable(TABLE_NAME);
|
||||
if (!tableInfo.receiving_task_id) {
|
||||
await queryInterface.addColumn(TABLE_NAME, 'receiving_task_id', {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '收件任务ID,关联 wms_receiving_task.id;默认 1=系统预设「历史收件」',
|
||||
});
|
||||
}
|
||||
|
||||
// 显式回填:所有现有行统一为 1(系统预设「历史收件」任务)
|
||||
await queryInterface.sequelize.query(
|
||||
'UPDATE `' + TABLE_NAME + '` SET receiving_task_id = 1 WHERE receiving_task_id IS NULL OR receiving_task_id = 0'
|
||||
);
|
||||
|
||||
const indexes = await queryInterface.showIndex(TABLE_NAME);
|
||||
const hasIndex = (indexes || []).some(i => i.name === 'idx_receiving_task_id');
|
||||
if (!hasIndex) {
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'receiving_task_id' ], { name: 'idx_receiving_task_id' });
|
||||
}
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
const indexes = await queryInterface.showIndex(TABLE_NAME);
|
||||
const hasIndex = (indexes || []).some(i => i.name === 'idx_receiving_task_id');
|
||||
if (hasIndex) {
|
||||
await queryInterface.removeIndex(TABLE_NAME, 'idx_receiving_task_id');
|
||||
}
|
||||
await queryInterface.removeColumn(TABLE_NAME, 'receiving_task_id');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,78 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 收件任务表与关联字段改名(对齐 return_received 退回收件命名体系)。
|
||||
*
|
||||
* - 表 wms_receiving_task 重命名为 wms_return_received_task
|
||||
* - wms_return_received.receiving_task_id 列改名为 return_received_task_id
|
||||
* - 索引 idx_receiving_task_id 改名为 idx_return_received_task_id
|
||||
*
|
||||
* 说明:仅改名,不改数据类型/默认值/数据;列改名后索引保留,先删旧索引再
|
||||
* CHANGE COLUMN 再重建新索引,保证索引名与列名一致。
|
||||
*/
|
||||
|
||||
const TASK_TABLE_OLD = 'wms_receiving_task';
|
||||
const TASK_TABLE_NEW = 'wms_return_received_task';
|
||||
const REGISTER_TABLE = 'wms_return_received';
|
||||
const COLUMN_OLD = 'receiving_task_id';
|
||||
const COLUMN_NEW = 'return_received_task_id';
|
||||
const INDEX_OLD = 'idx_receiving_task_id';
|
||||
const INDEX_NEW = 'idx_return_received_task_id';
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
const { sequelize } = queryInterface;
|
||||
|
||||
// 1. 表重命名
|
||||
await sequelize.query(
|
||||
`RENAME TABLE \`${TASK_TABLE_OLD}\` TO \`${TASK_TABLE_NEW}\``
|
||||
);
|
||||
|
||||
// 2. 登记表列改名(先删旧索引,CHANGE COLUMN 后重建新索引)
|
||||
const indexes = await queryInterface.showIndex(REGISTER_TABLE);
|
||||
const hasOldIndex = (indexes || []).some(i => i.name === INDEX_OLD);
|
||||
if (hasOldIndex) {
|
||||
await queryInterface.removeIndex(REGISTER_TABLE, INDEX_OLD);
|
||||
}
|
||||
|
||||
const tableInfo = await queryInterface.describeTable(REGISTER_TABLE);
|
||||
if (tableInfo[COLUMN_OLD]) {
|
||||
await sequelize.query(
|
||||
`ALTER TABLE \`${REGISTER_TABLE}\` CHANGE COLUMN \`${COLUMN_OLD}\` \`${COLUMN_NEW}\` BIGINT(20) UNSIGNED NOT NULL DEFAULT 1 COMMENT '收件任务ID,关联 wms_return_received_task.id;默认 1=系统预设「历史收件」'`
|
||||
);
|
||||
}
|
||||
|
||||
const indexesAfter = await queryInterface.showIndex(REGISTER_TABLE);
|
||||
const hasNewIndex = (indexesAfter || []).some(i => i.name === INDEX_NEW);
|
||||
if (!hasNewIndex) {
|
||||
await queryInterface.addIndex(REGISTER_TABLE, [ COLUMN_NEW ], { name: INDEX_NEW });
|
||||
}
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
const { sequelize } = queryInterface;
|
||||
|
||||
const indexes = await queryInterface.showIndex(REGISTER_TABLE);
|
||||
const hasNewIndex = (indexes || []).some(i => i.name === INDEX_NEW);
|
||||
if (hasNewIndex) {
|
||||
await queryInterface.removeIndex(REGISTER_TABLE, INDEX_NEW);
|
||||
}
|
||||
|
||||
const tableInfo = await queryInterface.describeTable(REGISTER_TABLE);
|
||||
if (tableInfo[COLUMN_NEW]) {
|
||||
await sequelize.query(
|
||||
`ALTER TABLE \`${REGISTER_TABLE}\` CHANGE COLUMN \`${COLUMN_NEW}\` \`${COLUMN_OLD}\` BIGINT(20) UNSIGNED NOT NULL DEFAULT 1 COMMENT '收件任务ID,关联 wms_receiving_task.id;默认 1=系统预设「历史收件」'`
|
||||
);
|
||||
}
|
||||
|
||||
const indexesAfter = await queryInterface.showIndex(REGISTER_TABLE);
|
||||
const hasOldIndex = (indexesAfter || []).some(i => i.name === INDEX_OLD);
|
||||
if (!hasOldIndex) {
|
||||
await queryInterface.addIndex(REGISTER_TABLE, [ COLUMN_OLD ], { name: INDEX_OLD });
|
||||
}
|
||||
|
||||
await sequelize.query(
|
||||
`RENAME TABLE \`${TASK_TABLE_NEW}\` TO \`${TASK_TABLE_OLD}\``
|
||||
);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,82 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 数据菜单下新增 web_pages 子菜单「退件记录」(id=640),并授权客服员工及以上角色。
|
||||
*
|
||||
* 权限明细:
|
||||
* 640 — ReturnRecord(web_pages 菜单,parent_id=16 数据)
|
||||
*
|
||||
* 角色授权(系统预设角色,不含通配符角色):
|
||||
* 640 → 客服组-员工(30) → 客服组-主管(28)(客服员工及以上)
|
||||
* 经理(8)/仓库管理员(2)/超级管理员(7) 已持有 * 通配符,自动拥有所有权限,无需处理
|
||||
*
|
||||
* 幂等:INSERT IGNORE 创建菜单权限;角色权限数组追加后去重排序,已存在跳过。
|
||||
*/
|
||||
|
||||
const TABLE = 'wms_permission';
|
||||
const ROLE_TABLE = 'wms_role';
|
||||
const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at';
|
||||
|
||||
/** 权限ID → 授权角色ID列表(不含通配符角色) */
|
||||
const PERMISSION_ROLES = {
|
||||
640: [ 30, 28 ],
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
async up(queryInterface, Sequelize) {
|
||||
// ── 1. 创建 web_pages 菜单权限(固定 ID,parent_id=16 数据)──
|
||||
await queryInterface.sequelize.query(
|
||||
`INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`,
|
||||
{ replacements: [ 640, 'ReturnRecord', '@/views/data/returnrecord/index', 'ReturnRecord', null, '退件记录', null, 0, 0, 16, 'web_pages', 1, 1 ] }
|
||||
);
|
||||
|
||||
// ── 2. 角色授权注入 ──
|
||||
for (const permId of Object.keys(PERMISSION_ROLES).map(Number)) {
|
||||
for (const roleId of PERMISSION_ROLES[permId]) {
|
||||
const rows = await queryInterface.sequelize.query(
|
||||
`SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE id = ?`,
|
||||
{ replacements: [ roleId ], type: queryInterface.sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
const record = Array.isArray(rows) ? rows[0] : null;
|
||||
if (!record) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 通配符角色跳过
|
||||
if (record.permissions === '*') {
|
||||
continue;
|
||||
}
|
||||
|
||||
let perms;
|
||||
try {
|
||||
perms = JSON.parse(record.permissions || '[]');
|
||||
} catch (err) {
|
||||
continue;
|
||||
}
|
||||
if (!Array.isArray(perms)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (perms.includes(permId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
perms.push(permId);
|
||||
perms.sort((a, b) => a - b);
|
||||
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`,
|
||||
{ replacements: [ JSON.stringify(perms), roleId ] }
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.sequelize.query(
|
||||
`DELETE FROM \`${TABLE}\` WHERE id = 640`
|
||||
);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,64 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 移除 returnwaybill / returnReceived / returnUnpack 前端页面权限。
|
||||
*
|
||||
* - wms_permission:删除 web_pages 类型页面记录 530(returnReceived)、
|
||||
* 550(returnUnpack)、556(returnwaybill)
|
||||
* - wms_role:从所有非通配符角色的 permissions 数组中移除这三个 id
|
||||
* (通配符角色 permissions='*' 自动拥有所有权限,无需处理)
|
||||
*
|
||||
* 注意:仅移除前端页面权限,API 权限(returnReceived.create 等 type=api)保留。
|
||||
*/
|
||||
|
||||
const TABLE = 'wms_permission';
|
||||
const ROLE_TABLE = 'wms_role';
|
||||
const PAGE_PERMISSION_IDS = [ 530, 550, 556 ];
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
// ── 1. 删除 web_pages 页面权限记录 ──
|
||||
await queryInterface.sequelize.query(
|
||||
`DELETE FROM \`${TABLE}\` WHERE type = 'web_pages' AND id IN (:ids)`,
|
||||
{ replacements: { ids: PAGE_PERMISSION_IDS } }
|
||||
);
|
||||
|
||||
// ── 2. 从非通配符角色 permissions 数组中移除 ──
|
||||
const roles = await queryInterface.sequelize.query(
|
||||
`SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE permissions IS NOT NULL AND permissions <> '' AND permissions <> '*'`,
|
||||
{ type: queryInterface.sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
|
||||
for (const role of roles) {
|
||||
let perms;
|
||||
try {
|
||||
perms = JSON.parse(role.permissions || '[]');
|
||||
} catch (err) {
|
||||
continue;
|
||||
}
|
||||
if (!Array.isArray(perms)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const filtered = perms.filter(id => !PAGE_PERMISSION_IDS.includes(Number(id)));
|
||||
if (filtered.length === perms.length) {
|
||||
continue;
|
||||
}
|
||||
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`,
|
||||
{ replacements: [ JSON.stringify(filtered), role.id ] }
|
||||
);
|
||||
}
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
// 恢复页面权限记录(角色数组不做恢复,回滚由后续授权迁移补充)
|
||||
await queryInterface.sequelize.query(
|
||||
`INSERT IGNORE INTO \`${TABLE}\` (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at) VALUES
|
||||
(530, 'returnReceived', '@/views/express/returnReceived/index', 'returnReceived', NULL, '快递收件', NULL, 0, 0, 19, 'web_pages', 1, 1, NOW(), NOW()),
|
||||
(550, 'returnUnpack', '@/views/express/returnUnpack/index', 'returnUnpack', NULL, '快递拆包', NULL, 0, 0, 19, 'web_pages', 1, 1, NOW(), NOW()),
|
||||
(556, 'returnwaybill', '@/views/express/returnwaybill/index', 'returnwaybill', NULL, '运单退回', NULL, 0, 0, 19, 'web_pages', 1, 1, NOW(), NOW())`
|
||||
);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,28 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 权限名称修正:「运单退回登记」→「未退登记」。
|
||||
*
|
||||
* 仅改 API 权限显示名称(meta_title),path/name(方法路由)保持不变:
|
||||
* 551 — API:未退登记
|
||||
* 552 — API:未退登记修改
|
||||
* 553 — API:未退登记列表
|
||||
* 554 — API:未退登记详情
|
||||
* 555 — API:未退登记删除
|
||||
*/
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
await queryInterface.sequelize.query(
|
||||
'UPDATE `wms_permission` SET meta_title = REPLACE(meta_title, :oldName, :newName) WHERE id IN (551, 552, 553, 554, 555)',
|
||||
{ replacements: { oldName: '运单退回登记', newName: '未退登记' } }
|
||||
);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.sequelize.query(
|
||||
'UPDATE `wms_permission` SET meta_title = REPLACE(meta_title, :newName, :oldName) WHERE id IN (551, 552, 553, 554, 555)',
|
||||
{ replacements: { oldName: '运单退回登记', newName: '未退登记' } }
|
||||
);
|
||||
},
|
||||
};
|
||||
Loading…
x
Reference in New Issue
Block a user