test_print_queue_api.py 151 KB

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