'use strict'; const MainService = require('../main'); const AFTER_SALE_EXPORT_TASK_CACHE_KEY_PREFIX = 'after_sale_export_task_'; const AFTER_SALE_EXPORT_TASK_CACHE_TTL_SECONDS = 1800; /** * 售后 block 权限 ID → role_group 映射表。 * 516=客服组, 517=仓库组, 518=财务组 */ const BLOCK_PERMISSION_ROLE_GROUP_MAP = Object.freeze({ 516: 'customer_service', 517: 'warehouse', 518: 'finance', }); /** * 售后模块工作列表排除的终态(已完成/已关闭/已取消)。 * pending_feedback 不在静态排除列表中,由 workList 根据 followup_at 动态判断。 */ const WORK_LIST_EXCLUDED_STATUSES = Object.freeze([ 'completed', 'closed', 'cancelled' ]); /** * 系统方法层:afterSale(售后模块接口包装层)。 * 主要职责:统一包装系统方法接口,处理权限、日志、where 解析等公共逻辑, * 将具体业务逻辑下沉到 systems.afterSale 中。 */ class AfterSaleMethodService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; const _noNeedRight = 'workList,auditList,detail,create,transfer,handleWorkOrder,batchSetPendingFeedback,batchClose,registerClaim,export,exportTaskProgress,workCount'; const _noNeedLog = 'workList,auditList,detail,export,exportTaskProgress,workCount'; const _noNeedAuth = 'workList,auditList,detail,create,transfer,handleWorkOrder,batchSetPendingFeedback,batchClose,registerClaim,export,exportTaskProgress,workCount'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } // =========================== // 售后工作列表 // =========================== /** * 售后工作列表:按当前用户的 block 权限筛选可见的售后单。 * 解析用户 wms_role.permissions 中 type=block 的售后权限 ID(516/517/518), * 映射为 role_group,仅展示当前用户可处理的售后单。 * * @param {Object} data 请求体 * @param {Object} [data.pagination] 分页参数 * @param {Object} [data.where] 动态筛选条件 * @param {Object} [data.sort] 排序参数 * @return {Promise} 统一 success 包装 */ async workList(data = {}) { const { service } = this; const { pagination, sort } = data; const { where } = this.prepareWhereContext(data, { specialFieldMap: { quickWhere: { bucket: 'quick', }, }, }); // 提取当前用户的售后 block 权限 → role_group 列表 const allowedRoleGroups = await this._resolveAfterSaleBlockRoleGroups(); // 强制过滤:仅展示当前用户可处理的 role_group,且排除已完成/已取消 const enforcedWhere = { ...where, role_group: { operator: 'in', value: allowedRoleGroups, }, status: { operator: 'notin', value: WORK_LIST_EXCLUDED_STATUSES, }, }; const result = await service.systems.afterSale.list(enforcedWhere, pagination, sort, { order: [[ 'priority', 'DESC' ], [ 'updated_at', 'DESC' ]], excludeFutureFollowup: true, // 列表行补充货主名称 store_name(合约表 store_remask 货主备注,无备注时回退货主公司全称) enrichStoreName: true, }); return this.success('ok', result); } /** * 解析当前用户所拥有的售后 block 权限对应的 role_group 列表。 * 从 wms_role.permissions 中查询当前激活角色的原始权限 ID, * 若 permissions='*' 则返回全部 role_group,否则筛选 516/517/518。 * * @return {Promise} 当前用户可处理的 role_group 列表 */ async _resolveAfterSaleBlockRoleGroups() { const { ctx } = this; const employeeId = ctx.user && ctx.user.employees_id; if (!employeeId) { return [ '__none__' ]; } try { // 1. 通过 EmployeeRole 找到 role_id const employeeRole = await ctx.model.EmployeeRole.findOne({ where: { employee_id: employeeId }, attributes: [ 'role_id' ], raw: true, }); if (!employeeRole || !employeeRole.role_id) { return [ '__none__' ]; } // 2. 读取 wms_role.permissions const role = await ctx.model.Role.findOne({ where: { id: employeeRole.role_id, status: 1 }, attributes: [ 'permissions' ], raw: true, }); if (!role) { return [ '__none__' ]; } // 3. 标准化解析 const state = ctx.service.systems.auth.rolePermission.normalizePermissionSet(role.permissions); // 超级管理员 → 全部 role_group if (state.allAccess) { return [ 'customer_service', 'warehouse', 'finance' ]; } // 匹配 block 权限 516/517/518 const allowedRoleGroups = []; for (const permId of state.permissionIds) { if (BLOCK_PERMISSION_ROLE_GROUP_MAP[permId]) { allowedRoleGroups.push(BLOCK_PERMISSION_ROLE_GROUP_MAP[permId]); } } if (allowedRoleGroups.length === 0) { return [ '__none__' ]; } return allowedRoleGroups; } catch (err) { ctx.logger.warn(`[_resolveAfterSaleBlockRoleGroups] 权限查询失败: ${err.message}`); return [ '__none__' ]; } } // =========================== // 待处理工单计数(角标用) // =========================== /** * 快速查询当前用户待处理售后工单数量(用于角标显示)。 * 过滤逻辑与 workList 一致:role_group 按 block 权限,排除已完成/已取消。 * 返回 { count: number },前端自行判断 >99 显示 99+。 * * @param {Object} data 请求体(可选 where 条件) * @return {Promise} { count: number } */ async workCount(data = {}) { const { service } = this; const { where } = this.prepareWhereContext(data, { specialFieldMap: { quickWhere: { bucket: 'quick', }, }, }); // 与 workList 一致的角色组 + 状态过滤 const allowedRoleGroups = await this._resolveAfterSaleBlockRoleGroups(); const enforcedWhere = { ...where, role_group: { operator: 'in', value: allowedRoleGroups, }, status: { operator: 'notin', value: WORK_LIST_EXCLUDED_STATUSES, }, }; const result = await service.systems.afterSale.countPending(enforcedWhere, { excludeFutureFollowup: true }); return this.success('ok', { count: result.count }); } // =========================== // 售后审计列表 // =========================== /** * 售后审计列表:不限 role_group 与 status(包含已完成/已取消)。 * 用于管理员/审计角色查看全部售后单。 * * @param {Object} data 请求体 * @param {Object} [data.pagination] 分页参数 * @param {Object} [data.where] 动态筛选条件 * @param {Object} [data.sort] 排序参数 * @return {Promise} 统一 success 包装 */ async auditList(data = {}) { const { service } = this; const { pagination, sort } = data; const { where } = this.prepareWhereContext(data, { specialFieldMap: { quickWhere: { bucket: 'quick', }, }, }); const result = await service.systems.afterSale.list(where, pagination, sort); return this.success('ok', result); } // =========================== // 售后明细 // =========================== /** * 售后明细:查询主表、步骤列表及步骤附件。 * * @param {Object} data 请求体 * @param {number} data.id 售后单主键ID * @return {Promise} 统一 success 包装,包含主表、步骤列表及附件信息 */ async detail(data = {}) { const { service } = this; const { id } = data || {}; if (!id) { return this.fail('缺少售后单ID'); } const result = await service.systems.afterSale.getDetail(Number(id)); return this.success('ok', result); } // =========================== // 创建售后单 // =========================== /** * 创建售后单:生成售后单号,写入主表记录。 * warehouse_id 由服务端从当前上下文自动注入。 * * @param {Object} data 请求体 * @param {string} data.type 售后类型(order/receiving/entry/stockout) * @param {string} data.sub_type 售后子类型 * @param {string} data.title 售后标题 * @param {string} [data.description] 售后详细描述 * @param {number} [data.priority=0] 优先级 * @param {number} [data.waybill_id] 关联运单ID * @param {number} [data.order_delivery_id] 关联发货订单ID(兼容别名 order_id) * @param {number} [data.entry_order_id] 关联入库单ID * @param {number} [data.order_stockout_id] 关联出库单ID * @param {number} [data.receiving_id] 关联收货单ID * @param {number} [data.store_id] 关联货主ID * @param {number} [data.inbox_message_id] 关联站内信ID * @return {Promise} 统一 success 包装,返回新创建的售后单信息 */ async create(data = {}) { const { ctx, service } = this; const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0; const creatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0; if (!warehouseId) { return this.fail('无法获取当前仓库上下文'); } const { type, sub_type: subType, title, description, priority, waybill_id: waybillId, order_delivery_id: orderDeliveryIdRaw, order_id: orderIdRaw, entry_order_id: entryOrderId, order_stockout_id: orderStockoutId, receiving_id: receivingId, store_id: storeId, inbox_message_id: inboxMessageId, } = data || {}; // 兼容 order_id 别名(优先 order_delivery_id,为空时取 order_id) const orderDeliveryId = orderDeliveryIdRaw || orderIdRaw || null; // 生成售后单号 const afterSaleNo = await this.generateAfterSaleNo(warehouseId); // 处理单据关联字段的冗余同步(waybill_no 等从对应表同步取数) const redundantFields = await this._resolveRedundantFields({ waybillId, orderDeliveryId, entryOrderId, orderStockoutId, receivingId, }); const createData = { warehouse_id: warehouseId, after_sale_no: afterSaleNo, type, sub_type: subType, title, description: description || null, priority: priority !== undefined ? Number(priority) : 0, creator_id: creatorId, role_group: 'customer_service', status: 'pending', waybill_id: waybillId || null, waybill_no: redundantFields.waybill_no || null, order_id: orderDeliveryId || null, order_no: redundantFields.order_no || null, entry_order_id: entryOrderId || null, entry_order_no: redundantFields.entry_order_no || null, order_stockout_id: orderStockoutId || null, order_stockout_no: redundantFields.order_stockout_no || null, receiving_id: receivingId || null, receiving_no: redundantFields.receiving_no || null, store_id: storeId || null, inbox_message_id: inboxMessageId || null, }; const result = await service.systems.afterSale.create(createData); return this.success('售后单创建成功', result); } /** * 解析单据关联字段的冗余值(waybill_no、order_delivery_no 等), * 从对应的关联表中同步取数。 * * @param {Object} params 关联ID集合 * @param {number} [params.waybillId] 运单ID * @param {number} [params.orderDeliveryId] 发货订单ID * @param {number} [params.entryOrderId] 入库单ID * @param {number} [params.orderStockoutId] 出库单ID * @param {number} [params.receivingId] 收货单ID * @return {Promise} 冗余字段键值对 */ async _resolveRedundantFields(params = {}) { const { ctx } = this; const redundant = {}; // 运单号 if (params.waybillId) { try { const waybill = await ctx.model.OrderExpress.findOne({ where: { id: params.waybillId }, attributes: [ 'waybill_code' ], raw: true, }); redundant.waybill_no = waybill ? waybill.waybill_code || null : null; } catch (err) { ctx.logger.warn(`[afterSale._resolveRedundantFields] 查询运单号失败: ${err.message}`); } } // 发货订单号 if (params.orderDeliveryId) { try { const warehouseId = ctx.user && ctx.user.store_id; const DeliveryModel = warehouseId ? await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId) : null; if (DeliveryModel) { const order = await DeliveryModel.findOne({ where: { id: params.orderDeliveryId }, attributes: [ 'delivery_order_code' ], raw: true, }); redundant.order_no = order ? order.delivery_order_code || null : null; } } catch (err) { ctx.logger.warn(`[afterSale._resolveRedundantFields] 查询发货订单号失败: ${err.message}`); } } // 入库单号 if (params.entryOrderId) { try { const entry = await ctx.model.EntryOrder.findOne({ where: { id: params.entryOrderId }, attributes: [ 'entry_order_code' ], raw: true, }); redundant.entry_order_no = entry ? entry.entry_order_code || null : null; } catch (err) { ctx.logger.warn(`[afterSale._resolveRedundantFields] 查询入库单号失败: ${err.message}`); } } // 出库单号 if (params.orderStockoutId) { try { const stockout = await ctx.model.OrderStockout.findOne({ where: { id: params.orderStockoutId }, attributes: [ 'order_stockout_no' ], raw: true, }); redundant.order_stockout_no = stockout ? stockout.order_stockout_no || null : null; } catch (err) { ctx.logger.warn(`[afterSale._resolveRedundantFields] 查询出库单号失败: ${err.message}`); } } // 收货单号 if (params.receivingId) { try { const receiving = await ctx.model.Receiving.findOne({ where: { id: params.receivingId }, attributes: [ 'receiving_code' ], raw: true, }); redundant.receiving_no = receiving ? receiving.receiving_code || null : null; } catch (err) { ctx.logger.warn(`[afterSale._resolveRedundantFields] 查询收货单号失败: ${err.message}`); } } return redundant; } // =========================== // 转单 // =========================== /** * 转单:将售后单的 role_group 更新为目标值,并写入一条 detail 步骤记录。 * * @param {Object} data 请求体 * @param {number} data.id 售后单主键ID * @param {string} data.role_group 目标角色组(customer_service/warehouse/finance) * @param {string} [data.remark] 转单备注 * @return {Promise} 统一 success 包装 */ async transfer(data = {}) { const { ctx, service } = this; const { id, role_group: targetRoleGroup, remark, } = data || {}; if (!id) { return this.fail('缺少售后单ID'); } if (!targetRoleGroup) { return this.fail('缺少目标角色组'); } const operatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0; const operatorSnapshot = this._buildOperatorSnapshot(); const result = await service.systems.afterSale.transfer({ id: Number(id), targetRoleGroup, remark: remark || '', operatorId, operatorSnapshot, }); return this.success('转单成功', result); } // =========================== // 处理工单 // =========================== /** * 处理工单:校验权限后写入步骤记录,可选更新状态与附件。 * 若处理完后当前 role_group 非客服组且状态未完结,自动回设为客服组。 * * @param {Object} data 请求体 * @param {number} data.id 售后单主键ID * @param {string} [data.remark] 处理备注 * @param {string} [data.status] 目标售后状态 * @param {string} [data.resolution] 完结处理结果(status=completed 时写入) * @param {number[]} [data.attachment_ids] 附件文件ID列表 * @return {Promise} 统一 success 包装 */ async handleWorkOrder(data = {}) { const { ctx, service } = this; const { id, remark, status: targetStatus, resolution, attachment_ids: attachmentIds, } = data || {}; if (!id) { return this.fail('缺少售后单ID'); } // 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'; const operatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0; const operatorSnapshot = this._buildOperatorSnapshot(); const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0; const result = await service.systems.afterSale.handleWorkOrder({ id: Number(id), remark: remark || null, targetStatus: safeStatus, resolution: resolution || null, attachmentIds: Array.isArray(attachmentIds) ? attachmentIds : [], operatorId, operatorSnapshot, warehouseId, notifyGroup: true, }); return this.success('处理成功', result); } // =========================== // 批量设为待反馈 // =========================== /** * 批量将售后工单设为"待反馈"状态,按仓库配置自动计算下次跟进时间。 * 所有工单在同一事务中处理,任一失败则全部回滚。 * * @param {Object} data 请求体 * @param {number[]} data.ids 售后单主键ID列表 * @param {string} [data.remark] 统一处理备注(所有工单共用) * @return {Promise} 统一 success 包装,包含 total/success/failed */ async batchSetPendingFeedback(data = {}) { const { ctx, service } = this; const { ids, remark } = data || {}; if (!Array.isArray(ids) || ids.length === 0) { return this.fail('ids 不能为空且必须为数组'); } const operatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0; const operatorSnapshot = this._buildOperatorSnapshot(); const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0; if (!warehouseId) { return this.fail('无法获取当前仓库上下文'); } const result = await service.systems.afterSale.batchSetPendingFeedback({ ids, remark: remark || null, operatorId, operatorSnapshot, warehouseId, }); return this.success('批量设为待反馈完成', result); } // =========================== // 批量完结/关闭 // =========================== /** * 批量将售后工单设为完结或关闭状态。 * completed 时自动写入 resolved_at 并清除 followup_at。 * 所有工单在同一事务中处理,任一失败则全部回滚。 * * @param {Object} data 请求体 * @param {number[]} data.ids 售后单主键ID列表 * @param {string} data.status 目标状态:completed | closed * @param {string} [data.resolution] 完结处理结果(仅 status=completed 时写入) * @param {string} [data.remark] 统一处理备注(所有工单共用) * @return {Promise} 统一 success 包装,包含 total/success/failed */ async batchClose(data = {}) { const { ctx, service } = this; const { ids, status: targetStatus, resolution, remark } = data || {}; if (!Array.isArray(ids) || ids.length === 0) { return this.fail('ids 不能为空且必须为数组'); } const ALLOWED_TARGET_STATUSES = new Set([ 'completed', 'closed' ]); if (!targetStatus || !ALLOWED_TARGET_STATUSES.has(targetStatus)) { return this.fail('status 必须为 completed 或 closed'); } const operatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0; const operatorSnapshot = this._buildOperatorSnapshot(); const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0; if (!warehouseId) { return this.fail('无法获取当前仓库上下文'); } const result = await service.systems.afterSale.batchClose({ ids, status: targetStatus, resolution: resolution || null, remark: remark || null, operatorId, operatorSnapshot, warehouseId, }); return this.success('批量操作完成', result); } // =========================== // 登记理赔 // =========================== /** * 登记理赔:更新售后单的理赔相关字段,写入步骤记录,绑定附件。 * * @param {Object} data 请求体 * @param {number} data.id 售后单主键ID * @param {number} [data.claim_needed] 仓库理赔标记(0/1) * @param {number} [data.claim_amount] 仓库理赔金额 * @param {string} [data.claim_status] 仓库理赔状态 * @param {number} [data.carrier_claim_needed] 运方理赔标记(0/1) * @param {number} [data.carrier_claim_amount] 运方理赔金额 * @param {string} [data.carrier_claim_status] 运方理赔状态 * @param {string} [data.remark] 理赔备注 * @param {string} [data.action] 操作动作描述,默认"登记理赔" * @param {number[]} [data.attachment_ids] 附件文件ID列表 * @return {Promise} 统一 success 包装 */ async registerClaim(data = {}) { const { ctx, service } = this; const { id, claim_needed: claimNeeded, claim_amount: claimAmount, claim_status: claimStatus, carrier_claim_needed: carrierClaimNeeded, carrier_claim_amount: carrierClaimAmount, carrier_claim_status: carrierClaimStatus, remark, action, attachment_ids: attachmentIds, } = data || {}; if (!id) { return this.fail('缺少售后单ID'); } const operatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0; const operatorSnapshot = this._buildOperatorSnapshot(); const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0; const result = await service.systems.afterSale.registerClaim({ id: Number(id), claimNeeded: claimNeeded !== undefined ? Number(claimNeeded) : undefined, claimAmount: claimAmount !== undefined ? Number(claimAmount) : undefined, claimStatus: claimStatus || undefined, carrierClaimNeeded: carrierClaimNeeded !== undefined ? Number(carrierClaimNeeded) : undefined, carrierClaimAmount: carrierClaimAmount !== undefined ? Number(carrierClaimAmount) : undefined, carrierClaimStatus: carrierClaimStatus || undefined, remark: remark || null, action: action || '登记理赔', attachmentIds: Array.isArray(attachmentIds) ? attachmentIds : [], operatorId, operatorSnapshot, warehouseId, }); return this.success('理赔登记成功', result); } // =========================== // 导出 // =========================== /** * 提交售后单导出任务。 * 异步执行:分页查询 → ExcelJS 流式写入 → COS 上传。 * 进度通过 Redis 缓存追踪。 * * @param {Object} data 请求体 * @param {Object} [data.where] 筛选条件(与列表一致) * @param {Object} [data.sort] 排序参数 * @return {Promise} 统一 success 包装,返回任务ID */ async export(data = {}) { const { service } = this; const { where, sort } = data || {}; const taskId = this.generateExportTaskId(); const taskPayload = { task_id: taskId, status: 'submitted', progress: 0, current_count: 0, total_count: 0, message: '导出任务已提交', result: null, error: '', }; await this.setExportTaskProgress(taskId, taskPayload); setImmediate(async () => { try { await this.setExportTaskProgress(taskId, { task_id: taskId, status: 'running', progress: 5, current_count: 0, total_count: 0, message: '导出任务执行中', result: null, error: '', }); const result = await service.systems.afterSale.exportAfterSales({ where: this.isPlainObject(where) ? { ...where } : {}, sort: this.isPlainObject(sort) ? { ...sort } : {}, onProgress: async progress => { const safeProgress = this.isPlainObject(progress) ? progress : {}; await this.setExportTaskProgress(taskId, { task_id: taskId, status: safeProgress.status || 'running', progress: safeProgress.progress, current_count: safeProgress.currentCount || 0, total_count: safeProgress.totalCount || 0, message: safeProgress.message || '导出任务执行中', result: safeProgress.result || null, error: '', }); }, }); await this.setExportTaskProgress(taskId, { task_id: taskId, status: 'success', progress: 100, current_count: result.current_count || 0, total_count: result.total_count || 0, message: '导出任务完成', result, error: '', }); } catch (error) { const errorMessage = error && error.message ? error.message : `${error}`; await this.setExportTaskProgress(taskId, { task_id: taskId, status: 'failed', progress: 100, current_count: 0, total_count: 0, message: '导出任务失败', result: null, error: errorMessage, }); } }); return this.success('ok', { ...taskPayload, update_time: Date.now(), }); } /** * 查询售后单导出任务进度。 * * @param {Object} data 请求体 * @param {string} [data.task_id] 任务ID(下划线写法) * @param {string} [data.taskId] 任务ID(驼峰写法) * @return {Promise} 统一 success 包装,包含进度与下载链接 */ async exportTaskProgress(data = {}) { const taskId = this.normalizeExportTaskId(data); if (!taskId) { return this.success('ok', { task_id: '', status: 'not_found', progress: 0, current_count: 0, total_count: 0, message: '任务不存在', result: null, error: '', download_url: '', update_time: Date.now(), }); } const cachedTask = await this.getExportTaskProgress(taskId); if (!cachedTask) { return this.success('ok', { task_id: taskId, status: 'not_found', progress: 0, current_count: 0, total_count: 0, message: '任务不存在', result: null, error: '', download_url: '', update_time: Date.now(), }); } const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; const downloadUrl = String( safeResult.url || safeResult.cdnUrl || safeResult.cosUrl || safeResult.fileKey || '' ); return this.success('ok', { task_id: taskId, ...cachedTask, download_url: downloadUrl, }); } // =========================== // 辅助方法 // =========================== /** * 生成售后单号。 * 格式:AS + YYYYMMDD + 6位序号(如 AS20240809000001)。 * * @param {number} warehouseId 仓库ID * @return {Promise} 售后单号 */ async generateAfterSaleNo(warehouseId) { const { ctx } = this; const datePart = this._getCurrentDatePart(); const prefix = 'AS'; const sql = ` SELECT after_sale_no FROM wms_after_sale WHERE warehouse_id = :warehouseId AND after_sale_no LIKE :pattern ORDER BY after_sale_no DESC LIMIT 1 `; const pattern = `${prefix}${datePart}%`; const rows = await ctx.model.query(sql, { replacements: { warehouseId, pattern }, type: ctx.model.QueryTypes.SELECT, }); const latestNo = String(rows && rows[0] && rows[0].after_sale_no || '').trim(); let sequence = 1; if (latestNo) { const match = latestNo.match(/(\d{6})$/); const lastSequence = match ? Number(match[1]) : 0; if (Number.isInteger(lastSequence) && lastSequence > 0) { sequence = lastSequence + 1; } } return `${prefix}${datePart}${String(sequence).padStart(6, '0')}`; } /** * 获取当前日期片段(YYYYMMDD)。 * * @return {string} 当前日期片段 */ _getCurrentDatePart() { const now = new Date(); const year = now.getFullYear(); const month = String(now.getMonth() + 1).padStart(2, '0'); const day = String(now.getDate()).padStart(2, '0'); return `${year}${month}${day}`; } /** * 构建操作人快照 JSON 字符串。 * 从 ctx.user 中提取关键身份信息。 * * @return {string} 操作人快照 JSON */ _buildOperatorSnapshot() { const { ctx } = this; const user = ctx.user && typeof ctx.user === 'object' ? ctx.user : {}; const snapshot = { id: user.id || user.user_id || null, name: user.employees_name || user.real_name || user.name || '', role: user.role && user.role.name ? user.role.name : '', }; return JSON.stringify(snapshot); } /** * 生成导出任务ID。 * * @return {string} 导出任务ID */ generateExportTaskId() { const warehouseId = this.ctx && this.ctx.user && this.ctx.user.store_id ? this.ctx.user.store_id : 'unknown'; const timestamp = Date.now(); const randomToken = Math.random().toString(36).slice(2, 10); return `after_sale_export_${warehouseId}_${timestamp}_${randomToken}`; } /** * 归一化导出任务ID(兼容 task_id / taskId)。 * * @param {Object} data 请求体 * @param {string} [data.task_id] 任务ID(下划线写法) * @param {string} [data.taskId] 任务ID(驼峰写法) * @return {string} 归一化后的任务ID */ normalizeExportTaskId(data = {}) { const normalizedData = this.isPlainObject(data) ? data : {}; return String(normalizedData.task_id || normalizedData.taskId || '').trim(); } /** * 获取导出任务缓存键。 * * @param {string} taskId 任务ID * @return {string} 缓存键 */ getExportTaskCacheKey(taskId = '') { const normalizedTaskId = String(taskId || '').trim(); if (!normalizedTaskId) { return ''; } return `${AFTER_SALE_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; } /** * 写入导出任务进度缓存。 * * @param {string} taskId 任务ID * @param {Object} payload 任务状态载荷 * @return {Promise} 无返回值 */ async setExportTaskProgress(taskId = '', payload = {}) { const cacheKey = this.getExportTaskCacheKey(taskId); if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { return; } const safePayload = this.isPlainObject(payload) ? payload : {}; const normalizeCount = value => { const numericValue = Number(value); return Number.isFinite(numericValue) && numericValue >= 0 ? Math.round(numericValue) : 0; }; const progressPayload = { task_id: String(taskId || '').trim(), status: String(safePayload.status || 'submitted').trim() || 'submitted', progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0, current_count: normalizeCount(safePayload.current_count), total_count: normalizeCount(safePayload.total_count), message: String(safePayload.message || ''), result: safePayload.result ?? null, error: String(safePayload.error || ''), update_time: Date.now(), }; try { await this.app.setCacheAsync( cacheKey, progressPayload, AFTER_SALE_EXPORT_TASK_CACHE_TTL_SECONDS ); } catch (error) { const errorMessage = error && error.message ? error.message : `${error}`; this.ctx.logger.warn(`[afterSale.export] 写入导出任务缓存失败: ${errorMessage}`); } } /** * 读取导出任务进度缓存。 * * @param {string} taskId 任务ID * @return {Promise} 任务缓存,不存在则返回 null */ async getExportTaskProgress(taskId = '') { const cacheKey = this.getExportTaskCacheKey(taskId); if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { return null; } try { const cached = await this.app.getCacheAsync(cacheKey); if (!this.isPlainObject(cached)) { return null; } return cached; } catch (error) { const errorMessage = error && error.message ? error.message : `${error}`; this.ctx.logger.warn(`[afterSale.export] 读取导出任务缓存失败: ${errorMessage}`); return null; } } } module.exports = AfterSaleMethodService;