EditArchiveModal.test.tsx 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  1. /**
  2. * Tests for the EditArchiveModal component.
  3. */
  4. import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
  5. import { screen, waitFor } from '@testing-library/react';
  6. import userEvent from '@testing-library/user-event';
  7. import { render } from '../utils';
  8. import { EditArchiveModal } from '../../components/EditArchiveModal';
  9. import { http, HttpResponse } from 'msw';
  10. import { server } from '../mocks/server';
  11. import { setAuthToken } from '../../api/client';
  12. const mockArchive = {
  13. id: 1,
  14. filename: 'benchy.gcode.3mf',
  15. print_name: 'Benchy',
  16. printer_id: 1,
  17. printer_name: 'X1 Carbon',
  18. notes: 'Test notes',
  19. rating: 4,
  20. project_id: null,
  21. tags: 'test,calibration',
  22. };
  23. const mockProjects = [
  24. { id: 1, name: 'Functional Parts', color: '#00ae42' },
  25. { id: 2, name: 'Art', color: '#ff5500' },
  26. ];
  27. describe('EditArchiveModal', () => {
  28. const mockOnClose = vi.fn();
  29. const mockOnSave = vi.fn();
  30. beforeEach(() => {
  31. vi.clearAllMocks();
  32. server.use(
  33. http.get('/api/v1/projects/', () => {
  34. return HttpResponse.json(mockProjects);
  35. }),
  36. http.get('/api/v1/archives/tags', () => {
  37. return HttpResponse.json([
  38. { name: 'test', count: 2 },
  39. { name: 'calibration', count: 1 },
  40. { name: 'functional', count: 3 },
  41. ]);
  42. }),
  43. http.patch('/api/v1/archives/:id', async ({ request }) => {
  44. const body = await request.json();
  45. return HttpResponse.json({ ...mockArchive, ...body });
  46. })
  47. );
  48. });
  49. describe('rendering', () => {
  50. it('renders the modal title', () => {
  51. render(
  52. <EditArchiveModal
  53. archive={mockArchive}
  54. onClose={mockOnClose}
  55. onSave={mockOnSave}
  56. />
  57. );
  58. expect(screen.getByText(/edit/i)).toBeInTheDocument();
  59. });
  60. it('shows print name field', async () => {
  61. render(
  62. <EditArchiveModal
  63. archive={mockArchive}
  64. onClose={mockOnClose}
  65. onSave={mockOnSave}
  66. />
  67. );
  68. await waitFor(() => {
  69. // Name field should be present
  70. const nameInput = screen.getByDisplayValue('Benchy');
  71. expect(nameInput).toBeInTheDocument();
  72. });
  73. });
  74. it('shows notes field', async () => {
  75. render(
  76. <EditArchiveModal
  77. archive={mockArchive}
  78. onClose={mockOnClose}
  79. onSave={mockOnSave}
  80. />
  81. );
  82. await waitFor(() => {
  83. const notesField = screen.getByDisplayValue('Test notes');
  84. expect(notesField).toBeInTheDocument();
  85. });
  86. });
  87. it('shows rating selector', async () => {
  88. render(
  89. <EditArchiveModal
  90. archive={mockArchive}
  91. onClose={mockOnClose}
  92. onSave={mockOnSave}
  93. />
  94. );
  95. await waitFor(() => {
  96. // Rating may be shown as stars or dropdown
  97. expect(screen.getByText(/edit/i)).toBeInTheDocument();
  98. });
  99. });
  100. it('shows project selector', async () => {
  101. render(
  102. <EditArchiveModal
  103. archive={mockArchive}
  104. onClose={mockOnClose}
  105. onSave={mockOnSave}
  106. />
  107. );
  108. await waitFor(() => {
  109. // Project section should be present
  110. expect(screen.getByText(/edit/i)).toBeInTheDocument();
  111. });
  112. });
  113. it('shows tags input', () => {
  114. render(
  115. <EditArchiveModal
  116. archive={mockArchive}
  117. onClose={mockOnClose}
  118. onSave={mockOnSave}
  119. />
  120. );
  121. expect(screen.getByText(/tags/i)).toBeInTheDocument();
  122. });
  123. });
  124. describe('existing values', () => {
  125. it('shows existing tags', () => {
  126. render(
  127. <EditArchiveModal
  128. archive={mockArchive}
  129. onClose={mockOnClose}
  130. onSave={mockOnSave}
  131. />
  132. );
  133. expect(screen.getByText('test')).toBeInTheDocument();
  134. expect(screen.getByText('calibration')).toBeInTheDocument();
  135. });
  136. });
  137. describe('actions', () => {
  138. it('has save button', () => {
  139. render(
  140. <EditArchiveModal
  141. archive={mockArchive}
  142. onClose={mockOnClose}
  143. onSave={mockOnSave}
  144. />
  145. );
  146. expect(screen.getByRole('button', { name: /save/i })).toBeInTheDocument();
  147. });
  148. it('has cancel button', () => {
  149. render(
  150. <EditArchiveModal
  151. archive={mockArchive}
  152. onClose={mockOnClose}
  153. onSave={mockOnSave}
  154. />
  155. );
  156. expect(screen.getByRole('button', { name: /cancel/i })).toBeInTheDocument();
  157. });
  158. it('calls onClose when cancel is clicked', async () => {
  159. const user = userEvent.setup();
  160. render(
  161. <EditArchiveModal
  162. archive={mockArchive}
  163. onClose={mockOnClose}
  164. onSave={mockOnSave}
  165. />
  166. );
  167. await user.click(screen.getByRole('button', { name: /cancel/i }));
  168. expect(mockOnClose).toHaveBeenCalled();
  169. });
  170. it('can edit print name', async () => {
  171. const user = userEvent.setup();
  172. render(
  173. <EditArchiveModal
  174. archive={mockArchive}
  175. onClose={mockOnClose}
  176. onSave={mockOnSave}
  177. />
  178. );
  179. const nameInput = screen.getByDisplayValue('Benchy');
  180. await user.clear(nameInput);
  181. await user.type(nameInput, 'New Name');
  182. expect(nameInput).toHaveValue('New Name');
  183. });
  184. });
  185. describe('failure_reason vocabulary (#1687 follow-up)', () => {
  186. // The Stats page's Failure Analysis widget groups by the raw column value.
  187. // Before this fix this modal saved the translated label, so a language
  188. // switch fragmented historical buckets and any round-trip through the
  189. // new PATCH /print-log endpoint (which validates against camelCase keys)
  190. // would reject the value. The dropdown now saves the key.
  191. const failedArchive = { ...mockArchive, status: 'failed', failure_reason: 'filamentRunout' };
  192. const legacyArchive = { ...mockArchive, status: 'failed', failure_reason: 'Filament runout' };
  193. it('preselects the option when the stored value is already a camelCase key', () => {
  194. render(<EditArchiveModal archive={failedArchive} onClose={mockOnClose} onSave={mockOnSave} />);
  195. const select = screen.getByLabelText(/failure reason/i) as HTMLSelectElement;
  196. expect(select.value).toBe('filamentRunout');
  197. });
  198. it('reverse-looks-up a legacy translated value back to its key', () => {
  199. render(<EditArchiveModal archive={legacyArchive} onClose={mockOnClose} onSave={mockOnSave} />);
  200. const select = screen.getByLabelText(/failure reason/i) as HTMLSelectElement;
  201. expect(select.value).toBe('filamentRunout');
  202. });
  203. it('sends the camelCase key on save, not the translated label', async () => {
  204. const user = userEvent.setup();
  205. let patched: { failure_reason?: string } | undefined;
  206. server.use(
  207. http.patch('/api/v1/archives/:id', async ({ request }) => {
  208. patched = (await request.json()) as { failure_reason?: string };
  209. return HttpResponse.json({ ...failedArchive, ...patched });
  210. }),
  211. );
  212. render(<EditArchiveModal archive={failedArchive} onClose={mockOnClose} onSave={mockOnSave} />);
  213. const select = screen.getByLabelText(/failure reason/i);
  214. await user.selectOptions(select, 'cloggedNozzle');
  215. await user.click(screen.getByRole('button', { name: /save/i }));
  216. await waitFor(() => {
  217. expect(patched?.failure_reason).toBe('cloggedNozzle');
  218. });
  219. });
  220. // A value outside the vocabulary used to initialise the dropdown to '',
  221. // and saving from that state wrote the empty selection over the stored
  222. // text -- opening the editor and pressing Save destroyed the
  223. // classification. The startup migration folds every known spelling onto a
  224. // key, so what reaches here is genuinely unrecognisable text; it has to
  225. // survive rather than be silently discarded (issue #2974).
  226. const freeTextArchive = {
  227. ...mockArchive,
  228. status: 'failed',
  229. failure_reason: 'Custom legacy reason',
  230. };
  231. it('keeps a stored value it cannot map, as its own option', () => {
  232. render(<EditArchiveModal archive={freeTextArchive} onClose={mockOnClose} onSave={mockOnSave} />);
  233. const select = screen.getByLabelText(/failure reason/i) as HTMLSelectElement;
  234. expect(select.value).toBe('Custom legacy reason');
  235. expect(
  236. screen.getByRole('option', { name: 'Custom legacy reason' }),
  237. ).toBeInTheDocument();
  238. });
  239. it('does not clear an unmappable reason on an untouched save', async () => {
  240. const user = userEvent.setup();
  241. let patched: { failure_reason?: string } | undefined;
  242. server.use(
  243. http.patch('/api/v1/archives/:id', async ({ request }) => {
  244. patched = (await request.json()) as { failure_reason?: string };
  245. return HttpResponse.json({ ...freeTextArchive, ...patched });
  246. }),
  247. );
  248. render(<EditArchiveModal archive={freeTextArchive} onClose={mockOnClose} onSave={mockOnSave} />);
  249. await user.click(screen.getByRole('button', { name: /save/i }));
  250. await waitFor(() => {
  251. expect(patched?.failure_reason).toBe('Custom legacy reason');
  252. });
  253. });
  254. it('offers the stale-path reason the backend now writes', () => {
  255. // Both stale writers in main.py store `noStatusUpdate`. If it were
  256. // missing from the dropdown the editor would treat it as unmappable and
  257. // show the raw key to the user instead of a translated label.
  258. const staleArchive = {
  259. ...mockArchive,
  260. status: 'failed',
  261. failure_reason: 'noStatusUpdate',
  262. };
  263. render(<EditArchiveModal archive={staleArchive} onClose={mockOnClose} onSave={mockOnSave} />);
  264. const select = screen.getByLabelText(/failure reason/i) as HTMLSelectElement;
  265. expect(select.value).toBe('noStatusUpdate');
  266. expect(
  267. screen.getByRole('option', { name: 'No status update received' }),
  268. ).toBeInTheDocument();
  269. });
  270. });
  271. describe('status', () => {
  272. function patchSpy() {
  273. const seen: { body?: Record<string, unknown> } = {};
  274. server.use(
  275. http.patch('/api/v1/archives/:id', async ({ request }) => {
  276. seen.body = (await request.json()) as Record<string, unknown>;
  277. return HttpResponse.json({ ...mockArchive, ...seen.body });
  278. }),
  279. );
  280. return seen;
  281. }
  282. const statusSelect = () =>
  283. (screen.getAllByRole('combobox') as HTMLSelectElement[]).find((select) =>
  284. Array.from(select.options).some((option) => option.value === 'cancelled'),
  285. )!;
  286. it('offers the finished outcomes, cancelled and aborted apart', () => {
  287. render(<EditArchiveModal archive={{ ...mockArchive, status: 'completed' }} onClose={mockOnClose} onSave={mockOnSave} />);
  288. const options = Array.from(statusSelect().options).map((o) => [o.value, o.textContent]);
  289. expect(options).toEqual([
  290. ['completed', 'Completed'],
  291. ['failed', 'Failed'],
  292. ['aborted', 'Aborted'],
  293. ['cancelled', 'Cancelled'],
  294. ]);
  295. });
  296. it('opens a cancelled archive as cancelled', () => {
  297. render(<EditArchiveModal archive={{ ...mockArchive, status: 'cancelled' }} onClose={mockOnClose} onSave={mockOnSave} />);
  298. expect(statusSelect().value).toBe('cancelled');
  299. });
  300. it('shows a printing archive as it is and leaves it out of an untouched save', async () => {
  301. const user = userEvent.setup();
  302. const seen = patchSpy();
  303. render(<EditArchiveModal archive={{ ...mockArchive, status: 'printing' }} onClose={mockOnClose} onSave={mockOnSave} />);
  304. const current = Array.from(statusSelect().options).find((o) => o.value === 'printing');
  305. expect(current?.disabled).toBe(true);
  306. await user.click(screen.getByRole('button', { name: /save/i }));
  307. await waitFor(() => expect(seen.body).toBeDefined());
  308. expect(seen.body).not.toHaveProperty('status');
  309. });
  310. it('keeps the recorded reason when an aborted print is moved to cancelled', async () => {
  311. const user = userEvent.setup();
  312. const seen = patchSpy();
  313. render(<EditArchiveModal archive={{ ...mockArchive, status: 'aborted', failure_reason: 'userCancelled' }} onClose={mockOnClose} onSave={mockOnSave} />);
  314. await user.selectOptions(statusSelect(), 'cancelled');
  315. await user.click(screen.getByRole('button', { name: /save/i }));
  316. await waitFor(() => expect(seen.body?.status).toBe('cancelled'));
  317. expect(seen.body).not.toHaveProperty('failure_reason');
  318. });
  319. it('clears the reason of a cancelled print marked completed', async () => {
  320. const user = userEvent.setup();
  321. const seen = patchSpy();
  322. render(<EditArchiveModal archive={{ ...mockArchive, status: 'cancelled', failure_reason: 'noStatusUpdate' }} onClose={mockOnClose} onSave={mockOnSave} />);
  323. await user.selectOptions(statusSelect(), 'completed');
  324. await user.click(screen.getByRole('button', { name: /save/i }));
  325. await waitFor(() => expect(seen.body?.status).toBe('completed'));
  326. expect(seen.body?.failure_reason).toBeNull();
  327. });
  328. it('sends cancelled when cancelled is chosen', async () => {
  329. const user = userEvent.setup();
  330. const seen = patchSpy();
  331. render(<EditArchiveModal archive={{ ...mockArchive, status: 'failed' }} onClose={mockOnClose} onSave={mockOnSave} />);
  332. await user.selectOptions(statusSelect(), 'cancelled');
  333. await user.click(screen.getByRole('button', { name: /save/i }));
  334. await waitFor(() => expect(seen.body?.status).toBe('cancelled'));
  335. });
  336. });
  337. describe('filament grams (#1820)', () => {
  338. // A print archived without its 3MF carries no weight at all, and nothing
  339. // can supply one — there is no file to read. Typing it here is the only
  340. // route, so the field has to reach the API, and an untouched save must not
  341. // overwrite a figure that came from a real slice.
  342. function patchSpy() {
  343. const seen: { body?: Record<string, unknown> } = {};
  344. server.use(
  345. http.patch('/api/v1/archives/:id', async ({ request }) => {
  346. seen.body = (await request.json()) as Record<string, unknown>;
  347. return HttpResponse.json({ ...mockArchive, ...seen.body });
  348. }),
  349. );
  350. return seen;
  351. }
  352. describe('without the right to edit every archive', () => {
  353. let meServed = false;
  354. const signInWith = (me: Record<string, unknown>) => {
  355. meServed = false;
  356. setAuthToken('own-archives-token', 'session');
  357. server.use(
  358. http.get('*/api/v1/auth/status', () => HttpResponse.json({ auth_enabled: true, requires_setup: false })),
  359. http.get('/api/v1/auth/me', () => {
  360. meServed = true;
  361. return HttpResponse.json({
  362. id: 7,
  363. username: 'owner',
  364. is_active: true,
  365. groups: [],
  366. created_at: '2026-10-16T00:00:00Z',
  367. ...me,
  368. });
  369. }),
  370. );
  371. };
  372. const owner = { is_admin: false, permissions: ['archives:read_own', 'archives:update_own'] };
  373. afterEach(() => {
  374. setAuthToken(null);
  375. });
  376. it('cannot change a weight the archive already has', async () => {
  377. signInWith(owner);
  378. render(<EditArchiveModal archive={{ ...mockArchive, filament_used_grams: 50 }} onClose={mockOnClose} onSave={mockOnSave} />);
  379. await waitFor(() => expect(screen.getByLabelText(/filament used/i)).toBeDisabled());
  380. expect(screen.getByText(/only users who can edit all archives can change this figure/i)).toBeInTheDocument();
  381. });
  382. it('cannot fill in the weight of an archive that has its 3MF', async () => {
  383. signInWith(owner);
  384. render(<EditArchiveModal archive={{ ...mockArchive, file_path: 'archive/1/benchy.gcode.3mf' }} onClose={mockOnClose} onSave={mockOnSave} />);
  385. await waitFor(() => expect(screen.getByLabelText(/filament used/i)).toBeDisabled());
  386. });
  387. it('can fill in the weight of an archive without its 3MF', async () => {
  388. signInWith(owner);
  389. render(<EditArchiveModal archive={{ ...mockArchive, file_path: '' }} onClose={mockOnClose} onSave={mockOnSave} />);
  390. await waitFor(() => expect(meServed).toBe(true));
  391. await new Promise((resolve) => setTimeout(resolve, 0));
  392. expect(screen.getByLabelText(/filament used/i)).toBeEnabled();
  393. });
  394. it('stays editable for an admin', async () => {
  395. signInWith({ is_admin: true, permissions: [] });
  396. render(<EditArchiveModal archive={{ ...mockArchive, filament_used_grams: 50 }} onClose={mockOnClose} onSave={mockOnSave} />);
  397. await waitFor(() => expect(meServed).toBe(true));
  398. await new Promise((resolve) => setTimeout(resolve, 0));
  399. expect(screen.getByLabelText(/filament used/i)).toBeEnabled();
  400. });
  401. });
  402. it('sends a figure typed for an archive that has none', async () => {
  403. const user = userEvent.setup();
  404. const seen = patchSpy();
  405. render(<EditArchiveModal archive={mockArchive} onClose={mockOnClose} onSave={mockOnSave} />);
  406. await user.type(screen.getByLabelText(/filament used/i), '46.16');
  407. await user.click(screen.getByRole('button', { name: /save/i }));
  408. await waitFor(() => {
  409. expect(seen.body?.filament_used_grams).toBe(46.16);
  410. });
  411. });
  412. it('leaves the field out of a save that did not touch it', async () => {
  413. const user = userEvent.setup();
  414. const seen = patchSpy();
  415. const weighed = { ...mockArchive, filament_used_grams: 50 };
  416. render(<EditArchiveModal archive={weighed} onClose={mockOnClose} onSave={mockOnSave} />);
  417. await user.click(screen.getByRole('button', { name: /save/i }));
  418. await waitFor(() => {
  419. expect(seen.body).toBeDefined();
  420. });
  421. expect(seen.body).not.toHaveProperty('filament_used_grams');
  422. });
  423. it('accepts a decimal comma, which a number input would have swallowed', async () => {
  424. const user = userEvent.setup();
  425. const seen = patchSpy();
  426. render(<EditArchiveModal archive={mockArchive} onClose={mockOnClose} onSave={mockOnSave} />);
  427. await user.type(screen.getByLabelText(/filament used/i), '46,16');
  428. await user.click(screen.getByRole('button', { name: /save/i }));
  429. await waitFor(() => {
  430. expect(seen.body?.filament_used_grams).toBe(46.16);
  431. });
  432. });
  433. it('refuses characters that could never reach the API as a number', async () => {
  434. const user = userEvent.setup();
  435. render(<EditArchiveModal archive={mockArchive} onClose={mockOnClose} onSave={mockOnSave} />);
  436. const field = screen.getByLabelText(/filament used/i) as HTMLInputElement;
  437. await user.type(field, '4a6-1..2');
  438. expect(field.value).toBe('461.2');
  439. });
  440. it('clamps to the bound the API enforces, so a save cannot be refused', async () => {
  441. const user = userEvent.setup();
  442. const seen = patchSpy();
  443. render(<EditArchiveModal archive={mockArchive} onClose={mockOnClose} onSave={mockOnSave} />);
  444. await user.type(screen.getByLabelText(/filament used/i), '999999');
  445. await user.click(screen.getByRole('button', { name: /save/i }));
  446. await waitFor(() => {
  447. expect(seen.body?.filament_used_grams).toBe(100000);
  448. });
  449. });
  450. it('does not read a half-typed value as a clear', async () => {
  451. // Enter submits without the field ever losing focus, so the blur-time
  452. // tidy-up has not run and the state still holds what was typed.
  453. const user = userEvent.setup();
  454. const seen = patchSpy();
  455. const weighed = { ...mockArchive, filament_used_grams: 50 };
  456. render(<EditArchiveModal archive={weighed} onClose={mockOnClose} onSave={mockOnSave} />);
  457. const field = screen.getByLabelText(/filament used/i);
  458. await user.clear(field);
  459. await user.type(field, '.{Enter}');
  460. await waitFor(() => {
  461. expect(seen.body).toBeDefined();
  462. });
  463. expect(seen.body).not.toHaveProperty('filament_used_grams');
  464. });
  465. it('refreshes the print log, which the mirrored figure lands in', async () => {
  466. const user = userEvent.setup();
  467. let runFetches = 0;
  468. server.use(
  469. http.get('/api/v1/archives/:id/runs', () => {
  470. runFetches += 1;
  471. return HttpResponse.json({ items: [], total: 0 });
  472. }),
  473. );
  474. render(<EditArchiveModal archive={mockArchive} onClose={mockOnClose} onSave={mockOnSave} />);
  475. await waitFor(() => expect(runFetches).toBe(1));
  476. await user.type(screen.getByLabelText(/filament used/i), '46.16');
  477. await user.click(screen.getByRole('button', { name: /save/i }));
  478. // Without the invalidation the table keeps serving its cached rows, so
  479. // the run the edit just corrected still shows the old figure.
  480. await waitFor(() => expect(runFetches).toBe(2));
  481. });
  482. it('clears the figure when the field is emptied', async () => {
  483. const user = userEvent.setup();
  484. const seen = patchSpy();
  485. const weighed = { ...mockArchive, filament_used_grams: 50 };
  486. render(<EditArchiveModal archive={weighed} onClose={mockOnClose} onSave={mockOnSave} />);
  487. await user.clear(screen.getByLabelText(/filament used/i));
  488. await user.click(screen.getByRole('button', { name: /save/i }));
  489. await waitFor(() => {
  490. expect(seen.body?.filament_used_grams).toBeNull();
  491. });
  492. });
  493. });
  494. describe('project picker (#2888)', () => {
  495. // Statuses matter here, so this describe brings its own list rather than
  496. // the bare one the rest of the file shares.
  497. const withStatuses = (rows: Array<Record<string, unknown>>) =>
  498. server.use(http.get('/api/v1/projects/', () => HttpResponse.json(rows)));
  499. function savedBody() {
  500. const seen: { body?: Record<string, unknown> } = {};
  501. server.use(
  502. http.patch('/api/v1/archives/:id', async ({ request }) => {
  503. seen.body = (await request.json()) as Record<string, unknown>;
  504. return HttpResponse.json({ ...mockArchive, ...seen.body });
  505. }),
  506. );
  507. return seen;
  508. }
  509. it('leaves archived projects out of the list', async () => {
  510. withStatuses([
  511. { id: 1, name: 'Live Work', color: '#00ae42', status: 'active' },
  512. { id: 2, name: 'Last Year', color: '#888888', status: 'archived' },
  513. ]);
  514. render(<EditArchiveModal archive={mockArchive} onClose={mockOnClose} onSave={mockOnSave} />);
  515. await screen.findByRole('option', { name: 'Live Work' });
  516. expect(screen.queryByRole('option', { name: 'Last Year' })).not.toBeInTheDocument();
  517. });
  518. it('keeps completed projects, which are still worth filing a reprint under', async () => {
  519. withStatuses([
  520. { id: 1, name: 'Live Work', color: '#00ae42', status: 'active' },
  521. { id: 3, name: 'Shipped', color: '#888888', status: 'completed' },
  522. ]);
  523. render(<EditArchiveModal archive={mockArchive} onClose={mockOnClose} onSave={mockOnSave} />);
  524. expect(await screen.findByRole('option', { name: 'Shipped' })).toBeInTheDocument();
  525. });
  526. it('still offers the archived project this archive is already in', async () => {
  527. // Filtered out, the select holds a value no option matches, and the
  528. // browser resets it to the first option -- "No project". The archive
  529. // would say it is filed nowhere while sitting in a project.
  530. withStatuses([
  531. { id: 1, name: 'Live Work', color: '#00ae42', status: 'active' },
  532. { id: 2, name: 'Last Year', color: '#888888', status: 'archived' },
  533. ]);
  534. const filed = { ...mockArchive, project_id: 2 };
  535. render(<EditArchiveModal archive={filed} onClose={mockOnClose} onSave={mockOnSave} />);
  536. const option = await screen.findByRole('option', { name: 'Last Year' });
  537. expect((option as HTMLOptionElement).selected).toBe(true);
  538. });
  539. it('saves the project it was already in when nothing else is touched', async () => {
  540. const user = userEvent.setup();
  541. const seen = savedBody();
  542. withStatuses([{ id: 2, name: 'Last Year', color: '#888888', status: 'archived' }]);
  543. render(
  544. <EditArchiveModal
  545. archive={{ ...mockArchive, project_id: 2 }}
  546. onClose={mockOnClose}
  547. onSave={mockOnSave}
  548. />,
  549. );
  550. await screen.findByRole('option', { name: 'Last Year' });
  551. await user.click(screen.getByRole('button', { name: /save/i }));
  552. // The stored id survives the round trip untouched: showing the archived
  553. // project is what makes the field honest, and it must not also change
  554. // what an untouched save writes.
  555. await waitFor(() => expect(seen.body?.project_id).toBe(2));
  556. });
  557. });
  558. describe('items printed (#3051)', () => {
  559. // A plate that jammed and came off ruined produced nothing, even when the
  560. // printer called the job a success. The project's completed-items count
  561. // sums this column, so 0 has to be typeable.
  562. function patchSpy() {
  563. const seen: { body?: Record<string, unknown> } = {};
  564. server.use(
  565. http.patch('/api/v1/archives/:id', async ({ request }) => {
  566. seen.body = (await request.json()) as Record<string, unknown>;
  567. return HttpResponse.json({ ...mockArchive, ...seen.body });
  568. }),
  569. );
  570. return seen;
  571. }
  572. it('sends 0 for a plate that produced nothing', async () => {
  573. const user = userEvent.setup();
  574. const seen = patchSpy();
  575. render(
  576. <EditArchiveModal
  577. archive={{ ...mockArchive, quantity: 4 }}
  578. onClose={mockOnClose}
  579. onSave={mockOnSave}
  580. />,
  581. );
  582. const field = screen.getByLabelText(/items printed/i) as HTMLInputElement;
  583. await user.clear(field);
  584. await user.type(field, '0');
  585. await user.click(screen.getByRole('button', { name: /save/i }));
  586. await waitFor(() => expect(seen.body?.quantity).toBe(0));
  587. });
  588. it('does not floor a cleared field back to 1', async () => {
  589. const user = userEvent.setup();
  590. render(
  591. <EditArchiveModal
  592. archive={{ ...mockArchive, quantity: 4 }}
  593. onClose={mockOnClose}
  594. onSave={mockOnSave}
  595. />,
  596. );
  597. const field = screen.getByLabelText(/items printed/i) as HTMLInputElement;
  598. await user.clear(field);
  599. // Empty while editing (#3182), and 0 rather than 1 once the field is left.
  600. expect(field.value).toBe('');
  601. await user.tab();
  602. expect(field.value).toBe('0');
  603. });
  604. it('still refuses a negative count', async () => {
  605. const user = userEvent.setup();
  606. const seen = patchSpy();
  607. render(
  608. <EditArchiveModal
  609. archive={{ ...mockArchive, quantity: 4 }}
  610. onClose={mockOnClose}
  611. onSave={mockOnSave}
  612. />,
  613. );
  614. const field = screen.getByLabelText(/items printed/i) as HTMLInputElement;
  615. await user.clear(field);
  616. await user.type(field, '-3');
  617. await user.click(screen.getByRole('button', { name: /save/i }));
  618. expect(field.value).toBe('0');
  619. await waitFor(() => expect(seen.body?.quantity).toBe(0));
  620. });
  621. });
  622. // Post-print outcome confirmation (#1898)
  623. describe('outcome verdict source', () => {
  624. const completed = {
  625. ...mockArchive,
  626. status: 'completed',
  627. user_verdict: 'good',
  628. confirm_requested: true,
  629. };
  630. it('explains a verdict the plate-clear default recorded', () => {
  631. render(
  632. <EditArchiveModal
  633. archive={{ ...completed, user_verdict_source: 'plate_clear' }}
  634. onClose={mockOnClose}
  635. onSave={mockOnSave}
  636. />,
  637. );
  638. expect(screen.getByTestId('verdict-source-hint')).toHaveTextContent(
  639. 'Recorded when the plate was cleared.',
  640. );
  641. });
  642. it('shows no hint for a verdict with no recorded source', () => {
  643. render(
  644. <EditArchiveModal
  645. archive={{ ...completed, user_verdict_source: null }}
  646. onClose={mockOnClose}
  647. onSave={mockOnSave}
  648. />,
  649. );
  650. expect(screen.queryByTestId('verdict-source-hint')).not.toBeInTheDocument();
  651. });
  652. it('stamps the dialog as the source when the verdict is changed here', async () => {
  653. const user = userEvent.setup();
  654. let seen: Record<string, unknown> | null = null;
  655. server.use(
  656. http.patch('/api/v1/archives/:id', async ({ request }) => {
  657. seen = (await request.json()) as Record<string, unknown>;
  658. return HttpResponse.json({ ...completed, ...seen });
  659. }),
  660. );
  661. render(
  662. <EditArchiveModal
  663. archive={{ ...completed, user_verdict_source: 'plate_clear' }}
  664. onClose={mockOnClose}
  665. onSave={mockOnSave}
  666. />,
  667. );
  668. await user.selectOptions(screen.getByLabelText(/outcome verdict/i), 'reject');
  669. await user.click(screen.getByRole('button', { name: /save/i }));
  670. await waitFor(() => expect(seen).not.toBeNull());
  671. expect(seen!.user_verdict).toBe('reject');
  672. expect(seen!.user_verdict_source).toBe('dialog');
  673. });
  674. });
  675. describe('failure_reason on a machine status the dropdown cannot show', () => {
  676. // The reject reason (#1898) reuses failure_reason, so the clearing branch
  677. // grew "|| archive.failure_reason" to drop it when the verdict goes away.
  678. // That clause also catches a 'cancelled' archive: print_queue writes
  679. // status 'cancelled' with "Stopped by user (printer was offline)" when a
  680. // stop is issued to an offline printer, the status dropdown has no
  681. // 'cancelled' option, and so opening the editor and pressing Save with
  682. // nothing touched wiped a reason the user could not put back.
  683. const cancelled = {
  684. ...mockArchive,
  685. status: 'cancelled',
  686. failure_reason: 'Stopped by user (printer was offline)',
  687. user_verdict: null,
  688. };
  689. it('keeps the machine-written reason on an untouched save', async () => {
  690. const user = userEvent.setup();
  691. let seen: Record<string, unknown> | null = null;
  692. server.use(
  693. http.patch('/api/v1/archives/:id', async ({ request }) => {
  694. seen = (await request.json()) as Record<string, unknown>;
  695. return HttpResponse.json({ ...cancelled, ...seen });
  696. }),
  697. );
  698. render(<EditArchiveModal archive={cancelled} onClose={mockOnClose} onSave={mockOnSave} />);
  699. await user.click(screen.getByRole('button', { name: /save/i }));
  700. await waitFor(() => expect(seen).not.toBeNull());
  701. expect(seen!).not.toHaveProperty('failure_reason');
  702. });
  703. it('still drops the reason when a reject verdict is taken back', async () => {
  704. // The behaviour the clause was written for, on the archive it was
  705. // written for: a completed print whose reject reason no longer applies.
  706. const user = userEvent.setup();
  707. let seen: Record<string, unknown> | null = null;
  708. const rejected = {
  709. ...mockArchive,
  710. status: 'completed',
  711. user_verdict: 'reject',
  712. failure_reason: 'warping',
  713. };
  714. server.use(
  715. http.patch('/api/v1/archives/:id', async ({ request }) => {
  716. seen = (await request.json()) as Record<string, unknown>;
  717. return HttpResponse.json({ ...rejected, ...seen });
  718. }),
  719. );
  720. render(<EditArchiveModal archive={rejected} onClose={mockOnClose} onSave={mockOnSave} />);
  721. await user.selectOptions(screen.getByLabelText(/outcome verdict/i), 'good');
  722. await user.click(screen.getByRole('button', { name: /save/i }));
  723. await waitFor(() => expect(seen).not.toBeNull());
  724. expect(seen!.failure_reason).toBeNull();
  725. });
  726. });
  727. });