2032 lines
60 KiB
JavaScript
2032 lines
60 KiB
JavaScript
'use strict';
|
||
|
||
const Service = require('egg').Service;
|
||
const { parseWhereConditions } = require('../../../lib/query_condition_parser');
|
||
class ReceivingService extends Service {
|
||
/**
|
||
* 查询收货单列表。
|
||
* @param {Object} where 动态筛选条件
|
||
* @param {Object} [pageParams] 分页参数
|
||
* @param {number} [pageParams.page=1] 页码
|
||
* @param {number} [pageParams.pageSize=20] 每页条数
|
||
* @param {Object} [sortParams] 排序参数
|
||
* @return {Promise<Object>} 列表、分页与汇总信息
|
||
*/
|
||
async getReceivingList(where, pageParams = {}, sortParams = {}) {
|
||
const {
|
||
ctx,
|
||
app,
|
||
config,
|
||
} = this;
|
||
const {
|
||
Sequelize,
|
||
} = app;
|
||
const {
|
||
Op,
|
||
} = Sequelize;
|
||
const {
|
||
page = 1,
|
||
pageSize = 20,
|
||
} = pageParams;
|
||
|
||
try {
|
||
const {
|
||
sortField = 'id',
|
||
sortOrder = 'DESC',
|
||
} = sortParams;
|
||
|
||
const queryOptions = {
|
||
where: {
|
||
[Op.and]: [
|
||
{
|
||
warehouse_id: ctx.user.store_id,
|
||
},
|
||
],
|
||
},
|
||
order: [],
|
||
attributes: {
|
||
exclude: [ 'deleted_at' ],
|
||
},
|
||
};
|
||
|
||
const normalizedWhere = ctx.where && typeof ctx.where === 'object'
|
||
? ctx.where
|
||
: (where && typeof where === 'object' ? where : {});
|
||
|
||
let parsedResult = ctx.whereParsed;
|
||
if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) {
|
||
const parsed = parseWhereConditions({
|
||
where: normalizedWhere,
|
||
app,
|
||
specialFieldMap: {
|
||
quickWhere: {
|
||
bucket: 'quick',
|
||
},
|
||
},
|
||
});
|
||
|
||
if (!parsed.ok) {
|
||
return {
|
||
code: 400,
|
||
data: {
|
||
list: [],
|
||
pagination: {
|
||
page: parseInt(page),
|
||
pageSize: parseInt(pageSize),
|
||
total: 0,
|
||
totalPages: 0,
|
||
hasPrevious: false,
|
||
hasNext: false,
|
||
},
|
||
summary: {
|
||
total_quantity: 0,
|
||
total_locked: 0,
|
||
total_available: 0,
|
||
total_items: 0,
|
||
},
|
||
},
|
||
message: `筛选条件解析失败: ${parsed.reason}`,
|
||
};
|
||
}
|
||
parsedResult = parsed.result;
|
||
}
|
||
|
||
const dynamicConditions = [ ...(parsedResult.dynamicConditions || []) ];
|
||
const quickWhereRaw = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere)
|
||
|| normalizedWhere.quickWhere;
|
||
|
||
if (quickWhereRaw && !this.isEmptyValue(quickWhereRaw.value)) {
|
||
const quickValue = String(quickWhereRaw.value).trim();
|
||
dynamicConditions.push({
|
||
[Op.or]: {
|
||
store_name: {
|
||
[Sequelize.Op.like]: `%${quickValue}%`,
|
||
},
|
||
receiving_number: {
|
||
[Sequelize.Op.like]: `%${quickValue}%`,
|
||
},
|
||
tracking_number: {
|
||
[Sequelize.Op.like]: `%${quickValue}%`,
|
||
},
|
||
creator_snapshot: {
|
||
[Sequelize.Op.like]: `%${quickValue}%`,
|
||
},
|
||
license_plate: {
|
||
[Sequelize.Op.like]: `%${quickValue}%`,
|
||
},
|
||
},
|
||
});
|
||
}
|
||
|
||
if (dynamicConditions.length > 0) {
|
||
queryOptions.where[Op.and].push({
|
||
[Op.and]: dynamicConditions,
|
||
});
|
||
}
|
||
|
||
const validSortFields = [
|
||
'id', 'receiving_number', 'status', 'create_at', 'update_at', 'store_id',
|
||
];
|
||
const actualSortField = validSortFields.includes(sortField) ? sortField : 'create_at';
|
||
const actualSortOrder = sortOrder.toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
|
||
queryOptions.order.push([ actualSortField, actualSortOrder ]);
|
||
|
||
const offset = (page - 1) * pageSize;
|
||
const include = [
|
||
{
|
||
model: ctx.model.StoreWarehouse,
|
||
as: 'store',
|
||
attributes: [ 'store_remask' ],
|
||
where: {
|
||
use_status: 1,
|
||
warehouse_id: ctx.user.store_id,
|
||
},
|
||
required: false,
|
||
},
|
||
{
|
||
model: ctx.model.AccountStoreEmployee,
|
||
as: 'creator',
|
||
attributes: [ 'real_name' ],
|
||
required: true,
|
||
},
|
||
];
|
||
|
||
const [ total, data ] = await Promise.all([
|
||
ctx.model.Receiving.count({
|
||
where: queryOptions.where,
|
||
include,
|
||
distinct: true,
|
||
}),
|
||
ctx.model.Receiving.findAll({
|
||
...queryOptions,
|
||
include,
|
||
limit: parseInt(pageSize),
|
||
offset: parseInt(offset),
|
||
distinct: true,
|
||
raw: true,
|
||
}),
|
||
]);
|
||
|
||
const totalPages = Math.ceil(total / pageSize);
|
||
const hasPrevious = page > 1;
|
||
const hasNext = page < totalPages;
|
||
|
||
const stockIds = data.map(item => item.id);
|
||
let images = [];
|
||
if (stockIds.length > 0) {
|
||
images = await ctx.model.FileReference.findAll({
|
||
where: {
|
||
business_type: 'receiving',
|
||
business_id: {
|
||
[Op.in]: stockIds,
|
||
},
|
||
},
|
||
include: [
|
||
{
|
||
model: ctx.model.File,
|
||
as: 'file',
|
||
attributes: [ 'file_url' ],
|
||
required: true,
|
||
},
|
||
],
|
||
});
|
||
}
|
||
|
||
const processedData = data.map(item => {
|
||
const availableQuantity = Math.max(0, item.quantity - item.locked_quantity);
|
||
const lockRate = item.quantity > 0 ? (item.locked_quantity / item.quantity * 100).toFixed(2) : 0;
|
||
const itemImages = images
|
||
.filter(row => parseInt(row.business_id) === item.id)
|
||
.map(row => row.file.file_url);
|
||
return {
|
||
...item,
|
||
images: itemImages,
|
||
available_quantity: availableQuantity,
|
||
lock_rate: parseFloat(lockRate),
|
||
lock_rate_display: `${lockRate}%`,
|
||
create_at_display: item.create_at ? this.formatDate(item.create_at) : '',
|
||
update_at_display: item.update_at ? this.formatDate(item.update_at) : '',
|
||
};
|
||
});
|
||
|
||
const summary = {
|
||
total_quantity: data.reduce((sum, item) => sum + item.quantity, 0),
|
||
total_locked: data.reduce((sum, item) => sum + item.locked_quantity, 0),
|
||
total_available: data.reduce((sum, item) => sum + Math.max(0, item.quantity - item.locked_quantity), 0),
|
||
total_items: data.length,
|
||
};
|
||
|
||
return {
|
||
code: 200,
|
||
data: {
|
||
list: processedData,
|
||
pagination: {
|
||
page: parseInt(page),
|
||
pageSize: parseInt(pageSize),
|
||
total,
|
||
totalPages,
|
||
hasPrevious,
|
||
hasNext,
|
||
},
|
||
summary,
|
||
queryInfo: {
|
||
conditions: normalizedWhere,
|
||
sortField: actualSortField,
|
||
sortOrder: actualSortOrder,
|
||
hasBarcodeSearch: false,
|
||
},
|
||
},
|
||
message: '查询成功',
|
||
};
|
||
} catch (error) {
|
||
ctx.logger.error('[StockService.getWarehouseStock] 查询失败:', error);
|
||
return {
|
||
code: 500,
|
||
data: {
|
||
list: [],
|
||
pagination: {
|
||
page: parseInt(page || 1),
|
||
pageSize: parseInt(pageSize || 20),
|
||
total: 0,
|
||
totalPages: 0,
|
||
hasPrevious: false,
|
||
hasNext: false,
|
||
},
|
||
summary: {
|
||
total_quantity: 0,
|
||
total_locked: 0,
|
||
total_available: 0,
|
||
total_items: 0,
|
||
},
|
||
},
|
||
message: `查询失败: ${error.message}`,
|
||
};
|
||
}
|
||
}
|
||
/**
|
||
* 获取收货单详情(主单 + 明细分页 + 图片)。
|
||
* @param {Object} data 请求体
|
||
* @param {number} data.id 收货单ID
|
||
* @param {Object} data.pagination 分页参数
|
||
* @return {Promise<Object>} 详情数据
|
||
*/
|
||
async getReceivingDetail(data) {
|
||
const { id, pagination } = data;
|
||
const { page, pageSize } = pagination;
|
||
const { ctx, app } = this;
|
||
const { Op } = app.Sequelize;
|
||
// 获取用户仓库ID,增加错误处理
|
||
const warehouseId = ctx.user?.store_id;
|
||
if (!warehouseId) {
|
||
return { code: 0, message: '用户未绑定仓库', data: {} };
|
||
}
|
||
try {
|
||
// 1. 查询收货单主表
|
||
const receiving = await app.model.Receiving.findOne({ where: { id, warehouse_id: warehouseId } });
|
||
if (!receiving) {
|
||
return { code: 0, message: '无记录或无权访问', data: {} };
|
||
}
|
||
// 2. 查询收货单明细,按分页
|
||
const receivingItems = await app.model.ReceivingDetail.findAll({
|
||
where: { receiving_id: id },
|
||
offset: (page - 1) * pageSize,
|
||
limit: pageSize,
|
||
});
|
||
// 获取明细总数
|
||
const totalItems = await app.model.ReceivingDetail.count({ where: { receiving_id: id } });
|
||
//组装分页信息
|
||
const pagination = {
|
||
total: totalItems,
|
||
currentPage: page,
|
||
pageSize: pageSize,
|
||
totalPages: Math.ceil(totalItems / pageSize),
|
||
hasPrevious: page > 1,
|
||
hasNext: page < Math.ceil(totalItems / pageSize),
|
||
};
|
||
|
||
// 3. 获取明细ID数组
|
||
const receivingItemsIds = receivingItems.map(item => item.id);
|
||
// 4. 查询明细图片(如果明细数量大于0)
|
||
const itemImagesMap = {}; // 用于存储每个明细的图片
|
||
if (receivingItemsIds.length > 0) {
|
||
const receivingItemsImages = await ctx.model.FileReference.findAll({
|
||
where: {
|
||
business_type: 'receivingItem',
|
||
business_id: { [Op.in]: receivingItemsIds },
|
||
}
|
||
});
|
||
// 将图片按明细ID分组,eggjs 不能使用forEach异步处理,所以改为同步处理
|
||
for (const image of receivingItemsImages) {
|
||
if (!itemImagesMap[image.business_id]) {
|
||
itemImagesMap[image.business_id] = [];
|
||
}
|
||
itemImagesMap[image.business_id].push(image);
|
||
}
|
||
}
|
||
// 5. 将图片合并到对应的明细中
|
||
const items = receivingItems.map(item => {
|
||
return {
|
||
...item.toJSON(),
|
||
images: itemImagesMap[item.id] || [],
|
||
};
|
||
});
|
||
// 6. 查询主表的图片
|
||
const receivingImages = await ctx.model.FileReference.findAll({
|
||
where: {
|
||
business_type: 'receiving',
|
||
business_id: id,
|
||
}
|
||
});
|
||
// 7. 组装返回数据
|
||
receiving.dataValues.details = items; // 包含图片的明细数据
|
||
receiving.dataValues.images = receivingImages; // 包含主表图片
|
||
receiving.dataValues.pagination = pagination; // 包含分页信息
|
||
return { code: 200, message: '查询成功', data: { receiving } };
|
||
|
||
} catch (error) {
|
||
console.error('获取收货单详情失败:', error);
|
||
return { code: 500, message: '服务器错误', data: {} };
|
||
}
|
||
}
|
||
/**
|
||
* 批量作废收货单。
|
||
* @param {Object} data 请求体
|
||
* @param {number[]} data.ids 收货单ID数组
|
||
* @return {Promise<Object>} 作废处理结果
|
||
*/
|
||
async batchCancelReceiving(data) {
|
||
const { ids } = data;
|
||
const { ctx } = this;
|
||
const { Op } = ctx.model.Sequelize;
|
||
const warehouse_id = ctx.user.store_id;
|
||
try {
|
||
//先查询这些单据是否都存在且状态允许作废
|
||
const receivings = await ctx.model.Receiving.findAll({where:{ id: { [Op.in]: ids }, warehouse_id }});
|
||
if (receivings.length !== ids.length) {
|
||
return { code: 0, message: '部分单据不存在或无权访问', data: {} };
|
||
}else{
|
||
const invalidStatus = receivings.find(r => r.status !== 'receiving');
|
||
if (invalidStatus) {
|
||
return { code: 0, message: '部分单据状态不允许作废', data: {} };
|
||
}
|
||
// 批量更新状态为cancelled
|
||
await ctx.model.Receiving.update({ status: 'cancelled' }, { where: { id: { [Op.in]: ids }, warehouse_id } });
|
||
return { code: 200, message: '批量作废成功', data: {} };
|
||
}
|
||
} catch (error) {
|
||
console.error('批量作废收货单失败:', error);
|
||
return { code: 500, message: '服务器错误', data: {} };
|
||
}
|
||
}
|
||
isEmptyValue(value) {
|
||
if (value === undefined || value === null) {
|
||
return true;
|
||
}
|
||
|
||
if (typeof value === 'string' && value.trim() === '') {
|
||
return true;
|
||
}
|
||
|
||
if (Array.isArray(value) && value.length === 0) {
|
||
return true;
|
||
}
|
||
|
||
return false;
|
||
}
|
||
/**
|
||
* 构建Sequelize查询条件
|
||
* @param {string} fieldKey - 字段键名
|
||
* @param {Object} condition - 条件对象
|
||
* @param {Object} app - Egg应用实例
|
||
* @return {Object|null} Sequelize条件对象
|
||
*/
|
||
buildSequelizeCondition(fieldKey, condition, app) {
|
||
const {
|
||
Sequelize,
|
||
} = app;
|
||
const {
|
||
operator = 'eq', value, type, isMultiple,
|
||
} = condition;
|
||
|
||
// 处理字段名
|
||
const fieldName = condition.field || fieldKey;
|
||
|
||
// 特殊值处理
|
||
const processedValue = this.processConditionValue(value, type);
|
||
// 根据操作符构建条件
|
||
switch (operator.toLowerCase()) {
|
||
case 'eq':
|
||
return {
|
||
[fieldName]: processedValue,
|
||
};
|
||
|
||
case 'ne':
|
||
return {
|
||
[fieldName]: {
|
||
[Sequelize.Op.ne]: processedValue,
|
||
},
|
||
};
|
||
|
||
case 'contains':
|
||
case 'like':
|
||
// 处理多值情况
|
||
if (Array.isArray(processedValue) && processedValue.length > 0) {
|
||
// 多个值使用 OR 连接
|
||
return {
|
||
[Sequelize.Op.or]: processedValue.map(val => ({
|
||
[fieldName]: {
|
||
[Sequelize.Op.like]: `%${val}%`,
|
||
},
|
||
})),
|
||
};
|
||
}
|
||
// 单个值正常处理
|
||
return {
|
||
[fieldName]: {
|
||
[Sequelize.Op.like]: `%${processedValue}%`,
|
||
},
|
||
};
|
||
|
||
case 'startswith':
|
||
// 处理多值情况
|
||
if (Array.isArray(processedValue) && processedValue.length > 0) {
|
||
return {
|
||
[Sequelize.Op.or]: processedValue.map(val => ({
|
||
[fieldName]: {
|
||
[Sequelize.Op.like]: `${val}%`,
|
||
},
|
||
})),
|
||
};
|
||
}
|
||
return {
|
||
[fieldName]: {
|
||
[Sequelize.Op.like]: `${processedValue}%`,
|
||
},
|
||
};
|
||
|
||
case 'endswith':
|
||
// 处理多值情况
|
||
if (Array.isArray(processedValue) && processedValue.length > 0) {
|
||
return {
|
||
[Sequelize.Op.or]: processedValue.map(val => ({
|
||
[fieldName]: {
|
||
[Sequelize.Op.like]: `%${val}`,
|
||
},
|
||
})),
|
||
};
|
||
}
|
||
return {
|
||
[fieldName]: {
|
||
[Sequelize.Op.like]: `%${processedValue}`,
|
||
},
|
||
};
|
||
|
||
case 'gt':
|
||
return {
|
||
[fieldName]: {
|
||
[Sequelize.Op.gt]: processedValue,
|
||
},
|
||
};
|
||
|
||
case 'lt':
|
||
return {
|
||
[fieldName]: {
|
||
[Sequelize.Op.lt]: processedValue,
|
||
},
|
||
};
|
||
|
||
case 'ge':
|
||
return {
|
||
[fieldName]: {
|
||
[Sequelize.Op.gte]: processedValue,
|
||
},
|
||
};
|
||
|
||
case 'le':
|
||
return {
|
||
[fieldName]: {
|
||
[Sequelize.Op.lte]: processedValue,
|
||
},
|
||
};
|
||
|
||
case 'in':
|
||
return Array.isArray(processedValue) ? {
|
||
[fieldName]: {
|
||
[Sequelize.Op.in]: processedValue,
|
||
},
|
||
} :
|
||
null;
|
||
|
||
case 'notin':
|
||
return Array.isArray(processedValue) ? {
|
||
[fieldName]: {
|
||
[Sequelize.Op.notIn]: processedValue,
|
||
},
|
||
} :
|
||
null;
|
||
|
||
case 'between':
|
||
return Array.isArray(processedValue) && processedValue.length === 2 ? {
|
||
[fieldName]: {
|
||
[Sequelize.Op.between]: processedValue,
|
||
},
|
||
} :
|
||
null;
|
||
|
||
case 'notbetween':
|
||
return Array.isArray(processedValue) && processedValue.length === 2 ? {
|
||
[fieldName]: {
|
||
[Sequelize.Op.notBetween]: processedValue,
|
||
},
|
||
} :
|
||
null;
|
||
|
||
case 'isnull':
|
||
return {
|
||
[fieldName]: {
|
||
[Sequelize.Op.is]: null,
|
||
},
|
||
};
|
||
|
||
case 'isnotnull':
|
||
return {
|
||
[fieldName]: {
|
||
[Sequelize.Op.not]: null,
|
||
},
|
||
};
|
||
|
||
case 'regexp':
|
||
return {
|
||
[fieldName]: {
|
||
[Sequelize.Op.regexp]: processedValue,
|
||
},
|
||
};
|
||
|
||
case 'notregexp':
|
||
return {
|
||
[fieldName]: {
|
||
[Sequelize.Op.notRegexp]: processedValue,
|
||
},
|
||
};
|
||
|
||
default:
|
||
// 默认使用等于操作符
|
||
return {
|
||
[fieldName]: processedValue,
|
||
};
|
||
}
|
||
}
|
||
/**
|
||
* 处理条件值
|
||
* @param {any} value - 原始值
|
||
* @param {string} type - 字段类型
|
||
* @return {any} 处理后的值
|
||
*/
|
||
processConditionValue(value, type) {
|
||
const { service } = this;
|
||
if (value === undefined || value === null) {
|
||
return value;
|
||
}
|
||
|
||
switch (type) {
|
||
case 'boolean':
|
||
// 处理布尔值:true/Y -> 'Y', false/N -> 'N'
|
||
if (value === true || value === 'true' || value === 'Y' || value === 'y') {
|
||
return 'Y';
|
||
}
|
||
if (value === false || value === 'false' || value === 'N' || value === 'n') {
|
||
return 'N';
|
||
}
|
||
return value;
|
||
|
||
case 'date':
|
||
// 单个日期,根据业务需求决定是开始还是结束时间
|
||
// 通常是开始时间(00:00:00)
|
||
return service.main.normalizeDate(value, false);
|
||
|
||
case 'daterange':
|
||
// 处理日期范围:数组的第一个元素是开始时间,第二个元素是结束时间
|
||
if (Array.isArray(value) && value.length === 2) {
|
||
const [startDate, endDate] = value;
|
||
console.log(startDate, endDate);
|
||
console.log(startDate ? service.main.normalizeDate(startDate, false) : null, endDate ? service.main.normalizeDate(endDate, true) : null);
|
||
return [
|
||
startDate ? service.main.normalizeDate(startDate, false) : null, // 开始时间设为00:00:00
|
||
endDate ? service.main.normalizeDate(endDate, true) : null, // 结束时间设为23:59:59
|
||
];
|
||
}
|
||
return value;
|
||
|
||
case 'number':
|
||
// 转换为数字
|
||
const num = parseFloat(value);
|
||
return isNaN(num) ? value : num;
|
||
|
||
case 'text':
|
||
// 文本类型,支持逗号分隔
|
||
if (typeof value === 'string') {
|
||
return value.split(',').map(item => item.trim());
|
||
}
|
||
return value;
|
||
|
||
default:
|
||
return value;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 创建收货单并生成收货单号。
|
||
* @param {Object} data 创建参数
|
||
* @return {Promise<Object>} 新建结果(含 id 与 receiving_number)
|
||
*/
|
||
async create(data) {
|
||
const {
|
||
delivery_method,
|
||
license_plate,
|
||
loading_method,
|
||
remark,
|
||
status,
|
||
store_id,
|
||
total_boxes,
|
||
total_pallets,
|
||
tracking_number,
|
||
video_device_id,
|
||
} = data;
|
||
|
||
const { ctx } = this;
|
||
const { app } = ctx;
|
||
|
||
try {
|
||
// 1. 获取当前用户信息
|
||
const warehouse_id = ctx.user.store_id;
|
||
const creator_id = ctx.user.employees_id;
|
||
const creator_snapshot = {
|
||
name: ctx.user.employees_name,
|
||
employees_id: ctx.user.employees_id,
|
||
id: creator_id,
|
||
};
|
||
|
||
// 2. 生成收货单号 (格式: R + 时间戳的day + 3位序列号,如: RR20231215001)
|
||
const now = new Date();
|
||
console.log('当前时间:', now);
|
||
const dateStr = Math.floor(now.getTime() / (1000 * 60 * 60 * 24)); // 时间戳到今日的天数
|
||
const prefix = `R${dateStr}`;
|
||
|
||
// 查找当天最大的收货单号
|
||
const maxReceiving = await app.model.Receiving.findOne({
|
||
where: {
|
||
receiving_number: {
|
||
[app.Sequelize.Op.like]: `${prefix}%`,
|
||
},
|
||
warehouse_id
|
||
},
|
||
order: [['receiving_number', 'DESC']],
|
||
});
|
||
|
||
let sequence = 1;
|
||
if (maxReceiving) {
|
||
// 提取最大收货单号的序号部分
|
||
const lastNumStr = maxReceiving.receiving_number.replace(prefix, '');
|
||
const lastNum = parseInt(lastNumStr);
|
||
sequence = lastNum + 1;
|
||
}
|
||
|
||
// 序号动态长度:<1000用3位,<10000用4位,>=10000用5位
|
||
let seqLen = 3;
|
||
if (sequence >= 1000 && sequence < 10000) seqLen = 4;
|
||
if (sequence >= 10000) seqLen = 5;
|
||
const receiving_number = `${prefix}${sequence.toString().padStart(seqLen, '0')}`;
|
||
// 3. 获取店铺名称(如果有货主)
|
||
let store_name = null;
|
||
if (store_id) {
|
||
const store = await app.model.StoreWarehouse.findOne({
|
||
where: {
|
||
store_id,
|
||
warehouse_id,
|
||
use_status: 1,
|
||
},
|
||
});
|
||
if (store) {
|
||
store_name = store.store_remask;
|
||
}
|
||
}
|
||
|
||
// 4. 创建收货单记录
|
||
const receivingData = {
|
||
receiving_number,
|
||
creator_id,
|
||
creator_snapshot: JSON.stringify(creator_snapshot),
|
||
status: status || 'receiving',
|
||
detail_status: 'unmatched',
|
||
storage_status: 'none',
|
||
delivery_method,
|
||
license_plate: delivery_method === 'truck' ? license_plate : null,
|
||
tracking_number: delivery_method !== 'truck' && delivery_method !== 'other' ? tracking_number : null,
|
||
loading_method,
|
||
video_device_id: video_device_id || null,
|
||
total_boxes: parseInt(total_boxes) || 0,
|
||
total_pallets: parseInt(total_pallets) || 0,
|
||
total_items: 0,
|
||
total_quantity: 0,
|
||
warehouse_id,
|
||
remark: remark || null,
|
||
store_name,
|
||
store_id: store_id || null,
|
||
receiving_start_time: new Date(),
|
||
is_deleted: false,
|
||
};
|
||
|
||
// 5. 保存到数据库
|
||
const result = await app.model.Receiving.create(receivingData);
|
||
|
||
return {
|
||
code: 200,
|
||
id: result.id,
|
||
receiving_number: result.receiving_number,
|
||
message: '收货任务创建成功',
|
||
};
|
||
|
||
} catch (error) {
|
||
ctx.logger.error('创建收货任务失败:', error);
|
||
return {
|
||
code: 0,
|
||
message: `创建失败: ${error.message}`,
|
||
};
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 查询单个收货单完整信息(含明细、图片)。
|
||
* @param {Object} data 请求体
|
||
* @param {number} data.id 收货单ID
|
||
* @return {Promise<Object>} 单据详情
|
||
*/
|
||
async get(data) {
|
||
const { id } = data;
|
||
const { ctx, app } = this;
|
||
const { Op } = app.Sequelize;
|
||
|
||
// 获取用户仓库ID,增加错误处理
|
||
const warehouseId = ctx.user?.store_id;
|
||
const creator_id = ctx.user.employees_id;
|
||
if (!warehouseId) {
|
||
return { code: 0, message: '用户未绑定仓库', data: {} };
|
||
}
|
||
|
||
try {
|
||
// 1. 查询收货单主表
|
||
const receiving = await app.model.Receiving.findOne({
|
||
where: {
|
||
id,
|
||
warehouse_id: warehouseId,
|
||
},
|
||
include: [{
|
||
model: ctx.model.StoreWarehouse,
|
||
as: 'store',
|
||
attributes: ['store_remask'],
|
||
where: {
|
||
use_status: 1,
|
||
warehouse_id: warehouseId,
|
||
},
|
||
required: false,
|
||
}, {
|
||
model: ctx.model.AccountStoreEmployee,
|
||
as: 'creator',
|
||
attributes: ['real_name'],
|
||
required: false,
|
||
}],
|
||
// 不需要order,因为根据id查询已经是唯一的
|
||
});
|
||
|
||
if (!receiving) {
|
||
return { code: 0, message: '无记录或无权访问', data: {} };
|
||
}
|
||
console.log('查询收货单明细');
|
||
// 2. 查询收货单明细
|
||
const receivingItems = await app.model.ReceivingDetail.findAll({
|
||
where: {
|
||
receiving_id: id,
|
||
},
|
||
include: [
|
||
{
|
||
model: ctx.model.LocationSpace,
|
||
as: 'receiving_space',
|
||
attributes: ['space_code', 'custom_barcode', 'custom_name'],
|
||
},
|
||
],
|
||
order: [['id', 'DESC']], // 保持倒序,最新在前
|
||
});
|
||
|
||
// 3. 获取明细ID数组
|
||
const receivingItemsIds = receivingItems.map(item => item.id);
|
||
|
||
// 4. 查询明细图片(如果明细数量大于0)
|
||
const itemImagesMap = {}; // 用于存储每个明细的图片
|
||
if (receivingItemsIds.length > 0) {
|
||
const receivingItemsImages = await ctx.model.FileReference.findAll({
|
||
where: {
|
||
business_type: 'receivingItem',
|
||
business_id: {
|
||
[Op.in]: receivingItemsIds,
|
||
},
|
||
},
|
||
include: [{
|
||
model: ctx.model.File,
|
||
as: 'file',
|
||
attributes: ['file_url'],
|
||
required: true,
|
||
}],
|
||
});
|
||
|
||
// 将图片按 business_id 分组
|
||
receivingItemsImages.forEach(itemImage => {
|
||
const businessId = itemImage.business_id;
|
||
if (!itemImagesMap[businessId]) {
|
||
itemImagesMap[businessId] = [];
|
||
}
|
||
itemImagesMap[businessId].push({
|
||
url: itemImage.file.file_url,
|
||
id: itemImage.file_id,
|
||
});
|
||
});
|
||
}
|
||
|
||
// 5. 将图片合并到对应的明细中
|
||
const items = receivingItems.map(item => {
|
||
const itemData = item.toJSON();
|
||
itemData.images = itemImagesMap[item.id] || []; // 获取该明细的图片,如果没有则为空数组
|
||
return itemData;
|
||
});
|
||
|
||
// 6. 查询主表的图片
|
||
const receivingImages = await ctx.model.FileReference.findAll({
|
||
where: {
|
||
business_type: 'receiving',
|
||
business_id: id,
|
||
},
|
||
include: [{
|
||
model: ctx.model.File,
|
||
as: 'file',
|
||
attributes: ['file_url'],
|
||
required: true,
|
||
}],
|
||
});
|
||
|
||
// 7. 组装返回数据
|
||
const result = {
|
||
...receiving.toJSON(), // 使用toJSON()确保获得纯对象
|
||
details: items, // 包含图片的明细数据
|
||
images: receivingImages.map(item => ({
|
||
url: item.file.file_url,
|
||
id: item.file_id,
|
||
})),
|
||
};
|
||
|
||
return { code: 200, message: '成功', data: result };
|
||
|
||
} catch (error) {
|
||
console.error('获取收货单详情失败:', error);
|
||
return { code: 500, message: '服务器错误', data: {} };
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 向收货单新增一条默认明细。
|
||
* @param {Object} data 请求体
|
||
* @param {number} data.receiving_id 收货单ID
|
||
* @return {Promise<Object>} 明细列表与默认选中ID
|
||
*/
|
||
async addDetail(data) {
|
||
const ctx = this.ctx;
|
||
const { receiving_id } = data;
|
||
|
||
// 获取当前用户信息
|
||
const creator_id = ctx.user.employees_id;
|
||
const warehouse_id = ctx.user.store_id;
|
||
// 验证收货单是否存在
|
||
const receiving = await ctx.model.Receiving.findOne({
|
||
where: { id: receiving_id, warehouse_id },
|
||
});
|
||
|
||
if (!receiving) {
|
||
return {
|
||
code: 404,
|
||
message: '收货单不存在',
|
||
};
|
||
}
|
||
|
||
// 验证收货单状态是否允许添加明细
|
||
if (receiving.status !== 'receiving') {
|
||
return {
|
||
code: 400,
|
||
message: '收货单状态不允许添加明细',
|
||
};
|
||
}
|
||
|
||
try {
|
||
// 创建默认的收货明细
|
||
const newDetail = await ctx.model.ReceivingDetail.create({
|
||
receiving_id,
|
||
product_name: '新商品',
|
||
barcode: '',
|
||
actual_quantity: 0,
|
||
box_quantity: 0,
|
||
boxes_per_pallet: 0,
|
||
pallet_quantity: 0,
|
||
receiving_status: 'pending',
|
||
storage_status: 'none',
|
||
stored_quantity: 0,
|
||
batch_number: '',
|
||
production_date: null,
|
||
expiry_date: null,
|
||
remark: '',
|
||
space_id: 1,
|
||
creator_id,
|
||
});
|
||
|
||
|
||
// 获取更新后的明细列表
|
||
const allDetails = await ctx.model.ReceivingDetail.findAll({
|
||
where: { receiving_id },
|
||
order: [['id', 'DESC']],
|
||
});
|
||
|
||
// 格式化返回数据
|
||
const formattedDetails = allDetails.map(detail => {
|
||
const detailData = detail.toJSON();
|
||
|
||
// 处理product_snapshot
|
||
if (detailData.product_snapshot) {
|
||
try {
|
||
detailData.product_snapshot = JSON.parse(detailData.product_snapshot);
|
||
} catch (e) {
|
||
detailData.product_snapshot = null;
|
||
}
|
||
}
|
||
|
||
// 如果有关联的系统商品,可以合并信息
|
||
if (detailData.system_product) {
|
||
detailData.system_product_info = detailData.system_product;
|
||
}
|
||
|
||
return detailData;
|
||
});
|
||
|
||
await this.updateReceivingStats(receiving_id);
|
||
return {
|
||
code: 200,
|
||
message: '添加成功',
|
||
data: {
|
||
details: formattedDetails,
|
||
selectId: newDetail.id,
|
||
},
|
||
};
|
||
|
||
} catch (error) {
|
||
ctx.logger.error('添加收货明细失败:', error);
|
||
return {
|
||
code: 500,
|
||
message: `添加失败: ${error.message}`,
|
||
};
|
||
}
|
||
}
|
||
|
||
async updateDetail(data) {
|
||
const ctx = this.ctx;
|
||
const { id, ...updateData } = data;
|
||
|
||
// 验证明细是否存在
|
||
const detail = await ctx.model.ReceivingDetail.findOne({
|
||
where: { id },
|
||
include: [
|
||
{
|
||
model: ctx.model.Receiving,
|
||
as: 'receiving',
|
||
attributes: ['id', 'status'],
|
||
},
|
||
],
|
||
});
|
||
|
||
if (!detail) {
|
||
return {
|
||
code: 404,
|
||
message: '明细不存在',
|
||
};
|
||
}
|
||
|
||
// 验证关联的收货单状态是否允许修改
|
||
if (detail.receiving && detail.receiving.status !== 'receiving') {
|
||
return {
|
||
code: 400,
|
||
message: '收货单状态不允许修改明细',
|
||
};
|
||
}
|
||
|
||
// 验证必填字段
|
||
if (updateData.product_name && !updateData.product_name.trim()) {
|
||
return {
|
||
code: 400,
|
||
message: '商品名称不能为空',
|
||
};
|
||
}
|
||
|
||
if (updateData.actual_quantity !== undefined && updateData.actual_quantity <= 0) {
|
||
return {
|
||
code: 400,
|
||
message: '实际数量必须大于0',
|
||
};
|
||
}
|
||
|
||
try {
|
||
// 如果需要处理商品匹配
|
||
if (updateData.barcode && updateData.barcode.trim()) {
|
||
// 尝试根据条码匹配系统商品
|
||
const systemProduct = await ctx.model.StockWarehouse.findOne({
|
||
where: { barcode: updateData.barcode },
|
||
});
|
||
|
||
if (systemProduct) {
|
||
updateData.system_product_id = systemProduct.id;
|
||
|
||
// 创建商品快照
|
||
updateData.product_snapshot = JSON.stringify({
|
||
name: systemProduct.name,
|
||
barcode: systemProduct.barcode,
|
||
spec: systemProduct.spec,
|
||
unit: systemProduct.unit,
|
||
images: systemProduct.images ? JSON.parse(systemProduct.images) : [],
|
||
});
|
||
|
||
// 如果用户没有输入商品名称,使用系统商品名称
|
||
if (!updateData.product_name) {
|
||
updateData.product_name = systemProduct.name;
|
||
}
|
||
}
|
||
}
|
||
|
||
// 处理数量类型的转换
|
||
if (updateData.actual_quantity !== undefined) {
|
||
updateData.actual_quantity = parseInt(updateData.actual_quantity) || 0;
|
||
}
|
||
|
||
if (updateData.box_quantity !== undefined) {
|
||
updateData.box_quantity = parseInt(updateData.box_quantity) || 0;
|
||
}
|
||
|
||
if (updateData.boxes_per_pallet !== undefined) {
|
||
updateData.boxes_per_pallet = parseInt(updateData.boxes_per_pallet) || 1;
|
||
}
|
||
|
||
if (updateData.pallet_quantity !== undefined) {
|
||
updateData.pallet_quantity = parseInt(updateData.pallet_quantity) || 0;
|
||
}
|
||
|
||
if (updateData.stored_quantity !== undefined) {
|
||
updateData.stored_quantity = parseInt(updateData.stored_quantity) || 0;
|
||
|
||
// 根据入库数量更新入库状态
|
||
if (updateData.stored_quantity >= updateData.actual_quantity) {
|
||
updateData.storage_status = 'all';
|
||
} else if (updateData.stored_quantity > 0) {
|
||
updateData.storage_status = 'partial';
|
||
} else {
|
||
updateData.storage_status = 'none';
|
||
}
|
||
}
|
||
|
||
// 更新明细
|
||
const [affectedRows] = await ctx.model.ReceivingDetail.update(updateData, {
|
||
where: { id },
|
||
});
|
||
|
||
if (affectedRows === 0) {
|
||
return {
|
||
code: 400,
|
||
message: '更新失败',
|
||
};
|
||
}
|
||
|
||
// 更新收货单统计信息
|
||
if (detail.receiving_id) {
|
||
await this.updateReceivingStats(detail.receiving_id);
|
||
}
|
||
|
||
// 获取更新后的明细
|
||
const updatedDetail = await ctx.model.ReceivingDetail.findOne({
|
||
where: { id },
|
||
include: [
|
||
{
|
||
model: ctx.model.StockWarehouse,
|
||
as: 'system_product',
|
||
attributes: ['id', 'name', 'barcode', 'spec', 'unit', 'images'],
|
||
},
|
||
],
|
||
});
|
||
|
||
// 格式化返回数据
|
||
const detailData = updatedDetail.toJSON();
|
||
|
||
if (detailData.product_snapshot) {
|
||
try {
|
||
detailData.product_snapshot = JSON.parse(detailData.product_snapshot);
|
||
} catch (e) {
|
||
detailData.product_snapshot = null;
|
||
}
|
||
}
|
||
|
||
if (detailData.system_product && detailData.system_product.images) {
|
||
try {
|
||
detailData.system_product.images = JSON.parse(detailData.system_product.images);
|
||
} catch (e) {
|
||
detailData.system_product.images = [];
|
||
}
|
||
}
|
||
|
||
return {
|
||
code: 200,
|
||
message: '更新成功',
|
||
data: detailData,
|
||
};
|
||
|
||
} catch (error) {
|
||
ctx.logger.error('更新收货明细失败:', error);
|
||
return {
|
||
code: 500,
|
||
message: `更新失败: ${error.message}`,
|
||
};
|
||
}
|
||
}
|
||
async getStockStoreInfo(stock_id) {
|
||
const ctx = this.ctx;
|
||
|
||
try {
|
||
// 方法1:通过 StockWarehouse 直接关联 StoreWarehouse
|
||
const stockWarehouse = await ctx.model.StockWarehouse.findOne({
|
||
where: { id: stock_id },
|
||
include: [
|
||
ctx.model.StoreWarehouse.buildStoreStockInclude({
|
||
warehouseId: ctx.user.store_id,
|
||
required: false,
|
||
attributes: [ 'store_id', 'store_remask' ],
|
||
}),
|
||
],
|
||
});
|
||
|
||
if (!stockWarehouse || !stockWarehouse.store_stock) {
|
||
return null;
|
||
}
|
||
|
||
// 直接返回 store_stock 的信息
|
||
return {
|
||
store_id: stockWarehouse.store_stock.store_id,
|
||
store_remask: stockWarehouse.store_stock.store_remask,
|
||
};
|
||
|
||
} catch (error) {
|
||
ctx.logger.error(`获取库存 ${stock_id} 的店铺信息失败:`, error);
|
||
// 根据需求决定是否抛出错误
|
||
// throw error;
|
||
return null;
|
||
}
|
||
}
|
||
// 更新收货单统计信息的辅助方法
|
||
async updateReceivingStats(receivingId) {
|
||
const { ctx, app } = this;
|
||
const { Op } = app.Sequelize;
|
||
const transaction = await ctx.model.transaction();
|
||
const warehouseId = ctx.user.store_id;
|
||
|
||
try {
|
||
// 1. 先查询收货单,并加锁
|
||
const receiving = await ctx.model.Receiving.findOne({
|
||
where: {
|
||
warehouse_id: warehouseId,
|
||
id: receivingId,
|
||
status: 'receiving',
|
||
},
|
||
lock: transaction.LOCK.UPDATE,
|
||
transaction,
|
||
});
|
||
|
||
if (!receiving) {
|
||
await transaction.rollback();
|
||
return;
|
||
}
|
||
|
||
// 2. 检查收货单是否已有 store_id(优先使用已有值)
|
||
let storeId = receiving.store_id;
|
||
let storeName = receiving.store_name;
|
||
|
||
// 如果收货单没有 store_id,尝试从已匹配的商品详情中获取
|
||
if (!storeId) {
|
||
// 查找第一个已匹配的商品详情(system_product_id 不为空)
|
||
const matchedDetail = await app.model.ReceivingDetail.findOne({
|
||
where: {
|
||
receiving_id: receivingId,
|
||
system_product_id: {
|
||
[Op.ne]: null,
|
||
},
|
||
},
|
||
transaction,
|
||
});
|
||
console.log('matchedDetail第一个有绑定的商品', matchedDetail);
|
||
if (matchedDetail && matchedDetail.system_product_id) {
|
||
try {
|
||
// 调用 getStockStoreInfo 获取库存信息
|
||
const storeInfo = await this.getStockStoreInfo(matchedDetail.system_product_id);
|
||
|
||
if (storeInfo && storeInfo.store_id) {
|
||
storeId = storeInfo.store_id;
|
||
// 注意:这里使用 store_remask 作为 store_name
|
||
storeName = storeInfo.store_remask; // 或者 storeInfo.store_remask
|
||
}
|
||
} catch (error) {
|
||
ctx.logger.warn(`获取商品 ${matchedDetail.system_product_id} 的库存信息失败:`, error);
|
||
// 继续执行,使用默认值
|
||
}
|
||
}
|
||
}
|
||
|
||
// 3. 统计该收货单的所有明细
|
||
const stats = await ctx.model.ReceivingDetail.findAll({
|
||
where: { receiving_id: receivingId },
|
||
attributes: [
|
||
[ctx.model.fn('COUNT', ctx.model.col('id')), 'total_items'],
|
||
[ctx.model.fn('SUM', ctx.model.col('actual_quantity')), 'total_quantity'],
|
||
],
|
||
raw: true,
|
||
transaction,
|
||
});
|
||
|
||
const stat = stats[0] || {};
|
||
|
||
// 4. 判断收货单的整体状态
|
||
const allDetails = await ctx.model.ReceivingDetail.findAll({
|
||
where: { receiving_id: receivingId },
|
||
transaction,
|
||
});
|
||
|
||
let detailStatus = 'unmatched';
|
||
|
||
if (allDetails.length > 0) {
|
||
const completedCount = allDetails.filter(d => !!d.system_product_id).length;
|
||
if (completedCount === allDetails.length) {
|
||
detailStatus = 'all_matched';
|
||
} else if (completedCount > 0) {
|
||
detailStatus = 'partial_matched';
|
||
}
|
||
}
|
||
|
||
// 5. 更新收货单
|
||
const updateData = {
|
||
total_items: parseInt(stat.total_items) || 0,
|
||
total_quantity: parseFloat(stat.total_quantity) || 0,
|
||
detail_status: detailStatus,
|
||
updated_at: new Date(),
|
||
};
|
||
|
||
// 只在有值且收货单当前没有这些值时更新 store 信息
|
||
if (storeId && !receiving.store_id) {
|
||
updateData.store_id = storeId;
|
||
updateData.store_name = storeName;
|
||
} else if (storeId && storeName && receiving.store_name !== storeName) {
|
||
// 如果 store_id 已有但 store_name 不同,也更新名称
|
||
updateData.store_name = storeName;
|
||
}
|
||
|
||
await ctx.model.Receiving.update(updateData, {
|
||
where: {
|
||
id: receivingId,
|
||
warehouse_id: warehouseId,
|
||
},
|
||
transaction,
|
||
});
|
||
|
||
// 6. 提交事务
|
||
await transaction.commit();
|
||
|
||
ctx.logger.info(`成功更新收货单 ${receivingId} 的统计信息`);
|
||
|
||
} catch (error) {
|
||
// 7. 发生错误时回滚事务
|
||
if (transaction) {
|
||
await transaction.rollback();
|
||
}
|
||
console.log(error);
|
||
ctx.logger.error('更新收货单统计失败:', error);
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 删除收货单明细并回算统计。
|
||
* @param {Object} data 请求体
|
||
* @param {number} data.detail_id 明细ID
|
||
* @return {Promise<Object>} 删除结果
|
||
*/
|
||
async deleteDetail(data) {
|
||
const ctx = this.ctx;
|
||
const { detail_id } = data;
|
||
const creator_id = ctx.user.employees_id;
|
||
const warehouse_id = ctx.user.store_id;
|
||
// 验证明细是否存在
|
||
const detail = await ctx.model.ReceivingDetail.findOne({
|
||
where: { id: detail_id, creator_id },
|
||
include: [
|
||
{
|
||
model: ctx.model.Receiving,
|
||
as: 'receiving',
|
||
attributes: ['id', 'status'],
|
||
where: {
|
||
warehouse_id,
|
||
},
|
||
required: true,
|
||
},
|
||
],
|
||
});
|
||
|
||
if (!detail) {
|
||
return {
|
||
code: 404,
|
||
message: '明细不存在',
|
||
};
|
||
}
|
||
|
||
// 验证关联的收货单状态是否允许删除
|
||
if (detail.receiving && detail.receiving.status !== 'receiving') {
|
||
return {
|
||
code: 400,
|
||
message: '收货单状态不允许删除明细',
|
||
};
|
||
}
|
||
|
||
// 检查是否已入库(已入库的明细不能删除)
|
||
if (detail.storage_status !== 'none' && detail.stored_quantity > 0) {
|
||
return {
|
||
code: 400,
|
||
message: '该明细已入库,不能删除',
|
||
};
|
||
}
|
||
|
||
try {
|
||
// 获取receiving_id用于后续更新统计
|
||
const receiving_id = detail.receiving_id;
|
||
|
||
// 删除明细
|
||
const deletedCount = await ctx.model.ReceivingDetail.destroy({
|
||
where: { id: detail_id },
|
||
});
|
||
|
||
if (deletedCount === 0) {
|
||
return {
|
||
code: 400,
|
||
message: '删除失败',
|
||
};
|
||
}
|
||
|
||
// 获取删除后的所有明细
|
||
const remainingDetails = await ctx.model.ReceivingDetail.findAll({
|
||
where: { receiving_id },
|
||
order: [['id', 'DESC']],
|
||
});
|
||
|
||
// 格式化返回数据
|
||
const formattedDetails = remainingDetails.map(detail => {
|
||
const detailData = detail.toJSON();
|
||
|
||
if (detailData.product_snapshot) {
|
||
try {
|
||
detailData.product_snapshot = JSON.parse(detailData.product_snapshot);
|
||
} catch (e) {
|
||
detailData.product_snapshot = null;
|
||
}
|
||
}
|
||
|
||
return detailData;
|
||
});
|
||
|
||
// 返回下一个选中的明细ID(如果有剩余明细)
|
||
let selectId = null;
|
||
if (remainingDetails.length > 0) {
|
||
// 默认选中第一个
|
||
selectId = remainingDetails[0].id;
|
||
}
|
||
await this.updateReceivingStats(receiving_id);
|
||
return {
|
||
code: 200,
|
||
message: '删除成功',
|
||
data: {
|
||
details: formattedDetails,
|
||
selectId,
|
||
},
|
||
};
|
||
|
||
} catch (error) {
|
||
ctx.logger.error('删除收货明细失败:', error);
|
||
return {
|
||
code: 500,
|
||
message: `删除失败: ${error.message}`,
|
||
};
|
||
}
|
||
}
|
||
/**
|
||
* 修改收货明细信息并触发库存/统计联动。
|
||
* @param {Object} data 请求体
|
||
* @return {Promise<Object>} 修改结果
|
||
*/
|
||
async detailChange(data) {
|
||
const { ctx, app } = this;
|
||
const warehouseId = ctx.user.store_id;
|
||
|
||
try {
|
||
// 1. 提取前端输入字段
|
||
const {
|
||
id, // 收货明细ID
|
||
receiving_id, // 收货单ID
|
||
actual_quantity, // 实际收货数量
|
||
batch_number, // 批次号
|
||
production_date, // 生产日期
|
||
expiry_date, // 到期日期
|
||
box_quantity, // 箱数
|
||
boxes_per_pallet, // 每托盘箱数
|
||
pallet_quantity, // 托盘数
|
||
space_id, // 存放库位ID
|
||
remark, // 备注
|
||
system_product_id, // 系统商品ID
|
||
barcode, // 条码
|
||
product_name, // 商品名称
|
||
box_width,
|
||
box_height,
|
||
box_length,
|
||
weight,
|
||
} = data;
|
||
console.log('barcode', barcode);
|
||
// 2. 验证必填字段
|
||
if (!id) {
|
||
return {
|
||
code: 400,
|
||
message: '收货明细ID不能为空',
|
||
};
|
||
}
|
||
|
||
if (!receiving_id) {
|
||
return {
|
||
code: 400,
|
||
message: '收货单ID不能为空',
|
||
};
|
||
}
|
||
|
||
|
||
// 3. 获取收货明细信息
|
||
const receivingDetail = await app.model.ReceivingDetail.findOne({
|
||
where: { id },
|
||
include: [
|
||
{
|
||
model: app.model.Receiving,
|
||
as: 'receiving',
|
||
attributes: ['id', 'warehouse_id', 'store_id', 'store_name'],
|
||
where: {
|
||
warehouse_id: warehouseId,
|
||
id: receiving_id,
|
||
status: 'receiving',
|
||
},
|
||
required: true,
|
||
},
|
||
],
|
||
});
|
||
|
||
if (!receivingDetail) {
|
||
return {
|
||
code: 404,
|
||
message: '收货明细不存在',
|
||
};
|
||
}
|
||
|
||
|
||
// 5. 验证箱规数据
|
||
if (box_quantity !== undefined && box_quantity < 0) {
|
||
return {
|
||
code: 400,
|
||
message: '箱数不能为负数',
|
||
};
|
||
}
|
||
|
||
if (pallet_quantity !== undefined && pallet_quantity < 0) {
|
||
return {
|
||
code: 400,
|
||
message: '托盘数不能为负数',
|
||
};
|
||
}
|
||
|
||
// 6. 准备更新数据
|
||
const updateData = {
|
||
actual_quantity,
|
||
remark: remark || '',
|
||
};
|
||
|
||
// 箱规相关字段
|
||
if (box_quantity !== undefined) updateData.box_quantity = box_quantity || 0;
|
||
if (boxes_per_pallet !== undefined) updateData.boxes_per_pallet = boxes_per_pallet || 0;
|
||
if (pallet_quantity !== undefined) updateData.pallet_quantity = pallet_quantity || 0;
|
||
if (barcode !== undefined) updateData.barcode = barcode || '';
|
||
|
||
if (box_length !== undefined) updateData.box_length = box_length || 0;
|
||
if (box_width !== undefined) updateData.box_width = box_width || 0;
|
||
if (box_height !== undefined) updateData.box_height = box_height || 0;
|
||
if (weight !== undefined) updateData.weight = weight || 0;
|
||
|
||
// 批次信息
|
||
if (batch_number !== undefined) updateData.batch_number = batch_number;
|
||
if (production_date !== undefined) updateData.production_date = production_date;
|
||
if (expiry_date !== undefined) updateData.expiry_date = expiry_date;
|
||
|
||
// 库位信息
|
||
if (space_id !== undefined) updateData.space_id = space_id;
|
||
|
||
// 7. 如果携带了系统商品ID,则更新商品相关信息
|
||
if (system_product_id) {
|
||
// 获取系统商品信息
|
||
const stockWarehouse = await app.model.StockWarehouse.findOne({
|
||
where: {
|
||
id: system_product_id,
|
||
warehouse_id: warehouseId,
|
||
},
|
||
include: [
|
||
app.model.StoreWarehouse.buildStoreStockInclude({
|
||
warehouseId,
|
||
required: false,
|
||
attributes: [ 'store_id', 'store_remask' ],
|
||
}),
|
||
{
|
||
model: app.model.StockBarcode,
|
||
as: 'barcodes',
|
||
attributes: ['barcode'],
|
||
required: false,
|
||
},
|
||
],
|
||
});
|
||
|
||
if (stockWarehouse) {
|
||
// 更新商品相关信息
|
||
updateData.system_product_id = system_product_id;
|
||
console.log('商品信息', stockWarehouse);
|
||
// 使用系统商品的条码(如果前端没有提供)
|
||
const barcodes = stockWarehouse.barcodes?.map(b => b.barcode) || [];
|
||
updateData.barcode = updateData.barcode || barcodes.join(';');
|
||
updateData.weight = updateData.weight || stockWarehouse.gross_weight;
|
||
if (stockWarehouse.enable_box_spec) {
|
||
updateData.boxes_per_pallet = updateData.boxes_per_pallet || stockWarehouse.quantity_per_box;
|
||
updateData.box_height = updateData.box_height || stockWarehouse.box_height;
|
||
updateData.box_width = updateData.box_width || stockWarehouse.box_width;
|
||
updateData.box_length = updateData.box_length || stockWarehouse.box_length;
|
||
}
|
||
// 使用系统商品的名称(如果前端没有提供)
|
||
updateData.product_name = stockWarehouse.item_name || product_name;
|
||
|
||
// 如果有货主信息,更新到产品快照中
|
||
if (stockWarehouse.store_stock) {
|
||
const productSnapshot = {
|
||
...(receivingDetail.product_snapshot ? JSON.parse(receivingDetail.product_snapshot) : {}),
|
||
store_id: stockWarehouse.store_stock.store_id,
|
||
store_name: stockWarehouse.store_stock.store_remask,
|
||
updated_at: new Date(),
|
||
};
|
||
updateData.product_snapshot = JSON.stringify(productSnapshot);
|
||
}
|
||
}
|
||
} else if (barcode !== undefined || product_name !== undefined) {
|
||
// 如果没有系统商品ID,但有条码或商品名称,也更新
|
||
if (barcode !== undefined) updateData.barcode = barcode;
|
||
if (product_name !== undefined) updateData.product_name = product_name;
|
||
updateData.system_product_id = null;
|
||
}
|
||
if (space_id) {
|
||
const sapce = await app.model.LocationSpace.findOne({
|
||
where: {
|
||
id: space_id,
|
||
[app.Sequelize.Op.or]: [
|
||
{ warehouse_id: warehouseId },
|
||
{ warehouse_id: null },
|
||
],
|
||
},
|
||
});
|
||
if (sapce) {
|
||
updateData.space_id = space_id;
|
||
}
|
||
}
|
||
console.log('更新收货明细', updateData);
|
||
// 8. 更新收货明细
|
||
await ctx.model.ReceivingDetail.update(updateData, {
|
||
where: { id },
|
||
});
|
||
console.log('更新收货明细2');
|
||
await this.updateReceivingStats(receiving_id);
|
||
// 9. 返回成功响应
|
||
return {
|
||
code: 200,
|
||
data: {
|
||
id: receivingDetail.id,
|
||
receiving_id: receivingDetail.receiving_id,
|
||
actual_quantity: receivingDetail.actual_quantity,
|
||
product_name: receivingDetail.product_name,
|
||
barcode: receivingDetail.barcode,
|
||
system_product_id: receivingDetail.system_product_id,
|
||
updated_at: receivingDetail.updated_at,
|
||
},
|
||
message: '修改成功',
|
||
};
|
||
|
||
} catch (error) {
|
||
ctx.logger.error('修改失败:', error);
|
||
return {
|
||
code: 500,
|
||
message: '修改失败,请稍后重试',
|
||
error: process.env.NODE_ENV === 'development' ? error.message : undefined,
|
||
};
|
||
}
|
||
}
|
||
async invalid(data) {
|
||
const { ctx, app } = this;
|
||
const warehouseId = ctx.user.store_id;
|
||
const { Op } = app.Sequelize;
|
||
const { id: receivingId, invalid_reason } = data;
|
||
|
||
const transaction = await ctx.model.transaction();
|
||
|
||
try {
|
||
// 1. 查询收货单并加锁
|
||
const receiving = await ctx.model.Receiving.findOne({
|
||
where: {
|
||
id: receivingId,
|
||
warehouse_id: warehouseId,
|
||
is_deleted: false,
|
||
},
|
||
lock: transaction.LOCK.UPDATE,
|
||
transaction,
|
||
include: [{
|
||
model: ctx.model.ReceivingDetail,
|
||
as: 'details',
|
||
required: false,
|
||
}],
|
||
});
|
||
|
||
if (!receiving) {
|
||
await transaction.rollback();
|
||
ctx.throw(404, '收货单不存在或已被删除');
|
||
}
|
||
|
||
// 2. 检查状态是否允许作废
|
||
if (receiving.status === 'cancelled') {
|
||
return {
|
||
code: 200,
|
||
success: true,
|
||
message: '收货单已作废,无需重复操作',
|
||
};
|
||
}
|
||
|
||
if (receiving.status === 'completed' && receiving.storage_status === 'all') {
|
||
await transaction.rollback();
|
||
ctx.throw(400, '已全部入库完成,无法作废');
|
||
}
|
||
|
||
// 3. 获取操作人信息
|
||
const operator = ctx.user;
|
||
|
||
// 4. 更新收货单状态为作废
|
||
await ctx.model.Receiving.update({
|
||
status: 'cancelled',
|
||
remark: invalid_reason ? `已作废: ${invalid_reason}` : (receiving.remark || '') + ' - 已作废',
|
||
updated_at: new Date(),
|
||
}, {
|
||
where: { id: receivingId },
|
||
transaction,
|
||
});
|
||
|
||
// 5. 处理已匹配的商品明细
|
||
if (receiving.details && receiving.details.length > 0) {
|
||
const matchedDetails = receiving.details.filter(detail => detail.system_product_id);
|
||
|
||
if (matchedDetails.length > 0) {
|
||
// 解除已匹配的商品关联
|
||
await ctx.model.ReceivingDetail.update({
|
||
system_product_id: null,
|
||
matched_at: null,
|
||
matched_by: null,
|
||
updated_at: new Date(),
|
||
}, {
|
||
where: {
|
||
receiving_id: receivingId,
|
||
system_product_id: { [Op.ne]: null },
|
||
},
|
||
transaction,
|
||
});
|
||
|
||
// 可以在这里处理库存的释放逻辑(如果需要)
|
||
// await this.releaseLockedStock(receivingId, transaction);
|
||
}
|
||
}
|
||
|
||
// 6. 处理关联的入库记录(如果有部分入库的情况)
|
||
if (receiving.storage_status === 'partial') {
|
||
// 将关联的入库记录状态也更新为作废
|
||
await ctx.model.Storage.update({
|
||
status: 'cancelled',
|
||
remark: `关联收货单${receiving.receiving_number}已作废`,
|
||
updated_at: new Date(),
|
||
}, {
|
||
where: {
|
||
receiving_id: receivingId,
|
||
status: { [Op.ne]: 'cancelled' },
|
||
},
|
||
transaction,
|
||
});
|
||
}
|
||
|
||
// 8. 提交事务
|
||
await transaction.commit();
|
||
|
||
|
||
return {
|
||
code: 200,
|
||
success: true,
|
||
message: '作废成功',
|
||
data: {
|
||
receiving_id: receivingId,
|
||
receiving_number: receiving.receiving_number,
|
||
previous_status: receiving.status,
|
||
invalidated_at: new Date(),
|
||
invalidated_by: operator.name,
|
||
invalid_reason,
|
||
},
|
||
};
|
||
|
||
} catch (error) {
|
||
console.log(error);
|
||
// 10. 回滚事务
|
||
if (transaction) {
|
||
await transaction.rollback();
|
||
}
|
||
|
||
ctx.logger.error(`作废收货单失败: ${error.message}`, {
|
||
receivingId,
|
||
warehouseId,
|
||
userId: ctx.user.id,
|
||
error: error.stack,
|
||
});
|
||
|
||
// 重新抛出错误,让上层处理
|
||
throw error;
|
||
}
|
||
}
|
||
/**
|
||
* 完成收货单:校验明细、更新状态并写入库存。
|
||
* @param {Object} data 请求体
|
||
* @param {number} data.id 收货单ID
|
||
* @param {string} [data.remark] 完成备注
|
||
* @return {Promise<Object>} 完成结果
|
||
*/
|
||
async completeReceiving(data) {
|
||
const { ctx, app } = this;
|
||
const warehouseId = ctx.user.store_id;
|
||
const { id, remark } = data;
|
||
const { Op } = app.Sequelize;
|
||
const transaction = await ctx.model.transaction();
|
||
|
||
try {
|
||
// 1. 查询收货单并加锁
|
||
const receiving = await ctx.model.Receiving.findOne({
|
||
where: {
|
||
id,
|
||
warehouse_id: warehouseId,
|
||
is_deleted: false,
|
||
},
|
||
lock: transaction.LOCK.UPDATE,
|
||
transaction,
|
||
include: [{
|
||
model: ctx.model.ReceivingDetail,
|
||
as: 'details',
|
||
required: false,
|
||
attributes: ['id', 'system_product_id', 'product_name', 'barcode', 'actual_quantity', 'weight'],
|
||
}],
|
||
});
|
||
|
||
if (!receiving) {
|
||
await transaction.rollback();
|
||
return {
|
||
code: 404,
|
||
message: '收货单不存在或已被删除',
|
||
};
|
||
}
|
||
|
||
// 2. 状态检查
|
||
if (receiving.status === 'completed') {
|
||
return {
|
||
code: 200,
|
||
message: '收货单已完成',
|
||
};
|
||
}
|
||
|
||
if (receiving.status === 'cancelled') {
|
||
await transaction.rollback();
|
||
return {
|
||
code: 400,
|
||
message: '已作废的收货单不可完成',
|
||
};
|
||
}
|
||
|
||
// 3. 检查是否有明细
|
||
if (!receiving.details || receiving.details.length === 0) {
|
||
await transaction.rollback();
|
||
return {
|
||
code: 400,
|
||
message: '收货单没有明细,请先添加商品',
|
||
};
|
||
}
|
||
|
||
// 4. 校验所有明细的完成条件
|
||
const invalidDetails = [];
|
||
const unmatchedDetails = receiving.details.filter(d => !d.system_product_id);
|
||
|
||
// 只有存在未绑定系统商品的明细时,才需要查询照片
|
||
|
||
const detailsIds = receiving.details.map(item => item.id);
|
||
const images = await ctx.model.FileReference.findAll({
|
||
where: {
|
||
business_type: 'receivingItem',
|
||
business_id: {
|
||
[Op.in]: detailsIds,
|
||
},
|
||
},
|
||
transaction,
|
||
});
|
||
|
||
// 按照业务ID分组照片
|
||
const imageMap = new Map();
|
||
images.forEach(image => {
|
||
const businessId = String(image.business_id).trim();
|
||
if (!imageMap.has(businessId)) {
|
||
imageMap.set(businessId, []);
|
||
}
|
||
imageMap.get(businessId).push(image);
|
||
});
|
||
|
||
console.log('imageMap', imageMap);
|
||
|
||
// 检查未绑定系统商品的明细
|
||
for (const detail of receiving.details) {
|
||
// 先检查是否有对应的图片数组
|
||
const businessId = String(detail.id).trim();
|
||
const imageArray = imageMap.get(businessId);
|
||
|
||
// 这里的关键修复:不仅要检查数组是否存在且有长度,还要检查数组中的元素是否有实际的数据
|
||
const hasPhoto = imageArray &&
|
||
imageArray.length > 0 &&
|
||
imageArray.some(img => {
|
||
// 检查图片对象是否有实际的数据
|
||
return img.dataValues ||
|
||
img.file_path ||
|
||
img.url ||
|
||
(img._options && Object.keys(img._options).length > 0);
|
||
});
|
||
const hasBarcode = !!detail.barcode && detail.barcode.trim() !== '';
|
||
const hasWeight = detail.weight > 0;
|
||
const hasCount = detail.actual_quantity > 0;
|
||
console.log('detailInfo', hasBarcode, hasWeight, hasCount);
|
||
|
||
if (!hasPhoto || !hasBarcode || !hasWeight || !hasCount) {
|
||
const itemName = detail.product_name || '未命名商品';
|
||
invalidDetails.push({
|
||
detail_id: detail.id,
|
||
item_name: itemName,
|
||
missing_fields: [
|
||
!hasPhoto && '照片',
|
||
!hasBarcode && '条码',
|
||
!hasWeight && '重量',
|
||
!hasCount && '数量',
|
||
].filter(Boolean),
|
||
});
|
||
}
|
||
}
|
||
|
||
// 5. 如果有不符合条件的明细,返回错误
|
||
if (invalidDetails.length > 0) {
|
||
await transaction.rollback();
|
||
|
||
const errorMsg = invalidDetails.length === 1
|
||
? `商品"${invalidDetails[0].item_name}"缺少${invalidDetails[0].missing_fields.join('、')}`
|
||
: `有${invalidDetails.length}个商品缺少必要信息`;
|
||
|
||
return {
|
||
success: false,
|
||
code: 'DETAIL_INCOMPLETE',
|
||
message: errorMsg,
|
||
data: {
|
||
invalid_details: invalidDetails,
|
||
total_details: receiving.details.length,
|
||
matched_details: receiving.details.filter(d => d.system_product_id).length,
|
||
unmatched_details: unmatchedDetails.length,
|
||
},
|
||
};
|
||
}
|
||
|
||
|
||
// 7. 获取操作人信息
|
||
const operator = ctx.user;
|
||
|
||
// 8. 更新收货单状态
|
||
const now = new Date();
|
||
const updateData = {
|
||
status: 'completed',
|
||
receiving_end_time: now,
|
||
updated_at: now,
|
||
};
|
||
|
||
// 更新备注
|
||
if (remark) {
|
||
const remarkPrefix = receiving.remark ? `${receiving.remark}\n` : '';
|
||
updateData.remark = `${remarkPrefix}【完成收货】${now.toLocaleString()} ${operator.employees_name} ${remark}`;
|
||
} else {
|
||
const remarkPrefix = receiving.remark ? `${receiving.remark}\n` : '';
|
||
updateData.remark = `${remarkPrefix}【完成收货】${now.toLocaleString()} ${operator.employees_name}`;
|
||
}
|
||
|
||
await ctx.model.Receiving.update(updateData, {
|
||
where: { id },
|
||
transaction,
|
||
});
|
||
|
||
// 9. 记录统计信息
|
||
const stats = {
|
||
total_details: receiving.details.length,
|
||
matched_details: receiving.details.filter(d => d.system_product_id).length,
|
||
unmatched_details: unmatchedDetails.length,
|
||
total_quantity: receiving.details.reduce((sum, d) => sum + (d.actual_quantity || 0), 0),
|
||
};
|
||
|
||
if (stats.matched_details > 0) {
|
||
// 通知
|
||
await ctx.service.systems.notification.send({
|
||
type: 'system',
|
||
title: `收货单${receiving.receiving_number}已完成`,
|
||
content: `收货单${receiving.receiving_number}已完成,匹配商品${stats.matched_details}件,未匹配商品${stats.unmatched_details}件。`,
|
||
bussinessType: 'receiving',
|
||
bussinessId: receiving.id,
|
||
});
|
||
}
|
||
|
||
// 11. 提交事务
|
||
await transaction.commit();
|
||
|
||
// 记录操作日志
|
||
ctx.logger.info('收货单已完成', {
|
||
receiving_id: id,
|
||
receiving_number: receiving.receiving_number,
|
||
completed_by: operator.employees_name,
|
||
stats,
|
||
});
|
||
|
||
return {
|
||
success: true,
|
||
message: '收货完成成功',
|
||
data: {
|
||
receiving_id: id,
|
||
receiving_number: receiving.receiving_number,
|
||
completed_at: now,
|
||
completed_by: operator.employees_name,
|
||
stats,
|
||
},
|
||
};
|
||
|
||
} catch (error) {
|
||
// 12. 回滚事务
|
||
if (transaction) {
|
||
await transaction.rollback();
|
||
}
|
||
|
||
ctx.logger.error(`完成收货失败: ${error.message}`, {
|
||
receiving_id: id,
|
||
warehouseId,
|
||
error: error.stack,
|
||
});
|
||
|
||
// 如果是已知的业务错误,返回具体信息
|
||
if (error.code && error.code.startsWith('DETAIL_')) {
|
||
return {
|
||
success: false,
|
||
code: error.code,
|
||
message: error.message,
|
||
};
|
||
}
|
||
|
||
// 其他错误
|
||
return {
|
||
success: false,
|
||
code: 'SYSTEM_ERROR',
|
||
message: error.message || '系统错误,请稍后重试',
|
||
};
|
||
}
|
||
}
|
||
}
|
||
|
||
module.exports = ReceivingService;
|