ArchivesPagePrintLogColumns.test.tsx 12 KB

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