Handler.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using Application.Abstractions.Data;
  2. using Application.Abstractions.Messaging;
  3. using Domain.Entities.Donations;
  4. using Domain.Entities.Donations.ValueObject;
  5. using Microsoft.EntityFrameworkCore;
  6. using SharedKernel.Results;
  7. namespace Application.Features.Api.ChannelTitle.CreateChannelTitle;
  8. internal sealed class Handler(IAppDbContext db) : ICommandHandler<Command, Result<int>>
  9. {
  10. public async Task<Result<int>> Handle(Command request, CancellationToken ct)
  11. {
  12. var channel = await db.Channel.FirstOrDefaultAsync(c => c.ID == request.ChannelID, ct);
  13. if (channel is null)
  14. {
  15. return Result.Failure<int>(Error.NotFound("ChannelTitle.ChannelNotFound", "채널을 찾을 수 없습니다."));
  16. }
  17. if (channel.MemberID != request.MemberID)
  18. {
  19. return Result.Failure<int>(Error.Forbidden("ChannelTitle.Forbidden", "본인 채널만 수정할 수 있습니다."));
  20. }
  21. var count = await db.ChannelTitle.CountAsync(t => t.ChannelID == request.ChannelID, ct);
  22. if (count >= DonationConstants.Title.MaxTitlesPerChannel)
  23. {
  24. return Result.Failure<int>(Error.Problem("ChannelTitle.TooMany", $"칭호는 최대 {DonationConstants.Title.MaxTitlesPerChannel}개까지 등록할 수 있습니다."));
  25. }
  26. if (string.IsNullOrWhiteSpace(request.Name))
  27. {
  28. return Result.Failure<int>(Error.Problem("ChannelTitle.NameRequired", "칭호 이름을 입력해 주세요."));
  29. }
  30. if (request.Name.Length > 20)
  31. {
  32. return Result.Failure<int>(Error.Problem("ChannelTitle.NameTooLong", "칭호 이름은 20자 이내여야 합니다."));
  33. }
  34. if (request.MinAmount < 0)
  35. {
  36. return Result.Failure<int>(Error.Problem("ChannelTitle.InvalidAmount", "최소 금액은 0원 이상이어야 합니다."));
  37. }
  38. var duplicateAmount = await db.ChannelTitle.AnyAsync(t => t.ChannelID == request.ChannelID && t.MinAmount == request.MinAmount, ct);
  39. if (duplicateAmount)
  40. {
  41. return Result.Failure<int>(Error.Conflict("ChannelTitle.DuplicateAmount", "같은 최소 금액의 칭호가 이미 존재합니다."));
  42. }
  43. var entity = Domain.Entities.Donations.ChannelTitle.Create(request.ChannelID, request.Name, request.MinAmount, request.Color);
  44. entity.Update(request.Name, request.Description, request.MinAmount, request.Color, request.IconUrl, true);
  45. entity.SetOrder(count);
  46. await db.ChannelTitle.AddAsync(entity, ct);
  47. await db.SaveChangesAsync(ct);
  48. return Result.Success(entity.ID);
  49. }
  50. }