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.

Rename Digital to DigitalAsset and harden digital downloads

Damian Legawiec3f33c7b608ce
diff --git a/CLAUDE.md b/CLAUDE.md
index 66c73969c9..16d122e981 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -27,6 +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` — `Spree::Digital` → `Spree::DigitalAsset` (full table + FK rename with one-release bridges; `DigitalLink` keeps its name; design finalized 2026-08-10) plus the missing management/delivery surface: Admin API v3 (assets nested under products, link `reset`, resend; catalog: assets ride `products`, link management rides `orders`), dashboard product card + order links + Downloads settings, dedicated `Spree::DigitalAssetMailer` (`files_ready_email` / opt-in `file_updated_email`), customer `GET /store/account/digital_links` + store SDK resource, `digital_link.downloaded` domain event (no log table), signed-URL download transport (dead `digital_asset_link_expire_time` pref becomes the TTL), 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.
- `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/upgrades/5.6-to-6.0.mdx b/docs/developer/upgrades/5.6-to-6.0.mdx
index b8c50ea2a1..98c6ef624c 100644
--- a/docs/developer/upgrades/5.6-to-6.0.mdx
+++ b/docs/developer/upgrades/5.6-to-6.0.mdx
@@ -288,6 +288,9 @@ A handler receives the workflow (so it can read `order`, `items`, `created_by`,
- **The reimbursement email is now `Spree::ReturnMailer#refunded_email`**, sent on `return.refunded` (in the optional `spree_emails` gem, like the other transactional mail).
- **`Refund#originator`** points at the new records.
- Events are `return.requested` / `.approved` / `.received` / `.refunded` / `.canceled`, and the matching `exchange.*` and `claim.*` families.
+- **Digital downloads redirect instead of streaming.** The download endpoint now answers `302` with a short-lived signed URL rather than sending the file bytes directly, so a large download no longer occupies a web worker. Clients that read the response body must follow redirects (most HTTP clients and every browser already do). The link's own lifetime is unchanged; `digital_asset_link_expire_time` (default 300 seconds) — previously unused — now sets how long the signed URL stays valid, and is capped at one hour because that URL is a bearer credential. The signed URL is additionally clamped so it can never outlive the download link that issued it.
+- **Download limits can be set per asset.** `authorized_clicks` and `authorized_days` on a digital asset override the store's download settings; left blank, the store settings apply as before.
+- **A successful download publishes `digital_link.downloaded`**, so downloads are visible to webhooks and subscribers for the first time.
## Dependency injection changes
@@ -572,6 +575,11 @@ Every rename keeps the legacy name working for one release with a deprecation wa
| `CustomFieldDefinition#name`, `#metafield_type`, `#display_on` | `#label`, `#field_type`, `#storefront_visible` (columns renamed) |
| `Spree::SearchProvider::Meilisearch` | `SpreeMeilisearch::SearchProvider` (moved to the `spree_meilisearch` gem) |
| `Spree::SearchProvider::ProductPresenter` | `SpreeMeilisearch::ProductPresenter` (moved to the `spree_meilisearch` gem) |
+| `Spree::Digital` | `Spree::DigitalAsset` (table `spree_digitals` → `spree_digital_assets`, `digital_id` → `digital_asset_id`) |
+| `Variant#digitals`, `Product#digitals`, `DigitalLink#digital` | `#digital_assets` / `#digital_asset` |
+| `digital.created` / `.updated` / `.deleted` events | `digital_asset.*` (both emitted for one release) |
+| `PermittedAttributes.digital_attributes` | `.digital_asset_attributes` |
+| `GET /api/v3/store/digitals/:token` | `GET /api/v3/store/digital_links/:token` (old path keeps working) |
## Meilisearch moved to its own gem
diff --git a/docs/plans/6.0-digital-assets.md b/docs/plans/6.0-digital-assets.md
new file mode 100644
index 0000000000..e96eea1101
--- /dev/null
+++ b/docs/plans/6.0-digital-assets.md
@@ -0,0 +1,95 @@
+# Digital Assets: Rename, Admin Management, Delivery
+
+**Status:** In Progress — wave 1 (rename) shipped 2026-08-10; waves 2–4 pending
+**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
+**Last updated:** 2026-08-10
+
+## Summary
+
+Spree ships a complete digital products engine in core: `Spree::Digital` (a file on a variant, private storage, many per variant) and `Spree::DigitalLink` (a per-purchase token with click and day limits), auto-fulfilled at order completion — including digital files riding on physically shipped items. But the engine is invisible: there is no Admin API, no dashboard page (the legacy Rails admin UI was deleted with that engine), no email ever delivers a download link, and downloads publish no events, so a merchant needs a console to sell an ebook and a customer never receives a file unless the storefront wires it up. This plan renames the model to `Spree::DigitalAsset` (the name the docs, the store preferences, and the legacy admin already use), builds the Admin API v3 + dashboard management surface, adds a delivery mailer, a customer downloads endpoint, download events, per-asset limit overrides, and signed-URL download transport — closing the gap between what the engine does and what merchants and customers can see.
+
+## Key Decisions (do not deviate without discussion)
+
+- **Rename `Spree::Digital` → `Spree::DigitalAsset`** (2026-08-10). The model name finally matches the docs, the store preferences (`digital_asset_*`), and the legacy admin's vocabulary. `Spree::DigitalLink` keeps its name — it reads correctly next to `DigitalAsset`. Prefixed ID stays `dig_`.
+- **Full table rename** (2026-08-10): `spree_digitals` → `spree_digital_assets`, `spree_digital_links.digital_id` → `digital_asset_id`. 6.0 is the breaking window and the categories rename set the precedent; class, table, and FK all match with no pinning. Accepted cost: one schema migration every host runs, one more upgrade-guide step.
+- **Deprecation bridges everywhere, per the standard convention**: `Spree::Digital = Spree::DigitalAsset` constant alias with a warning for one release; `variant.digitals` / `product.digitals` / `digital_link.digital` kept as deprecated twin associations (`deprecated: true`); internal code uses the new names only.
+- **Lifecycle events dual-emit for one release**: new canonical `digital_asset.*` events, legacy `digital.*` twins emitted alongside (same pattern as the fulfillment rename).
+- **Store download route**: canonical becomes `GET /api/v3/store/digital_links/:token` (the resource being fetched IS the link); the legacy `GET /api/v3/store/digitals/:token` path keeps working for one release because emailed/bookmarked URLs live in the wild.
+- **Dedicated delivery mailer** (2026-08-10): `Spree::DigitalAssetMailer` with `files_ready_email` (sent on order completion when digital links exist) and `file_updated_email` (opt-in, on attachment replacement), rather than a section in the order confirmation. Rationale: works for mixed orders, resendable from admin as a standalone action, and survives headless shops replacing the confirmation email. Accepted cost: a second email in the inbox for digital orders.
+- **Per-asset limit overrides** (2026-08-10): nullable `authorized_clicks` / `authorized_days` on `spree_digital_assets`; null falls back to the store setting. Lets one catalog mix re-download-forever items with time-limited ones. **This is an explicit, documented exception to the "store preference is authoritative, no runtime fallback" rule** in `6.0-store-scoped-configuration.md` — the fallback here is record-level (asset → its store's setting), never a chain through global config, and the store setting remains the single authoritative default.
+- **Signed-URL download transport** (2026-08-10): the store download action calls `authorize!` then redirects to a short-lived signed storage URL instead of proxying bytes through `send_data`, freeing Puma workers for large files. The previously dead `digital_asset_link_expire_time` store preference (default 300) becomes the signed-URL TTL — kept and documented instead of deleted. Accepted cost: clients that expected file bytes on the token URL must follow the redirect (one-release note in the changelog).
+- **Permission catalog placement**: `Spree::DigitalAsset` joins the `:products` catalog resource (rides `read_products` / `write_products` — catalog data managed from the product page); `Spree::DigitalLink` management (reset) joins `:orders` (`write_orders` — a per-purchase order artifact). No new catalog resource; digital assets are not `settings`-sensitive.
+- **Admin API shape**: nested index + create under products (`/admin/products/:product_id/digital_assets`), shallow show/update/destroy (`/admin/digital_assets/:id`), matching existing nested-resource conventions. File upload via direct-upload signed blob (same mechanism as CSV import), never multipart through the API request.
+- **Download visibility ships as an event, not a log table**: successful downloads publish a `digital_link.downloaded` domain event (webhook-visible). The dashboard surfaces `access_counter` and last-download time (already tracked — `authorize!` increments with `touch: true`). A persisted per-download log table is deferred until someone needs per-download rows (IP, user agent).
+- **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.
+
+## Design Details
+
+### Model rename
+
+`spree/core/app/models/spree/digital.rb` → `digital_asset.rb`, class `Spree::DigitalAsset`. One migration renames the table and the FK column. Associations gain explicit `class_name`. `Spree::DigitalLink` gets `belongs_to :digital_asset` plus deprecated `digital` reader/writer delegates. `Variant#digital_assets`, `Product#digital_assets` (through variants), scope `with_digital_assets` unchanged in behavior. The optional `Spree::Security::DigitalLinks` include point is untouched.
+
+New nullable override columns on `spree_digital_assets`: `authorized_clicks`, `authorized_days` (integers, no defaults — null means "use the store setting"). `DigitalLink#expired?` / `#access_limit_exceeded?` read the effective value through the asset.
+
+Serializers: `DigitalSerializer` → `DigitalAssetSerializer` (store, stays minimal and unmounted), new `Admin::DigitalAssetSerializer` extending it with `variant_id` (prefixed), `filename`, `content_type`, `byte_size`, the override fields, timestamps. Dependencies registration renamed with the legacy key readable one release.
+
+### Admin API v3
+
+- `GET /api/v3/admin/products/:product_id/digital_assets` — list, includes variant info for the picker.
+- `POST /api/v3/admin/products/:product_id/digital_assets` — params: `variant_id` (prefixed; defaults to the product's default variant when absent, mirroring the legacy admin's auto-assign), `attachment` (signed blob id), `authorized_clicks`, `authorized_days`.
+- `GET/PATCH/DELETE /api/v3/admin/digital_assets/:id` — PATCH accepts `variant_id`, the override fields, and a replacement `attachment` blob (which may trigger `file_updated_email`, opt-in per request).
+- `POST /api/v3/admin/digital_links/:id/reset` — zeroes the counter and restarts the expiry clock (`DigitalLink#reset!`, which has existed since 2021 without a caller).
+- `POST /api/v3/admin/orders/:id/resend_digital_links` — re-sends `files_ready_email`.
+
+All lookups scoped through `current_store` (assets via the product association chain, links via `current_store.digital_links`).
+
+### Dashboard
+
+- **Product page — "Digital files" card**: listed for products whose type includes the `digital` fulfillment type (and any product that already has assets, so legacy data stays reachable). Upload with progress (direct upload), variant picker, filename + human file size + variant columns, per-file "Custom limits" toggle exposing the two override fields, replace, delete behind `useConfirm({ variant: 'destructive' })`.
+- **Order page — links on digital line items**: per-link status (clicks used / effective limit, expires-at or expired badge), reset action behind a confirm explaining that it re-opens access, resend-email action.
+- **Store settings — Downloads section**: fields for `limit_digital_download_count`, `digital_asset_authorized_clicks`, `limit_digital_download_days`, `digital_asset_authorized_days`, `digital_asset_link_expire_time`.
+- `@spree/admin-sdk`: `digitalAssets` resource, `digitalLinks.reset`, order resend; translations in all locale files.
+
+### Delivery email
+
+`Spree::DigitalAssetMailer` in `spree/emails`, triggered by a subscriber on order completion when the order has digital links (after the auto-fulfill steps in `Orders::Complete` have created them). `files_ready_email` lists each purchased file with its download URL; `file_updated_email` notifies past buyers when an asset's attachment is replaced — opt-in at replacement time, never automatic. Both resendable from the admin order page.
+
+### Customer downloads
+
+`GET /api/v3/store/account/digital_links` — authenticated customer, lists links across their completed orders with product/variant/filename context and authorizability state. Store SDK gains a `digitalLinks` resource (list + a download-URL helper); today the SDK ships generated types but no methods, so storefronts hand-build URLs.
+
+### Download transport and events
+
+The 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`.
+
+## Migration Path
+
+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**: catalog entries (`DigitalAsset` → `:products`, link reset → `:orders`), controllers + routes + serializers, remove the phantom `:digital` product param, integration specs, typelizer + OpenAPI regeneration.
+3. **Dashboard wave**: admin-sdk resources, product card, order-page links + reset + resend, settings section, e2e specs.
+4. **Delivery wave**: mailer + subscriber, customer downloads endpoint + store SDK resource, signed-URL transport + `digital_link.downloaded` event, canonical route + legacy route bridge.
+5. **Docs correction** (can land first, independently): `docs/use-case/digital-products/admin-capabilities.mdx` currently describes management screens, release triggers, resendable emails, and download logs that do not exist — trim to reality now, re-expand as waves ship.
+
+## 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).
+- Emailed download URLs are long-lived customer-facing artifacts: any route change must keep old URLs working for at least one release.
+
+## Open Questions
+
+Only deferred items remain; nothing blocks implementation.
+
+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 once this plan ships. Unblocked by: this plan's waves landing, plus 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.
+
+## 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.
+- Code: `spree/core/app/models/spree/digital.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/digitals_controller.rb`, `spree/core/lib/spree/core/permission_configuration.rb`.
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index ad9f321602..ac70c4d31a 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -1102,6 +1102,42 @@ request keys but not response bodies) and were redacted; cassettes now default
to `record: :none`, since record-by-default turns renaming a `:vcr` example
into a live API call.
+## 2026-08-10: `Spree::Digital` → `Spree::DigitalAsset`; digital assets get an admin surface, delivery mailer, and per-asset limit fallback
+
+Plan: `6.0-digital-assets.md`. Full rename at 6.0 — class, `spree_digitals` →
+`spree_digital_assets` table, and `digital_id` → `digital_asset_id` FK — with
+the standard one-release bridges (constant alias, deprecated twin
+associations, dual-emitted `digital.*`/`digital_asset.*` events).
+`Spree::DigitalLink` keeps its name. The plan also builds the missing
+management surface (Admin API v3 + dashboard, catalog placement: assets under
+`:products`, link reset under `:orders`), a dedicated
+`Spree::DigitalAssetMailer` (never a section in the order confirmation), a
+customer `GET /store/account/digital_links` endpoint, a
+`digital_link.downloaded` domain event, and signed-URL download transport
+(the previously dead `digital_asset_link_expire_time` preference becomes the
+signed-URL TTL instead of being deleted).
+
+**Why:** the engine shipped in 6.0's fulfillment rework is complete but has
+no admin API, no dashboard page, no delivery email and no download
+visibility; the model name `Digital` never matched the docs, the
+`digital_asset_*` preferences, or the deleted legacy admin's vocabulary.
+Renaming before the admin endpoints exist is the cheap moment.
+
+**Recorded exception:** digital assets carry nullable `authorized_clicks` /
+`authorized_days` that fall back to the store's download settings at read
+time. This is a deliberate, documented exception to the
+`6.0-store-scoped-configuration.md` "store preference is authoritative, no
+runtime fallback" rule — the fallback is record → its store's setting only,
+never a chain through global `Spree::Config`, and the store setting remains
+the authoritative default.
+
+**Consequences:** new code uses `DigitalAsset`/`digital_assets` names only;
+admin controllers for these models land with their permission catalog
+entries; nothing outside the model may assume an attachment is always
+present (external/provider-backed asset kinds and license-key pools are
+groomed for 6.1); emailed download URLs must keep resolving across renames
+for at least one release.
+
## 2026-08-09: Metadata consolidated to one column — `public_metadata` dropped, `private_metadata` renamed
Implements the 2026-03-16 consolidation decision. All thirty metadata-carrying
diff --git a/docs/use-case/digital-products/admin-capabilities.mdx b/docs/use-case/digital-products/admin-capabilities.mdx
index 89243abbed..e0a432da93 100644
--- a/docs/use-case/digital-products/admin-capabilities.mdx
+++ b/docs/use-case/digital-products/admin-capabilities.mdx
@@ -3,47 +3,40 @@ title: "Digital Products Admin Capabilities"
description: "Learn about the digital product features available in the Spree admin dashboard."
---
-Spree Commerce provides robust tools for managing digital products, offering flexibility and control over how files are configured, delivered, and accessed. Whether you're selling standalone digital goods or bundling them with physical items, Spree helps you streamline digital product operations while maintaining security and customer satisfaction.
+Spree Commerce provides tools for managing digital products, offering flexibility and control over how files are configured, delivered, and accessed. Whether you're selling standalone digital goods or bundling them with physical items, Spree helps you streamline digital product operations while maintaining security and customer satisfaction.
Below is a breakdown of the key capabilities available to store administrators.
## Flexible Product Configuration
- Configure any product to be digital-only, physical, or a hybrid (e.g., physical textbook with downloadable companion PDF).
-- Attach digital files (PDFs, ZIPs, etc.) directly to the product variant or order.
-- File management UI in the admin dashboard for uploading, replacing, and associating files.
+- Attach digital files (PDFs, ZIPs, etc.) to any product variant — including variants of physical products, so a manual or warranty document ships alongside the goods.
## Download Access Management
-- Set download link expiration (e.g., 3 days) and/or maximum number of downloads (e.g., 5 per order).
-- Control when download links become available:
- - Immediately after payment
- - Manually after admin approval
- - Upon fulfillment or other triggers
+- Limit how long a download link stays valid and how many times it can be used.
+- Set those limits once for the whole store, or override either of them on an individual file — so an evergreen download and a time-limited course can live in the same catalog.
+- Reset a customer's download link when they run out of attempts.
-## Shipping Step Bypass
+## Delivery Step Bypass
-- Assign a “Digital Delivery” shipping category to digital products.
-- If a cart only contains digital items, the shipping step is skipped entirely for faster checkout.
+- Digital products are delivered by the built-in Digital delivery method, which needs no shipping address.
+- If a cart only contains digital items, the delivery step is skipped entirely for faster checkout.
## Automated Digital Delivery
-- Send download links by email after order placement.
-- Customers can also access downloads from their “My Account” dashboard after logging in.
-- Admins can resend download emails or regenerate download links when needed.
+- Digital items are fulfilled automatically when the order is placed — download links are ready immediately, with no manual step.
+- Customers access their downloads through your storefront or app, which reads the links from the order.
-## Order and Access Logs
+## Download Visibility
-- Track and manage:
- - Which files were downloaded
- - How many times
- - By whom (customer email/account)
-- Useful for fraud prevention or usage auditing.
+- Every download increments a counter on the link, so you can see how many times a file has been fetched.
+- A `digital_link.downloaded` event fires on each successful download, so you can feed downloads into your own auditing, analytics, or fraud tooling via webhooks.
## Security and Permissions
-- Files are stored securely and served via protected, time-limited download URLs.
-- Non-public file access prevents direct linking or unauthorized downloads.
+- Files are stored privately and served through protected, time-limited download URLs.
+- Each link is unique to a single purchased unit, and non-public file storage prevents direct linking or unauthorized downloads.
## Bundling & Promotions
@@ -52,8 +45,8 @@ Below is a breakdown of the key capabilities available to store administrators.
## Custom Rules & Logic (Optional)
-- Use Spree’s flexible architecture to create custom workflows, such as:
- - Requiring customer approval for certain file types
+- Use Spree's flexible architecture to create custom workflows, such as:
+ - Sending your own download emails by subscribing to order and download events
- Generating personalized files (e.g., license keys or certificates)
- Integrating with external file storage or DRM systems
diff --git a/packages/admin-sdk/src/types/generated/DigitalAsset.ts b/packages/admin-sdk/src/types/generated/DigitalAsset.ts
new file mode 100644
index 0000000000..d1ad4eec28
--- /dev/null
+++ b/packages/admin-sdk/src/types/generated/DigitalAsset.ts
@@ -0,0 +1,19 @@
+// Typelizer digest d29bb4005881ad3f5a627226586ba035
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+
+interface DigitalAsset {
+ id: string;
+ variant_id: string | null;
+ filename: string | null;
+ content_type: string | null;
+ authorized_clicks: number | null;
+ authorized_days: number | null;
+ byte_size: number | null;
+ created_at: string;
+ updated_at: string;
+ effective_authorized_clicks: number;
+ effective_authorized_days: number;
+}
+
+export default DigitalAsset;
diff --git a/packages/admin-sdk/src/types/generated/DigitalLink.ts b/packages/admin-sdk/src/types/generated/DigitalLink.ts
index cc65e73260..a525584b80 100644
--- a/packages/admin-sdk/src/types/generated/DigitalLink.ts
+++ b/packages/admin-sdk/src/types/generated/DigitalLink.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 7d22b35201e92223ecbfa24c5c249a20
+// Typelizer digest dcd70bd5624e961bf687c8c154bccbf0
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
@@ -8,6 +8,7 @@ interface DigitalLink {
filename: string;
content_type: string;
download_url: string;
+ expires_at: string | null;
authorizable: boolean;
expired: boolean;
access_limit_exceeded: boolean;
diff --git a/packages/admin-sdk/src/types/index.ts b/packages/admin-sdk/src/types/index.ts
index 775db9772b..596e047f9f 100644
--- a/packages/admin-sdk/src/types/index.ts
+++ b/packages/admin-sdk/src/types/index.ts
@@ -49,6 +49,7 @@ export type { default as DeliveryProfile } from './generated/DeliveryProfile'
export type { default as DeliveryRate } from './generated/DeliveryRate'
export type { default as DeliveryZone } from './generated/DeliveryZone'
export type { default as DeliveryZoneMember } from './generated/DeliveryZoneMember'
+export type { default as DigitalAsset } from './generated/DigitalAsset'
export type { default as DigitalLink } from './generated/DigitalLink'
export type { default as Discount } from './generated/Discount'
export type { default as Exchange } from './generated/Exchange'
diff --git a/packages/dashboard-starter/src/routeTree.gen.ts b/packages/dashboard-starter/src/routeTree.gen.ts
index cf6c752f6c..3226f35dba 100644
--- a/packages/dashboard-starter/src/routeTree.gen.ts
+++ b/packages/dashboard-starter/src/routeTree.gen.ts
@@ -9,7 +9,6 @@
// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
import { Route as rootRouteImport } from './../../dashboard/src/routes/__root'
-import { Route as setupRouteImport } from './../../dashboard/src/routes/setup'
import { Route as resetPasswordRouteImport } from './../../dashboard/src/routes/reset-password'
import { Route as loginRouteImport } from './../../dashboard/src/routes/login'
import { Route as forgotPasswordRouteImport } from './../../dashboard/src/routes/forgot-password'
@@ -87,11 +86,6 @@ import { Route as ProductsPriceListsPriceListIdIndexRouteImport } from './../../
import { Route as SettingsDeliveryProfilesProfileIdMethodsNewRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/delivery-profiles/$profileId/methods/new'
import { Route as SettingsDeliveryProfilesProfileIdMethodsMethodIdRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/delivery-profiles/$profileId/methods/$methodId'
-const setupRoute = setupRouteImport.update({
- id: '/setup',
- path: '/setup',
- getParentRoute: () => rootRouteImport,
-} as any)
const resetPasswordRoute = resetPasswordRouteImport.update({
id: '/reset-password',
path: '/reset-password',
@@ -490,7 +484,6 @@ export interface FileRoutesByFullPath {
'/forgot-password': typeof forgotPasswordRoute
'/login': typeof loginRoute
'/reset-password': typeof resetPasswordRoute
- '/setup': typeof setupRoute
'/$storeId': typeof authenticatedStoreIdRouteWithChildren
'/accept-invitation/$invitationId': typeof acceptInvitationDotinvitationIdRoute
'/$storeId/$': typeof SplatRoute
@@ -567,7 +560,6 @@ export interface FileRoutesByTo {
'/forgot-password': typeof forgotPasswordRoute
'/login': typeof loginRoute
'/reset-password': typeof resetPasswordRoute
- '/setup': typeof setupRoute
'/accept-invitation/$invitationId': typeof acceptInvitationDotinvitationIdRoute
'/': typeof authenticatedIndexRoute
'/$storeId/$': typeof SplatRoute
@@ -645,7 +637,6 @@ export interface FileRoutesById {
'/forgot-password': typeof forgotPasswordRoute
'/login': typeof loginRoute
'/reset-password': typeof resetPasswordRoute
- '/setup': typeof setupRoute
'/_authenticated/$storeId': typeof authenticatedStoreIdRouteWithChildren
'/accept-invitation/$invitationId': typeof acceptInvitationDotinvitationIdRoute
'/_authenticated/': typeof authenticatedIndexRoute
@@ -726,7 +717,6 @@ export interface FileRouteTypes {
| '/forgot-password'
| '/login'
| '/reset-password'
- | '/setup'
| '/$storeId'
| '/accept-invitation/$invitationId'
| '/$storeId/$'
@@ -803,7 +793,6 @@ export interface FileRouteTypes {
| '/forgot-password'
| '/login'
| '/reset-password'
- | '/setup'
| '/accept-invitation/$invitationId'
| '/'
| '/$storeId/$'
@@ -880,7 +869,6 @@ export interface FileRouteTypes {
| '/forgot-password'
| '/login'
| '/reset-password'
- | '/setup'
| '/_authenticated/$storeId'
| '/accept-invitation/$invitationId'
| '/_authenticated/'
@@ -960,19 +948,11 @@ export interface RootRouteChildren {
forgotPasswordRoute: typeof forgotPasswordRoute
loginRoute: typeof loginRoute
resetPasswordRoute: typeof resetPasswordRoute
- setupRoute: typeof setupRoute
acceptInvitationDotinvitationIdRoute: typeof acceptInvitationDotinvitationIdRoute
}
declare module '@tanstack/react-router' {
interface FileRoutesByPath {
- '/setup': {
- id: '/setup'
- path: '/setup'
- fullPath: '/setup'
- preLoaderRoute: typeof setupRouteImport
- parentRoute: typeof rootRouteImport
- }
'/reset-password': {
id: '/reset-password'
path: '/reset-password'
@@ -1689,7 +1669,6 @@ const rootRouteChildren: RootRouteChildren = {
forgotPasswordRoute: forgotPasswordRoute,
loginRoute: loginRoute,
resetPasswordRoute: resetPasswordRoute,
- setupRoute: setupRoute,
acceptInvitationDotinvitationIdRoute: acceptInvitationDotinvitationIdRoute,
}
export const routeTree = rootRouteImport
diff --git a/packages/sdk/src/types/generated/Digital.ts b/packages/sdk/src/types/generated/Digital.ts
deleted file mode 100644
index 74b77a0c6c..0000000000
--- a/packages/sdk/src/types/generated/Digital.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-// Typelizer digest fa050c7afcfdba96b97d96976b632e2c
-//
-// DO NOT MODIFY: This file was automatically generated by Typelizer.
-
-interface Digital {
- id: string;
- created_at: string;
- updated_at: string;
- variant_id: string | null;
-}
-
-export default Digital;
diff --git a/packages/sdk/src/types/generated/DigitalAsset.ts b/packages/sdk/src/types/generated/DigitalAsset.ts
new file mode 100644
index 0000000000..4c3c9fffeb
--- /dev/null
+++ b/packages/sdk/src/types/generated/DigitalAsset.ts
@@ -0,0 +1,12 @@
+// Typelizer digest 57b36abe5a6deb9ca97666f75b3cfeac
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+
+interface DigitalAsset {
+ id: string;
+ variant_id: string | null;
+ filename: string | null;
+ content_type: string | null;
+}
+
+export default DigitalAsset;
diff --git a/packages/sdk/src/types/generated/DigitalLink.ts b/packages/sdk/src/types/generated/DigitalLink.ts
index 390e5faff2..76c4aa30ca 100644
--- a/packages/sdk/src/types/generated/DigitalLink.ts
+++ b/packages/sdk/src/types/generated/DigitalLink.ts
@@ -1,4 +1,4 @@
-// Typelizer digest a87f85fa9733261f443b9236543566b8
+// Typelizer digest fc8455a1f474d22343645b2717da4b7f
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
@@ -8,6 +8,7 @@ interface DigitalLink {
filename: string;
content_type: string;
download_url: string;
+ expires_at: string | null;
authorizable: boolean;
expired: boolean;
access_limit_exceeded: boolean;
diff --git a/packages/sdk/src/types/generated/index.ts b/packages/sdk/src/types/generated/index.ts
index 5a9eb3c0e5..a87509318c 100644
--- a/packages/sdk/src/types/generated/index.ts
+++ b/packages/sdk/src/types/generated/index.ts
@@ -24,8 +24,8 @@ export type { default as DeliveryMethod } from './DeliveryMethod'
export type { default as DeliveryRate } from './DeliveryRate'
export type { default as DeliveryZoneMember } from './DeliveryZoneMember'
export type { default as DeliveryZone } from './DeliveryZone'
+export type { default as DigitalAsset } from './DigitalAsset'
export type { default as DigitalLink } from './DigitalLink'
-export type { default as Digital } from './Digital'
export type { default as Discount } from './Discount'
export type { default as Fee } from './Fee'
export type { default as Fulfillment } from './Fulfillment'
diff --git a/packages/sdk/src/types/index.ts b/packages/sdk/src/types/index.ts
index 182b45b149..82d3d7dad7 100644
--- a/packages/sdk/src/types/index.ts
+++ b/packages/sdk/src/types/index.ts
@@ -22,7 +22,7 @@ export type {
CustomField,
DeliveryMethod,
DeliveryRate,
- Digital,
+ DigitalAsset,
DigitalLink,
Discount,
Fulfillment,
diff --git a/packages/sdk/src/zod/generated/Digital.ts b/packages/sdk/src/zod/generated/Digital.ts
deleted file mode 100644
index 359033df6d..0000000000
--- a/packages/sdk/src/zod/generated/Digital.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-// This file is auto-generated. Do not edit directly.
-import { z } from 'zod';
-
-export const DigitalSchema = z.object({
- id: z.string(),
- created_at: z.string(),
- updated_at: z.string(),
- variant_id: z.string().nullable(),
-});
-
-export type Digital = z.infer<typeof DigitalSchema>;
diff --git a/packages/sdk/src/zod/generated/DigitalAsset.ts b/packages/sdk/src/zod/generated/DigitalAsset.ts
new file mode 100644
index 0000000000..18918204b2
--- /dev/null
+++ b/packages/sdk/src/zod/generated/DigitalAsset.ts
@@ -0,0 +1,11 @@
+// This file is auto-generated. Do not edit directly.
+import { z } from 'zod';
+
+export const DigitalAssetSchema = z.object({
+ id: z.string(),
+ variant_id: z.string().nullable(),
+ filename: z.string().nullable(),
+ content_type: z.string().nullable(),
+});
+
+export type DigitalAsset = z.infer<typeof DigitalAssetSchema>;
diff --git a/packages/sdk/src/zod/generated/DigitalLink.ts b/packages/sdk/src/zod/generated/DigitalLink.ts
index ce12ac2e45..d073f48289 100644
--- a/packages/sdk/src/zod/generated/DigitalLink.ts
+++ b/packages/sdk/src/zod/generated/DigitalLink.ts
@@ -7,6 +7,7 @@ export const DigitalLinkSchema = z.object({
filename: z.string(),
content_type: z.string(),
download_url: z.string(),
+ expires_at: z.string().nullable(),
authorizable: z.boolean(),
expired: z.boolean(),
access_limit_exceeded: z.boolean(),
diff --git a/packages/sdk/src/zod/generated/index.ts b/packages/sdk/src/zod/generated/index.ts
index e9f92a05a8..9e59b5ea15 100644
--- a/packages/sdk/src/zod/generated/index.ts
+++ b/packages/sdk/src/zod/generated/index.ts
@@ -22,7 +22,7 @@ export { DeliveryMethodSchema, type DeliveryMethod } from './DeliveryMethod';
export { DeliveryRateSchema, type DeliveryRate } from './DeliveryRate';
export { DeliveryZoneSchema, type DeliveryZone } from './DeliveryZone';
export { DeliveryZoneMemberSchema, type DeliveryZoneMember } from './DeliveryZoneMember';
-export { DigitalSchema, type Digital } from './Digital';
+export { DigitalAssetSchema, type DigitalAsset } from './DigitalAsset';
export { DigitalLinkSchema, type DigitalLink } from './DigitalLink';
export { DiscountSchema, type Discount } from './Discount';
export { FeeSchema, type Fee } from './Fee';
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/jwt_authentication.rb b/spree/api/app/controllers/concerns/spree/api/v3/jwt_authentication.rb
index 00c64ccc16..e82e586ff6 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/jwt_authentication.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/jwt_authentication.rb
@@ -73,7 +73,7 @@ module Spree
return header.split(' ').last if header.present? && header.start_with?('Bearer ')
# Restricted fallback: only for digital download endpoints
- params[:token] if controller_name == 'digitals'
+ params[:token] if controller_name == 'digital_links'
end
def decode_jwt(token)
diff --git a/spree/api/app/controllers/spree/api/v3/store/digital_links_controller.rb b/spree/api/app/controllers/spree/api/v3/store/digital_links_controller.rb
new file mode 100644
index 0000000000..f5408e5775
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/store/digital_links_controller.rb
@@ -0,0 +1,68 @@
+module Spree
+ module Api
+ module V3
+ module Store
+ class DigitalLinksController < Store::BaseController
+ # Lets the Disk service build absolute URLs from the current request;
+ # remote services (S3 et al.) sign without it.
+ include ActiveStorage::SetCurrent
+
+ allow_guest_storefront_access!
+ skip_before_action :authenticate_api_key!
+ before_action :set_resource
+
+ # GET /api/v3/store/digital_links/:token
+ #
+ # Redirects to a short-lived signed storage URL rather than streaming
+ # the file, so a large download does not hold a web worker open for
+ # its duration.
+ def show
+ if (download_url = authorized_download_url)
+ @resource.publish_event('digital_link.downloaded')
+
+ redirect_to download_url, allow_other_host: true
+ else
+ render_error(
+ code: ERROR_CODES[:digital_link_expired],
+ message: 'Download link expired or invalid',
+ status: :forbidden
+ )
+ end
+ end
+
+ private
+
+ # Everything that can refuse the download is settled before the click
+ # is spent, so a missing file never burns a customer's allowance.
+ def authorized_download_url
+ return unless @resource.digital_asset.downloadable?
+
+ window = signed_url_window
+ return if window <= 0
+ return unless @resource.authorize!
+
+ @resource.digital_asset.download_url(expires_in: window)
+ end
+
+ # The signed URL is a bearer credential, so it must never outlive the
+ # link that authorized it — otherwise an expired link keeps handing
+ # out working URLs for the rest of the store's window.
+ def signed_url_window
+ window = current_store.preferred_digital_asset_link_expire_time.seconds
+ return window unless (expiry = @resource.expires_at)
+
+ [window, expiry - Time.current].min
+ end
+
+ def set_resource
+ @resource = digital_link_scope.find_by!(token: params[:token])
+ end
+
+ def digital_link_scope
+ current_store.digital_links
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/store/digitals_controller.rb b/spree/api/app/controllers/spree/api/v3/store/digitals_controller.rb
deleted file mode 100644
index b657141bec..0000000000
--- a/spree/api/app/controllers/spree/api/v3/store/digitals_controller.rb
+++ /dev/null
@@ -1,51 +0,0 @@
-module Spree
- module Api
- module V3
- module Store
- class DigitalsController < Store::BaseController
- allow_guest_storefront_access!
- skip_before_action :authenticate_api_key!
- before_action :set_resource
-
- # GET /api/v3/store/digitals/:token
- def show
- if @resource.authorize!
- send_data @resource.digital.attachment.download,
- filename: @resource.digital.attachment.filename.to_s,
- type: @resource.digital.attachment.content_type
- else
- render_error(
- code: ERROR_CODES[:digital_link_expired],
- message: 'Download link expired or invalid',
- status: :forbidden
- )
- end
- end
-
- private
-
- # The download token is the request's credential and selects the
- # store (tokens are globally unique via has_secure_token) — no
- # publishable key accompanies emailed download links, so there is
- # no other credential to derive store context from. Assigned, not
- # memoized-into: earlier prepended callbacks resolve current_store
- # before the resource exists (to the key's store, when one is
- # sent), and the link's own store must overwrite that.
- def set_resource
- @resource = digital_link_scope.find_by!(token: params[:token])
- @current_store = @resource.order.store
- Spree::Current.store = @current_store
- end
-
- def digital_link_scope
- Spree::DigitalLink
- end
-
- def current_store
- @current_store ||= super
- end
- end
- end
- end
- end
-end
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
new file mode 100644
index 0000000000..b729829391
--- /dev/null
+++ b/spree/api/app/serializers/spree/api/v3/admin/digital_asset_serializer.rb
@@ -0,0 +1,33 @@
+# frozen_string_literal: true
+
+module Spree
+ module Api
+ module V3
+ module Admin
+ class DigitalAssetSerializer < V3::DigitalAssetSerializer
+ typelize byte_size: [:number, nullable: true],
+ authorized_clicks: [:number, nullable: true],
+ authorized_days: [:number, nullable: true],
+ effective_authorized_clicks: :number,
+ effective_authorized_days: :number
+
+ attributes :authorized_clicks, :authorized_days, :byte_size
+ attributes created_at: :iso8601, updated_at: :iso8601
+
+ # The limits actually applied, after the store-settings fallback. The
+ # request's store answers it — an admin request always carries one;
+ # the asset's own store covers serialization outside a request.
+ attribute :effective_authorized_clicks do |digital_asset, params|
+ store = params&.dig(:store) || Spree::Current.store || digital_asset.store
+ digital_asset.effective_authorized_clicks(store)
+ end
+
+ attribute :effective_authorized_days do |digital_asset, params|
+ store = params&.dig(:store) || Spree::Current.store || digital_asset.store
+ digital_asset.effective_authorized_days(store)
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/digital_asset_serializer.rb b/spree/api/app/serializers/spree/api/v3/digital_asset_serializer.rb
new file mode 100644
index 0000000000..6d1cd1481f
--- /dev/null
+++ b/spree/api/app/serializers/spree/api/v3/digital_asset_serializer.rb
@@ -0,0 +1,23 @@
+# frozen_string_literal: true
+
+module Spree
+ module Api
+ module V3
+ class DigitalAssetSerializer < BaseSerializer
+ typelize variant_id: [:string, nullable: true],
+ filename: [:string, nullable: true],
+ content_type: [:string, nullable: true]
+
+ attribute :variant_id do |digital_asset|
+ digital_asset.variant&.prefixed_id
+ end
+
+ attribute :filename do |digital_asset|
+ digital_asset.filename&.to_s
+ end
+
+ attributes :content_type
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/digital_link_serializer.rb b/spree/api/app/serializers/spree/api/v3/digital_link_serializer.rb
index f72122fb38..107cf9e53d 100644
--- a/spree/api/app/serializers/spree/api/v3/digital_link_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/digital_link_serializer.rb
@@ -3,13 +3,17 @@ module Spree
module V3
class DigitalLinkSerializer < BaseSerializer
typelize access_counter: :number, filename: :string, content_type: :string,
- download_url: :string,
+ download_url: :string, expires_at: [:string, nullable: true],
authorizable: :boolean, expired: :boolean, access_limit_exceeded: :boolean
attributes :access_counter, :filename, :content_type
attribute :download_url do |digital_link|
- Spree::Core::Engine.routes.url_helpers.api_v3_store_digital_download_path(token: digital_link.token)
+ Spree::Core::Engine.routes.url_helpers.api_v3_store_digital_link_download_path(token: digital_link.token)
+ end
+
+ attribute :expires_at do |digital_link|
+ digital_link.expires_at&.iso8601
end
attribute :authorizable do |digital_link|
diff --git a/spree/api/app/serializers/spree/api/v3/digital_serializer.rb b/spree/api/app/serializers/spree/api/v3/digital_serializer.rb
deleted file mode 100644
index e3e1ad4fac..0000000000
--- a/spree/api/app/serializers/spree/api/v3/digital_serializer.rb
+++ /dev/null
@@ -1,17 +0,0 @@
-# frozen_string_literal: true
-
-module Spree
- module Api
- module V3
- class DigitalSerializer < BaseSerializer
- typelize variant_id: [:string, nullable: true]
-
- attributes created_at: :iso8601, updated_at: :iso8601
-
- attribute :variant_id do |digital|
- digital.variant&.prefixed_id
- end
- end
- end
- end
-end
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index 45fbebc7eb..dd9bff0571 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -148,7 +148,9 @@ Spree::Core::Engine.add_routes do
# Digital Downloads
# Access via token in URL
- get 'digitals/:token', to: 'digitals#show', as: :digital_download
+ get 'digital_links/:token', to: 'digital_links#show', as: :digital_link_download
+ # Legacy path — emailed and bookmarked URLs outlive the rename. Removed in 6.1.
+ get 'digitals/:token', to: 'digital_links#show', as: :digital_download
# Data Feeds (public, no auth required)
resources :feeds, only: [:show], controller: 'data_feeds', param: :slug
diff --git a/spree/api/lib/spree/api/dependencies.rb b/spree/api/lib/spree/api/dependencies.rb
index a4f52fc9d9..971e913566 100644
--- a/spree/api/lib/spree/api/dependencies.rb
+++ b/spree/api/lib/spree/api/dependencies.rb
@@ -78,7 +78,7 @@ module Spree
claim_line_item_serializer: 'Spree::Api::V3::ClaimLineItemSerializer',
return_reason_serializer: 'Spree::Api::V3::ReturnReasonSerializer',
claim_reason_serializer: 'Spree::Api::V3::ClaimReasonSerializer',
- digital_serializer: 'Spree::Api::V3::DigitalSerializer',
+ digital_asset_serializer: 'Spree::Api::V3::DigitalAssetSerializer',
export_serializer: 'Spree::Api::V3::ExportSerializer',
gift_card_batch_serializer: 'Spree::Api::V3::GiftCardBatchSerializer',
import_serializer: 'Spree::Api::V3::ImportSerializer',
@@ -209,6 +209,7 @@ module Spree
admin_store_credit_serializer: 'Spree::Api::V3::Admin::StoreCreditSerializer',
admin_customer_group_serializer: 'Spree::Api::V3::Admin::CustomerGroupSerializer',
admin_payment_source_serializer: 'Spree::Api::V3::Admin::PaymentSourceSerializer',
+ admin_digital_asset_serializer: 'Spree::Api::V3::Admin::DigitalAssetSerializer',
admin_digital_link_serializer: 'Spree::Api::V3::Admin::DigitalLinkSerializer',
admin_store_serializer: 'Spree::Api::V3::Admin::StoreSerializer',
admin_setup_task_serializer: 'Spree::Api::V3::Admin::SetupTaskSerializer',
diff --git a/spree/api/spec/controllers/spree/api/v3/store/digital_links_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/digital_links_controller_spec.rb
new file mode 100644
index 0000000000..496d6d4a64
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/store/digital_links_controller_spec.rb
@@ -0,0 +1,155 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Store::DigitalLinksController, type: :controller do
+ render_views
+
+ include_context 'API v3 Store'
+
+ let(:order) { create(:order_with_line_items, store: store, customer: user) }
+ let(:line_item) { order.line_items.first }
+ let(:digital_asset) { create(:digital_asset, variant: line_item.variant) }
+ let!(:digital_link) { create(:digital_link, digital_asset: digital_asset, line_item: line_item) }
+
+ describe 'GET #show' do
+ it 'redirects to a download URL for a valid token' do
+ get :show, params: { token: digital_link.token }
+
+ expect(response).to have_http_status(:found)
+ expect(response.location).to be_present
+ end
+
+ it 'increments the access counter' do
+ expect {
+ get :show, params: { token: digital_link.token }
+ }.to change { digital_link.reload.access_counter }.by(1)
+ end
+
+ it 'publishes a downloaded event' do
+ expect_any_instance_of(Spree::DigitalLink).to receive(:publish_event).with('digital_link.downloaded')
+
+ get :show, params: { token: digital_link.token }
+ end
+
+ context 'when link is expired' do
+ before do
+ store.update!(
+ preferred_limit_digital_download_days: true,
+ preferred_digital_asset_authorized_days: 1
+ )
+ digital_link.update_column(:created_at, 2.days.ago)
+ end
+
+ it 'returns forbidden with digital_link_expired code' do
+ get :show, params: { token: digital_link.token }
+
+ expect(response).to have_http_status(:forbidden)
+ expect(json_response['error']['code']).to eq('digital_link_expired')
+ expect(json_response['error']['message']).to be_present
+ end
+ end
+
+ context 'when download limit is exceeded' do
+ before do
+ store.update!(
+ preferred_limit_digital_download_count: true,
+ preferred_digital_asset_authorized_clicks: 3
+ )
+ digital_link.update_column(:access_counter, 3)
+ end
+
+ it 'returns forbidden with digital_link_expired code' do
+ get :show, params: { token: digital_link.token }
+
+ expect(response).to have_http_status(:forbidden)
+ expect(json_response['error']['code']).to eq('digital_link_expired')
+ end
+ end
+
+ # The per-asset override wins over the store setting, so an asset marked
+ # freely re-downloadable stays available past the store's click cap.
+ context 'when the asset overrides the store click limit' do
+ before do
+ store.update!(
+ preferred_limit_digital_download_count: true,
+ preferred_digital_asset_authorized_clicks: 3
+ )
+ digital_asset.update!(authorized_clicks: 10)
+ digital_link.update_column(:access_counter, 3)
+ end
+
+ it 'still authorizes the download' do
+ get :show, params: { token: digital_link.token }
+
+ expect(response).to have_http_status(:found)
+ end
+ end
+
+ # The signed URL is a bearer credential; it must not outlive the link.
+ context 'when the link lapses sooner than the store download window' do
+ before do
+ store.update!(
+ preferred_limit_digital_download_days: true,
+ preferred_digital_asset_authorized_days: 1,
+ preferred_digital_asset_link_expire_time: 3600
+ )
+ end
+
+ it 'clamps the signed URL to the link expiry' do
+ digital_link.update_column(:created_at, (1.day - 30.seconds).ago)
+
+ expect_any_instance_of(Spree::DigitalAsset).to receive(:download_url) do |_asset, expires_in:|
+ expect(expires_in).to be <= 30.seconds
+ 'https://storage.example.com/signed'
+ end
+
+ get :show, params: { token: digital_link.token }
+
+ expect(response).to have_http_status(:found)
+ end
+ end
+
+ context 'when the asset has no file to serve' do
+ before { digital_asset.attachment.purge }
+
+ it 'returns forbidden without spending a download allowance' do
+ expect {
+ get :show, params: { token: digital_link.token }
+ }.not_to change { digital_link.reload.access_counter }
+
+ expect(response).to have_http_status(:forbidden)
+ end
+ end
+
+ context 'with invalid token' do
+ it 'returns not found' do
+ get :show, params: { token: 'invalid_token' }
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ context 'with token from another store' do
+ let(:other_store) { create(:store) }
+ let(:other_order) { create(:order_with_line_items, store: other_store) }
+ let(:other_line_item) { other_order.line_items.first }
+ let(:other_digital_asset) { create(:digital_asset, variant: other_line_item.variant) }
+ let(:other_digital_link) { create(:digital_link, digital_asset: other_digital_asset, line_item: other_line_item) }
+
+ it 'returns not found' do
+ get :show, params: { token: other_digital_link.token }
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ context 'without API key' do
+ before { request.headers['X-Spree-Api-Key'] = nil }
+
+ it 'still allows access (token is the authentication)' do
+ get :show, params: { token: digital_link.token }
+
+ expect(response).to have_http_status(:found)
+ end
+ end
+ end
+end
diff --git a/spree/api/spec/controllers/spree/api/v3/store/digitals_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/digitals_controller_spec.rb
deleted file mode 100644
index 3d9d50ca44..0000000000
--- a/spree/api/spec/controllers/spree/api/v3/store/digitals_controller_spec.rb
+++ /dev/null
@@ -1,101 +0,0 @@
-require 'spec_helper'
-
-RSpec.describe Spree::Api::V3::Store::DigitalsController, type: :controller do
- render_views
-
- include_context 'API v3 Store'
-
- let(:order) { create(:order_with_line_items, store: store, customer: user) }
- let(:line_item) { order.line_items.first }
- let(:digital) { create(:digital, variant: line_item.variant) }
- let!(:digital_link) { create(:digital_link, digital: digital, line_item: line_item) }
-
- describe 'GET #show' do
- it 'sends the file for a valid token' do
- get :show, params: { token: digital_link.token }
-
- expect(response).to have_http_status(:ok)
- expect(response.headers['Content-Disposition']).to include('thinking-cat.jpg')
- end
-
- it 'increments the access counter' do
- expect {
- get :show, params: { token: digital_link.token }
- }.to change { digital_link.reload.access_counter }.by(1)
- end
-
- context 'when link is expired' do
- before do
- store.update!(
- preferred_limit_digital_download_days: true,
- preferred_digital_asset_authorized_days: 1
- )
- digital_link.update_column(:created_at, 2.days.ago)
- end
-
- it 'returns forbidden with digital_link_expired code' do
- get :show, params: { token: digital_link.token }
-
- expect(response).to have_http_status(:forbidden)
- expect(json_response['error']['code']).to eq('digital_link_expired')
- expect(json_response['error']['message']).to be_present
- end
- end
-
- context 'when download limit is exceeded' do
- before do
- store.update!(
- preferred_limit_digital_download_count: true,
- preferred_digital_asset_authorized_clicks: 3
- )
- digital_link.update_column(:access_counter, 3)
- end
-
- it 'returns forbidden with digital_link_expired code' do
- get :show, params: { token: digital_link.token }
-
- expect(response).to have_http_status(:forbidden)
- expect(json_response['error']['code']).to eq('digital_link_expired')
- end
- end
-
- context 'with invalid token' do
- it 'returns not found' do
- get :show, params: { token: 'invalid_token' }
-
- expect(response).to have_http_status(:not_found)
- end
- end
-
- context 'with token from another store' do
- let(:other_store) { create(:store) }
- let(:other_order) { create(:order_with_line_items, store: other_store) }
- let(:other_line_item) { other_order.line_items.first }
- let(:other_digital) { create(:digital, variant: other_line_item.variant) }
- let(:other_digital_link) { create(:digital_link, digital: other_digital, line_item: other_line_item) }
-
- # The globally unique token is the credential and selects the store —
- # download links arrive by email with no API key, so there is no other
- # credential to scope by (see KeyStoreContext).
- it "downloads the file under the link's own store context" do
- get :show, params: { token: other_digital_link.token }
-
- expect(response).to have_http_status(:ok)
- # Even when a publishable key of another store accompanies the
- # request, the link's store wins for the download context. Asserted
- # via the ivar because the shared context stubs current_store itself.
- expect(controller.instance_variable_get(:@current_store)).to eq(other_store)
- end
- end
-
- context 'without API key' do
- before { request.headers['X-Spree-Api-Key'] = nil }
-
- it 'still allows access (token is the authentication)' do
- get :show, params: { token: digital_link.token }
-
- expect(response).to have_http_status(:ok)
- end
- end
- end
-end
diff --git a/spree/api/spec/integration/spree/api/v3/store/digitals_spec.rb b/spree/api/spec/integration/spree/api/v3/store/digital_links_spec.rb
similarity index 68%
rename from spree/api/spec/integration/spree/api/v3/store/digitals_spec.rb
rename to spree/api/spec/integration/spree/api/v3/store/digital_links_spec.rb
index a44674197d..a2b41c044e 100644
--- a/spree/api/spec/integration/spree/api/v3/store/digitals_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/store/digital_links_spec.rb
@@ -2,38 +2,39 @@
require 'swagger_helper'
-RSpec.describe 'Digitals API', type: :request, swagger_doc: 'api-reference/store.yaml' do
+RSpec.describe 'Digital Links API', type: :request, swagger_doc: 'api-reference/store.yaml' do
include_context 'API v3 Store'
let(:product) { create(:product) }
let(:order) { create(:order_with_line_items, store: store, customer: user, line_items_attributes: [{ variant: product.default_variant, quantity: 1 }]) }
let(:line_item) { order.line_items.first }
- let(:digital) { create(:digital, variant: line_item.variant) }
- let!(:digital_link) { create(:digital_link, digital: digital, line_item: line_item) }
+ let(:digital_asset) { create(:digital_asset, variant: line_item.variant) }
+ let!(:digital_link) { create(:digital_link, digital_asset: digital_asset, line_item: line_item) }
- path '/api/v3/store/digitals/{token}' do
+ path '/api/v3/store/digital_links/{token}' do
get 'Download a digital product' do
- tags 'Digitals'
- produces 'application/octet-stream', 'application/json'
+ tags 'Digital Links'
+ produces 'application/json'
description <<~DESC
Downloads a digital product file using the digital link token.
The token is provided via the `download_url` field on digital links
returned with order line items. No API key or authentication required —
the token itself grants access.
- Each download increments the access counter. Downloads may be limited by
- store settings (number of downloads and/or time-based expiration).
+
+ Responds with a redirect to a short-lived download URL; follow it to
+ fetch the file. Each download increments the access counter. Downloads
+ may be limited by the asset's own settings, falling back to the store's
+ (number of downloads and/or time-based expiration).
DESC
parameter name: :token, in: :path, type: :string, required: true,
description: 'Digital link token'
- response '200', 'file downloaded' do
+ response '302', 'redirect to the file download' do
let(:token) { digital_link.token }
- produces 'application/octet-stream'
-
run_test! do |response|
- expect(response.headers['Content-Disposition']).to include('thinking-cat.jpg')
+ expect(response.headers['Location']).to be_present
expect(digital_link.reload.access_counter).to eq(1)
end
end
diff --git a/spree/api/spec/routing/spree/api/v3/store/digital_links_routing_spec.rb b/spree/api/spec/routing/spree/api/v3/store/digital_links_routing_spec.rb
new file mode 100644
index 0000000000..01bb935f4e
--- /dev/null
+++ b/spree/api/spec/routing/spree/api/v3/store/digital_links_routing_spec.rb
@@ -0,0 +1,25 @@
+require 'spec_helper'
+
+# Emailed and bookmarked download URLs outlive the 6.0 rename, so both paths
+# must reach the controller until the legacy one is dropped in 6.1.
+RSpec.describe 'digital link download routing', type: :routing do
+ routes { Spree::Core::Engine.routes }
+
+ it 'routes the canonical digital_links path' do
+ expect(get: '/api/v3/store/digital_links/abc123').to route_to(
+ controller: 'spree/api/v3/store/digital_links',
+ action: 'show',
+ token: 'abc123',
+ format: 'json'
+ )
+ end
+
+ it 'routes the legacy digitals path to the same action' do
+ expect(get: '/api/v3/store/digitals/abc123').to route_to(
+ controller: 'spree/api/v3/store/digital_links',
+ action: 'show',
+ token: 'abc123',
+ format: 'json'
+ )
+ end
+end
diff --git a/spree/api/spec/serializers/spree/api/v3/digital_asset_serializer_spec.rb b/spree/api/spec/serializers/spree/api/v3/digital_asset_serializer_spec.rb
new file mode 100644
index 0000000000..bcd677db17
--- /dev/null
+++ b/spree/api/spec/serializers/spree/api/v3/digital_asset_serializer_spec.rb
@@ -0,0 +1,48 @@
+# frozen_string_literal: true
+
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::DigitalAssetSerializer do
+ let(:store) { @default_store }
+ let(:digital_asset) { create(:digital_asset) }
+ let(:base_params) { { store: store, currency: 'USD' } }
+
+ subject { described_class.new(digital_asset, params: base_params).to_h }
+
+ it 'includes all expected attributes' do
+ expect(subject.keys).to match_array(%w[
+ id variant_id filename content_type
+ ])
+ end
+
+ it 'returns the prefixed id' do
+ expect(subject['id']).to eq(digital_asset.prefixed_id)
+ end
+
+ it 'returns prefixed variant_id' do
+ expect(subject['variant_id']).to eq(digital_asset.variant.prefixed_id)
+ end
+
+ it 'returns the attachment filename' do
+ expect(subject['filename']).to eq('thinking-cat.jpg')
+ end
+
+ describe Spree::Api::V3::Admin::DigitalAssetSerializer do
+ subject { described_class.new(digital_asset, params: base_params).to_h }
+
+ it 'adds back-office attributes' do
+ expect(subject.keys).to include(
+ 'byte_size', 'authorized_clicks', 'authorized_days',
+ 'effective_authorized_clicks', 'effective_authorized_days',
+ 'created_at', 'updated_at'
+ )
+ end
+
+ it 'exposes the store fallback in the effective limits' do
+ store.update!(preferred_digital_asset_authorized_clicks: 5)
+
+ expect(subject['authorized_clicks']).to be_nil
+ expect(subject['effective_authorized_clicks']).to eq(5)
+ end
+ end
+end
diff --git a/spree/api/spec/serializers/spree/api/v3/digital_serializer_spec.rb b/spree/api/spec/serializers/spree/api/v3/digital_serializer_spec.rb
deleted file mode 100644
index 248d36338e..0000000000
--- a/spree/api/spec/serializers/spree/api/v3/digital_serializer_spec.rb
+++ /dev/null
@@ -1,25 +0,0 @@
-# frozen_string_literal: true
-
-require 'spec_helper'
-
-RSpec.describe Spree::Api::V3::DigitalSerializer do
- let(:store) { @default_store }
- let(:digital) { create(:digital) }
- let(:base_params) { { store: store, currency: 'USD' } }
-
- subject { described_class.new(digital, params: base_params).to_h }
-
- it 'includes all expected attributes' do
- expect(subject.keys).to match_array(%w[
- id variant_id created_at updated_at
- ])
- end
-
- it 'returns the prefixed id' do
- expect(subject['id']).to eq(digital.prefixed_id)
- end
-
- it 'returns prefixed variant_id' do
- expect(subject['variant_id']).to eq(digital.variant.prefixed_id)
- end
-end
diff --git a/spree/core/app/models/spree/digital.rb b/spree/core/app/models/spree/digital.rb
index ebcafe63c3..f3490a9bfb 100644
--- a/spree/core/app/models/spree/digital.rb
+++ b/spree/core/app/models/spree/digital.rb
@@ -1,17 +1,14 @@
-module Spree
- class Digital < Spree.base_class
- has_prefix_id :dig
-
- publishes_lifecycle_events
-
- belongs_to :variant
- has_many :digital_links, dependent: :destroy
+# frozen_string_literal: true
- has_one_attached :attachment, service: Spree.private_storage_service_name
-
- validates :attachment, attached: true
-
- delegate :product, to: :variant
- delegate :filename, :content_type, to: :attachment
- end
+module Spree
+ # Deprecation alias for Spree::DigitalAsset, renamed from Spree::Digital in
+ # 6.0. Retained for one release; removed in 6.1.
+ #
+ # A plain constant alias rather than a DeprecatedConstantProxy: the proxy
+ # would name the calling site, but it fails `is_a?`/`===` checks, so legacy
+ # code branching on the old constant would silently take the wrong path.
+ #
+ # The underlying class, table (spree_digital_assets), prefix (dig) and
+ # model_name are all Spree::DigitalAsset; only the constant differs.
+ Digital = DigitalAsset
end
diff --git a/spree/core/app/models/spree/digital_asset.rb b/spree/core/app/models/spree/digital_asset.rb
new file mode 100644
index 0000000000..2e5c7a4f33
--- /dev/null
+++ b/spree/core/app/models/spree/digital_asset.rb
@@ -0,0 +1,83 @@
+module Spree
+ class DigitalAsset < Spree.base_class
+ has_prefix_id :dig
+
+ publishes_lifecycle_events
+
+ belongs_to :variant, class_name: 'Spree::Variant'
+ has_many :digital_links, class_name: 'Spree::DigitalLink', dependent: :destroy
+
+ has_one_attached :attachment, service: Spree.private_storage_service_name
+
+ validates :attachment, attached: true
+ validates :authorized_clicks, numericality: { only_integer: true, greater_than: 0 }, allow_nil: true
+ validates :authorized_days, numericality: { only_integer: true, greater_than: 0 }, allow_nil: true
+
+ delegate :product, to: :variant
+ delegate :filename, :content_type, :byte_size, to: :attachment
+
+ # Download allowances fall back to the owning store's settings when the
+ # asset leaves them blank, so a catalog can mix evergreen files with
+ # time-limited ones without changing the store default.
+ #
+ # The store is passed in by the caller, which already holds it — resolving
+ # it here would walk variant → product → store for every link checked.
+ #
+ # @param store [Spree::Store]
+ # @return [Integer]
+ def effective_authorized_clicks(store = self.store)
+ authorized_clicks || store.preferred_digital_asset_authorized_clicks
+ end
+
+ # @param store [Spree::Store]
+ # @return [Integer]
+ def effective_authorized_days(store = self.store)
+ authorized_days || store.preferred_digital_asset_authorized_days
+ end
+
+ # @return [Spree::Store] the store this asset's product belongs to
+ def store
+ product.store
+ end
+
+ # Where the customer is sent to fetch the file. Owning this here keeps
+ # callers out of the storage layer, so asset kinds that are not uploaded
+ # files can answer it differently.
+ #
+ # @return [Boolean] whether there is anything to hand to a customer
+ def downloadable?
+ attachment.attached?
+ end
+
+ # @param expires_in [ActiveSupport::Duration] lifetime of the signed URL
+ # @return [String, nil] nil when there is nothing to download
+ def download_url(expires_in:)
+ return unless downloadable?
+
+ attachment.url(expires_in: expires_in, disposition: :attachment)
+ end
+
+ private
+
+ # The legacy digital.* events are dual-emitted for one release
+ # (webhook contract bridge — removed in 6.1).
+ def publish_create_event
+ publish_event('digital.created')
+ super
+ end
+
+ # Cannot call super like its siblings: touch_only_update? clears its flags
+ # when read, so the guard must run exactly once for both event names.
+ def publish_update_event
+ return if touch_only_update?
+
+ publish_event('digital.updated')
+ publish_event("#{event_prefix}.updated")
+ end
+
+ def publish_delete_event
+ publish_event('digital.deleted', @_pre_destroy_payload || event_payload)
+ super
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/digital_link.rb b/spree/core/app/models/spree/digital_link.rb
index 23c829b16f..3530775b80 100644
--- a/spree/core/app/models/spree/digital_link.rb
+++ b/spree/core/app/models/spree/digital_link.rb
@@ -14,30 +14,39 @@ module Spree
include Spree::Security::DigitalLinks
end
- belongs_to :digital
- belongs_to :line_item
+ belongs_to :digital_asset, class_name: 'Spree::DigitalAsset'
+ belongs_to :line_item, class_name: 'Spree::LineItem'
before_validation :set_defaults, on: :create
validates :access_counter, numericality: { greater_than_or_equal_to: 0 }
- delegate :filename, :content_type, to: :digital
+ delegate :filename, :content_type, to: :digital_asset
delegate :order, to: :line_item
+ # @deprecated Use {#digital_asset}; removed in 6.1.
+ def digital
+ Spree::Deprecation.warn('Spree::DigitalLink#digital is deprecated and will be removed in Spree 6.1. Use #digital_asset instead.')
+ digital_asset
+ end
+
+ # @deprecated Use {#digital_asset=}; removed in 6.1.
+ def digital=(value)
+ Spree::Deprecation.warn('Spree::DigitalLink#digital= is deprecated and will be removed in Spree 6.1. Use #digital_asset= instead.')
+ self.digital_asset = value
+ end
+
def authorizable?
!(expired? || access_limit_exceeded?)
end
def expired?
- if line_item.order.store.preferred_limit_digital_download_days
- created_at <= line_item.order.store.preferred_digital_asset_authorized_days.day.ago
- else
- false
- end
+ expiry = expires_at
+ expiry.present? && expiry <= Time.current
end
def access_limit_exceeded?
- if line_item.order.store.preferred_limit_digital_download_count
- access_counter >= line_item.order.store.preferred_digital_asset_authorized_clicks
+ if store.preferred_limit_digital_download_count
+ access_counter >= digital_asset.effective_authorized_clicks(store)
else
false
end
@@ -63,8 +72,21 @@ module Spree
save!
end
+ # @return [Time, nil] when access lapses, or nil when day limits are off
+ def expires_at
+ return unless store.preferred_limit_digital_download_days
+
+ created_at + digital_asset.effective_authorized_days(store).days
+ end
+
private
+ # The order's store is authoritative for both the limit flags and, passed
+ # into the asset, the limit values — so one store answers the whole check.
+ def store
+ @store ||= line_item.order.store
+ end
+
def set_defaults
self.access_counter ||= 0
end
diff --git a/spree/core/app/models/spree/fulfillment_provider/digital.rb b/spree/core/app/models/spree/fulfillment_provider/digital.rb
index cdc4c252c5..a594f44276 100644
--- a/spree/core/app/models/spree/fulfillment_provider/digital.rb
+++ b/spree/core/app/models/spree/fulfillment_provider/digital.rb
@@ -28,14 +28,14 @@ module Spree
true
end
- # Tops the line item up to one link per digital per unit of quantity.
+ # Tops the line item up to one link per asset per unit of quantity.
# Also used at order completion for physical items carrying digital
- # assets (e.g. vinyl + download code) that ship through other providers.
+ # assets (e.g. a manual with a device) that ship through other providers.
def ensure_links_for(line_item)
- line_item.variant.digitals.each do |digital|
- existing = line_item.digital_links.where(digital: digital).count
+ line_item.variant.digital_assets.each do |digital_asset|
+ existing = line_item.digital_links.where(digital_asset: digital_asset).count
(line_item.quantity - existing).times do
- line_item.digital_links.create!(digital: digital)
+ line_item.digital_links.create!(digital_asset: digital_asset)
end
end
end
diff --git a/spree/core/app/models/spree/line_item.rb b/spree/core/app/models/spree/line_item.rb
index dbb26b785c..4a890f0297 100644
--- a/spree/core/app/models/spree/line_item.rb
+++ b/spree/core/app/models/spree/line_item.rb
@@ -409,8 +409,8 @@ module Spree
# itself returns early unless the order is completed.
#
# No digitality gate: digital items get fulfillment items too (the
- # Digital provider issues one link per unit), and stock-limited digitals
- # — licences, seats, tickets — must decrement like anything else.
+ # Digital provider issues one link per unit), and stock-limited digital
+ # items — licences, seats, tickets — must decrement like anything else.
# Tracking is decided per variant by should_track_inventory?.
def update_inventory
if (saved_changes? || target_fulfillment.present?) && order.present?
diff --git a/spree/core/app/models/spree/product.rb b/spree/core/app/models/spree/product.rb
index 753df47627..5905853c18 100644
--- a/spree/core/app/models/spree/product.rb
+++ b/spree/core/app/models/spree/product.rb
@@ -224,7 +224,8 @@ module Spree
has_many :option_value_variants, class_name: 'Spree::OptionValueVariant', through: :variants
has_many :option_values, class_name: 'Spree::OptionValue', through: :variants
- has_many :digitals, through: :variants
+ has_many :digital_assets, through: :variants, class_name: 'Spree::DigitalAsset'
+ has_many :digitals, through: :variants, class_name: 'Spree::DigitalAsset', source: :digital_assets, deprecated: true
after_initialize :assign_default_tax_category
# The type's profile is a creation-time template: stamped here, never
diff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rb
index bed5b0d9dc..9368302b46 100644
--- a/spree/core/app/models/spree/store.rb
+++ b/spree/core/app/models/spree/store.rb
@@ -265,6 +265,10 @@ module Spree
end
validates :preferred_digital_asset_authorized_clicks, numericality: { only_integer: true, greater_than: 0 }
validates :preferred_digital_asset_authorized_days, numericality: { only_integer: true, greater_than: 0 }
+ # Sized for starting a transfer, not for keeping the file reachable — the
+ # signed URL it governs is a bearer credential.
+ validates :preferred_digital_asset_link_expire_time,
+ numericality: { only_integer: true, greater_than: 0, less_than_or_equal_to: 1.hour.to_i }
validates :preferred_stock_reservation_ttl_minutes, numericality: { only_integer: true, greater_than: 0 }
# A fraction, not a percentage: 0.21 is 21%. Bounded because the value is
# multiplied straight into what a seller is charged, so a negative would
diff --git a/spree/core/app/models/spree/variant.rb b/spree/core/app/models/spree/variant.rb
index b38a6f37c9..541551d9ed 100644
--- a/spree/core/app/models/spree/variant.rb
+++ b/spree/core/app/models/spree/variant.rb
@@ -79,7 +79,8 @@ module Spree
has_many :wished_items, dependent: :destroy
- has_many :digitals
+ has_many :digital_assets, class_name: 'Spree::DigitalAsset', dependent: :destroy
+ has_many :digitals, class_name: 'Spree::DigitalAsset', deprecated: true
before_validation :set_cost_currency
before_validation :apply_pending_options, if: :pending_options?
@@ -177,7 +178,7 @@ module Spree
joins(:option_values).where(Spree::OptionValue.table_name => { name: option_value, option_type_id: option_type_ids })
}
- scope :with_digital_assets, -> { joins(:digitals) }
+ scope :with_digital_assets, -> { joins(:digital_assets) }
# Free-text variant search: SKU, parent product name, and any
# option-value presentation (e.g. "Red", "XL"). The 3-char floor
@@ -916,7 +917,7 @@ module Spree
end
def with_digital_assets?
- digitals.any?
+ digital_assets.any?
end
private
diff --git a/spree/core/app/workflows/spree/orders/complete.rb b/spree/core/app/workflows/spree/orders/complete.rb
index 3bf6a2afec..7d39a839a0 100644
--- a/spree/core/app/workflows/spree/orders/complete.rb
+++ b/spree/core/app/workflows/spree/orders/complete.rb
@@ -129,7 +129,7 @@ module Spree
return unless order.with_digital_assets?
provider = Spree::FulfillmentProvider::Digital.new
- order.digital_line_items.where.not(id: @auto_fulfilled_line_item_ids).includes(variant: :digitals).each do |line_item|
+ order.digital_line_items.where.not(id: @auto_fulfilled_line_item_ids).includes(variant: :digital_assets).each do |line_item|
provider.ensure_links_for(line_item)
end
end
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index a50222f1cd..b5ee6ab54e 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -427,7 +427,7 @@ en:
spree/customer_group_user:
one: Customer Group User
other: Customer Group Users
- spree/digital:
+ spree/digital_asset:
one: Digital asset
other: Digital assets
spree/export:
diff --git a/spree/core/db/migrate/20260810000001_rename_digitals_to_digital_assets.rb b/spree/core/db/migrate/20260810000001_rename_digitals_to_digital_assets.rb
new file mode 100644
index 0000000000..2960dbf898
--- /dev/null
+++ b/spree/core/db/migrate/20260810000001_rename_digitals_to_digital_assets.rb
@@ -0,0 +1,19 @@
+class RenameDigitalsToDigitalAssets < ActiveRecord::Migration[8.1]
+ def up
+ rename_table :spree_digitals, :spree_digital_assets
+ rename_column :spree_digital_links, :digital_id, :digital_asset_id
+
+ # Null means "use the store's download settings". Per-asset values let one
+ # catalog mix evergreen re-downloadable files with time-limited ones.
+ add_column :spree_digital_assets, :authorized_clicks, :integer
+ add_column :spree_digital_assets, :authorized_days, :integer
+ end
+
+ def down
+ remove_column :spree_digital_assets, :authorized_days
+ remove_column :spree_digital_assets, :authorized_clicks
+
+ rename_column :spree_digital_links, :digital_asset_id, :digital_id
+ rename_table :spree_digital_assets, :spree_digitals
+ end
+end
diff --git a/spree/core/lib/spree/testing_support/factories/digital_asset_factory.rb b/spree/core/lib/spree/testing_support/factories/digital_asset_factory.rb
new file mode 100644
index 0000000000..c0c7bc6336
--- /dev/null
+++ b/spree/core/lib/spree/testing_support/factories/digital_asset_factory.rb
@@ -0,0 +1,13 @@
+FactoryBot.define do
+ factory :digital_asset, class: Spree::DigitalAsset do
+ after(:build) do |digital_asset|
+ digital_asset.attachment.attach(io: File.new("#{Spree::Core::Engine.root}/spec/fixtures/thinking-cat.jpg"),
+ filename: 'thinking-cat.jpg')
+ end
+
+ variant
+ end
+
+ # @deprecated Use :digital_asset; removed in 6.1.
+ factory :digital, parent: :digital_asset
+end
diff --git a/spree/core/lib/spree/testing_support/factories/digital_factory.rb b/spree/core/lib/spree/testing_support/factories/digital_factory.rb
deleted file mode 100644
index 5c534a544a..0000000000
--- a/spree/core/lib/spree/testing_support/factories/digital_factory.rb
+++ /dev/null
@@ -1,10 +0,0 @@
-FactoryBot.define do
- factory :digital, class: Spree::Digital do
- after(:build) do |digital|
- digital.attachment.attach(io: File.new("#{Spree::Core::Engine.root}/spec/fixtures/thinking-cat.jpg"),
- filename: 'thinking-cat.jpg')
- end
-
- variant
- end
-end
diff --git a/spree/core/lib/spree/testing_support/factories/digital_link_factory.rb b/spree/core/lib/spree/testing_support/factories/digital_link_factory.rb
index 9f9bd4c796..526feb96a1 100644
--- a/spree/core/lib/spree/testing_support/factories/digital_link_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/digital_link_factory.rb
@@ -1,6 +1,6 @@
FactoryBot.define do
factory :digital_link, class: Spree::DigitalLink do
- digital
+ digital_asset
line_item
end
end
diff --git a/spree/core/lib/spree/testing_support/lifecycle_events.rb b/spree/core/lib/spree/testing_support/lifecycle_events.rb
index 9f4a2dce5f..650204296b 100644
--- a/spree/core/lib/spree/testing_support/lifecycle_events.rb
+++ b/spree/core/lib/spree/testing_support/lifecycle_events.rb
@@ -40,8 +40,13 @@ shared_examples_for 'lifecycle events' do |factory: nil, event_prefix: nil|
describe "#{described_class.event_prefix}.deleted" do
it 'publishes deleted event when record is deleted' do
record = create(lifecycle_factory)
- expect(record).to receive(:publish_event).with("#{lifecycle_event_prefix}.deleted", kind_of(Hash))
allow(record).to receive(:publish_event).with(anything)
+ # Legacy delete twins (renamed models) also pass a payload — allow them
+ # without weakening the assertion below, which is declared last so it wins.
+ allow(record).to receive(:publish_event).with(
+ satisfy { |name| name != "#{lifecycle_event_prefix}.deleted" }, anything
+ )
+ expect(record).to receive(:publish_event).with("#{lifecycle_event_prefix}.deleted", kind_of(Hash))
record.destroy!
end
diff --git a/spree/core/spec/models/concerns/spree/purchase/digital_items_spec.rb b/spree/core/spec/models/concerns/spree/purchase/digital_items_spec.rb
index 159bab7674..ca49924467 100644
--- a/spree/core/spec/models/concerns/spree/purchase/digital_items_spec.rb
+++ b/spree/core/spec/models/concerns/spree/purchase/digital_items_spec.rb
@@ -4,7 +4,7 @@ RSpec.shared_examples 'a digital items host' do
let(:digital_product) { create(:digital_product) }
def digital_variant
- create(:variant, digitals: [create(:digital)], product: digital_product)
+ create(:variant, digitals: [create(:digital_asset)], product: digital_product)
end
context 'line_item analysis' do
@@ -27,7 +27,7 @@ RSpec.shared_examples 'a digital items host' do
it 'understands that not all products are digital' do
3.times { add_line_item(record, digital_variant, 1) }
- add_line_item(record, create(:variant, digitals: [create(:digital)]), 1) # analog product with assets
+ add_line_item(record, create(:variant, digitals: [create(:digital_asset)]), 1) # analog product with assets
expect(record.digital?).to be false
end
@@ -70,14 +70,14 @@ RSpec.shared_examples 'a digital items host' do
end
describe '#digital_links' do
- let(:digitals) { 2.times.map { create(:digital) } }
+ let(:digital_assets) { 2.times.map { create(:digital_asset) } }
it 'correctly loads the links' do
- digitals.each { |digital| add_line_item(record, create(:variant, digitals: [digital]), 1) }
+ digital_assets.each { |digital_asset| add_line_item(record, create(:variant, digital_assets: [digital_asset]), 1) }
add_line_item(record, create(:variant), 1)
links = record.digital_links
- links_from_digitals = digitals.map(&:reload).map(&:digital_links).flatten
+ links_from_digitals = digital_assets.map(&:reload).map(&:digital_links).flatten
expect(links.size).to eq(links_from_digitals.size)
links.each { |link| expect(links_from_digitals).to include(link) }
end
diff --git a/spree/core/spec/models/spree/calculator/shipping/digital_delivery_spec.rb b/spree/core/spec/models/spree/calculator/shipping/digital_delivery_spec.rb
index 2bc4fbfa7c..0f4bee3c3c 100644
--- a/spree/core/spec/models/spree/calculator/shipping/digital_delivery_spec.rb
+++ b/spree/core/spec/models/spree/calculator/shipping/digital_delivery_spec.rb
@@ -29,7 +29,7 @@ RSpec.describe Spree::Calculator::Shipping::DigitalDelivery do
let(:digital_order) do
order = create(:order)
- variants = 3.times.map { create(:variant, digitals: [FactoryBot.create(:digital)], product: digital_product) }
+ variants = 3.times.map { create(:variant, digitals: [FactoryBot.create(:digital_asset)], product: digital_product) }
package = Spree::Stock::Package.new(create(:stock_location), [])
variants.each do |v|
add_line_item_to_order(order, v, 1)
@@ -41,7 +41,7 @@ RSpec.describe Spree::Calculator::Shipping::DigitalDelivery do
let(:mixed_order) do
order = create(:order)
- variants = 2.times.map { create(:variant, digitals: [FactoryBot.create(:digital)], product: digital_product) }
+ variants = 2.times.map { create(:variant, digitals: [FactoryBot.create(:digital_asset)], product: digital_product) }
variants << create(:variant)
package = Spree::Stock::Package.new(create(:stock_location), [])
variants.each do |v|
diff --git a/spree/core/spec/models/spree/digital_asset_spec.rb b/spree/core/spec/models/spree/digital_asset_spec.rb
new file mode 100644
index 0000000000..91d1b1a57f
--- /dev/null
+++ b/spree/core/spec/models/spree/digital_asset_spec.rb
@@ -0,0 +1,106 @@
+require 'spec_helper'
+
+describe Spree::DigitalAsset, type: :model do
+ include ActionDispatch::TestProcess::FixtureFile
+
+ let(:file_upload) { fixture_file_upload(file_fixture('icon_256x256.png'), 'image/png') }
+ let(:variant) { create(:variant) }
+
+ it_behaves_like 'lifecycle events'
+
+ it 'validates presence of variant' do
+ expect(described_class.new(attachment: file_upload)).not_to be_valid
+ end
+
+ it 'validates presence of attachment' do
+ expect(described_class.new(variant: variant)).not_to be_valid
+ end
+
+ it 'validates presence of attachment and variant' do
+ expect(described_class.new(variant: variant, attachment: file_upload)).to be_valid
+ end
+
+ # The legacy names are the one-release webhook bridge; dropping them silently
+ # would break every subscriber written before the rename.
+ describe 'legacy digital.* events', events: true do
+ let(:digital_asset) { build(:digital_asset) }
+
+ it 'emits the legacy name alongside the canonical one on create' do
+ expect(digital_asset).to receive(:publish_event).with('digital.created')
+ expect(digital_asset).to receive(:publish_event).with('digital_asset.created')
+
+ digital_asset.save!
+ end
+
+ it 'emits the legacy name alongside the canonical one on update' do
+ digital_asset.save!
+ expect(digital_asset).to receive(:publish_event).with('digital.updated')
+ expect(digital_asset).to receive(:publish_event).with('digital_asset.updated')
+
+ Timecop.travel(1.minute.from_now) { digital_asset.update_attribute(:updated_at, Time.current) }
+ end
+
+ it 'does not emit either name on a bare touch' do
+ digital_asset.save!
+ expect(digital_asset).not_to receive(:publish_event).with('digital.updated')
+ expect(digital_asset).not_to receive(:publish_event).with('digital_asset.updated')
+ allow(digital_asset).to receive(:publish_event).with(anything)
+
+ digital_asset.touch
+ end
+
+ it 'emits the legacy name alongside the canonical one on destroy' do
+ digital_asset.save!
+ expect(digital_asset).to receive(:publish_event).with('digital.deleted', kind_of(Hash))
+ expect(digital_asset).to receive(:publish_event).with('digital_asset.deleted', kind_of(Hash))
+
+ digital_asset.destroy!
+ end
+ end
+
+ it 'rejects non-positive limit overrides' do
+ expect(described_class.new(variant: variant, attachment: file_upload, authorized_clicks: 0)).not_to be_valid
+ expect(described_class.new(variant: variant, attachment: file_upload, authorized_days: -1)).not_to be_valid
+ end
+
+ describe 'effective limits' do
+ let(:store) { @default_store }
+ let(:digital_asset) { create(:digital_asset) }
+
+ before do
+ store.update!(preferred_digital_asset_authorized_clicks: 5, preferred_digital_asset_authorized_days: 7)
+ end
+
+ it 'falls back to the store settings when the asset leaves them blank' do
+ expect(digital_asset.effective_authorized_clicks).to eq(5)
+ expect(digital_asset.effective_authorized_days).to eq(7)
+ end
+
+ it 'prefers the asset overrides when present' do
+ digital_asset.update!(authorized_clicks: 99, authorized_days: 365)
+
+ expect(digital_asset.effective_authorized_clicks).to eq(99)
+ expect(digital_asset.effective_authorized_days).to eq(365)
+ end
+
+ it 'overrides each limit independently' do
+ digital_asset.update!(authorized_clicks: 99)
+
+ expect(digital_asset.effective_authorized_clicks).to eq(99)
+ expect(digital_asset.effective_authorized_days).to eq(7)
+ end
+ end
+
+ # Replacing a file must never revoke access for people who already bought it.
+ describe 'replacing the attachment' do
+ let(:digital_asset) { create(:digital_asset) }
+ let!(:digital_link) { create(:digital_link, digital_asset: digital_asset) }
+
+ it 'keeps existing links pointing at the new file' do
+ digital_asset.attachment.attach(io: File.new(file_fixture('icon_256x256.png')), filename: 'replacement.png')
+
+ expect(digital_link.reload.digital_asset.filename.to_s).to eq('replacement.png')
+ expect(digital_link).to be_authorizable
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/digital_link_spec.rb b/spree/core/spec/models/spree/digital_link_spec.rb
index da325b735f..bf61840d8e 100644
--- a/spree/core/spec/models/spree/digital_link_spec.rb
+++ b/spree/core/spec/models/spree/digital_link_spec.rb
@@ -2,35 +2,35 @@ require 'spec_helper'
describe Spree::DigitalLink, type: :model do
let(:store) { @default_store }
- let(:digital) { create(:digital) }
- let(:variant) { digital.variant }
+ let(:digital_asset) { create(:digital_asset) }
+ let(:variant) { digital_asset.variant }
let(:line_item) { create(:line_item, variant: variant) }
it_behaves_like 'lifecycle events'
- it 'validates presence of digital and line_item' do
- expect(described_class.new(digital: digital, line_item: line_item)).to be_valid
+ it 'validates presence of digital_asset and line_item' do
+ expect(described_class.new(digital_asset: digital_asset, line_item: line_item)).to be_valid
end
it 'validates presence of line_item' do
- expect(described_class.new(digital: digital)).not_to be_valid
+ expect(described_class.new(digital_asset: digital_asset)).not_to be_valid
end
- it 'validates presence of digital' do
+ it 'validates presence of digital_asset' do
expect(described_class.new(line_item: line_item)).not_to be_valid
end
context 'validates access_counter' do
it 'validates access_counter numericality' do
- expect(described_class.new(digital: digital, line_item: line_item, access_counter: 'string')).not_to be_valid
+ expect(described_class.new(digital_asset: digital_asset, line_item: line_item, access_counter: 'string')).not_to be_valid
end
it 'validates access_counter 0 or greater' do
- expect(described_class.new(digital: digital, line_item: line_item, access_counter: -3)).not_to be_valid
+ expect(described_class.new(digital_asset: digital_asset, line_item: line_item, access_counter: -3)).not_to be_valid
end
it 'validates access_counter 0 is valid' do
- expect(described_class.new(digital: digital, line_item: line_item, access_counter: 0)).to be_valid
+ expect(described_class.new(digital_asset: digital_asset, line_item: line_item, access_counter: 0)).to be_valid
end
end
diff --git a/spree/core/spec/models/spree/digital_spec.rb b/spree/core/spec/models/spree/digital_spec.rb
deleted file mode 100644
index 0a5c2f31cf..0000000000
--- a/spree/core/spec/models/spree/digital_spec.rb
+++ /dev/null
@@ -1,22 +0,0 @@
-require 'spec_helper'
-
-describe Spree::Digital, type: :model do
- include ActionDispatch::TestProcess::FixtureFile
-
- let(:file_upload) { fixture_file_upload(file_fixture('icon_256x256.png'), 'image/png') }
- let(:variant) { create(:variant) }
-
- it_behaves_like 'lifecycle events'
-
- it 'validates presence of variant' do
- expect(described_class.new(attachment: file_upload)).not_to be_valid
- end
-
- it 'validates presence of attachment' do
- expect(described_class.new(variant: variant)).not_to be_valid
- end
-
- it 'validates presence of attachment and variant' do
- expect(described_class.new(variant: variant, attachment: file_upload)).to be_valid
- end
-end
diff --git a/spree/core/spec/models/spree/fulfillment_provider/digital_spec.rb b/spree/core/spec/models/spree/fulfillment_provider/digital_spec.rb
index 5574bc8dc5..ef116f35b8 100644
--- a/spree/core/spec/models/spree/fulfillment_provider/digital_spec.rb
+++ b/spree/core/spec/models/spree/fulfillment_provider/digital_spec.rb
@@ -9,7 +9,7 @@ describe Spree::FulfillmentProvider::Digital, type: :model do
describe '#create_fulfillment' do
let(:digital_product) { create(:digital_product) }
- let(:variant) { create(:variant, product: digital_product, digitals: [create(:digital), create(:digital)]) }
+ let(:variant) { create(:variant, product: digital_product, digitals: [create(:digital_asset), create(:digital_asset)]) }
let(:order) { create(:order) }
let!(:line_item) { create(:line_item, order: order, variant: variant, quantity: 3) }
let!(:fulfillment) { create(:fulfillment, order: order) }
@@ -18,10 +18,10 @@ describe Spree::FulfillmentProvider::Digital, type: :model do
fulfillment.fulfillment_items.create!(order: order, line_item: line_item, variant: variant, quantity: 3)
end
- it 'creates one link per digital per unit of quantity' do
+ it 'creates one link per digital asset per unit of quantity' do
provider.create_fulfillment(fulfillment)
- expect(line_item.digital_links.reload.group(:digital_id).count.values).to eq([3, 3])
+ expect(line_item.digital_links.reload.group(:digital_asset_id).count.values).to eq([3, 3])
end
it 'is idempotent' do
diff --git a/spree/core/spec/models/spree/line_item_spec.rb b/spree/core/spec/models/spree/line_item_spec.rb
index 13fedfff7a..df91bb9e51 100644
--- a/spree/core/spec/models/spree/line_item_spec.rb
+++ b/spree/core/spec/models/spree/line_item_spec.rb
@@ -136,7 +136,7 @@ describe Spree::LineItem, type: :model do
let(:licence_variant) do
licence_product.default_variant.tap do |variant|
variant.update!(track_inventory: true)
- variant.digitals << create(:digital, variant: variant)
+ variant.digital_assets << create(:digital_asset, variant: variant)
end
end
let(:order) { create(:completed_order_with_totals, store: store) }
diff --git a/spree/core/spec/models/spree/order/digital_auto_fulfillment_spec.rb b/spree/core/spec/models/spree/order/digital_auto_fulfillment_spec.rb
index f09d76b8bc..7fad84c809 100644
--- a/spree/core/spec/models/spree/order/digital_auto_fulfillment_spec.rb
+++ b/spree/core/spec/models/spree/order/digital_auto_fulfillment_spec.rb
@@ -3,7 +3,7 @@ require 'spec_helper'
describe 'Digital auto-fulfillment on order completion', type: :model do
let(:store) { @default_store }
let(:digital_product) { create(:digital_product, store: store) }
- let(:digital_variant) { create(:variant, product: digital_product, digitals: [create(:digital)]) }
+ let(:digital_variant) { create(:variant, product: digital_product, digitals: [create(:digital_asset)]) }
let(:order) { create(:order_with_line_items, store: store, variants: [digital_variant], line_items_count: 1) }
before do
diff --git a/spree/core/spec/models/spree/order_spec.rb b/spree/core/spec/models/spree/order_spec.rb
index 58e4b372da..fedc71f47c 100644
--- a/spree/core/spec/models/spree/order_spec.rb
+++ b/spree/core/spec/models/spree/order_spec.rb
@@ -2216,7 +2216,7 @@ describe Spree::Order, type: :model do
context 'quick checkout' do
let(:digital_product) { create(:digital_product) }
- let(:digital_variant) { create(:variant, product: digital_product, digitals: [create(:digital)]) }
+ let(:digital_variant) { create(:variant, product: digital_product, digitals: [create(:digital_asset)]) }
let(:digital_line_item) { create(:line_item, variant: digital_variant, quantity: 1, order: order) }
let(:physical_line_item) { create(:line_item, quantity: 1, order: order) }
let(:order) { create(:order) }