Handler.cs 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. using Application.Abstractions.Data;
  2. using Application.Abstractions.Messaging;
  3. using Application.Abstractions.Notification;
  4. using Domain.Entities.Notifications.ValueObject;
  5. using Microsoft.EntityFrameworkCore;
  6. using SharedKernel.Results;
  7. namespace Application.Features.Api.Note.SendNote;
  8. internal sealed class Handler(
  9. IAppDbContext db,
  10. INotificationService notification
  11. ) : ICommandHandler<Command, Result<Response>>
  12. {
  13. public async Task<Result<Response>> Handle(Command r, CancellationToken ct)
  14. {
  15. if (string.IsNullOrWhiteSpace(r.Title) || string.IsNullOrWhiteSpace(r.Content))
  16. {
  17. return Result.Failure<Response>(Error.Problem("Note.TitleContentRequired", "제목과 내용을 입력해주세요."));
  18. }
  19. // 시스템 발송이 아닌 일반 발송은 자기 자신에게 보낼 수 없음
  20. if (!r.IsSystem && r.SenderMemberID == r.ReceiverMemberID)
  21. {
  22. return Result.Failure<Response>(Error.Problem("Note.SelfSendNotAllowed", "자신에게 쪽지를 보낼 수 없습니다."));
  23. }
  24. // 일일 발송 제한 (시스템 쪽지 제외)
  25. if (!r.IsSystem)
  26. {
  27. var dailyLimit = await db.Config.AsNoTracking()
  28. .OrderByDescending(c => c.ID)
  29. .Select(c => c.Basic.NoteDailySendLimit)
  30. .FirstOrDefaultAsync(ct);
  31. if (dailyLimit <= 0)
  32. {
  33. return Result.Failure<Response>(Error.Problem("Note.SendDisabled", "현재 쪽지 발송이 차단되어 있습니다."));
  34. }
  35. var todayUtc = DateTime.UtcNow.Date;
  36. var sentToday = await db.Note.AsNoTracking()
  37. .CountAsync(n => n.SenderMemberID == r.SenderMemberID && !n.IsSystem && n.CreatedAt >= todayUtc, ct);
  38. if (sentToday >= dailyLimit)
  39. {
  40. return Result.Failure<Response>(Error.Problem("Note.DailyLimitExceeded", $"하루 최대 {dailyLimit}건까지 발송할 수 있습니다."));
  41. }
  42. }
  43. // 수신자 유효성 (탈퇴/차단 회원에게는 발송 차단)
  44. var receiverValid = await db.Member.AsNoTracking()
  45. .AnyAsync(m => m.ID == r.ReceiverMemberID && !m.IsWithdraw && !m.IsDenied, ct);
  46. if (!receiverValid)
  47. {
  48. return Result.Failure<Response>(Error.NotFound("Note.ReceiverNotFound", "받는 회원을 찾을 수 없습니다."));
  49. }
  50. var note = r.IsSystem
  51. ? Domain.Entities.Notes.Note.CreateSystem(r.ReceiverMemberID, r.Title, r.Content, r.RelatedType, r.RelatedID)
  52. : Domain.Entities.Notes.Note.Create(r.SenderMemberID, r.ReceiverMemberID, r.Title, r.Content, false, r.RelatedType, r.RelatedID);
  53. db.Note.Add(note);
  54. await db.SaveChangesAsync(ct);
  55. // 받는 사람에게 NoteReceived 알림 (시스템 쪽지도 발송 대상에게 알림).
  56. // 표기 우선순위: 채널명 > 회원 별명. 보조 식별자(@handle / #sid) 도 노출.
  57. string senderDisplay;
  58. if (r.IsSystem)
  59. {
  60. senderDisplay = "시스템";
  61. }
  62. else
  63. {
  64. var senderInfo = await db.Member.AsNoTracking()
  65. .Where(m => m.ID == r.SenderMemberID)
  66. .Select(m => new {
  67. m.Name, m.SID,
  68. ChannelName = m.Channel != null ? m.Channel.Name : null,
  69. ChannelHandle = m.Channel != null ? m.Channel.Handle : null
  70. })
  71. .FirstOrDefaultAsync(ct);
  72. var primary = senderInfo?.ChannelName ?? senderInfo?.Name ?? "알 수 없는 회원";
  73. var secondary = !string.IsNullOrEmpty(senderInfo?.ChannelHandle)
  74. ? $"@{senderInfo.ChannelHandle}"
  75. : (!string.IsNullOrEmpty(senderInfo?.SID) ? $"#{senderInfo.SID}" : null);
  76. senderDisplay = secondary is null ? primary : $"{primary} ({secondary})";
  77. }
  78. await notification.SendAsync(
  79. r.ReceiverMemberID,
  80. NotificationType.NoteReceived,
  81. "새 쪽지가 도착했습니다",
  82. $"{senderDisplay}: {r.Title}",
  83. actionUrl: "/note/inbox",
  84. relatedType: "Note",
  85. relatedID: note.ID,
  86. ct: ct
  87. );
  88. return Result.Success(new Response(note.ID));
  89. }
  90. }