RestoreModal.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. import { useState, useRef, useEffect } from 'react';
  2. import { Upload, X, AlertTriangle, CheckCircle, SkipForward, RefreshCw, Loader2, ChevronDown, ChevronUp } from 'lucide-react';
  3. import { Card, CardContent } from './Card';
  4. import { Button } from './Button';
  5. import { Toggle } from './Toggle';
  6. interface RestoreResult {
  7. success: boolean;
  8. message: string;
  9. restored?: Record<string, number>;
  10. skipped?: Record<string, number>;
  11. skipped_details?: Record<string, string[]>;
  12. files_restored?: number;
  13. total_skipped?: number;
  14. }
  15. interface RestoreModalProps {
  16. onClose: () => void;
  17. onRestore: (file: File, overwrite: boolean) => Promise<RestoreResult>;
  18. onSuccess: () => void;
  19. }
  20. type ModalState = 'options' | 'restoring' | 'result';
  21. const CATEGORY_LABELS: Record<string, string> = {
  22. settings: 'Settings',
  23. notification_providers: 'Notification Providers',
  24. notification_templates: 'Notification Templates',
  25. smart_plugs: 'Smart Plugs',
  26. printers: 'Printers',
  27. filaments: 'Filaments',
  28. maintenance_types: 'Maintenance Types',
  29. archives: 'Archives',
  30. projects: 'Projects',
  31. pending_uploads: 'Pending Uploads',
  32. external_links: 'External Links',
  33. };
  34. export function RestoreModal({ onClose, onRestore, onSuccess }: RestoreModalProps) {
  35. const [state, setState] = useState<ModalState>('options');
  36. const [overwrite, setOverwrite] = useState(false);
  37. const [selectedFile, setSelectedFile] = useState<File | null>(null);
  38. const [result, setResult] = useState<RestoreResult | null>(null);
  39. const [expandedCategories, setExpandedCategories] = useState<Set<string>>(new Set());
  40. const fileInputRef = useRef<HTMLInputElement>(null);
  41. useEffect(() => {
  42. const handleKeyDown = (e: KeyboardEvent) => {
  43. if (e.key === 'Escape' && state !== 'restoring') onClose();
  44. };
  45. window.addEventListener('keydown', handleKeyDown);
  46. return () => window.removeEventListener('keydown', handleKeyDown);
  47. }, [onClose, state]);
  48. const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
  49. const file = e.target.files?.[0];
  50. if (file) {
  51. setSelectedFile(file);
  52. }
  53. };
  54. const handleRestore = async () => {
  55. if (!selectedFile) return;
  56. setState('restoring');
  57. try {
  58. const restoreResult = await onRestore(selectedFile, overwrite);
  59. setResult(restoreResult);
  60. setState('result');
  61. if (restoreResult.success) {
  62. onSuccess();
  63. }
  64. } catch {
  65. setResult({
  66. success: false,
  67. message: 'Failed to restore backup. Please check the file format.',
  68. });
  69. setState('result');
  70. }
  71. };
  72. const toggleCategory = (category: string) => {
  73. setExpandedCategories(prev => {
  74. const next = new Set(prev);
  75. if (next.has(category)) {
  76. next.delete(category);
  77. } else {
  78. next.add(category);
  79. }
  80. return next;
  81. });
  82. };
  83. const totalRestored = result?.restored
  84. ? Object.values(result.restored).reduce((a, b) => a + b, 0) + (result.files_restored || 0)
  85. : 0;
  86. const totalSkipped = result?.total_skipped || 0;
  87. return (
  88. <div
  89. className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
  90. onMouseDown={(e) => {
  91. // Only close if clicking directly on the backdrop, not on children
  92. if (e.target === e.currentTarget && state !== 'restoring') {
  93. onClose();
  94. }
  95. }}
  96. >
  97. <Card className="w-full max-w-lg">
  98. <CardContent className="p-0">
  99. {/* Header */}
  100. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
  101. <div className="flex items-center gap-3">
  102. <div className={`p-2 rounded-full ${
  103. state === 'result' && result?.success
  104. ? 'bg-bambu-green/20 text-bambu-green'
  105. : state === 'result' && !result?.success
  106. ? 'bg-red-500/20 text-red-500'
  107. : 'bg-blue-500/20 text-blue-500'
  108. }`}>
  109. {state === 'result' && result?.success ? (
  110. <CheckCircle className="w-5 h-5" />
  111. ) : state === 'result' && !result?.success ? (
  112. <AlertTriangle className="w-5 h-5" />
  113. ) : (
  114. <Upload className="w-5 h-5" />
  115. )}
  116. </div>
  117. <div>
  118. <h3 className="text-lg font-semibold text-white">
  119. {state === 'options' && 'Restore Backup'}
  120. {state === 'restoring' && 'Restoring...'}
  121. {state === 'result' && (result?.success ? 'Restore Complete' : 'Restore Failed')}
  122. </h3>
  123. <p className="text-sm text-bambu-gray">
  124. {state === 'options' && 'Import settings from a backup file'}
  125. {state === 'restoring' && 'Please wait while your data is being restored'}
  126. {state === 'result' && result?.message}
  127. </p>
  128. </div>
  129. </div>
  130. {state !== 'restoring' && (
  131. <button
  132. onClick={onClose}
  133. className="p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors"
  134. >
  135. <X className="w-5 h-5" />
  136. </button>
  137. )}
  138. </div>
  139. {/* Options State */}
  140. {state === 'options' && (
  141. <>
  142. <div className="p-4 space-y-4">
  143. {/* File Selection */}
  144. <div>
  145. <input
  146. ref={fileInputRef}
  147. type="file"
  148. accept=".json,.zip"
  149. className="hidden"
  150. onChange={handleFileSelect}
  151. />
  152. <button
  153. type="button"
  154. onClick={() => fileInputRef.current?.click()}
  155. className={`w-full p-4 border-2 border-dashed rounded-lg transition-colors ${
  156. selectedFile
  157. ? 'border-bambu-green bg-bambu-green/10'
  158. : 'border-bambu-dark-tertiary hover:border-bambu-gray'
  159. }`}
  160. >
  161. {selectedFile ? (
  162. <div className="flex items-center justify-center gap-2 text-bambu-green">
  163. <CheckCircle className="w-5 h-5" />
  164. <span className="font-medium">{selectedFile.name}</span>
  165. </div>
  166. ) : (
  167. <div className="flex flex-col items-center gap-2 text-bambu-gray">
  168. <Upload className="w-8 h-8" />
  169. <span>Click to select backup file (.json or .zip)</span>
  170. </div>
  171. )}
  172. </button>
  173. </div>
  174. {/* Info Box */}
  175. <div className="p-3 rounded-lg bg-blue-500/10 border border-blue-500/30">
  176. <div className="flex items-start gap-2 text-sm">
  177. <AlertTriangle className="w-4 h-4 text-blue-500 dark:text-blue-400 mt-0.5 flex-shrink-0" />
  178. <div className="text-blue-700 dark:text-blue-200">
  179. <p className="font-medium mb-1">How duplicate handling works:</p>
  180. <ul className="text-blue-600 dark:text-blue-200/80 space-y-1 text-xs">
  181. <li><strong>Printers</strong> - matched by serial number</li>
  182. <li><strong>Smart Plugs</strong> - matched by IP address</li>
  183. <li><strong>Notification Providers</strong> - matched by name</li>
  184. <li><strong>Filaments</strong> - matched by name + type + brand</li>
  185. <li><strong>Archives</strong> - matched by content hash (always skipped)</li>
  186. <li><strong>Pending Uploads</strong> - matched by filename</li>
  187. <li><strong>Settings & Templates</strong> - always overwritten</li>
  188. </ul>
  189. </div>
  190. </div>
  191. </div>
  192. {/* Overwrite Toggle */}
  193. <div className="p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary">
  194. <div className="flex items-center justify-between">
  195. <div>
  196. <p className="text-white font-medium flex items-center gap-2">
  197. {overwrite ? (
  198. <RefreshCw className="w-4 h-4 text-orange-400" />
  199. ) : (
  200. <SkipForward className="w-4 h-4 text-bambu-gray" />
  201. )}
  202. {overwrite ? 'Replace existing data' : 'Keep existing data'}
  203. </p>
  204. <p className="text-sm text-bambu-gray mt-1">
  205. {overwrite
  206. ? 'Overwrite items that already exist with backup data'
  207. : 'Only restore items that don\'t already exist'}
  208. </p>
  209. </div>
  210. <Toggle checked={overwrite} onChange={setOverwrite} />
  211. </div>
  212. </div>
  213. {overwrite && (
  214. <div className="p-3 rounded-lg bg-orange-500/10 border border-orange-500/30">
  215. <div className="flex items-start gap-2 text-sm">
  216. <AlertTriangle className="w-4 h-4 text-orange-500 dark:text-orange-400 mt-0.5 flex-shrink-0" />
  217. <div className="text-orange-700 dark:text-orange-200">
  218. <span className="font-medium">Caution:</span> Overwriting will replace your current configurations with data from the backup. Printer access codes are never overwritten for security.
  219. </div>
  220. </div>
  221. </div>
  222. )}
  223. </div>
  224. {/* Footer */}
  225. <div className="flex items-center justify-end gap-3 p-4 border-t border-bambu-dark-tertiary">
  226. <Button type="button" variant="secondary" onClick={onClose}>
  227. Cancel
  228. </Button>
  229. <Button
  230. type="button"
  231. onClick={handleRestore}
  232. disabled={!selectedFile}
  233. className="bg-bambu-green hover:bg-bambu-green-dark disabled:opacity-50"
  234. >
  235. <Upload className="w-4 h-4 mr-2" />
  236. Restore
  237. </Button>
  238. </div>
  239. </>
  240. )}
  241. {/* Restoring State */}
  242. {state === 'restoring' && (
  243. <div className="p-8 flex flex-col items-center gap-4">
  244. <Loader2 className="w-12 h-12 text-bambu-green animate-spin" />
  245. <p className="text-bambu-gray">Processing backup file...</p>
  246. </div>
  247. )}
  248. {/* Result State */}
  249. {state === 'result' && result && (
  250. <>
  251. <div className="p-4 space-y-4 max-h-[400px] overflow-y-auto">
  252. {/* Summary */}
  253. <div className="grid grid-cols-2 gap-3">
  254. <div className="p-3 rounded-lg bg-bambu-green/10 border border-bambu-green/30">
  255. <div className="text-2xl font-bold text-bambu-green">{totalRestored}</div>
  256. <div className="text-sm text-bambu-gray">Items Restored</div>
  257. </div>
  258. <div className="p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/30">
  259. <div className="text-2xl font-bold text-yellow-500">{totalSkipped}</div>
  260. <div className="text-sm text-bambu-gray">Items Skipped</div>
  261. </div>
  262. </div>
  263. {/* Restored Details */}
  264. {result.restored && Object.entries(result.restored).some(([, count]) => count > 0) && (
  265. <div className="space-y-2">
  266. <h4 className="text-sm font-medium text-bambu-gray flex items-center gap-2">
  267. <CheckCircle className="w-4 h-4 text-bambu-green" />
  268. Restored
  269. </h4>
  270. <div className="space-y-1">
  271. {Object.entries(result.restored)
  272. .filter(([, count]) => count > 0)
  273. .map(([key, count]) => (
  274. <div key={key} className="flex items-center justify-between text-sm p-2 rounded bg-bambu-dark">
  275. <span className="text-white">{CATEGORY_LABELS[key] || key}</span>
  276. <span className="text-bambu-green font-medium">{count}</span>
  277. </div>
  278. ))}
  279. {(result.files_restored || 0) > 0 && (
  280. <div className="flex items-center justify-between text-sm p-2 rounded bg-bambu-dark">
  281. <span className="text-white">Files (3MF, thumbnails, etc.)</span>
  282. <span className="text-bambu-green font-medium">{result.files_restored}</span>
  283. </div>
  284. )}
  285. </div>
  286. </div>
  287. )}
  288. {/* Skipped Details */}
  289. {result.skipped && Object.entries(result.skipped).some(([, count]) => count > 0) && (
  290. <div className="space-y-2">
  291. <h4 className="text-sm font-medium text-bambu-gray flex items-center gap-2">
  292. <SkipForward className="w-4 h-4 text-yellow-500" />
  293. Skipped (already exist)
  294. </h4>
  295. <div className="space-y-1">
  296. {Object.entries(result.skipped)
  297. .filter(([, count]) => count > 0)
  298. .map(([key, count]) => {
  299. const details = result.skipped_details?.[key] || [];
  300. const isExpanded = expandedCategories.has(key);
  301. return (
  302. <div key={key}>
  303. <button
  304. onClick={() => details.length > 0 && toggleCategory(key)}
  305. className={`w-full flex items-center justify-between text-sm p-2 rounded bg-bambu-dark ${
  306. details.length > 0 ? 'hover:bg-bambu-dark-tertiary cursor-pointer' : ''
  307. }`}
  308. >
  309. <span className="text-white flex items-center gap-2">
  310. {CATEGORY_LABELS[key] || key}
  311. {details.length > 0 && (
  312. isExpanded ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />
  313. )}
  314. </span>
  315. <span className="text-yellow-500 font-medium">{count}</span>
  316. </button>
  317. {isExpanded && details.length > 0 && (
  318. <div className="mt-1 ml-4 p-2 rounded bg-bambu-dark-tertiary text-xs text-bambu-gray space-y-1">
  319. {details.slice(0, 10).map((item, i) => (
  320. <div key={i}>{item}</div>
  321. ))}
  322. {details.length > 10 && (
  323. <div className="text-bambu-gray/60">...and {details.length - 10} more</div>
  324. )}
  325. </div>
  326. )}
  327. </div>
  328. );
  329. })}
  330. </div>
  331. </div>
  332. )}
  333. {totalRestored === 0 && totalSkipped === 0 && (
  334. <div className="p-4 text-center text-bambu-gray">
  335. No data was found to restore in the backup file.
  336. </div>
  337. )}
  338. </div>
  339. {/* Footer */}
  340. <div className="flex items-center justify-end gap-3 p-4 border-t border-bambu-dark-tertiary">
  341. <Button onClick={onClose}>
  342. Close
  343. </Button>
  344. </div>
  345. </>
  346. )}
  347. </CardContent>
  348. </Card>
  349. </div>
  350. );
  351. }