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.

Correct the plans where they no longer describe the code

Łukasz Adamczykc693cd2d2690
diff --git a/CLAUDE.md b/CLAUDE.md
index f7716ea791..7e55bf978b 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -25,7 +25,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. 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-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 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 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-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 --git a/docs/plans/6.0-admin-api.md b/docs/plans/6.0-admin-api.md
index fc5d8e8482..52ac47c783 100644
--- a/docs/plans/6.0-admin-api.md
+++ b/docs/plans/6.0-admin-api.md
@@ -769,15 +769,17 @@ API key scopes: `read_vendors` / `write_vendors`, `read_commissions` / `write_co
- [x] `DELETE /api/v3/admin/tax_categories/:id`
### Tax Rates
-- [ ] `GET /api/v3/admin/tax_rates`
-- [ ] `GET /api/v3/admin/tax_rates/:id`
-- [ ] `POST /api/v3/admin/tax_rates`
-- [ ] `PATCH /api/v3/admin/tax_rates/:id`
-- [ ] `DELETE /api/v3/admin/tax_rates/:id`
+- [x] `GET /api/v3/admin/tax_rates`
+- [x] `GET /api/v3/admin/tax_rates/:id`
+- [x] `POST /api/v3/admin/tax_rates`
+- [x] `PATCH /api/v3/admin/tax_rates/:id`
+- [x] `DELETE /api/v3/admin/tax_rates/:id`
-> **6.0:** `zone_id` FK is dropped. `TaxRate` gets direct `country_id` + `state_id` FKs. Tax logic moves behind a `TaxProvider` interface. See `6.0-tax-provider.md`.
+> **6.0:** a rate names its jurisdiction directly as `country_iso` + `state_code` codes, and tax logic moves behind a `TaxProvider` interface. See `6.0-tax-provider.md`.
>
-> **Built by the tax-provider plan (2026-08-05), Phase 3.** These rows are the Internal provider's entire configuration, so that plan cannot verify its own tax calculation without them, and it specifies the serializer alongside the provider work. They ship against the `zone_id` shape and switch to `country_id`/`state_id` in its Phase 5 — tick these boxes from there rather than building separately.
+> `spree_tax_rates.zone_id` is **not** dropped in 6.0: `spree:migrate_tax_zones` reads it to convert existing rates, and that task runs after `db:migrate`, so removing the column in the same release would destroy its own input. It stays unread through 6.0 and comes off in 6.1.
+>
+> **Built by the tax-provider plan (2026-08-05), Phase 3.** These rows are the Internal provider's entire configuration, so that plan cannot verify its own tax calculation without them, and it specifies the serializer alongside the provider work. They shipped against the `zone_id` shape and moved to the jurisdiction codes in its Phase 5.
### Markets
- [x] `GET /api/v3/admin/markets`
diff --git a/docs/plans/6.0-core-rewrite-tasks.md b/docs/plans/6.0-core-rewrite-tasks.md
index fda1aa977a..f3a9302e24 100644
--- a/docs/plans/6.0-core-rewrite-tasks.md
+++ b/docs/plans/6.0-core-rewrite-tasks.md
@@ -161,10 +161,11 @@ Runs after Wave 2 (tables born with `fulfillment_id`). Can proceed in parallel w
- [x] ~~Promotion STI namespace rename~~ **REVERTED in Wave 6 (2026-07-29, Damian):** promotion rule/action class names stay `Spree::Promotion::Rules::*` / `Spree::Promotion::Actions::*` (incl. `CreateItemAdjustments`) — the rename wasn't required by the split; typed-Discount behavior kept under the legacy names. No STI type-column data task needed.
### T3.4 Minimal TaxProvider (the sanctioned TaxLine writer)
-- [x] `Spree::TaxProvider::Base` (estimate required; commit/void/refund no-op stubs; `exempt?` default) + `Spree::TaxProvider::Internal` computing directly from TaxRate data (rate × discounted base; VAT included-in-price math) — **no `Calculator::DefaultTax` indirection**; zone matching stays as today (`TaxRate.match` over `Spree::Zone`) until the tax plan decouples it.
+- [x] `Spree::TaxProvider::Base` (estimate required; commit/void/refund no-op stubs) + `Spree::TaxProvider::Internal` computing directly from TaxRate data (rate × discounted base; VAT included-in-price math) — **no `Calculator::DefaultTax` indirection**; zone matching stays as today (`TaxRate.match` over `Spree::Zone`) until the tax plan decouples it.
- [x] Write contract: **replace-all set semantics** per estimate (delete target items' TaxLines, insert fresh — kills stale tax after address changes); internal rows keep `tax_rate_id` + snapshot `rate`/`label`/`provider_id: 'internal'`.
- [x] `Spree.tax_provider` seam (global default → Internal; per-Market resolution arrives with the full tax plan). *Renamed `Spree.default_tax_provider` and now returns a class, with the tax plan's per-market selection.*
- [x] Removed: `TaxRate.adjust`, `AdjustmentSource`, `Calculator::DefaultTax`, `Adjuster::Tax`. TaxRate becomes pure configuration.
+- [x] The `exempt?` predicate this task first sketched is gone: exemption is typed evidence passed into `estimate` (`Spree::TaxExemption` via `tax_resolve_exemptions_service`), not a boolean a provider answers — see `docs/plans/decisions.md` 2026-08-05.
### T3.5 Typed recalculation + consumer rewrite
- [x] `OrderUpdater`: two-pass preserved — discount/fee adjusters persist the discounted taxable base (+ `pre_tax_amount`), then the sale's tax provider `estimate` (`Spree.tax_provider` at the time; now `owner.tax_provider`); totals via grouped SUMs from typed tables; all denormalized columns kept (incl. `taxable_adjustment_total`/`non_taxable_adjustment_total`) + new `fee_total`; freeze guard from T3.1.
diff --git a/docs/plans/6.0-tax-provider.md b/docs/plans/6.0-tax-provider.md
index 09e4b905ed..a82452a9ce 100644
--- a/docs/plans/6.0-tax-provider.md
+++ b/docs/plans/6.0-tax-provider.md
@@ -413,10 +413,11 @@ names the first "price consistency".
Spree takes the two-tier answer, which is Shopify's:
-1. **A price from a geo-scoped price list is final** — charged exactly as entered, never restated.
- `Spree::Price#final_for_destination?` is true when the winning list carries a rule that answers
- `geographic?` (`MarketRule`, `ZoneRule`). This is Shopify's carve-out: fixed per-country prices
- receive no adjustment.
+1. **A price the merchant set for a geography is final** — charged exactly as entered, never
+ restated. `Spree::Price#final_for_destination?` is true when the winning list carries a rule that
+ answers `geographic?` (`MarketRule`, `ZoneRule`) *and* that rule is why the list won — see the
+ `match_policy` condition in step 2 of the implementation below. This is Shopify's carve-out:
+ fixed per-country prices receive no adjustment.
2. **Everything else derives net-fixed** — the home rate out, the destination's on, via
`VatPriceCalculation`. The merchant's take is preserved; the gross moves, cents and all.
@@ -1395,9 +1396,12 @@ delivery already has.
on the cart, not on whether a client remembered a header. Audit the other constructors
(`from_currency` has no owner to read a market from — it keeps the `Spree::Current` fallback,
which is correct for a catalogue request).
-2. **`Spree::PriceRule.geographic?`** — `false` on the base class, `true` on `MarketRule` and
- `ZoneRule`. Then `Spree::Price#final_for_destination?` is
- `price_list&.price_rules&.any?(&:geographic?)`, and both `price_including_vat_for` and
+2. **`Spree::PriceRule.geographic?`** — `false` on the base class, and on `MarketRule`/`ZoneRule`
+ true only when the rule actually names a geography (an empty market or country list matches
+ every buyer, so it names none). `Spree::Price#final_for_destination?` then needs the list's
+ `match_policy` as well as the presence of such a rule: under `all` every rule matched, so the
+ geography is why the price applied; under `any` the list may have won on a non-geographic rule
+ alone, so it is final only when every rule is geographic. Both `price_including_vat_for` and
`compare_at_price_including_vat_for` return the stored figure unchanged when it answers true.
A volume or customer-group list price is still restated — it was priced for a quantity or a
group, not for a country, so its margin needs the same protection as a base price.
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index 6f2626b889..b574b51f51 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -181,10 +181,21 @@ A live pass against a running server found three defects in one seam — what a
when the destination's VAT rate differs from the home zone's. `6.0-tax-provider.md` gains Phase 8 to
fix them (the 6.1 cleanup renumbers to Phase 9).
-**The rule, which is Shopify's:** a price from a price list whose rules include a geographic one
-(`MarketRule`, `ZoneRule`) is **final** — charged exactly as entered, never restated. Everything else
-**derives net-fixed**: home rate out, destination rate on, via `VatPriceCalculation`. The merchant's
-net is preserved and the gross moves.
+**The rule, which is Shopify's:** a price the merchant set for a geography is **final** — charged
+exactly as entered, never restated. Everything else **derives net-fixed**: home rate out, destination
+rate on, via `VatPriceCalculation`. The merchant's net is preserved and the gross moves.
+
+"Set for a geography" needs the `match_policy`, not just the presence of a geographic rule
+(`MarketRule`, `ZoneRule`), because a list can win without its geographic rule being the reason:
+
+- `match_policy: 'all'` — every rule matched, so the geography is why this price applied. **Final.**
+- `match_policy: 'any'` — the list may have won on a non-geographic rule alone (a volume break, a
+ customer group), so the price is not evidence of a decision about this destination. Final only
+ when *every* rule is geographic.
+
+Each rule kind answers `geographic?` for itself, always a boolean; the base `PriceRule` answers
+false, so a rule that names no geography — including an empty country or market list, which matches
+every buyer — never makes a price final.
**Why this matters beyond tax.** Two of the three defects are pricing defects, not tax defects: