Handler.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using Application.Abstractions.Data;
  2. using Application.Abstractions.Messaging;
  3. using Microsoft.EntityFrameworkCore;
  4. using SharedKernel.Results;
  5. namespace Application.Features.Api.Stocks.GetForeignCustody;
  6. internal sealed class Handler(IAppDbContext db) : IQueryHandler<Query, Result<Response>>
  7. {
  8. public async Task<Result<Response>> Handle(Query request, CancellationToken ct)
  9. {
  10. var query = db.ForeignCustodyNation.AsNoTracking();
  11. var nation = request.Nation?.Trim();
  12. if (!string.IsNullOrEmpty(nation))
  13. {
  14. query = query.Where(c => c.NationCd == nation);
  15. }
  16. var secnTpcd = request.SecnTpcd?.Trim();
  17. var filterBySecnTpcd = !string.IsNullOrEmpty(secnTpcd);
  18. if (filterBySecnTpcd)
  19. {
  20. query = query.Where(c => c.SecnTpcd == secnTpcd);
  21. }
  22. if (request.From.HasValue)
  23. {
  24. query = query.Where(c => c.StdDt >= request.From.Value);
  25. }
  26. if (request.To.HasValue)
  27. {
  28. query = query.Where(c => c.StdDt <= request.To.Value);
  29. }
  30. var rows = await query
  31. .Select(c => new
  32. {
  33. c.NationCd,
  34. c.SecnTpcd,
  35. c.StdDt,
  36. c.FrsecCusAmt
  37. })
  38. .ToListAsync(ct);
  39. List<Response.Series> series;
  40. if (filterBySecnTpcd)
  41. {
  42. // 종목구분 지정 → 국가×종목구분별 시계열 (개별 유지)
  43. series = rows
  44. .GroupBy(c => new { c.NationCd, c.SecnTpcd })
  45. .Select(g => new Response.Series
  46. {
  47. NationCd = g.Key.NationCd,
  48. SecnTpcd = g.Key.SecnTpcd,
  49. Points = g
  50. .OrderBy(c => c.StdDt)
  51. .Select(c => new Response.Point { StdDt = c.StdDt, CustodyAmount = c.FrsecCusAmt ?? 0m })
  52. .ToList()
  53. })
  54. .OrderBy(c => c.NationCd)
  55. .ToList();
  56. }
  57. else
  58. {
  59. // 미지정 → 국가별로 같은 기준일의 종목구분 금액을 합산
  60. series = rows
  61. .GroupBy(c => c.NationCd)
  62. .Select(g => new Response.Series
  63. {
  64. NationCd = g.Key,
  65. SecnTpcd = null,
  66. Points = g
  67. .GroupBy(c => c.StdDt)
  68. .OrderBy(p => p.Key)
  69. .Select(p => new Response.Point { StdDt = p.Key, CustodyAmount = p.Sum(c => c.FrsecCusAmt ?? 0m) })
  70. .ToList()
  71. })
  72. .OrderBy(c => c.NationCd)
  73. .ToList();
  74. }
  75. return new Response { Nations = series };
  76. }
  77. }