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
Make the digital files card read like a listing
Damian Legawiecd97c5a455f87
diff --git a/packages/admin-sdk/src/types/generated/DigitalAsset.ts b/packages/admin-sdk/src/types/generated/DigitalAsset.tsindex d1ad4eec28..cde48396fb 100644--- a/packages/admin-sdk/src/types/generated/DigitalAsset.ts+++ b/packages/admin-sdk/src/types/generated/DigitalAsset.ts@@ -1,4 +1,4 @@-// Typelizer digest d29bb4005881ad3f5a627226586ba035+// Typelizer digest 3db1dfd6fed0d31eafcb3777caba36cc//// DO NOT MODIFY: This file was automatically generated by Typelizer.@@ -12,6 +12,7 @@ interface DigitalAsset {byte_size: number | null;created_at: string;updated_at: string;+ download_url: string | null;effective_authorized_clicks: number;effective_authorized_days: number;}diff --git a/packages/dashboard-ui/src/index.ts b/packages/dashboard-ui/src/index.tsindex 3dfb215215..e4bb04aa4d 100644--- a/packages/dashboard-ui/src/index.ts+++ b/packages/dashboard-ui/src/index.ts@@ -37,6 +37,7 @@ export * from './spree/copy-to-clipboard-button'export * from './spree/country-flag'export * from './spree/data-grid'export * from './spree/drag-handle'+export * from './spree/file-type-icon'export * from './spree/form-actions'// JsonPreviewDrawer and JsonValueView are intentionally NOT re-exported fromdiff --git a/packages/dashboard-ui/src/spree/file-type-icon.tsx b/packages/dashboard-ui/src/spree/file-type-icon.tsxnew file mode 100644index 0000000000..b45200264b--- /dev/null+++ b/packages/dashboard-ui/src/spree/file-type-icon.tsx@@ -0,0 +1,68 @@+import {+ FileArchiveIcon,+ FileAudioIcon,+ FileCodeIcon,+ FileIcon,+ FileImageIcon,+ FileSpreadsheetIcon,+ FileTextIcon,+ FileVideoIcon,+} from 'lucide-react'+import type { ComponentType } from 'react'++type IconComponent = ComponentType<{ className?: string }>++// Matched on the MIME type where it is specific enough, then on the extension —+// servers routinely hand back `application/octet-stream` for anything they do+// not recognise, which would otherwise flatten every row to a blank page icon.+const BY_SUBTYPE: Array<[RegExp, IconComponent]> = [+ [/^image\//, FileImageIcon],+ [/^audio\//, FileAudioIcon],+ [/^video\//, FileVideoIcon],+ [/(zip|compressed|tar|gzip|rar|7z)/, FileArchiveIcon],+ [/(spreadsheet|excel|csv)/, FileSpreadsheetIcon],+ [/(json|xml|javascript|typescript|html|x-ruby|x-python|x-sh)/, FileCodeIcon],+ [/(pdf|word|document|text|rtf|epub)/, FileTextIcon],+]++const BY_EXTENSION: Array<[RegExp, IconComponent]> = [+ [/\.(png|jpe?g|gif|webp|svg|avif|heic|tiff?)$/i, FileImageIcon],+ [/\.(mp3|wav|flac|aac|ogg|m4a|aiff?)$/i, FileAudioIcon],+ [/\.(mp4|mov|avi|mkv|webm|m4v)$/i, FileVideoIcon],+ [/\.(zip|rar|7z|tar|gz|bz2|dmg|iso)$/i, FileArchiveIcon],+ [/\.(csv|tsv|xlsx?|numbers|ods)$/i, FileSpreadsheetIcon],+ [/\.(json|xml|ya?ml|js|ts|tsx|rb|py|sh|css|html?)$/i, FileCodeIcon],+ [/\.(pdf|docx?|txt|rtf|md|epub|pages)$/i, FileTextIcon],+]++/**+ * Picks the icon for a downloadable file. Falls back to a plain page rather+ * than guessing, so an unknown type reads as "a file" instead of the wrong one.+ */+export function fileTypeIcon(filename?: string | null, contentType?: string | null): IconComponent {+ const type = contentType?.toLowerCase() ?? ''+ for (const [pattern, icon] of BY_SUBTYPE) {+ if (pattern.test(type)) return icon+ }++ const name = filename ?? ''+ for (const [pattern, icon] of BY_EXTENSION) {+ if (pattern.test(name)) return icon+ }++ return FileIcon+}++/** Convenience wrapper for the common `<FileTypeIcon .../>` call site. */+export function FileTypeIcon({+ filename,+ contentType,+ className,+}: {+ filename?: string | null+ contentType?: string | null+ className?: string+}) {+ const Icon = fileTypeIcon(filename, contentType)+ return <Icon className={className} />+}diff --git a/packages/dashboard/src/components/spree/products/digital-asset-edit-sheet.tsx b/packages/dashboard/src/components/spree/products/digital-asset-edit-sheet.tsxnew file mode 100644index 0000000000..078469bf81--- /dev/null+++ b/packages/dashboard/src/components/spree/products/digital-asset-edit-sheet.tsx@@ -0,0 +1,159 @@+import type { DigitalAsset, Variant } from '@spree/admin-sdk'+import {+ Button,+ Field,+ FieldLabel,+ Input,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+ Sheet,+ SheetContent,+ SheetFooter,+ SheetHeader,+ SheetTitle,+} from '@spree/dashboard-ui'+import { useEffect, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { useUpdateDigitalAsset } from '../../../hooks/use-digital-assets'++interface Props {+ productId: string+ asset: DigitalAsset | null+ variants?: Variant[]+ open: boolean+ onOpenChange: (open: boolean) => void+}++/** Blank means "use the store's setting", so an empty box is a real value. */+function toInput(value: number | null | undefined): string {+ return value == null ? '' : String(value)+}++function parseLimit(raw: string): number | null | undefined {+ if (raw.trim() === '') return null+ const parsed = Number(raw)+ return Number.isInteger(parsed) && parsed >= 1 ? parsed : undefined+}++export function DigitalAssetEditSheet({ productId, asset, variants, open, onOpenChange }: Props) {+ const { t } = useTranslation()+ const updateAsset = useUpdateDigitalAsset(productId)++ const [clicks, setClicks] = useState('')+ const [days, setDays] = useState('')+ const [variantId, setVariantId] = useState('')+ const [error, setError] = useState<string | null>(null)++ // Re-seed whenever a different file is opened, so the sheet never shows the+ // previous row's values.+ useEffect(() => {+ if (!asset) return+ setClicks(toInput(asset.authorized_clicks))+ setDays(toInput(asset.authorized_days))+ setVariantId(asset.variant_id ?? '')+ setError(null)+ }, [asset])++ if (!asset) return null++ const hasVariants = (variants?.length ?? 0) > 1++ async function handleSave() {+ const parsedClicks = parseLimit(clicks)+ const parsedDays = parseLimit(days)++ if (parsedClicks === undefined || parsedDays === undefined) {+ setError(t('admin.digital_assets.limit_invalid'))+ return+ }++ await updateAsset.mutateAsync({+ id: asset!.id,+ authorized_clicks: parsedClicks,+ authorized_days: parsedDays,+ ...(hasVariants && variantId ? { variant_id: variantId } : {}),+ })+ onOpenChange(false)+ }++ return (+ <Sheet open={open} onOpenChange={onOpenChange}>+ <SheetContent side="right" className="flex flex-col">+ <SheetHeader>+ <SheetTitle>{asset.filename ?? t('admin.digital_assets.untitled')}</SheetTitle>+ </SheetHeader>++ <div className="flex flex-1 flex-col gap-6 overflow-y-auto p-4">+ {hasVariants && (+ <Field>+ <FieldLabel htmlFor="digital-asset-variant">+ {t('admin.digital_assets.columns.variant')}+ </FieldLabel>+ <Select value={variantId} onValueChange={setVariantId}>+ <SelectTrigger id="digital-asset-variant">+ <SelectValue>+ {(value) =>+ variants?.find((v) => v.id === value)?.options_text ??+ t('admin.digital_assets.all_variants')+ }+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ {variants?.map((variant) => (+ <SelectItem key={variant.id} value={variant.id}>+ {variant.options_text || variant.sku}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>+ )}++ <Field>+ <FieldLabel htmlFor="digital-asset-clicks">+ {t('admin.fields.store.digital_asset_authorized_clicks.label')}+ </FieldLabel>+ <Input+ id="digital-asset-clicks"+ type="number"+ min={1}+ value={clicks}+ placeholder={String(asset.effective_authorized_clicks)}+ onChange={(e) => setClicks(e.target.value)}+ />+ </Field>++ <Field>+ <FieldLabel htmlFor="digital-asset-days">+ {t('admin.fields.store.digital_asset_authorized_days.label')}+ </FieldLabel>+ <Input+ id="digital-asset-days"+ type="number"+ min={1}+ value={days}+ placeholder={String(asset.effective_authorized_days)}+ onChange={(e) => setDays(e.target.value)}+ />+ </Field>++ <p className="text-muted-foreground text-xs">{t('admin.digital_assets.limits_help')}</p>++ {error && <p className="text-destructive text-sm">{error}</p>}+ </div>++ <SheetFooter>+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>+ {t('admin.actions.cancel')}+ </Button>+ <Button type="button" onClick={handleSave} disabled={updateAsset.isPending}>+ {updateAsset.isPending ? t('admin.actions.saving') : t('admin.actions.save')}+ </Button>+ </SheetFooter>+ </SheetContent>+ </Sheet>+ )+}diff --git a/packages/dashboard/src/components/spree/products/digital-assets-card.tsx b/packages/dashboard/src/components/spree/products/digital-assets-card.tsxindex ce9b301b2b..046bff577c 100644--- a/packages/dashboard/src/components/spree/products/digital-assets-card.tsx+++ b/packages/dashboard/src/components/spree/products/digital-assets-card.tsx@@ -3,16 +3,13 @@ import { formatFileSize, useDirectUpload } from '@spree/dashboard-core'import {Button,Card,+ CardAction,CardContent,CardHeader,CardTitle,- Input,+ FileTypeIcon,Pagination,- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,+ RowActions,Skeleton,Table,TableBody,@@ -22,17 +19,15 @@ import {TableRow,useConfirm,} from '@spree/dashboard-ui'-import { FileIcon, Trash2Icon, UploadIcon } from 'lucide-react'+import { DownloadIcon, FileIcon, UploadIcon } from 'lucide-react'import { useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import {useCreateDigitalAsset,useDeleteDigitalAsset,useDigitalAssets,- useUpdateDigitalAsset,} from '../../../hooks/use-digital-assets'--type LimitField = 'authorized_clicks' | 'authorized_days'+import { DigitalAssetEditSheet } from './digital-asset-edit-sheet'export function DigitalAssetsCard({productId,@@ -44,16 +39,15 @@ export function DigitalAssetsCard({const { t } = useTranslation()const confirm = useConfirm()const fileInputRef = useRef<HTMLInputElement>(null)- const [uploadingName, setUploadingName] = useState<string | null>(null)- const [selectedVariantId, setSelectedVariantId] = useState<string>('')+ const [uploading, setUploading] = useState(false)const [page, setPage] = useState(1)+ const [editing, setEditing] = useState<DigitalAsset | null>(null)// Digital files live on private storage: they are only ever served through an// authorized, signed link, never from the public bucket.const directUpload = useDirectUpload({ private: true })const { data, isLoading } = useDigitalAssets(productId ?? '', page, Boolean(productId))const createAsset = useCreateDigitalAsset(productId ?? '')- const updateAsset = useUpdateDigitalAsset(productId ?? '')const deleteAsset = useDeleteDigitalAsset(productId ?? '')const assets: DigitalAsset[] = data?.data ?? []@@ -65,16 +59,13 @@ export function DigitalAssetsCard({event.target.value = ''if (!file || !productId) return- setUploadingName(file.name)+ setUploading(true)try {const { signedId } = await directUpload.mutateAsync(file)- await createAsset.mutateAsync({- signed_id: signedId,- ...(selectedVariantId ? { variant_id: selectedVariantId } : {}),- })+ await createAsset.mutateAsync({ signed_id: signedId })setPage(1)} finally {- setUploadingName(null)+ setUploading(false)}}@@ -89,40 +80,10 @@ export function DigitalAssetsCard({if (confirmed) await deleteAsset.mutateAsync(asset.id)}- // Blank means "use the store setting", so an empty box is a real value.- function handleLimitChange(asset: DigitalAsset, field: LimitField, raw: string) {- const parsed = raw.trim() === '' ? null : Number(raw)- if (parsed !== null && (!Number.isFinite(parsed) || parsed < 1)) return-- updateAsset.mutate({ id: asset.id, [field]: parsed })- }-- function LimitCell({- asset,- field,- effective,- }: {- asset: DigitalAsset- field: LimitField- effective: number- }) {- const label = t(- field === 'authorized_clicks'- ? 'admin.digital_assets.columns.downloads'- : 'admin.digital_assets.columns.days',- )-- return (- <Input- type="number"- min={1}- className="w-24"- defaultValue={asset[field] ?? ''}- placeholder={String(effective)}- aria-label={label}- onBlur={(e) => handleLimitChange(asset, field, e.target.value)}- />- )+ // A blank limit means the store's setting applies — show the number actually+ // in force rather than an empty cell.+ function limitLabel(own: number | null | undefined, effective: number) {+ return own == null ? t('admin.digital_assets.store_default', { count: effective }) : String(own)}if (!productId) return null@@ -131,7 +92,23 @@ export function DigitalAssetsCard({<Card><CardHeader><CardTitle>{t('admin.digital_assets.title')}</CardTitle>+ <CardAction>+ <Button+ type="button"+ variant="outline"+ size="sm"+ disabled={uploading}+ onClick={() => fileInputRef.current?.click()}+ >+ <UploadIcon className="mr-2 size-4" />+ {uploading+ ? t('admin.digital_assets.uploading_short')+ : t('admin.digital_assets.upload')}+ </Button>+ <input ref={fileInputRef} type="file" className="hidden" onChange={handleFileSelected} />+ </CardAction></CardHeader>+<CardContent className="flex flex-col gap-4"><p className="text-muted-foreground text-sm">{t('admin.digital_assets.description')}</p>@@ -143,8 +120,8 @@ export function DigitalAssetsCard({<p className="text-muted-foreground text-sm">{t('admin.digital_assets.empty')}</p></div>) : (- <div className="overflow-x-auto">- <Table>+ <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>@@ -161,7 +138,25 @@ export function DigitalAssetsCard({{assets.map((asset) => (<TableRow key={asset.id}><TableCell className="font-medium">- {asset.filename ?? t('admin.digital_assets.untitled')}+ <span className="flex items-center gap-2">+ <FileTypeIcon+ filename={asset.filename}+ contentType={asset.content_type}+ className="text-muted-foreground size-4 shrink-0"+ />+ {asset.download_url ? (+ <a+ href={asset.download_url}+ target="_blank"+ rel="noreferrer"+ className="hover:underline"+ >+ {asset.filename ?? t('admin.digital_assets.untitled')}+ </a>+ ) : (+ (asset.filename ?? t('admin.digital_assets.untitled'))+ )}+ </span></TableCell>{hasVariants && (<TableCell className="text-muted-foreground">@@ -171,30 +166,30 @@ export function DigitalAssetsCard({<TableCell className="tabular-nums">{asset.byte_size ? formatFileSize(asset.byte_size) : '—'}</TableCell>- <TableCell>- <LimitCell- asset={asset}- field="authorized_clicks"- effective={asset.effective_authorized_clicks}- />+ <TableCell className="tabular-nums">+ {limitLabel(asset.authorized_clicks, asset.effective_authorized_clicks)}</TableCell>- <TableCell>- <LimitCell- asset={asset}- field="authorized_days"- effective={asset.effective_authorized_days}- />+ <TableCell className="tabular-nums">+ {limitLabel(asset.authorized_days, asset.effective_authorized_days)}</TableCell><TableCell className="text-right">- <Button- type="button"- variant="ghost"- size="icon"- aria-label={t('admin.common.delete')}- onClick={() => handleDelete(asset)}- >- <Trash2Icon className="size-4" />- </Button>+ <RowActions+ actions={[+ {+ key: 'download',+ label: t('admin.digital_assets.download'),+ icon: <DownloadIcon className="size-4" />,+ visible: Boolean(asset.download_url),+ onSelect: () => window.open(asset.download_url ?? '', '_blank'),+ },+ { key: 'edit', onSelect: () => setEditing(asset) },+ {+ key: 'delete',+ destructive: true,+ onSelect: () => handleDelete(asset),+ },+ ]}+ /></TableCell></TableRow>))}@@ -203,45 +198,15 @@ export function DigitalAssetsCard({{meta && <Pagination meta={meta} onPageChange={setPage} />}</div>)}-- <div className="flex flex-wrap items-center gap-2">- {hasVariants && (- <Select value={selectedVariantId} onValueChange={setSelectedVariantId}>- <SelectTrigger className="w-56">- <SelectValue placeholder={t('admin.digital_assets.all_variants')}>- {(value) =>- variants?.find((v) => v.id === value)?.options_text ??- t('admin.digital_assets.all_variants')- }- </SelectValue>- </SelectTrigger>- <SelectContent>- {variants?.map((variant) => (- <SelectItem key={variant.id} value={variant.id}>- {variant.options_text || variant.sku}- </SelectItem>- ))}- </SelectContent>- </Select>- )}-- <Button- type="button"- variant="outline"- disabled={Boolean(uploadingName)}- onClick={() => fileInputRef.current?.click()}- >- <UploadIcon className="mr-2 size-4" />- {uploadingName- ? t('admin.digital_assets.uploading', { name: uploadingName })- : t('admin.digital_assets.upload')}- </Button>-- <input ref={fileInputRef} type="file" className="hidden" onChange={handleFileSelected} />- </div>-- <p className="text-muted-foreground text-xs">{t('admin.digital_assets.limits_help')}</p></CardContent>++ <DigitalAssetEditSheet+ productId={productId}+ asset={editing}+ variants={variants}+ open={Boolean(editing)}+ onOpenChange={(open) => !open && setEditing(null)}+ /></Card>)}diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex c6b695d8fe..f4e7481d88 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -854,12 +854,16 @@"delete_description": "لن يتمكن من اشترى «{{name}}» من تنزيله بعد الآن. يسري هذا فورًا.","delete_title": "حذف هذا الملف؟","description": "ملفات يمكن للمشترين تنزيلها بعد الشراء. أرفقها بمنتج رقمي، أو بمنتج مادي لتسليم دليل أو ضمان مع البضاعة.",+ "download": "تنزيل","empty": "لا توجد ملفات بعد",+ "limit_invalid": "يجب أن تكون الحدود أعدادًا صحيحة من 1 فأكثر، أو فارغة.","limits_help": "اترك حدود التنزيل والأيام فارغة لاستخدام إعدادات المتجر.",+ "store_default": "{{count}} (افتراضي المتجر)","title": "الملفات الرقمية","untitled": "ملف بدون اسم","upload": "إضافة ملف",- "uploading": "جارٍ رفع {{name}}…"+ "uploading": "جارٍ رفع {{name}}…",+ "uploading_short": "جارٍ الرفع…"},"digital_links": {"columns": {diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex 50a01e6951..7eb7a2bb04 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -837,12 +837,16 @@"delete_description": "„{{name}}“ kann von niemandem mehr heruntergeladen werden, der sie gekauft hat. Dies wirkt sofort.","delete_title": "Diese Datei löschen?","description": "Dateien, die Käufer nach dem Kauf herunterladen können. Fügen Sie sie einem digitalen Produkt hinzu oder einem physischen, um eine Anleitung oder Garantie mitzuliefern.",+ "download": "Herunterladen","empty": "Noch keine Dateien",+ "limit_invalid": "Limits müssen ganze Zahlen ab 1 sein oder leer bleiben.","limits_help": "Lassen Sie die Download- und Tageslimits leer, um die Einstellungen des Shops zu verwenden.",+ "store_default": "{{count}} (Shop-Standard)","title": "Digitale Dateien","untitled": "Unbenannte Datei","upload": "Datei hinzufügen",- "uploading": "{{name}} wird hochgeladen…"+ "uploading": "{{name}} wird hochgeladen…",+ "uploading_short": "Wird hochgeladen…"},"digital_links": {"columns": {diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex 86ec937ef8..25183e3956 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -837,12 +837,16 @@"delete_description": "\"{{name}}\" will no longer be downloadable by anyone who bought it. This takes effect immediately.","delete_title": "Delete this file?","description": "Files buyers can download after purchase. Attach them to a digital product, or to a physical one to deliver a manual or warranty alongside the goods.",+ "download": "Download","empty": "No files yet",+ "limit_invalid": "Limits must be whole numbers of 1 or more, or blank.","limits_help": "Leave the download and day limits blank to use the store's settings.",+ "store_default": "{{count}} (store default)","title": "Digital files","untitled": "Untitled file","upload": "Add file",- "uploading": "Uploading {{name}}…"+ "uploading": "Uploading {{name}}…",+ "uploading_short": "Uploading…"},"digital_links": {"columns": {diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex 84477a5a70..a5953e731e 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -837,12 +837,16 @@"delete_description": "« {{name}} » ne sera plus téléchargeable par les personnes qui l'ont acheté. Effet immédiat.","delete_title": "Supprimer ce fichier ?","description": "Fichiers que les acheteurs peuvent télécharger après l'achat. Associez-les à un produit numérique, ou à un produit physique pour livrer un manuel ou une garantie.",+ "download": "Télécharger","empty": "Aucun fichier pour le moment",+ "limit_invalid": "Les limites doivent être des entiers supérieurs ou égaux à 1, ou vides.","limits_help": "Laissez les limites de téléchargements et de jours vides pour utiliser les paramètres de la boutique.",+ "store_default": "{{count}} (par défaut)","title": "Fichiers numériques","untitled": "Fichier sans nom","upload": "Ajouter un fichier",- "uploading": "Téléversement de {{name}}…"+ "uploading": "Téléversement de {{name}}…",+ "uploading_short": "Téléversement…"},"digital_links": {"columns": {diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex 6ac7d7284b..8c3675d2ef 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -855,12 +855,16 @@"delete_description": "„{{name}}” nie będzie już dostępny do pobrania dla osób, które go kupiły. Zmiana działa natychmiast.","delete_title": "Usunąć ten plik?","description": "Pliki, które kupujący mogą pobrać po zakupie. Dołącz je do produktu cyfrowego lub do fizycznego, aby dostarczyć instrukcję albo gwarancję.",+ "download": "Pobierz","empty": "Brak plików",+ "limit_invalid": "Limity muszą być liczbami całkowitymi od 1 lub puste.","limits_help": "Pozostaw limity pobrań i dni puste, aby użyć ustawień sklepu.",+ "store_default": "{{count}} (domyślne sklepu)","title": "Pliki cyfrowe","untitled": "Plik bez nazwy","upload": "Dodaj plik",- "uploading": "Przesyłanie {{name}}…"+ "uploading": "Przesyłanie {{name}}…",+ "uploading_short": "Przesyłanie…"},"digital_links": {"columns": {diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex f785eabfc6..72bdc6c004 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -832,12 +832,16 @@"delete_description": "购买过“{{name}}”的人将无法再下载它。此操作立即生效。","delete_title": "删除此文件?","description": "买家购买后可下载的文件。可附加到数字商品,也可附加到实体商品以随货提供说明书或保修卡。",+ "download": "下载","empty": "暂无文件",+ "limit_invalid": "限制必须是不小于 1 的整数,或留空。","limits_help": "将下载次数和天数限制留空即可使用商店设置。",+ "store_default": "{{count}}(商店默认)","title": "数字文件","untitled": "未命名文件","upload": "添加文件",- "uploading": "正在上传 {{name}}…"+ "uploading": "正在上传 {{name}}…",+ "uploading_short": "上传中…"},"digital_links": {"columns": {diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsxindex 9298bc8705..8eb4f95e2d 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx@@ -283,7 +283,6 @@ function ProductForm({ product }: { product: Product }) {<GeneralCard form={form} descriptionEditor={MediaRichTextEditor} /><VariantsCard form={form} /><MediaCard productId={productId} variants={assignableVariants} form={form} />- <DigitalAssetsCard productId={productId} variants={assignableVariants} /><PricesCard form={form} productName={product.name} /><InventoryCardform={form}@@ -291,6 +290,7 @@ function ProductForm({ product }: { product: Product }) {`/${storeId}/settings/stock-locations?edit=${encodeURIComponent(id)}`}/>+ <DigitalAssetsCard productId={productId} variants={assignableVariants} /><ProductCustomFieldsProvider form={form} productTypeId={selectedProductTypeId}><CustomFieldsInlineCard /></ProductCustomFieldsProvider>diff --git a/spree/api/app/serializers/spree/api/v3/admin/digital_asset_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/digital_asset_serializer.rbindex b729829391..2a2c1f06f6 100644--- a/spree/api/app/serializers/spree/api/v3/admin/digital_asset_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/digital_asset_serializer.rb@@ -9,11 +9,27 @@ module Spreeauthorized_clicks: [:number, nullable: true],authorized_days: [:number, nullable: true],effective_authorized_clicks: :number,- effective_authorized_days: :number+ effective_authorized_days: :number,+ download_url: [:string, nullable: true]attributes :authorized_clicks, :authorized_days, :byte_sizeattributes created_at: :iso8601, updated_at: :iso8601+ # Lets a merchant check what they actually uploaded. Short-lived and+ # admin-only: this is the file itself, not a customer's download+ # grant, so it carries no counter and spends nobody's allowance.+ #+ # Nil outside a request: the Disk service needs a host, which only a+ # controller can supply, and event payloads are serialized without one.+ attribute :download_url do |digital_asset, params|+ store = params&.dig(:store) || Spree::Current.store || digital_asset.store+ begin+ digital_asset.download_url(expires_in: store.preferred_digital_asset_link_expire_time.seconds)+ rescue ArgumentError+ nil+ end+ end+# The limits actually applied, after the store-settings fallback. The# request's store answers it — an admin request always carries one;# the asset's own store covers serialization outside a request.diff --git a/spree/api/spec/controllers/spree/api/v3/admin/products/digital_assets_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/products/digital_assets_controller_spec.rbindex 54a6bf478c..085de48df6 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/products/digital_assets_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/products/digital_assets_controller_spec.rb@@ -29,6 +29,12 @@ RSpec.describe Spree::Api::V3::Admin::Products::DigitalAssetsController, type: :expect(json_response['data'].map { |a| a['id'] }).to include(digital_asset.prefixed_id)end+ it 'gives each file a download link so the merchant can check it' do+ get :index, params: { product_id: product.prefixed_id }++ expect(json_response['data'].first['download_url']).to be_present+ end+it 'does not list assets belonging to another product' doother = create(:digital_asset)diff --git a/spree/api/spec/serializers/spree/api/v3/digital_asset_serializer_spec.rb b/spree/api/spec/serializers/spree/api/v3/digital_asset_serializer_spec.rbindex bcd677db17..b9ceabbe83 100644--- a/spree/api/spec/serializers/spree/api/v3/digital_asset_serializer_spec.rb+++ b/spree/api/spec/serializers/spree/api/v3/digital_asset_serializer_spec.rb@@ -38,6 +38,12 @@ RSpec.describe Spree::Api::V3::DigitalAssetSerializer do)end+ # Event payloads serialize outside a request, where the Disk service has no+ # host to build a URL from — that must degrade, not raise.+ it 'leaves the download url blank when there is no request context' do+ expect(subject['download_url']).to be_nil+ end+it 'exposes the store fallback in the effective limits' dostore.update!(preferred_digital_asset_authorized_clicks: 5)