1071 lines
29 KiB
JavaScript
1071 lines
29 KiB
JavaScript
'use strict';
|
||
|
||
const Service = require('egg').Service;
|
||
|
||
class LocationZoneService extends Service {
|
||
/**
|
||
* 获取所有仓库级别的分区列表
|
||
* @param warehouseId
|
||
* @return {Promise<Array>} 仓库级别分区列表
|
||
*/
|
||
async getWarehouseLevelZones(warehouseId) {
|
||
const { ctx, app } = this;
|
||
|
||
try {
|
||
const zones = await ctx.model.LocationZone.findAll({
|
||
where: {
|
||
zone_type: 'warehouse',
|
||
deleted_at: null,
|
||
is_active: 1,
|
||
warehouse_id: warehouseId,
|
||
},
|
||
order: [
|
||
[ 'created_at', 'DESC' ],
|
||
],
|
||
raw: false, // 保持 Sequelize 实例,方便后续操作
|
||
});
|
||
for (let i = 0; i < zones.length; i++) {
|
||
const warehouse_tree = await this.getZoneTreeByWarehouse(zones[i].id);
|
||
const racks = [];
|
||
let areaCount = 0;
|
||
let rackCount = 0;
|
||
let totalSpaces = 0;
|
||
for (let ii = 0; ii < warehouse_tree.warehouseRoot.children.length; ii++) {
|
||
const area = warehouse_tree.warehouseRoot.children[ii];
|
||
console.log('area', area);
|
||
for (let iii = 0; iii < area.children.length; iii++) {
|
||
const zone = area.children[iii];
|
||
if (zone.type == 'rack') {
|
||
console.log('货架', zone);
|
||
racks.push(zone);
|
||
rackCount++;
|
||
const sz_count = await app.model.LocationSpace.count({ where: { zone_id: zone.id } });
|
||
console.log(sz_count);
|
||
const { rackColumns = 1, rackRows = 1, rackLevels = 1 } = zone.data;
|
||
totalSpaces += rackColumns * rackRows * rackLevels;
|
||
}
|
||
}
|
||
if (area.type == 'area') {
|
||
areaCount++;
|
||
}
|
||
}
|
||
zones[i].rackCount = rackCount;
|
||
zones[i].areaCount = areaCount;
|
||
zones[i].totalSpaces = totalSpaces;
|
||
console.log('zones[i]', i, rackCount, areaCount, zones[i].rackCount, zones[i].areaCount);
|
||
}
|
||
// 转换为前端需要的格式
|
||
return zones.map(zone => ({
|
||
id: zone.id,
|
||
label: zone.zone_name,
|
||
code: zone.zone_code,
|
||
length: zone.length,
|
||
width: zone.width,
|
||
height: zone.height,
|
||
areaCount: zone.areaCount,
|
||
rackCount: zone.rackCount,
|
||
totalSpaces: zone.totalSpaces,
|
||
createdAt: zone.created_at,
|
||
|
||
}));
|
||
} catch (error) {
|
||
ctx.logger.error('获取仓库级别分区失败:', error);
|
||
throw new Error('获取仓库列表失败');
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 根据仓库ID获取完整的树状结构(支持Element Tree格式)
|
||
* @param {number} warehouseId - 仓库ID
|
||
* @param warehouseSpaceId
|
||
* @return {Promise<Object>} 树状结构数据
|
||
*/
|
||
async getZoneTreeByWarehouse(warehouseSpaceId) {
|
||
const { ctx } = this;
|
||
const warehouseId = ctx.user.store_id;
|
||
|
||
try {
|
||
// 1. 获取指定仓库实体(zone_type = 'warehouse')
|
||
const warehouseEntity = await ctx.model.LocationZone.findOne({
|
||
where: {
|
||
id: warehouseSpaceId,
|
||
zone_type: 'warehouse',
|
||
warehouse_id: warehouseId, // 属于当前主体的仓库
|
||
deleted_at: null,
|
||
is_active: 1,
|
||
},
|
||
});
|
||
|
||
if (!warehouseEntity) {
|
||
throw new Error('仓库不存在或无权访问');
|
||
}
|
||
|
||
// 2. 获取该仓库实体下的所有子分区
|
||
const zones = await ctx.model.LocationZone.findAll({
|
||
where: {
|
||
warehouse_id: warehouseId, // 所属主体
|
||
deleted_at: null,
|
||
is_active: 1,
|
||
},
|
||
order: [
|
||
[ 'zone_type', 'ASC' ],
|
||
[ 'zone_code', 'ASC' ],
|
||
],
|
||
raw: false,
|
||
});
|
||
|
||
// 3. 转换为树形结构
|
||
const zoneMap = new Map();
|
||
const treeNodes = [];
|
||
|
||
// 首先将所有节点放入map
|
||
zones.forEach(zone => {
|
||
const node = {
|
||
id: zone.id,
|
||
label: `${zone.zone_code || ''} - ${zone.zone_name}`,
|
||
type: zone.zone_type,
|
||
code: zone.zone_code,
|
||
name: zone.zone_name,
|
||
parentId: zone.parent_id,
|
||
children: [],
|
||
// 扩展属性
|
||
data: {
|
||
x: zone.x,
|
||
y: zone.y,
|
||
z: zone.z,
|
||
length: zone.length,
|
||
width: zone.width,
|
||
height: zone.height,
|
||
rackColumns: zone.rack_columns,
|
||
rackRows: zone.rack_rows,
|
||
rackLevels: zone.rack_levels,
|
||
direction: zone.direction,
|
||
color: zone.color,
|
||
isActive: zone.is_active,
|
||
createdAt: zone.created_at,
|
||
},
|
||
};
|
||
|
||
zoneMap.set(zone.id, node);
|
||
|
||
// 如果没有父节点(应该是直接属于仓库的子节点),直接加入根节点
|
||
if (!zone.parent_id || zone.parent_id === warehouseSpaceId) {
|
||
treeNodes.push(node);
|
||
}
|
||
});
|
||
|
||
// 4. 构建父子关系(递归构建)
|
||
const buildTree = parentId => {
|
||
const children = [];
|
||
zones.forEach(zone => {
|
||
if (zone.parent_id === parentId) {
|
||
const node = zoneMap.get(zone.id);
|
||
if (node) {
|
||
node.children = buildTree(zone.id);
|
||
children.push(node);
|
||
}
|
||
}
|
||
});
|
||
return children;
|
||
};
|
||
|
||
// 5. 从仓库实体的直接子节点开始构建树
|
||
const warehouseTree = buildTree(warehouseSpaceId);
|
||
|
||
// 6. 按类型排序子节点
|
||
const sortChildren = children => {
|
||
if (!children || children.length === 0) return;
|
||
|
||
// 按类型排序:area -> aisle -> rack -> obstacle/gate/pick_start
|
||
const typeOrder = {
|
||
area: 1,
|
||
aisle: 2,
|
||
rack: 3,
|
||
obstacle: 4,
|
||
gate: 5,
|
||
pick_start: 6,
|
||
};
|
||
|
||
children.sort((a, b) => {
|
||
const orderA = typeOrder[a.type] || 999;
|
||
const orderB = typeOrder[b.type] || 999;
|
||
if (orderA !== orderB) {
|
||
return orderA - orderB;
|
||
}
|
||
return (a.code || '').localeCompare(b.code || '');
|
||
});
|
||
|
||
// 递归排序子节点
|
||
children.forEach(child => sortChildren(child.children));
|
||
};
|
||
|
||
sortChildren(warehouseTree);
|
||
|
||
// 7. 创建完整的仓库根节点
|
||
const warehouseRoot = {
|
||
id: warehouseEntity.id,
|
||
label: `${warehouseEntity.zone_code || ''} - ${warehouseEntity.zone_name}`,
|
||
type: 'warehouse',
|
||
code: warehouseEntity.zone_code,
|
||
name: warehouseEntity.zone_name,
|
||
children: warehouseTree,
|
||
data: {
|
||
x: warehouseEntity.x,
|
||
y: warehouseEntity.y,
|
||
z: warehouseEntity.z,
|
||
length: warehouseEntity.length,
|
||
width: warehouseEntity.width,
|
||
height: warehouseEntity.height,
|
||
color: warehouseEntity.color,
|
||
isActive: warehouseEntity.is_active,
|
||
createdAt: warehouseEntity.created_at,
|
||
// 主体信息
|
||
storeInfo: warehouseEntity.warehouse ? {
|
||
storeName: warehouseEntity.warehouse.store_name,
|
||
storeCode: warehouseEntity.warehouse.store_code,
|
||
address: warehouseEntity.warehouse.address,
|
||
contact: warehouseEntity.warehouse.contact,
|
||
phone: warehouseEntity.warehouse.phone,
|
||
} : null,
|
||
},
|
||
};
|
||
return { warehouseRoot, code: 200 };
|
||
} catch (error) {
|
||
ctx.logger.error('获取仓库树状结构失败:', error);
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 根据分区ID获取子树(用于懒加载)
|
||
* @param {number} zoneId - 分区ID
|
||
* @return {Promise<Array>} 子节点列表
|
||
*/
|
||
async getChildrenByZoneId(zoneId) {
|
||
const { ctx } = this;
|
||
|
||
try {
|
||
// 验证分区是否存在
|
||
const parentZone = await ctx.model.LocationZone.findOne({
|
||
where: {
|
||
id: zoneId,
|
||
deleted_at: null,
|
||
},
|
||
});
|
||
|
||
if (!parentZone) {
|
||
throw new Error('分区不存在');
|
||
}
|
||
|
||
const children = await ctx.model.LocationZone.findAll({
|
||
where: {
|
||
parent_id: zoneId,
|
||
deleted_at: null,
|
||
is_active: 1,
|
||
},
|
||
order: [
|
||
[ 'zone_type', 'ASC' ],
|
||
[ 'zone_code', 'ASC' ],
|
||
],
|
||
});
|
||
|
||
return children.map(async child => ({
|
||
id: child.id,
|
||
label: `${child.zone_code} - ${child.zone_name}`,
|
||
type: child.zone_type,
|
||
code: child.zone_code,
|
||
name: child.zone_name,
|
||
parentId: child.parent_id,
|
||
children: [], // 初始为空,支持懒加载
|
||
isLeaf: await this.isLeafNode(child.id),
|
||
data: {
|
||
x: child.x,
|
||
y: child.y,
|
||
z: child.z,
|
||
length: child.length,
|
||
width: child.width,
|
||
height: child.height,
|
||
rackColumns: child.rack_columns,
|
||
rackRows: child.rack_rows,
|
||
rackLevels: child.rack_levels,
|
||
direction: child.direction,
|
||
color: child.color,
|
||
isActive: child.is_active,
|
||
},
|
||
}));
|
||
} catch (error) {
|
||
ctx.logger.error('获取子分区失败:', error);
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 判断节点是否为叶子节点
|
||
* @param {number} zoneId - 分区ID
|
||
* @return {Promise<boolean>} 是否为叶子节点
|
||
*/
|
||
async isLeafNode(zoneId) {
|
||
const { ctx } = this;
|
||
|
||
const count = await ctx.model.LocationZone.count({
|
||
where: {
|
||
parent_id: zoneId,
|
||
deleted_at: null,
|
||
is_active: 1,
|
||
},
|
||
});
|
||
|
||
return count === 0;
|
||
}
|
||
|
||
/**
|
||
* 创建元素
|
||
* @param {Object} data - 元素数据
|
||
* @return {Promise<Object>} 创建的元素
|
||
*/
|
||
/**
|
||
* 创建元素
|
||
* @param {Object} data - 元素数据
|
||
* @return {Promise<Object>} 创建的元素
|
||
*/
|
||
async createZone(data) {
|
||
const { ctx } = this;
|
||
try {
|
||
const warehouse_id = ctx.user.store_id;
|
||
|
||
// 1. 基本字段验证
|
||
this.validateBasicFields(data);
|
||
|
||
// 2. 根据类型进行特定验证
|
||
await this.validateByZoneType(data, warehouse_id);
|
||
|
||
// 3. 验证父元素
|
||
await this.validateParentElement(data, warehouse_id);
|
||
|
||
|
||
// 5. 处理编码(根据类型)
|
||
const zoneCode = this.generateZoneCodeByType(data);
|
||
|
||
// 6. 创建分区
|
||
const zone = await ctx.model.LocationZone.create({
|
||
warehouse_id,
|
||
zone_code: zoneCode,
|
||
zone_name: data.zone_name,
|
||
zone_type: data.zone_type,
|
||
parent_id: data.parent_id || null,
|
||
is_active: data.is_active !== undefined ? data.is_active : 1,
|
||
x: data.x,
|
||
y: data.y,
|
||
z: data.z,
|
||
length: data.length,
|
||
width: data.width,
|
||
height: data.height,
|
||
rack_columns: data.rack_columns,
|
||
rack_rows: data.rack_rows,
|
||
rack_levels: data.rack_levels,
|
||
direction: data.direction,
|
||
color: data.color || this.getDefaultColorByType(data.zone_type),
|
||
});
|
||
if (zone.zone_type == 'rack') {
|
||
await this.generateSpacesForRack(zone.id, zone);
|
||
}
|
||
return {
|
||
success: true,
|
||
data: zone,
|
||
message: '创建成功',
|
||
};
|
||
} catch (error) {
|
||
ctx.logger.error('创建分区失败:', error);
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 验证基本字段
|
||
* @param data
|
||
*/
|
||
validateBasicFields(data) {
|
||
// 所有元素都需要这些字段
|
||
const requiredFields = [ 'x', 'y', 'z', 'length', 'width', 'height', 'zone_type', 'zone_name' ];
|
||
|
||
for (const field of requiredFields) {
|
||
if (data[field] === undefined || data[field] === null || data[field] === '') {
|
||
throw new Error(`字段 ${field} 不能为空`);
|
||
}
|
||
}
|
||
|
||
// 坐标和尺寸必须是正数
|
||
const numberFields = [ 'x', 'y', 'z', 'length', 'width', 'height' ];
|
||
for (const field of numberFields) {
|
||
if (typeof data[field] !== 'number' || data[field] < 0) {
|
||
throw new Error(`字段 ${field} 必须是正数`);
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 根据类型进行特定验证
|
||
* @param data
|
||
* @param warehouseId
|
||
*/
|
||
async validateByZoneType(data, warehouseId) {
|
||
const { ctx } = this;
|
||
|
||
switch (data.zone_type) {
|
||
case 'warehouse':
|
||
// 仓库必须 parent_id = 0
|
||
if (data.parent_id !== 0 && data.parent_id !== null) {
|
||
throw new Error('仓库元素的父元素必须为0或null');
|
||
}
|
||
break;
|
||
|
||
case 'area':
|
||
// 库区必须有父元素且父元素必须是仓库
|
||
if (!data.parent_id) {
|
||
throw new Error('库区必须指定父元素');
|
||
}
|
||
const parentArea = await ctx.model.LocationZone.findOne({
|
||
where: {
|
||
id: data.parent_id,
|
||
warehouse_id: warehouseId,
|
||
deleted_at: null,
|
||
},
|
||
});
|
||
if (!parentArea) {
|
||
throw new Error('父元素不存在');
|
||
}
|
||
if (parentArea.zone_type !== 'warehouse') {
|
||
throw new Error('库区只能创建在仓库上');
|
||
}
|
||
break;
|
||
|
||
case 'rack':
|
||
// 货架必须有父元素且父元素必须是通道
|
||
if (!data.parent_id) {
|
||
throw new Error('货架必须指定父元素');
|
||
}
|
||
const parentRack = await ctx.model.LocationZone.findOne({
|
||
where: {
|
||
id: data.parent_id,
|
||
warehouse_id: warehouseId,
|
||
deleted_at: null,
|
||
},
|
||
});
|
||
if (!parentRack) {
|
||
throw new Error('父元素不存在');
|
||
}
|
||
if (parentRack.zone_type !== 'area') {
|
||
throw new Error('货架只能创建在库区上');
|
||
}
|
||
|
||
// 货架必须有货架属性
|
||
if (!data.rack_columns || !data.rack_rows || !data.rack_levels) {
|
||
throw new Error('货架必须设置列数、层数和分格数');
|
||
}
|
||
if (!data.direction) {
|
||
throw new Error('货架必须设置朝向');
|
||
}
|
||
|
||
// 货架属性必须是正数
|
||
if (data.rack_columns <= 0 || data.rack_rows <= 0 || data.rack_levels <= 0) {
|
||
throw new Error('货架列数、层数、分格数必须大于0');
|
||
}
|
||
break;
|
||
case 'pick_start':
|
||
// 这些元素必须有父元素且父元素可以是任何类型(除了自身)
|
||
if (!data.parent_id) {
|
||
throw new Error(`${this.getZoneTypeText(data.zone_type)}必须指定父元素`);
|
||
}
|
||
const parentSpecial = await ctx.model.LocationZone.findOne({
|
||
where: {
|
||
id: data.parent_id,
|
||
warehouse_id: warehouseId,
|
||
deleted_at: null,
|
||
},
|
||
});
|
||
if (parentSpecial.zone_type !== 'area') {
|
||
throw new Error('拣货起点只能创建在库区上');
|
||
}
|
||
if (!parentSpecial) {
|
||
throw new Error('父元素不存在');
|
||
}
|
||
break;
|
||
|
||
default:
|
||
throw new Error('不支持的分区类型');
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 验证父元素
|
||
* @param data
|
||
* @param warehouseId
|
||
*/
|
||
async validateParentElement(data, warehouseId) {
|
||
const { ctx } = this;
|
||
|
||
// 仓库类型不需要父元素验证(已经在上面的switch中处理)
|
||
if (data.zone_type === 'warehouse') {
|
||
return;
|
||
}
|
||
|
||
// 其他类型必须要有父元素
|
||
if (!data.parent_id) {
|
||
throw new Error('必须指定父元素');
|
||
}
|
||
|
||
const parent = await ctx.model.LocationZone.findOne({
|
||
where: {
|
||
id: data.parent_id,
|
||
warehouse_id: warehouseId,
|
||
deleted_at: null,
|
||
is_active: 1,
|
||
},
|
||
});
|
||
|
||
if (!parent) {
|
||
throw new Error('父元素不存在或已禁用');
|
||
}
|
||
|
||
// 检查是否在父元素范围内
|
||
const parentEndX = parent.x + parent.length;
|
||
const parentEndY = parent.y + parent.width;
|
||
const parentEndZ = parent.z + parent.height;
|
||
|
||
const elementEndX = data.x + data.length;
|
||
const elementEndY = data.y + data.width;
|
||
const elementEndZ = data.z + data.height;
|
||
|
||
}
|
||
|
||
/**
|
||
* 验证坐标是否重叠
|
||
* @param data
|
||
* @param warehouseId
|
||
* @param excludeId
|
||
*/
|
||
async validateZoneOverlap(data, warehouseId, excludeId = null) {
|
||
const { ctx } = this;
|
||
|
||
const overlaps = await ctx.model.LocationZone.findAll({
|
||
where: {
|
||
warehouse_id: warehouseId,
|
||
deleted_at: null,
|
||
parent_id: data.parent_id,
|
||
id: excludeId ? { $ne: excludeId } : undefined,
|
||
},
|
||
});
|
||
|
||
for (const existingZone of overlaps) {
|
||
if (this.isOverlap(data, existingZone)) {
|
||
throw new Error(`坐标与现有元素"${existingZone.zone_name}"重叠`);
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 检查两个元素是否重叠
|
||
* @param zone1
|
||
* @param zone2
|
||
*/
|
||
isOverlap(zone1, zone2) {
|
||
const zone1EndX = zone1.x + zone1.length;
|
||
const zone1EndY = zone1.y + zone1.width;
|
||
const zone1EndZ = zone1.z + zone1.height;
|
||
|
||
const zone2EndX = zone2.x + zone2.length;
|
||
const zone2EndY = zone2.y + zone2.width;
|
||
const zone2EndZ = zone2.z + zone2.height;
|
||
|
||
// AABB碰撞检测
|
||
const overlapX = !(zone1EndX <= zone2.x || zone1.x >= zone2EndX);
|
||
const overlapY = !(zone1EndY <= zone2.y || zone1.y >= zone2EndY);
|
||
const overlapZ = !(zone1EndZ <= zone2.z || zone1.z >= zone2EndZ);
|
||
|
||
return overlapX && overlapY && overlapZ;
|
||
}
|
||
|
||
/**
|
||
* 根据类型生成编码
|
||
* @param data
|
||
*/
|
||
generateZoneCodeByType(data) {
|
||
// 只有特定类型需要编码
|
||
const zoneTypesRequireCode = [ 'warehouse', 'area', 'rack' ];
|
||
|
||
if (!zoneTypesRequireCode.includes(data.zone_type)) {
|
||
return null;
|
||
}
|
||
|
||
// 如果已经提供了编码,使用提供的编码
|
||
if (data.zone_code) {
|
||
// 验证编码格式
|
||
if (!/^[A-Z0-9]{1,5}$/.test(data.zone_code)) {
|
||
throw new Error('编码必须是1-5位大写字母或数字');
|
||
}
|
||
return data.zone_code;
|
||
}
|
||
|
||
// 自动生成编码
|
||
const prefixMap = {
|
||
warehouse: 'WH',
|
||
area: 'A',
|
||
rack: 'R',
|
||
};
|
||
|
||
const prefix = prefixMap[data.zone_type];
|
||
const timestamp = Date.now().toString().slice(-3);
|
||
const random = Math.floor(Math.random() * 10);
|
||
return `${prefix}${timestamp}${random}`;
|
||
}
|
||
|
||
/**
|
||
* 根据类型获取默认颜色
|
||
* @param zoneType
|
||
*/
|
||
getDefaultColorByType(zoneType) {
|
||
const colorMap = {
|
||
warehouse: '#96ceb4',
|
||
area: '#c6e48b',
|
||
aisle: '#239a3b',
|
||
rack: '#7bc96f',
|
||
obstacle: '#ff6b6b',
|
||
gate: '#4ecdc4',
|
||
pick_start: '#45b7d1',
|
||
};
|
||
return colorMap[zoneType] || '#3B82F6';
|
||
}
|
||
|
||
/**
|
||
* 获取类型文本
|
||
* @param type
|
||
*/
|
||
getZoneTypeText(type) {
|
||
const typeMap = {
|
||
warehouse: '仓库',
|
||
area: '库区',
|
||
aisle: '通道',
|
||
rack: '货架',
|
||
obstacle: '障碍物',
|
||
gate: '大门',
|
||
pick_start: '拣货点',
|
||
};
|
||
return typeMap[type] || type;
|
||
}
|
||
|
||
/**
|
||
* 更新分区
|
||
* @param {number} id - 分区ID
|
||
* @param {Object} data - 更新数据
|
||
* @return {Promise<Object>} 更新结果
|
||
*/
|
||
async updateZone(id, data) {
|
||
const { ctx } = this;
|
||
|
||
try {
|
||
const zone = await ctx.model.LocationZone.findOne({
|
||
where: {
|
||
id,
|
||
deleted_at: null,
|
||
},
|
||
});
|
||
|
||
if (!zone) {
|
||
throw new Error('分区不存在');
|
||
}
|
||
|
||
console.log('修改的数据', data);
|
||
// 验证坐标是否重叠(如果修改了坐标)
|
||
if (
|
||
(data.x !== undefined || data.y !== undefined || data.length || data.width) &&
|
||
zone.warehouse_id
|
||
) {
|
||
const x = data.x !== undefined ? data.x : zone.x;
|
||
const y = data.y !== undefined ? data.y : zone.y;
|
||
const z = data.z !== undefined ? data.z : zone.z || 0;
|
||
const length = data.length || zone.length;
|
||
const width = data.width || zone.width;
|
||
const height = data.height || zone.height || 0;
|
||
|
||
const overlaps = await this.checkZoneOverlap(
|
||
zone.warehouse_id,
|
||
x,
|
||
y,
|
||
z,
|
||
length,
|
||
width,
|
||
height,
|
||
id // 排除当前分区
|
||
);
|
||
|
||
if (overlaps.length > 0) {
|
||
throw new Error('区域坐标与其他分区重叠');
|
||
}
|
||
}
|
||
|
||
// 更新分区
|
||
await zone.update(data);
|
||
|
||
return {
|
||
success: true,
|
||
data: zone,
|
||
message: '更新成功',
|
||
code: 200,
|
||
};
|
||
} catch (error) {
|
||
ctx.logger.error('更新分区失败:', error);
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 软删除分区
|
||
* @param {number} id - 分区ID
|
||
* @return {Promise<Object>} 删除结果
|
||
*/
|
||
async deleteZone(id) {
|
||
const { ctx } = this;
|
||
console.log('需要删除的id', id);
|
||
try {
|
||
const zone = await ctx.model.LocationZone.findOne({
|
||
where: {
|
||
id,
|
||
deleted_at: null,
|
||
},
|
||
});
|
||
|
||
if (!zone) {
|
||
throw new Error('分区不存在');
|
||
}
|
||
// 检查是否有子分区
|
||
const childrenCount = await ctx.model.LocationZone.count({
|
||
where: {
|
||
parent_id: id,
|
||
deleted_at: null,
|
||
},
|
||
});
|
||
if (zone.zone_type == 'rack') {
|
||
// 货架执行删除需要检测库位是否还有库存
|
||
throw new Error('货架XX库位有库存,禁止删除,请先移库');
|
||
}
|
||
if (childrenCount > 0) {
|
||
throw new Error('请先删除或转移所有子分区');
|
||
}
|
||
// 执行软删除
|
||
await zone.destroy();
|
||
return {
|
||
success: true,
|
||
message: '删除成功',
|
||
};
|
||
} catch (error) {
|
||
ctx.logger.error('删除分区失败:', error);
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 检查区域重叠
|
||
* @param warehouseId
|
||
* @param x
|
||
* @param y
|
||
* @param z
|
||
* @param length
|
||
* @param width
|
||
* @param height
|
||
* @param excludeId
|
||
* @private
|
||
*/
|
||
async checkZoneOverlap(warehouseId, x, y, z, length, width, height, excludeId) {
|
||
const { ctx } = this;
|
||
|
||
if (!warehouseId || x === undefined || y === undefined || !length || !width) {
|
||
return [];
|
||
}
|
||
|
||
const where = {
|
||
warehouse_id: warehouseId,
|
||
deleted_at: null,
|
||
x: { $ne: null },
|
||
y: { $ne: null },
|
||
length: { $ne: null },
|
||
width: { $ne: null },
|
||
};
|
||
|
||
if (excludeId) {
|
||
where.id = { $ne: excludeId };
|
||
}
|
||
|
||
const zones = await ctx.model.LocationZone.findAll({
|
||
where,
|
||
attributes: [ 'id', 'zone_code', 'zone_name', 'x', 'y', 'z', 'length', 'width', 'height' ],
|
||
});
|
||
|
||
// 检查空间重叠
|
||
return zones.filter(zone => {
|
||
const zHeight = zone.height || 0;
|
||
const currentHeight = height || 0;
|
||
|
||
// AABB(轴对齐边界框)碰撞检测
|
||
const overlapX = !(x + length <= zone.x || x >= zone.x + zone.length);
|
||
const overlapY = !(y + width <= zone.y || y >= zone.y + zone.width);
|
||
const overlapZ = !(z + currentHeight <= zone.z || z >= zone.z + zHeight);
|
||
|
||
return overlapX && overlapY && overlapZ;
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 根据分区ID获取分区详情
|
||
* @param {number} id - 分区ID
|
||
* @return {Promise<Object>} 分区详情
|
||
*/
|
||
async getZoneDetail(id) {
|
||
const { ctx } = this;
|
||
|
||
try {
|
||
const zone = await ctx.model.LocationZone.findOne({
|
||
where: {
|
||
id,
|
||
deleted_at: null,
|
||
},
|
||
});
|
||
|
||
if (!zone) {
|
||
throw new Error('分区不存在');
|
||
}
|
||
|
||
return { zone, code: 200 };
|
||
} catch (error) {
|
||
ctx.logger.error('获取分区详情失败:', error);
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 启用/禁用分区
|
||
* @param {number} id - 分区ID
|
||
* @param {boolean} isActive - 是否启用
|
||
* @return {Promise<Object>} 操作结果
|
||
*/
|
||
async toggleZoneActive(id, isActive) {
|
||
const { ctx } = this;
|
||
|
||
try {
|
||
const zone = await ctx.model.LocationZone.findOne({
|
||
where: {
|
||
id,
|
||
deleted_at: null,
|
||
},
|
||
});
|
||
|
||
if (!zone) {
|
||
throw new Error('分区不存在');
|
||
}
|
||
|
||
// 如果禁用分区,检查是否有启用的子分区
|
||
if (!isActive) {
|
||
const activeChildren = await ctx.model.LocationZone.count({
|
||
where: {
|
||
parent_id: id,
|
||
deleted_at: null,
|
||
is_active: 1,
|
||
},
|
||
});
|
||
|
||
if (activeChildren > 0) {
|
||
throw new Error('请先禁用所有子分区');
|
||
}
|
||
}
|
||
|
||
zone.is_active = isActive ? 1 : 0;
|
||
await zone.save();
|
||
|
||
return {
|
||
success: true,
|
||
message: isActive ? '启用成功' : '禁用成功',
|
||
};
|
||
} catch (error) {
|
||
ctx.logger.error('切换分区状态失败:', error);
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 获取分区路径(从根节点到当前节点的路径)
|
||
* @param {number} id - 分区ID
|
||
* @return {Promise<Array>} 路径数组
|
||
*/
|
||
async getZonePath(id) {
|
||
const { ctx } = this;
|
||
|
||
try {
|
||
const path = [];
|
||
let currentId = id;
|
||
|
||
while (currentId) {
|
||
const zone = await ctx.model.LocationZone.findOne({
|
||
where: {
|
||
id: currentId,
|
||
deleted_at: null,
|
||
},
|
||
attributes: [ 'id', 'zone_code', 'zone_name', 'zone_type', 'parent_id' ],
|
||
});
|
||
|
||
if (!zone) break;
|
||
|
||
path.unshift({
|
||
id: zone.id,
|
||
code: zone.zone_code,
|
||
name: zone.zone_name,
|
||
type: zone.zone_type,
|
||
});
|
||
|
||
currentId = zone.parent_id;
|
||
}
|
||
|
||
return path;
|
||
} catch (error) {
|
||
ctx.logger.error('获取分区路径失败:', error);
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
async generateSpacesForRack(rackId, rack, transaction = null) {
|
||
const { app } = this;
|
||
const { rack_columns, rack_rows, rack_levels, direction, x, y, z } = rack;
|
||
const spaces = [];
|
||
let rackWidth = 0;
|
||
let rackLength = 0;
|
||
const rackHeight = 0;
|
||
let cellLength = 0;
|
||
let cellWidth = 0;
|
||
let cellHeight = 0;
|
||
let prelativeX = 0;
|
||
let prelativeY = 0;
|
||
let prelativeZ = 0;
|
||
|
||
|
||
rackWidth = rack.width;
|
||
rackLength = rack.length;
|
||
prelativeX = x;
|
||
prelativeY = y;
|
||
prelativeZ = z;
|
||
// 计算每个仓位的尺寸
|
||
cellLength = rackLength / rack_columns / rack_levels;
|
||
cellWidth = rackWidth;
|
||
cellHeight = rack.height / rack_rows;
|
||
|
||
// 生成所有仓位
|
||
for (let column = 1; column <= rack_columns; column++) {
|
||
for (let row = 1; row <= rack_rows; row++) {
|
||
for (let level = 1; level <= rack_levels; level++) {
|
||
const spaceCode = `${rack.zone_code}-${column.toString().padStart(2, '0')}-${row.toString().padStart(2, '0')}-${level.toString().padStart(2, '0')}`;
|
||
|
||
// 计算相对坐标
|
||
let relativeX = 0;
|
||
let relativeY = 0;
|
||
let relativeZ = (level - 1) * cellWidth + prelativeZ;
|
||
|
||
if (direction === 'east' || direction === 'west') {
|
||
relativeY = (column - 1) * cellLength + prelativeX;
|
||
relativeX = cellWidth + prelativeY;
|
||
relativeZ = (row - 1) * cellHeight + prelativeZ;
|
||
} else {
|
||
relativeX = (column - 1) * cellLength + prelativeX;
|
||
relativeY = cellWidth + prelativeY;
|
||
relativeZ = (row - 1) * cellHeight + prelativeZ;
|
||
}
|
||
|
||
spaces.push({
|
||
warehouse_id: rack.warehouse_id,
|
||
zone_id: rackId,
|
||
location_type_id: row == 1 ? 1 : 2, // 默认第一层为分拣,其他层为存储
|
||
space_code: spaceCode,
|
||
row_no: row.toString(),
|
||
column_no: column.toString(),
|
||
level_no: level.toString(),
|
||
cell_no: `${column}-${row}-${level}`,
|
||
length: cellLength,
|
||
width: cellWidth,
|
||
height: cellHeight,
|
||
volume: cellLength * cellWidth * cellHeight / 1000000, // cm³转m³
|
||
max_weight: 100, // 默认100kg
|
||
space_status: 'AVAILABLE',
|
||
is_enabled: true,
|
||
relative_x: relativeX,
|
||
relative_y: relativeY,
|
||
relative_z: relativeZ,
|
||
pick_sequence: 0,
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
// 批量插入仓位
|
||
if (spaces.length > 0) {
|
||
await app.model.LocationSpace.bulkCreate(spaces, { transaction });
|
||
}
|
||
return `为货架 ${rack.zone_code} 生成了 ${spaces.length} 个仓位`;
|
||
}
|
||
async getSpaceInfo(id) {
|
||
const { ctx } = this;
|
||
|
||
try {
|
||
const path = [];
|
||
const space = await ctx.model.LocationSpace.findOne({
|
||
where: {
|
||
id,
|
||
warehouse_id: ctx.user.store_id,
|
||
deleted_at: null,
|
||
},
|
||
attributes: [ 'id', 'location_type_id', 'space_code', 'custom_name', 'custom_barcode', 'space_status', 'pick_sequence' ],
|
||
});
|
||
if (!space) {
|
||
throw new Error('仓位不存在');
|
||
}
|
||
return space;
|
||
} catch (error) {
|
||
ctx.logger.error('获取分区路径失败:', error);
|
||
throw error;
|
||
}
|
||
}
|
||
async checkBarcodeUnique(id, barcode) {
|
||
const { ctx } = this;
|
||
const { Op } = this.app.Sequelize || app.Sequelize;
|
||
try {
|
||
// 检查条码是否被其他仓位使用(排除当前仓位)
|
||
const space = await ctx.model.LocationSpace.findOne({
|
||
where: {
|
||
[Op.and]: [
|
||
{
|
||
id: {
|
||
[Op.ne]: id, // 排除当前仓位ID
|
||
},
|
||
},
|
||
{
|
||
[Op.or]: [
|
||
{ custom_barcode: barcode }, // 检查自定义条码
|
||
{ space_code: barcode }, // 检查仓位编码
|
||
],
|
||
},
|
||
{ deleted_at: null }, // 未删除的记录
|
||
],
|
||
},
|
||
attributes: [ 'id' ],
|
||
});
|
||
|
||
// 如果没有找到重复的条码,返回唯一
|
||
if (!space) {
|
||
return { isUnique: true };
|
||
}
|
||
return { isUnique: false, message: '条码已被使用' };
|
||
|
||
} catch (error) {
|
||
ctx.logger.error('检查条码唯一性失败:', error);
|
||
return { isUnique: false, message: '条码检测失败' };
|
||
}
|
||
}
|
||
}
|
||
|
||
module.exports = LocationZoneService;
|