Files
webup-cloud/backend/src/main/java/run/webup/platform/WalletService.java
T
WebUp Cloud db82325ed7
Verify control plane / verify (push) Canceled after 0s
Initial import of WebUp Cloud
2026-11-07 13:31:14 +08:00

279 lines
10 KiB
Java

package run.webup.platform;
import java.math.*;
import java.util.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class WalletService {
private final JdbcTemplate db;
public WalletService(JdbcTemplate db) {
this.db = db;
}
public static BigDecimal money(BigDecimal value) {
if (value == null || value.precision() > 24 || value.scale() > 8)
throw new ApiError.Failure(400, "金额精度超出范围");
return value.setScale(8, RoundingMode.UNNECESSARY);
}
public Map<String, Object> get(UUID user) {
var w = db.queryForMap("SELECT balance,reserved FROM wallets WHERE user_id=?", user);
w.put("available", ((BigDecimal) w.get("balance")).subtract((BigDecimal) w.get("reserved")));
w.put("currency", "CNY");
return w;
}
private void lock(UUID user) {
db.queryForObject("SELECT user_id FROM wallets WHERE user_id=? FOR UPDATE", UUID.class, user);
}
@Transactional
public void refundPurchase(
UUID user,
BigDecimal amount,
String originalKey,
String refundKey,
String business,
String reason) {
amount = money(amount);
lock(user);
var previous =
db.queryForList(
"SELECT amount,business_id,kind FROM wallet_ledger WHERE user_id=? AND"
+ " idempotency_key=?",
user,
refundKey);
if (!previous.isEmpty()) {
var old = previous.getFirst();
if (((BigDecimal) old.get("amount")).compareTo(amount) != 0
|| !business.equals(old.get("business_id"))
|| !"PRIORITY_REFUND".equals(old.get("kind")))
throw new ApiError.Failure(409, "退款幂等标识冲突");
return;
}
var purchase =
db.queryForList(
"SELECT amount,business_id,kind FROM wallet_ledger WHERE user_id=? AND"
+ " idempotency_key=?",
user,
originalKey);
if (amount.signum() <= 0
|| purchase.isEmpty()
|| ((BigDecimal) purchase.getFirst().get("amount")).negate().compareTo(amount) != 0
|| !business.equals(purchase.getFirst().get("business_id"))
|| !"PRIORITY_PURCHASE".equals(purchase.getFirst().get("kind")))
throw new ApiError.Failure(409, "未找到金额一致的优先权消费记录,未退款");
if (db.queryForObject(
"SELECT COUNT(*) FROM wallet_ledger WHERE user_id=? AND business_id=? AND"
+ " kind='PRIORITY_REFUND'",
Integer.class,
user,
business)
> 0) throw new ApiError.Failure(409, "该优先权消费已经退款");
db.update(
"UPDATE wallets SET balance=balance+?,updated_at=CURRENT_TIMESTAMP WHERE user_id=?",
amount,
user);
db.update(
"INSERT INTO"
+ " wallet_ledger(id,user_id,amount,balance_after,kind,business_id,idempotency_key,reason)"
+ " VALUES (?,?,?,?,'PRIORITY_REFUND',?,?,?)",
UUID.randomUUID(),
user,
amount,
get(user).get("balance"),
business,
refundKey,
reason);
}
@Transactional
public Map<String, Object> spend(
UUID user, BigDecimal amount, String business, String key, String kind, String reason) {
amount = money(amount);
if (amount.signum() < 0) throw new ApiError.Failure(400, "费用不能为负数");
lock(user);
var previous =
db.queryForList(
"SELECT * FROM wallet_ledger WHERE user_id=? AND idempotency_key=?", user, key);
if (!previous.isEmpty()) {
var p = previous.getFirst();
if (((BigDecimal) p.get("amount")).compareTo(amount.negate()) != 0
|| !business.equals(p.get("business_id"))
|| !kind.equals(p.get("kind"))) throw new ApiError.Failure(409, "消费幂等标识冲突");
return p;
}
if (((BigDecimal) get(user).get("available")).compareTo(amount) < 0)
throw new ApiError.Failure(402, "可用余额不足");
db.update(
"UPDATE wallets SET balance=balance-?,updated_at=CURRENT_TIMESTAMP WHERE user_id=?",
amount,
user);
UUID id = UUID.randomUUID();
db.update(
"INSERT INTO"
+ " wallet_ledger(id,user_id,amount,balance_after,kind,business_id,idempotency_key,reason)"
+ " VALUES (?,?,?,?,?,?,?,?)",
id,
user,
amount.negate(),
get(user).get("balance"),
kind,
business,
key,
reason);
return db.queryForMap("SELECT * FROM wallet_ledger WHERE id=?", id);
}
@Transactional
public Map<String, Object> adjust(
UUID user, BigDecimal amount, String key, String reason, UUID actor, String ip) {
amount = money(amount);
if (amount.signum() == 0) throw new ApiError.Failure(400, "调整金额不能为零");
lock(user);
var prior =
db.queryForList(
"SELECT * FROM wallet_ledger WHERE user_id=? AND idempotency_key=?", user, key);
if (!prior.isEmpty()) {
var p = prior.getFirst();
if (((BigDecimal) p.get("amount")).compareTo(amount) != 0
|| !reason.equals(p.get("reason"))
|| !actor.toString().equals(p.get("business_id")))
throw new ApiError.Failure(409, "幂等键已用于其他调整");
return p;
}
var wallet = get(user);
BigDecimal next = ((BigDecimal) wallet.get("balance")).add(amount);
if (next.compareTo((BigDecimal) wallet.get("reserved")) < 0)
throw new ApiError.Failure(409, "可用余额不足,不能扣除已预留资金");
UUID id = UUID.randomUUID();
db.update(
"UPDATE wallets SET balance=?,updated_at=CURRENT_TIMESTAMP WHERE user_id=?", next, user);
db.update(
"INSERT INTO"
+ " wallet_ledger(id,user_id,amount,balance_after,kind,business_id,idempotency_key,reason)"
+ " VALUES (?,?,?,?,?,?,?,?)",
id,
user,
amount,
next,
"ADMIN_ADJUSTMENT",
actor.toString(),
key,
reason);
db.update(
"INSERT INTO admin_operation_logs(id,actor_id,action,target,ip,details) VALUES"
+ " (?,?,?,?,?,?)",
UUID.randomUUID(),
actor,
"WALLET_ADJUST",
user.toString(),
ip,
"金额 " + amount + "; 原因 " + reason);
return db.queryForMap("SELECT * FROM wallet_ledger WHERE id=?", id);
}
@Transactional
public UUID reserve(UUID user, BigDecimal amount, String business) {
amount = money(amount);
if (amount.signum() <= 0) throw new ApiError.Failure(400, "预算必须大于零");
lock(user);
var existing =
db.queryForList(
"SELECT id,amount,user_id FROM wallet_reservations WHERE business_id=?", business);
if (!existing.isEmpty()) {
var e = existing.getFirst();
if (!user.toString().equals(e.get("user_id").toString())
|| amount.compareTo((BigDecimal) e.get("amount")) != 0)
throw new ApiError.Failure(409, "预算业务标识冲突");
return UUID.fromString(e.get("id").toString());
}
if (((BigDecimal) get(user).get("available")).compareTo(amount) < 0)
throw new ApiError.Failure(402, "可用余额不足,请充值或联系管理员");
UUID id = UUID.randomUUID();
db.update(
"UPDATE wallets SET reserved=reserved+?,updated_at=CURRENT_TIMESTAMP WHERE user_id=?",
amount,
user);
db.update(
"INSERT INTO wallet_reservations(id,user_id,amount,status,business_id) VALUES"
+ " (?,?,?,'OPEN',?)",
id,
user,
amount,
business);
return id;
}
@Transactional
public void charge(UUID reservation, BigDecimal amount, String key) {
amount = money(amount);
if (amount.signum() < 0) throw new ApiError.Failure(400, "费用不能为负数");
UUID user =
db.queryForObject(
"SELECT user_id FROM wallet_reservations WHERE id=?", UUID.class, reservation);
lock(user);
var prior =
db.queryForList(
"SELECT amount,business_id FROM wallet_ledger WHERE user_id=? AND idempotency_key=?",
user,
key);
if (!prior.isEmpty()) {
var p = prior.getFirst();
if (((BigDecimal) p.get("amount")).compareTo(amount.negate()) != 0
|| !reservation.toString().equals(p.get("business_id")))
throw new ApiError.Failure(409, "计费幂等键冲突");
return;
}
var r = db.queryForMap("SELECT * FROM wallet_reservations WHERE id=? FOR UPDATE", reservation);
if (!"OPEN".equals(r.get("status"))) throw new ApiError.Failure(409, "预算已关闭");
if (((BigDecimal) r.get("amount")).subtract((BigDecimal) r.get("spent")).compareTo(amount) < 0)
throw new ApiError.Failure(402, "任务预算不足,已暂停新的调用");
db.update(
"UPDATE wallets SET balance=balance-?,reserved=reserved-?,updated_at=CURRENT_TIMESTAMP"
+ " WHERE user_id=?",
amount,
amount,
user);
db.update(
"UPDATE wallet_reservations SET spent=spent+?,updated_at=CURRENT_TIMESTAMP WHERE id=?",
amount,
reservation);
BigDecimal after = (BigDecimal) get(user).get("balance");
db.update(
"INSERT INTO"
+ " wallet_ledger(id,user_id,amount,balance_after,kind,business_id,idempotency_key,reason)"
+ " VALUES (?,?,?,?,?,?,?,?)",
UUID.randomUUID(),
user,
amount.negate(),
after,
key.startsWith("manual:") ? "MANUAL_SETTLEMENT" : "AI_USAGE",
reservation.toString(),
key,
key.startsWith("manual:") ? "管理员人工核对结算" : "模型实际 usage 结算");
}
@Transactional
public void release(UUID reservation) {
UUID user =
db.queryForObject(
"SELECT user_id FROM wallet_reservations WHERE id=?", UUID.class, reservation);
lock(user);
var r = db.queryForMap("SELECT * FROM wallet_reservations WHERE id=? FOR UPDATE", reservation);
if ("CLOSED".equals(r.get("status"))) return;
BigDecimal remaining = ((BigDecimal) r.get("amount")).subtract((BigDecimal) r.get("spent"));
db.update(
"UPDATE wallets SET reserved=reserved-?,updated_at=CURRENT_TIMESTAMP WHERE user_id=?",
remaining,
user);
db.update(
"UPDATE wallet_reservations SET status='CLOSED',updated_at=CURRENT_TIMESTAMP WHERE id=?",
reservation);
}
}