Handler.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. using Application.Abstractions.Data;
  2. using Application.Abstractions.Messaging;
  3. using Application.Abstractions.Payment;
  4. using Domain.Entities.Common.ValueObject;
  5. using Domain.Entities.Payments.Toss;
  6. using Domain.Entities.Store.ValueObject;
  7. using Domain.Entities.Wallets.ValueObject;
  8. using Microsoft.EntityFrameworkCore;
  9. using SharedKernel.Results;
  10. namespace Application.Features.Admin.Store.Order.ProcessRefund;
  11. /// <summary>
  12. /// 환불 실행 흐름 (사용자 정책):
  13. /// 1. 사전 검증 (Digital 미사용 쿠폰 가치 합)
  14. /// 2. 토스 부분 취소 호출 — 실패 시 OrderRefund.Reject + 종료
  15. /// 3. TossCancel 행 기록
  16. /// 4. OrderRefund.Approve
  17. /// 5. 구매자 환원: 원본 OrderPay 트랜잭션의 BalanceType 별로 비례 분배해 출처 복원
  18. /// 7. GameSettlement 비례 차감
  19. /// 8. Digital 상품 CouponCode 처리:
  20. /// - OrderRefundItem 가 있으면 → 각 행의 PostRefundAction (Restore/Expire) 적용
  21. /// - 없으면 fallback → 모든 미사용 코드 Restore (옛 환불 호환)
  22. /// - Used 코드는 skip (안전망)
  23. /// 9. Physical 상품: 재고 복구
  24. /// 10. Order.Status 갱신 (Cancelled/Refunded/Exchanged), refund.Complete
  25. /// </summary>
  26. public sealed class Handler(IAppDbContext db, ITossPaymentService tossPay) : ICommandHandler<Command, Result>
  27. {
  28. public async Task<Result> Handle(Command request, CancellationToken ct)
  29. {
  30. var refund = await db.OrderRefund
  31. .Include(r => r.Order)
  32. .ThenInclude(o => o!.Items)
  33. .ThenInclude(i => i.Product)
  34. .ThenInclude(p => p!.Game)
  35. .Include(r => r.Order)
  36. .ThenInclude(o => o!.Items)
  37. .ThenInclude(i => i.IssuedCouponCode)
  38. .Include(r => r.Items)
  39. .FirstOrDefaultAsync(r => r.ID == request.RefundID, ct);
  40. if (refund is null)
  41. {
  42. return Result.Failure(Error.NotFound("Refund.NotFound", "환불 요청을 찾을 수 없습니다."));
  43. }
  44. if (refund.Status != RefundStatus.Requested)
  45. {
  46. return Result.Failure(Error.Problem("Refund.NotPending", "처리 대기 중인 환불 요청만 실행 가능합니다."));
  47. }
  48. var order = refund.Order!;
  49. // 1. 사전 검증 — 미사용 쿠폰 가치 합이 환불 금액 이상
  50. var digitalUnusedValue = 0;
  51. foreach (var item in order.Items)
  52. {
  53. if (item.Product?.Type != ProductType.Digital)
  54. {
  55. continue;
  56. }
  57. var unusedCount = await db.MemberInventory.CountAsync(m => m.OrderItemID == item.ID && m.CouponCode!.Status != CouponCodeStatus.Used, ct);
  58. digitalUnusedValue += unusedCount * item.UnitPrice;
  59. }
  60. if (digitalUnusedValue < refund.Amount)
  61. {
  62. return Result.Failure(Error.Problem("Refund.InsufficientUnusedCoupons", $"환불 금액({refund.Amount:N0}원)에 대응하는 미사용 쿠폰 코드 가치({digitalUnusedValue:N0}원)가 부족합니다. 일부 쿠폰이 이미 사용되었습니다."));
  63. }
  64. // 2. 토스 부분/전체 취소 — PaymentOrder 조회 후 호출 (paymentKey = TransactionID)
  65. var paymentOrder = await db.PaymentOrder
  66. .Where(p => p.OrderID == order.OrderNumber && p.TransactionID != null)
  67. .OrderByDescending(p => p.ID)
  68. .FirstOrDefaultAsync(ct);
  69. if (paymentOrder is not null && !string.IsNullOrEmpty(paymentOrder.TransactionID))
  70. {
  71. var paymentKey = paymentOrder.TransactionID;
  72. var isFullCancel = refund.Amount >= paymentOrder.Amount;
  73. var cancelReason = string.IsNullOrWhiteSpace(refund.Reason) ? "주문 환불" : refund.Reason;
  74. // 취소 요청 기록 저장 (부분/전체) — 응답 전에 요청 흔적을 남긴다
  75. var tossCancel = TossCancel.CreateRequest(
  76. memberID: order.MemberID,
  77. paymentOrderID: paymentOrder.ID,
  78. paymentKey: paymentKey,
  79. orderID: order.OrderNumber,
  80. cancelAmount: refund.Amount,
  81. cancelReason: cancelReason,
  82. cancelRequester: request.AdminEmail ?? request.AdminUserId
  83. );
  84. db.TossCancel.Add(tossCancel);
  85. // 토스 취소 API 호출 (cancelAmount null = 전액 취소) — 통신 예외도 기록을 남긴다
  86. TossPaymentResult cancelResult;
  87. try
  88. {
  89. cancelResult = await tossPay.CancelAsync(paymentKey, cancelReason, isFullCancel ? null : refund.Amount, ct);
  90. }
  91. catch (Exception ex)
  92. {
  93. tossCancel.SetError("EXCEPTION", ex.Message);
  94. refund.Reject(request.AdminUserId, request.AdminEmail, $"[토스 취소 통신 오류] {ex.Message}");
  95. await db.SaveChangesAsync(ct);
  96. return Result.Failure(Error.Problem("Refund.TossCancelFailed", "결제 취소 처리 중 오류가 발생했습니다."));
  97. }
  98. if (!cancelResult.Success)
  99. {
  100. // 토스 실패 → 환불 요청 거부 처리. 운영자 메모에 토스 응답 기록.
  101. tossCancel.SetError(cancelResult.Code ?? "FAIL", cancelResult.Message ?? "취소 실패");
  102. refund.Reject(request.AdminUserId, request.AdminEmail, $"[토스 취소 실패] code={cancelResult.Code} message={cancelResult.Message}");
  103. await db.SaveChangesAsync(ct);
  104. return Result.Failure(Error.Problem("Refund.TossCancelFailed", $"토스 취소 실패: {cancelResult.Message ?? cancelResult.Code ?? "ERROR"}"));
  105. }
  106. // 3. TossCancel 응답 기록
  107. var last = cancelResult.Cancels.Count > 0 ? cancelResult.Cancels[^1] : null;
  108. tossCancel.SetResponse(cancelResult.Status ?? "", last?.TransactionKey, last?.CanceledAt, cancelResult.RawJson);
  109. }
  110. // PaymentOrder 가 없으면 (캐시만 결제 / 옛 주문) 토스 호출 skip
  111. // 4. OrderRefund 승인
  112. refund.Approve(request.AdminUserId, request.AdminEmail, request.AdminMemo);
  113. // 5. 구매자 환원: 원본 OrderPay 의 BalanceType 별 비례 분배로 출처 복원
  114. var buyerWallet = await db.Wallet
  115. .Include(w => w.Balances)
  116. .Include(w => w.Transactions)
  117. .FirstOrDefaultAsync(w => w.MemberID == order.MemberID, ct);
  118. if (buyerWallet is null)
  119. {
  120. return Result.Failure(Error.NotFound("Wallet.NotFound", "구매자 지갑을 찾을 수 없습니다."));
  121. }
  122. var originalByType = buyerWallet.Transactions
  123. .Where(t => t.TxType == WalletTransactionType.OrderPay && t.RefID == order.OrderNumber)
  124. .GroupBy(t => t.BalanceType)
  125. .ToDictionary(g => g.Key, g => (int)g.Sum(t => t.Amount.Value));
  126. if (originalByType.Count == 0)
  127. {
  128. return Result.Failure(Error.Problem("Refund.NoOriginalTransactions",
  129. "원본 결제 트랜잭션을 찾을 수 없어 환불 출처를 복원할 수 없습니다."));
  130. }
  131. var alreadyRefundedByType = buyerWallet.Transactions
  132. .Where(t => t.TxType == WalletTransactionType.OrderRefund && t.RefID == order.OrderNumber)
  133. .GroupBy(t => t.BalanceType)
  134. .ToDictionary(g => g.Key, g => (int)g.Sum(t => t.Amount.Value));
  135. var remainingByType = originalByType.ToDictionary(
  136. kvp => kvp.Key,
  137. kvp => kvp.Value - alreadyRefundedByType.GetValueOrDefault(kvp.Key, 0));
  138. var totalRemaining = remainingByType.Values.Sum();
  139. if (totalRemaining < refund.Amount)
  140. {
  141. return Result.Failure(Error.Problem("Refund.ExceedsRemaining",
  142. $"환불 가능 잔여 금액을 초과합니다. 요청 {refund.Amount:N0}원 / 잔여 {totalRemaining:N0}원"));
  143. }
  144. var distribution = new Dictionary<WalletBalanceType, int>();
  145. var distributed = 0;
  146. foreach (var (type, remainingForType) in remainingByType.OrderBy(x => (int)x.Key))
  147. {
  148. if (remainingForType <= 0)
  149. {
  150. continue;
  151. }
  152. var share = (int)Math.Floor((decimal)refund.Amount * remainingForType / totalRemaining);
  153. if (share > 0)
  154. {
  155. distribution[type] = share;
  156. distributed += share;
  157. }
  158. }
  159. var residual = refund.Amount - distributed;
  160. if (residual > 0)
  161. {
  162. foreach (var (type, remainingForType) in remainingByType.OrderByDescending(x => x.Value))
  163. {
  164. var assigned = distribution.GetValueOrDefault(type, 0);
  165. var capacity = remainingForType - assigned;
  166. if (capacity <= 0)
  167. {
  168. continue;
  169. }
  170. var add = Math.Min(capacity, residual);
  171. distribution[type] = assigned + add;
  172. residual -= add;
  173. if (residual == 0)
  174. {
  175. break;
  176. }
  177. }
  178. }
  179. foreach (var (type, amount) in distribution)
  180. {
  181. if (amount > 0)
  182. {
  183. buyerWallet.CreditStoreOrderRefund(type, Money.KRW(amount), reason: "ORDER_REFUND", refID: order.OrderNumber);
  184. }
  185. }
  186. // 6. 채널 보상 비례 차감 — 채널 보상 적립 제거됨(2026-07-03)에 따라 차감 로직도 제거.
  187. // 과거 주문(ChannelRewardAmount > 0) 환불 시 채널 회수는 수동 정정(운영자 조정)으로 처리.
  188. // 7. GameSettlement 비례 차감
  189. if (order.TotalAmount > 0 && order.GameRevenueAmount > 0)
  190. {
  191. // Items 의 게임별로 비례 차감
  192. foreach (var item in order.Items)
  193. {
  194. if (item.Product is null || item.Product.Game is null)
  195. {
  196. continue;
  197. }
  198. var lineTotal = item.UnitPrice * item.Quantity;
  199. if (lineTotal <= 0)
  200. {
  201. continue;
  202. }
  203. var lineGameRevenue = (int)Math.Floor((decimal)lineTotal * item.Product.Game.CommissionRate / 100m);
  204. var proRataGame = (int)Math.Floor((decimal)refund.Amount * lineGameRevenue / order.TotalAmount);
  205. if (proRataGame <= 0)
  206. {
  207. continue;
  208. }
  209. var year = order.PaidAt?.Year ?? order.CreatedAt.Year;
  210. var month = order.PaidAt?.Month ?? order.CreatedAt.Month;
  211. var settlement = await db.GameSettlement
  212. .FirstOrDefaultAsync(s => s.GameID == item.Product.GameID && s.Year == year && s.Month == month, ct);
  213. if (settlement is not null && settlement.Status == GameSettlementStatus.Pending)
  214. {
  215. settlement.SubtractRevenue(proRataGame);
  216. }
  217. }
  218. }
  219. // 8. CouponCode 처리:
  220. // - OrderRefundItem 가 있으면 명시된 CouponCode 만, 명시된 PostRefundAction 적용
  221. // - 없으면 fallback (옛 환불 호환) — 미사용 코드 모두 RestoreToAvailable
  222. if (refund.Items.Count > 0)
  223. {
  224. var refundItemCouponIds = refund.Items.Select(x => x.CouponCodeID).ToList();
  225. var inventories = await db.MemberInventory
  226. .Include(m => m.CouponCode)
  227. .Where(m => refundItemCouponIds.Contains(m.CouponCodeID))
  228. .ToListAsync(ct);
  229. var invByCouponCode = inventories.ToDictionary(m => m.CouponCodeID);
  230. foreach (var refundItem in refund.Items)
  231. {
  232. if (!invByCouponCode.TryGetValue(refundItem.CouponCodeID, out var inv) || inv.CouponCode is null)
  233. {
  234. continue; // 이미 처리됐거나 데이터 없음 — skip
  235. }
  236. if (inv.CouponCode.Status == CouponCodeStatus.Used)
  237. {
  238. continue; // 안전망: Used 는 회수/만료 모두 불가
  239. }
  240. switch (refundItem.PostRefundAction)
  241. {
  242. case CouponPostRefundAction.Restore:
  243. inv.CouponCode.RestoreToAvailable();
  244. break;
  245. case CouponPostRefundAction.Expire:
  246. inv.CouponCode.Expire();
  247. break;
  248. }
  249. db.MemberInventory.Remove(inv);
  250. }
  251. }
  252. else
  253. {
  254. // Fallback: OrderRefundItem 없는 옛 환불 — 미사용 코드 모두 회수
  255. foreach (var item in order.Items)
  256. {
  257. if (item.Product is null)
  258. {
  259. continue;
  260. }
  261. if (item.Product.Type == ProductType.Physical)
  262. {
  263. item.Product.RestoreStock(item.Quantity);
  264. }
  265. else if (item.Product.Type == ProductType.Digital)
  266. {
  267. var memberInventories = await db.MemberInventory
  268. .Include(m => m.CouponCode)
  269. .Where(m => m.OrderItemID == item.ID)
  270. .ToListAsync(ct);
  271. foreach (var inv in memberInventories)
  272. {
  273. if (inv.CouponCode is null)
  274. {
  275. continue;
  276. }
  277. if (inv.CouponCode.Status == CouponCodeStatus.Used)
  278. {
  279. continue;
  280. }
  281. inv.CouponCode.RestoreToAvailable();
  282. db.MemberInventory.Remove(inv);
  283. }
  284. }
  285. }
  286. }
  287. // 9. Physical 상품 재고 복구 (OrderRefundItem 분기에서는 Physical 처리 안 함 — 쿠폰 환불은 Digital 만)
  288. // OrderRefundItem 가 있는 환불은 쿠폰 환불 전용 — Physical 상품은 fallback 분기에서 처리.
  289. // 10. Order.Status 갱신
  290. switch (refund.Type)
  291. {
  292. case RefundType.Cancel:
  293. if (order.Status is OrderStatus.Pending or OrderStatus.Paid)
  294. {
  295. order.Cancel(refund.Reason);
  296. }
  297. else
  298. {
  299. order.MarkRefunded(refund.Reason);
  300. }
  301. break;
  302. case RefundType.Refund:
  303. case RefundType.Return:
  304. order.MarkRefunded(refund.Reason);
  305. break;
  306. case RefundType.Exchange:
  307. order.MarkExchanged();
  308. break;
  309. }
  310. refund.Complete();
  311. await db.SaveChangesAsync(ct);
  312. return Result.Success();
  313. }
  314. }