Handler.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using Application.Abstractions.Data;
  2. using Application.Abstractions.Messaging;
  3. using Microsoft.EntityFrameworkCore;
  4. namespace Application.Features.Api.Stocks.GetSriBonds;
  5. /// <summary>
  6. /// 사회책임투자채권 목록 — 지정일(미지정 시 최신 TradeDate) 스냅샷을 발행금액 내림차순으로 페이징 (KRX 사회책임투자채권 수집, 익명).
  7. /// BondType(SRI_BND_TP_NM 채권종류) 지정 시 해당 종류만 필터한다.
  8. /// </summary>
  9. internal sealed class Handler(IAppDbContext db) : IQueryHandler<Query, Response>
  10. {
  11. private const ushort MaxPerPage = 100;
  12. public async Task<Response> Handle(Query request, CancellationToken ct)
  13. {
  14. var page = request.Page < 1 ? 1 : request.Page;
  15. var perPage = request.PerPage is 0 or > MaxPerPage ? (ushort)20 : request.PerPage;
  16. var targetDate = request.Date;
  17. if (targetDate is null)
  18. {
  19. targetDate = await db.SriBond.AsNoTracking()
  20. .OrderByDescending(c => c.TradeDate)
  21. .Select(c => (DateOnly?)c.TradeDate)
  22. .FirstOrDefaultAsync(ct);
  23. }
  24. if (targetDate is null)
  25. {
  26. return new Response
  27. {
  28. Total = 0,
  29. TradeDate = null,
  30. List = []
  31. };
  32. }
  33. var query = db.SriBond.AsNoTracking().Where(c => c.TradeDate == targetDate.Value);
  34. if (!string.IsNullOrWhiteSpace(request.BondType))
  35. {
  36. var bondType = request.BondType.Trim();
  37. query = query.Where(c => c.SriBondType == bondType);
  38. }
  39. var total = await query.CountAsync(ct);
  40. var list = await query
  41. .OrderByDescending(c => c.IssueAmount).ThenBy(c => c.Code)
  42. .Skip((page - 1) * perPage)
  43. .Take(perPage)
  44. .Select(c => new Response.Row
  45. {
  46. Code = c.Code,
  47. IssuerName = c.IssuerName,
  48. SriBondType = c.SriBondType,
  49. Name = c.Name,
  50. ListDate = c.ListDate,
  51. IssueDate = c.IssueDate,
  52. RedemptionDate = c.RedemptionDate,
  53. CouponRate = c.CouponRate,
  54. IssueAmount = c.IssueAmount,
  55. ListAmount = c.ListAmount,
  56. BondType = c.BondType
  57. })
  58. .ToListAsync(ct);
  59. return new Response
  60. {
  61. Total = total,
  62. TradeDate = targetDate.Value,
  63. List = list
  64. };
  65. }
  66. }