spree_core 6.0.1 → 6.0.3

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 (85) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +2 -2
  3. data/app/jobs/spree/addresses/geocode_address_job.rb +6 -3
  4. data/app/jobs/spree/variants/remove_line_item_job.rb +5 -0
  5. data/app/models/concerns/spree/admin_user_methods.rb +23 -0
  6. data/app/models/concerns/spree/preference_schema.rb +5 -0
  7. data/app/models/concerns/spree/typed_associations.rb +53 -20
  8. data/app/models/concerns/spree/user_roles.rb +9 -4
  9. data/app/models/spree/address.rb +2 -2
  10. data/app/models/spree/collection.rb +7 -2
  11. data/app/models/spree/order.rb +4 -2
  12. data/app/models/spree/order_promotion.rb +3 -1
  13. data/app/models/spree/payment.rb +16 -1
  14. data/app/models/spree/payment_method/store_credit.rb +3 -1
  15. data/app/models/spree/payment_method.rb +14 -1
  16. data/app/models/spree/payment_source.rb +3 -1
  17. data/app/models/spree/product.rb +15 -5
  18. data/app/models/spree/promotion/actions/create_item_adjustments.rb +1 -1
  19. data/app/models/spree/promotion.rb +11 -3
  20. data/app/models/spree/promotion_handler/cart.rb +7 -1
  21. data/app/models/spree/promotion_handler/coupon.rb +1 -29
  22. data/app/models/spree/refresh_token.rb +26 -0
  23. data/app/models/spree/variant.rb +1 -1
  24. data/app/services/spree/newsletter/subscribe.rb +1 -1
  25. data/app/services/spree/orders/create_from_cart.rb +6 -2
  26. data/app/services/spree/promotions/detach_from_owner.rb +72 -0
  27. data/app/services/spree/stock_reservations/reserve.rb +6 -2
  28. data/app/tools/spree/agent_tools/create_export.rb +3 -1
  29. data/app/tools/spree/agent_tools/create_import.rb +1 -0
  30. data/app/tools/spree/agent_tools/create_media.rb +2 -1
  31. data/app/tools/spree/agent_tools/create_resource.rb +12 -4
  32. data/app/tools/spree/agent_tools/delete_resource.rb +12 -4
  33. data/app/tools/spree/agent_tools/describe_resource.rb +69 -6
  34. data/app/tools/spree/agent_tools/get_resource.rb +7 -4
  35. data/app/tools/spree/agent_tools/resource_write.rb +15 -2
  36. data/app/tools/spree/agent_tools/search_resources.rb +10 -11
  37. data/app/tools/spree/agent_tools/update_resource.rb +6 -6
  38. data/app/tools/spree/agent_tools/upload_file.rb +1 -0
  39. data/app/workflows/spree/carts/complete.rb +4 -1
  40. data/app/workflows/spree/carts/merge.rb +25 -4
  41. data/app/workflows/spree/carts/recalculate.rb +5 -1
  42. data/app/workflows/spree/orders/complete.rb +39 -14
  43. data/app/workflows/spree/products/activate.rb +7 -2
  44. data/app/workflows/spree/products/archive.rb +7 -2
  45. data/app/workflows/spree/products/draft.rb +7 -2
  46. data/app/workflows/spree/products/status_transition.rb +24 -0
  47. data/config/locales/en.yml +3 -0
  48. data/db/migrate/20260809150001_promote_shipping_categories_to_delivery_profiles.rb +15 -6
  49. data/db/migrate/20261030100001_scope_payment_sources_profile_id_uniqueness_to_payment_method.rb +38 -0
  50. data/db/migrate/20261031000001_add_last_active_at_to_spree_admin_users.rb +7 -0
  51. data/db/migrate/20261031100001_delete_orphaned_spree_option_value_variants.rb +10 -0
  52. data/lib/generators/spree/api_resource/api_resource_generator.rb +35 -3
  53. data/lib/generators/spree/api_resource/templates/admin_controller.rb.tt +9 -4
  54. data/lib/generators/spree/api_resource/templates/admin_integration_spec.rb.tt +74 -0
  55. data/lib/generators/spree/api_resource/templates/store_controller.rb.tt +11 -6
  56. data/lib/generators/spree/dummy/dummy_generator.rb +0 -1
  57. data/lib/generators/spree/dummy/templates/rails/database.yml +6 -9
  58. data/lib/generators/spree/dummy/templates/rails/test.rb +9 -5
  59. data/lib/generators/spree/dummy_model/templates/migration.rb.tt +1 -1
  60. data/lib/spree/agent_tool.rb +105 -1
  61. data/lib/spree/agent_tools/default_catalog.rb +16 -21
  62. data/lib/spree/agent_tools/legacy_tools.rb +212 -0
  63. data/lib/spree/agent_tools/operation_catalog.rb +206 -0
  64. data/lib/spree/agent_tools/operation_tool.rb +189 -0
  65. data/lib/spree/agent_tools/registry.rb +65 -31
  66. data/lib/spree/agent_tools/resource_map.rb +128 -5
  67. data/lib/spree/agent_tools.rb +3 -3
  68. data/lib/spree/core/dependencies_helper.rb +96 -40
  69. data/lib/spree/core/engine.rb +2 -1
  70. data/lib/spree/core/version.rb +1 -1
  71. data/lib/spree/core.rb +19 -5
  72. data/lib/spree/testing_support/common_rake.rb +3 -2
  73. data/lib/spree/testing_support/extension_rake.rb +12 -0
  74. data/lib/spree/testing_support/lifecycle_events.rb +1 -3
  75. data/lib/spree/upgrades/5_6_to_6_0/manifest.yml +36 -1
  76. data/lib/tasks/delivery_migration.rake +17 -1
  77. data/lib/tasks/dependencies.rake +2 -2
  78. data/lib/tasks/remove_orphan_order_promotions.rake +20 -0
  79. metadata +19 -69
  80. data/lib/generators/spree/authentication/dummy/dummy_generator.rb +0 -54
  81. data/lib/generators/spree/authentication/dummy/templates/authentication_helpers.rb.tt +0 -52
  82. data/lib/generators/spree/authentication/dummy/templates/create_spree_admin_users.rb.tt +0 -33
  83. data/lib/spree/agent_tools/workflow_endpoints.rb +0 -88
  84. data/lib/spree/agent_tools/workflow_schema.rb +0 -279
  85. data/lib/spree/agent_tools/workflow_tool.rb +0 -654
@@ -0,0 +1,72 @@
1
+ module Spree
2
+ module Promotions
3
+ # Removes a promotion from a cart or an order the way a shopper removing the
4
+ # code does: the order promotion, held coupon code, discounts and items
5
+ # the promotion added are removed, then totals are recalculated.
6
+ #
7
+ # @example Removing a promotion from a cart
8
+ # Spree::Promotions::DetachFromOwner.call(owner: cart, promotion: promotion)
9
+ class DetachFromOwner
10
+ prepend Spree::ServiceModule::Base
11
+
12
+ # Action types whose line items are removed along with the promotion.
13
+ CREATE_LINE_ITEMS_ACTION_TYPES = %w[Spree::Promotion::Actions::CreateLineItems].freeze
14
+
15
+ # @param owner [Spree::Cart, Spree::Order] the cart or order holding the promotion
16
+ # @param promotion [Spree::Promotion] the promotion to remove
17
+ # @param clear_coupon_code [Boolean] also clear the code the shopper entered on the
18
+ # owner, so recalculating does not apply the promotion again. Leave it off when the
19
+ # shopper should be told the code was lost.
20
+ # @return [Spree::ServiceModule::Result] success, holding the owner; a failure when the
21
+ # owner is already completed, since placed orders are never changed this way
22
+ def call(owner:, promotion:, clear_coupon_code: false)
23
+ return failure(owner, 'Cannot remove a promotion from a completed order') if owner.completed?
24
+
25
+ held_code = promotion.coupon_codes.held_by(owner).first if promotion.multi_codes?
26
+ clear_entered_coupon_code(owner, held_code&.code || promotion.code) if clear_coupon_code
27
+
28
+ # The order promotion has to go before line items are removed
29
+ owner.promotions.delete(promotion)
30
+
31
+ if held_code
32
+ held_code.remove_from_order
33
+ else
34
+ promotion.touch
35
+ end
36
+
37
+ owner.discounts.where(promotion_action_id: promotion.actions.ids).destroy_all
38
+ remove_promotion_line_items(owner, promotion)
39
+ owner.recalculate_totals!
40
+
41
+ success(owner)
42
+ end
43
+
44
+ private
45
+
46
+ # Carts keep the entered code, and recalculation would apply it again.
47
+ # Callers that let the shopper be told the code went keep it.
48
+ def clear_entered_coupon_code(owner, code)
49
+ return if code.blank? || !owner.has_attribute?(:coupon_code)
50
+ return unless owner.read_attribute(:coupon_code).to_s.casecmp?(code)
51
+
52
+ owner.update_column(:coupon_code, nil)
53
+ end
54
+
55
+ # Removes the line items a promotion's create-line-items actions added.
56
+ def remove_promotion_line_items(owner, promotion)
57
+ action_ids = promotion.actions.where(type: CREATE_LINE_ITEMS_ACTION_TYPES).ids
58
+ remove_service = owner.is_a?(Spree::Cart) ? Spree.cart_remove_item_service : Spree.order_remove_item_service
59
+ owner_key = owner.is_a?(Spree::Cart) ? :cart : :order
60
+
61
+ Spree::PromotionActionLineItem.where(promotion_action: action_ids).find_each do |item|
62
+ next if owner.find_line_item_by_variant(item.variant).blank?
63
+
64
+ # The promotion is still active here, so recalculating would add its items back;
65
+ # other promotions are still re-evaluated.
66
+ options = owner.is_a?(Spree::Cart) ? { excluded_promotion_ids: [promotion.id] } : {}
67
+ remove_service.call(owner_key => owner, variant: item.variant, quantity: item.quantity, options: options)
68
+ end
69
+ end
70
+ end
71
+ end
72
+ end
@@ -33,8 +33,12 @@ module Spree
33
33
 
34
34
  this_order_used = Hash.new(0)
35
35
 
36
- reservations = targets.map do |line_item, stock_level, quantity|
37
- stock_level = locked_stock_levels.fetch(stock_level.id)
36
+ reservations = targets.filter_map do |line_item, stock_level, quantity|
37
+ # A shelf deleted since the allocation was read (a variant being
38
+ # discontinued removes its stock) has nothing left to hold.
39
+ stock_level = locked_stock_levels[stock_level.id]
40
+ next if stock_level.nil?
41
+
38
42
  available = stock_level.available_count - held.fetch(stock_level.id, 0) - this_order_used[stock_level.id]
39
43
 
40
44
  raise_insufficient_stock(line_item, available) if available < quantity
@@ -4,7 +4,8 @@ module Spree
4
4
  #
5
5
  # Mutating not because it changes the store — it does not — but because
6
6
  # it produces a file of store data and emails a link to it. That leaves
7
- # the building, so a merchant decides, not the model.
7
+ # the building, so a merchant decides, not the model. Additive, since
8
+ # nothing in the store is overwritten.
8
9
  class CreateExport < Spree::AgentTool
9
10
  tool_name 'create_export'
10
11
  description 'Export records to a CSV file. Say which kind of records and, ' \
@@ -25,6 +26,7 @@ module Spree
25
26
 
26
27
  permission nil
27
28
  mutating!
29
+ additive!
28
30
 
29
31
  param :resource, description: 'What to export: products, orders, customers',
30
32
  required: true
@@ -21,6 +21,7 @@ module Spree
21
21
  # tool from a caller who may import one kind of record but not another.
22
22
  permission nil
23
23
  mutating!
24
+ additive!
24
25
 
25
26
  param :resource, description: 'What the file holds: products, customers, purchase_orders',
26
27
  required: true
@@ -16,6 +16,7 @@ module Spree
16
16
  'the file sits in the library for the merchant to place later.'
17
17
  permission 'write_media'
18
18
  mutating!
19
+ additive!
19
20
 
20
21
  param :file_id, description: 'The file_id upload_file returned', required: true
21
22
  param :product_id, description: "A product's prefixed id, to place the file in its gallery"
@@ -27,7 +28,7 @@ module Spree
27
28
  # endpoint resolves the parent, checks it and verifies the signed id,
28
29
  # so there is nothing to look up here first.
29
30
  path = if product_id.present?
30
- "/api/v3/admin/products/#{product_id}/media"
31
+ "/api/v3/admin/products/#{ERB::Util.url_encode(product_id)}/media"
31
32
  else
32
33
  '/api/v3/admin/media'
33
34
  end
@@ -13,23 +13,31 @@ module Spree
13
13
 
14
14
  param :resource, description: 'Resource key — call describe_resource for the list', required: true
15
15
  param :attributes, type: :object, description: 'Attributes to set on the new record', required: true
16
+ param :parent_id, description: PARENT_ID_DESCRIPTION
16
17
 
17
- def call(resource:, attributes: {})
18
+ def call(resource:, attributes: {}, parent_id: nil)
18
19
  entry, refusal = writable_entry(resource, :create)
19
20
  return refusal if refusal
20
21
 
21
22
  body, rejection = body_for(entry, attributes)
22
23
  return rejection if rejection
23
24
 
24
- response = dispatch.call(method: :post, path: entry.api_path(:create), body: body)
25
+ path, missing = write_path(entry, :create, parent_id: parent_id)
26
+ return missing if missing
25
27
 
26
- result_for(response, entry, summary: summary(resource: resource, attributes: attributes))
28
+ response = dispatch.call(method: :post, path: path, body: body)
29
+
30
+ result_for(response, entry, summary: summary(resource: resource, attributes: attributes, parent_id: parent_id))
27
31
  end
28
32
 
29
33
  def summary(arguments)
30
34
  named = arguments[:attributes].to_h.values_at('name', :name, 'number', :number).compact.first
31
35
 
32
- "Create #{arguments[:resource].to_s.singularize.tr('_', ' ')} #{named}".strip
36
+ line = "Create #{arguments[:resource].to_s.singularize.tr('_', ' ')} #{named}".strip
37
+
38
+ # A top-level resource ignores parent_id, so the approval card does too.
39
+ nested = arguments[:parent_id].present? && ResourceMap.find(arguments[:resource])&.parent_param(:create)
40
+ nested ? "#{line} under #{arguments[:parent_id]}" : line
33
41
  end
34
42
  end
35
43
  end
@@ -9,19 +9,27 @@ module Spree
9
9
 
10
10
  param :resource, description: 'Resource key — call describe_resource for the list', required: true
11
11
  param :id, description: 'The record id as shown in search results', required: true
12
+ param :parent_id, description: PARENT_ID_DESCRIPTION
12
13
 
13
- def call(resource:, id:)
14
+ def call(resource:, id:, parent_id: nil)
14
15
  entry, refusal = writable_entry(resource, :destroy)
15
16
  return refusal if refusal
16
17
 
17
- response = dispatch.call(method: :delete, path: entry.api_path(:destroy).sub(':id', id.to_s))
18
+ path, missing = write_path(entry, :destroy, id: id, parent_id: parent_id)
19
+ return missing if missing
20
+
21
+ response = dispatch.call(method: :delete, path: path)
18
22
  return { error: response.error_message } unless response.success?
19
23
 
20
- { summary: summary(resource: resource, id: id) }
24
+ { summary: summary(resource: resource, id: id, parent_id: parent_id) }
21
25
  end
22
26
 
23
27
  def summary(arguments)
24
- "Delete #{arguments[:resource].to_s.singularize.tr('_', ' ')} #{arguments[:id]}"
28
+ line = "Delete #{arguments[:resource].to_s.singularize.tr('_', ' ')} #{arguments[:id]}"
29
+ # The approval card is all a merchant sees, so a nested delete names
30
+ # the record it runs under, as a nested create does.
31
+ nested = arguments[:parent_id].present? && ResourceMap.find(arguments[:resource])&.parent_param(:destroy)
32
+ nested ? "#{line} under #{arguments[:parent_id]}" : line
25
33
  end
26
34
  end
27
35
  end
@@ -5,9 +5,11 @@ module Spree
5
5
  # producing errors the merchant has to read.
6
6
  class DescribeResource < Spree::AgentTool
7
7
  tool_name 'describe_resource'
8
- description 'List the store resources you can search, and the fields each one ' \
9
- 'can be filtered and sorted by. Call this before search_resources ' \
10
- 'if you are unsure which filter to use.'
8
+ description 'List the store resources you can search, the fields each one can be ' \
9
+ 'filtered and sorted by, and what a write accepts. Describe one resource ' \
10
+ 'for the full detail: what fits inside each list-valued attribute, and the ' \
11
+ 'kinds a `type` field takes with each kind\'s preferences schema. Call this ' \
12
+ 'before search_resources, create_resource or update_resource if unsure.'
11
13
  # Deliberately ungated: it exposes only field names, and the resources it
12
14
  # lists are already filtered to what this admin may read.
13
15
  permission nil
@@ -25,11 +27,47 @@ module Spree
25
27
  available: Spree::AgentTools::ResourceMap.available_for(context).map(&:key) }
26
28
  end
27
29
 
28
- { resources: entries.map { |entry| describe(entry) } }
30
+ # One resource gets every type's schema; the listing names the types
31
+ # only, because every family's schema at once is more than an index
32
+ # should cost a model's context.
33
+ { resources: entries.map { |entry| describe(entry, detailed: resource.present?) } }
29
34
  end
30
35
 
31
36
  private
32
37
 
38
+ # The kinds a `type` takes, from the family's own registry — the same
39
+ # list its `…/types` endpoint serves. An agent that never saw this list
40
+ # guessed Ruby class names, and the write dropped every row.
41
+ def types_for(family, detailed)
42
+ return if family.nil?
43
+
44
+ return family.api_types.sort unless detailed
45
+
46
+ family.subclasses_with_preference_schema.map do |kind|
47
+ kind.slice(:type, :label, :description, :schema).merge(calculators: calculators_for(family, kind[:type])).compact
48
+ end
49
+ rescue StandardError
50
+ nil
51
+ end
52
+
53
+ # An action that prices its discount through a calculator takes one of
54
+ # these, each with its own preferences — the same list as
55
+ # `GET /promotion_actions/calculators`.
56
+ def calculators_for(family, type)
57
+ klass = family.find_by_api_type(type)
58
+ return unless klass.respond_to?(:calculators)
59
+
60
+ klass.calculators.map do |calculator|
61
+ { type: calculator.api_type, label: calculator.description, schema: calculator.preference_json_schema }
62
+ end.sort_by { |entry| entry[:label].to_s }.presence
63
+ end
64
+
65
+ def nested_types_for(entry, detailed)
66
+ return if writable_attributes_for(entry).blank?
67
+
68
+ entry.nested_typed_families.transform_values { |family| types_for(family, detailed) }.compact.presence
69
+ end
70
+
33
71
  # Every dispatchable resource reports its attributes now: the generic
34
72
  # writes reach the controller, which runs whatever workflow it
35
73
  # declares, so there is no longer a class of resource they refuse.
@@ -46,19 +84,43 @@ module Spree
46
84
  entry.writable_attribute_names.presence
47
85
  end
48
86
 
49
- def describe(entry)
87
+ # The action tools this caller is offered, by resource, worked out once
88
+ # per call rather than once per resource described.
89
+ def actions_for(entry)
90
+ @actions ||= Spree.admin_agent_tools.to_a.grep(->(klass) { klass < Spree::AgentTools::OperationTool }).
91
+ select { |klass| context.permitted?(klass.permission) }.
92
+ group_by { |klass| klass.operation.resource_key }.
93
+ transform_values { |classes| classes.map(&:tool_name).sort }
94
+ @actions[entry.key]
95
+ end
96
+
97
+ def describe(entry, detailed:)
50
98
  {
51
99
  resource: entry.key,
100
+ # A resource reached through another record — an order's items, a
101
+ # product's variants when written — needs that record's id as
102
+ # parent_id on the calls whose route runs under it.
103
+ parent: %i[index create update].lazy.filter_map { |action| entry.parent_key(action) }.first,
52
104
  filterable_fields: entry.filterable_fields,
53
105
  # What a generic write accepts, so the model learns the schema here
54
106
  # rather than by sending an invalid write and reading the refusal —
55
107
  # which is what create_resource and update_resource tell it to do.
56
108
  # Offered only where the caller could actually write.
57
109
  writable_attributes: writable_attributes_for(entry),
110
+ # The action tools that act on this resource — cancel, approve,
111
+ # capture — so a model that found an order learns what it can do
112
+ # to one without scanning the whole tool list.
113
+ actions: actions_for(entry),
58
114
  # What goes inside a list-valued attribute. Without it a model sees
59
115
  # `variants` and has no idea a whole variant fits there, so it
60
116
  # creates the product and then adds each variant separately.
61
117
  nested_attributes: nested_shapes_for(entry),
118
+ # The kinds this resource's own `type` takes (a payment method's
119
+ # provider), and the kinds each nested row's `type` takes (a
120
+ # promotion's rules and actions). The accepted values and their
121
+ # preference schemas, so a model does not guess class names.
122
+ types: types_for(entry.typed_family, detailed),
123
+ nested_types: nested_types_for(entry, detailed),
62
124
  # What get_resource can be asked to include. A record arrives
63
125
  # without its associations, so a model that does not know these
64
126
  # names cannot ask for the one it needs.
@@ -73,7 +135,8 @@ module Spree
73
135
  filterable_scopes: entry.filterable_scopes,
74
136
  usage: 'Attribute filters use Ransack predicates, e.g. name_cont, created_at_gteq, ' \
75
137
  'status_eq. Named scopes are passed as a bare key set to true, e.g. ' \
76
- '{"out_of_stock": true}.'
138
+ '{"out_of_stock": true}. A type field takes one of the kinds under types or ' \
139
+ 'nested_types, and a row\'s preferences follow that kind\'s schema.'
77
140
  }.compact
78
141
  end
79
142
  end
@@ -14,20 +14,23 @@ module Spree
14
14
  param :id, description: 'The record id as shown in search results', required: true
15
15
  param :expand, type: :array, items: :string,
16
16
  description: "Associations to include, e.g. [\"variants\"] on a product"
17
+ param :parent_id, description: PARENT_ID_DESCRIPTION
17
18
 
18
- def call(resource:, id:, expand: nil)
19
+ def call(resource:, id:, expand: nil, parent_id: nil)
19
20
  entry = ResourceMap.find(resource)
20
21
  return unknown_resource(resource) if entry.nil?
21
22
  return { error: "You do not have permission to read #{entry.key}." } unless
22
23
  context.permitted?(entry.permission)
23
24
 
24
- path = entry.api_path(:show)
25
- return { error: "#{entry.key} cannot be fetched one at a time." } if path.blank? || path.include?('/:') && path.count(':') > 1
25
+ return { error: "#{entry.key} cannot be fetched one at a time." } if entry.api_path(:show).blank?
26
+
27
+ path = entry.path_for(:show, id: id, parent_id: parent_id)
28
+ return nested_resource_error(entry, 'fetched', :show) if path.nil?
26
29
 
27
30
  requested, refusal = expansions(entry, expand)
28
31
  return refusal if refusal
29
32
 
30
- response = dispatch.call(method: :get, path: path.sub(':id', id.to_s),
33
+ response = dispatch.call(method: :get, path: path,
31
34
  params: requested.any? ? { expand: requested.join(',') } : {})
32
35
  return { error: not_found(entry, id, response) } unless response.success?
33
36
 
@@ -77,6 +77,17 @@ module Spree
77
77
  accepted_attributes: accepted }]
78
78
  end
79
79
 
80
+ # The path for this write, or the refusal saying which record a nested
81
+ # resource needs.
82
+ #
83
+ # @return [Array(String, nil), Array(nil, Hash)]
84
+ def write_path(entry, action, id: nil, parent_id: nil)
85
+ path = entry.path_for(action, id: id, parent_id: parent_id)
86
+ return [path, nil] if path
87
+
88
+ [nil, nested_resource_error(entry, verb_for(action), action)]
89
+ end
90
+
80
91
  def result_for(response, entry, summary:)
81
92
  return { error: response.error_message } unless response.success?
82
93
 
@@ -90,9 +101,11 @@ module Spree
90
101
  end
91
102
 
92
103
  def not_writable(entry, action)
93
- verb = { create: 'created', update: 'updated', destroy: 'deleted' }.fetch(action, 'changed')
104
+ "#{entry.key} cannot be #{verb_for(action)} this way — call describe_resource to see what can."
105
+ end
94
106
 
95
- "#{entry.key} cannot be #{verb} this way — call describe_resource to see what can."
107
+ def verb_for(action)
108
+ { create: 'created', update: 'updated', destroy: 'deleted' }.fetch(action, 'changed')
96
109
  end
97
110
  end
98
111
  end
@@ -26,11 +26,12 @@ module Spree
26
26
  param :filters, type: :object, description: 'Ransack filter hash, e.g. {"name_cont": "shirt"}'
27
27
  param :sort, description: 'Sort, e.g. "created_at desc"'
28
28
  param :limit, type: :integer, description: "Max records to return (default #{DEFAULT_LIMIT})"
29
+ param :parent_id, description: PARENT_ID_DESCRIPTION
29
30
 
30
- def call(resource:, filters: nil, sort: nil, limit: nil)
31
+ def call(resource:, filters: nil, sort: nil, limit: nil, parent_id: nil)
31
32
  entry = ResourceMap.find(resource)
32
33
  return unknown_resource(resource) if entry.nil?
33
- return not_searchable(entry) unless entry.dispatchable?
34
+ return not_searchable(entry) if entry.api_path(:index).blank?
34
35
  return forbidden(entry) unless context.permitted?(entry.permission)
35
36
 
36
37
  applied = sanitize_filters(filters)
@@ -42,11 +43,10 @@ module Spree
42
43
  unrecognised = unrecognised_filters(entry, applied)
43
44
  return invalid_filters(entry, unrecognised) if unrecognised.any?
44
45
 
45
- response = dispatch.call(
46
- method: :get,
47
- path: entry.api_path(:index),
48
- params: query_for(applied, sort, limit)
49
- )
46
+ path = entry.path_for(:index, parent_id: parent_id)
47
+ return not_searchable(entry) if path.nil?
48
+
49
+ response = dispatch.call(method: :get, path: path, params: query_for(applied, sort, limit))
50
50
  return { error: response.error_message } unless response.success?
51
51
 
52
52
  rows = Array(response.data)
@@ -145,10 +145,9 @@ module Spree
145
145
  # resolves its scope per request. Named rather than guessed at, because
146
146
  # a tool cannot invent the parent id such a path needs.
147
147
  def not_searchable(entry)
148
- {
149
- error: "#{entry.key} cannot be searched on its own.",
150
- available: ResourceMap.available_for(context).select(&:dispatchable?).map(&:key).sort
151
- }
148
+ refusal = entry.nested?(:index) ? nested_resource_error(entry, 'searched', :index) : { error: "#{entry.key} cannot be searched on its own." }
149
+
150
+ refusal.merge(available: ResourceMap.available_for(context).select(&:dispatchable?).map(&:key).sort)
152
151
  end
153
152
  end
154
153
  end
@@ -14,19 +14,19 @@ module Spree
14
14
  param :resource, description: 'Resource key — call describe_resource for the list', required: true
15
15
  param :id, description: 'The record id as shown in search results', required: true
16
16
  param :attributes, type: :object, description: 'Attributes to change', required: true
17
+ param :parent_id, description: PARENT_ID_DESCRIPTION
17
18
 
18
- def call(resource:, id:, attributes: {})
19
+ def call(resource:, id:, attributes: {}, parent_id: nil)
19
20
  entry, refusal = writable_entry(resource, :update)
20
21
  return refusal if refusal
21
22
 
22
23
  body, rejection = body_for(entry, attributes)
23
24
  return rejection if rejection
24
25
 
25
- response = dispatch.call(
26
- method: :patch,
27
- path: entry.api_path(:update).sub(':id', id.to_s),
28
- body: body
29
- )
26
+ path, missing = write_path(entry, :update, id: id, parent_id: parent_id)
27
+ return missing if missing
28
+
29
+ response = dispatch.call(method: :patch, path: path, body: body)
30
30
 
31
31
  result_for(response, entry, summary: summary(resource: resource, id: id, attributes: attributes))
32
32
  end
@@ -21,6 +21,7 @@ module Spree
21
21
  # passes; whatever uses the file checks its own permission after.
22
22
  permission 'write_products'
23
23
  mutating!
24
+ additive!
24
25
 
25
26
  param :filename, description: 'The file name, with its extension', required: true
26
27
  param :content, description: 'The file contents — text as text, binary base64 encoded',
@@ -292,6 +292,7 @@ module Spree
292
292
  copy_tax_exemptions!(cart, order, line_item_map, fulfillment_map, fee_map)
293
293
  copy_po_document!(cart, order)
294
294
  repoint_money_records!(cart, order)
295
+ Spree.cart_copiers.each { |copier| copier.call(cart: cart, order: order, line_item_map: line_item_map) }
295
296
 
296
297
  order.update_columns(
297
298
  item_total: cart.item_total,
@@ -560,7 +561,9 @@ module Spree
560
561
  # its children is the order this checkout carries on with. No child holds
561
562
  # the confirmation: the customer is confirmed from the group.
562
563
  def complete_orders
563
- result = Spree.order_complete_workflow.call(order: order, payment_pending: payment_pending)
564
+ # carts.complete.validate ran before the payment was taken; a veto now
565
+ # would leave the customer charged for an order that never places.
566
+ result = Spree.order_complete_workflow.call(order: order, payment_pending: payment_pending, validated: true)
564
567
  failure(cart, code: 'completion_failed', message: result.error) if result.failure?
565
568
 
566
569
  return unless result.value.is_a?(Spree::OrderGroup)
@@ -10,7 +10,14 @@ module Spree
10
10
  # cap the merged quantity) and previously required replacing the whole
11
11
  # strategy class.
12
12
  class Merge < Spree::Workflow
13
- hooks :validate, :after_merge
13
+ hooks :validate, :after_items_moved, :after_merge
14
+
15
+ # Every line item of the folded-in cart → the line item now holding its
16
+ # quantity: itself when it moved across, or the surviving cart's line it
17
+ # was added to. Set before +after_items_moved+ runs.
18
+ #
19
+ # @return [Hash{Spree::LineItem => Spree::LineItem}]
20
+ attr_reader :line_item_map
14
21
 
15
22
  # @param cart [Spree::Cart] the surviving cart
16
23
  # @param other_cart [Spree::Cart, nil] the cart folded in and destroyed
@@ -28,6 +35,10 @@ module Spree
28
35
 
29
36
  ApplicationRecord.transaction do
30
37
  step :move_line_items
38
+ # Inside the transaction and before the absorbed lines are deleted,
39
+ # so an extension can move what it keeps against them.
40
+ run_hooks :after_items_moved
41
+ step :destroy_absorbed_line_items
31
42
  step :associate_customer
32
43
  step :destroy_drained_cart
33
44
  end
@@ -46,19 +57,29 @@ module Spree
46
57
  end
47
58
 
48
59
  # A matching item absorbs the quantity; everything else is re-pointed
49
- # at the surviving cart.
60
+ # at the surviving cart. Absorbed items are deleted only after the
61
+ # +after_items_moved+ hook.
50
62
  def move_line_items
51
- other_cart.line_items.reload.each do |other_line_item|
63
+ @line_item_map = other_cart.line_items.reload.to_a.index_with do |other_line_item|
52
64
  existing = matching_line_item(other_line_item)
53
65
 
54
66
  if existing
55
67
  existing.quantity += other_line_item.quantity
56
68
  existing.save!
57
- other_line_item.destroy!
69
+ existing
58
70
  else
59
71
  other_line_item.update!(cart: cart, order: nil)
72
+ other_line_item
60
73
  end
61
74
  end
75
+ # Matching loaded the surviving cart's items before any moved in.
76
+ cart.line_items.reset
77
+ end
78
+
79
+ def destroy_absorbed_line_items
80
+ line_item_map.each do |other_line_item, line_item|
81
+ other_line_item.destroy! unless other_line_item == line_item
82
+ end
62
83
  end
63
84
 
64
85
  # Options-aware comparison (personalization, gift wrapping) with a
@@ -9,6 +9,8 @@ module Spree
9
9
 
10
10
  # @param cart [Spree::Cart, Spree::Order] draft orders ride the same pipeline
11
11
  # @param line_item [Spree::LineItem, nil] the item whose change triggered this
12
+ # @param options [Hash] +excluded_promotion_ids:+ lists promotions to leave out of activation,
13
+ # for callers that are removing a promotion's effects
12
14
  def perform(cart: nil, order: nil, line_item: nil, line_item_created: false, options: {})
13
15
  if order
14
16
  Spree::Deprecation.warn('Calling Spree::Carts::Recalculate with order: is deprecated and will be removed in Spree 6.1. Pass cart: instead.')
@@ -47,7 +49,9 @@ module Spree
47
49
  def activate_promotions
48
50
  @promotion_context = run_hooks :set_promotion_context
49
51
 
50
- ::Spree::PromotionHandler::Cart.new(cart, line_item).activate
52
+ ::Spree::PromotionHandler::Cart.new(
53
+ cart, line_item, excluded_promotion_ids: options[:excluded_promotion_ids] || []
54
+ ).activate
51
55
  end
52
56
  end
53
57
  end
@@ -7,6 +7,8 @@ module Spree
7
7
  # may still need to process payments). Idempotent: an already-placed
8
8
  # order halts successfully, so interrupted completions replay safely.
9
9
  class Complete < Spree::Workflow
10
+ hooks :validate
11
+
10
12
  # Set only when the order divided between sellers.
11
13
  attr_reader :order_group
12
14
 
@@ -18,9 +20,13 @@ module Spree
18
20
  # rollup work's call (docs/plans/6.0-b2b-wholesale-shipping.md phase 7)
19
21
  # @param notify_customer [Boolean, nil] admin drafts pass false to
20
22
  # complete silently; nil (checkout) leaves customer notification on
23
+ # @param validated [Boolean] the caller already ran its own veto, so the
24
+ # validate hook is skipped: checkout's finalize, whose
25
+ # carts.complete.validate ran before the payment was taken, and the
26
+ # orders a seller division places beside the one it came from
21
27
  # @return [Spree::ServiceModule::Result] value is the order, or the
22
28
  # Spree::OrderGroup when it divided between sellers
23
- def perform(order:, payment_pending: false, notify_customer: nil)
29
+ def perform(order:, payment_pending: false, notify_customer: nil, validated: false)
24
30
  super
25
31
 
26
32
  order.notify_customer = notify_customer unless notify_customer.nil?
@@ -37,20 +43,30 @@ module Spree
37
43
 
38
44
  step :ensure_not_canceled
39
45
 
40
- order.with_lock do
41
- unless order.reload.placed?
42
- step :process_payments unless payment_pending || !order.payment_required?
43
- step :split_by_seller
44
- step :finalize_fulfillments
45
- step :place_order
46
- step :freeze_tax_exemptions
47
- step :use_coupon_codes
48
- step :redeem_gift_card
49
- step :fulfill_auto_fulfillments
50
- step :ensure_digital_links
51
- end
46
+ placed_here = order.with_lock do
47
+ # A completion running alongside this one placed it while this one
48
+ # waited for the lock. Placed, not merely in that status: it may
49
+ # have been canceled since.
50
+ next false if order.reload.completed?
51
+
52
+ step :validate_order unless validated
53
+ step :process_payments unless payment_pending || !order.payment_required?
54
+ step :split_by_seller
55
+ step :finalize_fulfillments
56
+ step :place_order
57
+ step :freeze_tax_exemptions
58
+ step :use_coupon_codes
59
+ step :redeem_gift_card
60
+ step :fulfill_auto_fulfillments
61
+ step :ensure_digital_links
62
+ true
52
63
  end
53
64
 
65
+ # The run that placed it announces it and finishes what follows; this
66
+ # one answers as a replay would, so nothing after placement happens
67
+ # twice.
68
+ halt!(order.order_group || order) unless placed_here
69
+
54
70
  step :ensure_placed_status
55
71
  step :release_stock_reservations
56
72
  step :cancel_unused_payment_sessions
@@ -67,6 +83,14 @@ module Spree
67
83
  failure(order, 'Order is canceled') if order.canceled?
68
84
  end
69
85
 
86
+ # The extension veto, under the order's row lock: a handler sees the
87
+ # order as it is placed, and anything else that takes the lock to change
88
+ # it waits for the outcome. Rejecting rolls the lock back before any
89
+ # payment is processed.
90
+ def validate_order
91
+ run_hooks :validate
92
+ end
93
+
70
94
  def process_payments
71
95
  order.process_payments! unless payment_covered?
72
96
 
@@ -276,7 +300,8 @@ module Spree
276
300
  end
277
301
 
278
302
  def place_sibling(sibling)
279
- result = Spree.order_complete_workflow.call(order: sibling, payment_pending: true, notify_customer: false)
303
+ result = Spree.order_complete_workflow.call(order: sibling, payment_pending: true, notify_customer: false,
304
+ validated: true)
280
305
  failure(order, result.error) if result.failure?
281
306
  end
282
307