diff --git a/app/service/systemMethods/warehouse.js b/app/service/systemMethods/warehouse.js index 2e14924..27a7db4 100644 --- a/app/service/systemMethods/warehouse.js +++ b/app/service/systemMethods/warehouse.js @@ -1,5 +1,6 @@ 'use strict'; +const ExcelJS = require('exceljs'); const MainService = require('../main'); class warehouseService extends MainService { @@ -360,7 +361,7 @@ class warehouseService extends MainService { zone_id: id, deleted_at: null, }, - order: [[ 'pick_sequence', 'ASC' ]], + order: [[ 'space_code', 'ASC' ]], }); return this.success('获取成功', { spaces, code: 200 }); } catch (e) { @@ -380,6 +381,7 @@ class warehouseService extends MainService { id, deleted_at: null, }, + lock: transaction.LOCK.UPDATE, transaction, }); if (!rack) { @@ -450,5 +452,398 @@ class warehouseService extends MainService { } } + + getBatchFieldValue(row, keys) { + for (const key of keys) { + if (Object.prototype.hasOwnProperty.call(row, key)) { + return row[key]; + } + } + return undefined; + } + + hasBatchField(row, keys) { + return keys.some(key => Object.prototype.hasOwnProperty.call(row, key)); + } + + normalizeBatchString(value) { + if (value === undefined || value === null) { + return null; + } + const normalized = String(value).trim(); + return normalized === '' ? null : normalized; + } + + async getCurrentWarehouseCode(warehouseId, transaction) { + const { ctx } = this; + const warehouseZone = await ctx.model.LocationZone.findOne({ + where: { + warehouse_id: warehouseId, + zone_type: 'warehouse', + deleted_at: null, + }, + attributes: [ 'zone_code' ], + order: [[ 'id', 'ASC' ]], + raw: true, + transaction, + }); + + return String(warehouseZone && warehouseZone.zone_code || warehouseId).trim(); + } + + async batchUpdateSpaceInfo(data) { + const { ctx } = this; + const { Op } = this.app.Sequelize; + const warehouseId = ctx.user && ctx.user.store_id; + const items = Array.isArray(data && data.items) ? data.items : (Array.isArray(data && data.list) ? data.list : []); + const rackId = data && data.id ? Number(data.id) : null; + + if (!warehouseId) { + return this.fail('缺少当前仓库上下文'); + } + if (items.length === 0) { + return this.fail('批量数据不能为空'); + } + if (rackId !== null && (!Number.isFinite(rackId) || rackId <= 0)) { + return this.fail('货架ID格式不正确'); + } + + const transaction = await ctx.model.transaction(); + try { + const seenSpaceCodes = new Set(); + const seenBarcodes = new Map(); + const normalizedItems = []; + const typeIdSet = new Set(); + const MAX_PICK_SEQUENCE = 2147483647; + + for (let index = 0; index < items.length; index++) { + const row = items[index]; + const rowNo = index + 1; + + if (!row || typeof row !== 'object' || Array.isArray(row)) { + throw new Error(`第 ${rowNo} 行数据格式不正确`); + } + + const spaceCode = this.normalizeBatchString(this.getBatchFieldValue(row, [ 'space_code', '仓位编码' ])); + if (!spaceCode) { + throw new Error(`第 ${rowNo} 行缺少仓位编码`); + } + if (seenSpaceCodes.has(spaceCode)) { + throw new Error(`第 ${rowNo} 行仓位编码重复: ${spaceCode}`); + } + seenSpaceCodes.add(spaceCode); + + const customName = this.normalizeBatchString(this.getBatchFieldValue(row, [ 'custom_name', '自定义名称' ])); + if (customName && customName.length > 100) { + throw new Error(`第 ${rowNo} 行自定义名称超出长度边界`); + } + + const customBarcode = this.normalizeBatchString(this.getBatchFieldValue(row, [ 'custom_barcode', '自定义条码' ])); + if (customBarcode && customBarcode.length > 100) { + throw new Error(`第 ${rowNo} 行自定义条码超出长度边界`); + } + if (customBarcode) { + const duplicateRowNo = seenBarcodes.get(customBarcode); + if (duplicateRowNo) { + throw new Error(`第 ${rowNo} 行自定义条码重复,首次出现在第 ${duplicateRowNo} 行`); + } + seenBarcodes.set(customBarcode, rowNo); + } + + const hasPickSequence = this.hasBatchField(row, [ 'pick_sequence', '拣货顺序' ]); + const rawPickSequence = this.getBatchFieldValue(row, [ 'pick_sequence', '拣货顺序' ]); + let pickSequence = null; + if (hasPickSequence) { + if (rawPickSequence === '' || rawPickSequence === null || rawPickSequence === undefined) { + pickSequence = null; + } else if (!Number.isInteger(Number(rawPickSequence))) { + throw new Error(`第 ${rowNo} 行拣货顺序必须为整数`); + } else { + pickSequence = Number(rawPickSequence); + if (pickSequence < 0 || pickSequence > MAX_PICK_SEQUENCE) { + throw new Error(`第 ${rowNo} 行拣货顺序超出边界`); + } + } + } + + const hasLocationTypeId = this.hasBatchField(row, [ 'location_type_id' ]); + const rawLocationTypeId = this.getBatchFieldValue(row, [ 'location_type_id' ]); + let locationTypeId = null; + if (hasLocationTypeId) { + if (rawLocationTypeId === '' || rawLocationTypeId === null || rawLocationTypeId === undefined) { + locationTypeId = null; + } else if (!Number.isInteger(Number(rawLocationTypeId)) || Number(rawLocationTypeId) <= 0) { + throw new Error(`第 ${rowNo} 行仓位类型ID必须为正整数`); + } else { + locationTypeId = Number(rawLocationTypeId); + typeIdSet.add(locationTypeId); + } + } + + normalizedItems.push({ + rowNo, + spaceCode, + customName, + customBarcode, + hasPickSequence, + pickSequence, + locationTypeId, + hasCustomName: this.hasBatchField(row, [ 'custom_name', '自定义名称' ]), + hasCustomBarcode: this.hasBatchField(row, [ 'custom_barcode', '自定义条码' ]), + hasLocationTypeId, + }); + } + + const spaces = await ctx.model.LocationSpace.findAll({ + where: { + warehouse_id: warehouseId, + deleted_at: null, + space_code: Array.from(seenSpaceCodes), + }, + include: [ + { + model: ctx.model.LocationZone, + as: 'zone', + attributes: [ 'id', 'zone_type' ], + required: true, + where: { + zone_type: 'rack', + deleted_at: null, + ...(rackId !== null ? { id: rackId } : {}), + }, + }, + ], + transaction, + lock: transaction.LOCK.UPDATE, + }); + + const spaceMap = new Map(); + for (const space of spaces) { + spaceMap.set(String(space.space_code).trim(), space); + } + + const missingSpaceCodes = normalizedItems + .map(item => item.spaceCode) + .filter(spaceCode => !spaceMap.has(spaceCode)); + if (missingSpaceCodes.length > 0) { + throw new Error(`提交数据超出货架库位边界,以下仓位不存在或不属于当前货架: ${missingSpaceCodes.slice(0, 10).join(', ')}`); + } + + const targetIds = spaces.map(item => item.id); + if (targetIds.length !== normalizedItems.length) { + throw new Error('提交数据超出货架库位边界'); + } + + if (typeIdSet.size > 0) { + const locationTypes = await ctx.model.LocationType.findAll({ + where: { + id: Array.from(typeIdSet), + is_active: true, + [Op.or]: [ + { warehouse_id: warehouseId }, + { warehouse_id: null }, + ], + }, + attributes: [ 'id' ], + raw: true, + transaction, + }); + + const validTypeIds = new Set(locationTypes.map(lt => lt.id)); + const invalidTypeIds = Array.from(typeIdSet).filter(id => !validTypeIds.has(id)); + if (invalidTypeIds.length > 0) { + throw new Error(`存在无效仓位类型ID: ${invalidTypeIds.join(', ')}`); + } + } + + for (const item of normalizedItems) { + if (!item.customBarcode) { + continue; + } + const matchedSpace = spaceMap.get(item.customBarcode); + if (matchedSpace && String(matchedSpace.space_code).trim() !== item.spaceCode) { + throw new Error(`第 ${item.rowNo} 行自定义条码与其他仓位编码冲突: ${item.customBarcode}`); + } + } + + const requestedBarcodes = normalizedItems + .map(item => item.customBarcode) + .filter(Boolean); + if (requestedBarcodes.length > 0) { + const conflictSpace = await ctx.model.LocationSpace.findOne({ + where: { + deleted_at: null, + id: { + [Op.notIn]: targetIds, + }, + custom_barcode: requestedBarcodes, + }, + attributes: [ 'id', 'space_code', 'custom_barcode' ], + raw: true, + transaction, + }); + + if (conflictSpace) { + throw new Error(`存在重复条码冲突: ${conflictSpace.custom_barcode}`); + } + } + + await Promise.all(normalizedItems.map(item => { + const space = spaceMap.get(item.spaceCode); + const updateData = { + updated_by: ctx.user.id, + }; + + if (item.hasLocationTypeId) { + updateData.location_type_id = item.locationTypeId !== null ? item.locationTypeId : null; + } + if (item.hasCustomName) { + updateData.custom_name = item.customName; + } + if (item.hasCustomBarcode) { + updateData.custom_barcode = item.customBarcode; + } + if (item.hasPickSequence) { + updateData.pick_sequence = item.pickSequence; + } + + return space.update(updateData, { transaction }); + })); + + await transaction.commit(); + return this.success('批量保存成功', { + code: 200, + count: normalizedItems.length, + }); + } catch (error) { + await transaction.rollback(); + return this.fail(`批量保存失败: ${error.message}`, { code: 500 }); + } + } + + async exportRackSpaces(data) { + const { ctx } = this; + const { Op } = this.app.Sequelize; + const warehouseId = ctx.user && ctx.user.store_id; + const rackId = Number(data && data.id); + + if (!warehouseId) { + return this.fail('缺少当前仓库上下文'); + } + if (!Number.isFinite(rackId) || rackId <= 0) { + return this.fail('导出失败: 货架ID不能为空', { code: 500 }); + } + + try { + const warehouseCode = await this.getCurrentWarehouseCode(warehouseId); + + const rackZone = await ctx.model.LocationZone.findOne({ + where: { + id: rackId, + warehouse_id: warehouseId, + zone_type: 'rack', + deleted_at: null, + }, + attributes: [ 'id', 'zone_code' ], + raw: true, + }); + + if (!rackZone) { + return this.fail('导出失败: 指定货架不存在或不属于当前仓库', { code: 500 }); + } + + const [ spaces, locationTypes ] = await Promise.all([ + ctx.model.LocationSpace.findAll({ + where: { + warehouse_id: warehouseId, + deleted_at: null, + zone_id: rackId, + }, + attributes: [ 'id', 'space_code', 'custom_name', 'custom_barcode', 'pick_sequence', 'location_type_id' ], + include: [ + { + model: ctx.model.LocationType, + as: 'locationType', + attributes: [ 'type_name' ], + required: false, + }, + ], + order: [[ 'space_code', 'ASC' ], [ 'id', 'ASC' ]], + }), + ctx.model.LocationType.findAll({ + where: { + is_active: true, + [Op.or]: [ + { warehouse_id: warehouseId }, + { warehouse_id: null }, + ], + }, + attributes: [ 'type_name' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }), + ]); + + if (!Array.isArray(spaces) || spaces.length === 0) { + return this.fail('导出失败: 指定货架下没有可导出的仓位数据', { code: 500 }); + } + + const locationTypeNames = locationTypes + .map(t => String(t.type_name || '').trim()) + .filter(Boolean); + + const workbook = new ExcelJS.Workbook(); + const worksheet = workbook.addWorksheet('货架导出'); + + worksheet.columns = [ + { header: '仓位编码', key: 'space_code', width: 20 }, + { header: '自定义名称', key: 'custom_name', width: 24 }, + { header: '自定义条码', key: 'custom_barcode', width: 24 }, + { header: '拣货顺序', key: 'pick_sequence', width: 14 }, + { header: '仓位类型', key: 'location_type_name', width: 18 }, + ]; + + worksheet.getRow(1).font = { bold: true }; + + for (const space of spaces) { + const row = typeof space.get === 'function' ? space.get({ plain: true }) : space; + worksheet.addRow({ + space_code: row && row.space_code ? String(row.space_code) : '', + custom_name: row && row.custom_name ? String(row.custom_name) : '', + custom_barcode: row && row.custom_barcode ? String(row.custom_barcode) : '', + pick_sequence: row && row.pick_sequence !== null && row.pick_sequence !== undefined ? Number(row.pick_sequence) : '', + location_type_name: String(row && row.locationType && row.locationType.type_name || '').trim(), + }); + } + + if (locationTypeNames.length > 0) { + const typeSheet = workbook.addWorksheet('_仓位类型', { state: 'veryHidden' }); + locationTypeNames.forEach((name, i) => { + typeSheet.getCell(i + 1, 1).value = name; + }); + const lastDataRow = spaces.length + 1; + worksheet.dataValidations.add(`E2:E${lastDataRow}`, { + type: 'list', + allowBlank: true, + formulae: [ `_仓位类型!$A$1:$A$${locationTypeNames.length}` ], + }); + } + + const rackCode = String(rackZone.zone_code || rackId).trim(); + const filename = `warehouse-rack-spaces-${warehouseCode || warehouseId}-${rackCode}.xlsx`; + const buffer = await workbook.xlsx.writeBuffer(); + const base64 = Buffer.from(buffer).toString('base64'); + + return this.success('导出成功', { + code: 200, + count: Array.isArray(spaces) ? spaces.length : 0, + base64, + filename, + mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + }); + } catch (error) { + return this.fail(`导出失败: ${error.message}`); + } + } } module.exports = warehouseService; diff --git a/methods/system.json b/methods/system.json index 724407a..ca52e54 100644 --- a/methods/system.json +++ b/methods/system.json @@ -552,6 +552,76 @@ "isNeedAuth": false, "isNeedLogin": true, "params": [] + }, + { + "method": "index.getLocationTypeList", + "description": "查询库位类型基础列表,优先返回当前仓库下启用的库位类型,同时合并系统公共类型;结果带 300 秒缓存", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "list", + "type": "array", + "description": "库位类型列表", + "children": [ + { + "name": "id", + "type": "number", + "description": "库位类型 ID" + }, + { + "name": "type_code", + "type": "string", + "description": "库位类型编码" + }, + { + "name": "type_name", + "type": "string", + "description": "库位类型名称" + }, + { + "name": "temperature_zone", + "type": "string", + "description": "温区" + }, + { + "name": "allow_allocation", + "type": "boolean", + "description": "是否允许分配储位" + }, + { + "name": "allow_transfer_out", + "type": "boolean", + "description": "是否允许移出" + }, + { + "name": "description", + "type": "string", + "description": "描述" + }, + { + "name": "warehouse_id", + "type": "number", + "description": "所属仓库 ID,null 表示系统公共类型" + } + ] + }, + { + "name": "total", + "type": "number", + "description": "返回总数" + } + ], + "errors": [] } ] }, @@ -10041,6 +10111,120 @@ "response": [], "errors": [] }, + { + "method": "warehouse.exportRackSpaces", + "description": "按货架ID导出仓位模板(含仓库编码、仓位编码、自定义名称、自定义条码、拣货顺序、仓位类型)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "货架ID,仅导出该货架下仓位" + } + ], + "response": [ + { + "name": "count", + "type": "number", + "description": "导出记录数" + }, + { + "name": "fileName", + "type": "string", + "description": "导出文件名" + }, + { + "name": "fileUrl", + "type": "string", + "description": "导出文件下载地址" + } + ], + "errors": [] + }, + { + "method": "warehouse.batchUpdateSpaceInfo", + "description": "按导出模板批量修改货架仓位信息,任一行越界或冲突则整批失败。前端提交示例:{ id: 36, items: [ { space_code: 'A01-01-01', custom_name: '拣货位1', custom_barcode: 'PICK-001', pick_sequence: 10, location_type_id: 3 } ] }。其中 id 为货架ID(可选,传入时只允许操作该货架下的仓位),space_code 为必填定位键,location_type_id 为仓位类型主键(可通过 index.getLocationTypeList 获取)。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "货架ID,传入时校验所有 space_code 必须属于该货架,不传则只校验属于任意货架类型库位" + }, + { + "name": "items", + "type": "array", + "required": true, + "source": "body", + "description": "批量修改数据数组;每项支持字段:space_code、custom_name、custom_barcode、pick_sequence、location_type_name" + }, + { + "name": "items[].space_code", + "type": "string", + "required": true, + "source": "body", + "description": "仓位编码,作为批量修改的唯一定位键;缺失、重复或不存在都会整批失败" + }, + { + "name": "items[].custom_name", + "type": "string", + "required": false, + "source": "body", + "description": "自定义名称,空字符串会被清空" + }, + { + "name": "items[].custom_barcode", + "type": "string", + "required": false, + "source": "body", + "description": "自定义条码,批次内或系统内冲突都会整批失败;空字符串会被清空" + }, + { + "name": "items[].pick_sequence", + "type": "number", + "required": false, + "source": "body", + "description": "拣货顺序,必须为非负整数,超出边界则整批失败" + }, + { + "name": "items[].location_type_id", + "type": "number", + "required": false, + "source": "body", + "description": "仓位类型ID,必须为正整数且在当前仓库或全局类型中存在(is_active=true),否则整批失败;传 null 或不传则不修改仓位类型" + } + ], + "response": [ + { + "name": "count", + "type": "number", + "description": "成功更新的记录数" + } + ], + "errors": [] + }, { "method": "warehouse.getSpaceInfo", "description": "warehouse.getSpaceInfo 接口", diff --git a/runtime/file-writer/qimen-logs/.consume-progress b/runtime/file-writer/qimen-logs/.consume-progress index 8ba54cd..7075d21 100644 --- a/runtime/file-writer/qimen-logs/.consume-progress +++ b/runtime/file-writer/qimen-logs/.consume-progress @@ -2,6 +2,6 @@ "filePath": "D:\\wms\\runtime\\file-writer\\qimen-logs\\2026\\04\\12\\qimen-logs-MINGREN-worker-p38224-0001.log", "offset": 1713, "processedCount": 1, - "completedAt": "2026-04-12T14:46:52.525Z", - "updatedAt": "2026-04-27T08:09:00.255Z" + "completedAt": "2026-04-12T14:54:22.636Z", + "updatedAt": "2026-04-17T12:02:32.964Z" }