RestoreModal.tsx 19 KB

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