@@ -33,37 +33,24 @@ def sender
3333 delegate :url , to : :event
3434
3535 def send_email_notification?
36- recipient . email . present? && should_send_email?
36+ recipient . email . present? && recipient . notification_preferences [ 'notify_by_email' ] && should_send_email?
3737 end
3838
39- # rubocop:todo Metrics/MethodLength
40- def should_send_email? # rubocop:todo Metrics/AbcSize, Metrics/MethodLength
41- # Find the events related to the conversation
42- related_event_ids = BetterTogether ::NewMessageNotifier . where ( params : { conversation_id : conversation . id } )
43- . pluck ( :id )
39+ def should_send_email?
40+ # Check for unread notifications for the recipient for the record's conversation
41+ unread_notifications = recipient . notifications . where (
42+ event_id : BetterTogether ::NewMessageNotifier . where ( params : { conversation_id : conversation . id } ) . select ( :id ) ,
43+ read_at : nil
44+ ) . order ( created_at : :desc )
4445
45- # Check for unread notifications for the recipient related to these events
46- unread_notifications = recipient . notifications
47- . where ( event_id : related_event_ids , read_at : nil )
48-
49- if unread_notifications . empty? || ( unread_notifications . last . created_at <= 1 . day . ago )
50- # No unread recent notifications, send the email
51- true
46+ if unread_notifications . none?
47+ # If the recipient has read their notifications, do not send
48+ false
5249 else
53- # Optional: Implement a time-based delay or other conditions
54- last_email_sent_at = recipient . notifications
55- . where ( event_id : related_event_ids )
56- . order ( created_at : :desc )
57- . pluck ( :created_at )
58- . first
59-
60- return true if last_email_sent_at . blank? # Send if no previous email sent
61-
62- # Send email only if more than 30 minutes have passed since the last one
63- last_email_sent_at < 30 . minutes . ago
50+ # Only send one email per unread notifications per conversation
51+ message . id == unread_notifications . last . event . record_id
6452 end
6553 end
66- # rubocop:enable Metrics/MethodLength
6754 end
6855
6956 def identifier
0 commit comments