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
Unblock tax exemptions by pulling Company forward
Łukasz Adamczyk961bb95b4b28
diff --git a/CLAUDE.md b/CLAUDE.mdindex 75efc00a84..25fa0bf51c 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -23,7 +23,7 @@ Active plans (6.0 target, work pending):- `6.0-fulfillment-and-delivery.md` — Shipment→Fulfillment, ShippingMethod→DeliveryMethod, drop ShippingCategory, FulfillmentProvider strategy, pickup (merchant StockLocation) + pickup_point (third-party PickupPointProvider). **Shipped to 6-0-dev (Waves 2+4+6):** renames + deprecated twins, providers (Manual/Digital/Pickup/PickupPoint), dual-emit events, store pickup discovery endpoints, admin delivery_methods/delivery_zones CRUD + dashboard settings pages, FulfillmentMailer; Wave 7 shipping→delivery data migration remains- `6.0-returns-exchanges-claims.md` — First-class Return, Exchange, Claim models replacing ReturnAuthorization/Reimbursement chain. **COMPLETE (2026-08-05):** all three entities (+ permanent `ReturnLineItem`/`ExchangeLineItem`/`ClaimLineItem` line items), `Spree::HasStatus`, all fifteen workflows (each with a leading `validate` hook), `Refund#originator`, admin + store v3 APIs (transitions as PATCH member actions; no destroy — cancel instead), dashboard pages. Legacy chain **removed**: ReturnAuthorization/CustomerReturn/Reimbursement/ReimbursementType/legacy ReturnItem + eligibility validators + ReturnsCalculator classes all deleted, but their **tables deliberately survive to 6.1** as the data migration's source and rollback path. `spree:upgrade:migrate_returns` (`Spree::ReturnsMigrator`, defined in the rake file like its sibling upgrade tasks; anonymous-AR readers) is in the 5.6→6.0 manifest after the adjustments step; it needs no cursor because the preserved `number` is uniquely indexed on the new tables, so "what's left" is a `where.not(number: ...)` query and an interrupted run resumes for free. `ReturnAuthorizationReason`→`ReturnReason` (alias one release) + new `ClaimReason`; `Metafields` on all three. Capability replacements: `Spree::ReturnMailer#refunded_email` on `return.refunded` (replaces the reimbursement email), `Order#outstanding_balance` drops the reimbursement term (refunds already net out of `payment_total`), `Return#refunded_total` counts store credits too, `StoreCreditCategory.default_refund_category` (alias kept). **Reasons** ship admin-only CRUD (`/api/v3/admin/{return,claim,refund}_reasons`, `settings` scope) + a combined Settings → Reasons dashboard page + reason pickers on the create dialogs; `mutable` is never client-writable and the immutability guard lives on `Spree::NamedType` (`can_be_deleted?` + rename/destroy guards) because secret API keys authorize by scope and never consult CanCanCan. **No state machines (2026-08-02):** plain `status` string + inclusion validation; all fifteen transitions are workflows (`Returns::Receive`, `Exchanges::Fulfill`, `Claims::Resolve`, …) with `validate` hooks for return-eligibility policy and refunds as `external_step`. Nothing happens in a model or transition callback. Statuses live in a `class_attribute` via the core `Spree::HasStatus` concern (`has_status` + additive `add_status(value, after:)`, generating predicates and scopes) — extensible by design, additive only, and no transition graph (that would be a state machine again). **Return eligibility is a hook, not a policy engine (2026-08-03):** no window/restocking-fee/final-sale flag in core — a `validate` handler decides, enforcing for customers while letting staff override (it reads `created_by`), and region-varying policy reads `order.market`. Medusa/Saleor/Vendure ship no policy at all; Shopify's engine has no API. A `ReturnPolicy` model can arrive later behind the same hook.- `6.0-platform-auth.md` — Drop Devise, own auth stack, User→Customer/Staff rename (RefreshToken shipped in 5.4)-- `6.0-tax-provider.md` — Per-Market TaxProvider (market selects the provider, providers stateless/argless; global config class stays as fallback), replaces TaxRate.adjust + Calculator; reference provider: Avalara (decisions.md 2026-07-30). **Shipped to 6-0-dev (core-rewrite waves):** `Spree::TaxProvider::Base`/`Internal` as the sole TaxLine write path, called from `Carts::RecalculateTotals` behind the `money_frozen?` freeze. **Contract refined 2026-08-05 after the spree/spree#14056 review (decisions.md):** TaxLine gains `taxability_reason` + jurisdiction snapshot (e-invoice category/exemption codes derived at invoicing time, never stored); new `Spree::TaxIdentifier` model (customer/cart/order dual-FK, frozen order snapshot; validation via the kind-keyed `Spree.tax_id_validators` registry + async job on the geocoding precedent — NOT a provider method, and no registry client in core); exemptions = typed `estimate` input via `tax_resolve_exemptions_service` (boolean `exempt?` removed, no flags anywhere); explicit `tax_date:`; `refund(order, return_items, tax_date:)`; capability declarations (Internal declares no US local tax / no reverse charge / no one-stop-shop thresholds; `estimate` keeps its no-op return — a structured result + indeterminacy channel deferred as safely additive). **Phases 3-5 in development:** the enriched contract, `Spree::TaxIdentifier` + validator registry, exemption value objects, per-Market selection with commit/void/refund as external steps, and the Zone decoupling (rates carry `country_id`/`state_id`; `spree_tax_rates.zone_id` stays through 6.0 as the conversion source). Pending: Phase 6 `spree_tax_avalara`, Phase 7 exemption certificates (gated on Company from the B2B plan), Phase 8 6.1 cleanup (drop `zone_id`, `null: false` on the tax `store_id`s, remove the two `tax_zone` bridges, decide `Market#tax_inclusive`)+- `6.0-tax-provider.md` — Per-Market TaxProvider (market selects the provider, providers stateless/argless; global config class stays as fallback), replaces TaxRate.adjust + Calculator; reference provider: Avalara (decisions.md 2026-07-30). **Shipped to 6-0-dev (core-rewrite waves):** `Spree::TaxProvider::Base`/`Internal` as the sole TaxLine write path, called from `Carts::RecalculateTotals` behind the `money_frozen?` freeze. **Contract refined 2026-08-05 after the spree/spree#14056 review (decisions.md):** TaxLine gains `taxability_reason` + jurisdiction snapshot (e-invoice category/exemption codes derived at invoicing time, never stored); new `Spree::TaxIdentifier` model (customer/cart/order dual-FK, frozen order snapshot; validation via the kind-keyed `Spree.tax_id_validators` registry + async job on the geocoding precedent — NOT a provider method, and no registry client in core); exemptions = typed `estimate` input via `tax_resolve_exemptions_service` (boolean `exempt?` removed, no flags anywhere); explicit `tax_date:`; `refund(order, return_items, tax_date:)`; capability declarations (Internal declares no US local tax / no reverse charge / no one-stop-shop thresholds; `estimate` keeps its no-op return — a structured result + indeterminacy channel deferred as safely additive). **Phases 3-5 in development:** the enriched contract, `Spree::TaxIdentifier` + validator registry, exemption value objects, per-Market selection with commit/void/refund as external steps, and the Zone decoupling (rates carry `country_id`/`state_id`; `spree_tax_rates.zone_id` stays through 6.0 as the conversion source). **Phases 3-5 + the Zone decoupling shipped to `feature/v-3526` (PR #14410).** **Phase 7 is next and no longer gated (2026-08-07):** it pulls the minimal Company tree forward out of the B2B plan — Company → CompanyLocation → CompanyContact, `company_location_id` on both carts and orders, `company_id` as a fourth TaxIdentifier owner, `Spree::TaxExemptionCertificate` hanging off Company scoped by country/state, and the `ResolveExemptions` body; **no `tax_exempt` boolean anywhere** (supersedes the B2B plan's sketches), and Catalog/pricing/visibility stay 6.1. Pending after that: Phase 6 `spree_tax_avalara`, Phase 8 6.1 cleanup (drop `zone_id`, `null: false` on the tax `store_id`s, decide `Market#tax_inclusive`). Still open: delivery-rate tax display bypasses the provider- `6.0-delivery-rate-provider.md` — Per-DeliveryMethod DeliveryRateProvider wrapping Stock::Estimator (calculators stay — 2026-07-27 reversal), `store_id` on ShippingMethod, enriched DeliveryRate (carrier/service/date/metadata); monorepo ships one reference multi-carrier provider (Shippo/EasyPost, pick pending — decisions.md 2026-07-29); method rows stay regional (no cross-market method entity)- `6.0-delivery-zones.md` — Zone → DeliveryZone with postal-code-range/prefix members (country-scoped); owns the full ~183-reference Zone consumer inventory; `Spree::Zone` dropped entirely by end of 6.0 (2026-07-27 — 6.0 is the breaking-change window)- `6.0-rich-text-descriptions.md` — Drop ActionText **entirely** at 6.0 (incl. CustomFields::RichText values + Order/User internal notes; gem dependency removed), store sanitized HTML in text columns, serve `field` + `field_html`, **write via `field_html`** (read/write symmetry). description_html serializer shipped 5.4; sanitizer shipped in **5.6.2** with a permissive-but-safe configurable allowlist + `sanitize_rich_text` step in the 5.5→5.6 upgrade manifest (decisions.md 2026-07-27/28), tightened to the Tiptap set at 6.0diff --git a/docs/plans/6.0-tax-provider.md b/docs/plans/6.0-tax-provider.mdindex 32468a46ae..99f1acb71c 100644--- a/docs/plans/6.0-tax-provider.md+++ b/docs/plans/6.0-tax-provider.md@@ -1,6 +1,6 @@# Tax Provider Interface-**Status:** In progress — the provider seam, `Spree::TaxProvider::Internal` and the `TaxLine` write path shipped to 6-0-dev with the core-rewrite waves (see Current State). **Phases 3, 4 and 5 are in development** (contract enrichment, per-Market selection, commit/void/refund wiring, Zone decoupling). Remaining: Phase 6 (the Avalara reference gem), Phase 7 (exemption certificates, gated on Company) and Phase 8 (the 6.1 cleanup of the schema 6.0 keeps deliberately).+**Status:** In progress — the provider seam, `Spree::TaxProvider::Internal` and the `TaxLine` write path shipped to 6-0-dev with the core-rewrite waves (see Current State). **Phases 3, 4 and 5 are in development** (contract enrichment, per-Market selection, commit/void/refund wiring, Zone decoupling). **Phase 7 (exemption certificates) is next up and no longer gated** — it builds the minimal Company tree itself (2026-08-07, see Key Decisions). Remaining after that: Phase 6 (the Avalara reference gem) and Phase 8 (the 6.1 cleanup of the schema 6.0 keeps deliberately).> **Store binding (2026-07-29):** TaxRate and TaxCategory adopt the every-major-model-carries-a-store_id convention as part of this plan's implementation (`Spree::SingleStoreResource`, backfill task, NOT NULL in 6.1) — same treatment DeliveryMethod/StockLocation/DeliveryZone received on the 6.0 core-rewrite branch.@@ -11,7 +11,7 @@> **Contract refinement (2026-08-05):** the provider contract was reworked after the community review on spree/spree#14056, with every concern verified against primary sources (EN 16931 / VAT Directive / VIES), the major provider APIs (Avalara, Stripe Tax, TaxJar, Vertex) and platform practice (Medusa, Saleor, commercetools, Shopify, Magento, Odoo). Headlines: tax results carry a **taxability reason**, not just an amount; buyer tax identity becomes a first-class **`Spree::TaxIdentifier`** model with an order-time snapshot; exemption is a **typed estimate input** (the boolean `exempt?` is removed); the **effective date** is an explicit input; providers declare **capability limits** honestly. See Key Decisions.**Target:** Spree 6.0-**Depends on:** Split Adjustments (6.0-6.1-split-adjustments.md — shipped; provides TaxLine). Phase 7 (exemption certificates) and the Company link in the tax-identifier chain are gated on the B2B plan (6.1-channels-catalogs-b2b.md); nothing in Phases 3–6 waits on it.+**Depends on:** Split Adjustments (6.0-6.1-split-adjustments.md — shipped; provides TaxLine). Phase 7 pulls the Company tree forward out of `6.1-channels-catalogs-b2b.md` rather than waiting on it — that plan keeps Catalog, per-company pricing and product visibility, and inherits the models this phase ships.**Author:** Damian + Claude**Last updated:** 2026-08-07@@ -219,8 +219,9 @@ class Spree::TaxIdentifier < Spree.base_classbelongs_to :customer, class_name: 'Spree::Customer', optional: true # durable profile valuebelongs_to :cart, class_name: 'Spree::Cart', optional: true # checkout-time overridebelongs_to :order, class_name: 'Spree::Order', optional: true # frozen completion snapshot- # + company_id / company_location_id when the B2B plan ships (per-branch- # registrations follow Shopify's CompanyLocation.taxRegistrationId precedent)+ # + 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).# kind: 'eu_vat', 'gb_vat', 'au_abn', … (Stripe's typed-kind model)# value: the registration number@@ -244,7 +245,39 @@ end```- **Cart and order tables get zero tax columns; consumer orders carry no row at all.** The customer-level row exists because not every business buyer will have a Company — sole proprietors with VAT IDs are exactly who reverse charge exists for, and the B2B Company model targets bigger businesses.-- **Resolution chain at estimate:** cart-owned override → (Company, when the B2B plan ships) → customer's row → nil (B2C treatment). This is a fallback chain, so it lives as `#resolved_tax_identifier` on `Spree::Purchase::Taxation` — the concern that already owns `tax_address` for both Cart and Order — not behind a Dependencies seam. A three-link `||` has no swappable behavior worth freezing as public API, and an installation that genuinely needs different selection decorates the method.+- **Resolution chain at estimate:** cart-owned override → the order's company → customer's row → nil (B2C treatment). The company link arrives with Phase 7. This is a fallback chain, so it lives as `#resolved_tax_identifier` on `Spree::Purchase::Taxation` — the concern that already owns `tax_address` for both Cart and Order — not behind a Dependencies seam. A three-link `||` has no swappable behavior worth freezing as public API, and an installation that genuinely needs different selection decorates the method.++### Company, pulled forward for exemptions (2026-08-07)++Exemption resolution needs an entity to hang certificates on, and `Spree::Company` did not exist —+the B2B plan targets 6.1. Rather than leave Phase 7 blocked, this plan builds the **minimum tree that+makes exemptions resolvable** and hands the rest back. Four decisions settle the shape:++- **The Cart and the Order both reference `company_location`, not `company`.** That is the FK the B2B+ plan already specifies for orders, so 6.1 adds no second column and moves nothing; `#company`+ derives through the location. The column lands on `spree_carts` too, following `channel_id` and+ `market_id` — exemption has to resolve during checkout, not only after placement. The alternative,+ a direct `company_id`, is one hop cheaper today and costs a schema reversal later, with per-branch+ registration having nowhere to go.+- **All three models ship: Company → CompanyLocation → CompanyContact.** The contact is not+ decoration — it is what lets a logged-in B2B buyer's own cart resolve a company without staff+ touching the order. Without it, exemption only works on admin-created orders, which is exactly the+ wrong limitation for a self-serve wholesale channel.+- **No `tax_exempt` boolean, on either model.** This supersedes the B2B plan's Company and+ CompanyLocation sketches, which both carry one. A flag cannot say which jurisdiction it holds in or+ which line it covers, and removing the boolean `exempt?` from the provider contract was the whole+ point of the 2026-08-05 refinement — reintroducing it one layer down would undo that. Exemption is+ certificates, resolved into typed entries.+- **Certificates hang off Company, scoped by jurisdiction.** Their own `country`/`state` columns+ already answer "where does this hold", so per-location rows would restate the branch address and+ force a company-wide certificate to be duplicated per branch. Shopify hangs exemptions on the+ location; it also has no jurisdiction columns to scope with.++**Explicitly still 6.1, and not to be built here:** Catalog, CatalogProduct, CatalogAssignment and+`default_catalog_id`; per-company pricing and `Products::ForContext` visibility; the Company →+CustomerGroup link; roles, approval workflows, purchase limits and invoicing. Contacts carry a plain+`role` string with no behavior attached, as the B2B plan specifies.+- **Completion copies, never references:** the copy step in `Carts::Complete` calls the same `#resolved_tax_identifier` and duplicates the winning row as a frozen order-owned row with `source` stamped — Stripe's invoice-finalization freeze plus the evidence Stripe drops. Post-completion provider calls (`commit`/`void`/`refund`) read the order-owned snapshot directly; the resolution chain is a checkout-time concern only.- **Freeze enforcement, three layers:** single writer (the `Carts::Complete` copy step — nothing else creates order-owned rows), the `readonly?` model backstop above (ActiveRecord refuses save/destroy; customer- and cart-owned rows stay editable), and the API perimeter (identifier params permitted on cart + customer endpoints only, never order endpoints). Deliberately **no correction path**: a wrong ID on a completed order already produced the tax treatment; the remedy is cancel/refund (later the order-change substrate), not editing a frozen snapshot.- **The address is an input, never the owner.** A tax ID identifies the legal entity, not a location; Spree addresses are cloned/deduplicated value records and a bad host for identity data (Magento's address-level columns are the cautionary precedent). The billing address's existing `company` field pairs with the ID on invoices — no duplicate field.@@ -362,7 +395,7 @@ endMultiple certificates = multiple entries. Certificate *lifecycle* (verified/expired) is a resolution-time filter — only active certificates produce entries; presence of an entry is the claim. Providers translate: Avalara `reason_code` → `entityUseCode`, `certificate_number` → `exemptionNo`, item overrides → line-level codes (the generalization of what `spree_avatax_official` sends today from its user-level fields); Stripe → `taxability_override`.-**Assembly** — the `tax_resolve_exemptions_service` dependency (`Spree::Tax::ResolveExemptions`, plain Tier 1 service, `call(order:)` → array, **default returns `[]`**). Callers never build exemptions; providers never fetch them. In stock 6.0 the input is empty and the working exemption paths are provider-native certificates (Avalara merchants get durable per-customer exemption through Avalara's certificate store, needing nothing from our schema) and extensions swapping the service — the `spree_tax_avalara` gem keeping the legacy user-level `exemption_number`/`entity_use_code` as gem-owned storage is the seam's first real implementation. Company-backed `TaxExemptionCertificate` records become the default implementation's source in Phase 7, resolving into the same entries.+**Assembly** — the `tax_resolve_exemptions_service` dependency (`Spree::Tax::ResolveExemptions`, plain Tier 1 service, `call(order:)` → array, **default returns `[]`**). Callers never build exemptions; providers never fetch them. In stock 6.0 the input is empty and the working exemption paths are provider-native certificates (Avalara merchants get durable per-customer exemption through Avalara's certificate store, needing nothing from our schema) and extensions swapping the service — the `spree_tax_avalara` gem keeping the legacy user-level `exemption_number`/`entity_use_code` as gem-owned storage is the seam's first real implementation. Company-backed `TaxExemptionCertificate` records become the default implementation's source in Phase 7, resolving into the same entries — which is what the empty default was standing in for, and why the seam shipped first.**Output** — zero-amount TaxLines with `customer_exempt`/`product_exempt` reasons, per the write contract. No flags anywhere: the claim is ephemeral input, the outcome is rows.@@ -1001,7 +1034,7 @@ The dashboard cannot build a provider dropdown, nor warn that Internal should no**Re-validation is admin-only.** `POST /admin/customers/:id/tax_identifier/validate` enqueues `ValidateJob`. Without it, a check that came back `unavailable` because a registry was down could never be retried — the `after_commit` only fires when the value changes. There is deliberately **no storefront equivalent**: a customer has nothing to do with the verdict (the treatment follows the number's format), so an on-demand check would only expose registry latency and downtime to the buyer for no decision they can make. Retrying is an operator's job.-**Exemption certificates** (Phase 7): `/admin/companies/:id/tax_exemption_certificates` full CRUD, plus direct-upload for the attached document.+**Companies and exemption certificates** (Phase 7): admin CRUD for the Company tree plus nested `/admin/companies/:company_id/tax_exemption_certificates` with direct-upload for the document and a `verify` member action. No Store API — see that phase.### Lifecycle integration points@@ -1067,9 +1100,85 @@ Tax-side only — shipping keeps Zone untouched; full Zone removal is deferred t- Migrates `spree_avatax_official`'s user-level `exemption_number`/`entity_use_code` into gem-owned storage feeding `tax_resolve_exemptions_service` — the seam's first real implementation.- Documents how to build custom providers.-### Phase 7: Tax exemption certificates+### Phase 7: Company tree + tax exemption certificates++**Next up.** Ships the minimum Company surface exemptions need (see Key Decisions, 2026-08-07),+then the certificates and the `ResolveExemptions` body its empty default was standing in for. The+provider contract does not change — that is the payoff for having built the seam first.++#### Step 1 — the Company tree++```ruby+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 certificates (Key Decisions).+ if t.respond_to?(:jsonb) then 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'++ 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) then 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 :user, 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, :user_id], unique: true++ # Both, following channel_id and market_id: exemption resolves during+ # checkout, and completion copies the column onto the order.+ add_reference :spree_carts, :company_location+ add_reference :spree_orders, :company_location+ end+end+```++Models follow the conventions already in force — `Spree::SingleStoreResource` on Company (locations+and contacts reach the store through it), `Spree::Metafields` + `Spree::Metadata`, `has_prefix_id`+(`comp`, `cloc`, `cc`), `class_name` and `dependent` on every association, `Spree.user_class` for the+contact's user. Nothing carries a state machine.-Last, and **gated on Company existing** (`6.1-channels-catalogs-b2b.md`) — the only phase here with an external dependency. Nothing earlier waits on it: until this ships, exemptions work through provider-native certificates and through extensions swapping `tax_resolve_exemptions_service`.+A `Spree::Purchase::Company` concern gives Cart and Order the shared surface, mirroring+`Spree::Purchase::Channel`:++```ruby+def company+ company_location&.company+end++def b2b?+ company_location_id.present?+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.++#### Step 2 — Company joins the tax identifier chain++`spree_tax_identifiers` gains `company_id` as a fourth owner (still exactly one), with the same+`(company_id, kind)` uniqueness the customer owner has, and `#resolved_tax_identifier` becomes+cart override → company → customer → nil. A company's registration outranks the buyer's own,+because the invoice is addressed to the entity.++#### Step 3 — certificates```rubyclass CreateSpreeTaxExemptionCertificates < ActiveRecord::Migration[8.1]@@ -1085,11 +1194,7 @@ class CreateSpreeTaxExemptionCertificates < ActiveRecord::Migration[8.1]t.datetime :issued_att.datetime :expires_att.string :issuing_authority- if t.respond_to?(:jsonb)- t.jsonb :metadata- else- t.json :metadata- end+ if t.respond_to?(:jsonb) then t.jsonb :metadata else t.json :metadata endt.timestampsend@@ -1125,7 +1230,7 @@ class Spree::TaxExemptionCertificate < Spree.base_classend```-With the model in place, `Spree::Tax::ResolveExemptions` grows the body its empty default was standing in for — and this is the whole point of having built the seam first, since nothing about the provider contract changes:+#### Step 4 — the resolution body```rubydef call(order:)@@ -1145,7 +1250,35 @@ def call(order:)end```-Also in this phase: `has_many :tax_exemption_certificates` on Company, admin API CRUD for certificates, and the admin surface for uploading and verifying them.+`for_address` needs an address, so a cart with no address yet resolves nothing — consistent with+`tax_country` falling back to the market for display while real exemption waits for a destination.++#### Step 5 — Admin API++```+GET/POST /api/v3/admin/companies+PATCH/DELETE /api/v3/admin/companies/:id+POST /api/v3/admin/companies/:company_id/locations+PATCH/DELETE /api/v3/admin/company_locations/:id+POST /api/v3/admin/company_locations/:location_id/contacts+DELETE /api/v3/admin/company_contacts/:id++GET/POST /api/v3/admin/companies/:company_id/tax_exemption_certificates+PATCH/DELETE /api/v3/admin/companies/:company_id/tax_exemption_certificates/:id+PATCH /api/v3/admin/companies/:company_id/tax_exemption_certificates/:id/verify+```++Certificate creation takes a direct-upload signed blob for `document`, as the CSV importer does.+Transitions are member PATCH actions, per the returns plan's convention — no destroy on a verified+certificate, revoke instead. Scope-gated on `write_customers` (a company is a customer record), and+every lookup goes through `current_store.companies` so a certificate cannot be read across tenants.++**No Store API in this phase.** Exemption resolves server-side from the buyer's contacts, so the+storefront needs no company endpoint to get correct tax. Exposing a buyer's own company for a B2B+account area is a 6.1 question, with the gated-channel work.++**No dashboard work in this phase either.** The Company tree and certificates ship as API only;+managing them in the admin UI belongs to the B2B release.### Phase 8: 6.1 cleanup — the schema 6.0 deliberately kept@@ -1174,6 +1307,14 @@ manifest, so every install arriving at 6.1 has run them.## Constraints on Current Work+- **No `tax_exempt` boolean anywhere.** Not on Company, not on CompanyLocation, not on Customer. Exemption+ is a `Spree::TaxExemption` entry resolved from a certificate; a flag cannot name its jurisdiction or its+ lines. This supersedes the Company and CompanyLocation sketches in `6.1-channels-catalogs-b2b.md`.+- **Don't build Catalog while building Company.** Phase 7 ships Company, CompanyLocation, CompanyContact and+ certificates only. Catalog, `default_catalog_id`, per-company pricing, `Products::ForContext` and the+ CustomerGroup link stay with the B2B release, which inherits these models rather than redefining them.+- **A B2B order references `company_location`, never `company` directly.** `#company` derives through the+ location on both Cart and Order. Don't add a `company_id` column to either table.- **The provider is the only TaxLine writer.** Don't add tax computation anywhere else; don't reintroduce calculators or adjuster-side tax.- **Don't put typed tax inputs in `set_tax_line_context`.** Exemptions, tax identifiers and dates are named `estimate` parameters, assembled by `tax_resolve_exemptions_service` and `#resolved_tax_identifier`; the hook carries untyped provider extras only.- **No exemption flags on customer, order or line items.** The claim is an ephemeral `Spree::TaxExemption`; the outcome is TaxLines with reasons. Don't add ad-hoc exemption checks in controllers or services — swap `tax_resolve_exemptions_service`.@@ -1190,7 +1331,7 @@ manifest, so every install arriving at 6.1 has run them.The awkward part is that pricing five options means five *hypothetical* computations that must not be persisted, whereas `estimate` is defined as a write. That is a quote, not a write — a different operation. Roughly three ways out: scope the inline math to Internal and show nothing otherwise (honest, cheap); add a read-only `quote` to the contract that returns an amount without writing rows (correct, but earns the provider a second method, and one API call per option is expensive for external providers); or drop tax from the option labels and let it appear once a rate is chosen.- Deferrable, and deliberately left uncovered while 6.0 is in development: Phases 3–5 neither need nor are blocked by an answer, and the only knock-on is that from Phase 4 a market pointed at an external provider shows no tax on its delivery options while checkout charges the provider's — a display defect, not a collection one, since the money still comes from the provider's TaxLines. Phase 5 re-points the rate matching mechanically. The natural time to settle the design is alongside `6.0-delivery-rate-provider.md`, which owns `DeliveryRate` enrichment.+ **Still open, and now sequenced after Phase 7** (2026-08-07 — it is one of the two remaining items on PR #14410). Phases 3–5 neither need nor are blocked by an answer, and the only knock-on is that a market pointed at an external provider shows no tax on its delivery options while checkout charges the provider's — a display defect, not a collection one, since the money still comes from the provider's TaxLines. Phase 5 re-pointed the rate matching mechanically. Dropping tax from the option labels entirely stays on the table as an outcome, not just a fallback; whichever way it lands, it should be settled with `6.0-delivery-rate-provider.md`, which owns `DeliveryRate` enrichment.Resolved (previously open):- **Context key discoverability** — no declaration mechanism. `estimate`'s `context:` is the hash produced by the `set_tax_line_context` hook: extensions register handlers, each returns a hash, and `run_hooks` deep-merges them all into one before the provider is called. Whatever rides it is either documented by the gem that reads it, or — if a merchant is meant to configure it — belongs on that provider's `Spree::Integration` as a preference, where it already gets persistence and an admin form. Handlers should namespace their contribution under the provider key (`{ 'avalara' => { … } }`), because unlike `TaxLine.data`, which one provider writes onto a row already stamped with `provider_id`, this hash is merged across every registered handler and same-key contributions overwrite each other in registration order. Declaring keys the way `unsupported_capabilities` is declared was considered and rejected: validating them would make the channel typed, and a typed input deserves a named `estimate` parameter rather than a hash — `context:` exists precisely for what does not warrant a contract. The residual cost is accepted: a mistyped key is silently ignored, which is a bug in an extension that owns both ends.diff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex 48837e9316..85184dd2ee 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -1,3 +1,40 @@+## 2026-08-07: The tax plan builds the minimal Company tree; the B2B release keeps Catalog++Exemption certificates need an entity to hang off, and `Spree::Company` does not+exist — `6.1-channels-catalogs-b2b.md` targets 6.1. Rather than leave the tax+plan's last phase blocked behind a release, `6.0-tax-provider.md` Phase 7 builds+**Company → CompanyLocation → CompanyContact** plus+`Spree::TaxExemptionCertificate`, and the B2B release inherits those models+instead of defining them.++**Why the whole tree and not just Company.** The contact record is what lets a+logged-in B2B buyer's own cart resolve a company without staff touching the+order. Company alone would mean exemption works only on admin-created orders —+the wrong limitation for a self-serve wholesale channel. The location is what+the Cart and Order reference (`company_location_id` on both, following+`channel_id`/`market_id`), because that is the FK the B2B plan already specifies+for orders; a direct `company_id` would save one hop now and cost a schema+reversal later.++**Supersedes the B2B plan on one point: no `tax_exempt` boolean.** That plan's+Company and CompanyLocation sketches both carry one. It is not being built. A+flag cannot say which jurisdiction it holds in or which lines it covers, and+removing the boolean `exempt?` from the provider contract was the substance of+the 2026-08-05 refinement — reintroducing it a layer down would undo it.+Exemption is a certificate resolved into a typed `Spree::TaxExemption` entry.+**`6.1-channels-catalogs-b2b.md` still needs this note added to its own Key+Decisions** — deliberately not edited yet, at the author's instruction.++**Explicitly not pulled forward:** Catalog, CatalogProduct, CatalogAssignment,+`default_catalog_id`, per-company pricing, `Products::ForContext` visibility, the+Company → CustomerGroup link, and roles/approvals/purchase limits/invoicing.+Certificates hang off Company scoped by their own country/state columns, so no+per-location duplication.++**Constraint going forward:** pulling a model forward out of another plan takes+the model, not the feature. If a field only makes sense for the deferred feature,+it waits with it.+## 2026-08-07: The pricing zone dimension ships with the tax provider, but the price-rule design stays with delivery-zones`6.0-delivery-zones.md`'s ownership table gives the `Pricing::Context` zone