feat(procurement): implement sample fulfillment and settled fee workflow

This commit is contained in:
2026-10-10 02:19:38 +08:00
parent 040f3bbd93
commit a973be2103
104 changed files with 9823 additions and 714 deletions
@@ -130,6 +130,14 @@ public class BusinessFeeSourceEventService {
}
positive(value.sourceFeeId(), "sourceFeeId");
positive(value.customerId(), "customerId");
if (value.walletSettlement() != null) {
if (!"RECEIVABLE".equals(value.direction())) throw error("FIN-EVT-012", "钱包消费只能关联应收费用");
positive(value.walletSettlement().holdId(), "walletSettlement.holdId");
positive(value.walletSettlement().ledgerId(), "walletSettlement.ledgerId");
if (blank(value.walletSettlement().commandEventId())) throw error("FIN-EVT-012", "缺少原资金命令引用");
} else if ("OVERSEAS_PROCUREMENT_FEE".equals(value.sourceType()) && "RECEIVABLE".equals(value.direction())) {
throw error("FIN-EVT-012", "采购应收必须引用成功实扣资金,不能进入待收费池");
}
if ("OVERSEAS_CONTAINER_FEE".equals(value.sourceType())) {
if (!"LASTLEG".equals(value.sourceSystem()) || !"OVERSEAS_CONTAINER".equals(value.businessType()))
throw error("FIN-EVT-012", "海外柜费来源不一致");
@@ -160,7 +168,7 @@ public class BusinessFeeSourceEventService {
value.paymentReferenceNo(), value.paymentVoucherFileIds(), value.businessDate(), value.currency(),
value.totalAmount(), value.originalCurrency(), value.originalAmount(), value.exchangeRate(),
value.exchangeRateMonth(), value.chargeableQuantity(), value.quantityUnit(), value.unitPrice(),
value.periodStart(), value.periodEnd(), value.reviewStatus(), "PUBLISHED", "ACTIVE", null);
value.periodStart(), value.periodEnd(), value.reviewStatus(), "PUBLISHED", "ACTIVE", null, value.walletSettlement());
String expected = EventPayloadHash.sha256(EventPayloadCanonicalizer.canonicalize(objectMapper.valueToTree(unsigned)));
if (!expected.equals(value.sourceHash())) throw error("FIN-EVT-004", "费用来源快照哈希不一致");
}
@@ -189,7 +197,40 @@ public class BusinessFeeSourceEventService {
private void linkSettledWalletHold(long feeSourceId, BusinessFeeSourceChangedV1 source) {
if (!"RECEIVABLE".equals(source.direction())) return;
jdbc.update("UPDATE fin_fee_source f JOIN fin_wallet_hold h ON h.customer_id=f.customer_id AND h.business_type=f.business_type AND h.business_no=f.business_no SET f.wallet_hold_id=h.id,f.status='SETTLED' WHERE f.id=? AND f.status='AVAILABLE' AND h.status='SETTLED' AND h.amount=f.amount",
if (source.walletSettlement() != null) {
var reference = source.walletSettlement();
long customerId = positive(source.customerId(), "customerId");
long holdId = positive(reference.holdId(), "holdId");
long ledgerId = positive(reference.ledgerId(), "ledgerId");
List<Map<String, Object>> rows = jdbc.queryForList(
"SELECT l.amount,c.result_json FROM fin_wallet_hold h JOIN fin_wallet_ledger l ON l.id=h.action_ledger_id AND l.customer_id=h.customer_id JOIN fin_wallet_command_inbox c ON c.event_id=? AND c.status='SUCCEEDED' WHERE h.id=? AND l.id=? AND h.customer_id=? AND h.business_type=? AND h.business_no=? AND h.status='SETTLED' AND l.change_type='CONSUMPTION' FOR UPDATE",
reference.commandEventId(), holdId, ledgerId, customerId, source.businessType(), source.businessNo());
if (rows.size() != 1 || !(rows.get(0).get("amount") instanceof java.math.BigDecimal amount)
|| amount.negate().compareTo(source.totalAmount()) != 0) {
throw error("FIN-EVT-017", "费用来源与成功扣款的客户、业务或金额不匹配");
}
com.fasterxml.jackson.databind.JsonNode result;
try { result = objectMapper.readTree(String.valueOf(rows.get(0).get("result_json"))); }
catch (JsonProcessingException exception) { throw error("FIN-EVT-017", "原资金结果无法核对"); }
if (!"SUCCEEDED".equals(result.path("result").asText())
|| !Set.of("SETTLE", "SETTLE_ACTUAL").contains(result.path("operation").asText())
|| !reference.commandEventId().equals(result.path("commandEventId").asText())
|| !reference.holdId().equals(result.path("walletHoldId").asText())
|| !reference.ledgerId().equals(result.path("walletLedgerId").asText())
|| result.path("customerId").asLong() != customerId
|| !source.businessType().equals(result.path("businessType").asText())
|| !source.businessNo().equals(result.path("businessNo").asText())
|| result.path("amount").decimalValue().compareTo(source.totalAmount()) != 0) {
throw error("FIN-EVT-017", "费用来源引用的资金结果不匹配");
}
List<Long> used = jdbc.queryForList("SELECT id FROM fin_fee_source WHERE wallet_hold_id=? AND id<>? FOR UPDATE",
Long.class, holdId, feeSourceId);
if (!used.isEmpty()) throw error("FIN-EVT-017", "同一成功扣款已关联其他费用来源");
jdbc.update("UPDATE fin_fee_source SET wallet_hold_id=?,status='SETTLED' WHERE id=? AND customer_id=? AND status='AVAILABLE'",
holdId, feeSourceId, customerId);
return;
}
jdbc.update("UPDATE fin_fee_source f JOIN fin_wallet_hold h ON h.customer_id=f.customer_id AND h.business_type=f.business_type AND h.business_no=f.business_no JOIN fin_wallet_ledger l ON l.id=h.action_ledger_id AND l.customer_id=h.customer_id AND l.change_type='CONSUMPTION' SET f.wallet_hold_id=h.id,f.status='SETTLED' WHERE f.id=? AND f.status='AVAILABLE' AND h.status='SETTLED' AND f.amount=-l.amount",
feeSourceId);
}
@@ -300,6 +300,113 @@ public class FinanceWalletService {
return completeHold(customerId, businessType, businessNo, idempotencyKey, request, false);
}
/** Settles one estimate without releasing its protection before checking any shortfall. */
@Transactional
public WalletHold settleActual(long customerId, String rawBusinessType, String rawBusinessNo,
String idempotencyKey, BigDecimal actualAmount, String remark) {
requirePositive(customerId, "客户");
BigDecimal amount = money(actualAmount);
String businessType = businessType(rawBusinessType);
String businessNo = businessNo(rawBusinessNo);
String operation = "WALLET_HOLD_SETTLE_ACTUAL";
String requestHash = hash(Map.of("customerId", customerId, "businessType", businessType,
"businessNo", businessNo, "amount", amount, "remark", String.valueOf(remark)));
Long replay = reserve(customerId, 0, operation, idempotencyKey, requestHash);
if (replay != null) return requiredHold(replay, customerId);
WalletAccount before = accountForUpdate(customerId);
WalletHold hold = findHold(customerId, businessType, businessNo, true);
if (hold == null) throw error("FIN-WALLET-HOLD-404", "资金冻结记录不存在");
if (!"FROZEN".equals(hold.status())) throw error("FIN-WALLET-HOLD-409", "资金冻结记录已处理");
WalletAccount after = settleActualAccount(before, hold, amount);
updateAccount(customerId, after, before.version(), 0);
WalletLedgerEntry ledger = insertLedger(customerId, "CONSUMPTION", amount.negate(), after,
businessType, businessNo, LocalDate.now(), null, businessNo, 0, "业务系统", remark);
// The hold retains the original estimate; its action ledger records the actual charge.
int updated = jdbc.update("UPDATE fin_wallet_hold SET status='SETTLED',action_ledger_id=?,completed_at=CURRENT_TIMESTAMP(3) WHERE id=? AND status='FROZEN'",
ledger.ledgerId(), hold.holdId());
if (updated != 1) throw error("FIN-WALLET-HOLD-409", "资金冻结记录已处理");
audit(customerId, "WALLET_HOLD", hold.holdId(), "SETTLE_ACTUAL", remark, before, after, 0, "业务系统");
complete(customerId, 0, operation, idempotencyKey, hold.holdId());
return requiredHold(hold.holdId(), customerId);
}
/** Refunds a successful consumption; recharge allocation rules apply without creating a recharge. */
@Transactional
public WalletLedgerEntry refundConsumption(long customerId, long originalLedgerId, String refundNo,
String idempotencyKey, BigDecimal refundAmount,
long operatorId, String operatorName, String remark) {
requirePositive(customerId, "客户");
requirePositive(originalLedgerId, "原扣款流水");
String reference = businessNo(refundNo);
BigDecimal amount = money(refundAmount);
if (!StringUtils.hasText(remark)) throw bad("退款原因不能为空");
String requestHash = hash(Map.of("customerId", customerId, "originalLedgerId", originalLedgerId,
"refundNo", reference, "amount", amount, "remark", remark));
Long replay = reserve(customerId, 0, "WALLET_BUSINESS_REFUND", idempotencyKey, requestHash);
if (replay != null) return requiredLedger(replay, customerId);
WalletAccount before = accountForUpdate(customerId);
List<WalletLedgerEntry> originals = jdbc.query(
"SELECT * FROM fin_wallet_ledger WHERE id=? AND customer_id=? FOR UPDATE",
(rs, n) -> ledgerRow(rs), originalLedgerId, customerId);
if (originals.isEmpty()) throw error("FIN-WALLET-404", "原扣款流水不存在");
WalletLedgerEntry original = originals.get(0);
if (!"CONSUMPTION".equals(original.changeType()) || original.amount().signum() >= 0) {
throw bad("仅可对成功业务扣款发起关联退款");
}
List<WalletLedgerEntry> existing = jdbc.query(
"SELECT * FROM fin_wallet_ledger WHERE customer_id=? AND source_type='BUSINESS_REFUND' AND source_no=? FOR UPDATE",
(rs, n) -> ledgerRow(rs), customerId, reference);
if (!existing.isEmpty()) {
WalletLedgerEntry refunded = existing.get(0);
if (refunded.amount().compareTo(amount) != 0 || !original.businessNo().equals(refunded.referenceNo())) {
throw error("FIN-IDEMPOTENCY-CONFLICT", "同一退款单对应的原扣款或金额不一致");
}
complete(customerId, 0, "WALLET_BUSINESS_REFUND", idempotencyKey, refunded.ledgerId());
return refunded;
}
// Locking reads see refunds committed while this transaction waited for the account lock,
// even under MySQL REPEATABLE READ after the idempotency lookup established a snapshot.
BigDecimal refunded = jdbc.queryForList(
"SELECT amount FROM fin_wallet_ledger WHERE customer_id=? AND source_type='BUSINESS_REFUND' AND reference_no=? FOR UPDATE",
BigDecimal.class, customerId, original.businessNo()).stream().reduce(BigDecimal.ZERO, BigDecimal::add);
if (refunded.add(amount).compareTo(original.amount().negate()) > 0) {
throw error("FIN-WALLET-REFUND-EXCEEDED", "退款金额超过原扣款剩余可退金额");
}
WalletAccount after = rechargeAccount(before, amount);
updateAccount(customerId, after, before.version(), operatorId);
WalletLedgerEntry result = insertLedger(customerId, "REFUND", amount, after,
"BUSINESS_REFUND", reference, LocalDate.now(), null, original.businessNo(),
operatorId, operatorName, remark);
audit(customerId, "WALLET_LEDGER", originalLedgerId, "REFUND", remark, before, after, operatorId, operatorName);
complete(customerId, 0, "WALLET_BUSINESS_REFUND", idempotencyKey, result.ledgerId());
return result;
}
WalletAccount settleActualAccount(WalletAccount before, WalletHold hold, BigDecimal actualAmount) {
BigDecimal amount = money(actualAmount);
BigDecimal extra = amount.subtract(hold.amount()).max(BigDecimal.ZERO);
if (extra.signum() > 0 && before.availableBalance().compareTo(extra) < 0) {
throw error("FIN-WALLET-INSUFFICIENT", "实际费用补差所需的可用余额和授信额度不足");
}
BigDecimal actual = before.actualBalance();
BigDecimal creditUsed = before.creditUsed();
if (before.creditActive()) {
BigDecimal reservedCharge = amount.min(hold.amount());
BigDecimal cashCharge = reservedCharge.min(hold.actualFrozenAmount());
BigDecimal freeCash = actual.subtract(before.frozenBalance().subtract(before.creditFrozen()))
.max(BigDecimal.ZERO);
cashCharge = cashCharge.add(extra.min(freeCash));
actual = actual.subtract(cashCharge);
creditUsed = creditUsed.add(amount.subtract(cashCharge));
} else {
// Previously reserved credit still settles after expiry, without granting new credit.
actual = actual.subtract(amount);
}
return accountState(actual, before.frozenBalance().subtract(hold.amount()), before.creditLimit(),
creditUsed, before.creditFrozen().subtract(hold.creditFrozenAmount()),
before.creditExpiresOn(), before.version());
}
private WalletHold completeHold(long customerId, String rawBusinessType, String rawBusinessNo,
String idempotencyKey, WalletHoldActionRequest request, boolean settle) {
requirePositive(customerId, "客户");
@@ -29,9 +29,10 @@ import java.util.Set;
@Service
public class WalletCommandEventService {
private static final Set<String> OPERATIONS = Set.of("FREEZE", "SETTLE", "RELEASE");
private static final Set<String> OPERATIONS = Set.of("FREEZE", "SETTLE", "SETTLE_ACTUAL", "RELEASE", "REFUND");
private static final Set<String> FINAL_REJECTIONS = Set.of(
"FIN-WALLET-INSUFFICIENT", "FIN-WALLET-HOLD-409", "FIN-IDEMPOTENCY-CONFLICT", "FIN-REQ-400");
"FIN-WALLET-INSUFFICIENT", "FIN-WALLET-HOLD-409", "FIN-IDEMPOTENCY-CONFLICT", "FIN-REQ-400",
"FIN-WALLET-REFUND-EXCEEDED", "FIN-WALLET-404");
private final JdbcTemplate jdbc;
private final ObjectMapper objectMapper;
private final FinanceWalletService walletService;
@@ -56,10 +57,9 @@ public class WalletCommandEventService {
if (resultExists(envelope.eventId())) return DeliveryAck.of(envelope, DeliveryAck.Outcome.DUPLICATE);
// Wallet methods join this transaction: money, the Inbox outcome and
// the result Outbox commit together, or all roll back.
WalletHold hold = execute(command);
if (hold == null) throw new IllegalStateException("资金操作未返回处理结果");
ExecutionResult execution = execute(command);
finalizeResult(envelope, completed(envelope.eventId(), command, "SUCCEEDED",
hold.status(), hold.amount(), null, null));
execution.status(), execution.amount(), null, null, execution.holdId(), execution.ledgerId()));
return DeliveryAck.of(envelope, DeliveryAck.Outcome.APPLIED);
});
} catch (FinanceEventException exception) {
@@ -70,7 +70,7 @@ public class WalletCommandEventService {
requireLockedIdentity(envelope);
if (resultExists(envelope.eventId())) return DeliveryAck.of(envelope, DeliveryAck.Outcome.DUPLICATE);
finalizeResult(envelope, completed(envelope.eventId(), command, "FAILED",
null, command.amount(), exception.code(), exception.getMessage()));
null, command.amount(), exception.code(), exception.getMessage(), null, null));
return DeliveryAck.of(envelope, DeliveryAck.Outcome.APPLIED);
});
}
@@ -86,21 +86,33 @@ public class WalletCommandEventService {
}
}
private WalletHold execute(WalletCommandRequestedV1 command) {
private record ExecutionResult(String status, BigDecimal amount, String holdId, String ledgerId) { }
private ExecutionResult execute(WalletCommandRequestedV1 command) {
if ("REFUND".equals(command.operation())) {
var refund = walletService.refundConsumption(command.customerId(), Long.parseLong(command.originalLedgerId()),
command.businessNo(), command.idempotencyKey(), command.amount(), 0, "业务系统", command.remark());
return new ExecutionResult("REFUNDED", refund.amount(), null, String.valueOf(refund.ledgerId()));
}
WalletHold hold = switch (command.operation()) {
case "FREEZE" -> walletService.freeze(command.customerId(), command.idempotencyKey(),
new WalletFreezeRequest(command.amount(), command.businessType(), command.businessNo(), command.remark()));
case "SETTLE" -> walletService.settle(command.customerId(), command.businessType(), command.businessNo(),
command.idempotencyKey(), new WalletHoldActionRequest(command.remark()));
case "SETTLE_ACTUAL" -> walletService.settleActual(command.customerId(), command.businessType(), command.businessNo(),
command.idempotencyKey(), command.amount(), command.remark());
case "RELEASE" -> walletService.release(command.customerId(), command.businessType(), command.businessNo(),
command.idempotencyKey(), new WalletHoldActionRequest(command.remark()));
default -> throw new FinanceEventException("FIN-EVT-001", "资金指令操作无效");
};
if ("SETTLE".equals(command.operation())) {
jdbc.update("UPDATE fin_fee_source f JOIN fin_wallet_hold h ON h.customer_id=f.customer_id AND h.business_type=f.business_type AND h.business_no=f.business_no SET f.wallet_hold_id=h.id,f.status='SETTLED' WHERE h.id=? AND f.direction='RECEIVABLE' AND f.status='AVAILABLE' AND f.amount=h.amount",
if (hold == null) throw new IllegalStateException("资金操作未返回处理结果");
if (Set.of("SETTLE", "SETTLE_ACTUAL").contains(command.operation())) {
jdbc.update("UPDATE fin_fee_source f JOIN fin_wallet_hold h ON h.customer_id=f.customer_id AND h.business_type=f.business_type AND h.business_no=f.business_no JOIN fin_wallet_ledger l ON l.id=h.action_ledger_id AND l.customer_id=h.customer_id AND l.change_type='CONSUMPTION' SET f.wallet_hold_id=h.id,f.status='SETTLED' WHERE h.id=? AND f.direction='RECEIVABLE' AND f.status='AVAILABLE' AND f.amount=-l.amount",
hold.holdId());
}
return hold;
Long ledgerId = "FREEZE".equals(command.operation()) ? hold.freezeLedgerId() : hold.actionLedgerId();
return new ExecutionResult(hold.status(), "SETTLE_ACTUAL".equals(command.operation()) ? command.amount() : hold.amount(),
String.valueOf(hold.holdId()), ledgerId == null ? null : String.valueOf(ledgerId));
}
private WalletCommandRequestedV1 validate(EventEnvelope envelope) {
@@ -118,14 +130,22 @@ public class WalletCommandEventService {
String operation = value.operation() == null ? "" : value.operation().trim().toUpperCase(Locale.ROOT);
if (!OPERATIONS.contains(operation) || value.customerId() <= 0 || blank(value.businessType())
|| blank(value.businessNo()) || blank(value.idempotencyKey())
|| ("FREEZE".equals(operation) && (value.amount() == null || value.amount().signum() <= 0))) {
|| (Set.of("FREEZE", "SETTLE_ACTUAL", "REFUND").contains(operation)
&& (value.amount() == null || value.amount().signum() <= 0 || value.amount().scale() > 2))) {
throw new FinanceEventException("FIN-EVT-001", "资金指令字段无效");
}
if ("REFUND".equals(operation)) {
if (blank(value.originalLedgerId()) || Long.parseLong(value.originalLedgerId()) <= 0 || blank(value.remark())) {
throw new FinanceEventException("FIN-EVT-001", "退款必须关联原扣款并填写原因");
}
} else if (value.originalLedgerId() != null) {
throw new FinanceEventException("FIN-EVT-001", "非退款指令不能指定原扣款");
}
if (!String.valueOf(value.customerId()).equals(envelope.tenantId())) {
throw new FinanceEventException("FIN-EVT-007", "资金指令客户归属不一致");
}
return new WalletCommandRequestedV1(operation, value.customerId(), value.businessType(), value.businessNo(),
value.amount(), value.remark(), value.idempotencyKey(), value.requestedAt());
value.amount(), value.remark(), value.idempotencyKey(), value.requestedAt(), value.originalLedgerId());
} catch (FinanceEventException exception) { throw exception; }
catch (Exception exception) { throw new FinanceEventException("FIN-EVT-001", "资金指令载荷无法解析"); }
}
@@ -159,9 +179,10 @@ public class WalletCommandEventService {
return count != null && count > 0;
}
private WalletCommandCompletedV1 completed(String eventId, WalletCommandRequestedV1 command, String result,
String holdStatus, BigDecimal amount, String errorCode, String errorMessage) {
String holdStatus, BigDecimal amount, String errorCode, String errorMessage,
String holdId, String ledgerId) {
return new WalletCommandCompletedV1(eventId, command.operation(), command.customerId(), command.businessType(),
command.businessNo(), result, holdStatus, amount, errorCode, errorMessage, Instant.now());
command.businessNo(), result, holdStatus, amount, errorCode, errorMessage, Instant.now(), holdId, ledgerId);
}
private String json(Object value) {
try { return objectMapper.writeValueAsString(value); }
@@ -45,11 +45,11 @@ class BusinessFeeSourceEventServiceTest {
when(jdbc.queryForList(startsWith("SELECT payload_hash,status,result_resource_id"),
eq("LASTLEG"), eq(event.eventId()))).thenReturn(List.of());
when(jdbc.queryForList(startsWith("SELECT id,source_hash,status FROM fin_fee_source"),
eq("LASTLEG"), eq("OVERSEAS_PROCUREMENT_FEE"), eq(701L), eq(1))).thenReturn(List.of());
eq("LASTLEG"), eq("OVERSEAS_WAREHOUSE_FEE"), eq(701L), eq(1))).thenReturn(List.of());
when(jdbc.queryForObject(startsWith("SELECT COUNT(*) FROM fin_fee_source f WHERE f.source_system=?"),
eq(Integer.class), eq("LASTLEG"), eq("OVERSEAS_PROCUREMENT_FEE"), eq(701L))).thenReturn(0);
eq(Integer.class), eq("LASTLEG"), eq("OVERSEAS_WAREHOUSE_FEE"), eq(701L))).thenReturn(0);
when(jdbc.queryForObject(startsWith("SELECT id FROM fin_fee_source"), eq(Long.class),
eq("LASTLEG"), eq("OVERSEAS_PROCUREMENT_FEE"), eq(701L), eq(1))).thenReturn(901L);
eq("LASTLEG"), eq("OVERSEAS_WAREHOUSE_FEE"), eq(701L), eq(1))).thenReturn(901L);
assertThat(service.consume(event).eventId()).isEqualTo(event.eventId());
@@ -65,21 +65,21 @@ class BusinessFeeSourceEventServiceTest {
private EventEnvelope eventWithoutInbound() {
BusinessFeeSourceChangedV1 unsigned = new BusinessFeeSourceChangedV1(null, "LASTLEG",
"OVERSEAS_PROCUREMENT_FEE", "701", 1, "10001", "客户A", "PO-US-001",
"OVERSEAS_PROCUREMENT", "801", "PO-US-001", null, null, null, null, null,
"OVERSEAS_WAREHOUSE_FEE", "701", 1, "10001", "客户A", "PO-US-001",
"WAREHOUSE_SERVICE", "801", "PO-US-001", null, null, null, null, null,
null, "91", "PROCUREMENT_SERVICE", "采购服务费", "RECEIVABLE", null, null,
null, null, null, null, null, List.of(), LocalDate.of(2026, 9, 2), "CNY",
new BigDecimal("120.00"), "CNY", new BigDecimal("120.00"), BigDecimal.ONE,
"2026-09", null, null, null, null, null, "APPROVED", "PUBLISHED", "ACTIVE", null);
"2026-09", null, null, null, null, null, "APPROVED", "PUBLISHED", "ACTIVE", null, null);
String sourceHash = EventPayloadHash.sha256(
EventPayloadCanonicalizer.canonicalize(json.valueToTree(unsigned)));
BusinessFeeSourceChangedV1 payload = new BusinessFeeSourceChangedV1("PUBLISHED", "LASTLEG",
"OVERSEAS_PROCUREMENT_FEE", "701", 1, "10001", "客户A", "PO-US-001",
"OVERSEAS_PROCUREMENT", "801", "PO-US-001", null, null, null, null, null,
"OVERSEAS_WAREHOUSE_FEE", "701", 1, "10001", "客户A", "PO-US-001",
"WAREHOUSE_SERVICE", "801", "PO-US-001", null, null, null, null, null,
null, "91", "PROCUREMENT_SERVICE", "采购服务费", "RECEIVABLE", null, null,
null, null, null, null, null, List.of(), LocalDate.of(2026, 9, 2), "CNY",
new BigDecimal("120.00"), "CNY", new BigDecimal("120.00"), BigDecimal.ONE,
"2026-09", null, null, null, null, null, "APPROVED", "PUBLISHED", "ACTIVE", sourceHash);
"2026-09", null, null, null, null, null, "APPROVED", "PUBLISHED", "ACTIVE", sourceHash, null);
JsonNode node = json.valueToTree(payload);
String payloadHash = EventPayloadHash.sha256(EventPayloadCanonicalizer.canonicalize(node));
return new EventEnvelope("123e4567-e89b-12d3-a456-426614174701",
@@ -237,4 +237,53 @@ class BusinessFeeSourceEventServiceTest {
verify(jdbc, never()).update(startsWith("INSERT INTO fin_cost"), any(Object[].class));
verify(jdbc, never()).update(startsWith("UPDATE fin_cost"), any(Object[].class));
}
@Test
void procurementWithoutConsumptionReferenceNeverEntersReceivablePool() {
EventEnvelope event = procurementEvent(false);
assertThatThrownBy(() -> service.consume(event)).hasMessageContaining("必须引用成功实扣");
noFinancialWrites();
}
@Test
void settledProcurementUsesVerifiedActualConsumptionAndNeverOriginalEstimate() {
EventEnvelope event = procurementEvent(true);
when(jdbc.queryForObject(startsWith("SELECT id FROM fin_fee_source"), eq(Long.class),
eq("LASTLEG"), eq("OVERSEAS_PROCUREMENT_FEE"), eq(701L), eq(1))).thenReturn(901L);
when(jdbc.queryForList(startsWith("SELECT l.amount,c.result_json"), eq("command-1"), eq(9L), eq(72L),
eq(10001L), eq("PROCUREMENT_FEE"), eq("PO-US-001"))).thenReturn(List.of(Map.of(
"amount", new BigDecimal("-120.00"), "result_json", """
{"result":"SUCCEEDED","operation":"SETTLE_ACTUAL","commandEventId":"command-1",
"walletHoldId":"9","walletLedgerId":"72","customerId":10001,
"businessType":"PROCUREMENT_FEE","businessNo":"PO-US-001","amount":120.00}
""")));
service.consume(event);
verify(jdbc).update(startsWith("UPDATE fin_fee_source SET wallet_hold_id="), eq(9L), eq(901L), eq(10001L));
verify(jdbc, never()).update(startsWith("UPDATE fin_fee_source f JOIN fin_wallet_hold"), any(Object[].class));
}
@Test
void incorrectOrCrossCustomerConsumptionIsRejectedInsteadOfBecomingAvailable() {
EventEnvelope event = procurementEvent(true);
when(jdbc.queryForObject(startsWith("SELECT id FROM fin_fee_source"), eq(Long.class),
eq("LASTLEG"), eq("OVERSEAS_PROCUREMENT_FEE"), eq(701L), eq(1))).thenReturn(901L);
assertThatThrownBy(() -> service.consume(event)).hasMessageContaining("不匹配");
verify(jdbc, never()).update(startsWith("UPDATE fin_fee_source SET wallet_hold_id="), any(Object[].class));
}
private EventEnvelope procurementEvent(boolean reference) {
EventEnvelope base = eventWithoutInbound();
ObjectNode payload = (ObjectNode) base.payload().deepCopy();
payload.put("sourceType", "OVERSEAS_PROCUREMENT_FEE");
payload.put("businessType", "PROCUREMENT_FEE");
if (reference) {
payload.putObject("walletSettlement").put("commandEventId", "command-1").put("holdId", "9").put("ledgerId", "72");
}
payload.putNull("action"); payload.putNull("sourceHash");
payload.put("sourceHash", EventPayloadHash.sha256(EventPayloadCanonicalizer.canonicalize(payload)));
payload.put("action", "PUBLISHED");
return new EventEnvelope(base.eventId(), base.eventType(), base.eventVersion(), base.occurredAt(), base.tenantId(),
base.aggregateType(), base.aggregateId(), base.aggregateVersion(), null, base.traceId(), base.correlationId(), null,
payload, EventPayloadHash.sha256(EventPayloadCanonicalizer.canonicalize(payload)));
}
}
@@ -101,6 +101,38 @@ class WalletCommandEventServiceTest {
verify(jdbc, never()).update(startsWith("INSERT INTO fin_wallet_event_outbox"), any(Object[].class));
}
@Test
void actualSettlementReportsActualChargeInsteadOfOriginalEstimate() throws Exception {
EventEnvelope event = envelope("SETTLE_ACTUAL", 31L, new BigDecimal("60.00"));
when(jdbc.queryForList(startsWith("SELECT payload_hash"), eq(String.class), eq(event.eventId())))
.thenReturn(List.of(event.payloadHash()));
when(jdbc.queryForObject(startsWith("SELECT COUNT(*)"), eq(Integer.class), anyString())).thenReturn(0);
when(wallet.settleActual(eq(31L), eq("OVERSEAS_PROCUREMENT_FEE"), eq("PO-1"),
eq("freeze-procurement-1"), argThat((BigDecimal amount) -> amount.compareTo(new BigDecimal("60.00")) == 0), any())).thenReturn(
new WalletHold(9L, 31L, "OVERSEAS_PROCUREMENT_FEE", "PO-1", new BigDecimal("100.00"),
new BigDecimal("100.00"), BigDecimal.ZERO, "SETTLED", 71L, 72L, null, null, null));
service.consume(event);
var resultJson = org.mockito.ArgumentCaptor.forClass(String.class);
verify(jdbc).update(startsWith("UPDATE fin_wallet_command_inbox SET status="), eq("SUCCEEDED"),
resultJson.capture(), eq(event.eventId()));
JsonNode result = mapper.readTree(resultJson.getValue());
assertThat(result.path("amount").decimalValue()).isEqualByComparingTo("60.00");
assertThat(result.path("holdStatus").asText()).isEqualTo("SETTLED");
assertThat(result.path("walletHoldId").asText()).isEqualTo("9");
assertThat(result.path("walletLedgerId").asText()).isEqualTo("72");
verify(jdbc).update(contains("f.amount=-l.amount"), eq(9L));
verify(wallet, never()).release(anyLong(), anyString(), anyString(), anyString(), any());
}
@Test
void actualSettlementRejectsZeroAndMissingAmountsBeforeOpeningTransaction() {
for (BigDecimal amount : new BigDecimal[]{null, BigDecimal.ZERO, new BigDecimal("0.001")}) {
assertThatThrownBy(() -> service.consume(envelope("SETTLE_ACTUAL", 31L, amount)))
.isInstanceOf(FinanceEventException.class);
}
verifyNoInteractions(jdbc, wallet, transactions);
}
@Test
void losingInboxInsertMustRecheckThePersistedHash() {
EventEnvelope event = envelope("FREEZE", 31L, new BigDecimal("10.00"));
@@ -133,9 +165,44 @@ class WalletCommandEventServiceTest {
}
private EventEnvelope envelope(String operation, long customerId, BigDecimal amount) {
return envelope(operation, customerId, amount, null);
}
@Test
void refundRequiresOriginalConsumptionBeforeAnyWalletCall() {
assertThatThrownBy(() -> service.consume(envelope("REFUND", 31L, BigDecimal.TEN)))
.isInstanceOf(FinanceEventException.class);
verifyNoInteractions(jdbc, wallet);
}
@Test
void refundHasItsOwnLedgerReferenceAndNeverPretendsToSettleAHold() throws Exception {
EventEnvelope event = envelope("REFUND", 31L, BigDecimal.TEN, "72");
when(jdbc.queryForList(startsWith("SELECT payload_hash"), eq(String.class), eq(event.eventId())))
.thenReturn(List.of(event.payloadHash()));
when(jdbc.queryForObject(startsWith("SELECT COUNT(*)"), eq(Integer.class), anyString())).thenReturn(0);
var refunded = new com.baiyue.finance.dto.FinanceWalletDtos.WalletLedgerEntry(73L, "AC-TEST", "REFUND",
BigDecimal.TEN, BigDecimal.TEN, BigDecimal.ZERO, BigDecimal.TEN, BigDecimal.ZERO, BigDecimal.ZERO,
BigDecimal.ZERO, null, "BUSINESS_REFUND", "PO-1", java.time.LocalDate.now(), null,
"AC-ORIGINAL", "业务系统", "采购快递费", null);
when(wallet.refundConsumption(eq(31L), eq(72L), eq("PO-1"), eq("freeze-procurement-1"),
any(), eq(0L), anyString(), anyString())).thenReturn(refunded);
service.consume(event);
var capture = org.mockito.ArgumentCaptor.forClass(String.class);
verify(jdbc).update(startsWith("UPDATE fin_wallet_command_inbox SET status="), eq("SUCCEEDED"),
capture.capture(), eq(event.eventId()));
JsonNode result = mapper.readTree(capture.getValue());
assertThat(result.path("walletLedgerId").asText()).isEqualTo("73");
assertThat(result.path("walletHoldId").isNull()).isTrue();
assertThat(result.path("holdStatus").asText()).isEqualTo("REFUNDED");
verify(wallet, never()).settle(anyLong(), anyString(), anyString(), anyString(), any());
verify(jdbc, never()).update(startsWith("UPDATE fin_fee_source"), any(Object[].class));
}
private EventEnvelope envelope(String operation, long customerId, BigDecimal amount, String originalLedgerId) {
WalletCommandRequestedV1 command = new WalletCommandRequestedV1(operation, customerId,
"OVERSEAS_PROCUREMENT_FEE", "PO-1", amount, "采购快递费",
"freeze-procurement-1", Instant.parse("2026-09-05T01:00:00Z"));
"freeze-procurement-1", Instant.parse("2026-09-05T01:00:00Z"), originalLedgerId);
JsonNode payload = mapper.valueToTree(command);
return new EventEnvelope(UUID.randomUUID().toString(), EventTypes.WALLET_COMMAND_REQUESTED,
WalletCommandRequestedV1.VERSION, Instant.parse("2026-09-05T01:00:00Z"), String.valueOf(customerId), "WALLET_HOLD", "PO-1", 1,
@@ -190,7 +190,7 @@ class WalletCommandTransactionTest {
private EventEnvelope event(String id, String amount) {
var command = new WalletCommandRequestedV1("FREEZE", 31L, "OVERSEAS_PROCUREMENT_FEE", "PO-1",
new BigDecimal(amount), "fee", "freeze-1", Instant.parse("2026-09-05T01:00:00Z"));
new BigDecimal(amount), "fee", "freeze-1", Instant.parse("2026-09-05T01:00:00Z"), null);
var payload = mapper.valueToTree(command);
return new EventEnvelope(id, EventTypes.WALLET_COMMAND_REQUESTED, WalletCommandRequestedV1.VERSION,
Instant.now(), "31", "WALLET_HOLD", "PO-1", 1,
@@ -0,0 +1,91 @@
package com.baiyue.finance.service;
import com.baiyue.finance.client.FinanceFileClient;
import com.baiyue.finance.dto.FinanceWalletDtos.WalletAccount;
import com.baiyue.finance.dto.FinanceWalletDtos.WalletHold;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import java.math.BigDecimal;
import java.time.LocalDate;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.mock;
class ProcurementActualSettlementTest {
private final FinanceWalletService service = new FinanceWalletService(mock(JdbcTemplate.class),
new ObjectMapper().findAndRegisterModules(), mock(FinanceFileClient.class),
mock(FinanceDocumentNumberGenerator.class), "token", "", "test", "test");
@Test
void smallerActualChargeReleasesRemainderAndKeepsOtherReservations() {
WalletAccount before = account("200", "150", "0", "0", "0", null);
WalletAccount after = service.settleActualAccount(before, hold("100", "100", "0"), n("60"));
assertThat(after.actualBalance()).isEqualByComparingTo("140");
assertThat(after.frozenBalance()).isEqualByComparingTo("50");
assertThat(after.availableBalance()).isEqualByComparingTo("90");
}
@Test
void excessUsesAvailableCashThenActiveCreditWithoutTouchingOtherHolds() {
WalletAccount before = account("120", "130", "100", "0", "30", LocalDate.now().plusDays(1));
WalletAccount after = service.settleActualAccount(before, hold("100", "70", "30"), n("150"));
assertThat(after.actualBalance()).isEqualByComparingTo("30");
assertThat(after.creditUsed()).isEqualByComparingTo("60");
assertThat(after.frozenBalance()).isEqualByComparingTo("30");
assertThat(after.creditFrozen()).isZero();
assertThat(after.availableBalance()).isEqualByComparingTo("40");
}
@Test
void insufficientExcessRejectsWithoutChangingOriginalAccount() {
WalletAccount before = account("120", "100", "0", "0", "0", null);
assertThatThrownBy(() -> service.settleActualAccount(before, hold("100", "100", "0"), n("120.01")))
.isInstanceOf(FinanceEventException.class)
.extracting(e -> ((FinanceEventException) e).code()).isEqualTo("FIN-WALLET-INSUFFICIENT");
assertThat(before.actualBalance()).isEqualByComparingTo("120");
assertThat(before.frozenBalance()).isEqualByComparingTo("100");
}
@Test
void partialChargeUsesReservedCashBeforeCredit() {
WalletAccount before = account("70", "100", "100", "0", "30", LocalDate.now().plusDays(1));
WalletAccount after = service.settleActualAccount(before, hold("100", "70", "30"), n("60"));
assertThat(after.actualBalance()).isEqualByComparingTo("10");
assertThat(after.creditUsed()).isZero();
assertThat(after.creditFrozen()).isZero();
assertThat(after.frozenBalance()).isZero();
}
@Test
void expiredCreditAllowsOriginalReservationButNeverNewCredit() {
WalletAccount before = account("20", "100", "100", "0", "80", LocalDate.now().minusDays(1));
WalletAccount after = service.settleActualAccount(before, hold("100", "20", "80"), n("100"));
assertThat(after.actualBalance()).isEqualByComparingTo("-80");
assertThat(after.creditUsed()).isZero();
assertThat(after.frozenBalance()).isZero();
assertThatThrownBy(() -> service.settleActualAccount(before, hold("100", "20", "80"), n("100.01")))
.isInstanceOf(FinanceEventException.class);
}
@Test
void invalidActualAmountMustUseReleaseOrCorrectPrecision() {
WalletAccount before = account("200", "100", "0", "0", "0", null);
for (String value : new String[]{"0", "-1", "0.001"}) {
assertThatThrownBy(() -> service.settleActualAccount(before, hold("100", "100", "0"), n(value)))
.isInstanceOf(FinanceEventException.class);
}
}
private WalletAccount account(String actual, String frozen, String limit, String used, String creditFrozen, LocalDate expiry) {
return service.accountState(n(actual), n(frozen), n(limit), n(used), n(creditFrozen), expiry, 1);
}
private WalletHold hold(String amount, String cash, String credit) {
return new WalletHold(1L, 9L, "PROCUREMENT_FEE", "PF-TEST", n(amount), n(cash), n(credit),
"FROZEN", 1L, null, null, null, null);
}
private static BigDecimal n(String value) { return new BigDecimal(value); }
}
@@ -0,0 +1,200 @@
package com.baiyue.finance.service;
import com.baiyue.finance.client.FinanceFileClient;
import com.baiyue.finance.dto.FinanceWalletDtos.WalletHold;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.h2.jdbcx.JdbcDataSource;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.dao.TransientDataAccessResourceException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import java.math.BigDecimal;
import java.util.UUID;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
/** Executes the real wallet service against transactional JDBC; no mocked money mutations. */
class ProcurementSettlementTransactionTest {
private JdbcTemplate jdbc;
private TransactionTemplate tx;
private FinanceWalletService wallet;
@BeforeEach
void setup() {
JdbcDataSource source = new JdbcDataSource();
source.setURL("jdbc:h2:mem:" + UUID.randomUUID() + ";MODE=MySQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=5000");
jdbc = spy(new JdbcTemplate(source));
tx = new TransactionTemplate(new DataSourceTransactionManager(source));
jdbc.execute("CREATE TABLE fin_wallet_account(customer_id BIGINT PRIMARY KEY,currency_code VARCHAR(3),actual_balance DECIMAL(18,2),frozen_balance DECIMAL(18,2),available_balance DECIMAL(18,2),credit_limit DECIMAL(18,2),credit_used DECIMAL(18,2),credit_frozen DECIMAL(18,2),credit_expires_on DATE,version INT,created_by BIGINT,updated_by BIGINT,updated_at TIMESTAMP)");
jdbc.execute("CREATE TABLE fin_wallet_hold(id BIGINT AUTO_INCREMENT PRIMARY KEY,customer_id BIGINT,business_type VARCHAR(32),business_no VARCHAR(128),amount DECIMAL(18,2),actual_frozen_amount DECIMAL(18,2),credit_frozen_amount DECIMAL(18,2),status VARCHAR(32),freeze_ledger_id BIGINT,action_ledger_id BIGINT,created_at TIMESTAMP,completed_at TIMESTAMP,remark VARCHAR(500),UNIQUE(customer_id,business_type,business_no))");
jdbc.execute("CREATE TABLE fin_idempotency_record(tenant_id BIGINT,operator_id BIGINT,operation VARCHAR(64),idempotency_key VARCHAR(128),request_hash VARCHAR(128),status VARCHAR(32),result_resource_id BIGINT,error_code VARCHAR(128),UNIQUE(tenant_id,operator_id,operation,idempotency_key))");
jdbc.execute("CREATE TABLE fin_wallet_ledger(id BIGINT AUTO_INCREMENT PRIMARY KEY,customer_id BIGINT,business_no VARCHAR(128),change_type VARCHAR(32),amount DECIMAL(18,2),actual_balance_after DECIMAL(18,2),frozen_balance_after DECIMAL(18,2),available_balance_after DECIMAL(18,2),credit_limit_after DECIMAL(18,2),credit_used_after DECIMAL(18,2),available_credit_after DECIMAL(18,2),credit_expires_on_after DATE,source_type VARCHAR(32),source_no VARCHAR(128),occurred_date DATE,payment_method VARCHAR(32),reference_no VARCHAR(128),operator_id BIGINT,operator_name VARCHAR(128),remark VARCHAR(500),created_at TIMESTAMP)");
jdbc.execute("CREATE TABLE fin_audit_log(tenant_id BIGINT,resource_type VARCHAR(64),resource_id BIGINT,action VARCHAR(64),reason VARCHAR(500),before_data TEXT,after_data TEXT,operator_id BIGINT,operator_name_snapshot VARCHAR(128),request_id VARCHAR(128),trace_id VARCHAR(128))");
jdbc.update("INSERT INTO fin_wallet_account VALUES(9,'CNY',200,100,100,0,0,0,NULL,0,0,0,CURRENT_TIMESTAMP)");
jdbc.update("INSERT INTO fin_wallet_hold(id,customer_id,business_type,business_no,amount,actual_frozen_amount,credit_frozen_amount,status) VALUES(1,9,'PROCUREMENT_FEE','PF-1',100,100,0,'FROZEN')");
FinanceDocumentNumberGenerator numbers = mock(FinanceDocumentNumberGenerator.class);
AtomicInteger sequence = new AtomicInteger();
when(numbers.next("AC")).thenAnswer(i -> "AC-TEST-" + sequence.incrementAndGet());
wallet = new FinanceWalletService(jdbc, new ObjectMapper().findAndRegisterModules(),
mock(FinanceFileClient.class), numbers, "token", "", "test", "test");
}
@Test
void partialSettlementKeepsEstimateAndRecordsActualExactlyOnce() {
WalletHold first = settle("request-1", "60");
WalletHold replay = settle("request-1", "60");
assertThat(replay.actionLedgerId()).isEqualTo(first.actionLedgerId());
assertThat(first.amount()).isEqualByComparingTo("100");
assertThat(first.account().actualBalance()).isEqualByComparingTo("140");
assertThat(first.account().frozenBalance()).isZero();
assertThat(jdbc.queryForObject("SELECT amount FROM fin_wallet_ledger", BigDecimal.class)).isEqualByComparingTo("-60");
assertThatThrownBy(() -> settle("different-request", "60")).isInstanceOf(FinanceEventException.class);
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM fin_wallet_ledger", Integer.class)).isEqualTo(1);
}
@Test
void sameKeyWithDifferentAmountCannotChangeCharge() {
settle("request-1", "60");
assertThatThrownBy(() -> settle("request-1", "70")).isInstanceOf(FinanceEventException.class)
.extracting(e -> ((FinanceEventException) e).code()).isEqualTo("FIN-IDEMPOTENCY-CONFLICT");
assertThat(wallet.account(9).actualBalance()).isEqualByComparingTo("140");
}
@Test
void insufficientDifferenceLeavesOriginalHoldAndAccountUntouched() {
assertThatThrownBy(() -> settle("request-1", "201")).isInstanceOf(FinanceEventException.class);
assertUntouched();
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM fin_idempotency_record", Integer.class)).isZero();
}
@Test
void auditFailureRollsBackDebitLedgerHoldAndIdempotencyReservation() {
doThrow(new TransientDataAccessResourceException("audit storage unavailable"))
.when(jdbc).update(startsWith("INSERT INTO fin_audit_log"), any(Object[].class));
assertThatThrownBy(() -> settle("request-1", "150"))
.isInstanceOf(TransientDataAccessResourceException.class);
assertUntouched();
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM fin_idempotency_record", Integer.class)).isZero();
}
@Test
void concurrentDifferentRequestsCannotSettleTheSameGoodsTwice() throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(2);
CountDownLatch start = new CountDownLatch(1);
try {
Future<Boolean> one = executor.submit(() -> attempt(start, "one"));
Future<Boolean> two = executor.submit(() -> attempt(start, "two"));
start.countDown();
assertThat((one.get(10, TimeUnit.SECONDS) ? 1 : 0) + (two.get(10, TimeUnit.SECONDS) ? 1 : 0)).isEqualTo(1);
assertThat(wallet.account(9).actualBalance()).isEqualByComparingTo("50");
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM fin_wallet_ledger", Integer.class)).isEqualTo(1);
} finally {
executor.shutdownNow();
assertThat(executor.awaitTermination(5, TimeUnit.SECONDS)).isTrue();
}
}
private boolean attempt(CountDownLatch start, String key) throws InterruptedException {
if (!start.await(5, TimeUnit.SECONDS)) throw new AssertionError("start timeout");
try { settle(key, "150"); return true; }
catch (FinanceEventException expected) {
assertThat(expected.code()).isEqualTo("FIN-WALLET-HOLD-409");
return false;
}
}
@Test
void refundsAreBoundedByOriginalConsumptionAndCannotReplayWithNewKey() {
WalletHold settled = settle("settle", "60");
var refund = tx.execute(s -> wallet.refundConsumption(9, settled.actionLedgerId(), "RF-1", "refund-1",
new BigDecimal("40"), 7, "finance", "confirmed correction"));
var replay = tx.execute(s -> wallet.refundConsumption(9, settled.actionLedgerId(), "RF-1", "new-key",
new BigDecimal("40"), 7, "finance", "confirmed correction"));
assertThat(replay.ledgerId()).isEqualTo(refund.ledgerId());
assertThat(wallet.account(9).actualBalance()).isEqualByComparingTo("180");
assertThatThrownBy(() -> tx.execute(s -> wallet.refundConsumption(9, settled.actionLedgerId(), "RF-2", "refund-2",
new BigDecimal("20.01"), 7, "finance", "too much")))
.isInstanceOf(FinanceEventException.class)
.extracting(e -> ((FinanceEventException) e).code()).isEqualTo("FIN-WALLET-REFUND-EXCEEDED");
tx.execute(s -> wallet.refundConsumption(9, settled.actionLedgerId(), "RF-2", "refund-2",
new BigDecimal("20"), 7, "finance", "remaining refund"));
assertThat(wallet.account(9).actualBalance()).isEqualByComparingTo("200");
assertThat(jdbc.queryForObject("SELECT status FROM fin_wallet_hold", String.class)).isEqualTo("SETTLED");
assertThat(jdbc.queryForObject("SELECT SUM(amount) FROM fin_wallet_ledger WHERE source_type='BUSINESS_REFUND'", BigDecimal.class))
.isEqualByComparingTo("60");
}
@Test
void refundCannotReferenceAnotherCustomerOrAnUnsettledReservation() {
WalletHold settled = settle("settle", "60");
assertThatThrownBy(() -> tx.execute(s -> wallet.refundConsumption(10, settled.actionLedgerId(), "RF-1", "refund-1",
BigDecimal.ONE, 7, "finance", "wrong customer"))).isInstanceOf(FinanceEventException.class);
assertThatThrownBy(() -> tx.execute(s -> wallet.refundConsumption(9, settled.actionLedgerId(), "RF-1", "refund-1",
BigDecimal.ZERO, 7, "finance", "zero refund"))).isInstanceOf(FinanceEventException.class);
assertThat(wallet.account(9).actualBalance()).isEqualByComparingTo("140");
}
@Test
void refundFailureRollsBackBalanceAndCanRetryOriginalRequest() {
WalletHold settled = settle("settle", "60");
doThrow(new TransientDataAccessResourceException("audit unavailable"))
.when(jdbc).update(startsWith("INSERT INTO fin_audit_log"), any(Object[].class));
assertThatThrownBy(() -> tx.execute(s -> wallet.refundConsumption(9, settled.actionLedgerId(), "RF-1", "refund-1",
new BigDecimal("20"), 7, "finance", "correction"))).isInstanceOf(TransientDataAccessResourceException.class);
assertThat(wallet.account(9).actualBalance()).isEqualByComparingTo("140");
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM fin_wallet_ledger WHERE change_type='REFUND'", Integer.class)).isZero();
doCallRealMethod().when(jdbc).update(startsWith("INSERT INTO fin_audit_log"), any(Object[].class));
tx.execute(s -> wallet.refundConsumption(9, settled.actionLedgerId(), "RF-1", "refund-1",
new BigDecimal("20"), 7, "finance", "correction"));
assertThat(wallet.account(9).actualBalance()).isEqualByComparingTo("160");
}
private WalletHold settle(String key, String amount) {
return tx.execute(s -> wallet.settleActual(9, "PROCUREMENT_FEE", "PF-1", key, new BigDecimal(amount), "actual freight"));
}
@Test
void concurrentRefundsCannotExceedTheOriginalConsumption() throws Exception {
WalletHold original = settle("settle", "60");
ExecutorService executor = Executors.newFixedThreadPool(2);
CountDownLatch start = new CountDownLatch(1);
try {
Future<Boolean> one = executor.submit(() -> refundAttempt(start, original.actionLedgerId(), "RF-A"));
Future<Boolean> two = executor.submit(() -> refundAttempt(start, original.actionLedgerId(), "RF-B"));
start.countDown();
assertThat((one.get(10, TimeUnit.SECONDS) ? 1 : 0) + (two.get(10, TimeUnit.SECONDS) ? 1 : 0)).isEqualTo(1);
assertThat(wallet.account(9).actualBalance()).isEqualByComparingTo("180");
assertThat(jdbc.queryForObject("SELECT SUM(amount) FROM fin_wallet_ledger WHERE change_type='REFUND'", BigDecimal.class))
.isEqualByComparingTo("40");
} finally {
executor.shutdownNow();
assertThat(executor.awaitTermination(5, TimeUnit.SECONDS)).isTrue();
}
}
private boolean refundAttempt(CountDownLatch start, long originalId, String number) throws InterruptedException {
if (!start.await(5, TimeUnit.SECONDS)) throw new AssertionError("start timeout");
try {
tx.execute(s -> wallet.refundConsumption(9, originalId, number, number, new BigDecimal("40"),
7, "finance", "correction"));
return true;
} catch (FinanceEventException expected) {
assertThat(expected.code()).isEqualTo("FIN-WALLET-REFUND-EXCEEDED");
return false;
}
}
private void assertUntouched() {
assertThat(wallet.account(9).actualBalance()).isEqualByComparingTo("200");
assertThat(wallet.account(9).frozenBalance()).isEqualByComparingTo("100");
assertThat(jdbc.queryForObject("SELECT status FROM fin_wallet_hold", String.class)).isEqualTo("FROZEN");
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM fin_wallet_ledger", Integer.class)).isZero();
}
}