EditArchiveModal.tsx 29 KB

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