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.

Merge remote-tracking branch 'origin/main' into feature/v-3526

Damian Legawiece5cb179333eb
diff --cc CLAUDE.md
index 3f4276ab5c,7acd340a8e..7ff8dbc357
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@@ -25,7 -26,8 +26,8 @@@ 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. Pickup work beyond shipped code deferred to 6.1 (2026-08-06): contract hardening (`new(delivery_method)` ctor, `find_nearby` zipcode/query) + how-to guide; `PickupPointProvider::Base` stays **undocumented in 6.0** (v6 docs cover only the delivery rate provider interface) — never add pickup-provider docs in 6.0 work. Delivery mechanics live on provider classes (`pickup_point` provider ships but stays unregistered until 6.1; `local_delivery` cut = shipping + postal-code zone); the string fulfillment-type registry was deleted by `6.0-delivery-profiles.md`. **Partial fulfillment (2026-08-10, resolved question 12):** shipping a subset is `Spree::Fulfillments::Fulfill` (optional per-line-item `items:` + `tracking:` + `notify_customer:`; splits then fulfills in one transaction) — never a state-machine event, since split-then-ship in an `after_transition` is what service-workflows prohibits. **Side effects left the machine (2026-08-10, question 13):** `after_cancel`/`after_resume` are gone as transition callbacks — restock + carrier stand-down live in `Fulfillments::Cancel`/`::Resume` as inline steps (provider call is an `external_step`; `notify_provider: false` lets `Orders::Cancel` delegate and batch carrier I/O after its own transaction), `after_cancel`/`after_resume` are deprecated shells and the only trace left on the model — never add public model methods for workflows to call. **Status model (2026-08-11, question 14): the machine is REMOVED.** `status` = plain `HasStatus` `unfulfilled → fulfilled → delivered | canceled` (`pending`/`ready`/`ready_for_pickup` collapse — payment/stock gating is a `Fulfillments::Fulfill` validate guard, pickup renders modality-aware labels); `delivered` = confirmed receipt (`Fulfillments::MarkDelivered`, `delivered_at`, `fulfillment.delivered`) — the returns window + EU withdrawal anchor; carrier truth is the separate `tracking_status` axis (data, never a machine) written by `Fulfillments::UpdateTracking`, fed by EasyPost tracker webhooks (opt-in trackers for hand-entered numbers). Rollup domain `backorder | canceled | partial | unfulfilled | fulfilled | delivered`. **Phase 7 shipped 2026-08-11** (core + API + dashboard + EasyPost tracker webhook + `spree:migrate_fulfillment_statuses`); **label leads, fulfilled follows (2026-08-12):** `Fulfillments::PurchaseLabel` = explicit pre-ship label buy (loud failure, no email); `Fulfill` buys label BEFORE marking fulfilled (email always carries tracking; post-split failure keeps the split, never rolls it back); providers declare `generates_labels?` + idempotent `create_fulfillment`. **One tracking number per fulfillment (2026-08-11, question 15):** diverging parcels are split fulfillments; a `spree_fulfillment_trackings` model is 6.1 work and must absorb the entire carrier axis (per-row status/`delivered_at`, webhook matching by row) — never split the axis across fulfillment and tracking rows
- `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-store-context-and-first-run-setup.md` — Store context becomes credential-derived (design finalized 2026-08-13): publishable key selects the store on the Store API, Admin API honors `X-Spree-Store-Id` with membership checked against the *requested* store (header-less JWT → default store + deprecation, required 6.1), hostname-based store resolution retired (`FindDefault`'s `url:` is dead; never read `request.host` to pick a store). First-run setup replaces the `[email protected]`/`spree123` dummy seed: seed creates an admin only when `ADMIN_EMAIL`/`ADMIN_PASSWORD` are explicitly set; otherwise a one-time setup-token flow (dashboard `/setup` + unauthenticated `auth/setup` endpoints; `has_secure_token :setup_token` on Store — plaintext like invitation tokens, printed by installer, `spree:setup:token` reprints, cleared on completion — required in EVERY environment; `Spree::Stores::DashboardUrl` is the single resolver for the dashboard origin — used by the setup link, invitation emails and the SSO callback — resolving `dashboard_url` pref/`SPREE_DASHBOARD_URL` → deprecated `admin_url` → this app's own `/dashboard` mount when `spree_dashboard` serves a build → dev Vite → store URL; never a hardcoded port, and the CLI rebuilds the link host-side since the seed runs before any dashboard is up). **App configuration reads ENV:** `RuntimeConfiguration.preference` accepts `env:` (precedence: explicit value → env var → coded default), so deployment settings are configurable without touching Ruby; `dashboard_url` is env-backed via `SPREE_DASHBOARD_URL` and `admin_url` is deprecated in its favour. Applies to `Spree::Config` only — per-store behavior belongs in Store preferences. The setup flow creates the first admin and adopts/renames the seeded store; no general store CRUD in the OSS Admin API. **Constraints now:** never assume `current_store == Store.default` in Admin API code; store-touching cache keys include the store id by construction (enforced by the cache-key audit spec in core — global data needs a reviewed allowlist entry); new scripts pass `ADMIN_EMAIL`/`ADMIN_PASSWORD` explicitly. **Isolation tripwires (2026-08-13):** `Spree::StoreScopeGuard` wraps every v3 API request in dev/test and flags store-less secondary-key lookups and unscoped scans on store-owned tables (schema-derived set; id/FK filters and `SELECT 1 AS one` are exempt as loads-from-scoped-rows and uniqueness validations — exemption is NOT proof of scoping, request-derived ids still need `current_store` fetching; `log` default, `raise` in this repo's API suite, `SPREE_STORE_SCOPE_GUARD` to change) — wrap deliberately global lookups in `Spree::StoreScopeGuard.skip { }`. A store-owned model with an unscoped `acts_as_list` also fails the core suite (positions bleed across stores).
-- `6.0-tax-provider.md` — Per-Market TaxProvider, replaces TaxRate.adjust + Calculator; TaxRate gets direct country/state FKs (tax decoupled from Zone; Zone model dropped in 6.0 via `6.0-delivery-zones.md`); reference provider: Avalara (decisions.md 2026-07-30)
+- `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_iso`/`state_code` — codes, not FKs, since Country/State are being dropped; `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 shipped to `feature/v-3526` (2026-08-12):** the minimal Company tree pulled 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_iso`/`state_code`, and the `ResolveExemptions` body; **no `tax_exempt` boolean anywhere** (supersedes the B2B plan's sketches), and Catalog/pricing/visibility stay 6.1. A buyer's company resolves only within the sale's own store, since customers are global. Pending after that: Phase 6 `spree_tax_avalara`, **Phase 8 cross-border pricing with tax-inclusive prices** (2026-08-11 live pass: `Pricing::Context.from_order` never carried the cart's market so market-scoped price lists were unreachable from a cart; `recalculate_for_address_change!` called the non-persisting `update_price`; restatement was applied even to prices set for the destination — the rule is now derive net-fixed unless the winning price list carries a `geographic?` rule, Shopify's model), Phase 9 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; monorepo ships one reference multi-carrier provider (**EasyPost** — decisions.md 2026-08-06 reversal: BYOCA fit for larger merchants + only maintained official Ruby SDK; Shippo's ruby gem dead since 2020); method rows stay regional (no cross-market method entity). **Dynamic carrier rates (2026-08-09):** a carrier method is the carrier connection — `estimates(package)` returns one Estimate per service, each becoming its own named DeliveryRate (unique (fulfillment, method) rate index dropped; `DeliveryRate#name` falls back to the method name); `Spree::DeliveryMethodService` rows narrow/rename/mark-up services (no rows = all, method-level markup columns as default); selection + EasyPost label buy key off the selected rate's carrier/service; seeds/sample data reshaped Shopify-style (Domestic + International zones with basic methods)
- `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-integrations-admin.md` — **Implemented (2026-08-06).** `Spree::Integration` as the single credential surface for all provider seams (delivery rates/tax/fulfillment/pickup points): explicit `Spree.integrations` registry, Admin API v3 CRUD + types discovery (reusing `PreferenceSchema`/`Masking` — secrets are `:password` preferences), dashboard `/settings/integrations` gallery grouped by `integration_group`. Verify-before-activate (`active: true` runs `can_connect?`, 422 on failure), ephemeral connection status. Constraints now: provider gems ship an Integration subclass (no env-var credential contracts for per-store providers); no per-provider credential UIs — pickers deep-link to the integrations page.
diff --cc docs/plans/decisions.md
index b574b51f51,d00a526af0..1fb71aad02
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@@ -1,44 -1,117 +1,158 @@@
+ ## 2026-08-13: Document numbers — sequential by default, store-configurable orders, derived child numbers
+
+ `Spree::Core::NumberGenerator` (the boot-frozen `Module` factory) is replaced
+ at 6.0 by a `has_spree_number prefix: 'R'` macro (`Spree::HasNumber`, included
+ into `Spree::Base` so no model needs its own include) plus runtime-resolved
+ strategy classes
+ (`Spree.number_generators` registry, `NumberGenerators::Sequential` |
+ `::Random`). Sequential is the new default — invoice-like `R1001, R1002` with
+ a per-`(store, resource_type)` counter table (`spree_number_sequences`,
+ `with_lock` increment, portable across all three databases); random becomes
+ opt-in. Merchants get exactly one dashboard surface: an "Order numbers" card
+ (prefix, suffix, format, starting value — default 1001) stored as
+ `Spree::Store` preferences. Other document types keep code defaults;
+ developers swap generators via the registry.
+
+ The numbered-model census shrank. Numbers predate prefixed IDs as the
+ human-readable identifier, so each model was audited for who actually reads
+ its number: **Order** keeps the flagship stored number; **Return / Exchange /
+ Claim** keep stored numbers (customer-visible, dashboard cards, and the
+ `migrate_returns` resume cursor); **Fulfillment and Payment numbers become
+ derived methods** — stored value honored on legacy rows, new rows compute
+ `"#{order.number}-F1"` / `"-P1"` from parent + sibling position, generation
+ and counters gone (gateway `order_id` simplifies to `payment.number`;
+ idempotency to `"spree-#{payment.number}"`). Every other numbered model keeps
+ its stored number. The dividing line is *document handled outside the
+ dashboard* versus *row in an admin table* — which on inspection kept more
+ than the draft expected: transfer slips travel on boxes, POs are quoted to
+ suppliers, and **imports and exports mail their number in a subject line**
+ (`Your export EF1001 was successfully processed!`), so the planned removal of
+ back-office numbers was dropped during implementation.
+
+ Consequences: never parse or regex a `number` (format is merchant data now);
+ never write `spree_fulfillments.number` / `spree_payments.number` (frozen
+ until the 6.1 column drop); the global unique index stays, so sequential is
+ mostly-gapless and must never be sold as legal invoice numbering; settings
+ changes only affect future numbers; and code saving a numbered record with
+ `validate: false` must call `generate_number` itself, since the hook that
+ normally assigns one is `before_validation`. Plan:
+ `6.0-document-numbers.md`.
+
+ ## 2026-08-13: Isolation tripwires — the guard under the store-scoping discipline
+
+ Open-core isolation is the controller discipline (every lookup through a
+ `current_store` association); row-level enforcement is deliberately not a
+ core feature. Two nets now sit under that discipline rather than trusting
+ review alone.
+
+ `Spree::StoreScopeGuard` wraps every v3 API request in development and test:
+ a SELECT against a store-owned table (schema-derived — any `spree_*` table
+ with a `store_id` column) carrying no `store_id` predicate is reported with
+ the SQL and call site. `log` by default, `raise` in this repo's API suite,
+ never active in production. Deliberately global lookups — the API-key
+ searches, where the key selects the store — opt out with
+ `StoreScopeGuard.skip`, which doubles as documentation of intent.
+ `watchable_environment?` is overridable so a multi-tenant enforcement layer
+ can run the guard as a production log-mode canary, and the schema-derived
+ watched set means tables stamped with `store_id` later are watched with no
+ registration.
+
+ Cache keys get a static audit spec: every `Rails.cache` call site in core
+ and api must visibly carry the store in its key or hold a reviewed allowlist
+ entry saying why the data is global. Writing the audit surfaced a real bug —
+ idempotency replay caching keyed per credential but not per store, so a
+ staff JWT reusing an Idempotency-Key across stores replayed the first
+ store's response. The key now partitions by the requested store.
+
+ Consequences: a store-less secondary-key lookup (slug, number, code, email,
+ token) or unscoped scan on a store-owned table inside an API request is a
+ test failure, not a review comment — wrap genuinely global lookups in
+ `skip`. Honest limits: id/foreign-key filters and `SELECT 1 AS one`
+ existence checks are exempt (they are dominated by loads from already-scoped
+ rows and uniqueness validations) — exemption is NOT proof of scoping, so a
+ lookup fed a request-derived id still requires `current_store` fetching even
+ though the guard stays silent on it; and only the v3 controller surface is
+ watched — jobs, webhooks and callbacks are a future extension, ideally keyed
+ off `Spree::Current.store` assignment rather than per-entry-point
+ registration. A new `Rails.cache` call without a store-scoped key fails the
+ core suite until scoped or reviewed onto the allowlist, and a store-owned
+ model with an unscoped `acts_as_list` fails it too (positions would bleed
+ across stores — the bug PaymentMethod shipped with, fixed alongside three
+ sibling leaks the tripwires surfaced: the pickup-location fallback, the
+ stock-location default flag, variant stock-item propagation, and data-feed
+ name uniqueness). Plan: `6.0-store-context-and-first-run-setup.md`.
+
+ ## 2026-08-13: Store context is credential-derived — hostname resolution retired; first-run setup replaces the dummy admin
+
+ Every v3 API request resolved to `Spree::Store.default`: the configured finder
+ discarded the hostname it was handed, and no server code read the
+ `X-Spree-Store-Id` header the admin SDK sends on every request — so the
+ dashboard's store switcher silently lied, and API keys were validated
+ *against* the default store instead of *selecting* their own.
+
+ Decision: store context is explicit and comes from the credential, never the
+ hostname. The publishable key selects the store on the Store API (the key
+ already `belongs_to :store`); a secret key is bound to its store; JWT staff
+ sessions select via `X-Spree-Store-Id`, membership-checked against the
+ *requested* store (header-less JWT requests fall back to the default store
+ with a deprecation warning through 6.0, required at 6.1). Hostname-based
+ store resolution was a requirement of the server-rendered per-subdomain era
+ and is gone with it — never read `request.host` to pick a store.
+ `Spree.current_store_finder` stays as the override point.
+
+ With it, installation stops minting `[email protected]` / `spree123`: the
+ seed creates an admin only when `ADMIN_EMAIL`/`ADMIN_PASSWORD` are explicitly
+ set, and otherwise a one-time, token-guarded first-run setup flow (dashboard
+ `/setup` + `auth/setup` endpoints, invitation-acceptance shape) creates the
+ first admin and adopts/renames the seeded store. The token is required in
+ every environment — no env-based security branches. No general store CRUD
+ ships in the OSS Admin API; first-run configures the one store.
+
+ Consequences: Admin API code must never assume `current_store` is the default
+ store, and store-touching cache keys must carry the store id by construction.
+ Plan: `6.0-store-context-and-first-run-setup.md`.
+
+## 2026-08-12: Jurisdiction is stored as a code, never as a country or state row
+
+Amends 2026-08-06 ("Converted-away columns outlive the release that converts
+them"), which had tax rates gaining `country_id`/`state_id`. They gain
+`country_iso` and `state_code` instead — plain strings, upcased on write. The
+reason is that `Spree::Country` and `Spree::State` are themselves on the way out,
+so a rate pointing at their rows would need converting a second time; and "DE"
+is what a merchant recognises, where a row id is not. It also matches the
+jurisdiction snapshot `spree_tax_lines` already carries, so a rate and the line
+it produced now speak in the same terms.
+
+Everything else in that entry stands: `spree_tax_rates.zone_id` still survives
+through 6.0 as `spree:migrate_tax_zones`'s input, and the task now writes codes.
+
+**The cost, accepted:** the `state_belongs_to_country` validation is gone. With
+codes there is no country row to check a state against, and keeping the guard
+would mean keeping the `Spree::State` lookup this removes. A mismatched pair is
+simply a rate that never matches an address — which is what the mismatch always
+meant in practice, minus the early warning.
+
+Because the columns had not shipped, the original migration was amended rather
+than followed by a second one.
+
+**Extended the same day to everything this work owns**, after a review pass found
+the same shape elsewhere. `Spree::TaxExemptionCertificate` held country and state
+references, and `Spree::PriceRules::ZoneRule` held a `country_ids` preference of
+`Spree::Country` primary keys; both now hold codes (`country_iso`/`state_code`,
+`country_isos`). The certificate case was a live defect rather than a tidy-up:
+an unrecognised ISO resolved to a nil country, and nil claims *every* country
+there, so a mistyped code silently turned one state's certificate into a
+worldwide exemption. A code that matches nothing narrows to nothing.
+
+`Spree::Pricing::Context` gained a `country_iso` reader so a price rule compares
+codes rather than reaching through `context.country`; when Country goes, the
+context is the only place that changes.
+
+**Where a Country object is still correct:** `Purchase::Taxation#tax_country` and
+`Spree::Current.tax_country` return one, and should. Those are lookups in request
+context, not stored jurisdiction, and addresses and markets still speak in
+countries. The rule this entry sets is about what a row *persists*.
+
## 2026-08-12: The label leads, fulfilled follows (amends the Phase 7 fulfill flow)
A warehouse prints the label, sticks it on the box, hands the box over — and
diff --cc spree/core/spec/lib/tasks/six_zero_data_migrations_spec.rb
index 408087911d,3980c0c774..3dffdbaff0
--- a/spree/core/spec/lib/tasks/six_zero_data_migrations_spec.rb
+++ b/spree/core/spec/lib/tasks/six_zero_data_migrations_spec.rb
@@@ -12,7 -12,7 +12,8 @@@ describe '6.0 data migration tasks' d
load Spree::Core::Engine.root.join('lib', 'tasks', 'order_market_backfill.rake')
load Spree::Core::Engine.root.join('lib', 'tasks', 'store_binding_migration.rake')
load Spree::Core::Engine.root.join('lib', 'tasks', 'fulfillment_statuses_migration.rake')
+ load Spree::Core::Engine.root.join('lib', 'tasks', 'tax_zones_migration.rake')
+ load Spree::Core::Engine.root.join('lib', 'tasks', 'capture_methods_migration.rake')
end
let(:store) { @default_store }