4345 lines
148 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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

'use strict';
const Service = require('egg').Service;
const { parseWhereConditions } = require('../../../lib/query_condition_parser');
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();
}
/**
* 判断到期日期是å<C2AF>¦æ—©äºŽå½“å‰<C3A5>日期ã€? * @param {string|Date|number} expiryDate 到期日期
* @param {Date} [currentDate=new Date()] 当å‰<C3A5>日期
* @return {boolean} 是å<C2AF>¦å·²è¿‡æœ? */
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 {
/**
* 查询收货å<C2A7>•列表ã€? * @param {Object} where 动æ€<C3A6>筛选æ<E280B0>¡ä»? * @param {Object} [pageParams] 分页å<C2B5>‚æ•°
* @param {number} [pageParams.page=1] 页ç <C3A7>
* @param {number} [pageParams.pageSize=20] æ¯<C3A6>页æ<C2B5>¡æ•°
* @param {Object} [sortParams] 排åº<C3A5>å<EFBFBD>‚æ•°
* @param {Object} [options] é¢<C3A9>外选项
* @param {boolean} [options.filterDepleted=false] 是å<C2AF>¦è¿‡æ»¤æŽ‰æ— å<C2A0>¯å†<C3A5>用é‡<C3A9>的收货å<C2A7>•
* @param {number} [options.entry_order_id] å<>¯é€‰ï¼ŒæŒ‰å…¥åº“å<E2809C>•商å“<C3A5>交集过滤:å<C5A1>ªè¿”回"至少有一æ<E282AC>¡æ˜Žç»†çš„ system_product_id 在入库å<E2809C>•明细ä¸?的收货å<C2A7>•
* @return {Promise<Object>} 列表ã€<C3A3>分页与汇总信æ<C2A1>? */
async getReceivingList(where, pageParams = {}, sortParams = {}, options = {}) {
const {
ctx,
app,
} = this;
const {
Sequelize,
} = app;
const {
Op,
} = Sequelize;
const {
page = 1,
pageSize = 20,
} = pageParams;
try {
const {
sortField = 'id',
sortOrder = 'DESC',
} = sortParams;
const { filterDepleted = false, entry_order_id: entryOrderId } = options;
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: `筛选æ<EFBFBD>¡ä»¶è§£æž<EFBFBD>失è´? ${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: {
warehouse_use_status: 1,
warehouse_id: ctx.user.store_id,
},
required: false,
},
{
model: ctx.model.AccountStoreEmployee,
as: 'creator',
attributes: [ 'real_name' ],
required: true,
},
];
// å<>¯é€‰è¿‡æ»¤ï¼šæŽ’除无å<C2A0>¯å†<C3A5>用é‡<C3A9>的收货å<C2A7>? let filteredReceivingIds = null;
if (filterDepleted) {
const candidateRows = await ctx.model.Receiving.findAll({
attributes: [ 'id' ],
where: queryOptions.where,
include,
distinct: true,
raw: true,
});
const candidateIds = candidateRows.map(r => r.id);
if (candidateIds.length > 0) {
// 1. 候选收货å<C2A7>•明细çš?actual_quantity 总和(按 receiving_id 分组ï¼? const detailSums = await ctx.model.ReceivingDetail.findAll({
attributes: [
'receiving_id',
[ Sequelize.fn('SUM', Sequelize.col('actual_quantity')), 'total_actual' ],
],
where: { receiving_id: { [Op.in]: candidateIds } },
group: [ 'receiving_id' ],
raw: true,
});
const totalActualMap = {};
for (const row of detailSums) {
totalActualMap[row.receiving_id] = Number(row.total_actual) || 0;
}
// 2. 这些明细对应çš?committed 绑定é‡<C3A9>(æŒ?receiving_detail_id 分组ï¼? const detailIds = detailSums.length > 0
? (await ctx.model.ReceivingDetail.findAll({
attributes: [ 'id' ],
where: { receiving_id: { [Op.in]: candidateIds } },
raw: true,
})).map(r => r.id)
: [];
const committedByDetailId = {};
if (detailIds.length > 0) {
const bindingRows = await ctx.model.InboundDirectLog.findAll({
attributes: [
'receiving_detail_id',
[ Sequelize.fn('SUM', Sequelize.col('quantity')), 'committed_sum' ],
],
where: {
receiving_detail_id: { [Op.in]: detailIds },
status: 'committed',
},
group: [ 'receiving_detail_id' ],
raw: true,
});
for (const row of bindingRows) {
committedByDetailId[row.receiving_detail_id] = Number(row.committed_sum) || 0;
}
}
// 3. 计算æ¯<C3A6>个收货å<C2A7>•的剩余å<E284A2>¯ç”¨é‡?= SUM(actual_quantity) - SUM(committed)
const idToDetailIdsMap = {};
if (detailIds.length > 0) {
const detailIdRows = await ctx.model.ReceivingDetail.findAll({
attributes: [ 'id', 'receiving_id' ],
where: { id: { [Op.in]: detailIds } },
raw: true,
});
for (const d of detailIdRows) {
if (!idToDetailIdsMap[d.receiving_id]) idToDetailIdsMap[d.receiving_id] = [];
idToDetailIdsMap[d.receiving_id].push(d.id);
}
}
const remainingByReceivingId = {};
for (const receivingId of candidateIds) {
const totalActual = totalActualMap[receivingId] || 0;
const detailIdList = idToDetailIdsMap[receivingId] || [];
const totalCommitted = detailIdList.reduce((sum, did) => sum + (committedByDetailId[did] || 0), 0);
remainingByReceivingId[receivingId] = totalActual - totalCommitted;
}
// 过滤:å<C5A1>ªä¿<C3A4>留剩余å<E284A2>¯ç”¨é‡?> 0 的收货å<C2A7>•
filteredReceivingIds = candidateIds.filter(id => remainingByReceivingId[id] > 0);
} else {
filteredReceivingIds = [];
}
}
// å<>¯é€‰è¿‡æ»¤ï¼šæŒ‰å…¥åº“å<E2809C>•商å“<C3A5>交集过滤(å<CB86>ªè¿”回 system_product_id 有交集的收货å<C2A7>•)
let intersectionFilteredIds = null;
if (entryOrderId) {
// 1. 查该入库å<E2809C>•的所æœ?entry_items â†?stock_id 集å<E280A0>ˆ
const entryItemRows = await ctx.model.EntryItems.findAll({
where: { order_id: entryOrderId },
attributes: [ 'stock_id' ],
raw: true,
});
const entrySpIdSet = new Set(entryItemRows.map(r => r.stock_id).filter(Boolean));
if (entrySpIdSet.size === 0) {
// 入库å<E2809C>•无明细 â†?ä¸<C3A4>返回任何收货å<C2A7>•
intersectionFilteredIds = [];
} else {
// 2. 查所有收货å<C2A7>•明细,找å‡?system_product_id åœ?entrySpIdSet 中的收货å<C2A7>?ID
const matchingDetailRows = await ctx.model.ReceivingDetail.findAll({
attributes: [ 'receiving_id' ],
where: {
system_product_id: { [Op.in]: [ ...entrySpIdSet ] },
},
group: [ 'receiving_id' ],
raw: true,
});
intersectionFilteredIds = matchingDetailRows.map(r => r.receiving_id);
}
}
// å<>ˆå¹¶ filterDepleted å’?entry_order_id 的过滤结æž? let combinedFilteredIds = null;
if (filteredReceivingIds !== null || intersectionFilteredIds !== null) {
if (filteredReceivingIds !== null && intersectionFilteredIds !== null) {
// 两个过滤都å<C2BD>¯ç”?â†?å<>–交é›? const intersectionSet = new Set(intersectionFilteredIds);
combinedFilteredIds = filteredReceivingIds.filter(id => intersectionSet.has(id));
} else if (filteredReceivingIds !== null) {
combinedFilteredIds = filteredReceivingIds;
} else {
combinedFilteredIds = intersectionFilteredIds;
}
}
// 如果å<C593>¯ç”¨äº†è¿‡æ»¤ï¼Œç”¨è¿‡æ»¤å<C2A4>Žçš?ID å<>šæœ€ç»ˆæŸ¥è¯? const finalWhere = combinedFilteredIds !== null
? { id: { [Op.in]: combinedFilteredIds } }
: queryOptions.where;
const [ total, data ] = await Promise.all([
ctx.model.Receiving.count({
where: finalWhere,
include,
distinct: true,
}),
ctx.model.Receiving.findAll({
...queryOptions,
where: finalWhere,
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 => {
// 注æ„<C3A6>:wms_receiving 表中没有 locked_quantity 字段,total_quantity 为商å“<C3A5>总数é‡? const availableQuantity = Math.max(0, item.total_quantity || 0);
const lockRate = 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.total_quantity || 0), 0),
total_locked: 0,
total_available: data.reduce((sum, item) => sum + (item.total_quantity || 0), 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: '查询æˆ<C3A6>功',
};
} 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}`,
};
}
}
/**
* 获å<C2B7>–æ”¶è´§å<C2A7>•详情(主å<C2BB>• + 明细分页 + 图片)ã€? * @param {Object} data 请求ä½? * @param {number} data.id æ”¶è´§å<C2A7>•ID
* @param {Object} data.pagination 分页å<C2B5>‚æ•°
* @return {Promise<Object>} 详情数æ<C2B0>®ï¼Œæ˜Žç»†ä¸­çš?space_id 会优先展示自定义库ä½<C3A4>å<EFBFBD><C3A5>称,其次展示库ä½<C3A4>ç¼–ç <C3A7>,并补å…?space_id_raw 兼容原始ID
*/
async getReceivingDetail(data) {
const { id, pagination } = data;
const { page, pageSize } = pagination;
const { ctx, app } = this;
const { Op } = app.Sequelize;
// 获å<C2B7>–用户仓库ID,增加错误处ç<E2809E>? const warehouseId = ctx.user?.store_id;
if (!warehouseId) {
return { code: 0, message: '用户未绑定仓�, data: {} };
}
try {
// 1. 查询收货å<C2A7>•主è¡? const receiving = await app.model.Receiving.findOne({ where: { id, warehouse_id: warehouseId } });
if (!receiving) {
return { code: 0, message: '无记录或无æ<EFBFBD>ƒè®¿é—®', data: {} };
}
// 2. 查询收货å<C2A7>•明ç»?按分é¡? const receivingItems = await app.model.ReceivingDetail.findAll({
where: { receiving_id: id },
include: [{
model: app.model.LocationSpace,
as: 'receiving_space',
attributes: [ 'id', 'custom_name', 'space_code' ],
required: false,
}],
offset: (page - 1) * pageSize,
limit: pageSize,
});
// 获å<C2B7>–明细总数
const totalItems = await app.model.ReceivingDetail.count({ where: { receiving_id: id } });
// 组装分页信æ<C2A1>¯
const detailPagination = {
total: totalItems,
currentPage: page,
pageSize,
totalPages: Math.ceil(totalItems / pageSize),
hasPrevious: page > 1,
hasNext: page < Math.ceil(totalItems / pageSize),
};
// 3. 获å<C2B7>–明细ID数组
const receivingItemsIds = receivingItems.map(item => item.id);
// 4. 查询明细图片(如果明细数é‡<C3A9>大äº?ï¼? const itemImagesMap = {}; // 用于存储æ¯<C3A6>个明细的图ç‰? 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分组,并转æ<C2AC>¢ä¸ºå‰<C3A5>端å<C2AF>¯ç›´æŽ¥ä½¿ç”¨çš„链æŽ? 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. 将图片å<E280A1>ˆå¹¶åˆ°å¯¹åº”的明细中
const items = receivingItems.map(item => {
const detail = item.toJSON();
const { receiving_space: receivingSpace, ...detailBase } = detail;
const spaceName = receivingSpace?.custom_name || receivingSpace?.space_code || null;
return {
...detailBase,
space_id_raw: detailBase.space_id ?? null,
space_name: spaceName,
custom_space_name: receivingSpace?.custom_name ?? null,
space_id: spaceName,
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. 组装返回数æ<C2B0>®
receiving.dataValues.details = items; // 包å<E280A6>«å›¾ç‰‡é“¾æŽ¥çš„æ˜Žç»†æ•°æ<C2B0>? receiving.dataValues.images = receivingImages.map(image => ({
id: image.file_id,
url: image.file.file_url,
})); // 包å<E280A6>«ä¸»è¡¨å›¾ç‰‡é“¾æŽ¥
receiving.dataValues.pagination = detailPagination; // 包å<E280A6>«åˆ†é¡µä¿¡æ<C2A1>¯
return { code: 200, message: '查询æˆ<EFBFBD>功', data: { receiving } };
} catch (error) {
console.error('获å<EFBFBD>–æ”è´§å<EFBFBD>•详情失è´?', error);
return { code: 500, message: 'æœ<EFBFBD>务器错è¯?, data: {} };
}
}
/**
* 批é‡<C3A9>作废收货å<C2A7>•ã€? * @param {Object} data 请求ä½? * @param {number[]} data.ids æ”¶è´§å<C2A7>•ID数组
* @return {Promise<Object>} 作废处ç<E2809E>†ç»“æžœ
*/
async batchCancelReceiving(data) {
const { ids } = data;
const { ctx } = this;
const { Op } = ctx.model.Sequelize;
const warehouse_id = ctx.user.store_id;
try {
// 先查询这些å<E280BA>•æ<E280A2>®æ˜¯å<C2AF>¦éƒ½å­˜åœ¨ä¸”状æ€<C3A6>å…<C3A5>许作åº? const receivings = await ctx.model.Receiving.findAll({ where: { id: { [Op.in]: ids }, warehouse_id } });
if (receivings.length !== ids.length) {
return { code: 0, message: '部分å<E280A0>•æ<E280A2>®ä¸<C3A4>存在或无æ<C2A0>ƒè®¿é—®', data: {} };
}
const invalidStatus = receivings.find(r => r.status !== 'receiving');
if (invalidStatus) {
return { code: 0, message: '部分å<E280A0>•æ<E280A2>®çжæ€<C3A6>ä¸<C3A4>å…<C3A5>许作废', data: {} };
}
// 批é‡<C3A9>更新状æ€<C3A6>为cancelled
await ctx.model.Receiving.update({ status: 'cancelled' }, { where: { id: { [Op.in]: ids }, warehouse_id } });
// 批é‡<C3A9>记录æ“<C3A6>作日志
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] 写入æ“<C3A6>作日志失败,ä¸<C3A4>å½±å“<C3A5>业务', logErr);
}
return { code: 200, message: '批é‡<C3A9>作废æˆ<C3A6>功', data: {} };
} catch (error) {
console.error('批é‡<C3A9>作废收货å<C2A7>•失è´?', error);
return { code: 500, message: 'æœ<C3A6>务器错è¯?, data: {} };
}
}
/**
* 驳回收货å<C2A7>•:将已完æˆ<C3A6>æ”¶è´§å<C2A7>•æ<E280A2>¢å¤<C3A5>为收货中,记录审核人信æ<C2A1>¯ä¸Žé©³å›žç<C5BE>†ç”±ã€? * @param {Object} data 请求ä½? * @param {number[]} data.ids æ”¶è´§å<C2A7>•ID数组
* @param {string} [data.remark] 驳回ç<C5BE>†ç”±ï¼ˆè¦†ç›–原备注ï¼? * @return {Promise<Object>} æ“<C3A6>作结果
*/
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: 'æ”è´§å<EFBFBD>•IDä¸<EFBFBD>能为空', 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: '部分å<EFBFBD>•æ<EFBFBD>®ä¸<EFBFBD>存在或无æ<EFBFBD>ƒè®¿é—®', data: {} };
}
const nonCompleted = receivings.find(r => r.status !== 'completed');
if (nonCompleted) {
return { code: 0, message: 'å<EFBFBD>ªæœ‰çŠæ€<EFBFBD>为æ”货完æˆ<EFBFBD>çš„æ”è´§å<EFBFBD>•æ‰<EFBFBD>能驳回', data: {} };
}
const alreadyReviewed = receivings.find(r => Number(r.is_review) === 1);
if (alreadyReviewed) {
return { code: 0, message: '存在已审核的æ”è´§å<EFBFBD>•,无法驳回', data: {} };
}
const alreadyStored = receivings.find(r => r.storage_status === 'partial' || r.storage_status === 'all');
if (alreadyStored) {
return { code: 0, message: '存在已入库的æ”è´§å<EFBFBD>•,无法驳回', 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] 写入æ“<EFBFBD>作日志失败,ä¸<EFBFBD>å½±å“<EFBFBD>业务', logErr);
}
// å<>‘é€<C3A9>驳回通知
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: `æ”¶è´§å<C2A7>?${item.receiving_number || item.id} 已被驳回`,
content: [
`驳回人:${reviewerName || '未知'}`,
`驳回ç<C5BE>†ç”±ï¼?{updateData.remark || 'æ—?}`,
`æ”è´§å<EFBFBD>•IDï¼?{item.id || ''}`,
`æ”è´§å<EFBFBD>•å<EFBFBD>·ï¼?{item.receiving_number || 'æ—?}`,
`收货创建人:${item.creator && item.creator.name || '�}`,
'请å<C2B7>Šæ—¶å¤„ç<E2809E>†é‡<C3A9>æ–°æ<C2B0><C3A6>交完æˆ<C3A6>æ”¶è´§ã€?,
].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] å<>‘é€<C3A9>驳回通知失败,ä¸<C3A4>å½±å“<C3A5>业务', notifyErr);
}
return { code: 200, message: '驳回æˆ<C3A6>功', data: { count: ids.length } };
} catch (error) {
ctx.logger.error('[receiving.rejectReceiving] 驳回收货å<C2A7>•失è´?, error);
return { code: 500, message: 'æœ<C3A6>务器错è¯?, data: {} };
}
}
/**
* 批é‡<C3A9>审核收货å<C2A7>•:校验所有å<E280B0>•æ<E280A2>®çš„状æ€<C3A6>å<EFBFBD>Žï¼Œç”¨äº‹åŠ¡æ‰¹é‡<C3A9>更新审核信æ<C2A1>¯ã€? * ä»»æ„<C3A6>一张ä¸<C3A4>符å<C2A6>ˆæ<CB86>¡ä»¶åˆ™æ•´æ‰¹å¤±è´¥å¹¶å›žæ»šã€? * @param {Object} data 请求ä½? * @param {number[]} data.ids æ”¶è´§å<C2A7>•ID数组
* @return {Promise<Object>} æ“<C3A6>作结果
*/
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: 'æ”¶è´§å<C2A7>•IDä¸<C3A4>能为空', 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: 'æ”¶è´§å<C2A7>•IDæ ¼å¼<C3A5>ä¸<C3A4>æ­£ç¡?, data: {} };
}
const reviewerName = String(ctx.user?.employees_name || '').trim() || null;
const reviewerEmployeeId = ctx.user?.employees_id || null;
const transaction = await ctx.model.transaction();
try {
// 加行é”<C3A9>查询,防止并å<C2B6>‘审核
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: '部分å<E280A0>•æ<E280A2>®ä¸<C3A4>存在或无æ<C2A0>ƒè®¿é—®', data: {} };
}
// é€<C3A9>æ<EFBFBD>¡æ ¡éªŒï¼Œæ”¶é›†æ‰€æœ‰ä¸<C3A4>符å<C2A6>ˆçš„æ”¶è´§å<C2A7>•
const errors = [];
for (const r of receivings) {
if (r.status !== 'completed') {
errors.push(`æ”è´§å<EFBFBD>?${r.receiving_number || r.id} çŠæ€<EFBFBD>é<EFBFBD>žæ”货完æˆ<EFBFBD>`);
}
if (r.detail_status !== 'all_matched') {
errors.push(`æ”è´§å<EFBFBD>?${r.receiving_number || r.id} 明细未全部匹é…<EFBFBD>`);
}
if (r.storage_status !== 'none') {
errors.push(`æ”è´§å<EFBFBD>?${r.receiving_number || r.id} 已存在入库记录`);
}
if (!r.store_id) {
errors.push(`æ”è´§å<EFBFBD>?${r.receiving_number || r.id} 未绑定货主`);
}
if (Number(r.is_review) === 1) {
errors.push(`æ”è´§å<EFBFBD>?${r.receiving_number || r.id} 已审核,无需é‡<EFBFBD>å¤<EFBFBD>æ“<EFBFBD>作`);
}
}
if (errors.length > 0) {
await transaction.rollback();
return { code: 0, message: errors.join('ï¼?), data: {} };
}
// MySQL 二次状æ€<C3A6>核实:确ä¿<C3A4> WHERE æ<>¡ä»¶ç²¾å‡†åŒ¹é…<C3A9>,防止并å<C2B6>‘竞äº? 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: 'æ”¶è´§å<C2A7>•审核状æ€<C3A6>å·²å<C2B2>˜åŒ–,请刷新å<C2B0>Žé‡<C3A9>è¯?, data: {} };
}
// 写æ“<C3A6>作日志(失败ä¸<C3A4>å½±å“<C3A5>业务)
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] 写入æ“<C3A6>作日志失败,ä¸<C3A4>å½±å“<C3A5>业务', logErr);
}
await transaction.commit();
// é€<C3A9>å<EFBFBD>•å<E280A2>‘é€<C3A9>审核完æˆ<C3A6>通知(文å­?+ 文件,失败ä¸<C3A4>å½±å“<C3A5>业务ï¼? 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] 开始处ç<E2809E>†å<E280A0>•æ<E280A2>®é€šçŸ¥', {
receiving_id: r.id,
receiving_number: r.receiving_number,
reviewer: reviewerName,
});
// 1. å<>‘é€<C3A9>文字通知
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] 文字通知å<C2A5>‘é€<C3A9>失è´?, {
receiving_id: r.id,
error: textErr.message,
});
}
// 2. 加载明细与图片,生æˆ<C3A6> 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报表生æˆ<C3A6>结果', {
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报表生æˆ<C3A6>失败,跳过文件通知', {
receiving_id: r.id,
error: reportErr.message,
});
}
// 3. å<>‘é€<C3A9>文件通知(仅å½?Excel 上传æˆ<C3A6>功时)
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] 文件通知å<C2A5>‘é€<C3A9>失è´?, {
receiving_id: r.id,
error: fileErr.message,
});
}
}
ctx.logger.info('[receiving.reviewReceiving] å<>•æ<E280A2>®é€šçŸ¥å¤„ç<E2809E>†å®Œæˆ<C3A6>', {
receiving_id: r.id,
receiving_number: r.receiving_number,
hasReport: !!reviewReport,
});
}
return { code: 200, message: '审核æˆ<C3A6>功', data: { count: normalizedIds.length } };
} catch (error) {
await transaction.rollback();
ctx.logger.error('[receiving.reviewReceiving] 审核收货å<C2A7>•失è´?, error);
return { code: 500, message: `审核失败: ${error.message}`, data: {} };
}
}
/**
* 构建审核完æˆ<C3A6> Excel 报表 sheets,å¤<C3A5>用收货完æˆ<C3A6>报表结构,但标æ³?审核äº?而é<C592>ž"完æˆ<C3A6>äº?ã€? * @param {Object} options 构建å<C2BA>‚æ•°
* @param {Object} options.receiving æ”¶è´§å<C2A7>•(需å<E282AC>?details 数组ï¼? * @param {Object} [options.reviewer={}] 审核人信æ<C2A1>? * @param {Object} [options.stats={}] 明细统计
* @param {Map} [options.detailImageMap] 明细图片 Map(key=detail.id字符串)
* @param {Array} [options.receivingImages] æ”¶è´§å<C2A7>•主图片数组
* @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 = [
'åº<C3A5>å<EFBFBD>·', '商å“<C3A5>å<EFBFBD><C3A5>ç§°', 'æ<>¡ç <C3A7>',
'æ•°é‡<C3A9>', 'é‡<C3A9>é‡<C3A9>', '箱数', '托数',
'批次å<C2A1>?, '生产日期', '到期日期', '备注', '图片链接', '图片',
];
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();
[
[ 'æ”¶è´§å<C2A7>•ID', receiving && receiving.id ],
[ 'æ”¶è´§å<C2A7>•å<E280A2>·', receiving && receiving.receiving_number ],
[ '货主', receiving && receiving.store_name ],
[ 'æ<>¥è´§æ–¹å¼<C3A5>', this.formatDeliveryMethod(receiving && receiving.delivery_method) ],
...this.getCompletionContactFields(receiving),
[ '总明细数', stats.total_details || details.length ],
[ '已匹é…<C3A9>明细数', stats.matched_details || 0 ],
[ '未匹é…<C3A9>明细数', 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,
},
];
}
/**
* å<>‘é€<C3A9>审核完æˆ<C3A6>通知(receiving_reviewed),支æŒ<C3A6>文字/文件两ç§<C3A7>类型ã€? * @param {Object} options å<>‘é€<C3A9>å<EFBFBD>‚æ•? * @param {Object} options.receiving æ”¶è´§å<C2A7>•å¿«ç…? * @param {Object} [options.reviewer={}] 审核人信æ<C2A1>? * @param {Object|null} [options.reviewReport=null] 审核报表(有值则å<E284A2>‘文件通知ï¼? * @return {Promise<Object|null>} å<>‘é€<C3A9>结æž? */
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 = [
`æ”è´§å<EFBFBD>•å<EFBFBD>·ï¼?{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: `æ”¶è´§å<EFBFBD>?{receivingNumber}审核完æˆ<C3A6>`,
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查询æ<C2A2>¡ä»¶
* @param {string} fieldKey - 字段键å<C2AE><C3A5>
* @param {Object} condition - æ<>¡ä»¶å¯¹è±¡
* @param {Object} app - Egg应用实例
* @return {Object|null} Sequelizeæ<65>¡ä»¶å¯¹è±¡
*/
buildSequelizeCondition(fieldKey, condition, app) {
const {
Sequelize,
} = app;
const {
operator = 'eq', value, type,
} = condition;
// 处ç<E2809E>†å­—段å<C2B5>? const fieldName = condition.field || fieldKey;
// 特殊值处ç<E2809E>? const processedValue = this.processConditionValue(value, type);
// æ ¹æ<C2B9>®æ“<C3A6>作符构建æ<C2BA>¡ä»? switch (operator.toLowerCase()) {
case 'eq':
return {
[fieldName]: processedValue,
};
case 'ne':
return {
[fieldName]: {
[Sequelize.Op.ne]: processedValue,
},
};
case 'contains':
case 'like':
// 处ç<E2809E>†å¤šå€¼æƒ…å†? if (Array.isArray(processedValue) && processedValue.length > 0) {
// 多个值使�OR 连接
return {
[Sequelize.Op.or]: processedValue.map(val => ({
[fieldName]: {
[Sequelize.Op.like]: `%${val}%`,
},
})),
};
}
// å<>•个值正常处ç<E2809E>? return {
[fieldName]: {
[Sequelize.Op.like]: `%${processedValue}%`,
},
};
case 'startswith':
// 处ç<E2809E>†å¤šå€¼æƒ…å†? 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':
// 处ç<E2809E>†å¤šå€¼æƒ…å†? 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:
// 默认使用等于æ“<C3A6>作ç¬? return {
[fieldName]: processedValue,
};
}
}
/**
* 处ç<E2809E>†æ<E280A0>¡ä»¶å€? * @param {any} value - 原始å€? * @param {string} type - 字段类型
* @return {any} 处ç<E2809E>†å<E280A0>Žçš„å€? */
processConditionValue(value, type) {
const { service } = this;
if (value === undefined || value === null) {
return value;
}
switch (type) {
case 'boolean':
// 处ç<E2809E>†å¸ƒå°”值: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':
// å<>•个日期,根æ<C2B9>®ä¸šåŠ¡éœ€æ±‚å†³å®šæ˜¯å¼€å§‹è¿˜æ˜¯ç»“æ<E2809C>Ÿæ—¶é—? // 通常是开始时间(00:00:00ï¼? return service.main.normalizeDate(value, false);
case 'daterange':
// 处ç<E2809E>†æ—¥æœŸèŒƒå›´ï¼šæ•°ç»„的第一个元素是开始时间,第二个元素是结æ<E2809C>Ÿæ—¶é—´
if (Array.isArray(value) && value.length === 2) {
const [ startDate, endDate ] = value;
return [
startDate ? service.main.normalizeDate(startDate, false) : null, // 开始时间设�0:00:00
endDate ? service.main.normalizeDate(endDate, true) : null, // 结æ<E2809C>Ÿæ—¶é—´è®¾ä¸º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);
}
/**
* 创建收货å<C2A7>•并生æˆ<C3A6>æ”¶è´§å<C2A7>•å<E280A2>·ã€? * @param {Object} data 创建å<C2BA>‚æ•°
* @return {Promise<Object>} 新建结果(å<CB86>« 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. 获å<C2B7>–当å‰<C3A5>用户信æ<C2A1>¯
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. 生æˆ<C3A6>æ”¶è´§å<C2A7>•å<E280A2>·ã€‚注æ„<C3A6>:`wms_receiving.receiving_number` 在数æ<C2B0>®åº“中是全局唯一索引ï¼? // ä¸<C3A4>能æŒ?warehouse_id å<>„自ä»?001 开始,å<C592>¦åˆ™è·¨ä»“会撞å<C5BE>·ï¼›å¹¶å<C2B6>‘创建时也需è¦<C3A8>é‡<C3A9>试兜底ã€? const now = new Date();
const prefix = this.buildReceivingNumberPrefix(now);
// 3. 获å<C2B7>–店铺å<C2BA><C3A5>称(如果有货主ï¼? let store_name = null;
if (store_id) {
const store = await app.model.StoreWarehouse.findOne({
where: {
store_id,
warehouse_id,
warehouse_use_status: 1,
},
});
if (store) {
store_name = store.store_remask;
}
}
// 4. 创建收货å<C2A7>•记录(并å<C2B6>‘下若撞到唯一键则自动é‡<C3A9>试å<E280A2>–下一个å<C2AA>·ï¼? 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 冲çª<C3A7>,准备é‡<C3A9>试第 ${attempt + 1} 次`, {
prefix,
warehouse_id,
});
continue;
}
throw error;
}
}
if (!result) {
throw lastCreateError || new Error('创建收货任务失败');
}
// 记录æ“<C3A6>作日志
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] 写入æ“<C3A6>作日志失败,ä¸<C3A4>å½±å“<C3A5>业务', logErr);
}
return {
code: 200,
id: result.id,
receiving_number: result.receiving_number,
message: '收货任务创建æˆ<C3A6>功',
};
} catch (error) {
ctx.logger.error('创建收货任务失败:', error);
return {
code: 0,
message: `创建失败: ${error.message}`,
};
}
}
/**
* 按ID修改收货å<C2A7>•基础信æ<C2A1>¯ã€? * @param {Object} data 修改å<C2B9>‚æ•°
* @param {number} data.id æ”¶è´§å<C2A7>•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: 'æ”è´§å<EFBFBD>•IDä¸<EFBFBD>能为空',
};
}
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: 'æ”è´§å<EFBFBD>•ä¸<EFBFBD>存在或无æ<EFBFBD>ƒè®¿é—?,
};
}
if (receiving.status === 'cancelled') {
await transaction.rollback();
return {
code: 400,
message: 'å·²å<C2B2>–消的收货å<C2A7>•ä¸<C3A4>å…<C3A5>许修改',
};
}
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,
warehouse_use_status: 1,
},
attributes: [ 'store_id', 'store_remask' ],
transaction,
});
if (!storeRelation) {
await transaction.rollback();
return {
code: 404,
message: '货主ä¸<C3A4>存在或未与当å‰<C3A5>仓库建立有效签约关系',
};
}
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] 写入æ“<C3A6>作日志失败,ä¸<C3A4>å½±å“<C3A5>业务', logErr);
}
return {
code: 200,
id: receivingId,
receiving_number: receiving.receiving_number,
message: 'æ”¶è´§å<C2A7>•修改æˆ<C3A6>åŠ?,
};
} catch (error) {
await transaction.rollback();
ctx.logger.error('[receiving.save] 修改æ”è´§å<EFBFBD>•失è´?, error);
return {
code: 0,
message: `修改失败: ${error.message}`,
};
}
}
/**
* 绑定收货å<C2A7>•货主ã€? * 规则ï¼? * 1. å·²å<C2B2>–消收货å<C2A7>•ç¦<C3A7>止绑定ï¼? * 2. æ”¶è´§ä¸?已完æˆ<C3A6>状æ€<C3A6>下,若已存在货主,则ç¦<C3A7>æ­¢é‡<C3A9>å¤<C3A5>绑定;
* 3. ä»…å…<C3A5>许绑定与当å‰<C3A5>仓库存在有效签约关系的货主ã€? * @param {Object} data 请求ä½? * @param {number} data.id æ”¶è´§å<C2A7>•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: 'æ”è´§å<EFBFBD>•IDä¸<EFBFBD>能为空',
};
}
if (storeId <= 0) {
return {
code: 400,
message: '货主IDä¸<EFBFBD>能为空',
};
}
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: 'æ”è´§å<EFBFBD>•ä¸<EFBFBD>存在或无æ<EFBFBD>ƒè®¿é—?,
};
}
if (receiving.status === 'cancelled') {
await transaction.rollback();
return {
code: 400,
message: 'å·²å<C2B2>–消的收货å<C2A7>•ä¸<C3A4>å…<C3A5>许绑定货主',
};
}
if ([ 'receiving', 'completed' ].includes(receiving.status) && Number(receiving.store_id || 0) > 0) {
await transaction.rollback();
return {
code: 400,
message: '当å‰<C3A5>æ”¶è´§å<C2A7>•已有货主,拒ç»<C3A7>é‡<C3A9>å¤<C3A5>绑定',
};
}
const storeRelation = await ctx.model.StoreWarehouse.findOne({
where: {
warehouse_id: warehouseId,
store_id: storeId,
warehouse_use_status: 1,
},
attributes: [ 'store_id', 'store_remask' ],
transaction,
});
if (!storeRelation) {
await transaction.rollback();
return {
code: 404,
message: '货主ä¸<C3A4>存在或未与当å‰<C3A5>仓库建立有效签约关系',
};
}
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();
// 记录æ“<C3A6>作日志
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] 写入æ“<C3A6>作日志失败,ä¸<C3A4>å½±å“<C3A5>业务', logErr);
}
return {
code: 200,
message: '绑定货主æˆ<C3A6>功',
data: {
id: receivingId,
store_id: storeId,
store_name: storeName,
status: receiving.status,
},
};
} catch (error) {
await transaction.rollback();
ctx.logger.error('绑定收货å<C2A7>•货主失è´?', error);
return {
code: 500,
message: `绑定货主失败: ${error.message}`,
};
}
}
/**
* 查询å<C2A2>•个收货å<C2A7>•完整信æ<C2A1>¯ï¼ˆå<CB86>«æ˜Žç»†ã€<C3A3>图片)ã€? * @param {Object} data 请求ä½? * @param {number} data.id æ”¶è´§å<C2A7>•ID
* @return {Promise<Object>} å<>•æ<E280A2>®è¯¦æƒ…
*/
async get(data) {
const { id } = data;
const { ctx, app } = this;
const { Op } = app.Sequelize;
// 获å<C2B7>–用户仓库ID,增加错误处ç<E2809E>? const warehouseId = ctx.user?.store_id;
if (!warehouseId) {
return { code: 0, message: '用户未绑定仓�, data: {} };
}
try {
// 1. 查询收货å<C2A7>•主è¡? const receiving = await app.model.Receiving.findOne({
where: {
id,
warehouse_id: warehouseId,
},
include: [{
model: ctx.model.StoreWarehouse,
as: 'store',
attributes: [ 'store_remask' ],
where: {
warehouse_use_status: 1,
warehouse_id: warehouseId,
},
required: false,
}, {
model: ctx.model.AccountStoreEmployee,
as: 'creator',
attributes: [ 'real_name' ],
required: false,
}],
// ä¸<C3A4>需è¦<C3A8>order,因为根æ<C2B9>®id查询已ç»<C3A7>是唯一çš? });
if (!receiving) {
return { code: 0, message: '无记录或无æ<EFBFBD>ƒè®¿é—®', data: {} };
}
// 2. 查询收货å<C2A7>•明ç»? 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' ]], // ä¿<C3A4>æŒ<C3A6>倒åº<C3A5>,最新在å‰? });
// 3. 获å<C2B7>–明细ID数组
const receivingItemsIds = receivingItems.map(item => item.id);
// 4. 查询明细图片(如果明细数é‡<C3A9>大äº?ï¼? const itemImagesMap = {}; // 用于存储æ¯<C3A6>个明细的图ç‰? 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. 将图片å<E280A1>ˆå¹¶åˆ°å¯¹åº”的明细中
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] || [], // 获å<C2B7>–该明细的图片,如果没有则为空数组
};
});
// 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. 组装返回数æ<C2B0>®
const result = {
...receiving.toJSON(), // 使用toJSON()ç¡®ä¿<C3A4>获得纯对è±? details: items, // 包å<E280A6>«å›¾ç‰‡çš„æ˜Žç»†æ•°æ<C2B0>? images: receivingImages.map(item => ({
url: item.file.file_url,
id: item.file_id,
})),
};
return { code: 200, message: 'æˆ<EFBFBD>功', data: result };
} catch (error) {
console.error('获å<EFBFBD>–æ”è´§å<EFBFBD>•详情失è´?', error);
return { code: 500, message: 'æœ<EFBFBD>务器错è¯?, data: {} };
}
}
/**
* å<>‘æ”¶è´§å<C2A7>•新增一æ<E282AC>¡æ”¶è´§æ˜Žç»†ã€? * @param {Object} data 请求ä½? * @param {number} data.receiving_id æ”¶è´§å<C2A7>•ID
* @param {Object} [data.item] å<>¯é€‰çš„æ˜Žç»†å­—段
* @return {Promise<Object>} 明细列表与默认选中ID
* @description 未传 `item` 时,ä¿<C3A4>æŒ<C3A6>原有空白明细创建行为;传å…?`item` 时,å<C592>ˆå¹¶é»˜è®¤å€¼å<C2BC>Žäº¤ç”± Sequelize 校验与写入,并由æœ<C3A6>务端覆ç›?`receiving_id` ä¸?`creator_id`ã€? */
async addDetail(data) {
const ctx = this.ctx;
const { receiving_id } = data;
const item = data && data.item && typeof data.item === 'object' && !Array.isArray(data.item)
? data.item
: {};
// 获å<C2B7>–当å‰<C3A5>用户信æ<C2A1>¯
const creator_id = ctx.user.employees_id;
const warehouse_id = ctx.user.store_id;
// 验è¯<C3A8>æ”¶è´§å<C2A7>•是å<C2AF>¦å­˜åœ? const receiving = await ctx.model.Receiving.findOne({
where: { id: receiving_id, warehouse_id },
});
if (!receiving) {
return {
code: 404,
message: 'æ”¶è´§å<C2A7>•ä¸<C3A4>存在',
};
}
// 验è¯<C3A8>æ”¶è´§å<C2A7>•状æ€<C3A6>是å<C2AF>¦å…<C3A5>许添加明ç»? if (receiving.status !== 'receiving') {
return {
code: 400,
message: 'æ”¶è´§å<C2A7>•状æ€<C3A6>ä¸<C3A4>å…<C3A5>许添加明细',
};
}
try {
const defaultDetail = {
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,
};
// å…<C3A5>许å‰<C3A5>端传入å<C2A5>¯é€‰æ˜Žç»†å­—段,但æœ<C3A6>务端字段始终覆盖ã€? const newDetail = await ctx.model.ReceivingDetail.create({
...defaultDetail,
...item,
receiving_id,
creator_id,
});
// 获å<C2B7>–æ›´æ–°å<C2B0>Žçš„æ˜Žç»†åˆ—表
const allDetails = await ctx.model.ReceivingDetail.findAll({
where: { receiving_id },
order: [[ 'id', 'DESC' ]],
});
// æ ¼å¼<C3A5>化返回数æ<C2B0>? const formattedDetails = allDetails.map(detail => {
const detailData = detail.toJSON();
// 处ç<E2809E>†product_snapshot
if (detailData.product_snapshot) {
try {
detailData.product_snapshot = JSON.parse(detailData.product_snapshot);
} catch (e) {
detailData.product_snapshot = null;
}
}
// 如果有关è<C2B3>”的系统商å“<C3A5>,å<C592>¯ä»¥å<C2A5>ˆå¹¶ä¿¡æ<C2A1>? if (detailData.system_product) {
detailData.system_product_info = detailData.system_product;
}
return detailData;
});
await this.updateReceivingStats(receiving_id);
// 记录æ“<C3A6>作日志
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] 写入æ“<EFBFBD>作日志失败,ä¸<EFBFBD>å½±å“<EFBFBD>业务', logErr);
}
return {
code: 200,
message: '添加æˆ<EFBFBD>功',
data: {
details: formattedDetails,
selectId: newDetail.id,
},
};
} catch (error) {
ctx.logger.error('添加æ”货明细失败:', error);
return {
code: 500,
message: `添加失败: ${error.message}`,
};
}
}
/**
* 绑定或改绑收货å<C2A7>•明细的系统商å“<C3A5>ã€? * @param {Object} data 请求ä½? * @param {number} data.detail_id æ”¶è´§å<C2A7>•明细ID(兼å®?`id`ï¼? * @param {number} data.system_product_id 商å“<C3A5>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: 'æ”¶è´§å<C2A7>•明细IDä¸<C3A4>能为空',
};
}
if (systemProductId <= 0) {
return {
code: 400,
message: '商å“<C3A5>IDä¸<C3A4>能为空',
};
}
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: 'æ”¶è´§å<C2A7>•明细ä¸<C3A4>存在',
};
}
if (Number(receivingDetail.receiving?.is_review) === 1) {
return {
code: 400,
message: 'æ”¶è´§å<C2A7>•已审核,ç¦<C3A7>止绑定或改绑商å“<C3A5>',
};
}
if (String(receivingDetail.receiving?.status || '') === 'cancelled') {
return {
code: 400,
message: 'æ”¶è´§å<C2A7>•已作废,ç¦<C3A7>止绑定或改绑商å“<C3A5>',
};
}
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: '商å“<C3A5>ä¸<C3A4>存在或ä¸<C3A4>属于当å‰<C3A5>仓åº?,
};
}
const productStoreId = Number(stockWarehouse.store_stock?.store_id || 0);
const receivingStoreId = Number(receivingDetail.receiving?.store_id || 0);
// 货主校验:收货å<C2A7>•已有货主时,å<C592>ªå…<C3A5>许绑定å<C5A1>Œä¸€è´§ä¸»çš„商å“? if (receivingStoreId > 0 && productStoreId > 0 && receivingStoreId !== productStoreId) {
return {
code: 400,
message: '该商å“<EFBFBD>ä¸<EFBFBD>属于当å‰<EFBFBD>æ”è´§å<EFBFBD>•的货主,ä¸<EFBFBD>å…<EFBFBD>许绑定',
};
}
// æ”¶è´§å<C2A7>•无货主时,自动设置为当å‰<C3A5>商å“<C3A5>的货主
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 || '未命å<EFBFBD><EFBFBD>商å“?;
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(),
}),
};
// 如果收货明细有æ<E280B0>¡ç <C3A7>且商å“<C3A5>尚未包å<E280A6>«è¯¥æ<C2A5>¡ç <C3A7>,则自动为商å“<C3A5>新增æ<C5BE>¡ç <C3A7>
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) {
// 唯一索引冲çª<C3A7>说明æ<C5BD>¡ç <C3A7>已被其他商å“<C3A5>å<EFBFBD> ç”¨ï¼Œä»…记录日志ä¸<C3A4>阻断业åŠ? ctx.logger.warn('[receiving.bindDetailProduct] 自动新增æ<C5BE>¡ç <C3A7>失败(å<CB86>¯èƒ½å·²å­˜åœ¨ï¼?, 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);
// 记录æ“<C3A6>作日志
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] 写入æ“<C3A6>作日志失败,ä¸<C3A4>å½±å“<C3A5>业务', 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 ? '绑定商å“<C3A5>æˆ<C3A6>功,已自动设置货主' : '绑定商å“<C3A5>æˆ<C3A6>功',
data: responseData,
};
} catch (error) {
ctx.logger.error('绑定收货å<C2A7>•明细商å“<C3A5>失è´?', error);
return {
code: 500,
message: `绑定商å“<EFBFBD>失败: ${error.message}`,
};
}
}
async updateDetail(data) {
const ctx = this.ctx;
const { id, ...updateData } = data;
// 验è¯<C3A8>明细是å<C2AF>¦å­˜åœ¨
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: '明细ä¸<C3A4>å­˜åœ?,
};
}
// 验è¯<C3A8>å…³è<C2B3>”的收货å<C2A7>•状æ€<C3A6>是å<C2AF>¦å…<C3A5>许修æ”? if (detail.receiving && detail.receiving.status !== 'receiving') {
return {
code: 400,
message: 'æ”è´§å<EFBFBD>•çŠæ€<EFBFBD>ä¸<EFBFBD>å…<EFBFBD>许修改明细',
};
}
// 验è¯<C3A8>必填字段
if (updateData.product_name && !updateData.product_name.trim()) {
return {
code: 400,
message: '商å“<EFBFBD>å<EFBFBD><EFBFBD>ç§°ä¸<EFBFBD>能为空',
};
}
if (updateData.actual_quantity !== undefined && updateData.actual_quantity <= 0) {
return {
code: 400,
message: '实际数é‡<EFBFBD>必须大于0',
};
}
try {
// 如果需è¦<C3A8>处ç<E2809E>†å•†å“<C3A5>匹é…? if (updateData.barcode && updateData.barcode.trim()) {
// å°<C3A5>试根æ<C2B9>®æ<C2AE>¡ç <C3A7>匹é…<C3A9>系统商å“<C3A5>
const systemProduct = await ctx.model.StockWarehouse.findOne({
where: { barcode: updateData.barcode },
});
if (systemProduct) {
updateData.system_product_id = systemProduct.id;
// 创建商å“<C3A5>å¿«ç…§
updateData.product_snapshot = JSON.stringify({
name: systemProduct.name,
barcode: systemProduct.barcode,
spec: systemProduct.spec,
unit: systemProduct.unit,
images: systemProduct.images ? JSON.parse(systemProduct.images) : [],
});
// 如果用户没有输入商å“<C3A5>å<EFBFBD><C3A5>称,使用系统商å“<C3A5>å<EFBFBD><C3A5>ç§? if (!updateData.product_name) {
updateData.product_name = systemProduct.name;
}
}
}
// 处ç<E2809E>†æ•°é‡<C3A9>类型的转æ<C2AC>? 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;
// æ ¹æ<C2B9>®å…¥åº“æ•°é‡<C3A9>更新入库状æ€? 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: '更新失败',
};
}
// æ›´æ–°æ”¶è´§å<C2A7>•统计信æ<C2A1>? if (detail.receiving_id) {
await this.updateReceivingStats(detail.receiving_id);
}
// 获å<C2B7>–æ›´æ–°å<C2B0>Žçš„æ˜Žç»†
const updatedDetail = await ctx.model.ReceivingDetail.findOne({
where: { id },
include: [
{
model: ctx.model.StockWarehouse,
as: 'system_product',
attributes: [ 'id', 'name', 'barcode', 'spec', 'unit', 'images' ],
},
],
});
// æ ¼å¼<C3A5>化返回数æ<C2B0>? 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: 'æ›´æ–°æˆ<EFBFBD>功',
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 直接关è<C2B3>” 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 的信æ<C2A1>? return {
store_id: stockWarehouse.store_stock.store_id,
store_remask: stockWarehouse.store_stock.store_remask,
};
} catch (error) {
ctx.logger.error(`获å<C2B7>–库存 ${stock_id} 的店铺信æ<C2A1>¯å¤±è´?`, error);
// æ ¹æ<C2B9>®éœ€æ±‚决定是å<C2AF>¦æŠ›å‡ºé”™è¯? // throw error;
return null;
}
}
// æ›´æ–°æ”¶è´§å<C2A7>•统计信æ<C2A1>¯çš„辅助方法
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. 先查询收货å<C2A7>•,并加é”<C3A9>
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. 检查收货å<C2A7>•是å<C2AF>¦å·²æœ‰ store_id(优先使用已有值)
let storeId = receiving.store_id;
let storeName = receiving.store_name;
// 如果收货å<C2A7>•没æœ?store_id,å°<C3A5>试从已匹é…<C3A9>的商å“<C3A5>详情中获å<C2B7>? if (!storeId) {
// 查找第一个已匹é…<C3A9>的商å“<C3A5>详情(system_product_id ä¸<C3A4>为空)
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 获å<C2B7>–库存信æ<C2A1>¯
const storeInfo = await this.getStockStoreInfo(matchedDetail.system_product_id);
if (storeInfo && storeInfo.store_id) {
storeId = storeInfo.store_id;
// 注æ„<C3A6>:这里使ç”?store_remask 作为 store_name
storeName = storeInfo.store_remask; // 或�storeInfo.store_remask
}
} catch (error) {
ctx.logger.warn(`获å<C2B7>–商å“<C3A5> ${matchedDetail.system_product_id} 的库存信æ<C2A1>¯å¤±è´?`, error);
// 继续执行,使用默认� }
}
}
// 3. 统计该收货å<C2A7>•的所有明ç»? 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. 判断收货å<C2A7>•的整体状æ€? 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. æ›´æ–°æ”¶è´§å<C2A7>? const updateData = {
total_items: parseInt(stat.total_items) || 0,
total_quantity: parseFloat(stat.total_quantity) || 0,
detail_status: detailStatus,
updated_at: new Date(),
};
// å<>ªåœ¨æœ‰å€¼ä¸”æ”¶è´§å<C2A7>•当å‰<C3A5>没有这些值时更新 store ä¿¡æ<C2A1>¯
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 ä¸<C3A4>å<EFBFBD>Œï¼Œä¹Ÿæ›´æ–°å<C2B0><C3A5>ç§°
updateData.store_name = storeName;
}
await ctx.model.Receiving.update(updateData, {
where: {
id: receivingId,
warehouse_id: warehouseId,
},
transaction,
});
// 6. æ<><C3A6>交事务
await transaction.commit();
ctx.logger.info(`æˆ<C3A6>功更新收货å<C2A7>?${receivingId} 的统计信æ<C2A1>¯`);
} catch (error) {
// 7. å<>‘生错误时回滚事åŠ? if (transaction) {
await transaction.rollback();
}
ctx.logger.error('æ›´æ–°æ”è´§å<EFBFBD>•统计失è´?', error);
throw error;
}
}
/**
* 删除收货å<C2A7>•明细并回算统计ã€? * @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;
// 验è¯<C3A8>明细是å<C2AF>¦å­˜åœ¨
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: '明细ä¸<EFBFBD>å­˜åœ?,
};
}
// 验è¯<C3A8>å…³è<C2B3>”的收货å<C2A7>•状æ€<C3A6>是å<C2AF>¦å…<C3A5>许删é™? if (detail.receiving && detail.receiving.status !== 'receiving') {
return {
code: 400,
message: 'æ”¶è´§å<C2A7>•状æ€<C3A6>ä¸<C3A4>å…<C3A5>许删除明细',
};
}
// 检查是å<C2AF>¦å·²å…¥åº“(已入库的明细ä¸<C3A4>能删除)
if (detail.storage_status !== 'none' && detail.stored_quantity > 0) {
return {
code: 400,
message: '该明细已入库,ä¸<C3A4>能删é™?,
};
}
try {
// 获å<C2B7>–receiving_id用于å<C5BD>Žç»­æ›´æ–°ç»Ÿè®¡
const receiving_id = detail.receiving_id;
// 删除明细
const deletedCount = await ctx.model.ReceivingDetail.destroy({
where: { id: detail_id },
});
if (deletedCount === 0) {
return {
code: 400,
message: '删除失败',
};
}
// 获å<C2B7>–删除å<C2A4>Žçš„æ‰€æœ‰æ˜Žç»? const remainingDetails = await ctx.model.ReceivingDetail.findAll({
where: { receiving_id },
order: [[ 'id', 'DESC' ]],
});
// æ ¼å¼<C3A5>化返回数æ<C2B0>? 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);
// 记录æ“<C3A6>作日志
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] 写入æ“<EFBFBD>作日志失败,ä¸<EFBFBD>å½±å“<EFBFBD>业务', logErr);
}
return {
code: 200,
message: '删除æˆ<EFBFBD>功',
data: {
details: formattedDetails,
selectId,
},
};
} catch (error) {
ctx.logger.error('删除æ”货明细失败:', error);
return {
code: 500,
message: `删除失败: ${error.message}`,
};
}
}
/**
* 修改收货明细ã€? * @param {Object} data 收货明细修改å<C2B9>‚æ•°
* @return {Promise<Object>} 修改结果
*/
async detailChange(data) {
const { ctx, app } = this;
const warehouseId = ctx.user.store_id;
try {
// 1. æ<><C3A6>å<EFBFBD>–å‰<C3A5>端输入字段
const {
id, // 收货明细ID
receiving_id, // æ”¶è´§å<C2A7>•ID
actual_quantity, // 实际收货数é‡<C3A9>
batch_number, // 批次å<C2A1>? production_date, // 生产日期
expiry_date, // 到期日期
box_quantity, // 箱数
boxes_per_pallet, // æ¯<C3A6>托盘箱æ•? pallet_quantity, // 托盘æ•? space_id, // 存放库ä½<C3A4>ID
remark, // 备注
system_product_id, // 系统商å“<C3A5>ID
barcode, // æ<>¡ç <C3A7>
product_name, // 商å“<C3A5>å<EFBFBD><C3A5>ç§°
box_width,
box_height,
box_length,
weight,
box_remainder, // 箱余æ•? box_weight, // ç®±é‡<C3A9>é‡? } = data;
// 2. 验è¯<C3A8>必填字段
if (!id) {
return {
code: 400,
message: 'æ”货明细IDä¸<EFBFBD>能为空',
};
}
if (!receiving_id) {
return {
code: 400,
message: 'æ”è´§å<EFBFBD>•IDä¸<EFBFBD>能为空',
};
}
// 3. 获å<C2B7>–收货明细信æ<C2A1>¯
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: 'æ”货明细ä¸<EFBFBD>å­˜åœ?,
};
}
if (expiry_date && expiry_date !== undefined && isExpiryDateBeforeToday(expiry_date)) {
return {
code: 400,
message: '到期日期已过期,ä¸<C3A4>能录入收货',
};
}
// 5. 验è¯<C3A8>箱规数æ<C2B0>®
if (box_quantity !== undefined && box_quantity < 0) {
return {
code: 400,
message: '箱数ä¸<C3A4>能为负æ•?,
};
}
if (pallet_quantity !== undefined && pallet_quantity < 0) {
return {
code: 400,
message: '托盘数ä¸<EFBFBD>能为负数',
};
}
if (box_remainder !== undefined && box_remainder < 0) {
return {
code: 400,
message: '箱余数ä¸<EFBFBD>能为负数',
};
}
if (box_weight !== undefined && box_weight < 0) {
return {
code: 400,
message: 'ç®±é‡<EFBFBD>é‡<EFBFBD>ä¸<EFBFBD>能为负数',
};
}
// 6. 准备更新数æ<C2B0>®
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;
// 批次信æ<C2A1>¯
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;
// 库ä½<C3A4>ä¿¡æ<C2A1>¯
if (space_id !== undefined) updateData.space_id = space_id;
// 7. 如果æ<C593>ºå¸¦äº†ç³»ç»Ÿå•†å“<C3A5>ID,则更新商å“<C3A5>相关信æ<C2A1>¯
if (system_product_id) {
// 获å<C2B7>–系统商å“<C3A5>ä¿¡æ<C2A1>¯
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) {
// 更新商å“<C3A5>相关信æ<C2A1>¯
updateData.system_product_id = system_product_id;
// 使用系统商å“<C3A5>çš„æ<E2809E>¡ç <C3A7>(如果å‰<C3A5>端没有æ<E280B0><C3A6>ä¾›ï¼? 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;
}
// 使用系统商å“<C3A5>çš„å<E2809E><C3A5>称(如果å‰<C3A5>端没有æ<E280B0><C3A6>ä¾›ï¼? updateData.product_name = stockWarehouse.item_name || product_name;
// 如果有货主信æ<C2A1>¯ï¼Œæ›´æ–°åˆ°äº§å“<C3A5>快照中
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) {
// 如果没有系统商å“<C3A5>ID,但有æ<E280B0>¡ç <C3A7>或商å“<C3A5>å<EFBFBD><C3A5>称,也更新
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);
// 记录æ“<C3A6>作日志
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] 写入æ“<EFBFBD>作日志失败,ä¸<EFBFBD>å½±å“<EFBFBD>业务', logErr);
}
// 9. 返回æˆ<C3A6>功å“<C3A5>应
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: '修改æˆ<EFBFBD>功',
};
} catch (error) {
ctx.logger.error('修改失败:', error);
return {
code: 500,
message: '修改失败,请ç¨<EFBFBD>å<EFBFBD>Žé‡<EFBFBD>试',
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. 查询收货å<C2A7>•并加é”<C3A9>
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, 'æ”è´§å<EFBFBD>•ä¸<EFBFBD>存在或已被删é™?);
}
// 2. 检查状æ€<C3A6>是å<C2AF>¦å…<C3A5>许作åº? if (receiving.status === 'cancelled') {
return {
code: 200,
success: true,
message: 'æ”¶è´§å<C2A7>•已作废,无需é‡<C3A9>å¤<C3A5>æ“<C3A6>作',
};
}
if (receiving.status === 'completed' && receiving.storage_status === 'all') {
await transaction.rollback();
ctx.throw(400, '已全部入库完æˆ<C3A6>,无法作废');
}
// 3. 获å<C2B7>–æ“<C3A6>作人信æ<C2A1>? const operator = ctx.user;
// 4. æ›´æ–°æ”¶è´§å<C2A7>•状æ€<C3A6>为作废
await ctx.model.Receiving.update({
status: 'cancelled',
remark: invalid_reason ? `已作� ${invalid_reason}` : (receiving.remark || '') + ' - 已作�,
updated_at: new Date(),
}, {
where: { id: receivingId },
transaction,
});
// 5. 处ç<E2809E>†å·²åŒ¹é…<C3A9>的商å“<C3A5>明细
if (receiving.details && receiving.details.length > 0) {
const matchedDetails = receiving.details.filter(detail => detail.system_product_id);
if (matchedDetails.length > 0) {
// 解除已匹é…<C3A9>的商å“<C3A5>å…³è<C2B3>”
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,
});
// å<>¯ä»¥åœ¨è¿™é‡Œå¤„ç<E2809E>†åº“存的释放逻辑(如果需è¦<C3A8>)
// await this.releaseLockedStock(receivingId, transaction);
}
}
// 6. 处ç<E2809E>†å…³è<C2B3>”的入库记录(如果有部分入库的情况ï¼? if (receiving.storage_status === 'partial') {
// 将关è<C2B3>”的入库记录状æ€<C3A6>也更新为作åº? await ctx.model.Storage.update({
status: 'cancelled',
remark: `å…³è<C2B3>”æ”¶è´§å<C2A7>?{receiving.receiving_number}已作废`,
updated_at: new Date(),
}, {
where: {
receiving_id: receivingId,
status: { [Op.ne]: 'cancelled' },
},
transaction,
});
}
// 8. æ<><C3A6>交事务
await transaction.commit();
// 记录æ“<C3A6>作日志
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] 写入æ“<EFBFBD>作日志失败,ä¸<EFBFBD>å½±å“<EFBFBD>业务', logErr);
}
return {
code: 200,
success: true,
message: '作废æˆ<EFBFBD>功',
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(`作废收货å<C2A7>•失è´? ${error.message}`, {
receivingId,
warehouseId,
userId: ctx.user.id,
error: error.stack,
});
// é‡<C3A9>新抛出错误,让上层处ç<E2809E>†
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: '空è¿<C3A8>',
sea_freight: 'æµ·è¿<C3A8>',
other: 'å…¶ä»–',
};
const normalizedValue = String(value || '').trim();
return methodMap[normalizedValue] || normalizedValue;
}
/**
* 获å<C2B7>–完æˆ<C3A6>收货时需è¦<C3A8>展示的è<E2809E>”系字段ã€? * @param {Object} receiving æ”¶è´§å<C2A7>•å¿«ç…§ã€? * @return {Array<Array>} 需è¦<C3A8>展示的è<E2809E>”系字段列表ã€? */
getCompletionContactFields(receiving) {
const deliveryMethod = String((receiving && receiving.delivery_method) || '').trim();
if (deliveryMethod === 'truck') {
return [[ '车牌å<C592>?, receiving && receiving.license_plate ]];
}
if (deliveryMethod === 'express') {
return [[ '物æµ<EFBFBD>å<EFBFBD>•å<EFBFBD>·', receiving && receiving.tracking_number ]];
}
return [];
}
/**
* 生æˆ<C3A6>收货完æˆ<C3A6>报表的工作表数æ<C2B0>®ã€? * @param {Object} options 报表å<C2A8>‚æ•°ã€? * @param {Object} options.receiving æ”¶è´§å<C2A7>•å¿«ç…§ã€? * @param {Object} [options.operator={}] æ“<C3A6>作人信æ<C2A1>¯ã€? * @param {Object} [options.stats={}] 收货统计数æ<C2B0>®ã€? * @param {Map} [options.detailImageMap=new Map()] 明细图片映射ã€? * @param {Array} [options.receivingImages=[]] æ”¶è´§å<C2A7>•图片列表ã€? * @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 = [
'åº<EFBFBD>å<EFBFBD>·', '商å“<EFBFBD>å<EFBFBD><EFBFBD>ç§°', 'æ<EFBFBD>¡ç <EFBFBD>',
'æ•°é‡<EFBFBD>', 'é‡<EFBFBD>é‡<EFBFBD>', '箱数', '托数',
'批次å<EFBFBD>?, '生产日期', '到期日期', '备注', '图片链接', '图片',
];
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([]);
[
[ 'æ”¶è´§å<C2A7>•ID', receiving && receiving.id ],
[ 'æ”¶è´§å<C2A7>•å<E280A2>·', receiving && receiving.receiving_number ],
[ '货主', receiving && receiving.store_name ],
[ 'æ<>¥è´§æ–¹å¼<C3A5>', this.formatDeliveryMethod(receiving && receiving.delivery_method) ],
...this.getCompletionContactFields(receiving),
[ '总明细数', stats.total_details || details.length ],
[ '已匹é…<C3A9>明细数', stats.matched_details || 0 ],
[ '未匹é…<C3A9>明细数', stats.unmatched_details || 0 ],
[ '总数�, stats.total_quantity || 0 ],
[ '总箱�, receiving && receiving.total_boxes ],
[ '总托盘数', receiving && receiving.total_pallets ],
[ '完æˆ<C3A6>äº?, operator.employees_name || operator.real_name || operator.name || '' ],
[ '完æˆ<EFBFBD>æ—é—´', 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: 'æ”货清å<EFBFBD>•',
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: `收货明细(已完æˆ<C3A6>æ”¶è´?_${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,
}),
});
}
/**
* å<>‘é€<C3A9>收货完æˆ<C3A6>统一通知,通知外部订阅 `receiving_completed` 事件ã€? * @param {Object} options 通知å<C2A5>‚æ•°
* @param {Object} options.receiving æ”¶è´§å<C2A7>•å¿«ç…? * @param {Object} [options.operator={}] æ“<C3A6>作人信æ<C2A1>? * @param {Object} [options.stats={}] 收货统计
* @param {Object|null} [options.completionReport=null] 完æˆ<C3A6>报表信æ<C2A1>¯
* @return {Promise<Object|null>} 通知å<C2A5>‘é€<C3A9>结果,若æ<C2A5>¡ä»¶ä¸<C3A4>满足则返å›?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)) || `收货完æˆ<C3A6>_${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 = `æ”¶è´§å<C2A7>?{receivingNumber}已完æˆ<C3A6>`;
const contactLines = this.getCompletionContactFields(receiving).map(([ field, value ]) => `${field}ï¼?{value || 'æ—?}`);
const content = [
`æ”è´§å<EFBFBD>•å<EFBFBD>·ï¼?{receivingNumber} 已完æˆ<EFBFBD>`,
`货主�{receiving.store_name || '未知'}`,
`æ<EFBFBD>¥è´§æ–¹å¼<EFBFBD>ï¼?{this.formatDeliveryMethod(receiving.delivery_method) || '未知'}`,
...contactLines,
`总明细数ï¼?{Number(stats.total_details || 0)}ä»`,
`匹é…<EFBFBD>商å“<EFBFBD>ï¼?{matchedDetails}ä»`,
`未匹é…<EFBFBD>商å“<EFBFBD>:${unmatchedDetails}ä»`,
`总数é‡<EFBFBD>:${totalQuantity}`,
`总箱数:${receiving.total_boxes || 0}`,
`总箱余数�{totalBoxRemainder}`,
`总箱é‡<EFBFBD>:${totalBoxWeight}`,
`总托盘数�{receiving.total_pallets || 0}`,
operatorName ? `完æˆ<EFBFBD>人:${operatorName}` : '',
`开始æ—间:${this.formatReportDate(receiving.created_at)}`,
`完æˆ<EFBFBD>æ—é—´ï¼?{this.formatReportDate(receiving.receiving_end_time)}`,
`备注�{receiving.remark || '�}`,
`快速查看:${ctx.app.config.frontendUrl || ''}/storage/receiving?id=${receivingNumber}`, // 替æ<C2BF>¢ä¸ºå®žé™…çš„å‰<C3A5>端地å<C2B0>€
].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,
},
});
}
/**
* 完æˆ<C3A6>æ”¶è´§å<C2A7>•:校验明细ã€<C3A3>更新状æ€<C3A6>并写入库存ã€? * @param {Object} data 请求ä½? * @param {number} data.id æ”¶è´§å<C2A7>•ID
* @param {string} [data.remark] 完æˆ<C3A6>备注
* @return {Promise<Object>} 完æˆ<C3A6>结果
*/
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. 查询收货å<C2A7>•并加é”<C3A9>
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: 'æ”¶è´§å<C2A7>•ä¸<C3A4>存在或已被删é™?,
};
}
// 2. 状æ€<C3A6>检æŸ? if (receiving.status === 'completed') {
await transaction.rollback();
return {
code: 200,
message: 'æ”è´§å<EFBFBD>•已完æˆ<EFBFBD>',
};
}
if (receiving.status === 'cancelled') {
await transaction.rollback();
return {
code: 400,
message: '已作废的æ”è´§å<EFBFBD>•ä¸<EFBFBD>å<EFBFBD>¯å®Œæˆ?,
};
}
// 3. 检查是å<C2AF>¦æœ‰æ˜Žç»†
if (!receiving.details || receiving.details.length === 0) {
await transaction.rollback();
return {
code: 400,
message: 'æ”¶è´§å<C2A7>•没有明细,请先添加商å“<C3A5>',
};
}
// 4. 校验明细数é‡<C3A9>:ä¸<C3A4>å…<C3A5>许存在数é‡<C3A9>ä¸?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
? `商å“<EFBFBD>â€?{zeroQuantityDetails[0].product_name || '未命å<C2BD><C3A5>商å“?}â€<C3A2>的数é‡<C3A9>ä¸?,请填写实际收货数é‡<C3A9>`
: `æœ?{zeroQuantityDetails.length}个商å“<C3A5>æ•°é‡<C3A9>为0,请填写实际收货数é‡<C3A9>`;
return {
success: false,
code: 'DETAIL_QUANTITY_ZERO',
message: errorMsg,
data: {
invalid_details: zeroQuantityDetails.map(d => ({
detail_id: d.id,
item_name: d.product_name || '未命å<C2BD><C3A5>商å“?,
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: '批次管ç<EFBFBD>†å•†å“<EFBFBD>必须填写批次å<EFBFBD>?,
data: {
invalid_details: missingBatchNumberDetails.map(detail => ({
detail_id: detail.id,
item_name: detail.product_name || detail.system_product?.item_name || '未命å<C2BD><C3A5>商å“?,
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: '批次管ç<EFBFBD>†å•†å“<EFBFBD>必须填写生产日期和有效期',
data: {
invalid_details: missingBatchDetails.map(detail => ({
detail_id: detail.id,
item_name: detail.product_name || detail.system_product?.item_name || '未命å<EFBFBD><EFBFBD>商å“?,
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: `商å“<EFBFBD>â€?{firstInvalid.product_name || firstInvalid.system_product?.item_name || '未命å<C2BD><C3A5>商å“?}â€<C3A2>的有效期ä¸<C3A4>足最å°<C3A5>å…<C3A5>许收货天数(${minReceiveDays}天),无法完æˆ<EFBFBD>æ”¶è´§`,
data: {
invalid_details: invalidExpiryDetails.map(detail => ({
detail_id: detail.id,
item_name: detail.product_name || detail.system_product?.item_name || '未命å<C2BD><C3A5>商å“?,
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. 准备明细图片与统计信æ<C2A1>¯ï¼ˆç…§ç‰‡/æ<>¡ç <C3A7>/é‡<C3A9>é‡<C3A9>ä¸<C3A4>å†<C3A5>强制è¦<C3A8>求ï¼? 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. 获å<C2B7>–æ“<C3A6>作人信æ<C2A1>? const operator = ctx.user;
// 8. æ›´æ–°æ”¶è´§å<C2A7>•状æ€? 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}ã€<C3A3>完æˆ<C3A6>æ”¶è´§ã€?{now.toLocaleString()} ${operator.employees_name} ${remark}`;
} else {
const remarkPrefix = receiving.remark ? `${receiving.remark}\n` : '';
updateData.remark = `${remarkPrefix}ã€<C3A3>完æˆ<C3A6>æ”¶è´§ã€?{now.toLocaleString()} ${operator.employees_name}`;
}
await ctx.model.Receiving.update(updateData, {
where: { id },
transaction,
});
// 9. 记录统计信æ<C2A1>¯
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. æ<><C3A6>交事务
await transaction.commit();
// 10.1 清除收货å<C2A7>•缓存,确ä¿<C3A4>下次入库完æˆ<C3A6>时匹é…<C3A9>到最新收货å<C2A7>•列表
const receivingCacheKey = `cache:receiving_orders:warehouse:${warehouseId}`;
app.delCacheAsync(receivingCacheKey).catch(cacheErr => {
ctx.logger.warn(`[receiving.completeReceiving] 清除收货å<C2A7>•缓存失è´? ${cacheErr.message}`, { cacheKey: receivingCacheKey });
});
// 记录æ“<C3A6>作日志
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] 写入æ“<EFBFBD>作日志失败,ä¸<EFBFBD>å½±å“<EFBFBD>业务', logErr);
}
const receivingSnapshot = {
...(typeof receiving.toJSON === 'function' ? receiving.toJSON() : receiving),
...updateData,
};
const completionNoticePayload = {
receiving: receivingSnapshot,
operator,
stats,
};
// 11. æ”¶è´§æˆ<C3A6>功å<C5B8>Žå…ˆè§¦å<C2A6>‘文字通知,å†<C3A5>生æˆ<C3A6> Excel;若 Excel æˆ<C3A6>功,å†<C3A5>è¡¥å<C2A5>‘文件通知ã€? try {
const textNoticeResult = await this.sendCompletionNotice(completionNoticePayload);
ctx.logger.info('æ”货完æˆ<EFBFBD>文字通知结果', {
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(`收货完æˆ<C3A6>文字通知å<C2A5>‘é€<C3A9>失è´? ${notifyError.message}`, {
receiving_id: id,
warehouseId,
error: notifyError.stack,
});
}
ctx.logger.info('æ”è´§å<EFBFBD>•已完æˆ<EFBFBD>', {
receiving_id: id,
receiving_number: receiving.receiving_number,
completed_by: operator.employees_name,
stats,
});
// 异步补全商å“<C3A5>图片与毛é‡<C3A9>,ä¸<C3A4>阻塞主进程
this._syncProductDataFromReceiving({
receivingId: id,
warehouseId,
details: receiving.details,
}).catch(err => {
ctx.logger.warn('[receiving._syncProductDataFromReceiving] 异步补全失败,ä¸<EFBFBD>å½±å“<EFBFBD>业务', err.message);
});
return {
success: true,
code: 200,
message: 'æ”货完æˆ<EFBFBD>æˆ<EFBFBD>功',
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(`完æˆ<C3A6>收货失败: ${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 || '系统错误,请ç¨<EFBFBD>å<EFBFBD>Žé‡<EFBFBD>试',
};
}
}
/**
* 收货完æˆ<C3A6>å<EFBFBD>Žå¼‚步补全商å“<C3A5>资料:绑定图片ã€<C3A3>补填毛é‡<C3A9>ã€? *
* é<><C3A9>历当å‰<C3A5>æ”¶è´§å<C2A7>•所有已绑定系统商å“<C3A5>的明细:
* 1. 若商å“?is_images === 'N' 且该明细有收货图片,则将收货图片å¤<C3A5>制为商å“<C3A5>图片(FileReference),
* 并将商å“<C3A5>çš?is_images æ›´æ–°ä¸?'Y'ã€? * 2. 若商å“?gross_weight ä¸?0 æˆ?null,且明细çš?weight > 0,则将商å“<C3A5>毛é‡<C3A9>更新为该明细的 weightã€? *
* 本方法通过 setImmediate 调用,è¿<C3A8>行在事务æ<C2A1><C3A6>交å<C2A4>Žï¼Œä»»ä½•异常å<C2B8>ªè®°å½•日志,ä¸<C3A4>å½±å“<C3A5>主进程ã€? *
* @param {Object} options å<>‚数对象
* @param {number} options.receivingId æ”¶è´§å<C2A7>?ID
* @param {number} options.warehouseId 仓库 ID
* @param {Array} options.details 收货明细数组(æ<CB86>¥è‡?completeReceiving 中已加载çš?detailsï¼? * @return {Promise<void>}
*/
async _syncProductDataFromReceiving({ receivingId, warehouseId, details }) {
console.log('_syncProductDataFromReceiving异步执行�..'); // 调试日志
const { ctx, app } = this;
// å<>ªå¤„ç<E2809E>†å·²ç»‘定系统商å“<C3A5>的明ç»? 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 {
// -------- 查询当å‰<C3A5>商å“<C3A5>资料 --------
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;
// 查询该明细是å<C2AF>¦æœ‰æ”¶è´§å›¾ç‰‡
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) {
// 查询商å“<C3A5>已有的图ç‰?file_id(é<CB86>¿å…<C3A5>é‡<C3A9>å¤<C3A5>)
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 });
}
// 更新商å“<C3A5> is_images 标记
await app.model.StockWarehouse.update(
{ is_images: 'Y' },
{ where: { id: systemProductId } }
);
ctx.logger.info(
`[_syncProductDataFromReceiving] 商å“<C3A5> ${systemProductId} 已补全图片,共å¤<C3A5>åˆ?${toCreate.length} 张(收货å<C2A7>?${receivingId} 明细 ${detail.id})`
);
}
// -------- 2. 毛é‡<C3A9>补全 --------
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] 商å“<C3A5> ${systemProductId} 已补全毛é‡?${detailWeight}(收货å<C2A7>• ${receivingId} 明细 ${detail.id})`
);
}
} catch (err) {
// å<>•æ<E280A2>¡æ˜Žç»†å¤±è´¥ä¸<C3A4>中断å<C2AD>Žç»­å¤„ç<E2809E>? console.log(
`[_syncProductDataFromReceiving] 处ç<E2809E>†æ˜Žç»† ${detail.id} (商å“<C3A5> ${systemProductId}) 失败: ${err.message}`
);
}
}
}
/**
* PDA 扫ç <C3A7>定ä½<C3A4>收货明细:通过入库å<E2809C>•ID + 扫æ<C2AB><C3A6>æ<EFBFBD>¡ç <C3A7>快速定ä½<C3A4>收货明细ã€? * æ<>œç´¢ç­–ç•¥ï¼? * 1. 通过 entry_order_id â†?wms_entry_order_receiving 查出关è<C2B3>”çš?receiving_id 列表ï¼? * 2. 查出所有未绑定的收货明细(仅按 receiving_id IN + 排除已绑定过滤)ï¼? * 3. 收集明细çš?system_product_id,批é‡<C3A9>è°ƒç”?getStockDetails 获å<C2B7>–æ<E28093>¡ç <C3A7>ä¿¡æ<C2A1>¯ï¼? * 4. 在内存中é<C2AD><C3A9>历明细进行精确匹é…<C3A9>ï¼? * - è‹?barcode 为纯数字,优先按明细 ID 精确匹é…<C3A9>ï¼? * - å†<C3A5>按 getStockDetails 返回çš?barcodes[].barcode 精确匹é…<C3A9>商å“<C3A5>æ<EFBFBD>¡ç <C3A7>ï¼? * 5. 返回所有匹é…<C3A9>的明细列表(å<CB86>Œä¸€æ<E282AC>¡ç <C3A7>å<EFBFBD>¯èƒ½åŒ¹é…<C3A9>到多æ<C5A1>¡æ”¶è´§æ˜Žç»†ï¼‰ã€? * @param {number} entryOrderId 入库å<E2809C>•ID
* @param {string} barcode 扫æ<C2AB><C3A6>æ<EFBFBD>¡ç <C3A7>(商å“<C3A5>æ<EFBFBD>¡ç ?箱唛/托盘å”?明细IDï¼? * @return {Promise<Object>} 包å<E280A6>« codeã€<C3A3>message 与匹é…<C3A9>明细列è¡?data.list 的结果对è±? */
async scanDetail(entryOrderId, barcode) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const warehouseId = ctx.user?.store_id;
// å<>‚数校验
if (!warehouseId) {
return { code: 0, message: '用户未绑定仓�, data: null };
}
if (!entryOrderId || Number(entryOrderId) <= 0) {
return { code: 0, message: '入库å<E2809C>•IDä¸<C3A4>能为空', data: null };
}
if (!barcode || String(barcode).trim() === '') {
return { code: 0, message: '扫æ<C2AB><C3A6>æ<EFBFBD>¡ç <C3A7>ä¸<C3A4>能为空', data: null };
}
const normalizedBarcode = String(barcode).trim();
const normalizedEntryOrderId = Number(entryOrderId);
try {
// 1. 验è¯<C3A8>入库å<E2809C>•存在且属于当å‰<C3A5>仓库
const entryOrder = await ctx.model.EntryOrder.findOne({
where: {
id: normalizedEntryOrderId,
warehouse_id: warehouseId,
},
attributes: [ 'id' ],
raw: true,
});
if (!entryOrder) {
return { code: 0, message: '入库å<E2809C>•ä¸<C3A4>存在或无æ<C2A0>ƒè®¿é—?, data: null };
}
// 2. 通过 wms_entry_order_receiving 查出关è<C2B3>”çš?receiving_id 列表
const entryReceivingRows = await ctx.model.EntryOrderReceiving.findAll({
where: { entry_order_id: normalizedEntryOrderId },
attributes: [ 'receiving_id' ],
raw: true,
});
const receivingIds = entryReceivingRows.map(r => r.receiving_id).filter(Boolean);
if (receivingIds.length === 0) {
return { code: 0, message: '该入库å<EFBFBD>•尚未关è<EFBFBD>”æ”è´§å<EFBFBD>?, data: null };
}
// 排除已绑定的收货明细(wms_inbound_direct_log 中有记录且未软删除)
const notBoundCondition = app.Sequelize.literal(
'NOT EXISTS (SELECT 1 FROM wms_inbound_direct_log erb WHERE erb.receiving_detail_id = wms_receiving_detail.id AND erb.deleted_at IS NULL)'
);
// 3. 查出所有未绑定的收货明细(ä¸<C3A4>å†<C3A5>åœ?SQL 层å<E2809A>š barcode 模糊匹é…<C3A9>ï¼? const details = await ctx.model.ReceivingDetail.findAll({
where: {
[Op.and]: [
{ receiving_id: { [Op.in]: receivingIds } },
notBoundCondition,
],
},
raw: true,
});
if (details.length === 0) {
return { code: 0, message: '未找到å<C2B0>¯ç”¨çš„æ”¶è´§æ˜Žç»†', data: null };
}
// 4. 收集所有明细的 system_product_id,批é‡<C3A9>è°ƒç”?getStockDetails 获å<C2B7>–æ<E28093>¡ç <C3A7>
const stockIdSet = new Set();
for (const d of details) {
if (d.system_product_id != null) {
stockIdSet.add(Number(d.system_product_id));
}
}
const stockIds = [ ...stockIdSet ];
/** @type {Map<number, Object>} */
const stockDetailMap = new Map();
if (stockIds.length > 0) {
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId });
for (const sd of stockDetails) {
if (sd && sd.id != null) {
stockDetailMap.set(sd.id, sd);
}
}
}
// 5. 在内存中é<C2AD><C3A9>历明细,精确匹é…<C3A9>,收集所有命ä¸? const isNumericBarcode = /^\d+$/.test(normalizedBarcode);
const matchedDetails = [];
for (const detail of details) {
// 优先按明ç»?ID 精确匹é…<C3A9>(托盘唛头场景)
if (isNumericBarcode && detail.id === Number(normalizedBarcode)) {
matchedDetails.push(detail);
continue;
}
// 按商å“<C3A5>æ<EFBFBD>¡ç <C3A7>精确匹é…? const stockDetail = stockDetailMap.get(detail.system_product_id);
if (stockDetail && Array.isArray(stockDetail.barcodes)) {
const barcodeMatch = stockDetail.barcodes.some(
bc => bc.barcode === normalizedBarcode
);
if (barcodeMatch) {
matchedDetails.push(detail);
}
}
}
if (matchedDetails.length === 0) {
return { code: 0, message: '未找到匹é…<C3A9>的收货明细', data: null };
}
const list = matchedDetails.map(matchedDetail => ({
detail_id: matchedDetail.id,
receiving_id: matchedDetail.receiving_id,
barcode: matchedDetail.barcode || '',
product_name: matchedDetail.product_name || '',
actual_quantity: matchedDetail.actual_quantity || 0,
receiving_status: matchedDetail.receiving_status || '',
stock: stockDetailMap.get(Number(matchedDetail.system_product_id)) || null,
}));
return {
code: 200,
message: '查询æˆ<C3A6>功',
data: {
list,
total: list.length,
},
};
} catch (error) {
ctx.logger.error('[receiving.scanDetail] 扫ç <C3A7>定ä½<C3A4>收货明细失败', error);
return { code: 500, message: `æœ<EFBFBD>务器错è¯? ${error.message}`, data: null };
}
}
}
module.exports = ReceivingService;