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.

Book the 6.1 tax cleanup as a phase of its own

Łukasz Adamczykc62629e9d9f3
diff --git a/CLAUDE.md b/CLAUDE.md
index f6c387f2d1..75efc00a84 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). Pending: Phase 3 contract enrichment, Phase 4 per-Market selection + commit/void/refund wiring, Phase 5 tax-side Zone decoupling (Zone model survives 6.0), Phase 6 `spree_tax_avalara`, Phase 7 exemption certificates (gated on Company from the B2B plan)
+- `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-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.0
diff --git a/docs/plans/6.0-tax-provider.md b/docs/plans/6.0-tax-provider.md
index 345f4c2de8..bf8d4d3e66 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). Remaining: the contract enrichment below (2026-08-05 revision), per-Market provider selection, commit/void/refund lifecycle wiring, Phase 5 Zone decoupling, and the Avalara reference gem.
+**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 and bridges 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.
@@ -484,7 +484,7 @@ scope :for_address, ->(address) {
State-level rates override country-level (more specific wins). **Tax stops using Zone; the Zone model itself survives 6.0** — a data migration converts Zone records used by TaxRate into direct country/state FKs, no code reads `zone_id` on TaxRate any more, and the generic `Spree::Zone` stays for the request-context surface (`Spree::Current.zone`, `Market#tax_zone`, factories). Full Zone removal gets its own future plan with a complete consumer inventory.
-**`spree_tax_rates.zone_id` is dropped in 6.1, not 6.0.** The column is what `spree:migrate_tax_zones` converts *from*, and the manifest runs after `db:migrate` — so a migration dropping it in the same release would destroy the conversion's own input, and leave no rollback source if a merchant needs to re-run it. 6.0 therefore severs every reader (the `belongs_to :zone`, the zone scopes, and `Zone#has_many :tax_rates`, whose `dependent: :destroy` would otherwise delete live rates when a shipping zone is destroyed) and leaves the column in place, unread. This matches how `spree_adjustments` is handled by `migrate_adjustments_to_typed_rows`. The 6.1 cleanup drops the column alongside the other converted-away schema.
+**`spree_tax_rates.zone_id` is dropped in 6.1, not 6.0.** The column is what `spree:migrate_tax_zones` converts *from*, and the manifest runs after `db:migrate` — so a migration dropping it in the same release would destroy the conversion's own input, and leave no rollback source if a merchant needs to re-run it. 6.0 therefore severs every reader (the `belongs_to :zone`, the zone scopes, and `Zone#has_many :tax_rates`, whose `dependent: :destroy` would otherwise delete live rates when a shipping zone is destroyed) and leaves the column in place, unread. This matches how `spree_adjustments` is handled by `migrate_adjustments_to_typed_rows`. **Phase 8** drops the column alongside the other converted-away schema.
## Design Details
@@ -1032,13 +1032,12 @@ Tax-side only — shipping keeps Zone untouched; full Zone removal is deferred t
```
- Add `country_id`/`state_id` to `spree_tax_rates`; run the data task; sever every `zone_id` reader.
- The column itself stays until 6.1 — see "Drop TaxZone" above for why the conversion cannot
- drop its own input.
+ The column itself is dropped in **Phase 8**, not here — the conversion cannot drop its own input.
- Update the `/admin/tax_rates` serializer, permitted params and Ransack allowlist from `zone_id` to `country_id`/`state_id` — the only rework those endpoints take, and the reason they are worth building in Phase 3 rather than waiting.
- Rewrite the tax-side zone readers against `TaxRate.for_address`: `Order#tax_zone`, `Spree::Current.zone`/`default_tax_zone`, `Market#tax_zone` — these feed pre-address tax display and Estimator VAT options, so they move to the provider/`for_address` path rather than being deleted.
- **Re-point whatever populates `DeliveryRate#tax_rate`.** The Estimator matches that rate through the Zone path this phase removes, so it must move to `for_address` to keep working. Mechanical only — preserving current behavior here does not require answering Open Question 1, though this is the natural moment to.
- `spree_zones`/`spree_zone_members` are **not** dropped in 6.0, and neither is
- `spree_tax_rates.zone_id`.
+ `spree_tax_rates.zone_id` (Phase 8).
### Phase 6: Avalara reference gem (`spree_tax_avalara`)
@@ -1126,6 +1125,37 @@ 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.
+### Phase 8: 6.1 cleanup — the schema and bridges 6.0 deliberately kept
+
+**Ships in 6.1, never inside 6.0.** Every item here needs a release boundary for one of two
+reasons: a 6.0 install may not have run its data task yet, or a third party may still be passing
+a shape 6.0 still accepts. The precondition that makes the schema changes safe is that
+`spree:migrate_tax_zones` and `spree:backfill_tax_store_ids` are both steps in the 5.6→6.0
+manifest, so every install arriving at 6.1 has run them.
+
+1. **Drop `spree_tax_rates.zone_id`.** Nothing reads it after Phase 5 — the association, the
+ zone scopes and `Zone#has_many :tax_rates` are gone. It survives 6.0 only as the conversion
+ source for `spree:migrate_tax_zones`, which runs *after* `db:migrate`: a 6.0 migration
+ dropping it would destroy its own input and leave a merchant no source to re-run from
+ (decisions.md 2026-08-06).
+2. **`null: false` on `spree_tax_rates.store_id` and `spree_tax_categories.store_id`** — the
+ store-binding convention's second half, matching DeliveryMethod and StockLocation. Presence
+ is model-enforced from 6.0; the constraint waits for the backfill to have run everywhere.
+3. **Remove the two tax-zone bridges,** which exist so a host app or extension still passing
+ `tax_zone:` keeps working for one release:
+ - `Spree::VatPriceCalculation#country_from`'s `price_options[:tax_zone]` branch, which reads
+ the first country off a zone.
+ - `Stock::Estimator#taxation_options_for`'s `tax_zone:` key, redundant beside `address:`.
+ Removing them makes `country`/`address` the only accepted shape.
+4. **Drop the vestigial `tax_rates` slot from the `SpreeCalculators` struct.** Tax has had no
+ calculator since `Calculator::DefaultTax` was removed; the slot is a public-ish constant, so
+ it gets a boundary rather than a silent edit.
+5. **Decide `Market#tax_inclusive`.** A dead boolean with no reader in `app/` that the API still
+ serializes and permits. 6.0 left it alone deliberately — Internal derives
+ inclusive-vs-additive per rate from `TaxRate#included_in_price`, which is finer-grained than
+ a market-wide flag. Either wire it for external providers or drop it together with its API
+ fields; it should not survive a third release undecided.
+
## Constraints on Current Work
- **The provider is the only TaxLine writer.** Don't add tax computation anywhere else; don't reintroduce calculators or adjuster-side tax.