feat: 完善后端架构 - 标准化Controller层和Service层

 新功能:
- 创建了完整的Service层架构,包含所有业务实体的Service接口和实现类
- 新增8个标准化的Controller类,支持完整的CRUD操作
- 实现了统一的Request/Response模式和分页查询功能
- 创建了认证服务(AuthService)和令牌服务(TokenService)
- 添加了Redis配置和认证拦截器

🏗️ 架构优化:
- 移除Controller层所有try-catch块,使用全局异常处理机制
- 创建了专门的异常类(AuthException, TokenException, CaptchaException)
- 统一了API返回格式,完善了Result类的方法
- 实现了标准的分页查询和参数校验

📦 新增文件:
- 8个Controller类: Achievement, Comment, CommunityPost, Conversation, CozeApiCall, EmotionAnalysis, Reward, UserStats
- 12个Service接口和对应的实现类
- 标准化的DTO类(Request/Response)
- 异常处理类和拦截器
- 测试用例

🔧 重构优化:
- 重写了AuthController,移除所有业务逻辑到Service层
- 优化了MessageController,使用标准的Request/Response格式
- 更新了全局异常处理器,支持多种异常类型
- 完善了WebConfig配置,添加认证拦截器

📊 代码统计:
- 新增文件: 60+个
- 新增代码行数: 8000+行
- 重构代码行数: 1000+行
- 移除过时接口: 4个
This commit is contained in:
2025-07-24 07:38:40 +08:00
parent 880e0e3c88
commit 873b8e55da
67 changed files with 8619 additions and 850 deletions
@@ -0,0 +1,307 @@
package com.emotion.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.emotion.common.PageResult;
import com.emotion.common.Result;
import com.emotion.dto.request.PageRequest;
import com.emotion.dto.response.BaseResponse;
import com.emotion.entity.CozeApiCall;
import com.emotion.service.CozeApiCallService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;
/**
* Coze API调用记录控制器
*
* @author emotion-museum
* @date 2025-07-23
*/
@RestController
@RequestMapping("/coze-api-call")
public class CozeApiCallController {
@Autowired
private CozeApiCallService cozeApiCallService;
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
/**
* 分页查询API调用记录
*/
@GetMapping("/page")
public Result<PageResult<CozeApiCallResponse>> getPage(@Validated PageRequest request) {
IPage<CozeApiCall> page = cozeApiCallService.getPage(request);
List<CozeApiCallResponse> responses = page.getRecords().stream()
.map(this::convertToResponse)
.collect(Collectors.toList());
PageResult<CozeApiCallResponse> pageResult = new PageResult<>();
pageResult.setCurrent(page.getCurrent());
pageResult.setSize(page.getSize());
pageResult.setTotal(page.getTotal());
pageResult.setPages(page.getPages());
pageResult.setRecords(responses);
return Result.success(pageResult);
}
/**
* 根据会话ID分页查询API调用记录
*/
@GetMapping("/conversation/{conversationId}/page")
public Result<PageResult<CozeApiCallResponse>> getPageByConversationId(@PathVariable String conversationId, @Validated PageRequest request) {
IPage<CozeApiCall> page = cozeApiCallService.getPageByConversationId(request, conversationId);
List<CozeApiCallResponse> responses = page.getRecords().stream()
.map(this::convertToResponse)
.collect(Collectors.toList());
PageResult<CozeApiCallResponse> pageResult = new PageResult<>();
pageResult.setCurrent(page.getCurrent());
pageResult.setSize(page.getSize());
pageResult.setTotal(page.getTotal());
pageResult.setPages(page.getPages());
pageResult.setRecords(responses);
return Result.success(pageResult);
}
/**
* 根据用户ID分页查询API调用记录
*/
@GetMapping("/user/{userId}/page")
public Result<PageResult<CozeApiCallResponse>> getPageByUserId(@PathVariable String userId, @Validated PageRequest request) {
IPage<CozeApiCall> page = cozeApiCallService.getPageByUserId(request, userId);
List<CozeApiCallResponse> responses = page.getRecords().stream()
.map(this::convertToResponse)
.collect(Collectors.toList());
PageResult<CozeApiCallResponse> pageResult = new PageResult<>();
pageResult.setCurrent(page.getCurrent());
pageResult.setSize(page.getSize());
pageResult.setTotal(page.getTotal());
pageResult.setPages(page.getPages());
pageResult.setRecords(responses);
return Result.success(pageResult);
}
/**
* 根据ID获取API调用记录
*/
@GetMapping("/{id}")
public Result<CozeApiCallResponse> getById(@PathVariable String id) {
CozeApiCall apiCall = cozeApiCallService.getById(id);
if (apiCall == null) {
return Result.notFound("API调用记录不存在");
}
return Result.success(convertToResponse(apiCall));
}
/**
* 根据Bot ID查询API调用记录
*/
@GetMapping("/bot/{botId}")
public Result<List<CozeApiCallResponse>> getByBotId(@PathVariable String botId) {
List<CozeApiCall> apiCalls = cozeApiCallService.getByBotId(botId);
List<CozeApiCallResponse> responses = apiCalls.stream()
.map(this::convertToResponse)
.collect(Collectors.toList());
return Result.success(responses);
}
/**
* 根据状态查询API调用记录
*/
@GetMapping("/status/{status}")
public Result<List<CozeApiCallResponse>> getByStatus(@PathVariable String status) {
List<CozeApiCall> apiCalls = cozeApiCallService.getByStatus(status);
List<CozeApiCallResponse> responses = apiCalls.stream()
.map(this::convertToResponse)
.collect(Collectors.toList());
return Result.success(responses);
}
/**
* 根据请求类型查询API调用记录
*/
@GetMapping("/request-type/{requestType}")
public Result<List<CozeApiCallResponse>> getByRequestType(@PathVariable String requestType) {
List<CozeApiCall> apiCalls = cozeApiCallService.getByRequestType(requestType);
List<CozeApiCallResponse> responses = apiCalls.stream()
.map(this::convertToResponse)
.collect(Collectors.toList());
return Result.success(responses);
}
/**
* 统计用户的API调用次数
*/
@GetMapping("/user/{userId}/count")
public Result<Long> countByUserId(@PathVariable String userId) {
Long count = cozeApiCallService.countByUserId(userId);
return Result.success(count);
}
/**
* 统计Bot的API调用次数
*/
@GetMapping("/bot/{botId}/count")
public Result<Long> countByBotId(@PathVariable String botId) {
Long count = cozeApiCallService.countByBotId(botId);
return Result.success(count);
}
/**
* 统计指定状态的API调用次数
*/
@GetMapping("/status/{status}/count")
public Result<Long> countByStatus(@PathVariable String status) {
Long count = cozeApiCallService.countByStatus(status);
return Result.success(count);
}
/**
* 统计用户的Token使用量
*/
@GetMapping("/user/{userId}/tokens")
public Result<Long> sumTokensByUserId(@PathVariable String userId) {
Long totalTokens = cozeApiCallService.sumTokensByUserId(userId);
return Result.success(totalTokens);
}
/**
* 统计用户的API调用费用
*/
@GetMapping("/user/{userId}/cost")
public Result<java.math.BigDecimal> sumCostByUserId(@PathVariable String userId) {
java.math.BigDecimal totalCost = cozeApiCallService.sumCostByUserId(userId);
return Result.success(totalCost);
}
/**
* 查询失败的API调用记录
*/
@GetMapping("/failed")
public Result<List<CozeApiCallResponse>> getFailedCalls() {
List<CozeApiCall> apiCalls = cozeApiCallService.getFailedCalls();
List<CozeApiCallResponse> responses = apiCalls.stream()
.map(this::convertToResponse)
.collect(Collectors.toList());
return Result.success(responses);
}
/**
* 查询超时的API调用记录
*/
@GetMapping("/timeout")
public Result<List<CozeApiCallResponse>> getTimeoutCalls() {
List<CozeApiCall> apiCalls = cozeApiCallService.getTimeoutCalls();
List<CozeApiCallResponse> responses = apiCalls.stream()
.map(this::convertToResponse)
.collect(Collectors.toList());
return Result.success(responses);
}
/**
* 根据追踪ID查询API调用记录
*/
@GetMapping("/trace/{traceId}")
public Result<CozeApiCallResponse> getByTraceId(@PathVariable String traceId) {
CozeApiCall apiCall = cozeApiCallService.getByTraceId(traceId);
if (apiCall == null) {
return Result.notFound("API调用记录不存在");
}
return Result.success(convertToResponse(apiCall));
}
/**
* 创建API调用记录
*/
@PostMapping
public Result<CozeApiCallResponse> create(@RequestBody CozeApiCall apiCall) {
boolean saved = cozeApiCallService.save(apiCall);
if (!saved) {
return Result.error("创建失败");
}
return Result.success(convertToResponse(apiCall));
}
/**
* 更新API调用记录
*/
@PutMapping("/{id}")
public Result<CozeApiCallResponse> update(@PathVariable String id, @RequestBody CozeApiCall apiCall) {
apiCall.setId(id);
boolean updated = cozeApiCallService.updateById(apiCall);
if (!updated) {
return Result.error("更新失败");
}
CozeApiCall updatedApiCall = cozeApiCallService.getById(id);
return Result.success(convertToResponse(updatedApiCall));
}
/**
* 删除API调用记录
*/
@DeleteMapping("/{id}")
public Result<Void> delete(@PathVariable String id) {
boolean deleted = cozeApiCallService.removeById(id);
if (!deleted) {
return Result.error("删除失败");
}
return Result.success();
}
/**
* 转换为响应对象
*/
private CozeApiCallResponse convertToResponse(CozeApiCall apiCall) {
CozeApiCallResponse response = new CozeApiCallResponse();
BeanUtils.copyProperties(apiCall, response);
response.setId(apiCall.getId());
if (apiCall.getCreateTime() != null) {
response.setCreateTime(apiCall.getCreateTime().format(DATE_TIME_FORMATTER));
}
if (apiCall.getUpdateTime() != null) {
response.setUpdateTime(apiCall.getUpdateTime().format(DATE_TIME_FORMATTER));
}
if (apiCall.getStartTime() != null) {
response.setStartTime(apiCall.getStartTime().format(DATE_TIME_FORMATTER));
}
if (apiCall.getEndTime() != null) {
response.setEndTime(apiCall.getEndTime().format(DATE_TIME_FORMATTER));
}
return response;
}
/**
* API调用记录响应类
*/
@lombok.Data
@lombok.EqualsAndHashCode(callSuper = true)
public static class CozeApiCallResponse extends BaseResponse {
private String conversationId;
private String messageId;
private String userId;
private String botId;
private String requestType;
private String requestUrl;
private String requestBody;
private Integer responseStatus;
private String responseBody;
private String aiReply;
private Integer totalTokens;
private java.math.BigDecimal cost;
private String status;
private String finalStatus;
private String startTime;
private String endTime;
private String traceId;
}
}