using Application.Abstractions.Data; using Application.Abstractions.Messaging; using Microsoft.EntityFrameworkCore; namespace Application.Features.Api.Stocks.GetEsgIndices; /// /// ESG 지수 목록 — 지정일(미지정 시 최신 TradeDate) 행을 지수명순으로 페이징 (KRX ESG 지수 수집, 익명). /// internal sealed class Handler(IAppDbContext db) : IQueryHandler { private const ushort MaxPerPage = 100; public async Task Handle(Query request, CancellationToken ct) { var page = request.Page < 1 ? 1 : request.Page; var perPage = request.PerPage is 0 or > MaxPerPage ? (ushort)20 : request.PerPage; var targetDate = request.Date; if (targetDate is null) { targetDate = await db.EsgIndexDailyPrice.AsNoTracking() .OrderByDescending(c => c.TradeDate) .Select(c => (DateOnly?)c.TradeDate) .FirstOrDefaultAsync(ct); } if (targetDate is null) { return new Response { Total = 0, TradeDate = null, List = [] }; } var query = db.EsgIndexDailyPrice.AsNoTracking().Where(c => c.TradeDate == targetDate.Value); var total = await query.CountAsync(ct); var list = await query .OrderBy(c => c.IndexName) .Skip((page - 1) * perPage) .Take(perPage) .Select(c => new Response.Row { Name = c.IndexName, Close = c.Close, ChangeVal = c.ChangeVal, FlucRateBp = c.FlucRateBp, ConstituentCount = c.ConstituentCount, Volume = c.Volume, Value = c.Value }) .ToListAsync(ct); return new Response { Total = total, TradeDate = targetDate.Value, List = list }; } }