test_print_queue_api.py 146 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791
  1. """Integration tests for Print Queue API endpoints."""
  2. import pytest
  3. from httpx import AsyncClient
  4. from sqlalchemy import select
  5. from backend.app.models.finance import CostCenter
  6. from backend.app.models.settings import Settings
  7. async def enable_billing(db_session):
  8. setting = await db_session.scalar(select(Settings).where(Settings.key == "billing_enabled"))
  9. if setting is None:
  10. db_session.add(Settings(key="billing_enabled", value="true"))
  11. else:
  12. setting.value = "true"
  13. await db_session.commit()
  14. class TestPrintQueueAPI:
  15. """Integration tests for /api/v1/queue endpoints."""
  16. @pytest.fixture
  17. async def printer_factory(self, db_session):
  18. """Factory to create test printers."""
  19. _counter = [0]
  20. async def _create_printer(**kwargs):
  21. from backend.app.models.printer import Printer
  22. _counter[0] += 1
  23. counter = _counter[0]
  24. defaults = {
  25. "name": f"Test Printer {counter}",
  26. "ip_address": f"192.168.1.{100 + counter}",
  27. "serial_number": f"TESTSERIAL{counter:04d}",
  28. "access_code": "12345678",
  29. "model": "X1C",
  30. }
  31. defaults.update(kwargs)
  32. printer = Printer(**defaults)
  33. db_session.add(printer)
  34. await db_session.commit()
  35. await db_session.refresh(printer)
  36. return printer
  37. return _create_printer
  38. @pytest.fixture
  39. async def archive_factory(self, db_session):
  40. """Factory to create test archives."""
  41. _counter = [0]
  42. async def _create_archive(**kwargs):
  43. from backend.app.models.archive import PrintArchive
  44. _counter[0] += 1
  45. counter = _counter[0]
  46. defaults = {
  47. "filename": f"test_print_{counter}.3mf",
  48. "print_name": f"Test Print {counter}",
  49. "file_path": f"/tmp/test_print_{counter}.3mf",
  50. "file_size": 1024,
  51. "content_hash": f"testhash{counter:08d}",
  52. "status": "completed",
  53. }
  54. defaults.update(kwargs)
  55. archive = PrintArchive(**defaults)
  56. db_session.add(archive)
  57. await db_session.commit()
  58. await db_session.refresh(archive)
  59. return archive
  60. return _create_archive
  61. @pytest.fixture
  62. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  63. """Factory to create test queue items."""
  64. _counter = [0]
  65. async def _create_queue_item(**kwargs):
  66. from backend.app.models.print_queue import PrintQueueItem
  67. _counter[0] += 1
  68. counter = _counter[0]
  69. # Create printer and archive if not provided
  70. if "printer_id" not in kwargs:
  71. printer = await printer_factory()
  72. kwargs["printer_id"] = printer.id
  73. if "archive_id" not in kwargs:
  74. archive = await archive_factory()
  75. kwargs["archive_id"] = archive.id
  76. defaults = {
  77. "status": "pending",
  78. "position": counter,
  79. }
  80. defaults.update(kwargs)
  81. item = PrintQueueItem(**defaults)
  82. db_session.add(item)
  83. await db_session.commit()
  84. await db_session.refresh(item)
  85. return item
  86. return _create_queue_item
  87. @pytest.mark.asyncio
  88. @pytest.mark.integration
  89. async def test_list_queue_empty(self, async_client: AsyncClient):
  90. """Verify empty list when no queue items exist."""
  91. response = await async_client.get("/api/v1/queue/")
  92. assert response.status_code == 200
  93. assert isinstance(response.json(), list)
  94. @pytest.mark.asyncio
  95. @pytest.mark.integration
  96. async def test_add_to_queue(self, async_client: AsyncClient, printer_factory, archive_factory, db_session):
  97. """Verify item can be added to queue."""
  98. printer = await printer_factory()
  99. archive = await archive_factory()
  100. data = {
  101. "printer_id": printer.id,
  102. "archive_id": archive.id,
  103. }
  104. response = await async_client.post("/api/v1/queue/", json=data)
  105. assert response.status_code == 200
  106. result = response.json()
  107. assert result["printer_id"] == printer.id
  108. assert result["archive_id"] == archive.id
  109. assert result["status"] == "pending"
  110. assert result["manual_start"] is False
  111. @pytest.mark.asyncio
  112. @pytest.mark.integration
  113. async def test_add_to_queue_with_cost_center_id(
  114. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  115. ):
  116. """Verify item can be added to queue with cost_center_id."""
  117. await enable_billing(db_session)
  118. printer = await printer_factory()
  119. archive = await archive_factory()
  120. cost_center = CostCenter(name="Queue CC", is_active=True, is_private=False)
  121. db_session.add(cost_center)
  122. await db_session.commit()
  123. await db_session.refresh(cost_center)
  124. response = await async_client.post(
  125. "/api/v1/queue/",
  126. json={
  127. "printer_id": printer.id,
  128. "archive_id": archive.id,
  129. "cost_center_id": cost_center.id,
  130. "estimated_cost": 1.25,
  131. },
  132. )
  133. assert response.status_code == 200
  134. result = response.json()
  135. assert result["cost_center_id"] == cost_center.id
  136. assert result["estimated_cost"] == 1.25
  137. from backend.app.models.print_queue import PrintQueueItem
  138. row = await db_session.scalar(select(PrintQueueItem).where(PrintQueueItem.id == result["id"]))
  139. assert row is not None
  140. assert row.cost_center_id == cost_center.id
  141. assert row.estimated_cost == 1.25
  142. @pytest.mark.asyncio
  143. @pytest.mark.integration
  144. async def test_add_to_queue_with_cost_center_requires_estimated_cost(
  145. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  146. ):
  147. """Cost-center queue items require an estimated cost for budget checks."""
  148. await enable_billing(db_session)
  149. printer = await printer_factory()
  150. archive = await archive_factory()
  151. cost_center = CostCenter(name="Budget CC", is_active=True, is_private=False, monthly_budget=10.0)
  152. db_session.add(cost_center)
  153. await db_session.commit()
  154. await db_session.refresh(cost_center)
  155. response = await async_client.post(
  156. "/api/v1/queue/",
  157. json={
  158. "printer_id": printer.id,
  159. "archive_id": archive.id,
  160. "cost_center_id": cost_center.id,
  161. },
  162. )
  163. assert response.status_code == 400
  164. assert "Estimated cost is required" in response.json()["detail"]
  165. @pytest.mark.asyncio
  166. @pytest.mark.integration
  167. async def test_add_to_queue_rejects_when_estimated_cost_exceeds_budget(
  168. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  169. ):
  170. """Queue creation is rejected if the estimated cost exceeds remaining budget."""
  171. await enable_billing(db_session)
  172. printer = await printer_factory()
  173. archive = await archive_factory()
  174. cost_center = CostCenter(name="Tiny Budget CC", is_active=True, is_private=False, monthly_budget=1.0)
  175. db_session.add(cost_center)
  176. await db_session.commit()
  177. await db_session.refresh(cost_center)
  178. response = await async_client.post(
  179. "/api/v1/queue/",
  180. json={
  181. "printer_id": printer.id,
  182. "archive_id": archive.id,
  183. "cost_center_id": cost_center.id,
  184. "estimated_cost": 2.0,
  185. },
  186. )
  187. assert response.status_code == 400
  188. assert "exceeds available cost center budget" in response.json()["detail"]
  189. @pytest.mark.asyncio
  190. @pytest.mark.integration
  191. async def test_add_to_queue_requires_cost_center_when_billing_enabled(
  192. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  193. ):
  194. """Billing enforcement rejects queue jobs that omit cost center."""
  195. await enable_billing(db_session)
  196. printer = await printer_factory()
  197. archive = await archive_factory()
  198. response = await async_client.post(
  199. "/api/v1/queue/",
  200. json={
  201. "printer_id": printer.id,
  202. "archive_id": archive.id,
  203. },
  204. )
  205. assert response.status_code == 400
  206. assert "Cost center is required" in response.json()["detail"]
  207. @pytest.mark.asyncio
  208. @pytest.mark.integration
  209. async def test_add_to_queue_counts_pending_queue_reservations_against_budget(
  210. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory, db_session
  211. ):
  212. """Open queue items reserve budget until they leave pending/printing states."""
  213. await enable_billing(db_session)
  214. printer = await printer_factory()
  215. archive = await archive_factory()
  216. cost_center = CostCenter(name="Reserved Budget CC", is_active=True, is_private=False, monthly_budget=10.0)
  217. db_session.add(cost_center)
  218. await db_session.commit()
  219. await db_session.refresh(cost_center)
  220. await queue_item_factory(
  221. printer_id=printer.id,
  222. archive_id=archive.id,
  223. cost_center_id=cost_center.id,
  224. estimated_cost=8.0,
  225. status="pending",
  226. )
  227. response = await async_client.post(
  228. "/api/v1/queue/",
  229. json={
  230. "printer_id": printer.id,
  231. "archive_id": archive.id,
  232. "cost_center_id": cost_center.id,
  233. "estimated_cost": 3.0,
  234. },
  235. )
  236. assert response.status_code == 400
  237. assert "exceeds available cost center budget" in response.json()["detail"]
  238. @pytest.mark.asyncio
  239. @pytest.mark.integration
  240. async def test_add_to_queue_with_manual_start(
  241. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  242. ):
  243. """Verify item can be added to queue with manual_start=True."""
  244. printer = await printer_factory()
  245. archive = await archive_factory()
  246. data = {
  247. "printer_id": printer.id,
  248. "archive_id": archive.id,
  249. "manual_start": True,
  250. }
  251. response = await async_client.post("/api/v1/queue/", json=data)
  252. assert response.status_code == 200
  253. result = response.json()
  254. assert result["printer_id"] == printer.id
  255. assert result["archive_id"] == archive.id
  256. assert result["status"] == "pending"
  257. assert result["manual_start"] is True
  258. @pytest.mark.asyncio
  259. @pytest.mark.integration
  260. async def test_add_to_queue_with_skip_filament_check(
  261. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  262. ):
  263. """PrintModal "Print Anyway" persists skip_filament_check on creation (#1698-followup)."""
  264. printer = await printer_factory()
  265. archive = await archive_factory()
  266. data = {
  267. "printer_id": printer.id,
  268. "archive_id": archive.id,
  269. "skip_filament_check": True,
  270. }
  271. response = await async_client.post("/api/v1/queue/", json=data)
  272. assert response.status_code == 200
  273. result = response.json()
  274. assert result["skip_filament_check"] is True
  275. @pytest.mark.asyncio
  276. @pytest.mark.integration
  277. async def test_add_to_queue_skip_filament_check_defaults_false(
  278. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  279. ):
  280. """Default add-to-queue has skip_filament_check=False — no silent bypass."""
  281. printer = await printer_factory()
  282. archive = await archive_factory()
  283. data = {"printer_id": printer.id, "archive_id": archive.id}
  284. response = await async_client.post("/api/v1/queue/", json=data)
  285. assert response.status_code == 200
  286. result = response.json()
  287. assert result["skip_filament_check"] is False
  288. @pytest.mark.asyncio
  289. @pytest.mark.integration
  290. async def test_update_queue_item_cost_center_id(
  291. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory, db_session
  292. ):
  293. """Verify a pending queue item can be updated with cost_center_id."""
  294. await enable_billing(db_session)
  295. printer = await printer_factory()
  296. archive = await archive_factory()
  297. item = await queue_item_factory(printer_id=printer.id, archive_id=archive.id)
  298. cost_center = CostCenter(name="Update CC", is_active=True, is_private=False)
  299. db_session.add(cost_center)
  300. await db_session.commit()
  301. await db_session.refresh(cost_center)
  302. response = await async_client.patch(
  303. f"/api/v1/queue/{item.id}",
  304. json={"cost_center_id": cost_center.id, "estimated_cost": 1.25},
  305. )
  306. assert response.status_code == 200
  307. assert response.json()["cost_center_id"] == cost_center.id
  308. assert response.json()["estimated_cost"] == 1.25
  309. @pytest.mark.asyncio
  310. @pytest.mark.integration
  311. async def test_add_to_queue_with_project_id(
  312. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  313. ):
  314. """#932: queue items created from the project view carry project_id forward."""
  315. from backend.app.models.project import Project
  316. printer = await printer_factory()
  317. archive = await archive_factory()
  318. project = Project(name="Queue Project")
  319. db_session.add(project)
  320. await db_session.commit()
  321. await db_session.refresh(project)
  322. data = {
  323. "printer_id": printer.id,
  324. "archive_id": archive.id,
  325. "project_id": project.id,
  326. }
  327. response = await async_client.post("/api/v1/queue/", json=data)
  328. assert response.status_code == 200
  329. result = response.json()
  330. # The response schema may or may not echo project_id; the stored row is
  331. # what matters, so verify via DB.
  332. from sqlalchemy import select
  333. from backend.app.models.print_queue import PrintQueueItem
  334. row = (await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id == result["id"]))).scalar_one()
  335. assert row.project_id == project.id
  336. @pytest.mark.asyncio
  337. @pytest.mark.integration
  338. async def test_add_to_queue_invalid_project_id_returns_404(
  339. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  340. ):
  341. """#932: bogus project_id must be rejected before the FK constraint fires.
  342. Regression guard for the pre-check added to add_to_queue. Without the
  343. validation, a nonexistent project_id would reach db.commit() and raise
  344. an IntegrityError → 500. The pre-check must convert that to a 404 so
  345. the UI gets a clean error it can surface.
  346. """
  347. printer = await printer_factory()
  348. archive = await archive_factory()
  349. data = {
  350. "printer_id": printer.id,
  351. "archive_id": archive.id,
  352. "project_id": 999999, # nonexistent
  353. }
  354. response = await async_client.post("/api/v1/queue/", json=data)
  355. assert response.status_code == 404
  356. assert "project" in response.json()["detail"].lower()
  357. @pytest.mark.asyncio
  358. @pytest.mark.integration
  359. async def test_add_to_queue_with_ams_mapping(
  360. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  361. ):
  362. """Verify item can be added to queue with ams_mapping."""
  363. printer = await printer_factory()
  364. archive = await archive_factory()
  365. data = {
  366. "printer_id": printer.id,
  367. "archive_id": archive.id,
  368. "ams_mapping": [5, -1, 2, -1], # Slot 1 -> tray 5, slot 3 -> tray 2
  369. }
  370. response = await async_client.post("/api/v1/queue/", json=data)
  371. assert response.status_code == 200
  372. result = response.json()
  373. assert result["printer_id"] == printer.id
  374. assert result["archive_id"] == archive.id
  375. assert result["ams_mapping"] == [5, -1, 2, -1]
  376. @pytest.mark.asyncio
  377. @pytest.mark.integration
  378. async def test_add_to_queue_falls_back_to_archive_slicer_ams_mapping_when_unset(
  379. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  380. ):
  381. """When the caller sends no explicit ams_mapping, but the archive
  382. carries the slicer's own saved pick for this exact printer
  383. (extra_data.slicer_ams_mapping, written by a VP with "Save AMS
  384. mapping" on), the queue item should inherit it — the same
  385. exact-physical-spool reuse the "Mapping" button gives you, but
  386. automatic when nothing was hand-edited.
  387. """
  388. printer = await printer_factory()
  389. archive = await archive_factory(
  390. extra_data={"slicer_ams_mapping": {"mapping": [5, -1, 2, -1], "printer_id": printer.id}}
  391. )
  392. data = {
  393. "printer_id": printer.id,
  394. "archive_id": archive.id,
  395. }
  396. response = await async_client.post("/api/v1/queue/", json=data)
  397. assert response.status_code == 200
  398. result = response.json()
  399. assert result["ams_mapping"] == [5, -1, 2, -1]
  400. @pytest.mark.asyncio
  401. @pytest.mark.integration
  402. async def test_add_to_queue_ignores_archive_slicer_ams_mapping_for_different_printer(
  403. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  404. ):
  405. """A saved mapping's tray IDs only mean something relative to the
  406. printer they were resolved against. Reprinting the same archive on a
  407. *different* printer must not inherit it — tray 5 on printer A can
  408. hold a completely different spool than tray 5 on printer B.
  409. """
  410. origin_printer = await printer_factory()
  411. other_printer = await printer_factory()
  412. archive = await archive_factory(
  413. extra_data={"slicer_ams_mapping": {"mapping": [5, -1, 2, -1], "printer_id": origin_printer.id}}
  414. )
  415. data = {
  416. "printer_id": other_printer.id,
  417. "archive_id": archive.id,
  418. }
  419. response = await async_client.post("/api/v1/queue/", json=data)
  420. assert response.status_code == 200
  421. result = response.json()
  422. assert result["ams_mapping"] is None
  423. @pytest.mark.asyncio
  424. @pytest.mark.integration
  425. async def test_add_to_queue_ignores_archive_slicer_ams_mapping_for_model_based_dispatch(
  426. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  427. ):
  428. """A model-based item (no fixed printer_id) can't know in advance
  429. which printer the scheduler will pick, so a saved mapping resolved
  430. against one specific printer must never be inherited here either.
  431. """
  432. origin_printer = await printer_factory()
  433. archive = await archive_factory(
  434. extra_data={"slicer_ams_mapping": {"mapping": [5, -1, 2, -1], "printer_id": origin_printer.id}}
  435. )
  436. data = {
  437. "target_model": "X1C",
  438. "archive_id": archive.id,
  439. }
  440. response = await async_client.post("/api/v1/queue/", json=data)
  441. assert response.status_code == 200
  442. result = response.json()
  443. assert result["ams_mapping"] is None
  444. @pytest.mark.asyncio
  445. @pytest.mark.integration
  446. async def test_add_to_queue_explicit_ams_mapping_wins_over_archive_fallback(
  447. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  448. ):
  449. """An explicit ams_mapping in the request (e.g. from the filament
  450. mapping panel) must take priority over the archive's saved slicer
  451. pick — the fallback only fires when the caller sent nothing at all.
  452. """
  453. printer = await printer_factory()
  454. archive = await archive_factory(
  455. extra_data={"slicer_ams_mapping": {"mapping": [5, -1, 2, -1], "printer_id": printer.id}}
  456. )
  457. data = {
  458. "printer_id": printer.id,
  459. "archive_id": archive.id,
  460. "ams_mapping": [9, -1, 1, -1],
  461. }
  462. response = await async_client.post("/api/v1/queue/", json=data)
  463. assert response.status_code == 200
  464. result = response.json()
  465. assert result["ams_mapping"] == [9, -1, 1, -1]
  466. @pytest.mark.asyncio
  467. @pytest.mark.integration
  468. async def test_add_to_queue_archive_extra_data_without_slicer_mapping_key_not_used(
  469. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  470. ):
  471. """extra_data present but without a slicer_ams_mapping key (the
  472. common case — most archives have other metadata but no saved slicer
  473. mapping) must not accidentally trip the fallback."""
  474. printer = await printer_factory()
  475. archive = await archive_factory(extra_data={"filament_slots": []})
  476. data = {
  477. "printer_id": printer.id,
  478. "archive_id": archive.id,
  479. }
  480. response = await async_client.post("/api/v1/queue/", json=data)
  481. assert response.status_code == 200
  482. result = response.json()
  483. assert result["ams_mapping"] is None
  484. @pytest.mark.asyncio
  485. @pytest.mark.integration
  486. async def test_add_to_queue_force_color_match_overrides_beat_the_archive_fallback(
  487. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  488. ):
  489. """Force-color-match overrides are the caller asking the scheduler to
  490. match strictly against the printer's live trays, and they are only ever
  491. applied inside `_compute_ams_mapping_for_printer` — the function a
  492. stored mapping makes the scheduler skip. Inheriting the saved mapping
  493. here would silently retire the strictness that was just requested
  494. (#2700 review).
  495. """
  496. printer = await printer_factory()
  497. archive = await archive_factory(
  498. extra_data={"slicer_ams_mapping": {"mapping": [5, -1, 2, -1], "printer_id": printer.id}}
  499. )
  500. data = {
  501. "printer_id": printer.id,
  502. "archive_id": archive.id,
  503. "filament_overrides": [
  504. {"slot_id": 1, "type": "PLA", "color": "#FF0000", "force_color_match": True},
  505. ],
  506. }
  507. response = await async_client.post("/api/v1/queue/", json=data)
  508. assert response.status_code == 200
  509. result = response.json()
  510. assert result["ams_mapping"] is None
  511. @pytest.mark.asyncio
  512. @pytest.mark.integration
  513. async def test_add_to_queue_plain_overrides_still_allow_the_archive_fallback(
  514. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  515. ):
  516. """Only force_color_match stands the fallback down. A plain preference
  517. override is a filament swap, not a request for live colour matching, so
  518. the saved mapping is still the best starting point.
  519. """
  520. printer = await printer_factory()
  521. archive = await archive_factory(
  522. extra_data={"slicer_ams_mapping": {"mapping": [5, -1, 2, -1], "printer_id": printer.id}}
  523. )
  524. data = {
  525. "printer_id": printer.id,
  526. "archive_id": archive.id,
  527. "filament_overrides": [{"slot_id": 1, "type": "PLA", "color": "#FF0000"}],
  528. }
  529. response = await async_client.post("/api/v1/queue/", json=data)
  530. assert response.status_code == 200
  531. result = response.json()
  532. assert result["ams_mapping"] == [5, -1, 2, -1]
  533. @pytest.mark.asyncio
  534. @pytest.mark.integration
  535. async def test_queue_response_flags_saved_mapping_only_for_its_own_printer(
  536. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  537. ):
  538. """`archive_has_slicer_ams_mapping` drives a badge that claims the
  539. print reuses the slicer's exact trays. Global tray IDs mean nothing on
  540. another printer, so the flag must be false for a row targeting one —
  541. otherwise the badge is there while nothing is reused (#2700 review).
  542. """
  543. origin_printer = await printer_factory()
  544. other_printer = await printer_factory()
  545. archive = await archive_factory(
  546. extra_data={"slicer_ams_mapping": {"mapping": [5, -1, 2, -1], "printer_id": origin_printer.id}}
  547. )
  548. own = await async_client.post(
  549. "/api/v1/queue/", json={"printer_id": origin_printer.id, "archive_id": archive.id}
  550. )
  551. assert own.status_code == 200
  552. assert own.json()["archive_has_slicer_ams_mapping"] is True
  553. foreign = await async_client.post(
  554. "/api/v1/queue/", json={"printer_id": other_printer.id, "archive_id": archive.id}
  555. )
  556. assert foreign.status_code == 200
  557. assert foreign.json()["archive_has_slicer_ams_mapping"] is False
  558. # Model-based: the scheduler hasn't picked a printer yet, so the
  559. # mapping is not reused there either.
  560. model_based = await async_client.post("/api/v1/queue/", json={"target_model": "X1C", "archive_id": archive.id})
  561. assert model_based.status_code == 200
  562. assert model_based.json()["archive_has_slicer_ams_mapping"] is False
  563. @pytest.mark.asyncio
  564. @pytest.mark.integration
  565. async def test_add_to_queue_with_plate_id(
  566. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  567. ):
  568. """Verify item can be added to queue with plate_id for multi-plate 3MF."""
  569. printer = await printer_factory()
  570. archive = await archive_factory()
  571. data = {
  572. "printer_id": printer.id,
  573. "archive_id": archive.id,
  574. "plate_id": 3,
  575. }
  576. response = await async_client.post("/api/v1/queue/", json=data)
  577. assert response.status_code == 200
  578. result = response.json()
  579. assert result["plate_id"] == 3
  580. @pytest.mark.asyncio
  581. @pytest.mark.integration
  582. async def test_add_to_queue_with_print_options(
  583. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  584. ):
  585. """Verify item can be added to queue with print options."""
  586. printer = await printer_factory()
  587. archive = await archive_factory()
  588. data = {
  589. "printer_id": printer.id,
  590. "archive_id": archive.id,
  591. "bed_levelling": "off",
  592. "flow_cali": "on",
  593. "vibration_cali": False,
  594. "layer_inspect": True,
  595. "timelapse": True,
  596. "use_ams": False,
  597. }
  598. response = await async_client.post("/api/v1/queue/", json=data)
  599. assert response.status_code == 200
  600. result = response.json()
  601. assert result["bed_levelling"] == "off"
  602. assert result["flow_cali"] == "on"
  603. assert result["vibration_cali"] is False
  604. assert result["layer_inspect"] is True
  605. assert result["timelapse"] is True
  606. assert result["use_ams"] is False
  607. @pytest.mark.asyncio
  608. @pytest.mark.integration
  609. async def test_update_queue_item_plate_id(self, async_client: AsyncClient, queue_item_factory, db_session):
  610. """Verify queue item plate_id can be updated."""
  611. item = await queue_item_factory()
  612. response = await async_client.patch(f"/api/v1/queue/{item.id}", json={"plate_id": 5})
  613. assert response.status_code == 200
  614. result = response.json()
  615. assert result["plate_id"] == 5
  616. @pytest.mark.asyncio
  617. @pytest.mark.integration
  618. async def test_update_queue_item_print_options(self, async_client: AsyncClient, queue_item_factory, db_session):
  619. """Verify queue item print options can be updated."""
  620. item = await queue_item_factory()
  621. response = await async_client.patch(
  622. f"/api/v1/queue/{item.id}",
  623. json={
  624. "bed_levelling": "off",
  625. "timelapse": True,
  626. },
  627. )
  628. assert response.status_code == 200
  629. result = response.json()
  630. assert result["bed_levelling"] == "off"
  631. assert result["timelapse"] is True
  632. @pytest.mark.asyncio
  633. @pytest.mark.integration
  634. async def test_reassign_rejected_while_dispatching(
  635. self, async_client: AsyncClient, queue_item_factory, printer_factory, db_session
  636. ):
  637. """#2615: a claimed (in-flight) row rejects edits with 409, so its printer
  638. can't be reassigned out from under the running FTP upload."""
  639. from datetime import datetime, timezone
  640. item = await queue_item_factory(dispatching_at=datetime.now(timezone.utc))
  641. other = await printer_factory()
  642. original_printer_id = item.printer_id
  643. response = await async_client.patch(f"/api/v1/queue/{item.id}", json={"printer_id": other.id})
  644. assert response.status_code == 409
  645. await db_session.refresh(item)
  646. assert item.printer_id == original_printer_id, "printer_id must not change on a dispatching row"
  647. @pytest.mark.asyncio
  648. @pytest.mark.integration
  649. async def test_bulk_update_skips_dispatching_item(
  650. self, async_client: AsyncClient, queue_item_factory, printer_factory, db_session
  651. ):
  652. """#2615: bulk edits skip a claimed row rather than splitting it."""
  653. from datetime import datetime, timezone
  654. item = await queue_item_factory(dispatching_at=datetime.now(timezone.utc))
  655. other = await printer_factory()
  656. original_printer_id = item.printer_id
  657. response = await async_client.patch("/api/v1/queue/bulk", json={"item_ids": [item.id], "printer_id": other.id})
  658. assert response.status_code == 200
  659. body = response.json()
  660. assert body["skipped_count"] == 1
  661. assert body["updated_count"] == 0
  662. await db_session.refresh(item)
  663. assert item.printer_id == original_printer_id
  664. @pytest.mark.asyncio
  665. @pytest.mark.integration
  666. async def test_update_allowed_on_unclaimed_pending_item(
  667. self, async_client: AsyncClient, queue_item_factory, db_session
  668. ):
  669. """Regression guard: a normal pending row (no claim) still edits fine."""
  670. item = await queue_item_factory()
  671. response = await async_client.patch(f"/api/v1/queue/{item.id}", json={"plate_id": 7})
  672. assert response.status_code == 200
  673. assert response.json()["plate_id"] == 7
  674. @pytest.mark.asyncio
  675. @pytest.mark.integration
  676. async def test_get_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  677. """Verify single queue item can be retrieved."""
  678. item = await queue_item_factory()
  679. response = await async_client.get(f"/api/v1/queue/{item.id}")
  680. assert response.status_code == 200
  681. assert response.json()["id"] == item.id
  682. @pytest.mark.asyncio
  683. @pytest.mark.integration
  684. async def test_get_queue_item_not_found(self, async_client: AsyncClient):
  685. """Verify 404 for non-existent queue item."""
  686. response = await async_client.get("/api/v1/queue/9999")
  687. assert response.status_code == 404
  688. @pytest.mark.asyncio
  689. @pytest.mark.integration
  690. async def test_update_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  691. """Verify queue item can be updated."""
  692. item = await queue_item_factory()
  693. response = await async_client.patch(f"/api/v1/queue/{item.id}", json={"auto_off_after": True})
  694. assert response.status_code == 200
  695. result = response.json()
  696. assert result["auto_off_after"] is True
  697. @pytest.mark.asyncio
  698. @pytest.mark.integration
  699. async def test_update_queue_item_manual_start(self, async_client: AsyncClient, queue_item_factory, db_session):
  700. """Verify queue item manual_start can be updated."""
  701. item = await queue_item_factory(manual_start=False)
  702. response = await async_client.patch(f"/api/v1/queue/{item.id}", json={"manual_start": True})
  703. assert response.status_code == 200
  704. result = response.json()
  705. assert result["manual_start"] is True
  706. @pytest.mark.asyncio
  707. @pytest.mark.integration
  708. async def test_delete_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  709. """Verify queue item can be deleted."""
  710. item = await queue_item_factory()
  711. response = await async_client.delete(f"/api/v1/queue/{item.id}")
  712. assert response.status_code == 200
  713. assert response.json()["message"] == "Queue item deleted"
  714. @pytest.mark.asyncio
  715. @pytest.mark.integration
  716. async def test_delete_queue_item_releases_reserved_budget(
  717. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory, db_session
  718. ):
  719. """Deleting a pending cost-center queue item releases its reserved budget."""
  720. await enable_billing(db_session)
  721. printer = await printer_factory()
  722. archive = await archive_factory()
  723. cost_center = CostCenter(
  724. name="Delete Releases Budget CC", is_active=True, is_private=False, monthly_budget=10.0
  725. )
  726. db_session.add(cost_center)
  727. await db_session.commit()
  728. await db_session.refresh(cost_center)
  729. item = await queue_item_factory(
  730. printer_id=printer.id,
  731. archive_id=archive.id,
  732. cost_center_id=cost_center.id,
  733. estimated_cost=8.0,
  734. status="pending",
  735. )
  736. blocked = await async_client.post(
  737. "/api/v1/queue/",
  738. json={
  739. "printer_id": printer.id,
  740. "archive_id": archive.id,
  741. "cost_center_id": cost_center.id,
  742. "estimated_cost": 3.0,
  743. },
  744. )
  745. assert blocked.status_code == 400
  746. deleted = await async_client.delete(f"/api/v1/queue/{item.id}")
  747. assert deleted.status_code == 200
  748. allowed = await async_client.post(
  749. "/api/v1/queue/",
  750. json={
  751. "printer_id": printer.id,
  752. "archive_id": archive.id,
  753. "cost_center_id": cost_center.id,
  754. "estimated_cost": 3.0,
  755. },
  756. )
  757. assert allowed.status_code == 200
  758. @pytest.mark.asyncio
  759. @pytest.mark.integration
  760. async def test_delete_queue_item_not_found(self, async_client: AsyncClient):
  761. """Verify 404 for deleting non-existent queue item."""
  762. response = await async_client.delete("/api/v1/queue/9999")
  763. assert response.status_code == 404
  764. class TestQueueStartEndpoint:
  765. """Tests for the /queue/{item_id}/start endpoint."""
  766. @pytest.fixture
  767. async def printer_factory(self, db_session):
  768. """Factory to create test printers."""
  769. _counter = [0]
  770. async def _create_printer(**kwargs):
  771. from backend.app.models.printer import Printer
  772. _counter[0] += 1
  773. counter = _counter[0]
  774. defaults = {
  775. "name": f"Test Printer {counter}",
  776. "ip_address": f"192.168.1.{100 + counter}",
  777. "serial_number": f"TESTSERIAL{counter:04d}",
  778. "access_code": "12345678",
  779. "model": "X1C",
  780. }
  781. defaults.update(kwargs)
  782. printer = Printer(**defaults)
  783. db_session.add(printer)
  784. await db_session.commit()
  785. await db_session.refresh(printer)
  786. return printer
  787. return _create_printer
  788. @pytest.fixture
  789. async def archive_factory(self, db_session):
  790. """Factory to create test archives."""
  791. _counter = [0]
  792. async def _create_archive(**kwargs):
  793. from backend.app.models.archive import PrintArchive
  794. _counter[0] += 1
  795. counter = _counter[0]
  796. defaults = {
  797. "filename": f"test_print_{counter}.3mf",
  798. "print_name": f"Test Print {counter}",
  799. "file_path": f"/tmp/test_print_{counter}.3mf",
  800. "file_size": 1024,
  801. "content_hash": f"testhash{counter:08d}",
  802. "status": "completed",
  803. }
  804. defaults.update(kwargs)
  805. archive = PrintArchive(**defaults)
  806. db_session.add(archive)
  807. await db_session.commit()
  808. await db_session.refresh(archive)
  809. return archive
  810. return _create_archive
  811. @pytest.fixture
  812. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  813. """Factory to create test queue items."""
  814. _counter = [0]
  815. async def _create_queue_item(**kwargs):
  816. from backend.app.models.print_queue import PrintQueueItem
  817. _counter[0] += 1
  818. counter = _counter[0]
  819. if "printer_id" not in kwargs:
  820. printer = await printer_factory()
  821. kwargs["printer_id"] = printer.id
  822. if "archive_id" not in kwargs:
  823. archive = await archive_factory()
  824. kwargs["archive_id"] = archive.id
  825. defaults = {
  826. "status": "pending",
  827. "position": counter,
  828. }
  829. defaults.update(kwargs)
  830. item = PrintQueueItem(**defaults)
  831. db_session.add(item)
  832. await db_session.commit()
  833. await db_session.refresh(item)
  834. return item
  835. return _create_queue_item
  836. @pytest.mark.asyncio
  837. @pytest.mark.integration
  838. async def test_start_staged_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  839. """Verify starting a staged (manual_start=True) queue item clears the flag."""
  840. item = await queue_item_factory(manual_start=True)
  841. assert item.manual_start is True
  842. response = await async_client.post(f"/api/v1/queue/{item.id}/start")
  843. assert response.status_code == 200
  844. result = response.json()
  845. assert result["manual_start"] is False
  846. assert result["status"] == "pending"
  847. @pytest.mark.asyncio
  848. @pytest.mark.integration
  849. async def test_start_non_staged_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  850. """Verify starting a non-staged queue item still works (idempotent)."""
  851. item = await queue_item_factory(manual_start=False)
  852. assert item.manual_start is False
  853. response = await async_client.post(f"/api/v1/queue/{item.id}/start")
  854. assert response.status_code == 200
  855. result = response.json()
  856. assert result["manual_start"] is False
  857. @pytest.mark.asyncio
  858. @pytest.mark.integration
  859. async def test_start_queue_item_with_cost_center_requires_estimated_cost(
  860. self, async_client: AsyncClient, queue_item_factory, db_session
  861. ):
  862. """Starting a cost-center queue item requires a stored estimate."""
  863. await enable_billing(db_session)
  864. cost_center = CostCenter(name="Start Budget CC", is_active=True, is_private=False, monthly_budget=10.0)
  865. db_session.add(cost_center)
  866. await db_session.commit()
  867. await db_session.refresh(cost_center)
  868. item = await queue_item_factory(manual_start=True, cost_center_id=cost_center.id, estimated_cost=None)
  869. response = await async_client.post(f"/api/v1/queue/{item.id}/start")
  870. assert response.status_code == 400
  871. assert "Estimated cost is required" in response.json()["detail"]
  872. @pytest.mark.asyncio
  873. @pytest.mark.integration
  874. async def test_start_queue_item_not_found(self, async_client: AsyncClient):
  875. """Verify 404 for non-existent queue item."""
  876. response = await async_client.post("/api/v1/queue/9999/start")
  877. assert response.status_code == 404
  878. @pytest.mark.asyncio
  879. @pytest.mark.integration
  880. async def test_start_non_pending_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  881. """Verify 400 error when trying to start a non-pending queue item."""
  882. item = await queue_item_factory(status="printing", manual_start=True)
  883. response = await async_client.post(f"/api/v1/queue/{item.id}/start")
  884. assert response.status_code == 400
  885. assert "pending" in response.json()["detail"].lower()
  886. @pytest.mark.asyncio
  887. @pytest.mark.integration
  888. async def test_start_completed_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  889. """Verify 400 error when trying to start a completed queue item."""
  890. item = await queue_item_factory(status="completed", manual_start=True)
  891. response = await async_client.post(f"/api/v1/queue/{item.id}/start")
  892. assert response.status_code == 400
  893. @pytest.mark.asyncio
  894. @pytest.mark.integration
  895. async def test_start_returns_409_on_filament_deficit(
  896. self,
  897. async_client: AsyncClient,
  898. queue_item_factory,
  899. db_session,
  900. monkeypatch,
  901. ):
  902. """Filament deficit must surface as 409 + structured payload (#1496)."""
  903. from backend.app.services import filament_deficit as fd_module
  904. item = await queue_item_factory(manual_start=True)
  905. async def _fake_deficit(_db, _item):
  906. return [
  907. fd_module.FilamentDeficit(
  908. slot_id=1,
  909. ams_id=0,
  910. tray_id=0,
  911. filament_type="PLA",
  912. required_grams=270.0,
  913. remaining_grams=200.0,
  914. ),
  915. ]
  916. monkeypatch.setattr(
  917. "backend.app.api.routes.print_queue.compute_deficit_for_queue_item",
  918. _fake_deficit,
  919. )
  920. response = await async_client.post(f"/api/v1/queue/{item.id}/start")
  921. assert response.status_code == 409
  922. body = response.json()
  923. assert body["detail"]["code"] == "insufficient_filament"
  924. assert len(body["detail"]["deficit"]) == 1
  925. assert body["detail"]["deficit"][0]["slot_id"] == 1
  926. assert body["detail"]["deficit"][0]["required_grams"] == 270.0
  927. assert body["detail"]["deficit"][0]["remaining_grams"] == 200.0
  928. # Item still pending, manual_start unchanged.
  929. await db_session.refresh(item)
  930. assert item.status == "pending"
  931. assert item.manual_start is True
  932. @pytest.mark.asyncio
  933. @pytest.mark.integration
  934. async def test_start_with_skip_flag_bypasses_deficit_check(
  935. self,
  936. async_client: AsyncClient,
  937. queue_item_factory,
  938. db_session,
  939. monkeypatch,
  940. ):
  941. """With skip_filament_check=true the route dispatches even when short (#1496)."""
  942. from backend.app.services import filament_deficit as fd_module
  943. item = await queue_item_factory(manual_start=True, filament_short=True)
  944. called_with = {}
  945. async def _fake_deficit(_db, _item):
  946. called_with["called"] = True
  947. return [
  948. fd_module.FilamentDeficit(
  949. slot_id=1,
  950. ams_id=0,
  951. tray_id=0,
  952. filament_type="PLA",
  953. required_grams=270.0,
  954. remaining_grams=200.0,
  955. ),
  956. ]
  957. monkeypatch.setattr(
  958. "backend.app.api.routes.print_queue.compute_deficit_for_queue_item",
  959. _fake_deficit,
  960. )
  961. response = await async_client.post(f"/api/v1/queue/{item.id}/start?skip_filament_check=true")
  962. assert response.status_code == 200
  963. body = response.json()
  964. assert body["manual_start"] is False
  965. assert body["filament_short"] is False
  966. # Helper not called on the bypass path — we trust the operator's
  967. # decision to print anyway.
  968. assert called_with == {}
  969. @pytest.mark.asyncio
  970. @pytest.mark.integration
  971. async def test_start_with_skip_flag_persists_acknowledgement(
  972. self,
  973. async_client: AsyncClient,
  974. queue_item_factory,
  975. db_session,
  976. ):
  977. """skip_filament_check=true sets the persistent flag on the queue item
  978. so the scheduler doesn't re-flag it on the next tick (#1698-followup).
  979. Without persistence the route's flag-clearing only survives until the
  980. next scheduler tick re-runs the deficit check on identical spool
  981. state and re-promotes the item — the user has to click Play+Confirm
  982. every single tick.
  983. """
  984. item = await queue_item_factory(manual_start=True, filament_short=True)
  985. assert item.skip_filament_check is False
  986. response = await async_client.post(f"/api/v1/queue/{item.id}/start?skip_filament_check=true")
  987. assert response.status_code == 200
  988. body = response.json()
  989. assert body["skip_filament_check"] is True
  990. await db_session.refresh(item)
  991. assert item.skip_filament_check is True
  992. @pytest.mark.asyncio
  993. @pytest.mark.integration
  994. async def test_start_without_skip_flag_does_not_set_acknowledgement(
  995. self,
  996. async_client: AsyncClient,
  997. queue_item_factory,
  998. db_session,
  999. ):
  1000. """A successful Play click with no deficit must NOT silently set the
  1001. acknowledgement flag — only an explicit Print Anyway should.
  1002. """
  1003. item = await queue_item_factory(manual_start=False, filament_short=False)
  1004. assert item.skip_filament_check is False
  1005. response = await async_client.post(f"/api/v1/queue/{item.id}/start")
  1006. assert response.status_code == 200
  1007. await db_session.refresh(item)
  1008. assert item.skip_filament_check is False
  1009. class TestQueueCancelEndpoint:
  1010. """Tests for the /queue/{item_id}/cancel endpoint."""
  1011. @pytest.fixture
  1012. async def printer_factory(self, db_session):
  1013. """Factory to create test printers."""
  1014. async def _create_printer(**kwargs):
  1015. from backend.app.models.printer import Printer
  1016. defaults = {
  1017. "name": "Cancel Test Printer",
  1018. "ip_address": "192.168.1.200",
  1019. "serial_number": "TESTCANCEL001",
  1020. "access_code": "12345678",
  1021. "model": "X1C",
  1022. }
  1023. defaults.update(kwargs)
  1024. printer = Printer(**defaults)
  1025. db_session.add(printer)
  1026. await db_session.commit()
  1027. await db_session.refresh(printer)
  1028. return printer
  1029. return _create_printer
  1030. @pytest.fixture
  1031. async def archive_factory(self, db_session):
  1032. """Factory to create test archives."""
  1033. async def _create_archive(**kwargs):
  1034. from backend.app.models.archive import PrintArchive
  1035. defaults = {
  1036. "filename": "cancel_test.3mf",
  1037. "print_name": "Cancel Test Print",
  1038. "file_path": "/tmp/cancel_test.3mf",
  1039. "file_size": 1024,
  1040. "content_hash": "cancelhash001",
  1041. "status": "completed",
  1042. }
  1043. defaults.update(kwargs)
  1044. archive = PrintArchive(**defaults)
  1045. db_session.add(archive)
  1046. await db_session.commit()
  1047. await db_session.refresh(archive)
  1048. return archive
  1049. return _create_archive
  1050. @pytest.fixture
  1051. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  1052. """Factory to create test queue items."""
  1053. async def _create_queue_item(**kwargs):
  1054. from backend.app.models.print_queue import PrintQueueItem
  1055. if "printer_id" not in kwargs:
  1056. printer = await printer_factory()
  1057. kwargs["printer_id"] = printer.id
  1058. if "archive_id" not in kwargs:
  1059. archive = await archive_factory()
  1060. kwargs["archive_id"] = archive.id
  1061. defaults = {
  1062. "status": "pending",
  1063. "position": 1,
  1064. }
  1065. defaults.update(kwargs)
  1066. item = PrintQueueItem(**defaults)
  1067. db_session.add(item)
  1068. await db_session.commit()
  1069. await db_session.refresh(item)
  1070. return item
  1071. return _create_queue_item
  1072. @pytest.mark.asyncio
  1073. @pytest.mark.integration
  1074. async def test_cancel_pending_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  1075. """Verify cancelling a pending queue item."""
  1076. item = await queue_item_factory(status="pending")
  1077. response = await async_client.post(f"/api/v1/queue/{item.id}/cancel")
  1078. assert response.status_code == 200
  1079. assert response.json()["message"] == "Queue item cancelled"
  1080. @pytest.mark.asyncio
  1081. @pytest.mark.integration
  1082. async def test_cancel_non_pending_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  1083. """Verify 400 error when trying to cancel a non-pending queue item."""
  1084. item = await queue_item_factory(status="printing")
  1085. response = await async_client.post(f"/api/v1/queue/{item.id}/cancel")
  1086. assert response.status_code == 400
  1087. class TestQueueLibraryFileSupport:
  1088. """Tests for queue items with library_file_id (instead of archive_id)."""
  1089. @pytest.fixture
  1090. async def printer_factory(self, db_session):
  1091. """Factory to create test printers."""
  1092. _counter = [0]
  1093. async def _create_printer(**kwargs):
  1094. from backend.app.models.printer import Printer
  1095. _counter[0] += 1
  1096. counter = _counter[0]
  1097. defaults = {
  1098. "name": f"Library Test Printer {counter}",
  1099. "ip_address": f"192.168.1.{150 + counter}",
  1100. "serial_number": f"TESTLIB{counter:04d}",
  1101. "access_code": "12345678",
  1102. "model": "X1C",
  1103. }
  1104. defaults.update(kwargs)
  1105. printer = Printer(**defaults)
  1106. db_session.add(printer)
  1107. await db_session.commit()
  1108. await db_session.refresh(printer)
  1109. return printer
  1110. return _create_printer
  1111. @pytest.fixture
  1112. async def library_file_factory(self, db_session):
  1113. """Factory to create test library files."""
  1114. _counter = [0]
  1115. async def _create_library_file(**kwargs):
  1116. from backend.app.models.library import LibraryFile
  1117. _counter[0] += 1
  1118. counter = _counter[0]
  1119. defaults = {
  1120. "filename": f"library_test_{counter}.3mf",
  1121. "file_path": f"/test/library/library_test_{counter}.3mf",
  1122. "file_size": 2048,
  1123. "file_type": "3mf",
  1124. "file_metadata": {"print_name": f"Library Print {counter}", "print_time_seconds": 3600},
  1125. }
  1126. defaults.update(kwargs)
  1127. lib_file = LibraryFile(**defaults)
  1128. db_session.add(lib_file)
  1129. await db_session.commit()
  1130. await db_session.refresh(lib_file)
  1131. return lib_file
  1132. return _create_library_file
  1133. @pytest.mark.asyncio
  1134. @pytest.mark.integration
  1135. async def test_add_to_queue_with_library_file(
  1136. self, async_client: AsyncClient, printer_factory, library_file_factory, db_session
  1137. ):
  1138. """Verify item can be added to queue using library_file_id instead of archive_id."""
  1139. printer = await printer_factory()
  1140. lib_file = await library_file_factory()
  1141. data = {
  1142. "printer_id": printer.id,
  1143. "library_file_id": lib_file.id,
  1144. }
  1145. response = await async_client.post("/api/v1/queue/", json=data)
  1146. assert response.status_code == 200
  1147. result = response.json()
  1148. assert result["printer_id"] == printer.id
  1149. assert result["library_file_id"] == lib_file.id
  1150. assert result["archive_id"] is None
  1151. assert result["status"] == "pending"
  1152. assert result["library_file_name"] == "Library Print 1"
  1153. assert result["print_time_seconds"] == 3600
  1154. @pytest.mark.asyncio
  1155. @pytest.mark.integration
  1156. async def test_add_library_file_rejects_cross_model_mismatch(
  1157. self, async_client: AsyncClient, printer_factory, library_file_factory, db_session
  1158. ):
  1159. """Cross-model gate (#2578) also reads sliced_for_model from library file metadata."""
  1160. await printer_factory(model="H2D")
  1161. lib_file = await library_file_factory(file_metadata={"print_name": "Mismatch", "sliced_for_model": "X1C"})
  1162. response = await async_client.post(
  1163. "/api/v1/queue/",
  1164. json={"target_model": "H2D", "library_file_id": lib_file.id},
  1165. )
  1166. assert response.status_code == 400
  1167. assert "sliced for X1C" in response.json()["detail"]
  1168. @pytest.mark.asyncio
  1169. @pytest.mark.integration
  1170. async def test_add_to_queue_library_file_with_options(
  1171. self, async_client: AsyncClient, printer_factory, library_file_factory, db_session
  1172. ):
  1173. """Verify library file queue item can have all options set."""
  1174. printer = await printer_factory()
  1175. lib_file = await library_file_factory()
  1176. data = {
  1177. "printer_id": printer.id,
  1178. "library_file_id": lib_file.id,
  1179. "ams_mapping": [1, 2, -1, -1],
  1180. "plate_id": 2,
  1181. "bed_levelling": "off",
  1182. "timelapse": True,
  1183. "manual_start": True,
  1184. }
  1185. response = await async_client.post("/api/v1/queue/", json=data)
  1186. assert response.status_code == 200
  1187. result = response.json()
  1188. assert result["library_file_id"] == lib_file.id
  1189. assert result["ams_mapping"] == [1, 2, -1, -1]
  1190. assert result["plate_id"] == 2
  1191. assert result["bed_levelling"] == "off"
  1192. assert result["timelapse"] is True
  1193. assert result["manual_start"] is True
  1194. @pytest.mark.asyncio
  1195. @pytest.mark.integration
  1196. async def test_add_to_queue_requires_archive_or_library_file(
  1197. self, async_client: AsyncClient, printer_factory, db_session
  1198. ):
  1199. """Verify 400 error when neither archive_id nor library_file_id provided."""
  1200. printer = await printer_factory()
  1201. data = {
  1202. "printer_id": printer.id,
  1203. }
  1204. response = await async_client.post("/api/v1/queue/", json=data)
  1205. assert response.status_code == 400
  1206. assert (
  1207. "archive_id" in response.json()["detail"].lower() or "library_file_id" in response.json()["detail"].lower()
  1208. )
  1209. @pytest.mark.asyncio
  1210. @pytest.mark.integration
  1211. async def test_update_queue_item_with_library_file(
  1212. self, async_client: AsyncClient, printer_factory, library_file_factory, db_session
  1213. ):
  1214. """Verify queue item with library_file_id can be updated."""
  1215. from backend.app.models.print_queue import PrintQueueItem
  1216. printer = await printer_factory()
  1217. lib_file = await library_file_factory()
  1218. # Create queue item directly
  1219. item = PrintQueueItem(
  1220. printer_id=printer.id,
  1221. library_file_id=lib_file.id,
  1222. status="pending",
  1223. position=1,
  1224. )
  1225. db_session.add(item)
  1226. await db_session.commit()
  1227. await db_session.refresh(item)
  1228. # Update the item
  1229. response = await async_client.patch(
  1230. f"/api/v1/queue/{item.id}",
  1231. json={"auto_off_after": True, "plate_id": 3},
  1232. )
  1233. assert response.status_code == 200
  1234. result = response.json()
  1235. assert result["auto_off_after"] is True
  1236. assert result["plate_id"] == 3
  1237. assert result["library_file_id"] == lib_file.id
  1238. @pytest.mark.asyncio
  1239. @pytest.mark.integration
  1240. async def test_list_queue_includes_library_file_info(
  1241. self, async_client: AsyncClient, printer_factory, library_file_factory, db_session
  1242. ):
  1243. """Verify queue list includes library file metadata."""
  1244. from backend.app.models.print_queue import PrintQueueItem
  1245. printer = await printer_factory()
  1246. lib_file = await library_file_factory(
  1247. file_metadata={"print_name": "Custom Print Name", "print_time_seconds": 7200}
  1248. )
  1249. item = PrintQueueItem(
  1250. printer_id=printer.id,
  1251. library_file_id=lib_file.id,
  1252. status="pending",
  1253. position=1,
  1254. )
  1255. db_session.add(item)
  1256. await db_session.commit()
  1257. response = await async_client.get("/api/v1/queue/")
  1258. assert response.status_code == 200
  1259. items = response.json()
  1260. assert len(items) >= 1
  1261. # Find our item
  1262. our_item = next((i for i in items if i["library_file_id"] == lib_file.id), None)
  1263. assert our_item is not None
  1264. assert our_item["library_file_name"] == "Custom Print Name"
  1265. assert our_item["print_time_seconds"] == 7200
  1266. class TestBulkUpdateEndpoint:
  1267. """Tests for the /queue/bulk endpoint."""
  1268. @pytest.fixture
  1269. async def printer_factory(self, db_session):
  1270. """Factory to create test printers."""
  1271. _counter = [0]
  1272. async def _create_printer(**kwargs):
  1273. from backend.app.models.printer import Printer
  1274. _counter[0] += 1
  1275. counter = _counter[0]
  1276. defaults = {
  1277. "name": f"Bulk Test Printer {counter}",
  1278. "ip_address": f"192.168.1.{150 + counter}",
  1279. "serial_number": f"TESTBULK{counter:04d}",
  1280. "access_code": "12345678",
  1281. "model": "X1C",
  1282. }
  1283. defaults.update(kwargs)
  1284. printer = Printer(**defaults)
  1285. db_session.add(printer)
  1286. await db_session.commit()
  1287. await db_session.refresh(printer)
  1288. return printer
  1289. return _create_printer
  1290. @pytest.fixture
  1291. async def archive_factory(self, db_session):
  1292. """Factory to create test archives."""
  1293. _counter = [0]
  1294. async def _create_archive(**kwargs):
  1295. from backend.app.models.archive import PrintArchive
  1296. _counter[0] += 1
  1297. counter = _counter[0]
  1298. defaults = {
  1299. "filename": f"bulk_test_{counter}.3mf",
  1300. "print_name": f"Bulk Test Print {counter}",
  1301. "file_path": f"/tmp/bulk_test_{counter}.3mf",
  1302. "file_size": 1024,
  1303. "content_hash": f"bulkhash{counter:04d}",
  1304. "status": "completed",
  1305. }
  1306. defaults.update(kwargs)
  1307. archive = PrintArchive(**defaults)
  1308. db_session.add(archive)
  1309. await db_session.commit()
  1310. await db_session.refresh(archive)
  1311. return archive
  1312. return _create_archive
  1313. @pytest.fixture
  1314. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  1315. """Factory to create test queue items."""
  1316. async def _create_item(**kwargs):
  1317. from backend.app.models.print_queue import PrintQueueItem
  1318. if "printer_id" not in kwargs:
  1319. printer = await printer_factory()
  1320. kwargs["printer_id"] = printer.id
  1321. if "archive_id" not in kwargs:
  1322. archive = await archive_factory()
  1323. kwargs["archive_id"] = archive.id
  1324. defaults = {
  1325. "status": "pending",
  1326. "position": 1,
  1327. "bed_levelling": "on",
  1328. "flow_cali": "off",
  1329. "vibration_cali": True,
  1330. }
  1331. defaults.update(kwargs)
  1332. item = PrintQueueItem(**defaults)
  1333. db_session.add(item)
  1334. await db_session.commit()
  1335. await db_session.refresh(item)
  1336. return item
  1337. return _create_item
  1338. @pytest.mark.asyncio
  1339. @pytest.mark.integration
  1340. async def test_bulk_update_single_field(self, async_client: AsyncClient, queue_item_factory, db_session):
  1341. """Verify bulk update can change a single field on multiple items."""
  1342. item1 = await queue_item_factory(bed_levelling="on")
  1343. item2 = await queue_item_factory(bed_levelling="on")
  1344. response = await async_client.patch(
  1345. "/api/v1/queue/bulk",
  1346. json={"item_ids": [item1.id, item2.id], "bed_levelling": "off"},
  1347. )
  1348. assert response.status_code == 200
  1349. result = response.json()
  1350. assert result["updated_count"] == 2
  1351. assert result["skipped_count"] == 0
  1352. # Verify items were updated
  1353. await db_session.refresh(item1)
  1354. await db_session.refresh(item2)
  1355. assert item1.bed_levelling == "off"
  1356. assert item2.bed_levelling == "off"
  1357. @pytest.mark.asyncio
  1358. @pytest.mark.integration
  1359. async def test_bulk_update_multiple_fields(self, async_client: AsyncClient, queue_item_factory, db_session):
  1360. """Verify bulk update can change multiple fields at once."""
  1361. item1 = await queue_item_factory(bed_levelling="on", flow_cali="off", manual_start=False)
  1362. item2 = await queue_item_factory(bed_levelling="on", flow_cali="off", manual_start=False)
  1363. response = await async_client.patch(
  1364. "/api/v1/queue/bulk",
  1365. json={
  1366. "item_ids": [item1.id, item2.id],
  1367. "bed_levelling": "off",
  1368. "flow_cali": "on",
  1369. "manual_start": True,
  1370. },
  1371. )
  1372. assert response.status_code == 200
  1373. result = response.json()
  1374. assert result["updated_count"] == 2
  1375. await db_session.refresh(item1)
  1376. assert item1.bed_levelling == "off"
  1377. assert item1.flow_cali == "on"
  1378. assert item1.manual_start is True
  1379. @pytest.mark.asyncio
  1380. @pytest.mark.integration
  1381. async def test_bulk_update_skips_non_pending(self, async_client: AsyncClient, queue_item_factory, db_session):
  1382. """Verify bulk update skips non-pending items."""
  1383. pending_item = await queue_item_factory(status="pending", bed_levelling="on")
  1384. printing_item = await queue_item_factory(status="printing", bed_levelling="on")
  1385. completed_item = await queue_item_factory(status="completed", bed_levelling="on")
  1386. response = await async_client.patch(
  1387. "/api/v1/queue/bulk",
  1388. json={
  1389. "item_ids": [pending_item.id, printing_item.id, completed_item.id],
  1390. "bed_levelling": "off",
  1391. },
  1392. )
  1393. assert response.status_code == 200
  1394. result = response.json()
  1395. assert result["updated_count"] == 1
  1396. assert result["skipped_count"] == 2
  1397. # Only pending item should be updated
  1398. await db_session.refresh(pending_item)
  1399. await db_session.refresh(printing_item)
  1400. await db_session.refresh(completed_item)
  1401. assert pending_item.bed_levelling == "off"
  1402. assert printing_item.bed_levelling == "on"
  1403. assert completed_item.bed_levelling == "on"
  1404. @pytest.mark.asyncio
  1405. @pytest.mark.integration
  1406. async def test_bulk_update_change_printer(
  1407. self, async_client: AsyncClient, queue_item_factory, printer_factory, db_session
  1408. ):
  1409. """Verify bulk update can reassign items to a different printer."""
  1410. new_printer = await printer_factory(name="New Target Printer")
  1411. item1 = await queue_item_factory()
  1412. item2 = await queue_item_factory()
  1413. original_printer_id = item1.printer_id
  1414. response = await async_client.patch(
  1415. "/api/v1/queue/bulk",
  1416. json={"item_ids": [item1.id, item2.id], "printer_id": new_printer.id},
  1417. )
  1418. assert response.status_code == 200
  1419. await db_session.refresh(item1)
  1420. await db_session.refresh(item2)
  1421. assert item1.printer_id == new_printer.id
  1422. assert item2.printer_id == new_printer.id
  1423. assert item1.printer_id != original_printer_id
  1424. @pytest.mark.asyncio
  1425. @pytest.mark.integration
  1426. async def test_bulk_update_empty_item_ids(self, async_client: AsyncClient):
  1427. """Verify 400 error when item_ids is empty."""
  1428. response = await async_client.patch(
  1429. "/api/v1/queue/bulk",
  1430. json={"item_ids": [], "bed_levelling": False},
  1431. )
  1432. assert response.status_code == 400
  1433. assert "no item" in response.json()["detail"].lower()
  1434. @pytest.mark.asyncio
  1435. @pytest.mark.integration
  1436. async def test_bulk_update_no_fields(self, async_client: AsyncClient, queue_item_factory):
  1437. """Verify 400 error when no fields to update."""
  1438. item = await queue_item_factory()
  1439. response = await async_client.patch(
  1440. "/api/v1/queue/bulk",
  1441. json={"item_ids": [item.id]},
  1442. )
  1443. assert response.status_code == 400
  1444. assert "no fields" in response.json()["detail"].lower()
  1445. @pytest.mark.asyncio
  1446. @pytest.mark.integration
  1447. async def test_bulk_update_invalid_printer(self, async_client: AsyncClient, queue_item_factory):
  1448. """Verify 400 error when printer_id doesn't exist."""
  1449. item = await queue_item_factory()
  1450. response = await async_client.patch(
  1451. "/api/v1/queue/bulk",
  1452. json={"item_ids": [item.id], "printer_id": 99999},
  1453. )
  1454. assert response.status_code == 400
  1455. assert "printer not found" in response.json()["detail"].lower()
  1456. @pytest.mark.asyncio
  1457. @pytest.mark.integration
  1458. async def test_bulk_update_cost_center_requires_estimated_cost(
  1459. self, async_client: AsyncClient, queue_item_factory, db_session
  1460. ):
  1461. """Bulk assigning a cost center requires an estimate, same as single-item updates."""
  1462. await enable_billing(db_session)
  1463. item = await queue_item_factory()
  1464. cost_center = CostCenter(name="Bulk Budget CC", is_active=True, is_private=False, monthly_budget=10.0)
  1465. db_session.add(cost_center)
  1466. await db_session.commit()
  1467. await db_session.refresh(cost_center)
  1468. response = await async_client.patch(
  1469. "/api/v1/queue/bulk",
  1470. json={"item_ids": [item.id], "cost_center_id": cost_center.id},
  1471. )
  1472. assert response.status_code == 400
  1473. assert "Estimated cost is required" in response.json()["detail"]
  1474. @pytest.mark.asyncio
  1475. @pytest.mark.integration
  1476. async def test_bulk_update_cost_center_counts_pending_reservations(
  1477. self, async_client: AsyncClient, queue_item_factory, db_session
  1478. ):
  1479. """Bulk updates cannot reserve more than the available cost-center budget."""
  1480. await enable_billing(db_session)
  1481. item = await queue_item_factory()
  1482. existing = await queue_item_factory()
  1483. cost_center = CostCenter(name="Bulk Reserved CC", is_active=True, is_private=False, monthly_budget=10.0)
  1484. db_session.add(cost_center)
  1485. await db_session.commit()
  1486. await db_session.refresh(cost_center)
  1487. existing.cost_center_id = cost_center.id
  1488. existing.estimated_cost = 8.0
  1489. await db_session.commit()
  1490. response = await async_client.patch(
  1491. "/api/v1/queue/bulk",
  1492. json={"item_ids": [item.id], "cost_center_id": cost_center.id, "estimated_cost": 3.0},
  1493. )
  1494. assert response.status_code == 400
  1495. assert "exceeds available cost center budget" in response.json()["detail"]
  1496. await db_session.refresh(item)
  1497. assert item.cost_center_id is None
  1498. assert item.estimated_cost is None
  1499. class TestTargetLocationFeature:
  1500. """Tests for queue items with target_location (Issue #220)."""
  1501. @pytest.fixture
  1502. async def printer_factory(self, db_session):
  1503. """Factory to create test printers."""
  1504. _counter = [0]
  1505. async def _create_printer(**kwargs):
  1506. from backend.app.models.printer import Printer
  1507. _counter[0] += 1
  1508. counter = _counter[0]
  1509. defaults = {
  1510. "name": f"Location Test Printer {counter}",
  1511. "ip_address": f"192.168.1.{50 + counter}",
  1512. "serial_number": f"TESTLOC{counter:04d}",
  1513. "access_code": "12345678",
  1514. "model": "X1C",
  1515. }
  1516. defaults.update(kwargs)
  1517. printer = Printer(**defaults)
  1518. db_session.add(printer)
  1519. await db_session.commit()
  1520. await db_session.refresh(printer)
  1521. return printer
  1522. return _create_printer
  1523. @pytest.fixture
  1524. async def archive_factory(self, db_session):
  1525. """Factory to create test archives."""
  1526. _counter = [0]
  1527. async def _create_archive(**kwargs):
  1528. from backend.app.models.archive import PrintArchive
  1529. _counter[0] += 1
  1530. counter = _counter[0]
  1531. defaults = {
  1532. "filename": f"location_test_{counter}.3mf",
  1533. "print_name": f"Location Test Print {counter}",
  1534. "file_path": f"/tmp/location_test_{counter}.3mf",
  1535. "file_size": 1024,
  1536. "content_hash": f"lochash{counter:08d}",
  1537. "status": "completed",
  1538. }
  1539. defaults.update(kwargs)
  1540. archive = PrintArchive(**defaults)
  1541. db_session.add(archive)
  1542. await db_session.commit()
  1543. await db_session.refresh(archive)
  1544. return archive
  1545. return _create_archive
  1546. @pytest.fixture
  1547. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  1548. """Factory to create test queue items."""
  1549. _counter = [0]
  1550. async def _create_queue_item(**kwargs):
  1551. from backend.app.models.print_queue import PrintQueueItem
  1552. _counter[0] += 1
  1553. counter = _counter[0]
  1554. if "printer_id" not in kwargs and "target_model" not in kwargs:
  1555. printer = await printer_factory()
  1556. kwargs["printer_id"] = printer.id
  1557. if "archive_id" not in kwargs:
  1558. archive = await archive_factory()
  1559. kwargs["archive_id"] = archive.id
  1560. defaults = {
  1561. "status": "pending",
  1562. "position": counter,
  1563. }
  1564. defaults.update(kwargs)
  1565. item = PrintQueueItem(**defaults)
  1566. db_session.add(item)
  1567. await db_session.commit()
  1568. await db_session.refresh(item)
  1569. return item
  1570. return _create_queue_item
  1571. @pytest.mark.asyncio
  1572. @pytest.mark.integration
  1573. async def test_add_to_queue_with_target_location(
  1574. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1575. ):
  1576. """Verify item can be added with target_model and target_location."""
  1577. # Create a printer with model X1C so the API can validate
  1578. await printer_factory(model="X1C", location="Office")
  1579. archive = await archive_factory()
  1580. data = {
  1581. "target_model": "X1C",
  1582. "target_location": "Workbench",
  1583. "archive_id": archive.id,
  1584. }
  1585. response = await async_client.post("/api/v1/queue/", json=data)
  1586. assert response.status_code == 200
  1587. result = response.json()
  1588. assert result["target_model"] == "X1C"
  1589. assert result["target_location"] == "Workbench"
  1590. assert result["printer_id"] is None
  1591. @pytest.mark.asyncio
  1592. @pytest.mark.integration
  1593. async def test_add_to_queue_location_without_model_ignored(
  1594. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1595. ):
  1596. """Verify target_location without target_model is allowed (location is just ignored)."""
  1597. printer = await printer_factory()
  1598. archive = await archive_factory()
  1599. data = {
  1600. "printer_id": printer.id,
  1601. "target_location": "Workbench", # This gets ignored since printer_id is set
  1602. "archive_id": archive.id,
  1603. }
  1604. response = await async_client.post("/api/v1/queue/", json=data)
  1605. # The API accepts this but the location is only used with target_model
  1606. assert response.status_code == 200
  1607. result = response.json()
  1608. assert result["printer_id"] == printer.id
  1609. # Location may or may not be stored since it's meaningless without target_model
  1610. # The important thing is the request succeeds
  1611. @pytest.mark.asyncio
  1612. @pytest.mark.integration
  1613. async def test_queue_item_target_location_in_response(
  1614. self, async_client: AsyncClient, queue_item_factory, db_session
  1615. ):
  1616. """Verify target_location is returned in queue item response."""
  1617. item = await queue_item_factory(
  1618. printer_id=None,
  1619. target_model="X1C",
  1620. target_location="Workshop",
  1621. )
  1622. response = await async_client.get(f"/api/v1/queue/{item.id}")
  1623. assert response.status_code == 200
  1624. result = response.json()
  1625. assert result["target_model"] == "X1C"
  1626. assert result["target_location"] == "Workshop"
  1627. @pytest.mark.asyncio
  1628. @pytest.mark.integration
  1629. async def test_queue_list_includes_target_location(self, async_client: AsyncClient, queue_item_factory, db_session):
  1630. """Verify target_location is included in queue list."""
  1631. await queue_item_factory(
  1632. printer_id=None,
  1633. target_model="P1S",
  1634. target_location="Garage",
  1635. )
  1636. response = await async_client.get("/api/v1/queue/")
  1637. assert response.status_code == 200
  1638. items = response.json()
  1639. assert len(items) >= 1
  1640. # Find our item
  1641. our_item = next((i for i in items if i["target_location"] == "Garage"), None)
  1642. assert our_item is not None
  1643. assert our_item["target_model"] == "P1S"
  1644. @pytest.mark.asyncio
  1645. @pytest.mark.integration
  1646. async def test_update_queue_item_target_location(self, async_client: AsyncClient, queue_item_factory, db_session):
  1647. """Verify target_location can be updated on existing queue item."""
  1648. item = await queue_item_factory(
  1649. printer_id=None,
  1650. target_model="X1C",
  1651. target_location="Office",
  1652. )
  1653. response = await async_client.patch(
  1654. f"/api/v1/queue/{item.id}",
  1655. json={"target_location": "Basement"},
  1656. )
  1657. assert response.status_code == 200
  1658. result = response.json()
  1659. assert result["target_location"] == "Basement"
  1660. @pytest.mark.asyncio
  1661. @pytest.mark.integration
  1662. async def test_clear_target_location(self, async_client: AsyncClient, queue_item_factory, db_session):
  1663. """Verify target_location can be cleared (set to None)."""
  1664. item = await queue_item_factory(
  1665. printer_id=None,
  1666. target_model="X1C",
  1667. target_location="Office",
  1668. )
  1669. # Note: Setting to empty string should clear it
  1670. response = await async_client.patch(
  1671. f"/api/v1/queue/{item.id}",
  1672. json={"target_location": None},
  1673. )
  1674. assert response.status_code == 200
  1675. result = response.json()
  1676. assert result["target_location"] is None
  1677. # ------------------------------------------------------------------
  1678. # Cross-model dispatch gate (#2578): a G-code 3MF sliced for one model
  1679. # must not be queued for model-based dispatch to an incompatible model.
  1680. # ------------------------------------------------------------------
  1681. @pytest.mark.asyncio
  1682. @pytest.mark.integration
  1683. async def test_add_to_queue_rejects_cross_model_mismatch(
  1684. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1685. ):
  1686. """X1C-sliced archive + target_model=H2D must be rejected (#2578)."""
  1687. await printer_factory(model="H2D")
  1688. archive = await archive_factory(sliced_for_model="X1C")
  1689. response = await async_client.post(
  1690. "/api/v1/queue/",
  1691. json={"target_model": "H2D", "archive_id": archive.id},
  1692. )
  1693. assert response.status_code == 400
  1694. assert "sliced for X1C" in response.json()["detail"]
  1695. @pytest.mark.asyncio
  1696. @pytest.mark.integration
  1697. async def test_add_to_queue_allows_gcode_family_target(
  1698. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1699. ):
  1700. """X1C-sliced G-code on a P1S is an intentional mixed-farm workflow —
  1701. same kinematics/volume family, must stay allowed."""
  1702. await printer_factory(model="P1S")
  1703. archive = await archive_factory(sliced_for_model="X1C")
  1704. response = await async_client.post(
  1705. "/api/v1/queue/",
  1706. json={"target_model": "P1S", "archive_id": archive.id},
  1707. )
  1708. assert response.status_code == 200
  1709. assert response.json()["target_model"] == "P1S"
  1710. @pytest.mark.asyncio
  1711. @pytest.mark.integration
  1712. async def test_add_to_queue_without_sliced_metadata_not_blocked(
  1713. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1714. ):
  1715. """Legacy archives without sliced_for_model can't be validated — must keep working."""
  1716. await printer_factory(model="H2D")
  1717. archive = await archive_factory() # no sliced_for_model
  1718. response = await async_client.post(
  1719. "/api/v1/queue/",
  1720. json={"target_model": "H2D", "archive_id": archive.id},
  1721. )
  1722. assert response.status_code == 200
  1723. @pytest.mark.asyncio
  1724. @pytest.mark.integration
  1725. async def test_update_rejects_cross_model_mismatch(
  1726. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory, db_session
  1727. ):
  1728. """Editing an item must not be able to introduce an incompatible target either."""
  1729. await printer_factory(model="X1C")
  1730. await printer_factory(model="H2D")
  1731. archive = await archive_factory(sliced_for_model="X1C")
  1732. item = await queue_item_factory(printer_id=None, target_model="X1C", archive_id=archive.id)
  1733. response = await async_client.patch(f"/api/v1/queue/{item.id}", json={"target_model": "H2D"})
  1734. assert response.status_code == 400
  1735. assert "sliced for X1C" in response.json()["detail"]
  1736. @pytest.mark.asyncio
  1737. @pytest.mark.integration
  1738. async def test_update_can_fix_stale_mismatched_target(
  1739. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory, db_session
  1740. ):
  1741. """A pre-fix DB row with a wrong target (the reporter's rows 78-82) must be
  1742. repairable by editing the target back to the sliced-for model."""
  1743. await printer_factory(model="X1C")
  1744. archive = await archive_factory(sliced_for_model="X1C")
  1745. # Stale mismatched row written directly to the DB (bypasses the API gate)
  1746. item = await queue_item_factory(printer_id=None, target_model="H2D", archive_id=archive.id)
  1747. response = await async_client.patch(f"/api/v1/queue/{item.id}", json={"target_model": "X1C"})
  1748. assert response.status_code == 200
  1749. assert response.json()["target_model"] == "X1C"
  1750. class TestAbortedStatusNormalisation:
  1751. """Tests for issue #558: 'aborted' queue status causes 500 error."""
  1752. @pytest.fixture
  1753. async def printer_factory(self, db_session):
  1754. """Factory to create test printers."""
  1755. _counter = [0]
  1756. async def _create_printer(**kwargs):
  1757. from backend.app.models.printer import Printer
  1758. _counter[0] += 1
  1759. counter = _counter[0]
  1760. defaults = {
  1761. "name": f"Abort Test Printer {counter}",
  1762. "ip_address": f"192.168.1.{60 + counter}",
  1763. "serial_number": f"TESTABORT{counter:04d}",
  1764. "access_code": "12345678",
  1765. "model": "P1S",
  1766. }
  1767. defaults.update(kwargs)
  1768. printer = Printer(**defaults)
  1769. db_session.add(printer)
  1770. await db_session.commit()
  1771. await db_session.refresh(printer)
  1772. return printer
  1773. return _create_printer
  1774. @pytest.fixture
  1775. async def archive_factory(self, db_session):
  1776. """Factory to create test archives."""
  1777. _counter = [0]
  1778. async def _create_archive(**kwargs):
  1779. from backend.app.models.archive import PrintArchive
  1780. _counter[0] += 1
  1781. counter = _counter[0]
  1782. defaults = {
  1783. "filename": f"abort_test_{counter}.3mf",
  1784. "print_name": f"Abort Test Print {counter}",
  1785. "file_path": f"/tmp/abort_test_{counter}.3mf",
  1786. "file_size": 1024,
  1787. "content_hash": f"aborthash{counter:06d}",
  1788. "status": "completed",
  1789. }
  1790. defaults.update(kwargs)
  1791. archive = PrintArchive(**defaults)
  1792. db_session.add(archive)
  1793. await db_session.commit()
  1794. await db_session.refresh(archive)
  1795. return archive
  1796. return _create_archive
  1797. @pytest.fixture
  1798. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  1799. """Factory to create test queue items."""
  1800. _counter = [0]
  1801. async def _create_queue_item(**kwargs):
  1802. from backend.app.models.print_queue import PrintQueueItem
  1803. _counter[0] += 1
  1804. counter = _counter[0]
  1805. if "printer_id" not in kwargs:
  1806. printer = await printer_factory()
  1807. kwargs["printer_id"] = printer.id
  1808. if "archive_id" not in kwargs:
  1809. archive = await archive_factory()
  1810. kwargs["archive_id"] = archive.id
  1811. defaults = {
  1812. "status": "pending",
  1813. "position": counter,
  1814. }
  1815. defaults.update(kwargs)
  1816. item = PrintQueueItem(**defaults)
  1817. db_session.add(item)
  1818. await db_session.commit()
  1819. await db_session.refresh(item)
  1820. return item
  1821. return _create_queue_item
  1822. @pytest.mark.asyncio
  1823. @pytest.mark.integration
  1824. async def test_on_print_complete_normalises_aborted_to_cancelled(self, queue_item_factory, db_session):
  1825. """Verify the completion handler maps 'aborted' → 'cancelled' for queue items."""
  1826. import asyncio
  1827. from unittest.mock import AsyncMock, MagicMock, patch
  1828. item = await queue_item_factory(status="printing")
  1829. # Build a mock session whose execute returns our item
  1830. mock_result = MagicMock()
  1831. mock_result.scalars.return_value.all.return_value = [item]
  1832. mock_session = AsyncMock()
  1833. mock_session.__aenter__ = AsyncMock(return_value=mock_session)
  1834. mock_session.__aexit__ = AsyncMock(return_value=False)
  1835. mock_session.execute = AsyncMock(return_value=mock_result)
  1836. mock_session.commit = AsyncMock()
  1837. tasks_before = set(asyncio.all_tasks())
  1838. with (
  1839. patch("backend.app.main.async_session", return_value=mock_session),
  1840. patch("backend.app.core.database.async_session", return_value=mock_session),
  1841. patch("backend.app.main.ws_manager") as mock_ws,
  1842. patch("backend.app.main.mqtt_relay") as mock_relay,
  1843. patch("backend.app.main.notification_service") as mock_notif,
  1844. patch("backend.app.main.smart_plug_manager") as mock_plug,
  1845. patch("backend.app.main.printer_manager") as mock_pm,
  1846. ):
  1847. mock_ws.send_print_complete = AsyncMock()
  1848. mock_ws.broadcast = AsyncMock()
  1849. mock_relay.on_print_complete = AsyncMock()
  1850. mock_relay.on_queue_job_completed = AsyncMock()
  1851. mock_notif.on_print_complete = AsyncMock()
  1852. mock_plug.on_print_complete = AsyncMock()
  1853. mock_pm.get_printer.return_value = None
  1854. from backend.app.main import on_print_complete
  1855. await on_print_complete(
  1856. item.printer_id,
  1857. {
  1858. "status": "aborted",
  1859. "filename": "test.gcode",
  1860. "subtask_name": "Test",
  1861. "timelapse_was_active": False,
  1862. },
  1863. )
  1864. # Cancel background tasks before leaving mock context
  1865. for task in asyncio.all_tasks() - tasks_before:
  1866. task.cancel()
  1867. try:
  1868. await task
  1869. except (asyncio.CancelledError, Exception):
  1870. pass
  1871. # The item status should be normalised to 'cancelled', not 'aborted'
  1872. assert item.status == "cancelled"
  1873. @pytest.mark.asyncio
  1874. @pytest.mark.integration
  1875. async def test_startup_fixup_converts_aborted_to_cancelled(self, queue_item_factory, db_session):
  1876. """Verify the startup fixup converts existing 'aborted' rows to 'cancelled'."""
  1877. from sqlalchemy import select
  1878. from backend.app.models.print_queue import PrintQueueItem
  1879. # Create items with various statuses including 'aborted'
  1880. item_aborted = await queue_item_factory(status="pending")
  1881. item_pending = await queue_item_factory(status="pending")
  1882. # Manually set the invalid status
  1883. item_aborted.status = "aborted"
  1884. db_session.add(item_aborted)
  1885. await db_session.commit()
  1886. # Run the fixup query (same logic as lifespan)
  1887. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  1888. aborted_items = result.scalars().all()
  1889. for i in aborted_items:
  1890. i.status = "cancelled"
  1891. await db_session.commit()
  1892. # Verify: no more 'aborted' items
  1893. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  1894. assert len(result.scalars().all()) == 0
  1895. # The previously aborted item should now be 'cancelled'
  1896. await db_session.refresh(item_aborted)
  1897. assert item_aborted.status == "cancelled"
  1898. # The pending item should be unchanged
  1899. await db_session.refresh(item_pending)
  1900. assert item_pending.status == "pending"
  1901. @pytest.mark.asyncio
  1902. @pytest.mark.integration
  1903. async def test_completed_status_passes_through_unchanged(self, queue_item_factory, db_session):
  1904. """Verify normal statuses like 'completed' are not affected by normalisation."""
  1905. import asyncio
  1906. from unittest.mock import AsyncMock, MagicMock, patch
  1907. item = await queue_item_factory(status="printing")
  1908. mock_result = MagicMock()
  1909. mock_result.scalars.return_value.all.return_value = [item]
  1910. mock_session = AsyncMock()
  1911. mock_session.__aenter__ = AsyncMock(return_value=mock_session)
  1912. mock_session.__aexit__ = AsyncMock(return_value=False)
  1913. mock_session.execute = AsyncMock(return_value=mock_result)
  1914. mock_session.commit = AsyncMock()
  1915. tasks_before = set(asyncio.all_tasks())
  1916. with (
  1917. patch("backend.app.main.async_session", return_value=mock_session),
  1918. patch("backend.app.core.database.async_session", return_value=mock_session),
  1919. patch("backend.app.main.ws_manager") as mock_ws,
  1920. patch("backend.app.main.mqtt_relay") as mock_relay,
  1921. patch("backend.app.main.notification_service") as mock_notif,
  1922. patch("backend.app.main.smart_plug_manager") as mock_plug,
  1923. patch("backend.app.main.printer_manager") as mock_pm,
  1924. ):
  1925. mock_ws.send_print_complete = AsyncMock()
  1926. mock_ws.broadcast = AsyncMock()
  1927. mock_relay.on_print_complete = AsyncMock()
  1928. mock_relay.on_queue_job_completed = AsyncMock()
  1929. mock_notif.on_print_complete = AsyncMock()
  1930. mock_plug.on_print_complete = AsyncMock()
  1931. mock_pm.get_printer.return_value = None
  1932. from backend.app.main import on_print_complete
  1933. await on_print_complete(
  1934. item.printer_id,
  1935. {
  1936. "status": "completed",
  1937. "filename": "test.gcode",
  1938. "subtask_name": "Test",
  1939. "timelapse_was_active": False,
  1940. },
  1941. )
  1942. # Cancel background tasks before leaving mock context
  1943. for task in asyncio.all_tasks() - tasks_before:
  1944. task.cancel()
  1945. try:
  1946. await task
  1947. except (asyncio.CancelledError, Exception):
  1948. pass
  1949. assert item.status == "completed"
  1950. # ========================================================================
  1951. # Library file usage tracking on print completion (#1008)
  1952. #
  1953. # These exercise the _bump_library_file_usage_if_completed helper directly
  1954. # rather than invoking the whole on_print_complete handler — that path
  1955. # spawns background asyncio tasks (notifications, MQTT relay, smart-plug)
  1956. # that are expensive to mock and have nothing to do with the bump logic.
  1957. # ========================================================================
  1958. @pytest.mark.asyncio
  1959. @pytest.mark.integration
  1960. async def test_bump_library_file_usage_on_completed(self, printer_factory, db_session):
  1961. """Successful completion increments print_count and stamps last_printed_at."""
  1962. from datetime import datetime, timezone
  1963. from backend.app.main import _bump_library_file_usage_if_completed
  1964. from backend.app.models.library import LibraryFile
  1965. from backend.app.models.print_queue import PrintQueueItem
  1966. printer = await printer_factory()
  1967. lib_file = LibraryFile(
  1968. filename="benchy.gcode.3mf",
  1969. file_path="/data/library/benchy.gcode.3mf",
  1970. file_type="gcode.3mf",
  1971. file_size=1024,
  1972. print_count=0,
  1973. last_printed_at=None,
  1974. )
  1975. db_session.add(lib_file)
  1976. await db_session.commit()
  1977. await db_session.refresh(lib_file)
  1978. item = PrintQueueItem(
  1979. printer_id=printer.id,
  1980. library_file_id=lib_file.id,
  1981. status="printing",
  1982. position=1,
  1983. )
  1984. before = datetime.now(timezone.utc).replace(tzinfo=None)
  1985. await _bump_library_file_usage_if_completed(db_session, item, "completed")
  1986. await db_session.commit()
  1987. await db_session.refresh(lib_file)
  1988. assert lib_file.print_count == 1
  1989. assert lib_file.last_printed_at is not None
  1990. assert lib_file.last_printed_at >= before
  1991. @pytest.mark.asyncio
  1992. @pytest.mark.integration
  1993. async def test_bump_library_file_usage_repeated_prints_increment_count(self, printer_factory, db_session):
  1994. """Each successful completion bumps print_count cumulatively."""
  1995. from backend.app.main import _bump_library_file_usage_if_completed
  1996. from backend.app.models.library import LibraryFile
  1997. from backend.app.models.print_queue import PrintQueueItem
  1998. printer = await printer_factory()
  1999. lib_file = LibraryFile(
  2000. filename="repeat.gcode.3mf",
  2001. file_path="/data/library/repeat.gcode.3mf",
  2002. file_type="gcode.3mf",
  2003. file_size=1024,
  2004. print_count=0,
  2005. )
  2006. db_session.add(lib_file)
  2007. await db_session.commit()
  2008. await db_session.refresh(lib_file)
  2009. item = PrintQueueItem(
  2010. printer_id=printer.id,
  2011. library_file_id=lib_file.id,
  2012. status="printing",
  2013. position=1,
  2014. )
  2015. for _ in range(3):
  2016. await _bump_library_file_usage_if_completed(db_session, item, "completed")
  2017. await db_session.commit()
  2018. await db_session.refresh(lib_file)
  2019. assert lib_file.print_count == 3
  2020. @pytest.mark.asyncio
  2021. @pytest.mark.integration
  2022. @pytest.mark.parametrize("terminal_status", ["failed", "cancelled"])
  2023. async def test_bump_library_file_usage_skips_non_completed(self, printer_factory, db_session, terminal_status):
  2024. """Failed and cancelled prints must NOT count as usage."""
  2025. from backend.app.main import _bump_library_file_usage_if_completed
  2026. from backend.app.models.library import LibraryFile
  2027. from backend.app.models.print_queue import PrintQueueItem
  2028. printer = await printer_factory()
  2029. lib_file = LibraryFile(
  2030. filename="broken.gcode.3mf",
  2031. file_path="/data/library/broken.gcode.3mf",
  2032. file_type="gcode.3mf",
  2033. file_size=1024,
  2034. print_count=0,
  2035. last_printed_at=None,
  2036. )
  2037. db_session.add(lib_file)
  2038. await db_session.commit()
  2039. await db_session.refresh(lib_file)
  2040. item = PrintQueueItem(
  2041. printer_id=printer.id,
  2042. library_file_id=lib_file.id,
  2043. status="printing",
  2044. position=1,
  2045. )
  2046. await _bump_library_file_usage_if_completed(db_session, item, terminal_status)
  2047. await db_session.commit()
  2048. await db_session.refresh(lib_file)
  2049. assert lib_file.print_count == 0
  2050. assert lib_file.last_printed_at is None
  2051. @pytest.mark.asyncio
  2052. @pytest.mark.integration
  2053. async def test_bump_library_file_usage_skips_when_no_library_file_id(
  2054. self, printer_factory, archive_factory, db_session
  2055. ):
  2056. """Queue items without library_file_id (e.g. archive reprints) are a no-op."""
  2057. from backend.app.main import _bump_library_file_usage_if_completed
  2058. from backend.app.models.print_queue import PrintQueueItem
  2059. printer = await printer_factory()
  2060. archive = await archive_factory()
  2061. item = PrintQueueItem(
  2062. printer_id=printer.id,
  2063. library_file_id=None,
  2064. archive_id=archive.id,
  2065. status="printing",
  2066. position=1,
  2067. )
  2068. # Must not raise.
  2069. await _bump_library_file_usage_if_completed(db_session, item, "completed")
  2070. # ========================================================================
  2071. # Batch quantity tests
  2072. # ========================================================================
  2073. @pytest.mark.asyncio
  2074. @pytest.mark.integration
  2075. async def test_add_to_queue_quantity_default(
  2076. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2077. ):
  2078. """Verify quantity=1 (default) creates a single item with no batch."""
  2079. printer = await printer_factory()
  2080. archive = await archive_factory()
  2081. data = {
  2082. "printer_id": printer.id,
  2083. "archive_id": archive.id,
  2084. }
  2085. response = await async_client.post("/api/v1/queue/", json=data)
  2086. assert response.status_code == 200
  2087. result = response.json()
  2088. assert result["batch_id"] is None
  2089. assert result["batch_name"] is None
  2090. @pytest.mark.asyncio
  2091. @pytest.mark.integration
  2092. async def test_add_to_queue_quantity_one_explicit(
  2093. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2094. ):
  2095. """Verify quantity=1 explicitly creates a single item with no batch."""
  2096. printer = await printer_factory()
  2097. archive = await archive_factory()
  2098. data = {
  2099. "printer_id": printer.id,
  2100. "archive_id": archive.id,
  2101. "quantity": 1,
  2102. }
  2103. response = await async_client.post("/api/v1/queue/", json=data)
  2104. assert response.status_code == 200
  2105. result = response.json()
  2106. assert result["batch_id"] is None
  2107. assert result["batch_name"] is None
  2108. @pytest.mark.asyncio
  2109. @pytest.mark.integration
  2110. async def test_add_to_queue_quantity_creates_batch(
  2111. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2112. ):
  2113. """Verify quantity > 1 creates a batch and multiple queue items."""
  2114. printer = await printer_factory()
  2115. archive = await archive_factory()
  2116. data = {
  2117. "printer_id": printer.id,
  2118. "archive_id": archive.id,
  2119. "quantity": 3,
  2120. }
  2121. response = await async_client.post("/api/v1/queue/", json=data)
  2122. assert response.status_code == 200
  2123. result = response.json()
  2124. # First item is returned, linked to a batch
  2125. assert result["batch_id"] is not None
  2126. assert result["batch_name"] is not None
  2127. assert "×3" in result["batch_name"]
  2128. # Verify all 3 items were created
  2129. list_response = await async_client.get("/api/v1/queue/")
  2130. items = list_response.json()
  2131. batch_items = [i for i in items if i["batch_id"] == result["batch_id"]]
  2132. assert len(batch_items) == 3
  2133. # All items should have the same settings
  2134. for item in batch_items:
  2135. assert item["printer_id"] == printer.id
  2136. assert item["archive_id"] == archive.id
  2137. assert item["status"] == "pending"
  2138. @pytest.mark.asyncio
  2139. @pytest.mark.integration
  2140. async def test_add_to_queue_quantity_sequential_positions(
  2141. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2142. ):
  2143. """Verify batch items get sequential positions."""
  2144. printer = await printer_factory()
  2145. archive = await archive_factory()
  2146. data = {
  2147. "printer_id": printer.id,
  2148. "archive_id": archive.id,
  2149. "quantity": 3,
  2150. }
  2151. response = await async_client.post("/api/v1/queue/", json=data)
  2152. assert response.status_code == 200
  2153. batch_id = response.json()["batch_id"]
  2154. list_response = await async_client.get("/api/v1/queue/")
  2155. items = list_response.json()
  2156. batch_items = sorted(
  2157. [i for i in items if i["batch_id"] == batch_id],
  2158. key=lambda i: i["position"],
  2159. )
  2160. positions = [i["position"] for i in batch_items]
  2161. assert positions == [positions[0], positions[0] + 1, positions[0] + 2]
  2162. @pytest.mark.asyncio
  2163. @pytest.mark.integration
  2164. async def test_add_to_queue_insert_position_shifts_existing_items(
  2165. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2166. ):
  2167. """Verify priority insertion shifts existing pending items in the same printer queue."""
  2168. printer = await printer_factory()
  2169. first = await archive_factory(print_name="First")
  2170. second = await archive_factory(print_name="Second")
  2171. priority = await archive_factory(print_name="Priority")
  2172. assert (
  2173. await async_client.post("/api/v1/queue/", json={"printer_id": printer.id, "archive_id": first.id})
  2174. ).status_code == 200
  2175. assert (
  2176. await async_client.post("/api/v1/queue/", json={"printer_id": printer.id, "archive_id": second.id})
  2177. ).status_code == 200
  2178. response = await async_client.post(
  2179. "/api/v1/queue/",
  2180. json={
  2181. "printer_id": printer.id,
  2182. "archive_id": priority.id,
  2183. "insert_position": 1,
  2184. },
  2185. )
  2186. assert response.status_code == 200
  2187. list_response = await async_client.get(f"/api/v1/queue/?printer_id={printer.id}")
  2188. items = sorted(list_response.json(), key=lambda item: item["position"])
  2189. assert [item["archive_id"] for item in items[:3]] == [priority.id, first.id, second.id]
  2190. assert [item["position"] for item in items[:3]] == [1, 2, 3]
  2191. @pytest.mark.asyncio
  2192. @pytest.mark.integration
  2193. async def test_add_to_queue_insert_position_quantity_shifts_existing_by_quantity(
  2194. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2195. ):
  2196. """ASAP batch insertion shifts existing pending items by the inserted quantity."""
  2197. printer = await printer_factory()
  2198. first = await archive_factory(print_name="First")
  2199. second = await archive_factory(print_name="Second")
  2200. priority = await archive_factory(print_name="Priority")
  2201. assert (
  2202. await async_client.post("/api/v1/queue/", json={"printer_id": printer.id, "archive_id": first.id})
  2203. ).status_code == 200
  2204. assert (
  2205. await async_client.post("/api/v1/queue/", json={"printer_id": printer.id, "archive_id": second.id})
  2206. ).status_code == 200
  2207. response = await async_client.post(
  2208. "/api/v1/queue/",
  2209. json={
  2210. "printer_id": printer.id,
  2211. "archive_id": priority.id,
  2212. "quantity": 3,
  2213. "insert_position": 1,
  2214. },
  2215. )
  2216. assert response.status_code == 200
  2217. batch_id = response.json()["batch_id"]
  2218. list_response = await async_client.get(f"/api/v1/queue/?printer_id={printer.id}")
  2219. items = sorted(list_response.json(), key=lambda item: item["position"])
  2220. assert [item["archive_id"] for item in items] == [
  2221. priority.id,
  2222. priority.id,
  2223. priority.id,
  2224. first.id,
  2225. second.id,
  2226. ]
  2227. assert [item["position"] for item in items] == [1, 2, 3, 4, 5]
  2228. assert [item["batch_id"] for item in items[:3]] == [batch_id, batch_id, batch_id]
  2229. @pytest.mark.asyncio
  2230. @pytest.mark.integration
  2231. async def test_add_to_queue_insert_position_scopes_unassigned_items(
  2232. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2233. ):
  2234. """Unassigned inserts shift only the unassigned queue scope."""
  2235. printer = await printer_factory()
  2236. unassigned_first = await archive_factory(print_name="Unassigned First")
  2237. unassigned_second = await archive_factory(print_name="Unassigned Second")
  2238. assigned = await archive_factory(print_name="Assigned")
  2239. priority = await archive_factory(print_name="Unassigned Priority")
  2240. assert (await async_client.post("/api/v1/queue/", json={"archive_id": unassigned_first.id})).status_code == 200
  2241. assert (await async_client.post("/api/v1/queue/", json={"archive_id": unassigned_second.id})).status_code == 200
  2242. assigned_response = await async_client.post(
  2243. "/api/v1/queue/",
  2244. json={"printer_id": printer.id, "archive_id": assigned.id},
  2245. )
  2246. assert assigned_response.status_code == 200
  2247. assert assigned_response.json()["position"] == 1
  2248. response = await async_client.post(
  2249. "/api/v1/queue/",
  2250. json={
  2251. "archive_id": priority.id,
  2252. "insert_position": 1,
  2253. },
  2254. )
  2255. assert response.status_code == 200
  2256. unassigned_response = await async_client.get("/api/v1/queue/?printer_id=-1")
  2257. unassigned_items = sorted(unassigned_response.json(), key=lambda item: item["position"])
  2258. assert [item["archive_id"] for item in unassigned_items] == [
  2259. priority.id,
  2260. unassigned_first.id,
  2261. unassigned_second.id,
  2262. ]
  2263. assert [item["position"] for item in unassigned_items] == [1, 2, 3]
  2264. assigned_scope_response = await async_client.get(f"/api/v1/queue/?printer_id={printer.id}&target_model=NONE")
  2265. assigned_items = sorted(assigned_scope_response.json(), key=lambda item: item["position"])
  2266. assert [item["archive_id"] for item in assigned_items] == [assigned.id]
  2267. assert [item["position"] for item in assigned_items] == [1]
  2268. @pytest.mark.asyncio
  2269. @pytest.mark.integration
  2270. async def test_add_to_queue_insert_position_greater_than_max_appends_without_gap(
  2271. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2272. ):
  2273. """Oversized explicit insert_position appends at max+1 instead of creating sparse positions."""
  2274. printer = await printer_factory()
  2275. first = await archive_factory(print_name="First")
  2276. second = await archive_factory(print_name="Second")
  2277. appended = await archive_factory(print_name="Append")
  2278. assert (
  2279. await async_client.post("/api/v1/queue/", json={"printer_id": printer.id, "archive_id": first.id})
  2280. ).status_code == 200
  2281. assert (
  2282. await async_client.post("/api/v1/queue/", json={"printer_id": printer.id, "archive_id": second.id})
  2283. ).status_code == 200
  2284. response = await async_client.post(
  2285. "/api/v1/queue/",
  2286. json={
  2287. "printer_id": printer.id,
  2288. "archive_id": appended.id,
  2289. "insert_position": 99,
  2290. },
  2291. )
  2292. assert response.status_code == 200
  2293. assert response.json()["position"] == 3
  2294. list_response = await async_client.get(f"/api/v1/queue/?printer_id={printer.id}")
  2295. items = sorted(list_response.json(), key=lambda item: item["position"])
  2296. assert [item["archive_id"] for item in items] == [first.id, second.id, appended.id]
  2297. assert [item["position"] for item in items] == [1, 2, 3]
  2298. @pytest.mark.asyncio
  2299. @pytest.mark.integration
  2300. async def test_add_to_queue_consecutive_asap_inserts_stack_in_submission_order(
  2301. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2302. ):
  2303. """Consecutive ASAP inserts to the same printer preserve the client submission order."""
  2304. printer = await printer_factory()
  2305. existing = await archive_factory(print_name="Existing")
  2306. first_asap = await archive_factory(print_name="First ASAP")
  2307. second_asap = await archive_factory(print_name="Second ASAP")
  2308. assert (
  2309. await async_client.post("/api/v1/queue/", json={"printer_id": printer.id, "archive_id": existing.id})
  2310. ).status_code == 200
  2311. first_response = await async_client.post(
  2312. "/api/v1/queue/",
  2313. json={
  2314. "printer_id": printer.id,
  2315. "archive_id": first_asap.id,
  2316. "insert_position": 1,
  2317. },
  2318. )
  2319. assert first_response.status_code == 200
  2320. second_response = await async_client.post(
  2321. "/api/v1/queue/",
  2322. json={
  2323. "printer_id": printer.id,
  2324. "archive_id": second_asap.id,
  2325. "insert_position": 2,
  2326. },
  2327. )
  2328. assert second_response.status_code == 200
  2329. list_response = await async_client.get(f"/api/v1/queue/?printer_id={printer.id}")
  2330. items = sorted(list_response.json(), key=lambda item: item["position"])
  2331. assert [item["archive_id"] for item in items] == [first_asap.id, second_asap.id, existing.id]
  2332. assert [item["position"] for item in items] == [1, 2, 3]
  2333. @pytest.mark.asyncio
  2334. @pytest.mark.integration
  2335. async def test_add_to_queue_quantity_with_print_options(
  2336. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2337. ):
  2338. """Verify print options are applied to all batch items."""
  2339. printer = await printer_factory()
  2340. archive = await archive_factory()
  2341. data = {
  2342. "printer_id": printer.id,
  2343. "archive_id": archive.id,
  2344. "quantity": 2,
  2345. "bed_levelling": "off",
  2346. "timelapse": True,
  2347. }
  2348. response = await async_client.post("/api/v1/queue/", json=data)
  2349. assert response.status_code == 200
  2350. batch_id = response.json()["batch_id"]
  2351. list_response = await async_client.get("/api/v1/queue/")
  2352. batch_items = [i for i in list_response.json() if i["batch_id"] == batch_id]
  2353. assert len(batch_items) == 2
  2354. for item in batch_items:
  2355. assert item["bed_levelling"] == "off"
  2356. assert item["timelapse"] is True
  2357. @pytest.mark.asyncio
  2358. @pytest.mark.integration
  2359. async def test_get_batch(self, async_client: AsyncClient, printer_factory, archive_factory, db_session):
  2360. """Verify batch can be retrieved with progress stats."""
  2361. printer = await printer_factory()
  2362. archive = await archive_factory()
  2363. # Create a batch of 3
  2364. data = {
  2365. "printer_id": printer.id,
  2366. "archive_id": archive.id,
  2367. "quantity": 3,
  2368. }
  2369. response = await async_client.post("/api/v1/queue/", json=data)
  2370. batch_id = response.json()["batch_id"]
  2371. # Get batch
  2372. response = await async_client.get(f"/api/v1/queue/batches/{batch_id}")
  2373. assert response.status_code == 200
  2374. result = response.json()
  2375. assert result["id"] == batch_id
  2376. assert result["quantity"] == 3
  2377. assert result["status"] == "active"
  2378. assert result["pending_count"] == 3
  2379. assert result["printing_count"] == 0
  2380. assert result["completed_count"] == 0
  2381. @pytest.mark.asyncio
  2382. @pytest.mark.integration
  2383. async def test_list_batches(self, async_client: AsyncClient, printer_factory, archive_factory, db_session):
  2384. """Verify batches can be listed."""
  2385. printer = await printer_factory()
  2386. archive = await archive_factory()
  2387. # Create two batches
  2388. for qty in [2, 3]:
  2389. await async_client.post(
  2390. "/api/v1/queue/",
  2391. json={"printer_id": printer.id, "archive_id": archive.id, "quantity": qty},
  2392. )
  2393. response = await async_client.get("/api/v1/queue/batches")
  2394. assert response.status_code == 200
  2395. batches = response.json()
  2396. assert len(batches) >= 2
  2397. @pytest.mark.asyncio
  2398. @pytest.mark.integration
  2399. async def test_cancel_batch(self, async_client: AsyncClient, printer_factory, archive_factory, db_session):
  2400. """Verify cancelling a batch cancels all pending items."""
  2401. printer = await printer_factory()
  2402. archive = await archive_factory()
  2403. data = {
  2404. "printer_id": printer.id,
  2405. "archive_id": archive.id,
  2406. "quantity": 3,
  2407. }
  2408. response = await async_client.post("/api/v1/queue/", json=data)
  2409. batch_id = response.json()["batch_id"]
  2410. # Cancel the batch
  2411. response = await async_client.delete(f"/api/v1/queue/batches/{batch_id}")
  2412. assert response.status_code == 200
  2413. # Verify all items are cancelled
  2414. list_response = await async_client.get("/api/v1/queue/")
  2415. batch_items = [i for i in list_response.json() if i["batch_id"] == batch_id]
  2416. for item in batch_items:
  2417. assert item["status"] == "cancelled"
  2418. # Verify batch status
  2419. batch_response = await async_client.get(f"/api/v1/queue/batches/{batch_id}")
  2420. assert batch_response.json()["status"] == "cancelled"
  2421. @pytest.mark.asyncio
  2422. @pytest.mark.integration
  2423. async def test_get_batch_not_found(self, async_client: AsyncClient):
  2424. """Verify 404 for non-existent batch."""
  2425. response = await async_client.get("/api/v1/queue/batches/9999")
  2426. assert response.status_code == 404
  2427. # ========================================================================
  2428. # Queue redesign: create-empty + group-existing + ungroup
  2429. # ========================================================================
  2430. @pytest.mark.asyncio
  2431. @pytest.mark.integration
  2432. async def test_create_empty_batch_for_client_side_grouping(
  2433. self, async_client: AsyncClient, printer_factory, archive_factory
  2434. ):
  2435. """Verify POST /queue/batches without item_ids creates an empty batch
  2436. whose id can be passed on subsequent /queue/ POSTs (the multi-plate
  2437. auto-batch flow). Subsequent items must end up with the same batch_id."""
  2438. printer = await printer_factory()
  2439. archive = await archive_factory()
  2440. # 1. Pre-create batch
  2441. batch_resp = await async_client.post(
  2442. "/api/v1/queue/batches",
  2443. json={"name": "Plates · 2 plates", "archive_id": archive.id},
  2444. )
  2445. assert batch_resp.status_code == 200
  2446. batch = batch_resp.json()
  2447. assert batch["status"] == "active"
  2448. batch_id = batch["id"]
  2449. # 2. Add two items referencing that batch
  2450. for plate_id in (1, 2):
  2451. item_resp = await async_client.post(
  2452. "/api/v1/queue/",
  2453. json={
  2454. "printer_id": printer.id,
  2455. "archive_id": archive.id,
  2456. "plate_id": plate_id,
  2457. "batch_id": batch_id,
  2458. },
  2459. )
  2460. assert item_resp.status_code == 200
  2461. assert item_resp.json()["batch_id"] == batch_id
  2462. # 3. Verify batch now has 2 pending children
  2463. list_resp = await async_client.get("/api/v1/queue/")
  2464. siblings = [i for i in list_resp.json() if i["batch_id"] == batch_id]
  2465. assert len(siblings) == 2
  2466. assert {i["plate_id"] for i in siblings} == {1, 2}
  2467. @pytest.mark.asyncio
  2468. @pytest.mark.integration
  2469. async def test_group_existing_items_as_batch(
  2470. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory
  2471. ):
  2472. """Verify POST /queue/batches with item_ids assigns batch_id to
  2473. existing pending items (the 'Group as batch' UI action)."""
  2474. printer = await printer_factory()
  2475. archive = await archive_factory()
  2476. item_a = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="pending")
  2477. item_b = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="pending")
  2478. resp = await async_client.post(
  2479. "/api/v1/queue/batches",
  2480. json={"name": "Manual group", "item_ids": [item_a.id, item_b.id]},
  2481. )
  2482. assert resp.status_code == 200
  2483. batch_id = resp.json()["id"]
  2484. list_resp = await async_client.get("/api/v1/queue/")
  2485. grouped = [i for i in list_resp.json() if i["batch_id"] == batch_id]
  2486. assert {i["id"] for i in grouped} == {item_a.id, item_b.id}
  2487. @pytest.mark.asyncio
  2488. @pytest.mark.integration
  2489. async def test_group_skips_non_pending_items(
  2490. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory
  2491. ):
  2492. """Verify grouping doesn't pull in already-completed/cancelled items."""
  2493. printer = await printer_factory()
  2494. archive = await archive_factory()
  2495. pending = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="pending")
  2496. completed = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="completed")
  2497. resp = await async_client.post(
  2498. "/api/v1/queue/batches",
  2499. json={"name": "Mixed", "item_ids": [pending.id, completed.id]},
  2500. )
  2501. assert resp.status_code == 200
  2502. batch_id = resp.json()["id"]
  2503. list_resp = await async_client.get("/api/v1/queue/")
  2504. grouped = [i for i in list_resp.json() if i["batch_id"] == batch_id]
  2505. assert {i["id"] for i in grouped} == {pending.id}
  2506. @pytest.mark.asyncio
  2507. @pytest.mark.integration
  2508. async def test_create_batch_requires_name(self, async_client: AsyncClient):
  2509. """Verify empty / whitespace-only name is rejected with 400."""
  2510. resp = await async_client.post("/api/v1/queue/batches", json={"name": " "})
  2511. assert resp.status_code == 400
  2512. @pytest.mark.asyncio
  2513. @pytest.mark.integration
  2514. async def test_ungroup_batch_clears_batch_id_and_deletes_row(
  2515. self, async_client: AsyncClient, printer_factory, archive_factory
  2516. ):
  2517. """Verify POST /queue/batches/{id}/ungroup clears batch_id from all
  2518. members and deletes the batch row when nothing remains assigned."""
  2519. printer = await printer_factory()
  2520. archive = await archive_factory()
  2521. # Create batch with two items via the existing quantity flow
  2522. add_resp = await async_client.post(
  2523. "/api/v1/queue/",
  2524. json={"printer_id": printer.id, "archive_id": archive.id, "quantity": 2},
  2525. )
  2526. batch_id = add_resp.json()["batch_id"]
  2527. # Ungroup
  2528. ungroup_resp = await async_client.post(f"/api/v1/queue/batches/{batch_id}/ungroup")
  2529. assert ungroup_resp.status_code == 200
  2530. assert ungroup_resp.json()["ungrouped_count"] == 2
  2531. # Verify items still exist but no longer batched
  2532. list_resp = await async_client.get("/api/v1/queue/")
  2533. ex_members = [i for i in list_resp.json() if i["batch_id"] == batch_id]
  2534. assert ex_members == []
  2535. # Batch row was deleted
  2536. get_resp = await async_client.get(f"/api/v1/queue/batches/{batch_id}")
  2537. assert get_resp.status_code == 404
  2538. @pytest.mark.asyncio
  2539. @pytest.mark.integration
  2540. async def test_add_to_queue_with_unknown_batch_id_404(
  2541. self, async_client: AsyncClient, printer_factory, archive_factory
  2542. ):
  2543. """Verify addToQueue with a non-existent batch_id is rejected."""
  2544. printer = await printer_factory()
  2545. archive = await archive_factory()
  2546. resp = await async_client.post(
  2547. "/api/v1/queue/",
  2548. json={
  2549. "printer_id": printer.id,
  2550. "archive_id": archive.id,
  2551. "batch_id": 99999,
  2552. },
  2553. )
  2554. assert resp.status_code == 404
  2555. # ========================================================================
  2556. # Soft-deleted archive handling (#1348 follow-up)
  2557. # ========================================================================
  2558. @pytest.mark.asyncio
  2559. @pytest.mark.integration
  2560. async def test_soft_delete_archive_deletes_all_related_queue_items(
  2561. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory, db_session
  2562. ):
  2563. """Soft-deleting an archive removes every related queue item, regardless
  2564. of status (#1734). Pre-#1734 only ``pending`` rows were flipped to
  2565. ``cancelled`` and stayed in the DB, surprising users who expected the
  2566. queue lines to disappear with the archive — especially on multi-plate
  2567. Send All uploads (#1733), where ONE archive backed N queue items and
  2568. soft-deleting the archive left N "cancelled" rows behind. The change
  2569. keeps the printing guard (a row with ``status='printing'`` blocks the
  2570. delete one layer up at the API route), so we never delete the row of
  2571. an actively-running print here.
  2572. Print history lives in ``PrintLogEntry`` (FK ``ON DELETE SET NULL``) —
  2573. the audit trail survives independently of the queue rows.
  2574. """
  2575. from sqlalchemy import select
  2576. from backend.app.models.print_queue import PrintQueueItem
  2577. from backend.app.services.archive import ArchiveService
  2578. printer = await printer_factory()
  2579. archive = await archive_factory(thumbnail_path="archives/test/test/thumbnail.png")
  2580. pending = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="pending")
  2581. completed = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="completed")
  2582. service = ArchiveService(db_session)
  2583. assert await service.soft_delete_archive(archive.id) is True
  2584. # Every queue row that referenced this archive is gone — both the
  2585. # pending and the completed rows. Print history (PrintLogEntry) is
  2586. # the authoritative record and is preserved by the FK SET NULL.
  2587. remaining = (
  2588. (await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id.in_([pending.id, completed.id]))))
  2589. .scalars()
  2590. .all()
  2591. )
  2592. assert remaining == [], (
  2593. "Soft-deleting the archive must delete every related queue row, "
  2594. f"got {[(r.id, r.status) for r in remaining]} still present"
  2595. )
  2596. @pytest.mark.asyncio
  2597. @pytest.mark.integration
  2598. async def test_queue_api_hides_archive_surface_when_soft_deleted(
  2599. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory, db_session
  2600. ):
  2601. """Queue serializer must NOT populate archive_thumbnail / archive_name
  2602. when the archive is soft-deleted — otherwise the frontend renders a
  2603. broken <img> and 404-storms the thumbnail / plates / plate-thumbnail
  2604. endpoints. archive_deleted=True signals the soft-deleted state so
  2605. the UI can render a 'source deleted' badge."""
  2606. from datetime import datetime, timezone
  2607. printer = await printer_factory()
  2608. archive = await archive_factory(
  2609. print_name="Test Print",
  2610. thumbnail_path="archives/test/test/thumbnail.png",
  2611. deleted_at=datetime.now(timezone.utc), # Pre-soft-deleted
  2612. )
  2613. item = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="cancelled")
  2614. resp = await async_client.get("/api/v1/queue/")
  2615. assert resp.status_code == 200
  2616. body = resp.json()
  2617. row = next((r for r in body if r["id"] == item.id), None)
  2618. assert row is not None
  2619. assert row["archive_deleted"] is True
  2620. assert row["archive_thumbnail"] is None, "must not expose stale thumbnail path for soft-deleted archive"
  2621. assert row["archive_name"] is None
  2622. @pytest.mark.asyncio
  2623. @pytest.mark.integration
  2624. async def test_queue_api_still_exposes_archive_surface_when_live(
  2625. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory, db_session
  2626. ):
  2627. """Sanity guard: the soft-delete suppression must not affect live
  2628. archives. archive_name / archive_thumbnail still flow through and
  2629. archive_deleted stays False."""
  2630. printer = await printer_factory()
  2631. archive = await archive_factory(
  2632. print_name="Live Archive",
  2633. thumbnail_path="archives/test/live/thumbnail.png",
  2634. )
  2635. item = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="pending")
  2636. resp = await async_client.get("/api/v1/queue/")
  2637. assert resp.status_code == 200
  2638. row = next((r for r in resp.json() if r["id"] == item.id), None)
  2639. assert row is not None
  2640. assert row["archive_deleted"] is False
  2641. assert row["archive_name"] == "Live Archive"
  2642. assert row["archive_thumbnail"] == "archives/test/live/thumbnail.png"
  2643. class TestResumeQueueAfterFailure:
  2644. """Integration tests for POST /api/v1/queue/printer/{id}/resume (#1818)."""
  2645. @pytest.fixture
  2646. async def printer_factory(self, db_session):
  2647. _counter = [0]
  2648. async def _create_printer(**kwargs):
  2649. from backend.app.models.printer import Printer
  2650. _counter[0] += 1
  2651. counter = _counter[0]
  2652. defaults = {
  2653. "name": f"Resume Printer {counter}",
  2654. "ip_address": f"192.168.42.{100 + counter}",
  2655. "serial_number": f"RESUMESERIAL{counter:04d}",
  2656. "access_code": "12345678",
  2657. "model": "P1S",
  2658. }
  2659. defaults.update(kwargs)
  2660. printer = Printer(**defaults)
  2661. db_session.add(printer)
  2662. await db_session.commit()
  2663. await db_session.refresh(printer)
  2664. return printer
  2665. return _create_printer
  2666. @pytest.fixture
  2667. async def archive_factory(self, db_session):
  2668. _counter = [0]
  2669. async def _create_archive(**kwargs):
  2670. from backend.app.models.archive import PrintArchive
  2671. _counter[0] += 1
  2672. counter = _counter[0]
  2673. defaults = {
  2674. "filename": f"resume_print_{counter}.3mf",
  2675. "print_name": f"Resume Print {counter}",
  2676. "file_path": f"/tmp/resume_print_{counter}.3mf", # nosec B108
  2677. "file_size": 1024,
  2678. "content_hash": f"resumehash{counter:08d}",
  2679. "status": "completed",
  2680. }
  2681. defaults.update(kwargs)
  2682. archive = PrintArchive(**defaults)
  2683. db_session.add(archive)
  2684. await db_session.commit()
  2685. await db_session.refresh(archive)
  2686. return archive
  2687. return _create_archive
  2688. async def _add_item(self, db_session, printer, archive_factory, **kwargs):
  2689. from backend.app.models.print_queue import PrintQueueItem
  2690. archive = await archive_factory()
  2691. defaults = {
  2692. "printer_id": printer.id,
  2693. "archive_id": archive.id,
  2694. "status": "pending",
  2695. "require_previous_success": True,
  2696. }
  2697. defaults.update(kwargs)
  2698. item = PrintQueueItem(**defaults)
  2699. db_session.add(item)
  2700. await db_session.commit()
  2701. await db_session.refresh(item)
  2702. return item
  2703. @pytest.mark.asyncio
  2704. @pytest.mark.integration
  2705. async def test_resume_unknown_printer_returns_404(self, async_client: AsyncClient):
  2706. resp = await async_client.post("/api/v1/queue/printer/999999/resume")
  2707. assert resp.status_code == 404
  2708. @pytest.mark.asyncio
  2709. @pytest.mark.integration
  2710. async def test_resume_no_op_on_clean_queue(self, async_client: AsyncClient, printer_factory):
  2711. """Calling resume on a printer with no failures and no skipped items
  2712. returns zero counts — endpoint is idempotent and safe to spam."""
  2713. printer = await printer_factory()
  2714. resp = await async_client.post(f"/api/v1/queue/printer/{printer.id}/resume")
  2715. assert resp.status_code == 200
  2716. assert resp.json() == {"acknowledged": 0, "restored": 0}
  2717. @pytest.mark.asyncio
  2718. @pytest.mark.integration
  2719. async def test_resume_acknowledges_failed_and_restores_skipped(
  2720. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2721. ):
  2722. """Reporter's scenario: failed predecessor + N skipped downstream items.
  2723. Resume sets gate_acknowledged on the failure and flips skipped → pending."""
  2724. from sqlalchemy import select
  2725. from backend.app.models.print_queue import PrintQueueItem
  2726. printer = await printer_factory()
  2727. failed = await self._add_item(db_session, printer, archive_factory, status="failed")
  2728. skipped_1 = await self._add_item(
  2729. db_session,
  2730. printer,
  2731. archive_factory,
  2732. status="skipped",
  2733. error_message="Previous print failed or was aborted",
  2734. )
  2735. skipped_2 = await self._add_item(
  2736. db_session,
  2737. printer,
  2738. archive_factory,
  2739. status="skipped",
  2740. error_message="Previous print failed or was aborted",
  2741. )
  2742. resp = await async_client.post(f"/api/v1/queue/printer/{printer.id}/resume")
  2743. assert resp.status_code == 200
  2744. assert resp.json() == {"acknowledged": 1, "restored": 2}
  2745. failed_id = failed.id
  2746. skipped_ids = [skipped_1.id, skipped_2.id]
  2747. db_session.expire_all()
  2748. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id == failed_id))
  2749. assert result.scalar_one().gate_acknowledged is True
  2750. for sid in skipped_ids:
  2751. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id == sid))
  2752. row = result.scalar_one()
  2753. assert row.status == "pending"
  2754. assert row.error_message is None
  2755. assert row.completed_at is None
  2756. @pytest.mark.asyncio
  2757. @pytest.mark.integration
  2758. async def test_resume_preserves_skipped_items_with_other_reasons(
  2759. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2760. ):
  2761. """Skipped items whose error_message is something OTHER than the
  2762. gate string (e.g. filament-deficit promotion, future skip reasons)
  2763. must not be touched — they encode different user intent."""
  2764. from sqlalchemy import select
  2765. from backend.app.models.print_queue import PrintQueueItem
  2766. printer = await printer_factory()
  2767. gate_skip = await self._add_item(
  2768. db_session,
  2769. printer,
  2770. archive_factory,
  2771. status="skipped",
  2772. error_message="Previous print failed or was aborted",
  2773. )
  2774. other_skip = await self._add_item(
  2775. db_session,
  2776. printer,
  2777. archive_factory,
  2778. status="skipped",
  2779. error_message="User skipped via UI",
  2780. )
  2781. gate_id = gate_skip.id
  2782. other_id = other_skip.id
  2783. resp = await async_client.post(f"/api/v1/queue/printer/{printer.id}/resume")
  2784. assert resp.json() == {"acknowledged": 0, "restored": 1}
  2785. db_session.expire_all()
  2786. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id == gate_id))
  2787. assert result.scalar_one().status == "pending"
  2788. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id == other_id))
  2789. assert result.scalar_one().status == "skipped"
  2790. @pytest.mark.asyncio
  2791. @pytest.mark.integration
  2792. async def test_resume_scoped_to_printer(
  2793. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2794. ):
  2795. """A resume on printer A must not clear printer B's gate — farms run
  2796. each printer's queue independently."""
  2797. from sqlalchemy import select
  2798. from backend.app.models.print_queue import PrintQueueItem
  2799. p1 = await printer_factory()
  2800. p2 = await printer_factory()
  2801. failed_p1 = await self._add_item(db_session, p1, archive_factory, status="failed")
  2802. failed_p2 = await self._add_item(db_session, p2, archive_factory, status="failed")
  2803. failed_p1_id = failed_p1.id
  2804. failed_p2_id = failed_p2.id
  2805. resp = await async_client.post(f"/api/v1/queue/printer/{p1.id}/resume")
  2806. assert resp.json() == {"acknowledged": 1, "restored": 0}
  2807. db_session.expire_all()
  2808. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id == failed_p1_id))
  2809. assert result.scalar_one().gate_acknowledged is True
  2810. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id == failed_p2_id))
  2811. assert result.scalar_one().gate_acknowledged is False
  2812. @pytest.mark.asyncio
  2813. @pytest.mark.integration
  2814. async def test_resume_handles_aborted_status(
  2815. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2816. ):
  2817. """Aborted prints (printer-detected mid-print failure) gate the same
  2818. way failed prints do and must also be acknowledgeable."""
  2819. from sqlalchemy import select
  2820. from backend.app.models.print_queue import PrintQueueItem
  2821. printer = await printer_factory()
  2822. aborted = await self._add_item(db_session, printer, archive_factory, status="aborted")
  2823. aborted_id = aborted.id
  2824. resp = await async_client.post(f"/api/v1/queue/printer/{printer.id}/resume")
  2825. assert resp.json() == {"acknowledged": 1, "restored": 0}
  2826. db_session.expire_all()
  2827. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id == aborted_id))
  2828. assert result.scalar_one().gate_acknowledged is True
  2829. @pytest.mark.asyncio
  2830. @pytest.mark.integration
  2831. async def test_resume_idempotent_second_call_is_no_op(
  2832. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2833. ):
  2834. """Calling resume twice on the same printer doesn't re-acknowledge
  2835. the same failure — the second call sees acknowledged=0, restored=0."""
  2836. printer = await printer_factory()
  2837. await self._add_item(db_session, printer, archive_factory, status="failed")
  2838. await self._add_item(
  2839. db_session,
  2840. printer,
  2841. archive_factory,
  2842. status="skipped",
  2843. error_message="Previous print failed or was aborted",
  2844. )
  2845. first = await async_client.post(f"/api/v1/queue/printer/{printer.id}/resume")
  2846. assert first.json() == {"acknowledged": 1, "restored": 1}
  2847. second = await async_client.post(f"/api/v1/queue/printer/{printer.id}/resume")
  2848. assert second.json() == {"acknowledged": 0, "restored": 0}
  2849. class TestReorderEndpoint:
  2850. """Tests for the /queue/reorder endpoint (#1625-followup duplicate-position validator)."""
  2851. @pytest.fixture
  2852. async def printer_factory(self, db_session):
  2853. async def _create(**kwargs):
  2854. from backend.app.models.printer import Printer
  2855. defaults = {
  2856. "name": "Reorder Test Printer",
  2857. "ip_address": "192.168.1.220",
  2858. "serial_number": "TESTREORDER001",
  2859. "access_code": "12345678",
  2860. "model": "X1C",
  2861. }
  2862. defaults.update(kwargs)
  2863. printer = Printer(**defaults)
  2864. db_session.add(printer)
  2865. await db_session.commit()
  2866. await db_session.refresh(printer)
  2867. return printer
  2868. return _create
  2869. @pytest.fixture
  2870. async def archive_factory(self, db_session):
  2871. _counter = [0]
  2872. async def _create(**kwargs):
  2873. from backend.app.models.archive import PrintArchive
  2874. _counter[0] += 1
  2875. defaults = {
  2876. "filename": f"reorder_{_counter[0]}.3mf",
  2877. "print_name": f"Reorder {_counter[0]}",
  2878. "file_path": f"/tmp/reorder_{_counter[0]}.3mf", # nosec B108
  2879. "file_size": 1024,
  2880. "content_hash": f"reorderhash{_counter[0]:06d}",
  2881. "status": "completed",
  2882. }
  2883. defaults.update(kwargs)
  2884. archive = PrintArchive(**defaults)
  2885. db_session.add(archive)
  2886. await db_session.commit()
  2887. await db_session.refresh(archive)
  2888. return archive
  2889. return _create
  2890. @pytest.mark.asyncio
  2891. @pytest.mark.integration
  2892. async def test_reorder_rejects_duplicate_positions(
  2893. self, async_client: AsyncClient, db_session, printer_factory, archive_factory
  2894. ):
  2895. """Reorder payload with duplicate positions → 422 at schema layer.
  2896. Regression guard: pre-fix, a buggy client sending two items at the
  2897. same position would leave the queue in an inconsistent state (the
  2898. scheduler's ORDER BY (printer_id, position) tie would be broken by
  2899. physical row order — non-deterministic dispatch order).
  2900. """
  2901. from backend.app.models.print_queue import PrintQueueItem
  2902. printer = await printer_factory()
  2903. a1 = await archive_factory()
  2904. a2 = await archive_factory()
  2905. item1 = PrintQueueItem(printer_id=printer.id, archive_id=a1.id, status="pending", position=1)
  2906. item2 = PrintQueueItem(printer_id=printer.id, archive_id=a2.id, status="pending", position=2)
  2907. db_session.add_all([item1, item2])
  2908. await db_session.commit()
  2909. await db_session.refresh(item1)
  2910. await db_session.refresh(item2)
  2911. response = await async_client.post(
  2912. "/api/v1/queue/reorder",
  2913. json={
  2914. "items": [
  2915. {"id": item1.id, "position": 1},
  2916. {"id": item2.id, "position": 1}, # duplicate
  2917. ]
  2918. },
  2919. )
  2920. assert response.status_code == 422
  2921. body = response.json()
  2922. # Pydantic v2 wraps custom validator errors; the message must mention "Duplicate"
  2923. # so the FE can surface the actionable detail.
  2924. assert any("duplicate" in str(err).lower() for err in body.get("detail", []))
  2925. @pytest.mark.asyncio
  2926. @pytest.mark.integration
  2927. async def test_reorder_accepts_unique_positions(
  2928. self, async_client: AsyncClient, db_session, printer_factory, archive_factory
  2929. ):
  2930. """Reorder with unique positions succeeds and updates them in DB."""
  2931. from backend.app.models.print_queue import PrintQueueItem
  2932. printer = await printer_factory()
  2933. a1 = await archive_factory()
  2934. a2 = await archive_factory()
  2935. item1 = PrintQueueItem(printer_id=printer.id, archive_id=a1.id, status="pending", position=1)
  2936. item2 = PrintQueueItem(printer_id=printer.id, archive_id=a2.id, status="pending", position=2)
  2937. db_session.add_all([item1, item2])
  2938. await db_session.commit()
  2939. await db_session.refresh(item1)
  2940. await db_session.refresh(item2)
  2941. response = await async_client.post(
  2942. "/api/v1/queue/reorder",
  2943. json={
  2944. "items": [
  2945. {"id": item1.id, "position": 2},
  2946. {"id": item2.id, "position": 1},
  2947. ]
  2948. },
  2949. )
  2950. assert response.status_code == 200
  2951. await db_session.refresh(item1)
  2952. await db_session.refresh(item2)
  2953. assert item1.position == 2
  2954. assert item2.position == 1
  2955. class TestForceColorOverridesAreScopedToThePlate:
  2956. """Queueing several plates of one 3MF must not make each plate wait on the
  2957. colours of its siblings (#2551).
  2958. The print dialog builds one override list from every selected plate and posts
  2959. that same list with each plate's item, so the API is what has to keep only the
  2960. slots the plate prints -- a ``force_color_match`` entry blocks dispatch until
  2961. the printer has that exact colour loaded.
  2962. """
  2963. THREE_PLATES = """<?xml version="1.0" encoding="UTF-8"?>
  2964. <config>
  2965. <plate>
  2966. <metadata key="index" value="1"/>
  2967. <filament id="1" used_g="50.0" type="PLA" color="#0B2C7A"/>
  2968. </plate>
  2969. <plate>
  2970. <metadata key="index" value="2"/>
  2971. <filament id="2" used_g="40.0" type="PLA" color="#9B9EA0"/>
  2972. </plate>
  2973. <plate>
  2974. <metadata key="index" value="3"/>
  2975. <filament id="3" used_g="30.0" type="PLA" color="#F4EE2A"/>
  2976. </plate>
  2977. </config>
  2978. """
  2979. # What the dialog posts for every plate: the union of all three plates'
  2980. # filaments, each one force-matched.
  2981. ALL_THREE_COLORS = [
  2982. {"slot_id": 1, "type": "PLA", "color": "#0B2C7A", "color_name": "Army Blue", "force_color_match": True},
  2983. {"slot_id": 2, "type": "PLA", "color": "#9B9EA0", "color_name": "Ash Grey", "force_color_match": True},
  2984. {"slot_id": 3, "type": "PLA", "color": "#F4EE2A", "color_name": "Sunshine Yellow", "force_color_match": True},
  2985. ]
  2986. @pytest.fixture
  2987. async def multi_plate_archive(self, db_session, tmp_path):
  2988. """An archive whose 3MF really exists on disk, one colour per plate."""
  2989. import zipfile
  2990. from backend.app.models.archive import PrintArchive
  2991. file_path = tmp_path / "three_plates.gcode.3mf"
  2992. with zipfile.ZipFile(file_path, "w") as zf:
  2993. zf.writestr("Metadata/slice_info.config", self.THREE_PLATES)
  2994. archive = PrintArchive(
  2995. filename="three_plates.gcode.3mf",
  2996. print_name="Three Plates",
  2997. file_path=str(file_path),
  2998. file_size=file_path.stat().st_size,
  2999. content_hash="platehash0001",
  3000. status="completed",
  3001. )
  3002. db_session.add(archive)
  3003. await db_session.commit()
  3004. await db_session.refresh(archive)
  3005. return archive
  3006. @pytest.fixture
  3007. async def x1c(self, db_session):
  3008. from backend.app.models.printer import Printer
  3009. printer = Printer(
  3010. name="Force Color X1C",
  3011. ip_address="192.168.1.210",
  3012. serial_number="FORCECOLOR01",
  3013. access_code="12345678",
  3014. model="X1C",
  3015. )
  3016. db_session.add(printer)
  3017. await db_session.commit()
  3018. await db_session.refresh(printer)
  3019. return printer
  3020. @pytest.mark.asyncio
  3021. @pytest.mark.integration
  3022. async def test_each_plate_keeps_only_the_colour_it_prints(
  3023. self, async_client: AsyncClient, multi_plate_archive, x1c
  3024. ):
  3025. """The bug: plate 1 prints Army Blue only, but was stored demanding all three."""
  3026. stored = {}
  3027. for plate_id in (1, 2, 3):
  3028. response = await async_client.post(
  3029. "/api/v1/queue/",
  3030. json={
  3031. "target_model": "X1C",
  3032. "archive_id": multi_plate_archive.id,
  3033. "plate_id": plate_id,
  3034. "filament_overrides": self.ALL_THREE_COLORS,
  3035. },
  3036. )
  3037. assert response.status_code == 200
  3038. stored[plate_id] = response.json()["filament_overrides"]
  3039. assert [o["color_name"] for o in stored[1]] == ["Army Blue"]
  3040. assert [o["color_name"] for o in stored[2]] == ["Ash Grey"]
  3041. assert [o["color_name"] for o in stored[3]] == ["Sunshine Yellow"]
  3042. # The slot each entry maps to has to survive narrowing untouched, or the
  3043. # dispatch-time AMS mapping would key the override onto the wrong slot.
  3044. assert [o["slot_id"] for o in stored[2]] == [2]
  3045. @pytest.mark.asyncio
  3046. @pytest.mark.integration
  3047. async def test_whole_file_queue_keeps_every_colour(self, async_client: AsyncClient, multi_plate_archive, x1c):
  3048. """No plate_id means the job prints the whole file, so every colour is needed."""
  3049. response = await async_client.post(
  3050. "/api/v1/queue/",
  3051. json={
  3052. "target_model": "X1C",
  3053. "archive_id": multi_plate_archive.id,
  3054. "filament_overrides": self.ALL_THREE_COLORS,
  3055. },
  3056. )
  3057. assert response.status_code == 200
  3058. assert len(response.json()["filament_overrides"]) == 3
  3059. @pytest.mark.asyncio
  3060. @pytest.mark.integration
  3061. async def test_unreadable_3mf_keeps_every_colour(self, async_client: AsyncClient, db_session, tmp_path, x1c):
  3062. """When the plate's slots can't be read, keep the overrides rather than drop them.
  3063. An item waiting on a colour it doesn't need is visible and fixable; one that
  3064. silently lost its forced colour would dispatch in the wrong filament.
  3065. """
  3066. from backend.app.models.archive import PrintArchive
  3067. file_path = tmp_path / "not_a_zip.gcode.3mf"
  3068. file_path.write_text("this is not a 3mf")
  3069. archive = PrintArchive(
  3070. filename="not_a_zip.gcode.3mf",
  3071. print_name="Corrupt",
  3072. file_path=str(file_path),
  3073. file_size=file_path.stat().st_size,
  3074. content_hash="platehash0002",
  3075. status="completed",
  3076. )
  3077. db_session.add(archive)
  3078. await db_session.commit()
  3079. await db_session.refresh(archive)
  3080. response = await async_client.post(
  3081. "/api/v1/queue/",
  3082. json={
  3083. "target_model": "X1C",
  3084. "archive_id": archive.id,
  3085. "plate_id": 1,
  3086. "filament_overrides": self.ALL_THREE_COLORS,
  3087. },
  3088. )
  3089. assert response.status_code == 200
  3090. assert len(response.json()["filament_overrides"]) == 3
  3091. @pytest.mark.asyncio
  3092. @pytest.mark.integration
  3093. async def test_required_types_stay_scoped_to_the_plate(self, async_client: AsyncClient, db_session, tmp_path, x1c):
  3094. """Override types are merged into required_filament_types, so a shared list
  3095. also widened the type gate -- a PLA-only plate demanded PETG as well."""
  3096. import zipfile
  3097. from backend.app.models.archive import PrintArchive
  3098. xml = """<?xml version="1.0" encoding="UTF-8"?>
  3099. <config>
  3100. <plate>
  3101. <metadata key="index" value="1"/>
  3102. <filament id="1" used_g="50.0" type="PLA" color="#0B2C7A"/>
  3103. </plate>
  3104. <plate>
  3105. <metadata key="index" value="2"/>
  3106. <filament id="2" used_g="40.0" type="PETG" color="#9B9EA0"/>
  3107. </plate>
  3108. </config>
  3109. """
  3110. file_path = tmp_path / "mixed_types.gcode.3mf"
  3111. with zipfile.ZipFile(file_path, "w") as zf:
  3112. zf.writestr("Metadata/slice_info.config", xml)
  3113. archive = PrintArchive(
  3114. filename="mixed_types.gcode.3mf",
  3115. print_name="Mixed",
  3116. file_path=str(file_path),
  3117. file_size=file_path.stat().st_size,
  3118. content_hash="platehash0003",
  3119. status="completed",
  3120. )
  3121. db_session.add(archive)
  3122. await db_session.commit()
  3123. await db_session.refresh(archive)
  3124. response = await async_client.post(
  3125. "/api/v1/queue/",
  3126. json={
  3127. "target_model": "X1C",
  3128. "archive_id": archive.id,
  3129. "plate_id": 1,
  3130. "filament_overrides": [
  3131. {"slot_id": 1, "type": "PLA", "color": "#0B2C7A", "force_color_match": True},
  3132. {"slot_id": 2, "type": "PETG", "color": "#9B9EA0", "force_color_match": True},
  3133. ],
  3134. },
  3135. )
  3136. assert response.status_code == 200
  3137. assert response.json()["required_filament_types"] == ["PLA"]
  3138. @pytest.mark.asyncio
  3139. @pytest.mark.integration
  3140. async def test_editing_an_item_narrows_the_overrides_too(
  3141. self, async_client: AsyncClient, db_session, multi_plate_archive, x1c
  3142. ):
  3143. """The edit dialog posts the same shared list, so PATCH narrows it as well."""
  3144. from backend.app.models.print_queue import PrintQueueItem
  3145. item = PrintQueueItem(
  3146. target_model="X1C",
  3147. archive_id=multi_plate_archive.id,
  3148. plate_id=2,
  3149. status="pending",
  3150. position=1,
  3151. )
  3152. db_session.add(item)
  3153. await db_session.commit()
  3154. await db_session.refresh(item)
  3155. response = await async_client.patch(
  3156. f"/api/v1/queue/{item.id}",
  3157. json={"filament_overrides": self.ALL_THREE_COLORS},
  3158. )
  3159. assert response.status_code == 200
  3160. assert [o["color_name"] for o in response.json()["filament_overrides"]] == ["Ash Grey"]
  3161. @pytest.mark.asyncio
  3162. @pytest.mark.integration
  3163. async def test_editing_the_plate_renarrows_against_the_new_plate(
  3164. self, async_client: AsyncClient, db_session, multi_plate_archive, x1c
  3165. ):
  3166. """Moving an item to another plate must re-scope its colours to that plate."""
  3167. from backend.app.models.print_queue import PrintQueueItem
  3168. item = PrintQueueItem(
  3169. target_model="X1C",
  3170. archive_id=multi_plate_archive.id,
  3171. plate_id=1,
  3172. status="pending",
  3173. position=1,
  3174. )
  3175. db_session.add(item)
  3176. await db_session.commit()
  3177. await db_session.refresh(item)
  3178. response = await async_client.patch(
  3179. f"/api/v1/queue/{item.id}",
  3180. json={"plate_id": 3, "filament_overrides": self.ALL_THREE_COLORS},
  3181. )
  3182. assert response.status_code == 200
  3183. assert [o["color_name"] for o in response.json()["filament_overrides"]] == ["Sunshine Yellow"]
  3184. @pytest.mark.asyncio
  3185. async def test_stop_offline_reconciles_linked_archive_status_2603(
  3186. async_client: AsyncClient, printer_factory, archive_factory, db_session
  3187. ):
  3188. """Stopping a printing item while the printer is offline must also close out its
  3189. archive (#2603).
  3190. When the stop command reaches the printer, the later MQTT completion event flips
  3191. the archive to cancelled. When the printer is offline no such event ever arrives,
  3192. so without this the archive stays "printing" forever while the queue row is
  3193. already cancelled — the reporter's archive 436. The offline branch reconciles the
  3194. archive directly.
  3195. """
  3196. from unittest.mock import MagicMock, patch
  3197. from backend.app.models.print_queue import PrintQueueItem
  3198. printer = await printer_factory(name="Offline printer")
  3199. archive = await archive_factory(
  3200. printer.id, status="printing", plate_id=22, filename="heart 3.gcode.3mf", with_run=False
  3201. )
  3202. item = PrintQueueItem(printer_id=printer.id, archive_id=archive.id, status="printing")
  3203. db_session.add(item)
  3204. await db_session.commit()
  3205. await db_session.refresh(item)
  3206. # stop_print returns False => printer offline / not connected.
  3207. with patch(
  3208. "backend.app.services.printer_manager.printer_manager.stop_print",
  3209. MagicMock(return_value=False),
  3210. ):
  3211. resp = await async_client.post(f"/api/v1/queue/{item.id}/stop")
  3212. assert resp.status_code == 200
  3213. await db_session.refresh(item)
  3214. await db_session.refresh(archive)
  3215. assert item.status == "cancelled"
  3216. assert archive.status == "cancelled", "an offline stop must reconcile the archive, not leave it 'printing'"
  3217. assert archive.completed_at is not None
  3218. assert archive.failure_reason == "Stopped by user (printer was offline)"
  3219. @pytest.mark.asyncio
  3220. async def test_stop_online_leaves_archive_for_mqtt_to_reconcile_2603(
  3221. async_client: AsyncClient, printer_factory, archive_factory, db_session
  3222. ):
  3223. """When the stop command reaches the printer, the archive is left to the MQTT
  3224. completion path — the offline reconcile must NOT fire and pre-empt it."""
  3225. from unittest.mock import MagicMock, patch
  3226. from backend.app.models.print_queue import PrintQueueItem
  3227. printer = await printer_factory(name="Online printer")
  3228. archive = await archive_factory(printer.id, status="printing", filename="heart 3.gcode.3mf", with_run=False)
  3229. item = PrintQueueItem(printer_id=printer.id, archive_id=archive.id, status="printing")
  3230. db_session.add(item)
  3231. await db_session.commit()
  3232. await db_session.refresh(item)
  3233. with patch(
  3234. "backend.app.services.printer_manager.printer_manager.stop_print",
  3235. MagicMock(return_value=True),
  3236. ):
  3237. resp = await async_client.post(f"/api/v1/queue/{item.id}/stop")
  3238. assert resp.status_code == 200
  3239. await db_session.refresh(item)
  3240. await db_session.refresh(archive)
  3241. assert item.status == "cancelled"
  3242. assert archive.status == "printing", "an online stop must leave the archive for the MQTT completion path"