refactor(代理): 用户余量巡检与长样式出件,压回可读性棘轮
推送闸门抓到 UserApiSecretService 1278→1408、两枚 Vue 超过 800 行: 把用户级余量查询/缓存/巡检拆到 UserProxyBalanceService,两端组件的大段 样式移到同名 .css 由 scoped src 挂载。行为与选择器不变,只为让长文件棘轮 回到基线以内(不调基线、不整份回写)。
This commit is contained in:
+5
-3
@@ -13,6 +13,7 @@ import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretCheckResultVo;
|
||||
import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretItemVo;
|
||||
import com.nanri.aiimage.modules.usersecret.model.vo.UserProxyPlanVo;
|
||||
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
|
||||
import com.nanri.aiimage.modules.usersecret.service.UserProxyBalanceService;
|
||||
import com.nanri.aiimage.modules.usersecret.service.UserProxyPlanService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
@@ -43,6 +44,7 @@ public class UserApiSecretController {
|
||||
|
||||
private final UserApiSecretService userApiSecretService;
|
||||
private final UserProxyPlanService userProxyPlanService;
|
||||
private final UserProxyBalanceService userProxyBalanceService;
|
||||
private final AdminAuthSupport adminAuthSupport;
|
||||
|
||||
@GetMapping
|
||||
@@ -100,7 +102,7 @@ public class UserApiSecretController {
|
||||
@Operation(summary = "查询代理套餐余量", description = "转发 jikip find-balance;当前用户填了自己的套餐 ID/用户 ID 时查自己的,否则查平台套餐。")
|
||||
public ApiResponse<UserApiSecretBalanceVo> proxyBalance(HttpServletRequest request) {
|
||||
Long userId = currentUserId(request);
|
||||
return ApiResponse.success(userApiSecretService.proxyBalance(userId));
|
||||
return ApiResponse.success(userProxyBalanceService.balance(userId));
|
||||
}
|
||||
|
||||
@GetMapping("/proxy-plan")
|
||||
@@ -117,7 +119,7 @@ public class UserApiSecretController {
|
||||
@Valid @RequestBody UserProxyPlanSaveRequest body) {
|
||||
Long userId = currentUserId(request);
|
||||
UserProxyPlanVo vo = userProxyPlanService.save(userId, body.getPlanId(), body.getJikipUserId());
|
||||
userApiSecretService.invalidateProxyBalance(userId);
|
||||
userProxyBalanceService.invalidate(userId);
|
||||
return ApiResponse.success("保存成功", vo);
|
||||
}
|
||||
|
||||
@@ -126,7 +128,7 @@ public class UserApiSecretController {
|
||||
public ApiResponse<Void> clearProxyPlan(HttpServletRequest request) {
|
||||
Long userId = currentUserId(request);
|
||||
userProxyPlanService.clear(userId);
|
||||
userApiSecretService.invalidateProxyBalance(userId);
|
||||
userProxyBalanceService.invalidate(userId);
|
||||
return ApiResponse.success("已清除", null);
|
||||
}
|
||||
|
||||
|
||||
+4
-4
@@ -26,6 +26,7 @@ public class UserApiSecretCheckScheduler {
|
||||
private static final int MIN_LOCK_MINUTES = 30;
|
||||
|
||||
private final UserApiSecretService userApiSecretService;
|
||||
private final UserProxyBalanceService userProxyBalanceService;
|
||||
private final DistributedJobLockService distributedJobLockService;
|
||||
private final UserSecretProperties properties;
|
||||
|
||||
@@ -50,10 +51,9 @@ public class UserApiSecretCheckScheduler {
|
||||
log.info("[user-secret] 每日巡检完成 checked={} probed={} passed={} failed={} errors={} skipped={}",
|
||||
summary.checked(), summary.probed(), summary.passed(), summary.failed(),
|
||||
summary.errors(), summary.skipped());
|
||||
UserApiSecretService.ProxyBalanceCheckSummary proxySummary =
|
||||
userApiSecretService.checkUserProxyBalancesForScheduler(
|
||||
properties.getProxyBalanceCheckMaxRows(),
|
||||
properties.getProxyBalanceCheckBudgetMinutes());
|
||||
UserProxyBalanceService.Summary proxySummary = userProxyBalanceService.checkAll(
|
||||
properties.getProxyBalanceCheckMaxRows(),
|
||||
properties.getProxyBalanceCheckBudgetMinutes());
|
||||
log.info("[user-secret] 用户代理套餐余量巡检完成 users={} checked={} warned={} failed={}",
|
||||
proxySummary.users(), proxySummary.checked(), proxySummary.warned(), proxySummary.failed());
|
||||
} catch (Exception ex) {
|
||||
|
||||
+1
-138
@@ -17,15 +17,13 @@ import com.nanri.aiimage.modules.permission.support.UserDataScopeSupport;
|
||||
import com.nanri.aiimage.common.mapper.ShopManageGroupMapper;
|
||||
import com.nanri.aiimage.modules.shopkey.model.dto.UserGroupRef;
|
||||
import com.nanri.aiimage.common.model.entity.ShopManageGroupEntity;
|
||||
import com.nanri.aiimage.modules.usersecret.client.JikipProxyClient;import com.nanri.aiimage.modules.usersecret.mapper.UserApiSecretMapper;
|
||||
import com.nanri.aiimage.modules.usersecret.mapper.UserApiSecretMapper;
|
||||
import com.nanri.aiimage.modules.usersecret.model.dto.AdminUserSecretQuery;
|
||||
import com.nanri.aiimage.modules.usersecret.model.dto.UserApiSecretMigrateRequest;
|
||||
import com.nanri.aiimage.modules.usersecret.model.entity.UserApiSecretEntity;
|
||||
import com.nanri.aiimage.modules.usersecret.model.entity.UserProxyPlanEntity;
|
||||
import com.nanri.aiimage.modules.usersecret.model.vo.AdminUserSecretModuleVo;
|
||||
import com.nanri.aiimage.modules.usersecret.model.vo.AdminUserSecretPageVo;
|
||||
import com.nanri.aiimage.modules.usersecret.model.vo.AdminUserSecretRowVo;
|
||||
import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretBalanceVo;
|
||||
import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretBundleVo;
|
||||
import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretCheckResultVo;
|
||||
import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretItemVo;
|
||||
@@ -53,7 +51,6 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* 用户 API 密钥服务端存储:按登录用户绑定、AES 加密落库,
|
||||
@@ -92,17 +89,9 @@ public class UserApiSecretService implements UserSecretCleanupPort {
|
||||
private static final String PROXY_FORMAT_HINT =
|
||||
"代理地址格式不正确,请填写 http://host:port 形式的代理地址,或代理服务商的提取链接(https://...)";
|
||||
|
||||
/** 客户端右上角余量警告会周期性拉取;同一用户 5 分钟内复用结果,避免每个客户端轮询都打供应商。 */
|
||||
private static final long PROXY_BALANCE_CACHE_MILLIS = 5 * 60 * 1000L;
|
||||
|
||||
/** 用户级余量查询缓存(key=userId);改套餐配置时主动失效。 */
|
||||
private final Map<Long, CachedProxyBalance> proxyBalanceCache = new ConcurrentHashMap<>();
|
||||
|
||||
private final UserApiSecretMapper userApiSecretMapper;
|
||||
private final UserProxyPlanService userProxyPlanService;
|
||||
private final ShopCredentialCryptoService cryptoService;
|
||||
private final UserApiSecretCheckService checkService;
|
||||
private final JikipProxyClient jikipProxyClient;
|
||||
private final AdminUserMapper adminUserMapper;
|
||||
private final AdminAuthSupport adminAuthSupport;
|
||||
private final ShopManageGroupMapper adminGroupMapper;
|
||||
@@ -315,132 +304,6 @@ public class UserApiSecretService implements UserSecretCleanupPort {
|
||||
return vo;
|
||||
}
|
||||
|
||||
/** jikip 代理余量(客户端设置弹窗展示):用户填了自己的套餐 ID/用户 ID 时查自己的,否则查平台套餐。 */
|
||||
public UserApiSecretBalanceVo proxyBalance(Long userId) {
|
||||
requireUserId(userId);
|
||||
long now = System.currentTimeMillis();
|
||||
CachedProxyBalance cached = proxyBalanceCache.get(userId);
|
||||
if (cached != null && now - cached.cachedAt() < PROXY_BALANCE_CACHE_MILLIS) {
|
||||
return cached.balance();
|
||||
}
|
||||
UserProxyPlanEntity plan = userProxyPlanService.getEntity(userId);
|
||||
UserApiSecretBalanceVo vo;
|
||||
if (plan != null) {
|
||||
vo = jikipProxyClient.fetchBalance(
|
||||
new JikipProxyClient.PlanRef(plan.getPlanId(), plan.getJikipUserId()));
|
||||
vo.setScope("user");
|
||||
String reason = Boolean.TRUE.equals(vo.getAvailable()) ? proxyPlanLowReason(vo) : null;
|
||||
vo.setLow(reason != null);
|
||||
vo.setLowReason(reason);
|
||||
} else {
|
||||
vo = jikipProxyClient.fetchBalance();
|
||||
vo.setScope("platform");
|
||||
vo.setLow(false);
|
||||
}
|
||||
proxyBalanceCache.put(userId, new CachedProxyBalance(vo, now));
|
||||
return vo;
|
||||
}
|
||||
|
||||
/** 用户改了套餐配置后清缓存,下一次查询立即按新配置走。 */
|
||||
public void invalidateProxyBalance(Long userId) {
|
||||
if (userId != null) {
|
||||
proxyBalanceCache.remove(userId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户级 jikip 余量巡检:跟随密钥巡检一起跑;find-balance 免费,单条失败只记日志不中断。
|
||||
* 低于阈值时推该用户站内通知(每人每天一条),与平台套餐的管理员告警互不影响。
|
||||
*/
|
||||
public ProxyBalanceCheckSummary checkUserProxyBalancesForScheduler(int maxRows, int budgetMinutes) {
|
||||
if (!userSecretProperties.isNotifyEnabled()) {
|
||||
log.info("[user-secret][proxy-plan] 站内通知已关闭,余量巡检跳过");
|
||||
return new ProxyBalanceCheckSummary(0, 0, 0, 0);
|
||||
}
|
||||
List<UserProxyPlanEntity> plans = userProxyPlanService.listAll(maxRows);
|
||||
long deadline = System.currentTimeMillis() + Math.max(1, budgetMinutes) * 60_000L;
|
||||
int checked = 0;
|
||||
int warned = 0;
|
||||
int failed = 0;
|
||||
for (int i = 0; i < plans.size(); i++) {
|
||||
if (System.currentTimeMillis() > deadline) {
|
||||
log.warn("[user-secret][proxy-plan] 余量巡检超出时间预算,已处理 {}/{} 户,剩余顺延下一轮",
|
||||
i, plans.size());
|
||||
break;
|
||||
}
|
||||
UserProxyPlanEntity plan = plans.get(i);
|
||||
UserApiSecretBalanceVo balance = jikipProxyClient.fetchBalance(
|
||||
new JikipProxyClient.PlanRef(plan.getPlanId(), plan.getJikipUserId()));
|
||||
if (!Boolean.TRUE.equals(balance.getAvailable())) {
|
||||
failed++;
|
||||
continue;
|
||||
}
|
||||
checked++;
|
||||
if (notifyProxyPlanLow(plan, balance)) {
|
||||
warned++;
|
||||
}
|
||||
}
|
||||
return new ProxyBalanceCheckSummary(plans.size(), checked, warned, failed);
|
||||
}
|
||||
|
||||
private boolean notifyProxyPlanLow(UserProxyPlanEntity plan, UserApiSecretBalanceVo balance) {
|
||||
String reason = proxyPlanLowReason(balance);
|
||||
if (reason == null) {
|
||||
return false;
|
||||
}
|
||||
String day = LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE);
|
||||
boolean pushed = notificationDispatchService.pushToUser(plan.getUserId(),
|
||||
NotificationService.SCENE_SECRET_BALANCE, NotificationService.LEVEL_WARNING,
|
||||
"代理套餐余量不足",
|
||||
"您的 jikip 套餐(套餐 ID " + plan.getPlanId() + ")" + reason
|
||||
+ ",耗尽后相关任务将无法购买代理,请尽快充值。",
|
||||
"proxy_plan_low:" + plan.getUserId() + ":" + day);
|
||||
log.warn("[user-secret][proxy-plan] 余量不足 userId={} planId={} {} pushed={}",
|
||||
plan.getUserId(), plan.getPlanId(), reason, pushed);
|
||||
return pushed;
|
||||
}
|
||||
|
||||
private String proxyPlanLowReason(UserApiSecretBalanceVo balance) {
|
||||
Long surplus = firstNumber(balance.getSurplus());
|
||||
long surplusThreshold = userSecretProperties.getProxyBalanceLowSurplusThreshold();
|
||||
if (surplus != null && surplus <= 0) {
|
||||
return "套餐 IP 余量已耗尽";
|
||||
}
|
||||
if (surplusThreshold > 0 && surplus != null && surplus <= surplusThreshold) {
|
||||
return "套餐剩余 IP 余量仅 " + surplus + "(预警阈值 " + surplusThreshold + ")";
|
||||
}
|
||||
Long amount = firstNumber(balance.getBalance());
|
||||
long balanceThreshold = userSecretProperties.getProxyBalanceLowBalanceThreshold();
|
||||
// 余额耗尽必须报,即使管理员把预警阈值配成 0(默认关闭):这正是用户说的「欠费了要一直警告」
|
||||
if (amount != null && amount <= 0) {
|
||||
return "账户余额已耗尽";
|
||||
}
|
||||
if (balanceThreshold > 0 && amount != null && amount <= balanceThreshold) {
|
||||
return "账户余额仅 " + amount + "(预警阈值 " + balanceThreshold + ")";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 供应商字段可能是 "123" 或 "123次":取首个整数;非数字返回 null(不误报)。 */
|
||||
private static Long firstNumber(String raw) {
|
||||
if (raw == null) {
|
||||
return null;
|
||||
}
|
||||
java.util.regex.Matcher matcher = java.util.regex.Pattern.compile("\\d+").matcher(raw);
|
||||
if (!matcher.find()) {
|
||||
return null;
|
||||
}
|
||||
String digits = matcher.group();
|
||||
return digits.length() <= 18 ? Long.parseLong(digits) : null;
|
||||
}
|
||||
|
||||
/** 用户级余量巡检摘要。 */
|
||||
public record ProxyBalanceCheckSummary(int users, int checked, int warned, int failed) {
|
||||
}
|
||||
|
||||
private record CachedProxyBalance(UserApiSecretBalanceVo balance, long cachedAt) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 后台分页:一行一用户,聚合货源查询密钥/外观专利密钥/代理设置三个字段列,并计算行级状态。
|
||||
* 先按关键字圈定用户,再全量聚合、行级状态筛选、按最近更新时间倒序后内存分页
|
||||
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
package com.nanri.aiimage.modules.usersecret.service;
|
||||
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.config.UserSecretProperties;
|
||||
import com.nanri.aiimage.modules.notification.service.NotificationDispatchService;
|
||||
import com.nanri.aiimage.modules.notification.service.NotificationService;
|
||||
import com.nanri.aiimage.modules.usersecret.client.JikipProxyClient;
|
||||
import com.nanri.aiimage.modules.usersecret.model.entity.UserProxyPlanEntity;
|
||||
import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretBalanceVo;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* 用户级 jikip 余量:客户端展示、5 分钟缓存、跟随密钥巡检的批量检查与低余量通知。
|
||||
* 单独成类是因为 UserApiSecretService 已接近可读性棘轮上限,且这一块与密钥存取无耦合。
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class UserProxyBalanceService {
|
||||
|
||||
/** 客户端右上角余量警告会周期性拉取;同一用户 5 分钟内复用结果,避免每个客户端轮询都打供应商。 */
|
||||
private static final long CACHE_MILLIS = 5 * 60 * 1000L;
|
||||
|
||||
/** key=userId;改/清套餐配置时主动失效。 */
|
||||
private final Map<Long, CachedProxyBalance> cache = new ConcurrentHashMap<>();
|
||||
|
||||
private final UserProxyPlanService userProxyPlanService;
|
||||
private final JikipProxyClient jikipProxyClient;
|
||||
private final NotificationDispatchService notificationDispatchService;
|
||||
private final UserSecretProperties userSecretProperties;
|
||||
|
||||
/** 客户端设置弹窗展示:用户填了自己的套餐 ID/用户 ID 时查自己的,否则查平台套餐。 */
|
||||
public UserApiSecretBalanceVo balance(Long userId) {
|
||||
requireUserId(userId);
|
||||
long now = System.currentTimeMillis();
|
||||
CachedProxyBalance cached = cache.get(userId);
|
||||
if (cached != null && now - cached.cachedAt() < CACHE_MILLIS) {
|
||||
return cached.balance();
|
||||
}
|
||||
UserProxyPlanEntity plan = userProxyPlanService.getEntity(userId);
|
||||
UserApiSecretBalanceVo vo;
|
||||
if (plan != null) {
|
||||
vo = jikipProxyClient.fetchBalance(
|
||||
new JikipProxyClient.PlanRef(plan.getPlanId(), plan.getJikipUserId()));
|
||||
vo.setScope("user");
|
||||
String reason = Boolean.TRUE.equals(vo.getAvailable()) ? lowReason(vo) : null;
|
||||
vo.setLow(reason != null);
|
||||
vo.setLowReason(reason);
|
||||
} else {
|
||||
vo = jikipProxyClient.fetchBalance();
|
||||
vo.setScope("platform");
|
||||
vo.setLow(false);
|
||||
}
|
||||
cache.put(userId, new CachedProxyBalance(vo, now));
|
||||
return vo;
|
||||
}
|
||||
|
||||
/** 用户改了套餐配置后清缓存,下一次查询立即按新配置走。 */
|
||||
public void invalidate(Long userId) {
|
||||
if (userId != null) {
|
||||
cache.remove(userId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户级 jikip 余量巡检:跟随密钥巡检一起跑;find-balance 免费,单条失败只记日志不中断。
|
||||
* 低于阈值时推该用户站内通知(每人每天一条),与平台套餐的管理员告警互不影响。
|
||||
*/
|
||||
public Summary checkAll(int maxRows, int budgetMinutes) {
|
||||
if (!userSecretProperties.isNotifyEnabled()) {
|
||||
log.info("[user-secret][proxy-plan] 站内通知已关闭,余量巡检跳过");
|
||||
return new Summary(0, 0, 0, 0);
|
||||
}
|
||||
List<UserProxyPlanEntity> plans = userProxyPlanService.listAll(maxRows);
|
||||
long deadline = System.currentTimeMillis() + Math.max(1, budgetMinutes) * 60_000L;
|
||||
int checked = 0;
|
||||
int warned = 0;
|
||||
int failed = 0;
|
||||
for (int i = 0; i < plans.size(); i++) {
|
||||
if (System.currentTimeMillis() > deadline) {
|
||||
log.warn("[user-secret][proxy-plan] 余量巡检超出时间预算,已处理 {}/{} 户,剩余顺延下一轮",
|
||||
i, plans.size());
|
||||
break;
|
||||
}
|
||||
UserProxyPlanEntity plan = plans.get(i);
|
||||
UserApiSecretBalanceVo balance = jikipProxyClient.fetchBalance(
|
||||
new JikipProxyClient.PlanRef(plan.getPlanId(), plan.getJikipUserId()));
|
||||
if (!Boolean.TRUE.equals(balance.getAvailable())) {
|
||||
failed++;
|
||||
continue;
|
||||
}
|
||||
checked++;
|
||||
if (notifyLow(plan, balance)) {
|
||||
warned++;
|
||||
}
|
||||
}
|
||||
return new Summary(plans.size(), checked, warned, failed);
|
||||
}
|
||||
|
||||
private boolean notifyLow(UserProxyPlanEntity plan, UserApiSecretBalanceVo balance) {
|
||||
String reason = lowReason(balance);
|
||||
if (reason == null) {
|
||||
return false;
|
||||
}
|
||||
String day = LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE);
|
||||
boolean pushed = notificationDispatchService.pushToUser(plan.getUserId(),
|
||||
NotificationService.SCENE_SECRET_BALANCE, NotificationService.LEVEL_WARNING,
|
||||
"代理套餐余量不足",
|
||||
"您的 jikip 套餐(套餐 ID " + plan.getPlanId() + ")" + reason
|
||||
+ ",耗尽后相关任务将无法购买代理,请尽快充值。",
|
||||
"proxy_plan_low:" + plan.getUserId() + ":" + day);
|
||||
log.warn("[user-secret][proxy-plan] 余量不足 userId={} planId={} {} pushed={}",
|
||||
plan.getUserId(), plan.getPlanId(), reason, pushed);
|
||||
return pushed;
|
||||
}
|
||||
|
||||
private String lowReason(UserApiSecretBalanceVo balance) {
|
||||
Long surplus = firstNumber(balance.getSurplus());
|
||||
long surplusThreshold = userSecretProperties.getProxyBalanceLowSurplusThreshold();
|
||||
if (surplus != null && surplus <= 0) {
|
||||
return "套餐 IP 余量已耗尽";
|
||||
}
|
||||
if (surplusThreshold > 0 && surplus != null && surplus <= surplusThreshold) {
|
||||
return "套餐剩余 IP 余量仅 " + surplus + "(预警阈值 " + surplusThreshold + ")";
|
||||
}
|
||||
Long amount = firstNumber(balance.getBalance());
|
||||
long balanceThreshold = userSecretProperties.getProxyBalanceLowBalanceThreshold();
|
||||
// 余额耗尽必须报,即使管理员把预警阈值配成 0(默认关闭):这正是用户说的「欠费了要一直警告」
|
||||
if (amount != null && amount <= 0) {
|
||||
return "账户余额已耗尽";
|
||||
}
|
||||
if (balanceThreshold > 0 && amount != null && amount <= balanceThreshold) {
|
||||
return "账户余额仅 " + amount + "(预警阈值 " + balanceThreshold + ")";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 供应商字段可能是 "123" 或 "123次":取首个整数;非数字返回 null(不误报)。 */
|
||||
private static Long firstNumber(String raw) {
|
||||
if (raw == null) {
|
||||
return null;
|
||||
}
|
||||
java.util.regex.Matcher matcher = java.util.regex.Pattern.compile("\\d+").matcher(raw);
|
||||
if (!matcher.find()) {
|
||||
return null;
|
||||
}
|
||||
String digits = matcher.group();
|
||||
return digits.length() <= 18 ? Long.parseLong(digits) : null;
|
||||
}
|
||||
|
||||
private void requireUserId(Long userId) {
|
||||
if (userId == null || userId <= 0) {
|
||||
throw new BusinessException("用户 ID 不合法");
|
||||
}
|
||||
}
|
||||
|
||||
/** 用户级余量巡检摘要。 */
|
||||
public record Summary(int users, int checked, int warned, int failed) {
|
||||
}
|
||||
|
||||
private record CachedProxyBalance(UserApiSecretBalanceVo balance, long cachedAt) {
|
||||
}
|
||||
}
|
||||
+23
-18
@@ -97,7 +97,7 @@ class UserApiSecretServiceTest {
|
||||
valueOps = mockValueOps();
|
||||
when(stringRedisTemplate.opsForValue()).thenReturn(valueOps);
|
||||
return new UserApiSecretService(
|
||||
mapper, userProxyPlanService, crypto, checkService, jikipProxyClient, adminUserMapper, adminAuthSupport,
|
||||
mapper, crypto, checkService, adminUserMapper, adminAuthSupport,
|
||||
adminGroupMapper, userDataScopeSupport, notificationDispatchService, userSecretProperties,
|
||||
stringRedisTemplate, objectMapper);
|
||||
}
|
||||
@@ -1103,13 +1103,13 @@ class UserApiSecretServiceTest {
|
||||
/** 用户填了自己的套餐后,余量必须查自己的 planId/userId,不能回落到平台套餐。 */
|
||||
@Test
|
||||
void proxyBalanceUsesUserPlanAndFlagsLowSurplus() {
|
||||
UserApiSecretService service = newService();
|
||||
UserProxyBalanceService service = newBalanceService();
|
||||
UserProxyPlanEntity plan = proxyPlan(7L, "20261010593613392231", "626710989815");
|
||||
when(userProxyPlanService.getEntity(7L)).thenReturn(plan);
|
||||
JikipProxyClient.PlanRef ref = new JikipProxyClient.PlanRef(plan.getPlanId(), plan.getJikipUserId());
|
||||
when(jikipProxyClient.fetchBalance(ref)).thenReturn(proxyBalance("80", "10"));
|
||||
|
||||
UserApiSecretBalanceVo result = service.proxyBalance(7L);
|
||||
UserApiSecretBalanceVo result = service.balance(7L);
|
||||
|
||||
assertThat(result.getScope()).isEqualTo("user");
|
||||
assertThat(result.getLow()).isTrue();
|
||||
@@ -1120,11 +1120,11 @@ class UserApiSecretServiceTest {
|
||||
/** 没配套餐的用户看平台余量,但不参与用户级报警(平台告警归管理员巡检)。 */
|
||||
@Test
|
||||
void proxyBalanceFallsBackToPlatformWithoutUserPlan() {
|
||||
UserApiSecretService service = newService();
|
||||
UserProxyBalanceService service = newBalanceService();
|
||||
when(userProxyPlanService.getEntity(7L)).thenReturn(null);
|
||||
when(jikipProxyClient.fetchBalance()).thenReturn(proxyBalance("5000", "500"));
|
||||
|
||||
UserApiSecretBalanceVo result = service.proxyBalance(7L);
|
||||
UserApiSecretBalanceVo result = service.balance(7L);
|
||||
|
||||
assertThat(result.getScope()).isEqualTo("platform");
|
||||
assertThat(result.getLow()).isFalse();
|
||||
@@ -1134,14 +1134,14 @@ class UserApiSecretServiceTest {
|
||||
/** 余额耗尽必须报警,哪怕管理员把余额预警阈值配成 0(默认关闭)——「欠费了要一直警告」是需求原话。 */
|
||||
@Test
|
||||
void proxyBalanceFlagsExhaustedBalanceEvenWhenThresholdDisabled() {
|
||||
UserApiSecretService service = newService();
|
||||
UserProxyBalanceService service = newBalanceService();
|
||||
userSecretProperties.setProxyBalanceLowBalanceThreshold(0);
|
||||
UserProxyPlanEntity plan = proxyPlan(7L, "p-1", "u-1");
|
||||
when(userProxyPlanService.getEntity(7L)).thenReturn(plan);
|
||||
when(jikipProxyClient.fetchBalance(new JikipProxyClient.PlanRef("p-1", "u-1")))
|
||||
.thenReturn(proxyBalance(null, "0"));
|
||||
|
||||
UserApiSecretBalanceVo result = service.proxyBalance(7L);
|
||||
UserApiSecretBalanceVo result = service.balance(7L);
|
||||
|
||||
assertThat(result.getLow()).isTrue();
|
||||
assertThat(result.getLowReason()).contains("已耗尽");
|
||||
@@ -1150,29 +1150,29 @@ class UserApiSecretServiceTest {
|
||||
/** 客户端会周期性轮询:5 分钟内复用缓存;改/清套餐后主动失效,下一次立即按新配置查。 */
|
||||
@Test
|
||||
void proxyBalanceCachesPerUserAndInvalidatesOnPlanChange() {
|
||||
UserApiSecretService service = newService();
|
||||
UserProxyBalanceService service = newBalanceService();
|
||||
UserProxyPlanEntity plan = proxyPlan(7L, "p-1", "u-1");
|
||||
when(userProxyPlanService.getEntity(7L)).thenReturn(plan);
|
||||
JikipProxyClient.PlanRef ref = new JikipProxyClient.PlanRef("p-1", "u-1");
|
||||
when(jikipProxyClient.fetchBalance(ref)).thenReturn(proxyBalance("5000", "500"));
|
||||
|
||||
service.proxyBalance(7L);
|
||||
service.proxyBalance(7L);
|
||||
service.balance(7L);
|
||||
service.balance(7L);
|
||||
verify(jikipProxyClient, times(1)).fetchBalance(ref);
|
||||
|
||||
service.invalidateProxyBalance(7L);
|
||||
service.proxyBalance(7L);
|
||||
service.invalidate(7L);
|
||||
service.balance(7L);
|
||||
verify(jikipProxyClient, times(2)).fetchBalance(ref);
|
||||
}
|
||||
|
||||
/** 站内通知总开关关闭时连查都不查:余量巡检的唯一产出就是通知,查了也没处送。 */
|
||||
@Test
|
||||
void scheduledProxyBalanceSkipsWhenNotificationsDisabled() {
|
||||
UserApiSecretService service = newService();
|
||||
UserProxyBalanceService service = newBalanceService();
|
||||
userSecretProperties.setNotifyEnabled(false);
|
||||
|
||||
UserApiSecretService.ProxyBalanceCheckSummary summary =
|
||||
service.checkUserProxyBalancesForScheduler(2000, 10);
|
||||
UserProxyBalanceService.Summary summary =
|
||||
service.checkAll(2000, 10);
|
||||
|
||||
assertThat(summary.users()).isZero();
|
||||
assertThat(summary.checked()).isZero();
|
||||
@@ -1182,7 +1182,7 @@ class UserApiSecretServiceTest {
|
||||
/** 巡检按用户逐个查:只给低余量用户推通知,正常用户不打扰,去重键按用户+自然日。 */
|
||||
@Test
|
||||
void scheduledProxyBalanceNotifiesOnlyLowUsers() {
|
||||
UserApiSecretService service = newService();
|
||||
UserProxyBalanceService service = newBalanceService();
|
||||
when(userProxyPlanService.listAll(2000)).thenReturn(List.of(
|
||||
proxyPlan(7L, "p-low", "u-low"), proxyPlan(8L, "p-ok", "u-ok")));
|
||||
when(jikipProxyClient.fetchBalance(new JikipProxyClient.PlanRef("p-low", "u-low")))
|
||||
@@ -1192,8 +1192,8 @@ class UserApiSecretServiceTest {
|
||||
when(notificationDispatchService.pushToUser(anyLong(), anyString(), anyString(), anyString(),
|
||||
anyString(), anyString())).thenReturn(true);
|
||||
|
||||
UserApiSecretService.ProxyBalanceCheckSummary summary =
|
||||
service.checkUserProxyBalancesForScheduler(2000, 10);
|
||||
UserProxyBalanceService.Summary summary =
|
||||
service.checkAll(2000, 10);
|
||||
|
||||
assertThat(summary.users()).isEqualTo(2);
|
||||
assertThat(summary.checked()).isEqualTo(2);
|
||||
@@ -1207,6 +1207,11 @@ class UserApiSecretServiceTest {
|
||||
anyString(), anyString(), anyString());
|
||||
}
|
||||
|
||||
private UserProxyBalanceService newBalanceService() {
|
||||
return new UserProxyBalanceService(userProxyPlanService, jikipProxyClient,
|
||||
notificationDispatchService, userSecretProperties);
|
||||
}
|
||||
|
||||
private UserProxyPlanEntity proxyPlan(long userId, String planId, String jikipUserId) {
|
||||
UserProxyPlanEntity plan = new UserProxyPlanEntity();
|
||||
plan.setUserId(userId);
|
||||
|
||||
Reference in New Issue
Block a user