Handler.cs 15 KB

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