Created
November 19, 2012 06:42
-
-
Save jphpsf/4109290 to your computer and use it in GitHub Desktop.
Simple Spree adjusment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# Decorate Spree::LineItem model to add keg deposits | |
# and CRV automatically to the order (derived from | |
# the package format fees) when line items are changed | |
# | |
Spree::LineItem.class_eval do | |
after_save :update_order_package_fees | |
def update_order_package_fees | |
order.update_package_fees! | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# Decorate Spree::Order model with method to calculate | |
# keg deposits and CRV automatically to the order (derived | |
# from the package format fees) | |
# | |
Spree::Order.class_eval do | |
# Update custom fees derived from the package format (such as CRV for | |
# cases or keg deposit for kegs - see PackageFormat model) | |
def update_package_fees! | |
adjustments.where(:source_type => 'package-format-fee').destroy_all | |
fees = {} | |
self.line_items.each do |line_item| | |
qty = line_item.quantity | |
fee_name = line_item.product.package_format.fee_name | |
fee_value = line_item.product.package_format.fee_value | |
fees[fee_name] ||= 0 | |
fees[fee_name] += qty * fee_value | |
end | |
fees.each do |(fee_name, fee_value)| | |
add_package_fee(fee_name, fee_value) if fee_value > 0 | |
end | |
update! | |
end | |
private | |
def add_package_fee(label, amount) | |
self.adjustments.create({ | |
:amount => amount, | |
:adjustable => self, | |
:source_type => 'package-format-fee', | |
:label => label, | |
:mandatory => true, | |
:locked => true | |
}, :without_protection => true) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment