EditArchiveModal.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. import { useState, useEffect, useRef } from 'react';
  2. import { useMutation, useQueryClient, useQuery } from '@tanstack/react-query';
  3. import { useTranslation } from 'react-i18next';
  4. import { X, Save, Tag, Camera, Trash2, Loader2, Plus, FolderKanban, Hash, Link } from 'lucide-react';
  5. import { api } from '../api/client';
  6. import type { Archive } from '../api/client';
  7. import { Button } from './Button';
  8. import { PrintLogTable } from './PrintLogTable';
  9. // Keys for failure reasons - translated at render time.
  10. // Exported so the Print Log per-row classification editor (#1687 part 4)
  11. // can share the same vocabulary as the Archive Edit modal — the backend
  12. // PATCH /print-log/{id} validator gates writes against this exact list.
  13. export const FAILURE_REASON_KEYS = [
  14. 'adhesionFailure',
  15. 'spaghettiDetached',
  16. 'layerShift',
  17. 'cloggedNozzle',
  18. 'filamentRunout',
  19. 'warping',
  20. 'stringing',
  21. 'underExtrusion',
  22. 'powerFailure',
  23. 'userCancelled',
  24. 'other',
  25. ] as const;
  26. // Keys for archive statuses - translated at render time
  27. const ARCHIVE_STATUS_KEYS = ['completed', 'failed', 'aborted', 'printing'] as const;
  28. interface EditArchiveModalProps {
  29. archive: Archive;
  30. onClose: () => void;
  31. existingTags?: string[];
  32. }
  33. export function EditArchiveModal({ archive, onClose, existingTags = [] }: EditArchiveModalProps) {
  34. const { t } = useTranslation();
  35. // Close on Escape key
  36. useEffect(() => {
  37. const handleKeyDown = (e: KeyboardEvent) => {
  38. if (e.key === 'Escape') onClose();
  39. };
  40. window.addEventListener('keydown', handleKeyDown);
  41. return () => window.removeEventListener('keydown', handleKeyDown);
  42. }, [onClose]);
  43. const queryClient = useQueryClient();
  44. const [printName, setPrintName] = useState(archive.print_name || '');
  45. const [printerId, setPrinterId] = useState<number | null>(archive.printer_id);
  46. const [projectId, setProjectId] = useState<number | null>(archive.project_id ?? null);
  47. const [notes, setNotes] = useState(archive.notes || '');
  48. const [tags, setTags] = useState(archive.tags || '');
  49. // Failure reason is stored as a camelCase key (`filamentRunout`), but earlier
  50. // versions of this modal saved the translated label as the value. Reverse-
  51. // lookup any legacy translated text against the current locale so the
  52. // dropdown pre-selects the right option, then any save converts it forward.
  53. const [failureReason, setFailureReason] = useState(() => {
  54. const raw = archive.failure_reason || '';
  55. if (!raw) return '';
  56. if ((FAILURE_REASON_KEYS as readonly string[]).includes(raw)) return raw;
  57. const match = FAILURE_REASON_KEYS.find(
  58. (k) => t(`editArchive.failureReasons.${k}`) === raw,
  59. );
  60. return match || '';
  61. });
  62. const [status, setStatus] = useState(archive.status);
  63. const [quantity, setQuantity] = useState(archive.quantity ?? 1);
  64. const [photos, setPhotos] = useState<string[]>(archive.photos || []);
  65. const [externalUrl, setExternalUrl] = useState(archive.external_url || '');
  66. const [uploadingPhoto, setUploadingPhoto] = useState(false);
  67. const [showTagSuggestions, setShowTagSuggestions] = useState(false);
  68. const tagInputRef = useRef<HTMLInputElement>(null);
  69. const photoInputRef = useRef<HTMLInputElement>(null);
  70. const blurTimeoutRef = useRef<number | null>(null);
  71. const { data: printers } = useQuery({
  72. queryKey: ['printers'],
  73. queryFn: api.getPrinters,
  74. });
  75. const { data: projects } = useQuery({
  76. queryKey: ['projects'],
  77. queryFn: () => api.getProjects(),
  78. select: (rows) => [...rows].sort((a, b) => a.name.localeCompare(b.name)),
  79. });
  80. // Fetch all tags using the dedicated API
  81. const { data: tagsData } = useQuery({
  82. queryKey: ['tags'],
  83. queryFn: api.getTags,
  84. enabled: existingTags.length === 0,
  85. });
  86. // Use existing tags prop if provided, otherwise use fetched tags
  87. const allTags = existingTags.length > 0
  88. ? existingTags
  89. : (tagsData?.map(t => t.name) || []);
  90. // Get current tags as array
  91. const currentTags = tags.split(',').map(t => t.trim()).filter(Boolean);
  92. // Get the text being typed after the last comma (for autocomplete filtering)
  93. const currentInput = tags.includes(',')
  94. ? tags.substring(tags.lastIndexOf(',') + 1).trim().toLowerCase()
  95. : tags.trim().toLowerCase();
  96. // Filter suggestions: not already added AND matches current input (if any)
  97. const tagSuggestions = allTags.filter(t =>
  98. !currentTags.includes(t) &&
  99. (currentInput === '' || t.toLowerCase().includes(currentInput))
  100. );
  101. // Add a tag (replaces any partial input with the selected tag)
  102. const addTag = (tag: string) => {
  103. // If there's partial input being typed, replace it with the selected tag
  104. // Otherwise, just append the tag
  105. let baseTags: string[];
  106. if (currentInput && !allTags.includes(currentInput)) {
  107. // User is typing a partial tag - replace it with the selected one
  108. baseTags = tags.includes(',')
  109. ? tags.substring(0, tags.lastIndexOf(',')).split(',').map(t => t.trim()).filter(Boolean)
  110. : [];
  111. } else {
  112. // No partial input or input is already a complete tag - append
  113. baseTags = currentTags;
  114. }
  115. if (!baseTags.includes(tag)) {
  116. const newTags = [...baseTags, tag].join(', ');
  117. setTags(newTags);
  118. }
  119. // Clear any pending blur timeout to prevent hiding suggestions
  120. if (blurTimeoutRef.current !== null) {
  121. clearTimeout(blurTimeoutRef.current);
  122. }
  123. tagInputRef.current?.focus();
  124. };
  125. // Remove a tag
  126. const removeTag = (tagToRemove: string) => {
  127. const newTags = currentTags.filter(t => t !== tagToRemove).join(', ');
  128. setTags(newTags);
  129. };
  130. const updateMutation = useMutation({
  131. mutationFn: (data: Parameters<typeof api.updateArchive>[1]) =>
  132. api.updateArchive(archive.id, data),
  133. onSuccess: () => {
  134. queryClient.invalidateQueries({ queryKey: ['archives'] });
  135. queryClient.invalidateQueries({ queryKey: ['projects'] });
  136. onClose();
  137. },
  138. });
  139. const handlePhotoUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
  140. const file = e.target.files?.[0];
  141. if (!file) return;
  142. setUploadingPhoto(true);
  143. try {
  144. const result = await api.uploadArchivePhoto(archive.id, file);
  145. setPhotos(result.photos);
  146. queryClient.invalidateQueries({ queryKey: ['archives'] });
  147. } catch (error) {
  148. console.error('Failed to upload photo:', error);
  149. } finally {
  150. setUploadingPhoto(false);
  151. if (photoInputRef.current) {
  152. photoInputRef.current.value = '';
  153. }
  154. }
  155. };
  156. const handlePhotoDelete = async (filename: string) => {
  157. try {
  158. const result = await api.deleteArchivePhoto(archive.id, filename);
  159. setPhotos(result.photos || []);
  160. queryClient.invalidateQueries({ queryKey: ['archives'] });
  161. } catch (error) {
  162. console.error('Failed to delete photo:', error);
  163. }
  164. };
  165. const handleSubmit = (e: React.FormEvent) => {
  166. e.preventDefault();
  167. // Build update data
  168. const updateData: Parameters<typeof api.updateArchive>[1] = {
  169. print_name: printName || undefined,
  170. printer_id: printerId,
  171. project_id: projectId,
  172. notes: notes || undefined,
  173. tags: tags || undefined,
  174. quantity: quantity,
  175. external_url: externalUrl || null,
  176. };
  177. // Only include status if changed
  178. if (status !== archive.status) {
  179. updateData.status = status;
  180. }
  181. // Handle failure_reason based on status
  182. if (status === 'failed' || status === 'aborted') {
  183. updateData.failure_reason = failureReason || undefined;
  184. } else if (archive.status === 'failed' || archive.status === 'aborted') {
  185. // Clear failure_reason when changing from failed/aborted to another status
  186. updateData.failure_reason = null;
  187. }
  188. updateMutation.mutate(updateData);
  189. };
  190. return (
  191. <div
  192. className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4"
  193. onClick={onClose}
  194. >
  195. <div
  196. className="bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md max-h-[90vh] flex flex-col"
  197. onClick={(e) => e.stopPropagation()}
  198. >
  199. {/* Header */}
  200. <div className="flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary">
  201. <h2 className="text-lg font-semibold text-white">{t('editArchive.title')}</h2>
  202. <button
  203. onClick={onClose}
  204. className="text-bambu-gray hover:text-white transition-colors"
  205. >
  206. <X className="w-5 h-5" />
  207. </button>
  208. </div>
  209. {/* Form */}
  210. <form onSubmit={handleSubmit} className="p-6 space-y-4 overflow-y-auto flex-1">
  211. {/* Print Log — per-run history pulled from PrintLogEntry (#1378). Shown
  212. first so users can see which runs contributed to the aggregate stats. */}
  213. <div>
  214. <label className="block text-sm text-bambu-gray mb-1">{t('archives.runLog.title')}</label>
  215. <PrintLogTable archiveId={archive.id} />
  216. </div>
  217. {/* Print Name */}
  218. <div>
  219. <label className="block text-sm text-bambu-gray mb-1">{t('editArchive.name')}</label>
  220. <input
  221. type="text"
  222. value={printName}
  223. onChange={(e) => setPrintName(e.target.value)}
  224. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  225. placeholder={t('editArchive.namePlaceholder')}
  226. />
  227. </div>
  228. {/* Printer */}
  229. <div>
  230. <label className="block text-sm text-bambu-gray mb-1">{t('editArchive.printer')}</label>
  231. <select
  232. value={printerId ?? ''}
  233. onChange={(e) => setPrinterId(e.target.value ? Number(e.target.value) : null)}
  234. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  235. >
  236. <option value="">{t('editArchive.noPrinter')}</option>
  237. {printers?.map((p) => (
  238. <option key={p.id} value={p.id}>
  239. {p.name}
  240. </option>
  241. ))}
  242. </select>
  243. </div>
  244. {/* Project */}
  245. <div>
  246. <label className="block text-sm text-bambu-gray mb-1">
  247. <FolderKanban className="w-4 h-4 inline mr-1" />
  248. {t('editArchive.project')}
  249. </label>
  250. <select
  251. value={projectId ?? ''}
  252. onChange={(e) => setProjectId(e.target.value ? Number(e.target.value) : null)}
  253. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  254. >
  255. <option value="">{t('editArchive.noProject')}</option>
  256. {projects?.map((p) => (
  257. <option key={p.id} value={p.id}>
  258. {p.name}
  259. </option>
  260. ))}
  261. </select>
  262. </div>
  263. {/* Quantity - number of items printed */}
  264. <div>
  265. <label className="block text-sm text-bambu-gray mb-1">
  266. <Hash className="w-4 h-4 inline mr-1" />
  267. {t('editArchive.itemsPrinted')}
  268. </label>
  269. <input
  270. type="number"
  271. min={1}
  272. value={quantity}
  273. onChange={(e) => setQuantity(Math.max(1, parseInt(e.target.value) || 1))}
  274. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  275. placeholder="1"
  276. />
  277. <p className="text-xs text-bambu-gray mt-1">
  278. {t('editArchive.itemsPrintedHelp')}
  279. </p>
  280. </div>
  281. {/* Notes */}
  282. <div>
  283. <label className="block text-sm text-bambu-gray mb-1">{t('editArchive.notes')}</label>
  284. <textarea
  285. value={notes}
  286. onChange={(e) => setNotes(e.target.value)}
  287. rows={3}
  288. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none resize-none"
  289. placeholder={t('editArchive.notesPlaceholder')}
  290. />
  291. </div>
  292. {/* External Link */}
  293. <div>
  294. <label className="block text-sm text-bambu-gray mb-1">
  295. <Link className="w-4 h-4 inline mr-1" />
  296. {t('editArchive.externalLink')}
  297. </label>
  298. <input
  299. type="url"
  300. value={externalUrl}
  301. onChange={(e) => setExternalUrl(e.target.value)}
  302. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  303. placeholder="https://printables.com/model/..."
  304. />
  305. <p className="text-xs text-bambu-gray mt-1">
  306. {t('editArchive.externalLinkHelp')}
  307. </p>
  308. </div>
  309. {/* Tags */}
  310. <div>
  311. <label className="block text-sm text-bambu-gray mb-1">{t('editArchive.tags')}</label>
  312. {/* Current tags as chips */}
  313. {currentTags.length > 0 && (
  314. <div className="flex flex-wrap gap-1.5 mb-2">
  315. {currentTags.map((tag) => (
  316. <span
  317. key={tag}
  318. className="inline-flex items-center gap-1 px-2 py-0.5 bg-bambu-dark-tertiary rounded text-sm text-white"
  319. >
  320. <Tag className="w-3 h-3" />
  321. {tag}
  322. <button
  323. type="button"
  324. onClick={() => removeTag(tag)}
  325. className="ml-0.5 text-bambu-gray hover:text-white"
  326. >
  327. <X className="w-3 h-3" />
  328. </button>
  329. </span>
  330. ))}
  331. </div>
  332. )}
  333. {/* Tag input with suggestions */}
  334. <div className="relative">
  335. <input
  336. ref={tagInputRef}
  337. type="text"
  338. value={tags}
  339. onChange={(e) => setTags(e.target.value)}
  340. onFocus={() => {
  341. if (blurTimeoutRef.current !== null) {
  342. clearTimeout(blurTimeoutRef.current);
  343. }
  344. setShowTagSuggestions(true);
  345. }}
  346. onBlur={() => {
  347. blurTimeoutRef.current = window.setTimeout(() => setShowTagSuggestions(false), 200);
  348. }}
  349. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  350. placeholder={currentTags.length > 0 ? t('editArchive.addMoreTags') : t('editArchive.tagsPlaceholder')}
  351. />
  352. {/* Suggestions dropdown */}
  353. {showTagSuggestions && tagSuggestions.length > 0 && (
  354. <div className="absolute top-full left-0 right-0 mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg z-10 max-h-40 overflow-y-auto">
  355. <div className="p-2 text-xs text-bambu-gray border-b border-bambu-dark-tertiary">
  356. {currentInput ? t('editArchive.matchingTags', { query: currentInput }) : t('editArchive.existingTags')} {t('editArchive.clickToAdd')}
  357. </div>
  358. <div className="p-2 flex flex-wrap gap-1.5">
  359. {tagSuggestions.map((tag) => (
  360. <button
  361. key={tag}
  362. type="button"
  363. onClick={() => addTag(tag)}
  364. className="px-2 py-0.5 bg-bambu-dark-tertiary hover:bg-bambu-green/20 rounded text-sm text-bambu-gray hover:text-white transition-colors"
  365. >
  366. {tag}
  367. </button>
  368. ))}
  369. </div>
  370. </div>
  371. )}
  372. </div>
  373. </div>
  374. {/* Status */}
  375. <div>
  376. <label className="block text-sm text-bambu-gray mb-1">{t('editArchive.status')}</label>
  377. <select
  378. value={status}
  379. onChange={(e) => {
  380. setStatus(e.target.value);
  381. // Clear failure reason when changing to completed
  382. if (e.target.value === 'completed') {
  383. setFailureReason('');
  384. }
  385. }}
  386. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  387. >
  388. {ARCHIVE_STATUS_KEYS.map((statusKey) => (
  389. <option key={statusKey} value={statusKey}>
  390. {t(`editArchive.statuses.${statusKey}`)}
  391. </option>
  392. ))}
  393. </select>
  394. </div>
  395. {/* Failure Reason - only show for failed/aborted prints */}
  396. {(status === 'failed' || status === 'aborted') && (
  397. <div>
  398. <label htmlFor="failure-reason-select" className="block text-sm text-bambu-gray mb-1">{t('editArchive.failureReason')}</label>
  399. <select
  400. id="failure-reason-select"
  401. value={failureReason}
  402. onChange={(e) => setFailureReason(e.target.value)}
  403. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  404. >
  405. <option value="">{t('editArchive.selectReason')}</option>
  406. {FAILURE_REASON_KEYS.map((reasonKey) => (
  407. <option key={reasonKey} value={reasonKey}>
  408. {t(`editArchive.failureReasons.${reasonKey}`)}
  409. </option>
  410. ))}
  411. </select>
  412. </div>
  413. )}
  414. {/* Photos */}
  415. <div>
  416. <label className="block text-sm text-bambu-gray mb-1">
  417. <Camera className="w-4 h-4 inline mr-1" />
  418. {t('editArchive.photos')}
  419. </label>
  420. {/* Photo grid */}
  421. <div className="flex flex-wrap gap-2 mb-2">
  422. {photos.map((filename) => (
  423. <div key={filename} className="relative group">
  424. <img
  425. src={api.getArchivePhotoUrl(archive.id, filename)}
  426. alt={t('editArchive.printResult')}
  427. className="w-20 h-20 object-cover rounded-lg border border-bambu-dark-tertiary"
  428. />
  429. <button
  430. type="button"
  431. onClick={() => handlePhotoDelete(filename)}
  432. className="absolute -top-1 -right-1 p-1 bg-red-500 rounded-full opacity-0 group-hover:opacity-100 transition-opacity"
  433. >
  434. <Trash2 className="w-3 h-3 text-white" />
  435. </button>
  436. </div>
  437. ))}
  438. {/* Upload button */}
  439. <label className="w-20 h-20 flex items-center justify-center border-2 border-dashed border-bambu-dark-tertiary rounded-lg cursor-pointer hover:border-bambu-green transition-colors">
  440. <input
  441. ref={photoInputRef}
  442. type="file"
  443. accept="image/jpeg,image/png,image/webp"
  444. onChange={handlePhotoUpload}
  445. className="hidden"
  446. disabled={uploadingPhoto}
  447. />
  448. {uploadingPhoto ? (
  449. <Loader2 className="w-6 h-6 text-bambu-gray animate-spin" />
  450. ) : (
  451. <Plus className="w-6 h-6 text-bambu-gray" />
  452. )}
  453. </label>
  454. </div>
  455. <p className="text-xs text-bambu-gray">{t('editArchive.photosHelp')}</p>
  456. </div>
  457. {/* Actions */}
  458. <div className="flex gap-3 pt-2">
  459. <Button
  460. type="button"
  461. variant="secondary"
  462. onClick={onClose}
  463. className="flex-1"
  464. >
  465. {t('common.cancel')}
  466. </Button>
  467. <Button
  468. type="submit"
  469. disabled={updateMutation.isPending}
  470. className="flex-1"
  471. >
  472. <Save className="w-4 h-4" />
  473. {updateMutation.isPending ? t('common.saving') : t('common.save')}
  474. </Button>
  475. </div>
  476. </form>
  477. </div>
  478. </div>
  479. );
  480. }