diff --git a/app/jobs/cron/purge_old_email_event_job.rb b/app/jobs/cron/purge_old_email_event_job.rb new file mode 100644 index 000000000..b748a0fea --- /dev/null +++ b/app/jobs/cron/purge_old_email_event_job.rb @@ -0,0 +1,7 @@ +class Cron::PurgeOldEmailEventJob < Cron::CronJob + self.schedule_expression = "every week at 3:00" + + def perform + EmailEvent.outdated.destroy_all + end +end diff --git a/app/models/email_event.rb b/app/models/email_event.rb index 429d2515c..68e80401e 100644 --- a/app/models/email_event.rb +++ b/app/models/email_event.rb @@ -13,14 +13,18 @@ # message_id :string # class EmailEvent < ApplicationRecord + RETENTION_DURATION = 1.month + enum status: { dispatched: 'dispatched', dispatch_error: 'dispatch_error' } + scope :dolist, -> { dolist_smtp.or(dolist_api) } scope :dolist_smtp, -> { where(method: 'dolist_smtp') } scope :dolist_api, -> { where(method: 'dolist_api') } scope :sendinblue, -> { where(method: 'sendinblue') } + scope :outdated, -> { where("created_at < ?", RETENTION_DURATION.ago) } class << self def create_from_message!(message, status:) diff --git a/spec/jobs/cron/purge_old_email_event_job_spec.rb b/spec/jobs/cron/purge_old_email_event_job_spec.rb new file mode 100644 index 000000000..79061de3b --- /dev/null +++ b/spec/jobs/cron/purge_old_email_event_job_spec.rb @@ -0,0 +1,14 @@ +RSpec.describe Cron::PurgeOldEmailEventJob, type: :job do + describe 'perform' do + subject { Cron::PurgeOldEmailEventJob.perform_now } + let(:older_than_retention_duration) { create(:email_event, :dolist, created_at: Time.zone.now.utc - (EmailEvent::RETENTION_DURATION + 1.day)) } + let(:more_recent_than_retention_duraiton) { create(:email_event, :dolist, created_at: Time.zone.now.utc - (EmailEvent::RETENTION_DURATION - 1.day)) } + before do + older_than_retention_duration + more_recent_than_retention_duraiton + end + + it { expect { subject }.to change { EmailEvent.count }.by(-1) } + it { expect { subject }.to change { EmailEvent.exists?(id: older_than_retention_duration.id) }.from(true).to(false) } + end +end