Class: Payment::OrderProcessor

Inherits:
BaseService show all
Defined in:
app/services/payment/order_processor.rb

Overview

Splits an incoming payment across the Order's Deliverys and runs
one gateway authorization per delivery. Coordinates Stripe vault
creation, multicapture upgrades, and immediate capture for custom
products. Used by both CRM and storefront payment flows.

Defined Under Namespace

Classes: Result

Instance Attribute Summary

Attributes inherited from BaseService

#options

Instance Method Summary collapse

Methods inherited from BaseService

#log_debug, #log_error, #log_info, #log_warning, #logger, #tagged_logger

Constructor Details

#initialize(order, payment_params = nil, current_account = nil, request = nil, is_www = false, excluding_payment: nil) ⇒ OrderProcessor

Returns a new instance of OrderProcessor.



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'app/services/payment/order_processor.rb', line 14

def initialize(order, payment_params = nil,  = nil, request = nil, is_www = false, excluding_payment: nil)
  @payment_params = payment_params
  @order = order
  @order.is_www ||= is_www
  @current_account = 
  @excluding_payment = excluding_payment
  @request = request
  return if @payment_params.blank?

  @payment_params.symbolize_keys! if @payment_params.is_a? Hash
  return unless is_www

  # Use symbol keys so they line up with the symbolized reads in
  # `process` (`@payment_params[:amount]`, etc.). Writing string keys
  # here after `symbolize_keys!` would create stale duplicates and let
  # the order's true balance get shadowed by whatever was passed in.
  @payment_params[:amount] = @order.balance # We force to pay the total of the balance, if the payment is online
  @payment_params[:currency] = @order.currency
  @payment_params[:email] ||= @current_account.try(:email)
  @payment_params[:remote_ip_address] = @request.remote_ip
  @payment_params[:http_user_agent] = @request.env['HTTP_USER_AGENT']
  @payment_params[:http_accept_language] = @request.env['HTTP_ACCEPT_LANGUAGE']
  @payment_params[:account_id] ||= @current_account&.id
end

Instance Method Details

#processPayment::OrderProcessor::Result

Walk every Delivery on the order, build and authorize a Payment
against each one for the share of the available funds it needs, then
capture immediately for any deliveries containing custom products.
Handles vault creation for storefront card_token flows and
opportunistically upgrades the first authorization to a Stripe
multicapture PI when the gateway supports it and additional
deliveries remain.



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'app/services/payment/order_processor.rb', line 48

def process
  amount_available = BigDecimal(@payment_params[:amount])
  success = nil
  balance_paid = false
  notice = ''
  error = ''
  error_codes = ''
  all_payments = []

  if (@payment_params[:category] == Payment::CREDIT_CARD) && @payment_params && @payment_params[:card_token].present?
    if @payment_params[:card_token].start_with?('pi_')
      # PaymentIntent confirmed client-side -- skip vault creation.
      # The gateway's verify_confirmed_payment_intent will handle the rest.
    else
      has_consent = @payment_params[:store_card].to_b
      if has_consent
        hidden = false
        description = @payment_params[:store_card_name]
      else
        hidden = true
        description = nil
      end
      cc_vault = @order.customer.credit_card_vaults.new(
        card_token: @payment_params[:card_token],
        description: description,
        hidden: hidden,
        issuer_number: @payment_params[:issuer_number]
      )
      if has_consent
        cc_vault.consent_given_at = Time.current
        cc_vault.consent_channel = @payment_params[:consent_channel] || 'crm_phone'
      end
      res = cc_vault.store_card(@payment_params[:email])
      if res == false
        success = false
        balance_paid = false
        all_payments = []
        error = "Error processing card: #{cc_vault.errors_to_s}"
      end
      @payment_params[:vault_id] = cc_vault.vault_id
    end
  end

  deliveries_needing_payment = @order.deliveries.select { |d| delivery_balance_for(d).positive? }
  is_credit_card = @payment_params[:category] == Payment::CREDIT_CARD
  multicapture_pi = nil

  deliveries_needing_payment.each_with_index do |delivery, idx|
    if (success == false) || amount_available.zero?
      balance_paid = order_balance_after_replacement.zero?
      break
    end

    amount_to_auth = [delivery_balance_for(delivery), amount_available].min
    @payment_params[:amount] = amount_to_auth
    @payment = @order.payments.build(@payment_params)
    @payment.delivery = delivery

    if @payment.valid?
      @payment.save!

      res = if multicapture_pi
              @payment.gateway_class.new(@payment).register_shared_authorization(
                multicapture_pi, amount_cents: (amount_to_auth * 100).to_i
              )
            else
              @payment.gateway_class.new(@payment, delivery).authorize
            end

      balance_paid = order_balance_after_replacement.zero?
      if res.success
        success = true
        amount_available -= amount_to_auth

        if multicapture_pi.nil? && is_credit_card && idx == 0 && @payment.supports_multicapture?
          remaining_deliveries = deliveries_needing_payment[1..]
          # Cap the multicapture upgrade at the *total* remaining customer
          # funds, not at `amount_available` per delivery. The prior form
          # `sum { |d| [d.balance, amount_available].min }` re-used
          # `amount_available` for every iteration, so 2+ remaining
          # deliveries each saw the full residual and the sum could
          # exceed what the customer had actually authorised.
          remaining_balance_total = remaining_deliveries.sum(BigDecimal('0')) { |d| delivery_balance_for(d) }
          remaining_amount = [remaining_balance_total, amount_available].min
          multicapture_pi = try_upgrade_to_multicapture(@payment, amount_to_auth + remaining_amount) if remaining_amount.positive?
        end

        if balance_paid
          @order.reload
          payment_completed = @order.payment_complete
          error = "Order cannot be released to the warehouse. #{@order.errors_to_s} #{@order.shipping_address.errors_to_s}" unless payment_completed
          notice = 'Order needs to be authorized by accounting before it can be released.' if @order.pending_release_authorization?
        end
      else
        success = false
        error += "Could not process payment. #{res.message} "
        error += "Last response: #{@payment.last_response} " if @payment.last_response.present?
        error_codes += @payment.error_codes if @payment.error_codes.present?
      end
    else
      success = false
      error += "Payment could not be saved. #{@payment.errors.full_messages}"
    end
    all_payments << { payment: @payment }
  end

  # We do a second pass throught the deliveries to capture payments for any custom products.
  # IMPORTANT: Keep this method separate. The capture needs to happen after ALL DELIVERIES have been authorized.
  # If it happens before, then the vault gets deleted and we can't authorize the second payment.

  # If the delivery has a custom product, we capture the payment right away. We use this 2 step process instead
  # of the purchase action because not all payment gateways have a purchase option.
  all_payments.each do |payment_hash|
    payment = payment_hash[:payment]
    if payment.delivery.has_custom_products?
      payment.gateway_class.new(payment).capture(payment.amount) unless payment.does_not_allow_capture?
    end
  end

  if !success
    @payment ||= @order.payments.build(@payment_params)
    bad_payment = all_payments.any? ? all_payments.last[:payment] : nil
    errors = bad_payment.nil? ? [] : bad_payment.errors
    errors.each do |err|
      @payment.errors.add(err.attribute, err.message) unless @payment.errors.full_messages.include?(err.full_message)
    end
    Result.new(result: 'failed', error: error, notice: notice, payment: @payment)
  elsif balance_paid
    Result.new(result: 'fully_authorized')
  else
    Result.new(result: 'partially_authorized', notice: 'Additional payment required.')
  end
end