【定时任务】sync_outbound_orders_to_delivery: 执行日志写缓存 + 错误详情提取(parent/validation) 【基础设施】system.js: snake_case→camelCase 服务路由转换(兼容 express_interface 等) 【看板】dashboard: queryWarehouseStats 支持 storeId 货主维度过滤 【订单基类】order/base: getOrderModel 兼容无上下文时传入 warehouseId(货主侧场景) 【库存】inventory: 全量移库软删除→硬删除(force destroy)释放唯一键 + 唯一约束/校验错误友好提示 【快递平台】express_platform: KS(快手)平台 receiver.phone 不传(平台要求) 【迁移】delivery 自增起点 + supervisor CS 权限修复
1320 lines
38 KiB
JavaScript
1320 lines
38 KiB
JavaScript
'use strict';
|
||
|
||
const Service = require('egg').Service;
|
||
|
||
class LocationZoneService extends Service {
|
||
async collectZoneSubtree(rootId, transaction) {
|
||
const { ctx } = this;
|
||
const { Op } = ctx.app.Sequelize;
|
||
const zoneIds = [ Number(rootId) ];
|
||
const zones = [];
|
||
let parentIds = [ Number(rootId) ];
|
||
|
||
while (parentIds.length > 0) {
|
||
const children = await ctx.model.LocationZone.findAll({
|
||
where: {
|
||
parent_id: {
|
||
[Op.in]: parentIds,
|
||
},
|
||
deleted_at: null,
|
||
},
|
||
raw: true,
|
||
transaction,
|
||
});
|
||
|
||
if (!Array.isArray(children) || children.length === 0) {
|
||
break;
|
||
}
|
||
|
||
zones.push(...children);
|
||
parentIds = children
|
||
.map(item => Number(item && item.id))
|
||
.filter(childId => Number.isFinite(childId) && childId > 0);
|
||
zoneIds.push(...parentIds);
|
||
}
|
||
|
||
return {
|
||
zoneIds,
|
||
zones,
|
||
};
|
||
}
|
||
|
||
async assertSpacesNotOccupied(spaceIds, transaction) {
|
||
if (!Array.isArray(spaceIds) || spaceIds.length === 0) {
|
||
return;
|
||
}
|
||
|
||
const { ctx } = this;
|
||
const { Op } = ctx.app.Sequelize;
|
||
const stockCount = await ctx.model.Storage.count({
|
||
where: {
|
||
space_id: {
|
||
[Op.in]: spaceIds,
|
||
},
|
||
delete_at: null,
|
||
is_enabled: 1,
|
||
[Op.or]: [
|
||
{ quantity: { [Op.gt]: 0 } },
|
||
{ locked_quantity: { [Op.gt]: 0 } },
|
||
{ available_quantity: { [Op.gt]: 0 } },
|
||
],
|
||
},
|
||
transaction,
|
||
});
|
||
|
||
if (stockCount > 0) {
|
||
throw new Error('删除范围内库位有库存,禁止删除,请先移库');
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 获取所有仓库级别的分区列表
|
||
* @param {number|string} warehouseId 仓库ID
|
||
* @return {Promise<Array>} 仓库级别分区列表
|
||
*/
|
||
async getWarehouseLevelZones(warehouseId) {
|
||
const { ctx } = 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];
|
||
for (let iii = 0; iii < area.children.length; iii++) {
|
||
const zone = area.children[iii];
|
||
if (zone.type === 'rack') {
|
||
racks.push(zone);
|
||
rackCount++;
|
||
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;
|
||
}
|
||
// 转换为前端需要的格式
|
||
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|string} warehouseSpaceId 仓库分区ID
|
||
* @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>} 创建的元素
|
||
*/
|
||
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 {Object} 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 {Object} data 元素数据
|
||
* @param {number|string} warehouseId 仓库ID
|
||
*/
|
||
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) {
|
||
throw new Error('父元素不存在');
|
||
}
|
||
break;
|
||
}
|
||
|
||
default:
|
||
throw new Error('不支持的分区类型');
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 验证父元素
|
||
* @param {Object} data 元素数据
|
||
* @param {number|string} warehouseId 仓库ID
|
||
*/
|
||
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;
|
||
|
||
if (elementEndX > parentEndX || elementEndY > parentEndY || elementEndZ > parentEndZ) {
|
||
throw new Error('元素必须位于父元素范围内');
|
||
}
|
||
|
||
}
|
||
|
||
/**
|
||
* 验证坐标是否重叠
|
||
* @param {Object} data 元素数据
|
||
* @param {number|string} warehouseId 仓库ID
|
||
* @param {number|string|null} excludeId 排除的分区ID
|
||
*/
|
||
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 {Object} zone1 元素1
|
||
* @param {Object} zone2 元素2
|
||
* @return {boolean} 是否重叠
|
||
*/
|
||
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 {Object} data 元素数据
|
||
* @return {string|null} 编码
|
||
*/
|
||
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 {string} zoneType 类型
|
||
* @return {string} 默认颜色
|
||
*/
|
||
getDefaultColorByType(zoneType) {
|
||
const colorMap = {
|
||
warehouse: '#96ceb4',
|
||
area: '#c6e48b',
|
||
aisle: '#239a3b',
|
||
rack: '#7bc96f',
|
||
obstacle: '#ff6b6b',
|
||
gate: '#4ecdc4',
|
||
pick_start: '#45b7d1',
|
||
};
|
||
return colorMap[zoneType] || '#3B82F6';
|
||
}
|
||
|
||
/**
|
||
* 获取类型文本
|
||
* @param {string} type 类型
|
||
* @return {string} 类型文本
|
||
*/
|
||
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('分区不存在');
|
||
}
|
||
|
||
const updateData = { ...data };
|
||
|
||
if (data.is_active !== undefined) {
|
||
const isActive = [ true, 1, '1', 'true' ].includes(data.is_active);
|
||
const isInactive = [ false, 0, '0', 'false' ].includes(data.is_active);
|
||
|
||
if (!isActive && !isInactive) {
|
||
throw new Error('is_active 参数格式不正确');
|
||
}
|
||
|
||
if (isInactive) {
|
||
const activeChildren = await ctx.model.LocationZone.count({
|
||
where: {
|
||
parent_id: id,
|
||
deleted_at: null,
|
||
is_active: 1,
|
||
},
|
||
});
|
||
|
||
if (activeChildren > 0) {
|
||
throw new Error('请先禁用所有子分区');
|
||
}
|
||
}
|
||
|
||
updateData.is_active = isActive ? 1 : 0;
|
||
}
|
||
|
||
// 验证坐标是否重叠(如果修改了坐标)
|
||
if (
|
||
(updateData.x !== undefined || updateData.y !== undefined || updateData.length || updateData.width) &&
|
||
zone.warehouse_id
|
||
) {
|
||
const x = updateData.x !== undefined ? updateData.x : zone.x;
|
||
const y = updateData.y !== undefined ? updateData.y : zone.y;
|
||
const z = updateData.z !== undefined ? updateData.z : zone.z || 0;
|
||
const length = updateData.length || zone.length;
|
||
const width = updateData.width || zone.width;
|
||
const height = updateData.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(updateData);
|
||
|
||
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;
|
||
try {
|
||
const zone = await ctx.model.LocationZone.findOne({
|
||
where: {
|
||
id,
|
||
deleted_at: null,
|
||
},
|
||
});
|
||
|
||
if (!zone) {
|
||
throw new Error('分区不存在');
|
||
}
|
||
|
||
await ctx.model.transaction(async transaction => {
|
||
const { Op } = ctx.app.Sequelize;
|
||
const { zoneIds, zones } = await this.collectZoneSubtree(id, transaction);
|
||
const rackZoneIds = [ zone, ...zones ]
|
||
.filter(item => item && item.zone_type === 'rack')
|
||
.map(item => Number(item.id))
|
||
.filter(zoneId => Number.isFinite(zoneId) && zoneId > 0);
|
||
const spaceZoneIds = zone.zone_type === 'rack'
|
||
? zoneIds
|
||
: rackZoneIds;
|
||
|
||
const spaces = await ctx.model.LocationSpace.findAll({
|
||
where: {
|
||
zone_id: {
|
||
[Op.in]: spaceZoneIds,
|
||
},
|
||
deleted_at: null,
|
||
},
|
||
attributes: [ 'id' ],
|
||
raw: true,
|
||
transaction,
|
||
});
|
||
|
||
const spaceIds = (Array.isArray(spaces) ? spaces : [])
|
||
.map(space => Number(space && space.id))
|
||
.filter(spaceId => Number.isFinite(spaceId) && spaceId > 0);
|
||
|
||
await this.assertSpacesNotOccupied(spaceIds, transaction);
|
||
|
||
if (spaceIds.length > 0) {
|
||
await ctx.model.LocationSpace.destroy({
|
||
where: {
|
||
id: {
|
||
[Op.in]: spaceIds,
|
||
},
|
||
},
|
||
transaction,
|
||
});
|
||
}
|
||
|
||
await ctx.model.LocationZone.destroy({
|
||
where: {
|
||
id: {
|
||
[Op.in]: zoneIds,
|
||
},
|
||
},
|
||
transaction,
|
||
});
|
||
});
|
||
|
||
return {
|
||
success: true,
|
||
message: '删除成功',
|
||
};
|
||
} catch (error) {
|
||
ctx.logger.error('删除分区失败:', error);
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 检查区域重叠
|
||
* @param {number|string} warehouseId 仓库ID
|
||
* @param {number} x X 坐标
|
||
* @param {number} y Y 坐标
|
||
* @param {number} z Z 坐标
|
||
* @param {number} length 长度
|
||
* @param {number} width 宽度
|
||
* @param {number} height 高度
|
||
* @param {number|string|null} excludeId 排除的分区ID
|
||
* @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, ctx } = this;
|
||
const { Op } = app.Sequelize;
|
||
const { rack_columns, rack_rows, rack_levels, direction, x, y, z } = rack;
|
||
const expectedSpaceCount = Number(rack_columns || 0) * Number(rack_rows || 0) * Number(rack_levels || 0);
|
||
|
||
// 读取已有仓位编码,用于差量补齐。
|
||
const existingSpaces = await ctx.model.LocationSpace.findAll({
|
||
where: {
|
||
zone_id: rackId,
|
||
deleted_at: null,
|
||
},
|
||
attributes: [ 'id', 'space_code' ],
|
||
raw: true,
|
||
transaction,
|
||
});
|
||
const existingSpaceCodeSet = new Set(
|
||
(Array.isArray(existingSpaces) ? existingSpaces : [])
|
||
.map(item => String(item && item.space_code || '').trim())
|
||
.filter(Boolean)
|
||
);
|
||
|
||
const rackWidth = rack.width;
|
||
const rackLength = rack.length;
|
||
const prelativeX = x;
|
||
const prelativeY = y;
|
||
const prelativeZ = z;
|
||
const cellLength = rackLength / rack_columns / rack_levels;
|
||
const cellWidth = rackWidth;
|
||
const cellHeight = rack.height / rack_rows;
|
||
|
||
const spaces = [];
|
||
for (let row = 1; row <= rack_rows; row++) {
|
||
for (let column = 1; column <= rack_columns; column++) {
|
||
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,
|
||
max_weight: 100000,
|
||
space_status: 'AVAILABLE',
|
||
is_enabled: true,
|
||
relative_x: relativeX,
|
||
relative_y: relativeY,
|
||
relative_z: relativeZ,
|
||
pick_sequence: 0,
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
const expectedSpaceCodeSet = new Set(spaces.map(space => String(space.space_code || '').trim()).filter(Boolean));
|
||
const spacesNeedDelete = (Array.isArray(existingSpaces) ? existingSpaces : []).filter(space => {
|
||
const spaceCode = String(space && space.space_code || '').trim();
|
||
return spaceCode && !expectedSpaceCodeSet.has(spaceCode);
|
||
});
|
||
|
||
if (spacesNeedDelete.length > 0) {
|
||
const extraSpaceIds = spacesNeedDelete
|
||
.map(space => Number(space && space.id))
|
||
.filter(spaceId => Number.isFinite(spaceId) && spaceId > 0);
|
||
|
||
if (extraSpaceIds.length > 0) {
|
||
const storages = await ctx.model.Storage.findAll({
|
||
where: {
|
||
space_id: {
|
||
[Op.in]: extraSpaceIds,
|
||
},
|
||
delete_at: null,
|
||
is_enabled: 1,
|
||
[Op.or]: [
|
||
{ quantity: { [Op.gt]: 0 } },
|
||
{ locked_quantity: { [Op.gt]: 0 } },
|
||
{ available_quantity: { [Op.gt]: 0 } },
|
||
],
|
||
},
|
||
attributes: [ 'space_id', 'quantity', 'locked_quantity', 'available_quantity' ],
|
||
raw: true,
|
||
transaction,
|
||
});
|
||
|
||
if (Array.isArray(storages) && storages.length > 0) {
|
||
const occupiedSpaceIdSet = new Set(storages.map(item => Number(item && item.space_id)).filter(Boolean));
|
||
const occupiedSpaceCodes = spacesNeedDelete
|
||
.filter(space => occupiedSpaceIdSet.has(Number(space && space.id)))
|
||
.map(space => String(space && space.space_code || '').trim())
|
||
.filter(Boolean);
|
||
|
||
throw new Error(`发现 ${spacesNeedDelete.length} 个多余库位,其中 ${occupiedSpaceCodes.length} 个存在库存,禁止自动删除:${occupiedSpaceCodes.slice(0, 10).join(',')}`);
|
||
}
|
||
|
||
await ctx.model.LocationSpace.destroy({
|
||
where: {
|
||
id: {
|
||
[Op.in]: extraSpaceIds,
|
||
},
|
||
},
|
||
transaction,
|
||
});
|
||
}
|
||
}
|
||
|
||
const missingSpaces = spaces.filter(space => !existingSpaceCodeSet.has(String(space.space_code || '').trim()));
|
||
const existingSpaceCount = existingSpaceCodeSet.size;
|
||
|
||
if (missingSpaces.length === 0 && spacesNeedDelete.length === 0) {
|
||
return `货架 ${rack.zone_code} 已完整存在 ${existingSpaceCount} 个仓位,无需补齐`;
|
||
}
|
||
|
||
if (missingSpaces.length === 0) {
|
||
return `货架 ${rack.zone_code} 已删除 ${spacesNeedDelete.length} 个多余库位,当前总数 ${expectedSpaceCount}/${expectedSpaceCount}`;
|
||
}
|
||
|
||
try {
|
||
await app.model.LocationSpace.bulkCreate(missingSpaces, { transaction });
|
||
const finalSpaceCount = existingSpaceCount - spacesNeedDelete.length + missingSpaces.length;
|
||
if (spacesNeedDelete.length > 0) {
|
||
return `为货架 ${rack.zone_code} 删除 ${spacesNeedDelete.length} 个多余库位并补齐 ${missingSpaces.length} 个仓位(总数 ${finalSpaceCount}/${expectedSpaceCount})`;
|
||
}
|
||
return `为货架 ${rack.zone_code} 补齐 ${missingSpaces.length} 个仓位(总数 ${finalSpaceCount}/${expectedSpaceCount})`;
|
||
} catch (error) {
|
||
// 并发场景:再次按编码回查后补齐剩余缺口。
|
||
const latestSpaces = await ctx.model.LocationSpace.findAll({
|
||
where: {
|
||
zone_id: rackId,
|
||
deleted_at: null,
|
||
},
|
||
attributes: [ 'space_code' ],
|
||
raw: true,
|
||
transaction,
|
||
});
|
||
const latestSpaceCodeSet = new Set(
|
||
(Array.isArray(latestSpaces) ? latestSpaces : [])
|
||
.map(item => String(item && item.space_code || '').trim())
|
||
.filter(Boolean)
|
||
);
|
||
const retryMissingSpaces = spaces.filter(space => !latestSpaceCodeSet.has(String(space.space_code || '').trim()));
|
||
|
||
if (retryMissingSpaces.length === 0) {
|
||
return `货架 ${rack.zone_code} 已完整存在 ${latestSpaceCodeSet.size} 个仓位,无需补齐`;
|
||
}
|
||
|
||
await app.model.LocationSpace.bulkCreate(retryMissingSpaces, { transaction });
|
||
const finalSpaceCount = latestSpaceCodeSet.size + retryMissingSpaces.length;
|
||
if (spacesNeedDelete.length > 0) {
|
||
return `为货架 ${rack.zone_code} 删除 ${spacesNeedDelete.length} 个多余库位并补齐 ${retryMissingSpaces.length} 个仓位(总数 ${finalSpaceCount}/${expectedSpaceCount})`;
|
||
}
|
||
return `为货架 ${rack.zone_code} 补齐 ${retryMissingSpaces.length} 个仓位(总数 ${finalSpaceCount}/${expectedSpaceCount})`;
|
||
}
|
||
}
|
||
/**
|
||
* 获取仓位信息(优先当前仓库,未命中时校验全局归属)。
|
||
* @param {number|string} id 仓位ID
|
||
* @return {Promise<Object>} 仓位信息
|
||
* @throws {Error} 仓位不存在
|
||
* @throws {Error} 仓位不属于当前仓库
|
||
*/
|
||
async getSpaceInfo(id) {
|
||
const { ctx } = this;
|
||
const warehouseId = ctx.user.store_id;
|
||
const attributes = [ 'id', 'location_type_id', 'space_code', 'custom_name', 'custom_barcode', 'space_status', 'pick_sequence' ];
|
||
|
||
try {
|
||
const currentWarehouseSpace = await ctx.model.LocationSpace.findOne({
|
||
where: {
|
||
id,
|
||
warehouse_id: warehouseId,
|
||
deleted_at: null,
|
||
},
|
||
attributes,
|
||
});
|
||
|
||
if (currentWarehouseSpace) {
|
||
return currentWarehouseSpace;
|
||
}
|
||
|
||
const globalSpace = await ctx.model.LocationSpace.findOne({
|
||
where: {
|
||
id,
|
||
deleted_at: null,
|
||
},
|
||
attributes: [ 'id', 'warehouse_id' ],
|
||
});
|
||
|
||
if (!globalSpace) {
|
||
throw new Error('仓位不存在');
|
||
}
|
||
|
||
if (Number(globalSpace.warehouse_id) !== Number(warehouseId)) {
|
||
throw new Error('仓位不属于当前仓库');
|
||
}
|
||
|
||
throw new Error('仓位不存在');
|
||
} catch (error) {
|
||
ctx.logger.error('获取分区路径失败:', error);
|
||
throw error;
|
||
}
|
||
}
|
||
async checkBarcodeUnique(id, barcode, warehouseId) {
|
||
const { ctx, app } = this;
|
||
const { Op } = this.app.Sequelize || app.Sequelize;
|
||
try {
|
||
// 检查条码是否被其他仓位使用(排除当前仓位,仓库内唯一)
|
||
const whereConditions = [
|
||
{
|
||
id: {
|
||
[Op.ne]: id, // 排除当前仓位ID
|
||
},
|
||
},
|
||
{
|
||
[Op.or]: [
|
||
{ custom_barcode: barcode }, // 检查自定义条码
|
||
{ space_code: barcode }, // 检查仓位编码
|
||
],
|
||
},
|
||
{ deleted_at: null }, // 未删除的记录
|
||
];
|
||
if (warehouseId) {
|
||
whereConditions.push({ warehouse_id: warehouseId });
|
||
}
|
||
const space = await ctx.model.LocationSpace.findOne({
|
||
where: {
|
||
[Op.and]: whereConditions,
|
||
},
|
||
attributes: [ 'id' ],
|
||
});
|
||
|
||
// 如果没有找到重复的条码,返回唯一
|
||
if (!space) {
|
||
return { isUnique: true };
|
||
}
|
||
return { isUnique: false, message: '条码已被使用' };
|
||
|
||
} catch (error) {
|
||
ctx.logger.error('检查条码唯一性失败:', error);
|
||
return { isUnique: false, message: '条码检测失败' };
|
||
}
|
||
}
|
||
}
|
||
|
||
module.exports = LocationZoneService;
|