diff --git a/app/model/number_sequence.js b/app/model/number_sequence.js new file mode 100644 index 0000000..d6aab1e --- /dev/null +++ b/app/model/number_sequence.js @@ -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} 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; +}; diff --git a/app/model/return_query_log.js b/app/model/return_query_log.js new file mode 100644 index 0000000..ff693b9 --- /dev/null +++ b/app/model/return_query_log.js @@ -0,0 +1,65 @@ +'use strict'; + +/** + * 退回查询记录表模型(货主未退回、但做过查询退回的运单号)。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} 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; +}; diff --git a/app/model/return_unpack.js b/app/model/return_unpack.js new file mode 100644 index 0000000..60316b7 --- /dev/null +++ b/app/model/return_unpack.js @@ -0,0 +1,166 @@ +'use strict'; + +/** + * 退回拆包主表模型。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} 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; +}; diff --git a/app/model/return_unpack_detail.js b/app/model/return_unpack_detail.js new file mode 100644 index 0000000..91709e6 --- /dev/null +++ b/app/model/return_unpack_detail.js @@ -0,0 +1,111 @@ +'use strict'; + +/** + * 退回拆包明细表模型。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} 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; +}; diff --git a/app/model/return_unpack_video.js b/app/model/return_unpack_video.js new file mode 100644 index 0000000..4eb1219 --- /dev/null +++ b/app/model/return_unpack_video.js @@ -0,0 +1,89 @@ +'use strict'; + +/** + * 退回拆包视频记录表模型(参考 wms_pack_task_video)。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} 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; +}; diff --git a/app/service/systemMethods/returnUnpack.js b/app/service/systemMethods/returnUnpack.js new file mode 100644 index 0000000..39884be --- /dev/null +++ b/app/service/systemMethods/returnUnpack.js @@ -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} 统一 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} [data.camera_ids] 摄像头ID列表。 + * @param {number} [data.return_received_id] 关联退回收到单ID。 + * @param {string} [data.remark] 备注。 + * @return {Promise} 统一 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} 统一 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} 统一 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} 统一 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} 统一 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} 统一 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} 统一 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} 统一 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} 统一 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} 统一 success 包装。 + */ + async delete(data = {}) { + const { id } = data; + return this._call(() => this.service.systems.returnUnpack.delete(Number(id)), '删除失败'); + } +} + +module.exports = ReturnUnpackMethodService; diff --git a/app/service/systems/afterSale.js b/app/service/systems/afterSale.js index 048b311..3732ead 100644 --- a/app/service/systems/afterSale.js +++ b/app/service/systems/afterSale.js @@ -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 ); diff --git a/app/service/systems/return_received.js b/app/service/systems/return_received.js index bf9c192..d4f591d 100644 --- a/app/service/systems/return_received.js +++ b/app/service/systems/return_received.js @@ -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, + }; } /** diff --git a/app/service/systems/return_unpack.js b/app/service/systems/return_unpack.js new file mode 100644 index 0000000..413046c --- /dev/null +++ b/app/service/systems/return_unpack.js @@ -0,0 +1,1008 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * 退回拆包模块业务逻辑层。 + * 负责 wms_return_unpack(主表)/ wms_return_unpack_detail(明细)/ wms_return_unpack_video(视频)/ + * wms_return_query_log(退回查询记录)的增删查,以及原单反查、货主校验、单号生成等核心操作。 + * 所有数据库交互集中在此层,供 systemMethods/returnUnpack.js 调用。 + */ +class ReturnUnpackService 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; + } + + /** + * 开拆包单(明细不在此提交,由 addDetail 逐件录入)。 + * 用 waybill_code 反查原运单判定是否原单退回;未命中原单时再从退回查询记录表反查货主。 + * + * @param {Object} params 开单参数。 + * @param {string} params.waybill_code 拆包的运单号(必填)。 + * @param {Array} [params.camera_ids] 摄像头ID列表。 + * @param {number} [params.return_received_id] 关联退回收到单ID。 + * @param {string} [params.remark] 备注。 + * @return {Promise} 开单结果,含 id、record、is_original_return、store_remark、order。 + */ + async create({ waybill_code, camera_ids, return_received_id, remark }) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const waybillCode = String(waybill_code || '').trim(); + if (!waybillCode) { + throw this.createBusinessError('waybill_code 不能为空', 400); + } + + const warehouseId = Number(ctx.user && ctx.user.store_id || 0); + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少仓库上下文', 400); + } + + const unpackerId = ctx.user && ctx.user.employees_id ? Number(ctx.user.employees_id) : 0; + const unpackerName = String( + (ctx.user && ctx.user.employees_name) || (ctx.user && ctx.user.real_name) || '' + ).trim(); + + if (!Number.isFinite(unpackerId) || unpackerId <= 0) { + throw this.createBusinessError('缺少拆包人员工号上下文', 400); + } + + // 摄像头ID列表归一化 + let normalizedCameraIds = null; + if (Array.isArray(camera_ids)) { + normalizedCameraIds = camera_ids + .map(item => Number(item)) + .filter(id => Number.isInteger(id) && id > 0); + } + + // 1. 原单反查:命中则回填原单关联字段 + let orderExpressId = null; + let orderId = null; + let storeId = null; + try { + const orderExpress = await ctx.model.OrderExpress.findOne({ + where: { waybill_code: waybillCode }, + attributes: [ 'id', 'order_id', 'store_id' ], + raw: true, + }); + if (orderExpress) { + orderExpressId = orderExpress.id; + orderId = orderExpress.order_id; + storeId = orderExpress.store_id; + } + } catch (err) { + ctx.logger.warn(`[returnUnpack.create] 反查原运单失败: ${err.message}`); + } + + // 2. 未命中原单:从退回查询记录表反查货主(限最近 3 个月内登记,运单号可能被复用) + if (!orderExpressId) { + try { + const threeMonthsAgo = new Date(); + threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3); + const queryLog = await ctx.model.ReturnQueryLog.findOne({ + where: { + warehouse_id: warehouseId, + waybill_code: waybillCode, + created_at: { [Op.gte]: threeMonthsAgo }, + }, + attributes: [ 'store_id' ], + order: [[ 'created_at', 'DESC' ]], + raw: true, + }); + if (queryLog && queryLog.store_id) { + storeId = queryLog.store_id; + } + } catch (err) { + ctx.logger.warn(`[returnUnpack.create] 反查退回查询记录失败: ${err.message}`); + } + } + + const isOriginalReturn = Boolean(orderExpressId); + + // 3. 货主备注(原单退回 / 反查命中货主时) + const storeRemark = await this._resolveStoreRemark(storeId, warehouseId); + + // 4. 拆包日期/开始时间(单号在下方重试循环内生成) + const now = new Date(); + const unpackDate = app.formatDate(now, 'YYYY-MM-DD'); + + // 5. 插入主表(并发下撞 uk_unpack_no 唯一索引时重新取号重试,最多 5 次,指数退避+随机抖动) + const baseFields = { + warehouse_id: warehouseId, + return_received_id: return_received_id ? Number(return_received_id) || null : null, + waybill_code: waybillCode, + unpack_date: unpackDate, + start_time: now, + end_time: null, + unpacker_id: unpackerId, + unpacker_name: unpackerName || '未命名', + status: 'unpacking', + detail_status: 'none_recognized', + total_items: 0, + total_quantity: 0, + order_express_id: orderExpressId, + order_id: orderId, + store_id: storeId, + camera_ids: normalizedCameraIds, + remark: remark ? String(remark).slice(0, 500) : null, + }; + + let created = null; + const maxAttempts = 5; + for (let attempt = 1; attempt <= maxAttempts && !created; attempt += 1) { + const unpackNo = await this._generateUnpackNo(warehouseId); + try { + created = await ctx.model.ReturnUnpack.create({ + ...baseFields, + unpack_no: unpackNo, + }); + } catch (err) { + const isUniqueConflict = err && ( + err.name === 'SequelizeUniqueConstraintError' + || (err.parent && err.parent.code === 'ER_DUP_ENTRY') + ); + if (isUniqueConflict && attempt < maxAttempts) { + // 并发撞号:指数退避 + 随机抖动后重新取号重试,降低同一序号再次碰撞概率 + const backoffMs = Math.min(500, attempt * 40) + Math.floor(Math.random() * 60); + ctx.logger.warn(`[returnUnpack.create] 拆包单号唯一冲突,第 ${attempt} 次重试(退避 ${backoffMs}ms): ${err.message}`); + await new Promise(resolve => setTimeout(resolve, backoffMs)); + continue; + } + throw err; + } + } + + const createdRow = created && typeof created.toJSON === 'function' ? created.toJSON() : created; + + // 6. 原订单详情(仅原单退回时拉取,参考 afterSale.detail._resolveOrderDetail) + let order = null; + if (isOriginalReturn && orderId) { + try { + order = await ctx.service.systems.afterSale._resolveOrderDetail(orderId, warehouseId); + } catch (err) { + ctx.logger.warn(`[returnUnpack.create] 拉取原订单详情失败: ${err.message}`); + } + } + + return { + id: createdRow.id, + record: await this._enrichRow(createdRow), + is_original_return: isOriginalReturn, + store_remark: storeRemark, + order, + }; + } + + /** + * 录明细:以拆包单ID为依据录入一条明细(识别到系统商品时回填快照)。 + * + * @param {Object} params 明细参数。 + * @param {number} params.id 拆包单ID。 + * @param {number} [params.stock_id] 系统商品ID(wms_stock_warehouse.id),为空即无关联货物。 + * @param {number} [params.quantity] 数量,默认 1。 + * @param {string} [params.product_status] 产品状态 normal/damaged,默认 normal。 + * @param {string} [params.remark] 备注。 + * @return {Promise} 明细ID + 明细行 + 主表最新汇总。 + */ + async addDetail({ id, stock_id, quantity, product_status, remark }) { + const { ctx } = this; + + const unpack = await this._findByIdChecked(id); + this._assertUnpacking(unpack); + + const normalizedStockId = stock_id ? Number(stock_id) : null; + const normalizedQuantity = Math.max(1, parseInt(quantity) || 1); + const normalizedStatus = product_status === 'damaged' ? 'damaged' : 'normal'; + + // 识别到系统商品:校验货主归属 + 回填快照 + let isRecognized = 0; + let itemCode = null; + let itemName = null; + let spec = null; + let productSnapshot = null; + + if (normalizedStockId) { + const stock = await ctx.model.StockWarehouse.findOne({ + where: { id: normalizedStockId }, + raw: true, + }); + if (!stock) { + throw this.createBusinessError('系统商品不存在', 404); + } + + // 货主校验:主表已有货主则必须一致;主表货主为空则以首个识别商品回填货主 + const currentStoreId = Number(unpack.store_id || 0); + const stockStoreId = Number(stock.store_id || 0); + if (currentStoreId > 0 && stockStoreId !== currentStoreId) { + throw this.createBusinessError('该商品不属于当前货主,无法录入', 403); + } + + isRecognized = 1; + itemCode = stock.item_code || null; + itemName = stock.item_name || null; + spec = stock.sku_property || null; + productSnapshot = JSON.stringify({ + item_code: stock.item_code || '', + goods_code: stock.goods_code || '', + item_name: stock.item_name || '', + sku_property: stock.sku_property || '', + stock_unit: stock.stock_unit || '', + item_type: stock.item_type || '', + }); + + // 主表货主为空时回填(首个识别商品确定货主) + if (currentStoreId === 0 && stockStoreId > 0) { + await ctx.model.ReturnUnpack.update( + { store_id: stockStoreId }, + { where: { id: unpack.id } } + ); + } + } + + const created = await ctx.model.ReturnUnpackDetail.create({ + unpack_id: unpack.id, + warehouse_id: unpack.warehouse_id, + barcode: null, + stock_id: normalizedStockId, + is_recognized: isRecognized, + item_code: itemCode, + item_name: itemName, + spec, + quantity: normalizedQuantity, + product_status: normalizedStatus, + product_snapshot: productSnapshot, + remark: remark ? String(remark).slice(0, 500) : null, + }); + + const summary = await this._recalcMain(unpack.id, unpack.warehouse_id); + + const createdRow = created && typeof created.toJSON === 'function' ? created.toJSON() : created; + return { + detail_id: createdRow.id, + detail: createdRow, + ...summary, + }; + } + + /** + * 更新明细:仅允许更新数量 / 备注(白名单)。 + * + * @param {Object} params 更新参数。 + * @param {number} params.id 拆包单ID。 + * @param {number} params.detail_id 明细ID。 + * @param {number} [params.quantity] 数量。 + * @param {string} [params.remark] 备注。 + * @return {Promise} 更新后的明细 + 主表最新汇总。 + */ + async updateDetail({ id, detail_id, quantity, remark }) { + const { ctx } = this; + + const unpack = await this._findByIdChecked(id); + this._assertUnpacking(unpack); + + const detail = await this._findDetailChecked(unpack.id, detail_id); + + const updateFields = {}; + let quantityChanged = false; + + if (quantity !== undefined && quantity !== null) { + const normalizedQuantity = Math.max(1, parseInt(quantity) || 1); + if (normalizedQuantity !== Number(detail.quantity)) { + updateFields.quantity = normalizedQuantity; + quantityChanged = true; + } + } + if (remark !== undefined && remark !== null) { + updateFields.remark = String(remark).slice(0, 500); + } + + if (Object.keys(updateFields).length === 0) { + return { + detail, + total_items: unpack.total_items, + total_quantity: unpack.total_quantity, + detail_status: unpack.detail_status, + }; + } + + await ctx.model.ReturnUnpackDetail.update(updateFields, { + where: { id: detail.id }, + }); + + const updated = await ctx.model.ReturnUnpackDetail.findOne({ + where: { id: detail.id }, + raw: true, + }); + + let summary = { + total_items: unpack.total_items, + total_quantity: unpack.total_quantity, + detail_status: unpack.detail_status, + }; + if (quantityChanged) { + summary = await this._recalcMain(unpack.id, unpack.warehouse_id); + } + + return { + detail: updated, + ...summary, + }; + } + + /** + * 移除明细:硬删除拆包单下的一条明细。 + * + * @param {Object} params 移除参数。 + * @param {number} params.id 拆包单ID。 + * @param {number} params.detail_id 明细ID。 + * @return {Promise} 删除结果 + 主表最新汇总。 + */ + async removeDetail({ id, detail_id }) { + const { ctx } = this; + + const unpack = await this._findByIdChecked(id); + this._assertUnpacking(unpack); + + const detail = await this._findDetailChecked(unpack.id, detail_id); + + await ctx.model.ReturnUnpackDetail.destroy({ + where: { id: detail.id }, + }); + + const summary = await this._recalcMain(unpack.id, unpack.warehouse_id); + return { + removed_detail_id: detail.id, + ...summary, + }; + } + + /** + * 取消拆包单:仅在未完成(unpacking)状态可删,事务内硬删除主表 + 所有明细。 + * + * @param {Object} params 取消参数。 + * @param {number} params.id 拆包单ID。 + * @return {Promise} 取消结果。 + */ + async cancel({ id }) { + const { ctx } = this; + + const unpack = await this._findByIdChecked(id); + this._assertUnpacking(unpack); + + await ctx.model.transaction(async transaction => { + await ctx.model.ReturnUnpackDetail.destroy({ + where: { unpack_id: unpack.id }, + transaction, + }); + await ctx.model.ReturnUnpackVideo.destroy({ + where: { unpack_id: unpack.id }, + transaction, + }); + await ctx.model.ReturnUnpack.destroy({ + where: { id: unpack.id }, + transaction, + }); + }); + + return { id: unpack.id }; + } + + /** + * 提交确认:未完成拆包单转 completed 终态,回写结束时间, + * 并同步更新退回查询记录 is_back=1(标记该运单号已退回)。 + * + * @param {Object} params 提交参数。 + * @param {number} params.id 拆包单ID。 + * @return {Promise} 更新后的主表记录。 + */ + async submit({ id }) { + const { ctx } = this; + + const unpack = await this._findByIdChecked(id); + this._assertUnpacking(unpack); + + const now = new Date(); + await ctx.model.ReturnUnpack.update( + { status: 'completed', end_time: now }, + { where: { id: unpack.id } } + ); + + // 同步更新退回查询记录:按 warehouse_id + waybill_code 反查命中则 is_back=1 + try { + await ctx.model.ReturnQueryLog.update( + { is_back: 1 }, + { where: { warehouse_id: unpack.warehouse_id, waybill_code: unpack.waybill_code } } + ); + } catch (err) { + ctx.logger.warn(`[returnUnpack.submit] 更新退回查询记录 is_back 失败: ${err.message}`); + } + + const updated = await ctx.model.ReturnUnpack.findOne({ + where: { id: unpack.id }, + raw: true, + }); + + return { + record: await this._enrichRow(updated), + }; + } + + /** + * 分页查询拆包单列表(仓库隔离由方法层注入 warehouse_id)。 + * + * @param {Object} where 标准化 where 条件对象。 + * @param {Object} [pagination] 分页参数。 + * @param {Object} [sort] 排序参数。 + * @return {Promise} { 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, 'return_unpack'); + + const { count, rows } = await ctx.model.ReturnUnpack.findAndCountAll({ + where: queryWhere, + order, + offset: (page - 1) * pageSize, + limit: pageSize, + raw: true, + }); + + const list = []; + for (const row of rows) { + list.push(await this._enrichRow(row)); + } + + return { + list, + pagination: { + page, + pageSize, + total: count, + totalPages: Math.ceil(count / pageSize), + hasPrevious: page > 1, + hasNext: page * pageSize < count, + }, + }; + } + + /** + * 分页查询拆包明细列表(仓库隔离由方法层注入 warehouse_id)。 + * + * @param {Object} where 标准化 where 条件对象。 + * @param {Object} [pagination] 分页参数。 + * @param {Object} [sort] 排序参数。 + * @return {Promise} { list, pagination }。 + */ + async detailList(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._buildDetailListWhere(where, Op); + const order = this._buildListOrder(sort, 'return_unpack_detail'); + + const { count, rows } = await ctx.model.ReturnUnpackDetail.findAndCountAll({ + where: queryWhere, + include: [ + { + model: ctx.model.StockWarehouse, + as: 'stockWarehouse', + required: false, + }, + ], + order, + offset: (page - 1) * pageSize, + limit: pageSize, + raw: false, + }); + + const list = rows.map(row => (row && typeof row.toJSON === 'function' ? row.toJSON() : row)); + + return { + list, + pagination: { + page, + pageSize, + total: count, + totalPages: Math.ceil(count / pageSize), + hasPrevious: page > 1, + hasNext: page * pageSize < count, + }, + }; + } + + /** + * 查询拆包单详情:主表 + 明细 + 视频 + 退回收到单 + 原订单详情(原单退回时)。 + * + * @param {number} id 拆包单ID。 + * @return {Promise} 详情对象。 + */ + async detail(id) { + const { ctx } = this; + + const unpack = await this._findByIdChecked(id); + + const record = await ctx.model.ReturnUnpack.findOne({ + where: { id: unpack.id }, + include: [ + { + model: ctx.model.ReturnUnpackDetail, + as: 'details', + required: false, + include: [ + { + model: ctx.model.StockWarehouse, + as: 'stockWarehouse', + required: false, + }, + ], + }, + { + model: ctx.model.ReturnUnpackVideo, + as: 'videos', + where: { deleted_at: null }, + required: false, + include: [ + { + model: ctx.model.Camera, + as: 'camera', + required: false, + }, + ], + }, + { + model: ctx.model.ReturnReceived, + as: 'returnReceived', + required: false, + }, + ], + raw: false, + }); + + const recordJson = record && typeof record.toJSON === 'function' ? record.toJSON() : record; + + // 原订单详情(仅原单退回时返回) + let relatedOrder = null; + if (recordJson && recordJson.order_id) { + try { + relatedOrder = await ctx.service.systems.afterSale._resolveOrderDetail( + recordJson.order_id, + recordJson.warehouse_id + ); + } catch (err) { + ctx.logger.warn(`[returnUnpack.detail] 拉取原订单详情失败: ${err.message}`); + } + } + + return { + record: await this._enrichRow(recordJson), + related: { + order: relatedOrder, + }, + }; + } + + /** + * 删除拆包单(后台管理,不限制状态):事务内物理删除主表 + 明细,同步软删视频。 + * + * @param {number} id 拆包单ID。 + * @return {Promise} 删除结果。 + */ + async delete(id) { + const { ctx } = this; + + const unpack = await this._findByIdChecked(id); + + await ctx.model.transaction(async transaction => { + await ctx.model.ReturnUnpackDetail.destroy({ + where: { unpack_id: unpack.id }, + transaction, + }); + await ctx.model.ReturnUnpackVideo.destroy({ + where: { unpack_id: unpack.id }, + transaction, + }); + await ctx.model.ReturnUnpack.destroy({ + where: { id: unpack.id }, + transaction, + }); + }); + + return { id: unpack.id }; + } + + // =========================== + // 辅助方法 + // =========================== + + /** + * 按主键查询拆包单,并校验仓库隔离。 + * + * @param {number} id 拆包单ID。 + * @return {Promise} 拆包单原始数据。 + */ + 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.ReturnUnpack.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; + } + + /** + * 校验拆包单处于未完成(unpacking)状态。 + * + * @param {Object} unpack 拆包单记录。 + */ + _assertUnpacking(unpack) { + if (String(unpack.status) !== 'unpacking') { + throw this.createBusinessError('拆包单已提交或已取消,不可操作', 400); + } + } + + /** + * 查询明细并校验属于指定拆包单。 + * + * @param {number} unpackId 拆包单ID。 + * @param {number} detailId 明细ID。 + * @return {Promise} 明细原始数据。 + */ + async _findDetailChecked(unpackId, detailId) { + const { ctx } = this; + const normalizedDetailId = Number(detailId || 0); + if (!Number.isFinite(normalizedDetailId) || normalizedDetailId <= 0) { + throw this.createBusinessError('detail_id 必填且必须为正整数', 400); + } + + const detail = await ctx.model.ReturnUnpackDetail.findOne({ + where: { id: normalizedDetailId, unpack_id: unpackId }, + raw: true, + }); + if (!detail) { + throw this.createBusinessError('明细不存在或不属于该拆包单', 404); + } + + return detail; + } + + /** + * 重算主表汇总字段:total_items / total_quantity / detail_status。 + * + * @param {number} unpackId 拆包单ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 最新汇总对象。 + */ + async _recalcMain(unpackId, warehouseId) { + const { ctx } = this; + + const details = await ctx.model.ReturnUnpackDetail.findAll({ + where: { unpack_id: unpackId }, + attributes: [ 'id', 'quantity', 'is_recognized' ], + raw: true, + }); + + const totalItems = details.length; + const totalQuantity = details.reduce((sum, row) => sum + (Number(row.quantity) || 0), 0); + + let detailStatus = 'none_recognized'; + if (totalItems > 0) { + const recognizedCount = details.filter(row => Number(row.is_recognized) === 1).length; + if (recognizedCount === totalItems) { + detailStatus = 'all_recognized'; + } else if (recognizedCount > 0) { + detailStatus = 'partial_recognized'; + } + } + + await ctx.model.ReturnUnpack.update( + { + total_items: totalItems, + total_quantity: totalQuantity, + detail_status: detailStatus, + }, + { where: { id: unpackId, warehouse_id: warehouseId } } + ); + + return { + total_items: totalItems, + total_quantity: totalQuantity, + detail_status: detailStatus, + }; + } + + /** + * 组装主表展示字段(识别状态派生字段 + 时间格式化 + camera_ids 数组化)。 + * + * @param {Object} row 主表原始数据。 + * @return {Promise} 组装后的记录。 + */ + async _enrichRow(row) { + const { app } = this; + const record = { ...row }; + + record.is_original_return = Boolean(record.order_express_id); + + // camera_ids 归一化为数组(MySQL JSON 列可能返回字符串) + if (record.camera_ids !== undefined && record.camera_ids !== null) { + if (typeof record.camera_ids === 'string') { + try { + const parsed = JSON.parse(record.camera_ids); + record.camera_ids = Array.isArray(parsed) ? parsed : []; + } catch (err) { + record.camera_ids = []; + } + } else if (!Array.isArray(record.camera_ids)) { + record.camera_ids = []; + } + } else { + record.camera_ids = []; + } + + // 时间格式化 + record.unpack_date = record.unpack_date ? app.formatDate(record.unpack_date, 'YYYY-MM-DD') : null; + record.start_time = record.start_time ? app.formatDate(record.start_time) : null; + record.end_time = record.end_time ? app.formatDate(record.end_time) : null; + 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; + } + + /** + * 查询货主合约备注名称(wms_store_warehouse.store_remask)。 + * + * @param {number} storeId 货主ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 货主备注名称,未命中时返回空字符串。 + */ + async _resolveStoreRemark(storeId, warehouseId) { + const { ctx } = this; + const normalizedStoreId = Number(storeId || 0); + const normalizedWarehouseId = Number(warehouseId || 0); + if (!normalizedStoreId || !normalizedWarehouseId) { + return ''; + } + try { + const sw = await ctx.model.StoreWarehouse.findOne({ + where: { store_id: normalizedStoreId, warehouse_id: normalizedWarehouseId }, + attributes: [ 'store_remask' ], + raw: true, + }); + return (sw && sw.store_remask) || ''; + } catch (err) { + ctx.logger.warn(`[returnUnpack._resolveStoreRemark] 查询货主备注失败: ${err.message}`); + return ''; + } + } + + /** + * 生成拆包单号(原子取号)。 + * 格式:RP + YYYYMMDD + 6位序号(如 RP20260813000001)。 + * 取号基于序列表 wms_number_sequence 的单条 upsert 原子递增: + * INSERT ... VALUES (LAST_INSERT_ID(:seed + 1)) ON DUPLICATE KEY UPDATE + * current_seq = LAST_INSERT_ID(GREATEST(current_seq, :seed) + 1) + * 其中 :seed 为当日主表已有最大序号,保证历史数据对齐(首日启用不撞已有单号); + * 同事务(同连接)内回读 LAST_INSERT_ID() 取回本次分配序号,并发下无撞号。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 拆包单号。 + */ + async _generateUnpackNo(warehouseId) { + const { ctx } = this; + const now = new Date(); + const year = now.getFullYear(); + const month = String(now.getMonth() + 1).padStart(2, '0'); + const day = String(now.getDate()).padStart(2, '0'); + const datePart = `${year}${month}${day}`; + const prefix = 'RP'; + const bizType = 'return_unpack'; + + const sequence = await ctx.model.transaction(async transaction => { + // 历史对齐基准:当日主表已有最大序号(无则为 0) + const seedRows = await ctx.model.query( + `SELECT IFNULL(MAX(CAST(RIGHT(unpack_no, 6) AS UNSIGNED)), 0) AS max_seq + FROM wms_return_unpack + WHERE warehouse_id = :warehouseId AND unpack_no LIKE :pattern`, + { + replacements: { warehouseId, pattern: `${prefix}${datePart}%` }, + type: ctx.model.QueryTypes.SELECT, + transaction, + } + ); + const seed = Number(seedRows && seedRows[0] && seedRows[0].max_seq) || 0; + + // 原子取号:单条 upsert 内递增并设置连接级 LAST_INSERT_ID + await ctx.model.query( + `INSERT INTO wms_number_sequence (warehouse_id, biz_type, date_part, current_seq, created_at, updated_at) + VALUES (:warehouseId, :bizType, :datePart, LAST_INSERT_ID(:seed + 1), NOW(), NOW()) + ON DUPLICATE KEY UPDATE current_seq = LAST_INSERT_ID(GREATEST(current_seq, :seed) + 1), updated_at = NOW()`, + { + replacements: { warehouseId, bizType, datePart, seed }, + transaction, + } + ); + + const rows = await ctx.model.query( + 'SELECT LAST_INSERT_ID() AS seq', + { + type: ctx.model.QueryTypes.SELECT, + transaction, + } + ); + return Number(rows && rows[0] && rows[0].seq) || 1; + }); + + if (sequence > 999999) { + throw this.createBusinessError('当日拆包单号已用尽(序号超过 999999),请联系管理员', 500); + } + + return `${prefix}${datePart}${String(sequence).padStart(6, '0')}`; + } + + /** + * 根据标准化 where 条件构建主表 Sequelize 查询条件。 + * + * @param {Object} where 标准化 where 条件对象。 + * @param {Object} Op Sequelize Op 对象。 + * @return {Object} Sequelize where 条件。 + */ + _buildListWhere(where = {}, Op) { + const queryWhere = {}; + + const directFields = [ + 'warehouse_id', 'unpacker_id', 'return_received_id', 'store_id', + 'order_express_id', 'order_id', 'status', 'detail_status', + ]; + + for (const field of directFields) { + if (where[field] !== undefined && where[field] !== null) { + queryWhere[field] = this._resolveConditionValue(where[field], Op); + } + } + + // 日期/时间范围字段 + const rangeFields = [ 'unpack_date', 'start_time', 'end_time', 'created_at', 'updated_at' ]; + for (const field of rangeFields) { + if (where[field] !== undefined && where[field] !== null) { + queryWhere[field] = this._resolveConditionValue(where[field], Op); + } + } + + // 文本字段(支持模糊) + const textFields = [ 'unpack_no', 'waybill_code' ]; + for (const field of textFields) { + if (where[field] !== undefined && where[field] !== null) { + queryWhere[field] = this._resolveConditionValue(where[field], Op); + } + } + + return queryWhere; + } + + /** + * 根据标准化 where 条件构建明细表 Sequelize 查询条件。 + * + * @param {Object} where 标准化 where 条件对象。 + * @param {Object} Op Sequelize Op 对象。 + * @return {Object} Sequelize where 条件。 + */ + _buildDetailListWhere(where = {}, Op) { + const queryWhere = {}; + + const fields = [ + 'warehouse_id', 'unpack_id', 'stock_id', 'barcode', + 'is_recognized', 'product_status', + ]; + + 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 排序参数。 + * @param {string} scene 场景标识(return_unpack / return_unpack_detail)。 + * @return {Array>} Sequelize order 数组。 + */ + _buildListOrder(sort = {}, scene = 'return_unpack') { + 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 mainFields = new Set([ + 'id', 'created_at', 'updated_at', 'unpack_date', 'start_time', 'end_time', + 'unpack_no', 'waybill_code', + ]); + const detailFields = new Set([ 'id', 'created_at', 'updated_at', 'quantity' ]); + + const allowed = scene === 'return_unpack_detail' ? detailFields : mainFields; + const safeSortField = allowed.has(sortField) ? sortField : 'created_at'; + + return [[ safeSortField, sortOrder ]]; + } +} + +module.exports = ReturnUnpackService; diff --git a/database/migrations/20260813120000-create-wms-return-unpack.js b/database/migrations/20260813120000-create-wms-return-unpack.js new file mode 100644 index 0000000..582d33e --- /dev/null +++ b/database/migrations/20260813120000-create-wms-return-unpack.js @@ -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); + }, +}; diff --git a/database/migrations/20260813120100-create-wms-return-unpack-detail.js b/database/migrations/20260813120100-create-wms-return-unpack-detail.js new file mode 100644 index 0000000..df251fe --- /dev/null +++ b/database/migrations/20260813120100-create-wms-return-unpack-detail.js @@ -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); + }, +}; diff --git a/database/migrations/20260813120200-create-wms-return-unpack-video.js b/database/migrations/20260813120200-create-wms-return-unpack-video.js new file mode 100644 index 0000000..268e531 --- /dev/null +++ b/database/migrations/20260813120200-create-wms-return-unpack-video.js @@ -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); + }, +}; diff --git a/database/migrations/20260813120300-create-wms-return-query-log.js b/database/migrations/20260813120300-create-wms-return-query-log.js new file mode 100644 index 0000000..80e46f3 --- /dev/null +++ b/database/migrations/20260813120300-create-wms-return-query-log.js @@ -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); + }, +}; diff --git a/database/migrations/20260813130000-create-return-unpack-permissions.js b/database/migrations/20260813130000-create-return-unpack-permissions.js new file mode 100644 index 0000000..7890329 --- /dev/null +++ b/database/migrations/20260813130000-create-return-unpack-permissions.js @@ -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 } + ); + }, +}; diff --git a/database/migrations/20260813140000-add-order-delivery-base-table-missing-columns.js b/database/migrations/20260813140000-add-order-delivery-base-table-missing-columns.js new file mode 100644 index 0000000..33c8646 --- /dev/null +++ b/database/migrations/20260813140000-add-order-delivery-base-table-missing-columns.js @@ -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); + } + }, +}; diff --git a/database/migrations/20260813150000-create-wms-number-sequence.js b/database/migrations/20260813150000-create-wms-number-sequence.js new file mode 100644 index 0000000..9763d05 --- /dev/null +++ b/database/migrations/20260813150000-create-wms-number-sequence.js @@ -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); + }, +};