Commit c0d5047f by renyizhao

修改大屏数据

parent c532579c
......@@ -68,7 +68,7 @@ public class AiTokenStatsController {
}
AiTokenStatsVO vo = new AiTokenStatsVO();
vo.setStatsCount(result.getStatsCount());
vo.setStatsConsumeQuota(result.getStatsConsumeQuota());
vo.setStatsQuota(result.getStatsQuota());
vo.setStatsTokens(result.getStatsTokens());
vo.setStatsGiftAmount(result.getStatsGiftAmount());
......@@ -78,10 +78,10 @@ public class AiTokenStatsController {
@lombok.Data
public static class AiTokenStatsVO {
@io.swagger.v3.oas.annotations.media.Schema(description = "统计次数")
private Integer statsCount;
@io.swagger.v3.oas.annotations.media.Schema(description = "消费额度(元)")
private java.math.BigDecimal statsConsumeQuota;
@io.swagger.v3.oas.annotations.media.Schema(description = "统计额度(元)")
@io.swagger.v3.oas.annotations.media.Schema(description = "充值额度(元)")
private java.math.BigDecimal statsQuota;
@io.swagger.v3.oas.annotations.media.Schema(description = "统计Tokens")
......
......@@ -25,6 +25,27 @@ public class AiTokenService {
@Resource
private NewApiClient newApiClient;
/**
* 额度换算比例:1 元 = 500000 quota(与 NewAPI QuotaPerUnit 一致)
*/
private static final BigDecimal QUOTA_PER_YUAN = new BigDecimal("500000");
/**
* 充值类日志类型:1=充值(NewAPI 审计改造后,兑换码充值、管理员增加额度都归类到此)
*/
private static final int RECHARGE_LOG_TYPE = 1;
/**
* 兑换码充值:content = "通过兑换码充值 ¥1.000000 额度,兑换码ID 19",捕获的金额已是元
*/
private static final Pattern REDEMPTION_PATTERN =
Pattern.compile("^通过兑换码充值 ¥(\\d+(?:\\.\\d+)?)\\s*额度,兑换码ID\\s*(\\d+)$");
/**
* 管理员增加额度:content = "Increased user quota by 22500000",捕获的是原始 quota
*/
private static final Pattern GIFT_PATTERN = Pattern.compile("^Increased user quota by (\\d+)$");
public AiTokenResult getOrCreateToken(Long userId, String newApiUsername, String newApiPassword,
Long newApiUserId, String newApiAccessToken, String newApiKey) {
log.info("[AiTokenService] userId={}, hasApiKey={}", userId, newApiKey != null && !newApiKey.isEmpty());
......@@ -261,12 +282,15 @@ public class AiTokenService {
*
* @param startTimestamp 起始时间戳(秒)
* @param endTimestamp 截止时间戳(秒)
* @return 统计数据(统计次数、统计额度、统计Tokens)
* @return 统计数据(消费额度、充值额度、统计Tokens、赠送金额)
*/
public AiTokenStatsResult getUserStats(Long startTimestamp, Long endTimestamp) {
log.info("[AiTokenService.getUserStats] startTimestamp={}, endTimestamp={}", startTimestamp, endTimestamp);
try {
// 累计充值额度与累计赠送金额(来自 NewAPI 充值类日志)
RechargeStats rechargeStats = safeGetRechargeStats(startTimestamp, endTimestamp);
NewApiResponse<Map<String, Object>> resp = newApiClient.getUserStats(startTimestamp, endTimestamp);
log.info("[AiTokenService.getUserStats] resp success={}, message={}", resp.getSuccess(), resp.getMessage());
......@@ -283,10 +307,10 @@ public class AiTokenService {
if (dataField == null) {
return AiTokenStatsResult.builder()
.success(true)
.statsCount(0)
.statsQuota(BigDecimal.ZERO)
.statsConsumeQuota(BigDecimal.ZERO)
.statsQuota(rechargeStats.getRechargeAmount())
.statsTokens(0L)
.statsGiftAmount(safeGetGiftAmount(startTimestamp, endTimestamp))
.statsGiftAmount(rechargeStats.getGiftAmount())
.build();
}
......@@ -299,25 +323,18 @@ public class AiTokenService {
} else {
return AiTokenStatsResult.builder()
.success(true)
.statsCount(0)
.statsQuota(BigDecimal.ZERO)
.statsConsumeQuota(BigDecimal.ZERO)
.statsQuota(rechargeStats.getRechargeAmount())
.statsTokens(0L)
.statsGiftAmount(safeGetGiftAmount(startTimestamp, endTimestamp))
.statsGiftAmount(rechargeStats.getGiftAmount())
.build();
}
// 汇总统计
long totalCount = 0;
// 汇总统计:消耗额度与消耗 Tokens
long totalTokens = 0;
long totalQuota = 0;
for (Map<String, Object> item : items) {
// count 字段
Object countObj = item.get("count");
if (countObj instanceof Number) {
totalCount += ((Number) countObj).longValue();
}
// token_used 字段
Object tokensObj = item.get("token_used");
if (tokensObj instanceof Number) {
......@@ -331,18 +348,19 @@ public class AiTokenService {
}
}
// quota 转换为元(除以 500000)
BigDecimal statsQuota = BigDecimal.valueOf(totalQuota)
.divide(BigDecimal.valueOf(500000), 2, RoundingMode.HALF_UP);
// 消耗额度转换为元(1 元 = 500000 quota)
BigDecimal statsConsumeQuota = BigDecimal.valueOf(totalQuota)
.divide(QUOTA_PER_YUAN, 2, RoundingMode.HALF_UP);
log.info("[AiTokenService.getUserStats] 汇总结果: count={}, tokens={}, quota={}", totalCount, totalTokens, statsQuota);
log.info("[AiTokenService.getUserStats] 汇总结果: consumeQuota={}, tokens={}, 累计充值={} 元, 累计赠送={} 元",
statsConsumeQuota, totalTokens, rechargeStats.getRechargeAmount(), rechargeStats.getGiftAmount());
return AiTokenStatsResult.builder()
.success(true)
.statsCount((int) totalCount)
.statsConsumeQuota(statsConsumeQuota)
.statsQuota(rechargeStats.getRechargeAmount())
.statsTokens(totalTokens)
.statsQuota(statsQuota)
.statsGiftAmount(safeGetGiftAmount(startTimestamp, endTimestamp))
.statsGiftAmount(rechargeStats.getGiftAmount())
.build();
} catch (Exception e) {
......@@ -355,15 +373,18 @@ public class AiTokenService {
}
/**
* 安全调用 getAdminGiftAmount,失败时返回 0
* 主统计失败时不应被 gift 调用拖垮
* 安全调用 getRechargeStats,失败时降级返回 0
* 主统计失败时不应被充值类统计拖垮
*/
private BigDecimal safeGetGiftAmount(Long startTimestamp, Long endTimestamp) {
private RechargeStats safeGetRechargeStats(Long startTimestamp, Long endTimestamp) {
try {
return getAdminGiftAmount(startTimestamp, endTimestamp);
return getRechargeStats(startTimestamp, endTimestamp);
} catch (Exception e) {
log.error("[safeGetGiftAmount] 赠送金额查询失败,降级返回 0", e);
return BigDecimal.ZERO;
log.error("[safeGetRechargeStats] 充值类统计失败,降级返回 0", e);
return RechargeStats.builder()
.rechargeAmount(BigDecimal.ZERO)
.giftAmount(BigDecimal.ZERO)
.build();
}
}
......@@ -374,35 +395,53 @@ public class AiTokenService {
public static class AiTokenStatsResult {
private Boolean success;
private String message;
private Integer statsCount; // 统计次数
private BigDecimal statsQuota; // 统计额度(元)
private BigDecimal statsConsumeQuota; // 消费额度(元,累计消耗额度)
private BigDecimal statsQuota; // 充值额度(元,累计兑换码充值)
private Long statsTokens; // 统计Tokens
private BigDecimal statsGiftAmount; // 赠送金额(元,管理员增加的用户额度)
}
/**
* 统计全平台"管理员增加用户额度"的总金额(元)
* 通过 admin 调 New API /api/log?type=3,按 content 匹配 "管理员增加用户额度 ¥xxx 额度" 累加
* 注意:type=3 的记录 quota 字段为 0,金额必须从 content 提取
* 累计充值金额与累计赠送金额
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class RechargeStats {
private BigDecimal rechargeAmount; // 累计充值金额(元,兑换码充值)
private BigDecimal giftAmount; // 累计赠送金额(元,管理员增加额度)
}
/**
* 统计累计充值金额与累计赠送金额(元),时间范围内累计
* <p>
* 数据来源:NewAPI 充值类日志(type=1),两种内容格式:
* <ul>
* <li>兑换码充值:content = "通过兑换码充值 ¥1.000000 额度,兑换码ID 19",金额已是元</li>
* <li>管理员增加额度:content = "Increased user quota by 22500000",是原始 quota,需除以 500000 换成元</li>
* </ul>
* 旧版管理类(type=3)日志(content = "管理员增加用户额度 ¥x 额度")为内部测试数据,不参与统计。
* 注意:这些日志的 quota 字段为 0,金额必须从 content 提取。
*
* @param startTimestamp 起始时间戳(秒)
* @param endTimestamp 截止时间戳(秒)
* @return 赠送总额(元,保留 2 位小数)
* @return 累计充值金额与累计赠送金额(元,保留 2 位小数)
*/
public BigDecimal getAdminGiftAmount(Long startTimestamp, Long endTimestamp) {
public RechargeStats getRechargeStats(Long startTimestamp, Long endTimestamp) {
final int pageSize = 100;
final int maxPages = 200; // 安全上限,防止 total 异常时死循环
// 严格匹配 "管理员增加用户额度 ¥金额 额度",避免误匹配其他 type=3 记录
final Pattern pattern = Pattern.compile("^管理员增加用户额度\\s+¥(\\d+(?:\\.\\d+)?)\\s+额度$");
BigDecimal totalGiftYuan = BigDecimal.ZERO;
BigDecimal rechargeYuan = BigDecimal.ZERO;
BigDecimal giftYuan = BigDecimal.ZERO;
int total = 0;
for (int page = 1; page <= maxPages; page++) {
NewApiResponse<Map<String, Object>> resp = newApiClient.getAdminLog(
page, pageSize, 3, startTimestamp, endTimestamp);
page, pageSize, RECHARGE_LOG_TYPE, startTimestamp, endTimestamp);
if (!Boolean.TRUE.equals(resp.getSuccess()) || resp.getData() == null) {
log.warn("[getAdminGiftAmount] 第 {} 页请求失败: {}", page, resp.getMessage());
log.warn("[getRechargeStats] 第 {} 页请求失败: {}", page, resp.getMessage());
break;
}
......@@ -410,33 +449,39 @@ public class AiTokenService {
Map<String, Object> data = resp.getData();
@SuppressWarnings("unchecked")
List<Map<String, Object>> items = (List<Map<String, Object>>) data.get("items");
int total = 0;
Object totalObj = data.get("total");
if (totalObj instanceof Number) {
total = ((Number) totalObj).intValue();
}
if (items == null || items.isEmpty()) {
log.info("[getAdminGiftAmount] 第 {} 页无数据,结束", page);
break;
}
for (Map<String, Object> item : items) {
Object contentObj = item.get("content");
if (!(contentObj instanceof String)) continue;
Matcher matcher = pattern.matcher((String) contentObj);
if (matcher.matches()) {
try {
BigDecimal amount = new BigDecimal(matcher.group(1));
totalGiftYuan = totalGiftYuan.add(amount);
} catch (NumberFormatException nfe) {
log.warn("[getAdminGiftAmount] 金额解析失败: {}", matcher.group(1));
if (!(contentObj instanceof String)) {
continue;
}
String content = (String) contentObj;
// 兑换码充值:文案中已是元
Matcher redemptionMatcher = REDEMPTION_PATTERN.matcher(content);
if (redemptionMatcher.matches()) {
rechargeYuan = rechargeYuan.add(new BigDecimal(redemptionMatcher.group(1)));
continue;
}
// 管理员增加额度:捕获的是原始 quota,换算成元
Matcher giftMatcher = GIFT_PATTERN.matcher(content);
if (giftMatcher.matches()) {
giftYuan = giftYuan.add(new BigDecimal(giftMatcher.group(1))
.divide(QUOTA_PER_YUAN, 6, RoundingMode.DOWN));
}
}
log.info("[getAdminGiftAmount] 第 {} 页: items={}, total={}, 当前累加={} 元",
page, items.size(), total, totalGiftYuan);
log.info("[getRechargeStats] 第 {} 页: items={}, total={}, 累计充值={} 元, 累计赠送={} 元",
page, items.size(), total, rechargeYuan, giftYuan);
// 终止条件 1:已拉满 total
if (total > 0 && page * pageSize >= total) {
......@@ -448,7 +493,10 @@ public class AiTokenService {
}
}
log.info("[getAdminGiftAmount] 赠送总额: {} 元", totalGiftYuan);
return totalGiftYuan.setScale(2, RoundingMode.HALF_UP);
log.info("[getRechargeStats] 累计充值: {} 元, 累计赠送: {} 元", rechargeYuan, giftYuan);
return RechargeStats.builder()
.rechargeAmount(rechargeYuan.setScale(2, RoundingMode.HALF_UP))
.giftAmount(giftYuan.setScale(2, RoundingMode.HALF_UP))
.build();
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment