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.
2026-10-06: Custom fields stay a merchant-facing feature, not a data modelling system
Context: Custom fields were heading toward a general-purpose schema (record references, files, value lists, reusable content types) while basic gaps went unfixed: admin-only fields leaked through storefront search, a definition's type can change under existing values, shoppers cannot fill a field in at checkout, and core itself stores integration data in auto-created definitions. Revised 2026-11-02 after a review against the code and the plans written since, with 6.0.0 already released.
Decision: Custom fields serve merchants who cannot change code: typed, labelled values on a record, shown on or captured from the storefront. Developers and extensions — core included — store their data in real columns, tables or metadata, never in custom fields; core's gateway.processing_errors and external.url move out in 6.1. No custom field type will be added for references, files, measurement units, money, general lists or reusable content types, and no custom-field facets are added; cf_ filtering and sorting stay. A choice type is added for every resource (customers, orders and companies have no option types), but shopper-facing product value lists stay option types. Admin-only values stay off every storefront surface (done 2026-10-22), and emails carry storefront-visible fields only. A definition's field_type and resource_type are fixed once created: a 6.0.x patch ignores a change with a deprecation warning, 6.1 rejects it with 422. In 6.1: new definitions default to hidden from the storefront; order and customer fields can be storefront_writable — order fields held on the cart, copied to the order and to every seller split order, and shown read-only to sellers; customer fields written at registration and from the account; date, date_time and choice types; a validations JSON column (required, min/max, choices; no regular expressions) enforced in Spree::CustomField on new writes; values in emails and order/customer webhooks; label and text-value translations through the resource translations batch endpoint. required is enforced where a shopper writes — a checkout requirement for orders, a 422 at customer registration and account update — and stays advisory elsewhere (2026-08-06). Line-item and company shopper writes are deferred.
Consequences: Every shopper-facing read filters storefront_visible: true. API writes resolve existing definitions and never auto-create them. Required checkout input is a checkout requirement, never only a completion hook. No update path (API, import, configurator) may change a definition's type. See 6.0-6.1-custom-fields-roadmap.md.
Plans amended: 5.4-metafield-translations.md (6.1, superseded on mechanism), 5.5-6.0-resource-translations-api.md (custom-field phase moves to 6.1), 5.4-search-provider.md (faceting dropped, filterable-attribute constraint superseded), 6.0-extendable-validations.md (validation designed here; checkout requirement, not hook), 6.0-seller-order-management.md (sellers see shopper-writable order fields), 6.0-payment-gateways-monorepo.md (Adyen references in metadata), 6.0-admin-spa.md (6.1 kinds), 6.0-cli-configurator.md (section order, no type updates). Amends decisions.md "storefront_visible boolean (default: true)" for custom field definitions only.
2026-10-27: PayPal becomes a provider gem in a 6.0 patch release
Context: spree_paypal_checkout 0.7.1 does not run on 6.0, so merchants taking PayPal on 5.x cannot upgrade. Its payment-session code predates the cart/order split, settle_payment! and money amounts, and several of its behaviours are wrong under 6.0: it stores the capture id as the payment's reference, maps the buyer's approval to an authorization, which in 6.0 would place an order with no money taken, and logs buyer details.
Decision: Port the payment-session half to spree/providers/paypal, keeping the gem name and every stored class name, with no core behaviour changes (core gains only two upgrade-manifest entries), and ship it in the next 6.0 patch release. The first release covers PayPal's own buttons (PayPal, Pay Later, Venmo, guest card in PayPal's window), which the storefront renders from a list of allowed buttons so alternative payment methods never appear (amended 2026-10-28), and honors the store's capture setting through PayPal's AUTHORIZE intent. A payment's response_code is always the PayPal order id; an optional upgrade step rewrites payments taken before the upgrade to that shape. Webhooks register themselves, are always verified, and only report money that has moved: as soon as the buyer approves, the storefront calls the server, which takes the money, as in PayPal's own button guide, so the buyer's approval is not acted on by webhook (amended 2026-10-28). Like Stripe's gem, it has no circuit breaker.
Consequences: A PayPal authorization can only be captured for 29 days (honored for 3), and this release does not reauthorize, the same as Stripe, whose card holds cannot be renewed. A later capture that PayPal leaves pending is reported as not taken, so dispatch waits until PayPal releases it (amended 2026-10-28). spree_paypal_checkout_orders must not be dropped before the payment upgrade step runs. A buyer who closes the tab right after approving gets no order and is not charged; a core :approved webhook outcome is the planned fix once payment methods that send the buyer to their bank are added. During a PayPal outage each checkout waits for the timeout before failing, as with Stripe; outage handling, if added, goes into core for every gateway. Card fields and Apple Pay / Google Pay through PayPal are deferred; whether saved PayPal accounts are needed straight after the first release is still open.
Plan: 6.0-paypal-payment-provider.md. Plan amended: 6.0-payment-gateways-monorepo.md (its PayPal timing question is resolved).
2026-10-27: Stripe transfer reversals on refund move to open source
Context: A refund on a seller's order wrote the reversal row, and the next payout to the seller's bank subtracted it, but the open-source Stripe provider never reversed the transfer. The seller's share stayed on their connected account while the marketplace had refunded the customer from its own balance, and nothing in the books said where that money now was. The 2026-07-15 decision kept the pullback in Enterprise.
Decision: SpreeStripe::PayoutProvider#reverse! reverses the seller's share of the earning's Stripe transfer (Stripe::Transfer.create_reversal, keyed on the reversal row). A reversal whose earning has not reached Stripe yet stays pending; one whose earning nobody can account for waits for a person. SellerTransfers::ExecutePendingJob now retries owed reversals after the seller's earnings, through the provider that made the earning, and ExecutePendingDueJob picks up any seller holding one, including suspended sellers and those who can no longer be paid. A seller already paid out is left with a negative Stripe balance, which their next earnings make up before the sweep can pay them again.
Consequences: Supersedes the clawback part of 2026-07-15. Enterprise keeps reconciliation against provider statements, KYC operations, payout reports including DAC7, and marketplace-facilitator taxes.
Plans amended: 6.0-multi-vendor-marketplace.md (summary, scope table, payout provider section, funds flow).
2026-10-26: A warehouse that cannot deliver gives up the units another can supply, and holds follow the allocation
Context: A profile with per-region origin groups still allocated a cart to a warehouse with no method for the address whenever the warehouse that could deliver held the item only as backorderable (V-3596). Putting the capable warehouse first had no effect, because the Adjuster takes stock on hand anywhere over a backorder; the cart then reported the item as undeliverable. Reproducing it showed four more gaps on the same path. Orders allocated through OrderRouting::Strategy::Rules, which skipped the delivery profile and channel coverage that carts apply. A cart whose rebuild dropped an undeliverable proposal could still complete, placing an order with part of a line in no fulfillment. The checkout hold locked the first warehouse with stock, which could be one that cannot ship the order, and refused a cart another warehouse could have backordered. And allocation packed one line per variant, so a second line of the same variant (possible with a custom line finder) was allocated nowhere.
Decision: A backorder from a warehouse that can deliver beats stock on hand in one that cannot. Stock::Prioritizer takes from the warehouses that cannot deliver every unit the capable ones can supply between them, on hand or backordered; a unit they cannot cover stays where it was, so the split and the delivery_unavailable warning remain for it rather than a partial shipment being offered. Rules#for_allocation ranks Stock::Coordinator#candidate_stock_locations and packs them through Coordinator#allocated_packages(locations), so carts and orders allocate under one coverage check; the routing plan already saw the Coordinator becoming the strategy's internal machinery. A cart reports delivery_unavailable among its advisory requirements while any unit of a line needing delivery is in no fulfillment, so a storefront can say so before taking payment, and completion refuses it. StockReservations::Reserve runs the allocation without quoting rates (Coordinator#allocated_packages) and holds each line's on-hand units at the location it is packed from, withdrawing the cart's holds the allocation no longer takes; a line placed only in part is refused, as before, while one placed nowhere is left to the completion check. Once the cart has an address, a unit packed only at a location unable to deliver there is not held either, since the cart cannot complete with it and the hold would block buyers that location does serve. A change of destination reserves again instead of only extending the holds, so holds placed before the address was known move to where the order will ship from. The packer splits one shelf between the lines of a variant in order, and the Prioritizer tells proposed units apart by line item.
Consequences: A shopper may now wait for a backorder where before they were told the item could not be delivered. One line can hold stock at several warehouses, and each hold re-runs allocation, which costs the packing and deliverability queries but never a carrier request. An address change can now be refused when the warehouse serving the new address cannot cover the cart, as entering checkout already could. Holds and allocation still read stock on hand without other checkouts' holds, so a contended shelf is refused at the hold rather than spilling to the next warehouse — the routing plan's reservation-aware eligibility question stays open. The profile page's "Ships from" card still shows only the first origin group's warehouses; it is left for a separate change.
Plans amended: 6.0-delivery-profiles.md (Runtime flow, step 2), 6.0-order-routing.md (Since then, the for_allocation sequence, References), 6.0-channel-delivery.md (Enforcement points, step 1), 6.0-stock-reservations.md (Open Question 1, resolved).
2026-10-26: Every release is published from a tag, in one workflow
Context: The npm packages published from packages.yml whenever a merge to main touched certain paths, while the gems published from release.yml on a tag pushed by hand. The two halves of one Spree release went out at different times, a later merge cancelled a release part-way, and gems published without any check of the commit.
Decision: release.yml publishes everything, started by a tag on a commit already on main. v6.0.0.rc7 releases the gems and the npm packages that share the Spree version; @spree/[email protected] and [email protected] release those tools on their own. A first job checks the tag against Spree::VERSION and the package versions before anything publishes, and every step skips versions already on its registry. One script (scripts/publish-packages.mjs) publishes npm packages in dependency order. packages.yml only runs checks. pnpm version:tools versions the tools between Spree releases while the group's changesets wait. The templates the CLI embeds accept their whole major (^6.0.0-0) instead of the workspace version, so a CLI tag never points at packages not yet on npm.
Consequences: Nothing reaches npm from a merge alone; a release is the tag. npm Trusted Publishing names the workflow file, so every published package must trust release.yml before its first tag release. GitHub starts no workflow for more than three tags pushed at once. @spree/docs keeps publishing from docs-package.yml.
Plan amended: 6.0-beta-release.md (Key Decision 3, References).
2026-10-26: The TypeScript packages that talk to the API carry the Spree version
Context: One Spree release shipped under three numbering schemes: gems 6.0.0.rc6, @spree/sdk 2.0.0-rc.5, the Admin and Seller SDKs and the dashboard packages 1.0.0-rc.6, the seller panel 1.0.0-rc.7, @spree/core 0.3.0. The SDKs are generated from the serializers and the dashboards read only the Admin API, so each of those numbers stood for a backend version that nobody could read off it.
Decision: @spree/sdk, @spree/admin-sdk, @spree/seller-sdk, @spree/core, the dashboard trio and @spree/seller-dashboard form one Changesets fixed group versioned from Spree::VERSION in npm spelling (6.0.0.rc7 → 6.0.0-rc.7), released by pnpm version:packages. @spree/cli and create-spree-app keep their own versions, since they manage projects rather than talk to the API. The switch lands at the release candidate after rc6 rather than at GA, so the migration path runs before release day. spree upgrade rewrites a project's ranges that are still on an older line, and names the exact @spree/sdk range for the storefront.
Consequences: A Spree release publishes every package in the group even when one has no changes, as the gems already do. A breaking change in the TypeScript code alone waits for the next Spree major. Projects from the preview update @spree/cli before upgrading, because the CLI they have does not know the new numbering. Stable 1.0.0 and 2.0.0 are never published for the group, and the old lines get an npm deprecation pointing at spree upgrade.
Plan amended: 6.0-beta-release.md (Key Decisions 2 and 3).
2026-10-25: Maintenance tasks ship for upgrade steps only
Context: The maintenance tasks plan built a general-purpose surface for operator-run data work: a dashboard list of tasks with a form built from each task's parameters, endpoints to list and describe tasks, CSV input, throttling, per-record error reporting, masked arguments, preconditions and parent runs for an orchestrating walk. By release, only the upgrade manifests register tasks, and none of those uses any of it. The unused surface was most of the pull request's size and still needed review, tests and documentation.
Decision: 6.0 ships maintenance tasks as the runner for upgrade steps. Removed before release: the dashboard's Tasks tab and run form, GET /maintenance_tasks and its SDK methods, csv_collection and the run's CSV attachment, throttle_on, report_on, mask_attribute, precondition, description, max_run_time, the after_start/after_pause/after_interrupt/after_cancel/after_error hooks, parent_run and spree:maintenance_tasks:list. Pause and resume went too: upgrade steps are short or safe to re-run, so a step that fails or is cancelled is started again, and the pausing/paused statuses, their services, endpoints, events and dashboard buttons are gone. Kept: the runner and its checkpoints, run history, cancel, dry run, batch size, step parameters, after_complete, the permissions and spree:maintenance_tasks:perform.
Consequences: A task an extension or host wants to run outside an upgrade has no dashboard surface; adding one back is a new decision, built when there is a task that needs it. Runs no longer mask argument values, since no step takes a secret. Runs are installation-wide and belong to no store: an upgrade step converts every store's data, so a run no longer records the store the operator was in, and the runner no longer sets a current store while a step works. The guide at docs/developer/how-to/maintenance-tasks.mdx now documents upgrade steps.
Plan amended: 6.0-maintenance-tasks.md (header note).
2026-10-25: An upgrade step is a rake task or a task class, never both
Context: The 2026-08-15 maintenance tasks decision made every 5.6 → 6.0 upgrade step a task class. In practice most steps are one-pass updates that kept their rake body, so each step was declared in up to five places: the manifest, the rake task, a ten-line wrapper class naming that rake task, a line in the engine's registration list and a translated description repeating the manifest name. Six steps went further and carried the same logic twice, once in the rake task and once in the class, so a fix to one could miss the other.
Decision: The manifest is the only list of steps, and each step names exactly one of task or task_class. A one-pass step names its rake task and runs through the shared UpgradeStep runner, which records it like any other run. A step gets a class of its own only when it walks rows (progress, resume, dry run) or asks the operator for parameters, and then it has no rake twin. Task classes named by a manifest are registered from it, so neither core nor a provider gem keeps a second list. The history labels a one-pass step by its step id.
Consequences: Adding a step is a manifest entry plus either a rake task or a class. One-pass steps share one task name, so the history filter cannot single one out and two of them cannot run at once, which an ordered upgrade does not need. 38 classes (34 wrappers and four one-pass steps), their registrations and descriptions, and two duplicate rake tasks are removed; seven classes remain (five with parameters, two row walks).
Plan amended: 6.0-maintenance-tasks.md (Key Decisions, Upgrade manifest integration).
2026-10-24: A marketplace decides whether, what and under review its sellers may upload
Context: With sellers able to attach downloadable files to their products (the entry below), any approved seller can put a file on the marketplace's domain that buyers download trusting the marketplace's brand. Nothing in Spree scans a file's contents, and before this there was no way to keep seller uploads off, to narrow what they may be, or to re-check an approved listing whose file changed. Digital asset writes were also plain model saves in two places, so a host had no point at which to refuse an upload.
Decision: Three store settings, shown on the dashboard's Marketplace settings page. seller_digital_assets_enabled is off by default, like the two auto-approve settings: what a buyer downloads under the marketplace's name is something the marketplace vouches for, and that should be a choice. Off, a seller can neither add, replace nor remove files on their products. seller_digital_asset_content_types is an allowlist checked against the file's own signature where the format has one, never the file name; a signature-less format such as plain text keeps its declared type. Its default covers the formats digital goods usually come in and leaves out executables, scripts, SVG and unrecognised binaries. The operator's own uploads are not restricted. review_seller_digital_asset_changes is on by default: a seller adding or replacing a file on a listing already on sale sends it back to review, off sale until approved again; changing limits or deleting does not, and the rule is moot when seller products auto-approve. The submission row records the reason and who made the change, and the seller panel says so before the seller acts. Every digital asset write, from either endpoint or nested in a product write, runs through one workflow with hooks, so a host that scans uploads has a single place to refuse a file before it is attached. Core ships no scanner. The seller /me response carries the settings the panel needs under store.
Consequences: A marketplace that reviews listings will see approved products drop off sale for a file swap until it approves them again; the alternative, holding the new file in quarantine while the old one keeps serving, needs file versioning and is deferred to the uploads scanning work. ZIP is on the default list, so the allowlist is a policy, not protection. Opening uploads to sellers is now an explicit step in setting up a marketplace, documented beside the auto-approve settings. The 6.1 upload-scanning design (a scanner registry with a no-op default, a verdict on the blob, delivery refused while pending) builds on these hooks rather than on the controllers.
Plan amended: 6.0-digital-assets.md (Seller panel decisions, Migration Path step 9, Constraints on Current Work).
2026-10-24: Sellers manage the downloadable files on their own products, uploads only
Context: A marketplace seller could list a digital product, but only the operator could attach the file it delivers (GitHub #14965). The Seller API had a file upload endpoint and nothing to attach the upload to a product.
Decision: The Seller API gains /api/v3/seller/products/:product_id/digital_assets (index, show, create, update, destroy), rooted in current_seller.products, so another seller's or the marketplace's own product is a 404. Writes need :update on the product, so a read-only seller role can list files but not change them. Sellers upload files and may set the per-file download limits. They cannot pick a digital asset provider and never see provider settings: a provider is the operator's own integration into internal systems, and letting a seller choose one would route the seller's sales through it. Files are added from the product's edit page only, not while creating a product. The admin and seller endpoints share their write logic, their request shape and their serialized fields, and both panels render one Digital files card from @spree/dashboard-core.
Consequences: An asset the operator created with a provider still appears on the seller's product, and the seller may change its limits or delete it. Opening providers to sellers later means adding them to the seller request shape and registering providers on the seller panel's client; nothing else changes. Pre-save file attachment on the seller's new product form remains open until a seller asks for it.
Plan amended: 6.0-digital-assets.md (Seller panel decisions, Migration Path step 9).
2026-10-19: A self-service data request is confirmed from its email address before Spree acts on it
Context: A customer's own access or erasure request covers the guest orders, carts, cards and consent recorded at the account's email address, so that someone who checked out as a guest and registered later receives their whole history. Spree never confirms that an account's email address belongs to the account holder, so a request should not reach rows at that address until the address itself confirms it.
Decision: A request a customer raises for themselves starts as awaiting_confirmation and does nothing until it is confirmed from the address it names. Spree publishes data_request.confirmation_requested with a confirmation token, gated with credential: 'write_customers' like customer.password_reset_requested, and its key joins Spree::WebhookPayloadRedaction::SENSITIVE_PAYLOAD_KEYS, so the webhook delivery log stores [REDACTED] in its place. spree_emails sends the link, and a headless storefront can send it from a webhook instead. As in the newsletter and password reset flows, the request takes a redirect_url, kept only when it matches one of the store's allowed origins, and the email links to <redirect_url>?token=…, falling back to the store's storefront URL. That page acts only when the person presses its button, which calls POST /api/v3/store/data_requests/:token/confirmation: some mail scanners open links and run the page's scripts, so a page that confirmed on load could erase data nobody approved. Only then is the request queued, and it matches guest rows by email as before. The download link is given only to whoever holds the token, by email or through the token-addressed read; the account's own session sees the status and never the link. After 24 hours an unconfirmed request can no longer be confirmed, and it is marked lapsed the next time the customer asks, follows the link or is erased. Erasure still asks for the account password. Staff-raised requests skip confirmation, since staff check identity themselves. A verified-email flag on the customer was rejected for now: it would add state that every email change must clear, and no other feature needs it yet. Limiting self-service requests to rows the account owns was also rejected, because a former guest would then never receive their full history.
Consequences: Every self-service request costs one extra email, and an access request sends a second one when the file is ready. A store with neither spree_emails nor a handler for the event cannot complete self-service requests; staff requests still work, and the docs say so. download_url stays in the Store API response but is null on the account's own reads, which matters only to 6.0 prerelease adopters, since no stable release had data requests. The storefront gains the confirmation page in the same change, since it has no page for the newsletter's links either and a link to the storefront's home page would confirm nothing; and spree_emails gains a customer email that merchants can edit. awaiting_confirmation and lapsed join DataRequestStatus.
Plan amended: 5.4-6.0-eu-legal-compliance.md (Key Decision 8 and the Constraints on Current Work).
2026-10-17: Certificates point at their exemption reason
Context: Certificates stored a copy of their reason's code, so a code had to be locked once any certificate used it. A new store's seeded reasons could then never be switched to Avalara's codes, and finding a reason's certificates meant joining through companies on a copied string.
Decision: Spree::TaxExemptionCertificate belongs_to :tax_exemption_reason, like products and tax categories; the API takes tax_exemption_reason_id. A reason's code can change at any time and is stored in upper case. A tax line's exemption snapshot keeps the reason's name beside its code.
Consequences: Merchants on Avalara change each seeded code to Avalara's. Placed orders keep the code and name they were taxed with. A spree:upgrade:tax_exemption_reasons step seeds existing stores, saves existing codes in capitals, and links certificates recorded before reasons existed to the reason matching their old reason_code, which the migration keeps (nullable) for that purpose; until it runs, tax still reads an unlinked certificate's old code. The dashboard offers an engine's own codes only once a market uses that engine.
Plan: 6.0-tax-provider.md.
2026-10-16: Tax exemption reasons are a store-owned model
Context: The reasons a merchant records on a tax exemption certificate came from a code registry: six values hard-coded in core, replaced by the vocabulary of whichever tax provider gem registered one. Spree's own tax engine never reads the reason, so for most stores it was a label the merchant could not rename, translate or extend, unlike every other reason list.
Decision: Spree::TaxExemptionReason is a store-owned model (name, code, active), managed beside return, claim, refund and order-cancellation reasons through /api/v3/admin/tax_exemption_reasons. A certificate keeps its reason_code string, which must name an active reason of its store when set. A tax provider declares the codes its engine understands (exemption_reason_codes, published on /tax_providers) so the dashboard can offer them, but it does not own the list. The registry, the default list in core and the …/tax_exemption_certificates/reason_codes endpoint are removed.
Consequences: Seeds give each store six neutral reasons; the Avalara upgrade task adds one per Avalara entity use code. A provider whose engine reads reason codes adds exemption_reason_codes rather than registering a list.
Plan: 6.0-tax-provider.md.
2026-10-16: The market decides whether prices include tax, and prices are no longer adjusted for buyers abroad (V-3662, reverses 2026-08-11)
Context: A store whose home country is the US sold into a Eurozone market marked tax-inclusive. A €527.99 book shipped to Berlin was charged €564.95: the 2026-08-11 rule took the US's 0% out of the price and put Germany's 7% in, so the product page and checkout disagreed. Whether a price includes tax was spread over three places: TaxRate#included_in_price, which Spree's own tax tables read; Market#tax_inclusive, which the API and dashboard exposed but no code read; and the restatement, which assumed every price included the home country's tax. A first fix for #14833 added a per-market tax_display and a main country per market; review rejected a second setting beside the unused one.
Decision: Market#tax_inclusive is the one setting. On, every customer of the market pays the price as entered, with their own country's tax inside it; off, tax is added at checkout. Spree's own tax tables read it through Purchase::Taxation#tax_inclusive? (with no market, the store's default market answers), and every provider receives it as tax_inclusive: on estimate and estimate_replacement. Refunds keep the included flag the sale's tax lines recorded, so editing a market never changes a placed order. TaxRate#included_in_price leaves the Admin API, the SDK and the dashboard; the column stays until 6.1 for spree:markets:backfill_tax_inclusive, which sets each market from the rates covering its countries (all included sets true, all added on top sets false, a mix is left unchanged and reported). It reads each rate's flag once and clears it, because every upgrade re-runs every step, and new rates leave the flag empty. Restatement is removed, with VatPriceCalculation, PriceRule#geographic? and Price#final_for_destination?: it ran only on the Internal provider, showed a multi-country market the main country's price until checkout, and broke round prices. Without it the home country prices nothing, so markets keep no main country of their own. Commission tax reads every matching rate, since a commission's tax is added on top whatever a market does.
Consequences: A merchant who wants a different price in some countries gives them a market of their own with a price list, and one market cannot mix conventions by country. A 5.x store with a default tax zone, and a store on the 6.0 release candidates, charges buyers abroad the price as entered after upgrading, which the upgrade guide says. Commission VAT in an EU store whose rates were all marked included now uses the real rate rather than the store default. A provider that names its keyword arguments must accept tax_inclusive:. A business buyer with a valid tax number pays the price as entered in an inclusive market; whether they should pay it without tax stays open. Restatement can return in 6.1, reading the storefront's country, or as a country rule on price lists, if merchants ask for it.
Plans amended: 6.0-tax-provider.md (the cross-border Key Decision, Phase 8, the Phase 9 tax_inclusive item and the Constraints on Current Work).
2026-10-10: One upload endpoint, store-owned blobs, and <slot>_signed_id everywhere
Context: Files reached Spree through /direct_uploads, which copied Active Storage's nested request and minted references that never expired, and nothing recorded which store a blob belonged to. Endpoints that took those references named them seven different ways.
Decision: POST /api/v3/admin/files and POST /api/v3/seller/files replace /direct_uploads with no alias: a flat request, visibility (public/private), presigned or multipart bytes, and one response carrying an opaque signed_id that expires after a day. Blobs gain a nullable store_id, set on every creation and backfilled by the 6.0 upgrade; attaching a blob from another store is logged in 6.0 and refused in 6.1. Every parameter that takes an upload reference is signed_id or <slot>_signed_id (avatar_signed_id, logo_signed_id, po_document_signed_id, …). Public uploads are allowlisted (web images, videos, CSV); private uploads accept any type. A daily job purges blobs never attached, after Spree::Config.unattached_upload_retention_days. The Store API purchase-order presigner keeps its cart-nested route but adopts the same contract. In 6.1 blobs also record who uploaded them.
Consequences: A new endpoint that takes a file uses <slot>_signed_id, never file, document or attachment. A blob Spree creates must belong to a store: pass store_id, or create it where Spree::Current.store is set. API responses never contain a blob id, storage key or Rails blob URL; a response offering an existing file for reuse mints a fresh expiring signed_id. Supersedes 6.0-digital-assets.md's "never multipart through the API request": multipart is allowed for small files through /files.
Plan: 6.0-uploads-and-file-ownership.md.
2026-10-10: Agent tools run through the Admin API, not beside it
Context: The MCP branch (PR #14664) built its tools as a second way into the same data — their own store scoping, permission checks, Ransack call, writable-attribute lists and error shape, about 3,900 lines of Ruby. Probing the branch found three faults, all the same fault. A prefixed id filters nothing: search_resources calls .ransack directly and skips the controller step that decodes ids, so filtering variants by product_id_eq: "prod_3uWpPTcf5W" — the only form the tools return — answers 0 where the raw id answers 3, with no error. Extension attributes are invisible, because the writable list reads resource_permitted_attributes but not additional_permitted_attributes. And the stock upsert wrote to whichever shelf an id named, including another store's, because the scoping lived in its one caller.
Decision: A tool call runs the real Admin API request path — routing, authentication, controller, serializer, error format — dispatched in-process through Rails.application.call with the caller's own credential and Host header. No internal trusted header, which would rebuild the boundary this removes. No HTTP to itself: a socket back to the same app holds one Puma thread waiting on another, so concurrent tool calls on a small pool deadlock it.
Spree::Current does not reset across a nested dispatch — probed: an inner call overwrote the outer request's currency — so the adapter snapshots and restores it, with a spec proving a tool call cannot corrupt the MCP request's own state. Tool calls do not run inside a transaction the MCP controller opened.
The catalog is the lasting asset: each entry names an operation, a permission, a description and a parameter projection, with schemas from OpenAPI rather than Ruby signatures. A capability with no endpoint becomes an endpoint first — the rule the dashboard already follows.
Two simplifications follow. Generic create, update and destroy become correct for every resource, because the controller behind each runs whatever workflow it declares — the old rule that a resource with a workflow refuses the generic write existed only because those writes skipped workflows. That leaves dedicated tools for the non-CRUD member actions alone (cancel, complete, capture, fulfil, approve, activate). And the catalog is keyed by OpenAPI operation rather than by Spree::Dependencies key, so the contract spec walks admin.yaml instead of scanning controller source — and does not rest on a mechanism being replaced by workflow hooks.
Two operational notes recorded with it: the rate limiter counts the dispatched operations, not the MCP envelope, or one agent turn counts twice; and the adapter trims index responses until the Admin API has sparse fieldsets, since a full admin payload is more than a model's context should hold.
Consequences: Every guard added to the Admin API protects agents by construction. The prefixed-id fault stops existing rather than being patched, and the hand-written writable lists go. The branch loses more Ruby than it gains, which is the measure of the step. At 7 the same catalog runs under TypeScript with @spree/admin-sdk, differing only in which fetch it is given, so the Ruby adapter is deleted rather than ported. Credential filtering stays in the agent layer: guarding what leaves for a model is not the API's job.
2026-10-09: Typed filters keep sellers association-free, take arrays for _in, and ship no 5.x warning
Context: List filters are being generated into OpenAPI and the SDKs from the Ransack allowlists, and PR C will reject unknown filters. Three choices fix what the published contract says before that happens.
Decision: The Seller API reaches no associations through filters, as today; related-data filters for sellers are scopes. _in and _not_in accept arrays only, never comma-separated strings. There is no 5.x deprecation release: the upgrade guide covers the change, and PR C adds a Spree.api.strict_filters setting (default on) that a store can turn off for one release.
The published predicate set also gains i_cont for text and not_eq/in/not_in for true/false attributes, which the dashboard's filters already send.
Consequences: Seller SDK filter types stay attribute-only. A client sending q[status_in]=a,b gets a 400 once enforcement lands, which is the same empty result it already gets, made visible. Self-hosted stores learn of undeclared filters from the upgrade guide and the escape hatch, not from a warning in production.
Every searchable list gets a q[search] filter declared with search_by, which the dashboard's search boxes use; the API reference documents filters as a generated table per endpoint rather than as thousands of expanded parameters.
An app's own filters, which the published SDK types cannot know, are sent unchecked in q, generated into declarations with spree filters types, or declared by hand on …FilterExtensions.
Plan: 6.0-typed-filters.md.
2026-10-09: Spree stops parsing numbers by locale
Context: Price, variant, payment, refund, store credit, gift card and adjustment setters re-parsed every string with Spree::LocalizedNumber under the request's locale, for the legacy Rails admin. That admin is gone. In a store whose language writes a comma decimal (nl, de, fr) the setters read the dashboard's canonical "49.50" as 4950, and an untouched "99.0" grew tenfold on every save.
Decision: The locale-parsing setters are replaced by strict ones: a number or canonical decimal text is stored exactly, and any other text raises Spree::Money::InvalidFormat rather than being silently misread. Spree::LocalizedNumber.parse is deprecated with a warning and removed in 6.1. Clients normalize localized input before sending (5.5 plan). The dashboard shows and reads money in the admin's own dashboard language, whatever the currency or market (as Shopify does), instead of the currency's market locale, which was ambiguous when markets share a currency.
Consequences: A localized string sent to a model ("1.234,56") is refused with invalid_money_format; the Admin API never accepted it by contract. Supersedes the 5.5 plan's "LocalizedNumber.parse is NOT removed". See 6.0-money-correctness.md.
2026-10-08: Money is BigDecimal end to end, gateways get amount plus currency, strict canonical strings on the wire, and decimal(19,4) in the database
Context: Money columns were already decimal, but several money paths went through floats (Ruby .to_f, dashboard parseFloat). A few serializers emitted JSON numbers while the rest emitted unnormalized strings ("10.0"). Every gateway call was made in hundredths of the currency while Stripe sessions used ISO minor units, so yen captures recorded 100× the amount and dinar captures a tenth, and Stripe's own units differ from both for ISK, HUF and TWD. decimal(10,2) could hold neither a dinar's third decimal, a sub-cent unit price, nor a large dong order.
Decision: No float on a money path in Ruby or TypeScript, stated as a rule in CLAUDE.md (a lint cop was tried and dropped on 2026-10-09); @spree/sdk-core gets a string-based decimal helper. Currency exponents are ISO 4217 from one Spree-owned file, registered over the Money gem, imported by sdk-core and exposed as decimal_places on currencies. Gateways receive a Spree::Money and each adapter converts to its provider's unit; gateways that have not opted in keep receiving hundredths with a deprecation warning until 6.1. Every money field in every v3 serializer is a decimal string: exactly the exponent for totals and money that changes hands, up to four decimals for unit prices. Rates and percentages are decimal strings with trailing zeros stripped; _percent means 0–100, rate means a fraction, and no rate is named like money. Admin and Seller writes reject JSON numbers, non-canonical strings and over-precise strings with 422 invalid_money_format. Money columns become decimal(19,4) in one idempotent migration with a documented online path. Rounding happens only when persisting, in a gateway adapter, or when serializing, with the mode a parameter and tax providers owning theirs. Existing wrong capture events are reported, never rewritten. The migration changes all of a table's money columns in one ALTER TABLE and does not restate null/default (which PostgreSQL and MySQL keep through a type change), so each table is rewritten once; it is marked safe for apps using strong_migrations.
Consequences: Breaking for API clients sending numbers or comparing money strings, for clients reading the removed *_in_cents fields or the renamed tax rate fields, and (from 6.1) for gateways that never opt in. HUF stops rounding to whole forints. Open carts in zero- and three-decimal currencies change on their next recalculation; completed orders do not. Integer minor units are rejected as an API contract. Ships as four PRs: floats out, gateway amounts, wire contract, precision.
Plans amended: 5.5-client-side-money-normalization.md (its "lenient now" open question is settled as strict). See 6.0-money-correctness.md.
2026-10-09: Preferences are typed on the wire, and the preferred_ prefix leaves the API
Context: Preferences reached the v3 APIs as the Ruby DSL rather than a contract. Store, channel and import settings were exposed as preferred_* fields, and every configurable subtype (promotion rules and actions, calculators, payment methods, integrations, rules of every kind) sent an untyped preferences object next to a preference_schema written in Ruby type names, repeated on every row. The real rules (prefixed-ID decoding, country normalization, rejecting unknown keys) lived in code no client could read.
Decision: The preference declarations stay the single source and become complete (of:, keys:/values:, money:, choices:, format:, prefix:). They compile to JSON Schema, which feeds the OpenAPI components, the SDK unions (one member per built-in subtype plus a fallback for plugins), the /…/types endpoints (schema replaces preference_schema, which leaves resource rows) and the validation of every preferences write (422 invalid_preferences with a JSON pointer per failure). preferred_* fields are renamed to plain names through exposes_preferences on the model; order.preferred_stock_location_id is an association and stays. The store's storefront_url setting takes the plain name; the model's reader keeps the fallback to the first allowed origin and the store URL, while the API returns the stored setting and url carries the effective address. Old preferred_* keys are accepted on write until 6.1 with a deprecation warning. exposes_preferences grants no write access; each API keeps its own permitted list. Incomplete declarations in plugins warn and get a permissive schema in 6.0, and raise in 6.1. Delivery methods move to the nested calculator: { type, preferences } shape. All three phases ship in one pull request.
Consequences: A new preference declares its full type and never uses :any; an ID list is of: :id, prefix:, never a decoding lambda; no serializer or permitted list gains a preferred_* name or a preference_schema; a new configurable family publishes a /…/types endpoint and a typed union with a fallback member. The Store API is unaffected; the Admin and Seller APIs break, and every rename is listed in the upgrade guide.
Plan: 6.0-typed-preferences.md.
2026-10-07: Translations move into core, and Spree.t is deprecated for I18n.t
Context: Spree.t ran through Rails' view translation helper, so it needed Action View and returned <span class="translation_missing"> markup for a missing key, which leaked into JSON errors and dashboard notifications. Every language but English lived in spree_i18n: 6.5 MB of locale files, about 60% for the removed admin and storefront, plus kaminari-i18n (which requires the full rails gem), i18n_data (which swaps the global I18n.backend) and spree_extension.
Decision: Core calls I18n.t with full keys (I18n.t('spree.free')). Spree.t stays until 6.1 as a deprecated one-line proxy onto I18n.t, with no Action View and no HTML. The translations still used by core, the API and emails move into those gems' config/locales, trimmed to keys English has, after dead English keys are pruned. rails-i18n becomes a spree_core dependency; i18n_data, kaminari-i18n and spree_extension are dropped. Untranslated keys fall back to English: core sets [:en] when the app configured nothing and appends English to Rails' generated fallbacks = true. Regional English is not shipped; other regional variants keep only their differences. Spree's own specs raise on a missing key. spree_i18n gets an empty 6.0.0 release that warns, then is archived.
Consequences: Every install gets 43 languages besides English without an extra gem; regional English falls back to en. A missing key is plain text in production. Extensions calling Spree.t keep working with a warning. Removing a key the checker reports unused is a reviewed step: it cannot see keys passed around as strings or built from a value one level under spree.
Plan: 6.0-translations-in-core.md.
2026-10-04: Creating a payment session always opens a new one
Context: Handing back the cart's open Stripe session and re-pricing it (2026-09-30) drifts from the intent Stripe actually holds. The amount, the saved card, the customer and the ephemeral key are each updated on their own, and a failure partway through leaves Spree and Stripe describing different sessions. The storefront asks for a session every time the payment step loads, so that drift is the common path.
Decision: create_payment_session opens a new session on every call. Every earlier session for that gateway that can still be paid — open, or failed after a declined confirm — is canceled at the provider first, so a reloaded checkout still cannot pay two intents. The cancel waits until each of those intents has been read: one Stripe has already accepted (paid, authorized, or a debit in flight, including a card charge still processing) fails the request with payment_in_progress, and nothing is canceled or opened. A session this cart has already completed is the same refusal, with no call to Stripe. A timeout, a rate limit or an outage while canceling fails the request the same way and leaves the existing intent open. An intent already canceled at Stripe, or one the account the keys now reach does not have, is marked canceled locally and the new session still opens. The placement job that cancels sessions left with no payment is unchanged, and it now includes a failed session.
Consequences: A second request answers 201 with a new session, and the previous one is canceled. Checkout that reloads the payment step opens a new PaymentIntent each time. A buyer who already paid still gets payment_in_progress rather than a second charge.
Plans amended: 6.0-payment-gateways-monorepo.md (the one-open-session constraint now says the previous session is canceled, not handed back).
2026-10-01: Preferences are stored as JSON, and secrets move to an encrypted column
Context: Every preferences column is a YAML document written by one line in Spree::Preferences::Preferable. YAML loading is an attack surface Rails fences with a permitted-class list Spree has to inject; the columns cannot be queried; and the two 6.0 tables that declared preferences as JSON (delivery method rules, commission rules) actually hold a YAML document wrapped in a JSON string, because the shared coder still writes YAML.
Decision: JSON replaces YAML for every preferences column, with no Spree-specific coder: the column type does the conversion, and the metadata columns' HashSerializer lets the loaded hash answer to symbol and string keys; the preferred_* readers restore decimals and times from their declared type, and every other value comes back as JSON stores it. Decimals are exact strings. The conversion runs inside the 6.0 migration, reading rows without models, because spree:upgrade runs after db:migrate and would find the YAML column gone. A row still holding YAML raises when read and the upgrade task converts it; a boot check was rejected because it would block the migration that repairs the data. The tiered promotion calculators move their tiers from a hash with number keys to a list of {threshold, value} objects. Preferences declared :password are stored in a separate secret_preferences column with Rails' encrypts, so preferences never holds a secret; the declaration DSL does not change. Encryption applies whenever keys are configured, as for Spree's other encrypted fields; new projects have keys from setup. The migration moves existing secrets across in plain text, they stay readable through support_unencrypted_data, and an upgrade task encrypts them. The spree_preferences key-value table, whose only live row was the installation id, is dropped without copying the id; the default store generates a new one in an internal preference. Rejected: encrypting values inside the JSON by hand, and a polymorphic credential model.
Consequences: New preferences columns are JSON. Hash preferences must not use number keys. Every secret must be declared :password, the only type that is encrypted, and a table whose classes declare one needs a secret_preferences column. The tiered calculators' tiers value changes shape in the Admin API. See 6.0-json-preferences.md.
2026-09-30: A cart keeps one open Stripe intent, and the ones left behind are canceled once the order is placed
Context: Two Stripe payment sessions on one cart could both be paid (V-3726). Reproduced on main: a $55.00 cart, two POST /carts/:id/payment_sessions answering 201 with two $55.00 PaymentIntents, both confirmed through their own client secrets, and order R1001 placed with one $55.00 payment while Stripe held $110.00. Two concurrent requests are not needed, since the endpoint's cart lock already runs them one after the other: SpreeStripe::Gateway#create_payment_session opened a new intent on every call. The standalone gem reused the order's intent (CreatePaymentIntent, then CreatePaymentSession), but only its Rails checkout called that service, the port left the service with no callers, and it was deleted on 2026-08-12. The storefront creates a session every time the payment step loads, and whenever the buyer picks another saved card, so a second tab was enough. Switching payment method had the same result: a Stripe session followed by a Check payment placed order R1002, paid by check, and the abandoned intent could still be confirmed for $55.00 afterwards. Stripe's notification for the extra charge then fails the payment's cap on what is still owed, is reported, and records nothing.
Decision: Creating a Stripe session hands back the owner's open session for that gateway (pending, or being settled), re-priced, with a fresh ephemeral key, since Stripe expires those after an hour. A session opened for another Stripe customer, currency or saved card, or one Stripe will not re-price, is canceled at Stripe before its replacement opens, so no refusal can lock a cart out of paying by card. The exception is an intent Stripe has already accepted: paid, authorized, or a debit in flight. Stripe would cancel an authorization or a processing debit, so the request fails with payment_in_progress instead, and nothing is canceled or opened. An intent canceled at Stripe, or one the account the keys now reach does not have, is replaced. Core's payment-session contract gains PaymentMethod#cancel_payment_session. When Orders::Complete places an order that still has sessions pending with no payment, it enqueues Payments::CancelUnusedSessionsJob, which calls it for each one. The cancel is one provider call per session, so it runs in a job rather than holding up placement (review on #14777); the job enqueues only after the surrounding transaction commits, since a webhook places the order inside its own. The Stripe gateway cancels the intent, and the default leaves the session untouched, because a gateway that cannot cancel at its provider must not show as canceled a session that can still be paid. A provider refusal is reported and not retried, and the job's cursor keeps a resumed run from asking the provider again. The reuse lives in the gateway rather than the endpoint because only the gateway can tell a re-priceable intent from one that is paid or canceled.
Rejected: canceling every earlier session whenever a new one is created, which would open a new intent on every checkout load and was not how the gem behaved before. Rejected: refunding or flagging money that arrives for an order already paid; money should not be taken twice in the first place.
Consequences: Stripe is left holding at most one charge for the issue's steps: the second confirm is refused as already succeeded. The buyer can still pay twice in one case: they confirm Stripe, and then pay with another method before Stripe's notification completes the cart. That money has already moved, so the cancel is refused and reported, and nothing refunds it. Between placement and the job running, a leftover session can still be paid; the window is how long the queue takes to reach the job. Re-creating a session now answers 201 with an existing session. A buyer who paid in one tab and closed it, on a store without Stripe webhooks, gets payment_in_progress in the next tab rather than a second charge; the order still waits for the webhook, as it did before. The cancel runs only at placement, not when Orders::Complete replays a placed order: 6.1's pay-balance sessions live on placed orders, and a replay would cancel them. So a crash between placement and the enqueue leaves the leftover payable. Gateways outside the monorepo keep today's behaviour until they implement cancel_payment_session and reuse their own pending session; spree_adyen has not been checked. The intent's transfer_group and metadata.spree_order_id still carry the cart's prefixed id and raw database id rather than the order number; that is a separate issue.
Plans amended: 6.0-payment-gateways-monorepo.md (the Stripe keep-set note on CreatePaymentSession, a Constraints on Current Work bullet on one open session per gateway).
2026-10-02: Adding a fulfillment moves only bought units, and re-prices only the new parcel
Context: Adding a fulfillment for an exchanged line could fulfil the replacement instead of the line's own goods (V-3708). Reproduced on main, after the 2026-09-25 replacement flag: order R1004, one Stainless kettle at $79.99 plus $5.00 Standard delivery, shipped, exchanged for Matte Black, then raised to 2. The extra Stainless unit joined the replacement's $0.00 fulfillment behind the Matte Black unit. POST .../fulfillments for one unit of the line answered 201 with a new fulfillment holding the Matte Black replacement, and delivery went from $5.00 to $15.00. There were two causes. Fulfillments::Create#fulfillable_units offered every unshipped unit filed under the line, replacements included, sorted in-stock first and then oldest first, so whether the merchant got the line's goods depended on which unit happened to be created first. Then reprice_pending_fulfillments re-quoted every unshipped fulfillment on the order, not just the new one, so the replacement's $0.00 became $5.00 on an order nobody had asked to re-price. The re-pricing loop came over from the old updater's completed-order branch and was never a recorded decision.
Decision: Product calls, made on the issue: order-wide, a line's units are only the ones the customer bought, and adding a parcel re-prices only that parcel. Create takes an optional source_fulfillment:. Without one, fulfillable_units leaves flagged units out, so a replacement is never moved, drained or counted toward the quantity a request may ask for. With one, units come only out of that fulfillment, replacements included, bought units first. Fulfillments::Fulfill passes the parcel it is shipping when it splits one, so a partial dispatch can ship part of a replacement parcel and can no longer pull a unit out of a sibling, which its own guard already promised. Its shelf check moves after the split, which a refusal rolls back, and reads the units that actually moved: a request names a line, and the line's replacement is another variant, so a check that summed the request under the line's variant never looked at the replacement's shelf and let the stock write fail inside the dispatch. That transaction becomes a savepoint, as Orders::Update's is: Workflow#call rescues a failure, so a transaction that joined the API's order lock would commit the refused split. Seen on R1008 with the check moved but no savepoint: the 422 left the replacement parcel split in two. The Admin API exposes the same option as source_fulfillment_id, resolved through the order's fulfillments. That is how a canceled replacement is sent again, since a canceled parcel never ships and splitting one does not promise its stock again. Create re-prices only the fulfillment it builds, and every other fulfillment on the order keeps its cost. A unit moved out of a named source keeps its replacement flag, as the 2026-09-25 entry requires.
Rejected: taking bought units first and falling back to replacements when they run out. That would keep a larger request working, but the extra units would be goods the customer never bought on that line. Rejected: a switch letting only Fulfill include replacements. It would mend partial dispatch, but the split would still search the whole order and could take another parcel's replacement. Rejected: leaving replacements in canceled parcels available order-wide, which can reach them only by asking for more than the bought units and moving those too. Rejected: re-pricing every fulfillment except those holding replacements. The source parcel losing a unit is the same edit as any other, and a completed order's delivery is re-priced only by an explicit post-placement edit.
Consequences: A request for more of a line than its bought units now answers with the existing insufficient-quantity error, where it used to sweep up replacements. The same applies when items is omitted. A source fulfillment keeps its cost after units leave it, even when its calculator would now quote less. The new parcel still gets its own delivery charge, as a split parcel does, and a re-sent replacement is no exception: R1006's re-sent Matte Black kettle was priced $5.00 and the order turned partially_paid. Passing cost: 0 carries over the canceled parcel's $0.00 instead. Within a named parcel, a request still names a line rather than a unit, so a parcel holding a line's bought unit beside its replacement ships the bought one first. Left alone, all pre-existing: the dashboard counts replacement units toward a line's held quantity, so it never offers Add fulfillment for a line in this state, and the defect was reachable only through the Admin API. It offers no way to re-send a canceled parcel either. A raised unit can still land in a pending replacement fulfillment, which carries no delivery charge (2026-09-25). A pending new parcel is re-quoted even when it inherited a drained parcel's cost, so the "keeps the order total unchanged" promise on cost holds only when the rate has not moved. apply_status does not check the result of the inner Fulfill. A split that a later step of Fulfill rolls back has already run Create's after_create hooks, as a failed tracking write could before. Any other workflow transaction that joins a caller's open one has the same exposure as the split had, including Fulfill's dispatch transaction and Create's own under the create endpoint's lock: a failure after a write commits that write. The fix belongs in Spree::Workflow, not in each caller. Draining a source in Create destroys it, so a re-sent canceled parcel leaves no record of the cancellation on the order.
Plans amended: 6.0-returns-exchanges-claims.md (the replacement-unit note).
2026-10-02: A refunded return leaves nothing owed on the order
Context: Every order refunded through a return read as owing the refund back. Reproduced on R1004: total $50.26, paid $50.26, a return refunded $25.00 to the card. The admin summary showed payment total $25.26 and an outstanding balance of $25.00 in red, and the payment dialog pre-filled $25.00 to charge again. R1001, refunded before V-3725's fix, read the same. Carts::RecalculateTotals nets refunds out of payment_total, and Order#outstanding_balance is total − payment_total, so a refund for goods that came back raised the balance by exactly its amount. 5.x added the money returned through reimbursements back (reimbursement_paid_total); the legacy drop removed that term in the belief that netting refunds already covered it, and the returns plan recorded that reasoning. Store-credit refunds were never affected, as they write no refund row.
Decision: outstanding_balance subtracts returned_items_refund_total — refunds whose originator is a return, claim or exchange — restoring what the reimbursement term did. A refund with no originator still raises the balance: money handed back for nothing is owed again, as in 5.x.
Consequences: amount_due, which the Admin, Store and Seller APIs serve and the dashboard shows, reads zero after a refunded return. An exchange's balance owed still shows, because it is a fee on the order rather than a refund. The column payment_total is unchanged; only the balance reads differently.
Plans amended: 6.0-returns-exchanges-claims.md (Implementation Status — the outstanding_balance note).
2026-10-01: A buyer can buy only what their catalogs show them (V-3722)
Context: Catalogs narrowed the product listing and product reads, but the cart looked variants up across the whole store. A company buyer whose catalog hid a product could add it by sending its variant id, and check out with it; the same lookup let a shopper add a product not published on their channel. A product read answered 404 for both. Blocking adds alone would not close it: a guest cart claimed after sign-in, a cart switched to another company, or a catalog edited while a cart is open all leave a hidden line in the cart without any add.
Decision: Visibility is purchasability. The storefront's three item-writing paths (add item, and creating or updating a cart with items) resolve variants through Spree::Cart#orderable_variants — Products::ForContext asked about the cart's own customer, resolved company and channel — and answer 404 for anything outside it. Cart updates resolve after the cart's own attributes are saved, so a company named in the same request decides the catalogs. Completion re-checks every line and refuses a hidden one with a not_orderable requirement naming it, rather than silently removing it on read. A promotion's free gift gets no exception: merchants keep gift products inside the catalogs of the buyers they target. Staff draft orders are exempt, as they are from quantity terms, and the admin order workflows are untouched. A visible product with no price in the cart's currency keeps its 422 explanation, so the narrowing deliberately leaves out the listing's currency filter. Of the publication window it applies only the end: a publication whose unpublished_at has passed is the product's discontinuation on that channel, so the add answers 404 and checkout keeps its existing discontinued requirement for a line already in the cart, without a second not_orderable for it. The start is left out because the listing admits a product scheduled to publish later when it can be pre-ordered.
Consequences: Carts::UpsertItems takes an optional orderable_variants: relation; an app that swapped cart_upsert_items_workflow for a class not accepting it must add the keyword. A cart line for a product unpublished from the channel now blocks checkout until removed. A line already in the cart is a quantity edit, not an add, on both the item endpoint and a cart update: it is judged at completion, so one stale line cannot fail every other change a cart update carries. Not covered: a product whose channel publication starts in the future and cannot be pre-ordered can still be added, and the hidden line is only reported at completion — the cart's advisory requirements do not list it, the same trade quantity rules make. A buyer in several companies may still see a listing resolved without the cart's company while the cart checks against it; that gap is the listing's, and predates this.
Plans amended: 6.0-b2b-companies-and-catalogs.md (Visibility, and a Constraints on Current Work bullet).
2026-10-01: No delivery is offered before the address, and the storefront never charges a delivery it has not shown
Context: The storefront charged a delivery method and total the buyer was never shown (V-3718). Reproduced on main: a signed-in buyer's checkout read Store Pickup $0.00, total $89.98; pressing Place Order booked order R1001 as Standard $5.00, $94.98, and the Check payment completed for $94.98. Two things combined. Every item change rebuilt the cart's delivery proposals whether or not it had a destination, and quoted without one, only pickup qualifies, so the estimator preselected it. That contradicted the 2026-08-02 rule that proposals wait for an address or a pickup intent, which only Checkout::Advance applied. The preselected pickup also made shipping_address_required? answer false, so a cart whose email had saved but whose address had not could complete as pickup without the buyer choosing it. Then pressing Place Order moved focus out of the address block, which saved the address. That rebuilt the proposals for the new destination and picked Standard, as the 2026-09-24 entry intends. Next.js runs a client's server actions one at a time, so the Place Order handler always re-read the cart after that save, and then paid without comparing it with what was on screen.
Decision: Whether a cart gets delivery proposals is one rule, Purchase::Addresses#can_propose_deliveries?: a shipping address, a pickup intent, or items that no delivery profile ships to an address (digital, or pickup-only profiles). Cart#rebuild_fulfillments! and Checkout::Advance both read it, so a cart that needs an address shows no delivery option until it has one, as Shopify's checkout does. The rule reuses the item half of shipping_address_required?, now extracted as items_require_shipping_address?. In the storefront, Place Order first waits for any address save the press itself started, rather than counting on Next.js running server actions one at a time, and stops if that save failed, because the cart still holds the old address. It then compares the delivery that was on screen at the press with the cart it re-reads. The on-screen delivery is captured on pointerdown, before the address block's blur save can re-render it, and compared as each shipment's selected option name and price, not ids, because a rebuild that keeps the choice (after a corrected phone number) issues new ids. If they differ, it pays nothing, puts "Choose a delivery method, then place your order again." on the delivery section and focuses the selected option. The check runs before payment, so it also covers payment sessions charged ahead of completion.
Rejected: sending the client's expected_total with completion (the Carts::Complete drift guard, which the Store API's complete endpoint does not pass through). A total cannot tell two methods at the same price apart, and a guard at completion comes after a payment session has already charged. Rejected: saving the address as soon as its last required field is filled. It would make the stop rarer, but a buyer can still type the ZIP and press straight away. Rejected: hiding delivery only in the storefront. The server would still preselect pickup and still consider such carts in need of no address.
Consequences: Before an address, the Store API cart has no fulfillments, and its requirements now list "Shipping address is required" and "Select a delivery method for all fulfillments". The storefront's existing "Enter your shipping address to view available shipping methods." message and the summary's "Enter shipping address" shipping line show again. A store whose items only offer pickup still gets its pickup proposal straight away. Carts built before this change keep their pre-address pickup proposal until their next rebuild; if that rebuild happens on the press, the storefront stop catches it. Draft orders are unchanged: Order#rebuild_fulfillments! does not read the rule, and admin draft-order building was out of scope. The expected_total drift guard stays unreachable from the Store API. Left open: a total that moves while the delivery stays the same, such as tax after a country change saved by the press, is not stopped; a buyer who wants pickup must enter an address first unless the client sets a pickup intent (preferred_stock_location_id), which the starter storefront has no control for; and DeliveryProfile#requires_shipping_address? counts back-office-only methods, so a profile whose only storefront method is pickup but which also has an admin-only courier waits for an address.
Plans amended: 6.0-fulfillment-and-delivery.md (Rebuild triggers).
2026-10-01: Returns, claims and exchanges give back the tax the customer paid, as the tax provider decides
Context: A return never refunded tax charged on top of the price (V-3725). Reproduced on R1001: Shirt $25.00 + $2.50 tax (10% US, on top) + $5.00 delivery + $0.50 tax = $33.00 paid. The return offered $25.00, refused $27.50 and refunded $25.00, so the merchant kept $2.50 of the customer's tax. ReturnLineItem#refund_amount returned only the line's money figure, Returns::Refund used it as default and ceiling, and TaxProvider::Base#refund was an empty method Internal never overrode — the tax plan's promise that Internal refunds derive from the recorded TaxLines was never built. Claims and exchanges left tax out the same way and never told the provider anything. VAT-inclusive stores refunded the VAT only by accident: the return line's pre_tax_amount held the gross price ($30.26 on a 23% VAT line worth $24.60). With the Avalara provider (#14467) it is worse: Avalara credits the authority the full tax ($8.88 on a $100 New York return in its own recording) while the customer is repaid none of it. A regression from 5.x, whose return item refunded pre_tax_amount + included_tax_total + additional_tax_total.
Decision: The tax provider decides the tax a post-sale credit gives back, and the money follows its answer.
TaxProvider::Basegainsestimate_refund(order, items, amounts:, tax_date:), writingcredit: trueTaxLines onReturnLineItem,ClaimLineItemandExchangeLineItem— three more concrete adjustable keys, plusoriginal_tax_line_idnaming the sale row each credit gives back.Basehas no default;Internalanswers with the recorded share (Spree::TaxProvider::RecordedShare, which any provider may reuse): each credited unit's part of every row the sale charged, rounded once, divided by largest remainder, never crediting a row past what earlier credits left of it. A provider may quote instead but answers in the same rows.estimate_replacementtaxes an exchange's replacement as a sale of its own (credit: falserows; no base default,Internalimplements it), andcommit_replacementfiles it.refundkeeps its signature and files what the rows hold.- Post-sale rows are owned by the order but
Order#tax_linesreadssalerows only (post_sale_tax_linesholds the rest):Carts::RecalculateTotalsre-sums that association on completed orders too, and claims and exchanges re-sum after settling. - A return line carries its tax like an order line:
pre_tax_amounttruly before tax (what was paid after discounts less the tax inside it, so the figures add up to the cent),included_tax_totalandadditional_tax_totalbeside it, all for the announced quantity and copied from the rows once, at opening. Before money moves the provider is asked again and rewrites the rows — not the columns, which keep their 2026-09-18 meaning — for the units that arrived and the money actually refunded; a short refund gives tax back in proportion.Spree::Refund#tax_amountrecords the tax a gateway refund carried. - A claim line's ceiling (
paid_amount) is what was paid after discounts plus the tax on top, and itsrefund_amountis entered tax included; resolving with a replacement alone gives no tax back. An exchange credits the old item at what was paid plus its tax and charges the replacement at the same discount — its base price × the old line'sdiscounted_amount ÷ amount— plus its own tax. A balance the customer owes goes on the order as anexchangefee for the merchant to collect, never charged automatically. - A provider failure refuses the step (open, refund, resolve, fulfill) with
tax_provider_unavailable, or the provider's own message for a refusal. Cancelling or denying deletes the record's rows directly and never asks the provider. Filing (refund,commit_replacement) runs after the money moves and is reported rather than raised. The error classes move into core unchanged from #14467. The provider is asked inside the transaction that opens the record, so none exists without its tax; a provider that quotes over the network holds that transaction for the call. - Reporting nets refunded goods from
net_sales,seller_payoutandreturns, and refunded tax fromtaxes, readingRefund#tax_amount;total_salesstays gross.SellerTransfers::Reversesplits a refund that knows its tax into goods (which carry their commission share) and tax (which goes back only when the seller collected it).
Rejected:
- Refunding the tax by reading TaxRate configuration, or a provider quote by default: rates are unversioned and a quote can differ from what was charged by a cent or more; the customer is owed what they paid. A provider may still choose to quote.
- Flat tax totals on the line with no rows: one line can carry several taxes, and a credit note needs the rate, reason and jurisdiction of each.
- A separate table for post-sale tax: it would copy the TaxLine shape and make every reader combine two tables. Marking direction by sign rather than a
creditflag: a zero-rated credit and a zero-rated charge would look the same. - Rewriting the line's columns at receipt, and with it a column recording which quantity they describe: it breaks the 2026-09-18 rule that receipt rewrites no amounts. Stored before-tax and tax-inclusive price columns for claim and exchange lines: they are derived from the line item and the tax columns, so storing them adds a figure that can go stale.
- Charging an exchange's replacement at its base price: a same-price swap on a discounted order would cost the customer the discount and its tax.
- Refunding delivery or its tax: out of scope for this change.
Consequences:
- No backfill. A return or claim opened before this recorded no tax against a taxed sale line — read from its columns, never from whether rows exist, since a settle whose money step failed may have deleted them: it refunds exactly what it was opened with, is skipped when settling, files nothing, and reads the old way in the seller clawback. On a VAT-inclusive store its refund still carries VAT that reporting nets from net sales, as before. Open exchanges move to the new pricing at once, read at the time like the claim ceiling (2026-09-29); those opened before this carry no tax on either half.
- The Admin, Store and Seller APIs keep
pre_tax_amounton a return line, but on a VAT-inclusive store it now reads the price before tax ($24.60 rather than $30.26). Return lines gain the tax totals andrefund_amount, returnsrefund_tax_total, claim and exchange lines their halves' tax, tax lines the new keys andcredit, Admin refundstax_amount, and the seller's order line itemsadditional_tax_totalso its claim dialog can pre-fill the tax. - The
exchangefee carries the replacement's tax inside its amount, so an exchange's balance owed appears under fees rather than taxes in reports. - Store-credit refunds still do not reach reporting at all — an existing gap left as it was.
- Avalara (#14467) owes six follow-ups when it rebases, recorded in
6.0-tax-provider.mdunder Phase 6: rebasing onto the error classes and new methods, dating the credit on the refund day rather than the original sale, building the credit from the rows rather than the stale list-price basis, implementingestimate_refund(reusing the recorded share or quoting), implementing the exchange methods, and keying documents to the return, claim or exchange.
Plans amended: 6.0-tax-provider.md (contract, Internal refund limit, "Post-sale tax", lifecycle integration points, Phase 6 follow-ups, Constraints on Current Work), 6.0-returns-exchanges-claims.md (key decisions, ReturnLineItem, ExchangeLineItem and ClaimLineItem notes, refunding, exchange workflow, Constraints on Current Work, resolved question 7).
2026-10-01: Merchants edit email templates one language at a time, in readable text
Context: Spree's email templates print their text through translation keys ({{ 'order_mailer.payment_link_email.message' | t: store_name: store.name }}), so one file serves every language. In the dashboard editor a merchant cannot read those keys, and cannot change the text behind them. Other platforms with an email editor show merchants plain text and treat each language as its own copy.
Decision: Spree's files keep their translation keys. When a merchant edits a template for a language, the editor writes the keys out as text in that language, in the subject and the body, with each value as the variable the template passed (Dear {{ order.customer_name }},); the edit is that language's version. A key that cannot be written out exactly (a plural form, a missing translation) is left as it was. The editor no longer offers "All languages"; the API keeps accepting any, and a version for every language published earlier still applies to languages without their own, which the editor says.
Consequences: Languages nobody edited keep Spree's translated default, so an English edit never reaches French customers in English. The same change in several languages is made in each. Supersedes the "one template for every language" part of the 2026-09-30 entry for the dashboard.
Plans amended: 6.0-email-template-editor.md.
2026-10-01: Building the email editor settled its API shape, branding and sample data
Context: Implementing 6.0-email-template-editor.md met details the design left loose: how the API names a template and its language, how the editor shows what an upgrade changed in a default, where branding is edited, what a new store previews, and whether the generated email types get Zod schemas.
Decision: The API names a template by its key with dots (spree.order_mailer.confirm_email) and picks the version with a language parameter, because locale already sets the response's language. Templates and drafts store the default they started from as base_subject and base_body, so the editor can show what changed; reading a template returns the default and the base, with no separate diff endpoint, and saving a draft with rebase keeps the merchant's version as based on the new default. The editable registry is Spree.editable_email_templates in core, filled by spree_emails. Branding is six store preferences edited through the store settings endpoint under the settings permission; only #RRGGBB colors and fonts from a fixed list reach an email, and the preview takes unsaved values. Emails built from a record have no in-memory sample: a store with no such record is told there is nothing to preview with yet, and publishing such an email checks its syntax only. The Email* types are generated into their own folder of @spree/admin-sdk without Zod schemas, since the order email's schema is too large for TypeScript to emit and nothing validates email data at runtime.
Consequences: Type generation for every SDK now runs from spree_emails, where both the API and email serializers load. A brand-new store cannot preview its order emails until it has an order. The earlier entry's Zod schemas for email types and the in-memory fallback for previews no longer apply.
Plans amended: 6.0-email-template-editor.md.
2026-10-01: The email editor's variables come from generated types, and reverted templates keep their history
Context: Building the email template editor (6.0-email-template-editor.md) left three details open: how autocomplete learns each email's variables, how two admins editing one draft avoid overwriting each other, and what reverting to the default does to a template's history.
Decision: Typelizer is added to spree_emails and generates Email* TypeScript types for the email serializers into @spree/admin-sdk, turned into Zod schemas by the existing pipeline. A hand-written manifest in the dashboard maps each editable email to its variables and their schemas, and the preview response returns the data it rendered with for example values; there is no variables API. Drafts carry Rails' lock_version and updated_by, so a stale save is refused naming who changed it. Reverting marks the published row reverted (has_status) instead of deleting it; the lookup reads only published rows and a later publish reuses the row, so history survives.
Consequences: Which variables each email receives is kept in step with its mailer by hand in the manifest; their fields cannot drift because they are generated. Extensions adding a customer email add a manifest entry through a dashboard plugin.
Plans amended: 6.0-email-template-editor.md.
2026-09-30: Merchants edit email templates in the dashboard, as drafts published per store
Context: Since the Liquid and MJML plan, every email renders from a template only a developer can change. The end goal was always merchant editing; this settles its shape.
Decision: Each store can edit its customer emails, and the shared layout and partials those emails use. Staff emails in core, store-owner notifications and seller emails stay as Spree's files and never read a store's edited layout or partials, so a template edit can never break a staff password reset. Edits are saved as drafts and go live when published; publishing renders the template with sample data under strict variables (every customer email, for the layout or a partial) and refuses anything that does not render. Published templates are store-scoped rows found before the files in the template lookup, one version for every language (locale = 'any', never NULL, so the unique index holds) with optional per-language versions. History is an append-only revisions table next to the live row. Preview renders on the server through the same renderer customers' emails use, with the store's latest matching record or one the merchant picks. Test emails go only to the signed-in admin. Branding (colors, fonts) lives in store preferences, independent of template code. Templates are their own permission resource, email_templates. The editor is CodeMirror 6 in @spree/dashboard-ui.
Consequences: A bad layout or partial edit reaches every email, which is why publishing validates them all. Renaming an email key or a partial argument now breaks stores that customized it; keys need a data migration and partial arguments may only be added. Changing a default template shows an "updated by Spree" notice to every store that customized it.
Plans amended: 6.0-liquid-mjml-emails.md (its deferred editing work now points to 6.0-email-template-editor.md).
2026-09-30: A return owed nothing completes at zero
Context: Once a returned free gift was valued at what the customer paid for it (entry below), its return could never be closed. Reproduced on R1009: a Tee with a free pink Polo, the Polo returned alone, approved and received with a refund total of $0.00. Returns::Refund refused any amount that was not positive ("There is nothing left to refund on this return."), and Returns::Cancel only accepts requested or approved returns, so the return sat at received for good. It kept counting in the dashboard's open-returns counter and the open filter, the customer's return page never showed it finished, and return.refunded never reached webhooks. Any return whose refund works out to zero was caught the same way, including one where nothing that arrived was worth anything. Money was never at stake.
Decision: Returns::Refund accepts zero when zero is owed. It skips the money steps and the tax credit and moves the return to refunded with no Spree::Refund row and no store credit, runs the hooks, and publishes return.refunded. The tax credit is skipped because the run moved nothing: a return whose money already went back but that was never marked refunded completes the same way, and crediting its tax again at zero would be wrong. Zero on a return the customer is still owed money on is refused with refund_amount_required, and a negative amount with refund_amount_negative. The status stays refunded; refunded_total of zero tells the two apart. ReturnEmailSubscriber sends no refund email when nothing was refunded. The shared refund dialog in @spree/dashboard-ui reads "Complete return", with a note that no money goes back and no amount or method to pick, and both returns cards label the menu action the same way.
Rejected: accepting zero on any return, which would let "refund nothing" close a return the customer is owed money on — a mistyped amount would close it unpaid, and a deliberate refusal to refund deserves its own action if it is ever wanted. Also rejected: a separate completed status, which touches the status list, the counters, the serializers and every filter to rename an outcome the existing status already describes.
Consequences: A received return always has a way to close. Integrations that treat return.refunded as "money went back" now see it for returns that refunded nothing; the event payload's refund_total reads 0.0 for them, so no second lookup is needed. The zero refusal on an owed return names what to do instead of claiming there is nothing to refund. Claims::Resolve still refuses a zero refund, which does not strand a claim, since it can be resolved with a replacement. A return still cannot be refunded in two steps: the first refund marks it refunded and a second is refused as not received. The comment on Return#refunded_total says a return can be refunded in more than one step, which the workflow does not allow; the two are left to be reconciled in their own change.
Plans amended: 6.0-returns-exchanges-claims.md (Refunding: internal vs gateway).
2026-09-29: A returned or claimed unit is worth what the customer paid for it after discounts
Context: A return refunded a discounted line at its list price (V-3721). Reproduced on main: two orders of 2 × Shirt ($25.00) and 1 × Mug ($5.00) with a 10% whole-order coupon, items $55.00, discount −$5.50, paid $54.50. Returning everything on R1001 offered $55.00; returning the two shirts on R1002 refunded $50.00 for goods the customer paid $45.00 for. On a marketplace order the seller would be charged back the same excess, since SellerTransfers::Reverse scales its clawback by the refund. ReturnLineItem#default_pre_tax_amount and ClaimLineItem#paid_amount both took line_item.amount / quantity, which is price × quantity and ignores every discount, under comments and a plan that said "after discounts". Every discount recorded on the line was affected: whole-order and per-item promotions, free gifts and manual discounts; free shipping was not, since it discounts the delivery. It is a regression from the 5.x chain, whose refund calculator read the line's discounted pre_tax_amount. The dashboard and seller panel claim dialogs pre-filled each line's refund with list price × quantity as well.
Decision: LineItem#discounted_amount_for(units) is the one answer to what some of a line's units cost the customer: discounted_amount (price × quantity plus the line's discount rows), spread over its units, multiplied before dividing so every unit together comes to the whole line, rounded to the currency and never negative. ReturnLineItem's default and ClaimLineItem#paid_amount both read it. The claim dialog in @spree/dashboard-ui pre-fills its refund from the line's discounted_amount, which the Admin API already served; the Seller API's OrderLineItemSerializer gains discounted_amount / display_discounted_amount so the seller panel can do the same.
Rejected: the stored LineItem#pre_tax_amount, which the 5.x calculator read. Only a tax estimate writes it and it defaults to zero, so an order never estimated, or a tax service that does not write it, would default to refunding nothing; and on tax-inclusive prices it takes the VAT out, so VAT stores would refund less than they do today. Also rejected for now: the line's full total, which adds tax charged on top of the price and the line's own fees. Refunding tax is its own defect (V-3725) and keeps its own decision; line fees stay out of this change.
Consequences: Returns still refund no tax charged on top of the price, exactly as before; on a VAT-inclusive store the built-in VAT is still refunded, now minus the discount. A return keeps the amount stored when it was opened, so returns already open on beta4 or earlier keep their list-price figure; they are deliberately not recalculated. A claim's ceiling is computed when it is read, so open claims move to the new figure at once, and a claim opened with a per-line amount above it is now refused at resolution with refund_exceeds_paid. Refunds already issued stay as they were. ExchangeLineItem#original_price still reads the list price and is not changed here.
Plans amended: 6.0-returns-exchanges-claims.md (ReturnLineItem and ClaimLineItem design notes, Constraints on Current Work).
2026-09-29: A batch coupon code is held from the moment it is saved, and discounts only its holder
Context: A single-use batch code applied before the cart reached the promotion's minimum was never used up (V-3724). Reproduced on main: a $10-off code with a $60 minimum, applied to a $50 cart, answered 201 with coupon_code_not_eligible; raising the cart to $100 discounted it and order R1001 was placed at $95.00, while the code still read unused with no order. A second guest then applied the same code and got the discount too (R1002), two guests who both saved a code below the minimum both placed discounted orders (R1003, R1004), and a guest who saved a code another cart already held was discounted alongside it (R1005, R1006). The cause is a gap between two decisions. The 2026-07-29 coupon wiring saves a real but not-yet-eligible code on the cart and lets recalculation activate it, and the V-3680 fix (7335a712f1) moved "hold the code on the cart" into the handler's claim, which runs only when the code applies straight away. Recalculation activated the saved code from its text alone (Adjusters::Promotion#coupon_promotions), so no code record was ever held, and completion spends only the codes the cart holds. Separately, a saved code that had not applied yet could not be removed: DELETE /carts/:id/discount_codes/:code answered 422 "doesn't exist", because removal looked only at promotions already attached to the cart.
Decision: Saving a code keeps its Shopify-parity retry, and the code record carries the rule. PromotionHandler::Coupon claims a batch code before anything prices it, including when the cart does not qualify yet, so the takeover rules from V-3680 apply unchanged: an open cart gives the code up to whoever presents it, and a cart in checkout or a draft order keeps it. Promotion#eligible? answers false for a batch-code promotion unless the cart or order holds one of its codes, so the adjuster never discounts a non-holder, whichever way the promotion arrived — attached, saved code or being activated — and the other eligibility callers (the free-shipping handler, the gift action's revert) follow the same rule. A cart or order holds only the codes it shows: every apply gives back any other batch code it holds whose promotion is not attached, so a replaced or mistyped code does not leave a hold behind that is later spent with the order, and Orders::Create, which drops a code that does not qualify yet, gives that code back too. A cart that loses its code keeps the text it entered, so the next Store API request that reads or changes the cart removes it and carries a coupon_code_unavailable warning. Writes sweep as well as reads, unlike the out-of-stock sweep, since API clients may rely on write responses alone; each endpoint sweeps before it renders, as the line sweep does. Checkout refuses, with the same code, a cart showing a batch code it does not hold (used, taken by another cart or order, or given back by one), rather than placing it at a higher total than the shopper last saw or naming on the order a code it never used. Removing a saved code that has not applied yet now succeeds and gives the hold back. Product calls settled with the maintainer: takeover also applies to a cart still below the minimum, the losing shopper is warned, and checkout is refused rather than placed at full price.
Rejected: refusing codes that do not qualify yet, which would reverse the 2026-07-29 decision for the storefront and for draft orders; and claiming the code inside the adjuster when it first writes a discount, which would take locks and release other carts from inside a recalculation.
Consequences: A shopper who saves a batch code below the minimum now blocks nobody. Anyone presenting it takes it over, as with any held code. A takeover recalculates the losing cart at once, so the checkout refusal is what that shopper sees only if they place the order with no other cart request in between. A code saved on a cart before this change is held by nobody, so that cart's next response drops it with the same warning even though the code is free; the shopper can enter it again. Orders already placed on the affected builds keep their discount, because placed orders never re-run promotions. Their codes still read unused, but spree_orders.coupon_code records which code each used, so they can be found. No backfill ships. Left alone, both pre-existing: every checkout refusal that carries a code (payment_failed, cart_changed, now coupon_code_unavailable) reaches the Store API as the error hash's text rather than its message; and a single-code promotion's usage_limit counts placed orders only, so open carts can pass it together (not tested).
Plans amended: 6.0-core-rewrite-tasks.md (the "Coupon code wired fully" bullet).
2026-09-29: Liquid and MJML emails move into 6.0, and ERB email overrides are dropped
Context: The Liquid and MJML email plan (2026-09-25 entry below) targeted 6.1. Shipping 6.0 with the ERB emails would mean every app customising an email ports it twice in two releases: once to 6.0's rebuilt ERB, once to Liquid. A bridge that kept ERB overrides rendering through 6.0 was built first, as a spree_legacy_emails gem, and then removed the same day.
Decision: The plan targets 6.0 and is renamed 6.0-liquid-mjml-emails.md. All 16 mailers convert in 6.0, core's back-office emails included. ERB overrides of Spree's own emails are dropped with no bridge: 6.0 is a major release, the ERB emails were only rebuilt in 5.6, and the bridge cost a gem, a CI lane, an ERB step in the template lookup and a 6.1 cleanup. Custom mailers that render their own ERB views keep working: core keeps a one-line ERB layout that wraps them in the Liquid layout, plus the mailer_hero and mailer_button partials. A template carries its subject as YAML front matter, which maps straight onto a subject column when templates move to the database.
Consequences: An app that overrode one of Spree's emails in ERB must port it to Liquid; until it does, the default design goes out, with no warning beyond the upgrade guide. The mailer view helpers (name_for, spree_storefront_resource_url and the fulfillment and digital asset helpers) are removed.
Plans amended: 6.0-liquid-mjml-emails.md (renamed from 6.1-liquid-mjml-emails.md; target, override and subject decisions).
2026-09-25: Emails render through Liquid and MJML, reading serializers, not views
Context: Transactional emails are the last HTML Spree renders through Rails views: 61 ERB templates across 16 mailers, which call model methods, helpers and even database queries from the view. The longer-term direction is to shrink Rails in the stack, and to let merchants edit email templates from the dashboard later. ERB can do neither safely: it runs arbitrary Ruby and exists only in Ruby.
Decision: Every email template becomes Liquid written in MJML. Liquid fills in the data, then MJML (the mrml gem, no Node) compiles it to email-safe HTML, on every email. Liquid was picked over Handlebars because it's the only template language with first-class engines in both Ruby and TypeScript, and it was built for untrusted templates. Templates read hashes from email serializers: spree_emails serializers inherit the v3 Store serializers for customer emails, and core serializers serve back-office emails. alba moves into spree_core for that, together with its setup. Output is HTML-escaped by default, tokens are built by mailers and never serialized, templates keep their Rails view paths (which become their keys), the text part is generated from the HTML, and copy keeps its Spree.t keys through a t filter. Rejected: React Email, Maizzle and other build-time tools (the file you write isn't the file that runs, so merchant editing needs Node); plain HTML tables (fragile markup maintained by hand); widening the public Store serializers for email-only fields.
Consequences: Renaming a mailer or one of its methods becomes a breaking change, because the view path is what apps override. Email views must stop calling models and helpers now, so the conversion stays mechanical. Merchant editing, database-stored templates and previews are a later plan built on the resolver chain this one ships.
Plans amended: none. 6.0-liquid-mjml-emails.md is the new plan.
2026-09-25: Replacement units are flagged, so an order edit counts only what was bought
Context: Raising the quantity of an exchanged line on a placed order deleted the line's original fulfillment and its delivery charge (V-3707). Reproduced on main: order R1001, one Stainless kettle at $79.99 plus $5.00 Standard delivery, exchanged for Matte Black; raising the line to 2 answered 200, deleted the $5.00 fulfillment with its Stainless unit, took delivery_total from 5.0 to 0.0, and released the Stainless allocation instead of adding one. There were two causes. Exchanges::Fulfill and Claims::Resolve built their replacement units through order.fulfillment_items.new; the stock coordinator packs a copy of each, and the order's next save persisted the original as well, so every replacement left a second unit on the line with no fulfillment. Spree::OrderInventory#verify then counted every unit on the line against its quantity, found three units for a quantity of two, and removed the one it could reach, the original. With the stray unit gone the edit still added nothing, because the replacement counted as a unit the line already held. The 6.0 returns rebuild had removed exchanged_unit? and original_return_item, so nothing told a replacement apart from a unit the customer bought.
Decision: spree_fulfillment_items gains replacement, a boolean defaulting to false, set on every unit an exchange or claim sends. OrderInventory#verify leaves flagged units out of the count and out of the units it removes when the quantity falls, so an edit only ever adds or removes goods the customer paid for. A line being destroyed still counts and drains its replacements as it did before, so the stock promise on a same-variant replacement is released rather than left with nothing to cancel. Both workflows build their replacements through one Spree::Fulfillments::Replacements module, which builds the units by id rather than through the association writers: with has_many_inversing, each writer adds the unit to its owner's collection, and that owner's next save persists it. Fulfillments::Create and FulfillmentChanger, the two paths that rebuild units when a fulfillment is split or moved, carry the flag across. The changer takes it from the first unit it moves, the same way it already takes the line.
Rejected: counting only units of the line's own variant. It needs no migration and fixes exchanges, where a replacement is always a different variant, but a claim often sends the same variant again, and that replacement would still count. Rejected: fixing only the stray unit, which stops the deletion but leaves the raise adding nothing.
Consequences: Raising the line from 1 to 2 now keeps the original fulfillment and its $5.00, adds one Stainless unit and one Stainless allocation, and brings the total to $164.98. No data repair ships: replacement units already fulfilled on a beta install stay unflagged, and their stray duplicates stay behind, so an edit of those lines still misbehaves. The order still reads paid after the edit raises its total; that is V-3638. Left alone, all pre-existing: OrderInventory#add_to_shipment rebuilds every fulfillment on the order when no open fulfillment can take the unit, which on a placed order is what Orders::BuildFulfillments refuses to do. #determine_target_fulfillment can put a raised unit into a pending replacement fulfillment, which carries no delivery charge. Removing a line drains only units of the line's own variant, so an exchange replacement's stock promise outlives the line. FulfillmentChanger merges the units it moves by variant alone, so a fulfillment mixing bought and replacement units of one variant can come out with the wrong flag, as it can already come out with the wrong line. Stock::Packer#default_package keeps one unit per variant, so two replacements of the same variant for different lines fail as out of stock. An exchange accepts units that never shipped, then restocks them on receipt while the original fulfillment still holds them.
Plans amended: 6.0-returns-exchanges-claims.md (the Exchange section's replacement-fulfillment note, the Phase 3 note on the removed exchanged-unit API).
2026-09-25: A free gift does not count toward what other promotions measure
Context: The 2026-09-23 fix left the gift at its list price on its line and paid for it with a discount. Everything that measures the cart for promotions sums list prices, so the gift counted in full: 2 x $49.99 of paid goods plus a $49.99 gift passed a "spend over $100, 10% off" promotion, which took $15.00 and left the shopper paying $84.98 where $99.98 was owed, and with three paid units the 10% came to $20.00 instead of $15.00 (V-3710). A gift promotion with its own spend threshold was worse: its gift kept the cart over the threshold after the shopper dropped below it, so the same one-kettle cart cost $49.00 after starting at two and $60.00 when built fresh.
Decision: Free gifts are taken out of what promotions measure; every other line still counts at its list price, so a product sale still counts toward a spend threshold as before. Spree::Purchase::Totals#gift_amount is the one measure: the ItemTotal rule compares item_total - gift_amount, and #amount, which order-level calculators read, is net of it. A gift counts as given only while its promotion gives it (CreateLineItems#gives_away?, the same eligibility and "qualifies beyond the gift" test its discount uses), so a copy the shopper pays for still counts toward other promotions. A promotion's own gifts are always taken out of its own threshold, paid copy included, since the gift cannot be what qualifies the promotion giving it away. Deciding whether another promotion gives its gift is judged one level deep, through a new own_gift_only: true rule option, so two gift promotions with spend thresholds cannot each wait on the other. Other promotions' gifts are looked for among the promotions a recalculation writes discounts for - those the purchase carries, plus the one its saved coupon code names (Spree::Promotion.held_by_saved_coupon_code, moved out of Adjusters::Promotion so both read it) - so a gift leaves the measure exactly when its discount can be written. Looking among the store's automatic promotions instead let an eligible but not yet applied gift promotion take a gift the shopper was still paying for out of another promotion's threshold. The cost of the narrower set: adding the gift recalculates the cart before its promotion is linked, so a spend promotion can qualify in that moment and stay linked at $0.00 once the gift is taken out. It is listed at $0.00 in the Store and Admin API discount lists, counts as "used" for the delete guard, and uses none of the promotion's limit, which counts discount rows; links never being removed is the older behaviour behind it and is left to its own issue.
Rejected: subtracting every line-level discount, which would also stop product sales counting at full price toward thresholds - a change for every store pairing a sale with a spend offer, not only stores giving gifts. Rejected: reading the gift's persisted discount rows, because rules are evaluated before the recalculation writes them, so the answer would lag a recalculation behind. Deferred to separate issues: delivery method item-total rules and the business order minimum still count the gift.
Consequences: A gift promotion with a spend threshold now takes its gift back when the paid goods fall below it, which makes the 2026-09-23 limit more visible: a shopper whose own copy was made free loses that copy when the offer lapses. With two gift promotions whose gifts each qualify the other, the one-level judgement can differ from the full one; neither loops. Measuring costs a lookup of the gift promotions whose gifts are in the cart on each rule check; a full cart recalculation went from 1,026 to 1,110 queries on a 23-line cart with three promotions, and from 119 to 121 on a one-line cart without gifts. Caching the measure per recalculation was left out: the baseline is the larger cost, and a cache would have to know every input a rule reads.
Plans amended: 6.0-6.1-split-adjustments.md (the Discount section's CreateLineItems note).
2026-09-24: Store credit is applied rather than chosen, and a gift card follows the total it pays
Context: A buyer with a gift card that did not cover the cart was offered Store Credit as the only payment method, and Place Order did nothing (V-3668). Reproduced on main against a fresh install, which seeds exactly one payment method, Store Credit: $44.99 cart, card with $10.01 left, amount due $34.98, payment_methods [Store Credit], and POST /carts/:id/payments answered 422 "Source can't be blank". The gift card was only what put Store Credit in the list: a buyer holding store credit and no gift card failed the same way, because that endpoint builds a payment with no source and a store credit payment needs one. The docs already describe store credit as a balance applied through POST /carts/:id/store_credits before choosing how to pay. Testing the combinations turned up four more defects. A gift card's payment never moved with the total: the resize existed as Order#recalculate_store_credit_payment, ran from before_transition to: :payment, and lost its only caller when the state machine went (6ff55b19f8), so a buyer paid $5.00 by card where $2.99 was owed while the gift card still held $2.01 — and switching to a cheaper delivery left the card paying the old, higher amount. Any change to a store credit payment's amount made the order impossible to place ("Could not find store credit"): PaymentMethod::StoreCredit#purchase takes a payment against the eligibility event recorded for its amount, and only creation recorded one. Applying credit, adding an address and applying credit again was enough. The same resize also counted the payment twice against its own credit, so a $30 credit ended up behind a $44.99 payment, the cart showed nothing due, and Place Order failed. StoreCredits::Apply spent a gift card's credit as if it were the buyer's own, so the card's balance paid for another cart while its own cart could neither be placed nor have the card removed. And mixing the two was refused in one direction only: store credit applied after a gift card inflated the card's payment, $10.01 of balance ending up behind $24.99 of payments.
Decision: Store credit is never one of a cart's payment_methods (Purchase::PaymentProcessing), and the Store API payments endpoint refuses store credit, which passes its active-and-storefront-visible lookup but could only ever fail there. The deprecated Order#collect_payment_methods delegates to it rather than keeping its own copy of the rule. The order.gift_card.present? clause in PaymentMethod::StoreCredit#available_for_order? stays, because Payment's own validation needs it for the gift card's payment. Resizing a store credit payment goes through one method, Payment#update_store_credit_amount!, which records a new eligibility event; StoreCredits::Apply and the gift card resize both use it. A resized payment grows only into its own credit's remaining balance, since a payment not yet taken reserves nothing, and any shortfall is drawn from the buyer's other credits, never the same one again. A gift card's payment follows the total in Carts::RecalculateTotals (orders inherit it), the seam every totals change passes through, including P3's in-lock recalculation. When the total reaches zero the card is released rather than resized, since a store credit cannot hold zero and a stale amount would charge the card for a free order. The resize draws only what the card can still give (GiftCard#spendable_amount): nothing more once it has expired, been redeemed or been cancelled, and never less than it already pays when an admin lowers the card's amount below what is in use. GiftCards::Apply sizes a new payment the same way. Item changes still unapply the card in Carts::Recalculate, as before. A gift card and store credit are never combined: StoreCredits::Apply refuses once a gift card is on the order, mirroring GiftCards::Apply, and draws only on the credits the buyer's balance counts — their own, in the order's store and currency.
Rejected: seeding Store Credit with storefront_visible: false, which every existing install would miss and an admin could switch back on. Also rejected: dropping the gift card clause from available_for_order?, which breaks gift card application outright — tested. Also rejected: resizing only at completion, which the old plan text described. The amount due shown during checkout would stay wrong, and a remainder payment sized from it would overpay once the card grew.
Consequences: Store Credit leaves the storefront's payment list. The storefront has no control that applies store credit, so its buyers cannot use store credit until it calls the endpoint; that is a storefront change, deliberately out of scope here. POST /payments now answers 422 payment_method_unavailable for store credit instead of "Source can't be blank". A cart that a gift card covers in full still completes without a payment, since the storefront already skips payment when nothing is due. Plain store credit is still not resized when the total changes, and the plans now say so instead of claiming it was. That leaves a pre-existing defect standing, reproduced here: a buyer who applies credit and then picks a cheaper delivery is charged the old amount — order R1028 took $44.99 of credit on a $39.99 total and reads overcharged. Shrinking the credit to fit the total would fix it; whether credit should also grow with the total is a product decision, so both are deferred. Gift card specs that faked totals on orders with no items now build real ones — they had asserted a $30 payment on an order whose recalculated total was $0, which held only because nothing resized it. Left alone, all pre-existing: one ordinary store credit can sit on two open carts at once, and the second fails at Place Order with no money lost — deferred. On an order authorised at checkout and charged later, amount_due subtracts captured store credit twice — skipped. The storefront shows nothing when Place Order fails. The Bogus test gateway never settles a payment session. A payment session for store credit answers 500. Applying a gift card to an empty cart reports "Amount must be greater than 0". The older refusal, a gift card after store credit, returns its untranslated key. StoreCredits::Apply takes the store credit payment method without scoping it to the order's store. The deprecated Order#available_payment_methods passes an argument that collect_payment_methods does not take, so it raises.
Plans amended: 6.0-cart-order-split.md (the offline payments bullet and the partial store credit edge case), 6.0-core-rewrite-tasks.md (the PAYMENT line), 6.0-6.1-loyalty-gift-cards-store-credits.md (three new Constraints on Current Work bullets).
2026-09-25: Editing a placed order's money re-derives its payment status
Context: Adding a charge to a paid order left it reading paid with money owed (V-3638). Reproduced on main: order R1001, total $205.00, paid $205.00; a $50.00 fee took the total to $255.00 and amount_due to $50.00 while payment_status stayed paid, and update_statuses! answered partially_paid at once. The stale status then stuck through every later edit: deleting the fee left a fully paid order reading partially_paid, and cutting a quantity until the customer had paid $100.00 over the total still read partially_paid rather than overcharged. The cause is a gap in the trigger list. UpdateStatuses runs from payment, refund, store credit, fulfillment and return events, and the post-placement edit services (fees, manual discounts, items) re-sum the totals and stop, because no event announces a total moving. Changing a fulfillment's delivery rate was the one edit that worked: Fulfillments::Update calls update_statuses! itself.
Decision: Each service that edits an order's money calls order.update_statuses! after it re-sums the totals: Orders::Fees::{Create,Update,Destroy}, Orders::Discounts::{Create,Update,Destroy}, Orders::Update, Orders::UpdateItem and Orders::AddItem. The fee and discount services make the call inside their own order lock. The other three rely on the lock their API controllers take, and AddItem makes it after its transaction has committed. The call is unconditional, as the event subscriber's is, so a draft order's statuses stay derived as well. Edits that save a payment or fulfillment row (gift cards, store credit, fulfillment create and move) are already covered, since those events fire after commit, once the new total is in place.
Rejected: deriving the statuses inside the totals workflow, which would cover every caller at once but give up that workflow's money-only contract; and publishing a new "totals changed" event for the subscriber, which adds a public event name to answer something the edit services already know.
Consequences: A new service that edits a placed order's money has to make the same call, because nothing else will. Orders::RemoveLineItem does not, and is left alone deliberately. It routes through Orders::UpsertItems, which never recalculates totals, so DELETE /api/v3/admin/orders/:id/items/:id currently removes the line and leaves the total where it was. Deriving a status from that stale total would change nothing, and the missing recalculation is a defect of its own. Exchanges::Fulfill and Claims::Resolve are not covered either: they recalculate totals as their last step, after their refund and fulfillment events have already derived the statuses. Whether that final recalculation moves the total, for example by charging delivery on a replacement, was not established here. amount_due never goes below zero, so an overpaid order shows an outstanding balance of $0.00 and only the overcharged status says a refund is owed.
Plans amended: 6.0-cart-order-split.md (the derive-then-persist triggers).
2026-09-24: A rebuilt delivery proposal keeps the customer's choice and its price, silently, with no completion guard and no cleanup
Context: Adding an item after the address was set dropped delivery to $0.00 and the order completed that way (V-3696). Reproduced on main: a cart read $20.00 + $5.00 Standard = $25.00 after the address; one more unit made it $40.00 + $0.00 = $40.00, and order R1001 was placed and paid at $40.00. Every cart recalculation rebuilds the delivery proposals through Cart#ensure_updated_fulfillments -> rebuild_fulfillments!, and nothing copied the selected rate's price onto the new rows, so their stored cost stayed 0 and RecalculateTotals summed that into delivery_total. Only the address-change path priced its rebuild; Checkout::Advance's rebuild for quick checkout had the same gap. Completion's drift guard could not see it, because its in-lock recalculation re-sums the same stored zero. Review then found two more faces of the same rebuild. It re-ran the estimator's default pick, so a shopper who had chosen free Store Pickup was switched back to Standard on the next item change - hidden while the cost came out $0.00, a $5.00 charge once it did - against the rule in 6.0-delivery-rate-provider.md that nothing may silently reset a chosen rate. And draft orders ride the same recalculation, where Order#ensure_updated_fulfillments deleted the fulfillments outright and rebuilt nothing: a $25.00 draft became $40.00 with no delivery at all when an admin added an item.
Decision: A rebuild carries the choice over and prices what it builds. Fulfillment#carry_over_selection selects the rate standing for the one chosen before - the same carrier service when still quoted, then the same method, then the estimator's pick, the rule refresh_rates already applied, now shared through one private method - and sets the proposal's cost from it before it is saved. Cart#rebuild_fulfillments! and Order#rebuild_fulfillments! both call it, so every caller is covered: the recalculation after any item change, quick checkout, the draft-order build. The earlier choices are grouped by stock location, and each new proposal takes the first one whose method it is quoted for, because one location can ship several proposals - a digital item beside a physical one, stock on hand beside a backorder - each with its own choice. A rebuild for a changed destination keeps nothing (keep_selection: false, decided by Carts::Update and Orders::Update and passed down through Cart#recalculate_for_address_change! and Orders::BuildFulfillments): a choice made for one address is not a choice for another, and before an address is known only pickup is offered, so keeping that default once shipping is available would pin every cart to pickup. A destination change is a different address row, a pickup counter picked or cleared, or an edit to the fields a quote reads (Spree::Address::DESTINATION_FIELDS: street, city, state, postal code, country). The address id alone cannot say, because a guest's edit updates the row in place; and a corrected phone number or recipient name, or a market change, keeps the choice and quotes it again. Orders::Update now rebuilds on an in-place edit to those fields, where before it did not rebuild at all. Order#ensure_updated_fulfillments rebuilds instead of deleting. When the new contents re-quote the kept rate at a different price, the cart takes the new price without telling the shopper: it is the current quote for what they are buying, and the total already shows it.
Rejected: a warning when delivery changes on rebuild - the new figure is correct, not a surprise to flag. Deferred: a completion guard refusing an order whose stored delivery cost disagrees with its selected rate. It would catch this whole class of defect, but fixing the one path that produces the disagreement is enough for now. Rejected: a cleanup task or upgrade note for orders already placed with $0.00 delivery - they exist only on 6.0 beta installs. Rejected: setting the cost in Stock::Package#to_fulfillment, which would reach every builder at once - including OrderInventory's rebuild of a placed order, whose delivery was charged at placement and is re-priced only through the post-placement edit path. For the same reason Order#rebuild_fulfillments! does not carry a choice over or set a cost on a placed order; it still deletes and replaces that order's fulfillments, as it did before.
Consequences: Adding, changing or removing items keeps the delivery the customer or admin chose, at its price for the new contents, on carts and draft orders alike; a new address still starts from the default. Beta orders already placed at $0.00 delivery stay as they are. Two proposals from one location offering the same methods (stock on hand beside a backorder) that had different choices are matched in order, so the pairing can swap; nothing identifies a proposal across a rebuild. Left alone, all pre-existing: Order#ensure_updated_fulfillments publishes order.updated before the recalculation has summed the new delivery costs, so the event carries the previous figures; a rebuild still drops the parcel locker frozen into pickup_point_data, so a kept pickup-point method needs its point chosen again; recalculate_for_address_change! quotes delivery before item_total is refreshed, so a rate that reads the order value quotes on the old figure; and the currency-change callback rebuilds before the line items are converted. Nothing yet stops a future path from storing a cost that disagrees with the selected rate; that is the deferred guard.
Plans amended: 6.0-delivery-rate-provider.md (Selected-rate preservation).
2026-09-23: The free-gift action prices its own gift, and covers the copy the shopper already has
Context: The Create line items action added its variant at full price and wrote no discount, so the promotion raised the bill: a cart of 2 x $89.99 became $269.97 when an automatic gift promotion applied, with no line saying why, and the shopper could not delete the gift because every recalculation put it back (V-3666). The action was the only one describing itself in the docs without saying how the money worked - "Free items", "free items in the cart", "Free gift with purchase" - while discount_scope answered nil, which is what excluded it from Spree::Adjusters::Promotion. The documented workaround, pairing it with an order discount set to the gift's price, was tested and fails three ways: the order-level amount prorates across every line, so the gift reads as an $8.57 purchase and the $20 item beside it as $11.43; the discount still pays out when the gift is out of stock, because Promotion#activate maps over actions independently ($20 cart, $15 off, no gift); and the compensation competes for the order group under 6.0 winner-only, so a larger promotion deletes it and the bill goes back up ($2.00 to $17.00 on entering a free-gift coupon).
Decision: The action prices what it adds. CreateLineItems#discount_scope is :line_item and #compute_amount returns -price * gifted_quantity, where gifted quantity is the configured quantity capped at what the line holds - so a shopper buying three of a variant gifted once still pays for two. The gift's discount is not narrowed by the promotion's rules: PromotionAction#applies_to_line_item? is a new seam defaulting to promotion.line_item_actionable?, which CreateLineItems overrides with "is this one of my gift variants". Without it the rules decide the gift line, and the ordinary shape of the offer - buy a coffee maker, get a tote - has a gift the rules never name. A shopper who already holds the gift variant gets theirs free rather than a duplicate, which also settles the reported half where perform returned false, activate therefore returned false, and the promotion refused to attach at all while eligible? was true.
Rejected: a configurable gift price, which is what the issue's "or to the configured amount" asks for. It needs a column on spree_promotion_action_line_items and an editor field, and free is what every surface already promises. Rejected: leaving the price alone and rewriting the descriptions to say the action charges, the issue's other option - it would have to retract "free items in the cart" from the overview sentence defining what promotions do. Rejected: keeping the gift discount out of the winner-only competition entirely; it wins on its own line anyway, being the whole of it, and a bigger line-level promotion displacing it only ever makes the shopper pay less.
Consequences: revert now runs only when the promotion is actually joined to the order. It was deleting the gift variant from the cart of any shopper who had bought one themselves and did not qualify, on every recalculation, because the handler deactivates every promotion in scope whether or not it ever applied. What it still cannot do is tell a unit it gave from a unit the shopper bought, so a shopper whose own copy was made free loses that copy when the offer lapses; closing that needs the gifted quantity recorded per line, which no table holds. Installs that followed the old documented recipe now discount twice - the gift is free and the compensating order discount still fires, $20 of goods for $5 in the tested case - so the upgrade note is to delete the compensating action; the docs that taught it are corrected here. The gift still reappears when a shopper deletes it under an automatic promotion, now at zero, so it is no longer a charge but still an item they did not ask for. types_for_discount_scope(:line_item) gains the action, which had been listing CreateItemAdjustments twice.
Plans amended: 6.0-6.1-split-adjustments.md (the Discount section's per-action notes).
2026-09-22: Store credit names the order it puts right, so payment status counts both ledgers
Context: An order refunded to store credit went on reading paid. Reproduced on main: order R1016, total $99.99, one $89.99 line returned and refunded as credit — the return reported refunded_total $89.99 and refundable_total $0.00 while the order reported payment_status: paid and nothing given back. A claim behaves the same, and lands there by default, since the claim resolve dialog and ClaimActions#resolve both default to store_credit where the return side defaults to original_payment (V-3660). The cause was a decision applied in one place and not the other: the 2026-08-11 ruling that store credit is its own ledger and never writes a Spree::Refund row taught Return#refunded_total to sum both, but Orders::UpdateStatuses#money_for still counted refund rows alone. V-3561 was closed on the strength of the original-payment half working.
Decision: A store credit issued as a refund names the order it settles, in a nullable spree_store_credits.refunded_order_id — the same argument as spree_refunds.order_id (2026-08-20), which exists because a refund reached its order through its payment and a split checkout has no such payment to ask. Named refunded_order rather than order because this table already answers orders with the orders a credit went on to pay for, and a credit that settles one order and is spent on another is ordinary. Orders::UpdateStatuses adds that sum to the refunded figure in both branches, ordinary and grouped, so refunded in the derivation means what the customer got back rather than what left a gateway. The three issue_store_credit copies in Returns::Refund, Claims::Resolve and Exchanges::Fulfill become one issue_refund_store_credit in Refunds::OrderPayments, beside the gateway half — three copies drifting apart is what let one rule be applied to the ledger and not to the order. OrderStatusSubscriber gains the store_credit.* events, which are the only announcement a credit-settled claim makes — including deleted, so it resolves paranoid records with deleted ones included rather than losing the row that just went.
Rejected: walking order.returns/claims/exchanges to their credits, which needs three indexed queries on a path that runs on every payment, fulfillment and refund event, and counts no originator an extension adds. Also rejected: netting credit out of payment_total. That column is what came in through payments, the money is still with the store, and moving it would take paid? and outstanding_balance with it.
Consequences: payment_status moves on orders that were reading paid, which is the point. No backfill ships with it, in the migration or as an upgrade step. There is nothing to backfill: Spree 5 never set originator on a reimbursement's credit — that chain linked through spree_reimbursement_credits, and migrate_returns re-points refunds only — so no credit on an upgraded install carries a return, claim or exchange originator. The only rows a backfill could reach are a 6.0 beta tester's, and one console line fixes those. The refunded and partially_refunded Ransack scopes now read the derived column instead of re-summing refund rows through a join, which is what stored statuses are for; they had no callers and would otherwise have contradicted the column beside them. A credit for part of an order reads partially_refunded; one covering everything captured reads refunded. payment_total deliberately does not move, so a fully credit-refunded order shows payment_status: refunded beside a payment_total equal to its total — two columns answering two questions, and the second is the honest one for money that never left. The two roles a store credit plays stay in separate tables — credit as payment is spree_payments.source, credit as refund is this column — so nothing counts one as the other. Left alone, all pre-existing and none of them made worse here: Order#order_refunded? and #partially_refunded? count refund rows only and have the same blind spot, but nothing reads them; a claim's gateway refund is still stamped with the "Return processing" reason rather than the claim's own; SellerTransferReversalSubscriber hangs off refund.created, so a marketplace seller is never clawed back for a refund paid as credit, against its own comment that "every one of those funnels its money movement through a refund"; and Payment#credit_allowed counts refund rows alone, so credit does not reduce gateway headroom and the same money can be handed back twice through two post-sale records. The last two are money defects worth their own issues.
Plans amended: 6.0-returns-exchanges-claims.md (the Return#refunded_total replacement bullet), 6.0-cart-order-split.md (the derive-then-persist rules).
2026-09-22: The form that writes base prices filters for them itself; the variant prices expand stays whole
Context: Saving a product in the dashboard destroyed prices nobody had touched. On a store with a second market and a sale list, Save rewrote the USD shop price from $549.99 to the list's $329.99 and soft-deleted the EUR price outright; with a volume ladder on the same list the shop price became the 50-unit rate of $249.99, a 55% cut charged to every single-unit customer (V-3661). expand=variants.prices serves every row a variant has — base rows, price-list rows and every quantity break — and variantToFormValues took the lot, dropping price_list_id as it went. The card then showed the first row of the picked currency, whichever kind the database happened to return first, so which currency was destroyed and which was overwritten varied between saves. The form posts that array back under the same key, where Spree::Variant#prices= reads every entry as a base price; a null-amount placeholder, which is how a price list records membership (2026-09-08), arrived as a blank amount and took set_price's delete branch.
Decision: The form filters. variantToFormValues keeps only rows with a null price_list_id, so what the product form holds is what it is entitled to write. It lives in @spree/dashboard-core, which both the operator dashboard and the seller panel build their product form from, so one filter covers both panels.
Rejected: scoping the serializers' many :prices to base rows, which was built and reverted on review. expand=variants.prices means "this variant's prices" to every client, not "the subset one form may write", and narrowing a published read to protect one writer takes the price-list amounts and quantity breaks away from everyone else reading them in a single call. The rule it breaks is the general one: a read contract is not the place to encode a writer's constraint. Also rejected: hardening Spree::Variant#prices= against duplicate currencies, which treats the symptom. Whether a payload naming one currency twice should be a 422, and whether a blank amount should keep meaning "delete this price", are both still open.
Consequences: No API change, no serializer change, no generated types move — the fix is four lines of TypeScript and a price_list_id on the panel's price type. The Prices card now shows the shop price rather than whichever row sorted first. Any other client that reads variants.prices and posts it back still meets the same trap, and the setter is what would have to refuse it; that is the open question above rather than something the read should have absorbed.
This is the 2026-09-07 sweep ("a column that changes row identity is not finished at the writers") reaching a reader it missed — but the reader is in the dashboard, not the API. The rule to carry forward: when a form hydrates from a collection it will post back, it owes that collection a filter, because the setter on the other side cannot tell which rows the form was entitled to touch.
Plans amended: 6.0-volume-pricing.md (Notes from the build — the reader list).
2026-09-18: A return is owed what the warehouse counted, and the line works that out
Context: A return requested for three units and received as two offered the merchant a refund of all three. The dashboard pre-fills the refund dialog from refundable_total and always submits what is in the box, so the workflow's own correct default (amount || received_total) was never reached, and the only ceiling was the same announced-quantity figure — nothing refused it. On a $269.97 order line the customer was paid $89.99 too much and the seller clawed back $242.97 where $161.98 was owed, because SellerTransfers::Reverse scales the seller's share by the refund amount. Reproduced from a clean install, then twice more here: identical orders refunded with and without an amount came out $269.97 and $179.98 (V-3654). The same received-based arithmetic existed in three places — Returns::Refund#received_total, Return#refunded_line_amounts and nowhere else that anyone reading refund_total would find — which is how the offered figure and the owed figure came to disagree.
Decision: Spree::ReturnLineItem#refund_amount is the single answer to what a line refunds, and Return#refund_total / #refunded_line_amounts are plain sums over it — the shape Claim#refund_total already had over ClaimLineItem#refund_amount. Before the warehouse has counted, the line is worth the announced quantity, since nothing better exists to quote; once it has, only the units that arrived are paid for. "Counted" is Return#counted? — received? || refunded?, so the figure does not revert when the return moves on — read from the status and not from received_at, which migrate_returns.rake never writes: keying off the timestamp would have left every store upgraded from the 5.x return chain with the original bug intact. The derived share is rounded to the currency through Spree::Money::Rounding.to_currency, because this figure is now an enforced ceiling as well as a display: a third of $29.99 taken three times is $29.9900000000000000000000000000001 in BigDecimal, which would refuse a full refund of a fully received return, and a third of $10.00 taken three times is $9.9999999999999999999999999999999, which the dashboard would prefill into the amount box verbatim. pre_tax_amount keeps its meaning untouched as what the announced units are worth — it is stored history, and receiving must not rewrite it. Returns::Refund drops its private received_total and takes refundable_total as both its default and its ceiling, so the amount a caller may name is the amount a caller who names none would get.
Rejected: correcting only the dialog's pre-fill, which leaves the Admin API, the seller panel and every integration able to over-refund; and having Returns::Receive overwrite pre_tax_amount at receipt, which fixes every reader for free but destroys the record of what the customer announced.
Consequences: No API shape changes and no dashboard change at all — both panels already read refundable_total, and it is now right. The values move: after a partial receipt refund_total, display_refund_total and refundable_total all drop to what arrived, on the Admin, Seller and Store serializers alike, so the returns card and the customer's own return page stop quoting a figure nobody will be paid. An over-large amount is now a 422 refund_exceeds_balance where it used to succeed, which is a behaviour change for any integration that was passing the announced total deliberately. The seller clawback needed no change: it scales off the refund, so a correct refund makes it correct. The phantom outstanding balance on a refunded order (V-3562) is untouched and still open.
Plans amended: 6.0-returns-exchanges-claims.md (Return and ReturnLineItem snippets, the Returns::Refund workflow row).
2026-09-17: Seller attribution belongs to the one finalize home, so an admin-raised order divides like a checkout
Context: An order raised from the admin charged a seller commission and credited that seller nothing. Reproduced from a clean install: a $549.99 order for a seller's product completed paid, wrote a commission line of $82.50 against the seller by name, and left orders.seller_id NULL — so SellerTransfers::Create halted on the blank column and the seller's own order list never showed the sale. A mixed basket commissioned both sellers and divided into nothing. The cause is that the stamp and the split were steps in Carts::Complete, while commission is charged off order.placed, published by Orders::Complete — the home 6.0-cart-order-split.md designates for everything that happens when an order becomes placed, "serving both checkout and admin/B2B drafts". Two halves of one money path read two different columns, for exactly the orders that skip the cart. The 2026-08-21 entry on single-seller checkouts is the same oversight one level down: it fixed the case, not the cause (V-3643).
Decision: Attribution moves into Spree::Orders::Complete, which owns it alone. It partitions by seller after payment and before placement, then either stamps one seller onto the order or divides it into a group, apportions the payment and places the siblings the division produced. Carts::Complete no longer divides anything: its FINALIZE phase makes one call and reads the group back off the result, losing two steps and its per-child loop. An intermediate shape put the logic in a service both workflows called; it was removed as shallow indirection, and two homes for one decision was the shape that caused this bug. Carts::SplitBySeller takes cart: as optional — build_group was its only cart-coupled method and the order carries every fact it read. The admin completion endpoint answers with the group when one was made, following the Store API, and the dashboard redirects to the orders list filtered to that group.
Rejected: refusing to complete a multi-seller admin order. A customer asking a merchant to place an order spanning sellers is ordinary trade, and refusing would have left merchants hand-raising one order per seller with separate payments and reference numbers. The risk that argued for refusing — the six silent defects in post-placement money paths recorded on 2026-08-21 — does not apply, because those paths key on order_group_id and not on how the group was made, so an admin-raised group inherits every one of their fixes.
Consequences: PATCH /api/v3/admin/orders/:id/complete may now answer with an order group instead of an order; @spree/admin-sdk types it Order | OrderGroup and exports isOrderGroup to narrow it, since the payload carries no type discriminator of its own. An admin order spanning sellers now produces child orders numbered off the group (R1007-1), which is a visible change to what an operator gets back. Two adjacent defects were found and deliberately left: Orders::AddItem never calls Orders::BuildFulfillments, so create-then-add-items leaves an order with no fulfillments that can never be fulfilled (and therefore never credits its seller, which fires on order.fulfilled); and Admin::Orders::PaymentsController scopes to the order's own payments, so its index is empty for a grouped child and show/capture/void answer 404 — Admin::Orders::RefundsController reads settlement_payments and shows the shape a fix would take. Both are pre-existing and reach split checkouts too. The sibling fault, a grouped child reporting payment_total: 0 beside a correct payment_status: paid, was fixed separately in #14673.
Plans amended: 6.0-multi-vendor-marketplace.md (Constraints on Current Work, Resolved Decisions), 6.0-cart-order-split.md (the Gates line).
2026-09-16: A split checkout confirms once from its OrderGroup, and counts deliveries from parcels
Context: A checkout spanning several sellers splits into one order per seller and deliberately sent a single confirmation email — but it sent the first child order's own email, carrying that order's number, items, delivery and total. On a mixed basket the first-party child sorts first, so a $374.97 purchase of three items confirmed $50.67 and one item, with nothing to say the rest existed (V-3642). The workflow already published order_group.completed and nothing had ever subscribed to it.
Decision: The confirmation moves onto that event. Every child of a split places with notify_customer: false, Spree::OrderGroupEmailSubscriber answers the group, and Spree::OrderGroupMailer renders the whole purchase under the number the customer saw at checkout. The email is organised by parcel, and a parcel is a set of fulfillments sharing [stock_location_id, delivery_method_id] — collapsed by Spree::FulfillmentGroup, because when one warehouse serves several sellers the packer builds one package and the split divides its single quote across the children, so three orders can ship in one box. The store-owner notification moves to the group with it, and an admin resend on a grouped child sends the group's email. Two delivered flags on spree_order_groups mirror the order's, since replay re-publishes the event.
Consequences: "How many orders" and "how many deliveries" are now understood to be different questions, and any surface telling a customer what to expect must answer the second from fulfillments. Delivery method alone cannot key it — available_to_sellers lets two warehouses be quoted on one shared marketplace method — and a location alone cannot either, so the pair is the rule. A single-partition checkout is untouched and keeps Spree::OrderMailer. Grouped cancellation is left as it is: it is opt-in per child, so it is not misfiring on its own. The storefront's own confirmation page reads order.items, which the group serializer does not expose, so it needs the same treatment separately.
2026-09-16: Two catalogs on one company charge the best of them, and every order line says which agreement priced it
Context: Nothing stopped an operator assigning a second catalog to a company — the audience picker offered the company again with no warning — and once both were active the buyer was charged from whichever catalog sorted first, not the cheaper one. Reported against a company holding a 5%-off catalog and a contract catalog with a quantity break: at 24 units the buyer paid $2,280.00 where the company's other agreement said $1,200.00, and reversing the two catalogs' order reversed the outcome (V-3635). The tie-break was the documented design — Catalog#position, which is the order of the store-wide catalogs screen — so a merchant dragging that list to tidy it changed what companies paid, with no screen anywhere listing a company's catalogs to show it had happened.
Decision: Precedence between nodes is real and unchanged: a division's own agreement still answers over its parent's, cheaper or not, because someone negotiated it. Precedence within a node is not real, so it is gone — catalogs assigned to the same company node rank equally and the buyer pays the best price any of them gives. Equal amounts keep list order, so the answer stays stable. Spree::Catalog.groups_for_company / groups_for_context / groups_for_buyer return the catalogs grouped by assigning node and the flat for_* readers are derived from them, so visibility and quantity terms keep the union they always had while pricing alone sees the rank boundaries. Spree::Current memoizes the grouped form and derives the flat set from it, so the two cannot disagree about one buyer. Position keeps ordering the catalogs screen and nothing else.
Rejected: refusing the second assignment, which would delete a shipped feature (two catalogs on one company is how an operator unions two assortments) and invalidate stores already doing it; and warning the operator while leaving the money alone, which does not stop the overcharge. Best-price is also the rule a merchant can state in one sentence to the buyer they overcharged.
Consequences: The admin line-item serializer gains price_list_id, price_list_name, catalog_id and catalog_name, and the dashboard's order item rows link to the agreement that priced them. This is read off the price list the line was stamped with at pricing time, never re-resolved — so it reports what the buyer was actually charged from rather than what would apply today, and it keeps the order read path provider-free (2026-08-30, which is why catalog_price on the same serializer is a base price). Provenance stays admin-only, off the store serializers, like price_source. The orders controller preloads line_items: { price_list: :catalog } so a page of orders does not pay two queries per line.
Deliberately not done: an effective-price view on the company or customer page — what a named buyer would pay for a product before any order exists. Raised on the issue after the fix was scoped, with figures: one variant offered at $111.11 by a company catalog, $329.99 by a standalone list and $549.99 as the shop price, with no screen anywhere reconciling the three (the customer page shows groups only, the company page no pricing at all). It is a real gap and a larger one than the original report's "show which catalog applies". The link added above answers only after the fact. A preview needs a new admin endpoint taking company-or-customer plus variant and quantity — the quantity matters, since a break can reverse which agreement wins — and cards on two dashboard pages. Spree::Pricing::Context already takes exactly those inputs and the storefront resolves through it per variant, so this is a new surface over an existing resolver, not a second one; the provider-free rule it must respect is about order and listing serializers, not a deliberate preview call. Held out so an urgent money fix is not gated on a feature.
The same walk confirmed the tier order — company catalog, then standalone lists by their own rules, then shop price — is consistent and worth preserving. It is: best-price applies only within one node, never across tiers, and a test over that scenario charges $111.11 at every quantity.
The same first-wins shape remains in Catalogs::ResolveQuantityRules, where the fields are minimums and multiples rather than money and "best" has no obvious meaning; V-3592 is the same class of problem on commission rates and is untouched here.
Plans amended: 6.0-b2b-companies-and-catalogs.md (Key Decisions, the Catalog#position note, and Pricing).
2026-09-12: Reporting scopes money to one currency and never converts; counts are not scoped at all
Context: Every sales and payments base filtered currency unconditionally, so a multi-currency store could not ask how many orders it took — only how many were priced in one currency. That is a wrong answer rather than a partial one. The wider question of cross-currency totals came up at the same time, so both were settled together after looking at how other platforms handle it.
Decision: Money stays per-currency and is never converted. Query#scope_currency returns the currency only when some aggregated component of the requested metrics is money-formatted, and the bases skip the filter when it is nil — so counts, quantities and money-free ratios span every currency, while any query containing money narrows as before. A ratio counts as money when either side is (average order value), and not when neither is (sell-through). The dashboard home screen carries a currency switcher, shown only where the store sells in more than one.
Consequences: No base-currency column on orders and no conversion anywhere in reporting. The market splits on this: Magento and Shopify store a second, converted amount per order and report on it, while Saleor's Pulse analytics, Medusa and Vendure keep money scoped per currency. The converted approach buys one aggregate number and pays for it in reconciliation — Shopify converts at each money movement rather than freezing the sale's rate, so a full refund need not net to zero in shop currency and their own documentation calls the reporting conversion "approximate and may differ slightly from actual captured amounts"; Magento's own Advanced Reporting only supports installations that kept a single base currency throughout. For a platform whose figures merchants may file, exactness beats a single headline number. If a cross-currency total is ever wanted it must be a separate, clearly labelled figure carrying its rate and date — never the same metric as the exact one. A base that registers its own relation must guard the currency filter against nil.
2026-09-11: Home-screen counters send a key and a number, never copy
Context: The counters endpoint shipped with label and description resolved server-side through Spree.t, mirroring how the reporting schema labels metrics and dimensions. That reproduces exactly the defect the 2026-09-05 ruling was written to fix: Spree.t answers in the request locale, which the dashboard never sets, so a merchant reading the interface in one language could get a counter labelled in another. The low stock description also interpolated a store preference, putting a merchant setting into a translated sentence built on the server.
Decision: The endpoint returns { key, value, link, nav } only. The dashboard translates the key from its own locale files under admin.pages.home.operations.counters.<key>, and interpolates the low stock threshold from the store record the shell already holds — so the threshold stays a number on the wire and the sentence stays a translation. A counter the dashboard has no entry for renders its humanized key, which reads sensibly for an extension's own counter before anyone translates it. The description: registration option is removed; Registry::Counter keeps count, subject, key_scope, link and nav.
Consequences: Stricter than the 2026-09-05 decision, which deliberately keeps label/description on type catalogs as documented fallback for integrations and untranslated extension types. That fallback earns its place there because a type catalog is also read by non-dashboard clients; a counter is rendered by the dashboard alone, so the fallback bought nothing and guaranteed the mixed-language bug. Type catalogs are unchanged. An extension registering a counter now ships dashboard translations or accepts the humanized key.
2026-09-11: The legacy Spree::Report system is removed, its tables left alone
Context: 6.0-analytics-semantic-layer.md Decision 10 kept Spree::Report alongside the new reporting layer, on the grounds that it is a row-level CSV exporter and so answers a different question. Reviewing it once the layer shipped, that separation does not survive contact: Spree::Report has no v3 route and no dashboard screen, so a merchant cannot run one at all; both subclasses core ships are aggregate questions the new layer now answers as seeded reports; and row-level CSV is already Spree::Export's job, with the Admin API and dashboard page Spree::Report never had.
Decision: Remove the subsystem — the STI base and its two subclasses, ReportLineItem and its two subclasses, the generate job, the mailer and its view, the subscriber, the v3 serializer and its dependency key, the Spree.reports registry, the reports queue entry, the mailer preview, the factory, and the Store and admin-user associations. Leave the tables. The creating migration is deleted so a fresh install never makes them, while existing stores keep every row, inert. No drop migration is scheduled — there is no data-loss moment to time, and a merchant who wants the history can still read it.
Consequences: Aggregate questions are registry members (Spree.reporting); row-level CSV is a Spree::Export subclass. Nothing may reference Spree::Report, Spree::ReportLineItem or Spree.reports again. A host app that subclassed Spree::Report breaks on upgrade and has to move to one of the two replacements — accepted, since the class was unreachable from any shipped surface. Supersedes Decision 10 in 6.0-analytics-semantic-layer.md.
2026-09-11: Counters are reporting registry members, and one request serves the home card and the sidebar
Context: dashboard/operations served five counts as private methods on a serializer in the API gem, the dashboard hardcoded the matching rows (icons, labels, deep-link filters), one permission covered all five, and the out-of-stock deep link pointed at a products filter the server silently dropped. The low stock threshold was a request parameter with a hardcoded default that nothing sent.
Decision: Counters are a fourth member type on Spree.reporting (registry.counter), evaluated by Spree::Reporting::Counters rather than compiled into the query — a counter has no range, currency or base. Each declares subject + key_scope like every other member and is filtered by the shared Admin::ReportingAuthorization#member_allowed?; the endpoint returns { key, label, description, value, link } per counter and the dashboard renders whatever arrives. The link is declared beside the count so the list opened shows exactly the rows counted; a counter with no honest list (the stock ones, until the Inventory page) carries none. low_stock_threshold is a Spree::Store preference (default 5, 0 = off) surfaced in store settings. Spree.operations stays reserved; the registry name Spree.reporting is unchanged.
Amended 2026-09-11: the endpoint is dashboard/counters, not dashboard/operations — the payload was already named after what it holds, and the developer preview needs no bridge. The three post-sale sidebar badges fold into it: each used to issue its own list request with limit: 1 to read a total off the pagination meta, so the shell spent three round trips counting three things, and the returns badge counted received while open_returns did not. Counters now carry the nav entry they badge, open_exchanges and open_claims join the vocabulary, open_returns adopts the badge's wider definition, and the sidebar and home card share one query. The shell issues that query rather than any badge — the sidebar mounts only the children of the section being viewed, so the old badge-driven fetch produced no counts anywhere outside Orders — and a parent nav entry sums its own counter with its children's so the total is visible while the submenu is collapsed. orders_to_fulfill badges Orders as an inbox-unread count; payments_to_collect deliberately carries no nav, since a badge lit on nearly every store stops informing. The stock counters adopted the Inventory page's own reading of the shelves — what a customer could still buy (count_on_hand − allocated − reserved), counted per location — replacing a raw count_on_hand count of distinct variants that both undercounted, by ignoring allocation, and would have landed on a different number than the list it links to; Spree::StockLevel.low_stock is the shared scope behind the page's filter and the counter, so the two cannot drift.
Consequences: An extension registers a counter with a locale label and it appears on every merchant's home screen — and, with nav, in the sidebar — with the right permission gating and no dashboard change. A limited role sees a shorter list, not a refused card. New point-in-time numbers for the home screen are registrations — never serializer methods or client-side derivations. See 6.0-analytics-semantic-layer.md Decision 15.
2026-09-10: Close-short writes the incoming counter, the Inventory page opens on every location, and the recount is an upgrade step
Context: Implementing Phase 7 of 6.0-inventory-operations.md turned up three things the plan left open. The incoming writer table listed Update (which refuses anything past draft, so it never changes an incoming figure) and omitted the Close workflows, whose whole job is to take a document out of the open set the recount reads. The page had no stated default before a location is picked. And the backfill was described as "run it once" without saying who runs it.
Decision: (1) PurchaseOrders::Close and StockTransfers::Close decrement incoming_count by each line's incoming; Update leaves the table. (2) The Inventory page lists one row per stock level across every location, with a Location column, and the location switcher narrows the list. (3) spree:stock:recount_levels is a step of the 5_6_to_6_0 upgrade manifest.
Consequences: The writer set and the recount source now agree at every status: a document counts toward incoming exactly while it is ordered, in_transit or partially_received, whichever workflow moved it there or out. Nothing on the page is summed across locations — a merchant reading a variant's total on-hand across warehouses reads it on the variant, not here. Existing installs get their counters filled by the same spree:upgrade that runs the other 6.0 backfills; the task stays runnable by hand to repair drift.
2026-09-10: Stock levels carry reserved and incoming as counters, and the Inventory page reads them
Context: The dashboard's Inventory section (transfers, purchase orders, suppliers) had no view of the stock itself — no page answering "what do I have, where, and what is committed, held or on its way". The columns a merchant expects are Shopify's: on hand, committed, available, incoming. Spree already persists on hand (count_on_hand) and committed (allocated_count) but computed reserved at read time in Stock::Quantifier and had no notion of incoming at all, even though every purchase order and transfer now carries a destination_location_id.
Decision: Two new counter-cache columns on spree_stock_levels — reserved_count and incoming_count — and a new phase in 6.0-inventory-operations.md for the page that reads them. Counters, not computes: the page is a paginated list read many times a day, the inputs change through a small number of workflows, and the repo already trusts allocated_count, fee_total and commission_total the same way. Each counter has exactly one writer path — Reserve/Release/ExpireJob for reserved; MarkOrdered/MarkDraft/Cancel/Update on purchase orders, MarkInTransit/Cancel on transfers, and StockReceipts::Recording for both, for incoming — mirroring the movement-callback discipline that keeps allocated_count honest. A spree:stock:recount_levels task recomputes both from their sources, reports drift, and is the backfill. Available on the page is count_on_hand − allocated_count − reserved_count, the same figure the Quantifier already produces.
Consequences: Incoming is [expected − received − rejected, 0].max per line, added to Spree::ReceivableItem as #incoming so the counter and the recount share one definition — outstanding alone still counts rejected units as awaited, and they are not coming. A transfer counts as incoming from in_transit, when quantity_shipped is written, not from ready_to_ship; that diverges from Shopify, which counts from creation, and is deliberate: nothing is moving yet. The receipt recorder already runs inside receivable.with_lock, so the incoming decrement is atomic with the on-hand increment. Unavailable is out of scope. Rejected delivery units are not it — they "exist only on the receipt" (the 2026-09-10 dock decision) and were never in the building, whereas Shopify's Unavailable is on-site stock held back; a true bucket would be a fourth counter with its own adjust action and reason vocabulary, and no reference validates it yet. The page is dashboard-only; the seller panel gets the same table under a forced seller scope as a follow-up, per the dashboard-is-the-reference rule. The earlier note that "rejected receipt units have no backing" was half right: the count is recorded, the stock is not.
2026-09-10: A delivery is a stock receipt — discrepancies get quantities, over-receipt gets a status, and a short order can be closed
Context: Comparing the shipped inventory operations against a multi-location omnichannel
merchant's own purchasing code showed what a warehouse dock records that ours could not: a
delivery with two damaged units out of ten, a delivery of twelve against ten ordered, and a
supplier confirming the last two will never come. Ours held one running total per line, a
single free-text discrepancy on transfer lines only, refused any receive above the expected
quantity, and left a short order in partially_received forever. The same review found no way
back from ready_to_ship, no cancel-by date, and no CSV in either direction.
Decision: One new model and five additions, recorded in 6.0-inventory-operations.md
under "Receipts, discrepancies and the rest of the dock". Spree::StockReceipt is one
delivery against a purchase order or a transfer — numbered SR-…, carrying the packing-slip
reference and date — and Spree::StockReceiptItem is one line of it with quantity_accepted,
quantity_rejected and a rejection_reason. Named stock receipt because a customer-facing
sales receipt will want the plain word. A receive payload now carries this delivery's counts
rather than running totals, and PATCH …/receive becomes POST …/stock_receipts. Rejected
units are never stocked. Over-receipt is allowed and is a terminal over_received status of
its own (chosen over a badge: a list should say it at a glance). Close takes
partially_received → received with closed_short_at and a close_reason, which also
records why a cancelled transfer's in-flight units were written off. cancel_by is a date
on the order with Overdue and Past cancel-by filters and no automatic cancelling.
MarkDraft returns a ready_to_ship transfer, or an ordered order with no receipt, to
draft. CSV export and import ride the existing Spree::Export / Spree::Import frameworks
under the purchasing scope; the import groups rows by reference into drafts and requires
the SKU to exist.
Consequences: Every received movement against these documents now also names its
stock_receipt_id, so a delivery can be reconciled, and the upgrade task mints one receipt
per migrated 5.x receive so history reads the same way. discrepancy_reason leaves
spree_stock_transfer_items. Out of scope on purpose: purchase-order lines for products not
yet in the catalog, dropship, consignment, and a quarantine location for rejected units —
the first is a buying feature that drags product creation into purchasing, and the rest are
their own plans.
2026-09-09: Reporting bases are registry data, in three families that never mix
Context: The reporting compiler hardcoded its two bases (:orders, :line_items) in a case statement, and compatible? was written as a two-base special case where :orders is universal. That left the two report families merchants ask for next — payments and inventory — unreachable, and they were recorded as out of scope on an implementation-difficulty judgment rather than a product one. They are not session data, so nothing about a headless storefront excludes them.
Decision: Bases become registry entries. registry.base declares a base's family, its own table, a store-scoped relation, its time column and which bases its dimensions can reach; compatible? generalises into that reachability rule and the compiler stops branching on base names. Core registers four bases in three families: sales (:orders, :line_items), payments (:payments), inventory (:stock_movements). A query draws from one family only — the three answer different questions on different clocks (order completion, when a payment was taken, when stock moved), and a payment total beside a units-received count is two reports wearing one table. The schema publishes families so a builder never offers a cross-family pair.
Consequences: Payments and inventory ship with vocabulary and five more seeded reports (19 in total). Two mechanics are load-bearing: a stock movement's kind carries direction, so each metric sums one kind rather than raw quantity — summing across kinds nets a receipt against a dispatch; and spree_stock_movements has no store column, so its base scopes through StockMovement.for_store's stock level → variant → product walk, which is the only tenancy path that table has. A base now declares its table separately from its time_column, because deriving one from the other read every line-item dimension off the orders table (a line item's clock lives on its order). payment_result is deliberately not called payment_status: the order-level dimension of that name says how much of an order is paid, this one says whether one charge went through. Sessions, referrers and conversion rates remain the only recorded gap, and are unavailable by construction.
2026-09-09: Reporting speaks the industry sales chain; commission and payout numbers are permission-gated
Context: A survey of what merchants expect a commerce back office to report — the whole catalogue minus marketing and behaviour, which need session data a headless storefront never collects — showed the shipped reporting vocabulary answered the right questions under the wrong names. gross_revenue was in fact total sales, net_revenue was neither of the industry's two terms, and the two figures merchants ask for first (real net revenue, and what each seller is owed) could not be expressed at all. Registered names are public API from the release, so a rename had to happen before saved reports baked the wrong ones in.
Decision: The vocabulary follows the recognised chain — gross_sales − discounts − returns = net_sales, then net_sales + shipping + duties + fees + taxes = total_sales — with orders, customers and average_order_value replacing the *_count/aov names, plus margin (cost_of_goods, gross_profit, gross_margin) and marketplace (commission, seller_payout) metrics and seller / customer_type dimensions. A returning customer is one with prior orders, decided per order against history rather than a stored flag. Refunds are reported on the date they were processed, so a past period restates. Order-level money living on another table (refunds, commissions) is summed through a correlated subquery, never a join — an order with three refunds must stay one row. Metrics may now declare subject/key_scope the way dimensions do, and commission/seller_payout use it: marketplace money is gated by read_commissions / read_payouts, not readable by anyone holding read_reports.
Consequences: The nine seeded reports, the dashboard home's metric list and the reporting specs move together; a store already seeded keeps its old rows, since the seeder only adds what is missing (and a saved report naming a removed metric fails validation loudly rather than silently returning nothing — the upgrade note belongs with the release). A dimension may now carry expression: for a computed key, which is how customer_type works; column: keeps its identifier-only guard. Still out of reach and recorded so nobody hand-rolls them: net payments and payment-method breakdowns need a :payments base, inventory history needs a :stock_movements base, and both wait on the compiler taking its base list from the registry rather than its hardcoded pair. Sessions, referrers and conversion rates stay unavailable by construction.
2026-09-07: Inventory operations grooming — transfers get a status and workflows, supplier receives become purchase orders, and a receive records what the units cost
Context: 6.0-inventory-operations.md was written before three things
landed that its own code samples assume away: state_machines-activerecord
left the dependency list, permission sets became a registered catalog of
grant keys, and the public_metadata/private_metadata pair became one
metadata column. decisions.md 2026-08-30 also left one call explicitly to
this grooming — whether removing the one-shot StockTransfer.transfer API
uses the 6.0 breaking window or ships behind a deprecation bridge. Grooming it
for implementation surfaced a tenancy hole as well: spree_stock_transfers
has no store_id, Spree::Store has no stock_transfers association, and so
Spree::Base.for_store falls through to self — the admin transfers endpoint
has never been store-scoped.
Decision: Seven rulings, all inside the plan's existing design.
Statuses are declared, transitions are workflows. Spree::StockTransfer
(draft | ready_to_ship | in_transit | partially_received | received | canceled) and Spree::PurchaseOrder (draft | ordered | partially_received | received | canceled) both include Spree::HasStatus; every move between
statuses is a workflow under Spree::StockTransfers:: /
Spree::PurchaseOrders::, registered on Spree::Dependencies. This is not
merely conformance with 6.0-normalize-state-to-status.md: a receive has to
carry the quantities the warehouse actually counted and a cancellation has to
carry the merchant's restock-or-write-off choice, and a transition callback
takes no arguments. The guards a state machine expressed as from: become
each workflow's own status check.
The one-shot StockTransfer.transfer / .receive methods are removed
outright. A shim would keep a second write path into count_on_hand alive
through 6.0, which is the exact thing typed movements exist to prevent. The
admin POST /stock_transfers now persists a draft rather than moving stock.
spree_stock_transfers gains its own store_id, closing the scoping hole
above and giving transfers the same tenancy rule as purchase orders instead of
a second one derived from destination_location. source_location_id stays
nullable in the database with presence enforced on the model — a
change_column_null would fail on any install still holding external-receive
rows, and emptying that column is the upgrade task's job.
Legacy source-less transfers are soft-deleted, not dropped.
spree:upgrade:migrate_external_receives_to_purchase_orders mints the PO-…,
points the existing movements at it and stamps the T-… transfer
deleted_at, so the old number stays findable without the same receive
appearing twice in the admin;
spree:upgrade:purge_migrated_external_receives removes them later.
Suppliers and purchase orders are one new catalog resource, :purchasing
(read_purchasing / write_purchasing), registered beside :stock in
PermissionConfiguration::DefaultCatalog.register. The plan's earlier
read_inventory / write_inventory would have put "Stock" and "Inventory"
side by side on the roles screen with nothing to tell a merchant which covers
what. Spree::StockTransferItem joins the existing :stock subject list.
Suppliers are per store — store_id, Spree::SingleStoreResource, unique
on (store_id, name). Promoting them to installation-wide later means a join
table and a one-row-per-supplier backfill; nothing is built against that.
A receive records what the units cost.
spree_stock_movements.unit_cost (nullable decimal(10, 2)) carries the price
each unit landed at, so the rolling average-cost feature the plan defers has a
ledger to read rather than a reconstruction to attempt — including across two
partial receives at different prices. Transfers and returns leave it null:
moving stock a merchant already owns is not a purchase. Money is a
decimal(10, 2) column throughout, following Spree::Variant#cost_price —
Spree has no money-rails dependency, so the plan's _cents + monetize shape
does not exist.
Consequences: StockTransfer.transfer and .receive are gone at 6.0 and
need an upgrade note. Never write status on a transfer or a purchase order
directly — it passes the inclusion validation, writes no movement, and
desynchronizes the ledger from the shelf; call the workflow. Never reach
Spree::StockTransfer unscoped now that it carries store_id. Status columns
ship with no database default (the creating workflow sets them; has_status
supplies the attribute default), and both new metadata-carrying tables have
one metadata column. StockLocation#restock and #move take an optional
unit_cost:. Statuses spell canceled with one l, matching the other 87
occurrences in core. Status transitions are PATCH member routes, matching
orders/:id/cancel and returns/:id/receive — the plan's claim that they are
POSTs described no existing endpoint. Lot tracking stays 6.1 and the 6.0 half
builds no lot rows, so open questions 5 and 6 keep their reasons; open
question 4 (ship-to-store transfers) stays open pending the fulfillment plan's
call on what a pickup date range promises when stock has to travel.
2026-09-07: Deposits are not a shipping concern — how a buyer pays gets its own plan
Context: 6.0-b2b-wholesale-shipping.md originally specified deposits as part of wholesale freight: a delivery method would carry a deposit_percentage, checkout would collect it, and the order would complete part-paid. Building it raised two questions that had to be answered before it could ship. Is a shipping method the right thing to hang a payment arrangement on? And does merchant-configurable deposit collection belong in open source at all? Researching the second answered the first.
Decision: This plan covers how goods ship; how the buyer pays is a separate subject with its own plan. Three findings drove it. Deposits and net terms are two halves of one arrangement — merchants combine them ("40% deposit, balance Net 30"), and the only native implementation in the market models the deposit as an attribute on a payment term. Shipping half the subject inside a shipping plan leaves a vocabulary with no way to set it and no home for the other half. The arrangement belongs to the buyer, not the shipment — a deposit is negotiated with a company; no comparable platform configures one per shipping method, and every one that offers deposits scopes them per product, per customer, or per order. Two OSS plans already defer net terms to a payment-terms plan that does not exist (6.0-payment-method-rules.md, 6.0-6.1-b2b-payment-terms.md), so the destination was already named — it just had not been written.
Consequences: No delivery method carries a deposit_percentage, and freight must not become a second place payment arrangements are configured. One piece is deliberately kept so the payment-terms plan starts from a hook rather than from patching: Purchase#amount_due_at_checkout, answering the full total through Spree::Purchases::AmountDueAtCheckout (registered in Spree::Dependencies), read by the four decisions that gate on money arriving — checkout requirements, both completion guards, and dispatch. Without it, an arrangement collecting part of the total up front has to patch those four independently. It ships with a spec proving the open-source answer is the total, and a spec registering a half-up-front replacement and proving checkout, completion and dispatch all follow it. What a new payment or gateway session defaults to, and the capture loop, still read total: those are amounts rather than decisions. Partial payments are untouched — they predate this work. A related fix rides along because it holds independently: dispatch now guards on payment_total >= amount_due_at_checkout rather than paid?, which required a positive total and so refused to ship a fully discounted or store-credit-paid order.
2026-09-04: Catalog audiences are alternatives, not layers — a company buyer is never also priced by their customer group (V-3570)
Context: Catalog.for_context consults a buyer's customer groups only when the company axis came back empty, so a merchant who put a shared range on a dealer group's company node and each trade tier on a customer group got tier prices that never applied — every dealer paid retail, with the catalog active, the audience assigned and the percentage saved. The code said two things about whether that was intended: the plan and the resolver describe a fallback chain, while Spree::Catalog's class comment said visibility across applicable catalogs is their union, which reads as both audiences being consulted. The reading had to be ruled before either could be documented.
Decision: The fallback chain is the intended behaviour and stays: the company subtree if any of its nodes carry a catalog, otherwise the customer's groups, otherwise the channel's default catalog. A buyer is on one agreement, resolved from the nearest party to them — layering a personal segment's prices on top of a company's negotiated ones would price one purchase under two agreements at once, and which won would depend on catalog position rather than on anything a merchant chose. Trade tiers over a company tree are expressed as company assignments: the shared range on the root, each tier's catalog on the member companies or divisions in that tier (one tier catalog carries as many assignments as the tier has members). That route already works and is what the union-within-an-audience plus nearest-node-first pricing was built for. Customer group assignments remain for buyers not purchasing for a company at all — a retail loyalty tier, a staff discount.
Consequences: No behaviour change; the fix is that the code and the dashboard now say so. The class comment is corrected (it was the only place claiming the two audiences combine), the for_context and pricing-resolver comments read "or failing that" rather than "then", and the fallback carries an inline note. The dashboard states the precedence where a merchant can act on it: help text under the audience picker when a customer group is chosen, and a standing note on the audience card and wizard step whenever a group assignment is present, pointing at the company route for tier pricing. The developer docs stop framing the three ways of reaching a buyer as combining and carry the tier recipe as a warning. Three examples in catalog_spec.rb lock the ruling — the group dropping out once a company catalog exists, the group still applying when none does, and the subtree union when the tier is a company assignment. What is not solved: nothing detects a catalog assigned only to groups whose members are all company buyers, so such a catalog is still silently unreachable; a reachability warning needs the buyer population and is a separate piece of work.
2026-09-04: Catalog audiences are alternatives, not layers — a company buyer is never also priced by their customer group (V-3570)
Context: Catalog.for_context consults a buyer's customer groups only when the company axis came back empty, so a merchant who put a shared range on a dealer group's company node and each trade tier on a customer group got tier prices that never applied — every dealer paid retail, with the catalog active, the audience assigned and the percentage saved. The code said two things about whether that was intended: the plan and the resolver describe a fallback chain, while Spree::Catalog's class comment said visibility across applicable catalogs is their union, which reads as both audiences being consulted. The reading had to be ruled before either could be documented.
Decision: The fallback chain is the intended behaviour and stays: the company subtree if any of its nodes carry a catalog, otherwise the customer's groups, otherwise the channel's default catalog. A buyer is on one agreement, resolved from the nearest party to them — layering a personal segment's prices on top of a company's negotiated ones would price one purchase under two agreements at once, and which won would depend on catalog position rather than on anything a merchant chose. Trade tiers over a company tree are expressed as company assignments: the shared range on the root, each tier's catalog on the member companies or divisions in that tier (one tier catalog carries as many assignments as the tier has members). That route already works and is what the union-within-an-audience plus nearest-node-first pricing was built for. Customer group assignments remain for buyers not purchasing for a company at all — a retail loyalty tier, a staff discount.
Consequences: No behaviour change; the fix is that the code and the dashboard now say so. The class comment is corrected (it was the only place claiming the two audiences combine), the for_context and pricing-resolver comments read "or failing that" rather than "then", and the fallback carries an inline note. The dashboard states the precedence where a merchant can act on it: help text under the audience picker when a customer group is chosen, and a standing note on the audience card and wizard step whenever a group assignment is present, pointing at the company route for tier pricing. The developer docs stop framing the three ways of reaching a buyer as combining and carry the tier recipe as a warning. Three examples in catalog_spec.rb lock the ruling — the group dropping out once a company catalog exists, the group still applying when none does, and the subtree union when the tier is a company assignment. What is not solved: nothing detects a catalog assigned only to groups whose members are all company buyers, so such a catalog is still silently unreachable; a reachability warning needs the buyer population and is a separate piece of work.
2026-09-03: Reporting counts what stayed sold; the Total row is the dimensionless figure
Context: Reviewing the shipped saved-reports work (6.0-analytics-semantic-layer.md Steps 7–9) surfaced two semantic gaps in the live adapter: canceled orders kept counting toward revenue because only completed_at scoped the base, and the ungrouped totals carried the grouping joins, so a product in three categories tripled in the footer while orders without a shipping address vanished from "Sales by country".
Decision: Both metric bases exclude status: 'canceled'. Grouping joins apply only to the grouped query; totals run on the base rows with the same filters, and a filter on a joined dimension narrows through an id subquery so a line item matching two selected categories is counted once. Built-in (seeded) reports are read-only on the model; report CSV exports validate the query and the requester's members at create time. One predicate each for member authorization (Query#unreadable_subjects) and base compatibility (Registry#compatible?).
Consequences: The rows of a fan-out breakdown do not sum to the Total row, by design — the footer is the store figure for the range, the rows are the share each group had in it. Future adapters (fact tables, ClickHouse) inherit the same rule. Refund semantics are unchanged (already net in payment_total).
2026-09-03: Saved reports are store-wide and export through the Export pipeline
Steps 7–9 of 6.0-analytics-semantic-layer.md settled three product questions:
saved reports are visible store-wide (author recorded, viewer re-authorized at
execution), CSV export is a Spree::Exports::Report type on the existing
async Export pipeline rather than a synchronous download (one export UX across
the admin), and the full Step 8 vocabulary (presets, week grain, market /
country / variant dimensions, discounts / delivery / tax metrics) ships with the
Reports page. The :reports permission catalog resource gains write keys and
covers Spree::SavedReport + Spree::Exports::Report.
2026-09-03: A return label buys the cheapest rate; the fulfillment's tracking becomes a read-through summary
Context: Implementing 6.0-shipping-labels-and-deliveries.md raised two
questions the design left open — which rate a return label buys, and what
happens to code that assigns fulfillment.tracking.
Decision: A return label buys the cheapest rate the connected account
offers across every carrier. Unlike an outbound parcel there is no rate the
customer selected: return postage is the merchant's own money and nobody chose
a service for it. Reusing the outbound carrier was rejected because a parcel
whose tracking was hand-entered has no carrier to reuse, and mirroring the
outbound service inbound is usually the most expensive answer to a question the
merchant never asked; a merchant wanting a fixed return service configures it on
the integration later, which is additive. Separately, Spree::Fulfillment#tracking
becomes a read-through summary of the primary delivery and #tracking= a
deprecated shell that writes that delivery on save — the 5.6 field keeps
working for host code and the storefront one more release, and both go in 6.1
with the column. One naming consequence: the label's file format is written as
file_format on the API, because format is Rails' own request-format
parameter and a controller permitting it receives "json".
Consequences: Return labels need no configuration to work, which is what
makes the customer-facing return-label download usable the day the plan ships.
The deprecated tracking= writer is the reason the upgrade is quiet: an
extension or host app that sets a tracking number the old way still lands it
where every reader looks, with a warning naming the replacement. Plan:
6.0-shipping-labels-and-deliveries.md.
2026-09-03: Labels and parcels are records; the carrier axis moves onto Spree::Delivery in 6.0 (supersedes 2026-08-11 "multiple trackings deferred to 6.1")
Context: A shipping label was three EasyPost-private keys in fulfillment.metadata, surfaced by a per-read provider.documents call and bought through PATCH .../purchase_label. Spree never knew the postage cost, could not reprint once the carrier's hosted URL expired, could not buy a second label after a refund (idempotency keyed off the metadata), and had nowhere to put a return label — the returns plan had already sent that to "the URL in metadata". Tracking lived in seven columns on spree_fulfillments, one number per parcel, with a spree_fulfillment_trackings model deferred to 6.1 and required to absorb the whole axis when it came. Both were candidates for "promote to a model with RESTful routes"; only one of them is a thing.
Decision: Two new tables, both with a polymorphic owner (Fulfillment | Return) on the 2026-08-22 tax-identifier reasoning — one concept held by different parties, not a type string hiding several meanings. Spree::ShippingLabel is the purchased or uploaded carrier document: cost and currency (merchant accounting, admin-only), the file in private storage fetched from the provider at purchase, purchased → refund_requested → refunded, an external_id, and a frozen tracking_number. Spree::Delivery is one parcel's carrier journey — tracking number, carrier, carrier status (pending instead of nil), estimate, arrival, scan details — optionally minted by a label. delivered on the fulfillment stays a transition, not a model: marking delivered is the fulfillment's own status changing, and the fulfillment rolls it up from its deliveries (or from staff, for parcels that have none). Idempotency of the label buy moves into core — the workflow refuses on an active label, so providers stop keeping metadata keys. The provider contract grows a typed purchase_label(owner) → Spree::LabelPurchase and refund_label(label); create_fulfillment stays for non-label dispatch. The 6.0 edge's fulfillment-level tracking_carrier/tracking_status/tracking_details/estimated_delivery_at are removed in place rather than bridged (never released); tracking and tracking_url (5.6 API) stay forever as the primary delivery's summary.
Consequences: The 2026-08-11 deferral's constraint held — the delivery takes the entire axis, nothing stays split between fulfillment and row — but the model lands in 6.0 and under a different name, because a Return owns parcels too and FulfillmentTracking cannot say so. The name was tested twice: Delivery was questioned for leaning toward the arrival event, Parcel was chosen and then withdrawn the same day when checked against 6.0-b2b-wholesale-shipping.md, which uses "parcel" as the antonym of freight — a PRO number covering three pallets is not a parcel. Tracking collides with the 5.6 Fulfillment#tracking string that stays forever. Delivery is the modality-neutral word carriers use for a parcel and a pallet alike; the two-meanings cost beside DeliveryMethod/DeliveryRate is accepted. The same check settled that freight paperwork (bill of lading, placards, packing lists) is never a ShippingLabel — it belongs to OrderDocument in 6.1-b2b-order-documents.md — and that Delivery#carrier is free text, never validated against the carrier registry, or a forwarder's number becomes unenterable. Return labels ship now on the same table (EasyPost is_return), with a Return delivery that never auto-receives: arrival is not inspection. Uploaded labels are in scope, so merchants on the Manual provider get a place for postage they bought elsewhere; POST .../labels purchases without a body and records with a file. Sellers may upload and track but never purchase or refund — those need the operator's carrier account. The routing rule this settles for the whole Admin API: a durable record with its own identity (label, delivery, refund) is a nested resource created by POST; a lifecycle transition (fulfill, cancel, mark_delivered, capture, approve) stays a PATCH member action. Plan: 6.0-shipping-labels-and-deliveries.md.
2026-09-02: A 6.0 column rename is earned by public leakage, not by completeness
Context: 5.4-store-api-naming-standardization.md listed six database renames as its remaining 6.0 work — roughly 1,900 references. But the 5.4 model aliases already make every API response speak the new names, so the honest question was not "which renames are left" but "which ones still change anything a caller can see".
Decision: Rename only where the old name still reaches a public surface. Three things bypass an attribute alias: Ransack filter keys (the whitelist publishes the column, not the alias), validation error keys (a client sending postal_code got its error back under zipcode, so it could not map the error to the field it sent), and delegated method names (bill_address_firstname, which the dashboard's own order table sorts by). Renamed on that test: the address name and postal-code columns, and the option type/value presentation column with its two Mobility translation tables. Two more rode along for consistency rather than leakage — Spree::WishedItem (its class and table were the only ones that never matched the serializer the API already ships) and the last two promo_total columns (Order aliased one way, LineItem and Fulfillment the other, a reading trap). Deferred to 6.1: spree_credit_cards.cc_type/last_digits and the order/cart address foreign keys — absent from the v3 contract, never validated, aliases complete, and the FK pair alone is ~1,000 references.
Consequences: Two bridge shapes now coexist and the difference is load-bearing. alias_attribute resolves inside where and find_by, so the address and total bridges are complete. The option bridge cannot be an alias_attribute — Mobility owns label — so it is a plain method and where(presentation:) raises; that asymmetry is documented in the concern and the upgrade guide rather than papered over. The wishlist item's wi_ prefix stays put (amended 2026-09-03): a prefixed ID is a Store API identifier a client holds, and decode_own_prefixed_id rejects a foreign prefix, so moving it 404s every ID already issued. The si_ → sl_ precedent does not transfer — StockLevel is admin-side. An existing model keeps the prefix it issued; only a new model picks one. The leakage test is the reusable part: before renaming a column that an alias already hides, check whether Ransack, an error key, or a delegation still publishes the old name — if none do, the rename is churn.
2026-09-02: EU compliance ships whole in open source — subject requests are asynchronous, erasure is anonymization, withdrawal is its own window
Context: 5.4-6.0-eu-legal-compliance.md had shipped only its Omnibus half — Spree::PriceHistory, the recording callback and ?expand=prior_price. Everything GDPR and everything Consumer-Rights was still a sketch: no consent timestamp, no export, no anonymizer beyond scramble_email_and_names (which touches three columns on one row), no erasure endpoint a merchant could actually reach, and no withdrawal deadline. The gap mattered more than it looked: Spree::Customer#check_completed_orders refuses to destroy any customer who has bought something, so an EU merchant receiving an erasure request for a real buyer had no path at all short of the Rails console.
Decision: Build the rest of the plan in core, with four rulings settled before implementation.
A subject access request is asynchronous and leaves a record.
POST /store/customers/me/data_exportenqueues a job and answers202; the file is built off the request cycle, stored privately, and the customer is emailed a signed link. A second request while one is pending returns the pending one rather than starting a second build. The alternative — a synchronousGETreturning JSON inline, which the plan originally sketched — puts an unbounded multi-table query on a web worker and, worse, leaves nothing behind: Art. 30 record-keeping wants evidence the request happened and was answered, and a response body that was streamed and forgotten is not that. This is a newSpree::DataRequestmodel rather than aSpree::Exportsubclass: that pipeline is admin-owned (belongs_toan admin user), CSV-only and store-scoped, and a customer-owned JSON subject export is none of those things. The 24-hour cooldown the open question offered is subsumed — a pending request is the cooldown.Both subject-request endpoints ship in open source, on the storefront and in the admin. The plan had reserved
POST /admin/customers/:id/anonymizeandGET /admin/customers/:id/exportfor Enterprise. That split fails the common case: erasure and access requests arrive as email to the merchant's support address, from people who often no longer have a working login, and from guests who never had an account. A self-service-only implementation serves the rare request and leaves the ordinary one to the console. Core ships the mechanism at both ends, gated onwrite_customers. Enterprise keeps what is genuinely a product rather than a mechanism: the request queue, the one-month Art. 12(3) deadline clock, the audit trail, automated retention runs and per-market legal text.Erasure means anonymization, and the ledger survives it. Order totals, tax lines, line items, payments and refunds are never touched. Names, emails, phones, street lines, IP addresses, customer notes and metadata are replaced across the customer, their address book, the address snapshots on their orders, gateway customer profiles, OAuth identities and refresh tokens. City, state, country and a truncated postcode survive deliberately: a VAT audit has to be able to establish the jurisdiction a sale was taxed in, and erasing that would trade one legal obligation for another. Deleting the order address rows outright was rejected for the same reason.
The withdrawal period is its own market preference, anchored on delivery.
Spree::Marketalready carriesreturn_window_days, and reusing it was tempting. It is the wrong quantity. The statutory right of withdrawal runs 14 days from the moment the buyer receives the goods; a return window is merchant policy running from purchase, and merchants routinely set it to 30 days as goodwill. Collapsing the two would publish a goodwill figure as a statutory notice, and would count it from the wrong event. Sowithdrawal_period_days(default 14) sits besidereturn_window_days, and the deadline computes from the order's latestdelivered_at, falling back tocompleted_atwhile nothing has been delivered — which honours the 2026-08-11 ruling thatdelivered_atis what the EU withdrawal period counts from.
Consequences: Anonymization is the only sanctioned erasure path — scramble_email_and_names becomes a deprecated shell delegating to it, and no new code may delete customer PII by hand. Any new table carrying customer-identifiable data must be handled by Spree::Customers::Anonymize in the same change that introduces it, and there is a spec that fails when a PII-shaped column appears in the schema without the anonymizer covering it. Consent acquires a timestamp and a source: accepts_email_marketing alone is no longer sufficient proof, and every path that flips it records when and where. Checkout and registration consent is persisted (Spree::ConsentRecord), closing the item 6.0-store-policies.md parked. The price-history prune task reads the store preference rather than the global config, per the store-scoped configuration rule.
2026-09-02: Translation staleness tracking is cut, not deferred with a design
Context: 5.5-6.0-resource-translations-api.md had carried a Phase 2 commitment to server-side staleness since 2026-07-27 — a source_digest per translation cell, a stale flag computed at read time, and a ?include=staleness verbose read shape — described as "Shopify's idea minus its mandatory-digest footgun". The business case is genuine: coverage answers "is there a translation?", nothing answers "is it still about the current source?", so a merchant who edits English copy after translation serves stale copy in every other locale indefinitely, with the coverage grid still reading 100%. But when Phase 2 came up for implementation the case did not survive scrutiny.
Decision: Cut it. Ship the coverage endpoint, the generalized CSV import/export and the centralized dashboard page; build no staleness. Three reasons. Only Shopify tracks drift at all — Vendure, Medusa and Saleor ship nothing, so one-of-four is thin evidence of merchant demand. Shopify's mechanism is not the one we would have built: its digest is required on every write and serves as an optimistic-concurrency guard, whereas ours would have been a display flag alone, meaning we would ship something no platform has validated in that form. And it was the largest build in the phase — a migration, a write path on every cell, a read-time comparison, a verbose response mode and a backfill task — for the only item nothing else depends on.
Consequences: No source_digest column, no stale key, no ?include=staleness. The matrix keeps its flat { field → value } shape and translated_field_count stays the only completeness signal. Nothing forecloses a revival: two findings from the cut are recorded in the plan for whoever picks it up — a shared polymorphic digest table beats a column per *_translations table (per-field rather than per-row granularity, and future registry members need no migration), and the flag stays advisory, never required on write. Revisit when merchants using the coverage page report source drift as an actual complaint.
2026-09-02: Custom field definitions become store-owned, with a persisted filter_key
Context: Spree::CustomFieldDefinition (formerly MetafieldDefinition) was the last piece of merchant-facing schema with no owner. Every store in an installation shared one set of definitions, and the admin endpoint had no scope override, so any store's staff read and edited every other store's custom-field schema. Alongside it, filter_key — the cf_<namespace>_<key> identifier the product listing sorts and filters on — was computed in Ruby on every call, which left its uniqueness resting on a CONCAT-based validation with no index behind it. Both were deferred out of the 5.6 search/sort/filter work because they are schema changes and that shipped as a patch release.
Decision: The definition becomes a Spree::SingleStoreResource with a persisted filter_key, and uniqueness becomes (store_id, resource_type, filter_key) behind a real unique index. Three sub-rulings settled today:
- Existing definitions all move to the default store. No per-store copies. Copying would have produced N duplicate rows whose values still pointed at the originals, so every non-default store would show the same blank fields it shows under the simpler backfill — at N times the rows and with a re-pointing pass over
spree_custom_fieldsto write. Multi-store operators re-create the fields they want on their other stores. - The migration backfills and enforces NOT NULL itself, with
spree:upgrade:backfill_custom_field_definition_storesin the 5.6→6.0 manifest as the recovery path for installs that migrated before any store existed. This follows the return/refund reason precedent shipped earlier in 6.0 and closes the window the plan's original two-phase path left open: a nullable scope column voids the unique index outright, because SQL treats NULLs as distinct, so uniqueness would look enforced while not holding. - A custom field's value is validated to agree with its definition's store (revised during implementation). The original ruling was that resolution is store-scoped at every path, making a validation redundant — that turned out to be false.
custom_fields=routes through the store-scoped resolver, but Rails' ownaccepts_nested_attributes_forwriter assignscustom_field_definition_idstraight onto the row and reaches no resolver at all, so a foreign definition was accepted through the nested path. The validation now sits onSpree::CustomField, beside theresource_typeagreement check that was already there for the same reason, and it is the one gate every write path passes. It skips resources with no store of their own (a customer, an address are global), which is the partial-guarantee objection from the original ruling — but a partial guarantee at the convergence point beats none, and the skipped types were resolved within a store on the way in.
Consequences: store.custom_field_definitions is the reading mechanism — no for_store scope of its own, and no unscoped Spree::CustomFieldDefinition reads anywhere (the store-scope tripwire now watches the table). filter_key is a real column: it can be selected, indexed and ordered on, and the CONCAT validation is gone. Spree::SearchProvider::CustomFieldSchema takes the store it describes, so two stores no longer share one filter vocabulary. CSV header and value rows must be produced from the same store's definitions or they misalign.
2026-09-01: Seller delivery — the marketplace owns the profiles, the seller owns their methods
Context: 6.0-multi-vendor-marketplace.md had promised DeliveryMethod#seller_id since 2026-08-15 without ever designing it, and the shipped code went the other way: every delivery record is store-scoped, the estimator knows nothing about sellers, a seller's only delivery lever is where their stock sits, and Carts::SplitBySeller#divide_delivery_cost apportions one quote after payment. Meanwhile the seller branch had taken product type and delivery profile off the product form (2026-08-26), so every seller product landed on the store's default profile. The legacy multi-vendor module owned methods per vendor and kept zones and categories global; of the two marketplace platforms studied, one lets sellers build the whole shipping tree themselves and the other keeps an operator vocabulary the seller prices within.
Decision: Two questions, two owners. "What kind of goods is this" — DeliveryProfile, with its zones and origin groups — is the marketplace's vocabulary and never carries a seller_id; a seller assigns a profile (and a product type) to their product, shipped the same day. "Who ships it, how, at what price" — DeliveryMethod — is the seller's: nullable seller_id, plus an available_to_sellers switch on marketplace methods so an operator who runs shipping for everyone shares theirs. A package's seller is its stock location's, and the methods it is offered are decided in Stock::Estimator#filter_delivery_methods alone. Seller methods price through the internal rate provider and fulfil manually; carrier accounts stay on the store-scoped Integration until a seller-owned integration is needed. DeliveryOriginGroup#covers_location? answers true for seller locations, fixing the narrowed-group defect that made seller stock unallocatable. "At least one way to ship" becomes a computed seller requirement, and delivery_methods its own seller-grantable catalog resource.
Consequences: No per-seller profile, zone or origin-group layer, ever; no seller checks outside the estimator; the post-payment cost division stays only as the fallback for a first-party location holding several sellers' goods; carrier-backed seller methods are refused by validation rather than half-supported. Full design: 6.0-multi-vendor-marketplace.md, Decision 13.
2026-08-23: BusinessAddress stays a table-sharing subclass, not STI
Context: Spree::BusinessAddress overrides three predicates on Spree::Address — require_name? false, require_company? true, show_company_address_field? true — and is used by a seller's billing address. It was briefly converted to real STI (a type column on spree_addresses, an index, a backfill, CompanyLocation's two addresses typed to it), on the argument that the rules should travel with the row so a company address copied onto a cart's base-typed bill_address would still validate as a business address. That was reverted the next day.
Decision: No type column on spree_addresses. Business-ness is a fact about the owner — a seller, a company location, or company_location_id on the cart/order — not about the address row, and the owning association already states it.
Three findings killed the STI argument, all of them checkable in code that already existed:
- Checkout copies attributes, not records.
Spree::Purchase::Addresses#update_or_create_addresstakes a params hash and ends atSpree::Address.create(attributes), hardcoded to the base class. A company location's address entering checkout is reduced to a hash and reborn as a plainAddress; thetypenever travels. The premise of the STI conversion — that the class survives the copy — was false on the only path that matters. - Keeping
typesignificant for dedup breaks address-book reuse. Deduplication matches on all attributes (Spree::Address.find_duplicate, which spree/spree#14486 consolidated from the three divergent copies that existed while this was being decided). With atypecolumn, a business address and a personal address with identical postal details never dedupe, so a B2B buyer re-creates a row on every order. - The tax decision never consults the address class. Per
6.1-channels-catalogs-b2b.md, exemption hangs offCompanyandresolved_tax_identifierwalks order → company → customer. The address's Ruby class contributes nothing.
The base Address has carried a company column and preference-driven require_company? / show_company_address_field? predicates all along, so the mechanism for "this address belongs to a business" already existed and was already configurable. STI bought two boolean overrides at the cost of a column on one of the most-written tables in Spree, plus knock-on edits to empty?, the exclusion-list constants, json_api_columns, factories and six specs.
Rejected: keeping STI and teaching update_or_create_address to preserve the subclass (it fixes the copy path but leaves finding 2, and still buys nothing the owner does not already say).
Consequences: Seller#billing_address= keeps coercing an assigned plain Address with becomes — necessary precisely because rows are indistinguishable without a type. CompanyLocation's addresses stay Spree::Address; if a mandatory company line is wanted there, it belongs on the owner as a validation, not on the address class. Constraint: do not add a type column to spree_addresses without first checking update_or_create_address and Spree::Address.find_duplicate — the copy path and the dedup path are what decide this, not the model hierarchy.
2026-08-22: The tax identifier's owner is polymorphic
Context: Spree::TaxIdentifier carried one nullable FK per owner — customer, company, cart, order — with an exactly_one_owner validator holding the rule together, following the dual-FK convention from the Cart/Order split. The marketplace work added a fifth owner (Seller, per 6.0-multi-vendor-marketplace.md Decision 12), which made the shape hard to defend: five columns, three near-identical per-owner uniqueness validations, and an owner method that was a five-way || chain.
Decision: The table carries owner_type/owner_id. The dual-FK convention was adopted for cases where a polymorphic type string was hiding several different meanings in one table — split-adjustments removing adjustable_type, typed stock movements removing originator_type, each with methods dispatching on the string to tell six things apart. A tax identifier is not that: it is one concept, a tax registration, held by different kinds of party. The exactly-one rule becomes structural — a single FK cannot name two owners, and the owner is required by Rails' belongs_to default (spree/spree#14483 removed Spree::Base's opt-out the same week), the three uniqueness validations collapse into scope: [:owner_type, :owner_id], and a sixth owner costs no migration. Cardinality still varies by owner and is declared owner-side, where it always lived: has_many for customer, company and seller, has_one for cart and order. Because 6.0 is unreleased, the original create_table migration was amended in place rather than layering a conversion migration.
Rejected: keeping five FKs on consistency grounds alone (the convention's rationale does not reach this table); a shared exactly_one_owner concern (it would formalise the workaround rather than remove it).
Consequences: the admin serializer keeps exposing customer_id/cart_id/order_id, deriving them from the owner and reporting each under the name of what it is, so no client changes. readonly?, validatable? and number_changing? — all three meaning "this is the frozen order snapshot" — read one private order_owned? predicate instead of order_id. The completion copy and the seller split drop owner_type/owner_id from their except lists rather than naming four dead columns. The errors.messages.exactly_one_tax_identifier_owner translation is deleted. Specs pass owners as owner:, and the factory gains :on_company/:on_seller traits beside the existing ones.
2026-08-19: A payment settling refreshes the payment side only, through events
Context: Payment#update_order (an after_save callback) wrote payment_total with update_column and called update_statuses! inline, while Carts::RecalculateTotals carried the identical formula and OrderStatusSubscriber was already designated the sole status trigger. Measured with events enabled: one capture recomputed the order four times (callback + payment.updated + payment.completed + payment.captured). None of it was visible to the suite, because Spree::Events.enabled? is false in the test environment — the callback was doing all the work there, so nothing failed.
Decision: The callback is gone (deprecated shell until 7.0). Payment changes reach the order through events only. The subscriber re-sums the payment side alone via a new Spree::Purchase::Totals#refresh_payment_total! (shared by Cart and Order) — deliberately not the full totals workflow, which re-derives item and delivery money and would overwrite figures a caller set; the retired callback's own comment ("a payment settling moves only the payment side of the ledger") was right and an earlier attempt at this ignored it. payment.captured is skipped as the companion of payment.completed. Destruction keeps a dedicated after_destroy: Spree::Payment is not paranoid, so the row is gone when payment.deleted lands and its payload carries no owner — nothing can lead the subscriber back. Carts get the money refresh but no status update (they have no status columns).
Rejected: deduplicating per (order, request) — it silently swallowed the second settlement of a mixed-tender checkout, leaving payment_total at 0; skipping the settling save's own payment.updated — the payload cannot distinguish it from a genuine later edit, and skipping the wrong one leaves the order stale, so two cheap recomputations beat one missed; moving the callback's work into Payments::Create — three of the four payment-creating paths bypass that service.
Consequences: a capture recomputes twice (down from four). Callers must reload before reading payment_total: the subscriber writes through its own instance, so an in-memory copy goes stale — the batch loop's break guard re-reads that one column for this reason. Three latent bugs surfaced once specs ran with events on: the order_ready_to_ship factory produced payment_state: 'paid' with payment_total: 0 (it had relied on the callback), Payment::CustomEvents called order.paid? on cart-owned payments where order is nil, and the break guard read a stale attribute. New specs assert the recomputation count with events: true so a re-added writer fails loudly.
2026-08-18: Payment flows leave the model — workflows implement, shells delegate
Context: After the machine removal, Payments::Capture and Payments::Void were thin wrappers: guards and hooks in the workflow, the actual six-step choreography (capture! — gateway call, lock, recheck, capture event, split, remainder) opaque inside Payment::Processing. Mapping the callers showed the hook contract had holes: dispatch capture (Fulfillment) and order-cancel settlement called the model verbs directly, so a fraud hold on payments.capture.validate vetoed an admin capture but not a dispatch capture, and payment.captured fired for one and not the other. Checkout had no workflow at all. Review also confirmed two TOCTOU races (raised by coderabbit on #14460, verified real and pre-dating the branch — machine guards were in-memory checks over unconditional saves, and the machine allowed completed → processing): a stale instance could resurrect a settled payment and re-drive the gateway, and racing session writers could both pass a transition guard and double-publish.
Decision: Workflows implement the payment flows inline as named steps; the model keeps gateway mechanics only. Payments::Capture absorbs capture! (atomic claim → gateway external_step → locked bookkeeping → remainder re-authorization through Payments::Process), Payments::Void absorbs void_transaction!, and the new Payments::Process (payment_process_workflow, hooks payments.process.*) absorbs process!/authorize!/purchase! with the machine-era preconditions as its leading guard. Every entry point routes through the workflows: checkout batch, dispatch capture, order-cancel settlement. The races close structurally: Payment#started_processing! is now an atomic claim (conditional update_all from live statuses; false when settled concurrently, raises for dead payments — void/invalid only: failed is deliberately claimable (2026-08-19), breaking machine parity, because a failure can be a transient gateway outage and the retry must reuse the row — response_code is unique per order, so a session payment's intent can never move to a fresh payment) and session transitions are a conditional-update compare-and-swap (transition_to) — only the writer whose update moves the row publishes, the loser returning false with no event (a row lock was rejected: with_lock reloads, wiping the session's association cache mid-flow). Model verbs stay as deprecated shells delegating to the workflows until 7.0, a full major rather than the usual one release (2026-08-19) — they have been the public way to move money since Spree 1, every payment extension and host override calls them, and the replacement is a different shape (a workflow result, not a boolean), so migrating is real work rather than a rename; extensions keep working meanwhile, with warnings, and internal code never calls them. Payment#confirm! is deliberately not a workflow: its only caller is PaymentSession#settle_payment!, which runs inside owner.with_lock — where a workflow cannot go (external_step refuses a workflow-opened transaction, halt! raises inside any transaction) — and that lock is what makes settlement exactly-once when the webhook races the synchronous return. It makes no gateway call, so it has no I/O to isolate and nothing to compensate. Supersedes the 2026-08-12 "money movement deliberately stays in the model" position. Refund#perform! is unchanged — Refunds::Create already owned that flow.
Rejected: keeping the verbs real on the model with workflows wrapping them (the hook holes stay open, and every new entry point has to remember which door has the guards); a Payments::Cancel workflow (cancel! is a gateway dispatcher whose refund path already runs through Refunds::Create — no flow of its own, no hook demand); fixing the races inside the model verbs before dissolving them (the same code would move twice).
Consequences: Processing is ~130 lines of mechanics (gateway_options, handle_response, error translation) plus shells; protect_from_connection_error, handle_response, gateway_error, token_based? and split_uncaptured_amount are public mechanics API; order-cancel settlement now skips unvoidable payments (failed/invalid) instead of crashing mid-cancel as the machine-era code did.
2026-08-18: Payment family: state machines removed, state renamed to status
Context: 6.0-normalize-state-to-status.md listed Payment as a plain column rename with the machine kept (state_machine :status). Reviewing the new payments workflows (Capture, Void, Refunds::Create, PaymentSessions::Complete, HandleWebhook) showed the machine had become residue: guards were duplicated between workflow steps and the transition graph, events published from two different layers (payment.captured from the workflow, payment.completed from an after_transition that fires inside capture!'s lock), and the actual transitions hid behind send("#{success_state}!"). Order and Fulfillment had already answered this question.
Decision: Remove the machines from Spree::Payment, Spree::PaymentSession and Spree::PaymentSetupSession in the same change as the Payment column rename. Payment joins Spree::HasStatus; transitions are explicit named writes in Payment::Processing and the payments workflows, publishing payment.completed/payment.voided at the write. The two session models (identical machines) share a Spree::PaymentSessionTransitions concern whose non-raising guarded transitions preserve the non-bang event semantics the racing webhook/synchronous paths rely on. has_status now applies its default: as an ActiveModel attribute default (no callbacks — also removed Fulfillment's and Seller's after_initialize) and refuses to shadow methods Rails already defines (Payment's invalid vs ActiveModel#invalid?). Bridges until 6.1: state/state=, has_invalid_state?, with_state, INVALID_STATES, ransack state alias.
Rejected: keeping the machine with a renamed column (two sources of truth for the transition graph, callbacks still firing side effects inside locks); non-bang event shells on Payment (the machine is gone — Order precedent is wholesale removal, and all callers were internal); a generic transition-validation layer in HasStatus (a state machine by another name — the concern's docs already rule it out).
Consequences: an illegal direct status write no longer raises — the workflows are the transitions, which is the accepted trade across the family. InventoryUnit and GiftCard remain the last state columns and follow the same rename+removal doctrine when they move.
2026-08-16: A vendor's status is something that happened to it, not a field you set
Damian asked for vendor management with "invitation, approvals, all in workflows". Recording why the API refuses the obvious shortcut.
The shortcut we did not take. A status in permitted_params would have
made the whole lifecycle one endpoint. It is also how the transitions stop
meaning anything: approving a vendor sends mail, provisions payouts and is the
moment extensions want to hook — none of which happens when the value arrives
by mass assignment. So each move is its own workflow (Spree::Vendors::Invite,
Approve, Suspend, Reject), reached through its own member action, and
status is simply not writable. Consistent with returns and claims, which
already ship this way.
The guards admit more than the happy path, because the interesting moves
are the ones back. Approve lifts a suspension and revives a rejected
applicant, and it clears holiday mode on the way — a vendor coming back is
coming back to sell, and leaving them invisible would look like the approval
had not worked. Suspend and Reject are not synonyms: suspension is for a
vendor already trading and can be undone; rejection is for one that never did.
Rejecting an approved vendor is refused rather than quietly aliased, because
the two say different things to the person on the other end.
Reasons live in metadata, not columns. A suspension reason is a note about one event; the next suspension has its own. A column would hold only the most recent and read as though it described the vendor.
Creating a vendor is not a transition, so it stays plain CRUD and the
default status is applied in an after_initialize, following
Spree::Fulfillment. Only the moves are workflows.
Managing sellers is staff-only. read_vendors/write_vendors are not
offered to the vendor audience: a seller administering other sellers is the one
thing that key must never allow.
2026-08-16: Several sellers share a product by sharing it — the seller is on the variant, not on an offer record
Damian's call, after a survey of how marketplace platforms model a shared catalog and an audit of what it would cost Spree.
The gap. The marketplace plan assumed one product, one seller. Two sellers of the same book produced two unrelated products and two listings. That suits unique goods and fails commodities, and it is the capability the legacy module was most often asked for and could never provide.
Why not an offer record. Every surveyed implementation introduces one, and
every one of them is built on top of a commerce engine or a merchant's existing
catalog — they cannot put a seller on the variant and cannot re-key inventory.
Their offer is a variant they were not permitted to write. We own the variant.
An offer here would duplicate its seller, sku, price, stock, condition and
delivery config, and would cost a second pricing pipeline, a stock-anchor
migration (stock items are uniquely keyed on (variant, stock_location)), a
new line-item FK with the cart's variant-keyed deduplication reworked around
it, and offer-relative rewrites of the purchasability predicates. Putting the
seller on the variant makes all of that true by construction: two sellers are
two variant rows, so two stock rows; prices resolve unchanged; and the line
item already reaches the seller through the variant it points at — which is
exactly what the order split partitions on.
"Offer" survives as storefront vocabulary. Presentation need not be a table.
Condition is an OptionType, so it splits the variant like any other axis and inherits the option machinery. That also makes the buy box key on the option combination, giving the industry's separate new/used featured offers without a second mechanism.
An audit found four things that must ship with it, three of which are
pre-existing faults the change would expose rather than create: Product#variants=
destroys variants absent from the payload, so removal must be filtered to the
writer's own or a narrower read would make the write destructive; delivery
profile is product-level and memoised per product, so sellers would share
whichever profile resolved first (fixed by a variant-level override, which
follows Variant#tax_category exactly and is worth having for plain merchants);
option filtering matches each option type independently against the product, so
"Blue AND XL" already matches a product with no Blue XL variant; and product
rollups become buy-box-relative, which is what makes them correct again rather
than a change of meaning.
Operators see every seller's variants — they run the marketplace. Seller
isolation is the vendor API branch scope-fetching through current_vendor
(Decision 10), not a narrowing of the admin surface.
Catalog matching stays out of core. Deciding two submissions are the same item is hard enough that several platforms sell it separately. Core ships exact matching on a typed identifier, with the namespace stored rather than inferred from the value's shape; fuzzy matching is an extension.
Supersedes the plan's "SKU uniqueness relaxes to per-vendor scope" line, which assumed duplicate product rows per seller.
2026-08-16: Grant audiences are a vocabulary, not a vendor flag
Phase 0 of 6.0-multi-vendor-marketplace.md. Damian's call, after
re-examining the vendor principal question against a primary-source read of a
leading open-source marketplace platform.
The principal decision stands, and the survey explains why it differs
elsewhere. The surveyed platform separates credential from principal: a
standalone identity record holds the password, and it points at either an
operator principal or a seller principal, with the token naming which one is
acting. Spree has no such split — Spree::AdminUser is the credential
(has_secure_password, lockout, password policy, reset tokens, SSO identity
linking). Reproducing that shape means either a second copy of the whole auth
stack or rebuilding the shipped one. So Decision 10 holds: one AdminUser,
several hats, the surface distinguished by JWT audience. Worth noting the
convergence — that platform's per-request seller header and its token-level
actor tagging are the same two mechanisms Decision 10 specifies.
Where the boolean was wrong. The first cut marked catalog resources with
vendor_grantable: true. But Role#audience is already a string vocabulary
(staff | vendor), and the B2B plan anticipates company roles as a separate
future system — so the catalog would have needed a second boolean the moment a
third panel appeared, then a third. The catalog now carries audiences: — the
audiences beyond staff a resource opens up, staff being the implicit
baseline every resource grants — and grantable_keys(audience) replaces the
vendor-specific reader. An unregistered audience returns an empty set rather
than raising, so a panel that does not exist yet reads as granting nothing.
The vocabulary itself stays a constant on Spree::Role rather than a
registry: a third audience is a one-line change, and nothing has asked to
register one from outside.
Audience is immutable once a role exists, since flipping it would
re-point every existing assignment at the other panel, and a non-staff role
may only hold keys its audience is granted — so settings/staff/api_keys
cannot reach a seller even through a hand-written seed.
2026-08-15: Country-derived store defaults are born from the merchant's answer, not seeded and rewritten
Amends the 2026-08-13 first-run setup entry. Damian's call, after
verifying against a live database that the setup endpoint's country_code
parameter silently did nothing.
The seed can only guess a country, and the guess leaks. Four seeds bake
US/USD in: the bootstrap market, the default stock location's country, the
Domestic/International delivery zones with their flat rates, and the pickup
method's calculator currency. Worse, Store#default_country_code= only
reaches the market through after_create — on a store that already has a
market it writes a dead column and store.default_country_code keeps
answering US, because the readers delegate to the market and the
after_update sync copies locale and currency only. So a merchant who
submitted country_code: DE at setup got a store still named "United
States", their own buyers routed to the International rate, and a domestic
flat rate priced in dollars.
Decision: one provisioning service, two callers, seeds stop guessing.
Spree::Stores::ProvisionDefaults.call(store:, country:, locale:) updates
the bootstrap market in place (the sample_data/markets.rb shape) and
creates the warehouse, zones, methods and pickup method in the right country
and currency; Seeds::All no longer runs StockLocations, DeliveryZones
or PickupDelivery (deleted, absorbed). The setup endpoint calls it inside
its store lock; Seeds::AdminUser's env-credential branch calls it with
STORE_COUNTRY/STORE_LOCALE (defaults US/en), so CI, worktrees and e2e
are unchanged while scripted non-US installs stop being US-shaped.
Rewriting the seeded rows after the fact was the first sketch and was
rejected: every rewrite step that gets missed leaves stale "Domestic =
United States" data behind, whereas rows created from the answer cannot be
stale. A bare db:seed without credentials now yields a store with no
warehouse, zones or pickup until setup runs — correct, since nobody has said
where the shop is.
Setup asks for country, locale and currency, each defaulted from the
country. The countries gem gives currency and official languages per
country — the derivation ensure_default_market already used — so
country_code becomes required and both locale and currency default
from it. All three are editable: a first cut made currency read-only and
preselected English regardless of country, and both were wrong in the same
way — the form asked a question and then ignored the answer. Shipping from
Warsaw while pricing in euros, or running a Polish store in English, are
ordinary. Unknown currency is now a pre-token-spend 422 rather than
silently ignored. Locale options are the country's official languages
filtered to those Spree actually translates (Switzerland loses Romansh),
plus English; installs without spree_i18n skip the filter, since otherwise
every country would collapse to English. Country data comes from a new unauthenticated
GET auth/setup/countries guarded like the setup endpoint; folding it into
the status endpoint (polled by the login page) and a static SDK map (a
second source of truth) were both rejected.
Sample data builds around the default market, never resets it.
sample_data/markets.rb forced the default market back to US+CA/USD/en,
which would flip a German store to a US store on spree:load_sample_data;
it now reads what exists and creates the zones fulfillment.rb aborted
without.
Constraint for everyone: a store's country changes through its market,
never Store#default_country_code=; a new seed that depends on country or
currency goes into ProvisionDefaults, not Seeds::All; the service keeps
exactly two callers — wired to a settings page it becomes a data reset.
2026-08-14: ZoneRule retired by migration; Zone shelled to a migration-only reader
Two amendments to the 2026-08-12 jurisdiction-as-codes entry, both Damian's call, finishing what "kept because it is persisted in the type column" left hanging.
PriceRules::ZoneRule is retired — onto MarketRule, with no replacement
class. Markets are how pricing targets geography, so spree:migrate_tax_zones
converts each zone rule to a MarketRule where the zone's countries exactly
match one of the store's markets — the one mapping that provably keeps the
same buyers on the same prices. Where no market matches, the restriction is
unrepresentable: the price list is deactivated, the rule row removed, and
the task reports each list with the ISO codes it named so the merchant can
create the market and rebuild. Deactivating errs on buyers briefly losing a
discount over a restricted list quietly widening to everyone. A CountryRule
carrier class was written and then rejected the same day — it preserved data
at the cost of a second, half-alive geography concept beside markets.
ZoneRule survives as a bare STI shell (rows keep the old type until the task
runs; a 6.0 deployment boots before its upgrade tasks do), deleted in 6.1.
Spree::Zone and ZoneMember are shells. Bare ActiveRecord — the
associations plus a country_list — kept solely so the 5.6→6.0 upgrade tasks
(migrate_tax_zones, migrate_zones_to_delivery_zones,
backfill_order_markets) can read the rows they convert. Everything else
went: the matching/inclusion logic, seeds (Seeds::Zones and its EU_VAT
groupings — the markets sample data now names its ISO lists directly), the
permission-catalog entries, Country/State's zone associations, and Store's
checkout_zone bridge (deprecated since 5.4 with a 5.5 deadline, two
releases overdue). 6.0-delivery-zones.md still owns dropping the classes
and tables in 6.1; what remains for it is deletion, not untangling.
2026-08-13: Stock leaves the shelf at fulfillment, not at order placement
Spree has always decremented count_on_hand when an order is placed, so a
warehouse's on-hand number in Spree never matched what a picker could count,
and the one event a warehouse cares about — the parcel leaving — wrote nothing
to the stock ledger at all. Typed Stock Movements splits the two: placement
writes an allocated movement that raises allocated_count and leaves
count_on_hand untouched, and dispatch writes a shipped movement that
decrements count_on_hand and retires the allocation with it. On-hand becomes what is on the shelf and
StockLevel#allocated_count carries what is promised, which is the model every
other commerce platform ships.
Three consequences worth naming, because they change existing behavior rather
than adding to it. Oversell is now allocated_count > count_on_hand instead of
a negative count_on_hand — the same signed arithmetic, so backorder_limit
and pre-orders are untouched, but restock_backordered and the movement's
min_quantity guard both existed only to service the negative representation
and are deleted with it. Availability must be read through
Stock::Quantifier / available_count everywhere, since a raw count_on_hand
read now offers units already promised to another customer. And allocation is
keyed to the fulfillment, not the line item: the fulfillment already owns
the origin location and the on-hand/backordered split, so allocating anywhere
else would re-decide what the Coordinator already decided.
Shipping only ever converts an allocation, which is also how the upgrade stays
safe: a fulfillment carrying no allocation is one created before the upgrade,
whose units already left under the old rules, so it ships without a movement
and its stock is never decremented twice. The manifest task reconciles the open
fulfillments it finds — on-hand and allocated_count move up together, leaving
availability unchanged by construction.
Plan: 6.0-typed-stock-movements.md (phases reordered the same day: model
update before the data task, and the polymorphic originator drop held to 6.1
like every other 6.0 cleanup, since the task reads those columns). Consumers:
6.0-stock-reservations.md (the reservation term in the same formula),
6.0-inventory-operations.md (transfers, purchase orders, history screens).
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-09-07: N+1 tripwire — every API request in the suite is scanned for repeated queries
Lazy preloading on list collections already batches association reads, so
the N+1s Spree still ships are per-record model queries a serializer
reaches: a stock check, a price lookup, a count, a derived number. Rails'
strict loading cannot see those (it watches association loading, which the
lazy preloader satisfies first), so the net is Prosopite, which fingerprints
the SQL a request ran and reports a statement repeated from one call site.
This repository's dummy app hooks a scan around every v3 request and raises
on a report. The hook lives in the dummy app's test.rb, not in the shipped
controller, so a host application that bundles Prosopite for its own use is
never opted into Spree's guard. Statements issued while a record is
validated, saved, locked, destroyed or committed are not reported: writes
run their callbacks one record at a time by design (a dependent: :destroy
cascade, a uniqueness or number probe per created row), and the guard
exists for what a request reads. The few workflows that write one record
per requested row — a cart's lines, a split checkout's seller orders, a
payout per currency, a product payload's nested variants — are named in
the same allow list, each with its reason.
Two traps are worth naming, because both make the guard lie. Prosopite
fingerprints through pg_query, which cannot parse SQLite's ? binds, so
SQLite borrows the text normalizer written for MySQL — and that normalizer
blanks anything double-quoted, which is a string literal in MySQL but an
identifier in SQLite. Left alone it erases every table name, so unrelated
queries share one fingerprint and a single record's distinct associations
report as an N+1; re-quoting identifiers as backticks first fixes it, and
it accounted for more than half of the first run's failures. The second
has no fix at the guard: two associations on one table — an order's billing and shipping address, a category's image and square image —
are indistinguishable from a repeat in the SQL alone. Telling them apart by
the row each lookup asks for was tried and abandoned, because a genuine
belongs_to N+1 also fetches a different row every time, so the same rule
hid the commonest N+1 there is. The guard therefore reports these, and the
fix is to preload the pair at the render site; a review of this change
caught the earlier attempt.
No endpoint is exempt. Turning it on, with the fingerprinting corrected, left 63 API spec files with a repeated query; they were fixed in the same change rather than parked on a list that logs instead of failing, because a file on such a list hides every new repeat added to its endpoints too.
Products, categories and collections were then taken first, as the
highest-traffic surfaces. Every listing and detail endpoint across the
three is now clean; what remains on them is write-path work, where a query
per record created is inherent. The fixes worth naming are structural: a
category's product counts and its ancestor chain each collapse to one
query using the nested set's own lft/rgt bounds rather than a query per
node; the storefront's category filter sidebar costs one query instead of
two per child; counter-cache recounts across a bulk assignment are grouped
rather than reset_counters per record; and bulk tagging reads the tags it
needs once. A category's breadcrumb trail now preloads the images it
renders.
The shape behind most of them: a model method that reads a loaded
association when one happens to be loaded and runs a scoped query when it
is not, which on a list means a query per row. Prices, store credit,
publications, confirmation checks and the cart's delivery-address question
all had it. Cart writes were the worst case — price queries scaled at three
per line item, so a five-line cart cost fifteen — because a cart built one
item at a time has no relation to batch from; registering the resolved
variants as one preload context makes it flat. Two candidates were reverted
after the core suite caught them: category_and_ancestors is memoized, so
calling it from a callback poisons later reads, and the line-item finder
must re-query because callers add lines behind its back. Two conventions
follow. A repeated query is fixed at the line the report names — the association goes into
collection_includes, or the model reads a loaded association instead of
running a scoped query per record (read_association_in_memory?) — never
by widening the allow list. And a
list endpoint's spec renders at least two records, since a repeated
statement cannot show with one.
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. Coverage follows the store context
rather than the entry point (extended 2026-08-14): declaring a store through
Spree::Current#store= arms the guard for that unit of work, so jobs,
webhook controllers and console scripts are watched without registering
each one, while work that never declares a store stays unguarded — reading
the default store through the fallback is not a scoping claim worth
checking. 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 — Code review findings on the payment surface, and what they corrected
The review of the day's work surfaced ten findings; all ten held up. The ones that correct earlier entries in this log:
- Profile creation had become dead code. The after_save removal documented
"creation flows call this explicitly" with no flow calling it. Now they do:
Payments::Createprofiles after its transaction, the admin payment endpoint after its lock (a source that cannot be profiled destroys the half-created payment, matching the old rollback), and specs that create payments programmatically call it themselves. - The webhook path settled with cold provider caches — up to three Stripe
round trips inside the order lock, contradicting settle_payment!'s own
comment.
PaymentSession#prepare_for_settlement!(no-op default; Stripe warms intent, charge and gateway customer) runs before HandleWebhook's lock, making the comment true. - capture! completed before splitting, so a partial capture published payment.completed at the full amount. The split's row work now happens inside the lock before complete; only the remainder's authorize runs after.
- settle_payment!'s completed? guard read a stale cached payment — the same check-then-act shape one level down. Closed with a DB-state recheck inside the lock, not a reload (reload discards skip_source_requirement, as it discards card numbers in capture!).
- The completion fence broke reads: GET /carts/:id runs Checkout::Advance
under with_order_lock and answered 409 for the claim window. The advance
now skips claimed carts (
Cart#completion_claimed?, which owns the TTL). - Store scoping and correctness details: refund reasons resolve through
current_store.refund_reasons; Stripe's cancel passes the store to order_canceled_reason; the customer payload sends ISO codes like the shipping payload; setup_intent.succeeded left SUPPORTED_EVENTS until core's webhook contract can route setup sessions.
2026-08-12 — Amount consistency during gateway operations: the completion claim, not a lock
Raised as a challenge to the lock removals: shouldn't the order be locked for the whole gateway operation, so it cannot be mutated into a different total than the one sent to the gateway? The invariant is right; the mechanism cannot be. For session gateways the charge happens client-side before any server endpoint runs — no server lock reaches it. And a row lock spanning a gateway timeout pins a database connection per in-flight payment; a provider brownout turns that into pool exhaustion for the whole store, not one order.
What actually enforces the invariant is Carts::Complete's three layers:
totals recalculated inside the cart's row lock at PREPARE ("not trusted
from earlier requests") and checked against the client's expected_total; the
completing claim stamped before the lock releases; payment coverage
re-verified at FINALIZE, with the Y3 undo popping payments back to the cart
when it fails.
The challenge found a real hole in layer two: the claim was only consulted by
guard_concurrent_completion — it blocked a second completion, but nothing
blocked a mutation during the unlocked gateway window. An AddItem landing
there changed the cart under a completion whose totals were fixed at PREPARE.
Now with_order_lock — the funnel every store cart mutation passes through —
refuses mutations while a fresh claim holds the cart (409
completion_in_progress), checked after acquiring the row lock so it cannot
race the claim being written, with the same TTL as the completion guard so a
crashed completion never bricks its cart.
Consequences: third-party gateway authors rely on four guarantees, none of which is "the order is locked while you talk to your provider": the amount is fixed in the session/intent and synced on update; mutations are excluded during the completion window by the claim; completion re-verifies coverage and compensates; settlement and capture bookkeeping serialize on row locks.
2026-08-12 — Payment lock audit: locks live where money is recorded, never around gateway I/O
A sweep of every payment operation with the settle_payment! lens — check-then-act on money state without mutual exclusion — after the with_order_lock removals. The rule that came out: the row lock wraps the money bookkeeping with an in-lock recheck; the gateway call runs before it, unlocked, relying on provider idempotency.
Two real bugs found and fixed:
Payment#capture!wrote the capture event beforehandle_response. A concurrent second capture passed the completed? check, hit the gateway (idempotent at Stripe), persisted a second capture event, then exploded oncomplete!— doubled captured_amount plus an ungraceful error. Now: gateway first, then bookkeeping underowner.with_lockwith a DB-state recheck (deliberately not a reload — card numbers never persist, andsplit_uncaptured_amountauthorizes the remainder at the gateway, so it stays outside the lock). A declined response also no longer leaves a phantom capture event, and its failure transition runs outside the lock so the raise cannot roll it back.- Refund balance validation was unserialized. Two concurrent partial
refunds both validated against the pre-refund balance and both credited —
a double-clicked 50% refund refunded 100% (Stripe's credit carries no
idempotency key). The refund row is what reserves the balance
(credit_allowed sums rows), so creation takes
payment.with_lockin one place:Refunds::Create, which the returns/exchange/claim drain loops and Stripe's cancel verb all route through (code review caught the first version duplicating the lock/credit/compensation sequence at five sites — which also meant refund hooks and payment.refunded fired only for admin refunds).perform!stays outside the lock.
Judged acceptable, with reasons on record:
- Double void — no capture events involved; the second void gets the gateway's "already canceled" as a clean failure.
- Concurrent
process_payments!— the gateway is deduped by the per-payment idempotency key, and the loser'scomplete!raises before its capture-event line, so money math survives; the error is ungraceful. An atomic claim (compare-and-swap on the state column) would make replays graceful — follow-up, not urgent. - Session create/update endpoints still hold with_order_lock across Stripe intent calls — the same smell the confirm endpoint shed, but fixing it means restructuring gateway-owned code (persist the session row under a short lock after the intent call). Flagged as follow-up.
2026-08-12 — The payment lifecycle routes through its workflows; refund creation owns the credit
An audit found the two payment workflows were dead code: Payments::Capture
and Payments::Refund existed with hooks, but the admin API called
payment.capture! and Refund.create directly — inside with_order_lock, a
row lock held across gateway round trips — and Refund#after_create :perform!
fired the gateway credit from a save callback, the exact shape the workflow
doctrine prohibits. The boundary the plan says workflows own was owned by
controllers.
Five changes close the gap:
Refunds::Create(renamed fromPayments::Refund, keyrefund_create_workflow, before any release of the old key) owns refund creation end to end. Theafter_createis gone: the row commits, then the credit runs as an explicitexternal_stepvia a now-publicRefund#perform!(idempotent — a present transaction_id is a no-op). A cleanly declined credit destroys the uncredited row, becausecredit_allowedsums every refund row and a dangling one would block the retry; a crash between commit and credit leaves the row for reconciliation. Returns, exchanges, claims and Stripe's cancel verb callperform!explicitly from their own external steps.Payments::Voidexists (mirror of Capture) and the admin void endpoint routes through it; capture routes throughPayments::Capture. Neither wraps inwith_order_lock— replays are idempotent successes.PaymentSessions::Completeis the synchronous twin ofHandleWebhook: same settlement throughsettle_payment!, plus the one veto point the sync path lacked (validatebefore money is recorded — the webhook path deliberately has none, money that moved cannot be rejected).settle_payment!itself takes the owner's row lock around the local settlement — the completed? guard alone is check-then-act, and two concurrent settlements would each record a capture event. The lock never spans gateway I/O (Stripe memoizes the intent and charge before settling; the webhook path's outer lock nests reentrantly), which is the difference between this and the controller-level with_order_lock it replaced.create_payment_profileleft its save callback and became an explicit call. No subscriber replaced it — a first attempt proved why: the card number never persists, so profile creation only works on the in-memory instance the creation flow holds, and an observer that reloads the payment can never do it. Creation flows that take raw card data callpayment.create_payment_profileafter the commit; session gateways store profile ids during source creation and never call it. Row save alone no longer talks to a gateway.process_payments!dropped itswith_lockaround the gateway loop; re-entry is guarded bystarted_processing!and the per-payment gateway idempotency key.
Consequences: hook keys refunds.create.*, payments.void.* and
payment_sessions.complete.* are public API from 6.0. Controllers never wrap
gateway-calling workflows in with_order_lock. Anything creating a
Spree::Refund row must either call Refund#perform! from an external step
or accept an uncredited row — creation alone no longer moves money.
2026-08-12 — Providers never decorate core models; risk codes become a gateway interface
The Stripe provider shipped with three decorators on core models, and all three
are gone. A decorator is the extension mechanism of last resort — a first-party
provider using them licenses every third-party gateway to do the same, and a
before_save on Spree::Payment firing forever for one provider's bookkeeping
is exactly the shape that rots.
What replaced them decides the pattern for Adyen and every gateway after it:
- AVS/CVV risk codes are a core interface. The session flow never passes
through the gateway response path that normally sets
avs_response/cvv_response_code— the check results live on the payment source, in whatever shape the provider recorded them. Core now asks:PaymentMethod#risk_codes_for(source)(nil by default), called byPaymentonce at creation, response-path codes winning. Stripe's implementation translates its pass/fail/unchecked checks from the source's metadata. Core owns when to ask; the gateway owns how to answer. The old callback re-ran on every save; the hook runs at creation only — the sole lost case is a payment gaining a Stripe card source after creation, which nothing does. - Provider-scoped gateway customers are a core scope.
GatewayCustomer.for_provider(SpreeStripe::Gateway)replaces the decorated.stripescope; every gateway needs exactly this filter. - The rest was dead or sugar. The
.stripe/stripe?payment-method decorator had no callers left.store_accessor :metadata, :stripe_charge_idwas sugar over a hash write, so the service writespayment.metadata['stripe_charge_id']directly.
Consequences: the provider ships zero decorators and the engine's
to_prepare decorator glob is gone. A provider needing something from a core
model proposes a core interface, mirroring how delivery providers already work
(Spree.delivery_rate_providers, Spree.fulfillment_providers).
2026-08-13: Validate hooks are the validation extension surface; no generic model-validation registry
New plan 6.0-extendable-validations.md. The question was whether developers
customizing validations — the single most common core-model modification —
deserve a generic add/remove validation mechanism, or whether workflow
validate hooks plus the existing model-level knobs already are the answer.
Decision: the latter. Adding a rule via prepended decorator is already short
and Rails-native; removing one via registry would require repackaging every
core validation as a named unit, and no competitor ships anything comparable.
Relaxing a core rule stays on named store preferences
(disable_sku_validation pattern) or predicate overrides.
What ships instead is the work that makes the hook recommendation honest:
Carts::UpsertItemsgraduates to the workflow tier and absorbs every non-increment item mutation (bulk payloads, PATCH quantity, DELETE item — quantity0removes). It firesvalidateper item withAddItem-compatible readers, shares the item-application steps withAddItem(whose per-item full recalculate is what made N-item adds slow — the batch recalculates once), and is partial-success on the storefront: a per-item rejection skips the item onto the cart's existingwarningsarray on a 2xx response rather than rolling back the batch. The order-side twin fails the whole batch — a merchant's struck-out row silently not applying is worse than a failed request. No whole-batch veto in 6.0.SetQuantity/RemoveLineItembecome deprecated shells.Products::Create/Update/Destroybecome workflows (real orchestration, not the plain CRUD the doctrine rejects) with all write paths routed through them — Admin API v3, CSV importer, seeds — so hooks always fire. Variants ride the product graph; no standalone variant workflow.- Rejections carry
ActiveModel::Errors.Workflow#errors+ argument-lessreject!render throughrender_validation_error, so extension rejections share the model-422 shape (field-scoped symbolic codes) instead of a flat message under a controller-hardcoded wrong code.reject!(message)bridges to:base. - Address and cart creation get no workflow — plain CRUD, demand already
served (store preferences, gating predicates,
Spree.validators.addresseswhich finally gets docs + a removal API + arequire_companypreference; flow-level address policy belongs oncarts.complete.validate). - Custom-field value validation deferred to its own plan: Shopify-style
per-definition length/range/regex/allowed-values, enforced in the
CustomFieldmodel, gating new writes only. The 2026-08-06 "required stays advisory" constraint is untouched.
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: Provider-backed digital assets ship in 6.0 as wave 6 of the digital-assets plan
Plan: 6.0-digital-assets.md wave 6. No kind column — the provider is the
discriminator. Every asset always has a provider; an uploaded file is just the
default one (Spree::DigitalAssetProvider::File). A single nullable provider_type
class-name string: blank resolves to File, a class name to that provider —
exactly how DeliveryMethod#provider_class works (fulfillment_provider.presence || DEFAULT). A separate kind string would be redundant with provider_type,
and the download flow calls provider.deliver with no branch. The things that
genuinely differ by type — record validation, the file-metadata columns, the
admin create form — key off the provider class, which declares requires_attachment?.
No Spree::Integration binding (deliberately unlike delivery-rate/tax
providers). Those resolve credentials through a store integration because they
connect to marketplace services (EasyPost, Avalara) a merchant self-connects.
A digital-asset provider here is bespoke glue into one company's internal/legacy
software, written once in the host app — so it owns its own configuration (env
var, endpoint, credential) and Spree imposes no integration abstraction. No
integration_id column, no requires_integration?, no integration picker.
DigitalAsset#download_url generalizes to deliver, returning a
Spree::DigitalDelivery value object carrying EITHER a redirect_url (302, as
today) OR an inline_value + content_type (a 200 body — a license key to
show, not a link to follow). Registered via Spree.digital_asset_providers;
core ships only the File provider.
Why 6.0 and not 6.1: the first prospective customer is a licensing business
whose products are entitlements granted by their own system, not files, and they
want to launch on 6.0. The 6.0 model was built for this — the download flow
already routes through downloadable?/download_url and the controller already
redirects allow_other_host: true — so it is a provider_type column plus a
small strategy, not a rewrite.
Decisions: provider-as-discriminator, no kind column (initial sketch had
one; dropped as redundant); no Integration credential surface (the provider is
internal glue, not a marketplace connector — it self-configures); only the File
provider in core (seam + authoring docs, like delivery-rate/tax providers began —
the licensing provider lives in the host app); external_url deferred and needs
no schema when wanted (just another provider class); link-per-unit with
resolve-on-download (no on_fulfillment hook, whose failure would land after
money is taken); a provider exception is caught and returns the existing 403
without spending the click.
Consequences: nothing outside DigitalAsset may assume an attachment is
present — reach for deliver/downloadable?. Download-flow code treats the
deliverable as opaque. The store download endpoint now has two response shapes
(302 or a 200 body); a storefront consuming the token URL must handle both. Do
NOT add an Integration FK or credential surface to DigitalAsset.
2026-08-12: License-code pools ship in 6.0 (open source) as wave 7 of the digital-assets plan
Plan: 6.0-digital-assets.md wave 7. The open-source "sell game keys / gift
codes" feature: a merchant CSV-imports a finite batch of codes and Spree hands
one out per purchase. Built as a LicensePool provider on the wave-6 seam,
so it reuses deliver / Spree::DigitalDelivery whole — including the text
(inline value) vs image (redirect) split, which is exactly what code selling
needs (a key string, or a scan/photo of a card). Unlike the wave-6 licensing
provider, this ships in core: it needs no external system, Spree owns the codes.
Model: spree_license_codes — belongs_to :digital_asset, a value string
OR an attached scan, and a nullable digital_link_id that IS the redeemed
state (null = available, set = redeemed by that purchase's link). "Remaining" is
one query; "who got it" is the link's order. No separate flag.
Decisions: claim-once-pin-to-link — the first authorized download claims a
code and pins it to the link, every later view re-shows the SAME code (the click
limit caps views, never burns a second code); this forks the download flow from
the file case and is the behaviour most worth testing. CSV import reuses
Spree::Import (a LicenseCodesRowProcessor), text codes only — images can't
ride a CSV row and upload individually. Pool count IS the variant's stock
(the sharpest decision): a pool variant tracks inventory with count_on_hand
synced to codes.available.count, so the existing can_supply?/add-to-cart path
makes it sell out and forbids the "paid but got no code" oversell — no new
checkout code. This is a real integration with Stock::Quantifier (a digital
variant returns INFINITY on-hand today; a pool variant must return its finite
code count), not a flag.
Consequences: keep count_on_hand and the unredeemed-code count in sync
transactionally on both import and redeem — a drift blocks sellable stock or
permits an oversell; never compute one from the other lazily in the checkout
path. The stock sync is the one delicate piece of wave 7 and lands with its own
tests. Wave 7 depends on wave 6 (the provider seam + DigitalDelivery), so it
is built after it.
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 only then is the parcel fulfilled. The fulfill workflow used to invert that: status flipped and the shipped email queued first, the label bought after, which meant the merchant could not print a label without telling the customer the parcel had shipped, the email raced the label purchase for its tracking number, and a failed purchase surfaced only after the customer heard.
Two changes. Fulfillments::PurchaseLabel is the explicit pre-ship step:
buys the checkout-quoted rate through the provider, attaches tracking and the
label document, leaves the status untouched and sends nothing — and fails
loudly, because nothing has left the building yet. And Fulfillments::Fulfill
reordered its internals to split → buy label (external step) → mark fulfilled,
so the fulfilled event always sees the provider's tracking number; a label
failure there still degrades to "no label yet" per the provider doctrine,
since a carrier outage must never stop a merchant recording a parcel that
physically left.
Two contracts changed with it: providers must make create_fulfillment
idempotent (a label bought in the explicit step is returned, not re-bought,
when fulfill later runs), declared via FulfillmentProvider.generates_labels?;
and a failure after a partial-fulfillment split no longer rolls the split
back — a label may already be bought for the split parcel, and rolling the
parcel away would orphan a paid label. The split survives unfulfilled and a
retry picks it up.
Packing slips are the platform's document, not the carrier's — generated
client-side from data the order screen already holds, no prices, no admin
shell around them. Plan: 6.0-fulfillment-and-delivery.md.
2026-08-11: One tracking number per fulfillment; multiple trackings deferred to 6.1
A fulfillment carries exactly one tracking number, one carrier and one carrier
lifecycle. When a shipment physically diverges into parcels, the answer is the
split flow the partial-fulfillment work already provides: each parcel becomes
its own fulfillment with its own items, status, tracking and delivered_at.
That is strictly more expressive than a list of tracking numbers on one
record — a bare list cannot say which items are in the box that bounced, and
delivery becomes all-or-nothing across the list.
What a separate tracking model would add is the narrower case: one logical
shipment in several boxes the merchant does not want to manage as separate
fulfillments (furniture in three cartons, a pallet of mixed packages).
Deferred to 6.1, deliberately after the carrier-axis work landed, because the
cost is now clear: tracking_status, estimated_delivery_at, delivered_at
and webhook matching all live on the fulfillment, and a
spree_fulfillment_trackings row would have to absorb that whole axis —
per-parcel carrier status, webhooks matched to a row, the fulfillment
delivered only when every row is — plus deprecation bridges for the
fulfillment-level columns that are public API since 6.0.
Design constraint recorded for whoever builds it: the tracking row takes the
entire carrier axis with it. Splitting the axis across fulfillment and
tracking rows — status here, delivered_at there — recreates the two-sources
problem the 6.0 status rework just removed.
Plan: 6.0-fulfillment-and-delivery.md (Phase 6, resolved question 15).
2026-08-11: Fulfillment status model — two axes, delivered first-class, machine removed (supersedes part of 2026-08-10)
Fulfillment#status collapses to unfulfilled → fulfilled → delivered plus
canceled, plain string via HasStatus, state machine deleted. pending and
ready were payment and stock facts wearing a fulfillment costume —
determine_state re-derived them from order.paid? on every recalculation, so
a refund flipped a fulfillment's status with no physical change, and merchants
never understood them. That gating becomes a validate guard in
Fulfillments::Fulfill (rejects with a reason, staff-overridable).
ready_for_pickup dies as a status: pickup fulfilled means "ready at the
counter", delivered means picked up, presentation is modality-aware.
delivered is the new terminal state — confirmed receipt, the thing merchants
kept asking for (the lifecycle used to end at handover). Set by carrier
tracking, a staff button, or later customer confirmation, via
Fulfillments::MarkDelivered (delivered_at, fulfillment.delivered event).
The returns eligibility window and the EU 14-day withdrawal period anchor on
delivered_at.
Carrier truth is a second axis, data not a machine: tracking_status +
tracking_details + estimated_delivery_at, overwritten per update
(pre_transit … delivered, return_to_sender, failure), written by
Fulfillments::UpdateTracking. Bounces and failed attempts surface there
without mutating status. The EasyPost gem feeds it from tracker webhooks —
every purchased label already has a tracker whose updates were being thrown
away; trackers for hand-entered numbers cost money each, so opt-in.
This supersedes the 2026-08-10 "the dangerous callbacks move, the machine
stays" conclusion: with pending/ready gone the machine held two transitions
and its event publishes, which is what HasStatus + workflows already do for
Return/Exchange/Claim. The side-effect relocation stands and made removal
cheap. The FulfillmentItem machine and the other machines (Payment,
ReturnAuthorization, GiftCard) are unaffected. Status mapping for existing
rows: pending|ready → unfulfilled, ready_for_pickup → fulfilled,
pickup-modality fulfilled → delivered, shipping-modality fulfilled stays.
Plan: 6.0-fulfillment-and-delivery.md (Key Decisions → "Status model — two
axes", Resolved Question 14, Phase 7).
2026-08-11: The order edit screen stages edits and saves in bulk (reverses 2026-08-10)
The 6.0 admin order edit screen was specified to write immediately — one interaction, one request — and shipped that way: a dialog per quantity change, a confirm dialog per removal. That is the wrong shape for an order editor and the constraint behind it was wrong.
It now works as a form. Quantities are inputs, a row's x marks it removed
(struck through, reversible), Save applies the batch and Discard drops it.
Why the original constraint was wrong. It existed to forbid a persisted
per-domain draft: a shadow order in the database that
6.1-order-change-substrate.md Phase 3 would have to migrate onto OrderChange.
That reasoning holds. But it was extended to cover transient React form state,
which is a different thing entirely — a form holding "quantity 2 -> 3, line 4
removed" until submit persists nothing, so there is nothing to unpick later. It
is the same dirty-tracked form pattern the dashboard uses everywhere else.
Staged edits fit the substrate better, not worse. OrderChange is
begin -> request -> confirm -> cancel: accumulate actions, then confirm. A
screen that already batches behind Save maps onto that directly, and Phase 3
becomes additive (a totals delta, begin on entry). The immediate-write version
is the one that would have needed reshaping, having no confirm moment at all.
Immediate writes were also worse on their own terms. Every keystroke in a quantity field fired a request and re-summed the order server-side, and removing a line was irreversible with only a confirm dialog in the way. Staging gives the merchant a Discard.
Accepted limitation. There is no bulk line-item endpoint, so Save issues N
calls against the existing per-item routes and a mid-batch failure leaves
earlier writes applied. The screen reports what succeeded and keeps the rest
staged. Deliberately not fixed with a new bulk endpoint: Phase 3's
OrderChanges::Confirm applies every action in one transaction, so building one
now would be work thrown away.
What stays forbidden: persisting pending edits in any schema, and computing a projected total client-side to fake a preview — 6.0 cannot project totals, and an approximation would disagree with the server.
2026-08-11: Cross-border tax-inclusive pricing derives net-fixed, except where the merchant priced that geography
A live pass against a running server found three defects in one seam — what a customer is charged
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 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:
Pricing::Context.from_ordernever carried the owner'smarket, so cart line pricing followed the request'sx-spree-countryhint (or the store default) instead of the cart's own market. Measured: a catalogue request with the hint served a French price list at 99.00 while the cart on that same French market priced at 100.00, and the wrong figure persisted. Market-scoped price lists were therefore unreachable from a cart — they work for the catalogue only.Cart#recalculate_for_address_change!calledLineItem#update_price, which assigns without saving, whererecalculate_pricepersists. A destination change computed the restated price and discarded it; a later quantity change wrote it. So what a cross-border customer paid depended on the order of operations.
Constraints this places on other work: cart-stage pricing must read the cart's own market, never
Spree::Current (catalogue requests keep that fallback, having no owner); any new PriceRule
subclass must answer geographic?, since that predicate now decides whether its list's prices are
exempt from restatement; and re-pricing paths must stay behind
Carts::Complete#verify_expected_total, whose cart_changed failure is what makes a mid-checkout
price movement disclosable instead of silent.
Restatement is a capability of the Internal provider, not of the platform. VatPriceCalculation
derives both the home and destination rate from TaxRate rows, so it only works where those rows are
the whole truth. An absent row is ambiguous — no tax is due here or tax is computed by an engine —
and the code reads it as the former. Measured: German home zone, Japanese destination, no Japanese
rates, and 100.00 is charged as 84.03. Correct for a genuine zero-rated export; wrong for a market
whose engine simply has no rows in that table, where it makes every foreign destination look like an
export. So restatement runs for Internal and is skipped elsewhere, with a geo-scoped price list as the
external-provider merchant's way to state destination prices. Shopify arrived at the same separation:
dynamic tax-inclusive pricing reads a standard-rate table and is explicitly unsupported alongside
AvaTax. A
read-only rate_for on the provider contract would dissolve the limitation and stays deferred with
the delivery-option quote question, which is the same problem for a different surface.
Surveyed for this: Shopify, WooCommerce, Magento/Adobe Commerce, BigCommerce, Saleor, Medusa, Vendure, commercetools. Net-fixed is the majority default (WooCommerce, Magento, Shopify, Vendure); the headless platforms (Saleor, commercetools, Medusa) refuse to derive at all and require a price per channel/region.
2026-08-10: Fulfillment side effects move to workflows; the state machine keeps the status column
Answers "should Fulfillment follow Order and lose its state machine?" with partly, deliberately. The side effects move; the machine stays.
Fulfillment#after_cancel restocked every unit and called
provider.cancel_fulfillment — network I/O (an EasyPost label refund, a 3PL
stand-down) running inside the save transaction that held the stock movements.
That is precisely the failure 6.0-service-workflows.md cites as the reason
transition callbacks are the wrong place for side effects: a slow carrier holds
row locks, and a failing one rolls back a restock that already happened at the
warehouse.
Spree::Fulfillments::Cancel and ::Resume now own that work — restock and
status inside one transaction, the provider call as an external_step after it
commits. Fulfillments::Fulfill (added the same day for partial shipments)
gained an explicit unstock for the canceled -> fulfilled path the resume
callback used to cover; missing it would have shipped goods without taking them
off the shelf.
What the machine keeps: the status column, the transition graph and its
guards, and the publish_*_event callbacks. Publishing an event describes the
status change rather than being a side effect of it, so it belongs where the
transition is. The graph is real validation work — the narrow exception
6.0-service-workflows.md already allows.
Why not remove the machine outright. Four other models still carry machines
(Payment, InventoryUnit, ReturnAuthorization, GiftCard). Removing one at a time
means re-litigating the same design in five separate rounds, and Fulfillment's
ready/resume guards are conditional on determine_state, so replacing them
is not mechanical. A full removal is a planned wave with its own document, not a
refactor folded into fulfillment UI work. This also amends
6.0-fulfillment-and-delivery.md resolved question 1, which had promised all
transition hooks were preserved.
Composition constraint, and the wrong turn taken first. Orders::Cancel
and Orders::Resume cancel or resume every fulfillment from inside the order's
own transaction, and a nested external_step raises ContractError by design.
The first attempt worked around this by putting the restock bodies on the model
as public #restock_units/#unstock_units and having both layers call them.
That was wrong twice over: it violates the rule that workflows write behavior
inline as named steps rather than delegating to model business methods, and it
plants new public model surface that would have to be torn out again when the
machine is eventually removed — the opposite of the direction the model is
moving.
The right shape: the stock movements are written inline in the workflow steps,
and Fulfillments::Cancel takes a notify_provider: flag so a caller that
already holds a transaction can suppress the external step and batch the
carrier calls into its own. Orders::Cancel passes notify_provider: false
and notifies after commit; Orders::Resume nests cleanly because Resume has no
external step. The general rule: when a workflow with an external_step must
run inside another's transaction, give it a flag to defer the external half —
do not push the shared behavior down onto the model.
2026-08-10: Order editing splits from fulfillment management; two OrderChange questions resolved
The 6.0 admin order detail page grows a separate edit screen at
/orders/$orderId/edit owning post-placement line-item mutation — add, remove,
change quantity. The order detail page keeps fulfillment management (what ships,
from where, under which delivery method); it no longer offers line-item editing.
The split follows the reference layout and, more importantly, matches how
6.1-order-change-substrate.md Phase 3 wants to wrap the edit surface in a
change set without disturbing fulfillment UI.
The 6.0 screen writes immediately and shows no totals delta. Projecting
totals without writing rows is impossible before the OrderChange substrate
lands, and the alternative — buffering edits in React state so the UI can fake a
preview — is a per-domain draft living in the browser, which the substrate plan
explicitly forbids. The money math still goes through a value-object-returning
service so Phase 3 re-points it at OrderChanges::Preview without touching
callers.
Two of that plan's open questions are settled as a consequence:
A change set belongs to one Order, never to an OrderGroup. Multi-vendor
fans a cart into N child orders under one group, and the marketplace plan's
Decision 8 keeps line items, fulfillments and totals on the children — the group
holds only customer, payment and addresses. Change sets mutate child-owned rows,
so they bind to the child. Cross-vendor edits are N change sets, which is also
where the money belongs: each vendor settles against its own order.
A pending change set does not hold stock. Stock reservations are scoped to
checkout — held against a cart, extended by customer activity, expired by a job.
An admin editing a placed order is neither, so reusing that machinery would
create reservations with no expiry trigger. add_item takes stock at confirm,
and confirm is where an out-of-stock action fails.
Also settled for the backend: partial fulfillment ships as a
Spree::Fulfillments::Fulfill workflow, not by extending the state machine.
Spree::Fulfillment keeps its machine (preserved deliberately per
6.0-fulfillment-and-delivery.md resolved question 1), but shipping a subset
means splitting first, and split-then-ship inside an after_transition callback
is exactly the shape 6.0-service-workflows.md prohibits. The workflow wraps the
machine as a low-level mechanic, mirroring how Fulfillments::Create already
wraps mark_shipped.
2026-08-10 — One payment settlement path: PaymentSession#settle_payment!
A settled payment session is noticed on two routes — the storefront's confirm
call and the gateway webhook — and they settled the payment differently. The
webhook path called Payment#confirm!, a local state move guessed from the
auto_capture? setting. The Stripe sync path called process!/authorize!,
which route through gateway_action back into the gateway's authorize/purchase
verbs: a second Stripe round trip to learn what complete_payment_session had
just read from the intent. Worse, those verbs look the owner up in
store.orders, which can never find a cart — so checkout-time (cart-owned)
settlement failed with "Order not found". The specs missed it because they
built order-owned sessions.
Now both routes call PaymentSession#settle_payment!(captured:) — find or
create the payment, skip if completed, then confirm!(captured:). The
captured flag carries what the gateway actually reported instead of the
config guess: Payment#confirm! gained the keyword (nil keeps the old
auto_capture fallback for any other caller). Stripe passes intent status
succeeded; the webhook path passes action == :captured. That also fixes the
dashboard-capture edge: a manual-capture payment captured directly in the
Stripe dashboard now completes on webhook instead of pending forever.
Consequences: gateway complete_payment_session implementations settle via
settle_payment! and never call process!/authorize! — those verbs remain
core's fallback for payments not covered at completion time, where the owner is
already an Order. A gateway reports facts (captured or not); core owns what
the payment does with them.
2026-08-10 — Stripe drops Apple Pay domain registration; payment intents are not a subsystem
Two removals from the Stripe port, both from the same question: what does a headless backend actually know?
Apple Pay / Google Pay domain registration is gone. The gateway registered
store.url with Stripe on create, and re-registered whenever a store code or
custom domain changed. That only works when Spree serves the storefront. Headless,
the storefront is someone else's deployment on a domain the backend never sees,
so the call registers the wrong host — worse than not running, because it looks
like it worked. Merchants register domains in the Stripe dashboard, which is
where a headless setup has to do it regardless. Removes RegisterDomain, its
job, the CustomDomain decorator and the stripe_apple_pay_domain_id /
stripe_top_level_domain_id accessors.
Payment intents are not a parallel system. A Gateway::PaymentIntents
concern alongside Gateway::PaymentSessions implied two paths, one of them
legacy. There is one: creating a payment session is creating a Stripe payment
intent, and the session stores the intent id as its external id. The intent
calls now live in Gateway::PaymentSessions, with payload building private to
it. PaymentIntentPresenter went too — it presented nothing, it built a request
body, and update_payment_intent proved the framing wrong by constructing the
full create-payload only to slice most of it away.
Consequences: the gem no longer touches storefront domains at all, and there
is no "intents" vocabulary suggesting a second code path. Net −2,000 lines
against the initial port. A gateway that wants to register domains needs the
storefront's real host as configuration, not store.url.
2026-08-09 — Stripe moves into the monorepo as a payment-session-only gem, with no tables
spree_stripe ships from spree/providers/stripe in the monorepo, per
6.0-payment-gateways-monorepo.md. Three things were decided during the port
that the plan had left open or assumed differently.
Scope is the payment-session API, not the whole gateway. The plan's
keep-set was "the v3 half of the repo"; the sharper line is the session flow.
The six money verbs (authorize/purchase/capture/credit/void/cancel)
stay, because core's payment lifecycle calls them after a session completes —
Spree::Gateway::Bogus, core's own reference session gateway, implements the
same six. What left is the machinery around them: creating intents for payments
that never had a session, off-session confirmation, the storefront
redirect/confirm controllers, SpreeStripe::CompleteOrder (Carts::Complete
owns completion now), and the stripe_event engine with its four webhook
handlers — webhooks arrive at core's v3 endpoint and route through
#parse_webhook_event. Stripe Tax is dropped outright and revisits as a
TaxProvider.
The webhook-key tables collapse into preferences, and the gem ends up with no
schema at all. spree_stripe_webhook_keys plus its join table existed to map
signing secrets to payment methods many-to-many — a shape that only made sense
while a payment method could be shared across stores. belongs_to :store means
one endpoint per gateway, so the secret is a :password preference. Worth
stating plainly, because the plan called this an "encrypted preferences" move
and it is not: spree_payment_methods.preferences is serialized YAML with no
encryption at rest, while the dropped model declared
encrypts … deterministic: true. It is not a new exposure — the Stripe secret
key, a more powerful credential, has always sat in that same column — but
encrypting the preferences column is now a live core-wide question rather than
something this port solved. spree:upgrade:migrate_stripe_webhook_keys carries
existing secrets across.
Manifest steps from optional gems need an optional: true flag. The
upgrade runner resolves each step with Rake::Task[…], which raises when the
task isn't defined — so an unconditional Stripe step in core's 5.6→6.0 manifest
would break rake spree:upgrade for every install without the gem. The flag
makes the runner skip with a note. Every future gateway gem contributing a
backfill uses it.
Consequences: gateway configuration lives in payment-method preferences,
never in new tables — a gateway that thinks it needs one should first check
whether single-store ownership removed the reason. Gem-contributed upgrade
steps are always optional: true. Two committed VCR cassettes were found
carrying real webhook signing secrets (the sensitive-data filters covered
request keys but not response bodies) and were redacted; cassettes now default
to record: :none, since record-by-default turns renaming a :vcr example
into a live API call.
2026-08-10: Spree::Digital → Spree::DigitalAsset; digital assets get an admin surface, delivery mailer, and per-asset limit fallback
Plan: 6.0-digital-assets.md. Full rename at 6.0 — class, spree_digitals →
spree_digital_assets table, and digital_id → digital_asset_id FK — with
the standard one-release bridges (constant alias, deprecated twin
associations, dual-emitted digital.*/digital_asset.* events).
Spree::DigitalLink keeps its name. The plan also builds the missing
management surface (Admin API v3 + dashboard, catalog placement: assets under
:products, link reset under :orders), a dedicated
Spree::DigitalAssetMailer (never a section in the order confirmation), a
customer GET /store/account/digital_links endpoint, a
digital_link.downloaded domain event, and signed-URL download transport
(the previously dead digital_asset_link_expire_time preference becomes the
signed-URL TTL instead of being deleted).
Why: the engine shipped in 6.0's fulfillment rework is complete but has
no admin API, no dashboard page, no delivery email and no download
visibility; the model name Digital never matched the docs, the
digital_asset_* preferences, or the deleted legacy admin's vocabulary.
Renaming before the admin endpoints exist is the cheap moment.
Recorded exception: digital assets carry nullable authorized_clicks /
authorized_days that fall back to the store's download settings at read
time. This is a deliberate, documented exception to the
6.0-store-scoped-configuration.md "store preference is authoritative, no
runtime fallback" rule — the fallback is record → its store's setting only,
never a chain through global Spree::Config, and the store setting remains
the authoritative default.
Consequences: new code uses DigitalAsset/digital_assets names only;
admin controllers for these models land with their permission catalog
entries; nothing outside the model may assume an attachment is always
present (external/provider-backed asset kinds and license-key pools are
groomed for 6.1); emailed download URLs must keep resolving across renames
for at least one release.
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.0-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.0-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-09: Origin groups and per-currency delivery pricing in 6.0
Two same-day additions to the delivery-profiles model, both Damian-approved mid-review of PR #14404.
Spree::DeliveryOriginGroup (pulled forward from the 6.1 open
question). Zones are per-profile (the profile-based platforms' shape;
sharing across profiles was considered and rejected — editing a shared zone
would silently change other profiles' coverage). Within a profile, origin
groups partition the fulfillment origins: every zone and method belongs to
one group, so "same products, different warehouse, different rates" is one
profile with two groups instead of hand-narrowed method duplicates. The
auto-created nameless default group (no members = all locations) keeps the
layer invisible for single-origin stores. The profile ↔ stock-location join
is replaced by group membership (profile coverage = union of its groups);
per-method ships-from narrowing retires for shipping methods, and
DeliveryMethodStockLocation stays pickup-only (collection counters).
Admin API: nested origin_groups CRUD under delivery_profiles; the
profile-level stock_location_ids shorthand reads/writes the default
group.
Per-currency delivery pricing (kills method-per-currency). Amount-based
shipping calculators (FlatRate, PerItem, DigitalDelivery) gain an amounts
hash — one explicit amount per currency, no FX, mirroring product prices;
a currency without an amount hides the method for those carts. The legacy
single amount+currency pair stays as the fallback for its own currency,
so upgraded 5.x stores quote unchanged. Percent calculators are
currency-agnostic and drop the currency gate; PriceSack/FlexiRate keep
strict single-currency matching. The Estimator consults
calculator.supports_currency? instead of exact-matching the currency
preference. Carrier quotes: DeliveryRateProvider::Estimate gains
currency, EasyPost passes the carrier's rate.currency through, and the
Estimator drops estimates quoted in another currency than the cart's — a
number in the wrong currency must never reach checkout (EasyPost has no
quote-currency parameter; multi-currency carrier setups use
per-currency carrier accounts). The pricing card renders one amount per
supported store currency; the default currency maps to the legacy amount
preference.
Amended 2026-10-21: amounts decides alone once it holds an amount, and
the dashboard writes the store's default currency into it like every other
currency. The legacy pair still quotes its own currency, but only while
amounts is empty. Mapping the default currency to the legacy amount
made "left blank" impossible for it: the pair's untouched default (0 in the
store's currency) read as a price, so a method priced only in euros, through
the dashboard or the API, was offered free to dollar carts. Upgrades from 5.6
need no data step: 5.x methods hold only the legacy pair.
2026-08-09: Fulfillment profiles — ShippingCategory promoted, not removed
Reverses three recorded decisions inside the 6.0 window: "fulfillment types
are NOT a model", "named delivery groups are the 6.1-if-needed successor to
profiles" (both 6.0-fulfillment-and-delivery.md), and live-by-reference
fulfillment_types on ProductType (6.0-product-types.md). Full design in
6.0-delivery-profiles.md.
The model. Spree::DeliveryProfile — store-scoped STI, one default
per store, kinds registered via Spree.delivery_profile_types
(DeliveryProfiles::Shipping default, ::Digital) — groups products
for delivery: profile ↔ stock locations (origins, empty = all), profile →
delivery zones (destinations), profile → delivery methods (each with an
optional single zone and optional ships-from narrowing via the generalized
method↔location join). Products carry delivery_profile_id directly;
ProductType stamps its template profile at creation and never manages it
afterwards. Carts split per profile. Classes only, no string
vocabularies (refined same day): the method's fulfillment_type column
is dropped (not renamed to modality), Spree.fulfillment_types and the
ProductType array are deleted; behavior routes through class predicates —
FulfillmentProvider subclasses answer digital?/pickup?/
pickup_point?/requires_address?, rate providers declare
requires_address? instead of type lists, and the profile kind declares
digital?/requires_shipping_address? and validates composition (a
Digital profile accepts only digital-provider methods; a carrier rate
provider only prices methods that ship to an address). A location-group
layer was considered and dropped — per-method narrowing covers
multi-origin stores, and groups can arrive additively later.
Why reverse now. No rewrite window after 6.0; custom string types were second-class (provider declarations could never include them, so a custom type could not use carrier rate providers); the origin axis simply did not exist for shipping methods; and the fulfillment_types array was the sole live-by-reference exception to the product-type template doctrine.
Migration by rename. spree_shipping_categories →
spree_delivery_profiles and spree_products.shipping_category_id →
delivery_profile_id: 5.x products arrive assigned, the 5.x Digital
category becomes the Digital profile. spree:migrate_delivery_profiles
(5.6→6.0 manifest) handles what a rename cannot: store assignment for the
formerly-global categories (duplicate + remap when shared), folding
non-narrowing categories into the store default profile, digital-kind
detection, and collapsing the method m:n
(spree_shipping_method_categories, kept to 6.1 as source) into the
single method FK — loud warnings wherever flattening loses information.
2026-08-09: Dynamic carrier rates — one delivery method, many named rates
Supersedes the one-rate-per-method model in 6.0-delivery-rate-provider.md
(its unique-index gate is hereby exercised): a carrier-backed DeliveryMethod
is the carrier connection, DeliveryRateProvider::Base#estimates(package)
returns one Estimate per service, and every service becomes its own named
DeliveryRate at checkout ("UPS Ground", "USPS Priority Mail"). This also
finally delivers the "one Carrier shipping method per market, the provider
returns whatever serves the address" aspiration recorded in the 2026-07-29
aggregator survey, which the previous schema could not.
Merchant controls (Shopify's knob set plus label overrides, which
Shopify lacks): a new Spree::DeliveryMethodService row model — one row per
carrier service, unique on (method, carrier, service) — narrows which
services are offered (no rows = everything, current and future) and carries
per-service label, markup_flat, markup_percent; method-level markup
columns are the fallback. Rows, not preferences: independent per-service
controls need a real model with real validation and API round-tripping.
Consequences. spree_delivery_rates lost its unique
(fulfillment, delivery_method) index and gained name (nil for calculator
rates — DeliveryRate#name falls back to the method name, preserving the
old delegate behavior). Selection across re-quotes and EasyPost label
purchase key off the selected rate's carrier/service, not method config.
The EasyPost method-metadata carrier/service binding is deleted. Seeds and
sample data reshaped Shopify-style: Domestic + International delivery zones
per store with basic flat-rate methods, replacing the continental sprawl.
Competitive grounding (researched 2026-08-09): Shopify persists service selection + handling fee on the zone's carrier-rate entry and quotes live (labels not renamable); Medusa materializes one ShippingOption per service from the provider catalog; Saleor delegates everything to apps; Vendure is one-method-one-quote. The two-entity method→services shape is the normalized version of what Shopify/Woo store as config blobs, and Spree ends up expressing all four models.
2026-08-07: Country/State AR models dropped — ISO codes are the identifier everywhere
Decision: Delete Spree::Country and Spree::State as ActiveRecord models
in 6.0 — tables, seeds, factories, and every country_id/state_id FK. The
constants survive as gem-backed value objects (ActiveModel::Model, data from
the countries gem; carmen removed). Consumers store country_iso (+
state_abbr always paired with its country_iso — subdivision codes are not
globally unique). Address validation semantics are preserved exactly
(STATES_REQUIRED countries validate state_abbr against gem subdivisions
with name→abbr promotion; elsewhere state_name stays free text). Full design:
6.0-drop-country-state-models.md.
Why: No competitor points an address at a state row (Vendure has a Province
entity and still stores a string on Address); Medusa and Vendure's country
tables are materialized caches of static ISO lists. Our public surface is
already ISO-native — neither model exposes an id in v3, addresses serialize
flat ISO strings, the dashboard submits ISO only — so the AR layer was pure
internal overhead: two seed services, two gems (carmen + countries), duplicate
ISO→record resolution paths with divergent failure modes, and localized names
already delegating to ISO3166::Country with the DB column as fallback.
Supersedes: the FK member design in 6.0-delivery-zones.md
(DeliveryZoneMember converts to country_iso/state_abbr strings; state
members gain their own country_iso) and — decisive on timing — the unshipped
6.0-tax-provider.md Phase 5, amended so spree_tax_rates columns are born
as country_iso/state_abbr strings, never FKs (verified 2026-08-07 the FK
columns don't exist yet; amending now avoids migrating the same columns twice).
The two admin endpoints still permitting raw country_id/state_id params
(customer addresses, order addresses) drop them. Sequencing: the table drop
lands after delivery-zones Phase D so the polymorphic ZoneMember is removed,
never string-converted.
Constraint now: no new country_id/state_id columns or
belongs_to :country/:state anywhere — new features store ISO strings
(Promotion::Rules::Country is the template).
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
Reverses the "enforced at activation" position taken earlier the same day
in 6.0-product-types.md. The flag stays on
ProductTypeCustomFieldDefinition, ships in the Admin API, is editable
in the type editor, and renders as a marker on the product form — but no
model validation rejects a blank value.
Why. Spree writes a product and its custom fields in two steps:
the CSV importer saves at product_variant.rb:88 and attaches
metafields at :93, and API clients can do the same (a metafield needs
a persisted parent, so custom_fields= stashes values until
after_save). Any save-time rule fights that. Three triggers were tried
and each failed: activation-only left a product created active
permanently non-compliant, since status never changes again; excluding
creation had the same hole; including creation broke the sample-data
import twice and needed a staging shim inside the importer to work
around the model's own rule.
Competitor check. Shopify has no required flag on metafield
definitions at all — validations cover length/range/regex only. Medusa
and Vendure have no type-driven required concept. Only Saleor enforces
(valueRequired), and it can because attributes exist solely through
the product type and ride the product mutation atomically. Neither holds
in Spree, where any definition can attach to any product independently
of a type. Adopting the Shopify position deletes the most fragile code
in the feature.
Constraint going forward: never add a model validation for this. A dashboard-side nudge on the activation action is acceptable and reversible; a server rule is not.
2026-08-06: ProductType is a creation-time template, not a live sync; type changes are allowed; no Store API exposure
Competitor review (Saleor / Shopify / Medusa / Vendure) reversed the
2026-07-27 "live template" and hard-immutability decisions in
6.0-product-types.md before the unshipped Phase 2 built them. Saleor
is the only platform with live propagation, and only because its
attributes have no existence outside the type; Shopify — the largest
merchant base on this problem — made category changes affect nothing
retroactively. The settled semantics:
- Two regimes by data nature. Custom-field form generation,
required-field validation, and
fulfillment_typesare live by reference (read from the type at use time — no sync needed to be "live"). Option types and categories are seeded additively at attach (creation or later assignment); editing a type never mutates existing products. No propagation callbacks, no locked option types, no provenance tracking. - One explicit bulk path:
ProductTypes::ApplyToProducts— additive-only, idempotent, previewed withproducts_count, run as a background job, shipping in 6.0 Phase 2. A deliberate bulk edit the merchant asks for by name, never a side effect of editing a type. - Required fields validate at activation only — never on ordinary saves of an already-active product, otherwise adding a required definition to a type bricks every active product of that type on next save (Shopify precedent: definition validations gate new writes only).
- A product's type is changeable: explicit per-product detach and
reassign, both non-destructive (nothing deleted; custom-field values
survive as unstructured values; the new type seeds additively and its
required fields are checked at next activation). The immutability
guard was never shipped and will not be. Deleting a type in use stays
restrict_with_error. - ProductType is back-office vocabulary — no Store API surface at
all (no endpoint, no expand, no filter). Storefronts see categories
and collections only. The planned
expand=product_typewas never implemented and is cancelled. - Variant-level custom-field definitions deferred to 6.1 (no
speculative
levelcolumn in the join). - No shared value pools for custom fields — the plan's last open
question, closed. Both roles it conflated are already served:
predicate search/sort/filter on custom-field strings shipped in 5.6
(
SearchProvider::MetafieldSchema+with_metafield_filters, storefront included) and stays string-based; faceted navigation over canonical values with counts is the OptionType/OptionValue role (disjunctive faceting shipped 5.4). Product-level descriptive facets (Vendure Facet / Saleor non-variant attributes), if ever demanded, get their own dedicated plan — never a custom-fields extension.
Adjacent, same review: ShippingCategory stays removed despite the
removal being unreleased. Medusa's ShippingProfile / Shopify's shipping
profiles are the same design as the category, but the 6.0 stack already
covers all three of its jobs (fulfillment-type eligibility matching,
Splitter::FulfillmentType, excluded_delivery_method_ids). The one
real loss — a named product grouping for delivery management — gets an
if-needed 6.1 successor as a named eligibility set or a
DeliveryMethodRule kind, recorded in 6.0-fulfillment-and-delivery.md
("Named delivery groups"). Also on record: Spree never had a
variant-level shipping category (Solidus did), so product-level
fulfillment_types granularity is not a regression; the mixed
physical/digital product gap keeps a reserved relief valve (per-product
or per-variant fulfillment_types override, 6.1-if-needed).
2026-08-06: All three reason vocabularies are store-owned
ReturnReason, ClaimReason and now RefundReason include
SingleStoreResource. Name uniqueness moves from global to per-store, so
two stores can each have their own "Damaged" or "Order Canceled".
This is what makes the controller rule enforceable: every reason lookup
reads its matching association — current_store.return_reasons,
current_store.claim_reasons, current_store.refund_reasons — rather
than the model constant, so a prefixed id from another store is a 404
instead of a silent success — the
cheapest defence against IDOR, and now uniform across the returns surface
alongside current_store.stock_locations.
Refund reasons carried one wrinkle the others did not. Core looks three
of them up by name (RETURN_PROCESSING_REASON and friends) to attach to
refunds it issues itself, and a global find_or_create_by(name:) under a
per-store unique index would either find another store's row or create a
storeless one. The class methods therefore take the store explicitly —
return_processing_reason(store) — defaulting to Spree::Current.store
but never relying on it from a workflow, because a background job or
console session has no current store and would bind the reason to the
wrong one. All four call sites pass the store they already hold.
Existing rows are backfilled by spree:upgrade:backfill_reason_store_ids,
registered before migrate_returns in the 5.6→6.0 manifest. The
migration only adds the column — data transformations stay in rake tasks,
matching backfill_delivery_and_stock_store_ids.
2026-08-06: Return shipping labels are carrier output, not return state — cut from 6.0
Spree::Return briefly carried a return_label_url column written by a
generate_label: seam on Returns::Approve. The seam resolved its
provider through Spree.return_label_provider, which was never
registered in Spree::Dependencies — so the guard never passed and the
column was written by unreachable code. Both are removed.
The bug prompted the review; the market settled the direction. No
comparable platform stores a label URL on the return record. Medusa
returns label_url as part of a fulfillment (FulfillmentLabel) and
its own integration docs concede the default return flow "does not
provide enough data to create a full return shipment automatically";
Saleor's Fulfillment object exposes only trackingNumber, with labels
left to apps on webhooks; Vendure has no return-label concept at all,
producing labels as a side effect of a FulfillmentHandler calling a
courier API. A label is carrier output attached to a shipment, not a
property of the return.
Labels therefore ride with the carrier provider in
6.0-delivery-rate-provider.md, where an EasyPost/Shippo provider exists
to mint one and it can hang off a fulfillment like everywhere else. Until
then a store puts the URL in the return's metadata. This is the same
rule the return-policy decision (2026-08-03) applied: core ships a seam
when there is a real implementation behind it, never a speculative column
plus a provider key nobody declares.
2026-08-07: Provider gems live under spree/providers/
Established with the easypost move (spree/easypost →
spree/providers/easypost) while exactly one provider gem existed and
none had published. Rationale: the provider roster (easypost, stripe,
adyen, avalara, inpost, possibly meilisearch) will outnumber the four
platform gems (core/api/emails/dashboard), and a flat spree/ stops
communicating what is load-bearing versus optional — Medusa's monorepo
draws the same line. Kept under spree/ (not top-level) so the
spree/** CI path filters, gem-cache keys and starter globs keep
working. Gem names stay flat (spree_easypost, never
spree_provider_easypost) — the directory groups, the gem name is the
public identity. Mechanical consequences: CI matrix entries carry a
dir: field when it differs from the project name, and Bundler path
blocks need glob: '{,*,*/*,*/*/*}.gemspec' to reach the third level
(applied in the worktree server Gemfile; spree-starter needs the same
line when providers ship). 6.0-payment-gateways-monorepo.md retargeted
to spree/providers/stripe / spree/providers/adyen.
2026-08-06: Integrations become the admin-managed credential surface; verify-before-activate
Spree::Integration (shipped 5.x, previously zero subclasses, no API,
no UI) becomes the single credential home for every provider seam —
delivery rates, tax, fulfillment, pickup point networks. New plan:
6.0-integrations-admin.md. Explicit Spree.integrations registry
(house pattern, no descendants-scanning); Admin API v3 CRUD + types
discovery reusing the PreferenceSchema/Masking machinery from
payment methods (secrets are :password-typed preferences, masked on
read, round-trip-guarded on write); dashboard /settings/integrations
gallery grouped by integration_group — the one page showing what is
connected to the current store. Semantics settled interactively:
verify before activate (saving credentials never makes a network
call; flipping active: true runs can_connect? and 422s on failure;
POST /:id/test for diagnostics) and ephemeral connection status
(no last_checked_at/last_error columns). Constraints now: new
provider gems ship an Integration subclass — no env-var credential
contracts for per-store providers; no per-provider credential UIs —
provider pickers deep-link to the integrations page.
2026-08-06: Pickup point provider contract hardened; no reference network gem in 6.0
Decided before any concrete PickupPointProvider exists, precisely
because none does: (1) providers are constructed with
new(delivery_method) — the current zero-arg construction leaves no
path to store.integrations for credentials; (2) find_nearby accepts
zipcode:/query: alongside latitude:/longitude: (postcode/city
search is the standard EU checkout pattern; map-widget storefronts skip
find_nearby and only use server-side find_by_external_id
validation). Both are free now and breaking later. No reference
network provider (InPost/Sendcloud) ships in 6.0 — community/later,
with a how-to guide. The checkout flow itself is confirmed as
shipped: point selected during checkout at the delivery step
(pickup_point_external_id on rate selection, server-validated, frozen
into fulfillment.pickup_point_data).
Amended 2026-08-06 (same day, Damian): all pickup work beyond
already-shipped code — including the contract hardening above — is
deferred to 6.1; 6.0 is packed. The pickup point provider
interface is not documented in 6.0 at all — the v6 developer docs
cover only the delivery rate provider interface; a class-level comment
on PickupPointProvider::Base notes the constructor and find_nearby
signature change in 6.1, so the change breaks no sanctioned contract.
Accepted trade-off, recorded in 6.0-fulfillment-and-delivery.md
(Implementation status + Phase 6). Constraint: no 6.0 doc or guide may
cover the pickup point provider interface.
Second amendment 2026-08-06 (Damian): pickup_point is also
removed from the Spree.fulfillment_types registry and the dashboard
FULFILLMENT_TYPES const — not selectable anywhere in 6.0; existing
rows stay loadable (inclusion validates on change only) and the shipped
endpoints still serve them; one-word re-registration in 6.1 restores
the surface. local_delivery is removed the same way, but as a cut,
not a deferral: it fails the plan's own modality-vs-segment test —
identical address/zone/provider/lifecycle semantics to shipping; the
local-delivery use case is a shipping method with a postal-code
DeliveryZone. It returns only alongside real provider behavior
(delivery windows, courier assignment). 6.0 built-in types:
shipping, pickup, digital.
2026-08-06: EasyPost is the reference delivery rate provider (Shippo pick reversed same day)
Resolves the EasyPost-or-Shippo pick left open on 2026-07-29/30. The
monorepo's reference DeliveryRateProvider (6.0-delivery-rate-provider.md
Phase 5) is built on Shippo. Competitor survey: no platform ships
direct per-carrier integrations in core — Shopify and WooCommerce built
their in-house label services on an aggregator (both historically
EasyPost-backed), BigCommerce leans on ShipperHQ, and the OSS field
(Medusa, Saleor, Vendure) ships a provider interface with aggregator
plugins, Medusa's ecosystem having standardized on Shippo. A direct
UPS/USPS/FedEx trio was rejected: three churning carrier APIs to
maintain, US-only coverage against Spree's heavily European base, and
worse merchant onboarding than one aggregator account. Between the two
aggregators, Shippo fits the reference provider's audience (default OSS
install, SMB merchant): simpler API surface, pay-as-you-go pricing with
no monthly fee, solid EU carrier set. The spree_easypost lineage
carries no weight — it targets the pre-6.0 architecture and would be a
rewrite regardless. The interface stays aggregator-agnostic; EasyPost,
Sendcloud (EU-first, strong service-point coverage) or direct-carrier
providers remain buildable as third-party gems on the same base class.
Reversed 2026-08-06 (same day, Damian): EasyPost. Two factors the
Shippo lean under-weighted: (1) Spree's merchant profile skews
larger — merchants with negotiated UPS/FedEx contracts who want to
connect their own carrier accounts, which is EasyPost's core BYOCA
(bring-your-own-carrier-account) model, not Shippo's SMB
default-account posture; (2) Ruby SDK reality: EasyPost maintains
its official easypost gem (7.6.0, Feb 2026), while Shippo's official
Ruby client last released in April 2020 and signals deprecation — for
a Ruby-first reference implementation that difference is decisive (the
Shippo path would mean hand-rolling and maintaining an HTTP client in
the provider gem). Everything else in the original entry stands:
aggregator over direct-carrier trio, aggregator-agnostic interface,
third-party gems welcome on the same base class.
2026-08-05: Dashboard form values must not embed SDK entity types
The returns rework regenerated the admin SDK types, and the new Order
embeds (returns/exchanges/claims, each carrying line items →
variants and refunds → payments) enlarged Order's transitive type
closure. That pushed TypeScript 6 over its relation-cache ceiling
("RangeError: Map maximum size exceeded") — killing tsc -b for the
whole dashboard — because the price-list form's rule drafts embedded
Customer[] (→ orders → the enlarged graph) inside the react-hook-form
values, and RHF's Path<T> enumerates every nested key of the form type.
The old types were merely under the ceiling; the API embeds themselves
are legitimate surface and were not changed.
The rule this settles: form-values types carry opaque display records,
never SDK entity types. RuleEmbedRecord ({ id, name?, email?, code? }) in schemas/price-list.ts is the pattern — full SDK records
still flow in at runtime (covariant assignment), but the form type stays
shallow, so path expansion is O(form fields) instead of O(SDK graph).
PromotionRuleFormDraft embeds seven SDK types the same way and is one
graph-growth away from the same failure — apply the pattern there when
touched. Diagnostic note: @typescript/native-preview (tsgo) has no V8
Map ceiling, so it reports the offending comparison with a line number
instead of crashing — use it to locate this class of failure; keep tsc
as the build compiler.
2026-08-05: Reason CRUD ships admin-only; immutability moves onto the model
Dropping the legacy Rails admin left return, claim and refund reasons with
no editing surface at all, and the dashboard's create dialogs sent no
reason_id as a result — every return, claim and refund was created
reasonless, which quietly wasted the point of splitting return vocabulary
from claim vocabulary. Closed with three ResourceController subclasses
(settings scope), one combined Settings → Reasons page, and a reason
picker on the three create dialogs.
Two decisions worth recording:
mutableis not a writable attribute. Core seeds reasons it looks up by name —RefundReason.return_processing_reasonis attached to every refund a return issues — so letting a client flip the flag would hand it the ability to rename or delete the record the lookup depends on.permitted_paramscoversnameandactiveonly.- The immutability guard belongs on
Spree::NamedType, not the ability layer. The existingcannot [:edit, :update], …, mutable: falserule only fires for JWT users; secret API keys authorize by scope and never consult CanCanCan, so that path could rename a locked reason freely. The concern now carriescan_be_deleted?, a rename validation and a destroy guard, keyed offhas_attribute?(:mutable)so NamedTypes without the column are unaffected. This is the RBAC Axis A/B split applied as intended: capabilities in permission sets, record-state rules on the model.
Reasons have no Store API surface — they are back-office vocabulary — so the serializers are admin-only and excluded from Store SDK generation.
2026-08-05: Legacy returns chain removed — tables kept, three capability replacements
The drop landed. Four decisions came out of doing it, each because deleting the legacy code would otherwise have quietly removed working behaviour:
- The legacy tables stay through 6.0. Only the Ruby classes are
deleted.
spree_return_authorizations,spree_return_items,spree_customer_returns,spree_reimbursements,spree_reimbursement_typesandspree_reimbursement_creditsremain as the data migration's source and its rollback path; they drop in 6.1 once installs have runspree:upgrade:migrate_returns. A migration that deletes its own source in the same release has no way back. Order#outstanding_balancedrops the reimbursement term rather than replacing it.payment_totalis already computed net of refunds byCarts::RecalculateTotals, so returns and claims need no term of their own — the legacy reimbursement payout was the only money movement that sat outside that sum. A fully refunded order therefore shows its balance as outstanding again, which is what the pre-existing "refund without a reimbursement" test already asserted.Return#refunded_totalcounts store credit as well as refunds. Store credit is a separate ledger and never creates aSpree::Refundrow, so summing refunds alone reported zero for a store-credit refund — wrong on the record, in the API, and in the customer's email.- The reimbursement email is replaced, not dropped.
Spree::ReturnMailer#refunded_emailfires onreturn.refunded. The legacy template's expedited-exchange section has no counterpart in the new model and was not carried over.
Also renamed StoreCreditCategory.default_reimbursement_category to
.default_refund_category (deprecated alias kept one release), and
repointed OrderStatusSubscriber from the return_item.* events to
return.received/refunded/canceled.
2026-08-05: Returns/exchanges/claims — legacy drop scope, permanent *LineItem names, reason renames
The new returns system (6.0-returns-exchanges-claims.md) shipped to
6-0-dev: three entities, fifteen workflows, admin + store v3 APIs,
dashboard pages. Reviewing what remains settled four things:
ReturnLineItem/ExchangeLineItem/ClaimLineItemare the permanent names. Chosen during implementation because legacySpree::ReturnItemwas still in service, they stay after the drop: they mirrorSpree::LineItem, and renaming to the plan's shorter*Itemwould cost a table rename plus serializer/SDK/dashboard churn for nothing.- Reasons:
ReturnAuthorizationReason→ReturnReason(model + table rename, deprecated alias one release) plus a newClaimReasonmodel — claim vocabulary ("arrived damaged", "never arrived") is a different list from return vocabulary ("wrong size", "changed mind").RefundReasonstays. spree:upgrade:migrate_returnsships together with the legacy drop, on the same branch, reading legacy tables via lightweight anonymous AR classes (themigrate_users_to_customerspattern) so it works after the models are deleted. Riding Wave 7 would have blocked the drop. Resumption needs no cursor, job or checkpoint table: the legacynumbercarries onto the new record and is uniquely indexed there, so the remaining work is a query rather than tracked state — which cannot drift out of sync with what was actually written.- The drop scope: legacy models + STI reimbursement types + eligibility
validators + v3 legacy serializers + seeds + permission-set grants +
legacy tables (except
spree_return_items, kept under its original name for historical reference until 6.1).Spree::Metafieldslands on the three entities on the same branch.
2026-08-05: v5 developer docs are frozen until the 6.0 release; 6.0 docs land under docs/v6
The pages under docs/developer/ document the stable 5.x line and stay
untouched until 6.0 ships — even where they describe subsystems 6.0 has
already replaced on main (the polymorphic Adjustment model, the
AdjustmentSource concern, and similar). Any plan whose remaining work
includes "update developer docs" fulfills it by writing a v6 variant
under docs/v6/developer/ (registered in docs/docs.json under the
v6.x version), never by editing the v5 page. First applications: the
typed-adjustments docs (v6/developer/core-concepts/taxes-discounts-fees.mdx
already exists; promotions core-concepts and the custom-promotion how-to
get v6 variants). Also renamed 6.0-split-adjustments.md →
6.0-6.1-split-adjustments.md: the implementation shipped for 6.0 and
the remainder (legacy-table drop, promotion stacking) is 6.1 work, so
the plan spans two releases like the other X.Y-X.Z plans.
2026-08-05: Customer registration graduates to a workflow; core sends no welcome email
Customer creation today runs through three paths with three different
side-effect sets: store self-registration links a matching newsletter
subscriber but sends no email; the checkout "create an account" box
(Orders::CreateUserAccount) adopts addresses and sends a welcome email but
skips subscriber linking; Admin API create does neither. A fourth path —
storefront OIDC auto-provisioning — is coming and would have reinvented all
of it again.
Spree::Customers::Create (seam customer_create_workflow, hooks
customers.create.validate + customers.create.after_create) unifies the
storefront paths. The validate hook is the point of the exercise:
bot/disposable-email screening, fraud checks and B2B registration approval
all need to veto a signup, which the user.created lifecycle event
cannot do. The workflow takes an optional order: and absorbs
Orders::CreateUserAccount entirely (one flow = one workflow — the
Orders::Complete precedent); the old class stays as a deprecated one-release
shell. Explicitly outside the workflow: Admin API create (plain CRUD — staff
creation must not be blockable by registration-policy hooks; handlers that
want to distinguish anyway read created_by, the return-eligibility
pattern) and JWT/refresh-token issuance (HTTP session concern, stays in the
controller).
Checkout-created accounts are password-less (the old service generated a
random password): blank is the one unclaimed-account state — same as
admin-created customers — Customer#valid_password? guards the blank digest,
the account is claimed via password reset, and a generated value could fail a
host's swapped-in Spree.password_validator. Self-registration still requires
a password, because the caller issues a JWT on success. The
password_required: keyword carries that rule: it defaults to false when
order: is present (guest checkout collects no password) and true
otherwise, and an explicit value always wins — which is how a future
provisioning caller with no order (OIDC, invitations) waives the requirement
deliberately rather than by faking an order.
The welcome email leaves core. The only sender was the checkout path
(user.send_welcome_email if user.respond_to? — self-registration never
sent one, which was an accident of the split, not a choice). Signup email is
host-app implementation via a user.created subscriber or the
after_create hook — the same stance spree/emails already takes for
headless storefronts owning consumer email.
Upgrade step (host applications). A host that relied on the checkout
welcome email — i.e. defines send_welcome_email on its customer class — must
move the send itself, since core no longer calls it. Either subscribe to
user.created (fires on every creation path, including admin and imports) or
register a handler on customers.create.after_create (storefront registration
only). The method itself can stay; nothing in core invokes it any more.
Plan: 6.0-service-workflows.md decision 13.
2026-08-05: Tax provider contract carries treatments, identities and dates — refined after the #14056 community review
The provider contract in 6.0-tax-provider.md was reworked after two
outside implementers (an EU VAT decision engine, a US rates API) reviewed
the RFC on spree/spree#14056. Every concern was verified before adoption:
against primary legal sources (the European e-invoicing standard, the VAT
Directive, the EU verification service's own documentation — citations now
live in the plan's Regulatory background section), the major provider
APIs (Avalara, Stripe Tax, TaxJar, Vertex) and platform practice (Medusa,
Saleor, commercetools, Shopify, Magento, Odoo). Decisions:
TaxLine carries a taxability reason, not just an amount. A zero from
reverse charge, an export and an exemption are different facts landing in
different boxes of a tax return, and European e-invoices must state the
category for every line. New taxability_reason column with an additive
vocabulary (Stripe's enum pruned, plus intra_community_supply and
export — Stripe's own values cannot tell cross-border goods from
services, or an export from a domestic zero rate), plus a jurisdiction
snapshot (country_iso/state_code — one-stop-shop returns are filed per
destination country). The invoice category and exemption reason codes are
deliberately NOT stored — they derive at invoicing time from the reason
plus order facts (the Odoo pattern; no surveyed platform stores them).
Core ships the reason→code lookup maps as code. Write contract: a row for
every item the provider formed a treatment for, including zero amounts.
Buyer tax identity is a separate model, Spree::TaxIdentifier.
Stripe's shape (typed kinds, multiple per customer, verification state)
with Magento's evidence discipline (VIES consultation number, validated
country/value — VIES has no historical lookup, so entry-time evidence is
the only proof that will ever exist). Dual-FK owner: customer (durable —
sole proprietors will never have a Company), cart (override), order
(completion snapshot, frozen via readonly?, source-stamped, no
correction path); company/company_location FKs arrive with the B2B plan.
Zero footprint on consumer orders. Live-read designs were rejected on
documented drift pain (Shopify B2B, Odoo).
Validating a tax ID belongs to the identifier, not to a tax provider.
The registry that can answer is determined by the number's kind (EU VAT
→ the EU service, UK → HMRC, and so on), never by a market — a customer
saves a tax ID on a profile before any order exists, so a provider-hung
validate_tax_id would force an arbitrary choice (a US sales-tax engine
asked to check an EU number, or an EU market on Internal declining while
a connected Avalara sits unused). The seam is therefore
Spree.tax_identifier_validators, a registry keyed by kind and empty by default —
core ships no registry client for any jurisdiction — so two extensions
covering different kinds coexist where a single swappable service would
let the second loaded silently disable the first. Validation splits the way Stripe's does: format
synchronously, the registry asynchronously, and the tax treatment depends
on neither. Format is a hard validation on save — whitespace/case
normalization, presence, then the registered validator's class-level
valid_format? (the SearchProvider::Base.indexing_required? shape) — so a
typo is a field error and never persists. Core asserts no format rules of its
own: a charset or length range spanning every tax regime would be an untestable
guess whose failure mode is rejecting a real business customer. The registry check runs after
commit on the address-geocoding precedent (after_commit enqueues, the job
does the I/O, update_columns writes back, a non-answering registry is
reported and recorded as unavailable), never during estimate, which reads
the stored result. Reverse charge follows the number's format, not its
verdict — Stripe applies it "regardless of its validity" — so a sale may
complete with pending and still be treated correctly; the verdict is
evidence, not arithmetic. Magento's model was rejected: synchronous
registry validation gating the treatment through customer groups, whose own
ecosystem documents the cost (a third-party module exists solely to add
caching and offline fallback for the unstable registry, and per-transaction
validation cannot run at all under external checkouts). A tax provider gem
may register itself as the validator for kinds its service can check.
Exemption is a typed estimate input plus the TaxLine outcome — the
boolean exempt?(order) is removed (wrong arity: per jurisdiction, per
item, and the reason is the audit artifact; no provider API exposes an
exempt? query). Spree::TaxExemption value objects (mirroring the future
certificate row, with typed per-item overrides) are assembled by the
tax_resolve_exemptions_service dependency (default []) — a seam because
the real implementation, certificate filtering by active status and
jurisdiction, is the B2B integration point. The identifier chain gets no
seam: it is a fallback || and lives as #resolved_tax_identifier on the
Spree::Purchase::Taxation concern beside tax_address. No exemption flags
on customer, order or line items. The set_tax_line_context hook is NOT
the channel for typed inputs — it narrows to untyped provider extras
before the 6.0 hook freeze. TaxExemptionCertificate stays in the tax plan
as its last phase, gated on Company existing, and gains reason_code — the
field providers actually consume as an entity use code, missing from the
original sketch.
Dates are explicit. estimate/refund take the rates-effective tax
date (unanimous provider practice, and legally the rate in force when the
sale happened is the one that applies), kept distinct from the
document/posting date. Refund becomes
refund(order, return_items, tax_date:) — supports both recompute-at-
original-date (Avalara/Vertex) and derive-from-recorded (Stripe/TaxJar);
the Internal provider only ever derives (TaxRate rows are unversioned).
The "credit note corrects the original filing period" claim from the
thread was checked and not adopted: a return is reported in the period its
credit note is issued, and only correcting a genuine error reopens the
original period.
Capability honesty. Providers declare unsupported domains; Internal
declares no destination-based US local tax (state-level rates cannot
express county/city/district stacking — silently under-collecting lands
on the merchant), no OSS threshold tracking, no reverse charge (unvalidated
ID → normal VAT, the protected default), no ID validation. estimate
A runtime indeterminacy channel on estimate was
considered and deferred: both cases the review raised (one-stop-shop
thresholds, Internal against US local rates) are answered by the capability
declarations at configuration time, nothing in core would consume a
per-calculation verdict, and unlike a hook key a return value can be added
later without breaking providers. estimate keeps its current signature —
the rows it writes are its output. Per-Market provider selection is
reworded to selection-not-construction: the market names the provider,
providers stay stateless and argless (the shipped Base shape), the
shipped global config class stays as the fallback.
2026-08-04: Commerce-behavior globals move to Store preferences; app configuration stays global
A full usage audit of Spree::Config (multi-agent trace with adversarial
verification over all 68 preferences) found 38 genuinely live settings, 6 read
only by subsystems 6.0 replaced, and 7 with zero read sites anywhere. One of the
38 — default_stock_reservation_ttl_minutes — has a read site but is silently
unreachable: the Store preference it falls back from carries its own default
and a > 0 validation, so it is never blank. Both default to 10, so nobody
noticed.
That failure mode is the argument for the whole decision: two sources of truth
for one behavior, where one quietly wins and the documentation becomes a lie.
The classification test: would a second store on the same installation
plausibly want a different value? Yes → the setting belongs on Spree::Store
(an EU store needs track_price_history; its sibling doesn't). No → it stays
in Spree.config (password length protects the app, not a shop).
Nine globals move in 6.0 — auto_capture (the per-payment-method column still
wins when set), auto_capture_on_dispatch, allow_checkout_on_gateway_error,
track_inventory_levels, stock_reservations_enabled, track_price_history,
show_products_without_price, address_requires_phone,
disable_sku_validation. The store preference is authoritative with no
runtime fallback to the global; existing installs carry over through
spree:store_settings:backfill_from_config in the upgrade manifest, and the
globals live one release as deprecated shells. A fallback chain was explicitly
rejected — it is the shape that produced the unreachable TTL. This finishes the
migration company → Store#company_field_enabled and allow_guest_checkout
→ Store#guest_checkout already started.
Two readers have no record-level store: Address (no association) and the
class-level product availability scope. Both read Spree::Current.store and
fall back to the declared default. The trade-off is accepted knowingly —
validation or a catalog query outside a request uses the default — because the
alternative, threading a store argument through every caller and breaking a
public scope, is disproportionate. Jobs touching those paths must set
Spree::Current.store.
track_price_history goes to Store rather than Market despite Omnibus being
per-country law: Market already owns return_window_days and the other legal
settings, but prices are not market-scoped today, so a Market home needs design
this plan won't carry. Noted as a 6.1 refinement. Two behavior-looking settings
stay global: credit_to_new_allocation (ledger-shape convention — per-store
variance corrupts one install's accounting) and non_expiring_credit_types
(reference data).
Corollary settled at the same time: new behavior flags are born on Store (or
Market/Channel where regional), never in Spree.config. Also retired on the
evidence: reserve_stock_on (the Cart/Order split wired reservations into the
cart flows gated on stock_reservations_enabled; the trigger switch was never
read — superseding note added to 6.0-stock-reservations.md) and the confirm
checkout step as a configuration concern (confirm is advertised, never
enforced — a storefront renders a review screen when it wants one;
PaymentMethod#confirmation_required? is the real, unrelated requirement).
Plan: 6.0-store-scoped-configuration.md.
2026-08-03: Return eligibility ships as a hook, not a policy engine — enforced in the workflow, scoped per market
A survey of Shopify, Medusa, Saleor and Vendure settled how far 6.0 goes on
return policy. Core ships the seam and no policy: a validate hook on
Returns::Create, Exchanges::Create and Claims::Create, with no return
window, restocking fee or final-sale flag anywhere in core.
What the survey found. Medusa, Saleor and Vendure ship no return eligibility policy at all — not a different approach, genuinely nothing. Only Shopify has an engine (window with a delivery-date anchor, percentage restocking fee, final-sale product/collection lists, per-market rule sets), and it exposes no API for any of it; configuration is admin-UI only.
The seam comparison mattered more than the feature list. Medusa built a hook
system, exposed setPricingContext on returns, and deliberately did not expose
a validation hook — policy has to live in route middleware or a replaced
workflow. Saleor built the filter-veto webhook shape for shipping and never
generalized it to returns; an external app decides eligibility itself and calls
the staff mutation, which never asks permission. Vendure's onTransitionStart
returning false | string is the only comparable veto and hangs off a state
machine rather than a return flow; its RMA issue is open at priority P4.
So validate + reject!(message) is already the strongest extension point in
the field. A ReturnPolicy model with STI rules would be the most capable
thing on the market by a wide margin and entirely speculative — no competitor
has demonstrated the demand, and the hook carries one later without changing
its contract. Deferred, not rejected.
Enforce for customers, advise for staff. The one lesson worth copying from
Shopify: eligibility is enforced on the customer surface and advisory on the
staff surface. A Shopify staff member can create a return on a final-sale item
outside the window; the customer API refuses. Their returnableFulfillments
deliberately ignores return rules because it mirrors the admin, "where any
authorized staff can create returns." A handler that rejects unconditionally
would be stricter than Shopify — a supervisor overriding policy for a good
customer is ordinary retail.
This lives in the workflow, not the model. Eligibility is a decision made
during a flow with the caller's context in hand — who is asking, and whether
they may override — not a property of a return record. Returns::Create takes
created_by (nil for customer self-service, set for staff) and the handler
decides what that means.
Per market, not per store. Return rules are legal before they are
merchandising: the EU right of withdrawal is 14 days minimum, US practice is
the merchant's choice. Order belongs_to :market, and
5.4-6.0-eu-legal-compliance.md already puts withdrawal_period_days and the
other legal settings on Market, so a handler reads its window from
order.market. Shopify reached the same conclusion — its per-market rule sets
exist specifically for EU compliance.
Also noted from Shopify but not adopted in 6.0: rules are snapshotted onto the order at placement, so changing a window never retroactively invalidates a pending return, and non-returnable reasons are tracked per quantity rather than per line item. Both are right, and both belong with a policy engine rather than ahead of one.
2026-08-02: Workflows replace state machines for new models; hooks ship on the 6.0 boundary; OrderChange substrate targets 6.1
A review of our workflow and extension surface against the wider ecosystem settled three things.
1. New models get no state machine. The returns/exchanges/claims draft gave
each of Return, Exchange and Claim a state_machine :status block with
the real work on transition callbacks (after_transition to: :received, do: :restock_items, do: :process_refund). That is now removed: plain status
string column, inclusion validation, generated predicates, and every transition
is a workflow.
Why: a transition callback runs inside the transaction that saves the status
column, so process_refund would put a gateway call inside a database
transaction — the exact failure Carts::Complete's three-phase design exists to
prevent. Transitions also take no arguments, and every real return is partial
("two of three arrived, one not resellable") with nowhere to put that input;
there is no compensation story where on_flow_failure: is; and guards raise
StateMachines::InvalidTransition instead of returning an inspectable Result.
The stated purpose of that plan was escaping six interlocking state machines —
replacing six with three is a difference of degree, not of kind.
The precedent had already shipped: the Order state machine is gone in 6.0, and
Orders::Cancel/Orders::Resume absorbed Order#after_cancel/#after_resume,
moving gateway settlement out of the transaction in the process.
state_machines-activerecord stays a dependency for the legacy models through
6.0; it is simply not used on anything new.
2. Hook keys are public API, so they ship on the breaking-change boundary.
The doctrine's "a service graduates the moment it earns a hook — never
speculatively" was written to stop speculative abstraction, and it still governs
workflows. It does not govern hooks on flows already in the workflow tier.
Adding a hook later is cheap; moving one means restructuring a flow extensions
have registered against, which breaks them. 6.0 is the window. A documented,
coherent extension surface is itself the demand, so hooks are placed
deliberately across the existing workflows now rather than one merchant request
at a time. Two closed waves (see 6.0-service-workflows.md Phase 3): Wave A
adds validate and lifecycle hooks to the existing workflows; Wave B graduates
four services that already qualify on external I/O or orchestration
(Fulfillments::Create, Payments::Capture/Refund,
Payments::HandleWebhook, Carts::Merge).
Three hook families are now named: lifecycle (past tense, react, cannot
change the outcome — what we ship today), validation (validate, reject
before the work — the most-requested seam, currently only reachable by replacing
a whole service class), and context (set_pricing_context,
get_provider_data — feed data into a calculation). Context hooks are
blocked: they need handlers to write back, and run_hooks currently
dispatches the workflow instance for reading only. Do not ship a set_*_context
hook until that contract is settled.
Explicitly rejected: workflows for plain CRUD. Wrapping every region, tax-rate and API-key write in a workflow class would add hundreds of pass-through classes with no hook, no compensation and no external I/O. Workflows are earned by orchestration, not by being a write.
3. The OrderChange substrate targets 6.1, not 6.0
(6.1-order-change-substrate.md). One OrderChange + OrderChangeAction pair
behind every post-placement mutation — admin order edits, returns, exchanges,
claims, draft-order amendments — with a begin → request → confirm → cancel
lifecycle, so those flows stop inventing four separate draft models and four
separate "what will this cost" calculations. It is deferred because it is new
schema plus a new extension API, and 6.0 already carries the Cart/Order split,
typed adjustments, the fulfillment rename and the returns rework; designing it
under time pressure against three consumers that are themselves still landing
is how it would go wrong. The 6.0 returns work ships on its own status flows and
adopts the substrate additively in 6.1 via a nullable order_change_id.
Two constraints apply to 6.0 work in the meantime: do not persist a financial preview (compute in memory and discard — a persisted per-domain draft would have to be migrated onto the substrate later), and expose post-placement money math through a service returning a value object so callers can be re-pointed without changing.
4. Hook contracts and configurable statuses (settled interactively the same day), which unblock Wave A:
Context hooks collect and deep-merge handler return values. A handler returns
a hash; run_hooks merges every handler's hash in registration order and
returns it. Chosen over a mutable context object because handlers stay pure and
independently testable, with no order-dependent shared state. run_hooks
returning a value is additive — lifecycle hooks ignore it. Last writer wins on
a key collision, reported via Rails.error.report in development so two
extensions fighting over one key is visible. This unblocks the context-hook
family — set_promotion_context, set_tax_line_context and
get_provider_data now ship in Waves A and B rather than being deferred.
validate handlers reject with reject!(message) — a purpose-named method
wrapping the existing failure path (raises FailureSignal, unwinds the undo
stack, rolls back an open transaction). Preferred over reusing failure(...)
so "an extension vetoed this" stays legible against "this step failed", and
over a falsy return value, where a stray nil would abort a flow by accident.
Statuses are configuration, not frozen constants. Spree::HasStatus holds
values in a class_attribute with an additive add_status(value, after:), so
a merchant can add an inspecting step between received and refunded
without reopening core. This follows the established class_attribute pattern
for genuinely configurable collections (DeliveryZoneMember.range_capable_country_isos,
RichTextSanitizer.allowed_tags) rather than the frozen-constant pattern used
for closed value lists.
Additive only — wholesale replacement is not offered. Core workflows guard
on core statuses (Returns::Refund requires received?); letting an extension
drop one would silently break core flows with no error at the point of removal,
because the guard would simply never pass. Adding is safe, removing is not, so
the API exposes only the safe half.
add_status deliberately takes no from:/to: transition graph. A custom
status needs a custom workflow to move records into it, which is the intended
shape, not a gap: validating transitions centrally is a state machine by
another name — precisely what ruling 1 removes.
5. Two smaller rulings from the same session.
Refunds branch on method, not blanket external_step. Store credit and gift
cards are internal ledger writes, so routing them through external_step would
push a pure database write outside the transaction that marks the return
refunded — a crash between the two leaves a refunded return with no credit
issued. Returns::Refund (and Claims::Resolve, Exchanges::Fulfill) keeps
internal credit inside the transaction and sends only gateway refunds outside
it. Precedent: Orders::Cancel#settle_payments already distinguishes
gift-card-covered payments from gateway payments.
with: step swapping stays a core-only seam in 6.0. The public extension
surface is hook keys and their contracts, reject!, Spree::Dependencies
class swapping, has_status/add_status, and workflow #perform signatures.
Step names, step boundaries and with: targets are explicitly internal —
documenting them would freeze internal structure we still expect to refactor
during the 6.0 finishing work, in exchange for granularity that hooks largely
already provide. Revisit in 6.1 once real hook usage shows what is missing.
2026-07-27: One owner pattern for cart/order-scoped rows — dual concrete FKs, not polymorphic
The cart-order-split stub's "polymorphic LineItem#owner" is superseded. Every
cart-or-order-owned table uses the same shape: nullable cart_id + nullable
order_id with an exactly-one validation, and #owner as a plain method
(order || cart). Applies to spree_line_items, the typed money lines
(TaxLine/Discount/Fee), and Fulfillment/DeliveryRate.
Why: 6.0's design language is concrete FKs over polymorphic type strings
(split-adjustments removes adjustable_type/source_type,
typed-stock-movements removes originator_type) — reintroducing polymorphism
on the schema's highest-traffic table in the same release would be incoherent.
It's also the cheapest migration: spree_line_items.order_id already exists
and stays permanently; only a nullable cart_id is added, and every existing
line_item.order read keeps working for order-owned rows.
Provenance ("which cart did this order row come from") needs no second FK on
the row: Order#cart_id (unique — the completion idempotency key) links order
to cart, and the retained cart keeps its own rows as the frozen at-checkout
snapshot, so post-placement additions are distinguishable. Both-columns-set
was considered and rejected — order-side copies carrying cart_id would
collide with the cart's own rows in every cart.line_items-style association.
2026-07-23: Payment-method eligibility rules + Channel→Markets allowlist target 5.7; multi-credential grooming deferred
Merchant asks (wholesale net payment vs DTC Stripe, installments above an
order-total threshold, market-bound payment methods, channels limited to
certain markets) plus a four-platform review (OSS platform C channel-scoped
PaymentMethods + PaymentMethodEligibilityChecker, OSS platform A region-scoped
payment providers, OSS platform B per-channel payment apps, the hosted leader's Payment Customization Functions + the May-2026 per-market multi-entity payments product) settled three things:
6.0-payment-method-rules.md—Spree::PaymentMethodRuleSTI (Channel / Market / OrderTotal / CustomerGroup rules), mirroring the PromotionRule/PriceRule/OrderRoutingRule house pattern; enforced through the singleOrder#collect_frontend_payment_methodsseam; storefront-only (admin/backoffice bypasses). Supersedes the "payment methods have no distribution concept" rationale in5.6-6.0-single-store-promotions-payment-methods.md— the single-store FK stands, eligibility is layered on via rules.6.0-channel-markets.md— optional Channel→Markets allowlist (spree_channel_markets, empty = all markets), enforced in market resolution, the Store API markets reference endpoints, and order validation. Composes withMarketRuleabove.- Deferred for grooming: multiple provider credentials / legal entities
in one store (two Stripe accounts split by channel or market, the hosted leader's
multi-entity model). Candidate shapes — separate PaymentMethod records per
channel/market (OSS platform C/OSS platform A style; needs the Admin API
types"already installed" filter relaxed) vs per-channel credential mapping on one record (OSS platform B style) — plus the legal-entity attribution question (per-entity payouts, compliance, reporting). No plan yet; do not implement.
2026-07-22: Analytics semantic layer ships live-OLTP-first; fact tables are a later adapter
6.0-analytics-semantic-layer.md deliberately inverts the "fact tables as the
default substrate" instinct: Phase 1 ships the metric/dimension registry, the
query contract, and a live-OLTP adapter compiling through store associations —
zero new infra, correct on SQLite dev installs, proven viable at typical scale
by the 5.6 Pulse dashboard queries. Because every consumer speaks the contract,
storage swaps (incremental fact tables in 6.1, ClickHouse for Enterprise)
without touching consumers. This gets the developer extension point — the
actual replacement for Spree::Report authoring — out a release earlier and
keeps the hard restatement problems (refunds restating the original day, order
edits, timezone-of-record) off Phase 1's critical path.
Also decided: forced scopes (store, one-currency-per-money-query, vendor) are
compiler-enforced below every consumer including the future AI layer; unknown
query members 422 rather than being silently dropped (the Ransack
silently-dropped-predicate bug from 2026-07-22 is the cautionary tale); and
ankane/rollup / ankane/blazer are design references, not dependencies
(float-only values + PG-only dimensions, and a raw-SQL trust model with no
store scoping, respectively). Until Phase 1 lands: no new hand-rolled
aggregate endpoints anywhere in spree/api.
2026-07-21: Order routing rules get admin management in the React dashboard only
Per-channel Spree::OrderRoutingRule management (the Phase 2 "Admin API + SPA
settings page" slice of 6.0-order-routing.md) ships ahead of the rest of
Phase 2: Admin API v3 CRUD nested under channels
(/channels/:channel_id/order_routing_rules) + top-level
/order_routing_rules/types discovery, @spree/admin-sdk resource, and a
routing-rules editor inside the dashboard's channel edit sheet (drag-to-reorder,
active toggles, schema-driven preference forms via PreferencesForm).
No legacy Rails admin UI — routing rules are managed exclusively in the React dashboard. The legacy admin's channel form keeps only the strategy override select it already had. New admin surfaces target the SPA; the legacy admin is in maintenance mode for 6.0.
2026-07-20: Wholesale applicant company name stays in metadata until 6.1 Company accounts
The gated wholesale portal's apply form collects a company name. Considered
promoting it to a nullable company column on spree_users as a pre-6.1
stepping stone — mechanically fine (core already migrates that app-owned table:
add_phone_to_spree_users, add_first_name_and_last_name_to_spree_users), and
it would buy Ransack searchability and first-class serializer/export support.
Rejected for now. Free-text company on the customer becomes a second source
of truth the moment Spree::Company lands in 6.1, and free text doesn't dedupe
("Acme" / "Acme Ltd" / "ACME Limited"), so the backfill into real Company
records is messy and the column lingers as a deprecated shadow. Applicant
company is stored in customer metadata ({ company: "…" }) instead — already
supported end-to-end by RegisterParams + the Store customers controller, no
migration, no invented field.
The proper implementation is the Company → CompanyLocation → CompanyContact
tree in 6.0-channels-catalogs-b2b.md Phase 2 (6.1). Note that plan's
decision 7: approval workflows, role-based permissions, purchase limits, and
invoice management are deferred to a dedicated B2B plan after 6.1 — so the
demo's manual "admin adds the customer to the Wholesale group" approval step is
intentional and survives past 6.1 until that plan exists.
Also decided: no company row in the legacy Rails admin customer view. Metadata is exposed by the Admin API v3 customer serializer (React dashboard shows it); the legacy admin renders customer metadata nowhere and stays that way.
2026-07-19: Database search provider is the out-of-the-box default; Meilisearch becomes opt-in
spree-starter and create-spree-app no longer provision Meilisearch. The Docker
compose files stop running the meilisearch service and stop hardcoding
MEILISEARCH_URL, so Spree::SearchProvider::Database — already the core
default and already the effective default on the native (no-Docker) path — is
now the default on every install path. One less always-on container (image
pull, RAM, volume) for the common case; Spree::SearchProvider::IndexJob /
RemoveJob never enqueue under the DB provider (indexing_required? is
false), so the default stack also stops paying per-save indexing jobs.
Opt-in stays config-only: commented service/depends_on/env/volume blocks in
both compose files + MEILISEARCH_URL, then spree:search:reindex. The
meilisearch gem stays in the starter Gemfile so the prebuilt
ghcr.io/spree/spree image retains the capability — enabling Meilisearch on
the quick-start compose must not require a custom image build. Docs continue
to recommend Meilisearch for production-scale catalogs (see
5.4-search-provider.md); this changes what's provisioned by default, not the
recommendation.
2026-07-15: Basic Stripe Connect payouts move to OSS; Enterprise repositions on money operations
spree/spree#13323 originally kept "Stripe Connect onboarding, KYC, automatic
payouts" in Enterprise. Amended by the issue author: the basic Stripe Connect
path ships open-source in the monorepo, registering
Spree::PayoutProvider::StripeConnect — Express-account onboarding (hosted link +
account.updated status webhook) and on-fulfillment Stripe::Transfer execution
(source_transaction-tied), plus mapping the vendor payout schedule onto Stripe's
native schedule. It lands alongside the Stripe core gateway being pulled into the
monorepo from the standalone spree_stripe repo — only the payment-sessions-API
gateway classes come over (likely into spree/core); the legacy v2-API/storefront
code in that repo stays behind.
Rationale: the closest OSS competitor ships baseline Stripe transfers free —
"money moves automatically" is the demo that sells — and transfers are inseparable
from basic onboarding (a Stripe::Transfer requires a connected account), so a
transfers-only OSS cut was never buildable.
Enterprise keeps the money operations: automatic refund clawbacks (prorated
transfer reversals + negative-balance netting), KYC/account-health workflows beyond
hosted onboarding, ledger⇄Stripe reconciliation, payout reports incl. DAC7,
marketplace-facilitator taxes, and the Shopify/WooCommerce vendor apps. Ledger
correctness (reversal rows) stays OSS in every mode — only pullback execution is
paid. "Core runs the happy path; Enterprise operates the unhappy paths and
compliance at scale." #13323 to be updated accordingly.
Plan: 6.0-multi-vendor-marketplace.md.
2026-07-14: Spree::Vendor = marketplace seller; procurement source renamed Spree::Supplier
Superseded in part by 2026-08-17. The split stands — the marketplace seller and the procurement source are separate models — but the marketplace model is now
Spree::Seller(sel_,spree_sellers), notSpree::Vendor.Spree::Supplieris unchanged.
Two 6.0 plans introduced a Spree::Vendor: the marketplace seller
(6.0-multi-vendor-marketplace.md, prefix ven_) and the purchase-order
procurement source (6.0-inventory-operations.md, prefix vnd_). Same class
name, same spree_vendors table, different domains — a hard collision.
Resolution: the marketplace owns the Vendor name. It is locked publicly
(spree/spree#13323, the user docs' "Vendors" area, the legacy Enterprise gem's
ven_ prefix and its production data). The inventory-operations model is renamed
Spree::Supplier (spree_suppliers, prefix sup_, /api/v3/admin/suppliers) —
matching the hosted leader's purchase-order vocabulary and standard ERP terminology. They
are different lifecycles: a supplier is an address-book entry the merchant buys
stock from; a vendor is an onboarded selling party with users, commission, and
payouts.
Hybrid marketplaces (operator buys wholesale from a marketplace seller and
resells first-party) can later bridge the two with an optional
Spree::Supplier#vendor_id link — not scoped for 6.0.
2026-06-16: Split 6.0 into Marketplace, defer B2B to 6.1
6.0 is themed as the Marketplace release, headlined by open-sourcing the
multi-vendor marketplace (per spree/spree#13323) alongside React dashboard GA and
the architecture/rename wave. B2B (Catalog + Company/CompanyLocation/CompanyContact
from 6.0-channels-catalogs-b2b.md Phase 2) moves to 6.1, marketed as the B2B
release. Rationale: a crowded 6.0 dilutes the launch; one sharp headline per release
earns more buzz, and the B2B Phase 2 work is plan-only (not started), so deferring
it frees capacity for the multi-vendor open-sourcing rather than parking finished code.
Multi-vendor OSS/Enterprise boundary per #13323 as of this date (superseded in
part by 2026-07-15 above — basic Stripe Connect execution later moved to OSS):
core ships Vendor identity, order splitting, the commission engine (with EU
commission taxation), the payout ledger (Spree::VendorPayout — records what's
owed, provider-agnostic), vendor dashboard, CSV import/export, and Vendors API;
Enterprise keeps Stripe Connect/KYC and the execution of payouts (a
PayoutProvider::StripeConnect strategy), payout reports, Shopify/WooCommerce
sales-channel apps, and the category mapper. New plan:
6.0-multi-vendor-marketplace.md. The legacy Enterprise multi-vendor module is
rebuilt as native core models on top of the 6.0 Cart/Order split.
2026-03-17: Rename StockItem → StockLevel
Owned by 6.0-typed-stock-movements.md as of 2026-08-13 — it ships as that
plan's Phase 0, ahead of the new movement columns, so they are born beside a
final name. Bridges: constant, association and column aliases plus dual-emitted
stock_item.* events for one release; the prefix change and the endpoint rename
take the break.
Spree::StockItem → Spree::StockLevel, spree_stock_items → spree_stock_levels.
Prefix ID: si_ → sl_.
Every other platform uses "level" for this concept — the hosted market leader (InventoryLevel),
OSS platform A (InventoryLevel), OSS platform C (StockLevel), OSS platform B (Stock). "Item" sounds
like a physical object; "level" correctly describes "the quantity of a variant at
a location."
Part of the 6.0 model rename wave. Includes renaming the FK columns
(stock_item_id → stock_level_id) on StockMovement, StockReservation, and
any other referencing tables.
2026-03-16: Rename user_id → customer_id on customer-facing models
As part of the User → Customer rename (6.0-platform-auth.md), rename user_id
foreign key columns to customer_id on all models where the FK references a
storefront customer (not an admin user).
Rename to customer_id (11 models — FK references Spree.customer_class):
spree_orders.user_id→customer_idspree_addresses.user_id→customer_idspree_credit_cards.user_id→customer_idspree_store_credits.user_id→customer_idspree_wishlists.user_id→customer_idspree_gift_cards.user_id→customer_idspree_gateway_customers.user_id→customer_idspree_payment_sources.user_id→customer_idspree_newsletter_subscribers.user_id→customer_idspree_promotion_rule_users.user_id→customer_idspree_customer_group_users.user_id→customer_id(polymorphic —user_typealso renames tocustomer_typesobelongs_to :customer, polymorphic: trueresolves)
Keep as user_id (5 models — FK references Spree.admin_user_class or is polymorphic):
spree_imports.user_id— admin who ran the importspree_exports.user_id— admin who ran the exportspree_reports.user_id— admin who generated the reportspree_state_changes.user_id— references the order's customer (set fromorder.customer_id), not an admin. Kept asuser_idbecause it's an internal state-audit log, not customer-facing API surface; thebelongs_to :userassociation resolves toSpree.customer_class.spree_user_identities.user_id— polymorphic (Customer or AdminUser)
Single migration renames all 11 columns. Model associations updated:
belongs_to :user → belongs_to :customer with class_name: Spree.customer_class.
2026-03-16: PaymentMethod and DeliveryMethod become SingleStoreResource
Both PaymentMethod and DeliveryMethod (renamed from ShippingMethod) switch to
SingleStoreResource with direct belongs_to :store.
In practice, different stores have different currencies, zones, and provider accounts — sharing the same payment/delivery config across stores is rare. If a merchant wants the same config on two stores, they create two records.
Corrected 2026-07-27: the original entry claimed both models migrate away
from multi-store join tables (StorePaymentMethod, StoreShippingMethod).
That was only half true — spree_store_shipping_methods / a
StoreShippingMethod model never existed; ShippingMethod has always been
globally scoped (no store association of any kind). The PaymentMethod half was
real and shipped in 5.6 (5.6-6.0-single-store-promotions-payment-methods.md).
For ShippingMethod/DeliveryMethod, store_id is therefore a greenfield
addition with a derived backfill (no join table to read from), owned by
6.0-delivery-rate-provider.md Phase 1 — the provider needs the store to
resolve Spree::Integration credentials. Backfill: Store.default for
single-store installs; zone-overlap heuristic + loud logging for multi-store.
Note this is a behavior change for multi-store installs (globally-visible
methods become single-store), not a mechanical migration.
2026-03-16: Fix promotion rule/action STI namespacing
REVERSED 2026-07-29 (Damian, during Wave 6 of the core rewrite): the rename
shipped briefly on feature/6-0-core-rewrite and was rolled back — class-name
churn wasn't required by any 6.0 feature, and it forced an STI type-column
data migration plus extension breakage for a purely cosmetic consistency win.
Promotion rules/actions stay Spree::Promotion::Rules::* /
Spree::Promotion::Actions::* (incl. CreateItemAdjustments, which now writes
typed Spree::Discount rows under its legacy name). The STI-namespace
convention below still applies to NEW hierarchies; existing promotion classes
are grandfathered.
Original decision:
Rename Spree::Promotion::Rules::* → Spree::PromotionRules::* and
Spree::Promotion::Actions::* → Spree::PromotionActions::*.
The convention for STI subtypes is Spree::{BaseClass}s::{Subtype} — pluralized
base class as the namespace. Every other hierarchy follows this already:
Spree::PriceRules::VolumeRuleSpree::Metafields::ShortTextSpree::CollectionRules::Tag(from categories plan)Spree::ReimbursementType::Credit
Promotion was the only one nesting under the parent model (Spree::Promotion::Rules)
instead of the base class (Spree::PromotionRules).
Changes:
- Move files from
app/models/spree/promotion/rules/→app/models/spree/promotion_rules/ - Move files from
app/models/spree/promotion/actions/→app/models/spree/promotion_actions/ - Data migration: update
typecolumn inspree_promotion_rulesandspree_promotion_actions(e.g.,Spree::Promotion::Rules::Product→Spree::PromotionRules::Product) - Deprecation aliases for one release
2026-03-16: Normalize state → status across all models
Settle on status as the standard column name for state machines. Newer models
(Product, PriceList, PaymentSession, Import, Invitation) already use status.
Order.state and Adjustment.state are removed entirely by other 6.0 plans
(cart-order-split, split-adjustments). Five remaining models need a column
rename from state → status in 6.0:
- Payment —
state→status - Shipment —
state→status - InventoryUnit —
state→status - ReturnAuthorization —
state→status - GiftCard —
state→status
Single migration renaming all five columns. State machine declarations updated
to state_machine :status, initial: .... Deprecation aliases
(alias_attribute :state, :status) for one release.
Models already correct (no change): Product, PriceList, PaymentSession,
PaymentSetupSession, Import, ImportRow, Invitation, ReturnItem
(reception_status/acceptance_status), Reimbursement (reimbursement_status).
2026-03-28: Simplify metafield visibility — display_on → storefront_visible boolean (6.0)
Replace three-way display_on (both/front_end/back_end) with storefront_visible
boolean (default: true) on CustomFieldDefinition. front_end-only was already
excluded from MetafieldDefinition::DISPLAY and never made sense.
This makes the two-system boundary razor-sharp:
- Custom Fields (storefront_visible: true) = public structured data
- Custom Fields (storefront_visible: false) = admin-only structured data
- Metadata = private developer-owned data (never exposed)
Matches OSS platform C (public: boolean) and OSS platform B (visibleInStorefront: boolean).
Ships with the 6.0 model rename wave. See 5.4-6.0-custom-fields-rename.md.
2026-03-16: Consolidate metadata — drop public_metadata, keep metadata JSON column
Amended 2026-08-09 on one point:
public_metadatais merged intometadata, not discarded. "Unused" holds for Spree's own code but is not provably true of host applications, and a dropped column has no rollback. The merge runs inside the migration. Everything else below stands — see the 2026-08-09 entry at the top of this file.
Drop public_metadata column (never exposed in Store API, unused). Rename
private_metadata → metadata in the database. Simplify the Spree::Metadata
concern to a single metadata JSON column with no alias indirection.
Metadata (JSON column) is a permanent, first-class system — the schemaless
developer escape hatch for integration IDs, sync state, ad-hoc flags. No
definition required, one-step API:
PATCH /product { metadata: { erp_id: "123" } }. Never exposed in Store API
(Stripe convention: write-only). Metadata is here to stay.
Metafields (→ Custom Fields in 6.0, see 5.4-6.0-custom-fields-rename.md)
stay as merchant-defined structured data — typed values (short_text, number,
boolean, json, rich_text, long_text), require a MetafieldDefinition, have
storefront_visible boolean, searchable, CSV importable. With the
ProductType plan (6.0-product-types.md), metafields become schema-enforced
custom attributes driven by ProductType.
Two systems, two purposes, no overlap. No consolidation into one. Metadata for machines, metafields/custom fields for humans.
2026-03-10: Product descriptions stay as plain column
Considered Action Text. Rejected for API-first performance — serializing rich text adds overhead for every product response. Also in the new Admin UI we will use TipTap for rich text editing.
2026-07-27: Delivery rate provider wraps the Estimator — shipping calculators stay
Reverses the original 6.0-delivery-rate-provider.md key decision to delete
ShippingCalculator + Calculator::Shipping::* in favor of a pricing_type
enum. The enum cannot reach parity (FlexiRate/PriceSack inexpressible, FlatRate
suppression thresholds and DigitalDelivery's available? predicate lost) and
breaks every merchant calculator subclass with no migration path.
Instead the provider is dispatched at the single point where Stock::Estimator
calls calculator.compute(package); the Estimator keeps method filtering, VAT
gross-up, tax resolution, and default selection. Internal delegates to the
calculator — zero behavior change is the acceptance criterion. All three
Estimator entry points (Shipment#refresh_rates, OrderRouting::Strategy::Rules,
Cart::EstimateShippingRates) get provider support with no per-site changes.
Accepted asymmetry: the tax provider still removes its calculators — tax
calculators were pure math with no merchant extension surface; shipping
calculators are a documented extension point.
2026-07-27: Zone → DeliveryZone ships in 6.0, owned by a dedicated plan
A review found the old "drop Spree::Zone entirely" wording in the tax and
delivery-rate plans had no owner for ~183 non-spec references
(Spree::Current.zone / default_tax_zone, Market#tax_zone,
Order#tax_zone, VatPriceCalculation, Pricing::Context, permission sets,
admin Zone CRUD, and the Zone.global factory monkey-patch every
:shipping_method factory depends on). Briefly scoped back the same day, then
reinstated for 6.0 by user decision — 6.0 is the one breaking-change window;
big re-architecture does not wait for 6.1.
Final shape: tax decouples via 6.0-tax-provider.md Phase 5 (TaxRate direct
country/state FKs, tax readers rewritten onto TaxRate.for_address /
Spree::Current.tax_country); everything else is owned by the new
6.0-delivery-zones.md — DeliveryZone + typed members with country-scoped
postal-code ranges/prefixes, admin CRUD swap, factories rework
(worldwide-by-default methods, Zone.global retired), and the final
spree_zones/spree_zone_members drop at end of 6.0.
2026-07-27: Promotion stacking targets 6.1; 6.0 ships winner-only but stacking-ready
Stacking is among the most-requested features. Initially slated for 6.0 (the
discount engine is being rewritten there anyway), retargeted to 6.1 the same
day: stacking is purely additive — no schema change, no breaking window
needed — and 6.0 is already the heaviest release in Spree's history. Deferring
costs nothing structurally because the expensive prerequisites ship in 6.0
regardless (6.0-6.1-split-adjustments.md): typed Discount tables that permit
multiple rows per adjustable, per-adjustable clamping, and
prorate-over-the-remaining-discounted-base (needed for order-level
distribution either way), with winner-only selection isolated in a single
adjuster method.
6.1 adds: hosted-leader-style Promotion#combines_with flags (per class —
item/order/shipping; combining candidates all apply clamped, non-combining
compete winner-takes-all, default off so migrated promotions keep today's
behavior), dashboard UI, API fields. Industry: the hosted market leader combinesWith
(merchant-controlled), OSS platform A stacks all valid with caps, OSS platform C stacks
priority-ordered, OSS platform B winner-only — merchant control is the differentiated
middle.
2026-07-28: Customer/AdminUser models ship in the gem — no host-app model, no auth generators
Review of 6.0-platform-auth.md surfaced an unstated inversion: today's default
production setup is a host-app-owned Devise Spree::User (scaffolded by the
spree/authentication/devise generator), while the plan's gem-shipped
Spree::Customer/Spree::AdminUser were only implicit. Made explicit:
default models live in spree_core like any other Spree model; the host app
owns no auth code by default; both authentication generator directories
(devise/ AND custom/) are deleted. The only historic reason for an
app-local user model was Devise's devise_for/devise :... requirement —
dropping Devise removes it.
Rationale: auth is the worst place for generated-then-orphaned code (lockout,
rate limiting, future MFA never reach a scaffolded model without hand-merges);
matches the 6.0 strategy of customization via configuration over Rails code in
the host app. Custom user classes stay fully supported via
Spree.customer_class + a single include Spree::CustomerMethods (which
absorbs UserAddress + UserPaymentSource) — a documented recipe, not a
generator.
Migration bonus: Devise's encrypted_password is a plain bcrypt digest — the
same format has_secure_password reads — so the rake task migrating
spree-starter installs onto spree_customers copies it to password_digest
and no customer resets their password (task aborts loudly if
Devise.pepper is set).
2026-07-29: Phase 2 user→customer data migration — copy-preserving-id, in-place admins, single clash-aware migration
Implementing Phase 2 of 6.0-platform-auth.md settled several mechanics.
Customers are a row copy, admins are in place. The 6.0 split is already
two-table (spree_users=customers, spree_admin_users=admins; admin-ness is a
polymorphic spree_role_users.user_type, not a table). So spree_customers is a
new table and its data comes from copying spree_users — it cannot be a
rename_table (the create migration always runs, so the target already exists;
fresh installs have no spree_users; and spree_users carries Devise cruft).
spree_admin_users keeps its table and its class name Spree::AdminUser, so
admins never move — the task only backfills password_digest from the legacy
encrypted_password.
Copy preserves primary keys so the already-renamed customer_id FKs
(2026-03-16 entry) still resolve with no id remap. This is the first repo task to
insert explicit ids, so it also resets the Postgres sequence afterward
(reset_pk_sequence!, guarded to PG) — no prior precedent because taxon→category
preserved ids via rename_table. With ids preserved, the only polymorphic fixups
are type-string re-points Spree::User → Spree.customer_class on
spree_role_users, spree_refresh_tokens, spree_user_identities,
spree_api_keys (created_by_type + revoked_by_type), and
spree_customer_group_users (whose type column renamed user_type →
customer_type with the 2026-03-16 FK rename — must be re-pointed too or
memberships dangle); admin-typed rows stay. The task reads the legacy table by
name only (never LegacyUser, deleted once all phases ship together), aborts on
Devise.pepper (and, since Devise is gone in 6.0 and a pepper can't be
introspected, aborts when Devise is absent unless CONFIRM_NO_PEPPER=true),
preflight-aborts on blank-email or email-conflict rows (SKIP_INVALID_ROWS=true
to skip), and leaves spree_users in place as a safety net.
Single clash-aware create migration. The two Phase-1 create migrations merged
into 20260728000000_create_spree_customers_and_admin_users — a non-colliding
name, because install:migrations de-dupes engine migrations by name and every
existing app already has a create_spree_admin_users, so the gem's same-named
migration is skipped and never runs on upgrades. The merged migration creates
spree_customers cleanly and guards the admin side
(create … unless table_exists?, add_column :password_digest unless column_exists?). password_digest is added alongside encrypted_password,
never a rename — nothing is lost, and the backfill has both columns to read.
Path B is a recipe, not gem code. Keeping a custom user model needs no new
concern: on the app's own model, include Spree::CustomerMethods +
has_secure_password validations: false + alias_attribute :password_digest, :encrypted_password (or a column rename). The alias must live on the app model —
a blanket alias in CustomerMethods would shadow the default Spree::Customer's
real password_digest and break has_secure_password on it.
The 5.6→6.0 upgrade guide (docs/developer/upgrades/5.6-to-6.0.mdx) doesn't exist
yet (6.0 in-dev); Path A/B developer guidance currently lives in the task's desc,
the 5_6_to_6_0 manifest notes, and this plan. It moves to the mdx when the full
6.0 upgrade guide is authored.
2026-07-29: Account lockout enforced in the auth strategy; thresholds config-driven
Phase 4 of 6.0-platform-auth.md was mostly already shipped (RefreshToken issue/rotate/revoke,
login/refresh/logout endpoints, Rails rate_limit throttling). The remaining gap was that the
lockout methods on Customer/AdminUser were dead code — nothing in the login path called them.
Decisions made wiring it up:
Enforcement lives in EmailPasswordStrategy, not the controllers. The strategy is the single
point both store and admin login flow through, and it's the only layer that holds the user object on
a failed password (the controllers get a generic failure). So authenticate checks locked?
before validating, record_failed_attempt! on a bad password, and reset_failed_attempts! on
success. All calls are respond_to?-guarded so a Path-B custom customer_class without the lockout
methods still authenticates.
Thresholds moved to Spree::Config, logic to a shared concern. The identical
locked?/record_failed_attempt!/reset_failed_attempts! on both models (with hardcoded 5 /
30.minutes) were extracted into Spree::AccountLockout (core concern) reading
Spree::Config[:max_failed_login_attempts] (5) and [:lockout_duration] (1800s). These are core
prefs (not Spree::Api::Config) because the concern lives on core models, which can't depend on the
API config.
Distinct lockout message ("Account temporarily locked. Try again later.") over a generic invalid-credentials response — industry-common, and login is already rate-limited so the marginal enumeration signal is low. It's a single return string, easily switched to the generic message if a stricter anti-enumeration posture is wanted (Spree's login/password-reset are otherwise anti-enumeration).
Refresh-token hashing at rest was declined (tokens are already random + expiring; login
throttled). Admin logout gained a rate_limit to match the store side. Following the repo's
rate-limit spec convention, no throttle-trip test was added (those depend on the test cache store);
the existing specs cover response format/headers/config.
2026-07-29: Devise fully removed from core/api; legacy models deleted, table kept
Phases 5 & 6 of 6.0-platform-auth.md, scoped to spree/core + spree/api (spree/admin removed
wholesale by 6.0-admin-spa.md; the spree-starter / 5b changes are a separate pass).
Legacy models deleted, spree_users table retained. Spree::LegacyUser /
Spree::LegacyAdminUser are gone (no runtime fallback — Spree.customer_class has no default,
Role is dynamic, and only four specs named the constant, all repointed to Spree.customer_class).
The spree_users table is deliberately kept as the Phase 2 migration's safety net — its teardown
is a separate later operator task, and the 4.3 baseline migration still materializes it on fresh
installs.
Devise bridges removed, not kept. Both Spree::AdminUserMethods::DeviseNotifications and
CustomerMethods::SkipPasswordValidation were deleted. They were inert on the gem's
has_secure_password models: admin auth emails flow through the admin_user.password_reset_requested
event subscriber → AdminUserMailer (not send_devise_notification), and password-less
admin-created customers rely on has_secure_password validations: false rather than a
password_required? override. The defined?(Devise) guards in the migrate-users rake task are the
one Devise reference kept — they're defensive checks for installs migrating off Devise.
spree:install scaffolds no auth by default. With the generators deleted, the root-gem install
generator's --authentication default moved to nil (was devise): a plain install writes no auth
helpers because the gem owns auth (Spree::Customer/Spree::AdminUser + the initializer sets the
class names). dummy stays available and is what the test harness passes explicitly via
common_rake, so test_app is unaffected.
Deprecation aliases kept to 6.1. The earlier Phase 6 plan to drop the user_class alias in 6.0
is superseded — Spree.user_class, Spree::UserMethods, Spree::DeprecatedCustomerAlias, and the
:user/:admin_user factory aliases all remain through 6.0 (in-code comments already tag them 6.1).
Docs. The Devise-as-default pages were rewritten around gem-owned auth + the custom-model recipe,
and Spree.user_class references swept to Spree.customer_class. Spree::OauthAccessToken is a
no-op (extracted upstream). Deferred: the 6.0 upgrade guide, the spree_users teardown task, and the
unrelated search-area multi_search alias removal.
2026-07-28: Core-rewrite implementation decisions (cart/order split + fulfillment + split adjustments)
Interactive review settled everything blocking implementation start; task
sequencing lives in docs/plans/6.0-core-rewrite-tasks.md (7 waves, data
rake tasks last).
- ProductType prerequisite is the minimal Phase 1 slice — rename +
store ownership +
fulfillment_types+Product#product_type_id. The rest of6.0-product-types.md(custom-field-definition join, live template propagation, its API/dashboard) ships as its own effort. spree_adminis dropped from the spree-starter Gemfile on the 6.0 line. The legacy admin's adjustments/checkout screens hard-break whenSpree::Adjustmentand the Order state machine are removed; rather than limp on aliases, the dev server stops loading the gem — the React dashboard is the only admin. The gem stays in the monorepo untouched (it's already out of the CI matrix) until its 6.0 deletion; one-release constant aliases (Spree::Shipment = Spree::Fulfillment, …) still ship for extensions and the emails gem.checkout_flow/insert_checkout_stepare hard-removed in 6.0 — no translation shim (machine transitions have noCheckout::Registryequivalent); migration guide instead.DeliveryRatecarries no owner columns — it derivesownerthrough its fulfillment. The dual-FK pattern covers LineItem, the typed money lines, and Fulfillment; rates were never directly order-linked.- Cart reaper defaults: guest 30d, customer 90d, empty carts 48h (config preferences; carts with authorized/pending payment sessions are never reaped, unconditionally).
shipment.*webhooks dual-emit for exactly one release, dropped in 6.1.ready_for_pickupis a first-class Store API status (not mapped ontoready); the order-level rollup still reportsready.partially_canceledbecomes a derived predicate over child cancellations, not a stored status value.
2026-07-29: Delivery methods stay regional; a reference multi-carrier rate provider ships in the monorepo
Question raised during 6.0 review: does one carrier method (e.g. UPS) need
per-market rates/calculators, or is "UPS (Europe)" + "UPS (North America)" as
separate DeliveryMethod rows a modeling smell?
Competitor survey says the split IS the industry shape — every platform regionalizes the sellable method and shares only the carrier integration:
- Shopify: rates live inside Shipping Zones (per profile); a zone rate is a manual definition or a "participant" of a globally-registered CarrierService. No cross-zone method entity exists.
- Medusa v2: a Shipping Option belongs to exactly one Service Zone plus a
fulfillment provider module; flat prices come from the pricing module
(per currency/region),
calculateddelegates to the provider. - Saleor: Shipping Methods live inside Shipping Zones with per-channel price listings; external carriers are Shipping Apps returning dynamic methods per checkout.
- Vendure: ShippingMethod is standalone (eligibility checker + calculator strategies) but channel-scoped — idiomatically still one method per region.
Decision 1 — no cross-market method entity. DeliveryMethod +
DeliveryZone already matches the consensus: method rows are cheap and
regional; carrier logic is shared one level down. Built-in calculators carry a
single preferred_currency, so multi-currency stores need per-market methods
regardless. Nothing to build.
Decision 2 — the monorepo ships one reference DeliveryRateProvider
backed by a multi-carrier aggregator (Shippo or EasyPost — pick pending API/
pricing review), mirroring the Stripe reference-gateway decision (2026-07-15).
One integration returns live UPS/FedEx/DHL/USPS rates, which dissolves the
per-carrier-per-market method sprawl for the majority of installs: one
"Carrier shipping" method per market, the provider returns whatever serves the
address. It also makes the reference implementation the first real consumer of
the 6.0-delivery-rate-provider.md interface — validating the seam the way
payment sessions were validated by Stripe. Built-in calculators remain the
manual-rate path for the minority (2026-07-27 reversal unchanged).
2026-07-29: Geo modeling — Markets, DeliveryZones and StockLocations stay disjoint
Two follow-up questions from the same 6.0 review: should Markets link to DeliveryZones, and should StockLocations link to DeliveryZones? Competitor survey on both:
Markets ↔ delivery zones. Shopify (Markets vs profile shipping zones) and Medusa (Regions vs service zones) keep them fully disjoint — independent country lists, merchant coordinates, and Shopify's "market country with no shipping coverage" dead-end is a known sore point of that camp. Saleor links shipping zones to channels (m:n + per-channel price listings); Vendure reuses one country-granular Zone entity as channel defaults for tax and shipping — the unified model, bought at the cost of country-only granularity.
Decision: stay disjoint. Two structural reasons resist merging across
every platform surveyed: granularity (markets are country-level commercial
units; delivery coverage legitimately goes sub-country — states, postal
prefixes/ranges, remote-island carve-outs) and cardinality (one EU market
maps naturally onto several delivery zones — standard / remote / oversized).
Spree already carries a stronger coordination guardrail than the disjoint
camp: MarketCountry#country_covered_by_shipping_zone refuses market
countries the store cannot deliver to. The channel axis heads the Saleor
direction separately via 6.0-channel-markets.md. If more convenience is
ever wanted, it is a dashboard affordance ("create delivery zone from this
market's countries"), never a schema link.
Stock locations ↔ delivery zones. Here the industry splits 3–1 the other way: Shopify's delivery profiles nest location groups that each own their zones+rates; Medusa roots the whole hierarchy at the stock location (StockLocation → FulfillmentSet → ServiceZone → ShippingOption); Saleor links warehouses ↔ shipping zones m:n and allocates stock through that link. Only Vendure leaves origin/coverage coordination to code (allocation strategies).
Decision: no StockLocation↔DeliveryZone schema link — compose it at the
method level. Spree expresses per-origin coverage as
DeliveryMethod↔StockLocation (the spree_delivery_method_stock_locations
join shipped in the 6.0 rename migration, currently dormant/unwired) times
DeliveryMethod↔DeliveryZone — "UPS EU ships from the Poland warehouse" is a
method restricted to that location with EU zones. That is Shopify's
location-group→zones expressiveness without a third geo entity. Wiring the
dormant join (association + Estimator/Coordinator filtering + admin API
exposure) is follow-up work on 6.0-fulfillment-and-delivery.md, which
already uses the table for pickup locations. The Medusa/Saleor-style
allocation question — choosing the warehouse by destination — is the order
routing seam (6.0-order-routing.md strategies), not geo schema.
2026-07-29: Delivery-method eligibility moves out of calculators into DeliveryMethodRule
Dashboard review surfaced min/max item-total and weight bounds rendering
inside the rate-calculator preference form. They are eligibility, not
pricing — and structurally worse than they look: the four bounds exist only
on Calculator::Shipping::FlatRate (no other calculator has them), are
enforced by compute_package returning nil rather than the
available?(package) hook the Estimator consults, and would be silently
LOST on provider-priced methods once 6.0-delivery-rate-provider.md lands
(the provider bypasses the calculator that carries them).
Competitors uniformly separate the concerns: Shopify puts weight/price conditions on the zone rate, Saleor uses method columns (+ per-channel price bounds), Medusa v2 attaches typed ShippingOptionRule records, Vendure gives ShippingMethod an eligibility-checker strategy parallel to its calculator.
Decision: Spree::DeliveryMethodRule STI on DeliveryMethod — the fifth
instance of the house rule pattern and the symmetric sibling of
6.0-payment-method-rules.md (ItemTotal + Weight first; Channel/Market/
CustomerGroup later, in lockstep with the payment set). One enforcement
seam: the Estimator's method filter, so calculator- and provider-priced
methods obey the same eligibility; no admin-bypass concept (the Estimator is
the only rate source, and these are logistics constraints). FlatRate's
bound preferences become a one-release deprecation bridge with a data task.
Plan: 6.0-delivery-method-rules.md — targeted 6.0 directly; per the same
review, the pending 5.7 plans are expected to retarget 6.0 (skipping a 5.7
release for a faster 6.0 launch). Open questions resolved interactively the
same day: WeightRule uses the store's implicit unit (raw-number comparison,
legacy parity); rules are method-scoped only (no zone context — per-region
bounds are separate methods); Phase 1 ships with the 6.0 core-rewrite
finishing work, Channel/Market/CustomerGroup later with payment rules.
2026-07-29 — Admin discount application follows the Saleor shape
How should an admin apply a discount to an order in the dashboard? Competitor survey: Shopify draft orders take only manual discounts (order- or line-level custom amount/percent with a reason) — codes are a checkout concept the buyer redeems; Medusa admin drafts accept promotion codes directly; Saleor drafts take both a voucher code and a manual order discount stored as its own discount object.
Decision: the Saleor shape, split by lifecycle. Draft orders accept
discount codes post-creation via POST /admin/orders/:id/discount_codes
(same PromotionHandler::Coupon path and pending semantics as the
storefront cart endpoint — a real-but-not-yet-eligible code is stored and
activates on recalculation); completed orders refuse codes (recalculation
is frozen) and take manual typed Discount rows through the existing
/admin/orders/:id/discounts CRUD (Orders::AddManualDiscount,
largest-remainder distribution, resum_typed_totals!). The dashboard's
promotion picker is sugar over the code path — picking a coupon promotion
fills in its code; it is not a separate application mechanism. The coupon
handler now always reports ineligibility with the retryable status code so
endpoints can tell a not-yet-qualifying code from an invalid one.
2026-07-29 — order.placed replaces order.completed; carts get their own events
Competitor survey (Shopify, BigCommerce, Medusa v2, Saleor, Vendure): every
platform with a separate cart entity namespaces its events (carts/*,
cart.*, CHECKOUT_*), and "order created" then means placed only where
drafts live in their own namespace (draft_orders/*, DRAFT_ORDER_*).
Medusa — the same single-Order-model shape as ours — uses an explicit
order.placed, and reserves order.completed for "fulfillment finished",
a direct collision with our historical name.
Decisions: carts publish cart.created/updated/deleted (5.x
abandonment-signal parity). The placement event is renamed
order.completed → order.placed — newcomers are the primary
audience and the old name misleads anyone arriving from Medusa. Per the
one-release bridge convention, 6.0 dual-emits: order.completed still
fires with an identical payload and deprecated_alias_of: 'order.placed'
in the event metadata (wildcard subscribers dedupe on it); the alias is
dropped in 6.1. The dashboard event picker offers only order.placed. order.created keeps meaning "order row exists" (admin drafts
included). Admin confirmation resends publish the targeted
order.resend_confirmation_email instead of re-blasting the placement
event. Order payloads carry cart_id (BigCommerce store/cart/converted
parity) so abandonment flows can cancel on conversion. Server-side
abandonment detection (BigCommerce store/cart/abandoned) explicitly
skipped. No separate draft-order entity and no is_draft boolean —
status = 'draft' already encodes it (cart_id does NOT: the completion
pipeline's draft copy has a cart_id while briefly draft; admin drafts
have none).
2026-07-29 — Spree 6.0 requires Rails 8.1 (7.2 support dropped)
The core gemspec already pins rails >= 8.1, < 8.2 and the deprecation
bridges lean on Rails 8.1's deprecated: association option across every
6.0 rename twin — supporting 7.2 would mean hand-rolled warn-wrappers for
all of them on a platform whose security support ends 2026-08-09, before
6.0 GA. Rails 8.1 (Oct 2025, supported to Oct 2027) also unlocks
ActiveJob Continuations for resumable long-running jobs (upgrade data
migrations, imports, bulk operations — the durable-steps half of a
Medusa-style workflow story; compensation logic stays ours, e.g.
Carts::Complete). Existing stores upgrade Rails to 8.1 on the 5.6 line
first, then take 6.0 — 5.6 remains the bridge release. CI: the MySQL
lanes were the designated old-Rails coverage (RAILS_VERSION: 7.2.0) and
could no longer bundle; they now run 8.1 like the rest — MySQL itself
stays fully supported.
2026-07-29 — Every major model carries a store_id; DeliveryZone bound now, StockLocation next
Ratifies the principle already stated in 6.0-delivery-rate-provider.md
(DeliveryMethod gets store_id there) as a standing convention: new
models carrying store-specific data always belongs_to :store through
Spree::SingleStoreResource; only genuinely global reference data stays
unscoped. Store binding also closes cross-store lookup holes structurally
— admin controllers scope current_store.<resources> instead of relying
on ability scoping alone (see the Strix findings on delivery-method
bindings, 2026-07-29).
Applied immediately to DeliveryZone — an unreleased 6.0 table, so the
creation migration gained store_id NOT NULL + per-store name uniqueness
in place, with zero bridge cost. DeliveryMethod and StockLocation
(released tables) landed on the same branch via the 5.6 single-store
pattern: nullable store_id + SingleStoreResource, per-store seeds,
manifest backfill task assigning the default store, null: false in
6.1. (Cross-store sharing is not preserved anywhere — spree_multi_store
is legacy and unsupported.) Admin lookups and runtime pickers (Estimator, Coordinator, order
routing) all go through the store associations
(store.delivery_methods / store.stock_locations) — strict semantics;
the manifest backfill is a required upgrade step before checkout. TaxRate and
TaxCategory follow inside the tax-provider plan's implementation
(noted there). Stock availability (Stock::Quantifier) intentionally
stays location-global until the 6.1 NOT NULL work — correct for
single-store installs, revisited with multi-store.
2026-07-30 — Credential homes follow cardinality: Integration for store-level connections, PaymentMethod rows for merchant entities
Provider architecture is three layers: store-owned commerce config rows
(DeliveryMethod, PaymentMethod), stateless registry-keyed provider code
(FulfillmentProvider/DeliveryRateProvider/tax engines — never hold
credentials), and Spree::Integration as the per-store credentialed
vendor connection (one row per store+type, can_connect?, admin
listing). Where credentials live is decided by cardinality, and the two
domains are deliberately opposite:
- Delivery/vendor APIs — one connection, many methods. An EasyPost
account rates every method; config rows multiply, the connection does
not. Credentials belong on the Integration singleton; provider gems
ship an Integration subclass + a stateless provider pair
(
6.0-delivery-rate-provider.md). - Payments — one credential set per merchant entity, several per
store. Two Stripe accounts are two merchants of record (separate
settlement and liability), selected per market at checkout — exactly
what PaymentMethod rows model, gated by MarketRule once
6.0-payment-method-rules.mdlands. Credentials stay on the method row; converging them onto Integration would fight its store+type uniqueness and is explicitly NOT planned.
Consequence for tax (6.0-tax-provider.md): "one Stripe connection
serves payments and Stripe Tax" only holds single-entity. Under multiple
merchants of record, tax liability follows the charging entity per
market — a Stripe Tax provider must resolve credentials consistently
with the market's selected payment entity, not via a store-singleton
Integration lookup.
2026-07-30 — Reference providers: Stripe (payments), Avalara (tax), EasyPost-or-Shippo (delivery)
One first-party reference implementation per provider seam, each
exercising its layer's canonical shape from the credential-cardinality
entry above: Stripe for payments (monorepo move per 2026-07-15 —
credentials on PaymentMethod rows, multi-entity capable), Avalara
for tax (the enterprise standard, matching the enterprise-seller target;
Integration subclass for store credentials + stateless provider writing
TaxLines with provider_id: 'avalara'; the built-in 'internal' engine
stays the OSS default), and the EasyPost-or-Shippo multi-carrier
gem for delivery rates (pick still pending; Integration + provider
pair). Stripe Tax remains buildable by third parties but is not the
reference — and carries the merchant-of-record caveat recorded above.
2026-07-30 — Service workflows: one step DSL, Carts::Complete as the stress test
Services, sagas, extension hooks and events unify under a declared step
DSL evolved from ServiceModule in place (plan:
6.0-service-workflows.md, targeted 6.0). Medusa's workflows are the DX
benchmark; the runtime stays plain Ruby in Rails transactions — no
engine, no execution-state tables. Explicit transaction/io_step
boundaries, per-step compensation, in-transaction hook extension
points and declared emit events; the consistency doctrine (step →
sync subscriber → async subscriber) ships as documentation.
Carts::Complete is the reference implementation and acceptance test:
the cart→order swap already exercises every hard property (in-lock
verification, out-of-transaction payment I/O, compensation, replay
idempotency, sweeper resume) and its spec battery must pass unmodified
after the retrofit. Durable flows compile onto ActiveJob Continuations
in Phase 2 (imports, upgrade migrations, payout runs) and may land
post-GA without blocking the DSL.
2026-08-06 — Per-product delivery exclusions are a delivery-method rule, not a product column
spree_products.excluded_delivery_method_ids (JSON array, shipped with
the fulfillment rework but never writable through any API or UI) is
dropped in favor of Spree::DeliveryMethodRules::ExcludedProductsRule —
products attached through the concrete
spree_delivery_method_rule_products join table. Rationale: an ID list
in JSON is unqueryable and unindexable portably across the three
supported databases, rots when delivery methods are deleted, and would
have needed its own bespoke API/serializer/UI surface; the rules
framework already ships the registry, nested admin CRUD, discovery
endpoint and dashboard Conditions card. It also removes the second
eligibility seam inside Stock::Package#eligible_delivery_methods —
the rules plan mandates the Estimator's rule filter as the only one.
Method-side exclusion matches Saleor (excludedProducts); Shopify and
Medusa model the inverse via shipping profiles (≈ the retired
ShippingCategory), Vendure is code-only. Companion convention — storage
by cardinality: small reference sets (channels/markets/customer groups)
stay :array preferences via normalize_id_preference; catalog-scale
references (products) get a join table, per the
Promotion::Rules::Product/ProductPromotionRule precedent. On the
wire both travel as prefixed-ID params resolved through the store scope
and accessible_by(current_ability, :show). Plans updated:
6.0-delivery-method-rules.md (owner),
6.0-fulfillment-and-delivery.md, 6.0-core-rewrite-tasks.md.
2026-08-06 — STI rule families declare their subclass registry
Spree::PreferenceSchema.registered_subclasses resolved a class's
registered subclasses by matching two hardcoded class names
(Spree::PromotionAction, Spree::PromotionRule) and otherwise
returning []. Four families had each worked around that with a private
per-class override in three different idioms (PriceRule,
OrderRoutingRule, CollectionRule, DeliveryMethodRule), and
6.0-payment-method-rules.md specced a fifth. The empty-list fallback
failed silently: find_by_api_type returned nil, so
TypedAssociations dropped typed rows from a payload with no error and
subclasses_with_preference_schema rendered empty admin pickers — the
bug that broke DeliveryMethod#rules= on first attempt.
Replaced with a declarative hook: each STI parent calls
registers_subclasses_via { <registry> } (one line), stored in a
class_attribute so STI subclasses inherit the parent's declaration —
resolving on a subclass works, which it did not before under either
scheme. A class that declares none raises
Spree::PreferenceSchema::UndeclaredRegistryError (a StandardError,
so host apps' rescue => e catches it — NotImplementedError descends
from ScriptError and would slip past). Migrated in place:
PromotionRule, PromotionAction, PriceRule, OrderRoutingRule,
CollectionRule, DeliveryMethodRule, and PaymentMethod — gateways
declare registers_subclasses_via { providers } rather than being a
special case in the resolver, so there is exactly one resolution rule.
6.0-payment-method-rules.md updated to the new form.
Known debt: the registry is a lodger inside PreferenceSchema (which
Spree::Base includes, so ~200 models carry class methods only six use),
and Spree::CalculatedAdjustments resolves an equivalent registry
separately. Extract a Spree::RegisteredSubclasses concern when a family
needs the registry without preferences — that second consumer is the
trigger, 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 a jurisdiction of their own (country_id/state_id
here; changed to country_iso/state_code on 2026-08-12, see above), 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.0-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.0-channels-catalogs-b2b.md → "Company roles and
approvals".
2026-08-12 — OpenTelemetry: notifications in core, spans in an optional gem, traces only
Decision: Spree ships first-class OpenTelemetry support
(docs/plans/6.0-opentelemetry.md) as two layers. Core's instrumentation
contract is ActiveSupport::Notifications — core takes no OpenTelemetry
dependency, and the notification catalog (workflow perform/step/hooks,
events dispatch, webhook delivery, payment gateway boundary) becomes public
API with the same additive-only rule as workflow hook keys. A new optional
top-level engine spree/opentelemetry (gem spree_opentelemetry, beside
core/api/emails — NOT under spree/providers/, which means commerce
providers with an Integration credential surface) boots the OpenTelemetry
SDK purely from standard OTEL_* env vars (Saleor-style; no host
initializer; OTEL_SDK_DISABLED honored), installs the Rails
auto-instrumentation umbrella, and translates Spree notifications into spans
via hand-rolled subscribers following the Spree::EventLogSubscriber
reload-safety pattern. 6.0 ships the trace signal only — the Ruby metrics and
logs SDKs are experimental, so RED metrics are collector-derived
(spanmetrics) and log correlation is trace IDs in log tags, never the logs
SDK.
Consequences for other work:
- An outbound network call inside a workflow is always an
external_step, never a plainstep—external_stepnow also marks the span as CLIENT (external: truein thestep.spree_workflowpayload), so the distinction is a tracing contract on top of the transaction guard. - Never
rescue StandardErroraround workflow execution in instrumentation or middleware:FailureSignal/HaltedinheritExceptionand would be silently missed. - Anything added to an instrumented notification payload must be PII-safe (prefixed IDs, names, counts — never payloads, emails, addresses, credentials); assume every payload key ends up on someone's dashboard.
- Telemetry configuration is process-level deployment config (env vars) —
never a
Spree::Configpreference, store preference, or admin UI surface.
2026-08-12 — spree-starter bundles spree_opentelemetry by default; Sentry keeps errors
Decision: spree-starter adds spree_opentelemetry to its Gemfile
installed, not commented out (amends the plan's original "commented in the
Gemfile"). The official Docker image is built from the starter, so image
users cannot edit the Gemfile — and since the gem is dormant until a standard
OTEL_* exporter variable is set, bundling it makes tracing a pure
environment-variable opt-in for container deployments. Sentry (already in the
starter) and OpenTelemetry divide cleanly: Sentry keeps error capture, the
OpenTelemetry stack owns tracing. The starter must NOT set Sentry's
traces_sample_rate — that would double-instrument every request into two
disconnected trace systems. Teams that want traces in Sentry use the
sentry-opentelemetry OTLP integration, and ordering is load-bearing
(2026-08-12 code review): Sentry registers its span processor synchronously
inside Sentry.init (after(:configured)), which requires the OpenTelemetry
SDK to already be installed — so the recipe is SpreeOpenTelemetry.configure { |c| c.enabled = true } + SpreeOpenTelemetry.install! at the top of the
Sentry initializer, before Sentry.init with config.otlp.enabled = true,
plus OTEL_TRACES_EXPORTER=none so the SDK wires no competing default
exporter (Sentry derives its endpoint from the DSN). Auto-detecting Sentry's
OTLP mode from spree_opentelemetry was tried and reverted — the gem
installs after load_config_initializers by design, so detection can never
run early enough. A bare SENTRY_DSN deliberately does NOT activate tracing:
Sentry bills for ingested spans, so error capture must never silently become
span ingestion. The starter's own sentry initializer encapsulates the whole
recipe behind an env var (e.g. SENTRY_OTLP_ENABLED=true) so container
users still flip it without code. Docs:
docs/developer/deployment/telemetry.mdx.
2026-08-14 — Duties are fees, not tax lines; landed cost is a provider gem, not core
Decision: Customs duties are modeled as Spree::Fee rows with kind: 'duty' — never TaxLine rows and never a new table. Duty rows snapshot their
calculation inputs (hs_code, country_of_origin, rate, provider,
guaranteed flag) in metadata, so re-classifying the catalog never rewrites
order history. Classification lives as three plain nullable columns on
spree_variants (hs_code, country_of_origin, customs_description),
shipped together with their first consumer: the EasyPost provider's customs
declaration, built for international rate quotes as well as label purchases
(today it sends customs_info: null) — the two share one shipment builder, so
a label always carries the declaration and duty terms its quote was priced
with. Fees become shopper-visible — the Store API cart/order serializers
gain fees + fee_total. Duty estimation enters the cart exclusively through
Spree.adjusters (a provider gem's adjuster writes the duty fee rows during
recalculation); core ships no calculation engine and no landed-cost guarantee
— a guarantee requires being importer of record, which is a service business,
not a code path. Duties are excluded from the default taxable-item set in the
shared Spree::Purchase::Taxation#taxable_items (Cart and Order), so every
provider inherits the exclusion rather than each reimplementing it; a provider
that does tax duties passes its own item list. Import VAT on a duty therefore
exists only as provider-written TaxLine(fee_id: …) rows, preventing domestic
tax stacking and double-counting. Plumbing ships in 6.0; the landed-cost provider gem and a
Spree::Market shipping-terms setting are 6.1.
Consequences: No duty math against the live catalog on existing orders —
the metadata snapshot is the source of truth. New fee-producing code writes
typed Fee rows via adjusters or the order-locked fee services. Store
serializer work must not assume fees stay hidden. A dedicated duty-provider
contract (estimate/commit/void) is deliberately NOT built — it graduates only
if the first provider gem proves the need. Plan:
6.0-duties-and-custom-fees.md.
2026-08-15 — Vendor users are Spree::AdminUser; vendors get their own API branch, JWT audience and login surface
Context: The marketplace plan (2026-07-14 wording) said vendor users would
"hit the same admin API with JWT + vendor-scoped abilities — no separate
vendor routes", with abilities built from PermissionSets::VendorUser
carrying vendor_id: user.vendor_ids hash conditions. Two shipped PRs changed
the ground under that: platform-owned auth (#14380) made the platform
two-principal (Customer buys, AdminUser operates a back office, one auth
stack on that class), and first-class RBAC (#14412) removed permission sets
with no bridge — the catalog is flat read_*/write_* keys with no
conditions, tenancy is controller scoping, and Spree::Ability#staff_roles
already excludes vendor-resourced RoleUser rows as belonging to "their own
panel's ability" (the RBAC plan's 2026-08-08 direction: vendor-panel endpoints
scope-fetch through current_vendor). Two questions were re-examined: should
vendor staff be a separate model, and should they reuse the Admin API with
narrower permissions.
Decision: Reuse the principal, separate the surface.
- Vendor staff are
Spree.admin_user_class. NoVendorUsermodel, noSpree.vendor_user_class. A third principal would duplicatehas_secure_password, lockout, password policy, password-reset tokens,UserIdentitySSO linking, invitation acceptance and the refresh-cookie flow — every future MFA/passkey improvement, twice. Membership is byRoleUser.resource_type(Spree::VendorvsSpree::Store), never bystore_id; one account may hold a store role and a vendor role at once. - A dedicated
/api/v3/vendorbranch (third v3 branch besidestoreandadmin,Vendor::BaseController/ResourceControlleranchors). Every endpoint scope-fetches throughcurrent_vendor(X-Spree-Vendor-Id+ membership; the store is derived from the vendor, never from a header) — IDOR by construction, the same mechanism that isolates stores on the admin branch. Vendors never call the Admin API. What a vendor may not do is an endpoint that does not exist, not an ability rule. Own serializer branch off the store serializers, own OpenAPI spec; admin controllers are never subclassed into the vendor namespace (inheritedcurrent_store.*lookups are the leak). - Isolation at the token layer, not only at membership: own
JWT_AUDIENCE_VENDOR = 'vendor_api'(admin and vendor branches reject each other's tokens at decode, before any membership check); ownSpree.vendor_authentication_strategies+/vendor/auth/*(login policy is per surface, so staff can be SSO-only while vendors use passwords — the vendor login refuses accounts with no vendor membership);spree_refresh_tokens.audienceenforced on refresh with a separate cookie.
Rejected: a separate VendorUser model — buys only type-level separation
on top of the three token-layer measures, at the cost of a duplicated auth
stack and split identities. Reusing admin controllers with vendor
permissions — not expressible in the conditionless catalog; would require
per-principal forks in ~300 endpoints' scope/find_resource/incidental
lookups (stock_location_id, reason_id, variant_id), each miss a
cross-vendor read or write inside the same store.
Consequences: AdminAuthentication#current_user_member_of_store? must
match resource_type: 'Spree::Store' (today it matches store_id, which a
vendor-resourced assignment passes — scope-exempt admin endpoints such as
/admin/tags and /admin/store would be reachable by a vendor-only user
once vendors exist); ship this ahead of the Vendor model. Role#audience and
a vendor-grantable marker on register_scope come from the RBAC plan's
settled direction. Never add a login surface without its own strategy
registry and JWT audience; refresh tokens carry the audience they were minted
for. Accepted trade-off: password policy and lockout stay shared between
staff and vendors (model-level), and thin controllers are duplicated across
the two branches. Plan: 6.0-multi-vendor-marketplace.md Decision 10;
supersedes the 2026-07-14 "collapse into ability scoping" wording there and
extends 6.0-admin-rbac.md's vendor-scoped-assignments direction.
2026-08-15 — Marketplace: facilitator-tax flag and payout floor are core; the policy around them is Enterprise
Decision: Three of the marketplace plan's long-open questions were settled
the same day as the vendor-principal decision. (1) Store-credit and gift-card
payments on a split checkout are group-level Payments with their own
PaymentSplit rows, prorated by child totals like the gateway payment — one
attribution rule for every payment source. (2) spree_vendors.minimum_payout_amount
(nil ⇒ store preference) ships in core and the sweep carries sub-threshold
balances forward; a percentage holdback with a release window stays Enterprise.
(3) spree_vendors.tax_remittance (vendor | platform, default vendor)
ships in core and core's transfer basis honors it (platform ⇒
total − tax_total − commission); deciding that a vendor is
platform-remitted (US facilitator nexus, EU deemed-supplier rules) stays
Enterprise "automatic taxes", which sets the column. Vendor-scoped promotions
are deferred past 6.0 with their shape recorded.
Why: the ledger math must be provider- and edition-independent so
Enterprise never forks core ledger code — it configures rows, it does not
override the basis service. Consequences: amends the marketplace plan's
Decision 9 note that facilitator mode is "not core" (the flag and the math
are; the policy is not). Plan: 6.0-multi-vendor-marketplace.md.
2026-08-17 — The marketplace seller is Spree::Seller; Vendor is retired
Reverses the naming half of 2026-07-14. That entry gave the marketplace the
Vendor name on two grounds, and by 2026-08-17 both were gone: the user docs'
Vendors area is being rewritten wholesale for the 6.0 stable release, and there
is no Enterprise production data to keep ven_ continuity with. Nothing was
released, so nothing had to be carried over — the migrations were edited in
place rather than added to.
The decisive argument is Amazon's, and it is about the second party. Spree
models both a business selling through the marketplace and a supplier the
merchant buys stock from. Amazon names those two relationships in opposite
directions: Seller Central hosts third parties, Vendor Central buys from
suppliers. So vendor was the single worst available word for a marketplace
seller in a schema that also contains the supplier — every integrator with
Amazon experience reads vendor_id as the procurement relationship. Shopify
agrees by construction: when it built purchase orders it chose supplier.
Seller also matches the buyers we are selling to. Gartner's category is
"Enterprise Marketplaces" and its definition says "third-party sellers";
Forrester's Wave criteria are "seller onboarding" and "seller compliance".
Neither analyst firm uses "multi-vendor" for anything. VTEX (sellerId,
/sellers/), Marketplacer (Seller), Amazon (sellerId) and Mercur
(seller, sel_) all name the entity that way in public APIs. Mirakl is the
one mixed case — its data entity is shop_id while its docs and API routing
say seller — and its shop is a legacy artefact we have no reason to inherit.
Spryker's merchant is the sole enterprise divergence, and "merchant" fits
Spree badly since it most naturally means the store owner running the
marketplace.
Scope: Spree::Seller, spree_sellers, prefix sel_, seller_id,
current_seller, SellerMailer, read_sellers/write_sellers, and all three
API surfaces (store /sellers public profiles, admin /sellers operator CRUD,
and the seller-facing /api/v3/seller branch). Spree::Supplier is unchanged
and keeps the procurement source — 2026-07-14's split stands; only which word
lands on which side changed.
Category naming, separately: describe the product as a marketplace
platform, not a "multi-vendor" one. Every platform leading with "multi-vendor"
sits in the $29–$6,999 plugin tier (CS-Cart, Dokan, WCFM, Yo!Kart); every
analyst-recognised vendor says "marketplace platform". Keep "multi-vendor
marketplace" in SEO surfaces only — meta descriptions, comparison pages — which
is exactly what Marketplacer does, capturing the search volume without letting
the term define the positioning. Internal branch and plan filenames keep their
multi-vendor prefixes for stable cross-references; this is positioning, not
engineering.
Consequences: Rails/Bundler vendor/ directories, gemspec
{app,config,db,lib,vendor} globs, the "vendor lock-in" idiom, and EasyPost's
carrier-meaning "vendor" are all deliberately untouched — a blanket rename
breaks CI and ships broken gems, and each of those was caught only by running
the suites. docs/user/vendors/ and the rest of the published documentation
are not renamed here; they are part of the 6.0 stable docs overhaul. Plan:
6.0-multi-vendor-marketplace.md.
2026-08-18 — ERP / PIM / DAM: sync what is shown, call live only for what is decided
Damian asked what Spree's workflow should be for larger merchants who run a
dedicated ERP (inventory), PIM (product content, base pricing) and DAM (media):
plain sync into Spree, or pluggable third-party providers. Recorded in
6.0-third-party-pricing-inventory.md; the parts other plans need to know:
The rule. Spree is the system of record for what the shopper sees; the
external system is the system of record for what is true. Product content,
media references, base prices, price lists and stock levels are synced in and
rendered from Spree's copy. Live calls happen only at decision moments —
pricing a line item, add-to-cart, taking a checkout hold, completion — through
Spree::PricingProvider and Spree::InventoryProvider contracts whose
Internal defaults wrap today's price resolution and Stock::Quantifier
(the price-list walk moved into PricingProvider::Internal::Resolution — it is
that provider's implementation, not a seam of its own; Pricing::Context
stays outside, since it is the question every provider is asked).
External providers return unsaved readonly! Spree::Price / Spree::StockItem
instances — the AR shape is the contract, no new value-object type.
Identity mapping is Spree::ExternalReference, not a column. One
polymorphic, store-scoped table (metafields precedent) so a product can carry a
PIM key and an ERP key at once and an order can carry the ERP number written
back after the push; unique in both directions; system is a string key (an
Integration's api_type by convention), never an FK. No new external_id
columns on any model — Company#external_id on the unreleased B2B branch
switches to this model.
Two things the code forced. (1) The pricing resolver is on the catalog read
path — the Store API serializers call price_for on every listing — so an
external pricing provider must cache by Pricing::Context#cache_key and route
anonymous traffic to Internal; the inventory read path (in_stock?,
purchasable?, ProductScopes) stays local, full stop. (2) Live calls cannot
hide inside LineItem#recalculate_price / #sufficient_stock? — they move to
external_steps in AddItem / UpsertItems / Recalculate / Complete via
new Carts::PriceItems / Carts::CheckAvailability services, and line items
record price_source.
Selection and failure policy are Store preferences (pricing_provider,
inventory_provider, *_failure_policy — strict default for pricing,
fallback for inventory); credentials live on Spree::Integration. ERP-side
soft allocation and per-market provider selection are deferred, additive.
2026-08-18 — Identity mapping, and where a provider call is allowed to happen
Implementing 6.0-third-party-pricing-inventory.md settled three things other
plans will run into.
Spree::ExternalReference replaces every external_id column. One
polymorphic, store-scoped table, unique in both directions. No model gets its
own column any more — include Spree::HasExternalReferences. Company and
CompanyLocation lost theirs in the same commit. Note the name collision this
surfaced: Spree::Media#external_url already means where an imported image was
fetched from, and main's external_video_url is parsed as a video link, so
a DAM-hosted picture gets its own external_media_url — named for media
rather than images, since the same column will hold a self-hosted video file,
with media_type saying what it is — and rides
Media#hosted_still_url — the same "a URL that isn't ours to resize" slot a
provider thumbnail uses.
The inventory read path stays local, the pricing read path is cached. Store
API serializers price every row of every listing, so PricingProvider runs on
catalog reads and must declare a cache_ttl and use handles? to route
anonymous traffic to Internal. Variant#in_stock?/purchasable? and
ProductScopes never consult a provider at all — only add-to-cart,
reservations and completion do.
Provider calls are external_steps, and stand-ins must be detached. A
network call inside a database transaction is how a slow ERP becomes a table of
stuck locks, so pricing and availability resolve through
Spree::Carts::PriceItems / CheckAvailability before the transaction opens
and are written inside it. Two traps found the hard way: a stand-in line item
built with cart.line_items.new is found by the line-item finder and doubles
the quantity on the next add; and Quantifier subtracts reservations by
stock_item_id, which is nil on an external provider's unsaved rows — matching
by (variant, location) is what stops every local checkout hold counting as
zero and overselling.
2026-08-18 — Store credits lose their category and type
Spree::StoreCreditCategory and Spree::StoreCreditType are retired.
Both were inherited reference tables that no longer answered a question
anything asked. A type was never created by any code path — no seed, no
writer — so the "priority" it was meant to give store-credit redemption
ordered on NULL, and which of a customer's credits got spent first was
whatever the database returned. A category carried a name and an
expiring/non-expiring label that nothing enforced: store credits have no
expiry (gift cards do, on their own row), gift-card redemptions never set a
category, and the only readers were a read-only admin endpoint feeding a
dropdown nobody could manage.
What answers the question instead. Why a credit exists is
StoreCredit#originator (the return, exchange, claim or gift card that
issued it) plus the free-text memo the refund workflows already write.
Which credit is spent first is StoreCredit.oldest_first — deterministic
and what shoppers expect. This is the shape every hosted platform ships:
a balance with a note, no taxonomy.
Scope. Refund workflows stop passing a category; the admin store-credit
endpoint drops category_id/category_name and the read-only
/admin/store_credit_categories routes are gone, as are the dashboard
picker, the admin SDK resource, the seed and the settings catalog entry.
Spree::Config[:non_expiring_credit_types] is deprecated as
"nothing reads this". spree:upgrade:fold_store_credit_categories copies a
legacy category name into the memo of credits that have none, so the only
information a category row held stays visible.
Kept for one release. Both classes survive as deprecated shells on their
existing tables (warning on instantiation; default_refund_category and
order_by_priority warn and delegate), and spree_store_credits.category_id
/ type_id stay as frozen columns — never written — so extensions
referencing the constants fail loudly and the fold step has its source. 6.1
drops the two tables, the two columns and the shells.
2026-08-18 — Seller onboarding is an operator-configured requirement checklist, not a code-defined task list
The previous marketplace module decided what a seller must do before approval
in one Ruby method on the seller. Nothing in that shape lets an operator add,
drop, reorder or relax a step, and a developer adding a check had to override
the whole list. Spree 6.0 makes the checklist data: Spree::SellerRequirement
rows owned by the store, each an instance of a registered requirement kind
(an STI class with a preference schema, discovered through the same
registers_subclasses_via + PreferenceSchema types endpoint that delivery
method rules and payment methods use), with position, active and
required. Kinds complete in three ways — computed from seller data, attested
by the seller, or verified by the operator or a provider — and the last two
share one persisted Spree::SellerRequirementSubmission row (pending | accepted | rejected | waived, optional private file). Evaluation happens on
read through Spree::Sellers::Requirements; nothing is denormalized onto
spree_sellers.
Enforcement is deliberately narrow: Sellers::SubmitForReview refuses
while a required requirement is unmet, Sellers::Approve refuses unless the
operator passes override_requirements: true (recorded on the event), and
that is all. Seller#sellable? does not read the checklist; a payout account
gates payouts through its provider, not through the checklist; an approved
seller who later fails a requirement is shown as such, never suspended by
core. Automatic approval is a store preference (auto_approve_sellers, off).
Why: the operator, not the developer, owns admission policy, and the requirements that matter most in practice — documents, manual business checks, payout-account status — are per-seller facts with a reviewer, which a computed boolean cannot carry. Two gates keep the checklist an admission tool rather than a hidden purchasability rule.
Consequences: the marketplace plan's "onboarding task registry" paragraph
is superseded; Spree.store_setup_tasks stays code-only for the merchant's own
Getting Started list. Never add Seller#onboarding_completed?-style predicates
or step-done columns; a new admission check is a kind or a validate hook on
the seller workflows. Plan: 6.0-seller-onboarding-requirements.md.
2026-08-15 — Maintenance tasks: operator-run data work is a task class with a run row, and every 6.0 upgrade step is one
Decision: Spree 6.0 core gains a first-class maintenance-task primitive —
Spree::MaintenanceTask (Shopify maintenance_tasks authoring contract:
collection/process/count, ActiveModel attributes as parameters,
throttle_on, report_on, no_collection, later csv_collection) run by a
native ActiveJob::Continuable job, with a persistent
Spree::MaintenanceTaskRun row carrying cursor, progress, arguments, tallies,
outcome and who fired it from where. It is built natively, not by depending
on Shopify's gem: the gem's runner is a second interruption mechanism
(job-iteration) beside the one 6.0 already standardized on, and its UI is
a server-rendered engine Spree 6.0 has no place to mount. Tasks are
registered explicitly (Spree.maintenance_tasks, the same
Rails.application.config.spree.* array as every class family) — never
autodiscovered. Authorization is one catalog resource,
maintenance_tasks, in the access group: admins hold it by default,
nothing is gated per task and nothing checks the admin role by name.
Runs are installation-wide with a recorded context store the runner loads
into Spree::Current.store. Dry-run is opt-in and task-honored
(supports_dry_run + dry_run?), never a runner-faked rollback. The run
row is the audit; lifecycle events fire; no audit-log model. Schema
migrations stay in the deploy pipeline forever.
All 22 steps of the 5.6→6.0 upgrade manifest are rewritten as
Spree::MaintenanceTasks::Upgrade::* classes and the manifest names
task_class: instead of rake tasks (those rake names never shipped, so
there is nothing to bridge; older manifests keep rake steps and the walker
runs both kinds inside run rows). spree:upgrade keeps its interface and
becomes an inline walk that writes the same run rows; the dashboard gets an
Upgrade panel and Upgrade::Walk, an orchestrating task whose steps are
child runs.
Why: A console session records what was typed, not what it did; a managed platform cannot hand out shells; and the 6.0 upgrade is the largest data migration Spree has shipped. Building the runner for our own migration path yields the cloud capability as a side effect and turns "run this rake task and wait" into progress bars and resume buttons. It lives in BSD-3 core because it is infrastructure self-hosted merchants need exactly as much.
Consequences: New bulk/backfill work is a task, not a bare rake task or
a README console snippet; new 6.0 upgrade steps are born as task classes;
Imports::ProcessJob-style system-triggered jobs stay plain Continuable
jobs (the primitive is for operator-triggered work). Plan:
6.0-maintenance-tasks.md.
2026-08-24 — Media library reuses files by sharing blobs, never by a shared asset entity
The 6.0 media library is a store-scoped view over Spree::Media (which gains a
store_id, backfilled from the viewable's product), with upload-first
unattached rows (viewable_id: nil). Reusing a file elsewhere duplicates the
Media row and attaches the same ActiveStorage::Blob — no second file,
processed renditions shared, per-context alt/position/variant links kept. The
reuse API is source_media_id on the existing nested media create; the
library picker also hands out blob signed_ids so bare attachment fields
(category, collection, store, seller images) can adopt an existing file
through their unchanged endpoints. Rich text embeds are plain <img> URLs to
a new non-cropping rendition — no reference-tracking tables.
Why: the ownership model (viewable, acts_as_list, counter caches,
thumbnail denormalization, the variant-link boundary) all assume one owner per
row; a Vendure-style shared-asset join model reworks all of it for a benefit
blob sharing already delivers at the storage layer. Deletion stays safe
because the Rails foreign key from active_storage_attachments to
active_storage_blobs blocks purging a shared blob and
ActiveStorage::PurgeJob discards on that violation — reference counting for
free.
Consequences: that FK is load-bearing (the no-FK convention covers Spree's
own tables only — never strip it); media deletion paths must use
purge_later, never synchronous purge; new contexts needing a file get
their own Media row sharing the blob, never a join table onto Media; and
img enters RichTextSanitizer.allowed_tags only in the same change that
gives the dashboard editor its image node.
Two things the implementation settled. A copy takes the target's store,
never the source's — duplicate_for leaves store_id unset so
SingleStoreResource resolves it from the new owner's product, because media
follows the thing it is a picture of; copying the source's store wrote rows
into the wrong tenant whenever a placement crossed stores, which the
controller's scoped lookup hid. And source_media_id is honored by both
product write paths — the nested media create and the inline media: list —
since the dashboard's product Save uses the inline list, so supporting only
the endpoint left the picker silently dropping its files. A new media write
path must accept it or reuse breaks on that path alone.
Live use then reshaped two boundaries. Category and Collection are real
Media viewables (Spree.media_viewable_types registry: Product, Variant,
Category, Collection): their image/square_image slots reconcile into
placements via Spree::HasLibraryMedia on save — the slots stay the
operational storage, the placements are the library's view, clearing a slot
unplaces (never destroys) its row, and the future category gallery is additive
rows on the same association. Until that gallery exists, reconciliation owns
every placement on these records. Sellers and stores stay bare attachments —
branding, not merchandising media. And library delete detaches on
confirmation: a file in use returns 422 with its usage list, and
detach=true runs Spree::Media::Destroy — removing it from every placement
and plain attachment in its store, then deleting the row so the blob purges.
The refusal stays the default so an API client cannot pull a file out from
under a catalog by accident; only the nested gallery destroy removes a single
placement.
Review then caught two tenancy holes worth stating as rules. acts_as_list
needed store_id in its scope: an unplaced library row has no viewable, so
without it every store's uploads shared one list and their positions bled
across tenants. And Spree::Media::Usage had to scope all three of its sources
to the file's own store — a shared blob reaches other tenants' records, and
reporting them named another store's data to a merchant who cannot see it
anywhere else; its rich text search covers content models only, never order or
customer internal notes. Both are the general shape: a store-owned model
whose rows can exist unattached needs store_id wherever tenancy was
previously implied by a parent.
Plan: 6.0-media-library.md.
2026-08-25 — B2B moves into 6.0; the company model becomes a multi-level organization tree
B2B is a 6.0 deliverable — customers are waiting on it. The Catalog + Company
phase parked in 6.1 comes back into 6.0, and 6.1-channels-catalogs-b2b.md
is renamed back to 6.0-channels-catalogs-b2b.md, its Catalog/Company phase
superseded by the new 6.0-b2b-companies-and-catalogs.md.
The Company → CompanyLocation → CompanyContact tree that shipped with
tax-provider Phase 7 is merged but unreleased, so it is replaced outright
— no bridges, no data migration, migrations rewritten in place (the recorded
exception to the bridges convention applies: unreleased code gets no bridge).
The replacement is the from-scratch design, chosen over patching a
parent_id onto the shipped shape: Shopify's CompanyLocation conflates
org-unit, address pair, and terms anchor — the known weakness that forces one
node per ship-to site. No competitor ships organization hierarchy in open
source (flat models everywhere; depth is paid at Vendure/BigCommerce, absent
at Shopify/Medusa) — that gap is exactly what Spree 6.0 fills.
The model. One entity, one table: Spree::Company self-referential
(parent_id, depth cap 5, cycle-checked, store-scoped), typed by kind —
company (legal entity) | division (org unit), roots must be legal
entities. If the kinds ever grow diverging behavior the path is STI on the
same table, never a separate Division model (which would force dual-FK or
polymorphic references on every consumer). CompanyAddress is an address
book (labeled rows, at-most-one default billing/shipping) so ship-to count
never dictates node count. CompanyMembership joins a customer to a node
with subtree standing — membership at N authorizes N and everything
below. Carts and orders carry company_id (any node, frozen at completion);
company_location_id is gone.
kind is load-bearing for tax. Identifiers and exemption certificates
live only on company nodes; every purchase-side tax read goes through
Company#legal_entity — nearest self-or-ancestor company node, where the
walk stops whether or not it holds anything. A division is its legal
entity; a subsidiary never borrows its parent's registration. Kept as a
validation rather than schema so per-division foreign registrations can be
allowed later by relaxing the validation alone.
Catalogs inherit down the tree. CatalogAssignment's assignable set is
Channel, CustomerGroup, Market, Company; a company-node assignment applies to
its subtree, effective catalogs are the union over self_and_ancestors,
pricing takes the nearest node's assignment first, then catalog position.
The sketched Company↔CustomerGroup link is dropped — it promised composition
it couldn't deliver (a company "in" a group never put its buyers in that
group); group-style targeting of companies arrives, if ever, as explicit
rule kinds on the promotion/price-rule STI families.
OSS trusts every member; governance is Enterprise, and its plans live in
ee/docs/plans/. The Store API ships full directory
self-service — node detail, addresses, members, subtree order history,
writable cart company_id (sole standing as the default; explicit node for
multi-node buyers, finally settling the "provisional — revisit" resolution
question) — where any member with standing can do everything, including
removing other members. That trade-off is deliberate: OSS ships no company
roles and no member-vs-member permission logic anywhere; it ships injection
points — the storefront access policy class and the carts.complete.validate
hooks, both no-ops in OSS — which the Enterprise governance layer (roles,
approvals, spend limits, terms, quotes) fills without OSS schema changes.
Plan: 6.0-b2b-companies-and-catalogs.md.
Addendum (same day): member invitation for unregistered emails was
briefly deferred, then folded in. Adding a member takes an email from either
surface — dashboard or storefront — and converges: existing store customer →
membership immediately; unknown email → Spree::CompanyInvitation
(company-scoped, plaintext has_secure_token like the staff invitation and
setup tokens, 30-day expiry, functional invite email in spree/emails,
company_invitation.* events), whose unauthenticated token-accept runs
Customers::Create — the single customer-creation workflow — and lands as a
membership. Memberships stay always-active and customer-backed; pending
state lives on the invitation, never as a nullable customer_id or status
column on the membership. Invitations carry no role — Enterprise attaches
its payload via the same dialog slot (stored in invitation metadata or its
own referencing table) and applies it on company_invitation.accepted.
2026-08-27 — Policies read through their owner, and sellers get their own
The Policy.for_store override is deleted. It returned the store's
policies plus every policy not owned by a store — a deliberate widening
that becomes a cross-tenant leak the moment any other owner type gets
policies. With the override gone, the generic Spree::Base.for_store
resolves to store.policies, and all policy reads go through the owner
association (store.policies, seller.policies) — never a class-level
scope. This deletion is a prerequisite for seller-owned policies, not a
cleanup afterwards: under the old override, the first seller-created policy
would have appeared in GET /api/v3/store/policies for every store on the
installation. It also tightens the guarded reflective callers (translations
batch, exports) from "all non-store policies globally" to "this store's
policies", which is the correct behavior.
Sellers own policies through the existing polymorphic owner —
Seller has_many :policies, as: :owner, no seeding (stores keep their four
seeded defaults; sellers start empty). What a seller must provide is
expressed by a new computed requirement kind,
Spree::SellerRequirements::Policy — one row per document. The kind is
allow_multiple?, so the base already demands a per-row name, and that
name is the document required; a marketplace asking for two policies adds
the kind twice and the seller sees two lines that go complete separately.
An array-of-names preference was tried first and rejected the same day: it
rendered as the generic comma-separated text box (documented as being for
IDs and short tokens, not human-authored names), made progress
all-or-nothing, and set up a second vocabulary beside the row's own name.
The seller panel pre-fills the required name on create, so matching holds
by construction. Not in DEFAULT_KINDS. Seller-branch
CRUD rides scoped_resource :seller_profile; the Admin API manages
store-owned policies only. On the Store API, a seller's policies load
behind the standard ?expand=policies guard on the seller serializer.
Rich-text writes go to the plain attribute, not *_html. Both
6.0-admin-api.md and 6.0-rich-text-descriptions.md carried a line saying
writes accept description_html/body_html with HTML under the plain name
rejected 422. That was never implemented and contradicts the rich-text plan's
own summary: Spree::SanitizableRichText defines field_html as a read-only
reader and sanitizes writes made to the plain attribute, which is what every
shipped controller permits (Admin::CategoriesController takes
:description). Both plans are corrected; the plain attribute is the write
target until a bridge actually exists.
One recorded serializer exception: the store policy serializer exposes
updated_at — when a legal document last changed is customer-facing
information, not operational leakage. created_at stays admin-only.
Checkout consent capture (persisting acceptance) stays out of scope, parked
with 5.4-6.0-eu-legal-compliance.md. Plan: 6.0-store-policies.md.
2026-08-28 — Catalog assignments narrow to buyer audiences; Channel and Market drop out of the vocabulary
CatalogAssignment.ASSIGNABLE_TYPES shrinks from
Channel/CustomerGroup/Market/Company to CustomerGroup and Company. The
dropped pair was write-only from the day it shipped: resolution
(Products::ForContext) and pricing (PricingProvider::Internal) read only
company-subtree assignments, customer-group assignments, and the channel's
default_catalog_id — a channel or market assignment created an inert row,
and the assign dialog offered the gesture anyway. 6.0 is unreleased, so the
narrowing is free now and a breaking assignable_type-enum change after GA.
Channel is dropped for good. The channel↔catalog connection already has
a shipped mechanism with the semantics a sales surface wants:
default_catalog_id is a fallback that buyer-specific catalogs override,
where an assignment means "this audience sees this instead". Wiring a reader
to channel assignments would create a second mechanism with no defined
precedence against the first.
Market is deferred, not judged. Per-market assortment is a real feature
(the hosted leader's catalogs power per-market availability; the original
6.0-channels-catalogs-b2b.md sketch gave a Market a "regional assortment"
catalog) but its open questions — where it sits in ForContext precedence,
whether it intersects or overrides buyer catalogs, whether it also gates
pricing — have no answers yet. The type returns only in the same change as
the resolution code that reads it, plausibly alongside the
6.0-channel-markets.md allowlist work.
Each axis keeps exactly one mechanism: assignments answer who is this
buyer (Company subtree, CustomerGroup); default_catalog_id answers what
does this surface show when the buyer is nobody in particular; price-list
rules (PriceRules::ChannelRule/MarketRule, both shipped) answer what
does this context pay. No cleanup migration: any pre-release rows of the
dropped kinds were always inert (the inclusion validation runs on the
assignment row, which nothing re-saves), so they are left to lie. Plan
amended: 6.0-b2b-companies-and-catalogs.md.
2026-08-30 — Wholesale shipping ships in 6.0: PackageType, unpriced rates, collected deposits; lot-level inventory joins inventory-operations
Merchant feedback (wholesale carton/pallet/container shipping) turned into two new plans plus an inventory-operations extension. The decisions other plans need to know about:
Spree::PackageType is the packaging vocabulary and replaces the four
default_package_* store preferences. Store-scoped rows (box | envelope | carton | pallet | container, one default per store, Channel-style
demotion); the default row is what Stock::Package#weight/#dimensions
and the EasyPost parcel path read, with the preferences kept as deprecated
one-release bridges. The name is deliberately not Spree::Package —
Spree::Stock::Package is the in-memory packing unit and a persisted
sibling with that name would be permanently confusing. Variant carton data
is a reference to a carton-kind row (carton_package_type_id) plus
per-variant packing facts (units_per_carton, carton_weight,
cartons_per_pallet) — geometry is shared, packing facts are not.
Unpriced delivery rates are first-class. Estimate and
spree_delivery_rates gain unpriced; the estimator skips markup and
serializers/UIs render "quoted after review". A zero-cost rate displaying
as "Free" was rejected as the mechanism. Volume math behind the CBM tier
rules is unit-aware from day one (a new conversion helper) — the
raw-number shortcut recorded for WeightRule (2026-07-29) explicitly does
not extend to volume, where cm-vs-in is a 16× error.
Deposits are collected, not just displayed — the ambitious option,
chosen deliberately in review. A freight method's deposit_percentage
changes what Carts::Complete requires payments to cover
(Cart#amount_due_at_checkout; base = the order total at placement);
orders complete partially_paid against the existing
outstanding_balance. Consequence for all order code: completed no
longer implies paid in full. The later freight quote is a
Fee(kind: 'freight') through the existing admin fees endpoint, never a
delivery-rate edit. [Amended same day — the method-level deposit became a
default source feeding the order's payment_terms snapshot; see the
payment-terms entry below.]
Quantity rules (MOQ / order multiple / purchase unit) are a purchasing layer, never inventory. Stock stays in units everywhere; enforcement lives in the item workflows and completion, the server refuses invalid quantities rather than rounding. Contextual tiers (the same SKU at retail 1/1 and wholesale 48/24) were committed with the owner entity initially unresolved. [Resolved same day — the tiers live on the Catalog; see the one-question-per-entity entry below.]
Spree::ChannelRule is the home for channel-scoped gates.
[Superseded same day — see the one-question-per-entity entry below: the
family is dropped; terms went to the Catalog and gating stayed as Channel
preferences.]
Lot-level inventory (full tracking, not provenance-only) joins
6.0-inventory-operations.md. Spree::StockLot decomposes a
lot-tracked variant's count_on_hand per location, kept in sync
transactionally with typed movements (stock_lot_id on movements);
receives assign lots, dispatch picks FEFO, allocation stays lot-agnostic.
Lot numbers live only on StockLot rows.
Plans: 6.0-b2b-wholesale-shipping.md, 6.0-b2b-quantity-rules.md,
6.0-inventory-operations.md.
2026-08-30 — One question per entity: Channel is the surface, Catalog is the agreement, PriceList is the numbers
A stop-and-analyze pass over Channel (live), PriceList (live), and Catalog (unreleased) — triggered by the question of whether channel purchase rules duplicate catalog terms (they do) — settled the doctrine each of the three entities lives by. Each answers exactly one question with exactly one targeting mechanism:
Channel answers "where is the buyer shopping." Publications, publishable-
key binding, order routing, the stock-location allowlist, and access gating.
Gating (storefront_access, guest_checkout) stays as Channel
preferences and never moves to catalogs: it must bind before the buyer has
an identity, and catalogs resolve from identity — a catalog cannot gate
the door to the thing that determines the catalog. The ChannelRule STI
family proposed earlier the same day is dropped; nothing purchase-shaped
remains for it.
Catalog answers "what is this buyer's agreement." Assortment (optional),
its price list (optional), and — new — commercial terms: catalog-level
minimum_order_quantity/order_multiple columns with per-variant override
rows, and per-currency order minimums, resolved per-field,
nearest-agreement-wins through the existing Catalog.for_context chain
(nearest company node → customer groups → the channel's default catalog).
All-or-nothing resolution was rejected — an agreement silent on a field
passes it through rather than waiving it. The channel-level minimum falls
out for free: it is the terms on the channel's default catalog, so no
second mechanism exists. A terms-only catalog (empty assortment, no list)
is legitimate. Terms are typed tables/columns per grain — never one
generic catalog_rules table or an STI rule family (rules are matching
predicates; terms are values on the hot path needing indexed lookups and
DB uniqueness — the typed-adjustments doctrine).
PriceList answers "what are the numbers." Price rows, dates, status,
and context rules only. The audience-shaped rules duplicated catalog
assignment with different precedence and are removed from the vocabulary:
PriceRules::CustomerGroupRule and PriceRules::UserRule are deprecated
in 6.0 (one-release bridge + a data task converting each such list into
an assortment-less catalog assigned to the audience and owning the list).
PriceRules::ChannelRule is grandfathered — kept working, nothing new
builds on it, the forward path being the channel's default catalog.
MarketRule (carries VAT restatement) and VolumeRule are context-shaped
and stay first-class. Price lists also gain automatic pricing
(6.0-price-list-automatic-pricing.md): a signed percentage adjustment off
base prices, computed on read (never materialized), currency-rounded,
currency-agnostic, with explicit rows as per-variant overrides.
The list binding inverts: spree_price_lists.catalog_id replaces
spree_catalogs.price_list_id. A list is standalone (rule-matched) or
owned by exactly one catalog, and generic matching skips owned lists by
FK. This closes a live leak in the unreleased derived-set design:
Catalog.bound_price_list_ids excluded only lists bound to active
catalogs, so deactivating a catalog dropped its typically rule-less list
into generic matching — pricing the entire store. Detaching a list is now
an explicit act (dashboard warns that the list will start matching by its
rules). Sharing one list across catalogs is lost; one catalog serving many
audiences through assignments is the replacement.
Setup is catalog-first and one go. The catalog page is the agreement
editor (audiences, assortment, inline pricing card for the owned list,
terms, and a products-with-prices view exposing assortment↔pricing
divergence); the create flow takes the pricing choice (base / ±% / fixed)
and the admin catalog endpoints accept an inline price_list payload, so
standing up an agreement never requires visiting the price-lists page.
Rejected alternatives, for the record: merging Catalog and PriceList (forces
assignment-targeting and rule-matching into one entity — the ambiguity the
2026-08-28 narrowing removed — and rewrites a released surface); killing
Catalog (renames the merge); audience price rules kept alongside catalog
assignment (two mechanisms, silent precedence). Supersedes the ChannelRule
paragraph and resolves the "tier owner unresolved" clause of the earlier
2026-08-30 entry. Plans amended: 6.0-b2b-companies-and-catalogs.md
(amendment block), 6.0-b2b-quantity-rules.md (design finalized),
6.0-price-list-automatic-pricing.md (new).
2026-08-30 — Company registration is OSS 6.1 mechanisms; the approval flow is Enterprise onboarding
The B2B front door splits along the recorded boundary. OSS 6.1
(6.0-b2b-company-self-registration.md) ships the mechanisms: storefront
company self-registration (POST /store/companies — an authenticated
customer, including an existing retail customer, founds a root company +
their membership in one call; companies are born active), a fourth
storefront access posture approval_required (prices + checkout
require a standing over an active company; shipped prices_hidden
semantics untouched), a machine-readable pricing_access code beside
every nulled price (no more bare nulls a client must interpret), and a
dependency-registered Companies::ActivationPolicy consulted by every
company-resolving call site (catalog resolution, both
sole_standing_companys, cart company writes, the posture) — OSS default:
every company is active, so the posture reads "company members only".
Deliberately 6.1: every piece is additive, nothing needs the 6.0 breaking
window, and 6.0 work must not build interim approval primitives in the
meantime.
Enterprise (ee/docs/plans/b2b-company-onboarding.md)
registers the policy and owns the flow: an application record (FK → the
OSS company; spree_companies stays status-free — this supersedes the
same-day draft that put five statuses on Company), the seller-onboarding
shape reused deliberately — requirements + submissions + evaluated-on-read
statuses + exactly two enforcement points, reopen-with-note as the
request-more-information move — plus the review queue, mails, and
approval_pending pricing codes. Rationale: no modern platform ships
registration approval in open source and everyone who has it charges for
it, while the OSS side keeps a real free feature (instant self-registration
— open-starter parity) and the funnel shape holds: registration works free,
verification is the upgrade trigger. Two approval concepts stay distinct
forever: account verification (merchant ↔ company, this split) vs order
approvals/spend limits (company-internal governance, the existing
Enterprise plan).
Constraints now (OSS): any new code resolving a company for
visibility, pricing, or checkout consults the activation policy (and the
two sole_standing_company implementations stay mirrored); self-service
standing is never approval-gated; new prices-hidden surfaces carry the
pricing_access code; no status/approval columns on spree_companies;
customer-group membership is never an activation mechanism.
2026-08-30 — Quotes: OSS ships the negotiation mechanics, Enterprise the quote product; the OrderChange substrate is strictly post-placement
Merchant feedback proposed building B2B quotations by extending draft
orders, and the code audit confirmed the instinct: a 6.0 draft order
(Spree::Order, status: 'draft', cart_id: nil) already carries the
editing engine — items, addresses, manual fees/discounts that survive
recalculation and freeze at placement, notes, invoice-later conversion via
payment_pending. Four things were missing: a customer-facing surface,
negotiated unit prices, a lifecycle, and a cart-copy service. The tier
split mirrors company registration:
OSS (6.0-draft-order-negotiation-mechanics.md) ships the
mechanics that are features in their own right. In 6.0: manual line-item
pricing — admin item endpoints accept price, stamping
price_source: 'manual', and the provenance column gains its first
readers as guards (Carts::PriceItems skips manual rows;
LineItem#should_update_price? answers false for them) so a quantity edit
no longer silently re-prices a negotiated line; 'manual' is a reserved
key no pricing provider may register; price: null is the explicit
revert; overrides are pre-placement only and price_source stays off
store serializers. Plus two fixes: Orders::Create stamps created_by
(never written despite the column), and the payment_pending docstring
lied — completion yields payment_status: 'none', not 'balance_due'
(whether unpaid-placed deserves a distinct value belongs to the
wholesale-deposit rollup work, decided once). In 6.1:
Orders::CreateFromCart — copy a customer's cart into a fresh draft order
leaving the cart untouched (deliberately not the completion copier, which
re-points money records and is one-shot).
Enterprise (ee/docs/plans/b2b-quotes.md) owns the
quote product: a thin Quote row over the draft order (own model → clean
Q numbers from the per-resource sequence; one quote per draft), statuses
draft → sent → accepted → converted (+ changes_requested, expired
evaluated on read against valid_until, canceled), buyer PO
reference via the order's fields, /store/quotes view + accept (runs
payment_pending completion; placement freezing is the price lock) +
request-changes, mails. The quote never duplicates order data.
The OrderChange substrate narrows (Phase 5 superseded). The 6.1 plan
had draft-order amendments becoming OrderChanges "so draft-order editing
and placed-order editing share one implementation" — wrong in the split
world: a draft is directly mutable with no payments and no balance to
settle, so preview-then-apply is ceremony there, and pre-acceptance quote
negotiation needs no change-set (unlike the competitor whose draft is
placed-like). The substrate is strictly post-placement; edit screens may
share components, but only placed orders create OrderChange rows. Two
applier rulings recorded with it: appliers never derive unit prices (a
manual price comes through an amendment untouched), and a post-placement
price change is its own future action kind (update_item_price), never a
discount abused as one.
2026-08-30 — Buyer PO numbers: a plain order reference, required per company, never a payment method
Merchant feedback asked for the customer's purchase-order number as a
permanent order reference, and the platform research settled the shape.
The market: the largest platform's poNumber is a first-class, always-on,
optional field at B2B checkout with no configuration surface at all (staff
can edit it post-placement; their own emails cannot even render it); the
two platforms that control PO behavior at all hang it per company; two
platforms tie the number to an offline "Purchase Order" payment method —
an anti-pattern we explicitly reject (a reconciliation reference must not
depend on tender choice); nobody ships PO document upload on orders
(native attachments exist only on quotes).
Spree 6.0 ships (6.0-b2b-customer-po-numbers.md): po_number on cart +
order (copied at completion, staff-correctable after placement as a plain
write), optional po_document private-storage attachment (an order-native
first), and po_number_required on Spree::Company — per-company per the
market and the merchant ask, deliberately NOT a catalog term (a PO
requirement is the buyer's procurement process, not the commercial
agreement, and no platform models it on the assortment/pricing side) —
enforced in Carts::Complete for customer checkouts. po_number is
ransackable and the dashboard order search matches order number OR PO
number. The Enterprise quote plan drops its own customer_reference +
attachment in favor of the order's fields. Naming guard: po_number (the
buyer's reference) and Spree::PurchaseOrder (the merchant's procurement
document, 6.0-inventory-operations.md) are opposite directions and never
share endpoints, serializers, or vocabulary. "Only an authorised buyer may
submit the company's PO" is Enterprise governance (company-role
capability), untouched here.
2026-08-30 — Payment terms split on the risk line; stages are data, statuses stay code; documents without invoices
The deposits/terms/documents feedback plus the maintainer's status-composer question resolved into three plans and one doctrine ruling.
Payment terms split where the risk flips (6.0-6.1-b2b-payment-terms.md):
collect-first terms (prepaid, N% deposit + a balance-due label — the
merchant's own "configurable label rather than automating every workflow")
are OSS; ship-first terms (Net N, due dates, credit, invoicing, dunning)
stay Enterprise roadmap item #1. The order carries one frozen
payment_terms snapshot resolved from layered sources — quote/order
override → company's PaymentTerm preset → the freight method's deposit
preferences (demoted same-day from anchor to default source; wholesale plan
amended) → none. The derived payment schedule (due-now, deposit state,
balance + label) is computed on read; Orders::UpdateStatuses is untouched
— partially_paid is the ledger truth, the schedule is the commercial
truth. PaymentMethod::BankTransfer joins core with public-preference
account details, and every payment gains a stored, generated, ransackable
reference (structured, RF-style) — deliberately never the derived
R1001-P1 number, whose NULL column had silently broken ransack search and
the Stripe find_by(number:) lookup (6.0 fixes recorded). Storefront
pay-balance lands 6.1 and resolves the wholesale plan's open question 1.
Stages are data; statuses stay code (6.1-order-stages.md): merchants
compose a per-store, ordered, customer-visibility-flagged stage axis in the
dashboard (Spree::OrderStage + nullable order_stage_id +
expected_ready_on on orders; Orders::SetStage publishing
order.stage_changed; optional auto-enter event bindings from the
Spree.order_stage_events registry — event-driven labeling, never
gating), while semantic statuses remain code-defined and workflow-written.
No transition graph, no commerce semantics on stages, ever — nothing
in checkout/payments/stock may branch on a stage; a needed gate is a code
status/workflow validation; per-store status vocabularies on has_status
models are forbidden (statuses are process-global code; per-store process
expression is this axis). Order is deliberately not migrated to
has_status. Landscape: no platform offers composed stages
(label-on-fixed-state and code-config-machine are the closest), so this is
an OSS first with a proven app-economy demand.
Documents without invoices (6.1-b2b-order-documents.md):
Spree::OrderDocument = uploaded files on orders (private storage,
per-document customer visibility, buyer uploads allowed), and two
client-side prints extending the shipped packing-slip pattern — a
carton/pallet/CBM packing list off the frozen freight summary and a
payment-instructions sheet off the terms schedule + bank reference. No
invoice vocabulary in OSS — no model, number, or document called an
invoice, no PDF stack in core; numbered proforma/commercial documents are
the Enterprise invoicing product. expected_ready_on is an order-level
merchant promise, deliberately distinct from the variant's
preorder_ships_at (supply fact) and the fulfillment's
estimated_delivery_at (carrier truth).
2026-08-30 — Enterprise B2B ships on 6.0 GA: registration mechanisms and the cart→draft copy pulled forward
Sequencing the whole plan set exposed a commercial inversion: both designed
Enterprise B2B products (company onboarding, quotes) depended on OSS pieces
scheduled for 6.1 — deferred there purely on the additive test, not
necessity — leaving Enterprise revenue features gated behind a release that
does not exist yet. Retargeted the same day:
6.0-b2b-company-self-registration.md (renamed from 6.1 — the activation
policy, approval_required posture, pricing_access codes and the
registration endpoint are small, additive, and exist for Enterprise to
build on) and the Orders::CreateFromCart phase of
6.0-draft-order-negotiation-mechanics.md (renamed from 6.0-6.1) both land
late in 6.0. This supersedes the "deliberately 6.1" clauses in the two
earlier entries above. Consequence: onboarding starts after the 6.0
front-door wave, quotes after 6.0 wave 1 — every designed Enterprise B2B
product needs nothing beyond 6.0 GA. Track C (credit terms/invoicing)
deliberately stays behind OSS 6.1 wave 6: it is roadmap-stage, and it can
begin earlier on the 6.0 payment_terms snapshot if needed (the kind
vocabulary is extensible and Enterprise may assign terms from its own
tables), adopting the OSS PaymentTerm presets, bank-transfer method and
payment references when they land.
2026-08-30 — Scope trim: lot tracking defers to 6.1
The counterpart of the same day's pull-forwards: limiting 6.0 scope. Lot
tracking is the biggest additive chunk in the new set (new table, FEFO
picking, receive/pick integration, admin surfaces), opt-in per variant, and
nothing in 6.0 or the Enterprise GA products depends on it — so it moves to
6.1 within 6.0-inventory-operations.md (the plan keeps both halves:
transfers/POs 6.0, lots 6.1). Flagged alongside: the transfer lifecycle's
removal of the one-shot StockTransfer.transfer API is that plan's one
breaking piece — it either uses the 6.0 window or ships in 6.1 behind the
standard deprecation bridges; decided when inventory-operations is groomed.
Further optional trims, in order, if 6.0 needs more relief: the one-go
catalog wizard polish, the wholesale storefront surfaces, automatic pricing
(last resort — the catalog wizard's ±% option wants it).
2026-08-30 — Audience price rules are grandfathered, not deprecated: no bridge, no data task
Revises, later the same day, the retirement clause of the
one-question-per-entity entry above. That entry deprecated
PriceRules::CustomerGroupRule and PriceRules::UserRule in 6.0 with a
one-release bridge and a data task
(spree:upgrade:migrate_audience_price_rules_to_catalogs) converting each
audience-targeted list into an assortment-less catalog assigned to that
audience. Both were built, then removed on review.
Decision: the two audience rules are grandfathered on exactly the terms
PriceRules::ChannelRule already had — they keep matching indefinitely,
carry no removal date and no creation warning, and there is no upgrade step.
The only change that ships is a discovery-level flag: superseded? on the
rule class surfaces as superseded: true in
subclasses_with_preference_schema (present only when true, so rule families
without the concept keep their wire shape byte-identical), and the dashboard
rule picker filters those kinds out. Existing rules render, edit and match
unchanged.
The reasoning is that the data task only ever existed to service the removal. Once the classes simply keep working, converting is churn a merchant gains nothing from — and an automatic remap of who gets which price is exactly the class of change that is expensive to get wrong and invisible when it is. The doctrine goal was never to delete rows; it was to stop offering two mechanisms for one question, which hiding the kinds achieves on its own. It also removes the awkward middle state where a store that upgraded but never ran the task was one release away from silently losing its audience pricing.
Accepted trade-off: two mechanisms for audience targeting remain in the codebase permanently, with the precedence the resolver already defines (catalog-owned lists first, then rule-matched lists). New work builds only on catalog assignment.
Nothing else in the one-question-per-entity entry changes: the binding
inversion, the leak fix, and the catalog-first dashboard direction all stand.
Plans amended: 6.0-catalog-agreement-rework.md (Key Decisions + phase 3),
6.0-b2b-companies-and-catalogs.md (amendment block).
2026-08-30 — Draft-order negotiation mechanics implemented; payment lookup keys on the prefixed id
The full 6.0-draft-order-negotiation-mechanics.md scope shipped in one
pass, including the "6.0, late" Orders::CreateFromCart (small and
independent — no reason to hold it) and, per the Wave 1 roadmap bundling,
the payment-number search fixes owned by 6.0-6.1-b2b-payment-terms.md.
Two mechanism choices worth recording. The reserved-key check and the
'manual' constant live on the lightweight Spree::PricingProvider
module (LineItem aliases it), because the boot-time
verify_registry! call must not constant-load the model graph early —
doing so reorders Preferable#defined_preferences, which reads Ruby's
methods order, and churns the generated OpenAPI preference schemas. And
the Stripe gateway's broken find_by(number:) resolves through a new
payment_prefixed_id entry in GatewayOptions#to_hash — the plan said
"corrected" without naming the mechanism; the prefixed id is the same
stable handle the idempotency key was already built on, and "nothing
durable keys on derived payment numbers" ruled out anything parsed from
the number itself. The stored-number lookup stays as the legacy-row
fallback.
2026-08-30 — Order editor previews staged edits; the client-projection ban narrowed to exactness
Making the draft-order unit price editable turned the edit screen's "totals are server truth" stance into a misleading one: staging a revert redisplayed the very price being abandoned, struck through, while every total sat frozen. Reported from live UI review, not caught by any spec — each number was individually correct and collectively wrong.
The screen now previews staged edits as a before/after diff on the unit
price, line total, subtotal and grand total. This narrows, but does not
delete, the 6.1-order-change-substrate.md constraint against computing
projected totals client-side. The line is exactness, not arithmetic.
Price × quantity is exact, so the subtotal projects. The grand total
projects ONLY when shipping, tax, discounts and fees are all zero — where
the total simply is the subtotal — and falls back to the server's figure
the moment any of them is non-zero, because a quantity change can cross a
shipping band or a promotion threshold and no client arithmetic can know
it. A row that cannot be projected (a revert with no catalog price) nulls
the entire projection rather than contributing a partial sum: a total
stated confidently and wrongly is worse than a stale one.
Supporting change: the admin line-item serializer gained catalog_price
(the variant BASE price, not a resolved one — resolving would call the
pricing provider once per row on a read path the third-party-pricing plan
keeps provider-free). It is a comparison figure, not a promise: the revert
re-prices through the resolver and may land elsewhere. It required
eager-loading variant prices in the orders controller's own scope, which
bypasses scope_includes — 15 price queries per order page became 1.
2026-08-31 — Percentage adjustment is a catalog-owned feature; a standalone list must have something to apply to
Revises the same-day automatic-pricing decision, which put the ±% Pricing card on the standalone price-list page as well as the catalog page.
The finding. A percentage list has no product scope of its own: it adjusts every variant it is asked about. On a catalog-owned list the catalog's assortment draws that line, because the audience only ever sees (and so is only ever priced on) what the assortment allows. On a standalone list nothing draws it. A rule-less standalone −15% list put the entire store on sale for every shopper — and adding products to that list, which the UI offered and counted, changed nothing at all. A control that looks like it scopes and does not is worse than a missing one.
Decision. price_adjustment_percentage may only be set on a list a
catalog owns (a PriceList validation; Catalogs::SetPriceList creates
owned lists with their catalog_id already set). The standalone price-list
editor no longer offers the percentage at all. Open consequence for the plan's headline case — automatic volume
pricing, a VolumeRule plus a percentage: an owned list's own rules are not
consulted by the resolver (catalog_price_lists selects on status and dates
only, per the catalogs doc), so that combination has no working home until
owned lists honour their context rules. Deciding that is the next call;
recorded here rather than silently changing resolver semantics. A product-scoped store-wide percentage discount ("−15% on these 40
SKUs for everyone") is a Promotion's job: promotions already have product
rules and a percent action, and it is a campaign, not an agreement.
Also. A standalone list with no rules, no catalog and no products is
refused activation (PriceLists::Activate). Such a list applies to
everyone and prices nothing; a draft may sit that way while it is built,
but making it live is refused so that emptiness reads as the mistake it is.
Rejected: letting the list's own products scope an automatic list, with "no products" meaning "everything". That reintroduces the exact leak the catalog rework closed — remove the last product and the whole store goes on sale — as a default rather than an accident.
Plans amended: 6.0-price-list-automatic-pricing.md (Key Decisions, API +
dashboard), 6.0-catalog-agreement-rework.md (unchanged in substance — the
catalog page was always the card's home).
2026-08-31 — An owned price list honours its contextual rules, and only those
Settles the open consequence recorded in the catalog-owned-only decision earlier today, which left automatic volume pricing — the automatic-pricing plan's headline case — with no working home.
The finding. The resolver reaches a catalog-owned list through the
catalog and selects it on status and dates alone; applicable? is never
called, so an owned list's rules are inert. Meanwhile a percentage may only
live on an owned list. The two halves of "a VolumeRule at min_quantity: 10 plus −5%" were therefore in different rooms: the resolver specs prove
it, testing volume pricing only on standalone lists with hand-entered rows
and percentages only on rule-less owned lists.
Decision. Owned lists consult their contextual rules and ignore
their audience rules. The split is a class-level predicate on the rule,
PriceRule.contextual?, beside the existing geographic? and
superseded? — not a constant listing type names, since extensions
register rule kinds of their own and a frozen list would silently exclude
them. VolumeRule is contextual; every other core kind is not.
The reasoning is that an owned list has already been matched on audience by
the time the resolver holds it — the catalog assignment is what selected it,
nearest node first. Re-asking a CustomerGroupRule there could only narrow
an audience the agreement already decided, which is the second answer to a
question the doctrine says one entity owns. Quantity is different in kind:
no catalog assignment can express "when they buy ten", because it is a
property of the purchase and not of the buyer. Dates and status already
gate owned lists and are unchanged.
Consequences. Catalogs::SetPriceList accepts rules on the inline
payload, and the catalog editor offers the contextual kinds only — the
picker filters on contextual? for an owned list exactly as it filters on
superseded? elsewhere. An owned list carrying no rules behaves exactly as
before, so nothing merchants have already set up moves.
Rejected: consulting every rule on an owned list. That re-litigates the
audience inside the agreement and would let a stale CustomerGroupRule
silently switch a negotiated price off. Also rejected: a separate
quantity-tier table on the list — price rules already express the
predicate, and a second vocabulary for the same question is what the
one-question-per-entity doctrine exists to prevent.
Plans amended: 6.0-price-list-automatic-pricing.md (Key Decisions,
Resolution), 6.0-catalog-agreement-rework.md (Constraints — owned lists
are no longer rule-free).
2026-08-31 — Quantity rules: the divisor ships early, completion refuses, the storefront follows
Implementation of 6.0-b2b-quantity-rules.md settled four questions the
design left to the build.
units_per_carton moves to the quantity plan. The carton purchase unit
is a display vocabulary that needs a divisor, and the wholesale-shipping
plan that owns the packing chain is design only. Rather than ship a flag
that does nothing, the single column lands with the feature that first uses
it; wholesale shipping still owns carton_package_type_id,
carton_weight and cartons_per_pallet and must not re-declare it. The
alternative — waiting — would have meant either no carton vocabulary in 6.0
or pulling an unbuilt plan forward wholesale.
Completion refuses an out-of-rule line rather than warning. Rules can
change between add-to-cart and checkout (a company reassigned to a different
tier, a catalog term edited), so every line is re-checked at completion
through Checkout::Requirements with completion: true — the same place
out-of-stock and discontinued lines are already refused — with the message
naming the nearest valid quantities. Letting a below-MOQ wholesale order
through is the five-figure surprise the feature exists to prevent.
The order minimum is advisory before completion and blocking at it. The
shortfall rides the requirements feed as an advisory requirement so the
buyer reads "$180 to reach the $500 minimum" while they can still act, and
becomes refusal only when completion is attempted. Staff-initiated carts
(created_by_id present) skip both the line re-check and the minimum —
the same exemption po_number_required takes, for the same reason: staff
key in what the buyer actually negotiated.
The storefront ships separately. The Next.js selector, carton display
and shortfall banner land on spree/storefront afterwards. The Store API
exposes the buyer's resolved rules on the variant and the minimum plus
shortfall on the cart, so neither side blocks the other.
Plans amended: 6.0-b2b-quantity-rules.md (implementation started),
6.0-b2b-wholesale-shipping.md (units_per_carton no longer its column).
2026-08-31 — Catalog phase 4: the agreement's prices are shown where it is curated, and a new one is built in steps
Settling the last of the catalog agreement rework
(6.0-catalog-agreement-rework.md), whose remaining work was the
products-with-prices view and a create flow worth the name.
The resolved price and its source ride the catalog's own products
endpoint, behind expand. A catalog's nested membership listing answers
?expand=catalog_price with the amount a buyer on this agreement pays and
where that amount came from: an explicit row on the owned list, the list's
±% adjustment, or the variant's base price. Resolution stays server-side —
an adjusted price is derived on read and never stored, so a dashboard
inferring the source from the price rows would be re-implementing the
resolver against a shape it cannot observe, and would be wrong the moment
base prices move. expand rather than a bespoke query flag, because every
other optional payload on this API is asked for that way.
Those prices are columns on the assortment card, not a second surface. Assortment↔pricing divergence — a product in the agreement that the agreement does not actually price — is what the view exists to expose, so it belongs on the rows the merchant already curates. A parallel prices card, or a tab beside the assortment, both turn the divergence into something to go looking for, which is the state before this work.
The transitional price_list_id accessors on Spree::Catalog are
removed. They kept the admin API's pre-inversion write shape working
until phase 4 reshaped the payload; the inline price_list object has
done that, so the accessors, the pending-assignment machinery behind them
and the serializer attribute all go. Catalogs are unreleased, so no bridge
is owed — the same reasoning that let the migration be rewritten in place.
New catalog becomes a linear four-step wizard: Details → Audience → Pricing → Review. Back and Next only, with one create request on Finish carrying the whole agreement. Nothing is written until then, so abandoning midway leaves nothing behind — the staged-until-Save model the agreement editor already uses, and the reason a create-then-configure wizard was rejected. The assortment is deliberately not a step: product membership stages against a saved parent through the nested endpoints, and a first catalog is more usefully curated on the agreement editor the wizard lands on. Rejected alternatives: one sectioned create page (consistent with other create screens, but it asks a merchant standing up their first agreement to understand every part of it at once); skippable steps (a "create now" escape hatch competing with Next on every step).
Plans amended: 6.0-catalog-agreement-rework.md (phase 4 completed).
2026-08-31 — Wholesale shipping backend: the store's box becomes a row with no bridge, and unpriced rates carry the logistics instead of a price
Phases 1–6 of 6.0-b2b-wholesale-shipping.md — everything below the
dashboard and the storefront. Three rulings other plans need.
The four default_package_* store preferences are deleted outright, with
no deprecation bridge. A recorded exception to the always-bridge
convention, and the reasoning is narrow enough to be worth stating so it is
not read as a precedent: those preferences were added inside this same
unreleased 6.0 cycle, so no released version exposes them and there is no
caller to keep working. A bridge writing through to the new default
PackageType row would have left two spellings of the store's shipping box
coexisting for a release, each able to disagree with the other in the
dashboard, in exchange for compatibility nobody can be relying on. The
upgrade task (spree:package_types:backfill) creates each store's default
row from the preference values, which is what makes the removal safe. The
convention still holds for anything that shipped: bridge it.
An unset variant dimensions_unit follows the store's unit_system —
imperial reads as inches, metric as centimeters — rather than gaining a
default_dimensions_unit store preference to mirror weight_unit's
fallback. The store already answers "what do dimensions mean here" through
unit_system, which is what the box preferences and the EasyPost provider
have always read; a second settable value could contradict it, and the
merchant would have no way to tell which one a number obeyed.
An unpriced rate is a rate with no price, not a rate priced at zero.
Spree::DeliveryRateProvider::Estimate and spree_delivery_rates carry an
unpriced boolean; the estimator skips markup and tax gross-up for those
rows, and DeliveryRate#free? answers false for them so nothing renders
"Free" over a shipment whose cost is genuinely unknown. This is the
mechanism the plan's constraint points at — a zero-cost priced rate is the
workaround it exists to prevent. Spree::FreightSummary (units, cartons,
pallets, CBM, gross weight, complete?) rides in the estimate's metadata
and is frozen onto the selected rate at completion, never re-derived from
the live catalog afterwards.
Everything money-shaped stays for phase 7: deposits, the completion payment-sufficiency change and the partial-payment order surfaces are not in this cut. Constraint unchanged and now load-bearing: nothing may assume a completed order is paid in full once phase 7 lands.
Plan: 6.0-b2b-wholesale-shipping.md (phases 1–6 implemented).
2026-09-02 — Order cancellation and approval history tables are dropped; the reason lives on the order
Reassessing 5.5-6.0-order-cancellation-and-approval.md before its 6.0
half (drop the canceled_at/approved_at columns, multi-level approvals).
The two tables it added in 5.5 turned out to be write-only: the cancel and
approve services inserted a row and nothing ever read one — no endpoint,
serializer, view, mail, export or task — and the cancel endpoint never
accepted a reason, so every row said other. Worse, the record's
restock_items and refund_payments flags described decisions the
workflow did not take (items are always restocked through fulfillment
cancellation; an ordinary order's captured payments are always canceled),
so as an audit trail it misstated what happened.
Decision: drop both tables in 6.0 (if_exists, the 5.5 migrations
deleted so fresh installs never create them) and keep the cancellation on
the order itself — the shape every major platform uses and the one the
codebase already needs, since Ransack, sorting, the CSV export and staff
anonymization read canceled_at as a column. Nothing is carried over: no
row ever held more than the default.
The reason is merchant data, in its own table. cancel_reason_id
points at a new Spree::OrderCancellationReason — the fourth
NamedType vocabulary beside return, claim and refund reasons:
store-scoped, seeded per store, restrict_with_error while orders
reference it, managed on the Settings → Reasons page that already renders
its siblings, and optional like Return#reason. A fixed string list was
written first and rejected on the 2026-08-07 Claim#claim_type grounds —
nothing branches on the value, so a closed vocabulary asks the merchant a
question it will not act on, while the neighbouring reasons are theirs to
write. Merging the four into one table behind a kind was also rejected:
they carry different associations and delete guards, RefundReason has
named lookups core itself attaches to refunds, NamedType already factors
out everything shared, and one wider index replaces four DB-enforced ones
— typed tables per grain, as the quantity-rules plan puts it. The workflow
refuses a reason from another store, so console and extension callers get
the scoping the controllers apply to every incidental id. Orders::Approve
stays what it was, the risk-review clearance (considered_risky +
approved_at); a merchant-side multi-level approval of a placed order has
no industry precedent (the nearest thing elsewhere is a fulfillment hold),
and buyer-side company approvals are Enterprise (2026-08-30). level: /
note: on Approve and restock_items: on Cancel warn and are ignored
until 6.1.
Constraints now: no cancellation or approval history tables; a future customer self-cancel makes the actor on the order polymorphic — a column change, never a side table; company approval flows stay Enterprise and carry their own record.
2026-09-05 — The dashboard owns every string it shows; the Admin API sends codes
Type names and descriptions for pluggable kinds (price, promotion, collection,
routing, delivery-method and commission rules, promotion actions, calculators,
seller requirement kinds, integrations, the permission catalog) and the text
inside Admin 422 responses were produced in Ruby through Spree.t, in the
request locale, which the dashboard never sets. Interface language and rule
labels therefore disagreed whenever the two locales differed, and each type was
being fixed one en.yml key at a time (PR #14575). The Admin API was a preview
and can change: type catalogs and records are identified by their stable type
code, validation details carry the Rails error code with its parameters, and
the dashboard translates both from its own locale files. label, description
and message remain on the wire as fallback text for integrations and for
extension types without a dashboard translation, never as UI copy. The Store
API is untouched: the richer 422 shape lives in the Admin base controller, not
in the shared error handler. The dashboard keeps its UI language out of
x-spree-locale, which selects the content locale a merchant edits. Plan:
6.0-admin-ui-owns-its-copy.md.
Four follow-on questions were settled the same day when the plan came up for
implementation. The type catalogs keep label/description as a
documented fallback: dropping them would force every extension gem shipping a
Ruby type to also ship a dashboard plugin with locales, or merchants read a raw
code, and the fallback gives the migration itself a safety net. Built-in types
still lose the Ruby copy methods that exist only to feed the wire. reject!
takes the code as its first argument (reject!(:not_awaiting_review),
reject!(:below_minimum, count: 5)), reusing errors.add(:base, symbol, **params) unchanged rather than growing a second keyword signature; strings
keep working so conversion is incremental. Every core error call site
converts in one run, so no message-only fallback path remains in core and
specs assert on errors.details codes instead of English sentences. Shared
type-label and validation keys live in @spree/dashboard-core, which already
ships all six locale files, so the Seller Panel inherits every language by
importing the helper instead of duplicating locales.
Constraints now: new pluggable types ship their admin.types.<family>.<code>
keys in every dashboard locale, not a Spree.t label; new validation errors in
core use a symbol and parameters, never a preformatted string; nothing in the
dashboard prints an API label/name/description directly; shared admin copy
goes in dashboard-core locales, never in packages/seller-dashboard.
2026-09-07 — A column that changes row identity is not finished at the writers
Building volume pricing (6.0-volume-pricing.md) added min_quantity to
spree_prices, giving a variant several rows per price list where it had
one. The writers and the resolver were updated; the readers that never
ask the resolver were not, and that is where it showed.
Spree::Product#price_varies? and #lowest_price iterate the product's
prices — a has_many through: variants covering every row, price-list
rows included. On sample data a toaster with a B2B agreement attached
advertised "from $23.99" — a private contract rung — against a $39.99
shop price, and reported its price as varying when it does not. The same
shape sat in Products.with_currency,
Variant.for_currency_and_available_price_amount and the line-item
currency swap, which picked prices.where(currency:).first with no list
filter and could now land on an arbitrary rung.
The leak predates the column. Any price-list row already caused it,
since none of those readers filtered price_list_id. What
min_quantity changed is the odds: one stray row became a ladder of
them, and the cheapest is the one a "lowest price" reader finds. Fixed by
giving Product a shop_prices reader and scoping the three others to
base prices.
The reusable part: when a migration adds a dimension to a table,
grep every reader that counts, joins to, or picks from that table without
going through the thing that owns its semantics — here the pricing
resolver. Updating the writers and the one canonical reader is the half
of the job that is easy to see. Pricing paths were fine throughout:
Pricing::Context carries quantity everywhere it matters and the cache
key includes it.
2026-09-07 — Volume pricing implementation: CSV deferred, the cap is a validation, and a ladder needs no quantity-1 rung
Settled before building 6.0-volume-pricing.md. Three of the four are
narrow, one removes scope.
Price-list CSV is deferred rather than shipped. The plan called for
"CSV import/export of a list gains a min_quantity column", but no
price-list CSV surface has ever existed — the only price columns in any
export are the product CSV's base price / compare_at_price. Adding a
column to a pipeline that is not there is a whole export model, presenter,
import parser, endpoints and dashboard affordance: a feature of its own,
not a phase of this one. Recorded so the next person building a
price-list CSV carries min_quantity in its first version. The product
CSV stays untouched — breaks require a price list in v1, so every base row
is quantity 1 by construction and the column could never vary.
The ≤10 break cap is a model validation scoped to
(variant, currency, price_list), and the bulk-upsert path refuses a
batch that would cross it. A dashboard-only cap leaves the API unbounded,
and the resolver scans a variant's rows per priced line, so an unbounded
ladder is a cost paid on every cart recalculation.
A ladder needs no quantity-1 rung. A list may price a variant only
from 24 up; quantities below fall through to the next list or the base
price exactly as they do for a variant the list never priced. That is the
"wholesale from a case" agreement, and requiring a base rung would make
bulk writes order-dependent (a batch inserting 24 before 1 would have
to be sorted to pass). The tier editor locks its first row to 1 when one
exists, which is a convenience and not a rule.
Both tier editors ship together — the price-list bulk editor and the catalog's products-with-prices view — because they are one component with two homes, and shipping one leaves the other showing a "+3 tiers" badge nothing can open.
2026-09-07 — Three merchant asks resolved: market availability, the lot tier split, and the volume-pricing doctrine
The next feedback batch (market exclusions, lot detail + tier question, volume pricing) resolved after three research passes (per-market availability, lot landscape, volume-pricing implementations).
Product market availability is a product-level territory axis
(6.1-product-market-availability.md): nullable
spree_products.market_availability (NULL = all markets — zero backfill,
exceptions-only join rows, new markets correct by construction) composed
with publications as an intersection evaluated per request — published
on the channel ∧ available in the market — with full hiding (the
market-competent platform's choice; a "not available here" PDP advertises
the product the distributor holds rights to) and a completion validation
for the mid-cart market change no platform handles. One Availability card
shows both axes (their de-confusion recipe). Deliberately NOT a market
catalog — the 2026-08-28 closure stands; catalogs answer buyers, this
answers territory. Channels were considered and rejected as the wrong
axis (a channel per territory to hide two products is the duplication the
merchant rejects). Constraints: availability is never denormalized; every
market-context read surface applies the scope.
Lots split on the depth line (maintainer's call, 2026-09-07 —
supersedes the 2026-08-30 all-OSS decision and its 6.1 scope-trim note):
OSS 6.1 keeps simple lot capture — Spree::FulfillmentLot rows
(fulfillment item × lot number × optional quantity for split batches),
advisory lot_tracked prompt, ransackable recall search both directions;
the lot library (received-lot StockLot inventory, quantities,
expiry/manufactured dates, supplier references, manual/FIFO/FEFO
auto-allocation, the transactional count_on_hand decomposition) moves to
Enterprise (ee/docs/plans/inventory-lots.md), whose
allocation writes the same OSS capture rows so recall reads one
surface on either tier. Landscape recorded with the trade-off: no platform
ships lots natively at any tier, the app market monetizes exactly this
depth ladder ($10 record-and-alert vs $24–199 library+FEFO), the one full
open implementation (the ERP benchmark) is free in its community edition,
and the traceability-lot-code compliance wave (July 2028) is why level-1
capture stays OSS. Constraint: lot capture lives only on FulfillmentLot
rows — no lot strings anywhere else, and OSS never grows quantities,
expiry, or allocation.
Volume pricing: promotions = DTC consumers, price lists = B2B — the
one-sentence tier doctrine (6.0-volume-pricing.md). Fixed contracted
ladders become a price-row dimension: spree_prices.min_quantity
(integer default 1 — every existing row is a quantity-1 price, zero
backfill; row identity gains the column; resolver picks the highest break
≤ line quantity; ≤10 breaks; breaks require a price list in v1; a break
ladder beats the list's ±% per variant — the market leader's stated
precedence). Percentage ladders become quantity bands on the list's ±%
adjustment (spree_price_adjustment_tiers: list × min_quantity ×
percentage, falling back to the column) — this superseded, same day, a
briefly-drafted promotions-based percent design: the implemented
adjustment already treats percentage as pricing (computed on read, unit
prices, never touching explicit rows), so bands answer "percent off what"
with the implemented semantics, while marketing-visible volume discounts
(strikethrough, D2C) remain promotion territory as a recorded deferred
design (line-quantity rule + quantity-tiered percent calculator).
Research verdict behind it: every platform with real volume pricing
attaches tiers to the price record; nobody models them as list-matching
rules; quantity RULES (MOQ/multiples) stay a sibling non-pricing axis
everywhere — validating the existing quantity-rules split. Constraints:
contracted tiers are never discounts, marketing discounts are never
prices; price-reading callers must pass line quantity through
Pricing::Context; exports must carry tier rows.
2026-09-07 — Price-list CSV: SKU-keyed rows, a merge import, both homes, a sample ladder
Settled before building the follow-up to 6.0-volume-pricing.md, which
had deferred the price-list CSV because no such surface existed.
Rows are keyed by SKU, as the product CSV's are, and the file carries
only the columns the import reads (2026-09-08: read-only product and
variant columns were dropped — a column that changes nothing on the way
back reads as if it would). A SKU-less variant or a SKU shared across
sellers fails its row with a message. A
prefixed variant_id fallback was rejected as a second rule for a case the
product CSV does not cover either.
The import merges. Rows in the file are upserted, a blank price removes
that rung, and rungs absent from the file are untouched — the bulk price
editor's semantics, reached through the same Prices::BulkUpsert. A
replace mode was rejected: destructive, and a half-failed import leaves a
half-replaced list. Consequence for the export: placeholder rows are not
written — a blank price on re-import would remove the product from the
list, so an unchanged export must re-import as a no-op.
Both homes. Export and import sit next to "Edit prices" on the price-list page and on the catalog's pricing card, for the reason the tier editors ship in both: a merchant editing an agreement should not have to leave it.
A sample file ships in db/sample_data and sample data loads it onto
the Wholesale list — the import sheet's example download is then a real
ladder, and a fresh QA environment shows breaks without a script.
2026-09-08 — Price list rows are the membership model, and a job keeps them in step with the store's currencies
A store that added a market with a new currency found its existing price lists empty in that currency: the spreadsheet shows a currency's products through the list's quantity-1 placeholder rows, and those were materialized only for the currencies known when the products were added.
Kept: placeholder rows define membership. add_products writes a
row per variant × store currency; the products endpoint, the "N prices
configured" count and the spreadsheet all read those rows. A
Spree::PriceLists::SyncCurrenciesJob now runs for the store after a market
is created or changes currency; it re-runs add_products for what each list
already holds,
which inserts only the missing currency's rows. A removed currency keeps its
rows — dropping merchant-typed prices is not a side effect a market edit may
have. Markets are the only trigger: a store's currency set is
configured through them, and the legacy supported_currencies column is no
longer editable. The CSV import materializes the same placeholders for the products it
prices, so an imported product is on the list the way an added one is.
Not taken: derive the grid from membership. The spreadsheet could build its rows from the list's products and variants and show empty cells for any currency with nothing to sync. It would move the row model out of the database into the editor: the products endpoint would have to hand the editor variant rows, and the count and empty-state logic would follow. One model in one place, kept true by an idempotent job, was the smaller change.
2026-09-05 — A CSV names its carton rather than referencing one
Settled while building the wholesale plan's variant import.
A CSV names its carton; it does not reference one. A merchant's
spreadsheet says "Large carton", not a prefixed id, so the products import
resolves the carton by name — and resolves it through store.package_types,
so a name that matches another store's carton leaves the variant unpacked
rather than borrowing somebody else's measurements. The tax-category lookup
beside it is not store-scoped and was left alone: widening it is a
separate correctness fix with its own blast radius, not something to smuggle
into a packaging change.
Constraint now: a new named lookup in an importer resolves through the store's own association.
2026-09-08 — Package types are the seller's to own; the marketplace's are shared vocabulary
Settled in 6.0-seller-package-types.md.
A package type follows the seller side of the marketplace plan's Decision
13. "What kind of goods is this" (profiles, zones) is the marketplace's
question; "who ships it, how, and in what" is the seller's. Cartons and boxes
are the third clause, so spree_package_types.seller_id is nullable and a nil
owner is the marketplace's row, exactly as for delivery methods and stock
locations. The operator's rows are readable by every seller with no opt-in
flag — a carton is geometry and a tare, nothing to protect — while a seller's
rows are theirs alone. A package is quoted with its stock location's seller's
default box, falling back to the marketplace's.
One default per owner needs two partial indexes, not one. A nullable column inside a unique index constrains nothing for the rows where it is null, so "one default per (store, seller)" is enforced as one index for marketplace rows and one for seller rows; the name index is split the same way. MySQL, which has no partial indexes, relies on the model validations for marketplace rows — do not weaken them on the grounds that an index covers it.
A seller is asked for their box, never blocked without one. A computed
Spree::SellerRequirements::PackageType kind, provisioned by default, is met
by a default box with all three dimensions and a weight recorded. It does not
count the marketplace's box: a seller on shared rates still posts their own
parcel.
Constraint now: code that needs "the box for this package" reads
Stock::Package#default_package_type, never store.default_package_type;
seller-facing reads go through available_to_seller(seller), seller writes
through seller.package_types.
2026-09-09 — A seller's own books get their own permission key, and a grouped order's payments are read where they were taken
Making the marketplace fund ledger visible (docs/plans/6.0-seller-ledger-ui.md)
forced two questions that outlive the screens themselves.
The seller ledger is seller_earnings, not seller_profile. The obvious
move was to reuse the profile key, the way PoliciesController does for a
class the operator's settings owns. It was rejected: settlement
configuration is the seller's profile, but what they have earned is their
books, and a seller's owner must be able to hand a packing teammate the orders
without also handing them the money. So a new read-only, seller-audience
catalog resource with a symbol subject — the ledger classes stay subjects of
the operator's payouts key, and claiming them twice would make
scope_for_resource answer by registration order. The cost is real and was
accepted knowingly: a role holds the keys it was created with and is never
re-read, so a key added to the catalog reaches new roles only. That is
harmless here because sellers are new in 6.0 and no older role exists — but a
seller-audience key added after 6.0 ships needs a backfill task, and the
question to ask before adding one is always "which existing roles does this
silently not reach?"
A grouped child order's payments are the group's, read-only, with the
child's share beside them. order.payments is empty on an order from a
split checkout, so the operator's payments card rendered "no payments" on an
order that was paid in full — wrong, not merely incomplete. The fix reads the
group's payments and the order's payment_splits and shows both, and it
deliberately does not re-point Admin::OrderSerializer#payments at
settlement_payments: that would change what order.payments means for every
consumer, and capture/void through orders/:id/payments would then act on
every sibling's money without saying so. Capture, void and add are hidden on a
grouped child for the same reason — they belong on a surface that names every
order they touch.
Constraints now: a seller-facing money serializer carries amounts, never
provenance (no payment id, method, gateway status or source — Seller:: PaymentSplitSerializer and Seller::TransferSerializer are the reference);
seller ledger endpoints authorize :seller_earnings and root in
current_seller, never by opening payouts or payments to the seller
audience; and a new q[<column>_eq] filter on either ledger model needs that
column in whitelisted_ransackable_attributes — a whitelisted association
name does not make its foreign key filterable.
2026-09-12 — Reporting: the carts family, and abandonment is not the reaper's population
The reporting vocabulary gains a fourth family. A cart is its own table in 6.0,
so abandoned carts and cart conversion are a :carts base anchored on
created_at, never a filter on orders: the population being measured is the
carts that were started, and anchoring on completion drops every cart that
never converted — the exact rows the report is about. The one-family rule
refuses to mix carts with sales for the same reason it refuses sales with
inventory; the two clocks mean different things.
Abandonment is incomplete + untouched for the store's
abandoned_cart_after_hours window, and nothing else.
Carts::ReapExpiredJob additionally excludes carts carrying a live payment
session or a valid payment, and reporting deliberately does not inherit
that: the exclusion is there so the reaper cannot destroy rows with money
attached, not because such a cart is un-abandoned. A cart stalled mid-payment
is the most recoverable kind there is, and dropping it would hide the rows the
report exists to surface. The report and the reaper therefore disagree about
which carts they mean, which is recorded because they otherwise look like they
should match. Consequence worth knowing: the reaper destroys abandoned carts at
30 days (guest) / 90 days (customer), so an abandoned-cart report over a longer
range under-reports because the rows are gone.
Promotion attribution reads spree_discounts, which carries
promotion_id, promotion_action_id and a snapshot of the redeemed code on
every money row. Three rules bind anyone adding to it: amount is non-positive
by DB constraint so metrics sum -amount; promotion_id is nullified rather
than cascaded on deletion so the dimension must group NULL as "Unassigned"; and
rows are order_id XOR cart_id, so a sales-family join that omits the owner
filter mixes unpurchased cart discounts into revenue. Redemptions count
checkouts (COALESCE(order_group_id, id)), not orders — a multi-seller basket
is one redemption.
Constraints now: a metric filter (HAVING) never touches the ungrouped
totals query — the Total stays the period's real figure; a new grain is taught
to time_bucket_sql and expected_buckets together, because an unhandled
grain falls through to nil and silently groups by NULL rather than raising;
and cart_conversion_rate is never renamed to conversion_rate — storefront
conversion needs session data that never reaches Spree, and the two numbers
must not be confusable.
Reporting refusal data is registry data, not compiler data. The compiler
briefly held three hardcoded lists — which metrics need grouping, what to
suggest when an order-level metric is refused for a per-line breakdown, and
what each family's clock means. All three are now fields on the definitions
(requires_grouping: and suggests: on a metric, clock: on a base), for the
same reason a base is registered rather than hardcoded: an extension's own
metric must get the same refusals and the same advice without editing core.
per_group as a boolean was the wrong shape — it could say a metric needed
grouping but not by what, so the dimension was hardcoded in the validator
beside it.
Customer lifetime value needs spree_orders (store_id, email). The metric
correlates a customer's whole history on email, which had no index at all, so
each customer group drove a full scan; and it walked that history twice, once
for totals and again for refunds. One pass over the new index. Anything else
correlating on order email needs the same index to be viable.
2026-09-13 — Stored value is not a promotion: gift cards and store credits live under Loyalty
Plan: 6.0-6.1-loyalty-gift-cards-store-credits.md.
Gift cards sat under Promotions in the dashboard nav and in the user docs because both reduce an order total at checkout. That is where the likeness ends. A promotion is marketing: margin given up to change behaviour. A gift card or a store credit is prepaid money the store owes, a liability with a balance, redemption statuses and a ledger, and no rules or actions. Every platform in the comparison keeps the two apart; so does our model.
Decision. A top-level Loyalty group holds Gift Cards and a new
cross-customer Store Credits list, and is the home for any rewards or points
programme later. Promotions keeps only the discount machinery. The
gift_cards and store_credits permission keys move to a loyalty group;
the key names do not change, so existing roles keep working.
Store credits are edited per customer and listed across customers.
GET /admin/store_credits (index, show) is read-only; create, update and
destroy stay nested under /customers/:id/store_credits. The list carries
meta.totals, one grouped sum per currency over the filtered scope, so the
same list answers "this customer's balance" and "the store's liability"
depending on the filter. A separate balances resource was rejected because it
could not follow the filters; waiting for Reports was rejected because the
list would then answer "who" but not "how much".
Consequences for other work. Anything that should not apply to prepaid
money (tax, promotions, inventory, shipping, paying a balance with a balance)
must check one predicate on the product, gift_card?, which phase 2 adds as
a boolean on spree_products. Do not introduce a second "non-physical" flag
that would need reconciling with it. Gift card codes never appear in events,
logs or the buyer's order payload; only the recipient email carries the code.
Recipient details get their own table rather than columns on
spree_line_items or keys in metadata.
Two implementation calls settled when phase 1 was built (2026-09-13). The
cross-customer store credit list opens a read-only detail sheet carrying the
credit's amounts, origin, issuer, memo and its StoreCreditEvent ledger, and
links out to the customer profile for edits — the list never writes, so the
"writes stay nested under the customer" constraint holds without exception. The
per-currency meta.totals render as one summary card per currency above the
table, showing outstanding, issued and used; a single line or a footer row
cannot carry three figures per currency once a store trades in more than one.
2026-09-14 — Store configuration is a file deployed through the Admin API, not Ruby seeds
Plan: 6.0-cli-configurator.md.
Shaping an environment (channels, markets, tax, delivery, payment methods,
catalog, customer groups, roles, origins, webhooks) was only possible from
Ruby: db:seed, spree:load_sample_data, or Ruby embedded in the
dashboard's e2e global setup. None of that works against a hosted instance,
none of it is reviewable as a change, and headless teams on the API-only
install may never open the Rails side.
Decision. spree config diff | deploy | introspect | validate in
@spree/cli reconciles a YAML file against a live store through the Admin
API. YAML is canonical (comments, block text, clean diffs); JSON is accepted
because YAML is its superset; no defineConfig() TypeScript form. Records are
matched on natural keys, never prefixed IDs. Deploy is additive: deletes
happen only in sections named in --prune, and --fail-on-delete refuses any
plan with a delete. The engine lives inside @spree/cli as an exported
library entry so the dashboard e2e setup imports it. Every project scaffolded
by create-spree-app ships a spree.config.yml with the store, its default
channel and default market, and spree init deploys it.
Bootstrap stays in Ruby. The store row, the immutable admin role, the
first admin user and the first API key have no API by design and a Rails app
must seed without Node, so Spree::Seeds::All does not shrink. Transaction
data (orders, payments, fulfillments, payouts) is never configuration.
Consequences for other work. A new admin-manageable resource needs a
stable, unique, human-readable key (code, slug or name, unique per store,
backed by an index) and that key on its Ransack allowlist, or it cannot be
declared in a config file. Credential attributes on payment methods and
integrations must never read back in plain text through the Admin API;
introspect relies on that. Do not add a Ruby-side YAML loader to core.
2026-09-15 — Admin MCP ships in 6.0 over a core agent-tool registry; the assistant follows it
Plan: 6.0-mcp-server.md. Supersedes the "No MCP in 6.0" decision in
6.0-dashboard-assistant.md (2026-08-20) and executes the future-lanes table
in 5.5-admin-api-cli.md, whose CLI-first precondition is met now that
spree api has shipped.
Decision. The tool registry the assistant branch built
({name, description, params schema, permission key, mutating flag, executor}) moves into spree_core as Spree::AgentTool /
Spree.agent_tools, beside Spree.integrations and Spree.reporting, so an
extension registers a tool without depending on any adapter gem. A new
optional gem spree_mcp mounts the official mcp Ruby gem's Streamable HTTP
transport at /api/v3/admin/mcp, authenticates with secret keys and offers
only the tools the key's scopes permit. The assistant rebases onto the same
registry afterwards. No new spree_ai or spree_agents gem.
Catalog shape. Never one tool per endpoint. Generic reads and generic
writes over a resource map derived from the admin controllers, with writable
schemas read from the generated admin.yaml; reporting tools over
Spree.reporting; a short list of task tools only where a job crosses
records. Writes are scope-gated and confirmed by the MCP client; the
server-side approval gate stays an assistant feature.
Consequences for other work. New admin controllers must declare
model_class, serializer_class and scoped_resource, and expose their
workflow through create_workflow / update_workflow, or the generic tools
cannot see them. Tool results must stay compact because they land in the
model's context. No new tools under Spree::Assistant::Tools.
2026-09-16 — Workflows are the agent write tools; exposure is an allowlist in core
Plan: 6.0-mcp-server.md. Refines the 2026-09-15 entry above.
Reviewing the orders and products controllers showed that the Admin API has
no direct record writes left on its write paths: the base controller calls
the declared create_workflow / update_workflow, every member action calls
a registered workflow, and a workflow's perform keyword signature with its
YARD @param block is a machine-readable contract.
Decision. Each exposed workflow is one agent tool with a schema derived
from perform; no hand-written task tools. Exposure is
Spree.agent_tools.expose_workflows(<dependency key> => <permission>) in
spree_core, keyed by Spree::Dependencies key so a host app's replacement
workflow keeps the tool. Generic create_resource / update_resource /
delete_resource exist only for resources whose controller declares no
workflow and refuse the rest. Tier 1 services still called from controllers
are not adapted; they are promoted to workflows over time.
Consequences for other work. A new back-office write is a workflow plus
an allowlist entry in the same PR. perform parameters need typed YARD
docs; record parameters must be models the resource map knows; principal
parameters keep the established names so they are injected, never accepted
from a caller. A contract spec fails when an admin controller invokes a
workflow that is neither exposed nor explicitly excluded.
2026-09-16 — The API key is an actor; "who did this" associations become polymorphic
Plan: 6.0-action-actors.md, shipping before 6.0-mcp-server.md.
Every association that records who performed an action (canceler,
approver, created_by, refunder, received_by, …) pointed at the admin
user class only, so a write made with a secret API key — a warehouse
connector, an integration, soon any MCP client — recorded nobody.
Decision. Those associations are declared with acted_by, which makes
them polymorphic over Spree.actor_classes (the admin user class and
Spree::ApiKey; extensions register more). The Admin API passes
current_actor — the signed-in admin or the authenticating key — to
workflows in place of the user. 6.0 converts the order operations (orders,
refunds, returns, exchanges, claims, stock receipts: 8 columns on 6 tables);
the remaining 13 convert in 6.1. Serializers expose <name>_type beside
<name>_id. A transitional reader resolves un-backfilled rows through the
admin user class with a deprecation warning until 6.1. Rejected: user-bound
personal keys (platforms are retiring them; a connector is not a person) and
waiting for OAuth (leaves 6.0 key writes unattributed). OAuth, when it comes,
resolves a token to one of these two actor kinds.
Consequences for other work. New "who did this" associations use
acted_by, never belongs_to … class_name: Spree.admin_user_class;
ownership associations that gate visibility (Import#user, Export#user,
SavedReport#user) keep the plain form. Controllers pass current_actor,
not try_spree_current_user, for actor keywords. Workflow principal
parameters stay [Object, nil] and are assigned, not inspected.
Amended the same day, at implementation. Three points the design left
open. An expanded actor serializes as { id, type, label } through a new
ActorSerializer, not through the admin user serializer — the order
serializer already expanded approver/canceler/created_by as people and
the dashboard read full_name || email off them, which no key can answer.
ApiKeySerializer#created_by_email calls .email on the already-polymorphic
created_by, so it gains created_by_type and created_by_label and the
api-keys controller passes current_actor; the plan had said to leave that
file alone, which left a 500 waiting for the first key-creates-key call.
current_actor is defined on Api::V3::BaseController (answering the user)
and overridden in AdminAuthentication to prefer current_api_key, because
the post-sale concerns are shared with the JWT-only seller panel while a
publishable Store API key must never become an actor.
2026-09-16 — Update checks and usage telemetry are one daily heartbeat, on by default
Plan: 6.0-telemetry-and-update-check.md.
The 5.x update banner went with the spree_admin engine, and 6.0 had no
replacement and no usage reporting from servers or the CLI.
Decision. Spree::UpdateCheck in core asks spreecloud.io once a day
from a job, never inline in a request, and the same request is the usage
heartbeat: the four 5.x query keys (version, environment, url,
install_id) stay frozen, and stack fields plus order-of-magnitude size
buckets sit beside them. The dashboard reads GET /api/v3/admin/updates
(JWT admins with manage on the store only; secret keys get 404) and shows
a banner through an AppShell banner slot the seller panel leaves empty.
@spree/cli and create-spree-app send one event per command. Both
channels are on by default; SPREE_TELEMETRY_DISABLED=1 or DO_NOT_TRACK=1
reduces the heartbeat to version and silences the CLI,
SPREE_UPDATE_CHECK_DISABLED=1 stops the request entirely. Rejected: exact
counts (business data next to a store URL), folding the status into /me
(reaches admins who cannot manage the store), opt-in by default (no banner
for most installs, 5.x regression).
Consequences for other work. The running Spree version, gem list or
environment must not appear in any other Admin API response. A new outbound
call from core is cached, run from a job, short-timeout, failure-cached.
Env-backed booleans read through Spree::Config must be cast: the env:
option on preference returns the raw string. Cross-page notices go through
the AppShell banner slot, nowhere else.
2026-09-15 — Store setup is one step, shared by self-hosted and hosted signup
Plans: 6.0-store-context-and-first-run-setup.md, 6.0-cli-configurator.md.
Creating a store asks the same four questions wherever it happens — name, country, currency, language — and provisions the same things from the answers. Two flows ask them:
- Self-hosted: account setup, then store setup. No email confirmation.
- Hosted signup: account setup, then confirmation (instant with an OAuth provider), then store setup.
Only the middle step differs, so the store step is shared rather than reimplemented.
Frontend. The four fields live in StoreSetupFields, exported from
@spree/dashboard at ./components/spree/store-setup-fields. It is headless
about submission: the caller owns the form, the countries query and what
happens on submit, because those genuinely differ (a one-time setup token
versus an authenticated session). The country drives the currency and
language defaults, and both stay editable.
Backend. Spree::Stores::ProvisionDefaults is the one provisioning path,
already called by the first-run setup endpoint. Anything else that creates a
store calls it too, rather than hand-rolling a subset: it builds the default
market, the warehouse, the delivery zones, the package type and pickup, and a
store missing those cannot ship. The earlier hosted sandbox created only a
market, which is why its stores could not fulfil.
Consequences for other work. A new flow that creates a store mounts
StoreSetupFields and calls ProvisionDefaults; it does not write its own
country picker or its own provisioning. ProvisionDefaults previously
documented exactly two callers — that list grows as flows are added, but the
rule it protects stands: never wire it to a settings screen, since re-running
it against a configured store is a data reset.
2026-09-16 — The MCP server ships as one pull request, not a registry PR then an adapter PR
Plan: 6.0-mcp-server.md. Refines that plan's "Order of operations", which
proposed extracting the agent-tool registry into spree_core on its own
branch, merging it, and only then branching spree_mcp from main.
Decision. Migration Path steps 1 to 5 — the core registry, the reporting
tools, the workflow tools with their allowlist and generic record writes, the
spree_mcp gem, and the documentation — ship in one branch. A registry-only
pull request would ask reviewers to judge a contract with no caller, and the
follow-up would re-open every shape question with the first already merged.
The commits follow the plan's phase order so the history still reads as the
staged migration.
Consequences for other work. The feat/dash-assistant branch is read but
never written by this work: its files are copied across with git checkout so
blame follows the code, and deleting the originals and repointing the RubyLLM
adapter at Spree.agent_tools remains that branch's own step. Until it does,
the registry classes exist in both places, and the constraint against adding
tools under Spree::Assistant::Tools stands.
2026-09-29 — Webhook payloads stay on Store serializers; every event is declared
Plan: 6.0-typed-webhook-events.md.
About 110 webhook events were string literals spread across models,
workflows and controllers, the dashboard kept its own copy of the list, and
@spree/sdk/webhooks typed every payload as unknown.
Decision. Webhook payloads use the Store API serializers: the
customer-facing shape already shipped, with no back-office fields.
Integrations that need admin data fetch it from the Admin API by the IDs in
the payload, under a scoped secret key, which is how Stripe's thin events and
Medusa work and the same bound Saleor and Shopify reach by limiting payloads
to what the receiver may read. Every event is declared on the model whose
record is the payload (publishes_events / publishes_event), forming
Spree::Events.catalog. That catalog generates the event types and Zod
schemas in @spree/sdk/webhooks and serves the dashboard's picker. Hand-built
payload hashes become event serializers. Publishing an undeclared event
raises in development and test and warns in production. Rejected: Admin
payloads (they push internal notes, IP addresses and card-check results to
any endpoint), a central registry file (two places to edit per event),
scoping webhook endpoints (left out deliberately, its own plan if revisited).
Consequences for other work. A new event is declared with
publishes_event in the same change that publishes it, and its payload is a
record's Store serializer or a dedicated event serializer, never a hash.
Facts that are not part of the record go in metadata. Webhook payloads must
not switch to Admin serializers. WEBHOOK_EVENT_GROUPS in the dashboard is
frozen until it is replaced by the catalog endpoint.
Addendum (2026-09-30). Credential rules live in the catalog too.
customer.password_reset_requested is a credential event: it reaches only an
endpoint that names it, and naming it needs write_customers. The staff and
seller reset requests are declared webhook: false and never reach any
webhook endpoint, whatever it subscribes to — the rule 5.x kept in the
subscriber's NON_DELIVERABLE_EVENTS, now read from the catalog.
2026-10-05 — MCP consumer reach needs OAuth; nothing else is both interoperable and merchant-grade
The Admin MCP server shipped in 6.0 authenticates with a secret key in a
header, which reaches agents whose configuration a developer edits and no
further. Reviewing that against what merchants actually need closed every
alternative to OAuth 2.1, so 6.0-mcp-oauth plans it and it ships in the
same pull request.
A developer-only MCP server is worse than none. The spree api CLI
already serves agents with a shell, with full endpoint coverage and pipeable
output. An MCP server reaching only that audience is a second surface to
maintain that loses to the first, so consumer reach is the feature's
acceptance criterion rather than an enhancement to it.
A stdio bridge does not deliver it. Shipping a local proxy that injects
the header is the common pattern among self-hosted platforms (GitLab,
WooCommerce and BigCommerce all document one), and it does unblock desktop
clients. But it needs Node, a global install and a hand-edited
claude_desktop_config.json — a developer workflow. Anyone who can do it can
use the CLI. Packaging it as a desktop extension removes the JSON editing and
not the install, and reaches one vendor's client only.
Vendor header features do not deliver it either. Anthropic's
static_headers lets a merchant paste a key with no terminal, but it is in
beta behind per-organization gating, carries an open bug where the configured
header is ignored in favour of an OAuth flow, is an organization-wide
credential that cannot identify the calling user, and is Anthropic's alone.
Building the merchant path on it would mean Spree stores connect from Claude
and from nothing else.
OAuth is what the clients that matter actually require, and the spec is clear that authorization is optional — so the key-based server is already compliant and OAuth is about reach, not correctness. Hosted connectors (claude.ai, ChatGPT) fetch the URL from the vendor's own servers, so no local process can help them, and OAuth 2.1 is the single interoperable way in.
Consequences for other work. The key path stays permanently rather than
being retired by OAuth; it is how CI jobs, server-side integrations and
editors authenticate, and commercetools ships both for the same reason. A 401
on the MCP endpoint is now reserved for an authorization challenge, so
permission refusals must stay where they already are: { error: '…' }
inside a 200 JSON-RPC response, which is where MCP puts tool-level failures.
Promoting one to a 401 would send consumer clients into a re-authorization
loop. 6.0-platform-auth phase 7 makes
Spree an OIDC client and does not provide any of this; the two share a spec
family and almost no code.
2026-10-05 — A delegated grant narrows the user's authority; it never inherits it
The OAuth grant an admin approves for an agent carries scopes, and
Spree::AgentTools::Context now takes granted_scopes: so those scopes
intersect with what the user's own role allows. Without the intersection the
context read only the CanCanCan ability, so a merchant who consented to
reading products handed over all 64 tools, refunds included.
Two rules the intersection has to keep. It only ever narrows: a grant
naming every key in the catalog still gives a limited role nothing extra, so a
compromised client cannot widen its own reach. And it applies to record checks
too, not just to which tools are offered — being handed a read tool is not
permission to write through it, so can? consults the grant before the
ability.
Consequences for other work. Anything that builds a Context for a caller
acting on behalf of a person must pass granted_scopes:; omitting it means
the full ability, which is right for the dashboard assistant (the admin is
acting directly) and wrong for any delegated credential. The MCP endpoint is
the worked example.
2026-10-05 — OAuth lives in spree_api, its tables and models in spree_core
Making Spree an OAuth 2.1 authorization server is platform infrastructure, not
an MCP detail: 5.5-admin-api-key-scopes already recorded that a public app
marketplace would reuse the same scope vocabulary, and merchant-approved
integrations and storefront customer login are the same flow with a different
client. So the Doorkeeper configuration sits in spree_api, beside the
authentication it extends, and protected resources register themselves —
Spree::Api::Oauth.register_resource(:mcp) { |store| … } — rather than the
authorization server knowing about MCP.
The tables and the three models (Spree::OauthApplication,
OauthAccessGrant, OauthAccessToken, named as they were before 5.4) are in
spree_core for a blunter reason: a migration in spree_api/db/migrate is
only copied by spree_api:install:migrations, because the engine names
differ, while every upgrade guide tells people to run
spree:install:migrations. Left there the tables would silently never be
created on upgrade. Spree::ApiKey is already in core for the same reason.
Consequences for other work. doorkeeper is a spree_core dependency,
pinned to ~> 6.0.0.rc2 because that is the first release carrying RFC 8707
resource indicators; relax it to ~> 6.0 once 6.0.0 is final. A new engine
that needs its own migrations must either live in core or document its own
install task — do not assume spree:install:migrations covers it.
2026-10-06 — The products CSV carries each location's shelf count
Context: The products export filled inventory_count from
Variant#total_on_hand, which since stock reservations and allocation means
what a customer can still buy: the shelf, minus units promised to placed
orders, minus units held by checkouts, summed over every active location. The
import writes the same column back through Variant#set_stock, which sets the
shelf at a single location. Exporting and re-importing an unchanged file
therefore took every promised and held unit off the shelf, once per round trip
(V-3697), and moved stock from every other location onto the default one. Both
stock plans told readers to go through the availability figure and never the
shelf, and neither listed the export as a reader.
Decision: inventory_count is the shelf count at one location, and
inventory_backorderable that location's setting. A new stock_location
column names the location; blank means the owner's default, so existing files
keep their meaning. The export writes the default location on the full row and
a stock-only row for each further location holding stock — the shape the
price-only rows for extra currencies already have. Locations are named, not
referenced by id, as the purchase-order import's destination is. An
operator's file covers the marketplace's locations and, for a seller's
product, that seller's; on import the seller's own location wins when both
owners use the name, as with cartons. That misroutes only a seller's product
stocked in a marketplace location named like one of the seller's own — rare
enough that failing every shared name was the worse trade, since it would
fail ordinary rows. A seller's file and import cover only their own locations:
a seller never sets the marketplace's shelf. Rejected: keeping the
sellable figure and having the import add held units back (holds change
between export and import); one column per location (headers change when a
location is renamed); exporting the default location alone (stock elsewhere
disappears from the file).
Consequences: A reader whose figure is written back to the shelf
(set_stock, a stock adjustment, a file meant to be re-imported) reads the
stock level's own count_on_hand; every availability reader still reads
total_on_hand. Renaming a location between export and import fails that
location's rows rather than writing elsewhere. A seller's export leaves out
their products' stock held in marketplace locations.
Plans amended: 5.6-admin-spa-csv-import.md (stock is per location),
6.0-stock-reservations.md and 6.0-typed-stock-movements.md (the "read
availability, never the shelf" constraints name the write-back exception).
2026-10-05 — MCP takes a grant, the CLI takes a key
The MCP endpoint accepted a secret API key as well as an OAuth token, which made it the one surface with two ways in. The key path is now removed: a request without a grant is refused with the discovery challenge, whatever credential it carried.
The reasoning is what each credential can say. A grant names the person who approved the agent and the subset of their permissions they allowed, and both are re-read on every call — narrowing a role or deleting the user takes effect immediately. A key says neither: it is a standing credential with nobody behind it, and it outlives whoever created it. For an agent acting on someone's behalf that is the wrong shape, however convenient.
Keys keep their place on every other Admin API surface and in the spree api
CLI, which is what scripted callers that cannot open a browser should use.
Consequences for other work. A workflow run through MCP now records the
approving admin as the actor rather than an API key, so anything asserting a
key principal there is wrong. The store comes from the token's application,
so X-Spree-Store-Id is not consulted on this endpoint. Spree::AgentTools:: Context keeps its api_key: principal — the dashboard assistant and any
other adapter may still use it; only the MCP transport refuses one.
2026-10-16 — One OAuth audience for the Admin API, MCP included
The MCP endpoint had an audience of its own (/api/v3/admin/mcp) while the
Admin API demanded /api/v3/admin. A tool call reaches data by dispatching
into the Admin API carrying the caller's own token, so no single credential
could satisfy both checks: every dispatched read and write answered
"authentication required" while the endpoint itself looked healthy.
A workaround minted both audiences for an MCP grant, but only on the consent
preview — the action that writes the grant passed the client's raw resource
through, and the indicator is optional, so real grants carried none at all.
There is now one audience. granted_audience is gone, the MCP engine
registers no resource, and the endpoint checks the Admin API's audience like
every other admin surface. The scopes a merchant approves are the ceiling;
the path a token names was buying nothing.
The specs that missed this minted tokens in Ruby and dispatched with an admin JWT, so neither consent nor the OAuth dispatch path was ever exercised. The MCP suite now walks consent, token exchange and a tool call as a client does.
2026-10-16 — The store MCP surface reuses everything but the catalog
A second MCP endpoint for shoppers is planned for 6.1
(docs/plans/6.1-store-mcp-server.md). The tool contract, the registry, the
in-process dispatcher, the record summaries and the protocol adapter are all
surface-neutral and carry over unchanged — about 4,600 lines of tool layer
under 590 of adapter, and the adapter is the part that would otherwise need
rewriting.
Two things do not carry over. The resource map is derived by walking
Admin::ResourceController.descendants and reading each controller's
scoped_resource; Store controllers declare no scope, so the store map needs
its own basis. And a grant's owner is refused unless it is an admin user, in
two places, so a customer principal is a deliberate addition rather than a
relaxation.
The registry was split by surface during the 6.0 build for exactly this —
Spree.store_agent_tools exists and is empty, and a tool filed on the wrong
surface is refused at registration.
2026-10-19 — spree add installs extensions from a catalog shipped with the CLI
spree add paypal will eject (with consent), add the gem, run its install
generator if it has one, migrate, install any dashboard plugin and restart a
running server (docs/plans/6.0-cli-add-extensions.md). Names resolve only
through a JSON catalog bundled in @spree/cli, never by guessing a gem name,
because a guessed name turns a typo into installing a stranger's gem. The
catalog ships with the CLI rather than being fetched, so the command works
offline and a remote file cannot change what gets installed. Setup notes live
in each gem's post_install_message, not in the CLI.
2026-10-19 — Extensions released with Spree are pinned to the project's Spree version
spree add adds the gems that ship from this repository (spree_stripe,
spree_meilisearch, spree_easypost, spree_opentelemetry, spree_mcp) as
>= <locked spree version>. An unpinned bundle add spree_stripe resolves to
the 5.x line's 1.8.2, the newest stable release on RubyGems. A gem a project
already lists is reported as installed rather than ejecting the project to
re-add it.
2026-11-02 — Dashboard packages are tree-shakeable; registration at import time lives only in the bootstrap modules
The dashboard and seller panel ship as one JavaScript file because the four
dashboard packages declare no sideEffects, so a route that imports one
button through the @spree/dashboard-ui barrel keeps the editors and charts
reachable. docs/plans/6.1-dashboard-code-splitting.md declares sideEffects
on @spree/dashboard-ui, @spree/dashboard-core, @spree/dashboard and
@spree/seller-dashboard, listing only stylesheets and the shells' bootstrap
modules (admin i18n-setup, api-client-setup, nav/*, search/*; seller
i18n, nav/*), the tables/* modules list routes bare-import for their
defineTable call, and the register.ts(x) slot modules next to the editors
they register, and turns on TanStack Router's autoCodeSplitting in both Vite
plugins. From now on a module that registers something at import time (nav,
settings nav, search, slots, tables, translations) belongs in one of those
places; anywhere else the build drops it once the flag lands. TipTap,
CodeMirror and Recharts are imported only by their dashboard-ui component,
which loads them on demand.
2026-11-03 — Agent tools come from the Admin API document, and extensions ship theirs
Context: An extension's workflow reached agents only through expose_workflows under a Spree::Dependencies key, with its schema read from perform's YARD block and its endpoint found by scanning controller source for Spree.<key>. Building Enterprise quotes on it showed three silent failures: empty request bodies, workflows running in process when called another way, and parameter names bridged by guessing. spree/spree#15083 patched them and was closed: the 2026-10-10 MCP decision had already keyed the catalog on operations, and the patches deepened the dependency-key path instead.
Decision: Every non-CRUD write operation in the Admin API's OpenAPI document is an agent tool, opt-out with a stated reason; custom GET operations opt in. Name, description, path parameters and body schema come from the operation, and permission from the routed controller's write scope. Each extension generates openapi/admin.yaml from its own rswag specs and ships it in its gem; Spree merges every engine's document. CRUD stays with the generic tools, which take parent_id for nested resources. It ships in a 6.0 patch: expose_workflows is deprecated and has no effect (a workflow behind a documented endpoint is already that endpoint's tool), and is removed in 7.0. The 6.0.0 tools' renamed parameters and tool names stay accepted as aliases until 6.1. The agent layer stops reading Spree::Dependencies.
Consequences: A full-access key sees about a hundred tools. Extensions adding admin endpoints must write rswag specs for them. The 6.0.x release notes list the tools each write scope newly offers. Product activate, archive and draft get member endpoints. WorkflowTool, WorkflowSchema, the controller source scanner and the catalog allowlists are deleted.
Plan: 6.0-agent-tools-from-openapi.md. Plans amended: 6.0-mcp-server.md (allowlist keyed by dependency key superseded; "never one tool per endpoint" narrowed to CRUD and reads).