Wallet.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. using System.ComponentModel.DataAnnotations;
  2. using System.ComponentModel.DataAnnotations.Schema;
  3. using Domain.Entities.Common.ValueObject;
  4. using Domain.Entities.Members;
  5. using Domain.Entities.Wallets.Policy;
  6. using Domain.Entities.Wallets.ValueObject;
  7. namespace Domain.Entities.Wallets;
  8. public class Wallet
  9. {
  10. [ForeignKey(nameof(MemberID))]
  11. public virtual Member Member { get; private set; } = null!;
  12. private readonly List<WalletBalance> _balances = [];
  13. public IReadOnlyCollection<WalletBalance> Balances => _balances;
  14. private readonly List<WalletTransaction> _transactions = [];
  15. public IReadOnlyCollection<WalletTransaction> Transactions => _transactions;
  16. [Key]
  17. public int ID { get; private set; }
  18. public Guid WalletKey { get; private set; } = Guid.NewGuid();
  19. public int MemberID { get; private set; }
  20. public DateTime? UpdatedAt { get; private set; }
  21. public DateTime CreatedAt { get; private set; } = DateTime.UtcNow;
  22. private Wallet() { }
  23. private Wallet(int memberID)
  24. {
  25. if (memberID <= 0)
  26. {
  27. throw new ArgumentOutOfRangeException(nameof(memberID));
  28. }
  29. MemberID = memberID;
  30. // 지갑 생성 시 구분별 잔액 기본 생성
  31. EnsureBalance(WalletBalanceType.PgCharged);
  32. EnsureBalance(WalletBalanceType.Deposit);
  33. EnsureBalance(WalletBalanceType.Donation);
  34. EnsureBalance(WalletBalanceType.Reward);
  35. EnsureBalance(WalletBalanceType.Airdrop);
  36. EnsureBalance(WalletBalanceType.Locked);
  37. EnsureBalance(WalletBalanceType.Adjusted);
  38. }
  39. public static Wallet Create(int memberID) => new(memberID);
  40. public Money GetBalance(WalletBalanceType type) => GetBalanceEntity(type).Amount;
  41. public Money GetTotalAvailable()
  42. {
  43. var total = Money.KRW(0);
  44. foreach (var b in Balances.Where(x => x.Type != WalletBalanceType.Locked))
  45. total += b.Amount;
  46. return total;
  47. }
  48. /// <summary>
  49. /// 상점 결제로 사용 가능한 잔액 합계 (SpendPolicy.StoreOrderSpendOrder 기준).
  50. /// 비활성 잔액 유형(원장 호환용)과 Locked 는 제외.
  51. /// </summary>
  52. public Money GetStoreOrderAvailable()
  53. {
  54. var total = Money.KRW(0);
  55. foreach (var type in Policy.SpendPolicy.StoreOrderSpendOrder)
  56. {
  57. total += GetBalance(type);
  58. }
  59. return total;
  60. }
  61. // ---- Credit ----
  62. public void CreditPgCharge(Money amount, string reason = "PG_CHARGE", string? refID = null)
  63. => Credit(WalletBalanceType.PgCharged, WalletTransactionType.Charge, amount, reason, refID);
  64. public void CreditDonationIn(Money amount, string reason, string? refID = null)
  65. => Credit(WalletBalanceType.Donation, WalletTransactionType.DonationIn, amount, reason, refID);
  66. public void CreditReward(Money amount, string reason = "REWARD", string? refID = null)
  67. => Credit(WalletBalanceType.Reward, WalletTransactionType.RewardEarned, amount, reason, refID);
  68. /// <summary>
  69. /// 가입 축하 보상 적립: 지정 잔액 유형(코인=Airdrop, 캐시=Adjusted)으로 입금하되
  70. /// 트랜잭션 타입은 RewardEarned 로 기록해 멱등 판정(RefID "signup:{memberID}")을 일원화한다.
  71. /// Locked 는 출금 프로세스 전용이라 직접 적립 불가.
  72. /// </summary>
  73. public void CreditSignupReward(WalletBalanceType type, Money amount, string reason, string? refID = null)
  74. {
  75. if (type == WalletBalanceType.Locked)
  76. {
  77. throw new ArgumentException("Locked balance cannot be credited directly.", nameof(type));
  78. }
  79. Credit(type, WalletTransactionType.RewardEarned, amount, reason, refID);
  80. }
  81. /// <summary>
  82. /// 상점 환불 환원: 원본 결제(OrderPay)가 차감한 BalanceType 그대로 복원해 출처를 보존한다.
  83. /// 호출자는 OrderPay 트랜잭션을 BalanceType 별로 집계해 type 마다 한 번씩 호출한다.
  84. /// </summary>
  85. public void CreditStoreOrderRefund(WalletBalanceType type, Money amount, string reason = "ORDER_REFUND", string? refID = null)
  86. => Credit(type, WalletTransactionType.OrderRefund, amount, reason, refID);
  87. private void Credit(
  88. WalletBalanceType balanceType,
  89. WalletTransactionType txType,
  90. Money amount,
  91. string reason,
  92. string? refID
  93. ) {
  94. EnsureMoney(amount);
  95. var balance = EnsureBalance(balanceType);
  96. balance.Increase(amount);
  97. _transactions.Add(WalletTransaction.Create(
  98. walletKey: WalletKey,
  99. balanceType: balanceType,
  100. txType: txType,
  101. amount: amount,
  102. balanceAfter: balance.Amount,
  103. reason: reason,
  104. refID: refID
  105. ));
  106. }
  107. /// <summary>
  108. /// 모의투자 출금 환급: 계좌 → 지갑 토큰(Reward 파티션). 트랜잭션 타입 PaperWithdraw.
  109. /// </summary>
  110. public void CreditPaperWithdraw(Money amount, string reason = "PAPER_WITHDRAW", string? refID = null)
  111. => Credit(WalletBalanceType.Reward, WalletTransactionType.PaperWithdraw, amount, reason, refID);
  112. /// <summary>
  113. /// 모의투자 입금: 토큰 파티션(Reward → Airdrop) 순서로 분할 차감하고 사용된 BalanceType 별로
  114. /// PaperDeposit 트랜잭션을 각각 기록한다. 합계 부족 시 InvalidOperationException —
  115. /// 호출자가 GetPaperTokenAvailable 로 사전 검증할 것.
  116. /// </summary>
  117. public void DebitForPaperDeposit(Money total, string reason = "PAPER_DEPOSIT", string? refID = null)
  118. {
  119. EnsureMoney(total);
  120. var remaining = total;
  121. foreach (var type in PaperTokenSpendOrder)
  122. {
  123. if (remaining.IsZero) break;
  124. var balance = EnsureBalance(type);
  125. if (balance.Amount.IsZero) continue;
  126. var takeValue = Math.Min(balance.Amount.Value, remaining.Value);
  127. if (takeValue <= 0) continue;
  128. var take = Money.KRW(takeValue);
  129. balance.Decrease(take);
  130. remaining = remaining - take;
  131. _transactions.Add(WalletTransaction.Create(
  132. walletKey: WalletKey,
  133. balanceType: type,
  134. txType: WalletTransactionType.PaperDeposit,
  135. amount: take,
  136. balanceAfter: balance.Amount,
  137. reason: reason,
  138. refID: refID
  139. ));
  140. }
  141. if (!remaining.IsZero)
  142. {
  143. throw new InvalidOperationException("Insufficient token balance for paper deposit.");
  144. }
  145. }
  146. /// <summary>모의투자 입금 가용 토큰 합계 (Reward + Airdrop).</summary>
  147. public Money GetPaperTokenAvailable()
  148. {
  149. var total = Money.KRW(0);
  150. foreach (var type in PaperTokenSpendOrder)
  151. {
  152. total += GetBalance(type);
  153. }
  154. return total;
  155. }
  156. // 모의투자 토큰 파티션 (활동 보상 재화 = 코인/토큰). 입금 시 Reward 먼저, 이후 Airdrop.
  157. private static readonly WalletBalanceType[] PaperTokenSpendOrder =
  158. {
  159. WalletBalanceType.Reward,
  160. WalletBalanceType.Airdrop
  161. };
  162. // ---- Debit ----
  163. public void DebitDonationOut(Money amount, string reason, string? refID = null)
  164. => DebitSingle(WalletBalanceType.Donation, WalletTransactionType.DonationOut, amount, reason, refID);
  165. /// <summary>
  166. /// 상점 결제 전용 다중 잔액 차감: SpendPolicy.StoreOrderSpendOrder 순서로 분할 차감하고
  167. /// 사용된 BalanceType 별로 OrderPay 트랜잭션을 각각 기록한다 (환불 시 출처 복원용).
  168. /// 합계 부족 시 InvalidOperationException — 호출자가 GetStoreOrderAvailable 로 사전 검증할 것.
  169. /// </summary>
  170. public IReadOnlyList<(WalletBalanceType Type, Money Amount)> DebitForStoreOrder(
  171. Money total,
  172. string reason = "ORDER_PAY",
  173. string? refID = null)
  174. {
  175. EnsureMoney(total);
  176. var remaining = total;
  177. var splits = new List<(WalletBalanceType, Money)>();
  178. foreach (var type in Policy.SpendPolicy.StoreOrderSpendOrder)
  179. {
  180. if (remaining.IsZero) break;
  181. var balance = EnsureBalance(type);
  182. if (balance.Amount.IsZero) continue;
  183. var takeValue = Math.Min(balance.Amount.Value, remaining.Value);
  184. if (takeValue <= 0) continue;
  185. var take = Money.KRW(takeValue);
  186. balance.Decrease(take);
  187. remaining = remaining - take;
  188. _transactions.Add(WalletTransaction.Create(
  189. walletKey: WalletKey,
  190. balanceType: type,
  191. txType: WalletTransactionType.OrderPay,
  192. amount: take,
  193. balanceAfter: balance.Amount,
  194. reason: reason,
  195. refID: refID
  196. ));
  197. splits.Add((type, take));
  198. }
  199. if (!remaining.IsZero)
  200. {
  201. throw new InvalidOperationException("Insufficient balance for store order.");
  202. }
  203. return splits;
  204. }
  205. /// <summary>
  206. /// PG 결제 취소 회수: 충전분(PgCharged)을 되돌린다.
  207. /// 잔액 부족 시 WalletBalance.Decrease 예외 — 호출자가 PgCharged 잔액을 사전 검증할 것.
  208. /// </summary>
  209. public void DebitChargeCancel(Money amount, string reason = "CHARGE_CANCEL", string? refID = null)
  210. => DebitSingle(WalletBalanceType.PgCharged, WalletTransactionType.ChargeCancelled, amount, reason, refID);
  211. // ---- Spend (정책 순서대로 분할 차감) ----
  212. public void Spend(Money amount, string reason = "SPEND", string? refID = null)
  213. {
  214. EnsureMoney(amount);
  215. var remaining = amount;
  216. foreach (var type in SpendPolicy.DefaultSpendOrder)
  217. {
  218. if (remaining.IsZero) break;
  219. var balance = EnsureBalance(type);
  220. if (balance.Amount.IsZero) continue;
  221. var takeValue = Math.Min(balance.Amount.Value, remaining.Value);
  222. if (takeValue <= 0) continue;
  223. var take = Money.KRW(takeValue);
  224. balance.Decrease(take);
  225. remaining = remaining - take;
  226. _transactions.Add(WalletTransaction.Create(
  227. walletKey: WalletKey,
  228. balanceType: type,
  229. txType: WalletTransactionType.Spend,
  230. amount: take,
  231. balanceAfter: balance.Amount,
  232. reason: reason,
  233. refID: refID
  234. ));
  235. }
  236. if (!remaining.IsZero)
  237. {
  238. throw new InvalidOperationException("Insufficient balance for spending.");
  239. }
  240. }
  241. // ---- Lock/Unlock ----
  242. public void LockForWithdrawal(Money amount, string reason = "WITHDRAW_REQUEST", string? refID = null)
  243. {
  244. EnsureMoney(amount);
  245. var from = EnsureBalance(WalletBalanceType.Donation);
  246. var locked = EnsureBalance(WalletBalanceType.Locked);
  247. from.Decrease(amount);
  248. _transactions.Add(WalletTransaction.Create(WalletKey, WalletBalanceType.Donation, WalletTransactionType.Lock, amount, from.Amount, reason, refID));
  249. locked.Increase(amount);
  250. _transactions.Add(WalletTransaction.Create(WalletKey, WalletBalanceType.Locked, WalletTransactionType.Lock, amount, locked.Amount, reason, refID));
  251. }
  252. public void UnlockWithdrawal(Money amount, string reason = "WITHDRAW_CANCEL", string? refID = null)
  253. {
  254. EnsureMoney(amount);
  255. var locked = EnsureBalance(WalletBalanceType.Locked);
  256. var donation = EnsureBalance(WalletBalanceType.Donation);
  257. locked.Decrease(amount);
  258. _transactions.Add(WalletTransaction.Create(WalletKey, WalletBalanceType.Locked, WalletTransactionType.Unlock, amount, locked.Amount, reason, refID));
  259. donation.Increase(amount);
  260. _transactions.Add(WalletTransaction.Create(WalletKey, WalletBalanceType.Donation, WalletTransactionType.Unlock, amount, donation.Amount, reason, refID));
  261. }
  262. // ---- Adjust ----
  263. public void AdjustIncrease(Money amount, string reason, string? refID = null, string? memo = null)
  264. => AdjustIncrease(WalletBalanceType.Adjusted, amount, reason, refID, memo);
  265. /// <summary>
  266. /// 관리자 조정 충전: 지정한 잔액 유형으로 입금. 트랜잭션 타입은 Adjusted 로 기록해 수동 조작 추적을 보존한다.
  267. /// Locked 는 출금 프로세스 전용이라 직접 조정 불가.
  268. /// </summary>
  269. public void AdjustIncrease(WalletBalanceType type, Money amount, string reason, string? refID = null, string? memo = null)
  270. {
  271. EnsureMoney(amount);
  272. EnsureAdjustableType(type);
  273. if (string.IsNullOrWhiteSpace(reason))
  274. {
  275. throw new ArgumentException("Adjustment reason is required.", nameof(reason));
  276. }
  277. var balance = EnsureBalance(type);
  278. balance.Increase(amount);
  279. _transactions.Add(WalletTransaction.Create(
  280. walletKey: WalletKey,
  281. balanceType: type,
  282. txType: WalletTransactionType.Adjusted,
  283. amount: amount,
  284. balanceAfter: balance.Amount,
  285. reason: $"ADJUST_IN:{reason}",
  286. refID: refID,
  287. memo: memo
  288. ));
  289. }
  290. public void AdjustDecrease(Money amount, string reason, string? refID = null, string? memo = null)
  291. => AdjustDecrease(WalletBalanceType.Adjusted, amount, reason, refID, memo);
  292. /// <summary>
  293. /// 관리자 조정 차감: 지정한 잔액 유형에서만 차감. 잔액 부족 시 WalletBalance.Decrease 가 예외 —
  294. /// 호출자가 해당 잔액을 사전 검증할 것.
  295. /// </summary>
  296. public void AdjustDecrease(WalletBalanceType type, Money amount, string reason, string? refID = null, string? memo = null)
  297. {
  298. EnsureMoney(amount);
  299. EnsureAdjustableType(type);
  300. if (string.IsNullOrWhiteSpace(reason))
  301. {
  302. throw new ArgumentException("Adjustment reason is required.", nameof(reason));
  303. }
  304. var balance = EnsureBalance(type);
  305. balance.Decrease(amount);
  306. _transactions.Add(WalletTransaction.Create(
  307. walletKey: WalletKey,
  308. balanceType: type,
  309. txType: WalletTransactionType.Adjusted,
  310. amount: amount,
  311. balanceAfter: balance.Amount,
  312. reason: $"ADJUST_OUT:{reason}",
  313. refID: refID,
  314. memo: memo
  315. ));
  316. }
  317. private static void EnsureAdjustableType(WalletBalanceType type)
  318. {
  319. if (type == WalletBalanceType.Locked)
  320. {
  321. throw new ArgumentException("Locked balance cannot be adjusted directly.", nameof(type));
  322. }
  323. }
  324. /// <summary>
  325. /// 관리자 차감 전용 다중 잔액 분할 차감: SpendPolicy.DefaultSpendOrder 순서로 분할 차감하고
  326. /// 사용된 BalanceType 별로 Adjusted 트랜잭션을 각각 기록한다.
  327. /// 합계 부족 시 InvalidOperationException — 호출자가 GetTotalAvailable 로 사전 검증할 것.
  328. /// </summary>
  329. public void AdjustDecreaseAcrossBalances(Money amount, string reason, string? refID = null, string? memo = null)
  330. {
  331. EnsureMoney(amount);
  332. if (string.IsNullOrWhiteSpace(reason))
  333. {
  334. throw new ArgumentException("Adjustment reason is required.", nameof(reason));
  335. }
  336. var remaining = amount;
  337. foreach (var type in SpendPolicy.DefaultSpendOrder)
  338. {
  339. if (remaining.IsZero) break;
  340. var balance = EnsureBalance(type);
  341. if (balance.Amount.IsZero) continue;
  342. var takeValue = Math.Min(balance.Amount.Value, remaining.Value);
  343. if (takeValue <= 0) continue;
  344. var take = Money.KRW(takeValue);
  345. balance.Decrease(take);
  346. remaining = remaining - take;
  347. _transactions.Add(WalletTransaction.Create(
  348. walletKey: WalletKey,
  349. balanceType: type,
  350. txType: WalletTransactionType.Adjusted,
  351. amount: take,
  352. balanceAfter: balance.Amount,
  353. reason: $"ADJUST_OUT:{reason}",
  354. refID: refID,
  355. memo: memo
  356. ));
  357. }
  358. if (!remaining.IsZero)
  359. {
  360. throw new InvalidOperationException("Insufficient balance for adjustment.");
  361. }
  362. }
  363. // ---- Internal ----
  364. private void DebitSingle(WalletBalanceType balanceType, WalletTransactionType txType, Money amount, string reason, string? refID)
  365. {
  366. EnsureMoney(amount);
  367. var balance = EnsureBalance(balanceType);
  368. balance.Decrease(amount);
  369. _transactions.Add(WalletTransaction.Create(
  370. walletKey: WalletKey,
  371. balanceType: balanceType,
  372. txType: txType,
  373. amount: amount,
  374. balanceAfter: balance.Amount,
  375. reason: reason,
  376. refID: refID
  377. ));
  378. }
  379. private WalletBalance GetBalanceEntity(WalletBalanceType type)
  380. {
  381. var found = _balances.SingleOrDefault(x => x.Type == type);
  382. if (found is null)
  383. {
  384. throw new InvalidOperationException($"Balance type '{type}' not initialized.");
  385. }
  386. return found;
  387. }
  388. private WalletBalance EnsureBalance(WalletBalanceType type)
  389. {
  390. var found = _balances.SingleOrDefault(x => x.Type == type);
  391. if (found != null)
  392. {
  393. return found;
  394. }
  395. var created = WalletBalance.Create(WalletKey, type);
  396. _balances.Add(created);
  397. return created;
  398. }
  399. private static void EnsureMoney(Money amount)
  400. {
  401. if (amount.IsZero || amount.Value <= 0)
  402. {
  403. throw new ArgumentException("Amount must be positive.", nameof(amount));
  404. }
  405. }
  406. }