feat:文件上传的功能开发

master
赵佳正 4 weeks ago
parent a6a83e5bd5
commit 8f948dece3

@ -0,0 +1,21 @@
# 2026-10-10
- SSO 登录真实库报错 `Data truncated for column 'platform_user_id'`(非 401,401 已修好):
根因是**运行库 schema 漂移**,不是代码 bug。dev 环境 `spring.sql.init.mode=never`,`schema.sql` 不自动执行,
`platform_user_snapshot.platform_user_id`(及 auth_login_exchange_code / auth_refresh_token 的platform_user_id)
在真 MySQL 库里被建成比 VARCHAR(36) 更窄或数值型;代码写入本地 user_id(UUID,36 字符)装不下即截断。
H2 测试库按 schema.sql 的 VARCHAR(36) 建表,故全部测试通过、只在真库报错。
- **最终方案(用户拍板:快照表不需要)**:不再使用 `platform_user_snapshot`,把学校/学院/专业/班级
统一并进 `sys_user` 主表。已落地:
- schema.sql(main+test)给 `sys_user` 加 `college_id/college_name/major_id/major_name` 4 列,
并删除 `platform_user_snapshot` 建表与种子数据;
- `UserEntity`、`UserMapper.selectActiveByStudentId` 同步加列;
- `LocalSsoAccountService` 去掉 `upsertSnapshot`,改把 college/major 写进 `sys_user`;
`UserController.success` 与 `CurrentUserService` 改从 `sys_user` 读(不再读快照);
- 删除 `PlatformUserSnapshotEntity` / `PlatformUserSnapshotMapper`;
- 新增 `db/manual/sys_user_profile_upgrade.sql`(ADD 4 列 + DROP `platform_user_snapshot`)。
- **真库 `118.31.7.2/digital_rmb` 已执行**:`sys_user` 加了 4 列、`platform_user_snapshot` 已 DROP。
- 测试:`LocalSsoAccountServiceTest`/`UserControllerTest`/`CurrentUserAndLogoutTest`/
`PlatformTokenVerifierTest`/`PlatformSsoControllerTest`/`PlatformIntegrationConfigTest` 共 15 用例全过。
- 经验:此类"测试过、真库截断"优先怀疑运行库列定义与 schema.sql 不一致(本项目 dev 不跑 schema.sql),
直接给手动 ALTER 脚本比改代码更准。

@ -0,0 +1,103 @@
# digital-rmb-backend 项目长期约定
## 技术栈
Spring Boot 2.7.18 + Java 8;MyBatis-Plus 3.5.17;Spring Security + JWT;
统一响应 `ApiResponse<T>`(code/message/data/traceId/timestamp);异常用
`BusinessException(ErrorCode, message)`;当前用户用 `CurrentUserService.getCurrentUser()`
(schoolId 来自 sys_user),institutionidentity 模块另有 `AuthContextHolder`。
## 建库脚本(高频踩坑)
- 新增表必须**同时**改 `src/main/resources/schema.sql` 和 `src/test/resources/schema.sql`。
测试 classpath 优先加载 test 那份,只改 main 会导致 H2 报 `Table ... not found`。
- 存量库升级脚本放 `src/main/resources/db/manual/`。
- `application-dev.yml` 是 `spring.sql.init.mode: never`,schema.sql 不会自动执行到运行库。
- `stu_module_score_details` 唯一约束 `uk_user_moudule_serial (user_id, moudule, serial_number)`,
同模块多条数据 serial_number 必须递增。
## 构建与测试
- **不要用 `mvn clean`**:本机因文件占用删除 `target/classes/com/yau/digitalrmb/progress/infrastructure` 失败。
改用 PowerShell `Remove-Item -Recurse -Force target\classes` 与 `target\test-classes`。
- `target` 增量编译有历史残留,会出现主编译"成功"但缺包;先删 classes/test-classes 再编译。
- 沙箱会拦截 WMIC.exe,mvn 结束后 shell 退出码非 0 —— **以日志里的 BUILD SUCCESS 为准**。
- 跑单测:`mvn -o test -Dtest=XXXTest -DfailIfNoSpecifiedTests=false`。
## 六实验模块编号
1 中国人民银行生成数字货币 / 2 中国人民银行发行数字货币 / 3 开通数字货币钱包 /
4 用户兑换数字货币 / 5 用户支付数字货币 / 6 数字人民币创新应用场景仿真。
注意:成绩表 `stu_module_score_details.moudule` 里模块二写作"发行数字货币"、
模块四写作"数字货币兑换",与设置页标准名不同 —— 映射见
`com.yau.digitalrmb.training.score.application.TrainingModules`。
## 成绩与权重
- 学生端汇总:`GET /api/v1/training-scores`(参数 moudule 可空)。
**模块权重与扣分来自 `training_module_weight`**:查不到本校配置时由 `TrainingWeightService.moduleWeight`
落一条默认记录(含默认扣分 0.50)后返回,因此学生查成绩也会写库。返回体新增 `deductScore`
(数值,来自权重表),`scoringCriteria` 文本也由该值拼出。
- 教师端权重:`/api/v1/training-weights` 下 GET/POST `/school`、GET/POST `/modules`。
- 默认值集中在 `TrainingModules`:模块权重 0.30/0.25/0.10/0.10/0.10/0.15,
总成绩 0.80/0.20,扣分 0.50(**截图未能读取,待用户核对**)。
- 表结构(用户明确要求,勿改回纵向):
- `training_school_score_weight`:一校一行,只有 training_weight / report_weight,**无索引**。
- `training_module_weight`:一校一行,6 个模块权重**横向**存
`module1_weight`…`module6_weight`,`deduct_score` 也在这张表;不要 moudule / moudule_code 列,不要唯一索引。
- 接口语义(用户明确要求):**查询接口首次查不到数据时直接落库一条默认记录**并返回 id;
**修改接口按 id 更新**(请求体必传 id),不是按 schoolId upsert。
`id` 不存在 → 404;记录不属于当前学校 → 403;权重和不为 1 → 400。
- 返回 `{id, deductScore, modules:[...], configured}`;`configured=false` 表示这条默认记录是本次查询刚生成的。
- **性能红线(防止回归)**:教师端总成绩/详情/导出**严禁逐学生调用 `overall`/`summary`**(N+1:page=10 触发 200+ 次查询)。
已改为按分页学生整体批量——模块最高分/进度各一条 GROUP BY、报告一条 IN、权重整请求只查一次。
批量口径:`TeacherModuleScoreMapper.selectMaxScoresByUserIds`(最高分含已删除轮次)/
`selectLatestScheduleByUserIds`(进度取最新有效记录);学生端自身 `summary` 因含操作次数/明细/最值,仍按单用户调用。
- MySQL 8 新建表 CREATE TABLE 必须带 `DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`(对齐 sys_user 老表);漏 COLLATE 会按服务器默认建成 0900_ai_ci,与老表 join 时报 Illegal mix of collations。修复样例见 db/manual/experiment_report_upgrade.sql 末尾的 ALTER。
## 协作与排查约定(踩坑总结)
- 用户说"写到文档/接口文档"时,需求是**改 md 文档**,不要顺手写实现代码;先确认"只要文档还是也要代码"。
反之"帮我把 X 接口实现/改一下"才是写代码。
- 测试失败先别怀疑编译残留:先看目标 controller 的 handler 是否还在(方法是否被注释掉),
再查历史基准日志(项目根 ts.log / teacher-detail-test.log / test_r.log 记录了各测试类的通过情况),
最后才考虑删 target\classes、target\test-classes 重编译。
- 学生端成绩详情 /details 与教师端 teacher/details 的综合分数必须同口径:
Σ(模块最高分 × 模块权重),缺失模块计 0,保留 2 位 HALF_UP;最高分含已删除轮次。
## 单点登录(SSO)· 智云是中枢,digital-rmb 与 cross_training_platform 是平级子系统
- **拓扑**:智云(ZhiYun)是 SSO 中枢并签发 token;`digital-rmb` 与 `cross_training_platform`
都是它的平级子系统,互相独立、互不跳转。前端点的"智云单点登录"跳转直接带智云 token 到
`digital-rmb` 的 `/api/user/login`,**不经过 cross_training_platform**,后者不是"主系统"。
- 登录入口 `UserController` 的 `POST /api/user/login`(`@ConditionalOnProperty platform-integration.enabled=true`)。
参数 `TOKEN` 走 `tokenLogin` → `PlatformTokenVerifier.verify`;账号密码走 `LocalAccountAuthenticationService`。
- **秘钥已和智云对齐(写死常量)**:`PlatformTokenVerifier` 内常量 `ZHIYUN_SECRET = "zy_kzy_mnjy_fp76ckwuczzmb67w0a8x0"`
(HS256),即 cross_training_platform 的 `TokenProvider.SECRET_ZHIYUN`,与智云签发密钥一致。
2026-10-09 起已**移除 `platform-integration.token.link-secret-key` 配置项**(dev/test/prod/test-classpath 四处
yml 的 `token:` 块、`PlatformIntegrationProperties.Token` 类全部删掉),verifier 直接写死该常量,
不再读配置/env,避免 test profile 误用 `local-token-sso-test-secret-key-123456` 导致 401。
- 解析逻辑照抄 `getJWTUserByZhiYun`:HS256 验签 → 提取 userId/username/name/password(默认123qwe)/
roleid(默认4)/schoolId(默认0)/school→schoolName/class→className/studentNo→studentId/
college→collegeName/major→majorName;解析失败直接抛 `平台登录凭据无效`(无 subsystem 兜底)。
- 学生端登录 `UserController.tokenLogin` → `PlatformTokenVerifier.verify` → `LocalSsoAccountService.synchronize`
(查/建 UserEntity,差异仅数据表)→ `JwtTokenService.issueFor`,与 cross_training_platform 的
`UserController.login` 分支2 同构。
- **平台用户信息不再用快照表**(2026-10-10 起):`platform_user_snapshot` 表已删除,学校/学院/专业/班级
统一存在 `sys_user` 主表(`college_id/college_name/major_id/major_name` 等列)。
登录 `LocalSsoAccountService.synchronize` 直接写 `sys_user`;`UserController.success` 与
`CurrentUserService.getCurrentUser` 从 `sys_user` 读学院/专业。存量库升级脚本 `db/manual/sys_user_profile_upgrade.sql`。
- **两系统差异(待用户拍板)**:cross_training_platform 验完智云 token 后还远程调
`TzApi.foreignExchangeTradingLogin` 回智云再核用户;digital-rmb 的 `PlatformTokenVerifier` **只验签名+过期、不远程核身**。
- 排查 SSO 秘钥问题时,直接看上述三处 yml + `PlatformTokenVerifier`(验签 HS256)+ `cross_training_platform/.../TokenProvider.SECRET_ZHIYUN`,
别绕去 `PlatformSsoController`(那是另一条 platformintegration 链路)。
# 模块六 · 对公钱包ID格式(2026-10-31 起)
- 对公钱包ID = `CORP_` + 步骤一 SM3 摘要值(64 位 hex),统一由
`com.yau.digitalrmb.corporatewallet.domain.CorporateWalletId.normalize()` 生成/归一化;
临柜 `CorporateWalletService.outputWallet` 与远程 `RemoteWalletService.outputWallet` 两个输出接口都走它。
- 历史数据可能只有纯 hex:读取一律 `normalize`,比对一律 `CorporateWalletId.matches()`(忽略前缀+大小写),
不要再用裸 `equalsIgnoreCase` 比钱包ID。
- 捐赠 `POST /api/v1/donation/digest`:付款钱包 = 本企业对公钱包(临柜优先,回退远程),精确比对;
收款钱包**只判 `CORP_` 前缀且不等于付款钱包**,不查库、不校验受赠机构。

@ -2,6 +2,7 @@ package com.yau.digitalrmb.corporatewallet.application;
import com.yau.digitalrmb.corporatewallet.domain.CorporateWalletApplication;
import com.yau.digitalrmb.corporatewallet.domain.CorporateWalletApplicationRepository;
import com.yau.digitalrmb.corporatewallet.domain.CorporateWalletId;
import com.yau.digitalrmb.corporatewallet.domain.RemoteWalletApplication;
import com.yau.digitalrmb.corporatewallet.domain.RemoteWalletApplicationRepository;
import com.yau.digitalrmb.corporatewallet.interfaces.rest.dto.CorporateWalletApplicationRequest;
@ -170,8 +171,13 @@ public class CorporateWalletService {
throw new BusinessException(ErrorCode.VALIDATION_ERROR, "请先完成SM3摘要运算");
}
if (app.getWalletId() != null) {
String walletId = CorporateWalletId.normalize(app.getWalletId());
if (!walletId.equals(app.getWalletId())) {
app.setWalletId(walletId);
repository.update(app);
}
return new CorporateWalletResult(
app.getWalletId(), app.getCorpName(), app.getCreditCode(),
walletId, app.getCorpName(), app.getCreditCode(),
app.getWalletType(), "ACTIVATED", app.getActivateTime(), "临柜开立");
}
@ -183,17 +189,22 @@ public class CorporateWalletService {
if (remoteActivated != null) {
// 【企业信息一致性校验】比对临柜开立和远程开立的企业信息是否一致
validateEnterpriseInfoConsistency(app, remoteActivated);
// 复用远程开立的钱包ID,不再生成新钱包
app.activateWallet(remoteActivated.getWalletId(), remoteActivated.getActivateTime());
String sharedWalletId = CorporateWalletId.normalize(remoteActivated.getWalletId());
if (!sharedWalletId.equals(remoteActivated.getWalletId())) {
remoteActivated.setWalletId(sharedWalletId);
remoteRepository.update(remoteActivated);
}
app.activateWallet(sharedWalletId, remoteActivated.getActivateTime());
repository.update(app);
return new CorporateWalletResult(
remoteActivated.getWalletId(), app.getCorpName(), app.getCreditCode(),
sharedWalletId, app.getCorpName(), app.getCreditCode(),
app.getWalletType(), "ACTIVATED", remoteActivated.getActivateTime(), "远程开立");
}
// 钱包ID直接使用步骤一SM3摘要运算生成的摘要值
String walletId = app.getDigestValue();
// 钱包ID直接使用步骤一SM3摘要运算生成的摘要值,统一带 CORP_ 前缀
String walletId = CorporateWalletId.normalize(app.getDigestValue());
String activateTime = app.getVerifyTime() != null ? app.getVerifyTime()
: LocalDateTime.now().format(TIMESTAMP_FORMAT);

@ -2,6 +2,7 @@ package com.yau.digitalrmb.corporatewallet.application;
import com.yau.digitalrmb.corporatewallet.domain.CorporateWalletApplication;
import com.yau.digitalrmb.corporatewallet.domain.CorporateWalletApplicationRepository;
import com.yau.digitalrmb.corporatewallet.domain.CorporateWalletId;
import com.yau.digitalrmb.corporatewallet.domain.Donation;
import com.yau.digitalrmb.corporatewallet.domain.DonationRepository;
import com.yau.digitalrmb.corporatewallet.domain.RemoteWalletApplication;
@ -62,10 +63,9 @@ public class DonationService {
return new DonationDigestResult(donation.getDigestValue());
}
// 2. 校验付款钱包ID
// 2. 校验付款钱包ID(兼容历史无 CORP_ 前缀的纯摘要值)
String userWalletId = findUserWalletId(subject);
if (userWalletId == null
|| !userWalletId.equalsIgnoreCase(request.getCorpWalletId() != null ? request.getCorpWalletId().trim() : "")) {
if (userWalletId == null || !CorporateWalletId.matches(userWalletId, request.getCorpWalletId())) {
scoreService.recordError(subject.getUserId());
throw new BusinessException(ErrorCode.VALIDATION_ERROR, "付款钱包ID不正确,错误次数+1");
}
@ -200,13 +200,13 @@ public class DonationService {
.findLatest(subject.getUserId(), subject.getSchoolId(), subject.getClassId())
.orElse(null);
if (corpApp != null && corpApp.getWalletId() != null && !corpApp.getWalletId().isEmpty()) {
return corpApp.getWalletId();
return CorporateWalletId.normalize(corpApp.getWalletId());
}
RemoteWalletApplication remoteApp = remoteWalletRepository
.findLatest(subject.getUserId(), subject.getSchoolId(), subject.getClassId())
.orElse(null);
if (remoteApp != null && remoteApp.getWalletId() != null && !remoteApp.getWalletId().isEmpty()) {
return remoteApp.getWalletId();
return CorporateWalletId.normalize(remoteApp.getWalletId());
}
return null;
}

@ -3,6 +3,7 @@ package com.yau.digitalrmb.corporatewallet.application;
import com.yau.digitalrmb.corporatewallet.application.CorporateWalletKeyService;
import com.yau.digitalrmb.corporatewallet.domain.CorporateWalletApplication;
import com.yau.digitalrmb.corporatewallet.domain.CorporateWalletApplicationRepository;
import com.yau.digitalrmb.corporatewallet.domain.CorporateWalletId;
import com.yau.digitalrmb.corporatewallet.domain.RemoteWalletApplication;
import com.yau.digitalrmb.corporatewallet.domain.RemoteWalletApplicationRepository;
import com.yau.digitalrmb.corporatewallet.infrastructure.CorporateWalletKeyInfoEntity;
@ -303,8 +304,13 @@ public class RemoteWalletService {
throw new BusinessException(ErrorCode.VALIDATION_ERROR, "请先完成钱包SM3摘要运算");
}
if (app.getWalletId() != null) {
String walletId = CorporateWalletId.normalize(app.getWalletId());
if (!walletId.equals(app.getWalletId())) {
app.setWalletId(walletId);
repository.update(app);
}
return new RemoteWalletResult(
app.getWalletId(), app.getCorpName(), app.getCreditCode(),
walletId, app.getCorpName(), app.getCreditCode(),
app.getWalletType(), "ACTIVATED", app.getActivateTime(), "已验证", "远程开立");
}
@ -316,17 +322,22 @@ public class RemoteWalletService {
if (corpActivated != null) {
// 【企业信息一致性校验】比对远程开立和临柜开立的企业信息是否一致
validateEnterpriseInfoConsistency(app, corpActivated);
// 复用临柜开立的钱包ID,不再生成新钱包
app.activateWallet(corpActivated.getWalletId(), corpActivated.getActivateTime());
String sharedWalletId = CorporateWalletId.normalize(corpActivated.getWalletId());
if (!sharedWalletId.equals(corpActivated.getWalletId())) {
corpActivated.setWalletId(sharedWalletId);
corporateRepository.update(corpActivated);
}
app.activateWallet(sharedWalletId, corpActivated.getActivateTime());
repository.update(app);
return new RemoteWalletResult(
corpActivated.getWalletId(), app.getCorpName(), app.getCreditCode(),
sharedWalletId, app.getCorpName(), app.getCreditCode(),
app.getWalletType(), "ACTIVATED", corpActivated.getActivateTime(), "已验证", "临柜开立");
}
// 钱包ID直接使用钱包SM3摘要运算生成的摘要值
String walletId = app.getWalletDigestValue();
// 钱包ID直接使用钱包SM3摘要运算生成的摘要值,统一带 CORP_ 前缀
String walletId = CorporateWalletId.normalize(app.getWalletDigestValue());
String activateTime = app.getSignTime() != null ? app.getSignTime()
: LocalDateTime.now().format(TIMESTAMP_FORMAT);

@ -3,6 +3,7 @@ package com.yau.digitalrmb.corporatewallet.application;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yau.digitalrmb.corporatewallet.domain.CorporateWalletApplication;
import com.yau.digitalrmb.corporatewallet.domain.CorporateWalletApplicationRepository;
import com.yau.digitalrmb.corporatewallet.domain.CorporateWalletId;
import com.yau.digitalrmb.corporatewallet.domain.RemoteWalletApplication;
import com.yau.digitalrmb.corporatewallet.domain.RemoteWalletApplicationRepository;
import com.yau.digitalrmb.corporatewallet.infrastructure.CorporateWalletKeyInfoEntity;
@ -569,14 +570,14 @@ public class SalaryBatchService {
.findLatest(subject.getUserId(), subject.getSchoolId(), subject.getClassId())
.orElse(null);
if (corpApp != null && corpApp.getWalletId() != null && !corpApp.getWalletId().isEmpty()) {
return corpApp.getWalletId();
return CorporateWalletId.normalize(corpApp.getWalletId());
}
// 再查远程开立
RemoteWalletApplication remoteApp = remoteWalletRepository
.findLatest(subject.getUserId(), subject.getSchoolId(), subject.getClassId())
.orElse(null);
if (remoteApp != null && remoteApp.getWalletId() != null && !remoteApp.getWalletId().isEmpty()) {
return remoteApp.getWalletId();
return CorporateWalletId.normalize(remoteApp.getWalletId());
}
return null;
}

@ -0,0 +1,46 @@
package com.yau.digitalrmb.corporatewallet.domain;
/**
* 对公钱包ID格式约定:{@code CORP_} + 步骤一 SM3 摘要值。
* <p>
* 历史数据曾只落纯摘要值,读取与比对统一走本类归一化,避免新旧口径不一致导致校验失败。
*/
public final class CorporateWalletId {
public static final String PREFIX = "CORP_";
private CorporateWalletId() {
}
/** 补全 CORP_ 前缀;空值原样返回。 */
public static String normalize(String raw) {
if (raw == null) {
return null;
}
String value = raw.trim();
if (value.isEmpty() || hasPrefix(value)) {
return value;
}
return PREFIX + value;
}
public static boolean hasPrefix(String value) {
return value != null && value.regionMatches(true, 0, PREFIX, 0, PREFIX.length());
}
/** 去掉 CORP_ 前缀,仅保留摘要部分。 */
public static String stripPrefix(String value) {
if (value == null) {
return null;
}
String trimmed = value.trim();
return hasPrefix(trimmed) ? trimmed.substring(PREFIX.length()) : trimmed;
}
/** 忽略前缀与大小写比对两个钱包ID是否指向同一摘要。 */
public static boolean matches(String expected, String actual) {
String left = stripPrefix(expected);
String right = stripPrefix(actual);
return left != null && right != null && !left.isEmpty() && left.equalsIgnoreCase(right);
}
}

@ -92,7 +92,7 @@ public class CorporateWalletController {
@PostMapping("/wallet-output")
@Operation(summary = "生成对公钱包输出",
description = "根据SM3摘要生成对公钱包ID,返回钱包ID、企业名称、信用代码、钱包类型、状态和激活时间")
description = "根据SM3摘要生成对公钱包ID(格式 CORP_ + 摘要值),返回钱包ID、企业名称、信用代码、钱包类型、状态和激活时间")
public ApiResponse<CorporateWalletResult> outputWallet() {
return ApiResponse.success(corporateWalletService.outputWallet(
InstitutionKeySubject.from(AuthContextHolder.get())), traceId());

@ -136,7 +136,7 @@ public class RemoteWalletController {
@PostMapping("/wallet-output")
@Operation(summary = "步骤三-输出对公钱包",
description = "返回钱包ID、企业名称、信用代码、钱包类型、状态、激活时间和人脸识别记录")
description = "返回钱包ID(格式 CORP_ + 摘要值)、企业名称、信用代码、钱包类型、状态、激活时间和人脸识别记录")
public ApiResponse<RemoteWalletResult> outputWallet() {
return ApiResponse.success(remoteWalletService.outputWallet(
InstitutionKeySubject.from(AuthContextHolder.get())), traceId());

@ -32,12 +32,13 @@ public class LocalSsoAccountService {
studentId = token.getUsername();
}
UserEntity user = findExistingUser(token.getUserId(), studentId);
boolean newUser = user == null;
if (user == null) {
user = new UserEntity();
if (isUuid(token.getUserId())) {
user.setUserId(UUID.fromString(token.getUserId()).toString());
}
// 数据库已有对应账号:仅查询返回,不根据平台 token 覆盖任何字段
if (user != null) {
return user;
}
user = new UserEntity();
if (isUuid(token.getUserId())) {
user.setUserId(UUID.fromString(token.getUserId()).toString());
}
String passwordHash = passwordEncoder.encode(token.getRawPassword());
user.setStudentId(studentId);
@ -54,12 +55,8 @@ public class LocalSsoAccountService {
user.setRoleId(token.getRoleId());
user.setIsDeleted(false);
user.setZyUserId(token.getUserId());
user.setCreateTime(user.getCreateTime() == null ? LocalDateTime.now() : user.getCreateTime());
if (newUser) {
userMapper.insert(user);
} else {
userMapper.updateById(user);
}
user.setCreateTime(LocalDateTime.now());
userMapper.insert(user);
return user;
}

@ -10,6 +10,7 @@ import com.yau.digitalrmb.issuance.domain.model.CentralBankIssuanceBusinessRevie
import com.yau.digitalrmb.issuance.domain.model.CentralBankIssuanceReceipt;
import com.yau.digitalrmb.issuance.domain.model.CentralBankIssuanceVerification;
import com.yau.digitalrmb.issuance.domain.model.IssuanceAuditActor;
import com.yau.digitalrmb.issuance.domain.model.IssuanceOwner;
import com.yau.digitalrmb.issuance.domain.repository.CentralBankCurrencyVaultRepository;
import com.yau.digitalrmb.issuance.domain.repository.CentralBankInstitutionAccountRepository;
import com.yau.digitalrmb.issuance.domain.repository.CentralBankIssuanceBusinessReviewRepository;
@ -72,10 +73,11 @@ public class CentralBankIssuanceBusinessReviewService {
BigDecimal verifiedAmount = denominationTotal(denominations);
generationModuleGateway.validateIssuancePrerequisites(
keySubject, requestedAmount, organizationId, denominations);
Optional<CentralBankInstitutionAccount> account = accountRepository.findByBankCode(bankCode);
IssuanceOwner owner = IssuanceOwner.of(keySubject.getUserId(), keySubject.getSchoolId(), keySubject.getClassId());
Optional<CentralBankInstitutionAccount> account = accountRepository.findByBankCode(owner, bankCode);
boolean accountValid = account.isPresent() && "NORMAL".equals(account.get().getStatus())
&& generationModuleGateway.isCurrentConfirmedInstitutionIdentifier(keySubject, organizationId);
Optional<CentralBankCurrencyVault> vault = vaultRepository.findByCurrency(currency);
Optional<CentralBankCurrencyVault> vault = vaultRepository.findByCurrency(owner, currency);
boolean vaultSufficient = vault.isPresent() && vault.get().getAvailableBalance().compareTo(requestedAmount) >= 0;
boolean amountConsistent = requestedAmount.compareTo(verifiedAmount) == 0;
String status = accountValid && vaultSufficient && amountConsistent ? "REVIEW_PASSED" : "REVIEW_REJECTED";

@ -11,6 +11,7 @@ import com.yau.digitalrmb.issuance.domain.model.CentralBankIssuanceReceipt;
import com.yau.digitalrmb.issuance.domain.model.IssuanceApplicationId;
import com.yau.digitalrmb.issuance.domain.model.IssuanceAuditActor;
import com.yau.digitalrmb.issuance.domain.model.IssuanceBankInventory;
import com.yau.digitalrmb.issuance.domain.model.IssuanceOwner;
import com.yau.digitalrmb.issuance.domain.model.IssuanceRequest;
import com.yau.digitalrmb.issuance.domain.repository.IssuanceRequestRepository;
import com.yau.digitalrmb.issuance.domain.repository.CentralBankIssuanceReceiptRepository;
@ -89,9 +90,10 @@ public class CommercialBankIssuanceApplicationService {
}
@Transactional
public IssuanceRequestView create(CreateIssuanceRequestCommand command, IssuanceAuditActor auditActor) {
public IssuanceRequestView create(CreateIssuanceRequestCommand command, IssuanceOwner owner,
IssuanceAuditActor auditActor) {
try {
requireAmountWithinSuggestedSupplement(command.getTotalAmount());
requireAmountWithinSuggestedSupplement(command.getTotalAmount(), owner);
UUID id = UUID.randomUUID();
IssuanceRequest request = IssuanceRequest.create(new IssuanceApplicationId(id), requestNo(id),
command.getBankCode(), command.getOrganizationId(), command.getTotalAmount(), command.getCurrency(),
@ -103,15 +105,20 @@ public class CommercialBankIssuanceApplicationService {
}
}
public IssuanceRequestView create(CreateIssuanceRequestCommand command, IssuanceAuditActor auditActor) {
return create(command, legacyOwner(auditActor), auditActor);
}
public IssuanceRequestView create(CreateIssuanceRequestCommand command, String username) {
return create(command, legacyAuditActor(username));
}
@Transactional
public IssuanceRequestView update(UUID id, UpdateIssuanceRequestCommand command, IssuanceAuditActor auditActor) {
public IssuanceRequestView update(UUID id, UpdateIssuanceRequestCommand command, IssuanceOwner owner,
IssuanceAuditActor auditActor) {
try {
IssuanceRequest request = requireOwnedRequestForUpdate(id, auditActor);
requireAmountWithinSuggestedSupplement(command.getTotalAmount());
requireAmountWithinSuggestedSupplement(command.getTotalAmount(), owner);
request.updateDraft(command.getTotalAmount(), command.getCurrency(), command.getDenominations());
repository.save(request, auditActor(auditActor));
return IssuanceRequestView.from(request);
@ -120,6 +127,10 @@ public class CommercialBankIssuanceApplicationService {
}
}
public IssuanceRequestView update(UUID id, UpdateIssuanceRequestCommand command, IssuanceAuditActor auditActor) {
return update(id, command, legacyOwner(auditActor), auditActor);
}
public IssuanceRequestView update(UUID id, UpdateIssuanceRequestCommand command, String username) {
return update(id, command, legacyAuditActor(username));
}
@ -231,20 +242,31 @@ public class CommercialBankIssuanceApplicationService {
return IssuanceRequestView.from(requireOwnedRequest(id, auditActor));
}
@Transactional(readOnly = true)
public CommercialBankInventoryView getInventory() {
IssuanceBankInventory inventory = repository.findBuiltInInventory().orElseThrow(() ->
@Transactional
public CommercialBankInventoryView getInventory(IssuanceOwner owner) {
IssuanceBankInventory inventory = repository.findInventory(owner).orElseThrow(() ->
new BusinessException(ErrorCode.RESOURCE_NOT_FOUND, "发行库存配置不存在"));
return new CommercialBankInventoryView(inventory.getBankCode(), inventory.getCurrentBalance(),
inventory.getWarningThreshold(), inventory.getSuggestedSupplementAmount());
}
private void requireAmountWithinSuggestedSupplement(BigDecimal requestedAmount) {
/** 仅兼容历史调用:未提供归属主体时按当前操作人建一份独立资产,避免再共享全局库存。 */
private IssuanceOwner legacyOwner(IssuanceAuditActor auditActor) {
IssuanceAuditActor effective = auditActor(auditActor);
return IssuanceOwner.of(effective.getUserId(), 0L, 0L);
}
private void requireAmountWithinSuggestedSupplement(BigDecimal requestedAmount, IssuanceOwner owner) {
if (requestedAmount == null) {
throw new BusinessException(ErrorCode.VALIDATION_ERROR, "申请发行金额不能为空");
}
IssuanceBankInventory inventory = repository.findBuiltInInventory().orElseThrow(() ->
IssuanceBankInventory inventory = repository.findInventory(owner).orElseThrow(() ->
new BusinessException(ErrorCode.RESOURCE_NOT_FOUND, "发行库存配置不存在"));
if (inventory.getSuggestedSupplementAmount().compareTo(BigDecimal.ZERO) == 0) {
throw new BusinessException(ErrorCode.VALIDATION_ERROR,
"当前库存余额已达到库存容量阈值 " + inventory.getWarningThreshold().setScale(2).toPlainString()
+ " 元,建议补充金额为 0,请先重新实训");
}
if (requestedAmount.compareTo(inventory.getSuggestedSupplementAmount()) > 0) {
throw new BusinessException(ErrorCode.VALIDATION_ERROR,
"申请发行金额不得超过建议补充金额 "

@ -13,7 +13,9 @@ import com.yau.digitalrmb.shared.api.ErrorCode;
import com.yau.digitalrmb.shared.exception.BusinessException;
import com.yau.digitalrmb.issuance.domain.model.DenominationItem;
import com.yau.digitalrmb.issuance.domain.model.DraftDigitalCurrency;
import com.yau.digitalrmb.issuance.domain.model.IssuanceAssetDefaults;
import com.yau.digitalrmb.issuance.domain.model.IssuanceAuditActor;
import com.yau.digitalrmb.issuance.domain.model.IssuanceOwner;
import com.yau.digitalrmb.issuance.infrastructure.persistence.entity.IssuanceSourceCurrencyUsageEntity;
import com.yau.digitalrmb.issuance.infrastructure.persistence.mapper.IssuanceSourceCurrencyUsageMapper;
import com.yau.digitalrmb.institutionidentity.infrastructure.StandardCurrencyBatchEntity;
@ -261,7 +263,8 @@ public class DigitalCurrencyGenerationModuleGateway {
sources.add(source);
totalAmount = totalAmount.add(source.getDenomination()).setScale(2);
}
transferVaultBalances(requiredBankCode, currencyCode, totalAmount);
transferVaultBalances(IssuanceOwner.of(subject.getUserId(), subject.getSchoolId(), subject.getClassId()),
requiredBankCode, currencyCode, totalAmount);
LocalDateTime now = LocalDateTime.now();
for (int index = 0; index < sources.size(); index++) {
StandardCurrencyEntity source = sources.get(index);
@ -319,20 +322,72 @@ public class DigitalCurrencyGenerationModuleGateway {
}
}
private void transferVaultBalances(String bankCode, String currency, BigDecimal amount) {
private void transferVaultBalances(IssuanceOwner owner, String bankCode, String currency, BigDecimal amount) {
ensureVault(owner, currency);
List<BigDecimal> balances = jdbcTemplate.query("SELECT available_balance FROM central_bank_currency_vault "
+ "WHERE currency = ? FOR UPDATE", (rs, rowNum) -> rs.getBigDecimal(1), currency);
+ "WHERE user_id = ? AND school_id = ? AND class_id = ? AND currency = ? AND deleted = 0 FOR UPDATE",
(rs, rowNum) -> rs.getBigDecimal(1),
owner.getUserId(), owner.getSchoolId(), owner.getClassId(), currency);
if (balances.isEmpty()) throw validation("央行发行库不存在币种:" + currency);
if (balances.get(0).compareTo(amount) < 0) throw validation("央行发行库余额不足");
int deducted = jdbcTemplate.update("UPDATE central_bank_currency_vault SET available_balance = available_balance - ? "
+ "WHERE currency = ? AND available_balance >= ?", amount, currency, amount);
+ "WHERE user_id = ? AND school_id = ? AND class_id = ? AND currency = ? "
+ "AND available_balance >= ? AND deleted = 0",
amount, owner.getUserId(), owner.getSchoolId(), owner.getClassId(), currency, amount);
if (deducted != 1) throw validation("央行发行库余额已变化,请重新核查");
ensureInventory(owner, bankCode);
int increased = jdbcTemplate.update("UPDATE issuance_bank_inventory SET current_balance = current_balance + ?, "
+ "updated_at = CURRENT_TIMESTAMP WHERE bank_code = ?", amount, bankCode);
if (increased == 0) {
jdbcTemplate.update("INSERT INTO issuance_bank_inventory "
+ "(bank_code, current_balance, warning_threshold, updated_at) VALUES (?, ?, 0, CURRENT_TIMESTAMP)",
bankCode, amount);
+ "updated_at = CURRENT_TIMESTAMP "
+ "WHERE user_id = ? AND school_id = ? AND class_id = ? AND bank_code = ? AND deleted = 0",
amount, owner.getUserId(), owner.getSchoolId(), owner.getClassId(), bankCode);
if (increased != 1) throw validation("商业银行数字货币库存记录缺失,请重新进入实训后再试");
}
private void ensureVault(IssuanceOwner owner, String currency) {
Integer exists = jdbcTemplate.queryForObject("SELECT COUNT(*) FROM central_bank_currency_vault "
+ "WHERE user_id = ? AND school_id = ? AND class_id = ? AND currency = ? AND deleted = 0", Integer.class,
owner.getUserId(), owner.getSchoolId(), owner.getClassId(), currency);
if (exists != null && exists > 0) return;
jdbcTemplate.update("INSERT INTO central_bank_currency_vault "
+ "(user_id, school_id, class_id, currency, available_balance) VALUES (?, ?, ?, ?, ?)",
owner.getUserId(), owner.getSchoolId(), owner.getClassId(), currency,
IssuanceAssetDefaults.INITIAL_VAULT_BALANCE);
convergeVaultRows(owner, currency);
}
/** 该表不使用唯一键:并发首次初始化可能插出多条有效行,只保留 id 最小的一条,其余逻辑删除。 */
private void convergeVaultRows(IssuanceOwner owner, String currency) {
List<Long> ids = jdbcTemplate.queryForList("SELECT id FROM central_bank_currency_vault "
+ "WHERE user_id = ? AND school_id = ? AND class_id = ? AND currency = ? AND deleted = 0 "
+ "ORDER BY id",
Long.class, owner.getUserId(), owner.getSchoolId(), owner.getClassId(), currency);
for (int index = 1; index < ids.size(); index++) {
jdbcTemplate.update("UPDATE central_bank_currency_vault SET deleted = id WHERE id = ?", ids.get(index));
}
}
private void ensureInventory(IssuanceOwner owner, String bankCode) {
Integer exists = jdbcTemplate.queryForObject("SELECT COUNT(*) FROM issuance_bank_inventory "
+ "WHERE user_id = ? AND school_id = ? AND class_id = ? AND bank_code = ? AND deleted = 0", Integer.class,
owner.getUserId(), owner.getSchoolId(), owner.getClassId(), bankCode);
if (exists != null && exists > 0) return;
jdbcTemplate.update("INSERT INTO issuance_bank_inventory "
+ "(user_id, school_id, class_id, bank_code, current_balance, warning_threshold, updated_at) "
+ "VALUES (?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)",
owner.getUserId(), owner.getSchoolId(), owner.getClassId(), bankCode,
IssuanceAssetDefaults.INITIAL_BANK_INVENTORY_BALANCE,
IssuanceAssetDefaults.BANK_INVENTORY_WARNING_THRESHOLD);
convergeInventoryRows(owner, bankCode);
}
/** 该表不使用唯一键:并发首次初始化可能插出多条有效行,只保留 id 最小的一条,其余逻辑删除。 */
private void convergeInventoryRows(IssuanceOwner owner, String bankCode) {
List<Long> ids = jdbcTemplate.queryForList("SELECT id FROM issuance_bank_inventory "
+ "WHERE user_id = ? AND school_id = ? AND class_id = ? AND bank_code = ? AND deleted = 0 "
+ "ORDER BY id",
Long.class, owner.getUserId(), owner.getSchoolId(), owner.getClassId(), bankCode);
for (int index = 1; index < ids.size(); index++) {
jdbcTemplate.update("UPDATE issuance_bank_inventory SET deleted = id WHERE id = ?", ids.get(index));
}
}

@ -2,6 +2,7 @@ package com.yau.digitalrmb.issuance.application.service;
import com.yau.digitalrmb.issuance.application.query.ReserveDeductionNotificationView;
import com.yau.digitalrmb.issuance.domain.model.IssuanceAuditActor;
import com.yau.digitalrmb.issuance.domain.model.IssuanceOwner;
import com.yau.digitalrmb.shared.api.ErrorCode;
import com.yau.digitalrmb.shared.exception.BusinessException;
import com.yau.digitalrmb.training.attempt.application.AttemptCancellationHandler;
@ -45,6 +46,7 @@ public class IssuanceAttemptCancellationHandler implements AttemptCancellationHa
if (notification.isPresent()
&& executionService.find(notification.get().getTransactionId()).isPresent()) {
executionService.reverse(notification.get().getTransactionId(),
IssuanceOwner.of(subject.getUserId(), subject.getSchoolId(), subject.getClassId()),
new IssuanceAuditActor(subject.getUserId(), subject.getUserId()));
return;
}

@ -8,6 +8,7 @@ import com.yau.digitalrmb.issuance.application.command.UpdateIssuanceRequestComm
import com.yau.digitalrmb.issuance.application.query.ReserveDeductionNotificationView;
import com.yau.digitalrmb.issuance.domain.model.DenominationItem;
import com.yau.digitalrmb.issuance.domain.model.IssuanceAuditActor;
import com.yau.digitalrmb.issuance.domain.model.IssuanceOwner;
import com.yau.digitalrmb.issuance.interfaces.dto.IssuanceActionRequest;
import com.yau.digitalrmb.issuance.interfaces.dto.DenominationItemRequest;
import com.yau.digitalrmb.shared.api.ErrorCode;
@ -114,7 +115,7 @@ public class IssuanceTrainingActionService {
final boolean bindSuppliedRequest = attempt.getBusinessId() == null && businessRequestId != null;
ActionWork<Object> work = () -> {
try {
ActionOutcome<Object> outcome = run(actionKey, input, businessRequestId, actor, keySubject);
ActionOutcome<Object> outcome = run(actionKey, input, businessRequestId, actor, keySubject, subject);
return bindSuppliedRequest
? ActionOutcome.completed(outcome.getOutput(), businessRequestId.toString()) : outcome;
} catch (TrainingInputException exception) {
@ -136,16 +137,18 @@ public class IssuanceTrainingActionService {
}
private ActionOutcome<Object> run(String key, IssuanceActionRequest request, UUID requestId,
IssuanceAuditActor actor, InstitutionKeySubject keySubject) {
IssuanceAuditActor actor, InstitutionKeySubject keySubject,
ExperimentSubject subject) {
IssuanceOwner owner = IssuanceOwner.of(subject.getUserId(), subject.getSchoolId(), subject.getClassId());
switch (key) {
case "01:refresh-quota":
return completed(commercialService.getInventory());
return completed(commercialService.getInventory(owner));
case "01:refresh-custom-application":
if (requestId != null) {
Object existing = hasDraftValues(request)
? commercialService.update(requestId, new UpdateIssuanceRequestCommand(
positive(request.getTotalAmount(), "发行总金额"),
required(request.getCurrency(), "币种"), denominations(request.getDenominations())), actor)
required(request.getCurrency(), "币种"), denominations(request.getDenominations())), owner, actor)
: commercialService.getCommercialBankView(requestId, actor);
return ActionOutcome.completed(existing,
requestId.toString());
@ -154,7 +157,7 @@ public class IssuanceTrainingActionService {
new CreateIssuanceRequestCommand(required(request.getBankCode(), "商业银行机构代码"),
required(request.getOrganizationId(), "机构标识"),
positive(request.getTotalAmount(), "发行总金额"), required(request.getCurrency(), "币种"),
denominations(request.getDenominations())), actor);
denominations(request.getDenominations())), owner, actor);
return ActionOutcome.completed(created, created.getId().toString());
case "01:generate-timestamp":
return completed(commercialService.captureTimestamp(requestId, actor));
@ -177,13 +180,13 @@ public class IssuanceTrainingActionService {
case "03:query-institution-input":
return completed(commercialService.getCommercialBankView(requestId, actor));
case "03:query-quota-input":
return completed(commercialService.getInventory());
return completed(commercialService.getInventory(owner));
case "03:query-application-message":
return completed(centralBankService.getCentralBankView(requestId));
case "04:auto-confirm-plan":
return completed(reviewService.review(requestId, actor, keySubject));
case "04:generate-reserve-deduction-request":
return completed(notificationService.send(requestId, actor));
return completed(notificationService.send(requestId, owner, actor));
case "05:confirm-receipt":
return completed(notificationService.receive(requestId, actor));
case "05:query-account":
@ -191,7 +194,7 @@ public class IssuanceTrainingActionService {
case "05:verify-deduction":
return completed(notificationService.submit(requestId, actor));
case "05:execute-deduction":
return completed(executionService.execute(requireNotification(requestId).getTransactionId(), actor));
return completed(executionService.execute(requireNotification(requestId).getTransactionId(), owner, actor));
case "05:generate-balance-notice":
case "05:send-balance-notice":
ReserveDeductionNotificationView notification = requireNotification(requestId);

@ -1,6 +1,8 @@
package com.yau.digitalrmb.issuance.application.service;
import com.yau.digitalrmb.issuance.application.IssuanceTrainingResetResult;
import com.yau.digitalrmb.issuance.domain.model.IssuanceAssetDefaults;
import com.yau.digitalrmb.issuance.domain.model.IssuanceOwner;
import com.yau.digitalrmb.shared.api.ErrorCode;
import com.yau.digitalrmb.shared.exception.BusinessException;
import com.yau.digitalrmb.training.attempt.domain.ExperimentModule;
@ -27,6 +29,7 @@ public class IssuanceTrainingResetService {
@Transactional
public IssuanceTrainingResetResult reset(ExperimentSubject subject) {
requireSubject(subject);
IssuanceOwner owner = IssuanceOwner.of(subject.getUserId(), subject.getSchoolId(), subject.getClassId());
List<AttemptRecord> attempts = jdbc.query(
"SELECT id,business_id FROM training_experiment_attempt WHERE module_code=? "
+ "AND user_id=? AND school_id=? AND class_id=? AND organization_id=? FOR UPDATE",
@ -45,32 +48,16 @@ public class IssuanceTrainingResetService {
requireUnusedByFollowingModules(requestId);
}
BigDecimal restoredReserve = BigDecimal.ZERO.setScale(2);
BigDecimal restoredCurrency = BigDecimal.ZERO.setScale(2);
// 重置前余额,仅用于返回“本轮释放了多少额度”(asset 重置不再依赖它做加减)
BigDecimal reserveBefore = balanceOf("SELECT COALESCE(SUM(reserve_balance),0) "
+ "FROM central_bank_institution_account WHERE user_id=? AND school_id=? AND class_id=? AND deleted=0", owner);
BigDecimal inventoryBefore = balanceOf("SELECT COALESCE(SUM(current_balance),0) "
+ "FROM issuance_bank_inventory WHERE user_id=? AND school_id=? AND class_id=? AND deleted=0", owner);
int affected = 0;
for (String requestId : requestIds) {
for (ReserveRestoration value : reserveRestorations(requestId)) {
int updated = jdbc.update("UPDATE central_bank_institution_account "
+ "SET reserve_balance=reserve_balance+? WHERE bank_code=?",
value.amount, value.bankCode);
if (updated != 1) throw internal("恢复商业银行准备金余额失败:" + value.bankCode);
restoredReserve = restoredReserve.add(value.amount);
}
for (CurrencyRestoration value : currencyRestorations(requestId)) {
int vaultUpdated = jdbc.update("UPDATE central_bank_currency_vault "
+ "SET available_balance=available_balance+? WHERE currency=?",
value.amount, value.currency);
if (vaultUpdated != 1) throw internal("恢复央行发行库余额失败:" + value.currency);
int bankUpdated = jdbc.update("UPDATE issuance_bank_inventory "
+ "SET current_balance=current_balance-?,updated_at=CURRENT_TIMESTAMP "
+ "WHERE bank_code=? AND current_balance>=?",
value.amount, value.bankCode, value.amount);
if (bankUpdated != 1) throw internal("恢复商业银行数字货币库存失败:" + value.bankCode);
restoredCurrency = restoredCurrency.add(value.amount);
}
affected += deleteRequestData(requestId, subject.getUserId());
}
for (AttemptRecord attempt : attempts) {
affected += jdbc.update("DELETE FROM training_experiment_action WHERE attempt_id=?", attempt.id);
}
@ -80,9 +67,66 @@ public class IssuanceTrainingResetService {
subject.getOrganizationId());
affected += jdbc.update("DELETE FROM training_task_step_progress WHERE user_id=? AND module_code=?",
subject.getUserId(), PROGRESS_MODULE_CODE);
// 三份资产不按金额回滚,直接丢掉本轮记录(逻辑删除)并按原始值重新落一份,保证“重新实训 = 全新开始”
affected += resetAssets(owner);
BigDecimal restoredReserve = releasedAmount(reserveBefore, IssuanceAssetDefaults.INITIAL_RESERVE_BALANCE);
BigDecimal restoredCurrency = releasedAmount(inventoryBefore, IssuanceAssetDefaults.INITIAL_BANK_INVENTORY_BALANCE);
return new IssuanceTrainingResetResult(affected, restoredReserve, restoredCurrency);
}
/** 逻辑删除该生当前有效资产行(deleted 写入该行 id,历史行互不冲突),再按原始值插入新一轮记录。 */
private int resetAssets(IssuanceOwner owner) {
int count = 0;
count += jdbc.update("UPDATE issuance_bank_inventory SET deleted=id "
+ "WHERE user_id=? AND school_id=? AND class_id=? AND deleted=0",
owner.getUserId(), owner.getSchoolId(), owner.getClassId());
count += jdbc.update("UPDATE central_bank_currency_vault SET deleted=id "
+ "WHERE user_id=? AND school_id=? AND class_id=? AND deleted=0",
owner.getUserId(), owner.getSchoolId(), owner.getClassId());
count += jdbc.update("UPDATE central_bank_institution_account SET deleted=id "
+ "WHERE user_id=? AND school_id=? AND class_id=? AND deleted=0",
owner.getUserId(), owner.getSchoolId(), owner.getClassId());
count += jdbc.update("INSERT INTO issuance_bank_inventory "
+ "(user_id,school_id,class_id,bank_code,current_balance,warning_threshold,updated_at,deleted) "
+ "VALUES (?,?,?,?,?,?,CURRENT_TIMESTAMP,0)",
owner.getUserId(), owner.getSchoolId(), owner.getClassId(),
IssuanceAssetDefaults.BUILT_IN_BANK_CODE,
IssuanceAssetDefaults.INITIAL_BANK_INVENTORY_BALANCE,
IssuanceAssetDefaults.BANK_INVENTORY_WARNING_THRESHOLD);
count += jdbc.update("INSERT INTO central_bank_currency_vault "
+ "(user_id,school_id,class_id,currency,available_balance,deleted) VALUES (?,?,?,?,?,0)",
owner.getUserId(), owner.getSchoolId(), owner.getClassId(),
IssuanceAssetDefaults.BUILT_IN_CURRENCY,
IssuanceAssetDefaults.INITIAL_VAULT_BALANCE);
count += jdbc.update("INSERT INTO central_bank_institution_account "
+ "(user_id,school_id,class_id,bank_code,organization_id,reserve_account_no,"
+ "reserve_account_name,status,opened_on,reserve_balance,deleted) "
+ "VALUES (?,?,?,?,?,?,?,?,?,?,0)",
owner.getUserId(), owner.getSchoolId(), owner.getClassId(),
IssuanceAssetDefaults.BUILT_IN_BANK_CODE,
IssuanceAssetDefaults.BUILT_IN_ORGANIZATION_ID,
IssuanceAssetDefaults.BUILT_IN_RESERVE_ACCOUNT_NO,
IssuanceAssetDefaults.BUILT_IN_RESERVE_ACCOUNT_NAME,
IssuanceAssetDefaults.BUILT_IN_ACCOUNT_STATUS,
IssuanceAssetDefaults.BUILT_IN_ACCOUNT_OPENED_ON,
IssuanceAssetDefaults.INITIAL_RESERVE_BALANCE);
return count;
}
private BigDecimal balanceOf(String sql, IssuanceOwner owner) {
BigDecimal value = jdbc.queryForObject(sql, BigDecimal.class,
owner.getUserId(), owner.getSchoolId(), owner.getClassId());
return value == null ? BigDecimal.ZERO : value;
}
private BigDecimal releasedAmount(BigDecimal before, BigDecimal initial) {
BigDecimal released = before.subtract(initial);
return released.compareTo(BigDecimal.ZERO) > 0 ? released.setScale(2) : BigDecimal.ZERO.setScale(2);
}
private void requireOwnedRequest(String requestId, String userId) {
Integer count = jdbc.queryForObject("SELECT COUNT(*) FROM issuance_request "
+ "WHERE id=? AND created_by_user_id=?", Integer.class, requestId, userId);
@ -114,22 +158,6 @@ public class IssuanceTrainingResetService {
}
}
private List<ReserveRestoration> reserveRestorations(String requestId) {
return jdbc.query("SELECT n.bank_code,e.deduction_amount FROM reserve_deduction_execution e "
+ "JOIN reserve_deduction_notification n ON n.request_id=e.request_id "
+ "WHERE e.request_id=? AND e.status='DEDUCTED' FOR UPDATE",
(rs, rowNum) -> new ReserveRestoration(rs.getString("bank_code"),
rs.getBigDecimal("deduction_amount")), requestId);
}
private List<CurrencyRestoration> currencyRestorations(String requestId) {
return jdbc.query("SELECT bank_code,currency,SUM(denomination) amount "
+ "FROM commercial_bank_currency WHERE issuance_request_id=? "
+ "GROUP BY bank_code,currency",
(rs, rowNum) -> new CurrencyRestoration(rs.getString("bank_code"), rs.getString("currency"),
rs.getBigDecimal("amount")), requestId);
}
private int deleteRequestData(String requestId, String userId) {
int count = 0;
count += jdbc.update("DELETE FROM central_bank_currency_ownership WHERE currency_id IN "
@ -169,30 +197,9 @@ public class IssuanceTrainingResetService {
return new BusinessException(ErrorCode.VALIDATION_ERROR, message);
}
private BusinessException internal(String message) {
return new BusinessException(ErrorCode.INTERNAL_ERROR, message);
}
private static final class AttemptRecord {
private final String id;
private final String businessId;
private AttemptRecord(String id, String businessId) { this.id = id; this.businessId = businessId; }
}
private static final class ReserveRestoration {
private final String bankCode;
private final BigDecimal amount;
private ReserveRestoration(String bankCode, BigDecimal amount) {
this.bankCode = bankCode; this.amount = amount;
}
}
private static final class CurrencyRestoration {
private final String bankCode;
private final String currency;
private final BigDecimal amount;
private CurrencyRestoration(String bankCode, String currency, BigDecimal amount) {
this.bankCode = bankCode; this.currency = currency; this.amount = amount;
}
}
}

@ -3,6 +3,7 @@ package com.yau.digitalrmb.issuance.application.service;
import com.yau.digitalrmb.issuance.application.query.ReserveDeductionExecutionView;
import com.yau.digitalrmb.issuance.domain.model.CentralBankInstitutionAccount;
import com.yau.digitalrmb.issuance.domain.model.IssuanceAuditActor;
import com.yau.digitalrmb.issuance.domain.model.IssuanceOwner;
import com.yau.digitalrmb.issuance.domain.model.ReserveDeductionExecution;
import com.yau.digitalrmb.issuance.domain.model.ReserveDeductionNotification;
import com.yau.digitalrmb.issuance.domain.repository.CentralBankInstitutionAccountRepository;
@ -36,8 +37,9 @@ public class ReserveDeductionExecutionService {
}
@Transactional
public ReserveDeductionExecutionView execute(String transactionId, String reserveAccountNo, String reserveAccountName,
BigDecimal deductionAmount, IssuanceAuditActor actor) {
public ReserveDeductionExecutionView execute(String transactionId, IssuanceOwner owner, String reserveAccountNo,
String reserveAccountName, BigDecimal deductionAmount,
IssuanceAuditActor actor) {
requireActor(actor);
ReserveDeductionNotification notification = notificationRepository.findByTransactionId(required(transactionId, "交易信息标识"))
.orElseThrow(() -> new BusinessException(ErrorCode.RESOURCE_NOT_FOUND, "准备金扣减通知不存在"));
@ -45,7 +47,7 @@ public class ReserveDeductionExecutionService {
Optional<ReserveDeductionExecution> existing = executionRepository.findByTransactionId(transactionId);
if (existing.isPresent()) return ReserveDeductionExecutionView.from(existing.get());
CentralBankInstitutionAccount account = accountRepository.findByBankCodeForUpdate(notification.getBankCode())
CentralBankInstitutionAccount account = accountRepository.findByBankCodeForUpdate(owner, notification.getBankCode())
.orElseThrow(() -> new BusinessException(ErrorCode.RESOURCE_NOT_FOUND, "准备金账户不存在"));
existing = executionRepository.findByTransactionId(transactionId);
if (existing.isPresent()) return ReserveDeductionExecutionView.from(existing.get());
@ -62,17 +64,17 @@ public class ReserveDeductionExecutionService {
ReserveDeductionExecution execution = new ReserveDeductionExecution(notification.getRequestId(), notification.getTransactionId(),
beforeBalance, notification.getDeductionAmount(), afterBalance, "DEDUCTED", Instant.now(),
actor.getUserId(), actor.getUsername());
accountRepository.updateReserveBalance(account.getBankCode(), afterBalance);
accountRepository.updateReserveBalance(owner, account.getBankCode(), afterBalance);
executionRepository.save(execution);
return ReserveDeductionExecutionView.from(execution);
}
@Transactional
public ReserveDeductionExecutionView execute(String transactionId, IssuanceAuditActor actor) {
public ReserveDeductionExecutionView execute(String transactionId, IssuanceOwner owner, IssuanceAuditActor actor) {
ReserveDeductionNotification notification = notificationRepository
.findByTransactionId(required(transactionId, "交易信息标识"))
.orElseThrow(() -> new BusinessException(ErrorCode.RESOURCE_NOT_FOUND, "准备金扣减申请不存在"));
return execute(transactionId, notification.getReserveAccountNo(), notification.getReserveAccountName(),
return execute(transactionId, owner, notification.getReserveAccountNo(), notification.getReserveAccountName(),
notification.getDeductionAmount(), actor);
}
@ -82,7 +84,7 @@ public class ReserveDeductionExecutionService {
}
@Transactional
public ReserveDeductionExecutionView reverse(String transactionId, IssuanceAuditActor actor) {
public ReserveDeductionExecutionView reverse(String transactionId, IssuanceOwner owner, IssuanceAuditActor actor) {
requireActor(actor);
String requiredTransactionId = required(transactionId, "transaction id");
ReserveDeductionExecution execution = executionRepository.findByTransactionIdForUpdate(requiredTransactionId)
@ -103,7 +105,7 @@ public class ReserveDeductionExecutionService {
.findByTransactionId(requiredTransactionId)
.orElseThrow(() -> new BusinessException(ErrorCode.RESOURCE_NOT_FOUND,
"Reserve deduction notification does not exist"));
CentralBankInstitutionAccount account = accountRepository.findByBankCodeForUpdate(notification.getBankCode())
CentralBankInstitutionAccount account = accountRepository.findByBankCodeForUpdate(owner, notification.getBankCode())
.orElseThrow(() -> new BusinessException(ErrorCode.RESOURCE_NOT_FOUND,
"Reserve account does not exist"));
if (!notification.getReserveAccountNo().equals(account.getReserveAccountNo())
@ -113,7 +115,7 @@ public class ReserveDeductionExecutionService {
}
BigDecimal reversedBalance = account.getReserveBalance().add(execution.getDeductionAmount());
ReserveDeductionExecution reversed = execution.reversed(reversedBalance, Instant.now(), actor);
accountRepository.updateReserveBalance(account.getBankCode(), reversedBalance);
accountRepository.updateReserveBalance(owner, account.getBankCode(), reversedBalance);
executionRepository.save(reversed);
return ReserveDeductionExecutionView.from(reversed);
}

@ -8,6 +8,7 @@ import com.yau.digitalrmb.issuance.domain.model.CentralBankIssuanceBusinessRevie
import com.yau.digitalrmb.issuance.domain.model.CentralBankIssuanceReceipt;
import com.yau.digitalrmb.issuance.domain.model.CentralBankIssuanceVerification;
import com.yau.digitalrmb.issuance.domain.model.IssuanceAuditActor;
import com.yau.digitalrmb.issuance.domain.model.IssuanceOwner;
import com.yau.digitalrmb.issuance.domain.model.ReserveDeductionNotification;
import com.yau.digitalrmb.issuance.domain.repository.CentralBankInstitutionAccountRepository;
import com.yau.digitalrmb.issuance.domain.repository.CentralBankIssuanceBusinessReviewRepository;
@ -51,7 +52,7 @@ public class ReserveDeductionNotificationService {
}
@Transactional
public ReserveDeductionNotificationView send(UUID requestId, IssuanceAuditActor actor) {
public ReserveDeductionNotificationView send(UUID requestId, IssuanceOwner owner, IssuanceAuditActor actor) {
requireActor(actor);
requireVerificationPassed(requestId);
requireBusinessReviewPassed(requestId);
@ -63,7 +64,7 @@ public class ReserveDeductionNotificationService {
String organizationId = requiredText(payload, "orgId");
String currency = requiredText(payload, "currency");
BigDecimal deductionAmount = new BigDecimal(requiredText(payload, "totalAmount"));
CentralBankInstitutionAccount account = accountRepository.findByBankCode(bankCode)
CentralBankInstitutionAccount account = accountRepository.findByBankCode(owner, bankCode)
.orElseThrow(() -> new BusinessException(ErrorCode.VALIDATION_ERROR, "申请机构未开立准备金账户"));
if (!"NORMAL".equals(account.getStatus())) {
throw new BusinessException(ErrorCode.VALIDATION_ERROR, "申请机构准备金账户状态异常");

@ -1,8 +1,11 @@
package com.yau.digitalrmb.issuance.domain.repository;
import com.yau.digitalrmb.issuance.domain.model.CentralBankCurrencyVault;
import com.yau.digitalrmb.issuance.domain.model.IssuanceOwner;
import java.util.Optional;
public interface CentralBankCurrencyVaultRepository {
Optional<CentralBankCurrencyVault> findByCurrency(String currency);
/** 查询当前实训主体的央行发行库余额;首次访问时按其原始值初始化。 */
Optional<CentralBankCurrencyVault> findByCurrency(IssuanceOwner owner, String currency);
}

@ -1,10 +1,15 @@
package com.yau.digitalrmb.issuance.domain.repository;
import com.yau.digitalrmb.issuance.domain.model.CentralBankInstitutionAccount;
import com.yau.digitalrmb.issuance.domain.model.IssuanceOwner;
import java.util.Optional;
public interface CentralBankInstitutionAccountRepository {
Optional<CentralBankInstitutionAccount> findByBankCode(String bankCode);
Optional<CentralBankInstitutionAccount> findByBankCodeForUpdate(String bankCode);
void updateReserveBalance(String bankCode, java.math.BigDecimal reserveBalance);
/** 查询当前实训主体的准备金账户;首次访问时按其原始值初始化。 */
Optional<CentralBankInstitutionAccount> findByBankCode(IssuanceOwner owner, String bankCode);
Optional<CentralBankInstitutionAccount> findByBankCodeForUpdate(IssuanceOwner owner, String bankCode);
void updateReserveBalance(IssuanceOwner owner, String bankCode, java.math.BigDecimal reserveBalance);
}

@ -3,6 +3,7 @@ package com.yau.digitalrmb.issuance.domain.repository;
import com.yau.digitalrmb.issuance.domain.model.IssuanceApplicationId;
import com.yau.digitalrmb.issuance.domain.model.IssuanceAuditActor;
import com.yau.digitalrmb.issuance.domain.model.IssuanceBankInventory;
import com.yau.digitalrmb.issuance.domain.model.IssuanceOwner;
import com.yau.digitalrmb.issuance.domain.model.IssuanceRequest;
import java.util.Optional;
@ -20,5 +21,6 @@ public interface IssuanceRequestRepository {
return findById(id);
}
Optional<IssuanceBankInventory> findBuiltInInventory();
/** 查询当前实训主体的商业银行库存;首次访问时按其原始值初始化。 */
Optional<IssuanceBankInventory> findInventory(IssuanceOwner owner);
}

@ -10,6 +10,13 @@ import java.math.BigDecimal;
@Getter @Setter
@TableName("central_bank_currency_vault")
public class CentralBankCurrencyVaultEntity {
@TableId(value = "currency", type = IdType.INPUT) private String currency;
@TableId(type = IdType.AUTO) private Long id;
private String userId;
private Long schoolId;
private Long classId;
private String currency;
private BigDecimal availableBalance;
/** 逻辑删除标记:0 表示当前有效;重置实训时写入该行 id,保留历史轮次。 */
private Long deleted;
}

@ -11,11 +11,18 @@ import java.time.LocalDate;
@Getter @Setter
@TableName("central_bank_institution_account")
public class CentralBankInstitutionAccountEntity {
@TableId(value = "bank_code", type = IdType.INPUT) private String bankCode;
@TableId(type = IdType.AUTO) private Long id;
private String userId;
private Long schoolId;
private Long classId;
private String bankCode;
private String organizationId;
private String reserveAccountNo;
private String reserveAccountName;
private String status;
private LocalDate openedOn;
private BigDecimal reserveBalance;
/** 逻辑删除标记:0 表示当前有效;重置实训时写入该行 id,保留历史轮次。 */
private Long deleted;
}

@ -13,7 +13,15 @@ import java.time.LocalDateTime;
@Setter
@TableName("issuance_bank_inventory")
public class IssuanceBankInventoryEntity {
@TableId(value = "bank_code", type = IdType.INPUT)
@TableId(type = IdType.AUTO)
private Long id;
private String userId;
private Long schoolId;
private Long classId;
private String bankCode;
private BigDecimal currentBalance;
@ -21,4 +29,7 @@ public class IssuanceBankInventoryEntity {
private BigDecimal warningThreshold;
private LocalDateTime updatedAt;
/** 逻辑删除标记:0 表示当前有效;重置实训时写入该行 id,保留历史轮次。 */
private Long deleted;
}

@ -10,10 +10,20 @@ import java.math.BigDecimal;
@Mapper
public interface CentralBankInstitutionAccountMapper extends BaseMapper<CentralBankInstitutionAccountEntity> {
@Select("SELECT bank_code, organization_id, reserve_account_no, reserve_account_name, status, opened_on, reserve_balance "
+ "FROM central_bank_institution_account WHERE bank_code = #{bankCode} FOR UPDATE")
CentralBankInstitutionAccountEntity selectByBankCodeForUpdate(@Param("bankCode") String bankCode);
@Select("SELECT id, user_id, school_id, class_id, bank_code, organization_id, reserve_account_no, "
+ "reserve_account_name, status, opened_on, reserve_balance, deleted "
+ "FROM central_bank_institution_account "
+ "WHERE user_id = #{userId} AND school_id = #{schoolId} AND class_id = #{classId} "
+ "AND bank_code = #{bankCode} AND deleted = 0 FOR UPDATE")
CentralBankInstitutionAccountEntity selectByBankCodeForUpdate(@Param("userId") String userId,
@Param("schoolId") long schoolId,
@Param("classId") long classId,
@Param("bankCode") String bankCode);
@Update("UPDATE central_bank_institution_account SET reserve_balance = #{reserveBalance} WHERE bank_code = #{bankCode}")
int updateReserveBalance(@Param("bankCode") String bankCode, @Param("reserveBalance") BigDecimal reserveBalance);
@Update("UPDATE central_bank_institution_account SET reserve_balance = #{reserveBalance} "
+ "WHERE user_id = #{userId} AND school_id = #{schoolId} AND class_id = #{classId} "
+ "AND bank_code = #{bankCode} AND deleted = 0")
int updateReserveBalance(@Param("userId") String userId, @Param("schoolId") long schoolId,
@Param("classId") long classId, @Param("bankCode") String bankCode,
@Param("reserveBalance") BigDecimal reserveBalance);
}

@ -1,18 +1,81 @@
package com.yau.digitalrmb.issuance.infrastructure.persistence.repository;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yau.digitalrmb.issuance.domain.model.CentralBankCurrencyVault;
import com.yau.digitalrmb.issuance.domain.model.IssuanceAssetDefaults;
import com.yau.digitalrmb.issuance.domain.model.IssuanceOwner;
import com.yau.digitalrmb.issuance.domain.repository.CentralBankCurrencyVaultRepository;
import com.yau.digitalrmb.issuance.infrastructure.persistence.entity.CentralBankCurrencyVaultEntity;
import com.yau.digitalrmb.issuance.infrastructure.persistence.mapper.CentralBankCurrencyVaultMapper;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
@Repository
public class MybatisCentralBankCurrencyVaultRepository implements CentralBankCurrencyVaultRepository {
private final CentralBankCurrencyVaultMapper mapper;
public MybatisCentralBankCurrencyVaultRepository(CentralBankCurrencyVaultMapper mapper) { this.mapper = mapper; }
public Optional<CentralBankCurrencyVault> findByCurrency(String currency) {
CentralBankCurrencyVaultEntity entity = mapper.selectById(currency);
return entity == null ? Optional.<CentralBankCurrencyVault>empty() : Optional.of(new CentralBankCurrencyVault(entity.getCurrency(), entity.getAvailableBalance()));
public MybatisCentralBankCurrencyVaultRepository(CentralBankCurrencyVaultMapper mapper) {
this.mapper = mapper;
}
@Override
public Optional<CentralBankCurrencyVault> findByCurrency(IssuanceOwner owner, String currency) {
CentralBankCurrencyVaultEntity entity = select(owner, currency);
if (entity == null) {
entity = initialize(owner, currency);
}
return entity == null ? Optional.<CentralBankCurrencyVault>empty()
: Optional.of(new CentralBankCurrencyVault(entity.getCurrency(), entity.getAvailableBalance()));
}
private CentralBankCurrencyVaultEntity select(IssuanceOwner owner, String currency) {
return mapper.selectOne(new LambdaQueryWrapper<CentralBankCurrencyVaultEntity>()
.eq(CentralBankCurrencyVaultEntity::getUserId, owner.getUserId())
.eq(CentralBankCurrencyVaultEntity::getSchoolId, owner.getSchoolId())
.eq(CentralBankCurrencyVaultEntity::getClassId, owner.getClassId())
.eq(CentralBankCurrencyVaultEntity::getCurrency, currency)
.eq(CentralBankCurrencyVaultEntity::getDeleted, 0L)
.orderByAsc(CentralBankCurrencyVaultEntity::getId)
.last("LIMIT 1"));
}
/** 首次实训时按原始值落一条该学生专属的发行库记录;并发下若已被其他请求建好则直接复用。 */
private CentralBankCurrencyVaultEntity initialize(IssuanceOwner owner, String currency) {
CentralBankCurrencyVaultEntity entity = new CentralBankCurrencyVaultEntity();
entity.setUserId(owner.getUserId());
entity.setSchoolId(owner.getSchoolId());
entity.setClassId(owner.getClassId());
entity.setCurrency(currency);
entity.setAvailableBalance(IssuanceAssetDefaults.INITIAL_VAULT_BALANCE);
try {
mapper.insert(entity);
} catch (DuplicateKeyException duplicate) {
return select(owner, currency);
}
convergeDuplicates(owner, currency);
CentralBankCurrencyVaultEntity current = select(owner, currency);
return current == null ? entity : current;
}
/** 该表不使用唯一键:并发首次初始化可能插出多条有效行,只保留 id 最小的一条,其余逻辑删除。 */
private void convergeDuplicates(IssuanceOwner owner, String currency) {
List<CentralBankCurrencyVaultEntity> rows = mapper.selectList(
new LambdaQueryWrapper<CentralBankCurrencyVaultEntity>()
.select(CentralBankCurrencyVaultEntity::getId)
.eq(CentralBankCurrencyVaultEntity::getUserId, owner.getUserId())
.eq(CentralBankCurrencyVaultEntity::getSchoolId, owner.getSchoolId())
.eq(CentralBankCurrencyVaultEntity::getClassId, owner.getClassId())
.eq(CentralBankCurrencyVaultEntity::getCurrency, currency)
.eq(CentralBankCurrencyVaultEntity::getDeleted, 0L)
.orderByAsc(CentralBankCurrencyVaultEntity::getId));
for (int index = 1; index < rows.size(); index++) {
mapper.update(null, new LambdaUpdateWrapper<CentralBankCurrencyVaultEntity>()
.setSql("deleted = id")
.eq(CentralBankCurrencyVaultEntity::getId, rows.get(index).getId()));
}
}
}

@ -1,27 +1,103 @@
package com.yau.digitalrmb.issuance.infrastructure.persistence.repository;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yau.digitalrmb.issuance.domain.model.CentralBankInstitutionAccount;
import com.yau.digitalrmb.issuance.domain.model.IssuanceAssetDefaults;
import com.yau.digitalrmb.issuance.domain.model.IssuanceOwner;
import com.yau.digitalrmb.issuance.domain.repository.CentralBankInstitutionAccountRepository;
import com.yau.digitalrmb.issuance.infrastructure.persistence.entity.CentralBankInstitutionAccountEntity;
import com.yau.digitalrmb.issuance.infrastructure.persistence.mapper.CentralBankInstitutionAccountMapper;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
@Repository
public class MybatisCentralBankInstitutionAccountRepository implements CentralBankInstitutionAccountRepository {
private final CentralBankInstitutionAccountMapper mapper;
public MybatisCentralBankInstitutionAccountRepository(CentralBankInstitutionAccountMapper mapper) { this.mapper = mapper; }
public Optional<CentralBankInstitutionAccount> findByBankCode(String bankCode) {
return toDomain(mapper.selectById(bankCode));
public MybatisCentralBankInstitutionAccountRepository(CentralBankInstitutionAccountMapper mapper) {
this.mapper = mapper;
}
@Override
public Optional<CentralBankInstitutionAccount> findByBankCodeForUpdate(String bankCode) {
return toDomain(mapper.selectByBankCodeForUpdate(bankCode));
public Optional<CentralBankInstitutionAccount> findByBankCode(IssuanceOwner owner, String bankCode) {
return toDomain(selectOrInitialize(owner, bankCode));
}
@Override
public Optional<CentralBankInstitutionAccount> findByBankCodeForUpdate(IssuanceOwner owner, String bankCode) {
selectOrInitialize(owner, bankCode);
return toDomain(mapper.selectByBankCodeForUpdate(owner.getUserId(), owner.getSchoolId(),
owner.getClassId(), bankCode));
}
@Override
public void updateReserveBalance(String bankCode, java.math.BigDecimal reserveBalance) {
if (mapper.updateReserveBalance(bankCode, reserveBalance) != 1) throw new IllegalStateException("更新准备金余额失败");
public void updateReserveBalance(IssuanceOwner owner, String bankCode, java.math.BigDecimal reserveBalance) {
if (mapper.updateReserveBalance(owner.getUserId(), owner.getSchoolId(), owner.getClassId(),
bankCode, reserveBalance) != 1) {
throw new IllegalStateException("更新准备金余额失败");
}
}
private CentralBankInstitutionAccountEntity select(IssuanceOwner owner, String bankCode) {
return mapper.selectOne(new LambdaQueryWrapper<CentralBankInstitutionAccountEntity>()
.eq(CentralBankInstitutionAccountEntity::getUserId, owner.getUserId())
.eq(CentralBankInstitutionAccountEntity::getSchoolId, owner.getSchoolId())
.eq(CentralBankInstitutionAccountEntity::getClassId, owner.getClassId())
.eq(CentralBankInstitutionAccountEntity::getBankCode, bankCode)
.eq(CentralBankInstitutionAccountEntity::getDeleted, 0L)
.orderByAsc(CentralBankInstitutionAccountEntity::getId)
.last("LIMIT 1"));
}
/** 首次实训时按原始值落一条该学生专属的准备金账户;并发下若已被其他请求建好则直接复用。 */
private CentralBankInstitutionAccountEntity selectOrInitialize(IssuanceOwner owner, String bankCode) {
CentralBankInstitutionAccountEntity existing = select(owner, bankCode);
if (existing != null) {
return existing;
}
CentralBankInstitutionAccountEntity entity = new CentralBankInstitutionAccountEntity();
entity.setUserId(owner.getUserId());
entity.setSchoolId(owner.getSchoolId());
entity.setClassId(owner.getClassId());
entity.setBankCode(bankCode);
entity.setOrganizationId(IssuanceAssetDefaults.BUILT_IN_ORGANIZATION_ID);
entity.setReserveAccountNo(IssuanceAssetDefaults.BUILT_IN_RESERVE_ACCOUNT_NO);
entity.setReserveAccountName(IssuanceAssetDefaults.BUILT_IN_RESERVE_ACCOUNT_NAME);
entity.setStatus(IssuanceAssetDefaults.BUILT_IN_ACCOUNT_STATUS);
entity.setOpenedOn(IssuanceAssetDefaults.BUILT_IN_ACCOUNT_OPENED_ON);
entity.setReserveBalance(IssuanceAssetDefaults.INITIAL_RESERVE_BALANCE);
try {
mapper.insert(entity);
} catch (DuplicateKeyException duplicate) {
return select(owner, bankCode);
}
convergeDuplicates(owner, bankCode);
CentralBankInstitutionAccountEntity current = select(owner, bankCode);
return current == null ? entity : current;
}
/** 该表不使用唯一键:并发首次初始化可能插出多条有效行,只保留 id 最小的一条,其余逻辑删除。 */
private void convergeDuplicates(IssuanceOwner owner, String bankCode) {
List<CentralBankInstitutionAccountEntity> rows = mapper.selectList(
new LambdaQueryWrapper<CentralBankInstitutionAccountEntity>()
.select(CentralBankInstitutionAccountEntity::getId)
.eq(CentralBankInstitutionAccountEntity::getUserId, owner.getUserId())
.eq(CentralBankInstitutionAccountEntity::getSchoolId, owner.getSchoolId())
.eq(CentralBankInstitutionAccountEntity::getClassId, owner.getClassId())
.eq(CentralBankInstitutionAccountEntity::getBankCode, bankCode)
.eq(CentralBankInstitutionAccountEntity::getDeleted, 0L)
.orderByAsc(CentralBankInstitutionAccountEntity::getId));
for (int index = 1; index < rows.size(); index++) {
mapper.update(null, new LambdaUpdateWrapper<CentralBankInstitutionAccountEntity>()
.setSql("deleted = id")
.eq(CentralBankInstitutionAccountEntity::getId, rows.get(index).getId()));
}
}
private Optional<CentralBankInstitutionAccount> toDomain(CentralBankInstitutionAccountEntity entity) {
return entity == null ? Optional.<CentralBankInstitutionAccount>empty() : Optional.of(new CentralBankInstitutionAccount(
entity.getBankCode(), entity.getOrganizationId(), entity.getReserveAccountNo(), entity.getReserveAccountName(), entity.getStatus(),

@ -1,11 +1,14 @@
package com.yau.digitalrmb.issuance.infrastructure.persistence.repository;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yau.digitalrmb.issuance.domain.model.CentralBankReceiveStatus;
import com.yau.digitalrmb.issuance.domain.model.DenominationItem;
import com.yau.digitalrmb.issuance.domain.model.IssuanceApplicationId;
import com.yau.digitalrmb.issuance.domain.model.IssuanceAuditActor;
import com.yau.digitalrmb.issuance.domain.model.IssuanceBankInventory;
import com.yau.digitalrmb.issuance.domain.model.IssuanceAssetDefaults;
import com.yau.digitalrmb.issuance.domain.model.IssuanceOwner;
import com.yau.digitalrmb.issuance.domain.model.IssuanceRequest;
import com.yau.digitalrmb.issuance.domain.model.IssuanceRequestStatus;
import com.yau.digitalrmb.issuance.domain.repository.IssuanceRequestRepository;
@ -15,10 +18,12 @@ import com.yau.digitalrmb.issuance.infrastructure.persistence.entity.IssuanceReq
import com.yau.digitalrmb.issuance.infrastructure.persistence.mapper.IssuanceBankInventoryMapper;
import com.yau.digitalrmb.issuance.infrastructure.persistence.mapper.IssuanceRequestDenominationMapper;
import com.yau.digitalrmb.issuance.infrastructure.persistence.mapper.IssuanceRequestMapper;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
@ -28,7 +33,6 @@ import java.util.UUID;
@Repository
public class MybatisIssuanceRequestRepository implements IssuanceRequestRepository {
private static final String BUILT_IN_INVENTORY_BANK_CODE = "BKCHCNBJ00001";
private final IssuanceRequestMapper requestMapper;
private final IssuanceRequestDenominationMapper denominationMapper;
private final IssuanceBankInventoryMapper inventoryMapper;
@ -110,16 +114,69 @@ public class MybatisIssuanceRequestRepository implements IssuanceRequestReposito
}
@Override
public Optional<IssuanceBankInventory> findBuiltInInventory() {
IssuanceBankInventoryEntity inventory = inventoryMapper.selectById(BUILT_IN_INVENTORY_BANK_CODE);
public Optional<IssuanceBankInventory> findInventory(IssuanceOwner owner) {
IssuanceBankInventoryEntity inventory = selectInventory(owner);
if (inventory == null) {
return Optional.empty();
inventory = initializeInventory(owner);
}
BigDecimal suggested = inventory.getWarningThreshold().subtract(inventory.getCurrentBalance());
return Optional.of(new IssuanceBankInventory(inventory.getBankCode(), inventory.getCurrentBalance(),
inventory.getWarningThreshold(), suggested.max(BigDecimal.ZERO).setScale(2)));
}
private IssuanceBankInventoryEntity selectInventory(IssuanceOwner owner) {
return inventoryMapper.selectOne(new LambdaQueryWrapper<IssuanceBankInventoryEntity>()
.eq(IssuanceBankInventoryEntity::getUserId, owner.getUserId())
.eq(IssuanceBankInventoryEntity::getSchoolId, owner.getSchoolId())
.eq(IssuanceBankInventoryEntity::getClassId, owner.getClassId())
.eq(IssuanceBankInventoryEntity::getBankCode, IssuanceAssetDefaults.BUILT_IN_BANK_CODE)
.eq(IssuanceBankInventoryEntity::getDeleted, 0L)
.orderByAsc(IssuanceBankInventoryEntity::getId)
.last("LIMIT 1"));
}
/** 首次实训时按原始值落一条该学生专属的库存记录;并发下若已被其他请求建好则直接复用。 */
private IssuanceBankInventoryEntity initializeInventory(IssuanceOwner owner) {
IssuanceBankInventoryEntity entity = new IssuanceBankInventoryEntity();
entity.setUserId(owner.getUserId());
entity.setSchoolId(owner.getSchoolId());
entity.setClassId(owner.getClassId());
entity.setBankCode(IssuanceAssetDefaults.BUILT_IN_BANK_CODE);
entity.setCurrentBalance(IssuanceAssetDefaults.INITIAL_BANK_INVENTORY_BALANCE);
entity.setWarningThreshold(IssuanceAssetDefaults.BANK_INVENTORY_WARNING_THRESHOLD);
entity.setUpdatedAt(LocalDateTime.now());
try {
inventoryMapper.insert(entity);
} catch (DuplicateKeyException duplicate) {
IssuanceBankInventoryEntity existing = selectInventory(owner);
if (existing == null) {
throw duplicate;
}
return existing;
}
convergeDuplicateInventory(owner);
IssuanceBankInventoryEntity current = selectInventory(owner);
return current == null ? entity : current;
}
/** 该表不使用唯一键:并发首次初始化可能插出多条有效行,只保留 id 最小的一条,其余逻辑删除。 */
private void convergeDuplicateInventory(IssuanceOwner owner) {
List<IssuanceBankInventoryEntity> rows = inventoryMapper.selectList(
new LambdaQueryWrapper<IssuanceBankInventoryEntity>()
.select(IssuanceBankInventoryEntity::getId)
.eq(IssuanceBankInventoryEntity::getUserId, owner.getUserId())
.eq(IssuanceBankInventoryEntity::getSchoolId, owner.getSchoolId())
.eq(IssuanceBankInventoryEntity::getClassId, owner.getClassId())
.eq(IssuanceBankInventoryEntity::getBankCode, IssuanceAssetDefaults.BUILT_IN_BANK_CODE)
.eq(IssuanceBankInventoryEntity::getDeleted, 0L)
.orderByAsc(IssuanceBankInventoryEntity::getId));
for (int index = 1; index < rows.size(); index++) {
inventoryMapper.update(null, new LambdaUpdateWrapper<IssuanceBankInventoryEntity>()
.setSql("deleted = id")
.eq(IssuanceBankInventoryEntity::getId, rows.get(index).getId()));
}
}
private IssuanceRequestEntity toEntity(IssuanceRequest request) {
IssuanceRequestEntity entity = new IssuanceRequestEntity();
entity.setId(request.getId().value().toString());

@ -20,6 +20,9 @@ import com.yau.digitalrmb.issuance.interfaces.dto.DenominationPlanRequest;
import com.yau.digitalrmb.issuance.interfaces.dto.UpdateIssuanceRequest;
import com.yau.digitalrmb.issuance.interfaces.dto.IssuanceActionRequest;
import com.yau.digitalrmb.security.application.CurrentUser;
import com.yau.digitalrmb.issuance.domain.model.IssuanceOwner;
import com.yau.digitalrmb.security.context.AuthContextHolder;
import com.yau.digitalrmb.security.context.JwtUser;
import com.yau.digitalrmb.security.application.CurrentUserService;
import com.yau.digitalrmb.shared.api.ApiResponse;
import com.yau.digitalrmb.shared.api.ErrorCode;
@ -74,9 +77,24 @@ public class CommercialBankIssuanceController {
}
@GetMapping("/inventory")
@Operation(summary = "查询货币需求信息", description = "查询库存余额、预警阈值和建议补充金额")
@Operation(summary = "查询货币需求信息", description = "查询当前实训学生的库存余额、预警阈值和建议补充金额")
public ApiResponse<CommercialBankInventoryView> inventory() {
return ok(service.getInventory());
return ok(service.getInventory(currentOwner()));
}
/** 库存按当前登录学生隔离,身份取自登录凭据(与其它步骤的 actor 口径一致)。 */
private IssuanceOwner currentOwner() {
JwtUser user = AuthContextHolder.get();
return IssuanceOwner.of(user.getUserId(), optionalNumeric(user.getSchoolId()),
optionalNumeric(user.getClassId()));
}
private long optionalNumeric(String value) {
try {
return value == null ? 0L : Long.parseLong(value.trim());
} catch (RuntimeException exception) {
return 0L;
}
}
@GetMapping("/denomination-plan/default")

@ -68,13 +68,7 @@ public class PlatformTokenVerifier {
if (password == null || password.trim().isEmpty()) {
password = "123qwe";
}
int roleId;
JsonNode roleNode = payload.path("roleid");
if (roleNode.isMissingNode() || !roleNode.canConvertToLong()) {
roleId = 4;
} else {
roleId = (int) roleNode.asLong();
}
int roleId = parseRoleId(payload);
String displayName = optionalText(payload, "name");
if (displayName == null || displayName.trim().isEmpty()) {
displayName = username;
@ -135,4 +129,26 @@ public class PlatformTokenVerifier {
private PlatformTokenException invalid() {
return new PlatformTokenException("平台登录凭据无效");
}
/**
* 解析角色ID。智云 token 中 roleid 以字符串("3")或数字(3)形式出现,
* 需兼容两种形态;缺失或无法解析时回退默认 4(学生)。
*/
private int parseRoleId(JsonNode payload) {
for (String name : new String[]{"roleid", "roleId", "role"}) {
JsonNode node = payload.path(name);
if (node.isMissingNode() || node.isNull()) {
continue;
}
String text = node.asText();
if (text != null && !text.trim().isEmpty()) {
try {
return Integer.parseInt(text.trim());
} catch (NumberFormatException ignore) {
// 继续尝试下一个别名
}
}
}
return 4;
}
}

@ -24,7 +24,7 @@ import java.time.format.DateTimeFormatter;
public class WalletOpeningService {
private static final DateTimeFormatter TIMESTAMP_FORMAT = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
/** 原型“用户信息”面板中的固定身份信息,输出申请报文时必须与之一致 */
/** 原型“用户信息”面板中的默认身份信息:当用户档案里没有对应字段时作为兜底 */
private static final String FIXED_PHONE = "13800138000";
private static final String FIXED_ID_NUMBER = "110101199001011234";
private static final String FIXED_BANK_CARD_NUMBER = "6216610100001234567";
@ -48,6 +48,8 @@ public class WalletOpeningService {
jwtUser.getUserName(), jwtUser.getPhone());
return temp;
});
// 以当前登录用户身份为准刷新“用户信息”面板,避免展示首次登录时落库的旧手机号
app.refreshTokenUserInfo(jwtUser.getUserName(), jwtUser.getPhone());
return new UserWalletPageResult(app);
}
@ -61,6 +63,7 @@ public class WalletOpeningService {
jwtUser.getUserName(), jwtUser.getPhone());
return walletRepository.save(newApp);
});
app.refreshTokenUserInfo(jwtUser.getUserName(), jwtUser.getPhone());
app.updateFaceRecognition(status);
walletRepository.update(app);
return new FaceRecognitionResult(status);
@ -76,6 +79,7 @@ public class WalletOpeningService {
jwtUser.getUserName(), jwtUser.getPhone());
return walletRepository.save(newApp);
});
app.refreshTokenUserInfo(jwtUser.getUserName(), jwtUser.getPhone());
// 支持重复点击:已输出过则按最新表单内容重新生成报文并覆盖,不再拦截
if (app.getFaceRecognitionStatus() == null || app.getFaceRecognitionStatus() != 2) {
@ -85,8 +89,8 @@ public class WalletOpeningService {
throw new BusinessException(ErrorCode.VALIDATION_ERROR, "请选择数字钱包类型");
}
// 校验手机号、身份证号、银行卡号必须与原型“用户信息”一致,不一致则错误数+1
validateFixedUserInfo(subject, request);
// 校验手机号、身份证号、银行卡号必须与“用户信息”面板一致,不一致则错误数+1
validateFixedUserInfo(subject, app, request);
BigDecimal accountBalance = request.getAccountBalance();
if (accountBalance == null || accountBalance.compareTo(BigDecimal.ZERO) <= 0) {
@ -153,28 +157,30 @@ public class WalletOpeningService {
}
/**
* 校验手机号、身份证号、银行卡号必须与原型“用户信息”面板一致。
* 校验手机号、身份证号、银行卡号必须与“用户信息”面板一致。
* 期望值优先取用户档案(手机号来自登录用户,身份证/银行卡来自钱包申请记录),
* 档案缺失时回退原型固定值;手机号额外兼容原型演示号码 13800138000。
* 任一字段不一致:错误数+1(独立事务记录),并拒绝本次输出。
*/
private void validateFixedUserInfo(InstitutionKeySubject subject, WalletApplicationRequest request) {
private void validateFixedUserInfo(InstitutionKeySubject subject, WalletApplication app, WalletApplicationRequest request) {
java.util.List<String> mismatches = new java.util.ArrayList<>();
String expectedPhone = firstNonBlank(app.getPhone(), FIXED_PHONE);
String phone = normalized(request.getInputPhone());
if (!FIXED_PHONE.equals(phone)) {
// 兼容两种通过方式:与“用户信息”面板的手机号一致,或直接使用原型演示号码 13800138000
if (!expectedPhone.equals(phone) && !FIXED_PHONE.equals(phone)) {
mismatches.add("手机号");
}
String idNumber = normalized(request.getInputIdNumber() != null
&& !request.getInputIdNumber().trim().isEmpty()
? request.getInputIdNumber() : request.getIdNumber());
if (!FIXED_ID_NUMBER.equals(idNumber)) {
String expectedIdNumber = firstNonBlank(app.getIdNumber(), FIXED_ID_NUMBER);
String idNumber = normalized(firstNonBlank(request.getInputIdNumber(), request.getIdNumber()));
if (!expectedIdNumber.equals(idNumber)) {
mismatches.add("身份证号");
}
String bankCardNumber = normalized(request.getInputBankCardNumber() != null
&& !request.getInputBankCardNumber().trim().isEmpty()
? request.getInputBankCardNumber() : request.getBankCardNumber());
if (!FIXED_BANK_CARD_NUMBER.equals(bankCardNumber)) {
String expectedBankCardNumber = firstNonBlank(app.getBankCardNumber(), FIXED_BANK_CARD_NUMBER);
String bankCardNumber = normalized(firstNonBlank(request.getInputBankCardNumber(), request.getBankCardNumber()));
if (!expectedBankCardNumber.equals(bankCardNumber)) {
mismatches.add("银行卡号");
}
@ -185,6 +191,11 @@ public class WalletOpeningService {
}
}
/** 取第一个去除首尾空格后非空的值,用于“用户填写值优先、档案值兜底” */
private String firstNonBlank(String primary, String fallback) {
return normalized(primary).isEmpty() ? normalized(fallback) : normalized(primary);
}
/** 去除空格与全角空格后比较,兼容“621661 010000 1234567”这类带分隔的输入 */
private String normalized(String value) {
if (value == null) {

@ -1,6 +1,6 @@
spring:
datasource:
url: jdbc:mysql://${DB_HOST:118.31.7.2}:${DB_PORT:3306}/${DB_NAME:digital_rmb}?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&useSSL=false&useInformationSchema=true&allowPublicKeyRetrieval=true&connectTimeout=10000&socketTimeout=30000
url: jdbc:mysql://${DB_HOST:120.78.220.29}:${DB_PORT:3307}/${DB_NAME:digital_rmb}?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&useSSL=false&useInformationSchema=true&allowPublicKeyRetrieval=true&connectTimeout=10000&socketTimeout=30000
username: ${DB_USER:root}
password: ${DB_PWD:sztzjy2017}
driver-class-name: com.mysql.cj.jdbc.Driver

@ -4,15 +4,15 @@ spring:
application:
name: digital-rmb-backend
datasource:
url: ${DIGITAL_RMB_DB_URL}
username: ${DIGITAL_RMB_DB_USERNAME}
password: ${DIGITAL_RMB_DB_PASSWORD}
url: ${DIGITAL_RMB_DB_URL:jdbc:mysql://120.78.220.29:3307/digital_rmb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&useSSL=false&useInformationSchema=true&allowPublicKeyRetrieval=true&connectTimeout=10000&socketTimeout=30000}
username: ${DIGITAL_RMB_DB_USERNAME:root}
password: ${DIGITAL_RMB_DB_PASSWORD:sztzjy2017}
hikari:
minimum-idle: 2
driver-class-name: com.mysql.cj.jdbc.Driver
sql:
init:
mode: always
mode: never
encoding: UTF-8
logging:
file:
@ -27,7 +27,7 @@ server:
force: true
security:
jwt:
secret: ${DIGITAL_RMB_JWT_SECRET}
secret: ${DIGITAL_RMB_JWT_SECRET:0123456789012345678901234567890123456789012345678901234567890123}
access-token-ttl: PT4H
management:
endpoints:

@ -0,0 +1,96 @@
package com.yau.digitalrmb.corporatewallet.application;
import com.yau.digitalrmb.corporatewallet.domain.CorporateWalletApplication;
import com.yau.digitalrmb.corporatewallet.domain.CorporateWalletApplicationRepository;
import com.yau.digitalrmb.corporatewallet.domain.RemoteWalletApplication;
import com.yau.digitalrmb.corporatewallet.domain.RemoteWalletApplicationRepository;
import com.yau.digitalrmb.institutionidentity.application.InstitutionKeySubject;
import com.yau.digitalrmb.institutionidentity.infrastructure.SmInstitutionIdentityCryptography;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class CorporateWalletServiceTest {
private static final InstitutionKeySubject SUBJECT = new InstitutionKeySubject("corp-user", 1001L, 2001L);
private static final String DIGEST = "C2DBCCFE515B4570EABAD62B74385CF70CBF1CBC5ED7C7F7F58BEEE8722B8BB6";
@Mock private CorporateWalletApplicationRepository repository;
@Mock private RemoteWalletApplicationRepository remoteRepository;
@Mock private SmInstitutionIdentityCryptography cryptography;
@Mock private SalaryScoreService scoreService;
@InjectMocks private CorporateWalletService service;
@Test
void outputWalletPrefixesGeneratedWalletIdWithCorp() {
CorporateWalletApplication app = CorporateWalletApplication.create(
SUBJECT.getUserId(), SUBJECT.getSchoolId(), SUBJECT.getClassId());
app.setCreditCode("91440101MA5XXXXXX");
app.computeDigest("SM3", DIGEST);
when(repository.findLatest(SUBJECT.getUserId(), SUBJECT.getSchoolId(), SUBJECT.getClassId()))
.thenReturn(Optional.of(app));
when(remoteRepository.findActivatedByCreditCode("91440101MA5XXXXXX",
SUBJECT.getUserId(), SUBJECT.getSchoolId(), SUBJECT.getClassId()))
.thenReturn(Optional.empty());
CorporateWalletResult result = service.outputWallet(SUBJECT);
assertThat(result.getWalletId()).isEqualTo("CORP_" + DIGEST);
assertThat(app.getWalletId()).isEqualTo("CORP_" + DIGEST);
}
@Test
void outputWalletNormalizesHistoricalWalletIdWithoutPrefix() {
CorporateWalletApplication app = CorporateWalletApplication.create(
SUBJECT.getUserId(), SUBJECT.getSchoolId(), SUBJECT.getClassId());
app.setCreditCode("91440101MA5XXXXXX");
app.computeDigest("SM3", DIGEST);
app.activateWallet(DIGEST, "20261031120000");
when(repository.findLatest(SUBJECT.getUserId(), SUBJECT.getSchoolId(), SUBJECT.getClassId()))
.thenReturn(Optional.of(app));
CorporateWalletResult result = service.outputWallet(SUBJECT);
assertThat(result.getWalletId()).isEqualTo("CORP_" + DIGEST);
assertThat(app.getWalletId()).isEqualTo("CORP_" + DIGEST);
}
@Test
void outputWalletKeepsSharedRemoteWalletIdPrefixed() {
CorporateWalletApplication app = CorporateWalletApplication.create(
SUBJECT.getUserId(), SUBJECT.getSchoolId(), SUBJECT.getClassId());
app.setCorpName("创新科技公司");
app.setCreditCode("91440101MA5XXXXXX");
app.setLegalPerson("张三");
app.setApplyTime("20261031120000");
app.computeDigest("SM3", DIGEST);
RemoteWalletApplication remote = RemoteWalletApplication.create(
SUBJECT.getUserId(), SUBJECT.getSchoolId(), SUBJECT.getClassId());
remote.setCorpName("创新科技公司");
remote.setCreditCode("91440101MA5XXXXXX");
remote.setLegalPerson("张三");
remote.setPhone("13800138000");
remote.setApplyTime("20261031120000");
remote.activateWallet(DIGEST, "20261031121000");
when(repository.findLatest(SUBJECT.getUserId(), SUBJECT.getSchoolId(), SUBJECT.getClassId()))
.thenReturn(Optional.of(app));
when(remoteRepository.findActivatedByCreditCode("91440101MA5XXXXXX",
SUBJECT.getUserId(), SUBJECT.getSchoolId(), SUBJECT.getClassId()))
.thenReturn(Optional.of(remote));
CorporateWalletResult result = service.outputWallet(SUBJECT);
assertThat(result.getWalletId()).isEqualTo("CORP_" + DIGEST);
assertThat(remote.getWalletId()).isEqualTo("CORP_" + DIGEST);
}
}

@ -148,8 +148,13 @@ class ExchangeControllerTest {
jdbc.update("DELETE FROM institution_sm2_key WHERE user_id=?", USER_ID);
jdbc.update("DELETE FROM institution_identifier_application WHERE user_id=?", USER_ID);
jdbc.update("DELETE FROM sys_user WHERE user_id=?", USER_ID);
jdbc.update("UPDATE issuance_bank_inventory SET current_balance=49950000.00,updated_at=CURRENT_TIMESTAMP "
+ "WHERE bank_code='BKCHCNBJ00001'");
jdbc.update("DELETE FROM issuance_bank_inventory "
+ "WHERE user_id=? AND school_id=? AND class_id=? AND bank_code='BKCHCNBJ00001'",
USER_ID, 1999L, 2999L);
jdbc.update("INSERT INTO issuance_bank_inventory "
+ "(user_id,school_id,class_id,bank_code,current_balance,warning_threshold,updated_at,deleted) "
+ "VALUES (?,?,?,'BKCHCNBJ00001',49950000.00,50000000.00,CURRENT_TIMESTAMP,0)",
USER_ID, 1999L, 2999L);
}
@Test
@ -245,7 +250,13 @@ class ExchangeControllerTest {
jdbc.update("UPDATE commercial_bank_currency SET denomination=1289 WHERE currency_id='DC_EXCHANGE_TEST_1'");
jdbc.update("UPDATE commercial_bank_currency SET denomination=1300 WHERE currency_id='DC_EXCHANGE_TEST_2'");
}
jdbc.update("UPDATE issuance_bank_inventory SET current_balance=? WHERE bank_code='BKCHCNBJ00001'", moduleTwoStock);
jdbc.update("DELETE FROM issuance_bank_inventory "
+ "WHERE user_id=? AND school_id=? AND class_id=? AND bank_code='BKCHCNBJ00001'",
USER_ID, 1999L, 2999L);
jdbc.update("INSERT INTO issuance_bank_inventory "
+ "(user_id,school_id,class_id,bank_code,current_balance,warning_threshold,updated_at,deleted) "
+ "VALUES (?,?,?,'BKCHCNBJ00001',?,50000000.00,CURRENT_TIMESTAMP,0)",
USER_ID, 1999L, 2999L, moduleTwoStock);
String[] values = createHeldExchange("5000.00");
String exchangeId = values[1];
String accountId = values[2];
@ -273,8 +284,9 @@ class ExchangeControllerTest {
"WHERE c.issuance_request_id=? AND o.owner_type='WALLET' " +
"AND o.owner_id='WALLET_EXCHANGE_TEST' AND o.status='AVAILABLE'",
Integer.class, exchangeId)).isEqualTo(50);
assertThat(jdbc.queryForObject("SELECT current_balance FROM issuance_bank_inventory WHERE bank_code='BKCHCNBJ00001'",
java.math.BigDecimal.class)).isEqualByComparingTo(String.valueOf(moduleTwoStock));
assertThat(jdbc.queryForObject("SELECT current_balance FROM issuance_bank_inventory "
+ "WHERE user_id=? AND school_id=? AND class_id=? AND bank_code='BKCHCNBJ00001' AND deleted=0",
java.math.BigDecimal.class, USER_ID, 1999L, 2999L)).isEqualByComparingTo(String.valueOf(moduleTwoStock));
assertThat(jdbc.queryForObject("SELECT COALESCE(SUM(c.denomination),0) FROM commercial_bank_currency c " +
"JOIN central_bank_currency_ownership o ON o.currency_id=c.currency_id " +
"WHERE c.issuance_request_id=? AND o.owner_type='BANK' AND o.status='AVAILABLE'",

@ -182,7 +182,7 @@ class CommercialBankIssuanceApplicationServiceTest {
}
@Override
public Optional<IssuanceBankInventory> findBuiltInInventory() {
public Optional<IssuanceBankInventory> findInventory(com.yau.digitalrmb.issuance.domain.model.IssuanceOwner owner) {
return Optional.of(new IssuanceBankInventory("BKCHCNBJ00001", new BigDecimal("49960000.00"),
new BigDecimal("50000000.00"), new BigDecimal("50000.00")));
}

@ -88,10 +88,15 @@ class DigitalCurrencyGenerationStockIntegrationTest {
IssuanceAuditActor actor = new IssuanceAuditActor("stock-user", "库存测试员");
gateway.reserveGeneratedCurrencies(subject, 82L, requestId,
Arrays.asList(new DenominationItem(new BigDecimal("100.00"), 1)), actor);
seedAssetsForStockUser();
BigDecimal centralBefore = jdbcTemplate.queryForObject(
"SELECT available_balance FROM central_bank_currency_vault WHERE currency = 'DC'", BigDecimal.class);
"SELECT available_balance FROM central_bank_currency_vault "
+ "WHERE user_id='stock-user' AND school_id=1001 AND class_id=2001 AND currency='DC' AND deleted=0", BigDecimal.class);
BigDecimal bankBefore = jdbcTemplate.queryForObject(
"SELECT current_balance FROM issuance_bank_inventory WHERE bank_code = 'BKCHCNBJ00001'", BigDecimal.class);
"SELECT current_balance FROM issuance_bank_inventory "
+ "WHERE user_id='stock-user' AND school_id=1001 AND class_id=2001 AND bank_code='BKCHCNBJ00001' "
+ "AND deleted=0",
BigDecimal.class);
Instant now = Instant.parse("2026-08-07T03:00:00Z");
DraftDigitalCurrency confirmed = new DraftDigitalCurrency("DC_SOURCE_003", "ISSUE_BATCH_003", 1,
new BigDecimal("100.00"), "ORG_001", "DC", "AVAILABLE", now, actor.getUserId(), actor.getUsername(),
@ -112,13 +117,27 @@ class DigitalCurrencyGenerationStockIntegrationTest {
assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM commercial_bank_currency WHERE currency_id = 'DC_SOURCE_003'",
Integer.class)).isEqualTo(1);
assertThat(jdbcTemplate.queryForObject(
"SELECT available_balance FROM central_bank_currency_vault WHERE currency = 'DC'", BigDecimal.class))
"SELECT available_balance FROM central_bank_currency_vault "
+ "WHERE user_id='stock-user' AND school_id=1001 AND class_id=2001 AND currency='DC'", BigDecimal.class))
.isEqualByComparingTo(centralBefore.subtract(new BigDecimal("100.00")));
assertThat(jdbcTemplate.queryForObject(
"SELECT current_balance FROM issuance_bank_inventory WHERE bank_code = 'BKCHCNBJ00001'", BigDecimal.class))
"SELECT current_balance FROM issuance_bank_inventory "
+ "WHERE user_id='stock-user' AND school_id=1001 AND class_id=2001 AND bank_code='BKCHCNBJ00001'",
BigDecimal.class))
.isEqualByComparingTo(bankBefore.add(new BigDecimal("100.00")));
}
private void seedAssetsForStockUser() {
jdbcTemplate.update("INSERT INTO central_bank_currency_vault "
+ "(user_id, school_id, class_id, currency, available_balance, deleted) "
+ "VALUES ('stock-user', 1001, 2001, 'DC', ?, 0)",
new BigDecimal("300000000.00"));
jdbcTemplate.update("INSERT INTO issuance_bank_inventory "
+ "(user_id, school_id, class_id, bank_code, current_balance, warning_threshold, updated_at, deleted) "
+ "VALUES ('stock-user', 1001, 2001, 'BKCHCNBJ00001', ?, 50000000.00, CURRENT_TIMESTAMP, 0)",
new BigDecimal("49950000.00"));
}
private void insertCoin(long id, long batchId, int sequence, String denomination,
String currencyId, String completeCurrency) {
jdbcTemplate.update("INSERT INTO standard_currency "

@ -47,7 +47,8 @@ class IssuanceAttemptCancellationHandlerTest {
handler.cancel(attempt, subject);
verify(executions).reverse(org.mockito.ArgumentMatchers.eq("RESERVE-402"), any());
verify(executions).reverse(org.mockito.ArgumentMatchers.eq("RESERVE-402"),
any(com.yau.digitalrmb.issuance.domain.model.IssuanceOwner.class), any());
verify(gateway, never()).releaseGeneratedCurrencies(any(UUID.class), any());
}

@ -97,7 +97,8 @@ class IssuanceTrainingActionServiceTest {
new com.yau.digitalrmb.issuance.domain.model.IssuanceApplicationId(requestId), "REQ-299",
request.getBankCode(), request.getOrganizationId(), request.getTotalAmount(),
request.getCurrency(), completeDomainDenominations(), actor.getUserId()));
when(commercial.create(any(), any(IssuanceAuditActor.class))).thenReturn(view);
when(commercial.create(any(), any(com.yau.digitalrmb.issuance.domain.model.IssuanceOwner.class),
any(IssuanceAuditActor.class))).thenReturn(view);
ArgumentCaptor<ActionWork<Object>> work = ArgumentCaptor.forClass(ActionWork.class);
service.execute(attemptId, "01", "refresh-custom-application", request, subject, actor, keySubject);

@ -40,22 +40,46 @@ class IssuanceTrainingResetServiceTest {
@Autowired private IssuanceTrainingResetService service;
@Test
void restoresCompletedIssuanceAndDeletesOnlyCurrentSubjectsOperationData() {
void resetsAssetsBackToOriginalValuesAndDeletesOnlyCurrentSubjectsOperationData() {
seedCompletedIssuance("BANK", "AVAILABLE", null);
seedOtherUsersRequestAndAttempt();
IssuanceTrainingResetResult result = service.reset(subject());
assertThat(result.isReset()).isTrue();
assertThat(result.getRestoredReserveAmount()).isEqualByComparingTo("100.00");
assertThat(result.getRestoredCurrencyAmount()).isEqualByComparingTo("100.00");
// 重置前额度都低于原始值,所以“释放金额”为 0;重点是余额被拉回原始值
assertThat(result.getRestoredReserveAmount()).isEqualByComparingTo("0.00");
assertThat(result.getRestoredCurrencyAmount()).isEqualByComparingTo("0.00");
assertThat(result.getDeletedRecordCount()).isPositive();
assertThat(decimal("SELECT reserve_balance FROM central_bank_institution_account WHERE bank_code=?", BANK_CODE))
.isEqualByComparingTo("1000.00");
assertThat(decimal("SELECT current_balance FROM issuance_bank_inventory WHERE bank_code=?", BANK_CODE))
.isEqualByComparingTo("0.00");
assertThat(decimal("SELECT available_balance FROM central_bank_currency_vault WHERE currency=?", CURRENCY))
.isEqualByComparingTo("1000.00");
// 旧行逻辑删除留档,不参与任何查询
assertThat(count("SELECT COUNT(*) FROM issuance_bank_inventory WHERE user_id=? AND school_id=? AND class_id=? "
+ "AND bank_code=? AND deleted<>0", USER_ID, SCHOOL_ID, CLASS_ID, BANK_CODE)).isEqualTo(1);
assertThat(count("SELECT COUNT(*) FROM central_bank_currency_vault WHERE user_id=? AND school_id=? AND class_id=? "
+ "AND currency=? AND deleted<>0", USER_ID, SCHOOL_ID, CLASS_ID, CURRENCY)).isEqualTo(1);
assertThat(count("SELECT COUNT(*) FROM central_bank_institution_account WHERE user_id=? AND school_id=? "
+ "AND class_id=? AND bank_code=? AND deleted<>0", USER_ID, SCHOOL_ID, CLASS_ID, BANK_CODE)).isEqualTo(1);
// 新一轮只有一条有效记录,且是原始值
assertThat(count("SELECT COUNT(*) FROM issuance_bank_inventory WHERE user_id=? AND school_id=? AND class_id=? "
+ "AND deleted=0", USER_ID, SCHOOL_ID, CLASS_ID)).isEqualTo(1);
assertThat(decimal("SELECT current_balance FROM issuance_bank_inventory "
+ "WHERE user_id=? AND school_id=? AND class_id=? AND deleted=0",
USER_ID, SCHOOL_ID, CLASS_ID)).isEqualByComparingTo("49950000.00");
assertThat(decimal("SELECT warning_threshold FROM issuance_bank_inventory "
+ "WHERE user_id=? AND school_id=? AND class_id=? AND deleted=0",
USER_ID, SCHOOL_ID, CLASS_ID)).isEqualByComparingTo("50000000.00");
assertThat(count("SELECT COUNT(*) FROM central_bank_institution_account WHERE user_id=? AND school_id=? "
+ "AND class_id=? AND deleted=0", USER_ID, SCHOOL_ID, CLASS_ID)).isEqualTo(1);
assertThat(decimal("SELECT reserve_balance FROM central_bank_institution_account "
+ "WHERE user_id=? AND school_id=? AND class_id=? AND deleted=0",
USER_ID, SCHOOL_ID, CLASS_ID)).isEqualByComparingTo("50000000000.00");
assertThat(count("SELECT COUNT(*) FROM central_bank_currency_vault WHERE user_id=? AND school_id=? "
+ "AND class_id=? AND deleted=0", USER_ID, SCHOOL_ID, CLASS_ID)).isEqualTo(1);
assertThat(decimal("SELECT available_balance FROM central_bank_currency_vault "
+ "WHERE user_id=? AND school_id=? AND class_id=? AND deleted=0",
USER_ID, SCHOOL_ID, CLASS_ID)).isEqualByComparingTo("300000000.00");
assertThat(count("SELECT COUNT(*) FROM standard_currency WHERE id=?", SOURCE_CURRENCY_ID)).isEqualTo(1);
assertThat(count("SELECT COUNT(*) FROM issuance_source_currency_usage WHERE issuance_request_id=?", REQUEST_ID))
.isZero();
@ -74,10 +98,16 @@ class IssuanceTrainingResetServiceTest {
assertThat(count("SELECT COUNT(*) FROM training_experiment_attempt WHERE id=?", OTHER_ATTEMPT_ID))
.isEqualTo(1);
// 重复重置仍可执行,有效行始终只有一条原始值
IssuanceTrainingResetResult repeated = service.reset(subject());
assertThat(repeated.getDeletedRecordCount()).isZero();
assertThat(repeated.isReset()).isTrue();
assertThat(repeated.getRestoredReserveAmount()).isEqualByComparingTo("0.00");
assertThat(repeated.getRestoredCurrencyAmount()).isEqualByComparingTo("0.00");
assertThat(count("SELECT COUNT(*) FROM issuance_bank_inventory WHERE user_id=? AND school_id=? "
+ "AND class_id=? AND deleted=0", USER_ID, SCHOOL_ID, CLASS_ID)).isEqualTo(1);
assertThat(decimal("SELECT current_balance FROM issuance_bank_inventory "
+ "WHERE user_id=? AND school_id=? AND class_id=? AND deleted=0",
USER_ID, SCHOOL_ID, CLASS_ID)).isEqualByComparingTo("49950000.00");
}
@Test
@ -88,7 +118,8 @@ class IssuanceTrainingResetServiceTest {
.isInstanceOf(BusinessException.class)
.hasMessageContaining("后续模块");
assertThat(decimal("SELECT reserve_balance FROM central_bank_institution_account WHERE bank_code=?", BANK_CODE))
assertThat(decimal("SELECT reserve_balance FROM central_bank_institution_account "
+ "WHERE user_id=? AND school_id=? AND class_id=? AND bank_code=?", USER_ID, SCHOOL_ID, CLASS_ID, BANK_CODE))
.isEqualByComparingTo("900.00");
assertThat(count("SELECT COUNT(*) FROM issuance_request WHERE id=? AND deleted=FALSE", REQUEST_ID))
.isEqualTo(1);
@ -99,13 +130,17 @@ class IssuanceTrainingResetServiceTest {
private void seedCompletedIssuance(String ownerType, String ownerStatus, String lastTransactionId) {
jdbc.update("INSERT INTO central_bank_institution_account "
+ "(bank_code,organization_id,reserve_account_no,reserve_account_name,status,opened_on,reserve_balance) "
+ "VALUES (?,?,?,?,?,'2020-01-01',?)",
BANK_CODE, ORGANIZATION_ID, "RESERVE_RESET_9901", "重置测试准备金账户", "NORMAL", new BigDecimal("900.00"));
jdbc.update("INSERT INTO issuance_bank_inventory (bank_code,current_balance,warning_threshold,updated_at) "
+ "VALUES (?,?,?,CURRENT_TIMESTAMP)", BANK_CODE, new BigDecimal("100.00"), BigDecimal.ZERO);
jdbc.update("INSERT INTO central_bank_currency_vault (currency,available_balance) VALUES (?,?)",
CURRENCY, new BigDecimal("900.00"));
+ "(user_id,school_id,class_id,bank_code,organization_id,reserve_account_no,reserve_account_name,status,opened_on,reserve_balance) "
+ "VALUES (?,?,?,?,?,?,?,?,'2020-01-01',?)",
USER_ID, SCHOOL_ID, CLASS_ID, BANK_CODE, ORGANIZATION_ID, "RESERVE_RESET_9901", "重置测试准备金账户", "NORMAL",
new BigDecimal("900.00"));
jdbc.update("INSERT INTO issuance_bank_inventory "
+ "(user_id,school_id,class_id,bank_code,current_balance,warning_threshold,updated_at) "
+ "VALUES (?,?,?,?,?,?,CURRENT_TIMESTAMP)", USER_ID, SCHOOL_ID, CLASS_ID, BANK_CODE,
new BigDecimal("100.00"), BigDecimal.ZERO);
jdbc.update("INSERT INTO central_bank_currency_vault "
+ "(user_id,school_id,class_id,currency,available_balance) VALUES (?,?,?,?,?)",
USER_ID, SCHOOL_ID, CLASS_ID, CURRENCY, new BigDecimal("900.00"));
jdbc.update("INSERT INTO standard_currency_batch "
+ "(id,quota_control_bit_id,batch_number,total_amount,total_count,denomination_summary,status,"
+ "user_id,school_id,class_id,created_at,updated_at,created_by,updated_by,deleted) "

@ -4,6 +4,7 @@ import com.yau.digitalrmb.issuance.application.query.ReserveDeductionExecutionVi
import com.yau.digitalrmb.issuance.domain.model.CentralBankInstitutionAccount;
import com.yau.digitalrmb.issuance.domain.model.DigitalCurrencyProductionBatch;
import com.yau.digitalrmb.issuance.domain.model.IssuanceAuditActor;
import com.yau.digitalrmb.issuance.domain.model.IssuanceOwner;
import com.yau.digitalrmb.issuance.domain.model.ReserveDeductionExecution;
import com.yau.digitalrmb.issuance.domain.model.ReserveDeductionNotification;
import com.yau.digitalrmb.issuance.domain.repository.CentralBankInstitutionAccountRepository;
@ -35,6 +36,7 @@ class ReserveDeductionExecutionServiceTest {
private final DigitalCurrencyProductionRepository productions = mock(DigitalCurrencyProductionRepository.class);
private final ReserveDeductionExecutionService service =
new ReserveDeductionExecutionService(notifications, executions, accounts, productions);
private final IssuanceOwner owner = IssuanceOwner.of("user-2", 1L, 2L);
@Test
void restoresCurrentBalanceAndPreservesOriginalDeductionAudit() {
@ -44,16 +46,16 @@ class ReserveDeductionExecutionServiceTest {
when(executions.findByTransactionIdForUpdate("RESERVE-501")).thenReturn(Optional.of(original));
when(productions.findByRequestId(requestId)).thenReturn(Optional.empty());
when(notifications.findByTransactionId("RESERVE-501")).thenReturn(Optional.of(notification));
when(accounts.findByBankCodeForUpdate("BANK-501")).thenReturn(Optional.of(account("125000.00")));
when(accounts.findByBankCodeForUpdate(owner, "BANK-501")).thenReturn(Optional.of(account("125000.00")));
ReserveDeductionExecutionView result = service.reverse("RESERVE-501", new IssuanceAuditActor("user-2", "reviewer"));
ReserveDeductionExecutionView result = service.reverse("RESERVE-501", owner, new IssuanceAuditActor("user-2", "reviewer"));
assertThat(result.getStatus()).isEqualTo("REVERSED");
assertThat(result.getAfterBalance()).isEqualByComparingTo("150000.00");
assertThat(result.getReversedBalance()).isEqualByComparingTo("175000.00");
assertThat(result.getExecutedBy()).isEqualTo("operator");
assertThat(result.getReversedBy()).isEqualTo("reviewer");
verify(accounts).updateReserveBalance("BANK-501", new BigDecimal("175000.00"));
verify(accounts).updateReserveBalance(owner, "BANK-501", new BigDecimal("175000.00"));
ArgumentCaptor<ReserveDeductionExecution> saved = ArgumentCaptor.forClass(ReserveDeductionExecution.class);
verify(executions).save(saved.capture());
assertThat(saved.getValue().getBeforeBalance()).isEqualByComparingTo("200000.00");
@ -69,11 +71,11 @@ class ReserveDeductionExecutionServiceTest {
Instant.parse("2026-08-20T01:30:00Z"), "user-1", "operator", Collections.emptyList());
when(productions.findByRequestId(requestId)).thenReturn(Optional.of(batch));
assertThatThrownBy(() -> service.reverse("RESERVE-501", new IssuanceAuditActor("user-2", "reviewer")))
assertThatThrownBy(() -> service.reverse("RESERVE-501", owner, new IssuanceAuditActor("user-2", "reviewer")))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("already been produced");
verify(accounts, never()).updateReserveBalance(org.mockito.ArgumentMatchers.anyString(),
org.mockito.ArgumentMatchers.any(BigDecimal.class));
verify(accounts, never()).updateReserveBalance(org.mockito.ArgumentMatchers.any(IssuanceOwner.class),
org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(BigDecimal.class));
verify(executions, never()).save(org.mockito.ArgumentMatchers.any(ReserveDeductionExecution.class));
}

@ -77,8 +77,9 @@ class MybatisIssuanceRequestRepositoryTest {
@Test
void readsSuggestedAmountAsThresholdMinusCurrentBalance() {
IssuanceBankInventory inventory = repository.findBuiltInInventory()
.orElseThrow(() -> new AssertionError("seeded bank inventory was not found"));
IssuanceBankInventory inventory = repository
.findInventory(com.yau.digitalrmb.issuance.domain.model.IssuanceOwner.of("inventory-user", 1L, 2L))
.orElseThrow(() -> new AssertionError("bank inventory was not initialized"));
assertThat(inventory.getCurrentBalance()).isEqualByComparingTo("49950000.00");
assertThat(inventory.getWarningThreshold()).isEqualByComparingTo("50000000.00");

@ -303,8 +303,10 @@ class IssuanceControllerTest {
@Test
void readsBuiltInCurrencyDemandWithoutRequestParameters() throws Exception {
String ownerId = "00000000-0000-0000-0000-000000000486";
mockMvc.perform(get("/api/v1/commercial-banks/issuance/inventory")
.with(jwt().jwt(jwt -> jwt.subject("487").claim("preferred_username", "tzs001"))))
.with(jwt().jwt(jwt -> jwt.subject(ownerId).claim("userId", ownerId)
.claim("preferred_username", "tzs001"))))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.currentBalance").value(49950000.00))
.andExpect(jsonPath("$.data.warningThreshold").value(50000000.00))

@ -91,6 +91,30 @@ class PlatformTokenVerifierTest {
assertThatThrownBy(() -> verifier.verify(unsignedToken(incomplete, now.plus(Duration.ofMinutes(5))))).isInstanceOf(PlatformTokenException.class);
}
@Test
void parsesStringRoleIdIntoRoleId() throws Exception {
// 智云 token 中 roleid 是字符串 "3"(教师),旧逻辑用 canConvertToLong 对字符串返回 false,会回退默认 4
Map<String, Object> claims = new HashMap<String, Object>();
claims.put("userId", USER_ID);
claims.put("username", "tzt001");
claims.put("password", "123qwe");
claims.put("roleid", "3");
claims.putAll(completeProfile());
String tk = unsignedToken(claims, now.plus(Duration.ofMinutes(5)));
assertThat(verifier.verify(tk).getRoleId()).isEqualTo(3);
}
@Test
void fallsBackToDefaultRoleIdWhenMissing() throws Exception {
Map<String, Object> claims = new HashMap<String, Object>();
claims.put("userId", USER_ID);
claims.put("username", "tzt001");
claims.put("password", "123qwe");
claims.putAll(completeProfile());
String tk = unsignedToken(claims, now.plus(Duration.ofMinutes(5)));
assertThat(verifier.verify(tk).getRoleId()).isEqualTo(4);
}
private String token(String userId, String username, String password, long roleId, Instant expiresAt) throws Exception {
return token(userId, username, password, roleId, expiresAt, new HashMap<String, Object>());
}

Loading…
Cancel
Save