Compare commits

..

No commits in common. "75a248fdf6d6048c189607298f290a508d98817b" and "f4ed98555617dfbe6030e0a24f0efb08526098fa" have entirely different histories.

26 changed files with 337 additions and 4911 deletions

View File

@ -1,55 +0,0 @@
'use strict';
/**
* 业务单号序列表模型。
* 按「仓库 + 业务类型 + 日期」维度原子分配序号,
* 取号使用 INSERT ... ON DUPLICATE KEY UPDATE current_seq = LAST_INSERT_ID(current_seq + 1),
* 避免「查当日最大序号+1」在并发下的撞号问题。
* @param {import('egg').Application} app Egg 应用实例。
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} Sequelize 模型。
*/
module.exports = app => {
const { BIGINT, STRING, INTEGER, CHAR } = app.Sequelize;
const NumberSequence = app.model.define('wms_number_sequence', {
id: {
type: BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
comment: '主键',
},
warehouse_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '仓库ID(序号隔离维度)',
},
biz_type: {
type: STRING(30),
allowNull: false,
comment: '业务类型,如 return_unpack(退回拆包单号)',
},
date_part: {
type: CHAR(8),
allowNull: false,
comment: '日期片段 YYYYMMDD',
},
current_seq: {
type: INTEGER(11),
allowNull: false,
defaultValue: 0,
comment: '当前已分配序号(原子递增)',
},
}, {
tableName: 'wms_number_sequence',
comment: '业务单号序列表(原子取号)',
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
paranoid: false,
indexes: [
{ name: 'uk_warehouse_biz_date', unique: true, fields: [ 'warehouse_id', 'biz_type', 'date_part' ] },
],
});
return NumberSequence;
};

View File

@ -1,65 +0,0 @@
'use strict';
/**
* 退回查询记录表模型(货主未退回、但做过查询退回的运单号)。
* @param {import('egg').Application} app Egg 应用实例。
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} Sequelize 模型。
*/
module.exports = app => {
const { BIGINT, STRING, TINYINT } = app.Sequelize;
const ReturnQueryLog = app.model.define('wms_return_query_log', {
id: {
type: BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
comment: '主键',
},
warehouse_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '仓库ID(隔离维度)',
},
store_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '货主ID(隔离维度)',
},
waybill_code: {
type: STRING(50),
allowNull: false,
comment: '查询过的运单号',
},
remark: {
type: STRING(500),
allowNull: true,
comment: '备注',
},
is_notified: {
type: TINYINT(1),
allowNull: false,
defaultValue: 0,
comment: '是否已通知:0=未通知,1=已通知',
},
is_back: {
type: TINYINT(1),
allowNull: false,
defaultValue: 0,
comment: '是否退回:0=未退回,1=已退回',
},
}, {
tableName: 'wms_return_query_log',
comment: '退回查询记录表(货主未退回但查询过的运单号)',
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
paranoid: false,
indexes: [
{ name: 'idx_warehouse_store_waybill', fields: [ 'warehouse_id', 'store_id', 'waybill_code' ] },
{ name: 'idx_warehouse_store', fields: [ 'warehouse_id', 'store_id' ] },
{ name: 'idx_waybill_code', fields: [ 'waybill_code' ] },
],
});
return ReturnQueryLog;
};

View File

@ -1,166 +0,0 @@
'use strict';
/**
* 退回拆包主表模型。
* @param {import('egg').Application} app Egg 应用实例。
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} Sequelize 模型。
*/
module.exports = app => {
const { BIGINT, STRING, INTEGER, DATE, JSON: JSON_TYPE } = app.Sequelize;
const ReturnUnpack = app.model.define('wms_return_unpack', {
id: {
type: BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
comment: '主键',
},
warehouse_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '仓库ID(数据隔离维度)',
},
unpack_no: {
type: STRING(50),
allowNull: false,
unique: true,
comment: '拆包单号,RP+YYYYMMDD+6位序号',
},
return_received_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '关联退回收到表 wms_return_received.id;非必填',
},
waybill_code: {
type: STRING(50),
allowNull: false,
comment: '拆包的运单号(退回包裹运单号)',
},
unpack_date: {
type: DATE,
allowNull: false,
comment: '拆包日期',
},
start_time: {
type: DATE,
allowNull: true,
comment: '拆包开始时间(参考打包表 start_time)',
},
end_time: {
type: DATE,
allowNull: true,
comment: '拆包结束时间(参考打包表 end_time)',
},
unpacker_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '拆包人员工号ID,关联 wms_account_store_employee.id(employees_id)',
},
unpacker_name: {
type: STRING(50),
allowNull: false,
comment: '拆包人员工号名称快照(employees_name / real_name)',
},
status: {
type: STRING(20),
allowNull: false,
defaultValue: 'unpacking',
comment: '拆包状态:unpacking/completed/cancelled',
},
detail_status: {
type: STRING(30),
allowNull: false,
defaultValue: 'none_recognized',
comment: '明细识别状态:none_recognized/partial_recognized/all_recognized',
},
total_items: {
type: INTEGER(11),
allowNull: false,
defaultValue: 0,
comment: '物品种类数(明细行数)',
},
total_quantity: {
type: INTEGER(11),
allowNull: false,
defaultValue: 0,
comment: '物品总数量(明细数量合计)',
},
order_express_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '原运单ID,关联 wms_order_express.id;原单退回时回填',
},
order_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '原订单ID,便于快速匹配;原单退回时回填',
},
store_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '货主ID,原单退回/识别到系统商品时回填',
},
camera_ids: {
type: JSON_TYPE,
allowNull: true,
comment: '摄像头ID列表,如 [1,2,3](参考 wms_pack_task.device_ids)',
},
remark: {
type: STRING(500),
allowNull: true,
comment: '备注',
},
}, {
tableName: 'wms_return_unpack',
comment: '退回拆包主表',
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
paranoid: false,
indexes: [
{ name: 'uk_unpack_no', unique: true, fields: [ 'unpack_no' ] },
{ name: 'idx_warehouse_unpack_date', fields: [ 'warehouse_id', 'unpack_date' ] },
{ name: 'idx_return_received_id', fields: [ 'return_received_id' ] },
{ name: 'idx_waybill_code', fields: [ 'waybill_code' ] },
{ name: 'idx_order_express_id', fields: [ 'order_express_id' ] },
{ name: 'idx_unpacker_id', fields: [ 'unpacker_id' ] },
{ name: 'idx_start_time', fields: [ 'start_time' ] },
{ name: 'idx_store_id', fields: [ 'store_id' ] },
],
});
ReturnUnpack.associate = function() {
const { Store, AccountStoreEmployee, ReturnReceived, ReturnUnpackDetail, ReturnUnpackVideo, OrderExpress } = app.model;
// 关联仓库(wms_store 主体表)
ReturnUnpack.belongsTo(Store, {
foreignKey: 'warehouse_id',
as: 'warehouse',
});
// 关联拆包人员工号
ReturnUnpack.belongsTo(AccountStoreEmployee, {
foreignKey: 'unpacker_id',
as: 'unpacker',
});
// 关联退回收到单(非必填)
ReturnUnpack.belongsTo(ReturnReceived, {
foreignKey: 'return_received_id',
as: 'returnReceived',
});
// 关联原运单
ReturnUnpack.belongsTo(OrderExpress, {
foreignKey: 'order_express_id',
as: 'orderExpress',
});
// 明细 / 视频
ReturnUnpack.hasMany(ReturnUnpackDetail, {
foreignKey: 'unpack_id',
as: 'details',
});
ReturnUnpack.hasMany(ReturnUnpackVideo, {
foreignKey: 'unpack_id',
as: 'videos',
});
};
return ReturnUnpack;
};

View File

@ -1,111 +0,0 @@
'use strict';
/**
* 退回拆包明细表模型。
* @param {import('egg').Application} app Egg 应用实例。
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} Sequelize 模型。
*/
module.exports = app => {
const { BIGINT, STRING, INTEGER, TEXT, TINYINT } = app.Sequelize;
const ReturnUnpackDetail = app.model.define('wms_return_unpack_detail', {
id: {
type: BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
comment: '主键',
},
unpack_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '关联拆包主表 wms_return_unpack.id',
},
warehouse_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '仓库ID(冗余,隔离查询)',
},
barcode: {
type: STRING(100),
allowNull: true,
comment: '扫描条码(前端可选传入,仅作记录;后端不用于识别)',
},
stock_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '关联 wms_stock_warehouse.id;识别到系统商品时回填,非识别为空',
},
is_recognized: {
type: TINYINT(1),
allowNull: false,
defaultValue: 0,
comment: '是否识别:1=识别到系统商品,0=非识别物品',
},
item_code: {
type: STRING(50),
allowNull: true,
comment: '商品编码快照(识别时回填)',
},
item_name: {
type: STRING(255),
allowNull: true,
comment: '物品名称(识别时回填;非识别时可手工补录)',
},
spec: {
type: STRING(100),
allowNull: true,
comment: '规格快照(sku_property)',
},
quantity: {
type: INTEGER(11),
allowNull: false,
defaultValue: 1,
comment: '数量',
},
product_status: {
type: STRING(20),
allowNull: false,
defaultValue: 'normal',
comment: '产品状态:normal-正常,damaged-破损',
},
product_snapshot: {
type: TEXT,
allowNull: true,
comment: '商品信息快照(JSON),识别时回填,防止商品资料变更后历史丢失',
},
remark: {
type: STRING(500),
allowNull: true,
comment: '备注',
},
}, {
tableName: 'wms_return_unpack_detail',
comment: '退回拆包明细表',
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
paranoid: false,
indexes: [
{ name: 'idx_unpack_id', fields: [ 'unpack_id' ] },
{ name: 'idx_warehouse_barcode', fields: [ 'warehouse_id', 'barcode' ] },
{ name: 'idx_stock_id', fields: [ 'stock_id' ] },
{ name: 'idx_barcode', fields: [ 'barcode' ] },
],
});
ReturnUnpackDetail.associate = function() {
const { ReturnUnpack, StockWarehouse } = app.model;
// 关联拆包主表
ReturnUnpackDetail.belongsTo(ReturnUnpack, {
foreignKey: 'unpack_id',
as: 'unpack',
});
// 关联系统商品(识别到系统商品时命中)
ReturnUnpackDetail.belongsTo(StockWarehouse, {
foreignKey: 'stock_id',
as: 'stockWarehouse',
});
};
return ReturnUnpackDetail;
};

View File

@ -1,89 +0,0 @@
'use strict';
/**
* 退回拆包视频记录表模型(参考 wms_pack_task_video)。
* @param {import('egg').Application} app Egg 应用实例。
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} Sequelize 模型。
*/
module.exports = app => {
const { BIGINT, STRING, DATE } = app.Sequelize;
const ReturnUnpackVideo = app.model.define('wms_return_unpack_video', {
id: {
type: BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
comment: '主键ID',
},
unpack_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '关联拆包主表 wms_return_unpack.id',
},
camera_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '摄像头设备ID,关联 wms_camera.id',
},
video_url: {
type: STRING(500),
allowNull: false,
comment: '视频地址(录像回放URL)',
},
status: {
type: STRING(20),
allowNull: false,
defaultValue: 'created',
comment: '状态:created-已创建 recording-录制中 completed-已完成 failed-失败',
},
remark: {
type: STRING(500),
allowNull: true,
comment: '备注',
},
created_at: {
type: DATE,
allowNull: false,
comment: '创建时间',
},
updated_at: {
type: DATE,
allowNull: false,
comment: '更新时间',
},
deleted_at: {
type: DATE,
allowNull: true,
comment: '软删除时间',
},
}, {
tableName: 'wms_return_unpack_video',
comment: '退回拆包视频记录表',
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
paranoid: true,
deletedAt: 'deleted_at',
indexes: [
{ name: 'idx_unpack_id', fields: [ 'unpack_id' ] },
{ name: 'idx_camera_id', fields: [ 'camera_id' ] },
{ name: 'idx_deleted_at', fields: [ 'deleted_at' ] },
],
});
ReturnUnpackVideo.associate = function() {
const { ReturnUnpack, Camera } = app.model;
// 关联拆包主表
ReturnUnpackVideo.belongsTo(ReturnUnpack, {
foreignKey: 'unpack_id',
as: 'unpack',
});
// 关联摄像头
ReturnUnpackVideo.belongsTo(Camera, {
foreignKey: 'camera_id',
as: 'camera',
});
};
return ReturnUnpackVideo;
};

View File

@ -399,88 +399,6 @@ class InboxMessageService extends Service {
recent_24h_count: recentCount,
};
}
/**
* 手动重推失败(push_status=3)的站内信消息。
* 重置为待推送状态(push_status=0)并触发异步推送。
* @param {Object} params 重推参数。
* @param {number} params.warehouseId 仓库ID(必填,服务端上下文注入)。
* @param {number} params.id 消息ID。
* @return {Promise<Object>} { ok, id, ext_id, message }。
*/
async retry(params = {}) {
const { ctx } = this;
const { InboxMessage } = ctx.model;
const warehouseId = Number(params.warehouseId);
const id = Number(params.id);
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
throw new Error('warehouseId 无效');
}
if (!Number.isFinite(id) || id <= 0) {
throw new Error('消息ID无效');
}
const record = await InboxMessage.findOne({
where: { id, warehouse_id: warehouseId, deleted_at: null },
});
if (!record) {
throw new Error('消息不存在或无权访问');
}
if (record.push_status !== 3) {
throw new Error('仅失败状态的消息可以手动重推');
}
// 重置为待推送状态
await InboxMessage.update(
{ push_status: 0, push_response: null, push_started_at: null },
{ where: { id } }
);
// 回执记录 ext_id 形如 sys:ack:{原消息ext_id},反解出原消息 ext_id 以复用推送链路
const extId = String(record.ext_id || '');
const originalExtId = extId.startsWith('sys:ack:') ? extId.slice(8) : extId;
const hasUser = Boolean(record.user_id && record.user_name);
const pushData = {
warehouse_id: warehouseId,
ext_id: originalExtId,
parent_id: record.parent_id || null,
group_id: record.group_id || '',
group_name: record.group_name || '',
user_id: record.user_id || '',
user_name: record.user_name || '',
ext_data: record.ext_data || null,
};
// 触发异步推送
setImmediate(() => {
ctx.service.inbox.processor.writeOutboundReply(
pushData,
record.content || '',
hasUser ? 'ai_reply' : 'system'
).catch(async err => {
ctx.logger.error(`[inbox] 手动重推异步推送异常 id=${id}: ${err.message}`);
// 推送前校验失败时回写失败状态,避免消息卡在待推送
try {
await InboxMessage.update(
{ push_status: 3, push_response: { error: err.message } },
{ where: { id } }
);
} catch (updateErr) {
ctx.logger.error(`[inbox] 重推失败状态回写异常 id=${id}: ${updateErr.message}`);
}
});
});
return {
ok: true,
id: record.id,
ext_id: record.ext_id,
message: '已重置为待推送状态,正在异步重推',
};
}
}
module.exports = InboxMessageService;

View File

@ -44,8 +44,6 @@ class InboxSystemService extends MainService {
const warehouseId = Number(ctx.user?.store_id || 0);
return ctx.service.inbox.message.stats({ warehouseId, direction: data.direction });
},
reply: data => this.reply(data),
retry: data => this.retry(data),
checkAuth: (...args) => this.checkAuth(...args),
};
}
@ -188,39 +186,6 @@ class InboxSystemService extends MainService {
pageSize,
});
}
/**
* 手动重推失败(push_status=3)的站内信消息。
* 兼容旧版 inbox.retry 路径,与 inbox.message.retry 等价。
* warehouseId 从 ctx.user.store_id 自动注入。
*
* @param {Object} data 请求数据。
* @param {number} data.id 消息ID(必填)。
* @return {Promise<Object>} { ok, id, ext_id, message }。
*/
async retry(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user?.store_id || 0);
return await ctx.service.inbox.message.retry({ warehouseId, id: data.id });
}
/**
* 系统回信:写入 outbound 记录。
* 兼容旧版 inbox.reply 路径,与 inbox.message.reply 等价。
* warehouseId 从 ctx.user.store_id 自动注入。
*
* @param {Object} data 请求数据。
* @param {number} data.parentId 原消息ID(必填)。
* @param {string} [data.content] 回信正文。
* @param {Object} [data.extData] 透传数据。
* @param {Object} [data.flags] 处理标记。
* @return {Promise<Object>} 回信结果。
*/
async reply(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user?.store_id || 0);
return await ctx.service.inbox.index.reply({ warehouseId, ...data });
}
}
module.exports = InboxSystemService;

View File

@ -3700,13 +3700,11 @@ class RecheckOrderService extends OrderBaseService {
* 拦截扫描:通过运单号查找运单记录,标记退回与拦截并处理关联工单与订单拦截状态。
*
* 处理流程:
* 1. 根据运单号查询 wms_order_express;运单不存在,或运单 is_intercept≠'Y' 且关联订单
* intercept_status 不在 requested/intercepting 时,视为非拦截订单并拒绝
* 2. 校验通过后将运单 is_back、is_intercept 设为 'Y'
* 3. 检查是否存在关联的未完结售后工单(wms_after_sale),若有则调用 handleWorkOrder 写入
* 1. 根据运单号查询 wms_order_express,找到则将 is_back、is_intercept 设为 'Y';未找到则创建新记录补充缺失快递
* 2. 检查是否存在关联的未完结售后工单(wms_after_sale),若有则调用 handleWorkOrder 写入
* "库内拦截成功"步骤并将工单置为 completed
* 4. 同步更新 wms_order_delivery 的 intercept_status 为 intercepted_at_warehouse,
* 并释放储位分配与订单锁(仅订单级状态更新,不标记订单下其他面单)
* 3. 同步更新 wms_order_delivery 的 intercept_status 为 intercepted_at_warehouse,
* 并释放储位分配与订单锁(与 confirmIntercept 行为一致,订单级拦截覆盖所有面单含子面单)
*
* 注:库内拦截确认需标记退回 is_back='Y';发起拦截链路仅写 is_intercept,不写 is_back。
*
@ -3727,45 +3725,31 @@ class RecheckOrderService extends OrderBaseService {
const now = new Date();
// 1. 查询运单记录
const expressRecord = await ctx.model.OrderExpress.findOne({
let expressRecord = await ctx.model.OrderExpress.findOne({
where: { waybill_code: normalizedWaybillCode, warehouse_id: warehouseId },
raw: true,
});
// 1a. 非拦截订单校验:运单不存在,或运单/关联订单均未发起系统拦截,则拒绝
// 1a. 缺失快递补充:运单记录不存在则创建新记录(库内拦截确认需标记退回)
if (!expressRecord) {
throw new Error('非拦截订单');
const created = await ctx.model.OrderExpress.create({
waybill_code: normalizedWaybillCode,
order_id: null,
warehouse_id: warehouseId,
is_back: 'Y',
is_intercept: 'Y',
create_at: now,
});
expressRecord = (created && created.toJSON ? created.toJSON() : created) || {};
} else {
// 2. 标记退回 + 拦截
await ctx.model.OrderExpress.update(
{ is_back: 'Y', is_intercept: 'Y' },
{ where: { id: expressRecord.id } }
);
}
const expressIntercepted = String(expressRecord.is_intercept || '').trim() === 'Y';
let orderIntercepted = false;
if (!expressIntercepted) {
const linkedOrderId = Number(expressRecord.order_id || 0);
if (linkedOrderId > 0) {
const checkOrderModel = await this.getOrderModelByTableType('current', warehouseId);
const linkedOrder = await checkOrderModel.findOne({
where: this.buildOrderWhere([ linkedOrderId ], warehouseId),
attributes: [ 'id', 'intercept_status' ],
raw: true,
});
orderIntercepted = linkedOrder
? [ 'requested', 'intercepting' ].includes(String(linkedOrder.intercept_status || '').trim())
: false;
}
}
if (!expressIntercepted && !orderIntercepted) {
throw new Error('非拦截订单');
}
// 2. 标记退回 + 拦截
await ctx.model.OrderExpress.update(
{ is_back: 'Y', is_intercept: 'Y' },
{ where: { id: expressRecord.id } }
);
// 3. 检查关联的未完结售后工单
const afterSale = await ctx.model.AfterSale.findOne({
where: {

View File

@ -1,219 +0,0 @@
'use strict';
const MainService = require('../main');
/**
* 系统方法层:returnUnpack(退回拆包模块接口包装层)。
* 主要职责:统一包装系统方法接口,处理权限、where 解析等公共逻辑,
* 将具体业务逻辑下沉到 systems.return_unpack 中。
*/
class ReturnUnpackMethodService extends MainService {
constructor(ctx) {
super(ctx);
// 免登录方法列表:空(全部需要登录)
const _noNeedLogin = '';
// 免权限方法列表:空(全部走 API 权限校验;detail 走固定 ID 548 客服授权,与设计一致)
const _noNeedRight = '';
// 免日志方法列表:空(全部记录日志)
const _noNeedLog = '';
// 免鉴权(仓库有效期检查)方法列表:空(全部检查有效期)
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(`[returnUnpack] ${fallbackMessage}: ${error && error.message ? error.message : error}`);
return this.fail('服务器内部错误', {}, 500);
}
}
/**
* 开拆包单(增)。
*
* @param {Object} data 请求体。
* @param {string} data.waybill_code 拆包的运单号。
* @param {Array<number>} [data.camera_ids] 摄像头ID列表。
* @param {number} [data.return_received_id] 关联退回收到单ID。
* @param {string} [data.remark] 备注。
* @return {Promise<Object>} 统一 success 包装。
*/
async create(data = {}) {
const { waybill_code, camera_ids, return_received_id, remark } = data;
return this._call(
() => this.service.systems.returnUnpack.create({ waybill_code, camera_ids, return_received_id, remark }),
'开拆包单失败'
);
}
/**
* 录明细(增)。
*
* @param {Object} data 请求体。
* @param {number} data.id 拆包单ID。
* @param {number} [data.stock_id] 系统商品ID(wms_stock_warehouse.id)。
* @param {number} [data.quantity] 数量。
* @param {string} [data.product_status] 产品状态 normal/damaged。
* @param {string} [data.remark] 备注。
* @return {Promise<Object>} 统一 success 包装。
*/
async addDetail(data = {}) {
const { id, stock_id, quantity, product_status, remark } = data;
return this._call(
() => this.service.systems.returnUnpack.addDetail({ id, stock_id, quantity, product_status, remark }),
'录明细失败'
);
}
/**
* 更新明细(改,仅数量/备注)。
*
* @param {Object} data 请求体。
* @param {number} data.id 拆包单ID。
* @param {number} data.detail_id 明细ID。
* @param {number} [data.quantity] 数量。
* @param {string} [data.remark] 备注。
* @return {Promise<Object>} 统一 success 包装。
*/
async updateDetail(data = {}) {
const { id, detail_id, quantity, remark } = data;
return this._call(
() => this.service.systems.returnUnpack.updateDetail({ id, detail_id, quantity, remark }),
'更新明细失败'
);
}
/**
* 移除明细(删)。
*
* @param {Object} data 请求体。
* @param {number} data.id 拆包单ID。
* @param {number} data.detail_id 明细ID。
* @return {Promise<Object>} 统一 success 包装。
*/
async removeDetail(data = {}) {
const { id, detail_id } = data;
return this._call(
() => this.service.systems.returnUnpack.removeDetail({ id, detail_id }),
'移除明细失败'
);
}
/**
* 取消拆包单(删,仅未完成状态)。
*
* @param {Object} data 请求体。
* @param {number} data.id 拆包单ID。
* @return {Promise<Object>} 统一 success 包装。
*/
async cancel(data = {}) {
const { id } = data;
return this._call(() => this.service.systems.returnUnpack.cancel({ id }), '取消拆包单失败');
}
/**
* 提交确认(改,转 completed 终态)。
*
* @param {Object} data 请求体。
* @param {number} data.id 拆包单ID。
* @return {Promise<Object>} 统一 success 包装。
*/
async submit(data = {}) {
const { id } = data;
return this._call(() => this.service.systems.returnUnpack.submit({ id }), '提交确认失败');
}
/**
* 分页查询拆包单列表(查,仓库隔离自动注入)。
*
* @param {Object} data 请求体。
* @param {Object} [data.pagination] 分页参数。
* @param {Object} [data.where] 筛选条件。
* @param {Object} [data.sort] 排序参数。
* @return {Promise<Object>} 统一 success 包装。
*/
async list(data = {}) {
const { service } = this;
const { pagination, sort } = data;
const { where } = this.prepareWhereContext(data, {});
// 仓库隔离:由服务端从当前上下文自动注入,禁止前端传入
const warehouseId = Number(this.ctx.user && this.ctx.user.store_id || 0);
const enforcedWhere = { ...where };
if (warehouseId > 0) {
enforcedWhere.warehouse_id = { operator: 'eq', value: warehouseId };
}
return this._call(
() => service.systems.returnUnpack.list(enforcedWhere, pagination, sort),
'查询列表失败'
);
}
/**
* 分页查询拆包明细列表(查,仓库隔离自动注入)。
*
* @param {Object} data 请求体。
* @param {Object} [data.pagination] 分页参数。
* @param {Object} [data.where] 筛选条件。
* @param {Object} [data.sort] 排序参数。
* @return {Promise<Object>} 统一 success 包装。
*/
async detailList(data = {}) {
const { service } = this;
const { pagination, sort } = data;
const { where } = this.prepareWhereContext(data, {});
// 仓库隔离:由服务端从当前上下文自动注入,禁止前端传入
const warehouseId = Number(this.ctx.user && this.ctx.user.store_id || 0);
const enforcedWhere = { ...where };
if (warehouseId > 0) {
enforcedWhere.warehouse_id = { operator: 'eq', value: warehouseId };
}
return this._call(
() => service.systems.returnUnpack.detailList(enforcedWhere, pagination, sort),
'查询明细列表失败'
);
}
/**
* 查询拆包单详情(查)。
*
* @param {Object} data 请求体。
* @param {number} data.id 拆包单ID。
* @return {Promise<Object>} 统一 success 包装。
*/
async detail(data = {}) {
const { id } = data;
return this._call(() => this.service.systems.returnUnpack.detail(Number(id)), '查询详情失败');
}
/**
* 删除拆包单(删,后台管理,不限制状态)。
*
* @param {Object} data 请求体。
* @param {number} data.id 拆包单ID。
* @return {Promise<Object>} 统一 success 包装。
*/
async delete(data = {}) {
const { id } = data;
return this._call(() => this.service.systems.returnUnpack.delete(Number(id)), '删除失败');
}
}
module.exports = ReturnUnpackMethodService;

View File

@ -1,132 +0,0 @@
'use strict';
const MainService = require('../main');
/**
* 系统方法层:returnWaybill(运单退回登记模块接口包装层)。
* 主要职责:统一包装系统方法接口,处理权限、where 解析等公共逻辑,
* 将具体业务逻辑下沉到 systems.return_waybill 中。
*/
class ReturnWaybillMethodService extends MainService {
constructor(ctx) {
super(ctx);
// 免登录方法列表:空(全部需要登录)
const _noNeedLogin = '';
// 免权限方法列表:detail 复用列表权限(仅登录 + 仓库隔离校验),其余走 API 权限校验
const _noNeedRight = 'detail';
// 免日志方法列表:空(全部记录日志)
const _noNeedLog = '';
// 免鉴权(仓库有效期检查)方法列表:空(全部检查有效期)
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(`[returnWaybill] ${fallbackMessage}: ${error && error.message ? error.message : error}`);
return this.fail('服务器内部错误', {}, 500);
}
}
/**
* 运单退回登记(增)。
*
* @param {Object} data 请求体。
* @param {string} data.waybill_code 运单号。
* @param {number} data.store_id 货主ID。
* @param {string} [data.remark] 备注。
* @return {Promise<Object>} 统一 success 包装。
*/
async create(data = {}) {
const { waybill_code, store_id, remark } = data;
return this._call(
() => this.service.systems.returnWaybill.create({ waybill_code, store_id, remark }),
'登记失败'
);
}
/**
* 修改登记(改)。
*
* @param {Object} data 请求体。
* @param {number} data.id 登记记录ID。
* @param {string} [data.waybill_code] 运单号。
* @param {number} [data.store_id] 货主ID。
* @param {string} [data.remark] 备注。
* @return {Promise<Object>} 统一 success 包装。
*/
async update(data = {}) {
const { id, waybill_code, store_id, remark } = data;
return this._call(
() => this.service.systems.returnWaybill.update({ id, waybill_code, store_id, remark }),
'修改登记失败'
);
}
/**
* 分页查询登记列表(查,仓库隔离自动注入)。
*
* @param {Object} data 请求体。
* @param {Object} [data.pagination] 分页参数。
* @param {Object} [data.where] 筛选条件。
* @param {Object} [data.sort] 排序参数。
* @return {Promise<Object>} 统一 success 包装。
*/
async list(data = {}) {
const { service } = this;
const { pagination, sort } = data;
const { where } = this.prepareWhereContext(data, {});
// 仓库隔离:由服务端从当前上下文自动注入,禁止前端传入
const warehouseId = Number(this.ctx.user && this.ctx.user.store_id || 0);
const enforcedWhere = { ...where };
if (warehouseId > 0) {
enforcedWhere.warehouse_id = { operator: 'eq', value: warehouseId };
}
return this._call(
() => service.systems.returnWaybill.list(enforcedWhere, pagination, sort),
'查询列表失败'
);
}
/**
* 查询单条登记详情(查)。
*
* @param {Object} data 请求体。
* @param {number} data.id 登记记录ID。
* @return {Promise<Object>} 统一 success 包装。
*/
async detail(data = {}) {
const { id } = data;
return this._call(() => this.service.systems.returnWaybill.detail(Number(id)), '查询详情失败');
}
/**
* 删除单条登记(删)。
*
* @param {Object} data 请求体。
* @param {number} data.id 登记记录ID。
* @return {Promise<Object>} 统一 success 包装。
*/
async delete(data = {}) {
const { id } = data;
return this._call(() => this.service.systems.returnWaybill.delete(Number(id)), '删除失败');
}
}
module.exports = ReturnWaybillMethodService;

View File

@ -26,12 +26,11 @@ class configService extends MainService {
* @param {Object} [data.where] 筛选条件
* @param {boolean} [data.filterDepleted=false] 是否过滤掉无可再用量的收货单(所有明细已被其他入库单 committed 绑定占满)
* @param {number} [data.entry_order_id] 可选,按入库单商品交集过滤:只返回"至少有一条明细的 system_product_id 在入库单明细中"的收货单
* @param {string} [data.stock_query_where] 可选,按商品条码/商品编码/商品ID搜索,返回明细中含匹配商品的收货单
* @return {Promise<Object>} 统一成功包装响应
*/
async getReceivingList(data) {
const { service } = this;
const { pagination, sort, filterDepleted = false, entry_order_id: entryOrderId, stock_query_where: stockQueryWhere } = data;
const { pagination, sort, filterDepleted = false, entry_order_id: entryOrderId } = data;
const { where } = this.prepareWhereContext(data, {
specialFieldMap: {
quickWhere: {
@ -39,7 +38,7 @@ class configService extends MainService {
},
},
});
const result = await service.systems.storage.receiving.getReceivingList(where, pagination, sort, { filterDepleted, entry_order_id: entryOrderId, stock_query_where: stockQueryWhere });
const result = await service.systems.storage.receiving.getReceivingList(where, pagination, sort, { filterDepleted, entry_order_id: entryOrderId });
return this.success('ok', result);
}
@ -50,12 +49,11 @@ class configService extends MainService {
* @param {Object} [data.pagination] 分页参数
* @param {Object} [data.where] 筛选条件
* @param {Object} [data.sort] 排序参数
* @param {string|string[]} [data.stock_query_where] 可选,按商品条码/商品编码/商品ID搜索,返回明细中含匹配商品的收货单
* @return {Promise<Object>} 统一成功包装响应
*/
async getStoreReceivingList(data) {
const { ctx, app } = this;
const { pagination, sort, stock_query_where: stockQueryWhere } = data;
const { pagination, sort } = data;
// 从平台激活上下文获取 store_id(使用原生查询避免 AccountPlatformActive 无 id 列兼容问题)
const platformRows = await app.model.query(
@ -87,8 +85,7 @@ class configService extends MainService {
where,
storeId,
pagination,
sort,
{ stock_query_where: stockQueryWhere }
sort
);
return this.success('ok', result);

View File

@ -421,202 +421,202 @@ class AfterSaleService extends Service {
ctx.logger.info(`[_resolveOrderDetail] 找到订单 id=${orderDeliveryId} code=${order.delivery_order_code} status=${order.status}`);
// 2. 构建收件人信息
const recipient = {
name: order.name || '',
tel: order.tel || '',
mobile: order.mobile || '',
email: order.email || '',
zip_code: order.zip_code || '',
country: order.country_code || '',
province: order.province || '',
city: order.city || '',
district: order.district || '',
town: order.town || '',
address: order.detail_address || '',
};
// 2. 构建收件人信息
const recipient = {
name: order.name || '',
tel: order.tel || '',
mobile: order.mobile || '',
email: order.email || '',
zip_code: order.zip_code || '',
country: order.country_code || '',
province: order.province || '',
city: order.city || '',
district: order.district || '',
town: order.town || '',
address: order.detail_address || '',
};
// 3. 构建发件人信息(从货主 subject_config 中取)
let sender = null;
if (order.store_id) {
try {
const store = await ctx.model.Store.findOne({
where: { id: order.store_id },
attributes: [ 'id', 'subject_config', 'company_name' ],
raw: true,
});
if (store) {
let subjectConfig = store.subject_config;
if (typeof subjectConfig === 'string') {
try { subjectConfig = JSON.parse(subjectConfig); } catch { subjectConfig = {}; }
}
sender = {
name: (subjectConfig && subjectConfig.sender_name) || store.company_name || '',
tel: (subjectConfig && subjectConfig.sender_tel) || '',
province: (subjectConfig && subjectConfig.province_name) || '',
city: (subjectConfig && subjectConfig.city_name) || '',
district: (subjectConfig && subjectConfig.district_name) || '',
town: (subjectConfig && subjectConfig.town_name) || '',
address: (subjectConfig && subjectConfig.address) || '',
};
}
} catch (err) {
ctx.logger.warn(`[_resolveOrderDetail] 查询发件人信息失败: ${err.message}`);
}
}
// 4. 订单明细(优先 order.items JSON,为空时回退到分表查询)
let orderItems = [];
if (order.items) {
try {
const parsed = typeof order.items === 'string' ? JSON.parse(order.items) : order.items;
orderItems = Array.isArray(parsed) ? parsed : [];
} catch {
// items 解析失败,忽略
}
}
// 回退:若 items 为空且 OrderItemsFactory 可用,从分表查询
if (orderItems.length === 0 && ctx.model.OrderItemsFactory) {
try {
const itemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId);
if (itemsModel) {
const dbItems = await itemsModel.findAll({
where: { order_id: orderDeliveryId },
raw: true,
});
if (dbItems && dbItems.length > 0) {
// 收集 stock_id 用于批量查库存详情
const stockIds = dbItems
.map(item => Number(item.stock_id))
.filter(id => Number.isInteger(id) && id > 0);
// 批量获取库存详情(带缓存的并行查询:条码 + 图片 + 库存属性)
const stockDetailsMap = new Map();
if (stockIds.length > 0) {
try {
const details = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, {
warehouseId,
cacheTTL: 300,
});
for (const detail of details) {
stockDetailsMap.set(detail.id, detail);
}
} catch (err) {
ctx.logger.warn(`[_resolveOrderDetail] 批量获取库存详情失败: ${err.message}`);
}
}
orderItems = dbItems.map(item => {
const stock = stockDetailsMap.get(Number(item.stock_id)) || {};
return {
id: item.id,
order_line_no: item.order_line_no || '',
item_code: item.item_code || stock.item_code || '',
item_name: item.item_name || stock.item_name || '',
sku_property: stock.sku_property || '',
quantity: stock.quantity || 0,
locked_quantity: stock.locked_quantity || 0,
is_batch_mgmt: stock.is_batch_mgmt || 'N',
is_shelf_life_mgmt: stock.is_shelf_life_mgmt || 'N',
is_images: stock.is_images || 'N',
store_id: stock.store_id || null,
packing_requirements: stock.packing_requirements || '',
stock_unit: stock.stock_unit || '',
image_url: stock.image_url || [],
barcodes: stock.barcodes || [],
plan_qty: item.plan_qty || 0,
stock_id: item.stock_id || null,
order_item_id: item.id,
order_id: orderDeliveryId,
};
});
ctx.logger.info(`[_resolveOrderDetail] 从分表加载 ${orderItems.length} 条明细(含库存详情)`);
}
}
} catch (err) {
ctx.logger.warn(`[_resolveOrderDetail] 分表查询商品明细失败: ${err.message}`);
}
}
// 5. 打包视频
const packVideos = [];
// 3. 构建发件人信息(从货主 subject_config 中取)
let sender = null;
if (order.store_id) {
try {
const packTasks = await ctx.model.PackTask.findAll({
where: { order_id: orderDeliveryId, deleted_at: null },
include: [
{
model: ctx.model.PackTaskVideo,
as: 'videos',
where: { deleted_at: null },
required: false,
},
],
order: [[ 'create_time', 'DESC' ]],
raw: false,
const store = await ctx.model.Store.findOne({
where: { id: order.store_id },
attributes: [ 'id', 'subject_config', 'name' ],
raw: true,
});
for (const task of packTasks) {
const taskJson = task.toJSON ? task.toJSON() : task;
const videos = (taskJson.videos || []).map(v => ({
id: v.id,
video_url: v.video_url,
camera_id: v.camera_id,
status: v.status,
created_at: v.created_at ? app.formatDate(v.created_at) : null,
}));
packVideos.push({
pack_task_id: taskJson.id,
status: taskJson.status,
pack_quantity: taskJson.pack_quantity,
start_time: taskJson.start_time ? app.formatDate(taskJson.start_time) : null,
end_time: taskJson.end_time ? app.formatDate(taskJson.end_time) : null,
operator_text: taskJson.operator_text || '',
videos,
});
if (store) {
let subjectConfig = store.subject_config;
if (typeof subjectConfig === 'string') {
try { subjectConfig = JSON.parse(subjectConfig); } catch { subjectConfig = {}; }
}
sender = {
name: (subjectConfig && subjectConfig.sender_name) || store.name || '',
tel: (subjectConfig && subjectConfig.sender_tel) || '',
province: (subjectConfig && subjectConfig.province_name) || '',
city: (subjectConfig && subjectConfig.city_name) || '',
district: (subjectConfig && subjectConfig.district_name) || '',
town: (subjectConfig && subjectConfig.town_name) || '',
address: (subjectConfig && subjectConfig.address) || '',
};
}
} catch (err) {
ctx.logger.warn(`[_resolveOrderDetail] 查询打包视频失败: ${err.message}`);
ctx.logger.warn(`[_resolveOrderDetail] 查询发件人信息失败: ${err.message}`);
}
}
// 6. 组装返回
return {
id: order.id,
delivery_order_code: order.delivery_order_code || '',
warehouse_id: order.warehouse_id,
store_id: order.store_id,
// 重量(g)
items_weight: order.items_weight || 0,
// 波次
wave_id: order.wave_id || 0,
wave_no: order.wave_no || '',
// 来源
platform_name: order.source_platform_name || '',
source_order_codes: order.source_order_codes || '',
// 创建来源渠道
create_channel: order.create_channel || '',
create_channel_label: this._getCreateChannelLabel(order.create_channel),
// 状态机
sync_status: order.sync_status || 'padding',
inspection_status: order.inspection_status || 'none',
storage_status: order.storage_status || 'none',
post_status: order.post_status || 'none',
print_status: order.print_status || 'none',
pick_status: order.pick_status || 'none',
pack_status: order.pack_status || 'none',
intercept_status: order.intercept_status || 'none',
// 数量
items_count: order.items_count,
items_total: order.items_total,
// 金额
total_amount: order.total_amount,
item_amount: order.item_amount,
// 收件人 / 发件人 / 明细 / 打包视频
recipient,
sender,
items: orderItems,
pack_videos: packVideos,
};
// 4. 订单明细(优先 order.items JSON,为空时回退到分表查询)
let orderItems = [];
if (order.items) {
try {
const parsed = typeof order.items === 'string' ? JSON.parse(order.items) : order.items;
orderItems = Array.isArray(parsed) ? parsed : [];
} catch {
// items 解析失败,忽略
}
}
// 回退:若 items 为空且 OrderItemsFactory 可用,从分表查询
if (orderItems.length === 0 && ctx.model.OrderItemsFactory) {
try {
const itemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId);
if (itemsModel) {
const dbItems = await itemsModel.findAll({
where: { order_id: orderDeliveryId },
raw: true,
});
if (dbItems && dbItems.length > 0) {
// 收集 stock_id 用于批量查库存详情
const stockIds = dbItems
.map(item => Number(item.stock_id))
.filter(id => Number.isInteger(id) && id > 0);
// 批量获取库存详情(带缓存的并行查询:条码 + 图片 + 库存属性)
let stockDetailsMap = new Map();
if (stockIds.length > 0) {
try {
const details = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, {
warehouseId,
cacheTTL: 300,
});
for (const detail of details) {
stockDetailsMap.set(detail.id, detail);
}
} catch (err) {
ctx.logger.warn(`[_resolveOrderDetail] 批量获取库存详情失败: ${err.message}`);
}
}
orderItems = dbItems.map(item => {
const stock = stockDetailsMap.get(Number(item.stock_id)) || {};
return {
id: item.id,
order_line_no: item.order_line_no || '',
item_code: item.item_code || stock.item_code || '',
item_name: item.item_name || stock.item_name || '',
sku_property: stock.sku_property || '',
quantity: stock.quantity || 0,
locked_quantity: stock.locked_quantity || 0,
is_batch_mgmt: stock.is_batch_mgmt || 'N',
is_shelf_life_mgmt: stock.is_shelf_life_mgmt || 'N',
is_images: stock.is_images || 'N',
store_id: stock.store_id || null,
packing_requirements: stock.packing_requirements || '',
stock_unit: stock.stock_unit || '',
image_url: stock.image_url || [],
barcodes: stock.barcodes || [],
plan_qty: item.plan_qty || 0,
stock_id: item.stock_id || null,
order_item_id: item.id,
order_id: orderDeliveryId,
};
});
ctx.logger.info(`[_resolveOrderDetail] 从分表加载 ${orderItems.length} 条明细(含库存详情)`);
}
}
} catch (err) {
ctx.logger.warn(`[_resolveOrderDetail] 分表查询商品明细失败: ${err.message}`);
}
}
// 5. 打包视频
let packVideos = [];
try {
const packTasks = await ctx.model.PackTask.findAll({
where: { order_id: orderDeliveryId, deleted_at: null },
include: [
{
model: ctx.model.PackTaskVideo,
as: 'videos',
where: { deleted_at: null },
required: false,
},
],
order: [[ 'create_time', 'DESC' ]],
raw: false,
});
for (const task of packTasks) {
const taskJson = task.toJSON ? task.toJSON() : task;
const videos = (taskJson.videos || []).map(v => ({
id: v.id,
video_url: v.video_url,
camera_id: v.camera_id,
status: v.status,
created_at: v.created_at ? app.formatDate(v.created_at) : null,
}));
packVideos.push({
pack_task_id: taskJson.id,
status: taskJson.status,
pack_quantity: taskJson.pack_quantity,
start_time: taskJson.start_time ? app.formatDate(taskJson.start_time) : null,
end_time: taskJson.end_time ? app.formatDate(taskJson.end_time) : null,
operator_text: taskJson.operator_text || '',
videos,
});
}
} catch (err) {
ctx.logger.warn(`[_resolveOrderDetail] 查询打包视频失败: ${err.message}`);
}
// 6. 组装返回
return {
id: order.id,
delivery_order_code: order.delivery_order_code || '',
warehouse_id: order.warehouse_id,
store_id: order.store_id,
// 重量(g)
items_weight: order.items_weight || 0,
// 波次
wave_id: order.wave_id || 0,
wave_no: order.wave_no || '',
// 来源
platform_name: order.source_platform_name || '',
source_order_codes: order.source_order_codes || '',
// 创建来源渠道
create_channel: order.create_channel || '',
create_channel_label: this._getCreateChannelLabel(order.create_channel),
// 状态机
sync_status: order.sync_status || 'padding',
inspection_status: order.inspection_status || 'none',
storage_status: order.storage_status || 'none',
post_status: order.post_status || 'none',
print_status: order.print_status || 'none',
pick_status: order.pick_status || 'none',
pack_status: order.pack_status || 'none',
intercept_status: order.intercept_status || 'none',
// 数量
items_count: order.items_count,
items_total: order.items_total,
// 金额
total_amount: order.total_amount,
item_amount: order.item_amount,
// 收件人 / 发件人 / 明细 / 打包视频
recipient,
sender,
items: orderItems,
pack_videos: packVideos,
};
} catch (err) {
ctx.logger.warn(`[_resolveOrderDetail] 整体异常 id=${orderDeliveryId}: ${err.message}`, err.stack);
return null;
@ -1063,7 +1063,7 @@ class AfterSaleService extends Service {
if (safeStatus === 'pending_feedback') {
const hours = await this._resolveFollowupHours(afterSale.warehouse_id, afterSale.type, afterSale.sub_type);
ctx.logger.info(
'[handleWorkOrder] id=%s warehouse=%s type=%s subType=%s hours=%d',
`[handleWorkOrder] id=%s warehouse=%s type=%s subType=%s hours=%d`,
id, afterSale.warehouse_id, afterSale.type, afterSale.sub_type, hours
);
// 使用数据库 NOW() 确保与查询条件时区一致
@ -1293,7 +1293,7 @@ class AfterSaleService extends Service {
});
ctx.logger.info(
'[_resolveFollowupHours] warehouseId=%s type=%s subType=%s hasStoreWarehouse=%s',
`[_resolveFollowupHours] warehouseId=%s type=%s subType=%s hasStoreWarehouse=%s`,
warehouseId, type, subType, !!(sw && sw.policy_config)
);
@ -1304,14 +1304,14 @@ class AfterSaleService extends Service {
}
const whConfig = config && config.after_sale_followup_hours;
ctx.logger.info(
'[_resolveFollowupHours] whConfig type=%s value=%s',
`[_resolveFollowupHours] whConfig type=%s value=%s`,
typeof whConfig, JSON.stringify(whConfig)
);
if (whConfig && typeof whConfig === 'object') {
const whTypeMap = whConfig[type];
ctx.logger.info(
'[_resolveFollowupHours] whTypeMap for type=%s: %s',
`[_resolveFollowupHours] whTypeMap for type=%s: %s`,
type, JSON.stringify(whTypeMap)
);
@ -1320,13 +1320,13 @@ class AfterSaleService extends Service {
if (subType) {
const subVal = this._tryParseHours(whTypeMap[subType]);
if (typeof subVal === 'number' && subVal >= MIN_VALID_FOLLOWUP_HOURS) {
ctx.logger.info('[_resolveFollowupHours] MATCH subType (nested): %s=%dh', subType, subVal);
ctx.logger.info(`[_resolveFollowupHours] MATCH subType (nested): %s=%dh`, subType, subVal);
return subVal;
}
}
const defVal = this._tryParseHours(whTypeMap._default);
if (typeof defVal === 'number' && defVal >= MIN_VALID_FOLLOWUP_HOURS) {
ctx.logger.info('[_resolveFollowupHours] MATCH type._default (nested): %s._default=%dh', type, defVal);
ctx.logger.info(`[_resolveFollowupHours] MATCH type._default (nested): %s._default=%dh`, type, defVal);
return defVal;
}
}
@ -1335,7 +1335,7 @@ class AfterSaleService extends Service {
// 值为字符串或数字,直接作为该 type 下所有 subType 的统一时长
const flatVal = this._tryParseHours(whTypeMap);
if (typeof flatVal === 'number' && flatVal >= MIN_VALID_FOLLOWUP_HOURS) {
ctx.logger.info('[_resolveFollowupHours] MATCH type flat: %s=%dh', type, flatVal);
ctx.logger.info(`[_resolveFollowupHours] MATCH type flat: %s=%dh`, type, flatVal);
return flatVal;
}
}
@ -1343,7 +1343,7 @@ class AfterSaleService extends Service {
{
const globalVal = this._tryParseHours(whConfig);
if (typeof globalVal === 'number' && globalVal >= MIN_VALID_FOLLOWUP_HOURS) {
ctx.logger.info('[_resolveFollowupHours] MATCH whConfig global: %dh', globalVal);
ctx.logger.info(`[_resolveFollowupHours] MATCH whConfig global: %dh`, globalVal);
return globalVal;
}
}
@ -1360,17 +1360,17 @@ class AfterSaleService extends Service {
const typeDefault = DEFAULTS[type];
if (typeDefault) {
if (subType && typeof typeDefault[subType] === 'number') {
ctx.logger.info('[_resolveFollowupHours] DEFAULTS subType match: %s=%dh', subType, typeDefault[subType]);
ctx.logger.info(`[_resolveFollowupHours] DEFAULTS subType match: %s=%dh`, subType, typeDefault[subType]);
return typeDefault[subType];
}
if (typeof typeDefault._default === 'number') {
ctx.logger.info('[_resolveFollowupHours] DEFAULTS type._default: %s=%dh', type, typeDefault._default);
ctx.logger.info(`[_resolveFollowupHours] DEFAULTS type._default: %s=%dh`, type, typeDefault._default);
return typeDefault._default;
}
}
// 3. 硬兜底
ctx.logger.warn('[_resolveFollowupHours] FALLBACK 24h for type=%s subType=%s', type, subType);
ctx.logger.warn(`[_resolveFollowupHours] FALLBACK 24h for type=%s subType=%s`, type, subType);
return 24;
}
@ -1474,7 +1474,7 @@ class AfterSaleService extends Service {
);
ctx.logger.info(
'[batchSetPendingFeedback] id=%s type=%s subType=%s hours=%d',
`[batchSetPendingFeedback] id=%s type=%s subType=%s hours=%d`,
record.id, record.type, record.sub_type, hours
);

View File

@ -71,12 +71,7 @@ class ReturnReceivedService extends Service {
if (existing) {
const enriched = await this._enrichReturn(existing);
return {
record: enriched,
is_original_return: Boolean(enriched.order_express_id),
store_remark: enriched.store_remark || '',
duplicated: true,
};
return { ...enriched, duplicated: true };
}
// 反查原运单,判定是否原单退回
@ -132,12 +127,7 @@ class ReturnReceivedService extends Service {
const createdRow = created && typeof created.toJSON === 'function' ? created.toJSON() : created;
const enriched = await this._enrichReturn(createdRow);
return {
record: enriched,
is_original_return: Boolean(enriched.order_express_id),
store_remark: enriched.store_remark || '',
duplicated: false,
};
return { ...enriched, duplicated: false };
}
/**

File diff suppressed because it is too large Load Diff

View File

@ -1,371 +0,0 @@
'use strict';
const Service = require('egg').Service;
/**
* 运单退回登记模块业务逻辑层。
* 复用 wms_return_query_log 表,提供「货主 + 运单号」退回登记的增删查改。
* 所有数据库交互集中在此层,供 systemMethods/returnWaybill.js 调用。
*/
class ReturnWaybillService 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;
}
/**
* 运单退回登记(增)。入参:运单号 + 货主ID。
* 同 warehouse_id + store_id + waybill_code 已存在时返回已有记录(幂等)。
*
* @param {Object} params 登记参数。
* @param {string} params.waybill_code 运单号(必填)。
* @param {number} params.store_id 货主ID(必填)。
* @param {string} [params.remark] 备注。
* @return {Promise<Object>} { record, duplicated }。
*/
async create({ waybill_code, store_id, remark }) {
const { ctx } = this;
const waybillCode = String(waybill_code || '').trim();
if (!waybillCode) {
throw this.createBusinessError('waybill_code 不能为空', 400);
}
const storeId = Number(store_id || 0);
if (!Number.isFinite(storeId) || storeId <= 0) {
throw this.createBusinessError('store_id 必填且必须为正整数', 400);
}
const warehouseId = Number(ctx.user && ctx.user.store_id || 0);
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
throw this.createBusinessError('缺少仓库上下文', 400);
}
// 货主合约校验:wms_store_warehouse 存在 store_id + warehouse_id 合约
await this._assertStoreContract(storeId, warehouseId);
// 幂等:同仓库+货主+运单号已存在 → 返回已有记录
const existing = await ctx.model.ReturnQueryLog.findOne({
where: {
warehouse_id: warehouseId,
store_id: storeId,
waybill_code: waybillCode,
},
order: [[ 'id', 'ASC' ]],
raw: true,
});
if (existing) {
return { record: this._formatRow(existing), duplicated: true };
}
const created = await ctx.model.ReturnQueryLog.create({
warehouse_id: warehouseId,
store_id: storeId,
waybill_code: waybillCode,
remark: remark ? String(remark).slice(0, 500) : null,
is_notified: 0,
is_back: 0,
});
const createdRow = created && typeof created.toJSON === 'function' ? created.toJSON() : created;
return { record: this._formatRow(createdRow), duplicated: false };
}
/**
* 修改登记(改)。入参:id + 可改运单号/货主ID/备注。
*
* @param {Object} params 修改参数。
* @param {number} params.id 登记记录ID(必填)。
* @param {string} [params.waybill_code] 运单号。
* @param {number} [params.store_id] 货主ID。
* @param {string} [params.remark] 备注。
* @return {Promise<Object>} { record }。
*/
async update({ id, waybill_code, store_id, remark }) {
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
const record = await this._findByIdChecked(id);
const updateFields = {};
const nextWaybillCode = waybill_code !== undefined && waybill_code !== null
? String(waybill_code).trim()
: record.waybill_code;
if (!nextWaybillCode) {
throw this.createBusinessError('waybill_code 不能为空', 400);
}
const nextStoreId = store_id !== undefined && store_id !== null
? Number(store_id)
: Number(record.store_id);
if (!Number.isFinite(nextStoreId) || nextStoreId <= 0) {
throw this.createBusinessError('store_id 必填且必须为正整数', 400);
}
if (waybill_code !== undefined && waybill_code !== null) {
updateFields.waybill_code = nextWaybillCode;
}
if (store_id !== undefined && store_id !== null && Number(store_id) !== Number(record.store_id)) {
// 货主变更时校验新货主合约
await this._assertStoreContract(nextStoreId, record.warehouse_id);
updateFields.store_id = nextStoreId;
}
if (remark !== undefined && remark !== null) {
updateFields.remark = String(remark).slice(0, 500);
}
// 冲突防护:改后与另一条同仓库+货主+运单号冲突则拒绝
const changed = Object.keys(updateFields).length > 0;
if (changed) {
const conflict = await ctx.model.ReturnQueryLog.findOne({
where: {
warehouse_id: record.warehouse_id,
store_id: nextStoreId,
waybill_code: nextWaybillCode,
id: { [Op.ne]: record.id },
},
attributes: [ 'id' ],
raw: true,
});
if (conflict) {
throw this.createBusinessError('已存在相同货主 + 运单号的登记记录', 409);
}
await ctx.model.ReturnQueryLog.update(updateFields, {
where: { id: record.id },
});
}
const updated = await ctx.model.ReturnQueryLog.findOne({
where: { id: record.id },
raw: true,
});
return { record: this._formatRow(updated) };
}
/**
* 分页查询登记列表(仓库隔离由方法层注入 warehouse_id)。
*
* @param {Object} where 标准化 where 条件对象。
* @param {Object} [pagination] 分页参数。
* @param {Object} [sort] 排序参数。
* @return {Promise<Object>} { list, pagination }。
*/
async list(where = {}, pagination = {}, sort = {}) {
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 queryWhere = this._buildListWhere(where, Op);
const order = this._buildListOrder(sort);
const { count, rows } = await ctx.model.ReturnQueryLog.findAndCountAll({
where: queryWhere,
order,
offset: (page - 1) * pageSize,
limit: pageSize,
raw: true,
});
return {
list: rows.map(row => this._formatRow(row)),
pagination: {
page,
pageSize,
total: count,
totalPages: Math.ceil(count / pageSize),
hasPrevious: page > 1,
hasNext: page * pageSize < count,
},
};
}
/**
* 查询单条登记详情。
*
* @param {number} id 登记记录ID。
* @return {Promise<Object>} { record }。
*/
async detail(id) {
const record = await this._findByIdChecked(id);
return { record: this._formatRow(record) };
}
/**
* 删除单条登记(物理删除)。
*
* @param {number} id 登记记录ID。
* @return {Promise<Object>} 删除结果,含被删除记录 id。
*/
async delete(id) {
const { ctx } = this;
const record = await this._findByIdChecked(id);
await ctx.model.ReturnQueryLog.destroy({ where: { id: record.id } });
return { id: record.id };
}
// ===========================
// 辅助方法
// ===========================
/**
* 按主键查询登记记录,并校验仓库隔离。
*
* @param {number} id 登记记录ID。
* @return {Promise<Object>} 登记记录原始数据。
*/
async _findByIdChecked(id) {
const { ctx } = this;
const normalizedId = Number(id || 0);
if (!Number.isFinite(normalizedId) || normalizedId <= 0) {
throw this.createBusinessError('id 必填且必须为正整数', 400);
}
const record = await ctx.model.ReturnQueryLog.findOne({
where: { id: normalizedId },
raw: true,
});
if (!record) {
throw this.createBusinessError('登记记录不存在', 404);
}
const warehouseId = Number(ctx.user && ctx.user.store_id || 0);
if (warehouseId > 0 && Number(record.warehouse_id) !== warehouseId) {
throw this.createBusinessError('无权访问该登记记录', 403);
}
return record;
}
/**
* 货主合约校验:wms_store_warehouse 必须存在 store_id + warehouse_id 合约。
*
* @param {number} storeId 货主ID。
* @param {number} warehouseId 仓库ID。
* @return {Promise<void>} 校验失败抛业务异常。
*/
async _assertStoreContract(storeId, warehouseId) {
const { ctx } = this;
const contract = await ctx.model.StoreWarehouse.findOne({
where: { store_id: storeId, warehouse_id: warehouseId },
attributes: [ 'id' ],
raw: true,
});
if (!contract) {
throw this.createBusinessError('货主在当前仓库无合约关系,无法登记', 400);
}
}
/**
* 格式化登记记录(时间字段本地化)。
*
* @param {Object} row 登记记录原始数据。
* @return {Object} 格式化后的记录。
*/
_formatRow(row) {
const { app } = this;
const record = { ...row };
record.created_at = record.created_at ? app.formatDate(record.created_at) : null;
record.updated_at = record.updated_at ? app.formatDate(record.updated_at) : null;
return record;
}
/**
* 根据标准化 where 条件构建 Sequelize 查询条件。
*
* @param {Object} where 标准化 where 条件对象。
* @param {Object} Op Sequelize Op 对象。
* @return {Object} Sequelize where 条件。
*/
_buildListWhere(where = {}, Op) {
const queryWhere = {};
const fields = [
'warehouse_id', 'store_id', 'waybill_code',
'is_notified', 'is_back', 'created_at', 'updated_at',
];
for (const field of fields) {
if (where[field] !== undefined && where[field] !== null) {
queryWhere[field] = this._resolveConditionValue(where[field], Op);
}
}
return queryWhere;
}
/**
* 解析标准化条件值为 Sequelize 可用的条件对象。
*
* @param {*} condition 标准化条件(可能是 {operator, value} 或直接值)。
* @param {Object} Op Sequelize Op 对象。
* @return {*} Sequelize 条件。
*/
_resolveConditionValue(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 数组。
*/
_buildListOrder(sort = {}) {
const sortField = sort.sortField || sort.sort_field || 'created_at';
const sortOrderRaw = (sort.sortOrder || sort.sort_order || 'desc').toLowerCase();
const sortOrder = sortOrderRaw === 'asc' ? 'ASC' : 'DESC';
const allowedSortFields = new Set([ 'id', 'created_at', 'updated_at', 'waybill_code' ]);
const safeSortField = allowedSortFields.has(sortField) ? sortField : 'created_at';
return [[ safeSortField, sortOrder ]];
}
}
module.exports = ReturnWaybillService;

View File

@ -47,7 +47,6 @@ class ReceivingService extends Service {
* @param {Object} [options] 额外选项
* @param {boolean} [options.filterDepleted=false] 是否过滤掉无可再用量的收货单
* @param {number} [options.entry_order_id] 可选,按入库单商品交集过滤:只返回"至少有一条明细的 system_product_id 在入库单明细中"的收货单
* @param {string|string[]} [options.stock_query_where] 可选,按商品维度过滤:搜索条码/商品编码/商品ID,返回明细中含匹配商品的收货单(支持字符串或字符串数组,多个关键字取并集)
* @return {Promise<Object>} 列表、分页与汇总信息
*/
async getReceivingList(where, pageParams = {}, sortParams = {}, options = {}) {
@ -71,7 +70,7 @@ class ReceivingService extends Service {
sortField = 'id',
sortOrder = 'DESC',
} = sortParams;
const { filterDepleted = false, entry_order_id: entryOrderId, stock_query_where: stockQueryWhere } = options;
const { filterDepleted = false, entry_order_id: entryOrderId } = options;
const queryOptions = {
where: {
@ -302,23 +301,18 @@ class ReceivingService extends Service {
}
}
// 可选过滤:按 stock_query_where(商品条码/编码/ID)过滤,支持字符串或字符串数组
let stockQueryFilteredIds = null;
const stockQueryKeywords = Array.isArray(stockQueryWhere)
? stockQueryWhere.map(v => String(v).trim()).filter(Boolean)
: (typeof stockQueryWhere === 'string' && stockQueryWhere.trim() !== '' ? [ stockQueryWhere.trim() ] : []);
if (stockQueryKeywords.length > 0) {
stockQueryFilteredIds = await this._resolveStockQueryReceivingIds(stockQueryKeywords);
}
// 合并 filterDepleted / entry_order_id / stock_query_where 的过滤结果(多组启用时取交集)
// 合并 filterDepleted 和 entry_order_id 的过滤结果
let combinedFilteredIds = null;
const idFilterSets = [ filteredReceivingIds, intersectionFilteredIds, stockQueryFilteredIds ]
.filter(arr => arr !== null)
.map(arr => new Set(arr));
if (idFilterSets.length > 0) {
const [ first, ...rest ] = idFilterSets;
combinedFilteredIds = [ ...first ].filter(id => rest.every(set => set.has(id)));
if (filteredReceivingIds !== null || intersectionFilteredIds !== null) {
if (filteredReceivingIds !== null && intersectionFilteredIds !== null) {
// 两个过滤都启用 → 取交集
const intersectionSet = new Set(intersectionFilteredIds);
combinedFilteredIds = filteredReceivingIds.filter(id => intersectionSet.has(id));
} else if (filteredReceivingIds !== null) {
combinedFilteredIds = filteredReceivingIds;
} else {
combinedFilteredIds = intersectionFilteredIds;
}
}
// 如果启用了过滤,用过滤后的 ID 做最终查询
@ -410,7 +404,7 @@ class ReceivingService extends Service {
conditions: normalizedWhere,
sortField: actualSortField,
sortOrder: actualSortOrder,
hasBarcodeSearch: stockQueryKeywords.length > 0,
hasBarcodeSearch: false,
},
},
message: '查询成功',
@ -440,70 +434,6 @@ class ReceivingService extends Service {
};
}
}
/**
* 按商品关键字解析收货单 ID 列表。
* 搜索范围:
* 1) wms_stock_warehouse.item_code(商品编码)模糊匹配
* 2) wms_stock_warehouse.id 精确匹配(关键字为纯数字时)
* 3) wms_stock_barcodes.barcode(条码)模糊匹配
* 再通过 wms_receiving_detail.system_product_id 关联回收货单。
* @param {string|string[]} keywords 搜索关键字(字符串或字符串数组,多个关键字取并集)
* @return {Promise<number[]|null>} 收货单 ID 数组;关键字为空返回 null
*/
async _resolveStockQueryReceivingIds(keywords) {
const { ctx, app } = this;
const { Sequelize } = app;
const { Op } = Sequelize;
const keywordList = (Array.isArray(keywords) ? keywords : [ keywords ])
.map(v => String(v).trim())
.filter(Boolean);
if (keywordList.length === 0) return null;
const stockIds = new Set();
// 1. 商品编码 / 商品ID 匹配(wms_stock_warehouse)
const stockWhere = {
[Op.or]: keywordList.map(k => ({ item_code: { [Op.like]: `%${k}%` } })),
};
keywordList.forEach(k => {
if (/^\d+$/.test(k)) {
stockWhere[Op.or].push({ id: Number(k) });
}
});
const stockRows = await ctx.model.StockWarehouse.findAll({
attributes: [ 'id' ],
where: stockWhere,
raw: true,
});
stockRows.forEach(row => stockIds.add(Number(row.id)));
// 2. 条码匹配(wms_stock_barcodes → stock_id)
const barcodeRows = await ctx.model.StockBarcode.findAll({
attributes: [ 'stock_id' ],
where: {
[Op.or]: keywordList.map(k => ({ barcode: { [Op.like]: `%${k}%` } })),
},
raw: true,
});
barcodeRows.forEach(row => stockIds.add(Number(row.stock_id)));
if (stockIds.size === 0) return [];
// 3. 通过明细表关联回收货单
const detailRows = await ctx.model.ReceivingDetail.findAll({
attributes: [ 'receiving_id' ],
where: {
system_product_id: { [Op.in]: [ ...stockIds ] },
},
group: [ 'receiving_id' ],
raw: true,
});
return [ ...new Set(detailRows.map(row => row.receiving_id)) ];
}
/**
* 货主侧收货单列表查询。
* 以 store_id 为维度查询收货单,支持分页、多条件筛选与排序。
@ -515,17 +445,14 @@ class ReceivingService extends Service {
* @param {Object} [sortParams] 排序参数
* @param {string} [sortParams.sortField='created_at'] 排序字段
* @param {string} [sortParams.sortOrder='DESC'] 排序方向
* @param {Object} [options] 额外选项
* @param {string|string[]} [options.stock_query_where] 可选,按商品维度过滤:搜索条码/商品编码/商品ID,返回明细中含匹配商品的收货单(支持字符串或字符串数组,多个关键字取并集)
* @return {Promise<Object>} 列表、分页与汇总信息
*/
async getStoreReceivingList(where, storeId, pageParams = {}, sortParams = {}, options = {}) {
async getStoreReceivingList(where, storeId, pageParams = {}, sortParams = {}) {
const { ctx, app } = this;
const { Sequelize } = app;
const { Op } = Sequelize;
const { page = 1, pageSize = 20 } = pageParams;
const { sortField = 'created_at', sortOrder = 'DESC' } = sortParams;
const { stock_query_where: stockQueryWhere } = options;
try {
const queryOptions = {
@ -595,27 +522,13 @@ class ReceivingService extends Service {
const offset = (page - 1) * pageSize;
// 可选过滤:按 stock_query_where(商品条码/编码/ID)过滤,支持字符串或字符串数组
let stockQueryFilteredIds = null;
const stockQueryKeywords = Array.isArray(stockQueryWhere)
? stockQueryWhere.map(v => String(v).trim()).filter(Boolean)
: (typeof stockQueryWhere === 'string' && stockQueryWhere.trim() !== '' ? [ stockQueryWhere.trim() ] : []);
if (stockQueryKeywords.length > 0) {
stockQueryFilteredIds = await this._resolveStockQueryReceivingIds(stockQueryKeywords);
}
const finalWhere = stockQueryFilteredIds !== null
? { id: { [Op.in]: stockQueryFilteredIds } }
: queryOptions.where;
const [ total, data ] = await Promise.all([
ctx.model.Receiving.count({
where: finalWhere,
where: queryOptions.where,
distinct: true,
}),
ctx.model.Receiving.findAll({
...queryOptions,
where: finalWhere,
limit: Number(pageSize),
offset: Number(offset),
distinct: true,
@ -698,7 +611,7 @@ class ReceivingService extends Service {
conditions: normalizedWhere,
sortField: actualSortField,
sortOrder: actualSortOrder,
hasBarcodeSearch: stockQueryKeywords.length > 0,
hasBarcodeSearch: false,
},
},
message: '查询成功',

View File

@ -1,145 +0,0 @@
'use strict';
/**
* 创建退回拆包主表 wms_return_unpack。
*
* 字段:仓库隔离 warehouse_id、拆包单号 unpack_no(RP+YYYYMMDD+6位序号)、
* 关联退回收到单 return_received_id(非必填)、运单号 waybill_code、拆包日期 unpack_date、
* 起止时间 start_time/end_time、拆包人 unpacker_id/unpacker_name、状态 status/detail_status、
* 汇总 total_items/total_quantity、原单关联 order_express_id/order_id/store_id(非必填)、
* 摄像头列表 camera_ids(JSON)、备注 remark。
*
* 索引:
* uk_unpack_no(单号唯一)
* idx_warehouse_unpack_date(仓库+日期隔离查询)
* idx_return_received_id / idx_waybill_code / idx_order_express_id
* idx_unpacker_id / idx_start_time / idx_store_id
*/
const TABLE_NAME = 'wms_return_unpack';
module.exports = {
// eslint-disable-next-line no-unused-vars
async up(queryInterface, Sequelize) {
const { BIGINT, STRING, INTEGER, DATE } = Sequelize;
await queryInterface.createTable(TABLE_NAME, {
id: {
type: BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键',
},
warehouse_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '仓库ID(数据隔离维度)',
},
unpack_no: {
type: STRING(50),
allowNull: false,
comment: '拆包单号,RP+YYYYMMDD+6位序号',
},
return_received_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '关联退回收到表 wms_return_received.id;非必填',
},
waybill_code: {
type: STRING(50),
allowNull: false,
comment: '拆包的运单号(退回包裹运单号)',
},
unpack_date: {
type: DATE,
allowNull: false,
comment: '拆包日期',
},
start_time: {
type: DATE,
allowNull: true,
comment: '拆包开始时间',
},
end_time: {
type: DATE,
allowNull: true,
comment: '拆包结束时间',
},
unpacker_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '拆包人员工号ID(employees_id)',
},
unpacker_name: {
type: STRING(50),
allowNull: false,
comment: '拆包人员工号名称快照(employees_name / real_name)',
},
status: {
type: STRING(20),
allowNull: false,
defaultValue: 'unpacking',
comment: '拆包状态:unpacking/completed/cancelled',
},
detail_status: {
type: STRING(30),
allowNull: false,
defaultValue: 'none_recognized',
comment: '明细识别状态:none_recognized/partial_recognized/all_recognized',
},
total_items: {
type: INTEGER(11),
allowNull: false,
defaultValue: 0,
comment: '物品种类数(明细行数)',
},
total_quantity: {
type: INTEGER(11),
allowNull: false,
defaultValue: 0,
comment: '物品总数量(明细数量合计)',
},
order_express_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '原运单ID,关联 wms_order_express.id;原单退回时回填',
},
order_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '原订单ID,便于快速匹配;原单退回时回填',
},
store_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '货主ID,原单退回/识别到系统商品时回填',
},
camera_ids: {
type: Sequelize.JSON,
allowNull: true,
comment: '摄像头ID列表,如 [1,2,3](参考 wms_pack_task.device_ids)',
},
remark: {
type: STRING(500),
allowNull: true,
comment: '备注',
},
created_at: { type: DATE, allowNull: false },
updated_at: { type: DATE, allowNull: false },
});
await queryInterface.addIndex(TABLE_NAME, [ 'unpack_no' ], { unique: true, name: 'uk_unpack_no' });
await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'unpack_date' ], { name: 'idx_warehouse_unpack_date' });
await queryInterface.addIndex(TABLE_NAME, [ 'return_received_id' ], { name: 'idx_return_received_id' });
await queryInterface.addIndex(TABLE_NAME, [ 'waybill_code' ], { name: 'idx_waybill_code' });
await queryInterface.addIndex(TABLE_NAME, [ 'order_express_id' ], { name: 'idx_order_express_id' });
await queryInterface.addIndex(TABLE_NAME, [ 'unpacker_id' ], { name: 'idx_unpacker_id' });
await queryInterface.addIndex(TABLE_NAME, [ 'start_time' ], { name: 'idx_start_time' });
await queryInterface.addIndex(TABLE_NAME, [ 'store_id' ], { name: 'idx_store_id' });
},
// eslint-disable-next-line no-unused-vars
async down(queryInterface, Sequelize) {
await queryInterface.dropTable(TABLE_NAME);
},
};

View File

@ -1,110 +0,0 @@
'use strict';
/**
* 创建退回拆包明细表 wms_return_unpack_detail。
*
* 字段:关联主表 unpack_id、仓库冗余 warehouse_id、扫描条码 barcode(可空,仅记录)、
* 系统商品 stock_id(可空,关联 wms_stock_warehouse.id)、识别标记 is_recognized、
* 快照 item_code/item_name/spec/product_snapshot、数量 quantity、产品状态 product_status、备注 remark。
*
* 索引:
* idx_unpack_id(按拆包单查明细,最高频)
* idx_warehouse_barcode(仓库+条码)
* idx_stock_id(按系统商品反查)
* idx_barcode(按条码查询)
*
* 说明:同一拆包单内可能多次扫描同一条码,明细不设 barcode 唯一约束。
*/
const TABLE_NAME = 'wms_return_unpack_detail';
module.exports = {
// eslint-disable-next-line no-unused-vars
async up(queryInterface, Sequelize) {
const { BIGINT, STRING, INTEGER, DATE, TEXT, TINYINT } = Sequelize;
await queryInterface.createTable(TABLE_NAME, {
id: {
type: BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键',
},
unpack_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '关联拆包主表 wms_return_unpack.id',
},
warehouse_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '仓库ID(冗余,隔离查询)',
},
barcode: {
type: STRING(100),
allowNull: true,
comment: '扫描条码(前端可选传入,仅作记录;后端不用于识别)',
},
stock_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '关联 wms_stock_warehouse.id;识别到系统商品时回填,非识别为空',
},
is_recognized: {
type: TINYINT(1),
allowNull: false,
defaultValue: 0,
comment: '是否识别:1=识别到系统商品,0=非识别物品',
},
item_code: {
type: STRING(50),
allowNull: true,
comment: '商品编码快照(识别时回填)',
},
item_name: {
type: STRING(255),
allowNull: true,
comment: '物品名称(识别时回填;非识别时可手工补录)',
},
spec: {
type: STRING(100),
allowNull: true,
comment: '规格快照(sku_property)',
},
quantity: {
type: INTEGER(11),
allowNull: false,
defaultValue: 1,
comment: '数量',
},
product_status: {
type: STRING(20),
allowNull: false,
defaultValue: 'normal',
comment: '产品状态:normal-正常,damaged-破损',
},
product_snapshot: {
type: TEXT,
allowNull: true,
comment: '商品信息快照(JSON),识别时回填,防止商品资料变更后历史丢失',
},
remark: {
type: STRING(500),
allowNull: true,
comment: '备注',
},
created_at: { type: DATE, allowNull: false },
updated_at: { type: DATE, allowNull: false },
});
await queryInterface.addIndex(TABLE_NAME, [ 'unpack_id' ], { name: 'idx_unpack_id' });
await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'barcode' ], { name: 'idx_warehouse_barcode' });
await queryInterface.addIndex(TABLE_NAME, [ 'stock_id' ], { name: 'idx_stock_id' });
await queryInterface.addIndex(TABLE_NAME, [ 'barcode' ], { name: 'idx_barcode' });
},
// eslint-disable-next-line no-unused-vars
async down(queryInterface, Sequelize) {
await queryInterface.dropTable(TABLE_NAME);
},
};

View File

@ -1,66 +0,0 @@
'use strict';
/**
* 创建退回拆包视频记录表 wms_return_unpack_video(参考 wms_pack_task_video)。
*
* 字段:关联主表 unpack_id、摄像头 camera_id(非必填)、视频地址 video_url、状态 status、
* 备注 remark、软删除 deleted_at(paranoid)。
*
* 索引:idx_unpack_id(按拆包单查视频)、idx_camera_id(按摄像头反查)、idx_deleted_at(软删除优化)。
*/
const TABLE_NAME = 'wms_return_unpack_video';
module.exports = {
// eslint-disable-next-line no-unused-vars
async up(queryInterface, Sequelize) {
const { BIGINT, STRING, DATE, ENUM } = Sequelize;
await queryInterface.createTable(TABLE_NAME, {
id: {
type: BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键ID',
},
unpack_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '关联拆包主表 wms_return_unpack.id',
},
camera_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '摄像头设备ID,关联 wms_camera.id',
},
video_url: {
type: STRING(500),
allowNull: false,
comment: '视频地址(录像回放URL)',
},
status: {
type: ENUM('created', 'recording', 'completed', 'failed'),
allowNull: false,
defaultValue: 'created',
comment: '状态:created/recording/completed/failed',
},
remark: {
type: STRING(500),
allowNull: true,
comment: '备注',
},
created_at: { type: DATE, allowNull: false },
updated_at: { type: DATE, allowNull: false },
deleted_at: { type: DATE, allowNull: true, comment: '软删除时间' },
});
await queryInterface.addIndex(TABLE_NAME, [ 'unpack_id' ], { name: 'idx_unpack_id' });
await queryInterface.addIndex(TABLE_NAME, [ 'camera_id' ], { name: 'idx_camera_id' });
await queryInterface.addIndex(TABLE_NAME, [ 'deleted_at' ], { name: 'idx_deleted_at' });
},
// eslint-disable-next-line no-unused-vars
async down(queryInterface, Sequelize) {
await queryInterface.dropTable(TABLE_NAME);
},
};

View File

@ -1,75 +0,0 @@
'use strict';
/**
* 创建退回查询记录表 wms_return_query_log。
*
* 用途:登记「货主未退回、但做过查询退回」的运单号,仓库 + 货主隔离。
* 创建拆包单未命中原单时,据此反查运单号对应的货主并回写 store_id(限最近 3 个月内登记)。
* is_back / is_notified 供定时任务扫描拆包通知;拆包单提交确认时更新 is_back=1。
*
* 索引:
* idx_warehouse_store_waybill(仓库+货主+运单号,核心)
* idx_warehouse_store(仓库+货主隔离查询)
* idx_waybill_code(按运单号查询)
*/
const TABLE_NAME = 'wms_return_query_log';
module.exports = {
// eslint-disable-next-line no-unused-vars
async up(queryInterface, Sequelize) {
const { BIGINT, STRING, DATE, TINYINT } = Sequelize;
await queryInterface.createTable(TABLE_NAME, {
id: {
type: BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键',
},
warehouse_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '仓库ID(隔离维度)',
},
store_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '货主ID(隔离维度)',
},
waybill_code: {
type: STRING(50),
allowNull: false,
comment: '查询过的运单号',
},
remark: {
type: STRING(500),
allowNull: true,
comment: '备注',
},
is_notified: {
type: TINYINT(1),
allowNull: false,
defaultValue: 0,
comment: '是否已通知:0=未通知,1=已通知',
},
is_back: {
type: TINYINT(1),
allowNull: false,
defaultValue: 0,
comment: '是否退回:0=未退回,1=已退回',
},
created_at: { type: DATE, allowNull: false },
updated_at: { type: DATE, allowNull: false },
});
await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'store_id', 'waybill_code' ], { name: 'idx_warehouse_store_waybill' });
await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'store_id' ], { name: 'idx_warehouse_store' });
await queryInterface.addIndex(TABLE_NAME, [ 'waybill_code' ], { name: 'idx_waybill_code' });
},
// eslint-disable-next-line no-unused-vars
async down(queryInterface, Sequelize) {
await queryInterface.dropTable(TABLE_NAME);
},
};

View File

@ -1,119 +0,0 @@
'use strict';
/**
* 退回拆包模块权限记录 + 角色授权迁移。
*
* 权限明细(固定 ID 540-549,550 预留):
* 540 — returnUnpack.create API:退回拆包开单
* 541 — returnUnpack.addDetail API:退回拆包录明细
* 542 — returnUnpack.updateDetail API:退回拆包更新明细
* 543 — returnUnpack.removeDetail API:退回拆包移除明细
* 544 — returnUnpack.cancel API:退回拆包取消
* 545 — returnUnpack.submit API:退回拆包提交确认
* 546 — returnUnpack.list API:退回拆包列表查询
* 547 — returnUnpack.detailList API:退回拆包明细列表
* 548 — returnUnpack.detail API:退回拆包详情
* 549 — returnUnpack.delete API:退回拆包删除
*
* 角色授权(系统预设角色,不含通配符角色):
* 作业类(540-545)→ 仓库组-员工(27) → 仓库组-主管(26)(仓库员工及以上)
* 查询/删除类(546-549)→ 客服组-员工(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 = {
540: [ 27, 26 ],
541: [ 27, 26 ],
542: [ 27, 26 ],
543: [ 27, 26 ],
544: [ 27, 26 ],
545: [ 27, 26 ],
546: [ 30, 28 ],
547: [ 30, 28 ],
548: [ 30, 28 ],
549: [ 30, 28 ],
};
module.exports = {
// eslint-disable-next-line no-unused-vars
async up(queryInterface, Sequelize) {
// ── 1. 创建 API 权限记录(固定 ID)──
const apis = [
[ 540, 'returnUnpack.create', 'API:退回拆包开单' ],
[ 541, 'returnUnpack.addDetail', 'API:退回拆包录明细' ],
[ 542, 'returnUnpack.updateDetail', 'API:退回拆包更新明细' ],
[ 543, 'returnUnpack.removeDetail', 'API:退回拆包移除明细' ],
[ 544, 'returnUnpack.cancel', 'API:退回拆包取消' ],
[ 545, 'returnUnpack.submit', 'API:退回拆包提交确认' ],
[ 546, 'returnUnpack.list', 'API:退回拆包列表查询' ],
[ 547, 'returnUnpack.detailList', 'API:退回拆包明细列表' ],
[ 548, 'returnUnpack.detail', 'API:退回拆包详情' ],
[ 549, 'returnUnpack.delete', 'API:退回拆包删除' ],
];
for (const [ id, path, metaTitle ] of apis) {
await queryInterface.sequelize.query(
`INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`,
{ replacements: [ id, path, null, path, null, metaTitle, null, 0, 0, null, 'api', 0, 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) {
const ids = [ 540, 541, 542, 543, 544, 545, 546, 547, 548, 549 ];
const placeholders = ids.map(() => '?').join(', ');
await queryInterface.sequelize.query(
`DELETE FROM \`${TABLE}\` WHERE id IN (${placeholders})`,
{ replacements: ids }
);
},
};

View File

@ -1,118 +0,0 @@
'use strict';
/**
* 补齐 wms_order_delivery 基表相对模型缺失的 25 列。
*
* 背景:app/model/order_delivery.js 声明 92 个字段,但基表只有 67 列,
* 缺列导致按模型全字段 SELECT(如 afterSale._resolveOrderDetail 先查基表)时
* 报 Unknown column 'extend_props' 等错误。
* 分表(wms_order_delivery_100000 等)均已有这些列,本迁移以分表结构为参照补齐基表。
*
* 修复后 afterSale._resolveOrderDetail 查基表不再抛错(查无数据时回退工厂分表)。
*/
const TABLE_NAME = 'wms_order_delivery';
/** 缺失列定义(类型/是否可空/默认值/注释),与分表结构一致 */
const MISSING_COLUMNS = [
{ name: 'extend_props', type: 'JSON', allowNull: true, defaultValue: null, comment: '订单扩展属性' },
{ name: 'create_channel', type: 'STRING(20)', allowNull: false, defaultValue: 'MANUAL', comment: '创建来源渠道' },
{ name: 'sys_platform_code', type: 'STRING(50)', allowNull: true, defaultValue: null, comment: '系统平台编码' },
{ name: 'sys_platform_name', type: 'STRING(200)', allowNull: true, defaultValue: null, comment: '系统平台名称' },
{ name: 'buyer_message', type: 'STRING(500)', allowNull: true, defaultValue: null, comment: '买家留言' },
{ name: 'seller_message', type: 'STRING(500)', allowNull: true, defaultValue: null, comment: '卖家留言' },
{ name: 'remark', type: 'STRING(500)', allowNull: true, defaultValue: null, comment: '备注' },
{ name: 'sys_logistics_code', type: 'STRING(50)', allowNull: true, defaultValue: null, comment: '系统物流公司编码' },
{ name: 'sys_logistics_name', type: 'STRING(200)', allowNull: true, defaultValue: null, comment: '系统物流公司名称' },
{ name: 'basket_number', type: 'STRING(50)', allowNull: true, defaultValue: null, comment: '筐号' },
{ name: 'from_key', type: 'INTEGER(11)', allowNull: true, defaultValue: null, comment: '来源键' },
{ name: 'items', type: 'TEXT', allowNull: true, defaultValue: null, comment: '商品JSON字符串' },
{ name: 'items_count', type: 'SMALLINT(5).UNSIGNED', allowNull: false, defaultValue: 0, comment: '商品种类数' },
{ name: 'items_total', type: 'INTEGER(10).UNSIGNED', allowNull: false, defaultValue: 0, comment: '商品总数' },
{ name: 'items_weight', type: 'INTEGER(11)', allowNull: false, defaultValue: 0, comment: '总重量(g)' },
{ name: 'items_hash', type: 'CHAR(32)', allowNull: false, defaultValue: '', comment: 'MD5哈希值(32位)' },
{ name: 'items_crc', type: 'INTEGER(10).UNSIGNED', allowNull: false, defaultValue: 0, comment: 'CRC32校验码' },
{ name: 'wave_id', type: 'BIGINT(20)', allowNull: false, defaultValue: 0, comment: '波次ID,0表示未分配' },
{ name: 'wave_no', type: 'STRING(50)', allowNull: false, defaultValue: '', comment: '波次号,空字符串表示未分配' },
{ name: 'wave_strategy_version', type: 'INTEGER(10)', allowNull: false, defaultValue: 0, comment: '波次策略版本号' },
{ name: 'wave_scan_result', type: 'INTEGER(10)', allowNull: false, defaultValue: 0, comment: '波次扫描结果,0未扫描' },
{ name: 'sended_status', type: 'ENUM', enumValues: [ 'none', 'padding', 'fin', 'error' ], allowNull: true, defaultValue: 'none', comment: '发货状态机' },
{ name: 'recheck_status', type: 'STRING(20)', allowNull: true, defaultValue: 'none', comment: '复核状态' },
{ name: 'recheck_time', type: 'DATE', allowNull: true, defaultValue: null, comment: '复核时间' },
{ name: 'print_lock_status', type: 'ENUM', enumValues: [ 'none', 'warehouse' ], allowNull: true, defaultValue: 'none', comment: '打印锁定状态机' },
];
/**
* 将列定义转为 Sequelize 字段描述。
*
* @param {Object} Sequelize Sequelize 构造器。
* @param {Object} def 列定义(name/type/allowNull/defaultValue/comment)。
* @return {Object} Sequelize addColumn 字段描述。
*/
function toColumnDef(Sequelize, def) {
let type;
if (def.type === 'ENUM') {
type = Sequelize.ENUM(...def.enumValues);
} else if (def.type === 'JSON') {
type = Sequelize.JSON;
} else if (def.type === 'DATE') {
type = Sequelize.DATE;
} else if (def.type === 'TEXT') {
type = Sequelize.TEXT;
} else if (def.type === 'CHAR(32)') {
type = Sequelize.CHAR(32);
} else {
const match = def.type.match(/^([A-Z]+)(?:\(([^)]+)\))?(?:\.([A-Z]+))?$/);
if (!match) {
throw new Error(`无法解析列类型: ${def.type}`);
}
const base = match[1];
const args = match[2] ? match[2].split(',').map(s => Number(s.trim())) : [];
const unsigned = Boolean(match[3] && match[3] === 'UNSIGNED');
switch (base) {
case 'STRING':
type = Sequelize.STRING(args[0]);
break;
case 'INTEGER':
type = Sequelize.INTEGER(args[0]);
break;
case 'BIGINT':
type = Sequelize.BIGINT(args[0]);
break;
case 'SMALLINT':
type = Sequelize.SMALLINT(args[0]);
break;
default:
throw new Error(`无法解析列类型: ${def.type}`);
}
if (unsigned) {
type = type.UNSIGNED;
}
}
const columnDef = {
type,
allowNull: def.allowNull,
comment: def.comment,
};
if (def.defaultValue !== null && def.defaultValue !== undefined) {
columnDef.defaultValue = def.defaultValue;
}
return columnDef;
}
module.exports = {
// eslint-disable-next-line no-unused-vars
async up(queryInterface, Sequelize) {
for (const def of MISSING_COLUMNS) {
await queryInterface.addColumn(TABLE_NAME, def.name, toColumnDef(Sequelize, def));
}
},
// eslint-disable-next-line no-unused-vars
async down(queryInterface, Sequelize) {
for (const def of MISSING_COLUMNS) {
await queryInterface.removeColumn(TABLE_NAME, def.name);
}
},
};

View File

@ -1,63 +0,0 @@
'use strict';
/**
* 创建业务单号序列表 wms_number_sequence。
*
* 用途:按「仓库 + 业务类型 + 日期」维度原子分配单号序号,
* 取代「查当日最大序号+1」的并发撞号方案。
* 取号 SQL:INSERT ... ON DUPLICATE KEY UPDATE current_seq = LAST_INSERT_ID(current_seq + 1)
* (同连接内再 SELECT LAST_INSERT_ID() 取回本次分配序号)。
*
* 索引:uk_warehouse_biz_date(仓库+业务类型+日期 唯一,原子取号的幂等键)。
*/
const TABLE_NAME = 'wms_number_sequence';
module.exports = {
// eslint-disable-next-line no-unused-vars
async up(queryInterface, Sequelize) {
const { BIGINT, STRING, INTEGER, CHAR, DATE } = Sequelize;
await queryInterface.createTable(TABLE_NAME, {
id: {
type: BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键',
},
warehouse_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '仓库ID(序号隔离维度)',
},
biz_type: {
type: STRING(30),
allowNull: false,
comment: '业务类型,如 return_unpack(退回拆包单号)',
},
date_part: {
type: CHAR(8),
allowNull: false,
comment: '日期片段 YYYYMMDD',
},
current_seq: {
type: INTEGER(11),
allowNull: false,
defaultValue: 0,
comment: '当前已分配序号(原子递增)',
},
created_at: { type: DATE, allowNull: false },
updated_at: { type: DATE, allowNull: false },
});
await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'biz_type', 'date_part' ], {
unique: true,
name: 'uk_warehouse_biz_date',
});
},
// eslint-disable-next-line no-unused-vars
async down(queryInterface, Sequelize) {
await queryInterface.dropTable(TABLE_NAME);
},
};

View File

@ -1,104 +0,0 @@
'use strict';
/**
* 运单退回登记模块权限记录 + 角色授权迁移。
*
* 权限明细(固定 ID 551-555,550 预留):
* 551 — returnWaybill.create API:运单退回登记
* 552 — returnWaybill.update API:运单退回登记修改
* 553 — returnWaybill.list API:运单退回登记列表
* 554 — returnWaybill.detail API:运单退回登记详情
* 555 — returnWaybill.delete API:运单退回登记删除
*
* 角色授权(系统预设角色,不含通配符角色):
* 作业类(551-552)→ 仓库组-员工(27) → 仓库组-主管(26)(仓库员工及以上)
* 查询/删除类(553-555)→ 客服组-员工(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 = {
551: [ 27, 26 ],
552: [ 27, 26 ],
553: [ 30, 28 ],
554: [ 30, 28 ],
555: [ 30, 28 ],
};
module.exports = {
// eslint-disable-next-line no-unused-vars
async up(queryInterface, Sequelize) {
// ── 1. 创建 API 权限记录(固定 ID)──
const apis = [
[ 551, 'returnWaybill.create', 'API:运单退回登记' ],
[ 552, 'returnWaybill.update', 'API:运单退回登记修改' ],
[ 553, 'returnWaybill.list', 'API:运单退回登记列表' ],
[ 554, 'returnWaybill.detail', 'API:运单退回登记详情' ],
[ 555, 'returnWaybill.delete', 'API:运单退回登记删除' ],
];
for (const [ id, path, metaTitle ] of apis) {
await queryInterface.sequelize.query(
`INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`,
{ replacements: [ id, path, null, path, null, metaTitle, null, 0, 0, null, 'api', 0, 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) {
const ids = [ 551, 552, 553, 554, 555 ];
const placeholders = ids.map(() => '?').join(', ');
await queryInterface.sequelize.query(
`DELETE FROM \`${TABLE}\` WHERE id IN (${placeholders})`,
{ replacements: ids }
);
},
};

View File

@ -1,21 +1,4 @@
[
{
"version": "2026.08.13-stockQueryWhere",
"date": "2026-08-13",
"type": "added",
"summary": "storage.receiving.getReceivingList / getStoreReceivingList 新增 stock_query_where 参数:按商品条码/商品编码/商品ID 搜索,经收货明细关联过滤收货单列表(仓库侧与货主侧同步支持)",
"methods": [
"storage.receiving.getReceivingList",
"storage.receiving.getStoreReceivingList"
],
"notes": [
"新增 stock_query_where 入参(string|string[], optional, body,前端通常传数组),搜索范围:wms_stock_barcodes.barcode + wms_stock_warehouse.item_code + wms_stock_warehouse.id(纯数字时精确匹配)",
"解析链路:stock_query_where → wms_stock_warehouse.id 集合 → wms_receiving_detail.system_product_id IN 集合 → receiving_id 列表",
"与 filterDepleted、entry_order_id 可组合使用(多组过滤取交集,仓库侧),无匹配结果时返回空列表",
"代码变更:systems/storage/receiving.js 新增 _resolveStockQueryReceivingIds 并对两个列表方法注入过滤;systemMethods/storage/receiving.js 两个列表方法均透传 stock_query_where;methods/system.json 两个接口均新增参数文档"
],
"module": "storage"
},
{
"version": "2026.08.12-confirmIntercept-doc",
"date": "2026-08-12",
@ -5792,129 +5775,5 @@
"代码变更:app/model/return_received.js、app/service/systems/return_received.js、app/service/systemMethods/returnReceived.js、database/migrations/20260812160000-create-wms-return-received.js、20260813100000-create-return-received-permissions.js"
],
"module": "returnReceived"
},
{
"version": "2026.08.13-shops-GetAuthorizeSessionKey-doc-sync",
"date": "2026-08-13",
"type": "updated",
"summary": "同步 shops.GetAuthorizeSessionKey 文档:实现已切换为调用授权服务 saveShop 换取授权会话,旧的 PDD/CAINIAO 预占码方案已下线。",
"methods": [
"shops.GetAuthorizeSessionKey"
],
"notes": [
"实现:按店铺 platform_code 取 wms_print_platform.get_auth_platform_name 作为 platName,POST 授权服务 saveShop,携带 RedirectCodeUrl/shopName;京东平台附 VenderID,视频号平台改传 appId/toUserName 且不带 RedirectCodeUrl",
"成功后更新店铺 access_token=sessionKey、status=1,返回 data.message='获取授权成功';上游 code≠0 或未返回 sessionKey 时抛 500",
"文档更新:移除旧 data.session_key/authorize_url/state 返回结构与 501 未实现错误,补充 appId/toUserName 入参及 shop_id/callbackurl/platform_code 校验错误码",
"仅文档同步,不修改业务代码"
],
"module": "shops"
},
{
"version": "2026.08.13-interceptScan-non-intercept-guard",
"date": "2026-08-13",
"type": "updated",
"summary": "order.recheckOrder.interceptScan 增加非拦截订单前置校验:运单不存在或未发起系统拦截时直接拒绝并提示「非拦截订单」,移除原先自动创建运单补充记录的逻辑。",
"methods": [
"order.recheckOrder.interceptScan"
],
"notes": [
"校验规则:运单记录不存在即拒绝;运单 is_intercept≠'Y' 时回查关联订单,intercept_status 不在 requested/intercepting 也拒绝,提示「非拦截订单」",
"校验通过后原逻辑不变:标记 is_back='Y'/is_intercept='Y'、处理未完结售后工单、订单级更新 intercepted_at_warehouse 并释放储位分配与订单锁",
"移除运单不存在时自动创建补充记录的分支(未发起拦截的运单不再被静默置为拦截)",
"同步更新 JSDoc 与 methods/system.json 文档,错误码新增 400 非拦截订单"
],
"module": "order.recheckOrder"
},
{
"version": "2026.08.13-returnUnpack",
"date": "2026-08-13",
"type": "added",
"summary": "新增退回拆包模块(returnUnpack):开拆包单、录明细、更新明细、移除明细、取消、提交确认、分页列表、明细列表、详情、删除十个接口。开单反查原运单判定原单退回并回填货主,未命中原单时按 warehouse_id+waybill_code 从退回查询记录反查货主;拆包单号 RP+YYYYMMDD+6位序号;状态机 unpacking/completed/cancelled;明细识别状态 none_recognized/partial_recognized/all_recognized;全接口仓库隔离(服务端注入 warehouse_id)。配套权限 540-549(作业类→仓库员工及以上,查询/删除类→客服员工及以上,detail 免权限复用列表权限)",
"methods": [
"returnUnpack.create",
"returnUnpack.addDetail",
"returnUnpack.updateDetail",
"returnUnpack.removeDetail",
"returnUnpack.cancel",
"returnUnpack.submit",
"returnUnpack.list",
"returnUnpack.detailList",
"returnUnpack.detail",
"returnUnpack.delete"
],
"notes": [
"新增表 wms_return_unpack(主表)/ wms_return_unpack_detail(明细)/ wms_return_unpack_video(视频,paranoid 软删)/ wms_return_query_log(退回查询记录)",
"returnUnpack.create:waybill_code 必填;反查 wms_order_express.waybill_code 命中则回填 order_express_id/order_id/store_id 并返回原订单详情(复用 afterSale._resolveOrderDetail);未命中再从 wms_return_query_log 按 warehouse_id+waybill_code 反查货主(限最近 3 个月内登记);返回 id/record/is_original_return/store_remark/order",
"returnUnpack.addDetail:主单非终态校验;stock_id 有值 → 查 wms_stock_warehouse 校验货主归属(不一致 403)+ 回填 is_recognized=1 与快照;主表 store_id 为空时以首个识别商品回填货主;写明细后重算 total_items/total_quantity/detail_status",
"returnUnpack.updateDetail:白名单仅 quantity/remark;仅 quantity 变更时重算主表汇总",
"returnUnpack.removeDetail:明细表 paranoid:false 硬删除 + 重算主表汇总",
"returnUnpack.cancel:仅 unpacking 状态;事务内硬删主表+明细,软删视频",
"returnUnpack.submit:仅 unpacking;status=completed + 回写 end_time,并同步更新 wms_return_query_log.is_back=1(失败不阻断主流程)",
"returnUnpack.list:主表分页,仓库隔离服务端注入 warehouse_id;where 支持 unpack_no/waybill_code 模糊、unpack_date/start_time/end_time 范围、status/detail_status/unpacker_id/return_received_id/store_id/order_express_id/order_id 等值",
"returnUnpack.detailList:明细分页 + stockWarehouse 关联(命中时);where 支持 unpack_id/stock_id/barcode/is_recognized/product_status",
"returnUnpack.detail:主表 + details(stockWarehouse) + videos(camera) + returnReceived;原单退回时返回 related.order;免权限仅登录 + 仓库隔离",
"returnUnpack.delete:后台删除不限状态;事务物理删主表+明细,软删视频",
"仓库隔离:全部接口禁止前端传入 warehouse_id,由服务端注入 ctx.user.store_id;拆包单号规则 RP+YYYYMMDD+6位序号(仓库维度序号)",
"权限:540 returnUnpack.create、541 addDetail、542 updateDetail、543 removeDetail、544 cancel、545 submit(仓库员工及以上);546 list、547 detailList、548 detail、549 delete(客服员工及以上);detail 免权限(复用列表权限)",
"代码变更:app/model/return_unpack.js、return_unpack_detail.js、return_unpack_video.js、return_query_log.js;app/service/systems/return_unpack.js;app/service/systemMethods/returnUnpack.js;database/migrations/20260813120000-20260813120300 建表、20260813130000 权限"
],
"module": "returnUnpack"
},
{
"version": "2026.08.13-returnReceived.createResponse",
"date": "2026-08-13",
"type": "updated",
"summary": "returnReceived.create 出参结构调整:由平铺返回登记字段改为包装结构 { record, is_original_return, store_remark, duplicated },record 含登记记录完整字段与派生字段 is_original_return/store_remark,与代码实现(app/service/systems/return_received.js)及设计文档对齐",
"methods": [
"returnReceived.create"
],
"notes": [
"原出参平铺 id/waybill_code/scan_date/scanner_id/scanner_name/order_express_id/order_id/store_id/remark/is_original_return/store_remark/duplicated,现改为四个顶层字段:record(object,必填)、is_original_return(boolean,必填)、store_remark(string,必填)、duplicated(boolean,必填)",
"record 内字段:id、waybill_code、scan_date、scanner_id、scanner_name、order_express_id、order_id、store_id、remark、created_at、updated_at(时间为格式化字符串)+ 派生字段 is_original_return、store_remark",
"顶层 is_original_return / store_remark / duplicated 为 record 之外独立返回字段,与 record 内同名字段取值一致",
"仅文档变更,代码实现已对齐(create 返回 { record, is_original_return, store_remark, duplicated },30日幂等命中与新建分支结构一致)"
],
"module": "returnReceived"
},
{
"version": "2026.08.13-returnWaybill",
"date": "2026-08-13",
"type": "added",
"summary": "新增运单退回登记模块(returnWaybill):复用 wms_return_query_log 表实现「货主 + 运单号」退回关系的增删查改五个接口(create/update/list/detail/delete)。create 校验货主合约并幂等返回已有记录;update 支持改运单号/货主/备注,改后冲突 409 拒绝;list 分页筛选(运单号模糊/货主/是否已通知/是否退回/登记时间范围);detail 免权限仅登录+仓库隔离;delete 物理删除。全接口仓库隔离(warehouse_id 服务端注入)。配套权限 551-555(作业类 create/update→仓库员工及以上,查询/删除类 list/detail/delete→客服员工及以上,detail 免权限复用列表权限)",
"methods": [
"returnWaybill.create",
"returnWaybill.update",
"returnWaybill.list",
"returnWaybill.detail",
"returnWaybill.delete"
],
"notes": [
"复用表 wms_return_query_log(20260813120300 迁移已落地):warehouse_id/store_id/waybill_code/remark/is_notified/is_back/created_at/updated_at;登记接口不维护 is_notified/is_back(由定时任务与拆包联动维护)",
"returnWaybill.create:waybill_code/store_id 必填;货主合约校验(wms_store_warehouse 存在 store_id+warehouse_id,无合约 400 拒绝);同仓库+货主+运单号已存在时幂等返回已有记录 duplicated=true;写入 is_notified=0/is_back=0",
"returnWaybill.update:id 必填;仓库隔离校验;waybill_code/store_id/remark 可选更新;store_id 变更时校验新货主合约;改后与另一条同仓库+货主+运单号冲突则 409 拒绝",
"returnWaybill.list:pagination(pageSize 上限 500 默认 20)+ where(waybill_code 模糊、store_id、is_notified、is_back、created_at 起止)+ sort(id/created_at/updated_at/waybill_code,默认 created_at desc)",
"returnWaybill.detail:免权限(复用列表权限),仅登录 + 仓库隔离校验",
"returnWaybill.delete:物理删除(表 paranoid:false),返回被删除记录 id",
"仓库隔离:所有接口 warehouse_id 由服务端注入 ctx.user.store_id,禁止前端传入",
"权限:551 create、552 update(仓库员工及以上);553 list、554 detail、555 delete(客服员工及以上);detail 免权限复用 list 权限",
"代码变更:app/service/systems/return_waybill.js、app/service/systemMethods/returnWaybill.js、database/migrations/20260813160000-create-return-waybill-permissions.js"
],
"module": "returnWaybill"
},
{
"version": "2026.08.13-returnUnpack.detailAuth",
"date": "2026-08-13",
"type": "updated",
"summary": "returnUnpack.detail 鉴权配置变更:不再免权限(原 _noNeedRight='detail'),改为走 API 权限校验(固定权限 ID 548,客服员工及以上),与 app/service/systemMethods/returnUnpack.js 实现对齐。",
"methods": [
"returnUnpack.detail"
],
"notes": [
"isNeedAuth:false → true;description 同步说明「需 548 权限(客服员工及以上)」",
"代码对齐:returnUnpack.js _noNeedRight 改为空字符串,detail 与其他接口一致走 API 权限校验",
"权限 548 为客服员工及以上(与原「查询类→客服员工及以上」设计一致)",
"仅文档同步,其余接口与模块不动"
],
"module": "returnUnpack"
}
]

File diff suppressed because it is too large Load Diff