Class: Gold::ApplyTierOp

Inherits:
Object
  • Object
show all
Includes:
Outcomes, Retries
Defined in:
app/operations/gold/apply_tier_op.rb

Overview

Apply the tier that the shop has selected.

Constant Summary

Constants included from Outcomes

Outcomes::AcceptedCharge, Outcomes::AcceptedTerms, Outcomes::ActiveCharge, Outcomes::CannotApplyDiscount, Outcomes::CannotIssueCredit, Outcomes::CannotProcessCharge, Outcomes::CannotSelectTier, Outcomes::ChargeNeeded, Outcomes::ChargeNotNeeded, Outcomes::DeclinedCharge, Outcomes::DeclinedTerms, Outcomes::ExpiredCharge, Outcomes::FrozenCharge, Outcomes::MismatchCharge, Outcomes::MissingCharge, Outcomes::PendingCharge, Outcomes::SameDiscount, Outcomes::SameTier, Outcomes::TierApplied, Outcomes::TierNotFound, Outcomes::Uninstalled

Instance Method Summary collapse

Methods included from Retries

#request_with_retries

Constructor Details

#initialize(billing) ⇒ ApplyTierOp

Returns a new instance of ApplyTierOp.



7
8
9
# File 'app/operations/gold/apply_tier_op.rb', line 7

def initialize(billing)
  @billing = billing
end

Instance Method Details

#callObject



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
# File 'app/operations/gold/apply_tier_op.rb', line 11

def call
  begin
    tier = @billing.last_selected_tier
  rescue UnknownTier => e
    return TierNotFound.new(e.message)
  end

  @billing.transaction do
    unless %i[apply_tier apply_free_tier].include?(@billing.current_state)
      if tier.free?
        @billing.transition_to!(:apply_free_tier, tier_id: tier.id)
      elsif @billing.shopify_plan.paying?
        @billing.transition_to!(:apply_tier, tier_id: tier.id)
      end
    end

    @billing.tier = tier
    @billing.save!

    if tier.free?
      if Gold.configuration.allow_automated_charge_cancellation
        # Remove any outstanding active charges
        if (charge = ShopifyAPI::RecurringApplicationCharge.current)
          request_with_retries do
            Gold.logger.info("[#{@billing.id}] Free tier applied, canceling " \
                            "charge '#{charge.price}' for " \
                            "'#{@billing.shop.shopify_domain}'")
            charge.cancel
          end
        end
      else
        Gold.logger.info("[#{@billing.id}] Would have cancelled charge for " \
                        "'#{@billing.shop.shopify_domain}', but prevented by setting")
      end
    end

    @billing.transition_to!(billing_state)
  end

  Gold.configuration.on_apply_tier&.call(@billing, tier.id)
  TierApplied.new
end