fix: enforce issuance workflow and validate learner answers
parent
e9c6947b35
commit
d78ec58d96
@ -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 旧测试问题未在本次修改业务规则或放宽断言来消除。
|
||||||
@ -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<String,String> 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;i<keys.length;i++) PREVIOUS.put(keys[i],keys[i-1]); }
|
||||||
|
public static void requireReady(ExperimentAttemptView attempt,String action) {
|
||||||
|
if(attempt.getModuleCode()!=ExperimentModule.ISSUANCE) throw new BusinessException(ErrorCode.VALIDATION_ERROR,"实验类型不匹配");
|
||||||
|
String previous=PREVIOUS.get(action);
|
||||||
|
if(previous==null)return;
|
||||||
|
String[] parts=previous.split(":",2);
|
||||||
|
boolean completed=attempt.getActions().stream().anyMatch(a->parts[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() {}
|
||||||
|
}
|
||||||
@ -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<String,Object> 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<String,Object> find(UUID id,InstitutionKeySubject subject){
|
||||||
|
ReserveDeductionApplication value=owned(id,subject);
|
||||||
|
try{
|
||||||
|
Map<String,Object> result=mapper.readValue(value.getOriginalText(),new TypeReference<LinkedHashMap<String,Object>>(){});
|
||||||
|
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<String,Object> 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);}
|
||||||
|
}
|
||||||
@ -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;
|
||||||
|
}
|
||||||
@ -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<ReserveDeductionApplication> find(UUID requestId);
|
||||||
|
void saveIfAbsent(ReserveDeductionApplication application);
|
||||||
|
}
|
||||||
@ -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<ReserveDeductionApplication> find(UUID requestId){
|
||||||
|
List<ReserveDeductionApplication> 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());
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,60 @@
|
|||||||
|
-- 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)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Repeatable additions preserve existing ledger rows.
|
||||||
|
SET @closure_ddl = (SELECT IF(COUNT(*)=0,'ALTER TABLE payment_reserve_account ADD COLUMN created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP','SELECT 1') FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='payment_reserve_account' AND column_name='created_at');
|
||||||
|
PREPARE closure_stmt FROM @closure_ddl;
|
||||||
|
EXECUTE closure_stmt;
|
||||||
|
DEALLOCATE PREPARE closure_stmt;
|
||||||
|
SET @closure_ddl = (SELECT IF(COUNT(*)=0,'ALTER TABLE payment_reserve_account ADD COLUMN updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP','SELECT 1') FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='payment_reserve_account' AND column_name='updated_at');
|
||||||
|
PREPARE closure_stmt FROM @closure_ddl;
|
||||||
|
EXECUTE closure_stmt;
|
||||||
|
DEALLOCATE PREPARE closure_stmt;
|
||||||
|
SET @closure_ddl = (SELECT IF(COUNT(*)=0,'ALTER TABLE payment_reserve_account ADD COLUMN created_by VARCHAR(64) NOT NULL DEFAULT ''SYSTEM''','SELECT 1') FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='payment_reserve_account' AND column_name='created_by');
|
||||||
|
PREPARE closure_stmt FROM @closure_ddl;
|
||||||
|
EXECUTE closure_stmt;
|
||||||
|
DEALLOCATE PREPARE closure_stmt;
|
||||||
|
SET @closure_ddl = (SELECT IF(COUNT(*)=0,'ALTER TABLE payment_reserve_account ADD COLUMN updated_by VARCHAR(64) NOT NULL DEFAULT ''SYSTEM''','SELECT 1') FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='payment_reserve_account' AND column_name='updated_by');
|
||||||
|
PREPARE closure_stmt FROM @closure_ddl;
|
||||||
|
EXECUTE closure_stmt;
|
||||||
|
DEALLOCATE PREPARE closure_stmt;
|
||||||
|
SET @closure_ddl = (SELECT IF(COUNT(*)=0,'ALTER TABLE payment_reserve_account ADD COLUMN deleted BIGINT NOT NULL DEFAULT 0','SELECT 1') FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='payment_reserve_account' AND column_name='deleted');
|
||||||
|
PREPARE closure_stmt FROM @closure_ddl;
|
||||||
|
EXECUTE closure_stmt;
|
||||||
|
DEALLOCATE PREPARE closure_stmt;
|
||||||
|
SET @closure_ddl = (SELECT IF(COUNT(*)=0,'ALTER TABLE payment_reserve_entry ADD COLUMN created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP','SELECT 1') FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='payment_reserve_entry' AND column_name='created_at');
|
||||||
|
PREPARE closure_stmt FROM @closure_ddl;
|
||||||
|
EXECUTE closure_stmt;
|
||||||
|
DEALLOCATE PREPARE closure_stmt;
|
||||||
|
SET @closure_ddl = (SELECT IF(COUNT(*)=0,'ALTER TABLE payment_reserve_entry ADD COLUMN updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP','SELECT 1') FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='payment_reserve_entry' AND column_name='updated_at');
|
||||||
|
PREPARE closure_stmt FROM @closure_ddl;
|
||||||
|
EXECUTE closure_stmt;
|
||||||
|
DEALLOCATE PREPARE closure_stmt;
|
||||||
|
SET @closure_ddl = (SELECT IF(COUNT(*)=0,'ALTER TABLE payment_reserve_entry ADD COLUMN created_by VARCHAR(64) NOT NULL DEFAULT ''SYSTEM''','SELECT 1') FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='payment_reserve_entry' AND column_name='created_by');
|
||||||
|
PREPARE closure_stmt FROM @closure_ddl;
|
||||||
|
EXECUTE closure_stmt;
|
||||||
|
DEALLOCATE PREPARE closure_stmt;
|
||||||
|
SET @closure_ddl = (SELECT IF(COUNT(*)=0,'ALTER TABLE payment_reserve_entry ADD COLUMN updated_by VARCHAR(64) NOT NULL DEFAULT ''SYSTEM''','SELECT 1') FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='payment_reserve_entry' AND column_name='updated_by');
|
||||||
|
PREPARE closure_stmt FROM @closure_ddl;
|
||||||
|
EXECUTE closure_stmt;
|
||||||
|
DEALLOCATE PREPARE closure_stmt;
|
||||||
|
SET @closure_ddl = (SELECT IF(COUNT(*)=0,'ALTER TABLE payment_reserve_entry ADD COLUMN deleted BIGINT NOT NULL DEFAULT 0','SELECT 1') FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='payment_reserve_entry' AND column_name='deleted');
|
||||||
|
PREPARE closure_stmt FROM @closure_ddl;
|
||||||
|
EXECUTE closure_stmt;
|
||||||
|
DEALLOCATE PREPARE closure_stmt;
|
||||||
@ -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<ExperimentActionView<?>> history=new ArrayList<>();
|
||||||
|
if(step!=null)history.add(new ExperimentActionView<Object>(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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -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");
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue