Skip to content

armgit / spree

Public Imported from GitHub
0

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

Fixed review findings on the marketplace rules for seller files

Damian Legawiec2167dba6c792
diff --git a/docs/api-reference/admin.yaml b/docs/api-reference/admin.yaml
index 3702a78d6e..19a295d948 100644
--- a/docs/api-reference/admin.yaml
+++ b/docs/api-reference/admin.yaml
@@ -79318,8 +79318,8 @@ components:
type: string
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.'
+ file must be of a content type the marketplace accepts, checked against
+ the file''s own signature.'
variant_id:
type: string
description: On create, defaults to the product's default variant when omitted.
@@ -79347,8 +79347,8 @@ components:
type: string
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.'
+ file must be of a content type the marketplace accepts, checked against
+ the file''s own signature.'
variant_id:
type: string
description: On create, defaults to the product's default variant when omitted.
@@ -83689,8 +83689,9 @@ components:
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.
+ description: The content types a seller's file may have, checked against
+ the file's own signature where it has one. The operator's own uploads
+ are not restricted.
example:
- application/pdf
- application/zip
diff --git a/docs/api-reference/seller.yaml b/docs/api-reference/seller.yaml
index 5366948449..fc09dc13c2 100644
--- a/docs/api-reference/seller.yaml
+++ b/docs/api-reference/seller.yaml
@@ -592,6 +592,7 @@ paths:
- image/gif
- image/webp
- image/tiff
+ review_seller_digital_asset_changes: true
permissions:
- allow: true
actions:
@@ -892,6 +893,7 @@ paths:
- image/gif
- image/webp
- image/tiff
+ review_seller_digital_asset_changes: true
permissions: []
permission_keys: []
schema:
@@ -29849,11 +29851,14 @@ components:
type: array
items:
type: string
+ review_seller_digital_asset_changes:
+ type: boolean
required:
- id
- name
- seller_digital_assets_enabled
- seller_digital_asset_content_types
+ - review_seller_digital_asset_changes
x-typelizer: true
TaxIdentifier:
type: object
@@ -31916,8 +31921,8 @@ components:
type: string
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.'
+ file must be of a content type the marketplace accepts, checked against
+ the file''s own signature.'
variant_id:
type: string
description: On create, defaults to the product's default variant when omitted.
@@ -31939,8 +31944,8 @@ components:
type: string
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.'
+ file must be of a content type the marketplace accepts, checked against
+ the file''s own signature.'
variant_id:
type: string
description: On create, defaults to the product's default variant when omitted.
diff --git a/docs/developer/how-to/build-a-marketplace.mdx b/docs/developer/how-to/build-a-marketplace.mdx
index cfd4138f16..6a35b6ef58 100644
--- a/docs/developer/how-to/build-a-marketplace.mdx
+++ b/docs/developer/how-to/build-a-marketplace.mdx
@@ -95,7 +95,7 @@ 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. |
+| `seller_digital_asset_content_types` | documents, ebooks, archives, audio, video, images, plain text | The content types a seller's file may have, checked against the file's own signature. 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. |
diff --git a/docs/developer/how-to/sell-digital-products.mdx b/docs/developer/how-to/sell-digital-products.mdx
index 16e3aead84..e6e9437371 100644
--- a/docs/developer/how-to/sell-digital-products.mdx
+++ b/docs/developer/how-to/sell-digital-products.mdx
@@ -65,7 +65,7 @@ Sellers upload files only. A [custom digital asset provider](/developer/how-to/c
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.
+- **Accepted file types for sellers** (`seller_digital_asset_content_types`). Checked against the file's own signature where it has one, not its name, so a renamed executable does not pass as a PDF; a format with no signature, such as plain text, is taken at the type the upload declared. 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>
diff --git a/docs/plans/6.0-digital-assets.md b/docs/plans/6.0-digital-assets.md
index ad8fb699dd..87e53e4f45 100644
--- a/docs/plans/6.0-digital-assets.md
+++ b/docs/plans/6.0-digital-assets.md
@@ -46,7 +46,7 @@ Spree ships a complete digital products engine in core: `Spree::Digital` (a file
- **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 seller's file must be of an accepted content type** (`seller_digital_asset_content_types`), checked against the signature Marcel reads from the bytes where the format has one, never the file name; signature-less formats (plain text) keep their declared type. 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`.
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index fd0c73f830..3c87f21213 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -2,7 +2,7 @@
**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`.
+**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 checked against the signature Marcel reads from the bytes where the format has one, never the file name (plain text has none and keeps its declared type); its default covers the formats digital goods usually come in and leaves out executables, scripts, SVG and unrecognised binaries. The operator's own uploads are not restricted. `review_seller_digital_asset_changes` is on by default: a seller adding or replacing a file on a listing already on sale sends it back to review, off sale until approved again; changing limits or deleting does not, and the rule is moot when seller products auto-approve. Turning uploads off also stops a seller removing the marketplace's own files from their product. `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.
diff --git a/packages/admin-sdk/src/types/params/DigitalAssetCreateParams.ts b/packages/admin-sdk/src/types/params/DigitalAssetCreateParams.ts
index 109a8ffcf0..266aec2ffe 100644
--- a/packages/admin-sdk/src/types/params/DigitalAssetCreateParams.ts
+++ b/packages/admin-sdk/src/types/params/DigitalAssetCreateParams.ts
@@ -4,7 +4,7 @@ export type DigitalAssetCreateParams = {
/**
* 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.
+ * marketplace accepts, checked against the file's own signature.
*/
signed_id?: string
/**
diff --git a/packages/admin-sdk/src/types/params/DigitalAssetUpdateParams.ts b/packages/admin-sdk/src/types/params/DigitalAssetUpdateParams.ts
index b3a0b246e9..32c95e4a42 100644
--- a/packages/admin-sdk/src/types/params/DigitalAssetUpdateParams.ts
+++ b/packages/admin-sdk/src/types/params/DigitalAssetUpdateParams.ts
@@ -4,7 +4,7 @@ export type DigitalAssetUpdateParams = {
/**
* 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.
+ * marketplace accepts, checked against the file's own signature.
*/
signed_id?: string
/**
diff --git a/packages/admin-sdk/src/types/params/StoreUpdateParams.ts b/packages/admin-sdk/src/types/params/StoreUpdateParams.ts
index e04c268703..e4a851f9e9 100644
--- a/packages/admin-sdk/src/types/params/StoreUpdateParams.ts
+++ b/packages/admin-sdk/src/types/params/StoreUpdateParams.ts
@@ -77,8 +77,8 @@ export type StoreUpdateParams = {
/** 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.
+ * The content types a seller's file may have, checked against the file's own signature where it
+ * has one. The operator's own uploads are not restricted.
*/
seller_digital_asset_content_types?: string[]
/**
diff --git a/packages/dashboard-core/src/products/digital-assets-card.tsx b/packages/dashboard-core/src/products/digital-assets-card.tsx
index fcbbef6ba6..69f46eef73 100644
--- a/packages/dashboard-core/src/products/digital-assets-card.tsx
+++ b/packages/dashboard-core/src/products/digital-assets-card.tsx
@@ -58,6 +58,7 @@ export function DigitalAssetsCard({
variants,
readOnly = false,
accept,
+ notice,
}: {
productId?: string
variants?: PanelVariant[]
@@ -70,6 +71,11 @@ export function DigitalAssetsCard({
readOnly?: boolean
/** The content types the picker offers, when the host restricts them. */
accept?: string[]
+ /**
+ * What else a file change does here, shown under the description — the
+ * seller panel says that a listing on sale goes back to review.
+ */
+ notice?: string
}) {
const { t } = useTranslation()
const confirm = useConfirm()
@@ -293,6 +299,7 @@ export function DigitalAssetsCard({
<CardContent className="flex flex-col gap-4">
<p className="text-muted-foreground text-sm">{t('admin.digital_assets.description')}</p>
+ {notice && canWrite && <p className="text-sm">{notice}</p>}
<input
ref={fileInputRef}
diff --git a/packages/dashboard/e2e/seller-panel-products.spec.ts b/packages/dashboard/e2e/seller-panel-products.spec.ts
index d969749576..6990b6d607 100644
--- a/packages/dashboard/e2e/seller-panel-products.spec.ts
+++ b/packages/dashboard/e2e/seller-panel-products.spec.ts
@@ -97,12 +97,10 @@ test.describe('seller panel — products', () => {
// 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',
- )
+ const store = await adminRequest<{
+ seller_digital_assets_enabled: boolean
+ 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(
@@ -166,5 +164,11 @@ test.describe('seller panel — products', () => {
await expect(replacedRow).toBeHidden({ timeout: 15_000 })
await expect(digitalCard.getByText(/drag & drop files here/i)).toBeVisible()
+
+ // Put the store back so later specs read what the seed left.
+ await adminRequest(page, admin, 'patch', '/store', {
+ seller_digital_assets_enabled: store.seller_digital_assets_enabled,
+ seller_digital_asset_content_types: store.seller_digital_asset_content_types,
+ })
})
})
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index 229139b3b1..5a578b0a22 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -2345,8 +2345,9 @@
},
"seller_digital_asset_content_types": {
"label": "أنواع الملفات المقبولة من البائعين",
- "help": "نوع محتوى واحد في كل سطر، مثل application/pdf. يُحكم عليه من بايتات الملف لا من اسمه. ملفاتك أنت غير مقيدة.",
- "placeholder": "application/pdf\napplication/zip\naudio/mpeg"
+ "help": "نوع محتوى واحد في كل سطر، مثل application/pdf. يُتحقق منه من توقيع الملف نفسه إن وُجد، لا من اسمه. ملفاتك أنت غير مقيدة.",
+ "placeholder": "application/pdf\napplication/zip\naudio/mpeg",
+ "invalid": "يجب أن يكون كل سطر نوع محتوى مثل application/pdf."
},
"review_seller_digital_asset_changes": {
"label": "مراجعة تغييرات الملفات في المنتجات المعروضة للبيع",
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index e222770585..8ae84a1ccb 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -2327,8 +2327,9 @@
},
"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"
+ "help": "Ein Inhaltstyp pro Zeile, zum Beispiel application/pdf. Geprüft anhand der eigenen Signatur der Datei, wo sie eine hat, nicht anhand ihres Namens. Ihre eigenen Uploads sind nicht eingeschränkt.",
+ "placeholder": "application/pdf\napplication/zip\naudio/mpeg",
+ "invalid": "Jede Zeile muss ein Inhaltstyp wie application/pdf sein."
},
"review_seller_digital_asset_changes": {
"label": "Dateiänderungen an bereits verkauften Produkten prüfen",
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index 5e681d9448..67391e9c12 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -2327,8 +2327,9 @@
},
"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"
+ "help": "One content type per line, such as application/pdf. Checked against the file’s own signature where it has one, not its name. Your own uploads are not restricted.",
+ "placeholder": "application/pdf\napplication/zip\naudio/mpeg",
+ "invalid": "Each line must be a content type such as application/pdf."
},
"review_seller_digital_asset_changes": {
"label": "Review file changes on products already on sale",
diff --git a/packages/dashboard/src/locales/es.json b/packages/dashboard/src/locales/es.json
index 22f1c765bf..b4d81d0a0c 100644
--- a/packages/dashboard/src/locales/es.json
+++ b/packages/dashboard/src/locales/es.json
@@ -2269,8 +2269,9 @@
},
"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"
+ "help": "Un tipo de contenido por línea, por ejemplo application/pdf. Se comprueba con la firma propia del archivo cuando la tiene, no con su nombre. Sus propias subidas no están restringidas.",
+ "placeholder": "application/pdf\napplication/zip\naudio/mpeg",
+ "invalid": "Cada línea debe ser un tipo de contenido como application/pdf."
},
"review_seller_digital_asset_changes": {
"label": "Revisar cambios de archivos en productos ya en venta",
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index 955d6f4e20..3c74f6297f 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -2327,8 +2327,9 @@
},
"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"
+ "help": "Un type de contenu par ligne, par exemple application/pdf. Vérifié d’après la signature propre du fichier quand il en a une, pas son nom. Vos propres téléversements ne sont pas restreints.",
+ "placeholder": "application/pdf\napplication/zip\naudio/mpeg",
+ "invalid": "Chaque ligne doit être un type de contenu tel que application/pdf."
},
"review_seller_digital_asset_changes": {
"label": "Réexaminer les changements de fichiers sur les produits déjà en vente",
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index d7363414aa..1a5ed093f6 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -2345,8 +2345,9 @@
},
"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"
+ "help": "Jeden typ zawartości w wierszu, na przykład application/pdf. Sprawdzany na podstawie własnej sygnatury pliku, gdy ją ma, a nie jego nazwy. Twoje własne pliki nie podlegają ograniczeniom.",
+ "placeholder": "application/pdf\napplication/zip\naudio/mpeg",
+ "invalid": "Każdy wiersz musi być typem zawartości, na przykład application/pdf."
},
"review_seller_digital_asset_changes": {
"label": "Weryfikuj zmiany plików w produktach już w sprzedaży",
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index 41a143d59c..3d3dd2da11 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -2322,8 +2322,9 @@
},
"seller_digital_asset_content_types": {
"label": "卖家可上传的文件类型",
- "help": "每行一个内容类型,例如 application/pdf。按文件内容而非文件名判断。您自己的上传不受限制。",
- "placeholder": "application/pdf\napplication/zip\naudio/mpeg"
+ "help": "每行一个内容类型,例如 application/pdf。按文件自身的签名(如有)判断,而非文件名。您自己的上传不受限制。",
+ "placeholder": "application/pdf\napplication/zip\naudio/mpeg",
+ "invalid": "每行必须是一个内容类型,例如 application/pdf。"
},
"review_seller_digital_asset_changes": {
"label": "审核在售商品的文件变更",
diff --git a/packages/dashboard/src/schemas/marketplace.ts b/packages/dashboard/src/schemas/marketplace.ts
index fa1f2f38c4..5ed18f5a51 100644
--- a/packages/dashboard/src/schemas/marketplace.ts
+++ b/packages/dashboard/src/schemas/marketplace.ts
@@ -1,4 +1,5 @@
import { compareMoney, isDecimalString, PAYOUT_SCHEDULE_INTERVALS } from '@spree/core'
+import { i18n } from '@spree/dashboard-core'
import { z } from 'zod'
const nonNegativeDecimal = z
@@ -16,8 +17,13 @@ export const marketplaceSettingsFormSchema = z.object({
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(),
+ // One content type per line in the form; sent as a list. Each line must
+ // be a type/subtype, or a typo would refuse every seller upload.
+ seller_digital_asset_content_types: z
+ .string()
+ .refine((value) => contentTypesFromLines(value).every((type) => MEDIA_TYPE.test(type)), {
+ message: i18n.t('admin.fields.store.seller_digital_asset_content_types.invalid'),
+ }),
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
@@ -30,6 +36,8 @@ export const marketplaceSettingsFormSchema = z.object({
export type MarketplaceSettingsFormValues = z.infer<typeof marketplaceSettingsFormSchema>
+const MEDIA_TYPE = /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+*-]*$/i
+
/** The textarea's lines as the list the API stores, blank lines dropped. */
export function contentTypesFromLines(value: string): string[] {
return value
diff --git a/packages/seller-dashboard/src/api-client.ts b/packages/seller-dashboard/src/api-client.ts
index 3307f6cf7d..0a836ad587 100644
--- a/packages/seller-dashboard/src/api-client.ts
+++ b/packages/seller-dashboard/src/api-client.ts
@@ -1,4 +1,4 @@
-import { runtimeListParams, setApiClient } from '@spree/dashboard-core'
+import { i18n, runtimeListParams, setApiClient } from '@spree/dashboard-core'
import type { SellerApiClient, SellerExportCreateParams } from '@spree/seller-sdk'
import { createSellerClient } from '@spree/seller-sdk'
@@ -150,7 +150,7 @@ export function createSellerApiClient({
list: (productId, params) => sellerClient().products.digitalAssets.list(productId, params),
// Sellers upload files only, so a file is the one thing a new asset must carry.
create: (productId, { signed_id, ...params }) => {
- if (!signed_id) throw new Error('Upload a file first.')
+ if (!signed_id) throw new Error(i18n.t('admin.errors.unexpected'))
return sellerClient().products.digitalAssets.create(productId, { ...params, signed_id })
},
update: (productId, id, params) =>
diff --git a/packages/seller-dashboard/src/locales/ar.json b/packages/seller-dashboard/src/locales/ar.json
index 9d41da1cb4..0907489c4e 100644
--- a/packages/seller-dashboard/src/locales/ar.json
+++ b/packages/seller-dashboard/src/locales/ar.json
@@ -750,7 +750,8 @@
"variant_remove_confirm_description": "يُزال من المنتج عند الحفظ.",
"variant_remove_confirm_title": "إزالة هذا الخيار؟",
"variants": "الخيارات",
- "variants_empty": "يُباع هذا المنتج كقطعة واحدة بالسعر أعلاه. أضف خيارًا لبيعه بخيارات مثل المقاس أو اللون."
+ "variants_empty": "يُباع هذا المنتج كقطعة واحدة بالسعر أعلاه. أضف خيارًا لبيعه بخيارات مثل المقاس أو اللون.",
+ "digital_files_review_notice": "إضافة ملف أو استبداله يعيد هذا المنتج إلى المراجعة، ويتوقف بيعه حتى يعتمده السوق مجددًا."
},
"profile": {
"about": "نبذة",
diff --git a/packages/seller-dashboard/src/locales/de.json b/packages/seller-dashboard/src/locales/de.json
index d649603cd3..9b79b6b4b9 100644
--- a/packages/seller-dashboard/src/locales/de.json
+++ b/packages/seller-dashboard/src/locales/de.json
@@ -738,7 +738,8 @@
"variant_remove_confirm_description": "Sie wird beim Speichern vom Produkt entfernt.",
"variant_remove_confirm_title": "Diese Variante entfernen?",
"variants": "Varianten",
- "variants_empty": "Dieses Produkt wird als ein Artikel zum obigen Preis verkauft. Fügen Sie eine Variante hinzu, um es in Optionen wie Größe oder Farbe anzubieten."
+ "variants_empty": "Dieses Produkt wird als ein Artikel zum obigen Preis verkauft. Fügen Sie eine Variante hinzu, um es in Optionen wie Größe oder Farbe anzubieten.",
+ "digital_files_review_notice": "Das Hinzufügen oder Ersetzen einer Datei schickt dieses Produkt zurück in die Prüfung; es ist nicht verkäuflich, bis der Marktplatz es erneut freigibt."
},
"profile": {
"about": "Über uns",
diff --git a/packages/seller-dashboard/src/locales/en.json b/packages/seller-dashboard/src/locales/en.json
index ecb4a8e26e..6b6c392797 100644
--- a/packages/seller-dashboard/src/locales/en.json
+++ b/packages/seller-dashboard/src/locales/en.json
@@ -738,7 +738,8 @@
"variant_remove_confirm_description": "It comes off the product when you save.",
"variant_remove_confirm_title": "Remove this variant?",
"variants": "Variants",
- "variants_empty": "This product is sold as one item, at the price above. Add a variant to sell it in options such as size or colour."
+ "variants_empty": "This product is sold as one item, at the price above. Add a variant to sell it in options such as size or colour.",
+ "digital_files_review_notice": "Adding or replacing a file sends this product back to review, and it is off sale until the marketplace approves it again."
},
"profile": {
"about": "About",
diff --git a/packages/seller-dashboard/src/locales/fr.json b/packages/seller-dashboard/src/locales/fr.json
index 79955f9573..ac781fd851 100644
--- a/packages/seller-dashboard/src/locales/fr.json
+++ b/packages/seller-dashboard/src/locales/fr.json
@@ -738,7 +738,8 @@
"variant_remove_confirm_description": "Elle sera retirée du produit à l’enregistrement.",
"variant_remove_confirm_title": "Retirer cette variante ?",
"variants": "Variantes",
- "variants_empty": "Ce produit est vendu comme un article unique, au prix ci-dessus. Ajoutez une variante pour le vendre en plusieurs options, par exemple la taille ou la couleur."
+ "variants_empty": "Ce produit est vendu comme un article unique, au prix ci-dessus. Ajoutez une variante pour le vendre en plusieurs options, par exemple la taille ou la couleur.",
+ "digital_files_review_notice": "Ajouter ou remplacer un fichier renvoie ce produit en révision ; il n’est plus en vente jusqu’à ce que la place de marché l’approuve de nouveau."
},
"profile": {
"about": "À propos",
diff --git a/packages/seller-dashboard/src/locales/pl.json b/packages/seller-dashboard/src/locales/pl.json
index 61b310e503..a80f1f2973 100644
--- a/packages/seller-dashboard/src/locales/pl.json
+++ b/packages/seller-dashboard/src/locales/pl.json
@@ -744,7 +744,8 @@
"variant_remove_confirm_description": "Zniknie z produktu po zapisaniu.",
"variant_remove_confirm_title": "Usunąć ten wariant?",
"variants": "Warianty",
- "variants_empty": "Ten produkt sprzedajesz jako jedną pozycję, w cenie powyżej. Dodaj wariant, aby sprzedawać go w opcjach takich jak rozmiar czy kolor."
+ "variants_empty": "Ten produkt sprzedajesz jako jedną pozycję, w cenie powyżej. Dodaj wariant, aby sprzedawać go w opcjach takich jak rozmiar czy kolor.",
+ "digital_files_review_notice": "Dodanie lub zastąpienie pliku wysyła ten produkt ponownie do weryfikacji; do ponownego zatwierdzenia przez marketplace nie jest w sprzedaży."
},
"profile": {
"about": "O sprzedawcy",
diff --git a/packages/seller-dashboard/src/locales/zh-CN.json b/packages/seller-dashboard/src/locales/zh-CN.json
index 49d27b02d5..9bdc353cff 100644
--- a/packages/seller-dashboard/src/locales/zh-CN.json
+++ b/packages/seller-dashboard/src/locales/zh-CN.json
@@ -735,7 +735,8 @@
"variant_remove_confirm_description": "保存后它会从商品中移除。",
"variant_remove_confirm_title": "移除此变体?",
"variants": "变体",
- "variants_empty": "此商品按上述价格作为单一款式销售。添加变体即可按尺码、颜色等选项销售。"
+ "variants_empty": "此商品按上述价格作为单一款式销售。添加变体即可按尺码、颜色等选项销售。",
+ "digital_files_review_notice": "添加或替换文件会将此商品重新送审,在平台再次批准前将暂停销售。"
},
"profile": {
"about": "简介",
diff --git a/packages/seller-dashboard/src/pages/product.tsx b/packages/seller-dashboard/src/pages/product.tsx
index 8a18bd0d23..7a8b129eb1 100644
--- a/packages/seller-dashboard/src/pages/product.tsx
+++ b/packages/seller-dashboard/src/pages/product.tsx
@@ -266,6 +266,11 @@ export function ProductPage({ mode }: { mode: 'new' | 'edit' }) {
variants={assignableVariants}
readOnly={!marketplace?.seller_digital_assets_enabled}
accept={marketplace?.seller_digital_asset_content_types}
+ notice={
+ product?.status === 'active' && marketplace?.review_seller_digital_asset_changes
+ ? t('products.digital_files_review_notice')
+ : undefined
+ }
/>
<Slot name="seller.product.form_main" context={{ product, mode }} />
</>
diff --git a/packages/seller-sdk/src/types/generated/Store.ts b/packages/seller-sdk/src/types/generated/Store.ts
index 0d23a628f0..b056bca557 100644
--- a/packages/seller-sdk/src/types/generated/Store.ts
+++ b/packages/seller-sdk/src/types/generated/Store.ts
@@ -1,4 +1,4 @@
-// Typelizer digest e968e05312ca7f559c414474d1b3657e
+// Typelizer digest 19753137ffa553d775550024da9c0374
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
@@ -7,6 +7,7 @@ type Store = {
name: string;
seller_digital_assets_enabled: boolean;
seller_digital_asset_content_types: Array<string>;
+ review_seller_digital_asset_changes: boolean;
}
export default Store;
diff --git a/packages/seller-sdk/src/types/params/DigitalAssetCreateParams.ts b/packages/seller-sdk/src/types/params/DigitalAssetCreateParams.ts
index 7615e090a8..5a1ef25d21 100644
--- a/packages/seller-sdk/src/types/params/DigitalAssetCreateParams.ts
+++ b/packages/seller-sdk/src/types/params/DigitalAssetCreateParams.ts
@@ -4,7 +4,7 @@ export type DigitalAssetCreateParams = {
/**
* 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.
+ * marketplace accepts, checked against the file's own signature.
*/
signed_id: string
/**
diff --git a/packages/seller-sdk/src/types/params/DigitalAssetUpdateParams.ts b/packages/seller-sdk/src/types/params/DigitalAssetUpdateParams.ts
index a6e9420ba4..992c8676de 100644
--- a/packages/seller-sdk/src/types/params/DigitalAssetUpdateParams.ts
+++ b/packages/seller-sdk/src/types/params/DigitalAssetUpdateParams.ts
@@ -4,7 +4,7 @@ export type DigitalAssetUpdateParams = {
/**
* 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.
+ * marketplace accepts, checked against the file's own signature.
*/
signed_id?: string
/**
diff --git a/packages/seller-sdk/src/zod/generated/Store.ts b/packages/seller-sdk/src/zod/generated/Store.ts
index 20d5073306..d7d7c4e57f 100644
--- a/packages/seller-sdk/src/zod/generated/Store.ts
+++ b/packages/seller-sdk/src/zod/generated/Store.ts
@@ -6,6 +6,7 @@ export const StoreSchema = z.object({
name: z.string(),
seller_digital_assets_enabled: z.boolean(),
seller_digital_asset_content_types: z.array(z.string()),
+ review_seller_digital_asset_changes: z.boolean(),
});
export type Store = z.infer<typeof StoreSchema>;
diff --git a/spree/api/app/controllers/spree/api/v3/admin/store_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/store_controller.rb
index 47270d858b..27ea531e25 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
@@ -69,7 +69,7 @@ module Spree
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."
+ description: "The content types a seller's file may have, checked against the file's own signature where it has one. 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,
diff --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.rb
index a45bd2e702..361ee03768 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
@@ -25,6 +25,19 @@ module Spree
body.require_attributes :signed_id, on: :create
end
+ # DELETE /api/v3/seller/products/:product_id/digital_assets/:id
+ #
+ # Removing a file is covered by the same switch as adding one: a
+ # marketplace that keeps digital files to itself keeps the ones it
+ # attached to a seller's product.
+ def destroy
+ unless current_store.preferred_seller_digital_assets_enabled
+ return render_validation_error(I18n.t('spree.digital_assets_sellers_disabled'))
+ end
+
+ super
+ end
+
protected
def serializer_class
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.rb
index af8ad811bd..9584381412 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. A seller's file must be of a content type the marketplace accepts, judged from its bytes."
+ 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, checked against the file's own signature."
# 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/seller/store_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/store_serializer.rb
index b077d5d419..abe5a5063d 100644
--- a/spree/api/app/serializers/spree/api/v3/seller/store_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/seller/store_serializer.rb
@@ -9,7 +9,8 @@ module Spree
attributes :name
- preference_attributes Spree::Store, :seller_digital_assets_enabled, :seller_digital_asset_content_types
+ preference_attributes Spree::Store, :seller_digital_assets_enabled, :seller_digital_asset_content_types,
+ :review_seller_digital_asset_changes
end
end
end
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.rb
index 2046a1a144..6dbb3a4a0d 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
@@ -182,14 +182,26 @@ RSpec.describe Spree::Api::V3::Seller::Products::DigitalAssetsController, type:
end
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)
+ context 'when the marketplace has not opened files to sellers' do
+ before { stub_store_preferences(seller_digital_assets_enabled: false) }
- post :create, params: { product_id: product.prefixed_id, signed_id: blob.signed_id }, as: :json
+ it 'refuses every upload' do
+ 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)
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(response.parsed_body.dig('error', 'message')).to match(/does not let sellers add or change digital files/)
+ expect(Spree::DigitalAsset.count).to eq(0)
+ end
+
+ # The operator attached it; the seller may look but not remove it.
+ it "keeps the marketplace's own file on the product" do
+ digital_asset = create(:digital_asset, variant: variant)
+
+ delete :destroy, params: { product_id: product.prefixed_id, id: digital_asset.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(Spree::DigitalAsset.where(id: digital_asset.id)).to exist
+ end
end
# The blob declares itself a generic binary; its bytes are a JPEG, and the
diff --git a/spree/core/app/models/spree/digital_asset.rb b/spree/core/app/models/spree/digital_asset.rb
index 7e8f937fb9..451f2db741 100644
--- a/spree/core/app/models/spree/digital_asset.rb
+++ b/spree/core/app/models/spree/digital_asset.rb
@@ -29,6 +29,8 @@ module Spree
# 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.
+ # The text formats have no signature, so they are taken at the type the
+ # upload declared.
DEFAULT_SELLER_CONTENT_TYPES = %w[
application/pdf application/epub+zip application/zip application/x-7z-compressed application/gzip
application/json text/plain text/csv
diff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rb
index c564ecfdb8..ee87222b4e 100644
--- a/spree/core/app/models/spree/store.rb
+++ b/spree/core/app/models/spree/store.rb
@@ -82,10 +82,13 @@ module Spree
# 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.
+ # What a seller's file may be, checked against the file's own signature
+ # 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 typo here would refuse every seller upload with a message about the
+ # file, so the list is checked for the type/subtype shape when written.
+ validate :seller_digital_asset_content_types_are_media_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.
@@ -169,6 +172,8 @@ module Spree
# B2B store collects it from everyone, a mixed store only offers it.
preference :address_requires_company, :boolean, default: false
preference :address_requires_phone, :boolean, default: false
+ MEDIA_TYPE_FORMAT = %r{\A[a-z0-9][a-z0-9!#$&^_.+-]*/[a-z0-9][a-z0-9!#$&^_.+*-]*\z}i
+
# digital assets preferences
preference :limit_digital_download_count, :boolean, default: true
preference :limit_digital_download_days, :boolean, default: true
@@ -846,5 +851,13 @@ module Spree
errors.add(:preferred_order_number_sequence_start, :locked_after_first_number)
end
+
+ def seller_digital_asset_content_types_are_media_types
+ bad = Array(preferred_seller_digital_asset_content_types).reject { |type| type.to_s.match?(MEDIA_TYPE_FORMAT) }
+ return if bad.empty?
+
+ errors.add(:preferred_seller_digital_asset_content_types, :invalid,
+ message: I18n.t('spree.digital_assets_content_type_list_invalid', types: bad.join(', ')))
+ end
end
end
diff --git a/spree/core/app/workflows/spree/digital_assets/writing.rb b/spree/core/app/workflows/spree/digital_assets/writing.rb
index 74ed1f39f3..eb01ce7cb5 100644
--- a/spree/core/app/workflows/spree/digital_assets/writing.rb
+++ b/spree/core/app/workflows/spree/digital_assets/writing.rb
@@ -43,7 +43,10 @@ module Spree
end
# A provider-backed asset delivers through its provider, so a file on
- # it would show in the panel but never reach a buyer.
+ # it would show in the panel but never reach a buyer. An unregistered
+ # provider is left to the model's validation rather than asked.
+ return unless Spree.digital_asset_providers.include?(digital_asset.provider_class)
+
refuse(:digital_assets_provider_takes_no_file) unless digital_asset.provider_class.requires_attachment?
end
@@ -55,8 +58,9 @@ module Spree
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.
+ # Identifying reads the file's own signature where it has one, so a
+ # renamed executable cannot pass as a PDF; a format with no signature
+ # (plain text) keeps the type the client declared.
blob.identify_without_saving
return if store.preferred_seller_digital_asset_content_types.include?(blob.content_type)
diff --git a/spree/core/app/workflows/spree/products/nested_attributes.rb b/spree/core/app/workflows/spree/products/nested_attributes.rb
index f2a1e9943f..f158db3a01 100644
--- a/spree/core/app/workflows/spree/products/nested_attributes.rb
+++ b/spree/core/app/workflows/spree/products/nested_attributes.rb
@@ -221,106 +221,6 @@ module Spree
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 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.
- #
- # @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)
- signed_id = attrs.delete(:signed_id)
- variant_id = attrs.delete(:variant_id)
-
- # An id patches an existing asset; without one this is a new asset on
- # the named variant (or the default). A patch for an asset that is
- # gone is skipped rather than recreated.
- if asset_id.present?
- asset = product.digital_assets.find_by_param(asset_id) || next
- else
- target = variant_id.present? ? product.variants.find_by_param!(variant_id) : product.default_variant
- next unless target
-
- asset = target.digital_assets.build
- end
-
- asset.assign_attributes(attrs)
-
- if signed_id.present?
- # Attaching never moves a blob between storage services, so a file
- # uploaded to the public bucket would stay publicly readable. Refuse
- # it rather than attaching it wrongly.
- blob = ActiveStorage::Blob.find_signed(signed_id)
- unless blob && blob.service_name.to_s == Spree.private_storage_service_name.to_s
- asset.errors.add(:attachment, :digital_assets_attachment_must_be_private, message: I18n.t('spree.digital_assets_attachment_must_be_private'))
- raise ActiveRecord::RecordInvalid.new(asset)
- end
-
- asset.attachment.attach(signed_id)
- end
- asset.save!
- end
- end
end
end
end
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index b63bc360ce..c3d49a265d 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -822,9 +822,10 @@ en:
digital_delivery: Digital Delivery
digital_assets: Digital assets
digital_assets_attachment_must_be_private: Upload the file to private storage before attaching it
+ digital_assets_content_type_list_invalid: "Not a content type: %{types}. Use the type/subtype form, such as application/pdf"
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_sellers_disabled: This marketplace does not let sellers add or change digital files
digital_assets_upload_not_found: The uploaded file could not be found. Upload it again
discontinued: Discontinued
discontinued_variants_present: Some line items in this order have products that are no longer available.
diff --git a/spree/core/spec/models/spree/store_spec.rb b/spree/core/spec/models/spree/store_spec.rb
index 0945905d0e..69eb8d444d 100644
--- a/spree/core/spec/models/spree/store_spec.rb
+++ b/spree/core/spec/models/spree/store_spec.rb
@@ -327,6 +327,25 @@ describe Spree::Store, type: :model, without_global_store: true do
end
end
+ describe 'seller digital asset content types' do
+ let(:store) { build(:store) }
+
+ it 'accepts a list of media types' do
+ store.preferred_seller_digital_asset_content_types = %w[application/pdf audio/mpeg image/svg+xml]
+
+ expect(store).to be_valid
+ end
+
+ # A bare "pdf" would refuse every seller upload with a message about the
+ # file, so it is caught where the operator types it.
+ it 'refuses an entry that is not a type/subtype' do
+ store.preferred_seller_digital_asset_content_types = %w[application/pdf pdf]
+
+ expect(store).not_to be_valid
+ expect(store.errors[:preferred_seller_digital_asset_content_types].first).to include('pdf')
+ end
+ end
+
describe 'order routing strategy preference' do
it 'rejects an unregistered strategy' do
store = build(:store, preferred_order_routing_strategy: 'Spree::OrderRouting::Strategy::Reducer')