Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Added marketplace rules for the files sellers upload
Damian Legawiecff51002d4bd2
diff --git a/.changeset/seller-digital-assets.md b/.changeset/seller-digital-assets.mdindex 29fd4121c1..e81f135054 100644--- a/.changeset/seller-digital-assets.md+++ b/.changeset/seller-digital-assets.md@@ -1,8 +1,11 @@---"@spree/seller-sdk": minor+"@spree/admin-sdk": minor"@spree/seller-dashboard": minor"@spree/dashboard-core": minor-"@spree/dashboard": patch+"@spree/dashboard": minor----Sellers can manage the downloadable files on their own digital products. The Seller SDK adds `products.digitalAssets` (`list`, `get`, `create`, `update`, `delete`), and the seller panel's product page shows the same Digital files card as the dashboard: upload, replace and delete files, and set per-file download limits. A file the marketplace delivers through its own provider is listed but cannot be replaced by the seller. The card now lives in `@spree/dashboard-core` as `DigitalAssetsCard`, and a panel enables it by registering `digitalAssets` on its API client.+Sellers can manage the downloadable files on their own digital products. The Seller SDK adds `products.digitalAssets` (`list`, `get`, `create`, `update`, `delete`), and the seller panel's product page shows the same Digital files card as the dashboard: upload, replace and delete files, and set per-file download limits. A file the marketplace delivers through its own provider is listed but cannot be replaced by the seller. The card now lives in `@spree/dashboard-core` as `DigitalAssetsCard`, and a panel enables it by registering `digitalAssets` on its API client; `readOnly` shows the files without any way to change them and `accept` narrows the file picker.++Seller uploads are a marketplace decision: three store settings, edited on the dashboard's Marketplace settings page, say whether sellers may upload at all (off by default), which content types their files may have, and whether a file added to or replaced on an approved product sends it back to review. The seller `/me` response carries them under `store`, and the Admin SDK's `Store` type gains the three fields.diff --git a/docs/api-reference/admin.yaml b/docs/api-reference/admin.yamlindex b256c8f3a9..3702a78d6e 100644--- a/docs/api-reference/admin.yaml+++ b/docs/api-reference/admin.yaml@@ -30505,6 +30505,33 @@ paths:default_payouts_schedule_interval: monthlyauto_approve_sellers: falseauto_approve_seller_products: false+ seller_digital_assets_enabled: false+ seller_digital_asset_content_types:+ - application/pdf+ - application/epub+zip+ - application/zip+ - application/x-7z-compressed+ - application/gzip+ - application/json+ - text/plain+ - text/csv+ - audio/mpeg+ - audio/mp4+ - audio/aac+ - audio/flac+ - audio/ogg+ - audio/wav+ - audio/x-wav+ - audio/midi+ - video/mp4+ - video/webm+ - video/quicktime+ - image/jpeg+ - image/png+ - image/gif+ - image/webp+ - image/tiff+ review_seller_digital_asset_changes: truesend_seller_transactional_emails: truedocument_number_format: sequentialorder_number_prefix: R@@ -30848,6 +30875,33 @@ paths:default_payouts_schedule_interval: monthlyauto_approve_sellers: falseauto_approve_seller_products: false+ seller_digital_assets_enabled: false+ seller_digital_asset_content_types:+ - application/pdf+ - application/epub+zip+ - application/zip+ - application/x-7z-compressed+ - application/gzip+ - application/json+ - text/plain+ - text/csv+ - audio/mpeg+ - audio/mp4+ - audio/aac+ - audio/flac+ - audio/ogg+ - audio/wav+ - audio/x-wav+ - audio/midi+ - video/mp4+ - video/webm+ - video/quicktime+ - image/jpeg+ - image/png+ - image/gif+ - image/webp+ - image/tiff+ review_seller_digital_asset_changes: truesend_seller_transactional_emails: truedocument_number_format: sequentialorder_number_prefix: R@@ -72744,6 +72798,14 @@ components:type: booleanauto_approve_seller_products:type: boolean+ seller_digital_assets_enabled:+ type: boolean+ seller_digital_asset_content_types:+ type: array+ items:+ type: string+ review_seller_digital_asset_changes:+ type: booleansend_seller_transactional_emails:type: booleandocument_number_format:@@ -73453,6 +73515,9 @@ components:- default_payouts_schedule_interval- auto_approve_sellers- auto_approve_seller_products+ - seller_digital_assets_enabled+ - seller_digital_asset_content_types+ - review_seller_digital_asset_changes- send_seller_transactional_emails- document_number_format- order_number_prefix@@ -79252,7 +79317,9 @@ components:signed_id:type: stringdescription: 'A `signed_id` from `files.upload()` with `visibility: ''private''`.- On update it replaces the file for everyone who already bought it.'+ On update it replaces the file for everyone who already bought it. A seller''s+ file must be of a content type the marketplace accepts, judged from its+ bytes.'variant_id:type: stringdescription: On create, defaults to the product's default variant when omitted.@@ -79279,7 +79346,9 @@ components:signed_id:type: stringdescription: 'A `signed_id` from `files.upload()` with `visibility: ''private''`.- On update it replaces the file for everyone who already bought it.'+ On update it replaces the file for everyone who already bought it. A seller''s+ file must be of a content type the marketplace accepts, judged from its+ bytes.'variant_id:type: stringdescription: On create, defaults to the product's default variant when omitted.@@ -83613,6 +83682,22 @@ components:type: booleandescription: Puts a seller product on sale the moment it is submitted, withno review.+ seller_digital_assets_enabled:+ type: boolean+ description: Lets sellers attach downloadable files to their own products.+ seller_digital_asset_content_types:+ type: array+ items:+ type: string+ description: The content types a seller's file may have, judged from its+ bytes. The operator's own uploads are not restricted.+ example:+ - application/pdf+ - application/zip+ review_seller_digital_asset_changes:+ type: boolean+ description: Sends a seller product already on sale back to review when+ the seller adds or replaces a file on it.send_seller_transactional_emails:type: booleandescription: When false, transactional seller emails (approval, payoutsdiff --git a/docs/api-reference/seller.yaml b/docs/api-reference/seller.yamlindex 3bdff3d075..5366948449 100644--- a/docs/api-reference/seller.yaml+++ b/docs/api-reference/seller.yaml@@ -563,6 +563,35 @@ paths:name: Seller 89slug: seller-89status: approved+ store:+ id: store_UkLWZg9DAJ+ name: Spree Test Store+ seller_digital_assets_enabled: false+ seller_digital_asset_content_types:+ - application/pdf+ - application/epub+zip+ - application/zip+ - application/x-7z-compressed+ - application/gzip+ - application/json+ - text/plain+ - text/csv+ - audio/mpeg+ - audio/mp4+ - audio/aac+ - audio/flac+ - audio/ogg+ - audio/wav+ - audio/x-wav+ - audio/midi+ - video/mp4+ - video/webm+ - video/quicktime+ - image/jpeg+ - image/png+ - image/gif+ - image/webp+ - image/tiffpermissions:- allow: trueactions:@@ -834,6 +863,35 @@ paths:name: Seller 91slug: seller-91status: approved+ store:+ id: store_UkLWZg9DAJ+ name: Spree Test Store+ seller_digital_assets_enabled: false+ seller_digital_asset_content_types:+ - application/pdf+ - application/epub+zip+ - application/zip+ - application/x-7z-compressed+ - application/gzip+ - application/json+ - text/plain+ - text/csv+ - audio/mpeg+ - audio/mp4+ - audio/aac+ - audio/flac+ - audio/ogg+ - audio/wav+ - audio/x-wav+ - audio/midi+ - video/mp4+ - video/webm+ - video/quicktime+ - image/jpeg+ - image/png+ - image/gif+ - image/webp+ - image/tiffpermissions: []permission_keys: []schema:@@ -24401,6 +24459,8 @@ components:type: arrayitems:"$ref": "#/components/schemas/SellerMeSummary"+ store:+ "$ref": "#/components/schemas/Store"permissions:type: arrayitems:@@ -24417,6 +24477,7 @@ components:required:- user- sellers+ - store- permissions- permission_keysOnboardingProgress:@@ -29775,6 +29836,25 @@ components:- created_at- updated_atx-typelizer: true+ Store:+ type: object+ properties:+ id:+ type: string+ name:+ type: string+ seller_digital_assets_enabled:+ type: boolean+ seller_digital_asset_content_types:+ type: array+ items:+ type: string+ required:+ - id+ - name+ - seller_digital_assets_enabled+ - seller_digital_asset_content_types+ x-typelizer: trueTaxIdentifier:type: objectproperties:@@ -31835,7 +31915,9 @@ components:signed_id:type: stringdescription: 'A `signed_id` from `files.upload()` with `visibility: ''private''`.- On update it replaces the file for everyone who already bought it.'+ On update it replaces the file for everyone who already bought it. A seller''s+ file must be of a content type the marketplace accepts, judged from its+ bytes.'variant_id:type: stringdescription: On create, defaults to the product's default variant when omitted.@@ -31856,7 +31938,9 @@ components:signed_id:type: stringdescription: 'A `signed_id` from `files.upload()` with `visibility: ''private''`.- On update it replaces the file for everyone who already bought it.'+ On update it replaces the file for everyone who already bought it. A seller''s+ file must be of a content type the marketplace accepts, judged from its+ bytes.'variant_id:type: stringdescription: On create, defaults to the product's default variant when omitted.diff --git a/docs/developer/core-concepts/products.mdx b/docs/developer/core-concepts/products.mdxindex 63d5b646ac..0d41d38934 100644--- a/docs/developer/core-concepts/products.mdx+++ b/docs/developer/core-concepts/products.mdx@@ -340,6 +340,8 @@ Never store a rejection reason on the product itself. A seller can write their oAn approval with no `reviewed_by_id` and `metadata.auto_approved` set means the store approves listings automatically — never a decision whose author was lost. Turn that on with the `auto_approve_seller_products` store preference.+A product already on sale can come back to review when what it delivers changes: a seller adding or replacing a downloadable file reopens it, unless the store turns `review_seller_digital_asset_changes` off. The new submission carries `metadata.reason` (`digital_asset_changed`) and who made the change, so the queue says why the listing is back.+### Submitting, as a sellerStatus is not writable on the seller branch. A seller moves a product with an explicit action:diff --git a/docs/developer/customization/workflows.mdx b/docs/developer/customization/workflows.mdxindex 60255d3916..48ad9b9a98 100644--- a/docs/developer/customization/workflows.mdx+++ b/docs/developer/customization/workflows.mdx@@ -288,6 +288,10 @@ is reported through `Rails.error` so it's visible rather than mysterious.| `products.archive` | `validate` | validate | Before the product is taken off sale || `products.archive` | `after_archive` | lifecycle | After the status is written (in transaction) || `products.draft` | `validate` | validate | Before the product returns to draft |+| `digital_assets.create` | `validate` | validate | After the upload is resolved and the marketplace's seller rules pass, before anything is attached — `blob` is the file, already in storage, so a scanner can read it here. Fires for the operator's and the seller's endpoints and for files nested in a product write |+| `digital_assets.create` | `after_create` | lifecycle | After the asset is saved (in transaction) — queue a slower scan here |+| `digital_assets.update` | `validate` | validate | With the pending attributes assigned, so `digital_asset.changes` describes the edit; `blob` is the replacement file, or nil |+| `digital_assets.update` | `after_update` | lifecycle | After the asset is saved (in transaction) || `products.draft` | `after_draft` | lifecycle | After the status is written (in transaction) || `gift_cards.apply` | `validate` | validate | Before a card is drawn against — who may spend a card, on what, up to how much || `gift_cards.apply` | `after_apply` | lifecycle | After the store credit and payment exist (in transaction) |diff --git a/docs/developer/how-to/build-a-marketplace.mdx b/docs/developer/how-to/build-a-marketplace.mdxindex 6645e00eb8..cfd4138f16 100644--- a/docs/developer/how-to/build-a-marketplace.mdx+++ b/docs/developer/how-to/build-a-marketplace.mdx@@ -94,6 +94,9 @@ Admin API like the payout ones.|---|---|---|| `auto_approve_sellers` | `false` | Admit a seller the moment they finish the checklist, with nobody looking at them. || `auto_approve_seller_products` | `false` | Put a seller's product on sale the moment they submit it. |+| `seller_digital_assets_enabled` | `false` | Let sellers attach downloadable files to their own products. |+| `seller_digital_asset_content_types` | documents, ebooks, archives, audio, video, images, plain text | The content types a seller's file may have, judged from its bytes. Your own uploads are not restricted. |+| `review_seller_digital_asset_changes` | `true` | Send a seller product already on sale back to review when the seller adds or replaces a file on it. || `send_seller_transactional_emails` | `true` | Whether Spree emails sellers. Turn it off if you front seller communications yourself. || `default_commission_tax_rate` | `0` | Tax on your commission when neither the rate nor the tax provider names one. |@@ -126,6 +129,8 @@ curl -X PATCH 'https://api.mystore.com/api/v3/admin/store' \Turning either auto-approve preference on removes a human decision from your marketplace. `auto_approve_sellers` lets any applicant who ticks every box start trading; `auto_approve_seller_products` puts their listings on sale without review. Both are appropriate for an invite-only marketplace where you already trust the sellers, and dangerous for an open one.</Warning>+A file a buyer downloads under your marketplace's name is something your marketplace vouches for, so seller uploads are off until you turn them on. When you do, keep the accepted type list tight — executables and scripts are left out of the default — and leave file changes under review unless you auto-approve seller products anyway. See [Sell digital products → On a marketplace](/developer/how-to/sell-digital-products#on-a-marketplace) for what sellers can then do, and for scanning uploads with your own code.+Commission tax is stored as a fraction — `0.23` means 23%. The dashboard asks fora percentage and converts, so you only meet the fraction through the API. See[Tax on commission](/developer/core-concepts/commissions#tax-on-commission) fordiff --git a/docs/developer/how-to/sell-digital-products.mdx b/docs/developer/how-to/sell-digital-products.mdxindex af63d16204..16e3aead84 100644--- a/docs/developer/how-to/sell-digital-products.mdx+++ b/docs/developer/how-to/sell-digital-products.mdx@@ -62,6 +62,16 @@ A [seller](/developer/core-concepts/sellers) attaches files to their own productSellers upload files only. A [custom digital asset provider](/developer/how-to/custom-digital-asset-provider) is your own integration, so sellers cannot pick one. A file you attached with a provider still appears on the seller's product, without its provider settings, and the seller cannot replace it.+Seller uploads are **off until you turn them on**, under Settings → Marketplace → Seller files, because a file a buyer downloads under your name is one you vouch for. Three settings shape them:++- **Let sellers upload digital files** (`seller_digital_assets_enabled`). Off, the seller panel shows the files you attached and nothing else.+- **Accepted file types for sellers** (`seller_digital_asset_content_types`). Judged from the file's bytes, not its name, so a renamed executable does not pass as a PDF. The default covers documents, ebooks, archives, audio, video, images and plain text; add `application/octet-stream` only if your sellers trade in a format nothing recognises, since it admits anything unknown. Your own uploads are never restricted.+- **Review file changes on products already on sale** (`review_seller_digital_asset_changes`, on by default). A seller adding or replacing a file on an approved product sends it back to [review](/developer/core-concepts/products#submitting-as-a-seller) and off sale until you approve it again; the new submission says why. Changing download limits does not. The setting does nothing when seller products publish automatically.++<Warning>+None of this inspects a file for malware. The accepted type list is a policy, and ZIP is on it. To scan what sellers upload, register a handler on the `digital_assets.create.validate` hook, which fires with the file already in storage and can refuse it, or on `after_create` to queue a slower scan. The same hooks see the operator's uploads and files nested in a product write. See [Workflows → hooks](/developer/customization/workflows#extending-a-workflow-with-hooks).+</Warning>+<Tabs><Tab title="Seller SDK">```typescriptdiff --git a/docs/plans/6.0-digital-assets.md b/docs/plans/6.0-digital-assets.mdindex 9e1f73caab..ad8fb699dd 100644--- a/docs/plans/6.0-digital-assets.md+++ b/docs/plans/6.0-digital-assets.md@@ -45,6 +45,10 @@ Spree ships a complete digital products engine in core: `Spree::Digital` (a file- **Per-file download limits are the seller's to set**, with the same fallback to the store's settings.- **Edit page only.** The card needs a saved product; attaching files on the seller's new-product form is deferred until requested.- **One card for both panels.** The Digital files card lives in `@spree/dashboard-core` and talks through the registered panel client; the admin registers `providers`, the seller panel does not, and the card hides the provider menu.+- **Seller uploads are off until the marketplace opens them** (`seller_digital_assets_enabled`, default false, like the two auto-approve settings): a file a buyer downloads under the marketplace's name is one it vouches for. Off, the seller panel shows the operator's files read-only and the Seller API refuses create and replace.+- **A seller's file must be of an accepted content type** (`seller_digital_asset_content_types`), judged from the bytes Marcel identifies, never the file name. The default list covers documents, ebooks, archives, audio, video, images and plain text; executables, scripts, SVG and unrecognised binaries are out. The operator's own uploads are not restricted. This is policy, not scanning: ZIP is on the list.+- **A file change on an approved listing reopens its review** (`review_seller_digital_asset_changes`, default true). Adding or replacing a file, not changing limits or deleting. `Products::Propose` gains a `reason:` that admits an active product and lands on the submission row's metadata (`digital_asset_changed`) with who did it, so the queue says why. Moot when seller products auto-approve. Asset-level quarantine (the old file serving until the new one is approved) was considered and deferred to the uploads scanning work, since it needs file versioning.+- **Every digital asset write runs through a workflow.** `DigitalAssets::Create` and `Update`, declared by both controllers and called by the nested `digital_assets` list on a product write, with `validate` / `after_create` / `after_update` hooks. The seller rules are steps in them, keyed on a `seller:` argument the seller controller passes; a host's upload scanner registers on `digital_assets.create.validate` (the bytes are already in storage) or `after_create`.### Wave 7 — license-code pools (design finalized 2026-08-12; deferred to 6.1)@@ -204,7 +208,7 @@ Step numbers continue the shipped sequence; the design **waves** map to steps as8. **License-code pools** — **deferred to 6.1, open source**: `spree_license_codes` migration (value / attachment / nullable `digital_link_id`); the `LicensePool` provider (claim-once-pin-to-link, text or image); the `LicenseCodesRowProcessor` on the existing `Spree::Import` pipeline; the stock sync (`count_on_hand` ← `codes.available.count`, transactional on import + redeem) wired through `Stock::Quantifier`; admin (codes-remaining, import action, per-code list); docs. Builds on wave 6's provider seam, so it lands after it, in order: `LicenseCode` model + migration → `LicensePool` provider + the pin-then-reshow flow → stock sync → CSV import → admin → docs. The stock sync lands with its own test battery — it is the piece most able to drift.-9. **Seller panel management** — **in progress 2026-10-24** (GitHub #14965): Seller API nested endpoint, Seller SDK resource, the Digital files card moved to `@spree/dashboard-core` and mounted on the seller product page, a shared request shape and serializer fields for both branches.+9. **Seller panel management** — **in progress 2026-10-24** (GitHub #14965): Seller API nested endpoint, Seller SDK resource, the Digital files card moved to `@spree/dashboard-core` and mounted on the seller product page, a shared request shape and serializer fields for both branches. Extended the same day with the marketplace's rules for a seller's file: `DigitalAssets::Create` / `Update` workflows (the nested product payload and both endpoints run through them), three store settings on the Marketplace settings page, the seller `/me` response carrying them under `store`, and `Products::Propose` reopening review with a `reason`.## Constraints on Current Work@@ -214,6 +218,7 @@ Step numbers continue the shipped sequence; the design **waves** map to steps as- 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.- Wave 7: keep a pool variant's `count_on_hand` and its unredeemed-code count in sync **transactionally** — import and redeem both write both, in one transaction. A drift silently blocks sellable stock or permits an oversell. Never compute one from the other lazily at read time in the checkout path.- The seller branch never accepts `provider_type` or `provider_settings` and never serializes `provider_settings`; a provider stays the operator's own integration.+- Digital assets are written only through `Spree.digital_asset_create_workflow` / `update_workflow` — never `DigitalAsset.new` + `attach` in a controller, importer or seed — so a host's upload scanner and the marketplace's seller rules see every file. The seller rules are steps in the workflow keyed on `seller:`, never checks in a controller.- Do not assume `DigitalAsset#attachment` is present anywhere outside the model — a provider-backed asset has none. Reach for `deliver` / `downloadable?`, never `attachment` directly. (The 6.0 model already followed this; wave 6 is why it mattered.)- Wave 6 download-flow code treats the deliverable as opaque (a `DigitalDelivery` — URL or inline value), never as a storage URL. A digital-asset provider owns its own configuration (it is host-app glue into internal software) — do NOT add an `Integration` FK or credential surface to `DigitalAsset`. This deliberately differs from delivery-rate/tax providers, which connect to marketplace services; see the wave 6 decision.- Emailed download URLs are long-lived customer-facing artifacts: any route change must keep old URLs working for at least one release.diff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex 6af172b64e..fd0c73f830 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -1,3 +1,13 @@+## 2026-10-24: A marketplace decides whether, what and under review its sellers may upload++**Context:** With sellers able to attach downloadable files to their products (the entry below), any approved seller can put a file on the marketplace's domain that buyers download trusting the marketplace's brand. Nothing in Spree scans a file's contents, and before this there was no way to keep seller uploads off, to narrow what they may be, or to re-check an approved listing whose file changed. Digital asset writes were also plain model saves in two places, so a host had no point at which to refuse an upload.++**Decision:** Three store settings, shown on the dashboard's Marketplace settings page. `seller_digital_assets_enabled` is off by default, like the two auto-approve settings: what a buyer downloads under the marketplace's name is something the marketplace vouches for, and that should be a choice. `seller_digital_asset_content_types` is an allowlist judged from the bytes Marcel identifies, never the file name; its default covers the formats digital goods usually come in and leaves out executables, scripts, SVG and unrecognised binaries. The operator's own uploads are not restricted. `review_seller_digital_asset_changes` is on by default: a seller adding or replacing a file on a listing already on sale sends it back to review, off sale until approved again; changing limits or deleting does not, and the rule is moot when seller products auto-approve. `Products::Propose` admits an active product when told a `reason`, recorded on the submission row with who made the change. All digital asset writes now run through `Spree::DigitalAssets::Create` and `Update` — both endpoints and the nested list on a product write — with `validate` and `after_*` hooks; the seller rules are steps in them, applied when the caller names a `seller:`. A host that scans uploads registers on `digital_assets.create.validate`, where the bytes are already in storage, or queues a scan from `after_create`. Core ships no scanner. The seller `/me` response carries the two settings the panel needs under `store`.++**Consequences:** A marketplace that reviews listings will see approved products drop off sale for a file swap until it approves them again; the alternative, holding the new file in quarantine while the old one keeps serving, needs file versioning and is deferred to the uploads scanning work. ZIP is on the default list, so the allowlist is a policy, not protection. Opening uploads to sellers is now an explicit step in setting up a marketplace, documented beside the auto-approve settings. The 6.1 upload-scanning design (a scanner registry with a no-op default, a verdict on the blob, delivery refused while pending) builds on these hooks rather than on the controllers.++**Plan amended:** `6.0-digital-assets.md` (Seller panel decisions, Migration Path step 9, Constraints on Current Work).+## 2026-10-24: Sellers manage the downloadable files on their own products, uploads only**Context:** A marketplace seller could list a digital product, but only the operator could attach the file it delivers (GitHub #14965). The Seller API had a file upload endpoint and nothing to attach the upload to a product.diff --git a/packages/admin-sdk/src/types/generated/Store.ts b/packages/admin-sdk/src/types/generated/Store.tsindex 33932e6648..5cc9b6311e 100644--- a/packages/admin-sdk/src/types/generated/Store.ts+++ b/packages/admin-sdk/src/types/generated/Store.ts@@ -1,4 +1,4 @@-// Typelizer digest 9c505ea4d837ab23033514c186f95de4+// Typelizer digest 2dcf057b9f14ca9e573e79af02ce726b//// DO NOT MODIFY: This file was automatically generated by Typelizer.import type {SetupTask, CurrencyCode, LocaleCode, WeightUnit, UnitSystem, StorefrontAccess, CaptureMethod, ProviderFailurePolicy, PayoutScheduleInterval, DocumentNumberFormat, EmailFont} from '@/types'@@ -46,6 +46,9 @@ interface Store {default_payouts_schedule_interval: PayoutScheduleInterval;auto_approve_sellers: boolean;auto_approve_seller_products: boolean;+ seller_digital_assets_enabled: boolean;+ seller_digital_asset_content_types: Array<string>;+ review_seller_digital_asset_changes: boolean;send_seller_transactional_emails: boolean;document_number_format: DocumentNumberFormat;order_number_prefix: string;diff --git a/packages/admin-sdk/src/types/params/DigitalAssetCreateParams.ts b/packages/admin-sdk/src/types/params/DigitalAssetCreateParams.tsindex 9ec3151f65..109a8ffcf0 100644--- a/packages/admin-sdk/src/types/params/DigitalAssetCreateParams.ts+++ b/packages/admin-sdk/src/types/params/DigitalAssetCreateParams.ts@@ -3,7 +3,8 @@export type DigitalAssetCreateParams = {/*** A `signed_id` from `files.upload()` with `visibility: 'private'`. On update it replaces the- * file for everyone who already bought it.+ * file for everyone who already bought it. A seller's file must be of a content type the+ * marketplace accepts, judged from its bytes.*/signed_id?: string/**diff --git a/packages/admin-sdk/src/types/params/DigitalAssetUpdateParams.ts b/packages/admin-sdk/src/types/params/DigitalAssetUpdateParams.tsindex d10ee1770d..b3a0b246e9 100644--- a/packages/admin-sdk/src/types/params/DigitalAssetUpdateParams.ts+++ b/packages/admin-sdk/src/types/params/DigitalAssetUpdateParams.ts@@ -3,7 +3,8 @@export type DigitalAssetUpdateParams = {/*** A `signed_id` from `files.upload()` with `visibility: 'private'`. On update it replaces the- * file for everyone who already bought it.+ * file for everyone who already bought it. A seller's file must be of a content type the+ * marketplace accepts, judged from its bytes.*/signed_id?: string/**diff --git a/packages/admin-sdk/src/types/params/StoreUpdateParams.ts b/packages/admin-sdk/src/types/params/StoreUpdateParams.tsindex f556e8236c..e04c268703 100644--- a/packages/admin-sdk/src/types/params/StoreUpdateParams.ts+++ b/packages/admin-sdk/src/types/params/StoreUpdateParams.ts@@ -74,6 +74,18 @@ export type StoreUpdateParams = {auto_approve_sellers?: boolean/** Puts a seller product on sale the moment it is submitted, with no review. */auto_approve_seller_products?: boolean+ /** Lets sellers attach downloadable files to their own products. */+ seller_digital_assets_enabled?: boolean+ /**+ * The content types a seller's file may have, judged from its bytes. The operator's own uploads+ * are not restricted.+ */+ seller_digital_asset_content_types?: string[]+ /**+ * Sends a seller product already on sale back to review when the seller adds or replaces a file+ * on it.+ */+ review_seller_digital_asset_changes?: boolean/** When false, transactional seller emails (approval, payouts and so on) are not sent. */send_seller_transactional_emails?: boolean/**diff --git a/packages/admin-sdk/src/zod/generated/Store.ts b/packages/admin-sdk/src/zod/generated/Store.tsindex 730756d56e..371813fa6b 100644--- a/packages/admin-sdk/src/zod/generated/Store.ts+++ b/packages/admin-sdk/src/zod/generated/Store.ts@@ -43,6 +43,9 @@ export const StoreSchema = z.object({default_payouts_schedule_interval: z.string(),auto_approve_sellers: z.boolean(),auto_approve_seller_products: z.boolean(),+ seller_digital_assets_enabled: z.boolean(),+ seller_digital_asset_content_types: z.array(z.string()),+ review_seller_digital_asset_changes: z.boolean(),send_seller_transactional_emails: z.boolean(),document_number_format: z.string(),order_number_prefix: z.string(),diff --git a/packages/dashboard-core/src/products/digital-assets-card.tsx b/packages/dashboard-core/src/products/digital-assets-card.tsxindex e7e9c5ea37..33a1404d10 100644--- a/packages/dashboard-core/src/products/digital-assets-card.tsx+++ b/packages/dashboard-core/src/products/digital-assets-card.tsx@@ -56,14 +56,25 @@ import {export function DigitalAssetsCard({productId,variants,+ readOnly = false,+ accept,}: {productId?: stringvariants?: PanelVariant[]+ /**+ * Shows the files without any way to change them, for a panel whose host+ * has not opened file uploads to this user — the seller panel when the+ * marketplace keeps digital files to itself. With nothing to show, the+ * card renders nothing at all.+ */+ readOnly?: boolean+ /** The content types the picker offers, when the host restricts them. */+ accept?: string[]}) {const { t } = useTranslation()const confirm = useConfirm()const { permissions } = usePermissions()- const canWrite = permissions.can('update', Subject.Product)+ const canWrite = !readOnly && permissions.can('update', Subject.Product)const fileInputRef = useRef<HTMLInputElement>(null)const replaceInputRef = useRef<HTMLInputElement>(null)// The file whose replacement the picker was opened for.@@ -209,6 +220,7 @@ export function DigitalAssetsCard({}if (!productId || !getApiClient().digitalAssets) return null+ if (readOnly && !isLoading && !hasAssets) return nullreturn (<Card>@@ -272,10 +284,17 @@ export function DigitalAssetsCard({ref={fileInputRef}type="file"multiple+ accept={accept?.join(',')}className="hidden"onChange={handleFileInput}/>- <input ref={replaceInputRef} type="file" className="hidden" onChange={handleReplaceInput} />+ <input+ ref={replaceInputRef}+ type="file"+ accept={accept?.join(',')}+ className="hidden"+ onChange={handleReplaceInput}+ />{isLoading ? (<Skeleton className="h-24 w-full" />diff --git a/packages/dashboard/e2e/helpers.ts b/packages/dashboard/e2e/helpers.tsindex ace4c83244..1f46056b11 100644--- a/packages/dashboard/e2e/helpers.ts+++ b/packages/dashboard/e2e/helpers.ts@@ -226,6 +226,28 @@ export function getCredentials(): E2ECredentials {return cached}+/**+ * An Admin API session without opening the dashboard, for a spec that only+ * needs `adminRequest` — a seller panel spec arranging a store setting, say.+ */+export async function adminApiSession(+ page: Page,+ account?: { email: string; password: string },+): Promise<E2ELoginSession> {+ const creds = getCredentials()+ const res = await page.request.post('/api/v3/admin/auth/login', {+ data: account ?? { email: creds.admin_email, password: creds.admin_password },+ })+ if (!res.ok()) {+ throw new Error(`API login failed with ${res.status()}: ${await res.text()}`)+ }+ const { token: accessToken } = (await res.json()) as { token: string }+ if (!accessToken) {+ throw new Error('API login response missing token')+ }+ return { ...creds, accessToken }+}+/*** Establish an authenticated admin session as a precondition for any spec* that needs one. Returns the credentials so callers can immediately@@ -245,17 +267,7 @@ export async function login(page: Page,account?: { email: string; password: string },): Promise<E2ELoginSession> {- const creds = getCredentials()- const res = await page.request.post('/api/v3/admin/auth/login', {- data: account ?? { email: creds.admin_email, password: creds.admin_password },- })- if (!res.ok()) {- throw new Error(`API login failed with ${res.status()}: ${await res.text()}`)- }- const { token: accessToken } = (await res.json()) as { token: string }- if (!accessToken) {- throw new Error('API login response missing token')- }+ const session = await adminApiSession(page, account)await page.goto('/')// Wait for the authenticated redirect to the store-scoped home — not just// "left /login", which is trivially true at `/` while the boot refresh is@@ -264,8 +276,8 @@ export async function login(// loser of that race gets a 401 that clears the cookie and bounces the// page to /login. The redirect only fires after auth init settles, so it// doubles as the refresh-complete barrier.- await expect(page).toHaveURL(new RegExp(`/${creds.store_id}`), { timeout: 15_000 })- return { ...creds, accessToken }+ await expect(page).toHaveURL(new RegExp(`/${session.store_id}`), { timeout: 15_000 })+ return session}/**diff --git a/packages/dashboard/e2e/marketplace-settings.spec.ts b/packages/dashboard/e2e/marketplace-settings.spec.tsindex 476b4295fe..6829ea5cc6 100644--- a/packages/dashboard/e2e/marketplace-settings.spec.ts+++ b/packages/dashboard/e2e/marketplace-settings.spec.ts@@ -36,6 +36,42 @@ test.describe('marketplace settings', () => {await expect(page.getByRole('button', { name: /^save$/i })).toBeDisabled({ timeout: 15_000 })})+ test('opens digital files to sellers with an accepted type list, and it survives a reload', async ({+ page,+ }) => {+ const creds = await login(page)+ await page.goto(MARKETPLACE_PATH(creds.store_id))+ await expect(page.getByRole('heading', { name: /^marketplace$/i })).toBeVisible({+ timeout: 15_000,+ })++ const enabled = page.getByRole('switch', { name: /let sellers upload digital files/i })+ const types = page.getByLabel(/accepted file types for sellers/i)+ const review = page.getByRole('switch', { name: /review file changes on products/i })+ const originalTypes = await types.inputValue()+ const wasEnabled = (await enabled.getAttribute('aria-checked')) === 'true'++ if (!wasEnabled) await enabled.click()+ await types.fill('application/pdf\naudio/mpeg')+ await review.click()+ await page.getByRole('button', { name: /^save$/i }).click()+ await expect(page.getByText(/store settings updated/i).first()).toBeVisible({+ timeout: 15_000,+ })++ await page.reload()+ await expect(enabled).toHaveAttribute('aria-checked', 'true', { timeout: 15_000 })+ await expect(types).toHaveValue('application/pdf\naudio/mpeg')+ await expect(review).toHaveAttribute('aria-checked', 'false')++ // Put the store back so the seller panel specs read the defaults.+ if (!wasEnabled) await enabled.click()+ await types.fill(originalTypes)+ await review.click()+ await page.getByRole('button', { name: /^save$/i }).click()+ await expect(page.getByRole('button', { name: /^save$/i })).toBeDisabled({ timeout: 15_000 })+ })+test('the old payouts settings address opens this page', async ({ page }) => {const creds = await login(page)await page.goto(`/${creds.store_id}/settings/payouts`)diff --git a/packages/dashboard/e2e/seller-panel-products.spec.ts b/packages/dashboard/e2e/seller-panel-products.spec.tsindex 6523d2efcb..b21e439dd3 100644--- a/packages/dashboard/e2e/seller-panel-products.spec.ts+++ b/packages/dashboard/e2e/seller-panel-products.spec.ts@@ -1,7 +1,14 @@import * as path from 'node:path'import { fileURLToPath } from 'node:url'import { expect, type Page, test } from '@playwright/test'-import { clickBulkAction, FIXTURE_SELLER_WRITER_EMAIL, openRowMenu, sellerLogin } from './helpers'+import {+ adminApiSession,+ adminRequest,+ clickBulkAction,+ FIXTURE_SELLER_WRITER_EMAIL,+ openRowMenu,+ sellerLogin,+} from './helpers'// The card serves whatever is attached, so the shared image fixture will do.const DIGITAL_FILE = path.join(@@ -86,6 +93,23 @@ test.describe('seller panel — products', () => {test('uploads a digital file, sets its download limits, replaces it, then removes it', async ({page,}) => {+ // Off by default: the marketplace opens file uploads to its sellers. The+ // replacement below is a format nothing recognises, which the default+ // type list refuses, so the marketplace admits unknown binaries too.+ const admin = await adminApiSession(page)+ const store = await adminRequest<{ seller_digital_asset_content_types: string[] }>(+ page,+ admin,+ 'get',+ '/store',+ )+ await adminRequest(page, admin, 'patch', '/store', {+ seller_digital_assets_enabled: true,+ seller_digital_asset_content_types: Array.from(+ new Set([...store.seller_digital_asset_content_types, 'application/octet-stream']),+ ),+ })+const home = await sellerLogin(page, FIXTURE_SELLER_WRITER_EMAIL)await listProduct(page, home, `E2E Amp Model ${Date.now()}`)diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex 8f54a853b1..229139b3b1 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -2339,6 +2339,19 @@"label": "نشر منتجات البائعين تلقائياً","help": "يُعرض منتج البائع للبيع فور إرساله، دون أن يراجعه أحد."},+ "seller_digital_assets_enabled": {+ "label": "السماح للبائعين برفع الملفات الرقمية",+ "help": "يرفق البائعون ملفات قابلة للتنزيل بمنتجاتهم ويحددون حدود التنزيل. عند الإيقاف، يمكنك أنت فقط إضافة الملفات، ويرى البائعون ما أضفته."+ },+ "seller_digital_asset_content_types": {+ "label": "أنواع الملفات المقبولة من البائعين",+ "help": "نوع محتوى واحد في كل سطر، مثل application/pdf. يُحكم عليه من بايتات الملف لا من اسمه. ملفاتك أنت غير مقيدة.",+ "placeholder": "application/pdf\napplication/zip\naudio/mpeg"+ },+ "review_seller_digital_asset_changes": {+ "label": "مراجعة تغييرات الملفات في المنتجات المعروضة للبيع",+ "help": "عندما يضيف بائع ملفًا أو يستبدله في منتج معتمد، يعود المنتج إلى المراجعة ويُسحب من البيع حتى تعتمده مجددًا. لا تأثير له عند النشر التلقائي لمنتجات البائعين."+ },"send_seller_transactional_emails": {"label": "إرسال رسائل إلى البائعين","help": "يرسل للبائعين رسائل عن الموافقة والمنتجات والمدفوعات. أوقفه إذا كنت تراسل بائعيك بنفسك. لا يؤثر ذلك على رسائل العملاء."@@ -4343,6 +4356,8 @@"payouts_description": "كيف ومتى يدفع هذا السوق لبائعيه. يمكن أن يكون للبائع جدوله الخاص وحده الأدنى الخاص به بدلاً من ذلك.","admission_title": "الموافقة على البائعين","admission_description": "تفعيل أي من هذين الخيارين يلغي قراراً بشرياً. لا بأس بذلك في سوق بالدعوة فقط، لكنه محفوف بالمخاطر في سوق مفتوح للجميع.",+ "seller_files_title": "ملفات البائعين",+ "seller_files_description": "ما إذا كان يمكن للبائعين إرفاق ملفات قابلة للتنزيل بمنتجاتهم، وأي أنواع، وما إذا كان تغيير ملف في منتج معتمد يحتاج إلى مراجعة أخرى.","communication_title": "التواصل","commission_tax_title": "الضريبة على العمولة"},diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex 932b93485e..e222770585 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -2321,6 +2321,19 @@"label": "Produkte von Verkäufern automatisch veröffentlichen","help": "Das Produkt eines Verkäufers ist sofort nach dem Einreichen im Verkauf, ohne dass es jemand prüft."},+ "seller_digital_assets_enabled": {+ "label": "Verkäufern das Hochladen digitaler Dateien erlauben",+ "help": "Verkäufer hängen herunterladbare Dateien an ihre eigenen Produkte an und legen Download-Limits fest. Ausgeschaltet können nur Sie Dateien hinzufügen, und Verkäufer sehen die von Ihnen hinzugefügten."+ },+ "seller_digital_asset_content_types": {+ "label": "Zulässige Dateitypen für Verkäufer",+ "help": "Ein Inhaltstyp pro Zeile, zum Beispiel application/pdf. Beurteilt anhand der Bytes der Datei, nicht ihres Namens. Ihre eigenen Uploads sind nicht eingeschränkt.",+ "placeholder": "application/pdf\napplication/zip\naudio/mpeg"+ },+ "review_seller_digital_asset_changes": {+ "label": "Dateiänderungen an bereits verkauften Produkten prüfen",+ "help": "Fügt ein Verkäufer einem freigegebenen Produkt eine Datei hinzu oder ersetzt sie, geht das Produkt zurück in die Prüfung und aus dem Verkauf, bis Sie es erneut freigeben. Ohne Wirkung, wenn Verkäuferprodukte automatisch veröffentlicht werden."+ },"send_seller_transactional_emails": {"label": "E-Mails an Verkäufer senden","help": "Sendet Verkäufern E-Mails zu Freigabe, Produkten und Auszahlungen. Deaktivieren Sie dies, wenn Sie Ihre Verkäufer selbst anschreiben. E-Mails an Kunden bleiben davon unberührt."@@ -4311,6 +4324,8 @@"payouts_description": "Wie und wann dieser Marktplatz seine Verkäufer bezahlt. Ein Verkäufer kann stattdessen einen eigenen Rhythmus und Mindestbetrag haben.","admission_title": "Verkäuferfreigabe","admission_description": "Wenn Sie eine dieser Optionen aktivieren, entfällt eine menschliche Entscheidung. Für einen Marktplatz nur auf Einladung in Ordnung, für einen offenen riskant.",+ "seller_files_title": "Dateien von Verkäufern",+ "seller_files_description": "Ob Verkäufer herunterladbare Dateien an ihre Produkte anhängen dürfen, welche Arten, und ob eine Dateiänderung an einem freigegebenen Produkt erneut geprüft wird.","communication_title": "Kommunikation","commission_tax_title": "Steuer auf Provision"},diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex 534f9f41d9..5e681d9448 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -2321,6 +2321,19 @@"label": "Publish seller products automatically","help": "A seller’s product goes on sale the moment they submit it, without anyone reviewing it."},+ "seller_digital_assets_enabled": {+ "label": "Let sellers upload digital files",+ "help": "Sellers attach downloadable files to their own products and set download limits on them. Off, only you can add files, and sellers see the ones you added."+ },+ "seller_digital_asset_content_types": {+ "label": "Accepted file types for sellers",+ "help": "One content type per line, such as application/pdf. Judged from the file’s bytes, not its name. Your own uploads are not restricted.",+ "placeholder": "application/pdf\napplication/zip\naudio/mpeg"+ },+ "review_seller_digital_asset_changes": {+ "label": "Review file changes on products already on sale",+ "help": "When a seller adds or replaces a file on an approved product, it goes back to review and off sale until you approve it again. Does nothing when seller products publish automatically."+ },"send_seller_transactional_emails": {"label": "Email sellers","help": "Sends sellers transactional emails about approval, products and payouts. Turn this off if you write to your sellers yourself. Customer emails are unaffected."@@ -4311,6 +4324,8 @@"payouts_description": "How and when this marketplace pays its sellers. A seller can carry their own schedule and minimum instead.","admission_title": "Seller admission","admission_description": "Turning either of these on removes a human decision. Fine for an invite-only marketplace where you already know every seller; risky for one anyone can join.",+ "seller_files_title": "Seller files",+ "seller_files_description": "Whether sellers may attach downloadable files to their products, which kinds, and whether changing a file on an approved product needs another look.","communication_title": "Communication","commission_tax_title": "Commission tax"},diff --git a/packages/dashboard/src/locales/es.json b/packages/dashboard/src/locales/es.jsonindex 03ba008ff7..22f1c765bf 100644--- a/packages/dashboard/src/locales/es.json+++ b/packages/dashboard/src/locales/es.json@@ -731,6 +731,8 @@"payouts_description": "Cómo y cuándo paga este marketplace a sus vendedores. Un vendedor puede tener su propia frecuencia y su propio mínimo.","admission_title": "Aprobación de vendedores","admission_description": "Activar cualquiera de estas opciones elimina una decisión humana. Está bien en un marketplace solo por invitación; es arriesgado en uno abierto a cualquiera.",+ "seller_files_title": "Archivos de vendedores",+ "seller_files_description": "Si los vendedores pueden adjuntar archivos descargables a sus productos, de qué tipos, y si cambiar un archivo en un producto aprobado requiere otra revisión.","communication_title": "Comunicación","commission_tax_title": "Impuesto sobre la comisión"},@@ -2261,6 +2263,19 @@"label": "Publicar productos de vendedores automáticamente","help": "El producto de un vendedor sale a la venta en cuanto lo envía, sin que nadie lo revise."},+ "seller_digital_assets_enabled": {+ "label": "Permitir a los vendedores subir archivos digitales",+ "help": "Los vendedores adjuntan archivos descargables a sus propios productos y fijan límites de descarga. Desactivado, solo usted puede añadir archivos, y los vendedores ven los que usted añadió."+ },+ "seller_digital_asset_content_types": {+ "label": "Tipos de archivo aceptados para vendedores",+ "help": "Un tipo de contenido por línea, por ejemplo application/pdf. Se juzga por los bytes del archivo, no por su nombre. Sus propias subidas no están restringidas.",+ "placeholder": "application/pdf\napplication/zip\naudio/mpeg"+ },+ "review_seller_digital_asset_changes": {+ "label": "Revisar cambios de archivos en productos ya en venta",+ "help": "Cuando un vendedor añade o reemplaza un archivo en un producto aprobado, este vuelve a revisión y deja de venderse hasta que lo apruebe de nuevo. No hace nada cuando los productos de vendedores se publican automáticamente."+ },"send_seller_transactional_emails": {"label": "Enviar correos a los vendedores","help": "Envía a los vendedores correos sobre aprobación, productos y pagos. Desactivalo si les escribís vos mismo a tus vendedores. Los correos a clientes no cambian."diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex c146aa8985..955d6f4e20 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -2321,6 +2321,19 @@"label": "Publier les produits des vendeurs automatiquement","help": "Le produit d’un vendeur est mis en vente dès qu’il le soumet, sans que personne ne l’examine."},+ "seller_digital_assets_enabled": {+ "label": "Autoriser les vendeurs à téléverser des fichiers numériques",+ "help": "Les vendeurs joignent des fichiers téléchargeables à leurs propres produits et en fixent les limites de téléchargement. Désactivé, vous seul pouvez ajouter des fichiers, et les vendeurs voient ceux que vous avez ajoutés."+ },+ "seller_digital_asset_content_types": {+ "label": "Types de fichiers acceptés pour les vendeurs",+ "help": "Un type de contenu par ligne, par exemple application/pdf. Jugé d’après les octets du fichier, pas son nom. Vos propres téléversements ne sont pas restreints.",+ "placeholder": "application/pdf\napplication/zip\naudio/mpeg"+ },+ "review_seller_digital_asset_changes": {+ "label": "Réexaminer les changements de fichiers sur les produits déjà en vente",+ "help": "Quand un vendeur ajoute ou remplace un fichier sur un produit approuvé, celui-ci repasse en révision et sort de la vente jusqu’à ce que vous l’approuviez de nouveau. Sans effet quand les produits des vendeurs sont publiés automatiquement."+ },"send_seller_transactional_emails": {"label": "Envoyer des e-mails aux vendeurs","help": "Envoie aux vendeurs les e-mails sur la validation, les produits et les paiements. Désactivez si vous écrivez vous-même à vos vendeurs. Les e-mails clients ne sont pas concernés."@@ -4312,6 +4325,8 @@"payouts_description": "Comment et quand cette marketplace paie ses vendeurs. Un vendeur peut avoir sa propre fréquence et son propre minimum.","admission_title": "Validation des vendeurs","admission_description": "Activer l’une de ces options supprime une décision humaine. Acceptable sur une marketplace sur invitation, risqué sur une marketplace ouverte à tous.",+ "seller_files_title": "Fichiers des vendeurs",+ "seller_files_description": "Si les vendeurs peuvent joindre des fichiers téléchargeables à leurs produits, de quels types, et si changer un fichier sur un produit approuvé demande un nouvel examen.","communication_title": "Communication","commission_tax_title": "Taxe sur la commission"},diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex 5e8cd65307..d7363414aa 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -2339,6 +2339,19 @@"label": "Publikuj produkty sprzedawców automatycznie","help": "Produkt sprzedawcy trafia do sprzedaży zaraz po zgłoszeniu, bez weryfikacji przez nikogo."},+ "seller_digital_assets_enabled": {+ "label": "Pozwól sprzedawcom przesyłać pliki cyfrowe",+ "help": "Sprzedawcy dołączają pliki do pobrania do własnych produktów i ustawiają limity pobrań. Gdy wyłączone, tylko Ty możesz dodawać pliki, a sprzedawcy widzą te, które dodałeś."+ },+ "seller_digital_asset_content_types": {+ "label": "Akceptowane typy plików dla sprzedawców",+ "help": "Jeden typ zawartości w wierszu, na przykład application/pdf. Oceniany na podstawie bajtów pliku, nie jego nazwy. Twoje własne pliki nie podlegają ograniczeniom.",+ "placeholder": "application/pdf\napplication/zip\naudio/mpeg"+ },+ "review_seller_digital_asset_changes": {+ "label": "Weryfikuj zmiany plików w produktach już w sprzedaży",+ "help": "Gdy sprzedawca doda lub zastąpi plik w zatwierdzonym produkcie, produkt wraca do weryfikacji i znika ze sprzedaży do ponownego zatwierdzenia. Nie działa, gdy produkty sprzedawców publikują się automatycznie."+ },"send_seller_transactional_emails": {"label": "Wysyłaj e-maile do sprzedawców","help": "Wysyła sprzedawcom e-maile o zatwierdzeniu, produktach i wypłatach. Wyłącz, jeśli piszesz do sprzedawców samodzielnie. Nie wpływa to na e-maile do klientów."@@ -4367,6 +4380,8 @@"payouts_description": "Jak i kiedy ten marketplace płaci swoim sprzedawcom. Sprzedawca może mieć własny harmonogram i własną kwotę minimalną.","admission_title": "Zatwierdzanie sprzedawców","admission_description": "Włączenie którejkolwiek z tych opcji usuwa decyzję człowieka. To w porządku na marketplace tylko na zaproszenie, ale ryzykowne tam, gdzie dołączyć może każdy.",+ "seller_files_title": "Pliki sprzedawców",+ "seller_files_description": "Czy sprzedawcy mogą dołączać pliki do pobrania do swoich produktów, jakiego rodzaju, i czy zmiana pliku w zatwierdzonym produkcie wymaga ponownej weryfikacji.","communication_title": "Komunikacja","commission_tax_title": "Podatek od prowizji"},diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex 1e83371384..41a143d59c 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -2316,6 +2316,19 @@"label": "自动发布卖家商品","help": "卖家提交后商品立即上架销售,无需任何人审核。"},+ "seller_digital_assets_enabled": {+ "label": "允许卖家上传数字文件",+ "help": "卖家可为自己的商品附加可下载文件并设置下载限制。关闭后,只有您可以添加文件,卖家只能看到您添加的文件。"+ },+ "seller_digital_asset_content_types": {+ "label": "卖家可上传的文件类型",+ "help": "每行一个内容类型,例如 application/pdf。按文件内容而非文件名判断。您自己的上传不受限制。",+ "placeholder": "application/pdf\napplication/zip\naudio/mpeg"+ },+ "review_seller_digital_asset_changes": {+ "label": "审核在售商品的文件变更",+ "help": "卖家在已批准的商品上添加或替换文件时,商品将重新进入审核并下架,直到您再次批准。卖家商品自动发布时此项无效。"+ },"send_seller_transactional_emails": {"label": "向卖家发送邮件","help": "向卖家发送关于审核、商品和付款的邮件。如果你自行联系卖家,可以关闭。不影响发给顾客的邮件。"@@ -4300,6 +4313,8 @@"payouts_description": "本平台如何以及何时向卖家付款。卖家也可以使用自己的付款周期和最低金额。","admission_title": "卖家审核","admission_description": "开启其中任一项都会取消一次人工判断。仅限邀请的平台没问题,但对人人可加入的平台有风险。",+ "seller_files_title": "卖家文件",+ "seller_files_description": "卖家是否可以为商品附加可下载文件、允许哪些类型,以及在已批准商品上更改文件是否需要再次审核。","communication_title": "沟通","commission_tax_title": "佣金税"},diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/marketplace.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/marketplace.tsxindex 82134c9627..6fa034bc43 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/marketplace.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/marketplace.tsx@@ -36,6 +36,7 @@ import {SelectValue,Skeleton,Switch,+ Textarea,toastManager,useFormSubmitShortcut,} from '@spree/dashboard-ui'@@ -57,6 +58,7 @@ import {useUpdateStoreSettings,} from '../../../../hooks/use-store-settings'import {+ contentTypesFromLines,type MarketplaceSettingsFormValues,marketplaceSettingsFormSchema,} from '../../../../schemas/marketplace'@@ -102,6 +104,11 @@ function MarketplaceSettingsPage({ store }: { store: Store }) {default_minimum_payout_amount: String(store.default_minimum_payout_amount ?? '0'),auto_approve_sellers: store.auto_approve_sellers ?? false,auto_approve_seller_products: store.auto_approve_seller_products ?? false,+ seller_digital_assets_enabled: store.seller_digital_assets_enabled ?? false,+ seller_digital_asset_content_types: (store.seller_digital_asset_content_types ?? []).join(+ '\n',+ ),+ review_seller_digital_asset_changes: store.review_seller_digital_asset_changes ?? true,send_seller_transactional_emails: store.send_seller_transactional_emails ?? true,commission_tax_rate_percentage:fractionToPercent(String(store.default_commission_tax_rate ?? '')) || '0',@@ -157,6 +164,11 @@ function MarketplaceSettingsPage({ store }: { store: Store }) {default_minimum_payout_amount: values.default_minimum_payout_amount,auto_approve_sellers: values.auto_approve_sellers,auto_approve_seller_products: values.auto_approve_seller_products,+ seller_digital_assets_enabled: values.seller_digital_assets_enabled,+ seller_digital_asset_content_types: contentTypesFromLines(+ values.seller_digital_asset_content_types,+ ),+ review_seller_digital_asset_changes: values.review_seller_digital_asset_changes,send_seller_transactional_emails: values.send_seller_transactional_emails,default_commission_tax_rate: percentToFraction(values.commission_tax_rate_percentage),})@@ -346,6 +358,52 @@ function MarketplaceSettingsPage({ store }: { store: Store }) {</CardContent></Card>+ <Card>+ <CardHeader>+ <CardTitle>{t('admin.pages.settings.marketplace.seller_files_title')}</CardTitle>+ <CardDescription>+ {t('admin.pages.settings.marketplace.seller_files_description')}+ </CardDescription>+ </CardHeader>+ <CardContent>+ <FieldGroup>+ <SwitchField+ id="marketplace-seller-digital-assets"+ label={t('admin.fields.store.seller_digital_assets_enabled.label')}+ help={t('admin.fields.store.seller_digital_assets_enabled.help')}+ name="seller_digital_assets_enabled"+ control={form.control}+ />+ <Field>+ <FieldLabel htmlFor="marketplace-seller-content-types">+ {t('admin.fields.store.seller_digital_asset_content_types.label')}+ </FieldLabel>+ <Textarea+ id="marketplace-seller-content-types"+ rows={6}+ className="font-mono text-xs"+ placeholder={t(+ 'admin.fields.store.seller_digital_asset_content_types.placeholder',+ )}+ aria-invalid={!!errors.seller_digital_asset_content_types}+ {...form.register('seller_digital_asset_content_types')}+ />+ <FieldDescription>+ {t('admin.fields.store.seller_digital_asset_content_types.help')}+ </FieldDescription>+ <FieldError errors={[errors.seller_digital_asset_content_types]} />+ </Field>+ <SwitchField+ id="marketplace-review-seller-file-changes"+ label={t('admin.fields.store.review_seller_digital_asset_changes.label')}+ help={t('admin.fields.store.review_seller_digital_asset_changes.help')}+ name="review_seller_digital_asset_changes"+ control={form.control}+ />+ </FieldGroup>+ </CardContent>+ </Card>+<Card><CardHeader><CardTitle>{t('admin.pages.settings.marketplace.communication_title')}</CardTitle>diff --git a/packages/dashboard/src/schemas/marketplace.ts b/packages/dashboard/src/schemas/marketplace.tsindex a9832cd13e..fa1f2f38c4 100644--- a/packages/dashboard/src/schemas/marketplace.ts+++ b/packages/dashboard/src/schemas/marketplace.ts@@ -15,6 +15,10 @@ export const marketplaceSettingsFormSchema = z.object({default_minimum_payout_amount: nonNegativeDecimal,auto_approve_sellers: z.boolean(),auto_approve_seller_products: z.boolean(),+ seller_digital_assets_enabled: z.boolean(),+ // One content type per line in the form; sent as a list.+ seller_digital_asset_content_types: z.string(),+ review_seller_digital_asset_changes: z.boolean(),send_seller_transactional_emails: z.boolean(),// A percentage, because that is how a merchant states a VAT rate. The// preference behind it is a fraction bounded at 1, so the field is bounded@@ -25,3 +29,11 @@ export const marketplaceSettingsFormSchema = z.object({})export type MarketplaceSettingsFormValues = z.infer<typeof marketplaceSettingsFormSchema>++/** The textarea's lines as the list the API stores, blank lines dropped. */+export function contentTypesFromLines(value: string): string[] {+ return value+ .split(/[\n,]/)+ .map((line) => line.trim().toLowerCase())+ .filter(Boolean)+}diff --git a/packages/seller-dashboard/src/pages/product.tsx b/packages/seller-dashboard/src/pages/product.tsxindex 8c60d6502c..8a18bd0d23 100644--- a/packages/seller-dashboard/src/pages/product.tsx+++ b/packages/seller-dashboard/src/pages/product.tsx@@ -33,6 +33,7 @@ import { sellerClient } from '../api-client'import { CenteredMessage } from '../components/centered-message'import { ProductStatusCard } from '../components/product-status-card'import { RetryableError } from '../components/retryable-error'+import { useAccount } from '../hooks/use-account'/** Everything the form edits, in one request. */const PRODUCT_EXPAND = [@@ -99,6 +100,9 @@ export function ProductPage({ mode }: { mode: 'new' | 'edit' }) {})const assignableVariants = useAssignableVariants(form.control, product?.variants)+ // Whether this marketplace lets sellers upload files, and of which types,+ // comes with the account the panel already holds.+ const marketplace = useAccount().data?.store// Reset once the record arrives, so the inputs show what was last saved// rather than the blank defaults the form mounted with.@@ -257,7 +261,12 @@ export function ProductPage({ mode }: { mode: 'new' | 'edit' }) {defaultCurrency={profile?.default_currency}/><InventoryCard form={form} />- <DigitalAssetsCard productId={productId} variants={assignableVariants} />+ <DigitalAssetsCard+ productId={productId}+ variants={assignableVariants}+ readOnly={!marketplace?.seller_digital_assets_enabled}+ accept={marketplace?.seller_digital_asset_content_types}+ /><Slot name="seller.product.form_main" context={{ product, mode }} /></>}diff --git a/packages/seller-sdk/src/seller-client.ts b/packages/seller-sdk/src/seller-client.tsindex 60c2e0187c..3bb3fdcb54 100644--- a/packages/seller-sdk/src/seller-client.ts+++ b/packages/seller-sdk/src/seller-client.ts@@ -45,6 +45,7 @@ import type {SellerSummary,ShippingLabel,StockLocation,+ Store,TaxIdentifier,TeamMember,Transfer,@@ -1541,6 +1542,11 @@ export interface MeResponse {*/user: Accountsellers: SellerSummary[]+ /**+ * The marketplace's own settings that shape what the panel lets a seller+ * do — whether sellers may upload digital files, and of which types.+ */+ store: Store/** Empty until a seller is named — capability is per seller. */permissions: PermissionRule[]permission_keys: string[]diff --git a/packages/seller-sdk/src/types/generated/Store.ts b/packages/seller-sdk/src/types/generated/Store.tsnew file mode 100644index 0000000000..0d23a628f0--- /dev/null+++ b/packages/seller-sdk/src/types/generated/Store.ts@@ -0,0 +1,12 @@+// Typelizer digest e968e05312ca7f559c414474d1b3657e+//+// DO NOT MODIFY: This file was automatically generated by Typelizer.++type Store = {+ id: string;+ name: string;+ seller_digital_assets_enabled: boolean;+ seller_digital_asset_content_types: Array<string>;+}++export default Store;diff --git a/packages/seller-sdk/src/types/generated/index.ts b/packages/seller-sdk/src/types/generated/index.tsindex 9fc529143a..57ee994a41 100644--- a/packages/seller-sdk/src/types/generated/index.ts+++ b/packages/seller-sdk/src/types/generated/index.ts@@ -1,4 +1,4 @@-// Typelizer digest 641d89230378c944e97f7ffd97f1f2dc+// Typelizer digest 97da2d7b7854cdc75e53cded012ea3c7//// DO NOT MODIFY: This file was automatically generated by Typelizer.export type { ClaimResolution, ClaimStatus, CountryCode, CurrencyCode, DeliveryStatus, DimensionUnit, ExchangeStatus, FileUploadVisibility, FulfillmentStatus, ImportRowStatus, ImportStatus, InvitationStatus, MediaType, OptionTypeKind, OrderFulfillmentStatus, OrderPaymentStatus, OrderStatus, PackageTypeKind, PayoutScheduleInterval, ProductStatus, ProductSubmissionStatus, PurchaseUnit, ReturnStatus, SellerRequirementState, SellerRequirementSubmissionStatus, SellerStatus, ShippingLabelFormat, ShippingLabelOwnerType, ShippingLabelSource, ShippingLabelStatus, StockLocationKind, TaxIdentifierValidationStatus, TaxRemittance, WeightUnit } from './Enums'@@ -54,6 +54,7 @@ export type { default as ShippingLabel } from './ShippingLabel'export type { default as State } from './State'export type { default as StockLevel } from './StockLevel'export type { default as StockLocation } from './StockLocation'+export type { default as Store } from './Store'export type { default as TaxIdentifier } from './TaxIdentifier'export type { default as TeamMember } from './TeamMember'export type { default as Transfer } from './Transfer'diff --git a/packages/seller-sdk/src/types/params/DigitalAssetCreateParams.ts b/packages/seller-sdk/src/types/params/DigitalAssetCreateParams.tsindex e0661401cb..7615e090a8 100644--- a/packages/seller-sdk/src/types/params/DigitalAssetCreateParams.ts+++ b/packages/seller-sdk/src/types/params/DigitalAssetCreateParams.ts@@ -3,7 +3,8 @@export type DigitalAssetCreateParams = {/*** A `signed_id` from `files.upload()` with `visibility: 'private'`. On update it replaces the- * file for everyone who already bought it.+ * file for everyone who already bought it. A seller's file must be of a content type the+ * marketplace accepts, judged from its bytes.*/signed_id: string/**diff --git a/packages/seller-sdk/src/types/params/DigitalAssetUpdateParams.ts b/packages/seller-sdk/src/types/params/DigitalAssetUpdateParams.tsindex a108435422..a6e9420ba4 100644--- a/packages/seller-sdk/src/types/params/DigitalAssetUpdateParams.ts+++ b/packages/seller-sdk/src/types/params/DigitalAssetUpdateParams.ts@@ -3,7 +3,8 @@export type DigitalAssetUpdateParams = {/*** A `signed_id` from `files.upload()` with `visibility: 'private'`. On update it replaces the- * file for everyone who already bought it.+ * file for everyone who already bought it. A seller's file must be of a content type the+ * marketplace accepts, judged from its bytes.*/signed_id?: string/**diff --git a/packages/seller-sdk/src/zod/generated/Store.ts b/packages/seller-sdk/src/zod/generated/Store.tsnew file mode 100644index 0000000000..20d5073306--- /dev/null+++ b/packages/seller-sdk/src/zod/generated/Store.ts@@ -0,0 +1,11 @@+// This file is auto-generated. Do not edit directly.+import { z } from 'zod';++export const StoreSchema = z.object({+ id: z.string(),+ name: z.string(),+ seller_digital_assets_enabled: z.boolean(),+ seller_digital_asset_content_types: z.array(z.string()),+});++export type Store = z.infer<typeof StoreSchema>;diff --git a/packages/seller-sdk/src/zod/generated/index.ts b/packages/seller-sdk/src/zod/generated/index.tsindex 88cf1271e8..1314539d6b 100644--- a/packages/seller-sdk/src/zod/generated/index.ts+++ b/packages/seller-sdk/src/zod/generated/index.ts@@ -52,6 +52,7 @@ export { ShippingLabelSchema, type ShippingLabel } from './ShippingLabel';export { StateSchema, type State } from './State';export { StockLevelSchema, type StockLevel } from './StockLevel';export { StockLocationSchema, type StockLocation } from './StockLocation';+export { StoreSchema, type Store } from './Store';export { TaxIdentifierSchema, type TaxIdentifier } from './TaxIdentifier';export { TeamMemberSchema, type TeamMember } from './TeamMember';export { TransferSchema, type Transfer } from './Transfer';diff --git a/spree/api/app/controllers/concerns/spree/api/v3/digital_asset_writes.rb b/spree/api/app/controllers/concerns/spree/api/v3/digital_asset_writes.rbdeleted file mode 100644index bdd22c5cce..0000000000--- a/spree/api/app/controllers/concerns/spree/api/v3/digital_asset_writes.rb+++ /dev/null@@ -1,103 +0,0 @@-module Spree- module Api- module V3- # The downloadable files on one product, shared by the operator's and a- # seller's branch. Each includer finds and authorizes the product in- # `set_parent` and names its serializer.- module DigitalAssetWrites- extend ActiveSupport::Concern-- # PATCH .../products/:product_id/digital_assets/:id- #- # Replacing the file keeps every already-issued link working, since- # links resolve through the asset rather than the blob.- def update- return render_private_storage_error unless uploaded_blob_private?-- # The asset already exists, so attaching a replacement blob writes- # to the database immediately, while the update below renders a 422- # without raising when it fails. Wrap both so a failed update rolls- # the new attachment back rather than leaving the file swapped but- # the record unchanged.- model_class.transaction do- @resource.variant = requested_variant if params[:variant_id].present?- attach_uploaded_file(@resource)-- super-- raise ActiveRecord::Rollback if @resource.errors.any?- end- end-- # POST .../products/:product_id/digital_assets- def create- return render_private_storage_error unless uploaded_blob_private?-- super- end-- protected-- def model_class- Spree::DigitalAsset- end-- # Assets reach the product through `variants`, whose ORDER BY- # PostgreSQL rejects alongside the collection's DISTINCT.- def scope- super.reorder(created_at: :asc)- end-- def scope_includes- [:variant, { attachment_attachment: :blob }]- end-- # Not normalized: `provider_settings` may hold values shaped like- # prefixed ids.- def permitted_params- params.permit(*declared_permitted_attributes, *model_additional_permitted_attributes)- end-- private-- # A product without explicit variants keeps its file on the default- # variant, mirroring how the rest of the panels treat such products.- def build_resource- digital_asset = super- digital_asset.variant = requested_variant || @parent.default_variant- attach_uploaded_file(digital_asset)- digital_asset- end-- # Scoped to the parent, not merely to the store: an asset reached- # through a product's route has no business pointing at another- # product's variant. An id from anywhere else is a 404.- def requested_variant- return if params[:variant_id].blank?-- @parent.variants.find_by_prefix_id!(params[:variant_id])- end-- def attach_uploaded_file(digital_asset)- return if params[:signed_id].blank?-- digital_asset.attachment.attach(params[:signed_id])- end-- # Attaching never moves a blob between storage services, so a file- # uploaded to the public bucket would stay publicly readable while- # looking attached. Refuse it rather than storing it wrongly.- def uploaded_blob_private?- return true if params[:signed_id].blank?-- blob = ActiveStorage::Blob.find_signed(params[:signed_id])- blob.present? && blob.service_name.to_s == Spree.private_storage_service_name.to_s- end-- def render_private_storage_error- render_validation_error(I18n.t('spree.digital_assets_attachment_must_be_private'))- end- end- end- end-enddiff --git a/spree/api/app/controllers/concerns/spree/api/v3/digital_assets_resource.rb b/spree/api/app/controllers/concerns/spree/api/v3/digital_assets_resource.rbnew file mode 100644index 0000000000..caef71dd40--- /dev/null+++ b/spree/api/app/controllers/concerns/spree/api/v3/digital_assets_resource.rb@@ -0,0 +1,68 @@+module Spree+ module Api+ module V3+ # The downloadable files on one product, shared by the operator's and a+ # seller's branch. Writes run through the digital asset workflows; each+ # includer finds and authorizes the product in `set_parent`, names its+ # serializer, and may add to the workflow arguments.+ module DigitalAssetsResource+ extend ActiveSupport::Concern++ protected++ def model_class+ Spree::DigitalAsset+ end++ # Assets reach the product through `variants`, whose ORDER BY+ # PostgreSQL rejects alongside the collection's DISTINCT.+ def scope+ super.reorder(created_at: :asc)+ end++ def scope_includes+ [:variant, { attachment_attachment: :blob }]+ end++ # Not normalized: `provider_settings` may hold values shaped like+ # prefixed ids.+ def permitted_params+ params.permit(*declared_permitted_attributes, *model_additional_permitted_attributes)+ end++ def create_workflow+ Spree.digital_asset_create_workflow+ end++ def update_workflow+ Spree.digital_asset_update_workflow+ end++ # An asset belongs to a variant, not directly to a store; the workflow+ # resolves the variant through the product.+ def create_workflow_arguments+ { product: @parent, attributes: workflow_attributes }+ end++ def update_workflow_arguments+ { digital_asset: @resource, attributes: workflow_attributes }+ end++ private++ # `signed_id` and `variant_id` are declared `permit: false` because+ # neither is a column: the workflow attaches the one and resolves the+ # other through the product, so they travel beside the attributes.+ def workflow_attributes+ permitted_params.to_h.merge(params.permit(:signed_id, :variant_id).to_h)+ end++ # Only authorized, never saved: the workflow builds the record it+ # writes. The variant is what an ability's conditions read.+ def build_resource+ model_class.new(variant: @parent.default_variant)+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/admin/products/digital_assets_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/products/digital_assets_controller.rbindex e25c7403a7..7bafc5dc49 100644--- a/spree/api/app/controllers/spree/api/v3/admin/products/digital_assets_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/products/digital_assets_controller.rb@@ -4,7 +4,7 @@ module Spreemodule Adminmodule Productsclass DigitalAssetsController < ResourceController- include Spree::Api::V3::DigitalAssetWrites+ include Spree::Api::V3::DigitalAssetsResourcescoped_resource :productsdiff --git a/spree/api/app/controllers/spree/api/v3/admin/store_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/store_controller.rbindex c5017b490a..47270d858b 100644--- a/spree/api/app/controllers/spree/api/v3/admin/store_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/store_controller.rb@@ -65,6 +65,13 @@ module Spreedescription: 'Admits a seller as soon as they finish onboarding, with no operator review.'body.attribute :auto_approve_seller_products, :boolean,description: 'Puts a seller product on sale the moment it is submitted, with no review.'+ body.attribute :seller_digital_assets_enabled, :boolean,+ description: 'Lets sellers attach downloadable files to their own products.'+ body.attribute :seller_digital_asset_content_types, :array, of: :string,+ example: %w[application/pdf application/zip],+ description: "The content types a seller's file may have, judged from its bytes. The operator's own uploads are not restricted."+ body.attribute :review_seller_digital_asset_changes, :boolean,+ description: 'Sends a seller product already on sale back to review when the seller adds or replaces a file on it.'body.attribute :send_seller_transactional_emails, :boolean,description: 'When false, transactional seller emails (approval, payouts and so on) are not sent.'body.attribute :default_commission_tax_rate, :decimal,diff --git a/spree/api/app/controllers/spree/api/v3/seller/me_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/me_controller.rbindex 8b594690fe..f366738ed9 100644--- a/spree/api/app/controllers/spree/api/v3/seller/me_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/seller/me_controller.rb@@ -58,6 +58,10 @@ module Spree{user: Spree.api.seller_account_serializer.new(current_user, params: serializer_params).to_h,sellers: serialized_sellers,+ # The marketplace's own settings that shape what the panel lets a+ # seller do, read before any seller is chosen since there is one+ # store per installation.+ store: Spree.api.seller_store_serializer.new(current_store, params: serializer_params).to_h,# Both shapes, exactly as the admin `/me`: the panel's `<Can>`# reads CanCanCan rules, the key gate reads keys. Sending only# keys left `<Can>` answering false for everything on the sellerdiff --git a/spree/api/app/controllers/spree/api/v3/seller/products/digital_assets_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/products/digital_assets_controller.rbindex 283e48aec7..a45bd2e702 100644--- a/spree/api/app/controllers/spree/api/v3/seller/products/digital_assets_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/seller/products/digital_assets_controller.rb@@ -10,8 +10,13 @@ module Spree# one nor read its settings. An asset the operator set up with one# is still listed, since it is part of what the seller's product# delivers.+ #+ # The marketplace's rules for a seller's file — whether sellers may+ # upload at all, which content types, and whether an approved+ # listing goes back to review — apply because the workflow is told+ # who is writing.class DigitalAssetsController < Seller::ResourceController- include Spree::Api::V3::DigitalAssetWrites+ include Spree::Api::V3::DigitalAssetsResourcescoped_resource :products@@ -20,24 +25,20 @@ module Spreebody.require_attributes :signed_id, on: :createend- # PATCH /api/v3/seller/products/:product_id/digital_assets/:id- #- # A provider-backed asset delivers through the operator's provider,- # so a file attached to it would show here but never reach a buyer.- def update- if params[:signed_id].present? && [email protected]_class.requires_attachment?- return render_validation_error(I18n.t('spree.digital_assets_provider_takes_no_file'))- end-- super- end-protecteddef serializer_classSpree.api.seller_digital_asset_serializerend+ def create_workflow_arguments+ super.merge(seller: current_seller, submitted_by: current_user)+ end++ def update_workflow_arguments+ super.merge(seller: current_seller, submitted_by: current_user)+ end+# Rooted in the seller's own catalog, so another seller's product# is a 404. Changing a product's files is a change to the product,# so writes need `:update` on it, not just `:show`.diff --git a/spree/api/app/request_schemas/spree/api/v3/digital_asset_request_schema.rb b/spree/api/app/request_schemas/spree/api/v3/digital_asset_request_schema.rbindex 0f9561f6e7..af8ad811bd 100644--- a/spree/api/app/request_schemas/spree/api/v3/digital_asset_request_schema.rb+++ b/spree/api/app/request_schemas/spree/api/v3/digital_asset_request_schema.rb@@ -7,7 +7,7 @@ module Spree# Names a blob rather than a column, so it is attached separately.attribute :signed_id, :string,permit: false,- description: "A `signed_id` from `files.upload()` with `visibility: 'private'`. On update it replaces the file for everyone who already bought it."+ description: "A `signed_id` from `files.upload()` with `visibility: 'private'`. On update it replaces the file for everyone who already bought it. A seller's file must be of a content type the marketplace accepts, judged from its bytes."# Resolved through the parent rather than assigned, so an asset can't# be pointed at a variant of another product or store.attribute :variant_id, :id,diff --git a/spree/api/app/serializers/spree/api/v3/base_serializer.rb b/spree/api/app/serializers/spree/api/v3/base_serializer.rbindex 21c899f7d8..78c6ce8b0d 100644--- a/spree/api/app/serializers/spree/api/v3/base_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/base_serializer.rb@@ -154,9 +154,14 @@ module Spreedef self.preference_type_hint(schema, name)types = Array(schema['type'])- hint = TYPELIZER_TYPES.fetch((types - ['null']).first, :unknown)options = {}options[:nullable] = true if types.include?('null')+ if types.include?('array')+ hint = TYPELIZER_TYPES.fetch(Array(schema.dig('items', 'type')).first, :unknown)+ options[:multi] = true+ else+ hint = TYPELIZER_TYPES.fetch((types - ['null']).first, :unknown)+ endif schema['enum']options[:enum] = schema['enum'].compactoptions[:enum_type_name] = PREFERENCE_LIST_NAMES[name.to_sym] if PREFERENCE_LIST_NAMES.key?(name.to_sym)diff --git a/spree/api/app/serializers/spree/api/v3/seller/store_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/store_serializer.rbnew file mode 100644index 0000000000..b077d5d419--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/seller/store_serializer.rb@@ -0,0 +1,17 @@+module Spree+ module Api+ module V3+ module Seller+ # What a seller may know about the marketplace they sell on: its name,+ # and the settings that shape what the panel lets them do.+ class StoreSerializer < V3::BaseSerializer+ typelize name: :string++ attributes :name++ preference_attributes Spree::Store, :seller_digital_assets_enabled, :seller_digital_asset_content_types+ end+ end+ end+ end+enddiff --git a/spree/api/lib/spree/api/dependencies.rb b/spree/api/lib/spree/api/dependencies.rbindex 9ceb8e3b3a..c1e56bc063 100644--- a/spree/api/lib/spree/api/dependencies.rb+++ b/spree/api/lib/spree/api/dependencies.rb@@ -52,7 +52,7 @@ module Spreereturn_line_item exchange exchange_line_item claim claim_line_item reason package_type stock_locationrequirement_custom_field tax_identifier requirement_status import import_row import_mappingrequirement_submission export transfer payout balance payment_split price price_history file_upload digital_asset- file_upload_target].freeze+ file_upload_target store].freezeINJECTION_POINTS_WITH_DEFAULTS = {**STORE_SERIALIZERS.to_h { |name| [:"#{name}_serializer", "Spree::Api::V3::#{name.to_s.camelize}Serializer"] },diff --git a/spree/api/lib/spree/api/openapi/schema_helper.rb b/spree/api/lib/spree/api/openapi/schema_helper.rbindex e60069448e..f3f664e44e 100644--- a/spree/api/lib/spree/api/openapi/schema_helper.rb+++ b/spree/api/lib/spree/api/openapi/schema_helper.rb@@ -329,6 +329,7 @@ module Spree# team list does not publish about a colleague.user: { '$ref' => '#/components/schemas/Account' },sellers: { type: :array, items: { '$ref' => '#/components/schemas/SellerMeSummary' } },+ store: { '$ref' => '#/components/schemas/Store' },permissions: { type: :array, items: { '$ref' => '#/components/schemas/PermissionRule' } },permission_keys: {type: :array,@@ -337,7 +338,7 @@ module Spreeexample: %w[read_products write_products]}},- required: %w[user sellers permissions permission_keys]+ required: %w[user sellers store permissions permission_keys]},OnboardingProgress: {type: :object,diff --git a/spree/api/spec/controllers/spree/api/v3/seller/products/digital_assets_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/seller/products/digital_assets_controller_spec.rbindex 076805390b..2046a1a144 100644--- a/spree/api/spec/controllers/spree/api/v3/seller/products/digital_assets_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/seller/products/digital_assets_controller_spec.rb@@ -1,9 +1,9 @@require 'spec_helper'-# The writes themselves are shared with the operator's endpoint-# (Spree::Api::V3::DigitalAssetWrites, covered by the admin controller spec);-# this covers what the seller branch adds: tenancy, the seller's role, and-# that providers stay the operator's.+# The writes themselves run through the digital asset workflows (covered by+# their own spec and the admin controller spec); this covers what the seller+# branch adds: tenancy, the seller's role, the marketplace's rules for a+# seller's file, and that providers stay the operator's.RSpec.describe Spree::Api::V3::Seller::Products::DigitalAssetsController, type: :controller dorender_views@@ -22,7 +22,10 @@ RSpec.describe Spree::Api::V3::Seller::Products::DigitalAssetsController, type:)end- before { request.headers.merge!(headers) }+ before do+ request.headers.merge!(headers)+ stub_store_preferences(seller_digital_assets_enabled: true)+ enddescribe 'GET #index' dolet!(:digital_asset) { create(:digital_asset, variant: variant, authorized_clicks: 5) }@@ -74,6 +77,13 @@ RSpec.describe Spree::Api::V3::Seller::Products::DigitalAssetsController, type:'authorized_clicks' => 3, 'authorized_days' => 30)end+ it 'refuses an upload it cannot find' do+ post :create, params: { product_id: product.prefixed_id, signed_id: 'expired' }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ expect(response.parsed_body.dig('error', 'message')).to match(/could not be found/)+ end+it "refuses a variant of another seller's product" dotheirs = create(:product, seller: other_seller, store: store)@@ -171,6 +181,92 @@ RSpec.describe Spree::Api::V3::Seller::Products::DigitalAssetsController, type:endend+ describe "the marketplace's rules for a seller's file" do+ it 'refuses every file when the marketplace has not opened uploads to sellers' do+ stub_store_preferences(seller_digital_assets_enabled: false)++ post :create, params: { product_id: product.prefixed_id, signed_id: blob.signed_id }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ expect(response.parsed_body.dig('error', 'message')).to match(/does not accept files uploaded by sellers/)+ expect(Spree::DigitalAsset.count).to eq(0)+ end++ # The blob declares itself a generic binary; its bytes are a JPEG, and the+ # bytes are what the rule reads.+ it 'judges the content type from the bytes against the accepted list' do+ stub_store_preferences(seller_digital_asset_content_types: %w[application/pdf])++ post :create, params: { product_id: product.prefixed_id, signed_id: blob.signed_id }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ expect(response.parsed_body.dig('error', 'message')).to match(%r{image/jpeg files are not accepted})+ expect(Spree::DigitalAsset.count).to eq(0)+ end++ it 'leaves the limits editable when the type is no longer accepted' do+ digital_asset = create(:digital_asset, variant: variant)+ stub_store_preferences(seller_digital_asset_content_types: %w[application/pdf])++ patch :update, params: { product_id: product.prefixed_id, id: digital_asset.prefixed_id, authorized_clicks: 2 }, as: :json++ expect(response).to have_http_status(:ok)+ expect(digital_asset.reload.authorized_clicks).to eq(2)+ end++ context 'on a listing already on sale' do+ before { product.update!(status: 'active') }++ it 'sends the product back to review when a file is added, naming who did it and why' do+ post :create, params: { product_id: product.prefixed_id, signed_id: blob.signed_id }, as: :json++ expect(response).to have_http_status(:created)+ expect(product.reload).to be_proposed+ submission = product.submissions.latest_first.first+ expect(submission.status).to eq('pending')+ expect(submission.submitted_by).to eq(seller_user)+ expect(submission.metadata).to include('reason' => 'digital_asset_changed')+ end++ it 'sends the product back to review when a file is replaced' do+ digital_asset = create(:digital_asset, variant: variant)++ patch :update, params: { product_id: product.prefixed_id, id: digital_asset.prefixed_id, signed_id: blob.signed_id }, as: :json++ expect(response).to have_http_status(:ok)+ expect(product.reload).to be_proposed+ end++ it 'leaves the product on sale when only the limits change' do+ digital_asset = create(:digital_asset, variant: variant)++ patch :update, params: { product_id: product.prefixed_id, id: digital_asset.prefixed_id, authorized_clicks: 2 }, as: :json++ expect(response).to have_http_status(:ok)+ expect(product.reload).to be_active+ end++ it 'leaves the product on sale when the marketplace does not review file changes' do+ stub_store_preferences(review_seller_digital_asset_changes: false)++ post :create, params: { product_id: product.prefixed_id, signed_id: blob.signed_id }, as: :json++ expect(response).to have_http_status(:created)+ expect(product.reload).to be_active+ end++ it 'leaves the product on sale when the marketplace approves seller products automatically' do+ stub_store_preferences(auto_approve_seller_products: true)++ post :create, params: { product_id: product.prefixed_id, signed_id: blob.signed_id }, as: :json++ expect(response).to have_http_status(:created)+ expect(product.reload).to be_active+ expect(product.submissions).to be_empty+ end+ end+ end+describe 'DELETE #destroy' dolet!(:digital_asset) { create(:digital_asset, variant: variant) }diff --git a/spree/api/spec/integration/spree/api/v3/seller/products/digital_assets_spec.rb b/spree/api/spec/integration/spree/api/v3/seller/products/digital_assets_spec.rbindex 400365beeb..36c67c59bc 100644--- a/spree/api/spec/integration/spree/api/v3/seller/products/digital_assets_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/seller/products/digital_assets_spec.rb@@ -11,6 +11,9 @@ RSpec.describe 'Seller Product Digital Assets API', type: :request, swagger_doc:let(:'X-Spree-Seller-Id') { seller.prefixed_id }let(:product_id) { product.prefixed_id }+ # The marketplace opens uploads to sellers in its settings; off by default.+ before { stub_store_preferences(seller_digital_assets_enabled: true) }+path '/api/v3/seller/products/{product_id}/digital_assets' doparameter name: :product_id, in: :path, type: :string, required: true, description: 'Product ID'diff --git a/spree/core/app/models/spree/digital_asset.rb b/spree/core/app/models/spree/digital_asset.rbindex 5d6be9027d..7e8f937fb9 100644--- a/spree/core/app/models/spree/digital_asset.rb+++ b/spree/core/app/models/spree/digital_asset.rb@@ -25,6 +25,18 @@ module Spree# and provider-backed assets (which carry no file) are exempt.DEFAULT_PROVIDER = 'Spree::DigitalAssetProvider::File'.freeze+ # What a seller may upload unless the marketplace says otherwise: the+ # formats digital goods usually come in. Executables, scripts and+ # unrecognised binaries are left out on purpose, as is SVG, which can+ # carry scripts. A marketplace selling a niche format adds it in settings.+ DEFAULT_SELLER_CONTENT_TYPES = %w[+ application/pdf application/epub+zip application/zip application/x-7z-compressed application/gzip+ application/json text/plain text/csv+ audio/mpeg audio/mp4 audio/aac audio/flac audio/ogg audio/wav audio/x-wav audio/midi+ video/mp4 video/webm video/quicktime+ image/jpeg image/png image/gif image/webp image/tiff+ ].freeze+# The API names a provider by its shorthand (`file`); the column keeps the# class name.normalizes :provider_type, with: ->(value) { Spree::ApiTyped.class_name_for(Spree.digital_asset_providers, value) }diff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rbindex e814aa37cb..c564ecfdb8 100644--- a/spree/core/app/models/spree/store.rb+++ b/spree/core/app/models/spree/store.rb@@ -78,6 +78,18 @@ module Spree# same reason as auto_approve_sellers: what the marketplace lists is what# it vouches for.preference :auto_approve_seller_products, :boolean, default: false+ # Let sellers attach downloadable files to their own products. Off for the+ # same reason again: a file a buyer downloads under the marketplace's name+ # is something the marketplace vouches for, and that should be a choice.+ preference :seller_digital_assets_enabled, :boolean, default: false+ # What a seller's file may be, judged from its bytes rather than its name.+ # The operator's own uploads are not restricted.+ preference :seller_digital_asset_content_types, :array, of: :string,+ default: Spree::DigitalAsset::DEFAULT_SELLER_CONTENT_TYPES+ # A file added to or replaced on a seller's product already on sale sends+ # the product back to review, so an approved listing cannot change what it+ # delivers without anyone looking. Moot when seller products auto-approve.+ preference :review_seller_digital_asset_changes, :boolean, default: true# Who pays this store's sellers. Blank means core's record-only provider,# so a marketplace that has connected nothing still keeps a correct ledger# and settles by hand.@@ -186,7 +198,8 @@ module Spree:pricing_provider, :inventory_provider, :pricing_provider_failure_policy,:inventory_provider_failure_policy, :payout_provider, :default_payouts_schedule_interval,:default_minimum_payout_amount, :auto_approve_sellers, :auto_approve_seller_products,- :send_seller_transactional_emails, :default_commission_tax_rate, :document_number_format,+ :seller_digital_assets_enabled, :seller_digital_asset_content_types,+ :review_seller_digital_asset_changes, :send_seller_transactional_emails, :default_commission_tax_rate, :document_number_format,:order_number_prefix, :order_number_suffix, :order_number_sequence_start,:limit_digital_download_count, :digital_asset_authorized_clicks,:limit_digital_download_days, :digital_asset_authorized_days,diff --git a/spree/core/app/workflows/spree/digital_assets/create.rb b/spree/core/app/workflows/spree/digital_assets/create.rbnew file mode 100644index 0000000000..83d1da472f--- /dev/null+++ b/spree/core/app/workflows/spree/digital_assets/create.rb@@ -0,0 +1,56 @@+module Spree+ module DigitalAssets+ # Adds a downloadable file (or a provider-backed deliverable) to a product.+ #+ # The single gate for new assets: the operator's and the seller's nested+ # endpoints and the `digital_assets` list on a product write all run+ # through it, so a :validate handler sees every file a catalog gains.+ # A host that scans uploads registers on `digital_assets.create.validate`+ # for a quick check, or on `after_create` to queue a slower one; the bytes+ # are already in storage when either fires.+ #+ # Passing `seller:` applies the marketplace's rules for a seller's file —+ # whether sellers may upload at all, which content types, and whether an+ # approved listing goes back to review. The operator's own writes pass none.+ class Create < Spree::Workflow+ include Spree::DigitalAssets::Writing++ hooks :validate, :after_create++ # The unsaved record a :validate handler reads.+ attr_reader :digital_asset++ # @param product [Spree::Product]+ # @param attributes [Hash] `signed_id`, `variant_id`, the download limits+ # and, for the operator, the provider fields+ # @param seller [Spree::Seller, nil] the seller this file is written for+ # @param submitted_by [Spree.admin_user_class, nil] who made the change,+ # named on the review it may reopen+ # @return [Spree::ServiceModule::Result] value is the digital asset+ def perform(product:, attributes: {}, seller: nil, submitted_by: nil)+ super++ step :build_digital_asset+ step :resolve_upload+ step :enforce_seller_rules+ run_hooks :validate++ ApplicationRecord.transaction do+ step :attach_upload+ step :save_digital_asset+ step :reopen_review+ run_hooks :after_create+ end++ success(digital_asset)+ end++ private++ def build_digital_asset+ @digital_asset = Spree::DigitalAsset.new+ assign_attributes+ end+ end+ end+enddiff --git a/spree/core/app/workflows/spree/digital_assets/update.rb b/spree/core/app/workflows/spree/digital_assets/update.rbnew file mode 100644index 0000000000..d34e8fd639--- /dev/null+++ b/spree/core/app/workflows/spree/digital_assets/update.rb@@ -0,0 +1,44 @@+module Spree+ module DigitalAssets+ # Changes a digital asset: its download limits, the variant it hangs off,+ # or the file itself. Replacing the file keeps every already-issued link+ # working, since links resolve through the asset rather than the blob.+ #+ # Handlers reading `digital_asset.changes` in :validate see the pending+ # edit; `blob` is the replacement file, when the payload carries one.+ class Update < Spree::Workflow+ include Spree::DigitalAssets::Writing++ hooks :validate, :after_update++ # @param digital_asset [Spree::DigitalAsset]+ # @param attributes [Hash] see Spree::DigitalAssets::Create+ # @param seller [Spree::Seller, nil] the seller this change is written for+ # @param submitted_by [Spree.admin_user_class, nil] who made the change+ # @return [Spree::ServiceModule::Result] value is the digital asset+ def perform(digital_asset:, attributes: {}, seller: nil, submitted_by: nil)+ super++ step :assign_attributes+ step :resolve_upload+ step :enforce_seller_rules+ run_hooks :validate++ ApplicationRecord.transaction do+ step :attach_upload+ step :save_digital_asset+ step :reopen_review+ run_hooks :after_update+ end++ success(digital_asset)+ end++ private++ def product+ digital_asset.product+ end+ end+ end+enddiff --git a/spree/core/app/workflows/spree/digital_assets/writing.rb b/spree/core/app/workflows/spree/digital_assets/writing.rbnew file mode 100644index 0000000000..74ed1f39f3--- /dev/null+++ b/spree/core/app/workflows/spree/digital_assets/writing.rb@@ -0,0 +1,98 @@+module Spree+ module DigitalAssets+ # The steps a file write shares between Create and Update: the upload the+ # payload names, the marketplace's rules for a seller's file, and sending+ # an approved listing back to review once what it delivers has changed.+ module Writing+ extend ActiveSupport::Concern++ # Why a product reopened review: recorded on the submission row so the+ # operator's queue says what changed.+ REVIEW_REASON = 'digital_asset_changed'.freeze++ included do+ # The uploaded file the payload names, resolved before it is attached.+ attr_reader :blob+ end++ private++ def assign_attributes+ attrs = attributes.to_h.with_indifferent_access+ @signed_id = attrs.delete(:signed_id)+ variant_id = attrs.delete(:variant_id)++ digital_asset.assign_attributes(attrs)+ # Through the product's own variants, so an asset reached through one+ # product can never point at another product's variant.+ digital_asset.variant = product.variants.find_by_param!(variant_id) if variant_id.present?+ digital_asset.variant ||= product.default_variant+ end++ def resolve_upload+ return if @signed_id.blank?++ @blob = ActiveStorage::Blob.find_signed(@signed_id)+ return refuse(:digital_assets_upload_not_found) if blob.nil?++ # Attaching never moves a blob between storage services, so a file+ # uploaded to the public bucket would stay publicly readable while+ # looking attached.+ unless blob.service_name.to_s == Spree.private_storage_service_name.to_s+ return refuse(:digital_assets_attachment_must_be_private)+ end++ # A provider-backed asset delivers through its provider, so a file on+ # it would show in the panel but never reach a buyer.+ refuse(:digital_assets_provider_takes_no_file) unless digital_asset.provider_class.requires_attachment?+ end++ # What the marketplace lets a seller attach. The operator's own writes+ # are not subject to these: the operator is who the rules protect.+ def enforce_seller_rules+ return if seller.nil?++ refuse(:digital_assets_sellers_disabled) unless store.preferred_seller_digital_assets_enabled+ return if blob.nil?++ # Judged from the bytes: a direct upload arrives with the type the+ # browser declared, and identifying reads the file's own signature.+ blob.identify_without_saving+ return if store.preferred_seller_digital_asset_content_types.include?(blob.content_type)++ refuse(:digital_assets_content_type_not_accepted, content_type: blob.content_type)+ end++ def attach_upload+ digital_asset.attachment.attach(blob) if blob+ end++ def save_digital_asset+ failure(digital_asset) unless digital_asset.save+ end++ # A seller changing what an approved listing delivers reopens its review.+ # The operator's own change does not: they are the reviewer.+ def reopen_review+ return if seller.nil? || blob.nil? || !product.active?+ return unless store.preferred_review_seller_digital_asset_changes+ return if store.preferred_auto_approve_seller_products++ result = Spree.product_propose_workflow.call(product: product, submitted_by: submitted_by, reason: REVIEW_REASON)+ return if result.success?++ digital_asset.errors.add(:base, result.error.to_s)+ failure(digital_asset)+ end++ def store+ product.store+ end++ def refuse(key, **options)+ digital_asset.errors.add(:base, I18n.t("spree.#{key}", **options))+ failure(digital_asset)+ end+ end+ end+enddiff --git a/spree/core/app/workflows/spree/products/nested_attributes.rb b/spree/core/app/workflows/spree/products/nested_attributes.rbindex 68ab93eed9..f2a1e9943f 100644--- a/spree/core/app/workflows/spree/products/nested_attributes.rb+++ b/spree/core/app/workflows/spree/products/nested_attributes.rb@@ -185,6 +185,90 @@ module Spreeendend+ # Attaches downloadable files a product write ships inline, so a new+ # product can carry its digital files in the same request. Additive, like+ # {#apply_media}: each entry carries a `signed_id` (an uploaded file) or a+ # `provider_type` (a provider-backed asset), and attaches to the default+ # variant unless `variant_id` names another. An entry carrying an `id`+ # patches that asset rather than building a duplicate — so a client+ # replaying a product's existing digital_assets list on update does not+ # accumulate copies. Omitting an entry leaves it alone; removal is the+ # nested digital_assets DELETE endpoint's job.+ #+ # Delegates to the digital asset workflows, so a file written as part of+ # a product payload passes the same gate — and the same :validate+ # handlers — as one written through the digital assets endpoint.+ #+ # @param product [Spree::Product]+ # @param digital_assets_params [Array<Hash>, nil]+ # @return [void]+ def apply_digital_assets(product, digital_assets_params)+ return if digital_assets_params.blank?++ digital_assets_params.each do |raw|+ attrs = (raw.respond_to?(:to_h) ? raw.to_h : raw).with_indifferent_access+ asset_id = attrs.delete(:id)++ result =+ if asset_id.present?+ # A patch for an asset that is gone is skipped rather than recreated.+ asset = product.digital_assets.find_by_param(asset_id) || next+ Spree.digital_asset_update_workflow.call(digital_asset: asset, attributes: attrs)+ else+ Spree.digital_asset_create_workflow.call(product: product, attributes: attrs)+ end++ raise ActiveRecord::RecordInvalid, result.value if result.failure?+ end+ end++ # Places a file already in the store's library onto this product. The new+ # row shares the source's blob rather than copying the file.+ #+ # The source is looked up through the product's own store, so an id from+ # another store is ignored rather than copying a file across the tenancy+ # boundary — the same rule the media endpoint enforces with a 404.+ #+ # @param product [Spree::Product]+ # @param source_media_id [String] prefixed or raw id of the library row+ # @param attrs [Hash] attributes for the new placement+ # @return [void]+ def place_from_library(product, source_media_id, attrs)+ source = product.store&.media&.find_by_param(source_media_id)+ return if source.blank?++ copy = source.duplicate_for(product)+ copy.assign_attributes(attrs)+ copy.save!+ end++ # Downloading is a job rather than a step: it reaches out over the+ # network, and the job already owns the parts that makes necessary —+ # SSRF filtering, a size cap, and skipping a URL this product has+ # already fetched.+ #+ # Enqueued after the transaction commits, because the job loads the+ # product by id: a worker picking it up mid-transaction would not find+ # a product that is not visible to its connection yet.+ #+ # The asset is always attached to the product so one file is not+ # downloaded once per variant; `variant_id` links the resulting asset to+ # a variant afterwards.+ def enqueue_media_download(product, external_url, attrs)+ arguments = [+ product.id,+ 'Spree::Product',+ external_url,+ attrs[:external_id],+ attrs[:position],+ attrs[:variant_id]+ ]++ ActiveRecord.after_all_transactions_commit do+ Spree::Images::SaveFromUrlJob.perform_later(*arguments)+ end+ end+# Attaches downloadable files a product write ships inline, so a new# product can carry its digital files in the same request. Additive, like# {#apply_media}: each entry carries a `signed_id` (an uploaded file) or adiff --git a/spree/core/app/workflows/spree/products/propose.rb b/spree/core/app/workflows/spree/products/propose.rbindex 161a73b1a2..eab14edfb7 100644--- a/spree/core/app/workflows/spree/products/propose.rb+++ b/spree/core/app/workflows/spree/products/propose.rb@@ -13,16 +13,20 @@ module Spree# @param product [Spree::Product]# @param submitted_by [Spree.admin_user_class, nil] who asked+ # @param reason [String, nil] why a listing already on sale goes back to+ # review — what changed on it. Recorded on the submission row. Without+ # one, only a draft or a rejected product can be submitted.# @return [Spree::ServiceModule::Result] value is the product- def perform(product:, submitted_by: nil)+ def perform(product:, submitted_by: nil, reason: nil)super# Only a listing that is being worked on can be submitted. Guarding# `active?` alone let an archived product through — and with# auto-approval on, a withdrawn listing went straight back on sale# without anybody reviewing it. Re-submitting one already in review- # is equally meaningless.- unless product.draft? || product.rejected?+ # is equally meaningless. An active listing reopens review only when+ # the caller says what changed, which no seller-facing action does.+ unless product.draft? || product.rejected? || (reason.present? && product.active?)reject!(:cannot_propose, message: I18n.t('activerecord.errors.models.spree/product.attributes.base.cannot_propose'))end@@ -51,7 +55,8 @@ module Spree# one: the trail is how many times this was asked for, and rewriting# the last answer would erase that.def open_submission- product.submissions.create!(status: 'pending', submitted_by: submitted_by)+ product.submissions.create!(status: 'pending', submitted_by: submitted_by,+ metadata: reason.present? ? { 'reason' => reason } : {})enddef auto_approve?diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex 4d82e6f605..b63bc360ce 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -822,7 +822,10 @@ en:digital_delivery: Digital Deliverydigital_assets: Digital assetsdigital_assets_attachment_must_be_private: Upload the file to private storage before attaching it+ digital_assets_content_type_not_accepted: "%{content_type} files are not accepted on this marketplace"digital_assets_provider_takes_no_file: This file is delivered by the marketplace's own system, so a replacement file cannot be uploaded+ digital_assets_sellers_disabled: This marketplace does not accept files uploaded by sellers+ digital_assets_upload_not_found: The uploaded file could not be found. Upload it againdiscontinued: Discontinueddiscontinued_variants_present: Some line items in this order have products that are no longer available.display_delivery_range: Delivery in %{delivery_range} business daysdiff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rbindex 6f6dc734f8..6d6305a64c 100644--- a/spree/core/lib/spree/core/dependencies.rb+++ b/spree/core/lib/spree/core/dependencies.rb@@ -186,6 +186,11 @@ module Spree# handler sees a nested payload and the variants endpoint alikevariant_create_workflow: 'Spree::Variants::Create',variant_update_workflow: 'Spree::Variants::Update',++ # digital assets — the operator's and the seller's endpoints and the+ # nested list on a product write all run through these+ digital_asset_create_workflow: 'Spree::DigitalAssets::Create',+ digital_asset_update_workflow: 'Spree::DigitalAssets::Update',product_archive_workflow: 'Spree::Products::Archive',product_draft_workflow: 'Spree::Products::Draft',diff --git a/spree/core/spec/workflows/spree/digital_assets/write_spec.rb b/spree/core/spec/workflows/spree/digital_assets/write_spec.rbnew file mode 100644index 0000000000..f152587d98--- /dev/null+++ b/spree/core/spec/workflows/spree/digital_assets/write_spec.rb@@ -0,0 +1,112 @@+require 'spec_helper'++# The gate every digital file passes through. The marketplace's rules for a+# seller's file are exercised end to end in the Seller API controller spec;+# this covers the workflow's own contract: where a file lands, what a handler+# sees, and that the operator's writes are not subject to the seller rules.+RSpec.describe 'Spree::DigitalAssets write workflows' do+ let(:store) { @default_store }+ let(:product) { create(:product, store: store) }++ # Hooks registered by one example would otherwise fire in the next.+ after { Spree.hooks.clear! }++ def private_blob(filename = 'manual.pdf')+ ActiveStorage::Blob.create_and_upload!(+ io: File.open(Spree::Core::Engine.root.join('spec', 'fixtures', 'thinking-cat.jpg')),+ filename: filename,+ content_type: 'application/pdf',+ service_name: Spree.private_storage_service_name+ )+ end++ describe Spree::DigitalAssets::Create do+ it 'attaches the upload to the default variant' do+ result = described_class.call(product: product, attributes: { signed_id: private_blob.signed_id, authorized_clicks: 3 })++ expect(result).to be_success+ expect(result.value.variant).to eq(product.default_variant)+ expect(result.value.filename).to eq('manual.pdf')+ expect(result.value.authorized_clicks).to eq(3)+ end++ it "resolves the variant through the product's own variants" do+ variant = create(:variant, product: product)+ other = create(:variant, product: create(:product, store: store))++ result = described_class.call(product: product, attributes: { signed_id: private_blob.signed_id, variant_id: variant.prefixed_id })+ expect(result.value.variant).to eq(variant)++ expect do+ described_class.call(product: product, attributes: { signed_id: private_blob.signed_id, variant_id: other.prefixed_id })+ end.to raise_error(ActiveRecord::RecordNotFound)+ end++ it 'refuses an upload it cannot find' do+ result = described_class.call(product: product, attributes: { signed_id: 'expired' })++ expect(result).to be_failure+ expect(result.error.to_s).to match(/could not be found/)+ end++ # The bytes are in storage by the time the hook fires, so a scanner can+ # read them here and refuse before anything is attached.+ it 'lets a validate handler read the upload and reject it' do+ Spree.hooks.register('digital_assets.create.validate') do |workflow|+ workflow.reject!('the scanner refused this file') if workflow.blob.filename.to_s.end_with?('.pdf')+ end++ result = described_class.call(product: product, attributes: { signed_id: private_blob.signed_id })++ expect(result).to be_failure+ expect(result.error.to_s).to eq('the scanner refused this file')+ expect(Spree::DigitalAsset.count).to eq(0)+ end++ it 'dispatches after_create with the persisted asset' do+ seen = nil+ Spree.hooks.register('digital_assets.create.after_create') { |workflow| seen = workflow.digital_asset }++ result = described_class.call(product: product, attributes: { signed_id: private_blob.signed_id })++ expect(seen).to eq(result.value)+ expect(seen).to be_persisted+ end++ # The settings restrict what a seller may attach; the operator writing on+ # a seller's product is who those settings protect.+ it "does not hold the operator's own write to the seller rules" do+ stub_store_preferences(seller_digital_assets_enabled: false, seller_digital_asset_content_types: [])+ listing = create(:product, store: store, seller: create(:seller, :approved, store: store), status: 'active')++ result = described_class.call(product: listing, attributes: { signed_id: private_blob.signed_id })++ expect(result).to be_success+ expect(listing.reload).to be_active+ end+ end++ describe Spree::DigitalAssets::Update do+ let(:digital_asset) { create(:digital_asset, variant: product.default_variant, authorized_days: 7) }++ it 'shows a validate handler the pending edit and the replacement file' do+ seen = nil+ Spree.hooks.register('digital_assets.update.validate') do |workflow|+ seen = [workflow.digital_asset.changes.keys, workflow.blob&.filename.to_s]+ end++ result = described_class.call(digital_asset: digital_asset, attributes: { signed_id: private_blob.signed_id, authorized_days: nil })++ expect(result).to be_success+ expect(seen).to eq([%w[authorized_days], 'manual.pdf'])+ expect(digital_asset.reload.filename).to eq('manual.pdf')+ end++ it 'leaves the file alone when the payload carries none' do+ result = described_class.call(digital_asset: digital_asset, attributes: { authorized_clicks: 2 })++ expect(result).to be_success+ expect(digital_asset.reload).to have_attributes(authorized_clicks: 2, filename: 'thinking-cat.jpg')+ end+ end+enddiff --git a/spree/core/spec/workflows/spree/products/review_spec.rb b/spree/core/spec/workflows/spree/products/review_spec.rbindex 1a1a9bf029..90258525fb 100644--- a/spree/core/spec/workflows/spree/products/review_spec.rb+++ b/spree/core/spec/workflows/spree/products/review_spec.rb@@ -48,6 +48,18 @@ RSpec.describe 'Spree::Products review workflows' doexpect(product.reload).to be_proposedend+ # A listing on sale reopens review only when the caller says what changed,+ # and the queue then shows why it is back.+ it 'reopens review on a product on sale when told why' do+ product.update!(status: 'active')++ result = Spree.product_propose_workflow.call(product: product, reason: 'digital_asset_changed')++ expect(result).to be_success+ expect(product.reload).to be_proposed+ expect(product.submissions.latest_first.first.metadata).to include('reason' => 'digital_asset_changed')+ end+# The store that does not review listings says so once, rather than# leaving an operator to approve every submission by hand.it 'goes straight on sale when the store approves automatically' do