2026-05-17 21:51:46 +08:00

829 lines
25 KiB
JavaScript

'use strict';
const ExcelJS = require('exceljs');
const MainService = require('../main');
class warehouseService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'detail,getSpacesByRack,createRackWithSpaces,getSpaceInfo,checkBarcodeUnique';
const _noNeedLog = '*';
const _noNeedAuth = 'detail,getSpacesByRack,getSpaceInfo,checkBarcodeUnique,getWarehouseZones,getWarehouseTree,getChildren,toggleActive,getPath,getPickPath,getAreaRacks';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
async getWarehouseZones() {
const { ctx, service } = this;
try {
const zones = await service.systems.locationZone.getWarehouseLevelZones(ctx.user.store_id);
return this.success('获取成功', { zones, code: 200 });
} catch (error) {
return this.fail('获取失败' + error.message, { code: 0 });
}
}
/**
* 获取仓库树状结构
* @param {Object} data 请求体
*/
async getWarehouseTree(data) {
const { service } = this;
const { warehouseId } = data;
try {
if (!warehouseId) {
return this.fail('仓库ID不能为空');
}
const tree = await service.systems.locationZone.getZoneTreeByWarehouse(parseInt(warehouseId));
return this.success('获取成功', tree);
} catch (error) {
return this.fail(error.message);
}
}
/**
* 获取子节点(懒加载)
* @param {Object} data 请求体
*/
async getChildren(data) {
const { ctx, service } = this;
const { zoneId } = data;
try {
if (!zoneId) {
throw new Error('分区ID不能为空');
}
const children = await service.systems.locationZone.getChildrenByZoneId(parseInt(zoneId));
ctx.success(children);
} catch (error) {
this.fail(error.message);
}
}
/**
* 创建分区
* @param {Object} data 请求体
*/
async create(data) {
const { service } = this;
try {
const result = await service.systems.locationZone.createZone(data);
return this.success(result.message, { data: result.data, code: 200 });
} catch (error) {
return this.fail(error.message);
}
}
/**
* 更新分区
* @param {Object} datas 请求体
*/
async update(datas) {
const { service } = this;
const { id } = datas;
const { length, width, height, is_active, zone_code, zone_name, x, y, z, direction, rack_columns, rack_levels, rack_rows, cell_width, cell_length, cell_height, aisles } = datas;
try {
if (!id) {
return this.fail('分区ID不能为空');
}
const result = await service.systems.locationZone.updateZone(parseInt(id), { length, width, height, is_active, zone_code, zone_name, x, y, z, direction, rack_columns, rack_levels, rack_rows, cell_width, cell_length, cell_height, aisles });
return this.success(result.message, { data: result.data, code: 200 });
} catch (error) {
return this.fail(error.message);
}
}
/**
* 删除分区
* @param {Object} data 请求体
*/
async delete(data) {
const { service } = this;
const { id } = data;
try {
if (!id) {
return this.fail('分区ID不能为空');
}
const result = await service.systems.locationZone.deleteZone(parseInt(id));
return this.success(result.message, { code: 200 });
} catch (error) {
return this.fail(error.message);
}
}
/**
* 获取分区详情
* @param {Object} data 请求体
*/
async detail(data) {
const { service } = this;
const { id } = data;
try {
if (!id) {
return this.fail('分区ID不能为空');
}
const zone = await service.systems.locationZone.getZoneDetail(parseInt(id));
return this.success('获取成功', zone);
} catch (error) {
return this.fail(error.message);
}
}
async checkBarcodeUnique(data) {
const { service } = this;
const { id, barcode } = data;
try {
if (!id) {
return this.fail('库位ID不能为空');
}
if (!barcode) {
return this.fail('条码不能为空');
}
const data = await service.systems.locationZone.checkBarcodeUnique(parseInt(id), barcode);
return this.success('获取成功', { data, code: 200 });
} catch (error) {
return this.fail(error.message);
}
}
/**
* 切换分区状态
* @param {Object} data 请求体
*/
async toggleActive(data) {
const { ctx, service } = this;
const { id, isActive } = data;
try {
if (!id) {
throw new Error('分区ID不能为空');
}
const result = await service.systems.locationZone.toggleZoneActive(
parseInt(id),
isActive
);
ctx.success(null, result.message);
} catch (error) {
this.fail(error.message);
}
}
/**
* 获取分区路径
* @param {Object} data 请求体
*/
async getPath(data) {
const { ctx, service } = this;
const { id } = data;
try {
if (!id) {
throw new Error('分区ID不能为空');
}
const path = await service.systems.locationZone.getZonePath(parseInt(id));
ctx.success(path);
} catch (error) {
this.fail(error.message);
}
}
/**
* 获取拣货路径
*/
async getPickPath() {
const { ctx } = this;
const { warehouse_id } = ctx.query;
if (!warehouse_id) {
this.fail('仓库ID不能为空', 400);
return;
}
try {
const options = {
includeSpaces: ctx.query.include_spaces === 'true',
limit: parseInt(ctx.query.limit) || 50,
sortBy: ctx.query.sort_by || 'path_sequence',
};
const result = await ctx.service.location.getPickPath(warehouse_id, options);
ctx.success(result);
} catch (error) {
this.fail(error.message, 500);
}
}
/**
* 更新货架位置
*/
async updateRackPosition() {
const { ctx } = this;
const { rack_id } = ctx.params;
const { x, y, z } = ctx.request.body;
ctx.validate({
x: { type: 'int', required: true },
y: { type: 'int', required: true },
z: { type: 'int', required: false },
});
try {
const rack = await ctx.service.location.updateRackPosition(rack_id, { x, y, z });
ctx.success(rack, '货架位置更新成功');
} catch (error) {
this.fail(error.message, error.status || 400);
}
}
/**
* 重新计算拣货路径
*/
async recalculatePickPath() {
const { ctx } = this;
const { warehouse_id } = ctx.request.body;
if (!warehouse_id) {
this.fail('仓库ID不能为空', 400);
return;
}
try {
await ctx.service.location._calculatePickPathForWarehouse(warehouse_id);
ctx.success(null, '拣货路径重新计算成功');
} catch (error) {
this.fail(error.message, 500);
}
}
/**
* 更新邻居关系
*/
async updateNeighbors() {
const { ctx } = this;
const { warehouse_id } = ctx.request.body;
if (!warehouse_id) {
this.fail('仓库ID不能为空', 400);
return;
}
try {
await ctx.service.location.updateNeighborRelations(warehouse_id);
ctx.success(null, '邻居关系更新成功');
} catch (error) {
this.fail(error.message, 500);
}
}
/**
* 获取库区内的货架列表(按排序)
*/
async getAreaRacks() {
const { ctx } = this;
const { area_id } = ctx.query;
if (!area_id) {
this.fail('库区ID不能为空', 400);
return;
}
try {
const racks = await ctx.model.LocationZone.findAll({
where: {
parent_id: area_id,
zone_type: 'rack',
is_active: true,
deleted_at: null,
},
order: [[ 'path_sequence', 'ASC' ]],
include: [{
model: ctx.model.LocationSpace,
as: 'spaces',
where: {
is_enabled: true,
deleted_at: null,
},
required: false,
}],
});
ctx.success(racks);
} catch (error) {
this.fail(error.message, 500);
}
}
async getSpacesByRack(data) {
const { ctx } = this;
const { id } = data;
if (!id) {
return this.fail('货架ID不能为空');
}
try {
const spaces = await ctx.model.LocationSpace.findAll({
where: {
zone_id: id,
deleted_at: null,
},
order: [[ 'space_code', 'ASC' ]],
});
return this.success('获取成功', { spaces, code: 200 });
} catch (e) {
return this.fail(e.message, 500);
}
}
async createRackWithSpaces(data) {
const { ctx, service } = this;
const { id } = data;
if (!id) {
return this.fail('货架ID不能为空');
}
const transaction = await ctx.model.transaction();
try {
const rack = await ctx.model.LocationZone.findOne({
where: {
id,
deleted_at: null,
},
lock: transaction.LOCK.UPDATE,
transaction,
});
if (!rack) {
throw new Error('货架不存在');
}
if (rack.zone_type !== 'rack') {
throw new Error('仓库元素不为货架,拒绝生成仓位');
}
const message = await service.systems.locationZone.generateSpacesForRack(id, rack, transaction);
await transaction.commit();
return this.success(message, { code: 200 });
} catch (e) {
await transaction.rollback();
return this.fail(e.message, 500);
}
}
/**
* 获取仓位详情。
* @param {Object} data 请求参数
* @param {number|string} data.id 仓位ID
* @return {Promise<Object>} 标准响应结果
*/
async getSpaceInfo(data) {
const { service } = this;
const { id } = data;
try {
const data = await service.systems.locationZone.getSpaceInfo(id);
return this.success('获取成功', { data, code: 200 });
} catch (error) {
if (error.message === '仓位不存在' || error.message === '仓位不属于当前仓库') {
return this.fail(error.message, { code: 0 });
}
return this.fail('获取失败' + error.message, { code: 0 });
}
}
async updateSpaceInfo(data) {
const { ctx, service } = this;
const { id } = data;
if (!id) {
return this.fail('仓位ID不能为空');
}
const transaction = await ctx.model.transaction();
try {
const space = await ctx.model.LocationSpace.findOne({
where: {
id,
warehouse_id: ctx.user.store_id,
deleted_at: null,
},
transaction,
});
if (!space) {
throw new Error('仓位不存在');
}
if (data.custom_barcode) {
const { isUnique } = await service.systems.locationZone.checkBarcodeUnique(parseInt(id), data.custom_barcode);
if (!isUnique) {
throw new Error('自定义条码已存在');
}
}
const update_data = {
location_type_id: data.location_type_id || space.location_type_id,
custom_name: data.custom_name || null,
custom_barcode: data.custom_barcode || null,
space_status: data.space_status || space.space_status,
pick_sequence: data.pick_sequence || 0,
};
await space.update(update_data);
await transaction.commit();
return this.success('保存成功', { code: 200 });
} catch (e) {
await transaction.rollback();
return this.fail('保存失败:' + e.message, { code: 500 });
}
}
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;