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
Merge branch 'main' into feature/v-3526
Łukasz Adamczyk703bbc570f39
diff --cc docs/plans/decisions.mdindex 85184dd2ee,71833a49c9..589becc8cc--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@@ -1,76 -1,90 +1,163 @@@+ ## 2026-08-09: Metadata consolidated to one column — `public_metadata` dropped, `private_metadata` renamed++ Implements the 2026-03-16 consolidation decision. All thirty metadata-carrying+ tables lose `public_metadata` and have `private_metadata` renamed to `metadata`,+ so the column, the accessor and the API field finally share one name.+ `Spree::Metadata` keeps its place but collapses to a single attribute plus the+ `HashSerializer` — the alias indirection that made `metadata` a method forwarding+ to another column is gone. `Spree::Collection`, which had been declaring its own+ consolidated column to sidestep the concern, now just includes it.++ **Three shape decisions.**++ *`public_metadata` data is preserved, not discarded.* The original note called the+ column unused, which holds for Spree's own code — nothing read it, and it was+ never exposed in the Store API — but is not provably true of host applications+ that had a writable JSON column sitting there for four years. A dropped column has+ no rollback, so `spree:upgrade:consolidate_metadata` merges it into+ `private_metadata` first, private winning on key collision since that is the side+ the accessor and the API always read.++ *The merge lives inside the migration, not in a manifest step.* The obvious home+ was a pre-migration upgrade task, but `spree:upgrade` runs manifests *after*+ `db:migrate` — both the rake runner and the CLI's upgrade command sequence it that+ way. A merge scheduled there would find `public_metadata` already dropped and+ silently do nothing, losing exactly the data it existed to protect. Documentation+ telling operators to run a step "before migrate" would have been asking them to+ fight their own tooling. `spree:upgrade:consolidate_metadata` stays in the manifest+ as a safety net for schemas changed out of band, not as the primary path.++ *The rename is `rename_column`, not add-and-backfill.* Instant on PostgreSQL and+ MySQL, data stays in place.++ *No hardcoded table lists, in either direction.* Legacy tables are discovered by+ column: the pair was added across a dozen migrations and several of those tables have+ since been renamed (`spree_shipping_methods`, `spree_prototypes`, `spree_taxons`), so+ a static list would already be wrong. Rollback needs the inverse answer, and shape+ cannot supply it — a table we renamed and one born with a single `metadata` column look+ identical afterwards. An early version hardcoded the exclusions and was doubly wrong:+ it missed `spree_customers`, and it would have swept up `active_storage_blobs`, whose+ unrelated `metadata` column a shape-based rollback would have renamed, breaking every+ attachment. `up` now records what it renames and `down` reverses exactly that.++ Both the migration and the task use raw SQL rather than Active Record. Beyond the+ models already pointing at the new name, PostgreSQL has no equality operator for+ `json`, so `where.not(public_metadata: [nil, {}])` raises `PG::UndefinedFunction` —+ green on SQLite, broken on the databases most production installs actually run.++ **No bridge for `public_metadata`** — a recorded exception to the "every 6.0 rename+ keeps the legacy name one release" convention. The column is being removed rather+ than renamed, and it already carried a deprecation warning through 5.x.+ `private_metadata` does get the usual one-release bridge with a warning.++ **What this does not change.** Metadata and metafields stay two systems. Metadata+ is the schemaless developer escape hatch — no definition, write-only from the+ Store API's perspective, for integration ids and sync state. Metafields (custom+ fields) stay merchant-defined structured data with types, definitions and+ storefront visibility. Customer-visible structured data belongs in a metafield,+ never in metadata.++ Plan: `docs/plans/6.0-consolidate-metadata-columns.md`.++## 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+dimension and the `Spree::Current` zone attribute to that plan, "with+tax-provider". It landed in the tax provider work instead, because the two+cannot be separated: `Pricing::Context.from_order` read `order.tax_zone`, so it+broke the moment `Purchase::Taxation#tax_zone` was removed — which the same+table assigns to the tax plan.++`Spree::Current.tax_country` returns a `Spree::Country` rather than the ISO+string that plan's constraints section specified, matching the already-shipped+`Purchase::Taxation#tax_country`. An ISO code would mean a country lookup on+every read, and the price rule compares stored ids.++**Where the line was drawn.** `PriceRules::ZoneRule` also reads the zone+dimension, so it had to change or crash. It now decides by country, keeps its+class name (the `type` column persists it), stays out of the rule registry, and+`spree:migrate_tax_zones` restates each row's stored zones as the countries they+contained — state-level zones widen to the whole country, which the task+reports. What was **not** done: promoting it to a first-class `CountryRule` with+a factory and a registry entry. That is a customer-visible pricing feature no+plan called for, and it belongs to the plan that owns Zone's removal.++**Constraint going forward:** "something must change or it crashes" licenses the+minimum that keeps it working, not a redesign. When a forced edit reaches into+another plan's surface, do the minimum and hand the design decision back in that+plan's own document.++**Corollary (2026-08-07).** The same reasoning ruled out guarding the window+between `db:migrate` and the data task. A review found that an unconverted rule+matches every country, and the first fix made such a row refuse to apply. That+was also scope creep: the 6.0 data tasks are steps in the upgrade manifest, so+"code deployed, task not yet run" is not a state Spree supports, and inventing+behaviour for it adds a permanent branch to a hot path to cover a transient.+Don't design for half-upgraded installs; make the task correct and say what it+did.+ ## 2026-08-07: `Claim#claim_type` dropped — the reason vocabulary is the only "what went wrong" axis++ Reverses the two-axis design in `6.0-returns-exchanges-claims.md`, which+ paired a fixed `claim_type` (damaged / missing / wrong_item / other) with+ the merchant-owned `Spree::ClaimReason`. The column, its+ `class_attribute` list, the validation, the API field and the dashboard+ "Problem" picker are all removed; `reason` stays, still optional.++ **Why.** The two fields asked the merchant the same question twice. The+ seeded claim reasons made it plain — "Arrived damaged" next to type+ `damaged`, "Wrong item sent" next to `wrong_item`. Worse, `claim_type`+ was required and unmodifiable while earning nothing: no code ever+ branched on it (the model comment conceded "pure labels with no per-type+ behaviour"), unlike `resolution`, which is closed precisely because each+ value drives `Claims::Resolve`. Return and Exchange already carry a+ reason and no type column, so dropping it makes all three consistent.++ The coarse-fixed-axis-for-reporting argument is real but unearned here:+ nothing reported on it. A future reporting need is better served by+ grouping reasons than by a second required field.++ **Migration.** `spree_claims.claim_type` is dropped in+ `20260807120001_remove_claim_type_from_spree_claims.rb`. The 6.0 tables+ are unreleased, but the creating migration already shipped to `6-0-dev`+ and `main`, so this is a follow-up drop rather than an edit in place.+ The Store API claims endpoint gains `reason_id`, which it never accepted.## 2026-08-06: A product type's `required` custom field is advisory — no server-side enforcement@@@ -1688,18 -1597,147 +1782,162 @@@ and `Spree::CalculatedAdjustments` resoseparately. Extract a `Spree::RegisteredSubclasses` concern when a familyneeds the registry without preferences — that second consumer is thetrigger, and it would absorb CalculatedAdjustments too.+## 2026-08-06 — Converted-away columns outlive the release that converts them++`spree_tax_rates.zone_id` stays in the schema through 6.0 even though+nothing reads it, and is dropped in 6.1. The reason is ordering, and it+generalizes: a data task named in the upgrade manifest runs *after*+`db:migrate`, so a migration that removes the task's input column in the+same release destroys the data the task exists to convert — and leaves a+merchant no source to re-run from if the conversion needs repeating.+Tax rates therefore gain `country_id`/`state_id`, every `zone_id` reader+is severed (the association, the zone scopes, and `Zone#has_many+:tax_rates`, whose `dependent: :destroy` would otherwise delete live+rates when a shipping zone is destroyed), and the column is left in+place, unread. `spree_adjustments` already worked this way under+`migrate_adjustments_to_typed_rows`, which keeps the legacy table as its+rollback source; treat that as the pattern rather than the exception.++ ## 2026-08-07 — StateChange and LogEntry removed; lifecycle events are the only audit++ **Decision:** Delete `Spree::StateChange` and `Spree::LogEntry` in 6.0 — models,+ associations, state-machine writers, `Payment::Processing#record_response`,+ `Refund#create_log_entry` and the `Order#log_state_changes` shell. This+ supersedes the cart/order-split note that payment/fulfillment machines keep+ their `StateChange` rows.++ **Why:** Both were write-only. Nothing in the 6.0 codebase — no serializer, no+ API endpoint, no dashboard page, no event payload — ever read them back; the+ legacy Rails admin screens that displayed them are gone. Lifecycle events+ (`payment.completed`/`voided`, `fulfillment.ready`/`fulfilled`/`canceled`/+ `resumed`, `order.*`) are the sanctioned audit, the same call already made for+ Order rows. Removing LogEntry also retires YAML-serialized gateway responses+ in the database (a historic deserialization CVE surface); gateway dashboards+ and `PaymentSession` own transaction forensics now.++ **Tables survive to 6.1:** `spree_state_changes` and `spree_log_entries` stay+ (same pattern as the returns-chain tables). The 5.6→6.0 upgrade tasks that+ touch legacy rows (`migrate_incomplete_orders_to_carts`,+ `migrate_shipping_to_delivery`) read the table through anonymous ActiveRecord+ classes. Both tables drop in 6.1 alongside `spree_adjustments`.++ **Kept:** `Spree::PaymentCaptureEvent` — functional money data, not audit:+ `Payment#captured_amount` sums it, partial capture and capture-on-dispatch+ depend on it, and the Admin API exposes `captured_amount`.++ ## 2026-08-07 — Admin RBAC: one grant system, staff-only, catalog = scope vocabulary++ **Decision:** (from spree/spree#14164; plan `6.0-admin-rbac.md`) Role+ permissions become database-backed as flat `read_<resource>` /+ `write_<resource>` keys — the same vocabulary secret API keys use. One+ declarative catalog (resource → CanCanCan subjects → UI group) is the single+ source of truth: `Spree::ApiKey::SCOPES` derives from it, and the dashboard+ role editor and API-key scope picker share one `PermissionPicker` fed by+ `GET /api/v3/admin/permissions`. **Permission sets are deleted at 6.0 with NO+ compatibility bridge** — a deliberate exception to the one-release-bridge+ convention: this is a system removal, not a rename, and a shim would carry the+ runtime-union machinery the removal exists to kill. Old initializers fail+ loudly at boot (`NameError` on the deleted constants; `assign` raises with an+ upgrade-guide pointer). **Roles are pure data:** no `Spree.permissions.grant`,+ no runtime merge, no union — the editor is WYSIWYG; "roles as code" is seeds+ (plain ActiveRecord) or the Admin API; extensions register catalog resources,+ never roles (matching Saleor/Vendure/Shopify — roles are rows everywhere). A+ `mutable` column (NamedType pattern) covers locked roles: admin seeds+ `mutable: false`; hosts can lock compliance roles the same way. Record-level+ custom rules migrate to a `Spree::Dependencies.ability_class` swap — the one+ low-level escape hatch (`register_ability` was dropped with the sets, 6.0+ having no undocumented registration API to inherit).+ Upgrade is fail-closed: pre-existing custom role rows come up with empty+ permissions until filled in the editor. Enforcement unifies on+ the key gate: `ScopedAuthorization` generalizes so every admin request — JWT+ staff or secret key — checks its principal key set against+ `<read|write>_<scoped_resource>`; CanCanCan is demoted to internal plumbing+ behind it (still compiled from keys; nothing public configures it; dropping it+ from the admin path is a 6.1 option, not a goal). A new `staff` pair splits+ out of `settings`; admin-role protection moves onto the `Spree::Role` model+ (NamedType precedent — sk principals never consult CanCanCan). Resource+ granularity reaffirmed; full-page editor; client-side templates, no seeds.++ **The system is staff-only.** The storefront has no roles: `:default` /+ `DefaultCustomer` cease to be public concepts and the customer baseline+ (ownership conditions, guest tokens) becomes internal ability code, with+ scope-fetching the primary enforcement. Role resolution runs only for+ admin-user principals (aligns with the platform-auth Customer/Staff split, and+ drops a per-request `role_users` query for customers). B2B company-account+ roles (buyer/approver, hierarchies, spend limits — Enterprise) are explicitly+ a separate future system: the vocabulary must not be shared (`write_orders`+ means "manage the store's orders" to staff and "place my company's orders" to+ a purchaser), matching commercetools/Shopify B2B/Medusa, which all keep+ account roles apart from staff RBAC. Catalog/product visibility per customer+ group or company is data scoping, never a permission key.++ **Why:** the hard parts already shipped — the scope vocabulary and+ per-controller `scoped_resource` declarations (5.5), the `RoleGrantGuard`+ escalation check, store-scoped `RoleUser` assignments resolved per store by+ `Spree::Ability`, and the `/me` rules dump the SPA mirrors. Unifying on them+ turns "build an RBAC system" into "expose the one that exists". Two softer+ designs were drafted and rejected the same day: sets kept as bundles over the+ catalog, then a one-release `assign` bridge with an import task — each+ preserved grant-source duality (union semantics, locked "granted in code"+ rows, mixed escalation math) purely for back-compat comfort, in the release+ whose point is the breaking window, for a migration that is genuinely a+ five-minute UI task.++ **Reviewer constraints:** no new `PermissionSets::` classes or `assign` calls+ anywhere; every model a new admin controller authorizes must be covered by a+ catalog entry, or custom roles cannot reach the endpoint; new sensitive+ resources get their own catalog resource instead of riding `settings`;+ storefront code must never consult `Spree::Role` or the catalog.++ ## 2026-08-08 — Store API drops CanCanCan; storefront access is a swappable policy++ **Decision:** The Store API (v3) no longer consults CanCanCan anywhere.+ `Spree::Ability` is staff-only — a customer principal's ability has no rules —+ and the generic `authorize_resource!`/`authorize_parent!` hooks plus the+ `accessible_by` collection filter moved from the shared v3 `ResourceController`+ down to the Admin branch. Storefront authorization is ownership: account+ controllers read through `current_user` (scope-fetching, unchanged), catalog+ endpoints have no per-record check (the old `accessible_by` calls sat on+ unconditional `can :read` grants — no-op filters), and the two checks a scope+ cannot express — cart/order access proven by JWT ownership OR a guest token,+ plus the guest-token order-listing scope — live in+ `Spree::Storefront::AccessPolicy`, swappable via+ `Spree::Dependencies.storefront_access_policy_class`. Denials raise+ `Spree::Storefront::AccessDenied`, rendered identically to CanCan's 403.++ **Why:** Two reasons converged. First, the storefront never needed a rule+ engine — its "rules" were ownership conditions and token blocks, and CanCanCan+ block rules can't power `accessible_by`, so controllers carried both a scope+ AND an `authorize!` for the same fact. Second, the Enterprise B2B module+ (`6.1-channels-catalogs-b2b.md`) must extend storefront authority without+ decorating controllers, and a policy object is the right seam: **access+ widening** (approver sees company-location purchases) = subclass the policy and+ override `scope`/`readable?`/`writable?`; **action vetoes** (approvals,+ spending limits) = checkout workflow `validate` hooks; **catalog visibility**+ (per-location catalogs) = the products-for-context data scoping. Enterprise+ implements, open source owns the seams. Competitors ship no storefront rule+ engine (Medusa/Saleor/Vendure); Shopify B2B contact permissions are fixed+ server-side roles.++ **Consequences:** Extensions must not add storefront `can` rules or call+ `authorize!` in Store API controllers — widen the access policy or hook a+ workflow instead. The admin side is untouched: staff JWT + CanCanCan, secret+ keys + scopes. `register_ability`/`remove_ability` are gone with the sets+ (`Spree::Dependencies.ability_class` is the admin-side escape hatch).++ **Alternative considered and rejected (2026-08-08):** a dedicated storefront+ ability class fed by permission sets — two abilities, staff (catalog keys) and+ storefront (sets/code). Rejected on three grounds: a storefront rule engine+ only means something if store controllers consult it, which restores the+ scope-plus-`authorize!` dual bookkeeping across the store surface; OSS+ customers are all identical, so a storefront set registry would hold exactly+ one configuration (the old `DefaultCustomer`) — code plus registry+ indirection; and the B2B requirement itself decides it — a company admin+ managing roles/employees in a UI needs **data** roles (Enterprise+ `CompanyRole` with capability keys, the commercetools associate-roles shape),+ which code-defined sets cannot provide. The policy protocol is generic+ (`readable?`/`writable?`/`scope` with an ownership default), so wishlists,+ newsletter subscriptions and any new resource route through the same seam+ with no wiring; `/customers/me/*` endpoints stay owner-scoped by definition.+ Full B2B architecture: `6.1-channels-catalogs-b2b.md` → "Company roles and+ approvals".diff --cc packages/admin-sdk/src/types/generated/Order.tsindex d2822bdbca,510fbfb1f2..fec655fbfa--- a/packages/admin-sdk/src/types/generated/Order.ts+++ b/packages/admin-sdk/src/types/generated/Order.ts@@@ -1,4 -1,4 +1,4 @@@- // Typelizer digest 8774fcb5d4c850b70bcaa90661e0bd01-// Typelizer digest 9aa6d70adeda31f8c3a08e690176a893++// Typelizer digest 2e2618d1b70cf93bc0457d029f9c8869//// DO NOT MODIFY: This file was automatically generated by Typelizer.import type {LineItem, Fulfillment, Payment, Address, GiftCard, Market, AppliedPromotion, Cart, Channel, StockLocation, PaymentMethod, Customer, Return, Exchange, Claim} from '@/types'@@@ -61,10 -61,9 +61,11 @@@ interface Ordercreated_at: string;updated_at: string;preferred_stock_location_id: string | null;+ company_location_id: string | null;+ company_id: string | null;tags: Array<string>;internal_note: string | null;+ internal_note_html: string | null;approver_id: string | null;canceler_id: string | null;created_by_id: string | null;diff --cc packages/admin-sdk/src/types/generated/index.tsindex a85077bf1b,e4a1531539..7fa2dd7664--- a/packages/admin-sdk/src/types/generated/index.ts+++ b/packages/admin-sdk/src/types/generated/index.ts@@@ -1,4 -1,4 +1,4 @@@- // Typelizer digest 44bba369cb8612b6bc47f1f2e86fc75a-// Typelizer digest 4e3a26ed9e48909a90dcc0964ceec485++// Typelizer digest 0860d2a5cb38d80c615d11ec68e6aed1//// DO NOT MODIFY: This file was automatically generated by Typelizer.export type { default as Address } from './Address'diff --cc packages/sdk/src/types/generated/index.tsindex 59e8582fb7,6e1be420a4..2684c0a9ab--- a/packages/sdk/src/types/generated/index.ts+++ b/packages/sdk/src/types/generated/index.ts@@@ -1,4 -1,4 +1,4 @@@- // Typelizer digest 633530336b8aac863cf9cdd6fd46b204-// Typelizer digest ae998f49fd8e4ed3c6fe6a0794257bef++// Typelizer digest dc5a3838d4af3d442982ce86b5cbc28d//// DO NOT MODIFY: This file was automatically generated by Typelizer.export type { default as Address } from './Address'diff --cc spree/api/app/controllers/spree/api/v3/store/orders/tax_identifiers_controller.rbindex ae3a4ff819,0000000000..7a1ae5053emode 100644,000000..100644--- a/spree/api/app/controllers/spree/api/v3/store/orders/tax_identifiers_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/orders/tax_identifiers_controller.rb@@@ -1,55 -1,0 +1,46 @@@+module Spree+ module Api+ module V3+ module Store+ module Orders+ # Read-only: an order's registration is the snapshot taken when it was+ # placed, and an invoice has to keep saying what it said.+ class TaxIdentifiersController < Store::BaseController+ # GET /api/v3/store/orders/:order_id/tax_identifier+ def show+ return head :not_found if order.tax_identifier.nil?++ render json: serialize_resource(order.tax_identifier)+ end++ protected++ def serializer_class+ Spree.api.tax_identifier_serializer+ end++ private++ # The order is the customer's own — by JWT or by guest token,- # mirroring Store::Orders::ReturnsController.++ # mirroring Store::Orders::ReturnsController. The scope is the++ # enforcement: an order the caller does not own is simply not found.+ def order+ @order ||= begin+ cart_pk = Spree::Cart.decode_own_prefixed_id(params[:order_id])- found = if cart_pk- order_scope.find_by!(cart_id: cart_pk)- else- order_scope.find_by_prefix_id!(params[:order_id])- end- authorize!(:show, found, order_token)- found++ if cart_pk++ order_scope.find_by!(cart_id: cart_pk)++ else++ order_scope.find_by_prefix_id!(params[:order_id])++ end+ end+ end++ def order_scope- base = current_store.orders.complete-- if current_user.present?- base.where(customer: current_user)- elsif order_token.present?- base.where(token: order_token)- else- base.none- end++ storefront_access_policy.scope(current_store.orders.complete, token: order_token)+ end+ end+ end+ end+ end+ end+enddiff --cc spree/core/app/models/spree/company.rbindex 79db4ba5c4,0000000000..5396baef79mode 100644,000000..100644--- a/spree/core/app/models/spree/company.rb+++ b/spree/core/app/models/spree/company.rb@@@ -1,45 -1,0 +1,45 @@@+module Spree+ # A business customer — the entity an invoice is addressed to, as distinct+ # from the person who placed the order. Carries the tax registration and the+ # exemption certificates that decide how its purchases are taxed.+ #+ # Deliberately minimal: this is the part of the B2B model that tax needs+ # (docs/plans/6.0-tax-provider.md Phase 7). Assortment, negotiated pricing+ # and buyer roles belong to docs/plans/6.1-channels-catalogs-b2b.md, which+ # extends these models rather than redefining them.+ class Company < Spree.base_class+ has_prefix_id :comp++ include Spree::SingleStoreResource- include Spree::Metafields++ include Spree::HasCustomFields++ publishes_lifecycle_events++ # Single consolidated metadata JSON column (docs/plans/decisions.md+ # 2026-03-16 "Consolidate metadata") — write-only developer escape hatch.+ attribute :metadata, default: -> { {} }++ belongs_to :store, class_name: 'Spree::Store', inverse_of: :companies++ has_many :company_locations, class_name: 'Spree::CompanyLocation', dependent: :destroy,+ inverse_of: :company+ has_many :company_contacts, through: :company_locations+ has_many :tax_identifiers, class_name: 'Spree::TaxIdentifier', dependent: :destroy,+ inverse_of: :company+ has_many :tax_exemption_certificates, class_name: 'Spree::TaxExemptionCertificate',+ dependent: :destroy, inverse_of: :company++ validates :name, presence: true+ # Paired with the partial unique index, per the convention — without it a+ # duplicate reference reaches the database and surfaces as a 500 rather+ # than a validation error. Nil is exempt on both sides.+ validates :external_id, uniqueness: { scope: [:store_id, *spree_base_uniqueness_scope] }, allow_nil: true++ self.whitelisted_ransackable_attributes = %w[name external_id]+ self.whitelisted_ransackable_associations = %w[company_locations]++ def event_serializer_class+ 'Spree::Api::V3::CompanySerializer'.safe_constantize+ end+ end+enddiff --cc spree/core/app/models/spree/company_location.rbindex 4d492e0bfc,0000000000..71d90fb4f7mode 100644,000000..100644--- a/spree/core/app/models/spree/company_location.rb+++ b/spree/core/app/models/spree/company_location.rb@@@ -1,42 -1,0 +1,42 @@@+module Spree+ # A branch or office of a business customer. Reaches the store through its+ # company and so carries no store_id of its own.+ #+ # Its addresses are created inline and owned outright — a branch address is+ # the branch's, not a row shared with the buyer's address book, which is why+ # they are destroyed with it (docs/plans/decisions.md 2026-08-07).+ class CompanyLocation < Spree.base_class+ has_prefix_id :cloc+- include Spree::Metafields++ include Spree::HasCustomFields++ attribute :metadata, default: -> { {} }++ belongs_to :company, class_name: 'Spree::Company', inverse_of: :company_locations+ belongs_to :billing_address, class_name: 'Spree::Address', optional: true, dependent: :destroy+ belongs_to :shipping_address, class_name: 'Spree::Address', optional: true, dependent: :destroy++ # update_only, so editing one field of an existing address changes that+ # row instead of building a replacement and orphaning the old one.+ accepts_nested_attributes_for :billing_address, update_only: true+ accepts_nested_attributes_for :shipping_address, update_only: true++ # The API reads and writes these under the same name, so the writer takes+ # either a record or the nested hash a client sends.+ %i[billing_address shipping_address].each do |name|+ define_method(:"#{name}=") do |value|+ value.is_a?(Hash) || value.is_a?(ActionController::Parameters) ? send(:"#{name}_attributes=", value) : super(value)+ end+ end++ has_many :company_contacts, class_name: 'Spree::CompanyContact', dependent: :destroy,+ inverse_of: :company_location+ has_many :customers, through: :company_contacts, source: :customer++ validates :name, presence: true++ delegate :store, :store_id, to: :company++ self.whitelisted_ransackable_attributes = %w[name external_id]+ end+enddiff --cc spree/core/app/models/spree/order.rbindex 615da857e2,ae00a54cfb..b9a45509ad--- a/spree/core/app/models/spree/order.rb+++ b/spree/core/app/models/spree/order.rb@@@ -19,8 -19,8 +19,9 @@@ module Spreextend Spree::DisplayMoneyinclude Spree::SingleStoreResource+ include Spree::SanitizableRichTextinclude Spree::Purchase::Channel+ include Spree::Purchase::Companyinclude Spree::Purchase::Marketinclude Spree::Purchase::Currencyinclude Spree::Purchase::Locale@@@ -39,7 -39,8 +40,7 @@@include Spree::NumberIdentifierpublishes_lifecycle_events- include Spree::Metafields- include Spree::MemoizedData+ include Spree::HasCustomFieldsinclude Spree::Metadatainclude Spree::Searchableif defined?(Spree::Security::Orders)@@@ -50,8 -51,11 +51,9 @@@endhas_secure_token :token, length: 35- has_rich_text :internal_note++ has_spree_rich_text :internal_note- MEMOIZED_METHODS = %w(tax_zone)-money_methods :outstanding_balance, :item_total, :adjustment_total,:included_tax_total, :additional_tax_total, :tax_total,:delivery_total, :discount_total, :total,diff --cc spree/core/app/models/spree/tax_exemption_certificate.rbindex 516a6bb737,0000000000..35edbe13famode 100644,000000..100644--- a/spree/core/app/models/spree/tax_exemption_certificate.rb+++ b/spree/core/app/models/spree/tax_exemption_certificate.rb@@@ -1,103 -1,0 +1,103 @@@+module Spree+ # A business customer's evidence that some or all of its purchases are not+ # taxed — a resale certificate, a government exemption, a charity's own-use+ # claim. Resolved into ephemeral {Spree::TaxExemption} entries at estimate+ # time; the zero-amount tax rows a provider writes are the durable record of+ # what was claimed.+ #+ # Scoped by jurisdiction rather than duplicated per branch: a certificate+ # valid in one state and not the next is the ordinary case, and the country+ # and state columns say exactly where it holds.+ class TaxExemptionCertificate < Spree.base_class+ has_prefix_id :cert++ include Spree::HasStatus- include Spree::Metafields++ include Spree::HasCustomFields++ attribute :metadata, default: -> { {} }++ # A status column moved between values by a workflow — never a callback,+ # and never a state machine.+ has_status :pending, :verified, :expired, :revoked, default: :pending++ belongs_to :company, class_name: 'Spree::Company', inverse_of: :tax_exemption_certificates+ belongs_to :country, class_name: 'Spree::Country', optional: true+ belongs_to :state, class_name: 'Spree::State', optional: true+ belongs_to :verified_by, class_name: Spree.admin_user_class.to_s, optional: true++ # Confidential, so the private service rather than the public one that+ # serves product images.+ has_one_attached :document, service: Spree.private_storage_service_name++ validates :certificate_number, :reason_code, presence: true++ before_validation :resolve_state_code+ validate :state_belongs_to_country++ # Expiry is decided here rather than persisted: the date is the fact, and a+ # sweeper writing 'expired' would only restate it. Matches how gift cards+ # and stock reservations treat their own deadlines.+ scope :active, -> { verified.where('expires_at IS NULL OR expires_at > ?', Time.current) }+ scope :expired, -> { where(status: 'expired').or(where('expires_at <= ?', Time.current)) }+ # No address means no jurisdiction to match, which is not the same as+ # "matches the certificates valid everywhere" — a swapped-in resolver+ # calling this without a destination must not be handed a claim.+ scope :for_address, lambda { |address|+ next none if address.nil?++ where(country: [address.country, nil].uniq).where(state: [address.state, nil].uniq)+ }++ self.whitelisted_ransackable_attributes = %w[certificate_number reason_code status expires_at]++ delegate :store, :store_id, to: :company++ # The jurisdiction is written in the same vocabulary it is read in, mirroring+ # Spree::TaxRate. State abbreviations repeat across countries, so the state+ # is resolved in a callback once the country is known — a JSON body may name+ # the state first.+ def country_iso=(value)+ self.country = value.present? ? Spree::Country.by_iso(value) : nil+ end++ def state_code=(value)+ @state_code_input = value+ end++ # Accepting a certificate is a decision on record; withdrawing it is+ # revocation, not deletion.+ def can_be_deleted?+ !verified?+ end++ # Whether the date has passed, regardless of what the column says.+ def lapsed?+ expires_at.present? && expires_at <= Time.current+ end++ # Nothing writes the 'expired' status — the date is the fact — so the+ # predicate and scope HasStatus generated would answer false and empty+ # forever. Both derive instead, the way Spree::GiftCard does, so a caller+ # reaching for the obvious name gets the truth.+ def expired?+ status == 'expired' || lapsed?+ end++ private++ def resolve_state_code+ return unless defined?(@state_code_input)++ self.state = @state_code_input.blank? ? nil : Spree::State.where(country_id: country_id).find_by(abbr: @state_code_input)+ remove_instance_variable(:@state_code_input)+ end++ # A certificate whose state sits in another country would never match an+ # address — the two columns have to agree.+ def state_belongs_to_country+ return if state.nil? || country.nil? || state.country_id == country_id++ errors.add(:state, :invalid)+ end+ end+enddiff --cc spree/core/app/models/spree/tax_rate.rbindex 9791504e0a,2964ec62d3..e78c356682--- a/spree/core/app/models/spree/tax_rate.rb+++ b/spree/core/app/models/spree/tax_rate.rb@@@ -5,18 -5,13 +5,18 @@@ module Spreclass TaxRate < Spree.base_classhas_prefix_id :tax+ # Rates name their country and state directly since 6.0. No code reads+ # zone_id any more, but the column stays in the database through 6.0: it is+ # what `spree:migrate_tax_zones` converts from, and that task runs after+ # db:migrate. The physical drop lands in 6.1.+acts_as_paranoid- include Spree::Metafields+ include Spree::HasCustomFieldsinclude Spree::Metadata+ include Spree::SingleStoreResourcewith_options inverse_of: :tax_rates do- belongs_to :zone, class_name: 'Spree::Zone', optional: truebelongs_to :tax_category,class_name: 'Spree::TaxCategory'enddiff --cc spree/core/app/services/spree/seeds/all.rbindex 94636ad65c,8e3f5fbe46..38d81e37f2--- a/spree/core/app/services/spree/seeds/all.rb+++ b/spree/core/app/services/spree/seeds/all.rb@@@ -15,8 -15,8 +15,7 @@@ module SpreRoles.call# additional data- ReturnsEnvironment.callStoreCreditCategories.call- TaxCategories.callDigitalDelivery.call# store & stock location@@@ -27,9 -27,9 +26,10 @@@# add store resourcesPaymentMethods.call+ TaxCategories.callProductTypes.callCustomerGroups.call+ ReturnsEnvironment.callApiKeys.callAllowedOrigins.callenddiff --cc spree/core/lib/spree/core/permission_configuration.rbindex 308530f887,7edcabe3fe..3908d14dad--- a/spree/core/lib/spree/core/permission_configuration.rb+++ b/spree/core/lib/spree/core/permission_configuration.rb@@@ -122,8 -225,68 +225,71 @@@ module Spreprivate- def normalize_role_name(role_name)- role_name.to_s.downcase.to_sym+ # The core vocabulary — one entry per Admin API scope resource. Subjects+ # are lambdas so model classes resolve at activation, not load, time.+ # rubocop:disable Metrics/MethodLength+ def register_default_resources+ register_resource(:orders, group: :orders, subjects: -> {+ [Spree::Order, Spree::LineItem, Spree::TaxLine, Spree::Discount, Spree::Fee,- Spree::Return, Spree::Exchange, Spree::Claim, Spree::CustomField]++ Spree::Return, Spree::Exchange, Spree::Claim, Spree::TaxIdentifier,++ Spree::CustomField]+ })+ register_resource(:payments, group: :orders, subjects: -> { [Spree::Payment] })+ register_resource(:fulfillments, group: :orders, subjects: -> { [Spree::Fulfillment] })+ register_resource(:refunds, group: :orders, subjects: -> { [Spree::Refund] })+ register_resource(:gift_cards, group: :orders, subjects: -> {+ [Spree::GiftCard, Spree::GiftCardBatch]+ })+ register_resource(:store_credits, group: :orders, subjects: -> { [Spree::StoreCredit] })++ register_resource(:products, group: :catalog, subjects: -> {+ [Spree::Product, Spree::ProductType, Spree::Variant, Spree::OptionType,+ Spree::OptionValue, Spree::Price, Spree::PriceList, Spree::PriceRule,+ Spree::Asset, Spree::ProductPublication, Spree::CustomField]+ })+ register_resource(:categories, group: :catalog, subjects: -> {+ [Spree::Category, Spree::ProductCategory]+ })+ register_resource(:collections, group: :catalog, subjects: -> {+ [Spree::Collection, Spree::ProductCollection, Spree::CollectionRule]+ })+ register_resource(:stock, group: :catalog, subjects: -> {+ [Spree::StockItem, Spree::StockLocation, Spree::StockMovement,+ Spree::StockTransfer, Spree::StockReservation]+ })++ register_resource(:promotions, group: :marketing, subjects: -> {+ [Spree::Promotion, Spree::PromotionRule, Spree::PromotionAction,+ Spree::PromotionCategory, Spree::CouponCode, Spree::CustomField]+ })++ register_resource(:customers, group: :customers, subjects: -> {+ [Spree.customer_class, Spree::Address, Spree::CreditCard, Spree::CustomerGroup,++ Spree::Company, Spree::CompanyLocation, Spree::CompanyContact,++ Spree::TaxIdentifier, Spree::TaxExemptionCertificate,+ Spree::CustomField]+ })++ register_resource(:settings, group: :settings, subjects: -> {+ [Spree::Store, Spree::PaymentMethod, Spree::Gateway, Spree::DeliveryMethod,+ Spree::DeliveryMethodRule, Spree::DeliveryZone, Spree::DeliveryZoneMember,+ Spree::StockLocation, Spree::ShippingCategory, Spree::Zone, Spree::ZoneMember,+ Spree::Market, Spree::TaxCategory, Spree::TaxRate, Spree::AllowedOrigin,+ Spree::RefundReason, Spree::ReturnReason, Spree::ClaimReason, Spree::Channel,+ Spree::OrderRoutingRule, Spree::CustomFieldDefinition, Spree::Policy,+ Spree::StoreCreditCategory]+ })+ register_resource(:webhooks, group: :settings, subjects: -> {+ [Spree::WebhookEndpoint, Spree::WebhookDelivery]+ })++ register_resource(:api_keys, group: :access, subjects: -> { [Spree::ApiKey] })+ register_resource(:staff, group: :access, subjects: -> {+ [Spree.admin_user_class, Spree::Invitation, Spree::Role, Spree::RoleUser]+ })++ register_resource(:dashboard, group: :analytics, subjects: -> { [:dashboard] }, write: false)end+ # rubocop:enable Metrics/MethodLengthendend