From d1818ae0bf35bf562f997c7ed815b0568fdfd727 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 6 Jul 2026 22:19:34 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=20receiving.js=20?= =?UTF-8?q?=E7=BC=96=E7=A0=81=E6=8D=9F=E5=9D=8F=E5=AF=BC=E8=87=B4=E8=AF=AD?= =?UTF-8?q?=E6=B3=95=E9=94=99=E8=AF=AF=EF=BC=88use=5Fstatus=20=E2=86=92=20?= =?UTF-8?q?warehouse=5Fuse=5Fstatus=20=E9=87=8D=E5=81=9A=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systems/storage/receiving.js | 665 ++++++++++++++--------- 1 file changed, 417 insertions(+), 248 deletions(-) diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index c8232af..9817c79 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -12,9 +12,11 @@ function getStartOfDayMs(value) { } /** - * 判断到期日期是否早于当前日期ã€? * @param {string|Date|number} expiryDate 到期日期 + * 判断到期日期是否早于当前日期。 + * @param {string|Date|number} expiryDate 到期日期 * @param {Date} [currentDate=new Date()] 当前日期 - * @return {boolean} 是否已过æœ? */ + * @return {boolean} 是否已过期 + */ function isExpiryDateBeforeToday(expiryDate, currentDate = new Date()) { const expiryStartMs = getStartOfDayMs(expiryDate); if (expiryStartMs === null) return false; @@ -27,14 +29,17 @@ function isExpiryDateBeforeToday(expiryDate, currentDate = new Date()) { class ReceivingService extends Service { /** - * 查询收货单列表ã€? * @param {Object} where 动态筛选条ä»? * @param {Object} [pageParams] 分页参数 + * 查询收货单列表。 + * @param {Object} where 动态筛选条件 + * @param {Object} [pageParams] 分页参数 * @param {number} [pageParams.page=1] 页码 * @param {number} [pageParams.pageSize=20] 每页条数 * @param {Object} [sortParams] 排序参数 * @param {Object} [options] 额外选项 * @param {boolean} [options.filterDepleted=false] 是否过滤掉无可再用量的收货单 - * @param {number} [options.entry_order_id] 可选,按入库单商品交集过滤:只返回"至少有一条明细的 system_product_id 在入库单明细ä¸?的收货单 - * @return {Promise} 列表、分页与汇总信æ�? */ + * @param {number} [options.entry_order_id] 可选,按入库单商品交集过滤:只返回"至少有一条明细的 system_product_id 在入库单明细中"的收货单 + * @return {Promise} 列表、分页与汇总信息 + */ async getReceivingList(where, pageParams = {}, sortParams = {}, options = {}) { const { ctx, @@ -108,7 +113,7 @@ class ReceivingService extends Service { total_items: 0, }, }, - message: `筛选条件解析失è´? ${parsed.reason}`, + message: `筛选条件解析失败: ${parsed.reason}`, }; } parsedResult = parsed.result; @@ -174,7 +179,8 @@ class ReceivingService extends Service { }, ]; - // 可选过滤:排除无可再用量的收货å�? let filteredReceivingIds = null; + // 可选过滤:排除无可再用量的收货单 + let filteredReceivingIds = null; if (filterDepleted) { const candidateRows = await ctx.model.Receiving.findAll({ attributes: [ 'id' ], @@ -186,7 +192,8 @@ class ReceivingService extends Service { const candidateIds = candidateRows.map(r => r.id); if (candidateIds.length > 0) { - // 1. 候选收货单明细çš?actual_quantity 总和(按 receiving_id 分组ï¼? const detailSums = await ctx.model.ReceivingDetail.findAll({ + // 1. 候选收货单明细的 actual_quantity 总和(按 receiving_id 分组) + const detailSums = await ctx.model.ReceivingDetail.findAll({ attributes: [ 'receiving_id', [ Sequelize.fn('SUM', Sequelize.col('actual_quantity')), 'total_actual' ], @@ -200,7 +207,8 @@ class ReceivingService extends Service { totalActualMap[row.receiving_id] = Number(row.total_actual) || 0; } - // 2. 这些明细对应çš?committed 绑定量(æŒ?receiving_detail_id 分组ï¼? const detailIds = detailSums.length > 0 + // 2. 这些明细对应的 committed 绑定量(按 receiving_detail_id 分组) + const detailIds = detailSums.length > 0 ? (await ctx.model.ReceivingDetail.findAll({ attributes: [ 'id' ], where: { receiving_id: { [Op.in]: candidateIds } }, @@ -227,7 +235,7 @@ class ReceivingService extends Service { } } - // 3. 计算每个收货单的剩余可用é‡?= SUM(actual_quantity) - SUM(committed) + // 3. 计算每个收货单的剩余可用量 = SUM(actual_quantity) - SUM(committed) const idToDetailIdsMap = {}; if (detailIds.length > 0) { const detailIdRows = await ctx.model.ReceivingDetail.findAll({ @@ -249,7 +257,7 @@ class ReceivingService extends Service { remainingByReceivingId[receivingId] = totalActual - totalCommitted; } - // 过滤:只保留剩余可用é‡?> 0 的收货单 + // 过滤:只保留剩余可用量 > 0 的收货单 filteredReceivingIds = candidateIds.filter(id => remainingByReceivingId[id] > 0); } else { filteredReceivingIds = []; @@ -259,7 +267,7 @@ class ReceivingService extends Service { // 可选过滤:按入库单商品交集过滤(只返回 system_product_id 有交集的收货单) let intersectionFilteredIds = null; if (entryOrderId) { - // 1. 查该入库单的所æœ?entry_items â†?stock_id 集合 + // 1. 查该入库单的所有 entry_items → stock_id 集合 const entryItemRows = await ctx.model.EntryItems.findAll({ where: { order_id: entryOrderId }, attributes: [ 'stock_id' ], @@ -268,10 +276,10 @@ class ReceivingService extends Service { const entrySpIdSet = new Set(entryItemRows.map(r => r.stock_id).filter(Boolean)); if (entrySpIdSet.size === 0) { - // 入库单无明细 â†?不返回任何收货单 + // 入库单无明细 → 不返回任何收货单 intersectionFilteredIds = []; } else { - // 2. 查所有收货单明细,找å‡?system_product_id åœ?entrySpIdSet 中的收货å�?ID + // 2. 查所有收货单明细,找出 system_product_id 在 entrySpIdSet 中的收货单 ID const matchingDetailRows = await ctx.model.ReceivingDetail.findAll({ attributes: [ 'receiving_id' ], where: { @@ -284,10 +292,12 @@ class ReceivingService extends Service { } } - // 合并 filterDepleted å’?entry_order_id 的过滤结æž? let combinedFilteredIds = null; + // 合并 filterDepleted 和 entry_order_id 的过滤结果 + let combinedFilteredIds = null; if (filteredReceivingIds !== null || intersectionFilteredIds !== null) { if (filteredReceivingIds !== null && intersectionFilteredIds !== null) { - // 两个过滤都启ç”?â†?取交é›? const intersectionSet = new Set(intersectionFilteredIds); + // 两个过滤都启用 → 取交集 + const intersectionSet = new Set(intersectionFilteredIds); combinedFilteredIds = filteredReceivingIds.filter(id => intersectionSet.has(id)); } else if (filteredReceivingIds !== null) { combinedFilteredIds = filteredReceivingIds; @@ -296,7 +306,8 @@ class ReceivingService extends Service { } } - // 如果启用了过滤,用过滤后çš?ID 做最终查è¯? const finalWhere = combinedFilteredIds !== null + // 如果启用了过滤,用过滤后的 ID 做最终查询 + const finalWhere = combinedFilteredIds !== null ? { id: { [Op.in]: combinedFilteredIds } } : queryOptions.where; @@ -343,7 +354,8 @@ class ReceivingService extends Service { } const processedData = data.map(item => { - // 注意:wms_receiving 表中没有 locked_quantity 字段,total_quantity 为商品总数é‡? const availableQuantity = Math.max(0, item.total_quantity || 0); + // 注意:wms_receiving 表中没有 locked_quantity 字段,total_quantity 为商品总数量 + const availableQuantity = Math.max(0, item.total_quantity || 0); const lockRate = 0; const itemImages = images .filter(row => parseInt(row.business_id) === item.id) @@ -414,25 +426,30 @@ class ReceivingService extends Service { } } /** - * 获取收货单详情(主单 + 明细分页 + 图片)ã€? * @param {Object} data 请求ä½? * @param {number} data.id 收货单ID + * 获取收货单详情(主单 + 明细分页 + 图片)。 + * @param {Object} data 请求体 + * @param {number} data.id 收货单ID * @param {Object} data.pagination 分页参数 - * @return {Promise} 详情数据,明细中çš?space_id 会优先展示自定义库位名称,其次展示库位编码,并补å…?space_id_raw 兼容原始ID + * @return {Promise} 详情数据,明细中的 space_id 会优先展示自定义库位名称,其次展示库位编码,并补充 space_id_raw 兼容原始ID */ async getReceivingDetail(data) { const { id, pagination } = data; const { page, pageSize } = pagination; const { ctx, app } = this; const { Op } = app.Sequelize; - // 获取用户仓库ID,增加错误处ç�? const warehouseId = ctx.user?.store_id; + // 获取用户仓库ID,增加错误处理 + const warehouseId = ctx.user?.store_id; if (!warehouseId) { - return { code: 0, message: '用户未绑定仓åº?, data: {} }; + return { code: 0, message: '用户未绑定仓库', data: {} }; } try { - // 1. 查询收货单主è¡? const receiving = await app.model.Receiving.findOne({ where: { id, warehouse_id: warehouseId } }); + // 1. 查询收货单主表 + const receiving = await app.model.Receiving.findOne({ where: { id, warehouse_id: warehouseId } }); if (!receiving) { return { code: 0, message: '无记录或无权访问', data: {} }; } - // 2. 查询收货单明ç»?按分é¡? const receivingItems = await app.model.ReceivingDetail.findAll({ + // 2. 查询收货单明细,按分页 + const receivingItems = await app.model.ReceivingDetail.findAll({ where: { receiving_id: id }, include: [{ model: app.model.LocationSpace, @@ -457,7 +474,9 @@ class ReceivingService extends Service { // 3. 获取明细ID数组 const receivingItemsIds = receivingItems.map(item => item.id); - // 4. 查询明细图片(如果明细数量大äº?ï¼? const itemImagesMap = {}; // 用于存储每个明细的图ç‰? if (receivingItemsIds.length > 0) { + // 4. 查询明细图片(如果明细数量大于0) + const itemImagesMap = {}; // 用于存储每个明细的图片 + if (receivingItemsIds.length > 0) { const receivingItemsImages = await ctx.model.FileReference.findAll({ where: { business_type: 'receivingItem', @@ -470,7 +489,8 @@ class ReceivingService extends Service { required: true, }], }); - // 将图片按明细ID分组,并转换为前端可直接使用的链æŽ? for (const image of receivingItemsImages) { + // 将图片按明细ID分组,并转换为前端可直接使用的链接 + for (const image of receivingItemsImages) { if (!itemImagesMap[image.business_id]) { itemImagesMap[image.business_id] = []; } @@ -496,7 +516,8 @@ class ReceivingService extends Service { images: itemImagesMap[item.id] || [], }; }); - // 6. 查询主表的图ç‰? const receivingImages = await ctx.model.FileReference.findAll({ + // 6. 查询主表的图片 + const receivingImages = await ctx.model.FileReference.findAll({ where: { business_type: 'receiving', business_id: id, @@ -509,7 +530,8 @@ class ReceivingService extends Service { }], }); // 7. 组装返回数据 - receiving.dataValues.details = items; // 包含图片链接的明细数æ�? receiving.dataValues.images = receivingImages.map(image => ({ + receiving.dataValues.details = items; // 包含图片链接的明细数据 + receiving.dataValues.images = receivingImages.map(image => ({ id: image.file_id, url: image.file.file_url, })); // 包含主表图片链接 @@ -517,12 +539,14 @@ class ReceivingService extends Service { return { code: 200, message: '查询成功', data: { receiving } }; } catch (error) { - console.error('获取收货单详情失è´?', error); - return { code: 500, message: '服务器错è¯?, data: {} }; + console.error('获取收货单详情失败:', error); + return { code: 500, message: '服务器错误', data: {} }; } } /** - * 批量作废收货单ã€? * @param {Object} data 请求ä½? * @param {number[]} data.ids 收货单ID数组 + * 批量作废收货单。 + * @param {Object} data 请求体 + * @param {number[]} data.ids 收货单ID数组 * @return {Promise} 作废处理结果 */ async batchCancelReceiving(data) { @@ -531,7 +555,8 @@ class ReceivingService extends Service { const { Op } = ctx.model.Sequelize; const warehouse_id = ctx.user.store_id; try { - // 先查询这些单据是否都存在且状态允许作åº? const receivings = await ctx.model.Receiving.findAll({ where: { id: { [Op.in]: ids }, warehouse_id } }); + // 先查询这些单据是否都存在且状态允许作废 + const receivings = await ctx.model.Receiving.findAll({ where: { id: { [Op.in]: ids }, warehouse_id } }); if (receivings.length !== ids.length) { return { code: 0, message: '部分单据不存在或无权访问', data: {} }; } @@ -569,13 +594,16 @@ class ReceivingService extends Service { return { code: 200, message: '批量作废成功', data: {} }; } catch (error) { - console.error('批量作废收货单失è´?', error); - return { code: 500, message: '服务器错è¯?, data: {} }; + console.error('批量作废收货单失败:', error); + return { code: 500, message: '服务器错误', data: {} }; } } /** - * 驳回收货单:将已完成收货单恢复为收货中,记录审核人信息与驳回理由ã€? * @param {Object} data 请求ä½? * @param {number[]} data.ids 收货单ID数组 - * @param {string} [data.remark] 驳回理由(覆盖原备注ï¼? * @return {Promise} 操作结果 + * 驳回收货单:将已完成收货单恢复为收货中,记录审核人信息与驳回理由。 + * @param {Object} data 请求体 + * @param {number[]} data.ids 收货单ID数组 + * @param {string} [data.remark] 驳回理由(覆盖原备注) + * @return {Promise} 操作结果 */ async rejectReceiving(data) { const { ids, remark } = data; @@ -690,15 +718,15 @@ class ReceivingService extends Service { messageType: 'text', businessName: 'receiving', event: 'receiving_rejected', - title: `收货å�?${item.receiving_number || item.id} 已被驳回`, + title: `收货单 ${item.receiving_number || item.id} 已被驳回`, content: [ `驳回人:${reviewerName || '未知'}`, - `驳回理由ï¼?{updateData.remark || 'æ—?}`, - `收货单IDï¼?{item.id || ''}`, - `收货单号ï¼?{item.receiving_number || 'æ—?}`, - `收货创建人:${item.creator && item.creator.name || 'æ—?}`, - '请及时处理重新提交完成收货ã€?, - ].join('\n') + 'ã€?, + `驳回理由:${updateData.remark || '无'}`, + `收货单ID:${item.id || ''}`, + `收货单号:${item.receiving_number || '无'}`, + `收货创建人:${item.creator && item.creator.name || '无'}`, + '请及时处理重新提交完成收货。', + ].join('\n') + '。', businessId: item.id || ids[0], subject: { id: warehouse_id, @@ -731,13 +759,16 @@ class ReceivingService extends Service { return { code: 200, message: '驳回成功', data: { count: ids.length } }; } catch (error) { - ctx.logger.error('[receiving.rejectReceiving] 驳回收货单失è´?, error); - return { code: 500, message: '服务器错è¯?, data: {} }; + ctx.logger.error('[receiving.rejectReceiving] 驳回收货单失败', error); + return { code: 500, message: '服务器错误', data: {} }; } } /** - * 批量审核收货单:校验所有单据的状态后,用事务批量更新审核信息ã€? * 任意一张不符合条件则整批失败并回滚ã€? * @param {Object} data 请求ä½? * @param {number[]} data.ids 收货单ID数组 + * 批量审核收货单:校验所有单据的状态后,用事务批量更新审核信息。 + * 任意一张不符合条件则整批失败并回滚。 + * @param {Object} data 请求体 + * @param {number[]} data.ids 收货单ID数组 * @return {Promise} 操作结果 */ async reviewReceiving(data) { @@ -752,7 +783,7 @@ class ReceivingService extends Service { const normalizedIds = Array.from(new Set(ids.map(Number).filter(n => Number.isFinite(n) && n > 0))); if (normalizedIds.length === 0) { - return { code: 0, message: '收货单ID格式不正ç¡?, data: {} }; + return { code: 0, message: '收货单ID格式不正确', data: {} }; } const reviewerName = String(ctx.user?.employees_name || '').trim() || null; @@ -776,28 +807,29 @@ class ReceivingService extends Service { const errors = []; for (const r of receivings) { if (r.status !== 'completed') { - errors.push(`收货å�?${r.receiving_number || r.id} 状态非收货完成`); + errors.push(`收货单 ${r.receiving_number || r.id} 状态非收货完成`); } if (r.detail_status !== 'all_matched') { - errors.push(`收货å�?${r.receiving_number || r.id} 明细未全部匹配`); + errors.push(`收货单 ${r.receiving_number || r.id} 明细未全部匹配`); } if (r.storage_status !== 'none') { - errors.push(`收货å�?${r.receiving_number || r.id} 已存在入库记录`); + errors.push(`收货单 ${r.receiving_number || r.id} 已存在入库记录`); } if (!r.store_id) { - errors.push(`收货å�?${r.receiving_number || r.id} 未绑定货主`); + errors.push(`收货单 ${r.receiving_number || r.id} 未绑定货主`); } if (Number(r.is_review) === 1) { - errors.push(`收货å�?${r.receiving_number || r.id} 已审核,无需重复操作`); + errors.push(`收货单 ${r.receiving_number || r.id} 已审核,无需重复操作`); } } if (errors.length > 0) { await transaction.rollback(); - return { code: 0, message: errors.join('ï¼?), data: {} }; + return { code: 0, message: errors.join(';'), data: {} }; } - // MySQL 二次状态核实:确保 WHERE 条件精准匹配,防止并发竞äº? const updateResult = await ctx.model.Receiving.update( + // MySQL 二次状态核实:确保 WHERE 条件精准匹配,防止并发竞争 + const updateResult = await ctx.model.Receiving.update( { is_review: 1, reviewer_name: reviewerName, @@ -822,7 +854,7 @@ class ReceivingService extends Service { if (affectedRows !== normalizedIds.length) { await transaction.rollback(); - return { code: 0, message: '收货单审核状态已变化,请刷新后重è¯?, data: {} }; + return { code: 0, message: '收货单审核状态已变化,请刷新后重试', data: {} }; } // 写操作日志(失败不影响业务) @@ -850,7 +882,8 @@ class ReceivingService extends Service { await transaction.commit(); - // 逐单发送审核完成通知(文å­?+ 文件,失败不影响业务ï¼? const reviewer = { + // 逐单发送审核完成通知(文字 + 文件,失败不影响业务) + const reviewer = { employees_id: reviewerEmployeeId, employees_name: reviewerName, name: reviewerName, @@ -885,7 +918,7 @@ class ReceivingService extends Service { failedCount: Number(textResult && textResult.data && textResult.data.failedCount || 0), }); } catch (textErr) { - ctx.logger.error('[receiving.reviewReceiving] 文字通知发送失è´?, { + ctx.logger.error('[receiving.reviewReceiving] 文字通知发送失败', { receiving_id: r.id, error: textErr.message, }); @@ -961,7 +994,7 @@ class ReceivingService extends Service { }); } - // 3. 发送文件通知(仅å½?Excel 上传成功时) + // 3. 发送文件通知(仅当 Excel 上传成功时) if (reviewReport) { try { const fileResult = await this.sendReviewNotice({ receiving: receivingSnapshot, reviewer, reviewReport }); @@ -976,7 +1009,7 @@ class ReceivingService extends Service { reportUrl: reviewReport.url || reviewReport.cdnUrl || reviewReport.cosUrl || '', }); } catch (fileErr) { - ctx.logger.error('[receiving.reviewReceiving] 文件通知发送失è´?, { + ctx.logger.error('[receiving.reviewReceiving] 文件通知发送失败', { receiving_id: r.id, error: fileErr.message, }); @@ -993,14 +1026,17 @@ class ReceivingService extends Service { return { code: 200, message: '审核成功', data: { count: normalizedIds.length } }; } catch (error) { await transaction.rollback(); - ctx.logger.error('[receiving.reviewReceiving] 审核收货单失è´?, error); + ctx.logger.error('[receiving.reviewReceiving] 审核收货单失败', error); return { code: 500, message: `审核失败: ${error.message}`, data: {} }; } } /** - * 构建审核完成 Excel 报表 sheets,复用收货完成报表结构,但标æ³?审核äº?而非"完成äº?ã€? * @param {Object} options 构建参数 - * @param {Object} options.receiving 收货单(需å�?details 数组ï¼? * @param {Object} [options.reviewer={}] 审核人信æ�? * @param {Object} [options.stats={}] 明细统计 + * 构建审核完成 Excel 报表 sheets,复用收货完成报表结构,但标注"审核人"而非"完成人"。 + * @param {Object} options 构建参数 + * @param {Object} options.receiving 收货单(需含 details 数组) + * @param {Object} [options.reviewer={}] 审核人信息 + * @param {Object} [options.stats={}] 明细统计 * @param {Map} [options.detailImageMap] 明细图片 Map(key=detail.id字符串) * @param {Array} [options.receivingImages] 收货单主图片数组 * @return {Array} sheets 数组 @@ -1026,7 +1062,7 @@ class ReceivingService extends Service { const detailColumns = [ '序号', '商品名称', '条码', '数量', '重量', '箱数', '托数', - '批次å�?, '生产日期', '到期日期', '备注', '图片链接', '图片', + '批次号', '生产日期', '到期日期', '备注', '图片链接', '图片', ]; const detailImageColumnIndex = detailColumns.length; const maxDetailImageCount = Math.max( @@ -1079,10 +1115,10 @@ class ReceivingService extends Service { [ '总明细数', stats.total_details || details.length ], [ '已匹配明细数', stats.matched_details || 0 ], [ '未匹配明细数', stats.unmatched_details || 0 ], - [ '总数é‡?, stats.total_quantity || 0 ], - [ '总箱æ•?, receiving && receiving.total_boxes ], + [ '总数量', stats.total_quantity || 0 ], + [ '总箱数', receiving && receiving.total_boxes ], [ '总托盘数', receiving && receiving.total_pallets ], - [ '审核äº?, reviewerName ], + [ '审核人', reviewerName ], [ '审核时间', this.formatReportDate(reviewedAt) ], [ '备注', receiving && receiving.remark ], ].forEach(([ field, value ]) => { @@ -1093,7 +1129,7 @@ class ReceivingService extends Service { }); if (mainImageUrls.length === 0) { - pushRow([ '收货图片', 'æ—? ], { toCol: 2, style: { alignment: { vertical: 'top', wrapText: true } } }); + pushRow([ '收货图片', '无' ], { toCol: 2, style: { alignment: { vertical: 'top', wrapText: true } } }); } else { const summaryLinkCell = buildLinkCell(mainImageUrls); const imagePlaceholders = Array(Math.max(mainImageUrls.length, 1)).fill(''); @@ -1119,7 +1155,7 @@ class ReceivingService extends Service { }); if (details.length === 0) { - pushRow([ '', '', '无明ç»? ], { toCol: detailColumns.length, style: { alignment: { vertical: 'top', wrapText: true } } }); + pushRow([ '', '', '无明细' ], { toCol: detailColumns.length, style: { alignment: { vertical: 'top', wrapText: true } } }); } else { details.forEach((detail, index) => { const imgs = Array.isArray(detailImageMap.get(String(detail.id))) @@ -1173,7 +1209,13 @@ class ReceivingService extends Service { } /** - * 发送审核完成通知(receiving_reviewed),支持文字/文件两种类型ã€? * @param {Object} options 发送参æ•? * @param {Object} options.receiving 收货单快ç…? * @param {Object} [options.reviewer={}] 审核人信æ�? * @param {Object|null} [options.reviewReport=null] 审核报表(有值则发文件通知ï¼? * @return {Promise} 发送结æž? */ + * 发送审核完成通知(receiving_reviewed),支持文字/文件两种类型。 + * @param {Object} options 发送参数 + * @param {Object} options.receiving 收货单快照 + * @param {Object} [options.reviewer={}] 审核人信息 + * @param {Object|null} [options.reviewReport=null] 审核报表(有值则发文件通知) + * @return {Promise} 发送结果 + */ async sendReviewNotice({ receiving, reviewer = {}, @@ -1203,12 +1245,12 @@ class ReceivingService extends Service { ).trim(); const content = [ - `收货单号ï¼?{receivingNumber}`, - `货主ï¼?{receiving.store_name || '未知'}`, + `收货单号:${receivingNumber}`, + `货主:${receiving.store_name || '未知'}`, `审核人:${reviewerName || '未知'}`, - `审核时间ï¼?{this.formatReportDate(receiving.updated_at || new Date())}`, - `备注ï¼?{receiving.remark || 'æ—?}`, - ].join('\n') + 'ã€?; + `审核时间:${this.formatReportDate(receiving.updated_at || new Date())}`, + `备注:${receiving.remark || '无'}`, + ].join('\n') + '。'; return await noticeService.send({ warehouseId, @@ -1216,7 +1258,7 @@ class ReceivingService extends Service { messageType: reportUrl ? 'file' : 'text', businessName: 'receiving', event: 'receiving_reviewed', - title: `收货å�?{receivingNumber}审核完成`, + title: `收货单${receivingNumber}审核完成`, content, url: reportUrl || undefined, fileName: reportUrl ? reportFileName : '', @@ -1270,10 +1312,13 @@ class ReceivingService extends Service { operator = 'eq', value, type, } = condition; - // 处理字段å�? const fieldName = condition.field || fieldKey; + // 处理字段名 + const fieldName = condition.field || fieldKey; - // 特殊值处ç�? const processedValue = this.processConditionValue(value, type); - // 根据操作符构建条ä»? switch (operator.toLowerCase()) { + // 特殊值处理 + const processedValue = this.processConditionValue(value, type); + // 根据操作符构建条件 + switch (operator.toLowerCase()) { case 'eq': return { [fieldName]: processedValue, @@ -1288,8 +1333,9 @@ class ReceivingService extends Service { case 'contains': case 'like': - // 处理多值情å†? if (Array.isArray(processedValue) && processedValue.length > 0) { - // 多个值使ç”?OR 连接 + // 处理多值情况 + if (Array.isArray(processedValue) && processedValue.length > 0) { + // 多个值使用 OR 连接 return { [Sequelize.Op.or]: processedValue.map(val => ({ [fieldName]: { @@ -1298,14 +1344,16 @@ class ReceivingService extends Service { })), }; } - // 单个值正常处ç�? return { + // 单个值正常处理 + return { [fieldName]: { [Sequelize.Op.like]: `%${processedValue}%`, }, }; case 'startswith': - // 处理多值情å†? if (Array.isArray(processedValue) && processedValue.length > 0) { + // 处理多值情况 + if (Array.isArray(processedValue) && processedValue.length > 0) { return { [Sequelize.Op.or]: processedValue.map(val => ({ [fieldName]: { @@ -1321,7 +1369,8 @@ class ReceivingService extends Service { }; case 'endswith': - // 处理多值情å†? if (Array.isArray(processedValue) && processedValue.length > 0) { + // 处理多值情况 + if (Array.isArray(processedValue) && processedValue.length > 0) { return { [Sequelize.Op.or]: processedValue.map(val => ({ [fieldName]: { @@ -1425,14 +1474,18 @@ class ReceivingService extends Service { }; default: - // 默认使用等于操作ç¬? return { + // 默认使用等于操作符 + return { [fieldName]: processedValue, }; } } /** - * 处理条件å€? * @param {any} value - 原始å€? * @param {string} type - 字段类型 - * @return {any} 处理后的å€? */ + * 处理条件值 + * @param {any} value - 原始值 + * @param {string} type - 字段类型 + * @return {any} 处理后的值 + */ processConditionValue(value, type) { const { service } = this; if (value === undefined || value === null) { @@ -1451,14 +1504,16 @@ class ReceivingService extends Service { return value; case 'date': - // 单个日期,根据业务需求决定是开始还是结束时é—? // 通常是开始时间(00:00:00ï¼? return service.main.normalizeDate(value, false); + // 单个日期,根据业务需求决定是开始还是结束时间 + // 通常是开始时间(00:00:00) + return service.main.normalizeDate(value, false); case 'daterange': // 处理日期范围:数组的第一个元素是开始时间,第二个元素是结束时间 if (Array.isArray(value) && value.length === 2) { const [ startDate, endDate ] = value; return [ - startDate ? service.main.normalizeDate(startDate, false) : null, // 开始时间设ä¸?0:00:00 + startDate ? service.main.normalizeDate(startDate, false) : null, // 开始时间设为00:00:00 endDate ? service.main.normalizeDate(endDate, true) : null, // 结束时间设为23:59:59 ]; } @@ -1523,8 +1578,10 @@ class ReceivingService extends Service { } /** - * 创建收货单并生成收货单号ã€? * @param {Object} data 创建参数 - * @return {Promise} 新建结果(含 id ä¸?receiving_numberï¼? */ + * 创建收货单并生成收货单号。 + * @param {Object} data 创建参数 + * @return {Promise} 新建结果(含 id 与 receiving_number) + */ async create(data) { const { delivery_method, @@ -1552,10 +1609,13 @@ class ReceivingService extends Service { id: creator_id, }; - // 2. 生成收货单号。注意:`wms_receiving.receiving_number` 在数据库中是全局唯一索引ï¼? // 不能æŒ?warehouse_id 各自ä»?001 开始,否则跨仓会撞号;并发创建时也需要重试兜底ã€? const now = new Date(); + // 2. 生成收货单号。注意:`wms_receiving.receiving_number` 在数据库中是全局唯一索引, + // 不能按 warehouse_id 各自从 001 开始,否则跨仓会撞号;并发创建时也需要重试兜底。 + const now = new Date(); const prefix = this.buildReceivingNumberPrefix(now); - // 3. 获取店铺名称(如果有货主ï¼? let store_name = null; + // 3. 获取店铺名称(如果有货主) + let store_name = null; if (store_id) { const store = await app.model.StoreWarehouse.findOne({ where: { @@ -1569,7 +1629,8 @@ class ReceivingService extends Service { } } - // 4. 创建收货单记录(并发下若撞到唯一键则自动重试取下一个号ï¼? const maxCreateRetries = 5; + // 4. 创建收货单记录(并发下若撞到唯一键则自动重试取下一个号) + const maxCreateRetries = 5; let result = null; let lastCreateError = null; @@ -1655,7 +1716,8 @@ class ReceivingService extends Service { } /** - * 按ID修改收货单基础信息ã€? * @param {Object} data 修改参数 + * 按ID修改收货单基础信息。 + * @param {Object} data 修改参数 * @param {number} data.id 收货单ID * @return {Promise} 修改结果 */ @@ -1681,7 +1743,7 @@ class ReceivingService extends Service { if (!warehouseId) { return { code: 400, - message: '用户未绑定仓åº?, + message: '用户未绑定仓库', }; } @@ -1709,7 +1771,7 @@ class ReceivingService extends Service { await transaction.rollback(); return { code: 404, - message: '收货单不存在或无权访é—?, + message: '收货单不存在或无权访问', }; } @@ -1839,11 +1901,11 @@ class ReceivingService extends Service { code: 200, id: receivingId, receiving_number: receiving.receiving_number, - message: '收货单修改成åŠ?, + message: '收货单修改成功', }; } catch (error) { await transaction.rollback(); - ctx.logger.error('[receiving.save] 修改收货单失è´?, error); + ctx.logger.error('[receiving.save] 修改收货单失败', error); return { code: 0, message: `修改失败: ${error.message}`, @@ -1852,8 +1914,13 @@ class ReceivingService extends Service { } /** - * 绑定收货单货主ã€? * 规则ï¼? * 1. 已取消收货单禁止绑定ï¼? * 2. 收货ä¸?已完成状态下,若已存在货主,则禁止重复绑定; - * 3. 仅允许绑定与当前仓库存在有效签约关系的货主ã€? * @param {Object} data 请求ä½? * @param {number} data.id 收货单ID + * 绑定收货单货主。 + * 规则: + * 1. 已取消收货单禁止绑定; + * 2. 收货中/已完成状态下,若已存在货主,则禁止重复绑定; + * 3. 仅允许绑定与当前仓库存在有效签约关系的货主。 + * @param {Object} data 请求体 + * @param {number} data.id 收货单ID * @param {number} data.store_id 货主ID * @return {Promise} 绑定结果 */ @@ -1867,7 +1934,7 @@ class ReceivingService extends Service { if (!warehouseId) { return { code: 400, - message: '用户未绑定仓åº?, + message: '用户未绑定仓库', }; } @@ -1902,7 +1969,7 @@ class ReceivingService extends Service { await transaction.rollback(); return { code: 404, - message: '收货单不存在或无权访é—?, + message: '收货单不存在或无权访问', }; } @@ -1989,7 +2056,7 @@ class ReceivingService extends Service { }; } catch (error) { await transaction.rollback(); - ctx.logger.error('绑定收货单货主失è´?', error); + ctx.logger.error('绑定收货单货主失败:', error); return { code: 500, message: `绑定货主失败: ${error.message}`, @@ -1998,7 +2065,9 @@ class ReceivingService extends Service { } /** - * 查询单个收货单完整信息(含明细、图片)ã€? * @param {Object} data 请求ä½? * @param {number} data.id 收货单ID + * 查询单个收货单完整信息(含明细、图片)。 + * @param {Object} data 请求体 + * @param {number} data.id 收货单ID * @return {Promise} 单据详情 */ async get(data) { @@ -2006,13 +2075,15 @@ class ReceivingService extends Service { const { ctx, app } = this; const { Op } = app.Sequelize; - // 获取用户仓库ID,增加错误处ç�? const warehouseId = ctx.user?.store_id; + // 获取用户仓库ID,增加错误处理 + const warehouseId = ctx.user?.store_id; if (!warehouseId) { - return { code: 0, message: '用户未绑定仓åº?, data: {} }; + return { code: 0, message: '用户未绑定仓库', data: {} }; } try { - // 1. 查询收货单主è¡? const receiving = await app.model.Receiving.findOne({ + // 1. 查询收货单主表 + const receiving = await app.model.Receiving.findOne({ where: { id, warehouse_id: warehouseId, @@ -2032,12 +2103,14 @@ class ReceivingService extends Service { attributes: [ 'real_name' ], required: false, }], - // 不需要order,因为根据id查询已经是唯一çš? }); + // 不需要order,因为根据id查询已经是唯一的 + }); if (!receiving) { return { code: 0, message: '无记录或无权访问', data: {} }; } - // 2. 查询收货单明ç»? const receivingItems = await app.model.ReceivingDetail.findAll({ + // 2. 查询收货单明细 + const receivingItems = await app.model.ReceivingDetail.findAll({ where: { receiving_id: id, }, @@ -2048,12 +2121,15 @@ class ReceivingService extends Service { attributes: [ 'space_code', 'custom_barcode', 'custom_name' ], }, ], - order: [[ 'id', 'DESC' ]], // 保持倒序,最新在å‰? }); + order: [[ 'id', 'DESC' ]], // 保持倒序,最新在前 + }); // 3. 获取明细ID数组 const receivingItemsIds = receivingItems.map(item => item.id); - // 4. 查询明细图片(如果明细数量大äº?ï¼? const itemImagesMap = {}; // 用于存储每个明细的图ç‰? if (receivingItemsIds.length > 0) { + // 4. 查询明细图片(如果明细数量大于0) + const itemImagesMap = {}; // 用于存储每个明细的图片 + if (receivingItemsIds.length > 0) { const receivingItemsImages = await ctx.model.FileReference.findAll({ where: { business_type: 'receivingItem', @@ -2093,7 +2169,8 @@ class ReceivingService extends Service { }; }); - // 6. 查询主表的图ç‰? const receivingImages = await ctx.model.FileReference.findAll({ + // 6. 查询主表的图片 + const receivingImages = await ctx.model.FileReference.findAll({ where: { business_type: 'receiving', business_id: id, @@ -2108,7 +2185,9 @@ class ReceivingService extends Service { // 7. 组装返回数据 const result = { - ...receiving.toJSON(), // 使用toJSON()确保获得纯对è±? details: items, // 包含图片的明细数æ�? images: receivingImages.map(item => ({ + ...receiving.toJSON(), // 使用toJSON()确保获得纯对象 + details: items, // 包含图片的明细数据 + images: receivingImages.map(item => ({ url: item.file.file_url, id: item.file_id, })), @@ -2117,16 +2196,19 @@ class ReceivingService extends Service { return { code: 200, message: '成功', data: result }; } catch (error) { - console.error('获取收货单详情失è´?', error); - return { code: 500, message: '服务器错è¯?, data: {} }; + console.error('获取收货单详情失败:', error); + return { code: 500, message: '服务器错误', data: {} }; } } /** - * 向收货单新增一条收货明细ã€? * @param {Object} data 请求ä½? * @param {number} data.receiving_id 收货单ID + * 向收货单新增一条收货明细。 + * @param {Object} data 请求体 + * @param {number} data.receiving_id 收货单ID * @param {Object} [data.item] 可选的明细字段 * @return {Promise} 明细列表与默认选中ID - * @description 未传 `item` 时,保持原有空白明细创建行为;传å…?`item` 时,合并默认值后交由 Sequelize 校验与写入,并由服务端覆ç›?`receiving_id` ä¸?`creator_id`ã€? */ + * @description 未传 `item` 时,保持原有空白明细创建行为;传入 `item` 时,合并默认值后交由 Sequelize 校验与写入,并由服务端覆盖 `receiving_id` 与 `creator_id`。 + */ async addDetail(data) { const ctx = this.ctx; const { receiving_id } = data; @@ -2137,7 +2219,8 @@ class ReceivingService extends Service { // 获取当前用户信息 const creator_id = ctx.user.employees_id; const warehouse_id = ctx.user.store_id; - // 验证收货单是否存åœ? const receiving = await ctx.model.Receiving.findOne({ + // 验证收货单是否存在 + const receiving = await ctx.model.Receiving.findOne({ where: { id: receiving_id, warehouse_id }, }); @@ -2148,7 +2231,8 @@ class ReceivingService extends Service { }; } - // 验证收货单状态是否允许添加明ç»? if (receiving.status !== 'receiving') { + // 验证收货单状态是否允许添加明细 + if (receiving.status !== 'receiving') { return { code: 400, message: '收货单状态不允许添加明细', @@ -2158,7 +2242,7 @@ class ReceivingService extends Service { try { const defaultDetail = { receiving_id, - product_name: '新商å“?, + product_name: '新商品', barcode: '', actual_quantity: 0, box_quantity: 0, @@ -2175,7 +2259,8 @@ class ReceivingService extends Service { creator_id, }; - // 允许前端传入可选明细字段,但服务端字段始终覆盖ã€? const newDetail = await ctx.model.ReceivingDetail.create({ + // 允许前端传入可选明细字段,但服务端字段始终覆盖。 + const newDetail = await ctx.model.ReceivingDetail.create({ ...defaultDetail, ...item, receiving_id, @@ -2188,7 +2273,8 @@ class ReceivingService extends Service { order: [[ 'id', 'DESC' ]], }); - // 格式化返回数æ�? const formattedDetails = allDetails.map(detail => { + // 格式化返回数据 + const formattedDetails = allDetails.map(detail => { const detailData = detail.toJSON(); // 处理product_snapshot @@ -2200,7 +2286,8 @@ class ReceivingService extends Service { } } - // 如果有关联的系统商品,可以合并信æ�? if (detailData.system_product) { + // 如果有关联的系统商品,可以合并信息 + if (detailData.system_product) { detailData.system_product_info = detailData.system_product; } @@ -2249,7 +2336,10 @@ class ReceivingService extends Service { } /** - * 绑定或改绑收货单明细的系统商品ã€? * @param {Object} data 请求ä½? * @param {number} data.detail_id 收货单明细ID(兼å®?`id`ï¼? * @param {number} data.system_product_id 商品ID + * 绑定或改绑收货单明细的系统商品。 + * @param {Object} data 请求体 + * @param {number} data.detail_id 收货单明细ID(兼容 `id`) + * @param {number} data.system_product_id 商品ID * @return {Promise} 绑定结果 */ async bindDetailProduct(data) { @@ -2261,7 +2351,7 @@ class ReceivingService extends Service { if (!warehouseId) { return { code: 400, - message: '用户未绑定仓åº?, + message: '用户未绑定仓库', }; } @@ -2339,14 +2429,15 @@ class ReceivingService extends Service { if (!stockWarehouse) { return { code: 404, - message: '商品不存在或不属于当前仓åº?, + message: '商品不存在或不属于当前仓库', }; } const productStoreId = Number(stockWarehouse.store_stock?.store_id || 0); const receivingStoreId = Number(receivingDetail.receiving?.store_id || 0); - // 货主校验:收货单已有货主时,只允许绑定同一货主的商å“? if (receivingStoreId > 0 && productStoreId > 0 && receivingStoreId !== productStoreId) { + // 货主校验:收货单已有货主时,只允许绑定同一货主的商品 + if (receivingStoreId > 0 && productStoreId > 0 && receivingStoreId !== productStoreId) { return { code: 400, message: '该商品不属于当前收货单的货主,不允许绑定', @@ -2380,7 +2471,7 @@ class ReceivingService extends Service { } } - const productName = stockWarehouse.item_name || stockWarehouse.name || receivingDetail.product_name || '未命名商å“?; + const productName = stockWarehouse.item_name || stockWarehouse.name || receivingDetail.product_name || '未命名商品'; const updateData = { system_product_id: systemProductId, product_name: productName, @@ -2405,7 +2496,8 @@ class ReceivingService extends Service { }); barcodes.push(detailBarcode); } catch (barcodeErr) { - // 唯一索引冲突说明条码已被其他商品占用,仅记录日志不阻断业åŠ? ctx.logger.warn('[receiving.bindDetailProduct] 自动新增条码失败(可能已存在ï¼?, barcodeErr); + // 唯一索引冲突说明条码已被其他商品占用,仅记录日志不阻断业务 + ctx.logger.warn('[receiving.bindDetailProduct] 自动新增条码失败(可能已存在)', barcodeErr); } } @@ -2468,7 +2560,7 @@ class ReceivingService extends Service { data: responseData, }; } catch (error) { - ctx.logger.error('绑定收货单明细商品失è´?', error); + ctx.logger.error('绑定收货单明细商品失败:', error); return { code: 500, message: `绑定商品失败: ${error.message}`, @@ -2495,11 +2587,12 @@ class ReceivingService extends Service { if (!detail) { return { code: 404, - message: '明细不存åœ?, + message: '明细不存在', }; } - // 验证关联的收货单状态是否允许修æ”? if (detail.receiving && detail.receiving.status !== 'receiving') { + // 验证关联的收货单状态是否允许修改 + if (detail.receiving && detail.receiving.status !== 'receiving') { return { code: 400, message: '收货单状态不允许修改明细', @@ -2522,7 +2615,8 @@ class ReceivingService extends Service { } try { - // 如果需要处理商品匹é…? if (updateData.barcode && updateData.barcode.trim()) { + // 如果需要处理商品匹配 + if (updateData.barcode && updateData.barcode.trim()) { // 尝试根据条码匹配系统商品 const systemProduct = await ctx.model.StockWarehouse.findOne({ where: { barcode: updateData.barcode }, @@ -2540,13 +2634,15 @@ class ReceivingService extends Service { images: systemProduct.images ? JSON.parse(systemProduct.images) : [], }); - // 如果用户没有输入商品名称,使用系统商品名ç§? if (!updateData.product_name) { + // 如果用户没有输入商品名称,使用系统商品名称 + if (!updateData.product_name) { updateData.product_name = systemProduct.name; } } } - // 处理数量类型的转æ�? if (updateData.actual_quantity !== undefined) { + // 处理数量类型的转换 + if (updateData.actual_quantity !== undefined) { updateData.actual_quantity = parseInt(updateData.actual_quantity) || 0; } @@ -2565,7 +2661,8 @@ class ReceivingService extends Service { if (updateData.stored_quantity !== undefined) { updateData.stored_quantity = parseInt(updateData.stored_quantity) || 0; - // 根据入库数量更新入库状æ€? if (updateData.stored_quantity >= updateData.actual_quantity) { + // 根据入库数量更新入库状态 + if (updateData.stored_quantity >= updateData.actual_quantity) { updateData.storage_status = 'all'; } else if (updateData.stored_quantity > 0) { updateData.storage_status = 'partial'; @@ -2586,7 +2683,8 @@ class ReceivingService extends Service { }; } - // 更新收货单统计信æ�? if (detail.receiving_id) { + // 更新收货单统计信息 + if (detail.receiving_id) { await this.updateReceivingStats(detail.receiving_id); } @@ -2602,7 +2700,8 @@ class ReceivingService extends Service { ], }); - // 格式化返回数æ�? const detailData = updatedDetail.toJSON(); + // 格式化返回数据 + const detailData = updatedDetail.toJSON(); if (detailData.product_snapshot) { try { @@ -2654,14 +2753,16 @@ class ReceivingService extends Service { return null; } - // 直接返回 store_stock 的信æ�? return { + // 直接返回 store_stock 的信息 + return { store_id: stockWarehouse.store_stock.store_id, store_remask: stockWarehouse.store_stock.store_remask, }; } catch (error) { - ctx.logger.error(`获取库存 ${stock_id} 的店铺信息失è´?`, error); - // 根据需求决定是否抛出错è¯? // throw error; + ctx.logger.error(`获取库存 ${stock_id} 的店铺信息失败:`, error); + // 根据需求决定是否抛出错误 + // throw error; return null; } } @@ -2695,7 +2796,8 @@ class ReceivingService extends Service { let storeId = receiving.store_id; let storeName = receiving.store_name; - // 如果收货单没æœ?store_id,尝试从已匹配的商品详情中获å�? if (!storeId) { + // 如果收货单没有 store_id,尝试从已匹配的商品详情中获取 + if (!storeId) { // 查找第一个已匹配的商品详情(system_product_id 不为空) const matchedDetail = await app.model.ReceivingDetail.findOne({ where: { @@ -2713,16 +2815,18 @@ class ReceivingService extends Service { if (storeInfo && storeInfo.store_id) { storeId = storeInfo.store_id; - // 注意:这里使ç”?store_remask 作为 store_name - storeName = storeInfo.store_remask; // 或è€?storeInfo.store_remask + // 注意:这里使用 store_remask 作为 store_name + storeName = storeInfo.store_remask; // 或者 storeInfo.store_remask } } catch (error) { - ctx.logger.warn(`获取商品 ${matchedDetail.system_product_id} 的库存信息失è´?`, error); - // 继续执行,使用默认å€? } + ctx.logger.warn(`获取商品 ${matchedDetail.system_product_id} 的库存信息失败:`, error); + // 继续执行,使用默认值 + } } } - // 3. 统计该收货单的所有明ç»? const stats = await ctx.model.ReceivingDetail.findAll({ + // 3. 统计该收货单的所有明细 + const stats = await ctx.model.ReceivingDetail.findAll({ where: { receiving_id: receivingId }, attributes: [ [ ctx.model.fn('COUNT', ctx.model.col('id')), 'total_items' ], @@ -2734,7 +2838,8 @@ class ReceivingService extends Service { const stat = stats[0] || {}; - // 4. 判断收货单的整体状æ€? const allDetails = await ctx.model.ReceivingDetail.findAll({ + // 4. 判断收货单的整体状态 + const allDetails = await ctx.model.ReceivingDetail.findAll({ where: { receiving_id: receivingId }, transaction, }); @@ -2750,7 +2855,8 @@ class ReceivingService extends Service { } } - // 5. 更新收货å�? const updateData = { + // 5. 更新收货单 + const updateData = { total_items: parseInt(stat.total_items) || 0, total_quantity: parseFloat(stat.total_quantity) || 0, detail_status: detailStatus, @@ -2762,7 +2868,7 @@ class ReceivingService extends Service { updateData.store_id = storeId; updateData.store_name = storeName; } else if (storeId && storeName && receiving.store_name !== storeName) { - // 如果 store_id 已有ä½?store_name 不同,也更新名称 + // 如果 store_id 已有但 store_name 不同,也更新名称 updateData.store_name = storeName; } @@ -2777,19 +2883,22 @@ class ReceivingService extends Service { // 6. 提交事务 await transaction.commit(); - ctx.logger.info(`成功更新收货å�?${receivingId} 的统计信息`); + ctx.logger.info(`成功更新收货单 ${receivingId} 的统计信息`); } catch (error) { - // 7. 发生错误时回滚事åŠ? if (transaction) { + // 7. 发生错误时回滚事务 + if (transaction) { await transaction.rollback(); } - ctx.logger.error('更新收货单统计失è´?', error); + ctx.logger.error('更新收货单统计失败:', error); throw error; } } /** - * 删除收货单明细并回算统计ã€? * @param {Object} data 请求ä½? * @param {number} data.detail_id 明细ID + * 删除收货单明细并回算统计。 + * @param {Object} data 请求体 + * @param {number} data.detail_id 明细ID * @return {Promise} 删除结果 */ async deleteDetail(data) { @@ -2816,11 +2925,12 @@ class ReceivingService extends Service { if (!detail) { return { code: 404, - message: '明细不存åœ?, + message: '明细不存在', }; } - // 验证关联的收货单状态是否允许删é™? if (detail.receiving && detail.receiving.status !== 'receiving') { + // 验证关联的收货单状态是否允许删除 + if (detail.receiving && detail.receiving.status !== 'receiving') { return { code: 400, message: '收货单状态不允许删除明细', @@ -2831,7 +2941,7 @@ class ReceivingService extends Service { if (detail.storage_status !== 'none' && detail.stored_quantity > 0) { return { code: 400, - message: '该明细已入库,不能删é™?, + message: '该明细已入库,不能删除', }; } @@ -2851,12 +2961,14 @@ class ReceivingService extends Service { }; } - // 获取删除后的所有明ç»? const remainingDetails = await ctx.model.ReceivingDetail.findAll({ + // 获取删除后的所有明细 + const remainingDetails = await ctx.model.ReceivingDetail.findAll({ where: { receiving_id }, order: [[ 'id', 'DESC' ]], }); - // 格式化返回数æ�? const formattedDetails = remainingDetails.map(detail => { + // 格式化返回数据 + const formattedDetails = remainingDetails.map(detail => { const detailData = detail.toJSON(); if (detailData.product_snapshot) { @@ -2870,9 +2982,11 @@ class ReceivingService extends Service { return detailData; }); - // 返回下一个选中的明细ID(如果有剩余明细ï¼? let selectId = null; + // 返回下一个选中的明细ID(如果有剩余明细) + let selectId = null; if (remainingDetails.length > 0) { - // 默认选中第一ä¸? selectId = remainingDetails[0].id; + // 默认选中第一个 + selectId = remainingDetails[0].id; } await this.updateReceivingStats(receiving_id); @@ -2917,7 +3031,8 @@ class ReceivingService extends Service { } } /** - * 修改收货明细ã€? * @param {Object} data 收货明细修改参数 + * 修改收货明细。 + * @param {Object} data 收货明细修改参数 * @return {Promise} 修改结果 */ async detailChange(data) { @@ -2930,10 +3045,13 @@ class ReceivingService extends Service { id, // 收货明细ID receiving_id, // 收货单ID actual_quantity, // 实际收货数量 - batch_number, // 批次å�? production_date, // 生产日期 + batch_number, // 批次号 + production_date, // 生产日期 expiry_date, // 到期日期 box_quantity, // 箱数 - boxes_per_pallet, // 每托盘箱æ•? pallet_quantity, // 托盘æ•? space_id, // 存放库位ID + boxes_per_pallet, // 每托盘箱数 + pallet_quantity, // 托盘数 + space_id, // 存放库位ID remark, // 备注 system_product_id, // 系统商品ID barcode, // 条码 @@ -2942,7 +3060,9 @@ class ReceivingService extends Service { box_height, box_length, weight, - box_remainder, // 箱余æ•? box_weight, // 箱重é‡? } = data; + box_remainder, // 箱余数 + box_weight, // 箱重量 + } = data; // 2. 验证必填字段 if (!id) { return { @@ -2979,7 +3099,7 @@ class ReceivingService extends Service { if (!receivingDetail) { return { code: 404, - message: '收货明细不存åœ?, + message: '收货明细不存在', }; } @@ -2994,7 +3114,7 @@ class ReceivingService extends Service { if (box_quantity !== undefined && box_quantity < 0) { return { code: 400, - message: '箱数不能为负æ•?, + message: '箱数不能为负数', }; } @@ -3072,7 +3192,8 @@ class ReceivingService extends Service { if (stockWarehouse) { // 更新商品相关信息 updateData.system_product_id = system_product_id; - // 使用系统商品的条码(如果前端没有提供ï¼? const barcodes = stockWarehouse.barcodes?.map(b => b.barcode) || []; + // 使用系统商品的条码(如果前端没有提供) + 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) { @@ -3081,7 +3202,8 @@ class ReceivingService extends Service { updateData.box_width = updateData.box_width || stockWarehouse.box_width; updateData.box_length = updateData.box_length || stockWarehouse.box_length; } - // 使用系统商品的名称(如果前端没有提供ï¼? updateData.product_name = stockWarehouse.item_name || product_name; + // 使用系统商品的名称(如果前端没有提供) + updateData.product_name = stockWarehouse.item_name || product_name; // 如果有货主信息,更新到产品快照中 if (stockWarehouse.store_stock) { @@ -3197,10 +3319,11 @@ class ReceivingService extends Service { if (!receiving) { await transaction.rollback(); - ctx.throw(404, '收货单不存在或已被删é™?); + ctx.throw(404, '收货单不存在或已被删除'); } - // 2. 检查状态是否允许作åº? if (receiving.status === 'cancelled') { + // 2. 检查状态是否允许作废 + if (receiving.status === 'cancelled') { return { code: 200, success: true, @@ -3213,12 +3336,13 @@ class ReceivingService extends Service { ctx.throw(400, '已全部入库完成,无法作废'); } - // 3. 获取操作人信æ�? const operator = ctx.user; + // 3. 获取操作人信息 + const operator = ctx.user; // 4. 更新收货单状态为作废 await ctx.model.Receiving.update({ status: 'cancelled', - remark: invalid_reason ? `已作åº? ${invalid_reason}` : (receiving.remark || '') + ' - 已作åº?, + remark: invalid_reason ? `已作废: ${invalid_reason}` : (receiving.remark || '') + ' - 已作废', updated_at: new Date(), }, { where: { id: receivingId }, @@ -3249,10 +3373,12 @@ class ReceivingService extends Service { } } - // 6. 处理关联的入库记录(如果有部分入库的情况ï¼? if (receiving.storage_status === 'partial') { - // 将关联的入库记录状态也更新为作åº? await ctx.model.Storage.update({ + // 6. 处理关联的入库记录(如果有部分入库的情况) + if (receiving.storage_status === 'partial') { + // 将关联的入库记录状态也更新为作废 + await ctx.model.Storage.update({ status: 'cancelled', - remark: `关联收货å�?{receiving.receiving_number}已作废`, + remark: `关联收货单${receiving.receiving_number}已作废`, updated_at: new Date(), }, { where: { @@ -3308,7 +3434,7 @@ class ReceivingService extends Service { await transaction.rollback(); } - ctx.logger.error(`作废收货单失è´? ${error.message}`, { + ctx.logger.error(`作废收货单失败: ${error.message}`, { receivingId, warehouseId, userId: ctx.user.id, @@ -3335,7 +3461,7 @@ class ReceivingService extends Service { formatDeliveryMethod(value) { const methodMap = { truck: '货车', - express: '快é€?, + express: '快递', air_freight: '空运', sea_freight: '海运', other: '其他', @@ -3346,12 +3472,15 @@ class ReceivingService extends Service { } /** - * 获取完成收货时需要展示的联系字段ã€? * @param {Object} receiving 收货单快照ã€? * @return {Array} 需要展示的联系字段列表ã€? */ + * 获取完成收货时需要展示的联系字段。 + * @param {Object} receiving 收货单快照。 + * @return {Array} 需要展示的联系字段列表。 + */ getCompletionContactFields(receiving) { const deliveryMethod = String((receiving && receiving.delivery_method) || '').trim(); if (deliveryMethod === 'truck') { - return [[ '车牌å�?, receiving && receiving.license_plate ]]; + return [[ '车牌号', receiving && receiving.license_plate ]]; } if (deliveryMethod === 'express') { @@ -3362,7 +3491,15 @@ class ReceivingService extends Service { } /** - * 生成收货完成报表的工作表数据ã€? * @param {Object} options 报表参数ã€? * @param {Object} options.receiving 收货单快照ã€? * @param {Object} [options.operator={}] 操作人信息ã€? * @param {Object} [options.stats={}] 收货统计数据ã€? * @param {Map} [options.detailImageMap=new Map()] 明细图片映射ã€? * @param {Array} [options.receivingImages=[]] 收货单图片列表ã€? * @return {Array} 工作表列表ã€? */ + * 生成收货完成报表的工作表数据。 + * @param {Object} options 报表参数。 + * @param {Object} options.receiving 收货单快照。 + * @param {Object} [options.operator={}] 操作人信息。 + * @param {Object} [options.stats={}] 收货统计数据。 + * @param {Map} [options.detailImageMap=new Map()] 明细图片映射。 + * @param {Array} [options.receivingImages=[]] 收货单图片列表。 + * @return {Array} 工作表列表。 + */ buildCompletionReportSheets({ receiving, operator = {}, @@ -3384,7 +3521,7 @@ class ReceivingService extends Service { const detailColumns = [ '序号', '商品名称', '条码', '数量', '重量', '箱数', '托数', - '批次å�?, '生产日期', '到期日期', '备注', '图片链接', '图片', + '批次号', '生产日期', '到期日期', '备注', '图片链接', '图片', ]; const detailImageColumnIndex = detailColumns.length; const maxDetailImageCount = Math.max( @@ -3445,10 +3582,10 @@ class ReceivingService extends Service { [ '总明细数', stats.total_details || details.length ], [ '已匹配明细数', stats.matched_details || 0 ], [ '未匹配明细数', stats.unmatched_details || 0 ], - [ '总数é‡?, stats.total_quantity || 0 ], - [ '总箱æ•?, receiving && receiving.total_boxes ], + [ '总数量', stats.total_quantity || 0 ], + [ '总箱数', receiving && receiving.total_boxes ], [ '总托盘数', receiving && receiving.total_pallets ], - [ '完成äº?, operator.employees_name || operator.real_name || operator.name || '' ], + [ '完成人', operator.employees_name || operator.real_name || operator.name || '' ], [ '完成时间', this.formatReportDate(receiving && receiving.receiving_end_time) ], [ '备注', receiving && receiving.remark ], ].forEach(([ field, value ]) => { @@ -3461,7 +3598,7 @@ class ReceivingService extends Service { }); if (mainImageUrls.length === 0) { - pushReportRow([ '收货图片', 'æ—? ], { + pushReportRow([ '收货图片', '无' ], { toCol: 2, style: { alignment: { vertical: 'top', wrapText: true }, @@ -3507,7 +3644,7 @@ class ReceivingService extends Service { }); if (details.length === 0) { - pushReportRow([ '', '', '无明ç»? ], { + pushReportRow([ '', '', '无明细' ], { toCol: detailColumns.length, style: { alignment: { vertical: 'top', wrapText: true }, @@ -3594,7 +3731,7 @@ class ReceivingService extends Service { const receivingNumber = String(receiving.receiving_number || receiving.id).replace(/[\\/:*?"<>|]/g, '_'); return await excelService.generateAndUpload({ - filename: `收货明细(已完成收è´?_${receivingNumber}.xlsx`, + filename: `收货明细(已完成收货)_${receivingNumber}.xlsx`, dir: `exports/receiving/completed/${ctx.user.store_id || receiving.warehouse_id || 'common'}`, category: 'document', saveRecord: true, @@ -3612,10 +3749,13 @@ class ReceivingService extends Service { } /** - * 发送收货完成统一通知,通知外部订阅 `receiving_completed` 事件ã€? * @param {Object} options 通知参数 - * @param {Object} options.receiving 收货单快ç…? * @param {Object} [options.operator={}] 操作人信æ�? * @param {Object} [options.stats={}] 收货统计 + * 发送收货完成统一通知,通知外部订阅 `receiving_completed` 事件。 + * @param {Object} options 通知参数 + * @param {Object} options.receiving 收货单快照 + * @param {Object} [options.operator={}] 操作人信息 + * @param {Object} [options.stats={}] 收货统计 * @param {Object|null} [options.completionReport=null] 完成报表信息 - * @return {Promise} 通知发送结果,若条件不满足则返å›?null + * @return {Promise} 通知发送结果,若条件不满足则返回 null */ async sendCompletionNotice({ receiving, @@ -3666,28 +3806,28 @@ class ReceivingService extends Service { })); const totalBoxRemainder = normalizedDetails.reduce((sum, item) => sum + Number(item.box_remainder || 0), 0); const totalBoxWeight = normalizedDetails.reduce((sum, item) => sum + Number(item.box_weight || 0), 0); - const title = `收货å�?{receivingNumber}已完成`; - const contactLines = this.getCompletionContactFields(receiving).map(([ field, value ]) => `${field}ï¼?{value || 'æ—?}`); + const title = `收货单${receivingNumber}已完成`; + const contactLines = this.getCompletionContactFields(receiving).map(([ field, value ]) => `${field}:${value || '无'}`); const content = [ - `收货单号ï¼?{receivingNumber} 已完成`, - `货主ï¼?{receiving.store_name || '未知'}`, - `来货方式ï¼?{this.formatDeliveryMethod(receiving.delivery_method) || '未知'}`, + `收货单号:${receivingNumber} 已完成`, + `货主:${receiving.store_name || '未知'}`, + `来货方式:${this.formatDeliveryMethod(receiving.delivery_method) || '未知'}`, ...contactLines, - `总明细数ï¼?{Number(stats.total_details || 0)}件`, - `匹配商品ï¼?{matchedDetails}件`, + `总明细数:${Number(stats.total_details || 0)}件`, + `匹配商品:${matchedDetails}件`, `未匹配商品:${unmatchedDetails}件`, `总数量:${totalQuantity}`, `总箱数:${receiving.total_boxes || 0}`, - `总箱余数ï¼?{totalBoxRemainder}`, + `总箱余数:${totalBoxRemainder}`, `总箱重:${totalBoxWeight}`, - `总托盘数ï¼?{receiving.total_pallets || 0}`, + `总托盘数:${receiving.total_pallets || 0}`, operatorName ? `完成人:${operatorName}` : '', `开始时间:${this.formatReportDate(receiving.created_at)}`, - `完成时间ï¼?{this.formatReportDate(receiving.receiving_end_time)}`, - `备注ï¼?{receiving.remark || 'æ—?}`, + `完成时间:${this.formatReportDate(receiving.receiving_end_time)}`, + `备注:${receiving.remark || '无'}`, `快速查看:${ctx.app.config.frontendUrl || ''}/storage/receiving?id=${receivingNumber}`, // 替换为实际的前端地址 - ].filter(Boolean).join('\n') + 'ã€?; + ].filter(Boolean).join('\n') + '。'; return await noticeService.send({ warehouseId, @@ -3735,7 +3875,9 @@ class ReceivingService extends Service { } /** - * 完成收货单:校验明细、更新状态并写入库存ã€? * @param {Object} data 请求ä½? * @param {number} data.id 收货单ID + * 完成收货单:校验明细、更新状态并写入库存。 + * @param {Object} data 请求体 + * @param {number} data.id 收货单ID * @param {string} [data.remark] 完成备注 * @return {Promise} 完成结果 */ @@ -3788,11 +3930,12 @@ class ReceivingService extends Service { await transaction.rollback(); return { code: 404, - message: '收货单不存在或已被删é™?, + message: '收货单不存在或已被删除', }; } - // 2. 状态检æŸ? if (receiving.status === 'completed') { + // 2. 状态检查 + if (receiving.status === 'completed') { await transaction.rollback(); return { code: 200, @@ -3804,7 +3947,7 @@ class ReceivingService extends Service { await transaction.rollback(); return { code: 400, - message: '已作废的收货单不可完æˆ?, + message: '已作废的收货单不可完成', }; } @@ -3817,12 +3960,13 @@ class ReceivingService extends Service { }; } - // 4. 校验明细数量:不允许存在数量ä¸?0 的明ç»? const zeroQuantityDetails = receiving.details.filter(d => Number(d.actual_quantity || 0) <= 0); + // 4. 校验明细数量:不允许存在数量为 0 的明细 + const zeroQuantityDetails = receiving.details.filter(d => Number(d.actual_quantity || 0) <= 0); if (zeroQuantityDetails.length > 0) { await transaction.rollback(); const errorMsg = zeroQuantityDetails.length === 1 - ? `商品â€?{zeroQuantityDetails[0].product_name || '未命名商å“?}”的数量ä¸?,请填写实际收货数量` - : `æœ?{zeroQuantityDetails.length}个商品数量为0,请填写实际收货数量`; + ? `商品“${zeroQuantityDetails[0].product_name || '未命名商品'}”的数量为0,请填写实际收货数量` + : `有${zeroQuantityDetails.length}个商品数量为0,请填写实际收货数量`; return { success: false, code: 'DETAIL_QUANTITY_ZERO', @@ -3830,7 +3974,7 @@ class ReceivingService extends Service { data: { invalid_details: zeroQuantityDetails.map(d => ({ detail_id: d.id, - item_name: d.product_name || '未命名商å“?, + item_name: d.product_name || '未命名商品', actual_quantity: Number(d.actual_quantity || 0), })), }, @@ -3845,11 +3989,11 @@ class ReceivingService extends Service { return { success: false, code: 'BATCH_NUMBER_REQUIRED', - message: '批次管理商品必须填写批次å�?, + message: '批次管理商品必须填写批次号', data: { invalid_details: missingBatchNumberDetails.map(detail => ({ detail_id: detail.id, - item_name: detail.product_name || detail.system_product?.item_name || '未命名商å“?, + item_name: detail.product_name || detail.system_product?.item_name || '未命名商品', batch_number: detail.batch_number || '', production_date: detail.production_date || null, expiry_date: detail.expiry_date || null, @@ -3869,7 +4013,7 @@ class ReceivingService extends Service { data: { invalid_details: missingBatchDetails.map(detail => ({ detail_id: detail.id, - item_name: detail.product_name || detail.system_product?.item_name || '未命名商å“?, + item_name: detail.product_name || detail.system_product?.item_name || '未命名商品', batch_number: detail.batch_number || '', production_date: detail.production_date || null, expiry_date: detail.expiry_date || null, @@ -3897,11 +4041,11 @@ class ReceivingService extends Service { return { success: false, code: 'EXPIRY_DATE_TOO_SOON', - message: `商品â€?{firstInvalid.product_name || firstInvalid.system_product?.item_name || '未命名商å“?}”的有效期不足最小允许收货天数(${minReceiveDays}天),无法完成收货`, + message: `商品“${firstInvalid.product_name || firstInvalid.system_product?.item_name || '未命名商品'}”的有效期不足最小允许收货天数(${minReceiveDays}天),无法完成收货`, data: { invalid_details: invalidExpiryDetails.map(detail => ({ detail_id: detail.id, - item_name: detail.product_name || detail.system_product?.item_name || '未命名商å“?, + item_name: detail.product_name || detail.system_product?.item_name || '未命名商品', batch_number: detail.batch_number || '', production_date: detail.production_date || null, expiry_date: detail.expiry_date || null, @@ -3911,7 +4055,8 @@ class ReceivingService extends Service { }; } - // 5. 准备明细图片与统计信息(照片/条码/重量不再强制要求ï¼? const unmatchedDetails = receiving.details.filter(d => !d.system_product_id); + // 5. 准备明细图片与统计信息(照片/条码/重量不再强制要求) + const unmatchedDetails = receiving.details.filter(d => !d.system_product_id); const detailsIds = receiving.details.map(item => item.id); const images = await ctx.model.FileReference.findAll({ @@ -3944,9 +4089,11 @@ class ReceivingService extends Service { }); }); - // 5. 获取操作人信æ�? const operator = ctx.user; + // 5. 获取操作人信息 + const operator = ctx.user; - // 8. 更新收货单状æ€? const now = new Date(); + // 8. 更新收货单状态 + const now = new Date(); const updateData = { status: 'completed', receiving_end_time: now, @@ -3955,10 +4102,10 @@ class ReceivingService extends Service { if (remark) { const remarkPrefix = receiving.remark ? `${receiving.remark}\n` : ''; - updateData.remark = `${remarkPrefix}【完成收货ã€?{now.toLocaleString()} ${operator.employees_name} ${remark}`; + updateData.remark = `${remarkPrefix}【完成收货】${now.toLocaleString()} ${operator.employees_name} ${remark}`; } else { const remarkPrefix = receiving.remark ? `${receiving.remark}\n` : ''; - updateData.remark = `${remarkPrefix}【完成收货ã€?{now.toLocaleString()} ${operator.employees_name}`; + updateData.remark = `${remarkPrefix}【完成收货】${now.toLocaleString()} ${operator.employees_name}`; } await ctx.model.Receiving.update(updateData, { @@ -3980,7 +4127,7 @@ class ReceivingService extends Service { // 10.1 清除收货单缓存,确保下次入库完成时匹配到最新收货单列表 const receivingCacheKey = `cache:receiving_orders:warehouse:${warehouseId}`; app.delCacheAsync(receivingCacheKey).catch(cacheErr => { - ctx.logger.warn(`[receiving.completeReceiving] 清除收货单缓存失è´? ${cacheErr.message}`, { cacheKey: receivingCacheKey }); + ctx.logger.warn(`[receiving.completeReceiving] 清除收货单缓存失败: ${cacheErr.message}`, { cacheKey: receivingCacheKey }); }); // 记录操作日志 @@ -4016,7 +4163,8 @@ class ReceivingService extends Service { stats, }; - // 11. 收货成功后先触发文字通知,再生成 Excel;若 Excel 成功,再补发文件通知ã€? try { + // 11. 收货成功后先触发文字通知,再生成 Excel;若 Excel 成功,再补发文件通知。 + try { const textNoticeResult = await this.sendCompletionNotice(completionNoticePayload); ctx.logger.info('收货完成文字通知结果', { receiving_id: id, @@ -4029,7 +4177,7 @@ class ReceivingService extends Service { failedCount: Number(textNoticeResult && textNoticeResult.data && textNoticeResult.data.failedCount || 0), }); } catch (notifyError) { - ctx.logger.error(`收货完成文字通知发送失è´? ${notifyError.message}`, { + ctx.logger.error(`收货完成文字通知发送失败: ${notifyError.message}`, { receiving_id: id, warehouseId, error: notifyError.stack, @@ -4094,21 +4242,27 @@ class ReceivingService extends Service { } /** - * 收货完成后异步补全商品资料:绑定图片、补填毛重ã€? * + * 收货完成后异步补全商品资料:绑定图片、补填毛重。 + * * 遍历当前收货单所有已绑定系统商品的明细: - * 1. 若商å“?is_images === 'N' 且该明细有收货图片,则将收货图片复制为商品图片(FileReference), - * 并将商品çš?is_images 更新ä¸?'Y'ã€? * 2. 若商å“?gross_weight ä¸?0 æˆ?null,且明细çš?weight > 0,则将商品毛重更新为该明细的 weightã€? * - * 本方法通过 setImmediate 调用,运行在事务提交后,任何异常只记录日志,不影响主进程ã€? * + * 1. 若商品 is_images === 'N' 且该明细有收货图片,则将收货图片复制为商品图片(FileReference), + * 并将商品的 is_images 更新为 'Y'。 + * 2. 若商品 gross_weight 为 0 或 null,且明细的 weight > 0,则将商品毛重更新为该明细的 weight。 + * + * 本方法通过 setImmediate 调用,运行在事务提交后,任何异常只记录日志,不影响主进程。 + * * @param {Object} options 参数对象 - * @param {number} options.receivingId 收货å�?ID + * @param {number} options.receivingId 收货单 ID * @param {number} options.warehouseId 仓库 ID - * @param {Array} options.details 收货明细数组(来è‡?completeReceiving 中已加载çš?detailsï¼? * @return {Promise} + * @param {Array} options.details 收货明细数组(来自 completeReceiving 中已加载的 details) + * @return {Promise} */ async _syncProductDataFromReceiving({ receivingId, warehouseId, details }) { - console.log('_syncProductDataFromReceiving异步执行ä¸?..'); // 调试日志 + console.log('_syncProductDataFromReceiving异步执行中...'); // 调试日志 const { ctx, app } = this; - // 只处理已绑定系统商品的明ç»? const boundDetails = (Array.isArray(details) ? details : []).filter( + // 只处理已绑定系统商品的明细 + const boundDetails = (Array.isArray(details) ? details : []).filter( d => d && Number(d.system_product_id) > 0 ); @@ -4142,7 +4296,7 @@ class ReceivingService extends Service { }); if (detailImageRefs.length > 0) { - // 查询商品已有的图ç‰?file_id(避免重复) + // 查询商品已有的图片 file_id(避免重复) const existingStockImageFileIds = await app.model.FileReference.findAll({ where: { business_type: 'stock', @@ -4176,7 +4330,7 @@ class ReceivingService extends Service { ); ctx.logger.info( - `[_syncProductDataFromReceiving] 商品 ${systemProductId} 已补全图片,共复åˆ?${toCreate.length} 张(收货å�?${receivingId} 明细 ${detail.id})` + `[_syncProductDataFromReceiving] 商品 ${systemProductId} 已补全图片,共复制 ${toCreate.length} 张(收货单 ${receivingId} 明细 ${detail.id})` ); } @@ -4190,11 +4344,12 @@ class ReceivingService extends Service { ); ctx.logger.info( - `[_syncProductDataFromReceiving] 商品 ${systemProductId} 已补全毛é‡?${detailWeight}(收货单 ${receivingId} 明细 ${detail.id})` + `[_syncProductDataFromReceiving] 商品 ${systemProductId} 已补全毛重 ${detailWeight}(收货单 ${receivingId} 明细 ${detail.id})` ); } } catch (err) { - // 单条明细失败不中断后续处ç�? console.log( + // 单条明细失败不中断后续处理 + console.log( `[_syncProductDataFromReceiving] 处理明细 ${detail.id} (商品 ${systemProductId}) 失败: ${err.message}` ); } @@ -4202,8 +4357,19 @@ class ReceivingService extends Service { } /** - * PDA 扫码定位收货明细:通过入库单ID + 扫描条码快速定位收货明细ã€? * 搜索策略ï¼? * 1. 通过 entry_order_id â†?wms_entry_order_receiving 查出关联çš?receiving_id 列表ï¼? * 2. 查出所有未绑定的收货明细(仅按 receiving_id IN + 排除已绑定过滤)ï¼? * 3. 收集明细çš?system_product_id,批量调ç”?getStockDetails 获取条码信息ï¼? * 4. 在内存中遍历明细进行精确匹配ï¼? * - è‹?barcode 为纯数字,优先按明细 ID 精确匹配ï¼? * - 再按 getStockDetails 返回çš?barcodes[].barcode 精确匹配商品条码ï¼? * 5. 返回所有匹配的明细列表(同一条码可能匹配到多条收货明细)ã€? * @param {number} entryOrderId 入库单ID - * @param {string} barcode 扫描条码(商品条ç ?箱唛/托盘å”?明细IDï¼? * @return {Promise} 包含 code、message 与匹配明细列è¡?data.list 的结果对è±? */ + * PDA 扫码定位收货明细:通过入库单ID + 扫描条码快速定位收货明细。 + * 搜索策略: + * 1. 通过 entry_order_id → wms_entry_order_receiving 查出关联的 receiving_id 列表; + * 2. 查出所有未绑定的收货明细(仅按 receiving_id IN + 排除已绑定过滤); + * 3. 收集明细的 system_product_id,批量调用 getStockDetails 获取条码信息; + * 4. 在内存中遍历明细进行精确匹配: + * - 若 barcode 为纯数字,优先按明细 ID 精确匹配; + * - 再按 getStockDetails 返回的 barcodes[].barcode 精确匹配商品条码; + * 5. 返回所有匹配的明细列表(同一条码可能匹配到多条收货明细)。 + * @param {number} entryOrderId 入库单ID + * @param {string} barcode 扫描条码(商品条码/箱唛/托盘唛/明细ID) + * @return {Promise} 包含 code、message 与匹配明细列表 data.list 的结果对象 + */ async scanDetail(entryOrderId, barcode) { const { ctx, app } = this; const { Op } = app.Sequelize; @@ -4211,7 +4377,7 @@ class ReceivingService extends Service { // 参数校验 if (!warehouseId) { - return { code: 0, message: '用户未绑定仓åº?, data: null }; + return { code: 0, message: '用户未绑定仓库', data: null }; } if (!entryOrderId || Number(entryOrderId) <= 0) { return { code: 0, message: '入库单ID不能为空', data: null }; @@ -4235,10 +4401,10 @@ class ReceivingService extends Service { }); if (!entryOrder) { - return { code: 0, message: '入库单不存在或无权访é—?, data: null }; + return { code: 0, message: '入库单不存在或无权访问', data: null }; } - // 2. 通过 wms_entry_order_receiving 查出关联çš?receiving_id 列表 + // 2. 通过 wms_entry_order_receiving 查出关联的 receiving_id 列表 const entryReceivingRows = await ctx.model.EntryOrderReceiving.findAll({ where: { entry_order_id: normalizedEntryOrderId }, attributes: [ 'receiving_id' ], @@ -4247,7 +4413,7 @@ class ReceivingService extends Service { const receivingIds = entryReceivingRows.map(r => r.receiving_id).filter(Boolean); if (receivingIds.length === 0) { - return { code: 0, message: '该入库单尚未关联收货å�?, data: null }; + return { code: 0, message: '该入库单尚未关联收货单', data: null }; } // 排除已绑定的收货明细(wms_inbound_direct_log 中有记录且未软删除) @@ -4255,7 +4421,8 @@ class ReceivingService extends Service { '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. 查出所有未绑定的收货明细(不再åœ?SQL 层做 barcode 模糊匹配ï¼? const details = await ctx.model.ReceivingDetail.findAll({ + // 3. 查出所有未绑定的收货明细(不再在 SQL 层做 barcode 模糊匹配) + const details = await ctx.model.ReceivingDetail.findAll({ where: { [Op.and]: [ { receiving_id: { [Op.in]: receivingIds } }, @@ -4269,7 +4436,7 @@ class ReceivingService extends Service { return { code: 0, message: '未找到可用的收货明细', data: null }; } - // 4. 收集所有明细的 system_product_id,批量调ç”?getStockDetails 获取条码 + // 4. 收集所有明细的 system_product_id,批量调用 getStockDetails 获取条码 const stockIdSet = new Set(); for (const d of details) { if (d.system_product_id != null) { @@ -4289,17 +4456,19 @@ class ReceivingService extends Service { } } - // 5. 在内存中遍历明细,精确匹配,收集所有命ä¸? const isNumericBarcode = /^\d+$/.test(normalizedBarcode); + // 5. 在内存中遍历明细,精确匹配,收集所有命中 + const isNumericBarcode = /^\d+$/.test(normalizedBarcode); const matchedDetails = []; for (const detail of details) { - // 优先按明ç»?ID 精确匹配(托盘唛头场景) + // 优先按明细 ID 精确匹配(托盘唛头场景) if (isNumericBarcode && detail.id === Number(normalizedBarcode)) { matchedDetails.push(detail); continue; } - // 按商品条码精确匹é…? const stockDetail = stockDetailMap.get(detail.system_product_id); + // 按商品条码精确匹配 + const stockDetail = stockDetailMap.get(detail.system_product_id); if (stockDetail && Array.isArray(stockDetail.barcodes)) { const barcodeMatch = stockDetail.barcodes.some( bc => bc.barcode === normalizedBarcode @@ -4334,7 +4503,7 @@ class ReceivingService extends Service { }; } catch (error) { ctx.logger.error('[receiving.scanDetail] 扫码定位收货明细失败', error); - return { code: 500, message: `服务器错è¯? ${error.message}`, data: null }; + return { code: 500, message: `服务器错误: ${error.message}`, data: null }; } }