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 staff say which business an order is for, and buyers pick their own

Łukasz Adamczykc94c74485988
diff --git a/docs/plans/6.0-tax-provider.md b/docs/plans/6.0-tax-provider.md
index ce9aa3033e..43453d0182 100644
--- a/docs/plans/6.0-tax-provider.md
+++ b/docs/plans/6.0-tax-provider.md
@@ -245,6 +245,7 @@ end
```
- **Cart and order tables get zero tax columns; consumer orders carry no row at all.** The customer-level row exists because not every business buyer will have a Company — sole proprietors with VAT IDs are exactly who reverse charge exists for, and the B2B Company model targets bigger businesses.
+- **A checkout override is a copy of the number, not a link to the customer's row (2026-08-07).** The four owners are mutually exclusive, so a cart row cannot reference a customer row: `PUT /store/carts/:id/tax_identifier` takes `kind` and `value`, and a buyer choosing one of their own registrations from `GET /store/customers/me/tax_identifiers` resends the number rather than its id. Two consequences worth knowing: the copy is validated in its own right, so picking an already-verified registration triggers a fresh registry check; and it does not track the original, so correcting the profile afterwards leaves an in-flight cart on the old number. Both follow from the same reasoning as the order snapshot — a claim must not change under a sale in progress — applied one step earlier.
- **Resolution chain at estimate:** cart-owned override → the order's company → customer's row → nil (B2C treatment). The company link arrives with Phase 7. This is a fallback chain, so it lives as `#resolved_tax_identifier` on `Spree::Purchase::Taxation` — the concern that already owns `tax_address` for both Cart and Order — not behind a Dependencies seam. A three-link `||` has no swappable behavior worth freezing as public API, and an installation that genuinely needs different selection decorates the method.
### Company, pulled forward for exemptions (2026-08-07)
diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders_controller.rb
index 1739aac628..244a8a2e66 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/orders_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/orders_controller.rb
@@ -167,7 +167,7 @@ module Spree
:email, :customer_id, :user_id,
:customer_note, :internal_note,
:currency, :locale, :market_id, :channel_id,
- :preferred_stock_location_id,
+ :preferred_stock_location_id, :company_location_id,
metadata: {},
tags: [],
ship_address: address_permitted_keys,
diff --git a/spree/api/app/controllers/spree/api/v3/store/carts/tax_identifiers_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts/tax_identifiers_controller.rb
index cf6ed8aef5..61e33210d1 100644
--- a/spree/api/app/controllers/spree/api/v3/store/carts/tax_identifiers_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/carts/tax_identifiers_controller.rb
@@ -6,6 +6,14 @@ module Spree
# A registration entered during checkout, overriding whatever the
# customer's profile holds — the buyer paying through a different
# company than the one on their account.
+ #
+ # The override is a copy of the number, not a link: a cart row and a
+ # customer row cannot both own one identifier, so this takes `kind` and
+ # `value`. A buyer picking from their own registrations (see
+ # `GET /store/customers/me/tax_identifiers`) resends the number. The
+ # copy is therefore checked in its own right, and does not follow later
+ # corrections to the profile — deliberately, since a claim must not
+ # change under a sale in progress.
class TaxIdentifiersController < Store::BaseController
include Spree::Api::V3::CartResolvable
diff --git a/spree/api/app/controllers/spree/api/v3/store/customer/tax_identifiers_controller.rb b/spree/api/app/controllers/spree/api/v3/store/customer/tax_identifiers_controller.rb
index 80eb40d48c..c772e68276 100644
--- a/spree/api/app/controllers/spree/api/v3/store/customer/tax_identifiers_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/customer/tax_identifiers_controller.rb
@@ -3,11 +3,24 @@ module Spree
module V3
module Store
module Customer
- # The signed-in customer's own tax registration. Singular: one
- # registration per kind, and the storefront deals in one at a time.
+ # The signed-in customer's own tax registrations — one per kind, since a
+ # business can be registered under more than one regime.
+ #
+ # Reads come in two shapes: the list, for a checkout page offering the
+ # buyer a choice, and the singular one for reading or upserting a given
+ # kind without knowing whether it exists yet.
class TaxIdentifiersController < Store::BaseController
prepend_before_action :require_authentication!
+ # GET /api/v3/store/customers/me/tax_identifiers
+ #
+ # Everything the buyer could choose between at checkout. Small and
+ # unpaginated by nature — a business has a handful of registrations,
+ # not a page of them.
+ def index
+ render json: { data: serialize_collection(current_user.tax_identifiers.to_a) }
+ end
+
# GET /api/v3/store/customers/me/tax_identifier
def show
return head :not_found if tax_identifier.nil?
diff --git a/spree/api/app/serializers/spree/api/v3/admin/order_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/order_serializer.rb
index 0435ff6548..2b29d9b639 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/order_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/order_serializer.rb
@@ -6,6 +6,9 @@ module Spree
# Full order data including admin-only fields
class OrderSerializer < V3::OrderSerializer
+ typelize company_location_id: [:string, nullable: true],
+ company_id: [:string, nullable: true]
+
# The Admin API has no guest gating — money fields inherited from the
# store serializer are always present, so override their nullability.
typelize item_total: [:string, nullable: false], display_item_total: [:string, nullable: false],
@@ -44,6 +47,17 @@ module Spree
order.preferred_stock_location&.prefixed_id
end
+ # Which business the order is for, so the dashboard can show and change
+ # it. Read back from the column rather than #resolved_company_location:
+ # a placed order must report what it was stamped with.
+ attribute :company_location_id do |order|
+ order.company_location&.prefixed_id
+ end
+
+ attribute :company_id do |order|
+ order.company_location&.company&.prefixed_id
+ end
+
attribute :tags do |order|
order.tags.map(&:name) # not pluck as we preload tags
end
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index a3fabb6c76..db504a5a96 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -103,6 +103,9 @@ Spree::Core::Engine.add_routes do
resources :credit_cards, only: [:index, :show, :destroy]
resources :gift_cards, only: [:index, :show]
resources :store_credits, only: [:index, :show]
+ # Plural for the list a checkout page offers; singular for reading or
+ # upserting one kind without knowing whether it exists yet.
+ resources :tax_identifiers, only: [:index], controller: 'tax_identifiers'
resource :tax_identifier, only: [:show, :update, :destroy], controller: 'tax_identifiers'
resources :payment_setup_sessions, only: [:create, :show] do
member do
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/orders_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/orders_controller_spec.rb
index 6a4ab63ac9..9760a1fb1b 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/orders_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/orders_controller_spec.rb
@@ -423,6 +423,41 @@ RSpec.describe Spree::Api::V3::Admin::OrdersController, type: :controller do
expect(json_response['email']).to eq('[email protected]')
end
+ # Staff assigning the business an order is for — the only route to an
+ # exemption for a buyer who acts for several companies, until session-level
+ # selection is settled with channels and catalogs.
+ context 'assigning the business the order is for' do
+ let(:company) { create(:company, store: store) }
+ let(:location) { create(:company_location, company: company) }
+
+ it 'sets the branch and reports the company' do
+ patch :update, params: { id: order.prefixed_id, company_location_id: location.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['company_location_id']).to eq(location.prefixed_id)
+ expect(json_response['company_id']).to eq(company.prefixed_id)
+ expect(order.reload.company).to eq(company)
+ end
+
+ it 'refuses a branch belonging to another store' do
+ elsewhere = create(:company_location, company: create(:company, store: create(:store)))
+
+ patch :update, params: { id: order.prefixed_id, company_location_id: elsewhere.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(order.reload.company_location_id).to be_nil
+ end
+
+ it 'clears the branch when passed nothing' do
+ order.update!(company_location: location)
+
+ patch :update, params: { id: order.prefixed_id, company_location_id: nil }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(order.reload.company_location_id).to be_nil
+ end
+ end
+
context 'with customer assignment via customer_id' do
let(:customer) { create(:user) }
diff --git a/spree/api/spec/controllers/spree/api/v3/store/customer/tax_identifiers_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/customer/tax_identifiers_controller_spec.rb
new file mode 100644
index 0000000000..400cb6095f
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/store/customer/tax_identifiers_controller_spec.rb
@@ -0,0 +1,61 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Store::Customer::TaxIdentifiersController, type: :controller do
+ render_views
+
+ include_context 'API v3 Store'
+
+ let!(:eu) { create(:tax_identifier, customer: user, kind: 'eu_vat', value: 'DE123456789') }
+ let!(:gb) { create(:tax_identifier, customer: user, kind: 'gb_vat', value: 'GB123456789') }
+
+ before do
+ request.headers['X-Spree-Api-Key'] = api_key.token
+ request.headers['Authorization'] = "Bearer #{jwt_token}"
+ end
+
+ describe 'GET #index' do
+ # What a checkout page needs to offer the buyer a choice: a business
+ # registered under two regimes has two, and asking by kind means guessing.
+ it 'lists every registration the buyer holds' do
+ get :index
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['data'].map { |row| row['kind'] }).to contain_exactly('eu_vat', 'gb_vat')
+ expect(json_response['data'].map { |row| row['value'] }).to contain_exactly('DE123456789', 'GB123456789')
+ end
+
+ it 'lists nobody else\'s' do
+ create(:tax_identifier, customer: create(:user), kind: 'eu_vat', value: 'FR999999999')
+
+ get :index
+
+ expect(json_response['data'].map { |row| row['value'] }).not_to include('FR999999999')
+ end
+
+ it 'returns an empty list for a buyer with none' do
+ Spree::TaxIdentifier.where(customer_id: user.id).destroy_all
+
+ get :index
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['data']).to eq([])
+ end
+
+ it 'refuses an unauthenticated request' do
+ request.headers['Authorization'] = nil
+
+ get :index
+
+ expect(response).to have_http_status(:unauthorized)
+ end
+ end
+
+ describe 'GET #show' do
+ it 'returns the registration of the requested kind' do
+ get :show, params: { kind: 'gb_vat' }
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['value']).to eq('GB123456789')
+ end
+ end
+end
diff --git a/spree/core/app/models/concerns/spree/purchase/company.rb b/spree/core/app/models/concerns/spree/purchase/company.rb
index 690bf9311a..6fc864d8ad 100644
--- a/spree/core/app/models/concerns/spree/purchase/company.rb
+++ b/spree/core/app/models/concerns/spree/purchase/company.rb
@@ -9,6 +9,12 @@ module Spree
included do
belongs_to :company_location, class_name: 'Spree::CompanyLocation', optional: true
+
+ # Guarded on the model rather than in the controller so every path is
+ # covered — the admin write, a future storefront one, and the console.
+ # Companies are store-scoped, so a branch from another store would tax
+ # this sale against a business the merchant does not trade as.
+ validate :company_location_belongs_to_store
end
# @return [Spree::Company, nil]
@@ -28,11 +34,18 @@ module Spree
# and no exemption is claimed — refusing to guess, because guessing would
# invoice one business for another's purchase.
#
- # **Provisional.** Choosing between several branches is the same question
- # docs/plans/6.1-channels-catalogs-b2b.md leaves open for product
- # visibility (its `user_company_location` helper is referenced but never
- # defined), and that plan defers buyer authority to a dedicated B2B plan.
- # Whatever it settles on should replace this.
+ # **Provisional — revisit when channels and catalogs are implemented.**
+ # That work (docs/plans/6.1-channels-catalogs-b2b.md — filed as 6.1 today,
+ # expected to land in 6.0) has the identical question and no answer either:
+ # its `Products::ForContext` calls `user_company_location(user, store)`,
+ # singular, which the plan never defines. Catalog, negotiated pricing and
+ # tax all need the same answer, so it must be settled once and read from
+ # one place — otherwise a buyer could browse one company's catalog at its
+ # prices while being taxed as another.
+ #
+ # Until then, staff can set the branch explicitly through the admin order
+ # API. A buyer acting for several businesses who checks out unaided gets no
+ # company and no exemption, which is why this must not stay as it is.
#
# @return [Spree::CompanyLocation, nil]
def resolved_company_location
@@ -47,6 +60,13 @@ module Spree
private
+ def company_location_belongs_to_store
+ return if company_location.nil? || store_id.nil?
+ return if company_location.store_id == store_id
+
+ errors.add(:company_location, :invalid)
+ end
+
# Deliberately not memoized. An instance variable survives #reload, so a
# value cached before a contact was added stays stale for the life of the
# object — which silently dropped the branch at completion. Caching this
diff --git a/spree/core/spec/models/concerns/spree/purchase/company_spec.rb b/spree/core/spec/models/concerns/spree/purchase/company_spec.rb
index cc45e8c01c..b3115df079 100644
--- a/spree/core/spec/models/concerns/spree/purchase/company_spec.rb
+++ b/spree/core/spec/models/concerns/spree/purchase/company_spec.rb
@@ -48,6 +48,23 @@ RSpec.shared_examples 'a company host' do
end
end
+ describe 'the branch must belong to the same store' do
+ it 'refuses a branch from another store' do
+ elsewhere = create(:company_location, company: create(:company, store: create(:store)))
+
+ record.company_location = elsewhere
+
+ expect(record).not_to be_valid
+ expect(record.errors[:company_location]).to be_present
+ end
+
+ it 'accepts one from its own store' do
+ record.company_location = location
+
+ expect(record).to be_valid
+ end
+ end
+
describe '#b2b?' do
it 'is true once a branch resolves' do
record.update!(company_location: location)