Class: Spree::Order

Constant Summary collapse

PAYMENT_STATUSES =

What Orders::UpdateStatuses derives — the only writer of the column.

%w(none authorized partially_paid paid partially_refunded refunded overcharged voided).freeze
PAYMENT_STATES =
Deprecated.

legacy machine vocabulary; rows carrying it stay valid until the status migration rewrites them. Removed in 6.3.

%w(balance_due credit_owed failed paid void)
FULFILLMENT_STATUSES =
%w(backorder canceled partial unfulfilled fulfilled delivered pending ready shipped)
SHIPMENT_STATES =
Deprecated.

legacy name — remove in 6.3 together with the 'shipped' value

FULFILLMENT_STATUSES
LINE_ITEM_REMOVABLE_STATES =
Deprecated.

legacy machine vocabulary — line-item removability is completion-based since 6.0; removed in 6.3.

%w(cart address delivery payment confirm resumed)
STATUSES =
%w[draft placed canceled].freeze
ASSOCIATED_CUSTOMER_ATTRIBUTES =
[:customer_id, :email, :bill_address_id, :ship_address_id]

Constants included from Purchase::DeprecatedAliases

Purchase::DeprecatedAliases::RENAMED_ATTRIBUTES, Purchase::DeprecatedAliases::RENAMED_METHODS, Purchase::DeprecatedAliases::RENAMED_PAYMENT_METHOD_READERS

Constants included from Purchase::Validations

Purchase::Validations::MONEY_THRESHOLD, Purchase::Validations::MONEY_VALIDATION, Purchase::Validations::NEGATIVE_MONEY_VALIDATION, Purchase::Validations::POSITIVE_MONEY_VALIDATION

Constants included from Purchase::PurchaseOrder

Purchase::PurchaseOrder::MAX_PO_DOCUMENT_SIZE, Purchase::PurchaseOrder::PO_DOCUMENT_CONTENT_TYPES

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from DisplayMoney

money_methods

Methods included from HasExternalReferences

#assign_external_references, #external_id_for, #set_external_id

Methods included from Metadata

#private_metadata, #private_metadata=

Methods included from Purchase::Warnings

#lock!

Methods included from Purchase::Lifecycle

#backordered?, #can_be_deleted?, #completed?, #guest_checkout_disallowed?, #in_checkout?

Methods included from Purchase::Totals

#amount, #amount_due_at_checkout, #fulfillment_discount, #gift_amount, #outstanding_balance?, #paid?, #quantity, #refresh_payment_total!

Methods included from Purchase::Addresses

#assign_default_addresses!, #bill_address_attributes=, #bill_address_id=, #can_propose_deliveries?, #clone_billing_address, #clone_shipping_address, #owns_address?, #selectable_address, #selectable_addresses, #ship_address_attributes=, #ship_address_id=, #shipping_address_required?, #shipping_eq_billing_address?, #use_billing=, #use_billing?, #use_shipping?

Methods included from Purchase::PaymentProcessing

#amount_left_to_pay, #authorize_payments!, #capture_payments!, #confirmation_required?, #payment_methods, #payment_required?, #pending_payments, #process_payments!, #unprocessed_payments

Methods included from Purchase::LineItemLookup

#find_line_item_by_variant, #quantity_of

Methods included from Purchase::LineItemCurrencies

#homogenize_line_item_currencies, #price_from_line_item, #update_line_item_currencies!, #update_line_item_price!

Methods included from Purchase::GiftCards

#apply_gift_card, #gift_card_total, #recalculate_gift_card, #redeem_gift_card, #remove_gift_card, #total_minus_gift_cards

Methods included from Purchase::StoreCredits

#add_store_credit_payments, #amount_due, #available_store_credits, #could_use_store_credit?, #covered_by_store_credit?, #display_order_total_after_store_credit, #display_store_credit_remaining_after_capture, #display_store_credit_total, #display_total_applicable_store_credit, #display_total_applied_store_credit, #display_total_available_store_credit, #display_total_minus_store_credits, #order_total_after_store_credit, #remove_store_credit_payments, #store_credit_total, #total_applicable_store_credit, #total_applied_store_credit, #total_available_store_credit, #total_minus_store_credits, #using_store_credit?

Methods included from Purchase::Taxation

#pre_tax_item_amount, #pre_tax_total, #resolved_tax_identifier, #tax_address, #tax_country, #tax_estimate_inputs, #tax_inclusive?, #tax_provider, #tax_total, #taxable_items, #usable_exemptions

Methods included from Purchase::DigitalItems

#delivery_step_required?, #digital?, #digital_line_items, #digital_links, #some_digital?, #with_digital_assets?

Methods included from Purchase::Locale

#ensure_locale, #locale_must_be_supported_by_store

Methods included from Purchase::Currency

#currency_must_be_supported_by_store, #ensure_currency

Methods included from Purchase::Market

#ensure_market_presence, #resolve_market_from_currency

Methods included from Purchase::PurchaseOrder

#copy_po_document_from!, #po_number_required?

Methods included from Purchase::QuantityRules

#below_order_minimum?, #order_minimum, #order_minimum_amount, #order_minimum_shortfall, #quantity_rule_violation, #quantity_rule_violations, #quantity_rules_for, #quantity_rules_resolver, #reload, #staff_initiated?

Methods included from Purchase::Freight

#freight_summary, #reload

Methods included from Purchase::Company

#b2b?, #company_legal_entity, #resolved_company

Methods included from Purchase::Channel

#ensure_channel_presence

Methods included from SanitizableRichText

declaring_models

Methods included from ActedBy

#acted_by_prefixed_id, #acted_by_type, assume_admin_actor_type, columns_for, models, registered_model_names

Instance Attribute Details

#notify_customer ⇒ Object

Set to false on admin-initiated flows to suppress customer-facing emails.



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

def notify_customer
  @notify_customer
end

Class Method Details

.find_by_param(param) ⇒ Spree::Order?

Find an order by prefixed ID first, falling back to number, then integer id for backwards compatibility

Parameters:

  • param (String) —

    the prefixed ID, number, or integer id to search for

Returns:



393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
# File 'app/models/spree/order.rb', line 393

def self.find_by_param(param)
  return nil if param.blank?

  # Try prefixed ID first (new format)
  if param.to_s.include?('_')
    decoded = decode_prefixed_id(param)
    order = find_by(id: decoded) if decoded
    return order if order
  end

  # Try number (legacy format)
  order = find_by(number: param)
  return order if order

  # Fall back to id (numeric legacy format) - only if param looks like an integer
  find_by(id: param) if param.to_s.match?(/\A\d+\z/)
end

.find_by_param!(param) ⇒ Spree::Order

Find an order by prefixed ID first, falling back to number, then integer id for backwards compatibility Raises ActiveRecord::RecordNotFound if not found

Parameters:

  • param (String) —

    the prefixed ID, number, or integer id to search for

Returns:

Raises:

  • (ActiveRecord::RecordNotFound) —

    if order not found



416
417
418
# File 'app/models/spree/order.rb', line 416

def self.find_by_param!(param)
  find_by_param(param) || raise(ActiveRecord::RecordNotFound.new("Couldn't find Order with param=#{param}"))
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



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

def self.register_update_hook(hook)
  Spree::Deprecation.warn('Order.register_update_hook is deprecated and will be removed in Spree 6.3')
  update_hooks.add(hook)
end

.search(query) ⇒ Object



359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
# File 'app/models/spree/order.rb', line 359

def self.search(query)
  # Ransack passes `true` when the scope is called as a bare flag (`q[search]=1`)
  return none unless query.is_a?(String) && query.present?

  sanitized_query = sanitize_query_for_search(query)

  query_pattern = "%#{sanitized_query}%"

  conditions = []
  conditions << arel_table[:number].lower.matches(query_pattern)
  # An accountant holds one reference or the other — ours or their own
  # purchase order — and both have to find the same transaction.
  conditions << arel_table[:po_number].lower.matches(query_pattern)

  conditions << search_condition(Spree::Address, :first_name, sanitized_query)
  conditions << search_condition(Spree::Address, :last_name, sanitized_query)

  full_name = NameOfPerson::PersonName.full(sanitized_query)

  if full_name.first.present? && full_name.last.present?
    conditions << search_condition(Spree::Address, :first_name, full_name.first)
    conditions << search_condition(Spree::Address, :last_name, full_name.last)
  end

  # The exact match goes through the model, so it still finds an order in
  # an app that encrypts email, where SQL only ever sees ciphertext.
  left_joins(:bill_address).where(email: query).
    or(left_joins(:bill_address).where(arel_table[:email].lower.eq(query.downcase))).
    or(where(conditions.reduce(:or)))
end

Instance Method Details

#all_inventory_units_returned? ⇒ Boolean

Returns:

  • (Boolean)


668
669
670
# File 'app/models/spree/order.rb', line 668

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

#all_line_items_invalid? ⇒ Boolean

Checks if all line items cannot be shipped

Returns:

  • (Boolean)


1045
1046
1047
# File 'app/models/spree/order.rb', line 1045

def all_line_items_invalid?
  line_items_without_delivery_rates.size == line_items.count
end

#allow_cancel? ⇒ Boolean Also known as: can_cancel?

Returns:

  • (Boolean)


661
662
663
664
665
# File 'app/models/spree/order.rb', line 661

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

  fulfillment_status.nil? || %w{unfulfilled backorder canceled}.include?(fulfillment_status)
end

#analytics_subtotal ⇒ Float

Returns the subtotal used for analytics integrations It's a sum of the item total and the promo total

Returns:

  • (Float) —

    a JSON number, as analytics providers expect



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

def analytics_subtotal
  (item_total + line_items.sum(:discount_total)).to_f
end

#apply_free_shipping_promotions ⇒ Object



1049
1050
1051
1052
# File 'app/models/spree/order.rb', line 1049

def apply_free_shipping_promotions
  Spree::PromotionHandler::FreeShipping.new(self).activate
  recalculate_totals!
end

#apply_unassigned_promotions ⇒ Object

Applies user promotions when login after filling the cart



1055
1056
1057
# File 'app/models/spree/order.rb', line 1055

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

#approve! ⇒ Spree::ServiceModule::Result

Approves the order without recording an approver. Delegates to Spree::Orders::Approve service.



1174
1175
1176
# File 'app/models/spree/order.rb', line 1174

def approve!
  Spree.order_approve_service.call(order: self)
end

#approved? ⇒ Boolean

Returns:

  • (Boolean)


1150
1151
1152
# File 'app/models/spree/order.rb', line 1150

def approved?
  !!approved_at
end

#approved_by(actor = nil) ⇒ Spree::ServiceModule::Result

Approves the order and records the approver. Delegates to Spree::Orders::Approve service.

Parameters:

  • actor (Object, nil) (defaults to: nil) —

    who approved it — an admin user or an API key (see Spree.actor_classes)

Returns:



1146
1147
1148
# File 'app/models/spree/order.rb', line 1146

def approved_by(actor = nil)
  Spree.order_approve_service.call(order: self, approver: actor)
end

#associate_customer!(customer, override_email = true) ⇒ Spree::ServiceModule::Result

Associates the specified user with the order. Delegates to Carts::Associate service.

Parameters:

  • customer (Spree.customer_class) —

    the customer to associate with the order

  • override_email (Boolean) (defaults to: true) —

    whether to override the order email with the customer's email

Returns:



678
679
680
# File 'app/models/spree/order.rb', line 678

def associate_customer!(customer, override_email = true)
  Spree.cart_associate_service.call(guest_cart: self, customer: customer, override_email: override_email)
end

#backordered_variants ⇒ Array<Spree::Variant>

Returns the backordered variants for the order

Returns:



840
841
842
843
844
845
846
# File 'app/models/spree/order.rb', line 840

def backordered_variants
  variants.
    where(track_inventory: true).
    joins(:stock_levels, :product).
    where(Spree::StockLevel.table_name => { backorderable: true }).
    where("#{Spree::StockLevel.table_name}.count_on_hand - #{Spree::StockLevel.table_name}.allocated_count <= ?", 0)
end

#can_add_coupon? ⇒ Boolean

Returns:

  • (Boolean)


923
924
925
926
927
928
# File 'app/models/spree/order.rb', line 923

def can_add_coupon?
  Spree::Deprecation.warn(
    'Spree::Order#can_add_coupon? is deprecated and will be removed in Spree 6.3. Use Spree::Promotion.order_activatable? instead.'
  )
  Spree::Promotion.order_activatable?(self)
end

#can_approve? ⇒ Boolean

Returns:

  • (Boolean)


1154
1155
1156
# File 'app/models/spree/order.rb', line 1154

def can_approve?
  !approved?
end

#can_ship? ⇒ Boolean

Returns:

  • (Boolean)


848
849
850
# File 'app/models/spree/order.rb', line 848

def can_ship?
  placed?
end

#cancel ⇒ Object

Machine-free lifecycle: cancellation runs through the Spree::Orders::Cancel workflow. There is no way back — a canceled order stays canceled, as it does on every comparable platform.



1132
1133
1134
# File 'app/models/spree/order.rb', line 1132

def cancel
  Spree.order_cancel_workflow.call(order: self).success?
end

#cancel! ⇒ Object



1136
1137
1138
# File 'app/models/spree/order.rb', line 1136

def cancel!
  cancel || raise(ActiveRecord::RecordInvalid.new(self))
end

#canceled? ⇒ Boolean

Returns:

  • (Boolean)


463
464
465
# File 'app/models/spree/order.rb', line 463

def canceled?
  status == 'canceled'
end

#canceled_by(user, canceled_at = nil) ⇒ Spree::ServiceModule::Result

Deprecated.

Call Spree.order_cancel_workflow directly — it exposes the full cancellation vocabulary (reason, note, refund_payments, notify_customer) this wrapper cannot pass through.

Cancels the order and records the canceler. Delegates to Spree::Orders::Cancel workflow.

Parameters:

  • user (Spree.customer_class, nil) —

    the user who canceled the order

  • canceled_at (Time, nil) (defaults to: nil) —

    the time of cancellation (defaults to current time)

Returns:



1122
1123
1124
1125
1126
1127
# File 'app/models/spree/order.rb', line 1122

def canceled_by(user, canceled_at = nil)
  Spree::Deprecation.warn(
    'Spree::Order#canceled_by is deprecated and will be removed in Spree 6.3. Use Spree.order_cancel_workflow (Spree::Orders::Cancel) instead.'
  )
  Spree.order_cancel_workflow.call(order: self, canceler: user, canceled_at: canceled_at)
end

#cart? ⇒ Boolean

Deprecated.

machine vocabulary — data-derived bridge for the 6.0 transition, removed in 6.3. An order is "cart-like" while a draft with no checkout data.

Returns:

  • (Boolean)


470
471
472
# File 'app/models/spree/order.rb', line 470

def cart?
  draft? && !completed? && email.blank? && ship_address_id.blank?
end

#cart_promo_total ⇒ BigDecimal

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

Returns:

  • (BigDecimal)


1220
1221
1222
1223
1224
1225
# File 'app/models/spree/order.rb', line 1220

def cart_promo_total
  Spree::Deprecation.warn(
    'Spree::Order#cart_promo_total is deprecated and will be removed in Spree 6.3. Please use order.cart.discount_total instead'
  )
  discounts.promotion.nonzero.for_line_items.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)


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

def checkout_allowed?
  line_items.exists?
end

#checkout_step_index(step) ⇒ Object

Deprecated.

See #checkout_steps; removed in 6.3.



129
130
131
132
133
134
135
# File 'app/models/spree/order.rb', line 129

def checkout_step_index(step)
  Spree::Deprecation.warn(
    'Spree::Order#checkout_step_index is deprecated and will be removed in Spree 6.3. ' \
    'Checkout steps belong to Spree::Cart — ask the cart before it is completed.'
  )
  Spree::Checkout::Registry.step_names_for(self).index(step).to_i
end

#checkout_steps ⇒ Object

Deprecated.

Checkout steps belong to Spree::Cart; removed in 6.3.



111
112
113
114
115
116
117
# File 'app/models/spree/order.rb', line 111

def checkout_steps
  Spree::Deprecation.warn(
    'Spree::Order#checkout_steps is deprecated and will be removed in Spree 6.3. ' \
    'Checkout steps belong to Spree::Cart — ask the cart before it is completed.'
  )
  Spree::Checkout::Registry.step_names_for(self)
end

#collect_backend_payment_methods ⇒ Object



1178
1179
1180
# File 'app/models/spree/order.rb', line 1178

def collect_backend_payment_methods
  store.payment_methods.active.select { |pm| pm.available_for_order?(self) }
end

#completed_checkout_steps ⇒ Object

Deprecated.

See #checkout_steps; removed in 6.3. Every step is behind an order, so this is the whole list bar 'complete'.



158
159
160
161
162
163
164
# File 'app/models/spree/order.rb', line 158

def completed_checkout_steps
  Spree::Deprecation.warn(
    'Spree::Order#completed_checkout_steps is deprecated and will be removed in Spree 6.3. ' \
    "An order is past checkout, so every step bar 'complete' is behind it."
  )
  Spree::Checkout::Registry.step_names_for(self).reject { |step| step == 'complete' }
end

#consider_risk ⇒ Object



1159
1160
1161
# File 'app/models/spree/order.rb', line 1159

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

#considered_risky! ⇒ Object



1163
1164
1165
1166
1167
1168
# File 'app/models/spree/order.rb', line 1163

def considered_risky!
  update_column(:considered_risky, true)

  # Manually publish update event since update_column bypasses callbacks
  publish_event('order.updated')
end

#create_shipment_tax_charge! ⇒ Object



700
701
702
# File 'app/models/spree/order.rb', line 700

def create_shipment_tax_charge!
  tax_provider.estimate(self, fulfillments.to_a, **tax_estimate_inputs) if fulfillments.any?
end

#create_tax_charge! ⇒ Object

Re-estimates tax through the configured provider (writes TaxLine rows with replace-all semantics).



696
697
698
# File 'app/models/spree/order.rb', line 696

def create_tax_charge!
  tax_provider.estimate(self, **tax_estimate_inputs)
end

#current_checkout_step ⇒ Object

Deprecated.

See #checkout_steps; removed in 6.3. An order has no outstanding step, so this is always 'complete'.



139
140
141
142
143
144
145
# File 'app/models/spree/order.rb', line 139

def current_checkout_step
  Spree::Deprecation.warn(
    'Spree::Order#current_checkout_step is deprecated and will be removed in Spree 6.3. ' \
    "An order is past checkout, so this is always 'complete'."
  )
  'complete'
end

#delivery_method ⇒ Spree::DeliveryMethod

Returns first available delivery method from the fulfillments Useful for analytics and CSV exports



1100
1101
1102
1103
1104
1105
1106
1107
# File 'app/models/spree/order.rb', line 1100

def delivery_method
  # This query will select the first available delivery method from the fulfillments.
  # It will use subquery to first select the delivery method id from the fulfillments' selected_delivery_rate.
  Spree::DeliveryMethod.
    where(id: fulfillments.with_selected_delivery_method.limit(1).pluck(:delivery_method_id)).
    limit(1).
    first
end

#disassociate_customer! ⇒ Object



682
683
684
685
686
# File 'app/models/spree/order.rb', line 682

def disassociate_customer!
  nullified_attributes = ASSOCIATED_CUSTOMER_ATTRIBUTES.index_with(nil)

  update!(nullified_attributes)
end

#disassociate_user! ⇒ Object

Deprecated.

Use #disassociate_customer!; removed in 6.3.



689
690
691
692
# File 'app/models/spree/order.rb', line 689

def disassociate_user!
  Spree::Deprecation.warn('Spree::Order#disassociate_user! is deprecated and will be removed in Spree 6.3. Use #disassociate_customer! instead.')
  disassociate_customer!
end

#draft? ⇒ Boolean

Returns:

  • (Boolean)


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

def draft?
  status == 'draft'
end

#email_required? ⇒ Boolean

Returns:

  • (Boolean)


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

def email_required?
  require_email
end

#ensure_line_item_variants_are_not_discontinued ⇒ Object

Deprecated.

Completion validation lives in Checkout::DefaultRequirements (the discontinued stock error). Removed in 6.3.

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



885
886
887
888
889
890
891
892
893
894
895
896
# File 'app/models/spree/order.rb', line 885

def ensure_line_item_variants_are_not_discontinued
  Spree::Deprecation.warn(
    'Spree::Order#ensure_line_item_variants_are_not_discontinued is deprecated and will be removed in Spree 6.3. ' \
    'Completion validation lives in Spree::Checkout::Requirements.'
  )
  if line_items.any? { |li| !li.variant || li.variant.discontinued? }
    errors.add(:base, :discontinued_variants_present, message: I18n.t('spree.discontinued_variants_present'))
    false
  else
    true
  end
end

#ensure_line_items_are_in_stock ⇒ Object

Deprecated.

Completion validation lives in Checkout::DefaultRequirements (the out_of_stock stock error). Removed in 6.3.



901
902
903
904
905
906
907
908
909
910
911
912
# File 'app/models/spree/order.rb', line 901

def ensure_line_items_are_in_stock
  Spree::Deprecation.warn(
    'Spree::Order#ensure_line_items_are_in_stock is deprecated and will be removed in Spree 6.3. ' \
    'Completion validation lives in Spree::Checkout::Requirements.'
  )
  if insufficient_stock_lines.present?
    errors.add(:base, :insufficient_stock_lines_present, message: I18n.t('spree.insufficient_stock_lines_present'))
    false
  else
    true
  end
end

#ensure_updated_fulfillments ⇒ Object

Rebuilds stale fulfillments from the current items, keeping the chosen rates. The first ones are Spree::Orders::BuildFulfillments' to build.



1061
1062
1063
1064
1065
1066
1067
1068
# File 'app/models/spree/order.rb', line 1061

def ensure_updated_fulfillments
  if fulfillments.any? && !completed?
    rebuild_fulfillments!

    # Nothing here saves the order, so its update event is published by hand.
    publish_event('order.updated')
  end
end

#final_checkout_step ⇒ Object

Deprecated.

See #checkout_steps; removed in 6.3.



148
149
150
151
152
153
154
# File 'app/models/spree/order.rb', line 148

def final_checkout_step
  Spree::Deprecation.warn(
    'Spree::Order#final_checkout_step is deprecated and will be removed in Spree 6.3. ' \
    'Checkout steps belong to Spree::Cart — ask the cart before it is completed.'
  )
  Spree::Checkout::Registry.step_names_for(self).reject { |step| step == 'complete' }.last || 'address'
end

#finalize! ⇒ Object

Deprecated.

Completion lives in Spree::Orders::Complete (checkout reaches it through Spree.carts_complete_workflow). Removed in 6.3.

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



860
861
862
863
864
865
866
# File 'app/models/spree/order.rb', line 860

def finalize!
  Spree::Deprecation.warn(
    'Spree::Order#finalize! is deprecated and will be removed in Spree 6.3. ' \
    'Completion runs through Spree.order_complete_workflow (Spree::Orders::Complete).'
  )
  Spree.order_complete_workflow.call(order: self, payment_pending: true, validated: true)
end

#fulfill! ⇒ Object



868
869
870
871
# File 'app/models/spree/order.rb', line 868

def fulfill!
  save!
  update_statuses!
end

#full_name ⇒ Object



815
816
817
818
819
820
821
# File 'app/models/spree/order.rb', line 815

def full_name
  @full_name ||= if customer.present? && customer.name.present?
                   customer.full_name
                 else
                   billing_address&.full_name || email
                 end
end

#fully_delivered? ⇒ Boolean

True when every fulfillment reached confirmed receipt — the signal order.delivered publishes on.

Returns:

  • (Boolean)


943
944
945
946
# File 'app/models/spree/order.rb', line 943

def fully_delivered?
  total = fulfillments.size
  total.positive? && fulfillments.delivered.size == total
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)


1188
1189
1190
# File 'app/models/spree/order.rb', line 1188

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

#fully_fulfilled? ⇒ Boolean

True when every fulfillment has left the merchant's hands — the signal order.fulfilled publishes on. delivered counts: it is downstream of fulfilled, so a delivered order must not read as un-fulfilled.

Returns:

  • (Boolean)


937
938
939
# File 'app/models/spree/order.rb', line 937

def fully_fulfilled?
  fulfillments.fulfilled_or_delivered.size == fulfillments.size
end

#fully_shipped? ⇒ Boolean

Deprecated.

Use #fully_fulfilled?; removed in 6.3.

Returns:

  • (Boolean)


949
950
951
952
# File 'app/models/spree/order.rb', line 949

def fully_shipped?
  Spree::Deprecation.warn('Spree::Order#fully_shipped? is deprecated and will be removed in Spree 6.3. Use #fully_fulfilled? instead.')
  fully_fulfilled?
end

#grouped? ⇒ Boolean

Returns whether this order was placed alongside others in one checkout, and therefore shares their payment.

Returns:

  • (Boolean) —

    whether this order was placed alongside others in one checkout, and therefore shares their payment



784
785
786
# File 'app/models/spree/order.rb', line 784

def grouped?
  order_group_id.present?
end

#has_checkout_step?(step) ⇒ Boolean

Deprecated.

See #checkout_steps; removed in 6.3.

Returns:

  • (Boolean)


120
121
122
123
124
125
126
# File 'app/models/spree/order.rb', line 120

def has_checkout_step?(step)
  Spree::Deprecation.warn(
    'Spree::Order#has_checkout_step? is deprecated and will be removed in Spree 6.3. ' \
    'Checkout steps belong to Spree::Cart — ask the cart before it is completed.'
  )
  step.present? && Spree::Checkout::Registry.step_names_for(self).include?(step.to_s)
end

#has_free_shipping? ⇒ Boolean

Returns:

  • (Boolean)


1227
1228
1229
# File 'app/models/spree/order.rb', line 1227

def has_free_shipping?
  discounts.promotion.for_fulfillments.exists?
end

#inferred_preferred_stock_location_id ⇒ Integer?

Cascade for the preferred_location rule kind. Channel and B2B sources are layered in by their respective plans.

Returns:

  • (Integer, nil)


1007
1008
1009
1010
# File 'app/models/spree/order.rb', line 1007

def inferred_preferred_stock_location_id
  preferred_stock_location_id.presence ||
    created_by&.try(:preferred_stock_location_id)
end

#insufficient_stock_lines ⇒ Object



875
876
877
# File 'app/models/spree/order.rb', line 875

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

#is_risky? ⇒ Boolean

Returns:

  • (Boolean)


1109
1110
1111
# File 'app/models/spree/order.rb', line 1109

def is_risky?
  !payments.risky.empty?
end

#line_items_without_delivery_rates ⇒ Array<Spree::LineItem>

Returns line items that have no delivery rates

Deliberately not memoized: callers destroy fulfillments between reads (see #ensure_available_delivery_rates), so a cached value would describe fulfillments that no longer exist.

Returns:



1027
1028
1029
1030
1031
# File 'app/models/spree/order.rb', line 1027

def line_items_without_delivery_rates
  fulfillments.map do |fulfillment|
    fulfillment.manifest.map(&:line_item) if fulfillment.delivery_rates.blank?
  end.flatten.compact
end

#line_items_without_shipping_rates ⇒ Object

Deprecated.


1034
1035
1036
1037
1038
1039
1040
# File 'app/models/spree/order.rb', line 1034

def line_items_without_shipping_rates
  Spree::Deprecation.warn(
    'Spree::Order#line_items_without_shipping_rates is deprecated and will be removed in Spree 6.3. ' \
    'Use #line_items_without_delivery_rates instead.'
  )
  line_items_without_delivery_rates
end

#merger ⇒ Object

Deprecated.

Use Carts::Merge; removed in 6.3.



656
657
658
# File 'app/models/spree/order.rb', line 656

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

#name ⇒ Object



809
810
811
812
813
# File 'app/models/spree/order.rb', line 809

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

#net_captured_total ⇒ BigDecimal

What has been captured against this order, net of refunds.

Read from the share rows rather than the payment_total they are summed into, since a caller about to move money needs what they say now.

Returns:

  • (BigDecimal)


769
770
771
772
773
# File 'app/models/spree/order.rb', line 769

def net_captured_total
  return payment_total unless grouped?

  payment_splits.sum(&:net_captured_amount)
end

#order_level_promo_total ⇒ BigDecimal

Sum of the eligible promotion adjustments applied to the order itself (whole-order discounts created by Promotion::Actions::CreateAdjustment, distributed proportionally across line items), as opposed to promotions applied to individual line items or fulfillments. Zero or negative.

Returns:

  • (BigDecimal)


433
434
435
# File 'app/models/spree/order.rb', line 433

def order_level_promo_total
  discounts.promotion.where(promotion_action_id: promotion_actions_of_scope(:order)).sum(:amount)
end

#order_refunded? ⇒ Boolean

Checks if the order is fully refunded

Returns:

  • (Boolean)


481
482
483
484
485
486
# File 'app/models/spree/order.rb', line 481

def order_refunded?
  return false if total_quantity.zero?
  return false if refunds_total.zero?

  payment_state.in?(%w[void failed]) || refunds_total == total_minus_store_credits - additional_tax_total.abs
end

#order_routing_strategy ⇒ Spree::OrderRouting::Strategy::Base

Resolves the routing strategy from the channel override first, then the store default. Only a registered Spree::OrderRouting::Strategy::Base subclass is used; any other value (an unregistered/typo'd class, or a strategy that was unregistered after being persisted) is logged and skipped rather than raised, falling back to the default Rules strategy so a misconfiguration can't take down cart display or checkout.



995
996
997
998
999
1000
1001
# File 'app/models/spree/order.rb', line 995

def order_routing_strategy
  klass = valid_order_routing_strategy_class(channel&.preferred_order_routing_strategy) ||
          valid_order_routing_strategy_class(store.preferred_order_routing_strategy) ||
          Spree::OrderRouting::Strategy::Rules

  klass.new(order: self)
end

#outstanding_balance ⇒ Object

Refunds are netted out of payment_total by Spree::Carts::RecalculateTotals, which is right for money handed back for nothing. A refund for goods that came back on a return, claim or exchange also settles what the customer owed for them, so it is added back here — the job the legacy reimbursement total did. Without it every refunded return read as a balance due, and the payment dialog offered to charge it again.



728
729
730
731
732
733
734
# File 'app/models/spree/order.rb', line 728

def outstanding_balance
  if canceled?
    -1 * payment_total
  else
    total - payment_total - returned_items_refund_total
  end
end

#partially_canceled? ⇒ Boolean

Derived, not stored (Decision 8): some but not all fulfillments canceled.

Returns:

  • (Boolean)


475
476
477
# File 'app/models/spree/order.rb', line 475

def partially_canceled?
  !canceled? && fulfillments.canceled.any? && fulfillments.not_canceled.any?
end

#partially_refunded? ⇒ Boolean

Checks if the order is partially refunded

Returns:

  • (Boolean)


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

def partially_refunded?
  return false if total_quantity.zero?
  return false if payment_state.in?(%w[void failed]) || refunds.empty?
  # A refund only requested or failed has given nothing back yet.
  return false unless refunds_total.positive?

  refunds_total < total_minus_store_credits - additional_tax_total.abs
end

#payment_method ⇒ Spree::PaymentMethod

Returns the payment method for the order

Returns:



826
827
828
# File 'app/models/spree/order.rb', line 826

def payment_method
  payments.valid.not_store_credits.first&.payment_method
end

#payment_source ⇒ Spree::PaymentSource

Returns the payment source for the order

Returns:



833
834
835
# File 'app/models/spree/order.rb', line 833

def payment_source
  payments.valid.not_store_credits.first&.source
end

#payment_split_for(payment) ⇒ Spree::PaymentSplit?

This order's share of one payment made against its group.

Parameters:

Returns:



805
806
807
# File 'app/models/spree/order.rb', line 805

def payment_split_for(payment)
  payment_splits.find_by(payment_id: payment.id)
end

#placed? ⇒ Boolean

Returns:

  • (Boolean)


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

def placed?
  status == 'placed'
end

#promo_code ⇒ Object



1193
1194
1195
# File 'app/models/spree/order.rb', line 1193

def promo_code
  Spree::CouponCode.find_by(order: self, promotion: promotions).try(:code) || promotions.pluck(:code).compact.first
end

#promotion_actions_of_scope(scope) ⇒ Object

Promotion actions of the given discount scope, covering both the 6.0 class names and the legacy STI names still present in the type column until the 6.3 data migration.



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

def promotion_actions_of_scope(scope)
  Spree::PromotionAction.where(type: Spree::PromotionAction.types_for_discount_scope(scope))
end

#quick_checkout? ⇒ Boolean

Check if the shipping address is a quick checkout address quick checkout addresses are incomplete as wallet providers like Apple Pay and Google Pay do not provide all the address fields until the checkout is completed (confirmed) on their side

Returns:

  • (Boolean)


618
619
620
# File 'app/models/spree/order.rb', line 618

def quick_checkout?
  shipping_address.present? && shipping_address.quick_checkout?
end

#quick_checkout_available? ⇒ Boolean

Check if quick checkout is available for this order Either fully digital or not digital at all

Returns:

  • (Boolean)


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

def quick_checkout_available?
  payment_required? && fulfillments.count <= 1 && (digital? || !some_digital? || !delivery_step_required?)
end

#quick_checkout_require_address? ⇒ Boolean

Check if quick checkout requires an address collection

Returns:

  • (Boolean)


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

def quick_checkout_require_address?
  shipping_address_required?
end

#rebuild_fulfillments!(keep_selection: true) ⇒ Object

Parameters:

  • keep_selection (Boolean) (defaults to: true) —

    false when the destination changed, so the new proposals start from the default rate



956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
# File 'app/models/spree/order.rb', line 956

def rebuild_fulfillments!(keep_selection: true)
  # A placed order's delivery was charged at placement; re-pricing it
  # belongs to the post-placement edit path, not to a rebuild.
  unless completed?
    previous_selections = keep_selection ? fulfillments.selected_rates_by_stock_location : {}
  end

  discounts.for_fulfillments.delete_all
  tax_lines.for_fulfillments.delete_all
  fees.for_fulfillments.delete_all

  shipment_ids = fulfillments.map(&:id)
  DeliveryRate.where(fulfillment_id: shipment_ids).delete_all
  # A connector's key for a fulfillment that is going away would otherwise
  # outlive it and block the key from naming the rebuilt one.
  Spree::ExternalReference.where(resource_type: Spree::Fulfillment.name, resource_id: shipment_ids).delete_all if shipment_ids.any?

  fulfillments.delete_all

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

  self.fulfillments = order_routing_strategy.for_allocation.map do |package|
    package.to_fulfillment.tap do |fulfillment|
      fulfillment.address_id = ship_address_id
      fulfillment.carry_over_selection(previous_selections.fetch(fulfillment.stock_location_id, [])) if previous_selections
    end
  end
end

#recalculate_totals! ⇒ Object

Recomputes and persists money totals (item, tax, promotion, delivery) and derived item counts. Convenience for Spree::Orders::RecalculateTotals.



644
645
646
# File 'app/models/spree/order.rb', line 644

def recalculate_totals!
  Spree.order_recalculate_totals_workflow.call(order: self)
end

#refresh_delivery_rates(audience = DeliveryMethod::STOREFRONT) ⇒ Array<Array<Spree::DeliveryRate>>

Re-quotes every fulfillment for the given audience.

Parameters:

Returns:



1075
1076
1077
# File 'app/models/spree/order.rb', line 1075

def refresh_delivery_rates(audience = DeliveryMethod::STOREFRONT)
  fulfillments.map { |fulfillment| fulfillment.refresh_rates(audience) }
end

#refresh_shipment_rates(audience = DeliveryMethod::STOREFRONT) ⇒ Object

Deprecated.

Use #refresh_delivery_rates; removed in 6.3.



1080
1081
1082
1083
1084
1085
# File 'app/models/spree/order.rb', line 1080

def refresh_shipment_rates(audience = DeliveryMethod::STOREFRONT)
  Spree::Deprecation.warn(
    'Spree::Order#refresh_shipment_rates is deprecated and will be removed in Spree 6.3. Use #refresh_delivery_rates instead.'
  )
  refresh_delivery_rates(audience)
end

#refunds_total ⇒ Object



488
489
490
491
492
# File 'app/models/spree/order.rb', line 488

def refunds_total
  return refunds.select(&:completed?).sum(0.to_d, &:amount) if read_association_in_memory?(:refunds)

  refunds.completed_or_unset.sum(:amount)
end

#remove_out_of_stock_items! ⇒ Object

Deprecated.

Only Carts can auto remove out of stock items

Removes out-of-stock/discontinued items and populates warnings. Returns self (reloaded if items were removed) with warnings set. Captured before the call because removing items reloads the order, which would drop warnings already recorded upstream.



86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'app/models/spree/order.rb', line 86

def remove_out_of_stock_items!
  Spree::Deprecation.warn(
    'Spree::Order#remove_out_of_stock_items! is deprecated and will be removed in Spree 6.3. This method now works only on Spree::Cart objects'
  )

  existing_warnings = warnings
  result = Spree.cart_remove_out_of_stock_items_service.call(cart: self)
  return self unless result.success?

  order, _messages, new_warnings = result.value
  order.warnings = existing_warnings | (new_warnings || [])
  order
end

#returned_items_refund_total ⇒ BigDecimal

What refunds for returns, claims and exchanges have given back. Read off loaded refunds when a list preloaded them, as #refunds_total is, since every order serializer asks for it.

Returns:

  • (BigDecimal)


741
742
743
744
745
746
747
# File 'app/models/spree/order.rb', line 741

def returned_items_refund_total
  if read_association_in_memory?(:refunds)
    return refunds.select { |refund| refund.for_returned_items? && refund.completed? }.sum(0.to_d, &:amount)
  end

  refunds.for_returned_items.completed_or_unset.sum(:amount)
end

#set_fulfillments_cost ⇒ Object



1087
1088
1089
1090
# File 'app/models/spree/order.rb', line 1087

def set_fulfillments_cost
  fulfillments.each(&:update_amounts)
  recalculate_totals!
end

#settlement_payments ⇒ ActiveRecord::Relation<Spree::Payment>

The payments that settle this order.

An order placed in a split checkout has none of its own: the customer made one payment for the whole basket, against the group. Anything asking what money exists for this order — capture on dispatch, refunds, the admin payments panel — reads it here, and reads its own share of it from #payment_splits.

Returns:



759
760
761
# File 'app/models/spree/order.rb', line 759

def settlement_payments
  order_group_id.present? ? order_group.payments : payments
end

#settlement_pending_payments ⇒ ActiveRecord::Relation<Spree::Payment>, Array<Spree::Payment>

Payments still to be collected for this order, wherever they live.

Returns:



778
779
780
# File 'app/models/spree/order.rb', line 778

def settlement_pending_payments
  grouped? ? settlement_payments.pending : pending_payments
end

#shipped? ⇒ Boolean

Returns:

  • (Boolean)


930
931
932
# File 'app/models/spree/order.rb', line 930

def shipped?
  %w(partial shipped fulfilled delivered).include?(fulfillment_status)
end

#shipping_method ⇒ Object



1092
1093
1094
1095
# File 'app/models/spree/order.rb', line 1092

def shipping_method
  Spree::Deprecation.warn('Spree::Order#shipping_method is deprecated and will be removed in Spree 6.3. Please use Spree::Order#delivery_method')
  delivery_method
end

#sibling_order_ids ⇒ Array<Integer>

This order and any placed alongside it in the same checkout.

The set anything counting checkouts rather than orders works from — a promotion's usage limit, for one, which must not be spent several times over because a basket happened to span several sellers.

Returns:

  • (Array<Integer>)


795
796
797
798
799
# File 'app/models/spree/order.rb', line 795

def sibling_order_ids
  return [id] unless grouped?

  order_group.orders.ids
end

#tags=(tags) ⇒ Object



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

def tags=(tags)
  self.tag_list = tags
end

#to_csv(store = nil, omit_headers: []) ⇒ Object

Parameters:

  • omit_headers (Array<String>) (defaults to: []) —

    columns to leave out, named by their header. A seller's export drops the buyer's email this way — see Spree::Exports::Orders.



1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
# File 'app/models/spree/order.rb', line 1234

def to_csv(store = nil, omit_headers: [])
  store ||= self.store
  # Through the shared helper so the value row is built from exactly the
  # definitions, in exactly the order, that Export#custom_fields_headers
  # used for the header row — a mismatch shifts every value column.
  custom_field_values = custom_fields_for_csv(self, store)

  csv_lines = []
  line_items.each_with_index do |line_item, index|
    csv_lines << Spree::CSV::OrderLineItemPresenter.new(
      self, line_item, index, custom_field_values, omit_headers: omit_headers
    ).call
  end
  csv_lines
end

#total_weight ⇒ BigDecimal

Returns the total weight of the inventory units in the order This is used to calculate the shipping rates for the order

Returns:

  • (BigDecimal) —

    the total weight of the inventory units in the order



1016
1017
1018
# File 'app/models/spree/order.rb', line 1016

def total_weight
  @total_weight ||= line_items.joins(:variant).includes(:variant).map(&:item_weight).sum
end

#uneditable? ⇒ Boolean

Returns:

  • (Boolean)


852
853
854
# File 'app/models/spree/order.rb', line 852

def uneditable?
  completed? || canceled?
end

#update_line_item_prices! ⇒ void

This method returns an undefined value.

Re-prices every line from the catalog.

A completed order's money is frozen — re-pricing would rewrite what the customer was actually charged — so this refuses rather than reporting a success it did not deliver. Post-placement price changes belong to the order-change substrate (docs/plans/6.1-order-change-substrate.md).

Raises:

  • (RuntimeError) —

    when the order is already completed



713
714
715
716
717
718
719
720
# File 'app/models/spree/order.rb', line 713

def update_line_item_prices!
  raise 'cannot re-price a completed order' if completed?

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

#update_statuses! ⇒ Object

Derives and persists payment_status / fulfillment_status from the order's payment, refund and fulfillment records. Convenience for Spree::Orders::UpdateStatuses, the sole status writer.



651
652
653
# File 'app/models/spree/order.rb', line 651

def update_statuses!
  Spree.order_update_statuses_service.call(order: self)
end

#updater ⇒ Object

Deprecated.

Use #recalculate_totals! for money and #update_statuses! for payment/fulfillment statuses; removed in 6.3.



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

def updater
  @updater ||= Spree.order_updater.new(self)
end

#use_all_coupon_codes ⇒ Object



914
915
916
917
918
919
# File 'app/models/spree/order.rb', line 914

def use_all_coupon_codes
  Spree::Deprecation.warn(
    'Spree::Order#use_all_coupon_codes is deprecated and will be removed in Spree 6.3. Use Spree::CouponCodes::CouponCodesHandler instead.'
  )
  Spree::CouponCodes::CouponCodesHandler.new(order: self).use_all_codes
end

#valid_coupon_promotions ⇒ Array<Spree::Promotion>

Returns the valid coupon promotions for the order

Returns:



1211
1212
1213
1214
1215
# File 'app/models/spree/order.rb', line 1211

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

#valid_promotion_ids ⇒ Array<Integer>

Returns the IDs of the valid promotions for the order

Returns:

  • (Array<Integer>)


1205
1206
1207
# File 'app/models/spree/order.rb', line 1205

def valid_promotion_ids
  discounts.promotion.nonzero.where.not(promotion_id: nil).distinct.pluck(:promotion_id)
end

#valid_promotions ⇒ Array<Spree::OrderPromotion>

Returns the valid promotions for the order

Returns:



1199
1200
1201
# File 'app/models/spree/order.rb', line 1199

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

#withdrawal_period_days ⇒ Integer?

Returns nil where no market says otherwise — a statutory notice is not something to assume on an order with no region attached.

Returns:

  • (Integer, nil) —

    nil where no market says otherwise — a statutory notice is not something to assume on an order with no region attached



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

def withdrawal_period_days
  market&.preferred_withdrawal_period_days
end

#withdrawal_period_ends_at ⇒ ActiveSupport::TimeWithZone?

When the buyer's statutory right of withdrawal expires — the EU cooling-off period (Consumer Rights Directive 2011/83/EU Art. 9).

Derived rather than stored, because the clock starts when the buyer takes physical possession: a value written at placement would be wrong the moment a parcel arrived.

Nil until the last live parcel is delivered. Counting from completion instead would expire the deadline before the statutory period had even begun — the buyer would be told their right had run out while they were still waiting for the goods. A right whose start has not happened yet has no end date to report.

Returns:

  • (ActiveSupport::TimeWithZone, nil) —

    nil when the market grants no withdrawal right, the order is not complete, or delivery is outstanding



520
521
522
523
524
525
526
527
# File 'app/models/spree/order.rb', line 520

def withdrawal_period_ends_at
  return nil unless withdrawal_right_applies?

  started_at = withdrawal_period_starts_at
  return nil if started_at.nil?

  started_at + withdrawal_period_days.days
end

#withdrawal_period_starts_at ⇒ ActiveSupport::TimeWithZone?

The moment the cooling-off period starts: receipt of the goods. The Consumer Rights Directive treats an order delivered in instalments as received when the LAST one arrives, so a partly-delivered order has not started its clock at all — reading the max over the delivered subset would start it at the first parcel and could expire the right while the buyer is still waiting for the rest.

Returns:

  • (ActiveSupport::TimeWithZone, nil) —

    nil until every parcel that is still live has been delivered



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

def withdrawal_period_starts_at
  live = fulfillments.reject(&:canceled?)
  return nil if live.empty?

  received = live.map { |fulfillment| withdrawal_receipt_of(fulfillment) }
  return nil if received.any?(&:blank?)

  received.max
end

#withdrawal_receipt_of(fulfillment) ⇒ ActiveSupport::TimeWithZone?

When one fulfillment counts as received.

Digital content has no delivery event and no carrier to report one, so waiting for delivered_at would leave a mixed order's clock stopped forever — the physical parcel arrives and the deadline never appears. The Directive treats digital content differently from goods anyway (Art. 16(m)); handing it over is the moment it reaches the buyer.

Parameters:

Returns:

  • (ActiveSupport::TimeWithZone, nil)


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

def withdrawal_receipt_of(fulfillment)
  return fulfillment.delivered_at || fulfillment.fulfilled_at if fulfillment.digital?

  fulfillment.delivered_at
end

#withdrawal_right_applies? ⇒ Boolean

Whether a statutory right to withdraw exists on this order at all. A cancelled order has already ended the contract the right would end, and a market that sets no period grants none. Stated once because both readers above need the same answer.

Returns:

  • (Boolean)


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

def withdrawal_right_applies?
  completed? && !canceled? && withdrawal_period_days.present?
end

#within_withdrawal_period? ⇒ Boolean

Whether the buyer may still withdraw.

True while delivery is outstanding: the right cannot have lapsed before it started, so an order still in transit is always within its period even though no deadline can be named yet.

A canceled order is not: withdrawal is how a buyer ends a contract that is still standing, and cancellation has already ended this one. Without the guard, cancellation empties the live fulfillments, no start date can be found, and the open-ended reading above would keep the order reporting itself as withdrawable forever.

Returns:

  • (Boolean)


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

def within_withdrawal_period?
  return false unless withdrawal_right_applies?

  deadline = withdrawal_period_ends_at
  # No deadline yet means nothing has been delivered, so the clock that
  # would end the right has not started.
  deadline.nil? || deadline.future?
end