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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Companies and tax exemptions, Phases 1-2: describe a business and link a sale to it
Łukasz Adamczyk66e442ac2d28
diff --git a/docs/plans/6.0-tax-provider.md b/docs/plans/6.0-tax-provider.mdindex 99f1acb71c..ce9aa3033e 100644--- a/docs/plans/6.0-tax-provider.md+++ b/docs/plans/6.0-tax-provider.md@@ -1166,10 +1166,17 @@ def b2b?end```-**Resolution for a storefront buyer.** A cart with no `company_location` set falls back to the-customer's contacts — one contact means one location, so nothing to ask; several means the buyer-picks, and until they do there is no company and no exemption. Staff set the location directly on-admin-created orders. This is the only piece of B2B *behavior* in the phase; everything else is data.+**Resolution for a storefront buyer — provisional (2026-08-07).** A cart with no `company_location`+set falls back to the customer's contacts: acting for exactly one branch resolves to it, acting for+several resolves to nothing, so no company applies and no exemption is claimed. Staff set the branch+directly on admin-created orders. Refusing to guess is the point — picking one would invoice one+business for another's purchase.++Choosing *between* branches is deliberately not answered here. It is the same question+`6.1-channels-catalogs-b2b.md` leaves open for product visibility — its `user_company_location(user,+store)` helper is called but never defined — and that plan defers buyer authority to a dedicated B2B+plan after 6.1. Whatever it settles on replaces `Spree::Purchase::Company#resolved_company_location`.+This is the only piece of B2B *behavior* in the phase; everything else is data.#### Step 2 — Company joins the tax identifier chaindiff --git a/spree/core/app/models/concerns/spree/customer_methods.rb b/spree/core/app/models/concerns/spree/customer_methods.rbindex 8c9ecc1b6d..202b76c685 100644--- a/spree/core/app/models/concerns/spree/customer_methods.rb+++ b/spree/core/app/models/concerns/spree/customer_methods.rb@@ -70,6 +70,9 @@ module Spree# One per registration kind — a business can hold both an EU and a UK VAT number.has_many :tax_identifiers, class_name: 'Spree::TaxIdentifier', foreign_key: :customer_id,dependent: :destroy, inverse_of: :customer+ has_many :company_contacts, class_name: 'Spree::CompanyContact', foreign_key: :customer_id,+ dependent: :destroy, inverse_of: :customer+ has_many :company_locations, through: :company_contactsbelongs_to :ship_address, class_name: 'Spree::Address', optional: truebelongs_to :bill_address, class_name: 'Spree::Address', optional: truediff --git a/spree/core/app/models/concerns/spree/purchase/company.rb b/spree/core/app/models/concerns/spree/purchase/company.rbnew file mode 100644index 0000000000..9ff0d706b2--- /dev/null+++ b/spree/core/app/models/concerns/spree/purchase/company.rb@@ -0,0 +1,54 @@+module Spree+ module Purchase+ # Which business customer a sale is for, shared by Spree::Cart and+ # Spree::Order. The branch is what the sale references; the company is+ # derived from it, so a per-branch address or registration has somewhere to+ # live later without moving this column.+ module Company+ extend ActiveSupport::Concern++ included do+ belongs_to :company_location, class_name: 'Spree::CompanyLocation', optional: true+ end++ # @return [Spree::Company, nil]+ def company+ resolved_company_location&.company+ end++ # @return [Boolean] whether this sale is for a business customer+ def b2b?+ resolved_company_location.present?+ end++ # The branch this sale is for. An explicit choice wins; otherwise a buyer+ # who acts for exactly one branch is unambiguous and resolves to it.+ #+ # A buyer who acts for several resolves to nothing, so no company applies+ # 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.+ #+ # @return [Spree::CompanyLocation, nil]+ def resolved_company_location+ return company_location if company_location_id.present?++ sole_customer_location+ end++ private++ def sole_customer_location+ return nil if customer.nil?++ locations = customer.company_locations.to_a.uniq+ locations.one? ? locations.first : nil+ end+ end+ end+enddiff --git a/spree/core/app/models/spree/cart.rb b/spree/core/app/models/spree/cart.rbindex 042df04afb..db82b65319 100644--- a/spree/core/app/models/spree/cart.rb+++ b/spree/core/app/models/spree/cart.rb@@ -17,6 +17,7 @@ module Spreeinclude Spree::SingleStoreResourceinclude Spree::Purchase::Channel+ include Spree::Purchase::Companyinclude Spree::Purchase::Marketinclude Spree::Purchase::Currencyinclude Spree::Purchase::Localediff --git a/spree/core/app/models/spree/company.rb b/spree/core/app/models/spree/company.rbnew file mode 100644index 0000000000..809bc1b3b2--- /dev/null+++ b/spree/core/app/models/spree/company.rb@@ -0,0 +1,41 @@+module Spree+ # A business customer — the entity an invoice is addressed to, as distinct+ # from the person who placed the order. Carries the tax registration and the+ # exemption certificates that decide how its purchases are taxed.+ #+ # Deliberately minimal: this is the part of the B2B model that tax needs+ # (docs/plans/6.0-tax-provider.md Phase 7). Assortment, negotiated pricing+ # and buyer roles belong to docs/plans/6.1-channels-catalogs-b2b.md, which+ # extends these models rather than redefining them.+ class Company < Spree.base_class+ has_prefix_id :comp++ include Spree::SingleStoreResource+ include Spree::Metafields++ publishes_lifecycle_events++ # Single consolidated metadata JSON column (docs/plans/decisions.md+ # 2026-03-16 "Consolidate metadata") — write-only developer escape hatch.+ attribute :metadata, default: -> { {} }++ belongs_to :store, class_name: 'Spree::Store', inverse_of: :companies++ has_many :company_locations, class_name: 'Spree::CompanyLocation', dependent: :destroy,+ inverse_of: :company+ has_many :company_contacts, through: :company_locations++ validates :name, presence: true+ # Paired with the partial unique index, per the convention — without it a+ # duplicate reference reaches the database and surfaces as a 500 rather+ # than a validation error. Nil is exempt on both sides.+ validates :external_id, uniqueness: { scope: [:store_id, *spree_base_uniqueness_scope] }, allow_nil: true++ self.whitelisted_ransackable_attributes = %w[name external_id]+ self.whitelisted_ransackable_associations = %w[company_locations]++ def event_serializer_class+ 'Spree::Api::V3::CompanySerializer'.safe_constantize+ end+ end+enddiff --git a/spree/core/app/models/spree/company_contact.rb b/spree/core/app/models/spree/company_contact.rbnew file mode 100644index 0000000000..144aeec9f5--- /dev/null+++ b/spree/core/app/models/spree/company_contact.rb@@ -0,0 +1,21 @@+module Spree+ # Links a customer to a branch they buy for. This is what lets a signed-in+ # buyer's own cart find its company without staff touching the order.+ #+ # +role+ is a plain string with no behavior attached in 6.0 — permissions,+ # approval limits and purchase authority belong to the dedicated B2B plan.+ class CompanyContact < Spree.base_class+ has_prefix_id :cc++ belongs_to :company_location, class_name: 'Spree::CompanyLocation', inverse_of: :company_contacts+ belongs_to :customer, class_name: Spree.customer_class.to_s, inverse_of: :company_contacts++ has_one :company, through: :company_location++ validates :customer_id, uniqueness: { scope: :company_location_id }++ delegate :store, :store_id, to: :company_location++ self.whitelisted_ransackable_attributes = %w[role]+ end+enddiff --git a/spree/core/app/models/spree/company_location.rb b/spree/core/app/models/spree/company_location.rbnew file mode 100644index 0000000000..15d1b78087--- /dev/null+++ b/spree/core/app/models/spree/company_location.rb@@ -0,0 +1,32 @@+module Spree+ # A branch or office of a business customer. Reaches the store through its+ # company and so carries no store_id of its own.+ #+ # Its addresses are created inline and owned outright — a branch address is+ # the branch's, not a row shared with the buyer's address book, which is why+ # they are destroyed with it (docs/plans/decisions.md 2026-08-07).+ class CompanyLocation < Spree.base_class+ has_prefix_id :cloc++ include Spree::Metafields++ attribute :metadata, default: -> { {} }++ belongs_to :company, class_name: 'Spree::Company', inverse_of: :company_locations+ belongs_to :billing_address, class_name: 'Spree::Address', optional: true, dependent: :destroy+ belongs_to :shipping_address, class_name: 'Spree::Address', optional: true, dependent: :destroy++ accepts_nested_attributes_for :billing_address+ accepts_nested_attributes_for :shipping_address++ has_many :company_contacts, class_name: 'Spree::CompanyContact', dependent: :destroy,+ inverse_of: :company_location+ has_many :customers, through: :company_contacts, source: :customer++ validates :name, presence: true++ delegate :store, :store_id, to: :company++ self.whitelisted_ransackable_attributes = %w[name external_id]+ end+enddiff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rbindex eae767c8c8..615da857e2 100644--- a/spree/core/app/models/spree/order.rb+++ b/spree/core/app/models/spree/order.rb@@ -20,6 +20,7 @@ module Spreeinclude Spree::SingleStoreResourceinclude Spree::Purchase::Channel+ include Spree::Purchase::Companyinclude Spree::Purchase::Marketinclude Spree::Purchase::Currencyinclude Spree::Purchase::Localediff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rbindex 6be7d11946..b6f460e9ee 100644--- a/spree/core/app/models/spree/store.rb+++ b/spree/core/app/models/spree/store.rb@@ -154,6 +154,8 @@ module Spreehas_many :customer_groups, class_name: 'Spree::CustomerGroup', dependent: :destroy, inverse_of: :store+ has_many :companies, class_name: 'Spree::Company', dependent: :destroy, inverse_of: :store+has_many :api_keys, class_name: 'Spree::ApiKey', dependent: :destroyhas_many :allowed_origins, class_name: 'Spree::AllowedOrigin', dependent: :destroydiff --git a/spree/core/app/workflows/spree/carts/complete.rb b/spree/core/app/workflows/spree/carts/complete.rbindex c40d6de4fd..f9082f23cd 100644--- a/spree/core/app/workflows/spree/carts/complete.rb+++ b/spree/core/app/workflows/spree/carts/complete.rb@@ -176,6 +176,7 @@ module Spreelocale: cart.locale,market: cart.market,channel: cart.channel,+ company_location: cart.resolved_company_location,customer: cart.customer,token: cart.token,accept_marketing: cart.accept_marketing,diff --git a/spree/core/db/migrate/20260807000001_create_spree_companies.rb b/spree/core/db/migrate/20260807000001_create_spree_companies.rbnew file mode 100644index 0000000000..544e3ad7af--- /dev/null+++ b/spree/core/db/migrate/20260807000001_create_spree_companies.rb@@ -0,0 +1,52 @@+class CreateSpreeCompanies < ActiveRecord::Migration[8.1]+ def change+ create_table :spree_companies do |t|+ t.references :store, null: false+ t.string :name, null: false+ t.string :external_id # ERP/CRM reference+ # No tax_exempt boolean — exemption is a certificate scoped to a+ # jurisdiction, which a flag cannot express (docs/plans/decisions.md+ # 2026-08-07).+ if t.respond_to?(:jsonb)+ t.jsonb :metadata+ else+ t.json :metadata+ end+ t.timestamps+ end++ add_index :spree_companies, [:store_id, :external_id], unique: true,+ where: 'external_id IS NOT NULL', name: 'idx_companies_external_id'++ # No store_id on the children: they reach the store through the company,+ # matching spree_return_line_items.+ create_table :spree_company_locations do |t|+ t.references :company, null: false+ t.references :billing_address+ t.references :shipping_address+ t.string :name, null: false+ t.string :external_id+ if t.respond_to?(:jsonb)+ t.jsonb :metadata+ else+ t.json :metadata+ end+ t.timestamps+ end++ create_table :spree_company_contacts do |t|+ t.references :company_location, null: false+ t.references :customer, null: false+ t.string :role, null: false, default: 'buyer' # no behavior attached in 6.0+ t.timestamps+ end++ add_index :spree_company_contacts, [:company_location_id, :customer_id], unique: true,+ name: 'idx_company_contacts_on_location_and_customer'++ # Both sides: exemption has to resolve while the buyer is still in+ # checkout, and completion copies the branch onto the order.+ add_reference :spree_carts, :company_location+ add_reference :spree_orders, :company_location+ end+enddiff --git a/spree/core/lib/spree/testing_support/factories/company_factory.rb b/spree/core/lib/spree/testing_support/factories/company_factory.rbnew file mode 100644index 0000000000..3ee8d87fda--- /dev/null+++ b/spree/core/lib/spree/testing_support/factories/company_factory.rb@@ -0,0 +1,22 @@+FactoryBot.define do+ factory :company, class: Spree::Company do+ sequence(:name) { |n| "Acme Corp #{n}" }+ store { Spree::Store.default || create(:store) }++ factory :company_with_location do+ after(:create) do |company|+ create(:company_location, company: company)+ end+ end+ end++ factory :company_location, class: Spree::CompanyLocation do+ company+ sequence(:name) { |n| "Branch #{n}" }+ end++ factory :company_contact, class: Spree::CompanyContact do+ company_location+ customer+ end+enddiff --git a/spree/core/spec/models/concerns/spree/purchase/company_spec.rb b/spree/core/spec/models/concerns/spree/purchase/company_spec.rbnew file mode 100644index 0000000000..8114a25acb--- /dev/null+++ b/spree/core/spec/models/concerns/spree/purchase/company_spec.rb@@ -0,0 +1,78 @@+require 'spec_helper'++RSpec.shared_examples 'a company host' do+ let(:store) { @default_store }+ let(:company) { create(:company, store: store) }+ let(:location) { create(:company_location, company: company) }++ describe '#resolved_company_location' do+ it 'prefers the branch named on the sale' do+ record.update!(company_location: location)++ expect(record.resolved_company_location).to eq(location)+ end++ context 'with no branch named' do+ it 'resolves the one branch the buyer acts for' do+ create(:company_contact, company_location: location, customer: record.customer)++ expect(record.reload.resolved_company_location).to eq(location)+ end++ # Guessing here would invoice one business for another's purchase.+ it 'refuses to choose when the buyer acts for several' do+ create(:company_contact, company_location: location, customer: record.customer)+ create(:company_contact, company_location: create(:company_location, company: company),+ customer: record.customer)++ expect(record.reload.resolved_company_location).to be_nil+ end++ it 'resolves nothing for a guest' do+ record.update!(customer: nil)++ expect(record.resolved_company_location).to be_nil+ end+ end+ end++ describe '#company' do+ it 'derives from the resolved branch' do+ record.update!(company_location: location)++ expect(record.company).to eq(company)+ end++ it 'is nil for a consumer sale' do+ expect(record.company).to be_nil+ end+ end++ describe '#b2b?' do+ it 'is true once a branch resolves' do+ record.update!(company_location: location)++ expect(record).to be_b2b+ end++ it 'is false otherwise' do+ expect(record).not_to be_b2b+ end+ end+end++RSpec.describe Spree::Purchase::Company do+ let(:customer) { create(:customer) }++ context 'included in Spree::Cart' do+ let(:record) { create(:cart, store: @default_store, customer: customer) }++ it_behaves_like 'a company host'+ end++ context 'included in Spree::Order' do+ let(:record) { create(:order, store: @default_store, customer: customer) }++ it_behaves_like 'a company host'+ end+enddiff --git a/spree/core/spec/models/spree/company_contact_spec.rb b/spree/core/spec/models/spree/company_contact_spec.rbnew file mode 100644index 0000000000..2df0765b8a--- /dev/null+++ b/spree/core/spec/models/spree/company_contact_spec.rb@@ -0,0 +1,45 @@+require 'spec_helper'++describe Spree::CompanyContact, type: :model do+ let(:store) { @default_store }+ let(:company) { create(:company, store: store) }+ let(:location) { create(:company_location, company: company) }++ it 'reaches the company and store through its location' do+ contact = create(:company_contact, company_location: location)++ expect(contact.company).to eq(company)+ expect(contact.store).to eq(store)+ end++ it 'defaults the role to buyer' do+ expect(create(:company_contact, company_location: location).role).to eq('buyer')+ end++ it 'allows one contact per customer per location' do+ customer = create(:customer)+ create(:company_contact, company_location: location, customer: customer)++ duplicate = build(:company_contact, company_location: location, customer: customer)++ expect(duplicate).not_to be_valid+ end++ # A buyer purchasing for two branches is the case that makes selection+ # ambiguous — see the provisional resolution in Spree::Purchase::Company.+ it 'allows the same customer at several locations' do+ customer = create(:customer)+ create(:company_contact, company_location: location, customer: customer)+ other = create(:company_location, company: company)++ expect(build(:company_contact, company_location: other, customer: customer)).to be_valid+ end++ it 'is reachable from the customer' do+ customer = create(:customer)+ contact = create(:company_contact, company_location: location, customer: customer)++ expect(customer.company_contacts).to eq([contact])+ expect(customer.company_locations).to eq([location])+ end+enddiff --git a/spree/core/spec/models/spree/company_location_spec.rb b/spree/core/spec/models/spree/company_location_spec.rbnew file mode 100644index 0000000000..b567c51e79--- /dev/null+++ b/spree/core/spec/models/spree/company_location_spec.rb@@ -0,0 +1,47 @@+require 'spec_helper'++describe Spree::CompanyLocation, type: :model do+ let(:store) { @default_store }+ let(:company) { create(:company, store: store) }++ it 'reaches the store through its company' do+ location = create(:company_location, company: company)++ expect(location.store).to eq(store)+ expect(location.store_id).to eq(store.id)+ end++ describe 'addresses' do+ it 'creates them inline from nested attributes' do+ location = create(:company_location, company: company,+ billing_address_attributes: build(:address).attributes.except('id', 'created_at', 'updated_at'))++ expect(location.billing_address).to be_present+ end++ # The branch owns its address rows, so nothing is left behind and nothing+ # shared is taken away.+ it 'destroys its own address rows with it' do+ location = create(:company_location, company: company,+ billing_address: create(:address),+ shipping_address: create(:address))++ expect { location.destroy }.to change(Spree::Address, :count).by(-2)+ end+ end++ it 'destroys its contacts' do+ location = create(:company_location, company: company)+ create(:company_contact, company_location: location)++ expect { location.destroy }.to change(Spree::CompanyContact, :count).by(-1)+ end++ it 'exposes the customers who buy for it' do+ location = create(:company_location, company: company)+ customer = create(:customer)+ create(:company_contact, company_location: location, customer: customer)++ expect(location.customers).to eq([customer])+ end+enddiff --git a/spree/core/spec/models/spree/company_spec.rb b/spree/core/spec/models/spree/company_spec.rbnew file mode 100644index 0000000000..f085c8aa56--- /dev/null+++ b/spree/core/spec/models/spree/company_spec.rb@@ -0,0 +1,70 @@+require 'spec_helper'++describe Spree::Company, type: :model do+ let(:store) { @default_store }++ describe 'store binding' do+ it 'refuses to move between stores once saved' do+ company = create(:company, store: store)++ company.store = create(:store)++ expect(company).not_to be_valid+ end++ it 'is reachable through the store' do+ company = create(:company, store: store)++ expect(store.companies).to include(company)+ expect(Spree::Company.for_store(store)).to include(company)+ end+ end++ describe 'external_id' do+ it 'is unique per store' do+ create(:company, store: store, external_id: 'ACME')++ expect(build(:company, store: store, external_id: 'ACME')).not_to be_valid+ end++ it 'allows the same reference in another store' do+ create(:company, store: store, external_id: 'ACME')++ expect(build(:company, store: create(:store), external_id: 'ACME')).to be_valid+ end++ it 'lets several companies carry no reference' do+ create(:company, store: store, external_id: nil)++ expect(build(:company, store: store, external_id: nil)).to be_valid+ end+ end++ describe 'contacts' do+ it 'collects the contacts of every location' do+ company = create(:company, store: store)+ first = create(:company_contact, company_location: create(:company_location, company: company))+ second = create(:company_contact, company_location: create(:company_location, company: company))++ expect(company.company_contacts).to contain_exactly(first, second)+ end+ end++ describe 'metadata' do+ # Spree::Metadata would shadow the real column with a virtual+ # private_metadata and lose the write — see docs/plans/decisions.md.+ it 'persists to the single metadata column' do+ company = create(:company, store: store, metadata: { 'erp_ref' => 'X-1' })++ expect(company.reload.metadata['erp_ref']).to eq('X-1')+ end+ end++ it 'destroys its locations and their contacts' do+ company = create(:company, store: store)+ create(:company_contact, company_location: create(:company_location, company: company))++ expect { company.destroy }.to change(Spree::CompanyLocation, :count).by(-1).+ and change(Spree::CompanyContact, :count).by(-1)+ end+enddiff --git a/spree/core/spec/workflows/spree/carts/complete_spec.rb b/spree/core/spec/workflows/spree/carts/complete_spec.rbindex 1758b3c12a..17e52f050a 100644--- a/spree/core/spec/workflows/spree/carts/complete_spec.rb+++ b/spree/core/spec/workflows/spree/carts/complete_spec.rb@@ -97,6 +97,37 @@ module Spreeendend+ describe 'business customer' do+ let(:customer) { create(:customer) }+ let(:company) { create(:company, store: store) }+ let(:location) { create(:company_location, company: company) }++ before { ready_cart.update!(customer: customer) }++ # Without this the exemption applies during checkout and vanishes from the+ # placed order, so commit and refund work from different facts.+ it 'carries the branch onto the order' do+ ready_cart.update!(company_location: location)++ order = described_class.call(cart: ready_cart).value++ expect(order.company_location).to eq(location)+ expect(order.company).to eq(company)+ end++ it 'carries a branch the buyer resolved to without naming it' do+ create(:company_contact, company_location: location, customer: customer)++ order = described_class.call(cart: ready_cart.reload).value++ expect(order.company_location).to eq(location)+ end++ it 'leaves a consumer order with no branch' do+ expect(described_class.call(cart: ready_cart).value.company_location).to be_nil+ end+ end+describe 'tax identifier snapshot' dolet(:customer) { create(:user) }