SpoolCsvImportModal.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. import { useState, useRef, type DragEvent } from 'react';
  2. import { useTranslation } from 'react-i18next';
  3. import { Upload, X, FileText, Loader2, CheckCircle, XCircle, MinusCircle, Wand2, AlertTriangle, Copy } from 'lucide-react';
  4. import { api, type CsvImportPreview, type CsvImportRow } from '../api/client';
  5. import { getSwatchStyle } from '../utils/colors';
  6. import { Button } from './Button';
  7. interface SpoolCsvImportModalProps {
  8. onClose: () => void;
  9. /** Called after a successful import so the page can refetch the inventory. */
  10. onImported: (created: number) => void;
  11. }
  12. /**
  13. * CSV import flow (#1576): pick a file → backend dry-run preview (per-row
  14. * valid/error/skipped, colours resolved) → user reviews → confirm imports only
  15. * the valid rows. Nothing is written until confirm.
  16. */
  17. export function SpoolCsvImportModal({ onClose, onImported }: SpoolCsvImportModalProps) {
  18. const { t } = useTranslation();
  19. const [file, setFile] = useState<File | null>(null);
  20. const [isDragging, setIsDragging] = useState(false);
  21. const [preview, setPreview] = useState<CsvImportPreview | null>(null);
  22. const [loading, setLoading] = useState(false);
  23. const [importing, setImporting] = useState(false);
  24. const [error, setError] = useState<string | null>(null);
  25. const fileInputRef = useRef<HTMLInputElement>(null);
  26. const loadPreview = async (selected: File) => {
  27. setFile(selected);
  28. setPreview(null);
  29. setError(null);
  30. setLoading(true);
  31. try {
  32. const result = await api.importSpoolsCsvPreview(selected);
  33. setPreview(result);
  34. } catch (err) {
  35. setError(err instanceof Error ? err.message : t('inventory.csv.previewError', 'Could not read the CSV file'));
  36. } finally {
  37. setLoading(false);
  38. }
  39. };
  40. const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
  41. const selected = e.target.files?.[0];
  42. if (selected) loadPreview(selected);
  43. };
  44. const handleDrop = (e: DragEvent<HTMLDivElement>) => {
  45. e.preventDefault();
  46. setIsDragging(false);
  47. const dropped = e.dataTransfer.files?.[0];
  48. if (dropped) loadPreview(dropped);
  49. };
  50. const handleImport = async () => {
  51. if (!file) return;
  52. setImporting(true);
  53. setError(null);
  54. try {
  55. const result = await api.importSpoolsCsv(file);
  56. onImported(result.created);
  57. } catch (err) {
  58. setError(err instanceof Error ? err.message : t('inventory.csv.importError', 'Import failed'));
  59. setImporting(false);
  60. }
  61. };
  62. const statusIcon = (status: CsvImportRow['status']) => {
  63. if (status === 'valid') return <CheckCircle className="w-4 h-4 text-green-500 flex-shrink-0" />;
  64. if (status === 'error') return <XCircle className="w-4 h-4 text-red-500 flex-shrink-0" />;
  65. return <MinusCircle className="w-4 h-4 text-bambu-gray flex-shrink-0" />;
  66. };
  67. const validCount = preview?.valid_count ?? 0;
  68. return (
  69. <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4">
  70. <div className="bg-bambu-dark-secondary rounded-lg w-full max-w-3xl border border-bambu-dark-tertiary flex flex-col max-h-[90vh]">
  71. <div className="p-4 border-b border-bambu-dark-tertiary flex items-center justify-between">
  72. <h2 className="text-lg font-semibold text-white">{t('inventory.csv.modalTitle', 'Import spools from CSV')}</h2>
  73. <button onClick={onClose} className="p-1 hover:bg-bambu-dark rounded">
  74. <X className="w-5 h-5 text-bambu-gray" />
  75. </button>
  76. </div>
  77. <div className="p-4 space-y-4 overflow-y-auto flex-1">
  78. {/* Drop zone / file picker */}
  79. <div
  80. onDragOver={(e) => {
  81. e.preventDefault();
  82. setIsDragging(true);
  83. }}
  84. onDragLeave={(e) => {
  85. e.preventDefault();
  86. setIsDragging(false);
  87. }}
  88. onDrop={handleDrop}
  89. onClick={() => fileInputRef.current?.click()}
  90. className={`border-2 border-dashed rounded-lg p-6 text-center cursor-pointer transition-colors ${
  91. isDragging
  92. ? 'border-bambu-green bg-bambu-green/10'
  93. : 'border-bambu-dark-tertiary hover:border-bambu-green/50'
  94. }`}
  95. >
  96. <Upload className={`w-9 h-9 mx-auto mb-2 ${isDragging ? 'text-bambu-green' : 'text-bambu-gray'}`} />
  97. {file ? (
  98. <p className="text-white font-medium flex items-center justify-center gap-2">
  99. <FileText className="w-4 h-4" /> {file.name}
  100. </p>
  101. ) : (
  102. <>
  103. <p className="text-white font-medium">{t('inventory.csv.selectFile', 'Choose a CSV file or drag it here')}</p>
  104. <p className="text-xs text-bambu-gray/70 mt-1">{t('inventory.csv.dragHint', 'Header: material (required), brand, subtype, color_name, rgba, …')}</p>
  105. </>
  106. )}
  107. </div>
  108. <input ref={fileInputRef} type="file" accept=".csv,text/csv" className="hidden" onChange={handleFileSelect} />
  109. {loading && (
  110. <div className="flex items-center justify-center gap-2 text-bambu-gray py-4">
  111. <Loader2 className="w-4 h-4 animate-spin" />
  112. {t('inventory.csv.parsing', 'Reading file…')}
  113. </div>
  114. )}
  115. {error && (
  116. <div className="p-3 bg-red-50 dark:bg-red-500/10 border border-red-300 dark:border-red-500/30 rounded-lg flex items-start gap-3">
  117. <XCircle className="w-5 h-5 text-red-600 dark:text-red-400 mt-0.5 flex-shrink-0" />
  118. <p className="text-sm text-red-700 dark:text-red-300 break-words">{error}</p>
  119. </div>
  120. )}
  121. {preview && (
  122. <>
  123. {/* Summary */}
  124. <div className="flex flex-wrap gap-3 text-sm">
  125. <span className="px-2 py-1 rounded bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400">
  126. {t('inventory.csv.validCount', '{{count}} valid', { count: preview.valid_count })}
  127. </span>
  128. <span className="px-2 py-1 rounded bg-red-50 dark:bg-red-500/10 text-red-700 dark:text-red-400">
  129. {t('inventory.csv.errorCount', '{{count}} error', { count: preview.error_count })}
  130. </span>
  131. <span className="px-2 py-1 rounded bg-bambu-dark text-bambu-gray">
  132. {t('inventory.csv.skippedCount', '{{count}} skipped', { count: preview.skipped_count })}
  133. </span>
  134. </div>
  135. {preview.warnings.length > 0 && (
  136. <div className="p-3 bg-yellow-50 dark:bg-yellow-500/10 border border-yellow-300 dark:border-yellow-500/30 rounded-lg space-y-1">
  137. {preview.warnings.map((w, i) => (
  138. <p key={i} className="text-xs text-yellow-700 dark:text-yellow-300">{w}</p>
  139. ))}
  140. </div>
  141. )}
  142. {/* Preview table */}
  143. {preview.rows.length > 0 && (
  144. <div className="border border-bambu-dark-tertiary rounded-lg overflow-hidden">
  145. <div className="max-h-72 overflow-y-auto">
  146. <table className="w-full text-sm">
  147. <thead className="bg-bambu-dark sticky top-0">
  148. <tr className="text-left text-bambu-gray">
  149. <th className="px-3 py-2 font-medium">{t('inventory.csv.colRow', 'Row')}</th>
  150. <th className="px-3 py-2 font-medium">{t('inventory.csv.colStatus', 'Status')}</th>
  151. <th className="px-3 py-2 font-medium">{t('inventory.material', 'Material')}</th>
  152. <th className="px-3 py-2 font-medium">{t('inventory.brand', 'Brand')}</th>
  153. <th className="px-3 py-2 font-medium">{t('inventory.csv.colColor', 'Color')}</th>
  154. </tr>
  155. </thead>
  156. <tbody>
  157. {preview.rows.map((row) => (
  158. <tr key={row.row_number} className="border-t border-bambu-dark-tertiary">
  159. <td className="px-3 py-2 text-bambu-gray">{row.row_number}</td>
  160. <td className="px-3 py-2">
  161. <div className="flex items-center gap-1.5">
  162. {statusIcon(row.status)}
  163. {row.status === 'error' && row.reason && (
  164. <span className="text-xs text-red-700 dark:text-red-400 break-words">{row.reason}</span>
  165. )}
  166. </div>
  167. </td>
  168. <td className="px-3 py-2 text-white">{row.material || '—'}</td>
  169. <td className="px-3 py-2 text-white">{row.brand || '—'}</td>
  170. <td className="px-3 py-2">
  171. <div className="flex items-center gap-2">
  172. {row.rgba && (
  173. <span
  174. className="inline-block w-4 h-4 rounded-full border border-bambu-dark-tertiary flex-shrink-0"
  175. style={getSwatchStyle(row.rgba)}
  176. />
  177. )}
  178. <span className="text-white">{row.color_name || '—'}</span>
  179. {row.resolved_color && !row.cross_material_color && (
  180. <span title={t('inventory.csv.colorResolved', 'Color filled from catalog')}>
  181. <Wand2 className="w-3.5 h-3.5 text-bambu-green flex-shrink-0" />
  182. </span>
  183. )}
  184. {row.cross_material_color && (
  185. <span title={t('inventory.csv.colorCrossMaterial', 'Color taken from a different material — no exact match in catalog')}>
  186. <AlertTriangle className="w-3.5 h-3.5 text-yellow-500 flex-shrink-0" />
  187. </span>
  188. )}
  189. {row.duplicate_of_existing && (
  190. <span title={t('inventory.csv.duplicateExisting', 'A spool with this material, brand and color already exists — it will still be imported as a new spool')}>
  191. <Copy className="w-3.5 h-3.5 text-amber-600 dark:text-amber-400 flex-shrink-0" />
  192. </span>
  193. )}
  194. </div>
  195. </td>
  196. </tr>
  197. ))}
  198. </tbody>
  199. </table>
  200. </div>
  201. </div>
  202. )}
  203. </>
  204. )}
  205. </div>
  206. <div className="p-4 border-t border-bambu-dark-tertiary flex justify-end gap-2">
  207. <Button variant="secondary" onClick={onClose} disabled={importing}>
  208. {t('common.cancel')}
  209. </Button>
  210. <Button onClick={handleImport} disabled={!preview || validCount === 0 || importing}>
  211. {importing ? (
  212. <>
  213. <Loader2 className="w-4 h-4 mr-2 animate-spin" />
  214. {t('inventory.csv.importing', 'Importing…')}
  215. </>
  216. ) : validCount > 0 ? (
  217. t('inventory.csv.importValidRows', 'Import {{count}} valid rows', { count: validCount })
  218. ) : (
  219. t('inventory.csv.noValidRows', 'No valid rows')
  220. )}
  221. </Button>
  222. </div>
  223. </div>
  224. </div>
  225. );
  226. }