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.

Give the tax identifier one polymorphic owner

Damian Legawieced54736b9ffd
diff --git a/docs/plans/6.0-multi-vendor-marketplace.md b/docs/plans/6.0-multi-vendor-marketplace.md
index 131c1c6cf9..b1111849fa 100644
--- a/docs/plans/6.0-multi-vendor-marketplace.md
+++ b/docs/plans/6.0-multi-vendor-marketplace.md
@@ -237,11 +237,11 @@ Two things about `StockLocation` have to move for this to be true, and neither i
**Billing is a business identity, and most of it is not an address.** A commission invoice needs the seller's legal name, their registration number and — for EU B2B reverse charge on the fee (Decision 3) — a *verified* VAT number with the evidence retained, because a registry only ever answers "valid now" while an invoice must stay defensible for years. A `vat_number` string cannot carry a verdict, a timestamp or evidence.
-Core already models exactly this. `Spree::TaxIdentifier` (from `6.0-tax-provider.md` Phase 7) has `kind` / `value` / `validation_status` / `validated_at` / `validation_evidence` and a validator registry, with four owners. **The seller becomes the fifth owner** — one FK and one line in `exactly_one_owner`, and seller VAT inherits validation for free. `legal_name` and `registration_number` go on `spree_sellers`; `billing_address` stays a plain `Spree::Address` and means only where post goes.
+Core already models exactly this. `Spree::TaxIdentifier` (from `6.0-tax-provider.md` Phase 7) has `kind` / `value` / `validation_status` / `validated_at` / `validation_evidence` and a validator registry. **The seller becomes another owner** — and, since a fifth owner is what showed the per-owner-FK shape had outlived its rationale, the owner became polymorphic in the same pass (decisions.md 2026-08-22), so the seller costs no column at all and seller VAT inherits validation for free. `legal_name` and `registration_number` go on `spree_sellers`; `billing_address` is a `Spree::BusinessAddress`.
**No per-seller tax rate.** Adding one is the legacy `platform_fee_tax_rate` column this plan already rejected (Resolved Decisions, 2026-06-16): the seller supplies tax *identity*, and the commission tax *rate* resolves through `CommissionRate` + the `TaxProvider` so it stays jurisdiction-correct.
-**No `Address` STI subclasses.** The legacy module subclassed `BillingAddress`/`ReturnsAddress` to override `require_name?` (a company address has no first and last name) and `show_company_address_field?`. Both hooks still exist on `Spree::Address`, but `spree_addresses` has no `type` column, so STI would mean a schema change to the table every order, customer and company writes to — to encode a fact the owning FK already states. The seller declares the rules for the addresses it owns instead: company required, personal name waived. Whether the company *field* is shown is a form concern, and the form is React.
+**One `Address` subclass, sharing the table.** The legacy module subclassed `BillingAddress`/`ReturnsAddress` to override `require_name?` (a company address has no first and last name) and `show_company_address_field?`. Returns no longer need an address subclass at all — they route to a stock location — so only the billing half survives, as `Spree::BusinessAddress`. It is **not** STI: `spree_addresses` has no `type` column and gains none, because that would mean altering the table every order, customer and company writes to in order to encode a fact the owning association already states. The subclass reads the same rows and overrides the three predicates (`require_name?` false, `require_company?` true, `show_company_address_field?` true), which is where those rules belong — the alternative tried first was a `before_validation` flag on the seller, and a validation rule that has to be switched on per record is a class.
**Supersedes** the `belongs_to :returns_address` line in the Seller model sketch below, and the `Spree::SellerRequirements::ReturnsAddress` checklist kind becomes "has a returns location".
@@ -269,7 +269,7 @@ class Spree::Seller < Spree.base_class
has_many :products, class_name: 'Spree::Product', dependent: :nullify
has_many :stock_locations, class_name: 'Spree::StockLocation', dependent: :nullify
- has_many :tax_identifiers, class_name: 'Spree::TaxIdentifier', dependent: :destroy # VAT etc — Decision 12
+ has_many :tax_identifiers, class_name: 'Spree::TaxIdentifier', as: :owner # VAT etc — Decision 12
has_many :orders, class_name: 'Spree::Order' # child (seller) orders
has_many :commission_lines, class_name: 'Spree::CommissionLine'
has_many :seller_transfers, class_name: 'Spree::SellerTransfer'
@@ -743,7 +743,7 @@ Even before this lands, work touching adjacent areas should:
- **Tax provider (`6.0-tax-provider.md`)** and **Delivery rate provider (`6.0-delivery-rate-provider.md`)**: the `PayoutProvider` follows the same pluggable-strategy shape — keep the provider-registration convention consistent so all three (tax, delivery rate, payout) register and resolve the same way.
- **Admin API (`6.0-admin-api.md`)**: the `Seller` prefix is `sel_`. The "Marketplace (new in 6.0)" endpoint group there is the *operator's* API surface — keep it in sync. Seller users never call the Admin API (Decision 10).
- **Auth + RBAC (`6.0-platform-auth.md`, `6.0-admin-rbac.md`)**: no third principal — never add a `SellerUser`/`Spree.seller_user_class`; seller staff are `Spree.admin_user_class`. Never derive back-office membership from `store_id` alone — match `RoleUser.resource_type` (`Ability#staff_roles` and `RoleGrantGuard` already do; the membership check must follow). New login surfaces get their own strategy registry and JWT audience; refresh tokens must carry the audience they were minted for. Catalog resources that sellers may hold must be marked seller-grantable at `register_resource`; `settings`/`staff`/`api_keys` never are. Seller-branch controllers scope-fetch through `current_seller` and never subclass admin controllers.
-- **Seller addresses (Decision 12)**: do not add a `returns_address` back, and do not give a seller a tax *rate* column — identity (`legal_name`, `registration_number`, a `TaxIdentifier`) is the seller's, the rate is `CommissionRate` + `TaxProvider`. Do not subclass `Spree::Address`. Code reading a seller's returns destination goes through `Seller#returns_location`, never a stored address FK. `StockLocation` name-uniqueness and its `default` flag are per-owner, so new code must not assume one default per store.
+- **Seller addresses (Decision 12)**: do not add a `returns_address` back, and do not give a seller a tax *rate* column — identity (`legal_name`, `registration_number`, a `TaxIdentifier`) is the seller's, the rate is `CommissionRate` + `TaxProvider`. A billing address is a `Spree::BusinessAddress` (table-sharing subclass, never STI — `spree_addresses` gains no `type` column). Code reading a seller's returns destination goes through `Seller#returns_location`, never a stored address FK. `StockLocation` name-uniqueness and its `default` flag are per-owner, so new code must not assume one default per store.
- Do **not** revive the legacy commission model's shape (label-based rows + denormalized fee totals on the order), do **not** model commission as a polymorphic `Adjustment`, and do **not** write commission as a `Spree::Fee` (fees are buyer-facing and roll into order totals — Decision 2) — 6.0 uses the off-order `Spree::CommissionLine` ledger. Do **not** put the fund ledger in a payment-gateway namespace (the legacy gateway-namespaced-transfer mistake) nor collapse transfer and payout into one model — `Spree::SellerTransfer` (on-fulfillment) and `Spree::SellerPayout` (scheduled) are both core and provider-agnostic.
## Resolved Decisions
@@ -794,7 +794,7 @@ Even before this lands, work touching adjacent areas should:
- **Fund ledger → two levels: `Spree::SellerTransfer` (per-order, on-fulfillment) + `Spree::SellerPayout` (per-interval settlement), both generic in core + pluggable `PayoutProvider` (system no-op in core; basic StripeConnect with the monorepo Stripe gateway per the 2026-07-15 amendment, extended by Enterprise with the money operations)** (RESOLVED 2026-06-25). See Decision 9. Transfer credits the seller balance on fulfillment; payout sweeps unsettled transfers into a scheduled bank settlement (transfers `belong_to` their payout — auditable). `seller.balance(currency) = Σ completed transfers − Σ completed payouts` per currency. Splits the legacy gateway-namespaced transfer ledger (which conflated the two and outsourced settlement to Stripe) into core ledger + provider execution along the OSS/Enterprise seam.
- **Commission tax → one scalar on the line, in TaxLine's vocabulary** (RESOLVED 2026-08-17). `tax_amount` + `tax_rate` + `taxability_reason` + the seller's `country_code`/`state_code` on `Spree::CommissionLine`, with `Spree::CommissionTax` as the value object the resolver returns. Reusing `Spree::TaxLine` itself was rejected: its rows sum into the order total and are exposed on the buyer-facing `/orders/:id/tax_lines`, so a commission row there would overcharge the shopper and leak settlement data. Same shape, opposite side of the ledger — so the words are shared and the rows are not. See Decision 3.
- **Commission VAT base → net item price, VAT added on top of the fee** (RESOLVED 2026-06-25). For EU, commission is computed on the seller's **net (ex-VAT)** item price; the commission `tax_amount` (Decision 3) is then applied **on top of the commission** as a separate B2B service supply — the marketplace fee is a distinct taxable event from the consumer's item sale, so the two VATs never mix. The base toggle stays available for non-EU/edge merchants who genuinely want a gross base, but the EU default is net-base + fee-VAT. Shipped as **`tax_inclusive`** (2026-08-17), matching `Spree::Market#tax_inclusive` rather than the surveyed industry's `include_tax` — the flag says the commission base is tax-inclusive, which is the same adjective the rest of Spree already uses for a price that carries its tax. This makes the marketplace's commission invoice to the seller stand on its own (correct for EU invoicing + remittance).
-- **Seller addresses → a stock location + a business identity** (RESOLVED 2026-08-20). `returns_address` is dropped: returns route to a seller-owned `StockLocation` (default provisioned at creation) so received goods restock where the catalog can see them, which also requires `StockLocation` name-uniqueness and the `default` flag to become per-owner rather than per-store. Billing keeps a plain `Spree::Address`, while the parts that are not an address become `legal_name` + `registration_number` on the seller and a `Spree::TaxIdentifier` owned by it — reusing the validation/evidence rails the tax plan already built, because EU reverse charge on the commission invoice needs a verified number with retained evidence. No per-seller tax rate (that stays `CommissionRate` + `TaxProvider`) and no `Address` STI subclasses (the owning FK already says which address it is; `spree_addresses` has no `type` column). See Decision 12.
+- **Seller addresses → a stock location + a business identity** (RESOLVED 2026-08-20). `returns_address` is dropped: returns route to a seller-owned `StockLocation` (default provisioned at creation) so received goods restock where the catalog can see them, which also requires `StockLocation` name-uniqueness and the `default` flag to become per-owner rather than per-store. Billing becomes a `Spree::BusinessAddress`, while the parts that are not an address at all become `legal_name` + `registration_number` on the seller and a `Spree::TaxIdentifier` owned by it — reusing the validation/evidence rails the tax plan already built, because EU reverse charge on the commission invoice needs a verified number with retained evidence. No per-seller tax rate (that stays `CommissionRate` + `TaxProvider`) and no `Address` **STI** — `Spree::BusinessAddress` shares `spree_addresses` and the table gains no `type` column. See Decision 12.
- **Store-credit/gift-card payout → payment-source-agnostic** (RESOLVED 2026-06-25). The `SellerTransfer` amount (which rolls up into the payout) is `(seller's sale value) − (commission owed)`, **independent of how the customer paid**. Store credit / gift cards are the platform's funding concern, not the seller's — the seller is owed their full cut of the sale regardless. This **drops the legacy store-credit dual-basis** from the amount calculation; that branch existed only to reconcile the old store-credit funding model and does not belong in the payout basis. (The platform still tracks its own store-credit liability separately — that's orthogonal to what the seller receives.)
- **Commission precedence → an operator-ordered list** (RESOLVED 2026-06-25 as integer priority; **reshaped 2026-08-17 to `acts_as_list`, shipped**). `CommissionRate` carries `position` (`acts_as_list scope: :store_id, add_new_at: :top`) and resolution walks it top-down, first match wins (Decision 4). The list on screen is the precedence, so reordering is dragging rather than assigning numbers; new rates land at the top so they take effect on creation instead of behind the catch-all. `Spree::Seeds::CommissionRates` puts one disabled marketplace-wide rate at the bottom, which yields the product > category > seller order merchants asked for without hardcoding a ladder. No specificity inference — a rate can name all three dimensions at once, so there is nothing to infer from.
- **Commission rate currency → required for fixed, ignored for percentage** (RESOLVED 2026-06-25). A `kind: 'fixed'` rate **must** carry a `currency` (a flat "2" is meaningless without one); a `kind: 'percentage'` rate ignores currency (10% applies in any currency). Enforced by a model validation: `validates :currency, presence: true, if: -> { kind == 'fixed' }`. See the `CommissionRate` model.
diff --git a/docs/plans/6.0-tax-provider.md b/docs/plans/6.0-tax-provider.md
index 414a95370e..f50a649304 100644
--- a/docs/plans/6.0-tax-provider.md
+++ b/docs/plans/6.0-tax-provider.md
@@ -209,19 +209,37 @@ Both fields are written by every provider, and both are covered by the write con
### Buyer tax identity: `Spree::TaxIdentifier`
+> **The owner is polymorphic, not a column per owner (RESOLVED 2026-08-22).** The
+> original design used the dual-FK convention borrowed from the Cart/Order split.
+> That convention exists for a specific reason — split-adjustments and typed stock
+> movements were removing `adjustable_type`/`originator_type`, where one table
+> meant six different things and a dozen methods dispatched on the type string.
+> `TaxIdentifier` is not that case: it is **one** concept (a tax registration)
+> with several owners, which is what polymorphic modelling is for. With a fifth
+> owner arriving (Seller), five nullable FKs plus an `exactly_one_owner`
+> validator were expressing "has an owner" the long way round. So the table
+> carries `owner_type`/`owner_id`, the exactly-one rule becomes structural, the
+> three per-owner uniqueness validations collapse to one
+> `scope: [:owner_type, :owner_id]`, and a sixth owner costs no schema change.
+> Cardinality still differs by owner and is declared owner-side as it always was
+> (`has_many` for customer/company/seller, `has_one` for cart/order). The admin
+> serializer keeps exposing `customer_id`/`cart_id`/`order_id` — reading the
+> owner and reporting it under the name of what it is — so no client changes.
+
Survey verdict (Magento, Stripe, commercetools, Shopify, Odoo, Medusa/Saleor): column designs either forgo typed multiplicity (Magento, Odoo), forgo validation evidence (commercetools, Shopify), or impose nullable tax columns on every consumer row (Magento — 5–7 per address). Live-read designs (Shopify B2B, Odoo) have documented drift pain: historical documents resolve to the *current* registration. Stripe — the only system designed for the tax-document problem — uses a separate typed `tax_id` object on the customer plus a `{type, value}` snapshot frozen onto the finalized invoice. Spree adopts Stripe's shape with Magento's evidence discipline:
```ruby
class Spree::TaxIdentifier < Spree.base_class
has_prefix_id :txi
- # Owner — exactly one (dual-FK convention, never polymorphic):
- belongs_to :customer, class_name: 'Spree::Customer', optional: true # durable profile value
- belongs_to :cart, class_name: 'Spree::Cart', optional: true # checkout-time override
- belongs_to :order, class_name: 'Spree::Order', optional: true # frozen completion snapshot
- # + company_id in Phase 7 — the entity's durable registration, sitting above
- # the customer's own row in the chain. Per-branch registrations stay a 6.1
- # question (Shopify's CompanyLocation.taxRegistrationId precedent).
+ # Owner — polymorphic (decision 2026-08-22, below):
+ belongs_to :owner, polymorphic: true, optional: false
+ # Customer (durable profile value), Company (the entity's registration,
+ # sitting above the customer's own row in the chain), Seller (the
+ # marketplace's commission invoice — see 6.0-multi-vendor-marketplace.md
+ # Decision 12), Cart (checkout-time override), Order (frozen completion
+ # snapshot). Per-branch registrations stay a 6.1 question (Shopify's
+ # CompanyLocation.taxRegistrationId precedent).
# kind: 'eu_vat', 'gb_vat', 'au_abn', … (Stripe's typed-kind model)
# value: the registration number
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index 587caed85c..975559ac8a 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -1,3 +1,13 @@
+## 2026-08-22: The tax identifier's owner is polymorphic
+
+**Context:** `Spree::TaxIdentifier` carried one nullable FK per owner — customer, company, cart, order — with an `exactly_one_owner` validator holding the rule together, following the dual-FK convention from the Cart/Order split. The marketplace work added a fifth owner (Seller, per `6.0-multi-vendor-marketplace.md` Decision 12), which made the shape hard to defend: five columns, three near-identical per-owner uniqueness validations, and an `owner` method that was a five-way `||` chain.
+
+**Decision:** The table carries `owner_type`/`owner_id`. The dual-FK convention was adopted for cases where a polymorphic type string was hiding several different meanings in one table — split-adjustments removing `adjustable_type`, typed stock movements removing `originator_type`, each with methods dispatching on the string to tell six things apart. A tax identifier is not that: it is one concept, a tax registration, held by different kinds of party. The exactly-one rule becomes structural (a single FK cannot name two owners, and `optional: false` is explicit because `Spree::Base` turns off `belongs_to_required_by_default`), the three uniqueness validations collapse into `scope: [:owner_type, :owner_id]`, and a sixth owner costs no migration. Cardinality still varies by owner and is declared owner-side, where it always lived: `has_many` for customer, company and seller, `has_one` for cart and order. Because 6.0 is unreleased, the original `create_table` migration was amended in place rather than layering a conversion migration.
+
+**Rejected:** keeping five FKs on consistency grounds alone (the convention's rationale does not reach this table); a shared `exactly_one_owner` concern (it would formalise the workaround rather than remove it).
+
+**Consequences:** the admin serializer keeps exposing `customer_id`/`cart_id`/`order_id`, deriving them from the owner and reporting each under the name of what it is, so no client changes. `readonly?`, `validatable?` and `number_changing?` — all three meaning "this is the frozen order snapshot" — read one private `order_owned?` predicate instead of `order_id`. The completion copy and the seller split drop `owner_type`/`owner_id` from their `except` lists rather than naming four dead columns. The `errors.messages.exactly_one_tax_identifier_owner` translation is deleted. Specs pass owners as `owner:`, and the factory gains `:on_company`/`:on_seller` traits beside the existing ones.
+
## 2026-08-19: A payment settling refreshes the payment side only, through events
**Context:** `Payment#update_order` (an `after_save` callback) wrote `payment_total` with `update_column` and called `update_statuses!` inline, while `Carts::RecalculateTotals` carried the identical formula and `OrderStatusSubscriber` was already designated the sole status trigger. Measured with events enabled: one capture recomputed the order **four times** (callback + `payment.updated` + `payment.completed` + `payment.captured`). None of it was visible to the suite, because `Spree::Events.enabled?` is false in the test environment — the callback was doing all the work there, so nothing failed.
diff --git a/spree/api/app/serializers/spree/api/v3/admin/tax_identifier_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/tax_identifier_serializer.rb
index 14cbe23211..b94c283384 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/tax_identifier_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/tax_identifier_serializer.rb
@@ -22,16 +22,19 @@ module Spree
tax_identifier.validatable?
end
+ # The owner, reported under the name of what it is, so a client can
+ # tell a customer's durable registration from a cart override or an
+ # order's snapshot without reading a type string.
attribute :customer_id do |tax_identifier|
- tax_identifier.customer&.prefixed_id
+ tax_identifier.owner&.prefixed_id if tax_identifier.owner.is_a?(Spree.customer_class)
end
attribute :cart_id do |tax_identifier|
- tax_identifier.cart&.prefixed_id
+ tax_identifier.owner&.prefixed_id if tax_identifier.owner.is_a?(Spree::Cart)
end
attribute :order_id do |tax_identifier|
- tax_identifier.order&.prefixed_id
+ tax_identifier.owner&.prefixed_id if tax_identifier.owner.is_a?(Spree::Order)
end
end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/companies/tax_identifiers_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/companies/tax_identifiers_controller_spec.rb
index e84279b6b3..e7ca8f8f76 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/companies/tax_identifiers_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/companies/tax_identifiers_controller_spec.rb
@@ -11,7 +11,7 @@ RSpec.describe Spree::Api::V3::Admin::Companies::TaxIdentifiersController, type:
describe 'GET #index' do
it 'lists the business registrations' do
- create(:tax_identifier, customer: nil, company: company, kind: 'eu_vat', value: 'DE123456789')
+ create(:tax_identifier, owner: company, kind: 'eu_vat', value: 'DE123456789')
get :index, params: { company_id: company.prefixed_id }, as: :json
@@ -41,17 +41,17 @@ RSpec.describe Spree::Api::V3::Admin::Companies::TaxIdentifiersController, type:
end
it 'takes effect on a sale for that business' do
- create(:tax_identifier, customer: nil, company: company, kind: 'eu_vat', value: 'DE222222222')
+ create(:tax_identifier, owner: company, kind: 'eu_vat', value: 'DE222222222')
location = create(:company_location, company: company)
customer = create(:customer)
- create(:tax_identifier, customer: customer, kind: 'eu_vat', value: 'DE111111111')
+ create(:tax_identifier, owner: customer, kind: 'eu_vat', value: 'DE111111111')
cart = create(:cart, store: store, customer: customer, company_location: location)
expect(cart.resolved_tax_identifier.value).to eq('DE222222222')
end
it 'holds one registration per kind' do
- create(:tax_identifier, customer: nil, company: company, kind: 'eu_vat', value: 'DE123456789')
+ create(:tax_identifier, owner: company, kind: 'eu_vat', value: 'DE123456789')
post :create, params: { company_id: company.prefixed_id, kind: 'eu_vat', value: 'DE999999999' }, as: :json
@@ -83,7 +83,7 @@ RSpec.describe Spree::Api::V3::Admin::Companies::TaxIdentifiersController, type:
describe 'PATCH #update' do
it 'corrects the number' do
- identifier = create(:tax_identifier, customer: nil, company: company, kind: 'eu_vat', value: 'DE123456789')
+ identifier = create(:tax_identifier, owner: company, kind: 'eu_vat', value: 'DE123456789')
patch :update, params: { company_id: company.prefixed_id, id: identifier.prefixed_id, value: 'DE987654321' }, as: :json
@@ -94,7 +94,7 @@ RSpec.describe Spree::Api::V3::Admin::Companies::TaxIdentifiersController, type:
describe 'DELETE #destroy' do
it 'removes the registration' do
- identifier = create(:tax_identifier, customer: nil, company: company, kind: 'eu_vat')
+ identifier = create(:tax_identifier, owner: company, kind: 'eu_vat')
delete :destroy, params: { company_id: company.prefixed_id, id: identifier.prefixed_id }, as: :json
@@ -105,7 +105,7 @@ RSpec.describe Spree::Api::V3::Admin::Companies::TaxIdentifiersController, type:
describe 'POST #validate' do
it 'reports when no validator is installed for the kind' do
- identifier = create(:tax_identifier, customer: nil, company: company, kind: 'eu_vat')
+ identifier = create(:tax_identifier, owner: company, kind: 'eu_vat')
post :validate, params: { company_id: company.prefixed_id, id: identifier.prefixed_id }, as: :json
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/customers/tax_identifiers_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/customers/tax_identifiers_controller_spec.rb
index 4a12c181d0..bbd5f35cb7 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/customers/tax_identifiers_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/customers/tax_identifiers_controller_spec.rb
@@ -6,7 +6,7 @@ RSpec.describe Spree::Api::V3::Admin::Customers::TaxIdentifiersController, type:
include_context 'API v3 Admin authenticated'
let!(:customer) { create(:user) }
- let!(:tax_identifier) { create(:tax_identifier, :verified, customer: customer, kind: 'eu_vat', value: 'DE123456789') }
+ let!(:tax_identifier) { create(:tax_identifier, :verified, owner: customer, kind: 'eu_vat', value: 'DE123456789') }
before { request.headers.merge!(headers) }
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/orders/tax_identifiers_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/orders/tax_identifiers_controller_spec.rb
index a6bfbae317..577ae91a07 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/orders/tax_identifiers_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/orders/tax_identifiers_controller_spec.rb
@@ -11,7 +11,7 @@ RSpec.describe Spree::Api::V3::Admin::Orders::TaxIdentifiersController, type: :c
describe 'GET #show' do
it 'returns the snapshot with the verdict and the evidence behind it' do
- create(:tax_identifier, :on_order, :verified, order: order, kind: 'eu_vat', value: 'DE123456789')
+ create(:tax_identifier, :on_order, :verified, owner: order, kind: 'eu_vat', value: 'DE123456789')
get :show, params: { order_id: order.prefixed_id }, as: :json
@@ -33,7 +33,7 @@ RSpec.describe Spree::Api::V3::Admin::Orders::TaxIdentifiersController, type: :c
it '404s on an order from another store' do
other_order = create(:completed_order_with_totals, store: create(:store))
- create(:tax_identifier, :on_order, order: other_order)
+ create(:tax_identifier, :on_order, owner: other_order)
get :show, params: { order_id: other_order.prefixed_id }, as: :json
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
index 400cb6095f..733739ef23 100644
--- 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
@@ -5,8 +5,8 @@ RSpec.describe Spree::Api::V3::Store::Customer::TaxIdentifiersController, type:
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') }
+ let!(:eu) { create(:tax_identifier, owner: user, kind: 'eu_vat', value: 'DE123456789') }
+ let!(:gb) { create(:tax_identifier, owner: user, kind: 'gb_vat', value: 'GB123456789') }
before do
request.headers['X-Spree-Api-Key'] = api_key.token
@@ -25,7 +25,7 @@ RSpec.describe Spree::Api::V3::Store::Customer::TaxIdentifiersController, type:
end
it 'lists nobody else\'s' do
- create(:tax_identifier, customer: create(:user), kind: 'eu_vat', value: 'FR999999999')
+ create(:tax_identifier, owner: create(:user), kind: 'eu_vat', value: 'FR999999999')
get :index
@@ -33,7 +33,7 @@ RSpec.describe Spree::Api::V3::Store::Customer::TaxIdentifiersController, type:
end
it 'returns an empty list for a buyer with none' do
- Spree::TaxIdentifier.where(customer_id: user.id).destroy_all
+ user.tax_identifiers.destroy_all
get :index
diff --git a/spree/api/spec/integration/spree/api/v3/admin/companies/tax_identifiers_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/companies/tax_identifiers_spec.rb
index 83619d9a31..e9ddc6f0fa 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/companies/tax_identifiers_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/companies/tax_identifiers_spec.rb
@@ -8,7 +8,7 @@ RSpec.describe 'Admin Company Tax Identifiers API', type: :request, swagger_doc:
let(:Authorization) { "Bearer #{admin_jwt_token}" }
let!(:company) { create(:company, store: store) }
let!(:tax_identifier) do
- create(:tax_identifier, customer: nil, company: company, kind: 'eu_vat', value: 'DE123456789')
+ create(:tax_identifier, owner: company, kind: 'eu_vat', value: 'DE123456789')
end
path '/api/v3/admin/companies/{company_id}/tax_identifiers' do
diff --git a/spree/api/spec/requests/spree/api/v3/store/tax_identifiers_spec.rb b/spree/api/spec/requests/spree/api/v3/store/tax_identifiers_spec.rb
index 7f10f66a6d..fbe3d25498 100644
--- a/spree/api/spec/requests/spree/api/v3/store/tax_identifiers_spec.rb
+++ b/spree/api/spec/requests/spree/api/v3/store/tax_identifiers_spec.rb
@@ -36,8 +36,8 @@ RSpec.describe 'Store tax identifiers', type: :request do
# be told which one. Guessing meant a DELETE removed whichever row came back
# first — not the buyer's choice, and not predictable.
it 'refuses to guess which registration was meant' do
- create(:tax_identifier, customer: user, kind: 'eu_vat', value: 'DE123456789')
- create(:tax_identifier, customer: user, kind: 'gb_vat', value: 'GB123456789')
+ create(:tax_identifier, owner: user, kind: 'eu_vat', value: 'DE123456789')
+ create(:tax_identifier, owner: user, kind: 'gb_vat', value: 'GB123456789')
delete '/api/v3/store/customers/me/tax_identifier', headers: headers, as: :json
@@ -51,7 +51,7 @@ RSpec.describe 'Store tax identifiers', type: :request do
let(:cart) { create(:cart_with_line_items, line_items_count: 1, store: store, customer: user) }
it 'reads the customer registration when the cart has no override' do
- create(:tax_identifier, customer: user, kind: 'eu_vat', value: 'DE123456789')
+ create(:tax_identifier, owner: user, kind: 'eu_vat', value: 'DE123456789')
get "/api/v3/store/carts/#{cart.prefixed_id}/tax_identifier",
headers: headers.merge('x-spree-token' => cart.token), as: :json
@@ -62,8 +62,8 @@ RSpec.describe 'Store tax identifiers', type: :request do
end
it 'prefers the cart override over the customer registration' do
- create(:tax_identifier, customer: user, kind: 'eu_vat', value: 'DE123456789')
- create(:tax_identifier, customer: nil, cart: cart, kind: 'eu_vat', value: 'DE999999999')
+ create(:tax_identifier, owner: user, kind: 'eu_vat', value: 'DE123456789')
+ create(:tax_identifier, owner: cart, kind: 'eu_vat', value: 'DE999999999')
get "/api/v3/store/carts/#{cart.prefixed_id}/tax_identifier",
headers: headers.merge('x-spree-token' => cart.token), as: :json
@@ -72,8 +72,8 @@ RSpec.describe 'Store tax identifiers', type: :request do
end
it 'clears only the override, leaving the customer registration alone' do
- profile = create(:tax_identifier, customer: user, kind: 'eu_vat', value: 'DE123456789')
- create(:tax_identifier, customer: nil, cart: cart, kind: 'eu_vat', value: 'DE999999999')
+ profile = create(:tax_identifier, owner: user, kind: 'eu_vat', value: 'DE123456789')
+ create(:tax_identifier, owner: cart, kind: 'eu_vat', value: 'DE999999999')
delete "/api/v3/store/carts/#{cart.prefixed_id}/tax_identifier",
headers: headers.merge('x-spree-token' => cart.token), as: :json
@@ -84,7 +84,7 @@ RSpec.describe 'Store tax identifiers', type: :request do
end
it 'has nothing of its own to delete when the registration is inherited' do
- create(:tax_identifier, customer: user, kind: 'eu_vat', value: 'DE123456789')
+ create(:tax_identifier, owner: user, kind: 'eu_vat', value: 'DE123456789')
delete "/api/v3/store/carts/#{cart.prefixed_id}/tax_identifier",
headers: headers.merge('x-spree-token' => cart.token), as: :json
@@ -97,7 +97,7 @@ RSpec.describe 'Store tax identifiers', type: :request do
# used to relabel the number already there under a regime it was not issued
# for.
it 'refuses to relabel the existing number under a new kind' do
- create(:tax_identifier, customer: nil, cart: cart, kind: 'eu_vat', value: 'DE999999999')
+ create(:tax_identifier, owner: cart, kind: 'eu_vat', value: 'DE999999999')
put "/api/v3/store/carts/#{cart.prefixed_id}/tax_identifier",
params: { kind: 'gb_vat' },
@@ -149,7 +149,7 @@ RSpec.describe 'Store tax identifiers', type: :request do
end
it 'happens when the override is cleared' do
- create(:tax_identifier, customer: nil, cart: cart, kind: 'eu_vat', value: 'DE999999999')
+ create(:tax_identifier, owner: cart, kind: 'eu_vat', value: 'DE999999999')
delete "/api/v3/store/carts/#{cart.prefixed_id}/tax_identifier",
headers: headers.merge('x-spree-token' => cart.token), as: :json
@@ -182,7 +182,7 @@ RSpec.describe 'Store tax identifiers', type: :request do
let(:order) { create(:completed_order_with_totals, store: store, customer: user) }
it 'is readable and cannot be written' do
- create(:tax_identifier, :on_order, order: order, value: 'DE111111111')
+ create(:tax_identifier, :on_order, owner: order, value: 'DE111111111')
get "/api/v3/store/orders/#{order.prefixed_id}/tax_identifier", headers: headers, as: :json
@@ -192,7 +192,7 @@ RSpec.describe 'Store tax identifiers', type: :request do
put "/api/v3/store/orders/#{order.prefixed_id}/tax_identifier",
params: { kind: 'eu_vat', value: 'DE222222222' }, headers: headers, as: :json
expect(response).to have_http_status(:not_found)
- expect(order.tax_identifier.reload.value).to eq('DE111111111')
+ expect(order.reload.tax_identifier.value).to eq('DE111111111')
end
end
end
diff --git a/spree/core/app/models/concerns/spree/customer_methods.rb b/spree/core/app/models/concerns/spree/customer_methods.rb
index e0c20d3efd..5733365625 100644
--- a/spree/core/app/models/concerns/spree/customer_methods.rb
+++ b/spree/core/app/models/concerns/spree/customer_methods.rb
@@ -69,8 +69,8 @@ module Spree
has_many :customer_groups, through: :customer_group_users, class_name: 'Spree::CustomerGroup'
has_many :identities, class_name: 'Spree::UserIdentity', as: :user, dependent: :destroy
# 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 :tax_identifiers, class_name: 'Spree::TaxIdentifier', as: :owner,
+ dependent: :destroy, inverse_of: :owner
has_many :company_contacts, class_name: 'Spree::CompanyContact', foreign_key: :customer_id,
dependent: :destroy, inverse_of: :customer
has_many :company_locations, through: :company_contacts
diff --git a/spree/core/app/models/spree/business_address.rb b/spree/core/app/models/spree/business_address.rb
index a5d5e6d6ca..bea06e8615 100644
--- a/spree/core/app/models/spree/business_address.rb
+++ b/spree/core/app/models/spree/business_address.rb
@@ -1,14 +1,9 @@
module Spree
- # An address belonging to a business rather than a person — a seller's
- # billing address, as a commission invoice must address it.
+ # A seller's billing address, as a commission invoice must address it: no
+ # person to name, and the company is the part that cannot be left out.
#
- # Shares `spree_addresses` with its parent rather than being STI: the table
- # has no `type` column, and adding one to reach every order, customer and
- # company row would be a heavy migration to record what the owning
- # association already says.
- #
- # What differs is who the address names. There is no person to ask for, and
- # the company is the part that cannot be left out.
+ # Shares `spree_addresses` rather than being STI — the table has no `type`
+ # column, and the owning association already says which kind this is.
class BusinessAddress < Spree::Address
def require_name?
false
diff --git a/spree/core/app/models/spree/cart.rb b/spree/core/app/models/spree/cart.rb
index 90b60fefed..72d0b1737d 100644
--- a/spree/core/app/models/spree/cart.rb
+++ b/spree/core/app/models/spree/cart.rb
@@ -73,7 +73,8 @@ module Spree
has_many :variants, through: :line_items
has_many :products, through: :variants
has_many :tax_lines, class_name: 'Spree::TaxLine', dependent: :destroy, inverse_of: :cart
- has_one :tax_identifier, class_name: 'Spree::TaxIdentifier', dependent: :destroy, inverse_of: :cart
+ has_one :tax_identifier, class_name: 'Spree::TaxIdentifier', as: :owner,
+ dependent: :destroy, inverse_of: :owner
has_many :discounts, class_name: 'Spree::Discount', dependent: :destroy, inverse_of: :cart
has_many :fees, class_name: 'Spree::Fee', dependent: :destroy, inverse_of: :cart
has_many :fulfillments, -> { order(:created_at, :id) }, class_name: 'Spree::Fulfillment', dependent: :destroy, inverse_of: :cart do
diff --git a/spree/core/app/models/spree/company.rb b/spree/core/app/models/spree/company.rb
index 564c84964e..30001b6fa2 100644
--- a/spree/core/app/models/spree/company.rb
+++ b/spree/core/app/models/spree/company.rb
@@ -22,8 +22,8 @@ module Spree
has_many :company_locations, class_name: 'Spree::CompanyLocation', dependent: :destroy,
inverse_of: :company
has_many :company_contacts, through: :company_locations
- has_many :tax_identifiers, class_name: 'Spree::TaxIdentifier', dependent: :destroy,
- inverse_of: :company
+ has_many :tax_identifiers, class_name: 'Spree::TaxIdentifier', as: :owner,
+ dependent: :destroy, inverse_of: :owner
has_many :tax_exemption_certificates, class_name: 'Spree::TaxExemptionCertificate',
dependent: :destroy, inverse_of: :company
diff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rb
index 6c4970c5d3..2ce404ebfe 100644
--- a/spree/core/app/models/spree/order.rb
+++ b/spree/core/app/models/spree/order.rb
@@ -190,7 +190,8 @@ module Spree
has_many :tax_lines, class_name: 'Spree::TaxLine', dependent: :destroy, inverse_of: :order
# delete, not destroy: the snapshot is readonly once written, and destroy
# refuses readonly records. It has no dependents of its own.
- has_one :tax_identifier, class_name: 'Spree::TaxIdentifier', dependent: :delete, inverse_of: :order
+ has_one :tax_identifier, class_name: 'Spree::TaxIdentifier', as: :owner,
+ dependent: :delete, inverse_of: :owner
has_many :discounts, class_name: 'Spree::Discount', dependent: :destroy, inverse_of: :order
has_many :fees, class_name: 'Spree::Fee', dependent: :destroy, inverse_of: :order
diff --git a/spree/core/app/models/spree/seller.rb b/spree/core/app/models/spree/seller.rb
index 56c64a3135..85b3f2be44 100644
--- a/spree/core/app/models/spree/seller.rb
+++ b/spree/core/app/models/spree/seller.rb
@@ -19,7 +19,7 @@ module Spree
include Spree::MemoizedData
include Spree::SanitizableRichText
- MEMOIZED_METHODS = %w[onboarding_requirements].freeze
+ MEMOIZED_METHODS = %w[onboarding_requirements onboarding_progress products_count returns_location].freeze
publishes_lifecycle_events
@@ -60,9 +60,11 @@ module Spree
# Associations
#
belongs_to :store, class_name: 'Spree::Store'
- # Not `dependent: :destroy`: a seller is paranoid, so destroy is a soft
- # delete, and taking the address with it would hard-delete a row the
- # seller's historical commission invoices still point at.
+ # Typed as the subclass so a saved address is read back with the business
+ # rules — otherwise editing one field of it would fail on a personal name
+ # nobody was ever asked for. Not `dependent: :destroy`: a seller is
+ # paranoid, so destroy is a soft delete, and taking the address with it
+ # would hard-delete a row historical commission invoices still point at.
belongs_to :billing_address, class_name: 'Spree::BusinessAddress', optional: true
# `update_only` edits the existing row rather than building a replacement
@@ -73,11 +75,19 @@ module Spree
# The API reads and writes this under one name, so the writer takes the
# attributes a client sends as well as a record. Never an id: an address
# carries no store of its own, so binding one by id would reach another
- # store's rows.
+ # store's rows. A plain Spree::Address is accepted too — the two share
+ # `spree_addresses` and differ only in which fields they insist on, so a
+ # valid row should not be refused over its Ruby class.
def billing_address=(value)
- return super unless value.is_a?(Hash) || value.is_a?(ActionController::Parameters)
-
- self.billing_address_attributes = value
+ case value
+ when Hash, ActionController::Parameters
+ super(Spree::BusinessAddress.new) if billing_address.nil?
+ self.billing_address_attributes = value
+ when Spree::Address
+ super(value.becomes(Spree::BusinessAddress))
+ else
+ super
+ end
end
# Where this seller keeps stock, and so where their returns land. Released
@@ -94,8 +104,8 @@ module Spree
# delete, while a TaxIdentifier is not — cascading would permanently
# erase the evidence behind commission invoices already issued, which is
# exactly what it exists to preserve.
- has_many :tax_identifiers, class_name: 'Spree::TaxIdentifier', dependent: nil,
- inverse_of: :seller
+ has_many :tax_identifiers, class_name: 'Spree::TaxIdentifier', as: :owner,
+ dependent: nil, inverse_of: :owner
# Products and stock survive the seller leaving: the operator decides what
# happens to a departed seller's catalog, so it is never cascade-deleted.
@@ -172,12 +182,10 @@ module Spree
#
# @return [Spree::Role]
def default_user_role
- roles.for_resource(self).find_by(name: Spree::Role::ADMIN_ROLE) ||
- roles.create!(
- name: Spree::Role::ADMIN_ROLE,
- mutable: false,
- permissions: Spree.permissions.grantable_keys(:seller)
- )
+ roles.for_resource(self).find_or_create_by!(name: Spree::Role::ADMIN_ROLE) do |role|
+ role.mutable = false
+ role.permissions = Spree.permissions.grantable_keys(:seller)
+ end
end
# Whether the seller is currently away. The catalog stays visible; what
@@ -206,15 +214,9 @@ module Spree
# restock somewhere the catalog believes in: stock movements anchor to a
# location, so an address alone would leave the goods arriving nowhere.
#
- # Filtered and sorted in Ruby rather than SQL so a preloaded
- # `stock_locations` is actually used — an `.active` scope here would issue
- # a fresh query per seller and quietly undo the admin list's preload.
- # Memoized because the serializer asks twice: once to decide whether to
- # render the address at all, once to render it.
- #
# @return [Spree::StockLocation, nil]
def returns_location
- stock_locations.active.order_default.first
+ @returns_location ||= stock_locations.active.order_default.first
end
# The postal address a shopper is given for returns.
@@ -231,15 +233,9 @@ module Spree
location.address
end
- # How many products this seller lists. Memoized because two readers ask
- # on every list row — the operator's column and the minimum-products
- # requirement — and a catalog is the one thing here that can run to
- # thousands, so it is counted in SQL once rather than loaded or counted
- # twice.
- #
- # @return [Integer]
+ # @return [Integer] how many products this seller lists
def products_count
- products.count
+ @products_count ||= products.count
end
# Where this seller stands against the marketplace's checklist
@@ -247,9 +243,6 @@ module Spree
# views of them. Computed on read, never stored: a column would be wrong
# the moment a product was deleted or a document sent back.
#
- # Memoized per instance, like the store's own setup checklist: one seller
- # page reads it several times — the badge, the bar, the list.
- #
# Reads the store's checklist off its loaded association when the store
# was eager-loaded with it (the admin list and profile do), so a page of
# sellers loads the rows once; a seller reached any other way queries.
@@ -264,7 +257,7 @@ module Spree
# @return [Hash{Symbol => Integer}] done, total and percentage over the
# whole checklist, optional requirements included
def onboarding_progress
- Spree::Sellers::Requirements.progress_of(onboarding_requirements)
+ @onboarding_progress ||= Spree::Sellers::Requirements.progress_of(onboarding_requirements)
end
# @return [Integer] 0..100
diff --git a/spree/core/app/models/spree/tax_identifier.rb b/spree/core/app/models/spree/tax_identifier.rb
index c016247e97..4f69b9815d 100644
--- a/spree/core/app/models/spree/tax_identifier.rb
+++ b/spree/core/app/models/spree/tax_identifier.rb
@@ -44,12 +44,11 @@ module Spree
# Which link of the resolution chain produced an order's snapshot.
SOURCES = %w[override company customer].freeze
- # Owner — exactly one
- belongs_to :customer, class_name: Spree.customer_class.to_s, optional: true, inverse_of: :tax_identifiers
- belongs_to :company, class_name: 'Spree::Company', optional: true, inverse_of: :tax_identifiers
- belongs_to :seller, class_name: 'Spree::Seller', optional: true, inverse_of: :tax_identifiers
- belongs_to :cart, class_name: 'Spree::Cart', optional: true, inverse_of: :tax_identifier
- belongs_to :order, class_name: 'Spree::Order', optional: true, inverse_of: :tax_identifier
+ # Whoever holds this registration. Polymorphic rather than one nullable FK
+ # per owner: there is one relationship here with two cardinalities — a
+ # customer, company or seller holds one per kind, a cart or order holds
+ # one — and a further owner should cost no schema change.
+ belongs_to :owner, polymorphic: true, optional: false
# Whitespace and case only. Punctuation is deliberately kept: for several
# kinds it is part of the canonical number (Switzerland's CHE-123.456.789
@@ -66,17 +65,13 @@ module Spree
after_commit :publish_number_changed, on: %i[create update]
validates :kind, :value, presence: true
- # One per kind for a customer — what the storefront upsert assumes, and what
- # makes resolution deterministic. Cart and order rows are singular by their
- # own associations.
- validates :kind, uniqueness: { scope: :customer_id }, if: -> { customer_id.present? }
- validates :kind, uniqueness: { scope: :company_id }, if: -> { company_id.present? }
- validates :kind, uniqueness: { scope: :seller_id }, if: -> { seller_id.present? }
+ # One per kind per owner — what the storefront upsert assumes, and what
+ # makes resolution deterministic.
+ validates :kind, uniqueness: { scope: [:owner_type, :owner_id] }
# Data hygiene, not a format claim — no tax regime issues numbers this long.
validates :value, length: { maximum: 64 }
validates :validation_status, inclusion: { in: VALIDATION_STATUSES }, allow_nil: true
validates :source, inclusion: { in: SOURCES }, allow_nil: true
- validate :exactly_one_owner
validate :value_format
scope :for_kind, ->(kind) { where(kind: kind) }
@@ -85,12 +80,7 @@ module Spree
# An order-owned row is a completion snapshot: immutable once written, so
# the tax treatment of a placed order can always be explained.
def readonly?
- persisted? && order_id.present?
- end
-
- # @return [Spree::Customer, Spree::Company, Spree::Seller, Spree::Cart, Spree::Order, nil]
- def owner
- customer || company || seller || cart || order
+ persisted? && order_owned?
end
def verified?
@@ -103,11 +93,17 @@ module Spree
#
# @return [Boolean]
def validatable?
- order_id.nil? && Spree.tax_identifier_validators.key?(kind)
+ !order_owned? && Spree.tax_identifier_validators.key?(kind)
end
private
+ # An order-owned row is the frozen completion snapshot, which is what makes
+ # it immutable and exempt from re-validation.
+ def order_owned?
+ owner_type == 'Spree::Order'
+ end
+
# Format knowledge lives entirely in the registered validator. Core asserts
# nothing about the shape of a number whose rules live in someone else's
# statute book: a rule spanning every tax regime on earth would be a guess,
@@ -122,7 +118,7 @@ module Spree
end
def number_changing?
- order_id.nil? && (will_save_change_to_value? || will_save_change_to_kind?)
+ !order_owned? && (will_save_change_to_value? || will_save_change_to_kind?)
end
# `pending` when something here can answer for the new number, and nothing at
@@ -148,11 +144,5 @@ module Spree
publish_event('tax_identifier.number_changed')
end
-
- def exactly_one_owner
- return if [customer, company, seller, cart, order].compact.one?
-
- errors.add(:base, Spree.t('errors.messages.exactly_one_tax_identifier_owner'))
- end
end
end
diff --git a/spree/core/app/services/spree/carts/split_by_seller.rb b/spree/core/app/services/spree/carts/split_by_seller.rb
index a48fe99e44..db856d6c80 100644
--- a/spree/core/app/services/spree/carts/split_by_seller.rb
+++ b/spree/core/app/services/spree/carts/split_by_seller.rb
@@ -289,7 +289,7 @@ module Spree
identifier = source_order.tax_identifier
return if identifier.nil?
- attributes = identifier.attributes.except('id', 'order_id', 'customer_id', 'company_id', 'cart_id',
+ attributes = identifier.attributes.except('id', 'owner_type', 'owner_id',
'created_at', 'updated_at')
sibling.create_tax_identifier!(attributes)
end
diff --git a/spree/core/app/workflows/spree/carts/complete.rb b/spree/core/app/workflows/spree/carts/complete.rb
index 36050ad404..eb33128d11 100644
--- a/spree/core/app/workflows/spree/carts/complete.rb
+++ b/spree/core/app/workflows/spree/carts/complete.rb
@@ -261,7 +261,7 @@ module Spree
resolved = cart.resolved_tax_identifier
return if resolved.nil?
- attributes = resolved.attributes.except('id', 'customer_id', 'company_id', 'cart_id',
+ attributes = resolved.attributes.except('id', 'owner_type', 'owner_id',
'created_at', 'updated_at')
order.create_tax_identifier!(attributes.merge('source' => source_of(resolved)))
end
@@ -269,10 +269,11 @@ module Spree
# Which link of the chain produced the snapshot, so a placed order's tax
# treatment names its own reason.
def source_of(resolved)
- return 'override' if resolved.cart_id.present?
- return 'company' if resolved.company_id.present?
-
- 'customer'
+ case resolved.owner
+ when Spree::Cart then 'override'
+ when Spree::Company then 'company'
+ else 'customer'
+ end
end
# Copies carry skip_tax_estimation: the cart's tax rows are copied onto the
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index 63e7f078de..2527c6c60b 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -898,7 +898,6 @@ en:
exactly_one_adjustable: must be attached to exactly one adjustable
exactly_one_of_cart_or_order: must belong to exactly one of cart or order
exactly_one_of_line_item_or_fulfillment: must be charged against exactly one of a line item or a fulfillment
- exactly_one_tax_identifier_owner: must belong to exactly one of customer, company, seller, cart or order
flat_fee_cannot_charge_delivery: is not available on a flat fee, which already charges for the sale the delivery belongs to — add a separate rate to charge delivery
integration_connection_failed: could not connect with the saved credentials
integration_type_not_registered: is not a registered integration
diff --git a/spree/core/db/migrate/20260806000003_create_spree_tax_identifiers.rb b/spree/core/db/migrate/20260806000003_create_spree_tax_identifiers.rb
index 146622c26a..111d4ef592 100644
--- a/spree/core/db/migrate/20260806000003_create_spree_tax_identifiers.rb
+++ b/spree/core/db/migrate/20260806000003_create_spree_tax_identifiers.rb
@@ -7,12 +7,10 @@ class CreateSpreeTaxIdentifiers < ActiveRecord::Migration[8.1]
# No store_id: the row belongs to a customer, cart or order that already
# carries the store, matching spree_tax_lines.
create_table :spree_tax_identifiers do |t|
- # Owner — exactly one (enforced at model level). The customer row is the
- # durable profile value, the cart row a checkout-time override, the order
- # row a frozen completion snapshot.
- t.references :customer, null: true
- t.references :cart, null: true
- t.references :order, null: true
+ # Whoever holds this registration. A customer, company or seller holds
+ # one per kind — the durable profile value; a cart holds a checkout-time
+ # override and an order the frozen completion snapshot.
+ t.references :owner, polymorphic: true, null: false
t.string :kind, null: false
t.string :value, null: false
@@ -34,10 +32,10 @@ class CreateSpreeTaxIdentifiers < ActiveRecord::Migration[8.1]
t.timestamps
end
- # One registration per kind for a customer. Cart and order rows leave
- # customer_id null, and NULLs never collide in a unique index, so this
- # constrains the profile rows only — which is where duplicates would make
- # resolution ambiguous.
- add_index :spree_tax_identifiers, [:customer_id, :kind], unique: true
+ # One registration per kind per owner, which is what makes resolution
+ # unambiguous. Cart and order owners hold a single row each through their
+ # associations and are covered by the same rule.
+ add_index :spree_tax_identifiers, [:owner_type, :owner_id, :kind],
+ unique: true, name: 'index_spree_tax_identifiers_on_owner_and_kind'
end
end
diff --git a/spree/core/db/migrate/20260807000002_add_company_to_spree_tax_identifiers.rb b/spree/core/db/migrate/20260807000002_add_company_to_spree_tax_identifiers.rb
deleted file mode 100644
index 5fdbdfb1b7..0000000000
--- a/spree/core/db/migrate/20260807000002_add_company_to_spree_tax_identifiers.rb
+++ /dev/null
@@ -1,9 +0,0 @@
-class AddCompanyToSpreeTaxIdentifiers < ActiveRecord::Migration[8.1]
- def change
- # A fourth owner, still exactly one per row: the registration of the entity
- # the invoice is addressed to, which outranks the buyer's own.
- add_reference :spree_tax_identifiers, :company, null: true
-
- add_index :spree_tax_identifiers, [:company_id, :kind], unique: true
- end
-end
diff --git a/spree/core/lib/spree/testing_support/factories/tax_identifier_factory.rb b/spree/core/lib/spree/testing_support/factories/tax_identifier_factory.rb
index 4dd7910950..9b8c5fb800 100644
--- a/spree/core/lib/spree/testing_support/factories/tax_identifier_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/tax_identifier_factory.rb
@@ -1,6 +1,6 @@
FactoryBot.define do
factory :tax_identifier, class: Spree::TaxIdentifier do
- customer
+ owner factory: :customer
kind { 'eu_vat' }
sequence(:value) { |n| "DE#{123_456_780 + n}" }
@@ -12,15 +12,21 @@ FactoryBot.define do
# A number entered during checkout, overriding the customer's own.
trait :on_cart do
- customer { nil }
- cart
+ owner factory: :cart
end
# The frozen snapshot taken when the order was placed.
trait :on_order do
- customer { nil }
- order
+ owner factory: :order
source { 'customer' }
end
+
+ trait :on_company do
+ owner factory: :company
+ end
+
+ trait :on_seller do
+ owner factory: :seller
+ end
end
end
diff --git a/spree/core/spec/jobs/spree/tax_identifiers/validate_job_spec.rb b/spree/core/spec/jobs/spree/tax_identifiers/validate_job_spec.rb
index 4d42bd15ed..9ab5acddfd 100644
--- a/spree/core/spec/jobs/spree/tax_identifiers/validate_job_spec.rb
+++ b/spree/core/spec/jobs/spree/tax_identifiers/validate_job_spec.rb
@@ -2,7 +2,7 @@ require 'spec_helper'
describe Spree::TaxIdentifiers::ValidateJob do
let(:customer) { create(:user) }
- let(:tax_identifier) { create(:tax_identifier, customer: customer, kind: 'eu_vat') }
+ let(:tax_identifier) { create(:tax_identifier, owner: customer, kind: 'eu_vat') }
before do
stub_const('SpecJobValidator', Class.new(Spree::TaxIdentifiers::Validator::Base) do
diff --git a/spree/core/spec/models/concerns/spree/purchase/taxation_spec.rb b/spree/core/spec/models/concerns/spree/purchase/taxation_spec.rb
index a468ff1759..479f6b6355 100644
--- a/spree/core/spec/models/concerns/spree/purchase/taxation_spec.rb
+++ b/spree/core/spec/models/concerns/spree/purchase/taxation_spec.rb
@@ -36,14 +36,14 @@ RSpec.shared_examples 'a taxation host' do
end
it 'falls back to the customer registration' do
- identifier = create(:tax_identifier, customer: customer)
+ identifier = create(:tax_identifier, owner: customer)
expect(record.resolved_tax_identifier).to eq(identifier)
end
it 'prefers a verified registration over a newer unverified one' do
- verified = create(:tax_identifier, :verified, customer: customer, kind: 'eu_vat')
- create(:tax_identifier, customer: customer, kind: 'gb_vat')
+ verified = create(:tax_identifier, :verified, owner: customer, kind: 'eu_vat')
+ create(:tax_identifier, owner: customer, kind: 'gb_vat')
expect(record.resolved_tax_identifier).to eq(verified)
end
@@ -56,31 +56,30 @@ RSpec.shared_examples 'a taxation host' do
# The invoice is addressed to the entity, so its registration wins.
it 'prefers the company registration over the buyer own' do
- create(:tax_identifier, customer: customer, kind: 'eu_vat', value: 'DE111111111')
- company_identifier = create(:tax_identifier, customer: nil, company: company,
+ create(:tax_identifier, owner: customer, kind: 'eu_vat', value: 'DE111111111')
+ company_identifier = create(:tax_identifier, owner: company,
kind: 'eu_vat', value: 'DE222222222')
expect(record.resolved_tax_identifier).to eq(company_identifier)
end
it 'still falls back to the buyer when the company has none' do
- identifier = create(:tax_identifier, customer: customer)
+ identifier = create(:tax_identifier, owner: customer)
expect(record.resolved_tax_identifier).to eq(identifier)
end
it 'prefers a verified company registration' do
- verified = create(:tax_identifier, :verified, customer: nil, company: company, kind: 'eu_vat')
- create(:tax_identifier, customer: nil, company: company, kind: 'gb_vat')
+ verified = create(:tax_identifier, :verified, owner: company, kind: 'eu_vat')
+ create(:tax_identifier, owner: company, kind: 'gb_vat')
expect(record.resolved_tax_identifier).to eq(verified)
end
end
it 'prefers the record own override over the customer registration' do
- create(:tax_identifier, customer: customer)
- owner_key = record.is_a?(Spree::Cart) ? :cart : :order
- override = create(:tax_identifier, { customer: nil, kind: 'eu_vat', value: 'DE555555555', owner_key => record })
+ create(:tax_identifier, owner: customer)
+ override = create(:tax_identifier, kind: 'eu_vat', value: 'DE555555555', owner: record)
expect(record.resolved_tax_identifier).to eq(override)
end
@@ -92,7 +91,7 @@ RSpec.shared_examples 'a taxation host' do
before { record.update!(customer: customer) }
it 'carries the effective date, the buyer registration and the exemptions' do
- identifier = create(:tax_identifier, customer: customer)
+ identifier = create(:tax_identifier, owner: customer)
exemption = Spree::TaxExemption.new(reason_code: 'resale')
allow(Spree.tax_resolve_exemptions_service).to receive(:new).
and_return(instance_double(Spree::Tax::ResolveExemptions,
@@ -196,11 +195,11 @@ RSpec.describe Spree::Purchase::Taxation do
let(:record) { create(:completed_order_with_totals, customer: customer) }
it 'reads its own snapshot and never re-resolves' do
- create(:tax_identifier, customer: customer)
+ create(:tax_identifier, owner: customer)
expect(record.resolved_tax_identifier).to be_nil
- snapshot = create(:tax_identifier, :on_order, order: record)
+ snapshot = create(:tax_identifier, :on_order, owner: record)
expect(record.reload.resolved_tax_identifier).to eq(snapshot)
end
end
diff --git a/spree/core/spec/models/spree/tax_identifier_spec.rb b/spree/core/spec/models/spree/tax_identifier_spec.rb
index bd63f5c9f5..bd05a5843d 100644
--- a/spree/core/spec/models/spree/tax_identifier_spec.rb
+++ b/spree/core/spec/models/spree/tax_identifier_spec.rb
@@ -11,12 +11,10 @@ describe Spree::TaxIdentifier, type: :model do
expect(build(:tax_identifier, value: nil)).not_to be_valid
end
- it 'belongs to exactly one owner' do
- expect(build(:tax_identifier, customer: customer)).to be_valid
- expect(build(:tax_identifier, customer: nil, cart: cart)).to be_valid
-
- expect(build(:tax_identifier, customer: customer, cart: cart)).not_to be_valid
- expect(build(:tax_identifier, customer: nil)).not_to be_valid
+ it 'requires an owner' do
+ expect(build(:tax_identifier, owner: customer)).to be_valid
+ expect(build(:tax_identifier, owner: cart)).to be_valid
+ expect(build(:tax_identifier, owner: nil)).not_to be_valid
end
it 'rejects a validation status the platform never sets' do
@@ -27,25 +25,25 @@ describe Spree::TaxIdentifier, type: :model do
describe 'the order snapshot' do
it 'is immutable once written' do
- snapshot = create(:tax_identifier, :on_order, order: order)
+ snapshot = create(:tax_identifier, :on_order, owner: order)
expect(snapshot).to be_readonly
expect { snapshot.update!(value: 'DE999999999') }.to raise_error(ActiveRecord::ReadOnlyRecord)
end
it 'is writable while unsaved' do
- expect(build(:tax_identifier, :on_order, order: order)).not_to be_readonly
+ expect(build(:tax_identifier, :on_order, owner: order)).not_to be_readonly
end
end
it 'is editable while owned by a customer or a cart' do
- expect(create(:tax_identifier, customer: customer)).not_to be_readonly
- expect(create(:tax_identifier, :on_cart, cart: cart)).not_to be_readonly
+ expect(create(:tax_identifier, owner: customer)).not_to be_readonly
+ expect(create(:tax_identifier, :on_cart, owner: cart)).not_to be_readonly
end
describe 'normalization' do
it 'strips whitespace and upcases, keeping punctuation' do
- identifier = create(:tax_identifier, customer: customer, kind: 'ch_vat', value: ' che-123.456.789 mwst ')
+ identifier = create(:tax_identifier, owner: customer, kind: 'ch_vat', value: ' che-123.456.789 mwst ')
expect(identifier.value).to eq('CHE-123.456.789MWST')
end
@@ -71,18 +69,18 @@ describe Spree::TaxIdentifier, type: :model do
end
it 'rejects a malformed number as a typo to fix' do
- identifier = build(:tax_identifier, customer: customer, kind: 'eu_vat', value: '123456789')
+ identifier = build(:tax_identifier, owner: customer, kind: 'eu_vat', value: '123456789')
expect(identifier).not_to be_valid
expect(identifier.errors[:value]).to be_present
end
it 'accepts a well-formed one' do
- expect(build(:tax_identifier, customer: customer, kind: 'eu_vat', value: 'DE123456789')).to be_valid
+ expect(build(:tax_identifier, owner: customer, kind: 'eu_vat', value: 'DE123456789')).to be_valid
end
it 'accepts any number for a kind nothing here can check' do
- expect(build(:tax_identifier, customer: customer, kind: 'au_abn', value: 'anything')).to be_valid
+ expect(build(:tax_identifier, owner: customer, kind: 'au_abn', value: 'anything')).to be_valid
end
end
@@ -96,20 +94,20 @@ describe Spree::TaxIdentifier, type: :model do
it 'is queued when a checkable number is entered, and marked pending' do
identifier = nil
- expect { identifier = create(:tax_identifier, customer: customer, kind: 'eu_vat') }.to(
+ expect { identifier = create(:tax_identifier, owner: customer, kind: 'eu_vat') }.to(
have_enqueued_job(Spree::TaxIdentifiers::ValidateJob)
)
expect(identifier.reload.validation_status).to eq('pending')
end
it 'is not queued again when something else on the row changes' do
- identifier = create(:tax_identifier, customer: customer, kind: 'eu_vat')
+ identifier = create(:tax_identifier, owner: customer, kind: 'eu_vat')
expect { identifier.update!(source: nil) }.not_to have_enqueued_job(Spree::TaxIdentifiers::ValidateJob)
end
it 'is queued again when the number changes' do
- identifier = create(:tax_identifier, customer: customer, kind: 'eu_vat')
+ identifier = create(:tax_identifier, owner: customer, kind: 'eu_vat')
expect { identifier.update!(value: 'DE987654321') }.to have_enqueued_job(Spree::TaxIdentifiers::ValidateJob)
end
@@ -118,7 +116,7 @@ describe Spree::TaxIdentifier, type: :model do
# the request that changed the number must not report a stale verdict, and it
# must hold even where the event bus is switched off.
it 'marks the row pending on the object that was saved, without reloading' do
- identifier = Spree::Events.disable { create(:tax_identifier, customer: customer, kind: 'eu_vat') }
+ identifier = Spree::Events.disable { create(:tax_identifier, owner: customer, kind: 'eu_vat') }
expect(identifier.validation_status).to eq('pending')
expect(identifier.validated_at).to be_nil
@@ -127,7 +125,7 @@ describe Spree::TaxIdentifier, type: :model do
# Purchase::Taxation#best_of prefers a verified row, so a verdict left behind
# on a kind nothing can check would be actively chosen to decide tax.
it 'clears the verdict when the kind becomes one nothing can check' do
- identifier = create(:tax_identifier, customer: customer, kind: 'eu_vat')
+ identifier = create(:tax_identifier, owner: customer, kind: 'eu_vat')
identifier.update_columns(validation_status: 'verified', validated_at: Time.current)
identifier.update!(kind: 'au_abn', value: '51824753556')
@@ -139,7 +137,7 @@ describe Spree::TaxIdentifier, type: :model do
end
it 'clears an earlier verdict when the number changes' do
- identifier = create(:tax_identifier, customer: customer, kind: 'eu_vat')
+ identifier = create(:tax_identifier, owner: customer, kind: 'eu_vat')
identifier.update_columns(validation_status: 'verified', validated_at: Time.current)
identifier.update!(value: 'DE987654321')
@@ -149,14 +147,14 @@ describe Spree::TaxIdentifier, type: :model do
end
it 'is skipped for a kind nothing here can check' do
- expect { create(:tax_identifier, customer: customer, kind: 'au_abn') }.not_to(
+ expect { create(:tax_identifier, owner: customer, kind: 'au_abn') }.not_to(
have_enqueued_job(Spree::TaxIdentifiers::ValidateJob)
)
expect(described_class.last.validation_status).to be_nil
end
it 'is skipped for an order snapshot, frozen by definition' do
- expect { create(:tax_identifier, :on_order, order: order, kind: 'eu_vat') }.not_to(
+ expect { create(:tax_identifier, :on_order, owner: order, kind: 'eu_vat') }.not_to(
have_enqueued_job(Spree::TaxIdentifiers::ValidateJob)
)
end
@@ -164,7 +162,7 @@ describe Spree::TaxIdentifier, type: :model do
describe '#validatable?' do
it 'reports whether this installation can check the kind' do
- identifier = create(:tax_identifier, customer: customer, kind: 'eu_vat')
+ identifier = create(:tax_identifier, owner: customer, kind: 'eu_vat')
expect(identifier).not_to be_validatable
with_tax_identifier_validator('eu_vat', 'Spree::TaxIdentifiers::Validator::Base') do
@@ -177,23 +175,17 @@ describe Spree::TaxIdentifier, type: :model do
let(:company) { create(:company, store: @default_store) }
it 'is a valid sole owner' do
- expect(build(:tax_identifier, customer: nil, company: company)).to be_valid
- end
-
- it 'is rejected alongside another owner' do
- identifier = build(:tax_identifier, company: company, customer: create(:customer))
-
- expect(identifier).not_to be_valid
+ expect(build(:tax_identifier, owner: company)).to be_valid
end
it 'holds one registration per kind' do
- create(:tax_identifier, customer: nil, company: company, kind: 'eu_vat')
+ create(:tax_identifier, owner: company, kind: 'eu_vat')
- expect(build(:tax_identifier, customer: nil, company: company, kind: 'eu_vat')).not_to be_valid
+ expect(build(:tax_identifier, owner: company, kind: 'eu_vat')).not_to be_valid
end
it 'reports the company as its owner' do
- identifier = create(:tax_identifier, customer: nil, company: company)
+ identifier = create(:tax_identifier, owner: company)
expect(identifier.owner).to eq(company)
end
@@ -205,25 +197,18 @@ describe Spree::TaxIdentifier, type: :model do
let(:seller) { create(:seller) }
it 'is a valid owner' do
- identifier = described_class.new(seller: seller, kind: 'eu_vat', value: 'GB123456789')
+ identifier = described_class.new(owner: seller, kind: 'eu_vat', value: 'GB123456789')
expect(identifier).to be_valid
expect(identifier.owner).to eq(seller)
end
it 'holds one registration per kind' do
- described_class.create!(seller: seller, kind: 'eu_vat', value: 'GB123456789')
- duplicate = described_class.new(seller: seller, kind: 'eu_vat', value: 'GB987654321')
+ described_class.create!(owner: seller, kind: 'eu_vat', value: 'GB123456789')
+ duplicate = described_class.new(owner: seller, kind: 'eu_vat', value: 'GB987654321')
expect(duplicate).not_to be_valid
end
-
- it 'cannot also belong to somebody else' do
- identifier = described_class.new(seller: seller, company: create(:company),
- kind: 'eu_vat', value: 'GB123456789')
-
- expect(identifier).not_to be_valid
- end
end
end
diff --git a/spree/core/spec/services/spree/tax_identifiers/validate_spec.rb b/spree/core/spec/services/spree/tax_identifiers/validate_spec.rb
index d9d49106c5..442d444ad8 100644
--- a/spree/core/spec/services/spree/tax_identifiers/validate_spec.rb
+++ b/spree/core/spec/services/spree/tax_identifiers/validate_spec.rb
@@ -2,7 +2,7 @@ require 'spec_helper'
describe Spree::TaxIdentifiers::Validate do
let(:customer) { create(:user) }
- let(:tax_identifier) { create(:tax_identifier, customer: customer, kind: 'eu_vat', value: 'DE123456789') }
+ let(:tax_identifier) { create(:tax_identifier, owner: customer, kind: 'eu_vat', value: 'DE123456789') }
def register(validator_class)
stub_const('SpecRegistryValidator', validator_class)
diff --git a/spree/core/spec/subscribers/spree/tax_identifier_validation_subscriber_spec.rb b/spree/core/spec/subscribers/spree/tax_identifier_validation_subscriber_spec.rb
index d7cd70644c..1ec4a32b11 100644
--- a/spree/core/spec/subscribers/spree/tax_identifier_validation_subscriber_spec.rb
+++ b/spree/core/spec/subscribers/spree/tax_identifier_validation_subscriber_spec.rb
@@ -22,7 +22,7 @@ RSpec.describe Spree::TaxIdentifierValidationSubscriber do
end
describe '#call' do
- let(:identifier) { create(:tax_identifier, customer: customer, kind: 'eu_vat') }
+ let(:identifier) { create(:tax_identifier, owner: customer, kind: 'eu_vat') }
let(:event) { Spree::Event.new(name: 'tax_identifier.number_changed', payload: { 'id' => identifier.prefixed_id }) }
it 'queues the registry check' do
@@ -38,7 +38,7 @@ RSpec.describe Spree::TaxIdentifierValidationSubscriber do
# A placed order's number is a snapshot: re-checking it could contradict
# what the order was taxed under.
it 'does nothing for an order snapshot' do
- snapshot = create(:tax_identifier, :on_order, order: create(:order, store: store), kind: 'eu_vat')
+ snapshot = create(:tax_identifier, :on_order, owner: create(:order, store: store), kind: 'eu_vat')
snapshot_event = Spree::Event.new(name: 'tax_identifier.number_changed', payload: { 'id' => snapshot.prefixed_id })
expect { described_class.new.call(snapshot_event) }.not_to have_enqueued_job(Spree::TaxIdentifiers::ValidateJob)
diff --git a/spree/core/spec/workflows/spree/carts/complete_spec.rb b/spree/core/spec/workflows/spree/carts/complete_spec.rb
index 59f271132f..8fc8b8d57b 100644
--- a/spree/core/spec/workflows/spree/carts/complete_spec.rb
+++ b/spree/core/spec/workflows/spree/carts/complete_spec.rb
@@ -226,7 +226,7 @@ module Spree
before { ready_cart.update!(customer: customer) }
it 'freezes the customer registration onto the order' do
- create(:tax_identifier, customer: customer, kind: 'eu_vat', value: 'DE123456789')
+ create(:tax_identifier, owner: customer, kind: 'eu_vat', value: 'DE123456789')
order = described_class.call(cart: ready_cart).value
@@ -237,8 +237,8 @@ module Spree
end
it 'records a checkout override as such' do
- create(:tax_identifier, customer: customer, kind: 'eu_vat', value: 'DE123456789')
- create(:tax_identifier, customer: nil, cart: ready_cart, kind: 'eu_vat', value: 'DE999999999')
+ create(:tax_identifier, owner: customer, kind: 'eu_vat', value: 'DE123456789')
+ create(:tax_identifier, owner: ready_cart, kind: 'eu_vat', value: 'DE999999999')
order = described_class.call(cart: ready_cart).value
@@ -250,15 +250,14 @@ module Spree
company = create(:company, store: store)
location = create(:company_location, company: company)
ready_cart.update!(company_location: location)
- create(:tax_identifier, customer: nil, company: company, kind: 'eu_vat', value: 'DE777777777')
+ create(:tax_identifier, owner: company, kind: 'eu_vat', value: 'DE777777777')
order = described_class.call(cart: ready_cart).value
expect(order.tax_identifier.value).to eq('DE777777777')
expect(order.tax_identifier.source).to eq('company')
- # The copy must not carry the company along, or the order row would
- # have two owners.
- expect(order.tax_identifier.company_id).to be_nil
+ # The copy belongs to the order, not the company it was resolved from.
+ expect(order.tax_identifier.owner).to eq(order)
end
it 'copies nothing for a consumer sale' do