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
@@ -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,46 @@ 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,
104
+ # The records a search can list this resource under with parent_id
105
+ # — products under a category, collection or catalog.
106
+ listed_under: entry.index_parents.keys.sort.presence,
52
107
  filterable_fields: entry.filterable_fields,
53
108
  # What a generic write accepts, so the model learns the schema here
54
109
  # rather than by sending an invalid write and reading the refusal —
55
110
  # which is what create_resource and update_resource tell it to do.
56
111
  # Offered only where the caller could actually write.
57
112
  writable_attributes: writable_attributes_for(entry),
113
+ # The action tools that act on this resource — cancel, approve,
114
+ # capture — so a model that found an order learns what it can do
115
+ # to one without scanning the whole tool list.
116
+ actions: actions_for(entry),
58
117
  # What goes inside a list-valued attribute. Without it a model sees
59
118
  # `variants` and has no idea a whole variant fits there, so it
60
119
  # creates the product and then adds each variant separately.
61
120
  nested_attributes: nested_shapes_for(entry),
121
+ # The kinds this resource's own `type` takes (a payment method's
122
+ # provider), and the kinds each nested row's `type` takes (a
123
+ # promotion's rules and actions). The accepted values and their
124
+ # preference schemas, so a model does not guess class names.
125
+ types: types_for(entry.typed_family, detailed),
126
+ nested_types: nested_types_for(entry, detailed),
62
127
  # What get_resource can be asked to include. A record arrives
63
128
  # without its associations, so a model that does not know these
64
129
  # names cannot ask for the one it needs.
@@ -73,7 +138,8 @@ module Spree
73
138
  filterable_scopes: entry.filterable_scopes,
74
139
  usage: 'Attribute filters use Ransack predicates, e.g. name_cont, created_at_gteq, ' \
75
140
  'status_eq. Named scopes are passed as a bare key set to true, e.g. ' \
76
- '{"out_of_stock": true}.'
141
+ '{"out_of_stock": true}. A type field takes one of the kinds under types or ' \
142
+ 'nested_types, and a row\'s preferences follow that kind\'s schema.'
77
143
  }.compact
78
144
  end
79
145
  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
- context.permitted?(entry.permission)
23
+ entry.readable_by?(context)
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
 
@@ -46,7 +46,7 @@ module Spree
46
46
  # own words. This check only avoids offering a tool that cannot work
47
47
  # — a resource the caller cannot even read.
48
48
  return [nil, { error: "You do not have permission to change #{entry.key}." }] unless
49
- context.permitted?(entry.permission)
49
+ entry.readable_by?(context)
50
50
 
51
51
  [entry, nil]
52
52
  end
@@ -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
@@ -9,7 +9,8 @@ module Spree
9
9
  # reported it as a fact.
10
10
  class SearchResources < Spree::AgentTool
11
11
  DEFAULT_LIMIT = 10
12
- MAX_LIMIT = 25
12
+ # The Admin API's own page ceiling; asking for more returns this many.
13
+ MAX_LIMIT = 100
13
14
 
14
15
  tool_name 'search_resources'
15
16
  description 'Search the store. Filters are Ransack predicates ' \
@@ -24,14 +25,18 @@ module Spree
24
25
 
25
26
  param :resource, description: 'Resource key — call describe_resource for the list', required: true
26
27
  param :filters, type: :object, description: 'Ransack filter hash, e.g. {"name_cont": "shirt"}'
27
- param :sort, description: 'Sort, e.g. "created_at desc"'
28
- param :limit, type: :integer, description: "Max records to return (default #{DEFAULT_LIMIT})"
29
-
30
- def call(resource:, filters: nil, sort: nil, limit: nil)
28
+ param :sort, description: 'Sort field, prefixed with - for descending, e.g. "-created_at" for newest first'
29
+ param :limit, type: :integer,
30
+ description: "Records per page (default #{DEFAULT_LIMIT}, at most #{MAX_LIMIT}). " \
31
+ 'When total exceeds count, pass next_page as page to fetch the rest.'
32
+ param :page, type: :integer, description: 'Page number, starting at 1 (default 1)'
33
+ param :parent_id, description: PARENT_ID_DESCRIPTION
34
+
35
+ def call(resource:, filters: nil, sort: nil, limit: nil, page: nil, parent_id: nil)
31
36
  entry = ResourceMap.find(resource)
32
37
  return unknown_resource(resource) if entry.nil?
33
- return not_searchable(entry) unless entry.dispatchable?
34
- return forbidden(entry) unless context.permitted?(entry.permission)
38
+ return not_searchable(entry) if entry.api_path(:index).blank?
39
+ return forbidden(entry) unless entry.readable_by?(context)
35
40
 
36
41
  applied = sanitize_filters(filters)
37
42
  # Ransack drops a filter it does not recognise and returns the whole
@@ -42,11 +47,11 @@ module Spree
42
47
  unrecognised = unrecognised_filters(entry, applied)
43
48
  return invalid_filters(entry, unrecognised) if unrecognised.any?
44
49
 
45
- response = dispatch.call(
46
- method: :get,
47
- path: entry.api_path(:index),
48
- params: query_for(applied, sort, limit)
49
- )
50
+ path = entry.path_for(:index, parent_id: parent_id)
51
+ return wrong_parent(entry, parent_id) if path.nil? && parent_id.present? && !entry.nested?(:index)
52
+ return not_searchable(entry) if path.nil?
53
+
54
+ response = dispatch.call(method: :get, path: path, params: query_for(applied, sort, limit, page))
50
55
  return { error: response.error_message } unless response.success?
51
56
 
52
57
  rows = Array(response.data)
@@ -59,8 +64,13 @@ module Spree
59
64
  # for a store holding hundreds.
60
65
  total: meta['count'] || rows.size,
61
66
  count: rows.size,
67
+ page: meta['page'],
68
+ pages: meta['pages'],
69
+ # Named outright, because a model told only "25 of 88" reports the
70
+ # 25 as the answer.
71
+ next_page: meta['next'],
62
72
  records: rows.map { |row| RecordSummary.from_payload(entry: entry, payload: row) }
63
- }
73
+ }.compact
64
74
  end
65
75
 
66
76
  def summary(arguments)
@@ -81,13 +91,24 @@ module Spree
81
91
  # Ransack filters travel under `q`, the way every other client sends
82
92
  # them — so an unknown one is refused by the API's own filter
83
93
  # validation rather than silently widening the search here.
84
- def query_for(filters, sort, limit)
85
- params = { limit: capped_limit(limit) }
94
+ def query_for(filters, sort, limit, page)
95
+ params = { limit: capped_limit(limit), page: [page.to_i, 1].max }
86
96
  params[:q] = filters if filters.any?
87
- params[:sort] = sort if sort.present?
97
+ params[:sort] = api_sort(sort) if sort.present?
88
98
  params
89
99
  end
90
100
 
101
+ # The API reads `-field` for descending. Models also write Ransack's
102
+ # `field desc`, which reached the API as `field desc asc` and sorted
103
+ # ascending, so a request for the newest records paged through the
104
+ # oldest.
105
+ def api_sort(sort)
106
+ sort.to_s.split(',').map do |part|
107
+ field, direction = part.strip.split(/\s+/, 2)
108
+ direction.to_s.casecmp?('desc') ? "-#{field.delete_prefix('-')}" : field
109
+ end.join(',')
110
+ end
111
+
91
112
  # Empty values match everything, so they are dropped — but `false` is a
92
113
  # real filter value (`{"out_of_stock": false}`), which `compact_blank`
93
114
  # would have thrown away.
@@ -141,14 +162,24 @@ module Spree
141
162
  { error: "You do not have permission to read #{entry.key}." }
142
163
  end
143
164
 
165
+ # A parent the resource is not listed under is refused rather than
166
+ # dropped: dropped, the search listed the whole store and the model
167
+ # reported every claim as the one order's.
168
+ def wrong_parent(entry, parent_id)
169
+ parents = entry.index_parents.keys.sort
170
+ return { error: "#{entry.key} are not listed under another record. Search without parent_id and use filters." } if parents.empty?
171
+
172
+ { error: "#{entry.key} cannot be listed under #{parent_id}. Pass the id of one of: #{parents.join(', ')}.",
173
+ parents: parents }
174
+ end
175
+
144
176
  # A resource reached only under a parent, or one whose controller
145
177
  # resolves its scope per request. Named rather than guessed at, because
146
178
  # a tool cannot invent the parent id such a path needs.
147
179
  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
- }
180
+ refusal = entry.nested?(:index) ? nested_resource_error(entry, 'searched', :index) : { error: "#{entry.key} cannot be searched on its own." }
181
+
182
+ refusal.merge(available: ResourceMap.available_for(context).select(&:dispatchable?).map(&:key).sort)
152
183
  end
153
184
  end
154
185
  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',
@@ -21,6 +21,14 @@ module Spree
21
21
  end
22
22
  super(cart: cart, variant: variant, quantity: quantity, metadata: metadata, options: options, price: price)
23
23
 
24
+ # First, before anything is priced or reserved: a cart whose
25
+ # completion is in flight (or retained behind a payment-covered draft
26
+ # or a divided checkout) must not change under the purchase it
27
+ # supplied. The Store API fences this under its cart lock; a direct
28
+ # call to this workflow has to answer the same way rather than fall
29
+ # through to Reserve and report a misleading stock shortage.
30
+ step :guard_completion_claim
31
+
24
32
  step :parse_manual_price unless price.nil?
25
33
 
26
34
  # Core behaviour rather than a hook: an agreement's quantity terms are
@@ -43,6 +51,10 @@ module Spree
43
51
  external_step :resolve_price if price.nil?
44
52
 
45
53
  ApplicationRecord.transaction do
54
+ # Again under the row lock: the external steps above can take a
55
+ # while, and a completion may have claimed the cart since the
56
+ # first check read it.
57
+ step :guard_completion_claim_in_lock
46
58
  step :add_to_line_item
47
59
  step :handle_stock_reservations if cart.in_checkout?
48
60
  step :recalculate, with: -> { Spree.cart_recalculate_workflow }
@@ -54,6 +66,45 @@ module Spree
54
66
 
55
67
  private
56
68
 
69
+ # Draft orders (the admin path) carry no completion claim — only a cart
70
+ # does. Read from a fresh copy of the row, not the caller's instance:
71
+ # that one may predate the claim, and may carry in-memory changes the
72
+ # workflow must keep. The error matches the Store API's lock fence so a
73
+ # caller can treat both entry points alike.
74
+ def guard_completion_claim
75
+ return unless guarded_cart?
76
+ return unless completion_holds?(Spree::Cart.find(cart.id))
77
+
78
+ reject_claimed_cart
79
+ end
80
+
81
+ # Again under the row lock: the external steps can take a while, and a
82
+ # completion may have claimed — or finished — the cart since the first
83
+ # check. A no-op wait on the Store API path, which already holds this
84
+ # lock. +lock.find+ rather than +lock!+, which refuses to discard the
85
+ # caller's in-memory changes (pricing warnings).
86
+ def guard_completion_claim_in_lock
87
+ return unless guarded_cart?
88
+ return unless completion_holds?(Spree::Cart.lock.find(cart.id))
89
+
90
+ reject_claimed_cart
91
+ end
92
+
93
+ def guarded_cart?
94
+ cart.is_a?(Spree::Cart) && cart.persisted?
95
+ end
96
+
97
+ # Finalize clears the claim as it stamps +completed_at+, so a finished
98
+ # cart answers false to +completion_claimed?+ and has to be refused on
99
+ # its own.
100
+ def completion_holds?(fresh_cart)
101
+ fresh_cart.completed_at.present? || fresh_cart.completion_claimed?
102
+ end
103
+
104
+ def reject_claimed_cart
105
+ failure(cart, code: 'completion_in_progress', message: I18n.t('spree.cart_completion_in_progress'))
106
+ end
107
+
57
108
  # finite? is not redundant: BigDecimal parses "NaN" and "Infinity" and
58
109
  # neither is negative. reject! rather than failure(cart, message), which
59
110
  # would drop the message.
@@ -110,7 +110,7 @@ module Spree
110
110
  end
111
111
 
112
112
  finalize!(cart, result)
113
- halt!(result)
113
+ halt!(order_group || result)
114
114
  end
115
115
 
116
116
  # The split already ran, so the money and the division are settled — what
@@ -233,6 +233,7 @@ module Spree
233
233
  ApplicationRecord.transaction do
234
234
  order.payments.update_all(order_id: nil, cart_id: cart.id)
235
235
  order.payment_sessions.update_all(order_id: nil, cart_id: cart.id)
236
+ repoint_reservation_lines!(order, @copied_line_items.invert)
236
237
  order.stock_reservations.update_all(order_id: nil, cart_id: cart.id)
237
238
  Spree::CouponCode.where(order_id: order.id).update_all(order_id: nil, cart_id: cart.id)
238
239
  order.reload.destroy!
@@ -284,7 +285,11 @@ module Spree
284
285
  )
285
286
  order.save!
286
287
 
288
+ # Copied lines validate against the new order, so its own holds must already belong to it.
289
+ cart.stock_reservations.update_all(order_id: order.id, cart_id: nil)
287
290
  line_item_map = copy_line_items!(cart, order)
291
+ @copied_line_items = line_item_map
292
+ repoint_reservation_lines!(order, line_item_map)
288
293
  fulfillment_map = copy_fulfillments!(cart, order, line_item_map)
289
294
  fee_map = copy_typed_lines!(cart, order, line_item_map, fulfillment_map)
290
295
  copy_promotions!(cart, order)
@@ -292,6 +297,7 @@ module Spree
292
297
  copy_tax_exemptions!(cart, order, line_item_map, fulfillment_map, fee_map)
293
298
  copy_po_document!(cart, order)
294
299
  repoint_money_records!(cart, order)
300
+ Spree.cart_copiers.each { |copier| copier.call(cart: cart, order: order, line_item_map: line_item_map) }
295
301
 
296
302
  order.update_columns(
297
303
  item_total: cart.item_total,
@@ -311,6 +317,14 @@ module Spree
311
317
  order
312
318
  end
313
319
 
320
+ # Seller splitting follows the copied line ids. Compensation applies the
321
+ # inverse map before deleting those copies, keeping the cart's holds alive.
322
+ def repoint_reservation_lines!(order, line_item_map)
323
+ line_item_map.each do |source, target|
324
+ order.stock_reservations.where(line_item_id: source.id).update_all(line_item_id: target.id)
325
+ end
326
+ end
327
+
314
328
  # Freezes the buyer's tax registration onto the order, stamped with which
315
329
  # link of the chain won. A copy rather than a reference: the customer can
316
330
  # change or withdraw the number later, and the placed order's tax still
@@ -523,7 +537,6 @@ module Spree
523
537
  def repoint_money_records!(cart, order)
524
538
  cart.payments.update_all(order_id: order.id, cart_id: nil)
525
539
  cart.payment_sessions.update_all(order_id: order.id, cart_id: nil)
526
- cart.stock_reservations.update_all(order_id: order.id, cart_id: nil)
527
540
  Spree::CouponCode.where(cart_id: cart.id).update_all(order_id: order.id, cart_id: nil)
528
541
  order.payments.reset
529
542
  end
@@ -560,7 +573,9 @@ module Spree
560
573
  # its children is the order this checkout carries on with. No child holds
561
574
  # the confirmation: the customer is confirmed from the group.
562
575
  def complete_orders
563
- result = Spree.order_complete_workflow.call(order: order, payment_pending: payment_pending)
576
+ # carts.complete.validate ran before the payment was taken; a veto now
577
+ # would leave the customer charged for an order that never places.
578
+ result = Spree.order_complete_workflow.call(order: order, payment_pending: payment_pending, validated: true)
564
579
  failure(cart, code: 'completion_failed', message: result.error) if result.failure?
565
580
 
566
581
  return unless result.value.is_a?(Spree::OrderGroup)