diff --git a/backend-java/src/main/java/com/nanri/aiimage/config/NotificationProperties.java b/backend-java/src/main/java/com/nanri/aiimage/config/NotificationProperties.java
index f2ec398bd..acbd2e730 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/config/NotificationProperties.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/config/NotificationProperties.java
@@ -41,6 +41,17 @@ public class NotificationProperties {
/** jikip 代理接口探测开关(复用余额查询接口判活,使用 user-secret 的 jikip 配置)。 */
private boolean jikipProbeEnabled = true;
+ /**
+ * jikip 套餐余量预警阈值(剩余 IP 数):surplus ≤ 阈值即推管理员通知,0=关闭。
+ *
+ *
此前探测只判「余额接口还能不能访问」,surplus 只剩个位数也照样记正常,
+ * 平台自费代理欠费停服只能等任务大面积失败后由麦象扫描事后发现。
+ */
+ private long jikipLowSurplusThreshold = 100;
+
+ /** jikip 账户余额预警阈值(供应商返回口径):balance ≤ 阈值即推管理员通知,0=关闭。 */
+ private long jikipLowBalanceThreshold = 0;
+
/** 麦象(18960 任务调度)异常扫描开关:任务停滞/失败/队列积压 → 管理员通知。 */
private boolean maixiangScanEnabled = true;
diff --git a/backend-java/src/main/java/com/nanri/aiimage/config/UserSecretProperties.java b/backend-java/src/main/java/com/nanri/aiimage/config/UserSecretProperties.java
index 46ce1aaef..7141da154 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/config/UserSecretProperties.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/config/UserSecretProperties.java
@@ -41,11 +41,23 @@ public class UserSecretProperties {
/** jikip 余量查询接口(客户端设置弹窗展示套餐 IP 余量 / 账户余额)。 */
private String jikipBalanceUrl = "https://api.jikip.com/find-balance";
- /** jikip 套餐 id(余量查询参数)。 */
- private String jikipPlanId = "";
+ /**
+ * jikip 套餐/账号列表,格式 {@code planId:userId;planId:userId}(分号或逗号分隔)。
+ * 每个套餐独立探测、独立预警;留空=不查余量。
+ */
+ private String jikipPlans = "";
- /** jikip 用户 ID(余量查询参数)。 */
- private String jikipUserId = "";
+ /** 用户级 jikip 余量巡检:跟随密钥巡检一起跑,单轮最多检查的用户数。 */
+ private int proxyBalanceCheckMaxRows = 2000;
+
+ /** 用户级 jikip 余量巡检单轮时间预算(分钟)。 */
+ private int proxyBalanceCheckBudgetMinutes = 10;
+
+ /** 用户级套餐 IP 余量预警阈值:≤ 该值通知用户;0=关闭。 */
+ private long proxyBalanceLowSurplusThreshold = 100;
+
+ /** 用户级账户余额预警阈值:≤ 该值通知用户;0=关闭。 */
+ private long proxyBalanceLowBalanceThreshold = 0;
/**
* 巡检发现欠费/密钥失效时是否推送站内通知(桌面端用户 + 后台管理员);
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/notification/service/NotificationScanScheduler.java b/backend-java/src/main/java/com/nanri/aiimage/modules/notification/service/NotificationScanScheduler.java
index 7dc37d27b..f6bbd7077 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/modules/notification/service/NotificationScanScheduler.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/notification/service/NotificationScanScheduler.java
@@ -64,6 +64,9 @@ public class NotificationScanScheduler {
private static final DateTimeFormatter DAY_FORMAT = DateTimeFormatter.ofPattern("yyyyMMdd");
+ /** 「jikip 套餐信息未配置」的日志日期(按天只提示一次,避免每 5 分钟刷一条)。 */
+ private String jikipUnconfiguredWarnDay;
+
/**
* 任务模块类型 → 中文名:直接取模块注册表(G6),新增模块只需在
* {@code TaskModuleRegistry} 追加一行,不再需要同步这份表。
@@ -238,25 +241,102 @@ public class NotificationScanScheduler {
}
}
- /** jikip 探测:复用余额查询接口;未配置套餐信息时跳过(返回 null 不告警)。 */
+ /** jikip 探测:逐套餐复用余额查询接口;未配置任何套餐时跳过(返回 null 不告警)。 */
private ProbeOutcome probeJikip() {
try {
- ProxyBalancePort.ProxyBalanceSnapshot balance = proxyBalancePort.fetchBalance();
- if (balance.available()) {
- return ProbeOutcome.alive("余额接口可用 surplus=" + balance.surplus()
- + " balance=" + balance.balance());
- }
- String message = balance.message() == null ? "" : balance.message();
- if (message.contains("未配置")) {
- log.info("[notification-scan] jikip 探测跳过:{}", message);
+ List entries = proxyBalancePort.fetchBalances();
+ if (entries.isEmpty()) {
+ warnJikipUnconfiguredOncePerDay();
return null;
}
- return ProbeOutcome.down(message.isEmpty() ? "余额接口不可用" : message);
+ List alive = new ArrayList<>();
+ List failures = new ArrayList<>();
+ for (ProxyBalancePort.ProxyBalanceEntry entry : entries) {
+ ProxyBalancePort.ProxyBalanceSnapshot balance = entry.snapshot();
+ String message = balance.message() == null ? "" : balance.message();
+ if (balance.available()) {
+ warnIfLowBalance(entry.planId(), balance);
+ alive.add("套餐" + entry.planId() + " surplus=" + balance.surplus()
+ + " balance=" + balance.balance());
+ continue;
+ }
+ if (!message.contains("未配置")) {
+ failures.add("套餐" + entry.planId() + ":"
+ + (message.isEmpty() ? "余额接口不可用" : message));
+ }
+ }
+ if (!alive.isEmpty()) {
+ if (!failures.isEmpty()) {
+ log.warn("[notification-scan] jikip 部分套餐余量查询失败: {}",
+ String.join(";", failures));
+ }
+ return ProbeOutcome.alive(String.join(";", alive));
+ }
+ if (failures.isEmpty()) {
+ warnJikipUnconfiguredOncePerDay();
+ return null;
+ }
+ return ProbeOutcome.down(String.join(";", failures));
} catch (Exception ex) {
return ProbeOutcome.down(rootCauseMessage(ex));
}
}
+ /**
+ * 余额/套餐余量低于阈值时推管理员预警——这是「欠费导致代理全盘停摆」唯一的事前信号。
+ * 每个套餐独立判定、独立去重:一个套餐见底不影响另一个套餐的判定。
+ */
+ void warnIfLowBalance(String planId, ProxyBalancePort.ProxyBalanceSnapshot balance) {
+ warnBelowThreshold(planId, balance.surplus(), properties.getJikipLowSurplusThreshold(),
+ "jikip 代理套餐余量不足", "套餐剩余 IP 余量", "jikip_low_surplus");
+ warnBelowThreshold(planId, balance.balance(), properties.getJikipLowBalanceThreshold(),
+ "jikip 代理账户余额不足", "账户余额", "jikip_low_balance");
+ }
+
+ private void warnBelowThreshold(String planId, String raw, long threshold, String title,
+ String label, String dedupePrefix) {
+ if (threshold <= 0) {
+ return;
+ }
+ Long value = firstNumber(raw);
+ if (value == null || value > threshold) {
+ return;
+ }
+ log.warn("[notification-scan] jikip 预警 planId={} {}={} 阈值={},耗尽后平台自费代理将停摆",
+ planId, label, value, threshold);
+ notificationDispatchService.pushToAdmins(NotificationService.SCENE_SERVICE_DOWN,
+ NotificationService.LEVEL_WARNING, title,
+ "套餐 " + planId + " 的" + label + "仅剩 " + value + "(预警阈值 " + threshold
+ + ")。耗尽后平台自费代理会全盘停摆,请立即续费或补一把独立账号的钥匙。",
+ dedupePrefix + ":" + planId + ":" + dayOf(LocalDateTime.now()), null);
+ }
+
+ /** 供应商字段可能是 "123" 或 "123次":取首个整数;纯文本(如"充足")返回 null。 */
+ 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();
+ // 18 位以内必在 long 范围内;再长说明不是余量数字(不抛异常,静默 catch 会涨棘轮)
+ return digits.length() <= 18 ? Long.parseLong(digits) : null;
+ }
+
+ /** 套餐信息未配置 = 余量预警根本没生效:日志按天提示一次,别让「静默跳过」看起来像没事。 */
+ private void warnJikipUnconfiguredOncePerDay() {
+ String today = dayOf(LocalDateTime.now());
+ if (today.equals(jikipUnconfiguredWarnDay)) {
+ return;
+ }
+ jikipUnconfiguredWarnDay = today;
+ log.warn("[notification-scan] jikip 余量预警未启用:未配置代理套餐信息"
+ + "(格式 planId:userId;planId:userId,多个套餐用分号分隔;"
+ + "未配置时只能在任务停滞事后发现)");
+ }
+
/** 探测结果上报:正常记 info;故障按自然日去重推管理员通知;outcome=null 表示跳过。 */
private void reportProbe(String serviceKey, String serviceLabel, ProbeOutcome outcome) {
if (outcome == null) {
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/notification/spi/ProxyBalancePort.java b/backend-java/src/main/java/com/nanri/aiimage/modules/notification/spi/ProxyBalancePort.java
index bb25741c0..18b3b8b4d 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/modules/notification/spi/ProxyBalancePort.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/notification/spi/ProxyBalancePort.java
@@ -1,5 +1,7 @@
package com.nanri.aiimage.modules.notification.spi;
+import java.util.List;
+
/**
* 代理余额探测(2026-09 边界收敛:notification → usersecret 的类依赖改为端口)。
*
@@ -9,11 +11,15 @@ package com.nanri.aiimage.modules.notification.spi;
public interface ProxyBalancePort {
/**
- * 查询代理服务商余额。
+ * 逐套餐查询代理服务商余额;未配置任何套餐时返回空列表。
*
- * @return 余额快照;调用异常由实现方抛出(调用方负责降级)
+ * @return 每个套餐一条快照;单条失败由实现方降级成 {@code available=false},不中断其余套餐
*/
- ProxyBalanceSnapshot fetchBalance();
+ List fetchBalances();
+
+ /** 套餐 id + 该套餐的余额快照。 */
+ record ProxyBalanceEntry(String planId, ProxyBalanceSnapshot snapshot) {
+ }
/**
* @param available 余额接口是否可用
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/client/JikipProxyClient.java b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/client/JikipProxyClient.java
index e00cdb16c..df4c0768f 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/client/JikipProxyClient.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/client/JikipProxyClient.java
@@ -13,6 +13,9 @@ import org.springframework.web.client.RestClient;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -108,22 +111,86 @@ public class JikipProxyClient {
}
}
- /** 余量查询:GET {balanceUrl}?id={planId}&userId={userId},返回 surplus/balance。 */
+ /** 余量查询(客户端单套餐展示):多套餐时取余量最小的可用套餐,全失败时返回第一条失败。 */
public UserApiSecretBalanceVo fetchBalance() {
- UserApiSecretBalanceVo vo = new UserApiSecretBalanceVo();
- String balanceUrl = normalize(properties.getJikipBalanceUrl());
- String planId = normalize(properties.getJikipPlanId());
- String userId = normalize(properties.getJikipUserId());
- if (balanceUrl.isBlank() || planId.isBlank() || userId.isBlank()) {
- log.info("[user-secret][proxy] 余量查询跳过:jikip 套餐信息未配置");
+ List balances = fetchBalances();
+ if (balances.isEmpty()) {
+ UserApiSecretBalanceVo vo = new UserApiSecretBalanceVo();
vo.setAvailable(false);
vo.setMessage("未配置代理套餐信息");
return vo;
}
+ return balances.stream()
+ .map(PlanBalance::balance)
+ .filter(item -> Boolean.TRUE.equals(item.getAvailable()))
+ .min(Comparator.comparingLong(item -> surplusRank(item.getSurplus())))
+ .orElseGet(() -> balances.get(0).balance());
+ }
+
+ /** 单个套餐的余量查询(用户级配置用):失败降级为 available=false,不抛异常。 */
+ public UserApiSecretBalanceVo fetchBalance(PlanRef plan) {
+ String balanceUrl = normalize(properties.getJikipBalanceUrl());
+ if (plan == null || balanceUrl.isBlank()) {
+ UserApiSecretBalanceVo vo = new UserApiSecretBalanceVo();
+ vo.setAvailable(false);
+ vo.setMessage("未配置代理套餐信息");
+ return vo;
+ }
+ return fetchOneBalance(balanceUrl, plan);
+ }
+
+ /**
+ * 逐套餐查询余量:每个 {@code planId:userId} 独立发一次请求,单个失败不影响其余套餐。
+ * 未配置任何套餐时返回空列表,由调用方区分「未配置」与「全部失败」。
+ */
+ public List fetchBalances() {
+ String balanceUrl = normalize(properties.getJikipBalanceUrl());
+ List plans = parsePlans(properties.getJikipPlans());
+ if (balanceUrl.isBlank() || plans.isEmpty()) {
+ log.info("[user-secret][proxy] 余量查询跳过:jikip 套餐信息未配置");
+ return List.of();
+ }
+ List out = new ArrayList<>(plans.size());
+ for (PlanRef plan : plans) {
+ out.add(new PlanBalance(plan, fetchOneBalance(balanceUrl, plan)));
+ }
+ return out;
+ }
+
+ /** 解析 {@code planId:userId;planId:userId};格式不对的条目忽略并 WARN,不拖垮整表。 */
+ static List parsePlans(String raw) {
+ List plans = new ArrayList<>();
+ String text = normalize(raw);
+ if (text.isEmpty()) {
+ return plans;
+ }
+ for (String token : text.split("[;,]")) {
+ String item = token.trim();
+ if (item.isEmpty()) {
+ continue;
+ }
+ int separator = item.indexOf(':');
+ if (separator <= 0 || separator >= item.length() - 1) {
+ log.warn("[user-secret][proxy] jikip 套餐配置项应为 planId:userId,已忽略:{}", item);
+ continue;
+ }
+ String planId = item.substring(0, separator).trim();
+ String userId = item.substring(separator + 1).trim();
+ if (planId.isEmpty() || userId.isEmpty()) {
+ log.warn("[user-secret][proxy] jikip 套餐配置项 planId/userId 为空,已忽略:{}", item);
+ continue;
+ }
+ plans.add(new PlanRef(planId, userId));
+ }
+ return plans;
+ }
+
+ private UserApiSecretBalanceVo fetchOneBalance(String balanceUrl, PlanRef plan) {
+ UserApiSecretBalanceVo vo = new UserApiSecretBalanceVo();
try {
String separator = balanceUrl.contains("?") ? "&" : "?";
String url = balanceUrl + separator
- + "id=" + encode(planId) + "&userId=" + encode(userId);
+ + "id=" + encode(plan.planId()) + "&userId=" + encode(plan.userId());
String body = restClient(BALANCE_READ_TIMEOUT_MILLIS).get()
.uri(url)
.retrieve()
@@ -134,15 +201,35 @@ public class JikipProxyClient {
vo.setSurplus(text(source.get("surplus")));
vo.setBalance(text(source.get("balance")));
vo.setAvailable(true);
- log.info("[user-secret][proxy] 余量查询成功 surplus={} balance={}", vo.getSurplus(), vo.getBalance());
+ log.debug("[user-secret][proxy] 余量查询成功 planId={} surplus={} balance={}",
+ plan.planId(), vo.getSurplus(), vo.getBalance());
} catch (Exception ex) {
- log.warn("[user-secret][proxy] 余量查询失败 err={}", ex.getMessage());
+ log.warn("[user-secret][proxy] 余量查询失败 planId={} err={}", plan.planId(), ex.getMessage());
vo.setAvailable(false);
vo.setMessage(UserMessages.with("余量查询失败", ex));
}
return vo;
}
+ /** 余量排序口径:解析不出数字时排在最后,避免非数字串抢占「最小余量」。 */
+ private static long surplusRank(String raw) {
+ String text = normalize(raw);
+ Matcher matcher = Pattern.compile("\\d+").matcher(text);
+ if (!matcher.find()) {
+ return Long.MAX_VALUE;
+ }
+ String digits = matcher.group();
+ return digits.length() <= 18 ? Long.parseLong(digits) : Long.MAX_VALUE;
+ }
+
+ /** 套餐/账号配置项。 */
+ public record PlanRef(String planId, String userId) {
+ }
+
+ /** 单个套餐的余量结果。 */
+ public record PlanBalance(PlanRef plan, UserApiSecretBalanceVo balance) {
+ }
+
/** 解析提取接口响应:JSON 中的 ip/port 字段优先,否则正则匹配任意位置的 ip:port。 */
private String parseProxyUrl(String body) {
String text = normalize(body);
@@ -236,7 +323,7 @@ public class JikipProxyClient {
return normalized.substring(0, maxLength) + "...";
}
- private String normalize(String value) {
+ private static String normalize(String value) {
return value == null ? "" : value.trim();
}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/controller/UserApiSecretController.java b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/controller/UserApiSecretController.java
index 92d802915..57bb296af 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/controller/UserApiSecretController.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/controller/UserApiSecretController.java
@@ -6,11 +6,14 @@ import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.modules.usersecret.model.dto.UserApiSecretCheckRequest;
import com.nanri.aiimage.modules.usersecret.model.dto.UserApiSecretMigrateRequest;
import com.nanri.aiimage.modules.usersecret.model.dto.UserApiSecretSaveRequest;
+import com.nanri.aiimage.modules.usersecret.model.dto.UserProxyPlanSaveRequest;
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;
+import com.nanri.aiimage.modules.usersecret.model.vo.UserProxyPlanVo;
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
+import com.nanri.aiimage.modules.usersecret.service.UserProxyPlanService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
@@ -39,6 +42,7 @@ import java.util.Map;
public class UserApiSecretController {
private final UserApiSecretService userApiSecretService;
+ private final UserProxyPlanService userProxyPlanService;
private final AdminAuthSupport adminAuthSupport;
@GetMapping
@@ -93,10 +97,37 @@ public class UserApiSecretController {
}
@GetMapping("/proxy-balance")
- @Operation(summary = "查询代理套餐余量", description = "转发 jikip find-balance,返回套餐 IP 余量与账户余额。")
+ @Operation(summary = "查询代理套餐余量", description = "转发 jikip find-balance;当前用户填了自己的套餐 ID/用户 ID 时查自己的,否则查平台套餐。")
public ApiResponse proxyBalance(HttpServletRequest request) {
- currentUserId(request);
- return ApiResponse.success(userApiSecretService.proxyBalance());
+ Long userId = currentUserId(request);
+ return ApiResponse.success(userApiSecretService.proxyBalance(userId));
+ }
+
+ @GetMapping("/proxy-plan")
+ @Operation(summary = "读取当前用户的 jikip 套餐配置")
+ public ApiResponse proxyPlan(HttpServletRequest request) {
+ return ApiResponse.success(userProxyPlanService.get(currentUserId(request)));
+ }
+
+ @PutMapping("/proxy-plan")
+ @Operation(summary = "保存当前用户的 jikip 套餐配置",
+ description = "套餐 ID / 用户 ID 只用于查询余量,与代理提取链接(key)相互独立。")
+ public ApiResponse saveProxyPlan(
+ HttpServletRequest request,
+ @Valid @RequestBody UserProxyPlanSaveRequest body) {
+ Long userId = currentUserId(request);
+ UserProxyPlanVo vo = userProxyPlanService.save(userId, body.getPlanId(), body.getJikipUserId());
+ userApiSecretService.invalidateProxyBalance(userId);
+ return ApiResponse.success("保存成功", vo);
+ }
+
+ @DeleteMapping("/proxy-plan")
+ @Operation(summary = "清除当前用户的 jikip 套餐配置")
+ public ApiResponse clearProxyPlan(HttpServletRequest request) {
+ Long userId = currentUserId(request);
+ userProxyPlanService.clear(userId);
+ userApiSecretService.invalidateProxyBalance(userId);
+ return ApiResponse.success("已清除", null);
}
private Long currentUserId(HttpServletRequest request) {
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/mapper/UserProxyPlanMapper.java b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/mapper/UserProxyPlanMapper.java
new file mode 100644
index 000000000..1e2c8b28b
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/mapper/UserProxyPlanMapper.java
@@ -0,0 +1,9 @@
+package com.nanri.aiimage.modules.usersecret.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.nanri.aiimage.modules.usersecret.model.entity.UserProxyPlanEntity;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface UserProxyPlanMapper extends BaseMapper {
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/dto/UserProxyPlanSaveRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/dto/UserProxyPlanSaveRequest.java
new file mode 100644
index 000000000..1c7749691
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/dto/UserProxyPlanSaveRequest.java
@@ -0,0 +1,24 @@
+package com.nanri.aiimage.modules.usersecret.model.dto;
+
+import io.swagger.v3.oas.annotations.media.Schema;
+import jakarta.validation.constraints.NotBlank;
+import jakarta.validation.constraints.Pattern;
+import jakarta.validation.constraints.Size;
+import lombok.Data;
+
+@Data
+@Schema(description = "用户级 jikip 套餐配置")
+public class UserProxyPlanSaveRequest {
+
+ @Schema(description = "jikip 套餐 ID", example = "20261010593613392231")
+ @NotBlank(message = "套餐 ID 不能为空")
+ @Size(max = 64, message = "套餐 ID 过长")
+ @Pattern(regexp = "[A-Za-z0-9_-]+", message = "套餐 ID 只能是字母、数字、下划线或短横线")
+ private String planId;
+
+ @Schema(description = "jikip 用户 ID", example = "626710989815")
+ @NotBlank(message = "用户 ID 不能为空")
+ @Size(max = 64, message = "用户 ID 过长")
+ @Pattern(regexp = "[A-Za-z0-9_-]+", message = "用户 ID 只能是字母、数字、下划线或短横线")
+ private String jikipUserId;
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/entity/UserProxyPlanEntity.java b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/entity/UserProxyPlanEntity.java
new file mode 100644
index 000000000..f7799cec4
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/entity/UserProxyPlanEntity.java
@@ -0,0 +1,20 @@
+package com.nanri.aiimage.modules.usersecret.model.entity;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+import lombok.Data;
+
+import java.time.LocalDateTime;
+
+@Data
+@TableName("biz_user_proxy_plan")
+public class UserProxyPlanEntity {
+
+ @TableId(value = "user_id", type = IdType.INPUT)
+ private Long userId;
+ private String planId;
+ private String jikipUserId;
+ private LocalDateTime createdAt;
+ private LocalDateTime updatedAt;
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/vo/UserApiSecretBalanceVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/vo/UserApiSecretBalanceVo.java
index 797b082b1..d0966ee64 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/vo/UserApiSecretBalanceVo.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/vo/UserApiSecretBalanceVo.java
@@ -18,4 +18,13 @@ public class UserApiSecretBalanceVo {
@Schema(description = "失败原因(available=false 时)")
private String message;
+
+ @Schema(description = "余量来源:user=用户自己的套餐;platform=平台套餐")
+ private String scope;
+
+ @Schema(description = "是否低于预警阈值(仅用户自己的套餐判定;用于客户端右上角常驻警告)")
+ private Boolean low;
+
+ @Schema(description = "低余量原因(low=true 时)")
+ private String lowReason;
}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/vo/UserProxyPlanVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/vo/UserProxyPlanVo.java
new file mode 100644
index 000000000..90da20e81
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/model/vo/UserProxyPlanVo.java
@@ -0,0 +1,18 @@
+package com.nanri.aiimage.modules.usersecret.model.vo;
+
+import io.swagger.v3.oas.annotations.media.Schema;
+import lombok.Data;
+
+@Data
+@Schema(description = "用户级 jikip 套餐配置")
+public class UserProxyPlanVo {
+
+ @Schema(description = "jikip 套餐 ID;未配置时为 null")
+ private String planId;
+
+ @Schema(description = "jikip 用户 ID;未配置时为 null")
+ private String jikipUserId;
+
+ @Schema(description = "是否已配置")
+ private Boolean configured;
+}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/service/ProxyBalancePortAdapter.java b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/service/ProxyBalancePortAdapter.java
index b4d9a5117..6b553a0ca 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/service/ProxyBalancePortAdapter.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/service/ProxyBalancePortAdapter.java
@@ -6,6 +6,9 @@ import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretBalanceVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
+import java.util.ArrayList;
+import java.util.List;
+
/**
* 代理余额探测端口实现(2026-09 边界收敛):把 jikip 客户端与余额 VO 收敛在 usersecret 模块内。
*/
@@ -16,15 +19,19 @@ public class ProxyBalancePortAdapter implements ProxyBalancePort {
private final JikipProxyClient jikipProxyClient;
@Override
- public ProxyBalanceSnapshot fetchBalance() {
- UserApiSecretBalanceVo balance = jikipProxyClient.fetchBalance();
- if (balance == null) {
- return new ProxyBalanceSnapshot(false, null, null, "余额接口返回空");
+ public List fetchBalances() {
+ List out = new ArrayList<>();
+ for (JikipProxyClient.PlanBalance planBalance : jikipProxyClient.fetchBalances()) {
+ UserApiSecretBalanceVo balance = planBalance.balance();
+ ProxyBalanceSnapshot snapshot = balance == null
+ ? new ProxyBalanceSnapshot(false, null, null, "余额接口返回空")
+ : new ProxyBalanceSnapshot(
+ Boolean.TRUE.equals(balance.getAvailable()),
+ balance.getSurplus(),
+ balance.getBalance(),
+ balance.getMessage());
+ out.add(new ProxyBalanceEntry(planBalance.plan().planId(), snapshot));
}
- return new ProxyBalanceSnapshot(
- Boolean.TRUE.equals(balance.getAvailable()),
- balance.getSurplus(),
- balance.getBalance(),
- balance.getMessage());
+ return out;
}
}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/service/UserApiSecretCheckScheduler.java b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/service/UserApiSecretCheckScheduler.java
index 524da1ccd..57feaf7b1 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/service/UserApiSecretCheckScheduler.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/service/UserApiSecretCheckScheduler.java
@@ -14,6 +14,7 @@ import java.time.Duration;
* (代理模块每次探测都是真实提取、按次计费,故同一把密钥被多个账号配置时一轮只探测一次;
* 2026-09-14 成本审查后巡检频次由每日降为隔日),双实例经 Redis 分布式锁互斥;
* 单轮受条数与时间预算约束,超出顺延下一轮。
+ * 同一轮还捎带用户级 jikip 套餐余量巡检(find-balance 免费),低余量推该用户站内通知。
*/
@Service
@Slf4j
@@ -21,6 +22,8 @@ import java.time.Duration;
public class UserApiSecretCheckScheduler {
private static final String LOCK_NAME = "user-secret-daily-check";
+ /** 锁的兜底时长下限;实际按两段巡检预算之和加 5 分钟余量,避免后段跑飞时锁提前过期。 */
+ private static final int MIN_LOCK_MINUTES = 30;
private final UserApiSecretService userApiSecretService;
private final DistributedJobLockService distributedJobLockService;
@@ -32,7 +35,9 @@ public class UserApiSecretCheckScheduler {
log.info("[user-secret] 定时巡检已关闭,跳过本轮");
return;
}
- var lock = distributedJobLockService.tryLock(LOCK_NAME, Duration.ofMinutes(30));
+ int lockMinutes = Math.max(MIN_LOCK_MINUTES,
+ properties.getCheckBudgetMinutes() + properties.getProxyBalanceCheckBudgetMinutes() + 5);
+ var lock = distributedJobLockService.tryLock(LOCK_NAME, Duration.ofMinutes(lockMinutes));
if (lock == null) {
log.info("[user-secret] 另一实例持有巡检锁,跳过本轮");
return;
@@ -45,6 +50,12 @@ 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());
+ log.info("[user-secret] 用户代理套餐余量巡检完成 users={} checked={} warned={} failed={}",
+ proxySummary.users(), proxySummary.checked(), proxySummary.warned(), proxySummary.failed());
} catch (Exception ex) {
log.warn("[user-secret] 每日巡检异常终止 err={}", ex.getMessage(), ex);
}
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/service/UserApiSecretService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/service/UserApiSecretService.java
index 736695e41..e1bd491ea 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/service/UserApiSecretService.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/service/UserApiSecretService.java
@@ -21,6 +21,7 @@ import com.nanri.aiimage.modules.usersecret.client.JikipProxyClient;import com.n
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;
@@ -52,6 +53,7 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
/**
* 用户 API 密钥服务端存储:按登录用户绑定、AES 加密落库,
@@ -90,7 +92,14 @@ 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 proxyBalanceCache = new ConcurrentHashMap<>();
+
private final UserApiSecretMapper userApiSecretMapper;
+ private final UserProxyPlanService userProxyPlanService;
private final ShopCredentialCryptoService cryptoService;
private final UserApiSecretCheckService checkService;
private final JikipProxyClient jikipProxyClient;
@@ -306,9 +315,130 @@ public class UserApiSecretService implements UserSecretCleanupPort {
return vo;
}
- /** jikip 代理余量(客户端设置弹窗展示)。 */
- public UserApiSecretBalanceVo proxyBalance() {
- return jikipProxyClient.fetchBalance();
+ /** 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 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) {
}
/**
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/service/UserProxyPlanService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/service/UserProxyPlanService.java
new file mode 100644
index 000000000..1e9f47d31
--- /dev/null
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/usersecret/service/UserProxyPlanService.java
@@ -0,0 +1,72 @@
+package com.nanri.aiimage.modules.usersecret.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.nanri.aiimage.modules.usersecret.mapper.UserProxyPlanMapper;
+import com.nanri.aiimage.modules.usersecret.model.entity.UserProxyPlanEntity;
+import com.nanri.aiimage.modules.usersecret.model.vo.UserProxyPlanVo;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+
+import java.util.List;
+
+/**
+ * 用户级 jikip 套餐配置:一个用户对应一个当前在用的套餐/账号。
+ * 提取链接(key)与套餐 ID/用户 ID 相互独立:链接用于买 IP,这两个 ID 只用于查余量。
+ */
+@Service
+@Slf4j
+@RequiredArgsConstructor
+public class UserProxyPlanService {
+
+ private final UserProxyPlanMapper mapper;
+
+ public UserProxyPlanEntity getEntity(Long userId) {
+ return mapper.selectById(userId);
+ }
+
+ public UserProxyPlanVo get(Long userId) {
+ UserProxyPlanEntity row = mapper.selectById(userId);
+ UserProxyPlanVo vo = new UserProxyPlanVo();
+ if (row != null) {
+ vo.setPlanId(row.getPlanId());
+ vo.setJikipUserId(row.getJikipUserId());
+ }
+ vo.setConfigured(row != null);
+ return vo;
+ }
+
+ public UserProxyPlanVo save(Long userId, String planId, String jikipUserId) {
+ String normalizedPlanId = planId == null ? "" : planId.trim();
+ String normalizedUserId = jikipUserId == null ? "" : jikipUserId.trim();
+ UserProxyPlanEntity existing = mapper.selectById(userId);
+ if (existing == null) {
+ UserProxyPlanEntity row = new UserProxyPlanEntity();
+ row.setUserId(userId);
+ row.setPlanId(normalizedPlanId);
+ row.setJikipUserId(normalizedUserId);
+ mapper.insert(row);
+ log.info("[user-secret][proxy-plan] 已保存 userId={} planId={} jikipUserId={}",
+ userId, normalizedPlanId, normalizedUserId);
+ } else {
+ existing.setPlanId(normalizedPlanId);
+ existing.setJikipUserId(normalizedUserId);
+ mapper.updateById(existing);
+ log.info("[user-secret][proxy-plan] 已更新 userId={} planId={} jikipUserId={}",
+ userId, normalizedPlanId, normalizedUserId);
+ }
+ return get(userId);
+ }
+
+ public void clear(Long userId) {
+ mapper.deleteById(userId);
+ log.info("[user-secret][proxy-plan] 已清除 userId={}", userId);
+ }
+
+ /** 定时巡检用:按用户 ID 升序取一批,超出预算下一轮继续。 */
+ public List listAll(int limit) {
+ return mapper.selectList(new LambdaQueryWrapper()
+ .orderByAsc(UserProxyPlanEntity::getUserId)
+ .last("limit " + Math.max(1, limit)));
+ }
+}
diff --git a/backend-java/src/main/resources/application-local.example.yml b/backend-java/src/main/resources/application-local.example.yml
index fe09691be..e9ed13065 100644
--- a/backend-java/src/main/resources/application-local.example.yml
+++ b/backend-java/src/main/resources/application-local.example.yml
@@ -61,6 +61,21 @@ AIIMAGE_MODULE_CLEANUP_ENABLED=true
AIIMAGE_MODULE_CLEANUP_CRON=0 0 0 * * *
AIIMAGE_MODULE_CLEANUP_MODULE_TYPES=DEDUPE,SPLIT,CONVERT,DELETE_BRAND
+# 平台自费代理(jikip)余量预警:多个套餐用分号分隔,每项 planId:userId
+# 示例:AIIMAGE_USER_SECRET_JIKIP_PLANS=111:222;333:444
+# 留空 = 不查余量(巡检会按天 WARN 提示未启用)
+AIIMAGE_USER_SECRET_JIKIP_PLANS=
+AIIMAGE_NOTIFICATION_JIKIP_PROBE_ENABLED=true
+# 用户级余量巡检(跟随密钥巡检):低于阈值推用户站内通知
+AIIMAGE_USER_SECRET_PROXY_BALANCE_CHECK_MAX_ROWS=2000
+AIIMAGE_USER_SECRET_PROXY_BALANCE_CHECK_BUDGET_MINUTES=10
+AIIMAGE_USER_SECRET_PROXY_LOW_SURPLUS_THRESHOLD=100
+AIIMAGE_USER_SECRET_PROXY_LOW_BALANCE_THRESHOLD=0
+# 套餐剩余 IP 数 ≤ 阈值 → 管理员通知;0=关闭
+AIIMAGE_NOTIFICATION_JIKIP_LOW_SURPLUS_THRESHOLD=100
+# 账户余额 ≤ 阈值 → 管理员通知;供应商口径,0=关闭
+AIIMAGE_NOTIFICATION_JIKIP_LOW_BALANCE_THRESHOLD=0
+
AIIMAGE_APPEARANCE_PATENT_LLM_HOST=https://ai.t8star.org
AIIMAGE_APPEARANCE_PATENT_TITLE_MODEL=gemini-3.1-flash-lite-preview-thinking-medium
AIIMAGE_APPEARANCE_PATENT_APPEARANCE_MODEL=gemini-3.1-flash-lite-preview-thinking-medium
diff --git a/backend-java/src/main/resources/application.yml b/backend-java/src/main/resources/application.yml
index 38db3be85..a02d0144d 100644
--- a/backend-java/src/main/resources/application.yml
+++ b/backend-java/src/main/resources/application.yml
@@ -496,8 +496,13 @@ aiimage:
# 检测出口代理提取链接:留空=直连;配置后检测优先经代理、失败回退直连
check-proxy-extract-url: ${AIIMAGE_USER_SECRET_CHECK_PROXY_EXTRACT_URL:}
jikip-balance-url: ${AIIMAGE_USER_SECRET_JIKIP_BALANCE_URL:https://api.jikip.com/find-balance}
- jikip-plan-id: ${AIIMAGE_USER_SECRET_JIKIP_PLAN_ID:}
- jikip-user-id: ${AIIMAGE_USER_SECRET_JIKIP_USER_ID:}
+ # 多个套餐/账号:planId:userId;planId:userId(分号或逗号分隔);留空=不查余量
+ jikip-plans: ${AIIMAGE_USER_SECRET_JIKIP_PLANS:}
+ # 用户级余量巡检:跟随密钥巡检一起跑(find-balance 免费);低于阈值推该用户站内通知
+ proxy-balance-check-max-rows: ${AIIMAGE_USER_SECRET_PROXY_BALANCE_CHECK_MAX_ROWS:2000}
+ proxy-balance-check-budget-minutes: ${AIIMAGE_USER_SECRET_PROXY_BALANCE_CHECK_BUDGET_MINUTES:10}
+ proxy-balance-low-surplus-threshold: ${AIIMAGE_USER_SECRET_PROXY_LOW_SURPLUS_THRESHOLD:100}
+ proxy-balance-low-balance-threshold: ${AIIMAGE_USER_SECRET_PROXY_LOW_BALANCE_THRESHOLD:0}
# 巡检发现欠费/密钥失效时是否推送站内通知(铃铛)
notify-enabled: ${AIIMAGE_USER_SECRET_NOTIFY_ENABLED:true}
# 用量日统计保留期:取 400 天而非整年,避免跨年时把刚过期的上年数据删掉(含同比对比场景)
@@ -517,6 +522,10 @@ aiimage:
brand-service-url: ${AIIMAGE_NOTIFICATION_BRAND_SERVICE_URL:}
price-track-api-url: ${AIIMAGE_NOTIFICATION_PRICE_TRACK_API_URL:}
jikip-probe-enabled: ${AIIMAGE_NOTIFICATION_JIKIP_PROBE_ENABLED:true}
+ # 平台自费代理事前预警:套餐余量 / 账户余额低于阈值即推管理员通知(0=关闭该项)。
+ # 探测本身依赖 user-secret.jikip-plans,未配置时按天打 WARN 后跳过。
+ jikip-low-surplus-threshold: ${AIIMAGE_NOTIFICATION_JIKIP_LOW_SURPLUS_THRESHOLD:100}
+ jikip-low-balance-threshold: ${AIIMAGE_NOTIFICATION_JIKIP_LOW_BALANCE_THRESHOLD:0}
# 麦象(18960 任务调度)异常扫描:批量/单任务停滞、任务失败、队列积压 → 管理员通知。
# console-token 留空=跳过麦象扫描;接口地址复用上面的 price-track-api-url。
maixiang-scan-enabled: ${AIIMAGE_NOTIFICATION_MAIXIANG_SCAN_ENABLED:true}
diff --git a/backend-java/src/main/resources/db/V160__user_proxy_plan.sql b/backend-java/src/main/resources/db/V160__user_proxy_plan.sql
new file mode 100644
index 000000000..5bd94d28f
--- /dev/null
+++ b/backend-java/src/main/resources/db/V160__user_proxy_plan.sql
@@ -0,0 +1,15 @@
+-- V160: 用户级 jikip 余量配置(客户端代理设置里填写自己的套餐 ID / 用户 ID)
+--
+-- 背景:jikip find-balance 必须带「套餐 id + 用户 id」,光有提取链接里的 key 查不出余额。
+-- 用户各自持有 jikip 账号时,由用户在客户端填写,后端只按当前登录用户读写,不暴露平台账号。
+--
+-- 回滚:DROP TABLE `biz_user_proxy_plan`;
+
+CREATE TABLE IF NOT EXISTS `biz_user_proxy_plan` (
+ `user_id` BIGINT NOT NULL COMMENT '用户ID(users.id)',
+ `plan_id` VARCHAR(64) NOT NULL COMMENT 'jikip 套餐ID',
+ `jikip_user_id` VARCHAR(64) NOT NULL COMMENT 'jikip 用户ID',
+ `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
+ `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
+ PRIMARY KEY (`user_id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户级 jikip 套餐余量配置';
diff --git a/backend-java/src/test/java/com/nanri/aiimage/modules/notification/service/NotificationScanSchedulerTest.java b/backend-java/src/test/java/com/nanri/aiimage/modules/notification/service/NotificationScanSchedulerTest.java
index 2de71fc69..43b750b40 100644
--- a/backend-java/src/test/java/com/nanri/aiimage/modules/notification/service/NotificationScanSchedulerTest.java
+++ b/backend-java/src/test/java/com/nanri/aiimage/modules/notification/service/NotificationScanSchedulerTest.java
@@ -185,6 +185,122 @@ class NotificationScanSchedulerTest {
assertThat(keyBase.getValue()).matches("service_down:brand-service:\\d{8}");
}
+ /** 平台自费代理事前预警:套餐余量低于阈值必须推管理员警告,而不是等停摆后报接口不可用。 */
+ @Test
+ void lowProxySurplusWarnsAdminsBeforeOutage() {
+ properties.setBrandServiceUrl("");
+ properties.setPriceTrackApiUrl("");
+ properties.setJikipLowSurplusThreshold(100);
+ when(proxyBalancePort.fetchBalances()).thenReturn(List.of(plan("p-1", "80", "50")));
+ when(dispatch.pushToAdmins(anyString(), anyString(), anyString(), anyString(), anyString(), any()))
+ .thenReturn(1);
+
+ newScheduler().probeServices();
+
+ ArgumentCaptor keyBase = ArgumentCaptor.forClass(String.class);
+ verify(dispatch).pushToAdmins(eq(NotificationService.SCENE_SERVICE_DOWN),
+ eq(NotificationService.LEVEL_WARNING), eq("jikip 代理套餐余量不足"), anyString(),
+ keyBase.capture(), org.mockito.ArgumentMatchers.isNull());
+ assertThat(keyBase.getValue()).matches("jikip_low_surplus:p-1:\\d{8}");
+ }
+
+ /** 余量充足不许发预警:阈值默认常开,误报会把真正的停摆通知淹掉。 */
+ @Test
+ void healthyProxySurplusDoesNotWarn() {
+ properties.setBrandServiceUrl("");
+ properties.setPriceTrackApiUrl("");
+ properties.setJikipLowSurplusThreshold(100);
+ when(proxyBalancePort.fetchBalances()).thenReturn(List.of(plan("p-1", "5000", "50")));
+
+ newScheduler().probeServices();
+
+ verify(dispatch, never()).pushToAdmins(anyString(), anyString(), anyString(), anyString(), anyString(), any());
+ }
+
+ /** 供应商改字段口径(非数字)时宁可不报,不能把「解析失败」当成余量 0 天天误报。 */
+ @Test
+ void unparsableSurplusDoesNotWarn() {
+ properties.setBrandServiceUrl("");
+ properties.setPriceTrackApiUrl("");
+ properties.setJikipLowSurplusThreshold(100);
+ when(proxyBalancePort.fetchBalances()).thenReturn(List.of(plan("p-1", "充足", null)));
+
+ newScheduler().probeServices();
+
+ verify(dispatch, never()).pushToAdmins(anyString(), anyString(), anyString(), anyString(), anyString(), any());
+ }
+
+ /** 多套餐:每个套餐独立判定、独立去重,不能因一个套餐健康就漏掉另一个。 */
+ @Test
+ void eachLowPlanWarnsIndependently() {
+ properties.setBrandServiceUrl("");
+ properties.setPriceTrackApiUrl("");
+ properties.setJikipLowSurplusThreshold(100);
+ when(proxyBalancePort.fetchBalances()).thenReturn(List.of(
+ plan("p-a", "50", "50"),
+ plan("p-b", "80", "50"),
+ plan("p-c", "5000", "50")));
+ when(dispatch.pushToAdmins(anyString(), anyString(), anyString(), anyString(), anyString(), any()))
+ .thenReturn(1);
+
+ newScheduler().probeServices();
+
+ ArgumentCaptor keyBase = ArgumentCaptor.forClass(String.class);
+ verify(dispatch, times(2)).pushToAdmins(eq(NotificationService.SCENE_SERVICE_DOWN),
+ eq(NotificationService.LEVEL_WARNING), eq("jikip 代理套餐余量不足"), anyString(),
+ keyBase.capture(), org.mockito.ArgumentMatchers.isNull());
+ assertThat(keyBase.getAllValues()).anySatisfy(key ->
+ assertThat(key).matches("jikip_low_surplus:p-a:\\d{8}"));
+ assertThat(keyBase.getAllValues()).anySatisfy(key ->
+ assertThat(key).matches("jikip_low_surplus:p-b:\\d{8}"));
+ }
+
+ /** 完全没有配置套餐时跳过,不发告警。 */
+ @Test
+ void unconfiguredPlansSkipWithoutWarning() {
+ properties.setBrandServiceUrl("");
+ properties.setPriceTrackApiUrl("");
+ when(proxyBalancePort.fetchBalances()).thenReturn(List.of());
+
+ newScheduler().probeServices();
+
+ verify(dispatch, never()).pushToAdmins(anyString(), anyString(), anyString(), anyString(), anyString(), any());
+ }
+
+ /** 余额阈值默认关闭(0);显式配置后低于阈值同样预警。 */
+ @Test
+ void proxyBalanceWarnsOnlyWhenThresholdEnabled() {
+ properties.setBrandServiceUrl("");
+ properties.setPriceTrackApiUrl("");
+ properties.setJikipLowSurplusThreshold(0);
+ when(proxyBalancePort.fetchBalances()).thenReturn(List.of(plan("p-1", "5000", "3")));
+
+ newScheduler().probeServices();
+ verify(dispatch, never()).pushToAdmins(anyString(), anyString(), anyString(), anyString(), anyString(), any());
+
+ properties.setJikipLowBalanceThreshold(10);
+ when(dispatch.pushToAdmins(anyString(), anyString(), anyString(), anyString(), anyString(), any()))
+ .thenReturn(1);
+
+ newScheduler().probeServices();
+
+ ArgumentCaptor keyBase = ArgumentCaptor.forClass(String.class);
+ verify(dispatch).pushToAdmins(eq(NotificationService.SCENE_SERVICE_DOWN),
+ eq(NotificationService.LEVEL_WARNING), eq("jikip 代理账户余额不足"), anyString(),
+ keyBase.capture(), org.mockito.ArgumentMatchers.isNull());
+ assertThat(keyBase.getValue()).matches("jikip_low_balance:p-1:\\d{8}");
+ }
+
+ @Test
+ void firstNumberParsesSupplierFormats() {
+ assertThat(NotificationScanScheduler.firstNumber("123")).isEqualTo(123L);
+ assertThat(NotificationScanScheduler.firstNumber("123次")).isEqualTo(123L);
+ assertThat(NotificationScanScheduler.firstNumber("12.5")).isEqualTo(12L);
+ assertThat(NotificationScanScheduler.firstNumber("充足")).isNull();
+ assertThat(NotificationScanScheduler.firstNumber(null)).isNull();
+ assertThat(NotificationScanScheduler.firstNumber("123456789012345678901")).isNull();
+ }
+
/** 状态码三态口径:4xx 里只有 401/403/404 是「探活不可信」,其余按故障算。 */
@Test
void httpStatusClassifiesIntoThreeProbeVerdicts() {
@@ -348,6 +464,11 @@ class NotificationScanSchedulerTest {
return server;
}
+ private static ProxyBalancePort.ProxyBalanceEntry plan(String planId, String surplus, String balance) {
+ return new ProxyBalancePort.ProxyBalanceEntry(planId,
+ new ProxyBalancePort.ProxyBalanceSnapshot(true, surplus, balance, null));
+ }
+
private void stubAdminAudience() {
when(dispatch.prepareAdminAudience()).thenReturn(
new NotificationDispatchService.AdminAudience(List.of(), Set.of(), Map.of()));
diff --git a/backend-java/src/test/java/com/nanri/aiimage/modules/usersecret/client/JikipProxyClientTest.java b/backend-java/src/test/java/com/nanri/aiimage/modules/usersecret/client/JikipProxyClientTest.java
new file mode 100644
index 000000000..dc8e65127
--- /dev/null
+++ b/backend-java/src/test/java/com/nanri/aiimage/modules/usersecret/client/JikipProxyClientTest.java
@@ -0,0 +1,27 @@
+package com.nanri.aiimage.modules.usersecret.client;
+
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+class JikipProxyClientTest {
+
+ @Test
+ void parsePlansSupportsSemicolonAndComma() {
+ var plans = JikipProxyClient.parsePlans("111:222;333:444, 555: 666");
+
+ assertThat(plans).extracting(JikipProxyClient.PlanRef::planId)
+ .containsExactly("111", "333", "555");
+ assertThat(plans).extracting(JikipProxyClient.PlanRef::userId)
+ .containsExactly("222", "444", "666");
+ }
+
+ @Test
+ void parsePlansIgnoresMalformedEntries() {
+ assertThat(JikipProxyClient.parsePlans("bad;111:;:222;;333:444"))
+ .extracting(JikipProxyClient.PlanRef::planId)
+ .containsExactly("333");
+ assertThat(JikipProxyClient.parsePlans("")).isEmpty();
+ assertThat(JikipProxyClient.parsePlans(null)).isEmpty();
+ }
+}
diff --git a/backend-java/src/test/java/com/nanri/aiimage/modules/usersecret/service/UserApiSecretServiceTest.java b/backend-java/src/test/java/com/nanri/aiimage/modules/usersecret/service/UserApiSecretServiceTest.java
index d3a3e0f83..8f904fd36 100644
--- a/backend-java/src/test/java/com/nanri/aiimage/modules/usersecret/service/UserApiSecretServiceTest.java
+++ b/backend-java/src/test/java/com/nanri/aiimage/modules/usersecret/service/UserApiSecretServiceTest.java
@@ -24,8 +24,11 @@ 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.UserApiSecretBalanceVo;
import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretBundleVo;
+import com.nanri.aiimage.modules.notification.service.NotificationService;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
@@ -46,18 +49,22 @@ import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import com.nanri.aiimage.common.mapper.ShopManageGroupMapper;
class UserApiSecretServiceTest {
private final UserApiSecretMapper mapper = mock(UserApiSecretMapper.class);
+ private final UserProxyPlanService userProxyPlanService = mock(UserProxyPlanService.class);
private final ShopCredentialCryptoService crypto = mock(ShopCredentialCryptoService.class);
private final UserApiSecretCheckService checkService = mock(UserApiSecretCheckService.class);
private final JikipProxyClient jikipProxyClient = mock(JikipProxyClient.class);
@@ -90,8 +97,8 @@ class UserApiSecretServiceTest {
valueOps = mockValueOps();
when(stringRedisTemplate.opsForValue()).thenReturn(valueOps);
return new UserApiSecretService(
- mapper, crypto, checkService, jikipProxyClient, adminUserMapper, adminAuthSupport, adminGroupMapper,
- userDataScopeSupport, notificationDispatchService, userSecretProperties,
+ mapper, userProxyPlanService, crypto, checkService, jikipProxyClient, adminUserMapper, adminAuthSupport,
+ adminGroupMapper, userDataScopeSupport, notificationDispatchService, userSecretProperties,
stringRedisTemplate, objectMapper);
}
@@ -425,7 +432,7 @@ class UserApiSecretServiceTest {
when(mapper.selectOne(any())).thenReturn(null);
service.save(7L, "proxy",
- "https://api.jikip.com/ip-get?num=1&minute=3&format=json&area=all&protocol=1&mode=2&key=6p78gjm9c0p161o");
+ "https://api.jikip.com/ip-get?num=1&minute=3&format=json&area=all&protocol=1&mode=2&key=unit-test-key");
ArgumentCaptor captor = ArgumentCaptor.forClass(UserApiSecretEntity.class);
verify(mapper).insert(captor.capture());
@@ -1093,6 +1100,129 @@ class UserApiSecretServiceTest {
.isEqualTo("secret_invalid_admin:11:similar-asin:" + today());
}
+ /** 用户填了自己的套餐后,余量必须查自己的 planId/userId,不能回落到平台套餐。 */
+ @Test
+ void proxyBalanceUsesUserPlanAndFlagsLowSurplus() {
+ UserApiSecretService service = newService();
+ 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);
+
+ assertThat(result.getScope()).isEqualTo("user");
+ assertThat(result.getLow()).isTrue();
+ assertThat(result.getLowReason()).contains("80").contains("100");
+ verify(jikipProxyClient, never()).fetchBalance();
+ }
+
+ /** 没配套餐的用户看平台余量,但不参与用户级报警(平台告警归管理员巡检)。 */
+ @Test
+ void proxyBalanceFallsBackToPlatformWithoutUserPlan() {
+ UserApiSecretService service = newService();
+ when(userProxyPlanService.getEntity(7L)).thenReturn(null);
+ when(jikipProxyClient.fetchBalance()).thenReturn(proxyBalance("5000", "500"));
+
+ UserApiSecretBalanceVo result = service.proxyBalance(7L);
+
+ assertThat(result.getScope()).isEqualTo("platform");
+ assertThat(result.getLow()).isFalse();
+ assertThat(result.getLowReason()).isNull();
+ }
+
+ /** 余额耗尽必须报警,哪怕管理员把余额预警阈值配成 0(默认关闭)——「欠费了要一直警告」是需求原话。 */
+ @Test
+ void proxyBalanceFlagsExhaustedBalanceEvenWhenThresholdDisabled() {
+ UserApiSecretService service = newService();
+ 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);
+
+ assertThat(result.getLow()).isTrue();
+ assertThat(result.getLowReason()).contains("已耗尽");
+ }
+
+ /** 客户端会周期性轮询:5 分钟内复用缓存;改/清套餐后主动失效,下一次立即按新配置查。 */
+ @Test
+ void proxyBalanceCachesPerUserAndInvalidatesOnPlanChange() {
+ UserApiSecretService service = newService();
+ 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);
+ verify(jikipProxyClient, times(1)).fetchBalance(ref);
+
+ service.invalidateProxyBalance(7L);
+ service.proxyBalance(7L);
+ verify(jikipProxyClient, times(2)).fetchBalance(ref);
+ }
+
+ /** 站内通知总开关关闭时连查都不查:余量巡检的唯一产出就是通知,查了也没处送。 */
+ @Test
+ void scheduledProxyBalanceSkipsWhenNotificationsDisabled() {
+ UserApiSecretService service = newService();
+ userSecretProperties.setNotifyEnabled(false);
+
+ UserApiSecretService.ProxyBalanceCheckSummary summary =
+ service.checkUserProxyBalancesForScheduler(2000, 10);
+
+ assertThat(summary.users()).isZero();
+ assertThat(summary.checked()).isZero();
+ verifyNoInteractions(userProxyPlanService);
+ }
+
+ /** 巡检按用户逐个查:只给低余量用户推通知,正常用户不打扰,去重键按用户+自然日。 */
+ @Test
+ void scheduledProxyBalanceNotifiesOnlyLowUsers() {
+ UserApiSecretService service = newService();
+ 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")))
+ .thenReturn(proxyBalance("20", "10"));
+ when(jikipProxyClient.fetchBalance(new JikipProxyClient.PlanRef("p-ok", "u-ok")))
+ .thenReturn(proxyBalance("5000", "500"));
+ when(notificationDispatchService.pushToUser(anyLong(), anyString(), anyString(), anyString(),
+ anyString(), anyString())).thenReturn(true);
+
+ UserApiSecretService.ProxyBalanceCheckSummary summary =
+ service.checkUserProxyBalancesForScheduler(2000, 10);
+
+ assertThat(summary.users()).isEqualTo(2);
+ assertThat(summary.checked()).isEqualTo(2);
+ assertThat(summary.warned()).isEqualTo(1);
+ ArgumentCaptor dedupeKey = ArgumentCaptor.forClass(String.class);
+ verify(notificationDispatchService).pushToUser(eq(7L),
+ eq(NotificationService.SCENE_SECRET_BALANCE), eq(NotificationService.LEVEL_WARNING),
+ anyString(), anyString(), dedupeKey.capture());
+ assertThat(dedupeKey.getValue()).matches("proxy_plan_low:7:\\d{8}");
+ verify(notificationDispatchService, never()).pushToUser(eq(8L), anyString(), anyString(),
+ anyString(), anyString(), anyString());
+ }
+
+ private UserProxyPlanEntity proxyPlan(long userId, String planId, String jikipUserId) {
+ UserProxyPlanEntity plan = new UserProxyPlanEntity();
+ plan.setUserId(userId);
+ plan.setPlanId(planId);
+ plan.setJikipUserId(jikipUserId);
+ return plan;
+ }
+
+ private UserApiSecretBalanceVo proxyBalance(String surplus, String balance) {
+ UserApiSecretBalanceVo vo = new UserApiSecretBalanceVo();
+ vo.setAvailable(true);
+ vo.setSurplus(surplus);
+ vo.setBalance(balance);
+ return vo;
+ }
+
/** 管理员受众与推送出口打桩:只关心「发几条、发给谁、什么文案」,受众解析本身有专测。 */
private void stubAdminNotificationPath() {
when(notificationDispatchService.prepareAdminAudience()).thenReturn(
diff --git a/backend-java/src/test/java/com/nanri/aiimage/modules/usersecret/service/UserProxyPlanServiceTest.java b/backend-java/src/test/java/com/nanri/aiimage/modules/usersecret/service/UserProxyPlanServiceTest.java
new file mode 100644
index 000000000..6c0cbcaf0
--- /dev/null
+++ b/backend-java/src/test/java/com/nanri/aiimage/modules/usersecret/service/UserProxyPlanServiceTest.java
@@ -0,0 +1,70 @@
+package com.nanri.aiimage.modules.usersecret.service;
+
+import com.nanri.aiimage.modules.usersecret.mapper.UserProxyPlanMapper;
+import com.nanri.aiimage.modules.usersecret.model.entity.UserProxyPlanEntity;
+import com.nanri.aiimage.modules.usersecret.model.vo.UserProxyPlanVo;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/** 用户级 jikip 套餐配置:一个用户一行,保存即 upsert,清除即删行。 */
+class UserProxyPlanServiceTest {
+
+ private final UserProxyPlanMapper mapper = mock(UserProxyPlanMapper.class);
+ private final UserProxyPlanService service = new UserProxyPlanService(mapper);
+
+ @Test
+ void getReturnsUnconfiguredWhenNoRow() {
+ when(mapper.selectById(7L)).thenReturn(null);
+
+ UserProxyPlanVo vo = service.get(7L);
+
+ assertThat(vo.getConfigured()).isFalse();
+ assertThat(vo.getPlanId()).isNull();
+ assertThat(vo.getJikipUserId()).isNull();
+ }
+
+ @Test
+ void saveInsertsTrimmedValuesForFirstTime() {
+ when(mapper.selectById(7L)).thenReturn(null);
+
+ service.save(7L, " 20261010593613392231 ", " 626710989815 ");
+
+ ArgumentCaptor captor = ArgumentCaptor.forClass(UserProxyPlanEntity.class);
+ verify(mapper).insert(captor.capture());
+ UserProxyPlanEntity inserted = captor.getValue();
+ assertThat(inserted.getUserId()).isEqualTo(7L);
+ assertThat(inserted.getPlanId()).isEqualTo("20261010593613392231");
+ assertThat(inserted.getJikipUserId()).isEqualTo("626710989815");
+ assertThat(inserted.getUserId()).isNotNull();
+ }
+
+ @Test
+ void saveUpdatesExistingRowInPlace() {
+ UserProxyPlanEntity existing = new UserProxyPlanEntity();
+ existing.setUserId(7L);
+ existing.setPlanId("old-plan");
+ existing.setJikipUserId("old-user");
+ when(mapper.selectById(7L)).thenReturn(existing);
+
+ service.save(7L, "new-plan", "new-user");
+
+ ArgumentCaptor captor = ArgumentCaptor.forClass(UserProxyPlanEntity.class);
+ verify(mapper).updateById(captor.capture());
+ UserProxyPlanEntity updated = captor.getValue();
+ assertThat(updated.getUserId()).isEqualTo(7L);
+ assertThat(updated.getPlanId()).isEqualTo("new-plan");
+ assertThat(updated.getJikipUserId()).isEqualTo("new-user");
+ }
+
+ @Test
+ void clearDeletesByUserId() {
+ service.clear(7L);
+
+ verify(mapper).deleteById(7L);
+ }
+}
diff --git a/frontend-vue/src/App.vue b/frontend-vue/src/App.vue
index 6425587fd..c82c0dccf 100644
--- a/frontend-vue/src/App.vue
+++ b/frontend-vue/src/App.vue
@@ -2,6 +2,7 @@
+
@@ -16,6 +17,7 @@ import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { onBeforeUnmount } from 'vue'
import ExpiryNotice from '@/shared/components/ExpiryNotice.vue'
import ForceUpdateGate from '@/shared/components/ForceUpdateGate.vue'
+import ProxyBalanceAlert from '@/shared/components/ProxyBalanceAlert.vue'
import { disposeGlobalErrorGuard } from '@/shared/utils/app-error'
import { uninstallUserTokenSync } from '@/shared/auth/user-token-sync'
import { disposeDownloadProgressListener } from '@/shared/utils/download-progress'
diff --git a/frontend-vue/src/shared/api/endpoints.ts b/frontend-vue/src/shared/api/endpoints.ts
index cead8d7a1..dd0070805 100644
--- a/frontend-vue/src/shared/api/endpoints.ts
+++ b/frontend-vue/src/shared/api/endpoints.ts
@@ -205,6 +205,7 @@ export const API_ENDPOINTS = {
check: '/api/user-secrets/{moduleKey}/check',
migrate: '/api/user-secrets/migrate',
proxyBalance: '/api/user-secrets/proxy-balance',
+ proxyPlan: '/api/user-secrets/proxy-plan',
},
notification: {
summary: '/api/notifications/summary',
diff --git a/frontend-vue/src/shared/api/types/modules/user-secret.ts b/frontend-vue/src/shared/api/types/modules/user-secret.ts
index cef281e9a..3d625d7ee 100644
--- a/frontend-vue/src/shared/api/types/modules/user-secret.ts
+++ b/frontend-vue/src/shared/api/types/modules/user-secret.ts
@@ -48,6 +48,18 @@ export interface UserApiSecretBalance {
surplus: string | null
balance: string | null
message: string | null
+ /** 余量来源:user=用户自己的套餐;platform=平台套餐 */
+ scope?: 'user' | 'platform' | string
+ /** 是否低于预警阈值(仅用户自己的套餐判定) */
+ low?: boolean
+ /** 低余量原因 */
+ lowReason?: string | null
+}
+
+export interface UserProxyPlan {
+ planId: string | null
+ jikipUserId: string | null
+ configured: boolean
}
export interface UserApiSecretMigrateItem {
@@ -103,3 +115,25 @@ export function fetchProxyBalance() {
get>(buildJavaUrl(API_ENDPOINTS.userSecret.proxyBalance)),
)
}
+
+/** 读取当前用户填写的 jikip 套餐 ID / 用户 ID(只用于余量查询)。 */
+export function fetchProxyPlan() {
+ return unwrapJavaResponse(
+ get>(buildJavaUrl(API_ENDPOINTS.userSecret.proxyPlan)),
+ )
+}
+
+export function saveProxyPlan(planId: string, jikipUserId: string) {
+ return unwrapJavaResponse(
+ put, { planId: string; jikipUserId: string }>(
+ buildJavaUrl(API_ENDPOINTS.userSecret.proxyPlan),
+ { planId, jikipUserId },
+ ),
+ )
+}
+
+export function clearProxyPlan() {
+ return unwrapJavaResponse(
+ del>(buildJavaUrl(API_ENDPOINTS.userSecret.proxyPlan)),
+ )
+}
diff --git a/frontend-vue/src/shared/components/ApiSecretSettingsPanel.vue b/frontend-vue/src/shared/components/ApiSecretSettingsPanel.vue
index 4c3ccea0a..7018d0798 100644
--- a/frontend-vue/src/shared/components/ApiSecretSettingsPanel.vue
+++ b/frontend-vue/src/shared/components/ApiSecretSettingsPanel.vue
@@ -93,6 +93,52 @@
+
+
jikip 套餐信息(用于余量查询与预警)
+
+
+
+
+
+
+
+
+
+ 填写后,下方余量按你自己的 jikip 套餐查询;留空则显示平台默认套餐。套餐 ID / 用户 ID 在 jikip 后台「我的套餐」和「账户信息」查看。
+
+
+