diff --git a/AGENTS.md b/AGENTS.md index d894c00..1b643dd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -151,6 +151,16 @@ lpt-be/src/main/java/com/guo/learningprogresstracker/ - **计价在 lpt-ai 侧冻结**:`cost_usd` 是上报时按当期价目算好的,本服务只做聚合与汇率换算, 改价不会重写历史账。汇率走 `lpt.ai-usage.usd-to-cny`。 - **口径**:只统计 `is_llm_call = 1` 的记录(`/fetch-title` 这类不消耗 LLM)。 +- **分组维度**:`breakdown?groupBy=taskType|model|user`。用户维度下 `key` 是用户 id + (未归属为 `null`)、`label` 是登录名(未归属为「未归属」,查不到登录名时回退为 `key`); + 其它维度下 `label` 等于 `key`,前端统一渲染 `label` 即可。用户筛选用 `userId` 参数。 +- **归属链路(callerRef)**:lpt-ai 不知道调用方是谁,所以归属标记跟着请求走—— + `AiServiceClient` 提交任务时把当前用户 id 作为**顶层** `callerRef` 带上(取不到身份就不带, + 记为未归属,绝不让 AI 调用因此失败),lpt-ai 原样透传,上报后落到 `user_id`。 + 标记在 LLM 调用之前就已确定,因此没有「上报先到、归属还没写回」的竞态。 + **`callerRef` 不能放进 `params`**:params 会喂给 prompt 模板、也参与 lpt-ai 的幂等键。 +- **`user_id` 不是租户列**:本表在 `EXCLUDE_TABLES` 中,`user_id` 只用于分组与筛选。 + 改成租户过滤会让管理员只能看到自己触发的调用,面板等于永远是空的。 - 配置:`lpt.ai-usage.admin-usernames`(白名单,部署用 `LPT_AI-USAGE_ADMIN-USERNAMES`)、 `lpt.ai-usage.report-token`(上报令牌,部署用 `LPT_AI-USAGE_REPORT-TOKEN`,与 lpt-ai 的 `LPT_AI_REPORT_TOKEN` 共用 `lpt-secrets/lpt-ai-report-token`)。 diff --git a/src/main/java/com/guo/learningprogresstracker/dto/AiUsageBreakdownItem.java b/src/main/java/com/guo/learningprogresstracker/dto/AiUsageBreakdownItem.java index 1fc2764..5ef0365 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/AiUsageBreakdownItem.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/AiUsageBreakdownItem.java @@ -5,14 +5,23 @@ import lombok.Data; import java.math.BigDecimal; /** - * 用量按任务类型 / 模型分组的一项(契约 2.4,{@code GET /ai/usage/breakdown})。 + * 用量按任务类型 / 模型 / 用户分组的一项(契约 2.4、v2 第 4.2 节,{@code GET /ai/usage/breakdown})。 */ @Data public class AiUsageBreakdownItem { - /** 分组键:{@code groupBy=taskType} 时是任务类型,{@code groupBy=model} 时是模型名 */ + /** + * 分组键:{@code groupBy=taskType} 时是任务类型,{@code groupBy=model} 时是模型名, + * {@code groupBy=user} 时是用户 id(未归属的记录为 null)。 + */ private String key; + /** + * 展示名:{@code groupBy=user} 时是登录名(未归属为「未归属」,查不到登录名时回退为 {@code key}), + * 其它分组维度下等于 {@code key}——前端统一渲染 {@code label} 即可,不必按维度分支。 + */ + private String label; + private Long calls; private Long successCalls; diff --git a/src/main/java/com/guo/learningprogresstracker/dto/request/AiUsageQuery.java b/src/main/java/com/guo/learningprogresstracker/dto/request/AiUsageQuery.java index 4c13475..78e061d 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/request/AiUsageQuery.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/request/AiUsageQuery.java @@ -20,9 +20,12 @@ public class AiUsageQuery { /** 模型名,精确匹配;为空表示不限 */ private String model; + /** 归属用户 id,精确匹配;为空表示不限 */ + private String userId; + /** series 的分桶粒度:day / hour */ private String bucket = "day"; - /** breakdown 的分组维度:taskType / model */ + /** breakdown 的分组维度:taskType / model / user */ private String groupBy = "taskType"; } diff --git a/src/main/java/com/guo/learningprogresstracker/dto/request/AiUsageRecordRequest.java b/src/main/java/com/guo/learningprogresstracker/dto/request/AiUsageRecordRequest.java index 5c018f4..fc2564a 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/request/AiUsageRecordRequest.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/request/AiUsageRecordRequest.java @@ -2,6 +2,7 @@ package com.guo.learningprogresstracker.dto.request; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; import lombok.Data; import java.math.BigDecimal; @@ -28,6 +29,16 @@ public class AiUsageRecordRequest { private String taskId; + /** + * 归属标记(契约 v2 第 2 节):lpt-be 提交任务时带的用户 id,lpt-ai 原样透传,落库到 + * {@code ai_usage_records.user_id}。 + * + *

刻意不用 {@code @NotBlank}:历史数据、lpt-ai 独立调用、以及调用方没带标记时都是空值, + * 空值只表示「未归属」,不是错误——用 {@code @NotBlank} 会把这类上报整批打成 400。

+ */ + @Size(max = 64, message = "callerRef 不能超过 64 个字符") + private String callerRef; + /** * 模型名。 * diff --git a/src/main/java/com/guo/learningprogresstracker/entity/AiUsageRecordEntity.java b/src/main/java/com/guo/learningprogresstracker/entity/AiUsageRecordEntity.java index d5543c4..a1c2464 100644 --- a/src/main/java/com/guo/learningprogresstracker/entity/AiUsageRecordEntity.java +++ b/src/main/java/com/guo/learningprogresstracker/entity/AiUsageRecordEntity.java @@ -42,6 +42,15 @@ public class AiUsageRecordEntity extends BaseEntity implements Serializable { @TableField(value = "task_id") private String taskId; + /** + * 归属用户:取自上报的 {@code callerRef};null=未归属(历史数据/独立调用/调用方没传)。 + * + *

只用于分组与筛选,不是租户列:本表已在 {@code MybatisPlusConfig.EXCLUDE_TABLES} + * 中,绝不能按它过滤,否则面板只能看到当前管理员自己触发的调用。

+ */ + @TableField(value = "user_id") + private String userId; + /** 模型名,如 deepseek-flash */ @TableField(value = "model") private String model; diff --git a/src/main/java/com/guo/learningprogresstracker/mapper/AiUsageRecordMapper.java b/src/main/java/com/guo/learningprogresstracker/mapper/AiUsageRecordMapper.java index aa85b18..b122f62 100644 --- a/src/main/java/com/guo/learningprogresstracker/mapper/AiUsageRecordMapper.java +++ b/src/main/java/com/guo/learningprogresstracker/mapper/AiUsageRecordMapper.java @@ -31,12 +31,14 @@ public interface AiUsageRecordMapper extends BaseMapper { * @param to 结束时刻(含);null 表示不限 * @param taskType 任务类型精确匹配;null 表示不限 * @param model 模型名精确匹配;null 表示不限 + * @param userId 归属用户精确匹配;null 表示不限(契约 v2 第 4.1 节) * @return 无匹配记录时返回全 0 的一行(AVG 为 null) */ AiUsageSummaryRow selectSummary(@Param("from") LocalDateTime from, @Param("to") LocalDateTime to, @Param("taskType") String taskType, - @Param("model") String model); + @Param("model") String model, + @Param("userId") String userId); /** * P95 调用耗时(毫秒,最近秩法:取第 {@code ceil(0.95 × 调用数)} 小的耗时)。 @@ -49,7 +51,8 @@ public interface AiUsageRecordMapper extends BaseMapper { Integer selectP95DurationMs(@Param("from") LocalDateTime from, @Param("to") LocalDateTime to, @Param("taskType") String taskType, - @Param("model") String model); + @Param("model") String model, + @Param("userId") String userId); /** * 按天或按小时分桶的用量趋势(契约 2.3)。 @@ -60,16 +63,18 @@ public interface AiUsageRecordMapper extends BaseMapper { @Param("to") LocalDateTime to, @Param("taskType") String taskType, @Param("model") String model, + @Param("userId") String userId, @Param("bucket") String bucket); /** - * 按任务类型或模型分组的用量(契约 2.4)。 + * 按任务类型、模型或归属用户分组的用量(契约 2.4 / v2 第 4.2 节)。 * - * @param groupBy {@code taskType}(默认)或 {@code model} + * @param groupBy {@code taskType}(默认)、{@code model} 或 {@code user} */ List selectBreakdown(@Param("from") LocalDateTime from, @Param("to") LocalDateTime to, @Param("taskType") String taskType, @Param("model") String model, + @Param("userId") String userId, @Param("groupBy") String groupBy); } diff --git a/src/main/java/com/guo/learningprogresstracker/service/AiUsageService.java b/src/main/java/com/guo/learningprogresstracker/service/AiUsageService.java index 7b61b24..b4b82b9 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/AiUsageService.java +++ b/src/main/java/com/guo/learningprogresstracker/service/AiUsageService.java @@ -35,7 +35,7 @@ public interface AiUsageService { /** 按天/按小时的用量趋势(契约 2.3) */ List series(AiUsageQuery query) throws ErrorParameterException; - /** 按任务类型/模型的用量分组(契约 2.4) */ + /** 按任务类型/模型/归属用户的用量分组(契约 2.4、v2 第 4.2 节) */ List breakdown(AiUsageQuery query) throws ErrorParameterException; /** 代理查询上游余额(契约 2.5);上游不可用时返回 {@code configured=false} */ diff --git a/src/main/java/com/guo/learningprogresstracker/service/UserService.java b/src/main/java/com/guo/learningprogresstracker/service/UserService.java index 1740ab4..b738a5b 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/UserService.java +++ b/src/main/java/com/guo/learningprogresstracker/service/UserService.java @@ -4,6 +4,9 @@ import com.guo.learningprogresstracker.entity.UserEntity; import com.baomidou.mybatisplus.extension.service.IService; import com.guo.learningprogresstracker.exception.AppException; +import java.util.Collection; +import java.util.Map; + /** * @author guo * @description 针对表【user(用户信息表)】的数据库操作Service @@ -28,4 +31,14 @@ public interface UserService extends IService { * @return 用户不存在时返回 null */ String getUserNameById(String userId); + + /** + * 批量取登录名,用于「AI 用量统计」按用户分组的展示名(契约 v2 第 4.2 节)。 + * + *

一次 {@code IN} 查询拿全部,避免每个分组各查一次(N+1)。

+ * + * @param ids 用户 id 集合;为空或 null 时直接返回空 Map,不发查询 + * @return 用户 id → 登录名;查不到的用户不会出现在结果里,由调用方决定回退文案 + */ + Map getUserNamesByIds(Collection ids); } diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/AiServiceClient.java b/src/main/java/com/guo/learningprogresstracker/service/impl/AiServiceClient.java index 8b9e552..e766d67 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/AiServiceClient.java +++ b/src/main/java/com/guo/learningprogresstracker/service/impl/AiServiceClient.java @@ -1,8 +1,11 @@ package com.guo.learningprogresstracker.service.impl; +import cn.dev33.satoken.exception.SaTokenException; +import cn.dev33.satoken.stp.StpUtil; import com.fasterxml.jackson.databind.JsonNode; -import com.guo.learningprogresstracker.dto.ReportSections; import com.fasterxml.jackson.databind.ObjectMapper; +import com.guo.learningprogresstracker.common.TenantContext; +import com.guo.learningprogresstracker.dto.ReportSections; import jakarta.annotation.PostConstruct; import lombok.Setter; import lombok.extern.slf4j.Slf4j; @@ -15,6 +18,7 @@ import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; import java.time.Instant; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -213,7 +217,16 @@ public class AiServiceClient { /** 提交任务到 lpt-ai /ai/tasks */ private String submitTask(String type, Map params) { try { - Map body = Map.of("type", type, "params", params); + Map body = new LinkedHashMap<>(); + body.put("type", type); + body.put("params", params); + // 归属标记(契约 v2 第 1 节):放在顶层,绝不放进 params—— + // params 会喂给 prompt 模板、也参与 lpt-ai 的幂等键,混进去会污染两者。 + // 拿不到身份时整个键都不写(等价于 null),这笔用量记为「未归属」。 + String callerRef = currentCallerRef(); + if (callerRef != null && !callerRef.isBlank()) { + body.put("callerRef", callerRef); + } HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(url + "/ai/tasks")) .timeout(Duration.ofSeconds(30)) // 提交本身不应超时 @@ -243,6 +256,32 @@ public class AiServiceClient { } } + /** + * 归属标记:当前执行身份的用户 id(契约 v2 第 1 节)。 + * + *

口径与 {@code AutoTableField.currentLoginId()} 一致:后台执行线程通过 + * {@link TenantContext} 显式声明身份,请求线程回落到 {@link StpUtil}。

+ * + *

与自动填充不同的是这里必须容错:身份取不到只是这笔用量记成「未归属」, + * 不能让 AI 任务本身提交失败(非 Web 线程取 {@code StpUtil} 会抛 + * {@code NotWebContextException},未登录时抛 {@code NotLoginException},两者都属 + * {@link SaTokenException})。

+ * + * @return 拿不到身份时返回 null,请求体里就不带 callerRef + */ + private static String currentCallerRef() { + TenantContext.Identity identity = TenantContext.get(); + if (identity != null) { + return identity.loginId(); + } + try { + return StpUtil.getLoginIdAsString(); + } catch (SaTokenException e) { + log.debug("取不到当前身份,本次 AI 任务的用量将记为未归属: {}", e.getMessage()); + return null; + } + } + /** 轮询等待任务完成 */ private Optional pollResult(String taskId) { Instant deadline = Instant.now().plusSeconds(timeoutSeconds); diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/AiUsageServiceImpl.java b/src/main/java/com/guo/learningprogresstracker/service/impl/AiUsageServiceImpl.java index 0aaf661..ad82f0f 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/AiUsageServiceImpl.java +++ b/src/main/java/com/guo/learningprogresstracker/service/impl/AiUsageServiceImpl.java @@ -6,6 +6,7 @@ import com.guo.learningprogresstracker.common.TenantContext; import com.guo.learningprogresstracker.config.AiUsageProperties; import com.guo.learningprogresstracker.dto.AiUsageBalance; import com.guo.learningprogresstracker.dto.AiUsageBreakdownItem; +import com.guo.learningprogresstracker.dto.AiUsageBreakdownRow; import com.guo.learningprogresstracker.dto.AiUsageIngestResult; import com.guo.learningprogresstracker.dto.AiUsageSeriesPoint; import com.guo.learningprogresstracker.dto.AiUsageSummary; @@ -33,6 +34,8 @@ import java.time.format.DateTimeParseException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; +import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; @@ -51,6 +54,10 @@ public class AiUsageServiceImpl implements AiUsageService { private static final String BUCKET_HOUR = "hour"; private static final String GROUP_BY_TASK_TYPE = "taskType"; private static final String GROUP_BY_MODEL = "model"; + private static final String GROUP_BY_USER = "user"; + + /** 未归属({@code user_id} 为 null)在面板上的展示名;契约 v2 第 4.2 节要求它单独可见 */ + private static final String UNASSIGNED_LABEL = "未归属"; private final AiUsageRecordMapper aiUsageRecordMapper; private final UserService userService; @@ -126,6 +133,9 @@ public class AiUsageServiceImpl implements AiUsageService { entity.setOccurredAt(parseUtc(record.getOccurredAt())); entity.setTaskType(record.getTaskType()); entity.setTaskId(record.getTaskId()); + // 归属标记原样落库:lpt-ai 不解释它的含义,这里也不校验它是否真是个存在的用户—— + // 查不到用户名时面板回退显示用户 id(见 breakdown),比把整条用量丢掉强 + entity.setUserId(record.getCallerRef()); entity.setModel(record.getModel()); entity.setAttempts(record.getAttempts()); entity.setIsLlmCall(record.getIsLlmCall()); @@ -175,9 +185,9 @@ public class AiUsageServiceImpl implements AiUsageService { public AiUsageSummary summary(AiUsageQuery query) { ResolvedFilter filter = resolve(query); AiUsageSummaryRow row = aiUsageRecordMapper.selectSummary( - filter.from(), filter.to(), filter.taskType(), filter.model()); + filter.from(), filter.to(), filter.taskType(), filter.model(), filter.userId()); Integer p95DurationMs = aiUsageRecordMapper.selectP95DurationMs( - filter.from(), filter.to(), filter.taskType(), filter.model()); + filter.from(), filter.to(), filter.taskType(), filter.model(), filter.userId()); long cacheHitTokens = nullToZero(row.getCacheHitTokens()); long cacheMissTokens = nullToZero(row.getCacheMissTokens()); @@ -209,7 +219,7 @@ public class AiUsageServiceImpl implements AiUsageService { String bucket = requireBucket(query == null ? null : query.getBucket()); return aiUsageRecordMapper.selectSeries( - filter.from(), filter.to(), filter.taskType(), filter.model(), bucket) + filter.from(), filter.to(), filter.taskType(), filter.model(), filter.userId(), bucket) .stream() .map(row -> { AiUsageSeriesPoint point = new AiUsageSeriesPoint(); @@ -230,26 +240,60 @@ public class AiUsageServiceImpl implements AiUsageService { ResolvedFilter filter = resolve(query); String groupBy = requireGroupBy(query == null ? null : query.getGroupBy()); - return aiUsageRecordMapper.selectBreakdown( - filter.from(), filter.to(), filter.taskType(), filter.model(), groupBy) - .stream() - .map(row -> { - AiUsageBreakdownItem item = new AiUsageBreakdownItem(); - item.setKey(row.getGroupKey()); - item.setCalls(nullToZero(row.getCalls())); - item.setSuccessCalls(nullToZero(row.getSuccessCalls())); - item.setFailedCalls(nullToZero(row.getFailedCalls())); - item.setPromptTokens(nullToZero(row.getPromptTokens())); - item.setCompletionTokens(nullToZero(row.getCompletionTokens())); - item.setCacheHitTokens(nullToZero(row.getCacheHitTokens())); - item.setCostUsd(nullToZero(row.getCostUsd())); - item.setAvgDurationMs(row.getAvgDurationMs() == null - ? null : Math.round(row.getAvgDurationMs())); - return item; - }) + List rows = aiUsageRecordMapper.selectBreakdown( + filter.from(), filter.to(), filter.taskType(), filter.model(), filter.userId(), groupBy); + // groupBy=user 的分组键是用户 id,前端要显示登录名;一次批量查完,不要按分组逐条查 + Map userNames = GROUP_BY_USER.equals(groupBy) ? loadUserNames(rows) : Map.of(); + + return rows.stream() + .map(row -> toBreakdownItem(row, groupBy, userNames)) .collect(Collectors.toList()); } + /** 分组键就是用户 id:去重后一次查完登录名(未归属的 null 键不参与查询) */ + private Map loadUserNames(List rows) { + Set userIds = rows.stream() + .map(AiUsageBreakdownRow::getGroupKey) + .filter(Objects::nonNull) + .collect(Collectors.toSet()); + return userService.getUserNamesByIds(userIds); + } + + private static AiUsageBreakdownItem toBreakdownItem(AiUsageBreakdownRow row, String groupBy, + Map userNames) { + String key = row.getGroupKey(); + AiUsageBreakdownItem item = new AiUsageBreakdownItem(); + item.setKey(key); + item.setLabel(breakdownLabel(key, groupBy, userNames)); + item.setCalls(nullToZero(row.getCalls())); + item.setSuccessCalls(nullToZero(row.getSuccessCalls())); + item.setFailedCalls(nullToZero(row.getFailedCalls())); + item.setPromptTokens(nullToZero(row.getPromptTokens())); + item.setCompletionTokens(nullToZero(row.getCompletionTokens())); + item.setCacheHitTokens(nullToZero(row.getCacheHitTokens())); + item.setCostUsd(nullToZero(row.getCostUsd())); + item.setAvgDurationMs(row.getAvgDurationMs() == null + ? null : Math.round(row.getAvgDurationMs())); + return item; + } + + /** + * 分组的展示名(契约 v2 第 4.2 节)。 + * + *

非 user 分组下 label 就是 key:前端统一渲染 {@code label} 即可,不必按维度分支。 + * user 分组下换成登录名;未归属(key 为 null)显示「未归属」,否则归属链路断了也看不出来; + * 查不到登录名时回退成用户 id,总比整行显示空白强。

+ */ + private static String breakdownLabel(String key, String groupBy, Map userNames) { + if (!GROUP_BY_USER.equals(groupBy)) { + return key; + } + if (key == null) { + return UNASSIGNED_LABEL; + } + return userNames.getOrDefault(key, key); + } + @Override public AiUsageBalance balance() { return aiUsageClient.fetchBalance(); @@ -268,7 +312,8 @@ public class AiUsageServiceImpl implements AiUsageService { : LocalDateTime.ofInstant(Instant.ofEpochMilli(to), ZoneOffset.UTC); return new ResolvedFilter(fromTime, toTime, query == null ? null : query.getTaskType(), - query == null ? null : query.getModel()); + query == null ? null : query.getModel(), + query == null ? null : query.getUserId()); } private static String requireBucket(String bucket) throws ErrorParameterException { @@ -287,8 +332,8 @@ public class AiUsageServiceImpl implements AiUsageService { return GROUP_BY_TASK_TYPE; } String value = groupBy.trim(); - if (!GROUP_BY_TASK_TYPE.equals(value) && !GROUP_BY_MODEL.equals(value)) { - throw new ErrorParameterException("分组维度只支持 taskType 或 model"); + if (!GROUP_BY_TASK_TYPE.equals(value) && !GROUP_BY_MODEL.equals(value) && !GROUP_BY_USER.equals(value)) { + throw new ErrorParameterException("分组维度只支持 taskType、model 或 user"); } return value; } @@ -302,6 +347,6 @@ public class AiUsageServiceImpl implements AiUsageService { } /** 解析后的查询条件(时间已转成 UTC 本地时间) */ - private record ResolvedFilter(LocalDateTime from, LocalDateTime to, String taskType, String model) { + private record ResolvedFilter(LocalDateTime from, LocalDateTime to, String taskType, String model, String userId) { } } diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/UserServiceImpl.java b/src/main/java/com/guo/learningprogresstracker/service/impl/UserServiceImpl.java index 9b9bd9b..b46305f 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/UserServiceImpl.java +++ b/src/main/java/com/guo/learningprogresstracker/service/impl/UserServiceImpl.java @@ -10,6 +10,11 @@ import lombok.RequiredArgsConstructor; import org.mindrot.jbcrypt.BCrypt; import org.springframework.stereotype.Service; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.stream.Collectors; + /** * @author guo * @description 针对表【user(用户信息表)】的数据库操作Service实现 @@ -42,4 +47,18 @@ public class UserServiceImpl extends ServiceImpl UserEntity userEntity = getById(userId); return userEntity == null ? null : userEntity.getUserName(); } + + @Override + public Map getUserNamesByIds(Collection ids) { + if (ids == null || ids.isEmpty()) { + return Map.of(); + } + // 只取 id 与 user_name 两列,避免把密码哈希这类字段拉出来 + return list(Wrappers.lambdaQuery() + .select(UserEntity::getId, UserEntity::getUserName) + .in(UserEntity::getId, ids)) + .stream() + .collect(Collectors.toMap(UserEntity::getId, UserEntity::getUserName, + (first, second) -> first, LinkedHashMap::new)); + } } diff --git a/src/main/resources/db/migration/V20261010_5__add_user_id_to_ai_usage_records.sql b/src/main/resources/db/migration/V20261010_5__add_user_id_to_ai_usage_records.sql new file mode 100644 index 0000000..60586a5 --- /dev/null +++ b/src/main/resources/db/migration/V20261010_5__add_user_id_to_ai_usage_records.sql @@ -0,0 +1,16 @@ +-- 用户维度报表(契约 v2 第 3 节):用量记录归属到「哪个用户的任务消耗了这些 token」。 +-- +-- user_id 取自上报载荷的 callerRef:lpt-be 提交 AI 任务时把用户 id 作为归属标记带上, +-- lpt-ai 只做原样透传、不解释含义(它不知道调用方是谁),结算时写进用量记录。 +-- 标记在 LLM 调用之前就已确定,因此没有「上报先到、归属还没写回」的竞态。 +-- +-- NULL = 未归属,来源有三种:改造前的历史数据、lpt-ai 独立调用、调用方没传 callerRef。 +-- 面板必须能把「未归属」单独显示出来,否则归属链路断了也看不出来。 +-- +-- 注意:user_id **不是**租户列。本表已在 MybatisPlusConfig.EXCLUDE_TABLES 中, +-- 绝不能按 user_id 过滤(否则管理员只能看到自己触发的调用,面板等于永远是空的); +-- 它只用于分组与筛选,created_by 仍是审计列、不参与任何查询条件。 +ALTER TABLE ai_usage_records ADD COLUMN user_id VARCHAR(255) NULL COMMENT '归属用户:取自上报的 callerRef;NULL=未归属(历史数据/独立调用/调用方没传)' AFTER error_code; + +-- 按用户筛选或分组 + 时间范围。键长 utf8mb4 下 255×4 + 8 = 1028 字节,在 InnoDB 3072 上限内。 +CREATE INDEX idx_ai_usage_records_user_occurred ON ai_usage_records (user_id, occurred_at); diff --git a/src/main/resources/mapper/AiUsageRecordMapper.xml b/src/main/resources/mapper/AiUsageRecordMapper.xml index 818c488..8a98036 100644 --- a/src/main/resources/mapper/AiUsageRecordMapper.xml +++ b/src/main/resources/mapper/AiUsageRecordMapper.xml @@ -48,6 +48,7 @@ 面板口径:只看真正消耗 LLM 的调用(is_llm_call = 1),fetch-title 这类不消耗 LLM 的任务不进统计。 自定义 SQL 不会被 @TableLogic 自动追加逻辑删除条件,deleted = 0 必须显式写出; 而 created_by 条件刻意不写——本表是系统级表,用量要统计全部调用(见 MybatisPlusConfig)。 + 注意 user_id 不是租户列(同样不参与过滤),它只是归属标记:这里只按它做精确筛选与分组。 --> WHERE deleted = 0 @@ -56,6 +57,7 @@ AND occurred_at <= #{to} AND task_type = #{taskType} AND model = #{model} + AND user_id = #{userId}