Module: Spree::OrderDecorator

Defined in:
app/models/spree/order_decorator.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.prepended(base) ⇒ Object



3
4
5
6
7
8
9
# File 'app/models/spree/order_decorator.rb', line 3

def self.prepended(base)
  # Hook 1: Add/Remove COD Surcharge for both Rails (confirm) and Next.js (complete) flows
  base.state_machine.before_transition to: [:confirm, :complete], do: :manage_cod_surcharge
  
  # Hook 2: Auto-void Delhivery waybills if the order is canceled
  base.state_machine.after_transition to: :canceled, do: :cancel_delhivery_shipments
end

Instance Method Details

#manage_cod_surchargeObject



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
# File 'app/models/spree/order_decorator.rb', line 11

def manage_cod_surcharge
  # 1. Check if the customer chose Delhivery COD
  is_cod = payments.valid.any? { |p| p.payment_method&.type == 'Spree::PaymentMethod::DelhiveryCod' }
  
  # 2. Fetch your Delhivery configuration
  integration = Spree::Integrations::Delhivery.active.first
  surcharge_amount = integration&.preferred_cod_surcharge_amount.to_f

  # 3. Apply or Remove the financial adjustment
  if is_cod && surcharge_amount > 0
    # Destroy any old COD fees to prevent duplicate stacking
    adjustments.where(label: 'COD Surcharge').destroy_all
    
    # Create the new fee
    adjustments.create!(
      order: self,
      adjustable: self, # Apply to the whole order
      label: 'COD Surcharge',
      amount: surcharge_amount,
      state: 'closed', # Prevents Spree's auto-calculator from zeroing it out
      included: false
    )
  else
    # If they switched back to Prepaid, cleanly remove the fee
    adjustments.where(label: 'COD Surcharge').destroy_all
  end

  # Force Spree to recalculate the grand total with the new fee
  updater.update
end