PrintModal.test.tsx 115 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142
  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. it('creates one queue item per plate when submitting with select-all', async () => {
  1003. const queueRequests: unknown[] = [];
  1004. server.use(
  1005. http.post('/api/v1/queue/', async ({ request }) => {
  1006. const body = await request.json();
  1007. queueRequests.push(body);
  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. onClose={mockOnClose}
  1018. onSuccess={mockOnSuccess}
  1019. />
  1020. );
  1021. // Wait for plates and select a printer
  1022. await waitFor(() => {
  1023. expect(screen.getByText('Select All 3 Plates')).toBeInTheDocument();
  1024. expect(screen.getByText('X1 Carbon')).toBeInTheDocument();
  1025. });
  1026. // Select printer
  1027. await user.click(screen.getByText('X1 Carbon'));
  1028. // Click select all
  1029. await user.click(screen.getByText('Select All 3 Plates'));
  1030. // Find the submit button (type="submit") — distinct from the toggle button (type="button")
  1031. const submitButton = document.querySelector('button[type="submit"]') as HTMLElement;
  1032. await user.click(submitButton);
  1033. await waitFor(() => {
  1034. expect(queueRequests.length).toBe(3);
  1035. });
  1036. // Verify each request has the correct plate_id
  1037. expect((queueRequests[0] as { plate_id: number }).plate_id).toBe(1);
  1038. expect((queueRequests[1] as { plate_id: number }).plate_id).toBe(2);
  1039. expect((queueRequests[2] as { plate_id: number }).plate_id).toBe(3);
  1040. });
  1041. });
  1042. describe('batch quantity', () => {
  1043. it('shows quantity input in create mode', () => {
  1044. render(
  1045. <PrintModal
  1046. mode="create"
  1047. archiveId={1}
  1048. archiveName="Benchy"
  1049. onClose={mockOnClose}
  1050. onSuccess={mockOnSuccess}
  1051. />
  1052. );
  1053. expect(screen.getByLabelText('Quantity')).toBeInTheDocument();
  1054. });
  1055. it('shows quantity input in create mode', () => {
  1056. render(
  1057. <PrintModal
  1058. mode="create"
  1059. archiveId={1}
  1060. archiveName="Benchy"
  1061. onClose={mockOnClose}
  1062. onSuccess={mockOnSuccess}
  1063. />
  1064. );
  1065. expect(screen.getByLabelText('Quantity')).toBeInTheDocument();
  1066. });
  1067. it('does not show quantity input in edit-queue-item mode', () => {
  1068. render(
  1069. <PrintModal
  1070. mode="edit-queue-item"
  1071. archiveId={1}
  1072. archiveName="Benchy"
  1073. queueItem={createMockQueueItem()}
  1074. onClose={mockOnClose}
  1075. onSuccess={mockOnSuccess}
  1076. />
  1077. );
  1078. expect(screen.queryByLabelText('Quantity')).not.toBeInTheDocument();
  1079. });
  1080. it('defaults quantity to 1', () => {
  1081. render(
  1082. <PrintModal
  1083. mode="create"
  1084. archiveId={1}
  1085. archiveName="Benchy"
  1086. onClose={mockOnClose}
  1087. onSuccess={mockOnSuccess}
  1088. />
  1089. );
  1090. const input = screen.getByLabelText('Quantity') as HTMLInputElement;
  1091. expect(input.value).toBe('1');
  1092. });
  1093. it('quantity input has default value of 1 and accepts changes', async () => {
  1094. const user = userEvent.setup();
  1095. render(
  1096. <PrintModal
  1097. mode="create"
  1098. archiveId={1}
  1099. archiveName="Benchy"
  1100. initialSelectedPrinterIds={[1]}
  1101. onClose={mockOnClose}
  1102. onSuccess={mockOnSuccess}
  1103. />
  1104. );
  1105. const input = screen.getByLabelText('Quantity') as HTMLInputElement;
  1106. expect(input.value).toBe('1');
  1107. await user.tripleClick(input);
  1108. await user.keyboard('5');
  1109. expect(input.value).toBe('5');
  1110. });
  1111. it('quantity can be erased and retyped instead of snapping back to 1 (#3182)', async () => {
  1112. const user = userEvent.setup();
  1113. render(
  1114. <PrintModal
  1115. mode="create"
  1116. archiveId={1}
  1117. archiveName="Benchy"
  1118. initialSelectedPrinterIds={[1]}
  1119. onClose={mockOnClose}
  1120. onSuccess={mockOnSuccess}
  1121. />
  1122. );
  1123. const input = screen.getByLabelText('Quantity') as HTMLInputElement;
  1124. await user.click(input);
  1125. await user.keyboard('{Backspace}');
  1126. expect(input.value).toBe('');
  1127. await user.keyboard('6');
  1128. expect(input.value).toBe('6');
  1129. expect(screen.getByText('Creates 6 queue items')).toBeInTheDocument();
  1130. });
  1131. it('an emptied quantity settles back to 1 when the field is left', async () => {
  1132. const user = userEvent.setup();
  1133. render(
  1134. <PrintModal
  1135. mode="create"
  1136. archiveId={1}
  1137. archiveName="Benchy"
  1138. initialSelectedPrinterIds={[1]}
  1139. onClose={mockOnClose}
  1140. onSuccess={mockOnSuccess}
  1141. />
  1142. );
  1143. const input = screen.getByLabelText('Quantity') as HTMLInputElement;
  1144. await user.click(input);
  1145. await user.keyboard('{Backspace}');
  1146. await user.tab();
  1147. expect(input.value).toBe('1');
  1148. });
  1149. });
  1150. describe('reprint G-code injection dispatch (#422 / auto-eject)', () => {
  1151. // Guards the fix: when "Inject auto-print G-code" is ticked on a create with
  1152. // quantity > 1, ALL copies must go through the queue so every one is injected by
  1153. // the scheduler. The first copy must NOT be dispatched immediately via the direct
  1154. // create path — that path bypasses injection and would leave the first copy stuck
  1155. // on the plate for auto-eject setups.
  1156. const withSnippets = () =>
  1157. http.get('/api/v1/settings/', () =>
  1158. HttpResponse.json({ gcode_snippets: { X1C: { start_gcode: '', end_gcode: 'M400' } } }),
  1159. );
  1160. it('injection ON queues all copies and dispatches none immediately', async () => {
  1161. const queueCalls: Record<string, unknown>[] = [];
  1162. server.use(
  1163. withSnippets(),
  1164. http.post('/api/v1/queue/', async ({ request }) => {
  1165. queueCalls.push((await request.json()) as Record<string, unknown>);
  1166. return HttpResponse.json({ id: queueCalls.length, status: 'pending' });
  1167. }),
  1168. );
  1169. const user = userEvent.setup();
  1170. render(
  1171. <PrintModal
  1172. mode="create"
  1173. archiveId={1}
  1174. archiveName="Benchy"
  1175. initialSelectedPrinterIds={[1]}
  1176. onClose={mockOnClose}
  1177. onSuccess={mockOnSuccess}
  1178. />
  1179. );
  1180. // Quantity > 1 so the injection checkbox is offered
  1181. const qty = (await screen.findByLabelText('Quantity')) as HTMLInputElement;
  1182. await user.tripleClick(qty);
  1183. await user.keyboard('3');
  1184. expect(qty.value).toBe('3');
  1185. // Checkbox only renders once snippets are loaded AND quantity > 1
  1186. await user.click(await screen.findByLabelText(/inject auto-print/i));
  1187. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1188. await waitFor(() => expect(queueCalls.length).toBe(1));
  1189. // One queue item carrying all copies, and zero immediate reprint dispatches
  1190. expect(queueCalls[0].quantity).toBe(3);
  1191. });
  1192. it('quantity 1 + snippets configured: checkbox toggles cleanly (#1852)', async () => {
  1193. // The previous reset effect in PrintModal/index.tsx silently flipped
  1194. // gcodeInjection back to false whenever effectiveQuantity <= 1 in create
  1195. // mode, so a single print with snippets configured couldn't tick the
  1196. // checkbox — every click visibly un-ticked itself within the next render.
  1197. // The scheduler reads item.gcode_injection per queue item regardless of
  1198. // batch size, so quantity 1 must be allowed too.
  1199. const queueCalls: Record<string, unknown>[] = [];
  1200. server.use(
  1201. withSnippets(),
  1202. http.post('/api/v1/queue/', async ({ request }) => {
  1203. queueCalls.push((await request.json()) as Record<string, unknown>);
  1204. return HttpResponse.json({ id: queueCalls.length, status: 'pending' });
  1205. }),
  1206. );
  1207. const user = userEvent.setup();
  1208. render(
  1209. <PrintModal
  1210. mode="create"
  1211. archiveId={1}
  1212. archiveName="Benchy"
  1213. initialSelectedPrinterIds={[1]}
  1214. onClose={mockOnClose}
  1215. onSuccess={mockOnSuccess}
  1216. />
  1217. );
  1218. // Quantity stays at default (1) — this is the OP's exact scenario.
  1219. const checkbox = (await screen.findByLabelText(/inject auto-print/i)) as HTMLInputElement;
  1220. expect(checkbox.checked).toBe(false);
  1221. await user.click(checkbox);
  1222. // CRITICAL: after the click the checkbox must stay checked. Under the
  1223. // pre-fix reset effect, the parent state would flip back to false within
  1224. // a render and the displayed `checked` attribute would track it.
  1225. await waitFor(() => expect(checkbox.checked).toBe(true));
  1226. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1227. await waitFor(() => expect(queueCalls.length).toBe(1));
  1228. // The injection flag actually reaches the API — pre-fix the parent reset
  1229. // would have stripped it before submit.
  1230. expect(queueCalls[0].gcode_injection).toBe(true);
  1231. });
  1232. it('injection OFF queues all copies through the scheduler path', async () => {
  1233. const queueCalls: Record<string, unknown>[] = [];
  1234. server.use(
  1235. withSnippets(),
  1236. http.post('/api/v1/queue/', async ({ request }) => {
  1237. queueCalls.push((await request.json()) as Record<string, unknown>);
  1238. return HttpResponse.json({ id: queueCalls.length, status: 'pending' });
  1239. }),
  1240. );
  1241. const user = userEvent.setup();
  1242. render(
  1243. <PrintModal
  1244. mode="create"
  1245. archiveId={1}
  1246. archiveName="Benchy"
  1247. initialSelectedPrinterIds={[1]}
  1248. onClose={mockOnClose}
  1249. onSuccess={mockOnSuccess}
  1250. />
  1251. );
  1252. const qty = (await screen.findByLabelText('Quantity')) as HTMLInputElement;
  1253. await user.tripleClick(qty);
  1254. await user.keyboard('3');
  1255. expect(qty.value).toBe('3');
  1256. // Leave injection unticked: unified dispatch still queues all copies.
  1257. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1258. await waitFor(() => expect(queueCalls.length).toBe(1));
  1259. expect(queueCalls[0].quantity).toBe(3);
  1260. });
  1261. });
  1262. describe('project_id forwarding', () => {
  1263. beforeEach(() => {
  1264. // Additional handlers needed for library file mode
  1265. server.use(
  1266. http.get('/api/v1/library/files/:id', () => {
  1267. return HttpResponse.json({
  1268. id: 5,
  1269. filename: 'benchy.gcode.3mf',
  1270. print_name: null,
  1271. file_type: '3mf',
  1272. folder_id: null,
  1273. project_id: null,
  1274. file_hash: null,
  1275. file_size_bytes: 1024,
  1276. thumbnail_path: null,
  1277. created_at: '2024-01-01T00:00:00Z',
  1278. updated_at: '2024-01-01T00:00:00Z',
  1279. });
  1280. }),
  1281. http.get('/api/v1/library/files/:id/plates', () => {
  1282. return HttpResponse.json({ is_multi_plate: false, plates: [] });
  1283. }),
  1284. http.get('/api/v1/library/files/:id/filament-requirements', () => {
  1285. return HttpResponse.json({ file_id: 5, filename: 'benchy.gcode.3mf', filaments: [] });
  1286. }),
  1287. http.get('/api/v1/printers/:id/status', () => {
  1288. return HttpResponse.json({ connected: true, state: 'IDLE', ams: [], vt_tray: [] });
  1289. }),
  1290. );
  1291. });
  1292. it('includes project_id in queue item when printing a library file with projectId set', async () => {
  1293. let capturedBody: Record<string, unknown> | null = null;
  1294. server.use(
  1295. http.post('/api/v1/queue/', async ({ request }) => {
  1296. capturedBody = await request.json() as Record<string, unknown>;
  1297. return HttpResponse.json({ id: 1, status: 'pending' });
  1298. })
  1299. );
  1300. const user = userEvent.setup();
  1301. render(
  1302. <PrintModal
  1303. mode="create"
  1304. libraryFileId={5}
  1305. archiveName="Benchy"
  1306. projectId={42}
  1307. initialSelectedPrinterIds={[1]}
  1308. onClose={mockOnClose}
  1309. onSuccess={mockOnSuccess}
  1310. />
  1311. );
  1312. // Wait for the modal to load printer and file data
  1313. await waitFor(() => {
  1314. expect(screen.getByRole('button', { name: /^print$/i })).toBeInTheDocument();
  1315. });
  1316. await user.click(screen.getByRole('button', { name: /^print$/i }));
  1317. await waitFor(() => {
  1318. expect(capturedBody).not.toBeNull();
  1319. expect(capturedBody?.library_file_id).toBe(5);
  1320. expect(capturedBody?.project_id).toBe(42);
  1321. });
  1322. });
  1323. it('queues archive prints through the scheduler path', async () => {
  1324. let capturedBody: Record<string, unknown> | null = null;
  1325. server.use(
  1326. http.post('/api/v1/queue/', async ({ request }) => {
  1327. capturedBody = await request.json() as Record<string, unknown>;
  1328. return HttpResponse.json({ id: 1, status: 'pending' });
  1329. })
  1330. );
  1331. const user = userEvent.setup();
  1332. render(
  1333. <PrintModal
  1334. mode="create"
  1335. archiveId={1}
  1336. archiveName="Benchy"
  1337. projectId={42}
  1338. initialSelectedPrinterIds={[1]}
  1339. onClose={mockOnClose}
  1340. onSuccess={mockOnSuccess}
  1341. />
  1342. );
  1343. await waitFor(() => {
  1344. expect(screen.getByRole('button', { name: /^print$/i })).toBeInTheDocument();
  1345. });
  1346. await user.click(screen.getByRole('button', { name: /^print$/i }));
  1347. await waitFor(() => {
  1348. expect(capturedBody).not.toBeNull();
  1349. expect(capturedBody?.archive_id).toBe(1);
  1350. expect(capturedBody?.project_id).toBe(42);
  1351. });
  1352. });
  1353. it('adds ASAP prints to the top of the queue', async () => {
  1354. let capturedBody: Record<string, unknown> | null = null;
  1355. server.use(
  1356. http.post('/api/v1/queue/', async ({ request }) => {
  1357. capturedBody = await request.json() as Record<string, unknown>;
  1358. return HttpResponse.json({ id: 1, status: 'pending' });
  1359. })
  1360. );
  1361. const user = userEvent.setup();
  1362. render(
  1363. <PrintModal
  1364. mode="create"
  1365. archiveId={1}
  1366. archiveName="Benchy"
  1367. initialSelectedPrinterIds={[1]}
  1368. onClose={mockOnClose}
  1369. onSuccess={mockOnSuccess}
  1370. />
  1371. );
  1372. await waitFor(() => {
  1373. expect(screen.getByRole('button', { name: /^print$/i })).toBeInTheDocument();
  1374. });
  1375. await user.click(screen.getByRole('button', { name: /^print$/i }));
  1376. await waitFor(() => {
  1377. expect(capturedBody).not.toBeNull();
  1378. expect(capturedBody?.insert_at_top).toBe(true);
  1379. expect(capturedBody?.insert_position).toBe(1);
  1380. expect(capturedBody?.manual_start).toBe(false);
  1381. expect(capturedBody?.scheduled_time).toBeUndefined();
  1382. });
  1383. });
  1384. it('adds Queue prints to the back unless manual start is required', async () => {
  1385. let capturedBody: Record<string, unknown> | null = null;
  1386. server.use(
  1387. http.post('/api/v1/queue/', async ({ request }) => {
  1388. capturedBody = await request.json() as Record<string, unknown>;
  1389. return HttpResponse.json({ id: 1, status: 'pending' });
  1390. })
  1391. );
  1392. const user = userEvent.setup();
  1393. render(
  1394. <PrintModal
  1395. mode="create"
  1396. archiveId={1}
  1397. archiveName="Benchy"
  1398. initialSelectedPrinterIds={[1]}
  1399. onClose={mockOnClose}
  1400. onSuccess={mockOnSuccess}
  1401. />
  1402. );
  1403. await user.click(screen.getByRole('button', { name: /^queue$/i }));
  1404. expect(screen.getByLabelText(/require manual start/i)).toBeInTheDocument();
  1405. await user.click(screen.getByLabelText(/require manual start/i));
  1406. await user.click(screen.getByRole('button', { name: /^print$/i }));
  1407. await waitFor(() => {
  1408. expect(capturedBody).not.toBeNull();
  1409. expect(capturedBody?.insert_at_top).toBeUndefined();
  1410. expect(capturedBody?.insert_position).toBeUndefined();
  1411. expect(capturedBody?.manual_start).toBe(true);
  1412. });
  1413. });
  1414. });
  1415. describe('cleanup_library_after_dispatch forwarding (#730)', () => {
  1416. // The Printers-page Direct-Print flow passes cleanupLibraryAfterDispatch so the
  1417. // transient LibraryFile created by FileUploadModal is deleted once the archive
  1418. // owns its own copy. File Manager / Project Detail flows leave the prop unset so
  1419. // their deliberately-added library entries survive the print.
  1420. beforeEach(() => {
  1421. server.use(
  1422. http.get('/api/v1/library/files/:id', () => {
  1423. return HttpResponse.json({
  1424. id: 5,
  1425. filename: 'benchy.gcode.3mf',
  1426. file_type: '3mf',
  1427. folder_id: null,
  1428. project_id: null,
  1429. file_hash: null,
  1430. file_size_bytes: 1024,
  1431. thumbnail_path: null,
  1432. created_at: '2024-01-01T00:00:00Z',
  1433. updated_at: '2024-01-01T00:00:00Z',
  1434. });
  1435. }),
  1436. http.get('/api/v1/library/files/:id/plates', () => {
  1437. return HttpResponse.json({ is_multi_plate: false, plates: [] });
  1438. }),
  1439. http.get('/api/v1/library/files/:id/filament-requirements', () => {
  1440. return HttpResponse.json({ file_id: 5, filename: 'benchy.gcode.3mf', filaments: [] });
  1441. }),
  1442. http.get('/api/v1/printers/:id/status', () => {
  1443. return HttpResponse.json({ connected: true, state: 'IDLE', ams: [], vt_tray: [] });
  1444. }),
  1445. );
  1446. });
  1447. it('forwards cleanup_library_after_dispatch=true when the Direct-Print prop is set', async () => {
  1448. let capturedBody: Record<string, unknown> | null = null;
  1449. server.use(
  1450. http.post('/api/v1/queue/', async ({ request }) => {
  1451. capturedBody = (await request.json()) as Record<string, unknown>;
  1452. return HttpResponse.json({ id: 1, status: 'pending' });
  1453. })
  1454. );
  1455. const user = userEvent.setup();
  1456. render(
  1457. <PrintModal
  1458. mode="create"
  1459. libraryFileId={5}
  1460. archiveName="Benchy"
  1461. cleanupLibraryAfterDispatch
  1462. initialSelectedPrinterIds={[1]}
  1463. onClose={mockOnClose}
  1464. onSuccess={mockOnSuccess}
  1465. />
  1466. );
  1467. await waitFor(() => {
  1468. expect(screen.getByRole('button', { name: /^print$/i })).toBeInTheDocument();
  1469. });
  1470. await user.click(screen.getByRole('button', { name: /^print$/i }));
  1471. await waitFor(() => {
  1472. expect(capturedBody).not.toBeNull();
  1473. expect(capturedBody?.cleanup_library_after_dispatch).toBe(true);
  1474. });
  1475. });
  1476. it('defaults to omitting cleanup_library_after_dispatch (File Manager / Project flows survive)', async () => {
  1477. let capturedBody: Record<string, unknown> | null = null;
  1478. server.use(
  1479. http.post('/api/v1/queue/', async ({ request }) => {
  1480. capturedBody = (await request.json()) as Record<string, unknown>;
  1481. return HttpResponse.json({ id: 1, status: 'pending' });
  1482. })
  1483. );
  1484. const user = userEvent.setup();
  1485. render(
  1486. <PrintModal
  1487. mode="create"
  1488. libraryFileId={5}
  1489. archiveName="Benchy"
  1490. initialSelectedPrinterIds={[1]}
  1491. onClose={mockOnClose}
  1492. onSuccess={mockOnSuccess}
  1493. />
  1494. );
  1495. await waitFor(() => {
  1496. expect(screen.getByRole('button', { name: /^print$/i })).toBeInTheDocument();
  1497. });
  1498. await user.click(screen.getByRole('button', { name: /^print$/i }));
  1499. await waitFor(() => {
  1500. expect(capturedBody).not.toBeNull();
  1501. });
  1502. // Either omitted entirely or explicitly undefined — both interpret as "keep file"
  1503. expect(capturedBody?.cleanup_library_after_dispatch).toBeUndefined();
  1504. });
  1505. });
  1506. describe('ask-for-outcome pill (#1898 follow-up)', () => {
  1507. // The pill outside the collapsed Print Options panel and the row inside it
  1508. // edit the same printOptions.confirm_outcome, so flipping either must be
  1509. // reflected by the other and land in the submitted payload.
  1510. // Both carry the label "Ask for Outcome"; the pill is the only button with
  1511. // that name, the panel row is found through its description text.
  1512. const pill = () => screen.getByRole('button', { name: 'Ask for Outcome' });
  1513. const panelRowDesc = 'Ask whether the print came out well after it completes';
  1514. const panelRow = () => screen.getByText(panelRowDesc).closest('div')!.parentElement!;
  1515. it('starts off and toggles on a click', async () => {
  1516. const user = userEvent.setup();
  1517. render(
  1518. <PrintModal mode="create" archiveId={1} archiveName="Benchy" initialSelectedPrinterIds={[1]} onClose={mockOnClose} />
  1519. );
  1520. expect(pill()).toHaveAttribute('aria-pressed', 'false');
  1521. await user.click(pill());
  1522. expect(pill()).toHaveAttribute('aria-pressed', 'true');
  1523. });
  1524. it('shares its state with the row inside Print Options', async () => {
  1525. const user = userEvent.setup();
  1526. render(
  1527. <PrintModal mode="create" archiveId={1} archiveName="Benchy" initialSelectedPrinterIds={[1]} onClose={mockOnClose} />
  1528. );
  1529. await user.click(pill());
  1530. // The panel opens expanded when a printer is preselected; expand otherwise.
  1531. if (!screen.queryByText(panelRowDesc)) await user.click(screen.getByText('Print Options'));
  1532. const row = panelRow();
  1533. expect(within(row).getByRole('button', { name: 'On' })).toHaveClass('bg-bambu-green');
  1534. await user.click(within(row).getByRole('button', { name: 'Off' }));
  1535. expect(pill()).toHaveAttribute('aria-pressed', 'false');
  1536. });
  1537. it('submits confirm_outcome=true with the queue item when turned on', async () => {
  1538. let capturedBody: Record<string, unknown> | null = null;
  1539. server.use(
  1540. http.post('/api/v1/queue/', async ({ request }) => {
  1541. capturedBody = (await request.json()) as Record<string, unknown>;
  1542. return HttpResponse.json({ id: 1, status: 'pending' });
  1543. }),
  1544. );
  1545. const user = userEvent.setup();
  1546. render(
  1547. <PrintModal mode="create" archiveId={1} archiveName="Benchy" initialSelectedPrinterIds={[1]} onClose={mockOnClose} />
  1548. );
  1549. await user.click(pill());
  1550. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1551. await waitFor(() => expect(capturedBody).not.toBeNull());
  1552. expect(capturedBody!.confirm_outcome).toBe(true);
  1553. });
  1554. it('reflects the queue item value in edit mode and saves the change', async () => {
  1555. let capturedBody: Record<string, unknown> | null = null;
  1556. server.use(
  1557. http.patch('/api/v1/queue/:id', async ({ request }) => {
  1558. capturedBody = (await request.json()) as Record<string, unknown>;
  1559. return HttpResponse.json({ id: 1, status: 'pending' });
  1560. }),
  1561. );
  1562. const user = userEvent.setup();
  1563. render(
  1564. <PrintModal
  1565. mode="edit-queue-item"
  1566. archiveId={1}
  1567. archiveName="Test Print"
  1568. queueItem={createMockQueueItem({ confirm_outcome: true })}
  1569. onClose={mockOnClose}
  1570. />
  1571. );
  1572. expect(pill()).toHaveAttribute('aria-pressed', 'true');
  1573. await user.click(pill());
  1574. await user.click(screen.getByRole('button', { name: /save/i }));
  1575. await waitFor(() => expect(capturedBody).not.toBeNull());
  1576. expect(capturedBody!.confirm_outcome).toBe(false);
  1577. });
  1578. });
  1579. });
  1580. describe('PrintModal — per-plate filament mapping (#2551 follow-up)', () => {
  1581. const mockOnClose = vi.fn();
  1582. // These tests deliberately do NOT use the shared `render` from '../utils': its
  1583. // QueryClient sets `gcTime: 0`, which evicts a query the instant it loses its
  1584. // observer. The whole-file filament requirements are fetched on open and then
  1585. // orphaned when a plate is auto-selected, so under gcTime:0 they vanish and the
  1586. // modal simply sends no mapping — the bug cannot reproduce. A real browser keeps
  1587. // that entry for 5 minutes and hands the union straight back when the user picks
  1588. // a second plate, which is what got mapped onto every plate. Same providers,
  1589. // production cache behaviour.
  1590. const render = (ui: React.ReactElement) => {
  1591. const queryClient = new QueryClient({
  1592. defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
  1593. });
  1594. return rtlRender(
  1595. <QueryClientProvider client={queryClient}>
  1596. <BrowserRouter>
  1597. <AuthProvider>
  1598. <ThemeProvider>
  1599. <ToastProvider>{ui}</ToastProvider>
  1600. </ThemeProvider>
  1601. </AuthProvider>
  1602. </BrowserRouter>
  1603. </QueryClientProvider>,
  1604. );
  1605. };
  1606. // Two plates, each printing one red object, but on different slots of the same
  1607. // file. The printer has exactly one red spool (tray 0) and one black (tray 1).
  1608. // Matching the union of both plates makes slot 1 claim the red tray and drops
  1609. // slot 2 onto the black one — so plate 2 would print in the wrong colour.
  1610. const PLATES = {
  1611. is_multi_plate: true,
  1612. plates: [
  1613. { 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 },
  1614. { 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 },
  1615. ],
  1616. };
  1617. const SLOT_1_RED = { slot_id: 1, type: 'PLA', color: '#FF0000', tray_info_idx: '', used_grams: 50 };
  1618. const SLOT_2_RED = { slot_id: 2, type: 'PLA', color: '#FF0000', tray_info_idx: '', used_grams: 50 };
  1619. beforeEach(() => {
  1620. vi.clearAllMocks();
  1621. server.use(
  1622. http.get('/api/v1/printers/', () => HttpResponse.json(mockPrinters)),
  1623. http.get('/api/v1/archives/:id/plates', () => HttpResponse.json(PLATES)),
  1624. // The endpoint is plate-aware: no plate_id yields the whole-file union.
  1625. http.get('/api/v1/archives/:id/filament-requirements', ({ request }) => {
  1626. const plateId = new URL(request.url).searchParams.get('plate_id');
  1627. if (plateId === '1') return HttpResponse.json({ filaments: [SLOT_1_RED] });
  1628. if (plateId === '2') return HttpResponse.json({ filaments: [SLOT_2_RED] });
  1629. return HttpResponse.json({ filaments: [SLOT_1_RED, SLOT_2_RED] });
  1630. }),
  1631. http.get('/api/v1/printers/:id/status', () =>
  1632. HttpResponse.json({
  1633. connected: true,
  1634. state: 'IDLE',
  1635. ams: [{ id: 0, tray: [
  1636. { id: 0, tray_type: 'PLA', tray_color: 'FF0000' },
  1637. { id: 1, tray_type: 'PLA', tray_color: '000000' },
  1638. ] }],
  1639. vt_tray: [],
  1640. }),
  1641. ),
  1642. http.get('/api/v1/printers/:id/assignments', () => HttpResponse.json([])),
  1643. http.post('/api/v1/queue/', () => HttpResponse.json({ id: 1, status: 'pending' })),
  1644. );
  1645. });
  1646. const selectBothPlates = async (user: ReturnType<typeof userEvent.setup>) => {
  1647. await waitFor(() => expect(screen.getByText('X1 Carbon')).toBeInTheDocument());
  1648. await user.click(screen.getByText('X1 Carbon'));
  1649. await waitFor(() => expect(screen.getByText('Plate 2')).toBeInTheDocument());
  1650. await user.click(screen.getByText('Plate 2')); // Plate 1 is auto-selected
  1651. };
  1652. it('shows one mapping panel per selected plate, named after the plate', async () => {
  1653. const user = userEvent.setup();
  1654. render(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  1655. await selectBothPlates(user);
  1656. await waitFor(() => {
  1657. expect(screen.getByText(/Filament Mapping — Plate 1/)).toBeInTheDocument();
  1658. expect(screen.getByText(/Filament Mapping — Plate 2/)).toBeInTheDocument();
  1659. });
  1660. });
  1661. it('sends each plate the mapping for its own slots, not the whole-file union', async () => {
  1662. const queued: { plate_id: number; ams_mapping: number[] | null }[] = [];
  1663. server.use(
  1664. http.post('/api/v1/queue/', async ({ request }) => {
  1665. queued.push((await request.json()) as { plate_id: number; ams_mapping: number[] | null });
  1666. return HttpResponse.json({ id: queued.length, status: 'pending' });
  1667. }),
  1668. );
  1669. const user = userEvent.setup();
  1670. render(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  1671. await selectBothPlates(user);
  1672. await waitFor(() => expect(screen.getByText(/Filament Mapping — Plate 2/)).toBeInTheDocument());
  1673. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1674. await waitFor(() => expect(queued.length).toBe(2));
  1675. const plate1 = queued.find((q) => q.plate_id === 1);
  1676. const plate2 = queued.find((q) => q.plate_id === 2);
  1677. // Plate 1 prints slot 1 from the red tray.
  1678. expect(plate1?.ams_mapping).toEqual([0]);
  1679. // Plate 2 prints slot 2 from the SAME red tray — slot 1 is not its business.
  1680. // The union mapping would have been [0, 1], sending this plate to the black tray.
  1681. expect(plate2?.ams_mapping).toEqual([-1, 0]);
  1682. });
  1683. it('sends no mapping when several plates fan out across several printers', async () => {
  1684. // A tray id is meaningless on a different printer, so the first printer's
  1685. // mapping must not be handed to the second. The scheduler maps each plate
  1686. // against the printer it actually dispatches to.
  1687. const queued: { printer_id: number; ams_mapping?: number[] | null }[] = [];
  1688. server.use(
  1689. http.post('/api/v1/queue/', async ({ request }) => {
  1690. queued.push((await request.json()) as { printer_id: number; ams_mapping?: number[] | null });
  1691. return HttpResponse.json({ id: queued.length, status: 'pending' });
  1692. }),
  1693. );
  1694. const user = userEvent.setup();
  1695. render(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  1696. await waitFor(() => expect(screen.getByText('X1 Carbon')).toBeInTheDocument());
  1697. await user.click(screen.getByText('X1 Carbon'));
  1698. await user.click(screen.getByText('P1S'));
  1699. await waitFor(() => expect(screen.getByText('Plate 2')).toBeInTheDocument());
  1700. await user.click(screen.getByText('Plate 2'));
  1701. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1702. await waitFor(() => expect(queued.length).toBe(4)); // 2 plates x 2 printers
  1703. queued.forEach((q) => expect(q.ams_mapping ?? null).toBeNull());
  1704. });
  1705. it('sends no mapping for a model-assigned multi-plate job, leaving it to the scheduler', async () => {
  1706. const queued: { ams_mapping?: number[] | null }[] = [];
  1707. server.use(
  1708. http.post('/api/v1/queue/', async ({ request }) => {
  1709. queued.push((await request.json()) as { ams_mapping?: number[] | null });
  1710. return HttpResponse.json({ id: queued.length, status: 'pending' });
  1711. }),
  1712. );
  1713. const user = userEvent.setup();
  1714. render(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  1715. // "Any model" mode: no printer is chosen, so there is no AMS to map onto and
  1716. // the scheduler computes the mapping per plate once it picks one.
  1717. await waitFor(() => expect(screen.getByText('Plate 2')).toBeInTheDocument());
  1718. await user.click(screen.getByText('Plate 2'));
  1719. await user.click(screen.getByRole('button', { name: /any model/i }));
  1720. await waitFor(() => expect(screen.getByRole('combobox')).toBeInTheDocument());
  1721. await user.selectOptions(screen.getByRole('combobox'), 'X1C');
  1722. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1723. await waitFor(() => expect(queued.length).toBe(2));
  1724. queued.forEach((q) => expect(q.ams_mapping ?? null).toBeNull());
  1725. });
  1726. it('drops a plate\'s manual tray overrides when the printer changes', async () => {
  1727. // A manual override holds a global tray id, which names a different spool on a
  1728. // different printer. Carrying plate 1's "slot 1 -> tray 1" from the X1C over to
  1729. // the P1S would dispatch a tray the user never picked.
  1730. const queued: { plate_id: number; ams_mapping: number[] | null }[] = [];
  1731. server.use(
  1732. http.post('/api/v1/queue/', async ({ request }) => {
  1733. queued.push((await request.json()) as { plate_id: number; ams_mapping: number[] | null });
  1734. return HttpResponse.json({ id: queued.length, status: 'pending' });
  1735. }),
  1736. );
  1737. const user = userEvent.setup();
  1738. render(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  1739. await selectBothPlates(user);
  1740. await waitFor(() => expect(screen.getByText(/Filament Mapping — Plate 1/)).toBeInTheDocument());
  1741. // Force plate 1's slot 1 onto the black tray (1) instead of the auto-matched red (0).
  1742. // A2 is AMS 0 / tray 1, i.e. global tray id 1 — the value the old
  1743. // `selectOptions(..., '1')` picked.
  1744. await user.click(screen.getByText(/Filament Mapping — Plate 1/));
  1745. await pickFromSlotPicker(user, /printer slot for/i, /^A2:/);
  1746. // Now move the job to the other printer.
  1747. await user.click(screen.getByText('X1 Carbon')); // deselect
  1748. await user.click(screen.getByText('P1S'));
  1749. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1750. await waitFor(() => expect(queued.length).toBe(2));
  1751. // Plate 1 auto-matches red (tray 0) on the new printer. Tray 1 is the stale pick.
  1752. const plate1 = queued.find((q) => q.plate_id === 1);
  1753. expect(plate1?.ams_mapping).toEqual([0]);
  1754. });
  1755. it('sets Print Anyway only on the printers whose filament warning it answered', async () => {
  1756. // X1 Carbon is short on the mapped spool, P1S is not. Answering the warning
  1757. // for X1 Carbon must not wave P1S's job through the scheduler's own check.
  1758. const queued: { printer_id: number; skip_filament_check?: boolean }[] = [];
  1759. server.use(
  1760. http.get('/api/v1/printers/:id/inventory-remain', ({ params }) => {
  1761. const grams = params.id === '1' ? 10 : 1000;
  1762. return HttpResponse.json({
  1763. inventory_remain_g: { '0': grams },
  1764. slot_materials: [
  1765. { ams_id: 0, tray_id: 0, global_tray_id: 0, material_key: 'preset:GFA00|color:FF0000', remaining_g: grams, extruder: 0 },
  1766. ],
  1767. });
  1768. }),
  1769. http.post('/api/v1/queue/', async ({ request }) => {
  1770. queued.push((await request.json()) as { printer_id: number; skip_filament_check?: boolean });
  1771. return HttpResponse.json({ id: queued.length, status: 'pending' });
  1772. }),
  1773. );
  1774. const user = userEvent.setup();
  1775. render(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  1776. await waitFor(() => expect(screen.getByText('X1 Carbon')).toBeInTheDocument());
  1777. await user.click(screen.getByText('X1 Carbon'));
  1778. await user.click(screen.getByText('P1S'));
  1779. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1780. await waitFor(() => expect(screen.getByText(/Not enough filament/i)).toBeInTheDocument());
  1781. await user.click(screen.getByRole('button', { name: /print anyway/i }));
  1782. await waitFor(() => expect(queued.length).toBe(2));
  1783. const byPrinter = Object.fromEntries(queued.map((q) => [q.printer_id, q.skip_filament_check]));
  1784. expect(byPrinter).toEqual({ 1: true, 2: undefined });
  1785. });
  1786. it('sums what the plates draw from one spool before warning about it', async () => {
  1787. // Both plates map to the same red tray. 60 g left covers either plate on its
  1788. // own (40 g), but not both — the check has to add them up, not test them
  1789. // one at a time.
  1790. server.use(
  1791. http.get('/api/v1/archives/:id/filament-requirements', ({ request }) => {
  1792. const plateId = new URL(request.url).searchParams.get('plate_id');
  1793. if (plateId === '1') return HttpResponse.json({ filaments: [{ ...SLOT_1_RED, used_grams: 40 }] });
  1794. if (plateId === '2') return HttpResponse.json({ filaments: [{ ...SLOT_2_RED, used_grams: 40 }] });
  1795. return HttpResponse.json({ filaments: [SLOT_1_RED, SLOT_2_RED] });
  1796. }),
  1797. http.get('/api/v1/printers/:id/inventory-remain', () =>
  1798. HttpResponse.json({
  1799. inventory_remain_g: { '0': 60 },
  1800. slot_materials: [
  1801. { ams_id: 0, tray_id: 0, global_tray_id: 0, material_key: 'preset:GFA00|color:FF0000', remaining_g: 60, extruder: 0 },
  1802. ],
  1803. }),
  1804. ),
  1805. );
  1806. const user = userEvent.setup();
  1807. render(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  1808. await selectBothPlates(user);
  1809. await waitFor(() => expect(screen.getByText(/Filament Mapping — Plate 2/)).toBeInTheDocument());
  1810. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1811. // 80 g needed from a spool with 60 g left → the acknowledgement dialog, not a
  1812. // silent queue.
  1813. await waitFor(() => expect(screen.getByText(/Not enough filament/i)).toBeInTheDocument());
  1814. expect(screen.getByText(/needs 80g, remaining 60g/i)).toBeInTheDocument();
  1815. });
  1816. // Two red trays holding the same material, so AMS Filament Backup can switch
  1817. // between them mid-print. Both tests below map both plates onto tray 0.
  1818. const twoRedTrays = (backupOn: boolean) =>
  1819. http.get('/api/v1/printers/:id/status', () =>
  1820. HttpResponse.json({
  1821. connected: true,
  1822. state: 'IDLE',
  1823. ams_filament_backup: backupOn,
  1824. ams: [{ id: 0, tray: [
  1825. { id: 0, tray_type: 'PLA', tray_color: 'FF0000' },
  1826. { id: 1, tray_type: 'PLA', tray_color: 'FF0000' },
  1827. ] }],
  1828. vt_tray: [],
  1829. }),
  1830. );
  1831. const redPool = (trayZeroGrams: number, trayOneGrams: number) =>
  1832. http.get('/api/v1/printers/:id/inventory-remain', () =>
  1833. HttpResponse.json({
  1834. inventory_remain_g: { '0': trayZeroGrams, '1': trayOneGrams },
  1835. slot_materials: [
  1836. { ams_id: 0, tray_id: 0, global_tray_id: 0, material_key: 'preset:GFA00|color:FF0000', remaining_g: trayZeroGrams, extruder: 0 },
  1837. { ams_id: 0, tray_id: 1, global_tray_id: 1, material_key: 'preset:GFA00|color:FF0000', remaining_g: trayOneGrams, extruder: 0 },
  1838. ],
  1839. }),
  1840. );
  1841. const bothPlatesNeedForty = http.get('/api/v1/archives/:id/filament-requirements', ({ request }) => {
  1842. const plateId = new URL(request.url).searchParams.get('plate_id');
  1843. if (plateId === '1') return HttpResponse.json({ filaments: [{ ...SLOT_1_RED, used_grams: 40 }] });
  1844. if (plateId === '2') return HttpResponse.json({ filaments: [{ ...SLOT_2_RED, used_grams: 40 }] });
  1845. return HttpResponse.json({ filaments: [SLOT_1_RED, SLOT_2_RED] });
  1846. });
  1847. it('lets the print through when AMS Filament Backup covers it from a peer spool', async () => {
  1848. // The reported block: two plates draw 80 g from a tray holding 60 g, but the
  1849. // slot next to it holds the same material. The firmware switches between
  1850. // them, and the dispatcher has pooled them since #1762 — the modal used to
  1851. // weigh the mapped slot alone and refused a print the dispatcher would run.
  1852. const queued: unknown[] = [];
  1853. server.use(
  1854. bothPlatesNeedForty,
  1855. twoRedTrays(true),
  1856. redPool(60, 1000),
  1857. http.post('/api/v1/queue/', async ({ request }) => {
  1858. queued.push(await request.json());
  1859. return HttpResponse.json({ id: queued.length, status: 'pending' });
  1860. }),
  1861. );
  1862. const user = userEvent.setup();
  1863. render(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  1864. await selectBothPlates(user);
  1865. await waitFor(() => expect(screen.getByText(/Filament Mapping — Plate 2/)).toBeInTheDocument());
  1866. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1867. await waitFor(() => expect(queued.length).toBe(2));
  1868. expect(screen.queryByText(/Not enough filament/i)).not.toBeInTheDocument();
  1869. });
  1870. it('warns against the pooled total when AMS Filament Backup still cannot cover it', async () => {
  1871. // Backup is on but both spools together are short. The shortfall is real, so
  1872. // it still has to be raised — against the pool, not the one slot, or the
  1873. // numbers contradict the AMS the user is looking at.
  1874. server.use(bothPlatesNeedForty, twoRedTrays(true), redPool(60, 10));
  1875. const user = userEvent.setup();
  1876. render(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  1877. await selectBothPlates(user);
  1878. await waitFor(() => expect(screen.getByText(/Filament Mapping — Plate 2/)).toBeInTheDocument());
  1879. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1880. await waitFor(() => expect(screen.getByText(/Not enough filament/i)).toBeInTheDocument());
  1881. expect(screen.getByText(/needs 80g, 70g available across matching spools/i)).toBeInTheDocument();
  1882. });
  1883. it('keeps weighing the mapped slot alone when AMS Filament Backup is off', async () => {
  1884. // Same two spools, backup off: the firmware will not switch, so the peer's
  1885. // grams are not available to this print and the warning must still fire.
  1886. server.use(bothPlatesNeedForty, twoRedTrays(false), redPool(60, 1000));
  1887. const user = userEvent.setup();
  1888. render(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  1889. await selectBothPlates(user);
  1890. await waitFor(() => expect(screen.getByText(/Filament Mapping — Plate 2/)).toBeInTheDocument());
  1891. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  1892. await waitFor(() => expect(screen.getByText(/Not enough filament/i)).toBeInTheDocument());
  1893. expect(screen.getByText(/needs 80g, remaining 60g/i)).toBeInTheDocument();
  1894. });
  1895. it('holds the Print button until every selected plate has answered', async () => {
  1896. // A plate whose filaments cannot be read has no mapping and no forced colours;
  1897. // queueing it anyway prints it in whatever happens to be loaded.
  1898. server.use(
  1899. http.get('/api/v1/archives/:id/filament-requirements', ({ request }) => {
  1900. const plateId = new URL(request.url).searchParams.get('plate_id');
  1901. if (plateId === '1') return HttpResponse.json({ filaments: [SLOT_1_RED] });
  1902. if (plateId === '2') return new HttpResponse(null, { status: 500 });
  1903. return HttpResponse.json({ filaments: [SLOT_1_RED, SLOT_2_RED] });
  1904. }),
  1905. );
  1906. const user = userEvent.setup();
  1907. render(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  1908. await selectBothPlates(user);
  1909. await waitFor(() =>
  1910. expect(document.querySelector('button[type="submit"]')).toBeDisabled(),
  1911. );
  1912. expect(screen.getByText(/could not be read/i)).toBeInTheDocument();
  1913. // Deselecting the unreadable plate frees the rest of the job.
  1914. await user.click(screen.getByText('Plate 2'));
  1915. await waitFor(() =>
  1916. expect(document.querySelector('button[type="submit"]')).not.toBeDisabled(),
  1917. );
  1918. });
  1919. });
  1920. describe('PrintModal — per-plate filament override in model mode (#2552)', () => {
  1921. const mockOnClose = vi.fn();
  1922. // The reporter's trigger — "only after the file was previously queued or printed"
  1923. // — is really "only once the plates query is warm in the cache". On a cold cache
  1924. // the plates data is undefined for the first render, so the whole-file filament
  1925. // requirements are fetched and left behind; the override panel then rendered from
  1926. // that union. On a warm cache the modal knows it is multi-plate from the first
  1927. // render, the whole-file query never runs, and the panel disappeared entirely.
  1928. // Both states are exercised here, and neither may depend on the cache.
  1929. const renderWithCache = (ui: React.ReactElement, prewarm?: (qc: QueryClient) => void) => {
  1930. const queryClient = new QueryClient({
  1931. defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
  1932. });
  1933. prewarm?.(queryClient);
  1934. return rtlRender(
  1935. <QueryClientProvider client={queryClient}>
  1936. <BrowserRouter>
  1937. <AuthProvider>
  1938. <ThemeProvider>
  1939. <ToastProvider>{ui}</ToastProvider>
  1940. </ThemeProvider>
  1941. </AuthProvider>
  1942. </BrowserRouter>
  1943. </QueryClientProvider>,
  1944. );
  1945. };
  1946. // Plate 1 prints slot 1 (red), plate 2 prints slot 2 (blue). Nothing is shared.
  1947. const PLATES = {
  1948. is_multi_plate: true,
  1949. plates: [
  1950. { 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 },
  1951. { 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 },
  1952. ],
  1953. };
  1954. const SLOT_1_RED = { slot_id: 1, type: 'PLA', color: '#FF0000', tray_info_idx: '', used_grams: 50 };
  1955. const SLOT_2_BLUE = { slot_id: 2, type: 'PLA', color: '#0000FF', tray_info_idx: '', used_grams: 50 };
  1956. beforeEach(() => {
  1957. vi.clearAllMocks();
  1958. server.use(
  1959. http.get('/api/v1/printers/', () => HttpResponse.json(mockPrinters)),
  1960. http.get('/api/v1/archives/:id/plates', () => HttpResponse.json(PLATES)),
  1961. http.get('/api/v1/archives/:id/filament-requirements', ({ request }) => {
  1962. const plateId = new URL(request.url).searchParams.get('plate_id');
  1963. if (plateId === '1') return HttpResponse.json({ filaments: [SLOT_1_RED] });
  1964. if (plateId === '2') return HttpResponse.json({ filaments: [SLOT_2_BLUE] });
  1965. return HttpResponse.json({ filaments: [SLOT_1_RED, SLOT_2_BLUE] });
  1966. }),
  1967. http.get('/api/v1/printers/available-filaments', () =>
  1968. HttpResponse.json([
  1969. { type: 'PLA', color: '#FF0000', tray_info_idx: 'GFA00', tray_sub_brands: 'PLA Basic', extruder_id: null },
  1970. { type: 'PLA', color: '#00FF00', tray_info_idx: 'GFA00', tray_sub_brands: 'PLA Basic', extruder_id: null },
  1971. ]),
  1972. ),
  1973. http.post('/api/v1/queue/', () => HttpResponse.json({ id: 1, status: 'pending' })),
  1974. );
  1975. });
  1976. const selectAnyX1CAndBothPlates = async (user: ReturnType<typeof userEvent.setup>) => {
  1977. await waitFor(() => expect(screen.getByText('Plate 2')).toBeInTheDocument());
  1978. await user.click(screen.getByText('Plate 2')); // Plate 1 is auto-selected
  1979. await user.click(screen.getByRole('button', { name: /any model/i }));
  1980. // Switching to model mode pre-selects the first model, so the override panels
  1981. // are already up; the target-model select is the one offering the models.
  1982. const modelSelect = await waitFor(() => {
  1983. const select = screen
  1984. .getAllByRole('combobox')
  1985. .find((el) => (el as HTMLSelectElement).options[0]?.value === '' && (el as HTMLSelectElement).options[0]?.text === 'Select a model...');
  1986. if (!select) throw new Error('target model select not rendered');
  1987. return select as HTMLSelectElement;
  1988. });
  1989. await user.selectOptions(modelSelect, 'X1C');
  1990. };
  1991. it('shows one override panel per selected plate even when the plates query is already cached', async () => {
  1992. const user = userEvent.setup();
  1993. renderWithCache(
  1994. <PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />,
  1995. // The file has been opened before: the plates are known on the first render,
  1996. // so the whole-file requirements query never runs. This is the state in which
  1997. // the override section used to vanish for a multi-plate selection.
  1998. (qc) => qc.setQueryData(['archive-plates', 1], PLATES),
  1999. );
  2000. await selectAnyX1CAndBothPlates(user);
  2001. await waitFor(() => {
  2002. expect(screen.getByText(/Filament Override — Plate 1/)).toBeInTheDocument();
  2003. expect(screen.getByText(/Filament Override — Plate 2/)).toBeInTheDocument();
  2004. });
  2005. });
  2006. it('shows the same per-plate panels on a cold cache', async () => {
  2007. const user = userEvent.setup();
  2008. renderWithCache(<PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />);
  2009. await selectAnyX1CAndBothPlates(user);
  2010. await waitFor(() => {
  2011. expect(screen.getByText(/Filament Override — Plate 1/)).toBeInTheDocument();
  2012. expect(screen.getByText(/Filament Override — Plate 2/)).toBeInTheDocument();
  2013. });
  2014. // Not the whole-file union in a single unnamed panel.
  2015. expect(screen.queryByText('Filament Override')).not.toBeInTheDocument();
  2016. });
  2017. it('sends each plate only the overrides for the slots it prints', async () => {
  2018. type Queued = {
  2019. plate_id: number;
  2020. filament_overrides?: Array<{ slot_id: number; force_color_match: boolean }> | null;
  2021. };
  2022. const queued: Queued[] = [];
  2023. server.use(
  2024. http.post('/api/v1/queue/', async ({ request }) => {
  2025. queued.push((await request.json()) as Queued);
  2026. return HttpResponse.json({ id: queued.length, status: 'pending' });
  2027. }),
  2028. );
  2029. const user = userEvent.setup();
  2030. renderWithCache(
  2031. <PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />,
  2032. (qc) => qc.setQueryData(['archive-plates', 1], PLATES),
  2033. );
  2034. await selectAnyX1CAndBothPlates(user);
  2035. await waitFor(() => expect(screen.getByText(/Filament Override — Plate 2/)).toBeInTheDocument());
  2036. // Force the colour on plate 2's only slot. Plate 1 does not print slot 2 and
  2037. // must not be held back waiting for a blue spool it never uses (#2551).
  2038. const forceBoxes = screen.getAllByRole('checkbox', { name: /force color match/i });
  2039. expect(forceBoxes).toHaveLength(2); // one slot per plate
  2040. await user.click(forceBoxes[1]);
  2041. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  2042. await waitFor(() => expect(queued.length).toBe(2));
  2043. const plate1 = queued.find((q) => q.plate_id === 1);
  2044. const plate2 = queued.find((q) => q.plate_id === 2);
  2045. expect(plate1?.filament_overrides ?? null).toBeNull();
  2046. expect(plate2?.filament_overrides).toEqual([
  2047. expect.objectContaining({ slot_id: 2, force_color_match: true }),
  2048. ]);
  2049. });
  2050. // The queue page shows the stored colour name. The same blue is "Marine
  2051. // Blue" in PLA Matte; the plain type "PLA" only reaches the generic name (SN-C9).
  2052. it("stores a forced slot's colour name within its sliced product line", async () => {
  2053. setColorCatalog({ '0000ff': 'Blue' }, { 'PLA Matte|0000ff': 'Marine Blue' });
  2054. type Queued = { plate_id: number; filament_overrides?: Array<{ slot_id: number; color_name?: string }> | null };
  2055. const queued: Queued[] = [];
  2056. server.use(
  2057. http.get('/api/v1/archives/:id/filament-requirements', () =>
  2058. HttpResponse.json({ filaments: [{ ...SLOT_2_BLUE, tray_info_idx: 'GFA01' }] }),
  2059. ),
  2060. http.get('/api/v1/cloud/builtin-filaments', () =>
  2061. HttpResponse.json([{ filament_id: 'GFA01', name: 'Bambu PLA Matte' }]),
  2062. ),
  2063. http.get('/api/v1/cloud/filament-id-map', () => HttpResponse.json({})),
  2064. http.post('/api/v1/queue/', async ({ request }) => {
  2065. queued.push((await request.json()) as Queued);
  2066. return HttpResponse.json({ id: queued.length, status: 'pending' });
  2067. }),
  2068. );
  2069. try {
  2070. const user = userEvent.setup();
  2071. renderWithCache(
  2072. <PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />,
  2073. (qc) => qc.setQueryData(['archive-plates', 1], PLATES),
  2074. );
  2075. await selectAnyX1CAndBothPlates(user);
  2076. await waitFor(() => expect(screen.getByText(/Filament Override — Plate 2/)).toBeInTheDocument());
  2077. // Wait for the preset names, which the stored colour name is derived from.
  2078. await waitFor(() => expect(screen.getAllByText(/PLA Matte/).length).toBeGreaterThan(0));
  2079. await user.click(screen.getAllByRole('checkbox', { name: /force color match/i })[1]);
  2080. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  2081. await waitFor(() => expect(queued.length).toBe(2));
  2082. expect(queued.find((q) => q.plate_id === 2)?.filament_overrides).toEqual([
  2083. expect.objectContaining({ slot_id: 2, color_name: 'Marine Blue' }),
  2084. ]);
  2085. } finally {
  2086. __resetColorCatalogForTests();
  2087. }
  2088. });
  2089. it("does not name a swapped slot's colour by the preset it was sliced with", async () => {
  2090. setColorCatalog({ '00ff00': 'Green' }, { 'PLA Matte|00ff00': 'Matte Green' });
  2091. type Queued = { plate_id: number; filament_overrides?: Array<{ slot_id: number; color_name?: string }> | null };
  2092. const queued: Queued[] = [];
  2093. server.use(
  2094. http.get('/api/v1/archives/:id/filament-requirements', () =>
  2095. HttpResponse.json({ filaments: [{ ...SLOT_2_BLUE, tray_info_idx: 'GFA01' }] }),
  2096. ),
  2097. http.get('/api/v1/cloud/builtin-filaments', () =>
  2098. HttpResponse.json([{ filament_id: 'GFA01', name: 'Bambu PLA Matte' }]),
  2099. ),
  2100. http.get('/api/v1/cloud/filament-id-map', () => HttpResponse.json({})),
  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. try {
  2107. const user = userEvent.setup();
  2108. renderWithCache(
  2109. <PrintModal mode="create" archiveId={1} archiveName="Two.gcode.3mf" onClose={mockOnClose} />,
  2110. (qc) => qc.setQueryData(['archive-plates', 1], PLATES),
  2111. );
  2112. await selectAnyX1CAndBothPlates(user);
  2113. await waitFor(() => expect(screen.getByText(/Filament Override — Plate 2/)).toBeInTheDocument());
  2114. await waitFor(() => expect(screen.getAllByText(/PLA Matte/).length).toBeGreaterThan(0));
  2115. // Swap the PLA Matte blue for the loaded PLA Basic green.
  2116. const pickers = screen.getAllByRole('combobox', { name: /filament override for/i });
  2117. await user.click(pickers[pickers.length - 1]);
  2118. await user.click(within(await screen.findByRole('listbox')).getByText(/Green/));
  2119. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  2120. await waitFor(() => expect(queued.length).toBe(2));
  2121. expect(queued.find((q) => q.plate_id === 2)?.filament_overrides).toEqual([
  2122. expect.objectContaining({ slot_id: 2, color: '#00FF00', color_name: 'Green' }),
  2123. ]);
  2124. } finally {
  2125. __resetColorCatalogForTests();
  2126. }
  2127. });
  2128. });
  2129. describe('PrintModal — per-plate quantity (#342)', () => {
  2130. const mockOnClose = vi.fn();
  2131. const PLATES = {
  2132. is_multi_plate: true,
  2133. plates: [
  2134. { 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 },
  2135. { 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 },
  2136. { 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 },
  2137. ],
  2138. };
  2139. const renderModal = (ui: React.ReactElement) => {
  2140. const queryClient = new QueryClient({
  2141. defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
  2142. });
  2143. queryClient.setQueryData(['archive-plates', 1], PLATES);
  2144. return rtlRender(
  2145. <QueryClientProvider client={queryClient}>
  2146. <BrowserRouter>
  2147. <AuthProvider>
  2148. <ThemeProvider>
  2149. <ToastProvider>{ui}</ToastProvider>
  2150. </ThemeProvider>
  2151. </AuthProvider>
  2152. </BrowserRouter>
  2153. </QueryClientProvider>,
  2154. );
  2155. };
  2156. beforeEach(() => {
  2157. vi.clearAllMocks();
  2158. server.use(
  2159. http.get('/api/v1/printers/', () => HttpResponse.json(mockPrinters)),
  2160. http.get('/api/v1/archives/:id/plates', () => HttpResponse.json(PLATES)),
  2161. http.get('/api/v1/archives/:id/filament-requirements', () =>
  2162. HttpResponse.json({ filaments: [{ slot_id: 1, type: 'PLA', color: '#FF0000', tray_info_idx: '', used_grams: 50 }] }),
  2163. ),
  2164. http.get('/api/v1/printers/available-filaments', () => HttpResponse.json([])),
  2165. http.post('/api/v1/queue/batches', () => HttpResponse.json({ id: 42, name: 'Order', status: 'active' })),
  2166. http.post('/api/v1/queue/', () => HttpResponse.json({ id: 1, status: 'pending' })),
  2167. );
  2168. });
  2169. const qtyInput = (plateName: string) =>
  2170. screen.getByRole('spinbutton', { name: new RegExp(plateName, 'i') });
  2171. it('replaces the single Quantity field with one control per selected plate', async () => {
  2172. const user = userEvent.setup();
  2173. renderModal(<PrintModal mode="create" archiveId={1} archiveName="Three.gcode.3mf" onClose={mockOnClose} />);
  2174. await waitFor(() => expect(screen.getByText('Plate 2')).toBeInTheDocument());
  2175. // Plate 1 is auto-selected and already carries its own quantity control.
  2176. expect(qtyInput('Plate 1')).toBeInTheDocument();
  2177. // The global field is gone — two controls for the same number would be ambiguous.
  2178. expect(screen.queryByLabelText(/^Quantity$/i)).not.toBeInTheDocument();
  2179. // Unselected plates have no control.
  2180. expect(screen.queryByRole('spinbutton', { name: /Plate 2/i })).not.toBeInTheDocument();
  2181. await user.click(screen.getByText('Plate 2'));
  2182. await waitFor(() => expect(qtyInput('Plate 2')).toBeInTheDocument());
  2183. });
  2184. it('keeps the single Quantity field for a single-plate file', async () => {
  2185. const queryClient = new QueryClient({
  2186. defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
  2187. });
  2188. queryClient.setQueryData(['archive-plates', 1], { is_multi_plate: false, plates: [] });
  2189. rtlRender(
  2190. <QueryClientProvider client={queryClient}>
  2191. <BrowserRouter>
  2192. <AuthProvider>
  2193. <ThemeProvider>
  2194. <ToastProvider>
  2195. <PrintModal mode="create" archiveId={1} archiveName="One.gcode.3mf" onClose={mockOnClose} />
  2196. </ToastProvider>
  2197. </ThemeProvider>
  2198. </AuthProvider>
  2199. </BrowserRouter>
  2200. </QueryClientProvider>,
  2201. );
  2202. await waitFor(() => expect(screen.getByLabelText(/^Quantity$/i)).toBeInTheDocument());
  2203. });
  2204. it('queues the reporter\'s example: plate 1 once, plate 2 twice, plate 3 three times', async () => {
  2205. type Queued = { plate_id: number | null; quantity?: number; batch_id?: number };
  2206. type OrderBody = { plates?: Array<{ plate_id: number | null; quantity_target: number }> };
  2207. const queued: Queued[] = [];
  2208. let order: OrderBody | null = null;
  2209. server.use(
  2210. http.post('/api/v1/queue/batches', async ({ request }) => {
  2211. order = (await request.json()) as OrderBody;
  2212. return HttpResponse.json({ id: 42, name: 'Order', status: 'active' });
  2213. }),
  2214. http.post('/api/v1/queue/', async ({ request }) => {
  2215. queued.push((await request.json()) as Queued);
  2216. return HttpResponse.json({ id: queued.length, status: 'pending' });
  2217. }),
  2218. );
  2219. const user = userEvent.setup();
  2220. renderModal(<PrintModal mode="create" archiveId={1} archiveName="Three.gcode.3mf" onClose={mockOnClose} />);
  2221. await waitFor(() => expect(screen.getByText('Plate 2')).toBeInTheDocument());
  2222. await user.click(screen.getByText('Plate 2'));
  2223. await user.click(screen.getByText('Plate 3'));
  2224. fireEvent.change(qtyInput('Plate 2'), { target: { value: '2' } });
  2225. fireEvent.change(qtyInput('Plate 3'), { target: { value: '3' } });
  2226. await waitFor(() => expect(screen.getByText(/6 runs in total/i)).toBeInTheDocument());
  2227. await user.click(screen.getAllByRole('button', { name: /X1 Carbon/i })[0]);
  2228. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  2229. await waitFor(() => expect(queued.length).toBe(3));
  2230. // The order records the intent, so a failed run still reads as owed.
  2231. expect(order!.plates).toEqual([
  2232. expect.objectContaining({ plate_id: 1, quantity_target: 1 }),
  2233. expect.objectContaining({ plate_id: 2, quantity_target: 2 }),
  2234. expect.objectContaining({ plate_id: 3, quantity_target: 3 }),
  2235. ]);
  2236. // ...and the runs are dispatched immediately, one call per plate carrying
  2237. // that plate's own count. Quantity 1 is left off the payload as before.
  2238. const byPlate = Object.fromEntries(queued.map((q) => [q.plate_id, q]));
  2239. expect(byPlate[1].quantity).toBeUndefined();
  2240. expect(byPlate[2].quantity).toBe(2);
  2241. expect(byPlate[3].quantity).toBe(3);
  2242. expect(queued.every((q) => q.batch_id === 42)).toBe(true);
  2243. });
  2244. it('does not multiply per-plate counts across a multi-printer fan-out', async () => {
  2245. type Queued = { plate_id: number | null; quantity?: number; printer_id: number | null };
  2246. const queued: Queued[] = [];
  2247. server.use(
  2248. http.post('/api/v1/queue/', async ({ request }) => {
  2249. queued.push((await request.json()) as Queued);
  2250. return HttpResponse.json({ id: queued.length, status: 'pending' });
  2251. }),
  2252. );
  2253. const user = userEvent.setup();
  2254. renderModal(<PrintModal mode="create" archiveId={1} archiveName="Three.gcode.3mf" onClose={mockOnClose} />);
  2255. await waitFor(() => expect(screen.getByText('Plate 2')).toBeInTheDocument());
  2256. await user.click(screen.getByText('Plate 2'));
  2257. fireEvent.change(qtyInput('Plate 2'), { target: { value: '4' } });
  2258. // Two printers: the printer count already answers "how many".
  2259. await user.click(screen.getAllByRole('button', { name: /X1 Carbon/i })[0]);
  2260. await user.click(screen.getAllByRole('button', { name: /P1S/i })[0]);
  2261. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  2262. await waitFor(() => expect(queued.length).toBe(4)); // 2 plates × 2 printers
  2263. expect(queued.every((q) => q.quantity === undefined)).toBe(true);
  2264. });
  2265. });
  2266. describe('PrintModal — override survives "Any model" -> "Specific Printer" (#3133)', () => {
  2267. const mockOnClose = vi.fn();
  2268. const PRINTERS = [
  2269. { id: 1, name: 'Printer 01', model: 'P2S', ip_address: '192.168.1.101', enabled: true, is_active: true },
  2270. { id: 2, name: 'Printer 02', model: 'X1C', ip_address: '192.168.1.102', enabled: true, is_active: true },
  2271. ];
  2272. const BROWN = '#8B4513';
  2273. const BONE_WHITE = '#F5F5DC';
  2274. // The 3MF was sliced in brown; the user asked for Bone White.
  2275. const SLOT_1_BROWN = { slot_id: 1, type: 'PLA', color: BROWN, tray_info_idx: 'GFA00', used_grams: 50 };
  2276. type Patched = {
  2277. printer_id?: number | null;
  2278. target_model?: string | null;
  2279. ams_mapping?: number[] | null;
  2280. filament_overrides?: Array<{ slot_id: number; type: string; color: string }> | null;
  2281. };
  2282. let patched: Patched[];
  2283. let posted: Patched[];
  2284. const statusWith = (trays: Array<{ id: number; tray_type: string; tray_color: string }>) =>
  2285. HttpResponse.json({ connected: true, state: 'IDLE', ams: [{ id: 0, tray: trays }], vt_tray: [] });
  2286. beforeEach(() => {
  2287. vi.clearAllMocks();
  2288. patched = [];
  2289. posted = [];
  2290. server.use(
  2291. http.get('/api/v1/printers/', () => HttpResponse.json(PRINTERS)),
  2292. http.get('/api/v1/archives/:id/plates', () => HttpResponse.json({ is_multi_plate: false, plates: [] })),
  2293. http.get('/api/v1/archives/:id/filament-requirements', () => HttpResponse.json({ filaments: [SLOT_1_BROWN] })),
  2294. http.get('/api/v1/printers/available-filaments', () =>
  2295. HttpResponse.json([
  2296. { type: 'PLA', color: BROWN, tray_info_idx: 'GFA00', tray_sub_brands: 'PLA Basic', extruder_id: null },
  2297. { type: 'PLA', color: BONE_WHITE, tray_info_idx: 'GFA00', tray_sub_brands: 'PLA Basic', extruder_id: null },
  2298. ]),
  2299. ),
  2300. // Printer 01 has both colours loaded; brown is first, so a match against
  2301. // the 3MF picks tray 0 and a match against the override picks tray 1.
  2302. http.get('/api/v1/printers/:id/status', () =>
  2303. statusWith([
  2304. { id: 0, tray_type: 'PLA', tray_color: '8B4513FF' },
  2305. { id: 1, tray_type: 'PLA', tray_color: 'F5F5DCFF' },
  2306. ]),
  2307. ),
  2308. http.get('/api/v1/printers/:id/assignments', () => HttpResponse.json([])),
  2309. http.patch('/api/v1/queue/:id', async ({ request }) => {
  2310. patched.push((await request.json()) as Patched);
  2311. return HttpResponse.json({ id: 1, status: 'pending' });
  2312. }),
  2313. http.post('/api/v1/queue/', async ({ request }) => {
  2314. posted.push((await request.json()) as Patched);
  2315. return HttpResponse.json({ id: 1, status: 'pending' });
  2316. }),
  2317. );
  2318. });
  2319. const anyP2SItem = () =>
  2320. createMockQueueItem({
  2321. printer_id: null,
  2322. target_model: 'P2S',
  2323. filament_overrides: [{ slot_id: 1, type: 'PLA', color: BONE_WHITE, force_color_match: false }],
  2324. } as Partial<PrintQueueItem>);
  2325. const moveToPrinter01 = async (user: ReturnType<typeof userEvent.setup>) => {
  2326. await user.click(await screen.findByRole('button', { name: /specific printer/i }));
  2327. await user.click(await screen.findByText('Printer 01'));
  2328. };
  2329. const submit = async (user: ReturnType<typeof userEvent.setup>) => {
  2330. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  2331. };
  2332. // The slot picker's list is portaled to <body>, outside the dialog's own
  2333. // DOM, and the dialog closes both on a click outside itself and on Escape.
  2334. // Either would be a bad regression: picking a slot, or dismissing the list,
  2335. // would throw away everything typed into the dialog (#3159).
  2336. it('does not close the dialog when a slot is picked from the portaled list', async () => {
  2337. const user = userEvent.setup();
  2338. render(<PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={anyP2SItem()} onClose={mockOnClose} />);
  2339. await moveToPrinter01(user);
  2340. // The panel is collapsed by default; the picker only exists once open.
  2341. await user.click(await screen.findByText(/filament mapping/i));
  2342. const trigger = await screen.findByRole('combobox', { name: /printer slot for/i });
  2343. await user.click(trigger);
  2344. const listbox = await screen.findByRole('listbox');
  2345. await user.click(within(listbox).getAllByRole('option')[1]);
  2346. expect(mockOnClose).not.toHaveBeenCalled();
  2347. expect(screen.getByText(/filament mapping/i)).toBeInTheDocument();
  2348. });
  2349. it('closes only the slot list on Escape, not the dialog', async () => {
  2350. const user = userEvent.setup();
  2351. render(<PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={anyP2SItem()} onClose={mockOnClose} />);
  2352. await moveToPrinter01(user);
  2353. await user.click(await screen.findByText(/filament mapping/i));
  2354. await user.click(await screen.findByRole('combobox', { name: /printer slot for/i }));
  2355. await screen.findByRole('listbox');
  2356. await user.keyboard('{Escape}');
  2357. await waitFor(() => expect(screen.queryByRole('listbox')).not.toBeInTheDocument());
  2358. expect(mockOnClose).not.toHaveBeenCalled();
  2359. // And a second Escape, with no list open, still closes the dialog — the
  2360. // picker must not have swallowed the key permanently.
  2361. await user.keyboard('{Escape}');
  2362. expect(mockOnClose).toHaveBeenCalled();
  2363. });
  2364. it('matches the chosen printer against the override and keeps it on the item', async () => {
  2365. const user = userEvent.setup();
  2366. render(<PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={anyP2SItem()} onClose={mockOnClose} />);
  2367. await moveToPrinter01(user);
  2368. // Wait for the mapping to settle on the printer's trays before saving.
  2369. await waitFor(() => expect(screen.getByText(/filament mapping/i)).toBeInTheDocument());
  2370. await submit(user);
  2371. await waitFor(() => expect(patched).toHaveLength(1));
  2372. expect(patched[0].printer_id).toBe(1);
  2373. expect(patched[0].target_model).toBeNull();
  2374. // Tray 1 is the Bone White spool. Matching the 3MF would have taken tray 0.
  2375. expect(patched[0].ams_mapping).toEqual([1]);
  2376. expect(patched[0].filament_overrides).toEqual([
  2377. expect.objectContaining({ slot_id: 1, type: 'PLA', color: BONE_WHITE }),
  2378. ]);
  2379. });
  2380. it('keeps the requested colour when the printer has no such spool', async () => {
  2381. server.use(
  2382. http.get('/api/v1/printers/:id/status', () =>
  2383. statusWith([
  2384. { id: 0, tray_type: 'PLA', tray_color: '8B4513FF' },
  2385. { id: 1, tray_type: 'PLA', tray_color: '000000FF' },
  2386. ]),
  2387. ),
  2388. );
  2389. const user = userEvent.setup();
  2390. render(<PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={anyP2SItem()} onClose={mockOnClose} />);
  2391. await moveToPrinter01(user);
  2392. await waitFor(() => expect(screen.getByText(/filament mapping/i)).toBeInTheDocument());
  2393. await submit(user);
  2394. await waitFor(() => expect(patched).toHaveLength(1));
  2395. // Still asked for, so the scheduler's recompute at dispatch looks for it too
  2396. // instead of settling on the brown the 3MF was sliced with.
  2397. expect(patched[0].filament_overrides).toEqual([
  2398. expect.objectContaining({ slot_id: 1, color: BONE_WHITE }),
  2399. ]);
  2400. });
  2401. it('still drops the override when the job moves to a different model', async () => {
  2402. const user = userEvent.setup();
  2403. render(<PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={anyP2SItem()} onClose={mockOnClose} />);
  2404. const modelSelect = await waitFor(() => {
  2405. const select = screen
  2406. .getAllByRole('combobox')
  2407. .find((el) => (el as HTMLSelectElement).options[0]?.text === 'Select a model...');
  2408. if (!select) throw new Error('target model select not rendered');
  2409. return select as HTMLSelectElement;
  2410. });
  2411. // The override was picked from P2S's loaded filaments; X1C's are another list.
  2412. await user.selectOptions(modelSelect, 'X1C');
  2413. await submit(user);
  2414. await waitFor(() => expect(patched).toHaveLength(1));
  2415. expect(patched[0].target_model).toBe('X1C');
  2416. expect(patched[0].filament_overrides ?? null).toBeNull();
  2417. });
  2418. it("keeps a virtual printer's variant pin when its specific-printer job is saved", async () => {
  2419. // A VP with force colour on writes the 3MF's own filament back as an
  2420. // override, tray_info_idx included, to tell PLA variants apart (#2650). Two
  2421. // brown trays differ only by variant; the job was sliced for Matte (GFA01).
  2422. server.use(
  2423. http.get('/api/v1/archives/:id/filament-requirements', () =>
  2424. HttpResponse.json({ filaments: [{ ...SLOT_1_BROWN, tray_info_idx: 'GFA01' }] }),
  2425. ),
  2426. http.get('/api/v1/printers/:id/status', () =>
  2427. HttpResponse.json({
  2428. connected: true,
  2429. state: 'IDLE',
  2430. ams: [{ id: 0, tray: [
  2431. { id: 0, tray_type: 'PLA', tray_color: '8B4513FF', tray_info_idx: 'GFA00' },
  2432. { id: 1, tray_type: 'PLA', tray_color: '8B4513FF', tray_info_idx: 'GFA01' },
  2433. ] }],
  2434. vt_tray: [],
  2435. }),
  2436. ),
  2437. );
  2438. const vpItem = createMockQueueItem({
  2439. printer_id: 1,
  2440. target_model: null,
  2441. filament_overrides: [
  2442. { slot_id: 1, type: 'PLA', color: BROWN, tray_info_idx: 'GFA01', force_color_match: true },
  2443. ],
  2444. } as Partial<PrintQueueItem>);
  2445. const user = userEvent.setup();
  2446. render(<PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={vpItem} onClose={mockOnClose} />);
  2447. await waitFor(() => expect(screen.getByText(/filament mapping/i)).toBeInTheDocument());
  2448. await submit(user);
  2449. await waitFor(() => expect(patched).toHaveLength(1));
  2450. // Not treated as a swap: the matcher still pins the Matte tray...
  2451. expect(patched[0].ams_mapping).toEqual([1]);
  2452. // ...and the row keeps the pin rather than losing it on save.
  2453. expect(patched[0].filament_overrides).toEqual([
  2454. expect.objectContaining({ slot_id: 1, color: BROWN, tray_info_idx: 'GFA01', force_color_match: true }),
  2455. ]);
  2456. });
  2457. it("keeps a virtual printer's variant pin when its any-model job is saved", async () => {
  2458. const vpItem = createMockQueueItem({
  2459. printer_id: null,
  2460. target_model: 'P2S',
  2461. filament_overrides: [
  2462. { slot_id: 1, type: 'PLA', color: BROWN, tray_info_idx: 'GFA01', force_color_match: true },
  2463. ],
  2464. } as Partial<PrintQueueItem>);
  2465. const user = userEvent.setup();
  2466. render(<PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={vpItem} onClose={mockOnClose} />);
  2467. await waitFor(() => expect(screen.getByText('Filament Override')).toBeInTheDocument());
  2468. await submit(user);
  2469. await waitFor(() => expect(patched).toHaveLength(1));
  2470. expect(patched[0].target_model).toBe('P2S');
  2471. expect(patched[0].filament_overrides).toEqual([
  2472. expect.objectContaining({ slot_id: 1, tray_info_idx: 'GFA01', force_color_match: true }),
  2473. ]);
  2474. });
  2475. it("names a kept pin's colour within its product line when the file's filaments can't be read", async () => {
  2476. const hex = BROWN.replace('#', '').toLowerCase();
  2477. setColorCatalog({ [hex]: 'Brown' }, { [`PLA Matte|${hex}`]: 'Matte Brown' });
  2478. server.use(
  2479. http.get('/api/v1/archives/:id/filament-requirements', () => HttpResponse.json({ detail: 'gone' }, { status: 500 })),
  2480. );
  2481. const vpItem = createMockQueueItem({
  2482. printer_id: null,
  2483. target_model: 'P2S',
  2484. filament_overrides: [
  2485. { slot_id: 1, type: 'PLA', color: BROWN, tray_info_idx: 'GFA01', force_color_match: true },
  2486. ],
  2487. } as Partial<PrintQueueItem>);
  2488. // The preset names are known from the first render, so the save can't race them.
  2489. const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
  2490. queryClient.setQueryData(['builtin-filaments'], [{ filament_id: 'GFA01', name: 'Bambu PLA Matte' }]);
  2491. queryClient.setQueryData(['filament-id-map'], {});
  2492. try {
  2493. const user = userEvent.setup();
  2494. rtlRender(
  2495. <QueryClientProvider client={queryClient}>
  2496. <BrowserRouter>
  2497. <AuthProvider>
  2498. <ThemeProvider>
  2499. <ToastProvider>
  2500. <PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={vpItem} onClose={mockOnClose} />
  2501. </ToastProvider>
  2502. </ThemeProvider>
  2503. </AuthProvider>
  2504. </BrowserRouter>
  2505. </QueryClientProvider>,
  2506. );
  2507. await submit(user);
  2508. await waitFor(() => expect(patched).toHaveLength(1));
  2509. expect(patched[0].filament_overrides).toEqual([
  2510. expect.objectContaining({ slot_id: 1, tray_info_idx: 'GFA01', color_name: 'Matte Brown' }),
  2511. ]);
  2512. } finally {
  2513. __resetColorCatalogForTests();
  2514. }
  2515. });
  2516. it('carries an override picked in model mode into a specific-printer job when creating', async () => {
  2517. const user = userEvent.setup();
  2518. render(<PrintModal mode="create" archiveId={1} archiveName="Job" onClose={mockOnClose} />);
  2519. await user.click(await screen.findByRole('button', { name: /any model/i }));
  2520. const modelSelect = await waitFor(() => {
  2521. const select = screen
  2522. .getAllByRole('combobox')
  2523. .find((el) => (el as HTMLSelectElement).options[0]?.text === 'Select a model...');
  2524. if (!select) throw new Error('target model select not rendered');
  2525. return select as HTMLSelectElement;
  2526. });
  2527. await user.selectOptions(modelSelect, 'P2S');
  2528. // Matched on the hex the row now prints (#3159) rather than on the option
  2529. // value, so the assertion names the colour the user is actually picking.
  2530. await pickFromSlotPicker(
  2531. user,
  2532. /filament override for/i,
  2533. new RegExp(BONE_WHITE.toUpperCase().replace('#', '#?')),
  2534. );
  2535. await moveToPrinter01(user);
  2536. await waitFor(() => expect(screen.getByText(/filament mapping/i)).toBeInTheDocument());
  2537. await submit(user);
  2538. await waitFor(() => expect(posted).toHaveLength(1));
  2539. expect(posted[0].printer_id).toBe(1);
  2540. expect(posted[0].ams_mapping).toEqual([1]);
  2541. expect(posted[0].filament_overrides).toEqual([
  2542. expect.objectContaining({ slot_id: 1, type: 'PLA', color: BONE_WHITE }),
  2543. ]);
  2544. });
  2545. });
  2546. describe('PrintModal — a deliberate material substitution is acknowledged (#2799)', () => {
  2547. // The scheduler re-checks a stored mapping against the printer before
  2548. // dispatch, and a slot on a tray of another material is what a mapping meant
  2549. // for a different printer looks like. A user who picks such a tray by hand
  2550. // means it, so the dialog sends skip_filament_check, which the re-check
  2551. // honours.
  2552. const mockOnClose = vi.fn();
  2553. const PRINTERS = [
  2554. { id: 1, name: 'Printer 01', model: 'P2S', ip_address: '192.168.1.101', enabled: true, is_active: true },
  2555. ];
  2556. type Patched = { ams_mapping?: number[] | null; skip_filament_check?: boolean };
  2557. let patched: Patched[];
  2558. beforeEach(() => {
  2559. vi.clearAllMocks();
  2560. patched = [];
  2561. server.use(
  2562. http.get('/api/v1/printers/', () => HttpResponse.json(PRINTERS)),
  2563. http.get('/api/v1/archives/:id/plates', () => HttpResponse.json({ is_multi_plate: false, plates: [] })),
  2564. http.get('/api/v1/archives/:id/filament-requirements', () =>
  2565. HttpResponse.json({ filaments: [{ slot_id: 1, type: 'PLA', color: '#8B4513', tray_info_idx: '', used_grams: 50 }] }),
  2566. ),
  2567. // Tray 0 holds the PLA the plate asks for, tray 1 a PETG.
  2568. http.get('/api/v1/printers/:id/status', () =>
  2569. HttpResponse.json({
  2570. connected: true,
  2571. state: 'IDLE',
  2572. ams: [
  2573. {
  2574. id: 0,
  2575. tray: [
  2576. { id: 0, tray_type: 'PLA', tray_color: '8B4513FF' },
  2577. { id: 1, tray_type: 'PETG', tray_color: 'FFFFFFFF' },
  2578. ],
  2579. },
  2580. ],
  2581. vt_tray: [],
  2582. }),
  2583. ),
  2584. http.get('/api/v1/printers/:id/assignments', () => HttpResponse.json([])),
  2585. http.patch('/api/v1/queue/:id', async ({ request }) => {
  2586. patched.push((await request.json()) as Patched);
  2587. return HttpResponse.json({ id: 1, status: 'pending' });
  2588. }),
  2589. );
  2590. });
  2591. const pinnedItem = () => createMockQueueItem({ printer_id: 1, target_model: null } as Partial<PrintQueueItem>);
  2592. const pickTrayAndSave = async (option: number) => {
  2593. const user = userEvent.setup();
  2594. render(<PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={pinnedItem()} onClose={mockOnClose} />);
  2595. await user.click(await screen.findByText(/filament mapping/i));
  2596. await user.click(await screen.findByRole('combobox', { name: /printer slot for/i }));
  2597. const listbox = await screen.findByRole('listbox');
  2598. await user.click(within(listbox).getAllByRole('option')[option]);
  2599. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  2600. await waitFor(() => expect(patched).toHaveLength(1));
  2601. return patched[0];
  2602. };
  2603. it('sends skip_filament_check when a slot is put on a tray of another material', async () => {
  2604. // Option 0 is the empty '-- Select slot --'; 1 is the PLA tray, 2 the PETG.
  2605. const saved = await pickTrayAndSave(2);
  2606. expect(saved.ams_mapping).toEqual([1]);
  2607. expect(saved.skip_filament_check).toBe(true);
  2608. });
  2609. it('does not treat a stored mapping the dialog opened with as a pick made here', async () => {
  2610. // A job queued before the dispatch re-check existed can carry a mapping
  2611. // made for another printer. Saving an unrelated edit must not enshrine it.
  2612. const user = userEvent.setup();
  2613. const item = createMockQueueItem({ printer_id: 1, target_model: null, ams_mapping: [1] } as Partial<PrintQueueItem>);
  2614. render(<PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={item} onClose={mockOnClose} />);
  2615. await waitFor(() => expect(screen.getByText(/filament mapping/i)).toBeInTheDocument());
  2616. await user.click(document.querySelector('button[type="submit"]') as HTMLElement);
  2617. await waitFor(() => expect(patched).toHaveLength(1));
  2618. expect(patched[0].ams_mapping).toEqual([1]);
  2619. expect(patched[0].skip_filament_check).toBeUndefined();
  2620. });
  2621. it('sends nothing extra when the picked tray holds the material asked for', async () => {
  2622. const saved = await pickTrayAndSave(1);
  2623. expect(saved.ams_mapping).toEqual([0]);
  2624. expect(saved.skip_filament_check).toBeUndefined();
  2625. });
  2626. });
  2627. describe('PrintModal edit: moving a job to another printer', () => {
  2628. const mockOnClose = vi.fn();
  2629. let patched: Record<string, unknown>[];
  2630. beforeEach(() => {
  2631. vi.clearAllMocks();
  2632. patched = [];
  2633. server.use(
  2634. http.get('/api/v1/printers/', () =>
  2635. HttpResponse.json([
  2636. { id: 1, name: 'Printer 01', model: 'H2C', ip_address: '192.168.1.101', enabled: true, is_active: true },
  2637. { id: 2, name: 'Printer 02', model: 'H2C', ip_address: '192.168.1.102', enabled: true, is_active: true },
  2638. ]),
  2639. ),
  2640. http.get('/api/v1/archives/:id/plates', () => HttpResponse.json({ is_multi_plate: false, plates: [] })),
  2641. http.get('/api/v1/printers/:id/status', () =>
  2642. HttpResponse.json({ connected: true, state: 'IDLE', ams: [], vt_tray: [] }),
  2643. ),
  2644. http.patch('/api/v1/queue/:id', async ({ request }) => {
  2645. patched.push((await request.json()) as Record<string, unknown>);
  2646. return HttpResponse.json({ id: 1, status: 'pending' });
  2647. }),
  2648. );
  2649. });
  2650. it("does not carry the old printer's nozzle rack picks over", async () => {
  2651. const user = userEvent.setup();
  2652. const item = createMockQueueItem({
  2653. printer_id: 1,
  2654. target_model: null,
  2655. nozzle_rack_choice: { 0: 3 },
  2656. } as Partial<PrintQueueItem>);
  2657. render(<PrintModal mode="edit-queue-item" archiveId={1} archiveName="Job" queueItem={item} onClose={mockOnClose} />);
  2658. // The dialog adds printers; moving the job is deselecting one, selecting the other.
  2659. await user.click(await screen.findByText('Printer 01'));
  2660. await user.click(screen.getByText('Printer 02'));
  2661. await user.click(screen.getByRole('button', { name: /save/i }));
  2662. await waitFor(() => expect(patched).toHaveLength(1));
  2663. expect(patched[0].printer_id).toBe(2);
  2664. expect(patched[0].nozzle_rack_choice).toBeNull();
  2665. });
  2666. });
  2667. describe('PrintModal default printer', () => {
  2668. beforeEach(() => {
  2669. vi.clearAllMocks();
  2670. server.use(
  2671. http.get('/api/v1/printers/', () => HttpResponse.json(mockPrinters)),
  2672. http.get('/api/v1/settings/', () => HttpResponse.json({ default_printer_id: 2, currency: 'USD' })),
  2673. http.get('/api/v1/archives/:id/plates', () => HttpResponse.json({ is_multi_plate: false, plates: [] })),
  2674. http.get('/api/v1/archives/:id/filament-requirements', () => HttpResponse.json({ filaments: [] })),
  2675. http.get('/api/v1/printers/:id/status', () =>
  2676. HttpResponse.json({ connected: true, state: 'IDLE', ams: [], vt_tray: [] }),
  2677. ),
  2678. );
  2679. });
  2680. it('preselects the default printer from Settings', async () => {
  2681. render(<PrintModal mode="create" archiveId={1} archiveName="Test Print" onClose={vi.fn()} />);
  2682. expect(await screen.findByText('1 printer selected')).toBeInTheDocument();
  2683. });
  2684. it('does not bring the default back once it was deselected', async () => {
  2685. const user = userEvent.setup();
  2686. render(<PrintModal mode="create" archiveId={1} archiveName="Test Print" onClose={vi.fn()} />);
  2687. await screen.findByText('1 printer selected');
  2688. await user.click(screen.getByText('P1S'));
  2689. await new Promise((resolve) => setTimeout(resolve, 100));
  2690. expect(screen.queryByText('1 printer selected')).not.toBeInTheDocument();
  2691. });
  2692. it('does not select a default printer of another model than the file was sliced for', async () => {
  2693. server.use(
  2694. http.get('/api/v1/archives/:id', async () => {
  2695. // Later than printers and settings: the model must be waited for.
  2696. await new Promise((resolve) => setTimeout(resolve, 50));
  2697. return HttpResponse.json({ id: 1, filename: 'test.3mf', sliced_for_model: 'X1C' });
  2698. }),
  2699. );
  2700. const user = userEvent.setup();
  2701. render(<PrintModal mode="create" archiveId={1} archiveName="Test Print" onClose={vi.fn()} />);
  2702. // The P1S is hidden behind "show all" as another model than X1C.
  2703. await user.click(await screen.findByText('show all'));
  2704. await new Promise((resolve) => setTimeout(resolve, 200));
  2705. expect(screen.getByText('P1S').closest('button')).not.toHaveClass('border-bambu-green');
  2706. });
  2707. });