Handler.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using Application.Abstractions.Data;
  2. using Application.Abstractions.Messaging;
  3. using Domain.Entities.Donations;
  4. using Microsoft.EntityFrameworkCore;
  5. using SharedKernel.Results;
  6. namespace Application.Features.Api.ChannelTitle.SelectMyTitle;
  7. internal sealed class Handler(IAppDbContext db) : ICommandHandler<Command, Result>
  8. {
  9. public async Task<Result> Handle(Command request, CancellationToken ct)
  10. {
  11. if (request.TitleID.HasValue)
  12. {
  13. var title = await db.ChannelTitle.FirstOrDefaultAsync(t => t.ID == request.TitleID.Value, ct);
  14. if (title is null || title.ChannelID != request.ChannelID)
  15. {
  16. return Result.Failure(Error.NotFound("ChannelTitle.NotFound", "칭호를 찾을 수 없습니다."));
  17. }
  18. if (!title.IsActive)
  19. {
  20. return Result.Failure(Error.Problem("ChannelTitle.Inactive", "비활성화된 칭호는 선택할 수 없습니다."));
  21. }
  22. var stats = await db.DonorChannelStats.AsNoTracking()
  23. .FirstOrDefaultAsync(s => s.DonorMemberID == request.MemberID && s.ChannelID == request.ChannelID, ct);
  24. if (stats is null || stats.CumulativeAmount < title.MinAmount)
  25. {
  26. return Result.Failure(Error.Forbidden("ChannelTitle.NotAcquired", "아직 획득하지 못한 칭호입니다."));
  27. }
  28. }
  29. var selection = await db.DonorTitleSelection
  30. .FirstOrDefaultAsync(s => s.DonorMemberID == request.MemberID && s.ChannelID == request.ChannelID, ct);
  31. if (selection is null)
  32. {
  33. selection = DonorTitleSelection.Create(request.MemberID, request.ChannelID, request.TitleID);
  34. await db.DonorTitleSelection.AddAsync(selection, ct);
  35. }
  36. else
  37. {
  38. selection.Update(request.TitleID);
  39. }
  40. await db.SaveChangesAsync(ct);
  41. return Result.Success();
  42. }
  43. }