diff --git a/app/model/pack_task.js b/app/model/pack_task.js new file mode 100644 index 0000000..16944d7 --- /dev/null +++ b/app/model/pack_task.js @@ -0,0 +1,164 @@ +'use strict'; + +module.exports = app => { + const { STRING, BIGINT, INTEGER, DATE, TINYINT, TEXT, JSON: JSON_TYPE } = app.Sequelize; + + const PackTask = app.model.define('pack_task', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '订单ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '仓库ID', + }, + workbench_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '工作台ID,关联 wms_workbench.id', + }, + wave_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: 0, + comment: '波次ID', + }, + wave_no: { + type: STRING(50), + allowNull: true, + comment: '波次号', + }, + waybill_code: { + type: STRING(50), + allowNull: true, + comment: '运单号', + }, + pack_quantity: { + type: INTEGER.UNSIGNED, + allowNull: true, + defaultValue: 0, + comment: '打包数量(件数)', + }, + item_quantity: { + type: INTEGER.UNSIGNED, + allowNull: true, + defaultValue: 0, + comment: '商品总数量', + }, + sku_count: { + type: INTEGER.UNSIGNED, + allowNull: true, + defaultValue: 0, + comment: '商品种类数(SKU数)', + }, + pack_mode: { + type: TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 1, + comment: '打包模式:1=散单 2=团购', + }, + status: { + type: TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '任务状态:0=待处理 1=打包中 2=已完成 3=异常', + }, + start_time: { + type: DATE, + allowNull: true, + comment: '开始打包时间', + }, + end_time: { + type: DATE, + allowNull: true, + comment: '结束打包时间', + }, + operator_text: { + type: TEXT, + allowNull: true, + comment: '作业人员(自由文本,如多人逗号分隔)', + }, + device_ids: { + type: JSON_TYPE, + allowNull: true, + comment: '设备ID列表,如 [1,2,3]', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + meta: { + type: JSON_TYPE, + allowNull: true, + comment: '扩展信息JSON', + }, + create_time: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + update_time: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '删除时间', + }, + }, { + tableName: 'wms_pack_task', + timestamps: true, + createdAt: 'create_time', + updatedAt: 'update_time', + paranoid: true, + deletedAt: 'deleted_at', + comment: '打包任务表(含作业记录)', + indexes: [ + { name: 'idx_order_id', fields: [ 'order_id' ] }, + { name: 'idx_warehouse_id', fields: [ 'warehouse_id' ] }, + { name: 'idx_workbench_id', fields: [ 'workbench_id' ] }, + { name: 'idx_wave_id', fields: [ 'wave_id' ] }, + { name: 'idx_waybill_code', fields: [ 'waybill_code' ] }, + { name: 'idx_pack_mode_status', fields: [ 'pack_mode', 'status' ] }, + { name: 'idx_start_time', fields: [ 'start_time' ] }, + { name: 'idx_status', fields: [ 'status' ] }, + ], + }); + + PackTask.associate = () => { + app.model.PackTask.belongsTo(app.model.Workbench, { + foreignKey: 'workbench_id', + targetKey: 'id', + as: 'workbench', + }); + app.model.PackTask.hasMany(app.model.PackTaskVideo, { + foreignKey: 'pack_task_id', + sourceKey: 'id', + as: 'videos', + }); + app.model.PackTask.hasMany(app.model.PackTaskPacker, { + foreignKey: 'pack_task_id', + sourceKey: 'id', + as: 'packers', + }); + app.model.PackTask.hasMany(app.model.OrderExpress, { + foreignKey: 'order_id', + sourceKey: 'order_id', + as: 'expresses', + }); + }; + + return PackTask; +}; diff --git a/app/model/pack_task_packer.js b/app/model/pack_task_packer.js new file mode 100644 index 0000000..65d2e39 --- /dev/null +++ b/app/model/pack_task_packer.js @@ -0,0 +1,78 @@ +'use strict'; + +module.exports = app => { + const { STRING, BIGINT, DATE, TINYINT } = app.Sequelize; + + const PackTaskPacker = app.model.define('pack_task_packer', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + pack_task_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '打包任务ID,关联 wms_pack_task.id', + }, + account_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '账号ID,关联 wms_account.id', + }, + account_name: { + type: STRING(128), + allowNull: false, + comment: '账号姓名快照', + }, + seq: { + type: TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '排序序号', + }, + create_time: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + update_time: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '删除时间', + }, + }, { + tableName: 'wms_pack_task_packer', + timestamps: true, + createdAt: 'create_time', + updatedAt: 'update_time', + paranoid: true, + deletedAt: 'deleted_at', + comment: '打包任务-打包人关系表', + indexes: [ + { name: 'uix_pack_task_account', fields: [ 'pack_task_id', 'account_id' ], unique: true }, + { name: 'idx_account_id', fields: [ 'account_id' ] }, + { name: 'idx_pack_task_id', fields: [ 'pack_task_id' ] }, + ], + }); + + PackTaskPacker.associate = () => { + app.model.PackTaskPacker.belongsTo(app.model.PackTask, { + foreignKey: 'pack_task_id', + targetKey: 'id', + as: 'packTask', + }); + app.model.PackTaskPacker.belongsTo(app.model.Account, { + foreignKey: 'account_id', + targetKey: 'id', + as: 'account', + }); + }; + + return PackTaskPacker; +}; diff --git a/app/model/workbench.js b/app/model/workbench.js new file mode 100644 index 0000000..ee65b8a --- /dev/null +++ b/app/model/workbench.js @@ -0,0 +1,82 @@ +'use strict'; + +module.exports = app => { + const { STRING, BIGINT, DATE, TINYINT, ENUM, JSON: JSON_TYPE } = app.Sequelize; + + const Workbench = app.model.define('workbench', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + name: { + type: STRING(100), + allowNull: false, + comment: '工作台名称(用户自定义)', + }, + barcode: { + type: STRING(100), + allowNull: true, + comment: '工作台条码(用户自定义,仓库内唯一)', + }, + status: { + type: TINYINT, + allowNull: false, + defaultValue: 1, + comment: '状态:0-禁用 1-启用', + }, + type: { + type: ENUM('personal', 'group'), + allowNull: false, + defaultValue: 'personal', + comment: '工作台类型:personal-个人工作台 group-团体工作台', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + device_ids: { + type: JSON_TYPE, + allowNull: true, + comment: '设备ID列表,如 [1,2,3],触发打包任务时透传到 wms_pack_task.device_ids', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_workbench', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: true, + deletedAt: 'deleted_at', + comment: '工作台表', + indexes: [ + { name: 'idx_warehouse_id', fields: ['warehouse_id'] }, + { name: 'idx_barcode', fields: ['barcode'] }, + { name: 'uk_warehouse_barcode', unique: true, fields: ['warehouse_id', 'barcode', 'deleted_at'] }, + { name: 'idx_deleted_at', fields: ['deleted_at'] }, + ], + }); + + return Workbench; +}; diff --git a/app/service/systemMethods/workbench.js b/app/service/systemMethods/workbench.js new file mode 100644 index 0000000..1f7c3fe --- /dev/null +++ b/app/service/systemMethods/workbench.js @@ -0,0 +1,137 @@ +'use strict'; + +const MainService = require('../main'); + +class WorkbenchService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = 'business'; + const _noNeedRight = 'list,detail,checkBarcode,business'; + const _noNeedLog = 'list,detail,checkBarcode'; + const _noNeedAuth = 'list,detail,checkBarcode,business'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 工作台列表(分页 + 筛选) + */ + async list(data) { + const { service } = this; + try { + const result = await service.systems.workbench.list(data || {}); + return this.success('获取成功', result); + } catch (error) { + return this.fail(error.message); + } + } + + /** + * 工作台详情 + */ + async detail(data) { + const { service } = this; + try { + const { id } = data || {}; + if (!id) return this.fail('工作台ID不能为空'); + const record = await service.systems.workbench.detail(parseInt(id)); + return this.success('获取成功', record); + } catch (error) { + return this.fail(error.message); + } + } + + /** + * 创建工作台 + */ + async create(data) { + const { service } = this; + try { + const record = await service.systems.workbench.create(data); + return this.success('创建成功', record); + } catch (error) { + return this.fail(error.message); + } + } + + /** + * 更新工作台 + */ + async update(data) { + const { service } = this; + try { + const { id, ...fields } = data || {}; + if (!id) return this.fail('工作台ID不能为空'); + const record = await service.systems.workbench.update(parseInt(id), fields); + return this.success('更新成功', record); + } catch (error) { + return this.fail(error.message); + } + } + + /** + * 删除工作台(软删除) + */ + async delete(data) { + const { service } = this; + try { + const { id } = data || {}; + if (!id) return this.fail('工作台ID不能为空'); + await service.systems.workbench.delete(parseInt(id)); + return this.success('删除成功'); + } catch (error) { + return this.fail(error.message); + } + } + + /** + * 工作台业务入口(免登录、免鉴权) + * @param {Object} data - { name, data } + */ + async business(data) { + const { ctx, service } = this; + const { name, data: bizData } = data || {}; + ctx.logger.info('[Workbench.business] 收到业务请求 name=%s data=%j', name, bizData); + try { + const result = await service.systems.workbench.business(name, bizData); + return this.success('ok', result); + } catch (error) { + ctx.logger.error('[Workbench.business] 业务处理失败 name=%s error=%s', name, error.message); + return this.fail(error.message); + } + } + + /** + * 工作台绑定摄像头 + */ + async bindCamera(data) { + const { service } = this; + try { + const { id, camera_ids } = data || {}; + if (!id) return this.fail('工作台ID不能为空'); + const record = await service.systems.workbench.bindCamera(parseInt(id), camera_ids); + return this.success('绑定成功', record); + } catch (error) { + return this.fail(error.message); + } + } + + /** + * 检查条码是否已存在 + */ + async checkBarcode(data) { + const { service } = this; + try { + const { barcode, excludeId } = data || {}; + if (!barcode) return this.fail('条码不能为空'); + const exists = await service.systems.workbench.checkBarcodeExists( + String(barcode).trim(), + excludeId ? parseInt(excludeId) : undefined + ); + return this.success('ok', { exists }); + } catch (error) { + return this.fail(error.message); + } + } +} + +module.exports = WorkbenchService; diff --git a/app/service/systems/workbench.js b/app/service/systems/workbench.js index 9cb9805..1290e90 100644 --- a/app/service/systems/workbench.js +++ b/app/service/systems/workbench.js @@ -200,6 +200,11 @@ class WorkbenchService extends Service { return await this._queryOrder(data || {}); case 'packOrder': return await this._packOrder(data || {}); + case 'finishPack': + return await this._finishPack(data || {}); + case 'sendWeight': + return await this._sendWeight(data || {}); + case '': default: throw new Error(`不支持的业务类型: ${name}`); } @@ -230,6 +235,195 @@ class WorkbenchService extends Service { return total; } + /** + * 获取波次下所有订单ID(遍历 current + dispatch 分表) + * @param {number} warehouseId + * @param {number} waveId + * @returns {Promise} + */ + async _getWaveOrderIds(warehouseId, waveId) { + const { ctx } = this; + const orderDeliveryFactory = ctx.model.OrderDeliveryFactory; + const tableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + const orderIds = []; + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model) continue; + const rows = await model.findAll({ + where: { wave_id: waveId, warehouse_id: warehouseId }, + attributes: [ 'id' ], + raw: true, + }); + orderIds.push(...rows.map(r => r.id)); + } catch (_err) { continue; } + } + return [ ...new Set(orderIds) ]; + } + + /** + * 打包任务字段白名单:只有这些字段的变化才会记入操作日志 + */ + PACK_OPLOG_FIELD_WHITELIST = new Set([ + 'pack_mode', + 'status', + 'pack_quantity', + 'item_quantity', + 'sku_count', + 'workbench_id', + 'wave_no', + ]); + + /** + * 打包任务字段中文翻译 + */ + PACK_OPLOG_FIELD_LABEL = { + pack_mode: '打包模式', + status: '任务状态', + pack_quantity: '打包数量', + item_quantity: '商品总数量', + sku_count: '商品种类数', + workbench_id: '工作台', + wave_no: '波次号', + }; + + /** + * 打包任务字段值翻译 + */ + PACK_OPLOG_VALUE_LABEL = { + pack_mode: { 1: '散单', 2: '团购' }, + status: { 0: '待处理', 1: '打包中', 2: '已完成', 3: '异常' }, + }; + + /** + * 构建打包操作日志的变更描述。 + * @param {Object} packData 打包数据 + * @returns {string} 变更描述 + */ + _buildPackChangeSummary(packData) { + const whitelist = this.PACK_OPLOG_FIELD_WHITELIST; + const fieldLabel = this.PACK_OPLOG_FIELD_LABEL; + const valueLabel = this.PACK_OPLOG_VALUE_LABEL; + + const parts = []; + for (const [ key, value ] of Object.entries(packData)) { + if (!whitelist.has(key) || value === undefined || value === null) continue; + const label = fieldLabel[key] || key; + const valStr = (valueLabel[key] && valueLabel[key][value] !== undefined) + ? valueLabel[key][value] + : String(value); + parts.push(`${label}: ${valStr}`); + } + return parts.join(','); + } + + /** + * 写入打包操作日志。 + * - 散单:写入单个订单操作日志 + * - 团购:批量写入波次下所有订单的操作日志 + * 写入失败不影响主流程。 + * + * @param {Object} options + * @param {number} options.warehouseId 仓库ID + * @param {number} options.orderId 当前订单ID + * @param {number} options.waveId 波次ID + * @param {string} options.waveNo 波次号 + * @param {number} options.isSandan 是否散单(1=散单 0=团购) + * @param {Object} options.packData 打包数据(用于变更描述) + * @param {Array} options.users 打包人员列表 + */ + async _writePackOperationLog({ warehouseId, orderId, waveId, waveNo, isSandan, packData, users }) { + const { ctx } = this; + try { + const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + if (!operationLogService || typeof operationLogService.createOperationLogs !== 'function') { + return; + } + + // 操作人信息:从 users 中取第一个作为主操作人 + const operator = { + id: users && users[0] ? String(users[0].wms_account_id || users[0].id || '') : null, + name: users && users[0] ? (users[0].real_name || '') : null, + }; + + const changeSummary = this._buildPackChangeSummary(packData); + const operationCode = isSandan === 1 ? 'ORDER_PACK' : 'ORDER_PACK_GROUP'; + + if (isSandan === 1) { + // 散单:写入单个订单操作日志 + await operationLogService.createOperationLogs([{ + businessType: 'order', + businessId: String(orderId), + operationCode, + operator, + extras: { + warehouseId, + message: `散单打包完成:${changeSummary}`, + }, + }]); + ctx.logger.info('[Workbench._writePackOperationLog] 散单操作日志已写入 orderId=%d', orderId); + } else { + // 团购:批量写入波次下所有订单的操作日志 + if (!waveId || waveId <= 0) { + // 无波次ID时按散单处理 + await operationLogService.createOperationLogs([{ + businessType: 'order', + businessId: String(orderId), + operationCode, + operator, + extras: { + warehouseId, + message: `打包完成:${changeSummary}`, + }, + }]); + return; + } + + const waveOrderIds = await this._getWaveOrderIds(warehouseId, waveId); + if (waveOrderIds.length === 0) { + // 波次下无订单,只写当前订单 + await operationLogService.createOperationLogs([{ + businessType: 'order', + businessId: String(orderId), + operationCode, + operator, + extras: { + warehouseId, + message: `打包完成(波次 ${waveNo || waveId}):${changeSummary}`, + }, + }]); + return; + } + + const messagePrefix = `团购打包完成(波次 ${waveNo || waveId},共${waveOrderIds.length}单):`; + const payloads = waveOrderIds.map(oid => ({ + businessType: 'order', + businessId: String(oid), + operationCode, + operator, + extras: { + warehouseId, + message: `${messagePrefix}${changeSummary}`, + }, + })); + + await operationLogService.createOperationLogs(payloads); + ctx.logger.info('[Workbench._writePackOperationLog] 团购操作日志已批量写入 waveNo=%s orderCount=%d', + waveNo || waveId, waveOrderIds.length); + } + } catch (e) { + ctx.logger.warn('[Workbench._writePackOperationLog] 写入操作日志失败,不影响主流程', { + error: e && e.message, + orderId, + waveId, + warehouseId, + }); + } + } + /** * 打包任务写入:根据发货单号查询订单并创建/更新打包任务记录 * @param {Object} params - { delivery_order_code, wave_no, warehouse_id, workbench_id, status, pack_time } @@ -238,13 +432,24 @@ class WorkbenchService extends Service { async _packOrder(params) { const { ctx } = this; const { delivery_order_code: deliveryOrderCode, wave_no: waveNo, - warehouse_id: inputWarehouseId, workbench_id: workbenchId, - status: packStatus, pack_time: packTime } = params; + warehouse_id: inputWarehouseId, workbench_id: workbenchIdRaw, + status: packStatus, pack_time: packTime, + wave_total_orders: waveTotalOrders, + items_count: itemsCount, + items_total: itemsTotal, + users: usersParam } = params; if (!deliveryOrderCode) throw new Error('发货单号不能为空'); if (!inputWarehouseId) throw new Error('仓库ID不能为空'); const warehouseId = parseInt(inputWarehouseId); + // 防护 NaN:parseInt 对非数字字符串返回 NaN,会导致 Sequelize 生成非法 SQL + const workbenchId = (workbenchIdRaw !== undefined && workbenchIdRaw !== null && workbenchIdRaw !== '') + ? parseInt(workbenchIdRaw) + : null; + const validWorkbenchId = (workbenchId !== null && !isNaN(workbenchId) && workbenchId > 0) + ? workbenchId + : null; const packTimeMs = packTime ? Number(packTime) * 1000 : Date.now(); // 步骤1:查找订单 @@ -295,9 +500,9 @@ class WorkbenchService extends Service { // 步骤3:获取工作台 device_ids let deviceIds = null; - if (workbenchId) { + if (validWorkbenchId) { try { - const wb = await ctx.model.Workbench.findByPk(parseInt(workbenchId), { + const wb = await ctx.model.Workbench.findByPk(validWorkbenchId, { attributes: ['device_ids'], raw: true, }); @@ -306,10 +511,10 @@ class WorkbenchService extends Service { } // 步骤4:同一工作台有新的打包任务时,关闭上一个未结束的任务 - if (workbenchId) { + if (validWorkbenchId) { const previousTask = await ctx.model.PackTask.findOne({ where: { - workbench_id: parseInt(workbenchId), + workbench_id: validWorkbenchId, warehouse_id: warehouseId, order_id: { [ctx.app.Sequelize.Op.ne]: orderId }, status: { [ctx.app.Sequelize.Op.lt]: 2 }, @@ -318,39 +523,143 @@ class WorkbenchService extends Service { if (previousTask) { await previousTask.update({ end_time: new Date(packTimeMs), status: 2 }); ctx.logger.info('[Workbench._packOrder] 关闭上一个未结束任务 taskId=%d orderId=%d workbenchId=%d', - previousTask.id, previousTask.order_id, workbenchId); + previousTask.id, previousTask.order_id, validWorkbenchId); } } - // 步骤5:查找是否已有该订单的打包任务 - let packTask = await ctx.model.PackTask.findOne({ - where: { order_id: orderId, warehouse_id: warehouseId, status: { [ctx.app.Sequelize.Op.lt]: 2 } }, - }); + // 步骤5:去重 — 散单按 order_id 物理删除旧记录,团购按 wave_no 物理删除旧记录 + if (isSandan === 1) { + // 散单:按 order_id 去重,先收集旧任务ID清理关联打包人,再物理移除旧任务 + const oldTasks = await ctx.model.PackTask.findAll({ + where: { order_id: orderId, warehouse_id: warehouseId }, + attributes: ['id'], + raw: true, + paranoid: false, + }); + if (oldTasks.length > 0) { + const oldTaskIds = oldTasks.map(t => t.id); + await ctx.model.PackTaskPacker.destroy({ + where: { pack_task_id: { [ctx.app.Sequelize.Op.in]: oldTaskIds } }, + force: true, + }); + await ctx.model.PackTask.destroy({ + where: { id: { [ctx.app.Sequelize.Op.in]: oldTaskIds } }, + force: true, + }); + ctx.logger.info('[Workbench._packOrder] 散单去重:物理删除 %d 条旧记录 orderId=%d', oldTasks.length, orderId); + } + } else { + // 团购:按 wave_no 去重,先收集旧任务ID清理关联打包人,再物理移除旧任务 + if (actualWaveNo) { + const oldTasks = await ctx.model.PackTask.findAll({ + where: { wave_no: actualWaveNo, warehouse_id: warehouseId }, + attributes: ['id'], + raw: true, + paranoid: false, + }); + if (oldTasks.length > 0) { + const oldTaskIds = oldTasks.map(t => t.id); + await ctx.model.PackTaskPacker.destroy({ + where: { pack_task_id: { [ctx.app.Sequelize.Op.in]: oldTaskIds } }, + force: true, + }); + await ctx.model.PackTask.destroy({ + where: { id: { [ctx.app.Sequelize.Op.in]: oldTaskIds } }, + force: true, + }); + ctx.logger.info('[Workbench._packOrder] 团购去重:物理删除 %d 条旧记录 waveNo=%s', oldTasks.length, actualWaveNo); + } + } + } + // 步骤6:创建新的打包任务 const packData = { order_id: orderId, warehouse_id: warehouseId, - workbench_id: workbenchId ? parseInt(workbenchId) : null, + workbench_id: validWorkbenchId, wave_id: waveId, wave_no: actualWaveNo, waybill_code: null, // 后续可从 order_express 补 pack_mode: isSandan === 0 ? 2 : 1, // 1=散单 2=团购 status: packStatus !== undefined ? parseInt(packStatus) : 1, - pack_quantity: orderRow.items_total || 0, - start_time: packTask ? packTask.start_time : new Date(packTimeMs), + pack_quantity: waveTotalOrders !== undefined ? parseInt(waveTotalOrders) || 0 : 1, + item_quantity: itemsTotal !== undefined ? parseInt(itemsTotal) || 0 : (orderRow.items_total || 0), + sku_count: itemsCount !== undefined ? parseInt(itemsCount) || 0 : (orderRow.item_count || 0), + start_time: new Date(packTimeMs), end_time: packStatus >= 2 ? new Date(packTimeMs) : null, device_ids: deviceIds, }; - if (packTask) { - // 更新已有任务 - await packTask.update(packData); - ctx.logger.info('[Workbench._packOrder] 更新打包任务 taskId=%d orderId=%d', packTask.id, orderId); - } else { - packTask = await ctx.model.PackTask.create(packData); - ctx.logger.info('[Workbench._packOrder] 创建打包任务 taskId=%d orderId=%d', packTask.id, orderId); + const packTask = await ctx.model.PackTask.create(packData); + ctx.logger.info('[Workbench._packOrder] 创建打包任务 taskId=%d orderId=%d', packTask.id, orderId); + + // 步骤6.5:更新订单的打包状态字段 + const orderPackStatus = (packStatus !== undefined && parseInt(packStatus) >= 2) ? 'fin' + : (packStatus !== undefined && parseInt(packStatus) === 1) ? 'padding' + : 'fin'; + const orderUpdateData = { pack_status: orderPackStatus }; + + if (isSandan === 1) { + // 散单:更新单个订单 + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model) continue; + const affected = await model.update(orderUpdateData, { + where: { id: orderId, warehouse_id: warehouseId }, + }); + if (affected[0] > 0) { + ctx.logger.info('[Workbench._packOrder] 更新订单打包状态 orderId=%d pack_status=%s table=%s', + orderId, orderPackStatus, entry.label); + break; + } + } catch (_err) { continue; } + } + } else if (waveId > 0) { + // 团购:批量更新波次下所有订单 + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model) continue; + const affected = await model.update(orderUpdateData, { + where: { wave_id: waveId, warehouse_id: warehouseId }, + }); + if (affected[0] > 0) { + ctx.logger.info('[Workbench._packOrder] 团购批量更新订单打包状态 waveId=%d pack_status=%s table=%s affected=%d', + waveId, orderPackStatus, entry.label, affected[0]); + } + } catch (_err) { continue; } + } } + // 步骤7:写入打包人员信息 + const users = Array.isArray(usersParam) ? usersParam : []; + let operatorText = ''; + if (users.length > 0) { + const packerRecords = users.map((user, idx) => ({ + pack_task_id: packTask.id, + account_id: user.wms_account_id != null ? parseInt(user.wms_account_id) || 0 : 0, + account_name: user.real_name || '', + seq: idx, + })); + await ctx.model.PackTaskPacker.bulkCreate(packerRecords); + operatorText = users.map(u => u.real_name || '').filter(Boolean).join(','); + // 回写 operator_text 到打包任务 + await packTask.update({ operator_text: operatorText }); + ctx.logger.info('[Workbench._packOrder] 写入 %d 个打包人员 operatorText=%s', users.length, operatorText); + } + + // 步骤8:写入操作日志(散单写单个订单,团购批量写波次所有订单) + await this._writePackOperationLog({ + warehouseId, + orderId, + waveId, + waveNo: actualWaveNo, + isSandan, + packData, + users, + }); + const result = { task_id: packTask.id, order_id: orderId, @@ -369,6 +678,346 @@ class WorkbenchService extends Service { return result; } + /** + * 工作台打包完成:传入工作台ID,查找最后一个未结束的打包任务并结束 + * @param {Object} params - { workbench_id, warehouse_id } + * @returns {Promise} + */ + async _finishPack(params) { + const { ctx } = this; + const { workbench_id: workbenchIdRaw, warehouse_id: inputWarehouseId } = params; + + if (!inputWarehouseId) throw new Error('仓库ID不能为空'); + + const warehouseId = parseInt(inputWarehouseId); + const workbenchId = (workbenchIdRaw !== undefined && workbenchIdRaw !== null && workbenchIdRaw !== '') + ? parseInt(workbenchIdRaw) + : null; + const validWorkbenchId = (workbenchId !== null && !isNaN(workbenchId) && workbenchId > 0) + ? workbenchId + : null; + + if (!validWorkbenchId) throw new Error('工作台ID不能为空'); + + // 查找该工作台最后一个未结束的打包任务(按 id 倒序取最新) + const lastTask = await ctx.model.PackTask.findOne({ + where: { + workbench_id: validWorkbenchId, + warehouse_id: warehouseId, + status: { [ctx.app.Sequelize.Op.lt]: 2 }, + }, + order: [[ 'id', 'DESC' ]], + }); + + if (!lastTask) { + ctx.logger.info('[Workbench._finishPack] 工作台 %d 无未结束的打包任务', validWorkbenchId); + return { workbench_id: validWorkbenchId, finished: false, message: '无未结束的打包任务' }; + } + + const now = new Date(); + await lastTask.update({ end_time: now, status: 2 }); + + ctx.logger.info('[Workbench._finishPack] 工作台 %d 结束打包任务 taskId=%d orderId=%d', + validWorkbenchId, lastTask.id, lastTask.order_id); + + return { + workbench_id: validWorkbenchId, + finished: true, + task_id: lastTask.id, + order_id: lastTask.order_id, + end_time: now, + }; + } + + /** + * 称重上报:条码(sn) → 运单号 → 更新称重重量 + * 支持散单直接更新和团购波次批量称重 + * @param {Object} params - { barcode, weight(克), warehouseId } + * @returns {Promise} weighing_weight/total_weight 单位为 g + */ + async _sendWeight(params) { + const { ctx } = this; + const { barcode, weight, warehouseId: inputWarehouseId } = params; + + // 参数校验 + if (!barcode || !String(barcode).trim()) { + throw new Error('条码(sn)不能为空'); + } + if (weight === null || weight === undefined || String(weight).trim() === '') { + throw new Error('重量(weight)不能为空'); + } + if (!inputWarehouseId) { + throw new Error('仓库ID不能为空'); + } + + const normalizedBarcode = String(barcode).trim(); + const warehouseId = parseInt(inputWarehouseId); + + // 校验重量格式(入参单位:克),必须大于0 + const weightText = String(weight).trim(); + if (!/^\d+$/.test(weightText)) { + throw new Error('重量格式非法,必须为正整数(单位 g)'); + } + const weightGram = Number(weightText); + if (!Number.isFinite(weightGram) || weightGram <= 0) { + throw new Error('重量必须大于0'); + } + // DB 存储单位已统一为 g,无需转换 + const normalizedWeight = weightGram; + + // 步骤1:条码 → 运单记录(按 waybill_code + warehouse_id 精确匹配) + const expressRow = await ctx.model.OrderExpress.findOne({ + where: { + waybill_code: normalizedBarcode, + warehouse_id: warehouseId, + delete_at: null, + }, + attributes: [ 'id', 'order_id', 'waybill_code', 'business_key' ], + raw: true, + }); + + if (!expressRow) { + throw new Error(`未找到条码 [${normalizedBarcode}] 对应的运单记录`); + } + + const orderId = Number(expressRow.order_id); + + // 步骤2:遍历 current → history → dispatch 分表查找订单及波次信息 + const orderDeliveryFactory = ctx.model.OrderDeliveryFactory; + const tableOrders = [ + { label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) }, + { label: 'history', getModel: () => orderDeliveryFactory.getHistoryModel(warehouseId) }, + { label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) }, + ]; + + let orderRow = null; + let orderDeliveryModel = null; + for (const entry of tableOrders) { + try { + const model = await entry.getModel(); + if (!model || typeof model.findOne !== 'function') continue; + const row = await model.findOne({ + where: { id: orderId, warehouse_id: warehouseId }, + attributes: [ 'id', 'wave_id', 'wave_no', 'items_weight' ], + raw: true, + }); + if (row) { + orderRow = row; + orderDeliveryModel = model; + break; + } + } catch (_err) { + ctx.logger.warn('[Workbench._sendWeight] 查询表 %s 失败: %s', entry.label, _err.message); + continue; + } + } + + if (!orderRow) { + throw new Error(`未找到运单对应的订单 [id=${orderId}, warehouse=${warehouseId}]`); + } + + const waveId = Number(orderRow.wave_id || 0); + + // 步骤3:散单(wave_id=0)→ 仅更新该运单的称重重量 + if (waveId === 0) { + await ctx.model.OrderExpress.update( + { weighing_weight: normalizedWeight }, + { where: { id: Number(expressRow.id) } } + ); + + ctx.logger.info('[Workbench._sendWeight] 散单称重 barcode=%s orderId=%d weightG=%s', + normalizedBarcode, orderId, normalizedWeight); + + // 写入操作日志 + await this._writeWeighOpLog({ + orderId, + barcode: normalizedBarcode, + weightGram, + normalizedWeight, + warehouseId, + }); + + return { + barcode: normalizedBarcode, + waybill_code: normalizedBarcode, + order_id: orderId, + weighing_weight: normalizedWeight, + items_weight: Number(orderRow.items_weight || 0), + mode: 'single', + }; + } + + // 步骤4:查询波次类型,判断是否为团购波次 + const waveRow = await ctx.model.WaveBatch.findOne({ + where: { wave_id: waveId, warehouse_id: warehouseId }, + attributes: [ 'wave_id', 'wave_no', 'wave_type' ], + raw: true, + }); + + // 非团购波次 → 降级为散单逻辑 + if (!waveRow || Number(waveRow.wave_type) !== 1) { + await ctx.model.OrderExpress.update( + { weighing_weight: normalizedWeight }, + { where: { id: Number(expressRow.id) } } + ); + + ctx.logger.info('[Workbench._sendWeight] 非团购波次称重 barcode=%s orderId=%d weightG=%s waveType=%s', + normalizedBarcode, orderId, normalizedWeight, waveRow ? waveRow.wave_type : 'N/A'); + + // 写入操作日志 + await this._writeWeighOpLog({ + orderId, + barcode: normalizedBarcode, + weightGram, + normalizedWeight, + warehouseId, + }); + + return { + barcode: normalizedBarcode, + waybill_code: normalizedBarcode, + order_id: orderId, + weighing_weight: normalizedWeight, + items_weight: Number(orderRow.items_weight || 0), + mode: 'single', + }; + } + + // 步骤5:团购波次(wave_type=1)→ 批量更新波次下所有运单的称重重量 + const { Op } = ctx.app.Sequelize; + const waveOrders = await orderDeliveryModel.findAll({ + where: { wave_id: waveId, warehouse_id: warehouseId }, + attributes: [ 'id' ], + raw: true, + }); + + if (!waveOrders || waveOrders.length === 0) { + throw new Error('波次下未找到订单'); + } + + const orderIds = waveOrders.map(o => Number(o.id)); + const totalCount = orderIds.length; + + await ctx.model.OrderExpress.update( + { weighing_weight: normalizedWeight }, + { + where: { + order_id: { [Op.in]: orderIds }, + delete_at: null, + }, + } + ); + + ctx.logger.info('[Workbench._sendWeight] 团购波次批量称重 barcode=%s waveId=%d waveNo=%s orderCount=%d weightG=%s', + normalizedBarcode, waveId, waveRow.wave_no, totalCount, normalizedWeight); + + // 写入操作日志(团购波次:逐订单批量写入) + await this._writeWeighOpLog({ + orderId, + barcode: normalizedBarcode, + weightGram, + normalizedWeight, + warehouseId, + waveId, + waveNo: String(waveRow.wave_no || ''), + waveOrderIds: orderIds, + }); + + return { + barcode: normalizedBarcode, + waybill_code: normalizedBarcode, + wave_id: waveId, + wave_no: String(waveRow.wave_no || ''), + weighing_weight: normalizedWeight, + total_weight: normalizedWeight * totalCount, + order_count: totalCount, + items_weight: Number(orderRow.items_weight || 0), + mode: 'wave', + }; + } + + /** + * 写入称重操作日志(内部方法,失败不影响主流程) + * @param {Object} opts + * @param {number} opts.orderId 触发订单ID + * @param {string} opts.barcode 条码/运单号 + * @param {number} opts.weightGram 称重重量(克) + * @param {number} opts.normalizedWeight 称重重量(克) + * @param {number} opts.warehouseId 仓库ID + * @param {number} [opts.waveId] 波次ID(团购时传入) + * @param {string} [opts.waveNo] 波次号 + * @param {number[]} [opts.waveOrderIds] 波次下所有订单ID(团购时传入,逐条写日志) + */ + async _writeWeighOpLog(opts = {}) { + const { ctx } = this; + const { + orderId, barcode, weightGram, normalizedWeight, warehouseId, + waveId, waveNo, waveOrderIds, + } = opts; + + try { + const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + if (!operationLogService || typeof operationLogService.createOperationLogs !== 'function') { + return; + } + + const isWave = waveId && waveId > 0 && Array.isArray(waveOrderIds) && waveOrderIds.length > 0; + const operator = { id: '', name: 'system' }; + + if (isWave) { + // 团购波次:逐订单批量写入操作日志 + const orderCount = waveOrderIds.length; + const message = `工作台团购波次称重 ${normalizedWeight}g,波次 ${waveNo || waveId},共 ${orderCount} 单,触发条码 ${barcode}`; + const payloads = waveOrderIds.map(oid => ({ + businessType: 'order', + businessId: String(oid), + operationCode: 'ORDER_WEIGH', + operator, + extras: { + warehouseId, + message, + barcode, + weightGram, + weighingWeight: normalizedWeight, + waveId, + waveNo: waveNo || '', + orderCount, + }, + })); + + await operationLogService.createOperationLogs(payloads); + ctx.logger.info('[Workbench._writeWeighOpLog] 团购称重操作日志已批量写入 waveId=%d orderCount=%d', + waveId, orderCount); + } else { + // 散单:单条操作日志 + const payload = { + businessType: 'order', + businessId: String(orderId), + operationCode: 'ORDER_WEIGH', + operator, + extras: { + warehouseId, + message: `工作台称重 ${normalizedWeight}g,条码 ${barcode}`, + barcode, + weightGram, + weighingWeight: normalizedWeight, + orderId, + }, + }; + + await operationLogService.createOperationLogs([ payload ]); + ctx.logger.info('[Workbench._writeWeighOpLog] 散单称重操作日志已写入 orderId=%d barcode=%s', + orderId, barcode); + } + } catch (e) { + ctx.logger.warn('[Workbench._writeWeighOpLog] 写入操作日志失败,不影响主流程', { + error: e && e.message, + orderId, + barcode, + }); + } + } + /** * 条码查订单:条码 → wms_order_express → 待处理/配送订单详情 * @param {Object} params - { barcode, warehouseId } @@ -483,8 +1132,8 @@ class WorkbenchService extends Service { where: { order_id: orderId }, attributes: [ 'id', 'order_id', 'item_id', 'item_code', 'item_name', - 'plan_qty', 'actual_qty', 'stock_id', 'order_line_no', - 'item_snapshot', + 'plan_qty', 'actual_price', 'stock_id', 'order_line_no', + 'inventory_type', 'item_snapshot', ], order: [[ 'id', 'ASC' ]], raw: true, @@ -500,7 +1149,7 @@ class WorkbenchService extends Service { const stockMap = new Map(); if (stockIds.length > 0) { try { - const stockDetails = await service.systems.stockWarehouse.getStockDetails( + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails( stockIds, { warehouseId } ); @@ -523,9 +1172,10 @@ class WorkbenchService extends Service { item_code: item.item_code || stock.item_code || '', item_name: item.item_name || stock.item_name || '', plan_qty: item.plan_qty, - actual_qty: item.actual_qty, + actual_price: item.actual_price, stock_id: stockId, order_line_no: item.order_line_no || '', + inventory_type: item.inventory_type || '', sku_property: stock.sku_property || '', stock_unit: stock.stock_unit || '', barcodes: stock.barcodes || [], diff --git a/database/migrations/20260715160000-create-wms-workbench.js b/database/migrations/20260715160000-create-wms-workbench.js new file mode 100644 index 0000000..4912d91 --- /dev/null +++ b/database/migrations/20260715160000-create-wms-workbench.js @@ -0,0 +1,89 @@ +'use strict'; + +const TABLE_NAME = 'wms_workbench'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + name: { + type: Sequelize.STRING(100), + allowNull: false, + comment: '工作台名称(用户自定义)', + }, + barcode: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '工作台条码(用户自定义,仓库内唯一)', + }, + status: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 1, + comment: '状态:0-禁用 1-启用', + }, + remark: { + type: Sequelize.STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '软删除时间', + }, + }); + + // 仓库隔离查询 + await queryInterface.addIndex(TABLE_NAME, ['warehouse_id'], { + name: 'idx_warehouse_id', + }); + + // 条码检索 + await queryInterface.addIndex(TABLE_NAME, ['barcode'], { + name: 'idx_barcode', + }); + + // 仓库级别唯一条码(含软删除,遵循 location_space 同款模式) + await queryInterface.addIndex(TABLE_NAME, ['warehouse_id', 'barcode', 'deleted_at'], { + unique: true, + name: 'uk_warehouse_barcode', + }); + + // 软删除查询优化 + await queryInterface.addIndex(TABLE_NAME, ['deleted_at'], { + name: 'idx_deleted_at', + }); + }, + + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260715170000-add-type-to-wms-workbench.js b/database/migrations/20260715170000-add-type-to-wms-workbench.js new file mode 100644 index 0000000..5ce0cda --- /dev/null +++ b/database/migrations/20260715170000-add-type-to-wms-workbench.js @@ -0,0 +1,19 @@ +'use strict'; + +const TABLE_NAME = 'wms_workbench'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'type', { + type: Sequelize.ENUM('personal', 'group'), + allowNull: false, + defaultValue: 'personal', + comment: '工作台类型:personal-个人工作台 group-团体工作台', + after: 'status', + }); + }, + + down: async (queryInterface) => { + await queryInterface.removeColumn(TABLE_NAME, 'type'); + }, +}; diff --git a/database/migrations/20260715180000-extend-wms-pack-task.js b/database/migrations/20260715180000-extend-wms-pack-task.js new file mode 100644 index 0000000..365b690 --- /dev/null +++ b/database/migrations/20260715180000-extend-wms-pack-task.js @@ -0,0 +1,160 @@ +'use strict'; + +const TABLE_NAME = 'wms_pack_task'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + // 1. 仓库隔离 + await queryInterface.addColumn(TABLE_NAME, 'warehouse_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '仓库ID', + after: 'order_id', + }); + + // 2. 工作台关联 + await queryInterface.addColumn(TABLE_NAME, 'workbench_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '工作台ID,关联 wms_workbench.id', + after: 'warehouse_id', + }); + + // 3. 波次信息 + await queryInterface.addColumn(TABLE_NAME, 'wave_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: 0, + comment: '波次ID', + after: 'workbench_id', + }); + await queryInterface.addColumn(TABLE_NAME, 'wave_no', { + type: Sequelize.STRING(50), + allowNull: true, + comment: '波次号', + after: 'wave_id', + }); + + // 4. 运单号 + await queryInterface.addColumn(TABLE_NAME, 'waybill_code', { + type: Sequelize.STRING(50), + allowNull: true, + comment: '运单号', + after: 'wave_no', + }); + + // 5. 打包数量 + await queryInterface.addColumn(TABLE_NAME, 'pack_quantity', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: true, + defaultValue: 0, + comment: '打包数量(件数)', + after: 'waybill_code', + }); + + // 6. 作业时间 + await queryInterface.addColumn(TABLE_NAME, 'start_time', { + type: Sequelize.DATE, + allowNull: true, + comment: '开始打包时间', + after: 'pack_quantity', + }); + await queryInterface.addColumn(TABLE_NAME, 'end_time', { + type: Sequelize.DATE, + allowNull: true, + comment: '结束打包时间', + after: 'start_time', + }); + + // 7. 作业人员(兼容多人的自由文本) + await queryInterface.addColumn(TABLE_NAME, 'operator_text', { + type: Sequelize.TEXT, + allowNull: true, + comment: '作业人员(自由文本,如多人逗号分隔)', + after: 'end_time', + }); + + // 8. 设备IDS(JSON列表) + await queryInterface.addColumn(TABLE_NAME, 'device_ids', { + type: Sequelize.JSON, + allowNull: true, + comment: '设备ID列表,如 [1,2,3]', + after: 'operator_text', + }); + + // 9. 包材信息 + await queryInterface.addColumn(TABLE_NAME, 'package_material_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '包材ID,关联 wms_package_material.id', + after: 'device_ids', + }); + await queryInterface.addColumn(TABLE_NAME, 'package_material_snapshot', { + type: Sequelize.STRING(200), + allowNull: true, + comment: '包材快照(编码+名称)', + after: 'package_material_id', + }); + + // 10. 称重 + await queryInterface.addColumn(TABLE_NAME, 'weighing_weight', { + type: Sequelize.DECIMAL(10, 3), + allowNull: true, + comment: '打包称重(kg)', + after: 'package_material_snapshot', + }); + + // 11. 异常 + await queryInterface.addColumn(TABLE_NAME, 'abnormal_reason', { + type: Sequelize.STRING(500), + allowNull: true, + comment: '异常原因', + after: 'weighing_weight', + }); + + // 12. 备注 + await queryInterface.addColumn(TABLE_NAME, 'remark', { + type: Sequelize.STRING(500), + allowNull: true, + comment: '备注', + after: 'abnormal_reason', + }); + + // 13. 修改 status 注释以包含更多状态 + await queryInterface.changeColumn(TABLE_NAME, 'status', { + type: Sequelize.TINYINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '任务状态:0=待处理 1=打包中 2=已完成 3=异常', + }); + + // ======== 索引 ======== + await queryInterface.addIndex(TABLE_NAME, ['warehouse_id'], { name: 'idx_warehouse_id' }); + await queryInterface.addIndex(TABLE_NAME, ['workbench_id'], { name: 'idx_workbench_id' }); + await queryInterface.addIndex(TABLE_NAME, ['wave_id'], { name: 'idx_wave_id' }); + await queryInterface.addIndex(TABLE_NAME, ['waybill_code'], { name: 'idx_waybill_code' }); + await queryInterface.addIndex(TABLE_NAME, ['start_time'], { name: 'idx_start_time' }); + await queryInterface.addIndex(TABLE_NAME, ['status'], { name: 'idx_status' }); + }, + + down: async queryInterface => { + const cols = [ + 'remark', 'abnormal_reason', 'weighing_weight', + 'package_material_snapshot', 'package_material_id', + 'device_ids', 'operator_text', 'end_time', 'start_time', + 'pack_quantity', 'waybill_code', 'wave_no', 'wave_id', + 'workbench_id', 'warehouse_id', + ]; + for (const col of cols) { + await queryInterface.removeColumn(TABLE_NAME, col); + } + + await queryInterface.removeIndex(TABLE_NAME, 'idx_status'); + await queryInterface.removeIndex(TABLE_NAME, 'idx_start_time'); + await queryInterface.removeIndex(TABLE_NAME, 'idx_waybill_code'); + await queryInterface.removeIndex(TABLE_NAME, 'idx_wave_id'); + await queryInterface.removeIndex(TABLE_NAME, 'idx_workbench_id'); + await queryInterface.removeIndex(TABLE_NAME, 'idx_warehouse_id'); + }, +}; diff --git a/database/migrations/20260715190000-remove-redundant-packer-fields.js b/database/migrations/20260715190000-remove-redundant-packer-fields.js new file mode 100644 index 0000000..93bab49 --- /dev/null +++ b/database/migrations/20260715190000-remove-redundant-packer-fields.js @@ -0,0 +1,36 @@ +'use strict'; + +const TABLE_NAME = 'wms_pack_task'; + +module.exports = { + up: async queryInterface => { + // 打包人信息已由 wms_pack_task_packer 子表承载,删除主表冗余字段 + await queryInterface.removeColumn(TABLE_NAME, 'primary_packer_emp_id'); + await queryInterface.removeColumn(TABLE_NAME, 'primary_packer_emp_no'); + await queryInterface.removeColumn(TABLE_NAME, 'primary_packer_name'); + await queryInterface.removeColumn(TABLE_NAME, 'packers_snapshot'); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'primary_packer_emp_id', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: true, + comment: '主打包人工号ID', + }); + await queryInterface.addColumn(TABLE_NAME, 'primary_packer_emp_no', { + type: Sequelize.STRING(64), + allowNull: true, + comment: '主打包人工号', + }); + await queryInterface.addColumn(TABLE_NAME, 'primary_packer_name', { + type: Sequelize.STRING(128), + allowNull: true, + comment: '主打包人姓名', + }); + await queryInterface.addColumn(TABLE_NAME, 'packers_snapshot', { + type: Sequelize.JSON, + allowNull: true, + comment: '打包人快照:散单对象/团购数组', + }); + }, +}; diff --git a/database/migrations/20260715200000-remove-redundant-material-fields.js b/database/migrations/20260715200000-remove-redundant-material-fields.js new file mode 100644 index 0000000..e40cb8e --- /dev/null +++ b/database/migrations/20260715200000-remove-redundant-material-fields.js @@ -0,0 +1,36 @@ +'use strict'; + +const TABLE_NAME = 'wms_pack_task'; + +module.exports = { + up: async queryInterface => { + // 包材/称重/异常已由 wms_order_express 表(按运单号维度)承载,删除冗余 + await queryInterface.removeColumn(TABLE_NAME, 'package_material_id'); + await queryInterface.removeColumn(TABLE_NAME, 'package_material_snapshot'); + await queryInterface.removeColumn(TABLE_NAME, 'weighing_weight'); + await queryInterface.removeColumn(TABLE_NAME, 'abnormal_reason'); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'package_material_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '包材ID,关联 wms_package_material.id', + }); + await queryInterface.addColumn(TABLE_NAME, 'package_material_snapshot', { + type: Sequelize.STRING(200), + allowNull: true, + comment: '包材快照(编码+名称)', + }); + await queryInterface.addColumn(TABLE_NAME, 'weighing_weight', { + type: Sequelize.DECIMAL(10, 3), + allowNull: true, + comment: '打包称重(kg)', + }); + await queryInterface.addColumn(TABLE_NAME, 'abnormal_reason', { + type: Sequelize.STRING(500), + allowNull: true, + comment: '异常原因', + }); + }, +}; diff --git a/database/migrations/20260715210000-add-device-ids-to-wms-workbench.js b/database/migrations/20260715210000-add-device-ids-to-wms-workbench.js new file mode 100644 index 0000000..a76c697 --- /dev/null +++ b/database/migrations/20260715210000-add-device-ids-to-wms-workbench.js @@ -0,0 +1,18 @@ +'use strict'; + +const TABLE_NAME = 'wms_workbench'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'device_ids', { + type: Sequelize.JSON, + allowNull: true, + comment: '设备ID列表,如 [1,2,3],触发打包任务时透传到 wms_pack_task.device_ids', + after: 'remark', + }); + }, + + down: async queryInterface => { + await queryInterface.removeColumn(TABLE_NAME, 'device_ids'); + }, +}; diff --git a/database/migrations/20260719120000-add-packing-flow-permission.js b/database/migrations/20260719120000-add-packing-flow-permission.js new file mode 100644 index 0000000..8a13f36 --- /dev/null +++ b/database/migrations/20260719120000-add-packing-flow-permission.js @@ -0,0 +1,17 @@ +'use strict'; + +module.exports = { + async up(queryInterface) { + // 在"数据"(id=16)菜单下新增"打包流水"页面权限 + await queryInterface.sequelize.query(` + INSERT INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, sort, status, created_at, update_at, type) + VALUES (449, 'PackingFlow', '@/views/storage/packingflow/index', 'PackingFlow', '', '打包流水', '', 0, 0, 16, 1, 1, NOW(), NOW(), 'web_pages') + `); + }, + + async down(queryInterface) { + await queryInterface.sequelize.query(` + DELETE FROM wms_permission WHERE id = 449 AND path = 'PackingFlow' + `); + }, +}; diff --git a/database/migrations/20260719130000-grant-packing-review-permissions.js b/database/migrations/20260719130000-grant-packing-review-permissions.js new file mode 100644 index 0000000..bf91711 --- /dev/null +++ b/database/migrations/20260719130000-grant-packing-review-permissions.js @@ -0,0 +1,36 @@ +'use strict'; + +module.exports = { + async up(queryInterface) { + // 给客服及以上角色追加 打包流水(449) 和 复核流水(450) 权限 + // 排除 permissions='*' 的角色(已有全部权限) + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_ARRAY_APPEND(permissions, '$', 449, '$', 450), + updated_at = NOW() + WHERE id IN (5, 8, 26, 27, 28, 29, 30, 31, 32, 33, 34) + AND permissions IS NOT NULL + AND permissions != '*' + AND permissions != '[]' + AND JSON_VALID(permissions) = 1 + AND JSON_CONTAINS(permissions, '449', '$') = 0 + `); + }, + + async down(queryInterface) { + // 回滚:从角色权限中移除 449 和 450 + await queryInterface.sequelize.query(` + UPDATE wms_role + SET permissions = JSON_REMOVE( + JSON_REMOVE(permissions, JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '449'))), + JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '450')) + ), + updated_at = NOW() + WHERE id IN (5, 8, 26, 27, 28, 29, 30, 31, 32, 33, 34) + AND permissions IS NOT NULL + AND permissions != '*' + AND JSON_VALID(permissions) = 1 + AND JSON_CONTAINS(permissions, '449', '$') = 1 + `); + }, +}; diff --git a/database/migrations/20260719150000-refactor-pack-task-packer-fields.js b/database/migrations/20260719150000-refactor-pack-task-packer-fields.js new file mode 100644 index 0000000..123beee --- /dev/null +++ b/database/migrations/20260719150000-refactor-pack-task-packer-fields.js @@ -0,0 +1,76 @@ +'use strict'; + +const TABLE_NAME = 'wms_pack_task_packer'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + // 0. 清空已有数据(字段结构变更,emp 字段无法映射到新字段) + await queryInterface.bulkDelete(TABLE_NAME, {}); + + // 1. 删除旧索引 + await queryInterface.removeIndex(TABLE_NAME, 'uix_pack_task_emp'); + await queryInterface.removeIndex(TABLE_NAME, 'idx_emp_id'); + + // 2. 删除旧字段 + await queryInterface.removeColumn(TABLE_NAME, 'emp_id'); + await queryInterface.removeColumn(TABLE_NAME, 'emp_no'); + await queryInterface.removeColumn(TABLE_NAME, 'emp_name'); + + // 3. 新增 account 字段 + await queryInterface.addColumn(TABLE_NAME, 'account_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '账号ID,关联 wms_account.id', + }); + await queryInterface.addColumn(TABLE_NAME, 'account_name', { + type: Sequelize.STRING(128), + allowNull: false, + comment: '账号姓名快照', + }); + + // 4. 建新索引 + await queryInterface.addIndex(TABLE_NAME, [ 'pack_task_id', 'account_id' ], { + name: 'uix_pack_task_account', + unique: true, + }); + await queryInterface.addIndex(TABLE_NAME, [ 'account_id' ], { + name: 'idx_account_id', + }); + }, + + down: async (queryInterface, Sequelize) => { + // 1. 删除新索引 + await queryInterface.removeIndex(TABLE_NAME, 'uix_pack_task_account'); + await queryInterface.removeIndex(TABLE_NAME, 'idx_account_id'); + + // 2. 删除新字段 + await queryInterface.removeColumn(TABLE_NAME, 'account_id'); + await queryInterface.removeColumn(TABLE_NAME, 'account_name'); + + // 3. 恢复旧字段 + await queryInterface.addColumn(TABLE_NAME, 'emp_id', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: false, + comment: '打包人工号ID', + }); + await queryInterface.addColumn(TABLE_NAME, 'emp_no', { + type: Sequelize.STRING(64), + allowNull: false, + comment: '打包人工号', + }); + await queryInterface.addColumn(TABLE_NAME, 'emp_name', { + type: Sequelize.STRING(128), + allowNull: false, + comment: '打包人姓名', + }); + + // 4. 恢复旧索引 + await queryInterface.addIndex(TABLE_NAME, [ 'pack_task_id', 'emp_id' ], { + name: 'uix_pack_task_emp', + unique: true, + }); + await queryInterface.addIndex(TABLE_NAME, [ 'emp_id' ], { + name: 'idx_emp_id', + }); + }, +}; diff --git a/database/migrations/20260725200000-add-item-quantity-sku-count-to-wms-pack-task.js b/database/migrations/20260725200000-add-item-quantity-sku-count-to-wms-pack-task.js new file mode 100644 index 0000000..df61b10 --- /dev/null +++ b/database/migrations/20260725200000-add-item-quantity-sku-count-to-wms-pack-task.js @@ -0,0 +1,36 @@ +'use strict'; + +module.exports = { + /** + * 为打包任务表新增"商品数量"和"商品种类数"字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_pack_task', 'item_quantity', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: true, + defaultValue: 0, + comment: '商品总数量', + }); + + await queryInterface.addColumn('wms_pack_task', 'sku_count', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: true, + defaultValue: 0, + comment: '商品种类数(SKU数)', + }); + }, + + /** + * 回滚删除打包任务表的"商品数量"和"商品种类数"字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + await queryInterface.removeColumn('wms_pack_task', 'sku_count'); + await queryInterface.removeColumn('wms_pack_task', 'item_quantity'); + }, +};