feat(代理): 多套餐余量预警与用户级 jikip 套餐配置

平台自费池由单个 planId/userId 改为 planId:userId 列表逐套餐探测,
套餐余量或账户余额低于阈值时推管理员预警;用户可在密钥设置里为自己
配置多个套餐,巡检跟随密钥检查按用户查余量并推站内通知,欠费状态在
客户端右上角常驻提示(V160 新建用户级套餐表)。

同时把测试里写死的真实代理 key 换成占位串,避免凭证随仓库扩散。
This commit is contained in:
2026-10-21 13:32:56 +08:00
parent 19a291ec39
commit f6aa04d0f2
31 changed files with 1544 additions and 52 deletions
@@ -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<String> 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.<Long>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<String> 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.<Long>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<String> 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.<Long>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()));
@@ -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();
}
}
@@ -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<UserApiSecretEntity> 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<String> 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(
@@ -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<UserProxyPlanEntity> 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<UserProxyPlanEntity> 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);
}
}