feat(console): add deletion lifecycle, usage history and balance adjustments
This commit is contained in:
1 parent
32e977df5c
commit
7360cf3ebe
18 files changed
+832
-68
No files matched your search
@@ -12,6 +12,11 @@ public class WalletController {
|
||||
private final WalletService wallet;
|
||||
public WalletController(WalletService wallet) { this.wallet=wallet; }
|
||||
public record GrantRequest(UUID requestId, String amount, String reason) {}
|
||||
public record AdjustmentRequest(UUID requestId, String operation, String amount, String reason, String expectedBalance) {}
|
||||
@PostMapping("/users/{id}/wallet/adjustments")
|
||||
public Map<String,Object> adjust(@PathVariable UUID id,@RequestBody AdjustmentRequest input,HttpServletRequest request) {
|
||||
return wallet.adjust(AuthController.sessionToken(request),id,input.requestId(),input.operation(),input.amount(),input.reason(),input.expectedBalance(),AuthController.meta(request));
|
||||
}
|
||||
@GetMapping("/wallets")
|
||||
public Map<String,Object> balances(HttpServletRequest request) { return Map.of("wallets",wallet.balances(AuthController.sessionToken(request))); }
|
||||
@GetMapping("/users/{id}/wallet")
|
||||
|
||||
@@ -25,36 +25,51 @@ public class WalletService {
|
||||
|
||||
public List<Map<String,Object>> entries(String token, UUID userId) {
|
||||
auth.requireAdmin(token);
|
||||
return jdbc.queryForList("SELECT e.id, e.amount, e.balance_after AS \"balanceAfter\", e.currency, e.reason, e.created_at AS \"createdAt\", u.display_name AS actor FROM wallet_entries e JOIN users u ON u.id=e.actor_user_id WHERE e.user_id=? ORDER BY e.created_at DESC LIMIT 100",userId);
|
||||
return jdbc.queryForList("SELECT e.id, e.amount, e.operation, e.balance_before AS \"balanceBefore\", e.balance_after AS \"balanceAfter\", e.currency, e.reason, e.created_at AS \"createdAt\", u.display_name AS actor FROM wallet_entries e JOIN users u ON u.id=e.actor_user_id WHERE e.user_id=? ORDER BY e.created_at DESC LIMIT 100",userId);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Map<String,Object> grant(String token, UUID userId, UUID requestId, String amountInput, String reasonInput, AuthService.RequestMeta meta) {
|
||||
return adjust(token,userId,requestId,"increase",amountInput,reasonInput,null,meta);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Map<String,Object> adjust(String token, UUID userId, UUID requestId, String operation, String amountInput, String reasonInput, String expectedBalanceInput, AuthService.RequestMeta meta) {
|
||||
var actor=auth.requireAdmin(token);
|
||||
if(requestId==null) throw new ApiException("INVALID_REQUEST_ID","请提供发放请求编号");
|
||||
if(requestId==null) throw new ApiException("INVALID_REQUEST_ID","请提供调整请求编号");
|
||||
if(operation==null || !List.of("increase","decrease","set").contains(operation)) throw new ApiException("INVALID_OPERATION","请选择增加、减少或设置余额");
|
||||
BigDecimal amount;
|
||||
try {
|
||||
amount=new BigDecimal(amountInput).setScale(2,RoundingMode.UNNECESSARY);
|
||||
if(amount.signum()<=0 || amount.compareTo(new BigDecimal("1000000"))>0) throw new NumberFormatException();
|
||||
} catch(Exception exception) { throw new ApiException("INVALID_AMOUNT","金额需大于 0,最多两位小数,单次不超过 100 万元"); }
|
||||
if(amount.signum()<0 || (!"set".equals(operation) && amount.signum()==0) || amount.compareTo(new BigDecimal("1000000"))>0) throw new NumberFormatException();
|
||||
} catch(Exception exception) { throw new ApiException("INVALID_AMOUNT","金额最多两位小数,不超过 100 万元;增减金额需大于 0,目标余额可为 0"); }
|
||||
BigDecimal expected=null;
|
||||
if(expectedBalanceInput!=null) {
|
||||
try { expected=new BigDecimal(expectedBalanceInput); }
|
||||
catch(Exception e) { throw new ApiException("INVALID_BALANCE","当前余额格式无效"); }
|
||||
}
|
||||
if("set".equals(operation) && expected==null) throw new ApiException("BALANCE_REQUIRED","设置余额前请刷新当前余额");
|
||||
String reason=reasonInput==null?"":reasonInput.trim();
|
||||
if(reason.isBlank() || reason.length()>500) throw new ApiException("INVALID_REASON","请填写发放原因(最多 500 字符)");
|
||||
if(reason.isBlank() || reason.length()>500) throw new ApiException("INVALID_REASON","请填写调整原因(最多 500 字符)");
|
||||
if(jdbc.queryForObject("SELECT count(*) FROM users WHERE id=? AND status='active'",Integer.class,userId)==0) throw new ApiException("USER_NOT_FOUND","用户不存在或已停用",404);
|
||||
// Lock the idempotency key before the wallet so concurrent retries cannot grant twice.
|
||||
jdbc.queryForList("SELECT pg_advisory_xact_lock(hashtextextended(?, 0))",requestId.toString());
|
||||
List<Map<String,Object>> existing=jdbc.queryForList("SELECT * FROM wallet_entries WHERE request_id=?",requestId);
|
||||
if(!existing.isEmpty()) {
|
||||
var entry=existing.getFirst();
|
||||
if(!userId.equals(entry.get("user_id")) || !actor.id().equals(entry.get("actor_user_id")) || amount.compareTo((BigDecimal)entry.get("amount"))!=0 || !reason.equals(entry.get("reason"))) throw new ApiException("REQUEST_CONFLICT","请求编号已被另一笔发放使用",409);
|
||||
if(!userId.equals(entry.get("user_id")) || !actor.id().equals(entry.get("actor_user_id")) || !operation.equals(entry.get("operation")) || amount.compareTo((BigDecimal)entry.get("requested_amount"))!=0 || !reason.equals(entry.get("reason")) || (expected!=null && expected.compareTo((BigDecimal)entry.get("balance_before"))!=0)) throw new ApiException("REQUEST_CONFLICT","请求编号已被另一笔调整使用",409);
|
||||
return Map.of("id",entry.get("id"),"balance",entry.get("balance_after"),"currency","CNY","replayed",true);
|
||||
}
|
||||
jdbc.update("INSERT INTO user_wallets(user_id) VALUES (?) ON CONFLICT DO NOTHING",userId);
|
||||
BigDecimal balance=jdbc.queryForObject("SELECT balance FROM user_wallets WHERE user_id=? FOR UPDATE",BigDecimal.class,userId);
|
||||
BigDecimal next=balance.add(amount);
|
||||
if(expected!=null && balance.compareTo(expected)!=0) throw new ApiException("BALANCE_CHANGED","余额已变化,请刷新后重新确认调整",409);
|
||||
BigDecimal next=switch(operation) { case "decrease" -> balance.subtract(amount); case "set" -> amount; default -> balance.add(amount); };
|
||||
if(next.signum()<0) throw new ApiException("INSUFFICIENT_BALANCE","减少金额不能超过当前余额",409);
|
||||
BigDecimal delta=next.subtract(balance);
|
||||
UUID id=UUID.randomUUID();
|
||||
jdbc.update("UPDATE user_wallets SET balance=?, updated_at=now() WHERE user_id=?",next,userId);
|
||||
jdbc.update("INSERT INTO wallet_entries(id,user_id,actor_user_id,request_id,amount,balance_after,reason) VALUES (?,?,?,?,?,?,?)",id,userId,actor.id(),requestId,amount,next,reason);
|
||||
auth.audit("wallet.credit_granted",actor.id(),meta,Map.of("userId",userId,"entryId",id,"amount",amount,"currency","CNY","reason",reason));
|
||||
jdbc.update("INSERT INTO wallet_entries(id,user_id,actor_user_id,request_id,amount,balance_before,balance_after,reason,operation,requested_amount) VALUES (?,?,?,?,?,?,?,?,?,?)",id,userId,actor.id(),requestId,delta,balance,next,reason,operation,amount);
|
||||
auth.audit("increase".equals(operation)?"wallet.credit_granted":"wallet.credit_adjusted",actor.id(),meta,Map.of("userId",userId,"entryId",id,"amount",delta,"balanceBefore",balance,"balanceAfter",next,"operation",operation,"currency","CNY","reason",reason));
|
||||
return Map.of("id",id,"balance",next,"currency","CNY","replayed",false);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user