diff --git a/app/jobs/clock/subscriptions_to_be_terminated_job.rb b/app/jobs/clock/subscriptions_to_be_terminated_job.rb index 11c54808ae9..0b65ae2ea6b 100644 --- a/app/jobs/clock/subscriptions_to_be_terminated_job.rb +++ b/app/jobs/clock/subscriptions_to_be_terminated_job.rb @@ -12,7 +12,7 @@ def perform .active .where( 'DATE(subscriptions.ending_at::timestamptz) IN (?)', - [(Time.current + 45.days).to_date, (Time.current + 15.days).to_date], + sent_at_dates, ) .where('webhooks.id IS NULL OR webhooks.created_at::date != ?', Time.current.to_date) .find_each do |subscription| @@ -21,5 +21,16 @@ def perform end end end + + private + + def sent_at_dates + # NOTE: The alert will be sent 15 and 45 days before the subscription is terminated by default. + # You can override the default by setting below env var. + # E.g. LAGO_SUBSCRIPTION_TERMINATION_ALERT_SENT_AT_DAYS=1,15,45 will cause it + # to be sent at 1, 15, 45 days before subscription terminates, respectively. + sent_at_days_config = ENV.fetch('LAGO_SUBSCRIPTION_TERMINATION_ALERT_SENT_AT_DAYS', '15,45') + sent_at_days_config.split(',').map { |day_string| Time.current + day_string.to_i.days }.map(&:to_date) + end end end diff --git a/spec/jobs/clock/subscriptions_to_be_terminated_job_spec.rb b/spec/jobs/clock/subscriptions_to_be_terminated_job_spec.rb index 87206547b53..e783f696ecc 100644 --- a/spec/jobs/clock/subscriptions_to_be_terminated_job_spec.rb +++ b/spec/jobs/clock/subscriptions_to_be_terminated_job_spec.rb @@ -57,6 +57,24 @@ end end + context 'when current date is 1 day before subscription ending_at' do + it 'sends webhook that subscription is going to be terminated but only if config is overridden' do + current_date = ending_at - 1.days + + travel_to(current_date) do + # First validate that with default config nothing is sent + expect { described_class.perform_now }.not_to have_enqueued_job(SendWebhookJob) + + # Now validate that with custom config, it is actually sent + stub_const('ENV', 'LAGO_SUBSCRIPTION_TERMINATION_ALERT_SENT_AT_DAYS' => '1,15,45') + expect { described_class.perform_now} + .to have_enqueued_job(SendWebhookJob) + .with('subscription.termination_alert', Subscription) + .exactly(:once) + end + end + end + context 'when the same alert webhook had been already triggered on the same day' do let(:webhook_alert1) do create(