7
8
9
10
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
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
|
# File 'lib/spree_volume_pricing/engine.rb', line 7
def self.activate
Variant.class_eval do
has_many :volume_prices, :order => :position, :dependent => :destroy
accepts_nested_attributes_for :volume_prices
def volume_price(quantity)
volume_prices.each do |price|
return price.amount if price.include?(quantity)
end
self.price
end
end
Order.class_eval do
def add_variant(variant, quantity=1)
current_item = contains?(variant)
price = variant.volume_price(quantity) if current_item
current_item.increment_quantity unless quantity > 1
current_item.quantity = (current_item.quantity + quantity) if quantity > 1
current_item.price = price current_item.save
else
current_item = line_items.create(:quantity => quantity)
current_item.variant = variant
current_item.price = price
current_item.save
end
Variant.additional_fields.select{|f| !f[:populate].nil? && f[:populate].include?(:line_item) }.each do |field|
value = ""
if field[:only].nil? || field[:only].include?(:variant)
value = variant.send(field[:name].gsub(" ", "_").downcase)
elsif field[:only].include?(:product)
value = variant.product.send(field[:name].gsub(" ", "_").downcase)
end
current_item.update_attribute(field[:name].gsub(" ", "_").downcase, value)
end
end
end
LineItem.class_eval do
before_update :check_volume_pricing
private
def check_volume_pricing
if changed? && changes.keys.include?("quantity")
self.price = variant.volume_price(quantity)
end
end
end
String.class_eval do
def to_range
case self.count('.')
when 2
elements = self.split('..')
return Range.new(elements[0].from(1).to_i, elements[1].to_i)
when 3
elements = self.split('...')
return Range.new(elements[0].from(1).to_i, elements[1].to_i-1)
else
raise ArgumentError.new("Couldn't convert to Range: #{self}")
end
end
end
Admin::VariantsController.class_eval do
update.before do
params[:variant][:volume_price_attributes] ||= {}
end
update.response do |wants|
wants.html do
redirect_to object.is_master ? volume_prices_admin_product_variant_url(object.product, object) : collection_url
end
end
def object
@object ||= Variant.find(params[:id])
end
def volume_prices
@variant = object
@product = @variant.product
end
end
end
|