Class: Spree::Order

Inherits:
Base
  • Object
show all
Includes:
Checkout, CurrencyUpdater, Payments
Defined in:
app/models/spree/order.rb,
app/models/spree/order/checkout.rb,
app/models/spree/order/payments.rb,
app/models/spree/order/currency_updater.rb

Defined Under Namespace

Modules: Checkout, CurrencyUpdater, Payments

Constant Summary collapse

ORDER_NUMBER_LENGTH =
9
ORDER_NUMBER_LETTERS =
false
ORDER_NUMBER_PREFIX =
'R'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from CurrencyUpdater

#price_from_line_item, #update_line_item_currencies!, #update_line_item_price!

Methods included from Checkout

included

Methods inherited from Base

page

Methods included from Preferences::Preferable

#clear_preferences, #default_preferences, #defined_preferences, #get_preference, #has_preference!, #has_preference?, #preference_default, #preference_type, #set_preference

Instance Attribute Details

#coupon_codeObject

Returns the value of attribute coupon_code.



24
25
26
# File 'app/models/spree/order.rb', line 24

def coupon_code
  @coupon_code
end

#temporary_addressObject

Returns the value of attribute temporary_address.



25
26
27
# File 'app/models/spree/order.rb', line 25

def temporary_address
  @temporary_address
end

#temporary_credit_cardObject

Returns the value of attribute temporary_credit_card.



25
26
27
# File 'app/models/spree/order.rb', line 25

def temporary_credit_card
  @temporary_credit_card
end

#use_billingObject

Returns the value of attribute use_billing.



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

def use_billing
  @use_billing
end

Class Method Details

.by_customer(customer) ⇒ Object



116
117
118
# File 'app/models/spree/order.rb', line 116

def self.by_customer(customer)
  joins(:user).where("#{Spree.user_class.table_name}.email" => customer)
end

.by_number(number) ⇒ Object



106
107
108
# File 'app/models/spree/order.rb', line 106

def self.by_number(number)
  where(number: number)
end

.by_state(state) ⇒ Object



120
121
122
# File 'app/models/spree/order.rb', line 120

def self.by_state(state)
  where(state: state)
end

.completeObject



124
125
126
# File 'app/models/spree/order.rb', line 124

def self.complete
  where.not(completed_at: nil)
end

.incompleteObject



128
129
130
# File 'app/models/spree/order.rb', line 128

def self.incomplete
  where(completed_at: nil)
end

.register_line_item_comparison_hook(hook) ⇒ Object

Use this method in other gems that wish to register their own custom logic that should be called when determining if two line items are equal.



140
141
142
# File 'app/models/spree/order.rb', line 140

def self.register_line_item_comparison_hook(hook)
  self.line_item_comparison_hooks.add(hook)
end

.register_update_hook(hook) ⇒ Object

Use this method in other gems that wish to register their own custom logic that should be called after Order#update



134
135
136
# File 'app/models/spree/order.rb', line 134

def self.register_update_hook(hook)
  self.update_hooks.add(hook)
end

Instance Method Details

#all_inventory_units_returned?Boolean

Returns:

  • (Boolean)


267
268
269
# File 'app/models/spree/order.rb', line 267

def all_inventory_units_returned?
  inventory_units.all? { |inventory_unit| inventory_unit.returned? }
end

#allow_cancel?Boolean

Returns:

  • (Boolean)


262
263
264
265
# File 'app/models/spree/order.rb', line 262

def allow_cancel?
  return false unless completed? and state != 'canceled'
  shipment_state.nil? || %w{ready backorder pending}.include?(shipment_state)
end

#amountObject

For compatiblity with Calculator::PriceSack



145
146
147
# File 'app/models/spree/order.rb', line 145

def amount
  line_items.inject(0.0) { |sum, li| sum + li.amount }
end

#apply_free_shipping_promotionsObject



524
525
526
527
528
529
# File 'app/models/spree/order.rb', line 524

def apply_free_shipping_promotions
  Spree::PromotionHandler::FreeShipping.new(self).activate
  shipments.each { |shipment| ItemAdjustments.new(shipment).update }
  updater.update_shipment_total
  persist_totals
end

#approve!Object



608
609
610
# File 'app/models/spree/order.rb', line 608

def approve!
  update_column(:considered_risky, false)
end

#approved?Boolean

Returns:

  • (Boolean)


590
591
592
# File 'app/models/spree/order.rb', line 590

def approved?
  !!self.approved_at
end

#approved_by(user) ⇒ Object



580
581
582
583
584
585
586
587
588
# File 'app/models/spree/order.rb', line 580

def approved_by(user)
  self.transaction do
    approve!
    self.update_columns(
      approver_id: user.id,
      approved_at: Time.now,
    )
  end
end

#associate_user!(user, override_email = true) ⇒ Object

Associates the specified user with the order.



276
277
278
279
280
281
282
283
284
285
286
287
# File 'app/models/spree/order.rb', line 276

def associate_user!(user, override_email = true)
  self.user = user
  attrs_to_set = { user_id: user.id }
  attrs_to_set[:email] = user.email if override_email
  attrs_to_set[:created_by_id] = user.id if self.created_by.blank?
  assign_attributes(attrs_to_set)

  if persisted?
    # immediately persist the changes we just made, but don't use save since we might have an invalid address associated
    self.class.unscoped.where(id: id).update_all(attrs_to_set)
  end
end

#available_payment_methodsObject



435
436
437
# File 'app/models/spree/order.rb', line 435

def available_payment_methods
  @available_payment_methods ||= (PaymentMethod.available(:front_end) + PaymentMethod.available(:both)).uniq
end

#backordered?Boolean

Returns:

  • (Boolean)


226
227
228
# File 'app/models/spree/order.rb', line 226

def backordered?
  shipments.any?(&:backordered?)
end

#billing_firstnameObject



439
440
441
# File 'app/models/spree/order.rb', line 439

def billing_firstname
  bill_address.try(:firstname)
end

#billing_lastnameObject



443
444
445
# File 'app/models/spree/order.rb', line 443

def billing_lastname
  bill_address.try(:lastname)
end

#can_add_coupon?Boolean

Returns:

  • (Boolean)


509
510
511
# File 'app/models/spree/order.rb', line 509

def can_add_coupon?
  Spree::Promotion.order_activatable?(self)
end

#can_approve?Boolean

Returns:

  • (Boolean)


594
595
596
# File 'app/models/spree/order.rb', line 594

def can_approve?
  !approved?
end

#can_ship?Boolean

Returns:

  • (Boolean)


381
382
383
# File 'app/models/spree/order.rb', line 381

def can_ship?
  self.complete? || self.resumed? || self.awaiting_return? || self.returned?
end

#canceled_by(user) ⇒ Object



570
571
572
573
574
575
576
577
578
# File 'app/models/spree/order.rb', line 570

def canceled_by(user)
  self.transaction do
    cancel!
    self.update_columns(
      canceler_id: user.id,
      canceled_at: Time.now,
    )
  end
end

#checkout_allowed?Boolean

Indicates whether or not the user is allowed to proceed to checkout. Currently this is implemented as a check for whether or not there is at least one LineItem in the Order. Feel free to override this logic in your own application if you require additional steps before allowing a checkout.

Returns:

  • (Boolean)


207
208
209
# File 'app/models/spree/order.rb', line 207

def checkout_allowed?
  line_items.count > 0
end

#clone_billing_addressObject



253
254
255
256
257
258
259
260
# File 'app/models/spree/order.rb', line 253

def clone_billing_address
  if bill_address and self.ship_address.nil?
    self.ship_address = bill_address.clone
  else
    self.ship_address.attributes = bill_address.attributes.except('id', 'updated_at', 'created_at')
  end
  true
end

#completed?Boolean

Returns:

  • (Boolean)


199
200
201
# File 'app/models/spree/order.rb', line 199

def completed?
  completed_at.present?
end

#confirmation_required?Boolean

If true, causes the confirmation step to happen during the checkout process

Returns:

  • (Boolean)


217
218
219
220
221
222
223
224
# File 'app/models/spree/order.rb', line 217

def confirmation_required?
  Spree::Config[:always_include_confirm_step] ||
    payments.valid.map(&:payment_method).compact.any?(&:payment_profiles_supported?) ||
    # Little hacky fix for #4117
    # If this wasn't here, order would transition to address state on confirm failure
    # because there would be no valid payments any more.
    state == 'confirm'
end

#consider_riskObject



598
599
600
601
602
# File 'app/models/spree/order.rb', line 598

def consider_risk
  if is_risky? && !approved?
    considered_risky!
  end
end

#considered_risky!Object



604
605
606
# File 'app/models/spree/order.rb', line 604

def considered_risky!
  update_column(:considered_risky, true)
end

#contains?(variant, options = {}) ⇒ Boolean

Returns:

  • (Boolean)


314
315
316
# File 'app/models/spree/order.rb', line 314

def contains?(variant, options = {})
  find_line_item_by_variant(variant, options).present?
end

#contentsObject



271
272
273
# File 'app/models/spree/order.rb', line 271

def contents
  @contents ||= Spree::OrderContents.new(self)
end

#create_proposed_shipmentsObject



518
519
520
521
522
# File 'app/models/spree/order.rb', line 518

def create_proposed_shipments
  adjustments.shipping.delete_all
  shipments.destroy_all
  self.shipments = Spree::Stock::Coordinator.new(self).shipments
end

#create_tax_charge!Object

Creates new tax charges if there are any applicable rates. If prices already include taxes then price adjustments are created instead.



349
350
351
352
353
354
# File 'app/models/spree/order.rb', line 349

def create_tax_charge!
  # We want to only look up the applicable tax zone once and pass it to TaxRate calculation to avoid duplicated lookups.
  order_tax_zone = self.tax_zone
  Spree::TaxRate.adjust(order_tax_zone, line_items)
  Spree::TaxRate.adjust(order_tax_zone, shipments) if shipments.any?
end

#credit_cardsObject



385
386
387
388
# File 'app/models/spree/order.rb', line 385

def credit_cards
  credit_card_ids = payments.from_credit_card.pluck(:source_id).uniq
  CreditCard.where(id: credit_card_ids)
end

#currencyObject



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

def currency
  self[:currency] || Spree::Config[:currency]
end

#deliver_order_confirmation_emailObject



425
426
427
428
# File 'app/models/spree/order.rb', line 425

def deliver_order_confirmation_email
  OrderMailer.confirm_email(self.id).deliver
  update_column(:confirmation_delivered, true)
end

#display_additional_tax_totalObject



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

def display_additional_tax_total
  Spree::Money.new(additional_tax_total, { currency: currency })
end

#display_adjustment_totalObject



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

def display_adjustment_total
  Spree::Money.new(adjustment_total, { currency: currency })
end

#display_included_tax_totalObject



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

def display_included_tax_total
  Spree::Money.new(included_tax_total, { currency: currency })
end

#display_item_totalObject



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

def display_item_total
  Spree::Money.new(item_total, { currency: currency })
end

#display_outstanding_balanceObject



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

def display_outstanding_balance
  Spree::Money.new(outstanding_balance, { currency: currency })
end

#display_shipment_totalObject Also known as: display_ship_total



182
183
184
# File 'app/models/spree/order.rb', line 182

def display_shipment_total
  Spree::Money.new(shipment_total, { currency: currency })
end

#display_tax_totalObject



178
179
180
# File 'app/models/spree/order.rb', line 178

def display_tax_total
  Spree::Money.new(tax_total, { currency: currency })
end

#display_totalObject



187
188
189
# File 'app/models/spree/order.rb', line 187

def display_total
  Spree::Money.new(total, { currency: currency })
end

#empty!Object



474
475
476
477
478
479
480
481
482
483
# File 'app/models/spree/order.rb', line 474

def empty!
  line_items.destroy_all
  updater.update_item_count
  adjustments.destroy_all
  shipments.destroy_all
  state_changes.destroy_all

  update_totals
  persist_totals
end

#ensure_line_item_variants_are_not_deletedObject

Check to see if any line item variants are soft deleted. If so add error and restart checkout.



454
455
456
457
458
459
460
461
462
# File 'app/models/spree/order.rb', line 454

def ensure_line_item_variants_are_not_deleted
  if line_items.any?{ |li| !li.variant || li.variant.paranoia_destroyed? }
    errors.add(:base, Spree.t(:deleted_variants_present))
    restart_checkout_flow
    false
  else
    true
  end
end

#ensure_line_items_are_in_stockObject



464
465
466
467
468
469
470
471
472
# File 'app/models/spree/order.rb', line 464

def ensure_line_items_are_in_stock
  if insufficient_stock_lines.present?
    errors.add(:base, Spree.t(:insufficient_stock_lines_present))
    restart_checkout_flow
    false
  else
    true
  end
end

#ensure_updated_shipmentsObject

Clean shipments and make order back to address state

At some point the might need to force the order to transition from address to delivery again so that proper updated shipments are created. e.g. customer goes back from payment step and changes order items



536
537
538
539
540
541
542
# File 'app/models/spree/order.rb', line 536

def ensure_updated_shipments
  if shipments.any? && !self.completed?
    self.shipments.destroy_all
    self.update_column(:shipment_total, 0)
    restart_checkout_flow
  end
end

#finalize!Object

Finalizes an in progress order after checkout is complete. Called after transition to complete state when payments will have been processed



397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
# File 'app/models/spree/order.rb', line 397

def finalize!
  # lock all adjustments (coupon promotions, etc.)
  all_adjustments.each{|a| a.close}

  # update payment and shipment(s) states, and save
  updater.update_payment_state
  shipments.each do |shipment|
    shipment.update!(self)
    shipment.finalize!
  end

  updater.update_shipment_state
  save!
  updater.run_hooks

  touch :completed_at

  deliver_order_confirmation_email unless confirmation_delivered?

  consider_risk
end

#find_line_item_by_variant(variant, options = {}) ⇒ Object



323
324
325
326
327
328
# File 'app/models/spree/order.rb', line 323

def find_line_item_by_variant(variant, options = {})
  line_items.detect { |line_item|
                line_item.variant_id == variant.id &&
                line_item_options_match(line_item, options)
              }
end

#fulfill!Object



419
420
421
422
423
# File 'app/models/spree/order.rb', line 419

def fulfill!
  shipments.each { |shipment| shipment.update!(self) if shipment.persisted? }
  updater.update_shipment_state
  save!
end

#generate_order_number(options = {}) ⇒ Object



289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
# File 'app/models/spree/order.rb', line 289

def generate_order_number(options = {})
  options[:length]  ||= ORDER_NUMBER_LENGTH
  options[:letters] ||= ORDER_NUMBER_LETTERS
  options[:prefix]  ||= ORDER_NUMBER_PREFIX

  possible = (0..9).to_a
  possible += ('A'..'Z').to_a if options[:letters]

  self.number ||= loop do
    # Make a random number.
    random = "#{options[:prefix]}#{(0...options[:length]).map { possible.shuffle.first }.join}"
    # Use the random  number if no other order exists with it.
    if self.class.exists?(number: random)
      # If over half of all possible options are taken add another digit.
      options[:length] += 1 if self.class.count > (10 ** options[:length] / 2)
    else
      break random
    end
  end
end

Returns:

  • (Boolean)


638
639
640
641
# File 'app/models/spree/order.rb', line 638

def has_non_reimbursement_related_refunds?
  refunds.non_reimbursement.exists? ||
    payments.offset_payment.exists? # how old versions of spree stored refunds
end

#has_step?(step) ⇒ Boolean

Returns:

  • (Boolean)


485
486
487
# File 'app/models/spree/order.rb', line 485

def has_step?(step)
  checkout_steps.include?(step)
end

#insufficient_stock_linesObject



447
448
449
# File 'app/models/spree/order.rb', line 447

def insufficient_stock_lines
  line_items.select(&:insufficient_stock?)
end

#is_risky?Boolean

Returns:

  • (Boolean)


566
567
568
# File 'app/models/spree/order.rb', line 566

def is_risky?
  self.payments.risky.count > 0
end

#line_item_options_match(line_item, options) ⇒ Object

This method enables extensions to participate in the “Are these line items equal” decision.

When adding to cart, an extension would send something like: params=…

and would provide:

def product_customizations_match



339
340
341
342
343
344
345
# File 'app/models/spree/order.rb', line 339

def line_item_options_match(line_item, options)
  return true unless options

  self.line_item_comparison_hooks.all? { |hook|
    self.send(hook, line_item, options)
  }
end

#mergerObject



249
250
251
# File 'app/models/spree/order.rb', line 249

def merger
  @merger ||= Spree::OrderMerger.new(self)
end

#nameObject



375
376
377
378
379
# File 'app/models/spree/order.rb', line 375

def name
  if (address = bill_address || ship_address)
    "#{address.firstname} #{address.lastname}"
  end
end

#outstanding_balanceObject



356
357
358
359
360
361
362
363
364
365
366
367
368
369
# File 'app/models/spree/order.rb', line 356

def outstanding_balance
  if state == 'canceled'
    -1 * payment_total
  elsif reimbursements.includes(:refunds).size > 0
    reimbursed = reimbursements.includes(:refunds).inject(0) do |sum, reimbursement|
      sum + reimbursement.refunds.sum(:amount)
    end
    # If reimbursement has happened add it back to total to prevent balance_due payment state
    # See: https://github.com/spree/spree/issues/6229
    total - (payment_total + reimbursed)
  else
    total - payment_total
  end
end

#outstanding_balance?Boolean

Returns:

  • (Boolean)


371
372
373
# File 'app/models/spree/order.rb', line 371

def outstanding_balance?
  self.outstanding_balance != 0
end

#paid?Boolean

Helper methods for checkout steps

Returns:

  • (Boolean)


431
432
433
# File 'app/models/spree/order.rb', line 431

def paid?
  payment_state == 'paid' || payment_state == 'credit_owed'
end

#payment_required?Boolean

Is this a free order in which case the payment step should be skipped

Returns:

  • (Boolean)


212
213
214
# File 'app/models/spree/order.rb', line 212

def payment_required?
  total.to_f > 0.0
end

#pre_tax_item_amountObject

Sum of all line item amounts pre-tax



150
151
152
# File 'app/models/spree/order.rb', line 150

def pre_tax_item_amount
  line_items.to_a.sum(&:pre_tax_amount)
end

#quantityObject



634
635
636
# File 'app/models/spree/order.rb', line 634

def quantity
  line_items.sum(:quantity)
end

#quantity_of(variant, options = {}) ⇒ Object



318
319
320
321
# File 'app/models/spree/order.rb', line 318

def quantity_of(variant, options = {})
  line_item = find_line_item_by_variant(variant, options)
  line_item ? line_item.quantity : 0
end

#refresh_shipment_ratesObject



552
553
554
# File 'app/models/spree/order.rb', line 552

def refresh_shipment_rates
  shipments.map &:refresh_rates
end

#reload(options = nil) ⇒ Object



625
626
627
628
# File 'app/models/spree/order.rb', line 625

def reload(options=nil)
  remove_instance_variable(:@tax_zone) if defined?(@tax_zone)
  super
end

#restart_checkout_flowObject



544
545
546
547
548
549
550
# File 'app/models/spree/order.rb', line 544

def restart_checkout_flow
  self.update_columns(
    state: 'cart',
    updated_at: Time.now,
  )
  self.next! if self.line_items.size > 0
end

#set_shipments_costObject



560
561
562
563
564
# File 'app/models/spree/order.rb', line 560

def set_shipments_cost
  shipments.each(&:update_amounts)
  updater.update_shipment_total
  persist_totals
end

#shipped?Boolean

Returns:

  • (Boolean)


514
515
516
# File 'app/models/spree/order.rb', line 514

def shipped?
  %w(partial shipped).include?(shipment_state)
end

#shipped_shipmentsObject



310
311
312
# File 'app/models/spree/order.rb', line 310

def shipped_shipments
  shipments.shipped
end

#shipping_discountObject



191
192
193
# File 'app/models/spree/order.rb', line 191

def shipping_discount
  shipment_adjustments.eligible.sum(:amount) * - 1
end

#shipping_eq_billing_address?Boolean

Returns:

  • (Boolean)


556
557
558
# File 'app/models/spree/order.rb', line 556

def shipping_eq_billing_address?
  (bill_address.empty? && ship_address.empty?) || bill_address.same_as?(ship_address)
end

#state_changed(name) ⇒ Object



489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
# File 'app/models/spree/order.rb', line 489

def state_changed(name)
  state = "#{name}_state"
  if persisted?
    old_state = self.send("#{state}_was")
    new_state = self.send(state)
    unless old_state == new_state
      self.state_changes.create(
        previous_state: old_state,
        next_state:     new_state,
        name:           name,
        user_id:        self.user_id
      )
    end
  end
end

#tax_addressObject

Returns the address for taxation based on configuration



237
238
239
# File 'app/models/spree/order.rb', line 237

def tax_address
  Spree::Config[:tax_using_ship_address] ? ship_address : bill_address
end

#tax_totalObject



630
631
632
# File 'app/models/spree/order.rb', line 630

def tax_total
  included_tax_total + additional_tax_total
end

#tax_zoneObject

Returns the relevant zone (if any) to be used for taxation purposes. Uses default tax zone unless there is a specific match



232
233
234
# File 'app/models/spree/order.rb', line 232

def tax_zone
  @tax_zone ||= Zone.match(tax_address) || Zone.default_tax
end

#to_paramObject



195
196
197
# File 'app/models/spree/order.rb', line 195

def to_param
  number.to_s.to_url.upcase
end

#update!Object



245
246
247
# File 'app/models/spree/order.rb', line 245

def update!
  updater.update
end

#update_line_items(line_item_params) ⇒ Object

moved from api order_decorator. This is a better place for it.



613
614
615
616
617
618
619
620
621
622
623
# File 'app/models/spree/order.rb', line 613

def update_line_items(line_item_params)
  return if line_item_params.blank?
  line_item_params.each_value do |attributes|
    if attributes[:id].present?
      self.line_items.find(attributes[:id]).update_attributes!(attributes)
    else
      self.line_items.create!(attributes)
    end
  end
  self.ensure_updated_shipments
end

#updaterObject



241
242
243
# File 'app/models/spree/order.rb', line 241

def updater
  @updater ||= OrderUpdater.new(self)
end

#valid_credit_cardsObject



390
391
392
393
# File 'app/models/spree/order.rb', line 390

def valid_credit_cards
  credit_card_ids = payments.from_credit_card.valid.pluck(:source_id).uniq
  CreditCard.where(id: credit_card_ids)
end