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 the CSV import wizard and history to the dashboard

Damian Legawieceb74cb21f257
diff --git a/packages/dashboard/src/hooks/use-imports.ts b/packages/dashboard/src/hooks/use-imports.ts
new file mode 100644
index 0000000000..09075fd797
--- /dev/null
+++ b/packages/dashboard/src/hooks/use-imports.ts
@@ -0,0 +1,78 @@
+import type { Import, ImportCompleteMappingParams } from '@spree/admin-sdk'
+import { adminClient, useResourceKey, useResourceKeyBuilder } from '@spree/dashboard-core'
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { isImportActive } from '@/lib/import-types'
+
+export { isImportActive }
+
+const IMPORT_POLL_INTERVAL_MS = 2000
+const ROWS_POLL_INTERVAL_MS = 5000
+
+/**
+ * Single import, polled every 2s while the pipeline is running. `mapping`
+ * (user-driven) and terminal statuses don't poll — a mapping-state refetch
+ * would re-read the attached CSV server-side on every tick.
+ */
+export function useImport(id: string) {
+ return useQuery({
+ queryKey: useResourceKey('imports', id),
+ queryFn: () => adminClient.imports.get(id),
+ enabled: !!id,
+ refetchInterval: (query) =>
+ isImportActive(query.state.data?.status) ? IMPORT_POLL_INTERVAL_MS : false,
+ })
+}
+
+/** Rows of an import (the failure report), optionally polled while processing. */
+export function useImportRows(
+ importId: string,
+ params: Record<string, unknown>,
+ options?: { poll?: boolean },
+) {
+ return useQuery({
+ queryKey: useResourceKey('imports', importId, 'rows', params),
+ queryFn: () => adminClient.imports.rows.list(importId, params),
+ enabled: !!importId,
+ refetchInterval: options?.poll ? ROWS_POLL_INTERVAL_MS : false,
+ placeholderData: (previous) => previous,
+ })
+}
+
+export function useCompleteMapping(id: string) {
+ const queryClient = useQueryClient()
+ const buildKey = useResourceKeyBuilder()
+
+ return useMutation({
+ mutationFn: (params?: ImportCompleteMappingParams) =>
+ adminClient.imports.completeMapping(id, params),
+ onSuccess: (imp) => {
+ queryClient.setQueryData<Import>(buildKey('imports', id), imp)
+ },
+ })
+}
+
+export function useRetryFailedRows(id: string) {
+ const queryClient = useQueryClient()
+ const buildKey = useResourceKeyBuilder()
+
+ return useMutation({
+ mutationFn: () => adminClient.imports.retryFailedRows(id),
+ onSuccess: (imp) => {
+ queryClient.setQueryData<Import>(buildKey('imports', id), imp)
+ queryClient.invalidateQueries({ queryKey: buildKey('imports', id, 'rows') })
+ },
+ })
+}
+
+export function useDeleteImport() {
+ const queryClient = useQueryClient()
+ const buildKey = useResourceKeyBuilder()
+
+ return useMutation({
+ mutationFn: (id: string) => adminClient.imports.delete(id),
+ onSuccess: (_data, id) => {
+ queryClient.removeQueries({ queryKey: buildKey('imports', id) })
+ queryClient.invalidateQueries({ queryKey: buildKey('imports') })
+ },
+ })
+}
diff --git a/packages/dashboard/src/lib/import-types.test.ts b/packages/dashboard/src/lib/import-types.test.ts
new file mode 100644
index 0000000000..69b87592cb
--- /dev/null
+++ b/packages/dashboard/src/lib/import-types.test.ts
@@ -0,0 +1,40 @@
+import { describe, expect, it } from 'vitest'
+import { importTypeIndexPath, importTypeKey, isImportActive } from './import-types'
+
+describe('importTypeKey', () => {
+ it('demodulizes and underscores the STI type', () => {
+ expect(importTypeKey('Spree::Imports::Products')).toBe('products')
+ expect(importTypeKey('Spree::Imports::Customers')).toBe('customers')
+ expect(importTypeKey('Spree::Imports::ProductTranslations')).toBe('product_translations')
+ })
+
+ it('returns an empty string for null', () => {
+ expect(importTypeKey(null)).toBe('')
+ })
+})
+
+describe('importTypeIndexPath', () => {
+ it('routes customers imports to the customers index', () => {
+ expect(importTypeIndexPath('Spree::Imports::Customers')).toBe('/$storeId/customers')
+ })
+
+ it('routes product-ish imports to the products index', () => {
+ expect(importTypeIndexPath('Spree::Imports::Products')).toBe('/$storeId/products')
+ expect(importTypeIndexPath('Spree::Imports::ProductTranslations')).toBe('/$storeId/products')
+ })
+})
+
+describe('isImportActive', () => {
+ it('is true only while the pipeline is running', () => {
+ expect(isImportActive('completed_mapping')).toBe(true)
+ expect(isImportActive('processing')).toBe(true)
+ })
+
+ it('is false for mapping, terminal statuses and undefined', () => {
+ expect(isImportActive('pending')).toBe(false)
+ expect(isImportActive('mapping')).toBe(false)
+ expect(isImportActive('completed')).toBe(false)
+ expect(isImportActive('failed')).toBe(false)
+ expect(isImportActive(undefined)).toBe(false)
+ })
+})
diff --git a/packages/dashboard/src/lib/import-types.ts b/packages/dashboard/src/lib/import-types.ts
new file mode 100644
index 0000000000..b17547fdcf
--- /dev/null
+++ b/packages/dashboard/src/lib/import-types.ts
@@ -0,0 +1,37 @@
+import i18n from 'i18next'
+
+/** Statuses the wizard polls through — row creation and processing. */
+const ACTIVE_STATUSES = new Set(['completed_mapping', 'processing'])
+
+export function isImportActive(status: string | undefined): boolean {
+ return !!status && ACTIVE_STATUSES.has(status)
+}
+
+/**
+ * `Spree::Imports::Products` → `products`. Keys the per-type translations
+ * (`admin.imports.types.<key>`) and the post-import destination below.
+ */
+export function importTypeKey(type: string | null): string {
+ return (
+ (type ?? '')
+ .split('::')
+ .pop()
+ ?.replace(/([a-z])([A-Z])/g, '$1_$2')
+ .toLowerCase() ?? ''
+ )
+}
+
+export function importTypeLabel(type: string | null): string {
+ const key = importTypeKey(type)
+ return key ? i18n.t(`admin.imports.types.${key}`, { defaultValue: key }) : ''
+}
+
+/** Resource index the "Done" action points to after a finished import. */
+export function importTypeIndexPath(type: string | null): string {
+ switch (importTypeKey(type)) {
+ case 'customers':
+ return '/$storeId/customers'
+ default:
+ return '/$storeId/products'
+ }
+}
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index 947bfba0bf..5289cdc405 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -112,7 +112,8 @@
"store": "المتجر",
"payments": "المدفوعات والضرائب",
"fulfillment": "التنفيذ",
- "team": "الفريق والوصول"
+ "team": "الفريق والوصول",
+ "audit": "التدقيق"
},
"items": {
"store": "المتجر",
@@ -127,7 +128,8 @@
"api_keys": "مفاتيح API",
"webhooks": "Webhooks",
"allowed_origins": "المصادر المسموح بها",
- "profile": "الملف الشخصي"
+ "profile": "الملف الشخصي",
+ "imports": "عمليات الاستيراد"
}
},
"fields": {
@@ -1614,6 +1616,22 @@
"allowed_origins": {
"add_sheet_title": "أضف الأصل المسموح به",
"edit_sheet_title": "تحرير الأصل المسموح به"
+ },
+ "imports": {
+ "title": "عمليات الاستيراد",
+ "search_placeholder": "البحث بالرقم…",
+ "empty_title": "لا توجد عمليات استيراد بعد",
+ "table": {
+ "number": "الرقم",
+ "type": "النوع",
+ "status": "الحالة",
+ "rows": "الصفوف",
+ "failed_count": "{{failed}} فشلت"
+ },
+ "delete_confirm": {
+ "title": "حذف الاستيراد؟",
+ "message": "سيؤدي هذا إلى إزالة {{number}} وصفوفه والملف المرفوع."
+ }
}
},
"promotions": {
@@ -2588,6 +2606,64 @@
"no_matches": "لا توجد منتجات تطابق عامل التصفية."
},
"load_failed": "فشل تحميل الفئات. يرجى المحاولة مرة أخرى."
+ },
+ "imports": {
+ "steps": {
+ "map_fields": "مطابقة الحقول",
+ "process_rows": "معالجة الصفوف",
+ "complete": "اكتمل"
+ },
+ "status": {
+ "pending": "قيد الانتظار",
+ "mapping": "المطابقة",
+ "completed_mapping": "في قائمة الانتظار",
+ "processing": "قيد المعالجة",
+ "completed": "مكتمل",
+ "failed": "فشل"
+ },
+ "types": {
+ "products": "المنتجات",
+ "customers": "العملاء",
+ "product_translations": "ترجمات المنتجات"
+ },
+ "mapping": {
+ "title": "مطابقة الأعمدة",
+ "description": "طابق أعمدة ملفك مع حقول {{type}}.",
+ "field": "الحقل",
+ "file_column": "عمود الملف",
+ "sample": "مثال",
+ "not_mapped": "غير مطابق",
+ "required": "مطلوب",
+ "missing_required": "طابق الحقول المطلوبة للمتابعة: {{fields}}",
+ "start": "بدء الاستيراد",
+ "starting": "جارٍ البدء…"
+ },
+ "processing": {
+ "title": "جارٍ معالجة الصفوف",
+ "preparing": "جارٍ تجهيز الصفوف…",
+ "progress": "تمت معالجة {{processed}} من {{total}} صفًا",
+ "failed_count": "{{failed}} فشلت",
+ "retrying": "إعادة محاولة الصفوف الفاشلة · {{remaining}} متبقية",
+ "note": "يمكنك مغادرة هذه الصفحة — سيستمر الاستيراد في الخلفية."
+ },
+ "results": {
+ "completed_title": "اكتمل الاستيراد",
+ "summary": "تم استيراد {{completed}} صفًا · {{failed}} فشلت",
+ "retry_failed": "إعادة محاولة الصفوف الفاشلة ({{failed}})",
+ "retrying": "جارٍ إعادة المحاولة…",
+ "view_records": "عرض {{type}}"
+ },
+ "failed": {
+ "title": "فشل الاستيراد",
+ "description": "تعذّرت معالجة الملف."
+ },
+ "failed_rows": {
+ "title": "الصفوف الفاشلة",
+ "row_number": "الصف",
+ "error": "الخطأ",
+ "view_data": "عرض بيانات الصف",
+ "hide_data": "إخفاء بيانات الصف"
+ }
}
}
}
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index 050d46e603..c1845a1100 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -64,7 +64,8 @@
"store": "Shop",
"payments": "Zahlungen & Steuern",
"fulfillment": "Fulfillment",
- "team": "Team & Zugriff"
+ "team": "Team & Zugriff",
+ "audit": "Audit"
},
"items": {
"store": "Shop",
@@ -79,7 +80,8 @@
"api_keys": "API-Schlüssel",
"webhooks": "Webhooks",
"allowed_origins": "Zugelassene Ursprünge",
- "profile": "Profil"
+ "profile": "Profil",
+ "imports": "Importe"
}
},
"fields": {
@@ -1566,6 +1568,22 @@
"allowed_origins": {
"add_sheet_title": "Erlaubten Ursprung hinzufügen",
"edit_sheet_title": "Erlaubten Ursprung bearbeiten"
+ },
+ "imports": {
+ "title": "Importe",
+ "search_placeholder": "Nach Nummer suchen…",
+ "empty_title": "Noch keine Importe",
+ "table": {
+ "number": "Nummer",
+ "type": "Typ",
+ "status": "Status",
+ "rows": "Zeilen",
+ "failed_count": "{{failed}} fehlgeschlagen"
+ },
+ "delete_confirm": {
+ "title": "Import löschen?",
+ "message": "Dies entfernt {{number}}, seine Zeilen und die hochgeladene Datei."
+ }
}
},
"promotions": {
@@ -2588,6 +2606,64 @@
"no_matches": "Keine Produkte entsprechen dem Filter."
},
"load_failed": "Kategorien konnten nicht geladen werden. Bitte erneut versuchen."
+ },
+ "imports": {
+ "steps": {
+ "map_fields": "Felder zuordnen",
+ "process_rows": "Zeilen verarbeiten",
+ "complete": "Fertig"
+ },
+ "status": {
+ "pending": "Ausstehend",
+ "mapping": "Zuordnung",
+ "completed_mapping": "In Warteschlange",
+ "processing": "In Bearbeitung",
+ "completed": "Abgeschlossen",
+ "failed": "Fehlgeschlagen"
+ },
+ "types": {
+ "products": "Produkte",
+ "customers": "Kunden",
+ "product_translations": "Produktübersetzungen"
+ },
+ "mapping": {
+ "title": "Spalten zuordnen",
+ "description": "Ordnen Sie die Spalten Ihrer Datei den Feldern für {{type}} zu.",
+ "field": "Feld",
+ "file_column": "Dateispalte",
+ "sample": "Beispiel",
+ "not_mapped": "Nicht zugeordnet",
+ "required": "Erforderlich",
+ "missing_required": "Ordnen Sie die erforderlichen Felder zu, um fortzufahren: {{fields}}",
+ "start": "Import starten",
+ "starting": "Wird gestartet…"
+ },
+ "processing": {
+ "title": "Zeilen werden verarbeitet",
+ "preparing": "Zeilen werden vorbereitet…",
+ "progress": "{{processed}} von {{total}} Zeilen verarbeitet",
+ "failed_count": "{{failed}} fehlgeschlagen",
+ "retrying": "Fehlgeschlagene Zeilen werden wiederholt · {{remaining}} verbleibend",
+ "note": "Sie können diese Seite verlassen — der Import läuft im Hintergrund weiter."
+ },
+ "results": {
+ "completed_title": "Import abgeschlossen",
+ "summary": "{{completed}} Zeilen importiert · {{failed}} fehlgeschlagen",
+ "retry_failed": "Fehlgeschlagene Zeilen wiederholen ({{failed}})",
+ "retrying": "Wird wiederholt…",
+ "view_records": "{{type}} anzeigen"
+ },
+ "failed": {
+ "title": "Import fehlgeschlagen",
+ "description": "Die Datei konnte nicht verarbeitet werden."
+ },
+ "failed_rows": {
+ "title": "Fehlgeschlagene Zeilen",
+ "row_number": "Zeile",
+ "error": "Fehler",
+ "view_data": "Zeilendaten anzeigen",
+ "hide_data": "Zeilendaten ausblenden"
+ }
}
}
}
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index 03037cf999..f1c1c9b8d0 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -112,7 +112,8 @@
"store": "Store",
"payments": "Payments & taxes",
"fulfillment": "Fulfillment",
- "team": "Team & access"
+ "team": "Team & access",
+ "audit": "Audit"
},
"items": {
"store": "Store",
@@ -127,7 +128,8 @@
"api_keys": "API keys",
"webhooks": "Webhooks",
"allowed_origins": "Allowed origins",
- "profile": "Profile"
+ "profile": "Profile",
+ "imports": "Imports"
}
},
"fields": {
@@ -1614,6 +1616,22 @@
"allowed_origins": {
"add_sheet_title": "Add allowed origin",
"edit_sheet_title": "Edit allowed origin"
+ },
+ "imports": {
+ "title": "Imports",
+ "search_placeholder": "Search by number…",
+ "empty_title": "No imports yet",
+ "table": {
+ "number": "Number",
+ "type": "Type",
+ "status": "Status",
+ "rows": "Rows",
+ "failed_count": "{{failed}} failed"
+ },
+ "delete_confirm": {
+ "title": "Delete import?",
+ "message": "This removes {{number}}, its rows and the uploaded file."
+ }
}
},
"promotions": {
@@ -2588,6 +2606,64 @@
"no_matches": "No products match your filter."
},
"load_failed": "Failed to load categories. Please try again."
+ },
+ "imports": {
+ "steps": {
+ "map_fields": "Map fields",
+ "process_rows": "Process rows",
+ "complete": "Complete"
+ },
+ "status": {
+ "pending": "Pending",
+ "mapping": "Mapping",
+ "completed_mapping": "Queued",
+ "processing": "Processing",
+ "completed": "Completed",
+ "failed": "Failed"
+ },
+ "types": {
+ "products": "Products",
+ "customers": "Customers",
+ "product_translations": "Product translations"
+ },
+ "mapping": {
+ "title": "Map columns",
+ "description": "Match the columns from your file to {{type}} fields.",
+ "field": "Field",
+ "file_column": "File column",
+ "sample": "Example",
+ "not_mapped": "Not mapped",
+ "required": "Required",
+ "missing_required": "Map the required fields to continue: {{fields}}",
+ "start": "Start import",
+ "starting": "Starting…"
+ },
+ "processing": {
+ "title": "Processing rows",
+ "preparing": "Preparing rows…",
+ "progress": "{{processed}} of {{total}} rows processed",
+ "failed_count": "{{failed}} failed",
+ "retrying": "Retrying failed rows · {{remaining}} remaining",
+ "note": "You can leave this page — the import continues in the background."
+ },
+ "results": {
+ "completed_title": "Import completed",
+ "summary": "{{completed}} rows imported · {{failed}} failed",
+ "retry_failed": "Retry failed rows ({{failed}})",
+ "retrying": "Retrying…",
+ "view_records": "View {{type}}"
+ },
+ "failed": {
+ "title": "Import failed",
+ "description": "The file could not be processed."
+ },
+ "failed_rows": {
+ "title": "Failed rows",
+ "row_number": "Row",
+ "error": "Error",
+ "view_data": "View row data",
+ "hide_data": "Hide row data"
+ }
}
}
}
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index 07ee9bce5f..f663ede0da 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -64,7 +64,8 @@
"store": "Boutique",
"payments": "Paiements et taxes",
"fulfillment": "Traitement des commandes",
- "team": "Équipe et accès"
+ "team": "Équipe et accès",
+ "audit": "Audit"
},
"items": {
"store": "Boutique",
@@ -79,7 +80,8 @@
"api_keys": "Clés API",
"webhooks": "Webhooks",
"allowed_origins": "Origines autorisées",
- "profile": "Profil"
+ "profile": "Profil",
+ "imports": "Imports"
}
},
"fields": {
@@ -1566,6 +1568,22 @@
"allowed_origins": {
"add_sheet_title": "Ajouter une origine autorisée",
"edit_sheet_title": "Modifier l'origine autorisée"
+ },
+ "imports": {
+ "title": "Imports",
+ "search_placeholder": "Rechercher par numéro…",
+ "empty_title": "Aucun import pour l'instant",
+ "table": {
+ "number": "Numéro",
+ "type": "Type",
+ "status": "Statut",
+ "rows": "Lignes",
+ "failed_count": "{{failed}} en échec"
+ },
+ "delete_confirm": {
+ "title": "Supprimer l'import ?",
+ "message": "Cela supprime {{number}}, ses lignes et le fichier téléversé."
+ }
}
},
"promotions": {
@@ -2588,6 +2606,64 @@
"no_matches": "Aucun produit ne correspond au filtre."
},
"load_failed": "Échec du chargement des catégories. Veuillez réessayer."
+ },
+ "imports": {
+ "steps": {
+ "map_fields": "Associer les champs",
+ "process_rows": "Traiter les lignes",
+ "complete": "Terminé"
+ },
+ "status": {
+ "pending": "En attente",
+ "mapping": "Association",
+ "completed_mapping": "En file",
+ "processing": "En cours",
+ "completed": "Terminé",
+ "failed": "Échoué"
+ },
+ "types": {
+ "products": "Produits",
+ "customers": "Clients",
+ "product_translations": "Traductions de produits"
+ },
+ "mapping": {
+ "title": "Associer les colonnes",
+ "description": "Associez les colonnes de votre fichier aux champs {{type}}.",
+ "field": "Champ",
+ "file_column": "Colonne du fichier",
+ "sample": "Exemple",
+ "not_mapped": "Non associée",
+ "required": "Requis",
+ "missing_required": "Associez les champs requis pour continuer : {{fields}}",
+ "start": "Lancer l'import",
+ "starting": "Lancement…"
+ },
+ "processing": {
+ "title": "Traitement des lignes",
+ "preparing": "Préparation des lignes…",
+ "progress": "{{processed}} lignes traitées sur {{total}}",
+ "failed_count": "{{failed}} en échec",
+ "retrying": "Nouvelle tentative des lignes en échec · {{remaining}} restantes",
+ "note": "Vous pouvez quitter cette page — l'import continue en arrière-plan."
+ },
+ "results": {
+ "completed_title": "Import terminé",
+ "summary": "{{completed}} lignes importées · {{failed}} en échec",
+ "retry_failed": "Réessayer les lignes en échec ({{failed}})",
+ "retrying": "Nouvelle tentative…",
+ "view_records": "Voir {{type}}"
+ },
+ "failed": {
+ "title": "Échec de l'import",
+ "description": "Le fichier n'a pas pu être traité."
+ },
+ "failed_rows": {
+ "title": "Lignes en échec",
+ "row_number": "Ligne",
+ "error": "Erreur",
+ "view_data": "Voir les données",
+ "hide_data": "Masquer les données"
+ }
}
}
}
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index 9369b8e7d3..4afbdb178b 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -64,7 +64,8 @@
"store": "Sklep",
"payments": "Płatności i podatki",
"fulfillment": "Realizacja zamówień",
- "team": "Zespół i dostęp"
+ "team": "Zespół i dostęp",
+ "audit": "Audyt"
},
"items": {
"store": "Sklep",
@@ -79,7 +80,8 @@
"api_keys": "Klucze API",
"webhooks": "Webhooki",
"allowed_origins": "Dozwolone źródła",
- "profile": "Profil"
+ "profile": "Profil",
+ "imports": "Importy"
}
},
"fields": {
@@ -1586,6 +1588,22 @@
"allowed_origins": {
"add_sheet_title": "Dodaj dozwolone źródło",
"edit_sheet_title": "Edytuj dozwolone źródło"
+ },
+ "imports": {
+ "title": "Importy",
+ "search_placeholder": "Szukaj po numerze…",
+ "empty_title": "Brak importów",
+ "table": {
+ "number": "Numer",
+ "type": "Typ",
+ "status": "Status",
+ "rows": "Wiersze",
+ "failed_count": "{{failed}} nieudanych"
+ },
+ "delete_confirm": {
+ "title": "Usunąć import?",
+ "message": "Spowoduje to usunięcie {{number}}, jego wierszy i przesłanego pliku."
+ }
}
},
"promotions": {
@@ -2620,6 +2638,64 @@
"no_matches": "Żaden produkt nie pasuje do filtra."
},
"load_failed": "Nie udało się załadować kategorii. Spróbuj ponownie."
+ },
+ "imports": {
+ "steps": {
+ "map_fields": "Dopasuj pola",
+ "process_rows": "Przetwórz wiersze",
+ "complete": "Gotowe"
+ },
+ "status": {
+ "pending": "Oczekujący",
+ "mapping": "Dopasowywanie",
+ "completed_mapping": "W kolejce",
+ "processing": "Przetwarzanie",
+ "completed": "Zakończony",
+ "failed": "Nieudany"
+ },
+ "types": {
+ "products": "Produkty",
+ "customers": "Klienci",
+ "product_translations": "Tłumaczenia produktów"
+ },
+ "mapping": {
+ "title": "Dopasuj kolumny",
+ "description": "Dopasuj kolumny z pliku do pól: {{type}}.",
+ "field": "Pole",
+ "file_column": "Kolumna pliku",
+ "sample": "Przykład",
+ "not_mapped": "Niedopasowane",
+ "required": "Wymagane",
+ "missing_required": "Aby kontynuować, dopasuj wymagane pola: {{fields}}",
+ "start": "Rozpocznij import",
+ "starting": "Rozpoczynanie…"
+ },
+ "processing": {
+ "title": "Przetwarzanie wierszy",
+ "preparing": "Przygotowywanie wierszy…",
+ "progress": "Przetworzono {{processed}} z {{total}} wierszy",
+ "failed_count": "{{failed}} nieudanych",
+ "retrying": "Ponawianie nieudanych wierszy · pozostało {{remaining}}",
+ "note": "Możesz opuścić tę stronę — import będzie kontynuowany w tle."
+ },
+ "results": {
+ "completed_title": "Import zakończony",
+ "summary": "Zaimportowano {{completed}} wierszy · {{failed}} nieudanych",
+ "retry_failed": "Ponów nieudane wiersze ({{failed}})",
+ "retrying": "Ponawianie…",
+ "view_records": "Zobacz: {{type}}"
+ },
+ "failed": {
+ "title": "Import nieudany",
+ "description": "Nie udało się przetworzyć pliku."
+ },
+ "failed_rows": {
+ "title": "Nieudane wiersze",
+ "row_number": "Wiersz",
+ "error": "Błąd",
+ "view_data": "Pokaż dane wiersza",
+ "hide_data": "Ukryj dane wiersza"
+ }
}
}
}
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index 7fcde7e011..df91f4676f 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -112,7 +112,8 @@
"store": "店铺",
"payments": "支付与税务",
"fulfillment": "履约",
- "team": "团队与权限"
+ "team": "团队与权限",
+ "audit": "审计"
},
"items": {
"store": "店铺",
@@ -127,7 +128,8 @@
"api_keys": "API 密钥",
"webhooks": "Webhooks",
"allowed_origins": "允许的来源",
- "profile": "个人资料"
+ "profile": "个人资料",
+ "imports": "导入"
}
},
"fields": {
@@ -1614,6 +1616,22 @@
"allowed_origins": {
"add_sheet_title": "添加允许的来源",
"edit_sheet_title": "编辑允许的来源"
+ },
+ "imports": {
+ "title": "导入",
+ "search_placeholder": "按编号搜索…",
+ "empty_title": "暂无导入",
+ "table": {
+ "number": "编号",
+ "type": "类型",
+ "status": "状态",
+ "rows": "行数",
+ "failed_count": "{{failed}} 条失败"
+ },
+ "delete_confirm": {
+ "title": "删除导入?",
+ "message": "这将删除 {{number}} 及其行数据和上传的文件。"
+ }
}
},
"promotions": {
@@ -2588,6 +2606,64 @@
"no_matches": "没有商品匹配筛选条件。"
},
"load_failed": "加载分类失败。请重试。"
+ },
+ "imports": {
+ "steps": {
+ "map_fields": "匹配字段",
+ "process_rows": "处理行",
+ "complete": "完成"
+ },
+ "status": {
+ "pending": "待处理",
+ "mapping": "匹配中",
+ "completed_mapping": "已排队",
+ "processing": "处理中",
+ "completed": "已完成",
+ "failed": "失败"
+ },
+ "types": {
+ "products": "产品",
+ "customers": "客户",
+ "product_translations": "产品翻译"
+ },
+ "mapping": {
+ "title": "匹配列",
+ "description": "将文件中的列与{{type}}字段进行匹配。",
+ "field": "字段",
+ "file_column": "文件列",
+ "sample": "示例",
+ "not_mapped": "未匹配",
+ "required": "必填",
+ "missing_required": "请先匹配必填字段:{{fields}}",
+ "start": "开始导入",
+ "starting": "正在开始…"
+ },
+ "processing": {
+ "title": "正在处理行",
+ "preparing": "正在准备行…",
+ "progress": "已处理 {{processed}} / {{total}} 行",
+ "failed_count": "{{failed}} 条失败",
+ "retrying": "正在重试失败的行 · 剩余 {{remaining}} 条",
+ "note": "您可以离开此页面——导入将在后台继续进行。"
+ },
+ "results": {
+ "completed_title": "导入完成",
+ "summary": "已导入 {{completed}} 行 · {{failed}} 条失败",
+ "retry_failed": "重试失败的行({{failed}})",
+ "retrying": "正在重试…",
+ "view_records": "查看{{type}}"
+ },
+ "failed": {
+ "title": "导入失败",
+ "description": "无法处理该文件。"
+ },
+ "failed_rows": {
+ "title": "失败的行",
+ "row_number": "行号",
+ "error": "错误",
+ "view_data": "查看行数据",
+ "hide_data": "隐藏行数据"
+ }
}
}
}
diff --git a/packages/dashboard/src/nav/settings.ts b/packages/dashboard/src/nav/settings.ts
index bc3effbaf2..49e96b5f66 100644
--- a/packages/dashboard/src/nav/settings.ts
+++ b/packages/dashboard/src/nav/settings.ts
@@ -9,6 +9,7 @@ import {
RadioTowerIcon,
StoreIcon,
TagIcon,
+ UploadIcon,
UsersRoundIcon,
WarehouseIcon,
WebhookIcon,
@@ -29,6 +30,7 @@ settingsNav.addGroup({
labelKey: 'admin.settings_nav.groups.fulfillment',
position: 200,
})
+settingsNav.addGroup({ key: 'audit', labelKey: 'admin.settings_nav.groups.audit', position: 250 })
settingsNav.addGroup({ key: 'team', labelKey: 'admin.settings_nav.groups.team', position: 300 })
settingsNav.add({
@@ -150,3 +152,14 @@ settingsNav.add({
position: 300,
subject: Subject.AllowedOrigin,
})
+
+// No `subject`: the page spans import types and the API already filters what
+// the caller can see.
+settingsNav.add({
+ key: 'settings.imports',
+ labelKey: 'admin.settings_nav.items.imports',
+ path: '/imports',
+ icon: UploadIcon,
+ group: 'audit',
+ position: 100,
+})
diff --git a/packages/dashboard/src/routeTree.gen.ts b/packages/dashboard/src/routeTree.gen.ts
index 3d6066a84a..443778c207 100644
--- a/packages/dashboard/src/routeTree.gen.ts
+++ b/packages/dashboard/src/routeTree.gen.ts
@@ -49,9 +49,11 @@ import { Route as AuthenticatedStoreIdOrdersOrderIdRouteImport } from './routes/
import { Route as AuthenticatedStoreIdCustomersGroupsRouteImport } from './routes/_authenticated/$storeId/customers/groups'
import { Route as AuthenticatedStoreIdCustomersCustomerIdRouteImport } from './routes/_authenticated/$storeId/customers/$customerId'
import { Route as AuthenticatedStoreIdSettingsWebhooksIndexRouteImport } from './routes/_authenticated/$storeId/settings/webhooks/index'
+import { Route as AuthenticatedStoreIdSettingsImportsIndexRouteImport } from './routes/_authenticated/$storeId/settings/imports/index'
import { Route as AuthenticatedStoreIdProductsPriceListsIndexRouteImport } from './routes/_authenticated/$storeId/products/price-lists/index'
import { Route as AuthenticatedStoreIdProductsCategoriesIndexRouteImport } from './routes/_authenticated/$storeId/products/categories/index'
import { Route as AuthenticatedStoreIdSettingsWebhooksWebhookEndpointIdRouteImport } from './routes/_authenticated/$storeId/settings/webhooks/$webhookEndpointId'
+import { Route as AuthenticatedStoreIdSettingsImportsImportIdRouteImport } from './routes/_authenticated/$storeId/settings/imports/$importId'
import { Route as AuthenticatedStoreIdProductsPriceListsNewRouteImport } from './routes/_authenticated/$storeId/products/price-lists/new'
import { Route as AuthenticatedStoreIdProductsCategoriesNewRouteImport } from './routes/_authenticated/$storeId/products/categories/new'
import { Route as AuthenticatedStoreIdProductsCategoriesCategoryIdRouteImport } from './routes/_authenticated/$storeId/products/categories/$categoryId'
@@ -290,6 +292,12 @@ const AuthenticatedStoreIdSettingsWebhooksIndexRoute =
path: '/webhooks/',
getParentRoute: () => AuthenticatedStoreIdSettingsRoute,
} as any)
+const AuthenticatedStoreIdSettingsImportsIndexRoute =
+ AuthenticatedStoreIdSettingsImportsIndexRouteImport.update({
+ id: '/imports/',
+ path: '/imports/',
+ getParentRoute: () => AuthenticatedStoreIdSettingsRoute,
+ } as any)
const AuthenticatedStoreIdProductsPriceListsIndexRoute =
AuthenticatedStoreIdProductsPriceListsIndexRouteImport.update({
id: '/products/price-lists/',
@@ -308,6 +316,12 @@ const AuthenticatedStoreIdSettingsWebhooksWebhookEndpointIdRoute =
path: '/webhooks/$webhookEndpointId',
getParentRoute: () => AuthenticatedStoreIdSettingsRoute,
} as any)
+const AuthenticatedStoreIdSettingsImportsImportIdRoute =
+ AuthenticatedStoreIdSettingsImportsImportIdRouteImport.update({
+ id: '/imports/$importId',
+ path: '/imports/$importId',
+ getParentRoute: () => AuthenticatedStoreIdSettingsRoute,
+ } as any)
const AuthenticatedStoreIdProductsPriceListsNewRoute =
AuthenticatedStoreIdProductsPriceListsNewRouteImport.update({
id: '/products/price-lists/new',
@@ -375,9 +389,11 @@ export interface FileRoutesByFullPath {
'/$storeId/products/categories/$categoryId': typeof AuthenticatedStoreIdProductsCategoriesCategoryIdRoute
'/$storeId/products/categories/new': typeof AuthenticatedStoreIdProductsCategoriesNewRoute
'/$storeId/products/price-lists/new': typeof AuthenticatedStoreIdProductsPriceListsNewRoute
+ '/$storeId/settings/imports/$importId': typeof AuthenticatedStoreIdSettingsImportsImportIdRoute
'/$storeId/settings/webhooks/$webhookEndpointId': typeof AuthenticatedStoreIdSettingsWebhooksWebhookEndpointIdRoute
'/$storeId/products/categories/': typeof AuthenticatedStoreIdProductsCategoriesIndexRoute
'/$storeId/products/price-lists/': typeof AuthenticatedStoreIdProductsPriceListsIndexRoute
+ '/$storeId/settings/imports/': typeof AuthenticatedStoreIdSettingsImportsIndexRoute
'/$storeId/settings/webhooks/': typeof AuthenticatedStoreIdSettingsWebhooksIndexRoute
'/$storeId/products/price-lists/$priceListId/': typeof AuthenticatedStoreIdProductsPriceListsPriceListIdIndexRoute
}
@@ -421,9 +437,11 @@ export interface FileRoutesByTo {
'/$storeId/products/categories/$categoryId': typeof AuthenticatedStoreIdProductsCategoriesCategoryIdRoute
'/$storeId/products/categories/new': typeof AuthenticatedStoreIdProductsCategoriesNewRoute
'/$storeId/products/price-lists/new': typeof AuthenticatedStoreIdProductsPriceListsNewRoute
+ '/$storeId/settings/imports/$importId': typeof AuthenticatedStoreIdSettingsImportsImportIdRoute
'/$storeId/settings/webhooks/$webhookEndpointId': typeof AuthenticatedStoreIdSettingsWebhooksWebhookEndpointIdRoute
'/$storeId/products/categories': typeof AuthenticatedStoreIdProductsCategoriesIndexRoute
'/$storeId/products/price-lists': typeof AuthenticatedStoreIdProductsPriceListsIndexRoute
+ '/$storeId/settings/imports': typeof AuthenticatedStoreIdSettingsImportsIndexRoute
'/$storeId/settings/webhooks': typeof AuthenticatedStoreIdSettingsWebhooksIndexRoute
'/$storeId/products/price-lists/$priceListId': typeof AuthenticatedStoreIdProductsPriceListsPriceListIdIndexRoute
}
@@ -471,9 +489,11 @@ export interface FileRoutesById {
'/_authenticated/$storeId/products/categories/$categoryId': typeof AuthenticatedStoreIdProductsCategoriesCategoryIdRoute
'/_authenticated/$storeId/products/categories/new': typeof AuthenticatedStoreIdProductsCategoriesNewRoute
'/_authenticated/$storeId/products/price-lists/new': typeof AuthenticatedStoreIdProductsPriceListsNewRoute
+ '/_authenticated/$storeId/settings/imports/$importId': typeof AuthenticatedStoreIdSettingsImportsImportIdRoute
'/_authenticated/$storeId/settings/webhooks/$webhookEndpointId': typeof AuthenticatedStoreIdSettingsWebhooksWebhookEndpointIdRoute
'/_authenticated/$storeId/products/categories/': typeof AuthenticatedStoreIdProductsCategoriesIndexRoute
'/_authenticated/$storeId/products/price-lists/': typeof AuthenticatedStoreIdProductsPriceListsIndexRoute
+ '/_authenticated/$storeId/settings/imports/': typeof AuthenticatedStoreIdSettingsImportsIndexRoute
'/_authenticated/$storeId/settings/webhooks/': typeof AuthenticatedStoreIdSettingsWebhooksIndexRoute
'/_authenticated/$storeId/products/price-lists/$priceListId/': typeof AuthenticatedStoreIdProductsPriceListsPriceListIdIndexRoute
}
@@ -521,9 +541,11 @@ export interface FileRouteTypes {
| '/$storeId/products/categories/$categoryId'
| '/$storeId/products/categories/new'
| '/$storeId/products/price-lists/new'
+ | '/$storeId/settings/imports/$importId'
| '/$storeId/settings/webhooks/$webhookEndpointId'
| '/$storeId/products/categories/'
| '/$storeId/products/price-lists/'
+ | '/$storeId/settings/imports/'
| '/$storeId/settings/webhooks/'
| '/$storeId/products/price-lists/$priceListId/'
fileRoutesByTo: FileRoutesByTo
@@ -567,9 +589,11 @@ export interface FileRouteTypes {
| '/$storeId/products/categories/$categoryId'
| '/$storeId/products/categories/new'
| '/$storeId/products/price-lists/new'
+ | '/$storeId/settings/imports/$importId'
| '/$storeId/settings/webhooks/$webhookEndpointId'
| '/$storeId/products/categories'
| '/$storeId/products/price-lists'
+ | '/$storeId/settings/imports'
| '/$storeId/settings/webhooks'
| '/$storeId/products/price-lists/$priceListId'
id:
@@ -616,9 +640,11 @@ export interface FileRouteTypes {
| '/_authenticated/$storeId/products/categories/$categoryId'
| '/_authenticated/$storeId/products/categories/new'
| '/_authenticated/$storeId/products/price-lists/new'
+ | '/_authenticated/$storeId/settings/imports/$importId'
| '/_authenticated/$storeId/settings/webhooks/$webhookEndpointId'
| '/_authenticated/$storeId/products/categories/'
| '/_authenticated/$storeId/products/price-lists/'
+ | '/_authenticated/$storeId/settings/imports/'
| '/_authenticated/$storeId/settings/webhooks/'
| '/_authenticated/$storeId/products/price-lists/$priceListId/'
fileRoutesById: FileRoutesById
@@ -913,6 +939,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AuthenticatedStoreIdSettingsWebhooksIndexRouteImport
parentRoute: typeof AuthenticatedStoreIdSettingsRoute
}
+ '/_authenticated/$storeId/settings/imports/': {
+ id: '/_authenticated/$storeId/settings/imports/'
+ path: '/imports'
+ fullPath: '/$storeId/settings/imports/'
+ preLoaderRoute: typeof AuthenticatedStoreIdSettingsImportsIndexRouteImport
+ parentRoute: typeof AuthenticatedStoreIdSettingsRoute
+ }
'/_authenticated/$storeId/products/price-lists/': {
id: '/_authenticated/$storeId/products/price-lists/'
path: '/products/price-lists'
@@ -934,6 +967,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AuthenticatedStoreIdSettingsWebhooksWebhookEndpointIdRouteImport
parentRoute: typeof AuthenticatedStoreIdSettingsRoute
}
+ '/_authenticated/$storeId/settings/imports/$importId': {
+ id: '/_authenticated/$storeId/settings/imports/$importId'
+ path: '/imports/$importId'
+ fullPath: '/$storeId/settings/imports/$importId'
+ preLoaderRoute: typeof AuthenticatedStoreIdSettingsImportsImportIdRouteImport
+ parentRoute: typeof AuthenticatedStoreIdSettingsRoute
+ }
'/_authenticated/$storeId/products/price-lists/new': {
id: '/_authenticated/$storeId/products/price-lists/new'
path: '/products/price-lists/new'
@@ -979,7 +1019,9 @@ interface AuthenticatedStoreIdSettingsRouteChildren {
AuthenticatedStoreIdSettingsStoreRoute: typeof AuthenticatedStoreIdSettingsStoreRoute
AuthenticatedStoreIdSettingsTaxCategoriesRoute: typeof AuthenticatedStoreIdSettingsTaxCategoriesRoute
AuthenticatedStoreIdSettingsIndexRoute: typeof AuthenticatedStoreIdSettingsIndexRoute
+ AuthenticatedStoreIdSettingsImportsImportIdRoute: typeof AuthenticatedStoreIdSettingsImportsImportIdRoute
AuthenticatedStoreIdSettingsWebhooksWebhookEndpointIdRoute: typeof AuthenticatedStoreIdSettingsWebhooksWebhookEndpointIdRoute
+ AuthenticatedStoreIdSettingsImportsIndexRoute: typeof AuthenticatedStoreIdSettingsImportsIndexRoute
AuthenticatedStoreIdSettingsWebhooksIndexRoute: typeof AuthenticatedStoreIdSettingsWebhooksIndexRoute
}
@@ -1011,8 +1053,12 @@ const AuthenticatedStoreIdSettingsRouteChildren: AuthenticatedStoreIdSettingsRou
AuthenticatedStoreIdSettingsTaxCategoriesRoute,
AuthenticatedStoreIdSettingsIndexRoute:
AuthenticatedStoreIdSettingsIndexRoute,
+ AuthenticatedStoreIdSettingsImportsImportIdRoute:
+ AuthenticatedStoreIdSettingsImportsImportIdRoute,
AuthenticatedStoreIdSettingsWebhooksWebhookEndpointIdRoute:
AuthenticatedStoreIdSettingsWebhooksWebhookEndpointIdRoute,
+ AuthenticatedStoreIdSettingsImportsIndexRoute:
+ AuthenticatedStoreIdSettingsImportsIndexRoute,
AuthenticatedStoreIdSettingsWebhooksIndexRoute:
AuthenticatedStoreIdSettingsWebhooksIndexRoute,
}
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/customers/index.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/customers/index.tsx
index 4cb249c2f0..bf68525e69 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/customers/index.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/customers/index.tsx
@@ -4,6 +4,7 @@ import type { BulkAction, BulkActionFormProps } from '@spree/dashboard-core'
import {
adminClient,
ExportButton,
+ ImportButton,
mapSpreeErrorsToForm,
ResourceMultiAutocomplete,
ResourceTable,
@@ -197,6 +198,16 @@ function CustomersPage() {
rowActions={(customer) => <CustomerRowActions customer={customer} storeId={storeId} />}
actions={(ctx) => (
<>
+ <ImportButton
+ type="Spree::Imports::Customers"
+ subject={Subject.Customer}
+ onCreated={(imp) =>
+ navigate({
+ to: '/$storeId/settings/imports/$importId',
+ params: { storeId, importId: imp.id },
+ })
+ }
+ />
<ExportButton type="Spree::Exports::Customers" {...ctx} />
<Button size="sm" className="h-[2.125rem]" onClick={openCreate}>
<PlusIcon className="size-4" />
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/index.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/index.tsx
index 9cb55c9f3d..26b5d5c6b9 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/index.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/index.tsx
@@ -3,6 +3,7 @@ import type { BulkAction, BulkActionFormProps } from '@spree/dashboard-core'
import {
adminClient,
ExportButton,
+ ImportButton,
ResourceMultiAutocomplete,
ResourceTable,
resourceSearchSchema,
@@ -264,6 +265,16 @@ function ProductsPage() {
rowActions={renderRowActions}
actions={(ctx) => (
<>
+ <ImportButton
+ type="Spree::Imports::Products"
+ subject={Subject.Product}
+ onCreated={(imp) =>
+ navigate({
+ to: '/$storeId/settings/imports/$importId',
+ params: { storeId, importId: imp.id },
+ })
+ }
+ />
<ExportButton type="Spree::Exports::Products" {...ctx} />
<Button
size="sm"
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/imports/$importId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/imports/$importId.tsx
new file mode 100644
index 0000000000..dc23a1da74
--- /dev/null
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/imports/$importId.tsx
@@ -0,0 +1,489 @@
+import type { Import, ImportRow } from '@spree/admin-sdk'
+import { PageHeader } from '@spree/dashboard-core'
+import {
+ Badge,
+ Button,
+ Card,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ cn,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+ Skeleton,
+ StatusBadge,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from '@spree/dashboard-ui'
+import { createFileRoute, useNavigate } from '@tanstack/react-router'
+import {
+ AlertTriangleIcon,
+ CheckCircle2Icon,
+ ChevronLeftIcon,
+ ChevronRightIcon,
+ RotateCcwIcon,
+} from 'lucide-react'
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import {
+ isImportActive,
+ useCompleteMapping,
+ useImport,
+ useImportRows,
+ useRetryFailedRows,
+} from '@/hooks/use-imports'
+import { importTypeIndexPath, importTypeLabel } from '@/lib/import-types'
+
+export const Route = createFileRoute('/_authenticated/$storeId/settings/imports/$importId')({
+ component: ImportWizardPage,
+})
+
+const NOT_MAPPED = '__not_mapped__'
+
+function ImportWizardPage() {
+ const { t } = useTranslation()
+ const { importId, storeId } = Route.useParams()
+ const { data: imp, isLoading } = useImport(importId)
+
+ if (isLoading || !imp) {
+ return (
+ <div className="flex flex-col gap-4 p-4 md:p-6">
+ <Skeleton className="h-8 w-64" />
+ <Skeleton className="h-40 w-full" />
+ </div>
+ )
+ }
+
+ const showFailedRows =
+ imp.failed_rows_count > 0 && (isImportActive(imp.status) || imp.status === 'completed')
+
+ return (
+ <div className="flex flex-col gap-4 p-4 md:p-6">
+ <PageHeader
+ title={`${importTypeLabel(imp.type)} · ${imp.number}`}
+ backTo={`/${storeId}/settings/imports`}
+ badges={<StatusBadge status={imp.status} label={t(`admin.imports.status.${imp.status}`)} />}
+ />
+
+ <StepIndicator status={imp.status} />
+
+ {imp.status === 'mapping' && <MappingStep imp={imp} />}
+ {isImportActive(imp.status) && <ProcessingCard imp={imp} />}
+ {imp.status === 'completed' && <ResultsCard imp={imp} storeId={storeId} />}
+ {imp.status === 'failed' && <FailedCard imp={imp} />}
+ {showFailedRows && <FailedRowsCard imp={imp} />}
+ </div>
+ )
+}
+
+// ---------------------------------------------------------------------------
+// Step indicator — Map fields → Process rows → Complete, mirroring the legacy
+// wizard's three steps.
+// ---------------------------------------------------------------------------
+
+function StepIndicator({ status }: { status: string }) {
+ const { t } = useTranslation()
+
+ const activeIndex = status === 'mapping' ? 0 : isImportActive(status) ? 1 : 2
+ const steps = ['map_fields', 'process_rows', 'complete'] as const
+
+ return (
+ <ol className="flex items-center gap-2">
+ {steps.map((step, index) => (
+ <li key={step} className="flex items-center gap-2">
+ <span
+ className={cn(
+ 'flex size-5 items-center justify-center rounded-full text-xs',
+ index < activeIndex && 'bg-primary text-primary-foreground',
+ index === activeIndex && 'bg-primary text-primary-foreground',
+ index > activeIndex && 'bg-muted text-muted-foreground',
+ )}
+ >
+ {index < activeIndex ? <CheckCircle2Icon className="size-3.5" /> : index + 1}
+ </span>
+ <span
+ className={cn(
+ 'text-sm',
+ index === activeIndex ? 'font-medium' : 'text-muted-foreground',
+ )}
+ >
+ {t(`admin.imports.steps.${step}`)}
+ </span>
+ {index < steps.length - 1 && (
+ <ChevronRightIcon className="size-4 text-muted-foreground" />
+ )}
+ </li>
+ ))}
+ </ol>
+ )
+}
+
+// ---------------------------------------------------------------------------
+// Mapping step
+// ---------------------------------------------------------------------------
+
+function MappingStep({ imp }: { imp: Import }) {
+ const { t } = useTranslation()
+ const completeMapping = useCompleteMapping(imp.id)
+ const [assignments, setAssignments] = useState<Record<string, string | null>>(() =>
+ Object.fromEntries(imp.mappings.map((m) => [m.schema_field, m.file_column])),
+ )
+
+ const missingRequired = imp.schema_fields.filter((f) => f.required && !assignments[f.name])
+
+ function handleStart() {
+ completeMapping.mutate({
+ mappings: imp.schema_fields.map((field) => ({
+ schema_field: field.name,
+ file_column: assignments[field.name] ?? null,
+ })),
+ })
+ }
+
+ const headerOptions = (current: string | null) => [
+ { value: NOT_MAPPED, label: t('admin.imports.mapping.not_mapped') },
+ ...imp.csv_headers.map((header) => ({
+ value: header,
+ label: header,
+ // A file column can feed only one field — mirror the server's
+ // uniqueness validation instead of 422-ing on submit.
+ disabled: header !== current && Object.values(assignments).includes(header),
+ })),
+ ]
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('admin.imports.mapping.title')}</CardTitle>
+ <p className="text-muted-foreground text-sm">
+ {t('admin.imports.mapping.description', { type: importTypeLabel(imp.type) })}
+ </p>
+ </CardHeader>
+ <CardContent className="flex flex-col gap-4">
+ <div className="overflow-x-auto">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>{t('admin.imports.mapping.field')}</TableHead>
+ <TableHead>{t('admin.imports.mapping.file_column')}</TableHead>
+ <TableHead>{t('admin.imports.mapping.sample')}</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {imp.schema_fields.map((field) => {
+ const current = assignments[field.name] ?? null
+ const options = headerOptions(current)
+ const sample = current ? (imp.sample_row[current] ?? '') : ''
+
+ return (
+ <TableRow key={field.name}>
+ <TableCell>
+ <span className="inline-flex items-center gap-2">
+ {field.label}
+ {field.required && (
+ <Badge variant="outline">{t('admin.imports.mapping.required')}</Badge>
+ )}
+ </span>
+ </TableCell>
+ <TableCell className="w-72">
+ <Select
+ items={options}
+ value={current ?? NOT_MAPPED}
+ onValueChange={(value) =>
+ setAssignments((prev) => ({
+ ...prev,
+ [field.name]: value === NOT_MAPPED ? null : (value as string),
+ }))
+ }
+ >
+ <SelectTrigger className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {options.map((option) => (
+ <SelectItem
+ key={option.value}
+ value={option.value}
+ disabled={'disabled' in option ? option.disabled : false}
+ >
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </TableCell>
+ <TableCell className="max-w-48 truncate text-muted-foreground text-sm">
+ {sample}
+ </TableCell>
+ </TableRow>
+ )
+ })}
+ </TableBody>
+ </Table>
+ </div>
+
+ {missingRequired.length > 0 && (
+ <p className="text-muted-foreground text-sm">
+ {t('admin.imports.mapping.missing_required', {
+ fields: missingRequired.map((f) => f.label).join(', '),
+ })}
+ </p>
+ )}
+
+ {completeMapping.isError && (
+ <div className="flex items-start gap-2 rounded-md border border-destructive/40 bg-destructive/10 p-3 text-destructive text-sm">
+ <AlertTriangleIcon className="size-4 shrink-0" />
+ <span>
+ {completeMapping.error instanceof Error
+ ? completeMapping.error.message
+ : String(completeMapping.error)}
+ </span>
+ </div>
+ )}
+
+ <div className="flex justify-end">
+ <Button
+ onClick={handleStart}
+ disabled={missingRequired.length > 0 || completeMapping.isPending}
+ >
+ {completeMapping.isPending
+ ? t('admin.imports.mapping.starting')
+ : t('admin.imports.mapping.start')}
+ </Button>
+ </div>
+ </CardContent>
+ </Card>
+ )
+}
+
+// ---------------------------------------------------------------------------
+// Processing
+// ---------------------------------------------------------------------------
+
+function ProcessingCard({ imp }: { imp: Import }) {
+ const { t } = useTranslation()
+
+ const total = imp.rows_count
+ const processed = imp.completed_rows_count + imp.failed_rows_count
+ const preparing = total === 0
+ // A retry pass re-processes failed rows, so every row is already terminal
+ // and the bar would sit at 100% — show the shrinking failed count instead.
+ const retryPass = !preparing && processed >= total && imp.failed_rows_count > 0
+ const percent = preparing ? 0 : Math.min(100, Math.round((processed / total) * 100))
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('admin.imports.processing.title')}</CardTitle>
+ </CardHeader>
+ <CardContent className="flex flex-col gap-3">
+ <div className="h-2 w-full overflow-hidden rounded-full bg-muted">
+ {preparing ? (
+ <div className="h-full w-1/3 animate-pulse rounded-full bg-primary" />
+ ) : (
+ <div
+ className="h-full rounded-full bg-primary transition-all"
+ style={{ width: `${percent}%` }}
+ />
+ )}
+ </div>
+
+ <p className="text-sm">
+ {preparing ? (
+ t('admin.imports.processing.preparing')
+ ) : retryPass ? (
+ t('admin.imports.processing.retrying', { remaining: imp.failed_rows_count })
+ ) : (
+ <>
+ {t('admin.imports.processing.progress', {
+ processed: processed.toLocaleString(),
+ total: total.toLocaleString(),
+ })}
+ {imp.failed_rows_count > 0 && (
+ <span className="text-destructive">
+ {' · '}
+ {t('admin.imports.processing.failed_count', { failed: imp.failed_rows_count })}
+ </span>
+ )}
+ </>
+ )}
+ </p>
+
+ <p className="text-muted-foreground text-sm">{t('admin.imports.processing.note')}</p>
+ </CardContent>
+ </Card>
+ )
+}
+
+// ---------------------------------------------------------------------------
+// Results / file-level failure
+// ---------------------------------------------------------------------------
+
+function ResultsCard({ imp, storeId }: { imp: Import; storeId: string }) {
+ const { t } = useTranslation()
+ const navigate = useNavigate()
+ const retryMutation = useRetryFailedRows(imp.id)
+
+ return (
+ <Card>
+ <CardContent className="flex flex-col items-center gap-3 py-8 text-center">
+ <CheckCircle2Icon className="size-10 text-success" />
+ <p className="font-medium">{t('admin.imports.results.completed_title')}</p>
+ <p className="text-muted-foreground text-sm">
+ {t('admin.imports.results.summary', {
+ completed: imp.completed_rows_count.toLocaleString(),
+ failed: imp.failed_rows_count.toLocaleString(),
+ })}
+ </p>
+ <div className="mt-2 flex items-center gap-2">
+ {imp.failed_rows_count > 0 && (
+ <Button
+ variant="outline"
+ onClick={() => retryMutation.mutate()}
+ disabled={retryMutation.isPending}
+ >
+ <RotateCcwIcon className="size-4" />
+ {retryMutation.isPending
+ ? t('admin.imports.results.retrying')
+ : t('admin.imports.results.retry_failed', { failed: imp.failed_rows_count })}
+ </Button>
+ )}
+ <Button
+ onClick={() => navigate({ to: importTypeIndexPath(imp.type), params: { storeId } })}
+ >
+ {t('admin.imports.results.view_records', { type: importTypeLabel(imp.type) })}
+ </Button>
+ </div>
+ </CardContent>
+ </Card>
+ )
+}
+
+function FailedCard({ imp }: { imp: Import }) {
+ const { t } = useTranslation()
+
+ return (
+ <Card>
+ <CardContent className="flex flex-col items-center gap-3 py-8 text-center">
+ <AlertTriangleIcon className="size-10 text-destructive" />
+ <p className="font-medium">{t('admin.imports.failed.title')}</p>
+ <p className="text-muted-foreground text-sm">{t('admin.imports.failed.description')}</p>
+ {imp.processing_errors && (
+ <code className="max-w-full overflow-x-auto rounded-md bg-muted p-3 text-left text-xs">
+ {imp.processing_errors}
+ </code>
+ )}
+ </CardContent>
+ </Card>
+ )
+}
+
+// ---------------------------------------------------------------------------
+// Failed rows report
+// ---------------------------------------------------------------------------
+
+function FailedRowsCard({ imp }: { imp: Import }) {
+ const { t } = useTranslation()
+ const [page, setPage] = useState(1)
+ const { data } = useImportRows(
+ imp.id,
+ { status_eq: 'failed', sort: 'row_number', page },
+ { poll: isImportActive(imp.status) },
+ )
+
+ const rows = data?.data ?? []
+ const meta = data?.meta
+
+ if (rows.length === 0) return null
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('admin.imports.failed_rows.title')}</CardTitle>
+ </CardHeader>
+ <CardContent className="flex flex-col gap-3">
+ <div className="overflow-x-auto">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-16">{t('admin.imports.failed_rows.row_number')}</TableHead>
+ <TableHead>{t('admin.imports.failed_rows.error')}</TableHead>
+ <TableHead className="w-32" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {rows.map((row) => (
+ <FailedRow key={row.id} row={row} />
+ ))}
+ </TableBody>
+ </Table>
+ </div>
+
+ {meta && meta.pages > 1 && (
+ <div className="flex items-center justify-end gap-2">
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={page <= 1}
+ onClick={() => setPage((p) => Math.max(1, p - 1))}
+ >
+ <ChevronLeftIcon className="size-4" />
+ </Button>
+ <span className="text-muted-foreground text-sm">
+ {page} / {meta.pages}
+ </span>
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={page >= meta.pages}
+ onClick={() => setPage((p) => p + 1)}
+ >
+ <ChevronRightIcon className="size-4" />
+ </Button>
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ )
+}
+
+function FailedRow({ row }: { row: ImportRow }) {
+ const { t } = useTranslation()
+ const [expanded, setExpanded] = useState(false)
+
+ return (
+ <>
+ <TableRow>
+ <TableCell className="text-muted-foreground">{row.row_number}</TableCell>
+ <TableCell className="text-destructive text-sm">
+ {String(row.validation_errors ?? '')}
+ </TableCell>
+ <TableCell className="text-right">
+ <Button variant="ghost" size="sm" onClick={() => setExpanded((e) => !e)}>
+ {expanded
+ ? t('admin.imports.failed_rows.hide_data')
+ : t('admin.imports.failed_rows.view_data')}
+ </Button>
+ </TableCell>
+ </TableRow>
+ {expanded && (
+ <TableRow>
+ <TableCell colSpan={3}>
+ <div className="overflow-x-auto rounded-md bg-muted p-3">
+ <code className="whitespace-pre-wrap text-xs">
+ {JSON.stringify(row.data, null, 2)}
+ </code>
+ </div>
+ </TableCell>
+ </TableRow>
+ )}
+ </>
+ )
+}
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/imports/index.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/imports/index.tsx
new file mode 100644
index 0000000000..b9b3ff66f0
--- /dev/null
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/imports/index.tsx
@@ -0,0 +1,71 @@
+import type { Import } from '@spree/admin-sdk'
+import { adminClient, ResourceTable, resourceSearchSchema } from '@spree/dashboard-core'
+import { RowActions, useConfirm, useRowClickBridge } from '@spree/dashboard-ui'
+import { createFileRoute, useNavigate } from '@tanstack/react-router'
+import { useTranslation } from 'react-i18next'
+import { isImportActive, useDeleteImport } from '@/hooks/use-imports'
+import '@/tables/imports'
+
+export const Route = createFileRoute('/_authenticated/$storeId/settings/imports/')({
+ validateSearch: resourceSearchSchema,
+ component: ImportsPage,
+})
+
+function ImportsPage() {
+ const { t } = useTranslation()
+ const { storeId } = Route.useParams()
+ const search = Route.useSearch()
+ const navigate = useNavigate()
+ const confirm = useConfirm()
+ const deleteMutation = useDeleteImport()
+
+ useRowClickBridge('data-import-id', (id: string) =>
+ navigate({
+ to: '/$storeId/settings/imports/$importId',
+ params: { storeId, importId: id },
+ }),
+ )
+
+ async function handleDelete(imp: Import) {
+ const ok = await confirm({
+ title: t('admin.pages.settings.imports.delete_confirm.title'),
+ message: t('admin.pages.settings.imports.delete_confirm.message', { number: imp.number }),
+ variant: 'destructive',
+ confirmLabel: t('admin.actions.delete'),
+ })
+ if (!ok) return
+ await deleteMutation.mutateAsync(imp.id).catch(() => undefined)
+ }
+
+ return (
+ <ResourceTable<Import>
+ tableKey="imports"
+ queryKey="imports"
+ queryFn={(params) => adminClient.imports.list(params)}
+ searchParams={search}
+ rowActions={(imp) => (
+ <RowActions
+ actions={[
+ {
+ key: 'view',
+ label: t('admin.actions.view'),
+ onSelect: () =>
+ navigate({
+ to: '/$storeId/settings/imports/$importId',
+ params: { storeId, importId: imp.id },
+ }),
+ },
+ {
+ key: 'delete',
+ destructive: true,
+ // Deleting mid-processing is refused server-side (422) — the
+ // pipeline's jobs re-load the record while running.
+ disabled: deleteMutation.isPending || isImportActive(imp.status),
+ onSelect: () => handleDelete(imp),
+ },
+ ]}
+ />
+ )}
+ />
+ )
+}
diff --git a/packages/dashboard/src/tables/imports.tsx b/packages/dashboard/src/tables/imports.tsx
new file mode 100644
index 0000000000..959332ecb2
--- /dev/null
+++ b/packages/dashboard/src/tables/imports.tsx
@@ -0,0 +1,70 @@
+import type { Import } from '@spree/admin-sdk'
+import { defineTable } from '@spree/dashboard-core'
+import { RelativeTime, ResourceNameCell, StatusBadge } from '@spree/dashboard-ui'
+import i18n from 'i18next'
+import { UploadIcon } from 'lucide-react'
+import { importTypeLabel } from '@/lib/import-types'
+
+defineTable<Import>('imports', {
+ title: i18n.t('admin.pages.settings.imports.title'),
+ searchParam: 'number_cont',
+ searchPlaceholder: i18n.t('admin.pages.settings.imports.search_placeholder'),
+ defaultSort: { field: 'created_at', direction: 'desc' },
+ emptyIcon: <UploadIcon className="size-8 text-muted-foreground" />,
+ emptyMessage: i18n.t('admin.pages.settings.imports.empty_title'),
+ columns: [
+ {
+ key: 'number',
+ label: i18n.t('admin.pages.settings.imports.table.number'),
+ sortable: true,
+ filterable: true,
+ default: true,
+ render: (imp) => <ResourceNameCell id={imp.id} dataAttr="data-import-id" name={imp.number} />,
+ },
+ {
+ key: 'type',
+ label: i18n.t('admin.pages.settings.imports.table.type'),
+ sortable: true,
+ default: true,
+ render: (imp) => importTypeLabel(imp.type),
+ },
+ {
+ key: 'status',
+ label: i18n.t('admin.pages.settings.imports.table.status'),
+ sortable: true,
+ filterable: true,
+ default: true,
+ render: (imp) => (
+ <StatusBadge status={imp.status} label={i18n.t(`admin.imports.status.${imp.status}`)} />
+ ),
+ },
+ {
+ key: 'rows',
+ label: i18n.t('admin.pages.settings.imports.table.rows'),
+ default: true,
+ render: (imp) => {
+ if (imp.rows_count === 0) return <span className="text-muted-foreground">—</span>
+ return (
+ <span>
+ {imp.completed_rows_count}/{imp.rows_count}
+ {imp.failed_rows_count > 0 && (
+ <span className="ml-1 text-destructive">
+ ·{' '}
+ {i18n.t('admin.pages.settings.imports.table.failed_count', {
+ failed: imp.failed_rows_count,
+ })}
+ </span>
+ )}
+ </span>
+ )
+ },
+ },
+ {
+ key: 'created_at',
+ label: i18n.t('admin.fields.created_at.label'),
+ sortable: true,
+ default: true,
+ render: (imp) => <RelativeTime iso={imp.created_at} />,
+ },
+ ],
+})