spree_core 6.0.2 → 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 (100) hide show
  1. checksums.yaml +4 -4
  2. data/app/jobs/spree/addresses/geocode_address_job.rb +6 -3
  3. data/app/jobs/spree/payments/handle_webhook_job.rb +12 -1
  4. data/app/jobs/spree/variants/remove_line_item_job.rb +5 -0
  5. data/app/models/concerns/spree/has_custom_fields.rb +4 -1
  6. data/app/models/concerns/spree/personal_data_matching.rb +5 -1
  7. data/app/models/concerns/spree/preference_schema.rb +5 -0
  8. data/app/models/concerns/spree/product_scopes.rb +2 -2
  9. data/app/models/concerns/spree/publishable.rb +26 -3
  10. data/app/models/concerns/spree/typed_associations.rb +53 -20
  11. data/app/models/spree/address.rb +2 -2
  12. data/app/models/spree/authentication/strategies/base_strategy.rb +10 -1
  13. data/app/models/spree/cart.rb +7 -2
  14. data/app/models/spree/collection.rb +7 -2
  15. data/app/models/spree/invitation.rb +6 -2
  16. data/app/models/spree/media.rb +25 -1
  17. data/app/models/spree/order.rb +6 -2
  18. data/app/models/spree/price.rb +3 -0
  19. data/app/models/spree/product.rb +21 -14
  20. data/app/models/spree/product_category.rb +7 -1
  21. data/app/models/spree/product_collection.rb +8 -1
  22. data/app/models/spree/promotion.rb +1 -2
  23. data/app/models/spree/seller.rb +93 -10
  24. data/app/models/spree/seller_requirements/complete_profile.rb +26 -7
  25. data/app/models/spree/stock_level.rb +30 -1
  26. data/app/models/spree/stock_movement.rb +1 -0
  27. data/app/services/spree/carts/destroy.rb +22 -6
  28. data/app/services/spree/collections/regenerate_products.rb +37 -15
  29. data/app/services/spree/companies/add_member.rb +9 -4
  30. data/app/services/spree/diagnostics/error_log.rb +139 -0
  31. data/app/services/spree/diagnostics/section.rb +72 -0
  32. data/app/services/spree/diagnostics/sections.rb +121 -0
  33. data/app/services/spree/diagnostics/stack.rb +73 -0
  34. data/app/services/spree/diagnostics.rb +132 -0
  35. data/app/services/spree/newsletter/subscribe.rb +8 -4
  36. data/app/services/spree/orders/create_from_cart.rb +6 -2
  37. data/app/services/spree/orders/remove_line_item.rb +16 -5
  38. data/app/services/spree/product_memberships.rb +21 -1
  39. data/app/services/spree/product_types/apply_to_products.rb +12 -2
  40. data/app/services/spree/products/auto_match_collections.rb +20 -4
  41. data/app/services/spree/stock_reservations/reserve.rb +9 -6
  42. data/app/services/spree/store_credits/apply.rb +9 -1
  43. data/app/services/spree/update_check.rb +7 -31
  44. data/app/tools/spree/agent_tools/create_export.rb +3 -1
  45. data/app/tools/spree/agent_tools/create_import.rb +1 -0
  46. data/app/tools/spree/agent_tools/create_media.rb +2 -1
  47. data/app/tools/spree/agent_tools/create_resource.rb +12 -4
  48. data/app/tools/spree/agent_tools/delete_resource.rb +12 -4
  49. data/app/tools/spree/agent_tools/describe_resource.rb +72 -6
  50. data/app/tools/spree/agent_tools/get_resource.rb +8 -5
  51. data/app/tools/spree/agent_tools/resource_write.rb +16 -3
  52. data/app/tools/spree/agent_tools/search_resources.rb +51 -20
  53. data/app/tools/spree/agent_tools/update_resource.rb +6 -6
  54. data/app/tools/spree/agent_tools/upload_file.rb +1 -0
  55. data/app/workflows/spree/carts/add_item.rb +51 -0
  56. data/app/workflows/spree/carts/complete.rb +18 -3
  57. data/app/workflows/spree/carts/merge.rb +25 -4
  58. data/app/workflows/spree/orders/complete.rb +39 -14
  59. data/app/workflows/spree/payments/handle_webhook.rb +7 -3
  60. data/app/workflows/spree/products/activate.rb +7 -2
  61. data/app/workflows/spree/products/archive.rb +7 -2
  62. data/app/workflows/spree/products/draft.rb +7 -2
  63. data/app/workflows/spree/products/status_transition.rb +24 -0
  64. data/app/workflows/spree/sellers/approve.rb +6 -0
  65. data/app/workflows/spree/sellers/create.rb +5 -2
  66. data/app/workflows/spree/stock_levels/bulk_upsert.rb +19 -7
  67. data/config/locales/be.yml +1 -1
  68. data/config/locales/en.yml +11 -0
  69. data/config/locales/fr.yml +1 -1
  70. data/config/locales/lt.yml +1 -1
  71. data/config/locales/ru.yml +1 -1
  72. data/config/locales/uk.yml +1 -1
  73. data/db/migrate/20240303174340_fix_spree_stock_item_unique_index.rb +14 -10
  74. data/db/migrate/20260814000001_rename_stock_items_to_stock_levels.rb +13 -7
  75. data/lib/generators/spree/api_resource/api_resource_generator.rb +35 -3
  76. data/lib/generators/spree/api_resource/templates/admin_controller.rb.tt +9 -4
  77. data/lib/generators/spree/api_resource/templates/admin_integration_spec.rb.tt +74 -0
  78. data/lib/generators/spree/api_resource/templates/store_controller.rb.tt +11 -6
  79. data/lib/spree/agent_tool.rb +105 -1
  80. data/lib/spree/agent_tools/default_catalog.rb +16 -21
  81. data/lib/spree/agent_tools/legacy_tools.rb +212 -0
  82. data/lib/spree/agent_tools/operation_catalog.rb +206 -0
  83. data/lib/spree/agent_tools/operation_tool.rb +189 -0
  84. data/lib/spree/agent_tools/record_summary.rb +8 -2
  85. data/lib/spree/agent_tools/registry.rb +65 -31
  86. data/lib/spree/agent_tools/resource_map.rb +207 -9
  87. data/lib/spree/agent_tools.rb +3 -3
  88. data/lib/spree/core/dependencies_helper.rb +96 -40
  89. data/lib/spree/core/engine.rb +12 -1
  90. data/lib/spree/core/version.rb +1 -1
  91. data/lib/spree/core.rb +30 -2
  92. data/lib/spree/reporting/default_vocabulary.rb +25 -5
  93. data/lib/spree/testing_support/extension_rake.rb +12 -0
  94. data/lib/spree/upgrades/5_6_to_6_0/manifest.yml +34 -0
  95. data/lib/tasks/dependencies.rake +2 -2
  96. data/lib/tasks/diagnostics.rake +11 -0
  97. metadata +29 -7
  98. data/lib/spree/agent_tools/workflow_endpoints.rb +0 -88
  99. data/lib/spree/agent_tools/workflow_schema.rb +0 -279
  100. data/lib/spree/agent_tools/workflow_tool.rb +0 -654
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 95b9df74c721a763fd81c0ca389f4bf996400ed8e1a262ca031228387157be16
4
- data.tar.gz: ff8cd8cc1294aaa4eea49a2fbcd0c6319b15ed59d77988af865d48ae56782bf2
3
+ metadata.gz: e465daf49ecae5d15b57e998d9ea505ee2eba53224668e370c290536aad30736
4
+ data.tar.gz: 1a7596942af23ef5da1830f75c76acf3f6bad00e92e1b95b1f400424ddfa7603
5
5
  SHA512:
6
- metadata.gz: 94d512c61c6b2e6aa3c8672c883ea406af8efb8c509fe7ba0f0a49d58c02aa767d23a9ff82e8532965e32217130aeff39074c78d5b8d0896de6f8dac9e7e19e7
7
- data.tar.gz: cb944067256bc44223bca95b0c00bcf17f242745c2885ea063d7549592ebdbb013c0138359fb60326b662ae4b4ed583fdba553fc2f42378fa3952049b69d7af2
6
+ metadata.gz: 3fab6326b8031e792e88fe83aedc58879cef258f145fc828ae04c39425e1c0e1359a4e2ee26d4d64f7abea3b72cd7e79ceb2ba4c6e4dc045e5a266bd0c351255
7
+ data.tar.gz: 8dd0f193ddc437e1ab18983e34713743928ec239e4baa025f93aed3bc4b3e6bc85ac0e36630859a561fd1f901fef77cec49685e254c303d1502e2f53ca694e39
@@ -16,11 +16,14 @@ module Spree
16
16
  if coordinates.present?
17
17
  address.update_columns(latitude: coordinates[0], longitude: coordinates[1], updated_at: Time.current)
18
18
  else
19
- # Unfortunately there is no way to get the error message from Geocoder,
20
- # but the request is fully displayed in the server logs
19
+ # An address the geocoder cannot resolve is a data problem rather than
20
+ # a bug, so it is reported as a handled warning. Unfortunately there is
21
+ # no way to get the error message from Geocoder, but the request is
22
+ # fully displayed in the server logs
21
23
  Rails.error.report(
22
24
  GeocodeAddressError.new("Cannot geocode address ID: #{address.id}"),
23
- handled: false,
25
+ handled: true,
26
+ severity: :warning,
24
27
  context: { address_id: address_id },
25
28
  source: 'spree.core'
26
29
  )
@@ -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
@@ -7,6 +7,11 @@ module Spree
7
7
  owner = line_item.owner
8
8
  return if owner.nil?
9
9
 
10
+ # A completed cart is a read-only audit record; the order it became
11
+ # owns the lines now. The cart can complete between this job being
12
+ # enqueued and running, and there is nothing left to remove from it.
13
+ return if owner.is_a?(Spree::Cart) && owner.readonly?
14
+
10
15
  # Carts and draft orders have different contracts: the cart side turns
11
16
  # a vetoed removal into a warning and still succeeds, the order side
12
17
  # fails outright. Routing an order-owned line through the cart
@@ -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.
@@ -217,6 +217,11 @@ module Spree
217
217
  registered_subclasses.find { |klass| klass.api_type == shorthand.to_s }
218
218
  end
219
219
 
220
+ # @return [Array<String>] the wire name of every registered subclass
221
+ def api_types
222
+ registered_subclasses.map(&:api_type)
223
+ end
224
+
220
225
  # Returns a `[{ type:, label:, description:, schema: }]` array for every
221
226
  # registered subclass, sorted by label for stable output. `schema` is
222
227
  # the JSON Schema of the subclass's `preferences`, which never carries a
@@ -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
@@ -37,37 +37,55 @@ module Spree
37
37
  reconcile_typed_association(association, pending)
38
38
  end
39
39
 
40
- # Flushes a pending payload from `@pending_<assoc>` (typically from
41
- # an `after_save` hook) and clears the ivar.
40
+ # Flushes the pending payloads from `@pending_<assoc>` (typically from
41
+ # an `after_save` hook) and clears them.
42
42
  #
43
+ # Every association is written before any buffer is cleared: a refused
44
+ # row rolls the whole save back, and a retried save must carry every
45
+ # payload again rather than persist the owner with the rows that
46
+ # happened to come first.
47
+ #
48
+ # @param associations [Array<Symbol>]
49
+ # @return [void]
50
+ def flush_pending_typed_associations(*associations)
51
+ pending = associations.to_h { |association| [association, instance_variable_get(:"@pending_#{association}")] }.compact
52
+ pending.each { |association, rows| reconcile_typed_association(association, rows) }
53
+ pending.each_key { |association| instance_variable_set(:"@pending_#{association}", nil) }
54
+ end
55
+
43
56
  # @param association [Symbol]
44
57
  # @return [void]
45
58
  def flush_pending_typed_association(association)
46
- ivar = :"@pending_#{association}"
47
- pending = instance_variable_get(ivar)
48
- return unless pending
49
-
50
- instance_variable_set(ivar, nil)
51
- reconcile_typed_association(association, pending)
59
+ flush_pending_typed_associations(association)
52
60
  end
53
61
 
62
+ # All or nothing: on a saved parent the rows are written as they are
63
+ # assigned, so a refusal on the second row used to leave the first one
64
+ # behind — a list the caller never asked for, answered with a 422.
54
65
  def reconcile_typed_association(association, rows)
55
66
  collection = public_send(association)
56
- kept_ids = rows.each_with_index.filter_map { |row, index| save_typed_association_row(collection, row, "/#{association.to_s.split('_').last}/#{index}") }
57
- if kept_ids.any? || rows.empty?
58
- collection.where.not(id: kept_ids).destroy_all
59
- # `where.not(...).destroy_all` deletes the dropped rows from the DB but
60
- # leaves them in the already-loaded association target. Reset so a
61
- # same-request read (e.g. the serializer rendering `rule_ids`) reflects
62
- # the removal instead of echoing ghosts.
67
+ begin
68
+ self.class.transaction do
69
+ kept_ids = rows.each_with_index.map { |row, index| save_typed_association_row(collection, row, "/#{association.to_s.split('_').last}/#{index}") }
70
+ collection.where.not(id: kept_ids).destroy_all
71
+ # `where.not(...).destroy_all` deletes the dropped rows from the DB but
72
+ # leaves them in the already-loaded association target. Reset so a
73
+ # same-request read (e.g. the serializer rendering `rule_ids`) reflects
74
+ # the removal instead of echoing ghosts.
75
+ collection.reset
76
+ end
77
+ rescue StandardError
78
+ # The rows built before the refusal are still in the loaded target, and
79
+ # the owner's next save would write them; the rollback only undid the
80
+ # database.
63
81
  collection.reset
82
+ raise
64
83
  end
65
84
  end
66
85
 
67
86
  # @param pointer [String] where the row sits in the request, e.g. `/rules/1`
68
87
  def save_typed_association_row(collection, row, pointer)
69
- record = find_or_build_typed_association_row(collection, row)
70
- return nil unless record
88
+ record = find_or_build_typed_association_row(collection, row, pointer)
71
89
 
72
90
  preferences = row[:preferences]
73
91
  calculator = row[:calculator]
@@ -100,15 +118,19 @@ module Spree
100
118
  raise
101
119
  end
102
120
 
103
- def find_or_build_typed_association_row(collection, row)
121
+ def find_or_build_typed_association_row(collection, row, pointer)
104
122
  if row[:id].present?
105
123
  id = Spree::PrefixedId.prefixed_id?(row[:id]) ? Spree::PrefixedId.decode_prefixed_id(row[:id]) : row[:id]
106
124
  existing = collection.find { |r| r.id == id } || collection.find_by(id: id)
107
125
  return existing if existing
108
126
  end
109
127
 
110
- klass = collection.proxy_association.klass.find_by_api_type(row[:type])
111
- return nil unless klass
128
+ family = collection.proxy_association.klass
129
+ klass = family.find_by_api_type(row[:type])
130
+ # Refused, not skipped: a dropped row answered the request with a 200
131
+ # and a promotion that discounted nothing. Naming the accepted types is
132
+ # what lets an API client or an agent correct itself.
133
+ raise unknown_row_type_error(family, row[:type], pointer) unless klass
112
134
 
113
135
  # `build(type:) + becomes(klass)` would leave a stale STI-parent stub
114
136
  # in the collection target alongside the becomes'd copy; autosave then
@@ -117,5 +139,16 @@ module Spree
117
139
  collection.proxy_association.add_to_target(record)
118
140
  record
119
141
  end
142
+
143
+ def unknown_row_type_error(family, type, pointer)
144
+ types = family.api_types.sort.join(', ')
145
+ message = if type.blank?
146
+ I18n.t('spree.errors.messages.missing_row_type', types: types)
147
+ else
148
+ I18n.t('spree.errors.messages.unknown_row_type', type: type, family: family.model_name.human.downcase, types: types)
149
+ end
150
+
151
+ Spree::Preferences::InvalidPreferences.new([{ pointer: '/type', message: message }], prefix: pointer)
152
+ end
120
153
  end
121
154
  end
@@ -270,10 +270,10 @@ module Spree
270
270
  #
271
271
  # @return [String, nil]
272
272
  def company
273
- stored = read_attribute(:company)
273
+ stored = super
274
274
  return stored if stored.present?
275
275
 
276
- owner.name if owner.is_a?(Spree::Company)
276
+ owner&.name if owner_type == 'Spree::Company'
277
277
  end
278
278
 
279
279
  # Whether the owner prefills with this address. Every owner keeps the
@@ -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)
@@ -203,10 +203,15 @@ module Spree
203
203
  existing_by_id = rules.to_a.index_by(&:id)
204
204
  retained_ids = []
205
205
 
206
- rules_params.each do |rule_data|
206
+ rules_params.each_with_index do |rule_data, index|
207
207
  data = rule_data.to_h.with_indifferent_access
208
208
  rule_id = data.delete(:id)
209
- data[:type] = self.class.resolve_rule_type(data[:type]) if data.key?(:type)
209
+ if data.key?(:type) || rule_id.blank?
210
+ # Refused with the accepted kinds named; letting the nil through
211
+ # answered "type can't be blank" to a caller who had sent one.
212
+ data[:type] = self.class.resolve_rule_type(data[:type]) ||
213
+ raise(unknown_row_type_error(Spree::CollectionRule, data[:type], "/rules/#{index}"))
214
+ end
210
215
 
211
216
  record = if rule_id.present?
212
217
  existing_by_id[Spree::PrefixedId.decode_prefixed_id(rule_id) || rule_id] ||
@@ -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
@@ -829,7 +833,7 @@ module Spree
829
833
  # reaches it through +Spree.carts_complete_workflow+). Removed in 6.1.
830
834
  def finalize!
831
835
  Spree::Deprecation.warn('Spree::Order#finalize! is deprecated and will be removed in Spree 6.1. Completion runs through Spree.order_complete_workflow (Spree::Orders::Complete).')
832
- Spree.order_complete_workflow.call(order: self, payment_pending: true)
836
+ Spree.order_complete_workflow.call(order: self, payment_pending: true, validated: true)
833
837
  end
834
838
 
835
839
  def fulfill!
@@ -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
 
@@ -746,15 +748,25 @@ module Spree
746
748
  variants.active(current_currency).joins(:option_value_variants)
747
749
  end
748
750
 
751
+ # Units purchasable now across every variant: on hand, less what orders
752
+ # have taken and what checkouts are holding, at active locations, floored
753
+ # at zero per variant. Infinite when any variant does not track inventory.
749
754
  def total_on_hand
750
755
  @total_on_hand ||= if any_variants_not_track_inventory?
751
756
  BigDecimal::INFINITY
757
+ elsif variants.loaded?
758
+ variants.sum(&:total_on_hand)
752
759
  else
753
- if variants.loaded?
754
- variants.sum(&:total_on_hand)
755
- else
756
- stock_levels.loaded? ? stock_levels.sum(&:available_count) : stock_levels.sum('count_on_hand - allocated_count')
757
- end
760
+ # The same figure in one query: the per-variant floor
761
+ # needs the sums grouped before they are added up.
762
+ # Unordered, since the variants' position order cannot
763
+ # sit beside a GROUP BY on PostgreSQL. Holds count only
764
+ # while the store reserves stock, as on each variant.
765
+ levels = Spree::StockLevel.arel_table
766
+ purchasable = levels[:count_on_hand] - levels[:allocated_count]
767
+ purchasable -= levels[:reserved_count] if store_preference(:stock_reservations_enabled)
768
+ stock_levels.with_active_stock_location.unscope(:order).group(:variant_id).
769
+ sum(purchasable).values.sum { |count| [count, 0].max }
758
770
  end
759
771
  end
760
772
 
@@ -1025,11 +1037,6 @@ module Spree
1025
1037
  end
1026
1038
  end
1027
1039
 
1028
- def remove_category(category)
1029
- removed_product_categories = product_categories.where(category: category)
1030
- removed_product_categories.each(&:remove_from_list)
1031
- end
1032
-
1033
1040
  def discontinue_on_must_be_later_than_make_active_at
1034
1041
  if discontinue_on < make_active_at
1035
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
 
@@ -373,8 +373,7 @@ module Spree
373
373
  end
374
374
 
375
375
  def apply_pending_rules_and_actions
376
- flush_pending_typed_association(:promotion_rules)
377
- flush_pending_typed_association(:promotion_actions)
376
+ flush_pending_typed_associations(:promotion_rules, :promotion_actions)
378
377
  end
379
378
 
380
379
  # Runs before the promotion's actions are destroyed, since the carts'