summaryrefslogtreecommitdiff
path: root/lib/solidus_subscriptions/checkout.rb
blob: 7bed82359739995597680b7d6a7344283aea3729 (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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# frozen_string_literal: true

module SolidusSubscriptions
  class Checkout
    attr_reader :installment

    def initialize(installment)
      @installment = installment
    end

    def process
      order = create_order

      begin
        populate_order(order)
        finalize_order(order)

        SolidusSubscriptions.configuration.success_dispatcher_class.new(installment, order).dispatch
      rescue StateMachines::InvalidTransition
        if order.payments.any?(&:failed?)
          SolidusSubscriptions.configuration.payment_failed_dispatcher_class.new(installment, order).dispatch
        else
          SolidusSubscriptions.configuration.failure_dispatcher_class.new(installment, order).dispatch
        end
      rescue ::Spree::Order::InsufficientStock
        SolidusSubscriptions.configuration.out_of_stock_dispatcher_class.new(installment, order).dispatch
      end

      order
    end

    private

    def create_order
      SolidusSubscriptions.configuration.order_creator_class.new(installment).call
    end

    def populate_order(order)
      installment.subscription.line_items.each do |line_item|
        order.contents.add(line_item.subscribable, line_item.quantity)
      end
    end

    def finalize_order(order)
      ::Spree::PromotionHandler::Cart.new(order).activate
      order.recalculate

      order.checkout_steps[0...-1].each do
        case order.state
        when 'address'
          order.ship_address = installment.subscription.shipping_address_to_use
          order.bill_address = installment.subscription.billing_address_to_use
        when 'payment'
          order.payments.create(
            payment_method: installment.subscription.payment_method_to_use,
            source: installment.subscription.payment_source_to_use,
            amount: order.total
          )
        end

        order.next!
      end

      order.complete!
    end
  end
end