diff --git a/app/mailers/mailer.rb b/app/mailers/mailer.rb index ad87359af..25c019857 100644 --- a/app/mailers/mailer.rb +++ b/app/mailers/mailer.rb @@ -60,8 +60,8 @@ class Mailer < ApplicationMailer end end - def proposal_notification_digest(user) - @notifications = user.notifications.where(notifiable_type: "ProposalNotification") + def proposal_notification_digest(user, notifications) + @notifications = notifications with_user(user) do mail(to: user.email, subject: t('mailers.proposal_notification_digest.title', org_name: Setting['org_name'])) diff --git a/app/models/notification.rb b/app/models/notification.rb index 9695c1b01..c6c32eb8d 100644 --- a/app/models/notification.rb +++ b/app/models/notification.rb @@ -2,9 +2,11 @@ class Notification < ActiveRecord::Base belongs_to :user, counter_cache: true belongs_to :notifiable, polymorphic: true - scope :unread, -> { all } - scope :recent, -> { order(id: :desc) } - scope :for_render, -> { includes(:notifiable) } + scope :unread, -> { all } + scope :recent, -> { order(id: :desc) } + scope :not_emailed, -> { where(emailed_at: nil) } + scope :for_render, -> { includes(:notifiable) } + def timestamp notifiable.created_at diff --git a/lib/email_digest.rb b/lib/email_digest.rb index 90838f78f..0b4d796db 100644 --- a/lib/email_digest.rb +++ b/lib/email_digest.rb @@ -1,13 +1,22 @@ class EmailDigest - def initialize + attr_accessor :user, :notifications + + def initialize(user) + @user = user end - def create - User.email_digest.each do |user| - if user.notifications.where(notifiable_type: "ProposalNotification").any? - Mailer.proposal_notification_digest(user).deliver_later - end + def notifications + user.notifications.not_emailed.where(notifiable_type: "ProposalNotification").to_a + end + + def pending_notifications? + notifications.any? + end + + def deliver + if pending_notifications? + Mailer.proposal_notification_digest(user, notifications).deliver_later end end diff --git a/lib/tasks/emails.rake b/lib/tasks/emails.rake index 6670264a5..7c76b20c8 100644 --- a/lib/tasks/emails.rake +++ b/lib/tasks/emails.rake @@ -2,8 +2,10 @@ namespace :emails do desc "Sends email digest of proposal notifications to each user" task digest: :environment do - email_digest = EmailDigest.new - email_digest.create + User.email_digest.find_each do |user| + email_digest = EmailDigest.new(user) + email_digest.deliver + end end end