WMS_MAIN/app/service/systems/location_space.js

722 lines
18 KiB
JavaScript

'use strict';
const Service = require('egg').Service;
class LocationSpaceService extends Service {
/**
* 创建仓位
* @param {Object} data 仓位数据
* @return {Promise<Object>} 创建结果
*/
async create(data) {
const { ctx } = this;
// 验证参数
const rules = {
warehouse_id: { type: 'int', required: true },
zone_id: { type: 'int', required: true },
location_type_id: { type: 'int', required: true },
space_code: { type: 'string', required: true, max: 50 },
custom_name: { type: 'string', required: false, max: 100 },
custom_barcode: { type: 'string', required: false, max: 100 },
row_no: { type: 'string', required: false, max: 10 },
column_no: { type: 'string', required: false, max: 10 },
level_no: { type: 'string', required: false, max: 10 },
cell_no: { type: 'string', required: false, max: 10 },
length: { type: 'number', required: false },
width: { type: 'number', required: false },
height: { type: 'number', required: false },
volume: { type: 'number', required: false },
max_weight: { type: 'number', required: false },
};
try {
ctx.validate(rules, data);
} catch (error) {
ctx.throw(400, error.errors[0].message);
}
// 检查仓位编码唯一性
const exists = await ctx.model.LocationSpace.findOne({
where: {
warehouse_id: data.warehouse_id,
space_code: data.space_code,
},
});
if (exists) {
ctx.throw(400, '仓位编码已存在');
}
// 检查条码唯一性(仓库内唯一)
if (data.custom_barcode) {
const barcodeExists = await ctx.model.LocationSpace.findOne({
where: {
warehouse_id: data.warehouse_id,
custom_barcode: data.custom_barcode,
},
});
if (barcodeExists) {
ctx.throw(400, '条码已存在');
}
}
// 检查关联数据存在性
await this._validateReferences(data);
// 设置创建人
const user = ctx.state.user;
if (user && user.id) {
data.created_by = user.id;
}
return await ctx.model.LocationSpace.create(data);
}
/**
* 批量创建仓位
* @param {Array<Object>} dataList 仓位数据列表
* @return {Promise<Array>} 创建结果
*/
async batchCreate(dataList) {
const { ctx } = this;
if (!Array.isArray(dataList) || dataList.length === 0) {
ctx.throw(400, '仓位数据不能为空');
}
// 检查批量数据中的唯一性
const warehouseId = dataList[0].warehouse_id;
const spaceCodes = dataList.map(item => item.space_code);
const barcodes = dataList.map(item => item.custom_barcode).filter(Boolean);
// 检查编码重复
const duplicateCodes = await ctx.model.LocationSpace.findAll({
where: {
warehouse_id: warehouseId,
space_code: { [ctx.app.Sequelize.Op.in]: spaceCodes },
},
attributes: [ 'space_code' ],
raw: true,
});
if (duplicateCodes.length > 0) {
const codes = duplicateCodes.map(item => item.space_code).join(',');
ctx.throw(400, `以下仓位编码已存在: ${codes}`);
}
// 检查条码重复(仓库内唯一)
if (barcodes.length > 0) {
const duplicateBarcodes = await ctx.model.LocationSpace.findAll({
where: {
warehouse_id: warehouseId,
custom_barcode: { [ctx.app.Sequelize.Op.in]: barcodes },
},
attributes: [ 'custom_barcode' ],
raw: true,
});
if (duplicateBarcodes.length > 0) {
const codes = duplicateBarcodes.map(item => item.custom_barcode).join(',');
ctx.throw(400, `以下条码已存在: ${codes}`);
}
}
// 批量创建
const user = ctx.state.user;
const timestamp = new Date();
const locationSpaces = dataList.map(data => ({
...data,
created_by: user ? user.id : null,
created_at: timestamp,
updated_at: timestamp,
}));
return await ctx.model.LocationSpace.bulkCreate(locationSpaces);
}
/**
* 获取仓位列表
* @param {Object} params 查询参数
* @return {Promise<Object>} 列表结果
*/
async list(params = {}) {
const { ctx } = this;
const {
warehouse_id,
zone_id,
location_type_id,
space_status,
is_enabled,
space_code,
custom_name,
page = 1,
pageSize = 20,
} = params;
const where = {};
if (warehouse_id) {
where.warehouse_id = warehouse_id;
}
if (zone_id) {
where.zone_id = zone_id;
}
if (location_type_id) {
where.location_type_id = location_type_id;
}
if (space_status) {
where.space_status = space_status;
}
if (is_enabled !== undefined) {
where.is_enabled = is_enabled;
}
if (space_code) {
where.space_code = { [ctx.app.Sequelize.Op.like]: `%${space_code}%` };
}
if (custom_name) {
where.custom_name = { [ctx.app.Sequelize.Op.like]: `%${custom_name}%` };
}
const { count, rows } = await ctx.model.LocationSpace.findAndCountAll({
where,
include: [
{
model: ctx.model.Store,
as: 'warehouse',
attributes: [ 'store_name', 'store_code' ],
},
{
model: ctx.model.LocationZone,
as: 'zone',
attributes: [ 'zone_code', 'zone_name' ],
},
{
model: ctx.model.LocationType,
as: 'locationType',
attributes: [ 'type_code', 'type_name', 'category' ],
},
],
order: [
[ 'warehouse_id', 'ASC' ],
[ 'zone_id', 'ASC' ],
[ 'row_no', 'ASC' ],
[ 'column_no', 'ASC' ],
[ 'level_no', 'ASC' ],
[ 'cell_no', 'ASC' ],
],
offset: (page - 1) * pageSize,
limit: parseInt(pageSize),
distinct: true,
});
return {
list: rows,
pagination: {
page: parseInt(page),
pageSize: parseInt(pageSize),
total: count,
totalPages: Math.ceil(count / pageSize),
},
};
}
/**
* 获取仓位详情
* @param {number|string} id 仓位ID
* @return {Promise<Object>} 仓位详情
*/
async detail(id) {
const { ctx } = this;
const locationSpace = await ctx.model.LocationSpace.findByPk(id, {
include: [
{
model: ctx.model.Store,
as: 'warehouse',
attributes: [ 'id', 'store_name', 'store_code' ],
},
{
model: ctx.model.LocationZone,
as: 'zone',
attributes: [ 'id', 'zone_code', 'zone_name' ],
},
{
model: ctx.model.LocationType,
as: 'locationType',
attributes: [ 'id', 'type_code', 'type_name', 'category',
'allow_allocation', 'allow_transfer_out' ],
},
],
});
if (!locationSpace) {
ctx.throw(404, '仓位不存在');
}
return locationSpace;
}
/**
* 更新仓位
* @param {number|string} id 仓位ID
* @param {Object} data 更新数据
* @return {Promise<Object>} 更新结果
*/
async update(id, data) {
const { ctx } = this;
const locationSpace = await ctx.model.LocationSpace.findByPk(id);
if (!locationSpace) {
ctx.throw(404, '仓位不存在');
}
// 不能修改的字段
const protectedFields = [ 'id', 'warehouse_id', 'created_at', 'created_by' ];
protectedFields.forEach(field => delete data[field]);
// 如果修改编码,检查唯一性
if (data.space_code && data.space_code !== locationSpace.space_code) {
const exists = await ctx.model.LocationSpace.findOne({
where: {
warehouse_id: locationSpace.warehouse_id,
space_code: data.space_code,
id: { [ctx.app.Sequelize.Op.ne]: id },
},
});
if (exists) {
ctx.throw(400, '仓位编码已存在');
}
}
// 如果修改条码,检查唯一性(仓库内唯一)
if (data.custom_barcode && data.custom_barcode !== locationSpace.custom_barcode) {
const exists = await ctx.model.LocationSpace.findOne({
where: {
warehouse_id: locationSpace.warehouse_id,
custom_barcode: data.custom_barcode,
id: { [ctx.app.Sequelize.Op.ne]: id },
},
});
if (exists) {
ctx.throw(400, '条码已存在');
}
}
// 检查关联数据存在性
if (data.zone_id || data.location_type_id) {
await this._validateReferences({
zone_id: data.zone_id || locationSpace.zone_id,
location_type_id: data.location_type_id || locationSpace.location_type_id,
});
}
// 设置更新人
const user = ctx.state.user;
if (user && user.id) {
data.updated_by = user.id;
}
await locationSpace.update(data);
return locationSpace;
}
/**
* 删除仓位(软删除)
* @param {number|string} id 仓位ID
* @return {Promise<boolean>} 删除结果
*/
async delete(id) {
const { ctx } = this;
const locationSpace = await ctx.model.LocationSpace.findByPk(id);
if (!locationSpace) {
ctx.throw(404, '仓位不存在');
}
// 检查仓位是否被使用
if (locationSpace.space_status === 'OCCUPIED') {
ctx.throw(400, '仓位已被占用,无法删除');
}
if (locationSpace.current_quantity > 0) {
ctx.throw(400, '仓位内仍有库存,无法删除');
}
// 软删除:设置为禁用
const user = ctx.state.user;
const updateData = {
is_enabled: 0,
space_status: 'DISABLED',
};
if (user && user.id) {
updateData.updated_by = user.id;
}
await locationSpace.update(updateData);
return true;
}
/**
* 启用/禁用仓位
* @param {number|string} id 仓位ID
* @param {boolean} enabled 是否启用
* @return {Promise<Object>} 操作结果
*/
async toggleStatus(id, enabled) {
const { ctx } = this;
const locationSpace = await ctx.model.LocationSpace.findByPk(id);
if (!locationSpace) {
ctx.throw(404, '仓位不存在');
}
const user = ctx.state.user;
const updateData = {
is_enabled: enabled ? 1 : 0,
};
if (!enabled && locationSpace.space_status === 'AVAILABLE') {
updateData.space_status = 'DISABLED';
}
if (user && user.id) {
updateData.updated_by = user.id;
}
await locationSpace.update(updateData);
return locationSpace;
}
/**
* 更新仓位状态
* @param {number|string} id 仓位ID
* @param {string} status 仓位状态
* @return {Promise<Object>} 操作结果
*/
async updateStatus(id, status) {
const { ctx } = this;
const validStatuses = [ 'AVAILABLE', 'OCCUPIED', 'RESERVED', 'MAINTENANCE', 'DISABLED' ];
if (!validStatuses.includes(status)) {
ctx.throw(400, '无效的仓位状态');
}
const locationSpace = await ctx.model.LocationSpace.findByPk(id);
if (!locationSpace) {
ctx.throw(404, '仓位不存在');
}
// 状态转换限制
const statusRules = {
OCCUPIED: () => {
if (locationSpace.space_status !== 'AVAILABLE' && locationSpace.space_status !== 'RESERVED') {
throw new Error('只有可用或预留仓位才能设置为占用');
}
},
AVAILABLE: () => {
if (locationSpace.space_status === 'OCCUPIED' && locationSpace.current_quantity > 0) {
throw new Error('占用仓位有库存时不能设置为可用');
}
},
};
if (statusRules[status]) {
try {
statusRules[status]();
} catch (error) {
ctx.throw(400, error.message);
}
}
const user = ctx.state.user;
const updateData = { space_status: status };
if (user && user.id) {
updateData.updated_by = user.id;
}
await locationSpace.update(updateData);
return locationSpace;
}
/**
* 查询可用仓位
* @param {Object} params 查询参数
* @return {Promise<Array>} 可用仓位列表
*/
async findAvailableSpaces(params) {
const { ctx } = this;
const { warehouse_id, zone_id, location_type_id } = params;
const where = {
space_status: 'AVAILABLE',
is_enabled: 1,
};
if (warehouse_id) {
where.warehouse_id = warehouse_id;
}
if (zone_id) {
where.zone_id = zone_id;
}
if (location_type_id) {
where.location_type_id = location_type_id;
}
return await ctx.model.LocationSpace.findAll({
where,
include: [
{
model: ctx.model.LocationZone,
as: 'zone',
attributes: [ 'zone_code', 'zone_name' ],
},
{
model: ctx.model.LocationType,
as: 'locationType',
where: { allow_allocation: 1, is_active: 1 },
attributes: [ 'type_code', 'type_name' ],
},
],
order: [
[ 'zone_id', 'ASC' ],
[ 'row_no', 'ASC' ],
[ 'column_no', 'ASC' ],
[ 'level_no', 'ASC' ],
[ 'cell_no', 'ASC' ],
],
});
}
/**
* 根据编码查找仓位
* @param {number|string} warehouseId 仓库ID
* @param {string} spaceCode 仓位编码
* @return {Promise<Object>} 仓位信息
*/
async findByCode(warehouseId, spaceCode) {
const { ctx } = this;
const locationSpace = await ctx.model.LocationSpace.findOne({
where: {
warehouse_id: warehouseId,
space_code: spaceCode,
is_enabled: 1,
},
include: [
{
model: ctx.model.LocationZone,
as: 'zone',
attributes: [ 'zone_code', 'zone_name' ],
},
{
model: ctx.model.LocationType,
as: 'locationType',
attributes: [ 'type_code', 'type_name', 'allow_allocation', 'allow_transfer_out' ],
},
],
});
if (!locationSpace) {
ctx.throw(404, '仓位不存在');
}
return locationSpace;
}
/**
* 根据条码查找仓位
* @param {string} barcode 条码
* @return {Promise<Object>} 仓位信息
*/
async findByBarcode(barcode) {
const { ctx } = this;
const locationSpace = await ctx.model.LocationSpace.findOne({
where: {
custom_barcode: barcode,
is_enabled: 1,
},
include: [
{
model: ctx.model.Store,
as: 'warehouse',
attributes: [ 'store_name', 'store_code' ],
},
{
model: ctx.model.LocationZone,
as: 'zone',
attributes: [ 'zone_code', 'zone_name' ],
},
],
});
if (!locationSpace) {
ctx.throw(404, '仓位不存在');
}
return locationSpace;
}
/**
* 获取仓库仓位统计
* @param {number|string} warehouseId 仓库ID
* @return {Promise<Object>} 统计结果
*/
async getWarehouseStats(warehouseId) {
const { ctx } = this;
const stats = await ctx.model.LocationSpace.getWarehouseStats(ctx.app, warehouseId);
// 汇总数据
const result = {
available: 0,
occupied: 0,
reserved: 0,
maintenance: 0,
disabled: 0,
total: 0,
};
stats.forEach(item => {
result[item.space_status.toLowerCase()] = parseInt(item.count);
result.total += parseInt(item.count);
});
return result;
}
/**
* 获取分区的仓位统计
* @param {number|string} warehouseId 仓库ID
* @param {number|string|null} zoneId 分区ID
* @return {Promise<Array|Object>} 统计结果
*/
async getZoneStats(warehouseId, zoneId = null) {
const { ctx } = this;
const stats = await ctx.model.LocationSpace.getZoneStats(ctx.app, warehouseId);
if (zoneId) {
return stats.find(item => item.zone_id === zoneId);
}
return stats;
}
/**
* 验证仓位是否可分配
* @param {number|string} locationSpaceId 仓位ID
* @return {Promise<Object>} 仓位信息
*/
async validateAllocation(locationSpaceId) {
const { ctx } = this;
const locationSpace = await ctx.model.LocationSpace.findByPk(locationSpaceId, {
include: [{
model: ctx.model.LocationType,
as: 'locationType',
attributes: [ 'allow_allocation', 'is_active' ],
}],
});
if (!locationSpace) {
ctx.throw(404, '仓位不存在');
}
if (!locationSpace.isAvailable()) {
ctx.throw(400, '仓位不可用');
}
if (!locationSpace.locationType ||
locationSpace.locationType.allow_allocation !== 1 ||
locationSpace.locationType.is_active !== 1) {
ctx.throw(400, '该仓位类型不允许分配');
}
return locationSpace;
}
/**
* 验证仓位是否可移出
* @param {number|string} locationSpaceId 仓位ID
* @return {Promise<Object>} 仓位信息
*/
async validateTransferOut(locationSpaceId) {
const { ctx } = this;
const locationSpace = await ctx.model.LocationSpace.findByPk(locationSpaceId, {
include: [{
model: ctx.model.LocationType,
as: 'locationType',
attributes: [ 'allow_transfer_out', 'is_active' ],
}],
});
if (!locationSpace) {
ctx.throw(404, '仓位不存在');
}
if (locationSpace.space_status !== 'OCCUPIED') {
ctx.throw(400, '仓位未被占用');
}
if (!locationSpace.locationType ||
locationSpace.locationType.allow_transfer_out !== 1 ||
locationSpace.locationType.is_active !== 1) {
ctx.throw(400, '该仓位类型不允许移出');
}
return locationSpace;
}
/**
* 内部方法:验证关联数据
* @param {Object} data 关联数据
* @return {Promise<void>}
*/
async _validateReferences(data) {
const { ctx } = this;
// 验证仓库存在
if (data.warehouse_id) {
const warehouse = await ctx.model.Store.findByPk(data.warehouse_id);
if (!warehouse) {
ctx.throw(400, '仓库不存在');
}
}
// 验证分区存在
if (data.zone_id) {
const zone = await ctx.model.LocationZone.findByPk(data.zone_id);
if (!zone || !zone.is_active) {
ctx.throw(400, '分区不存在或已禁用');
}
}
// 验证仓位类型存在
if (data.location_type_id) {
const locationType = await ctx.model.LocationType.findByPk(data.location_type_id);
if (!locationType || !locationType.is_active) {
ctx.throw(400, '仓位类型不存在或已禁用');
}
}
}
}
module.exports = LocationSpaceService;