feat: 新增退回拆包模块(returnUnpack)与序列表原子取号

- 新增 wms_return_unpack 主表/明细/视频 与 wms_return_query_log 表(model + 迁移)
- 新增序列表 wms_number_sequence,单号取号改为 INSERT...ON DUPLICATE KEY 原子递增(含历史 seed 对齐)
- 补齐 wms_order_delivery 基表缺失 25 列(修复 Unknown column)
- 权限固定 ID 540-549 + 角色授权迁移
- 修复 returnReceived.create 出参 record 包装;修复 afterSale 发件人查询列名(name→company_name)
- detail 接口按设计走 548 权限校验
This commit is contained in:
liufumingren 2026-08-13 21:40:50 +08:00
parent f4ed985556
commit 38b29be776
16 changed files with 2620 additions and 201 deletions

View File

@ -0,0 +1,55 @@
'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

@ -0,0 +1,65 @@
'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;
};

166
app/model/return_unpack.js Normal file
View File

@ -0,0 +1,166 @@
'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

@ -0,0 +1,111 @@
'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

@ -0,0 +1,89 @@
'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

@ -0,0 +1,219 @@
'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

@ -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', '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.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 },
// 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 (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}`);
}
if (store) {
let subjectConfig = store.subject_config;
if (typeof subjectConfig === 'string') {
try { subjectConfig = JSON.parse(subjectConfig); } catch { subjectConfig = {}; }
}
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} 条明细(含库存详情)`);
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 = [];
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}`);
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,
};
// 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,7 +71,12 @@ class ReturnReceivedService extends Service {
if (existing) {
const enriched = await this._enrichReturn(existing);
return { ...enriched, duplicated: true };
return {
record: enriched,
is_original_return: Boolean(enriched.order_express_id),
store_remark: enriched.store_remark || '',
duplicated: true,
};
}
// 反查原运单,判定是否原单退回
@ -127,7 +132,12 @@ class ReturnReceivedService extends Service {
const createdRow = created && typeof created.toJSON === 'function' ? created.toJSON() : created;
const enriched = await this._enrichReturn(createdRow);
return { ...enriched, duplicated: false };
return {
record: enriched,
is_original_return: Boolean(enriched.order_express_id),
store_remark: enriched.store_remark || '',
duplicated: false,
};
}
/**

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,145 @@
'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

@ -0,0 +1,110 @@
'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

@ -0,0 +1,66 @@
'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

@ -0,0 +1,75 @@
'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

@ -0,0 +1,119 @@
'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

@ -0,0 +1,118 @@
'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

@ -0,0 +1,63 @@
'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);
},
};