'use strict'; 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) * @return {Promise} { list: Array, pagination: Object } */ async list(where = {}, pagination = {}, sort = {}) { 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); // 排序 const 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); return { list: rows, pagination: { page, pageSize, total: count, totalPages, hasPrevious: page > 1, hasNext: page * pageSize < 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 || 'created_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 ]]; } // =========================== // 明细查询 // =========================== /** * 售后单明细查询,包含主表信息、步骤列表及附件。 * * @param {number} id 售后单主键ID * @return {Promise} 售后单明细,包含主表、步骤列表(含附件) * @throws {Error} 售后单不存在时抛出 */ async getDetail(id) { const { ctx } = 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); return { ...afterSale, steps: stepsWithAttachments, }; } /** * 为步骤列表补充附件信息。 * * @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 } = this; const record = await ctx.model.AfterSale.create(data, { transaction }); return record && record.toJSON ? record.toJSON() : record; } // =========================== // 更新售后单 // =========================== /** * 更新售后单主表字段。 * * @param {number} id 售后单主键ID * @param {Object} data 需要更新的字段键值对 * @param {Object} [transaction] Sequelize 事务对象 * @return {Promise} 更新后的售后单记录 * @throws {Error} 售后单不存在时抛出 */ async update(id, data, transaction = null) { const { ctx } = this; const record = await ctx.model.AfterSale.findOne({ where: { id, deleted_at: null }, transaction, }); if (!record) { throw new Error('售后单不存在'); } await record.update(data, { transaction }); return record && record.toJSON ? record.toJSON() : record; } // =========================== // 步骤记录 // =========================== /** * 写入一条售后进度步骤记录。 * * @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 : 2, 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); // 写入步骤记录 await this.addStep(id, { step_status: 2, 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} params.action 操作动作描述 * @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 * @return {Promise} 处理结果,包含更新后的售后单和步骤记录 * @throws {Error} 售后单不存在或权限不足时抛出 */ async handleWorkOrder(params = {}) { const { id, action, remark, targetStatus, resolution, attachmentIds, operatorId, operatorSnapshot, warehouseId, } = 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. 校验 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('无权限处理当前角色组的售后单'); } // 3. 开启事务 const transaction = await ctx.model.transaction(); try { const now = new Date(); // 4. 写入步骤记录 const step = await this.addStep(id, { step_status: 2, operator_id: operatorId, operator_snapshot: operatorSnapshot, action, remark, started_at: now, completed_at: now, }, transaction); // 5. 绑定附件 if (Array.isArray(attachmentIds) && attachmentIds.length > 0) { await this.bindAttachments(step.id, attachmentIds, transaction); } // 6. 更新售后单状态 const updateFields = { updated_at: now }; if (targetStatus) { updateFields.status = targetStatus; // 若完结,写入 resolution 和 resolved_at if (targetStatus === 'completed') { updateFields.resolution = resolution || null; updateFields.resolved_at = now; } } // 7. 若当前角色非客服组且状态非完结,自动回设为客服组 if (currentRoleGroup && currentRoleGroup !== 'customer_service' && targetStatus !== 'completed') { updateFields.role_group = 'customer_service'; } await afterSale.update(updateFields, { transaction }); await transaction.commit(); const updatedAfterSale = afterSale.toJSON ? afterSale.toJSON() : afterSale; return { after_sale: updatedAfterSale, step, }; } 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 }); // 写入步骤 const step = await this.addStep(id, { step_status: 2, 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: updatedAfterSale, 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 = (status, progress, message, extra = {}) => { if (typeof onProgress === 'function') { onProgress({ status, progress, message, ...extra }); } }; reportProgress('running', 5, '正在准备导出数据...'); // 先统计总数 const { count: totalCount } = await this.ctx.model.AfterSale.findAndCountAll({ where: this._buildListWhere(where, this.ctx.app.Sequelize.Op), raw: true, }); 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)); reportProgress('running', progress, `正在导出... (${allRows.length}/${totalCount})`, { totalCount, currentCount: allRows.length, }); // 每页之间稍作让渡,避免长时间阻塞 await new Promise(resolve => setImmediate(resolve)); } reportProgress('running', 90, '正在上传文件...', { totalCount, currentCount: allRows.length }); // 生成 Excel 文件并上传 COS const exportResult = await this._generateAndUploadExcel(allRows); reportProgress('success', 100, '导出完成', { totalCount, currentCount: allRows.length, result: exportResult, }); return { ...exportResult, total_count: totalCount, current_count: allRows.length, }; } /** * 生成 Excel 并上传 COS,返回下载信息。 * * @param {Array} rows 售后单数据行 * @return {Promise} { url, fileKey, fileName } */ async _generateAndUploadExcel(rows = []) { const { ctx } = this; try { const ExcelJS = require('exceljs'); const workbook = new ExcelJS.Workbook(); 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); } // 生成 buffer const buffer = await workbook.xlsx.writeBuffer(); // 上传到 COS const now = new Date(); const dateStr = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`; const timestamp = Date.now(); const fileName = `after_sale_export_${dateStr}_${timestamp}.xlsx`; const fileKey = `export/after_sale/${fileName}`; let url = ''; try { if (ctx.service.systems && ctx.service.systems.upload && typeof ctx.service.systems.upload.uploadToCos === 'function') { const uploadResult = await ctx.service.systems.upload.uploadToCos({ buffer, fileKey, fileName, mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', }); url = uploadResult && uploadResult.url ? uploadResult.url : ''; } } catch (uploadError) { ctx.logger.warn(`[afterSale.export] COS 上传失败: ${uploadError.message}`); } return { url, fileKey, fileName, }; } catch (error) { ctx.logger.error(`[afterSale.export] 生成 Excel 失败: ${error.message}`); return { url: '', fileKey: '', fileName: '', }; } } } module.exports = AfterSaleService;