feat: 新增 AI 用量落库与统计接口

- 新增 ai_usage_records 表(系统级表,不按租户过滤)与幂等上报接口
- 新增按时间/任务类型/模型的汇总、趋势、明细查询,仅白名单用户可见
- 登录响应返回 aiAdmin,供前端决定是否展示入口
This commit is contained in:
2026-10-10 18:46:01 +08:00
parent 02d5c24946
commit 650b0956de
39 changed files with 2355 additions and 15 deletions
@@ -0,0 +1,62 @@
package com.guo.learningprogresstracker.controller;
import com.guo.learningprogresstracker.config.AiUsageProperties;
import com.guo.learningprogresstracker.dto.AiUsageIngestResult;
import com.guo.learningprogresstracker.dto.request.AiUsageRecordRequest;
import com.guo.learningprogresstracker.dto.request.AiUsageReportRequest;
import com.guo.learningprogresstracker.entity.CommonResult;
import com.guo.learningprogresstracker.exception.ErrorParameterException;
import com.guo.learningprogresstracker.service.AiUsageService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* lpt-ai 用量上报(契约 1)。
*
* <p>这是服务间接口,不是用户接口:调用方是 lpt-ai 进程,没有登录态,
* 因此 {@code /internal/**} 已在 {@code WebMvcConfig} 中排除 Sa-Token 登录校验,
* 改用 {@code x-api-token} 与 {@code lpt.ai-usage.report-token} 比对(配置为空表示不校验)。</p>
*/
@RestController
@RequestMapping("/internal/ai-usage")
@RequiredArgsConstructor
public class AiUsageInternalController {
/** 契约 1:单次最多 200 条 */
static final int MAX_RECORDS_PER_REPORT = 200;
private final AiUsageService aiUsageService;
private final AiUsageProperties properties;
/**
* 上报用量记录。
*
* <p>按 {@code recordId} 幂等:重复上报不报错,只在结果里体现为 {@code duplicated}。</p>
*/
@PostMapping("/records")
public CommonResult<AiUsageIngestResult> report(
@RequestHeader(name = "x-api-token", required = false) String apiToken,
@Valid @RequestBody AiUsageReportRequest request) throws ErrorParameterException {
if (!isTokenAccepted(apiToken)) {
return CommonResult.error("上报令牌不正确");
}
List<AiUsageRecordRequest> records = request.getRecords();
if (records.size() > MAX_RECORDS_PER_REPORT) {
return CommonResult.error("单次最多上报 " + MAX_RECORDS_PER_REPORT + " 条记录");
}
return CommonResult.success(aiUsageService.ingest(records));
}
/** 契约 1:report-token 为空表示 lpt-ai 未启用令牌校验,直接放行 */
private boolean isTokenAccepted(String apiToken) {
String expected = properties.getReportToken();
return expected == null || expected.isBlank() || expected.equals(apiToken);
}
}