Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Let a digital asset provider declare per-asset settings

Damian Legawiec5da1cab92450
diff --git a/CLAUDE.md b/CLAUDE.md
index 9aabe09394..b5ca3bcfd0 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` — **Waves 1–6 SHIPPED (waves 1–5 2026-08-10, hardened 2026-08-12; wave 6 provider-backed assets 2026-08-12); wave 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 (shipped 2026-08-12):** 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-digital-assets.md` — **Waves 1–6 SHIPPED (waves 1–5 2026-08-10, hardened 2026-08-12; wave 6 provider-backed assets 2026-08-12); wave 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 (shipped 2026-08-12):** 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. **Per-asset provider settings (shipped 2026-08-12):** shared config (endpoint/credential) stays the provider's own concern; *per-asset* config (which pool, which external SKU) is declared with a class-level `setting :key, :type` DSL (`Base.settings_schema` = the `PreferenceSchema` wire shape, but NOT `Preferable` — the provider is a stateless per-call strategy) and stored on the asset in `metadata['provider']` (`DigitalAsset` gained `Spree::Metadata` + a `metadata` column; `provider_settings` accessor), read in `deliver` via `digital_asset.provider_settings`. Primitive field types only (`:string`/`:number`/`:boolean`/`:select`); the `providers` discovery endpoint carries `settings_schema`; the dashboard renders a generic sheet — no provider ships React. **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); shared credentials/endpoints are never a `setting` (per-asset values only) and provider settings stay namespaced under `metadata['provider']`; 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/developer/how-to/custom-digital-asset-provider.mdx b/docs/developer/how-to/custom-digital-asset-provider.mdx
index 5ae8e4dd39..4ec32feca8 100644
--- a/docs/developer/how-to/custom-digital-asset-provider.mdx
+++ b/docs/developer/how-to/custom-digital-asset-provider.mdx
@@ -36,10 +36,17 @@ module Spree
false
end
+ # Per-asset configuration the dashboard renders as a form when a
+ # merchant adds an asset backed by this provider. See "Per-asset
+ # settings" below.
+ setting :pool_name, :string
+ setting :region, :select, in: %w[us eu], default: 'us'
+
def deliver(digital_link, expires_in:)
key = LicenseServer.issue(
- order_number: digital_link.line_item.order.number,
- sku: digital_asset.variant.sku
+ pool: digital_asset.provider_settings['pool_name'],
+ region: digital_asset.provider_settings['region'],
+ order_number: digital_link.line_item.order.number
)
return if key.blank?
@@ -61,6 +68,24 @@ Return a blank delivery (or `nil`) to mean "nothing to hand over". The download
`#deliver` must be safe to call before the download is charged. It runs while the grant is only *checked*, not yet *spent*, so a provider that raises or returns blank costs the customer nothing. Do any fallible work — the API call, the mint — inside `#deliver`, not after.
</Warning>
+## Per-asset settings
+
+Some providers need a value that differs from one asset to the next — which license pool this asset draws from, which external product it maps to. Declare each as a `setting`, and the dashboard renders a small form when the merchant adds an asset backed by this provider:
+
+```ruby
+setting :pool_name, :string
+setting :region, :select, in: %w[us eu], default: 'us'
+setting :auto_revoke, :boolean, default: false
+```
+
+Field types are `:string`, `:number`, `:boolean`, and `:select` (pass `in:` for the choices). The merchant's answers are stored on the asset and read back through `digital_asset.provider_settings`, a plain hash keyed by the setting name:
+
+```ruby
+digital_asset.provider_settings['pool_name'] # => "winter-sale"
+```
+
+A provider that declares no settings skips the form entirely — adding it is a single click. Settings are for per-asset values only; a credential or endpoint shared across every asset belongs in the provider's own configuration (an environment variable, Rails credentials), not a setting.
+
## 2. Register the provider
```ruby config/initializers/spree.rb
@@ -89,6 +114,7 @@ The order is deliberate: the deliverable is produced *before* the click is spent
|--------|----------|-------------|
| `#deliver(digital_link, expires_in:)` | Yes | Produce the deliverable for one authorized download. Return a `Spree::DigitalDelivery`, or blank/`nil` for "nothing to hand over". |
| `self.requires_attachment?` | No | Return `true` if an asset backed by this provider must carry an uploaded file. Defaults to `false`. Drives conditional validation and the admin create form. |
+| `self.setting(key, type, default:, in:)` | No | Declare a per-asset config field the dashboard renders as a form. Types: `:string`, `:number`, `:boolean`, `:select`. Read the merchant's answers via `digital_asset.provider_settings`. |
| `self.provider_name` | No | Human-readable name for admin UIs. Defaults to a titleized class name, or the outer module for a `SpreeAcme::LicenseProvider`-style gem. |
### DigitalDelivery
diff --git a/docs/plans/6.0-digital-assets.md b/docs/plans/6.0-digital-assets.md
index 74bacfdb9a..15340699ee 100644
--- a/docs/plans/6.0-digital-assets.md
+++ b/docs/plans/6.0-digital-assets.md
@@ -147,7 +147,9 @@ Registered via `Spree.digital_asset_providers` (mirrors `Spree.delivery_rate_pro
**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.
+**Admin + API.** The admin `DigitalAsset` serializer and params gain `provider_type` and `provider_settings` (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.
+
+**Per-asset provider settings (shipped 2026-08-12).** Two kinds of provider configuration, split clean: **shared** config (an endpoint, a credential — the same for every asset) stays the provider's own concern (env var, Rails credentials), never a Spree column; **per-asset** config (which license pool this asset draws from, which external product it maps to) is declared by the provider and stored on the asset. A provider declares fields with a class-level `setting :key, :type, default:, in:` DSL (`Base.settings_schema` returns the same `[{key,type,default}]` wire shape as `PreferenceSchema#serialized_preference_schema`, but is NOT `Preferable` — the provider is a stateless per-call strategy, not a persisted record, so the values can't live on it). Field types are primitives only: `:string`, `:number`, `:boolean`, `:select` (no record-reference pickers — a SKU is typed as a string). Values live on the `DigitalAsset` under one key in `metadata` (`DigitalAsset` gains `Spree::Metadata` + a `metadata` column; `provider_settings` reads/writes `metadata['provider']`), read back in `deliver` via `digital_asset.provider_settings`. The `providers` discovery endpoint carries each provider's `settings_schema`; picking a provider with a non-empty schema opens a sheet rendering one generic field per entry (a settings-free provider still creates in one click), and the edit sheet shows the same fields for a provider-backed asset. No provider ships dashboard code — the field list is data. **Constraint:** provider settings are per-asset values only; shared credentials/endpoints never become a `setting` (that path is the provider's own configuration), and the settings storage stays namespaced under `metadata['provider']` so it never collides with other developer metadata.
### Wave 7 — license-code pools
diff --git a/packages/admin-sdk/src/types/generated/DigitalAsset.ts b/packages/admin-sdk/src/types/generated/DigitalAsset.ts
index c004d0652a..3d8dee32eb 100644
--- a/packages/admin-sdk/src/types/generated/DigitalAsset.ts
+++ b/packages/admin-sdk/src/types/generated/DigitalAsset.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 50bce2576c8eedf0f0e048a65ad8f67c
+// Typelizer digest 91c63af32b0709bea23ff793d3a974c6
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
@@ -11,6 +11,7 @@ interface DigitalAsset {
authorized_days: number | null;
byte_size: number | null;
provider_type: string | null;
+ provider_settings: Record<string, unknown>;
created_at: string;
updated_at: string;
provider_name: string;
diff --git a/spree/api/app/controllers/spree/api/v3/admin/products/digital_assets_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/products/digital_assets_controller.rb
index 34d7bf27b9..a113494cd8 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/products/digital_assets_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/products/digital_assets_controller.rb
@@ -38,7 +38,8 @@ module Spree
{
type: provider_class.to_s,
name: provider_class.provider_name,
- requires_attachment: provider_class.requires_attachment?
+ requires_attachment: provider_class.requires_attachment?,
+ settings_schema: provider_class.settings_schema
}
end
@@ -84,8 +85,11 @@ module Spree
# rather than a column, so it is attached separately.
# provider_type is mass-assignable: the model validates it names a
# registered provider, so an unknown value is a 422, not a hazard.
+ # provider_settings is an open hash — its keys are declared by the
+ # provider, not fixed here — so it is permitted as arbitrary scalars
+ # and lands verbatim under one key in the asset's metadata.
def permitted_params
- params.permit(:authorized_clicks, :authorized_days, :provider_type)
+ params.permit(:authorized_clicks, :authorized_days, :provider_type, provider_settings: {})
end
private
diff --git a/spree/api/app/serializers/spree/api/v3/admin/digital_asset_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/digital_asset_serializer.rb
index 77116fe9fa..6da4582085 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/digital_asset_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/digital_asset_serializer.rb
@@ -12,9 +12,10 @@ module Spree
effective_authorized_days: :number,
provider_type: [:string, nullable: true],
provider_name: :string,
+ provider_settings: 'Record<string, unknown>',
download_url: [:string, nullable: true]
- attributes :authorized_clicks, :authorized_days, :byte_size, :provider_type
+ attributes :authorized_clicks, :authorized_days, :byte_size, :provider_type, :provider_settings
attributes created_at: :iso8601, updated_at: :iso8601
# Human-readable source for the admin listing. Blank provider_type is
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/products/digital_assets_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/products/digital_assets_controller_spec.rb
index 93a9c0c354..661f1ad172 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/products/digital_assets_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/products/digital_assets_controller_spec.rb
@@ -234,6 +234,7 @@ RSpec.describe Spree::Api::V3::Admin::Products::DigitalAssetsController, type: :
expect(types).to include('Spree::DigitalAssetProvider::File')
file = json_response['data'].find { |p| p['type'] == 'Spree::DigitalAssetProvider::File' }
expect(file['requires_attachment']).to be(true)
+ expect(file['settings_schema']).to eq([])
end
end
@@ -241,6 +242,7 @@ RSpec.describe Spree::Api::V3::Admin::Products::DigitalAssetsController, type: :
let(:stub_provider) do
Class.new(Spree::DigitalAssetProvider::Base) do
def self.requires_attachment? = false
+ setting :pool_name, :string
def deliver(_link, expires_in:) = Spree::DigitalDelivery.new(inline_value: 'X')
end
end
@@ -252,6 +254,13 @@ RSpec.describe Spree::Api::V3::Admin::Products::DigitalAssetsController, type: :
after { Spree.digital_asset_providers.delete(stub_provider) }
+ it 'advertises the provider settings schema for the source picker' do
+ get :providers, params: { product_id: product.prefixed_id }
+
+ stub = json_response['data'].find { |p| p['type'] == 'Spree::DigitalAssetProvider::Stub' }
+ expect(stub['settings_schema']).to eq([{ 'key' => 'pool_name', 'type' => 'string' }])
+ end
+
it 'creates a provider-backed asset with no file' do
post :create, params: {
product_id: product.prefixed_id,
@@ -262,6 +271,18 @@ RSpec.describe Spree::Api::V3::Admin::Products::DigitalAssetsController, type: :
expect(json_response['provider_type']).to eq('Spree::DigitalAssetProvider::Stub')
end
+ it 'stores the provider settings on the asset' do
+ post :create, params: {
+ product_id: product.prefixed_id,
+ provider_type: 'Spree::DigitalAssetProvider::Stub',
+ provider_settings: { pool_name: 'winter-sale' }
+ }, as: :json
+
+ expect(response).to have_http_status(:created)
+ expect(json_response['provider_settings']).to eq('pool_name' => 'winter-sale')
+ expect(Spree::DigitalAsset.last.provider_settings).to eq('pool_name' => 'winter-sale')
+ end
+
it 'rejects an unregistered provider_type' do
post :create, params: {
product_id: product.prefixed_id,
diff --git a/spree/core/app/models/spree/digital_asset.rb b/spree/core/app/models/spree/digital_asset.rb
index 9119ce84ed..a90bd32e70 100644
--- a/spree/core/app/models/spree/digital_asset.rb
+++ b/spree/core/app/models/spree/digital_asset.rb
@@ -1,9 +1,17 @@
module Spree
class DigitalAsset < Spree.base_class
+ include Spree::Metadata
+
has_prefix_id :dig
publishes_lifecycle_events
+ # Provider config lives under one key in `metadata` so a provider owns its
+ # own namespace without colliding with other developer metadata. The values
+ # match the provider's `settings_schema`; the provider reads them in
+ # `deliver`.
+ PROVIDER_SETTINGS_KEY = 'provider'.freeze
+
belongs_to :variant, class_name: 'Spree::Variant'
has_many :digital_links, class_name: 'Spree::DigitalLink', dependent: :destroy
@@ -55,6 +63,19 @@ module Spree
(provider_type.presence || DEFAULT_PROVIDER).safe_constantize || DEFAULT_PROVIDER.constantize
end
+ # The provider's per-asset configuration, as declared by its
+ # `settings_schema`. Stored under one key in `metadata`.
+ #
+ # @return [Hash]
+ def provider_settings
+ metadata.fetch(PROVIDER_SETTINGS_KEY, {}) || {}
+ end
+
+ # @param values [Hash]
+ def provider_settings=(values)
+ self.metadata = metadata.merge(PROVIDER_SETTINGS_KEY => (values || {}))
+ end
+
# Produces the deliverable for one authorized download — a redirect URL or
# an inline value — via the provider. Callers stay out of the storage layer
# so a provider-backed asset can answer without an attachment.
diff --git a/spree/core/app/models/spree/digital_asset_provider/base.rb b/spree/core/app/models/spree/digital_asset_provider/base.rb
index 0dc3a78a28..a4db10c7e9 100644
--- a/spree/core/app/models/spree/digital_asset_provider/base.rb
+++ b/spree/core/app/models/spree/digital_asset_provider/base.rb
@@ -14,7 +14,45 @@ module Spree
class Base
attr_reader :digital_asset
+ SETTING_TYPES = %i[string number boolean select].freeze
+
class << self
+ # Declares one per-asset configuration field the dashboard renders when
+ # a merchant adds an asset backed by this provider. Mirrors the
+ # `preference` shape used elsewhere, but the values live on the
+ # DigitalAsset (in `metadata`), not on the stateless provider instance.
+ #
+ # @param key [Symbol]
+ # @param type [Symbol] one of {SETTING_TYPES}
+ # @param default [Object]
+ # @param in [Array] allowed values for a `:select` field
+ def setting(key, type = :string, default: nil, in: nil)
+ raise ArgumentError, "unknown setting type #{type}" unless SETTING_TYPES.include?(type)
+
+ own_settings[key.to_sym] = {
+ key: key.to_sym,
+ type: type,
+ default: default,
+ in: binding.local_variable_get(:in)
+ }.compact
+ end
+
+ # `[{ key:, type:, default:, in? }]` for every setting declared on this
+ # provider and its ancestors. Same wire shape the admin form renders
+ # from, so no provider ships dashboard code.
+ #
+ # @return [Array<Hash>]
+ def settings_schema
+ ancestors.reverse.each_with_object({}) do |ancestor, merged|
+ merged.merge!(ancestor.own_settings) if ancestor.respond_to?(:own_settings)
+ end.values
+ end
+
+ # @api private
+ def own_settings
+ @own_settings ||= {}
+ end
+
# Human-readable name for admin UIs. Provider gems following the
# `SpreeAcme::LicenseProvider` convention get the outer module
# ("Acme"); a bare in-app class gets its own titleized name.
diff --git a/spree/core/db/migrate/20260812000002_add_metadata_to_spree_digital_assets.rb b/spree/core/db/migrate/20260812000002_add_metadata_to_spree_digital_assets.rb
new file mode 100644
index 0000000000..cf373552b0
--- /dev/null
+++ b/spree/core/db/migrate/20260812000002_add_metadata_to_spree_digital_assets.rb
@@ -0,0 +1,11 @@
+class AddMetadataToSpreeDigitalAssets < ActiveRecord::Migration[8.1]
+ def change
+ change_table :spree_digital_assets do |t|
+ if t.respond_to?(:jsonb)
+ add_column :spree_digital_assets, :metadata, :jsonb
+ else
+ add_column :spree_digital_assets, :metadata, :json
+ end
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/digital_asset_provider/base_spec.rb b/spree/core/spec/models/spree/digital_asset_provider/base_spec.rb
new file mode 100644
index 0000000000..ac8371333c
--- /dev/null
+++ b/spree/core/spec/models/spree/digital_asset_provider/base_spec.rb
@@ -0,0 +1,39 @@
+require 'spec_helper'
+
+RSpec.describe Spree::DigitalAssetProvider::Base do
+ describe '.setting / .settings_schema' do
+ let(:provider) do
+ Class.new(described_class) do
+ setting :pool_name, :string
+ setting :region, :select, in: %w[us eu], default: 'us'
+ setting :auto_revoke, :boolean, default: false
+ end
+ end
+
+ it 'exposes each declared setting in the wire shape the form renders' do
+ schema = provider.settings_schema
+
+ expect(schema).to contain_exactly(
+ { key: :pool_name, type: :string },
+ { key: :region, type: :select, default: 'us', in: %w[us eu] },
+ { key: :auto_revoke, type: :boolean, default: false }
+ )
+ end
+
+ it 'rejects an unknown field type' do
+ expect { Class.new(described_class) { setting :x, :date } }
+ .to raise_error(ArgumentError, /unknown setting type/)
+ end
+
+ it 'is empty for a provider that declares nothing' do
+ expect(Class.new(described_class).settings_schema).to eq([])
+ end
+
+ it 'inherits a parent provider settings' do
+ child = Class.new(provider) { setting :extra, :string }
+
+ expect(child.settings_schema.map { |field| field[:key] })
+ .to include(:pool_name, :region, :auto_revoke, :extra)
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/digital_asset_spec.rb b/spree/core/spec/models/spree/digital_asset_spec.rb
index 72e20d9243..c9f47adef9 100644
--- a/spree/core/spec/models/spree/digital_asset_spec.rb
+++ b/spree/core/spec/models/spree/digital_asset_spec.rb
@@ -60,6 +60,18 @@ describe Spree::DigitalAsset, type: :model do
expect(asset).not_to be_valid
expect(asset.errors[:provider_type]).to be_present
end
+
+ it 'stores provider settings under one key in metadata' do
+ asset = described_class.new
+ asset.provider_settings = { 'pool_name' => 'winter' }
+
+ expect(asset.provider_settings).to eq('pool_name' => 'winter')
+ expect(asset.metadata['provider']).to eq('pool_name' => 'winter')
+ end
+
+ it 'returns an empty hash when no provider settings are set' do
+ expect(described_class.new.provider_settings).to eq({})
+ end
end
# The legacy names are the one-release webhook bridge; dropping them silently