'use strict'; const fs = require('fs'); const fsp = require('fs/promises'); const os = require('os'); const path = require('path'); const crypto = require('crypto'); const Service = require('egg').Service; /** * 售后模块业务逻辑层。 * 负责 wms_after_sale / wms_after_sale_detail 的 CRUD、附件绑定等核心操作。 * 所有数据库交互集中在此层,供 systemMethods/afterSale.js 调用。 */ class AfterSaleService extends Service { // =========================== // 列表查询 // =========================== /** * 售后单列表查询,支持 where 条件、分页、排序。 * * @param {Object} where 标准化 where 条件对象 * @param {Object} [where.after_sale_no] 售后单号条件 * @param {Object} [where.type] 售后类型条件 * @param {Object} [where.sub_type] 售后子类型条件 * @param {Object} [where.status] 售后状态条件 * @param {Object} [where.priority] 优先级条件 * @param {Object} [where.role_group] 角色组条件 * @param {Object} [where.waybill_no] 运单号条件 * @param {Object} [where.claim_status] 仓库理赔状态条件 * @param {Object} [where.carrier_claim_status] 运方理赔状态条件 * @param {Object} [where.quickWhere] 快捷搜索条件 * @param {Object} [where.warehouse_id] 仓库ID(由方法层注入) * @param {Object} [pagination] 分页参数 * @param {number} [pagination.page=1] 页码 * @param {number} [pagination.pageSize=20] 每页数量 * @param {Object} [sort] 排序参数 * @param {string} [sort.sortField] 排序字段 * @param {string} [sort.sortOrder] 排序顺序(asc/desc) * @param {Object} [opts] 额外选项 * @param {Array} [opts.order] 自定义 Sequelize order(优先于 sort) * @param {boolean} [opts.excludeFutureFollowup] 是否排除 followup_at 未到的 pending_feedback 工单 * @param {boolean} [opts.enrichStoreName] 是否补充每行 store_name 货主名称(合约表货主备注 store_remask,无备注时回退货主公司全称) * @return {Promise} { list: Array, pagination: Object } */ async list(where = {}, pagination = {}, sort = {}, opts = {}) { const { ctx, app } = this; const { Op } = app.Sequelize; const page = Math.max(1, parseInt(pagination.page) || 1); const pageSize = Math.min(500, Math.max(1, parseInt(pagination.pageSize) || 20)); // 构建 Sequelize where 条件 const queryWhere = this._buildListWhere(where, Op); // 工作列表特殊逻辑:pending_feedback 状态的工单,若 followup_at 未到,暂不显示 if (opts.excludeFutureFollowup) { const pendingFeedbackWhere = { [Op.or]: [ { status: { [Op.ne]: 'pending_feedback' } }, { status: 'pending_feedback', [Op.or]: [ { followup_at: null }, { followup_at: { [Op.lte]: app.Sequelize.literal('NOW()') } }, ], }, ], }; // 合并到现有 where 中(AND 关系) if (queryWhere[Op.and]) { queryWhere[Op.and].push(pendingFeedbackWhere); } else { queryWhere[Op.and] = [ pendingFeedbackWhere ]; } } // 排序:opts.order 优先于 sort const order = Array.isArray(opts.order) && opts.order.length > 0 ? opts.order : this._buildListOrder(sort); const { count, rows } = await ctx.model.AfterSale.findAndCountAll({ where: queryWhere, order, offset: (page - 1) * pageSize, limit: pageSize, raw: true, }); const totalPages = Math.ceil(count / pageSize); const list = rows.map(row => this._formatAfterSaleRow(row, app)); // 工作列表:批量补充货主名称(合约表 store_remask 货主备注,无备注时回退货主公司全称) if (opts.enrichStoreName && list.length > 0) { await this._enrichListStoreNames(list); } return { list, pagination: { page, pageSize, total: count, totalPages, hasPrevious: page > 1, hasNext: page * pageSize < count, }, }; } /** * 快速统计符合条件的售后单数量(用于角标显示,不做分页)。 * 与 list() 共享相同的 where 构建逻辑,但只返回 count。 * * @param {Object} where 标准化 where 条件对象 * @param {Object} [opts] 额外选项 * @param {boolean} [opts.excludeFutureFollowup] 是否排除 followup_at 未到的 pending_feedback 工单 * @return {Promise} { count: number } */ async countPending(where = {}, opts = {}) { const { ctx, app } = this; const { Op } = app.Sequelize; const queryWhere = this._buildListWhere(where, Op); // 工作列表特殊逻辑:pending_feedback 状态的工单,若 followup_at 未到,暂不计数 if (opts.excludeFutureFollowup) { const pendingFeedbackWhere = { [Op.or]: [ { status: { [Op.ne]: 'pending_feedback' } }, { status: 'pending_feedback', [Op.or]: [ { followup_at: null }, { followup_at: { [Op.lte]: app.Sequelize.literal('NOW()') } }, ], }, ], }; if (queryWhere[Op.and]) { queryWhere[Op.and].push(pendingFeedbackWhere); } else { queryWhere[Op.and] = [ pendingFeedbackWhere ]; } } const count = await ctx.model.AfterSale.count({ where: queryWhere, }); return { count }; } /** * 根据标准化 where 条件构建 Sequelize 查询条件。 * * @param {Object} where 标准化 where 条件对象 * @param {Object} Op Sequelize Op 对象 * @return {Object} Sequelize where 条件 */ _buildListWhere(where = {}, Op) { const queryWhere = {}; // 软删除过滤 queryWhere.deleted_at = null; // 直接映射字段 const directFields = [ 'type', 'sub_type', 'status', 'priority', 'role_group', 'claim_status', 'carrier_claim_status', 'after_sale_no', 'waybill_no', 'order_delivery_no', 'entry_order_no', 'order_stockout_no', 'receiving_no', 'warehouse_id', 'store_id', 'creator_id', ]; for (const field of directFields) { if (where[field] !== undefined && where[field] !== null) { queryWhere[field] = this._resolveConditionValue(where[field], Op); } } // 快捷搜索:在 after_sale_no / title / waybill_no 等字段中模糊搜索 if (where.quickWhere !== undefined && where.quickWhere !== null) { const quickValue = this._extractConditionValue(where.quickWhere); if (quickValue !== undefined && quickValue !== null && String(quickValue).trim() !== '') { const likePattern = { [Op.like]: `%${String(quickValue).trim()}%` }; queryWhere[Op.or] = [ { after_sale_no: likePattern }, { title: likePattern }, { waybill_no: likePattern }, { order_delivery_no: likePattern }, { entry_order_no: likePattern }, { order_stockout_no: likePattern }, { receiving_no: likePattern }, ]; } } return queryWhere; } /** * 解析标准化条件值为 Sequelize 可用的条件对象。 * * @param {*} condition 标准化条件(可能是 {operator, value} 或直接值) * @param {Object} Op Sequelize Op 对象 * @return {*} Sequelize 条件 */ _resolveConditionValue(condition, Op) { if (condition && typeof condition === 'object' && !Array.isArray(condition)) { const operator = condition.operator; const value = condition.value; if (!operator) { return value; } switch (operator) { case 'eq': return value; case 'ne': return { [Op.ne]: value }; case 'in': return { [Op.in]: Array.isArray(value) ? value : [ value ] }; case 'notin': return { [Op.notIn]: Array.isArray(value) ? value : [ value ] }; case 'like': return { [Op.like]: `%${value}%` }; case 'gt': return { [Op.gt]: value }; case 'gte': return { [Op.gte]: value }; case 'lt': return { [Op.lt]: value }; case 'lte': return { [Op.lte]: value }; case 'between': return { [Op.between]: Array.isArray(value) ? value : [ value ] }; default: return value; } } return condition; } /** * 从条件对象中提取原始 value。 * * @param {*} condition 标准化条件 * @return {*} 原始值 */ _extractConditionValue(condition) { if (condition && typeof condition === 'object' && !Array.isArray(condition)) { if ('value' in condition) { return condition.value; } } return condition; } /** * 根据 sort 参数构建 Sequelize 排序数组。 * * @param {Object} sort 排序参数 * @param {string} [sort.sortField] 排序字段 * @param {string} [sort.sort_order] 排序顺序 * @param {string} [sort.sortOrder] 排序顺序(驼峰) * @return {Array>} Sequelize order 数组 */ _buildListOrder(sort = {}) { const sortField = sort.sortField || sort.sort_field || 'updated_at'; const sortOrderRaw = (sort.sortOrder || sort.sort_order || 'desc').toLowerCase(); const sortOrder = sortOrderRaw === 'asc' ? 'ASC' : 'DESC'; // 允许排序的字段白名单 const allowedSortFields = new Set([ 'id', 'after_sale_no', 'type', 'sub_type', 'status', 'priority', 'role_group', 'created_at', 'updated_at', 'resolved_at', 'claim_status', 'carrier_claim_status', ]); const safeSortField = allowedSortFields.has(sortField) ? sortField : 'created_at'; return [[ safeSortField, sortOrder ]]; } // =========================== // 明细查询 // =========================== /** * 售后单明细查询,包含主表信息、步骤列表及附件。 * 售后主表 description(详细描述)非空时,默认作为第一条 step 输出 * (虚拟步骤:id=null、is_virtual=true、action=售后描述、remark=description,不落库)。 * 若关联了订单(order_delivery_id),自动补充收件人/发件人/订单明细/打包视频。 * 若关联了货主(store_id),自动补充货主合约备注。 * * @param {number} id 售后单主键ID * @return {Promise} 售后单明细,包含主表、步骤列表(含附件)、关联单据详情 * @throws {Error} 售后单不存在时抛出 */ async getDetail(id) { const { ctx, app } = this; // 查询主表 const afterSale = await ctx.model.AfterSale.findOne({ where: { id, deleted_at: null }, raw: true, }); if (!afterSale) { throw new Error('售后单不存在'); } // 查询步骤列表(按创建时间升序) const steps = await ctx.model.AfterSaleDetail.findAll({ where: { after_sale_id: id, deleted_at: null }, order: [[ 'created_at', 'ASC' ]], raw: true, }); // 查询步骤附件 const stepsWithAttachments = await this._enrichStepsWithAttachments(steps); // 格式化时间字段 const formatRow = row => this._formatAfterSaleRow(row, app); // 补充关联单据详情 const related = await this._enrichAfterSaleDetail(afterSale); // 默认详细描述作为第一条 step 输出(虚拟步骤,不落库) let finalSteps = stepsWithAttachments; if (afterSale.description && String(afterSale.description).trim()) { finalSteps = [{ id: null, after_sale_id: afterSale.id, step_status: 'pending', operator_id: null, operator_snapshot: null, action: '售后描述', remark: afterSale.description, started_at: null, completed_at: null, created_at: afterSale.created_at, attachments: [], is_virtual: true, }, ...stepsWithAttachments ]; } // 开始处理时间:取首条真实步骤记录的创建时间(不含默认描述虚拟步骤) const firstStep = steps[0]; const startedAt = firstStep ? (firstStep.created_at ? app.formatDate(firstStep.created_at) : null) : null; return { after_sale: { ...formatRow(afterSale), started_at: startedAt }, steps: finalSteps.map(formatRow), related, }; } /** * 根据售后单关联的业务单据ID,补充关联详情。 * 包括:订单信息(收件人/发件人/明细/打包视频)、货主合约备注。 * * @param {Object} afterSale 售后主表记录 * @return {Promise} 关联详情对象 */ async _enrichAfterSaleDetail(afterSale) { const { ctx } = this; const related = {}; // ======= 1. 关联订单详情 ======= // 统一使用 order_id const resolvedOrderId = afterSale.order_id; if (resolvedOrderId) { try { related.order = await this._resolveOrderDetail( resolvedOrderId, afterSale.warehouse_id ); } catch (err) { ctx.logger.warn(`[_enrichAfterSaleDetail] 解析订单详情失败 id=${resolvedOrderId}: ${err.message}`); } } // ======= 2. 关联运单详情(快递公司 + 接口) ======= if (afterSale.waybill_id) { try { related.waybill = await this._resolveWaybillDetail(afterSale.waybill_id); } catch (err) { ctx.logger.warn(`[_enrichAfterSaleDetail] 解析运单详情失败 id=${afterSale.waybill_id}: ${err.message}`); } } // ======= 3. 货主合约备注 ======= if (afterSale.store_id && afterSale.warehouse_id) { try { related.store_contract = await this._resolveStoreContractNote( afterSale.store_id, afterSale.warehouse_id ); } catch (err) { ctx.logger.warn(`[_enrichAfterSaleDetail] 解析货主合约备注失败 store_id=${afterSale.store_id}: ${err.message}`); } } return related; } /** * 解析关联订单的详细信息:收件人、发件人、订单明细、打包视频。 * * @param {number} orderDeliveryId 发货订单ID * @param {number} warehouseId 仓库ID * @return {Promise} 订单详情,查询失败返回 null */ async _resolveOrderDetail(orderDeliveryId, warehouseId) { const { ctx, app } = this; try { // 1. 查询订单主记录:优先按订单 id 序列表(wms_order_id_location_{warehouseId}) // 定位订单所在车道直接查对应分表,未命中再按 current → history → dispatch → outsourced // 遍历回退,最后回退基表(存量订单) let order = null; let preferredLane = null; const factory = ctx.model.OrderDeliveryFactory; if (factory && typeof factory.getCurrentModel === 'function') { const laneLabels = [ 'current', 'history', 'dispatch', 'outsourced' ]; const laneGetters = { current: () => factory.getCurrentModel(warehouseId), history: () => factory.getHistoryModel(warehouseId), dispatch: () => factory.getDispatchModel(warehouseId), outsourced: () => factory.getOutsourcedModel(warehouseId), }; // 序列表定位优先:命中车道先查对应分表 try { if (typeof factory.getOrderLocation === 'function') { const location = await factory.getOrderLocation(orderDeliveryId, warehouseId); if (location && laneGetters[location]) { preferredLane = String(location); } } } catch (err) { ctx.logger.warn(`[_resolveOrderDetail] 序列表定位失败: ${err.message}`); } const orderedLanes = preferredLane ? [ preferredLane, ...laneLabels.filter(label => label !== preferredLane) ] : laneLabels; for (const lane of orderedLanes) { try { const model = await laneGetters[lane](); if (!model || typeof model.findOne !== 'function') continue; const row = await model.findOne({ where: { id: orderDeliveryId }, raw: true, }); if (row) { order = row; break; } } catch (err) { ctx.logger.warn(`[_resolveOrderDetail] 分表 ${lane} 查询失败: ${err.message}`); } } } // 分表均未命中:回退基表(存量订单) if (!order) { try { order = await ctx.model.OrderDelivery.findOne({ where: { id: orderDeliveryId }, attributes: [ 'id', 'name', 'tel', 'mobile', 'email', 'zip_code', 'country_code', 'province', 'city', 'area', 'town', 'detail_address', 'store_id', 'items', ], raw: true, }); } catch (err) { ctx.logger.warn(`[_resolveOrderDetail] 主表查询失败: ${err.message}`); } } if (!order) { ctx.logger.info(`[_resolveOrderDetail] 未找到订单 id=${orderDeliveryId} warehouseId=${warehouseId}`); return null; } ctx.logger.info(`[_resolveOrderDetail] 找到订单 id=${orderDeliveryId} code=${order.delivery_order_code} status=${order.status}`); // 2. 构建收件人信息 const recipient = { name: order.name || '', tel: order.tel || '', mobile: order.mobile || '', email: order.email || '', zip_code: order.zip_code || '', country: order.country_code || '', province: order.province || '', city: order.city || '', district: order.district || '', town: order.town || '', address: order.detail_address || '', }; // 3. 构建发件人信息(从货主 subject_config 中取) let sender = null; if (order.store_id) { try { const store = await ctx.model.Store.findOne({ where: { id: order.store_id }, attributes: [ 'id', 'subject_config', 'company_name' ], raw: true, }); if (store) { let subjectConfig = store.subject_config; if (typeof subjectConfig === 'string') { try { subjectConfig = JSON.parse(subjectConfig); } catch { subjectConfig = {}; } } sender = { name: (subjectConfig && subjectConfig.sender_name) || store.company_name || '', tel: (subjectConfig && subjectConfig.sender_tel) || '', province: (subjectConfig && subjectConfig.province_name) || '', city: (subjectConfig && subjectConfig.city_name) || '', district: (subjectConfig && subjectConfig.district_name) || '', town: (subjectConfig && subjectConfig.town_name) || '', address: (subjectConfig && subjectConfig.address) || '', }; } } catch (err) { ctx.logger.warn(`[_resolveOrderDetail] 查询发件人信息失败: ${err.message}`); } } // 4. 订单明细(优先 order.items JSON,为空时回退到分表查询) let orderItems = []; if (order.items) { try { const parsed = typeof order.items === 'string' ? JSON.parse(order.items) : order.items; orderItems = Array.isArray(parsed) ? parsed : []; } catch { // items 解析失败,忽略 } } // 回退:若 items 为空且 OrderItemsFactory 可用,从分表查询(序列表定位车道优先) if (orderItems.length === 0 && ctx.model.OrderItemsFactory) { try { const itemsFactory = ctx.model.OrderItemsFactory; const itemsLaneLabels = [ 'current', 'history', 'dispatch' ]; const itemsLaneGetters = { current: () => itemsFactory.getCurrentModel(warehouseId), history: () => itemsFactory.getHistoryModel(warehouseId), dispatch: () => itemsFactory.getDispatchModel(warehouseId), }; const orderedItemsLanes = preferredLane && itemsLaneGetters[preferredLane] ? [ preferredLane, ...itemsLaneLabels.filter(label => label !== preferredLane) ] : itemsLaneLabels; let dbItems = []; for (const lane of orderedItemsLanes) { try { const itemsModel = await itemsLaneGetters[lane](); if (!itemsModel || typeof itemsModel.findAll !== 'function') continue; const laneRows = await itemsModel.findAll({ where: { order_id: orderDeliveryId }, raw: true, }); if (laneRows && laneRows.length > 0) { dbItems = laneRows; break; } } catch (err) { ctx.logger.warn(`[_resolveOrderDetail] 商品明细分表 ${lane} 查询失败: ${err.message}`); } } if (dbItems.length > 0) { // 收集 stock_id 用于批量查库存详情 const stockIds = dbItems .map(item => Number(item.stock_id)) .filter(id => Number.isInteger(id) && id > 0); // 批量获取库存详情(带缓存的并行查询:条码 + 图片 + 库存属性) const stockDetailsMap = new Map(); if (stockIds.length > 0) { try { const details = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId, cacheTTL: 300, }); for (const detail of details) { stockDetailsMap.set(detail.id, detail); } } catch (err) { ctx.logger.warn(`[_resolveOrderDetail] 批量获取库存详情失败: ${err.message}`); } } orderItems = dbItems.map(item => { const stock = stockDetailsMap.get(Number(item.stock_id)) || {}; return { id: item.id, order_line_no: item.order_line_no || '', item_code: item.item_code || stock.item_code || '', item_name: item.item_name || stock.item_name || '', sku_property: stock.sku_property || '', quantity: stock.quantity || 0, locked_quantity: stock.locked_quantity || 0, is_batch_mgmt: stock.is_batch_mgmt || 'N', is_shelf_life_mgmt: stock.is_shelf_life_mgmt || 'N', is_images: stock.is_images || 'N', store_id: stock.store_id || null, packing_requirements: stock.packing_requirements || '', stock_unit: stock.stock_unit || '', image_url: stock.image_url || [], barcodes: stock.barcodes || [], plan_qty: item.plan_qty || 0, stock_id: item.stock_id || null, order_item_id: item.id, order_id: orderDeliveryId, }; }); ctx.logger.info(`[_resolveOrderDetail] 从分表加载 ${orderItems.length} 条明细(含库存详情)`); } } catch (err) { ctx.logger.warn(`[_resolveOrderDetail] 分表查询商品明细失败: ${err.message}`); } } // 5. 打包视频 const packVideos = []; try { const packTasks = await ctx.model.PackTask.findAll({ where: { order_id: orderDeliveryId, deleted_at: null }, include: [ { model: ctx.model.PackTaskVideo, as: 'videos', where: { deleted_at: null }, required: false, }, ], order: [[ 'create_time', 'DESC' ]], raw: false, }); for (const task of packTasks) { const taskJson = task.toJSON ? task.toJSON() : task; const videos = (taskJson.videos || []).map(v => ({ id: v.id, video_url: v.video_url, camera_id: v.camera_id, status: v.status, created_at: v.created_at ? app.formatDate(v.created_at) : null, })); packVideos.push({ pack_task_id: taskJson.id, status: taskJson.status, pack_quantity: taskJson.pack_quantity, start_time: taskJson.start_time ? app.formatDate(taskJson.start_time) : null, end_time: taskJson.end_time ? app.formatDate(taskJson.end_time) : null, operator_text: taskJson.operator_text || '', videos, }); } } catch (err) { ctx.logger.warn(`[_resolveOrderDetail] 查询打包视频失败: ${err.message}`); } // 6. 组装返回 return { id: order.id, delivery_order_code: order.delivery_order_code || '', warehouse_id: order.warehouse_id, store_id: order.store_id, // 重量(g) items_weight: order.items_weight || 0, // 波次 wave_id: order.wave_id || 0, wave_no: order.wave_no || '', // 来源 platform_name: order.source_platform_name || '', source_order_codes: order.source_order_codes || '', // 创建来源渠道 create_channel: order.create_channel || '', create_channel_label: this._getCreateChannelLabel(order.create_channel), // 状态机 sync_status: order.sync_status || 'padding', inspection_status: order.inspection_status || 'none', storage_status: order.storage_status || 'none', post_status: order.post_status || 'none', print_status: order.print_status || 'none', pick_status: order.pick_status || 'none', pack_status: order.pack_status || 'none', intercept_status: order.intercept_status || 'none', // 数量 items_count: order.items_count, items_total: order.items_total, // 金额 total_amount: order.total_amount, item_amount: order.item_amount, // 收件人 / 发件人 / 明细 / 打包视频 recipient, sender, items: orderItems, pack_videos: packVideos, }; } catch (err) { ctx.logger.warn(`[_resolveOrderDetail] 整体异常 id=${orderDeliveryId}: ${err.message}`, err.stack); return null; } } /** * 解析货主在当前仓库下的合约备注。 * * @param {number} storeId 货主ID * @param {number} warehouseId 仓库ID * @return {Promise} 合约备注信息 */ async _resolveStoreContractNote(storeId, warehouseId) { const { ctx } = this; const sw = await ctx.model.StoreWarehouse.findOne({ where: { store_id: storeId, warehouse_id: warehouseId }, attributes: [ 'id', 'store_remask', 'warehouse_remask', 'store_use_status', 'warehouse_use_status' ], raw: true, }); if (!sw) return null; return { contract_id: sw.id, store_remask: sw.store_remask || '', warehouse_remask: sw.warehouse_remask || '', store_use_status: sw.store_use_status, warehouse_use_status: sw.warehouse_use_status, }; } /** * 解析关联运单的快递公司名称与使用的物流接口。 * * @param {number} waybillId 运单ID(wms_order_express.id) * @return {Promise} 运单详情,查询失败返回 null */ async _resolveWaybillDetail(waybillId) { const { ctx } = this; const waybill = await ctx.model.OrderExpress.findOne({ where: { id: waybillId }, attributes: [ 'id', 'waybill_code', 'order_id', 'logistics_code', 'logistics_name', 'logistics_interface_id', 'logistics_interface_name', 'status', 'is_back', 'is_intercept', 'warehouse_id', 'create_at', ], raw: true, }); if (!waybill) return null; return { id: waybill.id, waybill_code: waybill.waybill_code || '', order_id: waybill.order_id, logistics_code: waybill.logistics_code || '', logistics_name: waybill.logistics_name || '', logistics_interface_id: waybill.logistics_interface_id, logistics_interface_name: waybill.logistics_interface_name || '', status: waybill.status, is_back: waybill.is_back || 'N', is_intercept: waybill.is_intercept || 'N', warehouse_id: waybill.warehouse_id, create_at: waybill.create_at ? ctx.app.formatDate(waybill.create_at) : null, }; } /** * 为步骤列表补充附件信息。 * * @param {Array} steps 步骤列表 * @return {Promise>} 含附件信息的步骤列表 */ async _enrichStepsWithAttachments(steps = []) { const { ctx } = this; if (!steps || steps.length === 0) { return []; } const detailIds = steps.map(s => s.id).filter(Boolean); if (detailIds.length === 0) { return steps; } // 查询所有步骤的附件引用 const references = await ctx.model.FileReference.findAll({ where: { business_type: 'after_sale_detail', business_id: { [ctx.app.Sequelize.Op.in]: detailIds.map(String) }, }, include: [ { model: ctx.model.File, as: 'file', attributes: [ 'id', 'file_key', 'file_url', 'file_name', 'file_size', 'mime_type' ], required: false, }, ], raw: false, }); // 构建 detailId → files 映射 const attachmentMap = new Map(); for (const ref of references) { const refJson = ref.toJSON ? ref.toJSON() : ref; const detailId = Number(refJson.business_id); const fileInfo = refJson.file || null; if (!detailId) continue; if (!attachmentMap.has(detailId)) { attachmentMap.set(detailId, []); } if (fileInfo) { attachmentMap.get(detailId).push({ id: fileInfo.id, file_key: fileInfo.file_key, file_url: fileInfo.file_url, file_name: fileInfo.file_name, file_size: fileInfo.file_size, mime_type: fileInfo.mime_type, }); } } // 为每个步骤挂载附件 return steps.map(step => ({ ...step, attachments: attachmentMap.get(step.id) || [], })); } // =========================== // 创建售后单 // =========================== /** * 创建售后单主表记录。 * * @param {Object} data 售后单数据 * @param {number} data.warehouse_id 仓库ID * @param {string} data.after_sale_no 售后单号 * @param {string} data.type 售后类型 * @param {string} data.sub_type 售后子类型 * @param {string} data.title 售后标题 * @param {string} [data.description] 售后描述 * @param {number} [data.priority] 优先级 * @param {number} data.creator_id 创建人ID * @param {string} [data.role_group] 当前处理角色组 * @param {string} [data.status] 售后状态 * @param {Object} [transaction] Sequelize 事务对象 * @return {Promise} 创建的售后单记录 */ async create(data, transaction = null) { const { ctx, app } = this; const record = await ctx.model.AfterSale.create(data, { transaction }); const json = record && record.toJSON ? record.toJSON() : record; return this._formatAfterSaleRow(json, app); } /** * 批量补充列表行的货主名称 store_name。 * 货主名称优先取合约表 wms_store_warehouse.store_remask(货主备注名称), * 无合约或备注为空时回退 wms_store.company_name(公司全称)。 * * @param {Object[]} list 售后单列表行(原地补充 store_name 字段) * @return {Promise} */ async _enrichListStoreNames(list) { const { ctx } = this; const { Op } = ctx.app.Sequelize; const storeIds = [ ...new Set(list.map(row => row.store_id).filter(Boolean)) ]; const warehouseIds = [ ...new Set(list.map(row => row.warehouse_id).filter(Boolean)) ]; if (storeIds.length === 0) { list.forEach(row => { row.store_name = ''; }); return; } // 1. 合约表货主备注名称(store_id + warehouse_id 维度) let contractMap = {}; if (warehouseIds.length > 0) { const swRows = await ctx.model.StoreWarehouse.findAll({ where: { store_id: { [Op.in]: storeIds }, warehouse_id: { [Op.in]: warehouseIds }, }, attributes: [ 'store_id', 'warehouse_id', 'store_remask' ], raw: true, }); contractMap = swRows.reduce((acc, sw) => { acc[`${sw.store_id}_${sw.warehouse_id}`] = sw.store_remask || ''; return acc; }, {}); } // 2. 货主公司全称兜底 let storeMap = {}; const storeRows = await ctx.model.Store.findAll({ where: { id: { [Op.in]: storeIds } }, attributes: [ 'id', 'company_name' ], raw: true, }); storeMap = storeRows.reduce((acc, store) => { acc[store.id] = store.company_name || ''; return acc; }, {}); list.forEach(row => { const contractRemask = contractMap[`${row.store_id}_${row.warehouse_id}`] || ''; row.store_name = contractRemask || storeMap[row.store_id] || ''; }); } // =========================== // 更新售后单 // =========================== /** * 更新售后单主表字段。 * * @param {number} id 售后单主键ID * @param {Object} data 需要更新的字段键值对 * @param {Object} [transaction] Sequelize 事务对象 * @return {Promise} 更新后的售后单记录 * @throws {Error} 售后单不存在时抛出 */ async update(id, data, transaction = null) { const { ctx, app } = this; const record = await ctx.model.AfterSale.findOne({ where: { id, deleted_at: null }, transaction, }); if (!record) { throw new Error('售后单不存在'); } await record.update(data, { transaction }); const json = record && record.toJSON ? record.toJSON() : record; return this._formatAfterSaleRow(json, app); } /** * 格式化售后单记录的时间字段。 * @param {Object} row 原始数据库行 * @param {Object} app Egg app 实例 * @return {Object} 格式化后的行 */ _formatAfterSaleRow(row, app) { if (!row) return row; return { ...row, created_at: row.created_at ? app.formatDate(row.created_at) : null, updated_at: row.updated_at ? app.formatDate(row.updated_at) : null, resolved_at: row.resolved_at ? app.formatDate(row.resolved_at) : null, followup_at: row.followup_at ? app.formatDate(row.followup_at) : null, started_at: row.started_at ? app.formatDate(row.started_at) : null, completed_at: row.completed_at ? app.formatDate(row.completed_at) : null, }; } // =========================== // 步骤记录 // =========================== /** * 写入一条售后进度步骤记录。 * * @param {number} afterSaleId 售后单主键ID * @param {Object} stepData 步骤数据 * @param {number} [stepData.step_status=2] 步骤状态(0=待开始,1=进行中,2=已完成,3=已跳过) * @param {number} [stepData.operator_id] 操作人账户ID * @param {string} [stepData.operator_snapshot] 操作人信息快照 JSON * @param {string} [stepData.action] 操作动作描述 * @param {string} [stepData.remark] 处理备注 * @param {Date} [stepData.started_at] 步骤开始时间 * @param {Date} [stepData.completed_at] 步骤完成时间 * @param {Object} [transaction] Sequelize 事务对象 * @return {Promise} 创建的步骤记录 */ async addStep(afterSaleId, stepData = {}, transaction = null) { const { ctx } = this; const now = new Date(); const record = await ctx.model.AfterSaleDetail.create({ after_sale_id: afterSaleId, step_status: stepData.step_status !== undefined ? stepData.step_status : 'processing', operator_id: stepData.operator_id || null, operator_snapshot: stepData.operator_snapshot || null, action: stepData.action || null, remark: stepData.remark || null, started_at: stepData.started_at || now, completed_at: stepData.completed_at || now, created_at: now, }, { transaction }); return record && record.toJSON ? record.toJSON() : record; } // =========================== // 附件绑定 // =========================== /** * 将文件绑定到售后步骤(批量)。 * 通过 wms_file_reference 表建立关联。 * * @param {number} detailId 售后步骤ID * @param {number[]} fileIds 文件ID列表 * @param {Object} [transaction] Sequelize 事务对象 * @return {Promise>} 创建的文件引用记录列表 */ async bindAttachments(detailId, fileIds = [], transaction = null) { const { ctx } = this; if (!detailId || !Array.isArray(fileIds) || fileIds.length === 0) { return []; } const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0; const createdBy = ctx.user ? String(ctx.user.employees_name || ctx.user.real_name || ctx.user.name || ctx.user.id || '') : ''; const references = []; for (const fileId of fileIds) { // 检查是否已存在绑定,防止重复 const existing = await ctx.model.FileReference.findOne({ where: { file_id: fileId, warehouse_id: warehouseId, business_type: 'after_sale_detail', business_id: String(detailId), }, transaction, }); if (existing) { references.push(existing); continue; } const reference = await ctx.model.FileReference.create({ file_id: fileId, warehouse_id: warehouseId, business_type: 'after_sale_detail', business_id: String(detailId), display_order: 0, created_by: createdBy, created_at: new Date(), }, { transaction }); references.push(reference); } return references.map(r => (r && r.toJSON ? r.toJSON() : r)); } // =========================== // 转单 // =========================== /** * 转单:更新售后单 role_group 并写入步骤记录。 * * @param {Object} params 转单参数 * @param {number} params.id 售后单主键ID * @param {string} params.targetRoleGroup 目标角色组 * @param {string} params.remark 转单备注 * @param {number} params.operatorId 操作人ID * @param {string} params.operatorSnapshot 操作人快照 JSON * @return {Promise} 更新后的售后单记录 */ async transfer(params = {}) { const { id, targetRoleGroup, remark, operatorId, operatorSnapshot } = params; const transaction = await this.ctx.model.transaction(); try { // 更新 role_group const updated = await this.update(id, { role_group: targetRoleGroup, updated_at: new Date(), }, transaction); // 写入步骤记录(step_status 与主表当前 status 一致) await this.addStep(id, { step_status: updated.status || 'processing', operator_id: operatorId, operator_snapshot: operatorSnapshot, action: '转单', remark: remark || `转至${targetRoleGroup}`, started_at: new Date(), completed_at: new Date(), }, transaction); await transaction.commit(); return updated; } catch (error) { await transaction.rollback(); throw error; } } // =========================== // 处理工单 // =========================== /** * 处理工单:校验权限 → 写步骤 → 可选更新状态 → 变量回设 → 绑附件。 * * @param {Object} params 处理参数 * @param {number} params.id 售后单主键ID * @param {string|null} params.remark 处理备注 * @param {string|null} params.targetStatus 目标售后状态 * @param {string|null} params.resolution 完结处理结果 * @param {number[]} params.attachmentIds 附件文件ID列表 * @param {number} params.operatorId 操作人ID * @param {string} params.operatorSnapshot 操作人快照 JSON * @param {number} params.warehouseId 仓库ID * @param {boolean} [params.notifyGroup] 是否将处理备注发送到对应货主售后群(内部自动处理不传) * @return {Promise} 处理结果,包含更新后的售后单、步骤记录和通知群数量 * @throws {Error} 售后单不存在或权限不足时抛出 */ async handleWorkOrder(params = {}) { const { id, remark, targetStatus, resolution, attachmentIds, operatorId, operatorSnapshot, warehouseId, notifyGroup, } = params; const { ctx } = this; // 1. 查询售后单并校验存在性(限定仓库范围) const afterSale = await ctx.model.AfterSale.findOne({ where: { id, warehouse_id: warehouseId, deleted_at: null }, }); if (!afterSale) { throw new Error('售后单不存在'); } // 2. status 不填或填错默认 processing;pending 是创建默认值,不适用于处理操作 const ALLOWED_STATUSES = Object.keys(ctx.model.AfterSale.AFTER_SALE_STATUS).filter(s => s !== 'pending'); const safeStatus = (targetStatus && ALLOWED_STATUSES.includes(targetStatus)) ? targetStatus : 'processing'; // 3. 校验 role_group 权限:操作人必须有对应 role_group 的处理权限。 // 实际权限解析已在方法层(systemMethods/afterSale.js)通过 block 权限完成, // 此处仅做兜底校验。 const allowedRoleGroups = [ 'customer_service', 'warehouse', 'finance' ]; const currentRoleGroup = afterSale.role_group; if (currentRoleGroup && !allowedRoleGroups.includes(currentRoleGroup)) { throw new Error('无权限处理当前角色组的售后单'); } // 4. 开启事务 const transaction = await ctx.model.transaction(); try { const now = new Date(); // 5. 写入步骤记录(action 由服务端固定为"处理工单",step_status 同步主表 status) const step = await this.addStep(id, { step_status: safeStatus, operator_id: operatorId, operator_snapshot: operatorSnapshot, action: '处理工单', remark, started_at: now, completed_at: now, }, transaction); // 6. 绑定附件 if (Array.isArray(attachmentIds) && attachmentIds.length > 0) { await this.bindAttachments(step.id, attachmentIds, transaction); } // 7. 更新售后单状态 const updateFields = { updated_at: now }; updateFields.status = safeStatus; // 若完结,写入 resolution 和 resolved_at;清除 followup_at if (safeStatus === 'completed') { updateFields.resolution = resolution || null; updateFields.resolved_at = now; updateFields.followup_at = null; } // 若设为 pending_feedback:按仓库配置自动计算下次跟进时间 if (safeStatus === 'pending_feedback') { const hours = await this._resolveFollowupHours(afterSale.warehouse_id, afterSale.type, afterSale.sub_type); ctx.logger.info( '[handleWorkOrder] id=%s warehouse=%s type=%s subType=%s hours=%d', id, afterSale.warehouse_id, afterSale.type, afterSale.sub_type, hours ); // 使用数据库 NOW() 确保与查询条件时区一致 updateFields.followup_at = ctx.app.Sequelize.literal(`DATE_ADD(NOW(), INTERVAL ${hours} HOUR)`); } // 8. 若当前角色非客服组且状态非完结,自动回设为客服组 if (currentRoleGroup && currentRoleGroup !== 'customer_service' && safeStatus !== 'completed') { updateFields.role_group = 'customer_service'; } await afterSale.update(updateFields, { transaction }); await transaction.commit(); // 9. 处理备注发送到对应的货主售后群(仅交互处理传入 notifyGroup 时触发,不转发快递群) let notifiedGroupCount = 0; if (notifyGroup && remark && String(remark).trim()) { try { const remarkText = String(remark).trim(); const asRow = afterSale.toJSON ? afterSale.toJSON() : afterSale; // 定位货主:优先工单 store_id,缺失时从来源消息所在群反查 let notifyStoreId = Number(asRow.store_id || 0); if (!notifyStoreId && asRow.inbox_message_id) { try { const inbound = await ctx.model.InboxMessage.findByPk(asRow.inbox_message_id, { attributes: [ 'group_id' ], raw: true, }); if (inbound && inbound.group_id) { const originGroup = await ctx.model.InboxGroup.findOne({ attributes: [ 'store_id' ], where: { group_id: inbound.group_id, warehouse_id: warehouseId, is_blocked: 0, }, raw: true, }); if (originGroup && originGroup.store_id) { notifyStoreId = Number(originGroup.store_id); } } } catch (originErr) { ctx.logger.warn(`[handleWorkOrder] 反查来源群货主失败 id=${id}: ${originErr.message}`); } } if (notifyStoreId) { const storeGroups = await ctx.service.systems.inbox.group.findStoreAfterSalesGroups({ storeIds: [ notifyStoreId ], warehouseId, }); // 通知文案只给运单号 + 处理内容(售后单号对客户无意义) const waybillNo = String(asRow.waybill_no || '').trim(); const content = waybillNo ? `运单${waybillNo} 处理备注:\n${remarkText}` : `处理备注:\n${remarkText}`; for (const g of storeGroups) { if (!g.group_id) continue; ctx.service.inbox.processor.pushSystemNotification({ warehouse_id: warehouseId, group_id: g.group_id, group_name: g.group_name || '', content, ext_data: g.ext_data || null, }); notifiedGroupCount += 1; } } ctx.logger.info( `[handleWorkOrder] 处理备注发送到货主售后群 id=${id} store=${notifyStoreId} notified=${notifiedGroupCount}` ); } catch (notifyErr) { ctx.logger.warn(`[handleWorkOrder] 处理备注发送群失败 id=${id}: ${notifyErr.message}`); } } const updatedAfterSale = afterSale.toJSON ? afterSale.toJSON() : afterSale; return { after_sale: this._formatAfterSaleRow(updatedAfterSale, ctx.app), step, notified_groups: notifiedGroupCount, }; } catch (error) { await transaction.rollback(); throw error; } } // =========================== // 拦截链路:批量创建工单 + 通知快递群 // =========================== /** * 拦截链路共享方法:根据订单 ID 查找运单,幂等创建售后工单,并按快递分组通知售后群。 * 用于 batchIntercept / confirmIntercept / Qimen cancel / OpenAPI cancel 等入口统一调用。 * * @param {Object} params 参数。 * @param {number[]} params.orderIds 订单 ID 列表。 * @param {number} params.warehouseId 仓库 ID。 * @param {string} params.creatorLabel 创建人标签(如 "系统"、"王小明")。 * @param {string} [params.reason] 拦截原因。 * @return {Promise<{ createdCount: number, notifiedCount: number }>} 创建与通知统计。 */ async createInterceptWorkOrdersAndNotify(params = {}) { const { ctx } = this; const { orderIds, warehouseId, creatorLabel, reason } = params; if (!Array.isArray(orderIds) || orderIds.length === 0 || !warehouseId) { return { createdCount: 0, notifiedCount: 0 }; } try { // 1. 查询运单信息 const expressList = await ctx.model.OrderExpress.findAll({ attributes: [ 'id', 'waybill_code', 'logistics_name', 'store_id', 'logistics_interface_id', 'logistics_code', 'order_id', ], where: { order_id: { [ctx.app.Sequelize.Op.in]: orderIds }, warehouse_id: warehouseId, }, raw: true, }); if (expressList.length === 0) { return { createdCount: 0, notifiedCount: 0 }; } // 2. 幂等检查:已有未完结的拦截工单不再重复创建 const expressIds = expressList.map(e => e.id); const existingASList = await ctx.model.AfterSale.findAll({ attributes: [ 'waybill_id' ], where: { waybill_id: { [ctx.app.Sequelize.Op.in]: expressIds }, type: 'order', sub_type: 'intercept', status: { [ctx.app.Sequelize.Op.notIn]: [ 'completed', 'closed', 'cancelled' ] }, }, raw: true, }); const existingWaybillIds = new Set(existingASList.map(r => r.waybill_id)); const toCreate = expressList.filter(e => !existingWaybillIds.has(e.id)); if (toCreate.length === 0) { return { createdCount: 0, notifiedCount: 0 }; } // 3. 批量创建工单 const label = creatorLabel || '系统'; let createdCount = 0; const createdWaybillIds = []; for (const e of toCreate) { try { const afterSaleNo = await ctx.service.systemMethods.afterSale.generateAfterSaleNo(warehouseId); const descParts = [ `发起人: ${label}`, `运单号: ${e.waybill_code}`, `快递公司: ${e.logistics_name || '未知'}`, reason ? `拦截原因: ${reason}` : '', ].filter(Boolean).join('\n'); await this.create({ warehouse_id: warehouseId, after_sale_no: afterSaleNo, type: 'order', sub_type: 'intercept', title: `[系统拦截] ${e.waybill_code}`, description: descParts, priority: 10, creator_id: 0, inbox_message_id: null, role_group: 'customer_service', status: 'pending', waybill_id: e.id, waybill_no: e.waybill_code, store_id: e.store_id || null, order_id: e.order_id || null, }); createdCount += 1; createdWaybillIds.push(e.id); } catch (createErr) { ctx.logger.warn( `[afterSale.createInterceptWorkOrdersAndNotify] 创建工单失败, waybill=${e.waybill_code}, error=${createErr.message}` ); } } // 4. 按快递分组通知售后群 const expressByCode = {}; for (const e of toCreate) { const code = e.logistics_code || '__unknown__'; if (!expressByCode[code]) { expressByCode[code] = { code, interfaceId: e.logistics_interface_id, logisticsName: String(e.logistics_name || '').trim(), waybills: [], }; } expressByCode[code].waybills.push(e.waybill_code); } let notifiedCount = 0; const notifiedWaybillIds = new Set(); // 无对应快递群(或快递无接口)的运单收集后统一降级通知仓库异常群(与货主群缺失降级行为一致) const fallbackEntries = []; for (const [ code, info ] of Object.entries(expressByCode)) { if (code === '__unknown__' || !info.interfaceId) { fallbackEntries.push(info); continue; } try { const { afterSalesGroups } = await ctx.service.systems.inbox.group.findGroupsByExpress({ expressInterfaceId: info.interfaceId, expressCode: code, warehouseId, }); if (afterSalesGroups.length === 0) { fallbackEntries.push(info); continue; } const notifyMsg = info.waybills.join('\n') + '\n拦截'; for (const g of afterSalesGroups) { ctx.service.inbox.processor.pushSystemNotification({ warehouse_id: warehouseId, group_id: g.group_id, group_name: g.group_name, content: notifyMsg, ext_data: g.ext_data || null, }); notifiedCount += 1; } // 标记该快递下所有运单已通知 const codeWaybills = toCreate.filter(e => (e.logistics_code || '__unknown__') === code); codeWaybills.forEach(e => notifiedWaybillIds.add(e.id)); } catch (e) { fallbackEntries.push(info); ctx.logger.warn(`[afterSale] 查售后群失败 code=${code}: ${e.message}`); } } // 4b. 无对应快递群降级:转发仓库异常群,内容前缀标记失败(与货主群缺失降级一致) if (fallbackEntries.length > 0) { try { const exceptionGroups = await ctx.model.InboxGroup.findAll({ attributes: [ 'group_id', 'group_name', 'ext_data' ], where: { warehouse_id: warehouseId, group_type: 'warehouse', sub_type: 'exception', is_blocked: 0, }, raw: true, }); if (exceptionGroups.length > 0) { const labelSet = new Set(); const fallbackLines = []; for (const entry of fallbackEntries) { const label = entry.logisticsName || entry.code || '未知快递'; labelSet.add(label); for (const waybill of entry.waybills) { fallbackLines.push(`${label} ${waybill}`); } } const fallbackContent = `通知快递【${Array.from(labelSet).join('、')}】失败\n${fallbackLines.join('\n')}\n拦截`; for (const g of exceptionGroups) { ctx.service.inbox.processor.pushSystemNotification({ warehouse_id: warehouseId, group_id: g.group_id, group_name: g.group_name, content: fallbackContent, ext_data: g.ext_data || null, }); } ctx.logger.warn('[afterSale.createInterceptWorkOrdersAndNotify] 无对应快递群,已降级通知仓库异常群', { warehouseId, fallbackCount: fallbackEntries.length, exceptionGroupCount: exceptionGroups.length, }); } } catch (fallbackErr) { ctx.logger.warn(`[afterSale] 降级通知异常群失败: ${fallbackErr.message}`); } } // 5. 有通知的工单升级为 pending_feedback if (notifiedWaybillIds.size > 0) { const notifiedWaybillIdArr = [ ...notifiedWaybillIds ]; const hours = await this._resolveFollowupHours(warehouseId, 'order', 'intercept'); await ctx.model.AfterSale.update( { status: 'pending_feedback', followup_at: ctx.app.Sequelize.literal(`DATE_ADD(NOW(), INTERVAL ${hours} HOUR)`), role_group: 'customer_service', }, { where: { waybill_id: { [ctx.app.Sequelize.Op.in]: notifiedWaybillIdArr }, warehouse_id: warehouseId, type: 'order', sub_type: 'intercept', status: 'pending', }, } ); } return { createdCount, notifiedCount }; } catch (error) { ctx.logger.warn(`[afterSale.createInterceptWorkOrdersAndNotify] 整体失败: ${error.message}`); return { createdCount: 0, notifiedCount: 0 }; } } // =========================== // 跟进时间配置 // =========================== /** * 根据仓库配置解析跟进小时数。 * 优先级:policy_config sub_type 精确匹配 → type._default → 整数兜底 → 24h。 * * @param {number} warehouseId 仓库ID * @param {string} type 售后类型 * @param {string} subType 售后子类型 * @return {Promise} 跟进小时数 */ async _resolveFollowupHours(warehouseId, type, subType) { const { ctx } = this; // 仓库配置值的最小有效阈值:≤1 视为未配置的占位值,回退到 DEFAULTS // (实际业务最小合理值为 intercept/urge 的 4h,不存在 0/1h 的跟进场景) const MIN_VALID_FOLLOWUP_HOURS = 2; // 1. 仓库已保存的配置 const sw = await ctx.model.StoreWarehouse.findOne({ where: { warehouse_id: warehouseId }, attributes: [ 'policy_config' ], order: [[ 'id', 'DESC' ]], raw: true, }); ctx.logger.info( '[_resolveFollowupHours] warehouseId=%s type=%s subType=%s hasStoreWarehouse=%s', warehouseId, type, subType, !!(sw && sw.policy_config) ); if (sw && sw.policy_config) { let config = sw.policy_config; if (typeof config === 'string') { try { config = JSON.parse(config); } catch { config = {}; } } const whConfig = config && config.after_sale_followup_hours; ctx.logger.info( '[_resolveFollowupHours] whConfig type=%s value=%s', typeof whConfig, JSON.stringify(whConfig) ); if (whConfig && typeof whConfig === 'object') { const whTypeMap = whConfig[type]; ctx.logger.info( '[_resolveFollowupHours] whTypeMap for type=%s: %s', type, JSON.stringify(whTypeMap) ); // 分支 A:嵌套对象格式 {"order": {"damage": 48, "_default": 24}} if (whTypeMap && typeof whTypeMap === 'object') { if (subType) { const subVal = this._tryParseHours(whTypeMap[subType]); if (typeof subVal === 'number' && subVal >= MIN_VALID_FOLLOWUP_HOURS) { ctx.logger.info('[_resolveFollowupHours] MATCH subType (nested): %s=%dh', subType, subVal); return subVal; } } const defVal = this._tryParseHours(whTypeMap._default); if (typeof defVal === 'number' && defVal >= MIN_VALID_FOLLOWUP_HOURS) { ctx.logger.info('[_resolveFollowupHours] MATCH type._default (nested): %s._default=%dh', type, defVal); return defVal; } } // 分支 B:扁平格式 {"order": "24"} 或 {"order": 24} // 值为字符串或数字,直接作为该 type 下所有 subType 的统一时长 const flatVal = this._tryParseHours(whTypeMap); if (typeof flatVal === 'number' && flatVal >= MIN_VALID_FOLLOWUP_HOURS) { ctx.logger.info('[_resolveFollowupHours] MATCH type flat: %s=%dh', type, flatVal); return flatVal; } } // 分支 C:全局数字 {"after_sale_followup_hours": 24} 或 {"after_sale_followup_hours": "24"} { const globalVal = this._tryParseHours(whConfig); if (typeof globalVal === 'number' && globalVal >= MIN_VALID_FOLLOWUP_HOURS) { ctx.logger.info('[_resolveFollowupHours] MATCH whConfig global: %dh', globalVal); return globalVal; } } ctx.logger.info(`[_resolveFollowupHours] whConfig found but no valid match (all < ${MIN_VALID_FOLLOWUP_HOURS}h or type mismatch), falling to DEFAULTS`); } // 2. 仓库未配置时,使用字段默认值(与 setting.warehouse.getFieldMeta 返回一致) const DEFAULTS = { order: { _default: 24, intercept: 4, urge: 4, change_address: 8, change_carrier: 8, delivery_delay: 12, damage: 48, quality_issue: 48, missing_item: 24 }, receiving: { _default: 24, shortage: 48, damage: 48 }, entry: { _default: 24, shortage: 48, damage: 48 }, stockout: { _default: 24, return_issue: 48, shortage: 48 }, }; const typeDefault = DEFAULTS[type]; if (typeDefault) { if (subType && typeof typeDefault[subType] === 'number') { ctx.logger.info('[_resolveFollowupHours] DEFAULTS subType match: %s=%dh', subType, typeDefault[subType]); return typeDefault[subType]; } if (typeof typeDefault._default === 'number') { ctx.logger.info('[_resolveFollowupHours] DEFAULTS type._default: %s=%dh', type, typeDefault._default); return typeDefault._default; } } // 3. 硬兜底 ctx.logger.warn('[_resolveFollowupHours] FALLBACK 24h for type=%s subType=%s', type, subType); return 24; } /** * 将配置值尝试转为有效的小时数。 * 兼容数字 24 和字符串 "24" 两种格式;无法解析时返回 null。 * * @param {*} raw 原始配置值 * @return {number|null} 有效小时数,或 null */ _tryParseHours(raw) { if (raw === null || raw === undefined || raw === '') return null; if (typeof raw === 'number' && Number.isFinite(raw)) return raw; if (typeof raw === 'string') { const parsed = Number(raw); if (Number.isFinite(parsed)) return parsed; } return null; } // =========================== // 批量设为待反馈 // =========================== /** * 批量将售后工单设为"待反馈"状态,并按仓库配置自动计算 followup_at。 * 对每个工单写入步骤记录,所有操作在同一事务中执行。 * * @param {Object} params 批量操作参数 * @param {number[]} params.ids 售后单主键ID列表 * @param {number} params.operatorId 操作人账户ID * @param {string} params.operatorSnapshot 操作人快照 JSON * @param {string} [params.remark] 统一处理备注(所有工单共用) * @param {number} params.warehouseId 仓库ID(用于权限校验) * @return {Promise} { total, success, failed: [{id, reason}] } */ async batchSetPendingFeedback(params = {}) { const { ids, operatorId, operatorSnapshot, remark, warehouseId } = params; const { ctx } = this; // 1. 入参校验 if (!Array.isArray(ids) || ids.length === 0) { return { total: 0, success: 0, failed: [] }; } const numericIds = ids.map(id => Number(id)).filter(id => Number.isInteger(id) && id > 0); if (numericIds.length === 0) { return { total: 0, success: 0, failed: [] }; } // 2. 查询所有目标工单 const afterSales = await ctx.model.AfterSale.findAll({ where: { id: { [ctx.app.Sequelize.Op.in]: numericIds }, deleted_at: null, }, }); const afterSaleMap = new Map(); for (const record of afterSales) { afterSaleMap.set(record.id, record); } // 3. 预校验 & 分类 const validRecords = []; const failed = []; // 终态不可设为待反馈 const TERMINAL_STATUSES = new Set([ 'completed', 'closed', 'cancelled' ]); for (const id of numericIds) { const record = afterSaleMap.get(id); if (!record) { failed.push({ id, reason: '售后单不存在或已删除' }); continue; } if (TERMINAL_STATUSES.has(record.status)) { failed.push({ id, reason: `工单已完结(${record.status}),不可设为待反馈` }); continue; } if (record.warehouse_id !== warehouseId) { failed.push({ id, reason: '仓库不匹配,无权操作' }); continue; } validRecords.push(record); } // 4. 开启事务,逐条更新 const transaction = await ctx.model.transaction(); try { const now = new Date(); let successCount = 0; for (const record of validRecords) { // 4a. 解析该工单的跟进小时数 const hours = await this._resolveFollowupHours( record.warehouse_id, record.type, record.sub_type ); ctx.logger.info( '[batchSetPendingFeedback] id=%s type=%s subType=%s hours=%d', record.id, record.type, record.sub_type, hours ); // 4b. 写入步骤记录 await this.addStep(record.id, { step_status: 'pending_feedback', operator_id: operatorId, operator_snapshot: operatorSnapshot, action: '设为待反馈', remark: remark || null, started_at: now, completed_at: now, }, transaction); // 4c. 更新主表:status + followup_at + role_group 回客服组 const updateFields = { status: 'pending_feedback', followup_at: ctx.app.Sequelize.literal(`DATE_ADD(NOW(), INTERVAL ${hours} HOUR)`), updated_at: now, }; // 若非客服组,自动回设为客服组(与 handleWorkOrder 行为一致) if (record.role_group && record.role_group !== 'customer_service') { updateFields.role_group = 'customer_service'; } await record.update(updateFields, { transaction }); successCount++; } await transaction.commit(); return { total: numericIds.length, success: successCount, failed, }; } catch (error) { await transaction.rollback(); throw error; } } // =========================== // 批量完结/关闭 // =========================== /** * 批量将售后工单设为完结或关闭状态。 * completed 时自动写入 resolved_at 并清除 followup_at;closed 仅更新状态。 * 对每个工单写入步骤记录,所有操作在同一事务中执行。 * * @param {Object} params 批量操作参数 * @param {number[]} params.ids 售后单主键ID列表 * @param {string} params.status 目标状态:completed | closed * @param {string} [params.resolution] 完结处理结果(仅 status=completed 时写入) * @param {number} params.operatorId 操作人账户ID * @param {string} params.operatorSnapshot 操作人快照 JSON * @param {string} [params.remark] 统一处理备注(所有工单共用) * @param {number} params.warehouseId 仓库ID(用于权限校验) * @return {Promise} { total, success, failed: [{id, reason}] } */ async batchClose(params = {}) { const { ids, status: targetStatus, resolution, operatorId, operatorSnapshot, remark, warehouseId } = params; const { ctx } = this; // 1. 入参校验 const ALLOWED_TARGET_STATUSES = new Set([ 'completed', 'closed' ]); if (!targetStatus || !ALLOWED_TARGET_STATUSES.has(targetStatus)) { return { total: 0, success: 0, failed: [{ id: 0, reason: 'status 必须为 completed 或 closed' }] }; } if (!Array.isArray(ids) || ids.length === 0) { return { total: 0, success: 0, failed: [] }; } const numericIds = ids.map(id => Number(id)).filter(id => Number.isInteger(id) && id > 0); if (numericIds.length === 0) { return { total: 0, success: 0, failed: [] }; } // 2. 查询所有目标工单 const afterSales = await ctx.model.AfterSale.findAll({ where: { id: { [ctx.app.Sequelize.Op.in]: numericIds }, deleted_at: null, }, }); const afterSaleMap = new Map(); for (const record of afterSales) { afterSaleMap.set(record.id, record); } // 3. 预校验 & 分类 const validRecords = []; const failed = []; // 终态不可重复完结/关闭 const TERMINAL_STATUSES = new Set([ 'completed', 'closed', 'cancelled' ]); for (const id of numericIds) { const record = afterSaleMap.get(id); if (!record) { failed.push({ id, reason: '售后单不存在或已删除' }); continue; } if (TERMINAL_STATUSES.has(record.status)) { failed.push({ id, reason: `工单已是终态(${record.status}),不可重复${targetStatus === 'completed' ? '完结' : '关闭'}` }); continue; } if (record.warehouse_id !== warehouseId) { failed.push({ id, reason: '仓库不匹配,无权操作' }); continue; } validRecords.push(record); } // 4. 开启事务,逐条更新 const transaction = await ctx.model.transaction(); try { const now = new Date(); let successCount = 0; // 操作动作名称 const actionName = targetStatus === 'completed' ? '批量完结' : '批量关闭'; for (const record of validRecords) { // 4a. 写入步骤记录 await this.addStep(record.id, { step_status: targetStatus, operator_id: operatorId, operator_snapshot: operatorSnapshot, action: actionName, remark: remark || null, started_at: now, completed_at: now, }, transaction); // 4b. 更新主表 const updateFields = { status: targetStatus, updated_at: now, followup_at: null, }; // completed:额外写入 resolution + resolved_at if (targetStatus === 'completed') { updateFields.resolution = resolution || null; updateFields.resolved_at = now; } await record.update(updateFields, { transaction }); successCount++; } await transaction.commit(); return { total: numericIds.length, success: successCount, failed, }; } catch (error) { await transaction.rollback(); throw error; } } // =========================== // 登记理赔 // =========================== /** * 登记理赔:更新售后单的理赔字段,写入步骤记录,绑定附件。 * * @param {Object} params 理赔参数 * @param {number} params.id 售后单主键ID * @param {number} [params.claimNeeded] 仓库理赔标记 * @param {number} [params.claimAmount] 仓库理赔金额 * @param {string} [params.claimStatus] 仓库理赔状态 * @param {number} [params.carrierClaimNeeded] 运方理赔标记 * @param {number} [params.carrierClaimAmount] 运方理赔金额 * @param {string} [params.carrierClaimStatus] 运方理赔状态 * @param {string|null} params.remark 理赔备注 * @param {string} params.action 操作动作描述 * @param {number[]} params.attachmentIds 附件文件ID列表 * @param {number} params.operatorId 操作人ID * @param {string} params.operatorSnapshot 操作人快照 JSON * @param {number} params.warehouseId 仓库ID * @return {Promise} 理赔处理结果 * @throws {Error} 售后单不存在时抛出 */ async registerClaim(params = {}) { const { id, claimNeeded, claimAmount, claimStatus, carrierClaimNeeded, carrierClaimAmount, carrierClaimStatus, remark, action, attachmentIds, operatorId, operatorSnapshot, } = params; const { ctx } = this; // 校验售后单存在 const afterSale = await ctx.model.AfterSale.findOne({ where: { id, deleted_at: null }, }); if (!afterSale) { throw new Error('售后单不存在'); } const transaction = await ctx.model.transaction(); try { const now = new Date(); // 构建更新字段(仅含非空传入值) const updateFields = { updated_at: now }; if (claimNeeded !== undefined) updateFields.claim_needed = claimNeeded; if (claimAmount !== undefined) updateFields.claim_amount = claimAmount; if (claimStatus !== undefined) updateFields.claim_status = claimStatus; if (carrierClaimNeeded !== undefined) updateFields.carrier_claim_needed = carrierClaimNeeded; if (carrierClaimAmount !== undefined) updateFields.carrier_claim_amount = carrierClaimAmount; if (carrierClaimStatus !== undefined) updateFields.carrier_claim_status = carrierClaimStatus; await afterSale.update(updateFields, { transaction }); // 写入步骤(step_status 与主表当前 status 一致) const step = await this.addStep(id, { step_status: afterSale.status || 'processing', operator_id: operatorId, operator_snapshot: operatorSnapshot, action, remark, started_at: now, completed_at: now, }, transaction); // 绑定附件 if (Array.isArray(attachmentIds) && attachmentIds.length > 0) { await this.bindAttachments(step.id, attachmentIds, transaction); } await transaction.commit(); const updatedAfterSale = afterSale.toJSON ? afterSale.toJSON() : afterSale; return { after_sale: this._formatAfterSaleRow(updatedAfterSale, ctx.app), step, }; } catch (error) { await transaction.rollback(); throw error; } } // =========================== // 导出 // =========================== /** * 售后单导出:分页查询 → ExcelJS 流式写入 → COS 上传。 * 通过 onProgress 回调实时推送进度。 * * @param {Object} options 导出选项 * @param {Object} [options.where] 筛选条件 * @param {Object} [options.sort] 排序参数 * @param {Function} [options.onProgress] 进度回调 * @return {Promise} 导出结果,包含文件下载信息 */ async exportAfterSales(options = {}) { const { where = {}, sort = {}, onProgress } = options; const reportProgress = async (status, progress, message, extra = {}) => { if (typeof onProgress === 'function') { await onProgress({ status, progress, message, ...extra }); } }; await reportProgress('running', 5, '正在准备导出数据...'); // 先统计总数 const { count: totalCount } = await this.ctx.model.AfterSale.findAndCountAll({ where: this._buildListWhere(where, this.ctx.app.Sequelize.Op), raw: true, }); await reportProgress('running', 10, `共 ${totalCount} 条记录,开始导出...`, { totalCount, currentCount: 0 }); // 分页查询并导出 const pageSize = 500; const totalPages = Math.ceil(totalCount / pageSize); const allRows = []; for (let page = 1; page <= totalPages; page++) { const result = await this.list(where, { page, pageSize }, sort); const rows = Array.isArray(result.list) ? result.list : []; allRows.push(...rows); const progress = 10 + Math.floor(((page / totalPages) * 80)); await reportProgress('running', progress, `正在导出... (${allRows.length}/${totalCount})`, { totalCount, currentCount: allRows.length, }); // 每页之间稍作让渡,避免长时间阻塞 await new Promise(resolve => setImmediate(resolve)); } await reportProgress('running', 90, '正在上传文件...', { totalCount, currentCount: allRows.length }); // 生成 Excel 文件并上传 COS const exportResult = await this._generateAndUploadExcel(allRows); await reportProgress('success', 100, '导出完成', { totalCount, currentCount: allRows.length, result: exportResult, }); return { ...exportResult, total_count: totalCount, current_count: allRows.length, }; } /** * 生成 Excel 并上传 COS,返回下载信息。 * 与其他导出(order/return_received 等)口径一致:流式写临时文件 → uploadFile → uploadSuccessNotify。 * * @param {Array} rows 售后单数据行 * @return {Promise} { filename, fileKey, url, cdnUrl, cosUrl } */ async _generateAndUploadExcel(rows = []) { const { ctx } = this; const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-after-sale-export-')); const now = new Date(); const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`; const filename = `售后单导出_${dateToken}.xlsx`; const filePath = path.join(tempDir, filename); const ExcelJS = require('exceljs'); const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ filename: filePath, useStyles: false, useSharedStrings: false, }); try { const worksheet = workbook.addWorksheet('售后单列表'); // 定义列 worksheet.columns = [ { header: '售后单号', key: 'after_sale_no', width: 22 }, { header: '售后类型', key: 'type', width: 12 }, { header: '售后子类型', key: 'sub_type', width: 14 }, { header: '售后状态', key: 'status', width: 12 }, { header: '优先级', key: 'priority', width: 10 }, { header: '标题', key: 'title', width: 30 }, { header: '描述', key: 'description', width: 30 }, { header: '当前处理角色', key: 'role_group', width: 16 }, { header: '仓库理赔状态', key: 'claim_status', width: 14 }, { header: '仓库理赔金额', key: 'claim_amount', width: 14 }, { header: '运方理赔状态', key: 'carrier_claim_status', width: 14 }, { header: '运方理赔金额', key: 'carrier_claim_amount', width: 14 }, { header: '运单号', key: 'waybill_no', width: 20 }, { header: '发货订单号', key: 'order_delivery_no', width: 20 }, { header: '入库单号', key: 'entry_order_no', width: 20 }, { header: '出库单号', key: 'order_stockout_no', width: 20 }, { header: '收货单号', key: 'receiving_no', width: 20 }, { header: '处理结果', key: 'resolution', width: 30 }, { header: '创建时间', key: 'created_at', width: 20 }, { header: '更新时间', key: 'updated_at', width: 20 }, { header: '完结时间', key: 'resolved_at', width: 20 }, ]; // 写入数据行 for (const row of rows) { worksheet.addRow(row).commit(); } worksheet.commit(); await workbook.commit(); // ---- 上传文件(与 order/return_received 导出口径一致)---- const uploadService = ctx?.service?.systems?.upload; if (!uploadService || typeof uploadService.uploadFile !== 'function') { throw new Error('上传服务不可用'); } const stat = await fsp.stat(filePath); const randomToken = crypto.randomBytes(6).toString('hex'); const uploadKey = `exports/after_sale/${Date.now()}_${randomToken}.xlsx`; const uploadStream = fs.createReadStream(filePath); uploadStream.filename = filename; uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; uploadStream.fileSize = stat.size; const uploadResult = await uploadService.uploadFile(uploadStream, { key: uploadKey, category: 'document', mimetype: 'xls,xlsx,csv', }); let fileRecord = null; if (typeof uploadService.uploadSuccessNotify === 'function') { fileRecord = await uploadService.uploadSuccessNotify({ url: uploadResult.fileName, fileKey: uploadResult.fileName, fileName: filename, fileType: 'document', mimeType: uploadStream.mimeType, fileSize: stat.size, category: 'document', businessType: 'afterSaleExport', description: `售后单导出,共 ${rows.length} 条记录`, }); } // 优先取 uploadFile 返回的完整 URL,其次取 uploadSuccessNotify 落库记录,最后回退 COS key const safeUploadResult = typeof uploadResult === 'object' && uploadResult !== null ? uploadResult : {}; const resolvedFileRecord = (fileRecord && (fileRecord.data || fileRecord)) || null; const fileUrlFromRecord = resolvedFileRecord ? (resolvedFileRecord.file_url || resolvedFileRecord.fileUrl || resolvedFileRecord.url || '') : ''; const uploadResultUrl = safeUploadResult.url || safeUploadResult.cdnUrl || safeUploadResult.cosUrl || ''; return { filename, fileKey: safeUploadResult.fileName || uploadKey, url: uploadResultUrl || fileUrlFromRecord || safeUploadResult.fileName || uploadKey, cdnUrl: safeUploadResult.cdnUrl || safeUploadResult.url || '', cosUrl: safeUploadResult.cosUrl || '', }; } catch (error) { const workbookStream = workbook.stream; if (workbookStream && typeof workbookStream.destroy === 'function') { workbookStream.destroy(); } ctx.logger.error(`[afterSale.export] 生成/上传 Excel 失败: ${error.message}`); throw error; } finally { await fsp.rm(tempDir, { recursive: true, force: true }); } } // =========================== // 工具方法 // =========================== /** * 获取创建来源渠道的中文标签。 * @param {string} channel 创建渠道代码 * @return {string} 中文标签 */ _getCreateChannelLabel(channel) { const labels = { MANUAL: '手工单', API: '接口', QM: '奇门', }; return labels[channel] || channel || ''; } // =========================== // 售后类型/子类型自定义配置 // =========================== /** * 构造售后类型配置业务错误(携带业务码,供方法层包装为统一失败响应)。 * @param {string} message 错误提示信息 * @param {number} [code=400] 业务错误码 * @return {Error} 携带业务码的错误对象 */ _createAfterSaleTypeConfigError(message, code = 400) { const error = new Error(message); error.code = code; return error; } /** * 校验售后类型/子类型编码:非空且仅允许小写字母、数字、下划线。 * @param {string} code 编码值 * @param {string} fieldLabel 字段中文名(用于错误提示) * @return {string} 去空格后的编码 * @throws {Error} 编码为空或格式不合法时抛出(业务码 400) */ _validateAfterSaleTypeCode(code, fieldLabel) { const trimmed = typeof code === 'string' ? code.trim() : ''; if (!trimmed) { throw this._createAfterSaleTypeConfigError(`${fieldLabel}不能为空`, 400); } if (!/^[a-z0-9_]+$/.test(trimmed)) { throw this._createAfterSaleTypeConfigError(`${fieldLabel}只能包含小写字母、数字和下划线`, 400); } return trimmed; } /** * 归一化售后类型/子类型的 sort_order 入参。 * @param {*} value 原始排序值 * @return {number} 归一化后的整数排序值(非法值按 0 处理) */ _normalizeAfterSaleTypeSortOrder(value) { const num = Number(value); if (!Number.isFinite(num)) return 0; return Math.floor(num); } /** * 归一化 is_enabled 入参。 * @param {*} value 原始值(0/1/布尔/字符串) * @param {number} [defaultValue=1] 缺省值 * @return {number} 0 或 1 */ _normalizeAfterSaleTypeEnabled(value, defaultValue = 1) { if (value === undefined || value === null || value === '') return defaultValue; return value === 0 || value === '0' || value === false || value === 'false' ? 0 : 1; } /** * 格式化售后类型/子类型配置行:数值字段归一化、时间字段格式化。 * @param {Object} row 原始行数据 * @return {Object} 格式化后的行数据 */ _formatAfterSaleTypeConfigRow(row) { if (!row) return row; const { app } = this; return { ...row, warehouse_id: row.warehouse_id === null || row.warehouse_id === undefined ? null : Number(row.warehouse_id), is_system: Number(row.is_system), is_enabled: Number(row.is_enabled), sort_order: Number(row.sort_order), created_at: row.created_at ? app.formatDate(row.created_at) : null, updated_at: row.updated_at ? app.formatDate(row.updated_at) : null, }; } /** * 构建售后类型列表的 where 条件(字段白名单,仓库维度由作用域条件统一控制)。 * @param {Object} where 标准化 where 条件对象 * @param {Object} Op Sequelize Op 对象 * @return {Object} Sequelize where 条件 */ _buildAfterSaleTypeListWhere(where = {}, Op) { const queryWhere = {}; const directFields = [ 'id', 'type', 'name', 'is_system', 'is_enabled', 'sort_order', 'created_at', 'updated_at', ]; for (const field of directFields) { if (where[field] !== undefined && where[field] !== null) { queryWhere[field] = this._resolveConditionValue(where[field], Op); } } return queryWhere; } /** * 构建售后类型列表的排序参数(字段白名单)。 * @param {Object} sort 排序参数 * @param {string} [sort.sortField] 排序字段 * @param {string} [sort.sortOrder] 排序顺序(asc/desc) * @return {Array>} Sequelize order 数组 */ _buildAfterSaleTypeListOrder(sort = {}) { const sortField = sort.sortField || sort.sort_field; const allowedSortFields = new Set([ 'id', 'type', 'name', 'is_enabled', 'sort_order', 'created_at', 'updated_at', ]); if (sortField && allowedSortFields.has(sortField)) { const sortOrderRaw = String(sort.sortOrder || sort.sort_order || 'asc').toLowerCase(); const sortOrder = sortOrderRaw === 'desc' ? 'DESC' : 'ASC'; return [[ sortField, sortOrder ], [ 'id', 'ASC' ]]; } return [[ 'sort_order', 'ASC' ], [ 'id', 'ASC' ]]; } /** * 构建售后子类型列表的 where 条件(字段白名单,仓库维度由作用域条件统一控制)。 * @param {Object} where 标准化 where 条件对象 * @param {Object} Op Sequelize Op 对象 * @return {Object} Sequelize where 条件 */ _buildAfterSaleSubTypeListWhere(where = {}, Op) { const queryWhere = {}; const directFields = [ 'id', 'type', 'sub_type', 'name', 'is_system', 'is_enabled', 'sort_order', 'created_at', 'updated_at', ]; for (const field of directFields) { if (where[field] !== undefined && where[field] !== null) { queryWhere[field] = this._resolveConditionValue(where[field], Op); } } return queryWhere; } /** * 构建售后子类型列表的排序参数(字段白名单)。 * @param {Object} sort 排序参数 * @param {string} [sort.sortField] 排序字段 * @param {string} [sort.sortOrder] 排序顺序(asc/desc) * @return {Array>} Sequelize order 数组 */ _buildAfterSaleSubTypeListOrder(sort = {}) { const sortField = sort.sortField || sort.sort_field; const allowedSortFields = new Set([ 'id', 'type', 'sub_type', 'name', 'is_enabled', 'sort_order', 'created_at', 'updated_at', ]); if (sortField && allowedSortFields.has(sortField)) { const sortOrderRaw = String(sort.sortOrder || sort.sort_order || 'asc').toLowerCase(); const sortOrder = sortOrderRaw === 'desc' ? 'DESC' : 'ASC'; return [[ sortField, sortOrder ], [ 'id', 'ASC' ]]; } return [[ 'sort_order', 'ASC' ], [ 'id', 'ASC' ]]; } /** * 售后类型列表:系统级(warehouse_id IS NULL)+ 当前仓库自定义合并,支持分页/where/sort。 * @param {Object} params 参数对象 * @param {number} params.warehouseId 当前仓库ID(0 表示无仓库上下文,仅返回系统级数据) * @param {Object} [params.where] 标准化 where 条件 * @param {Object} [params.pagination] 分页参数 {page, pageSize} * @param {Object} [params.sort] 排序参数 {sortField, sortOrder} * @return {Promise} { list: Array, pagination: Object } */ async getTypeList(params = {}) { const { ctx, app } = this; const { Op } = app.Sequelize; const { warehouseId = 0, where = {}, pagination = {}, sort = {} } = params; const page = Math.max(1, parseInt(pagination.page) || 1); const pageSize = Math.min(500, Math.max(1, parseInt(pagination.pageSize) || 20)); const scopeWhere = warehouseId ? { [Op.or]: [{ warehouse_id: null }, { warehouse_id: warehouseId }] } : { warehouse_id: null }; const fieldWhere = this._buildAfterSaleTypeListWhere(where, Op); const queryWhere = { ...scopeWhere, ...fieldWhere }; const order = this._buildAfterSaleTypeListOrder(sort); const { count, rows } = await ctx.model.AfterSaleType.findAndCountAll({ where: queryWhere, order, offset: (page - 1) * pageSize, limit: pageSize, raw: true, attributes: [ 'id', 'type', 'name', 'warehouse_id', 'is_system', 'is_enabled', 'sort_order', 'created_at', 'updated_at', ], }); const totalPages = Math.ceil(count / pageSize); return { list: rows.map(row => this._formatAfterSaleTypeConfigRow(row)), pagination: { page, pageSize, total: count, totalPages, hasPrevious: page > 1, hasNext: page * pageSize < count, }, }; } /** * 创建仓库自定义售后类型。 * @param {Object} params 参数对象 * @param {number} params.warehouseId 当前仓库ID * @param {string} params.type 类型编码 * @param {string} params.name 类型名称 * @param {*} [params.sortOrder] 排序值 * @param {*} [params.isEnabled] 是否启用(0/1) * @return {Promise} 新创建的售后类型记录 * @throws {Error} 参数不合法、编码重复时抛出(携带业务码) */ async createType(params = {}) { const { ctx } = this; const { warehouseId = 0, type, name, sortOrder, isEnabled } = params; if (!warehouseId) { throw this._createAfterSaleTypeConfigError('无法获取当前仓库上下文,不能创建售后类型', 400); } const typeCode = this._validateAfterSaleTypeCode(type, '类型编码'); if (typeCode.length > 20) { throw this._createAfterSaleTypeConfigError('类型编码长度不能超过20个字符', 400); } const typeName = typeof name === 'string' ? name.trim() : ''; if (!typeName) { throw this._createAfterSaleTypeConfigError('类型名称不能为空', 400); } if (typeName.length > 50) { throw this._createAfterSaleTypeConfigError('类型名称长度不能超过50个字符', 400); } const sortOrderValue = this._normalizeAfterSaleTypeSortOrder(sortOrder); const isEnabledValue = this._normalizeAfterSaleTypeEnabled(isEnabled); // 不能与系统级类型编码重复 const systemType = await ctx.model.AfterSaleType.findOne({ where: { type: typeCode, warehouse_id: null }, attributes: [ 'id' ], raw: true, }); if (systemType) { throw this._createAfterSaleTypeConfigError('该类型编码与系统预设类型重复,不允许使用', 409); } // 同仓库内唯一(唯一索引兜底) const existType = await ctx.model.AfterSaleType.findOne({ where: { type: typeCode, warehouse_id: warehouseId }, attributes: [ 'id' ], raw: true, }); if (existType) { throw this._createAfterSaleTypeConfigError('该类型编码在当前仓库已存在', 409); } try { const record = await ctx.model.AfterSaleType.create({ warehouse_id: warehouseId, type: typeCode, name: typeName, is_system: 0, is_enabled: isEnabledValue, sort_order: sortOrderValue, }); return this._formatAfterSaleTypeConfigRow(record && record.toJSON ? record.toJSON() : record); } catch (error) { if (error && error.name === 'SequelizeUniqueConstraintError') { throw this._createAfterSaleTypeConfigError('该类型编码在当前仓库已存在', 409); } throw error; } } /** * 更新仓库自定义售后类型(仅 name/is_enabled/sort_order 可改,type 编码不可变)。 * @param {Object} params 参数对象 * @param {number} params.warehouseId 当前仓库ID * @param {number} params.id 类型主键ID * @param {string} [params.name] 类型名称 * @param {*} [params.isEnabled] 是否启用(0/1) * @param {*} [params.sortOrder] 排序值 * @return {Promise} 更新后的售后类型记录 * @throws {Error} 记录不存在/为系统预设或参数不合法时抛出(携带业务码) */ async updateType(params = {}) { const { ctx } = this; const { warehouseId = 0, id, name, sortOrder, isEnabled } = params; if (!warehouseId) { throw this._createAfterSaleTypeConfigError('无法获取当前仓库上下文,不能修改售后类型', 400); } const typeId = Number(id); if (!Number.isFinite(typeId) || typeId <= 0) { throw this._createAfterSaleTypeConfigError('售后类型ID不合法', 400); } const record = await ctx.model.AfterSaleType.findOne({ where: { id: typeId, warehouse_id: warehouseId, is_system: 0 }, }); if (!record) { throw this._createAfterSaleTypeConfigError('售后类型不存在、无权操作或为系统预设类型', 404); } const updateData = {}; if (name !== undefined) { const typeName = typeof name === 'string' ? name.trim() : ''; if (!typeName) { throw this._createAfterSaleTypeConfigError('类型名称不能为空', 400); } if (typeName.length > 50) { throw this._createAfterSaleTypeConfigError('类型名称长度不能超过50个字符', 400); } updateData.name = typeName; } if (isEnabled !== undefined) { updateData.is_enabled = this._normalizeAfterSaleTypeEnabled(isEnabled); } if (sortOrder !== undefined) { updateData.sort_order = this._normalizeAfterSaleTypeSortOrder(sortOrder); } if (Object.keys(updateData).length === 0) { throw this._createAfterSaleTypeConfigError('没有需要更新的字段', 400); } await record.update(updateData); return this._formatAfterSaleTypeConfigRow(record.toJSON()); } /** * 删除仓库自定义售后类型(系统级禁止删除;存在当前仓库自定义子类型时拒绝删除)。 * @param {Object} params 参数对象 * @param {number} params.warehouseId 当前仓库ID * @param {number} params.id 类型主键ID * @return {Promise} { id, deleted: true } * @throws {Error} 记录不存在/为系统预设或存在自定义子类型时抛出(携带业务码) */ async deleteType(params = {}) { const { ctx } = this; const { warehouseId = 0, id } = params; if (!warehouseId) { throw this._createAfterSaleTypeConfigError('无法获取当前仓库上下文,不能删除售后类型', 400); } const typeId = Number(id); if (!Number.isFinite(typeId) || typeId <= 0) { throw this._createAfterSaleTypeConfigError('售后类型ID不合法', 400); } const record = await ctx.model.AfterSaleType.findOne({ where: { id: typeId, warehouse_id: warehouseId, is_system: 0 }, attributes: [ 'id', 'type' ], raw: true, }); if (!record) { throw this._createAfterSaleTypeConfigError('售后类型不存在、无权操作或为系统预设类型', 404); } // 删除前检查该类型下是否存在当前仓库的自定义子类型,存在则拒绝(不做级联删除,避免误删数据) const subTypeCount = await ctx.model.AfterSaleSubType.count({ where: { type: record.type, warehouse_id: warehouseId, is_system: 0 }, }); if (subTypeCount > 0) { throw this._createAfterSaleTypeConfigError('该类型下存在当前仓库的自定义子类型,请先删除子类型', 409); } await ctx.model.AfterSaleType.destroy({ where: { id: typeId, warehouse_id: warehouseId, is_system: 0 }, }); return { id: typeId, deleted: true }; } /** * 售后子类型列表:系统级 + 当前仓库自定义合并,支持 type 过滤与按 type 分组返回。 * @param {Object} params 参数对象 * @param {number} params.warehouseId 当前仓库ID(0 表示无仓库上下文,仅返回系统级数据) * @param {Object} [params.where] 标准化 where 条件 * @param {Object} [params.pagination] 分页参数 {page, pageSize} * @param {Object} [params.sort] 排序参数 {sortField, sortOrder} * @param {boolean} [params.group=false] 是否按 type 分组返回 groups * @return {Promise} { list: Array, pagination: Object, groups?: Array } */ async getSubTypeList(params = {}) { const { ctx, app } = this; const { Op } = app.Sequelize; const { warehouseId = 0, where = {}, pagination = {}, sort = {}, group = false, } = params; const page = Math.max(1, parseInt(pagination.page) || 1); const pageSize = Math.min(500, Math.max(1, parseInt(pagination.pageSize) || 20)); const scopeWhere = warehouseId ? { [Op.or]: [{ warehouse_id: null }, { warehouse_id: warehouseId }] } : { warehouse_id: null }; const fieldWhere = this._buildAfterSaleSubTypeListWhere(where, Op); const queryWhere = { ...scopeWhere, ...fieldWhere }; const order = this._buildAfterSaleSubTypeListOrder(sort); const attributes = [ 'id', 'type', 'sub_type', 'name', 'warehouse_id', 'is_system', 'is_enabled', 'sort_order', 'created_at', 'updated_at', ]; const { count, rows } = await ctx.model.AfterSaleSubType.findAndCountAll({ where: queryWhere, order, offset: (page - 1) * pageSize, limit: pageSize, raw: true, attributes, }); const totalPages = Math.ceil(count / pageSize); const result = { list: rows.map(row => this._formatAfterSaleTypeConfigRow(row)), pagination: { page, pageSize, total: count, totalPages, hasPrevious: page > 1, hasNext: page * pageSize < count, }, }; // 按 type 分组:基于全量过滤结果(不受分页影响)构建分组结构 if (group) { const typeRows = await ctx.model.AfterSaleType.findAll({ where: scopeWhere, attributes: [ 'type', 'name' ], raw: true, }); const typeNameMap = {}; for (const row of typeRows) { typeNameMap[row.type] = row.name; } const allRows = await ctx.model.AfterSaleSubType.findAll({ where: queryWhere, order: [[ 'sort_order', 'ASC' ], [ 'id', 'ASC' ]], raw: true, attributes, }); const groups = []; const groupIndexMap = new Map(); for (const row of allRows) { if (!groupIndexMap.has(row.type)) { groupIndexMap.set(row.type, groups.length); groups.push({ type: row.type, name: typeNameMap[row.type] || row.type, items: [], }); } groups[groupIndexMap.get(row.type)].items.push(this._formatAfterSaleTypeConfigRow(row)); } result.groups = groups; } return result; } /** * 创建仓库自定义售后子类型。 * @param {Object} params 参数对象 * @param {number} params.warehouseId 当前仓库ID * @param {string} params.type 所属类型编码(必须已存在且启用) * @param {string} params.subType 子类型编码 * @param {string} params.name 子类型名称 * @param {*} [params.sortOrder] 排序值 * @param {*} [params.isEnabled] 是否启用(0/1) * @return {Promise} 新创建的售后子类型记录 * @throws {Error} 参数不合法、类型不存在/停用、编码重复时抛出(携带业务码) */ async createSubType(params = {}) { const { ctx, app } = this; const { Op } = app.Sequelize; const { warehouseId = 0, type, subType, name, sortOrder, isEnabled } = params; if (!warehouseId) { throw this._createAfterSaleTypeConfigError('无法获取当前仓库上下文,不能创建售后子类型', 400); } const typeCode = this._validateAfterSaleTypeCode(type, '类型编码'); if (typeCode.length > 20) { throw this._createAfterSaleTypeConfigError('类型编码长度不能超过20个字符', 400); } const subTypeCode = this._validateAfterSaleTypeCode(subType, '子类型编码'); if (subTypeCode.length > 50) { throw this._createAfterSaleTypeConfigError('子类型编码长度不能超过50个字符', 400); } const subTypeName = typeof name === 'string' ? name.trim() : ''; if (!subTypeName) { throw this._createAfterSaleTypeConfigError('子类型名称不能为空', 400); } if (subTypeName.length > 50) { throw this._createAfterSaleTypeConfigError('子类型名称长度不能超过50个字符', 400); } // 所属类型必须存在(系统级或当前仓库自定义)且启用 const typeRecord = await ctx.model.AfterSaleType.findOne({ where: { [Op.or]: [ { type: typeCode, warehouse_id: null }, { type: typeCode, warehouse_id: warehouseId }, ], }, attributes: [ 'id', 'is_enabled' ], raw: true, }); if (!typeRecord) { throw this._createAfterSaleTypeConfigError('售后类型不存在', 400); } if (Number(typeRecord.is_enabled) !== 1) { throw this._createAfterSaleTypeConfigError('售后类型已停用,不能添加子类型', 400); } // 不能与系统级同 type 下的子类型编码重复 const systemSubType = await ctx.model.AfterSaleSubType.findOne({ where: { type: typeCode, sub_type: subTypeCode, warehouse_id: null }, attributes: [ 'id' ], raw: true, }); if (systemSubType) { throw this._createAfterSaleTypeConfigError('该子类型编码与系统预设重复,不允许使用', 409); } // 同类型同仓库内唯一(唯一索引兜底) const existSubType = await ctx.model.AfterSaleSubType.findOne({ where: { type: typeCode, sub_type: subTypeCode, warehouse_id: warehouseId }, attributes: [ 'id' ], raw: true, }); if (existSubType) { throw this._createAfterSaleTypeConfigError('该子类型编码在当前仓库已存在', 409); } const sortOrderValue = this._normalizeAfterSaleTypeSortOrder(sortOrder); const isEnabledValue = this._normalizeAfterSaleTypeEnabled(isEnabled); try { const record = await ctx.model.AfterSaleSubType.create({ warehouse_id: warehouseId, type: typeCode, sub_type: subTypeCode, name: subTypeName, is_system: 0, is_enabled: isEnabledValue, sort_order: sortOrderValue, }); return this._formatAfterSaleTypeConfigRow(record && record.toJSON ? record.toJSON() : record); } catch (error) { if (error && error.name === 'SequelizeUniqueConstraintError') { throw this._createAfterSaleTypeConfigError('该子类型编码在当前仓库已存在', 409); } throw error; } } /** * 更新仓库自定义售后子类型(仅 name/is_enabled/sort_order 可改,type 与 sub_type 编码不可变)。 * @param {Object} params 参数对象 * @param {number} params.warehouseId 当前仓库ID * @param {number} params.id 子类型主键ID * @param {string} [params.name] 子类型名称 * @param {*} [params.isEnabled] 是否启用(0/1) * @param {*} [params.sortOrder] 排序值 * @return {Promise} 更新后的售后子类型记录 * @throws {Error} 记录不存在/为系统预设或参数不合法时抛出(携带业务码) */ async updateSubType(params = {}) { const { ctx } = this; const { warehouseId = 0, id, name, sortOrder, isEnabled } = params; if (!warehouseId) { throw this._createAfterSaleTypeConfigError('无法获取当前仓库上下文,不能修改售后子类型', 400); } const subTypeId = Number(id); if (!Number.isFinite(subTypeId) || subTypeId <= 0) { throw this._createAfterSaleTypeConfigError('售后子类型ID不合法', 400); } const record = await ctx.model.AfterSaleSubType.findOne({ where: { id: subTypeId, warehouse_id: warehouseId, is_system: 0 }, }); if (!record) { throw this._createAfterSaleTypeConfigError('售后子类型不存在、无权操作或为系统预设类型', 404); } const updateData = {}; if (name !== undefined) { const subTypeName = typeof name === 'string' ? name.trim() : ''; if (!subTypeName) { throw this._createAfterSaleTypeConfigError('子类型名称不能为空', 400); } if (subTypeName.length > 50) { throw this._createAfterSaleTypeConfigError('子类型名称长度不能超过50个字符', 400); } updateData.name = subTypeName; } if (isEnabled !== undefined) { updateData.is_enabled = this._normalizeAfterSaleTypeEnabled(isEnabled); } if (sortOrder !== undefined) { updateData.sort_order = this._normalizeAfterSaleTypeSortOrder(sortOrder); } if (Object.keys(updateData).length === 0) { throw this._createAfterSaleTypeConfigError('没有需要更新的字段', 400); } await record.update(updateData); return this._formatAfterSaleTypeConfigRow(record.toJSON()); } /** * 删除仓库自定义售后子类型(系统级禁止删除;已被售后单使用时拒绝删除)。 * @param {Object} params 参数对象 * @param {number} params.warehouseId 当前仓库ID * @param {number} params.id 子类型主键ID * @return {Promise} { id, deleted: true } * @throws {Error} 记录不存在/为系统预设或已被售后单使用时抛出(携带业务码) */ async deleteSubType(params = {}) { const { ctx } = this; const { warehouseId = 0, id } = params; if (!warehouseId) { throw this._createAfterSaleTypeConfigError('无法获取当前仓库上下文,不能删除售后子类型', 400); } const subTypeId = Number(id); if (!Number.isFinite(subTypeId) || subTypeId <= 0) { throw this._createAfterSaleTypeConfigError('售后子类型ID不合法', 400); } const record = await ctx.model.AfterSaleSubType.findOne({ where: { id: subTypeId, warehouse_id: warehouseId, is_system: 0 }, attributes: [ 'id', 'type', 'sub_type' ], raw: true, }); if (!record) { throw this._createAfterSaleTypeConfigError('售后子类型不存在、无权操作或为系统预设类型', 404); } // 检查 wms_after_sale 引用(命中 idx_type_subtype 索引,成本可控),被使用时拒绝删除 const usedCount = await ctx.model.AfterSale.count({ where: { warehouse_id: warehouseId, type: record.type, sub_type: record.sub_type, deleted_at: null, }, }); if (usedCount > 0) { throw this._createAfterSaleTypeConfigError('该子类型已被售后单使用,无法删除', 409); } await ctx.model.AfterSaleSubType.destroy({ where: { id: subTypeId, warehouse_id: warehouseId, is_system: 0 }, }); return { id: subTypeId, deleted: true }; } } module.exports = AfterSaleService;