PrintModal.test.tsx 135 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631
  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. // Save waits for the printer's live status (#2589)
  443. const save = screen.getByRole('button', { name: /save/i });
  444. await waitFor(() => expect(save).toBeEnabled());
  445. await user.click(save);
  446. await waitFor(() => expect(body).not.toBeNull());
  447. expect(body!.manual_start).toBe(true);
  448. });
  449. describe('edit-queue-item mode', () => {
  450. it('renders the modal title', () => {
  451. const item = createMockQueueItem();
  452. render(
  453. <PrintModal
  454. mode="edit-queue-item"
  455. archiveId={1}
  456. archiveName="Test Print"
  457. queueItem={item}
  458. onClose={mockOnClose}
  459. />
  460. );
  461. expect(screen.getByText('Edit Queue Item')).toBeInTheDocument();
  462. });
  463. it('shows save button', () => {
  464. const item = createMockQueueItem();
  465. render(
  466. <PrintModal
  467. mode="edit-queue-item"
  468. archiveId={1}
  469. archiveName="Test Print"
  470. queueItem={item}
  471. onClose={mockOnClose}
  472. />
  473. );
  474. expect(screen.getByRole('button', { name: /save/i })).toBeInTheDocument();
  475. });
  476. it('shows cancel button', () => {
  477. const item = createMockQueueItem();
  478. render(
  479. <PrintModal
  480. mode="edit-queue-item"
  481. archiveId={1}
  482. archiveName="Test Print"
  483. queueItem={item}
  484. onClose={mockOnClose}
  485. />
  486. );
  487. expect(screen.getByRole('button', { name: /cancel/i })).toBeInTheDocument();
  488. });
  489. it('shows print options toggle', () => {
  490. const item = createMockQueueItem();
  491. render(
  492. <PrintModal
  493. mode="edit-queue-item"
  494. archiveId={1}
  495. archiveName="Test Print"
  496. queueItem={item}
  497. onClose={mockOnClose}
  498. />
  499. );
  500. expect(screen.getByText('Print Options')).toBeInTheDocument();
  501. });
  502. it('shows Queue option', () => {
  503. const item = createMockQueueItem();
  504. render(
  505. <PrintModal
  506. mode="edit-queue-item"
  507. archiveId={1}
  508. archiveName="Test Print"
  509. queueItem={item}
  510. onClose={mockOnClose}
  511. />
  512. );
  513. expect(screen.getByRole('button', { name: /queue/i })).toBeInTheDocument();
  514. });
  515. it('shows power off option', () => {
  516. const item = createMockQueueItem();
  517. render(
  518. <PrintModal
  519. mode="edit-queue-item"
  520. archiveId={1}
  521. archiveName="Test Print"
  522. queueItem={item}
  523. onClose={mockOnClose}
  524. />
  525. );
  526. expect(screen.getByText(/power off/i)).toBeInTheDocument();
  527. });
  528. it('calls onClose when cancel button is clicked', async () => {
  529. const user = userEvent.setup();
  530. const item = createMockQueueItem();
  531. render(
  532. <PrintModal
  533. mode="edit-queue-item"
  534. archiveId={1}
  535. archiveName="Test Print"
  536. queueItem={item}
  537. onClose={mockOnClose}
  538. />
  539. );
  540. const cancelButton = screen.getByRole('button', { name: /cancel/i });
  541. await user.click(cancelButton);
  542. expect(mockOnClose).toHaveBeenCalled();
  543. });
  544. it('shows printer selector for single selection', async () => {
  545. const item = createMockQueueItem();
  546. render(
  547. <PrintModal
  548. mode="edit-queue-item"
  549. archiveId={1}
  550. archiveName="Test Print"
  551. queueItem={item}
  552. onClose={mockOnClose}
  553. />
  554. );
  555. // PrinterSelector shows printer names directly
  556. await waitFor(() => {
  557. expect(screen.getByText('P1S')).toBeInTheDocument();
  558. });
  559. });
  560. });
  561. describe('multi-printer selection', () => {
  562. it('shows select all button when multiple printers available', async () => {
  563. render(
  564. <PrintModal
  565. mode="create"
  566. archiveId={1}
  567. archiveName="Benchy"
  568. onClose={mockOnClose}
  569. />
  570. );
  571. await waitFor(() => {
  572. expect(screen.getByText('Select all')).toBeInTheDocument();
  573. });
  574. });
  575. it('shows selected count when multiple printers selected', async () => {
  576. const user = userEvent.setup();
  577. render(
  578. <PrintModal
  579. mode="create"
  580. archiveId={1}
  581. archiveName="Benchy"
  582. onClose={mockOnClose}
  583. />
  584. );
  585. await waitFor(() => {
  586. expect(screen.getByText('Select all')).toBeInTheDocument();
  587. });
  588. await user.click(screen.getByText('Select all'));
  589. await waitFor(() => {
  590. expect(screen.getByText(/3 printers selected/)).toBeInTheDocument();
  591. });
  592. });
  593. it('updates button text when multiple printers selected', async () => {
  594. const user = userEvent.setup();
  595. render(
  596. <PrintModal
  597. mode="create"
  598. archiveId={1}
  599. archiveName="Benchy"
  600. onClose={mockOnClose}
  601. />
  602. );
  603. await waitFor(() => {
  604. expect(screen.getByText('Select all')).toBeInTheDocument();
  605. });
  606. await user.click(screen.getByText('Select all'));
  607. await waitFor(() => {
  608. expect(screen.getByRole('button', { name: /^print$/i })).toBeInTheDocument();
  609. });
  610. });
  611. });
  612. describe('busy printer handling (#622)', () => {
  613. beforeEach(() => {
  614. // Set up per-printer statuses: printer 1 RUNNING, printer 2 IDLE, printer 3 FINISH
  615. server.use(
  616. http.get('/api/v1/printers/:id/status', ({ params }) => {
  617. const id = Number(params.id);
  618. if (id === 1) {
  619. return HttpResponse.json({
  620. connected: true, state: 'RUNNING', stg_cur_name: null,
  621. ams: [], vt_tray: [], nozzles: [],
  622. });
  623. }
  624. if (id === 2) {
  625. return HttpResponse.json({
  626. connected: true, state: 'IDLE', stg_cur_name: null,
  627. ams: [], vt_tray: [], nozzles: [],
  628. });
  629. }
  630. // printer 3
  631. return HttpResponse.json({
  632. connected: true, state: 'FINISH', stg_cur_name: null,
  633. ams: [], vt_tray: [], nozzles: [],
  634. });
  635. })
  636. );
  637. });
  638. it('shows state badges on printers in create mode', async () => {
  639. render(
  640. <PrintModal
  641. mode="create"
  642. archiveId={1}
  643. archiveName="Benchy"
  644. onClose={mockOnClose}
  645. />
  646. );
  647. await waitFor(() => {
  648. expect(screen.getByText('Printing')).toBeInTheDocument();
  649. expect(screen.getByText('Idle')).toBeInTheDocument();
  650. expect(screen.getByText('Finished')).toBeInTheDocument();
  651. });
  652. });
  653. it('allows selecting a busy printer in create mode', async () => {
  654. const user = userEvent.setup();
  655. render(
  656. <PrintModal
  657. mode="create"
  658. archiveId={1}
  659. archiveName="Benchy"
  660. onClose={mockOnClose}
  661. />
  662. );
  663. await waitFor(() => {
  664. expect(screen.getByText('Printing')).toBeInTheDocument();
  665. });
  666. const busyButton = screen.getByText('X1 Carbon').closest('button');
  667. expect(busyButton).not.toBeDisabled();
  668. await user.click(busyButton!);
  669. await waitFor(() => {
  670. expect(screen.getByText('1 printer selected')).toBeInTheDocument();
  671. });
  672. });
  673. it('select all includes busy printers in create mode', async () => {
  674. const user = userEvent.setup();
  675. render(
  676. <PrintModal
  677. mode="create"
  678. archiveId={1}
  679. archiveName="Benchy"
  680. onClose={mockOnClose}
  681. />
  682. );
  683. await waitFor(() => {
  684. expect(screen.getByText('Select all')).toBeInTheDocument();
  685. expect(screen.getByText('Printing')).toBeInTheDocument();
  686. });
  687. await user.click(screen.getByText('Select all'));
  688. await waitFor(() => {
  689. expect(screen.getByText(/3 printers selected/)).toBeInTheDocument();
  690. });
  691. });
  692. it('allows selecting busy printers in create mode', async () => {
  693. const user = userEvent.setup();
  694. render(
  695. <PrintModal
  696. mode="create"
  697. archiveId={1}
  698. archiveName="Benchy"
  699. onClose={mockOnClose}
  700. />
  701. );
  702. await waitFor(() => {
  703. expect(screen.getByText('Printing')).toBeInTheDocument();
  704. });
  705. // The busy printer button should NOT be disabled in queue mode
  706. const busyButton = screen.getByText('X1 Carbon').closest('button');
  707. expect(busyButton).not.toBeDisabled();
  708. await user.click(busyButton!);
  709. await waitFor(() => {
  710. expect(screen.getByText('1 printer selected')).toBeInTheDocument();
  711. });
  712. });
  713. it('shows Offline badge for disconnected printers', async () => {
  714. server.use(
  715. http.get('/api/v1/printers/:id/status', () => {
  716. return HttpResponse.json({
  717. connected: false, state: null, stg_cur_name: null,
  718. ams: [], vt_tray: [], nozzles: [],
  719. });
  720. })
  721. );
  722. render(
  723. <PrintModal
  724. mode="create"
  725. archiveId={1}
  726. archiveName="Benchy"
  727. onClose={mockOnClose}
  728. />
  729. );
  730. await waitFor(() => {
  731. const offlineBadges = screen.getAllByText('Offline');
  732. expect(offlineBadges.length).toBeGreaterThanOrEqual(1);
  733. });
  734. });
  735. it('shows calibration stage name when printer is calibrating', async () => {
  736. server.use(
  737. http.get('/api/v1/printers/:id/status', () => {
  738. return HttpResponse.json({
  739. connected: true, state: 'RUNNING', stg_cur_name: 'Auto bed leveling',
  740. ams: [], vt_tray: [], nozzles: [],
  741. });
  742. })
  743. );
  744. render(
  745. <PrintModal
  746. mode="create"
  747. archiveId={1}
  748. archiveName="Benchy"
  749. onClose={mockOnClose}
  750. />
  751. );
  752. await waitFor(() => {
  753. const badges = screen.getAllByText('Auto bed leveling');
  754. expect(badges.length).toBeGreaterThanOrEqual(1);
  755. });
  756. });
  757. });
  758. describe('stagger start', () => {
  759. it('does not show stagger option with single printer in queue mode', async () => {
  760. const user = userEvent.setup();
  761. render(
  762. <PrintModal
  763. mode="create"
  764. archiveId={1}
  765. archiveName="Test Print"
  766. onClose={mockOnClose}
  767. />
  768. );
  769. await waitFor(() => {
  770. expect(screen.getByText('X1 Carbon')).toBeInTheDocument();
  771. });
  772. // Select single printer
  773. await user.click(screen.getByText('X1 Carbon'));
  774. expect(screen.queryByText('Stagger printer starts')).not.toBeInTheDocument();
  775. });
  776. it('shows stagger option when multiple printers selected in queue mode', async () => {
  777. const user = userEvent.setup();
  778. render(
  779. <PrintModal
  780. mode="create"
  781. archiveId={1}
  782. archiveName="Test Print"
  783. onClose={mockOnClose}
  784. />
  785. );
  786. await waitFor(() => {
  787. expect(screen.getByText('Select all')).toBeInTheDocument();
  788. });
  789. await user.click(screen.getByText('Select all'));
  790. await waitFor(() => {
  791. expect(screen.getByText('Stagger printer starts')).toBeInTheDocument();
  792. });
  793. });
  794. it('shows stagger option in create mode with multiple printers', async () => {
  795. const user = userEvent.setup();
  796. render(
  797. <PrintModal
  798. mode="create"
  799. archiveId={1}
  800. archiveName="Test Print"
  801. onClose={mockOnClose}
  802. />
  803. );
  804. await waitFor(() => {
  805. expect(screen.getByText('Select all')).toBeInTheDocument();
  806. });
  807. await user.click(screen.getByText('Select all'));
  808. await waitFor(() => {
  809. expect(screen.getByText(/2 printers selected|3 printers selected/)).toBeInTheDocument();
  810. });
  811. expect(screen.getByText('Stagger printer starts')).toBeInTheDocument();
  812. });
  813. it('shows stagger preview in create mode when enabled', async () => {
  814. const user = userEvent.setup();
  815. render(
  816. <PrintModal
  817. mode="create"
  818. archiveId={1}
  819. archiveName="Test Print"
  820. onClose={mockOnClose}
  821. />
  822. );
  823. await waitFor(() => {
  824. expect(screen.getByText('Select all')).toBeInTheDocument();
  825. });
  826. await user.click(screen.getByText('Select all'));
  827. await waitFor(() => {
  828. expect(screen.getByText('Stagger printer starts')).toBeInTheDocument();
  829. });
  830. await user.click(screen.getByLabelText('Stagger printer starts'));
  831. await waitFor(() => {
  832. // Default: 3 printers, group size 2 = 2 groups — preview text shown
  833. expect(screen.getByText(/3 printers.*2 groups/)).toBeInTheDocument();
  834. });
  835. });
  836. it('does not show stagger option in create mode with single printer', async () => {
  837. const user = userEvent.setup();
  838. render(
  839. <PrintModal
  840. mode="create"
  841. archiveId={1}
  842. archiveName="Test Print"
  843. onClose={mockOnClose}
  844. />
  845. );
  846. await waitFor(() => {
  847. expect(screen.getByText('X1 Carbon')).toBeInTheDocument();
  848. });
  849. // Select only one printer
  850. await user.click(screen.getByText('X1 Carbon'));
  851. expect(screen.queryByText('Stagger printer starts')).not.toBeInTheDocument();
  852. });
  853. it('shows stagger inputs when stagger checkbox is enabled', async () => {
  854. const user = userEvent.setup();
  855. render(
  856. <PrintModal
  857. mode="create"
  858. archiveId={1}
  859. archiveName="Test Print"
  860. onClose={mockOnClose}
  861. />
  862. );
  863. await waitFor(() => {
  864. expect(screen.getByText('Select all')).toBeInTheDocument();
  865. });
  866. await user.click(screen.getByText('Select all'));
  867. await waitFor(() => {
  868. expect(screen.getByText('Stagger printer starts')).toBeInTheDocument();
  869. });
  870. await user.click(screen.getByLabelText('Stagger printer starts'));
  871. await waitFor(() => {
  872. expect(screen.getByText('Group size')).toBeInTheDocument();
  873. expect(screen.getByText('Interval (min)')).toBeInTheDocument();
  874. });
  875. });
  876. it('shows stagger preview with printer count', async () => {
  877. const user = userEvent.setup();
  878. render(
  879. <PrintModal
  880. mode="create"
  881. archiveId={1}
  882. archiveName="Test Print"
  883. onClose={mockOnClose}
  884. />
  885. );
  886. await waitFor(() => {
  887. expect(screen.getByText('Select all')).toBeInTheDocument();
  888. });
  889. await user.click(screen.getByText('Select all'));
  890. await waitFor(() => {
  891. expect(screen.getByText('Stagger printer starts')).toBeInTheDocument();
  892. });
  893. await user.click(screen.getByLabelText('Stagger printer starts'));
  894. await waitFor(() => {
  895. // Default: 3 printers, group size 2 = 2 groups — preview text includes printer count
  896. expect(screen.getByText(/3 printers.*2 groups/)).toBeInTheDocument();
  897. });
  898. });
  899. });
  900. describe('multi-plate selection', () => {
  901. const multiPlateResponse = {
  902. is_multi_plate: true,
  903. plates: [
  904. { 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 },
  905. { 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 },
  906. { 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 },
  907. ],
  908. };
  909. beforeEach(() => {
  910. server.use(
  911. http.get('/api/v1/archives/:id/plates', () => {
  912. return HttpResponse.json(multiPlateResponse);
  913. }),
  914. );
  915. });
  916. it('shows "Select All" button only in create mode', async () => {
  917. render(
  918. <PrintModal
  919. mode="create"
  920. archiveId={1}
  921. archiveName="MultiPlate.3mf"
  922. onClose={mockOnClose}
  923. />
  924. );
  925. await waitFor(() => {
  926. expect(screen.getByText('Select All 3 Plates')).toBeInTheDocument();
  927. });
  928. });
  929. it('shows "Select All" button in create mode', async () => {
  930. render(
  931. <PrintModal
  932. mode="create"
  933. archiveId={1}
  934. archiveName="MultiPlate.3mf"
  935. initialSelectedPrinterIds={[1]}
  936. onClose={mockOnClose}
  937. />
  938. );
  939. await waitFor(() => {
  940. expect(screen.getByText('Plate 1')).toBeInTheDocument();
  941. });
  942. expect(screen.getByText('Select All 3 Plates')).toBeInTheDocument();
  943. });
  944. it('selects all plates when "Select All" is clicked', async () => {
  945. const user = userEvent.setup();
  946. render(
  947. <PrintModal
  948. mode="create"
  949. archiveId={1}
  950. archiveName="MultiPlate.3mf"
  951. onClose={mockOnClose}
  952. />
  953. );
  954. await waitFor(() => {
  955. expect(screen.getByText('Select All 3 Plates')).toBeInTheDocument();
  956. });
  957. await user.click(screen.getByText('Select All 3 Plates'));
  958. // All plates should be highlighted (green border)
  959. await waitFor(() => {
  960. const plateButtons = document.querySelectorAll('button[type="button"].border-bambu-green');
  961. // 3 plate buttons + the "Deselect All" toggle button = 4 green-bordered buttons
  962. expect(plateButtons.length).toBeGreaterThanOrEqual(3);
  963. });
  964. });
  965. it('allows selecting a subset of plates to queue', async () => {
  966. const queueRequests: unknown[] = [];
  967. server.use(
  968. http.post('/api/v1/queue/', async ({ request }) => {
  969. const body = await request.json();
  970. queueRequests.push(body);
  971. return HttpResponse.json({ id: queueRequests.length, status: 'pending' });
  972. }),
  973. );
  974. const user = userEvent.setup();
  975. render(
  976. <PrintModal
  977. mode="create"
  978. archiveId={1}
  979. archiveName="MultiPlate.3mf"
  980. onClose={mockOnClose}
  981. onSuccess={mockOnSuccess}
  982. />
  983. );
  984. // Wait for plates and select a printer
  985. await waitFor(() => {
  986. expect(screen.getByText('Select All 3 Plates')).toBeInTheDocument();
  987. expect(screen.getByText('X1 Carbon')).toBeInTheDocument();
  988. });
  989. // Select printer
  990. await user.click(screen.getByText('X1 Carbon'));
  991. // Plate 1 is auto-selected. Click Plate 3 to add it (multi-select in create mode)
  992. await user.click(screen.getByText('Plate 3'));
  993. // Submit — should queue plates 1 and 3
  994. const submitButton = document.querySelector('button[type="submit"]') as HTMLElement;
  995. await user.click(submitButton);
  996. await waitFor(() => {
  997. expect(queueRequests.length).toBe(2);
  998. });
  999. expect((queueRequests[0] as { plate_id: number }).plate_id).toBe(1);
  1000. expect((queueRequests[1] as { plate_id: number }).plate_id).toBe(3);
  1001. });
  1002. // #3395: a reprint opens on the plate the archive printed, not plate 1.
  1003. async function submitAndCollect(preselectPlateId: number | null) {
  1004. const queueRequests: { plate_id: number }[] = [];
  1005. server.use(
  1006. http.post('/api/v1/queue/', async ({ request }) => {
  1007. queueRequests.push((await request.json()) as { plate_id: number });
  1008. return HttpResponse.json({ id: queueRequests.length, status: 'pending' });
  1009. }),
  1010. );
  1011. const user = userEvent.setup();
  1012. render(
  1013. <PrintModal
  1014. mode="create"
  1015. archiveId={1}
  1016. archiveName="MultiPlate.3mf"
  1017. preselectPlateId={preselectPlateId}
  1018. initialSelectedPrinterIds={[1]}
  1019. onClose={mockOnClose}
  1020. onSuccess={mockOnSuccess}
  1021. />
  1022. );
  1023. await waitFor(() => {
  1024. expect(screen.getByText('Select All 3 Plates')).toBeInTheDocument();
  1025. });
  1026. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1027. await waitFor(() => {
  1028. expect(queueRequests.length).toBe(1);
  1029. });
  1030. return queueRequests.map((r) => r.plate_id);
  1031. }
  1032. it('queues the pre-selected plate only', async () => {
  1033. expect(await submitAndCollect(3)).toEqual([3]);
  1034. expect(screen.getByTestId('selected-plates-summary')).toHaveTextContent('Plate 3');
  1035. });
  1036. it('falls back to the first plate when the file no longer has the pre-selected one', async () => {
  1037. expect(await submitAndCollect(9)).toEqual([1]);
  1038. });
  1039. it('names the selected plates beside the buttons, with their names', async () => {
  1040. server.use(
  1041. http.get('/api/v1/archives/:id/plates', () =>
  1042. HttpResponse.json({
  1043. ...multiPlateResponse,
  1044. plates: multiPlateResponse.plates.map((p) => (p.index === 2 ? { ...p, name: 'Lid' } : p)),
  1045. }),
  1046. ),
  1047. );
  1048. const user = userEvent.setup();
  1049. render(
  1050. <PrintModal mode="create" archiveId={1} archiveName="MultiPlate.3mf" preselectPlateId={2} onClose={mockOnClose} />
  1051. );
  1052. await waitFor(() => {
  1053. expect(screen.getByTestId('selected-plates-summary')).toHaveTextContent('Plate 2 – Lid');
  1054. });
  1055. await user.click(screen.getByText('Plate 3'));
  1056. expect(screen.getByTestId('selected-plates-summary')).toHaveTextContent('Plate 2 – Lid, Plate 3');
  1057. });
  1058. it('scrolls the pre-selected plate into view', async () => {
  1059. const scrolled: string[] = [];
  1060. const original = Element.prototype.scrollIntoView;
  1061. Element.prototype.scrollIntoView = function (this: Element) {
  1062. scrolled.push(this.textContent ?? '');
  1063. };
  1064. try {
  1065. render(
  1066. <PrintModal mode="create" archiveId={1} archiveName="MultiPlate.3mf" preselectPlateId={3} onClose={mockOnClose} />
  1067. );
  1068. await waitFor(() => {
  1069. expect(scrolled.length).toBe(1);
  1070. });
  1071. expect(scrolled[0]).toContain('Part C');
  1072. // Once: picking another plate doesn't move the list again.
  1073. await userEvent.setup().click(screen.getByText('Plate 1'));
  1074. expect(scrolled.length).toBe(1);
  1075. } finally {
  1076. Element.prototype.scrollIntoView = original;
  1077. }
  1078. });
  1079. it('creates one queue item per plate when submitting with select-all', async () => {
  1080. const queueRequests: unknown[] = [];
  1081. server.use(
  1082. http.post('/api/v1/queue/', async ({ request }) => {
  1083. const body = await request.json();
  1084. queueRequests.push(body);
  1085. return HttpResponse.json({ id: queueRequests.length, status: 'pending' });
  1086. }),
  1087. );
  1088. const user = userEvent.setup();
  1089. render(
  1090. <PrintModal
  1091. mode="create"
  1092. archiveId={1}
  1093. archiveName="MultiPlate.3mf"
  1094. onClose={mockOnClose}
  1095. onSuccess={mockOnSuccess}
  1096. />
  1097. );
  1098. // Wait for plates and select a printer
  1099. await waitFor(() => {
  1100. expect(screen.getByText('Select All 3 Plates')).toBeInTheDocument();
  1101. expect(screen.getByText('X1 Carbon')).toBeInTheDocument();
  1102. });
  1103. // Select printer
  1104. await user.click(screen.getByText('X1 Carbon'));
  1105. // Click select all
  1106. await user.click(screen.getByText('Select All 3 Plates'));
  1107. // Find the submit button (type="submit") — distinct from the toggle button (type="button")
  1108. const submitButton = document.querySelector('button[type="submit"]') as HTMLElement;
  1109. await user.click(submitButton);
  1110. await waitFor(() => {
  1111. expect(queueRequests.length).toBe(3);
  1112. });
  1113. // Verify each request has the correct plate_id
  1114. expect((queueRequests[0] as { plate_id: number }).plate_id).toBe(1);
  1115. expect((queueRequests[1] as { plate_id: number }).plate_id).toBe(2);
  1116. expect((queueRequests[2] as { plate_id: number }).plate_id).toBe(3);
  1117. });
  1118. });
  1119. describe('batch quantity', () => {
  1120. it('shows quantity input in create mode', () => {
  1121. render(
  1122. <PrintModal
  1123. mode="create"
  1124. archiveId={1}
  1125. archiveName="Benchy"
  1126. onClose={mockOnClose}
  1127. onSuccess={mockOnSuccess}
  1128. />
  1129. );
  1130. expect(screen.getByLabelText('Quantity')).toBeInTheDocument();
  1131. });
  1132. it('shows quantity input in create mode', () => {
  1133. render(
  1134. <PrintModal
  1135. mode="create"
  1136. archiveId={1}
  1137. archiveName="Benchy"
  1138. onClose={mockOnClose}
  1139. onSuccess={mockOnSuccess}
  1140. />
  1141. );
  1142. expect(screen.getByLabelText('Quantity')).toBeInTheDocument();
  1143. });
  1144. it('does not show quantity input in edit-queue-item mode', () => {
  1145. render(
  1146. <PrintModal
  1147. mode="edit-queue-item"
  1148. archiveId={1}
  1149. archiveName="Benchy"
  1150. queueItem={createMockQueueItem()}
  1151. onClose={mockOnClose}
  1152. onSuccess={mockOnSuccess}
  1153. />
  1154. );
  1155. expect(screen.queryByLabelText('Quantity')).not.toBeInTheDocument();
  1156. });
  1157. it('defaults quantity to 1', () => {
  1158. render(
  1159. <PrintModal
  1160. mode="create"
  1161. archiveId={1}
  1162. archiveName="Benchy"
  1163. onClose={mockOnClose}
  1164. onSuccess={mockOnSuccess}
  1165. />
  1166. );
  1167. const input = screen.getByLabelText('Quantity') as HTMLInputElement;
  1168. expect(input.value).toBe('1');
  1169. });
  1170. it('quantity input has default value of 1 and accepts changes', async () => {
  1171. const user = userEvent.setup();
  1172. render(
  1173. <PrintModal
  1174. mode="create"
  1175. archiveId={1}
  1176. archiveName="Benchy"
  1177. initialSelectedPrinterIds={[1]}
  1178. onClose={mockOnClose}
  1179. onSuccess={mockOnSuccess}
  1180. />
  1181. );
  1182. const input = screen.getByLabelText('Quantity') as HTMLInputElement;
  1183. expect(input.value).toBe('1');
  1184. await user.tripleClick(input);
  1185. await user.keyboard('5');
  1186. expect(input.value).toBe('5');
  1187. });
  1188. it('quantity can be erased and retyped instead of snapping back to 1 (#3182)', async () => {
  1189. const user = userEvent.setup();
  1190. render(
  1191. <PrintModal
  1192. mode="create"
  1193. archiveId={1}
  1194. archiveName="Benchy"
  1195. initialSelectedPrinterIds={[1]}
  1196. onClose={mockOnClose}
  1197. onSuccess={mockOnSuccess}
  1198. />
  1199. );
  1200. const input = screen.getByLabelText('Quantity') as HTMLInputElement;
  1201. await user.click(input);
  1202. await user.keyboard('{Backspace}');
  1203. expect(input.value).toBe('');
  1204. await user.keyboard('6');
  1205. expect(input.value).toBe('6');
  1206. expect(screen.getByText('Creates 6 queue items')).toBeInTheDocument();
  1207. });
  1208. it('an emptied quantity settles back to 1 when the field is left', async () => {
  1209. const user = userEvent.setup();
  1210. render(
  1211. <PrintModal
  1212. mode="create"
  1213. archiveId={1}
  1214. archiveName="Benchy"
  1215. initialSelectedPrinterIds={[1]}
  1216. onClose={mockOnClose}
  1217. onSuccess={mockOnSuccess}
  1218. />
  1219. );
  1220. const input = screen.getByLabelText('Quantity') as HTMLInputElement;
  1221. await user.click(input);
  1222. await user.keyboard('{Backspace}');
  1223. await user.tab();
  1224. expect(input.value).toBe('1');
  1225. });
  1226. });
  1227. describe('reprint G-code injection dispatch (#422 / auto-eject)', () => {
  1228. // Guards the fix: when "Inject auto-print G-code" is ticked on a create with
  1229. // quantity > 1, ALL copies must go through the queue so every one is injected by
  1230. // the scheduler. The first copy must NOT be dispatched immediately via the direct
  1231. // create path — that path bypasses injection and would leave the first copy stuck
  1232. // on the plate for auto-eject setups.
  1233. const withSnippets = () =>
  1234. http.get('/api/v1/settings/', () =>
  1235. HttpResponse.json({ gcode_snippets: { X1C: { start_gcode: '', end_gcode: 'M400' } } }),
  1236. );
  1237. it('injection ON queues all copies and dispatches none immediately', async () => {
  1238. const queueCalls: Record<string, unknown>[] = [];
  1239. server.use(
  1240. withSnippets(),
  1241. http.post('/api/v1/queue/', async ({ request }) => {
  1242. queueCalls.push((await request.json()) as Record<string, unknown>);
  1243. return HttpResponse.json({ id: queueCalls.length, status: 'pending' });
  1244. }),
  1245. );
  1246. const user = userEvent.setup();
  1247. render(
  1248. <PrintModal
  1249. mode="create"
  1250. archiveId={1}
  1251. archiveName="Benchy"
  1252. initialSelectedPrinterIds={[1]}
  1253. onClose={mockOnClose}
  1254. onSuccess={mockOnSuccess}
  1255. />
  1256. );
  1257. // Quantity > 1 so the injection checkbox is offered
  1258. const qty = (await screen.findByLabelText('Quantity')) as HTMLInputElement;
  1259. await user.tripleClick(qty);
  1260. await user.keyboard('3');
  1261. expect(qty.value).toBe('3');
  1262. // Checkbox only renders once snippets are loaded AND quantity > 1
  1263. await user.click(await screen.findByLabelText(/inject auto-print/i));
  1264. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1265. await waitFor(() => expect(queueCalls.length).toBe(1));
  1266. // One queue item carrying all copies, and zero immediate reprint dispatches
  1267. expect(queueCalls[0].quantity).toBe(3);
  1268. });
  1269. it('quantity 1 + snippets configured: checkbox toggles cleanly (#1852)', async () => {
  1270. // The previous reset effect in PrintModal/index.tsx silently flipped
  1271. // gcodeInjection back to false whenever effectiveQuantity <= 1 in create
  1272. // mode, so a single print with snippets configured couldn't tick the
  1273. // checkbox — every click visibly un-ticked itself within the next render.
  1274. // The scheduler reads item.gcode_injection per queue item regardless of
  1275. // batch size, so quantity 1 must be allowed too.
  1276. const queueCalls: Record<string, unknown>[] = [];
  1277. server.use(
  1278. withSnippets(),
  1279. http.post('/api/v1/queue/', async ({ request }) => {
  1280. queueCalls.push((await request.json()) as Record<string, unknown>);
  1281. return HttpResponse.json({ id: queueCalls.length, status: 'pending' });
  1282. }),
  1283. );
  1284. const user = userEvent.setup();
  1285. render(
  1286. <PrintModal
  1287. mode="create"
  1288. archiveId={1}
  1289. archiveName="Benchy"
  1290. initialSelectedPrinterIds={[1]}
  1291. onClose={mockOnClose}
  1292. onSuccess={mockOnSuccess}
  1293. />
  1294. );
  1295. // Quantity stays at default (1) — this is the OP's exact scenario.
  1296. const checkbox = (await screen.findByLabelText(/inject auto-print/i)) as HTMLInputElement;
  1297. expect(checkbox.checked).toBe(false);
  1298. await user.click(checkbox);
  1299. // CRITICAL: after the click the checkbox must stay checked. Under the
  1300. // pre-fix reset effect, the parent state would flip back to false within
  1301. // a render and the displayed `checked` attribute would track it.
  1302. await waitFor(() => expect(checkbox.checked).toBe(true));
  1303. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1304. await waitFor(() => expect(queueCalls.length).toBe(1));
  1305. // The injection flag actually reaches the API — pre-fix the parent reset
  1306. // would have stripped it before submit.
  1307. expect(queueCalls[0].gcode_injection).toBe(true);
  1308. });
  1309. it('injection OFF queues all copies through the scheduler path', async () => {
  1310. const queueCalls: Record<string, unknown>[] = [];
  1311. server.use(
  1312. withSnippets(),
  1313. http.post('/api/v1/queue/', async ({ request }) => {
  1314. queueCalls.push((await request.json()) as Record<string, unknown>);
  1315. return HttpResponse.json({ id: queueCalls.length, status: 'pending' });
  1316. }),
  1317. );
  1318. const user = userEvent.setup();
  1319. render(
  1320. <PrintModal
  1321. mode="create"
  1322. archiveId={1}
  1323. archiveName="Benchy"
  1324. initialSelectedPrinterIds={[1]}
  1325. onClose={mockOnClose}
  1326. onSuccess={mockOnSuccess}
  1327. />
  1328. );
  1329. const qty = (await screen.findByLabelText('Quantity')) as HTMLInputElement;
  1330. await user.tripleClick(qty);
  1331. await user.keyboard('3');
  1332. expect(qty.value).toBe('3');
  1333. // Leave injection unticked: unified dispatch still queues all copies.
  1334. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1335. await waitFor(() => expect(queueCalls.length).toBe(1));
  1336. expect(queueCalls[0].quantity).toBe(3);
  1337. });
  1338. });
  1339. describe('project_id forwarding', () => {
  1340. beforeEach(() => {
  1341. // Additional handlers needed for library file mode
  1342. server.use(
  1343. http.get('/api/v1/library/files/:id', () => {
  1344. return HttpResponse.json({
  1345. id: 5,
  1346. filename: 'benchy.gcode.3mf',
  1347. print_name: null,
  1348. file_type: '3mf',
  1349. folder_id: null,
  1350. project_id: null,
  1351. file_hash: null,
  1352. file_size_bytes: 1024,
  1353. thumbnail_path: null,
  1354. created_at: '2024-01-01T00:00:00Z',
  1355. updated_at: '2024-01-01T00:00:00Z',
  1356. });
  1357. }),
  1358. http.get('/api/v1/library/files/:id/plates', () => {
  1359. return HttpResponse.json({ is_multi_plate: false, plates: [] });
  1360. }),
  1361. http.get('/api/v1/library/files/:id/filament-requirements', () => {
  1362. return HttpResponse.json({ file_id: 5, filename: 'benchy.gcode.3mf', filaments: [] });
  1363. }),
  1364. http.get('/api/v1/printers/:id/status', () => {
  1365. return HttpResponse.json({ connected: true, state: 'IDLE', ams: [], vt_tray: [] });
  1366. }),
  1367. );
  1368. });
  1369. it('includes project_id in queue item when printing a library file with projectId set', async () => {
  1370. let capturedBody: Record<string, unknown> | null = null;
  1371. server.use(
  1372. http.post('/api/v1/queue/', async ({ request }) => {
  1373. capturedBody = await request.json() as Record<string, unknown>;
  1374. return HttpResponse.json({ id: 1, status: 'pending' });
  1375. })
  1376. );
  1377. const user = userEvent.setup();
  1378. render(
  1379. <PrintModal
  1380. mode="create"
  1381. libraryFileId={5}
  1382. archiveName="Benchy"
  1383. projectId={42}
  1384. initialSelectedPrinterIds={[1]}
  1385. onClose={mockOnClose}
  1386. onSuccess={mockOnSuccess}
  1387. />
  1388. );
  1389. // Wait for the modal to load printer and file data
  1390. await waitFor(() => {
  1391. expect(screen.getByRole('button', { name: /^print$/i })).toBeInTheDocument();
  1392. });
  1393. await user.click(screen.getByRole('button', { name: /^print$/i }));
  1394. await waitFor(() => {
  1395. expect(capturedBody).not.toBeNull();
  1396. expect(capturedBody?.library_file_id).toBe(5);
  1397. expect(capturedBody?.project_id).toBe(42);
  1398. });
  1399. });
  1400. it('queues archive prints through the scheduler path', async () => {
  1401. let capturedBody: Record<string, unknown> | null = null;
  1402. server.use(
  1403. http.post('/api/v1/queue/', async ({ request }) => {
  1404. capturedBody = await request.json() as Record<string, unknown>;
  1405. return HttpResponse.json({ id: 1, status: 'pending' });
  1406. })
  1407. );
  1408. const user = userEvent.setup();
  1409. render(
  1410. <PrintModal
  1411. mode="create"
  1412. archiveId={1}
  1413. archiveName="Benchy"
  1414. projectId={42}
  1415. initialSelectedPrinterIds={[1]}
  1416. onClose={mockOnClose}
  1417. onSuccess={mockOnSuccess}
  1418. />
  1419. );
  1420. await waitFor(() => {
  1421. expect(screen.getByRole('button', { name: /^print$/i })).toBeInTheDocument();
  1422. });
  1423. await user.click(screen.getByRole('button', { name: /^print$/i }));
  1424. await waitFor(() => {
  1425. expect(capturedBody).not.toBeNull();
  1426. expect(capturedBody?.archive_id).toBe(1);
  1427. expect(capturedBody?.project_id).toBe(42);
  1428. });
  1429. });
  1430. it('adds ASAP prints to the top of the queue', async () => {
  1431. let capturedBody: Record<string, unknown> | null = null;
  1432. server.use(
  1433. http.post('/api/v1/queue/', async ({ request }) => {
  1434. capturedBody = await request.json() as Record<string, unknown>;
  1435. return HttpResponse.json({ id: 1, status: 'pending' });
  1436. })
  1437. );
  1438. const user = userEvent.setup();
  1439. render(
  1440. <PrintModal
  1441. mode="create"
  1442. archiveId={1}
  1443. archiveName="Benchy"
  1444. initialSelectedPrinterIds={[1]}
  1445. onClose={mockOnClose}
  1446. onSuccess={mockOnSuccess}
  1447. />
  1448. );
  1449. await waitFor(() => {
  1450. expect(screen.getByRole('button', { name: /^print$/i })).toBeInTheDocument();
  1451. });
  1452. await user.click(screen.getByRole('button', { name: /^print$/i }));
  1453. await waitFor(() => {
  1454. expect(capturedBody).not.toBeNull();
  1455. expect(capturedBody?.insert_at_top).toBe(true);
  1456. expect(capturedBody?.insert_position).toBe(1);
  1457. expect(capturedBody?.manual_start).toBe(false);
  1458. expect(capturedBody?.scheduled_time).toBeUndefined();
  1459. });
  1460. });
  1461. it('adds Queue prints to the back unless manual start is required', async () => {
  1462. let capturedBody: Record<string, unknown> | null = null;
  1463. server.use(
  1464. http.post('/api/v1/queue/', async ({ request }) => {
  1465. capturedBody = await request.json() as Record<string, unknown>;
  1466. return HttpResponse.json({ id: 1, status: 'pending' });
  1467. })
  1468. );
  1469. const user = userEvent.setup();
  1470. render(
  1471. <PrintModal
  1472. mode="create"
  1473. archiveId={1}
  1474. archiveName="Benchy"
  1475. initialSelectedPrinterIds={[1]}
  1476. onClose={mockOnClose}
  1477. onSuccess={mockOnSuccess}
  1478. />
  1479. );
  1480. await user.click(screen.getByRole('button', { name: /^queue$/i }));
  1481. expect(screen.getByLabelText(/require manual start/i)).toBeInTheDocument();
  1482. await user.click(screen.getByLabelText(/require manual start/i));
  1483. await user.click(screen.getByRole('button', { name: /^print$/i }));
  1484. await waitFor(() => {
  1485. expect(capturedBody).not.toBeNull();
  1486. expect(capturedBody?.insert_at_top).toBeUndefined();
  1487. expect(capturedBody?.insert_position).toBeUndefined();
  1488. expect(capturedBody?.manual_start).toBe(true);
  1489. });
  1490. });
  1491. });
  1492. describe('cleanup_library_after_dispatch forwarding (#730)', () => {
  1493. // The Printers-page Direct-Print flow passes cleanupLibraryAfterDispatch so the
  1494. // transient LibraryFile created by FileUploadModal is deleted once the archive
  1495. // owns its own copy. File Manager / Project Detail flows leave the prop unset so
  1496. // their deliberately-added library entries survive the print.
  1497. beforeEach(() => {
  1498. server.use(
  1499. http.get('/api/v1/library/files/:id', () => {
  1500. return HttpResponse.json({
  1501. id: 5,
  1502. filename: 'benchy.gcode.3mf',
  1503. file_type: '3mf',
  1504. folder_id: null,
  1505. project_id: null,
  1506. file_hash: null,
  1507. file_size_bytes: 1024,
  1508. thumbnail_path: null,
  1509. created_at: '2024-01-01T00:00:00Z',
  1510. updated_at: '2024-01-01T00:00:00Z',
  1511. });
  1512. }),
  1513. http.get('/api/v1/library/files/:id/plates', () => {
  1514. return HttpResponse.json({ is_multi_plate: false, plates: [] });
  1515. }),
  1516. http.get('/api/v1/library/files/:id/filament-requirements', () => {
  1517. return HttpResponse.json({ file_id: 5, filename: 'benchy.gcode.3mf', filaments: [] });
  1518. }),
  1519. http.get('/api/v1/printers/:id/status', () => {
  1520. return HttpResponse.json({ connected: true, state: 'IDLE', ams: [], vt_tray: [] });
  1521. }),
  1522. );
  1523. });
  1524. it('forwards cleanup_library_after_dispatch=true when the Direct-Print prop is set', async () => {
  1525. let capturedBody: Record<string, unknown> | null = null;
  1526. server.use(
  1527. http.post('/api/v1/queue/', async ({ request }) => {
  1528. capturedBody = (await request.json()) as Record<string, unknown>;
  1529. return HttpResponse.json({ id: 1, status: 'pending' });
  1530. })
  1531. );
  1532. const user = userEvent.setup();
  1533. render(
  1534. <PrintModal
  1535. mode="create"
  1536. libraryFileId={5}
  1537. archiveName="Benchy"
  1538. cleanupLibraryAfterDispatch
  1539. initialSelectedPrinterIds={[1]}
  1540. onClose={mockOnClose}
  1541. onSuccess={mockOnSuccess}
  1542. />
  1543. );
  1544. await waitFor(() => {
  1545. expect(screen.getByRole('button', { name: /^print$/i })).toBeInTheDocument();
  1546. });
  1547. await user.click(screen.getByRole('button', { name: /^print$/i }));
  1548. await waitFor(() => {
  1549. expect(capturedBody).not.toBeNull();
  1550. expect(capturedBody?.cleanup_library_after_dispatch).toBe(true);
  1551. });
  1552. });
  1553. it('defaults to omitting cleanup_library_after_dispatch (File Manager / Project flows survive)', async () => {
  1554. let capturedBody: Record<string, unknown> | null = null;
  1555. server.use(
  1556. http.post('/api/v1/queue/', async ({ request }) => {
  1557. capturedBody = (await request.json()) as Record<string, unknown>;
  1558. return HttpResponse.json({ id: 1, status: 'pending' });
  1559. })
  1560. );
  1561. const user = userEvent.setup();
  1562. render(
  1563. <PrintModal
  1564. mode="create"
  1565. libraryFileId={5}
  1566. archiveName="Benchy"
  1567. initialSelectedPrinterIds={[1]}
  1568. onClose={mockOnClose}
  1569. onSuccess={mockOnSuccess}
  1570. />
  1571. );
  1572. await waitFor(() => {
  1573. expect(screen.getByRole('button', { name: /^print$/i })).toBeInTheDocument();
  1574. });
  1575. await user.click(screen.getByRole('button', { name: /^print$/i }));
  1576. await waitFor(() => {
  1577. expect(capturedBody).not.toBeNull();
  1578. });
  1579. // Either omitted entirely or explicitly undefined — both interpret as "keep file"
  1580. expect(capturedBody?.cleanup_library_after_dispatch).toBeUndefined();
  1581. });
  1582. });
  1583. describe('ask-for-outcome pill (#1898 follow-up)', () => {
  1584. // The pill outside the collapsed Print Options panel and the row inside it
  1585. // edit the same printOptions.confirm_outcome, so flipping either must be
  1586. // reflected by the other and land in the submitted payload.
  1587. // Both carry the label "Ask for Outcome"; the pill is the only button with
  1588. // that name, the panel row is found through its description text.
  1589. const pill = () => screen.getByRole('button', { name: 'Ask for Outcome' });
  1590. const panelRowDesc = 'Ask whether the print came out well after it completes';
  1591. const panelRow = () => screen.getByText(panelRowDesc).closest('div')!.parentElement!;
  1592. it('starts off and toggles on a click', async () => {
  1593. const user = userEvent.setup();
  1594. render(
  1595. <PrintModal mode="create" archiveId={1} archiveName="Benchy" initialSelectedPrinterIds={[1]} onClose={mockOnClose} />
  1596. );
  1597. expect(pill()).toHaveAttribute('aria-pressed', 'false');
  1598. await user.click(pill());
  1599. expect(pill()).toHaveAttribute('aria-pressed', 'true');
  1600. });
  1601. it('shares its state with the row inside Print Options', async () => {
  1602. const user = userEvent.setup();
  1603. render(
  1604. <PrintModal mode="create" archiveId={1} archiveName="Benchy" initialSelectedPrinterIds={[1]} onClose={mockOnClose} />
  1605. );
  1606. await user.click(pill());
  1607. // The panel opens expanded when a printer is preselected; expand otherwise.
  1608. if (!screen.queryByText(panelRowDesc)) await user.click(screen.getByText('Print Options'));
  1609. const row = panelRow();
  1610. expect(within(row).getByRole('button', { name: 'On' })).toHaveClass('bg-bambu-green');
  1611. await user.click(within(row).getByRole('button', { name: 'Off' }));
  1612. expect(pill()).toHaveAttribute('aria-pressed', 'false');
  1613. });
  1614. it('submits confirm_outcome=true with the queue item when turned on', async () => {
  1615. let capturedBody: Record<string, unknown> | null = null;
  1616. server.use(
  1617. http.post('/api/v1/queue/', async ({ request }) => {
  1618. capturedBody = (await request.json()) as Record<string, unknown>;
  1619. return HttpResponse.json({ id: 1, status: 'pending' });
  1620. }),
  1621. );
  1622. const user = userEvent.setup();
  1623. render(
  1624. <PrintModal mode="create" archiveId={1} archiveName="Benchy" initialSelectedPrinterIds={[1]} onClose={mockOnClose} />
  1625. );
  1626. await user.click(pill());
  1627. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1628. await waitFor(() => expect(capturedBody).not.toBeNull());
  1629. expect(capturedBody!.confirm_outcome).toBe(true);
  1630. });
  1631. it('reflects the queue item value in edit mode and saves the change', async () => {
  1632. let capturedBody: Record<string, unknown> | null = null;
  1633. server.use(
  1634. http.patch('/api/v1/queue/:id', async ({ request }) => {
  1635. capturedBody = (await request.json()) as Record<string, unknown>;
  1636. return HttpResponse.json({ id: 1, status: 'pending' });
  1637. }),
  1638. );
  1639. const user = userEvent.setup();
  1640. render(
  1641. <PrintModal
  1642. mode="edit-queue-item"
  1643. archiveId={1}
  1644. archiveName="Test Print"
  1645. queueItem={createMockQueueItem({ confirm_outcome: true })}
  1646. onClose={mockOnClose}
  1647. />
  1648. );
  1649. expect(pill()).toHaveAttribute('aria-pressed', 'true');
  1650. await user.click(pill());
  1651. await user.click(screen.getByRole('button', { name: /save/i }));
  1652. await waitFor(() => expect(capturedBody).not.toBeNull());
  1653. expect(capturedBody!.confirm_outcome).toBe(false);
  1654. });
  1655. });
  1656. });
  1657. describe('PrintModal — per-plate filament mapping (#2551 follow-up)', () => {
  1658. const mockOnClose = vi.fn();
  1659. // These tests deliberately do NOT use the shared `render` from '../utils': its
  1660. // QueryClient sets `gcTime: 0`, which evicts a query the instant it loses its
  1661. // observer. The whole-file filament requirements are fetched on open and then
  1662. // orphaned when a plate is auto-selected, so under gcTime:0 they vanish and the
  1663. // modal simply sends no mapping — the bug cannot reproduce. A real browser keeps
  1664. // that entry for 5 minutes and hands the union straight back when the user picks
  1665. // a second plate, which is what got mapped onto every plate. Same providers,
  1666. // production cache behaviour.
  1667. const render = (ui: React.ReactElement) => {
  1668. const queryClient = new QueryClient({
  1669. defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
  1670. });
  1671. return rtlRender(
  1672. <QueryClientProvider client={queryClient}>
  1673. <BrowserRouter>
  1674. <AuthProvider>
  1675. <ThemeProvider>
  1676. <ToastProvider>{ui}</ToastProvider>
  1677. </ThemeProvider>
  1678. </AuthProvider>
  1679. </BrowserRouter>
  1680. </QueryClientProvider>,
  1681. );
  1682. };
  1683. // Two plates, each printing one red object, but on different slots of the same
  1684. // file. The printer has exactly one red spool (tray 0) and one black (tray 1).
  1685. // Matching the union of both plates makes slot 1 claim the red tray and drops
  1686. // slot 2 onto the black one — so plate 2 would print in the wrong colour.
  1687. const PLATES = {
  1688. is_multi_plate: true,
  1689. plates: [
  1690. { 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 },
  1691. { 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 },
  1692. ],
  1693. };
  1694. const SLOT_1_RED = { slot_id: 1, type: 'PLA', color: '#FF0000', tray_info_idx: '', used_grams: 50 };
  1695. const SLOT_2_RED = { slot_id: 2, type: 'PLA', color: '#FF0000', tray_info_idx: '', used_grams: 50 };
  1696. beforeEach(() => {
  1697. vi.clearAllMocks();
  1698. server.use(
  1699. http.get('/api/v1/printers/', () => HttpResponse.json(mockPrinters)),
  1700. http.get('/api/v1/archives/:id/plates', () => HttpResponse.json(PLATES)),
  1701. // The endpoint is plate-aware: no plate_id yields the whole-file union.
  1702. http.get('/api/v1/archives/:id/filament-requirements', ({ request }) => {
  1703. const plateId = new URL(request.url).searchParams.get('plate_id');
  1704. if (plateId === '1') return HttpResponse.json({ filaments: [SLOT_1_RED] });
  1705. if (plateId === '2') return HttpResponse.json({ filaments: [SLOT_2_RED] });
  1706. return HttpResponse.json({ filaments: [SLOT_1_RED, SLOT_2_RED] });
  1707. }),
  1708. http.get('/api/v1/printers/:id/status', () =>
  1709. HttpResponse.json({
  1710. connected: true,
  1711. state: 'IDLE',
  1712. ams: [{ id: 0, tray: [
  1713. { id: 0, tray_type: 'PLA', tray_color: 'FF0000' },
  1714. { id: 1, tray_type: 'PLA', tray_color: '000000' },
  1715. ] }],
  1716. vt_tray: [],
  1717. }),
  1718. ),
  1719. http.get('/api/v1/printers/:id/assignments', () => HttpResponse.json([])),
  1720. http.post('/api/v1/queue/', () => HttpResponse.json({ id: 1, status: 'pending' })),
  1721. );
  1722. });
  1723. const selectBothPlates = async (user: ReturnType<typeof userEvent.setup>) => {
  1724. await waitFor(() => expect(screen.getByText('X1 Carbon')).toBeInTheDocument());
  1725. await user.click(screen.getByText('X1 Carbon'));
  1726. await waitFor(() => expect(screen.getByText('Plate 2')).toBeInTheDocument());
  1727. await user.click(screen.getByText('Plate 2')); // Plate 1 is auto-selected
  1728. };
  1729. it('shows one mapping panel per selected plate, named after the plate', async () => {
  1730. const user = userEvent.setup();
  1731. render(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  1732. await selectBothPlates(user);
  1733. await waitFor(() => {
  1734. expect(screen.getByText(/Filament Mapping — Plate 1/)).toBeInTheDocument();
  1735. expect(screen.getByText(/Filament Mapping — Plate 2/)).toBeInTheDocument();
  1736. });
  1737. });
  1738. it('sends each plate the mapping for its own slots, not the whole-file union', async () => {
  1739. const queued: { plate_id: number; ams_mapping: number[] | null }[] = [];
  1740. server.use(
  1741. http.post('/api/v1/queue/', async ({ request }) => {
  1742. queued.push((await request.json()) as { plate_id: number; ams_mapping: number[] | null });
  1743. return HttpResponse.json({ id: queued.length, status: 'pending' });
  1744. }),
  1745. );
  1746. const user = userEvent.setup();
  1747. render(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  1748. await selectBothPlates(user);
  1749. await waitFor(() => expect(screen.getByText(/Filament Mapping — Plate 2/)).toBeInTheDocument());
  1750. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1751. await waitFor(() => expect(queued.length).toBe(2));
  1752. const plate1 = queued.find((q) => q.plate_id === 1);
  1753. const plate2 = queued.find((q) => q.plate_id === 2);
  1754. // Plate 1 prints slot 1 from the red tray.
  1755. expect(plate1?.ams_mapping).toEqual([0]);
  1756. // Plate 2 prints slot 2 from the SAME red tray — slot 1 is not its business.
  1757. // The union mapping would have been [0, 1], sending this plate to the black tray.
  1758. expect(plate2?.ams_mapping).toEqual([-1, 0]);
  1759. });
  1760. it('sends no mapping when several plates fan out across several printers', async () => {
  1761. // A tray id is meaningless on a different printer, so the first printer's
  1762. // mapping must not be handed to the second. The scheduler maps each plate
  1763. // against the printer it actually dispatches to.
  1764. const queued: { printer_id: number; ams_mapping?: number[] | null }[] = [];
  1765. server.use(
  1766. http.post('/api/v1/queue/', async ({ request }) => {
  1767. queued.push((await request.json()) as { printer_id: number; ams_mapping?: number[] | null });
  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 waitFor(() => expect(screen.getByText('Plate 2')).toBeInTheDocument());
  1777. await user.click(screen.getByText('Plate 2'));
  1778. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1779. await waitFor(() => expect(queued.length).toBe(4)); // 2 plates x 2 printers
  1780. queued.forEach((q) => expect(q.ams_mapping ?? null).toBeNull());
  1781. });
  1782. it('sends no mapping for a model-assigned multi-plate job, leaving it to the scheduler', async () => {
  1783. const queued: { ams_mapping?: number[] | null }[] = [];
  1784. server.use(
  1785. http.post('/api/v1/queue/', async ({ request }) => {
  1786. queued.push((await request.json()) as { ams_mapping?: number[] | null });
  1787. return HttpResponse.json({ id: queued.length, status: 'pending' });
  1788. }),
  1789. );
  1790. const user = userEvent.setup();
  1791. render(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  1792. // "Any model" mode: no printer is chosen, so there is no AMS to map onto and
  1793. // the scheduler computes the mapping per plate once it picks one.
  1794. await waitFor(() => expect(screen.getByText('Plate 2')).toBeInTheDocument());
  1795. await user.click(screen.getByText('Plate 2'));
  1796. await user.click(screen.getByRole('button', { name: /any model/i }));
  1797. await waitFor(() => expect(screen.getByRole('combobox')).toBeInTheDocument());
  1798. await user.selectOptions(screen.getByRole('combobox'), 'X1C');
  1799. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1800. await waitFor(() => expect(queued.length).toBe(2));
  1801. queued.forEach((q) => expect(q.ams_mapping ?? null).toBeNull());
  1802. });
  1803. it('drops a plate\'s manual tray overrides when the printer changes', async () => {
  1804. // A manual override holds a global tray id, which names a different spool on a
  1805. // different printer. Carrying plate 1's "slot 1 -> tray 1" from the X1C over to
  1806. // the P1S would dispatch a tray the user never picked.
  1807. const queued: { plate_id: number; ams_mapping: number[] | null }[] = [];
  1808. server.use(
  1809. http.post('/api/v1/queue/', async ({ request }) => {
  1810. queued.push((await request.json()) as { plate_id: number; ams_mapping: number[] | null });
  1811. return HttpResponse.json({ id: queued.length, status: 'pending' });
  1812. }),
  1813. );
  1814. const user = userEvent.setup();
  1815. render(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  1816. await selectBothPlates(user);
  1817. await waitFor(() => expect(screen.getByText(/Filament Mapping — Plate 1/)).toBeInTheDocument());
  1818. // Force plate 1's slot 1 onto the black tray (1) instead of the auto-matched red (0).
  1819. // A2 is AMS 0 / tray 1, i.e. global tray id 1 — the value the old
  1820. // `selectOptions(..., '1')` picked.
  1821. await user.click(screen.getByText(/Filament Mapping — Plate 1/));
  1822. await pickFromSlotPicker(user, /printer slot for/i, /^A2:/);
  1823. // Now move the job to the other printer.
  1824. await user.click(screen.getByText('X1 Carbon')); // deselect
  1825. await user.click(screen.getByText('P1S'));
  1826. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1827. await waitFor(() => expect(queued.length).toBe(2));
  1828. // Plate 1 auto-matches red (tray 0) on the new printer. Tray 1 is the stale pick.
  1829. const plate1 = queued.find((q) => q.plate_id === 1);
  1830. expect(plate1?.ams_mapping).toEqual([0]);
  1831. });
  1832. it('sets Print Anyway only on the printers whose filament warning it answered', async () => {
  1833. // X1 Carbon is short on the mapped spool, P1S is not. Answering the warning
  1834. // for X1 Carbon must not wave P1S's job through the scheduler's own check.
  1835. const queued: { printer_id: number; skip_filament_check?: boolean }[] = [];
  1836. server.use(
  1837. http.get('/api/v1/printers/:id/inventory-remain', ({ params }) => {
  1838. const grams = params.id === '1' ? 10 : 1000;
  1839. return HttpResponse.json({
  1840. inventory_remain_g: { '0': grams },
  1841. slot_materials: [
  1842. { ams_id: 0, tray_id: 0, global_tray_id: 0, material_key: 'preset:GFA00|color:FF0000', remaining_g: grams, extruder: 0 },
  1843. ],
  1844. });
  1845. }),
  1846. http.post('/api/v1/queue/', async ({ request }) => {
  1847. queued.push((await request.json()) as { printer_id: number; skip_filament_check?: boolean });
  1848. return HttpResponse.json({ id: queued.length, status: 'pending' });
  1849. }),
  1850. );
  1851. const user = userEvent.setup();
  1852. render(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  1853. await waitFor(() => expect(screen.getByText('X1 Carbon')).toBeInTheDocument());
  1854. await user.click(screen.getByText('X1 Carbon'));
  1855. await user.click(screen.getByText('P1S'));
  1856. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1857. await waitFor(() => expect(screen.getByText(/Not enough filament/i)).toBeInTheDocument());
  1858. await user.click(screen.getByRole('button', { name: /print anyway/i }));
  1859. await waitFor(() => expect(queued.length).toBe(2));
  1860. const byPrinter = Object.fromEntries(queued.map((q) => [q.printer_id, q.skip_filament_check]));
  1861. expect(byPrinter).toEqual({ 1: true, 2: undefined });
  1862. });
  1863. it('sums what the plates draw from one spool before warning about it', async () => {
  1864. // Both plates map to the same red tray. 60 g left covers either plate on its
  1865. // own (40 g), but not both — the check has to add them up, not test them
  1866. // one at a time.
  1867. server.use(
  1868. http.get('/api/v1/archives/:id/filament-requirements', ({ request }) => {
  1869. const plateId = new URL(request.url).searchParams.get('plate_id');
  1870. if (plateId === '1') return HttpResponse.json({ filaments: [{ ...SLOT_1_RED, used_grams: 40 }] });
  1871. if (plateId === '2') return HttpResponse.json({ filaments: [{ ...SLOT_2_RED, used_grams: 40 }] });
  1872. return HttpResponse.json({ filaments: [SLOT_1_RED, SLOT_2_RED] });
  1873. }),
  1874. http.get('/api/v1/printers/:id/inventory-remain', () =>
  1875. HttpResponse.json({
  1876. inventory_remain_g: { '0': 60 },
  1877. slot_materials: [
  1878. { ams_id: 0, tray_id: 0, global_tray_id: 0, material_key: 'preset:GFA00|color:FF0000', remaining_g: 60, extruder: 0 },
  1879. ],
  1880. }),
  1881. ),
  1882. );
  1883. const user = userEvent.setup();
  1884. render(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  1885. await selectBothPlates(user);
  1886. await waitFor(() => expect(screen.getByText(/Filament Mapping — Plate 2/)).toBeInTheDocument());
  1887. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1888. // 80 g needed from a spool with 60 g left → the acknowledgement dialog, not a
  1889. // silent queue.
  1890. await waitFor(() => expect(screen.getByText(/Not enough filament/i)).toBeInTheDocument());
  1891. expect(screen.getByText(/needs 80g, remaining 60g/i)).toBeInTheDocument();
  1892. });
  1893. // Two red trays holding the same material, so AMS Filament Backup can switch
  1894. // between them mid-print. Both tests below map both plates onto tray 0.
  1895. const twoRedTrays = (backupOn: boolean) =>
  1896. http.get('/api/v1/printers/:id/status', () =>
  1897. HttpResponse.json({
  1898. connected: true,
  1899. state: 'IDLE',
  1900. ams_filament_backup: backupOn,
  1901. ams: [{ id: 0, tray: [
  1902. { id: 0, tray_type: 'PLA', tray_color: 'FF0000' },
  1903. { id: 1, tray_type: 'PLA', tray_color: 'FF0000' },
  1904. ] }],
  1905. vt_tray: [],
  1906. }),
  1907. );
  1908. const redPool = (trayZeroGrams: number, trayOneGrams: number) =>
  1909. http.get('/api/v1/printers/:id/inventory-remain', () =>
  1910. HttpResponse.json({
  1911. inventory_remain_g: { '0': trayZeroGrams, '1': trayOneGrams },
  1912. slot_materials: [
  1913. { ams_id: 0, tray_id: 0, global_tray_id: 0, material_key: 'preset:GFA00|color:FF0000', remaining_g: trayZeroGrams, extruder: 0 },
  1914. { ams_id: 0, tray_id: 1, global_tray_id: 1, material_key: 'preset:GFA00|color:FF0000', remaining_g: trayOneGrams, extruder: 0 },
  1915. ],
  1916. }),
  1917. );
  1918. const bothPlatesNeedForty = http.get('/api/v1/archives/:id/filament-requirements', ({ request }) => {
  1919. const plateId = new URL(request.url).searchParams.get('plate_id');
  1920. if (plateId === '1') return HttpResponse.json({ filaments: [{ ...SLOT_1_RED, used_grams: 40 }] });
  1921. if (plateId === '2') return HttpResponse.json({ filaments: [{ ...SLOT_2_RED, used_grams: 40 }] });
  1922. return HttpResponse.json({ filaments: [SLOT_1_RED, SLOT_2_RED] });
  1923. });
  1924. it('lets the print through when AMS Filament Backup covers it from a peer spool', async () => {
  1925. // The reported block: two plates draw 80 g from a tray holding 60 g, but the
  1926. // slot next to it holds the same material. The firmware switches between
  1927. // them, and the dispatcher has pooled them since #1762 — the modal used to
  1928. // weigh the mapped slot alone and refused a print the dispatcher would run.
  1929. const queued: unknown[] = [];
  1930. server.use(
  1931. bothPlatesNeedForty,
  1932. twoRedTrays(true),
  1933. redPool(60, 1000),
  1934. http.post('/api/v1/queue/', async ({ request }) => {
  1935. queued.push(await request.json());
  1936. return HttpResponse.json({ id: queued.length, status: 'pending' });
  1937. }),
  1938. );
  1939. const user = userEvent.setup();
  1940. render(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  1941. await selectBothPlates(user);
  1942. await waitFor(() => expect(screen.getByText(/Filament Mapping — Plate 2/)).toBeInTheDocument());
  1943. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1944. await waitFor(() => expect(queued.length).toBe(2));
  1945. expect(screen.queryByText(/Not enough filament/i)).not.toBeInTheDocument();
  1946. });
  1947. it('warns against the pooled total when AMS Filament Backup still cannot cover it', async () => {
  1948. // Backup is on but both spools together are short. The shortfall is real, so
  1949. // it still has to be raised — against the pool, not the one slot, or the
  1950. // numbers contradict the AMS the user is looking at.
  1951. server.use(bothPlatesNeedForty, twoRedTrays(true), redPool(60, 10));
  1952. const user = userEvent.setup();
  1953. render(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  1954. await selectBothPlates(user);
  1955. await waitFor(() => expect(screen.getByText(/Filament Mapping — Plate 2/)).toBeInTheDocument());
  1956. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1957. await waitFor(() => expect(screen.getByText(/Not enough filament/i)).toBeInTheDocument());
  1958. expect(screen.getByText(/needs 80g, 70g available across matching spools/i)).toBeInTheDocument();
  1959. });
  1960. it('keeps weighing the mapped slot alone when AMS Filament Backup is off', async () => {
  1961. // Same two spools, backup off: the firmware will not switch, so the peer's
  1962. // grams are not available to this print and the warning must still fire.
  1963. server.use(bothPlatesNeedForty, twoRedTrays(false), redPool(60, 1000));
  1964. const user = userEvent.setup();
  1965. render(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  1966. await selectBothPlates(user);
  1967. await waitFor(() => expect(screen.getByText(/Filament Mapping — Plate 2/)).toBeInTheDocument());
  1968. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1969. await waitFor(() => expect(screen.getByText(/Not enough filament/i)).toBeInTheDocument());
  1970. expect(screen.getByText(/needs 80g, remaining 60g/i)).toBeInTheDocument();
  1971. });
  1972. it('holds the Print button until every selected plate has answered', async () => {
  1973. // A plate whose filaments cannot be read has no mapping and no forced colours;
  1974. // queueing it anyway prints it in whatever happens to be loaded.
  1975. server.use(
  1976. http.get('/api/v1/archives/:id/filament-requirements', ({ request }) => {
  1977. const plateId = new URL(request.url).searchParams.get('plate_id');
  1978. if (plateId === '1') return HttpResponse.json({ filaments: [SLOT_1_RED] });
  1979. if (plateId === '2') return new HttpResponse(null, { status: 500 });
  1980. return HttpResponse.json({ filaments: [SLOT_1_RED, SLOT_2_RED] });
  1981. }),
  1982. );
  1983. const user = userEvent.setup();
  1984. render(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  1985. await selectBothPlates(user);
  1986. await waitFor(() =>
  1987. expect(document.querySelector('button[type="submit"]')).toBeDisabled(),
  1988. );
  1989. expect(screen.getByText(/could not be read/i)).toBeInTheDocument();
  1990. // Deselecting the unreadable plate frees the rest of the job.
  1991. await user.click(screen.getByText('Plate 2'));
  1992. await waitFor(() =>
  1993. expect(document.querySelector('button[type="submit"]')).not.toBeDisabled(),
  1994. );
  1995. });
  1996. });
  1997. describe('PrintModal — per-plate filament override in model mode (#2552)', () => {
  1998. const mockOnClose = vi.fn();
  1999. // The reporter's trigger — "only after the file was previously queued or printed"
  2000. // — is really "only once the plates query is warm in the cache". On a cold cache
  2001. // the plates data is undefined for the first render, so the whole-file filament
  2002. // requirements are fetched and left behind; the override panel then rendered from
  2003. // that union. On a warm cache the modal knows it is multi-plate from the first
  2004. // render, the whole-file query never runs, and the panel disappeared entirely.
  2005. // Both states are exercised here, and neither may depend on the cache.
  2006. const renderWithCache = (ui: React.ReactElement, prewarm?: (qc: QueryClient) => void) => {
  2007. const queryClient = new QueryClient({
  2008. defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
  2009. });
  2010. prewarm?.(queryClient);
  2011. return rtlRender(
  2012. <QueryClientProvider client={queryClient}>
  2013. <BrowserRouter>
  2014. <AuthProvider>
  2015. <ThemeProvider>
  2016. <ToastProvider>{ui}</ToastProvider>
  2017. </ThemeProvider>
  2018. </AuthProvider>
  2019. </BrowserRouter>
  2020. </QueryClientProvider>,
  2021. );
  2022. };
  2023. // Plate 1 prints slot 1 (red), plate 2 prints slot 2 (blue). Nothing is shared.
  2024. const PLATES = {
  2025. is_multi_plate: true,
  2026. plates: [
  2027. { 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 },
  2028. { 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 },
  2029. ],
  2030. };
  2031. const SLOT_1_RED = { slot_id: 1, type: 'PLA', color: '#FF0000', tray_info_idx: '', used_grams: 50 };
  2032. const SLOT_2_BLUE = { slot_id: 2, type: 'PLA', color: '#0000FF', tray_info_idx: '', used_grams: 50 };
  2033. beforeEach(() => {
  2034. vi.clearAllMocks();
  2035. server.use(
  2036. http.get('/api/v1/printers/', () => HttpResponse.json(mockPrinters)),
  2037. http.get('/api/v1/archives/:id/plates', () => HttpResponse.json(PLATES)),
  2038. http.get('/api/v1/archives/:id/filament-requirements', ({ request }) => {
  2039. const plateId = new URL(request.url).searchParams.get('plate_id');
  2040. if (plateId === '1') return HttpResponse.json({ filaments: [SLOT_1_RED] });
  2041. if (plateId === '2') return HttpResponse.json({ filaments: [SLOT_2_BLUE] });
  2042. return HttpResponse.json({ filaments: [SLOT_1_RED, SLOT_2_BLUE] });
  2043. }),
  2044. http.get('/api/v1/printers/available-filaments', () =>
  2045. HttpResponse.json([
  2046. { type: 'PLA', color: '#FF0000', tray_info_idx: 'GFA00', tray_sub_brands: 'PLA Basic', extruder_id: null },
  2047. { type: 'PLA', color: '#00FF00', tray_info_idx: 'GFA00', tray_sub_brands: 'PLA Basic', extruder_id: null },
  2048. ]),
  2049. ),
  2050. http.post('/api/v1/queue/', () => HttpResponse.json({ id: 1, status: 'pending' })),
  2051. );
  2052. });
  2053. const selectAnyX1CAndBothPlates = async (user: ReturnType<typeof userEvent.setup>) => {
  2054. await waitFor(() => expect(screen.getByText('Plate 2')).toBeInTheDocument());
  2055. await user.click(screen.getByText('Plate 2')); // Plate 1 is auto-selected
  2056. await user.click(screen.getByRole('button', { name: /any model/i }));
  2057. // Switching to model mode pre-selects the first model, so the override panels
  2058. // are already up; the target-model select is the one offering the models.
  2059. const modelSelect = await waitFor(() => {
  2060. const select = screen
  2061. .getAllByRole('combobox')
  2062. .find((el) => (el as HTMLSelectElement).options[0]?.value === '' && (el as HTMLSelectElement).options[0]?.text === 'Select a model...');
  2063. if (!select) throw new Error('target model select not rendered');
  2064. return select as HTMLSelectElement;
  2065. });
  2066. await user.selectOptions(modelSelect, 'X1C');
  2067. };
  2068. it('shows one override panel per selected plate even when the plates query is already cached', async () => {
  2069. const user = userEvent.setup();
  2070. renderWithCache(
  2071. <PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />,
  2072. // The file has been opened before: the plates are known on the first render,
  2073. // so the whole-file requirements query never runs. This is the state in which
  2074. // the override section used to vanish for a multi-plate selection.
  2075. (qc) => qc.setQueryData(['archive-plates', 1], PLATES),
  2076. );
  2077. await selectAnyX1CAndBothPlates(user);
  2078. await waitFor(() => {
  2079. expect(screen.getByText(/Filament Override — Plate 1/)).toBeInTheDocument();
  2080. expect(screen.getByText(/Filament Override — Plate 2/)).toBeInTheDocument();
  2081. });
  2082. });
  2083. it('shows the same per-plate panels on a cold cache', async () => {
  2084. const user = userEvent.setup();
  2085. renderWithCache(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  2086. await selectAnyX1CAndBothPlates(user);
  2087. await waitFor(() => {
  2088. expect(screen.getByText(/Filament Override — Plate 1/)).toBeInTheDocument();
  2089. expect(screen.getByText(/Filament Override — Plate 2/)).toBeInTheDocument();
  2090. });
  2091. // Not the whole-file union in a single unnamed panel.
  2092. expect(screen.queryByText('Filament Override')).not.toBeInTheDocument();
  2093. });
  2094. it('sends each plate only the overrides for the slots it prints', async () => {
  2095. type Queued = {
  2096. plate_id: number;
  2097. filament_overrides?: Array<{ slot_id: number; force_color_match: boolean }> | null;
  2098. };
  2099. const queued: Queued[] = [];
  2100. server.use(
  2101. http.post('/api/v1/queue/', async ({ request }) => {
  2102. queued.push((await request.json()) as Queued);
  2103. return HttpResponse.json({ id: queued.length, status: 'pending' });
  2104. }),
  2105. );
  2106. const user = userEvent.setup();
  2107. renderWithCache(
  2108. <PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />,
  2109. (qc) => qc.setQueryData(['archive-plates', 1], PLATES),
  2110. );
  2111. await selectAnyX1CAndBothPlates(user);
  2112. await waitFor(() => expect(screen.getByText(/Filament Override — Plate 2/)).toBeInTheDocument());
  2113. // Force the colour on plate 2's only slot. Plate 1 does not print slot 2 and
  2114. // must not be held back waiting for a blue spool it never uses (#2551).
  2115. const forceBoxes = screen.getAllByRole('checkbox', { name: /force color match/i });
  2116. expect(forceBoxes).toHaveLength(2); // one slot per plate
  2117. await user.click(forceBoxes[1]);
  2118. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  2119. await waitFor(() => expect(queued.length).toBe(2));
  2120. const plate1 = queued.find((q) => q.plate_id === 1);
  2121. const plate2 = queued.find((q) => q.plate_id === 2);
  2122. expect(plate1?.filament_overrides ?? null).toBeNull();
  2123. expect(plate2?.filament_overrides).toEqual([
  2124. expect.objectContaining({ slot_id: 2, force_color_match: true }),
  2125. ]);
  2126. });
  2127. // The queue page shows the stored colour name. The same blue is "Marine
  2128. // Blue" in PLA Matte; the plain type "PLA" only reaches the generic name (SN-C9).
  2129. it("stores a forced slot's colour name within its sliced product line", async () => {
  2130. setColorCatalog({ '0000ff': 'Blue' }, { 'PLA Matte|0000ff': 'Marine Blue' });
  2131. type Queued = { plate_id: number; filament_overrides?: Array<{ slot_id: number; color_name?: string }> | null };
  2132. const queued: Queued[] = [];
  2133. server.use(
  2134. http.get('/api/v1/archives/:id/filament-requirements', () =>
  2135. HttpResponse.json({ filaments: [{ ...SLOT_2_BLUE, tray_info_idx: 'GFA01' }] }),
  2136. ),
  2137. http.get('/api/v1/cloud/builtin-filaments', () =>
  2138. HttpResponse.json([{ filament_id: 'GFA01', name: 'Bambu PLA Matte' }]),
  2139. ),
  2140. http.get('/api/v1/cloud/filament-id-map', () => HttpResponse.json({})),
  2141. http.post('/api/v1/queue/', async ({ request }) => {
  2142. queued.push((await request.json()) as Queued);
  2143. return HttpResponse.json({ id: queued.length, status: 'pending' });
  2144. }),
  2145. );
  2146. try {
  2147. const user = userEvent.setup();
  2148. renderWithCache(
  2149. <PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />,
  2150. (qc) => qc.setQueryData(['archive-plates', 1], PLATES),
  2151. );
  2152. await selectAnyX1CAndBothPlates(user);
  2153. await waitFor(() => expect(screen.getByText(/Filament Override — Plate 2/)).toBeInTheDocument());
  2154. // Wait for the preset names, which the stored colour name is derived from.
  2155. await waitFor(() => expect(screen.getAllByText(/PLA Matte/).length).toBeGreaterThan(0));
  2156. await user.click(screen.getAllByRole('checkbox', { name: /force color match/i })[1]);
  2157. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  2158. await waitFor(() => expect(queued.length).toBe(2));
  2159. expect(queued.find((q) => q.plate_id === 2)?.filament_overrides).toEqual([
  2160. expect.objectContaining({ slot_id: 2, color_name: 'Marine Blue' }),
  2161. ]);
  2162. } finally {
  2163. __resetColorCatalogForTests();
  2164. }
  2165. });
  2166. it("does not name a swapped slot's colour by the preset it was sliced with", async () => {
  2167. setColorCatalog({ '00ff00': 'Green' }, { 'PLA Matte|00ff00': 'Matte Green' });
  2168. type Queued = { plate_id: number; filament_overrides?: Array<{ slot_id: number; color_name?: string }> | null };
  2169. const queued: Queued[] = [];
  2170. server.use(
  2171. http.get('/api/v1/archives/:id/filament-requirements', () =>
  2172. HttpResponse.json({ filaments: [{ ...SLOT_2_BLUE, tray_info_idx: 'GFA01' }] }),
  2173. ),
  2174. http.get('/api/v1/cloud/builtin-filaments', () =>
  2175. HttpResponse.json([{ filament_id: 'GFA01', name: 'Bambu PLA Matte' }]),
  2176. ),
  2177. http.get('/api/v1/cloud/filament-id-map', () => HttpResponse.json({})),
  2178. http.post('/api/v1/queue/', async ({ request }) => {
  2179. queued.push((await request.json()) as Queued);
  2180. return HttpResponse.json({ id: queued.length, status: 'pending' });
  2181. }),
  2182. );
  2183. try {
  2184. const user = userEvent.setup();
  2185. renderWithCache(
  2186. <PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />,
  2187. (qc) => qc.setQueryData(['archive-plates', 1], PLATES),
  2188. );
  2189. await selectAnyX1CAndBothPlates(user);
  2190. await waitFor(() => expect(screen.getByText(/Filament Override — Plate 2/)).toBeInTheDocument());
  2191. await waitFor(() => expect(screen.getAllByText(/PLA Matte/).length).toBeGreaterThan(0));
  2192. // Swap the PLA Matte blue for the loaded PLA Basic green.
  2193. const pickers = screen.getAllByRole('combobox', { name: /filament override for/i });
  2194. await user.click(pickers[pickers.length - 1]);
  2195. await user.click(within(await screen.findByRole('listbox')).getByText(/Green/));
  2196. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  2197. await waitFor(() => expect(queued.length).toBe(2));
  2198. expect(queued.find((q) => q.plate_id === 2)?.filament_overrides).toEqual([
  2199. expect.objectContaining({ slot_id: 2, color: '#00FF00', color_name: 'Green' }),
  2200. ]);
  2201. } finally {
  2202. __resetColorCatalogForTests();
  2203. }
  2204. });
  2205. });
  2206. describe('PrintModal — per-plate quantity (#342)', () => {
  2207. const mockOnClose = vi.fn();
  2208. const PLATES = {
  2209. is_multi_plate: true,
  2210. plates: [
  2211. { 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 },
  2212. { 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 },
  2213. { 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 },
  2214. ],
  2215. };
  2216. const renderModal = (ui: React.ReactElement) => {
  2217. const queryClient = new QueryClient({
  2218. defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
  2219. });
  2220. queryClient.setQueryData(['archive-plates', 1], PLATES);
  2221. return rtlRender(
  2222. <QueryClientProvider client={queryClient}>
  2223. <BrowserRouter>
  2224. <AuthProvider>
  2225. <ThemeProvider>
  2226. <ToastProvider>{ui}</ToastProvider>
  2227. </ThemeProvider>
  2228. </AuthProvider>
  2229. </BrowserRouter>
  2230. </QueryClientProvider>,
  2231. );
  2232. };
  2233. beforeEach(() => {
  2234. vi.clearAllMocks();
  2235. server.use(
  2236. http.get('/api/v1/printers/', () => HttpResponse.json(mockPrinters)),
  2237. http.get('/api/v1/archives/:id/plates', () => HttpResponse.json(PLATES)),
  2238. http.get('/api/v1/archives/:id/filament-requirements', () =>
  2239. HttpResponse.json({ filaments: [{ slot_id: 1, type: 'PLA', color: '#FF0000', tray_info_idx: '', used_grams: 50 }] }),
  2240. ),
  2241. http.get('/api/v1/printers/available-filaments', () => HttpResponse.json([])),
  2242. http.post('/api/v1/queue/batches', () => HttpResponse.json({ id: 42, name: 'Order', status: 'active' })),
  2243. http.post('/api/v1/queue/', () => HttpResponse.json({ id: 1, status: 'pending' })),
  2244. );
  2245. });
  2246. const qtyInput = (plateName: string) =>
  2247. screen.getByRole('spinbutton', { name: new RegExp(plateName, 'i') });
  2248. it('replaces the single Quantity field with one control per selected plate', async () => {
  2249. const user = userEvent.setup();
  2250. renderModal(<PrintModal mode="create" archiveId={1} archiveName="Three.gcode.3mf" onClose={mockOnClose} />);
  2251. await waitFor(() => expect(screen.getByText('Plate 2')).toBeInTheDocument());
  2252. // Plate 1 is auto-selected and already carries its own quantity control.
  2253. expect(qtyInput('Plate 1')).toBeInTheDocument();
  2254. // The global field is gone — two controls for the same number would be ambiguous.
  2255. expect(screen.queryByLabelText(/^Quantity$/i)).not.toBeInTheDocument();
  2256. // Unselected plates have no control.
  2257. expect(screen.queryByRole('spinbutton', { name: /Plate 2/i })).not.toBeInTheDocument();
  2258. await user.click(screen.getByText('Plate 2'));
  2259. await waitFor(() => expect(qtyInput('Plate 2')).toBeInTheDocument());
  2260. });
  2261. it('keeps the single Quantity field for a single-plate file', async () => {
  2262. const queryClient = new QueryClient({
  2263. defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
  2264. });
  2265. queryClient.setQueryData(['archive-plates', 1], { is_multi_plate: false, plates: [] });
  2266. rtlRender(
  2267. <QueryClientProvider client={queryClient}>
  2268. <BrowserRouter>
  2269. <AuthProvider>
  2270. <ThemeProvider>
  2271. <ToastProvider>
  2272. <PrintModal mode="create" archiveId={1} archiveName="One.gcode.3mf" onClose={mockOnClose} />
  2273. </ToastProvider>
  2274. </ThemeProvider>
  2275. </AuthProvider>
  2276. </BrowserRouter>
  2277. </QueryClientProvider>,
  2278. );
  2279. await waitFor(() => expect(screen.getByLabelText(/^Quantity$/i)).toBeInTheDocument());
  2280. });
  2281. it('queues the reporter\'s example: plate 1 once, plate 2 twice, plate 3 three times', async () => {
  2282. type Queued = { plate_id: number | null; quantity?: number; batch_id?: number };
  2283. type OrderBody = { plates?: Array<{ plate_id: number | null; quantity_target: number }> };
  2284. const queued: Queued[] = [];
  2285. let order: OrderBody | null = null;
  2286. server.use(
  2287. http.post('/api/v1/queue/batches', async ({ request }) => {
  2288. order = (await request.json()) as OrderBody;
  2289. return HttpResponse.json({ id: 42, name: 'Order', status: 'active' });
  2290. }),
  2291. http.post('/api/v1/queue/', async ({ request }) => {
  2292. queued.push((await request.json()) as Queued);
  2293. return HttpResponse.json({ id: queued.length, status: 'pending' });
  2294. }),
  2295. );
  2296. const user = userEvent.setup();
  2297. renderModal(<PrintModal mode="create" archiveId={1} archiveName="Three.gcode.3mf" onClose={mockOnClose} />);
  2298. await waitFor(() => expect(screen.getByText('Plate 2')).toBeInTheDocument());
  2299. await user.click(screen.getByText('Plate 2'));
  2300. await user.click(screen.getByText('Plate 3'));
  2301. fireEvent.change(qtyInput('Plate 2'), { target: { value: '2' } });
  2302. fireEvent.change(qtyInput('Plate 3'), { target: { value: '3' } });
  2303. await waitFor(() => expect(screen.getByText(/6 runs in total/i)).toBeInTheDocument());
  2304. await user.click(screen.getAllByRole('button', { name: /X1 Carbon/i })[0]);
  2305. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  2306. await waitFor(() => expect(queued.length).toBe(3));
  2307. // The order records the intent, so a failed run still reads as owed.
  2308. expect(order!.plates).toEqual([
  2309. expect.objectContaining({ plate_id: 1, quantity_target: 1 }),
  2310. expect.objectContaining({ plate_id: 2, quantity_target: 2 }),
  2311. expect.objectContaining({ plate_id: 3, quantity_target: 3 }),
  2312. ]);
  2313. // ...and the runs are dispatched immediately, one call per plate carrying
  2314. // that plate's own count. Quantity 1 is left off the payload as before.
  2315. const byPlate = Object.fromEntries(queued.map((q) => [q.plate_id, q]));
  2316. expect(byPlate[1].quantity).toBeUndefined();
  2317. expect(byPlate[2].quantity).toBe(2);
  2318. expect(byPlate[3].quantity).toBe(3);
  2319. expect(queued.every((q) => q.batch_id === 42)).toBe(true);
  2320. });
  2321. it('does not multiply per-plate counts across a multi-printer fan-out', async () => {
  2322. type Queued = { plate_id: number | null; quantity?: number; printer_id: number | null };
  2323. const queued: Queued[] = [];
  2324. server.use(
  2325. http.post('/api/v1/queue/', async ({ request }) => {
  2326. queued.push((await request.json()) as Queued);
  2327. return HttpResponse.json({ id: queued.length, status: 'pending' });
  2328. }),
  2329. );
  2330. const user = userEvent.setup();
  2331. renderModal(<PrintModal mode="create" archiveId={1} archiveName="Three.gcode.3mf" onClose={mockOnClose} />);
  2332. await waitFor(() => expect(screen.getByText('Plate 2')).toBeInTheDocument());
  2333. await user.click(screen.getByText('Plate 2'));
  2334. fireEvent.change(qtyInput('Plate 2'), { target: { value: '4' } });
  2335. // Two printers: the printer count already answers "how many".
  2336. await user.click(screen.getAllByRole('button', { name: /X1 Carbon/i })[0]);
  2337. await user.click(screen.getAllByRole('button', { name: /P1S/i })[0]);
  2338. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  2339. await waitFor(() => expect(queued.length).toBe(4)); // 2 plates × 2 printers
  2340. expect(queued.every((q) => q.quantity === undefined)).toBe(true);
  2341. });
  2342. });
  2343. describe('PrintModal — override survives "Any model" -> "Specific Printer" (#3133)', () => {
  2344. const mockOnClose = vi.fn();
  2345. const PRINTERS = [
  2346. { id: 1, name: 'Printer 01', model: 'P2S', ip_address: '192.168.1.101', enabled: true, is_active: true },
  2347. { id: 2, name: 'Printer 02', model: 'X1C', ip_address: '192.168.1.102', enabled: true, is_active: true },
  2348. ];
  2349. const BROWN = '#8B4513';
  2350. const BONE_WHITE = '#F5F5DC';
  2351. // The 3MF was sliced in brown; the user asked for Bone White.
  2352. const SLOT_1_BROWN = { slot_id: 1, type: 'PLA', color: BROWN, tray_info_idx: 'GFA00', used_grams: 50 };
  2353. type Patched = {
  2354. printer_id?: number | null;
  2355. target_model?: string | null;
  2356. ams_mapping?: number[] | null;
  2357. filament_overrides?: Array<{ slot_id: number; type: string; color: string }> | null;
  2358. };
  2359. let patched: Patched[];
  2360. let posted: Patched[];
  2361. const statusWith = (trays: Array<{ id: number; tray_type: string; tray_color: string }>) =>
  2362. HttpResponse.json({ connected: true, state: 'IDLE', ams: [{ id: 0, tray: trays }], vt_tray: [] });
  2363. beforeEach(() => {
  2364. vi.clearAllMocks();
  2365. patched = [];
  2366. posted = [];
  2367. server.use(
  2368. http.get('/api/v1/printers/', () => HttpResponse.json(PRINTERS)),
  2369. http.get('/api/v1/archives/:id/plates', () => HttpResponse.json({ is_multi_plate: false, plates: [] })),
  2370. http.get('/api/v1/archives/:id/filament-requirements', () => HttpResponse.json({ filaments: [SLOT_1_BROWN] })),
  2371. http.get('/api/v1/printers/available-filaments', () =>
  2372. HttpResponse.json([
  2373. { type: 'PLA', color: BROWN, tray_info_idx: 'GFA00', tray_sub_brands: 'PLA Basic', extruder_id: null },
  2374. { type: 'PLA', color: BONE_WHITE, tray_info_idx: 'GFA00', tray_sub_brands: 'PLA Basic', extruder_id: null },
  2375. ]),
  2376. ),
  2377. // Printer 01 has both colours loaded; brown is first, so a match against
  2378. // the 3MF picks tray 0 and a match against the override picks tray 1.
  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: 'F5F5DCFF' },
  2383. ]),
  2384. ),
  2385. http.get('/api/v1/printers/:id/assignments', () => HttpResponse.json([])),
  2386. http.patch('/api/v1/queue/:id', async ({ request }) => {
  2387. patched.push((await request.json()) as Patched);
  2388. return HttpResponse.json({ id: 1, status: 'pending' });
  2389. }),
  2390. http.post('/api/v1/queue/', async ({ request }) => {
  2391. posted.push((await request.json()) as Patched);
  2392. return HttpResponse.json({ id: 1, status: 'pending' });
  2393. }),
  2394. );
  2395. });
  2396. const anyP2SItem = () =>
  2397. createMockQueueItem({
  2398. printer_id: null,
  2399. target_model: 'P2S',
  2400. filament_overrides: [{ slot_id: 1, type: 'PLA', color: BONE_WHITE, force_color_match: false }],
  2401. } as Partial<PrintQueueItem>);
  2402. const moveToPrinter01 = async (user: ReturnType<typeof userEvent.setup>) => {
  2403. await user.click(await screen.findByRole('button', { name: /specific printer/i }));
  2404. await user.click(await screen.findByText('Printer 01'));
  2405. };
  2406. const submit = async (user: ReturnType<typeof userEvent.setup>) => {
  2407. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  2408. };
  2409. // The slot picker's list is portaled to <body>, outside the dialog's own
  2410. // DOM, and the dialog closes both on a click outside itself and on Escape.
  2411. // Either would be a bad regression: picking a slot, or dismissing the list,
  2412. // would throw away everything typed into the dialog (#3159).
  2413. it('does not close the dialog when a slot is picked from the portaled list', async () => {
  2414. const user = userEvent.setup();
  2415. render(<PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={anyP2SItem()} onClose={mockOnClose} />);
  2416. await moveToPrinter01(user);
  2417. // The panel is collapsed by default; the picker only exists once open.
  2418. await user.click(await screen.findByText(/filament mapping/i));
  2419. const trigger = await screen.findByRole('combobox', { name: /printer slot for/i });
  2420. await user.click(trigger);
  2421. const listbox = await screen.findByRole('listbox');
  2422. await user.click(within(listbox).getAllByRole('option')[1]);
  2423. expect(mockOnClose).not.toHaveBeenCalled();
  2424. expect(screen.getByText(/filament mapping/i)).toBeInTheDocument();
  2425. });
  2426. it('closes only the slot list on Escape, not the dialog', async () => {
  2427. const user = userEvent.setup();
  2428. render(<PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={anyP2SItem()} onClose={mockOnClose} />);
  2429. await moveToPrinter01(user);
  2430. await user.click(await screen.findByText(/filament mapping/i));
  2431. await user.click(await screen.findByRole('combobox', { name: /printer slot for/i }));
  2432. await screen.findByRole('listbox');
  2433. await user.keyboard('{Escape}');
  2434. await waitFor(() => expect(screen.queryByRole('listbox')).not.toBeInTheDocument());
  2435. expect(mockOnClose).not.toHaveBeenCalled();
  2436. // And a second Escape, with no list open, still closes the dialog — the
  2437. // picker must not have swallowed the key permanently.
  2438. await user.keyboard('{Escape}');
  2439. expect(mockOnClose).toHaveBeenCalled();
  2440. });
  2441. it('matches the chosen printer against the override and keeps it on the item', async () => {
  2442. const user = userEvent.setup();
  2443. render(<PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={anyP2SItem()} onClose={mockOnClose} />);
  2444. await moveToPrinter01(user);
  2445. // Wait for the mapping to settle on the printer's trays before saving.
  2446. await waitFor(() => expect(screen.getByText(/filament mapping/i)).toBeInTheDocument());
  2447. await submit(user);
  2448. await waitFor(() => expect(patched).toHaveLength(1));
  2449. expect(patched[0].printer_id).toBe(1);
  2450. expect(patched[0].target_model).toBeNull();
  2451. // Tray 1 is the Bone White spool. Matching the 3MF would have taken tray 0.
  2452. expect(patched[0].ams_mapping).toEqual([1]);
  2453. expect(patched[0].filament_overrides).toEqual([
  2454. expect.objectContaining({ slot_id: 1, type: 'PLA', color: BONE_WHITE }),
  2455. ]);
  2456. });
  2457. it('keeps the requested colour when the printer has no such spool', async () => {
  2458. server.use(
  2459. http.get('/api/v1/printers/:id/status', () =>
  2460. statusWith([
  2461. { id: 0, tray_type: 'PLA', tray_color: '8B4513FF' },
  2462. { id: 1, tray_type: 'PLA', tray_color: '000000FF' },
  2463. ]),
  2464. ),
  2465. );
  2466. const user = userEvent.setup();
  2467. render(<PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={anyP2SItem()} onClose={mockOnClose} />);
  2468. await moveToPrinter01(user);
  2469. await waitFor(() => expect(screen.getByText(/filament mapping/i)).toBeInTheDocument());
  2470. await submit(user);
  2471. await waitFor(() => expect(patched).toHaveLength(1));
  2472. // Still asked for, so the scheduler's recompute at dispatch looks for it too
  2473. // instead of settling on the brown the 3MF was sliced with.
  2474. expect(patched[0].filament_overrides).toEqual([
  2475. expect.objectContaining({ slot_id: 1, color: BONE_WHITE }),
  2476. ]);
  2477. });
  2478. it('still drops the override when the job moves to a different model', async () => {
  2479. const user = userEvent.setup();
  2480. render(<PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={anyP2SItem()} onClose={mockOnClose} />);
  2481. const modelSelect = await waitFor(() => {
  2482. const select = screen
  2483. .getAllByRole('combobox')
  2484. .find((el) => (el as HTMLSelectElement).options[0]?.text === 'Select a model...');
  2485. if (!select) throw new Error('target model select not rendered');
  2486. return select as HTMLSelectElement;
  2487. });
  2488. // The override was picked from P2S's loaded filaments; X1C's are another list.
  2489. await user.selectOptions(modelSelect, 'X1C');
  2490. await submit(user);
  2491. await waitFor(() => expect(patched).toHaveLength(1));
  2492. expect(patched[0].target_model).toBe('X1C');
  2493. expect(patched[0].filament_overrides ?? null).toBeNull();
  2494. });
  2495. it("keeps a virtual printer's variant pin when its specific-printer job is saved", async () => {
  2496. // A VP with force colour on writes the 3MF's own filament back as an
  2497. // override, tray_info_idx included, to tell PLA variants apart (#2650). Two
  2498. // brown trays differ only by variant; the job was sliced for Matte (GFA01).
  2499. server.use(
  2500. http.get('/api/v1/archives/:id/filament-requirements', () =>
  2501. HttpResponse.json({ filaments: [{ ...SLOT_1_BROWN, tray_info_idx: 'GFA01' }] }),
  2502. ),
  2503. http.get('/api/v1/printers/:id/status', () =>
  2504. HttpResponse.json({
  2505. connected: true,
  2506. state: 'IDLE',
  2507. ams: [{ id: 0, tray: [
  2508. { id: 0, tray_type: 'PLA', tray_color: '8B4513FF', tray_info_idx: 'GFA00' },
  2509. { id: 1, tray_type: 'PLA', tray_color: '8B4513FF', tray_info_idx: 'GFA01' },
  2510. ] }],
  2511. vt_tray: [],
  2512. }),
  2513. ),
  2514. );
  2515. const vpItem = createMockQueueItem({
  2516. printer_id: 1,
  2517. target_model: null,
  2518. filament_overrides: [
  2519. { slot_id: 1, type: 'PLA', color: BROWN, tray_info_idx: 'GFA01', force_color_match: true },
  2520. ],
  2521. } as Partial<PrintQueueItem>);
  2522. const user = userEvent.setup();
  2523. render(<PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={vpItem} onClose={mockOnClose} />);
  2524. await waitFor(() => expect(screen.getByText(/filament mapping/i)).toBeInTheDocument());
  2525. await submit(user);
  2526. await waitFor(() => expect(patched).toHaveLength(1));
  2527. // Not treated as a swap: the matcher still pins the Matte tray...
  2528. expect(patched[0].ams_mapping).toEqual([1]);
  2529. // ...and the row keeps the pin rather than losing it on save.
  2530. expect(patched[0].filament_overrides).toEqual([
  2531. expect.objectContaining({ slot_id: 1, color: BROWN, tray_info_idx: 'GFA01', force_color_match: true }),
  2532. ]);
  2533. });
  2534. it("keeps a virtual printer's variant pin when its any-model job is saved", async () => {
  2535. const vpItem = createMockQueueItem({
  2536. printer_id: null,
  2537. target_model: 'P2S',
  2538. filament_overrides: [
  2539. { slot_id: 1, type: 'PLA', color: BROWN, tray_info_idx: 'GFA01', force_color_match: true },
  2540. ],
  2541. } as Partial<PrintQueueItem>);
  2542. const user = userEvent.setup();
  2543. render(<PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={vpItem} onClose={mockOnClose} />);
  2544. await waitFor(() => expect(screen.getByText('Filament Override')).toBeInTheDocument());
  2545. await submit(user);
  2546. await waitFor(() => expect(patched).toHaveLength(1));
  2547. expect(patched[0].target_model).toBe('P2S');
  2548. expect(patched[0].filament_overrides).toEqual([
  2549. expect.objectContaining({ slot_id: 1, tray_info_idx: 'GFA01', force_color_match: true }),
  2550. ]);
  2551. });
  2552. it("names a kept pin's colour within its product line when the file's filaments can't be read", async () => {
  2553. const hex = BROWN.replace('#', '').toLowerCase();
  2554. setColorCatalog({ [hex]: 'Brown' }, { [`PLA Matte|${hex}`]: 'Matte Brown' });
  2555. server.use(
  2556. http.get('/api/v1/archives/:id/filament-requirements', () => HttpResponse.json({ detail: 'gone' }, { status: 500 })),
  2557. );
  2558. const vpItem = createMockQueueItem({
  2559. printer_id: null,
  2560. target_model: 'P2S',
  2561. filament_overrides: [
  2562. { slot_id: 1, type: 'PLA', color: BROWN, tray_info_idx: 'GFA01', force_color_match: true },
  2563. ],
  2564. } as Partial<PrintQueueItem>);
  2565. // The preset names are known from the first render, so the save can't race them.
  2566. const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
  2567. queryClient.setQueryData(['builtin-filaments'], [{ filament_id: 'GFA01', name: 'Bambu PLA Matte' }]);
  2568. queryClient.setQueryData(['filament-id-map'], {});
  2569. try {
  2570. const user = userEvent.setup();
  2571. rtlRender(
  2572. <QueryClientProvider client={queryClient}>
  2573. <BrowserRouter>
  2574. <AuthProvider>
  2575. <ThemeProvider>
  2576. <ToastProvider>
  2577. <PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={vpItem} onClose={mockOnClose} />
  2578. </ToastProvider>
  2579. </ThemeProvider>
  2580. </AuthProvider>
  2581. </BrowserRouter>
  2582. </QueryClientProvider>,
  2583. );
  2584. await submit(user);
  2585. await waitFor(() => expect(patched).toHaveLength(1));
  2586. expect(patched[0].filament_overrides).toEqual([
  2587. expect.objectContaining({ slot_id: 1, tray_info_idx: 'GFA01', color_name: 'Matte Brown' }),
  2588. ]);
  2589. } finally {
  2590. __resetColorCatalogForTests();
  2591. }
  2592. });
  2593. it('carries an override picked in model mode into a specific-printer job when creating', async () => {
  2594. const user = userEvent.setup();
  2595. render(<PrintModal mode="create" archiveId={1} archiveName="Job" onClose={mockOnClose} />);
  2596. await user.click(await screen.findByRole('button', { name: /any model/i }));
  2597. const modelSelect = await waitFor(() => {
  2598. const select = screen
  2599. .getAllByRole('combobox')
  2600. .find((el) => (el as HTMLSelectElement).options[0]?.text === 'Select a model...');
  2601. if (!select) throw new Error('target model select not rendered');
  2602. return select as HTMLSelectElement;
  2603. });
  2604. await user.selectOptions(modelSelect, 'P2S');
  2605. // Matched on the hex the row now prints (#3159) rather than on the option
  2606. // value, so the assertion names the colour the user is actually picking.
  2607. await pickFromSlotPicker(
  2608. user,
  2609. /filament override for/i,
  2610. new RegExp(BONE_WHITE.toUpperCase().replace('#', '#?')),
  2611. );
  2612. await moveToPrinter01(user);
  2613. await waitFor(() => expect(screen.getByText(/filament mapping/i)).toBeInTheDocument());
  2614. await submit(user);
  2615. await waitFor(() => expect(posted).toHaveLength(1));
  2616. expect(posted[0].printer_id).toBe(1);
  2617. expect(posted[0].ams_mapping).toEqual([1]);
  2618. expect(posted[0].filament_overrides).toEqual([
  2619. expect.objectContaining({ slot_id: 1, type: 'PLA', color: BONE_WHITE }),
  2620. ]);
  2621. });
  2622. });
  2623. describe('PrintModal — a deliberate material substitution is acknowledged (#2799)', () => {
  2624. // The scheduler re-checks a stored mapping against the printer before
  2625. // dispatch, and a slot on a tray of another material is what a mapping meant
  2626. // for a different printer looks like. A user who picks such a tray by hand
  2627. // means it, so the dialog sends skip_filament_check, which the re-check
  2628. // honours.
  2629. const mockOnClose = vi.fn();
  2630. const PRINTERS = [
  2631. { id: 1, name: 'Printer 01', model: 'P2S', ip_address: '192.168.1.101', enabled: true, is_active: true },
  2632. ];
  2633. type Patched = { ams_mapping?: number[] | null; skip_filament_check?: boolean };
  2634. let patched: Patched[];
  2635. beforeEach(() => {
  2636. vi.clearAllMocks();
  2637. patched = [];
  2638. server.use(
  2639. http.get('/api/v1/printers/', () => HttpResponse.json(PRINTERS)),
  2640. http.get('/api/v1/archives/:id/plates', () => HttpResponse.json({ is_multi_plate: false, plates: [] })),
  2641. http.get('/api/v1/archives/:id/filament-requirements', () =>
  2642. HttpResponse.json({ filaments: [{ slot_id: 1, type: 'PLA', color: '#8B4513', tray_info_idx: '', used_grams: 50 }] }),
  2643. ),
  2644. // Tray 0 holds the PLA the plate asks for, tray 1 a PETG.
  2645. http.get('/api/v1/printers/:id/status', () =>
  2646. HttpResponse.json({
  2647. connected: true,
  2648. state: 'IDLE',
  2649. ams: [
  2650. {
  2651. id: 0,
  2652. tray: [
  2653. { id: 0, tray_type: 'PLA', tray_color: '8B4513FF' },
  2654. { id: 1, tray_type: 'PETG', tray_color: 'FFFFFFFF' },
  2655. ],
  2656. },
  2657. ],
  2658. vt_tray: [],
  2659. }),
  2660. ),
  2661. http.get('/api/v1/printers/:id/assignments', () => HttpResponse.json([])),
  2662. http.patch('/api/v1/queue/:id', async ({ request }) => {
  2663. patched.push((await request.json()) as Patched);
  2664. return HttpResponse.json({ id: 1, status: 'pending' });
  2665. }),
  2666. );
  2667. });
  2668. const pinnedItem = () => createMockQueueItem({ printer_id: 1, target_model: null } as Partial<PrintQueueItem>);
  2669. const pickTrayAndSave = async (option: number) => {
  2670. const user = userEvent.setup();
  2671. render(<PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={pinnedItem()} onClose={mockOnClose} />);
  2672. await user.click(await screen.findByText(/filament mapping/i));
  2673. await user.click(await screen.findByRole('combobox', { name: /printer slot for/i }));
  2674. const listbox = await screen.findByRole('listbox');
  2675. await user.click(within(listbox).getAllByRole('option')[option]);
  2676. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  2677. await waitFor(() => expect(patched).toHaveLength(1));
  2678. return patched[0];
  2679. };
  2680. it('sends skip_filament_check when a slot is put on a tray of another material', async () => {
  2681. // Option 0 is the empty '-- Select slot --'; 1 is the PLA tray, 2 the PETG.
  2682. const saved = await pickTrayAndSave(2);
  2683. expect(saved.ams_mapping).toEqual([1]);
  2684. expect(saved.skip_filament_check).toBe(true);
  2685. });
  2686. it('does not treat a stored mapping the dialog opened with as a pick made here', async () => {
  2687. // A job queued before the dispatch re-check existed can carry a mapping
  2688. // made for another printer. Saving an unrelated edit must not enshrine it.
  2689. const user = userEvent.setup();
  2690. const item = createMockQueueItem({ printer_id: 1, target_model: null, ams_mapping: [1] } as Partial<PrintQueueItem>);
  2691. render(<PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={item} onClose={mockOnClose} />);
  2692. await waitFor(() => expect(screen.getByText(/filament mapping/i)).toBeInTheDocument());
  2693. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  2694. await waitFor(() => expect(patched).toHaveLength(1));
  2695. expect(patched[0].ams_mapping).toEqual([1]);
  2696. expect(patched[0].skip_filament_check).toBeUndefined();
  2697. });
  2698. it('sends nothing extra when the picked tray holds the material asked for', async () => {
  2699. const saved = await pickTrayAndSave(1);
  2700. expect(saved.ams_mapping).toEqual([0]);
  2701. expect(saved.skip_filament_check).toBeUndefined();
  2702. });
  2703. });
  2704. describe('PrintModal edit: moving a job to another printer', () => {
  2705. const mockOnClose = vi.fn();
  2706. let patched: Record<string, unknown>[];
  2707. beforeEach(() => {
  2708. vi.clearAllMocks();
  2709. patched = [];
  2710. server.use(
  2711. http.get('/api/v1/printers/', () =>
  2712. HttpResponse.json([
  2713. { id: 1, name: 'Printer 01', model: 'H2C', ip_address: '192.168.1.101', enabled: true, is_active: true },
  2714. { id: 2, name: 'Printer 02', model: 'H2C', ip_address: '192.168.1.102', enabled: true, is_active: true },
  2715. ]),
  2716. ),
  2717. http.get('/api/v1/archives/:id/plates', () => HttpResponse.json({ is_multi_plate: false, plates: [] })),
  2718. http.get('/api/v1/printers/:id/status', () =>
  2719. HttpResponse.json({ connected: true, state: 'IDLE', ams: [], vt_tray: [] }),
  2720. ),
  2721. http.patch('/api/v1/queue/:id', async ({ request }) => {
  2722. patched.push((await request.json()) as Record<string, unknown>);
  2723. return HttpResponse.json({ id: 1, status: 'pending' });
  2724. }),
  2725. );
  2726. });
  2727. it("does not carry the old printer's nozzle rack picks over", async () => {
  2728. const user = userEvent.setup();
  2729. const item = createMockQueueItem({
  2730. printer_id: 1,
  2731. target_model: null,
  2732. nozzle_rack_choice: { 0: 3 },
  2733. } as Partial<PrintQueueItem>);
  2734. render(<PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={item} onClose={mockOnClose} />);
  2735. // The dialog adds printers; moving the job is deselecting one, selecting the other.
  2736. await user.click(await screen.findByText('Printer 01'));
  2737. await user.click(screen.getByText('Printer 02'));
  2738. await user.click(screen.getByRole('button', { name: /save/i }));
  2739. await waitFor(() => expect(patched).toHaveLength(1));
  2740. expect(patched[0].printer_id).toBe(2);
  2741. expect(patched[0].nozzle_rack_choice).toBeNull();
  2742. });
  2743. });
  2744. describe('PrintModal default printer', () => {
  2745. beforeEach(() => {
  2746. vi.clearAllMocks();
  2747. server.use(
  2748. http.get('/api/v1/printers/', () => HttpResponse.json(mockPrinters)),
  2749. http.get('/api/v1/settings/', () => HttpResponse.json({ default_printer_id: 2, currency: 'USD' })),
  2750. http.get('/api/v1/archives/:id/plates', () => HttpResponse.json({ is_multi_plate: false, plates: [] })),
  2751. http.get('/api/v1/archives/:id/filament-requirements', () => HttpResponse.json({ filaments: [] })),
  2752. http.get('/api/v1/printers/:id/status', () =>
  2753. HttpResponse.json({ connected: true, state: 'IDLE', ams: [], vt_tray: [] }),
  2754. ),
  2755. );
  2756. });
  2757. it('preselects the default printer from Settings', async () => {
  2758. render(<PrintModal mode="create" archiveId={1} archiveName="Test Print" onClose={vi.fn()} />);
  2759. expect(await screen.findByText('1 printer selected')).toBeInTheDocument();
  2760. });
  2761. it('does not bring the default back once it was deselected', async () => {
  2762. const user = userEvent.setup();
  2763. render(<PrintModal mode="create" archiveId={1} archiveName="Test Print" onClose={vi.fn()} />);
  2764. await screen.findByText('1 printer selected');
  2765. await user.click(screen.getByText('P1S'));
  2766. await new Promise((resolve) => setTimeout(resolve, 100));
  2767. expect(screen.queryByText('1 printer selected')).not.toBeInTheDocument();
  2768. });
  2769. it('does not select a default printer of another model than the file was sliced for', async () => {
  2770. server.use(
  2771. http.get('/api/v1/archives/:id', async () => {
  2772. // Later than printers and settings: the model must be waited for.
  2773. await new Promise((resolve) => setTimeout(resolve, 50));
  2774. return HttpResponse.json({ id: 1, filename: 'test.3mf', sliced_for_model: 'X1C' });
  2775. }),
  2776. );
  2777. const user = userEvent.setup();
  2778. render(<PrintModal mode="create" archiveId={1} archiveName="Test Print" onClose={vi.fn()} />);
  2779. // The P1S is hidden behind "show all" as another model than X1C.
  2780. await user.click(await screen.findByText('show all'));
  2781. await new Promise((resolve) => setTimeout(resolve, 200));
  2782. expect(screen.getByText('P1S').closest('button')).not.toHaveClass('border-bambu-green');
  2783. });
  2784. });
  2785. describe('PrintModal — "Force color match" on a specific printer is saved (#3445)', () => {
  2786. const mockOnClose = vi.fn();
  2787. const PRINTERS = [
  2788. { id: 1, name: 'Printer 01', model: 'P1S', ip_address: '192.168.1.101', enabled: true, is_active: true },
  2789. { id: 2, name: 'Printer 02', model: 'P1S', ip_address: '192.168.1.102', enabled: true, is_active: true },
  2790. ];
  2791. // Sliced in white; the printer holds green (tray 0) and black (tray 1), no white.
  2792. const SLOT_1_WHITE = { slot_id: 1, type: 'PLA', color: '#CBC6B8', tray_info_idx: 'GFA01', used_grams: 50 };
  2793. type Override = { slot_id: number; type: string; color: string; tray_info_idx?: string; force_color_match: boolean };
  2794. type Sent = { printer_id?: number | null; ams_mapping?: number[] | null; filament_overrides?: Override[] | null };
  2795. let patched: Sent[];
  2796. let posted: Sent[];
  2797. beforeEach(() => {
  2798. vi.clearAllMocks();
  2799. patched = [];
  2800. posted = [];
  2801. server.use(
  2802. http.get('/api/v1/printers/', () => HttpResponse.json(PRINTERS)),
  2803. http.get('/api/v1/archives/:id/plates', () => HttpResponse.json({ is_multi_plate: false, plates: [] })),
  2804. http.get('/api/v1/archives/:id/filament-requirements', () => HttpResponse.json({ filaments: [SLOT_1_WHITE] })),
  2805. http.get('/api/v1/printers/:id/status', () =>
  2806. HttpResponse.json({
  2807. connected: true,
  2808. state: 'IDLE',
  2809. ams: [
  2810. {
  2811. id: 0,
  2812. tray: [
  2813. { id: 0, tray_type: 'PLA', tray_color: '68724DFF', tray_info_idx: 'GFA01' },
  2814. { id: 1, tray_type: 'PLA', tray_color: '000000FF', tray_info_idx: 'GFA01' },
  2815. ],
  2816. },
  2817. ],
  2818. vt_tray: [],
  2819. }),
  2820. ),
  2821. http.get('/api/v1/printers/:id/assignments', () => HttpResponse.json([])),
  2822. http.patch('/api/v1/queue/:id', async ({ request }) => {
  2823. patched.push((await request.json()) as Sent);
  2824. return HttpResponse.json({ id: 1, status: 'pending' });
  2825. }),
  2826. http.post('/api/v1/queue/', async ({ request }) => {
  2827. posted.push((await request.json()) as Sent);
  2828. return HttpResponse.json({ id: 1, status: 'pending' });
  2829. }),
  2830. );
  2831. });
  2832. const printer01Item = (overrides: Partial<PrintQueueItem> = {}) =>
  2833. createMockQueueItem({ printer_id: 1, target_model: null, ams_mapping: [1], ...overrides } as Partial<PrintQueueItem>);
  2834. const BLACK_FORCED = { slot_id: 1, type: 'PLA', color: '#000000', tray_info_idx: 'GFA01', force_color_match: true };
  2835. const openMapping = async (user: ReturnType<typeof userEvent.setup>) => {
  2836. await user.click(await screen.findByText(/filament mapping/i));
  2837. return screen.findByRole('checkbox', { name: /force color match/i });
  2838. };
  2839. const submit = async (user: ReturnType<typeof userEvent.setup>) => {
  2840. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  2841. };
  2842. it("saves a ticked slot with the filament of the tray it was mapped to, not the sliced one", async () => {
  2843. const user = userEvent.setup();
  2844. render(<PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={printer01Item()} onClose={mockOnClose} />);
  2845. await user.click(await openMapping(user));
  2846. await submit(user);
  2847. await waitFor(() => expect(patched).toHaveLength(1));
  2848. expect(patched[0].ams_mapping).toEqual([1]);
  2849. // Black, so a recompute at dispatch asks for black and never takes green.
  2850. expect(patched[0].filament_overrides).toEqual([expect.objectContaining(BLACK_FORCED)]);
  2851. });
  2852. it('shows the box ticked again when the job is reopened, and keeps it on save', async () => {
  2853. const user = userEvent.setup();
  2854. render(
  2855. <PrintModal
  2856. mode="edit-queue-item"
  2857. archiveId={1}
  2858. archiveName="Job"
  2859. queueItem={printer01Item({ filament_overrides: [{ ...BLACK_FORCED, color_name: 'Black' }] } as Partial<PrintQueueItem>)}
  2860. onClose={mockOnClose}
  2861. />,
  2862. );
  2863. expect(await openMapping(user)).toBeChecked();
  2864. await submit(user);
  2865. await waitFor(() => expect(patched).toHaveLength(1));
  2866. expect(patched[0].filament_overrides).toEqual([expect.objectContaining(BLACK_FORCED)]);
  2867. });
  2868. it('saves an untick', async () => {
  2869. const user = userEvent.setup();
  2870. render(
  2871. <PrintModal
  2872. mode="edit-queue-item"
  2873. archiveId={1}
  2874. archiveName="Job"
  2875. queueItem={printer01Item({ filament_overrides: [BLACK_FORCED] } as Partial<PrintQueueItem>)}
  2876. onClose={mockOnClose}
  2877. />,
  2878. );
  2879. await user.click(await openMapping(user));
  2880. await submit(user);
  2881. await waitFor(() => expect(patched).toHaveLength(1));
  2882. // Black stays asked for, as picked; only no longer strictly.
  2883. expect(patched[0].filament_overrides).toEqual([
  2884. expect.objectContaining({ slot_id: 1, color: '#000000', force_color_match: false }),
  2885. ]);
  2886. });
  2887. it("keeps a reopened job's forced filament when its tray has been reloaded since", async () => {
  2888. // Tray 1 now holds a green third-party spool with no preset.
  2889. server.use(
  2890. http.get('/api/v1/printers/:id/status', () =>
  2891. HttpResponse.json({
  2892. connected: true,
  2893. state: 'IDLE',
  2894. ams: [{ id: 0, tray: [{ id: 1, tray_type: 'PLA', tray_color: '68724DFF', tray_info_idx: '' }] }],
  2895. vt_tray: [],
  2896. }),
  2897. ),
  2898. );
  2899. const user = userEvent.setup();
  2900. render(
  2901. <PrintModal
  2902. mode="edit-queue-item"
  2903. archiveId={1}
  2904. archiveName="Job"
  2905. queueItem={printer01Item({ filament_overrides: [BLACK_FORCED] } as Partial<PrintQueueItem>)}
  2906. onClose={mockOnClose}
  2907. />,
  2908. );
  2909. expect(await openMapping(user)).toBeChecked();
  2910. await submit(user);
  2911. await waitFor(() => expect(patched).toHaveLength(1));
  2912. // Still black, variant pin included: saving the schedule must not turn it green.
  2913. expect(patched[0].filament_overrides).toEqual([expect.objectContaining(BLACK_FORCED)]);
  2914. });
  2915. it("takes the new tray's filament when a reopened forced slot is moved to another tray", async () => {
  2916. const user = userEvent.setup();
  2917. render(
  2918. <PrintModal
  2919. mode="edit-queue-item"
  2920. archiveId={1}
  2921. archiveName="Job"
  2922. queueItem={printer01Item({ filament_overrides: [BLACK_FORCED] } as Partial<PrintQueueItem>)}
  2923. onClose={mockOnClose}
  2924. />,
  2925. );
  2926. await openMapping(user);
  2927. await user.click(await screen.findByRole('combobox', { name: /printer slot for/i }));
  2928. await user.click(within(await screen.findByRole('listbox')).getByRole('option', { name: /A1/ }));
  2929. await submit(user);
  2930. await waitFor(() => expect(patched).toHaveLength(1));
  2931. expect(patched[0].ams_mapping).toEqual([0]);
  2932. expect(patched[0].filament_overrides).toEqual([
  2933. expect.objectContaining({ slot_id: 1, color: '#68724D', force_color_match: true }),
  2934. ]);
  2935. });
  2936. it("does not force a slot whose chosen tray can't be read", async () => {
  2937. // The printer is off: no trays to say what the slot is set to.
  2938. server.use(
  2939. http.get('/api/v1/printers/:id/status', () =>
  2940. HttpResponse.json({ connected: false, state: 'OFFLINE', ams: [], vt_tray: [] }),
  2941. ),
  2942. );
  2943. const user = userEvent.setup();
  2944. render(<PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={printer01Item()} onClose={mockOnClose} />);
  2945. await user.click(await openMapping(user));
  2946. await submit(user);
  2947. await waitFor(() => expect(patched).toHaveLength(1));
  2948. // Not "wait for white": that would hold the job off the black tray picked for it.
  2949. expect(patched[0].filament_overrides ?? null).toBeNull();
  2950. });
  2951. it('does not save a tick whose box went away when a second printer was added', async () => {
  2952. const user = userEvent.setup();
  2953. render(<PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={printer01Item()} onClose={mockOnClose} />);
  2954. await user.click(await openMapping(user));
  2955. await user.click(screen.getByText('Printer 02'));
  2956. await waitFor(() => expect(screen.queryByRole('checkbox', { name: /force color match/i })).not.toBeInTheDocument());
  2957. await submit(user);
  2958. // The edited job stays on printer 01, a copy goes to printer 02.
  2959. await waitFor(() => expect(patched.length + posted.length).toBe(2));
  2960. for (const job of [...patched, ...posted]) expect(job.filament_overrides ?? null).toBeNull();
  2961. });
  2962. it('waits for the sliced colour when the box is ticked on a tray the dialog matched itself', async () => {
  2963. const user = userEvent.setup();
  2964. render(
  2965. <PrintModal mode="create" archiveId={1} archiveName="Job" initialSelectedPrinterIds={[1]} onClose={mockOnClose} />,
  2966. );
  2967. // No white loaded: the dialog stands in a PLA of another colour. The tick
  2968. // asks for white, not for that stand-in.
  2969. await user.click(await screen.findByRole('checkbox', { name: /force color match/i }));
  2970. await submit(user);
  2971. await waitFor(() => expect(posted).toHaveLength(1));
  2972. expect(posted[0].filament_overrides).toEqual([
  2973. expect.objectContaining({ slot_id: 1, type: 'PLA', color: '#CBC6B8', force_color_match: true }),
  2974. ]);
  2975. });
  2976. it('sends nothing for a slot left unticked and unchanged', async () => {
  2977. const user = userEvent.setup();
  2978. render(<PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={printer01Item()} onClose={mockOnClose} />);
  2979. await openMapping(user);
  2980. await submit(user);
  2981. await waitFor(() => expect(patched).toHaveLength(1));
  2982. expect(patched[0].filament_overrides ?? null).toBeNull();
  2983. });
  2984. it('saves the tick on a new job queued for one printer', async () => {
  2985. const user = userEvent.setup();
  2986. render(
  2987. <PrintModal mode="create" archiveId={1} archiveName="Job" initialSelectedPrinterIds={[1]} onClose={mockOnClose} />,
  2988. );
  2989. // Pick black for the white slot, then tick it. A preselected printer opens
  2990. // the mapping panel expanded.
  2991. await user.click(await screen.findByRole('combobox', { name: /printer slot for/i }));
  2992. const listbox = await screen.findByRole('listbox');
  2993. await user.click(within(listbox).getByRole('option', { name: /A2/ }));
  2994. await user.click(screen.getByRole('checkbox', { name: /force color match/i }));
  2995. await submit(user);
  2996. await waitFor(() => expect(posted).toHaveLength(1));
  2997. expect(posted[0].printer_id).toBe(1);
  2998. expect(posted[0].ams_mapping).toEqual([1]);
  2999. expect(posted[0].filament_overrides).toEqual([expect.objectContaining(BLACK_FORCED)]);
  3000. });
  3001. });
  3002. describe('PrintModal — filament rules of the user\'s group (#3522)', () => {
  3003. const mockOnClose = vi.fn();
  3004. const PRINTERS = [{ id: 1, name: 'Printer 01', model: 'P1S', ip_address: '192.168.1.101', enabled: true, is_active: true }];
  3005. // Same white PETG twice; only the slicer preset id differs, and GFG03 is blocked.
  3006. const STATUS = {
  3007. connected: true,
  3008. state: 'IDLE',
  3009. ams: [
  3010. {
  3011. id: 0,
  3012. tray: [
  3013. { id: 0, tray_type: 'PETG', tray_color: 'FFFFFFFF', tray_info_idx: 'GFG03', tray_sub_brands: 'PETG Matte' },
  3014. { id: 1, tray_type: 'PETG', tray_color: 'FFFFFFFF', tray_info_idx: 'GFG99', tray_sub_brands: 'PETG Other' },
  3015. ],
  3016. },
  3017. ],
  3018. vt_tray: [],
  3019. };
  3020. const PETG_ANY = { slot_id: 1, type: 'PETG', color: '#FFFFFF', used_grams: 10, used_meters: 3 };
  3021. const PETG_BLOCKED = { ...PETG_ANY, tray_info_idx: 'GFG03' };
  3022. const BANNER = "This file uses a filament your group can't print with: PETG (GFG03)";
  3023. let posted: Array<{ ams_mapping?: number[] | null }>;
  3024. const useRequirements = (filaments: unknown[]) =>
  3025. server.use(http.get('/api/v1/archives/:id/filament-requirements', () => HttpResponse.json({ filaments })));
  3026. const submitButton = () => document.querySelector('button[type="submit"]') as HTMLButtonElement;
  3027. beforeEach(() => {
  3028. vi.clearAllMocks();
  3029. posted = [];
  3030. setAuthToken('test-token', 'session');
  3031. server.use(
  3032. http.get('*/api/v1/auth/status', () => HttpResponse.json({ auth_enabled: true, requires_setup: false })),
  3033. http.get('*/api/v1/auth/me', () =>
  3034. HttpResponse.json({
  3035. id: 7,
  3036. username: 'student',
  3037. is_admin: false,
  3038. permissions: ['printers:read', 'queue:create'],
  3039. filament_policies: [
  3040. { group: 'Students', mode: 'block', rules: [{ match: 'filament_id', value: 'GFG03' }] },
  3041. ],
  3042. }),
  3043. ),
  3044. http.get('/api/v1/printers/', () => HttpResponse.json(PRINTERS)),
  3045. http.get('/api/v1/archives/:id/plates', () => HttpResponse.json({ is_multi_plate: false, plates: [] })),
  3046. http.get('/api/v1/printers/:id/status', () => HttpResponse.json(STATUS)),
  3047. http.get('/api/v1/printers/:id/assignments', () => HttpResponse.json([])),
  3048. http.get('/api/v1/printers/available-filaments', () => HttpResponse.json([])),
  3049. http.post('/api/v1/queue/', async ({ request }) => {
  3050. posted.push((await request.json()) as { ams_mapping?: number[] | null });
  3051. return HttpResponse.json({ id: 1, status: 'pending' });
  3052. }),
  3053. );
  3054. });
  3055. afterEach(() => {
  3056. setAuthToken(null);
  3057. });
  3058. it('greys out the blocked slot and sends the allowed one', async () => {
  3059. useRequirements([PETG_ANY]);
  3060. const user = userEvent.setup();
  3061. render(<PrintModal mode="create" archiveId={1} archiveName="Job" initialSelectedPrinterIds={[1]} onClose={mockOnClose} />);
  3062. const trigger = await screen.findByRole('combobox', { name: /printer slot for/i });
  3063. await waitFor(() => expect(trigger).toHaveTextContent(/PETG Other/));
  3064. await user.click(trigger);
  3065. const listbox = await screen.findByRole('listbox');
  3066. expect(within(listbox).getByRole('option', { name: /PETG Matte/ })).toHaveAttribute('aria-disabled', 'true');
  3067. await user.keyboard('{Escape}');
  3068. expect(screen.queryByRole('alert')).not.toBeInTheDocument();
  3069. await waitFor(() => expect(submitButton()).toBeEnabled());
  3070. await user.click(submitButton());
  3071. await waitFor(() => expect(posted).toHaveLength(1));
  3072. expect(posted[0].ams_mapping).toEqual([1]);
  3073. });
  3074. it('names the blocked filament and keeps submit disabled', async () => {
  3075. useRequirements([PETG_BLOCKED]);
  3076. render(<PrintModal mode="create" archiveId={1} archiveName="Job" initialSelectedPrinterIds={[1]} onClose={mockOnClose} />);
  3077. expect(await screen.findByRole('alert')).toHaveTextContent(BANNER);
  3078. expect(submitButton()).toBeDisabled();
  3079. });
  3080. it('names the blocked filament after a model-mode job is moved to a printer (#3133)', async () => {
  3081. // The mapping panel takes over the banner, so a disabled Print still says why.
  3082. useRequirements([PETG_BLOCKED]);
  3083. const user = userEvent.setup();
  3084. render(
  3085. <PrintModal
  3086. mode="edit-queue-item"
  3087. archiveId={1}
  3088. archiveName="Job"
  3089. queueItem={createMockQueueItem({ printer_id: null, target_model: 'P1S' } as Partial<PrintQueueItem>)}
  3090. onClose={mockOnClose}
  3091. />,
  3092. );
  3093. await user.click(await screen.findByRole('button', { name: /specific printer/i }));
  3094. await user.click(await screen.findByText('Printer 01'));
  3095. await screen.findByText(/filament mapping/i);
  3096. await waitFor(() => expect(submitButton()).toBeDisabled());
  3097. expect(await screen.findByRole('alert')).toHaveTextContent(BANNER);
  3098. // The panel's banner, not the dialog's as well.
  3099. expect(screen.getAllByRole('alert')).toHaveLength(1);
  3100. });
  3101. it('lets a slot swapped to another filament through, as the server does', async () => {
  3102. // The file was sliced with blocked GFG03; the job asks for PLA in that
  3103. // slot. The swap clears the preset id, so the tray it lands on is what
  3104. // the rules judge, here as on the server.
  3105. useRequirements([PETG_BLOCKED]);
  3106. render(
  3107. <PrintModal
  3108. mode="edit-queue-item"
  3109. archiveId={1}
  3110. archiveName="Job"
  3111. queueItem={createMockQueueItem({
  3112. printer_id: null,
  3113. target_model: 'P1S',
  3114. filament_overrides: [{ slot_id: 1, type: 'PLA', color: '#000000', force_color_match: false }],
  3115. } as Partial<PrintQueueItem>)}
  3116. onClose={mockOnClose}
  3117. />,
  3118. );
  3119. await waitFor(() => expect(submitButton()).toBeEnabled());
  3120. expect(screen.queryByRole('alert')).not.toBeInTheDocument();
  3121. });
  3122. it('still names it in model mode, which has no mapping panel', async () => {
  3123. useRequirements([PETG_BLOCKED]);
  3124. render(
  3125. <PrintModal
  3126. mode="edit-queue-item"
  3127. archiveId={1}
  3128. archiveName="Job"
  3129. queueItem={createMockQueueItem({ printer_id: null, target_model: 'P1S' } as Partial<PrintQueueItem>)}
  3130. onClose={mockOnClose}
  3131. />,
  3132. );
  3133. expect(await screen.findByRole('alert')).toHaveTextContent(BANNER);
  3134. expect(screen.getAllByRole('alert')).toHaveLength(1);
  3135. expect(submitButton()).toBeDisabled();
  3136. });
  3137. });