PrintModal.test.tsx 115 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139
  1. /**
  2. * Tests for the unified PrintModal component.
  3. *
  4. * The PrintModal supports two modes:
  5. * - 'create': Create a print queue item
  6. * - 'edit-queue-item': Edit existing queue item (single printer)
  7. */
  8. import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
  9. import type React from 'react';
  10. import { screen, waitFor, fireEvent, within, render as rtlRender } from '@testing-library/react';
  11. import userEvent from '@testing-library/user-event';
  12. import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
  13. import { BrowserRouter } from 'react-router-dom';
  14. import { render } from '../utils';
  15. import { PrintModal } from '../../components/PrintModal';
  16. import { AuthProvider } from '../../contexts/AuthContext';
  17. import { ThemeProvider } from '../../contexts/ThemeContext';
  18. import { ToastProvider } from '../../contexts/ToastContext';
  19. import { http, HttpResponse } from 'msw';
  20. import { setAuthToken } from '../../api/client';
  21. import { server } from '../mocks/server';
  22. import { setColorCatalog, __resetColorCatalogForTests } from '../../utils/colors';
  23. import type { PrintQueueItem } from '../../api/client';
  24. const mockPrinters = [
  25. { id: 1, name: 'X1 Carbon', model: 'X1C', ip_address: '192.168.1.100', enabled: true, is_active: true },
  26. { id: 2, name: 'P1S', model: 'P1S', ip_address: '192.168.1.101', enabled: true, is_active: true },
  27. { id: 3, name: 'A1 Mini', model: 'A1M', ip_address: '192.168.1.102', enabled: true, is_active: true },
  28. ];
  29. const createMockQueueItem = (overrides: Partial<PrintQueueItem> = {}): PrintQueueItem => ({
  30. id: 1,
  31. printer_id: 1,
  32. archive_id: 1,
  33. position: 1,
  34. scheduled_time: null,
  35. require_previous_success: false,
  36. auto_off_after: false,
  37. gcode_injection: false,
  38. manual_start: false,
  39. ams_mapping: null,
  40. plate_id: null,
  41. bed_levelling: 'on',
  42. flow_cali: 'off',
  43. vibration_cali: true,
  44. layer_inspect: false,
  45. timelapse: false,
  46. use_ams: true,
  47. status: 'pending',
  48. started_at: null,
  49. completed_at: null,
  50. error_message: null,
  51. created_at: '2024-01-01T00:00:00Z',
  52. archive_name: 'Test Print',
  53. archive_thumbnail: null,
  54. printer_name: 'Test Printer',
  55. print_time_seconds: 3600,
  56. batch_id: null,
  57. batch_name: null,
  58. ...overrides,
  59. });
  60. /**
  61. * Choose a row in a SlotPicker (#3159).
  62. *
  63. * The slot and override controls were native `<select>`s until a swatch had to
  64. * go next to each choice, which an `<option>` cannot render. They are listboxes
  65. * now, so a test picks by opening the control and clicking a row instead of
  66. * calling `selectOptions` with a value. `triggerName` matches the control's
  67. * aria-label ("Printer slot for …" / "Filament override for …"), which is a
  68. * steadier handle than the old "find the select that has an option with this
  69. * value".
  70. */
  71. async function pickFromSlotPicker(
  72. user: ReturnType<typeof userEvent.setup>,
  73. triggerName: RegExp,
  74. rowText: RegExp,
  75. ): Promise<void> {
  76. const trigger = await waitFor(() => {
  77. const found = screen.getAllByRole('combobox', { name: triggerName });
  78. if (found.length === 0) throw new Error(`no picker matching ${triggerName}`);
  79. return found[0];
  80. });
  81. await user.click(trigger);
  82. const listbox = await screen.findByRole('listbox');
  83. await user.click(within(listbox).getByText(rowText));
  84. }
  85. describe('PrintModal', () => {
  86. const mockOnClose = vi.fn();
  87. const mockOnSuccess = vi.fn();
  88. beforeEach(() => {
  89. vi.clearAllMocks();
  90. server.use(
  91. http.get('/api/v1/printers/', () => {
  92. return HttpResponse.json(mockPrinters);
  93. }),
  94. http.get('/api/v1/archives/:id/plates', () => {
  95. return HttpResponse.json({ is_multi_plate: false, plates: [] });
  96. }),
  97. http.get('/api/v1/archives/:id/filament-requirements', () => {
  98. return HttpResponse.json({ filaments: [] });
  99. }),
  100. http.get('/api/v1/printers/:id/status', () => {
  101. return HttpResponse.json({ connected: true, state: 'IDLE', ams: [], vt_tray: [] });
  102. }),
  103. http.post('/api/v1/queue/', () => {
  104. return HttpResponse.json({ id: 1, status: 'pending' });
  105. }),
  106. http.patch('/api/v1/queue/:id', () => {
  107. return HttpResponse.json({ id: 1, status: 'pending' });
  108. })
  109. );
  110. });
  111. describe('create mode', () => {
  112. it('renders the modal title', () => {
  113. render(
  114. <PrintModal
  115. mode="create"
  116. archiveId={1}
  117. archiveName="Benchy"
  118. initialSelectedPrinterIds={[1]}
  119. onClose={mockOnClose}
  120. onSuccess={mockOnSuccess}
  121. />
  122. );
  123. expect(screen.getByRole('heading', { name: 'Print' })).toBeInTheDocument();
  124. });
  125. it('shows archive name', () => {
  126. render(
  127. <PrintModal
  128. mode="create"
  129. archiveId={1}
  130. archiveName="Benchy"
  131. onClose={mockOnClose}
  132. onSuccess={mockOnSuccess}
  133. />
  134. );
  135. expect(screen.getByText('Benchy')).toBeInTheDocument();
  136. });
  137. it('shows printer selection with checkboxes for multi-select', async () => {
  138. render(
  139. <PrintModal
  140. mode="create"
  141. archiveId={1}
  142. archiveName="Benchy"
  143. onClose={mockOnClose}
  144. onSuccess={mockOnSuccess}
  145. />
  146. );
  147. await waitFor(() => {
  148. expect(screen.getByText('X1 Carbon')).toBeInTheDocument();
  149. expect(screen.getByText('P1S')).toBeInTheDocument();
  150. });
  151. });
  152. it('has print button', () => {
  153. render(
  154. <PrintModal
  155. mode="create"
  156. archiveId={1}
  157. archiveName="Benchy"
  158. onClose={mockOnClose}
  159. onSuccess={mockOnSuccess}
  160. />
  161. );
  162. // Get the submit button specifically (not printer selection buttons)
  163. const submitButton = screen.getByRole('button', { name: /^print$/i });
  164. expect(submitButton).toBeInTheDocument();
  165. });
  166. it('explains and blocks printing when billing has no printable cost center', async () => {
  167. server.use(
  168. http.get('/api/v1/settings/', () => HttpResponse.json({
  169. billing_enabled: true,
  170. default_filament_cost: 25,
  171. currency: 'USD',
  172. })),
  173. http.get('/api/v1/finance/cost-centers/mine', () => HttpResponse.json([])),
  174. );
  175. render(
  176. <PrintModal
  177. mode="create"
  178. archiveId={1}
  179. archiveName="Benchy"
  180. initialSelectedPrinterIds={[1]}
  181. onClose={mockOnClose}
  182. onSuccess={mockOnSuccess}
  183. />
  184. );
  185. expect(await screen.findByRole('alert')).toHaveTextContent(
  186. 'No active cost center is available for printing. Ask an administrator to grant you print access.',
  187. );
  188. expect(screen.getByRole('button', { name: /^print$/i })).toBeDisabled();
  189. });
  190. it('has cancel button', () => {
  191. render(
  192. <PrintModal
  193. mode="create"
  194. archiveId={1}
  195. archiveName="Benchy"
  196. onClose={mockOnClose}
  197. onSuccess={mockOnSuccess}
  198. />
  199. );
  200. expect(screen.getByRole('button', { name: /cancel/i })).toBeInTheDocument();
  201. });
  202. it('calls onClose when cancel is clicked', async () => {
  203. const user = userEvent.setup();
  204. render(
  205. <PrintModal
  206. mode="create"
  207. archiveId={1}
  208. archiveName="Benchy"
  209. onClose={mockOnClose}
  210. onSuccess={mockOnSuccess}
  211. />
  212. );
  213. await user.click(screen.getByRole('button', { name: /cancel/i }));
  214. expect(mockOnClose).toHaveBeenCalled();
  215. });
  216. it('print button is disabled until printer is selected', () => {
  217. render(
  218. <PrintModal
  219. mode="create"
  220. archiveId={1}
  221. archiveName="Benchy"
  222. onClose={mockOnClose}
  223. onSuccess={mockOnSuccess}
  224. />
  225. );
  226. // Get the submit button specifically (not printer selection buttons)
  227. const printButton = screen.getByRole('button', { name: /^print$/i });
  228. expect(printButton).toBeDisabled();
  229. });
  230. it('shows no printers message when none active', async () => {
  231. server.use(
  232. http.get('/api/v1/printers/', () => {
  233. return HttpResponse.json([]);
  234. })
  235. );
  236. render(
  237. <PrintModal
  238. mode="create"
  239. archiveId={1}
  240. archiveName="Benchy"
  241. onClose={mockOnClose}
  242. onSuccess={mockOnSuccess}
  243. />
  244. );
  245. await waitFor(() => {
  246. expect(screen.getByText('No active printers available')).toBeInTheDocument();
  247. });
  248. });
  249. it('shows print options toggle', async () => {
  250. render(
  251. <PrintModal
  252. mode="create"
  253. archiveId={1}
  254. archiveName="Benchy"
  255. initialSelectedPrinterIds={[1]}
  256. onClose={mockOnClose}
  257. onSuccess={mockOnSuccess}
  258. />
  259. );
  260. await waitFor(() => {
  261. expect(screen.getByText('Print Options')).toBeInTheDocument();
  262. });
  263. });
  264. });
  265. describe('create mode', () => {
  266. it('renders the modal title', () => {
  267. render(
  268. <PrintModal
  269. mode="create"
  270. archiveId={1}
  271. archiveName="Test Print"
  272. onClose={mockOnClose}
  273. />
  274. );
  275. expect(screen.getByRole('heading', { name: 'Print' })).toBeInTheDocument();
  276. });
  277. it('shows archive name', () => {
  278. render(
  279. <PrintModal
  280. mode="create"
  281. archiveId={1}
  282. archiveName="Test Print"
  283. onClose={mockOnClose}
  284. />
  285. );
  286. expect(screen.getByText('Test Print')).toBeInTheDocument();
  287. });
  288. it('shows add button', () => {
  289. render(
  290. <PrintModal
  291. mode="create"
  292. archiveId={1}
  293. archiveName="Test Print"
  294. onClose={mockOnClose}
  295. />
  296. );
  297. expect(screen.getByRole('button', { name: /^print$/i })).toBeInTheDocument();
  298. });
  299. it('shows cancel button', () => {
  300. render(
  301. <PrintModal
  302. mode="create"
  303. archiveId={1}
  304. archiveName="Test Print"
  305. onClose={mockOnClose}
  306. />
  307. );
  308. expect(screen.getByRole('button', { name: /cancel/i })).toBeInTheDocument();
  309. });
  310. it('shows Queue option', () => {
  311. render(
  312. <PrintModal
  313. mode="create"
  314. archiveId={1}
  315. archiveName="Test Print"
  316. onClose={mockOnClose}
  317. />
  318. );
  319. expect(screen.getByRole('button', { name: /queue/i })).toBeInTheDocument();
  320. });
  321. it('shows power off option', () => {
  322. render(
  323. <PrintModal
  324. mode="create"
  325. archiveId={1}
  326. archiveName="Test Print"
  327. onClose={mockOnClose}
  328. />
  329. );
  330. expect(screen.getByText(/power off/i)).toBeInTheDocument();
  331. });
  332. it('shows schedule options', () => {
  333. render(
  334. <PrintModal
  335. mode="create"
  336. archiveId={1}
  337. archiveName="Test Print"
  338. onClose={mockOnClose}
  339. />
  340. );
  341. expect(screen.getByRole('button', { name: /asap/i })).toBeInTheDocument();
  342. expect(screen.getByRole('button', { name: /queue/i })).toBeInTheDocument();
  343. expect(screen.getByRole('button', { name: /schedule/i })).toBeInTheDocument();
  344. });
  345. it('orders schedule options by time', () => {
  346. render(
  347. <PrintModal
  348. mode="create"
  349. archiveId={1}
  350. archiveName="Test Print"
  351. onClose={mockOnClose}
  352. />
  353. );
  354. const options = screen.getAllByRole('button', { name: /^(asap|queue|schedule)$/i });
  355. expect(options.map(button => button.textContent?.trim())).toEqual(['ASAP', 'Queue', 'Schedule']);
  356. });
  357. it('calls onClose when cancel is clicked', async () => {
  358. const user = userEvent.setup();
  359. render(
  360. <PrintModal
  361. mode="create"
  362. archiveId={1}
  363. archiveName="Test Print"
  364. onClose={mockOnClose}
  365. />
  366. );
  367. await user.click(screen.getByRole('button', { name: /cancel/i }));
  368. expect(mockOnClose).toHaveBeenCalled();
  369. });
  370. });
  371. // Without queue:start_unreviewed every job waits for staff to start it (#1620)
  372. describe('when the user needs review', () => {
  373. beforeEach(() => {
  374. setAuthToken('test-token', 'session');
  375. server.use(
  376. http.get('*/api/v1/auth/status', () => HttpResponse.json({ auth_enabled: true, requires_setup: false })),
  377. http.get('*/api/v1/auth/me', () =>
  378. HttpResponse.json({
  379. id: 7,
  380. username: 'student',
  381. is_admin: false,
  382. permissions: ['printers:read', 'queue:create', 'queue:update_own'],
  383. }),
  384. ),
  385. );
  386. });
  387. afterEach(() => {
  388. setAuthToken(null);
  389. });
  390. it('says the job waits and still asks for that when saving as ASAP', async () => {
  391. let body: Record<string, unknown> | null = null;
  392. server.use(
  393. http.patch('/api/v1/queue/:id', async ({ request }) => {
  394. body = (await request.json()) as Record<string, unknown>;
  395. return HttpResponse.json({ id: 1, status: 'pending' });
  396. }),
  397. );
  398. const user = userEvent.setup();
  399. render(
  400. <PrintModal
  401. mode="edit-queue-item"
  402. archiveId={1}
  403. archiveName="Test Print"
  404. queueItem={createMockQueueItem({ manual_start: true, created_by_id: 7 })}
  405. onClose={mockOnClose}
  406. />
  407. );
  408. expect(
  409. await screen.findByText('Your print waits for review: it starts once someone who manages the queue starts it.'),
  410. ).toBeInTheDocument();
  411. expect(screen.queryByText('Require manual start')).not.toBeInTheDocument();
  412. await user.click(screen.getByText('ASAP'));
  413. await user.click(screen.getByRole('button', { name: /save/i }));
  414. // Sending false would clear the wait, which the server refuses for them
  415. await waitFor(() => expect(body).not.toBeNull());
  416. expect(body!.manual_start).toBe(true);
  417. });
  418. });
  419. // A student's scheduled job waits too (#1620); staff editing it must not start it
  420. it('keeps a scheduled job waiting when it is edited', async () => {
  421. let body: Record<string, unknown> | null = null;
  422. server.use(
  423. http.patch('/api/v1/queue/:id', async ({ request }) => {
  424. body = (await request.json()) as Record<string, unknown>;
  425. return HttpResponse.json({ id: 1, status: 'pending' });
  426. }),
  427. );
  428. const user = userEvent.setup();
  429. render(
  430. <PrintModal
  431. mode="edit-queue-item"
  432. archiveId={1}
  433. archiveName="Test Print"
  434. queueItem={createMockQueueItem({
  435. manual_start: true,
  436. // Tomorrow: over six months ahead reads as the "no date" placeholder
  437. scheduled_time: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
  438. })}
  439. onClose={mockOnClose}
  440. />
  441. );
  442. await user.click(screen.getByRole('button', { name: /save/i }));
  443. await waitFor(() => expect(body).not.toBeNull());
  444. expect(body!.manual_start).toBe(true);
  445. });
  446. describe('edit-queue-item mode', () => {
  447. it('renders the modal title', () => {
  448. const item = createMockQueueItem();
  449. render(
  450. <PrintModal
  451. mode="edit-queue-item"
  452. archiveId={1}
  453. archiveName="Test Print"
  454. queueItem={item}
  455. onClose={mockOnClose}
  456. />
  457. );
  458. expect(screen.getByText('Edit Queue Item')).toBeInTheDocument();
  459. });
  460. it('shows save button', () => {
  461. const item = createMockQueueItem();
  462. render(
  463. <PrintModal
  464. mode="edit-queue-item"
  465. archiveId={1}
  466. archiveName="Test Print"
  467. queueItem={item}
  468. onClose={mockOnClose}
  469. />
  470. );
  471. expect(screen.getByRole('button', { name: /save/i })).toBeInTheDocument();
  472. });
  473. it('shows cancel button', () => {
  474. const item = createMockQueueItem();
  475. render(
  476. <PrintModal
  477. mode="edit-queue-item"
  478. archiveId={1}
  479. archiveName="Test Print"
  480. queueItem={item}
  481. onClose={mockOnClose}
  482. />
  483. );
  484. expect(screen.getByRole('button', { name: /cancel/i })).toBeInTheDocument();
  485. });
  486. it('shows print options toggle', () => {
  487. const item = createMockQueueItem();
  488. render(
  489. <PrintModal
  490. mode="edit-queue-item"
  491. archiveId={1}
  492. archiveName="Test Print"
  493. queueItem={item}
  494. onClose={mockOnClose}
  495. />
  496. );
  497. expect(screen.getByText('Print Options')).toBeInTheDocument();
  498. });
  499. it('shows Queue option', () => {
  500. const item = createMockQueueItem();
  501. render(
  502. <PrintModal
  503. mode="edit-queue-item"
  504. archiveId={1}
  505. archiveName="Test Print"
  506. queueItem={item}
  507. onClose={mockOnClose}
  508. />
  509. );
  510. expect(screen.getByRole('button', { name: /queue/i })).toBeInTheDocument();
  511. });
  512. it('shows power off option', () => {
  513. const item = createMockQueueItem();
  514. render(
  515. <PrintModal
  516. mode="edit-queue-item"
  517. archiveId={1}
  518. archiveName="Test Print"
  519. queueItem={item}
  520. onClose={mockOnClose}
  521. />
  522. );
  523. expect(screen.getByText(/power off/i)).toBeInTheDocument();
  524. });
  525. it('calls onClose when cancel button is clicked', async () => {
  526. const user = userEvent.setup();
  527. const item = createMockQueueItem();
  528. render(
  529. <PrintModal
  530. mode="edit-queue-item"
  531. archiveId={1}
  532. archiveName="Test Print"
  533. queueItem={item}
  534. onClose={mockOnClose}
  535. />
  536. );
  537. const cancelButton = screen.getByRole('button', { name: /cancel/i });
  538. await user.click(cancelButton);
  539. expect(mockOnClose).toHaveBeenCalled();
  540. });
  541. it('shows printer selector for single selection', async () => {
  542. const item = createMockQueueItem();
  543. render(
  544. <PrintModal
  545. mode="edit-queue-item"
  546. archiveId={1}
  547. archiveName="Test Print"
  548. queueItem={item}
  549. onClose={mockOnClose}
  550. />
  551. );
  552. // PrinterSelector shows printer names directly
  553. await waitFor(() => {
  554. expect(screen.getByText('P1S')).toBeInTheDocument();
  555. });
  556. });
  557. });
  558. describe('multi-printer selection', () => {
  559. it('shows select all button when multiple printers available', async () => {
  560. render(
  561. <PrintModal
  562. mode="create"
  563. archiveId={1}
  564. archiveName="Benchy"
  565. onClose={mockOnClose}
  566. />
  567. );
  568. await waitFor(() => {
  569. expect(screen.getByText('Select all')).toBeInTheDocument();
  570. });
  571. });
  572. it('shows selected count when multiple printers selected', async () => {
  573. const user = userEvent.setup();
  574. render(
  575. <PrintModal
  576. mode="create"
  577. archiveId={1}
  578. archiveName="Benchy"
  579. onClose={mockOnClose}
  580. />
  581. );
  582. await waitFor(() => {
  583. expect(screen.getByText('Select all')).toBeInTheDocument();
  584. });
  585. await user.click(screen.getByText('Select all'));
  586. await waitFor(() => {
  587. expect(screen.getByText(/3 printers selected/)).toBeInTheDocument();
  588. });
  589. });
  590. it('updates button text when multiple printers selected', async () => {
  591. const user = userEvent.setup();
  592. render(
  593. <PrintModal
  594. mode="create"
  595. archiveId={1}
  596. archiveName="Benchy"
  597. onClose={mockOnClose}
  598. />
  599. );
  600. await waitFor(() => {
  601. expect(screen.getByText('Select all')).toBeInTheDocument();
  602. });
  603. await user.click(screen.getByText('Select all'));
  604. await waitFor(() => {
  605. expect(screen.getByRole('button', { name: /^print$/i })).toBeInTheDocument();
  606. });
  607. });
  608. });
  609. describe('busy printer handling (#622)', () => {
  610. beforeEach(() => {
  611. // Set up per-printer statuses: printer 1 RUNNING, printer 2 IDLE, printer 3 FINISH
  612. server.use(
  613. http.get('/api/v1/printers/:id/status', ({ params }) => {
  614. const id = Number(params.id);
  615. if (id === 1) {
  616. return HttpResponse.json({
  617. connected: true, state: 'RUNNING', stg_cur_name: null,
  618. ams: [], vt_tray: [], nozzles: [],
  619. });
  620. }
  621. if (id === 2) {
  622. return HttpResponse.json({
  623. connected: true, state: 'IDLE', stg_cur_name: null,
  624. ams: [], vt_tray: [], nozzles: [],
  625. });
  626. }
  627. // printer 3
  628. return HttpResponse.json({
  629. connected: true, state: 'FINISH', stg_cur_name: null,
  630. ams: [], vt_tray: [], nozzles: [],
  631. });
  632. })
  633. );
  634. });
  635. it('shows state badges on printers in create mode', async () => {
  636. render(
  637. <PrintModal
  638. mode="create"
  639. archiveId={1}
  640. archiveName="Benchy"
  641. onClose={mockOnClose}
  642. />
  643. );
  644. await waitFor(() => {
  645. expect(screen.getByText('Printing')).toBeInTheDocument();
  646. expect(screen.getByText('Idle')).toBeInTheDocument();
  647. expect(screen.getByText('Finished')).toBeInTheDocument();
  648. });
  649. });
  650. it('allows selecting a busy printer in create mode', async () => {
  651. const user = userEvent.setup();
  652. render(
  653. <PrintModal
  654. mode="create"
  655. archiveId={1}
  656. archiveName="Benchy"
  657. onClose={mockOnClose}
  658. />
  659. );
  660. await waitFor(() => {
  661. expect(screen.getByText('Printing')).toBeInTheDocument();
  662. });
  663. const busyButton = screen.getByText('X1 Carbon').closest('button');
  664. expect(busyButton).not.toBeDisabled();
  665. await user.click(busyButton!);
  666. await waitFor(() => {
  667. expect(screen.getByText('1 printer selected')).toBeInTheDocument();
  668. });
  669. });
  670. it('select all includes busy printers in create mode', async () => {
  671. const user = userEvent.setup();
  672. render(
  673. <PrintModal
  674. mode="create"
  675. archiveId={1}
  676. archiveName="Benchy"
  677. onClose={mockOnClose}
  678. />
  679. );
  680. await waitFor(() => {
  681. expect(screen.getByText('Select all')).toBeInTheDocument();
  682. expect(screen.getByText('Printing')).toBeInTheDocument();
  683. });
  684. await user.click(screen.getByText('Select all'));
  685. await waitFor(() => {
  686. expect(screen.getByText(/3 printers selected/)).toBeInTheDocument();
  687. });
  688. });
  689. it('allows selecting busy printers in create mode', async () => {
  690. const user = userEvent.setup();
  691. render(
  692. <PrintModal
  693. mode="create"
  694. archiveId={1}
  695. archiveName="Benchy"
  696. onClose={mockOnClose}
  697. />
  698. );
  699. await waitFor(() => {
  700. expect(screen.getByText('Printing')).toBeInTheDocument();
  701. });
  702. // The busy printer button should NOT be disabled in queue mode
  703. const busyButton = screen.getByText('X1 Carbon').closest('button');
  704. expect(busyButton).not.toBeDisabled();
  705. await user.click(busyButton!);
  706. await waitFor(() => {
  707. expect(screen.getByText('1 printer selected')).toBeInTheDocument();
  708. });
  709. });
  710. it('shows Offline badge for disconnected printers', async () => {
  711. server.use(
  712. http.get('/api/v1/printers/:id/status', () => {
  713. return HttpResponse.json({
  714. connected: false, state: null, stg_cur_name: null,
  715. ams: [], vt_tray: [], nozzles: [],
  716. });
  717. })
  718. );
  719. render(
  720. <PrintModal
  721. mode="create"
  722. archiveId={1}
  723. archiveName="Benchy"
  724. onClose={mockOnClose}
  725. />
  726. );
  727. await waitFor(() => {
  728. const offlineBadges = screen.getAllByText('Offline');
  729. expect(offlineBadges.length).toBeGreaterThanOrEqual(1);
  730. });
  731. });
  732. it('shows calibration stage name when printer is calibrating', async () => {
  733. server.use(
  734. http.get('/api/v1/printers/:id/status', () => {
  735. return HttpResponse.json({
  736. connected: true, state: 'RUNNING', stg_cur_name: 'Auto bed leveling',
  737. ams: [], vt_tray: [], nozzles: [],
  738. });
  739. })
  740. );
  741. render(
  742. <PrintModal
  743. mode="create"
  744. archiveId={1}
  745. archiveName="Benchy"
  746. onClose={mockOnClose}
  747. />
  748. );
  749. await waitFor(() => {
  750. const badges = screen.getAllByText('Auto bed leveling');
  751. expect(badges.length).toBeGreaterThanOrEqual(1);
  752. });
  753. });
  754. });
  755. describe('stagger start', () => {
  756. it('does not show stagger option with single printer in queue mode', async () => {
  757. const user = userEvent.setup();
  758. render(
  759. <PrintModal
  760. mode="create"
  761. archiveId={1}
  762. archiveName="Test Print"
  763. onClose={mockOnClose}
  764. />
  765. );
  766. await waitFor(() => {
  767. expect(screen.getByText('X1 Carbon')).toBeInTheDocument();
  768. });
  769. // Select single printer
  770. await user.click(screen.getByText('X1 Carbon'));
  771. expect(screen.queryByText('Stagger printer starts')).not.toBeInTheDocument();
  772. });
  773. it('shows stagger option when multiple printers selected in queue mode', async () => {
  774. const user = userEvent.setup();
  775. render(
  776. <PrintModal
  777. mode="create"
  778. archiveId={1}
  779. archiveName="Test Print"
  780. onClose={mockOnClose}
  781. />
  782. );
  783. await waitFor(() => {
  784. expect(screen.getByText('Select all')).toBeInTheDocument();
  785. });
  786. await user.click(screen.getByText('Select all'));
  787. await waitFor(() => {
  788. expect(screen.getByText('Stagger printer starts')).toBeInTheDocument();
  789. });
  790. });
  791. it('shows stagger option in create mode with multiple printers', async () => {
  792. const user = userEvent.setup();
  793. render(
  794. <PrintModal
  795. mode="create"
  796. archiveId={1}
  797. archiveName="Test Print"
  798. onClose={mockOnClose}
  799. />
  800. );
  801. await waitFor(() => {
  802. expect(screen.getByText('Select all')).toBeInTheDocument();
  803. });
  804. await user.click(screen.getByText('Select all'));
  805. await waitFor(() => {
  806. expect(screen.getByText(/2 printers selected|3 printers selected/)).toBeInTheDocument();
  807. });
  808. expect(screen.getByText('Stagger printer starts')).toBeInTheDocument();
  809. });
  810. it('shows stagger preview in create mode when enabled', async () => {
  811. const user = userEvent.setup();
  812. render(
  813. <PrintModal
  814. mode="create"
  815. archiveId={1}
  816. archiveName="Test Print"
  817. onClose={mockOnClose}
  818. />
  819. );
  820. await waitFor(() => {
  821. expect(screen.getByText('Select all')).toBeInTheDocument();
  822. });
  823. await user.click(screen.getByText('Select all'));
  824. await waitFor(() => {
  825. expect(screen.getByText('Stagger printer starts')).toBeInTheDocument();
  826. });
  827. await user.click(screen.getByLabelText('Stagger printer starts'));
  828. await waitFor(() => {
  829. // Default: 3 printers, group size 2 = 2 groups — preview text shown
  830. expect(screen.getByText(/3 printers.*2 groups/)).toBeInTheDocument();
  831. });
  832. });
  833. it('does not show stagger option in create mode with single printer', async () => {
  834. const user = userEvent.setup();
  835. render(
  836. <PrintModal
  837. mode="create"
  838. archiveId={1}
  839. archiveName="Test Print"
  840. onClose={mockOnClose}
  841. />
  842. );
  843. await waitFor(() => {
  844. expect(screen.getByText('X1 Carbon')).toBeInTheDocument();
  845. });
  846. // Select only one printer
  847. await user.click(screen.getByText('X1 Carbon'));
  848. expect(screen.queryByText('Stagger printer starts')).not.toBeInTheDocument();
  849. });
  850. it('shows stagger inputs when stagger checkbox is enabled', async () => {
  851. const user = userEvent.setup();
  852. render(
  853. <PrintModal
  854. mode="create"
  855. archiveId={1}
  856. archiveName="Test Print"
  857. onClose={mockOnClose}
  858. />
  859. );
  860. await waitFor(() => {
  861. expect(screen.getByText('Select all')).toBeInTheDocument();
  862. });
  863. await user.click(screen.getByText('Select all'));
  864. await waitFor(() => {
  865. expect(screen.getByText('Stagger printer starts')).toBeInTheDocument();
  866. });
  867. await user.click(screen.getByLabelText('Stagger printer starts'));
  868. await waitFor(() => {
  869. expect(screen.getByText('Group size')).toBeInTheDocument();
  870. expect(screen.getByText('Interval (min)')).toBeInTheDocument();
  871. });
  872. });
  873. it('shows stagger preview with printer count', async () => {
  874. const user = userEvent.setup();
  875. render(
  876. <PrintModal
  877. mode="create"
  878. archiveId={1}
  879. archiveName="Test Print"
  880. onClose={mockOnClose}
  881. />
  882. );
  883. await waitFor(() => {
  884. expect(screen.getByText('Select all')).toBeInTheDocument();
  885. });
  886. await user.click(screen.getByText('Select all'));
  887. await waitFor(() => {
  888. expect(screen.getByText('Stagger printer starts')).toBeInTheDocument();
  889. });
  890. await user.click(screen.getByLabelText('Stagger printer starts'));
  891. await waitFor(() => {
  892. // Default: 3 printers, group size 2 = 2 groups — preview text includes printer count
  893. expect(screen.getByText(/3 printers.*2 groups/)).toBeInTheDocument();
  894. });
  895. });
  896. });
  897. describe('multi-plate selection', () => {
  898. const multiPlateResponse = {
  899. is_multi_plate: true,
  900. plates: [
  901. { index: 1, name: 'Plate 1', has_thumbnail: false, thumbnail_url: null, objects: ['Part A'], filaments: [{ type: 'PLA', color: '#FF0000' }], print_time_seconds: 1800, filament_used_grams: 50 },
  902. { index: 2, name: 'Plate 2', has_thumbnail: false, thumbnail_url: null, objects: ['Part B'], filaments: [{ type: 'PLA', color: '#00FF00' }], print_time_seconds: 2400, filament_used_grams: 60 },
  903. { index: 3, name: 'Plate 3', has_thumbnail: false, thumbnail_url: null, objects: ['Part C'], filaments: [{ type: 'PETG', color: '#0000FF' }], print_time_seconds: 3000, filament_used_grams: 70 },
  904. ],
  905. };
  906. beforeEach(() => {
  907. server.use(
  908. http.get('/api/v1/archives/:id/plates', () => {
  909. return HttpResponse.json(multiPlateResponse);
  910. }),
  911. );
  912. });
  913. it('shows "Select All" button only in create mode', async () => {
  914. render(
  915. <PrintModal
  916. mode="create"
  917. archiveId={1}
  918. archiveName="MultiPlate.3mf"
  919. onClose={mockOnClose}
  920. />
  921. );
  922. await waitFor(() => {
  923. expect(screen.getByText('Select All 3 Plates')).toBeInTheDocument();
  924. });
  925. });
  926. it('shows "Select All" button in create mode', async () => {
  927. render(
  928. <PrintModal
  929. mode="create"
  930. archiveId={1}
  931. archiveName="MultiPlate.3mf"
  932. initialSelectedPrinterIds={[1]}
  933. onClose={mockOnClose}
  934. />
  935. );
  936. await waitFor(() => {
  937. expect(screen.getByText('Plate 1')).toBeInTheDocument();
  938. });
  939. expect(screen.getByText('Select All 3 Plates')).toBeInTheDocument();
  940. });
  941. it('selects all plates when "Select All" is clicked', async () => {
  942. const user = userEvent.setup();
  943. render(
  944. <PrintModal
  945. mode="create"
  946. archiveId={1}
  947. archiveName="MultiPlate.3mf"
  948. onClose={mockOnClose}
  949. />
  950. );
  951. await waitFor(() => {
  952. expect(screen.getByText('Select All 3 Plates')).toBeInTheDocument();
  953. });
  954. await user.click(screen.getByText('Select All 3 Plates'));
  955. // All plates should be highlighted (green border)
  956. await waitFor(() => {
  957. const plateButtons = document.querySelectorAll('button[type="button"].border-bambu-green');
  958. // 3 plate buttons + the "Deselect All" toggle button = 4 green-bordered buttons
  959. expect(plateButtons.length).toBeGreaterThanOrEqual(3);
  960. });
  961. });
  962. it('allows selecting a subset of plates to queue', async () => {
  963. const queueRequests: unknown[] = [];
  964. server.use(
  965. http.post('/api/v1/queue/', async ({ request }) => {
  966. const body = await request.json();
  967. queueRequests.push(body);
  968. return HttpResponse.json({ id: queueRequests.length, status: 'pending' });
  969. }),
  970. );
  971. const user = userEvent.setup();
  972. render(
  973. <PrintModal
  974. mode="create"
  975. archiveId={1}
  976. archiveName="MultiPlate.3mf"
  977. onClose={mockOnClose}
  978. onSuccess={mockOnSuccess}
  979. />
  980. );
  981. // Wait for plates and select a printer
  982. await waitFor(() => {
  983. expect(screen.getByText('Select All 3 Plates')).toBeInTheDocument();
  984. expect(screen.getByText('X1 Carbon')).toBeInTheDocument();
  985. });
  986. // Select printer
  987. await user.click(screen.getByText('X1 Carbon'));
  988. // Plate 1 is auto-selected. Click Plate 3 to add it (multi-select in create mode)
  989. await user.click(screen.getByText('Plate 3'));
  990. // Submit — should queue plates 1 and 3
  991. const submitButton = document.querySelector('button[type="submit"]') as HTMLElement;
  992. await user.click(submitButton);
  993. await waitFor(() => {
  994. expect(queueRequests.length).toBe(2);
  995. });
  996. expect((queueRequests[0] as { plate_id: number }).plate_id).toBe(1);
  997. expect((queueRequests[1] as { plate_id: number }).plate_id).toBe(3);
  998. });
  999. it('creates one queue item per plate when submitting with select-all', async () => {
  1000. const queueRequests: unknown[] = [];
  1001. server.use(
  1002. http.post('/api/v1/queue/', async ({ request }) => {
  1003. const body = await request.json();
  1004. queueRequests.push(body);
  1005. return HttpResponse.json({ id: queueRequests.length, status: 'pending' });
  1006. }),
  1007. );
  1008. const user = userEvent.setup();
  1009. render(
  1010. <PrintModal
  1011. mode="create"
  1012. archiveId={1}
  1013. archiveName="MultiPlate.3mf"
  1014. onClose={mockOnClose}
  1015. onSuccess={mockOnSuccess}
  1016. />
  1017. );
  1018. // Wait for plates and select a printer
  1019. await waitFor(() => {
  1020. expect(screen.getByText('Select All 3 Plates')).toBeInTheDocument();
  1021. expect(screen.getByText('X1 Carbon')).toBeInTheDocument();
  1022. });
  1023. // Select printer
  1024. await user.click(screen.getByText('X1 Carbon'));
  1025. // Click select all
  1026. await user.click(screen.getByText('Select All 3 Plates'));
  1027. // Find the submit button (type="submit") — distinct from the toggle button (type="button")
  1028. const submitButton = document.querySelector('button[type="submit"]') as HTMLElement;
  1029. await user.click(submitButton);
  1030. await waitFor(() => {
  1031. expect(queueRequests.length).toBe(3);
  1032. });
  1033. // Verify each request has the correct plate_id
  1034. expect((queueRequests[0] as { plate_id: number }).plate_id).toBe(1);
  1035. expect((queueRequests[1] as { plate_id: number }).plate_id).toBe(2);
  1036. expect((queueRequests[2] as { plate_id: number }).plate_id).toBe(3);
  1037. });
  1038. });
  1039. describe('batch quantity', () => {
  1040. it('shows quantity input in create mode', () => {
  1041. render(
  1042. <PrintModal
  1043. mode="create"
  1044. archiveId={1}
  1045. archiveName="Benchy"
  1046. onClose={mockOnClose}
  1047. onSuccess={mockOnSuccess}
  1048. />
  1049. );
  1050. expect(screen.getByLabelText('Quantity')).toBeInTheDocument();
  1051. });
  1052. it('shows quantity input in create mode', () => {
  1053. render(
  1054. <PrintModal
  1055. mode="create"
  1056. archiveId={1}
  1057. archiveName="Benchy"
  1058. onClose={mockOnClose}
  1059. onSuccess={mockOnSuccess}
  1060. />
  1061. );
  1062. expect(screen.getByLabelText('Quantity')).toBeInTheDocument();
  1063. });
  1064. it('does not show quantity input in edit-queue-item mode', () => {
  1065. render(
  1066. <PrintModal
  1067. mode="edit-queue-item"
  1068. archiveId={1}
  1069. archiveName="Benchy"
  1070. queueItem={createMockQueueItem()}
  1071. onClose={mockOnClose}
  1072. onSuccess={mockOnSuccess}
  1073. />
  1074. );
  1075. expect(screen.queryByLabelText('Quantity')).not.toBeInTheDocument();
  1076. });
  1077. it('defaults quantity to 1', () => {
  1078. render(
  1079. <PrintModal
  1080. mode="create"
  1081. archiveId={1}
  1082. archiveName="Benchy"
  1083. onClose={mockOnClose}
  1084. onSuccess={mockOnSuccess}
  1085. />
  1086. );
  1087. const input = screen.getByLabelText('Quantity') as HTMLInputElement;
  1088. expect(input.value).toBe('1');
  1089. });
  1090. it('quantity input has default value of 1 and accepts changes', async () => {
  1091. const user = userEvent.setup();
  1092. render(
  1093. <PrintModal
  1094. mode="create"
  1095. archiveId={1}
  1096. archiveName="Benchy"
  1097. initialSelectedPrinterIds={[1]}
  1098. onClose={mockOnClose}
  1099. onSuccess={mockOnSuccess}
  1100. />
  1101. );
  1102. const input = screen.getByLabelText('Quantity') as HTMLInputElement;
  1103. expect(input.value).toBe('1');
  1104. await user.tripleClick(input);
  1105. await user.keyboard('5');
  1106. expect(input.value).toBe('5');
  1107. });
  1108. it('quantity can be erased and retyped instead of snapping back to 1 (#3182)', async () => {
  1109. const user = userEvent.setup();
  1110. render(
  1111. <PrintModal
  1112. mode="create"
  1113. archiveId={1}
  1114. archiveName="Benchy"
  1115. initialSelectedPrinterIds={[1]}
  1116. onClose={mockOnClose}
  1117. onSuccess={mockOnSuccess}
  1118. />
  1119. );
  1120. const input = screen.getByLabelText('Quantity') as HTMLInputElement;
  1121. await user.click(input);
  1122. await user.keyboard('{Backspace}');
  1123. expect(input.value).toBe('');
  1124. await user.keyboard('6');
  1125. expect(input.value).toBe('6');
  1126. expect(screen.getByText('Creates 6 queue items')).toBeInTheDocument();
  1127. });
  1128. it('an emptied quantity settles back to 1 when the field is left', async () => {
  1129. const user = userEvent.setup();
  1130. render(
  1131. <PrintModal
  1132. mode="create"
  1133. archiveId={1}
  1134. archiveName="Benchy"
  1135. initialSelectedPrinterIds={[1]}
  1136. onClose={mockOnClose}
  1137. onSuccess={mockOnSuccess}
  1138. />
  1139. );
  1140. const input = screen.getByLabelText('Quantity') as HTMLInputElement;
  1141. await user.click(input);
  1142. await user.keyboard('{Backspace}');
  1143. await user.tab();
  1144. expect(input.value).toBe('1');
  1145. });
  1146. });
  1147. describe('reprint G-code injection dispatch (#422 / auto-eject)', () => {
  1148. // Guards the fix: when "Inject auto-print G-code" is ticked on a create with
  1149. // quantity > 1, ALL copies must go through the queue so every one is injected by
  1150. // the scheduler. The first copy must NOT be dispatched immediately via the direct
  1151. // create path — that path bypasses injection and would leave the first copy stuck
  1152. // on the plate for auto-eject setups.
  1153. const withSnippets = () =>
  1154. http.get('/api/v1/settings/', () =>
  1155. HttpResponse.json({ gcode_snippets: { X1C: { start_gcode: '', end_gcode: 'M400' } } }),
  1156. );
  1157. it('injection ON queues all copies and dispatches none immediately', async () => {
  1158. const queueCalls: Record<string, unknown>[] = [];
  1159. server.use(
  1160. withSnippets(),
  1161. http.post('/api/v1/queue/', async ({ request }) => {
  1162. queueCalls.push((await request.json()) as Record<string, unknown>);
  1163. return HttpResponse.json({ id: queueCalls.length, status: 'pending' });
  1164. }),
  1165. );
  1166. const user = userEvent.setup();
  1167. render(
  1168. <PrintModal
  1169. mode="create"
  1170. archiveId={1}
  1171. archiveName="Benchy"
  1172. initialSelectedPrinterIds={[1]}
  1173. onClose={mockOnClose}
  1174. onSuccess={mockOnSuccess}
  1175. />
  1176. );
  1177. // Quantity > 1 so the injection checkbox is offered
  1178. const qty = (await screen.findByLabelText('Quantity')) as HTMLInputElement;
  1179. await user.tripleClick(qty);
  1180. await user.keyboard('3');
  1181. expect(qty.value).toBe('3');
  1182. // Checkbox only renders once snippets are loaded AND quantity > 1
  1183. await user.click(await screen.findByLabelText(/inject auto-print/i));
  1184. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1185. await waitFor(() => expect(queueCalls.length).toBe(1));
  1186. // One queue item carrying all copies, and zero immediate reprint dispatches
  1187. expect(queueCalls[0].quantity).toBe(3);
  1188. });
  1189. it('quantity 1 + snippets configured: checkbox toggles cleanly (#1852)', async () => {
  1190. // The previous reset effect in PrintModal/index.tsx silently flipped
  1191. // gcodeInjection back to false whenever effectiveQuantity <= 1 in create
  1192. // mode, so a single print with snippets configured couldn't tick the
  1193. // checkbox — every click visibly un-ticked itself within the next render.
  1194. // The scheduler reads item.gcode_injection per queue item regardless of
  1195. // batch size, so quantity 1 must be allowed too.
  1196. const queueCalls: Record<string, unknown>[] = [];
  1197. server.use(
  1198. withSnippets(),
  1199. http.post('/api/v1/queue/', async ({ request }) => {
  1200. queueCalls.push((await request.json()) as Record<string, unknown>);
  1201. return HttpResponse.json({ id: queueCalls.length, status: 'pending' });
  1202. }),
  1203. );
  1204. const user = userEvent.setup();
  1205. render(
  1206. <PrintModal
  1207. mode="create"
  1208. archiveId={1}
  1209. archiveName="Benchy"
  1210. initialSelectedPrinterIds={[1]}
  1211. onClose={mockOnClose}
  1212. onSuccess={mockOnSuccess}
  1213. />
  1214. );
  1215. // Quantity stays at default (1) — this is the OP's exact scenario.
  1216. const checkbox = (await screen.findByLabelText(/inject auto-print/i)) as HTMLInputElement;
  1217. expect(checkbox.checked).toBe(false);
  1218. await user.click(checkbox);
  1219. // CRITICAL: after the click the checkbox must stay checked. Under the
  1220. // pre-fix reset effect, the parent state would flip back to false within
  1221. // a render and the displayed `checked` attribute would track it.
  1222. await waitFor(() => expect(checkbox.checked).toBe(true));
  1223. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1224. await waitFor(() => expect(queueCalls.length).toBe(1));
  1225. // The injection flag actually reaches the API — pre-fix the parent reset
  1226. // would have stripped it before submit.
  1227. expect(queueCalls[0].gcode_injection).toBe(true);
  1228. });
  1229. it('injection OFF queues all copies through the scheduler path', async () => {
  1230. const queueCalls: Record<string, unknown>[] = [];
  1231. server.use(
  1232. withSnippets(),
  1233. http.post('/api/v1/queue/', async ({ request }) => {
  1234. queueCalls.push((await request.json()) as Record<string, unknown>);
  1235. return HttpResponse.json({ id: queueCalls.length, status: 'pending' });
  1236. }),
  1237. );
  1238. const user = userEvent.setup();
  1239. render(
  1240. <PrintModal
  1241. mode="create"
  1242. archiveId={1}
  1243. archiveName="Benchy"
  1244. initialSelectedPrinterIds={[1]}
  1245. onClose={mockOnClose}
  1246. onSuccess={mockOnSuccess}
  1247. />
  1248. );
  1249. const qty = (await screen.findByLabelText('Quantity')) as HTMLInputElement;
  1250. await user.tripleClick(qty);
  1251. await user.keyboard('3');
  1252. expect(qty.value).toBe('3');
  1253. // Leave injection unticked: unified dispatch still queues all copies.
  1254. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1255. await waitFor(() => expect(queueCalls.length).toBe(1));
  1256. expect(queueCalls[0].quantity).toBe(3);
  1257. });
  1258. });
  1259. describe('project_id forwarding', () => {
  1260. beforeEach(() => {
  1261. // Additional handlers needed for library file mode
  1262. server.use(
  1263. http.get('/api/v1/library/files/:id', () => {
  1264. return HttpResponse.json({
  1265. id: 5,
  1266. filename: 'benchy.gcode.3mf',
  1267. print_name: null,
  1268. file_type: '3mf',
  1269. folder_id: null,
  1270. project_id: null,
  1271. file_hash: null,
  1272. file_size_bytes: 1024,
  1273. thumbnail_path: null,
  1274. created_at: '2024-01-01T00:00:00Z',
  1275. updated_at: '2024-01-01T00:00:00Z',
  1276. });
  1277. }),
  1278. http.get('/api/v1/library/files/:id/plates', () => {
  1279. return HttpResponse.json({ is_multi_plate: false, plates: [] });
  1280. }),
  1281. http.get('/api/v1/library/files/:id/filament-requirements', () => {
  1282. return HttpResponse.json({ file_id: 5, filename: 'benchy.gcode.3mf', filaments: [] });
  1283. }),
  1284. http.get('/api/v1/printers/:id/status', () => {
  1285. return HttpResponse.json({ connected: true, state: 'IDLE', ams: [], vt_tray: [] });
  1286. }),
  1287. );
  1288. });
  1289. it('includes project_id in queue item when printing a library file with projectId set', async () => {
  1290. let capturedBody: Record<string, unknown> | null = null;
  1291. server.use(
  1292. http.post('/api/v1/queue/', async ({ request }) => {
  1293. capturedBody = await request.json() as Record<string, unknown>;
  1294. return HttpResponse.json({ id: 1, status: 'pending' });
  1295. })
  1296. );
  1297. const user = userEvent.setup();
  1298. render(
  1299. <PrintModal
  1300. mode="create"
  1301. libraryFileId={5}
  1302. archiveName="Benchy"
  1303. projectId={42}
  1304. initialSelectedPrinterIds={[1]}
  1305. onClose={mockOnClose}
  1306. onSuccess={mockOnSuccess}
  1307. />
  1308. );
  1309. // Wait for the modal to load printer and file data
  1310. await waitFor(() => {
  1311. expect(screen.getByRole('button', { name: /^print$/i })).toBeInTheDocument();
  1312. });
  1313. await user.click(screen.getByRole('button', { name: /^print$/i }));
  1314. await waitFor(() => {
  1315. expect(capturedBody).not.toBeNull();
  1316. expect(capturedBody?.library_file_id).toBe(5);
  1317. expect(capturedBody?.project_id).toBe(42);
  1318. });
  1319. });
  1320. it('queues archive prints through the scheduler path', async () => {
  1321. let capturedBody: Record<string, unknown> | null = null;
  1322. server.use(
  1323. http.post('/api/v1/queue/', async ({ request }) => {
  1324. capturedBody = await request.json() as Record<string, unknown>;
  1325. return HttpResponse.json({ id: 1, status: 'pending' });
  1326. })
  1327. );
  1328. const user = userEvent.setup();
  1329. render(
  1330. <PrintModal
  1331. mode="create"
  1332. archiveId={1}
  1333. archiveName="Benchy"
  1334. projectId={42}
  1335. initialSelectedPrinterIds={[1]}
  1336. onClose={mockOnClose}
  1337. onSuccess={mockOnSuccess}
  1338. />
  1339. );
  1340. await waitFor(() => {
  1341. expect(screen.getByRole('button', { name: /^print$/i })).toBeInTheDocument();
  1342. });
  1343. await user.click(screen.getByRole('button', { name: /^print$/i }));
  1344. await waitFor(() => {
  1345. expect(capturedBody).not.toBeNull();
  1346. expect(capturedBody?.archive_id).toBe(1);
  1347. expect(capturedBody?.project_id).toBe(42);
  1348. });
  1349. });
  1350. it('adds ASAP prints to the top of the queue', async () => {
  1351. let capturedBody: Record<string, unknown> | null = null;
  1352. server.use(
  1353. http.post('/api/v1/queue/', async ({ request }) => {
  1354. capturedBody = await request.json() as Record<string, unknown>;
  1355. return HttpResponse.json({ id: 1, status: 'pending' });
  1356. })
  1357. );
  1358. const user = userEvent.setup();
  1359. render(
  1360. <PrintModal
  1361. mode="create"
  1362. archiveId={1}
  1363. archiveName="Benchy"
  1364. initialSelectedPrinterIds={[1]}
  1365. onClose={mockOnClose}
  1366. onSuccess={mockOnSuccess}
  1367. />
  1368. );
  1369. await waitFor(() => {
  1370. expect(screen.getByRole('button', { name: /^print$/i })).toBeInTheDocument();
  1371. });
  1372. await user.click(screen.getByRole('button', { name: /^print$/i }));
  1373. await waitFor(() => {
  1374. expect(capturedBody).not.toBeNull();
  1375. expect(capturedBody?.insert_at_top).toBe(true);
  1376. expect(capturedBody?.insert_position).toBe(1);
  1377. expect(capturedBody?.manual_start).toBe(false);
  1378. expect(capturedBody?.scheduled_time).toBeUndefined();
  1379. });
  1380. });
  1381. it('adds Queue prints to the back unless manual start is required', async () => {
  1382. let capturedBody: Record<string, unknown> | null = null;
  1383. server.use(
  1384. http.post('/api/v1/queue/', async ({ request }) => {
  1385. capturedBody = await request.json() as Record<string, unknown>;
  1386. return HttpResponse.json({ id: 1, status: 'pending' });
  1387. })
  1388. );
  1389. const user = userEvent.setup();
  1390. render(
  1391. <PrintModal
  1392. mode="create"
  1393. archiveId={1}
  1394. archiveName="Benchy"
  1395. initialSelectedPrinterIds={[1]}
  1396. onClose={mockOnClose}
  1397. onSuccess={mockOnSuccess}
  1398. />
  1399. );
  1400. await user.click(screen.getByRole('button', { name: /^queue$/i }));
  1401. expect(screen.getByLabelText(/require manual start/i)).toBeInTheDocument();
  1402. await user.click(screen.getByLabelText(/require manual start/i));
  1403. await user.click(screen.getByRole('button', { name: /^print$/i }));
  1404. await waitFor(() => {
  1405. expect(capturedBody).not.toBeNull();
  1406. expect(capturedBody?.insert_at_top).toBeUndefined();
  1407. expect(capturedBody?.insert_position).toBeUndefined();
  1408. expect(capturedBody?.manual_start).toBe(true);
  1409. });
  1410. });
  1411. });
  1412. describe('cleanup_library_after_dispatch forwarding (#730)', () => {
  1413. // The Printers-page Direct-Print flow passes cleanupLibraryAfterDispatch so the
  1414. // transient LibraryFile created by FileUploadModal is deleted once the archive
  1415. // owns its own copy. File Manager / Project Detail flows leave the prop unset so
  1416. // their deliberately-added library entries survive the print.
  1417. beforeEach(() => {
  1418. server.use(
  1419. http.get('/api/v1/library/files/:id', () => {
  1420. return HttpResponse.json({
  1421. id: 5,
  1422. filename: 'benchy.gcode.3mf',
  1423. file_type: '3mf',
  1424. folder_id: null,
  1425. project_id: null,
  1426. file_hash: null,
  1427. file_size_bytes: 1024,
  1428. thumbnail_path: null,
  1429. created_at: '2024-01-01T00:00:00Z',
  1430. updated_at: '2024-01-01T00:00:00Z',
  1431. });
  1432. }),
  1433. http.get('/api/v1/library/files/:id/plates', () => {
  1434. return HttpResponse.json({ is_multi_plate: false, plates: [] });
  1435. }),
  1436. http.get('/api/v1/library/files/:id/filament-requirements', () => {
  1437. return HttpResponse.json({ file_id: 5, filename: 'benchy.gcode.3mf', filaments: [] });
  1438. }),
  1439. http.get('/api/v1/printers/:id/status', () => {
  1440. return HttpResponse.json({ connected: true, state: 'IDLE', ams: [], vt_tray: [] });
  1441. }),
  1442. );
  1443. });
  1444. it('forwards cleanup_library_after_dispatch=true when the Direct-Print prop is set', async () => {
  1445. let capturedBody: Record<string, unknown> | null = null;
  1446. server.use(
  1447. http.post('/api/v1/queue/', async ({ request }) => {
  1448. capturedBody = (await request.json()) as Record<string, unknown>;
  1449. return HttpResponse.json({ id: 1, status: 'pending' });
  1450. })
  1451. );
  1452. const user = userEvent.setup();
  1453. render(
  1454. <PrintModal
  1455. mode="create"
  1456. libraryFileId={5}
  1457. archiveName="Benchy"
  1458. cleanupLibraryAfterDispatch
  1459. initialSelectedPrinterIds={[1]}
  1460. onClose={mockOnClose}
  1461. onSuccess={mockOnSuccess}
  1462. />
  1463. );
  1464. await waitFor(() => {
  1465. expect(screen.getByRole('button', { name: /^print$/i })).toBeInTheDocument();
  1466. });
  1467. await user.click(screen.getByRole('button', { name: /^print$/i }));
  1468. await waitFor(() => {
  1469. expect(capturedBody).not.toBeNull();
  1470. expect(capturedBody?.cleanup_library_after_dispatch).toBe(true);
  1471. });
  1472. });
  1473. it('defaults to omitting cleanup_library_after_dispatch (File Manager / Project flows survive)', async () => {
  1474. let capturedBody: Record<string, unknown> | null = null;
  1475. server.use(
  1476. http.post('/api/v1/queue/', async ({ request }) => {
  1477. capturedBody = (await request.json()) as Record<string, unknown>;
  1478. return HttpResponse.json({ id: 1, status: 'pending' });
  1479. })
  1480. );
  1481. const user = userEvent.setup();
  1482. render(
  1483. <PrintModal
  1484. mode="create"
  1485. libraryFileId={5}
  1486. archiveName="Benchy"
  1487. initialSelectedPrinterIds={[1]}
  1488. onClose={mockOnClose}
  1489. onSuccess={mockOnSuccess}
  1490. />
  1491. );
  1492. await waitFor(() => {
  1493. expect(screen.getByRole('button', { name: /^print$/i })).toBeInTheDocument();
  1494. });
  1495. await user.click(screen.getByRole('button', { name: /^print$/i }));
  1496. await waitFor(() => {
  1497. expect(capturedBody).not.toBeNull();
  1498. });
  1499. // Either omitted entirely or explicitly undefined — both interpret as "keep file"
  1500. expect(capturedBody?.cleanup_library_after_dispatch).toBeUndefined();
  1501. });
  1502. });
  1503. describe('ask-for-outcome pill (#1898 follow-up)', () => {
  1504. // The pill outside the collapsed Print Options panel and the row inside it
  1505. // edit the same printOptions.confirm_outcome, so flipping either must be
  1506. // reflected by the other and land in the submitted payload.
  1507. // Both carry the label "Ask for Outcome"; the pill is the only button with
  1508. // that name, the panel row is found through its description text.
  1509. const pill = () => screen.getByRole('button', { name: 'Ask for Outcome' });
  1510. const panelRowDesc = 'Ask whether the print came out well after it completes';
  1511. const panelRow = () => screen.getByText(panelRowDesc).closest('div')!.parentElement!;
  1512. it('starts off and toggles on a click', async () => {
  1513. const user = userEvent.setup();
  1514. render(
  1515. <PrintModal mode="create" archiveId={1} archiveName="Benchy" initialSelectedPrinterIds={[1]} onClose={mockOnClose} />
  1516. );
  1517. expect(pill()).toHaveAttribute('aria-pressed', 'false');
  1518. await user.click(pill());
  1519. expect(pill()).toHaveAttribute('aria-pressed', 'true');
  1520. });
  1521. it('shares its state with the row inside Print Options', async () => {
  1522. const user = userEvent.setup();
  1523. render(
  1524. <PrintModal mode="create" archiveId={1} archiveName="Benchy" initialSelectedPrinterIds={[1]} onClose={mockOnClose} />
  1525. );
  1526. await user.click(pill());
  1527. // The panel opens expanded when a printer is preselected; expand otherwise.
  1528. if (!screen.queryByText(panelRowDesc)) await user.click(screen.getByText('Print Options'));
  1529. const row = panelRow();
  1530. expect(within(row).getByRole('button', { name: 'On' })).toHaveClass('bg-bambu-green');
  1531. await user.click(within(row).getByRole('button', { name: 'Off' }));
  1532. expect(pill()).toHaveAttribute('aria-pressed', 'false');
  1533. });
  1534. it('submits confirm_outcome=true with the queue item when turned on', async () => {
  1535. let capturedBody: Record<string, unknown> | null = null;
  1536. server.use(
  1537. http.post('/api/v1/queue/', async ({ request }) => {
  1538. capturedBody = (await request.json()) as Record<string, unknown>;
  1539. return HttpResponse.json({ id: 1, status: 'pending' });
  1540. }),
  1541. );
  1542. const user = userEvent.setup();
  1543. render(
  1544. <PrintModal mode="create" archiveId={1} archiveName="Benchy" initialSelectedPrinterIds={[1]} onClose={mockOnClose} />
  1545. );
  1546. await user.click(pill());
  1547. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1548. await waitFor(() => expect(capturedBody).not.toBeNull());
  1549. expect(capturedBody!.confirm_outcome).toBe(true);
  1550. });
  1551. it('reflects the queue item value in edit mode and saves the change', async () => {
  1552. let capturedBody: Record<string, unknown> | null = null;
  1553. server.use(
  1554. http.patch('/api/v1/queue/:id', async ({ request }) => {
  1555. capturedBody = (await request.json()) as Record<string, unknown>;
  1556. return HttpResponse.json({ id: 1, status: 'pending' });
  1557. }),
  1558. );
  1559. const user = userEvent.setup();
  1560. render(
  1561. <PrintModal
  1562. mode="edit-queue-item"
  1563. archiveId={1}
  1564. archiveName="Test Print"
  1565. queueItem={createMockQueueItem({ confirm_outcome: true })}
  1566. onClose={mockOnClose}
  1567. />
  1568. );
  1569. expect(pill()).toHaveAttribute('aria-pressed', 'true');
  1570. await user.click(pill());
  1571. await user.click(screen.getByRole('button', { name: /save/i }));
  1572. await waitFor(() => expect(capturedBody).not.toBeNull());
  1573. expect(capturedBody!.confirm_outcome).toBe(false);
  1574. });
  1575. });
  1576. });
  1577. describe('PrintModal — per-plate filament mapping (#2551 follow-up)', () => {
  1578. const mockOnClose = vi.fn();
  1579. // These tests deliberately do NOT use the shared `render` from '../utils': its
  1580. // QueryClient sets `gcTime: 0`, which evicts a query the instant it loses its
  1581. // observer. The whole-file filament requirements are fetched on open and then
  1582. // orphaned when a plate is auto-selected, so under gcTime:0 they vanish and the
  1583. // modal simply sends no mapping — the bug cannot reproduce. A real browser keeps
  1584. // that entry for 5 minutes and hands the union straight back when the user picks
  1585. // a second plate, which is what got mapped onto every plate. Same providers,
  1586. // production cache behaviour.
  1587. const render = (ui: React.ReactElement) => {
  1588. const queryClient = new QueryClient({
  1589. defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
  1590. });
  1591. return rtlRender(
  1592. <QueryClientProvider client={queryClient}>
  1593. <BrowserRouter>
  1594. <AuthProvider>
  1595. <ThemeProvider>
  1596. <ToastProvider>{ui}</ToastProvider>
  1597. </ThemeProvider>
  1598. </AuthProvider>
  1599. </BrowserRouter>
  1600. </QueryClientProvider>,
  1601. );
  1602. };
  1603. // Two plates, each printing one red object, but on different slots of the same
  1604. // file. The printer has exactly one red spool (tray 0) and one black (tray 1).
  1605. // Matching the union of both plates makes slot 1 claim the red tray and drops
  1606. // slot 2 onto the black one — so plate 2 would print in the wrong colour.
  1607. const PLATES = {
  1608. is_multi_plate: true,
  1609. plates: [
  1610. { index: 1, name: 'Plate 1', has_thumbnail: false, thumbnail_url: null, objects: ['A'], filaments: [{ type: 'PLA', color: '#FF0000' }], print_time_seconds: 1800, filament_used_grams: 50 },
  1611. { index: 2, name: 'Plate 2', has_thumbnail: false, thumbnail_url: null, objects: ['B'], filaments: [{ type: 'PLA', color: '#FF0000' }], print_time_seconds: 1800, filament_used_grams: 50 },
  1612. ],
  1613. };
  1614. const SLOT_1_RED = { slot_id: 1, type: 'PLA', color: '#FF0000', tray_info_idx: '', used_grams: 50 };
  1615. const SLOT_2_RED = { slot_id: 2, type: 'PLA', color: '#FF0000', tray_info_idx: '', used_grams: 50 };
  1616. beforeEach(() => {
  1617. vi.clearAllMocks();
  1618. server.use(
  1619. http.get('/api/v1/printers/', () => HttpResponse.json(mockPrinters)),
  1620. http.get('/api/v1/archives/:id/plates', () => HttpResponse.json(PLATES)),
  1621. // The endpoint is plate-aware: no plate_id yields the whole-file union.
  1622. http.get('/api/v1/archives/:id/filament-requirements', ({ request }) => {
  1623. const plateId = new URL(request.url).searchParams.get('plate_id');
  1624. if (plateId === '1') return HttpResponse.json({ filaments: [SLOT_1_RED] });
  1625. if (plateId === '2') return HttpResponse.json({ filaments: [SLOT_2_RED] });
  1626. return HttpResponse.json({ filaments: [SLOT_1_RED, SLOT_2_RED] });
  1627. }),
  1628. http.get('/api/v1/printers/:id/status', () =>
  1629. HttpResponse.json({
  1630. connected: true,
  1631. state: 'IDLE',
  1632. ams: [{ id: 0, tray: [
  1633. { id: 0, tray_type: 'PLA', tray_color: 'FF0000' },
  1634. { id: 1, tray_type: 'PLA', tray_color: '000000' },
  1635. ] }],
  1636. vt_tray: [],
  1637. }),
  1638. ),
  1639. http.get('/api/v1/printers/:id/assignments', () => HttpResponse.json([])),
  1640. http.post('/api/v1/queue/', () => HttpResponse.json({ id: 1, status: 'pending' })),
  1641. );
  1642. });
  1643. const selectBothPlates = async (user: ReturnType<typeof userEvent.setup>) => {
  1644. await waitFor(() => expect(screen.getByText('X1 Carbon')).toBeInTheDocument());
  1645. await user.click(screen.getByText('X1 Carbon'));
  1646. await waitFor(() => expect(screen.getByText('Plate 2')).toBeInTheDocument());
  1647. await user.click(screen.getByText('Plate 2')); // Plate 1 is auto-selected
  1648. };
  1649. it('shows one mapping panel per selected plate, named after the plate', async () => {
  1650. const user = userEvent.setup();
  1651. render(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  1652. await selectBothPlates(user);
  1653. await waitFor(() => {
  1654. expect(screen.getByText(/Filament Mapping — Plate 1/)).toBeInTheDocument();
  1655. expect(screen.getByText(/Filament Mapping — Plate 2/)).toBeInTheDocument();
  1656. });
  1657. });
  1658. it('sends each plate the mapping for its own slots, not the whole-file union', async () => {
  1659. const queued: { plate_id: number; ams_mapping: number[] | null }[] = [];
  1660. server.use(
  1661. http.post('/api/v1/queue/', async ({ request }) => {
  1662. queued.push((await request.json()) as { plate_id: number; ams_mapping: number[] | null });
  1663. return HttpResponse.json({ id: queued.length, status: 'pending' });
  1664. }),
  1665. );
  1666. const user = userEvent.setup();
  1667. render(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  1668. await selectBothPlates(user);
  1669. await waitFor(() => expect(screen.getByText(/Filament Mapping — Plate 2/)).toBeInTheDocument());
  1670. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1671. await waitFor(() => expect(queued.length).toBe(2));
  1672. const plate1 = queued.find((q) => q.plate_id === 1);
  1673. const plate2 = queued.find((q) => q.plate_id === 2);
  1674. // Plate 1 prints slot 1 from the red tray.
  1675. expect(plate1?.ams_mapping).toEqual([0]);
  1676. // Plate 2 prints slot 2 from the SAME red tray — slot 1 is not its business.
  1677. // The union mapping would have been [0, 1], sending this plate to the black tray.
  1678. expect(plate2?.ams_mapping).toEqual([-1, 0]);
  1679. });
  1680. it('sends no mapping when several plates fan out across several printers', async () => {
  1681. // A tray id is meaningless on a different printer, so the first printer's
  1682. // mapping must not be handed to the second. The scheduler maps each plate
  1683. // against the printer it actually dispatches to.
  1684. const queued: { printer_id: number; ams_mapping?: number[] | null }[] = [];
  1685. server.use(
  1686. http.post('/api/v1/queue/', async ({ request }) => {
  1687. queued.push((await request.json()) as { printer_id: number; ams_mapping?: number[] | null });
  1688. return HttpResponse.json({ id: queued.length, status: 'pending' });
  1689. }),
  1690. );
  1691. const user = userEvent.setup();
  1692. render(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  1693. await waitFor(() => expect(screen.getByText('X1 Carbon')).toBeInTheDocument());
  1694. await user.click(screen.getByText('X1 Carbon'));
  1695. await user.click(screen.getByText('P1S'));
  1696. await waitFor(() => expect(screen.getByText('Plate 2')).toBeInTheDocument());
  1697. await user.click(screen.getByText('Plate 2'));
  1698. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1699. await waitFor(() => expect(queued.length).toBe(4)); // 2 plates x 2 printers
  1700. queued.forEach((q) => expect(q.ams_mapping ?? null).toBeNull());
  1701. });
  1702. it('sends no mapping for a model-assigned multi-plate job, leaving it to the scheduler', async () => {
  1703. const queued: { ams_mapping?: number[] | null }[] = [];
  1704. server.use(
  1705. http.post('/api/v1/queue/', async ({ request }) => {
  1706. queued.push((await request.json()) as { ams_mapping?: number[] | null });
  1707. return HttpResponse.json({ id: queued.length, status: 'pending' });
  1708. }),
  1709. );
  1710. const user = userEvent.setup();
  1711. render(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  1712. // "Any model" mode: no printer is chosen, so there is no AMS to map onto and
  1713. // the scheduler computes the mapping per plate once it picks one.
  1714. await waitFor(() => expect(screen.getByText('Plate 2')).toBeInTheDocument());
  1715. await user.click(screen.getByText('Plate 2'));
  1716. await user.click(screen.getByRole('button', { name: /any model/i }));
  1717. await waitFor(() => expect(screen.getByRole('combobox')).toBeInTheDocument());
  1718. await user.selectOptions(screen.getByRole('combobox'), 'X1C');
  1719. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1720. await waitFor(() => expect(queued.length).toBe(2));
  1721. queued.forEach((q) => expect(q.ams_mapping ?? null).toBeNull());
  1722. });
  1723. it('drops a plate\'s manual tray overrides when the printer changes', async () => {
  1724. // A manual override holds a global tray id, which names a different spool on a
  1725. // different printer. Carrying plate 1's "slot 1 -> tray 1" from the X1C over to
  1726. // the P1S would dispatch a tray the user never picked.
  1727. const queued: { plate_id: number; ams_mapping: number[] | null }[] = [];
  1728. server.use(
  1729. http.post('/api/v1/queue/', async ({ request }) => {
  1730. queued.push((await request.json()) as { plate_id: number; ams_mapping: number[] | null });
  1731. return HttpResponse.json({ id: queued.length, status: 'pending' });
  1732. }),
  1733. );
  1734. const user = userEvent.setup();
  1735. render(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  1736. await selectBothPlates(user);
  1737. await waitFor(() => expect(screen.getByText(/Filament Mapping — Plate 1/)).toBeInTheDocument());
  1738. // Force plate 1's slot 1 onto the black tray (1) instead of the auto-matched red (0).
  1739. // A2 is AMS 0 / tray 1, i.e. global tray id 1 — the value the old
  1740. // `selectOptions(..., '1')` picked.
  1741. await user.click(screen.getByText(/Filament Mapping — Plate 1/));
  1742. await pickFromSlotPicker(user, /printer slot for/i, /^A2:/);
  1743. // Now move the job to the other printer.
  1744. await user.click(screen.getByText('X1 Carbon')); // deselect
  1745. await user.click(screen.getByText('P1S'));
  1746. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1747. await waitFor(() => expect(queued.length).toBe(2));
  1748. // Plate 1 auto-matches red (tray 0) on the new printer. Tray 1 is the stale pick.
  1749. const plate1 = queued.find((q) => q.plate_id === 1);
  1750. expect(plate1?.ams_mapping).toEqual([0]);
  1751. });
  1752. it('sets Print Anyway only on the printers whose filament warning it answered', async () => {
  1753. // X1 Carbon is short on the mapped spool, P1S is not. Answering the warning
  1754. // for X1 Carbon must not wave P1S's job through the scheduler's own check.
  1755. const queued: { printer_id: number; skip_filament_check?: boolean }[] = [];
  1756. server.use(
  1757. http.get('/api/v1/printers/:id/inventory-remain', ({ params }) => {
  1758. const grams = params.id === '1' ? 10 : 1000;
  1759. return HttpResponse.json({
  1760. inventory_remain_g: { '0': grams },
  1761. slot_materials: [
  1762. { ams_id: 0, tray_id: 0, global_tray_id: 0, material_key: 'preset:GFA00|color:FF0000', remaining_g: grams, extruder: 0 },
  1763. ],
  1764. });
  1765. }),
  1766. http.post('/api/v1/queue/', async ({ request }) => {
  1767. queued.push((await request.json()) as { printer_id: number; skip_filament_check?: boolean });
  1768. return HttpResponse.json({ id: queued.length, status: 'pending' });
  1769. }),
  1770. );
  1771. const user = userEvent.setup();
  1772. render(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  1773. await waitFor(() => expect(screen.getByText('X1 Carbon')).toBeInTheDocument());
  1774. await user.click(screen.getByText('X1 Carbon'));
  1775. await user.click(screen.getByText('P1S'));
  1776. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1777. await waitFor(() => expect(screen.getByText(/Not enough filament/i)).toBeInTheDocument());
  1778. await user.click(screen.getByRole('button', { name: /print anyway/i }));
  1779. await waitFor(() => expect(queued.length).toBe(2));
  1780. const byPrinter = Object.fromEntries(queued.map((q) => [q.printer_id, q.skip_filament_check]));
  1781. expect(byPrinter).toEqual({ 1: true, 2: undefined });
  1782. });
  1783. it('sums what the plates draw from one spool before warning about it', async () => {
  1784. // Both plates map to the same red tray. 60 g left covers either plate on its
  1785. // own (40 g), but not both — the check has to add them up, not test them
  1786. // one at a time.
  1787. server.use(
  1788. http.get('/api/v1/archives/:id/filament-requirements', ({ request }) => {
  1789. const plateId = new URL(request.url).searchParams.get('plate_id');
  1790. if (plateId === '1') return HttpResponse.json({ filaments: [{ ...SLOT_1_RED, used_grams: 40 }] });
  1791. if (plateId === '2') return HttpResponse.json({ filaments: [{ ...SLOT_2_RED, used_grams: 40 }] });
  1792. return HttpResponse.json({ filaments: [SLOT_1_RED, SLOT_2_RED] });
  1793. }),
  1794. http.get('/api/v1/printers/:id/inventory-remain', () =>
  1795. HttpResponse.json({
  1796. inventory_remain_g: { '0': 60 },
  1797. slot_materials: [
  1798. { ams_id: 0, tray_id: 0, global_tray_id: 0, material_key: 'preset:GFA00|color:FF0000', remaining_g: 60, extruder: 0 },
  1799. ],
  1800. }),
  1801. ),
  1802. );
  1803. const user = userEvent.setup();
  1804. render(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  1805. await selectBothPlates(user);
  1806. await waitFor(() => expect(screen.getByText(/Filament Mapping — Plate 2/)).toBeInTheDocument());
  1807. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1808. // 80 g needed from a spool with 60 g left → the acknowledgement dialog, not a
  1809. // silent queue.
  1810. await waitFor(() => expect(screen.getByText(/Not enough filament/i)).toBeInTheDocument());
  1811. expect(screen.getByText(/needs 80g, remaining 60g/i)).toBeInTheDocument();
  1812. });
  1813. // Two red trays holding the same material, so AMS Filament Backup can switch
  1814. // between them mid-print. Both tests below map both plates onto tray 0.
  1815. const twoRedTrays = (backupOn: boolean) =>
  1816. http.get('/api/v1/printers/:id/status', () =>
  1817. HttpResponse.json({
  1818. connected: true,
  1819. state: 'IDLE',
  1820. ams_filament_backup: backupOn,
  1821. ams: [{ id: 0, tray: [
  1822. { id: 0, tray_type: 'PLA', tray_color: 'FF0000' },
  1823. { id: 1, tray_type: 'PLA', tray_color: 'FF0000' },
  1824. ] }],
  1825. vt_tray: [],
  1826. }),
  1827. );
  1828. const redPool = (trayZeroGrams: number, trayOneGrams: number) =>
  1829. http.get('/api/v1/printers/:id/inventory-remain', () =>
  1830. HttpResponse.json({
  1831. inventory_remain_g: { '0': trayZeroGrams, '1': trayOneGrams },
  1832. slot_materials: [
  1833. { ams_id: 0, tray_id: 0, global_tray_id: 0, material_key: 'preset:GFA00|color:FF0000', remaining_g: trayZeroGrams, extruder: 0 },
  1834. { ams_id: 0, tray_id: 1, global_tray_id: 1, material_key: 'preset:GFA00|color:FF0000', remaining_g: trayOneGrams, extruder: 0 },
  1835. ],
  1836. }),
  1837. );
  1838. const bothPlatesNeedForty = http.get('/api/v1/archives/:id/filament-requirements', ({ request }) => {
  1839. const plateId = new URL(request.url).searchParams.get('plate_id');
  1840. if (plateId === '1') return HttpResponse.json({ filaments: [{ ...SLOT_1_RED, used_grams: 40 }] });
  1841. if (plateId === '2') return HttpResponse.json({ filaments: [{ ...SLOT_2_RED, used_grams: 40 }] });
  1842. return HttpResponse.json({ filaments: [SLOT_1_RED, SLOT_2_RED] });
  1843. });
  1844. it('lets the print through when AMS Filament Backup covers it from a peer spool', async () => {
  1845. // The reported block: two plates draw 80 g from a tray holding 60 g, but the
  1846. // slot next to it holds the same material. The firmware switches between
  1847. // them, and the dispatcher has pooled them since #1762 — the modal used to
  1848. // weigh the mapped slot alone and refused a print the dispatcher would run.
  1849. const queued: unknown[] = [];
  1850. server.use(
  1851. bothPlatesNeedForty,
  1852. twoRedTrays(true),
  1853. redPool(60, 1000),
  1854. http.post('/api/v1/queue/', async ({ request }) => {
  1855. queued.push(await request.json());
  1856. return HttpResponse.json({ id: queued.length, status: 'pending' });
  1857. }),
  1858. );
  1859. const user = userEvent.setup();
  1860. render(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  1861. await selectBothPlates(user);
  1862. await waitFor(() => expect(screen.getByText(/Filament Mapping — Plate 2/)).toBeInTheDocument());
  1863. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1864. await waitFor(() => expect(queued.length).toBe(2));
  1865. expect(screen.queryByText(/Not enough filament/i)).not.toBeInTheDocument();
  1866. });
  1867. it('warns against the pooled total when AMS Filament Backup still cannot cover it', async () => {
  1868. // Backup is on but both spools together are short. The shortfall is real, so
  1869. // it still has to be raised — against the pool, not the one slot, or the
  1870. // numbers contradict the AMS the user is looking at.
  1871. server.use(bothPlatesNeedForty, twoRedTrays(true), redPool(60, 10));
  1872. const user = userEvent.setup();
  1873. render(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  1874. await selectBothPlates(user);
  1875. await waitFor(() => expect(screen.getByText(/Filament Mapping — Plate 2/)).toBeInTheDocument());
  1876. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1877. await waitFor(() => expect(screen.getByText(/Not enough filament/i)).toBeInTheDocument());
  1878. expect(screen.getByText(/needs 80g, 70g available across matching spools/i)).toBeInTheDocument();
  1879. });
  1880. it('keeps weighing the mapped slot alone when AMS Filament Backup is off', async () => {
  1881. // Same two spools, backup off: the firmware will not switch, so the peer's
  1882. // grams are not available to this print and the warning must still fire.
  1883. server.use(bothPlatesNeedForty, twoRedTrays(false), redPool(60, 1000));
  1884. const user = userEvent.setup();
  1885. render(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  1886. await selectBothPlates(user);
  1887. await waitFor(() => expect(screen.getByText(/Filament Mapping — Plate 2/)).toBeInTheDocument());
  1888. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1889. await waitFor(() => expect(screen.getByText(/Not enough filament/i)).toBeInTheDocument());
  1890. expect(screen.getByText(/needs 80g, remaining 60g/i)).toBeInTheDocument();
  1891. });
  1892. it('holds the Print button until every selected plate has answered', async () => {
  1893. // A plate whose filaments cannot be read has no mapping and no forced colours;
  1894. // queueing it anyway prints it in whatever happens to be loaded.
  1895. server.use(
  1896. http.get('/api/v1/archives/:id/filament-requirements', ({ request }) => {
  1897. const plateId = new URL(request.url).searchParams.get('plate_id');
  1898. if (plateId === '1') return HttpResponse.json({ filaments: [SLOT_1_RED] });
  1899. if (plateId === '2') return new HttpResponse(null, { status: 500 });
  1900. return HttpResponse.json({ filaments: [SLOT_1_RED, SLOT_2_RED] });
  1901. }),
  1902. );
  1903. const user = userEvent.setup();
  1904. render(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  1905. await selectBothPlates(user);
  1906. await waitFor(() =>
  1907. expect(document.querySelector('button[type="submit"]')).toBeDisabled(),
  1908. );
  1909. expect(screen.getByText(/could not be read/i)).toBeInTheDocument();
  1910. // Deselecting the unreadable plate frees the rest of the job.
  1911. await user.click(screen.getByText('Plate 2'));
  1912. await waitFor(() =>
  1913. expect(document.querySelector('button[type="submit"]')).not.toBeDisabled(),
  1914. );
  1915. });
  1916. });
  1917. describe('PrintModal — per-plate filament override in model mode (#2552)', () => {
  1918. const mockOnClose = vi.fn();
  1919. // The reporter's trigger — "only after the file was previously queued or printed"
  1920. // — is really "only once the plates query is warm in the cache". On a cold cache
  1921. // the plates data is undefined for the first render, so the whole-file filament
  1922. // requirements are fetched and left behind; the override panel then rendered from
  1923. // that union. On a warm cache the modal knows it is multi-plate from the first
  1924. // render, the whole-file query never runs, and the panel disappeared entirely.
  1925. // Both states are exercised here, and neither may depend on the cache.
  1926. const renderWithCache = (ui: React.ReactElement, prewarm?: (qc: QueryClient) => void) => {
  1927. const queryClient = new QueryClient({
  1928. defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
  1929. });
  1930. prewarm?.(queryClient);
  1931. return rtlRender(
  1932. <QueryClientProvider client={queryClient}>
  1933. <BrowserRouter>
  1934. <AuthProvider>
  1935. <ThemeProvider>
  1936. <ToastProvider>{ui}</ToastProvider>
  1937. </ThemeProvider>
  1938. </AuthProvider>
  1939. </BrowserRouter>
  1940. </QueryClientProvider>,
  1941. );
  1942. };
  1943. // Plate 1 prints slot 1 (red), plate 2 prints slot 2 (blue). Nothing is shared.
  1944. const PLATES = {
  1945. is_multi_plate: true,
  1946. plates: [
  1947. { index: 1, name: 'Plate 1', has_thumbnail: false, thumbnail_url: null, objects: ['A'], filaments: [{ type: 'PLA', color: '#FF0000' }], print_time_seconds: 1800, filament_used_grams: 50 },
  1948. { index: 2, name: 'Plate 2', has_thumbnail: false, thumbnail_url: null, objects: ['B'], filaments: [{ type: 'PLA', color: '#0000FF' }], print_time_seconds: 1800, filament_used_grams: 50 },
  1949. ],
  1950. };
  1951. const SLOT_1_RED = { slot_id: 1, type: 'PLA', color: '#FF0000', tray_info_idx: '', used_grams: 50 };
  1952. const SLOT_2_BLUE = { slot_id: 2, type: 'PLA', color: '#0000FF', tray_info_idx: '', used_grams: 50 };
  1953. beforeEach(() => {
  1954. vi.clearAllMocks();
  1955. server.use(
  1956. http.get('/api/v1/printers/', () => HttpResponse.json(mockPrinters)),
  1957. http.get('/api/v1/archives/:id/plates', () => HttpResponse.json(PLATES)),
  1958. http.get('/api/v1/archives/:id/filament-requirements', ({ request }) => {
  1959. const plateId = new URL(request.url).searchParams.get('plate_id');
  1960. if (plateId === '1') return HttpResponse.json({ filaments: [SLOT_1_RED] });
  1961. if (plateId === '2') return HttpResponse.json({ filaments: [SLOT_2_BLUE] });
  1962. return HttpResponse.json({ filaments: [SLOT_1_RED, SLOT_2_BLUE] });
  1963. }),
  1964. http.get('/api/v1/printers/available-filaments', () =>
  1965. HttpResponse.json([
  1966. { type: 'PLA', color: '#FF0000', tray_info_idx: 'GFA00', tray_sub_brands: 'PLA Basic', extruder_id: null },
  1967. { type: 'PLA', color: '#00FF00', tray_info_idx: 'GFA00', tray_sub_brands: 'PLA Basic', extruder_id: null },
  1968. ]),
  1969. ),
  1970. http.post('/api/v1/queue/', () => HttpResponse.json({ id: 1, status: 'pending' })),
  1971. );
  1972. });
  1973. const selectAnyX1CAndBothPlates = async (user: ReturnType<typeof userEvent.setup>) => {
  1974. await waitFor(() => expect(screen.getByText('Plate 2')).toBeInTheDocument());
  1975. await user.click(screen.getByText('Plate 2')); // Plate 1 is auto-selected
  1976. await user.click(screen.getByRole('button', { name: /any model/i }));
  1977. // Switching to model mode pre-selects the first model, so the override panels
  1978. // are already up; the target-model select is the one offering the models.
  1979. const modelSelect = await waitFor(() => {
  1980. const select = screen
  1981. .getAllByRole('combobox')
  1982. .find((el) => (el as HTMLSelectElement).options[0]?.value === '' && (el as HTMLSelectElement).options[0]?.text === 'Select a model...');
  1983. if (!select) throw new Error('target model select not rendered');
  1984. return select as HTMLSelectElement;
  1985. });
  1986. await user.selectOptions(modelSelect, 'X1C');
  1987. };
  1988. it('shows one override panel per selected plate even when the plates query is already cached', async () => {
  1989. const user = userEvent.setup();
  1990. renderWithCache(
  1991. <PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />,
  1992. // The file has been opened before: the plates are known on the first render,
  1993. // so the whole-file requirements query never runs. This is the state in which
  1994. // the override section used to vanish for a multi-plate selection.
  1995. (qc) => qc.setQueryData(['archive-plates', 1], PLATES),
  1996. );
  1997. await selectAnyX1CAndBothPlates(user);
  1998. await waitFor(() => {
  1999. expect(screen.getByText(/Filament Override — Plate 1/)).toBeInTheDocument();
  2000. expect(screen.getByText(/Filament Override — Plate 2/)).toBeInTheDocument();
  2001. });
  2002. });
  2003. it('shows the same per-plate panels on a cold cache', async () => {
  2004. const user = userEvent.setup();
  2005. renderWithCache(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  2006. await selectAnyX1CAndBothPlates(user);
  2007. await waitFor(() => {
  2008. expect(screen.getByText(/Filament Override — Plate 1/)).toBeInTheDocument();
  2009. expect(screen.getByText(/Filament Override — Plate 2/)).toBeInTheDocument();
  2010. });
  2011. // Not the whole-file union in a single unnamed panel.
  2012. expect(screen.queryByText('Filament Override')).not.toBeInTheDocument();
  2013. });
  2014. it('sends each plate only the overrides for the slots it prints', async () => {
  2015. type Queued = {
  2016. plate_id: number;
  2017. filament_overrides?: Array<{ slot_id: number; force_color_match: boolean }> | null;
  2018. };
  2019. const queued: Queued[] = [];
  2020. server.use(
  2021. http.post('/api/v1/queue/', async ({ request }) => {
  2022. queued.push((await request.json()) as Queued);
  2023. return HttpResponse.json({ id: queued.length, status: 'pending' });
  2024. }),
  2025. );
  2026. const user = userEvent.setup();
  2027. renderWithCache(
  2028. <PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />,
  2029. (qc) => qc.setQueryData(['archive-plates', 1], PLATES),
  2030. );
  2031. await selectAnyX1CAndBothPlates(user);
  2032. await waitFor(() => expect(screen.getByText(/Filament Override — Plate 2/)).toBeInTheDocument());
  2033. // Force the colour on plate 2's only slot. Plate 1 does not print slot 2 and
  2034. // must not be held back waiting for a blue spool it never uses (#2551).
  2035. const forceBoxes = screen.getAllByRole('checkbox', { name: /force color match/i });
  2036. expect(forceBoxes).toHaveLength(2); // one slot per plate
  2037. await user.click(forceBoxes[1]);
  2038. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  2039. await waitFor(() => expect(queued.length).toBe(2));
  2040. const plate1 = queued.find((q) => q.plate_id === 1);
  2041. const plate2 = queued.find((q) => q.plate_id === 2);
  2042. expect(plate1?.filament_overrides ?? null).toBeNull();
  2043. expect(plate2?.filament_overrides).toEqual([
  2044. expect.objectContaining({ slot_id: 2, force_color_match: true }),
  2045. ]);
  2046. });
  2047. // The queue page shows the stored colour name. The same blue is "Marine
  2048. // Blue" in PLA Matte; the plain type "PLA" only reaches the generic name (SN-C9).
  2049. it("stores a forced slot's colour name within its sliced product line", async () => {
  2050. setColorCatalog({ '0000ff': 'Blue' }, { 'PLA Matte|0000ff': 'Marine Blue' });
  2051. type Queued = { plate_id: number; filament_overrides?: Array<{ slot_id: number; color_name?: string }> | null };
  2052. const queued: Queued[] = [];
  2053. server.use(
  2054. http.get('/api/v1/archives/:id/filament-requirements', () =>
  2055. HttpResponse.json({ filaments: [{ ...SLOT_2_BLUE, tray_info_idx: 'GFA01' }] }),
  2056. ),
  2057. http.get('/api/v1/cloud/builtin-filaments', () =>
  2058. HttpResponse.json([{ filament_id: 'GFA01', name: 'Bambu PLA Matte' }]),
  2059. ),
  2060. http.get('/api/v1/cloud/filament-id-map', () => HttpResponse.json({})),
  2061. http.post('/api/v1/queue/', async ({ request }) => {
  2062. queued.push((await request.json()) as Queued);
  2063. return HttpResponse.json({ id: queued.length, status: 'pending' });
  2064. }),
  2065. );
  2066. try {
  2067. const user = userEvent.setup();
  2068. renderWithCache(
  2069. <PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />,
  2070. (qc) => qc.setQueryData(['archive-plates', 1], PLATES),
  2071. );
  2072. await selectAnyX1CAndBothPlates(user);
  2073. await waitFor(() => expect(screen.getByText(/Filament Override — Plate 2/)).toBeInTheDocument());
  2074. // Wait for the preset names, which the stored colour name is derived from.
  2075. await waitFor(() => expect(screen.getAllByText(/PLA Matte/).length).toBeGreaterThan(0));
  2076. await user.click(screen.getAllByRole('checkbox', { name: /force color match/i })[1]);
  2077. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  2078. await waitFor(() => expect(queued.length).toBe(2));
  2079. expect(queued.find((q) => q.plate_id === 2)?.filament_overrides).toEqual([
  2080. expect.objectContaining({ slot_id: 2, color_name: 'Marine Blue' }),
  2081. ]);
  2082. } finally {
  2083. __resetColorCatalogForTests();
  2084. }
  2085. });
  2086. it("does not name a swapped slot's colour by the preset it was sliced with", async () => {
  2087. setColorCatalog({ '00ff00': 'Green' }, { 'PLA Matte|00ff00': 'Matte Green' });
  2088. type Queued = { plate_id: number; filament_overrides?: Array<{ slot_id: number; color_name?: string }> | null };
  2089. const queued: Queued[] = [];
  2090. server.use(
  2091. http.get('/api/v1/archives/:id/filament-requirements', () =>
  2092. HttpResponse.json({ filaments: [{ ...SLOT_2_BLUE, tray_info_idx: 'GFA01' }] }),
  2093. ),
  2094. http.get('/api/v1/cloud/builtin-filaments', () =>
  2095. HttpResponse.json([{ filament_id: 'GFA01', name: 'Bambu PLA Matte' }]),
  2096. ),
  2097. http.get('/api/v1/cloud/filament-id-map', () => HttpResponse.json({})),
  2098. http.post('/api/v1/queue/', async ({ request }) => {
  2099. queued.push((await request.json()) as Queued);
  2100. return HttpResponse.json({ id: queued.length, status: 'pending' });
  2101. }),
  2102. );
  2103. try {
  2104. const user = userEvent.setup();
  2105. renderWithCache(
  2106. <PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />,
  2107. (qc) => qc.setQueryData(['archive-plates', 1], PLATES),
  2108. );
  2109. await selectAnyX1CAndBothPlates(user);
  2110. await waitFor(() => expect(screen.getByText(/Filament Override — Plate 2/)).toBeInTheDocument());
  2111. await waitFor(() => expect(screen.getAllByText(/PLA Matte/).length).toBeGreaterThan(0));
  2112. // Swap the PLA Matte blue for the loaded PLA Basic green.
  2113. const pickers = screen.getAllByRole('combobox', { name: /filament override for/i });
  2114. await user.click(pickers[pickers.length - 1]);
  2115. await user.click(within(await screen.findByRole('listbox')).getByText(/Green/));
  2116. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  2117. await waitFor(() => expect(queued.length).toBe(2));
  2118. expect(queued.find((q) => q.plate_id === 2)?.filament_overrides).toEqual([
  2119. expect.objectContaining({ slot_id: 2, color: '#00FF00', color_name: 'Green' }),
  2120. ]);
  2121. } finally {
  2122. __resetColorCatalogForTests();
  2123. }
  2124. });
  2125. });
  2126. describe('PrintModal — per-plate quantity (#342)', () => {
  2127. const mockOnClose = vi.fn();
  2128. const PLATES = {
  2129. is_multi_plate: true,
  2130. plates: [
  2131. { index: 1, name: 'Plate 1', has_thumbnail: false, thumbnail_url: null, objects: ['A'], filaments: [{ type: 'PLA', color: '#FF0000' }], print_time_seconds: 1800, filament_used_grams: 50 },
  2132. { index: 2, name: 'Plate 2', has_thumbnail: false, thumbnail_url: null, objects: ['B'], filaments: [{ type: 'PLA', color: '#FF0000' }], print_time_seconds: 1800, filament_used_grams: 50 },
  2133. { index: 3, name: 'Plate 3', has_thumbnail: false, thumbnail_url: null, objects: ['C'], filaments: [{ type: 'PLA', color: '#FF0000' }], print_time_seconds: 1800, filament_used_grams: 50 },
  2134. ],
  2135. };
  2136. const renderModal = (ui: React.ReactElement) => {
  2137. const queryClient = new QueryClient({
  2138. defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
  2139. });
  2140. queryClient.setQueryData(['archive-plates', 1], PLATES);
  2141. return rtlRender(
  2142. <QueryClientProvider client={queryClient}>
  2143. <BrowserRouter>
  2144. <AuthProvider>
  2145. <ThemeProvider>
  2146. <ToastProvider>{ui}</ToastProvider>
  2147. </ThemeProvider>
  2148. </AuthProvider>
  2149. </BrowserRouter>
  2150. </QueryClientProvider>,
  2151. );
  2152. };
  2153. beforeEach(() => {
  2154. vi.clearAllMocks();
  2155. server.use(
  2156. http.get('/api/v1/printers/', () => HttpResponse.json(mockPrinters)),
  2157. http.get('/api/v1/archives/:id/plates', () => HttpResponse.json(PLATES)),
  2158. http.get('/api/v1/archives/:id/filament-requirements', () =>
  2159. HttpResponse.json({ filaments: [{ slot_id: 1, type: 'PLA', color: '#FF0000', tray_info_idx: '', used_grams: 50 }] }),
  2160. ),
  2161. http.get('/api/v1/printers/available-filaments', () => HttpResponse.json([])),
  2162. http.post('/api/v1/queue/batches', () => HttpResponse.json({ id: 42, name: 'Order', status: 'active' })),
  2163. http.post('/api/v1/queue/', () => HttpResponse.json({ id: 1, status: 'pending' })),
  2164. );
  2165. });
  2166. const qtyInput = (plateName: string) =>
  2167. screen.getByRole('spinbutton', { name: new RegExp(plateName, 'i') });
  2168. it('replaces the single Quantity field with one control per selected plate', async () => {
  2169. const user = userEvent.setup();
  2170. renderModal(<PrintModal mode="create" archiveId={1} archiveName="Three.gcode.3mf" onClose={mockOnClose} />);
  2171. await waitFor(() => expect(screen.getByText('Plate 2')).toBeInTheDocument());
  2172. // Plate 1 is auto-selected and already carries its own quantity control.
  2173. expect(qtyInput('Plate 1')).toBeInTheDocument();
  2174. // The global field is gone — two controls for the same number would be ambiguous.
  2175. expect(screen.queryByLabelText(/^Quantity$/i)).not.toBeInTheDocument();
  2176. // Unselected plates have no control.
  2177. expect(screen.queryByRole('spinbutton', { name: /Plate 2/i })).not.toBeInTheDocument();
  2178. await user.click(screen.getByText('Plate 2'));
  2179. await waitFor(() => expect(qtyInput('Plate 2')).toBeInTheDocument());
  2180. });
  2181. it('keeps the single Quantity field for a single-plate file', async () => {
  2182. const queryClient = new QueryClient({
  2183. defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
  2184. });
  2185. queryClient.setQueryData(['archive-plates', 1], { is_multi_plate: false, plates: [] });
  2186. rtlRender(
  2187. <QueryClientProvider client={queryClient}>
  2188. <BrowserRouter>
  2189. <AuthProvider>
  2190. <ThemeProvider>
  2191. <ToastProvider>
  2192. <PrintModal mode="create" archiveId={1} archiveName="One.gcode.3mf" onClose={mockOnClose} />
  2193. </ToastProvider>
  2194. </ThemeProvider>
  2195. </AuthProvider>
  2196. </BrowserRouter>
  2197. </QueryClientProvider>,
  2198. );
  2199. await waitFor(() => expect(screen.getByLabelText(/^Quantity$/i)).toBeInTheDocument());
  2200. });
  2201. it('queues the reporter\'s example: plate 1 once, plate 2 twice, plate 3 three times', async () => {
  2202. type Queued = { plate_id: number | null; quantity?: number; batch_id?: number };
  2203. type OrderBody = { plates?: Array<{ plate_id: number | null; quantity_target: number }> };
  2204. const queued: Queued[] = [];
  2205. let order: OrderBody | null = null;
  2206. server.use(
  2207. http.post('/api/v1/queue/batches', async ({ request }) => {
  2208. order = (await request.json()) as OrderBody;
  2209. return HttpResponse.json({ id: 42, name: 'Order', status: 'active' });
  2210. }),
  2211. http.post('/api/v1/queue/', async ({ request }) => {
  2212. queued.push((await request.json()) as Queued);
  2213. return HttpResponse.json({ id: queued.length, status: 'pending' });
  2214. }),
  2215. );
  2216. const user = userEvent.setup();
  2217. renderModal(<PrintModal mode="create" archiveId={1} archiveName="Three.gcode.3mf" onClose={mockOnClose} />);
  2218. await waitFor(() => expect(screen.getByText('Plate 2')).toBeInTheDocument());
  2219. await user.click(screen.getByText('Plate 2'));
  2220. await user.click(screen.getByText('Plate 3'));
  2221. fireEvent.change(qtyInput('Plate 2'), { target: { value: '2' } });
  2222. fireEvent.change(qtyInput('Plate 3'), { target: { value: '3' } });
  2223. await waitFor(() => expect(screen.getByText(/6 runs in total/i)).toBeInTheDocument());
  2224. await user.click(screen.getAllByRole('button', { name: /X1 Carbon/i })[0]);
  2225. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  2226. await waitFor(() => expect(queued.length).toBe(3));
  2227. // The order records the intent, so a failed run still reads as owed.
  2228. expect(order!.plates).toEqual([
  2229. expect.objectContaining({ plate_id: 1, quantity_target: 1 }),
  2230. expect.objectContaining({ plate_id: 2, quantity_target: 2 }),
  2231. expect.objectContaining({ plate_id: 3, quantity_target: 3 }),
  2232. ]);
  2233. // ...and the runs are dispatched immediately, one call per plate carrying
  2234. // that plate's own count. Quantity 1 is left off the payload as before.
  2235. const byPlate = Object.fromEntries(queued.map((q) => [q.plate_id, q]));
  2236. expect(byPlate[1].quantity).toBeUndefined();
  2237. expect(byPlate[2].quantity).toBe(2);
  2238. expect(byPlate[3].quantity).toBe(3);
  2239. expect(queued.every((q) => q.batch_id === 42)).toBe(true);
  2240. });
  2241. it('does not multiply per-plate counts across a multi-printer fan-out', async () => {
  2242. type Queued = { plate_id: number | null; quantity?: number; printer_id: number | null };
  2243. const queued: Queued[] = [];
  2244. server.use(
  2245. http.post('/api/v1/queue/', async ({ request }) => {
  2246. queued.push((await request.json()) as Queued);
  2247. return HttpResponse.json({ id: queued.length, status: 'pending' });
  2248. }),
  2249. );
  2250. const user = userEvent.setup();
  2251. renderModal(<PrintModal mode="create" archiveId={1} archiveName="Three.gcode.3mf" onClose={mockOnClose} />);
  2252. await waitFor(() => expect(screen.getByText('Plate 2')).toBeInTheDocument());
  2253. await user.click(screen.getByText('Plate 2'));
  2254. fireEvent.change(qtyInput('Plate 2'), { target: { value: '4' } });
  2255. // Two printers: the printer count already answers "how many".
  2256. await user.click(screen.getAllByRole('button', { name: /X1 Carbon/i })[0]);
  2257. await user.click(screen.getAllByRole('button', { name: /P1S/i })[0]);
  2258. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  2259. await waitFor(() => expect(queued.length).toBe(4)); // 2 plates × 2 printers
  2260. expect(queued.every((q) => q.quantity === undefined)).toBe(true);
  2261. });
  2262. });
  2263. describe('PrintModal — override survives "Any model" -> "Specific Printer" (#3133)', () => {
  2264. const mockOnClose = vi.fn();
  2265. const PRINTERS = [
  2266. { id: 1, name: 'Printer 01', model: 'P2S', ip_address: '192.168.1.101', enabled: true, is_active: true },
  2267. { id: 2, name: 'Printer 02', model: 'X1C', ip_address: '192.168.1.102', enabled: true, is_active: true },
  2268. ];
  2269. const BROWN = '#8B4513';
  2270. const BONE_WHITE = '#F5F5DC';
  2271. // The 3MF was sliced in brown; the user asked for Bone White.
  2272. const SLOT_1_BROWN = { slot_id: 1, type: 'PLA', color: BROWN, tray_info_idx: 'GFA00', used_grams: 50 };
  2273. type Patched = {
  2274. printer_id?: number | null;
  2275. target_model?: string | null;
  2276. ams_mapping?: number[] | null;
  2277. filament_overrides?: Array<{ slot_id: number; type: string; color: string }> | null;
  2278. };
  2279. let patched: Patched[];
  2280. let posted: Patched[];
  2281. const statusWith = (trays: Array<{ id: number; tray_type: string; tray_color: string }>) =>
  2282. HttpResponse.json({ connected: true, state: 'IDLE', ams: [{ id: 0, tray: trays }], vt_tray: [] });
  2283. beforeEach(() => {
  2284. vi.clearAllMocks();
  2285. patched = [];
  2286. posted = [];
  2287. server.use(
  2288. http.get('/api/v1/printers/', () => HttpResponse.json(PRINTERS)),
  2289. http.get('/api/v1/archives/:id/plates', () => HttpResponse.json({ is_multi_plate: false, plates: [] })),
  2290. http.get('/api/v1/archives/:id/filament-requirements', () => HttpResponse.json({ filaments: [SLOT_1_BROWN] })),
  2291. http.get('/api/v1/printers/available-filaments', () =>
  2292. HttpResponse.json([
  2293. { type: 'PLA', color: BROWN, tray_info_idx: 'GFA00', tray_sub_brands: 'PLA Basic', extruder_id: null },
  2294. { type: 'PLA', color: BONE_WHITE, tray_info_idx: 'GFA00', tray_sub_brands: 'PLA Basic', extruder_id: null },
  2295. ]),
  2296. ),
  2297. // Printer 01 has both colours loaded; brown is first, so a match against
  2298. // the 3MF picks tray 0 and a match against the override picks tray 1.
  2299. http.get('/api/v1/printers/:id/status', () =>
  2300. statusWith([
  2301. { id: 0, tray_type: 'PLA', tray_color: '8B4513FF' },
  2302. { id: 1, tray_type: 'PLA', tray_color: 'F5F5DCFF' },
  2303. ]),
  2304. ),
  2305. http.get('/api/v1/printers/:id/assignments', () => HttpResponse.json([])),
  2306. http.patch('/api/v1/queue/:id', async ({ request }) => {
  2307. patched.push((await request.json()) as Patched);
  2308. return HttpResponse.json({ id: 1, status: 'pending' });
  2309. }),
  2310. http.post('/api/v1/queue/', async ({ request }) => {
  2311. posted.push((await request.json()) as Patched);
  2312. return HttpResponse.json({ id: 1, status: 'pending' });
  2313. }),
  2314. );
  2315. });
  2316. const anyP2SItem = () =>
  2317. createMockQueueItem({
  2318. printer_id: null,
  2319. target_model: 'P2S',
  2320. filament_overrides: [{ slot_id: 1, type: 'PLA', color: BONE_WHITE, force_color_match: false }],
  2321. } as Partial<PrintQueueItem>);
  2322. const moveToPrinter01 = async (user: ReturnType<typeof userEvent.setup>) => {
  2323. await user.click(await screen.findByRole('button', { name: /specific printer/i }));
  2324. await user.click(await screen.findByText('Printer 01'));
  2325. };
  2326. const submit = async (user: ReturnType<typeof userEvent.setup>) => {
  2327. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  2328. };
  2329. // The slot picker's list is portaled to <body>, outside the dialog's own
  2330. // DOM, and the dialog closes both on a click outside itself and on Escape.
  2331. // Either would be a bad regression: picking a slot, or dismissing the list,
  2332. // would throw away everything typed into the dialog (#3159).
  2333. it('does not close the dialog when a slot is picked from the portaled list', async () => {
  2334. const user = userEvent.setup();
  2335. render(<PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={anyP2SItem()} onClose={mockOnClose} />);
  2336. await moveToPrinter01(user);
  2337. // The panel is collapsed by default; the picker only exists once open.
  2338. await user.click(await screen.findByText(/filament mapping/i));
  2339. const trigger = await screen.findByRole('combobox', { name: /printer slot for/i });
  2340. await user.click(trigger);
  2341. const listbox = await screen.findByRole('listbox');
  2342. await user.click(within(listbox).getAllByRole('option')[1]);
  2343. expect(mockOnClose).not.toHaveBeenCalled();
  2344. expect(screen.getByText(/filament mapping/i)).toBeInTheDocument();
  2345. });
  2346. it('closes only the slot list on Escape, not the dialog', async () => {
  2347. const user = userEvent.setup();
  2348. render(<PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={anyP2SItem()} onClose={mockOnClose} />);
  2349. await moveToPrinter01(user);
  2350. await user.click(await screen.findByText(/filament mapping/i));
  2351. await user.click(await screen.findByRole('combobox', { name: /printer slot for/i }));
  2352. await screen.findByRole('listbox');
  2353. await user.keyboard('{Escape}');
  2354. await waitFor(() => expect(screen.queryByRole('listbox')).not.toBeInTheDocument());
  2355. expect(mockOnClose).not.toHaveBeenCalled();
  2356. // And a second Escape, with no list open, still closes the dialog — the
  2357. // picker must not have swallowed the key permanently.
  2358. await user.keyboard('{Escape}');
  2359. expect(mockOnClose).toHaveBeenCalled();
  2360. });
  2361. it('matches the chosen printer against the override and keeps it on the item', async () => {
  2362. const user = userEvent.setup();
  2363. render(<PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={anyP2SItem()} onClose={mockOnClose} />);
  2364. await moveToPrinter01(user);
  2365. // Wait for the mapping to settle on the printer's trays before saving.
  2366. await waitFor(() => expect(screen.getByText(/filament mapping/i)).toBeInTheDocument());
  2367. await submit(user);
  2368. await waitFor(() => expect(patched).toHaveLength(1));
  2369. expect(patched[0].printer_id).toBe(1);
  2370. expect(patched[0].target_model).toBeNull();
  2371. // Tray 1 is the Bone White spool. Matching the 3MF would have taken tray 0.
  2372. expect(patched[0].ams_mapping).toEqual([1]);
  2373. expect(patched[0].filament_overrides).toEqual([
  2374. expect.objectContaining({ slot_id: 1, type: 'PLA', color: BONE_WHITE }),
  2375. ]);
  2376. });
  2377. it('keeps the requested colour when the printer has no such spool', async () => {
  2378. server.use(
  2379. http.get('/api/v1/printers/:id/status', () =>
  2380. statusWith([
  2381. { id: 0, tray_type: 'PLA', tray_color: '8B4513FF' },
  2382. { id: 1, tray_type: 'PLA', tray_color: '000000FF' },
  2383. ]),
  2384. ),
  2385. );
  2386. const user = userEvent.setup();
  2387. render(<PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={anyP2SItem()} onClose={mockOnClose} />);
  2388. await moveToPrinter01(user);
  2389. await waitFor(() => expect(screen.getByText(/filament mapping/i)).toBeInTheDocument());
  2390. await submit(user);
  2391. await waitFor(() => expect(patched).toHaveLength(1));
  2392. // Still asked for, so the scheduler's recompute at dispatch looks for it too
  2393. // instead of settling on the brown the 3MF was sliced with.
  2394. expect(patched[0].filament_overrides).toEqual([
  2395. expect.objectContaining({ slot_id: 1, color: BONE_WHITE }),
  2396. ]);
  2397. });
  2398. it('still drops the override when the job moves to a different model', async () => {
  2399. const user = userEvent.setup();
  2400. render(<PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={anyP2SItem()} onClose={mockOnClose} />);
  2401. const modelSelect = await waitFor(() => {
  2402. const select = screen
  2403. .getAllByRole('combobox')
  2404. .find((el) => (el as HTMLSelectElement).options[0]?.text === 'Select a model...');
  2405. if (!select) throw new Error('target model select not rendered');
  2406. return select as HTMLSelectElement;
  2407. });
  2408. // The override was picked from P2S's loaded filaments; X1C's are another list.
  2409. await user.selectOptions(modelSelect, 'X1C');
  2410. await submit(user);
  2411. await waitFor(() => expect(patched).toHaveLength(1));
  2412. expect(patched[0].target_model).toBe('X1C');
  2413. expect(patched[0].filament_overrides ?? null).toBeNull();
  2414. });
  2415. it("keeps a virtual printer's variant pin when its specific-printer job is saved", async () => {
  2416. // A VP with force colour on writes the 3MF's own filament back as an
  2417. // override, tray_info_idx included, to tell PLA variants apart (#2650). Two
  2418. // brown trays differ only by variant; the job was sliced for Matte (GFA01).
  2419. server.use(
  2420. http.get('/api/v1/archives/:id/filament-requirements', () =>
  2421. HttpResponse.json({ filaments: [{ ...SLOT_1_BROWN, tray_info_idx: 'GFA01' }] }),
  2422. ),
  2423. http.get('/api/v1/printers/:id/status', () =>
  2424. HttpResponse.json({
  2425. connected: true,
  2426. state: 'IDLE',
  2427. ams: [{ id: 0, tray: [
  2428. { id: 0, tray_type: 'PLA', tray_color: '8B4513FF', tray_info_idx: 'GFA00' },
  2429. { id: 1, tray_type: 'PLA', tray_color: '8B4513FF', tray_info_idx: 'GFA01' },
  2430. ] }],
  2431. vt_tray: [],
  2432. }),
  2433. ),
  2434. );
  2435. const vpItem = createMockQueueItem({
  2436. printer_id: 1,
  2437. target_model: null,
  2438. filament_overrides: [
  2439. { slot_id: 1, type: 'PLA', color: BROWN, tray_info_idx: 'GFA01', force_color_match: true },
  2440. ],
  2441. } as Partial<PrintQueueItem>);
  2442. const user = userEvent.setup();
  2443. render(<PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={vpItem} onClose={mockOnClose} />);
  2444. await waitFor(() => expect(screen.getByText(/filament mapping/i)).toBeInTheDocument());
  2445. await submit(user);
  2446. await waitFor(() => expect(patched).toHaveLength(1));
  2447. // Not treated as a swap: the matcher still pins the Matte tray...
  2448. expect(patched[0].ams_mapping).toEqual([1]);
  2449. // ...and the row keeps the pin rather than losing it on save.
  2450. expect(patched[0].filament_overrides).toEqual([
  2451. expect.objectContaining({ slot_id: 1, color: BROWN, tray_info_idx: 'GFA01', force_color_match: true }),
  2452. ]);
  2453. });
  2454. it("keeps a virtual printer's variant pin when its any-model job is saved", async () => {
  2455. const vpItem = createMockQueueItem({
  2456. printer_id: null,
  2457. target_model: 'P2S',
  2458. filament_overrides: [
  2459. { slot_id: 1, type: 'PLA', color: BROWN, tray_info_idx: 'GFA01', force_color_match: true },
  2460. ],
  2461. } as Partial<PrintQueueItem>);
  2462. const user = userEvent.setup();
  2463. render(<PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={vpItem} onClose={mockOnClose} />);
  2464. await waitFor(() => expect(screen.getByText('Filament Override')).toBeInTheDocument());
  2465. await submit(user);
  2466. await waitFor(() => expect(patched).toHaveLength(1));
  2467. expect(patched[0].target_model).toBe('P2S');
  2468. expect(patched[0].filament_overrides).toEqual([
  2469. expect.objectContaining({ slot_id: 1, tray_info_idx: 'GFA01', force_color_match: true }),
  2470. ]);
  2471. });
  2472. it("names a kept pin's colour within its product line when the file's filaments can't be read", async () => {
  2473. const hex = BROWN.replace('#', '').toLowerCase();
  2474. setColorCatalog({ [hex]: 'Brown' }, { [`PLA Matte|${hex}`]: 'Matte Brown' });
  2475. server.use(
  2476. http.get('/api/v1/archives/:id/filament-requirements', () => HttpResponse.json({ detail: 'gone' }, { status: 500 })),
  2477. );
  2478. const vpItem = createMockQueueItem({
  2479. printer_id: null,
  2480. target_model: 'P2S',
  2481. filament_overrides: [
  2482. { slot_id: 1, type: 'PLA', color: BROWN, tray_info_idx: 'GFA01', force_color_match: true },
  2483. ],
  2484. } as Partial<PrintQueueItem>);
  2485. // The preset names are known from the first render, so the save can't race them.
  2486. const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
  2487. queryClient.setQueryData(['builtin-filaments'], [{ filament_id: 'GFA01', name: 'Bambu PLA Matte' }]);
  2488. queryClient.setQueryData(['filament-id-map'], {});
  2489. try {
  2490. const user = userEvent.setup();
  2491. rtlRender(
  2492. <QueryClientProvider client={queryClient}>
  2493. <BrowserRouter>
  2494. <AuthProvider>
  2495. <ThemeProvider>
  2496. <ToastProvider>
  2497. <PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={vpItem} onClose={mockOnClose} />
  2498. </ToastProvider>
  2499. </ThemeProvider>
  2500. </AuthProvider>
  2501. </BrowserRouter>
  2502. </QueryClientProvider>,
  2503. );
  2504. await submit(user);
  2505. await waitFor(() => expect(patched).toHaveLength(1));
  2506. expect(patched[0].filament_overrides).toEqual([
  2507. expect.objectContaining({ slot_id: 1, tray_info_idx: 'GFA01', color_name: 'Matte Brown' }),
  2508. ]);
  2509. } finally {
  2510. __resetColorCatalogForTests();
  2511. }
  2512. });
  2513. it('carries an override picked in model mode into a specific-printer job when creating', async () => {
  2514. const user = userEvent.setup();
  2515. render(<PrintModal mode="create" archiveId={1} archiveName="Job" onClose={mockOnClose} />);
  2516. await user.click(await screen.findByRole('button', { name: /any model/i }));
  2517. const modelSelect = await waitFor(() => {
  2518. const select = screen
  2519. .getAllByRole('combobox')
  2520. .find((el) => (el as HTMLSelectElement).options[0]?.text === 'Select a model...');
  2521. if (!select) throw new Error('target model select not rendered');
  2522. return select as HTMLSelectElement;
  2523. });
  2524. await user.selectOptions(modelSelect, 'P2S');
  2525. // Matched on the hex the row now prints (#3159) rather than on the option
  2526. // value, so the assertion names the colour the user is actually picking.
  2527. await pickFromSlotPicker(
  2528. user,
  2529. /filament override for/i,
  2530. new RegExp(BONE_WHITE.toUpperCase().replace('#', '#?')),
  2531. );
  2532. await moveToPrinter01(user);
  2533. await waitFor(() => expect(screen.getByText(/filament mapping/i)).toBeInTheDocument());
  2534. await submit(user);
  2535. await waitFor(() => expect(posted).toHaveLength(1));
  2536. expect(posted[0].printer_id).toBe(1);
  2537. expect(posted[0].ams_mapping).toEqual([1]);
  2538. expect(posted[0].filament_overrides).toEqual([
  2539. expect.objectContaining({ slot_id: 1, type: 'PLA', color: BONE_WHITE }),
  2540. ]);
  2541. });
  2542. });
  2543. describe('PrintModal — a deliberate material substitution is acknowledged (#2799)', () => {
  2544. // The scheduler re-checks a stored mapping against the printer before
  2545. // dispatch, and a slot on a tray of another material is what a mapping meant
  2546. // for a different printer looks like. A user who picks such a tray by hand
  2547. // means it, so the dialog sends skip_filament_check, which the re-check
  2548. // honours.
  2549. const mockOnClose = vi.fn();
  2550. const PRINTERS = [
  2551. { id: 1, name: 'Printer 01', model: 'P2S', ip_address: '192.168.1.101', enabled: true, is_active: true },
  2552. ];
  2553. type Patched = { ams_mapping?: number[] | null; skip_filament_check?: boolean };
  2554. let patched: Patched[];
  2555. beforeEach(() => {
  2556. vi.clearAllMocks();
  2557. patched = [];
  2558. server.use(
  2559. http.get('/api/v1/printers/', () => HttpResponse.json(PRINTERS)),
  2560. http.get('/api/v1/archives/:id/plates', () => HttpResponse.json({ is_multi_plate: false, plates: [] })),
  2561. http.get('/api/v1/archives/:id/filament-requirements', () =>
  2562. HttpResponse.json({ filaments: [{ slot_id: 1, type: 'PLA', color: '#8B4513', tray_info_idx: '', used_grams: 50 }] }),
  2563. ),
  2564. // Tray 0 holds the PLA the plate asks for, tray 1 a PETG.
  2565. http.get('/api/v1/printers/:id/status', () =>
  2566. HttpResponse.json({
  2567. connected: true,
  2568. state: 'IDLE',
  2569. ams: [
  2570. {
  2571. id: 0,
  2572. tray: [
  2573. { id: 0, tray_type: 'PLA', tray_color: '8B4513FF' },
  2574. { id: 1, tray_type: 'PETG', tray_color: 'FFFFFFFF' },
  2575. ],
  2576. },
  2577. ],
  2578. vt_tray: [],
  2579. }),
  2580. ),
  2581. http.get('/api/v1/printers/:id/assignments', () => HttpResponse.json([])),
  2582. http.patch('/api/v1/queue/:id', async ({ request }) => {
  2583. patched.push((await request.json()) as Patched);
  2584. return HttpResponse.json({ id: 1, status: 'pending' });
  2585. }),
  2586. );
  2587. });
  2588. const pinnedItem = () => createMockQueueItem({ printer_id: 1, target_model: null } as Partial<PrintQueueItem>);
  2589. const pickTrayAndSave = async (option: number) => {
  2590. const user = userEvent.setup();
  2591. render(<PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={pinnedItem()} onClose={mockOnClose} />);
  2592. await user.click(await screen.findByText(/filament mapping/i));
  2593. await user.click(await screen.findByRole('combobox', { name: /printer slot for/i }));
  2594. const listbox = await screen.findByRole('listbox');
  2595. await user.click(within(listbox).getAllByRole('option')[option]);
  2596. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  2597. await waitFor(() => expect(patched).toHaveLength(1));
  2598. return patched[0];
  2599. };
  2600. it('sends skip_filament_check when a slot is put on a tray of another material', async () => {
  2601. // Option 0 is the empty '-- Select slot --'; 1 is the PLA tray, 2 the PETG.
  2602. const saved = await pickTrayAndSave(2);
  2603. expect(saved.ams_mapping).toEqual([1]);
  2604. expect(saved.skip_filament_check).toBe(true);
  2605. });
  2606. it('does not treat a stored mapping the dialog opened with as a pick made here', async () => {
  2607. // A job queued before the dispatch re-check existed can carry a mapping
  2608. // made for another printer. Saving an unrelated edit must not enshrine it.
  2609. const user = userEvent.setup();
  2610. const item = createMockQueueItem({ printer_id: 1, target_model: null, ams_mapping: [1] } as Partial<PrintQueueItem>);
  2611. render(<PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={item} onClose={mockOnClose} />);
  2612. await waitFor(() => expect(screen.getByText(/filament mapping/i)).toBeInTheDocument());
  2613. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  2614. await waitFor(() => expect(patched).toHaveLength(1));
  2615. expect(patched[0].ams_mapping).toEqual([1]);
  2616. expect(patched[0].skip_filament_check).toBeUndefined();
  2617. });
  2618. it('sends nothing extra when the picked tray holds the material asked for', async () => {
  2619. const saved = await pickTrayAndSave(1);
  2620. expect(saved.ams_mapping).toEqual([0]);
  2621. expect(saved.skip_filament_check).toBeUndefined();
  2622. });
  2623. });
  2624. describe('PrintModal edit: moving a job to another printer', () => {
  2625. const mockOnClose = vi.fn();
  2626. let patched: Record<string, unknown>[];
  2627. beforeEach(() => {
  2628. vi.clearAllMocks();
  2629. patched = [];
  2630. server.use(
  2631. http.get('/api/v1/printers/', () =>
  2632. HttpResponse.json([
  2633. { id: 1, name: 'Printer 01', model: 'H2C', ip_address: '192.168.1.101', enabled: true, is_active: true },
  2634. { id: 2, name: 'Printer 02', model: 'H2C', ip_address: '192.168.1.102', enabled: true, is_active: true },
  2635. ]),
  2636. ),
  2637. http.get('/api/v1/archives/:id/plates', () => HttpResponse.json({ is_multi_plate: false, plates: [] })),
  2638. http.get('/api/v1/printers/:id/status', () =>
  2639. HttpResponse.json({ connected: true, state: 'IDLE', ams: [], vt_tray: [] }),
  2640. ),
  2641. http.patch('/api/v1/queue/:id', async ({ request }) => {
  2642. patched.push((await request.json()) as Record<string, unknown>);
  2643. return HttpResponse.json({ id: 1, status: 'pending' });
  2644. }),
  2645. );
  2646. });
  2647. it("does not carry the old printer's nozzle rack picks over", async () => {
  2648. const user = userEvent.setup();
  2649. const item = createMockQueueItem({
  2650. printer_id: 1,
  2651. target_model: null,
  2652. nozzle_rack_choice: { 0: 3 },
  2653. } as Partial<PrintQueueItem>);
  2654. render(<PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={item} onClose={mockOnClose} />);
  2655. // The dialog adds printers; moving the job is deselecting one, selecting the other.
  2656. await user.click(await screen.findByText('Printer 01'));
  2657. await user.click(screen.getByText('Printer 02'));
  2658. await user.click(screen.getByRole('button', { name: /save/i }));
  2659. await waitFor(() => expect(patched).toHaveLength(1));
  2660. expect(patched[0].printer_id).toBe(2);
  2661. expect(patched[0].nozzle_rack_choice).toBeNull();
  2662. });
  2663. });
  2664. describe('PrintModal default printer', () => {
  2665. beforeEach(() => {
  2666. vi.clearAllMocks();
  2667. server.use(
  2668. http.get('/api/v1/printers/', () => HttpResponse.json(mockPrinters)),
  2669. http.get('/api/v1/settings/', () => HttpResponse.json({ default_printer_id: 2, currency: 'USD' })),
  2670. http.get('/api/v1/archives/:id/plates', () => HttpResponse.json({ is_multi_plate: false, plates: [] })),
  2671. http.get('/api/v1/archives/:id/filament-requirements', () => HttpResponse.json({ filaments: [] })),
  2672. http.get('/api/v1/printers/:id/status', () =>
  2673. HttpResponse.json({ connected: true, state: 'IDLE', ams: [], vt_tray: [] }),
  2674. ),
  2675. );
  2676. });
  2677. it('preselects the default printer from Settings', async () => {
  2678. render(<PrintModal mode="create" archiveId={1} archiveName="Test Print" onClose={vi.fn()} />);
  2679. expect(await screen.findByText('1 printer selected')).toBeInTheDocument();
  2680. });
  2681. it('does not bring the default back once it was deselected', async () => {
  2682. const user = userEvent.setup();
  2683. render(<PrintModal mode="create" archiveId={1} archiveName="Test Print" onClose={vi.fn()} />);
  2684. await screen.findByText('1 printer selected');
  2685. await user.click(screen.getByText('P1S'));
  2686. await new Promise((resolve) => setTimeout(resolve, 100));
  2687. expect(screen.queryByText('1 printer selected')).not.toBeInTheDocument();
  2688. });
  2689. it('does not select a default printer of another model than the file was sliced for', async () => {
  2690. server.use(
  2691. http.get('/api/v1/archives/:id', async () => {
  2692. // Later than printers and settings: the model must be waited for.
  2693. await new Promise((resolve) => setTimeout(resolve, 50));
  2694. return HttpResponse.json({ id: 1, filename: 'test.3mf', sliced_for_model: 'X1C' });
  2695. }),
  2696. );
  2697. const user = userEvent.setup();
  2698. render(<PrintModal mode="create" archiveId={1} archiveName="Test Print" onClose={vi.fn()} />);
  2699. // The P1S is hidden behind "show all" as another model than X1C.
  2700. await user.click(await screen.findByText('show all'));
  2701. await new Promise((resolve) => setTimeout(resolve, 200));
  2702. expect(screen.getByText('P1S').closest('button')).not.toHaveClass('border-bambu-green');
  2703. });
  2704. });