| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- using Application.Abstractions.Data;
- using Application.Abstractions.Messaging;
- using Application.Abstractions.Notification;
- using Domain.Entities.Notifications.ValueObject;
- using Microsoft.EntityFrameworkCore;
- using SharedKernel.Results;
- namespace Application.Features.Api.Note.SendNote;
- internal sealed class Handler(
- IAppDbContext db,
- INotificationService notification
- ) : ICommandHandler<Command, Result<Response>>
- {
- public async Task<Result<Response>> Handle(Command r, CancellationToken ct)
- {
- if (string.IsNullOrWhiteSpace(r.Title) || string.IsNullOrWhiteSpace(r.Content))
- {
- return Result.Failure<Response>(Error.Problem("Note.TitleContentRequired", "제목과 내용을 입력해주세요."));
- }
- // 시스템 발송이 아닌 일반 발송은 자기 자신에게 보낼 수 없음
- if (!r.IsSystem && r.SenderMemberID == r.ReceiverMemberID)
- {
- return Result.Failure<Response>(Error.Problem("Note.SelfSendNotAllowed", "자신에게 쪽지를 보낼 수 없습니다."));
- }
- // 일일 발송 제한 (시스템 쪽지 제외)
- if (!r.IsSystem)
- {
- var dailyLimit = await db.Config.AsNoTracking()
- .OrderByDescending(c => c.ID)
- .Select(c => c.Basic.NoteDailySendLimit)
- .FirstOrDefaultAsync(ct);
- if (dailyLimit <= 0)
- {
- return Result.Failure<Response>(Error.Problem("Note.SendDisabled", "현재 쪽지 발송이 차단되어 있습니다."));
- }
- var todayUtc = DateTime.UtcNow.Date;
- var sentToday = await db.Note.AsNoTracking()
- .CountAsync(n => n.SenderMemberID == r.SenderMemberID && !n.IsSystem && n.CreatedAt >= todayUtc, ct);
- if (sentToday >= dailyLimit)
- {
- return Result.Failure<Response>(Error.Problem("Note.DailyLimitExceeded", $"하루 최대 {dailyLimit}건까지 발송할 수 있습니다."));
- }
- }
- // 수신자 유효성 (탈퇴/차단 회원에게는 발송 차단)
- var receiverValid = await db.Member.AsNoTracking()
- .AnyAsync(m => m.ID == r.ReceiverMemberID && !m.IsWithdraw && !m.IsDenied, ct);
- if (!receiverValid)
- {
- return Result.Failure<Response>(Error.NotFound("Note.ReceiverNotFound", "받는 회원을 찾을 수 없습니다."));
- }
- var note = r.IsSystem
- ? Domain.Entities.Notes.Note.CreateSystem(r.ReceiverMemberID, r.Title, r.Content, r.RelatedType, r.RelatedID)
- : Domain.Entities.Notes.Note.Create(r.SenderMemberID, r.ReceiverMemberID, r.Title, r.Content, false, r.RelatedType, r.RelatedID);
- db.Note.Add(note);
- await db.SaveChangesAsync(ct);
- // 받는 사람에게 NoteReceived 알림 (시스템 쪽지도 발송 대상에게 알림).
- // 표기 우선순위: 채널명 > 회원 별명. 보조 식별자(@handle / #sid) 도 노출.
- string senderDisplay;
- if (r.IsSystem)
- {
- senderDisplay = "시스템";
- }
- else
- {
- var senderInfo = await db.Member.AsNoTracking()
- .Where(m => m.ID == r.SenderMemberID)
- .Select(m => new {
- m.Name, m.SID,
- ChannelName = m.Channel != null ? m.Channel.Name : null,
- ChannelHandle = m.Channel != null ? m.Channel.Handle : null
- })
- .FirstOrDefaultAsync(ct);
- var primary = senderInfo?.ChannelName ?? senderInfo?.Name ?? "알 수 없는 회원";
- var secondary = !string.IsNullOrEmpty(senderInfo?.ChannelHandle)
- ? $"@{senderInfo.ChannelHandle}"
- : (!string.IsNullOrEmpty(senderInfo?.SID) ? $"#{senderInfo.SID}" : null);
- senderDisplay = secondary is null ? primary : $"{primary} ({secondary})";
- }
- await notification.SendAsync(
- r.ReceiverMemberID,
- NotificationType.NoteReceived,
- "새 쪽지가 도착했습니다",
- $"{senderDisplay}: {r.Title}",
- actionUrl: "/note/inbox",
- relatedType: "Note",
- relatedID: note.ID,
- ct: ct
- );
- return Result.Success(new Response(note.ID));
- }
- }
|