ArchivesPagePrintLogColumns.test.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. /**
  2. * Print Log column configuration (#2636, reporter @ajbastien).
  3. *
  4. * The log view hardcoded seven columns, so four populated fields of
  5. * `print_log_entries` — filament used, cost, energy, energy cost — were
  6. * unreachable in the UI even though the API had always returned them. The
  7. * "Filament" column showed only type and colour, which is what made the
  8. * amount look missing: the per-archive Print Log modal has shown grams since
  9. * it was written, so the two surfaces disagreed.
  10. */
  11. import { describe, it, expect, beforeEach, vi } from 'vitest';
  12. import { screen, waitFor, fireEvent, within } from '@testing-library/react';
  13. import userEvent from '@testing-library/user-event';
  14. import { http, HttpResponse } from 'msw';
  15. import { render } from '../utils';
  16. import { server } from '../mocks/server';
  17. import { ArchivesPage } from '../../pages/ArchivesPage';
  18. /** Columns visible out of the box — the seven that shipped before, plus the
  19. * filament amount #2636 asked for. */
  20. const DEFAULT_VISIBLE_COUNT = 8;
  21. const LOG_ENTRIES = [
  22. {
  23. id: 1,
  24. archive_id: 10,
  25. print_name: 'Califlower Calibration',
  26. printer_name: '3DP-00M-191',
  27. printer_id: 1,
  28. status: 'completed',
  29. started_at: '2026-07-24T18:35:00Z',
  30. completed_at: '2026-07-24T19:24:00Z',
  31. duration_seconds: 2940,
  32. filament_type: 'PLA',
  33. filament_color: '#000000',
  34. filament_used_grams: 15.5,
  35. cost: 0.42,
  36. energy_kwh: 0.31,
  37. energy_cost: 0.09,
  38. failure_reason: null,
  39. thumbnail_path: null,
  40. created_by_id: null,
  41. created_by_username: null,
  42. created_at: '2026-07-24T18:35:00Z',
  43. },
  44. ];
  45. /** One archive so the page isn't in its empty state; the log view doesn't
  46. * read it, but the rest of the page does. */
  47. const ONE_ARCHIVE = [
  48. {
  49. id: 10,
  50. filename: 'cali.gcode.3mf',
  51. print_name: 'Califlower',
  52. printer_id: 1,
  53. printer_name: '3DP-00M-191',
  54. print_time_seconds: 2940,
  55. filament_used_grams: 15.5,
  56. status: 'completed',
  57. started_at: '2026-07-24T18:35:00Z',
  58. completed_at: '2026-07-24T19:24:00Z',
  59. thumbnail_path: null,
  60. notes: null,
  61. rating: null,
  62. project_id: null,
  63. project_name: null,
  64. project_color: null,
  65. print_count: 1,
  66. tags: '',
  67. created_at: '2026-07-24T18:00:00Z',
  68. updated_at: '2026-07-24T19:24:00Z',
  69. has_f3d: false,
  70. },
  71. ];
  72. /** Query strings the page asked the log endpoint for, newest last. */
  73. const logRequests: URLSearchParams[] = [];
  74. function mockLog(entries = LOG_ENTRIES, archives: unknown[] = ONE_ARCHIVE) {
  75. server.use(
  76. http.get('/api/v1/archives/', () => HttpResponse.json(archives)),
  77. http.get('/api/v1/archives/stats', () =>
  78. HttpResponse.json({
  79. total_archives: 0,
  80. total_print_time_seconds: 0,
  81. total_filament_grams: 0,
  82. prints_this_week: 0,
  83. prints_this_month: 0,
  84. }),
  85. ),
  86. http.get('/api/v1/archives/tags', () => HttpResponse.json([])),
  87. http.get('/api/v1/print-log/', ({ request }) => {
  88. logRequests.push(new URL(request.url).searchParams);
  89. return HttpResponse.json({ items: entries, total: entries.length });
  90. }),
  91. );
  92. }
  93. /** `setup.ts` replaces localStorage with a no-op vi.fn() stub, so a stored
  94. * config has to be handed to the component through the mock. Keyed on the
  95. * column key alone — the page reads several other keys (view mode, page
  96. * size) and answering those with column JSON would derail the whole page. */
  97. function stubStoredColumns(value: string | null) {
  98. vi.mocked(localStorage.getItem).mockImplementation((key: string) =>
  99. (key === 'bambuddy-printlog-columns' ? value : null),
  100. );
  101. }
  102. /** Switch to the log view — the clipboard icon beside grid / list / calendar. */
  103. async function openLogView() {
  104. render(<ArchivesPage />);
  105. await waitFor(() => expect(screen.getByTitle('Print Log')).toBeInTheDocument());
  106. fireEvent.click(screen.getByTitle('Print Log'));
  107. await waitFor(() => expect(screen.getByText('All Statuses')).toBeInTheDocument());
  108. await waitFor(() => expect(screen.queryByText('No print log entries found')).toBeNull());
  109. }
  110. describe('Print Log columns', () => {
  111. beforeEach(() => {
  112. logRequests.length = 0;
  113. stubStoredColumns(null);
  114. vi.mocked(localStorage.setItem).mockClear();
  115. mockLog();
  116. });
  117. it('shows how much filament the run used, not just which filament', async () => {
  118. await openLogView();
  119. const table = screen.getByRole('table');
  120. // The pre-existing "Filament" column: colour swatch + type.
  121. expect(within(table).getByText('PLA')).toBeInTheDocument();
  122. // The amount, which is what the issue asked for.
  123. expect(within(table).getByText('Filament Used')).toBeInTheDocument();
  124. expect(within(table).getByText('15.5 g')).toBeInTheDocument();
  125. });
  126. it('keeps the optional columns hidden until asked for', async () => {
  127. await openLogView();
  128. // Cost / energy exist on every row but would widen the table for everyone,
  129. // so they ship off. Scoped to the table: "Cost" also appears elsewhere.
  130. const table = screen.getByRole('table');
  131. expect(within(table).queryByText('Cost')).not.toBeInTheDocument();
  132. expect(within(table).queryByText('Energy')).not.toBeInTheDocument();
  133. expect(within(table).queryByText('$0.42')).not.toBeInTheDocument();
  134. });
  135. it('renders a column the user switches on, and remembers it', async () => {
  136. await openLogView();
  137. const user = userEvent.setup();
  138. await user.click(screen.getByRole('button', { name: /Columns/ }));
  139. expect(await screen.findByText('Configure Columns')).toBeInTheDocument();
  140. // Turn on the first hidden column, then apply.
  141. await user.click(screen.getAllByTitle('Show column')[0]);
  142. await user.click(screen.getByRole('button', { name: 'Apply Changes' }));
  143. await waitFor(() => {
  144. expect(localStorage.setItem).toHaveBeenCalledWith(
  145. 'bambuddy-printlog-columns',
  146. expect.any(String),
  147. );
  148. });
  149. const [, written] = vi.mocked(localStorage.setItem).mock.calls.at(-1)!;
  150. const stored = JSON.parse(written as string) as Array<Record<string, unknown>>;
  151. // Labels are deliberately NOT persisted — they are re-derived from t() on
  152. // every render, so a config stored before a language switch can't pin the
  153. // picker to the old language.
  154. expect(Object.keys(stored[0]).sort()).toEqual(['id', 'visible']);
  155. // Whatever was off is now on: the picker's first hidden entry.
  156. expect(stored.filter((c) => c.visible).length).toBeGreaterThan(
  157. DEFAULT_VISIBLE_COUNT,
  158. );
  159. });
  160. it('falls back to defaults when the stored config is unusable', async () => {
  161. // A hand-edited or truncated value must not take the page down with it.
  162. stubStoredColumns('{not json');
  163. await openLogView();
  164. const table = screen.getByRole('table');
  165. expect(within(table).getByText('Filament Used')).toBeInTheDocument();
  166. expect(within(table).getByText('15.5 g')).toBeInTheDocument();
  167. });
  168. it('drops columns that no longer exist and adopts ones added since', async () => {
  169. // An upgrade must neither crash on a removed id nor silently hide a new
  170. // column: the stored order wins, unknown ids go, new defaults append.
  171. stubStoredColumns(
  172. JSON.stringify([
  173. { id: 'date', visible: true },
  174. { id: 'gone_in_a_later_version', visible: true },
  175. ]),
  176. );
  177. await openLogView();
  178. const table = screen.getByRole('table');
  179. expect(within(table).getByText('Date')).toBeInTheDocument();
  180. // Appended from the defaults, with its default visibility.
  181. expect(within(table).getByText('Filament Used')).toBeInTheDocument();
  182. });
  183. it('shows a dash for energy that the background task has not written yet', async () => {
  184. // energy_kwh / energy_cost land via a background task after the row is
  185. // created, so a just-finished print genuinely has none.
  186. stubStoredColumns(
  187. JSON.stringify([
  188. { id: 'print_name', visible: true },
  189. { id: 'energy', visible: true },
  190. ]),
  191. );
  192. // Every other visible cell has a value, so a lone dash can only be energy.
  193. mockLog([{ ...LOG_ENTRIES[0], energy_kwh: null, created_by_username: 'martin' }]);
  194. await openLogView();
  195. const table = screen.getByRole('table');
  196. expect(within(table).getByText('Energy')).toBeInTheDocument();
  197. expect(within(table).getByText('—')).toBeInTheDocument();
  198. expect(within(table).queryByText('0.31 kWh')).not.toBeInTheDocument();
  199. });
  200. it('reaches the log even when there are no archives left', async () => {
  201. // `print_log_entries` outlives the archives it refers to — deleting an
  202. // archive only NULLs the FK, and clearing the log is a separate action.
  203. // The page's "no archives yet" branch used to short-circuit before the
  204. // log branch, so purging archives made the whole Print Log unreachable
  205. // while its rows were still in the database.
  206. mockLog(LOG_ENTRIES, []);
  207. await openLogView();
  208. const table = screen.getByRole('table');
  209. expect(within(table).getByText('Califlower Calibration')).toBeInTheDocument();
  210. expect(within(table).getByText('15.5 g')).toBeInTheDocument();
  211. });
  212. it('sorts on the server, not just the page the browser is holding', async () => {
  213. // The table is paginated server-side, so ordering the 25 rows in hand
  214. // would answer "the priciest print on this page". The click has to reach
  215. // the query.
  216. await openLogView();
  217. logRequests.length = 0;
  218. await userEvent.setup().click(screen.getByRole('button', { name: /Filament Used/ }));
  219. await waitFor(() => expect(logRequests.length).toBeGreaterThan(0));
  220. const last = logRequests[logRequests.length - 1];
  221. expect(last.get('sort_by')).toBe('filament_used');
  222. // Amounts open biggest-first; that is what someone clicking them wants.
  223. expect(last.get('sort_dir')).toBe('desc');
  224. // Back to page 1 — re-sorting from page 3 would otherwise drop the user
  225. // into the middle of a freshly ordered list with no explanation.
  226. expect(last.get('offset')).toBe('0');
  227. });
  228. it('flips direction on a second click of the same column', async () => {
  229. await openLogView();
  230. const user = userEvent.setup();
  231. await user.click(screen.getByRole('button', { name: /Filament Used/ }));
  232. await waitFor(() =>
  233. expect(logRequests[logRequests.length - 1].get('sort_dir')).toBe('desc'),
  234. );
  235. await user.click(screen.getByRole('button', { name: /Filament Used/ }));
  236. await waitFor(() =>
  237. expect(logRequests[logRequests.length - 1].get('sort_dir')).toBe('asc'),
  238. );
  239. expect(logRequests[logRequests.length - 1].get('sort_by')).toBe('filament_used');
  240. });
  241. it('opens text columns A-Z and marks the active header for screen readers', async () => {
  242. await openLogView();
  243. await userEvent.setup().click(screen.getByRole('button', { name: /Printer/ }));
  244. await waitFor(() =>
  245. expect(logRequests[logRequests.length - 1].get('sort_by')).toBe('printer'),
  246. );
  247. expect(logRequests[logRequests.length - 1].get('sort_dir')).toBe('asc');
  248. const header = screen.getByRole('columnheader', { name: /Printer/ });
  249. expect(header).toHaveAttribute('aria-sort', 'ascending');
  250. // Only the active column claims a sort.
  251. expect(screen.getByRole('columnheader', { name: /Status/ })).toHaveAttribute('aria-sort', 'none');
  252. });
  253. it('starts from the stored sort and ignores one naming a dropped column', async () => {
  254. vi.mocked(localStorage.getItem).mockImplementation((key: string) => {
  255. if (key === 'bambuddy-printlog-sort') return JSON.stringify({ column: 'not_a_column', direction: 'asc' });
  256. return null;
  257. });
  258. await openLogView();
  259. // Falls back to the default rather than sending a key the API rejects.
  260. expect(logRequests[0].get('sort_by')).toBe('date');
  261. expect(logRequests[0].get('sort_dir')).toBe('desc');
  262. });
  263. });