diff --git a/app/service/systemMethods/returnUnpack.js b/app/service/systemMethods/returnUnpack.js index 2a19022..a094698 100644 --- a/app/service/systemMethods/returnUnpack.js +++ b/app/service/systemMethods/returnUnpack.js @@ -64,6 +64,22 @@ class ReturnUnpackMethodService extends MainService { ); } + /** + * 运单批量转入退件登记(退回拆包,批量)。 + * 新方法需鉴权 + 需登录 + 记录日志,不在任何免检清单内。 + * + * @param {Object} data 请求体。 + * @param {string|Array} data.waybill_codes 运单号(单个字符串或数组,去重后上限 200)。 + * @return {Promise} 统一 success 包装,data 含 total/success_count/failed_count/success/failed。 + */ + async transferByWaybills(data = {}) { + const { waybill_codes } = data; + return this._call( + () => this.service.systems.returnUnpack.transferByWaybills({ waybill_codes }), + '运单批量转入退件登记失败' + ); + } + /** * 录明细(增)。 * diff --git a/app/service/systems/return_unpack.js b/app/service/systems/return_unpack.js index 00d986f..d37dc2f 100644 --- a/app/service/systems/return_unpack.js +++ b/app/service/systems/return_unpack.js @@ -245,32 +245,7 @@ class ReturnUnpackService extends Service { remark: remark ? String(remark).slice(0, 500) : null, }; - let created = null; - const maxAttempts = 5; - for (let attempt = 1; attempt <= maxAttempts && !created; attempt += 1) { - const unpackNo = await this._generateUnpackNo(warehouseId); - try { - created = await ctx.model.ReturnUnpack.create({ - ...baseFields, - unpack_no: unpackNo, - }); - } catch (err) { - const isUniqueConflict = err && ( - err.name === 'SequelizeUniqueConstraintError' - || (err.parent && err.parent.code === 'ER_DUP_ENTRY') - ); - if (isUniqueConflict && attempt < maxAttempts) { - // 并发撞号:指数退避 + 随机抖动后重新取号重试,降低同一序号再次碰撞概率 - const backoffMs = Math.min(500, attempt * 40) + Math.floor(Math.random() * 60); - ctx.logger.warn(`[returnUnpack.create] 拆包单号唯一冲突,第 ${attempt} 次重试(退避 ${backoffMs}ms): ${err.message}`); - await new Promise(resolve => setTimeout(resolve, backoffMs)); - continue; - } - throw err; - } - } - - const createdRow = created && typeof created.toJSON === 'function' ? created.toJSON() : created; + const createdRow = await this._insertMainWithRetry(baseFields, warehouseId, 'create'); // 7. 原订单详情(仅原单退回时拉取,参考 afterSale.detail._resolveOrderDetail) let order = null; @@ -292,6 +267,80 @@ class ReturnUnpackService extends Service { }; } + /** + * 运单批量转入退件登记(退回拆包,批量)。 + * 批量入参运单号数组:去重 + trim + 过滤空值,单次上限 200;逐单处理,单条失败不阻断主流程。 + * 命中的运单统一标记 wms_order_express.is_back='Y'(不做其他前置条件限制); + * 幂等:同仓库 + 同运单号已存在有效(status != 'cancelled')拆包单时直接复用, + * 复用单明细为空时按订单明细补写(优先 items JSON,为空回退明细分表)。 + * + * @param {Object} params 批量转入参数。 + * @param {string|Array} params.waybill_codes 运单号(单个字符串或数组)。 + * @return {Promise} { total, success_count, failed_count, success[], failed[] }, + * 成功项含 waybill_code/unpack_id/unpack_no/reused/detail_count/total_quantity, + * 失败项含 waybill_code/reason。 + */ + async transferByWaybills({ waybill_codes }) { + const { ctx } = this; + + // 入参归一化:单个字符串转数组,trim + 去重 + 过滤空值 + const rawCodes = Array.isArray(waybill_codes) ? waybill_codes : [ waybill_codes ]; + const waybillCodes = [ ...new Set( + rawCodes.map(code => String(code == null ? '' : code).trim()).filter(Boolean) + ) ]; + + if (waybillCodes.length === 0) { + throw this.createBusinessError('waybill_codes 不能为空', 400); + } + if (waybillCodes.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); + } + + /** @type {Array} 成功项列表 */ + const success = []; + /** @type {Array} 失败项列表 */ + const failed = []; + + for (const waybillCode of waybillCodes) { + try { + const item = await this._transferOneWaybill({ + waybillCode, + warehouseId, + unpackerId, + unpackerName, + }); + success.push(item); + } catch (err) { + const reason = (err && err.message) || '转入失败'; + ctx.logger.warn(`[returnUnpack.transferByWaybills] 运单 ${waybillCode} 转入失败: ${reason}`); + failed.push({ waybill_code: waybillCode, reason }); + } + } + + return { + total: waybillCodes.length, + success_count: success.length, + failed_count: failed.length, + success, + failed, + }; + } + /** * 录明细:以拆包单ID为依据录入一条明细(识别到系统商品时回填快照)。 * 仅以 stock_id 识别商品;不指定 stock_id 时一律标注未知商品, @@ -1918,6 +1967,369 @@ class ReturnUnpackService extends Service { // 辅助方法 // =========================== + /** + * 生成拆包单号并插入主表(并发撞 uk_unpack_no 唯一索引时重新取号重试)。 + * 最多重试 5 次,指数退避 + 随机抖动;create 与 transferByWaybills 共用。 + * + * @param {Object} baseFields 主表插入字段(不含 unpack_no)。 + * @param {number} warehouseId 仓库ID(用于取号)。 + * @param {string} scene 调用场景标识(用于日志)。 + * @return {Promise} 创建后的主表记录(JSON 对象)。 + */ + async _insertMainWithRetry(baseFields, warehouseId, scene) { + const { ctx } = this; + const maxAttempts = 5; + for (let attempt = 1; attempt <= maxAttempts; attempt += 1) { + const unpackNo = await this._generateUnpackNo(warehouseId); + try { + const created = await ctx.model.ReturnUnpack.create({ + ...baseFields, + unpack_no: unpackNo, + }); + return created && typeof created.toJSON === 'function' ? created.toJSON() : created; + } catch (err) { + const isUniqueConflict = err && ( + err.name === 'SequelizeUniqueConstraintError' + || (err.parent && err.parent.code === 'ER_DUP_ENTRY') + ); + if (isUniqueConflict && attempt < maxAttempts) { + // 并发撞号:指数退避 + 随机抖动后重新取号重试,降低同一序号再次碰撞概率 + const backoffMs = Math.min(500, attempt * 40) + Math.floor(Math.random() * 60); + ctx.logger.warn( + `[returnUnpack.${scene}] 拆包单号唯一冲突,第 ${attempt} 次重试(退避 ${backoffMs}ms): ${err.message}` + ); + await new Promise(resolve => setTimeout(resolve, backoffMs)); + continue; + } + throw err; + } + } + throw this.createBusinessError('拆包单号生成失败,请重试', 500); + } + + /** + * 处理单个运单的批量转入:反查原运单 → 标记退回 → 幂等复用/新建拆包单 → 复制订单明细。 + * 子单(business_key > 1)跳过;一个运单只允许一条有效拆包单。 + * + * @param {Object} params 单运单处理参数。 + * @param {string} params.waybillCode 运单号。 + * @param {number} params.warehouseId 仓库ID。 + * @param {number} params.unpackerId 拆包人员工号ID。 + * @param {string} params.unpackerName 拆包人员工号名称。 + * @return {Promise} 成功项:{ waybill_code, unpack_id, unpack_no, reused, detail_count, total_quantity }。 + */ + async _transferOneWaybill({ waybillCode, warehouseId, unpackerId, unpackerName }) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + // 1. 反查原运单(不做其他前置条件限制;按仓库隔离,避免跨仓运单被转入本仓拆包单) + let orderExpress = null; + try { + orderExpress = await ctx.model.OrderExpress.findOne({ + where: { waybill_code: waybillCode, warehouse_id: warehouseId }, + attributes: [ 'id', 'order_id', 'store_id', 'source_order_codes', 'business_key' ], + raw: true, + }); + } catch (err) { + ctx.logger.warn(`[returnUnpack.transferByWaybills] 反查原运单失败 ${waybillCode}: ${err.message}`); + } + if (!orderExpress) { + throw this.createBusinessError('运单不存在', 404); + } + + // 子单不处理:business_key 为空或 1 视为主单,>1 跳过 + if (Number(orderExpress.business_key || 0) > 1) { + throw this.createBusinessError('运单为子单(business_key>1),跳过', 400); + } + + // 2. 命中的运单统一标记退回(不做其他前置条件限制) + try { + await ctx.model.OrderExpress.update( + { is_back: 'Y' }, + { where: { id: orderExpress.id } } + ); + } catch (err) { + ctx.logger.warn(`[returnUnpack.transferByWaybills] 标记运单退回失败 id=${orderExpress.id}: ${err.message}`); + } + + // 3. 幂等复用:同仓库 + 同运单号已存在有效(status != 'cancelled')拆包单时直接复用 + let existing = null; + try { + const existingList = await ctx.model.ReturnUnpack.findAll({ + where: { + warehouse_id: warehouseId, + waybill_code: waybillCode, + status: { [Op.ne]: 'cancelled' }, + }, + attributes: [ 'id', 'unpack_no', 'return_received_id', 'order_express_id', 'order_id' ], + order: [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]], + raw: true, + }); + if (existingList.length > 0) { + existing = existingList[0]; + // 同运单号可能有多张拆包单:优先复用已录明细的最新单(与 create 口径一致) + const countRows = await ctx.model.ReturnUnpackDetail.findAll({ + where: { unpack_id: { [Op.in]: existingList.map(row => row.id) } }, + attributes: [ + 'unpack_id', + [ ctx.model.fn('COUNT', ctx.model.col('id')), 'detail_count' ], + ], + group: [ 'unpack_id' ], + raw: true, + }); + const detailCountMap = new Map( + countRows.map(row => [ Number(row.unpack_id), Number(row.detail_count) || 0 ]) + ); + const withDetails = existingList.find(row => (detailCountMap.get(Number(row.id)) || 0) > 0); + if (withDetails) { + existing = withDetails; + } + } + } catch (err) { + ctx.logger.warn(`[returnUnpack.transferByWaybills] 查重已有拆包单失败 ${waybillCode}: ${err.message}`); + } + + // 可选:命中退回收到登记(同仓库 + 同运单号)时回填 return_received_id + const returnReceivedId = await this._resolveReturnReceivedId(warehouseId, waybillCode); + + if (existing) { + const unpackId = Number(existing.id); + + // 复用单明细为空时按规则 4 补写订单明细 + let summary = await this._countDetails(unpackId); + if (summary.detail_count === 0) { + try { + const backfillOrderId = Number(existing.order_id || 0) || Number(orderExpress.order_id || 0); + await this._backfillDetailsFromOrder(unpackId, warehouseId, backfillOrderId); + summary = await this._countDetails(unpackId); + } catch (err) { + ctx.logger.warn(`[returnUnpack.transferByWaybills] 复用单补写明细失败 unpack_id=${unpackId}: ${err.message}`); + } + } + + // 主表退回收到单ID为空时回填 + if (returnReceivedId && !existing.return_received_id) { + try { + await ctx.model.ReturnUnpack.update( + { return_received_id: returnReceivedId }, + { where: { id: unpackId } } + ); + } catch (err) { + ctx.logger.warn(`[returnUnpack.transferByWaybills] 回填退回收到单失败 unpack_id=${unpackId}: ${err.message}`); + } + } + + return { + waybill_code: waybillCode, + unpack_id: unpackId, + unpack_no: existing.unpack_no || '', + reused: true, + detail_count: summary.detail_count, + total_quantity: summary.total_quantity, + }; + } + + // 4. 新建拆包单:解析关联订单明细(优先 items JSON,为空回退明细分表,复用 afterSale 现成实现) + const orderId = Number(orderExpress.order_id || 0); + let order = null; + if (orderId > 0) { + try { + order = await ctx.service.systems.afterSale._resolveOrderDetail(orderId, warehouseId); + } catch (err) { + ctx.logger.warn(`[returnUnpack.transferByWaybills] 拉取订单详情失败 orderId=${orderId}: ${err.message}`); + } + } + + const orderItems = order && Array.isArray(order.items) ? order.items : []; + if (orderItems.length === 0) { + throw this.createBusinessError('运单关联订单无明细可复制', 400); + } + + const storeId = Number(orderExpress.store_id || 0) || Number(order && order.store_id || 0) || null; + const storeRemark = await this._resolveStoreRemark(storeId, warehouseId); + + const now = new Date(); + const unpackDate = app.formatDate(now, 'YYYY-MM-DD'); + + 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.id, + order_id: orderId > 0 ? orderId : null, + store_id: storeId, + source_order_codes: orderExpress.source_order_codes || null, + shop_name: storeRemark || null, + camera_ids: null, + remark: null, + }, warehouseId, 'transferByWaybills'); + + const unpackId = Number(createdRow.id); + + // 5. 复制订单明细(逐行 1:1 复制,不做合并/换算),插入后回填主表汇总 + 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); + + return { + waybill_code: waybillCode, + unpack_id: unpackId, + unpack_no: createdRow.unpack_no || '', + reused: false, + detail_count: summary.total_items, + total_quantity: summary.total_quantity, + }; + } + + /** + * 按规则补写拆包单明细:解析关联订单明细(优先 items JSON,为空回退明细分表)并逐行复制写入。 + * + * @param {number} unpackId 拆包单ID。 + * @param {number} warehouseId 仓库ID。 + * @param {number} orderId 订单ID。 + * @return {Promise} 写入的明细行数。 + */ + async _backfillDetailsFromOrder(unpackId, warehouseId, orderId) { + const { ctx } = this; + if (!orderId || !Number.isFinite(orderId) || orderId <= 0) { + throw this.createBusinessError('未找到关联订单', 404); + } + + let order = null; + try { + order = await ctx.service.systems.afterSale._resolveOrderDetail(orderId, warehouseId); + } catch (err) { + ctx.logger.warn(`[returnUnpack._backfillDetailsFromOrder] 拉取订单详情失败 orderId=${orderId}: ${err.message}`); + } + + const orderItems = order && Array.isArray(order.items) ? order.items : []; + if (orderItems.length === 0) { + throw this.createBusinessError('订单无明细可复制', 400); + } + + const detailRows = await this._buildTransferDetailRows(orderItems); + await ctx.model.ReturnUnpackDetail.bulkCreate( + detailRows.map(row => ({ ...row, unpack_id: unpackId, warehouse_id: warehouseId })) + ); + await this._recalcMain(unpackId, warehouseId); + return detailRows.length; + } + + /** + * 统计拆包单明细行数与总数量(不更新主表)。 + * + * @param {number} unpackId 拆包单ID。 + * @return {Promise} { detail_count, total_quantity }。 + */ + async _countDetails(unpackId) { + const { ctx } = this; + const details = await ctx.model.ReturnUnpackDetail.findAll({ + where: { unpack_id: unpackId }, + attributes: [ 'quantity' ], + raw: true, + }); + return { + detail_count: details.length, + total_quantity: details.reduce((sum, row) => sum + (Number(row.quantity) || 0), 0), + }; + } + + /** + * 反查退回收到登记单ID(同仓库 + 同运单号,取最新一条),用于主表回填。 + * + * @param {number} warehouseId 仓库ID。 + * @param {string} waybillCode 运单号。 + * @return {Promise} 退回收到单ID,未命中返回 null。 + */ + async _resolveReturnReceivedId(warehouseId, waybillCode) { + const { ctx } = this; + try { + const received = await ctx.model.ReturnReceived.findOne({ + where: { warehouse_id: warehouseId, waybill_code: waybillCode }, + attributes: [ 'id' ], + order: [[ 'id', 'DESC' ]], + raw: true, + }); + return received ? Number(received.id) || null : null; + } catch (err) { + ctx.logger.warn(`[returnUnpack._resolveReturnReceivedId] 反查退回收到单失败: ${err.message}`); + return null; + } + } + + /** + * 将订单明细逐行映射为拆包明细行(1:1 复制,不做合并/换算)。 + * 口径参考 addDetail:有 stock_id 记 is_recognized=1;spec 仅在取到库存 sku_property 时填; + * quantity 取订单行 plan_qty(最小 1);product_status 固定 normal; + * product_snapshot 仅在取到库存详情时写入。 + * + * @param {Array} orderItems 订单明细行(来自 afterSale._resolveOrderDetail 的 items)。 + * @return {Promise>} 拆包明细行数组(不含 unpack_id / warehouse_id)。 + */ + async _buildTransferDetailRows(orderItems) { + const { ctx } = this; + const stockIds = [ ...new Set( + orderItems + .map(item => Number(item && item.stock_id)) + .filter(id => Number.isInteger(id) && id > 0) + ) ]; + + /** @type {Map} 库存详情快照映射 */ + const stockMap = new Map(); + if (stockIds.length > 0) { + try { + const stockRows = await ctx.model.StockWarehouse.findAll({ + where: { id: { [this.app.Sequelize.Op.in]: stockIds } }, + attributes: [ + 'id', 'item_code', 'goods_code', 'item_name', + 'sku_property', 'stock_unit', 'item_type', + ], + raw: true, + }); + for (const row of stockRows) { + stockMap.set(Number(row.id), row); + } + } catch (err) { + ctx.logger.warn(`[returnUnpack._buildTransferDetailRows] 批量查询库存详情失败: ${err.message}`); + } + } + + return orderItems.map(item => { + const stockId = Number(item && item.stock_id); + const stock = stockId > 0 ? (stockMap.get(stockId) || null) : null; + const isRecognized = stockId > 0 ? 1 : 0; + return { + stock_id: isRecognized ? stockId : null, + is_recognized: isRecognized, + item_code: String((item && item.item_code) || (stock && stock.item_code) || '').slice(0, 50) || null, + item_name: String((item && item.item_name) || (stock && stock.item_name) || '未知商品').slice(0, 255), + spec: stock && stock.sku_property ? String(stock.sku_property).slice(0, 100) : null, + quantity: Math.max(1, parseInt(item && item.plan_qty) || 1), + product_status: 'normal', + product_snapshot: stock ? JSON.stringify({ + item_code: stock.item_code || '', + goods_code: stock.goods_code || '', + item_name: stock.item_name || '', + sku_property: stock.sku_property || '', + stock_unit: stock.stock_unit || '', + item_type: stock.item_type || '', + }) : null, + remark: null, + }; + }); + } + /** * 按主键查询拆包单,并校验仓库隔离。 * diff --git a/database/migrations/20260915100000-add-return-unpack-transfer-waybills-permission.js b/database/migrations/20260915100000-add-return-unpack-transfer-waybills-permission.js new file mode 100644 index 0000000..b20b0f4 --- /dev/null +++ b/database/migrations/20260915100000-add-return-unpack-transfer-waybills-permission.js @@ -0,0 +1,88 @@ +'use strict'; + +/** + * 退回拆包「运单批量转入退件登记」权限记录 + 角色授权迁移。 + * + * 权限明细(固定 ID 568,当前迁移内最大已用 ID=567): + * 568 — returnUnpack.transferByWaybills API:运单批量转入退件登记 + * + * 角色授权(系统预设角色,不含通配符角色): + * 作业类(568)→ 仓库组-员工(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 = { + 568: [ 27, 26 ], +}; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + // ── 1. 创建 API 权限记录(固定 ID)── + const apis = [ + [ 568, 'returnUnpack.transferByWaybills', '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 = 568` + ); + }, +};