Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Let a controller declare its workflow instead of re-implementing the action

Damian Legawiecc3890f0ade37
diff --git a/CLAUDE.md b/CLAUDE.md
index 83beb1a5ae..bcefe902c2 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -266,6 +266,10 @@ The Store API (customer-facing) and Admin API (back-office) are two halves of th
`model_class`, `serializer_class` (use `Spree.api.serializer_name`), `scope` (call `super` and chain), `find_resource`, `permitted_params`, `collection_includes`
+**A resource written through a workflow declares it, never re-implements the action.** Override `create_workflow` / `update_workflow` to return the workflow, and the inherited `create`/`update` keep their authorization, their result handling and their rendering — hand-writing those actions is how a controller silently loses the record-level `authorize_resource!` the base class does. Override `create_workflow_arguments` / `update_workflow_arguments` when the workflow's keywords differ from the defaults (`store:`/`attributes:` and `<resource>:`/`attributes:`).
+
+`build_resource` builds through the owner's association — `current_store.products`, or a nested resource's parent — so a new record carries its tenancy from where it was built rather than from an attribute assigned afterwards. A model the store has no association for falls back to the class. When a `create_workflow` is declared the record is left bare, since the workflow assigns the payload and the authorization check reads the record's owner rather than its attributes.
+
#### Flat request/response structure
API v3 uses flat params — no nested Rails-style wrapping. Declare a controller's writable attributes by overriding **`resource_permitted_attributes`** (a plain list). The base `permitted_attributes` appends extension-contributed attributes to it, and `permitted_params` permits and normalizes the result. `Spree::PermittedAttributes` and its model-name inference are **removed in 6.0** — a controller that declares neither `resource_permitted_attributes` nor `permitted_params` raises `NotImplementedError` on its first write.
diff --git a/spree/api/app/controllers/spree/api/v3/admin/imports_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/imports_controller.rb
index 0d62b1c27f..e7f44d31a1 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/imports_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/imports_controller.rb
@@ -29,7 +29,9 @@ module Spree
if @resource.save
begin
- Spree.import_start_mapping_workflow.call(import: @resource)
+ result = Spree.import_start_mapping_workflow.call(import: @resource)
+
+ return render_service_error(result.error) unless result.success?
rescue ::CSV::MalformedCSVError, EncodingError => e
@resource.update_columns(status: 'failed', processing_errors: e.message, updated_at: Time.current)
return render_error(
@@ -72,7 +74,10 @@ module Spree
apply_mappings!(@resource)
if @resource.mapping_done?
- Spree.import_complete_mapping_workflow.call(import: @resource)
+ result = Spree.import_complete_mapping_workflow.call(import: @resource)
+
+ return render_service_error(result.error) unless result.success?
+
render json: serialize_resource(@resource)
else
missing = @resource.required_fields - @resource.mappings.mapped.pluck(:schema_field)
diff --git a/spree/api/app/controllers/spree/api/v3/admin/price_lists_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/price_lists_controller.rb
index 5af1034afb..edd90ce338 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/price_lists_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/price_lists_controller.rb
@@ -70,30 +70,6 @@ module Spree
end
end
- # POST /api/v3/admin/price_lists
- def create
- authorize! :create, model_class
-
- result = Spree.price_list_create_workflow.call(store: current_store, attributes: permitted_params)
-
- if result.success?
- render json: serialize_resource(result.value), status: :created
- else
- render_result_error(result)
- end
- end
-
- # PATCH /api/v3/admin/price_lists/:id
- def update
- result = Spree.price_list_update_workflow.call(price_list: @resource, attributes: permitted_params)
-
- if result.success?
- render json: serialize_resource(result.value)
- else
- render_result_error(result)
- end
- end
-
# GET /api/v3/admin/price_lists/:id/prices
#
# The spreadsheet editor's data source. Returns every Price row
@@ -126,6 +102,14 @@ module Spree
Spree.api.admin_price_list_serializer
end
+ def create_workflow
+ Spree.price_list_create_workflow
+ end
+
+ def update_workflow
+ Spree.price_list_update_workflow
+ end
+
def scope
super.for_store(current_store)
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb
index 3e379bedc3..bad33b8eeb 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb
@@ -116,30 +116,6 @@ module Spree
render json: { product_count: destroyed }
end
- # POST /api/v3/admin/products
- def create
- authorize! :create, model_class
-
- result = Spree.product_create_workflow.call(store: current_store, attributes: permitted_params)
-
- if result.success?
- render json: serialize_resource(result.value), status: :created
- else
- render_result_error(result)
- end
- end
-
- # PATCH /api/v3/admin/products/:id
- def update
- result = Spree.product_update_workflow.call(product: @resource, attributes: permitted_params)
-
- if result.success?
- render json: serialize_resource(result.value)
- else
- render_result_error(result)
- end
- end
-
# DELETE /api/v3/admin/products/:id
def destroy
result = Spree.product_destroy_workflow.call(product: @resource)
@@ -161,6 +137,14 @@ module Spree
Spree.api.admin_product_serializer
end
+ def create_workflow
+ Spree.product_create_workflow
+ end
+
+ def update_workflow
+ Spree.product_update_workflow
+ end
+
# Use SearchProvider::Database for collection to handle price/best_selling
# sorting correctly (counts before sorting, avoiding PG/Mobility issues).
def collection
diff --git a/spree/api/app/controllers/spree/api/v3/resource_controller.rb b/spree/api/app/controllers/spree/api/v3/resource_controller.rb
index 7a21eb7ea8..354d41120d 100644
--- a/spree/api/app/controllers/spree/api/v3/resource_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/resource_controller.rb
@@ -32,23 +32,40 @@ module Spree
end
# POST /api/v3/resource
+ #
+ # A controller whose resource is written through a workflow declares it
+ # with `create_workflow` and gets this action unchanged — same
+ # authorization, same rendering. Without one the record saves directly.
def create
@resource = build_resource
authorize_resource!(@resource, :create)
- if @resource.save
+ return save_and_render(@resource, status: :created) if create_workflow.nil?
+
+ result = create_workflow.call(**create_workflow_arguments)
+
+ if result.success?
+ @resource = result.value
render json: serialize_resource(@resource), status: :created
else
- render_errors(@resource.errors)
+ render_result_error(result)
end
end
# PATCH /api/v3/resource/:id
def update
- if @resource.update(permitted_params)
+ if update_workflow.nil?
+ @resource.assign_attributes(permitted_params)
+ return save_and_render(@resource)
+ end
+
+ result = update_workflow.call(**update_workflow_arguments)
+
+ if result.success?
+ @resource = result.value
render json: serialize_resource(@resource)
else
- render_errors(@resource.errors)
+ render_result_error(result)
end
end
@@ -107,17 +124,102 @@ module Spree
end
# Builds a new resource, using parent association when @parent is set
+ # The workflow that writes this resource, or nil to save the record
+ # directly. Declaring one is all a controller needs to do — `create`
+ # and `update` keep their authorization and rendering.
+ #
+ # @return [#call, nil]
+ def create_workflow
+ nil
+ end
+
+ # @return [#call, nil]
+ def update_workflow
+ nil
+ end
+
+ # Keywords passed to `create_workflow`. The default suits a workflow
+ # taking `store:` and `attributes:`; override for anything else.
+ #
+ # @return [Hash]
+ def create_workflow_arguments
+ { store: current_store, attributes: permitted_params }
+ end
+
+ # Keywords passed to `update_workflow`, keyed by the resource's own
+ # name — `product:`, `price_list:` — which is how the workflows in
+ # app/workflows name their subject. `element` rather than `singular`,
+ # which would carry the `spree_` prefix.
+ #
+ # @return [Hash]
+ def update_workflow_arguments
+ { model_class.model_name.element.to_sym => @resource, attributes: permitted_params }
+ end
+
+ def save_and_render(resource, status: :ok)
+ if resource.save
+ render json: serialize_resource(resource), status: status
+ else
+ render_errors(resource.errors)
+ end
+ end
+
+ # Builds the record a create writes, through its owner's association so
+ # tenancy comes from where the record was built rather than from an
+ # attribute assigned afterwards.
+ #
+ # A workflow-written resource gets the bare scoped record: the workflow
+ # assigns the payload itself, and assigning it here would only be for
+ # the authorization check — which reads the record's owner, not its
+ # attributes — while raising on any bulk payload the model has no
+ # setter for (`product_ids`, `variants`).
def build_resource
- resource = if @parent.present?
- @parent.send(parent_association).build(permitted_params)
- else
- model_class.new(permitted_params)
- end
- resource.store = current_store if resource.respond_to?(:store_id) && resource.store_id.blank?
+ resource = resource_scope.new
+ resource.assign_attributes(permitted_params) if create_workflow.nil?
resource.created_by = try_spree_current_user if resource.respond_to?(:created_by_id)
resource
end
+ # The relation a new record is built on: a nested resource's parent
+ # association, the store's own association for this model, or the
+ # class itself for genuinely global data (countries, roles).
+ #
+ # @return [ActiveRecord::Relation, Class]
+ def resource_scope
+ return @parent.send(parent_association) if @parent.present?
+ return model_class unless store_association
+
+ current_store.public_send(store_association)
+ end
+
+ # The store association a new record of this model builds on, or nil
+ # when there is none it can build through.
+ #
+ # Found by asking the reflections which association actually points at
+ # this model rather than by inflecting its name, so a model whose
+ # association is not the plural of its own name still resolves. Two
+ # cases yield nil and build on the class instead, taking their tenancy
+ # from the record they belong to: a doubly-nested has_many :through
+ # (Store#prices, through variants through products) is readonly, and
+ # genuinely global data (countries, roles) has no store association.
+ #
+ # @return [Symbol, nil]
+ def store_association
+ reflections = current_store.class.reflect_on_all_associations(:has_many).select do |reflection|
+ !reflection.nested? && reflection.klass == model_class
+ rescue NameError
+ # A reflection naming a class this installation does not load.
+ false
+ end
+ return reflections.first&.name if reflections.one?
+
+ # More than one association reaches this model — Store has both
+ # `orders` and `checkouts` for Spree::Order — so the conventional
+ # name decides which one a create belongs on.
+ conventional = model_class.model_name.element.pluralize.to_sym
+ reflections.find { |reflection| reflection.name == conventional }&.name
+ end
+
# Finds a single resource within scope using prefixed ID
def find_resource
scope.find_by_prefix_id!(params[:id])
diff --git a/spree/api/spec/controllers/spree/api/v3/resource_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/resource_controller_spec.rb
index e6e9216383..11f9902c13 100644
--- a/spree/api/spec/controllers/spree/api/v3/resource_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/resource_controller_spec.rb
@@ -76,4 +76,43 @@ RSpec.describe Spree::Api::V3::ResourceController, type: :controller do
Spree::TaxCategory.additional_permitted_attributes = original
end
end
+
+ # build_resource builds through the owner's association so a record carries
+ # its tenancy from where it was built. The association is found by asking
+ # the reflections which one points at the model, not by inflecting its name.
+ describe 'store association resolution' do
+ def resolve(model_class)
+ reflections = Spree::Store.reflect_on_all_associations(:has_many).select do |reflection|
+ !reflection.nested? && (reflection.klass == model_class rescue false)
+ end
+ return reflections.first&.name if reflections.one?
+
+ conventional = model_class.model_name.element.pluralize.to_sym
+ reflections.find { |reflection| reflection.name == conventional }&.name
+ end
+
+ it 'resolves a model whose association is the plural of its name' do
+ expect(resolve(Spree::Product)).to eq(:products)
+ expect(resolve(Spree::PriceList)).to eq(:price_lists)
+ end
+
+ # Store#prices goes through variants through products, which Rails makes
+ # readonly — building on it raises, so those build on the class.
+ it 'declines a doubly-nested has_many through' do
+ expect(resolve(Spree::Price)).to be_nil
+ end
+
+ # Several associations reach these, including the deprecated twins this
+ # release introduced; the conventional name picks the right one.
+ it 'breaks a tie with the conventional name' do
+ expect(resolve(Spree::Order)).to eq(:orders)
+ expect(resolve(Spree::Fulfillment)).to eq(:fulfillments)
+ expect(resolve(Spree::CustomField)).to eq(:custom_fields)
+ end
+
+ # Global data has no store association at all, so it builds on the class.
+ it 'declines a model the store does not own' do
+ expect(resolve(Spree::OptionType)).to be_nil
+ end
+ end
end