diff --git a/app/model/after_sale.js b/app/model/after_sale.js new file mode 100644 index 0000000..2ec2f60 --- /dev/null +++ b/app/model/after_sale.js @@ -0,0 +1,421 @@ +'use strict'; + +/** + * 售后主表 Model,基于 `wms_after_sale` 表。 + * @param {import('egg').Application} app Egg 应用实例 + * @return {import('sequelize').ModelCtor} 售后 Model(含常量挂载) + */ +module.exports = app => { + const { STRING, BIGINT, INTEGER, DECIMAL, TEXT, TINYINT, DATE } = app.Sequelize; + + // ============================ + // 枚举常量定义 + // ============================ + + /** + * 售后类型 + 子类型枚举,按业务单据维度分类。 + * @type {Array<{name: string, type: string, subType: Array<{name: string, value: string}>}>} + */ + const AFTER_SALE_TYPES = [ + { + name: '订单', + type: 'order', + subType: [ + { name: '破损', value: 'damage' }, + { name: '少发', value: 'missing_item' }, + { name: '错发', value: 'mis_shipment' }, + { name: '错品', value: 'wrong_sku' }, + { name: '质量问题', value: 'quality_issue' }, + { name: '发货延迟', value: 'delivery_delay' }, + { name: '物流异常', value: 'logistics_issue' }, + { name: '客户拒收', value: 'rejected' }, + { name: '拦截', value: 'intercept' }, + { name: '核实签收', value: 'verify_delivery' }, + { name: '催件', value: 'urge' }, + { name: '多发', value: 'extra_item' }, + { name: '改地址', value: 'change_address' }, + { name: '换快递', value: 'change_carrier' }, + { name: '重量异常', value: 'weight_issue' }, + { name: '运费争议', value: 'freight_issue' }, + { name: '其他', value: 'other' }, + ], + }, + { + name: '收货单', + type: 'receiving', + subType: [ + { name: '少货', value: 'shortage' }, + { name: '破损', value: 'damage' }, + { name: '错品', value: 'wrong_sku' }, + { name: '质量问题', value: 'quality_issue' }, + { name: '其他', value: 'other' }, + ], + }, + { + name: '入库单', + type: 'entry', + subType: [ + { name: '少货', value: 'shortage' }, + { name: '破损', value: 'damage' }, + { name: '错品', value: 'wrong_sku' }, + { name: '质量问题', value: 'quality_issue' }, + { name: '其他', value: 'other' }, + ], + }, + { + name: '出库单', + type: 'stockout', + subType: [ + { name: '退货异常', value: 'return_issue' }, + { name: '错发', value: 'wrong_outbound' }, + { name: '少发', value: 'shortage' }, + { name: '其他', value: 'other' }, + ], + }, + ]; + + /** + * 售后处理角色组枚举。 + * @type {{customer_service: string, warehouse: string, finance: string}} + */ + const AFTER_SALE_ROLE_GROUPS = { + customer_service: '客服组', + warehouse: '仓库组', + finance: '财务组', + }; + + /** + * 售后单状态枚举。 + * @type {{pending: string, processing: string, completed: string, closed: string, cancelled: string}} + */ + const AFTER_SALE_STATUS = { + pending: '待处理', + processing: '处理中', + completed: '已完成', + closed: '已关闭', + cancelled: '已取消', + }; + + /** + * 理赔状态枚举(仓库理赔 & 运方理赔通用)。 + * @type {{pending: string, reviewing: string, approved: string, paid: string, monthly: string, rejected: string}} + */ + const CLAIM_STATUS = { + pending: '待理赔', + reviewing: '审核中', + approved: '已通过', + paid: '已打款', + monthly: '月结', + rejected: '已拒绝', + }; + + // ============================ + // Model 定义 + // ============================ + + const AfterSale = app.model.define('after_sale', { + /** 主键 */ + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键', + }, + /** 仓库ID */ + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + /** 货主ID */ + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '货主ID', + }, + /** 售后单号,唯一 */ + after_sale_no: { + type: STRING(50), + allowNull: false, + comment: '售后单号,唯一。生成规则:前缀AS + 日期YYYYMMDD + 6位序号', + }, + /** 售后类型 */ + type: { + type: STRING(20), + allowNull: false, + comment: '售后类型:order=订单, receiving=收货单, entry=入库单, stockout=出库单', + }, + /** 售后子类型 */ + sub_type: { + type: STRING(50), + allowNull: false, + comment: '售后子类型,与 type 组成二级分类', + }, + /** 售后状态 */ + status: { + type: STRING(20), + allowNull: false, + defaultValue: 'pending', + comment: '售后状态:pending=待处理, processing=处理中, completed=已完成, closed=已关闭, cancelled=已取消', + }, + /** 优先级 */ + priority: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '优先级,数值越大越优先(0=普通,10=紧急)', + }, + /** 售后标题 */ + title: { + type: STRING(200), + allowNull: false, + comment: '售后标题(简要描述)', + }, + /** 售后详细描述 */ + description: { + type: TEXT, + allowNull: true, + comment: '售后详细描述', + }, + /** 创建人账户ID */ + creator_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '创建人账户ID(关联 accounts 表)', + }, + /** 关联站内信消息ID */ + inbox_message_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联 wms_inbox_message.id,为空表示无关联信息', + }, + /** 当前处理角色组 */ + role_group: { + type: STRING(50), + allowNull: true, + comment: '当前处理角色组:customer_service=客服组, warehouse=仓库组, finance=财务组。NULL 表示未分配', + }, + /** 最终处理结果说明 */ + resolution: { + type: TEXT, + allowNull: true, + comment: '最终处理结果说明', + }, + /** 完结时间 */ + resolved_at: { + type: DATE, + allowNull: true, + comment: '完结时间(状态变为 completed 时写入)', + }, + /** 仓库理赔标记 */ + claim_needed: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '仓库理赔标记:0=不需要,1=需要', + }, + /** 仓库理赔金额(元) */ + claim_amount: { + type: DECIMAL(12, 2), + allowNull: true, + comment: '仓库理赔金额,单位:人民币(元),claim_needed=1 时可填写', + }, + /** 仓库理赔状态 */ + claim_status: { + type: STRING(20), + allowNull: true, + comment: '仓库理赔状态:pending=待理赔, reviewing=审核中, approved=已通过, paid=已打款, monthly=月结, rejected=已拒绝', + }, + /** 运方理赔标记 */ + carrier_claim_needed: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '运方理赔标记:0=不需要,1=需要', + }, + /** 运方理赔金额(元) */ + carrier_claim_amount: { + type: DECIMAL(12, 2), + allowNull: true, + comment: '运方理赔金额,单位:人民币(元),carrier_claim_needed=1 时可填写', + }, + /** 运方理赔状态 */ + carrier_claim_status: { + type: STRING(20), + allowNull: true, + comment: '运方理赔状态:pending=待理赔, reviewing=审核中, approved=已通过, paid=已打款, monthly=月结, rejected=已拒绝', + }, + // ========== 单据关联字段(替代旧版多态关联) ========== + /** 运单ID */ + waybill_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '运单ID(关联 wms_order_express.id)', + }, + /** 运单号(冗余) */ + waybill_no: { + type: STRING(50), + allowNull: true, + comment: '运单号(冗余字段,方便查询展示)', + }, + /** 发货订单ID */ + order_delivery_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '发货订单ID(关联 wms_order_delivery.id)', + }, + /** 发货订单号(冗余) */ + order_delivery_no: { + type: STRING(50), + allowNull: true, + comment: '发货订单号(冗余字段)', + }, + /** 入库单ID */ + entry_order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '入库单ID(关联 wms_entry_order.id)', + }, + /** 入库单号(冗余) */ + entry_order_no: { + type: STRING(50), + allowNull: true, + comment: '入库单号(冗余字段)', + }, + /** 出库单/退货出库单ID */ + order_stockout_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '出库单/退货出库单ID(关联 wms_order_stockout.id)', + }, + /** 出库单号(冗余) */ + order_stockout_no: { + type: STRING(50), + allowNull: true, + comment: '出库单号(冗余字段)', + }, + /** 收货单ID */ + receiving_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '收货单ID(关联 wms_receiving.id)', + }, + /** 收货单号(冗余) */ + receiving_no: { + type: STRING(50), + allowNull: true, + comment: '收货单号(冗余字段)', + }, + /** 创建时间 */ + created_at: { + type: DATE, + allowNull: true, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + /** 更新时间 */ + updated_at: { + type: DATE, + allowNull: true, + comment: '更新时间', + }, + /** 软删除时间 */ + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_after_sale', + comment: '售后主表', + timestamps: false, + indexes: [ + { + name: 'uk_after_sale_no', + unique: true, + fields: [ 'after_sale_no' ], + }, + { + name: 'idx_warehouse_status', + fields: [ 'warehouse_id', 'status', 'deleted_at' ], + }, + { + name: 'idx_warehouse_type', + fields: [ 'warehouse_id', 'type', 'deleted_at' ], + }, + { + name: 'idx_type_subtype', + fields: [ 'warehouse_id', 'type', 'sub_type', 'deleted_at' ], + }, + { + name: 'idx_store_id', + fields: [ 'store_id', 'deleted_at' ], + }, + { + name: 'idx_creator_id', + fields: [ 'creator_id', 'deleted_at' ], + }, + { + name: 'idx_role_group', + fields: [ 'role_group', 'status', 'deleted_at' ], + }, + { + name: 'idx_created_at', + fields: [ 'warehouse_id', 'created_at' ], + }, + { + name: 'idx_waybill_id', + fields: [ 'waybill_id' ], + }, + { + name: 'idx_order_delivery_id', + fields: [ 'order_delivery_id' ], + }, + { + name: 'idx_entry_order_id', + fields: [ 'entry_order_id' ], + }, + { + name: 'idx_order_stockout_id', + fields: [ 'order_stockout_id' ], + }, + { + name: 'idx_receiving_id', + fields: [ 'receiving_id' ], + }, + { + name: 'idx_carrier_claim_status', + fields: [ 'carrier_claim_status' ], + }, + { + name: 'idx_inbox_message_id', + fields: [ 'inbox_message_id' ], + }, + ], + }); + + // ============================ + // 关联关系 + // ============================ + + AfterSale.associate = function() { + const { AfterSale, AfterSaleDetail } = app.model; + + // 关联售后进度步骤(一对多) + AfterSale.hasMany(AfterSaleDetail, { + foreignKey: 'after_sale_id', + as: 'details', + }); + }; + + // ============================ + // 常量挂载到 Model + // ============================ + + AfterSale.AFTER_SALE_TYPES = AFTER_SALE_TYPES; + AfterSale.AFTER_SALE_ROLE_GROUPS = AFTER_SALE_ROLE_GROUPS; + AfterSale.AFTER_SALE_STATUS = AFTER_SALE_STATUS; + AfterSale.CLAIM_STATUS = CLAIM_STATUS; + + return AfterSale; +}; diff --git a/app/model/after_sale_detail.js b/app/model/after_sale_detail.js new file mode 100644 index 0000000..9a828e2 --- /dev/null +++ b/app/model/after_sale_detail.js @@ -0,0 +1,143 @@ +'use strict'; + +/** + * 售后进度步骤表 Model,基于 `wms_after_sale_detail` 表。 + * @param {import('egg').Application} app Egg 应用实例 + * @return {import('sequelize').ModelCtor} 售后进度步骤 Model(含常量挂载) + */ +module.exports = app => { + const { STRING, BIGINT, TEXT, TINYINT, DATE } = app.Sequelize; + + // ============================ + // 枚举常量定义 + // ============================ + + /** + * 步骤状态枚举。 + * @type {{0: string, 1: string, 2: string, 3: string}} + */ + const STEP_STATUS = { + 0: '待开始', + 1: '进行中', + 2: '已完成', + 3: '已跳过', + }; + + // ============================ + // Model 定义 + // ============================ + + const AfterSaleDetail = app.model.define('after_sale_detail', { + /** 主键 */ + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键', + }, + /** 关联售后主表ID */ + after_sale_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '关联售后主表ID(wms_after_sale.id)', + }, + /** 步骤状态 */ + step_status: { + type: TINYINT(3).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '步骤状态:0=待开始,1=进行中,2=已完成,3=已跳过', + }, + /** 操作人账户ID */ + operator_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '操作人账户ID(关联 accounts 表);外部系统回调/自动触发的步骤可为空', + }, + /** 操作人信息快照 */ + operator_snapshot: { + type: TEXT, + allowNull: true, + comment: '操作人信息快照(JSON),如 {"name":"张三","role":"客服"},防止账户删除后历史丢失', + }, + /** 操作动作描述 */ + action: { + type: STRING(100), + allowNull: true, + comment: '操作动作描述,如"确认收货"、"审核驳回"、"发起退款"', + }, + /** 处理备注 */ + remark: { + type: TEXT, + allowNull: true, + comment: '处理备注', + }, + /** 步骤开始时间 */ + started_at: { + type: DATE, + allowNull: true, + comment: '步骤开始时间', + }, + /** 步骤完成时间 */ + completed_at: { + type: DATE, + allowNull: true, + comment: '步骤完成时间', + }, + /** 创建时间 */ + created_at: { + type: DATE, + allowNull: true, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + /** 更新时间 */ + updated_at: { + type: DATE, + allowNull: true, + comment: '更新时间', + }, + /** 软删除时间 */ + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_after_sale_detail', + comment: '售后进度步骤表', + timestamps: false, + indexes: [ + { + name: 'idx_after_sale_id', + fields: [ 'after_sale_id' ], + }, + { + name: 'idx_operator_id', + fields: [ 'operator_id' ], + }, + ], + }); + + // ============================ + // 关联关系 + // ============================ + + AfterSaleDetail.associate = function() { + const { AfterSale, AfterSaleDetail } = app.model; + + // 关联售后主表(多对一) + AfterSaleDetail.belongsTo(AfterSale, { + foreignKey: 'after_sale_id', + as: 'afterSale', + }); + }; + + // ============================ + // 常量挂载到 Model + // ============================ + + AfterSaleDetail.STEP_STATUS = STEP_STATUS; + + return AfterSaleDetail; +}; diff --git a/app/service/systemMethods/afterSale.js b/app/service/systemMethods/afterSale.js new file mode 100644 index 0000000..9263fad --- /dev/null +++ b/app/service/systemMethods/afterSale.js @@ -0,0 +1,843 @@ +'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', +}); + +/** + * 售后模块工作列表排除的状态(已完成/已取消)。 + */ +const WORK_LIST_EXCLUDED_STATUSES = Object.freeze([ 'completed', 'cancelled' ]); + +/** + * 系统方法层:afterSale(售后模块接口包装层)。 + * 主要职责:统一包装系统方法接口,处理权限、日志、where 解析等公共逻辑, + * 将具体业务逻辑下沉到 systems.afterSale 中。 + */ +class AfterSaleMethodService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'workList,auditList,detail,create,transfer,handleWorkOrder,registerClaim,export,exportTaskProgress'; + const _noNeedLog = 'workList,auditList,detail,export,exportTaskProgress'; + const _noNeedAuth = 'workList,auditList,detail,create,transfer,handleWorkOrder,registerClaim,export,exportTaskProgress'; + 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 = 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); + return this.success('ok', result); + } + + /** + * 解析当前用户所拥有的售后 block 权限对应的 role_group 列表。 + * 从 ctx.user.role.permissions 中筛选 type=block 且 ID 为 516/517/518 的权限项。 + * + * @return {string[]} 当前用户可处理的 role_group 列表 + */ + _resolveAfterSaleBlockRoleGroups() { + const { ctx } = this; + const rolePermissions = ctx.user && ctx.user.role && Array.isArray(ctx.user.role.permissions) + ? ctx.user.role.permissions + : []; + + const allowedRoleGroups = []; + for (const perm of rolePermissions) { + const permId = Number(perm && (perm.id || perm.permission_id || 0)); + const permType = String(perm && (perm.type || '')).trim(); + if (permType === 'block' && BLOCK_PERMISSION_ROLE_GROUP_MAP[permId]) { + allowedRoleGroups.push(BLOCK_PERMISSION_ROLE_GROUP_MAP[permId]); + } + } + + // 如果未匹配到任何售后 block 权限,默认不给任何 role_group 可见范围 + if (allowedRoleGroups.length === 0) { + return [ '__none__' ]; + } + + return allowedRoleGroups; + } + + // =========================== + // 售后审计列表 + // =========================== + + /** + * 售后审计列表:不限 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 + * @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: orderDeliveryId, + entry_order_id: entryOrderId, + order_stockout_id: orderStockoutId, + receiving_id: receivingId, + store_id: storeId, + inbox_message_id: inboxMessageId, + } = data || {}; + + // 生成售后单号 + 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_delivery_id: orderDeliveryId || null, + order_delivery_no: redundantFields.order_delivery_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_delivery_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.target_role_group 目标角色组(customer_service/warehouse/finance) + * @param {string} [data.remark] 转单备注 + * @return {Promise} 统一 success 包装 + */ + async transfer(data = {}) { + const { ctx, service } = this; + const { + id, + target_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.action 操作动作描述 + * @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, + action, + remark, + status: targetStatus, + resolution, + attachment_ids: attachmentIds, + } = data || {}; + + if (!id) { + return this.fail('缺少售后单ID'); + } + if (!action) { + return this.fail('缺少操作动作'); + } + + 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), + action, + remark: remark || null, + targetStatus: targetStatus || null, + resolution: resolution || null, + attachmentIds: Array.isArray(attachmentIds) ? attachmentIds : [], + 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; diff --git a/app/service/systems/afterSale.js b/app/service/systems/afterSale.js new file mode 100644 index 0000000..e44e387 --- /dev/null +++ b/app/service/systems/afterSale.js @@ -0,0 +1,863 @@ +'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; diff --git a/database/designs/after-sale-v2-design.md b/database/designs/after-sale-v2-design.md new file mode 100644 index 0000000..1244763 --- /dev/null +++ b/database/designs/after-sale-v2-design.md @@ -0,0 +1,845 @@ +# 售后模块 V2 设计方案 + +> **状态**: 📋 v1 初稿,待评审 +> **设计日期**: 2026-08-09 +> **设计人**: wms-doc-agent +> **模块**: 售后管理(After-Sale) +> **表**: 2 张 — `wms_after_sale`(售后主表)、`wms_after_sale_detail`(售后进度步骤表) +> **说明**: 本文档为全新设计,替代已移除的旧版 `wms_after_sale_work_order` + `wms_after_sale_work_order_step` 体系。 + +--- + +## 一、设计背景 + +### 1.1 旧版问题 + +旧版售后工单(`after_sale_work_order` + `after_sale_work_order_step`)已于 2026-08-09 通过迁移 `20260809120000-drop-wms-after-sale-work-order.js` 正式移除。旧版存在以下核心问题: + +1. **多态关联难以维护**:使用 `business_type` + `business_sub_type` + `business_id` 三元组关联业务单据,导致: + - 查询需要动态拼接 JOIN 条件,性能差 + - 无法利用数据库外键约束保证数据完整性 + - 业务类型枚举膨胀,新增业务类型需改动多处代码 +2. **不支持多单据共存**:一个售后单只能关联一种业务单据,实际场景中退货退款往往同时涉及运单、发货订单、收货单等多张单据 +3. **覆盖场景不足**:旧版仅覆盖工单流转,未涵盖理赔、投诉等售后场景 +4. **缺少明细层级**:无法记录售后单中的商品明细(退什么货、换什么货、赔多少钱) + +### 1.2 V2 设计目标 + +| 目标 | 说明 | +|------|------| +| **废弃多态关联** | 每种业务单据使用独立字段,类型安全、查询高效 | +| **支持多单据共存** | 一个售后单可同时关联运单、发货订单、入库单、出库单、收货单等 | +| **覆盖全场景** | 按单据维度分类(订单/收货单/入库单/出库单),售后动作(退货/换货/理赔/投诉等)通过进度步骤体现 | +| **进度追溯** | `wms_after_sale_detail` 记录售后处理进度步骤,支持按步骤序号追踪操作人、操作动作、处理时间 | +| **可追溯** | 完整记录创建人、处理人、最终处理结果、完结时间 | + +### 1.3 与旧版核心差异 + +| 维度 | 旧版(已移除) | V2(本设计) | +|------|---------------|-------------| +| 主表 | `wms_after_sale_work_order` | `wms_after_sale` | +| 子表 | `wms_after_sale_work_order_step`(工单步骤流转) | `wms_after_sale_detail`(售后进度步骤) | +| 单据关联 | 多态三元组 `business_type + business_sub_type + business_id` | 每种单据独立字段组,可多个同时有值 | +| 多单据共存 | ❌ 不支持 | ✅ 支持 | +| 理赔 | ❌ 不支持 | ✅ 内建仓库理赔(`claim_needed / claim_amount / claim_status`)和运方理赔(`carrier_claim_needed / carrier_claim_amount / carrier_claim_status`) | +| 进度步骤 | ❌ `after_sale_work_order_step` | ✅ `wms_after_sale_detail` 记录步骤序号/操作人/操作动作/耗时 | +| 商品明细 | ❌ 无 | ❌ 不再独立建表,商品明细可存入 `remark` 或扩展 JSON 字段 | + +--- + +## 二、ER 图 + +```mermaid +erDiagram + wms_after_sale ||--o{ wms_after_sale_detail : "1:N" + + wms_after_sale { + BIGINT id PK "主键" + BIGINT warehouse_id "仓库ID" + BIGINT store_id "货主ID" + VARCHAR after_sale_no UK "售后单号,唯一" + VARCHAR type "售后类型" + VARCHAR sub_type "售后子类型" + VARCHAR status "状态" + INT priority "优先级" + VARCHAR title "标题" + TEXT description "描述" + BIGINT creator_id "创建人" + BIGINT inbox_message_id "关联消息ID" + VARCHAR role_group "角色组" + TEXT resolution "最终处理结果" + DATETIME resolved_at "完结时间" + TINYINT claim_needed "仓库理赔标记" + DECIMAL claim_amount "仓库理赔金额(元)" + VARCHAR claim_status "仓库理赔状态" + TINYINT carrier_claim_needed "运方理赔标记" + DECIMAL carrier_claim_amount "运方理赔金额(元)" + VARCHAR carrier_claim_status "运方理赔状态" + BIGINT waybill_id "运单ID" + VARCHAR waybill_no "运单号" + BIGINT order_delivery_id "发货订单ID" + VARCHAR order_delivery_no "发货订单号" + BIGINT entry_order_id "入库单ID" + VARCHAR entry_order_no "入库单号" + BIGINT order_stockout_id "出库单ID" + VARCHAR order_stockout_no "出库单号" + BIGINT receiving_id "收货单ID" + VARCHAR receiving_no "收货单号" + DATETIME created_at "创建时间" + DATETIME updated_at "更新时间" + DATETIME deleted_at "软删除" + } + + wms_after_sale_detail { + BIGINT id PK "主键" + BIGINT after_sale_id FK "关联售后主表" + TINYINT step_status "步骤状态" + BIGINT operator_id "操作人ID" + TEXT operator_snapshot "操作人信息快照" + VARCHAR action "操作动作" + TEXT remark "处理备注" + DATETIME started_at "步骤开始时间" + DATETIME completed_at "步骤完成时间" + DATETIME created_at "创建时间" + DATETIME updated_at "更新时间" + DATETIME deleted_at "软删除" + } +``` + +### 关联关系说明 + +``` +wms_after_sale + ├─ warehouse_id → stores.id(仓库,逻辑关联) + ├─ store_id → stores.id(货主,逻辑关联) + ├─ creator_id → accounts.id(创建人,逻辑关联) + ├─ inbox_message_id → wms_inbox_message.id(站内信消息,逻辑关联) + ├─ waybill_id → wms_order_express.id(运单,逻辑关联) + ├─ order_delivery_id → wms_order_delivery.id(发货订单,逻辑关联) + ├─ entry_order_id → wms_entry_order.id(入库单,逻辑关联) + ├─ order_stockout_id → wms_order_stockout.id(出库单,逻辑关联) + └─ receiving_id → wms_receiving.id(收货单,逻辑关联) + +wms_after_sale_detail + └─ after_sale_id → wms_after_sale.id(级联删除) +``` + +> **注意**:所有关联均为逻辑关联(不做物理外键),遵循项目现有惯例。 + +--- + +## 三、数据库表 + +### 3.1 表 A:售后主表 `wms_after_sale` + +#### 3.1.1 基础字段 + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `id` | `BIGINT UNSIGNED` | ✅ | AUTO | 主键 | +| `warehouse_id` | `BIGINT UNSIGNED` | ✅ | — | 仓库ID | +| `store_id` | `BIGINT UNSIGNED` | — | NULL | 货主ID | + +#### 3.1.2 售后信息 + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `after_sale_no` | `VARCHAR(50)` | ✅ | — | **售后单号**,唯一索引。生成规则:前缀 `AS` + 日期 `YYYYMMDD` + 6 位序号(当天同仓库自增),如 `AS20260809000001`。参考波次号 `wave_no` 生成逻辑。 | +| `type` | `VARCHAR(20)` | ✅ | — | 售后类型,枚举见 §3.1.6 | +| `sub_type` | `VARCHAR(50)` | ✅ | — | 售后子类型,枚举见 §3.1.6,与 type 组成二级分类 | +| `status` | `VARCHAR(20)` | ✅ | `pending` | 售后状态,枚举及流转见 §五 | +| `priority` | `INT(11)` | ✅ | 0 | 优先级,数值越大越优先(0=普通,10=紧急) | +| `title` | `VARCHAR(200)` | ✅ | — | 售后标题(简要描述) | +| `description` | `TEXT` | — | NULL | 售后详细描述 | + +#### 3.1.3 人员信息 + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `creator_id` | `BIGINT UNSIGNED` | ✅ | — | 创建人账户ID(关联 `accounts` 表) | +| `role_group` | `VARCHAR(50)` | — | NULL | 当前处理角色组,用于角色维度查询待处理工单和转单。枚举见 §3.1.6。NULL 表示未分配。 | +| `inbox_message_id` | `BIGINT UNSIGNED` | — | NULL | 关联 `wms_inbox_message.id`(站内信消息主键)。为空表示无关联信息,非空表示该售后单由对应站内信消息创建或关联。 | + +#### 3.1.4 处理结果 + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `resolution` | `TEXT` | — | NULL | 最终处理结果说明 | +| `resolved_at` | `DATETIME` | — | NULL | 完结时间(状态变为 `completed` 时写入) | + +#### 3.1.5 仓库理赔 & 运方理赔 + +**仓库理赔**: + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `claim_needed` | `TINYINT(1)` | ✅ | 0 | 仓库理赔标记:0=不需要,1=需要 | +| `claim_amount` | `DECIMAL(12,2)` | — | NULL | 仓库理赔金额,单位:人民币(元),claim_needed=1 时可填写 | +| `claim_status` | `VARCHAR(20)` | — | NULL | 仓库理赔状态,枚举见 §3.1.6,仅 `claim_needed=1` 时有意义 | + +**运方理赔**: + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `carrier_claim_needed` | `TINYINT(1)` | ✅ | 0 | 运方理赔标记:0=不需要,1=需要 | +| `carrier_claim_amount` | `DECIMAL(12,2)` | — | NULL | 运方理赔金额,单位:人民币(元),carrier_claim_needed=1 时可填写 | +| `carrier_claim_status` | `VARCHAR(20)` | — | NULL | 运方理赔状态,枚举见 §3.1.6,仅 `carrier_claim_needed=1` 时有意义 | + +#### 3.1.6 类型与状态枚举 + +**售后类型 `type` + 售后子类型 `sub_type`**: + +> 售后类型表示售后单主要关联的业务单据类型,售后子类型表示具体售后原因分类,两者组成二级分类。具体的售后动作(退货/换货/理赔/投诉等)通过进度步骤和最终处理结果体现。 + +| type | 说明 | sub_type | +|------|------|----------| +| `order` | 订单 | `damage` 破损, `missing_item` 少发, `mis_shipment` 错发, `wrong_sku` 错品, `quality_issue` 质量问题, `delivery_delay` 发货延迟, `logistics_issue` 物流异常, `rejected` 客户拒收, `intercept` 拦截, `verify_delivery` 核实签收, `urge` 催件, `extra_item` 多发, `change_address` 改地址, `change_carrier` 换快递, `weight_issue` 重量异常, `freight_issue` 运费争议, `other` 其他 | +| `receiving` | 收货单 | `shortage` 少货, `damage` 破损, `wrong_sku` 错品, `quality_issue` 质量问题, `other` 其他 | +| `entry` | 入库单 | `shortage` 少货, `damage` 破损, `wrong_sku` 错品, `quality_issue` 质量问题, `other` 其他 | +| `stockout` | 出库单 | `return_issue` 退货异常, `wrong_outbound` 错发, `shortage` 少发, `other` 其他 | + +**Model 层常量定义**(`app/model/after_sale.js`): + +```javascript +// app/model/after_sale.js 中的常量定义 +const AFTER_SALE_TYPES = [ + { + name: '订单', + type: 'order', + subType: [ + { name: '破损', value: 'damage' }, + { name: '少发', value: 'missing_item' }, + { name: '错发', value: 'mis_shipment' }, + { name: '错品', value: 'wrong_sku' }, + { name: '质量问题', value: 'quality_issue' }, + { name: '发货延迟', value: 'delivery_delay' }, + { name: '物流异常', value: 'logistics_issue' }, + { name: '客户拒收', value: 'rejected' }, + { name: '拦截', value: 'intercept' }, + { name: '核实签收', value: 'verify_delivery' }, + { name: '催件', value: 'urge' }, + { name: '多发', value: 'extra_item' }, + { name: '改地址', value: 'change_address' }, + { name: '换快递', value: 'change_carrier' }, + { name: '重量异常', value: 'weight_issue' }, + { name: '运费争议', value: 'freight_issue' }, + { name: '其他', value: 'other' }, + ], + }, + { + name: '收货单', + type: 'receiving', + subType: [ + { name: '少货', value: 'shortage' }, + { name: '破损', value: 'damage' }, + { name: '错品', value: 'wrong_sku' }, + { name: '质量问题', value: 'quality_issue' }, + { name: '其他', value: 'other' }, + ], + }, + { + name: '入库单', + type: 'entry', + subType: [ + { name: '少货', value: 'shortage' }, + { name: '破损', value: 'damage' }, + { name: '错品', value: 'wrong_sku' }, + { name: '质量问题', value: 'quality_issue' }, + { name: '其他', value: 'other' }, + ], + }, + { + name: '出库单', + type: 'stockout', + subType: [ + { name: '退货异常', value: 'return_issue' }, + { name: '错发', value: 'wrong_outbound' }, + { name: '少发', value: 'shortage' }, + { name: '其他', value: 'other' }, + ], + }, +]; +``` + +**角色组 `role_group`**: + +| 值 | 说明 | +|----|------| +| `customer_service` | 客服组 | +| `warehouse` | 仓库组 | +| `finance` | 财务组 | + +> 设计理由:运方(快递公司)是外部角色,不登录 WMS 系统,不纳入内部角色组。 + +**售后状态 `status`**: + +| 值 | 说明 | +|----|------| +| `pending` | 待处理 | +| `processing` | 处理中 | +| `completed` | 已完成 | +| `closed` | 已关闭 | +| `cancelled` | 已取消 | + +**理赔状态(仓库理赔 & 运方理赔通用枚举)**: + +| 值 | 说明 | +|----|------| +| `pending` | 待理赔 | +| `reviewing` | 审核中 | +| `approved` | 已通过 | +| `paid` | 已打款 | +| `monthly` | 月结 | +| `rejected` | 已拒绝 | + +#### 3.1.7 单据关联字段(核心设计) + +> **设计要点**:每种业务单据使用独立字段组(ID + 单号冗余),替代旧版多态关联。多个字段组可同时有值,实现"一个售后单关联多种单据"。 + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `waybill_id` | `BIGINT UNSIGNED` | — | NULL | 运单ID(关联 `wms_order_express.id`) | +| `waybill_no` | `VARCHAR(50)` | — | NULL | 运单号(冗余字段,方便查询展示) | +| `order_delivery_id` | `BIGINT UNSIGNED` | — | NULL | 发货订单ID(关联 `wms_order_delivery.id`) | +| `order_delivery_no` | `VARCHAR(50)` | — | NULL | 发货订单号(冗余字段) | +| `entry_order_id` | `BIGINT UNSIGNED` | — | NULL | 入库单ID(关联 `wms_entry_order.id`) | +| `entry_order_no` | `VARCHAR(50)` | — | NULL | 入库单号(冗余字段) | +| `order_stockout_id` | `BIGINT UNSIGNED` | — | NULL | 出库单/退货出库单ID(关联 `wms_order_stockout.id`) | +| `order_stockout_no` | `VARCHAR(50)` | — | NULL | 出库单号(冗余字段) | +| `receiving_id` | `BIGINT UNSIGNED` | — | NULL | 收货单ID(关联 `wms_receiving.id`) | +| `receiving_no` | `VARCHAR(50)` | — | NULL | 收货单号(冗余字段) | + +> **冗余字段说明**:`_no` 后缀字段为冗余存储,目的是在售后列表查询时避免 JOIN 各业务表。写入时从对应业务表同步取数,后续若业务表单号变更需同步更新(建议通过业务 hook 或定时任务保证最终一致)。 + +#### 3.1.8 时间戳 + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `created_at` | `DATETIME` | ✅ | `CURRENT_TIMESTAMP` | 创建时间 | +| `updated_at` | `DATETIME` | ✅ | `CURRENT_TIMESTAMP ON UPDATE` | 更新时间 | +| `deleted_at` | `DATETIME` | — | NULL | 软删除时间 | + +--- + +### 3.2 表 B:售后进度步骤表 `wms_after_sale_detail` + +用于记录售后单的处理进度步骤(谁在什么时间做了什么操作)。步骤按 `created_at` 自然时间排序,通过 `action` 描述步骤内容,可记录步骤开始/完成时间、操作人及操作快照。 + +#### 3.2.1 字段定义 + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `id` | `BIGINT UNSIGNED` | ✅ | AUTO | 主键 | +| `after_sale_id` | `BIGINT UNSIGNED` | ✅ | — | 关联售后主表ID(`wms_after_sale.id`) | +| `step_status` | `TINYINT UNSIGNED` | ✅ | 0 | 步骤状态:0=待开始,1=进行中,2=已完成,3=已跳过 | +| `operator_id` | `BIGINT UNSIGNED` | — | NULL | 操作人账户ID(关联 `accounts` 表);可为空,外部系统回调/自动触发的步骤无人操作 | +| `operator_snapshot` | `TEXT` | — | NULL | 操作人信息快照(JSON),如 `{"name":"张三","role":"客服"}`,防止账户删除后历史丢失 | +| `action` | `VARCHAR(100)` | — | NULL | 操作动作描述,如"确认收货"、"审核驳回"、"发起退款" | +| `remark` | `TEXT` | — | NULL | 处理备注 | +| `started_at` | `DATETIME` | — | NULL | 步骤开始时间 | +| `completed_at` | `DATETIME` | — | NULL | 步骤完成时间 | +| `created_at` | `DATETIME` | ✅ | `CURRENT_TIMESTAMP` | 创建时间 | +| `updated_at` | `DATETIME` | ✅ | `CURRENT_TIMESTAMP ON UPDATE` | 更新时间 | +| `deleted_at` | `DATETIME` | — | NULL | 软删除时间 | + +#### 3.2.2 步骤状态 `step_status` 枚举 + +| 值 | 说明 | 典型场景 | +|----|------|---------| +| `0` | 待开始 | 步骤尚未触发,等待前置步骤完成 | +| `1` | 进行中 | 步骤正在处理中 | +| `2` | 已完成 | 步骤处理完毕 | +| `3` | 已跳过 | 因条件不满足或审批豁免而跳过此步骤 | + +> **设计考量**:`step_status` 决定步骤的当前状态。步骤按 `created_at` 自然时间排序,通过 `action` 描述步骤内容。后续步骤在前置步骤全部 `completed` 或 `skipped` 后才能开始。步骤可在创建售后单时预置(如按 `type` 生成一套标准步骤),也可在处理过程中动态追加。 +> +> **外部系统触发说明**:当步骤由外部系统触发(如快递签收回调、支付平台退款回调、ERP 同步等)时,`operator_id` 为 NULL,`action` 记录触发来源(如"快递签收回调"、"支付宝退款通知")。这确保自动触发的步骤可追溯来源,同时与人工操作步骤明确区分。 + +### 3.2.3 附件关联 + +售后进度步骤可通过 `wms_file_reference` 表挂载附件(如破损照片、签收凭证、理赔单据等)。 + +**绑定方式:** + +| wms_file_reference 字段 | 值 | 说明 | +|--------------------------|-----|------| +| `business_type` | `after_sale_detail` | 售后进度步骤 | +| `business_id` | `{wms_after_sale_detail.id}` | 步骤主键ID | + +**典型场景:** +- 仓库验货步骤上传破损商品照片 +- 客服接单步骤上传客户提供的聊天截图 +- 运方理赔步骤上传快递破损证明 +- 退款步骤上传打款凭证截图 + +**查询示例:** +```sql +-- 查询某售后单所有步骤的附件 +SELECT f.*, fr.business_id AS step_id +FROM wms_file_reference fr +JOIN wms_file f ON f.id = fr.file_id +WHERE fr.business_type = 'after_sale_detail' + AND fr.business_id IN ( + SELECT id FROM wms_after_sale_detail WHERE after_sale_id = ? + ); +``` + +--- + +## 四、索引设计 + +### 4.1 `wms_after_sale` 索引 + +| 索引名 | 字段 | 类型 | 说明 | +|--------|------|------|------| +| `PRIMARY` | `id` | 主键 | — | +| `uk_after_sale_no` | `after_sale_no` | 唯一 | 售后单号唯一约束 | +| `idx_warehouse_status` | `warehouse_id`, `status`, `deleted_at` | 普通 | 按仓库+状态查询售后列表(最高频) | +| `idx_warehouse_type` | `warehouse_id`, `type`, `deleted_at` | 普通 | 按仓库+类型筛选 | +| `idx_type_subtype` | `warehouse_id`, `type`, `sub_type`, `deleted_at` | 普通 | 按仓库+类型+子类型筛选 | +| `idx_store_id` | `store_id`, `deleted_at` | 普通 | 按货主查询 | +| `idx_creator_id` | `creator_id`, `deleted_at` | 普通 | 按创建人查询 | +| `idx_role_group` | `role_group`, `status`, `deleted_at` | 普通 | 按角色组+状态查询待处理工单(角色维度) | +| `idx_created_at` | `warehouse_id`, `created_at` | 普通 | 按仓库+时间排序分页 | +| `idx_waybill_id` | `waybill_id` | 普通 | 按运单反查售后单 | +| `idx_order_delivery_id` | `order_delivery_id` | 普通 | 按发货订单反查售后单 | +| `idx_entry_order_id` | `entry_order_id` | 普通 | 按入库单反查售后单 | +| `idx_order_stockout_id` | `order_stockout_id` | 普通 | 按出库单反查售后单 | +| `idx_receiving_id` | `receiving_id` | 普通 | 按收货单反查售后单 | +| `idx_carrier_claim_status` | `carrier_claim_status` | 普通 | 按运方理赔状态筛选 | +| `idx_inbox_message_id` | `inbox_message_id` | 普通 | 按站内信消息反查售后单 | + +### 4.2 `wms_after_sale_detail` 索引 + +| 索引名 | 字段 | 类型 | 说明 | +|--------|------|------|------| +| `PRIMARY` | `id` | 主键 | — | +| `idx_after_sale_id` | `after_sale_id` | 普通 | 按售后单查询进度步骤(最高频) | +| `idx_operator_id` | `operator_id` | 普通 | 按操作人查询其处理的步骤 | + +--- + +## 五、状态流转 + +```mermaid +stateDiagram-v2 + [*] --> pending: 创建售后单 + pending --> processing: 指派处理人 / 开始处理 + pending --> cancelled: 取消 + processing --> completed: 处理完成 + processing --> closed: 强制关闭 + completed --> [*] + closed --> [*] + cancelled --> [*] +``` + +| 流转 | 触发条件 | 说明 | +|------|---------|------| +| `pending` → `processing` | 指派处理人 or 手动开始处理 | 通过 `wms_after_sale_detail` 记录的处理步骤追踪 | +| `pending` → `cancelled` | 创建人取消 | 仅待处理状态可取消 | +| `processing` → `completed` | 处理完毕 | 写入 `resolution` + `resolved_at` | +| `processing` → `closed` | 管理员强制关闭 | 如重复单、无效单等 | +| 转单(跨角色组) | 客服转仓库 / 仓库转财务等 | 更新 `role_group` 为目标角色组,如 `customer_service` → `warehouse`;同时可在 `wms_after_sale_detail` 记录转单步骤 | + +**理赔状态流转**(仓库理赔 & 运方理赔通用):`pending` → `reviewing` → `approved` → `paid`,任意阶段可 → `rejected`,或走 `monthly`(月结)通道。 + +> `wms_after_sale_detail` 即操作日志:每条进度步骤记录操作人、操作动作、处理备注、开始/完成时间,已完整覆盖状态变更追踪需求,无需额外日志表。 + +--- + +## 六、典型使用场景 + +### 场景1:订单售后(退货退款,关联运单 + 收货单) + +``` +售后单 type=order, sub_type=damage, role_group=customer_service +├─ inbox_message_id: 12345(关联站内信消息,客户发送"破损"指令触发) +├─ waybill_id / waybill_no: 客户寄回的快递单号 +├─ receiving_id / receiving_no: 仓库收货单 +└─ 进度步骤: + ├─ step_status=2(已完成), operator_id=1001, action=客服接单-受理退货申请 + ├─ step_status=2(已完成), operator_id=2001, action=仓库收货-确认收货入库 + └─ step_status=0(待开始), action=退款打款 +``` + +> **转单说明**:当客服接单后发现需要仓库核实实物时,可将 `role_group` 从 `customer_service` 更新为 `warehouse`,仓库组即可在自己的待办列表中看到该工单。 + +### 场景2:订单售后(换货,关联运单 + 发货订单) + +``` +售后单 type=order, sub_type=quality_issue +├─ waybill_id / waybill_no: 客户寄回的快递单号 +├─ order_delivery_id / order_delivery_no: 仓库补发的发货订单 +└─ 进度步骤: + ├─ step_status=2(已完成), action=客服接单-确认换货申请 + ├─ step_status=2(已完成), action=退回入库-客户退回商品已入库 + └─ step_status=1(进行中), action=补发换货-仓库补发新商品 +``` + +### 场景3:订单售后(仓库理赔) + +``` +售后单 type=order, sub_type=damage +├─ claim_needed=1, claim_amount=50.00, claim_status=pending +└─ 进度步骤: + ├─ step_status=2(已完成), action=客服接单-受理仓库理赔 + ├─ step_status=2(已完成), action=核实定损, remark=仓库出库破损, 核定赔偿50元 + └─ step_status=1(进行中), action=审批打款 +``` + +### 场景3b:订单售后(运方理赔) + +``` +售后单 type=order, sub_type=logistics_issue +├─ carrier_claim_needed=1, carrier_claim_amount=200.00, carrier_claim_status=pending +├─ waybill_id / waybill_no: 涉损运单 +└─ 进度步骤: + ├─ step_status=2(已完成), action=客服接单-受理运方理赔 + ├─ step_status=2(已完成), action=核实定损, remark=运输途中破损, 核定赔偿200元 + └─ step_status=1(进行中), action=快递审批 +``` + +> **说明**:仓库理赔与运方理赔可同时存在(如货物在仓库出库&运输途中均发生破损),分别使用 `claim_*` 和 `carrier_claim_*` 字段组记录。 + +### 场景4:订单售后(多单据共存:退货退款 + 运单 + 收货单 + 出库单) + +``` +售后单 type=order, sub_type=damage, role_group=warehouse +├─ waybill_id / waybill_no: 客户退货快递 +├─ receiving_id / receiving_no: 仓库收货单 +├─ order_stockout_id / order_stockout_no: 退货出库单 +└─ 进度步骤: + ├─ step_status=2(已完成), action=客服接单-批量退货受理 + ├─ step_status=2(已完成), operator_id=3001, action=验货签收, remark=SKU001×3, SKU002×1 均完好(可挂附件:破损照片 × 2) + ├─ step_status=2(已完成), action=退货入库 + └─ step_status=0(待开始), action=退款打款 +``` + +> **说明**:此场景中 `role_group=warehouse` 表示当前由仓库组负责验货入库环节;验货完成后如需财务退款,转单时将 `role_group` 更新为 `finance`。 + +--- + +## 七、迁移计划 + +### 7.1 迁移文件 + +``` +database/migrations/YYYYMMDDHHMMSS-create-wms-after-sale.js +database/migrations/YYYYMMDDHHMMSS-create-wms-after-sale-detail.js +``` + +### 7.2 Model 文件 + +``` +app/model/after_sale.js → wms_after_sale +app/model/after_sale_detail.js → wms_after_sale_detail +``` + +### 7.3 后续扩展(不纳入本期) + +| 扩展项 | 说明 | +|--------|------| +| 批量创建 | 按运单号/订单号批量生成售后单 | +| 自动创建规则 | 如收到退货快递自动创建售后单 | +| 售后统计看板 | 按仓库/类型/状态统计售后量、理赔金额等 | + +--- + +## 八、版本记录 + +| 版本 | 日期 | 变更内容 | 作者 | +|------|------|---------|------| +| v1 | 2026-08-09 | 初稿,待评审 | wms-doc-agent | + +--- + +## 九、权限设计 + +售后模块的角色组通过 `wms_permission` 表中 `type='block'` 的权限条目来承载,与主表 `role_group` 字段一一对应。 + +### 9.1 Block 权限(角色组区分) + +> ID 516-523 为售后模块固定 ID。 + +| ID | meta_title | type | 对应 role_group | +|----|-----------|------|-----------------| +| 516 | 售后-客服组 | `block` | `customer_service` | +| 517 | 售后-仓库组 | `block` | `warehouse` | +| 518 | 售后-财务组 | `block` | `finance` | + +> 生产组主管(role_code=03)和拣货组组长(role_code=021)使用仓库组 block(517),共享仓库组视角。 + +### 9.2 页面权限 + +| ID | path | meta_title | type | parent_id | +|----|------|-----------|------|-----------| +| 519 | `afterSale` | 售后管理 | `web_pages` | null | +| 520 | `afterSale.list` | 售后列表 | `web_pages` | 519 | +| 521 | `afterSale.detail` | 售后明细 | `web_pages` | 519 | + +### 9.3 API 权限 + +| ID | path | meta_title | type | +|----|------|-----------|------| +| 522 | `afterSale.workList` | API:售后工作列表查询 | `api` | +| 523 | `afterSale.auditList` | API:售后审计列表查询 | `api` | +| 508 | `afterSale.detail` | API:售后明细查询 | `api` | +| 509 | `afterSale.create` | API:创建售后单 | `api` | +| 510 | `afterSale.update` | API:更新售后单 | `api` | +| 511 | `afterSale.transfer` | API:售后转单 | `api` | +| 512 | `afterSale.handleWorkOrder` | API:处理工单 | `api` | +| 513 | `afterSale.registerClaim` | API:登记理赔 | `api` | +| 514 | `afterSale.export` | API:售后导出 | `api` | +| 515 | `afterSale.exportTaskProgress` | API:导出进度查询 | `api` | + +### 9.4 角色权限绑定 + +| 角色 | 角色组 block | 页面 | API | +|------|------------|------|-----| +| 客服 | 516 | 519, 520, 521 | 522, 523, 508, 509, 510, 511, 512, 513, 514, 515 | +| 仓库 | 517 | 519, 520, 521 | 522, 508, 510, 512 | +| 生产组-主管 | 517 | 519, 520, 521 | 522, 508, 510, 512 | +| 拣货组-组长 | 517 | 519, 520, 521 | 522, 508, 510, 512 | +| 财务 | 518 | 519, 520, 521 | 522, 508 | + +> - 客服:全部权限(创建、更新、转单、查理赔) +> - 仓库:只读查询 + 更新处理结果 +> - 生产组-主管 / 拣货组-组长:共享仓库组视角(同仓库组权限),处理退货验货入库等实物操作。普通生产组员工不授权任何售后权限。 +> - 财务:只读查询(理赔审核通过财务系统操作,不走 WMS) + +> **生产组其他角色**(普通员工、复核、其他普工)不授权任何售后权限。 + +--- + +## 十、Methods API 设计 + +### 10.1 概述 + +售后模块 API method 统一以 `afterSale.` 为前缀,使用 `/system` 网关接入。工作列表与审计列表分离,导出采用异步任务模式。 + +### 10.2 列表一:工作列表 `afterSale.workList` + +**定位**:仓库内员工看到自己角色组需要处理的工单。 + +**可见性规则:** +- 创建时 `role_group` 默认为 `customer_service`,仅客服组可见 +- 转单后(如 `customer_service` → `warehouse`),原角色组不再可见,目标角色组可见 +- 用户通过角色绑定的 block 权限(516/517/518)确定可见哪些 role_group +- **核心逻辑**:`WHERE role_group IN (用户拥有的售后block对应的role_group)` 且 `status != 'completed' AND status != 'cancelled'` + +**method 定义:** +```json +{ + "method": "afterSale.workList", + "description": "售后工作列表。仅返回当前用户角色组负责的待处理工单。创建时默认进入客服组,转单后原组不可见、目标组可见。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "pagination", "type": "object", "required": false, "source": "body", "description": "分页参数 page/pageSize" }, + { "name": "where", "type": "object", "required": false, "source": "body", "description": "筛选条件:支持 type/sub_type/status/priority/after_sale_no/waybill_no 等字段筛选,以及 quickWhere 快捷搜索" }, + { "name": "sort", "type": "object", "required": false, "source": "body", "description": "排序参数 sortField/sortOrder,默认按 priority DESC, created_at DESC" } + ], + "response": [ + { "name": "list", "type": "array", "required": true, "description": "售后工单列表" }, + { "name": "pagination", "type": "object", "required": true, "description": "分页信息" } + ] +} +``` + +### 10.3 列表二:审计列表 `afterSale.auditList` + +**定位**:所有售后单全局视图,不限角色组,用于审计和管理。 + +**可见性规则:** +- 所有 `status` 的工单均可见(包括 completed/cancelled) +- 不限 `role_group` +- 与工作列表共享 where/sort/pagination 参数格式 + +**method 定义:** +```json +{ + "method": "afterSale.auditList", + "description": "售后审计列表。全局售后单视图,不限角色组、不限状态,用于审计和统计分析。入参与 afterSale.workList 一致。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "pagination", "type": "object", "required": false, "source": "body" }, + { "name": "where", "type": "object", "required": false, "source": "body", "description": "同 workList,额外支持 claim_status/carrier_claim_status 筛选" }, + { "name": "sort", "type": "object", "required": false, "source": "body" } + ], + "response": [ + { "name": "list", "type": "array", "required": true }, + { "name": "pagination", "type": "object", "required": true } + ] +} +``` + +### 10.4 导出接口 `afterSale.export` + `afterSale.exportTaskProgress` + +参考项目现有导出模式(`order.export` / `order.exportTaskProgress`)。 + +**`afterSale.export`:** +```json +{ + "method": "afterSale.export", + "description": "提交售后审计列表导出任务(异步)。入参 where/sort 与 afterSale.auditList 完全一致。提交后立即返回 task_id,后台异步执行 Excel 生成并上传 COS。通过 afterSale.exportTaskProgress 查询进度和下载链接。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "where", "type": "object", "required": false, "source": "body", "description": "查询条件,与 afterSale.auditList 的 where 语义一致" }, + { "name": "sort", "type": "object", "required": false, "source": "body", "description": "排序参数,与 afterSale.auditList 的 sort 语义一致" } + ], + "response": [ + { "name": "task_id", "type": "string", "required": true, "description": "导出任务ID" }, + { "name": "status", "type": "string", "required": true, "description": "submitted/running/success/failed" }, + { "name": "progress", "type": "number", "required": true, "description": "0-100" }, + { "name": "message", "type": "string", "required": true } + ] +} +``` + +**`afterSale.exportTaskProgress`:** +```json +{ + "method": "afterSale.exportTaskProgress", + "description": "查询售后导出任务进度和下载链接。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "task_id", "type": "string", "required": true, "source": "body", "description": "导出任务ID" } + ], + "response": [ + { "name": "task_id", "type": "string", "required": true }, + { "name": "status", "type": "string", "required": true }, + { "name": "progress", "type": "number", "required": true }, + { "name": "download_url", "type": "string", "required": false, "description": "status=success 时返回 Excel 下载链接" }, + { "name": "error", "type": "string", "required": false, "description": "status=failed 时返回错误信息" } + ] +} +``` + +### 10.5 其他 methods + +| method | 说明 | 权限 | +|--------|------|------| +| `afterSale.create` | 创建售后单 | 客服 | +| `afterSale.detail` | 售后明细(主表+步骤列表) | 全部 | +| `afterSale.update` | 更新售后单 | 客服/仓库 | +| `afterSale.transfer` | 转单(更新 role_group) | 客服 | +| `afterSale.handleWorkOrder` | 处理工单(写步骤+绑附件) | 当前 role_group 匹配的用户 | +| `afterSale.registerClaim` | 登记售后理赔信息(仓库理赔+运方理赔) | 客服 | + +### 10.6 导出流程说明 + +导出流程参考项目现有异步导出模式(`order.export`): + +1. 客户端调用 `afterSale.export` 提交导出任务,服务端生成 `task_id`,在 Redis 中初始化任务状态为 `submitted` +2. 通过 `setImmediate` 启动异步执行,立即返回 `task_id` 给客户端 +3. 后台任务分页查询售后数据,使用 ExcelJS 流式写入 Excel 文件 +4. Excel 生成完成后上传至 COS,获取下载链接 +5. 更新 Redis 中任务状态为 `success`,并写入 `download_url` +6. 若任一步骤失败,更新任务状态为 `failed`,并写入错误信息 +7. 客户端轮询 `afterSale.exportTaskProgress` 获取进度和下载链接 + +**Redis 缓存规范:** +- Key 格式:`after_sale_export_task_{task_id}` +- TTL:30 分钟(任务完成后自动过期) + +### 10.7 处理工单 `afterSale.handleWorkOrder` + +```json +{ + "method": "afterSale.handleWorkOrder", + "description": "处理售后工单。员工在工作列表中对工单进行操作,写入进度步骤并绑定附件。操作人信息从登录上下文自动获取。非客服组处理完成后自动转回客服组继续跟进。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "id", "type": "integer", "required": true, "source": "body", "description": "售后工单主表ID(wms_after_sale.id)" }, + { "name": "status", "type": "string", "required": false, "source": "body", "description": "更新售后单状态(pending/processing/completed/closed),不传则保持当前状态" }, + { "name": "action", "type": "string", "required": true, "source": "body", "description": "操作动作描述,如"客服接单"、"仓库验货"、"确认收货入库"、"退款打款"" }, + { "name": "remark", "type": "string", "required": false, "source": "body", "description": "处理备注/消息主体" }, + { "name": "attachment_ids", "type": "array", "required": false, "source": "body", "description": "附件 file_id 数组,如 [123, 456]。处理时自动绑定到本次步骤。" } + ], + "response": [ + { "name": "detail_id", "type": "integer", "required": true, "description": "本次写入的 wms_after_sale_detail.id" }, + { "name": "after_sale_id", "type": "integer", "required": true } + ], + "errors": [ + { "code": 400, "message": "工单不存在或参数缺失" }, + { "code": 403, "message": "无权限处理该工单(role_group 不匹配)" }, + { "code": 500, "message": "处理失败" } + ] +} +``` + +**处理流程:** + +1. 校验工单 `id` 存在,且当前用户 `role_group` 与工单 `role_group` 匹配(否则 403) +2. 从登录上下文(JWT token)提取操作人 `operator_id` 和 `operator_snapshot` +3. 写入 `wms_after_sale_detail`: + - `step_status = 2`(已完成) + - `action` = 入参 `action` + - `remark` = 入参 `remark` + - `operator_id` / `operator_snapshot` = 当前用户 + - `started_at = now`, `completed_at = now` +4. 若传入了 `attachment_ids`,遍历写入 `wms_file_reference`: + - `business_type = 'after_sale_detail'` + - `business_id` = 刚写入的 `detail.id` + - `file_id = attachment_id` +5. 若传入了 `status`,更新 `wms_after_sale.status` +6. 若当前 `role_group` ≠ `'customer_service'` 且 `status` ≠ `'completed'`,自动将 `role_group` 回设为 `'customer_service'`(仓库/财务处理完本环节后自动退回客服组继续跟进) +7. 若 `status = 'completed'`,同时写入 `resolution` 和 `resolved_at` + +### 10.8 理赔登记 `afterSale.registerClaim` + +```json +{ + "method": "afterSale.registerClaim", + "description": "登记售后理赔信息。一次性填入仓库理赔和运方理赔的全部字段,同时写入进度步骤。两套理赔字段可同时填写(双赔场景)。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "id", "type": "integer", "required": true, "source": "body", "description": "售后工单主表ID" }, + { "name": "claim_needed", "type": "integer", "required": false, "source": "body", "description": "仓库理赔标记:0/1" }, + { "name": "claim_amount", "type": "number", "required": false, "source": "body", "description": "仓库理赔金额(元)" }, + { "name": "claim_status", "type": "string", "required": false, "source": "body", "description": "仓库理赔状态:pending/reviewing/approved/paid/monthly/rejected" }, + { "name": "carrier_claim_needed", "type": "integer", "required": false, "source": "body", "description": "运方理赔标记:0/1" }, + { "name": "carrier_claim_amount", "type": "number", "required": false, "source": "body", "description": "运方理赔金额(元)" }, + { "name": "carrier_claim_status", "type": "string", "required": false, "source": "body", "description": "运方理赔状态:pending/reviewing/approved/paid/monthly/rejected" }, + { "name": "action", "type": "string", "required": true, "source": "body", "description": "操作动作描述,如"登记仓库理赔"、"登记运方理赔"" }, + { "name": "remark", "type": "string", "required": false, "source": "body", "description": "处理备注,如"快递破损核定赔200元"" }, + { "name": "attachment_ids", "type": "array", "required": false, "source": "body", "description": "附件 file_id 数组(破损照片、理赔单据等)" } + ], + "response": [ + { "name": "detail_id", "type": "integer", "required": true, "description": "本次写入的步骤ID" }, + { "name": "after_sale_id", "type": "integer", "required": true } + ], + "errors": [ + { "code": 400, "message": "工单不存在或参数缺失" }, + { "code": 500, "message": "登记失败" } + ] +} +``` + +**处理流程:** + +1. 校验工单 `id` 存在 +2. 从登录上下文提取操作人信息 +3. 更新 `wms_after_sale` 中传入的非空理赔字段(`claim_needed/amount/status`、`carrier_claim_needed/amount/status`) +4. 写入 `wms_after_sale_detail`(step_status=2,action/remark/operator) +5. 若有 `attachment_ids`,绑定到本次步骤 + +**使用场景:** +- 单赔:只传仓库理赔字段组,运方字段不传 +- 单赔:只传运方理赔字段组,仓库字段不传 +- 双赔:同时传两套字段(仓库+运输途中均破损) + +--- + +## 十一、待评审事项 + +- [ ] 售后单号 `after_sale_no` 生成规则:格式已确定为 `AS + YYYYMMDD + 6位序号`(如 `AS20260809000001`),待确认序号从 1 起始还是从指定起始值起 +- [ ] 仓库理赔(`claim_status`)和运方理赔(`carrier_claim_status`)是否需要更细粒度的流转(如:待审核 → 审核通过 → 已打款 → 月结) +- [ ] 进度步骤表是否需要记录商品明细信息(如退货 SKU/数量),或通过 `remark` JSON 扩展存储 +- [ ] 单据关联字段是否需要扩展到更多类型(如质检单 `quality_check_id`) +- [ ] 是否需要支持售后单之间的关联(如换货单关联原退货单) diff --git a/database/migrations/20260809130000-create-wms-after-sale.js b/database/migrations/20260809130000-create-wms-after-sale.js new file mode 100644 index 0000000..68eae7b --- /dev/null +++ b/database/migrations/20260809130000-create-wms-after-sale.js @@ -0,0 +1,293 @@ +'use strict'; + +const TABLE_NAME = 'wms_after_sale'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + store_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '货主ID', + }, + after_sale_no: { + type: Sequelize.STRING(50), + allowNull: false, + comment: '售后单号,唯一,生成规则:AS+YYYYMMDD+6位序号', + }, + type: { + type: Sequelize.STRING(20), + allowNull: false, + comment: '售后类型:order/receiving/entry/stockout', + }, + sub_type: { + type: Sequelize.STRING(50), + allowNull: false, + comment: '售后子类型,与 type 组成二级分类', + }, + status: { + type: Sequelize.STRING(20), + allowNull: false, + defaultValue: 'pending', + comment: '售后状态:pending/processing/completed/closed/cancelled', + }, + priority: { + type: Sequelize.INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '优先级,数值越大越优先(0=普通,10=紧急)', + }, + title: { + type: Sequelize.STRING(200), + allowNull: false, + comment: '售后标题/简要描述', + }, + description: { + type: Sequelize.TEXT, + allowNull: true, + defaultValue: null, + comment: '售后详细描述', + }, + creator_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '创建人账户ID', + }, + role_group: { + type: Sequelize.STRING(50), + allowNull: true, + defaultValue: null, + comment: '当前处理角色组:customer_service/warehouse/finance', + }, + inbox_message_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '关联站内信消息ID(wms_inbox_message.id)', + }, + resolution: { + type: Sequelize.TEXT, + allowNull: true, + defaultValue: null, + comment: '最终处理结果说明', + }, + resolved_at: { + type: Sequelize.DATE, + allowNull: true, + defaultValue: null, + comment: '完结时间(状态变为 completed 时写入)', + }, + claim_needed: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '仓库理赔标记:0=不需要,1=需要', + }, + claim_amount: { + type: Sequelize.DECIMAL(12, 2), + allowNull: true, + defaultValue: null, + comment: '仓库理赔金额,单位:元', + }, + claim_status: { + type: Sequelize.STRING(20), + allowNull: true, + defaultValue: null, + comment: '仓库理赔状态:pending/reviewing/approved/paid/monthly/rejected', + }, + carrier_claim_needed: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '运方理赔标记:0=不需要,1=需要', + }, + carrier_claim_amount: { + type: Sequelize.DECIMAL(12, 2), + allowNull: true, + defaultValue: null, + comment: '运方理赔金额,单位:元', + }, + carrier_claim_status: { + type: Sequelize.STRING(20), + allowNull: true, + defaultValue: null, + comment: '运方理赔状态:pending/reviewing/approved/paid/monthly/rejected', + }, + waybill_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '运单ID(关联 wms_order_express.id)', + }, + waybill_no: { + type: Sequelize.STRING(50), + allowNull: true, + defaultValue: null, + comment: '运单号(冗余)', + }, + order_delivery_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '发货订单ID(关联 wms_order_delivery.id)', + }, + order_delivery_no: { + type: Sequelize.STRING(50), + allowNull: true, + defaultValue: null, + comment: '发货订单号(冗余)', + }, + entry_order_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '入库单ID(关联 wms_entry_order.id)', + }, + entry_order_no: { + type: Sequelize.STRING(50), + allowNull: true, + defaultValue: null, + comment: '入库单号(冗余)', + }, + order_stockout_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '出库单ID(关联 wms_order_stockout.id)', + }, + order_stockout_no: { + type: Sequelize.STRING(50), + allowNull: true, + defaultValue: null, + comment: '出库单号(冗余)', + }, + receiving_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '收货单ID(关联 wms_receiving.id)', + }, + receiving_no: { + type: Sequelize.STRING(50), + allowNull: true, + defaultValue: null, + comment: '收货单号(冗余)', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + defaultValue: null, + comment: '软删除时间', + }, + }); + + // 唯一索引 — 售后单号 + await queryInterface.addIndex(TABLE_NAME, ['after_sale_no'], { + unique: true, + name: 'uk_after_sale_no', + }); + + // 仓库+状态查询(最高频) + await queryInterface.addIndex(TABLE_NAME, ['warehouse_id', 'status', 'deleted_at'], { + name: 'idx_warehouse_status', + }); + + // 仓库+类型筛选 + await queryInterface.addIndex(TABLE_NAME, ['warehouse_id', 'type', 'deleted_at'], { + name: 'idx_warehouse_type', + }); + + // 仓库+类型+子类型筛选 + await queryInterface.addIndex(TABLE_NAME, ['warehouse_id', 'type', 'sub_type', 'deleted_at'], { + name: 'idx_type_subtype', + }); + + // 货主查询 + await queryInterface.addIndex(TABLE_NAME, ['store_id', 'deleted_at'], { + name: 'idx_store_id', + }); + + // 创建人查询 + await queryInterface.addIndex(TABLE_NAME, ['creator_id', 'deleted_at'], { + name: 'idx_creator_id', + }); + + // 角色组+状态查询 + await queryInterface.addIndex(TABLE_NAME, ['role_group', 'status', 'deleted_at'], { + name: 'idx_role_group', + }); + + // 仓库+时间排序分页 + await queryInterface.addIndex(TABLE_NAME, ['warehouse_id', 'created_at'], { + name: 'idx_created_at', + }); + + // 运单反查 + await queryInterface.addIndex(TABLE_NAME, ['waybill_id'], { + name: 'idx_waybill_id', + }); + + // 发货订单反查 + await queryInterface.addIndex(TABLE_NAME, ['order_delivery_id'], { + name: 'idx_order_delivery_id', + }); + + // 入库单反查 + await queryInterface.addIndex(TABLE_NAME, ['entry_order_id'], { + name: 'idx_entry_order_id', + }); + + // 出库单反查 + await queryInterface.addIndex(TABLE_NAME, ['order_stockout_id'], { + name: 'idx_order_stockout_id', + }); + + // 收货单反查 + await queryInterface.addIndex(TABLE_NAME, ['receiving_id'], { + name: 'idx_receiving_id', + }); + + // 运方理赔状态筛选 + await queryInterface.addIndex(TABLE_NAME, ['carrier_claim_status'], { + name: 'idx_carrier_claim_status', + }); + + // 站内信消息反查 + await queryInterface.addIndex(TABLE_NAME, ['inbox_message_id'], { + name: 'idx_inbox_message_id', + }); + }, + + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260809130100-create-wms-after-sale-detail.js b/database/migrations/20260809130100-create-wms-after-sale-detail.js new file mode 100644 index 0000000..4a139ec --- /dev/null +++ b/database/migrations/20260809130100-create-wms-after-sale-detail.js @@ -0,0 +1,100 @@ +'use strict'; + +const TABLE_NAME = 'wms_after_sale_detail'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + after_sale_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '关联售后主表ID(wms_after_sale.id)', + }, + step_status: { + type: Sequelize.TINYINT(3).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '步骤状态:0=待开始,1=进行中,2=已完成,3=已跳过', + }, + operator_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '操作人账户ID(关联 accounts 表)', + }, + operator_snapshot: { + type: Sequelize.TEXT, + allowNull: true, + defaultValue: null, + comment: '操作人信息快照(JSON),防止账户删除后历史丢失', + }, + action: { + type: Sequelize.STRING(100), + allowNull: true, + defaultValue: null, + comment: '操作动作描述', + }, + remark: { + type: Sequelize.TEXT, + allowNull: true, + defaultValue: null, + comment: '处理备注', + }, + started_at: { + type: Sequelize.DATE, + allowNull: true, + defaultValue: null, + comment: '步骤开始时间', + }, + completed_at: { + type: Sequelize.DATE, + allowNull: true, + defaultValue: null, + comment: '步骤完成时间', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + defaultValue: null, + comment: '软删除时间', + }, + }); + + // 按售后单查询进度步骤(最高频) + await queryInterface.addIndex(TABLE_NAME, ['after_sale_id'], { + name: 'idx_after_sale_id', + }); + + // 按操作人查询 + await queryInterface.addIndex(TABLE_NAME, ['operator_id'], { + name: 'idx_operator_id', + }); + }, + + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260809130200-add-after-sale-permissions.js b/database/migrations/20260809130200-add-after-sale-permissions.js new file mode 100644 index 0000000..d4f2901 --- /dev/null +++ b/database/migrations/20260809130200-add-after-sale-permissions.js @@ -0,0 +1,97 @@ +'use strict'; + +/** + * 新增售后模块权限记录(固定 ID 策略,确保开发/生产一致)。 + * + * 新增权限明细: + * Block(角色组维度): + * 516 — 售后-客服组 + * 517 — 售后-仓库组 + * 518 — 售后-财务组 + * + * Web Pages(菜单/页面): + * 519 — afterSale 售后管理(根菜单) + * 520 — afterSale.list 售后列表 + * 521 — afterSale.detail 售后明细 + * + * API: + * 522 — afterSale.workList API:售后工作列表查询 + * 523 — afterSale.auditList API:售后审计列表查询 + * 508 — afterSale.detail API:售后明细查询 + * 509 — afterSale.create API:创建售后单 + * 510 — afterSale.update API:更新售后单 + * 511 — afterSale.transfer API:售后转单 + * 512 — afterSale.handleWorkOrder API:处理工单 + * 513 — afterSale.registerClaim API:登记理赔 + * 514 — afterSale.export API:售后导出 + * 515 — afterSale.exportTaskProgress API:导出进度查询 + * + * 幂等设计:使用 INSERT IGNORE,已存在的 id 不会重复插入。 + */ + +const TABLE = 'wms_permission'; +const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at'; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + // ── 1. Block 权限(角色组维度,用于权限分配分组)── + const blocks = [ + [516, null, null, '售后-客服组', null, '售后-客服组', null, 0, 0, null, 'block', 0, 1], + [517, null, null, '售后-仓库组', null, '售后-仓库组', null, 0, 0, null, 'block', 0, 1], + [518, null, null, '售后-财务组', null, '售后-财务组', null, 0, 0, null, 'block', 0, 1], + ]; + + for (const [id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status] of blocks) { + await queryInterface.sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + { replacements: [id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status] } + ); + } + + // ── 2. Web Pages 权限(菜单/页面)── + const pages = [ + [519, 'afterSale', null, 'afterSale', null, '售后管理', null, 0, 0, null, 'web_pages', 14, 1], + [520, 'afterSale.list', null, 'afterSale.list', null, '售后列表', null, 0, 0, 519, 'web_pages', 0, 1], + [521, 'afterSale.detail', null, 'afterSale.detail', null, '售后明细', null, 0, 0, 519, 'web_pages', 1, 1], + ]; + + for (const [id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status] of pages) { + await queryInterface.sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + { replacements: [id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status] } + ); + } + + // ── 3. API 权限 ── + const apis = [ + [522, 'afterSale.workList', 'API:售后工作列表查询'], + [523, 'afterSale.auditList', 'API:售后审计列表查询'], + [508, 'afterSale.detail', 'API:售后明细查询'], + [509, 'afterSale.create', 'API:创建售后单'], + [510, 'afterSale.update', 'API:更新售后单'], + [511, 'afterSale.transfer', 'API:售后转单'], + [512, 'afterSale.handleWorkOrder', 'API:处理工单'], + [513, 'afterSale.registerClaim', 'API:登记理赔'], + [514, 'afterSale.export', 'API:售后导出'], + [515, 'afterSale.exportTaskProgress', 'API:导出进度查询'], + ]; + + for (const [id, path, meta_title] of apis) { + await queryInterface.sequelize.query( + `INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + { replacements: [id, path, null, path, null, meta_title, null, 0, 0, null, 'api', 0, 1] } + ); + } + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + const ids = [516, 517, 518, 519, 520, 521, 522, 523, 508, 509, 510, 511, 512, 513, 514, 515]; + const placeholders = ids.map(() => '?').join(', '); + await queryInterface.sequelize.query( + `DELETE FROM \`${TABLE}\` WHERE id IN (${placeholders})`, + { replacements: ids } + ); + }, +}; diff --git a/methods/system.json b/methods/system.json index def17fe..8145c8b 100644 --- a/methods/system.json +++ b/methods/system.json @@ -2,7 +2,7 @@ "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", "version": "0.3.21", - "updatedAt": "2026-08-06", + "updatedAt": "2026-08-09", "headers": [ { "name": "platform", @@ -33593,6 +33593,164 @@ ] } ] + }, + { + "groupName": "售后管理", + "module": "afterSale", + "list": [ + { + "method": "afterSale.workList", + "description": "售后工作列表。仅返回当前用户角色组负责的待处理工单。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "pagination", "type": "object", "required": false, "source": "body", "description": "分页参数 page/pageSize" }, + { "name": "where", "type": "object", "required": false, "source": "body", "description": "筛选条件:type/sub_type/status/priority/after_sale_no/waybill_no 等" }, + { "name": "sort", "type": "object", "required": false, "source": "body", "description": "排序参数 sortField/sortOrder" } + ], + "response": [ + { "name": "list", "type": "array", "required": true }, + { "name": "pagination", "type": "object", "required": true } + ] + }, + { + "method": "afterSale.auditList", + "description": "售后审计列表。全局售后单视图,不限角色组、不限状态。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "pagination", "type": "object", "required": false, "source": "body" }, + { "name": "where", "type": "object", "required": false, "source": "body", "description": "同 workList,额外支持 claim_status/carrier_claim_status" }, + { "name": "sort", "type": "object", "required": false, "source": "body" } + ], + "response": [ + { "name": "list", "type": "array", "required": true }, + { "name": "pagination", "type": "object", "required": true } + ] + }, + { + "method": "afterSale.detail", + "description": "售后明细(主表+步骤列表+附件)。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "id", "type": "integer", "required": true, "source": "body", "description": "售后工单主表ID" } + ], + "response": [ + { "name": "after_sale", "type": "object", "required": true, "description": "主表数据" }, + { "name": "steps", "type": "array", "required": true, "description": "步骤列表(含附件)" } + ] + }, + { + "method": "afterSale.create", + "description": "创建售后单。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "warehouse_id", "type": "integer", "required": true, "source": "body" }, + { "name": "store_id", "type": "integer", "required": false, "source": "body" }, + { "name": "type", "type": "string", "required": true, "source": "body", "description": "order/receiving/entry/stockout" }, + { "name": "sub_type", "type": "string", "required": true, "source": "body" }, + { "name": "priority", "type": "integer", "required": false, "source": "body" }, + { "name": "title", "type": "string", "required": true, "source": "body" }, + { "name": "description", "type": "string", "required": false, "source": "body" }, + { "name": "waybill_id", "type": "integer", "required": false, "source": "body" }, + { "name": "order_delivery_id", "type": "integer", "required": false, "source": "body" }, + { "name": "entry_order_id", "type": "integer", "required": false, "source": "body" }, + { "name": "order_stockout_id", "type": "integer", "required": false, "source": "body" }, + { "name": "receiving_id", "type": "integer", "required": false, "source": "body" }, + { "name": "inbox_message_id", "type": "integer", "required": false, "source": "body" } + ], + "response": [ + { "name": "id", "type": "integer", "required": true }, + { "name": "after_sale_no", "type": "string", "required": true } + ] + }, + { + "method": "afterSale.transfer", + "description": "转单(更新 role_group)。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "id", "type": "integer", "required": true, "source": "body" }, + { "name": "role_group", "type": "string", "required": true, "source": "body", "description": "customer_service/warehouse/finance" }, + { "name": "remark", "type": "string", "required": false, "source": "body" } + ], + "response": [ + { "name": "after_sale_id", "type": "integer", "required": true } + ] + }, + { + "method": "afterSale.handleWorkOrder", + "description": "处理售后工单(写步骤+绑附件+自动转回客服)。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "id", "type": "integer", "required": true, "source": "body" }, + { "name": "status", "type": "string", "required": false, "source": "body", "description": "更新状态" }, + { "name": "action", "type": "string", "required": true, "source": "body" }, + { "name": "remark", "type": "string", "required": false, "source": "body" }, + { "name": "attachment_ids", "type": "array", "required": false, "source": "body", "description": "附件 file_id 数组" } + ], + "response": [ + { "name": "detail_id", "type": "integer", "required": true }, + { "name": "after_sale_id", "type": "integer", "required": true } + ] + }, + { + "method": "afterSale.registerClaim", + "description": "登记售后理赔信息(仓库+运方一次性填入)。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "id", "type": "integer", "required": true, "source": "body" }, + { "name": "claim_needed", "type": "integer", "required": false, "source": "body" }, + { "name": "claim_amount", "type": "number", "required": false, "source": "body" }, + { "name": "claim_status", "type": "string", "required": false, "source": "body" }, + { "name": "carrier_claim_needed", "type": "integer", "required": false, "source": "body" }, + { "name": "carrier_claim_amount", "type": "number", "required": false, "source": "body" }, + { "name": "carrier_claim_status", "type": "string", "required": false, "source": "body" }, + { "name": "action", "type": "string", "required": true, "source": "body" }, + { "name": "remark", "type": "string", "required": false, "source": "body" }, + { "name": "attachment_ids", "type": "array", "required": false, "source": "body" } + ], + "response": [ + { "name": "detail_id", "type": "integer", "required": true }, + { "name": "after_sale_id", "type": "integer", "required": true } + ] + }, + { + "method": "afterSale.export", + "description": "提交售后审计列表导出任务(异步)。返回 task_id。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "where", "type": "object", "required": false, "source": "body" }, + { "name": "sort", "type": "object", "required": false, "source": "body" } + ], + "response": [ + { "name": "task_id", "type": "string", "required": true }, + { "name": "status", "type": "string", "required": true }, + { "name": "progress", "type": "number", "required": true }, + { "name": "message", "type": "string", "required": true } + ] + }, + { + "method": "afterSale.exportTaskProgress", + "description": "查询售后导出任务进度和下载链接。", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [ + { "name": "task_id", "type": "string", "required": true, "source": "body" } + ], + "response": [ + { "name": "task_id", "type": "string", "required": true }, + { "name": "status", "type": "string", "required": true }, + { "name": "progress", "type": "number", "required": true }, + { "name": "download_url", "type": "string", "required": false } + ] + } + ] } ] }