EditArchiveModal.tsx 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  1. import { useState, useEffect, useMemo, 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, Weight } from 'lucide-react';
  5. import { api } from '../api/client';
  6. import { useAuth } from '../contexts/AuthContext';
  7. import type { Archive } from '../api/client';
  8. import { Button } from './Button';
  9. import { PrintLogTable } from './PrintLogTable';
  10. import { invalidateArchiveAndProjectViews } from '../utils/projectQueries';
  11. import { assignableProjects } from '../utils/projectTree';
  12. import { verdictSourceKey } from '../utils/verdictSource';
  13. import { NumberInput } from './NumberInput';
  14. // Keys for failure reasons - translated at render time.
  15. // Exported so the Print Log per-row classification editor (#1687 part 4)
  16. // can share the same vocabulary as the Archive Edit modal — the backend
  17. // PATCH /print-log/{id} validator gates writes against this exact list.
  18. export const FAILURE_REASON_KEYS = [
  19. 'adhesionFailure',
  20. 'spaghettiDetached',
  21. 'layerShift',
  22. 'cloggedNozzle',
  23. 'filamentRunout',
  24. 'warping',
  25. 'stringing',
  26. 'underExtrusion',
  27. 'powerFailure',
  28. 'userCancelled',
  29. 'noStatusUpdate',
  30. 'other',
  31. ] as const;
  32. // The finished outcomes an archive can be given by hand (the API refuses any
  33. // other). Translated at render time.
  34. const ARCHIVE_STATUS_KEYS: readonly string[] = ['completed', 'failed', 'aborted', 'cancelled'];
  35. // Mirrors the API's own bound on filament_used_grams. Clamped here as well so
  36. // the field cannot produce a request the backend would reject with a 422 —
  37. // this modal has no error surface, so a refused save looks like nothing
  38. // happened at all (#1820).
  39. const MAX_FILAMENT_GRAMS = 100000;
  40. interface EditArchiveModalProps {
  41. archive: Archive;
  42. onClose: () => void;
  43. existingTags?: string[];
  44. }
  45. export function EditArchiveModal({ archive, onClose, existingTags = [] }: EditArchiveModalProps) {
  46. const { t } = useTranslation();
  47. // Close on Escape key
  48. useEffect(() => {
  49. const handleKeyDown = (e: KeyboardEvent) => {
  50. if (e.key === 'Escape') onClose();
  51. };
  52. window.addEventListener('keydown', handleKeyDown);
  53. return () => window.removeEventListener('keydown', handleKeyDown);
  54. }, [onClose]);
  55. const queryClient = useQueryClient();
  56. const [printName, setPrintName] = useState(archive.print_name || '');
  57. const [printerId, setPrinterId] = useState<number | null>(archive.printer_id);
  58. const [projectId, setProjectId] = useState<number | null>(archive.project_id ?? null);
  59. const [notes, setNotes] = useState(archive.notes || '');
  60. const [tags, setTags] = useState(archive.tags || '');
  61. // Failure reason is stored as a camelCase key (`filamentRunout`). Three older
  62. // writers stored other spellings -- English display labels from the backend,
  63. // this modal's own translated labels, and two prose sentences from the stale
  64. // archive paths -- and a startup migration folds all of them onto keys
  65. // (issue #2974). This reverse lookup is the belt to that migration's braces,
  66. // for a frontend running against a backend that has not restarted yet.
  67. //
  68. // A value it cannot resolve is kept rather than dropped. It used to fall back
  69. // to '', which did not merely look wrong: the empty selection was then saved
  70. // over the stored text, so opening the editor on an archive whose reason was
  71. // free text and pressing Save silently destroyed the classification. Anything
  72. // unrecognised now shows up as its own option (see `unmappedReason` below).
  73. const [failureReason, setFailureReason] = useState(() => {
  74. const raw = archive.failure_reason || '';
  75. if (!raw) return '';
  76. if ((FAILURE_REASON_KEYS as readonly string[]).includes(raw)) return raw;
  77. const match = FAILURE_REASON_KEYS.find(
  78. (k) => t(`editArchive.failureReasons.${k}`) === raw,
  79. );
  80. return match || raw;
  81. });
  82. // The stored value when it is not part of the vocabulary, so the dropdown can
  83. // offer it verbatim instead of appearing empty over a reason that exists.
  84. const unmappedReason =
  85. failureReason && !(FAILURE_REASON_KEYS as readonly string[]).includes(failureReason)
  86. ? failureReason
  87. : null;
  88. const [status, setStatus] = useState(archive.status);
  89. // Post-print quality verdict (#1898): '' = none, 'good' / 'reject'
  90. const [userVerdict, setUserVerdict] = useState<string>(archive.user_verdict ?? '');
  91. const verdictSourceHintKey = verdictSourceKey(archive.user_verdict_source);
  92. const [quantity, setQuantity] = useState(archive.quantity ?? 1);
  93. // Kept as a string so the field can be genuinely empty: a print archived
  94. // without its 3MF has no figure at all, and "" has to stay distinguishable
  95. // from 0 both on the way in and on the way out (#1820).
  96. const [filamentGrams, setFilamentGrams] = useState(
  97. archive.filament_used_grams != null ? String(archive.filament_used_grams) : ''
  98. );
  99. const { hasPermission } = useAuth();
  100. // Later prints of the archive are charged from its weight: without the right
  101. // to edit every archive, it can only be filled in for an archive without its
  102. // 3MF, which has none and cannot be printed again (the API refuses the rest).
  103. const filamentGramsLocked =
  104. !hasPermission('archives:update_all') && (archive.filament_used_grams != null || !!archive.file_path);
  105. const [photos, setPhotos] = useState<string[]>(archive.photos || []);
  106. const [externalUrl, setExternalUrl] = useState(archive.external_url || '');
  107. const [uploadingPhoto, setUploadingPhoto] = useState(false);
  108. const [showTagSuggestions, setShowTagSuggestions] = useState(false);
  109. const tagInputRef = useRef<HTMLInputElement>(null);
  110. const photoInputRef = useRef<HTMLInputElement>(null);
  111. const blurTimeoutRef = useRef<number | null>(null);
  112. const { data: printers } = useQuery({
  113. queryKey: ['printers'],
  114. queryFn: api.getPrinters,
  115. });
  116. const { data: projects } = useQuery({
  117. queryKey: ['projects'],
  118. queryFn: () => api.getProjects(),
  119. select: (rows) => [...rows].sort((a, b) => a.name.localeCompare(b.name)),
  120. });
  121. // Archived projects drop off the list, except the one this archive is
  122. // already filed under. That one has to stay: a select holding a value with
  123. // no matching option resets to the first one, so the field would read
  124. // "No project" for an archive that is in one (#2888).
  125. const projectOptions = useMemo(
  126. () => assignableProjects(projects ?? [], archive.project_id),
  127. [projects, archive.project_id],
  128. );
  129. // Fetch all tags using the dedicated API
  130. const { data: tagsData } = useQuery({
  131. queryKey: ['tags'],
  132. queryFn: api.getTags,
  133. enabled: existingTags.length === 0,
  134. });
  135. // Use existing tags prop if provided, otherwise use fetched tags
  136. const allTags = existingTags.length > 0
  137. ? existingTags
  138. : (tagsData?.map(t => t.name) || []);
  139. // Get current tags as array
  140. const currentTags = tags.split(',').map(t => t.trim()).filter(Boolean);
  141. // Get the text being typed after the last comma (for autocomplete filtering)
  142. const currentInput = tags.includes(',')
  143. ? tags.substring(tags.lastIndexOf(',') + 1).trim().toLowerCase()
  144. : tags.trim().toLowerCase();
  145. // Filter suggestions: not already added AND matches current input (if any)
  146. const tagSuggestions = allTags.filter(t =>
  147. !currentTags.includes(t) &&
  148. (currentInput === '' || t.toLowerCase().includes(currentInput))
  149. );
  150. // Add a tag (replaces any partial input with the selected tag)
  151. const addTag = (tag: string) => {
  152. // If there's partial input being typed, replace it with the selected tag
  153. // Otherwise, just append the tag
  154. let baseTags: string[];
  155. if (currentInput && !allTags.includes(currentInput)) {
  156. // User is typing a partial tag - replace it with the selected one
  157. baseTags = tags.includes(',')
  158. ? tags.substring(0, tags.lastIndexOf(',')).split(',').map(t => t.trim()).filter(Boolean)
  159. : [];
  160. } else {
  161. // No partial input or input is already a complete tag - append
  162. baseTags = currentTags;
  163. }
  164. if (!baseTags.includes(tag)) {
  165. const newTags = [...baseTags, tag].join(', ');
  166. setTags(newTags);
  167. }
  168. // Clear any pending blur timeout to prevent hiding suggestions
  169. if (blurTimeoutRef.current !== null) {
  170. clearTimeout(blurTimeoutRef.current);
  171. }
  172. tagInputRef.current?.focus();
  173. };
  174. // Remove a tag
  175. const removeTag = (tagToRemove: string) => {
  176. const newTags = currentTags.filter(t => t !== tagToRemove).join(', ');
  177. setTags(newTags);
  178. };
  179. const updateMutation = useMutation({
  180. mutationFn: (data: Parameters<typeof api.updateArchive>[1]) =>
  181. api.updateArchive(archive.id, data),
  182. onSuccess: () => {
  183. // This form can change the archive's project, so the project detail
  184. // views need refreshing too — not just the overview cards (#2731).
  185. invalidateArchiveAndProjectViews(queryClient);
  186. // Some of what this form writes is mirrored onto the archive's most
  187. // recent run — status and failure reason since #1444, filament grams
  188. // since #1820 — and the Print Log this modal renders at its top reads
  189. // the runs through their own query. Without this it serves the cached
  190. // pre-edit row, so the correction looks like it did not take.
  191. queryClient.invalidateQueries({ queryKey: ['archive-runs', archive.id] });
  192. onClose();
  193. },
  194. });
  195. const handlePhotoUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
  196. const file = e.target.files?.[0];
  197. if (!file) return;
  198. setUploadingPhoto(true);
  199. try {
  200. const result = await api.uploadArchivePhoto(archive.id, file);
  201. setPhotos(result.photos);
  202. queryClient.invalidateQueries({ queryKey: ['archives'] });
  203. } catch (error) {
  204. console.error('Failed to upload photo:', error);
  205. } finally {
  206. setUploadingPhoto(false);
  207. if (photoInputRef.current) {
  208. photoInputRef.current.value = '';
  209. }
  210. }
  211. };
  212. const handlePhotoDelete = async (filename: string) => {
  213. try {
  214. const result = await api.deleteArchivePhoto(archive.id, filename);
  215. setPhotos(result.photos || []);
  216. queryClient.invalidateQueries({ queryKey: ['archives'] });
  217. } catch (error) {
  218. console.error('Failed to delete photo:', error);
  219. }
  220. };
  221. const handleSubmit = (e: React.FormEvent) => {
  222. e.preventDefault();
  223. // Build update data
  224. const updateData: Parameters<typeof api.updateArchive>[1] = {
  225. print_name: printName || undefined,
  226. printer_id: printerId,
  227. project_id: projectId,
  228. notes: notes || undefined,
  229. tags: tags || undefined,
  230. quantity: quantity,
  231. external_url: externalUrl || null,
  232. };
  233. // Only include status if changed
  234. if (status !== archive.status) {
  235. updateData.status = status;
  236. }
  237. // Verdict only when touched, same reasoning as status; '' clears it.
  238. if (userVerdict !== (archive.user_verdict ?? '')) {
  239. updateData.user_verdict = userVerdict === '' ? null : (userVerdict as 'good' | 'reject');
  240. updateData.user_verdict_source = 'dialog';
  241. }
  242. // Sent only when the user actually touched it, so an ordinary save of an
  243. // archive that has its 3MF cannot overwrite the sliced figure with a
  244. // rounded one from the input.
  245. const trimmedGrams = filamentGrams.trim();
  246. const typedGrams = trimmedGrams === '' ? null : Number(trimmedGrams);
  247. // An empty field means "no figure" and clears the stored one; a field that
  248. // holds something unparseable (a lone decimal point, mid-typing) means the
  249. // user is not finished, and must not read as a clear. Clamped here as well
  250. // as on blur because Enter submits without the field losing focus.
  251. const gramsUnparseable = typedGrams !== null && !Number.isFinite(typedGrams);
  252. const parsedGrams = typedGrams === null ? null : Math.min(Math.max(typedGrams, 0), MAX_FILAMENT_GRAMS);
  253. const originalGrams = archive.filament_used_grams ?? null;
  254. if (!gramsUnparseable && parsedGrams !== originalGrams) {
  255. updateData.filament_used_grams = parsedGrams;
  256. }
  257. // Handle failure_reason based on status. A completed-but-rejected print
  258. // (#1898) uses the same field as its reject reason.
  259. if (status === 'failed' || status === 'aborted') {
  260. updateData.failure_reason = failureReason || undefined;
  261. } else if (status === 'completed' && userVerdict === 'reject') {
  262. updateData.failure_reason = failureReason || undefined;
  263. } else if (status === 'completed' && archive.failure_reason) {
  264. // A completed print without a reject carries no reason. A cancelled one
  265. // keeps its own: the machine wrote it ("User cancelled", "No status
  266. // update received") and the dialog has no field to put it back.
  267. updateData.failure_reason = null;
  268. }
  269. updateMutation.mutate(updateData);
  270. };
  271. return (
  272. <div
  273. className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4"
  274. onClick={onClose}
  275. >
  276. <div
  277. className="bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md max-h-[90vh] flex flex-col"
  278. onClick={(e) => e.stopPropagation()}
  279. >
  280. {/* Header */}
  281. <div className="flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary">
  282. <h2 className="text-lg font-semibold text-white">{t('editArchive.title')}</h2>
  283. <button
  284. onClick={onClose}
  285. className="text-bambu-gray hover:text-white transition-colors"
  286. >
  287. <X className="w-5 h-5" />
  288. </button>
  289. </div>
  290. {/* Form */}
  291. <form onSubmit={handleSubmit} className="p-6 space-y-4 overflow-y-auto flex-1">
  292. {/* Print Log — per-run history pulled from PrintLogEntry (#1378). Shown
  293. first so users can see which runs contributed to the aggregate stats. */}
  294. <div>
  295. <label className="block text-sm text-bambu-gray mb-1">{t('archives.runLog.title')}</label>
  296. <PrintLogTable archiveId={archive.id} />
  297. </div>
  298. {/* Print Name */}
  299. <div>
  300. <label className="block text-sm text-bambu-gray mb-1">{t('editArchive.name')}</label>
  301. <input
  302. type="text"
  303. value={printName}
  304. onChange={(e) => setPrintName(e.target.value)}
  305. 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"
  306. placeholder={t('editArchive.namePlaceholder')}
  307. />
  308. </div>
  309. {/* Printer */}
  310. <div>
  311. <label className="block text-sm text-bambu-gray mb-1">{t('editArchive.printer')}</label>
  312. <select
  313. value={printerId ?? ''}
  314. onChange={(e) => setPrinterId(e.target.value ? Number(e.target.value) : null)}
  315. 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"
  316. >
  317. <option value="">{t('editArchive.noPrinter')}</option>
  318. {printers?.map((p) => (
  319. <option key={p.id} value={p.id}>
  320. {p.name}
  321. </option>
  322. ))}
  323. </select>
  324. </div>
  325. {/* Project */}
  326. <div>
  327. <label className="block text-sm text-bambu-gray mb-1">
  328. <FolderKanban className="w-4 h-4 inline mr-1" />
  329. {t('editArchive.project')}
  330. </label>
  331. <select
  332. value={projectId ?? ''}
  333. onChange={(e) => setProjectId(e.target.value ? Number(e.target.value) : null)}
  334. 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"
  335. >
  336. <option value="">{t('editArchive.noProject')}</option>
  337. {projectOptions.map((p) => (
  338. <option key={p.id} value={p.id}>
  339. {p.name}
  340. </option>
  341. ))}
  342. </select>
  343. </div>
  344. {/* Quantity - number of items printed */}
  345. <div>
  346. <label className="block text-sm text-bambu-gray mb-1" htmlFor="archive-items-printed">
  347. <Hash className="w-4 h-4 inline mr-1" />
  348. {t('editArchive.itemsPrinted')}
  349. </label>
  350. <NumberInput
  351. id="archive-items-printed"
  352. min={0}
  353. value={quantity}
  354. // 0 is a real answer, not an empty field: a plate that jammed and
  355. // came off ruined produced nothing, and the project's completed
  356. // count has to be able to say so (#3051).
  357. onChange={setQuantity}
  358. fallback={0}
  359. 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"
  360. placeholder="1"
  361. />
  362. <p className="text-xs text-bambu-gray mt-1">
  363. {t('editArchive.itemsPrintedHelp')}
  364. </p>
  365. </div>
  366. {/* Filament used - the only way to supply a figure for a print that
  367. archived without its 3MF, which no rescan can repair (#1820). */}
  368. <div>
  369. <label className="block text-sm text-bambu-gray mb-1" htmlFor="archive-filament-grams">
  370. <Weight className="w-4 h-4 inline mr-1" />
  371. {t('editArchive.filamentUsed')}
  372. </label>
  373. <input
  374. id="archive-filament-grams"
  375. type="text"
  376. inputMode="decimal"
  377. value={filamentGrams}
  378. // Text rather than number, and filtered on the way in. A number
  379. // input reports an empty string for anything the browser judges
  380. // malformed — including a decimal comma in a locale it doesn't
  381. // expect — which would read here as "the user cleared it" and
  382. // wipe a good figure. Filtering keeps what is displayed and what
  383. // would be sent the same thing, and keeps the value inside the
  384. // range the API accepts: this modal shows nothing at all when a
  385. // save is refused, so it must not be able to send a refusable one.
  386. onChange={(e) => {
  387. const next = e.target.value.replace(',', '.');
  388. if (next === '' || /^\d*\.?\d*$/.test(next)) setFilamentGrams(next);
  389. }}
  390. onBlur={() => setFilamentGrams((current) => {
  391. const parsed = Number(current);
  392. if (current === '' || !Number.isFinite(parsed)) return '';
  393. return String(Math.min(parsed, MAX_FILAMENT_GRAMS));
  394. })}
  395. 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 disabled:opacity-50 disabled:cursor-not-allowed"
  396. placeholder={t('editArchive.filamentUsedPlaceholder')}
  397. disabled={filamentGramsLocked}
  398. />
  399. <p className="text-xs text-bambu-gray mt-1">
  400. {filamentGramsLocked ? t('editArchive.filamentUsedLocked') : t('editArchive.filamentUsedHelp')}
  401. </p>
  402. </div>
  403. {/* Notes */}
  404. <div>
  405. <label className="block text-sm text-bambu-gray mb-1">{t('editArchive.notes')}</label>
  406. <textarea
  407. value={notes}
  408. onChange={(e) => setNotes(e.target.value)}
  409. rows={3}
  410. 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"
  411. placeholder={t('editArchive.notesPlaceholder')}
  412. />
  413. </div>
  414. {/* External Link */}
  415. <div>
  416. <label className="block text-sm text-bambu-gray mb-1">
  417. <Link className="w-4 h-4 inline mr-1" />
  418. {t('editArchive.externalLink')}
  419. </label>
  420. <input
  421. type="url"
  422. value={externalUrl}
  423. onChange={(e) => setExternalUrl(e.target.value)}
  424. 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"
  425. placeholder="https://printables.com/model/..."
  426. />
  427. <p className="text-xs text-bambu-gray mt-1">
  428. {t('editArchive.externalLinkHelp')}
  429. </p>
  430. </div>
  431. {/* Tags */}
  432. <div>
  433. <label className="block text-sm text-bambu-gray mb-1">{t('editArchive.tags')}</label>
  434. {/* Current tags as chips */}
  435. {currentTags.length > 0 && (
  436. <div className="flex flex-wrap gap-1.5 mb-2">
  437. {currentTags.map((tag) => (
  438. <span
  439. key={tag}
  440. className="inline-flex items-center gap-1 px-2 py-0.5 bg-bambu-dark-tertiary rounded text-sm text-white"
  441. >
  442. <Tag className="w-3 h-3" />
  443. {tag}
  444. <button
  445. type="button"
  446. onClick={() => removeTag(tag)}
  447. className="ml-0.5 text-bambu-gray hover:text-white"
  448. >
  449. <X className="w-3 h-3" />
  450. </button>
  451. </span>
  452. ))}
  453. </div>
  454. )}
  455. {/* Tag input with suggestions */}
  456. <div className="relative">
  457. <input
  458. ref={tagInputRef}
  459. type="text"
  460. value={tags}
  461. onChange={(e) => setTags(e.target.value)}
  462. onFocus={() => {
  463. if (blurTimeoutRef.current !== null) {
  464. clearTimeout(blurTimeoutRef.current);
  465. }
  466. setShowTagSuggestions(true);
  467. }}
  468. onBlur={() => {
  469. blurTimeoutRef.current = window.setTimeout(() => setShowTagSuggestions(false), 200);
  470. }}
  471. 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"
  472. placeholder={currentTags.length > 0 ? t('editArchive.addMoreTags') : t('editArchive.tagsPlaceholder')}
  473. />
  474. {/* Suggestions dropdown */}
  475. {showTagSuggestions && tagSuggestions.length > 0 && (
  476. <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">
  477. <div className="p-2 text-xs text-bambu-gray border-b border-bambu-dark-tertiary">
  478. {currentInput ? t('editArchive.matchingTags', { query: currentInput }) : t('editArchive.existingTags')} {t('editArchive.clickToAdd')}
  479. </div>
  480. <div className="p-2 flex flex-wrap gap-1.5">
  481. {tagSuggestions.map((tag) => (
  482. <button
  483. key={tag}
  484. type="button"
  485. onClick={() => addTag(tag)}
  486. 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"
  487. >
  488. {tag}
  489. </button>
  490. ))}
  491. </div>
  492. </div>
  493. )}
  494. </div>
  495. </div>
  496. {/* Status */}
  497. <div>
  498. <label className="block text-sm text-bambu-gray mb-1">{t('editArchive.status')}</label>
  499. <select
  500. value={status}
  501. onChange={(e) => {
  502. setStatus(e.target.value);
  503. // Clear failure reason when changing to completed
  504. if (e.target.value === 'completed') {
  505. setFailureReason('');
  506. }
  507. }}
  508. 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"
  509. >
  510. {/* Any other status (still printing, never printed) is shown as it
  511. is, and is only sent if the user picks an outcome. */}
  512. {archive.status && !ARCHIVE_STATUS_KEYS.includes(archive.status) && (
  513. <option value={archive.status} disabled>
  514. {t(`editArchive.statuses.${archive.status}`, { defaultValue: archive.status })}
  515. </option>
  516. )}
  517. {ARCHIVE_STATUS_KEYS.map((statusKey) => (
  518. <option key={statusKey} value={statusKey}>
  519. {t(`editArchive.statuses.${statusKey}`)}
  520. </option>
  521. ))}
  522. </select>
  523. <p className="text-xs text-bambu-gray mt-1">{t('editArchive.statusHelp')}</p>
  524. </div>
  525. {/* Outcome verdict (#1898) - only meaningful on completed prints */}
  526. {status === 'completed' && (
  527. <div>
  528. <label htmlFor="user-verdict-select" className="block text-sm text-bambu-gray mb-1">
  529. {t('editArchive.userVerdict')}
  530. </label>
  531. <select
  532. id="user-verdict-select"
  533. value={userVerdict}
  534. onChange={(e) => setUserVerdict(e.target.value)}
  535. 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"
  536. >
  537. <option value="">{t('editArchive.verdicts.none')}</option>
  538. <option value="good">{t('editArchive.verdicts.good')}</option>
  539. <option value="reject">{t('editArchive.verdicts.reject')}</option>
  540. </select>
  541. {/* How the stored verdict got here (#1898) — hidden once the
  542. select no longer shows that verdict, since the hint would
  543. then describe an answer the user is replacing. */}
  544. {verdictSourceHintKey && userVerdict === (archive.user_verdict ?? '') && (
  545. <p className="text-xs text-bambu-gray/70 mt-1" data-testid="verdict-source-hint">
  546. {t(verdictSourceHintKey)}
  547. </p>
  548. )}
  549. </div>
  550. )}
  551. {/* Failure Reason - shown for failed/aborted prints and for
  552. completed-but-rejected ones (#1898: the reject reason reuses
  553. this field and vocabulary) */}
  554. {(status === 'failed' || status === 'aborted' || (status === 'completed' && userVerdict === 'reject')) && (
  555. <div>
  556. <label htmlFor="failure-reason-select" className="block text-sm text-bambu-gray mb-1">{t('editArchive.failureReason')}</label>
  557. <select
  558. id="failure-reason-select"
  559. value={failureReason}
  560. onChange={(e) => setFailureReason(e.target.value)}
  561. 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"
  562. >
  563. <option value="">{t('editArchive.selectReason')}</option>
  564. {FAILURE_REASON_KEYS.map((reasonKey) => (
  565. <option key={reasonKey} value={reasonKey}>
  566. {t(`editArchive.failureReasons.${reasonKey}`)}
  567. </option>
  568. ))}
  569. {/* A stored reason outside the vocabulary keeps its own option
  570. so it stays visible and survives a save (issue #2974). */}
  571. {unmappedReason && (
  572. <option value={unmappedReason}>{unmappedReason}</option>
  573. )}
  574. </select>
  575. </div>
  576. )}
  577. {/* Photos */}
  578. <div>
  579. <label className="block text-sm text-bambu-gray mb-1">
  580. <Camera className="w-4 h-4 inline mr-1" />
  581. {t('editArchive.photos')}
  582. </label>
  583. {/* Photo grid */}
  584. <div className="flex flex-wrap gap-2 mb-2">
  585. {photos.map((filename) => (
  586. <div key={filename} className="relative group">
  587. <img
  588. src={api.getArchivePhotoUrl(archive.id, filename)}
  589. alt={t('editArchive.printResult')}
  590. className="w-20 h-20 object-cover rounded-lg border border-bambu-dark-tertiary"
  591. />
  592. <button
  593. type="button"
  594. onClick={() => handlePhotoDelete(filename)}
  595. className="absolute -top-1 -right-1 p-1 bg-red-500 rounded-full can-hover:opacity-0 group-hover:opacity-100 focus-visible:opacity-100 transition-opacity"
  596. >
  597. <Trash2 className="w-3 h-3 text-white" />
  598. </button>
  599. </div>
  600. ))}
  601. {/* Upload button */}
  602. <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">
  603. <input
  604. ref={photoInputRef}
  605. type="file"
  606. accept="image/jpeg,image/png,image/webp"
  607. onChange={handlePhotoUpload}
  608. className="hidden"
  609. disabled={uploadingPhoto}
  610. />
  611. {uploadingPhoto ? (
  612. <Loader2 className="w-6 h-6 text-bambu-gray animate-spin" />
  613. ) : (
  614. <Plus className="w-6 h-6 text-bambu-gray" />
  615. )}
  616. </label>
  617. </div>
  618. <p className="text-xs text-bambu-gray">{t('editArchive.photosHelp')}</p>
  619. </div>
  620. {/* Actions */}
  621. <div className="flex gap-3 pt-2">
  622. <Button
  623. type="button"
  624. variant="secondary"
  625. onClick={onClose}
  626. className="flex-1"
  627. >
  628. {t('common.cancel')}
  629. </Button>
  630. <Button
  631. type="submit"
  632. disabled={updateMutation.isPending}
  633. className="flex-1"
  634. >
  635. <Save className="w-4 h-4" />
  636. {updateMutation.isPending ? t('common.saving') : t('common.save')}
  637. </Button>
  638. </div>
  639. </form>
  640. </div>
  641. </div>
  642. );
  643. }