4193 lines
135 KiB
JavaScript
4193 lines
135 KiB
JavaScript
'use strict';
|
||
|
||
const Service = require('egg').Service;
|
||
const { parseWhereConditions } = require('../../../lib/query_condition_parser');
|
||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||
|
||
function getStartOfDayMs(value) {
|
||
const date = new Date(value);
|
||
if (Number.isNaN(date.getTime())) return null;
|
||
date.setHours(0, 0, 0, 0);
|
||
return date.getTime();
|
||
}
|
||
|
||
/**
|
||
* 判断到期日期是否早于当前日期。
|
||
* @param {string|Date|number} expiryDate 到期日期
|
||
* @param {Date} [currentDate=new Date()] 当前日期
|
||
* @return {boolean} 是否已过期
|
||
*/
|
||
function isExpiryDateBeforeToday(expiryDate, currentDate = new Date()) {
|
||
const expiryStartMs = getStartOfDayMs(expiryDate);
|
||
if (expiryStartMs === null) return false;
|
||
|
||
const currentStartMs = getStartOfDayMs(currentDate);
|
||
if (currentStartMs === null) return false;
|
||
|
||
return expiryStartMs < currentStartMs;
|
||
}
|
||
|
||
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,
|
||
} = 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,
|
||
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 => {
|
||
const detail = item.toJSON();
|
||
return {
|
||
...detail,
|
||
box_remainder: detail.box_remainder ?? 0,
|
||
box_weight: detail.box_weight ?? 0,
|
||
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: {} };
|
||
}
|
||
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 } });
|
||
|
||
// 批量记录操作日志
|
||
try {
|
||
const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog;
|
||
const payloads = ids.map(receivingId => ({
|
||
businessType: 'receiving',
|
||
businessId: receivingId,
|
||
operationCode: 'RECEIVING_BATCH_CANCEL',
|
||
operator: {
|
||
id: ctx.user?.employees_id || ctx.user?.id,
|
||
name: ctx.user?.employees_name || '',
|
||
},
|
||
extras: {
|
||
warehouseId: warehouse_id,
|
||
},
|
||
beforeChanges: null,
|
||
}));
|
||
|
||
if (operationLogService && typeof operationLogService.createOperationLogs === 'function') {
|
||
await operationLogService.createOperationLogs(payloads);
|
||
}
|
||
} catch (logErr) {
|
||
ctx.logger.warn('[receiving.batchCancelReceiving] 写入操作日志失败,不影响业务', logErr);
|
||
}
|
||
|
||
return { code: 200, message: '批量作废成功', data: {} };
|
||
|
||
} catch (error) {
|
||
console.error('批量作废收货单失败:', error);
|
||
return { code: 500, message: '服务器错误', data: {} };
|
||
}
|
||
}
|
||
/**
|
||
* 驳回收货单:将已完成收货单恢复为收货中,记录审核人信息与驳回理由。
|
||
* @param {Object} data 请求体
|
||
* @param {number[]} data.ids 收货单ID数组
|
||
* @param {string} [data.remark] 驳回理由(覆盖原备注)
|
||
* @return {Promise<Object>} 操作结果
|
||
*/
|
||
async rejectReceiving(data) {
|
||
const { ids, remark } = data;
|
||
const { ctx } = this;
|
||
const { Op } = ctx.model.Sequelize;
|
||
const warehouse_id = ctx.user.store_id;
|
||
|
||
if (!Array.isArray(ids) || ids.length === 0) {
|
||
return { code: 0, message: '收货单ID不能为空', data: {} };
|
||
}
|
||
|
||
const reviewerName = String(ctx.user?.employees_name || '').trim();
|
||
const reviewerEmployeeId = ctx.user?.employees_id || null;
|
||
|
||
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: {} };
|
||
}
|
||
|
||
const nonCompleted = receivings.find(r => r.status !== 'completed');
|
||
if (nonCompleted) {
|
||
return { code: 0, message: '只有状态为收货完成的收货单才能驳回', data: {} };
|
||
}
|
||
|
||
const alreadyReviewed = receivings.find(r => Number(r.is_review) === 1);
|
||
if (alreadyReviewed) {
|
||
return { code: 0, message: '存在已审核的收货单,无法驳回', data: {} };
|
||
}
|
||
|
||
const alreadyStored = receivings.find(r => r.storage_status === 'partial' || r.storage_status === 'all');
|
||
if (alreadyStored) {
|
||
return { code: 0, message: '存在已入库的收货单,无法驳回', data: {} };
|
||
}
|
||
|
||
const updateData = {
|
||
status: 'receiving',
|
||
reviewer_name: reviewerName || null,
|
||
reviewer_employee_id: reviewerEmployeeId || null,
|
||
};
|
||
if (remark !== undefined && remark !== null) {
|
||
updateData.remark = String(remark).trim() || null;
|
||
}
|
||
|
||
await ctx.model.Receiving.update(updateData, {
|
||
where: { id: { [Op.in]: ids }, warehouse_id },
|
||
});
|
||
|
||
try {
|
||
const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog;
|
||
const payloads = ids.map(receivingId => ({
|
||
businessType: 'receiving',
|
||
businessId: receivingId,
|
||
operationCode: 'RECEIVING_REJECT',
|
||
operator: {
|
||
id: reviewerEmployeeId || ctx.user?.id,
|
||
name: reviewerName,
|
||
},
|
||
extras: {
|
||
warehouseId: warehouse_id,
|
||
remark: updateData.remark || '',
|
||
},
|
||
beforeChanges: null,
|
||
}));
|
||
|
||
if (operationLogService && typeof operationLogService.createOperationLogs === 'function') {
|
||
await operationLogService.createOperationLogs(payloads);
|
||
}
|
||
} catch (logErr) {
|
||
ctx.logger.warn('[receiving.rejectReceiving] 写入操作日志失败,不影响业务', logErr);
|
||
}
|
||
|
||
// 发送驳回通知
|
||
try {
|
||
const rawNoticeService = ctx.service && ctx.service.systems && ctx.service.systems.notice;
|
||
const noticeService = rawNoticeService && typeof rawNoticeService.send === 'function'
|
||
? rawNoticeService
|
||
: (rawNoticeService && rawNoticeService.index && typeof rawNoticeService.index.send === 'function'
|
||
? rawNoticeService.index
|
||
: null);
|
||
|
||
const receivingSummaries = receivings.map(item => {
|
||
let creator = null;
|
||
const rawSnapshot = item && item.creator_snapshot;
|
||
if (rawSnapshot && typeof rawSnapshot === 'string') {
|
||
try {
|
||
creator = JSON.parse(rawSnapshot);
|
||
} catch (error) {
|
||
creator = null;
|
||
}
|
||
} else if (rawSnapshot && typeof rawSnapshot === 'object') {
|
||
creator = rawSnapshot;
|
||
}
|
||
|
||
return {
|
||
id: Number(item && item.id),
|
||
receiving_number: String(item && item.receiving_number || ''),
|
||
creator: creator ? {
|
||
id: creator.id || creator.employees_id || null,
|
||
employees_id: creator.employees_id || creator.id || null,
|
||
name: String(creator.name || creator.real_name || '').trim() || null,
|
||
} : null,
|
||
};
|
||
});
|
||
|
||
if (noticeService) {
|
||
await Promise.all(receivingSummaries.map(item => noticeService.send({
|
||
warehouseId: warehouse_id,
|
||
messageType: 'text',
|
||
businessName: 'receiving',
|
||
event: 'receiving_rejected',
|
||
title: `收货单 ${item.receiving_number || item.id} 已被驳回`,
|
||
content: [
|
||
`驳回人:${reviewerName || '未知'}`,
|
||
`驳回理由:${updateData.remark || '无'}`,
|
||
`收货单ID:${item.id || ''}`,
|
||
`收货单号:${item.receiving_number || '无'}`,
|
||
`收货创建人:${item.creator && item.creator.name || '无'}`,
|
||
'请及时处理重新提交完成收货。',
|
||
].join('\n') + '。',
|
||
businessId: item.id || ids[0],
|
||
subject: {
|
||
id: warehouse_id,
|
||
type: 'warehouse',
|
||
name: String((ctx.user && (ctx.user.store_name || ctx.user.company_name)) || ''),
|
||
},
|
||
sender: {
|
||
id: reviewerEmployeeId || ctx.user?.id || null,
|
||
name: reviewerName,
|
||
},
|
||
metadata: {
|
||
id: item.id || null,
|
||
ids: [ item.id || null ].filter(Boolean),
|
||
receiving_id: item.id || null,
|
||
receiving_ids: [ item.id || null ].filter(Boolean),
|
||
receiving_number: item.receiving_number || '',
|
||
receiving_numbers: item.receiving_number ? [ item.receiving_number ] : [],
|
||
receiving_creator: item.creator || null,
|
||
receiving_creators: item.creator ? [ item.creator ] : [],
|
||
receiving: item,
|
||
receivings: [ item ],
|
||
warehouseId: warehouse_id,
|
||
remark: updateData.remark || '',
|
||
},
|
||
})));
|
||
}
|
||
} catch (notifyErr) {
|
||
ctx.logger.warn('[receiving.rejectReceiving] 发送驳回通知失败,不影响业务', notifyErr);
|
||
}
|
||
|
||
return { code: 200, message: '驳回成功', data: { count: ids.length } };
|
||
} catch (error) {
|
||
ctx.logger.error('[receiving.rejectReceiving] 驳回收货单失败', error);
|
||
return { code: 500, message: '服务器错误', data: {} };
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 批量审核收货单:校验所有单据的状态后,用事务批量更新审核信息。
|
||
* 任意一张不符合条件则整批失败并回滚。
|
||
* @param {Object} data 请求体
|
||
* @param {number[]} data.ids 收货单ID数组
|
||
* @return {Promise<Object>} 操作结果
|
||
*/
|
||
async reviewReceiving(data) {
|
||
const { ids } = data;
|
||
const { ctx } = this;
|
||
const { Op } = ctx.model.Sequelize;
|
||
const warehouse_id = ctx.user.store_id;
|
||
|
||
if (!Array.isArray(ids) || ids.length === 0) {
|
||
return { code: 0, message: '收货单ID不能为空', data: {} };
|
||
}
|
||
|
||
const normalizedIds = Array.from(new Set(ids.map(Number).filter(n => Number.isFinite(n) && n > 0)));
|
||
if (normalizedIds.length === 0) {
|
||
return { code: 0, message: '收货单ID格式不正确', data: {} };
|
||
}
|
||
|
||
const reviewerName = String(ctx.user?.employees_name || '').trim() || null;
|
||
const reviewerEmployeeId = ctx.user?.employees_id || null;
|
||
|
||
const transaction = await ctx.model.transaction();
|
||
try {
|
||
// 加行锁查询,防止并发审核
|
||
const receivings = await ctx.model.Receiving.findAll({
|
||
where: { id: { [Op.in]: normalizedIds }, warehouse_id },
|
||
lock: transaction.LOCK.UPDATE,
|
||
transaction,
|
||
});
|
||
|
||
if (receivings.length !== normalizedIds.length) {
|
||
await transaction.rollback();
|
||
return { code: 0, message: '部分单据不存在或无权访问', data: {} };
|
||
}
|
||
|
||
// 逐条校验,收集所有不符合的收货单
|
||
const errors = [];
|
||
for (const r of receivings) {
|
||
if (r.status !== 'completed') {
|
||
errors.push(`收货单 ${r.receiving_number || r.id} 状态非收货完成`);
|
||
}
|
||
if (r.detail_status !== 'all_matched') {
|
||
errors.push(`收货单 ${r.receiving_number || r.id} 明细未全部匹配`);
|
||
}
|
||
if (r.storage_status !== 'none') {
|
||
errors.push(`收货单 ${r.receiving_number || r.id} 已存在入库记录`);
|
||
}
|
||
if (!r.store_id) {
|
||
errors.push(`收货单 ${r.receiving_number || r.id} 未绑定货主`);
|
||
}
|
||
if (Number(r.is_review) === 1) {
|
||
errors.push(`收货单 ${r.receiving_number || r.id} 已审核,无需重复操作`);
|
||
}
|
||
}
|
||
|
||
if (errors.length > 0) {
|
||
await transaction.rollback();
|
||
return { code: 0, message: errors.join(';'), data: {} };
|
||
}
|
||
|
||
// MySQL 二次状态核实:确保 WHERE 条件精准匹配,防止并发竞争
|
||
const updateResult = await ctx.model.Receiving.update(
|
||
{
|
||
is_review: 1,
|
||
reviewer_name: reviewerName,
|
||
reviewer_employee_id: reviewerEmployeeId,
|
||
},
|
||
{
|
||
where: {
|
||
id: { [Op.in]: normalizedIds },
|
||
warehouse_id,
|
||
[Op.or]: [
|
||
{ is_review: 0 },
|
||
{ is_review: null },
|
||
],
|
||
},
|
||
transaction,
|
||
}
|
||
);
|
||
|
||
const affectedRows = Array.isArray(updateResult)
|
||
? Number(updateResult[0] || 0)
|
||
: Number(updateResult || 0);
|
||
|
||
if (affectedRows !== normalizedIds.length) {
|
||
await transaction.rollback();
|
||
return { code: 0, message: '收货单审核状态已变化,请刷新后重试', data: {} };
|
||
}
|
||
|
||
// 写操作日志(失败不影响业务)
|
||
try {
|
||
const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog;
|
||
const payloads = normalizedIds.map(receivingId => ({
|
||
businessType: 'receiving',
|
||
businessId: receivingId,
|
||
operationCode: 'RECEIVING_REVIEW',
|
||
operator: {
|
||
id: reviewerEmployeeId || ctx.user?.id,
|
||
name: reviewerName || '',
|
||
},
|
||
extras: { warehouseId: warehouse_id },
|
||
beforeChanges: null,
|
||
transaction,
|
||
}));
|
||
|
||
if (operationLogService && typeof operationLogService.createOperationLogs === 'function') {
|
||
await operationLogService.createOperationLogs(payloads, { transaction });
|
||
}
|
||
} catch (logErr) {
|
||
ctx.logger.warn('[receiving.reviewReceiving] 写入操作日志失败,不影响业务', logErr);
|
||
}
|
||
|
||
await transaction.commit();
|
||
|
||
// 逐单发送审核完成通知(文字 + 文件,失败不影响业务)
|
||
const reviewer = {
|
||
employees_id: reviewerEmployeeId,
|
||
employees_name: reviewerName,
|
||
name: reviewerName,
|
||
id: reviewerEmployeeId,
|
||
};
|
||
|
||
for (const r of receivings) {
|
||
const receivingSnapshot = {
|
||
...(typeof r.toJSON === 'function' ? r.toJSON() : r),
|
||
is_review: 1,
|
||
reviewer_name: reviewerName,
|
||
reviewer_employee_id: reviewerEmployeeId,
|
||
updated_at: new Date(),
|
||
};
|
||
|
||
ctx.logger.info('[receiving.reviewReceiving] 开始处理单据通知', {
|
||
receiving_id: r.id,
|
||
receiving_number: r.receiving_number,
|
||
reviewer: reviewerName,
|
||
});
|
||
|
||
// 1. 发送文字通知
|
||
try {
|
||
const textResult = await this.sendReviewNotice({ receiving: receivingSnapshot, reviewer });
|
||
ctx.logger.info('[receiving.reviewReceiving] 文字通知结果', {
|
||
receiving_id: r.id,
|
||
receiving_number: r.receiving_number,
|
||
success: !!(textResult && textResult.success),
|
||
message: textResult && textResult.message,
|
||
matchedHookCount: Number(textResult && textResult.data && textResult.data.matchedHookCount || 0),
|
||
sentCount: Number(textResult && textResult.data && textResult.data.sentCount || 0),
|
||
failedCount: Number(textResult && textResult.data && textResult.data.failedCount || 0),
|
||
});
|
||
} catch (textErr) {
|
||
ctx.logger.error('[receiving.reviewReceiving] 文字通知发送失败', {
|
||
receiving_id: r.id,
|
||
error: textErr.message,
|
||
});
|
||
}
|
||
|
||
// 2. 加载明细与图片,生成 Excel 报表
|
||
let reviewReport = null;
|
||
try {
|
||
const details = await ctx.model.ReceivingDetail.findAll({
|
||
where: { receiving_id: r.id },
|
||
});
|
||
|
||
const detailIds = details.map(d => String(d.id));
|
||
const detailImageMap = new Map();
|
||
if (detailIds.length > 0) {
|
||
const detailImageRefs = await ctx.model.FileReference.findAll({
|
||
where: {
|
||
business_type: 'receivingItem',
|
||
business_id: { [Op.in]: detailIds },
|
||
},
|
||
include: [{ model: ctx.model.File, as: 'file', attributes: [ 'file_url' ], required: true }],
|
||
});
|
||
detailImageRefs.forEach(ref => {
|
||
const bid = String(ref.business_id);
|
||
if (!detailImageMap.has(bid)) detailImageMap.set(bid, []);
|
||
detailImageMap.get(bid).push(ref);
|
||
});
|
||
}
|
||
|
||
const receivingImages = await ctx.model.FileReference.findAll({
|
||
where: { business_type: 'receiving', business_id: r.id },
|
||
include: [{ model: ctx.model.File, as: 'file', attributes: [ 'file_url' ], required: true }],
|
||
});
|
||
|
||
const stats = {
|
||
total_details: details.length,
|
||
matched_details: details.filter(d => d.system_product_id).length,
|
||
unmatched_details: details.filter(d => !d.system_product_id).length,
|
||
total_quantity: details.reduce((sum, d) => sum + (d.actual_quantity || 0), 0),
|
||
};
|
||
|
||
const excelService = ctx.service && ctx.service.systems && ctx.service.systems.excel;
|
||
if (excelService && typeof excelService.generateAndUpload === 'function') {
|
||
const receivingNumber = String(r.receiving_number || r.id).replace(/[\\/:*?"<>|]/g, '_');
|
||
reviewReport = await excelService.generateAndUpload({
|
||
filename: `审核明细_${receivingNumber}.xlsx`,
|
||
dir: `exports/receiving/reviewed/${warehouse_id}`,
|
||
category: 'document',
|
||
saveRecord: true,
|
||
businessType: 'receivingReviewReport',
|
||
businessId: r.id,
|
||
expireDays: 90,
|
||
sheets: this.buildReviewReportSheets({
|
||
receiving: { ...receivingSnapshot, details },
|
||
reviewer,
|
||
stats,
|
||
detailImageMap,
|
||
receivingImages,
|
||
}),
|
||
});
|
||
}
|
||
|
||
ctx.logger.info('[receiving.reviewReceiving] Excel报表生成结果', {
|
||
receiving_id: r.id,
|
||
receiving_number: r.receiving_number,
|
||
success: !!reviewReport,
|
||
url: reviewReport && (reviewReport.url || reviewReport.cdnUrl || reviewReport.cosUrl || ''),
|
||
});
|
||
} catch (reportErr) {
|
||
ctx.logger.error('[receiving.reviewReceiving] Excel报表生成失败,跳过文件通知', {
|
||
receiving_id: r.id,
|
||
error: reportErr.message,
|
||
});
|
||
}
|
||
|
||
// 3. 发送文件通知(仅当 Excel 上传成功时)
|
||
if (reviewReport) {
|
||
try {
|
||
const fileResult = await this.sendReviewNotice({ receiving: receivingSnapshot, reviewer, reviewReport });
|
||
ctx.logger.info('[receiving.reviewReceiving] 文件通知结果', {
|
||
receiving_id: r.id,
|
||
receiving_number: r.receiving_number,
|
||
success: !!(fileResult && fileResult.success),
|
||
message: fileResult && fileResult.message,
|
||
matchedHookCount: Number(fileResult && fileResult.data && fileResult.data.matchedHookCount || 0),
|
||
sentCount: Number(fileResult && fileResult.data && fileResult.data.sentCount || 0),
|
||
failedCount: Number(fileResult && fileResult.data && fileResult.data.failedCount || 0),
|
||
reportUrl: reviewReport.url || reviewReport.cdnUrl || reviewReport.cosUrl || '',
|
||
});
|
||
} catch (fileErr) {
|
||
ctx.logger.error('[receiving.reviewReceiving] 文件通知发送失败', {
|
||
receiving_id: r.id,
|
||
error: fileErr.message,
|
||
});
|
||
}
|
||
}
|
||
|
||
ctx.logger.info('[receiving.reviewReceiving] 单据通知处理完成', {
|
||
receiving_id: r.id,
|
||
receiving_number: r.receiving_number,
|
||
hasReport: !!reviewReport,
|
||
});
|
||
}
|
||
|
||
return { code: 200, message: '审核成功', data: { count: normalizedIds.length } };
|
||
} catch (error) {
|
||
await transaction.rollback();
|
||
ctx.logger.error('[receiving.reviewReceiving] 审核收货单失败', error);
|
||
return { code: 500, message: `审核失败: ${error.message}`, data: {} };
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 构建审核完成 Excel 报表 sheets,复用收货完成报表结构,但标注"审核人"而非"完成人"。
|
||
* @param {Object} options 构建参数
|
||
* @param {Object} options.receiving 收货单(需含 details 数组)
|
||
* @param {Object} [options.reviewer={}] 审核人信息
|
||
* @param {Object} [options.stats={}] 明细统计
|
||
* @param {Map} [options.detailImageMap] 明细图片 Map(key=detail.id字符串)
|
||
* @param {Array} [options.receivingImages] 收货单主图片数组
|
||
* @return {Array} sheets 数组
|
||
*/
|
||
buildReviewReportSheets({
|
||
receiving,
|
||
reviewer = {},
|
||
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 imgs = Array.isArray(detailImageMap.get(String(detail.id)))
|
||
? detailImageMap.get(String(detail.id))
|
||
: [];
|
||
return imgs
|
||
.map(item => (item && (item.url || item.file_url || (item.file && item.file.file_url))) || '')
|
||
.filter(Boolean).length;
|
||
})
|
||
);
|
||
|
||
const buildLinkCell = urls => {
|
||
const normalized = (Array.isArray(urls) ? urls : [ urls ])
|
||
.map(item => String(item || '').trim())
|
||
.filter(Boolean);
|
||
if (normalized.length === 0) return '';
|
||
return { text: normalized.join('\n'), hyperlink: normalized[0], tooltip: normalized.join('\n') };
|
||
};
|
||
|
||
const pushRow = (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;
|
||
};
|
||
|
||
pushRow([]);
|
||
|
||
const reviewerName = reviewer.employees_name || reviewer.real_name || reviewer.name || '';
|
||
const reviewedAt = receiving.updated_at || new Date();
|
||
|
||
[
|
||
[ '收货单ID', receiving && receiving.id ],
|
||
[ '收货单号', receiving && receiving.receiving_number ],
|
||
[ '货主', receiving && receiving.store_name ],
|
||
[ '来货方式', this.formatDeliveryMethod(receiving && receiving.delivery_method) ],
|
||
...this.getCompletionContactFields(receiving),
|
||
[ '总明细数', 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 ],
|
||
[ '审核人', reviewerName ],
|
||
[ '审核时间', this.formatReportDate(reviewedAt) ],
|
||
[ '备注', receiving && receiving.remark ],
|
||
].forEach(([ field, value ]) => {
|
||
pushRow([ field, value ], {
|
||
toCol: 2,
|
||
style: { alignment: { vertical: 'top', wrapText: true } },
|
||
});
|
||
});
|
||
|
||
if (mainImageUrls.length === 0) {
|
||
pushRow([ '收货图片', '无' ], { toCol: 2, style: { alignment: { vertical: 'top', wrapText: true } } });
|
||
} else {
|
||
const summaryLinkCell = buildLinkCell(mainImageUrls);
|
||
const imagePlaceholders = Array(Math.max(mainImageUrls.length, 1)).fill('');
|
||
const firstImageRowIndex = pushRow([ '收货图片', 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}` });
|
||
});
|
||
}
|
||
|
||
pushRow([]);
|
||
pushRow(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) {
|
||
pushRow([ '', '', '无明细' ], { toCol: detailColumns.length, style: { alignment: { vertical: 'top', wrapText: true } } });
|
||
} else {
|
||
details.forEach((detail, index) => {
|
||
const imgs = Array.isArray(detailImageMap.get(String(detail.id)))
|
||
? detailImageMap.get(String(detail.id))
|
||
: [];
|
||
const imgUrls = imgs
|
||
.map(item => (item && (item.url || item.file_url || (item.file && item.file.file_url))) || '')
|
||
.filter(Boolean);
|
||
const imageSlotCount = Math.max(imgUrls.length, 1);
|
||
const linkCell = buildLinkCell(imgUrls);
|
||
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 = pushRow(rowCells, {
|
||
toCol: rowCells.length,
|
||
height: imgUrls.length > 0 ? 88 : null,
|
||
style: { alignment: { vertical: 'top', wrapText: true } },
|
||
});
|
||
imgUrls.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,
|
||
},
|
||
];
|
||
}
|
||
|
||
/**
|
||
* 发送审核完成通知(receiving_reviewed),支持文字/文件两种类型。
|
||
* @param {Object} options 发送参数
|
||
* @param {Object} options.receiving 收货单快照
|
||
* @param {Object} [options.reviewer={}] 审核人信息
|
||
* @param {Object|null} [options.reviewReport=null] 审核报表(有值则发文件通知)
|
||
* @return {Promise<Object|null>} 发送结果
|
||
*/
|
||
async sendReviewNotice({
|
||
receiving,
|
||
reviewer = {},
|
||
reviewReport = null,
|
||
} = {}) {
|
||
const { ctx } = this;
|
||
const rawNoticeService = ctx && ctx.service && ctx.service.systems && ctx.service.systems.notice;
|
||
const noticeService = rawNoticeService && typeof rawNoticeService.send === 'function'
|
||
? rawNoticeService
|
||
: (rawNoticeService && rawNoticeService.index && typeof rawNoticeService.index.send === 'function'
|
||
? rawNoticeService.index
|
||
: null);
|
||
|
||
if (!receiving || !receiving.id || !noticeService) return null;
|
||
|
||
const warehouseId = Number(receiving.warehouse_id || (ctx.user && ctx.user.store_id) || 0);
|
||
if (!Number.isFinite(warehouseId) || warehouseId <= 0) return null;
|
||
|
||
const storeId = Number(receiving.store_id || 0);
|
||
const reviewerName = String(reviewer.employees_name || reviewer.real_name || reviewer.name || '').trim();
|
||
const receivingNumber = String(receiving.receiving_number || receiving.id || '').trim();
|
||
const reportUrl = String(
|
||
(reviewReport && (reviewReport.url || reviewReport.cdnUrl || reviewReport.cosUrl || reviewReport.fileUrl)) || ''
|
||
).trim();
|
||
const reportFileName = String(
|
||
(reviewReport && (reviewReport.filename || reviewReport.fileKey || reviewReport.key)) || `审核明细_${receivingNumber}.xlsx`
|
||
).trim();
|
||
|
||
const content = [
|
||
`收货单号:${receivingNumber}`,
|
||
`货主:${receiving.store_name || '未知'}`,
|
||
`审核人:${reviewerName || '未知'}`,
|
||
`审核时间:${this.formatReportDate(receiving.updated_at || new Date())}`,
|
||
`备注:${receiving.remark || '无'}`,
|
||
].join('\n') + '。';
|
||
|
||
return await noticeService.send({
|
||
warehouseId,
|
||
storeId: Number.isFinite(storeId) && storeId > 0 ? storeId : undefined,
|
||
messageType: reportUrl ? 'file' : 'text',
|
||
businessName: 'receiving',
|
||
event: 'receiving_reviewed',
|
||
title: `收货单${receivingNumber}审核完成`,
|
||
content,
|
||
url: reportUrl || undefined,
|
||
fileName: reportUrl ? reportFileName : '',
|
||
mimeType: reportUrl ? 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' : '',
|
||
businessId: receiving.id,
|
||
subject: {
|
||
id: warehouseId,
|
||
type: 'warehouse',
|
||
name: String((ctx.user && (ctx.user.store_name || ctx.user.company_name)) || ''),
|
||
},
|
||
sender: {
|
||
id: reviewer.employees_id || reviewer.id || null,
|
||
name: reviewerName,
|
||
},
|
||
metadata: {
|
||
receivingId: receiving.id,
|
||
receivingNumber,
|
||
warehouseId,
|
||
reviewReport: reportUrl ? { fileKey: reviewReport.fileKey || '', url: reportUrl } : null,
|
||
},
|
||
});
|
||
}
|
||
|
||
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,
|
||
} = 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;
|
||
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;
|
||
}
|
||
}
|
||
|
||
buildReceivingNumberPrefix(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();
|
||
const prefix = this.buildReceivingNumberPrefix(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('创建收货任务失败');
|
||
}
|
||
|
||
// 记录操作日志
|
||
try {
|
||
await ctx.service.systems.operationLog.createOperationLog({
|
||
businessType: 'receiving',
|
||
businessId: result.id,
|
||
operationCode: 'RECEIVING_CREATE',
|
||
operator: {
|
||
id: ctx.user?.employees_id || ctx.user?.id,
|
||
name: ctx.user?.employees_name || '',
|
||
},
|
||
extras: {
|
||
warehouseId: warehouse_id,
|
||
},
|
||
beforeChanges: null,
|
||
});
|
||
} catch (logErr) {
|
||
ctx.logger.warn('[receiving.create] 写入操作日志失败,不影响业务', logErr);
|
||
}
|
||
|
||
return {
|
||
code: 200,
|
||
id: result.id,
|
||
receiving_number: result.receiving_number,
|
||
message: '收货任务创建成功',
|
||
};
|
||
|
||
} catch (error) {
|
||
ctx.logger.error('创建收货任务失败:', error);
|
||
return {
|
||
code: 0,
|
||
message: `创建失败: ${error.message}`,
|
||
};
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 按ID修改收货单基础信息。
|
||
* @param {Object} data 修改参数
|
||
* @param {number} data.id 收货单ID
|
||
* @return {Promise<Object>} 修改结果
|
||
*/
|
||
async save(data = {}) {
|
||
const {
|
||
id,
|
||
delivery_method,
|
||
license_plate,
|
||
loading_method,
|
||
remark,
|
||
status,
|
||
store_id,
|
||
total_boxes,
|
||
total_pallets,
|
||
tracking_number,
|
||
video_device_id,
|
||
} = data;
|
||
|
||
const { ctx } = this;
|
||
const warehouseId = Number(ctx.user && ctx.user.store_id);
|
||
const receivingId = Number(id || 0);
|
||
|
||
if (!warehouseId) {
|
||
return {
|
||
code: 400,
|
||
message: '用户未绑定仓库',
|
||
};
|
||
}
|
||
|
||
if (receivingId <= 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: '已取消的收货单不允许修改',
|
||
};
|
||
}
|
||
|
||
let storeName = receiving.store_name || null;
|
||
if (Object.prototype.hasOwnProperty.call(data, 'store_id')) {
|
||
const normalizedStoreId = Number(store_id || 0);
|
||
if (normalizedStoreId > 0) {
|
||
const storeRelation = await ctx.model.StoreWarehouse.findOne({
|
||
where: {
|
||
warehouse_id: warehouseId,
|
||
store_id: normalizedStoreId,
|
||
use_status: 1,
|
||
},
|
||
attributes: [ 'store_id', 'store_remask' ],
|
||
transaction,
|
||
});
|
||
|
||
if (!storeRelation) {
|
||
await transaction.rollback();
|
||
return {
|
||
code: 404,
|
||
message: '货主不存在或未与当前仓库建立有效签约关系',
|
||
};
|
||
}
|
||
|
||
storeName = storeRelation.store_remask || null;
|
||
} else {
|
||
storeName = null;
|
||
}
|
||
}
|
||
|
||
const updateData = {
|
||
updated_at: new Date(),
|
||
};
|
||
|
||
if (delivery_method !== undefined) {
|
||
updateData.delivery_method = delivery_method;
|
||
updateData.license_plate = delivery_method === 'truck'
|
||
? (license_plate === undefined ? (receiving.license_plate || null) : (license_plate || null))
|
||
: null;
|
||
updateData.tracking_number = delivery_method !== 'truck' && delivery_method !== 'other'
|
||
? (tracking_number === undefined ? (receiving.tracking_number || null) : (tracking_number || null))
|
||
: null;
|
||
} else {
|
||
if (license_plate !== undefined) {
|
||
updateData.license_plate = receiving.delivery_method === 'truck' ? (license_plate || null) : null;
|
||
}
|
||
if (tracking_number !== undefined) {
|
||
updateData.tracking_number = receiving.delivery_method !== 'truck' && receiving.delivery_method !== 'other'
|
||
? (tracking_number || null)
|
||
: null;
|
||
}
|
||
}
|
||
|
||
if (loading_method !== undefined) {
|
||
updateData.loading_method = loading_method;
|
||
}
|
||
if (remark !== undefined) {
|
||
updateData.remark = remark || null;
|
||
}
|
||
if (status !== undefined) {
|
||
updateData.status = status || 'receiving';
|
||
}
|
||
if (Object.prototype.hasOwnProperty.call(data, 'store_id')) {
|
||
updateData.store_id = Number(store_id || 0) > 0 ? Number(store_id) : null;
|
||
updateData.store_name = storeName;
|
||
}
|
||
if (total_boxes !== undefined) {
|
||
updateData.total_boxes = parseInt(total_boxes) || 0;
|
||
}
|
||
if (total_pallets !== undefined) {
|
||
updateData.total_pallets = parseInt(total_pallets) || 0;
|
||
}
|
||
if (video_device_id !== undefined) {
|
||
updateData.video_device_id = video_device_id || null;
|
||
}
|
||
|
||
await ctx.model.Receiving.update(updateData, {
|
||
where: {
|
||
id: receivingId,
|
||
warehouse_id: warehouseId,
|
||
},
|
||
transaction,
|
||
});
|
||
|
||
await transaction.commit();
|
||
|
||
try {
|
||
await ctx.service.systems.operationLog.createOperationLog({
|
||
businessType: 'receiving',
|
||
businessId: receivingId,
|
||
operationCode: 'RECEIVING_UPDATE',
|
||
operator: {
|
||
id: ctx.user?.employees_id || ctx.user?.id,
|
||
name: ctx.user?.employees_name || '',
|
||
},
|
||
extras: {
|
||
warehouseId,
|
||
},
|
||
beforeChanges: {
|
||
delivery_method: receiving.delivery_method,
|
||
license_plate: receiving.license_plate,
|
||
loading_method: receiving.loading_method,
|
||
remark: receiving.remark,
|
||
status: receiving.status,
|
||
store_id: receiving.store_id,
|
||
store_name: receiving.store_name,
|
||
total_boxes: receiving.total_boxes,
|
||
total_pallets: receiving.total_pallets,
|
||
tracking_number: receiving.tracking_number,
|
||
video_device_id: receiving.video_device_id,
|
||
},
|
||
});
|
||
} catch (logErr) {
|
||
ctx.logger.warn('[receiving.save] 写入操作日志失败,不影响业务', logErr);
|
||
}
|
||
|
||
return {
|
||
code: 200,
|
||
id: receivingId,
|
||
receiving_number: receiving.receiving_number,
|
||
message: '收货单修改成功',
|
||
};
|
||
} catch (error) {
|
||
await transaction.rollback();
|
||
ctx.logger.error('[receiving.save] 修改收货单失败', 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();
|
||
|
||
// 记录操作日志
|
||
try {
|
||
await ctx.service.systems.operationLog.createOperationLog({
|
||
businessType: 'receiving',
|
||
businessId: receivingId,
|
||
operationCode: 'RECEIVING_BIND_STORE',
|
||
operator: {
|
||
id: ctx.user?.employees_id || ctx.user?.id,
|
||
name: ctx.user?.employees_name || '',
|
||
},
|
||
extras: {
|
||
warehouseId,
|
||
},
|
||
beforeChanges: {
|
||
store_id: receiving.store_id,
|
||
store_name: receiving.store_name,
|
||
},
|
||
});
|
||
} catch (logErr) {
|
||
ctx.logger.warn('[receiving.bindStore] 写入操作日志失败,不影响业务', logErr);
|
||
}
|
||
|
||
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;
|
||
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: {} };
|
||
}
|
||
// 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();
|
||
return {
|
||
...itemData,
|
||
box_remainder: itemData.box_remainder ?? 0,
|
||
box_weight: itemData.box_weight ?? 0,
|
||
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. 组装返回数据
|
||
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);
|
||
|
||
// 记录操作日志
|
||
try {
|
||
await ctx.service.systems.operationLog.createOperationLog({
|
||
businessType: 'receiving',
|
||
businessId: receiving_id,
|
||
operationCode: 'RECEIVING_ADD_DETAIL',
|
||
operator: {
|
||
id: ctx.user?.employees_id || ctx.user?.id,
|
||
name: ctx.user?.employees_name || '',
|
||
},
|
||
extras: {
|
||
warehouseId: warehouse_id,
|
||
},
|
||
beforeChanges: {
|
||
detail_id: newDetail.id,
|
||
},
|
||
});
|
||
} catch (logErr) {
|
||
ctx.logger.warn('[receiving.addDetail] 写入操作日志失败,不影响业务', logErr);
|
||
}
|
||
|
||
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', 'is_review' ],
|
||
where: {
|
||
warehouse_id: warehouseId,
|
||
},
|
||
required: true,
|
||
},
|
||
],
|
||
});
|
||
|
||
if (!receivingDetail) {
|
||
return {
|
||
code: 404,
|
||
message: '收货单明细不存在',
|
||
};
|
||
}
|
||
|
||
if (Number(receivingDetail.receiving?.is_review) === 1) {
|
||
return {
|
||
code: 400,
|
||
message: '收货单已审核,禁止绑定或改绑商品',
|
||
};
|
||
}
|
||
|
||
if (String(receivingDetail.receiving?.status || '') === 'cancelled') {
|
||
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 receivingStoreId = Number(receivingDetail.receiving?.store_id || 0);
|
||
|
||
// 货主校验:收货单已有货主时,只允许绑定同一货主的商品
|
||
if (receivingStoreId > 0 && productStoreId > 0 && receivingStoreId !== productStoreId) {
|
||
return {
|
||
code: 400,
|
||
message: '该商品不属于当前收货单的货主,不允许绑定',
|
||
};
|
||
}
|
||
|
||
// 收货单无货主时,自动设置为当前商品的货主
|
||
let autoBindStore = false;
|
||
if (receivingStoreId <= 0 && productStoreId > 0) {
|
||
const storeName = stockWarehouse.store_stock?.store_remask || null;
|
||
await app.model.Receiving.update({
|
||
store_id: productStoreId,
|
||
store_name: storeName,
|
||
updated_at: new Date(),
|
||
}, {
|
||
where: { id: receivingDetail.receiving_id, warehouse_id: warehouseId },
|
||
});
|
||
autoBindStore = true;
|
||
}
|
||
|
||
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(),
|
||
}),
|
||
};
|
||
|
||
// 如果收货明细有条码且商品尚未包含该条码,则自动为商品新增条码
|
||
const detailBarcode = String(receivingDetail.barcode || '').trim();
|
||
if (detailBarcode && !barcodes.includes(detailBarcode)) {
|
||
try {
|
||
await app.model.StockBarcode.create({
|
||
stock_id: systemProductId,
|
||
warehouse_id: warehouseId,
|
||
barcode: detailBarcode,
|
||
});
|
||
barcodes.push(detailBarcode);
|
||
} catch (barcodeErr) {
|
||
// 唯一索引冲突说明条码已被其他商品占用,仅记录日志不阻断业务
|
||
ctx.logger.warn('[receiving.bindDetailProduct] 自动新增条码失败(可能已存在)', barcodeErr);
|
||
}
|
||
}
|
||
|
||
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);
|
||
|
||
// 记录操作日志
|
||
try {
|
||
await ctx.service.systems.operationLog.createOperationLog({
|
||
businessType: 'receiving',
|
||
businessId: receivingDetail.receiving_id,
|
||
operationCode: 'RECEIVING_BIND_PRODUCT',
|
||
operator: {
|
||
id: ctx.user?.employees_id || ctx.user?.id,
|
||
name: ctx.user?.employees_name || '',
|
||
},
|
||
extras: {
|
||
warehouseId,
|
||
},
|
||
beforeChanges: {
|
||
detail_id: detailId,
|
||
old_system_product_id: receivingDetail.system_product_id,
|
||
new_system_product_id: systemProductId,
|
||
},
|
||
});
|
||
} catch (logErr) {
|
||
ctx.logger.warn('[receiving.bindDetailProduct] 写入操作日志失败,不影响业务', logErr);
|
||
}
|
||
|
||
const responseData = {
|
||
detail_id: detailId,
|
||
receiving_id: receivingDetail.receiving_id,
|
||
system_product_id: systemProductId,
|
||
product_name: productName,
|
||
};
|
||
if (autoBindStore) {
|
||
responseData.auto_bind_store_id = productStoreId;
|
||
responseData.auto_bind_store_name = stockWarehouse.store_stock?.store_remask || null;
|
||
}
|
||
|
||
return {
|
||
code: 200,
|
||
message: autoBindStore ? '绑定商品成功,已自动设置货主' : '绑定商品成功',
|
||
data: responseData,
|
||
};
|
||
} 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: {
|
||
[Op.ne]: 'cancelled',
|
||
},
|
||
},
|
||
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,
|
||
});
|
||
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();
|
||
}
|
||
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);
|
||
|
||
// 记录操作日志
|
||
try {
|
||
await ctx.service.systems.operationLog.createOperationLog({
|
||
businessType: 'receiving',
|
||
businessId: receiving_id,
|
||
operationCode: 'RECEIVING_DELETE_DETAIL',
|
||
operator: {
|
||
id: ctx.user?.employees_id || ctx.user?.id,
|
||
name: ctx.user?.employees_name || '',
|
||
},
|
||
extras: {
|
||
warehouseId: warehouse_id,
|
||
},
|
||
beforeChanges: {
|
||
detail_id,
|
||
product_name: detail.product_name,
|
||
actual_quantity: detail.actual_quantity,
|
||
},
|
||
});
|
||
} catch (logErr) {
|
||
ctx.logger.warn('[receiving.deleteDetail] 写入操作日志失败,不影响业务', logErr);
|
||
}
|
||
|
||
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,
|
||
box_remainder, // 箱余数
|
||
box_weight, // 箱重量
|
||
} = data;
|
||
// 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: '收货明细不存在',
|
||
};
|
||
}
|
||
|
||
if (expiry_date && expiry_date !== undefined && isExpiryDateBeforeToday(expiry_date)) {
|
||
return {
|
||
code: 400,
|
||
message: '到期日期已过期,不能录入收货',
|
||
};
|
||
}
|
||
|
||
// 5. 验证箱规数据
|
||
if (box_quantity !== undefined && box_quantity < 0) {
|
||
return {
|
||
code: 400,
|
||
message: '箱数不能为负数',
|
||
};
|
||
}
|
||
|
||
if (pallet_quantity !== undefined && pallet_quantity < 0) {
|
||
return {
|
||
code: 400,
|
||
message: '托盘数不能为负数',
|
||
};
|
||
}
|
||
|
||
if (box_remainder !== undefined && box_remainder < 0) {
|
||
return {
|
||
code: 400,
|
||
message: '箱余数不能为负数',
|
||
};
|
||
}
|
||
|
||
if (box_weight !== undefined && box_weight < 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 (box_remainder !== undefined) updateData.box_remainder = box_remainder || 0;
|
||
if (box_weight !== undefined) updateData.box_weight = box_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;
|
||
// 使用系统商品的条码(如果前端没有提供)
|
||
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;
|
||
}
|
||
}
|
||
// 8. 更新收货明细
|
||
await ctx.model.ReceivingDetail.update(updateData, {
|
||
where: { id },
|
||
});
|
||
await this.updateReceivingStats(receiving_id);
|
||
|
||
// 记录操作日志
|
||
try {
|
||
await ctx.service.systems.operationLog.createOperationLog({
|
||
businessType: 'receiving',
|
||
businessId: receiving_id,
|
||
operationCode: 'RECEIVING_UPDATE_DETAIL',
|
||
operator: {
|
||
id: ctx.user?.employees_id || ctx.user?.id,
|
||
name: ctx.user?.employees_name || '',
|
||
},
|
||
extras: {
|
||
warehouseId,
|
||
},
|
||
beforeChanges: {
|
||
detail_id: id,
|
||
product_name: receivingDetail.product_name,
|
||
actual_quantity: receivingDetail.actual_quantity,
|
||
system_product_id: receivingDetail.system_product_id,
|
||
},
|
||
});
|
||
} catch (logErr) {
|
||
ctx.logger.warn('[receiving.detailChange] 写入操作日志失败,不影响业务', logErr);
|
||
}
|
||
|
||
// 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,
|
||
box_remainder: updateData.box_remainder !== undefined ? updateData.box_remainder : receivingDetail.box_remainder,
|
||
box_weight: updateData.box_weight !== undefined ? updateData.box_weight : receivingDetail.box_weight,
|
||
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();
|
||
|
||
// 记录操作日志
|
||
try {
|
||
await ctx.service.systems.operationLog.createOperationLog({
|
||
businessType: 'receiving',
|
||
businessId: receivingId,
|
||
operationCode: 'RECEIVING_CANCEL',
|
||
operator: {
|
||
id: ctx.user?.employees_id || ctx.user?.id,
|
||
name: ctx.user?.employees_name || '',
|
||
},
|
||
extras: {
|
||
warehouseId,
|
||
},
|
||
beforeChanges: {
|
||
previous_status: receiving.status,
|
||
invalid_reason,
|
||
},
|
||
});
|
||
} catch (logErr) {
|
||
ctx.logger.warn('[receiving.invalid] 写入操作日志失败,不影响业务', logErr);
|
||
}
|
||
|
||
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) {
|
||
// 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 });
|
||
}
|
||
|
||
formatDeliveryMethod(value) {
|
||
const methodMap = {
|
||
truck: '货车',
|
||
express: '快递',
|
||
air_freight: '空运',
|
||
sea_freight: '海运',
|
||
other: '其他',
|
||
};
|
||
|
||
const normalizedValue = String(value || '').trim();
|
||
return methodMap[normalizedValue] || normalizedValue;
|
||
}
|
||
|
||
/**
|
||
* 获取完成收货时需要展示的联系字段。
|
||
* @param {Object} receiving 收货单快照。
|
||
* @return {Array<Array>} 需要展示的联系字段列表。
|
||
*/
|
||
getCompletionContactFields(receiving) {
|
||
const deliveryMethod = String((receiving && receiving.delivery_method) || '').trim();
|
||
|
||
if (deliveryMethod === 'truck') {
|
||
return [[ '车牌号', receiving && receiving.license_plate ]];
|
||
}
|
||
|
||
if (deliveryMethod === 'express') {
|
||
return [[ '物流单号', receiving && receiving.tracking_number ]];
|
||
}
|
||
|
||
return [];
|
||
}
|
||
|
||
/**
|
||
* 生成收货完成报表的工作表数据。
|
||
* @param {Object} options 报表参数。
|
||
* @param {Object} options.receiving 收货单快照。
|
||
* @param {Object} [options.operator={}] 操作人信息。
|
||
* @param {Object} [options.stats={}] 收货统计数据。
|
||
* @param {Map} [options.detailImageMap=new Map()] 明细图片映射。
|
||
* @param {Array} [options.receivingImages=[]] 收货单图片列表。
|
||
* @return {Array<Object>} 工作表列表。
|
||
*/
|
||
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.store_name ],
|
||
[ '来货方式', this.formatDeliveryMethod(receiving && receiving.delivery_method) ],
|
||
...this.getCompletionContactFields(receiving),
|
||
[ '总明细数', 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,
|
||
}),
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 发送收货完成统一通知,通知外部订阅 `receiving_completed` 事件。
|
||
* @param {Object} options 通知参数
|
||
* @param {Object} options.receiving 收货单快照
|
||
* @param {Object} [options.operator={}] 操作人信息
|
||
* @param {Object} [options.stats={}] 收货统计
|
||
* @param {Object|null} [options.completionReport=null] 完成报表信息
|
||
* @return {Promise<Object|null>} 通知发送结果,若条件不满足则返回 null
|
||
*/
|
||
async sendCompletionNotice({
|
||
receiving,
|
||
operator = {},
|
||
stats = {},
|
||
completionReport = null,
|
||
} = {}) {
|
||
const { ctx } = this;
|
||
const rawNoticeService = ctx && ctx.service && ctx.service.systems && ctx.service.systems.notice;
|
||
const noticeService = rawNoticeService && typeof rawNoticeService.send === 'function'
|
||
? rawNoticeService
|
||
: (rawNoticeService && rawNoticeService.index && typeof rawNoticeService.index.send === 'function'
|
||
? rawNoticeService.index
|
||
: null);
|
||
|
||
if (!receiving || !receiving.id || !noticeService) {
|
||
return null;
|
||
}
|
||
|
||
const warehouseId = Number(receiving.warehouse_id || (ctx.user && ctx.user.store_id) || 0);
|
||
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
|
||
return null;
|
||
}
|
||
|
||
const storeId = Number(receiving.store_id || 0);
|
||
const matchedDetails = Number(stats.matched_details || 0);
|
||
const unmatchedDetails = Number(stats.unmatched_details || 0);
|
||
const totalQuantity = Number(stats.total_quantity || 0);
|
||
const operatorName = String(operator.employees_name || operator.real_name || operator.name || '').trim();
|
||
const receivingNumber = String(receiving.receiving_number || receiving.id || '').trim() || String(receiving.id);
|
||
const reportUrl = String(
|
||
(completionReport && (completionReport.url || completionReport.cdnUrl || completionReport.cosUrl || completionReport.fileUrl)) || ''
|
||
).trim();
|
||
const reportFileName = String(
|
||
(completionReport && (completionReport.filename || completionReport.fileKey || completionReport.key)) || `收货完成_${receivingNumber}.xlsx`
|
||
).trim();
|
||
const detailItems = Array.isArray(receiving.details) ? receiving.details : [];
|
||
const normalizedDetails = detailItems.map(item => ({
|
||
id: Number(item.id || 0),
|
||
product_name: item.product_name || '',
|
||
barcode: item.barcode || '',
|
||
actual_quantity: Number(item.actual_quantity || 0),
|
||
box_quantity: Number(item.box_quantity || 0),
|
||
pallet_quantity: Number(item.pallet_quantity || 0),
|
||
box_remainder: Number(item.box_remainder || 0),
|
||
box_weight: Number(item.box_weight || 0),
|
||
weight: Number(item.weight || 0),
|
||
}));
|
||
const totalBoxRemainder = normalizedDetails.reduce((sum, item) => sum + Number(item.box_remainder || 0), 0);
|
||
const totalBoxWeight = normalizedDetails.reduce((sum, item) => sum + Number(item.box_weight || 0), 0);
|
||
const title = `收货单${receivingNumber}已完成`;
|
||
const contactLines = this.getCompletionContactFields(receiving).map(([ field, value ]) => `${field}:${value || '无'}`);
|
||
const content = [
|
||
`收货单号:${receivingNumber} 已完成`,
|
||
`货主:${receiving.store_name || '未知'}`,
|
||
`来货方式:${this.formatDeliveryMethod(receiving.delivery_method) || '未知'}`,
|
||
...contactLines,
|
||
`总明细数:${Number(stats.total_details || 0)}件`,
|
||
`匹配商品:${matchedDetails}件`,
|
||
`未匹配商品:${unmatchedDetails}件`,
|
||
`总数量:${totalQuantity}`,
|
||
`总箱数:${receiving.total_boxes || 0}`,
|
||
`总箱余数:${totalBoxRemainder}`,
|
||
`总箱重:${totalBoxWeight}`,
|
||
`总托盘数:${receiving.total_pallets || 0}`,
|
||
operatorName ? `完成人:${operatorName}` : '',
|
||
`开始时间:${this.formatReportDate(receiving.created_at)}`,
|
||
`完成时间:${this.formatReportDate(receiving.receiving_end_time)}`,
|
||
`备注:${receiving.remark || '无'}`,
|
||
`快速查看:${ctx.app.config.frontendUrl || ''}/storage/receiving?id=${receivingNumber}`, // 替换为实际的前端地址
|
||
|
||
].filter(Boolean).join('\n') + '。';
|
||
|
||
return await noticeService.send({
|
||
warehouseId,
|
||
storeId: Number.isFinite(storeId) && storeId > 0 ? storeId : undefined,
|
||
messageType: reportUrl ? 'file' : 'text',
|
||
businessName: 'receiving',
|
||
event: 'receiving_completed',
|
||
title,
|
||
content,
|
||
url: reportUrl || undefined,
|
||
fileName: reportUrl ? reportFileName : '',
|
||
mimeType: reportUrl ? 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' : '',
|
||
businessId: receiving.id,
|
||
subject: {
|
||
id: warehouseId,
|
||
type: 'warehouse',
|
||
name: String((ctx.user && (ctx.user.store_name || ctx.user.company_name)) || ''),
|
||
},
|
||
sender: {
|
||
id: operator.employees_id || operator.id || null,
|
||
name: operatorName,
|
||
},
|
||
metadata: {
|
||
receivingId: receiving.id,
|
||
receivingNumber,
|
||
warehouseId,
|
||
storeId: Number.isFinite(storeId) && storeId > 0 ? storeId : null,
|
||
stats: {
|
||
total_details: Number(stats.total_details || 0),
|
||
matched_details: matchedDetails,
|
||
unmatched_details: unmatchedDetails,
|
||
total_quantity: totalQuantity,
|
||
},
|
||
details: normalizedDetails,
|
||
boxSummary: {
|
||
total_box_remainder: totalBoxRemainder,
|
||
total_box_weight: totalBoxWeight,
|
||
},
|
||
completionReport: completionReport ? {
|
||
fileKey: completionReport.fileKey || completionReport.key || '',
|
||
url: reportUrl,
|
||
} : null,
|
||
},
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 完成收货单:校验明细、更新状态并写入库存。
|
||
* @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', 'box_remainder', 'box_weight',
|
||
'receiving_status', 'storage_status',
|
||
'batch_number', 'production_date', 'expiry_date', 'remark',
|
||
],
|
||
include: [{
|
||
model: ctx.model.StockWarehouse,
|
||
as: 'system_product',
|
||
required: false,
|
||
attributes: [
|
||
'id',
|
||
'item_name',
|
||
'item_code',
|
||
'is_batch_mgmt',
|
||
'is_shelf_life_mgmt',
|
||
'inbound_min_days',
|
||
'shelf_life_days',
|
||
'remaining_threshold_days',
|
||
],
|
||
}],
|
||
}],
|
||
});
|
||
|
||
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. 校验明细数量:不允许存在数量为 0 的明细
|
||
const zeroQuantityDetails = receiving.details.filter(d => Number(d.actual_quantity || 0) <= 0);
|
||
if (zeroQuantityDetails.length > 0) {
|
||
await transaction.rollback();
|
||
const errorMsg = zeroQuantityDetails.length === 1
|
||
? `商品“${zeroQuantityDetails[0].product_name || '未命名商品'}”的数量为0,请填写实际收货数量`
|
||
: `有${zeroQuantityDetails.length}个商品数量为0,请填写实际收货数量`;
|
||
return {
|
||
success: false,
|
||
code: 'DETAIL_QUANTITY_ZERO',
|
||
message: errorMsg,
|
||
data: {
|
||
invalid_details: zeroQuantityDetails.map(d => ({
|
||
detail_id: d.id,
|
||
item_name: d.product_name || '未命名商品',
|
||
actual_quantity: Number(d.actual_quantity || 0),
|
||
})),
|
||
},
|
||
};
|
||
}
|
||
|
||
const batchManagedDetails = receiving.details.filter(detail => detail.system_product && detail.system_product.is_batch_mgmt === 'Y');
|
||
const missingBatchNumberDetails = batchManagedDetails.filter(detail => !String(detail.batch_number || '').trim());
|
||
|
||
if (missingBatchNumberDetails.length > 0) {
|
||
await transaction.rollback();
|
||
return {
|
||
success: false,
|
||
code: 'BATCH_NUMBER_REQUIRED',
|
||
message: '批次管理商品必须填写批次号',
|
||
data: {
|
||
invalid_details: missingBatchNumberDetails.map(detail => ({
|
||
detail_id: detail.id,
|
||
item_name: detail.product_name || detail.system_product?.item_name || '未命名商品',
|
||
batch_number: detail.batch_number || '',
|
||
production_date: detail.production_date || null,
|
||
expiry_date: detail.expiry_date || null,
|
||
})),
|
||
},
|
||
};
|
||
}
|
||
|
||
const missingBatchDetails = batchManagedDetails.filter(detail => !detail.production_date || !detail.expiry_date);
|
||
|
||
if (missingBatchDetails.length > 0) {
|
||
await transaction.rollback();
|
||
return {
|
||
success: false,
|
||
code: 'PRODUCTION_DATE_REQUIRED',
|
||
message: '批次管理商品必须填写生产日期和有效期',
|
||
data: {
|
||
invalid_details: missingBatchDetails.map(detail => ({
|
||
detail_id: detail.id,
|
||
item_name: detail.product_name || detail.system_product?.item_name || '未命名商品',
|
||
batch_number: detail.batch_number || '',
|
||
production_date: detail.production_date || null,
|
||
expiry_date: detail.expiry_date || null,
|
||
})),
|
||
},
|
||
};
|
||
}
|
||
|
||
const todayStartMs = getStartOfDayMs(new Date());
|
||
const invalidExpiryDetails = batchManagedDetails.filter(detail => {
|
||
const minReceiveDays = Number(detail.system_product?.inbound_min_days) || 0;
|
||
if (minReceiveDays <= 0) return false;
|
||
|
||
const expiryTime = new Date(detail.expiry_date).getTime();
|
||
if (Number.isNaN(expiryTime)) return false;
|
||
|
||
return (expiryTime - (minReceiveDays * DAY_MS)) < todayStartMs;
|
||
});
|
||
|
||
if (invalidExpiryDetails.length > 0) {
|
||
await transaction.rollback();
|
||
const firstInvalid = invalidExpiryDetails[0];
|
||
const minReceiveDays = Number(firstInvalid.system_product?.inbound_min_days) || 0;
|
||
|
||
return {
|
||
success: false,
|
||
code: 'EXPIRY_DATE_TOO_SOON',
|
||
message: `商品“${firstInvalid.product_name || firstInvalid.system_product?.item_name || '未命名商品'}”的有效期不足最小允许收货天数(${minReceiveDays}天),无法完成收货`,
|
||
data: {
|
||
invalid_details: invalidExpiryDetails.map(detail => ({
|
||
detail_id: detail.id,
|
||
item_name: detail.product_name || detail.system_product?.item_name || '未命名商品',
|
||
batch_number: detail.batch_number || '',
|
||
production_date: detail.production_date || null,
|
||
expiry_date: detail.expiry_date || null,
|
||
inbound_min_days: Number(detail.system_product?.inbound_min_days) || 0,
|
||
})),
|
||
},
|
||
};
|
||
}
|
||
|
||
// 5. 准备明细图片与统计信息(照片/条码/重量不再强制要求)
|
||
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,
|
||
},
|
||
warehouse_id: warehouseId,
|
||
},
|
||
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 || '',
|
||
});
|
||
});
|
||
|
||
// 5. 获取操作人信息
|
||
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();
|
||
|
||
// 记录操作日志
|
||
try {
|
||
await ctx.service.systems.operationLog.createOperationLog({
|
||
businessType: 'receiving',
|
||
businessId: id,
|
||
operationCode: 'RECEIVING_COMPLETE',
|
||
operator: {
|
||
id: ctx.user?.employees_id || ctx.user?.id,
|
||
name: ctx.user?.employees_name || '',
|
||
},
|
||
extras: {
|
||
warehouseId,
|
||
},
|
||
beforeChanges: {
|
||
previous_status: receiving.status,
|
||
stats,
|
||
},
|
||
});
|
||
} catch (logErr) {
|
||
ctx.logger.warn('[receiving.completeReceiving] 写入操作日志失败,不影响业务', logErr);
|
||
}
|
||
|
||
const receivingSnapshot = {
|
||
...(typeof receiving.toJSON === 'function' ? receiving.toJSON() : receiving),
|
||
...updateData,
|
||
};
|
||
|
||
const completionNoticePayload = {
|
||
receiving: receivingSnapshot,
|
||
operator,
|
||
stats,
|
||
};
|
||
|
||
// 11. 收货成功后先触发文字通知,再生成 Excel;若 Excel 成功,再补发文件通知。
|
||
try {
|
||
const textNoticeResult = await this.sendCompletionNotice(completionNoticePayload);
|
||
ctx.logger.info('收货完成文字通知结果', {
|
||
receiving_id: id,
|
||
receiving_number: receiving.receiving_number,
|
||
warehouseId,
|
||
success: !!(textNoticeResult && textNoticeResult.success),
|
||
message: textNoticeResult && textNoticeResult.message,
|
||
matchedHookCount: Number(textNoticeResult && textNoticeResult.data && textNoticeResult.data.matchedHookCount || 0),
|
||
sentCount: Number(textNoticeResult && textNoticeResult.data && textNoticeResult.data.sentCount || 0),
|
||
failedCount: Number(textNoticeResult && textNoticeResult.data && textNoticeResult.data.failedCount || 0),
|
||
});
|
||
} 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,
|
||
});
|
||
|
||
// 异步补全商品图片与毛重,不阻塞主进程
|
||
this._syncProductDataFromReceiving({
|
||
receivingId: id,
|
||
warehouseId,
|
||
details: receiving.details,
|
||
}).catch(err => {
|
||
ctx.logger.warn('[receiving._syncProductDataFromReceiving] 异步补全失败,不影响业务', err.message);
|
||
});
|
||
|
||
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: 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 || '系统错误,请稍后重试',
|
||
};
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 收货完成后异步补全商品资料:绑定图片、补填毛重。
|
||
*
|
||
* 遍历当前收货单所有已绑定系统商品的明细:
|
||
* 1. 若商品 is_images === 'N' 且该明细有收货图片,则将收货图片复制为商品图片(FileReference),
|
||
* 并将商品的 is_images 更新为 'Y'。
|
||
* 2. 若商品 gross_weight 为 0 或 null,且明细的 weight > 0,则将商品毛重更新为该明细的 weight。
|
||
*
|
||
* 本方法通过 setImmediate 调用,运行在事务提交后,任何异常只记录日志,不影响主进程。
|
||
*
|
||
* @param {Object} options 参数对象
|
||
* @param {number} options.receivingId 收货单 ID
|
||
* @param {number} options.warehouseId 仓库 ID
|
||
* @param {Array} options.details 收货明细数组(来自 completeReceiving 中已加载的 details)
|
||
* @return {Promise<void>}
|
||
*/
|
||
async _syncProductDataFromReceiving({ receivingId, warehouseId, details }) {
|
||
console.log('_syncProductDataFromReceiving异步执行中...'); // 调试日志
|
||
const { ctx, app } = this;
|
||
|
||
// 只处理已绑定系统商品的明细
|
||
const boundDetails = (Array.isArray(details) ? details : []).filter(
|
||
d => d && Number(d.system_product_id) > 0
|
||
);
|
||
|
||
if (boundDetails.length === 0) return;
|
||
|
||
for (const detail of boundDetails) {
|
||
const systemProductId = Number(detail.system_product_id);
|
||
try {
|
||
// -------- 查询当前商品资料 --------
|
||
const stock = await app.model.StockWarehouse.findOne({
|
||
where: {
|
||
id: systemProductId,
|
||
warehouse_id: warehouseId,
|
||
deleted_at: null,
|
||
},
|
||
attributes: [ 'id', 'is_images', 'gross_weight' ],
|
||
raw: true,
|
||
});
|
||
|
||
if (!stock) continue;
|
||
|
||
// 查询该明细是否有收货图片
|
||
const detailImageRefs = await app.model.FileReference.findAll({
|
||
where: {
|
||
business_type: 'receivingItem',
|
||
business_id: String(detail.id),
|
||
warehouse_id: warehouseId,
|
||
},
|
||
attributes: [ 'file_id' ],
|
||
raw: true,
|
||
});
|
||
|
||
if (detailImageRefs.length > 0) {
|
||
// 查询商品已有的图片 file_id(避免重复)
|
||
const existingStockImageFileIds = await app.model.FileReference.findAll({
|
||
where: {
|
||
business_type: 'stock',
|
||
business_id: String(systemProductId),
|
||
warehouse_id: warehouseId,
|
||
},
|
||
attributes: [ 'file_id' ],
|
||
raw: true,
|
||
}).then(rows => rows.map(r => r.file_id));
|
||
|
||
const toCreate = detailImageRefs
|
||
.filter(ref => !existingStockImageFileIds.includes(ref.file_id))
|
||
.map(ref => ({
|
||
file_id: ref.file_id,
|
||
business_type: 'stock',
|
||
business_id: String(systemProductId),
|
||
warehouse_id: warehouseId,
|
||
display_order: 0,
|
||
created_by: 'system',
|
||
created_at: new Date(),
|
||
}));
|
||
|
||
if (toCreate.length > 0) {
|
||
await app.model.FileReference.bulkCreate(toCreate, { ignoreDuplicates: true });
|
||
}
|
||
|
||
// 更新商品 is_images 标记
|
||
await app.model.StockWarehouse.update(
|
||
{ is_images: 'Y' },
|
||
{ where: { id: systemProductId } }
|
||
);
|
||
|
||
ctx.logger.info(
|
||
`[_syncProductDataFromReceiving] 商品 ${systemProductId} 已补全图片,共复制 ${toCreate.length} 张(收货单 ${receivingId} 明细 ${detail.id})`
|
||
);
|
||
}
|
||
|
||
// -------- 2. 毛重补全 --------
|
||
const currentWeight = parseFloat(stock.gross_weight) || 0;
|
||
const detailWeight = parseFloat(detail.weight) || 0;
|
||
if (currentWeight <= 0 && detailWeight > 0) {
|
||
await app.model.StockWarehouse.update(
|
||
{ gross_weight: detailWeight },
|
||
{ where: { id: systemProductId } }
|
||
);
|
||
|
||
ctx.logger.info(
|
||
`[_syncProductDataFromReceiving] 商品 ${systemProductId} 已补全毛重 ${detailWeight}(收货单 ${receivingId} 明细 ${detail.id})`
|
||
);
|
||
}
|
||
} catch (err) {
|
||
// 单条明细失败不中断后续处理
|
||
console.log(
|
||
`[_syncProductDataFromReceiving] 处理明细 ${detail.id} (商品 ${systemProductId}) 失败: ${err.message}`
|
||
);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
module.exports = ReceivingService;
|