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.

Merge remote-tracking branch 'origin/main' into feature/v-3526

Damian Legawiec92ebd8968322
diff --cc docs/plans/decisions.md
index 1fb71aad02,83e39b61b6..d86f61d49f
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@@ -112,47 -112,49 +112,90 @@@ Consequences: Admin API code must neve
store, and store-touching cache keys must carry the store id by construction.
Plan: `6.0-store-context-and-first-run-setup.md`.
+ ## 2026-08-13: Validate hooks are the validation extension surface; no generic model-validation registry
+
+ New plan `6.0-extendable-validations.md`. The question was whether developers
+ customizing validations — the single most common core-model modification —
+ deserve a generic add/remove validation mechanism, or whether workflow
+ `validate` hooks plus the existing model-level knobs already are the answer.
+ Decision: the latter. Adding a rule via prepended decorator is already short
+ and Rails-native; removing one via registry would require repackaging every
+ core validation as a named unit, and no competitor ships anything comparable.
+ Relaxing a core rule stays on named store preferences
+ (`disable_sku_validation` pattern) or predicate overrides.
+
+ What ships instead is the work that makes the hook recommendation honest:
+
+ - **`Carts::UpsertItems` graduates to the workflow tier** and absorbs every
+ non-increment item mutation (bulk payloads, PATCH quantity, DELETE item —
+ quantity `0` removes). It fires `validate` per item with `AddItem`-compatible
+ readers, shares the item-application steps with `AddItem` (whose per-item
+ full recalculate is what made N-item adds slow — the batch recalculates
+ once), and is **partial-success on the storefront**: a per-item rejection
+ skips the item onto the cart's existing `warnings` array on a 2xx response
+ rather than rolling back the batch. The **order-side twin fails the whole
+ batch** — a merchant's struck-out row silently not applying is worse than a
+ failed request. No whole-batch veto in 6.0.
+ `SetQuantity`/`RemoveLineItem` become deprecated shells.
+ - **`Products::Create`/`Update`/`Destroy` become workflows** (real
+ orchestration, not the plain CRUD the doctrine rejects) with all write paths
+ routed through them — Admin API v3, CSV importer, seeds — so hooks always
+ fire. Variants ride the product graph; no standalone variant workflow.
+ - **Rejections carry `ActiveModel::Errors`.** `Workflow#errors` +
+ argument-less `reject!` render through `render_validation_error`, so
+ extension rejections share the model-422 shape (field-scoped symbolic
+ codes) instead of a flat message under a controller-hardcoded wrong code.
+ `reject!(message)` bridges to `:base`.
+ - **Address and cart creation get no workflow** — plain CRUD, demand already
+ served (store preferences, gating predicates, `Spree.validators.addresses`
+ which finally gets docs + a removal API + a `require_company` preference;
+ flow-level address policy belongs on `carts.complete.validate`).
+ - **Custom-field value validation deferred** to its own plan: Shopify-style
+ per-definition length/range/regex/allowed-values, enforced in the
+ `CustomField` model, gating new writes only. The 2026-08-06 "required stays
+ advisory" constraint is untouched.
+
+## 2026-08-12: Jurisdiction is stored as a code, never as a country or state row
+
+Amends 2026-08-06 ("Converted-away columns outlive the release that converts
+them"), which had tax rates gaining `country_id`/`state_id`. They gain
+`country_iso` and `state_code` instead — plain strings, upcased on write. The
+reason is that `Spree::Country` and `Spree::State` are themselves on the way out,
+so a rate pointing at their rows would need converting a second time; and "DE"
+is what a merchant recognises, where a row id is not. It also matches the
+jurisdiction snapshot `spree_tax_lines` already carries, so a rate and the line
+it produced now speak in the same terms.
+
+Everything else in that entry stands: `spree_tax_rates.zone_id` still survives
+through 6.0 as `spree:migrate_tax_zones`'s input, and the task now writes codes.
+
+**The cost, accepted:** the `state_belongs_to_country` validation is gone. With
+codes there is no country row to check a state against, and keeping the guard
+would mean keeping the `Spree::State` lookup this removes. A mismatched pair is
+simply a rate that never matches an address — which is what the mismatch always
+meant in practice, minus the early warning.
+
+Because the columns had not shipped, the original migration was amended rather
+than followed by a second one.
+
+**Extended the same day to everything this work owns**, after a review pass found
+the same shape elsewhere. `Spree::TaxExemptionCertificate` held country and state
+references, and `Spree::PriceRules::ZoneRule` held a `country_ids` preference of
+`Spree::Country` primary keys; both now hold codes (`country_iso`/`state_code`,
+`country_isos`). The certificate case was a live defect rather than a tidy-up:
+an unrecognised ISO resolved to a nil country, and nil claims *every* country
+there, so a mistyped code silently turned one state's certificate into a
+worldwide exemption. A code that matches nothing narrows to nothing.
+
+`Spree::Pricing::Context` gained a `country_iso` reader so a price rule compares
+codes rather than reaching through `context.country`; when Country goes, the
+context is the only place that changes.
+
+**Where a Country object is still correct:** `Purchase::Taxation#tax_country` and
+`Spree::Current.tax_country` return one, and should. Those are lookups in request
+context, not stored jurisdiction, and addresses and markets still speak in
+countries. The rule this entry sets is about what a row *persists*.
+
## 2026-08-12: The label leads, fulfilled follows (amends the Phase 7 fulfill flow)
A warehouse prints the label, sticks it on the box, hands the box over — and
diff --cc spree/core/app/workflows/spree/carts/upsert_items.rb
index 0000000000,cdaf14f902..fa25ddea87
mode 000000,100644..100644
--- a/spree/core/app/workflows/spree/carts/upsert_items.rb
+++ b/spree/core/app/workflows/spree/carts/upsert_items.rb
@@@ -1,0 -1,208 +1,214 @@@
+ module Spree
+ module Carts
+ # Applies a batch of item changes to a cart in one pass — the single gate
+ # for every item mutation that is not a plain add-increment (bulk
+ # payloads, a quantity edit, a removal). AddItem stays the increment
+ # ("add 2 more"); this workflow SETS quantity, and quantity zero removes.
+ #
+ # Two things make it worth a workflow rather than a loop over AddItem.
+ # Extensions get one veto point covering every non-increment path, and
+ # the cart recalculates ONCE for the whole batch instead of once per
+ # item — the money math is the expensive part, so a dozen items cost
+ # roughly one item's work.
+ #
+ # Rejections are per item, not per batch: a validate handler that vetoes
+ # one line skips that line and the rest still apply, so a customer
+ # restoring a saved cart keeps everything still purchasable and hears
+ # about what was dropped. The skipped items come back as +warnings+
+ # (see Spree::Carts::ItemWarning) beside a successful result.
+ class UpsertItems < Spree::Workflow
+ hooks :validate, :after_items_upserted
+
+ # Readers a :validate handler uses. variant/quantity/metadata describe
+ # the item currently being validated — the same reader names AddItem
+ # exposes, so one handler class registers on both keys unchanged.
+ # +items+ is the whole resolved batch, for rules that need to see it
+ # (a per-order unit cap, a mixed-category restriction).
+ attr_reader :variant, :quantity, :metadata, :items, :warnings
+
+ # @param cart [Spree::Cart, Spree::Order]
+ # @param items [Array<Hash>] :variant_id (prefixed or raw), :quantity,
+ # :metadata. Quantity defaults to 1; zero or less removes.
+ # @return [Spree::ServiceModule::Result] value is the cart
+ def perform(cart:, items:)
+ super
+ @warnings = []
+
+ step :resolve_items
+ return success(cart) if resolved_items.empty?
+
+ ApplicationRecord.transaction do
+ step :apply_items
+ step :handle_stock_reservations if cart.in_checkout?
+ step :recalculate, with: -> { Spree.cart_recalculate_workflow } if recalculate?
+ run_hooks :after_items_upserted
+ end
+
+ # Warnings ride on the cart itself — the same channel the
+ # out-of-stock sweep uses — so they reach the serializer without
+ # every caller forwarding them by hand. Set after the reload, which
+ # would otherwise drop them.
+ cart.reload
+ cart.warnings |= warnings.map(&:to_h) if warnings.any?
+
+ success(cart)
+ end
+
+ private
+
+ attr_reader :resolved_items
+
+ # The cart side recalculates here because nothing else will. The order
+ # side overrides this: admin edits run items, fulfillments and coupons
+ # as one pipeline and recalculate once at the end of it.
+ def recalculate?
+ true
+ end
+
+ # A customer restoring a saved cart should keep whatever is still
+ # purchasable, so a bad line becomes a warning. A merchant editing an
+ # order should not: a struck-out or repriced row silently not applying
+ # is worse than the edit failing, so the order twin turns this off.
+ def partial_success?
+ true
+ end
+
+ # One pass for lookup and currency checks, before anything is written,
+ # so a batch naming an unknown variant fails before it has half
+ # applied.
+ def resolve_items
+ store = cart.store || Spree::Current.store
+
+ @resolved_items = Array(items).filter_map do |item_params|
+ item_params = item_params.to_h.deep_symbolize_keys
+ quantity = (item_params[:quantity] || 1).to_i
+ variant = resolve_variant(store, item_params[:variant_id], removing: quantity <= 0)
+ next if variant.nil?
+
+ Spree::Carts::ResolvedItem.new(
+ variant: variant,
+ quantity: quantity,
+ metadata: item_params[:metadata].to_h
+ )
+ end
+ end
+
+ def apply_items
+ resolved_items.each_with_index do |item, index|
+ next unless validated?(item, index)
+
+ line_item = Spree.line_item_by_variant_finder.new.execute(owner: cart, variant: item.variant)
+
+ if item.remove?
+ line_item&.destroy!
+ next
+ end
+
+ if item.variant.amount_in(cart.currency).nil?
+ message = Spree.t('cart_line_item.currency_unavailable', li_name: item.variant.name, currency: cart.currency)
+ failure(item.variant, message) unless partial_success?
+
+ warn(index, item, :currency_unavailable, message)
+ next
+ end
+
+ apply_item(item, line_item, index)
+ end
+ end
+
+ # Dispatches :validate for one item with that item's readers bound, and
+ # converts a handler's rejection into a warning instead of failing the
+ # batch. FailureSignal is what reject! raises; catching it here is the
+ # deliberate difference between this workflow and every other one.
+ def validated?(item, index)
+ bind_current_item(item)
+ run_hooks :validate
+ true
+ rescue Spree::Workflow::FailureSignal
+ raise unless partial_success?
+
+ rejection = errors
+ @errors = nil
+ warnings << Spree::Carts::ItemWarning.new(
+ item_index: index,
+ variant: item.variant,
+ code: rejection.details.values.flatten.first&.dig(:error) || :rejected,
+ message: rejection.full_messages.to_sentence
+ )
+ false
+ ensure
+ bind_current_item(nil)
+ end
+
+ def bind_current_item(item)
+ @variant = item&.variant
+ @quantity = item&.quantity
+ @metadata = item&.metadata || {}
+ end
+
+ def apply_item(item, line_item, index)
+ if line_item
+ line_item.quantity = item.quantity
+ line_item.metadata = line_item.metadata.merge(item.metadata) if item.metadata.present?
+ else
+ line_item = cart.line_items.new(
+ quantity: item.quantity,
+ variant: item.variant,
+ options: { currency: cart.currency }
+ )
+ line_item.metadata = item.metadata if item.metadata.present?
+ end
+
+ created = line_item.new_record?
+
+ # A line that won't save — most often the stock availability
+ # validator — is this item's problem, not the batch's. Failing here
+ # would roll back every other line, which is exactly what a customer
+ # restoring a saved cart must not lose.
+ unless line_item.save
+ failure(line_item) unless partial_success?
+
+ warn(index, item, line_item.errors.details.values.flatten.first&.dig(:error) || :invalid,
+ line_item.errors.full_messages.to_sentence)
+ return
+ end
+
+ line_item.reload.recalculate_price
- ::Spree.tax_provider.estimate(line_item.owner, [line_item]) if created
++ return unless created
++
++ # Per-market provider rather than a global one, and carrying the same
++ # typed inputs as a full recalculation so a single new line is taxed
++ # with the buyer's registration and exemptions.
++ owner = line_item.owner
++ owner.tax_provider.estimate(owner, [line_item], **owner.tax_estimate_inputs)
+ end
+
+ def handle_stock_reservations
+ result = Spree::StockReservations::Reserve.call(cart: cart)
+ failure(cart, result.error) if result.failure?
+ end
+
+ # Adds resolve through the store, so a variant belonging to another
+ # tenant is a 404 rather than a cross-store add. Removals resolve
+ # through the cart's own items instead: the line is already there, and
+ # a product that has since been deleted or unpublished has left
+ # store.variants — refusing to remove it would strand the customer
+ # with a line they cannot get rid of.
+ def resolve_variant(store, variant_id, removing: false)
+ return nil if variant_id.blank?
+
+ if removing
+ cart.line_items.detect { |line_item| line_item.variant_id.to_s == variant_id.to_s }&.variant ||
+ Spree::Variant.with_deleted.find_by_param(variant_id)
+ else
+ store.variants.find_by_param(variant_id) ||
+ raise(ActiveRecord::RecordNotFound.new("Variant '#{variant_id}' not found in this store", 'Spree::Variant', 'id', variant_id))
+ end
+ end
+
+ def warn(index, item, code, message)
+ warnings << Spree::Carts::ItemWarning.new(item_index: index, variant: item.variant, code: code, message: message)
+ end
+ end
+ end
+ end
diff --cc spree/core/spec/workflows/spree/tax_exemption_certificates/verify_spec.rb
index b96fd07989,0000000000..fb67a8a488
mode 100644,000000..100644
--- a/spree/core/spec/workflows/spree/tax_exemption_certificates/verify_spec.rb
+++ b/spree/core/spec/workflows/spree/tax_exemption_certificates/verify_spec.rb
@@@ -1,74 -1,0 +1,74 @@@
+require 'spec_helper'
+
+RSpec.describe Spree::TaxExemptionCertificates::Verify do
+ let(:store) { @default_store }
+ let(:company) { create(:company, store: store) }
+ let(:certificate) { create(:tax_exemption_certificate, company: company) }
+ let(:staff) { create(:admin_user) }
+
+ before { Spree.hooks.clear! }
+ after { Spree.hooks.clear! }
+
+ it 'accepts a pending certificate and records who did' do
+ result = described_class.call(certificate: certificate, verified_by: staff)
+
+ expect(result).to be_success
+ expect(result.value).to be_verified
+ expect(result.value.verified_at).to be_present
+ expect(result.value.verified_by).to eq(staff)
+ end
+
+ it 'makes the certificate count at estimate time' do
+ expect { described_class.call(certificate: certificate) }.
+ to change { Spree::TaxExemptionCertificate.active.include?(certificate.reload) }.from(false).to(true)
+ end
+
+ it 'refuses anything not pending' do
+ revoked = create(:tax_exemption_certificate, company: company, status: 'revoked')
+
+ result = described_class.call(certificate: revoked)
+
+ expect(result).to be_failure
+ expect(revoked.reload).to be_revoked
+ end
+
+ it 'publishes the event', :events do
+ allow(Spree::Events).to receive(:publish)
+
+ described_class.call(certificate: certificate)
+
+ expect(Spree::Events).to have_received(:publish).with('tax_exemption_certificate.verified', any_args)
+ end
+
+ # The reason this is a workflow at all: somewhere to refuse before the
+ # certificate starts exempting sales.
+ describe 'the validate hook' do
+ it 'lets a handler veto, writing nothing' do
+ Spree.hooks.register('tax_exemption_certificates.verify.validate') do |flow|
+ flow.reject!('registry check failed')
+ end
+
+ result = described_class.call(certificate: certificate)
+
+ expect(result).to be_failure
- expect(result.error.value).to eq('registry check failed')
++ expect(result.error.to_s).to eq('registry check failed')
+ expect(certificate.reload).to be_pending
+ expect(certificate.verified_at).to be_nil
+ end
+
+ it 'runs after_verify once accepted' do
+ seen = nil
+ Spree.hooks.register('tax_exemption_certificates.verify.after_verify') do |flow|
+ seen = flow.certificate.status
+ end
+
+ described_class.call(certificate: certificate)
+
+ expect(seen).to eq('verified')
+ end
+ end
+
+ it 'is reachable through the dependency seam' do
+ expect(Spree.tax_exemption_certificate_verify_workflow).to eq(described_class)
+ end
+end