Class: Spree::Order

Inherits:
Base
  • Object
show all
Extended by:
DisplayMoney
Includes:
Core::TokenGenerator, NumberAsParam, AddressBook, Checkout, CurrencyUpdater, Payments, StoreCredit
Defined in:
app/models/spree/order.rb,
app/models/spree/order/checkout.rb,
app/models/spree/order/payments.rb,
app/models/spree/order/address_book.rb,
app/models/spree/order/store_credit.rb,
app/models/spree/order/currency_updater.rb

Defined Under Namespace

Modules: AddressBook, Checkout, CurrencyUpdater, Payments, StoreCredit

Constant Summary collapse

PAYMENT_STATES =
%w(balance_due credit_owed failed paid void)
SHIPMENT_STATES =
%w(backorder canceled partial pending ready shipped)
MONEY_THRESHOLD =
100_000_000
MONEY_VALIDATION =
{
  presence: true,
  numericality: {
    greater_than: -MONEY_THRESHOLD,
    less_than: MONEY_THRESHOLD,
    allow_blank: true
  },
  format: { with: /\A-?\d+(?:\.\d{1,2})?\z/, allow_blank: true }
}.freeze
POSITIVE_MONEY_VALIDATION =
MONEY_VALIDATION.deep_dup.tap do |validation|
  validation.fetch(:numericality)[:greater_than_or_equal_to] = 0
end.freeze
NEGATIVE_MONEY_VALIDATION =
MONEY_VALIDATION.deep_dup.tap do |validation|
  validation.fetch(:numericality)[:less_than_or_equal_to] = 0
end.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from DisplayMoney

money_methods

Methods included from NumberAsParam

#to_param

Methods included from Core::TokenGenerator

#generate_token

Methods included from AddressBook

#bill_address_attributes=, #bill_address_id=, #clone_billing_address, #clone_shipping_address, #ship_address_attributes=, #ship_address_id=

Methods included from StoreCredit

#could_use_store_credit?, #covered_by_store_credit?, #display_order_total_after_store_credit, #display_store_credit_remaining_after_capture, #display_total_applicable_store_credit, #display_total_applied_store_credit, #display_total_available_store_credit, #order_total_after_store_credit, #total_applicable_store_credit, #total_applied_store_credit, #total_available_store_credit, #using_store_credit?

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

belongs_to_required_by_default, page, spree_base_scopes

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.



61
62
63
# File 'app/models/spree/order.rb', line 61

def coupon_code
  @coupon_code
end

#temporary_addressObject

Returns the value of attribute temporary_address.



62
63
64
# File 'app/models/spree/order.rb', line 62

def temporary_address
  @temporary_address
end

#temporary_credit_cardObject

Returns the value of attribute temporary_credit_card.



62
63
64
# File 'app/models/spree/order.rb', line 62

def temporary_credit_card
  @temporary_credit_card
end

#use_billingObject

Returns the value of attribute use_billing.



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

def use_billing
  @use_billing
end

Class Method Details

.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



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

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

Instance Method Details

#all_inventory_units_returned?Boolean

Returns:

  • (Boolean)


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

def all_inventory_units_returned?
  inventory_units.all?(&:returned?)
end

#allow_cancel?Boolean

Returns:

  • (Boolean)


242
243
244
245
246
# File 'app/models/spree/order.rb', line 242

def allow_cancel?
  return false if !completed? || canceled?

  shipment_state.nil? || %w{ready backorder pending}.include?(shipment_state)
end

#amountObject

For compatiblity with Calculator::PriceSack



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

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

#apply_free_shipping_promotionsObject



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

def apply_free_shipping_promotions
  Spree::PromotionHandler::FreeShipping.new(self).activate
  shipments.each { |shipment| Spree::Adjustable::AdjustmentsUpdater.update(shipment) }
  create_shipment_tax_charge!
  update_with_updater!
end

#apply_unassigned_promotionsObject

Applies user promotions when login after filling the cart



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

def apply_unassigned_promotions
  ::Spree::PromotionHandler::Cart.new(self).activate
end

#approve!Object



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

def approve!
  update_column(:considered_risky, false)
end

#approved?Boolean

Returns:

  • (Boolean)


549
550
551
# File 'app/models/spree/order.rb', line 549

def approved?
  !!approved_at
end

#approved_by(user) ⇒ Object



539
540
541
542
543
544
545
546
547
# File 'app/models/spree/order.rb', line 539

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

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

Associates the specified user with the order.



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

def associate_user!(user, override_email = true)
  self.user           = user
  self.email          = user.email if override_email
  self.created_by   ||= user
  self.bill_address ||= user.bill_address.try(:clone)
  self.ship_address ||= user.ship_address.try(:clone)

  changes = slice(:user_id, :email, :created_by_id, :bill_address_id, :ship_address_id)

  # 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: self).update_all(changes)
end

#available_payment_methods(store = nil) ⇒ Object



373
374
375
# File 'app/models/spree/order.rb', line 373

def available_payment_methods(store = nil)
  @available_payment_methods ||= collect_payment_methods(store)
end

#backordered?Boolean

Returns:

  • (Boolean)


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

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

#can_add_coupon?Boolean

Returns:

  • (Boolean)


454
455
456
# File 'app/models/spree/order.rb', line 454

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

#can_approve?Boolean

Returns:

  • (Boolean)


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

def can_approve?
  !approved?
end

#can_ship?Boolean

Returns:

  • (Boolean)


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

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

#canceled_by(user) ⇒ Object



529
530
531
532
533
534
535
536
537
# File 'app/models/spree/order.rb', line 529

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

#cart_promo_totalBigDecimal

Returns item and whole order discount amount for Order without Shipment disccounts (eg. Free Shipping)

Returns:

  • (BigDecimal)


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

def cart_promo_total
  all_adjustments.eligible.nonzero.promotion.
    where.not(adjustable_type: 'Spree::Shipment').
    sum(:amount)
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)


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

def checkout_allowed?
  line_items.exists?
end

#collect_backend_payment_methodsObject



587
588
589
# File 'app/models/spree/order.rb', line 587

def collect_backend_payment_methods
  PaymentMethod.available_on_back_end.select { |pm| pm.available_for_order?(self) }
end

#completed?Boolean

Returns:

  • (Boolean)


184
185
186
# File 'app/models/spree/order.rb', line 184

def completed?
  completed_at.present?
end

#confirmation_required?Boolean

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

Returns:

  • (Boolean)


202
203
204
205
206
207
208
209
# File 'app/models/spree/order.rb', line 202

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.
    confirm?
end

#consider_riskObject



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

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

#considered_risky!Object



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

def considered_risky!
  update_column(:considered_risky, true)
end

#create_proposed_shipmentsObject



462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
# File 'app/models/spree/order.rb', line 462

def create_proposed_shipments
  all_adjustments.shipping.delete_all

  shipment_ids = shipments.map(&:id)
  StateChange.where(stateful_type: 'Spree::Shipment', stateful_id: shipment_ids).delete_all
  ShippingRate.where(shipment_id: shipment_ids).delete_all

  shipments.delete_all

  # Inventory Units which are not associated to any shipment (unshippable)
  # and are not returned or shipped should be deleted
  inventory_units.on_hand_or_backordered.delete_all

  self.shipments = Spree::Stock::Coordinator.new(self).shipments
end

#create_shipment_tax_charge!Object



286
287
288
# File 'app/models/spree/order.rb', line 286

def create_shipment_tax_charge!
  Spree::TaxRate.adjust(self, shipments) if shipments.any?
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.



281
282
283
284
# File 'app/models/spree/order.rb', line 281

def create_tax_charge!
  Spree::TaxRate.adjust(self, line_items)
  Spree::TaxRate.adjust(self, shipments) if shipments.any?
end

#credit_cardsObject



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

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

#deliver_order_confirmation_emailObject



363
364
365
366
# File 'app/models/spree/order.rb', line 363

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

#empty!Object



404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
# File 'app/models/spree/order.rb', line 404

def empty!
  if completed?
    raise Spree.t(:cannot_empty_completed_order)
  else
    line_items.destroy_all
    updater.update_item_count
    adjustments.destroy_all
    shipments.destroy_all
    state_changes.destroy_all
    order_promotions.destroy_all

    update_totals
    persist_totals
    restart_checkout_flow
    self
  end
end

#ensure_line_item_variants_are_not_discontinuedObject

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



384
385
386
387
388
389
390
391
392
# File 'app/models/spree/order.rb', line 384

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

#ensure_line_items_are_in_stockObject



394
395
396
397
398
399
400
401
402
# File 'app/models/spree/order.rb', line 394

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

#ensure_store_presenceObject



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

def ensure_store_presence
  self.store ||= Spree::Store.default
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



495
496
497
498
499
500
501
# File 'app/models/spree/order.rb', line 495

def ensure_updated_shipments
  if shipments.any? && !completed?
    shipments.destroy_all
    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



335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
# File 'app/models/spree/order.rb', line 335

def finalize!
  # lock all adjustments (coupon promotions, etc.)
  all_adjustments.each(&: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



272
273
274
275
276
277
# File 'app/models/spree/order.rb', line 272

def find_line_item_by_variant(variant, options = {})
  line_items.detect do |line_item|
    line_item.variant_id == variant.id &&
      Spree::Dependencies.cart_compare_line_items_service.constantize.new.call(order: self, line_item: line_item, options: options).value
  end
end

#fulfill!Object



357
358
359
360
361
# File 'app/models/spree/order.rb', line 357

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

#fully_discounted?Boolean Also known as: fully_discounted

determines whether the inventory is fully discounted

Returns

  • true if inventory amount is the exact negative of inventory related adjustments

  • false otherwise

Returns:

  • (Boolean)


596
597
598
# File 'app/models/spree/order.rb', line 596

def fully_discounted?
  adjustment_total + line_items.map(&:final_amount).sum == 0.0
end

Returns:

  • (Boolean)


582
583
584
585
# File 'app/models/spree/order.rb', line 582

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)


422
423
424
# File 'app/models/spree/order.rb', line 422

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

#insufficient_stock_linesObject



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

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

#is_risky?Boolean

Returns:

  • (Boolean)


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

def is_risky?
  !payments.risky.empty?
end

#log_state_changes(state_name:, old_state:, new_state:) ⇒ Object



437
438
439
440
441
442
443
444
# File 'app/models/spree/order.rb', line 437

def log_state_changes(state_name:, old_state:, new_state:)
  state_changes.create(
    previous_state: old_state,
    next_state: new_state,
    name: state_name,
    user_id: user_id
  )
end

#mergerObject



234
235
236
# File 'app/models/spree/order.rb', line 234

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

#nameObject



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

def name
  if (address = bill_address || ship_address)
    address.full_name
  end
end

#outstanding_balanceObject



297
298
299
300
301
302
303
304
305
306
307
# File 'app/models/spree/order.rb', line 297

def outstanding_balance
  if canceled?
    -1 * payment_total
  elsif refunds.exists?
    # If refund has happened add it back to total to prevent balance_due payment state
    # See: https://github.com/spree/spree/issues/6229 & https://github.com/spree/spree/issues/8136
    total - (payment_total + refunds.sum(:amount))
  else
    total - payment_total
  end
end

#outstanding_balance?Boolean

Returns:

  • (Boolean)


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

def outstanding_balance?
  outstanding_balance != 0
end

#paid?Boolean

Helper methods for checkout steps

Returns:

  • (Boolean)


369
370
371
# File 'app/models/spree/order.rb', line 369

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)


197
198
199
# File 'app/models/spree/order.rb', line 197

def payment_required?
  total.to_f > 0.0
end

#payments_attributes=(attributes) ⇒ Object



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

def payments_attributes=(attributes)
  validate_payments_attributes(attributes)
  super(attributes)
end

#pre_tax_item_amountObject

Sum of all line item amounts pre-tax



176
177
178
# File 'app/models/spree/order.rb', line 176

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

#promo_codeObject



601
602
603
# File 'app/models/spree/order.rb', line 601

def promo_code
  promotions.pluck(:code).compact.first
end

#quantityObject



578
579
580
# File 'app/models/spree/order.rb', line 578

def quantity
  line_items.sum(:quantity)
end

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



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

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

#refresh_shipment_rates(shipping_method_filter = ShippingMethod::DISPLAY_ON_FRONT_END) ⇒ Object



511
512
513
# File 'app/models/spree/order.rb', line 511

def refresh_shipment_rates(shipping_method_filter = ShippingMethod::DISPLAY_ON_FRONT_END)
  shipments.map { |s| s.refresh_rates(shipping_method_filter) }
end

#reload(options = nil) ⇒ Object



569
570
571
572
# File 'app/models/spree/order.rb', line 569

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

#restart_checkout_flowObject



503
504
505
506
507
508
509
# File 'app/models/spree/order.rb', line 503

def restart_checkout_flow
  update_columns(
    state: 'cart',
    updated_at: Time.current
  )
  next! unless line_items.empty?
end

#set_shipments_costObject



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

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

#shipped?Boolean

Returns:

  • (Boolean)


458
459
460
# File 'app/models/spree/order.rb', line 458

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

#shipping_discountObject



180
181
182
# File 'app/models/spree/order.rb', line 180

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

#shipping_eq_billing_address?Boolean

Returns:

  • (Boolean)


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

def shipping_eq_billing_address?
  bill_address == ship_address
end

#state_changed(name) ⇒ Object



426
427
428
429
430
431
432
433
434
435
# File 'app/models/spree/order.rb', line 426

def state_changed(name)
  state = "#{name}_state"
  if persisted?
    old_state = send("#{state}_was")
    new_state = send(state)
    unless old_state == new_state
      log_state_changes(state_name: name, old_state: old_state, new_state: new_state)
    end
  end
end

#tax_addressObject

Returns the address for taxation based on configuration



222
223
224
# File 'app/models/spree/order.rb', line 222

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

#tax_totalObject



574
575
576
# File 'app/models/spree/order.rb', line 574

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



217
218
219
# File 'app/models/spree/order.rb', line 217

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

#update_line_item_prices!Object



290
291
292
293
294
295
# File 'app/models/spree/order.rb', line 290

def update_line_item_prices!
  transaction do
    line_items.reload.each(&:update_price)
    save!
  end
end

#update_with_updater!Object



230
231
232
# File 'app/models/spree/order.rb', line 230

def update_with_updater!
  updater.update
end

#updaterObject



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

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

#valid_coupon_promotionsObject



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

def valid_coupon_promotions
  promotions.
    where(id: valid_promotion_ids).
    coupons
end

#valid_credit_cardsObject



328
329
330
331
# File 'app/models/spree/order.rb', line 328

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

#valid_promotion_idsObject



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

def valid_promotion_ids
  all_adjustments.eligible.nonzero.promotion.map { |a| a.source.promotion_id }.uniq
end

#valid_promotionsObject



621
622
623
# File 'app/models/spree/order.rb', line 621

def valid_promotions
  order_promotions.where(promotion_id: valid_promotion_ids).uniq(&:promotion_id)
end

#validate_payments_attributes(attributes) ⇒ Object



610
611
612
613
614
615
616
617
618
619
# File 'app/models/spree/order.rb', line 610

def validate_payments_attributes(attributes)
  # Ensure the payment methods specified are allowed for this user
  payment_methods = Spree::PaymentMethod.where(id: available_payment_methods.map(&:id))
  attributes.each do |payment_attributes|
    payment_method_id = payment_attributes[:payment_method_id]

    # raise RecordNotFound unless it is an allowed payment method
    payment_methods.find(payment_method_id) if payment_method_id
  end
end