Class: Spree::Adjustment

Inherits:
Object
  • Object
show all
Extended by:
DisplayMoney
Defined in:
app/models/spree/adjustment.rb

Instance Method Summary collapse

Methods included from DisplayMoney

money_methods

Instance Method Details

#additional?Boolean

Returns:

  • (Boolean)


95
96
97
# File 'app/models/spree/adjustment.rb', line 95

def additional?
  !included?
end

#amount=(amount) ⇒ Object



79
80
81
# File 'app/models/spree/adjustment.rb', line 79

def amount=(amount)
  self[:amount] = Spree::LocalizedNumber.parse(amount)
end

#cached_sourceObject?

Returns the source using Rails.cache to avoid repeated database lookups. Sources are cached by their type and ID combination. Cache is automatically invalidated when the source is saved (see AdjustmentSource concern).

Returns:

  • (Object, nil)

    The source object (TaxRate, PromotionAction, etc.)



104
105
106
107
108
109
110
111
# File 'app/models/spree/adjustment.rb', line 104

def cached_source
  return nil if source_type.blank? || source_id.blank?

  Rails.cache.fetch(source_cache_key) { source }
rescue TypeError
  # Handle objects that can't be serialized (e.g., mock objects in tests)
  source
end

#currencyObject



83
84
85
# File 'app/models/spree/adjustment.rb', line 83

def currency
  adjustable ? adjustable.currency : order.currency
end

#promotion?Boolean

Returns:

  • (Boolean)


87
88
89
# File 'app/models/spree/adjustment.rb', line 87

def promotion?
  source_type == 'Spree::PromotionAction'
end

#source_cache_keyObject

Cache key for the source object



114
115
116
# File 'app/models/spree/adjustment.rb', line 114

def source_cache_key
  "spree/adjustment_source/#{source_type}/#{source_id}"
end

#tax?Boolean

Returns:

  • (Boolean)


91
92
93
# File 'app/models/spree/adjustment.rb', line 91

def tax?
  source_type == 'Spree::TaxRate'
end

#update!(target = adjustable) ⇒ Object

Passing a target here would always be recommended as it would avoid hitting the database again and would ensure you’re compute values over the specific object amount passed here.



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'app/models/spree/adjustment.rb', line 121

def update!(target = adjustable)
  src = cached_source
  return amount if closed? || src.blank?

  new_amount = src.compute_amount(target)
  new_eligible = promotion? ? src.promotion.eligible?(target) : eligible

  changed_attributes = {}
  changed_attributes[:amount] = new_amount if new_amount != amount
  changed_attributes[:eligible] = new_eligible if new_eligible != eligible

  if changed_attributes.any?
    changed_attributes[:updated_at] = Time.current
    update_columns(changed_attributes)
  end

  new_amount
end