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.

Add product create, update and destroy workflows

Damian Legawiecb4425cf6ca46
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 d8c5763473..4212ccad2d 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,6 +116,41 @@ 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)
+
+ if result.success?
+ head :no_content
+ else
+ render_result_error(result)
+ end
+ end
+
protected
def model_class
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb
index 0f36699879..1660795881 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb
@@ -2067,4 +2067,42 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
expect(json_response['translations']['de']['name']).to eq('Espressomaschine')
end
end
+ describe 'validate hooks' do
+ before { request.headers.merge!(headers) }
+ after { Spree.hooks.clear! }
+
+ it 'rejects a create with the handler\'s field errors' do
+ Spree.hooks.register('products.create.validate') do |flow|
+ flow.errors.add(:name, :reserved_word, message: 'may not mention a competitor')
+ flow.reject!
+ end
+
+ expect do
+ post :create, params: { name: 'Better than BrandX' }, as: :json
+ end.not_to change(Spree::Product, :count)
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(json_response['error']['details']['name']).to eq(['may not mention a competitor'])
+ end
+
+ it 'rejects an update' do
+ product = create(:product, name: 'Original')
+ Spree.hooks.register('products.update.validate') { |flow| flow.reject!('locked for editing') }
+
+ patch :update, params: { id: product.prefixed_id, name: 'Renamed' }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(product.reload.name).to eq('Original')
+ end
+
+ it 'refuses a destroy' do
+ product = create(:product)
+ Spree.hooks.register('products.destroy.validate') { |flow| flow.reject!('still under contract') }
+
+ delete :destroy, params: { id: product.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(product.reload.deleted_at).to be_nil
+ end
+ end
end
diff --git a/spree/core/app/services/spree/imports/row_processors/product_variant.rb b/spree/core/app/services/spree/imports/row_processors/product_variant.rb
index 116f7a2123..037fd2ebd3 100644
--- a/spree/core/app/services/spree/imports/row_processors/product_variant.rb
+++ b/spree/core/app/services/spree/imports/row_processors/product_variant.rb
@@ -85,7 +85,7 @@ module Spree
# Store is touched when the import completes
Spree::Store.no_touching do
product = assign_attributes_to_product(product)
- product.save!
+ save_through_workflow!(product)
end
handle_tags(product) if attributes['tags'].present?
@@ -109,6 +109,23 @@ module Spree
Spree::Product.accessible_by(import.current_ability, :manage)
end
+ # Imported rows pass the same :validate hook dashboard edits do — one
+ # gate, so a store's product rules can't be sidestepped by uploading
+ # a CSV. Attributes are already assigned, so the workflow gets the
+ # dirty record and nothing more.
+ def save_through_workflow!(product)
+ result =
+ if product.new_record?
+ Spree.product_create_workflow.call(store: product.store, record: product)
+ else
+ Spree.product_update_workflow.call(product: product)
+ end
+
+ raise ActiveRecord::RecordInvalid, product if result.failure?
+
+ product
+ end
+
def assign_attributes_to_product(product)
# set the SKU on a product/header row so process! updates the default variant instead of creating a new one
if product.new_record?
diff --git a/spree/core/app/workflows/spree/products/create.rb b/spree/core/app/workflows/spree/products/create.rb
new file mode 100644
index 0000000000..9462a103e8
--- /dev/null
+++ b/spree/core/app/workflows/spree/products/create.rb
@@ -0,0 +1,53 @@
+module Spree
+ module Products
+ # Creates a product. The single gate for product creation — the Admin
+ # API, the CSV importer and seeds all run through it, so a :validate
+ # handler sees every product a store gains rather than only the ones
+ # typed into the dashboard.
+ #
+ # Product writes earn a workflow (rather than the plain CRUD the services
+ # doctrine leaves alone) because creation is already orchestration:
+ # nested variants, a delivery profile stamped from the product type, and
+ # custom-field values that can only be written after the product exists.
+ class Create < Spree::Workflow
+ hooks :validate, :after_create
+
+ # The unsaved record a :validate handler reads (with its `changes`).
+ attr_reader :product
+
+ # @param store [Spree::Store]
+ # @param attributes [Hash] product attributes
+ # @param record [Spree::Product, nil] an already-built unsaved product.
+ # The CSV importer assigns its own attributes across several steps and
+ # hands the record over rather than a hash.
+ # @return [Spree::ServiceModule::Result] value is the product
+ def perform(store:, attributes: {}, record: nil)
+ super
+
+ step :build_product
+
+ # Before the insert: a rejection costs no rollback, and a handler
+ # reading `product` sees exactly what would have been saved.
+ run_hooks :validate
+
+ ApplicationRecord.transaction do
+ step :save_product
+ run_hooks :after_create
+ end
+
+ success(product)
+ end
+
+ private
+
+ def build_product
+ @product = record || store.products.new
+ @product.assign_attributes(attributes) if attributes.present?
+ end
+
+ def save_product
+ failure(product) unless product.save
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/products/destroy.rb b/spree/core/app/workflows/spree/products/destroy.rb
new file mode 100644
index 0000000000..07576e2768
--- /dev/null
+++ b/spree/core/app/workflows/spree/products/destroy.rb
@@ -0,0 +1,35 @@
+module Spree
+ module Products
+ # Soft-deletes a product. A workflow rather than a bare `destroy` so
+ # cleanup that belongs to the host — unpublishing from a channel, telling
+ # an ERP, archiving assets — has a place to attach, and so a store can
+ # refuse the deletion outright (an active supplier contract, a product
+ # still on a live campaign).
+ class Destroy < Spree::Workflow
+ hooks :validate, :after_destroy
+
+ # `product` — the record about to be soft-deleted.
+
+ # @param product [Spree::Product]
+ # @return [Spree::ServiceModule::Result] value is the destroyed product
+ def perform(product:)
+ super
+
+ run_hooks :validate
+
+ ApplicationRecord.transaction do
+ step :destroy_product
+ run_hooks :after_destroy
+ end
+
+ success(product)
+ end
+
+ private
+
+ def destroy_product
+ failure(product) unless product.destroy
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/products/update.rb b/spree/core/app/workflows/spree/products/update.rb
new file mode 100644
index 0000000000..14fa679bef
--- /dev/null
+++ b/spree/core/app/workflows/spree/products/update.rb
@@ -0,0 +1,41 @@
+module Spree
+ module Products
+ # Updates a product. Handlers reading `product.changes` in :validate see
+ # the pending edit before it is written, which is what makes rules like
+ # "price may not drop below cost" or "an active product needs an image"
+ # expressible without a model validation.
+ class Update < Spree::Workflow
+ hooks :validate, :after_update
+
+ # `product` — the record with the pending attributes assigned, so a
+ # :validate handler reads `product.changes` to see the edit.
+
+ # @param product [Spree::Product]
+ # @param attributes [Hash]
+ # @return [Spree::ServiceModule::Result] value is the product
+ def perform(product:, attributes: {})
+ super
+
+ step :assign_attributes
+ run_hooks :validate
+
+ ApplicationRecord.transaction do
+ step :save_product
+ run_hooks :after_update
+ end
+
+ success(product)
+ end
+
+ private
+
+ def assign_attributes
+ product.assign_attributes(attributes)
+ end
+
+ def save_product
+ failure(product) unless product.save
+ end
+ end
+ end
+end
diff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rb
index e3784c467c..4beae6c363 100644
--- a/spree/core/lib/spree/core/dependencies.rb
+++ b/spree/core/lib/spree/core/dependencies.rb
@@ -101,6 +101,12 @@ module Spree
# customers
customer_create_workflow: 'Spree::Customers::Create',
+ # products — every server-side write path runs through these, so a
+ # :validate handler sees dashboard edits, CSV imports and seeds alike
+ product_create_workflow: 'Spree::Products::Create',
+ product_update_workflow: 'Spree::Products::Update',
+ product_destroy_workflow: 'Spree::Products::Destroy',
+
# tracking numbers
tracking_number_service: 'Spree::TrackingNumbers::BaseService',
diff --git a/spree/core/lib/spree/workflow.rb b/spree/core/lib/spree/workflow.rb
index 1371039de8..8c79aedb4c 100644
--- a/spree/core/lib/spree/workflow.rb
+++ b/spree/core/lib/spree/workflow.rb
@@ -126,6 +126,12 @@ module Spree
# Public readers for #perform's parameters, memoized per class. An
# author-defined method of the same name wins.
+ #
+ # Note for workflow authors: inside #perform, a parameter name is a
+ # local variable and shadows the reader, so a step that reassigns the
+ # ivar (`@product = ...`) is invisible to `success(product)` further
+ # down. Name derived state differently from the parameter that seeded
+ # it — Carts::AddItem takes `variant` and exposes `line_item`.
def define_argument_readers(names)
@argument_readers ||= {}
names.each do |name|
diff --git a/spree/core/spec/workflows/spree/products/lifecycle_spec.rb b/spree/core/spec/workflows/spree/products/lifecycle_spec.rb
new file mode 100644
index 0000000000..62090d82d5
--- /dev/null
+++ b/spree/core/spec/workflows/spree/products/lifecycle_spec.rb
@@ -0,0 +1,120 @@
+require 'spec_helper'
+
+RSpec.describe 'product workflows' do
+ let(:store) { @default_store }
+
+ after { Spree.hooks.clear! }
+
+ describe Spree::Products::Create do
+ it 'creates the product' do
+ result = described_class.call(store: store, attributes: { name: 'Chair' })
+
+ expect(result).to be_success
+ expect(result.value).to be_persisted
+ expect(result.value.name).to eq('Chair')
+ expect(result.value.store).to eq(store)
+ end
+
+ it 'lets a validate handler reject the product before it is written' do
+ Spree.hooks.register('products.create.validate') do |flow|
+ flow.errors.add(:name, :reserved_word, message: 'may not contain "sample"')
+ flow.reject! if flow.product.name.to_s.include?('sample')
+ end
+
+ result = described_class.call(store: store, attributes: { name: 'a sample chair' })
+
+ expect(result).to be_failure
+ expect(result.error.to_s).to include('may not contain')
+ expect(Spree::Product.find_by(name: 'a sample chair')).to be_nil
+ end
+
+ it 'fires after_create with the saved product' do
+ seen = nil
+ Spree.hooks.register('products.create.after_create') { |flow| seen = flow.product }
+
+ described_class.call(store: store, attributes: { name: 'Desk' })
+
+ expect(seen).to be_persisted
+ expect(seen.name).to eq('Desk')
+ end
+
+ it 'returns a failure when the product is invalid' do
+ result = described_class.call(store: store, attributes: { name: '' })
+
+ expect(result).to be_failure
+ expect(result.error.to_s).to include("Name can't be blank")
+ end
+
+ # The CSV importer assigns attributes across several steps and hands over
+ # the record rather than a hash.
+ it 'accepts an already-built product' do
+ product = store.products.new(name: 'Prebuilt')
+
+ result = described_class.call(store: store, record: product)
+
+ expect(result).to be_success
+ expect(product.reload).to be_persisted
+ end
+ end
+
+ describe Spree::Products::Update do
+ let(:product) { create(:product, store: store, name: 'Original') }
+
+ it 'applies the attributes' do
+ result = described_class.call(product: product, attributes: { name: 'Renamed' })
+
+ expect(result).to be_success
+ expect(product.reload.name).to eq('Renamed')
+ end
+
+ # Reading `changes` in validate is what makes "the price may not drop
+ # below cost" expressible without a model validation.
+ it 'exposes the pending edit to a validate handler' do
+ pending_change = nil
+ Spree.hooks.register('products.update.validate') { |flow| pending_change = flow.product.changes['name'] }
+
+ described_class.call(product: product, attributes: { name: 'Renamed' })
+
+ expect(pending_change).to eq(%w[Original Renamed])
+ end
+
+ it 'leaves the record untouched when a handler rejects' do
+ Spree.hooks.register('products.update.validate') { |flow| flow.reject!('locked for editing') }
+
+ result = described_class.call(product: product, attributes: { name: 'Renamed' })
+
+ expect(result).to be_failure
+ expect(product.reload.name).to eq('Original')
+ end
+ end
+
+ describe Spree::Products::Destroy do
+ let!(:product) { create(:product, store: store) }
+
+ it 'soft-deletes the product' do
+ result = described_class.call(product: product)
+
+ expect(result).to be_success
+ expect(product.reload.deleted_at).to be_present
+ end
+
+ it 'lets a handler refuse the deletion' do
+ Spree.hooks.register('products.destroy.validate') { |flow| flow.reject!('still under contract') }
+
+ result = described_class.call(product: product)
+
+ expect(result).to be_failure
+ expect(result.error.to_s).to eq('still under contract')
+ expect(product.reload.deleted_at).to be_nil
+ end
+
+ it 'fires after_destroy for host cleanup' do
+ fired = false
+ Spree.hooks.register('products.destroy.after_destroy') { fired = true }
+
+ described_class.call(product: product)
+
+ expect(fired).to be(true)
+ end
+ end
+end