diff --git a/docs/module245-upgrade.md b/docs/module245-upgrade.md new file mode 100644 index 0000000..7437e1e --- /dev/null +++ b/docs/module245-upgrade.md @@ -0,0 +1,33 @@ +# 模块二、四、五整改升级 + +本次升级补齐发行动作顺序、扣减申请签名、生产授权有效期,以及三个实训模块的原始输入校验。发行实验在银行反馈回执后结束;生成确权结果报文本身不会结束实验。 + +## 数据库与部署 + +先备份表结构,再按现有数据库版本顺序执行以下手工脚本,最后启动新后端: + +1. `src/main/resources/db/manual/issuance_owner_schema_upgrade.sql`:旧库缺少发行资产归属字段时执行。 +2. `src/main/resources/db/manual/payment_reserve_ledger_upgrade.sql`:创建模拟 ACS 账户和分录表。 +3. `src/main/resources/db/manual/issuance_training_completion_upgrade.sql`:创建真实签名的准备金扣减申请表,并为已有 ACS 表补齐通用审计字段。 + +脚本支持重复执行,不删除现有业务记录。第三份脚本依赖第二份脚本的两张表已经存在。旧 ACS 记录新增操作者默认标为 `SYSTEM`,新增时间默认为迁移时间;新业务记录使用当前实训用户及真实操作时间。 + +2026-10-31 已在指定的 `120.78.220.29:3307/digital_rmb` 执行升级并核对相关表行数不变。原配置的另一台数据库未执行本次升级。应用保留 `spring.sql.init.mode=never`,不会在启动时替代手工迁移。 + +## 接口与状态 + +- 三个模块增加 `POST /api/v1/{issuance|exchange|payment}/attempts/{attemptId}/steps/{stepCode}/validate/{actionCode}`。仅支持服务端白名单中的填写项;原文、卡号、时间戳、金额等与当前用户实训数据比对。错误计数增加一次;不创建订单、不扣款、不推进动作或成绩进度。 +- 正式动作同样校验原始输入;已完成动作返回历史结果前也检查提交内容。兑换和支付保留旧聚合业务接口的服务端调用约定。 +- 发行增加准备金扣减申请签名与查询接口。签名使用本用户备案的商业银行 SM2 密钥;提交、核查和 ACS 执行均验证申请内容、SM3 摘要、公钥与签名,拒绝篡改内容。 +- 生产批次返回 `authorizationTime`、`validUntil`。未确权批次的生产授权有效期为一小时;到期后的动作及重放均拒绝,需重新实训申请新授权。已确认的历史批次仍可查询。 +- 时间戳仍通过独立只读 GET 接口获取,不创建发行申请。 + +模拟 ACS 账户沿用每名学员独立的归属规则;清算、重复清算、重置回补和跨用户隔离均有回归覆盖。原型中独立合规报告与报文内嵌摘要采用不同结构,本次保留原型展示,独立报告的原始 JSON 为 SM3 输入依据。 + +## 验证范围 + +专项回归:真实 MySQL 80 项、H2 84 项,均通过;前端按钮输入、请求封装、卡号回显、时间戳与草稿恢复测试通过。完整业务用例在同一 MySQL 实例的隔离库执行,保留真实外键,不复制学生数据。 + +浏览器跑通模块五六步,并核对数据库订单 `SUCCESS`、实训 `COMPLETED`、付款余额 9000、收款余额 1000 和单笔双边准备金分录。模块四抽测正确卡号提交、错误原文拦截及刷新恢复。前后端构建通过。部署后应用空闲约 15 分钟的健康检查为 `UP`,耗时 144 毫秒。 + +该专项结论不等于全项目验收;此前基线中的模块一及 SSO 旧测试问题未在本次修改业务规则或放宽断言来消除。 diff --git a/src/main/java/com/yau/digitalrmb/exchange/application/service/ExchangeTrainingActionService.java b/src/main/java/com/yau/digitalrmb/exchange/application/service/ExchangeTrainingActionService.java index 769f8c2..dcbe3b1 100644 --- a/src/main/java/com/yau/digitalrmb/exchange/application/service/ExchangeTrainingActionService.java +++ b/src/main/java/com/yau/digitalrmb/exchange/application/service/ExchangeTrainingActionService.java @@ -93,6 +93,47 @@ public class ExchangeTrainingActionService { return executeInternal(attemptId, stepCode, actionCode, request, subject, actor, false); } + /** Validate learner answers without creating an order or advancing an experiment. */ + public void validateInput(UUID attemptId,String step,String action,ExchangeActionRequest input, + ExperimentSubject subject,ExchangeActor actor) { + String key=step+":"+action; + ExperimentAttemptView attempt=attempts.detail(attemptId,subject); + if(attempt.getModuleCode()!=com.yau.digitalrmb.training.attempt.domain.ExperimentModule.EXCHANGE)throw validation("实验类型不匹配"); + int index=ACTIONS.indexOf(key); + if(!ANSWER_ACTIONS.contains(key))throw validation("此操作没有原文填写项"); + requirePrevious(attempt,index); + try{checkAnswer(key,input,attempt,actor);}catch(TrainingInputException e){ + if(scoreService==null)throw e; + int count=scoreService.recordError(subject.getUserId()); + throw new TrainingInputException(e.getMessage()+",本次实训第"+count+"次错误"); + } + } + private static final List ANSWER_ACTIONS=Arrays.asList("02:concatenate-withdrawal","03:concatenate-sign-source","03:generate-digest"); + private void checkAnswer(String key,ExchangeActionRequest input,ExperimentAttemptView attempt,ExchangeActor actor){ + if("02:concatenate-withdrawal".equals(key)){ + Map expected=withdrawalOutput(input,attempt,actor); + if(decimal(expected,"amount").compareTo(new BigDecimal("5000.00"))!=0)throw inputValidation("本案例兑换金额应为5000.00元"); + ExchangeContext context=exchanges.context(actor); + com.yau.digitalrmb.shared.validation.TrainingAnswerChecks.same(input.getWalletId(),context.getWalletId(),"钱包ID"); + com.yau.digitalrmb.shared.validation.TrainingAnswerChecks.same(input.getBankCardNumber(),context.getBankCardNumber(),"银行卡号"); + com.yau.digitalrmb.shared.validation.TrainingAnswerChecks.same(input.getTimestamp(),text(expected,"timestamp"),"时间戳"); + com.yau.digitalrmb.shared.validation.TrainingAnswerChecks.original(input.getSourceText(),text(expected,"sourceText"),2); + }else if("03:concatenate-sign-source".equals(key)){ + ExchangeOrderView order=exchanges.get(businessId(attempt.getBusinessId()),actor); + ExchangeContext context=exchanges.context(actor); + String timestamp=text(prior(attempt,"03","generate-sign-timestamp"),"timestamp"); + com.yau.digitalrmb.shared.validation.TrainingAnswerChecks.same(input.getRequestNo(),order.getRequestNo(),"取币请求ID"); + com.yau.digitalrmb.shared.validation.TrainingAnswerChecks.same(input.getBankCardLast4(),context.getBankCardLast4(),"银行卡尾号"); + BigDecimal amount=com.yau.digitalrmb.shared.validation.TrainingAnswerChecks.amount(input.getRawAmount(),input.getAmount()); + if(amount==null || amount.compareTo(order.getAmount())!=0)throw inputValidation("兑换金额与取币请求不一致"); + com.yau.digitalrmb.shared.validation.TrainingAnswerChecks.same(input.getTimestamp(),timestamp,"时间戳"); + com.yau.digitalrmb.shared.validation.TrainingAnswerChecks.original(input.getSourceText(),"SIGN|"+order.getRequestNo()+"|"+order.getAmount().toPlainString()+"|"+context.getBankCardLast4()+"|"+timestamp,2); + }else{ + requireAlgorithm(input,"SM3"); + com.yau.digitalrmb.shared.validation.TrainingAnswerChecks.original(input.getSourceText(),text(prior(attempt,"03","concatenate-sign-source"),"sourceText"),2); + } + } + private ExperimentActionView executeInternal(UUID attemptId, String stepCode, String actionCode, ExchangeActionRequest request, ExperimentSubject subject, ExchangeActor actor, boolean validateStudentInput) { @@ -101,7 +142,9 @@ public class ExchangeTrainingActionService { if (index < 0) throw validation("不支持的兑换实验动作:" + key); ExchangeActionRequest input = request == null ? new ExchangeActionRequest() : request; ExperimentAttemptView attempt = attempts.detail(attemptId, subject); + if(attempt.getModuleCode()!=com.yau.digitalrmb.training.attempt.domain.ExperimentModule.EXCHANGE)throw validation("实验类型不匹配"); requirePrevious(attempt, index); + if(validateStudentInput && ANSWER_ACTIONS.contains(key) && attempt.getActions().stream().anyMatch(a->stepCode.equals(a.getStepCode()) && actionCode.equals(a.getActionCode()) && a.getActionStatus()==ActionStatus.COMPLETED))validateInput(attemptId,stepCode,actionCode,input,subject,actor); UUID exchangeId = businessId(attempt.getBusinessId()); if (index > ACTIONS.indexOf("02:output-withdrawal-request") && exchangeId == null) { throw validation("请先输出取币请求报文"); @@ -112,6 +155,7 @@ public class ExchangeTrainingActionService { fingerprint(key, input, subject), Object.class, () -> { try { + if(validateStudentInput && ANSWER_ACTIONS.contains(key))checkAnswer(key,input,attempt,actor); return run(key, input, attempt, boundExchangeId, actor, validateStudentInput); } catch (TrainingInputException exception) { if (scoreService == null) throw exception; @@ -255,7 +299,7 @@ public class ExchangeTrainingActionService { if (request.getBankAccountId() != null && !context.getBankAccountId().equals(request.getBankAccountId())) { throw inputValidation("银行账户不属于当前用户"); } - BigDecimal amount = money(request.getAmount()); + BigDecimal amount = money(com.yau.digitalrmb.shared.validation.TrainingAnswerChecks.amount(request.getRawAmount(),request.getAmount())); String timestamp = text(prior(attempt, "02", "generate-timestamp"), "timestamp"); Map output = new LinkedHashMap(); output.put("walletId", context.getWalletId()); diff --git a/src/main/java/com/yau/digitalrmb/exchange/interfaces/dto/ExchangeActionRequest.java b/src/main/java/com/yau/digitalrmb/exchange/interfaces/dto/ExchangeActionRequest.java index 80bf012..86b962f 100644 --- a/src/main/java/com/yau/digitalrmb/exchange/interfaces/dto/ExchangeActionRequest.java +++ b/src/main/java/com/yau/digitalrmb/exchange/interfaces/dto/ExchangeActionRequest.java @@ -12,6 +12,18 @@ public class ExchangeActionRequest { private String algorithm; private String privateKey; private String publicKey; + @com.fasterxml.jackson.annotation.JsonInclude(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL) private String sourceText; + @com.fasterxml.jackson.annotation.JsonInclude(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL) private String rawAmount; + @com.fasterxml.jackson.annotation.JsonInclude(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL) private String bankCardNumber; + @com.fasterxml.jackson.annotation.JsonInclude(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL) private String bankCardLast4; + @com.fasterxml.jackson.annotation.JsonInclude(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL) private String requestNo; + @com.fasterxml.jackson.annotation.JsonInclude(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL) private String timestamp; + public String getSourceText(){return sourceText;} public void setSourceText(String v){sourceText=v;} + public String getRawAmount(){return rawAmount;} public void setRawAmount(String v){rawAmount=v;} + public String getBankCardNumber(){return bankCardNumber;} public void setBankCardNumber(String v){bankCardNumber=v;} + public String getBankCardLast4(){return bankCardLast4;} public void setBankCardLast4(String v){bankCardLast4=v;} + public String getRequestNo(){return requestNo;} public void setRequestNo(String v){requestNo=v;} + public String getTimestamp(){return timestamp;} public void setTimestamp(String v){timestamp=v;} public String getWalletId() { return walletId; } public void setWalletId(String walletId) { this.walletId = walletId; } diff --git a/src/main/java/com/yau/digitalrmb/exchange/interfaces/rest/ExchangeTrainingAttemptController.java b/src/main/java/com/yau/digitalrmb/exchange/interfaces/rest/ExchangeTrainingAttemptController.java index e828448..4ecc075 100644 --- a/src/main/java/com/yau/digitalrmb/exchange/interfaces/rest/ExchangeTrainingAttemptController.java +++ b/src/main/java/com/yau/digitalrmb/exchange/interfaces/rest/ExchangeTrainingAttemptController.java @@ -84,6 +84,15 @@ public class ExchangeTrainingAttemptController { request == null ? new ExchangeActionRequest() : request, subject(user), actor(user))); } + @PostMapping("/{attemptId}/steps/{stepCode}/validate/{actionCode}") + @Operation(summary="核对原始填写内容",description="根据当前用户实验数据校验,错误计入成绩;不扣款、不创建订单、不推进进度") + public ApiResponse> validate(@PathVariable UUID attemptId,@PathVariable String stepCode, + @PathVariable String actionCode,@RequestBody ExchangeActionRequest input){ + CurrentUser user=users.getCurrentUser(); + actions.validateInput(attemptId,stepCode,actionCode,input,subject(user),actor(user)); + return ok(java.util.Collections.singletonMap("valid",true)); + } + private ExperimentSubject subject(CurrentUser user) { return new ExperimentSubject(required(user.getUserId(), "用户 ID"), numeric(user.getSchoolId(), "学校 ID"), numeric(user.getClassId(), "班级 ID"), ""); diff --git a/src/main/java/com/yau/digitalrmb/issuance/application/query/DigitalCurrencyProductionBatchView.java b/src/main/java/com/yau/digitalrmb/issuance/application/query/DigitalCurrencyProductionBatchView.java index 1fa36b8..7cf5811 100644 --- a/src/main/java/com/yau/digitalrmb/issuance/application/query/DigitalCurrencyProductionBatchView.java +++ b/src/main/java/com/yau/digitalrmb/issuance/application/query/DigitalCurrencyProductionBatchView.java @@ -28,6 +28,8 @@ public class DigitalCurrencyProductionBatchView { private final String controlSystemSignature; private final DigitalCurrencyOwnershipConfirmationView ownershipConfirmation; private final List draftCoins; + public Instant getAuthorizationTime(){return createdAt;} + public Instant getValidUntil(){return createdAt.plus(com.yau.digitalrmb.issuance.application.service.ProductionAuthorizationPolicy.VALIDITY);} public static DigitalCurrencyProductionBatchView from(DigitalCurrencyProductionBatch value) { return from(value, null); diff --git a/src/main/java/com/yau/digitalrmb/issuance/application/service/DigitalCurrencyDraftProductionService.java b/src/main/java/com/yau/digitalrmb/issuance/application/service/DigitalCurrencyDraftProductionService.java index c829f30..33a3b57 100644 --- a/src/main/java/com/yau/digitalrmb/issuance/application/service/DigitalCurrencyDraftProductionService.java +++ b/src/main/java/com/yau/digitalrmb/issuance/application/service/DigitalCurrencyDraftProductionService.java @@ -33,6 +33,7 @@ import java.util.UUID; @Service public class DigitalCurrencyDraftProductionService { + @Autowired private ProductionAuthorizationPolicy authorization; private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("yyyyMMdd").withZone(ZoneOffset.UTC); private final CentralBankIssuanceReceiptRepository receiptRepository; private final ReserveDeductionNotificationRepository notificationRepository; @@ -62,6 +63,7 @@ public class DigitalCurrencyDraftProductionService { throw new BusinessException(ErrorCode.INTERNAL_ERROR, "生成数字货币模块控制数据服务未配置"); } requireActor(actor); + if(authorization!=null)authorization.requireActive(requestId); Optional existing = productionRepository.findByRequestId(requestId); if (existing.isPresent()) return DigitalCurrencyProductionBatchView.from(existing.get()); ReserveDeductionNotification notification = notificationRepository.findByRequestId(requestId) @@ -111,6 +113,7 @@ public class DigitalCurrencyDraftProductionService { @Transactional(readOnly = true) public Optional digests(UUID requestId) { + if(authorization!=null)authorization.requireActive(requestId); return productionRepository.findByRequestId(requestId).map(batch -> { List values = new ArrayList(); diff --git a/src/main/java/com/yau/digitalrmb/issuance/application/service/DigitalCurrencyOwnershipConfirmationService.java b/src/main/java/com/yau/digitalrmb/issuance/application/service/DigitalCurrencyOwnershipConfirmationService.java index 2c8f1e1..1bf194e 100644 --- a/src/main/java/com/yau/digitalrmb/issuance/application/service/DigitalCurrencyOwnershipConfirmationService.java +++ b/src/main/java/com/yau/digitalrmb/issuance/application/service/DigitalCurrencyOwnershipConfirmationService.java @@ -24,6 +24,7 @@ import java.util.List; @Service public class DigitalCurrencyOwnershipConfirmationService { + @org.springframework.beans.factory.annotation.Autowired private ProductionAuthorizationPolicy authorization; private final DigitalCurrencyProductionRepository productionRepository; private final ReserveDeductionNotificationRepository notificationRepository; private final DigitalCurrencyGenerationModuleGateway generationGateway; @@ -39,6 +40,7 @@ public class DigitalCurrencyOwnershipConfirmationService { @Transactional public DigitalCurrencyProductionBatchView confirm(UUID requestId, IssuanceAuditActor actor, InstitutionKeySubject subject) { + if(authorization!=null)authorization.requireActive(requestId); requireActor(actor); if (generationGateway == null) { throw new BusinessException(ErrorCode.INTERNAL_ERROR, "生成数字货币模块密钥服务未配置"); diff --git a/src/main/java/com/yau/digitalrmb/issuance/application/service/IssuanceActionInputValidator.java b/src/main/java/com/yau/digitalrmb/issuance/application/service/IssuanceActionInputValidator.java index 7b2881d..d2d9c0b 100644 --- a/src/main/java/com/yau/digitalrmb/issuance/application/service/IssuanceActionInputValidator.java +++ b/src/main/java/com/yau/digitalrmb/issuance/application/service/IssuanceActionInputValidator.java @@ -12,6 +12,8 @@ import java.util.UUID; @Service public class IssuanceActionInputValidator { + @org.springframework.beans.factory.annotation.Autowired private DenominationPlanService plans; + @org.springframework.beans.factory.annotation.Autowired private ReserveDeductionNotificationService notices; private final InstitutionKeyService keys; private final InstitutionIdentityCryptography crypto; private final CommercialBankIssuanceApplicationService requests; @@ -24,6 +26,19 @@ public class IssuanceActionInputValidator { public void validate(String action, IssuanceActionRequest input, UUID requestId, IssuanceAuditActor actor, InstitutionKeySubject subject) { switch (action) { + case "01:refresh-custom-application": + if(input.getRawAmount()!=null)input.setTotalAmount(com.yau.digitalrmb.shared.validation.TrainingAnswerChecks.amount(input.getRawAmount(),null)); + if(input.getTotalAmount()==null || input.getTotalAmount().signum()<=0)throw wrong("发行金额必须大于零"); + if(!"DC".equals(required(input.getCurrency(),"币种")))throw wrong("币种应为DC"); + if(requestId==null){required(input.getBankCode(),"机构代码");required(input.getOrganizationId(),"机构标识");} + java.math.BigDecimal sum=java.math.BigDecimal.ZERO; + if(input.getDenominations()==null || input.getDenominations().size()!=11)throw wrong("面额必须包含全部 11 种标准面额"); + for(com.yau.digitalrmb.issuance.interfaces.dto.DenominationItemRequest item:input.getDenominations()){ + if(item==null || item.getDenomination()==null || item.getQuantity()==null || item.getQuantity()<0)throw wrong("面额明细无效"); + sum=sum.add(item.getDenomination().multiply(java.math.BigDecimal.valueOf(item.getQuantity()))); + } + if(sum.compareTo(input.getTotalAmount())!=0)throw wrong("面额明细合计与申请金额不一致"); + break; case "01:generate-digest": algorithm(input,"SM3"); break; @@ -48,9 +63,25 @@ public class IssuanceActionInputValidator { throw wrong("H1与H2不一致,请核对请求原文及摘要"); break; case "05:execute-deduction": + if(input.getRawAmount()!=null)input.setDeductionAmount(com.yau.digitalrmb.shared.validation.TrainingAnswerChecks.amount(input.getRawAmount(),null)); required(input.getReserveAccountNo(),"准备金账户标识"); required(input.getReserveAccountName(),"准备金账户名称"); if (input.getDeductionAmount()==null || input.getDeductionAmount().signum()<=0) throw wrong("扣减金额必须大于零"); + com.yau.digitalrmb.issuance.application.query.ReserveDeductionNotificationView notice=notices.find(requestId).orElseThrow(()->wrong("准备金扣减通知不存在")); + if(!notice.getReserveAccountNo().equals(input.getReserveAccountNo().trim()) || !notice.getReserveAccountName().equals(input.getReserveAccountName().trim()) + ||notice.getDeductionAmount().compareTo(input.getDeductionAmount())!=0)throw wrong("准备金账户或扣减金额与申请不一致"); + break; + case "04:generate-reserve-deduction-request": + java.math.BigDecimal entered=com.yau.digitalrmb.shared.validation.TrainingAnswerChecks.amount(input.getRawAmount(),input.getDeductionAmount()); + if(entered==null || requests.getCommercialBankView(requestId,actor).getTotalAmount().compareTo(entered)!=0)throw wrong("应扣金额与发行总金额不一致"); + break; + case "05:query-account": + if(!requests.getCommercialBankView(requestId,actor).getBankCode().equals(required(input.getBankCode(),"机构代码")))throw wrong("未查询到该机构的准备金账户"); + break; + case "06:generate-production-digest": + algorithm(input,"SM3"); + String currency=production.find(requestId).orElseThrow(()->wrong("请先生成生产批次")).getDraftCoins().get(0).getSourceCompleteCurrency(); + if(!currency.equals(required(input.getSourceText(),"完整币串")))throw wrong("完整币串与当前批次第一枚币串不一致"); break; case "07:central-confirm-ownership": algorithm(input,"SM2"); diff --git a/src/main/java/com/yau/digitalrmb/issuance/application/service/IssuanceActionOrder.java b/src/main/java/com/yau/digitalrmb/issuance/application/service/IssuanceActionOrder.java new file mode 100644 index 0000000..3bb5472 --- /dev/null +++ b/src/main/java/com/yau/digitalrmb/issuance/application/service/IssuanceActionOrder.java @@ -0,0 +1,55 @@ +package com.yau.digitalrmb.issuance.application.service; + +import com.yau.digitalrmb.shared.api.ErrorCode; +import com.yau.digitalrmb.shared.exception.BusinessException; +import com.yau.digitalrmb.training.attempt.domain.ActionStatus; +import com.yau.digitalrmb.training.attempt.domain.ExperimentModule; +import com.yau.digitalrmb.training.attempt.interfaces.dto.ExperimentAttemptView; +import java.util.*; + +/** Dependencies follow the actual learner controls, including receipt/submission in step four. */ +public final class IssuanceActionOrder { + private static final Map PREVIOUS = new LinkedHashMap<>(); + static { + chain("01:refresh-quota", "01:refresh-custom-application", "01:generate-timestamp", "01:concatenate-application", + "01:generate-digest", "01:sign-application", "01:package-application", "01:send-application", + "02:verify-signature", "02:recalculate-digest", "02:compare-digest", + "03:query-institution-input", "03:query-quota-input", "03:query-application-message", + "04:auto-confirm-plan", "04:generate-reserve-deduction-request", "05:confirm-receipt", + "04:sign-reserve-application", "05:verify-deduction", "05:query-account", "05:check-application", + "05:execute-deduction", "05:generate-balance-notice", "05:send-balance-notice", "05:confirm-balance-receipt", + "06:confirm-production-receipt", "06:send-authorization", "06:receive-authorization", + "06:generate-currency", "06:generate-production-digest", "06:assemble-production-confirmation", + "06:send-production-confirmation", "07:preliminary-verification", "07:generate-ownership-list", + "07:central-confirm-ownership", "07:transfer-ownership", "07:verify-central-bank-signature", + "07:activate-bank-currencies", "07:generate-ownership-report", "07:send-ownership-result", + "07:update-bank-status", "07:sign-bank-receipt", "07:load-ownership-result"); + } + private static void chain(String... keys) { for(int i=1;iparts[0].equals(a.getStepCode()) + && parts[1].equals(a.getActionCode()) && a.getActionStatus()==ActionStatus.COMPLETED); + if(!completed)throw new BusinessException(ErrorCode.VALIDATION_ERROR,"请先完成步骤"+Integer.parseInt(parts[0])+"的前序操作,再继续当前操作"); + } + public static Integer completedStep(String action) { + switch(action) { + case "01:send-application":return 1; + case "02:compare-digest":return 2; + case "03:query-application-message":return 3; + case "05:verify-deduction":return 4; + case "05:confirm-balance-receipt":return 5; + case "06:send-production-confirmation":return 6; + case "07:load-ownership-result":return 7; + default:return null; + } + } + public static String[] next(String action){ + return PREVIOUS.entrySet().stream().filter(e->e.getValue().equals(action)).map(e->e.getKey().split(":",2)) + .findFirst().orElse(action.split(":",2)); + } + private IssuanceActionOrder() {} +} diff --git a/src/main/java/com/yau/digitalrmb/issuance/application/service/IssuanceTrainingActionService.java b/src/main/java/com/yau/digitalrmb/issuance/application/service/IssuanceTrainingActionService.java index b9cbdf7..c9d4a60 100644 --- a/src/main/java/com/yau/digitalrmb/issuance/application/service/IssuanceTrainingActionService.java +++ b/src/main/java/com/yau/digitalrmb/issuance/application/service/IssuanceTrainingActionService.java @@ -48,7 +48,12 @@ public class IssuanceTrainingActionService { "05:send-balance-notice", "06:confirm-production-receipt", "06:generate-production-digest", "07:central-confirm-ownership", "07:verify-central-bank-signature", "07:activate-bank-currencies", - "07:sign-bank-receipt", "07:load-ownership-result"); + "07:sign-bank-receipt", "07:load-ownership-result", + "04:sign-reserve-application", "05:check-application", "05:confirm-balance-receipt", + "06:send-authorization", "06:receive-authorization", "06:generate-currency", + "06:assemble-production-confirmation", "06:send-production-confirmation", + "07:preliminary-verification", "07:generate-ownership-list", "07:transfer-ownership", + "07:generate-ownership-report", "07:send-ownership-result", "07:update-bank-status"); private final ExperimentAttemptService attempts; private final ObjectMapper objectMapper; @@ -62,6 +67,8 @@ public class IssuanceTrainingActionService { private final IssuanceScoreService scoreService; @Autowired private IssuanceActionInputValidator inputValidator; @Autowired private com.yau.digitalrmb.institutionidentity.domain.InstitutionIdentityCryptography cryptography; + @Autowired private ReserveDeductionApplicationService signedApplications; + @Autowired private ProductionAuthorizationPolicy authorization; @Autowired public IssuanceTrainingActionService(ExperimentAttemptService attempts, ObjectMapper objectMapper, @@ -106,6 +113,7 @@ public class IssuanceTrainingActionService { if (actionIndex < 0) throw validation("不支持的发行实验动作:" + key); IssuanceActionRequest input = request == null ? new IssuanceActionRequest() : request; ExperimentAttemptView attempt = attempts.detail(attemptId, subject); + IssuanceActionOrder.requireReady(attempt,key); UUID requestId = resolveRequestId(attempt.getBusinessId(), input.getRequestId()); // Owning an experiment does not grant access to a supplied business record. // Apply this before every action, including read-only and idempotent replays. @@ -114,13 +122,18 @@ public class IssuanceTrainingActionService { && requestId == null) { throw validation("请先生成或关联发行申请"); } - String[] next = nextAction(actionIndex); + if(authorization!=null && requestId!=null && ("06".equals(stepCode)||"07".equals(stepCode)))authorization.requireActive(requestId); + if(signedApplications!=null && Arrays.asList("05:verify-deduction","05:check-application","05:execute-deduction").contains(key)) + signedApplications.requireValid(requestId,keySubject); + try{if(inputValidator!=null)inputValidator.validate(key,input,requestId,actor,keySubject);} + catch(TrainingInputException e){throw scoredInputError(e,subject);} + String[] next = IssuanceActionOrder.next(key); final UUID businessRequestId = requestId; final String actionKey = key; final boolean bindSuppliedRequest = attempt.getBusinessId() == null && businessRequestId != null; ActionWork work = () -> { try { - if (inputValidator != null) inputValidator.validate(actionKey,input,businessRequestId,actor,keySubject); + IssuanceActionOrder.requireReady(attempts.detail(attemptId,subject),actionKey); ActionOutcome outcome = run(actionKey, input, businessRequestId, actor, keySubject, subject); return bindSuppliedRequest ? ActionOutcome.completed(outcome.getOutput(), businessRequestId.toString()) : outcome; @@ -136,8 +149,9 @@ public class IssuanceTrainingActionService { }; ExperimentActionView result = attempts.execute(attemptId, subject, stepCode, actionCode, fingerprint(key, input, requestId, subject), Object.class, work, next[0], next[1]); - if (scoreService != null && isLastActionInStep(actionIndex)) { - scoreService.markStepCompleted(subject.getUserId(), stepNumber(stepCode)); + Integer completedStep=IssuanceActionOrder.completedStep(key); + if (scoreService != null && completedStep!=null) { + scoreService.markStepCompleted(subject.getUserId(), completedStep); } return result; } @@ -199,25 +213,38 @@ public class IssuanceTrainingActionService { return completed(reviewService.review(requestId, actor, keySubject)); case "04:generate-reserve-deduction-request": return completed(notificationService.send(requestId, owner, actor)); + case "04:sign-reserve-application": + return completed(signedApplications.sign(requestId,keySubject)); case "05:confirm-receipt": return completed(notificationService.receive(requestId, actor)); case "05:query-account": return completed(requireNotification(requestId)); case "05:verify-deduction": return completed(notificationService.submit(requestId, actor)); + case "05:check-application": + return completed(requireNotification(requestId)); case "05:execute-deduction": return completed(executionService.execute(requireNotification(requestId).getTransactionId(), owner, request.getReserveAccountNo(),request.getReserveAccountName(),request.getDeductionAmount(),actor)); case "05:generate-balance-notice": case "05:send-balance-notice": + case "05:confirm-balance-receipt": ReserveDeductionNotificationView notification = requireNotification(requestId); return completed(executionService.find(notification.getTransactionId()) .orElseThrow(() -> validation("准备金尚未扣减,不能生成余额通知"))); case "06:confirm-production-receipt": return completed(productionService.produce(requestId, actor, keySubject)); case "06:generate-production-digest": + case "07:preliminary-verification": + case "07:generate-ownership-list": return completed(productionService.digests(requestId) .orElseThrow(() -> validation("请先生成数字货币生产批次"))); + case "06:send-authorization": + case "06:receive-authorization": + case "06:generate-currency": + case "06:assemble-production-confirmation": + case "06:send-production-confirmation": + return completed(productionService.find(requestId).orElseThrow(()->validation("请先生成生产授权"))); case "07:central-confirm-ownership": return completed(ownershipService.confirm(requestId, actor, keySubject)); case "07:verify-central-bank-signature": @@ -226,6 +253,11 @@ public class IssuanceTrainingActionService { return completed(ownershipService.activateCurrencies(requestId, actor, keySubject)); case "07:sign-bank-receipt": return completed(ownershipService.signReceipt(requestId, actor, keySubject)); + case "07:transfer-ownership": + case "07:generate-ownership-report": + case "07:send-ownership-result": + case "07:update-bank-status": + return completed(ownershipService.findProduction(requestId).orElseThrow(()->validation("数字货币确权结果不存在"))); case "07:load-ownership-result": return ActionOutcome.completedAttempt(ownershipService.findProduction(requestId) .orElseThrow(() -> validation("数字货币确权结果不存在"))); @@ -234,6 +266,25 @@ public class IssuanceTrainingActionService { } } + public com.yau.digitalrmb.issuance.application.query.CentralBankIssuanceBusinessReviewView previewReview( + UUID id,ExperimentSubject subject,IssuanceAuditActor actor,InstitutionKeySubject keySubject){ + commercialService.getCommercialBankView(id,actor); + IssuanceActionOrder.requireReady(attempts.current(com.yau.digitalrmb.training.attempt.domain.ExperimentModule.ISSUANCE,subject),"03:query-institution-input"); + return reviewService.review(id,actor,keySubject); + } + + public void validateInput(UUID attemptId,String step,String action,IssuanceActionRequest input,ExperimentSubject subject, + IssuanceAuditActor actor,InstitutionKeySubject keySubject){ + String key=step+":"+action; + if(!Arrays.asList("01:refresh-custom-application","01:generate-digest","01:sign-application","02:verify-signature", + "02:recalculate-digest","02:compare-digest","04:generate-reserve-deduction-request","05:query-account", + "05:execute-deduction","06:generate-production-digest","07:central-confirm-ownership").contains(key))throw validation("此操作没有可填写的验证数据"); + ExperimentAttemptView attempt=attempts.detail(attemptId,subject);IssuanceActionOrder.requireReady(attempt,key); + UUID id=resolveRequestId(attempt.getBusinessId(),input.getRequestId()); + if(id!=null)commercialService.getCommercialBankView(id,actor); + try{inputValidator.validate(key,input,id,actor,keySubject);}catch(TrainingInputException e){throw scoredInputError(e,subject);} + } + private ReserveDeductionNotificationView requireNotification(UUID requestId) { return notificationService.find(requestId) .orElseThrow(() -> validation("准备金扣减通知不存在")); diff --git a/src/main/java/com/yau/digitalrmb/issuance/application/service/IssuanceTrainingResetService.java b/src/main/java/com/yau/digitalrmb/issuance/application/service/IssuanceTrainingResetService.java index 5b87e76..d7821ed 100644 --- a/src/main/java/com/yau/digitalrmb/issuance/application/service/IssuanceTrainingResetService.java +++ b/src/main/java/com/yau/digitalrmb/issuance/application/service/IssuanceTrainingResetService.java @@ -169,6 +169,7 @@ public class IssuanceTrainingResetService { count += jdbc.update("DELETE FROM digital_currency_production_batch WHERE request_id=?", requestId); count += jdbc.update("DELETE FROM issuance_source_currency_usage WHERE issuance_request_id=?", requestId); count += jdbc.update("DELETE FROM reserve_deduction_execution WHERE request_id=?", requestId); + count += jdbc.update("DELETE FROM issuance_reserve_application WHERE request_id=?", requestId); count += jdbc.update("DELETE FROM reserve_deduction_notification WHERE request_id=?", requestId); count += jdbc.update("DELETE FROM central_bank_issuance_business_review WHERE request_id=?", requestId); count += jdbc.update("DELETE FROM central_bank_issuance_verification WHERE request_id=?", requestId); diff --git a/src/main/java/com/yau/digitalrmb/issuance/application/service/ProductionAuthorizationPolicy.java b/src/main/java/com/yau/digitalrmb/issuance/application/service/ProductionAuthorizationPolicy.java new file mode 100644 index 0000000..35f0bf0 --- /dev/null +++ b/src/main/java/com/yau/digitalrmb/issuance/application/service/ProductionAuthorizationPolicy.java @@ -0,0 +1,23 @@ +package com.yau.digitalrmb.issuance.application.service; +import com.yau.digitalrmb.issuance.domain.model.DigitalCurrencyProductionBatch; +import com.yau.digitalrmb.issuance.domain.repository.DigitalCurrencyProductionRepository; +import com.yau.digitalrmb.shared.api.ErrorCode; +import com.yau.digitalrmb.shared.exception.BusinessException; +import org.springframework.stereotype.Service; +import org.springframework.beans.factory.annotation.Autowired; +import java.time.*; +import java.util.UUID; + +@Service +public class ProductionAuthorizationPolicy { + public static final Duration VALIDITY=Duration.ofHours(1); + private final DigitalCurrencyProductionRepository batches; + private final Clock clock; + @Autowired public ProductionAuthorizationPolicy(DigitalCurrencyProductionRepository batches){this(batches,Clock.systemUTC());} + ProductionAuthorizationPolicy(DigitalCurrencyProductionRepository batches,Clock clock){this.batches=batches;this.clock=clock;} + public void requireActive(UUID id){batches.findByRequestId(id).ifPresent(this::requireActive);} + public void requireActive(DigitalCurrencyProductionBatch batch){ + if("WAITING_OWNERSHIP".equals(batch.getStatus()) && !clock.instant().isBefore(batch.getCreatedAt().plus(VALIDITY))) + throw new BusinessException(ErrorCode.VALIDATION_ERROR,"生产授权已超过1小时有效期,请重新实训并申请新的生产授权"); + } +} diff --git a/src/main/java/com/yau/digitalrmb/issuance/application/service/ReserveDeductionApplicationService.java b/src/main/java/com/yau/digitalrmb/issuance/application/service/ReserveDeductionApplicationService.java new file mode 100644 index 0000000..3f373f4 --- /dev/null +++ b/src/main/java/com/yau/digitalrmb/issuance/application/service/ReserveDeductionApplicationService.java @@ -0,0 +1,71 @@ +package com.yau.digitalrmb.issuance.application.service; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.yau.digitalrmb.institutionidentity.application.*; +import com.yau.digitalrmb.institutionidentity.domain.InstitutionIdentityCryptography; +import com.yau.digitalrmb.issuance.domain.model.*; +import com.yau.digitalrmb.issuance.domain.repository.*; +import com.yau.digitalrmb.shared.api.ErrorCode; +import com.yau.digitalrmb.shared.exception.BusinessException; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import java.time.Instant; +import java.util.*; + +@Service +public class ReserveDeductionApplicationService { + private final ReserveDeductionApplicationRepository applications; + private final ReserveDeductionNotificationRepository notifications; + private final InstitutionKeyService keys; + private final InstitutionIdentityCryptography crypto; + private final ObjectMapper mapper; + public ReserveDeductionApplicationService(ReserveDeductionApplicationRepository applications,ReserveDeductionNotificationRepository notifications, + InstitutionKeyService keys,InstitutionIdentityCryptography crypto,ObjectMapper mapper){ + this.applications=applications;this.notifications=notifications;this.keys=keys;this.crypto=crypto;this.mapper=mapper; + } + @Transactional + public Map sign(UUID id,InstitutionKeySubject subject){ + ReserveDeductionNotification notice=notice(id); + if(!Arrays.asList("RECEIVED","SUBMITTED").contains(notice.getStatus()))throw invalid("请先确认接收准备金扣减通知"); + if(!applications.find(id).isPresent()){ + String original=original(notice),digest=crypto.sm3(original); + applications.saveIfAbsent(new ReserveDeductionApplication(id,original,digest,keys.signCommercialBank(subject,digest), + keys.commercialBankSecondPublicKeyOrNull(subject),Instant.now(),subject.getUserId(),subject.getSchoolId(),subject.getClassId())); + } + requireValid(id,subject); + return find(id,subject); + } + @Transactional(readOnly=true) + public Map find(UUID id,InstitutionKeySubject subject){ + ReserveDeductionApplication value=owned(id,subject); + try{ + Map result=mapper.readValue(value.getOriginalText(),new TypeReference>(){}); + result.put("originalText",value.getOriginalText());result.put("digest",value.getDigest()); + result.put("bankSignature",value.getBankSignature());result.put("bankPublicKey",value.getBankPublicKey()); + result.put("signingKeyRef","BANK_SECOND_SM2_KEY");result.put("signedAt",value.getSignedAt());return result; + }catch(Exception e){throw invalid("准备金扣减申请原文无法解析");} + } + @Transactional(readOnly=true) + public void requireValid(UUID id,InstitutionKeySubject subject){ + ReserveDeductionApplication value=owned(id,subject); + String current=original(notice(id)); + if(!current.equals(value.getOriginalText())||!crypto.sm3(current).equalsIgnoreCase(value.getDigest()) + ||!keys.matchesCommercialBankPublicKey(subject,value.getBankPublicKey()) + ||!keys.verifyCommercialBank(subject,value.getBankPublicKey(),value.getDigest(),value.getBankSignature())) + throw invalid("准备金扣减申请的银行签名或申请内容校验失败,不能提交或执行扣款"); + } + private ReserveDeductionApplication owned(UUID id,InstitutionKeySubject subject){ + ReserveDeductionApplication value=applications.find(id).orElseThrow(()->invalid("请先生成并签名准备金扣减申请")); + if(!value.getUserId().equals(subject.getUserId())||value.getSchoolId()!=subject.getSchoolId()||value.getClassId()!=subject.getClassId()) + throw new BusinessException(ErrorCode.FORBIDDEN,"不能访问其他实训主体的扣减申请"); + return value; + } + private ReserveDeductionNotification notice(UUID id){return notifications.findByRequestId(id).orElseThrow(()->invalid("准备金扣减通知不存在"));} + private String original(ReserveDeductionNotification n){ + Map fields=new LinkedHashMap<>();fields.put("requestId",n.getRequestId().toString());fields.put("transactionId",n.getTransactionId()); + fields.put("bankCode",n.getBankCode());fields.put("organizationId",n.getOrganizationId());fields.put("reserveAccountNo",n.getReserveAccountNo()); + fields.put("reserveAccountName",n.getReserveAccountName());fields.put("currency",n.getCurrency());fields.put("deductionAmount",n.getDeductionAmount().setScale(2).toPlainString());fields.put("reason","数字货币发行"); + try{return mapper.writeValueAsString(fields);}catch(Exception e){throw invalid("不能生成准备金扣减申请原文");} + } + private BusinessException invalid(String message){return new BusinessException(ErrorCode.VALIDATION_ERROR,message);} +} diff --git a/src/main/java/com/yau/digitalrmb/issuance/application/service/ReserveDeductionExecutionService.java b/src/main/java/com/yau/digitalrmb/issuance/application/service/ReserveDeductionExecutionService.java index 53c3e5e..113c2ad 100644 --- a/src/main/java/com/yau/digitalrmb/issuance/application/service/ReserveDeductionExecutionService.java +++ b/src/main/java/com/yau/digitalrmb/issuance/application/service/ReserveDeductionExecutionService.java @@ -21,6 +21,7 @@ import java.util.Optional; @Service public class ReserveDeductionExecutionService { + @org.springframework.beans.factory.annotation.Autowired private ReserveDeductionApplicationService signedApplications; private final ReserveDeductionNotificationRepository notificationRepository; private final ReserveDeductionExecutionRepository executionRepository; private final CentralBankInstitutionAccountRepository accountRepository; @@ -44,6 +45,8 @@ public class ReserveDeductionExecutionService { ReserveDeductionNotification notification = notificationRepository.findByTransactionId(required(transactionId, "交易信息标识")) .orElseThrow(() -> new BusinessException(ErrorCode.RESOURCE_NOT_FOUND, "准备金扣减通知不存在")); requireNotificationMatches(notification, reserveAccountNo, reserveAccountName, deductionAmount); + if(signedApplications!=null)signedApplications.requireValid(notification.getRequestId(), + new com.yau.digitalrmb.institutionidentity.application.InstitutionKeySubject(owner.getUserId(),owner.getSchoolId(),owner.getClassId())); Optional existing = executionRepository.findByTransactionId(transactionId); if (existing.isPresent()) return ReserveDeductionExecutionView.from(existing.get()); diff --git a/src/main/java/com/yau/digitalrmb/issuance/domain/model/ReserveDeductionApplication.java b/src/main/java/com/yau/digitalrmb/issuance/domain/model/ReserveDeductionApplication.java new file mode 100644 index 0000000..bb1660e --- /dev/null +++ b/src/main/java/com/yau/digitalrmb/issuance/domain/model/ReserveDeductionApplication.java @@ -0,0 +1,18 @@ +package com.yau.digitalrmb.issuance.domain.model; +import lombok.AllArgsConstructor; +import lombok.Getter; +import java.time.Instant; +import java.util.UUID; + +@Getter @AllArgsConstructor +public final class ReserveDeductionApplication { + private final UUID requestId; + private final String originalText; + private final String digest; + private final String bankSignature; + private final String bankPublicKey; + private final Instant signedAt; + private final String userId; + private final long schoolId; + private final long classId; +} diff --git a/src/main/java/com/yau/digitalrmb/issuance/domain/repository/ReserveDeductionApplicationRepository.java b/src/main/java/com/yau/digitalrmb/issuance/domain/repository/ReserveDeductionApplicationRepository.java new file mode 100644 index 0000000..5f74bf4 --- /dev/null +++ b/src/main/java/com/yau/digitalrmb/issuance/domain/repository/ReserveDeductionApplicationRepository.java @@ -0,0 +1,9 @@ +package com.yau.digitalrmb.issuance.domain.repository; +import com.yau.digitalrmb.issuance.domain.model.ReserveDeductionApplication; +import java.util.Optional; +import java.util.UUID; + +public interface ReserveDeductionApplicationRepository { + Optional find(UUID requestId); + void saveIfAbsent(ReserveDeductionApplication application); +} diff --git a/src/main/java/com/yau/digitalrmb/issuance/infrastructure/persistence/repository/JdbcReserveDeductionApplicationRepository.java b/src/main/java/com/yau/digitalrmb/issuance/infrastructure/persistence/repository/JdbcReserveDeductionApplicationRepository.java new file mode 100644 index 0000000..40fb2af --- /dev/null +++ b/src/main/java/com/yau/digitalrmb/issuance/infrastructure/persistence/repository/JdbcReserveDeductionApplicationRepository.java @@ -0,0 +1,26 @@ +package com.yau.digitalrmb.issuance.infrastructure.persistence.repository; +import com.yau.digitalrmb.issuance.domain.model.ReserveDeductionApplication; +import com.yau.digitalrmb.issuance.domain.repository.ReserveDeductionApplicationRepository; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; +import java.sql.Timestamp; +import java.util.*; + +@Repository +public class JdbcReserveDeductionApplicationRepository implements ReserveDeductionApplicationRepository { + private final JdbcTemplate jdbc; + public JdbcReserveDeductionApplicationRepository(JdbcTemplate jdbc){this.jdbc=jdbc;} + public Optional find(UUID requestId){ + List result=jdbc.query("SELECT * FROM issuance_reserve_application WHERE request_id=? AND deleted=0", + (rs,row)->new ReserveDeductionApplication(UUID.fromString(rs.getString("request_id")),rs.getString("original_text"), + rs.getString("digest"),rs.getString("bank_signature"),rs.getString("bank_public_key"),rs.getTimestamp("signed_at").toInstant(), + rs.getString("user_id"),rs.getLong("school_id"),rs.getLong("class_id")),requestId.toString()); + return result.isEmpty()?Optional.empty():Optional.of(result.get(0)); + } + public void saveIfAbsent(ReserveDeductionApplication value){ + jdbc.update("INSERT INTO issuance_reserve_application (request_id,original_text,digest,bank_signature,bank_public_key,signed_at,"+ + "user_id,school_id,class_id,created_at,updated_at,created_by,updated_by,deleted) VALUES (?,?,?,?,?,?,?,?,?,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,?,?,0) "+ + "ON DUPLICATE KEY UPDATE request_id=VALUES(request_id)",value.getRequestId().toString(),value.getOriginalText(),value.getDigest(), + value.getBankSignature(),value.getBankPublicKey(),Timestamp.from(value.getSignedAt()),value.getUserId(),value.getSchoolId(),value.getClassId(),value.getUserId(),value.getUserId()); + } +} diff --git a/src/main/java/com/yau/digitalrmb/issuance/interfaces/dto/IssuanceActionRequest.java b/src/main/java/com/yau/digitalrmb/issuance/interfaces/dto/IssuanceActionRequest.java index 2ea8d92..f947096 100644 --- a/src/main/java/com/yau/digitalrmb/issuance/interfaces/dto/IssuanceActionRequest.java +++ b/src/main/java/com/yau/digitalrmb/issuance/interfaces/dto/IssuanceActionRequest.java @@ -24,6 +24,8 @@ public class IssuanceActionRequest { private String reserveAccountNo; private String reserveAccountName; private BigDecimal deductionAmount; + @com.fasterxml.jackson.annotation.JsonInclude(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL) private String rawAmount; + public String getRawAmount(){return rawAmount;} public void setRawAmount(String v){rawAmount=v;} public String getAlgorithm() { return algorithm; } public String getRequestTimestamp() { return requestTimestamp; } diff --git a/src/main/java/com/yau/digitalrmb/issuance/interfaces/rest/CentralBankIssuanceController.java b/src/main/java/com/yau/digitalrmb/issuance/interfaces/rest/CentralBankIssuanceController.java index b5967b4..01c71bf 100644 --- a/src/main/java/com/yau/digitalrmb/issuance/interfaces/rest/CentralBankIssuanceController.java +++ b/src/main/java/com/yau/digitalrmb/issuance/interfaces/rest/CentralBankIssuanceController.java @@ -117,13 +117,20 @@ public class CentralBankIssuanceController { new BusinessException(ErrorCode.RESOURCE_NOT_FOUND, "发行计划核查结果不存在"))); } + @GetMapping("/requests/{id}/business-review/preview") + @Operation(summary="查询业务核查所需数据",description="要求第二步已完成,供第三步逐项核对展示;不记录第四步完成进度") + public ApiResponse previewBusinessReview(@PathVariable UUID id){ + CurrentUser user=currentUserService.getCurrentUser(); + return ok(trainingActionService.previewReview(id,subject(user),actor(user),InstitutionKeySubject.from(user))); + } + @PostMapping("/requests/{id}/reserve-deduction-notification") @Operation(summary = "发送准备金扣减通知", description = "仅在发行请求验签和业务核查通过后发送通知,不执行实际准备金扣款") - public ApiResponse sendReserveDeductionNotification(@PathVariable UUID id) { + public ApiResponse sendReserveDeductionNotification(@PathVariable UUID id,@RequestBody(required=false) IssuanceActionRequest input) { CurrentUser user = currentUserService.getCurrentUser(); IssuanceAuditActor actor = actor(user); accessGuard.requireRequestOwner(id, actor); - runAction(id, "04", "generate-reserve-deduction-request", user); + runAction(id, "04", "generate-reserve-deduction-request", user,input); return ok(reserveDeductionNotificationService.find(id).orElseThrow(() -> new BusinessException(ErrorCode.RESOURCE_NOT_FOUND, "准备金扣减通知不存在"))); } @@ -184,8 +191,8 @@ public class CentralBankIssuanceController { CurrentUser currentUser = currentUserService.getCurrentUser(); IssuanceAuditActor actor = actor(currentUser); accessGuard.requireRequestOwner(id, actor); - String[] actions = {"central-confirm-ownership", "verify-central-bank-signature", - "activate-bank-currencies", "sign-bank-receipt", "load-ownership-result"}; + String[] actions = {"preliminary-verification","generate-ownership-list","central-confirm-ownership", "transfer-ownership", "verify-central-bank-signature", + "activate-bank-currencies", "generate-ownership-report", "send-ownership-result", "update-bank-status", "sign-bank-receipt", "load-ownership-result"}; for (String action : actions) runAction(id, "07", action, currentUser, "central-confirm-ownership".equals(action) ? input : null); return ok(digitalCurrencyOwnershipConfirmationService.findProduction(id).orElseThrow(() -> diff --git a/src/main/java/com/yau/digitalrmb/issuance/interfaces/rest/CommercialBankIssuanceController.java b/src/main/java/com/yau/digitalrmb/issuance/interfaces/rest/CommercialBankIssuanceController.java index b3b8a2b..5b684dc 100644 --- a/src/main/java/com/yau/digitalrmb/issuance/interfaces/rest/CommercialBankIssuanceController.java +++ b/src/main/java/com/yau/digitalrmb/issuance/interfaces/rest/CommercialBankIssuanceController.java @@ -53,6 +53,7 @@ import java.util.UUID; @RequestMapping("/api/v1/commercial-banks/issuance") @Tag(name = "数字货币发行模块 - 商业银行端", description = "商业银行发起和处理数字货币发行申请") public class CommercialBankIssuanceController { + @org.springframework.beans.factory.annotation.Autowired private com.yau.digitalrmb.issuance.application.service.ReserveDeductionApplicationService signedApplications; private final CommercialBankIssuanceApplicationService service; private final DenominationPlanService denominationPlanService; private final ReserveDeductionNotificationService notificationService; @@ -118,7 +119,10 @@ public class CommercialBankIssuanceController { IssuanceActionRequest actionRequest = actionRequest(null, request.getBankCode(), request.getOrganizationId(), request.getTotalAmount(), request.getCurrency(), request.getDenominations()); ExperimentSubject subject = subject(user); - ExperimentAttemptView attempt = attemptService.create(ExperimentModule.ISSUANCE, subject); + ExperimentAttemptView attempt; + try { attempt=attemptService.current(ExperimentModule.ISSUANCE,subject); } + catch(BusinessException e){if(e.getErrorCode()!=ErrorCode.RESOURCE_NOT_FOUND)throw e;attempt=attemptService.create(ExperimentModule.ISSUANCE,subject);} + if(attempt.getBusinessId()!=null)attempt=attemptService.create(ExperimentModule.ISSUANCE,subject); trainingActionService.execute(attempt.getAttemptId(), "01", "refresh-custom-application", actionRequest, subject, actor(user), InstitutionKeySubject.from(user)); attempt = attemptService.detail(attempt.getAttemptId(), subject); @@ -216,6 +220,21 @@ public class CommercialBankIssuanceController { new BusinessException(ErrorCode.RESOURCE_NOT_FOUND, "准备金扣减通知不存在"))); } + @PostMapping("/requests/{id}/reserve-deduction-application/sign") + @Operation(summary="生成并签名准备金扣减申请",description="使用当前实训商业银行第二私钥对规范申请原文的SM3摘要执行SM2签名") + public ApiResponse> signDeductionApplication(@PathVariable UUID id){ + CurrentUser user=currentUserService.getCurrentUser(); + runAction("04","sign-reserve-application",actionRequest(id),user); + return ok(signedApplications.find(id,InstitutionKeySubject.from(user))); + } + + @GetMapping("/requests/{id}/reserve-deduction-application") + @Operation(summary="读取当前实训已签名的准备金扣减申请") + public ApiResponse> signedDeductionApplication(@PathVariable UUID id){ + CurrentUser user=currentUserService.getCurrentUser();service.getCommercialBankView(id,actor(user)); + return ok(signedApplications.find(id,InstitutionKeySubject.from(user))); + } + private ExperimentAttemptView runAction(String stepCode, String actionCode, IssuanceActionRequest request, CurrentUser user) { ExperimentSubject subject = subject(user); diff --git a/src/main/java/com/yau/digitalrmb/issuance/interfaces/rest/IssuanceTrainingAttemptController.java b/src/main/java/com/yau/digitalrmb/issuance/interfaces/rest/IssuanceTrainingAttemptController.java index 11b34cc..1e90b8d 100644 --- a/src/main/java/com/yau/digitalrmb/issuance/interfaces/rest/IssuanceTrainingAttemptController.java +++ b/src/main/java/com/yau/digitalrmb/issuance/interfaces/rest/IssuanceTrainingAttemptController.java @@ -84,6 +84,15 @@ public class IssuanceTrainingAttemptController { numeric(user.getClassId(), "班级 ID"), ""); } + @PostMapping("/{attemptId}/steps/{stepCode}/validate/{actionCode}") + @Operation(summary="校验发行实训填写内容",description="以当前实训真实数据核对原始输入;错误计入成绩,不执行扣款、签名或推进进度") + public ApiResponse> validate(@PathVariable UUID attemptId,@PathVariable String stepCode, + @PathVariable String actionCode,@RequestBody IssuanceActionRequest input){ + CurrentUser user=currentUserService.getCurrentUser(); + actionService.validateInput(attemptId,stepCode,actionCode,input,subject(user),actor(user),InstitutionKeySubject.from(user)); + return ok(java.util.Collections.singletonMap("valid",true)); + } + private IssuanceAuditActor actor(CurrentUser user) { return new IssuanceAuditActor(required(user.getUserId(), "用户 ID"), required(user.getName(), "用户姓名")); } diff --git a/src/main/java/com/yau/digitalrmb/payment/application/service/PaymentTrainingActionService.java b/src/main/java/com/yau/digitalrmb/payment/application/service/PaymentTrainingActionService.java index a80bb34..7338571 100644 --- a/src/main/java/com/yau/digitalrmb/payment/application/service/PaymentTrainingActionService.java +++ b/src/main/java/com/yau/digitalrmb/payment/application/service/PaymentTrainingActionService.java @@ -85,6 +85,37 @@ public class PaymentTrainingActionService { return executeInternal(attemptId, stepCode, actionCode, request, subject, actor, false); } + /** Validate learner answers without creating an order or advancing an experiment. */ + public void validateInput(UUID attemptId,String step,String action,PaymentActionRequest input, + ExperimentSubject subject,PaymentActor actor) { + String key=step+":"+action; + ExperimentAttemptView attempt=attempts.detail(attemptId,subject); + if(attempt.getModuleCode()!=com.yau.digitalrmb.training.attempt.domain.ExperimentModule.PAYMENT)throw validation("实验类型不匹配"); + int index=ACTIONS.indexOf(key); + if(!ANSWER_ACTIONS.contains(key))throw validation("此操作没有原文填写项"); + requirePrevious(attempt,index); + try{checkAnswer(key,input,attempt,actor);}catch(TrainingInputException e){ + if(scoreService==null)throw e; + int count=scoreService.recordError(subject.getUserId()); + throw new TrainingInputException(e.getMessage()+",本次实训第"+count+"次错误"); + } + } + private static final List ANSWER_ACTIONS=Arrays.asList("02:concatenate-payment","02:generate-digest"); + private void checkAnswer(String key,PaymentActionRequest input,ExperimentAttemptView attempt,PaymentActor actor){ + if("02:concatenate-payment".equals(key)){ + Map expected=paymentSource(input,attempt,actor); + if(decimal(expected,"amount").compareTo(new BigDecimal("1000.00"))!=0)throw inputValidation("本案例支付金额应为1000.00元"); + com.yau.digitalrmb.shared.validation.TrainingAnswerChecks.same(input.getNote(),"房租","支付备注"); + com.yau.digitalrmb.shared.validation.TrainingAnswerChecks.same(input.getPayerWalletId(),text(expected,"payerWalletId"),"付款钱包ID"); + com.yau.digitalrmb.shared.validation.TrainingAnswerChecks.same(input.getPayeeWalletId(),text(expected,"payeeWalletId"),"收款钱包ID"); + com.yau.digitalrmb.shared.validation.TrainingAnswerChecks.same(input.getTimestamp(),text(expected,"timestamp"),"时间戳"); + com.yau.digitalrmb.shared.validation.TrainingAnswerChecks.original(input.getSourceText(),text(expected,"sourceText"),3); + }else{ + requireAlgorithm(input,"SM3"); + com.yau.digitalrmb.shared.validation.TrainingAnswerChecks.original(input.getSourceText(),text(prior(attempt,"02","concatenate-payment"),"sourceText"),3); + } + } + private ExperimentActionView executeInternal(UUID attemptId, String stepCode, String actionCode, PaymentActionRequest request, ExperimentSubject subject, PaymentActor actor, boolean validateStudentInput) { @@ -93,7 +124,9 @@ public class PaymentTrainingActionService { if (index < 0) throw validation("不支持的支付实验动作:" + key); PaymentActionRequest input = request == null ? new PaymentActionRequest() : request; ExperimentAttemptView attempt = attempts.detail(attemptId, subject); + if(attempt.getModuleCode()!=com.yau.digitalrmb.training.attempt.domain.ExperimentModule.PAYMENT)throw validation("实验类型不匹配"); requirePrevious(attempt, index); + if(validateStudentInput && ANSWER_ACTIONS.contains(key) && attempt.getActions().stream().anyMatch(a->stepCode.equals(a.getStepCode()) && actionCode.equals(a.getActionCode()) && a.getActionStatus()==ActionStatus.COMPLETED))validateInput(attemptId,stepCode,actionCode,input,subject,actor); UUID paymentId = businessId(attempt.getBusinessId()); if (index > ACTIONS.indexOf("02:generate-digest") && paymentId == null) { throw validation("请先生成支付摘要"); @@ -104,6 +137,7 @@ public class PaymentTrainingActionService { fingerprint(key, input, subject), Object.class, () -> { try { + if(validateStudentInput && ANSWER_ACTIONS.contains(key))checkAnswer(key,input,attempt,actor); return run(key, input, attempt, boundPaymentId, actor, validateStudentInput); } catch (TrainingInputException exception) { if (scoreService == null) throw exception; @@ -227,7 +261,7 @@ public class PaymentTrainingActionService { && !context.getPayer().getWalletId().equals(request.getPayerWalletId().trim())) { throw inputValidation("付款钱包不属于当前用户"); } - BigDecimal amount = money(request.getAmount()); + BigDecimal amount = money(com.yau.digitalrmb.shared.validation.TrainingAnswerChecks.amount(request.getRawAmount(),request.getAmount())); String note = request.getNote() == null ? "" : request.getNote().trim(); if (note.length() > 256) throw inputValidation("支付备注最多256个字符"); String timestamp = text(prior(attempt, "02", "generate-timestamp"), "timestamp"); diff --git a/src/main/java/com/yau/digitalrmb/payment/infrastructure/persistence/PaymentReserveLedger.java b/src/main/java/com/yau/digitalrmb/payment/infrastructure/persistence/PaymentReserveLedger.java index 00d8a3e..47e8aa3 100644 --- a/src/main/java/com/yau/digitalrmb/payment/infrastructure/persistence/PaymentReserveLedger.java +++ b/src/main/java/com/yau/digitalrmb/payment/infrastructure/persistence/PaymentReserveLedger.java @@ -30,18 +30,18 @@ public class PaymentReserveLedger { BigDecimal debit = balances.get(payer).subtract(order.getAmount()); if (debit.signum() < 0) throw invalid("付款银行教学准备金余额不足"); BigDecimal credit = balances.get(payee).add(order.getAmount()); - jdbc.update("UPDATE payment_reserve_account SET balance=? WHERE id=?", debit, payer); - jdbc.update("UPDATE payment_reserve_account SET balance=? WHERE id=?", credit, payee); + jdbc.update("UPDATE payment_reserve_account SET balance=?,updated_at=CURRENT_TIMESTAMP,updated_by=? WHERE id=?", debit,actor.getUserId(), payer); + jdbc.update("UPDATE payment_reserve_account SET balance=?,updated_at=CURRENT_TIMESTAMP,updated_by=? WHERE id=?", credit,actor.getUserId(), payee); jdbc.update("INSERT INTO payment_reserve_entry (payment_id,payer_account_id,payee_account_id,amount," + - "payer_before,payer_after,payee_before,payee_after,reversed,created_at) " + - "VALUES (?,?,?,?,?,?,?,?,FALSE,CURRENT_TIMESTAMP)", - order.getId().toString(), payer, payee, order.getAmount(), balances.get(payer), debit, balances.get(payee), credit); + "payer_before,payer_after,payee_before,payee_after,reversed,created_at,created_by,updated_by) " + + "VALUES (?,?,?,?,?,?,?,?,FALSE,CURRENT_TIMESTAMP,?,?)", + order.getId().toString(), payer, payee, order.getAmount(), balances.get(payer), debit, balances.get(payee), credit,actor.getUserId(),actor.getUserId()); } @Transactional public void reverse(List paymentIds) { for (String paymentId : paymentIds) { - List> entries = jdbc.queryForList("SELECT payer_account_id,payee_account_id,amount " + + List> entries = jdbc.queryForList("SELECT payer_account_id,payee_account_id,amount,created_by " + "FROM payment_reserve_entry WHERE payment_id=? AND reversed=FALSE FOR UPDATE", paymentId); if (entries.isEmpty()) continue; Map entry = entries.get(0); @@ -50,9 +50,9 @@ public class PaymentReserveLedger { BigDecimal amount = (BigDecimal) entry.get("amount"); Map balances = lock(payer, payee); if (balances.get(payee).compareTo(amount) < 0) throw invalid("收款银行教学准备金不足,不能回滚清算"); - jdbc.update("UPDATE payment_reserve_account SET balance=balance+? WHERE id=?", amount, payer); - jdbc.update("UPDATE payment_reserve_account SET balance=balance-? WHERE id=?", amount, payee); - jdbc.update("UPDATE payment_reserve_entry SET reversed=TRUE WHERE payment_id=?", paymentId); + jdbc.update("UPDATE payment_reserve_account SET balance=balance+?,updated_at=CURRENT_TIMESTAMP,updated_by=? WHERE id=?", amount,entry.get("created_by"), payer); + jdbc.update("UPDATE payment_reserve_account SET balance=balance-?,updated_at=CURRENT_TIMESTAMP,updated_by=? WHERE id=?", amount,entry.get("created_by"), payee); + jdbc.update("UPDATE payment_reserve_entry SET reversed=TRUE,updated_at=CURRENT_TIMESTAMP,updated_by=? WHERE payment_id=?",entry.get("created_by"), paymentId); } } @@ -61,8 +61,8 @@ public class PaymentReserveLedger { .getBytes(StandardCharsets.UTF_8)).toString(); if (jdbc.queryForObject("SELECT COUNT(*) FROM payment_reserve_account WHERE id=?", Integer.class,id) == 0) { try { - jdbc.update("INSERT INTO payment_reserve_account (id,user_id,school_id,class_id,bank_code,balance) VALUES (?,?,?,?,?,?)", - id,actor.getUserId(),actor.getSchoolId(),actor.getClassId(),bankCode,INITIAL); + jdbc.update("INSERT INTO payment_reserve_account (id,user_id,school_id,class_id,bank_code,balance,created_by,updated_by) VALUES (?,?,?,?,?,?,?,?)", + id,actor.getUserId(),actor.getSchoolId(),actor.getClassId(),bankCode,INITIAL,actor.getUserId(),actor.getUserId()); } catch (DuplicateKeyException concurrentInitialization) { if (jdbc.queryForObject("SELECT COUNT(*) FROM payment_reserve_account WHERE id=?",Integer.class,id) == 0) throw concurrentInitialization; diff --git a/src/main/java/com/yau/digitalrmb/payment/interfaces/dto/PaymentActionRequest.java b/src/main/java/com/yau/digitalrmb/payment/interfaces/dto/PaymentActionRequest.java index 6452b62..a3aa0ad 100644 --- a/src/main/java/com/yau/digitalrmb/payment/interfaces/dto/PaymentActionRequest.java +++ b/src/main/java/com/yau/digitalrmb/payment/interfaces/dto/PaymentActionRequest.java @@ -10,6 +10,12 @@ public class PaymentActionRequest { private String algorithm; private String privateKey; private String publicKey; + @com.fasterxml.jackson.annotation.JsonInclude(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL) private String sourceText; + @com.fasterxml.jackson.annotation.JsonInclude(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL) private String rawAmount; + @com.fasterxml.jackson.annotation.JsonInclude(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL) private String timestamp; + public String getSourceText(){return sourceText;} public void setSourceText(String v){sourceText=v;} + public String getRawAmount(){return rawAmount;} public void setRawAmount(String v){rawAmount=v;} + public String getTimestamp(){return timestamp;} public void setTimestamp(String v){timestamp=v;} public String getPayerWalletId() { return payerWalletId; } public void setPayerWalletId(String payerWalletId) { this.payerWalletId = payerWalletId; } diff --git a/src/main/java/com/yau/digitalrmb/payment/interfaces/rest/PaymentTrainingAttemptController.java b/src/main/java/com/yau/digitalrmb/payment/interfaces/rest/PaymentTrainingAttemptController.java index 1e00246..0c44d05 100644 --- a/src/main/java/com/yau/digitalrmb/payment/interfaces/rest/PaymentTrainingAttemptController.java +++ b/src/main/java/com/yau/digitalrmb/payment/interfaces/rest/PaymentTrainingAttemptController.java @@ -77,6 +77,15 @@ public class PaymentTrainingAttemptController { request == null ? new PaymentActionRequest() : request, subject(user), actor(user))); } + @PostMapping("/{attemptId}/steps/{stepCode}/validate/{actionCode}") + @Operation(summary="核对原始填写内容",description="根据当前用户实验数据校验,错误计入成绩;不扣款、不创建订单、不推进进度") + public ApiResponse> validate(@PathVariable UUID attemptId,@PathVariable String stepCode, + @PathVariable String actionCode,@RequestBody PaymentActionRequest input){ + CurrentUser user=users.getCurrentUser(); + actions.validateInput(attemptId,stepCode,actionCode,input,subject(user),actor(user)); + return ok(java.util.Collections.singletonMap("valid",true)); + } + private ExperimentSubject subject(CurrentUser user) { return new ExperimentSubject(required(user.getUserId(), "用户 ID"), numeric(user.getSchoolId(), "学校 ID"), numeric(user.getClassId(), "班级 ID"), ""); diff --git a/src/main/java/com/yau/digitalrmb/shared/validation/TrainingAnswerChecks.java b/src/main/java/com/yau/digitalrmb/shared/validation/TrainingAnswerChecks.java new file mode 100644 index 0000000..72d6407 --- /dev/null +++ b/src/main/java/com/yau/digitalrmb/shared/validation/TrainingAnswerChecks.java @@ -0,0 +1,27 @@ +package com.yau.digitalrmb.shared.validation; +import com.yau.digitalrmb.shared.exception.TrainingInputException; +import java.math.BigDecimal; + +/** Shared parsing of learner answers; expected values always come from the current server-side case. */ +public final class TrainingAnswerChecks { + public static BigDecimal amount(String raw,BigDecimal fallback){ + if(raw==null)return fallback; + String text=raw.trim(); + if(!text.matches("\\d{1,18}(\\.\\d{1,2})?"))throw wrong("金额格式不正确,最多保留两位小数"); + return new BigDecimal(text).setScale(2); + } + public static void same(String actual,String expected,String label){ + if(actual==null || !actual.trim().equals(expected))throw wrong(label+"与当前实训数据不一致"); + } + public static void original(String actual,String expected,int amountPosition){ + if(actual==null)throw wrong("请填写请求原文"); + String[] supplied=actual.trim().replace('|','|').split("\\|",-1), canonical=expected.split("\\|",-1); + if(supplied.length!=canonical.length)throw wrong("请求原文格式或字段数量不正确"); + for(int i=0;i order=jdbc.queryForMap("SELECT request_no,amount FROM currency_exchange_order WHERE id=(SELECT business_id FROM training_experiment_attempt WHERE id=?)",attemptId); + input.put("requestNo",order.get("request_no").toString()).put("rawAmount",order.get("amount").toString()).put("bankCardLast4","4567").put("timestamp",timestamp); + input.put("sourceText","SIGN|"+order.get("request_no")+"|"+order.get("amount")+"|4567|"+timestamp); + }else if("03".equals(step)&&"generate-digest".equals(action)){ + String json=jdbc.queryForObject("SELECT output_json FROM training_experiment_action WHERE attempt_id=? AND action_code='concatenate-sign-source'",String.class,attemptId); + input.put("sourceText",mapper.readTree(json).path("sourceText").asText()); + } + return input.toString(); + } + private String actionStatus(String attemptId, String step, String action) { return jdbc.queryForObject("SELECT status FROM training_experiment_action " + "WHERE attempt_id=? AND step_code=? AND action_code=?", @@ -725,6 +766,9 @@ class ExchangeControllerTest { private void seedIssuanceProofData(String controlOriginalText, String controlDigest, String controlSignature, String issuanceSignature) { + jdbc.update("INSERT INTO currency_generation_request (id,identifier_application_id,institution_identifier,full_institution_identifier,amount,delivery_node_code,request_timestamp,status,user_id,school_id,class_id,created_at,updated_at,created_by,updated_by,deleted) VALUES (990004,990001,'ORG_EXCHANGE_TEST',?,200,'BANK','20260812090000','SENT',?,1999,2999,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,'test','test',FALSE)",repeat('A',64),USER_ID); + jdbc.update("INSERT INTO currency_generation_verification (id,request_id,request_message,request_original_text,request_digest,bank_signature,bank_key_id,amount,status,user_id,school_id,class_id,created_at,updated_at,created_by,updated_by,deleted) VALUES (990005,990004,'{}','ORIGINAL',?,'SIGNATURE','KEY',200,'RETURNED',?,1999,2999,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,'test','test',FALSE)",repeat('A',64),USER_ID); + jdbc.update("INSERT INTO transaction_information_identifier (id,verification_id,request_id,identifier_application_id,amount,institution_identifier,transaction_timestamp,original_text,status,user_id,school_id,class_id,created_at,updated_at,created_by,updated_by,deleted) VALUES (990003,990005,990004,990001,200,'ORG_EXCHANGE_TEST','20260812090000','ORIGINAL','SENT',?,1999,2999,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,'test','test',FALSE)",USER_ID); jdbc.update("INSERT INTO control_system_signature (id,transaction_identifier_id,control_id,amount," + "institution_identifier,transaction_identifier,original_text,digest,signing_key_id,signature," + "control_signature,response_message,status,user_id,school_id,class_id,created_at,updated_at," + @@ -774,6 +818,9 @@ class ExchangeControllerTest { jdbc.update("DELETE FROM reserve_deduction_notification WHERE request_id=?", ISSUANCE_REQUEST_ID); jdbc.update("DELETE FROM central_bank_issuance_receipt WHERE request_id=?", ISSUANCE_REQUEST_ID); jdbc.update("DELETE FROM control_system_signature WHERE id=?", CONTROL_SIGNATURE_ID); + jdbc.update("DELETE FROM transaction_information_identifier WHERE id=990003"); + jdbc.update("DELETE FROM currency_generation_verification WHERE id=990005"); + jdbc.update("DELETE FROM currency_generation_request WHERE id=990004"); } private String repeat(char value, int count) { diff --git a/src/test/java/com/yau/digitalrmb/issuance/application/service/DigitalCurrencyGenerationStockIntegrationTest.java b/src/test/java/com/yau/digitalrmb/issuance/application/service/DigitalCurrencyGenerationStockIntegrationTest.java index d7614c2..34eecb5 100644 --- a/src/test/java/com/yau/digitalrmb/issuance/application/service/DigitalCurrencyGenerationStockIntegrationTest.java +++ b/src/test/java/com/yau/digitalrmb/issuance/application/service/DigitalCurrencyGenerationStockIntegrationTest.java @@ -27,6 +27,19 @@ class DigitalCurrencyGenerationStockIntegrationTest { @Autowired private DigitalCurrencyGenerationModuleGateway gateway; @Autowired private JdbcTemplate jdbcTemplate; + @org.junit.jupiter.api.BeforeEach + void seedForeignKeyParentsForRealMySqlSchema() { + for(int i=1;i<=2;i++) { + long id=880000L+i*10; + jdbcTemplate.update("INSERT INTO institution_identifier_application (id,bank_code,request_timestamp,original_text,status,institution_identifier,training_round,scoring_criteria,user_id,school_id,class_id,created_at,updated_at,created_by,updated_by,deleted) VALUES (?,'BKCHCNBJ00001','20260812090000','ORIGINAL','ISSUED','ORG_001',?,0,'stock-user',1001,2001,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,'test','test',FALSE)",id,i); + jdbcTemplate.update("INSERT INTO currency_generation_request (id,identifier_application_id,institution_identifier,full_institution_identifier,amount,delivery_node_code,request_timestamp,status,user_id,school_id,class_id,created_at,updated_at,created_by,updated_by,deleted) VALUES (?,?,'ORG_001',?,150,'BANK','20260812090000','SENT','stock-user',1001,2001,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,'test','test',FALSE)",id+1,id,String.join("",java.util.Collections.nCopies(64,"A"))); + jdbcTemplate.update("INSERT INTO currency_generation_verification (id,request_id,request_message,request_original_text,request_digest,bank_signature,bank_key_id,amount,status,user_id,school_id,class_id,created_at,updated_at,created_by,updated_by,deleted) VALUES (?,?,'{}','ORIGINAL',?,'SIGNATURE','KEY',150,'RETURNED','stock-user',1001,2001,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,'test','test',FALSE)",id+2,id+1,String.join("",java.util.Collections.nCopies(64,"A"))); + jdbcTemplate.update("INSERT INTO transaction_information_identifier (id,verification_id,request_id,identifier_application_id,amount,institution_identifier,transaction_timestamp,original_text,status,user_id,school_id,class_id,created_at,updated_at,created_by,updated_by,deleted) VALUES (?,?,?,?,150,'ORG_001','20260812090000','ORIGINAL','SENT','stock-user',1001,2001,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,'test','test',FALSE)",id+3,id+2,id+1,id); + jdbcTemplate.update("INSERT INTO control_system_signature (id,transaction_identifier_id,control_id,amount,institution_identifier,transaction_identifier,original_text,status,user_id,school_id,class_id,created_at,updated_at,created_by,updated_by,deleted) VALUES (?,?,'CTRL',150,'ORG_001','TXN','ORIGINAL','SENT','stock-user',1001,2001,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,'test','test',FALSE)",id+4,id+3); + jdbcTemplate.update("INSERT INTO quota_control_bit (id,control_signature_id,quota_id,amount,institution_identifier,transaction_identifier,status,user_id,school_id,class_id,created_at,updated_at,created_by,updated_by,deleted) VALUES (?,?,'QUOTA',150,'ORG_001','TXN','SENT','stock-user',1001,2001,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,'test','test',FALSE)",80+i,id+4); + } + } + @Test void locksExistingGeneratedCoinsForTheExactIssuanceRequest() { long batchId = 8801L; diff --git a/src/test/java/com/yau/digitalrmb/issuance/application/service/IssuanceActionOrderTest.java b/src/test/java/com/yau/digitalrmb/issuance/application/service/IssuanceActionOrderTest.java new file mode 100644 index 0000000..8cc1693 --- /dev/null +++ b/src/test/java/com/yau/digitalrmb/issuance/application/service/IssuanceActionOrderTest.java @@ -0,0 +1,32 @@ +package com.yau.digitalrmb.issuance.application.service; + +import com.yau.digitalrmb.training.attempt.domain.*; +import com.yau.digitalrmb.training.attempt.interfaces.dto.*; +import org.junit.jupiter.api.Test; +import java.time.Instant; +import java.util.*; +import static org.assertj.core.api.Assertions.*; + +class IssuanceActionOrderTest { + ExperimentAttemptView attempt(String status,String step,String action) { + List> history=new ArrayList<>(); + if(step!=null)history.add(new ExperimentActionView(UUID.randomUUID(),ExperimentModule.ISSUANCE,step,action, + ActionStatus.valueOf(status),AttemptStatus.IN_PROGRESS,step,action,Instant.now(),Collections.emptyMap())); + return new ExperimentAttemptView(UUID.randomUUID(),ExperimentModule.ISSUANCE,1,AttemptStatus.IN_PROGRESS,"01","test","request",Instant.now(),Instant.now(),null,history); + } + @Test void cannotEnterBusinessReviewWithoutFinishingTheDigestComparison() { + assertThatThrownBy(()->IssuanceActionOrder.requireReady(attempt(null,null,null),"03:query-institution-input")) + .isInstanceOf(com.yau.digitalrmb.shared.exception.BusinessException.class); + assertThatCode(()->IssuanceActionOrder.requireReady(attempt("COMPLETED","02","compare-digest"),"03:query-institution-input")) + .doesNotThrowAnyException(); + } + @Test void failedPredecessorDoesNotUnlockMoneyMovement() { + assertThatThrownBy(()->IssuanceActionOrder.requireReady(attempt("FAILED","05","check-application"),"05:execute-deduction")) + .isInstanceOf(com.yau.digitalrmb.shared.exception.BusinessException.class); + } + @Test void producingAReportDoesNotCompleteTheExperimentOrAwardTheFinalStep() { + assertThat(IssuanceActionOrder.completedStep("07:generate-ownership-report")).isNull(); + assertThat(IssuanceActionOrder.completedStep("07:load-ownership-result")).isEqualTo(7); + assertThat(IssuanceActionOrder.completedStep("05:verify-deduction")).isEqualTo(4); + } +} diff --git a/src/test/java/com/yau/digitalrmb/issuance/application/service/IssuanceTrainingActionServiceTest.java b/src/test/java/com/yau/digitalrmb/issuance/application/service/IssuanceTrainingActionServiceTest.java index d245b3d..779977f 100644 --- a/src/test/java/com/yau/digitalrmb/issuance/application/service/IssuanceTrainingActionServiceTest.java +++ b/src/test/java/com/yau/digitalrmb/issuance/application/service/IssuanceTrainingActionServiceTest.java @@ -162,8 +162,12 @@ class IssuanceTrainingActionServiceTest { } private ExperimentAttemptView attemptView(String businessId) { + java.util.List> history = new java.util.ArrayList<>(); + String[] actions = {"refresh-quota","refresh-custom-application","generate-timestamp","concatenate-application","generate-digest","sign-application","package-application","send-application","verify-signature","recalculate-digest","compare-digest","query-institution-input","query-quota-input","query-application-message","auto-confirm-plan","generate-reserve-deduction-request","sign-reserve-application","confirm-receipt","query-account","verify-deduction","check-application","execute-deduction","generate-balance-notice","send-balance-notice","confirm-balance-receipt","confirm-production-receipt","send-authorization","receive-authorization","generate-currency","generate-production-digest","assemble-production-confirmation","send-production-confirmation","preliminary-verification","generate-ownership-list","central-confirm-ownership","transfer-ownership","verify-central-bank-signature","activate-bank-currencies","generate-ownership-report","send-ownership-result","update-bank-status","sign-bank-receipt","load-ownership-result"}; + for(int i=0;i(attemptId,ExperimentModule.ISSUANCE,String.format("%02d",step),action, + com.yau.digitalrmb.training.attempt.domain.ActionStatus.COMPLETED,com.yau.digitalrmb.training.attempt.domain.AttemptStatus.IN_PROGRESS,"01",action,Instant.now(),Collections.emptyMap()));} return new ExperimentAttemptView(attemptId, ExperimentModule.ISSUANCE, 1, com.yau.digitalrmb.training.attempt.domain.AttemptStatus.IN_PROGRESS, "01", null, - businessId, Instant.now(), Instant.now(), null, Collections.emptyList()); + businessId, Instant.now(), Instant.now(), null, history); } } diff --git a/src/test/java/com/yau/digitalrmb/issuance/application/service/ProductionAuthorizationPolicyTest.java b/src/test/java/com/yau/digitalrmb/issuance/application/service/ProductionAuthorizationPolicyTest.java new file mode 100644 index 0000000..cd43ea5 --- /dev/null +++ b/src/test/java/com/yau/digitalrmb/issuance/application/service/ProductionAuthorizationPolicyTest.java @@ -0,0 +1,29 @@ +package com.yau.digitalrmb.issuance.application.service; +import com.yau.digitalrmb.issuance.domain.model.DigitalCurrencyProductionBatch; +import com.yau.digitalrmb.issuance.domain.repository.DigitalCurrencyProductionRepository; +import com.yau.digitalrmb.issuance.application.query.DigitalCurrencyProductionBatchView; +import org.junit.jupiter.api.Test; +import java.math.BigDecimal; +import java.time.*; +import java.util.*; +import static org.assertj.core.api.Assertions.*; +import static org.mockito.Mockito.*; + +class ProductionAuthorizationPolicyTest { + final Instant issued=Instant.parse("2026-10-31T08:00:00Z"); + DigitalCurrencyProductionBatch batch(String status){return new DigitalCurrencyProductionBatch("batch",UUID.randomUUID(),"tx","org","DC",BigDecimal.TEN,status,issued,"u","test",Collections.emptyList());} + @Test void validUntilIsExactlyOneHourAfterPersistedAuthorizationTime(){ + DigitalCurrencyProductionBatchView view=DigitalCurrencyProductionBatchView.from(batch("WAITING_OWNERSHIP")); + assertThat(view.getAuthorizationTime()).isEqualTo(issued);assertThat(view.getValidUntil()).isEqualTo(issued.plusSeconds(3600)); + } + @Test void rejectsAtExpiryIncludingAnAlreadyCompletedProductionActionReplay(){ + DigitalCurrencyProductionRepository repo=mock(DigitalCurrencyProductionRepository.class); + DigitalCurrencyProductionBatch value=batch("WAITING_OWNERSHIP");when(repo.findByRequestId(value.getRequestId())).thenReturn(Optional.of(value)); + ProductionAuthorizationPolicy policy=new ProductionAuthorizationPolicy(repo,Clock.fixed(issued.plusSeconds(3600),ZoneOffset.UTC)); + assertThatThrownBy(()->policy.requireActive(value.getRequestId())).hasMessageContaining("授权已超过1小时"); + } + @Test void confirmationCompletedInTimeRemainsReadableAfterAuthorizationExpires(){ + ProductionAuthorizationPolicy policy=new ProductionAuthorizationPolicy(mock(DigitalCurrencyProductionRepository.class),Clock.fixed(issued.plusSeconds(7200),ZoneOffset.UTC)); + assertThatCode(()->policy.requireActive(batch("OWNERSHIP_CONFIRMED"))).doesNotThrowAnyException(); + } +} diff --git a/src/test/java/com/yau/digitalrmb/issuance/interfaces/rest/IssuanceControllerTest.java b/src/test/java/com/yau/digitalrmb/issuance/interfaces/rest/IssuanceControllerTest.java index f908f95..853ced6 100644 --- a/src/test/java/com/yau/digitalrmb/issuance/interfaces/rest/IssuanceControllerTest.java +++ b/src/test/java/com/yau/digitalrmb/issuance/interfaces/rest/IssuanceControllerTest.java @@ -47,7 +47,7 @@ class IssuanceControllerTest { @Autowired private InstitutionKeyService acceptanceKeys; @BeforeEach - void configureGenerationModuleData() { + void configureGenerationModuleData() throws Exception { acceptanceKeys.commercialBankKey(acceptanceSubject(), "test"); acceptanceKeys.centralBankKey(acceptanceSubject(), "test"); when(generationGateway.commercialBankSigningKeyId()).thenReturn(InstitutionKeyService.BANK_SECOND_KEY); @@ -63,11 +63,14 @@ class IssuanceControllerTest { when(generationGateway.signReceipt(any(), anyString())).thenReturn("BANK_RECEIPT_SIGNATURE"); when(generationGateway.reserveGeneratedCurrencies(any(), any(), any(), any(), any())) .thenAnswer(invocation -> generatedStock(invocation.getArgument(3))); + String attemptResponse = mockMvc.perform(post("/api/v1/issuance/attempts").with(acceptanceUser())).andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + String round = JsonPath.read(attemptResponse,"$.data.attemptId"); + mockMvc.perform(post("/api/v1/issuance/attempts/"+round+"/steps/01/actions/refresh-quota").with(acceptanceUser()).contentType(MediaType.APPLICATION_JSON).content("{}")).andExpect(status().isOk()); } private List generatedStock(List denominations) { List stock = new ArrayList<>(); - long sourceId = 100_000L; + long sourceId = Math.abs(java.util.UUID.randomUUID().getMostSignificantBits() % 1_000_000_000L)*10000L; for (DenominationItem item : denominations) { for (int index = 0; index < item.getQuantity(); index++) { long id = sourceId++; @@ -169,6 +172,9 @@ class IssuanceControllerTest { .contentType(MediaType.APPLICATION_JSON).content(requestBody)) .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); String requestId = JsonPath.read(response, "$.data.id"); + String attemptForOrder=jdbcTemplate.queryForObject("SELECT id FROM training_experiment_attempt WHERE business_id=?",String.class,requestId); + mockMvc.perform(post("/api/v1/issuance/attempts/"+attemptForOrder+"/steps/03/actions/query-application-message").with(acceptanceUser()).contentType(MediaType.APPLICATION_JSON).content("{}")).andExpect(status().isBadRequest()); + assertThat(jdbcTemplate.queryForObject("SELECT current_step_code FROM training_experiment_attempt WHERE id=?",String.class,attemptForOrder)).isEqualTo("01"); String base = "/api/v1/commercial-banks/issuance/requests/" + requestId; mockMvc.perform(post(base + "/timestamp").with(jwt().jwt(jwt -> jwt.subject("00000000-0000-0000-0000-000000000487").claim("userId", "00000000-0000-0000-0000-000000000487")))).andExpect(status().isOk()); mockMvc.perform(post(base + "/prepare-message").with(jwt().jwt(jwt -> jwt.subject("00000000-0000-0000-0000-000000000487").claim("userId", "00000000-0000-0000-0000-000000000487")))).andExpect(status().isOk()); @@ -193,6 +199,7 @@ class IssuanceControllerTest { .andExpect(status().isOk()) .andExpect(jsonPath("$.data.verification.status").value("PASSED")); + completeReviewInputs(requestId); mockMvc.perform(post("/api/v1/central-banks/issuance/requests/{id}/business-review", requestId) .with(jwt().jwt(jwt -> jwt.subject("00000000-0000-0000-0000-000000000487").claim("userId", "00000000-0000-0000-0000-000000000487")))) .andExpect(status().isOk()) @@ -222,7 +229,8 @@ class IssuanceControllerTest { .andExpect(jsonPath("$.data.businessReview.reviewedBy").value("tzs001")); String notificationResponse = mockMvc.perform(post("/api/v1/central-banks/issuance/requests/{id}/reserve-deduction-notification", requestId) - .with(jwt().jwt(jwt -> jwt.subject("00000000-0000-0000-0000-000000000487").claim("userId", "00000000-0000-0000-0000-000000000487")))) + .with(jwt().jwt(jwt -> jwt.subject("00000000-0000-0000-0000-000000000487").claim("userId", "00000000-0000-0000-0000-000000000487"))) + .contentType(MediaType.APPLICATION_JSON).content("{\"deductionAmount\":50000}")) .andExpect(status().isOk()) .andExpect(jsonPath("$.data.status").value("SENT")) .andExpect(jsonPath("$.data.deductionAmount").value(50000.00)) @@ -242,6 +250,13 @@ class IssuanceControllerTest { .andExpect(jsonPath("$.data.receivedByUserId").value("00000000-0000-0000-0000-000000000487")) .andExpect(jsonPath("$.data.receivedBy").value("tzs001")); + signDeductionInput(requestId); + String signed=jdbcTemplate.queryForObject("SELECT bank_signature FROM issuance_reserve_application WHERE request_id=?",String.class,requestId); + assertThat(signed).isNotBlank().isNotEqualTo("BANK_SIGNATURE"); + jdbcTemplate.update("UPDATE issuance_reserve_application SET bank_signature='TAMPERED' WHERE request_id=?",requestId); + mockMvc.perform(post("/api/v1/commercial-banks/issuance/requests/"+requestId+"/reserve-deduction-application").with(acceptanceUser())).andExpect(status().isBadRequest()); + assertThat(jdbcTemplate.queryForObject("SELECT status FROM reserve_deduction_notification WHERE request_id=?",String.class,requestId)).isEqualTo("RECEIVED"); + jdbcTemplate.update("UPDATE issuance_reserve_application SET bank_signature=? WHERE request_id=?",signed,requestId); mockMvc.perform(post("/api/v1/commercial-banks/issuance/requests/{id}/reserve-deduction-application", requestId) .with(jwt().jwt(jwt -> jwt.subject("00000000-0000-0000-0000-000000000487") .claim("userId", "00000000-0000-0000-0000-000000000487")))) @@ -250,6 +265,8 @@ class IssuanceControllerTest { .andExpect(jsonPath("$.data.submittedByUserId").value("00000000-0000-0000-0000-000000000487")) .andExpect(jsonPath("$.data.submittedBy").value("tzs001")); + acceptanceAction(requestId,"05","query-account","{\"bankCode\":\"BKCHCNBJ00001\"}"); + acceptanceAction(requestId,"05","check-application","{}"); mockMvc.perform(post("/api/v1/central-banks/issuance/reserve-deductions/{transactionId}/execute", transactionId) .with(jwt().jwt(jwt -> jwt.subject("00000000-0000-0000-0000-000000000487").claim("userId", "00000000-0000-0000-0000-000000000487"))) .contentType(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON).content(acceptanceInput("deduction"))) @@ -268,6 +285,7 @@ class IssuanceControllerTest { .andExpect(jsonPath("$.data.reserveDeductionNotification.status").value("SUBMITTED")) .andExpect(jsonPath("$.data.reserveDeductionExecution.status").value("DEDUCTED")); + completeBalanceReceipt(requestId); mockMvc.perform(post("/api/v1/central-banks/issuance/requests/{id}/digital-currency-production", requestId) .with(jwt().jwt(jwt -> jwt.subject("00000000-0000-0000-0000-000000000487").claim("userId", "00000000-0000-0000-0000-000000000487")))) .andExpect(status().isOk()) @@ -287,22 +305,17 @@ class IssuanceControllerTest { .andExpect(jsonPath("$.data.status").value("WAITING_OWNERSHIP")) .andExpect(jsonPath("$.data.draftCoinCount").value(930)); - String attemptResponse = mockMvc.perform(get("/api/v1/issuance/attempts/current") - .with(jwt().jwt(jwt -> jwt.subject("00000000-0000-0000-0000-000000000487") - .claim("userId", "00000000-0000-0000-0000-000000000487")))) - .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); - String attemptId = JsonPath.read(attemptResponse, "$.data.attemptId"); - mockMvc.perform(post("/api/v1/issuance/attempts/{attemptId}/steps/06/actions/generate-production-digest", - attemptId) - .with(jwt().jwt(jwt -> jwt.subject("00000000-0000-0000-0000-000000000487") - .claim("userId", "00000000-0000-0000-0000-000000000487"))) - .contentType(MediaType.APPLICATION_JSON).content("{}")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.data.output.batch.batchId").value(org.hamcrest.Matchers.startsWith("MINT_"))) - .andExpect(jsonPath("$.data.output.digests.length()").value(930)) - .andExpect(jsonPath("$.data.output.digests[0].digest") - .value("0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF")); - + java.sql.Timestamp authorizedAt=jdbcTemplate.queryForObject("SELECT created_at FROM digital_currency_production_batch WHERE request_id=?",java.sql.Timestamp.class,requestId); + jdbcTemplate.update("UPDATE digital_currency_production_batch SET created_at=? WHERE request_id=?",java.sql.Timestamp.valueOf(java.time.LocalDateTime.ofInstant(java.time.Instant.now().minusSeconds(3601),java.time.ZoneOffset.UTC)),requestId); + String activeRound=jdbcTemplate.queryForObject("SELECT id FROM training_experiment_attempt WHERE business_id=?",String.class,requestId); + mockMvc.perform(post("/api/v1/issuance/attempts/"+activeRound+"/steps/06/actions/send-authorization").with(acceptanceUser()).contentType(MediaType.APPLICATION_JSON).content("{}")).andExpect(status().isBadRequest()); + jdbcTemplate.update("UPDATE digital_currency_production_batch SET created_at=? WHERE request_id=?",authorizedAt,requestId); + String digestResponse=completeProductionInputs(requestId); + assertThat(((java.util.List)JsonPath.read(digestResponse,"$.data.output.digests")).size()).isEqualTo(930); + assertThat((String)JsonPath.read(digestResponse,"$.data.output.digests[0].digest")).isEqualTo("0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF"); + for(String action:new String[]{"preliminary-verification","generate-ownership-list","central-confirm-ownership","transfer-ownership","verify-central-bank-signature","activate-bank-currencies","generate-ownership-report"}) + acceptanceAction(requestId,"07",action,"central-confirm-ownership".equals(action)?acceptanceInput("ownership"):"{}"); + assertThat(jdbcTemplate.queryForObject("SELECT status FROM training_experiment_attempt WHERE id=?",String.class,activeRound)).isEqualTo("IN_PROGRESS"); mockMvc.perform(post("/api/v1/central-banks/issuance/requests/{id}/digital-currency-ownership", requestId) .with(jwt().jwt(jwt -> jwt.subject("00000000-0000-0000-0000-000000000487") .claim("userId", "00000000-0000-0000-0000-000000000487") @@ -423,4 +436,33 @@ class IssuanceControllerTest { .put("reserveAccountName",com.yau.digitalrmb.issuance.domain.model.IssuanceAssetDefaults.BUILT_IN_RESERVE_ACCOUNT_NAME).put("deductionAmount",50000); return input.toString(); } + protected org.springframework.test.web.servlet.request.RequestPostProcessor acceptanceUser() { + return jwt().jwt(t->t.subject("00000000-0000-0000-0000-000000000487").claim("userId","00000000-0000-0000-0000-000000000487").claim("preferred_username","tzs001")); + } + protected String acceptanceAction(String id,String step,String action,String body) throws Exception { + String round=jdbcTemplate.queryForObject("SELECT id FROM training_experiment_attempt WHERE business_id=?",String.class,id); + com.fasterxml.jackson.databind.node.ObjectNode submitted=(com.fasterxml.jackson.databind.node.ObjectNode)new com.fasterxml.jackson.databind.ObjectMapper().readTree(body); + submitted.put("requestId",id); + return mockMvc.perform(post("/api/v1/issuance/attempts/"+round+"/steps/"+step+"/actions/"+action).with(acceptanceUser()) + .contentType(MediaType.APPLICATION_JSON).content(submitted.toString())).andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + } + protected void completeReviewInputs(String id) throws Exception { + String original=jdbcTemplate.queryForObject("SELECT message_text FROM issuance_request WHERE id=?",String.class,id); + String input=new com.fasterxml.jackson.databind.ObjectMapper().createObjectNode().put("algorithm","SM3").put("sourceText",original).toString(); + acceptanceAction(id,"02","recalculate-digest",input);acceptanceAction(id,"02","compare-digest",input); + for(String action:new String[]{"query-institution-input","query-quota-input","query-application-message"})acceptanceAction(id,"03",action,"{}"); + } + protected void signDeductionInput(String id) throws Exception {acceptanceAction(id,"04","sign-reserve-application","{}");} + protected void completeBalanceReceipt(String id) throws Exception { + for(String action:new String[]{"generate-balance-notice","send-balance-notice","confirm-balance-receipt"})acceptanceAction(id,"05",action,"{}"); + } + protected String completeProductionInputs(String id) throws Exception { + for(String action:new String[]{"send-authorization","receive-authorization","generate-currency"})acceptanceAction(id,"06",action,"{}"); + String original=jdbcTemplate.queryForObject("SELECT source_complete_currency FROM draft_digital_currency WHERE batch_id IN (SELECT batch_id FROM digital_currency_production_batch WHERE request_id=?) ORDER BY sequence_no LIMIT 1",String.class,id); + String input=new com.fasterxml.jackson.databind.ObjectMapper().createObjectNode().put("algorithm","SM3").put("sourceText",original).toString(); + String result=acceptanceAction(id,"06","generate-production-digest",input); + acceptanceAction(id,"06","assemble-production-confirmation","{}");acceptanceAction(id,"06","send-production-confirmation","{}"); + return result; + } + } diff --git a/src/test/java/com/yau/digitalrmb/payment/infrastructure/persistence/PaymentReserveLedgerTest.java b/src/test/java/com/yau/digitalrmb/payment/infrastructure/persistence/PaymentReserveLedgerTest.java new file mode 100644 index 0000000..73515cf --- /dev/null +++ b/src/test/java/com/yau/digitalrmb/payment/infrastructure/persistence/PaymentReserveLedgerTest.java @@ -0,0 +1,48 @@ +package com.yau.digitalrmb.payment.infrastructure.persistence; + +import com.yau.digitalrmb.payment.domain.model.*; +import com.yau.digitalrmb.payment.infrastructure.persistence.PaymentReserveLedger; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.jdbc.core.JdbcTemplate; +import java.math.BigDecimal; +import java.time.Instant; +import java.util.*; +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest @ActiveProfiles("test") @Transactional +class PaymentReserveLedgerTest { + @Autowired PaymentReserveLedger ledger; + @Autowired JdbcTemplate jdbc; + PaymentActor actor(String user) {return new PaymentActor(user,"retest",1001,2001);} + PaymentOrder order(String user) { + PaymentParticipant a=new PaymentParticipant(user,"WA","TYPE1","CA","KEY","BANK_A","A","ORG_A",BigDecimal.TEN,BigDecimal.ZERO); + PaymentParticipant b=new PaymentParticipant(user,"WB","TYPE1","CB","KEY","BANK_B","B","ORG_B",BigDecimal.TEN,BigDecimal.ZERO); + return PaymentOrder.create(new PaymentOrderId(UUID.randomUUID()),"RETEST_"+UUID.randomUUID(),a,b,new BigDecimal("1000"),"rent","20261031120000","PAY|RETEST","digest",Instant.now()); + } + BigDecimal balance(String user,String bank) {return jdbc.queryForObject("SELECT balance FROM payment_reserve_account WHERE user_id=? AND bank_code=?",BigDecimal.class,user,bank);} + @Test void debitsCreditsAndDoesNotDoubleSettle() { + String user="retest-ledger-a"; PaymentOrder order=order(user); ledger.clear(order,actor(user));ledger.clear(order,actor(user)); + assertThat(balance(user,"BANK_A")).isEqualByComparingTo("49999999000"); + assertThat(balance(user,"BANK_B")).isEqualByComparingTo("50000001000"); + assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM payment_reserve_entry WHERE payment_id=?",Integer.class,order.getId().toString())).isEqualTo(1); + } + @Test void reversesOnceAndRestoresBothBalances() { + String user="retest-ledger-reset";PaymentOrder order=order(user);ledger.clear(order,actor(user)); + ledger.reverse(Collections.singletonList(order.getId().toString()));ledger.reverse(Collections.singletonList(order.getId().toString())); + assertThat(balance(user,"BANK_A")).isEqualByComparingTo("50000000000"); + assertThat(balance(user,"BANK_B")).isEqualByComparingTo("50000000000"); + assertThat(jdbc.queryForObject("SELECT reversed FROM payment_reserve_entry WHERE payment_id=?",Boolean.class,order.getId().toString())).isTrue(); + } + @Test void separateLearnersDoNotShareReserveBalances() { + String a="retest-ledger-scope-a",b="retest-ledger-scope-b";PaymentOrder a1=order(a),a2=order(a),b1=order(b); + ledger.clear(a1,actor(a));ledger.clear(a2,actor(a));ledger.clear(b1,actor(b)); + assertThat(balance(a,"BANK_A")).isEqualByComparingTo("49999998000"); + assertThat(balance(b,"BANK_A")).isEqualByComparingTo("49999999000"); + ledger.reverse(Arrays.asList(a1.getId().toString(),a2.getId().toString())); + assertThat(balance(b,"BANK_A")).isEqualByComparingTo("49999999000"); + } +} diff --git a/src/test/java/com/yau/digitalrmb/payment/interfaces/rest/PaymentControllerTest.java b/src/test/java/com/yau/digitalrmb/payment/interfaces/rest/PaymentControllerTest.java index ed26b1b..32c4100 100644 --- a/src/test/java/com/yau/digitalrmb/payment/interfaces/rest/PaymentControllerTest.java +++ b/src/test/java/com/yau/digitalrmb/payment/interfaces/rest/PaymentControllerTest.java @@ -154,6 +154,10 @@ class PaymentControllerTest { mockMvc.perform(post("/api/v1/payments/{id}/central-bank-settle", id).with(payer())) .andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("CENTRAL_SETTLED")) .andExpect(jsonPath("$.data.clearingNo").value(org.hamcrest.Matchers.startsWith("ACS_PAY_REQ_"))); + assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM payment_reserve_entry WHERE payment_id=?",Integer.class,id)).isEqualTo(1); + assertThat(jdbc.queryForObject("SELECT payer_before-payer_after FROM payment_reserve_entry WHERE payment_id=?",BigDecimal.class,id)).isEqualByComparingTo("200"); + assertThat(jdbc.queryForObject("SELECT payee_after-payee_before FROM payment_reserve_entry WHERE payment_id=?",BigDecimal.class,id)).isEqualByComparingTo("200"); + assertThat(jdbc.queryForObject("SELECT created_by FROM payment_reserve_entry WHERE payment_id=?",String.class,id)).isEqualTo(PAYER_USER); mockMvc.perform(get("/api/v1/payment/attempts/current").with(payer())) .andExpect(status().isOk()) .andExpect(jsonPath("$.data.currentStepCode").value("05")) @@ -233,7 +237,7 @@ class PaymentControllerTest { executeAction(attemptId, "01", "refresh-payee", payer()); executeAction(attemptId, "02", "generate-timestamp", payer()); executeAction(attemptId, "02", "concatenate-payment", - "{\"amount\":200.00,\"note\":\"校验测试\"}", payer()); + "{\"amount\":1000.00,\"note\":\"房租\"}", payer()); mockMvc.perform(post("/api/v1/payment/attempts/{id}/steps/02/actions/generate-digest", attemptId) .with(payer()).contentType(MediaType.APPLICATION_JSON) @@ -302,7 +306,7 @@ class PaymentControllerTest { executeAction(attemptId, "02", "generate-timestamp", payer()); mockMvc.perform(post("/api/v1/payment/attempts/{id}/steps/02/actions/concatenate-payment", attemptId) .with(payer()).contentType(MediaType.APPLICATION_JSON) - .content("{\"payerWalletId\":\"" + PAYER_WALLET + "\",\"payeeWalletId\":\"WALLET_B_7D8E9F0A1B2C3D4E5F6A7B8C9D0E1F2A3B4C5D6E7F8A9B0C1D2E3F4A5B6\",\"amount\":50,\"note\":\"教学支付\"}")) + .content(answerBody(attemptId,"02","concatenate-payment","{\"payerWalletId\":\"" + PAYER_WALLET + "\",\"payeeWalletId\":\"WALLET_B_7D8E9F0A1B2C3D4E5F6A7B8C9D0E1F2A3B4C5D6E7F8A9B0C1D2E3F4A5B6\",\"amount\":1000,\"note\":\"房租\"}"))) .andExpect(status().isOk()) .andExpect(jsonPath("$.data.output.payeeWalletId").value( "WALLET_B_7D8E9F0A1B2C3D4E5F6A7B8C9D0E1F2A3B4C5D6E7F8A9B0C1D2E3F4A5B6")); @@ -635,7 +639,7 @@ class PaymentControllerTest { RequestPostProcessor actor) throws Exception { mockMvc.perform(post("/api/v1/payment/attempts/{id}/steps/{step}/actions/{action}", attemptId, step, action).with(actor) - .contentType(MediaType.APPLICATION_JSON).content(body)) + .contentType(MediaType.APPLICATION_JSON).content(answerBody(attemptId,step,action,body))) .andExpect(status().isOk()) .andExpect(jsonPath("$.data.actionStatus").value("COMPLETED")); } @@ -754,6 +758,43 @@ class PaymentControllerTest { jdbc.update("DELETE FROM commercial_bank_currency WHERE currency_id LIKE 'PAY_TEACH_A_%'"); } + @Test + void rejectsRawAnswerErrorsWithoutCreatingAPayment() throws Exception { + String created=mockMvc.perform(post("/api/v1/payment/attempts").with(payer())).andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + String attemptId=JsonPath.read(created,"$.data.attemptId"); + executeAction(attemptId,"01","refresh-payer",payer());executeAction(attemptId,"01","refresh-payee",payer());executeAction(attemptId,"02","generate-timestamp",payer()); + String base="/api/v1/payment/attempts/"+attemptId+"/steps/02/validate/concatenate-payment"; + String valid=answerBody(attemptId,"02","concatenate-payment","{\"amount\":1000,\"note\":\"房租\"}"); + com.fasterxml.jackson.databind.ObjectMapper mapper=new com.fasterxml.jackson.databind.ObjectMapper(); + com.fasterxml.jackson.databind.node.ObjectNode wrong=(com.fasterxml.jackson.databind.node.ObjectNode)mapper.readTree(valid); + wrong.put("rawAmount","abc"); + mockMvc.perform(post(base).with(payer()).contentType(MediaType.APPLICATION_JSON).content(wrong.toString())).andExpect(status().isBadRequest()); + wrong=(com.fasterxml.jackson.databind.node.ObjectNode)mapper.readTree(valid);wrong.put("sourceText","TAMPERED"); + mockMvc.perform(post(base).with(payer()).contentType(MediaType.APPLICATION_JSON).content(wrong.toString())).andExpect(status().isBadRequest()); + assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM payment_order WHERE payer_user_id=?",Integer.class,PAYER_USER)).isZero(); + assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM training_experiment_action WHERE attempt_id=? AND action_code='concatenate-payment'",Integer.class,attemptId)).isZero(); + assertThat(jdbc.queryForObject("SELECT completion_status FROM stu_module_score_details WHERE user_id=? AND serial_number=5",String.class,PAYER_USER)).isEqualTo("2"); + mockMvc.perform(post(base).with(payer()).contentType(MediaType.APPLICATION_JSON).content(valid)).andExpect(status().isOk()); + assertThat(jdbc.queryForObject("SELECT completion_status FROM stu_module_score_details WHERE user_id=? AND serial_number=5",String.class,PAYER_USER)).isEqualTo("2"); + } + + private String answerBody(String attemptId,String step,String action,String body) throws Exception { + if(!"02".equals(step)||!("concatenate-payment".equals(action)||"generate-digest".equals(action)))return body; + com.fasterxml.jackson.databind.ObjectMapper mapper=new com.fasterxml.jackson.databind.ObjectMapper(); + com.fasterxml.jackson.databind.node.ObjectNode input=(com.fasterxml.jackson.databind.node.ObjectNode)mapper.readTree(body); + if("generate-digest".equals(action)){ + String json=jdbc.queryForObject("SELECT output_json FROM training_experiment_action WHERE attempt_id=? AND action_code='concatenate-payment'",String.class,attemptId); + input.put("sourceText",mapper.readTree(json).path("sourceText").asText()); + }else{ + String json=jdbc.queryForObject("SELECT output_json FROM training_experiment_action WHERE attempt_id=? AND action_code='generate-timestamp'",String.class,attemptId); + String timestamp=mapper.readTree(json).path("timestamp").asText(); + String from=input.path("payerWalletId").asText(PAYER_WALLET),to=input.path("payeeWalletId").asText(TEACHING_PAYEE_WALLET); + input.put("payerWalletId",from).put("payeeWalletId",to).put("timestamp",timestamp); + input.put("sourceText","PAY|"+from+"|"+to+"|"+input.path("amount").asText()+"|"+input.path("note").asText()+"|"+timestamp); + } + return input.toString(); + } + private RequestPostProcessor payer() { return jwt().jwt(jwt -> jwt.subject(PAYER_USER).claim("userId", PAYER_USER).claim("preferred_username", "payment-a")); } diff --git a/src/test/java/com/yau/digitalrmb/shared/wallet/WalletRuntimeResetTest.java b/src/test/java/com/yau/digitalrmb/shared/wallet/WalletRuntimeResetTest.java index bd077da..c087b96 100644 --- a/src/test/java/com/yau/digitalrmb/shared/wallet/WalletRuntimeResetTest.java +++ b/src/test/java/com/yau/digitalrmb/shared/wallet/WalletRuntimeResetTest.java @@ -149,7 +149,7 @@ class WalletRuntimeResetTest { assertThat(userCount("training_experiment_attempt")).isZero(); assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM commercial_bank_currency " + "WHERE source_batch_id=-1 AND received_by_user_id=?", Integer.class, USER_ID)).isZero(); - assertThat(jdbc.queryForObject("SELECT owner_type || '|' || owner_id || '|' || status " + + assertThat(jdbc.queryForObject("SELECT CONCAT(owner_type, '|', owner_id, '|', status) " + "FROM central_bank_currency_ownership WHERE currency_id='DC_RUNTIME_RESET_1'", String.class)) .isEqualTo("BANK|" + BANK_CODE + "|AVAILABLE"); diff --git a/src/test/resources/schema.sql b/src/test/resources/schema.sql index b8df8f5..cfdd15e 100644 --- a/src/test/resources/schema.sql +++ b/src/test/resources/schema.sql @@ -1070,7 +1070,12 @@ CREATE TABLE IF NOT EXISTS payment_reserve_account ( class_id BIGINT NOT NULL, bank_code VARCHAR(32) NOT NULL, balance DECIMAL(28,2) NOT NULL, - UNIQUE KEY uk_payment_reserve_subject (user_id,school_id,class_id,bank_code) + UNIQUE KEY uk_payment_reserve_subject (user_id,school_id,class_id,bank_code), + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + created_by VARCHAR(64) NOT NULL DEFAULT 'SYSTEM', + updated_by VARCHAR(64) NOT NULL DEFAULT 'SYSTEM', + deleted BIGINT NOT NULL DEFAULT 0 ); CREATE TABLE IF NOT EXISTS payment_reserve_entry ( payment_id CHAR(36) PRIMARY KEY, @@ -1082,5 +1087,28 @@ CREATE TABLE IF NOT EXISTS payment_reserve_entry ( payee_before DECIMAL(28,2) NOT NULL, payee_after DECIMAL(28,2) NOT NULL, reversed BOOLEAN NOT NULL DEFAULT FALSE, - created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + created_by VARCHAR(64) NOT NULL DEFAULT 'SYSTEM', + updated_by VARCHAR(64) NOT NULL DEFAULT 'SYSTEM', + deleted BIGINT NOT NULL DEFAULT 0 +); + +-- Signed reserve deduction applications. Execute before starting the updated backend. +CREATE TABLE IF NOT EXISTS issuance_reserve_application ( + request_id CHAR(36) PRIMARY KEY, + original_text LONGTEXT NOT NULL, + digest VARCHAR(128) NOT NULL, + bank_signature TEXT NOT NULL, + bank_public_key TEXT NOT NULL, + signed_at TIMESTAMP NOT NULL, + user_id VARCHAR(36) NOT NULL, + school_id BIGINT NOT NULL, + class_id BIGINT NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + created_by VARCHAR(64) NOT NULL, + updated_by VARCHAR(64) NOT NULL, + deleted BIGINT NOT NULL DEFAULT 0, + INDEX idx_reserve_application_subject (user_id,school_id,class_id) );