summaryrefslogtreecommitdiff
path: root/lib/solidus_subscriptions/processor.rb
blob: b5aaa707f2c0caf9b835c7a25ecf49cd50350d6d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# frozen_string_literal: true

module SolidusSubscriptions
  class Processor
    class << self
      def run
        SolidusSubscriptions::Subscription.actionable.find_each(&method(:process_subscription))
        SolidusSubscriptions::Installment.actionable.with_active_subscription.find_each(&method(:process_installment))
      end

      private

      def process_subscription(subscription)
        ActiveRecord::Base.transaction do
          subscription.successive_skip_count = 0
          subscription.advance_actionable_date

          subscription.cancel! if subscription.pending_cancellation?
          subscription.deactivate! if subscription.can_be_deactivated?

          if SolidusSubscriptions.configuration.clear_past_installments
            subscription.installments.unfulfilled.actionable.each do |installment|
              installment.update!(actionable_date: nil)
            end
          end

          subscription.installments.create!(actionable_date: Time.zone.now)
        end
      end

      def process_installment(installment)
        ProcessInstallmentJob.perform_later(installment)
      end
    end
  end
end