diff --git a/app/service/systemMethods/returnUnpack.js b/app/service/systemMethods/returnUnpack.js index b17fc14..c769e00 100644 --- a/app/service/systemMethods/returnUnpack.js +++ b/app/service/systemMethods/returnUnpack.js @@ -80,6 +80,23 @@ class ReturnUnpackMethodService extends MainService { ); } + /** + * 配送订单批量转退回拆包单。 + * 新方法需鉴权 + 需登录 + 记录日志,不在任何免检清单内。 + * + * @param {Object} data 请求体。 + * @param {number|Array} data.ids 订单表主键ID(单个数值或数组,去重后上限 200)。 + * @return {Promise} 统一 success 包装,data 含 + * total/success_count/skipped_count/failed_count/success/skipped/failed。 + */ + async transferByOrders(data = {}) { + const { ids } = data; + return this._call( + () => this.service.systems.returnUnpack.transferByOrders({ ids }), + '配送订单批量转退回拆包单失败' + ); + } + /** * 录明细(增)。 * diff --git a/app/service/systems/return_unpack.js b/app/service/systems/return_unpack.js index 4523ff5..242f509 100644 --- a/app/service/systems/return_unpack.js +++ b/app/service/systems/return_unpack.js @@ -365,6 +365,533 @@ class ReturnUnpackService extends Service { }; } + /** + * 配送订单批量转退回拆包单。 + * 批量入参订单主键 ID(wms_order_delivery*.id):过滤非正整数 + 去重,单次上限 200; + * 逐单处理,单条失败不阻断主流程。仅「库内拦截」订单(intercept_status=intercepted_at_warehouse, + * 兼容历史值 intercepted)可转换,其余订单(未拦截/其它拦截状态)、已存在有效拆包单的订单、 + * 无运单号/无明细的订单均静默跳过,不报错。 + * 每单新建一张拆包单:waybill_code 取订单主运单号(无运单时回退发货单号), + * 明细按订单原本明细 1:1 复制(product_status 固定 normal),创建后回填主表汇总。 + * + * @param {Object} params 批量转换参数。 + * @param {Array|number} params.ids 订单表主键ID(单个数值或数组)。 + * @return {Promise} { total, success_count, skipped_count, failed_count, success[], skipped[], failed[] }, + * 成功项含 order_id/unpack_id/unpack_no/waybill_code/detail_count/total_quantity, + * 跳过/失败项含 order_id/reason。 + */ + async transferByOrders({ ids }) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + // 入参归一化:单个数值转数组,过滤非正整数 + 去重 + const rawIds = Array.isArray(ids) ? ids : [ ids ]; + const orderIds = [ ...new Set( + rawIds.map(id => Number(id)).filter(id => Number.isInteger(id) && id > 0) + ) ]; + + if (orderIds.length === 0) { + throw this.createBusinessError('ids 不能为空', 400); + } + if (orderIds.length > 200) { + throw this.createBusinessError('单次最多批量转换 200 个订单', 400); + } + + // 仓库隔离:由服务端从当前上下文自动注入,禁止前端传入 + const warehouseId = Number(ctx.user && ctx.user.store_id || 0); + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('缺少仓库上下文', 400); + } + + // 操作人上下文(与 create 完全一致) + const unpackerId = Number(ctx.user && ctx.user.employees_id || 0); + const unpackerName = String( + (ctx.user && ctx.user.employees_name) || (ctx.user && ctx.user.real_name) || '' + ).trim(); + if (!Number.isFinite(unpackerId) || unpackerId <= 0) { + throw this.createBusinessError('缺少拆包人员工号上下文', 400); + } + + // 1. 批量载入订单主记录(序列表定位车道 + 分表批量查询 + 基表兜底) + const orderMap = await this._loadOrdersForTransferByOrders(orderIds, warehouseId); + + // 2. 批量载入订单原本明细(items JSON 优先,为空回退明细分表) + const itemsMap = await this._loadOrderItemsForTransferByOrders(orderMap, warehouseId); + + // 3. 批量载入订单主运单(用于回填拆包单运单号/原运单ID) + const expressMap = await this._resolveOrderExpressForTransferByOrders(orderIds, warehouseId); + + // 4. 已存在有效拆包单(同订单 或 同运单号)→ 静默跳过 + const existingOrderIdSet = new Set(); + const existingWaybillSet = new Set(); + try { + const waybillCodes = [ ...new Set( + [ + ...[ ...expressMap.values() ] + .map(row => String(row && row.waybill_code || '').trim()), + // 无运单的订单以发货单号作为拆包单运单号,查重时一并纳入 + ...orderIds.map(orderId => { + const orderEntry = orderMap.get(orderId); + return String(orderEntry && orderEntry.order && orderEntry.order.delivery_order_code || '').trim(); + }), + ].filter(Boolean) + ) ]; + const orConditions = [{ order_id: { [Op.in]: orderIds } }]; + if (waybillCodes.length > 0) { + orConditions.push({ waybill_code: { [Op.in]: waybillCodes } }); + } + const existingRows = await ctx.model.ReturnUnpack.findAll({ + where: { + warehouse_id: warehouseId, + status: { [Op.ne]: 'cancelled' }, + [Op.or]: orConditions, + }, + attributes: [ 'id', 'order_id', 'waybill_code' ], + raw: true, + }); + for (const row of existingRows) { + const existingOrderId = Number(row.order_id || 0); + if (existingOrderId > 0) { + existingOrderIdSet.add(existingOrderId); + } + const existingWaybillCode = String(row.waybill_code || '').trim(); + if (existingWaybillCode) { + existingWaybillSet.add(existingWaybillCode); + } + } + } catch (err) { + ctx.logger.warn(`[returnUnpack.transferByOrders] 查询已有拆包单失败: ${err.message}`); + throw this.createBusinessError('查询已有拆包单失败,请稍后重试', 500); + } + + /** @type {Array} 成功项列表 */ + const success = []; + /** @type {Array} 静默跳过项列表 */ + const skipped = []; + /** @type {Array} 失败项列表 */ + const failed = []; + + const now = new Date(); + const unpackDate = app.formatDate(now, 'YYYY-MM-DD'); + + for (const orderId of orderIds) { + const entry = orderMap.get(orderId) || null; + const order = entry ? entry.order || {} : null; + + // 静默跳过:订单不存在/不属于当前仓库 + if (!order) { + skipped.push({ order_id: orderId, reason: '订单不存在或不属于当前仓库' }); + continue; + } + + // 静默跳过:仅允许库内拦截订单 + if (!this._isWarehouseInterceptedOrderStatus(order.intercept_status)) { + skipped.push({ order_id: orderId, reason: '非库内拦截订单' }); + continue; + } + + // 静默跳过:已有有效拆包单 + if (existingOrderIdSet.has(orderId)) { + skipped.push({ order_id: orderId, reason: '订单已存在拆包单' }); + continue; + } + + const orderExpress = expressMap.get(orderId) || null; + const waybillCode = String( + (orderExpress && orderExpress.waybill_code) || order.delivery_order_code || '' + ).trim(); + if (!waybillCode) { + skipped.push({ order_id: orderId, reason: '订单无运单号,无法创建拆包单' }); + continue; + } + + // 同运单号已有有效拆包单(可能由运单转入等入口创建)→ 静默跳过 + if (existingWaybillSet.has(waybillCode)) { + skipped.push({ order_id: orderId, reason: '运单号已存在拆包单' }); + continue; + } + + const orderItems = itemsMap.get(orderId) || []; + if (orderItems.length === 0) { + skipped.push({ order_id: orderId, reason: '订单无明细可复制' }); + continue; + } + + try { + const storeId = Number(order.store_id || 0) + || Number(orderExpress && orderExpress.store_id || 0) + || null; + const storeRemark = await this._resolveStoreRemark(storeId, warehouseId); + const returnReceivedId = await this._resolveReturnReceivedId(warehouseId, waybillCode); + + const createdRow = await this._insertMainWithRetry({ + warehouse_id: warehouseId, + return_received_id: returnReceivedId, + waybill_code: waybillCode, + unpack_date: unpackDate, + start_time: now, + end_time: null, + unpacker_id: unpackerId, + unpacker_name: unpackerName || '未命名', + status: 'unpacking', + detail_status: 'none_recognized', + total_items: 0, + total_quantity: 0, + order_express_id: orderExpress ? orderExpress.id : null, + order_id: orderId, + store_id: storeId, + source_order_codes: order.source_order_codes + || (orderExpress && orderExpress.source_order_codes) + || null, + shop_name: storeRemark || null, + camera_ids: null, + remark: null, + }, warehouseId, 'transferByOrders'); + + const unpackId = Number(createdRow.id); + + // 明细 1:1 复制订单原本明细(product_status 固定 normal),插入后回填主表汇总 + const detailRows = await this._buildTransferDetailRows(orderItems); + await ctx.model.ReturnUnpackDetail.bulkCreate( + detailRows.map(row => ({ ...row, unpack_id: unpackId, warehouse_id: warehouseId })) + ); + const summary = await this._recalcMain(unpackId, warehouseId); + + // 同批内后续重复订单/运单不再重复创建 + existingOrderIdSet.add(orderId); + existingWaybillSet.add(waybillCode); + + success.push({ + order_id: orderId, + unpack_id: unpackId, + unpack_no: createdRow.unpack_no || '', + waybill_code: waybillCode, + detail_count: summary.total_items, + total_quantity: summary.total_quantity, + }); + } catch (err) { + const reason = (err && err.message) || '转换失败'; + ctx.logger.warn(`[returnUnpack.transferByOrders] 订单ID ${orderId} 转换失败: ${reason}`); + failed.push({ order_id: orderId, reason }); + } + } + + return { + total: orderIds.length, + success_count: success.length, + skipped_count: skipped.length, + failed_count: failed.length, + success, + skipped, + failed, + }; + } + + /** + * 判断订单拦截状态是否为「库内拦截」。 + * 库内确定拦截由 recheckOrder.confirmIntercept / intercept_auto_confirm 写入 + * intercepted_at_warehouse;历史遗留值 intercepted 一并兼容。 + * + * @param {*} status 拦截状态值。 + * @return {boolean} 是否库内拦截。 + */ + _isWarehouseInterceptedOrderStatus(status) { + const normalizedStatus = String(status || '').trim(); + return normalizedStatus === 'intercepted_at_warehouse' || normalizedStatus === 'intercepted'; + } + + /** + * 批量载入订单主记录:序列表定位车道 → 分表批量查询 → 基表兜底。 + * 仅返回属于当前仓库的订单(warehouse_id 为空的历史数据不额外拦截)。 + * + * @param {Array} orderIds 订单ID列表。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} orderId → { order, lane }。 + */ + async _loadOrdersForTransferByOrders(orderIds, warehouseId) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const result = new Map(); + const laneLabels = [ 'current', 'history', 'dispatch', 'outsourced' ]; + const attributes = [ + 'id', 'warehouse_id', 'store_id', 'delivery_order_code', + 'source_order_codes', 'intercept_status', 'items', + ]; + + const factory = ctx.model.OrderDeliveryFactory; + if (!factory || typeof factory.getCurrentModel !== 'function') { + return result; + } + + const laneGetters = { + current: () => factory.getCurrentModel(warehouseId), + history: () => factory.getHistoryModel(warehouseId), + dispatch: () => factory.getDispatchModel(warehouseId), + outsourced: () => factory.getOutsourcedModel(warehouseId), + }; + + // 序列表定位优先:命中车道只查对应分表,未命中按全车道遍历 + const locationMap = new Map(); + try { + if (typeof factory.getOrderLocations === 'function') { + const located = await factory.getOrderLocations(orderIds, warehouseId); + for (const [ orderId, lane ] of located.entries()) { + locationMap.set(Number(orderId), String(lane)); + } + } + } catch (err) { + ctx.logger.warn(`[returnUnpack.transferByOrders] 序列表定位失败: ${err.message}`); + } + + const laneOrderIds = new Map(); + for (const orderId of orderIds) { + const lane = locationMap.get(orderId); + const targets = lane && laneGetters[lane] ? [ lane ] : laneLabels; + for (const targetLane of targets) { + if (!laneOrderIds.has(targetLane)) { + laneOrderIds.set(targetLane, []); + } + laneOrderIds.get(targetLane).push(orderId); + } + } + + for (const lane of laneLabels) { + const ids = (laneOrderIds.get(lane) || []).filter(id => !result.has(id)); + if (ids.length === 0) continue; + try { + const model = await laneGetters[lane](); + if (!model || typeof model.findAll !== 'function') continue; + const rows = await model.findAll({ + where: { id: { [Op.in]: ids } }, + attributes, + raw: true, + }); + for (const row of rows) { + const orderId = Number(row.id || 0); + if (orderId <= 0) continue; + if (row.warehouse_id !== null && row.warehouse_id !== undefined + && Number(row.warehouse_id) !== warehouseId) { + continue; + } + result.set(orderId, { order: row, lane }); + } + } catch (err) { + ctx.logger.warn(`[returnUnpack.transferByOrders] 查询 ${lane} 分表失败: ${err.message}`); + } + } + + // 分表均未命中:回退基表(存量订单) + const missingIds = orderIds.filter(id => !result.has(id)); + if (missingIds.length > 0) { + try { + const rows = await ctx.model.OrderDelivery.findAll({ + where: { id: { [Op.in]: missingIds } }, + attributes, + raw: true, + }); + for (const row of rows) { + const orderId = Number(row.id || 0); + if (orderId <= 0) continue; + if (row.warehouse_id !== null && row.warehouse_id !== undefined + && Number(row.warehouse_id) !== warehouseId) { + continue; + } + result.set(orderId, { order: row, lane: null }); + } + } catch (err) { + ctx.logger.warn(`[returnUnpack.transferByOrders] 查询订单基表失败: ${err.message}`); + } + } + + return result; + } + + /** + * 批量载入订单原本明细:优先解析订单 items JSON 数组,为空时按订单所在车道 + * 批量查询明细分表(订单无车道索引时遍历 current/dispatch/history)。 + * 输出统一为下划线字段(stock_id/item_code/item_name/plan_qty),供复制明细使用。 + * + * @param {Map} orderMap 订单载入结果(orderId → { order, lane })。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>>} orderId → 明细行数组。 + */ + async _loadOrderItemsForTransferByOrders(orderMap, warehouseId) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const itemsMap = new Map(); + const laneLabels = [ 'current', 'dispatch', 'history' ]; + + // 1. 订单 items JSON 优先(存量/兼容路径),统一归一化为下划线字段 + const needDbOrderIds = []; + for (const [ orderId, entry ] of orderMap.entries()) { + const inlineItems = this._parseOrderItemsJson(entry && entry.order && entry.order.items); + if (inlineItems.length > 0) { + itemsMap.set(orderId, inlineItems); + } else { + needDbOrderIds.push(orderId); + } + } + + const factory = ctx.model.OrderItemsFactory; + if (!factory || needDbOrderIds.length === 0) { + return itemsMap; + } + + const laneGetters = { + current: () => factory.getCurrentModel(warehouseId), + history: () => factory.getHistoryModel(warehouseId), + dispatch: () => factory.getDispatchModel(warehouseId), + }; + + // 2. 按订单车道分组批量查询(无车道索引的订单遍历三个车道) + const laneOrderIds = new Map(); + for (const orderId of needDbOrderIds) { + const entry = orderMap.get(orderId) || {}; + const lane = entry.lane && laneGetters[entry.lane] ? entry.lane : null; + const targets = lane ? [ lane ] : laneLabels; + for (const targetLane of targets) { + if (!laneOrderIds.has(targetLane)) { + laneOrderIds.set(targetLane, []); + } + laneOrderIds.get(targetLane).push(orderId); + } + } + + for (const lane of laneLabels) { + const ids = (laneOrderIds.get(lane) || []).filter(id => !itemsMap.has(id)); + if (ids.length === 0) continue; + try { + const model = await laneGetters[lane](); + if (!model || typeof model.findAll !== 'function') continue; + const rows = await model.findAll({ + where: { order_id: { [Op.in]: ids } }, + attributes: [ 'order_id', 'stock_id', 'item_code', 'item_name', 'plan_qty' ], + raw: true, + }); + for (const row of rows) { + const orderId = Number(row.order_id || 0); + if (orderId <= 0) continue; + if (!itemsMap.has(orderId)) { + itemsMap.set(orderId, []); + } + itemsMap.get(orderId).push(row); + } + } catch (err) { + ctx.logger.warn(`[returnUnpack.transferByOrders] 查询 ${lane} 商品明细失败: ${err.message}`); + } + } + + // 3. 指定车道未命中时兜底遍历其余车道(订单与明细分表迁移不同步) + const stillMissingIds = needDbOrderIds.filter(id => !itemsMap.has(id)); + for (const orderId of stillMissingIds) { + for (const lane of laneLabels) { + try { + const model = await laneGetters[lane](); + if (!model || typeof model.findAll !== 'function') continue; + const rows = await model.findAll({ + where: { order_id: orderId }, + attributes: [ 'order_id', 'stock_id', 'item_code', 'item_name', 'plan_qty' ], + raw: true, + }); + if (rows.length > 0) { + itemsMap.set(orderId, rows); + break; + } + } catch (err) { + // 该车道表可能不存在,继续下一张 + } + } + } + + return itemsMap; + } + + /** + * 解析订单 items JSON 数组(非数组/解析失败返回空数组),并归一化为下划线字段。 + * + * @param {*} raw 订单 items 原始值(字符串或数组)。 + * @return {Array} 明细行数组。 + */ + _parseOrderItemsJson(raw) { + if (!raw) { + return []; + } + let parsed = raw; + if (typeof raw === 'string') { + const trimmed = raw.trim(); + if (!trimmed.startsWith('[')) { + return []; + } + try { + parsed = JSON.parse(trimmed); + } catch (err) { + return []; + } + } + if (!Array.isArray(parsed)) { + return []; + } + return parsed.map(item => ({ + stock_id: item.stock_id !== undefined ? item.stock_id : (item.stockId !== undefined ? item.stockId : null), + item_code: item.item_code !== undefined ? item.item_code : (item.itemCode || ''), + item_name: item.item_name !== undefined ? item.item_name : (item.itemName || ''), + plan_qty: item.plan_qty !== undefined ? item.plan_qty : (item.planQty || 1), + })); + } + + /** + * 批量反查订单主运单(business_key=1 优先,其次最小 id 且有运单号的运单)。 + * + * @param {Array} orderIds 订单ID列表。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} orderId → 运单行。 + */ + async _resolveOrderExpressForTransferByOrders(orderIds, warehouseId) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const result = new Map(); + if (orderIds.length === 0) { + return result; + } + + try { + const rows = await ctx.model.OrderExpress.findAll({ + where: { + order_id: { [Op.in]: orderIds }, + warehouse_id: warehouseId, + delete_at: null, + }, + attributes: [ + 'id', 'order_id', 'waybill_code', 'business_key', + 'source_order_codes', 'store_id', + ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const byOrder = new Map(); + for (const row of rows) { + const orderId = Number(row.order_id || 0); + if (orderId <= 0) continue; + if (!byOrder.has(orderId)) { + byOrder.set(orderId, []); + } + byOrder.get(orderId).push(row); + } + + for (const [ orderId, list ] of byOrder.entries()) { + const withCode = list.filter(row => String(row.waybill_code || '').trim()); + if (withCode.length === 0) continue; + const mainRow = withCode.find(row => Number(row.business_key) === 1) || withCode[0]; + result.set(orderId, mainRow); + } + } catch (err) { + ctx.logger.warn(`[returnUnpack.transferByOrders] 批量反查订单运单失败: ${err.message}`); + } + + return result; + } + /** * 录明细:以拆包单ID为依据录入一条明细(识别到系统商品时回填快照)。 * 仅以 stock_id 识别商品;不指定 stock_id 时一律标注未知商品, diff --git a/database/migrations/20261017100000-add-return-unpack-transfer-orders-permission.js b/database/migrations/20261017100000-add-return-unpack-transfer-orders-permission.js new file mode 100644 index 0000000..e6f3111 --- /dev/null +++ b/database/migrations/20261017100000-add-return-unpack-transfer-orders-permission.js @@ -0,0 +1,88 @@ +'use strict'; + +/** + * 退回拆包「配送订单批量转退回拆包单」权限记录 + 角色授权迁移。 + * + * 权限明细(固定 ID 643,当前库内最大已用 ID=642): + * 643 — returnUnpack.transferByOrders API:配送订单批量转退回拆包单 + * + * 角色授权(系统预设角色,不含通配符角色): + * 作业类(643)→ 仓库组-员工(27) → 仓库组-主管(26)(仓库员工及以上) + * 经理(8)/仓库管理员(2)/超级管理员(7) 已持有 * 通配符,自动拥有所有权限,无需处理 + * + * 幂等:INSERT IGNORE 创建权限记录;角色权限数组追加后去重排序,已存在跳过。 + */ + +const TABLE = 'wms_permission'; +const ROLE_TABLE = 'wms_role'; +const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at'; + +/** 权限ID → 授权角色ID列表(不含通配符角色) */ +const PERMISSION_ROLES = { + 643: [ 27, 26 ], +}; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + // ── 1. 创建 API 权限记录(固定 ID)── + const apis = [ + [ 643, 'returnUnpack.transferByOrders', 'API:配送订单批量转退回拆包单' ], + ]; + + for (const [ id, path, metaTitle ] of apis) { + await queryInterface.sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + { replacements: [ id, path, null, path, null, metaTitle, null, 0, 0, null, 'api', 0, 1 ] } + ); + } + + // ── 2. 角色授权注入 ── + for (const permId of Object.keys(PERMISSION_ROLES).map(Number)) { + for (const roleId of PERMISSION_ROLES[permId]) { + const rows = await queryInterface.sequelize.query( + `SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE id = ?`, + { replacements: [ roleId ], type: queryInterface.sequelize.QueryTypes.SELECT } + ); + const record = Array.isArray(rows) ? rows[0] : null; + if (!record) { + continue; + } + + // 通配符角色跳过 + if (record.permissions === '*') { + continue; + } + + let perms; + try { + perms = JSON.parse(record.permissions || '[]'); + } catch (err) { + continue; + } + if (!Array.isArray(perms)) { + continue; + } + + if (perms.includes(permId)) { + continue; + } + + perms.push(permId); + perms.sort((a, b) => a - b); + + await queryInterface.sequelize.query( + `UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`, + { replacements: [ JSON.stringify(perms), roleId ] } + ); + } + } + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.sequelize.query( + `DELETE FROM \`${TABLE}\` WHERE id = 643` + ); + }, +}; diff --git a/methods/changes/system.json b/methods/changes/system.json index 5de0ddc..21c2448 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,21 @@ [ + { + "version": "2026.10.17-returnUnpack.transferByOrders", + "date": "2026-10-17", + "type": "added", + "summary": "新增退回拆包接口 returnUnpack.transferByOrders(配送订单批量转退回拆包单):入参 ids 为订单表主键数组(去重后上限 200),仅允许库内拦截订单转换;已有拆包单/非库内拦截/无运单号/无明细的订单静默跳过;每单新建拆包单并 1:1 复制订单明细(product_status=normal),返回成功/跳过/失败明细。新增权限 643(API:配送订单批量转退回拆包单,授权角色 27/26)。", + "methods": [ + "returnUnpack.transferByOrders" + ], + "notes": [ + "方法层:app/service/systemMethods/returnUnpack.js 新增 transferByOrders(data)(位于 transferByWaybills 之后),统一 this.success('ok', data) 包装,未加入 _noNeedRight/_noNeedLogin/_noNeedLog/_noNeedAuth 免检清单(isNeedAuth=true、isNeedLogin=true)", + "系统层:app/service/systems/return_unpack.js 新增 transferByOrders / _isWarehouseInterceptedOrderStatus / _loadOrdersForTransferByOrders / _loadOrderItemsForTransferByOrders / _parseOrderItemsJson / _resolveOrderExpressForTransferByOrders;复用 _insertMainWithRetry / _buildTransferDetailRows / _recalcMain / _resolveStoreRemark / _resolveReturnReceivedId", + "转换限制(用户确认):仅允许库内拦截(intercept_status=intercepted_at_warehouse,兼容 intercepted)的订单;非库内拦截订单跳过;已有拆包单(同订单或同运单号 status != 'cancelled')跳过;静默跳过,完成几个算几个", + "拆包单:status=unpacking、detail_status 按明细识别率回填;明细 product_status 固定 normal;waybill_code 取订单主运单号,无运单回退 delivery_order_code", + "权限:迁移 20261017100000-add-return-unpack-transfer-orders-permission.js,固定 ID 643(角色 27/26),开发库已执行(641/642 已被外部仓库小程序页面占用)", + "文档变更范围:methods/system.json 的 returnUnpack.transferByOrders 一条(新增)+根版本 0.3.301 → 0.3.302、updatedAt 2026-10-17;methods/changes/system.json 新增本条(插入数组首位)" + ] + }, { "version": "0.3.301", "date": "2026-10-16", diff --git a/methods/system.json b/methods/system.json index 1edfbb7..478ebc7 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.301", - "updatedAt": "2026-10-16", + "version": "0.3.302", + "updatedAt": "2026-10-17", "headers": [ { "name": "platform", @@ -49554,6 +49554,107 @@ "幂等复用命中时 reused=true 不重复创建;复用单明细为空时按订单明细补写,已有明细不重复写入", "标记 wms_order_express.is_back='Y' 与回填 return_received_id 为尽力而为(失败仅告警不阻断主流程)" ] + }, + { + "method": "returnUnpack.transferByOrders", + "description": "配送订单批量转退回拆包单:一次调用把多个配送订单批量转换为退回拆包单。ids 为订单表主键ID(wms_order_delivery*.id,支持单个数值或 JSON 数组),服务端 Number() 归一化 + 过滤非正整数 + 去重,去重后单次上限 200。仓库隔离:warehouse_id 由服务端从 ctx.user.store_id 注入,禁止前端传入。逐单处理,单条失败不阻断主流程。转换限制(静默跳过,不报错、不阻断其它订单):1) 仅允许「库内拦截」订单转换(intercept_status=intercepted_at_warehouse,兼容历史值 intercepted),非库内拦截订单跳过;2) 订单已有有效拆包单(wms_return_unpack 同仓库 + order_id 命中,或同运单号已存在,status != 'cancelled')跳过;3) 订单不存在/不属于当前仓库、无运单号、无明细可复制的订单同样跳过。每单新建一张拆包单:订单主运单(wms_order_express,business_key=1 优先)的 waybill_code 写入拆包单(无运单时回退订单发货单号),回填 order_express_id/order_id/store_id/source_order_codes/shop_name;明细直接使用订单原本明细 1:1 复制(订单 items JSON 优先,为空回退明细分表;通过订单索引表 wms_order_id_location_{warehouseId} 定位车道),product_status 固定 normal,写入后回填主表 total_items/total_quantity/detail_status。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "ids", + "type": "array", + "required": true, + "source": "body", + "description": "订单表主键ID列表(wms_order_delivery*.id,也兼容单个数值,服务端统一归一化:Number() 转换 → 过滤非正整数 → 去重,去重后单次上限 200)" + } + ], + "response": [ + { + "name": "total", + "type": "number", + "required": true, + "description": "去重后待处理订单总数" + }, + { + "name": "success_count", + "type": "number", + "required": true, + "description": "成功创建拆包单的订单数量" + }, + { + "name": "skipped_count", + "type": "number", + "required": true, + "description": "静默跳过的订单数量(非库内拦截/已有拆包单/无运单号/无明细等)" + }, + { + "name": "failed_count", + "type": "number", + "required": true, + "description": "处理失败的订单数量(非预期异常,如数据库写入失败)" + }, + { + "name": "success", + "type": "array", + "required": true, + "description": "成功项数组,每项含 order_id(订单ID)/ unpack_id(拆包单ID)/ unpack_no(拆包单号)/ waybill_code(写入拆包单的运单号)/ detail_count(明细行数)/ total_quantity(明细数量合计)" + }, + { + "name": "skipped", + "type": "array", + "required": true, + "description": "跳过项数组,每项含 order_id / reason(跳过原因,如「非库内拦截订单」「订单已存在拆包单」「运单号已存在拆包单」「订单无明细可复制」)" + }, + { + "name": "failed", + "type": "array", + "required": true, + "description": "失败项数组,每项含 order_id / reason(失败原因)" + } + ], + "errors": [ + { + "code": "400", + "message": "ids 不能为空" + }, + { + "code": "400", + "message": "单次最多批量转换 200 个订单" + }, + { + "code": "400", + "message": "缺少仓库上下文" + }, + { + "code": "400", + "message": "缺少拆包人员工号上下文" + }, + { + "code": "500", + "message": "查询已有拆包单失败,请稍后重试" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "403", + "message": "无权访问该接口" + }, + { + "code": "500", + "message": "服务器内部错误" + } + ], + "notes": [ + "静默跳过口径:非库内拦截订单、已有有效拆包单的订单、订单不存在/不属于当前仓库、无运单号、无明细可复制均不抛错,进入 skipped[],整体响应仍为 success;仅非预期异常进入 failed[]", + "库内拦截判定:intercept_status === 'intercepted_at_warehouse'(recheckOrder.confirmIntercept / intercept_auto_confirm 写入),历史遗留值 'intercepted' 一并兼容", + "拆包单运单号来源:wms_order_express 同订单主运单(business_key=1 优先,其次最小 id)的 waybill_code;无运单时回退订单 delivery_order_code,二者都没有则跳过", + "明细口径:与 returnUnpack.transferByWaybills 一致,订单原本明细 1:1 复制(不做合并/换算),quantity 取订单行 plan_qty(最小 1),product_status 固定 normal,写入后回填主表 total_items/total_quantity/detail_status", + "鉴权口径:isNeedAuth=true、isNeedLogin=true,未加入 _noNeedRight/_noNeedLogin/_noNeedLog/_noNeedAuth 免检清单;权限 wms_permission id=643 path=returnUnpack.transferByOrders(meta_title=API:配送订单批量转退回拆包单),授权角色 27(仓库组-员工)/ 26(仓库组-主管),经理/仓库管理员/超级管理员持 * 通配符自动拥有" + ] } ] }, diff --git a/package.json b/package.json index cc2f1fa..4eabf39 100644 --- a/package.json +++ b/package.json @@ -69,7 +69,7 @@ "ops:clean-root-logs:apply": "node ./script/check-root-logs.cjs production --clean --apply", "version:record": "node ./script/version-record.cjs", "version:history": "node ./script/version-history.cjs --limit=50", - "depeeloy": "npm run deploy:prod", + "deploy": "npm run deploy:prod", "deploy:prod": "node ./script/deploy-remote.cjs production", "rollback": "npm run rollback:prod", "rollback:prod": "node ./script/rollback-remote.cjs production",