| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- using Application.Abstractions.Data;
- using Application.Abstractions.Messaging;
- using Domain.Entities.Donations;
- using Domain.Entities.Donations.ValueObject;
- using Microsoft.EntityFrameworkCore;
- using SharedKernel.Results;
- namespace Application.Features.Api.ChannelTitle.CreateChannelTitle;
- internal sealed class Handler(IAppDbContext db) : ICommandHandler<Command, Result<int>>
- {
- public async Task<Result<int>> Handle(Command request, CancellationToken ct)
- {
- var channel = await db.Channel.FirstOrDefaultAsync(c => c.ID == request.ChannelID, ct);
- if (channel is null)
- {
- return Result.Failure<int>(Error.NotFound("ChannelTitle.ChannelNotFound", "채널을 찾을 수 없습니다."));
- }
- if (channel.MemberID != request.MemberID)
- {
- return Result.Failure<int>(Error.Forbidden("ChannelTitle.Forbidden", "본인 채널만 수정할 수 있습니다."));
- }
- var count = await db.ChannelTitle.CountAsync(t => t.ChannelID == request.ChannelID, ct);
- if (count >= DonationConstants.Title.MaxTitlesPerChannel)
- {
- return Result.Failure<int>(Error.Problem("ChannelTitle.TooMany", $"칭호는 최대 {DonationConstants.Title.MaxTitlesPerChannel}개까지 등록할 수 있습니다."));
- }
- if (string.IsNullOrWhiteSpace(request.Name))
- {
- return Result.Failure<int>(Error.Problem("ChannelTitle.NameRequired", "칭호 이름을 입력해 주세요."));
- }
- if (request.Name.Length > 20)
- {
- return Result.Failure<int>(Error.Problem("ChannelTitle.NameTooLong", "칭호 이름은 20자 이내여야 합니다."));
- }
- if (request.MinAmount < 0)
- {
- return Result.Failure<int>(Error.Problem("ChannelTitle.InvalidAmount", "최소 금액은 0원 이상이어야 합니다."));
- }
- var duplicateAmount = await db.ChannelTitle.AnyAsync(t => t.ChannelID == request.ChannelID && t.MinAmount == request.MinAmount, ct);
- if (duplicateAmount)
- {
- return Result.Failure<int>(Error.Conflict("ChannelTitle.DuplicateAmount", "같은 최소 금액의 칭호가 이미 존재합니다."));
- }
- var entity = Domain.Entities.Donations.ChannelTitle.Create(request.ChannelID, request.Name, request.MinAmount, request.Color);
- entity.Update(request.Name, request.Description, request.MinAmount, request.Color, request.IconUrl, true);
- entity.SetOrder(count);
- await db.ChannelTitle.AddAsync(entity, ct);
- await db.SaveChangesAsync(ct);
- return Result.Success(entity.ID);
- }
- }
|