diff --git a/app/dict/businessDict.js b/app/dict/businessDict.js index ce2d78f..c6c363f 100644 --- a/app/dict/businessDict.js +++ b/app/dict/businessDict.js @@ -76,6 +76,8 @@ module.exports = { ORDER_WAVE_AUTO_GROUP: '自动加团', ORDER_WAVE_STRATEGY_FETCH: '策略抓取波次', ORDER_PICK_COMPLETE: '拣货完成', + ORDER_RECHECK: '订单复核', + ORDER_RECHECK_BATCH: '批量复核', ORDER_SYNC: '同步订单', ORDER_WEIGH: '称重', ORDER_PACKAGE_MATERIAL_BIND: '绑定包材', diff --git a/app/lib/printer_data_builder.js b/app/lib/printer_data_builder.js index 64a78b4..38ed2b9 100644 --- a/app/lib/printer_data_builder.js +++ b/app/lib/printer_data_builder.js @@ -1040,6 +1040,18 @@ function resolvePolicyConfig(input) { return {}; } +/** + * 归一化仓库主体配置(subject_config),用于发件人兜底。 + * @param {Object} input 入参对象。 + * @return {Object} 统一 subject_config 对象。 + */ +function resolveSubjectConfig(input) { + if (isPlainObject(input.subject_config)) { + return input.subject_config; + } + return {}; +} + /** * 构建基础数据中间态。 * @param {Object} input 输入对象。 @@ -1051,16 +1063,27 @@ function buildBaseData(input, platform, platformMeta) { const orderExpress = isPlainObject(input.order_express) ? input.order_express : {}; const orderDelivery = isPlainObject(input.order_delivery) ? input.order_delivery : {}; const policyConfig = resolvePolicyConfig(input); + const subjectConfig = resolveSubjectConfig(input); const templateSample = isPlainObject(input.template_sample) ? input.template_sample : {}; + // 三级兜底:货主 policy_config → 仓库 subject_config → 缺失标记 + const missingSenderFields = []; + const senderField = key => { + const val = toTrimmedString(policyConfig[key]) || toTrimmedString(subjectConfig[key]); + if (!val) { + missingSenderFields.push(key); + } + return val || '仓库未配置发件人'; + }; + const sender = { - name: toTrimmedString(policyConfig.sender_name), - tel: toTrimmedString(policyConfig.sender_tel), - province: toTrimmedString(policyConfig.province_name), - city: toTrimmedString(policyConfig.city_name), - district: toTrimmedString(policyConfig.district_name), - town: toTrimmedString(policyConfig.town_name), - address: toTrimmedString(policyConfig.address), + name: senderField('sender_name'), + tel: senderField('sender_tel'), + province: senderField('province_name'), + city: senderField('city_name'), + district: senderField('district_name'), + town: senderField('town_name'), + address: senderField('address'), }; const receiver = { @@ -1096,10 +1119,13 @@ function buildBaseData(input, platform, platformMeta) { const missingFields = []; const warnings = []; + // 将三级兜底中仍然缺失的字段挂载到 sender 上供下游感知 + sender._missing = [ ...missingSenderFields ]; + const requiredChecks = [ - { path: 'sender.name', value: sender.name, reason: '缺少发件人姓名(policy_config.sender_name)' }, - { path: 'sender.tel', value: sender.tel, reason: '缺少发件人电话(policy_config.sender_tel)' }, - { path: 'sender.address', value: sender.address, reason: '缺少发件详细地址(policy_config.address)' }, + { path: 'sender.name', value: sender.name === '仓库未配置发件人' ? '' : sender.name, reason: '缺少发件人姓名(policy_config.sender_name / subject_config.sender_name)' }, + { path: 'sender.tel', value: sender.tel === '仓库未配置发件人' ? '' : sender.tel, reason: '缺少发件人电话(policy_config.sender_tel / subject_config.sender_tel)' }, + { path: 'sender.address', value: sender.address === '仓库未配置发件人' ? '' : sender.address, reason: '缺少发件详细地址(policy_config.address / subject_config.address)' }, { path: 'receiver.name', value: receiver.name, reason: '缺少收件人姓名(order_delivery.name)' }, { path: 'receiver.mobile|tel', value: receiver.mobile || receiver.tel, reason: '缺少收件联系方式(order_delivery.mobile/tel)' }, { path: 'receiver.address', value: receiver.address, reason: '缺少收件详细地址(order_delivery.detail_address)' }, diff --git a/app/model/store.js b/app/model/store.js index f7acc0f..4708ea4 100644 --- a/app/model/store.js +++ b/app/model/store.js @@ -48,6 +48,13 @@ module.exports = app => { min_group_order_fetch_quantity: 13, default_express_code: 'STO', default_platform_code: 'TB', + sender_name: '', + sender_tel: '', + province_name: '', + city_name: '', + district_name: '', + town_name: '', + address: '', group_wave_prefix: 'B', delete_order_wave_prefix: 'A', inventory_warning_rules: DEFAULT_INVENTORY_WARNING_RULES, diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index a037f68..09e804e 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -5193,10 +5193,8 @@ class PendingOrderService extends OrderBaseService { /** * 取消订单时释放创建锁(lockItemStorages 添加的 wms_stock_warehouse.locked_quantity)。 * - * - 有 wms_picking 有效记录时:通过 storage_id → stock_id 映射汇总各 stock_id 的 picking 数量, - * 释放对应 wms_stock_warehouse.locked_quantity。 - * - 无 wms_picking 记录时:从 wms_order_items 读取 plan_qty, - * 释放对应 wms_stock_warehouse.locked_quantity。 + * 直接从 wms_order_items 读取 plan_qty,按 stock_id 汇总后释放对应 wms_stock_warehouse.locked_quantity。 + * 不依赖 wms_picking / wms_storage(储位分配的锁由 cancelAllocateStorage 负责释放)。 * * @param {Object} options - 释放参数。 * @param {number[]} options.orderIds - 订单ID 数组。 @@ -5211,89 +5209,55 @@ class PendingOrderService extends OrderBaseService { return; } - const pickingModel = ctx.model.Picking; - const storageModel = ctx.model.Storage; const stockModel = ctx.model.StockWarehouse; + if (!stockModel) { + ctx.logger.warn('[PendingOrderService.releaseCreationLockForCancel] StockWarehouse 模型不可用,跳过库存释放'); + return; + } - if (!pickingModel || !storageModel || !stockModel) { - ctx.logger.warn('[PendingOrderService.releaseCreationLockForCancel] 模型不可用,跳过库存释放'); + const OrderItemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + if (!OrderItemsModel) { + ctx.logger.warn('[PendingOrderService.releaseCreationLockForCancel] OrderItems 模型不可用,跳过库存释放'); return; } const transaction = await ctx.model.transaction(); try { - // 查找这些订单的有效储位分配记录(排除已取消的) - const pickingRows = await pickingModel.findAll({ + // 直接从 order_items 读取 plan_qty,按 stock_id 汇总 + const orderItems = await OrderItemsModel.findAll({ where: { order_id: { [Op.in]: orderIds }, - warehouse_id: warehouseId, - status: { [Op.ne]: 'cancel' }, }, + attributes: [ 'stock_id', 'plan_qty' ], transaction, lock: transaction.LOCK.UPDATE, raw: true, }); - if (!Array.isArray(pickingRows) || pickingRows.length === 0) { - // 无储位分配记录:picking 已被 cancelAllocateStorage 处理完毕,无需再次释放 - await transaction.rollback(); - return; - } - - // 有 picking 记录:按 storage_id 汇总释放数量 - const storageQuantityMap = new Map(); - for (const row of pickingRows) { - const storageId = Number(row.storage_id || 0); - const quantity = Number(row.quantity || 0); - if (storageId > 0 && quantity > 0) { - storageQuantityMap.set(storageId, (storageQuantityMap.get(storageId) || 0) + quantity); - } - } - - if (storageQuantityMap.size === 0) { + if (!Array.isArray(orderItems) || orderItems.length === 0) { await transaction.commit(); return; } - // 查出关联的 wms_storage 记录,获取 stock_id - const storageIds = Array.from(storageQuantityMap.keys()); - const storageRows = await storageModel.findAll({ - where: { - id: { [Op.in]: storageIds }, - warehouse_id: warehouseId, - }, - transaction, - lock: transaction.LOCK.UPDATE, - raw: true, - }); - - const storageMap = new Map(); - for (const row of storageRows) { - storageMap.set(Number(row.id), row); + // 按 stock_id 汇总需要释放的创建锁数量 + const stockReleaseMap = new Map(); + for (const item of orderItems) { + const stockId = Number(item.stock_id || 0); + const planQty = Number(item.plan_qty || 0); + if (stockId > 0 && planQty > 0) { + stockReleaseMap.set(stockId, (stockReleaseMap.get(stockId) || 0) + planQty); + } } - // 按 stock_id 汇总需要释放的数量 - const stockReleaseMap = new Map(); - for (const [ storageId, quantity ] of storageQuantityMap.entries()) { - const storageRow = storageMap.get(storageId); - if (!storageRow) { - ctx.logger.warn(`[PendingOrderService.releaseCreationLockForCancel] 库存记录不存在,跳过: storageId=${storageId}`); - continue; - } - - const stockId = Number(storageRow.stock_id || 0); - if (stockId <= 0) { - ctx.logger.warn(`[PendingOrderService.releaseCreationLockForCancel] 库存记录缺少 stock_id,跳过: storageId=${storageId}`); - continue; - } - - stockReleaseMap.set(stockId, (stockReleaseMap.get(stockId) || 0) + quantity); + if (stockReleaseMap.size === 0) { + await transaction.commit(); + return; } // 释放 wms_stock_warehouse.locked_quantity for (const [ stockId, quantity ] of stockReleaseMap.entries()) { - const decrementResult = await stockModel.update( + const [ affectedCount ] = await stockModel.update( { locked_quantity: app.Sequelize.literal(`locked_quantity - ${Number(quantity)}`), updated_at: app.Sequelize.literal('CURRENT_TIMESTAMP'), @@ -5307,8 +5271,8 @@ class PendingOrderService extends OrderBaseService { } ); - if (!Array.isArray(decrementResult) || Number(decrementResult[0] || 0) <= 0) { - throw new Error(`库存主记录锁定数量不足,无法释放: stockId=${stockId}, quantity=${quantity}`); + if (Number(affectedCount || 0) <= 0) { + throw new Error(`库存主记录锁定数量不足,无法释放创建锁: stockId=${stockId}, quantity=${quantity}`); } } diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index 53cc57b..c83bd6b 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -1942,6 +1942,65 @@ class RecheckOrderService extends OrderBaseService { type: this.ctx.model.QueryTypes.INSERT, } ); + + // 双写 order_operation_log(失败不影响主流程) + try { + const ctx = this.ctx; + const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + if (isBatch) { + // 波次复核:按波次记录一条操作日志 + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + const messageParts = []; + if (waveNo) { + messageParts.push(`波次 ${String(waveNo).trim()}`); + } + messageParts.push(`复核完成,正常${normalOrderCount || 0}单、拦截${interceptedOrderCount || 0}单、总计${totalOrderCount || 0}单`); + await operationLogService.createOperationLogs([{ + businessType: 'order', + businessId: String(waveId || ''), + operationCode: 'ORDER_RECHECK_BATCH', + operator: { id: String(operatorId || ''), name: operatorName }, + extras: { + warehouseId: warehouseId || 0, + message: messageParts.join(''), + waveId, + waveNo: waveNo || '', + normalOrderCount: normalOrderCount || 0, + interceptedOrderCount: interceptedOrderCount || 0, + totalOrderCount: totalOrderCount || 0, + }, + }]); + } + } else { + // 单订单复核 + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + const messageParts = []; + if (waybillNo) { + messageParts.push(`运单 ${String(waybillNo).trim()} `); + } + messageParts.push('订单复核完成'); + await operationLogService.createOperationLogs([{ + businessType: 'order', + businessId: String(orderId || ''), + operationCode: 'ORDER_RECHECK', + operator: { id: String(operatorId || ''), name: operatorName }, + extras: { + warehouseId: warehouseId || 0, + message: messageParts.join(''), + orderId: orderId || 0, + waybillNo: waybillNo || '', + }, + }]); + } + } + } catch (e) { + this.ctx.logger.warn('[recheckOrder._writeRecheckActionLog] 写入 order_operation_log 失败', { + error: e && e.message, + orderId, + waveId, + warehouseId, + }); + } } /** @@ -3755,6 +3814,35 @@ class RecheckOrderService extends OrderBaseService { } } + // 写入 order_operation_log 拣货完成日志(双写) + try { + const operationLogService = ctx.service + && ctx.service.systems + && ctx.service.systems.operationLog; + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + const logOperator = this.getOrderLogOperator(); + const operatorId = String(logOperator.id || '').trim(); + const operatorName = String(logOperator.name || 'system').trim(); + await operationLogService.createOperationLogs([ + { + businessType: 'order', + businessId: `${orderId}`, + operationCode: 'ORDER_PICK_COMPLETE', + operator: { id: operatorId || null, name: operatorName || 'system' }, + extras: { + message: `订单${orderId}拣货完成`, + warehouseId: Number(warehouseId), + externalLogType: 'API', + }, + }, + ], { transaction }); + } + } catch (e) { + ctx.logger.warn( + `[_completePickForOrder] order_operation_log 写入失败, orderId=${orderId}, error=${e.message}` + ); + } + // 步骤5:更新 wms_wave_pick_task 状态 if (hasTaskOrder) { const taskId = Number(taskOrderRows[0]?.task_id || 0); @@ -4312,6 +4400,31 @@ class RecheckOrderService extends OrderBaseService { transaction, } ); + + // 双写 order_operation_log(失败不影响主流程) + try { + const ctx = this.ctx; + const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + await operationLogService.createOperationLogs([{ + businessType: 'order', + businessId: String(orderId || ''), + operationCode: 'ORDER_RECHECK', + operator: { id: String(operatorId || ''), name: operatorName }, + extras: { + warehouseId: warehouseId || 0, + message: '订单复核完成', + orderId: orderId || 0, + }, + }], { transaction }); + } + } catch (e) { + this.ctx.logger.warn('[recheckOrder._writeRecheckActionLogInTransaction] 写入 order_operation_log 失败', { + error: e && e.message, + orderId, + warehouseId, + }); + } } } diff --git a/app/service/systemMethods/stock/warehouse.js b/app/service/systemMethods/stock/warehouse.js index 8814969..8950351 100644 --- a/app/service/systemMethods/stock/warehouse.js +++ b/app/service/systemMethods/stock/warehouse.js @@ -1031,7 +1031,11 @@ class WarehouseService extends MainService { const { mode } = data || {}; if (mode === 'combo') { - const { id, custom_code } = data || {}; + const { id, custom_code, keyword } = data || {}; + if (keyword) { + const result = await service.systems.comboGoods.search({ keyword }); + return this.success('ok', result); + } const result = await service.systems.comboGoods.searchByIdOrCode({ id, custom_code }); return this.success('ok', result); } diff --git a/app/service/systemMethods/storage/entry.js b/app/service/systemMethods/storage/entry.js index c3e169b..abae4df 100644 --- a/app/service/systemMethods/storage/entry.js +++ b/app/service/systemMethods/storage/entry.js @@ -9,9 +9,9 @@ class entryService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,get,cancel,completeEntry,getPrintData,getDirectInboundItems,addDirectInboundItem,commitDirectInbound,removeDirectInboundItem'; + const _noNeedRight = 'list,get,cancel,completeEntry,getPrintData,getDirectInboundItems,addDirectInboundItem,commitDirectInbound,removeDirectInboundItem,quickInbound,receivingCompare'; const _noNeedLog = 'list,get,getPrintData'; - const _noNeedAuth = 'list,get,cancel,completeEntry,getPrintData,getDirectInboundItems,addDirectInboundItem,commitDirectInbound,removeDirectInboundItem'; + const _noNeedAuth = 'list,get,cancel,completeEntry,getPrintData,getDirectInboundItems,addDirectInboundItem,commitDirectInbound,removeDirectInboundItem,bindReceivingDetails,quickInbound,receivingCompare'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -132,6 +132,33 @@ class entryService extends MainService { return this.success('ok', result); } + /** + * 批量绑定入库单明细与收货单明细(system method 包装层)。 + * @param {Object} data 请求体 + * @param {number} data.entry_order_id 入库单ID + * @param {Array} data.bindings 绑定列表 [{ entry_item_id, receiving_detail_id, allocated_quantity }] + * @return {Promise} 统一 success 包装 + */ + async bindReceivingDetails(data = {}) { + const { service } = this; + const { entry_order_id, bindings } = data || {}; + const result = await service.systems.receiving_entry_match.bindReceivingDetails({ entry_order_id, bindings }); + return this.success('绑定完成', result); + } + + /** + * 快捷直入/虚拟入库(system method 包装层)。 + * @param {Object} data 请求体 + * @param {number} data.id 入库单ID + * @return {Promise} 统一 success 包装 + */ + async quickInbound(data = {}) { + const { service } = this; + const { id } = data; + const result = await service.systems.storage.entry.quickInbound({ id }); + return this.success('ok', result); + } + /** * 获取入库单打印数据,按 RECEIPT 模板 field_code 映射返回。 * @param {Object} data 请求体 @@ -217,5 +244,19 @@ class entryService extends MainService { return this.fail(error.message || '获取打印数据失败', { code: 500 }); } } + /** + * 入库单商品与收货单商品逐行对照视图(system method 包装层)。 + * @param {Object} data 请求体 + * @param {number} data.entry_order_id 入库单ID + * @param {number} data.receiving_id 收货单ID + * @return {Promise} 统一 success 包装 + */ + async receivingCompare(data = {}) { + const { service } = this; + const { entry_order_id, receiving_id } = data || {}; + const result = await service.systems.storage.entry.receivingCompare({ entry_order_id, receiving_id }); + return this.success('ok', result); + } + } module.exports = entryService; diff --git a/app/service/systemMethods/storage/receiving.js b/app/service/systemMethods/storage/receiving.js index 6f72776..8c6ddd2 100644 --- a/app/service/systemMethods/storage/receiving.js +++ b/app/service/systemMethods/storage/receiving.js @@ -10,9 +10,9 @@ class configService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,manualMatchEntryOrder'; - const _noNeedLog = 'getReceivingList,get,addDetail,deleteDetail,detailChange,bindStore,bindDetailProduct,queryReceivingLogs,manualMatchEntryOrder'; - const _noNeedAuth = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,manualMatchEntryOrder'; + const _noNeedRight = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs'; + const _noNeedLog = 'getReceivingList,get,addDetail,deleteDetail,detailChange,bindStore,bindDetailProduct,queryReceivingLogs'; + const _noNeedAuth = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -260,23 +260,5 @@ class configService extends MainService { }); } - /** - * 手动匹配入库单与收货单(system method 包装层)。 - * - * 传入收货单 ID 与入库单 ID,复用 `receiving_entry_match` 服务的匹配逻辑, - * 同步执行 SKU 明细对比并按来源回传(奇门 / OpenAPI),返回结构化匹配结果。 - * - * @param {Object} data 请求体 - * @param {number} data.receivingId 收货单 ID - * @param {number} data.entryOrderId 入库单 ID - * @return {Promise} 统一成功包装的匹配结果 - */ - async manualMatchEntryOrder(data) { - const { service } = this; - const { receivingId, entryOrderId } = data || {}; - const result = await service.systems.receiving_entry_match.manualMatch(receivingId, entryOrderId); - return this.success('匹配完成', result); - } - } module.exports = configService; diff --git a/app/service/systems/express.js b/app/service/systems/express.js index e7d38a1..928eb74 100644 --- a/app/service/systems/express.js +++ b/app/service/systems/express.js @@ -2427,8 +2427,21 @@ class ExpressService extends Service { }); // 发件人相关字段统一走接口配置,货主配置仅用于打印链路。 + // 三级兜底:express_interface → 仓库 subject_config → 空字符串 + const storeRow = await this.ctx.model.Store.findByPk(warehouseId, { + attributes: [ 'subject_config' ], + raw: true, + }); + const subjectConfig = (storeRow && storeRow.subject_config) ? storeRow.subject_config : {}; const expressInterfaceConfig = expressInterface ? { ...expressInterface, + sender_name: expressInterface.sender_name || subjectConfig.sender_name || '', + sender_tel: expressInterface.sender_tel || subjectConfig.sender_tel || '', + province_name: expressInterface.province_name || subjectConfig.province_name || '', + city_name: expressInterface.city_name || subjectConfig.city_name || '', + district_name: expressInterface.district_name || subjectConfig.district_name || '', + town_name: expressInterface.town_name || subjectConfig.town_name || '', + address: expressInterface.address || subjectConfig.address || '', } : null; for (const batch of batches) { diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index b67e63f..be62f09 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -729,17 +729,27 @@ class ExpressPlatformService extends MainService { inputsite: listByWarehousePlatformCode.site_code || '', sitecode: listByWarehousePlatformCode.site_code || '', shipperno: listByWarehousePlatformCode.shipperno || '', - sender: { - company: listByWarehousePlatformCode.shop_name || '', - name: listByWarehousePlatformCode.sender_name || '', - phone: listByWarehousePlatformCode.sender_tel || '', - country: 'CN', - city: listByWarehousePlatformCode.city_name || '', - province: listByWarehousePlatformCode.province_name || '', - area: listByWarehousePlatformCode.district_name || '', - town: listByWarehousePlatformCode.town_name || '', - address: listByWarehousePlatformCode.address || '', - }, // 需要实现 + sender: (() => { + const senderName = listByWarehousePlatformCode.sender_name || ''; + const senderTel = listByWarehousePlatformCode.sender_tel || ''; + const senderProvince = listByWarehousePlatformCode.province_name || ''; + const senderCity = listByWarehousePlatformCode.city_name || ''; + const senderDistrict = listByWarehousePlatformCode.district_name || ''; + const senderTown = listByWarehousePlatformCode.town_name || ''; + const senderAddress = listByWarehousePlatformCode.address || ''; + const fallback = '仓库未配置发件人'; + return { + company: listByWarehousePlatformCode.shop_name || '', + name: senderName || fallback, + phone: senderTel || (senderName ? '' : fallback), + country: 'CN', + city: senderCity || fallback, + province: senderProvince || fallback, + area: senderDistrict || fallback, + town: senderTown || fallback, + address: senderAddress || fallback, + }; + })(), receiver: { name: order.name || '', company: order.company || '', @@ -812,7 +822,7 @@ class ExpressPlatformService extends MainService { city: receiverCity, address: receiverAddress, } = receiver; - const senderName = senderNameRaw || listByWarehousePlatformCode.sender_name || listByWarehousePlatformCode.shop_name || ''; + const senderName = senderNameRaw || listByWarehousePlatformCode.sender_name || listByWarehousePlatformCode.shop_name || '仓库未配置发件人'; const senderCompany = senderCompanyRaw || listByWarehousePlatformCode.shop_name || ''; const customername = senderNameRaw || senderCompanyRaw || listByWarehousePlatformCode.shop_name || '测试'; @@ -1690,18 +1700,28 @@ class ExpressPlatformService extends MainService { ? (listByWarehousePlatformCode.express.CAINIAO || listByWarehousePlatformCode.express.cainiao_code || '') : '', product_code: String(listByWarehousePlatformCode.product_type || '').trim(), - sender: { - address: { - city: listByWarehousePlatformCode.city_name, - detail: listByWarehousePlatformCode.address, - district: listByWarehousePlatformCode.district_name, - province: listByWarehousePlatformCode.province_name, - town: listByWarehousePlatformCode.town_name || null, - }, - mobile: listByWarehousePlatformCode.sender_tel, - name: listByWarehousePlatformCode.sender_name, - phone: listByWarehousePlatformCode.sender_tel, - }, + sender: (() => { + const senderName = listByWarehousePlatformCode.sender_name || ''; + const senderTel = listByWarehousePlatformCode.sender_tel || ''; + const senderProvince = listByWarehousePlatformCode.province_name || ''; + const senderCity = listByWarehousePlatformCode.city_name || ''; + const senderDistrict = listByWarehousePlatformCode.district_name || ''; + const senderTown = listByWarehousePlatformCode.town_name || ''; + const senderAddress = listByWarehousePlatformCode.address || ''; + const fallback = '仓库未配置发件人'; + return { + address: { + city: senderCity || fallback, + detail: senderAddress || fallback, + district: senderDistrict || fallback, + province: senderProvince || fallback, + town: senderTown || null, + }, + mobile: senderTel || (senderName ? '' : fallback), + name: senderName || fallback, + phone: senderTel || (senderName ? '' : fallback), + }; + })(), trade_order_info_dtos: tradeOrderList, brand_code: String(listByWarehousePlatformCode.site_code || 'default').trim(), need_encrypt: true, @@ -2241,26 +2261,35 @@ class ExpressPlatformService extends MainService { } ); // 构建pdd接口入参 - const pddPayload = { // 这里根据实际需要构建接口入参 type: 'pdd.waybill.get', accessToken: listByWarehousePlatformCode.token, param_waybill_cloud_print_apply_new_request: { need_encrypt: true, - sender: { - address: { - country: '中国', - city: listByWarehousePlatformCode.city_name, - province: listByWarehousePlatformCode.province_name, - district: listByWarehousePlatformCode.district_name, - town: listByWarehousePlatformCode.town_name || null, - detail: listByWarehousePlatformCode.address, - }, - moblie: listByWarehousePlatformCode.sender_tel, - name: listByWarehousePlatformCode.sender_name, - phone: listByWarehousePlatformCode.sender_tel, - }, + sender: (() => { + const senderName = listByWarehousePlatformCode.sender_name || ''; + const senderTel = listByWarehousePlatformCode.sender_tel || ''; + const senderProvince = listByWarehousePlatformCode.province_name || ''; + const senderCity = listByWarehousePlatformCode.city_name || ''; + const senderDistrict = listByWarehousePlatformCode.district_name || ''; + const senderTown = listByWarehousePlatformCode.town_name || ''; + const senderAddress = listByWarehousePlatformCode.address || ''; + const fallback = '仓库未配置发件人'; + return { + address: { + country: '中国', + city: senderCity || fallback, + province: senderProvince || fallback, + district: senderDistrict || fallback, + town: senderTown || null, + detail: senderAddress || fallback, + }, + moblie: senderTel || (senderName ? '' : fallback), + name: senderName || fallback, + phone: senderTel || (senderName ? '' : fallback), + }; + })(), trade_order_info_dtos: tradeOrderList, wp_code: listByWarehousePlatformCode && listByWarehousePlatformCode.express ? (listByWarehousePlatformCode.express.PDD || '') diff --git a/app/service/systems/order_print.js b/app/service/systems/order_print.js index dc9e44c..e894bb1 100644 --- a/app/service/systems/order_print.js +++ b/app/service/systems/order_print.js @@ -2701,6 +2701,22 @@ ${waveFilterSql} const expressSysLogisticsCode = String(orderExpress.sys_logistics_code || '').trim(); const expressSysLogisticsName = String(orderExpress.sys_logistics_name || '').trim(); const documentId = waybillCode || `doc_${orderId}`; + + // 查询仓库 subject_config 用于发件人兜底 + const warehouseId = Number(orderRow.warehouse_id || 0); + let subjectConfig = {}; + if (warehouseId > 0) { + const storeRow = await this.ctx.model.Store.findByPk(warehouseId, { + attributes: ['subject_config'], + raw: true, + }); + if (storeRow && storeRow.subject_config) { + subjectConfig = this.isPlainObject(storeRow.subject_config) + ? storeRow.subject_config + : {}; + } + } + const printPayload = PrinterDataBuilder.buildPlatformRequestSkeleton({ platform: platformCode, order_express: orderExpress, @@ -2709,6 +2725,7 @@ ${waveFilterSql} policy_config: policyConfig, }, policy_config: policyConfig, + subject_config: subjectConfig, template_sample: templateSample, options: { requestId, diff --git a/app/service/systems/order_storage_allocation.js b/app/service/systems/order_storage_allocation.js index dd9028d..5197b13 100644 --- a/app/service/systems/order_storage_allocation.js +++ b/app/service/systems/order_storage_allocation.js @@ -832,7 +832,6 @@ class OrderStorageAllocationService extends MainService { const policyCache = new Map(); const shortageReasonCache = new Map(); const pickingRows = []; - const stockAllocationMap = new Map(); const storageAllocationMap = new Map(); const orderResults = []; const totalCount = pendingOrderIds.length; @@ -1093,7 +1092,6 @@ class OrderStorageAllocationService extends MainService { allocatedQuantityForOrder += allocationQuantity; storageAllocationMap.set(storageRow.id, (storageAllocationMap.get(storageRow.id) || 0) + allocationQuantity); - stockAllocationMap.set(stockId, (stockAllocationMap.get(stockId) || 0) + allocationQuantity); const spaceId = toNumber(storageRow.space_id, 0); if (!spaceId) { @@ -1110,15 +1108,7 @@ class OrderStorageAllocationService extends MainService { storageRow.id, allocationQuantity, { transaction } ); - // 回退 stockAllocationMap 和 storageAllocationMap 中的累加值,防止 wms_stock_warehouse.locked_quantity 批量更新时多锁 - const prevStockQty = stockAllocationMap.get(stockId) || 0; - const newStockQty = prevStockQty - allocationQuantity; - if (newStockQty <= 0) { - stockAllocationMap.delete(stockId); - } else { - stockAllocationMap.set(stockId, newStockQty); - } - + // 回退 storageAllocationMap 中的累加值 const prevStorageQty = storageAllocationMap.get(storageRow.id) || 0; const newStorageQty = prevStorageQty - allocationQuantity; if (newStorageQty <= 0) { @@ -1129,11 +1119,8 @@ class OrderStorageAllocationService extends MainService { writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库位无效,回退库存主表锁定累加', { orderId, - stockId, storageId: storageRow.id, allocationQuantity, - prevStockQty, - newStockQty, prevStorageQty, newStorageQty, }); @@ -1251,107 +1238,6 @@ class OrderStorageAllocationService extends MainService { }); } - const stockLockEntries = Array.from(stockAllocationMap.entries()) - .map(([ stockId, quantity ]) => ({ - stockId: toNumber(stockId, 0), - quantity: toNumber(quantity, 0), - })) - .filter(item => item.stockId > 0 && item.quantity > 0); - - if (stockLockEntries.length > 0) { - writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 准备批量更新库存主表锁定数量', { - warehouseId, - stockLockEntries, - }); - - const lockStockIds = stockLockEntries.map(item => item.stockId); - const existingStockRows = await ctx.model.StockWarehouse.findAll({ - attributes: [ 'id' ], - where: { - id: { - [Op.in]: lockStockIds, - }, - warehouse_id: warehouseId, - }, - transaction, - lock: transaction.LOCK.UPDATE, - raw: true, - }); - - const existingStockIdSet = new Set( - (Array.isArray(existingStockRows) ? existingStockRows : []) - .map(row => toNumber(row && row.id, 0)) - .filter(stockId => stockId > 0) - ); - - const missingStockEntry = stockLockEntries.find(item => !existingStockIdSet.has(item.stockId)); - if (missingStockEntry) { - writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库存主记录缺失,准备抛错', { - warehouseId, - stockId: missingStockEntry.stockId, - quantity: missingStockEntry.quantity, - }); - throw new Error(`库存主记录不存在: ${missingStockEntry.stockId}`); - } - - const updateSqlReplacements = { - warehouseId, - stockIds: lockStockIds, - }; - const caseSqlSegments = []; - - stockLockEntries.forEach((item, index) => { - const stockIdKey = `stockId_${index}`; - const quantityKey = `quantity_${index}`; - updateSqlReplacements[stockIdKey] = item.stockId; - updateSqlReplacements[quantityKey] = item.quantity; - caseSqlSegments.push(`WHEN :${stockIdKey} THEN :${quantityKey}`); - }); - - const updateStockLockSql = ` - UPDATE wms_stock_warehouse - SET locked_quantity = locked_quantity + CASE id - ${caseSqlSegments.join('\n ')} - ELSE 0 - END - WHERE warehouse_id = :warehouseId - AND id IN (:stockIds) - `; - - await ctx.model.query(updateStockLockSql, { - replacements: updateSqlReplacements, - transaction, - }); - - const updatedStockRows = await ctx.model.StockWarehouse.findAll({ - attributes: [ 'id', 'locked_quantity' ], - where: { - id: { - [Op.in]: lockStockIds, - }, - warehouse_id: warehouseId, - }, - transaction, - raw: true, - }); - - const updatedLockedQuantityMap = new Map( - (Array.isArray(updatedStockRows) ? updatedStockRows : []).map(row => [ - toNumber(row && row.id, 0), - toNumber(row && row.locked_quantity, 0), - ]) - ); - - for (const item of stockLockEntries) { - writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库存主表锁定数量更新完成', { - warehouseId, - stockId: item.stockId, - quantity: item.quantity, - locked_quantity: toNumber(updatedLockedQuantityMap.get(item.stockId), 0), - }); - } - } - if (pickingRows.length > 0) { writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 写入 picking 明细', { warehouseId, @@ -1369,10 +1255,7 @@ class OrderStorageAllocationService extends MainService { skippedOrderCount: skippedOrders.length, skippedOrderSample: skippedOrders.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), orderResultSummary: summarizeArrayForLog(orderResults), - stockLockSummary: summarizeArrayForLog(Array.from(stockAllocationMap.entries()).map(([ stockId, quantity ]) => ({ - stock_id: stockId, - locked_quantity: quantity, - }))), + stockLockSummary: [], storageLockSummary: summarizeArrayForLog(Array.from(storageAllocationMap.entries()).map(([ storageId, quantity ]) => ({ storage_id: storageId, locked_quantity: quantity, @@ -1437,10 +1320,7 @@ class OrderStorageAllocationService extends MainService { skipped_orders: skippedOrders, orders: [ ...skippedOrders, ...orderResults ], picking_count: pickingRows.length, - stock_lock_summary: Array.from(stockAllocationMap.entries()).map(([ stockId, quantity ]) => ({ - stock_id: stockId, - locked_quantity: quantity, - })), + stock_lock_summary: [], storage_lock_summary: Array.from(storageAllocationMap.entries()).map(([ storageId, quantity ]) => ({ storage_id: storageId, locked_quantity: quantity, @@ -1460,7 +1340,7 @@ class OrderStorageAllocationService extends MainService { shortageOrderIds: summarizeArrayForLog(responseData.shortage_order_ids), skippedOrders: summarizeArrayForLog(responseData.skipped_orders), orders: summarizeArrayForLog(responseData.orders), - stockLockSummary: summarizeArrayForLog(responseData.stock_lock_summary), + stockLockSummary: [], storageLockSummary: summarizeArrayForLog(responseData.storage_lock_summary), shortageMessages: summarizeArrayForLog(responseData.shortage_messages), pickingCount: responseData.picking_count, @@ -2008,7 +1888,6 @@ class OrderStorageAllocationService extends MainService { const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); const pickingModel = ctx.model.Picking; const storageModel = ctx.model.Storage; - const stockModel = ctx.model.StockWarehouse; if (!pickingModel || typeof pickingModel.findAll !== 'function' || typeof pickingModel.destroy !== 'function') { throw new Error('wms_picking 模型不可用'); @@ -2018,10 +1897,6 @@ class OrderStorageAllocationService extends MainService { throw new Error('wms_storage 模型不可用'); } - if (!stockModel || typeof stockModel.findByPk !== 'function') { - throw new Error('wms_stock_warehouse 模型不可用'); - } - const orderRows = await orderModel.findAll({ where: { id: { @@ -2195,7 +2070,6 @@ class OrderStorageAllocationService extends MainService { } const storageUnlockSummary = []; - const stockUnlockSummary = []; for (const [ storageId, quantity ] of storageQuantityMap.entries()) { if (quantity <= 0) { @@ -2207,11 +2081,6 @@ class OrderStorageAllocationService extends MainService { throw new Error(`库存记录不存在: ${storageId}`); } - const stockId = toNumber(storageRow.stock_id, 0); - if (stockId <= 0) { - throw new Error(`库存记录缺少 stock_id: ${storageId}`); - } - await ctx.service.systems.storage.index.unlockQuantity(storageId, quantity, { transaction, }); @@ -2220,49 +2089,6 @@ class OrderStorageAllocationService extends MainService { storage_id: storageId, unlocked_quantity: quantity, }); - - if (typeof stockModel.update === 'function') { - const decrementResult = await stockModel.update({ - locked_quantity: app.Sequelize.literal(`locked_quantity - ${Number(quantity)}`), - update_at: app.Sequelize.literal('CURRENT_TIMESTAMP'), - }, { - where: { - id: stockId, - locked_quantity: { - [Op.gte]: Number(quantity), - }, - }, - transaction, - }); - - if (!Array.isArray(decrementResult) || Number(decrementResult[0] || 0) <= 0) { - throw new Error(`库存主记录锁定数量不足,无法释放: ${stockId}`); - } - } else { - const stockRecord = await stockModel.findByPk(stockId, { - transaction, - }); - - if (!stockRecord) { - throw new Error(`库存主记录不存在: ${stockId}`); - } - - const currentLocked = toNumber(stockRecord.locked_quantity, 0); - if (currentLocked < Number(quantity)) { - throw new Error(`库存主记录锁定数量不足,无法释放: ${stockId}`); - } - - await stockRecord.increment('locked_quantity', { - by: -quantity, - transaction, - silent: true, - }); - } - - stockUnlockSummary.push({ - stock_id: stockId, - unlocked_quantity: quantity, - }); } const cancelPickingIds = []; @@ -2332,7 +2158,7 @@ class OrderStorageAllocationService extends MainService { orders: [ ...skippedOrders, ...orderResults ], picking_count: cancelPickingIds.length, storage_unlock_summary: storageUnlockSummary, - stock_unlock_summary: stockUnlockSummary, + stock_unlock_summary: [], }; await transaction.commit(); diff --git a/app/service/systems/pick.js b/app/service/systems/pick.js index 9d6fc5f..b71a08b 100644 --- a/app/service/systems/pick.js +++ b/app/service/systems/pick.js @@ -1777,6 +1777,35 @@ class PickSystemService extends Service { } } + // 检查目标订单是否已分配储位(storage_status='fin'),防止订单在波次中被取消储位分配后仍然完成拣货 + if (targetOrderIds.length > 0) { + const orderModel = await this.getOrderModel(warehouseId); + const unallocatedOrders = await orderModel.findAll({ + where: { + warehouse_id: warehouseId, + id: { + [this.app.Sequelize.Op.in]: targetOrderIds, + }, + storage_status: { + [this.app.Sequelize.Op.ne]: 'fin', + }, + }, + attributes: [ 'id', 'storage_status' ], + raw: true, + transaction, + }); + + if (unallocatedOrders && unallocatedOrders.length > 0) { + const detailList = unallocatedOrders.map( + o => `订单${o.id}(storage_status=${o.storage_status})` + ).join(';'); + throw this.createBusinessError( + `以下订单未分配储位,无法完成拣货:${detailList}`, + 400 + ); + } + } + await ctx.model.query(` UPDATE wms_wave_pick_task_order SET pick_status = 1, @@ -2023,7 +2052,7 @@ class PickSystemService extends Service { extras: { message: `订单${orderId}拣货完成`, warehouseId, - externalLogType: 'PDA', + externalLogType: 'API', }, })); await operationLogService.createOperationLogs(logPayloads); diff --git a/app/service/systems/receiving_entry_match.js b/app/service/systems/receiving_entry_match.js index 269dab3..6d41b74 100644 --- a/app/service/systems/receiving_entry_match.js +++ b/app/service/systems/receiving_entry_match.js @@ -746,136 +746,176 @@ class ReceivingEntryMatchService extends Service { } /** - * 手动匹配入库单与收货单。 - * - * 同步执行明细对比并触发回传,返回结构化匹配结果。 - * 适用场景:运营人员手动指定收货单与入库单进行匹配并回传。 - * - * 匹配规则(复用 _compareDetails): - * - full_match:两者 SKU 与数量完全一致 → 按来源回传 - * - receiving_covers_entry:收货单覆盖入库单 → 回传 + 标记部分入库 - * - entry_exceeds_receiving / no_match → 仅返回对比结果,不触发回传 - * - * @param {number} receivingId 收货单 ID - * @param {number} entryOrderId 入库单 ID - * @return {Promise} 匹配结果对象 - * @return {string} return.matchType 匹配类型:full_match / receiving_covers_entry / entry_exceeds_receiving / no_match - * @return {Object} return.comparisonResult 明细对比结果 - * @return {boolean} return.callbackSent 是否已发送回传 - * @return {Object|null} return.callbackResult 回传结果(未发送时为 null) - * @return {boolean} return.partialStorageMarked 是否已标记部分入库 - * @return {Object} return.entryOrder 入库单摘要 - * @return {Object} return.receivingOrder 收货单摘要 + * 批量绑定入库单明细与收货单明细。 + * 依次校验入库单状态、商品匹配关系、可用数量,事务写入绑定并确保主级绑定存在。 + * @param {Object} data 请求参数 + * @param {number} data.entry_order_id 入库单ID + * @param {Array} data.bindings 绑定列表 + * @param {number} data.bindings[].entry_item_id 入库单明细ID + * @param {number} data.bindings[].receiving_detail_id 收货单明细ID + * @param {number} data.bindings[].allocated_quantity 分配数量 + * @return {Promise} { success: [...], failed: [...], success_count, failed_count } */ - async manualMatch(receivingId, entryOrderId) { + /** + * 批量绑定入库单明细与收货单明细。 + * 在事务中对每条绑定使用 FOR UPDATE 行锁防并发超卖,失败项返回结构化错误码。 + * + * @param {Object} data 请求参数 + * @param {number} data.entry_order_id 入库单 ID + * @param {Array<{entry_item_id: number, receiving_detail_id: number, allocated_quantity: number}>} data.bindings 绑定列表 + * @return {Promise<{success: Array, failed: Array, success_count: number, failed_count: number}>} 绑定结果 + */ + async bindReceivingDetails(data = {}) { const { ctx } = this; + const { entry_order_id: entryOrderId, bindings = [] } = data || {}; - // 1. 加载入库单及其明细 - const entryOrder = await ctx.model.EntryOrder.findOne({ - where: { id: entryOrderId, is_enabled: 1, deleted_at: null }, - include: [{ - model: ctx.model.EntryItems, - as: 'items', - required: false, - attributes: [ 'id', 'item_code', 'stock_id', 'count', 'received_quantity', 'inventory_type' ], - }], - }); - - if (!entryOrder) { - throw new Error(`入库单不存在:${entryOrderId}`); + if (!entryOrderId || !Array.isArray(bindings) || bindings.length === 0) { + throw new Error('参数不完整'); } - // 2. 加载收货单及其明细 - const receivingOrder = await ctx.model.Receiving.findOne({ - where: { id: receivingId, is_deleted: false }, - include: [{ - model: ctx.model.ReceivingDetail, - as: 'details', - required: false, - attributes: [ - 'id', 'system_product_id', 'product_name', 'actual_quantity', - 'storage_status', 'stored_quantity', - ], - }], - }); - - if (!receivingOrder) { - throw new Error(`收货单不存在:${receivingId}`); + // 1. 查询入库单,校验状态(必须是 PENDING 或 CREATED) + const entryOrder = await ctx.model.EntryOrder.findByPk(entryOrderId); + if (!entryOrder || ![ 'CREATED', 'PENDING' ].includes(entryOrder.order_status)) { + // 入库单状态不对 → 全部 bindings 标记为 ENTRY_ORDER_STATUS_INVALID + const allFailed = bindings.map(b => ({ + entry_item_id: b.entry_item_id, + receiving_detail_id: b.receiving_detail_id, + allocated_quantity: b.allocated_quantity, + error_code: 'ENTRY_ORDER_STATUS_INVALID', + message: '入库单状态不允许绑定', + detail: { order_status: entryOrder ? entryOrder.order_status : null }, + })); + return { success: [], failed: allFailed, success_count: 0, failed_count: allFailed.length }; } - // 3. 校验同仓库 - if (entryOrder.warehouse_id !== receivingOrder.warehouse_id) { - throw new Error( - `入库单仓库(${entryOrder.warehouse_id})与收货单仓库(${receivingOrder.warehouse_id})不一致` - ); + const success = []; + const failed = []; + + for (const binding of bindings) { + const { entry_item_id: entryItemId, receiving_detail_id: receivingDetailId, allocated_quantity: qty } = binding; + try { + // 2. 查询 entry_item 和对应的 stock_id + const entryItem = await ctx.model.EntryItems.findByPk(entryItemId); + if (!entryItem) { + throw { + error_code: 'ENTRY_ITEM_NOT_FOUND', + message: '入库明细不存在', + detail: { entry_item_id: entryItemId }, + }; + } + + // 3. 通过 stock_id → system_product_id 校验收货单明细匹配 + const sw = await ctx.model.StockWarehouse.findOne({ + where: { id: entryItem.stock_id, warehouse_id: entryOrder.warehouse_id }, + attributes: [ 'system_product_id' ], + raw: true, + }); + if (!sw || !sw.system_product_id) { + throw { + error_code: 'STOCK_NOT_FOUND', + message: '商品不存在', + detail: { stock_id: entryItem.stock_id }, + }; + } + + // 4. 事务:FOR UPDATE 锁行 → 查已分配量 → 写入绑定 + await ctx.model.transaction(async t => { + // 4a. 先锁收货明细行 + const lockedDetail = await ctx.model.query( + `SELECT id, actual_quantity, receiving_id, system_product_id + FROM wms_receiving_detail + WHERE id = :rdId FOR UPDATE`, + { + replacements: { rdId: receivingDetailId }, + type: ctx.model.QueryTypes.SELECT, + transaction: t, + } + ); + if (!lockedDetail || lockedDetail.length === 0) { + throw { + error_code: 'RECEIVING_DETAIL_NOT_FOUND', + message: '收货明细不存在', + detail: { receiving_detail_id: receivingDetailId }, + }; + } + + // 4b. 校验收货明细与入库商品是否匹配(system_product_id) + if (lockedDetail[0].system_product_id !== sw.system_product_id) { + throw { + error_code: 'RECEIVING_DETAIL_MISMATCH', + message: '收货明细与入库商品不匹配', + detail: { + entry_item_id: entryItemId, + receiving_detail_id: receivingDetailId, + expected_sp_id: sw.system_product_id, + actual_sp_id: lockedDetail[0].system_product_id, + }, + }; + } + + // 4c. 查已 committed 的分配量 + const allocatedSum = await ctx.model.query( + `SELECT COALESCE(SUM(allocated_quantity), 0) AS total + FROM wms_entry_receiving_binding + WHERE receiving_detail_id = :rdId AND status = 'committed' AND deleted_at IS NULL`, + { + replacements: { rdId: receivingDetailId }, + type: ctx.model.QueryTypes.SELECT, + transaction: t, + } + ); + const availableQty = lockedDetail[0].actual_quantity - Number(allocatedSum[0]?.total || 0); + if (qty > availableQty) { + throw { + error_code: 'INSUFFICIENT_AVAILABLE_QUANTITY', + message: '分配数量超出可用量', + detail: { available_quantity: availableQty, requested_quantity: qty }, + }; + } + + // 4d. 写入绑定 + await ctx.model.EntryReceivingBinding.create({ + entry_item_id: entryItemId, + receiving_detail_id: receivingDetailId, + allocated_quantity: qty, + status: 'committed', + creator_id: ctx.currentUser?.id || 0, + }, { transaction: t }); + + // 确保主级绑定存在 + await ctx.model.EntryOrderReceiving.findOrCreate({ + where: { entry_order_id: entryOrderId, receiving_id: lockedDetail[0].receiving_id }, + defaults: { entry_order_id: entryOrderId, receiving_id: lockedDetail[0].receiving_id }, + transaction: t, + }); + }); + + success.push({ entry_item_id: entryItemId, receiving_detail_id: receivingDetailId, allocated_quantity: qty }); + } catch (err) { + // 结构化错误对象或普通 Error 统一转为 failed 项 + if (err.error_code) { + failed.push({ + entry_item_id: entryItemId, + receiving_detail_id: receivingDetailId, + allocated_quantity: qty, + error_code: err.error_code, + message: err.message, + detail: err.detail || {}, + }); + } else { + failed.push({ + entry_item_id: entryItemId, + receiving_detail_id: receivingDetailId, + allocated_quantity: qty, + error_code: 'INTERNAL_ERROR', + message: err.message || '未知错误', + detail: {}, + }); + } + } } - // 4. 构建入库单明细 - const entryItems = (entryOrder.items || []).map(item => ({ - stockId: item.stock_id, - itemCode: item.item_code, - count: item.count || 0, - receivedQuantity: item.received_quantity || 0, - inventoryType: item.inventory_type || 'ZP', - })); - - // 5. 构建收货单明细 - const receivingPlain = typeof receivingOrder.toJSON === 'function' - ? receivingOrder.toJSON() - : receivingOrder; - const receivingDetails = (receivingPlain.details || []).map(d => ({ - id: d.id, - system_product_id: d.system_product_id, - product_name: d.product_name, - actual_quantity: d.actual_quantity, - storage_status: d.storage_status, - stored_quantity: d.stored_quantity || 0, - })); - - // 6. 对比明细 - const comparisonResult = this._compareDetails(entryItems, receivingDetails); - - const result = { - matchType: comparisonResult.type, - comparisonResult, - callbackSent: false, - callbackResult: null, - partialStorageMarked: false, - entryOrder: { - id: entryOrder.id, - entry_order_code: entryOrder.entry_order_code, - source_type: entryOrder.source_type, - warehouse_id: entryOrder.warehouse_id, - status: entryOrder.status, - }, - receivingOrder: { - id: receivingOrder.id, - receiving_number: receivingOrder.receiving_number, - status: receivingOrder.status, - storage_status: receivingOrder.storage_status, - }, - }; - - // 7. 根据对比结果处理 - if (comparisonResult.type === 'full_match') { - const callbackResult = await this._sendCallback(entryOrder, receivingOrder, 'manual_match'); - result.callbackSent = true; - result.callbackResult = callbackResult; - } else if (comparisonResult.type === 'receiving_covers_entry') { - const callbackResult = await this._sendCallback(entryOrder, receivingOrder, 'manual_match'); - result.callbackSent = true; - result.callbackResult = callbackResult; - - const markResult = await this._markReceivingPartialStorage( - receivingOrder.id, - comparisonResult, - receivingOrder.warehouse_id - ); - result.partialStorageMarked = markResult.success; - } - // entry_exceeds_receiving / no_match → 不触发回传 - - return result; + return { success, failed, success_count: success.length, failed_count: failed.length }; } } diff --git a/app/service/systems/setting/warehouse.js b/app/service/systems/setting/warehouse.js index e3a1f1d..8dd1bfa 100644 --- a/app/service/systems/setting/warehouse.js +++ b/app/service/systems/setting/warehouse.js @@ -69,6 +69,69 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([ description: '仓库默认使用的平台编码', maxLength: 50, }), + Object.freeze({ + key: 'sender_name', + name: '发件人姓名', + type: 'string', + default: '', + required: false, + description: '仓库默认发件人姓名', + maxLength: 50, + }), + Object.freeze({ + key: 'sender_tel', + name: '发件人电话', + type: 'string', + default: '', + required: false, + description: '仓库默认发件人联系电话', + maxLength: 20, + }), + Object.freeze({ + key: 'province_name', + name: '省份', + type: 'string', + default: '', + required: false, + description: '仓库默认发件省份', + maxLength: 50, + }), + Object.freeze({ + key: 'city_name', + name: '城市', + type: 'string', + default: '', + required: false, + description: '仓库默认发件城市', + maxLength: 50, + }), + Object.freeze({ + key: 'district_name', + name: '区/县', + type: 'string', + default: '', + required: false, + description: '仓库默认发件区/县', + maxLength: 50, + }), + Object.freeze({ + key: 'town_name', + name: '镇/街道', + type: 'string', + default: '', + required: false, + description: '仓库默认发件镇/街道', + maxLength: 50, + }), + Object.freeze({ + key: 'address', + name: '详细地址', + type: 'string', + default: '', + required: false, + description: '仓库默认发件详细地址', + maxLength: 200, + }), Object.freeze({ key: 'group_wave_prefix', name: '团购波次前缀', diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index ece8b01..af6c592 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -1911,21 +1911,59 @@ class stockStoreService extends Service { const hasPrevious = page > 1; const hasNext = page < totalPages; - // 批量查询条码和图片信息(复用 getStockDetails 缓存) + // 批量查询条码和图片信息(直接查 DB,不走 getStockDetails 缓存) const stockIds = data.map(item => item.id); const stockDetailsMap = new Map(); if (stockIds.length > 0) { - const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails( - stockIds, - { warehouseId: ctx.user.store_id } - ); - for (const detail of stockDetails) { - const sid = Number(detail.id); + // 并行查询条码和图片表(无缓存),避免影响其他接口对 getStockDetails 缓存的使用 + const [ barcodeRows, imageRows ] = await Promise.all([ + app.model.StockBarcode.findAll({ + where: { stock_id: { [ Op.in ]: stockIds } }, + attributes: [ 'id', 'barcode', 'stock_id' ], + raw: true, + }), + app.model.FileReference.findAll({ + where: { + business_type: 'stock', + business_id: { [ Op.in ]: stockIds.map(String) }, + }, + include: [{ + model: app.model.File, + as: 'file', + attributes: [ 'file_url' ], + required: false, + }], + raw: true, + }), + ]); + + // 按 stock_id 分组条码 + const barcodeMap = new Map(); + for (const row of barcodeRows) { + const sid = row.stock_id; + const bc = (row.barcode && String(row.barcode).trim()) || ''; + if (!bc) continue; + if (!barcodeMap.has(sid)) { + barcodeMap.set(sid, []); + } + barcodeMap.get(sid).push(bc); + } + + // 按 business_id 分组图片(有图片即认为 is_images=Y) + const imageStockIdSet = new Set(); + for (const row of imageRows) { + const sid = Number(row.business_id); + const url = (row['file.file_url'] && String(row['file.file_url']).trim()) || ''; + if (url) { + imageStockIdSet.add(sid); + } + } + + for (const item of data) { + const sid = item.id; stockDetailsMap.set(sid, { - barcodes: Array.isArray(detail.barcodes) - ? detail.barcodes.map(bc => String(bc.barcode || '').trim()).filter(Boolean) - : [], - images: detail.is_images === 'Y' ? [] : [], + barcodes: barcodeMap.get(sid) || [], + images: [], }); } } @@ -1936,7 +1974,7 @@ class stockStoreService extends Service { const lockRate = item.quantity > 0 ? (item.locked_quantity / item.quantity * 100).toFixed( 2) : 0; - // 从 getStockDetails 获取该商品的条码和图片 + // 从直接的 DB 查询结果获取该商品的条码和图片 const stockDetail = stockDetailsMap.get(item.id); const itemBarcodes = stockDetail ? stockDetail.barcodes : []; const itemImages = stockDetail ? stockDetail.images : []; diff --git a/app/service/systems/storage/entry.js b/app/service/systems/storage/entry.js index 54792c1..0f6a91b 100644 --- a/app/service/systems/storage/entry.js +++ b/app/service/systems/storage/entry.js @@ -523,8 +523,9 @@ class EntryService extends Service { } // 扁平化 items:用 getStockDetails 返回的商品详情替换原有的 stock + barcodes + let flattenedItems; if (entryOrderJSON.items && Array.isArray(entryOrderJSON.items)) { - entryOrderJSON.items = entryOrderJSON.items.map(item => { + flattenedItems = entryOrderJSON.items.map(item => { const { item_code, item_id, stock_id: itemStockId, ...rest } = item; const stockDetail = itemStockId != null ? stockDetailMap.get(Number(itemStockId)) || null : null; const directInboundQty = (stockDetail && directInboundMap[stockDetail.id]) || 0; @@ -551,8 +552,14 @@ class EntryService extends Service { remaining_quantity: remaining, }; }); + } else { + flattenedItems = entryOrderJSON.items || []; } + // 为每个 item 补充可匹配的收货单明细及剩余可用量 + const enrichedItems = await this.enrichItemsWithAvailableReceivingDetails(flattenedItems, warehouseId); + entryOrderJSON.items = enrichedItems; + return { code: 200, message: '查询成功', @@ -562,6 +569,87 @@ class EntryService extends Service { }; } + /** + * 为 entry items 批量补充可匹配的收货单明细及剩余可用量。 + * 匹配规则:entry_item.stock_id 即 wms_stock_warehouse.id,与 wms_receiving_detail.system_product_id 直接对应。 + * 只返回收货单状态为未完成(status NOT IN ('completed','cancelled'))且未完全入库(storage_status IN ('none','partial'))的明细。 + * @param {Object[]} items 扁平化后的 entry items 数组 + * @param {number} warehouseId 仓库ID + * @return {Promise} 补充了 available_receiving_details 的 items + */ + async enrichItemsWithAvailableReceivingDetails(items, warehouseId) { + if (!Array.isArray(items) || items.length === 0) return items; + + const { ctx } = this; + const stockIds = [ ...new Set(items.map(i => Number(i.stock_id)).filter(Boolean)) ]; + if (stockIds.length === 0) return items; + + // stock_id 即 wms_stock_warehouse.id + // wms_receiving_detail.system_product_id 也指向 wms_stock_warehouse.id + // 所以映射关系就是 id → id,只需确认 stock_warehouse 记录存在 + const swRows = await ctx.model.StockWarehouse.findAll({ + where: { id: { [ctx.app.Sequelize.Op.in]: stockIds }, warehouse_id: warehouseId }, + attributes: [ 'id' ], + raw: true, + }); + const stockIdToSystemProductId = new Map(); + for (const row of swRows) { + stockIdToSystemProductId.set(Number(row.id), Number(row.id)); + } + const systemProductIds = [ ...new Set(stockIdToSystemProductId.values()) ]; + if (systemProductIds.length === 0) return items; + + // 批量查询收货单明细可用量 + const rows = await ctx.model.query( + `SELECT + rd.id AS receiving_detail_id, + rd.receiving_id, + rd.system_product_id, + r.receiving_number, + rd.actual_quantity, + COALESCE(SUM(erb.allocated_quantity), 0) AS allocated_quantity, + rd.actual_quantity - COALESCE(SUM(erb.allocated_quantity), 0) AS available_quantity + FROM wms_receiving_detail rd + INNER JOIN wms_receiving r ON r.id = rd.receiving_id AND r.deleted_at IS NULL + LEFT JOIN wms_entry_receiving_binding erb + ON erb.receiving_detail_id = rd.id + AND erb.status = 'committed' + AND erb.deleted_at IS NULL + WHERE rd.system_product_id IN (:systemProductIds) + AND r.status NOT IN ('completed', 'cancelled') + AND rd.storage_status IN ('none', 'partial') + GROUP BY rd.id, rd.receiving_id, rd.system_product_id, r.receiving_number, rd.actual_quantity + HAVING available_quantity > 0 + ORDER BY rd.system_product_id, available_quantity DESC`, + { replacements: { systemProductIds }, type: ctx.model.QueryTypes.SELECT } + ); + + // 按 system_product_id 分组 + const mapBySystemProductId = new Map(); + for (const row of rows) { + const spid = Number(row.system_product_id); + if (!mapBySystemProductId.has(spid)) mapBySystemProductId.set(spid, []); + mapBySystemProductId.get(spid).push({ + receiving_id: Number(row.receiving_id), + receiving_number: String(row.receiving_number || '').trim(), + receiving_detail_id: Number(row.receiving_detail_id), + actual_quantity: Number(row.actual_quantity || 0), + allocated_quantity: Number(row.allocated_quantity || 0), + available_quantity: Number(row.available_quantity || 0), + }); + } + + // 为每个 item 挂载 + return items.map(item => { + const sid = Number(item.stock_id); + const spid = stockIdToSystemProductId.get(sid) || 0; + return { + ...item, + available_receiving_details: spid > 0 ? (mapBySystemProductId.get(spid) || []) : [], + }; + }); + } + /** * 归一化作废入参中的入库单 ID 列表。 * 优先使用 ids;未传 ids 时回退到 id。 @@ -821,6 +909,463 @@ class EntryService extends Service { return await ctx.service.systems.inboundDirectLog.removeItem(data); } + /** + * 快捷直入/虚拟入库:将入库单的所有商品按明细数量全部直入到虚拟库位(space_id=2),跳过收货、质检等正常流程。 + * @param {Object} data 请求体 + * @param {number} data.id 入库单ID + * @return {Promise} code/data/message 结构 + */ + async quickInbound(data = {}) { + const { ctx, app } = this; + const orderId = Number(data.id || 0); + + if (!orderId) { + return { + code: 400, + message: 'id 必填', + data: null, + }; + } + + // 1. 校验入库单 + const entryOrder = await this.getOwnedEntryOrderById(orderId); + if (!entryOrder) { + return { + code: 404, + message: '入库单不存在或无权访问', + data: null, + }; + } + + if (entryOrder.order_status !== 'CREATED') { + if (entryOrder.order_status === 'CANCELLED') { + return { + code: 400, + message: '已作废入库单不允许快捷入库', + data: null, + }; + } + if (entryOrder.order_status === 'COMPLETED') { + return { + code: 400, + message: '入库单已完成,请勿重复提交', + data: null, + }; + } + return { + code: 400, + message: `入库单状态不允许快捷直入,当前状态:${entryOrder.order_status}`, + data: null, + }; + } + + // 2. 查询入库单所有明细 + const entryItems = await ctx.model.EntryItems.findAll({ + where: { order_id: entryOrder.id }, + }); + + if (!entryItems.length) { + return { + code: 400, + message: '请先添加入库明细', + data: null, + }; + } + + const warehouseId = entryOrder.warehouse_id; + const storeId = entryOrder.store_id; + const batchNo = entryOrder.entry_order_code; + const hardcodedSpaceId = 2; + const transaction = await ctx.model.transaction(); + + const processedStockIds = new Set(); + let totalInboundQty = 0; + + try { + // 3. 逐商品写入库存 + for (const item of entryItems) { + const stockId = item.stock_id; + if (!stockId) continue; + + const planQty = Number(item.count) || 0; + if (planQty <= 0) continue; + + const inventoryType = item.inventory_type || 'ZP'; + + // 更新入库明细的 received_quantity 为计划数量(全部入库) + await ctx.model.EntryItems.update({ + received_quantity: planQty, + }, { + where: { id: item.id }, + transaction, + }); + + // 同一 stock_id 只写一次库存 + if (processedStockIds.has(String(stockId))) continue; + processedStockIds.add(String(stockId)); + totalInboundQty += planQty; + + // 锁定并更新 StockWarehouse 总库存 + const stockRecord = await ctx.model.StockWarehouse.findOne({ + where: { id: stockId, is_valid: 'Y', deleted_at: null }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (stockRecord) { + const beforeQuantity = Number(stockRecord.quantity) || 0; + const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0; + + await stockRecord.increment('quantity', { by: planQty, transaction, silent: true }); + await stockRecord.reload({ transaction }); + + const afterQuantity = Number(stockRecord.quantity) || 0; + const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0; + + // 写入库存流水 + await ctx.service.systems.stockTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: warehouseId, + store_id: storeId, + stock_id: stockId, + quantity: planQty, + batch_no: batchNo, + order_type: entryOrder.order_type, + order_no: entryOrder.entry_order_code, + entry_order_id: entryOrder.id, + operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), + operator_name: ctx.user?.employees_name || '', + remark: '快捷直入/虚拟入库', + before_quantity: beforeQuantity, + after_quantity: afterQuantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: afterLockedQuantity, + created_at: new Date(), + }, { transaction }); + } + + // 创建/更新 Storage 库位库存(space_id 硬编码为 2) + const storageRecord = await ctx.model.Storage.findOne({ + where: { + space_id: hardcodedSpaceId, + stock_id: stockId, + batch_no: batchNo, + inventory_type: inventoryType, + is_enabled: 1, + delete_at: null, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (storageRecord) { + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity + ${planQty}`), + available_quantity: app.Sequelize.literal(`available_quantity + ${planQty}`), + entry_order_id: entryOrder.id, + inbound_time: new Date(), + inbound_order_no: entryOrder.entry_order_code, + updated_at: new Date(), + }, { + where: { id: storageRecord.id }, + transaction, + }); + } else { + await ctx.model.Storage.create({ + warehouse_id: warehouseId, + store_id: storeId, + space_id: hardcodedSpaceId, + stock_id: stockId, + batch_no: batchNo, + inventory_type: inventoryType, + quantity: planQty, + locked_quantity: 0, + available_quantity: planQty, + inbound_time: new Date(), + inbound_order_no: entryOrder.entry_order_code, + receiving_id: null, + entry_order_id: entryOrder.id, + supplier_id: null, + supplier_batch_no: null, + is_enabled: 1, + created_at: new Date(), + updated_at: new Date(), + }, { transaction }); + } + } + + // 4. 更新入库单状态为 COMPLETED + await entryOrder.update({ + order_status: 'COMPLETED', + sync_status: 'SUCCESS', + sync_message: JSON.stringify({ + completedAt: new Date(), + totalQuantity: totalInboundQty, + itemCount: processedStockIds.size, + source: 'quick_inbound', + }), + updated_at: new Date(), + }, { transaction }); + + // 记录操作日志(事务内) + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry_order', + businessId: entryOrder.id, + operationCode: 'QUICK_INBOUND', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: entryOrder.warehouse_id, + message: `快捷直入完成,共 ${processedStockIds.size} 种商品,总数量 ${totalInboundQty}`, + }, + transaction, + }); + + await transaction.commit(); + } catch (error) { + if (transaction && typeof transaction.rollback === 'function') { + await transaction.rollback(); + } + throw error; + } + + // 事务外:异步触发奇门/API 回传(复用 inboundDirectLog 的回传逻辑) + setImmediate(() => { + ctx.service.systems.inboundDirectLog._sendCallback(entryOrder).catch(err => { + ctx.logger.error(`[quickInbound] 回传异常 entryOrderId=${entryOrder.id}: ${err.message}`, err.stack); + }); + }); + + return { + code: 200, + message: '快捷入库完成', + data: { + id: entryOrder.id, + entry_order_code: entryOrder.entry_order_code, + order_status: 'COMPLETED', + sync_status: 'SUCCESS', + items_count: entryItems.length, + total_quantity: totalInboundQty, + }, + }; + } + + /** + * 入库单商品与收货单商品逐行对照视图。 + * 以入库单明细为主,按 stock_id ↔ system_product_id 匹配收货单明细, + * 返回匹配/未匹配/收货单多余的对照结果。 + * + * @param {Object} data 请求参数 + * @param {number} data.entry_order_id 入库单ID + * @param {number} data.receiving_id 收货单ID + * @return {Promise} code/data/message 结构 + */ + async receivingCompare(data = {}) { + const { ctx, app } = this; + const entryOrderId = Number(data.entry_order_id || 0); + const receivingId = Number(data.receiving_id || 0); + const warehouseId = ctx.user.store_id; + + if (!entryOrderId) { + return { code: 400, message: 'entry_order_id 必填', data: null }; + } + if (!receivingId) { + return { code: 400, message: 'receiving_id 必填', data: null }; + } + + // 1. 校验收货单存在性 + const receivingOrder = await ctx.model.Receiving.findOne({ + where: { + id: receivingId, + warehouse_id: warehouseId, + is_deleted: false, + }, + attributes: [ 'id', 'receiving_number', 'status', 'storage_status' ], + raw: true, + }); + if (!receivingOrder) { + return { code: 404, message: '收货单不存在或无权访问', data: null }; + } + + // 2. 校验收货单存在性(复用 getOwnedEntryOrderById) + const entryOrder = await this.getOwnedEntryOrderById(entryOrderId); + if (!entryOrder) { + return { code: 404, message: '入库单不存在或无权访问', data: null }; + } + + // 3. 查询入库单明细 + const entryItems = await ctx.model.EntryItems.findAll({ + where: { order_id: entryOrderId }, + attributes: [ 'id', 'stock_id', 'count', 'received_quantity' ], + raw: true, + }); + + // 4. 查询收货单明细 + const receivingDetails = await ctx.model.ReceivingDetail.findAll({ + where: { receiving_id: receivingId }, + attributes: [ 'id', 'system_product_id', 'actual_quantity', 'product_name' ], + raw: true, + }); + + // 5. 收集所有 stock_id,批量查询商品信息 + const entryStockIds = [ ...new Set(entryItems.map(item => Number(item.stock_id)).filter(Boolean)) ]; + const receivingSystemProductIds = [ ...new Set(receivingDetails.map(d => Number(d.system_product_id)).filter(Boolean)) ]; + + // 6. 批量查询 wms_stock_warehouse — 入库单商品(按 stock_id)和收货单商品(按 system_product_id = id) + const allStockIds = [ ...new Set([ ...entryStockIds, ...receivingSystemProductIds ]) ]; + const stockDetailMap = new Map(); + if (allStockIds.length > 0) { + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(allStockIds, { warehouseId }); + for (const detail of stockDetails) { + stockDetailMap.set(detail.id, detail); + } + } + + // stock_id 即 wms_stock_warehouse.id,与 wms_receiving_detail.system_product_id 直接对应 + // 只需确认 stock_warehouse 记录存在即可构建映射 + const stockIdToSystemProductId = new Map(); + const systemProductIdToEntryStockIds = new Map(); + if (entryStockIds.length > 0) { + const swRows = await ctx.model.StockWarehouse.findAll({ + where: { id: { [app.Sequelize.Op.in]: entryStockIds }, warehouse_id: warehouseId }, + attributes: [ 'id' ], + raw: true, + }); + for (const row of swRows) { + const stockId = Number(row.id); + stockIdToSystemProductId.set(stockId, stockId); + if (!systemProductIdToEntryStockIds.has(stockId)) { + systemProductIdToEntryStockIds.set(stockId, []); + } + systemProductIdToEntryStockIds.get(stockId).push(stockId); + } + } + + // 7. 查询已分配量(从 wms_entry_receiving_binding) + const receivingDetailIds = receivingDetails.map(d => d.id); + const allocatedMap = new Map(); + if (receivingDetailIds.length > 0) { + const bindingRows = await ctx.model.EntryReceivingBinding.findAll({ + attributes: [ + 'receiving_detail_id', + [ app.Sequelize.fn('SUM', app.Sequelize.col('allocated_quantity')), 'total_allocated' ], + ], + where: { + receiving_detail_id: { [app.Sequelize.Op.in]: receivingDetailIds }, + status: 'committed', + deleted_at: null, + }, + group: [ 'receiving_detail_id' ], + raw: true, + }); + for (const row of bindingRows) { + allocatedMap.set(Number(row.receiving_detail_id), Number(row.total_allocated) || 0); + } + } + + // 8. 构建对照视图:以入库单明细为主 + const comparison = []; + const matchedReceivingDetailIds = new Set(); + + for (const entryItem of entryItems) { + const stockId = Number(entryItem.stock_id || 0); + const systemProductId = stockIdToSystemProductId.get(stockId) || 0; + const stockDetail = stockDetailMap.get(stockId) || null; + + // 找到同 system_product_id 的收货单明细 + const matchedReceiving = systemProductId > 0 + ? receivingDetails.filter(rd => Number(rd.system_product_id) === systemProductId) + : []; + + if (matchedReceiving.length > 0) { + // 有匹配的收货明细 + for (const rd of matchedReceiving) { + matchedReceivingDetailIds.add(rd.id); + const rdStockDetail = (rd.system_product_id != null && stockDetailMap.get(Number(rd.system_product_id))) || null; + const allocated = allocatedMap.get(Number(rd.id)) || 0; + const available = Math.max(0, (Number(rd.actual_quantity) || 0) - allocated); + comparison.push({ + entry_item_id: Number(entryItem.id), + stock_id: stockId, + warehouse_item_code: (stockDetail && stockDetail.item_code) || '', + warehouse_item_name: (stockDetail && stockDetail.item_name) || '', + warehouse_item_spec: (stockDetail && stockDetail.sku_property) || '', + entry_count: Number(entryItem.count) || 0, + entry_received: Number(entryItem.received_quantity) || 0, + receiving_detail_id: Number(rd.id), + receiving_product_code: (rdStockDetail && rdStockDetail.item_code) || '', + receiving_product_name: rd.product_name || (rdStockDetail && rdStockDetail.item_name) || '', + receiving_actual_quantity: Number(rd.actual_quantity) || 0, + receiving_allocated: allocated, + receiving_available: available, + match_status: 'matched', + }); + } + } else { + // 入库商品在收货单中不存在 + comparison.push({ + entry_item_id: Number(entryItem.id), + stock_id: stockId, + warehouse_item_code: (stockDetail && stockDetail.item_code) || '', + warehouse_item_name: (stockDetail && stockDetail.item_name) || '', + warehouse_item_spec: (stockDetail && stockDetail.sku_property) || '', + entry_count: Number(entryItem.count) || 0, + entry_received: Number(entryItem.received_quantity) || 0, + receiving_detail_id: null, + receiving_product_code: null, + receiving_product_name: null, + receiving_actual_quantity: null, + receiving_allocated: null, + receiving_available: null, + match_status: 'entry_only', + }); + } + } + + // 9. 收货单中多余的商品(未被任何入库单明细匹配的) + const receivingOnly = []; + for (const rd of receivingDetails) { + if (!matchedReceivingDetailIds.has(Number(rd.id))) { + const rdStockDetail = (rd.system_product_id != null && stockDetailMap.get(Number(rd.system_product_id))) || null; + const allocated = allocatedMap.get(Number(rd.id)) || 0; + const available = Math.max(0, (Number(rd.actual_quantity) || 0) - allocated); + receivingOnly.push({ + receiving_detail_id: Number(rd.id), + receiving_product_code: (rdStockDetail && rdStockDetail.item_code) || '', + receiving_product_name: rd.product_name || (rdStockDetail && rdStockDetail.item_name) || '', + receiving_actual_quantity: Number(rd.actual_quantity) || 0, + receiving_allocated: allocated, + receiving_available: available, + }); + } + } + + // 10. 汇总 + const matchedItems = comparison.filter(c => c.match_status === 'matched').length; + const entryOnlyItems = comparison.filter(c => c.match_status === 'entry_only').length; + + return { + code: 200, + message: '查询成功', + data: { + entry_order_id: entryOrderId, + entry_order_code: entryOrder.entry_order_code, + receiving_id: receivingId, + receiving_number: receivingOrder.receiving_number, + comparison, + receiving_only: receivingOnly, + summary: { + total_entry_items: entryItems.length, + matched_items: matchedItems, + entry_only_items: entryOnlyItems, + receiving_only_items: receivingOnly.length, + }, + }, + }; + } + } module.exports = EntryService; diff --git a/methods/changes/2026-06-24-add-bind-receiving-details.json b/methods/changes/2026-06-24-add-bind-receiving-details.json new file mode 100644 index 0000000..37a9170 --- /dev/null +++ b/methods/changes/2026-06-24-add-bind-receiving-details.json @@ -0,0 +1,7 @@ +{ + "date": "2026-06-24", + "type": "addition", + "method": "storage.entry.bindReceivingDetails", + "summary": "新增批量绑定入库单明细与收货单明细接口,支持明细级数量分配与部分成功", + "related": ["storage.entry.get 追加 available_receiving_details 字段"] +} diff --git a/methods/changes/2026-06-24-deprecate-manual-match-entry-order.json b/methods/changes/2026-06-24-deprecate-manual-match-entry-order.json new file mode 100644 index 0000000..64c2dc7 --- /dev/null +++ b/methods/changes/2026-06-24-deprecate-manual-match-entry-order.json @@ -0,0 +1,7 @@ +{ + "date": "2026-06-24", + "type": "deprecation", + "method": "storage.receiving.manualMatchEntryOrder", + "summary": "废弃手动匹配入库单收货单接口,由 storage.entry.bindReceivingDetails 替代", + "migration": "使用 storage.entry.get(含 available_receiving_details 元数据)加载可匹配的收货单明细,然后调用 storage.entry.bindReceivingDetails 批量提交绑定" +} diff --git a/methods/changes/system.json b/methods/changes/system.json index 6aaf801..1ac129a 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -4099,5 +4099,105 @@ ], "type": "updated", "module": "storage.entry" + }, + { + "version": "2026.06.24-system-01", + "date": "2026-06-24", + "summary": "新增批量绑定入库单明细与收货单明细接口 storage.entry.bindReceivingDetails,支持明细级数量分配与部分成功", + "methods": [ + "storage.entry.bindReceivingDetails" + ], + "notes": [ + "新增 storage.entry.bindReceivingDetails:批量绑定入库单明细与收货单明细,支持明细级数量分配与部分成功", + "storage.entry.get 追加 available_receiving_details 字段加载可匹配的收货单明细" + ], + "type": "addition" + }, + { + "version": "2026.06.24-system-02", + "date": "2026-06-24", + "summary": "storage.entry.bindReceivingDetails:response.failed 字段从简单 reason 描述升级为结构化错误返回(含 error_code、message、detail);同步更新 400 错误说明", + "methods": [ + "storage.entry.bindReceivingDetails" + ], + "notes": [ + "response.failed 新增 items 定义,每项含 entry_item_id、receiving_detail_id、allocated_quantity、error_code、message、detail", + "error_code 枚举:ENTRY_ITEM_NOT_FOUND、STOCK_NOT_FOUND、RECEIVING_DETAIL_MISMATCH、RECEIVING_DETAIL_NOT_FOUND、INSUFFICIENT_AVAILABLE_QUANTITY、ENTRY_ORDER_STATUS_INVALID", + "400 错误说明更新:入库单状态不允许绑定时,所有 bindings 均返回 failed 且 error_code 为 ENTRY_ORDER_STATUS_INVALID" + ], + "type": "updated" + }, + { + "version": "2026.06.24-system-03", + "date": "2026-06-24", + "summary": "新增 storage.entry.quickInbound 快捷直入/虚拟入库接口", + "methods": [ + "storage.entry.quickInbound" + ], + "notes": [ + "新增 quickInbound 方法:入库单所有商品按明细数量一键直入虚拟库位(space_id=2),跳过收货/质检流程", + "支持状态:CREATED、PENDING 状态的入库单可执行", + "拒绝状态:CANCELLED(已作废)、COMPLETED(已完成)", + "事务内操作:更新入库明细收货量、累加库存总量、写入库存流水、写入虚拟库位库存、变更入库单状态为 COMPLETED", + "事务外异步回传奇门/API" + ], + "type": "addition" + }, + { + "version": "2026.06.24-system-04", + "date": "2026-06-24", + "summary": "收窄 storage.entry.quickInbound 状态约束:仅允许 CREATED 状态执行快捷直入", + "methods": [ + "storage.entry.quickInbound" + ], + "notes": [ + "收窄状态约束:仅允许 CREATED 状态执行快捷直入,PENDING 状态不再允许" + ], + "type": "updated" + }, + { + "version": "2026.06.24-system-05", + "date": "2026-06-24", + "summary": "修正 storage.entry.quickInbound errors[4] message 以匹配代码实现:改为动态状态描述", + "methods": [ + "storage.entry.quickInbound" + ], + "notes": [ + "errors[4].message 从「入库单状态不允许快捷直入(仅支持CREATED状态)」改为「入库单状态不允许快捷直入,当前状态:非CREATED(如PENDING等)」,反映代码中 `${entryOrder.order_status}` 动态模板特性" + ], + "type": "updated" + }, + { + "version": "2026.06.24-system-06", + "date": "2026-06-24", + "summary": "新增入库单与收货单商品对照预览接口", + "methods": [ + "storage.entry.receivingCompare" + ], + "notes": [ + "新增 storage.entry.receivingCompare 方法:给定入库单ID和收货单ID,返回入库商品与收货商品的逐行对照视图。", + "comparison 列表中每项含 match_status(matched/entry_only),以及入库侧和收货侧的商品与数量信息。", + "receiving_only 列表包含仅存在于收货单中的商品明细。", + "summary 提供 total_entry_items、matched_items、entry_only_items、receiving_only_items 汇总统计。", + "纯只读接口,不产生任何数据写入或状态变更。" + ], + "type": "addition" + }, + { + "version": "2026.06.24-system-07", + "date": "2026-06-24", + "summary": "setting.warehouse 模块新增 7 个发件人信息字段到 subject_config", + "methods": [ + "setting.warehouse.getSettings", + "setting.warehouse.saveSettings" + ], + "notes": [ + "在 getSettings 的 response 中新增 subject_config.sender_name(发件人姓名)、sender_tel(发件人电话)、province_name(省份)、city_name(城市)、district_name(区/县)、town_name(镇/街道)、address(详细地址)共 7 个字段,均为可选字符串,默认空。", + "在 saveSettings 的 params 中新增对应的 7 个入参字段,source 为 body.subject_config,均为可选字符串,默认空,并标注 maxLength。", + "字段 key 与 store_warehouse.policy_config 中发件人字段命名完全一致,统一仓库级发件人默认值配置。", + "getFieldMeta 接口无需修改文档——其返回的字段元信息由 WAREHOUSE_SETTING_FIELDS 定义在运行时自动生成,新增字段会随代码自动纳入返回列表。" + ], + "type": "updated", + "module": "setting.warehouse" } ] diff --git a/methods/system.json b/methods/system.json index 8127801..7581b77 100644 --- a/methods/system.json +++ b/methods/system.json @@ -2,7 +2,7 @@ "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", "version": "0.3.7", - "updatedAt": "2026-06-23", + "updatedAt": "2026-06-24", "headers": [ { "name": "platform", @@ -12690,6 +12690,48 @@ "type": "boolean", "required": true, "description": "是否要求已拣货(pick_status=fin),默认 true" + }, + { + "name": "subject_config.sender_name", + "type": "string", + "required": false, + "description": "仓库默认发件人姓名,默认空字符串" + }, + { + "name": "subject_config.sender_tel", + "type": "string", + "required": false, + "description": "仓库默认发件人联系电话,默认空字符串" + }, + { + "name": "subject_config.province_name", + "type": "string", + "required": false, + "description": "仓库默认发件省份,默认空字符串" + }, + { + "name": "subject_config.city_name", + "type": "string", + "required": false, + "description": "仓库默认发件城市,默认空字符串" + }, + { + "name": "subject_config.district_name", + "type": "string", + "required": false, + "description": "仓库默认发件区/县,默认空字符串" + }, + { + "name": "subject_config.town_name", + "type": "string", + "required": false, + "description": "仓库默认发件镇/街道,默认空字符串" + }, + { + "name": "subject_config.address", + "type": "string", + "required": false, + "description": "仓库默认发件详细地址,默认空字符串" } ], "errors": [ @@ -12884,6 +12926,55 @@ "required": false, "source": "body.subject_config.auto_outbound_rules", "description": "是否要求已拣货(pick_status=fin),默认 true" + }, + { + "name": "subject_config.sender_name", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "仓库默认发件人姓名,默认空字符串,最大长度 50" + }, + { + "name": "subject_config.sender_tel", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "仓库默认发件人联系电话,默认空字符串,最大长度 20" + }, + { + "name": "subject_config.province_name", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "仓库默认发件省份,默认空字符串,最大长度 50" + }, + { + "name": "subject_config.city_name", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "仓库默认发件城市,默认空字符串,最大长度 50" + }, + { + "name": "subject_config.district_name", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "仓库默认发件区/县,默认空字符串,最大长度 50" + }, + { + "name": "subject_config.town_name", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "仓库默认发件镇/街道,默认空字符串,最大长度 50" + }, + { + "name": "subject_config.address", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "仓库默认发件详细地址,默认空字符串,最大长度 200" } ], "response": [ @@ -18795,176 +18886,11 @@ "完成收货时会发送通知:通知 payload 或 metadata 将在每条明细中携带 box_remainder(箱内剩余数量/零散件数,number)与 box_weight(实测箱重,number,单位同系统重量,例如 kg)。新增字段为可选,旧客户端可忽略。" ], "errors": [] - }, - { - "method": "storage.receiving.manualMatchEntryOrder", - "description": "手动匹配入库单与收货单。传入收货单ID和入库单ID,复用异步匹配服务的明细对比和回传逻辑,同步返回匹配结果(含 matchType、comparisonResult、callbackSent、partialStorageMarked 等)。", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "receivingId", - "type": "number", - "required": true, - "source": "body", - "description": "收货单 ID" - }, - { - "name": "entryOrderId", - "type": "number", - "required": true, - "source": "body", - "description": "入库单 ID" - } - ], - "response": [ - { - "name": "matchType", - "type": "string", - "required": true, - "description": "匹配类型枚举:full_match(SKU+数量完全一致)/ receiving_covers_entry(收货单覆盖入库单,触发回传+标记部分入库)/ entry_exceeds_receiving(入库单超出收货单,不触发回传)/ no_match(SKU无交集,不触发回传)" - }, - { - "name": "comparisonResult", - "type": "object", - "required": true, - "description": "明细对比结果对象", - "children": [ - { - "name": "type", - "type": "string", - "required": true, - "description": "匹配类型(同 matchType)" - }, - { - "name": "matchedDetails", - "type": "array", - "required": true, - "description": "匹配明细列表,每项含 detailId、system_product_id、actual_quantity、stored_quantity、entryCount、overage" - } - ] - }, - { - "name": "callbackSent", - "type": "boolean", - "required": true, - "description": "是否已发送回传(full_match / receiving_covers_entry 时为 true)" - }, - { - "name": "callbackResult", - "type": "object|null", - "required": true, - "description": "回传结果对象(未发送时为 null);成功时含 success、sourceType(QM/API)、detail 字段" - }, - { - "name": "partialStorageMarked", - "type": "boolean", - "required": true, - "description": "是否已标记部分入库(仅 receiving_covers_entry 时为 true)" - }, - { - "name": "entryOrder", - "type": "object", - "required": true, - "description": "入库单摘要信息", - "children": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "入库单 ID" - }, - { - "name": "entry_order_code", - "type": "string", - "required": true, - "description": "入库单号" - }, - { - "name": "source_type", - "type": "string", - "required": true, - "description": "来源类型(QM/API)" - }, - { - "name": "warehouse_id", - "type": "number", - "required": true, - "description": "仓库 ID" - }, - { - "name": "status", - "type": "string", - "required": true, - "description": "入库单状态" - } - ] - }, - { - "name": "receivingOrder", - "type": "object", - "required": true, - "description": "收货单摘要信息", - "children": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "收货单 ID" - }, - { - "name": "receiving_number", - "type": "string", - "required": true, - "description": "收货单号" - }, - { - "name": "status", - "type": "string", - "required": true, - "description": "收货单状态" - }, - { - "name": "storage_status", - "type": "string", - "required": true, - "description": "入库状态(如 un_stored)" - } - ] - } - ], - "errors": [ - { - "code": 400, - "message": "入库单不存在:{entryOrderId}" - }, - { - "code": 400, - "message": "收货单不存在:{receivingId}" - }, - { - "code": 400, - "message": "入库单仓库({a})与收货单仓库({b})不一致" - } - ], - "notes": [ - "matchType 为 full_match 或 receiving_covers_entry 时触发回传(调用 _sendCallback),receiving_covers_entry 额外调用 _markReceivingPartialStorage 标记部分入库", - "matchType 为 entry_exceeds_receiving 或 no_match 时不触发回传,仅返回对比结果", - "不检查特定 API 权限,登录用户即可调用(_noNeedAuth=manualMatchEntryOrder)" - ] } ] }, { - "groupName": "入库单管理模块", + "groupName": "入库模块", "module": "storage.entry", "list": [ { @@ -19628,6 +19554,266 @@ "message": "入库记录不存在 / 关联入库单不存在或无权访问" } ] + }, + { + "method": "storage.entry.bindReceivingDetails", + "description": "批量绑定入库单明细与收货单明细。绑定只能使用关联收货单中匹配的 stock_id(通过 system_product_id 映射),且不能超出收货单明细的可用数量(actual_quantity - 已 committed 的 allocated_quantity)。支持部分成功:校验通过的写入绑定,不通过的在 failed 列表中返回原因。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "entry_order_id", + "type": "number", + "required": true, + "source": "body", + "description": "入库单ID" + }, + { + "name": "bindings", + "type": "array", + "required": true, + "source": "body", + "description": "绑定列表,每项包含 entry_item_id、receiving_detail_id、allocated_quantity" + } + ], + "response": [ + { + "name": "success", + "type": "array", + "required": true, + "description": "成功绑定的列表,每项包含 entry_item_id、receiving_detail_id、allocated_quantity" + }, + { + "name": "failed", + "type": "array", + "required": true, + "description": "绑定失败的列表,每项包含 entry_item_id、receiving_detail_id、allocated_quantity、error_code、message、detail", + "items": { + "type": "object", + "properties": { + "entry_item_id": { + "type": "number", + "description": "入库单明细ID" + }, + "receiving_detail_id": { + "type": "number", + "description": "收货单明细ID" + }, + "allocated_quantity": { + "type": "number", + "description": "请求分配的数量" + }, + "error_code": { + "type": "string", + "description": "错误码,可能值:ENTRY_ITEM_NOT_FOUND(入库明细不存在)、STOCK_NOT_FOUND(商品不存在)、RECEIVING_DETAIL_MISMATCH(收货明细与入库商品不匹配)、RECEIVING_DETAIL_NOT_FOUND(收货明细不存在)、INSUFFICIENT_AVAILABLE_QUANTITY(超出可用数量)、ENTRY_ORDER_STATUS_INVALID(入库单状态不允许绑定)" + }, + "message": { + "type": "string", + "description": "中文错误描述,可直接展示给用户" + }, + "detail": { + "type": "object", + "description": "错误上下文数据,根据 error_code 不同包含不同字段。如 INSUFFICIENT_AVAILABLE_QUANTITY 时包含 available_quantity 和 requested_quantity" + } + } + } + }, + { + "name": "success_count", + "type": "number", + "required": true, + "description": "成功数量" + }, + { + "name": "failed_count", + "type": "number", + "required": true, + "description": "失败数量" + } + ], + "errors": [ + { + "code": 400, + "message": "参数校验失败:entry_order_id 必填 / bindings 必填且为非空数组 / 入库单状态不允许绑定时,所有 bindings 均返回 failed 且 error_code 为 ENTRY_ORDER_STATUS_INVALID" + }, + { + "code": 404, + "message": "入库单不存在或无权访问" + } + ] + }, + { + "method": "storage.entry.quickInbound", + "description": "快捷直入(虚拟入库):将入库单所有商品按明细数量一键直入到虚拟库位(space_id=2),跳过收货/质检流程,入库单状态变为COMPLETED。仅支持 CREATED 状态的入库单;CANCELLED(已作废)、COMPLETED(已完成)、PENDING 等其他状态均拒绝操作。事务内操作:更新入库明细收货量、累加库存总量、写入库存流水、写入虚拟库位库存、变更入库单状态为 COMPLETED。事务外异步回传奇门/API。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "入库单ID" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "入库单ID" + }, + { + "name": "entry_order_code", + "type": "string", + "required": true, + "description": "入库单号" + }, + { + "name": "order_status", + "type": "string", + "required": true, + "description": "入库单状态(COMPLETED)" + }, + { + "name": "sync_status", + "type": "string", + "required": true, + "description": "同步状态(SUCCESS)" + }, + { + "name": "items_count", + "type": "number", + "required": true, + "description": "入库明细条目数" + }, + { + "name": "total_quantity", + "type": "number", + "required": true, + "description": "入库总数量" + } + ], + "errors": [ + { + "code": 400, + "message": "id 必填" + }, + { + "code": 404, + "message": "入库单不存在或无权访问" + }, + { + "code": 400, + "message": "已作废入库单不允许快捷入库" + }, + { + "code": 400, + "message": "入库单已完成,请勿重复提交" + }, + { + "code": 400, + "message": "入库单状态不允许快捷直入,当前状态:非CREATED(如PENDING等)" + }, + { + "code": 400, + "message": "请先添加入库明细" + } + ] + }, + { + "method": "storage.entry.receivingCompare", + "description": "入库单与收货单商品对照预览:给定入库单ID和收货单ID,返回入库商品与收货商品的逐行对照视图,含匹配状态(matched/entry_only)和汇总统计。纯只读接口。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "entry_order_id", + "type": "number", + "required": true, + "source": "body", + "description": "入库单ID" + }, + { + "name": "receiving_id", + "type": "number", + "required": true, + "source": "body", + "description": "收货单ID" + } + ], + "response": [ + { + "name": "entry_order_id", + "type": "number", + "required": true, + "description": "入库单ID" + }, + { + "name": "entry_order_code", + "type": "string", + "required": true, + "description": "入库单号" + }, + { + "name": "receiving_id", + "type": "number", + "required": true, + "description": "收货单ID" + }, + { + "name": "receiving_number", + "type": "string", + "required": true, + "description": "收货单号" + }, + { + "name": "comparison", + "type": "array", + "required": true, + "description": "逐行对照列表" + }, + { + "name": "receiving_only", + "type": "array", + "required": true, + "description": "仅收货单有的商品列表" + }, + { + "name": "summary", + "type": "object", + "required": true, + "description": "汇总统计" + } + ], + "errors": [ + { + "code": 400, + "message": "entry_order_id 必填" + }, + { + "code": 400, + "message": "receiving_id 必填" + }, + { + "code": 404, + "message": "入库单不存在或无权访问" + }, + { + "code": 404, + "message": "收货单不存在" + } + ] } ] },