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
Add ImportButton and the CSV upload flow to @spree/dashboard-core
Damian Legawiec0f9944021847
diff --git a/packages/dashboard-core/src/components/import-button.tsx b/packages/dashboard-core/src/components/import-button.tsxnew file mode 100644index 0000000000..3f8028071f--- /dev/null+++ b/packages/dashboard-core/src/components/import-button.tsx@@ -0,0 +1,208 @@+import type { Import, ImportType } from '@spree/admin-sdk'+import {+ Button,+ cn,+ Dialog,+ DialogBody,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ Field,+ FieldLabel,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@spree/dashboard-ui'+import { DownloadIcon, FileSpreadsheetIcon, UploadIcon } from 'lucide-react'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import { toast } from 'sonner'+import { useCreateImport, useDownloadImportTemplate } from '../hooks/use-import'+import type { SubjectName } from '../lib/permissions'+import { Can } from './can'++const DELIMITERS = [+ { value: ',', labelKey: 'comma' },+ { value: ';', labelKey: 'semicolon' },+ { value: '|', labelKey: 'pipe' },+ { value: '\t', labelKey: 'tab' },+] as const++type Delimiter = (typeof DELIMITERS)[number]['value']++interface ImportButtonProps {+ /** Which dataset to import. Server validates against `Spree::Import.available_types`. */+ type: ImportType+ /**+ * CanCanCan subject gating the button — the *imported resource*+ * (e.g. `Subject.Product`), mirroring the server's `write_<resource>`+ * scope model. Purely UX; the backend authorizes every request.+ */+ subject: SubjectName+ /** Receives the created import (in `mapping` state); the app navigates to the wizard. */+ onCreated: (imp: Import) => void+ /** Label shown on the button. Defaults to the translated "Import" action. */+ label?: string+}++export function ImportButton({ type, subject, onCreated, label }: ImportButtonProps) {+ const { t } = useTranslation()+ const [open, setOpen] = useState(false)+ const [file, setFile] = useState<File | null>(null)+ const [delimiter, setDelimiter] = useState<Delimiter>(',')+ const createImport = useCreateImport()+ const downloadTemplate = useDownloadImportTemplate()++ const delimiterOptions = DELIMITERS.map(({ value, labelKey }) => ({+ value,+ label: t(`admin.components.import_button.delimiters.${labelKey}`),+ }))++ function handleOpenChange(next: boolean) {+ setOpen(next)+ if (!next) setFile(null)+ }++ function handleSubmit() {+ if (!file || createImport.isPending) return++ createImport.mutate(+ { type, file, preferredDelimiter: delimiter },+ {+ onSuccess: (imp) => {+ handleOpenChange(false)+ onCreated(imp)+ },+ onError: (err) => {+ toast.error(+ t('admin.components.import_button.failed', {+ message: err instanceof Error ? err.message : String(err),+ }),+ )+ },+ },+ )+ }++ function handleTemplateDownload() {+ downloadTemplate.mutate(type, {+ onError: (err) => {+ toast.error(+ t('admin.components.import_button.template_failed', {+ message: err instanceof Error ? err.message : String(err),+ }),+ )+ },+ })+ }++ return (+ <Can I="create" a={subject}>+ <Button+ size="sm"+ variant="outline"+ className="h-[2.125rem]"+ onClick={() => setOpen(true)}+ disabled={createImport.isPending}+ >+ <UploadIcon className="size-4" />+ {label ?? t('admin.actions.import')}+ </Button>++ <Dialog open={open} onOpenChange={handleOpenChange}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>{t('admin.components.import_button.title')}</DialogTitle>+ <DialogDescription>{t('admin.components.import_button.description')}</DialogDescription>+ </DialogHeader>++ <DialogBody className="flex flex-col gap-4">+ {/* A <label> wrapping the file input: clicking anywhere opens the+ picker natively, no JS forwarding needed. */}+ <label+ className={cn(+ 'flex cursor-pointer flex-col items-center justify-center gap-2 rounded-md border border-border border-dashed bg-muted/40 px-4 py-8 text-center transition-colors hover:bg-muted',+ file && 'border-solid',+ )}+ onDragOver={(e) => e.preventDefault()}+ onDrop={(e) => {+ e.preventDefault()+ const dropped = e.dataTransfer.files?.[0]+ if (dropped) setFile(dropped)+ }}+ >+ <FileSpreadsheetIcon className="size-6 text-muted-foreground" />+ {file ? (+ <span className="font-medium text-sm">{file.name}</span>+ ) : (+ <span className="text-muted-foreground text-sm">+ {t('admin.components.import_button.drop_label')}+ </span>+ )}+ <span className="mt-1 inline-flex h-8 items-center rounded-md border border-border bg-background px-3 font-medium text-sm shadow-xs">+ {t('admin.components.import_button.browse')}+ </span>+ <input+ type="file"+ accept=".csv,text/csv"+ className="hidden"+ onChange={(e) => {+ const picked = e.target.files?.[0]+ if (picked) setFile(picked)+ e.target.value = ''+ }}+ />+ </label>++ <Field>+ <FieldLabel>{t('admin.components.import_button.delimiter_label')}</FieldLabel>+ <Select+ items={delimiterOptions}+ value={delimiter}+ onValueChange={(value) => setDelimiter(value as Delimiter)}+ >+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {delimiterOptions.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>++ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="self-start"+ onClick={handleTemplateDownload}+ disabled={downloadTemplate.isPending}+ >+ <DownloadIcon className="size-4" />+ {t('admin.components.import_button.download_template')}+ </Button>+ </DialogBody>++ <DialogFooter>+ <Button variant="outline" onClick={() => handleOpenChange(false)}>+ {t('admin.actions.cancel')}+ </Button>+ <Button onClick={handleSubmit} disabled={!file || createImport.isPending}>+ {createImport.isPending+ ? t('admin.components.import_button.uploading')+ : t('admin.components.import_button.submit')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </Can>+ )+}diff --git a/packages/dashboard-core/src/hooks/use-import.ts b/packages/dashboard-core/src/hooks/use-import.tsnew file mode 100644index 0000000000..8315a705b9--- /dev/null+++ b/packages/dashboard-core/src/hooks/use-import.ts@@ -0,0 +1,69 @@+import type { Import, ImportCreateParams, ImportType } from '@spree/admin-sdk'+import { useMutation } from '@tanstack/react-query'+import { adminClient } from '../client'+import { useAuth } from './use-auth'+import { useDirectUpload } from './use-direct-upload'++const API_BASE_URL = import.meta.env.VITE_SPREE_API_URL || ''++export interface CreateImportInput {+ type: ImportType+ file: File+ preferredDelimiter?: ImportCreateParams['preferred_delimiter']+}++/**+ * Direct-uploads the CSV, then creates the import (returned in the `mapping`+ * state). The file is re-wrapped with an explicit `text/csv` content type —+ * Windows browsers report `.csv` files as `application/vnd.ms-excel`, which+ * the server's content-type validation rejects.+ */+export function useCreateImport() {+ const directUpload = useDirectUpload()++ return useMutation({+ mutationFn: async ({ type, file, preferredDelimiter }: CreateImportInput): Promise<Import> => {+ const csvFile = new File([file], file.name, { type: 'text/csv' })+ const { signedId } = await directUpload.mutateAsync(csvFile)++ return adminClient.imports.create({+ type,+ attachment: signedId,+ preferred_delimiter: preferredDelimiter,+ })+ },+ })+}++/**+ * Fetches the CSV template for an import type and drives a browser download+ * via a Blob URL — the endpoint is JWT-protected, so a top-level navigation+ * (which cannot carry the in-memory token) does not work.+ */+export function useDownloadImportTemplate() {+ const { token } = useAuth()++ return useMutation({+ mutationFn: async (type: ImportType): Promise<void> => {+ const url = `${API_BASE_URL}/api/v3/admin/imports/template?type=${encodeURIComponent(type)}`+ const headers: Record<string, string> = {}+ if (token) headers.Authorization = `Bearer ${token}`++ const response = await fetch(url, { headers, credentials: 'include' })+ if (!response.ok) throw new Error(`Template download failed: ${response.status}`)++ const disposition = response.headers.get('Content-Disposition')+ const filename = disposition?.match(/filename="?([^";]+)"?/)?.[1] ?? 'import_template.csv'++ const blob = await response.blob()+ const objectUrl = URL.createObjectURL(blob)+ const anchor = document.createElement('a')+ anchor.href = objectUrl+ anchor.download = filename+ document.body.appendChild(anchor)+ anchor.click()+ anchor.remove()+ URL.revokeObjectURL(objectUrl)+ },+ })+}diff --git a/packages/dashboard-core/src/index.ts b/packages/dashboard-core/src/index.tsindex 0498d88fdc..74b332e17d 100644--- a/packages/dashboard-core/src/index.ts+++ b/packages/dashboard-core/src/index.ts@@ -23,6 +23,7 @@ export * from './components/country-state-fields'export * from './components/currency-select'export * from './components/export-button'export * from './components/image-upload-field'+export * from './components/import-button'export * from './components/locale-select'export * from './components/market-combobox'export * from './components/nav-main'@@ -51,6 +52,7 @@ export * from './hooks/use-direct-upload'export * from './hooks/use-display-name'export * from './hooks/use-export'export * from './hooks/use-global-search'+export * from './hooks/use-import'export * from './hooks/use-resource-mutation'export * from './hooks/use-switch-admin-locale'// ---------------------------------------------------------------------------diff --git a/packages/dashboard-core/src/locales/ar.json b/packages/dashboard-core/src/locales/ar.jsonindex bdac2a98d8..bdad335a5e 100644--- a/packages/dashboard-core/src/locales/ar.json+++ b/packages/dashboard-core/src/locales/ar.json@@ -16,6 +16,7 @@"discard": "تجاهل","discard_changes": "تجاهل التغييرات","edit": "تعديل",+ "view": "عرض","generate": "إنشاء","remove": "إزالة","save": "حفظ",@@ -467,6 +468,24 @@"email_fallback": "لا يزال قيد المعالجة — سنرسل لك رابطًا بالبريد عند الجاهزية.","failed": "فشل التصدير: {{message}}"},+ "import_button": {+ "title": "استيراد من CSV",+ "description": "قم برفع ملف CSV. ستقوم بمطابقة أعمدته مع الحقول في الخطوة التالية.",+ "drop_label": "أسقط ملف CSV هنا، أو انقر للاستعراض",+ "browse": "استعراض الملفات",+ "delimiter_label": "فاصل الأعمدة",+ "delimiters": {+ "comma": "فاصلة (,)",+ "semicolon": "فاصلة منقوطة (;)",+ "pipe": "خط عمودي (|)",+ "tab": "مسافة جدولة"+ },+ "download_template": "تنزيل قالب CSV",+ "template_failed": "فشل تنزيل القالب: {{message}}",+ "submit": "رفع ومتابعة",+ "uploading": "جارٍ الرفع…",+ "failed": "فشل الاستيراد: {{message}}"+ },"metadata_card": {"title": "البيانات الوصفية","empty_title": "لا توجد بيانات وصفية",diff --git a/packages/dashboard-core/src/locales/de.json b/packages/dashboard-core/src/locales/de.jsonindex ce9993c380..388cd848ab 100644--- a/packages/dashboard-core/src/locales/de.json+++ b/packages/dashboard-core/src/locales/de.json@@ -16,6 +16,7 @@"discard": "Verwerfen","discard_changes": "Änderungen verwerfen","edit": "Bearbeiten",+ "view": "Anzeigen","generate": "Generieren","remove": "Entfernen","save": "Speichern",@@ -467,6 +468,24 @@"email_fallback": "Noch in Bearbeitung — wir senden Ihnen einen Link per E-Mail, sobald er fertig ist.","failed": "Export fehlgeschlagen: {{message}}"},+ "import_button": {+ "title": "Aus CSV importieren",+ "description": "Laden Sie eine CSV-Datei hoch. Im nächsten Schritt ordnen Sie ihre Spalten den Feldern zu.",+ "drop_label": "CSV-Datei hier ablegen oder klicken zum Auswählen",+ "browse": "Dateien durchsuchen",+ "delimiter_label": "Spaltentrennzeichen",+ "delimiters": {+ "comma": "Komma (,)",+ "semicolon": "Semikolon (;)",+ "pipe": "Pipe (|)",+ "tab": "Tabulator"+ },+ "download_template": "CSV-Vorlage herunterladen",+ "template_failed": "Vorlagen-Download fehlgeschlagen: {{message}}",+ "submit": "Hochladen & weiter",+ "uploading": "Wird hochgeladen…",+ "failed": "Import fehlgeschlagen: {{message}}"+ },"metadata_card": {"title": "Metadaten","empty_title": "Keine Metadaten",diff --git a/packages/dashboard-core/src/locales/en.json b/packages/dashboard-core/src/locales/en.jsonindex a5ec379484..cc961f6177 100644--- a/packages/dashboard-core/src/locales/en.json+++ b/packages/dashboard-core/src/locales/en.json@@ -16,6 +16,7 @@"discard": "Discard","discard_changes": "Discard changes","edit": "Edit",+ "view": "View","generate": "Generate","remove": "Remove","save": "Save",@@ -467,6 +468,24 @@"email_fallback": "Still processing — we'll email you a link when it's ready.","failed": "Export failed: {{message}}"},+ "import_button": {+ "title": "Import from CSV",+ "description": "Upload a CSV file. You'll match its columns to fields in the next step.",+ "drop_label": "Drop a CSV file here, or click to browse",+ "browse": "Browse files",+ "delimiter_label": "Column separator",+ "delimiters": {+ "comma": "Comma (,)",+ "semicolon": "Semicolon (;)",+ "pipe": "Pipe (|)",+ "tab": "Tab"+ },+ "download_template": "Download CSV template",+ "template_failed": "Template download failed: {{message}}",+ "submit": "Upload & continue",+ "uploading": "Uploading…",+ "failed": "Import failed: {{message}}"+ },"metadata_card": {"title": "Metadata","empty_title": "No metadata",diff --git a/packages/dashboard-core/src/locales/fr.json b/packages/dashboard-core/src/locales/fr.jsonindex 34326dc308..842c276101 100644--- a/packages/dashboard-core/src/locales/fr.json+++ b/packages/dashboard-core/src/locales/fr.json@@ -16,6 +16,7 @@"discard": "Abandonner","discard_changes": "Abandonner les modifications","edit": "Modifier",+ "view": "Afficher","generate": "Générer","remove": "Retirer","save": "Enregistrer",@@ -467,6 +468,24 @@"email_fallback": "Toujours en cours — nous vous enverrons un lien par e-mail dès qu’il sera prêt.","failed": "Échec de l’export : {{message}}"},+ "import_button": {+ "title": "Importer depuis un CSV",+ "description": "Téléversez un fichier CSV. Vous associerez ses colonnes aux champs à l'étape suivante.",+ "drop_label": "Déposez un fichier CSV ici ou cliquez pour parcourir",+ "browse": "Parcourir les fichiers",+ "delimiter_label": "Séparateur de colonnes",+ "delimiters": {+ "comma": "Virgule (,)",+ "semicolon": "Point-virgule (;)",+ "pipe": "Barre verticale (|)",+ "tab": "Tabulation"+ },+ "download_template": "Télécharger le modèle CSV",+ "template_failed": "Échec du téléchargement du modèle : {{message}}",+ "submit": "Téléverser et continuer",+ "uploading": "Téléversement…",+ "failed": "Échec de l'import : {{message}}"+ },"metadata_card": {"title": "Métadonnées","empty_title": "Aucune métadonnée",diff --git a/packages/dashboard-core/src/locales/pl.json b/packages/dashboard-core/src/locales/pl.jsonindex 59aa84b03d..d154a3a9c2 100644--- a/packages/dashboard-core/src/locales/pl.json+++ b/packages/dashboard-core/src/locales/pl.json@@ -16,6 +16,7 @@"discard": "Odrzuć","discard_changes": "Odrzuć zmiany","edit": "Edytuj",+ "view": "Zobacz","generate": "Generuj","remove": "Usuń","save": "Zapisz",@@ -467,6 +468,24 @@"email_fallback": "Nadal przetwarzamy — wyślemy link e-mailem, gdy będzie gotowy.","failed": "Eksport nie powiódł się: {{message}}"},+ "import_button": {+ "title": "Importuj z pliku CSV",+ "description": "Prześlij plik CSV. W następnym kroku dopasujesz jego kolumny do pól.",+ "drop_label": "Upuść plik CSV tutaj lub kliknij, aby przeglądać",+ "browse": "Przeglądaj pliki",+ "delimiter_label": "Separator kolumn",+ "delimiters": {+ "comma": "Przecinek (,)",+ "semicolon": "Średnik (;)",+ "pipe": "Kreska pionowa (|)",+ "tab": "Tabulator"+ },+ "download_template": "Pobierz szablon CSV",+ "template_failed": "Pobieranie szablonu nie powiodło się: {{message}}",+ "submit": "Prześlij i kontynuuj",+ "uploading": "Przesyłanie…",+ "failed": "Import nie powiódł się: {{message}}"+ },"metadata_card": {"title": "Metadane","empty_title": "Brak metadanych",diff --git a/packages/dashboard-core/src/locales/zh-CN.json b/packages/dashboard-core/src/locales/zh-CN.jsonindex 9f65c42e99..df371751ae 100644--- a/packages/dashboard-core/src/locales/zh-CN.json+++ b/packages/dashboard-core/src/locales/zh-CN.json@@ -16,6 +16,7 @@"discard": "放弃","discard_changes": "放弃更改","edit": "编辑",+ "view": "查看","generate": "生成","remove": "移除","save": "保存",@@ -467,6 +468,24 @@"email_fallback": "仍在处理中 — 完成后我们会通过邮件发送链接。","failed": "导出失败:{{message}}"},+ "import_button": {+ "title": "从 CSV 导入",+ "description": "上传 CSV 文件。下一步将文件列与字段进行匹配。",+ "drop_label": "将 CSV 文件拖放到此处,或点击浏览",+ "browse": "浏览文件",+ "delimiter_label": "列分隔符",+ "delimiters": {+ "comma": "逗号 (,)",+ "semicolon": "分号 (;)",+ "pipe": "竖线 (|)",+ "tab": "制表符"+ },+ "download_template": "下载 CSV 模板",+ "template_failed": "模板下载失败:{{message}}",+ "submit": "上传并继续",+ "uploading": "正在上传…",+ "failed": "导入失败:{{message}}"+ },"metadata_card": {"title": "元数据","empty_title": "暂无元数据",