Wallet.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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. // ---- Debit ----
  108. public void DebitDonationOut(Money amount, string reason, string? refID = null)
  109. => DebitSingle(WalletBalanceType.Donation, WalletTransactionType.DonationOut, amount, reason, refID);
  110. /// <summary>
  111. /// 상점 결제 전용 다중 잔액 차감: SpendPolicy.StoreOrderSpendOrder 순서로 분할 차감하고
  112. /// 사용된 BalanceType 별로 OrderPay 트랜잭션을 각각 기록한다 (환불 시 출처 복원용).
  113. /// 합계 부족 시 InvalidOperationException — 호출자가 GetStoreOrderAvailable 로 사전 검증할 것.
  114. /// </summary>
  115. public IReadOnlyList<(WalletBalanceType Type, Money Amount)> DebitForStoreOrder(
  116. Money total,
  117. string reason = "ORDER_PAY",
  118. string? refID = null)
  119. {
  120. EnsureMoney(total);
  121. var remaining = total;
  122. var splits = new List<(WalletBalanceType, Money)>();
  123. foreach (var type in Policy.SpendPolicy.StoreOrderSpendOrder)
  124. {
  125. if (remaining.IsZero) break;
  126. var balance = EnsureBalance(type);
  127. if (balance.Amount.IsZero) continue;
  128. var takeValue = Math.Min(balance.Amount.Value, remaining.Value);
  129. if (takeValue <= 0) continue;
  130. var take = Money.KRW(takeValue);
  131. balance.Decrease(take);
  132. remaining = remaining - take;
  133. _transactions.Add(WalletTransaction.Create(
  134. walletKey: WalletKey,
  135. balanceType: type,
  136. txType: WalletTransactionType.OrderPay,
  137. amount: take,
  138. balanceAfter: balance.Amount,
  139. reason: reason,
  140. refID: refID
  141. ));
  142. splits.Add((type, take));
  143. }
  144. if (!remaining.IsZero)
  145. {
  146. throw new InvalidOperationException("Insufficient balance for store order.");
  147. }
  148. return splits;
  149. }
  150. /// <summary>
  151. /// PG 결제 취소 회수: 충전분(PgCharged)을 되돌린다.
  152. /// 잔액 부족 시 WalletBalance.Decrease 예외 — 호출자가 PgCharged 잔액을 사전 검증할 것.
  153. /// </summary>
  154. public void DebitChargeCancel(Money amount, string reason = "CHARGE_CANCEL", string? refID = null)
  155. => DebitSingle(WalletBalanceType.PgCharged, WalletTransactionType.ChargeCancelled, amount, reason, refID);
  156. // ---- Spend (정책 순서대로 분할 차감) ----
  157. public void Spend(Money amount, string reason = "SPEND", string? refID = null)
  158. {
  159. EnsureMoney(amount);
  160. var remaining = amount;
  161. foreach (var type in SpendPolicy.DefaultSpendOrder)
  162. {
  163. if (remaining.IsZero) break;
  164. var balance = EnsureBalance(type);
  165. if (balance.Amount.IsZero) continue;
  166. var takeValue = Math.Min(balance.Amount.Value, remaining.Value);
  167. if (takeValue <= 0) continue;
  168. var take = Money.KRW(takeValue);
  169. balance.Decrease(take);
  170. remaining = remaining - take;
  171. _transactions.Add(WalletTransaction.Create(
  172. walletKey: WalletKey,
  173. balanceType: type,
  174. txType: WalletTransactionType.Spend,
  175. amount: take,
  176. balanceAfter: balance.Amount,
  177. reason: reason,
  178. refID: refID
  179. ));
  180. }
  181. if (!remaining.IsZero)
  182. {
  183. throw new InvalidOperationException("Insufficient balance for spending.");
  184. }
  185. }
  186. // ---- Lock/Unlock ----
  187. public void LockForWithdrawal(Money amount, string reason = "WITHDRAW_REQUEST", string? refID = null)
  188. {
  189. EnsureMoney(amount);
  190. var from = EnsureBalance(WalletBalanceType.Donation);
  191. var locked = EnsureBalance(WalletBalanceType.Locked);
  192. from.Decrease(amount);
  193. _transactions.Add(WalletTransaction.Create(WalletKey, WalletBalanceType.Donation, WalletTransactionType.Lock, amount, from.Amount, reason, refID));
  194. locked.Increase(amount);
  195. _transactions.Add(WalletTransaction.Create(WalletKey, WalletBalanceType.Locked, WalletTransactionType.Lock, amount, locked.Amount, reason, refID));
  196. }
  197. public void UnlockWithdrawal(Money amount, string reason = "WITHDRAW_CANCEL", string? refID = null)
  198. {
  199. EnsureMoney(amount);
  200. var locked = EnsureBalance(WalletBalanceType.Locked);
  201. var donation = EnsureBalance(WalletBalanceType.Donation);
  202. locked.Decrease(amount);
  203. _transactions.Add(WalletTransaction.Create(WalletKey, WalletBalanceType.Locked, WalletTransactionType.Unlock, amount, locked.Amount, reason, refID));
  204. donation.Increase(amount);
  205. _transactions.Add(WalletTransaction.Create(WalletKey, WalletBalanceType.Donation, WalletTransactionType.Unlock, amount, donation.Amount, reason, refID));
  206. }
  207. // ---- Adjust ----
  208. public void AdjustIncrease(Money amount, string reason, string? refID = null, string? memo = null)
  209. => AdjustIncrease(WalletBalanceType.Adjusted, amount, reason, refID, memo);
  210. /// <summary>
  211. /// 관리자 조정 충전: 지정한 잔액 유형으로 입금. 트랜잭션 타입은 Adjusted 로 기록해 수동 조작 추적을 보존한다.
  212. /// Locked 는 출금 프로세스 전용이라 직접 조정 불가.
  213. /// </summary>
  214. public void AdjustIncrease(WalletBalanceType type, Money amount, string reason, string? refID = null, string? memo = null)
  215. {
  216. EnsureMoney(amount);
  217. EnsureAdjustableType(type);
  218. if (string.IsNullOrWhiteSpace(reason))
  219. {
  220. throw new ArgumentException("Adjustment reason is required.", nameof(reason));
  221. }
  222. var balance = EnsureBalance(type);
  223. balance.Increase(amount);
  224. _transactions.Add(WalletTransaction.Create(
  225. walletKey: WalletKey,
  226. balanceType: type,
  227. txType: WalletTransactionType.Adjusted,
  228. amount: amount,
  229. balanceAfter: balance.Amount,
  230. reason: $"ADJUST_IN:{reason}",
  231. refID: refID,
  232. memo: memo
  233. ));
  234. }
  235. public void AdjustDecrease(Money amount, string reason, string? refID = null, string? memo = null)
  236. => AdjustDecrease(WalletBalanceType.Adjusted, amount, reason, refID, memo);
  237. /// <summary>
  238. /// 관리자 조정 차감: 지정한 잔액 유형에서만 차감. 잔액 부족 시 WalletBalance.Decrease 가 예외 —
  239. /// 호출자가 해당 잔액을 사전 검증할 것.
  240. /// </summary>
  241. public void AdjustDecrease(WalletBalanceType type, Money amount, string reason, string? refID = null, string? memo = null)
  242. {
  243. EnsureMoney(amount);
  244. EnsureAdjustableType(type);
  245. if (string.IsNullOrWhiteSpace(reason))
  246. {
  247. throw new ArgumentException("Adjustment reason is required.", nameof(reason));
  248. }
  249. var balance = EnsureBalance(type);
  250. balance.Decrease(amount);
  251. _transactions.Add(WalletTransaction.Create(
  252. walletKey: WalletKey,
  253. balanceType: type,
  254. txType: WalletTransactionType.Adjusted,
  255. amount: amount,
  256. balanceAfter: balance.Amount,
  257. reason: $"ADJUST_OUT:{reason}",
  258. refID: refID,
  259. memo: memo
  260. ));
  261. }
  262. private static void EnsureAdjustableType(WalletBalanceType type)
  263. {
  264. if (type == WalletBalanceType.Locked)
  265. {
  266. throw new ArgumentException("Locked balance cannot be adjusted directly.", nameof(type));
  267. }
  268. }
  269. /// <summary>
  270. /// 관리자 차감 전용 다중 잔액 분할 차감: SpendPolicy.DefaultSpendOrder 순서로 분할 차감하고
  271. /// 사용된 BalanceType 별로 Adjusted 트랜잭션을 각각 기록한다.
  272. /// 합계 부족 시 InvalidOperationException — 호출자가 GetTotalAvailable 로 사전 검증할 것.
  273. /// </summary>
  274. public void AdjustDecreaseAcrossBalances(Money amount, string reason, string? refID = null, string? memo = null)
  275. {
  276. EnsureMoney(amount);
  277. if (string.IsNullOrWhiteSpace(reason))
  278. {
  279. throw new ArgumentException("Adjustment reason is required.", nameof(reason));
  280. }
  281. var remaining = amount;
  282. foreach (var type in SpendPolicy.DefaultSpendOrder)
  283. {
  284. if (remaining.IsZero) break;
  285. var balance = EnsureBalance(type);
  286. if (balance.Amount.IsZero) continue;
  287. var takeValue = Math.Min(balance.Amount.Value, remaining.Value);
  288. if (takeValue <= 0) continue;
  289. var take = Money.KRW(takeValue);
  290. balance.Decrease(take);
  291. remaining = remaining - take;
  292. _transactions.Add(WalletTransaction.Create(
  293. walletKey: WalletKey,
  294. balanceType: type,
  295. txType: WalletTransactionType.Adjusted,
  296. amount: take,
  297. balanceAfter: balance.Amount,
  298. reason: $"ADJUST_OUT:{reason}",
  299. refID: refID,
  300. memo: memo
  301. ));
  302. }
  303. if (!remaining.IsZero)
  304. {
  305. throw new InvalidOperationException("Insufficient balance for adjustment.");
  306. }
  307. }
  308. // ---- Internal ----
  309. private void DebitSingle(WalletBalanceType balanceType, WalletTransactionType txType, Money amount, string reason, string? refID)
  310. {
  311. EnsureMoney(amount);
  312. var balance = EnsureBalance(balanceType);
  313. balance.Decrease(amount);
  314. _transactions.Add(WalletTransaction.Create(
  315. walletKey: WalletKey,
  316. balanceType: balanceType,
  317. txType: txType,
  318. amount: amount,
  319. balanceAfter: balance.Amount,
  320. reason: reason,
  321. refID: refID
  322. ));
  323. }
  324. private WalletBalance GetBalanceEntity(WalletBalanceType type)
  325. {
  326. var found = _balances.SingleOrDefault(x => x.Type == type);
  327. if (found is null)
  328. {
  329. throw new InvalidOperationException($"Balance type '{type}' not initialized.");
  330. }
  331. return found;
  332. }
  333. private WalletBalance EnsureBalance(WalletBalanceType type)
  334. {
  335. var found = _balances.SingleOrDefault(x => x.Type == type);
  336. if (found != null)
  337. {
  338. return found;
  339. }
  340. var created = WalletBalance.Create(WalletKey, type);
  341. _balances.Add(created);
  342. return created;
  343. }
  344. private static void EnsureMoney(Money amount)
  345. {
  346. if (amount.IsZero || amount.Value <= 0)
  347. {
  348. throw new ArgumentException("Amount must be positive.", nameof(amount));
  349. }
  350. }
  351. }