From d711ba9c21ca79363deb7b103d3bd62a3be49236 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 6 May 2026 17:53:54 +0800 Subject: [PATCH] =?UTF-8?q?0506=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Copilot --- app/lib/qimen_client.js | 1 - app/model/receiving_detail.js | 12 + app/model/store.js | 9 + app/model/store_warehouse.js | 16 + .../store_warehouse_print_quantity_log.js | 5 - app/model/wave_batch.js | 4 +- app/service/im.js | 3 +- app/service/pda.js | 2 +- app/service/system.js | 2 +- app/service/systemMethods/order/index.js | 6 +- app/service/systemMethods/order/wave.js | 341 +++++++++- .../systemMethods/setting/warehouse.js | 5 +- app/service/systems/delivery_order.js | 642 +++++++++++++++++- app/service/systems/setting/warehouse.js | 12 +- app/service/systems/storage/receiving.js | 59 +- .../migrations/20260504000000-baseline.js | 2 +- ...-add-box-fields-to-wms_receiving_detail.js | 53 ++ docs/storage-receiving-api.md | 109 +++ methods/changes/system.json | 75 ++ methods/system.json | 505 +++++++++++++- .../file-writer/qimen-logs/.consume-progress | 2 +- script/db-query-prod-config.js | 13 + .../system.setting.storeWarehouse.test.js | 6 + .../system.storage.receiving.test.js | 4 + .../controller/system.storeWarehouse.test.js | 12 + test/app/model/store.test.js | 75 ++ .../systemMethods/order/wave.fetch.test.js | 18 +- .../order/wave.singleFetchByIds.test.js | 250 +++++++ ...ery_order.asyncProcessOrderCreated.test.js | 232 +++++++ .../service/systems/setting/warehouse.test.js | 104 +++ .../storage.receiving.complete.notice.test.js | 112 +++ .../storage.receiving.detailChange.test.js | 28 +- .../storage.receiving.getDetail.test.js | 119 ++++ 33 files changed, 2733 insertions(+), 105 deletions(-) create mode 100644 database/migrations/20260506103000-add-box-fields-to-wms_receiving_detail.js create mode 100644 script/db-query-prod-config.js create mode 100644 test/app/model/store.test.js create mode 100644 test/app/service/systemMethods/order/wave.singleFetchByIds.test.js create mode 100644 test/app/service/systems/delivery_order.asyncProcessOrderCreated.test.js create mode 100644 test/app/service/systems/setting/warehouse.test.js create mode 100644 test/app/service/systems/storage.receiving.complete.notice.test.js create mode 100644 test/app/service/systems/storage.receiving.getDetail.test.js diff --git a/app/lib/qimen_client.js b/app/lib/qimen_client.js index e6582e8..b4af2f7 100644 --- a/app/lib/qimen_client.js +++ b/app/lib/qimen_client.js @@ -157,7 +157,6 @@ class QimenClient { async sendRequest(url, requestData, logData = {}, runtime = {}) { const helpers = this.resolveRuntime(runtime); const startTime = Date.now(); - const { ctx } = helpers; const requestLogData = Object.assign({ body: requestData, result: '', diff --git a/app/model/receiving_detail.js b/app/model/receiving_detail.js index a634b90..da18c8f 100644 --- a/app/model/receiving_detail.js +++ b/app/model/receiving_detail.js @@ -107,6 +107,18 @@ module.exports = app => { weight: { type: INTEGER, }, + box_remainder: { + type: INTEGER, + allowNull: false, + defaultValue: 0, + comment: '箱余数', + }, + box_weight: { + type: DECIMAL(10, 2), + allowNull: false, + defaultValue: '0.00', + comment: '箱重量(kg)', + }, }, { tableName: 'wms_receiving_detail', timestamps: true, diff --git a/app/model/store.js b/app/model/store.js index 0fbf2c3..d9e34f1 100644 --- a/app/model/store.js +++ b/app/model/store.js @@ -8,6 +8,7 @@ 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', @@ -100,6 +101,14 @@ 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/model/store_warehouse.js b/app/model/store_warehouse.js index 617dfd3..0ef7363 100644 --- a/app/model/store_warehouse.js +++ b/app/model/store_warehouse.js @@ -25,6 +25,22 @@ module.exports = app => { required: false, description: '收货上架时是否自动推荐库位', }), + Object.freeze({ + key: 'auto_allocate_express', + name: '是否自动分配快递', + type: 'flag', + default: 0, + required: false, + description: '控制该货主在当前仓库下是否自动分配快递', + }), + Object.freeze({ + key: 'auto_allocate_storage', + name: '是否自动分配储位', + type: 'flag', + default: 0, + required: false, + description: '控制该货主在当前仓库下是否自动分配储位', + }), Object.freeze({ key: 'allow_receiving_quick_putaway', name: '收货单快捷入库', diff --git a/app/model/store_warehouse_print_quantity_log.js b/app/model/store_warehouse_print_quantity_log.js index 518dbe9..07f613c 100644 --- a/app/model/store_warehouse_print_quantity_log.js +++ b/app/model/store_warehouse_print_quantity_log.js @@ -63,11 +63,6 @@ module.exports = app => { allowNull: false, comment: '本次变更数量,整数,可正可负', }, - balance_before: { - type: INTEGER(11), - allowNull: false, - comment: '变更前余额', - }, balance_after: { type: INTEGER(11), allowNull: false, diff --git a/app/model/wave_batch.js b/app/model/wave_batch.js index 5e8196d..38d4c5f 100644 --- a/app/model/wave_batch.js +++ b/app/model/wave_batch.js @@ -176,10 +176,10 @@ module.exports = app => { }, { name: 'idx_wave_item_machine_prefix', - fields: [ { name: 'item_detail_machine', length: 191 } ], + fields: [{ name: 'item_detail_machine', length: 191 }], }, ], }); return WaveBatch; -}; \ No newline at end of file +}; diff --git a/app/service/im.js b/app/service/im.js index 7d66c3f..dcdedc1 100644 --- a/app/service/im.js +++ b/app/service/im.js @@ -75,7 +75,8 @@ class ImService extends Service { } /** * 获取主体员工信息 - * @param data + * @param data {Object<>} 请求数据,包含 store_id + * @return {Promise<{code: number, message: string, data: Array}>} 响应数据,包含员工列表 */ async getStoreEmployees(data) { const { store_id } = data || {}; diff --git a/app/service/pda.js b/app/service/pda.js index 77cc5b2..234a802 100644 --- a/app/service/pda.js +++ b/app/service/pda.js @@ -65,7 +65,7 @@ class pdaService extends Service { * 保存接口日志到系统日志模型 * @param {Object} logData 日志数据 * @param {number} startTime 开始时间戳 - * @returns {Promise} 写入结果 + * @return {Promise} 写入结果 */ async saveLog(logData, startTime) { const { diff --git a/app/service/system.js b/app/service/system.js index 4e4d71d..67e5b69 100644 --- a/app/service/system.js +++ b/app/service/system.js @@ -160,7 +160,7 @@ class systemService extends Service { * 保存接口日志到系统日志模型 * @param {Object} logData 日志数据 * @param {number} startTime 开始时间戳 - * @returns {Promise} 写入结果 + * @return {Promise} 写入结果 */ async saveLog(logData, startTime) { const { diff --git a/app/service/systemMethods/order/index.js b/app/service/systemMethods/order/index.js index 944c065..3b5adbc 100644 --- a/app/service/systemMethods/order/index.js +++ b/app/service/systemMethods/order/index.js @@ -132,17 +132,17 @@ class OrderIndexService extends OrderBaseService { const rawOrderId = orderId ?? id ?? orderIdAlias; if (rawOrderId === undefined || rawOrderId === null || String(rawOrderId).trim() === '') { - return this.fail(`order_id 参数不能为空`, {}, 400); + return this.fail('order_id 参数不能为空', {}, 400); } const normalizedOrderId = Number(String(rawOrderId).trim()); if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) { - return this.fail(`order_id 参数不合法`, {}, 400); + return this.fail('order_id 参数不合法', {}, 400); } const warehouseId = this.getWarehouseId(); if (warehouseId === null || warehouseId === undefined || warehouseId === '') { - return this.fail(`缺少当前用户仓库上下文 store_id`, {}, 400); + return this.fail('缺少当前用户仓库上下文 store_id', {}, 400); } const logs = await service.systems.operationLog.queryAllOrderLogs({ diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index 56f80d5..9ef750c 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -9,6 +9,7 @@ const MAX_PAGE_SIZE = 200; const BATCH_LIST_MAX_PAGE_SIZE = 500; const DEFAULT_MAX_WAVE_QUANTITY = 500; const DEFAULT_MIN_GROUP_ORDER_FETCH_QUANTITY = 13; +const SINGLE_FETCH_BY_IDS_WAVE_PREFIX = 'S'; const WAVE_MANUAL_FETCH_FLAG = 'wave_manual_fetch'; const FETCH_TASK_CACHE_KEY_PREFIX = 'wave:fetch:task:'; const FETCH_TASK_CACHE_TTL_SECONDS = 60 * 60 * 2; @@ -33,9 +34,9 @@ class WaveService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'groupOrderFetchList,singleOrderFetchList,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders'; - const _noNeedLog = 'groupOrderFetchList,singleOrderFetchList,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders'; - const _noNeedAuth = 'groupOrderFetchList,singleOrderFetchList,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders'; + const _noNeedRight = 'groupOrderFetchList,singleOrderFetchList,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds'; + const _noNeedLog = 'groupOrderFetchList,singleOrderFetchList,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds'; + const _noNeedAuth = 'groupOrderFetchList,singleOrderFetchList,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -2881,6 +2882,340 @@ class WaveService extends OrderBaseService { return this.success('ok', payload); } + /** + * 过滤 singleFetchByIds 中属于团购候选结构的订单。 + * + * 规则:同结构(items_hash/items)待处理订单数达到最小团购阈值时,视为团购候选。 + * 为避免误抓,singleFetchByIds 默认排除这些订单,仅允许显式团购入口处理。 + * + * @param {Object} orderModel 订单模型。 + * @param {number} warehouseId 仓库ID。 + * @param {Array} orderRows 待过滤订单行。 + * @return {Promise} 需排除的订单ID集合。 + */ + async resolveGroupCandidateOrderIdsForSingleFetch(orderModel, warehouseId, orderRows = []) { + const normalizedWarehouseId = Number(warehouseId || 0); + const normalizedRows = Array.isArray(orderRows) + ? orderRows.filter(row => Number.isInteger(Number(row && row.id || 0)) && Number(row && row.id || 0) > 0) + : []; + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0 || normalizedRows.length === 0) { + return []; + } + + const minGroupOrderFetchQuantity = await this.getMinGroupOrderFetchQuantity(normalizedWarehouseId); + if (!Number.isInteger(Number(minGroupOrderFetchQuantity)) || Number(minGroupOrderFetchQuantity) <= 1) { + return []; + } + + const itemHashValues = [ ...new Set(normalizedRows + .map(row => String(row && row.items_hash || '').trim()) + .filter(Boolean)) ]; + const itemValues = [ ...new Set(normalizedRows + .map(row => String(row && row.items || '').trim()) + .filter(Boolean)) ]; + if (itemHashValues.length === 0 && itemValues.length === 0) { + return []; + } + + const candidateWhereList = []; + if (itemHashValues.length > 0) { + candidateWhereList.push({ + items_hash: { [Op.in]: itemHashValues }, + }); + } + if (itemValues.length > 0) { + candidateWhereList.push({ + items: { [Op.in]: itemValues }, + }); + } + if (candidateWhereList.length === 0) { + return []; + } + + const candidateRows = await orderModel.findAll({ + attributes: [ 'id', 'items_hash', 'items', 'logistics_name' ], + where: { + wave_id: 0, + step: { [Op.in]: [ 1, 2, 3 ] }, + status: { [Op.ne]: 'cancel' }, + outbound_status: { [Op.ne]: 'padding' }, + [Op.or]: candidateWhereList, + }, + raw: true, + }); + + const buildItemKey = row => { + const itemHash = String(row && row.items_hash || '').trim(); + const itemText = String(row && row.items || '').trim(); + if (itemHash) { + return `items_hash:${itemHash}`; + } + if (itemText) { + return `items:${itemText}`; + } + return ''; + }; + + const itemCountMap = new Map(); + for (const row of Array.isArray(candidateRows) ? candidateRows : []) { + const itemKey = buildItemKey(row); + if (!itemKey) { + continue; + } + itemCountMap.set(itemKey, Number(itemCountMap.get(itemKey) || 0) + 1); + } + + const excludedOrderIds = []; + const normalizedThreshold = Number(minGroupOrderFetchQuantity); + for (const row of normalizedRows) { + const orderId = Number(row && row.id || 0); + const itemKey = buildItemKey(row); + if (!itemKey) { + continue; + } + + const itemGroupCount = Number(itemCountMap.get(itemKey) || 0); + if (itemGroupCount >= normalizedThreshold) { + excludedOrderIds.push(orderId); + } + } + + return [ ...new Set(excludedOrderIds) ].sort((a, b) => a - b); + } + + /** + * 按订单ID集合抓取到一个散单波次。 + * + * 规则: + * 1. 仅处理当前仓库上下文订单; + * 2. 传入 ids 中已存在波次(wave_id>0)的订单会被排除; + * 3. 不区分快递,所有可抓取订单统一写入同一个新波次; + * 4. 仅抓取待处理订单(step in [1,2,3])且未取消、未进入出库中的订单; + * 5. 成功抓取后批量写入订单操作日志。 + * + * @param {Object} data 请求参数。 + * @param {Array|number|string} data.ids 订单ID集合(优先)。 + * @param {Array|number|string} data.order_ids 订单ID集合别名。 + * @param {Array|number|string} data.orderIds 订单ID集合别名。 + * @return {Promise} 抓取结果。 + */ + async singleFetchByIds(data = {}) { + const contextWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const warehouseId = contextWarehouseId; + const rawIds = data && ( + data.ids !== undefined + ? data.ids + : data.order_ids !== undefined + ? data.order_ids + : data.orderIds + ); + const normalizedIds = this.normalizeIdsInput(rawIds); + if (normalizedIds.length === 0) { + throw new Error('ids 参数不能为空或格式错误'); + } + + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const transaction = await this.ctx.model.transaction(); + + try { + const orderRows = await orderModel.findAll({ + attributes: [ 'id', 'wave_id', 'wave_no', 'step', 'status', 'outbound_status', 'items_hash', 'items', 'logistics_name' ], + where: { + id: { [Op.in]: normalizedIds }, + }, + raw: true, + transaction, + lock: transaction.LOCK.UPDATE, + }); + + const normalizedOrderRows = Array.isArray(orderRows) ? orderRows : []; + const foundOrderIds = [ ...new Set(normalizedOrderRows + .map(row => Number(row && row.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + const existingWaveRows = normalizedOrderRows + .filter(row => Number(row && row.wave_id || 0) > 0); + const excludedExistingWaveOrderIds = [ ...new Set(existingWaveRows + .map(row => Number(row && row.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ] + .sort((a, b) => a - b); + + const fetchableRows = normalizedOrderRows.filter(row => { + const orderId = Number(row && row.id || 0); + const waveId = Number(row && row.wave_id || 0); + const step = Number(row && row.step || 0); + const status = String(row && row.status || '').trim(); + const outboundStatus = String(row && row.outbound_status || '').trim(); + + if (!Number.isInteger(orderId) || orderId <= 0) { + return false; + } + + if (waveId > 0) { + return false; + } + + if (![ 1, 2, 3 ].includes(step)) { + return false; + } + + if (status === 'cancel') { + return false; + } + + if (outboundStatus === 'padding') { + return false; + } + + return true; + }); + + const groupCandidateOrderIds = await this.resolveGroupCandidateOrderIdsForSingleFetch( + orderModel, + warehouseId, + fetchableRows + ); + const fetchableRowsAfterGroupFilter = fetchableRows.filter(row => { + const orderId = Number(row && row.id || 0); + return !groupCandidateOrderIds.includes(orderId); + }); + + const fetchableOrderIds = [ ...new Set(fetchableRowsAfterGroupFilter + .map(row => Number(row && row.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ] + .sort((a, b) => a - b); + const notFoundOrderIds = normalizedIds.filter(id => !foundOrderIds.includes(id)); + const skippedOrderIds = normalizedIds.filter(id => !fetchableOrderIds.includes(id)); + + if (fetchableOrderIds.length === 0) { + await transaction.commit(); + return this.success('ok', { + ids: normalizedIds, + wave_id: 0, + wave_no: '', + fetched_order_ids: [], + fetched_order_count: 0, + excluded_existing_wave_order_ids: excludedExistingWaveOrderIds, + excluded_group_order_ids: groupCandidateOrderIds, + skipped_order_ids: skippedOrderIds, + not_found_order_ids: notFoundOrderIds, + }); + } + + const { waveId, waveNo } = await this.createWaveBatchReady({ + warehouseId, + totalOrders: fetchableOrderIds.length, + itemDetailMachine: `manual_single_ids_${Date.now()}`, + itemPartType: 'manual_ids', + itemPart: `ids_${fetchableOrderIds.length}`, + distinguishExpress: false, + logisticsName: '', + itemSnapshotKey: 'manual_single_ids', + wavePrefix: SINGLE_FETCH_BY_IDS_WAVE_PREFIX, + transaction, + }); + + const orderFlagExpression = this.app.Sequelize.literal(`CASE + WHEN order_flag IS NULL OR order_flag = '' THEN '${WAVE_MANUAL_FETCH_FLAG}' + WHEN order_flag LIKE '%${WAVE_MANUAL_FETCH_FLAG}%' THEN order_flag + ELSE CONCAT(order_flag, ',${WAVE_MANUAL_FETCH_FLAG}') + END`); + + await orderModel.update({ + wave_id: waveId, + wave_no: waveNo, + order_flag: orderFlagExpression, + }, { + where: { + id: { [Op.in]: fetchableOrderIds }, + wave_id: 0, + }, + transaction, + }); + + const grabbedRows = await orderModel.findAll({ + where: { + id: { [Op.in]: fetchableOrderIds }, + wave_id: waveId, + }, + attributes: [ 'id' ], + raw: true, + transaction, + }); + const grabbedOrderIds = [ ...new Set((Array.isArray(grabbedRows) ? grabbedRows : []) + .map(row => Number(row && row.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ] + .sort((a, b) => a - b); + + if (grabbedOrderIds.length <= 0) { + await this.ctx.model.query(` + DELETE FROM wms_wave_batch + WHERE wave_id = :waveId + `, { + replacements: { waveId }, + transaction, + }); + + await transaction.commit(); + return this.success('ok', { + ids: normalizedIds, + wave_id: 0, + wave_no: '', + fetched_order_ids: [], + fetched_order_count: 0, + excluded_existing_wave_order_ids: excludedExistingWaveOrderIds, + excluded_group_order_ids: groupCandidateOrderIds, + skipped_order_ids: skippedOrderIds, + not_found_order_ids: notFoundOrderIds, + }); + } + + if (grabbedOrderIds.length !== fetchableOrderIds.length) { + await this.ctx.model.query(` + UPDATE wms_wave_batch + SET total_orders = :totalOrders, + update_time = NOW() + WHERE wave_id = :waveId + `, { + replacements: { + waveId, + totalOrders: grabbedOrderIds.length, + }, + transaction, + }); + } + + await transaction.commit(); + + await this.batchCreateOrderOperationLogs(grabbedOrderIds.map(orderId => ({ + orderId, + operationCode: 'ORDER_WAVE_ASSIGN', + message: `订单被分配到波次 ${waveNo}`, + })), { + warehouseId, + scene: 'singleFetchByIds', + }); + + return this.success('ok', { + ids: normalizedIds, + wave_id: waveId, + wave_no: waveNo, + fetched_order_ids: grabbedOrderIds, + fetched_order_count: grabbedOrderIds.length, + excluded_existing_wave_order_ids: excludedExistingWaveOrderIds, + excluded_group_order_ids: groupCandidateOrderIds, + skipped_order_ids: skippedOrderIds, + not_found_order_ids: notFoundOrderIds, + }); + } catch (error) { + await transaction.rollback(); + throw error; + } + } + /** * 批量将订单从波次中移出。 * diff --git a/app/service/systemMethods/setting/warehouse.js b/app/service/systemMethods/setting/warehouse.js index a550df9..bb1d182 100644 --- a/app/service/systemMethods/setting/warehouse.js +++ b/app/service/systemMethods/setting/warehouse.js @@ -57,7 +57,7 @@ class SettingWarehouseMethodsService extends MainService { } /** - * 修改仓库设置并清理指定仓库缓存。 + * 修改仓库设置并清理当前仓库缓存。 * * @param {Object} data 请求参数。 * @return {Promise} 统一响应结果。 @@ -70,7 +70,8 @@ class SettingWarehouseMethodsService extends MainService { } try { - const result = await targetService.saveSettings(data); + const { subject_config } = data || {}; + const result = await targetService.saveSettings({ subject_config }); return this.success('ok', result); } catch (error) { return this.fail(error.message || '保存仓库设置失败', { diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index d451dd7..18c9fa7 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -14,6 +14,7 @@ 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', }); @@ -639,8 +640,13 @@ class DeliveryOrderService extends Service { warehouseId: info.warehouseId, }); - // 异步处理:订单入队列 - await this.addOrderToQueue(orderId, info.warehouseId); + // 异步处理订单后续流程 + this.asyncProcessOrderCreated(orderId, info, normalizedCreateChannel).catch(error => { + ctx.logger.warn(`[DeliveryOrderService.addOrder] asyncProcessOrderCreated failed: ${error.message}`, { + orderId, + error: error.message, + }); + }); return { success: true, @@ -1216,45 +1222,619 @@ class DeliveryOrderService extends Service { return isNaN(num) ? defaultValue : num; } - // 订单入队列(异步处理) - async addOrderToQueue(orderId, warehouseId) { + /** + * 在当前调用内临时注入 ctx.user 上下文,并在结束后恢复。 + * + * 仅用于复用依赖登录上下文的既有 service 能力,避免扩大影响范围。 + * + * @param {Object} patchUser 需要覆盖的用户上下文字段。 + * @param {Function} callback 业务回调。 + * @return {Promise} 回调执行结果。 + */ + async withPatchedCtxUser(patchUser, callback) { const { ctx } = this; - - if (!orderId || !warehouseId) { - ctx.logger.warn('[订单入队列] 参数无效', { orderId, warehouseId }); - return; - } - - const cacheRedis = ctx.app && ctx.app.redis && ctx.app.redis.get ? ctx.app.redis.get('cache') : null; - if (!cacheRedis || typeof cacheRedis.publish !== 'function') { - ctx.logger.warn('[订单入队列] Redis 不可用', { orderId, warehouseId }); - return; - } - - const channel = `delivery_order:queue:${warehouseId}`; + const originUser = ctx.user; + const safeOriginUser = originUser && typeof originUser === 'object' ? originUser : {}; + const safePatchUser = patchUser && typeof patchUser === 'object' ? patchUser : {}; + ctx.user = { + ...safeOriginUser, + ...safePatchUser, + }; try { - await cacheRedis.publish(channel, JSON.stringify({ - orderId, - warehouseId, - timestamp: Date.now(), - action: 'order_created', - })); + return await callback(); + } finally { + ctx.user = originUser; + } + } - ctx.logger.info('[订单入队列] 发布成功', { - orderId, - warehouseId, - channel, - }); + /** + * 构建订单创建后异步处理所需上下文。 + * + * @param {number|string} orderId 订单ID。 + * @param {Object} info 订单创建上下文。 + * @return {Promise} 异步处理上下文。 + */ + async buildAsyncProcessContext(orderId, info = {}) { + const { ctx } = this; + const normalizedOrderId = Number(orderId || 0); + const warehouseId = Number(info && info.warehouseId || 0); + const storeId = Number(info && info.storeId || 0); + + if (!Number.isInteger(normalizedOrderId) || normalizedOrderId <= 0) { + return null; + } + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + return null; + } + + const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + const order = await DeliveryModel.findOne({ + where: { + id: normalizedOrderId, + warehouse_id: warehouseId, + }, + raw: true, + }); + + if (!order) { + return null; + } + + const OrderItemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + const orderItemRows = await OrderItemsModel.findAll({ + where: { + order_id: normalizedOrderId, + }, + attributes: [ 'order_id', 'plan_qty', 'stock_id', 'item_code', 'item_name', 'item_snapshot' ], + raw: true, + }); + + return { + orderId: normalizedOrderId, + warehouseId, + storeId: storeId > 0 ? storeId : Number(order.store_id || 0), + order, + orderItemRows: Array.isArray(orderItemRows) ? orderItemRows : [], + }; + } + + /** + * 构建快递分配显式请求体。 + * + * @param {Object} context 异步处理上下文。 + * @return {Object} 快递分配请求。 + */ + buildExpressAllocateRequest(context) { + const order = context && context.order ? context.order : {}; + return { + orders: [{ + order_id: Number(order.id || context.orderId || 0), + business_key: 1, + sys_platform_code: String(order.sys_platform_code || '').trim(), + logistics_code: String(order.logistics_code || '').trim(), + store_id: Number(order.store_id || context.storeId || 0), + warehouse_id: Number(order.warehouse_id || context.warehouseId || 0), + }], + }; + } + + /** + * 构建储位分配显式请求体。 + * + * @param {Object} context 异步处理上下文。 + * @return {Object} 储位分配请求。 + */ + buildStorageAllocateRequest(context) { + return { + allow_storage_location: true, + order_ids: [ Number(context && context.orderId || 0) ], + }; + } + + /** + * 读取货主-仓库策略配置。 + * + * @param {number} storeId 货主ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 策略配置。 + */ + async getStoreWarehousePolicyConfig(storeId, warehouseId) { + const storeWarehouseService = this.ctx.service + && this.ctx.service.systems + && this.ctx.service.systems.storeWarehouse; + if (!storeWarehouseService || typeof storeWarehouseService.getContractConfig !== 'function') { + return {}; + } + + try { + const contractConfig = await storeWarehouseService.getContractConfig( + Number(warehouseId || 0), + Number(storeId || 0) + ); + const policyConfig = contractConfig && typeof contractConfig.policy_config === 'object' + ? contractConfig.policy_config + : {}; + return policyConfig; } catch (error) { - ctx.logger.warn('[订单入队列] 发布失败', { - orderId, + this.ctx.logger.warn(`[DeliveryOrderService.getStoreWarehousePolicyConfig] read contract config failed: ${error.message}`, { + storeId, warehouseId, - channel, + error: error.message, + }); + return {}; + } + } + + /** + * 归一化策略开关值。 + * + * @param {any} value 原始开关值。 + * @return {boolean} 是否开启。 + */ + normalizePolicyFlag(value) { + if (typeof value === 'boolean') { + return value; + } + const normalizedText = String(value === undefined || value === null ? '' : value).trim().toLowerCase(); + return [ '1', 'true', 'yes', 'on' ].includes(normalizedText); + } + + /** + * 构建自动加团结构信息。 + * + * @param {Object} context 异步处理上下文。 + * @return {Object|null} 自动加团结构信息。 + */ + buildAutoGroupingStructure(context) { + const waveService = this.ctx.service && this.ctx.service.systemMethods + && this.ctx.service.systemMethods.order + && this.ctx.service.systemMethods.order.wave; + if (!waveService) { + return null; + } + + const order = context && context.order ? context.order : {}; + const itemPartType = String(order.items_hash || '').trim() ? 'items_hash' : 'items'; + const itemPart = String(itemPartType === 'items_hash' ? order.items_hash : order.items || '').trim(); + if (!itemPart) { + return null; + } + + const logisticsName = String(order.logistics_name || '').trim(); + const mergedItemDetails = typeof waveService.mergeOrderItemDetails === 'function' + ? waveService.mergeOrderItemDetails(context && context.orderItemRows ? context.orderItemRows : []) + : []; + const itemSnapshotKey = typeof waveService.buildItemSnapshotKey === 'function' + ? waveService.buildItemSnapshotKey(mergedItemDetails) + : ''; + const itemDetailMachine = typeof waveService.buildMachineStructureToken === 'function' + ? waveService.buildMachineStructureToken({ + item_part_type: itemPartType, + item_part: itemPart, + distinguish_express: true, + logistics_name: logisticsName, + item_snapshot_key: itemSnapshotKey, + }) + : ''; + + return { + itemPartType, + itemPart, + logisticsName, + itemSnapshotKey, + itemDetailMachine, + }; + } + + /** + * 查找自动加团中的匹配波次。 + * + * @param {Object} context 异步处理上下文。 + * @param {Object} structure 自动加团结构信息。 + * @return {Promise} 命中的波次ID,未命中返回 0。 + */ + async findAutoGroupingWaveId(context, structure) { + const { ctx } = this; + const waveService = ctx.service.systemMethods.order.wave; + const request = { + page: 1, + pageSize: 50, + where: { + wave_status: 0, + item_part_type: structure.itemPartType, + item_part: structure.itemPart, + item_snapshot_key: structure.itemSnapshotKey, + distinguish_express: 1, + logistics_name: structure.logisticsName, + }, + }; + + const response = await this.withPatchedCtxUser({ + store_id: context.warehouseId, + warehouse_id: context.warehouseId, + }, async () => { + return await waveService.batchList(request); + }); + const list = response && response.list; + if (!Array.isArray(list) || list.length === 0) { + return 0; + } + + return Number(list[0] && list[0].wave_id || 0); + } + + /** + * 将订单加入指定波次,并回写波次统计。 + * + * @param {Object} context 异步处理上下文。 + * @param {number} waveId 波次ID。 + * @return {Promise} 是否成功加入。 + */ + async appendOrderToWave(context, waveId) { + const { ctx } = this; + const normalizedWaveId = Number(waveId || 0); + if (!Number.isInteger(normalizedWaveId) || normalizedWaveId <= 0) { + return false; + } + + const warehouseId = Number(context.warehouseId || 0); + const orderId = Number(context.orderId || 0); + if (!Number.isInteger(warehouseId) || warehouseId <= 0 || !Number.isInteger(orderId) || orderId <= 0) { + return false; + } + + const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + const transaction = await ctx.model.transaction(); + try { + const orderRow = await DeliveryModel.findOne({ + where: { + id: orderId, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'wave_id', 'step', 'status', 'outbound_status' ], + transaction, + lock: transaction.LOCK.UPDATE, + }); + if (!orderRow) { + await transaction.commit(); + return false; + } + + const currentWaveId = Number(orderRow.wave_id || 0); + if (currentWaveId === normalizedWaveId) { + await transaction.commit(); + return true; + } + if (currentWaveId > 0) { + await transaction.commit(); + return false; + } + + const currentStep = Number(orderRow.step || 0); + const currentStatus = String(orderRow.status || '').trim(); + const currentOutboundStatus = String(orderRow.outbound_status || '').trim(); + if (![ 1, 2, 3 ].includes(currentStep) || currentStatus === 'cancel' || currentOutboundStatus === 'padding') { + await transaction.commit(); + return false; + } + + const waveRows = await ctx.model.query(` + SELECT wave_id, wave_no, total_orders + FROM wms_wave_batch + WHERE warehouse_id = :warehouseId + AND wave_id = :waveId + LIMIT 1 + FOR UPDATE + `, { + replacements: { + warehouseId, + waveId: normalizedWaveId, + }, + type: ctx.model.QueryTypes.SELECT, + transaction, + }); + const wave = Array.isArray(waveRows) && waveRows[0] ? waveRows[0] : null; + if (!wave) { + await transaction.commit(); + return false; + } + + await DeliveryModel.update({ + wave_id: normalizedWaveId, + wave_no: String(wave.wave_no || '').trim(), + }, { + where: { + id: orderId, + warehouse_id: warehouseId, + wave_id: 0, + }, + transaction, + }); + + await ctx.model.query(` + UPDATE wms_wave_batch + SET total_orders = total_orders + 1, + update_time = NOW() + WHERE warehouse_id = :warehouseId + AND wave_id = :waveId + `, { + replacements: { + warehouseId, + waveId: normalizedWaveId, + }, + transaction, + }); + + await transaction.commit(); + return true; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 统计可参与新团购波次的订单数量。 + * + * @param {Object} context 异步处理上下文。 + * @param {Object} structure 自动加团结构信息。 + * @return {Promise} 可参与数量。 + */ + async countCandidateGroupOrders(context, structure) { + const { ctx } = this; + const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(context.warehouseId); + const where = { + warehouse_id: context.warehouseId, + wave_id: 0, + step: { [ctx.app.Sequelize.Op.in]: [ 1, 2, 3 ] }, + status: { [ctx.app.Sequelize.Op.ne]: 'cancel' }, + outbound_status: { [ctx.app.Sequelize.Op.ne]: 'padding' }, + logistics_name: structure.logisticsName, + }; + where[structure.itemPartType] = structure.itemPart; + + return await DeliveryModel.count({ where }); + } + + /** + * 按结构创建团购波次。 + * + * @param {Object} context 异步处理上下文。 + * @param {Object} structure 自动加团结构信息。 + * @param {number} minGroupOrderFetchQuantity 最小团购抓取数量。 + * @param {number} maxWaveQuantity 最大加团数量。 + * @return {Promise} 抓取结果。 + */ + async createGroupingWave(context, structure, minGroupOrderFetchQuantity, maxWaveQuantity) { + const { ctx } = this; + const waveService = ctx.service.systemMethods.order.wave; + const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(context.warehouseId); + + const requestStructure = { + item_part_type: structure.itemPartType, + item_part: structure.itemPart, + distinguish_express: true, + logistics_name: structure.logisticsName, + item_snapshot_key: structure.itemSnapshotKey, + item_detail_machine: structure.itemDetailMachine, + quantity: maxWaveQuantity, + }; + + return await this.withPatchedCtxUser({ + store_id: context.warehouseId, + warehouse_id: context.warehouseId, + }, async () => { + return await waveService.fetchSingleStructure( + DeliveryModel, + requestStructure, + context.warehouseId, + 'B', + minGroupOrderFetchQuantity, + { maxFetchQuantity: maxWaveQuantity } + ); + }); + } + + /** + * 将波次标记为自动加团中。 + * + * @param {Object} context 异步处理上下文。 + * @param {number[]} waveIds 波次ID集合。 + * @return {Promise} 无返回值。 + */ + async markWaveAutoGrouping(context, waveIds) { + const waveService = this.ctx.service.systemMethods.order.wave; + await this.withPatchedCtxUser({ + store_id: context.warehouseId, + warehouse_id: context.warehouseId, + }, async () => { + await waveService.batchAutoGrouping({ ids: waveIds }); + }); + } + + /** + * 达到最大加团数时将波次结束自动加团。 + * + * @param {Object} context 异步处理上下文。 + * @param {number} waveId 波次ID。 + * @param {number} maxWaveQuantity 最大加团数量。 + * @return {Promise} 无返回值。 + */ + async finishAutoGroupingIfNeeded(context, waveId, maxWaveQuantity) { + const { ctx } = this; + const normalizedWaveId = Number(waveId || 0); + const normalizedMaxWaveQuantity = Number(maxWaveQuantity || 0); + if (!Number.isInteger(normalizedWaveId) || normalizedWaveId <= 0) { + return; + } + if (!Number.isInteger(normalizedMaxWaveQuantity) || normalizedMaxWaveQuantity <= 0) { + return; + } + + const rows = await ctx.model.query(` + SELECT total_orders + FROM wms_wave_batch + WHERE warehouse_id = :warehouseId + AND wave_id = :waveId + LIMIT 1 + `, { + replacements: { + warehouseId: context.warehouseId, + waveId: normalizedWaveId, + }, + type: ctx.model.QueryTypes.SELECT, + }); + + const totalOrders = Number(Array.isArray(rows) && rows[0] ? rows[0].total_orders : 0); + if (!Number.isInteger(totalOrders) || totalOrders < normalizedMaxWaveQuantity) { + return; + } + + const waveService = this.ctx.service.systemMethods.order.wave; + await this.withPatchedCtxUser({ + store_id: context.warehouseId, + warehouse_id: context.warehouseId, + }, async () => { + await waveService.batchFinishAutoGrouping({ ids: [ normalizedWaveId ] }); + }); + } + + /** + * 执行自动加团逻辑(仅团购)。 + * + * @param {Object} context 异步处理上下文。 + * @return {Promise} 无返回值。 + */ + async runAutoGrouping(context) { + const { ctx } = this; + const storeSubjectConfig = await this.getStoreSubjectConfig(context.storeId); + if (!storeSubjectConfig || !storeSubjectConfig.auto_grouping_enabled) { + return; + } + + const maxWaveQuantity = Number(storeSubjectConfig.max_wave_quantity || 0) > 0 + ? Number(storeSubjectConfig.max_wave_quantity) + : 500; + const structure = this.buildAutoGroupingStructure(context); + if (!structure) { + return; + } + + const waveService = ctx.service.systemMethods.order.wave; + const minGroupOrderFetchQuantity = await this.withPatchedCtxUser({ + store_id: context.warehouseId, + warehouse_id: context.warehouseId, + }, async () => { + return await waveService.getMinGroupOrderFetchQuantity(context.warehouseId); + }); + + const matchedAutoGroupingWaveId = await this.findAutoGroupingWaveId(context, structure); + if (matchedAutoGroupingWaveId > 0) { + const joined = await this.appendOrderToWave(context, matchedAutoGroupingWaveId); + if (!joined) { + return; + } + + await this.finishAutoGroupingIfNeeded(context, matchedAutoGroupingWaveId, maxWaveQuantity); + return; + } + + const candidateCount = await this.countCandidateGroupOrders(context, structure); + if (candidateCount < minGroupOrderFetchQuantity) { + return; + } + + const fetchResult = await this.createGroupingWave( + context, + structure, + minGroupOrderFetchQuantity, + maxWaveQuantity + ); + const createdWaveIds = Array.isArray(fetchResult && fetchResult.wave_ids) + ? fetchResult.wave_ids.filter(id => Number.isInteger(Number(id)) && Number(id) > 0).map(id => Number(id)) + : []; + if (createdWaveIds.length <= 0) { + return; + } + + await this.markWaveAutoGrouping(context, createdWaveIds); + await this.finishAutoGroupingIfNeeded(context, createdWaveIds[0], maxWaveQuantity); + } + + /** + * 执行订单创建后的单步动作,单步失败不影响后续。 + * + * @param {string} stepName 步骤名称。 + * @param {Function} stepHandler 步骤处理函数。 + * @return {Promise} 无返回值。 + */ + async runAsyncProcessStep(stepName, stepHandler) { + try { + await stepHandler(); + } catch (error) { + this.ctx.logger.warn(`[DeliveryOrderService.asyncProcessOrderCreated] ${stepName} failed: ${error.message}`, { + step: stepName, error: error.message, }); } } + + // 订单异步流程 + /** + * 订单创建后的异步流程。 + * + * 按顺序执行:自动分配快递 -> 自动分配储位 -> 自动加团。 + * 每一步都使用显式请求对象调用下游能力,单步异常不中断后续。 + * + * @param {number|string} orderId 订单ID。 + * @param {Object} info 当前仓库与货主上下文。 + * @param {string} createChannel 订单创建渠道。 + * @return {Promise} 无返回值。 + */ + async asyncProcessOrderCreated(orderId, info, createChannel) { + const normalizedCreateChannel = String(createChannel || '').trim().toUpperCase(); + if (![ 'API', 'QM' ].includes(normalizedCreateChannel)) { + return; + } + + const context = await this.buildAsyncProcessContext(orderId, info); + if (!context) { + return; + } + + const policyConfig = await this.getStoreWarehousePolicyConfig(context.storeId, context.warehouseId); + const isAutoAllocateExpressEnabled = this.normalizePolicyFlag(policyConfig.auto_allocate_express); + const isAutoAllocateStorageEnabled = this.normalizePolicyFlag(policyConfig.auto_allocate_storage); + + if (isAutoAllocateExpressEnabled) { + await this.runAsyncProcessStep('allocateExpress', async () => { + const request = this.buildExpressAllocateRequest(context); + await this.withPatchedCtxUser({ + store_id: context.warehouseId, + warehouse_id: context.warehouseId, + }, async () => { + await this.ctx.service.systemMethods.order.pendingOrder.allocateExpressCode(request); + }); + }); + } + + if (isAutoAllocateStorageEnabled) { + await this.runAsyncProcessStep('allocateStorage', async () => { + const request = this.buildStorageAllocateRequest(context); + await this.withPatchedCtxUser({ + store_id: context.warehouseId, + warehouse_id: context.warehouseId, + }, async () => { + await this.ctx.service.systems.orderStorageAllocation.allocateStorage(request); + }); + }); + } + + await this.runAsyncProcessStep('autoGrouping', async () => { + await this.runAutoGrouping(context); + }); + } } module.exports = DeliveryOrderService; diff --git a/app/service/systems/setting/warehouse.js b/app/service/systems/setting/warehouse.js index 3e59b35..82d0099 100644 --- a/app/service/systems/setting/warehouse.js +++ b/app/service/systems/setting/warehouse.js @@ -196,12 +196,10 @@ class SettingWarehouseService extends Service { } /** - * 修改当前仓库设置并清理指定仓库缓存。 + * 修改当前仓库设置并清理当前仓库缓存。 * * @param {Object} [data={}] 请求参数。 * @param {Object} [data.subject_config] 仓库设置对象,支持部分字段更新。 - * @param {number|string} [data.cache_warehouse_id] 需要清理缓存的仓库 ID,默认当前仓库。 - * @param {number|string} [data.cacheWarehouseId] 同 cache_warehouse_id。 * @return {Promise} 更新后的仓库设置。 */ async saveSettings(data = {}) { @@ -244,13 +242,7 @@ class SettingWarehouseService extends Service { subject_config: normalizedConfig, }); - let cacheWarehouseId = Number( - data.cache_warehouse_id !== undefined ? data.cache_warehouse_id : (data.cacheWarehouseId !== undefined ? data.cacheWarehouseId : warehouseId) - ); - if (!Number.isFinite(cacheWarehouseId) || cacheWarehouseId <= 0) { - throw this.createError('cache_warehouse_id 参数不合法', 400); - } - cacheWarehouseId = Math.floor(cacheWarehouseId); + const cacheWarehouseId = warehouseId; await this.clearWarehouseSettingCache(cacheWarehouseId); diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index e514e73..fd84cc6 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -358,8 +358,11 @@ class ReceivingService extends Service { } // 5. 将图片合并到对应的明细中 const items = receivingItems.map(item => { + const detail = item.toJSON(); return { - ...item.toJSON(), + ...detail, + box_remainder: detail.box_remainder ?? 0, + box_weight: detail.box_weight ?? 0, images: itemImagesMap[item.id] || [], }; }); @@ -2008,8 +2011,12 @@ class ReceivingService extends Service { // 5. 将图片合并到对应的明细中 const items = receivingItems.map(item => { const itemData = item.toJSON(); - itemData.images = itemImagesMap[item.id] || []; // 获取该明细的图片,如果没有则为空数组 - return itemData; + return { + ...itemData, + box_remainder: itemData.box_remainder ?? 0, + box_weight: itemData.box_weight ?? 0, + images: itemImagesMap[item.id] || [], // 获取该明细的图片,如果没有则为空数组 + }; }); // 6. 查询主表的图片 @@ -2247,13 +2254,11 @@ class ReceivingService extends Service { warehouseId, required: false, attributes: [ 'store_id', 'store_remask' ], - attributes: [ 'store_id', 'store_remask' ], }), { model: app.model.StockBarcode, as: 'barcodes', attributes: [ 'barcode' ], - attributes: [ 'barcode' ], required: false, }, ], @@ -2893,6 +2898,8 @@ class ReceivingService extends Service { box_height, box_length, weight, + box_remainder, // 箱余数 + box_weight, // 箱重量 } = data; // 2. 验证必填字段 if (!id) { @@ -2956,6 +2963,20 @@ class ReceivingService extends Service { }; } + if (box_remainder !== undefined && box_remainder < 0) { + return { + code: 400, + message: '箱余数不能为负数', + }; + } + + if (box_weight !== undefined && box_weight < 0) { + return { + code: 400, + message: '箱重量不能为负数', + }; + } + // 6. 准备更新数据 const updateData = { actual_quantity, @@ -2972,6 +2993,8 @@ class ReceivingService extends Service { if (box_width !== undefined) updateData.box_width = box_width || 0; if (box_height !== undefined) updateData.box_height = box_height || 0; if (weight !== undefined) updateData.weight = weight || 0; + if (box_remainder !== undefined) updateData.box_remainder = box_remainder || 0; + if (box_weight !== undefined) updateData.box_weight = box_weight || 0; // 批次信息 if (batch_number !== undefined) updateData.batch_number = batch_number; @@ -3091,6 +3114,8 @@ class ReceivingService extends Service { product_name: receivingDetail.product_name, barcode: receivingDetail.barcode, system_product_id: receivingDetail.system_product_id, + box_remainder: updateData.box_remainder !== undefined ? updateData.box_remainder : receivingDetail.box_remainder, + box_weight: updateData.box_weight !== undefined ? updateData.box_weight : receivingDetail.box_weight, updated_at: receivingDetail.updated_at, }, message: '修改成功', @@ -3605,6 +3630,20 @@ class ReceivingService extends Service { const reportFileName = String( (completionReport && (completionReport.filename || completionReport.fileKey || completionReport.key)) || `收货完成_${receivingNumber}.xlsx` ).trim(); + const detailItems = Array.isArray(receiving.details) ? receiving.details : []; + const normalizedDetails = detailItems.map(item => ({ + id: Number(item.id || 0), + product_name: item.product_name || '', + barcode: item.barcode || '', + actual_quantity: Number(item.actual_quantity || 0), + box_quantity: Number(item.box_quantity || 0), + pallet_quantity: Number(item.pallet_quantity || 0), + box_remainder: Number(item.box_remainder || 0), + box_weight: Number(item.box_weight || 0), + weight: Number(item.weight || 0), + })); + const totalBoxRemainder = normalizedDetails.reduce((sum, item) => sum + Number(item.box_remainder || 0), 0); + const totalBoxWeight = normalizedDetails.reduce((sum, item) => sum + Number(item.box_weight || 0), 0); const title = `收货单${receivingNumber}已完成`; const contactLines = this.getCompletionContactFields(receiving).map(([ field, value ]) => `${field}:${value || '无'}`); const content = [ @@ -3617,6 +3656,8 @@ class ReceivingService extends Service { `未匹配商品:${unmatchedDetails}件`, `总数量:${totalQuantity}`, `总箱数:${receiving.total_boxes || 0}`, + `总箱余数:${totalBoxRemainder}`, + `总箱重:${totalBoxWeight}`, `总托盘数:${receiving.total_pallets || 0}`, operatorName ? `完成人:${operatorName}` : '', `开始时间:${this.formatReportDate(receiving.created_at)}`, @@ -3658,6 +3699,11 @@ class ReceivingService extends Service { unmatched_details: unmatchedDetails, total_quantity: totalQuantity, }, + details: normalizedDetails, + boxSummary: { + total_box_remainder: totalBoxRemainder, + total_box_weight: totalBoxWeight, + }, completionReport: completionReport ? { fileKey: completionReport.fileKey || completionReport.key || '', url: reportUrl, @@ -3696,7 +3742,8 @@ class ReceivingService extends Service { required: false, attributes: [ 'id', 'system_product_id', 'product_name', 'barcode', 'actual_quantity', 'weight', - 'box_quantity', 'pallet_quantity', 'receiving_status', 'storage_status', + 'box_quantity', 'pallet_quantity', 'box_remainder', 'box_weight', + 'receiving_status', 'storage_status', 'batch_number', 'production_date', 'expiry_date', 'remark', ], include: [{ diff --git a/database/migrations/20260504000000-baseline.js b/database/migrations/20260504000000-baseline.js index add6cc6..7219927 100644 --- a/database/migrations/20260504000000-baseline.js +++ b/database/migrations/20260504000000-baseline.js @@ -106,4 +106,4 @@ module.exports = { } await queryInterface.sequelize.query('SET FOREIGN_KEY_CHECKS = 1'); }, -}; \ No newline at end of file +}; diff --git a/database/migrations/20260506103000-add-box-fields-to-wms_receiving_detail.js b/database/migrations/20260506103000-add-box-fields-to-wms_receiving_detail.js new file mode 100644 index 0000000..b7a3fa6 --- /dev/null +++ b/database/migrations/20260506103000-add-box-fields-to-wms_receiving_detail.js @@ -0,0 +1,53 @@ +'use strict'; + +/** + * Migration: add box_remainder and box_weight to wms_receiving_detail + * - box_remainder: INT NOT NULL DEFAULT 0 COMMENT '箱余数' + * - box_weight: DECIMAL(10,2) NOT NULL DEFAULT '0.00' COMMENT '箱重量(kg)' + * + * Idempotent: uses queryInterface.describeTable to only add if missing. + * + * Raw SQL (MySQL 8+ supports IF NOT EXISTS): + * ALTER TABLE `wms_receiving_detail` + * ADD COLUMN IF NOT EXISTS `box_remainder` INT NOT NULL DEFAULT 0 COMMENT '箱余数', + * ADD COLUMN IF NOT EXISTS `box_weight` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '箱重量(kg`)'; + * + * If MySQL < 8 (no IF NOT EXISTS), use INFORMATION_SCHEMA checks before ALTER. + */ + +module.exports = { + up: async (queryInterface, Sequelize) => { + const table = 'wms_receiving_detail'; + const columns = await queryInterface.describeTable(table); + + if (!columns.box_remainder) { + await queryInterface.addColumn(table, 'box_remainder', { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '箱余数', + }); + } + + if (!columns.box_weight) { + await queryInterface.addColumn(table, 'box_weight', { + type: Sequelize.DECIMAL(10, 2), + allowNull: false, + defaultValue: '0.00', + comment: '箱重量(kg)', + }); + } + }, + + down: async (queryInterface, Sequelize) => { + const table = 'wms_receiving_detail'; + const columns = await queryInterface.describeTable(table); + + if (columns.box_remainder) { + await queryInterface.removeColumn(table, 'box_remainder'); + } + if (columns.box_weight) { + await queryInterface.removeColumn(table, 'box_weight'); + } + }, +}; diff --git a/docs/storage-receiving-api.md b/docs/storage-receiving-api.md index eab9ee7..158eb67 100644 --- a/docs/storage-receiving-api.md +++ b/docs/storage-receiving-api.md @@ -249,6 +249,8 @@ curl -X POST "http://127.0.0.1:6060/system?method=storage.receiving.bindDetailPr | `box_width` | `number` | 否 | 箱宽(单位按系统约定) | | `box_height` | `number` | 否 | 箱高 | | `box_length` | `number` | 否 | 箱长 | +| `box_remainder` | `number` | 否 | 箱内剩余数量/零散数量(不满箱时的件数) | +| `box_weight` | `number` | 否 | 实测箱重(单位与系统重量一致,如 kg) | | `weight` | `number` | 否 | 毛重/重量 | > 说明:`id` 与 `receiving_id` 为必须校验项,其他字段为可选—仅在传入时会写入/覆盖对应明细字段。传入 `system_product_id` 时,系统优先使用系统商品信息回填字段(前端可只传 `system_product_id` 来自动回填)。 @@ -287,6 +289,8 @@ curl -X POST "http://127.0.0.1:6060/system?method=storage.receiving.bindDetailPr "product_name": "测试商品", "barcode": "", "system_product_id": null, + "box_remainder": 0, + "box_weight": 0.0, "updated_at": "2026-04-01T00:00:00.000Z" } } @@ -300,6 +304,8 @@ curl -X POST "http://127.0.0.1:6060/system?method=storage.receiving.bindDetailPr - `data.product_name`:商品名称(若 `system_product_id` 回填则为系统商品名称) - `data.barcode`:条码 - `data.system_product_id`:回填或当前关联的系统商品 ID +- `data.box_remainder`:箱内剩余数量/零散数量(不满箱时的件数) +- `data.box_weight`:实测箱重(单位与系统重量一致) - `data.updated_at`:明细记录的更新时间 ### 11.5 常见错误码 @@ -324,4 +330,107 @@ curl -X POST "http://127.0.0.1:6060/system?method=storage.receiving.bindDetailPr --- +## 12. 接口:storage.receiving.getReceivingDetail + +## 接口:storage.receiving.get + +### 用途 + +查询收货单完整信息(含明细 `details`、`images` 等)。 + +### 请求参数 + +| 字段 | 类型 | 必填 | 说明 | +|---|---:|---|---| +| `id` | `number` | 是 | 收货单 ID(source=body) | + +### 返回字段补充 + +- `data.details.*.box_remainder`:number,可选,箱内剩余数量/零散数量(不满箱时的件数),默认 0。 +- `data.details.*.box_weight`:number,可选,实测箱重(单位与系统重量一致,如 kg),默认 0。 + +兼容性:新增字段为可选,旧客户端无需变更。 + +### 12.1 用途 + +查询单张收货单详情,返回收货单头信息与明细(`details`),用于前端展示或二次处理。 + +### 12.2 请求参数 + +| 字段 | 类型 | 必填 | 说明 | +|---|---:|---|---| +| `id` | `number` | 是 | 收货单 ID | +| `pagination` | `object` | 否 | 明细分页参数,支持 `page` / `pageSize` | + +### 12.3 返回示例(成功) + +```json +{ + "code": 200, + "message": "success", + "data": { + "receiving": { + "id": 12345, + "receiving_number": "RCV20260506001", + "details": [ + { + "id": 501, + "product_name": "测试商品", + "actual_quantity": 10, + "box_quantity": 2, + "box_remainder": 0, + "box_weight": 5.2 + } + ], + "pagination": { + "page": 1, + "pageSize": 20, + "total": 1 + } + } + } +} +``` + +### 12.4 返回字段说明(新增) + +- `receiving.details.*.box_remainder`:number,可选,箱内剩余数量/零散数量(不满箱时的件数)。 +- `receiving.details.*.box_weight`:number,可选,实测箱重(单位与系统重量一致,如 kg)。 + +## 13. 接口:storage.receiving.completeReceiving + +### 13.1 用途 + +完成收货操作;完成后系统会发送内部通知/回调,通知中会包含收货单明细层面的箱规回写信息。 + +### 13.2 通知说明(新增字段) + +完成收货时发送的通知 payload/metadata 将在每条明细中包含 `box_remainder` 与 `box_weight`,用于下游系统或前端展示箱内余量与实测箱重。通知示例(结构化示例,字段以实现为准): + +```json +{ + "event": "storage.receiving.completed", + "receiving_id": 12345, + "details": [ + { + "id": 501, + "box_remainder": 0, + "box_weight": 5.2 + } + ], + "metadata": { + "completed_by": 1001, + "completed_at": "2026-05-06T12:00:00.000Z" + } +} +``` + +### 13.3 字段说明(通知/metadata) + +- `details[*].box_remainder`:number,可选,箱内剩余数量/零散数量。 +- `details[*].box_weight`:number,可选,实测箱重,单位同系统重量(例如 kg)。 + +兼容性:上述新增字段为可选字段,旧版消费者在未识别这些字段时可忽略。 + + diff --git a/methods/changes/system.json b/methods/changes/system.json index 259f442..74ee9f7 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,79 @@ [ + { + "version": "2026.05.06-system-05", + "date": "2026-05-06", + "summary": "storage.receiving.get 返回扩展:data.details[*] 新增 box_remainder、box_weight", + "methods": [ + "storage.receiving.get" + ], + "notes": [ + "storage.receiving.get 的响应在 data.details[*] 中新增可选字段:box_remainder(箱内剩余数量/零散数量,number,默认 0)与 box_weight(实测箱重,number,默认 0)。", + "兼容性:新增字段为可选,旧客户端无需修改;建议前端在需要展示箱内余量/箱重时使用这些字段。" + ], + "type": "updated" + }, + { + "version": "2026.05.06-system-04", + "date": "2026-05-06", + "summary": "storage.receiving.getReceivingDetail 返回扩展:明细增加 box_remainder、box_weight;storage.receiving.completeReceiving 通知包含这两个字段", + "methods": [ + "storage.receiving.getReceivingDetail", + "storage.receiving.completeReceiving" + ], + "notes": [ + "为支持箱规统计与通知回传,getReceivingDetail 的明细项(receiving.details 或 data.details)在响应中新增可选字段:box_remainder(箱内剩余数量/零散数量,number)与 box_weight(实测箱重,number,单位同系统重量)。", + "completeReceiving 在完成收货后会发送通知(或回调),通知 payload/metadata 中将包含每条明细的 box_remainder 与 box_weight 字段,供下游系统/前端展示或审计使用。", + "兼容性:新增字段为可选,旧客户端在未使用这些字段时无需变更。" + ], + "type": "updated" + }, + { + "version": "2026.05.06-system-03", + "date": "2026-05-06", + "summary": "storage.receiving.detailChange:新增入参/出参字段 box_remainder、box_weight", + "methods": [ + "storage.receiving.detailChange" + ], + "notes": [ + "为支持箱规细化与回写,detailChange 新增可选入参 box_remainder(箱内余量/零散数量)和 box_weight(实测箱重,单位同系统重量),写入后会回写至明细并在响应 data 中返回对应字段。", + "兼容性:新增字段为可选,不传入则不影响现有调用;建议前端在需要回写箱余与箱重时一并传入。" + ], + "type": "updated" + }, + { + "version": "2026.05.06-system-02", + "date": "2026-05-06", + "summary": "新增 order.wave.singleFetchByIds:按订单ID抓取到一个散单波次", + "date": "2026-05-06", + "summary": "新增 order.wave.singleFetchByIds:按订单ID抓取到一个散单波次", + "methods": [ + "order.wave.singleFetchByIds" + ], + "notes": [ + "新增 order.wave.singleFetchByIds:按入参 ids(兼容 order_ids/orderIds)去重后筛选当前仓库内待处理且不在波次中的订单,若存在可抓取订单则创建单个散单波次并把这些订单写入该波次(不区分快递);成功后批量写入订单操作日志;若无可抓取订单返回 wave_id=0。", + "接口行为严格对齐实现:过滤条件包含 step in [1,2,3]、status != 'cancel'、outbound_status != 'padding';已在波次的订单会被排除并返回 excluded_existing_wave_order_ids;响应包含 ids、wave_id、wave_no、fetched_order_ids、fetched_order_count、excluded_existing_wave_order_ids、skipped_order_ids、not_found_order_ids。" + ], + "type": "added" + }, + { + "version": "2026.05.06-system-01", + "date": "2026-05-06", + "summary": "新增 order.wave.groupFetch 与 order.wave.singleFetch;order.wave.fetch 保留兼容别名;抓取进度补充上限字段", + "methods": [ + "order.wave.groupFetch", + "order.wave.singleFetch", + "order.wave.fetch", + "order.wave.fetchTaskProgress" + ], + "notes": [ + "新增 order.wave.groupFetch:抓取团购接口(异步任务提交),参数 structure_list 与原 fetch 一致。", + "新增 order.wave.singleFetch:抓取散单接口(异步任务提交),在 structure_list 每项新增必填字段 max_fetch_quantity(最大抓取上限,订单数,正整数)。", + "order.wave.fetch 保留为兼容别名(等同 groupFetch),避免误导客户端。", + "groupFetch/singleFetch/fetch 的响应新增可选字段 fetch_mode;singleFetch 响应额外返回 max_fetch_quantity。", + "order.wave.fetchTaskProgress 的响应增加单模式相关字段:fetch_mode、max_fetch_quantity、limit_reached、stop_reason,用于描述散单抓取的上限与停止原因。" + ], + "type": "updated" + }, { "version": "2026.05.05-system-02", "date": "2026-05-05", diff --git a/methods/system.json b/methods/system.json index 5e8628c..cd6cb17 100644 --- a/methods/system.json +++ b/methods/system.json @@ -2581,6 +2581,89 @@ } ] }, + { + "method": "order.wave.singleFetchByIds", + "description": "按订单 ID 列表抓取到一个散单波次。仅处理当前仓库的待处理订单(step in [1,2,3]),排除已在波次中的订单(wave_id>0),不区分快递;成功抓取后批量写入订单操作日志;当无可抓取订单时返回 wave_id=0。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids / order_ids / orderIds", + "type": "array|string|number", + "required": true, + "source": "body", + "description": "订单ID列表,支持数组、逗号分隔字符串或单个ID;优先使用 ids 字段" + } + ], + "response": [ + { + "name": "ids", + "type": "array", + "required": true, + "description": "请求归一化后的 ids 列表(去重且为正整数)" + }, + { + "name": "wave_id", + "type": "number", + "required": true, + "description": "创建的波次 ID;若无可抓取订单返回 0" + }, + { + "name": "wave_no", + "type": "string", + "required": true, + "description": "创建的波次号;无可抓取时为空字符串" + }, + { + "name": "fetched_order_ids", + "type": "array", + "required": true, + "description": "实际被抓取并分配到波次的订单ID列表" + }, + { + "name": "fetched_order_count", + "type": "number", + "required": true, + "description": "实际被抓取的订单数量" + }, + { + "name": "excluded_existing_wave_order_ids", + "type": "array", + "required": false, + "description": "原始入参中已在其它波次中的订单ID(被排除)" + }, + { + "name": "skipped_order_ids", + "type": "array", + "required": false, + "description": "未被抓取的订单ID(包括已存在波次、状态不符或出库中等)" + }, + { + "name": "not_found_order_ids", + "type": "array", + "required": false, + "description": "入参中未在数据库中找到的订单ID" + } + ], + "errors": [ + { + "code": "400", + "description": "未识别到当前仓库上下文或 ids 参数不能为空或格式错误" + }, + { + "code": "500", + "description": "抓取失败或内部错误" + } + ] + }, { "method": "order.wave.singleOrderFetchList", "description": "按机器结构分组的散单候选列表。仅处理待处理订单(排除待审核),且排除已在波次中的订单。与 order.wave.groupOrderFetchList 不同:groupOrderFetchList 返回满足同组订单数量 >= same_order_quantity(或仓库配置 min_group_order_fetch_quantity)的团购命中分组;singleOrderFetchList 则排除这些团购命中分组,仅返回同组订单数量小于该阈值的散单候选分组(即 < same_order_quantity)。", @@ -3439,8 +3522,8 @@ ] }, { - "method": "order.wave.fetch", - "description": "提交波次抓取任务:该接口为异步任务提交接口,立即返回任务已受理的信息,后端异步执行实际抓取,不在接口同步返回抓取结果。客户端可通过任务 ID 或调用 order.wave.fetchTaskProgress 查询任务状态与进度。", + "method": "order.wave.groupFetch", + "description": "抓取团购接口(异步任务提交)", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -3491,6 +3574,172 @@ "required": true, "description": "手动抓取标记;值为 'wave_manual_fetch' 表示手动抓取" }, + { + "name": "fetch_mode", + "type": "string", + "required": false, + "description": "抓取模式,值为 'group'(团购)或 'single'(散单)" + }, + { + "name": "message", + "type": "string", + "required": false, + "description": "受理信息提示,通常为 '任务已提交,后端异步处理中' 或失败/错误说明" + } + ], + "errors": [ + { + "code": 400, + "message": "structure_list 必须是非空数组或结构项参数不合法" + }, + { + "code": 500, + "message": "任务提交失败或内部错误" + } + ] + }, + { + "method": "order.wave.singleFetch", + "description": "抓取散单接口(异步任务提交)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "structure_list", + "type": "array", + "required": true, + "source": "body", + "description": "结构请求数组;每项必须包含 item_detail_machine(由 buildMachineStructureToken 生成的结构标识)并包含必填字段 max_fetch_quantity(最大抓取上限,订单数,正整数);可选 quantity(未传入时使用仓库默认或全局默认)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID(后端生成的唯一标识,用于查询任务状态或结果)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "生效的仓库 ID" + }, + { + "name": "structure_count", + "type": "number", + "required": true, + "description": "本次入参的结构数量(structure_list 长度)" + }, + { + "name": "default_quantity", + "type": "number", + "required": true, + "description": "仓库默认抓取数量或全局默认值" + }, + { + "name": "auto_fetch_disabled_marker", + "type": "string", + "required": true, + "description": "手动抓取标记;值为 'wave_manual_fetch' 表示手动抓取" + }, + { + "name": "fetch_mode", + "type": "string", + "required": false, + "description": "抓取模式,值为 'group'(团购)或 'single'(散单)" + }, + { + "name": "max_fetch_quantity", + "type": "number", + "required": false, + "description": "提交时生效的最大抓取上限(订单数,正整数)" + }, + { + "name": "message", + "type": "string", + "required": false, + "description": "受理信息提示,通常为 '任务已提交,后端异步处理中' 或失败/错误说明" + } + ], + "errors": [ + { + "code": 400, + "message": "structure_list 必须是非空数组或结构项参数不合法;max_fetch_quantity 必填且为正整数" + }, + { + "code": 500, + "message": "任务提交失败或内部错误" + } + ] + }, + { + "method": "order.wave.fetch", + "description": "兼容别名(等同 groupFetch)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "structure_list", + "type": "array", + "required": true, + "source": "body", + "description": "结构请求数组;每项必须包含 item_detail_machine(由 buildMachineStructureToken 生成的结构标识),可选 quantity(未传入时使用仓库默认或全局默认)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID(后端生成的唯一标识,用于查询任务状态或结果)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "生效的仓库 ID" + }, + { + "name": "structure_count", + "type": "number", + "required": true, + "description": "本次入参的结构数量(structure_list 长度)" + }, + { + "name": "default_quantity", + "type": "number", + "required": true, + "description": "仓库默认抓取数量或全局默认值" + }, + { + "name": "auto_fetch_disabled_marker", + "type": "string", + "required": true, + "description": "手动抓取标记;值为 'wave_manual_fetch' 表示手动抓取" + }, + { + "name": "fetch_mode", + "type": "string", + "required": false, + "description": "抓取模式,值为 'group'(团购)或 'single'(散单)" + }, { "name": "message", "type": "string", @@ -3586,6 +3835,30 @@ "required": false, "description": "错误信息,仅当 status=failed 时返回" }, + { + "name": "fetch_mode", + "type": "string", + "required": false, + "description": "抓取模式,值为 'group'(团购)或 'single'(散单);single 模式时可能返回下列额外字段" + }, + { + "name": "max_fetch_quantity", + "type": "number", + "required": false, + "description": "当 fetch_mode=single 时返回的最大抓取上限(订单数,正整数)" + }, + { + "name": "limit_reached", + "type": "boolean", + "required": false, + "description": "当 fetch_mode=single 时指示是否已达到 max_fetch_quantity 限制" + }, + { + "name": "stop_reason", + "type": "string", + "required": false, + "description": "任务停止原因(如达到上限、人工停止或其他失败原因)" + }, { "name": "update_time", "type": "string", @@ -4893,14 +5166,46 @@ "type": "object", "description": "收件信息", "children": [ - { "name": "name", "type": "string", "description": "收件人姓名" }, - { "name": "mobile", "type": "string", "description": "手机号" }, - { "name": "tel", "type": "string", "description": "电话" }, - { "name": "province", "type": "string", "description": "省" }, - { "name": "city", "type": "string", "description": "市" }, - { "name": "area", "type": "string", "description": "区/县" }, - { "name": "town", "type": "string", "description": "镇/街道" }, - { "name": "detail_address", "type": "string", "description": "详细地址" } + { + "name": "name", + "type": "string", + "description": "收件人姓名" + }, + { + "name": "mobile", + "type": "string", + "description": "手机号" + }, + { + "name": "tel", + "type": "string", + "description": "电话" + }, + { + "name": "province", + "type": "string", + "description": "省" + }, + { + "name": "city", + "type": "string", + "description": "市" + }, + { + "name": "area", + "type": "string", + "description": "区/县" + }, + { + "name": "town", + "type": "string", + "description": "镇/街道" + }, + { + "name": "detail_address", + "type": "string", + "description": "详细地址" + } ] }, { @@ -4908,9 +5213,21 @@ "type": "object", "description": "渠道信息", "children": [ - { "name": "sys_platform_code", "type": "string", "description": "平台编码" }, - { "name": "sys_platform_name", "type": "string", "description": "平台名称" }, - { "name": "logistics_name", "type": "string", "description": "快递名称" } + { + "name": "sys_platform_code", + "type": "string", + "description": "平台编码" + }, + { + "name": "sys_platform_name", + "type": "string", + "description": "平台名称" + }, + { + "name": "logistics_name", + "type": "string", + "description": "快递名称" + } ] }, { @@ -4918,9 +5235,21 @@ "type": "object", "description": "订单状态简要", "children": [ - { "name": "order_status", "type": "string", "description": "订单状态" }, - { "name": "outbound_status", "type": "string", "description": "出库状态" }, - { "name": "print_status", "type": "string", "description": "打印状态" } + { + "name": "order_status", + "type": "string", + "description": "订单状态" + }, + { + "name": "outbound_status", + "type": "string", + "description": "出库状态" + }, + { + "name": "print_status", + "type": "string", + "description": "打印状态" + } ] }, { @@ -4928,9 +5257,21 @@ "type": "object", "description": "数量度量", "children": [ - { "name": "items_count", "type": "number", "description": "商品种类数" }, - { "name": "items_total", "type": "number", "description": "商品总件数" }, - { "name": "items_weight", "type": "number", "description": "重量" } + { + "name": "items_count", + "type": "number", + "description": "商品种类数" + }, + { + "name": "items_total", + "type": "number", + "description": "商品总件数" + }, + { + "name": "items_weight", + "type": "number", + "description": "重量" + } ] }, { @@ -4938,8 +5279,16 @@ "type": "object", "description": "时间字段", "children": [ - { "name": "create_at", "type": "string", "description": "创建时间" }, - { "name": "pay_time", "type": "string", "description": "支付时间" } + { + "name": "create_at", + "type": "string", + "description": "创建时间" + }, + { + "name": "pay_time", + "type": "string", + "description": "支付时间" + } ] } ] @@ -8579,6 +8928,24 @@ "type": "object", "required": true, "description": "收货单详情(含 details、images、pagination)" + }, + { + "name": "receiving.details", + "type": "array", + "required": false, + "description": "收货单明细列表,单条记录包含明细字段(见下文)" + }, + { + "name": "receiving.details.*.box_remainder", + "type": "number", + "required": false, + "description": "箱内剩余数量/零散数量(不满箱时的件数)" + }, + { + "name": "receiving.details.*.box_weight", + "type": "number", + "required": false, + "description": "实测箱重(单位与系统重量一致,如 kg)" } ], "errors": [ @@ -9237,8 +9604,49 @@ "description": "Bearer token" } ], - "params": [], - "response": [], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "收货单ID" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "description": "业务状态码,200 表示成功" + }, + { + "name": "message", + "type": "string", + "description": "返回信息" + }, + { + "name": "data", + "type": "object", + "description": "收货单详情对象,包含 details(明细数组)、images 及主表字段" + }, + { + "name": "data.details", + "type": "array", + "description": "收货单明细数组(每项为明细对象)" + }, + { + "name": "data.details.*.box_remainder", + "type": "number", + "required": false, + "description": "箱内剩余数量/零散数量(不满箱时的件数),默认 0" + }, + { + "name": "data.details.*.box_weight", + "type": "number", + "required": false, + "description": "实测箱重(单位与系统重量一致,如 kg),默认 0" + } + ], "errors": [] }, { @@ -9408,6 +9816,20 @@ "source": "body", "description": "箱长" }, + { + "name": "box_remainder", + "type": "number", + "required": false, + "source": "body", + "description": "箱内剩余数量/零散数量(不满箱时的件数)" + }, + { + "name": "box_weight", + "type": "number", + "required": false, + "source": "body", + "description": "实测箱重(单位与系统重量一致,如 kg)" + }, { "name": "weight", "type": "number", @@ -9453,6 +9875,18 @@ "required": false, "description": "系统商品 ID" }, + { + "name": "data.box_remainder", + "type": "number", + "required": false, + "description": "箱内剩余数量/零散数量(不满箱时的件数)" + }, + { + "name": "data.box_weight", + "type": "number", + "required": false, + "description": "实测箱重(单位与系统重量一致,如 kg)" + }, { "name": "data.updated_at", "type": "string", @@ -9507,6 +9941,9 @@ ], "params": [], "response": [], + "notes": [ + "完成收货时会发送通知:通知 payload 或 metadata 将在每条明细中携带 box_remainder(箱内剩余数量/零散件数,number)与 box_weight(实测箱重,number,单位同系统重量,例如 kg)。新增字段为可选,旧客户端可忽略。" + ], "errors": [] } ] @@ -10540,7 +10977,7 @@ "list": [ { "method": "store.createStore", - "description": "store.createStore 接口,subject_config 未传时默认写入 max_notice_webhook_count=5、default_express_code=STO、default_platform_code=TB、group_wave_prefix=B、min_group_order_fetch_quantity=13", + "description": "store.createStore 接口,subject_config 未传时默认写入 max_notice_webhook_count=5、default_express_code=STO、default_platform_code=TB、group_wave_prefix=B、min_group_order_fetch_quantity=13、auto_grouping_enabled=false(是否自动加团,默认 false(关闭))", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -10593,6 +11030,13 @@ "required": false, "source": "body.subject_config", "description": "最小团购订单抓取数量,默认 13" + }, + { + "name": "subject_config.auto_grouping_enabled", + "type": "boolean", + "required": false, + "source": "body.subject_config", + "description": "是否自动加团,默认 false(关闭)" } ], "response": [], @@ -10600,7 +11044,7 @@ }, { "method": "store.createWarehouse", - "description": "store.createWarehouse 接口,subject_config 未传时默认写入 max_notice_webhook_count=5、default_express_code=STO、default_platform_code=TB、group_wave_prefix=B、min_group_order_fetch_quantity=13", + "description": "store.createWarehouse 接口,subject_config 未传时默认写入 max_notice_webhook_count=5、default_express_code=STO、default_platform_code=TB、group_wave_prefix=B、min_group_order_fetch_quantity=13、auto_grouping_enabled=false(是否自动加团,默认 false(关闭))", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -10653,6 +11097,13 @@ "required": false, "source": "body.subject_config", "description": "最小团购订单抓取数量,默认 13" + }, + { + "name": "subject_config.auto_grouping_enabled", + "type": "boolean", + "required": false, + "source": "body.subject_config", + "description": "是否自动加团,默认 false(关闭)" } ], "response": [], @@ -11224,7 +11675,7 @@ "type": "object", "required": true, "source": "body", - "description": "策略配置对象;仅支持 receive_mode、auto_allocate_bin、allow_mix_batch、allow_temp_storage、storage_separation、print_recharge_price(面单充值元/单,支持 2 位小数)、max_daily_inbound、remark" + "description": "策略配置对象;仅支持 receive_mode、auto_allocate_bin、auto_allocate_express(是否自动分配快递)、auto_allocate_storage(是否自动分配储位)、allow_mix_batch、allow_temp_storage、storage_separation、print_recharge_price(面单充值元/单,支持 2 位小数)、max_daily_inbound、remark" } ], "response": [], @@ -12358,4 +12809,4 @@ } ] } -} +} \ No newline at end of file diff --git a/runtime/file-writer/qimen-logs/.consume-progress b/runtime/file-writer/qimen-logs/.consume-progress index 9f76f77..9616324 100644 --- a/runtime/file-writer/qimen-logs/.consume-progress +++ b/runtime/file-writer/qimen-logs/.consume-progress @@ -3,5 +3,5 @@ "offset": 18973, "processedCount": 7, "completedAt": "2026-04-27T13:30:41.800Z", - "updatedAt": "2026-05-05T17:38:47.603Z" + "updatedAt": "2026-05-06T09:53:04.963Z" } diff --git a/script/db-query-prod-config.js b/script/db-query-prod-config.js new file mode 100644 index 0000000..5fbc022 --- /dev/null +++ b/script/db-query-prod-config.js @@ -0,0 +1,13 @@ +module.exports = { + mysql: { + clients: { + wms: { + host: '112.124.21.102', + port: 3306, + user: 'wms', + password: 'P6j3YTHTpirepYWz', + database: 'wms', + }, + }, + }, +}; diff --git a/test/app/controller/system.setting.storeWarehouse.test.js b/test/app/controller/system.setting.storeWarehouse.test.js index 250c004..726b19d 100644 --- a/test/app/controller/system.setting.storeWarehouse.test.js +++ b/test/app/controller/system.setting.storeWarehouse.test.js @@ -192,6 +192,8 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { const nextPolicyConfig = { receive_mode: 'strict', auto_allocate_bin: 1, + auto_allocate_express: 1, + auto_allocate_storage: 1, storage_separation: 1, allow_mix_batch: 0, max_daily_inbound: 5000, @@ -211,6 +213,8 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { assert.equal(Number(saveRes.body?.data?.contract_id || 0), Number(candidate.id)); assert.equal(String(saveRes.body?.data?.policy_config?.receive_mode || ''), 'strict'); assert.equal(Number(saveRes.body?.data?.policy_config?.auto_allocate_bin || 0), 1); + assert.equal(Number(saveRes.body?.data?.policy_config?.auto_allocate_express || 0), 1, '保存后 auto_allocate_express 应为 1'); + assert.equal(Number(saveRes.body?.data?.policy_config?.auto_allocate_storage || 0), 1, '保存后 auto_allocate_storage 应为 1'); assert.equal(Number(saveRes.body?.data?.policy_config?.storage_separation || 0), 1, '保存后 storage_separation 应为 1'); assert.equal(Number(saveRes.body?.data?.policy_config?.need_order_approval || 0), 1, '保存后 need_order_approval 应为 1'); @@ -227,6 +231,8 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { Number(candidate.print_quantity_locked || 0) ); assert.equal(Number(getRes.body?.data?.policy_config?.max_daily_inbound || 0), 5000); + assert.equal(Number(getRes.body?.data?.policy_config?.auto_allocate_express || 0), 1, '读取后 auto_allocate_express 应为 1'); + assert.equal(Number(getRes.body?.data?.policy_config?.auto_allocate_storage || 0), 1, '读取后 auto_allocate_storage 应为 1'); assert.equal(Number(getRes.body?.data?.policy_config?.storage_separation || 0), 1, '读取后 storage_separation 应为 1'); assert.equal(Number(getRes.body?.data?.policy_config?.need_order_approval || 0), 1, '读取后 need_order_approval 应为 1'); } finally { diff --git a/test/app/controller/system.storage.receiving.test.js b/test/app/controller/system.storage.receiving.test.js index 13a1796..f127809 100644 --- a/test/app/controller/system.storage.receiving.test.js +++ b/test/app/controller/system.storage.receiving.test.js @@ -626,6 +626,10 @@ describe('test/app/controller/system.storage.receiving.test.js', () => { const detail = data.details[0]; assert.ok(detail.id, '明细应包含 id'); assert.ok(Array.isArray(detail.images), '明细应包含 images 数组'); + assert.ok(Object.prototype.hasOwnProperty.call(detail, 'box_remainder'), '明细应显式返回 box_remainder'); + assert.ok(Object.prototype.hasOwnProperty.call(detail, 'box_weight'), '明细应显式返回 box_weight'); + assert.equal(Number(detail.box_remainder), 0, 'box_remainder 为空时应兜底为 0'); + assert.equal(Number(detail.box_weight), 0, 'box_weight 为空时应兜底为 0'); } finally { if (createdId > 0) { await invokeSystemMethod('storage.receiving.batchCancelReceiving', { diff --git a/test/app/controller/system.storeWarehouse.test.js b/test/app/controller/system.storeWarehouse.test.js index 4ec4bc9..5979154 100644 --- a/test/app/controller/system.storeWarehouse.test.js +++ b/test/app/controller/system.storeWarehouse.test.js @@ -181,6 +181,18 @@ describe('test/app/controller/system.storeWarehouse.test.js', () => { assert.equal(storageSeparationField.type, 'flag'); assert.equal(storageSeparationField.default, 1); + const autoAllocateExpressField = res.body.data.find(item => item.key === 'auto_allocate_express'); + assert.ok(autoAllocateExpressField, '字段信息应包含 auto_allocate_express'); + assert.equal(autoAllocateExpressField.name, '是否自动分配快递'); + assert.equal(autoAllocateExpressField.type, 'flag'); + assert.equal(autoAllocateExpressField.default, 0); + + const autoAllocateStorageField = res.body.data.find(item => item.key === 'auto_allocate_storage'); + assert.ok(autoAllocateStorageField, '字段信息应包含 auto_allocate_storage'); + assert.equal(autoAllocateStorageField.name, '是否自动分配储位'); + assert.equal(autoAllocateStorageField.type, 'flag'); + assert.equal(autoAllocateStorageField.default, 0); + const receiveModeField = res.body.data.find(item => item.key === 'receive_mode'); assert.ok(receiveModeField, '字段信息应包含 receive_mode'); assert.equal(receiveModeField.type, 'enum'); diff --git a/test/app/model/store.test.js b/test/app/model/store.test.js new file mode 100644 index 0000000..3c116f1 --- /dev/null +++ b/test/app/model/store.test.js @@ -0,0 +1,75 @@ +'use strict'; + +const assert = require('node:assert/strict'); + +/** + * 构造 store 模型测试所需的最小 Sequelize 类型集合。 + * @return {Object} Sequelize 类型集合。 + */ +function createSequelizeTypes() { + const makeType = sql => ({ + toSql() { + return sql; + }, + }); + + return { + BIGINT: { + UNSIGNED: makeType('BIGINT UNSIGNED'), + }, + STRING: length => makeType(`VARCHAR(${length})`), + DATE: makeType('DATETIME'), + TINYINT: length => makeType(`TINYINT(${length})`), + JSON: makeType('JSON'), + literal(value) { + return value; + }, + }; +} + +/** + * 构造加载 store 模型所需的最小应用对象。 + * @return {Object} 应用对象。 + */ +function createApp() { + return { + Sequelize: createSequelizeTypes(), + model: { + define(name, attributes, options) { + return { + name, + rawAttributes: attributes, + options, + prototype: {}, + belongsTo() {}, + hasMany() {}, + }; + }, + }, + }; +} + +describe('test/app/model/store.test.js', () => { + it('should keep auto_grouping_enabled disabled by default in normalized subject config', () => { + const Store = require('../../../app/model/store')(createApp()); + + const fromNull = Store.normalizeSubjectConfig(null); + const fromEmptyObject = Store.normalizeSubjectConfig({}); + + assert.equal(Store.DEFAULT_SUBJECT_CONFIG.auto_grouping_enabled, false); + assert.equal(fromNull.auto_grouping_enabled, false); + assert.equal(fromEmptyObject.auto_grouping_enabled, false); + }); + + it('should normalize auto_grouping_enabled to true when explicitly enabled', () => { + const Store = require('../../../app/model/store')(createApp()); + const truthyInputs = [ true, 1, '1', 'true' ]; + + truthyInputs.forEach(input => { + const normalized = Store.normalizeSubjectConfig({ + auto_grouping_enabled: input, + }); + assert.equal(normalized.auto_grouping_enabled, true); + }); + }); +}); diff --git a/test/app/service/systemMethods/order/wave.fetch.test.js b/test/app/service/systemMethods/order/wave.fetch.test.js index 0c40601..147a3c2 100644 --- a/test/app/service/systemMethods/order/wave.fetch.test.js +++ b/test/app/service/systemMethods/order/wave.fetch.test.js @@ -226,7 +226,7 @@ describe('test/app/service/systemMethods/order/wave.fetch.test.js', () => { async query(sql, options = {}) { sqlCalls.push({ sql, options }); if (sql.includes('INSERT INTO wms_wave_batch')) { - return [ { insertId: 900001 }, { insertId: 900001 } ]; + return [{ insertId: 900001 }, { insertId: 900001 }]; } if (sql.includes('SELECT wave_no')) { @@ -234,14 +234,14 @@ describe('test/app/service/systemMethods/order/wave.fetch.test.js', () => { } if (sql.includes('UPDATE wms_wave_batch')) { - return [ { affectedRows: 1 } ]; + return [{ affectedRows: 1 }]; } if (sql.includes('DELETE FROM wms_wave_batch')) { - return [ { affectedRows: 1 } ]; + return [{ affectedRows: 1 }]; } - return [ [] ]; + return [[]]; }, }, }; @@ -352,11 +352,11 @@ describe('test/app/service/systemMethods/order/wave.fetch.test.js', () => { async query(sql, options = {}) { sqlCalls.push({ sql, options }); if (sql.includes('INSERT INTO wms_wave_batch')) { - return [ {}, {} ]; + return [{}, {}]; } if (sql.includes('SELECT LAST_INSERT_ID() AS insertId')) { - return [ [ { insertId: 900002 } ], {} ]; + return [[{ insertId: 900002 }], {}]; } if (sql.includes('SELECT wave_no')) { @@ -364,14 +364,14 @@ describe('test/app/service/systemMethods/order/wave.fetch.test.js', () => { } if (sql.includes('UPDATE wms_wave_batch')) { - return [ { affectedRows: 1 } ]; + return [{ affectedRows: 1 }]; } if (sql.includes('DELETE FROM wms_wave_batch')) { - return [ { affectedRows: 1 } ]; + return [{ affectedRows: 1 }]; } - return [ [] ]; + return [[]]; }, }, }; diff --git a/test/app/service/systemMethods/order/wave.singleFetchByIds.test.js b/test/app/service/systemMethods/order/wave.singleFetchByIds.test.js new file mode 100644 index 0000000..c03a2a5 --- /dev/null +++ b/test/app/service/systemMethods/order/wave.singleFetchByIds.test.js @@ -0,0 +1,250 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { Op } = require('sequelize'); + +const WaveService = require('../../../../../app/service/systemMethods/order/wave'); + +/** + * 创建 singleFetchByIds 轻量测试上下文。 + * + * @param {Object} options 初始化参数。 + * @param {Array} options.orders 订单数据。 + * @param {number} [options.storeId=100000] 仓库ID。 + * @return {{ service: WaveService, state: Object }} 测试上下文。 + */ +function createHarness({ orders = [], storeId = 100000 } = {}) { + const orderStore = orders.map(item => ({ ...item })); + const state = { + committed: false, + rolledBack: false, + createWaveCalls: [], + orderLogItems: [], + }; + + const transaction = { + LOCK: { + UPDATE: 'UPDATE', + }, + async commit() { + state.committed = true; + }, + async rollback() { + state.rolledBack = true; + }, + }; + + const ctx = { + app: { + config: {}, + Sequelize: { + literal(value) { + return value; + }, + }, + }, + user: { + store_id: storeId, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + model: { + async transaction() { + return transaction; + }, + async query() { + return [[], { affectedRows: 0 }]; + }, + }, + }; + + const service = new WaveService(ctx); + service.getGroupWavePrefix = async () => 'B'; + service.getMinGroupOrderFetchQuantity = async () => 3; + service.createWaveBatchReady = async params => { + state.createWaveCalls.push({ ...params }); + const wavePrefix = String(params && params.wavePrefix || 'X'); + return { + waveId: 9001, + waveNo: `${wavePrefix}202605060001`, + }; + }; + service.batchCreateOrderOperationLogs = async logItems => { + state.orderLogItems = Array.isArray(logItems) ? logItems : []; + return state.orderLogItems.length; + }; + + service.getOrderModel = async () => ({ + async findAll(options = {}) { + const where = options.where || {}; + const idIn = where.id && where.id[Op.in]; + const filterIds = Array.isArray(idIn) ? idIn : []; + const waveEq = Number(where.wave_id || 0); + const whereOr = Array.isArray(where[Op.or]) ? where[Op.or] : []; + + const matchGroupCandidates = row => { + if (waveEq !== 0 || whereOr.length === 0) { + return false; + } + + return whereOr.some(clause => { + if (!clause || typeof clause !== 'object') { + return false; + } + + if (clause.items_hash && clause.items_hash[Op.in]) { + return clause.items_hash[Op.in].includes(String(row.items_hash || '')); + } + + if (clause.items && clause.items[Op.in]) { + return clause.items[Op.in].includes(String(row.items || '')); + } + + return false; + }); + }; + + if (waveEq > 0) { + return orderStore + .filter(row => filterIds.includes(Number(row.id || 0))) + .filter(row => Number(row.wave_id || 0) === waveEq) + .map(row => ({ id: row.id })); + } + + if (whereOr.length > 0) { + return orderStore + .filter(row => Number(row.wave_id || 0) === 0) + .filter(row => [ 1, 2, 3 ].includes(Number(row.step || 0))) + .filter(row => String(row.status || '') !== 'cancel') + .filter(row => String(row.outbound_status || '') !== 'padding') + .filter(row => matchGroupCandidates(row)) + .map(row => ({ + id: row.id, + items_hash: row.items_hash, + items: row.items, + logistics_name: row.logistics_name, + })); + } + + return orderStore + .filter(row => filterIds.includes(Number(row.id || 0))) + .map(row => ({ + id: row.id, + wave_id: row.wave_id, + wave_no: row.wave_no, + step: row.step, + status: row.status, + outbound_status: row.outbound_status, + items_hash: row.items_hash, + items: row.items, + logistics_name: row.logistics_name, + })); + }, + + async update(values = {}, options = {}) { + const where = options.where || {}; + const idIn = where.id && where.id[Op.in]; + const ids = Array.isArray(idIn) ? idIn : []; + const waveIdEq = Number(where.wave_id || 0); + let affected = 0; + + for (const row of orderStore) { + if (!ids.includes(Number(row.id || 0))) { + continue; + } + + if (Number(row.wave_id || 0) !== waveIdEq) { + continue; + } + + row.wave_id = Number(values.wave_id || 0); + row.wave_no = String(values.wave_no || ''); + affected += 1; + } + + return [ affected ]; + }, + }); + + return { + service, + state, + }; +} + +describe('test/app/service/systemMethods/order/wave.singleFetchByIds.test.js', () => { + it('should exclude orders already in wave and fetch remaining orders into one single wave', async () => { + const { service, state } = createHarness({ + orders: [ + { id: 1, wave_id: 0, wave_no: '', step: 1, status: 'new', outbound_status: 'none' }, + { id: 2, wave_id: 88, wave_no: 'W88', step: 1, status: 'new', outbound_status: 'none' }, + { id: 3, wave_id: 0, wave_no: '', step: 2, status: 'cancel', outbound_status: 'none' }, + { id: 4, wave_id: 0, wave_no: '', step: 9, status: 'new', outbound_status: 'none' }, + ], + }); + + const result = await service.singleFetchByIds({ ids: [ 1, 2, 3, 4, 5 ] }); + + assert.equal(result.flag, 'success'); + assert.equal(result.wave_id, 9001); + assert.equal(result.wave_no, 'S202605060001'); + assert.deepEqual(result.fetched_order_ids, [ 1 ]); + assert.equal(result.fetched_order_count, 1); + assert.deepEqual(result.excluded_existing_wave_order_ids, [ 2 ]); + assert.deepEqual(result.not_found_order_ids, [ 5 ]); + + assert.equal(state.createWaveCalls.length, 1); + assert.equal(state.createWaveCalls[0].wavePrefix, 'S'); + assert.equal(state.createWaveCalls[0].distinguishExpress, false); + assert.equal(state.createWaveCalls[0].logisticsName, ''); + assert.equal(state.orderLogItems.length, 1); + assert.equal(state.orderLogItems[0].operationCode, 'ORDER_WAVE_ASSIGN'); + assert.equal(state.committed, true); + assert.equal(state.rolledBack, false); + }); + + it('should return empty fetch result when no order can be fetched', async () => { + const { service, state } = createHarness({ + orders: [ + { id: 10, wave_id: 77, wave_no: 'W77', step: 1, status: 'new', outbound_status: 'none' }, + ], + }); + + const result = await service.singleFetchByIds({ ids: [ 10 ] }); + + assert.equal(result.flag, 'success'); + assert.equal(result.wave_id, 0); + assert.equal(result.fetched_order_count, 0); + assert.deepEqual(result.excluded_existing_wave_order_ids, [ 10 ]); + assert.equal(state.createWaveCalls.length, 0); + assert.equal(state.orderLogItems.length, 0); + assert.equal(state.committed, true); + assert.equal(state.rolledBack, false); + }); + + it('should exclude group-candidate orders from singleFetchByIds', async () => { + const { service, state } = createHarness({ + orders: [ + { id: 101, wave_id: 0, wave_no: '', step: 1, status: 'new', outbound_status: 'none', items_hash: 'H-A', items: 'I-A', logistics_name: 'ZTO' }, + { id: 102, wave_id: 0, wave_no: '', step: 1, status: 'new', outbound_status: 'none', items_hash: 'H-A', items: 'I-A', logistics_name: 'YTO' }, + { id: 103, wave_id: 0, wave_no: '', step: 1, status: 'new', outbound_status: 'none', items_hash: 'H-A', items: 'I-A', logistics_name: 'STO' }, + { id: 104, wave_id: 0, wave_no: '', step: 1, status: 'new', outbound_status: 'none', items_hash: 'H-B', items: 'I-B', logistics_name: 'ZTO' }, + ], + }); + + const result = await service.singleFetchByIds({ ids: [ 101, 104 ] }); + + assert.equal(result.flag, 'success'); + assert.equal(result.wave_id, 9001); + assert.deepEqual(result.fetched_order_ids, [ 104 ]); + assert.deepEqual(result.excluded_group_order_ids, [ 101 ]); + assert.deepEqual(result.skipped_order_ids, [ 101 ]); + assert.equal(state.createWaveCalls.length, 1); + assert.equal(state.createWaveCalls[0].wavePrefix, 'S'); + assert.equal(state.committed, true); + assert.equal(state.rolledBack, false); + }); +}); diff --git a/test/app/service/systems/delivery_order.asyncProcessOrderCreated.test.js b/test/app/service/systems/delivery_order.asyncProcessOrderCreated.test.js new file mode 100644 index 0000000..024f18a --- /dev/null +++ b/test/app/service/systems/delivery_order.asyncProcessOrderCreated.test.js @@ -0,0 +1,232 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const DeliveryOrderService = require('../../../../app/service/systems/delivery_order'); + +/** + * 创建异步流程测试桩。 + * + * @return {{ ctx: Object, service: DeliveryOrderService, calls: Object }} 测试上下文。 + */ +function createHarness() { + const calls = { + sequence: [], + warns: [], + }; + + const ctx = { + app: { + config: {}, + }, + user: { + store_id: 100000, + warehouse_id: 100000, + employees_name: '测试员', + }, + logger: { + info() {}, + error() {}, + warn(message) { + calls.warns.push(String(message || '')); + }, + }, + service: { + systemMethods: { + order: { + pendingOrder: { + async allocateExpressCode() { + calls.sequence.push('allocateExpress'); + return { + code: 1, + message: 'ok', + }; + }, + }, + wave: { + async getMinGroupOrderFetchQuantity() { + calls.sequence.push('wave.getMinGroupOrderFetchQuantity'); + return 2; + }, + }, + }, + }, + systems: { + orderStorageAllocation: { + async allocateStorage() { + calls.sequence.push('allocateStorage'); + return { + code: 200, + message: 'ok', + }; + }, + }, + }, + }, + }; + + const service = new DeliveryOrderService(ctx); + + service.withPatchedCtxUser = async (_patchUser, callback) => { + return await callback(); + }; + + return { + ctx, + service, + calls, + }; +} + +describe('test/app/service/systems/delivery_order.asyncProcessOrderCreated.test.js', () => { + it('should execute async flow in order: express -> storage -> autoGrouping', async () => { + const { service, calls } = createHarness(); + + service.buildAsyncProcessContext = async () => ({ + orderId: 101, + warehouseId: 100000, + storeId: 200000, + order: { + id: 101, + store_id: 200000, + warehouse_id: 100000, + logistics_code: 'STO', + logistics_name: '申通', + }, + orderItemRows: [], + }); + service.getStoreWarehousePolicyConfig = async () => ({ + auto_allocate_express: 1, + auto_allocate_storage: 1, + }); + service.buildExpressAllocateRequest = () => ({ orders: [{ order_id: 101 }] }); + service.buildStorageAllocateRequest = () => ({ order_ids: [ 101 ], allow_storage_location: true }); + service.runAutoGrouping = async () => { + calls.sequence.push('autoGrouping'); + }; + + await service.asyncProcessOrderCreated(101, { + warehouseId: 100000, + storeId: 200000, + }, 'API'); + + assert.deepEqual(calls.sequence, [ 'allocateExpress', 'allocateStorage', 'autoGrouping' ]); + }); + + it('should continue next steps when one step fails', async () => { + const { service, calls, ctx } = createHarness(); + + service.buildAsyncProcessContext = async () => ({ + orderId: 102, + warehouseId: 100000, + storeId: 200000, + order: { + id: 102, + store_id: 200000, + warehouse_id: 100000, + }, + orderItemRows: [], + }); + service.getStoreWarehousePolicyConfig = async () => ({ + auto_allocate_express: 1, + auto_allocate_storage: 1, + }); + + ctx.service.systemMethods.order.pendingOrder.allocateExpressCode = async () => { + calls.sequence.push('allocateExpress'); + throw new Error('分配快递异常'); + }; + ctx.service.systems.orderStorageAllocation.allocateStorage = async () => { + calls.sequence.push('allocateStorage'); + return { code: 200 }; + }; + service.runAutoGrouping = async () => { + calls.sequence.push('autoGrouping'); + }; + + await service.asyncProcessOrderCreated(102, { + warehouseId: 100000, + storeId: 200000, + }, 'API'); + + assert.deepEqual(calls.sequence, [ 'allocateExpress', 'allocateStorage', 'autoGrouping' ]); + assert.equal(calls.warns.length >= 1, true); + }); + + it('should skip auto grouping when switch is disabled', async () => { + const { service } = createHarness(); + let triggered = false; + + service.getStoreSubjectConfig = async () => ({ + auto_grouping_enabled: false, + max_wave_quantity: 10, + }); + service.buildAutoGroupingStructure = () => ({ + itemPartType: 'items_hash', + itemPart: 'hash_1', + logisticsName: '申通', + itemSnapshotKey: 'snapshot', + itemDetailMachine: 'token', + }); + service.findAutoGroupingWaveId = async () => { + triggered = true; + return 0; + }; + + await service.runAutoGrouping({ + orderId: 103, + warehouseId: 100000, + storeId: 200000, + order: {}, + orderItemRows: [], + }); + + assert.equal(triggered, false); + }); + + it('should trigger auto grouping chain when enabled and conditions matched', async () => { + const { service } = createHarness(); + const called = []; + + service.getStoreSubjectConfig = async () => ({ + auto_grouping_enabled: true, + max_wave_quantity: 2, + }); + service.buildAutoGroupingStructure = () => ({ + itemPartType: 'items_hash', + itemPart: 'hash_2', + logisticsName: '申通', + itemSnapshotKey: 'snapshot_2', + itemDetailMachine: 'token_2', + }); + service.findAutoGroupingWaveId = async () => 0; + service.countCandidateGroupOrders = async () => 2; + service.createGroupingWave = async () => { + called.push('createGroupingWave'); + return { + wave_ids: [ 9001 ], + }; + }; + service.markWaveAutoGrouping = async (_context, waveIds) => { + called.push(`markWaveAutoGrouping:${waveIds.join(',')}`); + }; + service.finishAutoGroupingIfNeeded = async (_context, waveId, maxWaveQuantity) => { + called.push(`finishAutoGroupingIfNeeded:${waveId}:${maxWaveQuantity}`); + }; + + await service.runAutoGrouping({ + orderId: 104, + warehouseId: 100000, + storeId: 200000, + order: { + id: 104, + }, + orderItemRows: [], + }); + + assert.deepEqual(called, [ + 'createGroupingWave', + 'markWaveAutoGrouping:9001', + 'finishAutoGroupingIfNeeded:9001:2', + ]); + }); +}); diff --git a/test/app/service/systems/setting/warehouse.test.js b/test/app/service/systems/setting/warehouse.test.js new file mode 100644 index 0000000..346ab33 --- /dev/null +++ b/test/app/service/systems/setting/warehouse.test.js @@ -0,0 +1,104 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const SettingWarehouseService = require('../../../../../app/service/systems/setting/warehouse'); + +function createHarness(options = {}) { + const calls = { + findByPkWarehouseIds: [], + updatePayload: null, + cacheDeletes: [], + }; + + const initialSubjectConfig = options.initialSubjectConfig || { + max_wave_quantity: 500, + }; + + const storeRecord = { + id: Number(options.storeId || 100000), + subject_config: { + ...initialSubjectConfig, + }, + async update(payload) { + calls.updatePayload = { + ...payload, + }; + this.subject_config = { + ...(payload.subject_config || {}), + }; + return this; + }, + }; + + const ctx = { + user: { + store_id: Number(options.storeId || 100000), + }, + app: { + async delCacheAsync(key) { + calls.cacheDeletes.push(key); + }, + }, + model: { + Store: { + async findByPk(warehouseId) { + calls.findByPkWarehouseIds.push(Number(warehouseId)); + return storeRecord; + }, + normalizeSubjectConfig(config) { + return { + ...config, + }; + }, + }, + }, + }; + + return { + ctx, + calls, + storeRecord, + }; +} + +describe('test/app/service/systems/setting/warehouse.test.js', () => { + it('should always clear cache for current ctx warehouse when saving settings', async () => { + const { ctx, calls } = createHarness({ + storeId: 100000, + }); + const service = new SettingWarehouseService(ctx); + + const result = await service.saveSettings({ + subject_config: { + max_wave_quantity: 600, + }, + cache_warehouse_id: 999999, + cacheWarehouseId: 888888, + }); + + assert.deepEqual(calls.findByPkWarehouseIds, [ 100000 ]); + assert.equal(result.warehouse_id, 100000); + assert.equal(result.cache_cleared_warehouse_id, 100000); + assert.equal(calls.updatePayload.subject_config.max_wave_quantity, 600); + assert.deepEqual(calls.cacheDeletes, [ + 'delivery_order:store:100000:subject_config', + 'warehouse:100000store:100000:info', + ]); + }); + + it('should keep validation behavior for invalid subject_config', async () => { + const { ctx } = createHarness(); + const service = new SettingWarehouseService(ctx); + + await assert.rejects( + service.saveSettings({ + subject_config: null, + }), + error => { + assert.equal(error.code, 400); + assert.match(error.message, /subject_config 参数不能为空且必须是对象/); + return true; + } + ); + }); +}); diff --git a/test/app/service/systems/storage.receiving.complete.notice.test.js b/test/app/service/systems/storage.receiving.complete.notice.test.js new file mode 100644 index 0000000..7f59ce5 --- /dev/null +++ b/test/app/service/systems/storage.receiving.complete.notice.test.js @@ -0,0 +1,112 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const ReceivingService = require('../../../../app/service/systems/storage/receiving'); + +describe('test/app/service/systems/storage.receiving.complete.notice.test.js', () => { + it('should include box_remainder and box_weight in completeReceiving notice payload', async () => { + const noticeCalls = []; + const transaction = { + LOCK: { + UPDATE: 'UPDATE', + }, + finished: false, + async commit() { + this.finished = 'commit'; + }, + async rollback() { + this.finished = 'rollback'; + }, + }; + + const ctx = { + app: { + Sequelize: { + Op: { + in: 'in', + }, + }, + }, + user: { + store_id: 100000, + employees_id: 2001, + employees_name: '测试员A', + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + service: { + systems: { + operationLog: { + async createOperationLog() { + return null; + }, + }, + }, + }, + model: { + async transaction() { + return transaction; + }, + ReceivingDetail: {}, + StockWarehouse: {}, + Receiving: { + async findOne() { + return { + id: 123, + warehouse_id: 100000, + store_id: 1000000, + store_name: '测试货主', + receiving_number: 'RCV202605060001', + status: 'receiving', + remark: '', + details: [ + { + id: 501, + system_product_id: 10001, + product_name: '测试商品A', + barcode: 'SKU-001', + actual_quantity: 8, + weight: 12, + box_quantity: 2, + pallet_quantity: 1, + box_remainder: 1, + box_weight: 24.5, + system_product: { + id: 10001, + is_batch_mgmt: 'N', + is_shelf_life_mgmt: 'N', + }, + }, + ], + }; + }, + async update() { + return [ 1 ]; + }, + }, + FileReference: { + async findAll() { + return []; + }, + }, + }, + }; + + const service = new ReceivingService(ctx); + service.sendCompletionNotice = async payload => { + noticeCalls.push(payload); + return { success: true }; + }; + service._syncProductDataFromReceiving = async () => {}; + + const result = await service.completeReceiving({ id: 123 }); + + assert.equal(result.success, true); + assert.equal(noticeCalls.length, 1); + assert.equal(Number(noticeCalls[0].receiving.details[0].box_remainder), 1); + assert.equal(Number(noticeCalls[0].receiving.details[0].box_weight), 24.5); + }); +}); diff --git a/test/app/service/systems/storage.receiving.detailChange.test.js b/test/app/service/systems/storage.receiving.detailChange.test.js index 1f89bdf..86b34ea 100644 --- a/test/app/service/systems/storage.receiving.detailChange.test.js +++ b/test/app/service/systems/storage.receiving.detailChange.test.js @@ -25,6 +25,7 @@ function createServiceHarness() { const calls = { detailUpdate: 0, updateReceivingStats: 0, + lastUpdateData: null, }; const model = { @@ -37,11 +38,14 @@ function createServiceHarness() { actual_quantity: 1, barcode: '', system_product_id: null, + box_remainder: 0, + box_weight: '0.00', updated_at: new Date('2026-04-01T00:00:00Z'), }; }, - async update() { + async update(updateData) { calls.detailUpdate += 1; + calls.lastUpdateData = updateData; }, }, Receiving: { @@ -145,4 +149,26 @@ describe('test/app/service/systems/storage.receiving.detailChange.test.js', () = assert.equal(calls.updateReceivingStats, 1); assert.equal(calls.operationLog, 1); }); + + it('should persist and return box_remainder and box_weight when provided', async () => { + const { service, calls } = createServiceHarness(); + service.updateReceivingStats = async () => { + calls.updateReceivingStats += 1; + }; + + const result = await service.detailChange({ + id: 501, + receiving_id: 123, + actual_quantity: 3, + box_remainder: 2, + box_weight: 12.5, + }); + + assert.equal(result.code, 200); + assert.equal(calls.detailUpdate, 1); + assert.equal(calls.lastUpdateData.box_remainder, 2); + assert.equal(calls.lastUpdateData.box_weight, 12.5); + assert.equal(result.data.box_remainder, 2); + assert.equal(result.data.box_weight, 12.5); + }); }); diff --git a/test/app/service/systems/storage.receiving.getDetail.test.js b/test/app/service/systems/storage.receiving.getDetail.test.js new file mode 100644 index 0000000..a260c25 --- /dev/null +++ b/test/app/service/systems/storage.receiving.getDetail.test.js @@ -0,0 +1,119 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const ReceivingService = require('../../../../app/service/systems/storage/receiving'); + +describe('test/app/service/systems/storage.receiving.getDetail.test.js', () => { + it('should include box_remainder and box_weight in receiving detail items', async () => { + const receivingRow = { + id: 123, + warehouse_id: 100000, + receiving_number: 'RCV202605060001', + dataValues: {}, + }; + + const detailRows = [ + { + id: 501, + receiving_id: 123, + product_name: '测试商品A', + box_remainder: 2, + box_weight: 18.5, + toJSON() { + return { + id: this.id, + receiving_id: this.receiving_id, + product_name: this.product_name, + box_remainder: this.box_remainder, + box_weight: this.box_weight, + }; + }, + }, + { + id: 502, + receiving_id: 123, + product_name: '测试商品B', + box_remainder: null, + box_weight: null, + toJSON() { + return { + id: this.id, + receiving_id: this.receiving_id, + product_name: this.product_name, + box_remainder: this.box_remainder, + box_weight: this.box_weight, + }; + }, + }, + ]; + + const model = { + Receiving: { + async findOne() { + return receivingRow; + }, + }, + ReceivingDetail: { + async findAll() { + return detailRows; + }, + async count() { + return detailRows.length; + }, + }, + FileReference: { + async findAll({ where }) { + if (where.business_type === 'receivingItem') { + return [ + { + business_id: 501, + file_id: 9001, + file: { + file_url: 'https://example.com/item-501.png', + }, + }, + ]; + } + return []; + }, + }, + File: {}, + }; + + const ctx = { + user: { + store_id: 100000, + }, + app: { + Sequelize: { + Op: { + in: 'in', + }, + }, + model, + }, + model, + }; + + const service = new ReceivingService(ctx); + const result = await service.getReceivingDetail({ + id: 123, + pagination: { + page: 1, + pageSize: 10, + }, + }); + + assert.equal(result.code, 200); + const receivingPayload = result.data.receiving; + const details = Array.isArray(receivingPayload.details) + ? receivingPayload.details + : receivingPayload.dataValues.details; + + assert.ok(Array.isArray(details)); + assert.equal(Number(details[0].box_remainder), 2); + assert.equal(Number(details[0].box_weight), 18.5); + assert.equal(Number(details[1].box_remainder), 0); + assert.equal(Number(details[1].box_weight), 0); + }); +});