spree_core 6.0.5 → 6.0.6

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 (82) hide show
  1. checksums.yaml +4 -4
  2. data/app/jobs/spree/payments/handle_modification_webhook_job.rb +93 -0
  3. data/app/jobs/spree/payments/handle_webhook_job.rb +4 -2
  4. data/app/maintenance_tasks/spree/maintenance_tasks/upgrade/backfill_settlement_statuses.rb +40 -0
  5. data/app/models/concerns/spree/customer_methods.rb +1 -1
  6. data/app/models/concerns/spree/product_scopes.rb +5 -2
  7. data/app/models/concerns/spree/purchase/payment_processing.rb +11 -0
  8. data/app/models/concerns/spree/purchase/purchase_order.rb +21 -0
  9. data/app/models/concerns/spree/purchase/totals.rb +3 -2
  10. data/app/models/concerns/spree/ransackable_attributes.rb +81 -4
  11. data/app/models/concerns/spree/settlement_status.rb +29 -0
  12. data/app/models/concerns/spree/stores/markets.rb +0 -30
  13. data/app/models/spree/base.rb +3 -3
  14. data/app/models/spree/category.rb +53 -32
  15. data/app/models/spree/collection_rule.rb +5 -1
  16. data/app/models/spree/export.rb +3 -1
  17. data/app/models/spree/exports/products.rb +9 -1
  18. data/app/models/spree/fulfillment.rb +23 -6
  19. data/app/models/spree/fulfillment_group.rb +2 -2
  20. data/app/models/spree/gateway/bogus.rb +41 -2
  21. data/app/models/spree/gift_card.rb +14 -2
  22. data/app/models/spree/media.rb +1 -1
  23. data/app/models/spree/option_type.rb +1 -0
  24. data/app/models/spree/order.rb +10 -4
  25. data/app/models/spree/order_group.rb +2 -2
  26. data/app/models/spree/payment/custom_events.rb +2 -1
  27. data/app/models/spree/payment/processing.rb +20 -3
  28. data/app/models/spree/payment.rb +186 -7
  29. data/app/models/spree/payment_capture_event.rb +2 -0
  30. data/app/models/spree/payment_method/store_credit.rb +6 -0
  31. data/app/models/spree/payment_method.rb +54 -2
  32. data/app/models/spree/payment_response.rb +19 -0
  33. data/app/models/spree/payment_session.rb +15 -3
  34. data/app/models/spree/payment_split.rb +14 -2
  35. data/app/models/spree/price.rb +1 -0
  36. data/app/models/spree/product.rb +4 -4
  37. data/app/models/spree/purchase_order.rb +20 -3
  38. data/app/models/spree/refund.rb +7 -1
  39. data/app/models/spree/return.rb +7 -1
  40. data/app/models/spree/search_provider/base.rb +10 -0
  41. data/app/models/spree/search_provider/database.rb +8 -5
  42. data/app/models/spree/store.rb +22 -0
  43. data/app/models/spree/store_credit.rb +1 -1
  44. data/app/models/spree/variant.rb +33 -0
  45. data/app/presenters/spree/csv/product_variant_presenter.rb +17 -8
  46. data/app/serializers/spree/emails/store_serializer.rb +1 -1
  47. data/app/services/spree/carts/split_by_seller.rb +4 -13
  48. data/app/services/spree/orders/create_from_cart.rb +2 -0
  49. data/app/services/spree/orders/update_statuses.rb +4 -2
  50. data/app/services/spree/store_credits/apply.rb +1 -1
  51. data/app/subscribers/spree/order_status_subscriber.rb +4 -3
  52. data/app/subscribers/spree/payment_split_subscriber.rb +39 -21
  53. data/app/subscribers/spree/seller_transfer_reversal_subscriber.rb +19 -7
  54. data/app/tools/spree/agent_tools/query_report.rb +116 -14
  55. data/app/workflows/spree/carts/complete.rb +1 -19
  56. data/app/workflows/spree/carts/recalculate_totals.rb +3 -3
  57. data/app/workflows/spree/orders/cancel.rb +19 -0
  58. data/app/workflows/spree/orders/complete.rb +7 -1
  59. data/app/workflows/spree/payments/capture.rb +99 -5
  60. data/app/workflows/spree/payments/handle_modification_webhook.rb +218 -0
  61. data/app/workflows/spree/payments/handle_webhook.rb +7 -1
  62. data/app/workflows/spree/payments/process.rb +47 -4
  63. data/app/workflows/spree/payments/void.rb +4 -1
  64. data/app/workflows/spree/products/approve.rb +17 -0
  65. data/app/workflows/spree/refunds/create.rb +10 -1
  66. data/app/workflows/spree/refunds/order_payments.rb +3 -1
  67. data/config/locales/be.yml +2 -2
  68. data/config/locales/bg.yml +4 -4
  69. data/config/locales/en.yml +8 -0
  70. data/config/locales/ru.yml +3 -3
  71. data/db/migrate/20261116100001_add_status_to_spree_payment_capture_events_and_refunds.rb +17 -0
  72. data/lib/spree/agent_tool.rb +11 -4
  73. data/lib/spree/core/dependencies.rb +1 -0
  74. data/lib/spree/core/version.rb +1 -1
  75. data/lib/spree/reporting/adapters/live.rb +69 -8
  76. data/lib/spree/reporting/default_vocabulary.rb +10 -4
  77. data/lib/spree/reporting/query.rb +4 -1
  78. data/lib/spree/reporting/registry.rb +50 -3
  79. data/lib/spree/testing_support/factories/payment_capture_event_factory.rb +10 -0
  80. data/lib/spree/testing_support/factories/refund_factory.rb +10 -0
  81. data/lib/spree/upgrades/5_6_to_6_0/manifest.yml +57 -0
  82. metadata +23 -4
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: d62d8e35b3c55f0a54ef1afb0e8270bfb1391899f12b3959ca6959324953e84d
4
- data.tar.gz: bd148a4547773fff7263a12765b45f5c2573612190ca06293204a7c25c73d775
3
+ metadata.gz: a5194af3427b9ca7bc42294f49a00db40225b42ef85b129625545f91da07ce74
4
+ data.tar.gz: a4f7d851aefe2c406973b9e3f034f9523e99c1e2d83f90e2965d35d28ac02799
5
5
  SHA512:
6
- metadata.gz: cacd3ad126f55a1cf7ec44ed1d243041bf1617ea3a38a303373995c39a96c9e2b6ab6d7eaf17f11ba4ba0bca7ee63dba8a4b3b3e7185473849afdd6a99afde68
7
- data.tar.gz: 27d668eb15bc37af05a04143de22cabc308dec4c14d2e63a15b8697d7c97ee3e18eedd82ce7844aeae6528abda210a629839f5fe21e507cd41be861d287b78e5
6
+ metadata.gz: 9a79ca48edd3e8b2caf20ec031be2fbb7f208cf256422a81177a774d2b7e8032d1fcfc193a169b5626e517d536289f456f16827db3e41cba5b4d179a311cb541
7
+ data.tar.gz: 0e92e81e2f39f437bee1efac62983ccbade8883a2b3f8c1f0ae4b6167f1edaa0d9ddbbf0c31e55be9659232e13c30b331cea22304ca0b59c5fb7a690dc8ab12b
@@ -0,0 +1,93 @@
1
+ module Spree
2
+ module Payments
3
+ # Runs Spree::Payments::HandleModificationWebhook for an outcome the
4
+ # webhook endpoint accepted: the provider got its 200 already and will not
5
+ # send it again, so a failure is retried here.
6
+ #
7
+ # An outcome can name a record Spree has not written yet: it arrived
8
+ # before the request that writes it finished, or that request's answer
9
+ # never reached Spree and a retry of it writes the record later. The job
10
+ # waits for the record as long as a retried request still gets the
11
+ # provider's first answer.
12
+ class HandleModificationWebhookJob < Spree::BaseJob
13
+ queue_as Spree.queues.payment_webhooks
14
+
15
+ retry_on ActiveRecord::Deadlocked, wait: 5.seconds, attempts: 3
16
+ retry_on ActiveRecord::LockWaitTimeout, wait: 5.seconds, attempts: 3
17
+ discard_on ActiveRecord::RecordNotFound
18
+
19
+ class OutcomeFailed < StandardError; end
20
+ # The wait ended with no record: an action taken outside Spree, or a
21
+ # request whose answer never reached Spree and that nobody retried.
22
+ class RecordNeverWritten < StandardError; end
23
+
24
+ retry_on OutcomeFailed, wait: :polynomially_longer, attempts: 5
25
+
26
+ CAPTURE_ACTIONS = %w[capture_succeeded capture_failed].freeze
27
+ # How long a retried request still gets the provider's first answer:
28
+ # Adyen keeps an idempotency key for at least 7 days.
29
+ RECORD_WAIT = 7.days
30
+ # Longer than any gateway call takes with its own retries, so after it
31
+ # no request for this outcome can still be running.
32
+ ANSWER_WINDOW = 5.minutes
33
+
34
+ # @param reference [String] the provider reference the outcome names its record by
35
+ # @param received_at [String] when the endpoint accepted the outcome, ISO 8601
36
+ # @param payment_id [Integer, nil] the payment a capture outcome's capture was asked for
37
+ def perform(payment_method_id:, action:, reference:, received_at:, payment_id: nil, metadata: {})
38
+ payment_method = Spree::PaymentMethod.find(payment_method_id)
39
+ Spree::Current.store = payment_method.store
40
+ received_at = Time.zone.parse(received_at)
41
+
42
+ record = payment_method.modification_record(action.to_sym, reference) ||
43
+ unanswered_capture(payment_method, action, reference, payment_id, metadata, received_at)
44
+ return wait_for_record(payment_method, action, reference, received_at) if record.nil?
45
+
46
+ result = Spree.payments_handle_modification_webhook_workflow.call(
47
+ payment_method: payment_method,
48
+ action: action.to_sym,
49
+ record: record,
50
+ metadata: metadata
51
+ )
52
+
53
+ raise OutcomeFailed, "#{action} #{reference}: #{result.error}" if result&.failure?
54
+ end
55
+
56
+ private
57
+
58
+ # A capture whose answer never reached Spree leaves its payment
59
+ # processing, with no capture event waiting. Once no request can still be
60
+ # running, the event is written as the request would have, so the
61
+ # outcome settles it.
62
+ def unanswered_capture(payment_method, action, reference, payment_id, metadata, received_at)
63
+ return unless CAPTURE_ACTIONS.include?(action.to_s) && payment_id
64
+ return if Time.current - received_at < ANSWER_WINDOW
65
+
66
+ payment = Spree::Payment.where(payment_method_id: payment_method.id).find_by(id: payment_id)
67
+ return if payment.nil?
68
+
69
+ payment.with_lock do
70
+ next unless payment.processing? && payment.capture_events.where(status: 'requested').none?
71
+
72
+ amount = metadata['amount'].presence&.to_d || payment.amount
73
+ payment.capture_events.create!(amount: amount, status: 'requested', transaction_id: reference)
74
+ end
75
+ end
76
+
77
+ # Looks again quickly at first, when the record is most likely only
78
+ # moments away, then every few hours.
79
+ def wait_for_record(payment_method, action, reference, received_at)
80
+ if Time.current - received_at < RECORD_WAIT
81
+ retry_job(wait: [5.seconds * (4**(executions - 1).clamp(0, 8)), 6.hours].min)
82
+ else
83
+ Rails.error.report(
84
+ RecordNeverWritten.new("#{action} names no record: #{reference}"),
85
+ handled: true,
86
+ context: { payment_method_id: payment_method.id, action: action, reference: reference },
87
+ source: 'spree.payments.modification_webhook'
88
+ )
89
+ end
90
+ end
91
+ end
92
+ end
93
+ end
@@ -16,7 +16,8 @@ module Spree
16
16
 
17
17
  retry_on SettlementFailed, wait: :polynomially_longer, attempts: 5
18
18
 
19
- def perform(payment_method_id:, action:, payment_session_id:)
19
+ # metadata defaults to {} so jobs enqueued before it was passed still run.
20
+ def perform(payment_method_id:, action:, payment_session_id:, metadata: {})
20
21
  payment_method = Spree::PaymentMethod.find(payment_method_id)
21
22
  Spree::Current.store = payment_method.store
22
23
  payment_session = Spree::PaymentSession.find(payment_session_id)
@@ -24,7 +25,8 @@ module Spree
24
25
  result = Spree.payments_handle_webhook_workflow.call(
25
26
  payment_method: payment_method,
26
27
  action: action.to_sym,
27
- payment_session: payment_session
28
+ payment_session: payment_session,
29
+ metadata: metadata
28
30
  )
29
31
 
30
32
  raise SettlementFailed, "Payment session #{payment_session.id}: #{result.error}" if result&.failure?
@@ -0,0 +1,40 @@
1
+ module Spree
2
+ module MaintenanceTasks
3
+ module Upgrade
4
+ # Capture events and refunds gained a status in a 6.0 patch release (a
5
+ # gateway may now answer that it is still waiting on its provider), added
6
+ # empty by the migration. Every row written before then is money that
7
+ # moved, so it is marked completed here. Walks payments, the one record
8
+ # both tables hang from, so the run has a single cursor.
9
+ class BackfillSettlementStatuses < Spree::MaintenanceTask
10
+ supports_dry_run
11
+ collection_batch_size 1_000
12
+
13
+ def collection
14
+ capture_event_payment_ids = Spree::PaymentCaptureEvent.where(status: nil).select(:payment_id)
15
+ refund_payment_ids = Spree::Refund.where(status: nil).select(:payment_id)
16
+
17
+ Spree::Payment.unscoped.
18
+ where(id: capture_event_payment_ids).
19
+ or(Spree::Payment.unscoped.where(id: refund_payment_ids)).
20
+ order(:id)
21
+ end
22
+
23
+ def process(payment)
24
+ capture_events = Spree::PaymentCaptureEvent.where(payment_id: payment.id, status: nil)
25
+ refunds = Spree::Refund.where(payment_id: payment.id, status: nil)
26
+
27
+ if dry_run?
28
+ tally(:capture_events_would_complete, capture_events.count)
29
+ tally(:refunds_would_complete, refunds.count)
30
+ return
31
+ end
32
+
33
+ now = Time.current
34
+ tally(:capture_events_completed, capture_events.update_all(status: 'completed', updated_at: now))
35
+ tally(:refunds_completed, refunds.update_all(status: 'completed', updated_at: now))
36
+ end
37
+ end
38
+ end
39
+ end
40
+ end
@@ -198,7 +198,7 @@ module Spree
198
198
  # Two-state scope: see Spree::Base.ransack_flag? for why the cast is
199
199
  # opted out of here and done inside the scope instead.
200
200
  def self.ransackable_scopes_skip_sanitize_args
201
- %i[anonymized]
201
+ super | %w[anonymized]
202
202
  end
203
203
 
204
204
  # Whether an erasure has been carried out. A scope rather than a
@@ -193,7 +193,10 @@ module Spree
193
193
  # a red XL. Every axis is therefore counted against the same variant row
194
194
  # rather than asked of the product separately — which is also what keeps
195
195
  # a filter honest once several sellers list variants on one product.
196
- def self.with_option_value_ids(*ids)
196
+ #
197
+ # +variants+ narrows which variants may answer: the storefront passes
198
+ # +Variant.for_option_filters+, while the admin keeps every variant.
199
+ def self.with_option_value_ids(*ids, variants: nil)
197
200
  ids = ids.flatten.compact
198
201
  return none if ids.empty?
199
202
 
@@ -203,7 +206,7 @@ module Spree
203
206
  grouped = OptionValue.where(id: actual_ids).group_by(&:option_type_id)
204
207
  return none if grouped.empty?
205
208
 
206
- matching_product_ids = Variant.where(deleted_at: nil).
209
+ matching_product_ids = (variants || Variant).where(deleted_at: nil).
207
210
  joins(option_value_variants: :option_value).
208
211
  where(OptionValue.table_name => { id: actual_ids }).
209
212
  group(Variant.arel_table[:id]).
@@ -62,6 +62,14 @@ module Spree
62
62
  payments.select(&:checkout?)
63
63
  end
64
64
 
65
+ # What is still owed once every live payment is counted, settled or not —
66
+ # the amount a new payment should be for. Never negative.
67
+ #
68
+ # @return [BigDecimal]
69
+ def amount_left_to_pay
70
+ [outstanding_balance - valid_payments.reject { |payment| payment.status == 'completed' }.sum(BigDecimal('0'), &:amount), BigDecimal('0')].max
71
+ end
72
+
65
73
  private
66
74
 
67
75
  # On a list the association batches across the page, so the loaded rows
@@ -85,6 +93,9 @@ module Spree
85
93
 
86
94
  unprocessed_payments.each do |payment|
87
95
  break if settled_payment_total >= total
96
+ # An order can carry several live payments; once those processed
97
+ # so far cover it, net of refunds, the rest are left uncharged.
98
+ break if is_a?(Spree::Order) && payment.amount_owed_by_order(including_in_flight: true)&.zero?
88
99
 
89
100
  result = Spree.payment_process_workflow.call(payment: payment, action: action)
90
101
  raise Spree::Core::GatewayError, result.error.value.to_s if result.failure?
@@ -67,6 +67,27 @@ module Spree
67
67
  resolved_company&.po_number_required? || false
68
68
  end
69
69
 
70
+ # Attaches the purchase order document of +source+ to this persisted
71
+ # record. The same blob is attached to both rather than uploaded twice,
72
+ # and the source keeps its copy, so a transaction that rolls back leaves
73
+ # the buyer's upload where they left it.
74
+ #
75
+ # On a persisted, unchanged record `attach` saves at once and answers
76
+ # nil instead of raising when the save is refused. Unchecked, the record
77
+ # would silently have no paperwork, so the refusal is raised instead.
78
+ #
79
+ # @param source [Spree::Cart, Spree::Order]
80
+ # @raise [ActiveRecord::RecordInvalid] when the document is refused
81
+ # @return [void]
82
+ def copy_po_document_from!(source)
83
+ return unless source.po_document.attached?
84
+ return if po_document.attach(source.po_document.blob)
85
+
86
+ # A callback can refuse the save without saying why.
87
+ errors.add(:po_document, :invalid) if errors.empty?
88
+ raise ActiveRecord::RecordInvalid, self
89
+ end
90
+
70
91
  private
71
92
 
72
93
  # The size validation above reads the blob's recorded `byte_size`, which
@@ -119,7 +119,7 @@ module Spree
119
119
  (own + others.to_a).uniq(&:id)
120
120
  end
121
121
 
122
- # Completed payments less their refunds, as a scalar subquery so the
122
+ # Completed payments less their completed refunds, as a scalar subquery so the
123
123
  # sum and the write are one statement.
124
124
  #
125
125
  # @return [Arel::Nodes::Grouping]
@@ -136,7 +136,8 @@ module Spree
136
136
  where(payments_table[:status].eq('completed'))
137
137
 
138
138
  refunded = refunds_table.project(refunds_table[:amount].sum).
139
- where(refunds_table[:payment_id].in(settled))
139
+ where(refunds_table[:payment_id].in(settled)).
140
+ where(refunds_table[:status].eq(nil).or(refunds_table[:status].eq('completed')))
140
141
 
141
142
  Arel::Nodes::NamedFunction.new(
142
143
  'COALESCE',
@@ -32,9 +32,8 @@ module Spree::RansackableAttributes
32
32
 
33
33
  class_attribute :default_ransackable_attributes
34
34
  # `position` is included so any `acts_as_list` model is sortable by it
35
- # without each subclass having to opt in. Ransack ignores attributes
36
- # the model doesn't actually expose, so this is a no-op for tables
37
- # without a position column.
35
+ # without each subclass having to opt in. Each one is offered only where
36
+ # the model has it, since filtering on a missing column fails in SQL.
38
37
  self.default_ransackable_attributes = %w[id name updated_at created_at position]
39
38
 
40
39
  def self.ransackable_associations(auth_object = nil)
@@ -47,7 +46,8 @@ module Spree::RansackableAttributes
47
46
  end
48
47
 
49
48
  def self.ransackable_attributes(auth_object = nil)
50
- base = default_ransackable_attributes | (whitelisted_ransackable_attributes || [])
49
+ base = default_ransackable_attributes.select { |attribute| ransack_attribute_defined?(attribute) }
50
+ base |= whitelisted_ransackable_attributes || []
51
51
  base |= Spree.ransack.custom_attributes_for(self)
52
52
  return base unless Spree::RansackableAttributes.restricted_audience?(auth_object)
53
53
 
@@ -63,6 +63,12 @@ module Spree::RansackableAttributes
63
63
  base - Array(private_ransackable_scopes[auth_object.to_sym])
64
64
  end
65
65
 
66
+ def self.ransack_attribute_defined?(attribute)
67
+ attribute_names.include?(attribute) || _ransackers.key?(attribute) || attribute_aliases.key?(attribute) ||
68
+ (respond_to?(:translatable_fields) && translatable_fields.map(&:to_s).include?(attribute))
69
+ end
70
+ private_class_method :ransack_attribute_defined?
71
+
66
72
  # Declares the `search` filter (`q[search]=term`): a case-insensitive
67
73
  # partial match on any of the given attributes, which may reach through
68
74
  # associations (`variant_sku`). It runs as Ransack's `_cont` on those
@@ -100,6 +106,77 @@ module Spree::RansackableAttributes
100
106
  end
101
107
  end
102
108
 
109
+ # In `class_methods`, not `included`, so a model that opts a scope out of
110
+ # Ransack's cast can extend the list with `super`.
111
+ class_methods do
112
+ # The arguments a ransackable scope takes: what the model or
113
+ # `Spree.ransack.add_scope` declared, else what its signature shows. A
114
+ # `scope` lambda hides its signature, so an undeclared one reads as text.
115
+ #
116
+ # @param scope [String, Symbol]
117
+ # @return [String, Array<String>, Hash] one kind, a list of kinds
118
+ # (positional arguments), or `{ 'list' => kind }` for any number of them
119
+ def ransackable_scope_type(scope)
120
+ declared_ransackable_scope_types.fetch(scope.to_s) do
121
+ Spree::RansackableAttributes.scope_type_from_signature(method(scope))
122
+ end
123
+ end
124
+
125
+ # Ransack turns `1`, `t` and `true` into `true`, and `0`, `f` and `false`
126
+ # into `false`, before calling a scope, and skips a scope given `false`.
127
+ # Only a flag wants that: a search for "1" must reach `search` as "1". A
128
+ # `scope` lambda declared without a type keeps the cast, since nothing
129
+ # shows whether it takes a value at all.
130
+ #
131
+ # @return [Array<String>]
132
+ def ransackable_scopes_skip_sanitize_args
133
+ declared = declared_ransackable_scope_types
134
+ ransackable_scopes.map(&:to_s).select do |scope|
135
+ next false unless respond_to?(scope)
136
+
137
+ signature = method(scope)
138
+ next false if !declared.key?(scope) && Spree::RansackableAttributes.signature_hidden?(signature)
139
+
140
+ declared.fetch(scope) { Spree::RansackableAttributes.scope_type_from_signature(signature) }.to_s != 'boolean'
141
+ end
142
+ end
143
+
144
+ private
145
+
146
+ def declared_ransackable_scope_types
147
+ declared = search_attributes.any? ? { 'search' => 'text' } : {}
148
+ declared.merge(ransackable_scope_types.stringify_keys, Spree.ransack.custom_scope_types_for(self).stringify_keys)
149
+ end
150
+ end
151
+
152
+ # What a method's signature says about the arguments a scope takes.
153
+ #
154
+ # @param method [Method]
155
+ # @return [String, Array<String>, Hash]
156
+ def self.scope_type_from_signature(method)
157
+ return 'text' if signature_hidden?(method)
158
+
159
+ parameters = method.parameters
160
+ return { 'list' => 'text' } if parameters.any? { |type, _| type == :rest }
161
+
162
+ required = parameters.count { |type, _| type == :req }
163
+ case required
164
+ when 0 then 'boolean'
165
+ when 1 then 'text'
166
+ else Array.new(required, 'text')
167
+ end
168
+ end
169
+
170
+ # A `scope` lambda is reached through a wrapper taking `(*args, **)`, which
171
+ # says nothing about the arguments the lambda takes. A named `**options` is
172
+ # a real signature.
173
+ #
174
+ # @param method [Method]
175
+ # @return [Boolean]
176
+ def self.signature_hidden?(method)
177
+ method.parameters.any? { |type, name| type == :keyrest && name == :** }
178
+ end
179
+
103
180
  # @param auth_object [Symbol, nil] the Ransack auth object a search ran with
104
181
  # @return [Boolean] whether it names a caller outside the back office
105
182
  def self.restricted_audience?(auth_object)
@@ -0,0 +1,29 @@
1
+ module Spree
2
+ # The status of money a provider moves for a payment: a capture event or a
3
+ # refund. A gateway that answers at once writes `completed`; one that answers
4
+ # `requested?` leaves the row `requested` until its webhook completes or
5
+ # fails it.
6
+ #
7
+ # Rows written before the column existed have no status until the
8
+ # backfill_settlement_statuses upgrade step runs, and read as completed
9
+ # until then, so no sum moves.
10
+ module SettlementStatus
11
+ extend ActiveSupport::Concern
12
+
13
+ included do
14
+ include Spree::HasStatus
15
+
16
+ has_status :requested, :completed, :failed, default: :completed
17
+
18
+ # Money that moved: completed rows and rows not yet backfilled.
19
+ scope :completed_or_unset, -> { where(status: [nil, 'completed']) }
20
+ # Money that moved or may still move, which a balance check reserves.
21
+ scope :not_failed, -> { where(status: nil).or(where.not(status: 'failed')) }
22
+ end
23
+
24
+ # @return [String]
25
+ def status
26
+ super.presence || 'completed'
27
+ end
28
+ end
29
+ end
@@ -11,7 +11,6 @@ module Spree
11
11
  validates_with Spree::LocaleCodesValidator, attributes: %i[default_locale supported_locales]
12
12
 
13
13
  after_create :ensure_default_market
14
- after_update :sync_default_market_settings
15
14
  end
16
15
 
17
16
  # Returns the default country, derived from the default market
@@ -159,35 +158,6 @@ module Spree
159
158
  end
160
159
  end
161
160
 
162
- # Store-level locale/currency edits keep steering the storefront: the
163
- # legacy columns stay writable and propagate onto the default market
164
- # (which is what readers delegate to).
165
- # Diffs against the market rather than dirty-tracking — long-lived store
166
- # instances (spec globals, app singletons) can carry stale change state.
167
- def sync_default_market_settings
168
- association(:default_market).reset
169
- market = default_market
170
- return if market.blank?
171
-
172
- updates = {}
173
- new_locale = read_attribute(:default_locale)
174
- new_currency = read_attribute(:default_currency)
175
- updates[:default_locale] = new_locale if new_locale.present? && market.default_locale != new_locale
176
- updates[:currency] = new_currency if new_currency.present? && market.currency != new_currency
177
- return if updates.empty?
178
-
179
- market.update_columns(updates.merge(updated_at: Time.current))
180
- association(:default_market).reset
181
- clear_market_derived_memoization
182
- end
183
-
184
- def clear_market_derived_memoization
185
- @supported_currencies_list = nil
186
- @supported_locales_list = nil
187
- @supported_locales = nil
188
- @has_markets = nil
189
- end
190
-
191
161
  def legacy_supported_currencies_list
192
162
  ([default_currency] + read_attribute(:supported_currencies).to_s.split(',')).uniq.map(&:to_s).map do |code|
193
163
  ::Money::Currency.find(code.strip)
@@ -285,9 +285,9 @@ class Spree::Base < ApplicationRecord
285
285
  # request the merchant is entitled to make. Asking for every side is no
286
286
  # constraint at all, which is the `nil` below.
287
287
  #
288
- # The scope must also be listed in the model's
289
- # `ransackable_scopes_skip_sanitize_args`, or Ransack casts `false` itself
290
- # and then declines to apply the scope at all.
288
+ # The scope must also be added to the model's
289
+ # `ransackable_scopes_skip_sanitize_args` (`super | %w[name]`), or Ransack
290
+ # casts `false` itself and then declines to apply the scope at all.
291
291
  #
292
292
  # @param values [Array<Object>] whatever Ransack passed through
293
293
  # @return [Boolean, nil] the side asked for, or nil when every side was
@@ -292,7 +292,7 @@ module Spree
292
292
  end
293
293
 
294
294
  def set_permalink
295
- self.permalink = generate_slug
295
+ self.permalink = persisted? && !will_save_change_to_permalink? ? unique_permalink(generate_slug) : generate_slug
296
296
  end
297
297
 
298
298
  def set_pretty_name
@@ -307,39 +307,45 @@ module Spree
307
307
  pretty_name.blank? ? translated_model[:pretty_name] : pretty_name
308
308
  end
309
309
 
310
+ # Ordered parent-first, so each child builds its path from its parent's
311
+ # already regenerated permalink and pretty name.
310
312
  def regenerate_pretty_name_and_permalink
311
- Spree::Category::Translation.where(spree_category_id: translated_model.cached_self_and_descendants_ids).each(&:update_pretty_name_and_permalink)
313
+ category_ids = translated_model.cached_self_and_descendants_ids
314
+ Spree::Category::Translation.where(spree_category_id: category_ids).
315
+ in_order_of(:spree_category_id, category_ids).
316
+ each(&:update_pretty_name_and_permalink)
312
317
  end
313
318
 
314
319
  def update_pretty_name_and_permalink
315
- update_columns(pretty_name: generate_pretty_name, permalink: generate_slug, updated_at: Time.current)
320
+ update_columns(pretty_name: generate_pretty_name, permalink: unique_permalink(generate_slug), updated_at: Time.current)
316
321
  end
317
322
 
318
323
  private
319
324
 
320
325
  def generate_slug
321
- if parent.present?
322
- generate_permalink_including_parent
323
- elsif permalink.blank?
324
- name_with_fallback.to_url
325
- else
326
- permalink.to_url
327
- end
326
+ own_segment = parent.blank? && will_save_change_to_permalink? ? permalink : permalink.to_s.split('/').last
327
+ own_segment = own_segment.blank? ? name_with_fallback.to_url : own_segment.to_url
328
+
329
+ parent.present? ? [parent_permalink_with_fallback, own_segment].join('/') : own_segment
328
330
  end
329
331
 
330
- def generate_pretty_name
331
- if parent.present?
332
- generate_pretty_name_including_parent
333
- elsif pretty_name.blank?
334
- name_with_fallback
335
- else
336
- pretty_name
337
- end
332
+ # A move can land on a path another category in the store already uses
333
+ # in this locale, so suffix it rather than share a permalink. Compared
334
+ # without case, like the category's own permalink.
335
+ def unique_permalink(candidate)
336
+ taken = Spree::Category::Translation.
337
+ joins(:translated_model).
338
+ where(locale: locale).
339
+ where(Spree::Category.table_name => { store_id: translated_model.store_id }).
340
+ where.not(id: id)
341
+ permalink_taken = ->(option) { taken.where(self.class.arel_table[:permalink].lower.eq(option.downcase)).exists? }
342
+ return candidate unless permalink_taken.call(candidate)
343
+
344
+ (2..).lazy.map { |suffix| "#{candidate}-#{suffix}" }.find { |option| !permalink_taken.call(option) }
338
345
  end
339
346
 
340
- def generate_permalink_including_parent
341
- [parent_permalink_with_fallback,
342
- (permalink.blank? ? name_with_fallback.to_url : permalink.split('/').last.to_url)].join('/')
347
+ def generate_pretty_name
348
+ parent.present? ? generate_pretty_name_including_parent : name_with_fallback
343
349
  end
344
350
 
345
351
  def generate_pretty_name_including_parent
@@ -378,27 +384,30 @@ module Spree
378
384
  [parent&.pretty_name, name].compact.join(' -> ')
379
385
  end
380
386
 
387
+ # The permalink is the full path, so only its last segment belongs to this
388
+ # category and the rest comes from the current parent. A permalink typed for
389
+ # a top-level category is kept whole.
381
390
  def generate_slug
382
- if parent.present?
383
- [parent.permalink, (permalink.blank? ? name.to_url : permalink.split('/').last.to_url)].join('/')
384
- elsif permalink.blank?
385
- name.to_url
386
- else
387
- permalink.to_url
388
- end
391
+ # Mobility's dirty tracking hides the change from will_save_change_to_permalink?
392
+ own_segment = parent.blank? && attribute_changed?(:permalink) ? permalink : permalink.to_s.split('/').last
393
+ own_segment = own_segment.blank? ? name.to_url : own_segment.to_url
394
+
395
+ parent.present? ? [parent.permalink, own_segment].join('/') : own_segment
389
396
  end
390
397
 
391
398
  def set_permalink
392
399
  if Spree.use_translations?
393
400
  translations.each(&:set_permalink)
394
401
  else
395
- self.permalink = generate_slug
402
+ # An existing category whose own permalink is not being edited only has
403
+ # its path rebuilt, which can land on one another category holds.
404
+ self.permalink = persisted? && !attribute_changed?(:permalink) ? unique_permalink(generate_slug) : generate_slug
396
405
  end
397
406
  end
398
407
 
399
408
  def regenerate_pretty_name_and_permalink
400
409
  Mobility.with_locale(nil) do
401
- update_columns(pretty_name: generate_pretty_name, permalink: generate_slug, updated_at: Time.current)
410
+ update_columns(pretty_name: generate_pretty_name, permalink: unique_permalink(generate_slug), updated_at: Time.current)
402
411
  end
403
412
 
404
413
  children.reload.each(&:regenerate_pretty_name_and_permalink_as_child)
@@ -406,7 +415,7 @@ module Spree
406
415
 
407
416
  def regenerate_pretty_name_and_permalink_as_child
408
417
  Mobility.with_locale(nil) do
409
- update_columns(pretty_name: generate_pretty_name, permalink: generate_slug, updated_at: Time.current)
418
+ update_columns(pretty_name: generate_pretty_name, permalink: unique_permalink(generate_slug), updated_at: Time.current)
410
419
  end
411
420
 
412
421
  children.reload.each(&:regenerate_pretty_name_and_permalink_as_child)
@@ -434,6 +443,17 @@ module Spree
434
443
  saved_changes.key?(:name) || saved_changes.key?(:permalink)
435
444
  end
436
445
 
446
+ # A move can land on a path another category in the store already holds,
447
+ # which the unique index rejects, so suffix it instead. Compared without
448
+ # case, like the permalink uniqueness validation.
449
+ def unique_permalink(candidate)
450
+ taken = self.class.unscoped.where(store_id: store_id).where.not(id: id)
451
+ permalink_taken = ->(option) { taken.where(self.class.arel_table[:permalink].lower.eq(option.downcase)).exists? }
452
+ return candidate unless permalink_taken.call(candidate)
453
+
454
+ (2..).lazy.map { |suffix| "#{candidate}-#{suffix}" }.find { |option| !permalink_taken.call(option) }
455
+ end
456
+
437
457
  # Refresh the moved subtree's products in the search index (their ancestor
438
458
  # category_ids + per-grouping positions changed). Guarded so DB-provider stores
439
459
  # (no indexing) skip the query entirely; enqueue_search_index self-guards too.
@@ -502,8 +522,9 @@ module Spree
502
522
  self.store = parent&.store || Spree::Store.current
503
523
  end
504
524
 
525
+ # One translation's rebuild already covers every locale of the whole subtree.
505
526
  def regenerate_translations_pretty_name_and_permalink
506
- translations.each(&:regenerate_pretty_name_and_permalink)
527
+ translations.first&.regenerate_pretty_name_and_permalink
507
528
  end
508
529
  end
509
530
  end
@@ -16,7 +16,7 @@ module Spree
16
16
  validates :match_policy, inclusion: { in: MATCH_POLICIES }, presence: true
17
17
 
18
18
  after_commit :regenerate_collection_products,
19
- if: -> { saved_change_to_value? || destroyed? || saved_change_to_match_policy? }
19
+ if: -> { saved_change_to_value? || destroyed? || saved_change_to_match_policy? || saved_change_to_type? }
20
20
 
21
21
  delegate :store, to: :collection
22
22
 
@@ -36,6 +36,10 @@ module Spree
36
36
  end
37
37
 
38
38
  def regenerate_collection_products
39
+ # A rule whose type changed in place is still loaded as its old class.
40
+ # Reload on every rule's commit: with only_once, the first rule to commit
41
+ # regenerates, and that may not be the retyped one.
42
+ collection.rules.reset
39
43
  collection.regenerate_products(only_once: true)
40
44
  end
41
45
  end
@@ -316,8 +316,10 @@ module Spree
316
316
  "#{type.demodulize.underscore}-#{store.code}-#{created_at.strftime('%Y%m%d%H%M%S')}.#{format}"
317
317
  end
318
318
 
319
+ # Unique per run: the file name repeats for every export of a store's type
320
+ # in the same second, and two workers writing one path corrupt each other.
319
321
  def export_tmp_file_path
320
- Rails.root.join('tmp', export_file_name)
322
+ @export_tmp_file_path ||= Rails.root.join('tmp', "#{SecureRandom.hex(8)}-#{export_file_name}")
321
323
  end
322
324
 
323
325
  # Public API name for the +results_url+ preference (read/write symmetry).