Handler.cs 1.3 KB

1234567891011121314151617181920212223242526272829
  1. using Application.Abstractions.Data;
  2. using Application.Abstractions.Messaging;
  3. using Microsoft.EntityFrameworkCore;
  4. namespace Application.Features.Api.DonationGoal.GetProgress;
  5. internal sealed class Handler(IAppDbContext db) : IQueryHandler<Query, Response>
  6. {
  7. public async Task<Response> Handle(Query request, CancellationToken ct)
  8. {
  9. var goal = await db.DonationGoalConfig.AsNoTracking().FirstOrDefaultAsync(g => g.ID == request.GoalConfigID && g.ChannelID == request.ChannelID && g.IsActive, ct);
  10. if (goal is null)
  11. {
  12. throw new KeyNotFoundException("목표 설정을 찾을 수 없습니다.");
  13. }
  14. var currentAmount = await db.Donation.AsNoTracking()
  15. .Where(d => d.ChannelID == request.ChannelID
  16. && !d.IsTest
  17. && (goal.StartAt == null || d.CreatedAt >= goal.StartAt)
  18. && (goal.EndAt == null || d.CreatedAt <= goal.EndAt))
  19. .SumAsync(d => d.Amount, ct);
  20. var adjusted = currentAmount + goal.StartAmount;
  21. var percent = goal.TargetAmount > 0 ? Math.Min((decimal)adjusted / goal.TargetAmount * 100, 100) : 0;
  22. return new Response(goal.ID, goal.Title, goal.StartAmount, goal.TargetAmount, adjusted, Math.Round(percent, 1));
  23. }
  24. }