Class: Effective::Order

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
app/models/effective/order.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(items = {}, user = nil) ⇒ Order

Can be an Effective::Cart, a single acts_as_purchasable, or an array of acts_as_purchasables



51
52
53
54
55
56
57
58
59
60
61
# File 'app/models/effective/order.rb', line 51

def initialize(items = {}, user = nil)
  super() # Call super with no arguments

  # Set up defaults
  self.save_billing_address = true
  self.save_shipping_address = true
  self.shipping_address_same_as_billing = true

  add_to_order(items) if items.present?
  self.user = user if user.present?
end

Instance Attribute Details

#save_billing_address ⇒ Object

save these addresses to the user if selected



10
11
12
# File 'app/models/effective/order.rb', line 10

def save_billing_address
  @save_billing_address
end

#save_shipping_address ⇒ Object

save these addresses to the user if selected



10
11
12
# File 'app/models/effective/order.rb', line 10

def save_shipping_address
  @save_shipping_address
end

#shipping_address_same_as_billing ⇒ Object

save these addresses to the user if selected



10
11
12
# File 'app/models/effective/order.rb', line 10

def shipping_address_same_as_billing
  @shipping_address_same_as_billing
end

Instance Method Details

#add(item, quantity = 1) ⇒ Object Also known as: add_to_order



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
# File 'app/models/effective/order.rb', line 63

def add(item, quantity = 1)
  raise 'unable to alter a purchased order' if purchased?
  raise 'unable to alter a declined order' if declined?

  if item.kind_of?(Effective::Cart)
    cart_items = item.cart_items
  else
    purchasables = [item].flatten

    if purchasables.any? { |p| !p.respond_to?(:is_effectively_purchasable?) }
      raise ArgumentError.new('Effective::Order.add() expects a single acts_as_purchasable item, or an array of acts_as_purchasable items')
    end

    cart_items = purchasables.map do |purchasable|
      CartItem.new(:quantity => quantity).tap { |cart_item| cart_item.purchasable = purchasable }
    end
  end

  retval = cart_items.map do |item|
    order_items.build(
      :title => item.title,
      :quantity => item.quantity,
      :price => item.price,
      :tax_exempt => item.tax_exempt,
      :tax_rate => item.tax_rate,
      :seller_id => (item.purchasable.try(:seller).try(:id) rescue nil)
    ).tap { |order_item| order_item.purchasable = item.purchasable }
  end

  retval.size == 1 ? retval.first : retval
end

#billing_name ⇒ Object



184
185
186
187
188
189
190
191
192
# File 'app/models/effective/order.rb', line 184

def billing_name
  name ||= billing_address.try(:full_name).presence
  name ||= user.try(:full_name).presence
  name ||= (user.try(:first_name).to_s + ' ' + user.try(:last_name).to_s).presence
  name ||= user.try(:email).presence
  name ||= user.to_s
  name ||= "User #{user.try(:id)}"
  name
end

#decline!(payment_details = nil) ⇒ Object



224
225
226
227
228
229
230
231
232
233
234
235
236
237
# File 'app/models/effective/order.rb', line 224

def decline!(payment_details = nil)
  return true if declined?

  raise EffectiveOrders::AlreadyPurchasedException.new('order already purchased') if purchased?

  Order.transaction do
    self.purchase_state = EffectiveOrders::DECLINED
    self.payment = payment_details.kind_of?(Hash) ? payment_details : {:details => (payment_details || 'none').to_s}

    order_items.each { |item| (item.purchasable.declined!(self, item) rescue nil) }

    save!
  end
end

#declined? ⇒ Boolean

Returns:

  • (Boolean)


260
261
262
# File 'app/models/effective/order.rb', line 260

def declined?
  purchase_state == EffectiveOrders::DECLINED
end

#num_items ⇒ Object



164
165
166
# File 'app/models/effective/order.rb', line 164

def num_items
  order_items.map(&:quantity).sum
end

#order_items_attributes=(order_item_attributes) ⇒ Object

This is used for updating Subscription codes. We want to update the underlying purchasable object of an OrderItem Passing the order_item_attributes using rails default acts_as_nested creates a new object instead of updating the temporary one. So we override this method to do the updates on the non-persisted OrderItem objects Right now strong_paramaters only lets through stripe_coupon_id "stripe_coupon_id"=>"50OFF", "id"=>"2"}}



133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'app/models/effective/order.rb', line 133

def order_items_attributes=(order_item_attributes)
  if self.persisted? == false
    (order_item_attributes || {}).each do |_, atts|
      order_item = self.order_items.find { |oi| oi.purchasable.class.name == atts[:class] && oi.purchasable.id == atts[:id].to_i }

      if order_item
        order_item.purchasable.attributes = atts.except(:id, :class)

        # Recalculate the OrderItem based on the updated purchasable object
        order_item.title = order_item.purchasable.title
        order_item.price = order_item.purchasable.price
        order_item.tax_exempt = order_item.purchasable.tax_exempt
        order_item.tax_rate = order_item.purchasable.tax_rate
        order_item.seller_id = (order_item.purchasable.try(:seller).try(:id) rescue nil)
      end
    end
  end
end

#purchase!(payment_details = nil, opts = {}) ⇒ Object

:validate => false, :email => false



195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'app/models/effective/order.rb', line 195

def purchase!(payment_details = nil, opts = {})
  opts = {validate: true, email: true}.merge(opts)

  return true if purchased?
  raise EffectiveOrders::AlreadyDeclinedException.new('order already declined') if (declined? && opts[:validate])

  success = false

  Order.transaction do
    begin
      self.purchase_state = EffectiveOrders::PURCHASED
      self.purchased_at ||= Time.zone.now
      self.payment = payment_details.kind_of?(Hash) ? payment_details : {:details => (payment_details || 'none').to_s}

      save!(validate: opts[:validate])

      order_items.each { |item| (item.purchasable.purchased!(self, item) rescue nil) }

      success = true
    rescue => e
      raise ActiveRecord::Rollback
    end
  end

  send_order_receipts! if success && opts[:email]

  success
end

#purchased?(provider = nil) ⇒ Boolean

Returns:

  • (Boolean)


239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# File 'app/models/effective/order.rb', line 239

def purchased?(provider = nil)
  return false if (purchase_state != EffectiveOrders::PURCHASED)
  return true if provider == nil

  begin
    case provider
    when :stripe_connect
      payment.keys.first.kind_of?(Numeric) && payment[payment.keys.first].key?('object') && payment[payment.keys.first]['object'] == 'charge'
    when :stripe
      payment.key?('object') && payment['object'] == 'charge'
    when :moneris
      payment.key?('response_code') && payment.key?('transactionKey')
    when :paypal
    else
      false
    end
  rescue => e
    false
  end
end

#save_billing_address? ⇒ Boolean

Returns:

  • (Boolean)


168
169
170
# File 'app/models/effective/order.rb', line 168

def save_billing_address?
  ::ActiveRecord::ConnectionAdapters::Column::TRUE_VALUES.include?(self.save_billing_address)
end

#save_shipping_address? ⇒ Boolean

Returns:

  • (Boolean)


172
173
174
# File 'app/models/effective/order.rb', line 172

def save_shipping_address?
  ::ActiveRecord::ConnectionAdapters::Column::TRUE_VALUES.include?(self.save_shipping_address)
end

#send_order_receipt_to_admin! ⇒ Object



270
271
272
273
274
275
276
277
278
# File 'app/models/effective/order.rb', line 270

def send_order_receipt_to_admin!
  return false unless purchased? && EffectiveOrders.mailer[:send_order_receipt_to_admin]

  if Rails.env.production?
    (OrdersMailer.order_receipt_to_admin(self).deliver rescue false)
  else
    OrdersMailer.order_receipt_to_admin(self).deliver
  end
end

#send_order_receipt_to_buyer! ⇒ Object



280
281
282
283
284
285
286
287
288
# File 'app/models/effective/order.rb', line 280

def send_order_receipt_to_buyer!
  return false unless purchased? && EffectiveOrders.mailer[:send_order_receipt_to_buyer]

  if Rails.env.production?
    (OrdersMailer.order_receipt_to_buyer(self).deliver rescue false)
  else
    OrdersMailer.order_receipt_to_buyer(self).deliver
  end
end

#send_order_receipt_to_seller! ⇒ Object



290
291
292
293
294
295
296
297
298
299
300
# File 'app/models/effective/order.rb', line 290

def send_order_receipt_to_seller!
  return false unless purchased?(:stripe_connect) && EffectiveOrders.mailer[:send_order_receipt_to_seller]

  order_items.group_by(&:seller).each do |seller, order_items|
    if Rails.env.production?
      (OrdersMailer.order_receipt_to_seller(self, seller, order_items).deliver rescue false)
    else
      OrdersMailer.order_receipt_to_seller(self, seller, order_items).deliver
    end
  end
end

#send_order_receipts! ⇒ Object



264
265
266
267
268
# File 'app/models/effective/order.rb', line 264

def send_order_receipts!
  send_order_receipt_to_admin!
  send_order_receipt_to_buyer!
  send_order_receipt_to_seller!
end

#shipping_address_same_as_billing? ⇒ Boolean

Returns:

  • (Boolean)


176
177
178
179
180
181
182
# File 'app/models/effective/order.rb', line 176

def shipping_address_same_as_billing?
  if self.shipping_address_same_as_billing.nil?
    true # Default value
  else
    ::ActiveRecord::ConnectionAdapters::Column::TRUE_VALUES.include?(self.shipping_address_same_as_billing)
  end
end

#subtotal ⇒ Object



156
157
158
# File 'app/models/effective/order.rb', line 156

def subtotal
  order_items.map(&:subtotal).sum
end

#tax ⇒ Object



160
161
162
# File 'app/models/effective/order.rb', line 160

def tax
  [order_items.map(&:tax).sum, 0].max
end

#total ⇒ Object



152
153
154
# File 'app/models/effective/order.rb', line 152

def total
  [order_items.map(&:total).sum, 0].max
end

#user=(user) ⇒ Object



96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'app/models/effective/order.rb', line 96

def user=(user)
  super

  # Copy user addresses into this order if they are present
  if user.respond_to?(:billing_address) && !user.billing_address.nil?
    self.billing_address = user.billing_address
  end

  if user.respond_to?(:shipping_address) && !user.shipping_address.nil?
    self.shipping_address = user.shipping_address
  end

  # If our addresses are required, make sure they exist
  if EffectiveOrders.require_billing_address
    self.billing_address ||= Effective::Address.new()
  end

  if EffectiveOrders.require_shipping_address
    self.shipping_address ||= Effective::Address.new()
  end

  # Ensure the Full Name is assigned when an address exists
  if billing_address.nil? == false && billing_address.full_name.blank?
    self.billing_address.full_name = billing_name
  end

  if shipping_address.nil? == false && shipping_address.full_name.blank?
    self.shipping_address.full_name = billing_name
  end
end