'use strict'; const { Controller } = require('egg'); const { toSuccess, toFailure } = require('../lib/api_response'); /** * 站内信内部管理接口控制器。 * 提供消息列表、详情、对话链、回信、重推、统计等管理功能。 */ class InboxController extends Controller { /** * 获取当前仓库上下文。 * @return {{ warehouseId: number }} 仓库上下文。 */ getWarehouseContext() { const { ctx } = this; const warehouseId = Number(ctx.user && ctx.user.store_id); if (!Number.isFinite(warehouseId) || warehouseId <= 0) { throw new Error('缺少仓库信息'); } return { warehouseId }; } /** * 内部管理统一入口,分发到对应 service 方法。 * @return {Promise} 无返回值,结果写入 ctx.body。 */ async index() { const { ctx } = this; try { const method = String(ctx.request.body && ctx.request.body.method || '').trim(); if (!method || !method.startsWith('inbox.')) { ctx.status = 400; ctx.body = toFailure({ message: 'method 参数无效' }); ctx.type = 'application/json'; return; } const action = method.replace('inbox.', ''); const data = (ctx.request.body && ctx.request.body.data) || {}; let result; switch (action) { case 'list': { const { warehouseId } = this.getWarehouseContext(); result = await ctx.service.inbox.index.list({ warehouseId, ...data, }); break; } case 'detail': { const { warehouseId } = this.getWarehouseContext(); result = await ctx.service.inbox.index.detail({ warehouseId, id: data.id, }); break; } case 'thread': { const { warehouseId } = this.getWarehouseContext(); result = await ctx.service.inbox.index.thread({ warehouseId, id: data.id, }); break; } case 'reply': { const { warehouseId } = this.getWarehouseContext(); result = await ctx.service.inbox.index.reply({ warehouseId, parentId: data.parentId, targetChannel: data.targetChannel, targetUrl: data.targetUrl, targetType: data.targetType, refCode: data.refCode, extData: data.extData, flags: data.flags, }); break; } case 'retry': { const { warehouseId } = this.getWarehouseContext(); result = await ctx.service.inbox.index.retry({ warehouseId, id: data.id, }); break; } case 'stats': { const { warehouseId } = this.getWarehouseContext(); result = await ctx.service.inbox.index.stats({ warehouseId, direction: data.direction, }); break; } default: ctx.status = 400; ctx.body = toFailure({ message: `不支持的 inbox 方法: ${action}` }); ctx.type = 'application/json'; return; } ctx.status = 200; ctx.body = toSuccess(result, 'ok'); ctx.type = 'application/json'; } catch (error) { const message = String(error && error.message || '请求失败'); ctx.status = 500; ctx.body = toFailure({ message: `站内信错误: ${message}` }); ctx.type = 'application/json'; } } } module.exports = InboxController;