diff --git a/app/lib/printer_data_builder.js b/app/lib/printer_data_builder.js index 7e00720..f7dde6f 100644 --- a/app/lib/printer_data_builder.js +++ b/app/lib/printer_data_builder.js @@ -465,6 +465,7 @@ function resolveItemQuantity(item) { * @param {number} [options.platforms_index] 平台内序号。 * @param {string} [options.expressInterfaceName] 快递渠道显示名。 * @param {number} [options.fallbackTotalQty] 兜底商品总数。 + * @param {string} [options.packageMaterialName] 推荐包材名称,非空时追加到波次号前。 * @return {Array} 自定义区文本行数组。 */ function buildWaybillCustomProductInfoLines(items, policyConfig = {}, options = {}) { @@ -544,9 +545,12 @@ function buildWaybillCustomProductInfoLines(items, policyConfig = {}, options = const hasWaveCustomPrefix = waveTotalOrders > 0 && waveIndex > 0 && Boolean(waveNo); - const waveHeaderText = hasWaveCustomPrefix - ? `${waveNo} [${finalTotalQty}-${waveIndex}]` + const packageMaterialName = String(safeOptions.packageMaterialName || '').trim(); + const packageMaterialLabel = packageMaterialName ? `【${packageMaterialName}】` : ''; + const waveBodyText = hasWaveCustomPrefix + ? `${waveNo} [${waveTotalOrders}-${waveIndex}]` : waveNo; + const waveHeaderText = packageMaterialLabel + waveBodyText; const headerParts = [ waveHeaderText, expressInterfaceName ].filter(Boolean); const headerLine = headerParts.join(' '); @@ -1243,6 +1247,7 @@ function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, orde wave_total_orders: Number(safeOrderDelivery.wave_total_orders || 0), wave_index: Number(safeOrderDelivery.wave_index || 0), platforms_index: Number(safeOrderDelivery.platforms_index || 0), + packageMaterialName: toTrimmedString(safeOrderDelivery.package_material_name), expressInterfaceName: toTrimmedString( safeOrderExpress.logistics_interface_name || safeOrderExpress.logistics_name @@ -1387,6 +1392,7 @@ function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDeli wave_total_orders: Number(safeOrderDelivery.wave_total_orders || 0), wave_index: Number(safeOrderDelivery.wave_index || 0), platforms_index: Number(safeOrderDelivery.platforms_index || 0), + packageMaterialName: toTrimmedString(safeOrderDelivery.package_material_name), expressInterfaceName: toTrimmedString( safeOrderExpress.logistics_interface_name || safeOrderExpress.logistics_name @@ -1573,6 +1579,7 @@ function applyDouyinExpressFieldMapping(platform, skeleton, orderExpress, orderD wave_total_orders: Number(safeOrderDelivery.wave_total_orders || 0), wave_index: Number(safeOrderDelivery.wave_index || 0), platforms_index: Number(safeOrderDelivery.platforms_index || 0), + packageMaterialName: toTrimmedString(safeOrderDelivery.package_material_name), expressInterfaceName: toTrimmedString( safeOrderExpress.logistics_interface_name || safeOrderExpress.logistics_name @@ -1705,6 +1712,7 @@ function applyCainiaoExpressFieldMapping( wave_total_orders: Number(safeOrderDelivery.wave_total_orders || 0), wave_index: Number(safeOrderDelivery.wave_index || 0), platforms_index: Number(safeOrderDelivery.platforms_index || 0), + packageMaterialName: toTrimmedString(safeOrderDelivery.package_material_name), expressInterfaceName: toTrimmedString( safeOrderExpress.logistics_interface_name || safeOrderExpress.logistics_name @@ -1905,6 +1913,7 @@ function applyXhsExpressFieldMapping( wave_total_orders: Number(safeOrderDelivery.wave_total_orders || 0), wave_index: Number(safeOrderDelivery.wave_index || 0), platforms_index: Number(safeOrderDelivery.platforms_index || 0), + packageMaterialName: toTrimmedString(safeOrderDelivery.package_material_name), expressInterfaceName: toTrimmedString( safeOrderExpress.logistics_interface_name || safeOrderExpress.logistics_name @@ -2008,6 +2017,7 @@ function applySphExpressFieldMapping( wave_total_orders: Number(safeOrderDelivery.wave_total_orders || 0), wave_index: Number(safeOrderDelivery.wave_index || 0), platforms_index: Number(safeOrderDelivery.platforms_index || 0), + packageMaterialName: toTrimmedString(safeOrderDelivery.package_material_name), expressInterfaceName: toTrimmedString( safeOrderExpress.logistics_interface_name || safeOrderExpress.logistics_name @@ -2173,6 +2183,7 @@ function applyJdExpressFieldMapping( wave_total_orders: Number(safeOrderDelivery.wave_total_orders || 0), wave_index: Number(safeOrderDelivery.wave_index || 0), platforms_index: Number(safeOrderDelivery.platforms_index || 0), + packageMaterialName: toTrimmedString(safeOrderDelivery.package_material_name), expressInterfaceName: toTrimmedString( safeOrderExpress.logistics_interface_name || safeOrderExpress.logistics_name @@ -2209,7 +2220,9 @@ function buildPlatformRequestSkeleton(input = {}) { const orderExpressForCompose = isPlainObject(input.order_express) ? { ...input.order_express } : {}; - const orderDeliveryForCompose = isPlainObject(input.order_delivery) ? input.order_delivery : {}; + const orderDeliveryForCompose = isPlainObject(input.order_delivery) + ? { ...input.order_delivery, package_material_name: String(options.packageMaterialName || '').trim() } + : {}; if (!orderExpressForCompose.items && orderDeliveryForCompose.items) { orderExpressForCompose.items = orderDeliveryForCompose.items; } diff --git a/app/model/api_app.js b/app/model/api_app.js index 7ecbacd..b81db1b 100644 --- a/app/model/api_app.js +++ b/app/model/api_app.js @@ -200,7 +200,7 @@ module.exports = app => { { name: 'uk_interface_warehouse', unique: true, - fields: [ 'qimen_app_key', 'qimen_customer_id' ], + fields: [ 'qimen_app_key', 'qimen_warehouse_code' ], }, { name: 'uk_interface_contract', diff --git a/app/model/package_material_item_relation.js b/app/model/package_material_item_relation.js new file mode 100644 index 0000000..8eb8e03 --- /dev/null +++ b/app/model/package_material_item_relation.js @@ -0,0 +1,130 @@ +'use strict'; + +/** + * 商品结构-包材绑定关系模型。 + * 记录订单商品结构指纹与包材的绑定历史,支持智能推荐。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { STRING, CHAR, INTEGER, BIGINT, DECIMAL, TINYINT, DATE } = app.Sequelize; + + const PackageMaterialItemRelation = app.model.define('package_material_item_relation', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + items_hash: { + type: CHAR(32), + allowNull: false, + comment: '订单商品结构MD5指纹', + }, + items_crc: { + type: INTEGER.UNSIGNED, + allowNull: false, + comment: '订单商品结构CRC32校验', + }, + package_material_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '包材ID', + }, + package_material_code: { + type: STRING(64), + allowNull: false, + comment: '包材编码(快照)', + }, + package_material_name: { + type: STRING(128), + allowNull: false, + comment: '包材名称(快照)', + }, + package_material_spec: { + type: STRING(128), + defaultValue: '', + comment: '规格(快照)', + }, + package_material_type: { + type: STRING(32), + defaultValue: '', + comment: '类型(快照)', + }, + length: { + type: DECIMAL(10, 2), + defaultValue: 0, + comment: '长(cm)快照', + }, + width: { + type: DECIMAL(10, 2), + defaultValue: 0, + comment: '宽(cm)快照', + }, + height: { + type: DECIMAL(10, 2), + defaultValue: 0, + comment: '高(cm)快照', + }, + weight: { + type: DECIMAL(10, 2), + defaultValue: 0, + comment: '重量(kg)快照', + }, + bind_count: { + type: INTEGER.UNSIGNED, + defaultValue: 1, + comment: '累计绑定次数', + }, + last_order_id: { + type: BIGINT(20).UNSIGNED, + comment: '最近订单ID', + }, + last_waybill_code: { + type: STRING(50), + defaultValue: '', + comment: '最近运单号', + }, + last_bind_user_id: { + type: BIGINT(20).UNSIGNED, + comment: '最近操作用户ID', + }, + last_bind_at: { + type: DATE, + comment: '最近绑定时间', + }, + is_active: { + type: TINYINT, + defaultValue: 1, + comment: '包材当前是否启用', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + delete_at: { + type: DATE, + comment: '软删除时间', + }, + }, { + tableName: 'wms_package_material_item_relation', + underscored: true, + paranoid: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + deletedAt: 'delete_at', + }); + + return PackageMaterialItemRelation; +}; diff --git a/app/model/platform_setting.js b/app/model/platform_setting.js index 268748e..1cb52dd 100644 --- a/app/model/platform_setting.js +++ b/app/model/platform_setting.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict'; /** * 平台设置模型定义。 @@ -34,8 +34,8 @@ module.exports = app => { }, warehouse_id: { type: BIGINT(20), - allowNull: false, - comment: '仓库ID', + allowNull: true, + comment: '仓库ID,NULL表示系统级设置', }, }, { tableName: 'wms_platfrom_setting', diff --git a/app/model/store.js b/app/model/store.js index 72865f9..105b028 100644 --- a/app/model/store.js +++ b/app/model/store.js @@ -42,7 +42,6 @@ module.exports = app => { max_notice_webhook_count: DEFAULT_MAX_NOTICE_WEBHOOK_COUNT, max_wave_quantity: DEFAULT_MAX_WAVE_QUANTITY, min_group_order_fetch_quantity: 13, - auto_grouping_enabled: false, default_express_code: 'STO', default_platform_code: 'TB', group_wave_prefix: 'B', @@ -228,14 +227,6 @@ module.exports = app => { normalized.min_group_order_fetch_quantity = minGroupOrderFetchQuantity; } - const autoGroupingEnabled = normalizeBooleanFlag( - parsed.auto_grouping_enabled, - 'subject_config.auto_grouping_enabled' - ); - normalized.auto_grouping_enabled = autoGroupingEnabled === undefined - ? DEFAULT_SUBJECT_CONFIG.auto_grouping_enabled - : autoGroupingEnabled; - normalized.default_express_code = normalizeSubjectConfigText( parsed.default_express_code, DEFAULT_SUBJECT_CONFIG.default_express_code diff --git a/app/service/qimenMethods/entryorder.js b/app/service/qimenMethods/entryorder.js index 48efe60..8be0b41 100644 --- a/app/service/qimenMethods/entryorder.js +++ b/app/service/qimenMethods/entryorder.js @@ -7,7 +7,12 @@ class entryorderServer extends MainService { const res = await this.ctx.service.systems.entryOrder.addOrder(data, this.getInfo(), 'QM'); if (res.success) { - return this.success(res.message, { createTime: this.app.formatDate(new Date()), entryOrderId: res.data.entryOrderId }); + return this.success(res.message, { + createTime: this.app.formatDate(new Date()), + entryOrderId: res.data.entryOrderId, + entryOrderCode: res.data.entryOrderCode, + status: res.data.status, + }); } return this.fail(res.message, { createTime: this.app.formatDate(new Date()) }); diff --git a/app/service/systemMethods/order/base.js b/app/service/systemMethods/order/base.js index c56b44b..ad6010c 100644 --- a/app/service/systemMethods/order/base.js +++ b/app/service/systemMethods/order/base.js @@ -707,7 +707,7 @@ class OrderBaseService extends MainService { where: { order_id: normalizedOrderId, }, - attributes: [ 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_id', 'weighing_weight', 'business_key', 'create_at' ], + attributes: [ 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_id', 'logistics_interface_name', 'weighing_weight', 'business_key', 'create_at', 'package_material_id', 'package_material_name_snapshot' ], order: [[ 'id', 'ASC' ]], raw: true, }); @@ -727,8 +727,11 @@ class OrderBaseService extends MainService { logistics_code: String(row && row.logistics_code || '').trim(), logistics_name: String(row && row.logistics_name || '').trim(), logistics_interface_id: row && row.logistics_interface_id == null ? null : Number(row.logistics_interface_id), + logistics_interface_name: String(row && row.logistics_interface_name || '').trim(), business_key: String(row && row.business_key || '').trim(), create_at: row && row.create_at != null ? new Date(row.create_at).getTime() : null, + package_material_id: row && row.package_material_id != null ? Number(row.package_material_id) : null, + package_material_name_snapshot: row && row.package_material_name_snapshot != null ? String(row.package_material_name_snapshot).trim() : null, })); } @@ -1184,10 +1187,18 @@ class OrderBaseService extends MainService { const orderItemsWithImages = this.attachImagesToOrderItems(orderItems, orderItemImagesByStockId); const expresses = await this.getOrderExpressesByOrderId(orderId, order); const logs = await this.getOrderOperationLogs(orderId); + + // 从运单列表中提取去重后的运单号数组 + const waybillCodes = Array.isArray(expresses) + ? [ ...new Set(expresses.map(expr => String(expr && expr.waybill_code || '').trim()).filter(Boolean)) ] + : []; + return { + order, detail: order, items: orderItemsWithImages, expresses, + waybill_codes: waybillCodes, logs, }; } diff --git a/app/service/systemMethods/order/index.js b/app/service/systemMethods/order/index.js index f10706c..e7a15d3 100644 --- a/app/service/systemMethods/order/index.js +++ b/app/service/systemMethods/order/index.js @@ -13,9 +13,9 @@ class OrderIndexService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail,updateExpressWeighingWeight,export,exportTaskProgress'; - const _noNeedLog = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail,updateExpressWeighingWeight,export,exportTaskProgress'; - const _noNeedAuth = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail,updateExpressWeighingWeight,export,exportTaskProgress'; + const _noNeedRight = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail,updateExpressWeighingWeight,export,exportTaskProgress,bindExpressPackageMaterialByWaybill'; + const _noNeedLog = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail,updateExpressWeighingWeight,export,exportTaskProgress,bindExpressPackageMaterialByWaybill'; + const _noNeedAuth = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail,updateExpressWeighingWeight,export,exportTaskProgress,bindExpressPackageMaterialByWaybill'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -512,6 +512,50 @@ class OrderIndexService extends OrderBaseService { } } + /** + * 根据运单号绑定包材。 + * + * method 层仅负责参数解构、systems 转发与统一返回结构。 + * 无需传入订单ID,仅凭运单号即可完成包材绑定。 + * + * 支持团购波次自动感知: + * - 非团购订单:仅绑定当前运单的包材。 + * - 团购波次(wave_type=1):自动将同一波次下、相同快递业务键(business_key)的 + * 所有运单批量绑定相同的包材,实现一键补齐。 + * + * @param {Object} data 请求体。 + * @param {string} data.waybill_code 运单号。 + * @param {string} data.package_material_code 包材编码。 + * @return {Promise} 统一成功/失败结构。 + * 单条绑定:data 含 {order_id, waybill_code, package_material_id, package_material_name_snapshot, package_material_code}; + * 团购批量绑定:data 含 {wave_id, wave_no, business_key, order_id, waybill_code, package_material_id, package_material_code, package_material_name_snapshot, bind_count, bound_waybills, store_name, sys_logistics_name}。 + */ + async bindExpressPackageMaterialByWaybill(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const { + waybill_code: waybillCode = '', + package_material_code: packageMaterialCode = '', + } = requestData; + + try { + const result = await this.service.systems.orderExpress.bindExpressPackageMaterialByWaybill({ + waybillCode, + packageMaterialCode, + }); + + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const errorCode = Number(error && error.code); + const statusCode = Number.isFinite(errorCode) && errorCode > 0 ? errorCode : 500; + return this.fail(error && error.message ? error.message : '绑定包材失败', { + data: null, + }, statusCode); + } + } + /** * 根据运单号拉取复核数据。 * diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 2b6d871..97ff7a7 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -2081,7 +2081,6 @@ class PendingOrderService extends OrderBaseService { sys_logistics_name: sysLogisticsName, logistics_code: logisticsCode, logistics_name: logisticsName, - post_status: 'fin', updated_at: new Date(), }, { where }); @@ -4979,7 +4978,7 @@ class PendingOrderService extends OrderBaseService { const where = this.buildOrderWhere([ orderId ], warehouseId); const order = await model.findOne({ where, - attributes: [ 'id', 'step', 'outbound_status', 'warehouse_id' ], + attributes: [ 'id', 'step', 'outbound_status', 'warehouse_id', 'store_id' ], raw: true, }); @@ -5059,6 +5058,32 @@ class PendingOrderService extends OrderBaseService { this.ctx.logger.warn('[PendingOrderService.manualWaybill] 写入操作日志失败,不影响业务', logErr); } + // 5. 自动同步回传(受合约策略 auto_sync_back 控制) + try { + const storeId = Number(order.store_id) || 0; + if (storeId > 0) { + const contractConfig = await this.service.systems.storeWarehouse.getContractConfig( + Number(order.warehouse_id) || warehouseId, + storeId + ); + if ( + contractConfig + && contractConfig.policy_config + && contractConfig.policy_config.auto_sync_back === 1 + ) { + this.syncOrderIds({ orderIds: [orderId] }).catch(err => { + this.ctx.logger.error( + `[auto_sync_back] manualWaybill 自动同步失败: ${err.message}` + ); + }); + } + } + } catch (err) { + this.ctx.logger.error( + `[auto_sync_back] manualWaybill 自动同步异常: ${err.message}` + ); + } + return this.success('ok', { id: expressRecord.id, order_id: orderId, diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index 570c8f8..320a635 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -2875,6 +2875,8 @@ class RecheckOrderService extends OrderBaseService { o.logistics_name, o.items_count, o.items_total, + o.items_weight, + o.weight_type, o.status, o.create_at, o.pick_time, @@ -2919,6 +2921,8 @@ class RecheckOrderService extends OrderBaseService { logistics_name: String(row?.logistics_name || '').trim(), items_count: Number(row?.items_count || 0), items_total: Number(row?.items_total || 0), + items_weight: row?.items_weight != null ? Number(row.items_weight) : null, + weight_type: this.formatWeightTypeLabel(row?.weight_type), status: Number(row?.status || 0), create_at: row?.create_at || null, pick_time: row?.pick_time || null, @@ -3486,7 +3490,7 @@ class RecheckOrderService extends OrderBaseService { // 构建 CASE WHEN 批量扣减 const summaryEntries = Array.from(storageQtyMap.entries()); const caseClauses = summaryEntries - .map(([sid, qty]) => `WHEN ${sid} THEN ${qty}`) + .map(([ sid, qty ]) => `WHEN ${sid} THEN ${qty}`) .join(' '); await ctx.model.query( @@ -3542,6 +3546,93 @@ class RecheckOrderService extends OrderBaseService { if (transactionRows.length > 0) { await ctx.model.StorageTransaction.bulkCreate(transactionRows, { transaction }); } + + // 释放 wms_stock_warehouse 锁定数量并写入 wms_stock_transaction 出库流水 + const stockQtyMap = new Map(); + for (const sRow of storageRows) { + const sid = Number(sRow.stock_id); + if (!sid || sid <= 0) continue; + const deduction = storageQtyMap.get(Number(sRow.id)) || 0; + if (deduction <= 0) continue; + stockQtyMap.set(sid, (stockQtyMap.get(sid) || 0) + deduction); + } + + if (stockQtyMap.size > 0) { + const stockIds = Array.from(stockQtyMap.keys()); + const stockWarehouseRows = await ctx.model.StockWarehouse.findAll({ + where: { + id: { [app.Sequelize.Op.in]: stockIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'quantity', 'locked_quantity' ], + lock: transaction.LOCK.UPDATE, + raw: true, + transaction, + }); + + const stockWarehouseMap = new Map(); + for (const swRow of stockWarehouseRows) { + stockWarehouseMap.set(Number(swRow.id), swRow); + } + + for (const [ stockId, qty ] of stockQtyMap) { + const swRow = stockWarehouseMap.get(stockId); + if (!swRow) { + ctx.logger.warn(`[recheckOrder] stock_warehouse 记录不存在: ${stockId}`); + continue; + } + const currentLocked = Number(swRow.locked_quantity) || 0; + if (currentLocked < qty) { + throw new Error( + `货主库存 ${stockId} 锁定数量不足:当前锁定 ${currentLocked},需释放 ${qty}` + ); + } + await ctx.model.StockWarehouse.update({ + locked_quantity: app.Sequelize.literal(`locked_quantity - ${qty}`), + update_at: app.Sequelize.literal('CURRENT_TIMESTAMP'), + }, { + where: { + id: stockId, + locked_quantity: { [app.Sequelize.Op.gte]: qty }, + }, + transaction, + }); + } + + const operator = this.getOrderLogOperator(); + const opId = String(operator.id || '').trim(); + const opName = String(operator.name || 'system').trim(); + const stockTransactionRows = []; + for (const [ stockId, qty ] of stockQtyMap) { + const swRow = stockWarehouseMap.get(stockId); + if (!swRow) continue; + const sRow = storageRows.find(r => Number(r.stock_id) === stockId); + const beforeQty = Number(swRow.quantity) || 0; + const beforeLocked = Number(swRow.locked_quantity) || 0; + stockTransactionRows.push({ + transaction_type: 'OUTBOUND', + warehouse_id: warehouseId, + store_id: sRow ? Number(sRow.store_id) || 0 : 0, + stock_id: stockId, + quantity: qty, + before_quantity: beforeQty, + after_quantity: Math.max(0, beforeQty - qty), + before_locked_quantity: beforeLocked, + after_locked_quantity: Math.max(0, beforeLocked - qty), + order_type: 'PICK_OUTBOUND', + order_no: String(orderId), + order_id: orderId, + operator_id: opId, + operator_name: opName, + remark: '拣货完成出库-货主库存释放(批量快捷复核)', + created_at: new Date(), + }); + } + + if (stockTransactionRows.length > 0) { + await ctx.model.StockTransaction.bulkCreate(stockTransactionRows, { transaction }); + } + } } } diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index 3ef4788..2f94475 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -2166,7 +2166,7 @@ class WaveService extends OrderBaseService { where, attributes: [ 'id', 'store_id', 'logistics_name', - 'items_hash', 'items', 'items_total', + 'items_hash', 'items', 'items_total', 'items_weight', 'post_status', 'pick_status', 'outbound_status', 'create_at', ], raw: true, @@ -2289,6 +2289,9 @@ class WaveService extends OrderBaseService { if (!last_order_time || o.create_at > last_order_time) last_order_time = o.create_at; } + // 同组订单 items_hash 相同,重量一致,取首单即可 + const firstOrder = g.orders[0] || {}; + list.push({ item_detail: itemSummary, item_detail_machine: itemDetailMachine, @@ -2297,6 +2300,7 @@ class WaveService extends OrderBaseService { group: g.orders.length, group_count: g.orders.length, items_total, + items_weight: firstOrder.items_weight != null ? Number(firstOrder.items_weight) : null, store_id: store_ids.length === 1 ? store_ids[0] : 0, store_ids, logistics_name: logisticsName, @@ -2398,7 +2402,7 @@ class WaveService extends OrderBaseService { where, attributes: [ 'id', 'store_id', 'logistics_name', - 'items_hash', 'items', 'items_total', + 'items_hash', 'items', 'items_total', 'items_weight', 'post_status', 'pick_status', 'outbound_status', 'create_at', ], raw: true, @@ -2521,6 +2525,9 @@ class WaveService extends OrderBaseService { if (!last_order_time || o.create_at > last_order_time) last_order_time = o.create_at; } + // 同组订单 items_hash 相同,重量一致,取首单即可 + const firstOrder = g.orders[0] || {}; + list.push({ item_detail: itemSummary, item_detail_machine: itemDetailMachine, @@ -2529,6 +2536,7 @@ class WaveService extends OrderBaseService { group: g.orders.length, group_count: g.orders.length, items_total, + items_weight: firstOrder.items_weight != null ? Number(firstOrder.items_weight) : null, store_id: store_ids.length === 1 ? store_ids[0] : 0, store_ids, logistics_name: logisticsName, @@ -3939,6 +3947,8 @@ class WaveService extends OrderBaseService { tracking_no: this.resolveWaveStrategyFallbackTrackingNo(normalizedOrderRow), items_count: normalizedOrderRow.items_count ?? null, items_total: normalizedOrderRow.items_total ?? null, + items_weight: normalizedOrderRow.items_weight != null ? Number(normalizedOrderRow.items_weight) : null, + weight_type: this.formatWeightTypeLabel(normalizedOrderRow.weight_type), sys_logistics_name: this.resolveWaveStrategyFallbackSysLogisticsName(normalizedOrderRow), store_name: this.resolveWaveStrategyFallbackStoreName(normalizedOrderRow), province: normalizedOrderRow.province ?? null, @@ -5782,6 +5792,62 @@ class WaveService extends OrderBaseService { }); } finally { await this.clearWaveStrategyQuickScanWarehouseLock(warehouseId, normalizedTaskId); + + // 方案 C:扫描完成后检查是否有新订单需要扫描 + try { + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const subjectConfig = await this.getWarehouseSubjectConfig(warehouseId); + const currentVersion = this.normalizeWaveStrategyQuickScanVersion( + this.getWarehouseSubjectConfigValue(subjectConfig, 'wave_strategy_version') + ); + + const pendingCount = await orderModel.count({ + where: { + warehouse_id: warehouseId, + step: { [Op.ne]: 0 }, + wave_id: 0, + intercept_status: 'none', + lock_status: 'none', + print_status: { [Op.ne]: 'fin' }, + [Op.or]: [ + { wave_strategy_version: { [Op.ne]: currentVersion } }, + { wave_strategy_version: { [Op.is]: null } }, + ], + }, + }); + + if (pendingCount > 0) { + this.ctx.logger.info( + '[wave.runWaveStrategyQuickScanTask] 检测到遗漏订单,触发新一轮扫描', + { + warehouseId, + previousTaskId: normalizedTaskId, + pendingCount, + } + ); + + setImmediate(() => { + this.submitWaveStrategyQuickScanForWarehouse(warehouseId).catch(error => { + this.ctx.logger.warn( + '[wave.runWaveStrategyQuickScanTask] 触发新一轮扫描失败', + { + warehouseId, + error: error && error.message ? error.message : `${error}`, + } + ); + }); + }); + } + } catch (checkError) { + this.ctx.logger.warn( + '[wave.runWaveStrategyQuickScanTask] 遗漏订单检查失败', + { + warehouseId, + taskId: normalizedTaskId, + error: checkError && checkError.message ? checkError.message : `${checkError}`, + } + ); + } } } diff --git a/app/service/systemMethods/print.js b/app/service/systemMethods/print.js index 3c4c95b..5d9a100 100644 --- a/app/service/systemMethods/print.js +++ b/app/service/systemMethods/print.js @@ -255,6 +255,43 @@ class PrintService extends MainService { return Array.from(orderIdSet); } + /** + * 从自定义打印数据中提取订单ID列表。 + * 支持 order_ids / orderIds 数组以及单个 order_id / orderId 字段。 + * @param {Object} customData 自定义打印数据对象。 + * @return {Array} 去重后的订单ID列表。 + */ + collectOrderIdsFromCustomizeData(customData = {}) { + const normalizedData = customData && typeof customData === 'object' ? customData : {}; + const orderIdSet = new Set(); + + // 尝试读取 order_ids 数组 + if (Array.isArray(normalizedData.order_ids)) { + for (const id of normalizedData.order_ids) { + const num = Number(id || 0); + if (Number.isInteger(num) && num > 0) { + orderIdSet.add(num); + } + } + } + // 尝试读取 orderIds 数组 + if (Array.isArray(normalizedData.orderIds)) { + for (const id of normalizedData.orderIds) { + const num = Number(id || 0); + if (Number.isInteger(num) && num > 0) { + orderIdSet.add(num); + } + } + } + // 尝试读取单个 order_id / orderId + const singleId = Number(normalizedData.order_id || normalizedData.orderId || 0); + if (Number.isInteger(singleId) && singleId > 0) { + orderIdSet.add(singleId); + } + + return Array.from(orderIdSet); + } + /** * 规范化快递打印平台编码,兼容常见别名。 * @param {Object} payload 入参。 @@ -810,6 +847,7 @@ class PrintService extends MainService { /** * 发送打印任务到打印电脑。 + * 本方法不做打印锁状态校验,不阻止重复打印请求。 * 仅在 type=customize 时要求 printer、template、page_width、page_height、template_content。 * @param {Object} _data 打印请求参数 * @param {string} [_data.printer] 打印机名称(type=customize 必填,type=express 忽略) @@ -821,7 +859,7 @@ class PrintService extends MainService { * @param {string} [_data.computerId] 打印电脑 ID(customize 必填,express 忽略) * @param {string} [_data.timestamp] 业务时间戳(express 忽略) * @param {number} [_data.count] 打印份数(express 忽略) - * @return {Promise} 统一返回结构 + * @return {Promise} 统一返回结构 */ async send(_data) { const { ctx } = this; @@ -869,16 +907,22 @@ class PrintService extends MainService { waveGroupsCount: Array.isArray(data && data.waveGroups) ? data.waveGroups.length : 0, }); } + // 从自定义打印数据中尝试提取关联的配送订单ID,用于后续同步 print_status + const customizeOrderIds = type !== 'express' ? this.collectOrderIdsFromCustomizeData(data) : []; let printRecord = null; if (type !== 'express') { // 生成打印编号并记录到数据库 try { + const printRecordData = { template, data }; + if (customizeOrderIds.length > 0) { + printRecordData.order_ids = customizeOrderIds; + } printRecord = await ctx.model.PrintRecord.create(this.buildPendingPrintRecordPayload({ warehouse_id: warehouseId, computer_id: computerId, printer, type, - data: { template, data }, + data: printRecordData, })); this.ctx.logger.info('[print.send] PrintRecord 创建成功', { warehouseId, @@ -1198,6 +1242,22 @@ class PrintService extends MainService { // 发送成功后更新打印记录状态 if (res.status === 'success') { await printRecord.update(this.buildSentPrintRecordUpdatePayload()); + // 同步更新关联配送订单的 print_status 为 'fin' + if (customizeOrderIds.length > 0) { + const updateResult = await this.updateOrderPrintStatusByCallback({ + warehouseId, + orderIds: customizeOrderIds, + result: 'success', + }); + if (!updateResult.success) { + this.ctx.logger.error('[print.send] 同步订单 print_status 失败', { + warehouseId, + type, + orderIdsCount: customizeOrderIds.length, + reason: updateResult.errorMessage, + }); + } + } this.ctx.logger.info('[print.send] 最终返回 success', { warehouseId, type, @@ -2110,6 +2170,7 @@ class PrintService extends MainService { : []; const generatedTaskCodes = []; const createdPrintRecordIds = []; + for (const waveGroup of waveGroups) { const platforms = Array.isArray(waveGroup && waveGroup.platforms) ? waveGroup.platforms : []; for (const platformGroup of platforms) { diff --git a/app/service/systemMethods/setting/packageMaterial.js b/app/service/systemMethods/setting/packageMaterial.js index 928e1d5..384c4ac 100644 --- a/app/service/systemMethods/setting/packageMaterial.js +++ b/app/service/systemMethods/setting/packageMaterial.js @@ -11,9 +11,9 @@ class packageMaterialService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'get,list,create,update,delete'; + const _noNeedRight = 'get,list,create,update,delete,search'; const _noNeedLog = '*'; - const _noNeedAuth = 'get,list,create,update,delete'; + const _noNeedAuth = 'get,list,create,update,delete,search'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -148,6 +148,18 @@ class packageMaterialService extends MainService { return await this.get(data); } + /** + * 快捷搜索包材,按关键词模糊匹配编码和名称。 + * + * @param {Object} [data={}] 请求参数 + * @param {string} [data.keyword] 搜索关键词 + * @return {Promise} data 为搜索结果数组,最多 50 条 + */ + async search(data = {}) { + const result = await this.service.systems.setting.packageMaterial.search(data); + return this.success('ok', result); + } + /** * 创建包材。 * diff --git a/app/service/systemMethods/stock/warehouse.js b/app/service/systemMethods/stock/warehouse.js index ea2e5ec..32d7f03 100644 --- a/app/service/systemMethods/stock/warehouse.js +++ b/app/service/systemMethods/stock/warehouse.js @@ -69,6 +69,10 @@ class WarehouseService extends MainService { bucket: 'prohibited', field: 'id', }, + has_bound_item: { + bucket: 'storeOutStock', + field: 'stock_id', + }, }, }); const result = await service.systems.stockStore.getWarehouseStock(where, pagination); @@ -99,6 +103,10 @@ class WarehouseService extends MainService { bucket: 'prohibited', field: 'id', }, + has_bound_item: { + bucket: 'storeOutStock', + field: 'stock_id', + }, }, }); @@ -374,7 +382,6 @@ class WarehouseService extends MainService { inbound_min_days, outbound_min_days, remaining_threshold_days, - barcode, } = data || {}; try { const result = await service.systems.stockStore.saveWarehouseStock({ @@ -417,7 +424,6 @@ class WarehouseService extends MainService { inbound_min_days, outbound_min_days, remaining_threshold_days, - barcode, }); return this.success('ok', { data: result, code: 200 }); } catch (error) { diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index 5c5e0f9..11de358 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -14,7 +14,6 @@ const DELIVERY_ORDER_STEP = Object.freeze({ const DEFAULT_STORE_SUBJECT_CONFIG = Object.freeze({ max_notice_webhook_count: 5, - auto_grouping_enabled: false, default_express_code: 'STO', default_platform_code: 'TB', }); @@ -320,7 +319,11 @@ class DeliveryOrderService extends Service { * @return {Promise} 平台快照。 */ async resolvePlatformSnapshot(sourcePlatformCode, storeSubjectConfig, info = {}, operationLogs = []) { - const platformList = await this.ctx.service.systems.platform.getPlatformList(); + const platformList = await this.ctx.service.systems.platform.getPlatformList( + false, + false, + info.warehouseId + ); const externalCode = String(sourcePlatformCode || '').trim(); const matchedPlatform = this.findPlatformOptionByCode(platformList, externalCode); @@ -1825,20 +1828,22 @@ class DeliveryOrderService extends Service { } /** - * 执行自动加团逻辑(仅团购)。 + * 执行自动加团逻辑(仅团购),从仓库级配置读取 auto_grouping_enabled。 * * @param {Object} context 异步处理上下文。 + * @param {number} context.storeId 货主ID。 + * @param {number} context.warehouseId 仓库ID。 * @return {Promise} 无返回值。 */ async runAutoGrouping(context) { const { ctx } = this; - const storeSubjectConfig = await this.getStoreSubjectConfig(context.storeId); - if (!storeSubjectConfig || !storeSubjectConfig.auto_grouping_enabled) { + const warehouseSubjectConfig = await this.getStoreSubjectConfig(context.warehouseId); + if (!warehouseSubjectConfig || !warehouseSubjectConfig.auto_grouping_enabled) { return; } - const maxWaveQuantity = Number(storeSubjectConfig.max_wave_quantity || 0) > 0 - ? Number(storeSubjectConfig.max_wave_quantity) + const maxWaveQuantity = Number(warehouseSubjectConfig.max_wave_quantity || 0) > 0 + ? Number(warehouseSubjectConfig.max_wave_quantity) : 500; const structure = this.buildAutoGroupingStructure(context); if (!structure) { diff --git a/app/service/systems/entry_order.js b/app/service/systems/entry_order.js index 88c4e50..c44d69a 100644 --- a/app/service/systems/entry_order.js +++ b/app/service/systems/entry_order.js @@ -111,8 +111,11 @@ class entryOrderService extends Service { const expectedTotalOrderLines = Number(totalOrderLines) || 0; if (lineCount === expectedTotalOrderLines) { - // 所有行数接收完成 - await this.received(orderId, warehouseId, storeId, transaction); + // 所有明细行已插入完毕,将状态从 CREATING 更新为 PENDING(等待收货) + await app.model.EntryOrder.update( + { order_status: 'PENDING', updated_at: new Date() }, + { where: { id: orderId, warehouse_id: warehouseId, store_id: storeId }, transaction } + ); } // 提交事务 @@ -121,13 +124,13 @@ class entryOrderService extends Service { if (lineCount === expectedTotalOrderLines) { return { success: true, - message: '入库单接收完毕', + message: '入库单创建完成,等待收货', data: { entryOrderId: orderId, entryOrderCode: orderCode, createTime: new Date(), warehouseCode, - status: 'COMPLETED', + status: 'PENDING', }, }; } @@ -135,13 +138,13 @@ class entryOrderService extends Service { // 部分接收或等待接收 return { success: true, - message: '入库单接收中', + message: '入库单创建中', data: { entryOrderId: orderId, entryOrderCode: orderCode, createTime: new Date(), warehouseCode, - status: 'PARTIAL_RECEIVED', + status: 'CREATING', }, }; diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index 4ca7be1..17ed35e 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -961,6 +961,39 @@ class ExpressPlatformService extends MainService { }; }); break; + case 'QT': + case 'OTHER': + successUpdates = (result.results || []).map(item => { + const [ warehouse_id, order_id, business_key ] = String(item.orderno || '').split('_'); + const waybillCode = String(item.logisticno || item.waybill_code || '').trim(); + return { + warehouse_id, + order_id, + business_key, + waybill_code: waybillCode, + orderExpressValues: { + waybill_code: waybillCode, + printinfo: item.printinfo, + signature: item.signature, + encryptprintinfo: item.encryptprintinfo, + encryptedtoken: item.encryptedtoken, + ...this.buildOrderExpressVerPatch([ item.ver ]), + create_at: new Date(), + logistics_code: listByWarehousePlatformCode.logistics_code || '', + logistics_interface_id: listByWarehousePlatformCode.id || null, + logistics_name: listByWarehousePlatformCode.logistics_name || '', + logistics_interface_name: listByWarehousePlatformCode.name || '', + platform_code: listByWarehousePlatformCode.platform_code || '', + status: 1, + retry_count: 0, + }, + orderDeliveryValues: { + post_status: 'fin', + order_flag: '', + }, + }; + }); + break; default: break; } diff --git a/app/service/systems/order_express.js b/app/service/systems/order_express.js index d0bea1e..f787f0b 100644 --- a/app/service/systems/order_express.js +++ b/app/service/systems/order_express.js @@ -141,7 +141,7 @@ class OrderExpressService extends Service { warehouse_id: warehouseId, delete_at: null, }, - attributes: [ 'id', 'order_id', 'waybill_code', 'warehouse_id', 'delete_at' ], + attributes: [ 'id', 'order_id', 'waybill_code', 'warehouse_id', 'delete_at', 'package_material_id' ], raw: true, }); @@ -953,6 +953,105 @@ class OrderExpressService extends Service { ); } + /** + * 写入或更新商品结构-包材绑定关系记录。 + * + * 若订单的 items_hash 不存在则跳过;关系表写入失败不影响主流程。 + * + * @param {Object} params 绑定上下文参数。 + * @param {number} params.orderId 订单ID。 + * @param {string} params.waybillCode 运单号。 + * @param {number} params.packageMaterialId 包材ID。 + * @param {string} params.packageMaterialCode 包材编码。 + * @param {string} params.packageMaterialName 包材名称。 + * @param {number} params.warehouseId 仓库ID。 + * @return {Promise} + */ + async _upsertPackageMaterialItemRelation({ orderId, waybillCode, packageMaterialId, packageMaterialCode, packageMaterialName, warehouseId }) { + const { ctx } = this; + try { + // 1. 查订单的 items_hash / items_crc + const orderDeliveryFactory = ctx.model && ctx.model.OrderDeliveryFactory; + if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') return; + + const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId); + const orderRow = await orderDeliveryModel.findOne({ + where: { id: orderId, warehouse_id: warehouseId }, + attributes: ['items_hash', 'items_crc'], + raw: true, + }); + if (!orderRow || !orderRow.items_hash) return; + + const { items_hash: itemsHash, items_crc: itemsCrc } = orderRow; + + // 2. 查关系表 + const relationModel = ctx.model && ctx.model.PackageMaterialItemRelation; + if (!relationModel) return; + + const existing = await relationModel.findOne({ + where: { + warehouse_id: warehouseId, + items_hash: itemsHash, + items_crc: itemsCrc, + package_material_id: packageMaterialId, + delete_at: null, + }, + raw: true, + }); + + // 3. 查包材完整快照 + const packageMaterialModel = ctx.model && ctx.model.PackageMaterial; + const materialRow = packageMaterialModel + ? await packageMaterialModel.findOne({ where: { id: packageMaterialId }, raw: true }) + : null; + + const snapshot = { + package_material_code: String(packageMaterialCode || '').trim(), + package_material_name: String(packageMaterialName || '').trim(), + package_material_spec: String(materialRow && materialRow.spec || '').trim(), + package_material_type: String(materialRow && materialRow.material_type || '').trim(), + length: Number(materialRow && materialRow.length || 0), + width: Number(materialRow && materialRow.width || 0), + height: Number(materialRow && materialRow.height || 0), + weight: Number(materialRow && materialRow.weight || 0), + }; + + const userId = ctx.user && ctx.user.id ? Number(ctx.user.id) : null; + const now = new Date(); + + if (existing) { + await relationModel.update({ + bind_count: (Number(existing.bind_count) || 0) + 1, + last_order_id: orderId, + last_waybill_code: waybillCode, + last_bind_user_id: userId, + last_bind_at: now, + is_active: 1, + ...snapshot, + }, { + where: { id: existing.id }, + }); + } else { + await relationModel.create({ + warehouse_id: warehouseId, + items_hash: itemsHash, + items_crc: itemsCrc, + package_material_id: packageMaterialId, + bind_count: 1, + last_order_id: orderId, + last_waybill_code: waybillCode, + last_bind_user_id: userId, + last_bind_at: now, + is_active: 1, + ...snapshot, + }); + } + } catch (err) { + // 关系表写入失败不影响主流程 + ctx && ctx.logger && ctx.logger.error(`[packageMaterialRelation] upsert failed: ${err.message}`); + } + } + /** * 绑定订单快递记录的包材信息。 * @param {Object} payload 入参对象。 @@ -989,10 +1088,24 @@ class OrderExpressService extends Service { }); const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); + const isSameMaterial = Number(orderExpressRow.package_material_id) === Number(materialRow.id); + if (!Number.isFinite(affectedRows) || affectedRows <= 0) { - throw this.createBusinessError('绑定包材失败', 500); + if (!isSameMaterial) { + throw this.createBusinessError('绑定包材失败', 500); + } + // 同一包材幂等:跳过 update 报错,继续走关系表 } + await this._upsertPackageMaterialItemRelation({ + orderId: normalizedOrderId, + waybillCode: normalizedWaybillCode, + packageMaterialId: Number(materialRow.id), + packageMaterialCode: String(materialRow.material_code || '').trim(), + packageMaterialName: String(materialRow.material_name || '').trim(), + warehouseId, + }); + return { order_id: Number(orderExpressRow.order_id), waybill_code: String(orderExpressRow.waybill_code || '').trim(), @@ -1001,6 +1114,433 @@ class OrderExpressService extends Service { package_material_code: String(materialRow.material_code || '').trim(), }; } + + /** + * 根据运单号绑定包材。 + * + * 仅凭运单号即可绑定包材,无需传入订单ID。 + * 先按运单号 + 仓库ID 查询有效运单记录,再按包材编码查询启用中的包材, + * 最后更新运单记录的包材字段。 + * + * 支持团购波次自动感知: + * - 非团购订单(wave_id=0 或 wave_type≠1):仅绑定当前运单的包材,行为与旧版一致。 + * - 团购波次(wave_type=1):自动将同一波次下、相同快递业务键(business_key)的 + * 所有运单批量绑定相同的包材,实现一键补齐。 + * + * @param {Object} [payload={}] 请求参数。 + * @param {string} payload.waybillCode 运单号。 + * @param {string} payload.packageMaterialCode 包材编码。 + * @return {Promise} 单条绑定返回 {order_id, waybill_code, package_material_id, package_material_name_snapshot, package_material_code}; + * 团购批量绑定返回 {wave_id, wave_no, business_key, order_id, waybill_code, package_material_id, package_material_code, package_material_name_snapshot, bind_count, bound_waybills, store_name, sys_logistics_name}。 + */ + async bindExpressPackageMaterialByWaybill(payload = {}) { + const requestData = payload && typeof payload === 'object' ? payload : {}; + const { + waybillCode, + packageMaterialCode, + } = requestData; + + const normalizedWaybillCode = this.normalizeWaybillCode(waybillCode); + const normalizedPackageMaterialCode = this.normalizePackageMaterialCode(packageMaterialCode); + const warehouseId = this.getCurrentWarehouseId(); + + // 按运单号 + 仓库ID 查询有效运单记录 + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel || typeof orderExpressModel.findOne !== 'function') { + throw this.createBusinessError('运单模型未初始化', 500); + } + + const orderExpressRow = await orderExpressModel.findOne({ + where: { + waybill_code: normalizedWaybillCode, + warehouse_id: warehouseId, + delete_at: null, + }, + attributes: ['id', 'order_id', 'waybill_code', 'warehouse_id', 'delete_at', 'package_material_id', 'business_key'], + raw: true, + }); + + if (!orderExpressRow) { + throw this.createBusinessError('运单号不存在', 404); + } + + // 查询启用中的包材 + const materialRow = await this.findActivePackageMaterialByCode(normalizedPackageMaterialCode, warehouseId); + + // --- 团购波次自动感知 --- + // 尝试查询运单所属订单是否属于团购波次 + const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + if (orderDeliveryFactory && typeof orderDeliveryFactory.getCurrentModel === 'function') { + try { + const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId); + const orderRow = await orderDeliveryModel.findOne({ + where: { id: Number(orderExpressRow.order_id), warehouse_id: warehouseId }, + attributes: ['id', 'wave_id', 'wave_no'], + raw: true, + }); + + if (orderRow) { + const waveId = Number(orderRow.wave_id || 0); + + if (waveId > 0) { + // 查询波次类型 + const waveBatchModel = this.ctx.model && this.ctx.model.WaveBatch; + if (waveBatchModel && typeof waveBatchModel.findOne === 'function') { + const waveRow = await waveBatchModel.findOne({ + where: { wave_id: waveId, warehouse_id: warehouseId }, + attributes: ['wave_id', 'wave_no', 'wave_type'], + raw: true, + }); + + // 团购波次(wave_type=1)→ 按业务键分类批量绑定 + if (waveRow && Number(waveRow.wave_type) === 1) { + return await this._bindWavePackageMaterialByBusinessKey({ + waveId, + waveNo: String(waveRow.wave_no || ''), + businessKey: orderExpressRow.business_key ?? null, + packageMaterialId: Number(materialRow.id), + packageMaterialCode: normalizedPackageMaterialCode, + packageMaterialName: String(materialRow.material_name || '').trim(), + warehouseId, + triggerOrderId: Number(orderExpressRow.order_id), + triggerWaybillCode: normalizedWaybillCode, + }); + } + } + } + } + } catch (_waveErr) { + // 波次查询失败时静默降级为单条绑定,保证向后兼容 + this.ctx && this.ctx.logger && this.ctx.logger.warn( + `[bindExpressPackageMaterialByWaybill] 团购波次检测失败,降级为单条绑定: ${_waveErr.message}` + ); + } + } + + // 非团购 → 单条绑定(保持现有逻辑) + return await this._bindSingleExpressPackageMaterial({ + orderExpressRow, + materialRow, + normalizedWaybillCode, + warehouseId, + }); + } + + /** + * 单条运单包材绑定(内部方法)。 + * + * 更新单条运单记录的包材字段,并写入包材-商品结构关系表。 + * + * @param {Object} params 绑定上下文参数。 + * @param {Object} params.orderExpressRow 运单记录。 + * @param {Object} params.materialRow 包材记录。 + * @param {string} params.normalizedWaybillCode 规范化后的运单号。 + * @param {number} params.warehouseId 仓库ID。 + * @return {Promise} 绑定后的结果快照,包含 order_id、waybill_code、package_material_id、package_material_name_snapshot、package_material_code。 + */ + async _bindSingleExpressPackageMaterial({ orderExpressRow, materialRow, normalizedWaybillCode, warehouseId }) { + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + + // 更新运单记录的包材字段 + const updateResult = await orderExpressModel.update({ + package_material_id: Number(materialRow.id), + package_material_name_snapshot: String(materialRow.material_name || '').trim(), + }, { + where: { + id: Number(orderExpressRow.id), + delete_at: null, + }, + }); + + const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); + const isSameMaterial = Number(orderExpressRow.package_material_id) === Number(materialRow.id); + + if (!Number.isFinite(affectedRows) || affectedRows <= 0) { + if (!isSameMaterial) { + throw this.createBusinessError('绑定包材失败', 500); + } + // 同一包材幂等:跳过 update 报错,继续走关系表 + } + + await this._upsertPackageMaterialItemRelation({ + orderId: Number(orderExpressRow.order_id), + waybillCode: normalizedWaybillCode, + packageMaterialId: Number(materialRow.id), + packageMaterialCode: String(materialRow.material_code || '').trim(), + packageMaterialName: String(materialRow.material_name || '').trim(), + warehouseId, + }); + + return { + order_id: Number(orderExpressRow.order_id), + waybill_code: String(orderExpressRow.waybill_code || '').trim(), + package_material_id: Number(materialRow.id), + package_material_name_snapshot: String(materialRow.material_name || '').trim(), + package_material_code: String(materialRow.material_code || '').trim(), + }; + } + + /** + * 团购波次按快递业务键分类批量绑定包材(内部方法)。 + * + * 查询波次下所有订单,再按触发运单的 business_key 筛选出同分类的运单, + * 批量更新包材字段并写入关系表。 + * + * @param {Object} params 批量绑定上下文参数。 + * @param {number} params.waveId 波次ID。 + * @param {string} params.waveNo 波次号。 + * @param {string|null} params.businessKey 快递业务键,用于分类过滤。 + * @param {number} params.packageMaterialId 包材ID。 + * @param {string} params.packageMaterialCode 包材编码。 + * @param {string} params.packageMaterialName 包材名称。 + * @param {number} params.warehouseId 仓库ID。 + * @param {number} params.triggerOrderId 触发绑定的订单ID。 + * @param {string} params.triggerWaybillCode 触发绑定的运单号。 + * @return {Promise} 团购批量绑定结果,含 wave_id、wave_no、business_key、order_id、waybill_code、package_material_id、package_material_code、package_material_name_snapshot、bind_count、bound_waybills、store_name、sys_logistics_name。 + */ + async _bindWavePackageMaterialByBusinessKey({ + waveId, + waveNo, + businessKey, + packageMaterialId, + packageMaterialCode, + packageMaterialName, + warehouseId, + triggerOrderId, + triggerWaybillCode, + }) { + // 1. 查询波次下所有订单 + const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { + throw this.createBusinessError('订单模型未初始化', 500); + } + + const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId); + const waveOrders = await orderDeliveryModel.findAll({ + where: { wave_id: waveId, warehouse_id: warehouseId }, + attributes: ['id'], + raw: true, + }); + + if (!waveOrders || waveOrders.length === 0) { + throw this.createBusinessError('波次下未找到订单', 404); + } + + const orderIds = waveOrders.map(o => Number(o.id)); + + // 2. 查询这些订单下相同 business_key 的所有有效运单 + const { Op } = this.app.Sequelize; + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function') { + throw this.createBusinessError('运单模型未初始化', 500); + } + + // business_key 为 null 时需特殊处理 Sequelize 查询 + const businessKeyWhere = (businessKey === null || businessKey === undefined) + ? { [Op.is]: null } + : businessKey; + + const expressRows = await orderExpressModel.findAll({ + where: { + order_id: { [Op.in]: orderIds }, + business_key: businessKeyWhere, + delete_at: null, + }, + attributes: ['id', 'order_id', 'waybill_code', 'business_key', 'package_material_id'], + raw: true, + }); + + if (!expressRows || expressRows.length === 0) { + // 波次下无同 business_key 运单 → 降级为仅绑定触发运单 + const orderExpressRow = await orderExpressModel.findOne({ + where: { waybill_code: triggerWaybillCode, warehouse_id: warehouseId, delete_at: null }, + attributes: ['id', 'order_id', 'waybill_code', 'package_material_id'], + raw: true, + }); + if (!orderExpressRow) { + throw this.createBusinessError('运单号不存在', 404); + } + + const materialRow = { + id: packageMaterialId, + material_code: packageMaterialCode, + material_name: packageMaterialName, + }; + + return await this._bindSingleExpressPackageMaterial({ + orderExpressRow, + materialRow, + normalizedWaybillCode: triggerWaybillCode, + warehouseId, + }); + } + + const expressIds = expressRows.map(r => Number(r.id)); + + // 3. 先验证匹配记录是否存在,避免 MySQL 因值未变返回 affected_rows=0 导致误判 + const matchingCount = await orderExpressModel.count({ + where: { id: { [Op.in]: expressIds }, delete_at: null }, + }); + if (matchingCount === 0) { + throw this.createBusinessError('批量绑定包材失败,无有效运单记录', 500); + } + + // 4. 批量更新包材字段 + await orderExpressModel.update( + { + package_material_id: packageMaterialId, + package_material_name_snapshot: packageMaterialName, + }, + { + where: { id: { [Op.in]: expressIds }, delete_at: null }, + } + ); + + // 5. 逐条写入包材-商品结构关系表(失败不影响主流程) + for (const row of expressRows) { + await this._upsertPackageMaterialItemRelation({ + orderId: Number(row.order_id), + waybillCode: String(row.waybill_code || '').trim(), + packageMaterialId, + packageMaterialCode, + packageMaterialName, + warehouseId, + }); + } + + // 6. 写入操作日志 + await this._writePackageMaterialActionLog({ + waveId, + waveNo, + businessKey, + packageMaterialCode, + packageMaterialName, + warehouseId, + bindCount: expressRows.length, + totalOrderCount: orderIds.length, + }); + + // 7. 获取货主名称与系统快递名称 + const storeName = await this._getStoreName(orderIds, warehouseId); + const sysLogisticsName = await this._getWaveSysLogisticsName(orderIds, warehouseId); + + // 8. 构建返回结构 + return { + wave_id: waveId, + wave_no: waveNo, + business_key: businessKey, + order_id: triggerOrderId, + waybill_code: triggerWaybillCode, + package_material_id: packageMaterialId, + package_material_code: packageMaterialCode, + package_material_name_snapshot: packageMaterialName, + bind_count: expressRows.length, + bound_waybills: expressRows.map(r => ({ + order_id: Number(r.order_id), + waybill_code: String(r.waybill_code || '').trim(), + })), + store_name: storeName, + sys_logistics_name: sysLogisticsName, + }; + } + + /** + * 写入包材绑定操作日志到 wms_wave_pick_action_log(内部方法)。 + * + * @param {Object} params 日志参数。 + * @param {number} params.waveId 波次ID。 + * @param {string} params.waveNo 波次号。 + * @param {string|null} params.businessKey 快递业务键。 + * @param {string} params.packageMaterialCode 包材编码。 + * @param {string} params.packageMaterialName 包材名称。 + * @param {number} params.warehouseId 仓库ID。 + * @param {number} params.bindCount 绑定运单数。 + * @param {number} params.totalOrderCount 波次下订单总数。 + * @return {Promise} 无返回值。 + */ + async _writePackageMaterialActionLog({ + waveId, + waveNo, + businessKey, + packageMaterialCode, + packageMaterialName, + warehouseId, + bindCount, + totalOrderCount, + }) { + const ctxUser = this.ctx && this.ctx.user ? this.ctx.user : {}; + const operatorId = Number(ctxUser.employees_id || ctxUser.id || 0); + const operatorName = String( + ctxUser.employees_name || ctxUser.name || 'system' + ).trim(); + + const requestId = `bind_pm_${warehouseId}_${waveId}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; + + await this.ctx.model.query( + `INSERT INTO wms_wave_pick_action_log ( + task_id, + warehouse_id, + wave_id, + order_id, + sku_id, + location_id, + box_no, + cart_id, + qty_delta, + action_type, + request_id, + operator_id, + device_id, + seq_no, + snapshot + ) VALUES ( + :taskId, + :warehouseId, + :waveId, + :orderId, + :skuId, + :locationId, + :boxNo, + :cartId, + :qtyDelta, + :actionType, + :requestId, + :operatorId, + :deviceId, + :seqNo, + :snapshot + )`, + { + replacements: { + taskId: 0, + warehouseId: warehouseId || 0, + waveId, + orderId: null, + skuId: null, + locationId: null, + boxNo: null, + cartId: null, + qtyDelta: 0, + actionType: 'bind_package_material', + requestId, + operatorId, + deviceId: null, + seqNo: 1, + snapshot: JSON.stringify({ + wave_id: waveId, + wave_no: waveNo || '', + business_key: businessKey, + package_material_code: packageMaterialCode, + package_material_name: packageMaterialName, + bind_count: bindCount, + total_order_count: totalOrderCount, + operator_name: operatorName, + }), + }, + type: this.ctx.model.QueryTypes.INSERT, + } + ); + } } module.exports = OrderExpressService; diff --git a/app/service/systems/order_print.js b/app/service/systems/order_print.js index f2bee5a..4665302 100644 --- a/app/service/systems/order_print.js +++ b/app/service/systems/order_print.js @@ -686,7 +686,7 @@ class OrderPrintSystemService extends OrderBaseService { const platformCode = this.resolvePrintPlatformCode(effectiveOrderRow, orderExpress); const templateSample = this.loadTemplateSampleByPlatform(platformCode, templateSampleCache); - orderPrintList.push(this.buildOrderPlatformPrintItem({ + orderPrintList.push(await this.buildOrderPlatformPrintItem({ orderRow: effectiveOrderRowWithWaveIndex, orderExpress, policyConfig, @@ -861,7 +861,7 @@ class OrderPrintSystemService extends OrderBaseService { const platformCode = this.resolvePrintPlatformCode(effectiveOrderRow, orderExpress); const templateSample = this.loadTemplateSampleByPlatform(platformCode, templateSampleCache); - orderPrintList.push(this.buildOrderPlatformPrintItem({ + orderPrintList.push(await this.buildOrderPlatformPrintItem({ orderRow: effectiveOrderRowWithWaveIndex, orderExpress, policyConfig, @@ -2652,9 +2652,9 @@ ${waveFilterSql} * @param {Object} payload.policyConfig 策略配置。 * @param {string} payload.platformCode 平台编码。 * @param {Object} payload.templateSample 模板样例。 - * @return {Object} 逐单打印中间态。 + * @return {Promise} 逐单打印中间态。 */ - buildOrderPlatformPrintItem(payload = {}) { + async buildOrderPlatformPrintItem(payload = {}) { const requestPayload = this.isPlainObject(payload) ? payload : {}; const orderRow = this.isPlainObject(requestPayload.orderRow) ? requestPayload.orderRow : {}; const orderExpress = this.isPlainObject(requestPayload.orderExpress) ? requestPayload.orderExpress : {}; @@ -2662,6 +2662,31 @@ ${waveFilterSql} const templateSample = this.isPlainObject(requestPayload.templateSample) ? requestPayload.templateSample : {}; const platformCode = String(requestPayload.platformCode || '').trim(); + // 查最匹配的包材名称(基于 items_hash) + let suggestedPackageMaterialName = ''; + const itemsHash = String(orderRow.items_hash || '').trim(); + const itemsCrc = Number(orderRow.items_crc || 0); + if (itemsHash) { + const relationModel = this.ctx.model && this.ctx.model.PackageMaterialItemRelation; + if (relationModel) { + const topMatch = await relationModel.findOne({ + where: { + warehouse_id: Number(orderRow.warehouse_id || 0), + items_hash: itemsHash, + items_crc: itemsCrc, + is_active: 1, + delete_at: null, + }, + order: [['bind_count', 'DESC']], + attributes: ['package_material_name'], + raw: true, + }); + if (topMatch && topMatch.package_material_name) { + suggestedPackageMaterialName = String(topMatch.package_material_name).trim(); + } + } + } + const orderId = Number(orderRow.id || 0); const waveId = Number(orderRow.wave_id || 0); const requestId = `wave_${waveId}_order_${orderId}`; @@ -2684,6 +2709,7 @@ ${waveFilterSql} requestId, taskId: requestId, documentId, + packageMaterialName: suggestedPackageMaterialName, }, }); const printData = this.extractSinglePlatformPrintData(printPayload); diff --git a/app/service/systems/order_storage_allocation.js b/app/service/systems/order_storage_allocation.js index 13b88d7..a8681a7 100644 --- a/app/service/systems/order_storage_allocation.js +++ b/app/service/systems/order_storage_allocation.js @@ -939,6 +939,7 @@ class OrderStorageAllocationService extends MainService { }); const shortageItems = []; + const storageRowErrors = []; let allocatedQuantityForOrder = 0; for (const orderItem of orderItems) { @@ -1094,6 +1095,23 @@ class OrderStorageAllocationService extends MainService { 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) { + storageRowErrors.push({ storage_id: storageRow.id, reason: '库位未设置' }); + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库位无效,跳过该库存行', { + orderId, + orderItemId: toNumber(orderItem.id, 0), + stockId, + storageId: storageRow.id, + spaceId: storageRow.space_id, + }); + // 释放刚才 lockQuantity 加的锁,防止 locked_quantity 泄漏 + await ctx.service.systems.storage.index.unlockQuantity( + storageRow.id, allocationQuantity, { transaction } + ); + continue; + } + pickingRows.push({ order_id: orderId, order_item_id: toNumber(orderItem.id, 0), @@ -1137,17 +1155,25 @@ class OrderStorageAllocationService extends MainService { } const shortageMessage = buildShortageMessage(shortageItems); + + const spaceErrorMessage = storageRowErrors.length > 0 && shortageMessage + ? `库位未设置(storage_id:${storageRowErrors.map(e => e.storage_id).join(',')})` + : ''; + const finalShortageMessage = [shortageMessage, spaceErrorMessage].filter(Boolean).join('|'); + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单缺货信息汇总', { orderId, shortageItems, + storageRowErrors, shortageMessage, + finalShortageMessage, }); - const orderUpdateValues = shortageMessage + const orderUpdateValues = finalShortageMessage ? { storage_status: STORAGE_STATUS_ERROR, step: ORDER_STEP_EXCEPTION, - order_flag: shortageMessage, + order_flag: finalShortageMessage, updated_at: now, } : { @@ -1179,8 +1205,8 @@ class OrderStorageAllocationService extends MainService { order_id: orderId, storage_status: orderUpdateValues.storage_status, allocated_quantity: allocatedQuantityForOrder, - shortage_message: shortageMessage || '', - status: shortageMessage ? 'error' : 'success', + shortage_message: finalShortageMessage || '', + status: finalShortageMessage ? 'error' : 'success', }); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 当前订单处理结束', { diff --git a/app/service/systems/pick.js b/app/service/systems/pick.js index 1c1256b..ef9c6a5 100644 --- a/app/service/systems/pick.js +++ b/app/service/systems/pick.js @@ -1931,6 +1931,91 @@ class PickSystemService extends Service { if (transactionRows.length > 0) { await ctx.model.StorageTransaction.bulkCreate(transactionRows, { transaction }); } + + // 释放 wms_stock_warehouse 锁定数量并写入 wms_stock_transaction 出库流水 + const stockQtyMap = new Map(); + for (const sRow of storageRows) { + const sid = Number(sRow.stock_id); + if (!sid || sid <= 0) continue; + const deduction = storageQtyMap.get(Number(sRow.id)) || 0; + if (deduction <= 0) continue; + stockQtyMap.set(sid, (stockQtyMap.get(sid) || 0) + deduction); + } + + if (stockQtyMap.size > 0) { + const stockIds = Array.from(stockQtyMap.keys()); + const stockWarehouseRows = await ctx.model.StockWarehouse.findAll({ + where: { + id: { [this.app.Sequelize.Op.in]: stockIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'quantity', 'locked_quantity' ], + lock: transaction.LOCK.UPDATE, + raw: true, + transaction, + }); + + const stockWarehouseMap = new Map(); + for (const swRow of stockWarehouseRows) { + stockWarehouseMap.set(Number(swRow.id), swRow); + } + + for (const [ stockId, qty ] of stockQtyMap) { + const swRow = stockWarehouseMap.get(stockId); + if (!swRow) { + ctx.logger.warn(`[pick] stock_warehouse 记录不存在: ${stockId}`); + continue; + } + const currentLocked = Number(swRow.locked_quantity) || 0; + if (currentLocked < qty) { + throw this.createBusinessError( + `货主库存 ${stockId} 锁定数量不足:当前锁定 ${currentLocked},需释放 ${qty}`, + 400 + ); + } + await ctx.model.StockWarehouse.update({ + locked_quantity: this.app.Sequelize.literal(`locked_quantity - ${qty}`), + update_at: this.app.Sequelize.literal('CURRENT_TIMESTAMP'), + }, { + where: { + id: stockId, + locked_quantity: { [this.app.Sequelize.Op.gte]: qty }, + }, + transaction, + }); + } + + const stockTransactionRows = []; + for (const [ stockId, qty ] of stockQtyMap) { + const swRow = stockWarehouseMap.get(stockId); + if (!swRow) continue; + const sRow = storageRows.find(r => Number(r.stock_id) === stockId); + const beforeQty = Number(swRow.quantity) || 0; + const beforeLocked = Number(swRow.locked_quantity) || 0; + stockTransactionRows.push({ + transaction_type: 'OUTBOUND', + warehouse_id: warehouseId, + store_id: sRow ? Number(sRow.store_id) || 0 : 0, + stock_id: stockId, + quantity: qty, + before_quantity: beforeQty, + after_quantity: Math.max(0, beforeQty - qty), + before_locked_quantity: beforeLocked, + after_locked_quantity: Math.max(0, beforeLocked - qty), + order_type: 'PICK_OUTBOUND', + order_no: targetOrderIds.join(',').slice(0, 255), + order_id: taskId, + operator_id: String(operatorId), + operator_name: operatorName, + remark: '拣货完成出库-货主库存释放', + created_at: new Date(), + }); + } + + if (stockTransactionRows.length > 0) { + await ctx.model.StockTransaction.bulkCreate(stockTransactionRows, { transaction }); + } + } } const progress = await this.getTaskPickProgress(taskId, warehouseId, transaction); diff --git a/app/service/systems/pick_compensation.js b/app/service/systems/pick_compensation.js index 61247e0..9a1f4ad 100644 --- a/app/service/systems/pick_compensation.js +++ b/app/service/systems/pick_compensation.js @@ -314,9 +314,9 @@ class PickCompensationService extends MainService { * 2. SELECT wms_storage FOR UPDATE * 3. 校验 locked_quantity >= 解锁数量 * 4. UPDATE wms_storage 只解锁 locked_quantity(不扣减 quantity) - * 5. UPDATE wms_picking SET status='cancelled_released' - * - * 注意:本方法不写入 wms_storage_transaction。 + * 5. 按 stock_id 汇总,UPDATE wms_stock_warehouse 释放 locked_quantity(仅解锁,不扣减 quantity) + * 6. INSERT wms_stock_transaction(OUTBOUND, quantity=0, 仅记录锁定释放) + * 7. UPDATE wms_picking SET status='cancelled_released' * * @param {number} warehouseId 仓库ID。 * @param {Array} cancelledPickingRows 已取消订单关联的拣货记录列表。 @@ -375,7 +375,7 @@ class PickCompensationService extends MainService { id: { [app.Sequelize.Op.in]: storageIds }, warehouse_id: warehouseId, }, - attributes: [ 'id', 'locked_quantity' ], + attributes: [ 'id', 'locked_quantity', 'quantity', 'store_id', 'stock_id' ], lock: transaction.LOCK.UPDATE, raw: true, transaction, @@ -417,6 +417,95 @@ class PickCompensationService extends MainService { transaction, }); + // 释放 wms_stock_warehouse 锁定数量(仅解锁,不扣减 quantity)并写入 wms_stock_transaction 流水 + const stockQtyMap = new Map(); + for (const sRow of storageRows) { + const sid = Number(sRow.stock_id); + if (!sid || sid <= 0) continue; + const deduction = storageQtyMap.get(Number(sRow.id)) || 0; + if (deduction <= 0) continue; + stockQtyMap.set(sid, (stockQtyMap.get(sid) || 0) + deduction); + } + + if (stockQtyMap.size > 0) { + const stockIds = Array.from(stockQtyMap.keys()); + const stockWarehouseRows = await ctx.model.StockWarehouse.findAll({ + where: { + id: { [app.Sequelize.Op.in]: stockIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'quantity', 'locked_quantity' ], + lock: transaction.LOCK.UPDATE, + raw: true, + transaction, + }); + + const stockWarehouseMap = new Map(); + for (const swRow of stockWarehouseRows) { + stockWarehouseMap.set(Number(swRow.id), swRow); + } + + for (const [ stockId, qty ] of stockQtyMap) { + const swRow = stockWarehouseMap.get(stockId); + if (!swRow) { + ctx.logger.warn(`[pick-compensation-cancel] stock_warehouse 记录不存在: ${stockId}`); + continue; + } + const currentLocked = Number(swRow.locked_quantity) || 0; + if (currentLocked < qty) { + throw this.createBusinessError( + `货主库存 ${stockId} 锁定数量不足:当前锁定 ${currentLocked},需释放 ${qty}`, + 400 + ); + } + await ctx.model.StockWarehouse.update({ + locked_quantity: app.Sequelize.literal(`locked_quantity - ${qty}`), + update_at: app.Sequelize.literal('CURRENT_TIMESTAMP'), + }, { + where: { + id: stockId, + locked_quantity: { [app.Sequelize.Op.gte]: qty }, + }, + transaction, + }); + } + + const stockTransactionRows = []; + for (const [ stockId, qty ] of stockQtyMap) { + const swRow = stockWarehouseMap.get(stockId); + if (!swRow) continue; + const sRow = storageRows.find(r => Number(r.stock_id) === stockId); + const currentQty = Number(swRow.quantity) || 0; + const currentLocked = Number(swRow.locked_quantity) || 0; + stockTransactionRows.push({ + transaction_type: 'OUTBOUND', + warehouse_id: warehouseId, + store_id: sRow ? Number(sRow.store_id) || 0 : 0, + stock_id: stockId, + quantity: 0, + before_quantity: currentQty, + after_quantity: currentQty, + before_locked_quantity: currentLocked, + after_locked_quantity: Math.max(0, currentLocked - qty), + order_type: 'PICK_CANCEL_RELEASE', + order_no: normalizedConfirmedRows + .filter(r => Number(r.stock_id) === stockId) + .map(r => String(r.order_id)) + .join(',') + .slice(0, 255), + order_id: 0, + operator_id: 'system', + operator_name: 'system', + remark: '拣货取消-货主库存锁定释放', + created_at: new Date(), + }); + } + + if (stockTransactionRows.length > 0) { + await ctx.model.StockTransaction.bulkCreate(stockTransactionRows, { transaction }); + } + } + // Step 5: UPDATE wms_picking SET status='cancelled_released' const compensatedPickingIds = normalizedConfirmedRows.map(r => Number(r.id)); await ctx.model.query(` @@ -454,7 +543,9 @@ class PickCompensationService extends MainService { * 5. 查询 dispatch 表获取订单的 delivery_order_code 和 source_order_codes, * 为每个拣货记录 INSERT 一条 wms_storage_transaction(OUTBOUND, PICK_COMPENSATION), * 同一 storage 的多条记录共享相同的 before/after 数量 - * 6. UPDATE wms_picking SET status='fin_compensated' + * 6. 按 stock_id 汇总,UPDATE wms_stock_warehouse 释放 locked_quantity + * 7. INSERT wms_stock_transaction(OUTBOUND)记录货主库存变更 + * 8. UPDATE wms_picking SET status='fin_compensated' * * @param {number} warehouseId 仓库ID。 * @param {Array} pickingRows 待补偿的拣货记录列表。 @@ -651,6 +742,91 @@ class PickCompensationService extends MainService { await ctx.model.StorageTransaction.bulkCreate(transactionRows, { transaction }); } + // 释放 wms_stock_warehouse 锁定数量并写入 wms_stock_transaction 出库流水 + const stockQtyMap = new Map(); + for (const sRow of storageRows) { + const sid = Number(sRow.stock_id); + if (!sid || sid <= 0) continue; + const deduction = storageQtyMap.get(Number(sRow.id)) || 0; + if (deduction <= 0) continue; + stockQtyMap.set(sid, (stockQtyMap.get(sid) || 0) + deduction); + } + + if (stockQtyMap.size > 0) { + const stockIds = Array.from(stockQtyMap.keys()); + const stockWarehouseRows = await ctx.model.StockWarehouse.findAll({ + where: { + id: { [app.Sequelize.Op.in]: stockIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'quantity', 'locked_quantity' ], + lock: transaction.LOCK.UPDATE, + raw: true, + transaction, + }); + + const stockWarehouseMap = new Map(); + for (const swRow of stockWarehouseRows) { + stockWarehouseMap.set(Number(swRow.id), swRow); + } + + for (const [ stockId, qty ] of stockQtyMap) { + const swRow = stockWarehouseMap.get(stockId); + if (!swRow) { + ctx.logger.warn(`[pick-compensation] stock_warehouse 记录不存在: ${stockId}`); + continue; + } + const currentLocked = Number(swRow.locked_quantity) || 0; + if (currentLocked < qty) { + throw this.createBusinessError( + `货主库存 ${stockId} 锁定数量不足:当前锁定 ${currentLocked},需释放 ${qty}`, + 400 + ); + } + await ctx.model.StockWarehouse.update({ + locked_quantity: app.Sequelize.literal(`locked_quantity - ${qty}`), + update_at: app.Sequelize.literal('CURRENT_TIMESTAMP'), + }, { + where: { + id: stockId, + locked_quantity: { [app.Sequelize.Op.gte]: qty }, + }, + transaction, + }); + } + + const stockTransactionRows = []; + for (const [ stockId, qty ] of stockQtyMap) { + const swRow = stockWarehouseMap.get(stockId); + if (!swRow) continue; + const sRow = storageRows.find(r => Number(r.stock_id) === stockId); + const beforeQty = Number(swRow.quantity) || 0; + const beforeLocked = Number(swRow.locked_quantity) || 0; + stockTransactionRows.push({ + transaction_type: 'OUTBOUND', + warehouse_id: warehouseId, + store_id: sRow ? Number(sRow.store_id) || 0 : 0, + stock_id: stockId, + quantity: qty, + before_quantity: beforeQty, + after_quantity: Math.max(0, beforeQty - qty), + before_locked_quantity: beforeLocked, + after_locked_quantity: Math.max(0, beforeLocked - qty), + order_type: COMPENSATION_ORDER_TYPE, + order_no: confirmedOrderIds.join(',').slice(0, 255), + order_id: confirmedOrderIds[0] || 0, + operator_id: 'system', + operator_name: 'system', + remark: '拣货完成补偿出库-货主库存释放', + created_at: new Date(), + }); + } + + if (stockTransactionRows.length > 0) { + await ctx.model.StockTransaction.bulkCreate(stockTransactionRows, { transaction }); + } + } + // Step 6: UPDATE wms_picking SET status='fin_compensated' const compensatedPickingIds = normalizedConfirmedRows.map(r => Number(r.id)); await ctx.model.query(` diff --git a/app/service/systems/platform.js b/app/service/systems/platform.js index 14db0e8..8733b5b 100644 --- a/app/service/systems/platform.js +++ b/app/service/systems/platform.js @@ -704,36 +704,45 @@ class PlatformService extends Service { } /** - * 从数据库加载当前仓库的平台设置列表。 + * 从数据库加载平台设置列表。 * - * @param {number|string} warehouseId 仓库ID。 + * 始终加载 warehouse_id IS NULL 的系统级设置;若 warehouseId 有效,则同时加载对应仓库的仓库级设置。 + * 结果按 code 升序、warehouse_id 降序排列,确保仓库级设置在合并时优先于系统级设置。 + * + * @param {number|string} warehouseId 仓库ID,无效时仅加载系统级设置。 + * @param {boolean} [full=false] 是否返回全量字段。 * @return {Promise} 平台设置列表。 */ - async loadPlatformSettingListFromDatabase(warehouseId = 0) { - const normalizedWarehouseId = Number(warehouseId || 0); - if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) { - return []; - } - + async loadPlatformSettingListFromDatabase(warehouseId = 0, full = false) { const platformSettingModel = this.ctx.model && this.ctx.model.PlatformSetting; if (!platformSettingModel || typeof platformSettingModel.findAll !== 'function') { return []; } + const normalizedWarehouseId = Number(warehouseId || 0); + const isFull = [ true, 1, '1', 'true' ].includes(full); + const attributes = isFull + ? this.getPlatformSettingFullAttributes() + : [ 'id', 'code', 'platform_code', 'warehouse_id' ]; + + // 构建 where 条件:系统级设置(warehouse_id IS NULL)始终加载 + const whereConditions = [{ warehouse_id: null }]; + + // 仓库级设置:仅在 warehouseId 有效时加载 + if (Number.isFinite(normalizedWarehouseId) && normalizedWarehouseId > 0) { + whereConditions.push({ warehouse_id: normalizedWarehouseId }); + } + const rows = await platformSettingModel.findAll({ - attributes: [ 'id', 'code', 'platform_code', 'warehouse_id' ], + attributes, where: { - warehouse_id: normalizedWarehouseId, + [this.ctx.app.Sequelize.Op.or]: whereConditions, }, - order: [[ 'code', 'ASC' ]], + order: [[ 'code', 'ASC' ], [ 'warehouse_id', 'DESC' ]], raw: true, }); - if (!Array.isArray(rows)) { - return []; - } - - return rows; + return Array.isArray(rows) ? rows : []; } /** @@ -875,7 +884,17 @@ class PlatformService extends Service { const mergedItem = full ? this.normalizeFullPlatformSettingRow(row, platformMap) : this.normalizePlatformSettingRow(row, platformMap); - if (!mergedItem || seenCodeMap.has(mergedItem.code)) { + if (!mergedItem) { + continue; + } + + if (seenCodeMap.has(mergedItem.code)) { + const idx = mergedList.findIndex(item => + String(item.code || item.value || '').trim() === mergedItem.code && !item.is_system_setting + ); + if (idx !== -1) { + mergedList[idx] = mergedItem; + } continue; } @@ -942,13 +961,16 @@ class PlatformService extends Service { * * @param {boolean} [systemOnly=false] 是否仅返回系统基础平台列表。 * @param {boolean} [full=false] 是否返回全量字段。 + * @param {number|null} [warehouseId=null] 仓库ID,传入时使用外部值,否则从 ctx.user.store_id 内部获取。 * @return {Promise} 平台列表。 */ - async getPlatformList(systemOnly = false, full = false) { - const warehouseId = this.getCurrentWarehouseId(); + async getPlatformList(systemOnly = false, full = false, warehouseId = null) { + const resolvedWarehouseId = warehouseId !== null && warehouseId !== undefined + ? Number(warehouseId) + : this.getCurrentWarehouseId(); const isSystemOnly = [ true, 1, '1', 'true' ].includes(systemOnly); const isFull = [ true, 1, '1', 'true' ].includes(full); - const cacheKey = this.getPlatformListCacheKey(warehouseId, isSystemOnly, isFull); + const cacheKey = this.getPlatformListCacheKey(resolvedWarehouseId, isSystemOnly, isFull); try { const cachedList = await this.app.getCacheAsync(cacheKey); @@ -975,7 +997,7 @@ class PlatformService extends Service { const [ platformList, platformSettingList ] = await Promise.all([ this.loadPlatformListFromDatabase(isFull), - this.loadPlatformSettingListFromDatabase(warehouseId, isFull), + this.loadPlatformSettingListFromDatabase(resolvedWarehouseId, isFull), ]); const mergedList = this.buildMergedPlatformList(platformList, platformSettingList, isFull); diff --git a/app/service/systems/setting/packageMaterial.js b/app/service/systems/setting/packageMaterial.js index 9a348ac..a7431a1 100644 --- a/app/service/systems/setting/packageMaterial.js +++ b/app/service/systems/setting/packageMaterial.js @@ -606,6 +606,46 @@ class SettingPackageMaterialService extends Service { .filter(Boolean), }; } + + /** + * 快捷搜索包材,按关键词模糊匹配编码和名称。 + * + * @param {Object} [data={}] 请求参数 + * @param {string} [data.keyword] 搜索关键词,匹配 material_code 和 material_name + * @return {Promise} 返回对象包含 data 属性,值为匹配结果数组,最多 50 条 + */ + async search(data = {}) { + const { app } = this; + const { Op } = app.Sequelize; + const warehouseId = this.getCurrentStoreId(); + const { keyword } = data || {}; + + const whereCondition = { + warehouse_id: warehouseId, + status: 1, + }; + + if (keyword && String(keyword).trim()) { + const kw = String(keyword).trim(); + const like = `%${kw}%`; + whereCondition[Op.or] = [ + { material_code: { [Op.like]: like } }, + { material_name: { [Op.like]: like } }, + ]; + } + + const rows = await app.model.PackageMaterial.findAll({ + where: whereCondition, + attributes: [ 'id', 'material_code', 'material_name', 'material_type', 'spec', 'status' ], + order: [[ 'id', 'DESC' ]], + limit: 50, + raw: true, + }); + + return { + data: rows, + }; + } } module.exports = SettingPackageMaterialService; diff --git a/app/service/systems/setting/warehouse.js b/app/service/systems/setting/warehouse.js index 6abb3c9..f24e70f 100644 --- a/app/service/systems/setting/warehouse.js +++ b/app/service/systems/setting/warehouse.js @@ -43,6 +43,14 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([ description: '控制团购波次最小抓取订单数量,默认 13', min: 1, }), + Object.freeze({ + key: 'auto_grouping_enabled', + name: '自动加团开关', + type: 'flag', + default: false, + required: false, + description: '是否启用订单创建后自动加入团购波次,默认 false(关闭)', + }), Object.freeze({ key: 'default_express_code', name: '默认快递编码', diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index b5862ce..b772bbd 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -1545,6 +1545,9 @@ class stockStoreService extends Service { const prohibitedQueryOptions = { where: {}, }; + const storeOutStockQueryOptions = { + where: {}, + }; // 添加默认条件 queryOptions.where[Op.and] = [{ warehouse_id: ctx.user.store_id, @@ -1558,9 +1561,12 @@ class stockStoreService extends Service { ]; barcodeQueryOptions.where[Op.and] = []; prohibitedQueryOptions.where[Op.and] = []; + storeOutStockQueryOptions.where[Op.and] = []; // 检测并处理条码查询条件 let hasBarcodeCondition = false; let hasProhibitedCondition = false; + let hasBoundItemCondition = false; + let boundItemValue = null; let barcodeCondition = null; let parsedBarcodeInput = null; @@ -1583,6 +1589,10 @@ class stockStoreService extends Service { bucket: 'prohibited', field: 'id', }, + has_bound_item: { + bucket: 'storeOutStock', + field: 'stock_id', + }, }, }); @@ -1622,12 +1632,18 @@ class stockStoreService extends Service { const barcodeDynamicConditions = bucketConditions.barcode || []; const prohibitedConditions = bucketConditions.prohibited || []; + const storeOutStockConditions = bucketConditions.storeOutStock || []; hasBarcodeCondition = Boolean(bucketFlags.barcode); hasProhibitedCondition = Boolean(bucketFlags.prohibited); + hasBoundItemCondition = Boolean(bucketFlags.storeOutStock); barcodeCondition = barcodeDynamicConditions[0] || null; parsedBarcodeInput = rawConditionsByField.barcode || null; + if (hasBoundItemCondition && rawConditionsByField.has_bound_item) { + boundItemValue = rawConditionsByField.has_bound_item.value; + } + if (dynamicConditions.length > 0) { queryOptions.where[Op.and].push({ [Op.and]: dynamicConditions, @@ -1644,6 +1660,27 @@ class stockStoreService extends Service { [Op.and]: prohibitedConditions, }); } + + if (storeOutStockConditions.length > 0) { + storeOutStockQueryOptions.where[Op.and].push({ + [Op.and]: storeOutStockConditions, + }); + } + + // has_bound_item 的「未绑定」场景:通过 NOT EXISTS 子查询在主表 where 上直接过滤 + const isBoundFalse = boundItemValue === false + || boundItemValue === 0 + || String(boundItemValue || '').trim().toLowerCase() === 'false' + || String(boundItemValue || '').trim() === '0' + || String(boundItemValue || '').trim().toLowerCase() === 'n'; + + if (hasBoundItemCondition && isBoundFalse) { + queryOptions.where[Op.and].push( + Sequelize.literal( + 'NOT EXISTS (SELECT 1 FROM wms_stock_store WHERE wms_stock_store.stock_id = stock_warehouse.id)' + ) + ); + } } // 如果有条码查询条件,先查询匹配的库存ID @@ -1752,39 +1789,53 @@ class stockStoreService extends Service { // 计算分页偏移量 const offset = (page - 1) * pageSize; + // 确定「外部商品绑定-已绑定」场景是否需要 INNER JOIN StockStore + const isBoundTrue = hasBoundItemCondition && ( + boundItemValue === true + || boundItemValue === 1 + || String(boundItemValue || '').trim().toLowerCase() === 'true' + || String(boundItemValue || '').trim() === '1' + || String(boundItemValue || '').trim().toLowerCase() === 'y' + ); + + // 构建 include 数组 + const includes = [ + ctx.model.StoreWarehouse.buildStoreStockInclude({ + warehouseId: ctx.user.store_id, + required: true, + attributes: [ 'store_remask' ], + }), + { + ...prohibitedQueryOptions, + model: ctx.model.ProhibitedType, + as: 'prohibited', + attributes: [ 'type_name' ], + required: hasProhibitedCondition, + }, + ]; + + if (isBoundTrue) { + includes.push({ + model: ctx.model.StockStore, + as: 'store_out_stock', + attributes: [], + required: true, + }); + } + // 执行查询:获取总数和数据 const [ total, data ] = await Promise.all([ // 获取总数 ctx.model.StockWarehouse.count({ where: queryOptions.where, - include: [ ctx.model.StoreWarehouse.buildStoreStockInclude({ - warehouseId: ctx.user.store_id, - required: true, - attributes: [ 'store_remask' ], - }), { - ...prohibitedQueryOptions, - model: ctx.model.ProhibitedType, - as: 'prohibited', - attributes: [ 'type_name' ], - required: hasProhibitedCondition, - }], + include: includes, distinct: true, }), // 获取分页数据 ctx.model.StockWarehouse.findAll({ ...queryOptions, - include: [ ctx.model.StoreWarehouse.buildStoreStockInclude({ - warehouseId: ctx.user.store_id, - required: true, - attributes: [ 'store_remask' ], - }), { - ...prohibitedQueryOptions, - model: ctx.model.ProhibitedType, - as: 'prohibited', - attributes: [ 'type_name' ], - required: hasProhibitedCondition, - }], + include: includes, limit: parseInt(pageSize), offset: parseInt(offset), distinct: true, // 确保去重 @@ -2682,7 +2733,6 @@ class stockStoreService extends Service { box_width, box_height, box_volume, box_remark, id, box_volume_m3, boxVolumeM3, shelf_life_days, inbound_min_days, outbound_min_days, remaining_threshold_days, - barcode, } = data; const normalizedVolume = volume ?? volume_cm3 ?? volumeCm3; const normalizedBoxVolume = box_volume ?? box_volume_m3 ?? boxVolumeM3; @@ -2804,38 +2854,6 @@ class stockStoreService extends Service { }, }); - // 6.5 处理条码:清理旧条码并写入新条码 - if (Object.prototype.hasOwnProperty.call(data, 'barcode')) { - const barcodesArr = Array.isArray(barcode) - ? barcode - : typeof barcode === 'string' - ? barcode.split(';') - : []; - const normalizedBarcodes = barcodesArr - .map(item => String(item || '').trim()) - .filter(item => item !== ''); - - // 删除该商品已有的所有条码 - await ctx.model.StockBarcode.destroy({ - where: { - stock_id: id, - warehouse_id: warehouseId, - }, - transaction, - }); - - // 写入新条码 - if (normalizedBarcodes.length > 0) { - const refData = normalizedBarcodes.map(item => ({ - stock_id: id, - barcode: item, - warehouse_id: warehouseId, - created_at: new Date(), - })); - await ctx.model.StockBarcode.bulkCreate(refData, { transaction }); - } - } - // 7. 提交事务 await transaction.commit(); @@ -2869,7 +2887,7 @@ class stockStoreService extends Service { prohibited_id, brand_name, managementFlags, enable_box_spec, box_unit, quantity_per_box, box_gross_weight, box_net_weight, box_length, - box_width, box_height, box_volume, box_remark, barcode, + box_width, box_height, box_volume, box_remark, } = data; // 1. 参数验证 @@ -2925,27 +2943,6 @@ class stockStoreService extends Service { try { // 2. 开启事务 const createdRecord = await ctx.model.StockWarehouse.create(insertData, transaction); - const barcodes_arr = Array.isArray(barcode) - ? barcode - : typeof barcode === 'string' - ? barcode.split(';') - : []; - const existingFileIds = []; - const toCreate = barcodes_arr - .map(item => String(item || '').trim()) - .filter(item => item && !existingFileIds.includes(item)); - // 批量操作 - const promises = []; - if (toCreate.length > 0) { - const refData = toCreate.map(item => ({ - stock_id: createdRecord.id, - barcode: item, - warehouse_id: warehouseId, - created_at: new Date(), - })); - promises.push(ctx.model.StockBarcode.bulkCreate(refData, { transaction })); - await Promise.all(promises); - } await service.systems.operationLog.createOperationLog({ businessType: 'stock', businessId: createdRecord.id, diff --git a/app/service/systems/store_warehouse.js b/app/service/systems/store_warehouse.js index 6723877..f47e75b 100644 --- a/app/service/systems/store_warehouse.js +++ b/app/service/systems/store_warehouse.js @@ -2158,11 +2158,11 @@ class SettingStoreWarehouseService extends Service { const { Op } = app.Sequelize; // 重复检测:按接口类型不同检查策略 let duplicateConfig = null; - if (isQimenWms && qimenAppKey && qimenCustomerId) { + if (isQimenWms && qimenAppKey && qimenWarehouseCode) { const duplicateWhere = { interface_type_id: Number(interfaceType.id || 0), qimen_app_key: qimenAppKey, - qimen_customer_id: qimenCustomerId, + qimen_warehouse_code: qimenWarehouseCode, }; if (config && config.id) { duplicateWhere.id = { [Op.ne]: config.id }; @@ -2173,7 +2173,7 @@ class SettingStoreWarehouseService extends Service { transaction, }); if (duplicateConfig) { - throw this.createError('该 AppKey 和客户ID 已绑定其他签约关系', 409); + throw this.createError('该 AppKey 和仓库编码 已绑定其他签约关系', 409); } } @@ -2276,7 +2276,7 @@ class SettingStoreWarehouseService extends Service { } catch (error) { await transaction.rollback(); if (error && error.name === 'SequelizeUniqueConstraintError') { - throw this.createError('接口配置已存在,请检查应用名或 AppKey / 客户ID 是否重复', 409); + throw this.createError('接口配置已存在,请检查应用名或 AppKey / 仓库编码 是否重复', 409); } if (error && error.name === 'SequelizeValidationError') { const message = error.errors && error.errors.length ? error.errors[0].message : '接口配置参数校验失败'; @@ -2506,15 +2506,16 @@ class SettingStoreWarehouseService extends Service { return null; } + const rawPolicyConfig = this.normalizePolicyConfig(row.policy_config, 'policy_config', { + allowEmpty: true, + sanitizeOnly: true, + }); const config = { id: row.id, store_id: row.store_id, warehouse_id: row.warehouse_id, auth_status: row.auth_status, - policy_config: this.normalizePolicyConfig(row.policy_config, 'policy_config', { - allowEmpty: true, - sanitizeOnly: true, - }), + policy_config: this.mergePolicyConfigWithDefaults(rawPolicyConfig), }; try { diff --git a/database/migrations/20260615143000-create-wms-package-material-item-relation.js b/database/migrations/20260615143000-create-wms-package-material-item-relation.js new file mode 100644 index 0000000..219e09a --- /dev/null +++ b/database/migrations/20260615143000-create-wms-package-material-item-relation.js @@ -0,0 +1,150 @@ +'use strict'; + +const TABLE_NAME = 'wms_package_material_item_relation'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + items_hash: { + type: Sequelize.CHAR(32), + allowNull: false, + comment: '订单商品结构MD5指纹', + }, + items_crc: { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: false, + comment: '订单商品结构CRC32校验', + }, + package_material_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '包材ID', + }, + package_material_code: { + type: Sequelize.STRING(64), + allowNull: false, + comment: '包材编码(快照)', + }, + package_material_name: { + type: Sequelize.STRING(128), + allowNull: false, + comment: '包材名称(快照)', + }, + package_material_spec: { + type: Sequelize.STRING(128), + allowNull: true, + defaultValue: '', + comment: '规格(快照)', + }, + package_material_type: { + type: Sequelize.STRING(32), + allowNull: true, + defaultValue: '', + comment: '类型(快照)', + }, + length: { + type: Sequelize.DECIMAL(10, 2), + allowNull: true, + defaultValue: 0, + comment: '长(cm)快照', + }, + width: { + type: Sequelize.DECIMAL(10, 2), + allowNull: true, + defaultValue: 0, + comment: '宽(cm)快照', + }, + height: { + type: Sequelize.DECIMAL(10, 2), + allowNull: true, + defaultValue: 0, + comment: '高(cm)快照', + }, + weight: { + type: Sequelize.DECIMAL(10, 2), + allowNull: true, + defaultValue: 0, + comment: '重量(kg)快照', + }, + bind_count: { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: false, + defaultValue: 1, + comment: '累计绑定次数', + }, + last_order_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '最近订单ID', + }, + last_waybill_code: { + type: Sequelize.STRING(50), + allowNull: true, + defaultValue: '', + comment: '最近运单号', + }, + last_bind_user_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '最近操作用户ID', + }, + last_bind_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '最近绑定时间', + }, + is_active: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 1, + comment: '包材当前是否启用', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + delete_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '软删除时间', + }, + }); + + await queryInterface.addIndex(TABLE_NAME, ['warehouse_id', 'items_hash', 'items_crc', 'package_material_id'], { + unique: true, + name: 'uk_item_material', + }); + + await queryInterface.addIndex(TABLE_NAME, ['warehouse_id', 'is_active', 'items_hash', 'bind_count'], { + name: 'idx_lookup', + }); + }, + + down: async (queryInterface) => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260615160000-alter-uk-interface-warehouse.js b/database/migrations/20260615160000-alter-uk-interface-warehouse.js new file mode 100644 index 0000000..45c35ac --- /dev/null +++ b/database/migrations/20260615160000-alter-uk-interface-warehouse.js @@ -0,0 +1,32 @@ +'use strict'; + +module.exports = { + /** + * 修改 wms_api_app 表的唯一键 uk_interface_warehouse: + * 从 (qimen_app_key, qimen_customer_id) 改为 (qimen_app_key, qimen_warehouse_code) + */ + up: async queryInterface => { + // 1. 删除旧唯一键 + await queryInterface.sequelize.query( + "ALTER TABLE wms_api_app DROP INDEX uk_interface_warehouse" + ); + // 2. 创建新唯一键 + await queryInterface.sequelize.query( + "ALTER TABLE wms_api_app ADD UNIQUE INDEX uk_interface_warehouse (qimen_app_key, qimen_warehouse_code)" + ); + }, + + /** + * 回滚:恢复为 (qimen_app_key, qimen_customer_id) + */ + down: async queryInterface => { + // 1. 删除新唯一键 + await queryInterface.sequelize.query( + "ALTER TABLE wms_api_app DROP INDEX uk_interface_warehouse" + ); + // 2. 恢复旧唯一键 + await queryInterface.sequelize.query( + "ALTER TABLE wms_api_app ADD UNIQUE INDEX uk_interface_warehouse (qimen_app_key, qimen_customer_id)" + ); + }, +}; diff --git a/database/migrations/20260617150000-make-warehouse-id-nullable-in-wms-platfrom-setting.js b/database/migrations/20260617150000-make-warehouse-id-nullable-in-wms-platfrom-setting.js new file mode 100644 index 0000000..5337fdf --- /dev/null +++ b/database/migrations/20260617150000-make-warehouse-id-nullable-in-wms-platfrom-setting.js @@ -0,0 +1,20 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.changeColumn('wms_platfrom_setting', 'warehouse_id', { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: true, + comment: '仓库ID,NULL表示系统级设置', + }); + }, + + async down(queryInterface, Sequelize) { + // 回滚前需确认没有 warehouse_id=NULL 的数据,否则回滚会失败 + await queryInterface.changeColumn('wms_platfrom_setting', 'warehouse_id', { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: false, + comment: '仓库ID', + }); + }, +}; diff --git a/docs/stock-stockWarehouse-query-rules.md b/docs/stock-stockWarehouse-query-rules.md index 28a081e..f0bad86 100644 --- a/docs/stock-stockWarehouse-query-rules.md +++ b/docs/stock-stockWarehouse-query-rules.md @@ -104,6 +104,17 @@ - 传入的是违禁品类型 `id`。 - 后端会映射到关联模型进行过滤。 +### has_bound_item + +- 筛选仓库商品是否已绑定外部商品(货主商品)。 +- `operator`:固定 `eq`(默认)。 +- `value`: + - 已绑定:`true` / `1` / `"Y"` / `"y"` + - 未绑定:`false` / `0` / `"N"` / `"n"` +- 示例: + - 查询已绑定外部商品的仓库商品:`has_bound_item={operator:eq,value:true}` + - 查询未绑定外部商品的仓库商品:`has_bound_item={operator:eq,value:false}` + ## 空值处理 以下值会被视为“空条件”并跳过: diff --git a/methods/changes/2026.06.16-system-01.json b/methods/changes/2026.06.16-system-01.json new file mode 100644 index 0000000..c6d1df0 --- /dev/null +++ b/methods/changes/2026.06.16-system-01.json @@ -0,0 +1,17 @@ +[ + { + "version": "2026.06.16-system-01", + "date": "2026-06-16", + "summary": "新增 order.recheckOrder.queryRecheckOrderSingleList:散单复核列表接口,响应新增 items_weight(总重量kg)和 weight_type(重量类型)字段", + "methods": [ + "order.recheckOrder.queryRecheckOrderSingleList" + ], + "notes": [ + "新增方法 order.recheckOrder.queryRecheckOrderSingleList,为 recheckOrderList 散单模式的独立入口。", + "响应 list 每项新增字段 items_weight (number|null):订单总重量(kg),来自 wms_order.items_weight,为 null 时返回 null。", + "响应 list 每项新增字段 weight_type (string):重量类型中文标签,来自 wms_order.weight_type 经 formatWeightTypeLabel 转换;取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。" + ], + "type": "added", + "module": "order.recheckOrder" + } +] diff --git a/methods/changes/2026.06.16-system-02.json b/methods/changes/2026.06.16-system-02.json new file mode 100644 index 0000000..545df34 --- /dev/null +++ b/methods/changes/2026.06.16-system-02.json @@ -0,0 +1,16 @@ +[ + { + "version": "2026.06.16-system-02", + "date": "2026-06-16", + "summary": "order.wave.groupOrderFetchList 响应新增 items_weight(总重量kg)字段", + "methods": [ + "order.wave.groupOrderFetchList" + ], + "notes": [ + "响应 list 每项新增字段 items_weight (number|null):订单总重量(kg),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", + "为 null 时返回 null。" + ], + "type": "updated", + "module": "order.wave" + } +] diff --git a/methods/changes/2026.06.16-system-03.json b/methods/changes/2026.06.16-system-03.json new file mode 100644 index 0000000..15005a5 --- /dev/null +++ b/methods/changes/2026.06.16-system-03.json @@ -0,0 +1,16 @@ +[ + { + "version": "2026.06.16-system-03", + "date": "2026-06-16", + "summary": "order.wave.waveStrategyFallbackOrderList 响应新增 items_weight(总重量kg)和 weight_type(重量类型)字段", + "methods": [ + "order.wave.waveStrategyFallbackOrderList" + ], + "notes": [ + "响应 list 每项新增字段 items_weight (number|null):订单总重量(kg),来自 wms_order.items_weight,为 null 时返回 null。", + "响应 list 每项新增字段 weight_type (string):重量类型中文标签,来自 wms_order.weight_type 经 formatWeightTypeLabel 转换;取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。" + ], + "type": "updated", + "module": "order.wave" + } +] diff --git a/methods/changes/2026.06.16-system-04.json b/methods/changes/2026.06.16-system-04.json new file mode 100644 index 0000000..4872712 --- /dev/null +++ b/methods/changes/2026.06.16-system-04.json @@ -0,0 +1,16 @@ +[ + { + "version": "2026.06.16-system-04", + "date": "2026-06-16", + "summary": "order.wave.singleOrderFetchList 响应新增 items_weight(总重量kg)字段", + "methods": [ + "order.wave.singleOrderFetchList" + ], + "notes": [ + "响应 list 每项新增字段 items_weight (number|null):订单总重量(kg),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", + "为 null 时返回 null。" + ], + "type": "updated", + "module": "order.wave" + } +] diff --git a/methods/changes/system.json b/methods/changes/system.json index 0284e7c..03d6488 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -3331,5 +3331,90 @@ "description": "包含拣货任务状态同步:全部拣完→任务状态=2(已完成),未全拣完→任务状态推进为1(拣货中)" }, "type": "added" + }, + { + "version": "2026.06.14-system-01", + "date": "2026-06-14", + "summary": "新增 order.bindExpressPackageMaterialByWaybill 方法:支持仅凭运单号绑定包材,无需传入订单ID", + "methods": [ + "order.bindExpressPackageMaterialByWaybill" + ], + "notes": [ + "新增 order.bindExpressPackageMaterialByWaybill 入参说明:waybill_code(运单号,必填)、package_material_code(包材编码,必填)。无需传入 order_id。", + "成功返回字段:order_id、waybill_code、package_material_id、package_material_name_snapshot、package_material_code。", + "错误码定义:400(参数错误)、404(运单号不存在 / 包材编码不存在)、500(绑定包材失败)。" + ], + "type": "added" + }, + { + "version": "2026.06.15-system-01", + "date": "2026-06-15", + "summary": "order.detail / order.deliveryOrder.detail 的 expresses 数组新增包材字段", + "methods": [ + "order.detail", + "order.deliveryOrder.detail" + ], + "notes": [ + "expresses 数组每个元素新增 package_material_id(包材ID,number|null)和 package_material_name_snapshot(包材名称快照,string|null)字段。" + ], + "type": "updated" + }, + { + "version": "2026.06.15-system-02", + "date": "2026-06-15", + "summary": "order.deliveryOrder.detail 的 expresses 数组新增包材字段", + "methods": [ + "order.deliveryOrder.detail" + ], + "notes": [ + "expresses 数组每个元素新增 package_material_id(包材ID,number|null)和 package_material_name_snapshot(包材名称快照,string|null)字段。" + ], + "type": "updated" + }, + { + "version": "2026.06.15-system-03", + "date": "2026-06-15", + "summary": "新增 setting.packageMaterial.search 方法:支持按关键字模糊搜索包材编码和名称", + "methods": [ + "setting.packageMaterial.search" + ], + "notes": [ + "新增 setting.packageMaterial.search 入参 keyword(可选),为空返回前 50 条启用中包材,有值时对 material_code 和 material_name 做模糊匹配。", + "返回包材数组,字段:id、material_code、material_name、material_type、spec、status。" + ], + "type": "added" + }, + { + "version": "2026.06.16-system-01", + "date": "2026-06-16", + "summary": "新增 order.recheckOrder.queryRecheckOrderSingleList:散单复核列表接口,响应新增 items_weight(总重量kg)和 weight_type(重量类型)字段", + "methods": [ + "order.recheckOrder.queryRecheckOrderSingleList" + ], + "notes": [ + "新增方法 order.recheckOrder.queryRecheckOrderSingleList,为 recheckOrderList 散单模式的独立入口。", + "响应 list 每项新增字段 items_weight (DECIMAL(10,2)):订单总重量(kg),来自 wms_order.items_weight,为 null 时返回 null。", + "响应 list 每项新增字段 weight_type (string):重量类型中文标签,来自 wms_order.weight_type 经 formatWeightTypeLabel 转换;取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。" + ], + "type": "added", + "module": "order.recheckOrder" + }, + { + "version": "2026.06.16-system-02", + "date": "2026-06-16", + "summary": "为 order.wave.groupOrderFetchList / waveStrategyFallbackOrderList / singleOrderFetchList 响应新增 items_weight(总重量kg)和 weight_type(重量类型)字段", + "methods": [ + "order.wave.groupOrderFetchList", + "order.wave.waveStrategyFallbackOrderList", + "order.wave.singleOrderFetchList" + ], + "notes": [ + "order.wave.groupOrderFetchList:响应 list 每项新增 items_weight (number|null):订单总重量(kg),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", + "order.wave.waveStrategyFallbackOrderList:响应 list 每项新增 items_weight (number|null):订单总重量(kg),来自 wms_order.items_weight;新增 weight_type (string):重量类型中文标签,取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。", + "order.wave.singleOrderFetchList:响应 list 每项新增 items_weight (number|null):订单总重量(kg),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", + "所有新增字段均为可选(required=false),为 null 时返回 null。" + ], + "type": "updated", + "module": "order.wave" } ] diff --git a/methods/system.json b/methods/system.json index 0680d68..d8518ef 100644 --- a/methods/system.json +++ b/methods/system.json @@ -2,7 +2,7 @@ "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", "version": "0.3.6", - "updatedAt": "2026-06-13", + "updatedAt": "2026-06-16", "headers": [ { "name": "platform", @@ -1733,7 +1733,7 @@ "name": "expresses", "type": "array", "required": true, - "description": "运单信息数组,每个元素包含以下字段:waybill_code(运单号,string)、weighing_weight(称重重量,number|null)、sys_logistics_code(系统物流公司编码,string)、sys_logistics_name(系统物流公司名称,string)、logistics_code(实际物流公司编码,string)、logistics_name(实际物流公司名称,string)、logistics_interface_id(物流接口ID,number|null)、business_key(业务标识,string)、created_at(创建时间戳毫秒,number|null)" + "description": "运单信息数组,每个元素包含以下字段:waybill_code(运单号,string)、weighing_weight(称重重量,number|null)、sys_logistics_code(系统物流公司编码,string)、sys_logistics_name(系统物流公司名称,string)、logistics_code(实际物流公司编码,string)、logistics_name(实际物流公司名称,string)、logistics_interface_id(物流接口ID,number|null)、business_key(业务标识,string)、created_at(创建时间戳毫秒,number|null)、package_material_id(包材ID,number|null)、package_material_name_snapshot(包材名称快照,string|null)" }, { "name": "waybill_codes", @@ -2288,6 +2288,86 @@ } ] }, + { + "method": "order.bindExpressPackageMaterialByWaybill", + "description": "按运单号绑定包材。仅需传入运单号与包材编码,系统自动根据运单号反查对应订单运单记录并绑定包材,无需传入订单ID。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "waybill_code", + "type": "string", + "required": true, + "source": "body", + "description": "运单号,必填。" + }, + { + "name": "package_material_code", + "type": "string", + "required": true, + "source": "body", + "description": "包材编码,必填。" + } + ], + "response": [ + { + "name": "order_id", + "type": "number", + "required": true, + "description": "运单号对应的订单ID(成功时返回于 data 对象中)。" + }, + { + "name": "waybill_code", + "type": "string", + "required": true, + "description": "运单号(成功时返回于 data 对象中)。" + }, + { + "name": "package_material_id", + "type": "number", + "required": true, + "description": "绑定后的包材ID(成功时返回于 data 对象中)。" + }, + { + "name": "package_material_name_snapshot", + "type": "string", + "required": true, + "description": "绑定时写入的包材名称快照(成功时返回于 data 对象中)。" + }, + { + "name": "package_material_code", + "type": "string", + "required": true, + "description": "绑定成功的包材编码(成功时返回于 data 对象中)。" + } + ], + "errors": [ + { + "code": 400, + "message": "参数错误" + }, + { + "code": 404, + "message": "运单号不存在" + }, + { + "code": 404, + "message": "包材编码不存在" + }, + { + "code": 500, + "message": "绑定包材失败" + } + ] + }, { "method": "order.export", "description": "提交订单导出任务(异步)。入参支持 table_type/tableType 与 module/module_name;where 与 sort 语义与 order.list 一致。提交后立即返回 task_id,后台异步执行,导出进度/下载请通过 order.exportTaskProgress 查询。", @@ -5981,6 +6061,51 @@ "message": "订单ID列表不能为空" } ] + }, + { + "method": "order.recheckOrder.queryRecheckOrderSingleList", + "description": "散单模式复核列表查询,按订单维度返回待复核订单(排除 pick_status='none' 和 recheck_status='fin'),支持分页与关键词/波次号/复核状态筛选。与 recheckOrderList 不同:本方法仅处理散单模式,不包含团购分支。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件。支持 keyword(运单号/订单号模糊搜索)、wave_no(精确匹配)、recheck_status、pick_status" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,支持 page / pageSize(默认 page=1, pageSize=20)" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "散单复核订单列表,每项含 order_id、delivery_order_code、order_type、wave_id、wave_no、pick_status、recheck_status、shop_nick、logistics_name、items_count、items_total、items_weight、weight_type、status、create_at、pick_time、recheck_time" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息,含 page、pageSize、total、totalPages、hasPrevious、hasNext" + } + ], + "errors": [] } ] }, @@ -7222,7 +7347,7 @@ "name": "list", "type": "array", "required": true, - "description": "分组列表,items 示例见实现:包含 item_detail_machine/item_snapshot/group_count 等字段" + "description": "分组列表,每项包含 item_detail、item_detail_machine、item_detail_machine_snapshot、item_snapshot、group、group_count、items_total、items_weight(总重量kg,取组内首单 items_weight)、store_id、store_ids、logistics_name、distinguish_express、first_order_time、last_order_time、status_summary 等字段;若指定 return_order_ids=true 则额外包含 order_ids" }, { "name": "pagination", @@ -7234,11 +7359,11 @@ "errors": [ { "code": "400", - "description": "缺少仓库上下文或参数格式错误" + "message": "缺少仓库上下文或参数格式错误" }, { "code": "500", - "description": "查询失败" + "message": "查询失败" } ] }, @@ -7386,6 +7511,16 @@ "type": "number", "description": "总件数" }, + { + "name": "items_weight", + "type": "number", + "description": "订单总重量(kg),来自 wms_order.items_weight,为 null 时返回 null" + }, + { + "name": "weight_type", + "type": "string", + "description": "重量类型中文标签,取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)" + }, { "name": "sys_logistics_name", "type": "string", @@ -7423,11 +7558,11 @@ "errors": [ { "code": "400", - "description": "未识别到当前仓库上下文或 where 中包含非法/禁止字段(如 warehouse_id)或存在别名冲突" + "message": "未识别到当前仓库上下文或 where 中包含非法/禁止字段(如 warehouse_id)或存在别名冲突" }, { "code": "500", - "description": "查询失败或内部错误" + "message": "查询失败或内部错误" } ] }, @@ -7500,7 +7635,7 @@ "name": "list", "type": "array", "required": true, - "description": "散单候选分组列表,items 示例见实现:包含 item_detail_machine/item_snapshot/group_count 等字段;返回的 group_count 均小于 same_order_quantity(或仓库配置的 min_group_order_fetch_quantity)。" + "description": "散单候选分组列表,每项包含 item_detail、item_detail_machine、item_detail_machine_snapshot、item_snapshot、group、group_count、items_total、items_weight(总重量kg,取组内首单 items_weight)、store_id、store_ids、logistics_name、distinguish_express、first_order_time、last_order_time、status_summary 等字段;返回的 group_count 均小于 same_order_quantity(或仓库配置的 min_group_order_fetch_quantity);若指定 return_order_ids=true 则额外包含 order_ids" }, { "name": "pagination", @@ -7512,11 +7647,11 @@ "errors": [ { "code": "400", - "description": "缺少仓库上下文或参数格式错误" + "message": "缺少仓库上下文或参数格式错误" }, { "code": "500", - "description": "查询失败" + "message": "查询失败" } ] }, @@ -9873,41 +10008,46 @@ { "name": "order", "type": "object", + "required": true, "description": "订单头对象(raw 行数据)" }, { "name": "detail", "type": "object", + "required": true, "description": "等同于 order" }, { "name": "orderItems / items", "type": "array", + "required": true, "description": "商品明细数组" }, { "name": "expresses", "type": "array", - "description": "运单信息数组" + "required": true, + "description": "运单信息数组,每个元素包含以下字段:waybill_code(运单号,string)、weighing_weight(称重重量,number|null)、sys_logistics_code(系统物流公司编码,string)、sys_logistics_name(系统物流公司名称,string)、logistics_code(实际物流公司编码,string)、logistics_name(实际物流公司名称,string)、logistics_interface_id(物流接口ID,number|null)、business_key(业务标识,string)、created_at(创建时间戳毫秒,number|null)、package_material_id(包材ID,number|null)、package_material_name_snapshot(包材名称快照,string|null)" }, { "name": "waybill_codes", "type": "array", + "required": true, "description": "去重后的运单号字符串数组" } ], "errors": [ { "code": "400", - "description": "订单ID 为空或格式错误" + "message": "订单ID 为空或格式错误" }, { "code": "404", - "description": "订单不存在或不属于当前仓库" + "message": "订单不存在或不属于当前仓库" }, { "code": "500", - "description": "内部错误" + "message": "内部错误" } ] } @@ -14632,7 +14772,7 @@ "type": "object", "required": false, "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;支持 quickWhere、barcode、prohibited_type 等商品筛选字段。示例:where.barcode={operator:like,value:69}; where.prohibited_type={operator:eq,value:liquid}。" + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;支持 quickWhere、barcode、prohibited_type、has_bound_item 等商品筛选字段。示例:where.barcode={operator:like,value:69}; where.prohibited_type={operator:eq,value:liquid}; where.has_bound_item={operator:eq,value:true}(已绑定外部商品)/ where.has_bound_item={operator:eq,value:false}(未绑定外部商品)。" } ], "response": [], @@ -23209,6 +23349,43 @@ "params": [], "response": [], "errors": [] + }, + { + "method": "setting.packageMaterial.search", + "description": "包材关键字搜索,按 material_code / material_name 模糊匹配,最多返回 50 条(仅返回启用中的包材)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "搜索关键字,模糊匹配 material_code、material_name;为空时返回前 50 条启用中的包材" + } + ], + "response": [ + { + "name": "data[]", + "type": "array", + "required": true, + "description": "包材列表,每项包含 id(包材ID)、material_code(包材编码)、material_name(包材名称)、material_type(包材类型)、spec(规格)、status(状态)" + } + ], + "errors": [ + { + "code": 500, + "message": "服务器错误" + } + ] } ] }, diff --git a/scripts/integration_test_stock_warehouse.js b/scripts/integration_test_stock_warehouse.js new file mode 100644 index 0000000..c6843f9 --- /dev/null +++ b/scripts/integration_test_stock_warehouse.js @@ -0,0 +1,114 @@ +'use strict'; +// 开发环境集成测试:验证 wms_stock_warehouse + wms_stock_transaction 修改 +const mysql = require('mysql2/promise'); +const DB_CONFIG = { host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' }; +const BASE_URL = 'http://127.0.0.1:6060'; +const TEST_WAREHOUSE_ID = 100000; +const TEST_STORE_ID = 1000000; + +async function main() { + const conn = await mysql.createConnection(DB_CONFIG); + + try { + console.log('='.repeat(70)); + console.log('WMS 拣货/复核完成 - stock_warehouse + stock_transaction 集成验证'); + console.log(`测试时间: ${new Date().toISOString()}`); + console.log(`测试仓库: ${TEST_WAREHOUSE_ID}`); + console.log(`测试货主: ${TEST_STORE_ID}`); + console.log('='.repeat(70)); + + // === 步骤1: 检查订单分表 === + console.log('\n--- 步骤1: 检查订单分表 ---'); + const [tables] = await conn.query("SHOW TABLES LIKE 'wms_order_delivery_%'"); + console.log(` 订单分表数量: ${tables.length}`); + tables.forEach(t => console.log(` - ${Object.values(t)[0]}`)); + + // === 步骤2: 查看订单状态分布 === + console.log('\n--- 步骤2: 订单状态分布 (wms_order_delivery_100000) ---'); + const [statusDist] = await conn.query(` + SELECT pick_status, recheck_status, storage_status, status, COUNT(*) as cnt + FROM wms_order_delivery_100000 + GROUP BY pick_status, recheck_status, storage_status, status + ORDER BY cnt DESC + LIMIT 15 + `); + console.table(statusDist); + + // === 步骤3: 查找最近有库存变更的 stock_warehouse === + console.log('\n--- 步骤3: wms_stock_warehouse 状态 (warehouse=100000) ---'); + const [swRows] = await conn.query(` + SELECT id, item_code, item_name, quantity, locked_quantity, store_id + FROM wms_stock_warehouse + WHERE warehouse_id = 100000 AND quantity > 0 + ORDER BY id DESC + LIMIT 10 + `); + console.table(swRows); + + // === 步骤4: wms_stock_transaction 最近记录 === + console.log('\n--- 步骤4: wms_stock_transaction 最近记录 ---'); + const [recentTx] = await conn.query(` + SELECT id, transaction_type, order_type, stock_id, quantity, + before_quantity, after_quantity, + before_locked_quantity, after_locked_quantity, + remark, created_at + FROM wms_stock_transaction + ORDER BY id DESC + LIMIT 15 + `); + console.table(recentTx); + + // 检查是否有 PICK_OUTBOUND 类型的记录 + const pickOutboundTx = recentTx.filter(r => r.order_type === 'PICK_OUTBOUND'); + console.log(`\n PICK_OUTBOUND 类型 stock_transaction 记录数: ${pickOutboundTx.length}`); + if (pickOutboundTx.length > 0) { + console.log(' ✅ 已有拣货出库 stock_transaction 记录,说明 pick.js 修改生效'); + for (const tx of pickOutboundTx) { + console.log(` id=${tx.id} stock_id=${tx.stock_id} qty=${tx.quantity} locked: ${tx.before_locked_quantity}→${tx.after_locked_quantity}`); + } + } else { + console.log(' ⚠️ 尚无 PICK_OUTBOUND stock_transaction 记录,需触发拣货流程验证'); + } + + // === 步骤5: 统计 stock_transaction 的 before_locked/after_locked 非零记录 === + console.log('\n--- 步骤5: stock_transaction locked_quantity 变更统计 ---'); + const [lockedStats] = await conn.query(` + SELECT + COUNT(*) as total, + SUM(CASE WHEN before_locked_quantity > 0 OR after_locked_quantity > 0 THEN 1 ELSE 0 END) as with_locked, + SUM(CASE WHEN before_locked_quantity != after_locked_quantity THEN 1 ELSE 0 END) as locked_changed + FROM wms_stock_transaction + `); + console.table(lockedStats); + + // === 步骤6: 检查 wms_stock_transaction 中 remark 包含"货主库存释放"的记录 === + console.log('\n--- 步骤6: 货主库存释放 stock_transaction 记录 ---'); + const [releaseTx] = await conn.query(` + SELECT id, transaction_type, order_type, stock_id, quantity, + before_locked_quantity, after_locked_quantity, remark, created_at + FROM wms_stock_transaction + WHERE remark LIKE '%货主库存释放%' + ORDER BY id DESC + LIMIT 10 + `); + console.log(` 货主库存释放记录数: ${releaseTx.length}`); + if (releaseTx.length > 0) { + console.table(releaseTx); + console.log(' ✅ stock_warehouse locked_quantity 释放 + stock_transaction 写入已验证'); + } else { + console.log(' ⚠️ 尚无"货主库存释放"remark 记录'); + } + + console.log('\n' + '='.repeat(70)); + console.log('集成验证完成'); + console.log('='.repeat(70)); + + } finally { + await conn.end(); + } +} + +main().catch(err => { + console.error('测试失败:', err); + process.exit(1); +});