diff --git a/app/controllers/billing_controller.rb b/app/controllers/billing_controller.rb index bf2879bb..ba5e2cc1 100644 --- a/app/controllers/billing_controller.rb +++ b/app/controllers/billing_controller.rb @@ -123,17 +123,18 @@ class BillingController < ApplicationController TenantMailer.subscription_confirmation(tenant: Current.tenant).deliver_later end elsif event['type'] == 'customer.subscription.updated' + # This event is triggered when: + # (1) A subscription is canceled OR a subscription is reactivated after being canceled + # (2) A subscription is updated (e.g. switching from monthly to yearly plan or vice versa) + # (3) A subscription is automatically renewed at the end of the billing period (e.g. every month for a monthly subscription) + # Since it is difficult to distinguish between these cases, we only update the status if the subscription is active or canceled + # and we do not send any emails notifications. + Current.tenant = get_tenant_from_customer_id(event.data.object.customer) if Current.tenant.tenant_billing.status == 'active' || Current.tenant.tenant_billing.status == 'canceled' has_canceled = event.data.object.cancel_at_period_end Current.tenant.tenant_billing.update!(status: has_canceled ? 'canceled' : 'active') - - if has_canceled - TenantMailer.cancellation_confirmation(tenant: Current.tenant).deliver_later - else - TenantMailer.renewal_confirmation(tenant: Current.tenant).deliver_later - end end end diff --git a/lib/tasks/notify_tenants_trial_period.rake b/lib/tasks/notify_tenants_trial_period.rake index 79725e4c..ef6dd072 100644 --- a/lib/tasks/notify_tenants_trial_period.rake +++ b/lib/tasks/notify_tenants_trial_period.rake @@ -8,7 +8,20 @@ def get_tenants_to_notify(period) trial_ends_at: date_to_check.beginning_of_day..date_to_check.end_of_day, status: 'trial' ) - Tenant.where(id: tbs.map(&:tenant_id)) + tenants_to_notify = Tenant.where(id: tbs.map(&:tenant_id)) + + # If notifying for "mid" trial period, check whether tenant has not been granted an extension of the trial period + # An extended trial period usually means that the tenant contacted me personally, so there is no need to send + # a "mid" trial period notification (which could also be sent multiple times in the case of an extension) + # So we filter out tenants whose trial_ends_at is not 7 days after the tenant created at date + if period == "mid" + tenants_to_notify = tenants_to_notify.select do |tenant| + tenant_billing = TenantBilling.unscoped.find_by(tenant_id: tenant.id) + tenant_billing.trial_ends_at.to_date == tenant.created_at.to_date + 7.days + end + end + + tenants_to_notify end task notify_tenants_trial_period: [:environment] do