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.

Add digital files to the product create page

Damian Legawiec34fe2ce564e3
diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.ts
index 7abd59380b..de3972faab 100644
--- a/packages/admin-sdk/src/params.ts
+++ b/packages/admin-sdk/src/params.ts
@@ -768,6 +768,12 @@ export interface ProductCreateParams {
variants?: ProductVariantInput[]
/** Media created alongside the product — see {@link ProductMediaInput}. */
media?: ProductMediaInput[]
+ /** Downloadable files shipped inline with the product (create-time). Each
+ * entry carries a `signed_id` (an uploaded file, to private storage) or a
+ * `provider_type` (a provider-backed asset); it attaches to the default
+ * variant unless `variant_id` is given. Edits/deletes use the nested
+ * `products.digitalAssets` endpoints. */
+ digital_assets?: DigitalAssetCreateParams[]
product_publications?: ProductPublicationInput[]
}
@@ -792,6 +798,8 @@ export interface ProductUpdateParams {
variants?: ProductVariantInput[]
/** See {@link ProductMediaInput}. */
media?: ProductMediaInput[]
+ /** See `ProductCreateParams.digital_assets`. */
+ digital_assets?: DigitalAssetCreateParams[]
product_publications?: ProductPublicationInput[]
}
diff --git a/packages/admin-sdk/src/types/generated/Product.ts b/packages/admin-sdk/src/types/generated/Product.ts
index de89ea01e2..a9d3b47f8b 100644
--- a/packages/admin-sdk/src/types/generated/Product.ts
+++ b/packages/admin-sdk/src/types/generated/Product.ts
@@ -1,7 +1,7 @@
-// Typelizer digest 616b02573bbc6fa85c5f7fabf9166e55
+// Typelizer digest a37dcbc8eedee8f7c56203648043ecb0
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
-import type {Price, PriceHistory, ProductSubmission, Seller, Media, Variant, OptionType, OptionValue, Category, CustomField, Collection, ProductPublication, Channel, ProductType} from '@/types'
+import type {Price, PriceHistory, ProductSubmission, Seller, Media, Variant, OptionType, OptionValue, Category, CustomField, DigitalAsset, Collection, ProductPublication, Channel, ProductType} from '@/types'
interface Product {
id: string;
@@ -49,6 +49,7 @@ interface Product {
seller_name: string | null;
product_type_id: string | null;
tax_category_id: string | null;
+ digital_assets?: Array<DigitalAsset>;
collections?: Array<Collection>;
product_publications?: Array<ProductPublication>;
channels?: Array<Channel>;
diff --git a/packages/dashboard-core/src/products/product-schema.ts b/packages/dashboard-core/src/products/product-schema.ts
index 73659398b9..cef359702b 100644
--- a/packages/dashboard-core/src/products/product-schema.ts
+++ b/packages/dashboard-core/src/products/product-schema.ts
@@ -120,6 +120,18 @@ export const mediaFormSchema = z
export type MediaFormValues = z.infer<typeof mediaFormSchema>
+// A downloadable file staged on the new-product form. Create-time only: each
+// entry is an upload (signed_id) buffered until the product POST. UI-only
+// fields (filename, byteSize, uploadId) are stripped at submit.
+export const digitalFileFormSchema = z.object({
+ signed_id: z.string(),
+ filename: z.string().nullable().optional(),
+ byteSize: z.number().nullable().optional(),
+ uploadId: z.string().optional(),
+})
+
+export type DigitalFileFormValues = z.infer<typeof digitalFileFormSchema>
+
export const productPublicationFormSchema = z.object({
id: z.string().optional(),
channel_id: z.string(),
@@ -178,6 +190,11 @@ export const productFormSchema = z.object({
// new uploads ride the same product PATCH.
media: z.array(mediaFormSchema).optional(),
+ // Downloadable files, staged pre-save on the new product page and shipped in
+ // the product POST. Edit uses the live API-driven card instead, so this stays
+ // empty there.
+ digital_assets: z.array(digitalFileFormSchema).optional(),
+
product_publications: z.array(productPublicationFormSchema).optional(),
})
@@ -222,6 +239,7 @@ export function newProductFormDefaults(): ProductFormValues {
],
custom_fields: [],
media: [],
+ digital_assets: [],
product_publications: [],
}
}
diff --git a/packages/dashboard/src/components/spree/products/digital-files-form-card.tsx b/packages/dashboard/src/components/spree/products/digital-files-form-card.tsx
new file mode 100644
index 0000000000..84a34dc80f
--- /dev/null
+++ b/packages/dashboard/src/components/spree/products/digital-files-form-card.tsx
@@ -0,0 +1,214 @@
+import { formatFileSize, type ProductFormValues, useDirectUpload } from '@spree/dashboard-core'
+import {
+ Button,
+ Card,
+ CardAction,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ FileTypeIcon,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+ toastManager,
+ useConfirm,
+} from '@spree/dashboard-ui'
+import { FileIcon, Loader2Icon, UploadIcon, XIcon } from 'lucide-react'
+import { useCallback, useRef, useState } from 'react'
+import type { UseFormReturn } from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
+
+interface PendingUpload {
+ id: string
+ name: string
+}
+
+/**
+ * Create-time digital files: buffers uploads to private storage and stages them
+ * in the product form's `digital_assets` field, so a new product ships its
+ * downloadable files in the same POST. The edit page uses the live, API-driven
+ * {@link DigitalAssetsCard} instead — this card is for products that don't exist
+ * yet, so it can't issue per-asset requests.
+ */
+export function DigitalFilesFormCard({
+ form,
+}: {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ form: UseFormReturn<ProductFormValues, any, any>
+}) {
+ const { t } = useTranslation()
+ const confirm = useConfirm()
+ // Files are only ever served through an authorized, signed link, so they go
+ // to private storage — never the public bucket.
+ const directUpload = useDirectUpload({ private: true })
+ const [pending, setPending] = useState<PendingUpload[]>([])
+ const fileInputRef = useRef<HTMLInputElement>(null)
+
+ const items = form.watch('digital_assets') ?? []
+
+ const handleFiles = useCallback(
+ async (files: FileList | File[]) => {
+ const fileArray = Array.from(files)
+ for (const file of fileArray) {
+ const uploadId = crypto.randomUUID()
+ setPending((prev) => [...prev, { id: uploadId, name: file.name }])
+ try {
+ const { signedId } = await directUpload.mutateAsync(file)
+ const current = form.getValues('digital_assets') ?? []
+ form.setValue(
+ 'digital_assets',
+ [
+ ...current,
+ { signed_id: signedId, filename: file.name, byteSize: file.size, uploadId },
+ ],
+ { shouldDirty: true },
+ )
+ } catch (err) {
+ const message = err instanceof Error ? err.message : t('admin.errors.unexpected')
+ toastManager.add({
+ type: 'error',
+ title: t('admin.digital_assets.upload_failed', { name: file.name, message }),
+ })
+ } finally {
+ setPending((prev) => prev.filter((p) => p.id !== uploadId))
+ }
+ }
+ },
+ [directUpload, form, t],
+ )
+
+ function handleFileInput(event: React.ChangeEvent<HTMLInputElement>) {
+ const files = event.target.files
+ event.target.value = ''
+ if (files) void handleFiles(files)
+ }
+
+ function handleDrop(event: React.DragEvent) {
+ event.preventDefault()
+ if (event.dataTransfer.files.length > 0) void handleFiles(event.dataTransfer.files)
+ }
+
+ async function handleRemove(index: number) {
+ const current = form.getValues('digital_assets') ?? []
+ const entry = current[index]
+ const confirmed = await confirm({
+ title: t('admin.digital_assets.delete_title'),
+ message: t('admin.digital_assets.delete_description', {
+ name: entry?.filename ?? t('admin.digital_assets.untitled'),
+ }),
+ variant: 'destructive',
+ })
+ if (!confirmed) return
+ form.setValue(
+ 'digital_assets',
+ current.filter((_, i) => i !== index),
+ { shouldDirty: true },
+ )
+ }
+
+ const empty = items.length === 0 && pending.length === 0
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('admin.digital_assets.title')}</CardTitle>
+ {!empty && (
+ <CardAction>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => fileInputRef.current?.click()}
+ >
+ <UploadIcon className="mr-2 size-4" />
+ {t('admin.digital_assets.upload')}
+ </Button>
+ </CardAction>
+ )}
+ </CardHeader>
+
+ <CardContent className="flex flex-col gap-4">
+ <p className="text-muted-foreground text-sm">{t('admin.digital_assets.description')}</p>
+
+ <input
+ ref={fileInputRef}
+ type="file"
+ multiple
+ className="hidden"
+ onChange={handleFileInput}
+ />
+
+ {empty ? (
+ <button
+ type="button"
+ onDrop={handleDrop}
+ onDragOver={(e) => e.preventDefault()}
+ onClick={() => fileInputRef.current?.click()}
+ className="flex w-full cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed border-border p-6 text-center transition-colors hover:border-foreground/30"
+ >
+ <FileIcon className="size-8 text-muted-foreground" />
+ <p className="text-muted-foreground text-sm">{t('admin.digital_assets.drop_hint')}</p>
+ </button>
+ ) : (
+ <div className="overflow-hidden rounded-md border border-border">
+ <Table className="border-collapse [&_td]:rounded-none [&_td]:border [&_th]:border [&_td]:border-border [&_th]:border-border">
+ <TableHeader>
+ <TableRow>
+ <TableHead>{t('admin.digital_assets.columns.file')}</TableHead>
+ <TableHead>{t('admin.digital_assets.columns.size')}</TableHead>
+ <TableHead />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {items.map((entry, index) => (
+ <TableRow key={entry.uploadId ?? entry.signed_id}>
+ <TableCell className="font-medium">
+ <span className="flex items-center gap-2">
+ <FileTypeIcon
+ filename={entry.filename}
+ className="text-muted-foreground size-4 shrink-0"
+ />
+ {entry.filename ?? t('admin.digital_assets.untitled')}
+ </span>
+ </TableCell>
+ <TableCell className="text-muted-foreground">
+ {entry.byteSize != null ? formatFileSize(entry.byteSize) : '—'}
+ </TableCell>
+ <TableCell className="text-right">
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ aria-label={t('admin.actions.remove')}
+ onClick={() => handleRemove(index)}
+ >
+ <XIcon className="size-4" />
+ </Button>
+ </TableCell>
+ </TableRow>
+ ))}
+ {pending.map((upload) => (
+ <TableRow key={upload.id}>
+ <TableCell className="font-medium">
+ <span className="flex items-center gap-2 text-muted-foreground">
+ <Loader2Icon className="size-4 shrink-0 animate-spin" />
+ {upload.name}
+ </span>
+ </TableCell>
+ <TableCell className="text-muted-foreground">
+ {t('admin.digital_assets.uploading_short')}
+ </TableCell>
+ <TableCell />
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ )
+}
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index 2fec298cf7..369b3cbbe4 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -867,6 +867,7 @@
"title": "الملفات الرقمية",
"untitled": "ملف بدون اسم",
"upload": "إضافة ملف",
+ "upload_failed": "فشل رفع {{name}}: {{message}}",
"uploading": "جارٍ رفع {{name}}…",
"uploading_short": "جارٍ الرفع…"
},
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index 4fd4ab51a7..b13d9074d9 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -850,6 +850,7 @@
"title": "Digitale Dateien",
"untitled": "Unbenannte Datei",
"upload": "Datei hinzufügen",
+ "upload_failed": "Hochladen von {{name}} fehlgeschlagen: {{message}}",
"uploading": "{{name}} wird hochgeladen…",
"uploading_short": "Wird hochgeladen…"
},
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index 549bcec4b2..809a257eb1 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -850,6 +850,7 @@
"title": "Digital files",
"untitled": "Untitled file",
"upload": "Add file",
+ "upload_failed": "Failed to upload {{name}}: {{message}}",
"uploading": "Uploading {{name}}…",
"uploading_short": "Uploading…"
},
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index edc25750dd..a322e433bc 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -850,6 +850,7 @@
"title": "Fichiers numériques",
"untitled": "Fichier sans nom",
"upload": "Ajouter un fichier",
+ "upload_failed": "Échec du téléversement de {{name}} : {{message}}",
"uploading": "Téléversement de {{name}}…",
"uploading_short": "Téléversement…"
},
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index 5d2d73cbd2..178cefbc19 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -868,6 +868,7 @@
"title": "Pliki cyfrowe",
"untitled": "Plik bez nazwy",
"upload": "Dodaj plik",
+ "upload_failed": "Nie udało się przesłać {{name}}: {{message}}",
"uploading": "Przesyłanie {{name}}…",
"uploading_short": "Przesyłanie…"
},
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index 681437e4e7..275bc9e111 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -845,6 +845,7 @@
"title": "数字文件",
"untitled": "未命名文件",
"upload": "添加文件",
+ "upload_failed": "上传 {{name}} 失败:{{message}}",
"uploading": "正在上传 {{name}}…",
"uploading_short": "上传中…"
},
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx
index 1e44af67d3..c09219c968 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx
@@ -31,6 +31,7 @@ import { FormProvider, useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { CustomFieldsInlineCard } from '../../../../components/spree/custom-fields/custom-fields-inline'
import { MediaRichTextEditor } from '../../../../components/spree/media-rich-text-editor'
+import { DigitalFilesFormCard } from '../../../../components/spree/products/digital-files-form-card'
import { ProductCustomFieldsProvider } from '../../../../components/spree/products/product-custom-fields-provider'
import { PublishingCard } from '../../../../components/spree/products/publishing-card'
import { useCreateProduct } from '../../../../hooks/use-product'
@@ -53,7 +54,7 @@ function NewProductPage() {
})
const onSubmit = async (data: ProductFormValues) => {
- const { variants, custom_fields, media, ...rest } = data
+ const { variants, custom_fields, media, digital_assets, ...rest } = data
// Strip the placeholder default variant if the merchant didn't touch it.
// Spree::Product#variants= auto-creates the canonical default variant
@@ -84,6 +85,15 @@ function NewProductPage() {
}))
}
+ // Pre-save digital files: strip the UI-only fields (filename/byteSize are
+ // display-only, uploadId is a client key) and ship each signed_id. The
+ // server's Product#digital_assets= attaches them to the default variant
+ // after the product is created.
+ if (digital_assets && digital_assets.length > 0) {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ ;(payload as any).digital_assets = digital_assets.map(({ signed_id }) => ({ signed_id }))
+ }
+
// For simple products (single variant with no options) the merchant
// doesn't realise a default variant is auto-created server-side. Two routes:
//
@@ -188,6 +198,7 @@ function NewProductPage() {
productName={form.watch('name') || t('admin.pages.products.new.title')}
/>
<InventoryCard form={form} />
+ <DigitalFilesFormCard form={form} />
<ProductCustomFieldsProvider
form={form}
productTypeId={form.watch('product_type_id')}
diff --git a/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb
index e812ebb0aa..589cdedcf9 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb
@@ -248,6 +248,12 @@ module Spree
# server fetch a URL the caller chose, so it belongs to trusted
# importers rather than to a request body.
media: [*Spree::Media::WRITABLE_ATTRIBUTES, :id, :signed_id, :source_media_id, { variant_ids: [] }],
+ # Inline digital files, so a new product ships its downloadable
+ # files in the same request. Create-only: entries carry a
+ # `signed_id` (uploaded file) or a `provider_type` (provider-backed
+ # asset). Edits and deletes use the nested digital_assets endpoints.
+ # See `Spree::Product#digital_assets=`.
+ digital_assets: [:signed_id, :variant_id, :provider_type, :authorized_clicks, :authorized_days, provider_settings: {}],
product_publications: [:id, :channel_id, :published_at, :unpublished_at],
variants: [
:id, :sku, :barcode,
diff --git a/spree/api/app/serializers/spree/api/v3/admin/product_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/product_serializer.rb
index 6d6b286740..a0a894d09e 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/product_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/product_serializer.rb
@@ -88,6 +88,12 @@ module Spree
resource: proc { Spree.api.admin_media_serializer },
if: proc { expand?('media') }
+ # Read/write symmetry: the product accepts inline `digital_assets` on
+ # create, so it exposes them (opt-in via ?expand=digital_assets).
+ many :digital_assets,
+ resource: proc { Spree.api.admin_digital_asset_serializer },
+ if: proc { expand?('digital_assets') }
+
many :option_types,
resource: proc { Spree.api.admin_option_type_serializer },
if: proc { expand?('option_types') }
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb
index 6ad848846b..ec47870c81 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb
@@ -639,6 +639,48 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
expect(created.variants.count).to eq(1)
end
+ it 'attaches inline digital files to the new product' do
+ blob = ActiveStorage::Blob.create_and_upload!(
+ io: File.open(Spree::Core::Engine.root.join('spec', 'fixtures', 'thinking-cat.jpg')),
+ filename: 'manual.pdf',
+ content_type: 'application/pdf',
+ service_name: Spree.private_storage_service_name
+ )
+
+ expect {
+ post :create, params: {
+ name: 'downloadable product',
+ status: 'active',
+ digital_assets: [{ signed_id: blob.signed_id, authorized_clicks: 5 }]
+ }, as: :json
+ }.to change(Spree::Product, :count).by(1).and change(Spree::DigitalAsset, :count).by(1)
+
+ expect(response).to have_http_status(:created)
+ created = Spree::Product.find_by(name: 'downloadable product')
+ asset = created.digital_assets.last
+ expect(asset.variant).to eq(created.default_variant)
+ expect(asset.attachment).to be_attached
+ expect(asset.authorized_clicks).to eq(5)
+ end
+
+ it 'refuses an inline digital file uploaded to public storage' do
+ public_blob = ActiveStorage::Blob.create_and_upload!(
+ io: File.open(Spree::Core::Engine.root.join('spec', 'fixtures', 'thinking-cat.jpg')),
+ filename: 'manual.pdf',
+ content_type: 'application/pdf'
+ )
+ allow(Spree).to receive(:private_storage_service_name).and_return(:private_bucket)
+
+ expect {
+ post :create, params: {
+ name: 'wrong bucket product',
+ digital_assets: [{ signed_id: public_blob.signed_id }]
+ }, as: :json
+ }.not_to change(Spree::DigitalAsset, :count)
+
+ expect(response).to have_http_status(:unprocessable_content)
+ end
+
it 'returns 422 with field-level details for an unknown custom_field_definition_id' do
expect {
post :create, params: {
diff --git a/spree/core/app/workflows/spree/products/create.rb b/spree/core/app/workflows/spree/products/create.rb
index f580355b28..8fc3db3424 100644
--- a/spree/core/app/workflows/spree/products/create.rb
+++ b/spree/core/app/workflows/spree/products/create.rb
@@ -64,7 +64,8 @@ module Spree
# against a product that has an id.
@variants_params = attrs[:variants]
@media_params = attrs[:media]
- @product.assign_attributes(attrs.except(:variants, :media))
+ @digital_assets_params = attrs[:digital_assets]
+ @product.assign_attributes(attrs.except(:variants, :media, :digital_assets))
end
def save_product
@@ -74,6 +75,7 @@ module Spree
def apply_nested_attributes
apply_variants(product, @variants_params)
apply_media(product, @media_params)
+ apply_digital_assets(product, @digital_assets_params)
end
end
end
diff --git a/spree/core/app/workflows/spree/products/nested_attributes.rb b/spree/core/app/workflows/spree/products/nested_attributes.rb
index 41428a0c68..97258361c5 100644
--- a/spree/core/app/workflows/spree/products/nested_attributes.rb
+++ b/spree/core/app/workflows/spree/products/nested_attributes.rb
@@ -184,6 +184,43 @@ module Spree
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. Create-only,
+ # additive: 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. Edits and deletes go through
+ # the nested digital_assets endpoints.
+ #
+ # @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
+
+ signed_id = attrs.delete(:signed_id)
+ variant_id = attrs.delete(:variant_id)
+ target = variant_id.present? ? product.variants.find_by_param!(variant_id) : product.default_variant
+ next unless target
+
+ asset = target.digital_assets.build(attrs.except(:id))
+ 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
+ raise ActiveRecord::RecordInvalid.new(asset)
+ end
+
+ asset.attachment.attach(signed_id)
+ end
+ asset.save!
+ end
+ end
end
end
end
diff --git a/spree/core/app/workflows/spree/products/update.rb b/spree/core/app/workflows/spree/products/update.rb
index 4bfc88df37..99eb81e89e 100644
--- a/spree/core/app/workflows/spree/products/update.rb
+++ b/spree/core/app/workflows/spree/products/update.rb
@@ -48,7 +48,8 @@ module Spree
# rather than a half-applied collection.
@variants_params = attrs[:variants]
@media_params = attrs[:media]
- product.assign_attributes(attrs.except(:variants, :media))
+ @digital_assets_params = attrs[:digital_assets]
+ product.assign_attributes(attrs.except(:variants, :media, :digital_assets))
end
# Leaving review is a decision, and a decision belongs to Approve or
@@ -75,6 +76,7 @@ module Spree
def apply_nested_attributes
apply_variants(product, @variants_params)
apply_media(product, @media_params)
+ apply_digital_assets(product, @digital_assets_params)
end
end
end
diff --git a/spree/core/spec/workflows/spree/products/lifecycle_spec.rb b/spree/core/spec/workflows/spree/products/lifecycle_spec.rb
index 763ac1a3a5..ca962051e3 100644
--- a/spree/core/spec/workflows/spree/products/lifecycle_spec.rb
+++ b/spree/core/spec/workflows/spree/products/lifecycle_spec.rb
@@ -74,6 +74,74 @@ module Spree
expect(result.value.variants.map(&:sku)).to include('WV-1')
end
+ context 'with inline digital files' do
+ let(:blob) do
+ ActiveStorage::Blob.create_and_upload!(
+ io: File.open(Spree::Core::Engine.root.join('spec', 'fixtures', 'thinking-cat.jpg')),
+ filename: 'manual.pdf',
+ content_type: 'application/pdf',
+ service_name: Spree.private_storage_service_name
+ )
+ end
+
+ it 'attaches an uploaded file to the new product default variant' do
+ result = described_class.call(
+ store: store,
+ attributes: { name: 'Downloadable', digital_assets: [{ signed_id: blob.signed_id, authorized_clicks: 3 }] }
+ )
+
+ expect(result).to be_success
+ asset = result.value.digital_assets.last
+ expect(asset.variant).to eq(result.value.default_variant)
+ expect(asset.attachment).to be_attached
+ expect(asset.authorized_clicks).to eq(3)
+ end
+
+ it 'attaches a provider-backed asset with no file' do
+ stub_provider = Class.new(Spree::DigitalAssetProvider::Base) do
+ def self.requires_attachment? = false
+ end
+ stub_const('Spree::DigitalAssetProvider::Stub', stub_provider)
+ Spree.digital_asset_providers << stub_provider
+
+ result = described_class.call(
+ store: store,
+ attributes: {
+ name: 'Provider backed',
+ digital_assets: [{ provider_type: 'Spree::DigitalAssetProvider::Stub', provider_settings: { 'pool' => 'winter' } }]
+ }
+ )
+
+ expect(result).to be_success
+ asset = result.value.digital_assets.last
+ expect(asset.provider_type).to eq('Spree::DigitalAssetProvider::Stub')
+ expect(asset.provider_settings).to eq('pool' => 'winter')
+ ensure
+ Spree.digital_asset_providers.delete(stub_provider)
+ end
+
+ # A file on the wrong bucket is refused the same way an invalid variant
+ # is — the nested step raises, the transaction rolls back, and the API
+ # layer turns it into a 422. Nothing is left behind.
+ it 'refuses a file uploaded to public storage' do
+ public_blob = ActiveStorage::Blob.create_and_upload!(
+ io: File.open(Spree::Core::Engine.root.join('spec', 'fixtures', 'thinking-cat.jpg')),
+ filename: 'manual.pdf',
+ content_type: 'application/pdf'
+ )
+ allow(Spree).to receive(:private_storage_service_name).and_return(:private_bucket)
+
+ expect do
+ expect do
+ described_class.call(
+ store: store,
+ attributes: { name: 'Wrong bucket', digital_assets: [{ signed_id: public_blob.signed_id }] }
+ )
+ end.to raise_error(ActiveRecord::RecordInvalid)
+ end.to change(Spree::Product, :count).by(0).and change(Spree::DigitalAsset, :count).by(0)
+ end
+ end
+
# The CSV importer assigns attributes across several steps and hands over
# the record rather than a hash.
it 'accepts an already-built product' do