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

  self.user = (items.delete(:user) if items.kind_of?(Hash)) || user
  add_to_order(items) if items.present?
end

Instance Attribute Details

#save_billing_addressObject

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_addressObject

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_billingObject

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_nameObject



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

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



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

def decline!(payment_details = nil)
  return false 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)


296
297
298
# File 'app/models/effective/order.rb', line 296

def declined?
  purchase_state == EffectiveOrders::DECLINED
end

#num_itemsObject



166
167
168
# File 'app/models/effective/order.rb', line 166

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”}}



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

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



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

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

  return false 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

#purchase_card_typeObject Also known as: payment_card_type



258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# File 'app/models/effective/order.rb', line 258

def purchase_card_type
  return 'None' unless purchased?

  if purchased?(:stripe_connect)
    ((payment[:charge] || payment['charge'])['card']['brand'] rescue 'Unknown')
  elsif purchased?(:stripe)
    ((payment[:charge] || payment['charge'])['card']['brand'] rescue 'Unknown')
  elsif purchased?(:moneris)
    payment[:card] || payment['card'] || 'Unknown'
  elsif purchased?(:paypal)
    payment[:payment_type] || payment['payment_type'] || 'Unknown'
  else
    'Online'
  end
end

#purchase_methodObject Also known as: payment_method



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

def purchase_method
  return 'None' unless purchased?

  if purchased?(:stripe_connect)
    'Stripe Connect'
  elsif purchased?(:stripe)
    'Stripe'
  elsif purchased?(:moneris)
    'Moneris'
  elsif purchased?(:paypal)
    'PayPal'
  else
    'Online'
  end
end

#purchased?(provider = nil) ⇒ Boolean

Returns:

  • (Boolean)


275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
# File 'app/models/effective/order.rb', line 275

def purchased?(provider = nil)
  return false if (purchase_state != EffectiveOrders::PURCHASED)
  return true if provider == nil || payment.kind_of?(Hash) == false

  case provider.to_sym
  when :stripe_connect
    charge = (payment[:charge] || payment['charge'] || {})
    charge['id'] && charge['customer'] && charge['application_fee'].present?
  when :stripe
    charge = (payment[:charge] || payment['charge'] || {})
    charge['id'] && charge['customer']
  when :moneris
    (payment[:response_code] || payment['response_code']) &&
    (payment[:transactionKey] || payment['transactionKey'])
  when :paypal
    (payment[:payer_email] || payment['payer_email'])
  else
    raise "Unknown provider #{provider} passed to Effective::Order.purchased?"
  end
end

#save_billing_address?Boolean

Returns:

  • (Boolean)


170
171
172
# File 'app/models/effective/order.rb', line 170

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

#save_shipping_address?Boolean

Returns:

  • (Boolean)


174
175
176
# File 'app/models/effective/order.rb', line 174

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

#send_order_receipt_to_admin!Object



306
307
308
309
310
311
312
313
314
# File 'app/models/effective/order.rb', line 306

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



316
317
318
319
320
321
322
323
324
# File 'app/models/effective/order.rb', line 316

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



326
327
328
329
330
331
332
333
334
335
336
# File 'app/models/effective/order.rb', line 326

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



300
301
302
303
304
# File 'app/models/effective/order.rb', line 300

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)


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

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

#subtotalObject



158
159
160
# File 'app/models/effective/order.rb', line 158

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

#taxObject



162
163
164
# File 'app/models/effective/order.rb', line 162

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

#totalObject



154
155
156
# File 'app/models/effective/order.rb', line 154

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

def user=(user)
  return if user.nil?

  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