Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Design provider assets (wave 6) and license-code pools (wave 7)
Damian Legawiecc30664710bcc
diff --git a/CLAUDE.md b/CLAUDE.mdindex 7118a5f8e9..df21073235 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -27,7 +27,7 @@ Active plans (6.0 target, work pending):- `6.0-document-numbers.md` — Document number customization (**implemented 2026-08-13**): `Spree::Core::NumberGenerator` module factory → **`has_spree_number prefix: 'R'`** (macro from `Spree::HasNumber`, included into `Spree::Base` — no per-model include) + runtime `Spree.number_generators` registry (`Sequential` | `Random` strategies). **Sequential is the 6.0 default** (per-`(store, resource_type)` `spree_number_sequences` counter, `with_lock`, start 1001), random opt-in; merchant settings = one "Order numbers" card (prefix/suffix/format/start as Store preferences) — orders only. Fulfillment + Payment numbers become **derived methods** (`R1001-F1`/`R1001-P1`; stored value honored on legacy rows, columns frozen — never write them; gateway `order_id` = `payment.number`); every other numbered model keeps its stored number (Import/Export mail theirs, so they stayed numbered too), and `Spree::PurchaseOrder` must be born with `has_spree_number prefix: 'PO'`. Saving a numbered record with `validate: false` requires calling `generate_number` first. Never parse/regex a `number`; mostly-gapless, never legal invoice numbering.- `6.0-delivery-profiles.md` — **Implemented in PR #14404 (2026-08-09).** `Spree::DeliveryProfile` = ShippingCategory promoted via table rename (`spree_shipping_categories`→`spree_delivery_profiles`, `products.shipping_category_id`→`delivery_profile_id`): store-scoped STI (kinds `DeliveryProfiles::Shipping`/`::Digital` via `Spree.delivery_profile_types`), one default per store, products reference it directly and it's required (auto-assigned: type template else store default; ProductType stamps at creation only — template doctrine). Profile ↔ stock locations (origins, empty=all) + profile→zones + profile→methods; method binds ≤1 zone (m:n join dropped), optional ships-from narrowing per method (no location-group layer — considered, dropped). **Classes only, NO string vocabularies:** method `fulfillment_type` column dropped, `Spree.fulfillment_types` registry + ProductType array deleted; behavior = `FulfillmentProvider` class predicates (`digital?`/`pickup?`/`pickup_point?`/`requires_address?`), rate-provider `requires_address?`, profile kind `digital?`/`requires_shipping_address?` + composition validations. Carts split per profile (`Splitter::DeliveryProfile`); Coordinator allocates only from profile-covered locations. `spree:migrate_delivery_profiles` (5.6→6.0 manifest) does store assignment/kind detection/non-narrowing fold-in/method m:n collapse (`spree_shipping_method_categories` survives to 6.1 as source). ShippingCategory/ShippingMethodCategory classes + associations deleted. Supersedes the string-registry + "named groups 6.1" decisions.- `6.0-fulfillment-and-delivery.md` — Shipment→Fulfillment, ShippingMethod→DeliveryMethod, drop ShippingCategory, FulfillmentProvider strategy, pickup (merchant StockLocation) + pickup_point (third-party PickupPointProvider). **Shipped to 6-0-dev (Waves 2+4+6):** renames + deprecated twins, providers (Manual/Digital/Pickup/PickupPoint), dual-emit events, store pickup discovery endpoints, admin delivery_methods/delivery_zones CRUD + dashboard settings pages, FulfillmentMailer; Wave 7 shipping→delivery data migration remains. Pickup work beyond shipped code deferred to 6.1 (2026-08-06): contract hardening (`new(delivery_method)` ctor, `find_nearby` zipcode/query) + how-to guide; `PickupPointProvider::Base` stays **undocumented in 6.0** (v6 docs cover only the delivery rate provider interface) — never add pickup-provider docs in 6.0 work. Delivery mechanics live on provider classes (`pickup_point` provider ships but stays unregistered until 6.1; `local_delivery` cut = shipping + postal-code zone); the string fulfillment-type registry was deleted by `6.0-delivery-profiles.md`. **Partial fulfillment (2026-08-10, resolved question 12):** shipping a subset is `Spree::Fulfillments::Fulfill` (optional per-line-item `items:` + `tracking:` + `notify_customer:`; splits then fulfills in one transaction) — never a state-machine event, since split-then-ship in an `after_transition` is what service-workflows prohibits. **Side effects left the machine (2026-08-10, question 13):** `after_cancel`/`after_resume` are gone as transition callbacks — restock + carrier stand-down live in `Fulfillments::Cancel`/`::Resume` as inline steps (provider call is an `external_step`; `notify_provider: false` lets `Orders::Cancel` delegate and batch carrier I/O after its own transaction), `after_cancel`/`after_resume` are deprecated shells and the only trace left on the model — never add public model methods for workflows to call. **Status model (2026-08-11, question 14): the machine is REMOVED.** `status` = plain `HasStatus` `unfulfilled → fulfilled → delivered | canceled` (`pending`/`ready`/`ready_for_pickup` collapse — payment/stock gating is a `Fulfillments::Fulfill` validate guard, pickup renders modality-aware labels); `delivered` = confirmed receipt (`Fulfillments::MarkDelivered`, `delivered_at`, `fulfillment.delivered`) — the returns window + EU withdrawal anchor; carrier truth is the separate `tracking_status` axis (data, never a machine) written by `Fulfillments::UpdateTracking`, fed by EasyPost tracker webhooks (opt-in trackers for hand-entered numbers). Rollup domain `backorder | canceled | partial | unfulfilled | fulfilled | delivered`. **Phase 7 shipped 2026-08-11** (core + API + dashboard + EasyPost tracker webhook + `spree:migrate_fulfillment_statuses`); **label leads, fulfilled follows (2026-08-12):** `Fulfillments::PurchaseLabel` = explicit pre-ship label buy (loud failure, no email); `Fulfill` buys label BEFORE marking fulfilled (email always carries tracking; post-split failure keeps the split, never rolls it back); providers declare `generates_labels?` + idempotent `create_fulfillment`. **One tracking number per fulfillment (2026-08-11, question 15):** diverging parcels are split fulfillments; a `spree_fulfillment_trackings` model is 6.1 work and must absorb the entire carrier axis (per-row status/`delivered_at`, webhook matching by row) — never split the axis across fulfillment and tracking rows-- `6.0-digital-assets.md` — **COMPLETE (2026-08-10, all five waves).** `Spree::Digital` → `Spree::DigitalAsset` (table + FK renamed; `DigitalLink` keeps its name) with one-release bridges: constant alias, deprecated `digitals` twins, dual-emitted `digital.*` events, `PermittedAttributes.digital_attributes`, legacy `store/digitals/:token` route. Shipped on top: Admin API v3 (assets nested under products with private-storage direct upload, `digital_links` read + `reset`, order `resend_digital_links`; catalog — assets ride `products`, links ride `orders`), dashboard (product Digital files card, order links card, store Downloads settings), `Spree::DigitalAssetMailer#files_ready_email` on `order.placed` (+ resend), customer `GET /store/customers/me/digital_links` + store SDK resource, `digital_link.downloaded` event (no log table), signed-URL download transport clamped to the link's own expiry with `digital_asset_link_expire_time` capped at 1h, phantom `:digital` product param removed. Per-asset nullable `authorized_clicks`/`authorized_days` fall back to store settings — a recorded exception to the store-scoped-configuration no-fallback rule. **Constraints now:** new code uses `DigitalAsset`/`digital_assets` names only; nothing outside the model assumes an attachment is present (asset kinds + license-key pools groomed for 6.1); emailed download URLs keep resolving across renames one release; the generated OpenAPI specs still need the pre-release regeneration pass.+- `6.0-digital-assets.md` — **Waves 1–5 SHIPPED (2026-08-10, hardened 2026-08-12); waves 6 (provider-backed assets) + 7 (license-code pools) design finalized 2026-08-12, pending.** `Spree::Digital` → `Spree::DigitalAsset` (table + FK renamed; `DigitalLink` keeps its name) with one-release bridges: constant alias, deprecated `digitals` twins, dual-emitted `digital.*` events, `PermittedAttributes.digital_attributes`, legacy `store/digitals/:token` route. Shipped: Admin API v3 (assets nested under products with private-storage direct upload, `digital_links` read + `reset`, order `resend_digital_links`; catalog — assets ride `products`, links ride `orders`), dashboard (product Digital files card, order links card, store Downloads settings), `Spree::DigitalAssetMailer#files_ready_email` on `order.placed` (+ resend), customer `GET /store/customers/me/digital_links` + store SDK resource, `digital_link.downloaded` event (no log table), signed-URL download transport clamped to the link's own expiry with `digital_asset_link_expire_time` capped at 1h, phantom `:digital` product param removed. Per-asset nullable `authorized_clicks`/`authorized_days` fall back to store settings — a recorded exception to the store-scoped-configuration no-fallback rule. **Wave 6 (pending, targeted 6.0 for a licensing launch customer):** NO `kind` column — the provider IS the discriminator. A single nullable `provider_type` (class name); blank resolves to `Spree::DigitalAssetProvider::File` (the default, = today's signed-URL behaviour), a class name to that provider — exactly like `DeliveryMethod#provider_class`. Validation/metadata/create-form key off `provider_class` (which declares `requires_attachment?`), never a string. **No `Spree::Integration` binding** (deliberately unlike delivery-rate/tax providers, which connect marketplace services): a digital-asset provider is bespoke glue into one company's internal legacy software, host-app code that self-configures — no `integration_id`, no `requires_integration?`, no picker. `download_url` generalizes to `deliver` returning a `Spree::DigitalDelivery` value object (redirect URL **or** inline value like a license key). Registered via `Spree.digital_asset_providers`; core ships only the `File` provider. Link-per-unit with resolve-on-download; a provider failure returns 403 without spending the click. **Constraints now:** new code uses `DigitalAsset`/`digital_assets` names only; **nothing outside the model may assume an attachment is present — reach for `deliver`/`downloadable?`, never `attachment`** (a provider-backed asset has none); download-flow code treats the deliverable as opaque; **do NOT add an `Integration` FK/credential surface to `DigitalAsset`** (providers self-configure); emailed download URLs keep resolving across renames one release; the generated OpenAPI specs still need the pre-release regeneration pass. **Wave 7 (pending, targeted 6.0, OPEN SOURCE):** license-code pools — the "sell game keys" feature. `Spree::LicenseCode` (belongs to a `DigitalAsset`; a `value` string OR an attached scan/photo; nullable `digital_link_id` = redeemed state) + a `LicensePool` provider on the wave-6 seam (text → `inline_value`, image → `redirect_url`). CSV import via `Spree::Import` (text codes only; images upload individually). **Claim-once-pin-to-link:** first download claims a code and pins it, later views re-show the SAME code (click limit caps views, never burns a second code). **Pool count IS the variant's stock** — `count_on_hand` synced to `codes.available.count` so it sells out via the existing `can_supply?` path (a real `Stock::Quantifier` integration — a digital variant returns INFINITY today, a pool variant must return its finite count). **Constraint:** keep `count_on_hand` and unredeemed-code count in sync **transactionally** on import + redeem — drift blocks stock or oversells; never compute lazily in checkout.- `6.0-returns-exchanges-claims.md` — First-class Return, Exchange, Claim models replacing ReturnAuthorization/Reimbursement chain. **COMPLETE (2026-08-05):** all three entities (+ permanent `ReturnLineItem`/`ExchangeLineItem`/`ClaimLineItem` line items), `Spree::HasStatus`, all fifteen workflows (each with a leading `validate` hook), `Refund#originator`, admin + store v3 APIs (transitions as PATCH member actions; no destroy — cancel instead), dashboard pages. Legacy chain **removed**: ReturnAuthorization/CustomerReturn/Reimbursement/ReimbursementType/legacy ReturnItem + eligibility validators + ReturnsCalculator classes all deleted, but their **tables deliberately survive to 6.1** as the data migration's source and rollback path. `spree:upgrade:migrate_returns` (`Spree::ReturnsMigrator`, defined in the rake file like its sibling upgrade tasks; anonymous-AR readers) is in the 5.6→6.0 manifest after the adjustments step; it needs no cursor because the preserved `number` is uniquely indexed on the new tables, so "what's left" is a `where.not(number: ...)` query and an interrupted run resumes for free. `ReturnAuthorizationReason`→`ReturnReason` (alias one release) + new `ClaimReason`; `Metafields` on all three. Capability replacements: `Spree::ReturnMailer#refunded_email` on `return.refunded` (replaces the reimbursement email), `Order#outstanding_balance` drops the reimbursement term (refunds already net out of `payment_total`), `Return#refunded_total` counts store credits too, store credit issued with `originator` + `memo` only (categories dropped 2026-08-18). **Reasons** ship admin-only CRUD (`/api/v3/admin/{return,claim,refund}_reasons`, `settings` scope) + a combined Settings → Reasons dashboard page + reason pickers on the create dialogs; `mutable` is never client-writable and the immutability guard lives on `Spree::NamedType` (`can_be_deleted?` + rename/destroy guards) because secret API keys authorize by scope and never consult CanCanCan. **No state machines (2026-08-02):** plain `status` string + inclusion validation; all fifteen transitions are workflows (`Returns::Receive`, `Exchanges::Fulfill`, `Claims::Resolve`, …) with `validate` hooks for return-eligibility policy and refunds as `external_step`. Nothing happens in a model or transition callback. Statuses live in a `class_attribute` via the core `Spree::HasStatus` concern (`has_status` + additive `add_status(value, after:)`, generating predicates and scopes) — extensible by design, additive only, and no transition graph (that would be a state machine again). **Return eligibility is a hook, not a policy engine (2026-08-03):** no window/restocking-fee/final-sale flag in core — a `validate` handler decides, enforcing for customers while letting staff override (it reads `created_by`), and region-varying policy reads `order.market`. Medusa/Saleor/Vendure ship no policy at all; Shopify's engine has no API. A `ReturnPolicy` model can arrive later behind the same hook.- `6.0-platform-auth.md` — Drop Devise, own auth stack, User→Customer/Staff rename (RefreshToken shipped in 5.4)- `6.0-store-context-and-first-run-setup.md` — Store context becomes credential-derived (design finalized 2026-08-13): publishable key selects the store on the Store API, Admin API honors `X-Spree-Store-Id` with membership checked against the *requested* store (header-less JWT → default store + deprecation, required 6.1), hostname-based store resolution retired (`FindDefault`'s `url:` is dead; never read `request.host` to pick a store). First-run setup replaces the `[email protected]`/`spree123` dummy seed: seed creates an admin only when `ADMIN_EMAIL`/`ADMIN_PASSWORD` are explicitly set; otherwise a one-time setup-token flow (dashboard `/setup` + unauthenticated `auth/setup` endpoints; `has_secure_token :setup_token` on Store — plaintext like invitation tokens, printed by installer, `spree:setup:token` reprints, cleared on completion — required in EVERY environment; `Spree::Stores::DashboardUrl` is the single resolver for the dashboard origin — used by the setup link, invitation emails and the SSO callback — resolving `dashboard_url` pref/`SPREE_DASHBOARD_URL` → deprecated `admin_url` → this app's own `/dashboard` mount when `spree_dashboard` serves a build → dev Vite → store URL; never a hardcoded port, and the CLI rebuilds the link host-side since the seed runs before any dashboard is up). **App configuration reads ENV:** `RuntimeConfiguration.preference` accepts `env:` (precedence: explicit value → env var → coded default), so deployment settings are configurable without touching Ruby; `dashboard_url` is env-backed via `SPREE_DASHBOARD_URL` and `admin_url` is deprecated in its favour. Applies to `Spree::Config` only — per-store behavior belongs in Store preferences. The setup flow creates the first admin and adopts/renames the seeded store; no general store CRUD in the OSS Admin API. **Constraints now:** never assume `current_store == Store.default` in Admin API code; store-touching cache keys include the store id by construction (enforced by the cache-key audit spec in core — global data needs a reviewed allowlist entry); new scripts pass `ADMIN_EMAIL`/`ADMIN_PASSWORD` explicitly. **Isolation tripwires (2026-08-13):** `Spree::StoreScopeGuard` wraps every v3 API request in dev/test and flags store-less secondary-key lookups and unscoped scans on store-owned tables (schema-derived set; id/FK filters and `SELECT 1 AS one` are exempt as loads-from-scoped-rows and uniqueness validations — exemption is NOT proof of scoping, request-derived ids still need `current_store` fetching; `log` default, `raise` in this repo's API suite, `SPREE_STORE_SCOPE_GUARD` to change) — wrap deliberately global lookups in `Spree::StoreScopeGuard.skip { }`. A store-owned model with an unscoped `acts_as_list` also fails the core suite (positions bleed across stores). **Country-aware setup (2026-08-15, shipped):** setup asks for `country_code` (required) plus `locale` (country's official languages, filtered to those Spree translates, + English) and `currency` — both optional to the endpoint and defaulted from the country, both editable in the form; an unresolvable currency is a pre-token-spend 422, never silently ignored. Country data from unauthenticated `GET auth/setup/countries`. `Spree::Stores::ProvisionDefaults.call(store:, country:, locale:, currency:)` owns every country-derived per-store default (bootstrap market updated in place, warehouse country, Domestic/International zones + flat rates, pickup method — all in the derived currency) and absorbs the `StockLocations`/`DeliveryZones`/`PickupDelivery` seeds; exactly two callers — the setup endpoint and `Seeds::AdminUser`'s env branch (`STORE_COUNTRY`/`STORE_LOCALE`/`STORE_CURRENCY`, defaults `US`/`en`). It also restates seeded zero-amount rates (digital delivery) into the store currency. Sample data builds around the default market, never resets it. **Constraints:** a store's country changes through its **market**, never `Store#default_country_code=` (on a store with a market that writer is a dead column — readers delegate to the market, the after_update sync copies locale/currency only); country- or currency-dependent seeds go into `ProvisionDefaults`, not `Seeds::All`; never give the service a third caller.diff --git a/docs/plans/6.0-digital-assets.md b/docs/plans/6.0-digital-assets.mdindex cc7366205c..653d10d897 100644--- a/docs/plans/6.0-digital-assets.md+++ b/docs/plans/6.0-digital-assets.md@@ -1,6 +1,6 @@# Digital Assets: Rename, Admin Management, Delivery-**Status:** Complete — all five waves shipped 2026-08-10; hardened and rebased onto main 2026-08-12+**Status:** Waves 1–5 complete (shipped 2026-08-10, hardened + rebased 2026-08-12); waves 6 (provider-backed assets) and 7 (license-code pools) design finalized 2026-08-12, pending implementation**Target:** Spree 6.0**Depends on:** `6.0-fulfillment-and-delivery.md` (Digital fulfillment provider, shipped), `6.0-admin-api.md` (endpoint conventions), `6.0-admin-spa.md` (dashboard architecture), `6.0-admin-rbac.md` (permission catalog), `6.0-store-scoped-configuration.md` (preference conventions)**Author:** Damian Legawiec@@ -26,6 +26,27 @@ Spree ships a complete digital products engine in core: `Spree::Digital` (a file- **Replacing an asset's file must never break past purchases.** Tokens resolve through the link to the current attachment, so replacement transparently updates for every past buyer — this existing behavior becomes a tested guarantee.- **Phantom `:digital` param removed** from the admin products controller `permitted_params` — `spree_products` has no such column; `digital?` is derived from the product type.+### Wave 6 — provider-backed assets (design finalized 2026-08-12)++- **Ships in 6.0, not 6.1** (2026-08-12). 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. So provider-backed assets move out of the deferred list into a sixth wave of this plan. The 6.0 model was built for exactly this: the download flow already routes through `DigitalAsset#downloadable?` / `#download_url` and the store controller already redirects `allow_other_host: true`, so the change is a `provider_type` column plus a small strategy, not a rewrite.+- **No `kind` column — the provider IS the discriminator** (2026-08-12, revised from the initial `kind`-column sketch). Every asset always has a provider; an uploaded file is just the default one. A nullable `provider_type` string column: blank means `Spree::DigitalAssetProvider::File` (signs a storage URL, today's behaviour), a class name means that provider. This is exactly how `DeliveryMethod#provider_class` resolves (`fulfillment_provider.presence || DEFAULT`), so it is an established pattern, not a new one. A separate `kind` string would be redundant state — `provider_type` already answers every question `kind` would, and the download flow calls `provider.deliver(link)` with no branch at all. **Consequence:** the three things that genuinely differ by type — record validation, the file-metadata columns, and the admin create form — key off `provider_class`, not a `kind` string. The provider class declares whether it needs an attachment (`File#requires_attachment? == true`) so validation and the form ask the class rather than switch on a string.+- **One column: `provider_type`** (2026-08-12). Just a nullable class-name string. No `integration_id`.+- **No `Spree::Integration` binding** (2026-08-12, revised). The delivery-rate/tax providers resolve credentials through a store `Integration` because they connect to *marketplace* services (EasyPost, Avalara) a merchant self-connects. A digital-asset provider here is not that: it is bespoke glue into one company's internal/legacy software, written once in the host app. So the provider owns its own configuration however that app needs it — an env var, a hardcoded endpoint, a Rails credential — and Spree imposes no integration abstraction. The asset names the provider; the provider knows how to reach the legacy system. This drops the integration picker, the `requires_integration?` predicate, and the `integration` FK entirely.+- **Provider strategy mirrors the delivery-rate/tax *shape*, not their credential model** (2026-08-12): `Spree::DigitalAssetProvider::Base`, stored as the `provider_type` class-name string on the asset, registered via `Spree.digital_asset_providers`. Core ships the `File` provider (the default) as the one concrete implementation; a licensing provider is host-app code that self-configures.+- **Deliverable is a URL *or* an inline value** (2026-08-12). `deliver` returns a `Spree::DigitalDelivery` value object (`ActiveModel::Model`, per the no-Struct rule) carrying either a `redirect_url` or an `inline_value` + `content_type`. Licensing systems commonly vend a key to display, not a link to follow — forcing everything into a redirect (a `data:` URI or a Spree-hosted page) would be awkward. Accepted cost: the store download endpoint gains a second response shape (302 vs a 200 body), and a storefront consuming the token URL must handle a non-redirect response. Documented in the store API.+- **Seam + docs, only the `File` provider in core** (2026-08-12). Ship the base class, the `File` default provider (which is just today's download behaviour expressed as a provider), the registry, and a provider-authoring guide — matching how delivery-rate and tax providers began before their reference gems. A *third-party-resolving* provider is specific to the licensing system and lives in the host app. Accepted cost: nothing runnable out of the box for the licensing case; that provider's author writes Ruby against the documented `deliver` contract.+- **Link-per-unit, resolve on download** (2026-08-12). Order completion still creates one `DigitalLink` per unit (the `FulfillmentProvider::Digital` code is unchanged); the provider is called only when the customer actually downloads. No `on_fulfillment` provider hook — that would add a second entry point whose failure lands *after* money is taken (a support incident, not a clean error). A provider that needs to pre-reserve a key does so on first authorized download. Accepted cost: for consumable keys, a link exists before a key is reserved; reservation happens at first download, which suits typical licensing flows.+- **A provider failure must refuse, not 500, and must not spend the click.** The 6.0 controller already settles every refusal before `authorize!` increments the counter; wave 6 extends that so a provider exception is caught and returns the same 403 as an expired link, leaving the customer's allowance intact.++### Wave 7 — license-code pools (design finalized 2026-08-12)++- **A license pool is its own wave, and open source** (2026-08-12). Selling a finite batch of codes (game keys, gift cards) is the common merchant case that needs *no* external system — the opposite of wave 6. It is built as a `LicensePool` provider on the wave-6 seam, so it reuses `deliver` / `DigitalDelivery` whole, but it is a real stateful feature: a `Spree::LicenseCode` table, reservation logic, CSV import, and admin. Ships in core, unlike the wave-6 licensing provider.+- **Redeemed state is a nullable FK, not a flag** (2026-08-12). `LicenseCode#digital_link_id` null means available, set means redeemed by that purchase. "Remaining" is one query; "who redeemed it" is the link's order. No separate boolean.+- **Text or image, reusing the wave-6 shapes** (2026-08-12). A code carries either a `value` (rendered as an `inline_value` text body) or an attached scan/photo (served as a signed `redirect_url`). Both shapes already exist from wave 6 — code selling was, unplanned, the second consumer that validated the two-shape deliverable.+- **Claim once, pin to the link, re-show the same code** (2026-08-12). The first authorized download claims a code and pins it to the `DigitalLink`; every later view returns that same code. The click limit caps *views*, never burns a second code. This forks the download flow from the file case (which re-signs each time), and the fork is the behaviour most worth testing.+- **CSV import via `Spree::Import`, text codes only** (2026-08-12). A `LicenseCodesRowProcessor` turns each row into a code — bulk-paste keys. Images can't ride a CSV row; scans upload individually. This matches merchant behaviour and avoids inventing a binary-CSV path.+- **Pool count IS the variant's stock** (2026-08-12, the sharpest decision). A pool-backed 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. **Accepted cost:** import and redemption must keep the count in sync transactionally; drift blocks sellable stock or permits an oversell, so the sync is the one delicate piece and gets dedicated tests. This is a real integration with `Stock::Quantifier`, not a flag — today a digital variant returns `INFINITY` on-hand; a pool variant must return its finite code count instead.+## Design Details### Model rename@@ -65,8 +86,102 @@ All lookups scoped through `current_store` (assets via the product association cThe store download action (`GET /api/v3/store/digital_links/:token`) calls `authorize!` and redirects (302, `allow_other_host: true`) to a signed storage URL with `expires_in: store.preferred_digital_asset_link_expire_time.seconds` and attachment disposition. On success it publishes `digital_link.downloaded` (payload: prefixed link id, asset id, order id, access counter) — the first domain event in this area, making downloads webhook-visible. Failure keeps the existing 403 with code `digital_link_expired`.+### Wave 6 — provider-backed assets++**No `kind` — every asset has a provider.** `spree_digital_assets` gains a single nullable `provider_type` (string, class name). `DigitalAsset#provider_class` resolves `(provider_type.presence || DEFAULT).safe_constantize`, where `DEFAULT` is `Spree::DigitalAssetProvider::File` — identical to `DeliveryMethod#provider_class`. Existing rows have a blank `provider_type` and so are `File` assets, unchanged. There is no discriminator column and no `if kind ==` anywhere.++**Validation asks the provider class, not a string.** The provider class declares whether it needs an uploaded file — `File.requires_attachment? == true`, a licensing provider's `== false`. `DigitalAsset` validates conditionally: `validates :attachment, attached: true, if: -> { provider_class.requires_attachment? }`. The click/day limits apply to every asset regardless. This keeps the "what does this type need" knowledge on the type, so a new provider brings its own answer. A provider needing configuration (an endpoint, a credential) reads it from wherever the host app put it — not from a Spree column.++**The delivery seam.** `DigitalAsset#downloadable?` and `#download_url` generalize into a single `deliver(digital_link, expires_in:)` that delegates straight to the provider — no branch:++```ruby+def deliver(digital_link, expires_in:)+ provider_class.new(self).deliver(digital_link, expires_in: expires_in)+end+```++It returns a `Spree::DigitalDelivery` value object:++```ruby+class Spree::DigitalDelivery+ include ActiveModel::Model+ include ActiveModel::Attributes+ attribute :redirect_url, :string # 302 here …+ attribute :inline_value, :string # … or render this body+ attribute :content_type, :string++ def redirect? = redirect_url.present?+end+```++**The provider strategy.** `File` is the default and the one concrete provider in core:++```ruby+module Spree+ module DigitalAssetProvider+ class Base+ def self.requires_attachment? = false++ def initialize(digital_asset) = @digital_asset = digital_asset++ # @return [Spree::DigitalDelivery]+ def deliver(digital_link, expires_in:) = raise NotImplementedError+ end++ class File < Base+ def self.requires_attachment? = true++ def deliver(_digital_link, expires_in:)+ return unless @digital_asset.attachment.attached?++ Spree::DigitalDelivery.new(+ redirect_url: @digital_asset.attachment.url(expires_in: expires_in, disposition: :attachment)+ )+ end+ end+ end+end+```++Registered via `Spree.digital_asset_providers` (mirrors `Spree.delivery_rate_providers`); `File` registers itself. A licensing provider (`SpreeCCLI::LicenseProvider`) is host-app code — it self-configures (endpoint, credentials — its own concern) and returns whichever shape fits: a freshly-minted signed link, or an `inline_value` license key.++**The download flow.** `DigitalLinksController#show` calls `@resource.digital_asset.deliver(@resource, expires_in: window)` inside the same "settle before incrementing" guard. A redirect delivery → 302 as today; an inline delivery → a 200 body with its content type. A provider raising is rescued to the existing 403 — the click is not spent. `digital_link.downloaded` fires on success regardless of shape. Because `File` is the default, the file path runs the exact same code today's controller does, now expressed through the provider.++**Admin + API.** The admin `DigitalAsset` serializer and params gain `provider_type` only (no `kind`, no `integration_id`). The `filename`/`content_type`/`byte_size` attributes already null-out when no attachment is attached, so a provider asset serializes them as null with no serializer change. The dashboard files card's **Add file** flow gains a source choice: **Upload a file** (the `File` provider, shows the file input) or a provider from the registry (shows just a provider selector — no integration picker, since a provider self-configures). The selector is fed by a `digital_asset_providers` discovery endpoint (same shape as the delivery-provider types endpoint), which returns only the registered providers; a host with no licensing provider registered sees just "Upload a file," so the UI degrades to today's behaviour with nothing extra to explain. The store serializer is unchanged — the customer still sees only `download_url`, never the provider.++### Wave 7 — license-code pools++A merchant sells game keys, gift-card codes, activation strings — a finite batch Spree owns and hands out one at a time. Unlike wave 6 (which asks an external system), the pool is fully internal and stateful: it is the open-source "sell codes" feature. It is built as a provider on the wave-6 seam, so it reuses the `deliver` / `DigitalDelivery` mechanism whole — including the text-or-image split, which is exactly what code selling needs (a key string, or a scan/photo of a card).++**The `Spree::LicenseCode` model.** A new `spree_license_codes` table:++```+belongs_to :digital_asset+value :string # the code text — OR —+has_one_attached :attachment # a scan/photo of a card+belongs_to :digital_link, optional: true # null = available; set = redeemed+```++The nullable `digital_link_id` IS the redeemed state — no separate flag. "Codes remaining" is `codes.where(digital_link_id: nil).count`; "who got this code" is the link's order. A code carries either a `value` or an `attachment`, never both.++**The `LicensePool` provider** (`DigitalAssetProvider::LicensePool`, ships in core). `requires_attachment? == false` (the codes carry the payload, not the asset). On `deliver(link)`:++1. If the link already has a claimed code (re-download), return that same code — **claim once, pin to link, re-show** (settled 2026-08-12). A code is consumed per purchased unit exactly once; the click limit still caps *views* but never burns a second code.+2. Otherwise claim the next available code under a row lock (`codes.available.lock.first`), set its `digital_link_id`, and return it.+3. Return shape: a text code → `DigitalDelivery.new(inline_value: code.value, content_type: 'text/plain')`; an image code → `DigitalDelivery.new(redirect_url: signed_attachment_url)`. Both shapes already exist from wave 6.++The claim runs in the same "settle before incrementing" guard as every other download, so a pool that has run dry refuses cleanly (403) without spending the click — and never hands out a half-claimed code.++**CSV import — reuse `Spree::Import`.** A `LicenseCodesRowProcessor` (the `row_processors/` directory already has a base + siblings) turns each CSV line into a `LicenseCode` on the target asset — paste a thousand keys, one per row. Images are **not** bulk-CSV-importable (a row can't carry a binary); scans upload individually on the asset, which matches how merchants work (bulk keys, occasional scans).++**Stock coupling — pool count IS the variant's stock** (settled 2026-08-12; the sharpest edge). Today a digital variant's `Stock::Quantifier#total_on_hand` returns `INFINITY` (infinite copies). A pool-backed variant needs the opposite — finite supply equal to its unredeemed-code count — so it sells out naturally and cannot oversell (the "paid but got no code" failure). This is a **real integration with the stock system, not a flag**: the pool keeps the variant tracking inventory with `count_on_hand` synced to `codes.available.count` — incremented on import, decremented on redemption — so the existing `can_supply?` / `in_stock` / add-to-cart path enforces it with no new checkout code. Accepted cost: import and redemption must keep the count in sync transactionally; a drift between codes-available and `count_on_hand` would either block sellable stock or permit an oversell. This sync is the one genuinely delicate piece of wave 7 and gets its own tests.++**Admin.** The files card's source choice gains **License codes**; a pool asset shows a codes-remaining count, an **Import codes (CSV)** action, and a per-code list (value or image thumbnail, redeemed/available, which order redeemed it). The store serializer is still unchanged — a customer sees only `download_url`.+## Migration Path+Step numbers continue the shipped sequence; the design **waves** map to steps as: wave 6 (provider) = step 7, wave 7 (pools) = step 8.+1. **Rename wave (core)** — **shipped 2026-08-10**: migration (table + FK rename, override columns), model/file/serializer rename, constant alias + deprecated twin associations, dual-emit events, dependencies key bridge, effective-limit readers. Also landed opportunistically because they touched the same files: the canonical `digital_links/:token` route with the legacy path bridged, signed-URL download transport (resurrecting `digital_asset_link_expire_time` as the TTL), the `digital_link.downloaded` event, removal of the phantom `:digital` product param, and the use-case doc correction. Core (7406 examples) and API (2714 examples) suites green; types, Zod schemas and OpenAPI regenerated.2. **Admin API wave** — **shipped 2026-08-10**: catalog entries (`DigitalAsset` → `:products`, link reset → `:orders`), controllers + routes + serializers, remove the phantom `:digital` product param, integration specs, typelizer + OpenAPI regeneration.3. **Dashboard wave** — **shipped 2026-08-10**: admin-sdk resources, product-page Digital files card (upload to private storage, per-file limit overrides, delete), order-page links card (status, reset, resend), store settings Downloads section, translations in all six locales. The product card was reworked on 2026-08-12 — see step 6. No e2e spec yet — the card is covered by API-level specs; add browser coverage when the digital-product flow gets an e2e pass.@@ -75,23 +190,30 @@ The store download action (`GET /api/v3/store/digital_links/:token`) calls `auth6. **Post-wave hardening** — **shipped 2026-08-12**: three defects found by review after the waves landed. A cross-tenant write (the client's `variant_id` went into mass assignment, so a file could be attached to any product in any store and would then be issued and emailed to that store's customers) is closed by resolving the id through the parent product. The admin listing returned a 500 on PostgreSQL — assets reach a product through its variants, so the association carried the variants' `ORDER BY`, which is invalid alongside the listing's `DISTINCT`; it now orders by its own table. The card itself was rebuilt to read as a listing: values not inputs, editing in a sheet behind the row menu, an admin-only download link and a type icon per file.+7. **Provider-backed assets** — **pending, targeted for 6.0**: migration adding `provider_type` only (no `kind`, no `integration_id`); `provider_class` resolution + provider-declared validation; the `deliver` seam + `Spree::DigitalDelivery` value object; `DigitalAssetProvider::Base` + the `File` default provider + `Spree.digital_asset_providers` registry; the download controller's two-shape response; admin serializer/params/validations + a `digital_asset_providers` discovery endpoint; the dashboard source selector on the files card; the provider-authoring developer guide. Only the `File` provider ships in core; the licensing customer's provider lives in their own app and self-configures. Order (each step green before the next): provider base + `File` + registry → migration + model resolution/validation → delivery seam + controller → API → dashboard → docs. (Provider base first so `File` exists as the default the migration's model code resolves to.)++8. **License-code pools** — **pending, targeted for 6.0, open source**: `spree_license_codes` migration (value / attachment / nullable `digital_link_id`); the `LicensePool` provider (claim-once-pin-to-link, text or image); the `LicenseCodesRowProcessor` on the existing `Spree::Import` pipeline; the stock sync (`count_on_hand` ← `codes.available.count`, transactional on import + redeem) wired through `Stock::Quantifier`; admin (codes-remaining, import action, per-code list); docs. Builds on wave 6's provider seam, so it lands after it, in order: `LicenseCode` model + migration → `LicensePool` provider + the pin-then-reshow flow → stock sync → CSV import → admin → docs. The stock sync lands with its own test battery — it is the piece most able to drift.+## Constraints on Current Work- New code (including the admin API and dashboard work on this branch) uses `Spree::DigitalAsset` and `digital_assets` association names only; the legacy names are for the bridge layer.- Any new admin controller touching these models must land with its permission catalog entry (RBAC plan constraint applies).- The per-asset fallback is the only sanctioned fallback: never add a chain through global `Spree::Config`, and new digital behavior settings are born on Store (or the asset), never global.- Do not build a per-download log table, PDF stamping, or streaming features ad hoc — the `digital_link.downloaded` event is the extension point until a real need arrives.-- Do not preclude future asset kinds: nothing outside the model should assume an attachment is always present (deferred external/provider-backed assets and license-key pools, see Open Questions).+- Wave 7: keep a pool variant's `count_on_hand` and its unredeemed-code count in sync **transactionally** — import and redeem both write both, in one transaction. A drift silently blocks sellable stock or permits an oversell. Never compute one from the other lazily at read time in the checkout path.+- Do not assume `DigitalAsset#attachment` is present anywhere outside the model — a provider-backed asset has none. Reach for `deliver` / `downloadable?`, never `attachment` directly. (The 6.0 model already followed this; wave 6 is why it mattered.)+- Wave 6 download-flow code treats the deliverable as opaque (a `DigitalDelivery` — URL or inline value), never as a storage URL. A digital-asset provider owns its own configuration (it is host-app glue into internal software) — do NOT add an `Integration` FK or credential surface to `DigitalAsset`. This deliberately differs from delivery-rate/tax providers, which connect to marketplace services; see the wave 6 decision.- Emailed download URLs are long-lived customer-facing artifacts: any route change must keep old URLs working for at least one release.## Open Questions-All five waves have shipped. Only deferred items remain.+Waves 1–5 shipped; wave 6 (provider-backed assets) is designed and pending implementation. Genuinely deferred:-1. **Asset kinds** (`external_url`, provider-backed for third-party repositories/licensing) and **license key pools** (pre-generated keys per variant, one consumed per purchase) — groom for 6.1. Unblocked now that the waves have landed; still wants a concrete integration target to design the provider contract against.-2. **Per-download log rows** (IP, user agent, per-download timestamps) — revisit if merchants ask for more than the counter + event; the event payload is designed so a subscriber can build this externally today.+1. **An `external_url` provider** (a merchant pastes a public URL) — not built now, and needs no schema when it is: it is just another `DigitalAssetProvider` subclass (`requires_attachment? == false`) reading a URL off the asset's metadata. Register it and it appears in the source selector. Add when a merchant asks.+2. **License-code pools** — no longer deferred; designed as wave 7 (see the "Wave 7 — license-code pools" Key Decisions and Design blocks, and Migration Path step 8). A first-class `Spree::LicenseCode` pool: CSV-import a batch, one consumed per purchase, text or image, stock-coupled so it sells out. Ships open source in 6.0.+3. **Per-download log rows** (IP, user agent, per-download timestamps) — revisit if merchants ask for more than the counter + event; the event payload is designed so a subscriber can build this externally today.## References-- Plans: `6.0-admin-api.md` (the four unchecked digital-asset endpoints this plan implements), `6.0-product-types.md` (variant-level fulfillment-type gap, 6.1 relief valve), `6.0-multi-vendor-marketplace.md` (vendor-owned digital catalogs intersect at 6.1), `6.0-store-scoped-configuration.md` (preference rule this plan records an exception to), `docs/plans/decisions.md` 2026-08-10.+- Plans: `6.0-admin-api.md` (the four unchecked digital-asset endpoints this plan implements), `6.0-product-types.md` (variant-level fulfillment-type gap, 6.1 relief valve), `6.0-multi-vendor-marketplace.md` (vendor-owned digital catalogs intersect at 6.1), `6.0-store-scoped-configuration.md` (preference rule this plan records an exception to), `6.0-delivery-rate-provider.md` / `6.0-tax-provider.md` (the provider-strategy *shape* wave 6 mirrors — but NOT their `Spree::Integration` credential model, which wave 6 deliberately drops), `docs/plans/decisions.md` 2026-08-10 and 2026-08-12.- Code: `spree/core/app/models/spree/digital_asset.rb`, `digital_link.rb`, `spree/core/app/models/concerns/spree/purchase/digital_items.rb`, `spree/core/app/models/spree/fulfillment_provider/digital.rb`, `spree/core/app/workflows/spree/orders/complete.rb`, `spree/api/app/controllers/spree/api/v3/store/digital_links_controller.rb`, `spree/core/lib/spree/core/permission_configuration.rb`.diff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex ac70c4d31a..b764451721 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -706,6 +706,90 @@ context is the only place that changes.context, not stored jurisdiction, and addresses and markets still speak incountries. 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