spree_core 6.0.3 → 6.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. checksums.yaml +4 -4
  2. data/app/jobs/spree/payments/handle_webhook_job.rb +12 -1
  3. data/app/models/concerns/spree/has_custom_fields.rb +4 -1
  4. data/app/models/concerns/spree/personal_data_matching.rb +5 -1
  5. data/app/models/concerns/spree/product_scopes.rb +2 -2
  6. data/app/models/concerns/spree/publishable.rb +26 -3
  7. data/app/models/spree/authentication/strategies/base_strategy.rb +10 -1
  8. data/app/models/spree/cart.rb +7 -2
  9. data/app/models/spree/invitation.rb +6 -2
  10. data/app/models/spree/media.rb +25 -1
  11. data/app/models/spree/order.rb +5 -1
  12. data/app/models/spree/price.rb +3 -0
  13. data/app/models/spree/product.rb +6 -9
  14. data/app/models/spree/product_category.rb +7 -1
  15. data/app/models/spree/product_collection.rb +8 -1
  16. data/app/models/spree/seller.rb +93 -10
  17. data/app/models/spree/seller_requirements/complete_profile.rb +26 -7
  18. data/app/models/spree/stock_level.rb +30 -1
  19. data/app/models/spree/stock_movement.rb +1 -0
  20. data/app/services/spree/carts/destroy.rb +22 -6
  21. data/app/services/spree/collections/regenerate_products.rb +37 -15
  22. data/app/services/spree/companies/add_member.rb +9 -4
  23. data/app/services/spree/diagnostics/error_log.rb +139 -0
  24. data/app/services/spree/diagnostics/section.rb +72 -0
  25. data/app/services/spree/diagnostics/sections.rb +121 -0
  26. data/app/services/spree/diagnostics/stack.rb +73 -0
  27. data/app/services/spree/diagnostics.rb +132 -0
  28. data/app/services/spree/newsletter/subscribe.rb +7 -3
  29. data/app/services/spree/orders/remove_line_item.rb +16 -5
  30. data/app/services/spree/product_memberships.rb +21 -1
  31. data/app/services/spree/product_types/apply_to_products.rb +12 -2
  32. data/app/services/spree/products/auto_match_collections.rb +20 -4
  33. data/app/services/spree/stock_reservations/reserve.rb +9 -6
  34. data/app/services/spree/store_credits/apply.rb +9 -1
  35. data/app/services/spree/update_check.rb +7 -31
  36. data/app/tools/spree/agent_tools/describe_resource.rb +3 -0
  37. data/app/tools/spree/agent_tools/get_resource.rb +1 -1
  38. data/app/tools/spree/agent_tools/resource_write.rb +1 -1
  39. data/app/tools/spree/agent_tools/search_resources.rb +42 -10
  40. data/app/workflows/spree/carts/add_item.rb +51 -0
  41. data/app/workflows/spree/carts/complete.rb +14 -2
  42. data/app/workflows/spree/payments/handle_webhook.rb +7 -3
  43. data/app/workflows/spree/sellers/approve.rb +6 -0
  44. data/app/workflows/spree/sellers/create.rb +5 -2
  45. data/app/workflows/spree/stock_levels/bulk_upsert.rb +19 -7
  46. data/config/locales/be.yml +1 -1
  47. data/config/locales/en.yml +8 -0
  48. data/config/locales/fr.yml +1 -1
  49. data/config/locales/lt.yml +1 -1
  50. data/config/locales/ru.yml +1 -1
  51. data/config/locales/uk.yml +1 -1
  52. data/db/migrate/20240303174340_fix_spree_stock_item_unique_index.rb +14 -10
  53. data/db/migrate/20260814000001_rename_stock_items_to_stock_levels.rb +13 -7
  54. data/lib/spree/agent_tool.rb +3 -3
  55. data/lib/spree/agent_tools/operation_tool.rb +1 -1
  56. data/lib/spree/agent_tools/record_summary.rb +8 -2
  57. data/lib/spree/agent_tools/resource_map.rb +82 -7
  58. data/lib/spree/core/engine.rb +10 -0
  59. data/lib/spree/core/version.rb +1 -1
  60. data/lib/spree/core.rb +11 -0
  61. data/lib/spree/reporting/default_vocabulary.rb +25 -5
  62. data/lib/tasks/diagnostics.rake +11 -0
  63. metadata +10 -4
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: a2157ca6ce976c9676d3c814939c6a69e8fd835b8864d73006b274f1216f2d4e
4
- data.tar.gz: 8a80c4a0d322fafe8ff3f4accb3bf293bfca4f4cf341a98015e8a494c0373185
3
+ metadata.gz: e465daf49ecae5d15b57e998d9ea505ee2eba53224668e370c290536aad30736
4
+ data.tar.gz: 1a7596942af23ef5da1830f75c76acf3f6bad00e92e1b95b1f400424ddfa7603
5
5
  SHA512:
6
- metadata.gz: 290b7d040a689ce9be4d01e20713ca97476d8b2b5ab1e8e735fad6bf651103375f037e2f96bb767662b866069d6c01219eae6d5d8da1de2ffed3a1e01756ab25
7
- data.tar.gz: bd9a079e8712771a6a77453e9ae63bdf6a75a39d549c3db86eb326a5f7ab60896e6ff2196274380d5805f583487b43a24f0c198feb780ab40bddf11c1b0e26bb
6
+ metadata.gz: 3fab6326b8031e792e88fe83aedc58879cef258f145fc828ae04c39425e1c0e1359a4e2ee26d4d64f7abea3b72cd7e79ceb2ba4c6e4dc045e5a266bd0c351255
7
+ data.tar.gz: 8dd0f193ddc437e1ab18983e34713743928ec239e4baa025f93aed3bc4b3e6bc85ac0e36630859a561fd1f901fef77cec49685e254c303d1502e2f53ca694e39
@@ -7,16 +7,27 @@ module Spree
7
7
  retry_on ActiveRecord::LockWaitTimeout, wait: 5.seconds, attempts: 3
8
8
  discard_on ActiveRecord::RecordNotFound
9
9
 
10
+ # The gateway got its 200 when this job was enqueued and will not send
11
+ # the webhook again, so a failed settlement (a gateway 5xx, a lock
12
+ # timeout swallowed by the workflow) must be retried here or the
13
+ # buyer is charged without an order. Safe to replay: the workflow
14
+ # skips a payment that is already completed.
15
+ class SettlementFailed < StandardError; end
16
+
17
+ retry_on SettlementFailed, wait: :polynomially_longer, attempts: 5
18
+
10
19
  def perform(payment_method_id:, action:, payment_session_id:)
11
20
  payment_method = Spree::PaymentMethod.find(payment_method_id)
12
21
  Spree::Current.store = payment_method.store
13
22
  payment_session = Spree::PaymentSession.find(payment_session_id)
14
23
 
15
- Spree.payments_handle_webhook_workflow.call(
24
+ result = Spree.payments_handle_webhook_workflow.call(
16
25
  payment_method: payment_method,
17
26
  action: action.to_sym,
18
27
  payment_session: payment_session
19
28
  )
29
+
30
+ raise SettlementFailed, "Payment session #{payment_session.id}: #{result.error}" if result&.failure?
20
31
  end
21
32
  end
22
33
  end
@@ -40,7 +40,10 @@ module Spree
40
40
  end
41
41
 
42
42
  included do
43
- has_many :custom_fields, -> { includes(:custom_field_definition) }, as: :resource, class_name: 'Spree::CustomField', dependent: :destroy
43
+ # The explicit inverse lets a custom field built on an unsaved owner find that owner when
44
+ # it is saved. Rails cannot infer it for a scoped association, so without it the row is
45
+ # inserted with a NULL resource_id unless the app happens to enable `has_many_inversing`.
46
+ has_many :custom_fields, -> { includes(:custom_field_definition) }, as: :resource, inverse_of: :resource, class_name: 'Spree::CustomField', dependent: :destroy
44
47
  has_many :storefront_custom_fields, -> { includes(:custom_field_definition).storefront_visible }, as: :resource, class_name: 'Spree::CustomField'
45
48
 
46
49
  # Deprecated 6.0 association names, removed in 6.1. `private_metafields`
@@ -90,11 +90,15 @@ module Spree
90
90
 
91
91
  # Rows of `model` whose `email` is this address, whatever its casing.
92
92
  #
93
+ # The exact match goes through the model, so a table whose email the app
94
+ # encrypts is still matched: SQL only ever sees its ciphertext.
95
+ #
93
96
  # @param model [Class]
94
97
  # @param email [String]
95
98
  # @return [ActiveRecord::Relation]
96
99
  def with_email(model, email)
97
- model.where(model.arel_table[:email].lower.eq(email.to_s.downcase))
100
+ model.where(email: email.to_s).
101
+ or(model.where(model.arel_table[:email].lower.eq(email.to_s.downcase)))
98
102
  end
99
103
 
100
104
  # Rows at this address that no *other* person already owns.
@@ -241,8 +241,8 @@ module Spree
241
241
  # (docs/plans/6.0-volume-pricing.md).
242
242
  def self.with_currency(currency)
243
243
  joins(variants: :prices).
244
- where(Price.table_name => { currency: currency.upcase, price_list_id: nil }).
245
- where.not(Price.table_name => { amount: nil }).
244
+ where(Price.table_name => { currency: currency.upcase }).
245
+ merge(Price.listing).
246
246
  distinct
247
247
  end
248
248
 
@@ -207,8 +207,9 @@ module Spree
207
207
  return unless Spree::Events.enabled?
208
208
 
209
209
  @_current_event_name = event_name
210
- payload ||= event_payload_for(event_name)
211
- Spree::Events.publish(event_name, payload, metadata)
210
+ publish_in_event_store do
211
+ Spree::Events.publish(event_name, payload || event_payload_for(event_name), metadata)
212
+ end
212
213
  ensure
213
214
  @_current_event_name = nil
214
215
  end
@@ -389,7 +390,29 @@ module Spree
389
390
  end
390
391
 
391
392
  def capture_pre_destroy_payload
392
- @_pre_destroy_payload = event_payload
393
+ @_pre_destroy_payload = in_event_store { event_payload }
394
+ end
395
+
396
+ # Publishes with the record's own store, so the event is
397
+ # attributed to it rather than to whatever store the caller happens to
398
+ # be in — the default store, in a job or a rake task.
399
+ #
400
+ # Spree::Event reads Spree::Current lazily, so store_id is settled here
401
+ # while the context is still open: a subscriber job or a webhook
402
+ # delivery reads it long after.
403
+ def publish_in_event_store
404
+ in_event_store do
405
+ published = yield
406
+ published.store_id if published.is_a?(Spree::Event)
407
+ published
408
+ end
409
+ end
410
+
411
+ def in_event_store(&block)
412
+ store = (respond_to?(:store) ? self.store : nil) || Spree::Current.store
413
+ return block.call if store.nil? || store == Spree::Current.store
414
+
415
+ Spree::Current.with_store(store, &block)
393
416
  end
394
417
  end
395
418
  end
@@ -82,12 +82,21 @@ module Spree
82
82
  # account as "ada@example.com" — an exact match would refuse login to
83
83
  # someone who capitalizes their own address differently.
84
84
  #
85
+ # When that finds nothing, an exact match through the model goes
86
+ # through whatever the app layers on the column: an app that encrypts
87
+ # email (`encrypts :email, deterministic: true, downcase: true`)
88
+ # stores ciphertext, which `LOWER(email)` in SQL can never match. The
89
+ # case-insensitive match comes first so that, where older data holds
90
+ # two accounts differing only in case, the casing typed never picks
91
+ # between them.
92
+ #
85
93
  # @param email [String]
86
94
  # @return [Object, nil]
87
95
  def find_user_by_email(email)
88
96
  return nil if email.blank?
89
97
 
90
- user_class.find_by(user_class.arel_table[:email].lower.eq(email.to_s.downcase))
98
+ user_class.find_by(user_class.arel_table[:email].lower.eq(email.to_s.downcase)) ||
99
+ user_class.find_by(email: email.to_s)
91
100
  end
92
101
 
93
102
  # Find or create user identity
@@ -141,11 +141,16 @@ module Spree
141
141
 
142
142
  # Whether a live completion attempt holds this cart — its totals are fixed
143
143
  # and money may be moving, so mutations must wait until it finishes or the
144
- # claim goes stale.
144
+ # claim goes stale. A payment-covered draft or a divided checkout resumes
145
+ # its existing result instead of editing the cart that supplied it.
145
146
  #
146
147
  # @return [Boolean]
147
148
  def completion_claimed?
148
- completing_at.present? && completing_at > COMPLETING_CLAIM_TTL.ago
149
+ return false if completing_at.blank?
150
+ return true if completing_at > COMPLETING_CLAIM_TTL.ago || order_group.present?
151
+ return false if order.nil?
152
+
153
+ order.payments.valid.where(status: %w[pending processing completed]).sum(:amount) >= order.amount_due_at_checkout
149
154
  end
150
155
 
151
156
  # Recomputes and persists money totals (item, tax, promotion, delivery)
@@ -120,9 +120,13 @@ module Spree
120
120
  # the way the account's email uniqueness is, case-insensitively, so an
121
121
  # address typed in another case still finds the one account it can belong
122
122
  # to. Resolved by record rather than by comparing strings in Ruby, whose
123
- # case folding is wider than the database's.
123
+ # case folding is wider than the database's. Failing that, an exact match
124
+ # through the model, so an app that encrypts email still finds the account.
124
125
  def invitee_account
125
- Spree.admin_user_class.where('LOWER(email) = LOWER(?)', email).first
126
+ return if email.blank?
127
+
128
+ Spree.admin_user_class.where('LOWER(email) = LOWER(?)', email).first ||
129
+ Spree.admin_user_class.find_by(email: email)
126
130
  end
127
131
 
128
132
  private
@@ -82,7 +82,31 @@ module Spree
82
82
  )
83
83
  }
84
84
 
85
- self.whitelisted_ransackable_attributes = %w[alt media_type created_at updated_at]
85
+ self.whitelisted_ransackable_attributes = %w[alt media_type created_at updated_at filename byte_size]
86
+
87
+ # The attached file's name and size, so a library can be listed by them.
88
+ # They live on the blob, not the asset row, hence a subquery per row.
89
+ ransacker :filename do |parent|
90
+ attached_blob_column(parent, :filename)
91
+ end
92
+
93
+ ransacker :byte_size, type: :integer do |parent|
94
+ attached_blob_column(parent, :byte_size)
95
+ end
96
+
97
+ def self.attached_blob_column(parent, column)
98
+ blobs = ActiveStorage::Blob.arel_table
99
+ attachments = ActiveStorage::Attachment.arel_table
100
+ Arel::Nodes::Grouping.new(
101
+ blobs.project(blobs[column]).
102
+ join(attachments).on(attachments[:blob_id].eq(blobs[:id])).
103
+ where(attachments[:record_type].eq(polymorphic_name)).
104
+ where(attachments[:record_id].eq(parent.table[:id])).
105
+ where(attachments[:name].eq('attachment')).
106
+ take(1)
107
+ )
108
+ end
109
+ private_class_method :attached_blob_column
86
110
  self.whitelisted_ransackable_scopes = %w[attached unattached filename_cont]
87
111
  self.ransackable_scope_types = { 'attached' => 'boolean', 'unattached' => 'boolean' }
88
112
 
@@ -360,7 +360,11 @@ module Spree
360
360
  conditions << search_condition(Spree::Address, :last_name, full_name.last)
361
361
  end
362
362
 
363
- left_joins(:bill_address).where(arel_table[:email].lower.eq(query.downcase)).or(where(conditions.reduce(:or)))
363
+ # The exact match goes through the model, so it still finds an order in
364
+ # an app that encrypts email, where SQL only ever sees ciphertext.
365
+ left_joins(:bill_address).where(email: query).
366
+ or(left_joins(:bill_address).where(arel_table[:email].lower.eq(query.downcase))).
367
+ or(where(conditions.reduce(:or)))
364
368
  end
365
369
 
366
370
  # Find an order by prefixed ID first, falling back to number, then integer id for backwards compatibility
@@ -67,6 +67,9 @@ module Spree
67
67
  scope :non_zero, -> { where.not(amount: [nil, 0]) }
68
68
  scope :discounted, -> { where('compare_at_amount > amount') }
69
69
  scope :base_prices, -> { where(price_list_id: nil) }
70
+ # Base prices with an amount: what puts a product on sale to everyone in a
71
+ # currency (docs/plans/6.0-volume-pricing.md).
72
+ scope :listing, -> { base_prices.where.not(amount: nil) }
70
73
  # A variant's rungs above its ordinary price on a list.
71
74
  scope :breaks, -> { where.not(min_quantity: 1) }
72
75
  scope :for_price_list, ->(price_list) { where(price_list_id: price_list) }
@@ -80,8 +80,10 @@ module Spree
80
80
 
81
81
  has_many :product_option_types, -> { order(:position) }, dependent: :destroy, inverse_of: :product
82
82
  has_many :option_types, through: :product_option_types
83
- has_many :product_categories, -> { order(created_at: :asc) }, class_name: 'Spree::ProductCategory', dependent: :delete_all, inverse_of: :product
84
- has_many :categories, through: :product_categories, class_name: 'Spree::Category', source: :category, before_remove: :remove_category
83
+ has_many :product_categories, -> { order(created_at: :asc) }, class_name: 'Spree::ProductCategory',
84
+ dependent: :destroy, inverse_of: :product
85
+ has_many :categories, through: :product_categories, class_name: 'Spree::Category', source: :category,
86
+ dependent: :destroy
85
87
  has_many :taxonomies, through: :categories, deprecated: true
86
88
 
87
89
  # @deprecated The classification_count column was renamed to categories_count in 6.0.
@@ -139,8 +141,8 @@ module Spree
139
141
  self.category_ids = ids
140
142
  end
141
143
 
142
- has_many :product_collections, class_name: 'Spree::ProductCollection', dependent: :destroy_async, inverse_of: :product
143
- has_many :collections, through: :product_collections
144
+ has_many :product_collections, class_name: 'Spree::ProductCollection', dependent: :destroy, inverse_of: :product
145
+ has_many :collections, through: :product_collections, dependent: :destroy
144
146
  has_many :catalog_products, class_name: 'Spree::CatalogProduct', dependent: :destroy_async, inverse_of: :product
145
147
  has_many :catalogs, through: :catalog_products
146
148
 
@@ -1035,11 +1037,6 @@ module Spree
1035
1037
  end
1036
1038
  end
1037
1039
 
1038
- def remove_category(category)
1039
- removed_product_categories = product_categories.where(category: category)
1040
- removed_product_categories.each(&:remove_from_list)
1041
- end
1042
-
1043
1040
  def discontinue_on_must_be_later_than_make_active_at
1044
1041
  if discontinue_on < make_active_at
1045
1042
  errors.add(:discontinue_on, :invalid_date_range)
@@ -4,13 +4,19 @@ module Spree
4
4
  # alias). The category_id column was renamed in 6.0, so the association is a
5
5
  # plain #category with no foreign_key override.
6
6
  class ProductCategory < Spree.base_class
7
+ has_prefix_id :pctg
8
+
9
+ publishes_lifecycle_events only: %i[create delete]
10
+
7
11
  acts_as_list scope: :category_id
8
12
 
9
13
  with_options inverse_of: :product_categories, touch: true do
10
- belongs_to :product, class_name: 'Spree::Product', counter_cache: :categories_count
14
+ belongs_to :product, -> { with_deleted }, class_name: 'Spree::Product', counter_cache: :categories_count
11
15
  belongs_to :category, class_name: 'Spree::Category'
12
16
  end
13
17
 
18
+ delegate :store, to: :product, allow_nil: true
19
+
14
20
  validates :position, numericality: { only_integer: true, allow_blank: true, allow_nil: true }
15
21
  # For #3494
16
22
  validates :category_id, uniqueness: { scope: :product_id, message: :already_linked, allow_blank: true }
@@ -4,14 +4,21 @@ module Spree
4
4
  class ProductCollection < Spree.base_class
5
5
  self.table_name = 'spree_product_collections'
6
6
 
7
+ has_prefix_id :pcoll
8
+
9
+ publishes_lifecycle_events only: %i[create delete]
10
+
7
11
  acts_as_list scope: :collection
8
12
 
9
13
  # products_count is a plain Rails counter_cache on the collection (collections are
10
14
  # flat, so — unlike Classification — there is no descendant-inclusive recompute).
11
- belongs_to :product, class_name: 'Spree::Product', counter_cache: :collections_count, touch: true
15
+ belongs_to :product, -> { with_deleted }, class_name: 'Spree::Product', counter_cache: :collections_count, touch: true,
16
+ inverse_of: :product_collections
12
17
  belongs_to :collection, class_name: 'Spree::Collection', counter_cache: :products_count, touch: true,
13
18
  inverse_of: :product_collections
14
19
 
20
+ delegate :store, to: :product, allow_nil: true
21
+
15
22
  validates :position, numericality: { only_integer: true, allow_blank: true, allow_nil: true }
16
23
  validates :collection_id, uniqueness: { scope: :product_id, message: :already_linked, allow_blank: true }
17
24
 
@@ -22,7 +22,7 @@ module Spree
22
22
  # #payout_account_reference.
23
23
  include Spree::HasExternalReferences
24
24
 
25
- MEMOIZED_METHODS = %w[onboarding_requirements onboarding_progress products_count returns_location].freeze
25
+ MEMOIZED_METHODS = %w[onboarding_requirements onboarding_progress products_count_by_status returns_location].freeze
26
26
 
27
27
  publishes_lifecycle_events
28
28
  publishes_events :approved, :invited, :onboarding_reopened, :onboarding_started, :rejected,
@@ -106,6 +106,36 @@ module Spree
106
106
  billing_address&.owner = self
107
107
  end
108
108
 
109
+ # The address fields a stock location keeps on itself, as the API names
110
+ # them. A location is a place rather than a person, so it has no name or
111
+ # label of its own.
112
+ RETURNS_ADDRESS_FIELDS = %w[company address1 address2 city postal_code country_code state_code state_name
113
+ phone].freeze
114
+
115
+ # The API writes the returns address inline, like the billing address. It
116
+ # is the returns location's own address, so it lands on that location — a
117
+ # new one for a seller who has none — and a received return still restocks
118
+ # somewhere the catalog knows. Saved with the seller, in its transaction.
119
+ def returns_address=(attributes)
120
+ attributes = attributes.to_h.stringify_keys.slice(*RETURNS_ADDRESS_FIELDS)
121
+ attributes['zipcode'] = attributes.delete('postal_code') if attributes.key?('postal_code')
122
+
123
+ # Not built through the association: that would validate and save it a
124
+ # second time, under a generic "stock locations is invalid".
125
+ location = returns_location ||
126
+ Spree::StockLocation.new(active: true, returns_enabled: true, propagate_all_variants: false)
127
+ # A state belongs to its country, so a new country drops the old state
128
+ # unless one comes with it.
129
+ if attributes.key?('country_code') && attributes['country_code'].to_s.upcase != location.country_code.to_s.upcase
130
+ attributes = { 'state_code' => nil, 'state_name' => nil }.merge(attributes)
131
+ end
132
+ location.assign_attributes(attributes)
133
+ @returns_location = @pending_returns_location = location
134
+ end
135
+
136
+ validate :validate_returns_location, if: -> { @pending_returns_location }
137
+ after_save :save_returns_location, if: -> { @pending_returns_location }
138
+
109
139
  # Where this seller keeps stock, and so where their returns land. Released
110
140
  # rather than destroyed for the same reason products are: the operator
111
141
  # decides what becomes of a departed seller's inventory.
@@ -428,14 +458,32 @@ module Spree
428
458
 
429
459
  # @return [Integer] how many products this seller lists
430
460
  def products_count
431
- return @products_count if @products_count
432
-
433
- siblings = lazy_preload_context&.records&.grep(self.class)
434
- return @products_count = products.count if siblings.blank?
461
+ products_count_by_status.values.sum
462
+ end
435
463
 
436
- counts = Spree::Product.where(seller_id: siblings.map(&:id)).group(:seller_id).count
437
- siblings.each { |seller| seller.preloaded_products_count = counts.fetch(seller.id, 0) }
438
- @products_count
464
+ # How many of this seller's products sit in each status, every status
465
+ # present: what the operator reads off a seller to see what is live and
466
+ # what is waiting on them. On a list, one grouped query serves every
467
+ # seller on the page.
468
+ #
469
+ # @return [Hash{String => Integer}]
470
+ def products_count_by_status
471
+ return @products_count_by_status if @products_count_by_status
472
+
473
+ blank = Spree::Product::ALL_STATUSES.index_with(0)
474
+ # An unsaved seller has no id, and `seller_id IS NULL` would count the
475
+ # operator's own catalog.
476
+ return blank if new_record?
477
+
478
+ siblings = (lazy_preload_context&.records&.grep(self.class).presence || [self]).select(&:persisted?)
479
+ counts = Spree::Product.where(seller_id: siblings.map(&:id)).group(:seller_id, :status).count
480
+ by_seller = counts.group_by { |(seller_id, _status), _count| seller_id }
481
+ siblings.each do |seller|
482
+ seller.preloaded_products_count_by_status = blank.merge(
483
+ by_seller.fetch(seller.id, []).to_h { |(_seller_id, status), count| [status, count] }
484
+ )
485
+ end
486
+ @products_count_by_status
439
487
  end
440
488
 
441
489
  # Where this seller stands against the marketplace's checklist
@@ -483,12 +531,47 @@ module Spree
483
531
 
484
532
  protected
485
533
 
486
- def preloaded_products_count=(count)
487
- @products_count = count
534
+ def preloaded_products_count_by_status=(counts)
535
+ @products_count_by_status = counts
488
536
  end
489
537
 
490
538
  private
491
539
 
540
+ # Reported under the names the client sent, so a 422 lands on the field.
541
+ def validate_returns_location
542
+ location = @pending_returns_location
543
+ # Filled in here rather than in the writer: on create, the name and the
544
+ # store may be assigned after the address. The id rather than the
545
+ # record, which would add the location to `stock_locations` and have it
546
+ # validated a second time.
547
+ location.seller_id = id
548
+ location.store ||= store
549
+ location.name ||= name
550
+ return if location.valid?
551
+
552
+ # Before the seller has an id, uniqueness compares against the
553
+ # operator's own locations; the save after the seller re-checks it.
554
+ location.errors.delete(:name, :taken) if new_record?
555
+ return if location.errors.empty?
556
+
557
+ location.errors.each do |error|
558
+ field = error.attribute == :zipcode ? :postal_code : error.attribute
559
+ errors.import(error, attribute: :"returns_address.#{field}")
560
+ end
561
+ end
562
+
563
+ def save_returns_location
564
+ location = @pending_returns_location
565
+ @pending_returns_location = nil
566
+ location.seller_id = id
567
+ return unless location.new_record? || location.changed?
568
+
569
+ location.save!
570
+ # A new location is not in a list loaded before it existed, and the
571
+ # returns location is read from that list once the memo clears.
572
+ stock_locations.reset
573
+ end
574
+
492
575
  # The same choice as the query in {#returns_location}, made over the
493
576
  # preloaded locations.
494
577
  def returns_location_from_loaded
@@ -10,16 +10,35 @@ module Spree
10
10
  preference :require_about, :boolean, default: true
11
11
  preference :require_logo, :boolean, default: true
12
12
  preference :require_cover_photo, :boolean, default: false
13
- preference :require_contact_email, :boolean, default: true
13
+ preference :require_contact_email, :boolean, default: false
14
14
 
15
15
  def met_by_seller?(seller)
16
- return false if seller.name.blank?
17
- return false if preferred_require_about && seller.about.blank?
18
- return false if preferred_require_logo && !seller.logo.attached?
19
- return false if preferred_require_cover_photo && !seller.cover_photo.attached?
20
- return false if preferred_require_contact_email && seller.contact_email.blank?
16
+ missing_fields(seller).empty?
17
+ end
18
+
19
+ # The checklist line only says "complete your profile", so the seller
20
+ # is told which ticked fields are still empty — the contact email in
21
+ # particular lives on a different settings page than the rest, so when
22
+ # it is the only gap the state says so and a panel can link there.
23
+ def blocker(seller)
24
+ missing = missing_fields(seller)
25
+ return nil if missing.empty? || latest_submission(seller)&.waived?
26
+
27
+ fields = missing.map { |field| I18n.t("spree.seller_requirement_types.complete_profile.fields.#{field}") }
28
+ state = missing == [:contact_email] ? 'contact_email_missing' : 'incomplete'
29
+ { state: state, message: I18n.t('spree.seller_requirement_types.complete_profile.missing', fields: fields.to_sentence) }
30
+ end
31
+
32
+ private
21
33
 
22
- true
34
+ def missing_fields(seller)
35
+ [
36
+ (:name if seller.name.blank?),
37
+ (:about if preferred_require_about && seller.about.blank?),
38
+ (:logo if preferred_require_logo && !seller.logo.attached?),
39
+ (:cover_photo if preferred_require_cover_photo && !seller.cover_photo.attached?),
40
+ (:contact_email if preferred_require_contact_email && seller.contact_email.blank?)
41
+ ].compact
23
42
  end
24
43
  end
25
44
  end
@@ -70,10 +70,39 @@ module Spree
70
70
  scope :with_incoming, -> { where(arel_table[:incoming_count].gt(0)) }
71
71
  scope :with_reserved, -> { where(arel_table[:reserved_count].gt(0)) }
72
72
 
73
+ # The same two questions asked of a variant rather than one shelf: every
74
+ # level of a variant whose stock, summed over all active locations, has run
75
+ # out or is running low. A variant with plenty in one warehouse is not out
76
+ # of stock because another location holds none of it. Untracked variants
77
+ # have no count to run out of, so they never match; a backorderable one
78
+ # still does, since selling on backorder is when restocking matters most.
79
+ scope :out_of_stock_overall, -> { where(variant_id: variant_ids_by_total_purchasable { |total| total.lteq(0) }) }
80
+ scope :low_stock_overall, lambda { |threshold = nil|
81
+ ceiling = threshold || Spree::Current.store&.preferred_low_stock_threshold || 0
82
+ where(variant_id: variant_ids_by_total_purchasable { |total| total.gt(0).and(total.lteq(ceiling)) })
83
+ }
84
+
73
85
  # What the Inventory page's stock-status filter can ask for. Each names a
74
86
  # scope above; `STOCK_STATUS_SCOPES` is the allowlist that keeps a request
75
87
  # from naming any other method.
76
- STOCK_STATUS_SCOPES = %w[in_stock low_stock out_of_stock with_incoming with_reserved].freeze
88
+ STOCK_STATUS_SCOPES = %w[in_stock low_stock out_of_stock low_stock_overall out_of_stock_overall
89
+ with_incoming with_reserved].freeze
90
+
91
+ # Ids of tracked variants whose purchasable units across
92
+ # every active location satisfy the condition the block builds. Unscoped,
93
+ # so the sum covers all locations even when the caller has narrowed the
94
+ # list to one.
95
+ #
96
+ # @yieldparam total [Arel::Nodes::Node] the summed purchasable units
97
+ # @return [ActiveRecord::Relation] a `variant_id` subquery
98
+ def self.variant_ids_by_total_purchasable
99
+ levels = unscoped.where(deleted_at: nil)
100
+ levels.joins(:stock_location).merge(Spree::StockLocation.active).
101
+ joins(:variant).where(spree_variants: { track_inventory: true, deleted_at: nil }).
102
+ group(:variant_id).
103
+ having(yield(Arel::Nodes::Sum.new([purchasable_arel]))).
104
+ select(:variant_id)
105
+ end
77
106
 
78
107
  # Rows in any of the named states — "out of stock, or with units on the
79
108
  # way" is one question a merchant asks, not two filters they combine.
@@ -58,6 +58,7 @@ module Spree
58
58
  validates :quantity, numericality: { greater_than: 0 }, allow_nil: true,
59
59
  if: -> { allocated? || released? || shipped? }
60
60
  validates :reason, presence: true, if: :adjusted?
61
+ validates :reason, length: { maximum: 255 }, allow_blank: true
61
62
 
62
63
  scope :recent, -> { order(created_at: :desc) }
63
64
  KINDS.each do |movement_kind|
@@ -3,23 +3,39 @@ module Spree
3
3
  class Destroy
4
4
  prepend Spree::ServiceModule::Base
5
5
 
6
+ # Destroys a deletable cart while serializing against checkout completion.
7
+ # Live completion claims leave the cart and its dependent records intact.
8
+ #
9
+ # @param cart [Spree::Cart, nil] cart to abandon
10
+ # @param order [Spree::Cart, Spree::Order, nil] deprecated input alias
11
+ # @return [Spree::ServiceModule::Result] deletion outcome
6
12
  def call(cart: nil, order: nil)
7
13
  if order
8
14
  Spree::Deprecation.warn('Calling Spree::Carts::Destroy with order: is deprecated and will be removed in Spree 6.1. Pass cart: instead.')
9
15
  cart ||= order
10
16
  end
11
17
  rewrite_input!(remove: [:order], cart: cart)
12
- run :check_if_can_be_destroyed
13
- run :cancel_shipments
14
- run :release_gift_card
15
- run :void_payments
16
- run :clear_addresses
17
- run :destroy_order
18
+ return failure(false, I18n.t('spree.cannot_be_destroyed')) unless cart
19
+
20
+ cart.with_lock do
21
+ run :check_if_can_be_destroyed
22
+ run :cancel_shipments
23
+ run :release_gift_card
24
+ run :void_payments
25
+ run :clear_addresses
26
+ run :destroy_order
27
+ end
18
28
  end
19
29
 
20
30
  private
21
31
 
32
+ # Refuses live completion claims and settled purchases before destructive steps.
33
+ #
34
+ # @param cart [Spree::Cart, Spree::Order] purchase being checked
35
+ # @return [Spree::ServiceModule::Result] deletion eligibility
22
36
  def check_if_can_be_destroyed(cart:)
37
+ return failure(false, I18n.t('spree.cart_completion_in_progress')) if cart.is_a?(Spree::Cart) && cart.completion_claimed?
38
+
23
39
  return failure(false, I18n.t('spree.cannot_be_destroyed')) unless cart&.can_be_deleted?
24
40
 
25
41
  success(cart: cart)