2690 lines
79 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'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 },
},
include: [{
model: ctx.model.File,
as: 'file',
attributes: ['file_url'],
required: true,
}],
});
// 将图片按明细ID分组,并转换为前端可直接使用的链接
for (const image of receivingItemsImages) {
if (!itemImagesMap[image.business_id]) {
itemImagesMap[image.business_id] = [];
}
itemImagesMap[image.business_id].push({
id: image.file_id,
url: image.file.file_url,
});
}
}
// 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,
},
include: [{
model: ctx.model.File,
as: 'file',
attributes: ['file_url'],
required: true,
}],
});
// 7. 组装返回数据
receiving.dataValues.details = items; // 包含图片链接的明细数据
receiving.dataValues.images = receivingImages.map(image => ({
id: image.file_id,
url: image.file.file_url,
})); // 包含主表图片链接
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;
}
}
buildReceivingPrefix(date = new Date()) {
const dateStr = Math.floor(date.getTime() / (1000 * 60 * 60 * 24));
return `R${dateStr}`;
}
async generateNextReceivingNumber(prefix) {
const { app } = this.ctx;
const suffixStartIndex = prefix.length + 1;
const maxReceiving = await app.model.Receiving.findOne({
attributes: [ 'receiving_number' ],
where: {
receiving_number: {
[app.Sequelize.Op.like]: `${prefix}%`,
},
},
order: [
[app.Sequelize.literal(`CAST(SUBSTRING(receiving_number, ${suffixStartIndex}) AS UNSIGNED)`), 'DESC'],
[ 'receiving_number', 'DESC' ],
],
});
let sequence = 1;
if (maxReceiving && maxReceiving.receiving_number) {
const lastNumStr = String(maxReceiving.receiving_number).slice(prefix.length);
const lastNum = Number.parseInt(lastNumStr, 10);
if (Number.isFinite(lastNum) && lastNum > 0) {
sequence = lastNum + 1;
}
}
const seqLen = Math.max(3, String(sequence).length);
return `${prefix}${String(sequence).padStart(seqLen, '0')}`;
}
isReceivingNumberDuplicateError(error) {
const parentCode = error && error.parent && error.parent.code;
const sqlMessage = String((error && error.parent && error.parent.sqlMessage) || error.message || '');
return parentCode === 'ER_DUP_ENTRY'
&& /uk_receiving_number|receiving_number/i.test(sqlMessage);
}
/**
* 创建收货单并生成收货单号。
* @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. 生成收货单号。注意:`wms_receiving.receiving_number` 在数据库中是全局唯一索引,
// 不能按 warehouse_id 各自从 001 开始,否则跨仓会撞号;并发创建时也需要重试兜底。
const now = new Date();
console.log('当前时间:', now);
const prefix = this.buildReceivingPrefix(now);
// 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 maxCreateRetries = 5;
let result = null;
let lastCreateError = null;
for (let attempt = 1; attempt <= maxCreateRetries; attempt++) {
const receiving_number = await this.generateNextReceivingNumber(prefix);
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,
};
try {
result = await app.model.Receiving.create(receivingData);
break;
} catch (error) {
lastCreateError = error;
if (this.isReceivingNumberDuplicateError(error) && attempt < maxCreateRetries) {
ctx.logger.warn(`[ReceivingCreateRetry] receiving_number 冲突,准备重试第 ${attempt + 1} 次`, {
prefix,
warehouse_id,
});
continue;
}
throw error;
}
}
if (!result) {
throw lastCreateError || new Error('创建收货任务失败');
}
return {
code: 200,
id: result.id,
receiving_number: result.receiving_number,
message: '收货任务创建成功',
};
} catch (error) {
ctx.logger.error('创建收货任务失败:', error);
return {
code: 0,
message: `创建失败: ${error.message}`,
};
}
}
/**
* 绑定收货单货主。
* 规则:
* 1. 已取消收货单禁止绑定;
* 2. 收货中/已完成状态下,若已存在货主,则禁止重复绑定;
* 3. 仅允许绑定与当前仓库存在有效签约关系的货主。
* @param {Object} data 请求体
* @param {number} data.id 收货单ID
* @param {number} data.store_id 货主ID
* @return {Promise<Object>} 绑定结果
*/
async bindStore(data) {
const { ctx } = this;
const { id, store_id } = data || {};
const warehouseId = Number(ctx.user && ctx.user.store_id);
const receivingId = Number(id || 0);
const storeId = Number(store_id || 0);
if (!warehouseId) {
return {
code: 400,
message: '用户未绑定仓库',
};
}
if (receivingId <= 0) {
return {
code: 400,
message: '收货单ID不能为空',
};
}
if (storeId <= 0) {
return {
code: 400,
message: '货主ID不能为空',
};
}
const transaction = await ctx.model.transaction();
try {
const receiving = await ctx.model.Receiving.findOne({
where: {
id: receivingId,
warehouse_id: warehouseId,
is_deleted: false,
},
lock: transaction.LOCK.UPDATE,
transaction,
});
if (!receiving) {
await transaction.rollback();
return {
code: 404,
message: '收货单不存在或无权访问',
};
}
if (receiving.status === 'cancelled') {
await transaction.rollback();
return {
code: 400,
message: '已取消的收货单不允许绑定货主',
};
}
if ([ 'receiving', 'completed' ].includes(receiving.status) && Number(receiving.store_id || 0) > 0) {
await transaction.rollback();
return {
code: 400,
message: '当前收货单已有货主,拒绝重复绑定',
};
}
const storeRelation = await ctx.model.StoreWarehouse.findOne({
where: {
warehouse_id: warehouseId,
store_id: storeId,
use_status: 1,
},
attributes: [ 'store_id', 'store_remask' ],
transaction,
});
if (!storeRelation) {
await transaction.rollback();
return {
code: 404,
message: '货主不存在或未与当前仓库建立有效签约关系',
};
}
const storeName = storeRelation.store_remask || null;
await ctx.model.Receiving.update({
store_id: storeId,
store_name: storeName,
updated_at: new Date(),
}, {
where: {
id: receivingId,
warehouse_id: warehouseId,
},
transaction,
});
await transaction.commit();
return {
code: 200,
message: '绑定货主成功',
data: {
id: receivingId,
store_id: storeId,
store_name: storeName,
status: receiving.status,
},
};
} catch (error) {
await transaction.rollback();
ctx.logger.error('绑定收货单货主失败:', error);
return {
code: 500,
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}`,
};
}
}
/**
* 绑定或改绑收货单明细的系统商品。
* @param {Object} data 请求体
* @param {number} data.detail_id 收货单明细ID(兼容 `id`)
* @param {number} data.system_product_id 商品ID
* @return {Promise<Object>} 绑定结果
*/
async bindDetailProduct(data) {
const { ctx, app } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id);
const detailId = Number((data && (data.detail_id || data.id)) || 0);
const systemProductId = Number((data && data.system_product_id) || 0);
if (!warehouseId) {
return {
code: 400,
message: '用户未绑定仓库',
};
}
if (detailId <= 0) {
return {
code: 400,
message: '收货单明细ID不能为空',
};
}
if (systemProductId <= 0) {
return {
code: 400,
message: '商品ID不能为空',
};
}
try {
const receivingDetail = await app.model.ReceivingDetail.findOne({
where: { id: detailId },
include: [
{
model: app.model.Receiving,
as: 'receiving',
attributes: [ 'id', 'warehouse_id', 'store_id', 'store_name', 'status' ],
where: {
warehouse_id: warehouseId,
},
required: true,
},
],
});
if (!receivingDetail) {
return {
code: 404,
message: '收货单明细不存在',
};
}
if (receivingDetail.receiving && receivingDetail.receiving.status !== 'receiving') {
return {
code: 400,
message: '收货单状态不允许绑定或改绑商品',
};
}
const stockWarehouse = await app.model.StockWarehouse.findOne({
where: {
id: systemProductId,
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) {
return {
code: 404,
message: '商品不存在或不属于当前仓库',
};
}
const productStoreId = Number(stockWarehouse.store_stock?.store_id || 0);
const barcodes = Array.isArray(stockWarehouse.barcodes)
? stockWarehouse.barcodes.map(item => item && item.barcode).filter(Boolean)
: [];
let productSnapshot = {};
if (receivingDetail.product_snapshot) {
try {
productSnapshot = JSON.parse(receivingDetail.product_snapshot) || {};
} catch {
productSnapshot = {};
}
}
const productName = stockWarehouse.item_name || stockWarehouse.name || receivingDetail.product_name || '未命名商品';
const updateData = {
system_product_id: systemProductId,
product_name: productName,
product_snapshot: JSON.stringify({
...productSnapshot,
system_product_id: systemProductId,
product_name: productName,
store_id: productStoreId || productSnapshot.store_id || null,
store_name: stockWarehouse.store_stock?.store_remask || productSnapshot.store_name || null,
updated_at: new Date(),
}),
};
if (barcodes.length > 0) {
updateData.barcode = barcodes.join(';');
}
if (stockWarehouse.gross_weight !== undefined && stockWarehouse.gross_weight !== null) {
updateData.weight = stockWarehouse.gross_weight;
}
if (stockWarehouse.enable_box_spec) {
updateData.boxes_per_pallet = stockWarehouse.quantity_per_box || receivingDetail.boxes_per_pallet || 0;
updateData.box_height = stockWarehouse.box_height || receivingDetail.box_height || 0;
updateData.box_width = stockWarehouse.box_width || receivingDetail.box_width || 0;
updateData.box_length = stockWarehouse.box_length || receivingDetail.box_length || 0;
}
await ctx.model.ReceivingDetail.update(updateData, {
where: { id: detailId },
});
await this.updateReceivingStats(receivingDetail.receiving_id);
return {
code: 200,
message: '绑定商品成功',
data: {
detail_id: detailId,
receiving_id: receivingDetail.receiving_id,
system_product_id: systemProductId,
product_name: productName,
},
};
} 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;
}
}
formatReportDate(value) {
if (!value) {
return '';
}
const date = value instanceof Date ? value : new Date(value);
if (Number.isNaN(date.getTime())) {
return '';
}
return date.toLocaleString('zh-CN', { hour12: false });
}
buildCompletionReportSheets({
receiving,
operator = {},
stats = {},
detailImageMap = new Map(),
receivingImages = [],
}) {
const details = Array.isArray(receiving && receiving.details)
? receiving.details.map(item => (typeof item.toJSON === 'function' ? item.toJSON() : item))
: [];
const mainImageUrls = (Array.isArray(receivingImages) ? receivingImages : [])
.map(item => (item && (item.url || item.file_url || (item.file && item.file.file_url))) || '')
.filter(Boolean);
const rows = [];
const embeddedImages = [];
const styledRows = [];
const summaryImageColumnIndex = 3;
const detailColumns = [
'序号', '商品名称', '条码',
'数量', '重量', '箱数', '托数',
'批次号', '生产日期', '到期日期', '备注', '图片链接', '图片',
];
const detailImageColumnIndex = detailColumns.length;
const maxDetailImageCount = Math.max(
1,
...details.map(detail => {
const detailImages = Array.isArray(detailImageMap.get(String(detail.id)))
? detailImageMap.get(String(detail.id))
: [];
const detailImageUrls = detailImages
.map(item => (item && (item.url || item.file_url || (item.file && item.file.file_url))) || '')
.filter(Boolean);
return detailImageUrls.length;
})
);
const buildLinkCell = urls => {
const normalizedUrls = (Array.isArray(urls) ? urls : [ urls ])
.map(item => String(item || '').trim())
.filter(Boolean);
if (normalizedUrls.length === 0) {
return '';
}
return {
text: normalizedUrls.join('\n'),
hyperlink: normalizedUrls[0],
tooltip: normalizedUrls.join('\n'),
};
};
const pushReportRow = (cells = [], options = {}) => {
rows.push(cells);
const rowIndex = rows.length;
const maxCol = Math.max(Number(options.toCol || cells.length || 1), 1);
if (options.style || options.height) {
styledRows.push({
row: rowIndex,
fromCol: Math.max(Number(options.fromCol || 1), 1),
toCol: maxCol,
style: options.style || null,
height: options.height || null,
});
}
return rowIndex;
};
pushReportRow([]);
[
[ '收货单ID', receiving && receiving.id ],
[ '收货单号', receiving && receiving.receiving_number ],
[ '状态', receiving && receiving.status ],
[ '货主', receiving && receiving.store_name ],
[ '仓库ID', receiving && receiving.warehouse_id ],
[ '来货方式', receiving && receiving.delivery_method ],
[ '车牌号', receiving && receiving.license_plate ],
[ '物流单号', receiving && receiving.tracking_number ],
[ '总明细数', stats.total_details || details.length ],
[ '已匹配明细数', stats.matched_details || 0 ],
[ '未匹配明细数', stats.unmatched_details || 0 ],
[ '总数量', stats.total_quantity || 0 ],
[ '总箱数', receiving && receiving.total_boxes ],
[ '总托盘数', receiving && receiving.total_pallets ],
[ '完成人', operator.employees_name || operator.real_name || operator.name || '' ],
[ '完成时间', this.formatReportDate(receiving && receiving.receiving_end_time) ],
[ '备注', receiving && receiving.remark ],
].forEach(([ field, value ]) => {
pushReportRow([ field, value ], {
toCol: 2,
style: {
alignment: { vertical: 'top', wrapText: true },
},
});
});
if (mainImageUrls.length === 0) {
pushReportRow([ '收货图片', '无' ], {
toCol: 2,
style: {
alignment: { vertical: 'top', wrapText: true },
},
});
} else {
const summaryLinkCell = buildLinkCell(mainImageUrls);
const imagePlaceholders = Array(Math.max(mainImageUrls.length, 1)).fill('');
const firstImageRowIndex = pushReportRow([ '收货图片', summaryLinkCell, ...imagePlaceholders ], {
toCol: 2 + imagePlaceholders.length,
height: 88,
style: {
alignment: { vertical: 'top', wrapText: true },
},
});
mainImageUrls.forEach((imageUrl, index) => {
embeddedImages.push({
row: firstImageRowIndex,
col: summaryImageColumnIndex + index,
url: imageUrl,
width: 96,
height: 96,
fallbackText: `收货图片${index + 1}`,
});
});
}
pushReportRow([]);
pushReportRow(detailColumns, {
toCol: detailColumns.length,
height: 22,
style: {
font: { bold: true, color: { argb: 'FF1F1F1F' } },
fill: {
type: 'pattern',
pattern: 'solid',
fgColor: { argb: 'FFD9EAF7' },
},
alignment: { horizontal: 'center', vertical: 'middle', wrapText: true },
},
});
if (details.length === 0) {
pushReportRow([ '', '', '无明细' ], {
toCol: detailColumns.length,
style: {
alignment: { vertical: 'top', wrapText: true },
},
});
} else {
details.forEach((detail, index) => {
const detailImages = Array.isArray(detailImageMap.get(String(detail.id)))
? detailImageMap.get(String(detail.id))
: [];
const detailImageUrls = detailImages
.map(item => (item && (item.url || item.file_url || (item.file && item.file.file_url))) || '')
.filter(Boolean);
const imageSlotCount = Math.max(detailImageUrls.length, 1);
const linkCell = buildLinkCell(detailImageUrls);
const rowCells = [
index + 1,
detail.product_name || '',
detail.barcode || '',
detail.actual_quantity || 0,
detail.weight || 0,
detail.box_quantity || 0,
detail.pallet_quantity || 0,
detail.batch_number || '',
this.formatReportDate(detail.production_date),
this.formatReportDate(detail.expiry_date),
detail.remark || '',
linkCell,
...Array(imageSlotCount).fill(''),
];
const targetRow = pushReportRow(rowCells, {
toCol: rowCells.length,
height: detailImageUrls.length > 0 ? 88 : null,
style: {
alignment: { vertical: 'top', wrapText: true },
},
});
detailImageUrls.forEach((imageUrl, imageIndex) => {
embeddedImages.push({
row: targetRow,
col: detailImageColumnIndex + imageIndex,
url: imageUrl,
width: 96,
height: 96,
fallbackText: `图片${imageIndex + 1}`,
});
});
});
}
return [
{
name: '收货清单',
rows,
widths: [
16, 28, 18, 10, 10, 10, 10, 18, 18, 18, 24, 42, 18,
...Array(Math.max(maxDetailImageCount - 1, 0)).fill(18),
],
embeddedImages,
styledRows,
skipHeader: true,
forceExcelJs: true,
},
];
}
async uploadCompletionExcelReport({
receiving,
operator = {},
stats = {},
detailImageMap = new Map(),
receivingImages = [],
}) {
const { ctx } = this;
const excelService = ctx && ctx.service && ctx.service.systems && ctx.service.systems.excel;
if (!receiving || !receiving.id || !excelService || typeof excelService.generateAndUpload !== 'function') {
return null;
}
const receivingNumber = String(receiving.receiving_number || receiving.id).replace(/[\\/:*?"<>|]/g, '_');
return await excelService.generateAndUpload({
filename: `收货完成_${receivingNumber}.xlsx`,
dir: `exports/receiving/completed/${ctx.user.store_id || receiving.warehouse_id || 'common'}`,
category: 'document',
saveRecord: true,
businessType: 'receivingReport',
businessId: receiving.id,
expireDays: 90,
sheets: this.buildCompletionReportSheets({
receiving,
operator,
stats,
detailImageMap,
receivingImages,
}),
});
}
/**
* 完成收货单:校验明细、更新状态并写入库存。
* @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',
'box_quantity', 'pallet_quantity', 'receiving_status', 'storage_status',
'batch_number', 'production_date', 'expiry_date', 'remark',
],
}],
});
if (!receiving) {
await transaction.rollback();
return {
code: 404,
message: '收货单不存在或已被删除',
};
}
// 2. 状态检查
if (receiving.status === 'completed') {
await transaction.rollback();
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,
},
},
include: [{
model: ctx.model.File,
as: 'file',
attributes: [ 'file_url' ],
required: false,
}],
transaction,
});
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({
id: image.file_id,
url: (image.file && image.file.file_url) || image.file_url || image.url || image.file_path || '',
});
});
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: false,
}],
transaction,
});
const receivingImageList = receivingImages
.map(image => ({
id: image.file_id,
url: (image.file && image.file.file_url) || image.file_url || image.url || '',
}))
.filter(item => item.url);
for (const detail of receiving.details) {
const businessId = String(detail.id).trim();
const imageArray = imageMap.get(businessId) || [];
const hasPhoto = imageArray.some(img => !!(img && img.url));
const hasBarcode = !!detail.barcode && detail.barcode.trim() !== '';
const hasWeight = Number(detail.weight || 0) > 0;
const hasCount = Number(detail.actual_quantity || 0) > 0;
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),
};
// 10. 提交事务
await transaction.commit();
const receivingSnapshot = {
...(typeof receiving.toJSON === 'function' ? receiving.toJSON() : receiving),
...updateData,
};
let completionReport = null;
try {
completionReport = await this.uploadCompletionExcelReport({
receiving: receivingSnapshot,
operator,
stats,
detailImageMap: imageMap,
receivingImages: receivingImageList,
});
} catch (reportError) {
ctx.logger.error(`收货完成报表上传失败: ${reportError.message}`, {
receiving_id: id,
warehouseId,
error: reportError.stack,
});
}
if (stats.matched_details > 0) {
try {
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,
});
} catch (notifyError) {
ctx.logger.error(`收货完成通知发送失败: ${notifyError.message}`, {
receiving_id: id,
warehouseId,
error: notifyError.stack,
});
}
}
ctx.logger.info('收货单已完成', {
receiving_id: id,
receiving_number: receiving.receiving_number,
completed_by: operator.employees_name,
stats,
completion_report: completionReport && completionReport.url,
});
return {
success: true,
code: 200,
message: '收货完成成功',
data: {
receiving_id: id,
receiving_number: receiving.receiving_number,
completed_at: now,
completed_by: operator.employees_name,
stats,
completion_report: completionReport ? {
fileKey: completionReport.fileKey || '',
url: completionReport.url || completionReport.cdnUrl || completionReport.cosUrl || '',
fileRecord: completionReport.fileRecord || null,
} : null,
},
};
} catch (error) {
if (transaction && !transaction.finished) {
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;