client.ts 269 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752
  1. import type { ArchivePlatesResponse, LibraryFilePlatesResponse } from '../types/plates';
  2. const API_BASE = '/api/v1';
  3. export class ApiError extends Error {
  4. status: number;
  5. /** Stable error code from a structured backend detail (`{code, message}`).
  6. * Frontend uses this to look up an i18n key instead of showing the raw
  7. * English fallback. Null when the backend returned a plain-string detail. */
  8. code: string | null;
  9. /** Full structured detail object when the backend returned `{code, ...}`
  10. * with additional fields (e.g. the deficit list for 409s on queue
  11. * start, #1496). Null for plain-string or array-shaped details. */
  12. detail: Record<string, unknown> | null;
  13. constructor(
  14. message: string,
  15. status: number,
  16. code: string | null = null,
  17. detail: Record<string, unknown> | null = null,
  18. ) {
  19. super(message);
  20. this.name = 'ApiError';
  21. this.status = status;
  22. this.code = code;
  23. this.detail = detail;
  24. }
  25. }
  26. // Auth token storage
  27. // By default tokens are stored in sessionStorage (tab-scoped, cleared on close).
  28. // When the token originates from the ?token= URL param (kiosk bootstrap), it is
  29. // additionally persisted in localStorage so the kiosk survives page reloads.
  30. // 'persistent' also writes to localStorage so the token survives tab close
  31. // (used by Remember Me and the ?token= kiosk bootstrap).
  32. let authToken: string | null =
  33. sessionStorage.getItem('auth_token') ?? localStorage.getItem('auth_token');
  34. export type TokenPersistence = 'session' | 'persistent';
  35. export function setAuthToken(token: string | null, persistence: TokenPersistence = 'session') {
  36. authToken = token;
  37. try {
  38. if (token) {
  39. sessionStorage.setItem('auth_token', token);
  40. } else {
  41. sessionStorage.removeItem('auth_token');
  42. }
  43. } catch (err) {
  44. // Storage unavailable (quota exceeded, private mode): in-memory token still works for this tab.
  45. console.warn('setAuthToken: sessionStorage unavailable, token kept in-memory only', err);
  46. }
  47. try {
  48. if (!token) {
  49. localStorage.removeItem('auth_token');
  50. } else if (persistence === 'persistent') {
  51. localStorage.setItem('auth_token', token);
  52. }
  53. } catch (err) {
  54. console.warn('setAuthToken: localStorage operation failed', err);
  55. }
  56. }
  57. export function getAuthToken(): string | null {
  58. return authToken;
  59. }
  60. // Stream token for image/video URLs loaded via <img>/<video> tags
  61. // (these can't send Authorization headers, so a query param token is used)
  62. let streamToken: string | null = null;
  63. export function setStreamToken(token: string | null) {
  64. streamToken = token;
  65. }
  66. export function getStreamToken(): string | null {
  67. return streamToken;
  68. }
  69. /** Append the stream token to a URL if available (for <img>/<video> src). */
  70. export function withStreamToken(url: string): string {
  71. if (!streamToken) return url;
  72. const sep = url.includes('?') ? '&' : '?';
  73. return `${url}${sep}token=${encodeURIComponent(streamToken)}`;
  74. }
  75. function parseContentDispositionFilename(header: string | null): string | null {
  76. if (!header) return null;
  77. // RFC 5987: filename*=utf-8''percent-encoded-name
  78. const rfc5987Match = header.match(/filename\*=(?:UTF-8|utf-8)''(.+?)(?:;|$)/);
  79. if (rfc5987Match) {
  80. try { return decodeURIComponent(rfc5987Match[1]); } catch { /* fall through */ }
  81. }
  82. // Standard: filename="name" or filename=name
  83. const standardMatch = header.match(/filename="?([^";\n]+)"?/);
  84. return standardMatch?.[1] || null;
  85. }
  86. function buildSlicerUrlFilename(filename: string): string {
  87. const safe = filename.replace(/[/\\?#]/g, '_');
  88. return safe.toLowerCase().endsWith('.3mf') ? safe : `${safe}.3mf`;
  89. }
  90. async function request<T>(
  91. endpoint: string,
  92. options: RequestInit = {}
  93. ): Promise<T> {
  94. const headers: Record<string, string> = {
  95. 'Content-Type': 'application/json',
  96. ...options.headers as Record<string, string>,
  97. };
  98. // Add auth token if available
  99. if (authToken) {
  100. headers['Authorization'] = `Bearer ${authToken}`;
  101. }
  102. const response = await fetch(`${API_BASE}${endpoint}`, {
  103. ...options,
  104. cache: 'no-store', // Prevent browser caching of API responses
  105. credentials: 'include', // Required for HttpOnly cookies (e.g. 2fa_challenge)
  106. headers,
  107. });
  108. if (!response.ok) {
  109. const error = await response.json().catch(() => ({}));
  110. const detail = error.detail;
  111. let message: string;
  112. let code: string | null = null;
  113. if (typeof detail === 'string') {
  114. message = detail;
  115. } else if (Array.isArray(detail)) {
  116. // FastAPI 422 shape: each entry has `msg` like "Value error, <real msg>".
  117. // Strip the prefix and join. Fall back to raw JSON if every entry has an
  118. // empty msg (defensive — shouldn't happen with stock Pydantic, but the
  119. // previous fallback masked the real cause as a bare "HTTP 422" toast).
  120. const joined = detail
  121. .map((e: { msg?: string }) => (e.msg ?? '').replace(/^Value error,\s*/i, ''))
  122. .filter(Boolean)
  123. .join('; ');
  124. message = joined || JSON.stringify(detail) || `HTTP ${response.status}`;
  125. } else if (detail && typeof detail === 'object') {
  126. // Structured detail `{code, message, ...}` — frontend uses the code
  127. // to pick an i18n key, message is the English fallback, any extra
  128. // fields land on ApiError.detail (e.g. `deficit` for #1496).
  129. code = typeof detail.code === 'string' ? detail.code : null;
  130. message = typeof detail.message === 'string' ? detail.message : `HTTP ${response.status}`;
  131. } else {
  132. message = `HTTP ${response.status}`;
  133. }
  134. const structuredDetail = detail && typeof detail === 'object' && !Array.isArray(detail)
  135. ? (detail as Record<string, unknown>)
  136. : null;
  137. // Handle 401 Unauthorized - only clear token if it's actually invalid
  138. // Don't clear on "Authentication required" which might be a timing issue
  139. if (response.status === 401) {
  140. const invalidTokenMessages = [
  141. 'Could not validate credentials',
  142. 'Token has expired',
  143. 'User not found or inactive',
  144. 'Invalid API key',
  145. 'API key has expired',
  146. ];
  147. if (invalidTokenMessages.some(m => message.includes(m))) {
  148. setAuthToken(null);
  149. // Notify AuthContext so the protected route guard re-evaluates and
  150. // redirects to /login on the same tab — without this, AuthContext.user
  151. // stays cached and the tab silently fails every request until a manual
  152. // refresh remounts AuthProvider (#1698, reported by @TCL987).
  153. if (typeof window !== 'undefined') {
  154. window.dispatchEvent(new CustomEvent('auth:expired'));
  155. }
  156. }
  157. }
  158. throw new ApiError(message, response.status, code, structuredDetail);
  159. }
  160. // Handle empty responses (204 No Content, etc.)
  161. const contentLength = response.headers.get('content-length');
  162. if (response.status === 204 || contentLength === '0') {
  163. return undefined as T;
  164. }
  165. return await response.json();
  166. }
  167. /** Upload a CSV to the spool import endpoint (#1576). Multipart, so it bypasses
  168. * `request<T>()` (which sends JSON): the browser must set the form-data
  169. * boundary itself. `dryRun` toggles preview-only vs. real import. */
  170. async function uploadSpoolsCsv<T>(file: File, dryRun: boolean): Promise<T> {
  171. const form = new FormData();
  172. form.append('file', file);
  173. const headers: Record<string, string> = {};
  174. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  175. const response = await fetch(`${API_BASE}/inventory/spools/import${dryRun ? '?dry_run=true' : ''}`, {
  176. method: 'POST',
  177. headers,
  178. body: form,
  179. });
  180. if (!response.ok) {
  181. const error = await response.json().catch(() => ({}));
  182. // detail may be a plain string or a structured {code, message} object
  183. // (e.g. the 413 too-large response). Surface the human message either way.
  184. const detail = error?.detail;
  185. const message = typeof detail === 'string' ? detail : detail?.message;
  186. throw new Error(message || `HTTP ${response.status}`);
  187. }
  188. return response.json();
  189. }
  190. // Camera diagnostic result (#1395 follow-up). Returned by
  191. // POST /printers/{id}/camera/diagnose; the frontend modal renders one
  192. // row per stage and looks up the summary code in i18n for the user-
  193. // facing remediation hint.
  194. export interface CameraDiagnoseStage {
  195. name: 'tcp_reachable' | 'first_frame' | 'live_stream_active';
  196. status: 'ok' | 'failed' | 'skipped';
  197. duration_ms: number;
  198. code: string | null;
  199. }
  200. export interface CameraDiagnoseResult {
  201. printer_id: number;
  202. protocol: 'rtsp' | 'chamber_image';
  203. port: number;
  204. // 'default' = historical X1/H2 tuning. Anything else = this model has
  205. // an override entry in backend/app/services/camera_profiles.py.
  206. profile: string;
  207. overall_status: 'ok' | 'failed';
  208. stages: CameraDiagnoseStage[];
  209. // i18n key under `camera.diagnose.summary.*`.
  210. summary_code: string;
  211. }
  212. // Connection diagnostic (GET /printers/{id}/diagnostic and
  213. // POST /printers/diagnostic). Each check's `id` + `status` resolve a
  214. // localized title/fix under `diagnostic.check.*`; `params` interpolate it.
  215. export type DiagnosticStatus = 'pass' | 'fail' | 'warn' | 'skip';
  216. export interface DiagnosticCheck {
  217. id:
  218. | 'port_mqtt'
  219. | 'port_ftps'
  220. | 'port_rtsps'
  221. | 'network_mode'
  222. | 'subnet'
  223. | 'mqtt_auth'
  224. | 'developer_mode';
  225. status: DiagnosticStatus;
  226. params: Record<string, string | number>;
  227. }
  228. export interface PrinterDiagnosticResult {
  229. printer_id: number | null;
  230. ip_address: string;
  231. overall: 'ok' | 'warnings' | 'problems';
  232. checks: DiagnosticCheck[];
  233. }
  234. // --- Log-health scan: self-service triage on the System page + bug reporter.
  235. // The backend matches recent logs against a curated known-issue catalog;
  236. // human-readable cause/fix text is rendered from i18n keys keyed by signature_id.
  237. export type LogFindingSeverity = 'error' | 'warning';
  238. export type LogFindingCategory = 'layer8' | 'environment' | 'bug';
  239. export interface LogFinding {
  240. signature_id: string;
  241. severity: LogFindingSeverity;
  242. category: LogFindingCategory;
  243. wiki_anchor: string;
  244. count: number;
  245. first_seen: string;
  246. last_seen: string;
  247. sample: string;
  248. }
  249. export interface SystemHealthResult {
  250. findings: LogFinding[];
  251. scanned_entries: number;
  252. log_available: boolean;
  253. summary: {
  254. total: number;
  255. layer8: number;
  256. environment: number;
  257. bug: number;
  258. };
  259. }
  260. // Long-lived camera tokens (#1108). The `token` field is populated only on the
  261. // create response — listing endpoints set it to null because the plaintext
  262. // value is shown to the user exactly once.
  263. //
  264. // 'camera_stream' reaches the video endpoints only. 'camwall' additionally
  265. // reaches the read-only Cam Wall feed, which names the printers (#2531), so it
  266. // is a separate scope rather than a widening of tokens already in the wild.
  267. export type LongLivedTokenScope = 'camera_stream' | 'camwall' | 'overlay';
  268. export interface LongLivedCameraToken {
  269. id: number;
  270. user_id: number;
  271. name: string;
  272. scope: LongLivedTokenScope;
  273. lookup_prefix: string;
  274. created_at: string;
  275. expires_at: string;
  276. last_used_at: string | null;
  277. token: string | null;
  278. }
  279. // One row of the token-authenticated Cam Wall feed (#2531). Deliberately
  280. // smaller than PrinterStatus: no serial, no IP, no print filename — a kiosk URL
  281. // is not a secret, so the payload behind it must not be either.
  282. export interface CamWallPrinter {
  283. id: number;
  284. name: string;
  285. camera_rotation: number;
  286. connected: boolean;
  287. state: string | null;
  288. progress: number | null;
  289. remaining_time: number | null;
  290. layer_num: number | null;
  291. total_layers: number | null;
  292. hms_errors: HMSError[];
  293. }
  294. // Streaming-overlay feed (#2613). The subset of print state the /overlay page
  295. // draws for one printer, served behind an `overlay`-scoped token so OBS embeds
  296. // with no login session can read it. Unlike CamWallPrinter this names the file
  297. // being printed (the overlay shows the part on screen).
  298. export interface OverlayStatus {
  299. id: number;
  300. name: string;
  301. camera_rotation: number;
  302. connected: boolean;
  303. state: string | null;
  304. current_print: string | null;
  305. gcode_file: string | null;
  306. progress: number | null;
  307. remaining_time: number | null;
  308. layer_num: number | null;
  309. total_layers: number | null;
  310. stg_cur_name: string | null;
  311. time_format: 'system' | '12h' | '24h';
  312. }
  313. // Printer types
  314. export interface Printer {
  315. id: number;
  316. name: string;
  317. serial_number: string;
  318. ip_address: string;
  319. // Optional because the backend only returns access_code when the caller has
  320. // PRINTERS_UPDATE — Admin / Operator JWTs or auth-disabled mode. Viewers and
  321. // API keys receive a Printer without this field.
  322. access_code?: string;
  323. model: string | null;
  324. location: string | null; // Group/location name
  325. nozzle_count: number; // 1 or 2, auto-detected from MQTT
  326. is_active: boolean;
  327. auto_archive: boolean;
  328. external_camera_url: string | null;
  329. external_camera_type: string | null; // "mjpeg", "rtsp", "snapshot"
  330. external_camera_enabled: boolean;
  331. external_camera_snapshot_url: string | null; // optional single-frame override (#1177)
  332. camera_rotation: number; // 0, 90, 180, 270 degrees
  333. plate_detection_enabled: boolean; // Check plate before print
  334. plate_detection_roi?: PlateDetectionROI; // ROI for plate detection
  335. created_at: string;
  336. updated_at: string;
  337. }
  338. export interface HMSError {
  339. code: string;
  340. attr: number; // Attribute value for constructing wiki URL
  341. module: number;
  342. severity: number; // 1=fatal, 2=serious, 3=common, 4=info
  343. actions?: string[]; // List of user-facing action keys (e.g. "CHECK_FILAMENT")
  344. job_id?: string; // Optional job ID for actions that require it (e.g. "CHECK_ASSISTANT")
  345. // Canonical hex identifier the firmware matches against — 8 chars for
  346. // print_error-sourced faults, 16 chars for hms[]-array-sourced faults. Send
  347. // this back as HmsActionBody.print_error so we don't truncate the 64-bit
  348. // identifier into the silent-rejection short code (#1830).
  349. full_code?: string;
  350. }
  351. export interface HMSActionBody {
  352. print_error: string; // HMS error code (e.g. "05000070")
  353. action: string; // "HMS action to execute (e.g. 'resume_after_error')"
  354. job_id: string | null; // Optional job ID for context (if applicable)
  355. }
  356. export interface AMSTray {
  357. id: number;
  358. tray_color: string | null;
  359. tray_type: string | null;
  360. tray_sub_brands: string | null; // Full name like "PLA Basic", "PETG HF"
  361. tray_id_name: string | null; // Bambu filament ID like "A00-Y2" (can decode to color)
  362. tray_info_idx: string | null; // Filament preset ID like "GFA00" - maps to cloud setting_id
  363. remain: number;
  364. k: number | null; // Pressure advance value (from tray or K-profile lookup)
  365. cali_idx: number | null; // Calibration index for K-profile lookup
  366. tag_uid: string | null; // RFID tag UID (any tag)
  367. tray_uuid: string | null; // Bambu Lab spool UUID (32-char hex, only valid for Bambu Lab spools)
  368. nozzle_temp_min: number | null; // Min nozzle temperature
  369. nozzle_temp_max: number | null; // Max nozzle temperature
  370. drying_temp: number | null; // RFID-recommended drying temp
  371. drying_time: number | null; // RFID-recommended drying time (hours)
  372. state: number | null; // AMS tray state: 9=empty, 10=spool present not loaded, 11=loaded
  373. exists?: boolean | null; // Firmware tray_exist_bits: spool physically present (non-RFID → "?" not "Empty", #2527)
  374. }
  375. export interface AMSUnit {
  376. id: number;
  377. humidity: number | null;
  378. temp: number | null;
  379. is_ams_ht: boolean; // True for AMS-HT (single spool), False for regular AMS (4 spools)
  380. tray: AMSTray[];
  381. serial_number: string; // AMS unit serial number (from MQTT sn field)
  382. sw_ver: string; // AMS firmware version (from get_version info.module ams/* entry)
  383. dry_time: number; // Minutes remaining (0 = not drying, >0 = drying active)
  384. dry_status: number; // 0=Off, 1=Checking, 2=Drying, 3=Cooling, 4=Stopping, 5=Error
  385. dry_sub_status: number; // 0=Off, 1=Heating, 2=Dehumidify
  386. dry_sf_reason: number[]; // Cannot-dry reasons (1=InsufficientPower, 8=NeedPluginPower)
  387. dry_target_temp: number | null; // Active-cycle target °C (Bambu does not echo)
  388. dry_filament: string | null; // Active-cycle filament name we sent
  389. module_type: string; // "ams", "n3f", "n3s"
  390. }
  391. export interface NozzleInfo {
  392. nozzle_type: string; // "stainless_steel" or "hardened_steel"
  393. nozzle_diameter: string; // e.g., "0.4"
  394. }
  395. export interface NozzleRackSlot {
  396. id: number;
  397. nozzle_type: string;
  398. nozzle_diameter: string;
  399. wear: number | null;
  400. stat: number | null; // Nozzle status (e.g. mounted/docked)
  401. max_temp: number;
  402. serial_number: string;
  403. filament_color: string; // RGBA hex ("00000000" = no filament)
  404. filament_id: string;
  405. filament_type: string; // Material type (e.g. "PLA", "PETG")
  406. }
  407. export interface PrintOptions {
  408. // Core AI detectors
  409. spaghetti_detector: boolean;
  410. print_halt: boolean;
  411. halt_print_sensitivity: string; // "low", "medium", "high" - spaghetti sensitivity
  412. first_layer_inspector: boolean;
  413. printing_monitor: boolean;
  414. buildplate_marker_detector: boolean;
  415. allow_skip_parts: boolean;
  416. // Additional AI detectors (decoded from cfg bitmask)
  417. nozzle_clumping_detector: boolean;
  418. nozzle_clumping_sensitivity: string; // "low", "medium", "high"
  419. pileup_detector: boolean;
  420. pileup_sensitivity: string; // "low", "medium", "high"
  421. airprint_detector: boolean;
  422. airprint_sensitivity: string; // "low", "medium", "high"
  423. auto_recovery_step_loss: boolean;
  424. filament_tangle_detect: boolean;
  425. }
  426. export interface FilaSwitchState {
  427. installed: boolean;
  428. // in[track] = currently loaded slot for that track (-1 = empty)
  429. in_slots: number[];
  430. // out[track] = extruder this track terminates at (0 = right, 1 = left)
  431. out_extruders: number[];
  432. stat: number;
  433. info: number;
  434. }
  435. export interface PrinterStatus {
  436. id: number;
  437. name: string;
  438. connected: boolean;
  439. state: string | null;
  440. current_print: string | null;
  441. subtask_name: string | null;
  442. current_archive_id: number | null;
  443. current_plate_id: number | null;
  444. gcode_file: string | null;
  445. progress: number | null;
  446. remaining_time: number | null;
  447. layer_num: number | null;
  448. total_layers: number | null;
  449. temperatures: {
  450. bed?: number;
  451. bed_target?: number;
  452. bed_heating?: boolean; // Actual heater state from MQTT
  453. nozzle?: number;
  454. nozzle_target?: number;
  455. nozzle_heating?: boolean; // Actual heater state from MQTT
  456. nozzle_2?: number; // Second nozzle for H2 series (dual nozzle)
  457. nozzle_2_target?: number;
  458. nozzle_2_heating?: boolean; // Actual heater state from MQTT
  459. chamber?: number;
  460. chamber_target?: number;
  461. chamber_heating?: boolean; // Actual heater state from MQTT
  462. } | null;
  463. cover_url: string | null;
  464. hms_errors: HMSError[];
  465. ams: AMSUnit[];
  466. ams_exists: boolean;
  467. vt_tray: AMSTray[]; // Virtual tray / external spool(s)
  468. store_to_sdcard: boolean; // Store sent files on SD card
  469. timelapse: boolean; // Timelapse recording active
  470. ipcam: boolean; // Live view enabled
  471. wifi_signal: number | null; // WiFi signal strength in dBm
  472. wired_network: boolean; // Ethernet connection detected
  473. door_open: boolean; // Enclosure door open (models with a door sensor: X1/X1C/X1E/X2D/P2S/H2*)
  474. nozzles: NozzleInfo[]; // Nozzle hardware info (index 0=left/primary, 1=right)
  475. nozzle_rack: NozzleRackSlot[]; // H2C 6-nozzle tool-changer rack
  476. print_options: PrintOptions | null; // AI detection and print options
  477. // Calibration stage tracking
  478. stg_cur: number; // Current stage number (-1 = not calibrating)
  479. stg_cur_name: string | null; // Human-readable current stage name
  480. stg: number[]; // List of stage numbers in calibration sequence
  481. // Air conditioning mode (0=cooling, 1=heating)
  482. airduct_mode: number;
  483. // Print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  484. speed_level: number;
  485. // Chamber light on/off
  486. chamber_light: boolean;
  487. // Active extruder for dual nozzle (0=right, 1=left)
  488. active_extruder: number;
  489. // AMS mapping - which AMS is connected to which nozzle
  490. // Format: [ams_id_for_nozzle0, ams_id_for_nozzle1, ...] where -1 means no AMS
  491. ams_mapping: number[];
  492. // Per-AMS extruder mapping - extracted from each AMS unit's info field
  493. // Format: {ams_id: extruder_id} where extruder 0=right, 1=left
  494. // Note: JSON keys are always strings
  495. ams_extruder_map: Record<string, number>;
  496. // Filament Track Switch accessory — null when not installed. When present,
  497. // AMS slots aren't tied to a specific extruder; the FTS routes any slot to
  498. // either extruder, so per-extruder slot filtering must be skipped.
  499. fila_switch: FilaSwitchState | null;
  500. // Currently loaded tray (global tray ID, 255 = no filament loaded, 254 = external spool)
  501. tray_now: number;
  502. // Runout / filament-replacement guidance (#2587). Populated only while PAUSED.
  503. // Global tray IDs (ams_id*4+slot, 128-135 = AMS-HT, 254 = external), matching
  504. // the same numbering as tray_now so the AMS graphic can highlight them.
  505. // expected_tray = the slot the firmware now expects filament in (null = idle,
  506. // not paused, or unresolvable → "check the printer").
  507. // previous_tray = the slot that ran out (null = unknown).
  508. expected_tray: number | null;
  509. previous_tray: number | null;
  510. // AMS status for filament change tracking (0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration)
  511. ams_status_main: number;
  512. // AMS sub-status for filament change step (when main=1): 4=retraction, 6=load verification, 7=purge
  513. ams_status_sub: number;
  514. // mc_print_sub_stage - filament change step indicator used by OrcaSlicer/BambuStudio
  515. mc_print_sub_stage: number;
  516. // Timestamp of last AMS data update (for RFID refresh detection)
  517. last_ams_update: number;
  518. // Number of printable objects in current print (for skip objects feature)
  519. printable_objects_count: number;
  520. // Fan speeds (0-100 percentage, null if not available for this model)
  521. cooling_fan_speed: number | null; // Part cooling fan
  522. big_fan1_speed: number | null; // Auxiliary fan
  523. big_fan2_speed: number | null; // Chamber/exhaust fan
  524. heatbreak_fan_speed: number | null; // Hotend heatbreak fan
  525. // Left auxiliary part cooling fan (optional P2S/X2D accessory, M106 P10).
  526. // null = not installed / not reported by this model.
  527. left_aux_fan_speed: number | null;
  528. // Chamber exhaust fan present (P2S/X2D External Exhaust Fan kit, airduct part 3).
  529. exhaust_fan_present: boolean;
  530. firmware_version: string | null; // Firmware version from MQTT
  531. // Developer LAN mode: true = enabled, false = disabled, null = unknown
  532. developer_mode: boolean | null;
  533. // AMS Filament Backup ("auto-switch" to a backup spool when one runs out).
  534. // true = ON, false = OFF, null = unknown / unsupported (A1 family).
  535. ams_filament_backup: boolean | null;
  536. // Queue: printer is awaiting user ack that the build plate was cleared after a
  537. // finished/failed print. Persisted across restarts (#961).
  538. awaiting_plate_clear: boolean;
  539. // AMS drying support
  540. supports_drying: boolean;
  541. // The AMS can dry, but only from the printer's own screen (P1 series, #2533).
  542. drying_screen_only?: boolean;
  543. // Active chamber heater (responds to M141). True only for H2C/H2D/H2DPro/H2S/X2D.
  544. supports_chamber_heater?: boolean;
  545. }
  546. export interface PrinterCreate {
  547. name: string;
  548. serial_number: string;
  549. ip_address: string;
  550. access_code: string;
  551. model?: string;
  552. location?: string;
  553. auto_archive?: boolean;
  554. // Maintenance Mode flag (#1476). Backend already gates MQTT, queue dispatch,
  555. // scheduler, metrics and the print picker on this; toggling via PATCH
  556. // /printers/{id} disconnects or reconnects MQTT accordingly.
  557. is_active?: boolean;
  558. external_camera_url?: string | null;
  559. external_camera_type?: string | null;
  560. external_camera_enabled?: boolean;
  561. external_camera_snapshot_url?: string | null;
  562. camera_rotation?: number;
  563. plate_detection_enabled?: boolean;
  564. plate_detection_roi?: PlateDetectionROI;
  565. }
  566. // Plate Detection
  567. export interface PlateDetectionROI {
  568. x: number; // X start % (0.0-1.0)
  569. y: number; // Y start % (0.0-1.0)
  570. w: number; // Width % (0.0-1.0)
  571. h: number; // Height % (0.0-1.0)
  572. }
  573. export interface PlateDetectionResult {
  574. is_empty: boolean;
  575. confidence: number;
  576. difference_percent: number;
  577. message: string;
  578. has_debug_image: boolean;
  579. debug_image_url?: string;
  580. needs_calibration: boolean;
  581. light_warning?: boolean;
  582. reference_count?: number;
  583. max_references?: number;
  584. roi?: PlateDetectionROI;
  585. }
  586. export interface PlateDetectionStatus {
  587. available: boolean;
  588. calibrated: boolean;
  589. reference_count: number;
  590. max_references: number;
  591. message: string;
  592. }
  593. export interface CalibrationResult {
  594. success: boolean;
  595. message: string;
  596. }
  597. export interface PlateReference {
  598. index: number;
  599. label: string;
  600. timestamp: string;
  601. has_image: boolean;
  602. thumbnail_url: string;
  603. }
  604. // Archive types
  605. export interface ArchiveDuplicate {
  606. id: number;
  607. print_name: string | null;
  608. created_at: string;
  609. match_type: 'exact' | 'similar'; // 'exact' = hash match, 'similar' = name match
  610. }
  611. export interface Archive {
  612. id: number;
  613. printer_id: number | null;
  614. project_id: number | null;
  615. project_name: string | null;
  616. filename: string;
  617. file_path: string;
  618. file_size: number;
  619. content_hash: string | null;
  620. thumbnail_path: string | null;
  621. timelapse_path: string | null;
  622. source_3mf_path: string | null;
  623. f3d_path: string | null;
  624. duplicates: ArchiveDuplicate[] | null;
  625. duplicate_count: number;
  626. duplicate_sequence: number; // 0 = original, 1+ = nth duplicate
  627. original_archive_id: number | null; // ID of the first/original archive
  628. object_count: number | null;
  629. print_name: string | null;
  630. plate_id: number | null; // Selected plate of a multi-plate 3MF (#2603)
  631. print_time_seconds: number | null;
  632. actual_time_seconds: number | null; // Computed from started_at/completed_at
  633. time_accuracy: number | null; // Percentage: 100 = perfect, >100 = faster than estimated
  634. filament_used_grams: number | null;
  635. filament_type: string | null;
  636. filament_color: string | null;
  637. layer_height: number | null;
  638. total_layers: number | null;
  639. nozzle_diameter: number | null;
  640. bed_temperature: number | null;
  641. bed_type: string | null; // Build plate type from 3MF (e.g. "Cool Plate", "Textured PEI Plate")
  642. nozzle_temperature: number | null;
  643. sliced_for_model: string | null; // Printer model this file was sliced for
  644. status: string;
  645. started_at: string | null;
  646. completed_at: string | null;
  647. extra_data: Record<string, unknown> | null;
  648. makerworld_url: string | null;
  649. designer: string | null;
  650. external_url: string | null;
  651. is_favorite: boolean;
  652. tags: string | null;
  653. notes: string | null;
  654. cost: number | null;
  655. photos: string[] | null;
  656. failure_reason: string | null;
  657. quantity: number;
  658. energy_kwh: number | null;
  659. energy_cost: number | null;
  660. created_at: string;
  661. // User tracking (Issue #206)
  662. created_by_id: number | null;
  663. created_by_username: string | null;
  664. // Per-archive run aggregates from PrintLogEntry (#1378)
  665. run_count: number;
  666. last_run_at: string | null;
  667. total_filament_actual_grams: number | null;
  668. successful_run_count: number;
  669. failed_run_count: number;
  670. }
  671. export interface ArchiveSlim {
  672. printer_id: number | null;
  673. print_name: string | null;
  674. print_time_seconds: number | null;
  675. actual_time_seconds: number | null;
  676. filament_used_grams: number | null;
  677. filament_type: string | null;
  678. filament_color: string | null;
  679. status: string;
  680. started_at: string | null;
  681. completed_at: string | null;
  682. cost: number | null;
  683. energy_kwh: number | null;
  684. energy_cost: number | null;
  685. quantity: number;
  686. created_at: string;
  687. }
  688. export interface PrintLogEntry {
  689. id: number;
  690. archive_id: number | null;
  691. print_name: string | null;
  692. printer_name: string | null;
  693. printer_id: number | null;
  694. status: string;
  695. started_at: string | null;
  696. completed_at: string | null;
  697. duration_seconds: number | null;
  698. filament_type: string | null;
  699. filament_color: string | null;
  700. filament_used_grams: number | null;
  701. cost: number | null;
  702. energy_kwh: number | null;
  703. energy_cost: number | null;
  704. failure_reason: string | null;
  705. thumbnail_path: string | null;
  706. created_by_id: number | null;
  707. created_by_username: string | null;
  708. created_at: string;
  709. }
  710. export interface PrintLogResponse {
  711. items: PrintLogEntry[];
  712. total: number;
  713. }
  714. export interface ArchiveStats {
  715. total_prints: number;
  716. successful_prints: number;
  717. failed_prints: number;
  718. cancelled_prints: number;
  719. total_print_time_hours: number;
  720. total_filament_grams: number;
  721. total_cost: number;
  722. prints_by_filament_type: Record<string, number>;
  723. prints_by_printer: Record<string, number>;
  724. average_time_accuracy: number | null;
  725. time_accuracy_by_printer: Record<string, number> | null;
  726. total_energy_kwh: number;
  727. total_energy_cost: number;
  728. // True when a date-filtered total-consumption query is running on incomplete
  729. // snapshot history (e.g. right after upgrade, before hourly snapshots have
  730. // a baseline). UI should explain why the number may undercount.
  731. energy_data_warming_up?: boolean;
  732. }
  733. export interface TagInfo {
  734. name: string;
  735. count: number;
  736. }
  737. export interface FailureAnalysis {
  738. period_days: number;
  739. total_prints: number;
  740. failed_prints: number;
  741. failure_rate: number;
  742. failures_by_reason: Record<string, number>;
  743. failures_by_filament: Record<string, number>;
  744. failures_by_printer: Record<string, number>;
  745. failures_by_hour: Record<number, number>;
  746. recent_failures: Array<{
  747. id: number;
  748. print_name: string;
  749. failure_reason: string | null;
  750. filament_type: string | null;
  751. printer_id: number | null;
  752. created_at: string | null;
  753. }>;
  754. trend: Array<{
  755. week_start: string;
  756. total_prints: number;
  757. failed_prints: number;
  758. failure_rate: number;
  759. }>;
  760. }
  761. export interface BulkUploadResult {
  762. uploaded: number;
  763. failed: number;
  764. results: Array<{ filename: string; id: number; status: string }>;
  765. errors: Array<{ filename: string; error: string }>;
  766. }
  767. // Archive Comparison types
  768. export interface ComparisonArchiveInfo {
  769. id: number;
  770. print_name: string;
  771. status: string;
  772. created_at: string | null;
  773. printer_id: number | null;
  774. project_name: string | null;
  775. }
  776. export interface ComparisonField {
  777. field: string;
  778. label: string;
  779. unit: string | null;
  780. values: (string | number | null)[];
  781. raw_values: (string | number | null)[];
  782. has_difference: boolean;
  783. }
  784. export interface SuccessCorrelationInsight {
  785. field: string;
  786. label: string;
  787. insight: string;
  788. success_avg?: number;
  789. failed_avg?: number;
  790. success_values?: string[];
  791. failed_values?: string[];
  792. }
  793. export interface SuccessCorrelation {
  794. has_both_outcomes: boolean;
  795. message?: string;
  796. successful_count?: number;
  797. failed_count?: number;
  798. insights?: SuccessCorrelationInsight[];
  799. }
  800. export interface ArchiveComparison {
  801. archives: ComparisonArchiveInfo[];
  802. comparison: ComparisonField[];
  803. differences: ComparisonField[];
  804. success_correlation: SuccessCorrelation;
  805. }
  806. export interface SimilarArchive {
  807. archive: {
  808. id: number;
  809. print_name: string;
  810. status: string;
  811. created_at: string | null;
  812. };
  813. match_reason: string;
  814. match_score: number;
  815. }
  816. // Project types
  817. export interface ProjectStats {
  818. total_archives: number;
  819. total_items: number; // Sum of quantities (total items printed)
  820. completed_prints: number; // Sum of quantities for completed prints (parts)
  821. failed_prints: number;
  822. queued_prints: number;
  823. in_progress_prints: number;
  824. total_print_time_hours: number;
  825. total_filament_grams: number;
  826. progress_percent: number | null; // Plates progress (total_archives / target_count)
  827. parts_progress_percent: number | null; // Parts progress (completed_prints / target_parts_count)
  828. estimated_cost: number;
  829. total_energy_kwh: number;
  830. total_energy_cost: number;
  831. remaining_prints: number | null; // Remaining plates
  832. remaining_parts: number | null; // Remaining parts
  833. bom_total_items: number;
  834. bom_completed_items: number;
  835. bom_cost: number;
  836. }
  837. export interface ProjectChildPreview {
  838. id: number;
  839. name: string;
  840. color: string | null;
  841. status: string;
  842. progress_percent: number | null;
  843. }
  844. export interface Project {
  845. id: number;
  846. name: string;
  847. description: string | null;
  848. color: string | null;
  849. status: string; // active, completed, archived
  850. target_count: number | null; // Target number of plates/print jobs
  851. target_parts_count: number | null; // Target number of parts/objects
  852. target_sets: number | null; // Copies-per-file target (#1897)
  853. notes: string | null;
  854. attachments: ProjectAttachment[] | null;
  855. tags: string | null;
  856. due_date: string | null;
  857. priority: string; // low, normal, high, urgent
  858. budget: number | null;
  859. is_template: boolean;
  860. template_source_id: number | null;
  861. parent_id: number | null;
  862. parent_name: string | null;
  863. children: ProjectChildPreview[];
  864. created_at: string;
  865. updated_at: string;
  866. stats?: ProjectStats;
  867. url: string | null; // External link rendered next to project name on the card (#1155)
  868. cover_image_filename: string | null; // Filename within project attachments dir (#1155)
  869. }
  870. export interface ProjectAttachment {
  871. filename: string;
  872. original_name: string;
  873. size: number;
  874. uploaded_at: string;
  875. }
  876. // Completed-run count for one library file inside a project (#1897)
  877. export interface ProjectFileProgress {
  878. file_id: number;
  879. completed_count: number;
  880. }
  881. export interface ArchivePreview {
  882. id: number;
  883. print_name: string | null;
  884. thumbnail_path: string | null;
  885. status: string;
  886. filament_type: string | null;
  887. filament_color: string | null;
  888. }
  889. export interface ProjectListItem {
  890. id: number;
  891. name: string;
  892. description: string | null;
  893. color: string | null;
  894. status: string;
  895. target_count: number | null; // Target number of plates/print jobs
  896. target_parts_count: number | null; // Target number of parts/objects
  897. target_sets: number | null; // #1897 — the shared edit dialog seeds itself from this
  898. budget: number | null;
  899. tags: string | null; // #2536 — the shared edit dialog seeds itself from this
  900. due_date: string | null; // #2536
  901. priority: string; // #2536
  902. created_at: string;
  903. archive_count: number; // Number of print jobs (plates)
  904. total_items: number; // Sum of quantities (total items printed, including failed)
  905. completed_count: number; // Sum of quantities for completed prints only (parts)
  906. failed_count: number; // Sum of quantities for failed prints
  907. queue_count: number;
  908. progress_percent: number | null; // Plates progress
  909. archives: ArchivePreview[];
  910. url: string | null; // #1155
  911. cover_image_filename: string | null; // #1155
  912. }
  913. export interface ProjectCreate {
  914. name: string;
  915. description?: string;
  916. color?: string;
  917. target_count?: number;
  918. target_parts_count?: number;
  919. target_sets?: number;
  920. notes?: string;
  921. tags?: string;
  922. due_date?: string;
  923. priority?: string;
  924. budget?: number | null;
  925. parent_id?: number;
  926. url?: string | null; // #1155
  927. }
  928. export interface ProjectUpdate {
  929. name?: string;
  930. description?: string;
  931. color?: string;
  932. status?: string;
  933. target_count?: number;
  934. target_parts_count?: number;
  935. target_sets?: number | null; // #1897 — explicit null clears the copies-per-file target
  936. notes?: string;
  937. tags?: string | null; // #2536 — explicit null clears the tags
  938. due_date?: string | null; // #2536 — explicit null clears the due date
  939. priority?: string;
  940. budget?: number | null;
  941. parent_id?: number;
  942. url?: string | null; // #1155 — explicit null clears the URL
  943. }
  944. // BOM Types - Tracks sourced/purchased parts (hardware, electronics, etc.)
  945. export interface BOMItem {
  946. id: number;
  947. project_id: number;
  948. name: string;
  949. quantity_needed: number;
  950. quantity_acquired: number;
  951. unit_price: number | null;
  952. sourcing_url: string | null;
  953. archive_id: number | null;
  954. archive_name: string | null;
  955. stl_filename: string | null;
  956. remarks: string | null;
  957. sort_order: number;
  958. is_complete: boolean;
  959. created_at: string;
  960. updated_at: string;
  961. }
  962. export interface BOMItemCreate {
  963. name: string;
  964. quantity_needed?: number;
  965. unit_price?: number;
  966. sourcing_url?: string;
  967. archive_id?: number;
  968. stl_filename?: string;
  969. remarks?: string;
  970. }
  971. export interface BOMItemUpdate {
  972. name?: string;
  973. quantity_needed?: number;
  974. quantity_acquired?: number;
  975. unit_price?: number;
  976. sourcing_url?: string;
  977. archive_id?: number;
  978. stl_filename?: string;
  979. remarks?: string;
  980. }
  981. // Project Export/Import Types
  982. export interface BOMItemExport {
  983. name: string;
  984. quantity_needed: number;
  985. quantity_acquired: number;
  986. unit_price: number | null;
  987. sourcing_url: string | null;
  988. stl_filename: string | null;
  989. remarks: string | null;
  990. }
  991. export interface LinkedFolderExport {
  992. name: string;
  993. }
  994. export interface ProjectExport {
  995. name: string;
  996. description: string | null;
  997. color: string | null;
  998. status: string;
  999. target_count: number | null;
  1000. target_parts_count: number | null;
  1001. target_sets: number | null; // #1897
  1002. notes: string | null;
  1003. tags: string | null;
  1004. due_date: string | null;
  1005. priority: string;
  1006. budget: number | null;
  1007. bom_items: BOMItemExport[];
  1008. linked_folders: LinkedFolderExport[];
  1009. }
  1010. export interface ProjectImport {
  1011. name: string;
  1012. description?: string;
  1013. color?: string;
  1014. status?: string;
  1015. target_count?: number;
  1016. target_parts_count?: number;
  1017. target_sets?: number; // #1897
  1018. notes?: string;
  1019. tags?: string;
  1020. due_date?: string;
  1021. priority?: string;
  1022. budget?: number | null;
  1023. bom_items?: BOMItemExport[];
  1024. linked_folders?: LinkedFolderExport[];
  1025. }
  1026. // Timeline Types
  1027. export interface TimelineEvent {
  1028. event_type: string;
  1029. timestamp: string;
  1030. title: string;
  1031. description: string | null;
  1032. metadata: Record<string, unknown> | null;
  1033. }
  1034. // API Key types
  1035. export interface APIKey {
  1036. id: number;
  1037. name: string;
  1038. key_prefix: string;
  1039. user_id: number | null; // Owner; null on legacy keys created before per-user ownership (#1182)
  1040. can_queue: boolean;
  1041. can_control_printer: boolean;
  1042. can_read_status: boolean;
  1043. can_manage_library: boolean;
  1044. can_manage_inventory: boolean;
  1045. can_manage_maintenance: boolean;
  1046. can_manage_archives: boolean;
  1047. can_manage_projects: boolean;
  1048. can_access_cloud: boolean;
  1049. can_update_energy_cost: boolean;
  1050. printer_ids: number[] | null;
  1051. enabled: boolean;
  1052. last_used: string | null;
  1053. created_at: string;
  1054. expires_at: string | null;
  1055. }
  1056. export interface APIKeyCreate {
  1057. name: string;
  1058. can_queue?: boolean;
  1059. can_control_printer?: boolean;
  1060. can_read_status?: boolean;
  1061. can_manage_library?: boolean;
  1062. can_manage_inventory?: boolean;
  1063. can_manage_maintenance?: boolean;
  1064. can_manage_archives?: boolean;
  1065. can_manage_projects?: boolean;
  1066. can_access_cloud?: boolean;
  1067. can_update_energy_cost?: boolean;
  1068. printer_ids?: number[] | null;
  1069. expires_at?: string | null;
  1070. }
  1071. export interface APIKeyCreateResponse extends APIKey {
  1072. key: string; // Full key, only shown on creation
  1073. }
  1074. export interface APIKeyUpdate {
  1075. name?: string;
  1076. can_queue?: boolean;
  1077. can_control_printer?: boolean;
  1078. can_read_status?: boolean;
  1079. can_manage_library?: boolean;
  1080. can_manage_inventory?: boolean;
  1081. can_manage_maintenance?: boolean;
  1082. can_manage_archives?: boolean;
  1083. can_manage_projects?: boolean;
  1084. can_access_cloud?: boolean;
  1085. can_update_energy_cost?: boolean;
  1086. printer_ids?: number[] | null;
  1087. enabled?: boolean;
  1088. expires_at?: string | null;
  1089. }
  1090. /**
  1091. * Tri-state calibration option (BambuStudio parity): "off" never runs it,
  1092. * "on" forces it every print, "auto" lets the printer skip it if it was done
  1093. * recently. Used by bed_levelling, flow_cali, and nozzle_offset_cali.
  1094. */
  1095. export type CalibrationMode = 'off' | 'on' | 'auto';
  1096. // Settings types
  1097. export interface AppSettings {
  1098. auto_archive: boolean;
  1099. save_thumbnails: boolean;
  1100. capture_finish_photo: boolean;
  1101. finish_photo_restore_plate: boolean;
  1102. default_filament_cost: number;
  1103. currency: string;
  1104. energy_cost_per_kwh: number;
  1105. energy_tracking_mode: 'print' | 'total';
  1106. check_updates: boolean;
  1107. check_printer_firmware: boolean;
  1108. include_beta_updates: boolean;
  1109. // #1589: false hides the local username/password form on the login page;
  1110. // BAMBUDDY_LOCAL_LOGIN=true on the server flips the reported value back to
  1111. // true so the env-var recovery path is visible to the SPA.
  1112. local_login_enabled: boolean;
  1113. language: string;
  1114. notification_language: string;
  1115. // AMS threshold settings
  1116. ams_humidity_good: number; // <= this is green
  1117. ams_humidity_fair: number; // <= this is orange, > is red
  1118. ams_temp_good: number; // <= this is green/blue
  1119. ams_temp_fair: number; // <= this is orange, > is red
  1120. ams_history_retention_days: number; // days to keep AMS sensor history
  1121. // Queue auto-drying settings
  1122. queue_drying_enabled: boolean; // Auto-dry AMS between queued prints
  1123. queue_drying_block: boolean; // Block queue until drying completes
  1124. ambient_drying_enabled: boolean; // Auto-dry idle printers based on humidity regardless of queue
  1125. print_drying_enabled: boolean; // Continue drying while a print is running on capable hardware
  1126. drying_presets: string; // JSON blob of drying presets per filament type
  1127. ams_humidity_thresholds: string; // JSON blob of per-filament humidity thresholds (#1605)
  1128. gcode_snippets: string; // JSON: per-model G-code injection snippets
  1129. // Scheduled local backup
  1130. local_backup_enabled: boolean;
  1131. local_backup_schedule: string;
  1132. local_backup_time: string;
  1133. local_backup_retention: number;
  1134. local_backup_path: string;
  1135. // Print modal settings
  1136. per_printer_mapping_expanded: boolean; // Whether custom mapping is expanded by default in print modal
  1137. // Date/time format settings
  1138. date_format: 'system' | 'us' | 'eu' | 'iso';
  1139. time_format: 'system' | '12h' | '24h';
  1140. // Filament tracking
  1141. disable_filament_warnings: boolean; // Disable filament warnings (print insufficiency and assignment mismatch)
  1142. prefer_lowest_filament: boolean; // When multiple spools match, prefer lowest remaining filament
  1143. spoolman_enabled: boolean; // True when the user has switched filament tracking to Spoolman; backend includes this in the /settings/ response even though earlier consumers read it from the dedicated /settings/spoolman endpoint as a string
  1144. auto_add_unknown_rfid: boolean; // When false, the backend skips auto-creating inventory spools for unknown RFID tags and instead broadcasts an unknown_tag event for the confirmation modal
  1145. spoolman_url: string;
  1146. // Default printer
  1147. default_printer_id: number | null;
  1148. pipeline_max_copies: number;
  1149. // Dark mode theme settings
  1150. dark_style: 'classic' | 'glow' | 'vibrant';
  1151. dark_background: 'neutral' | 'warm' | 'cool' | 'oled' | 'slate' | 'forest';
  1152. dark_accent: 'green' | 'teal' | 'blue' | 'orange' | 'purple' | 'red';
  1153. // Light mode theme settings
  1154. light_style: 'classic' | 'glow' | 'vibrant';
  1155. light_background: 'neutral' | 'warm' | 'cool';
  1156. light_accent: 'green' | 'teal' | 'blue' | 'orange' | 'purple' | 'red';
  1157. // FTP retry settings
  1158. ftp_retry_enabled: boolean;
  1159. ftp_retry_count: number;
  1160. ftp_retry_delay: number;
  1161. ftp_timeout: number;
  1162. // MQTT relay settings
  1163. mqtt_enabled: boolean;
  1164. mqtt_broker: string;
  1165. mqtt_port: number;
  1166. mqtt_username: string;
  1167. mqtt_password: string;
  1168. mqtt_topic_prefix: string;
  1169. mqtt_use_tls: boolean;
  1170. // External URL for notifications
  1171. external_url: string;
  1172. // Home Assistant integration
  1173. ha_enabled: boolean;
  1174. ha_url: string;
  1175. ha_token: string;
  1176. ha_url_from_env: boolean;
  1177. ha_token_from_env: boolean;
  1178. ha_env_managed: boolean;
  1179. // File Manager / Library settings
  1180. library_archive_mode: 'always' | 'never' | 'ask';
  1181. library_disk_warning_gb: number;
  1182. // Camera view settings
  1183. camera_view_mode: 'window' | 'embedded';
  1184. // Preferred slicer (server-side API / sidecar)
  1185. preferred_slicer: 'bambu_studio' | 'orcaslicer';
  1186. // Desktop "Open in Slicer" override (#1329). Null inherits from
  1187. // preferred_slicer so existing installs behave identically.
  1188. open_in_slicer: 'bambu_studio' | 'orcaslicer' | null;
  1189. // Use the slicer-API sidecar for slicing (in-app modal) vs desktop URI scheme
  1190. use_slicer_api: boolean;
  1191. // Per-install sidecar URLs. Empty string falls back to the env defaults.
  1192. orcaslicer_api_url: string;
  1193. bambu_studio_api_url: string;
  1194. // Minutes of silence from the sidecar before a slice is abandoned. Bounds
  1195. // stalls, not total slicing time — a model that keeps reporting progress
  1196. // runs to completion however long it takes.
  1197. slicer_stall_timeout_minutes: number;
  1198. // Prometheus metrics
  1199. prometheus_enabled: boolean;
  1200. prometheus_token: string;
  1201. // Bed cooled threshold
  1202. bed_cooled_threshold: number;
  1203. // Inventory low stock threshold
  1204. low_stock_threshold: number;
  1205. // Session policy (#1706) — admin-set ceiling, hours, [1, 720]
  1206. session_max_hours: number;
  1207. // User email notifications toggle
  1208. user_notifications_enabled: boolean;
  1209. // Default print options
  1210. default_bed_levelling: CalibrationMode;
  1211. default_flow_cali: CalibrationMode;
  1212. default_vibration_cali: boolean;
  1213. default_layer_inspect: boolean;
  1214. default_timelapse: boolean;
  1215. default_nozzle_offset_cali: CalibrationMode;
  1216. // Staggered batch start defaults
  1217. stagger_group_size: number;
  1218. stagger_interval_minutes: number;
  1219. // Plate-clear confirmation
  1220. require_plate_clear: boolean;
  1221. // Shortest job first scheduling
  1222. queue_shortest_first: boolean;
  1223. // How many printers the queue may upload to at once (#2555). 1 restores the
  1224. // old strictly-serial behaviour, where every printer waited out every other
  1225. // printer's transfer.
  1226. queue_max_concurrent_uploads: number;
  1227. // Preheat / heat-soak before queued prints (#1468). Master toggle is the
  1228. // default for new queue items; per-item PrintQueueItem.preheat_override can
  1229. // flip the decision per print. Chamber target derives from the loaded AMS
  1230. // filament types via preheat_filament_targets (JSON map of type → °C, max
  1231. // across loaded slots); the per-item override field bypasses derivation.
  1232. preheat_enabled: boolean;
  1233. preheat_filament_targets: string;
  1234. preheat_max_wait_seconds: number;
  1235. preheat_soak_seconds: number;
  1236. // User-configurable presets for the printer-card popovers (JSON arrays of 3 ints).
  1237. // Empty string = use built-in defaults.
  1238. nozzle_temp_presets: string;
  1239. bed_temp_presets: string;
  1240. chamber_temp_presets: string;
  1241. fan_speed_presets: string;
  1242. // Default sidebar order (admin-set for all users)
  1243. default_sidebar_order: string;
  1244. // LDAP authentication
  1245. ldap_enabled: boolean;
  1246. ldap_server_url: string;
  1247. ldap_bind_dn: string;
  1248. ldap_bind_password: string;
  1249. ldap_search_base: string;
  1250. ldap_user_filter: string;
  1251. ldap_security: string;
  1252. ldap_group_mapping: string;
  1253. ldap_auto_provision: boolean;
  1254. ldap_default_group: string;
  1255. obico_enabled: boolean;
  1256. obico_ml_url: string;
  1257. obico_ml_token: string;
  1258. obico_sensitivity: 'low' | 'medium' | 'high';
  1259. obico_action: 'notify' | 'pause' | 'pause_and_off';
  1260. obico_poll_interval: number;
  1261. obico_enabled_printers: string;
  1262. // Inventory forecasting global lead time
  1263. forecast_global_lead_time_days: number;
  1264. }
  1265. export type AppSettingsUpdate = Partial<AppSettings>;
  1266. // MQTT relay status
  1267. export interface MQTTStatus {
  1268. enabled: boolean;
  1269. connected: boolean;
  1270. broker: string;
  1271. port: number;
  1272. topic_prefix: string;
  1273. }
  1274. // Cloud types
  1275. export interface CloudAuthStatus {
  1276. is_authenticated: boolean;
  1277. email: string | null;
  1278. region?: 'global' | 'china' | null;
  1279. /** A token is stored but Bambu no longer accepts it — tell the user why the login form is back. */
  1280. sign_in_expired?: boolean;
  1281. }
  1282. export interface CloudLoginResponse {
  1283. success: boolean;
  1284. needs_verification: boolean;
  1285. message: string;
  1286. verification_type?: 'email' | 'totp' | null;
  1287. tfa_key?: string | null;
  1288. }
  1289. // Orca Cloud types — paste-flow PKCE handshake against auth.orcaslicer.com.
  1290. // See backend/app/services/orca_cloud.py for the deep dive on why this
  1291. // flow is paste-based rather than callback-based.
  1292. export interface OrcaDeviceStartResponse {
  1293. user_code: string;
  1294. verification_uri: string;
  1295. verification_uri_complete: string;
  1296. interval: number;
  1297. expires_in: number;
  1298. }
  1299. export type OrcaDevicePollStatus =
  1300. | 'authorization_pending'
  1301. | 'slow_down'
  1302. | 'access_denied'
  1303. | 'expired_token'
  1304. | 'complete';
  1305. export interface OrcaDevicePollResponse {
  1306. status: OrcaDevicePollStatus;
  1307. connected: boolean;
  1308. email: string | null;
  1309. user_id: string | null;
  1310. }
  1311. export interface OrcaAuthStatusResponse {
  1312. connected: boolean;
  1313. email: string | null;
  1314. user_id: string | null;
  1315. }
  1316. // Orca profiles are shaped to match Bambu Cloud's SlicerSetting on the wire
  1317. // so the frontend can use the same visual components for both surfaces (cards,
  1318. // grouped sections, filter bar). Backend handles the source-specific
  1319. // transformation in routes/orca_cloud.py::_orca_to_setting.
  1320. export interface OrcaProfileMeta {
  1321. setting_id: string;
  1322. name: string;
  1323. type: string;
  1324. version: string | null;
  1325. user_id: string | null;
  1326. updated_time: string | null;
  1327. is_custom: boolean;
  1328. }
  1329. export interface OrcaProfileListResponse {
  1330. filament: OrcaProfileMeta[];
  1331. printer: OrcaProfileMeta[];
  1332. process: OrcaProfileMeta[];
  1333. }
  1334. export interface OrcaProfileDetail {
  1335. setting_id: string;
  1336. name: string;
  1337. type: string;
  1338. version: string | null;
  1339. base_id: string | null;
  1340. update_time: string | null;
  1341. setting: Record<string, unknown>;
  1342. }
  1343. // MakerWorld integration. Full metadata/instance shapes come back as
  1344. // Record<string, unknown> — MakerWorld's API adds fields over time, so we
  1345. // pass them through verbatim rather than maintaining a brittle mirror.
  1346. export interface MakerworldStatus {
  1347. has_cloud_token: boolean;
  1348. can_download: boolean;
  1349. /** A token is stored but Bambu rejected it — downloads will fail until the user signs in again. */
  1350. sign_in_expired?: boolean;
  1351. }
  1352. export interface MakerworldResolvedModel {
  1353. model_id: number;
  1354. profile_id: number | null;
  1355. design: Record<string, unknown>;
  1356. instances: Array<Record<string, unknown>>;
  1357. already_imported_library_ids: number[];
  1358. }
  1359. export interface MakerworldImportResponse {
  1360. library_file_id: number;
  1361. filename: string;
  1362. folder_id: number | null;
  1363. profile_id: number | null;
  1364. was_existing: boolean;
  1365. }
  1366. export interface MakerworldRecentImport {
  1367. library_file_id: number;
  1368. filename: string;
  1369. folder_id: number | null;
  1370. thumbnail_path: string | null;
  1371. source_url: string | null;
  1372. created_at: string;
  1373. }
  1374. export interface SlicerSetting {
  1375. setting_id: string;
  1376. name: string;
  1377. type: string;
  1378. version: string | null;
  1379. user_id: string | null;
  1380. updated_time: string | null;
  1381. is_custom: boolean;
  1382. }
  1383. export interface SpoolCatalogEntry {
  1384. id: number;
  1385. name: string;
  1386. weight: number;
  1387. is_default: boolean;
  1388. }
  1389. export interface StorageLocation {
  1390. id: number;
  1391. name: string;
  1392. identifier: string | null;
  1393. spool_count: number;
  1394. created_at: string;
  1395. updated_at: string;
  1396. }
  1397. export interface ColorCatalogEntry {
  1398. id: number;
  1399. manufacturer: string;
  1400. color_name: string;
  1401. hex_color: string;
  1402. material: string | null;
  1403. is_default: boolean;
  1404. // #1154: optional multi-colour gradient stops + visual effect.
  1405. extra_colors?: string | null;
  1406. effect_type?: string | null;
  1407. }
  1408. export interface ColorLookupResult {
  1409. found: boolean;
  1410. hex_color: string | null;
  1411. material: string | null;
  1412. }
  1413. export interface SlicerSettingsResponse {
  1414. filament: SlicerSetting[];
  1415. printer: SlicerSetting[];
  1416. process: SlicerSetting[];
  1417. }
  1418. export interface SlicerSettingDetail {
  1419. message?: string | null;
  1420. code?: string | null;
  1421. error?: string | null;
  1422. public: boolean;
  1423. version?: string | null;
  1424. type: string;
  1425. name: string;
  1426. update_time?: string | null;
  1427. nickname?: string | null;
  1428. base_id?: string | null;
  1429. setting: Record<string, unknown>;
  1430. filament_id?: string | null;
  1431. setting_id?: string | null;
  1432. }
  1433. export interface SlicerSettingCreate {
  1434. type: string; // 'filament', 'print', or 'printer'
  1435. name: string;
  1436. base_id: string;
  1437. setting: Record<string, unknown>;
  1438. }
  1439. export interface SlicerSettingUpdate {
  1440. name?: string;
  1441. setting?: Record<string, unknown>;
  1442. }
  1443. export interface SlicerSettingDeleteResponse {
  1444. success: boolean;
  1445. message: string;
  1446. }
  1447. // Built-in filament fallback (static table from backend)
  1448. export interface BuiltinFilament {
  1449. filament_id: string;
  1450. name: string;
  1451. }
  1452. // Slice request/response — POST /library/files/{id}/slice and /archives/{id}/slice
  1453. //
  1454. // Two preset shapes are accepted per slot:
  1455. // - Legacy bare integer ids (`*_preset_id`) — pre-cloud-tier clients.
  1456. // - Source-aware refs (`*_preset: PresetRef`) — new SliceModal that picks
  1457. // across cloud / local / standard tiers. Source-aware refs win when both
  1458. // are present in the same payload.
  1459. export type PresetSource = 'orca_cloud' | 'cloud' | 'local' | 'standard';
  1460. export interface PresetRef {
  1461. source: PresetSource;
  1462. id: string;
  1463. }
  1464. export interface SliceRequest {
  1465. printer_preset_id?: number;
  1466. process_preset_id?: number;
  1467. filament_preset_id?: number;
  1468. printer_preset?: PresetRef;
  1469. process_preset?: PresetRef;
  1470. filament_preset?: PresetRef;
  1471. // Multi-color: one PresetRef per plate slot, in plate order. Always
  1472. // preferred over the singular `filament_preset` when both are sent; the
  1473. // backend validator promotes a singular into a one-element list when this
  1474. // is omitted, so legacy single-color clients keep working unchanged.
  1475. filament_presets?: PresetRef[];
  1476. plate?: number;
  1477. export_3mf?: boolean;
  1478. // Build-plate override (#1337). When omitted, the slicer uses the process
  1479. // preset's curr_bed_type as-is. Canonical values match BambuStudio /
  1480. // OrcaSlicer's enum: "Cool Plate", "Engineering Plate", "High Temp Plate",
  1481. // "Textured PEI Plate", "Smooth PEI Plate", "Cool Plate (SuperTack)",
  1482. // "Supertack Plate".
  1483. bed_type?: string | null;
  1484. // "Slice as designed" (#2611). 3MF only: slice using the file's embedded
  1485. // project_settings.config (the designer's own wall count, infill, etc.)
  1486. // instead of the picked profile triplet. The preset refs above are still
  1487. // required by the backend validator but go unused on this path.
  1488. use_embedded_settings?: boolean;
  1489. }
  1490. // GET /api/v1/slicer/presets — unified listing across cloud / local / standard.
  1491. export type SlicerCloudStatus = 'ok' | 'not_authenticated' | 'expired' | 'unreachable';
  1492. export interface UnifiedPreset {
  1493. id: string;
  1494. name: string;
  1495. source: PresetSource;
  1496. // Populated for the filament slot only — used by the SliceModal multi-color
  1497. // pre-pick to score presets against each plate slot's required (type,
  1498. // colour). Optional because the bundled / standard tier rarely carries a
  1499. // colour (colour is a runtime spool attribute on Bambu) and older API
  1500. // responses pre-date these fields entirely.
  1501. filament_type?: string | null;
  1502. filament_colour?: string | null;
  1503. // Printer-preset names a process / filament preset declares itself
  1504. // compatible with. Populated for the local tier (the slicer's own
  1505. // `compatible_printers`); null for cloud / standard. The SliceModal filters
  1506. // the process / filament dropdowns by the selected printer using this when
  1507. // present (#1325).
  1508. compatible_printers?: string[] | null;
  1509. }
  1510. export interface UnifiedPresetsBySlot {
  1511. printer: UnifiedPreset[];
  1512. process: UnifiedPreset[];
  1513. filament: UnifiedPreset[];
  1514. }
  1515. export interface UnifiedPresetsResponse {
  1516. // Priority order: local > orca_cloud > cloud > standard. No cross-tier
  1517. // dedup — every tier surfaces its full list so the user can pick from
  1518. // any source. The order drives auto-pick + visual group rendering only.
  1519. orca_cloud: UnifiedPresetsBySlot;
  1520. cloud: UnifiedPresetsBySlot;
  1521. local: UnifiedPresetsBySlot;
  1522. standard: UnifiedPresetsBySlot;
  1523. cloud_status: SlicerCloudStatus;
  1524. orca_cloud_status: SlicerCloudStatus;
  1525. }
  1526. // Slicer Pipelines (#1425) — named bundles of preset slots the SliceModal
  1527. // can apply in one click. PR A surfaces only the bundle; target_* and
  1528. // fanout_strategy round-trip from the backend but the UI doesn't yet expose
  1529. // them (they come alive in PR B / PR C).
  1530. export interface SlicerPipeline {
  1531. id: number;
  1532. name: string;
  1533. description: string | null;
  1534. printer_preset: PresetRef;
  1535. process_preset: PresetRef;
  1536. filament_presets: PresetRef[];
  1537. bed_type: string | null;
  1538. target_kind: 'specific_printer' | 'printer_class';
  1539. target_printer_id: number | null;
  1540. target_model_class: string | null;
  1541. fanout_strategy: 'max_parallel' | 'fill_one_first' | 'round_robin';
  1542. created_by: number | null;
  1543. created_at: string;
  1544. updated_at: string;
  1545. }
  1546. export interface SlicerPipelineCreateRequest {
  1547. name: string;
  1548. description?: string | null;
  1549. printer_preset: PresetRef;
  1550. process_preset: PresetRef;
  1551. filament_presets: PresetRef[];
  1552. bed_type?: string | null;
  1553. }
  1554. export type SlicerPipelineUpdateRequest = Partial<SlicerPipelineCreateRequest> & {
  1555. target_kind?: 'specific_printer' | 'printer_class';
  1556. // ``target_printer_id: 0`` means "clear the target" — the backend maps that
  1557. // to null. Use null in TypeScript for the same intent.
  1558. target_printer_id?: number | null;
  1559. target_model_class?: string | null;
  1560. fanout_strategy?: 'max_parallel' | 'fill_one_first' | 'round_robin';
  1561. };
  1562. export interface SlicerPipelinesListResponse {
  1563. pipelines: SlicerPipeline[];
  1564. }
  1565. // Slicer Pipeline runs (#1425 PR B + PR C)
  1566. export type PipelineEligibilityKind =
  1567. | 'printer_not_set'
  1568. | 'printer_not_found'
  1569. | 'printer_disabled'
  1570. | 'printer_offline'
  1571. | 'filament_type_mismatch'
  1572. | 'filament_color_mismatch'
  1573. | 'ams_slot_missing'
  1574. | 'filament_unverified'
  1575. | 'no_class_matches'
  1576. | 'class_not_set';
  1577. export interface PipelineEligibilityIssue {
  1578. kind: PipelineEligibilityKind;
  1579. slot_index: number | null;
  1580. expected: string | null;
  1581. actual: string | null;
  1582. }
  1583. export interface PipelinePerPrinterReport {
  1584. printer_id: number;
  1585. printer_name: string;
  1586. ok: boolean;
  1587. issues: PipelineEligibilityIssue[];
  1588. }
  1589. export interface PipelineEligibilityReport {
  1590. ok: boolean;
  1591. target_kind: 'specific_printer' | 'printer_class';
  1592. target_printer_id: number | null;
  1593. target_printer_name: string | null;
  1594. target_model_class: string | null;
  1595. issues: PipelineEligibilityIssue[];
  1596. printer_reports: PipelinePerPrinterReport[];
  1597. }
  1598. export interface PipelineJob {
  1599. id: number;
  1600. pipeline_run_id: number;
  1601. copy_index: number;
  1602. assigned_printer_id: number | null;
  1603. assigned_printer_name: string | null;
  1604. queue_entry_id: number | null;
  1605. status:
  1606. | 'pending'
  1607. | 'awaiting_printer'
  1608. | 'queued'
  1609. | 'printing'
  1610. | 'completed'
  1611. | 'failed'
  1612. | 'cancelled';
  1613. error_message: string | null;
  1614. dispatched_at: string | null;
  1615. completed_at: string | null;
  1616. }
  1617. export interface PipelineRun {
  1618. id: number;
  1619. pipeline_id: number | null;
  1620. pipeline_name: string | null;
  1621. source_library_file_id: number | null;
  1622. source_archive_id: number | null;
  1623. source_filename: string | null;
  1624. parent_run_id: number | null;
  1625. copies: number;
  1626. copies_completed: number;
  1627. copies_failed: number;
  1628. copies_cancelled: number;
  1629. copies_in_progress: number;
  1630. status:
  1631. | 'queued'
  1632. | 'slicing'
  1633. | 'dispatching'
  1634. | 'in_progress'
  1635. | 'completed'
  1636. | 'failed'
  1637. | 'partial_failure'
  1638. | 'cancelled';
  1639. slice_job_id: number | null;
  1640. sliced_library_file_id: number | null;
  1641. eligibility_overridden: boolean;
  1642. error_message: string | null;
  1643. created_by: number | null;
  1644. created_at: string;
  1645. started_at: string | null;
  1646. completed_at: string | null;
  1647. jobs: PipelineJob[];
  1648. target_kind: 'specific_printer' | 'printer_class' | null;
  1649. target_printer_id: number | null;
  1650. target_model_class: string | null;
  1651. fanout_strategy: 'max_parallel' | 'fill_one_first' | 'round_robin' | null;
  1652. }
  1653. export interface PipelineRunListResponse {
  1654. runs: PipelineRun[];
  1655. total: number;
  1656. }
  1657. export interface SliceResponse {
  1658. library_file_id: number;
  1659. name: string;
  1660. print_time_seconds: number;
  1661. filament_used_g: number;
  1662. filament_used_mm: number;
  1663. used_embedded_settings: boolean;
  1664. }
  1665. export interface SliceArchiveResponse {
  1666. archive_id: number;
  1667. name: string;
  1668. print_time_seconds: number;
  1669. filament_used_g: number;
  1670. filament_used_mm: number;
  1671. used_embedded_settings: boolean;
  1672. }
  1673. // Background slice-job lifecycle. POST /slice returns 202 + this shape;
  1674. // the frontend polls /slice-jobs/{id} until status is terminal.
  1675. export type SliceJobStatus = 'pending' | 'running' | 'completed' | 'failed';
  1676. export interface SliceJobEnqueueResponse {
  1677. job_id: number;
  1678. status: SliceJobStatus;
  1679. status_url: string;
  1680. }
  1681. export interface SliceJobProgress {
  1682. /** Stage label emitted by the slicer ("Generating G-code", "Slicing finished"). */
  1683. stage: string;
  1684. total_percent: number;
  1685. plate_percent: number;
  1686. /** 1-indexed plate position; 0 means "all plates" / final completion. */
  1687. plate_index: number;
  1688. plate_count: number;
  1689. updated_at: number;
  1690. /** When the backend is in the cross-class slice-all loop (#1493), each
  1691. * per-plate sub-slice's progress is augmented with the loop position
  1692. * so the toast can show "Plate 2 of 5 — Generating G-code 47%". The
  1693. * fields are absent on a single-plate slice. */
  1694. multi_plate_index?: number;
  1695. multi_plate_count?: number;
  1696. }
  1697. export interface SliceJobState {
  1698. job_id: number;
  1699. status: SliceJobStatus;
  1700. kind: 'library_file' | 'archive';
  1701. source_id: number;
  1702. source_name: string;
  1703. created_at: string;
  1704. started_at: string | null;
  1705. completed_at: string | null;
  1706. /** Live progress fed by the sidecar's --pipe channel; null until the
  1707. * slicer emits its first frame (early "Initializing" phase) or when
  1708. * the sidecar doesn't support progress. */
  1709. progress: SliceJobProgress | null;
  1710. result?: SliceResponse | SliceArchiveResponse;
  1711. error_status?: number;
  1712. error_detail?: string;
  1713. }
  1714. // Local preset types (OrcaSlicer imports)
  1715. export interface LocalPreset {
  1716. id: number;
  1717. name: string;
  1718. preset_type: string;
  1719. source: string;
  1720. filament_type: string | null;
  1721. filament_vendor: string | null;
  1722. nozzle_temp_min: number | null;
  1723. nozzle_temp_max: number | null;
  1724. pressure_advance: string | null;
  1725. default_filament_colour: string | null;
  1726. filament_cost: string | null;
  1727. filament_density: string | null;
  1728. compatible_printers: string | null;
  1729. inherits: string | null;
  1730. version: string | null;
  1731. created_at: string;
  1732. updated_at: string;
  1733. }
  1734. export interface LocalPresetDetail extends LocalPreset {
  1735. setting: Record<string, unknown>;
  1736. }
  1737. export interface LocalPresetsResponse {
  1738. filament: LocalPreset[];
  1739. printer: LocalPreset[];
  1740. process: LocalPreset[];
  1741. }
  1742. export interface ImportResponse {
  1743. success: boolean;
  1744. imported: number;
  1745. skipped: number;
  1746. errors: string[];
  1747. }
  1748. export interface FieldOption {
  1749. value: string;
  1750. label: string;
  1751. }
  1752. export interface FieldDefinition {
  1753. key: string;
  1754. label: string;
  1755. type: 'text' | 'number' | 'boolean' | 'select';
  1756. category: string;
  1757. description?: string;
  1758. options?: FieldOption[];
  1759. unit?: string;
  1760. min?: number;
  1761. max?: number;
  1762. step?: number;
  1763. }
  1764. export interface FieldDefinitionsResponse {
  1765. version: string;
  1766. description: string;
  1767. fields: FieldDefinition[];
  1768. }
  1769. export interface CloudDevice {
  1770. dev_id: string;
  1771. name: string;
  1772. dev_model_name: string | null;
  1773. dev_product_name: string | null;
  1774. online: boolean;
  1775. }
  1776. // Smart Plug types
  1777. export interface SmartPlug {
  1778. id: number;
  1779. name: string;
  1780. plug_type: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  1781. ip_address: string | null; // Required for Tasmota
  1782. ha_entity_id: string | null; // Required for Home Assistant (e.g., "switch.printer_plug", "script.turn_on_printer")
  1783. // Home Assistant energy sensor entities (optional)
  1784. ha_power_entity: string | null;
  1785. ha_energy_today_entity: string | null;
  1786. ha_energy_total_entity: string | null;
  1787. // MQTT fields (required when plug_type="mqtt")
  1788. // Legacy field - kept for backward compatibility
  1789. mqtt_topic: string | null; // Deprecated, use mqtt_power_topic
  1790. mqtt_multiplier: number; // Deprecated, use mqtt_power_multiplier
  1791. // Power monitoring
  1792. mqtt_power_topic: string | null; // Topic for power data
  1793. mqtt_power_path: string | null; // e.g., "power_l1" or "data.power"
  1794. mqtt_power_multiplier: number; // Unit conversion for power
  1795. // Energy monitoring
  1796. mqtt_energy_topic: string | null; // Topic for energy data
  1797. mqtt_energy_path: string | null; // e.g., "energy_l1"
  1798. mqtt_energy_multiplier: number; // Unit conversion for energy
  1799. // State monitoring
  1800. mqtt_state_topic: string | null; // Topic for state data
  1801. mqtt_state_path: string | null; // e.g., "state_l1" for ON/OFF
  1802. mqtt_state_on_value: string | null; // What value means "ON" (e.g., "ON", "true", "1")
  1803. // REST/Webhook fields (required when plug_type="rest")
  1804. rest_on_url: string | null;
  1805. rest_on_body: string | null;
  1806. rest_off_url: string | null;
  1807. rest_off_body: string | null;
  1808. rest_method: string | null;
  1809. rest_headers: string | null;
  1810. rest_status_url: string | null;
  1811. rest_status_path: string | null;
  1812. rest_status_on_value: string | null;
  1813. rest_power_url: string | null;
  1814. rest_power_path: string | null;
  1815. rest_power_multiplier: number;
  1816. rest_energy_url: string | null;
  1817. rest_energy_path: string | null;
  1818. rest_energy_multiplier: number;
  1819. // Lifetime counter, separate from the daily one (#2539). A Shelly reports only
  1820. // this; Today and Yesterday are derived from its hourly snapshots.
  1821. rest_energy_total_path: string | null;
  1822. rest_energy_total_multiplier: number;
  1823. printer_id: number | null;
  1824. // #2629: only a plug that really feeds the printer may mark it offline when
  1825. // switched off. Accessory plugs follow the print cycle without powering it.
  1826. controls_printer_power: boolean;
  1827. enabled: boolean;
  1828. auto_on: boolean;
  1829. auto_off: boolean;
  1830. auto_off_persistent: boolean;
  1831. off_delay_mode: 'time' | 'temperature';
  1832. off_delay_minutes: number;
  1833. off_temp_threshold: number;
  1834. // #1349: auto-off after AMS drying completes.
  1835. auto_off_after_drying: boolean;
  1836. off_delay_after_drying_minutes: number;
  1837. username: string | null;
  1838. password: string | null;
  1839. // Power alerts
  1840. power_alert_enabled: boolean;
  1841. power_alert_high: number | null;
  1842. power_alert_low: number | null;
  1843. power_alert_last_triggered: string | null;
  1844. // Schedule
  1845. schedule_enabled: boolean;
  1846. schedule_on_time: string | null;
  1847. schedule_off_time: string | null;
  1848. // Visibility options
  1849. show_in_switchbar: boolean;
  1850. show_on_printer_card: boolean; // For scripts: show on printer card
  1851. // Status
  1852. last_state: string | null;
  1853. last_checked: string | null;
  1854. auto_off_executed: boolean; // True when auto-off was triggered after print
  1855. created_at: string;
  1856. updated_at: string;
  1857. }
  1858. export interface SmartPlugCreate {
  1859. name: string;
  1860. plug_type?: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  1861. ip_address?: string | null; // Required for Tasmota
  1862. ha_entity_id?: string | null; // Required for Home Assistant
  1863. // Home Assistant energy sensor entities (optional)
  1864. ha_power_entity?: string | null;
  1865. ha_energy_today_entity?: string | null;
  1866. ha_energy_total_entity?: string | null;
  1867. // MQTT fields (required when plug_type="mqtt")
  1868. // Legacy fields - kept for backward compatibility
  1869. mqtt_topic?: string | null;
  1870. mqtt_multiplier?: number;
  1871. // Power monitoring
  1872. mqtt_power_topic?: string | null;
  1873. mqtt_power_path?: string | null;
  1874. mqtt_power_multiplier?: number;
  1875. // Energy monitoring
  1876. mqtt_energy_topic?: string | null;
  1877. mqtt_energy_path?: string | null;
  1878. mqtt_energy_multiplier?: number;
  1879. // State monitoring
  1880. mqtt_state_topic?: string | null;
  1881. mqtt_state_path?: string | null;
  1882. mqtt_state_on_value?: string | null;
  1883. // REST fields
  1884. rest_on_url?: string | null;
  1885. rest_on_body?: string | null;
  1886. rest_off_url?: string | null;
  1887. rest_off_body?: string | null;
  1888. rest_method?: string | null;
  1889. rest_headers?: string | null;
  1890. rest_status_url?: string | null;
  1891. rest_status_path?: string | null;
  1892. rest_status_on_value?: string | null;
  1893. rest_power_url?: string | null;
  1894. rest_power_path?: string | null;
  1895. rest_power_multiplier?: number;
  1896. rest_energy_url?: string | null;
  1897. rest_energy_path?: string | null;
  1898. rest_energy_multiplier?: number;
  1899. rest_energy_total_path?: string | null;
  1900. rest_energy_total_multiplier?: number;
  1901. printer_id?: number | null;
  1902. // #2629
  1903. controls_printer_power?: boolean;
  1904. enabled?: boolean;
  1905. auto_on?: boolean;
  1906. auto_off?: boolean;
  1907. auto_off_persistent?: boolean;
  1908. off_delay_mode?: 'time' | 'temperature';
  1909. off_delay_minutes?: number;
  1910. off_temp_threshold?: number;
  1911. // #1349
  1912. auto_off_after_drying?: boolean;
  1913. off_delay_after_drying_minutes?: number;
  1914. username?: string | null;
  1915. password?: string | null;
  1916. // Power alerts
  1917. power_alert_enabled?: boolean;
  1918. power_alert_high?: number | null;
  1919. power_alert_low?: number | null;
  1920. // Schedule
  1921. schedule_enabled?: boolean;
  1922. schedule_on_time?: string | null;
  1923. schedule_off_time?: string | null;
  1924. // Visibility options
  1925. show_in_switchbar?: boolean;
  1926. show_on_printer_card?: boolean;
  1927. }
  1928. export interface SmartPlugUpdate {
  1929. name?: string;
  1930. plug_type?: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  1931. ip_address?: string | null;
  1932. ha_entity_id?: string | null;
  1933. // Home Assistant energy sensor entities (optional)
  1934. ha_power_entity?: string | null;
  1935. ha_energy_today_entity?: string | null;
  1936. ha_energy_total_entity?: string | null;
  1937. // MQTT fields (legacy)
  1938. mqtt_topic?: string | null;
  1939. mqtt_multiplier?: number;
  1940. // MQTT power fields
  1941. mqtt_power_topic?: string | null;
  1942. mqtt_power_path?: string | null;
  1943. mqtt_power_multiplier?: number;
  1944. // MQTT energy fields
  1945. mqtt_energy_topic?: string | null;
  1946. mqtt_energy_path?: string | null;
  1947. mqtt_energy_multiplier?: number;
  1948. // MQTT state fields
  1949. mqtt_state_topic?: string | null;
  1950. mqtt_state_path?: string | null;
  1951. mqtt_state_on_value?: string | null;
  1952. // REST fields
  1953. rest_on_url?: string | null;
  1954. rest_on_body?: string | null;
  1955. rest_off_url?: string | null;
  1956. rest_off_body?: string | null;
  1957. rest_method?: string | null;
  1958. rest_headers?: string | null;
  1959. rest_status_url?: string | null;
  1960. rest_status_path?: string | null;
  1961. rest_status_on_value?: string | null;
  1962. rest_power_url?: string | null;
  1963. rest_power_path?: string | null;
  1964. rest_power_multiplier?: number;
  1965. rest_energy_url?: string | null;
  1966. rest_energy_path?: string | null;
  1967. rest_energy_multiplier?: number;
  1968. rest_energy_total_path?: string | null;
  1969. rest_energy_total_multiplier?: number;
  1970. printer_id?: number | null;
  1971. // #2629
  1972. controls_printer_power?: boolean;
  1973. enabled?: boolean;
  1974. auto_on?: boolean;
  1975. auto_off?: boolean;
  1976. auto_off_persistent?: boolean;
  1977. off_delay_mode?: 'time' | 'temperature';
  1978. off_delay_minutes?: number;
  1979. off_temp_threshold?: number;
  1980. // #1349
  1981. auto_off_after_drying?: boolean;
  1982. off_delay_after_drying_minutes?: number;
  1983. username?: string | null;
  1984. password?: string | null;
  1985. // Power alerts
  1986. power_alert_enabled?: boolean;
  1987. power_alert_high?: number | null;
  1988. power_alert_low?: number | null;
  1989. // Schedule
  1990. schedule_enabled?: boolean;
  1991. schedule_on_time?: string | null;
  1992. schedule_off_time?: string | null;
  1993. // Visibility options
  1994. show_in_switchbar?: boolean;
  1995. show_on_printer_card?: boolean;
  1996. }
  1997. // Home Assistant entity for smart plug selection
  1998. export interface HAEntity {
  1999. entity_id: string;
  2000. friendly_name: string;
  2001. state: string | null;
  2002. domain: string; // "switch", "light", "input_boolean", "script"
  2003. }
  2004. // Home Assistant sensor entity for energy monitoring
  2005. export interface HASensorEntity {
  2006. entity_id: string;
  2007. friendly_name: string;
  2008. state: string | null;
  2009. unit_of_measurement: string | null; // "W", "kW", "kWh", "Wh"
  2010. }
  2011. export interface HATestConnectionResult {
  2012. success: boolean;
  2013. message: string | null;
  2014. error: string | null;
  2015. }
  2016. export interface SmartPlugEnergy {
  2017. power: number | null; // Current watts
  2018. voltage: number | null; // Volts
  2019. current: number | null; // Amps
  2020. today: number | null; // kWh used today
  2021. yesterday: number | null; // kWh used yesterday
  2022. total: number | null; // Total kWh
  2023. factor: number | null; // Power factor (0-1)
  2024. apparent_power: number | null; // VA
  2025. reactive_power: number | null; // VAr
  2026. }
  2027. export interface SmartPlugStatus {
  2028. state: string | null;
  2029. reachable: boolean;
  2030. device_name: string | null;
  2031. energy: SmartPlugEnergy | null;
  2032. }
  2033. export interface SmartPlugTestResult {
  2034. success: boolean;
  2035. state: string | null;
  2036. device_name: string | null;
  2037. }
  2038. // Tasmota Discovery types
  2039. export interface TasmotaScanStatus {
  2040. running: boolean;
  2041. scanned: number;
  2042. total: number;
  2043. }
  2044. export interface DiscoveredTasmotaDevice {
  2045. ip_address: string;
  2046. name: string;
  2047. module: number | null;
  2048. state: string | null;
  2049. discovered_at: string | null;
  2050. }
  2051. // Print Queue types
  2052. export interface PrintQueueItem {
  2053. id: number;
  2054. printer_id: number | null; // null = unassigned
  2055. target_model: string | null; // Target printer model for model-based assignment
  2056. target_location: string | null; // Target location filter for model-based assignment
  2057. required_filament_types: string[] | null; // Required filament types for model-based assignment
  2058. waiting_reason: string | null; // Why a model-based job hasn't started yet
  2059. // Either archive_id OR library_file_id must be set (archive created at print start)
  2060. archive_id: number | null;
  2061. library_file_id: number | null;
  2062. position: number;
  2063. scheduled_time: string | null;
  2064. require_previous_success: boolean;
  2065. auto_off_after: boolean;
  2066. manual_start: boolean; // Requires manual trigger to start (staged)
  2067. // Set by the dispatch scheduler when the assigned spool can't satisfy
  2068. // any required slot's grams (#1496). Surfaced on the queue row as a
  2069. // "filament short" badge; cleared on a successful ▶ click (live recheck).
  2070. filament_short: boolean;
  2071. // Persistent "Print Anyway" acknowledgement — once true the scheduler
  2072. // skips the deficit check for this item (#1698-followup). Set by the
  2073. // start route when skip_filament_check=true, or at queue creation if
  2074. // PrintModal's deficit warning was acknowledged.
  2075. skip_filament_check: boolean;
  2076. // True when the source archive carries the slicer's own live-resolved
  2077. // AMS-slot pick (extra_data.slicer_ams_mapping) — a reprint reuses that
  2078. // exact physical spool instead of re-deriving one from type/color.
  2079. archive_has_slicer_ams_mapping: boolean;
  2080. ams_mapping: number[] | null; // AMS slot mapping for multi-color prints
  2081. filament_overrides: Array<{ slot_id: number; type: string; color: string; color_name?: string; tray_info_idx?: string; force_color_match?: boolean }> | null; // Filament overrides for model-based assignment
  2082. plate_id: number | null; // Plate ID for multi-plate 3MF files
  2083. // Print options
  2084. bed_levelling: CalibrationMode;
  2085. flow_cali: CalibrationMode;
  2086. vibration_cali: boolean;
  2087. layer_inspect: boolean;
  2088. timelapse: boolean;
  2089. use_ams: boolean;
  2090. nozzle_offset_cali: CalibrationMode;
  2091. preheat_override: 'inherit' | 'on' | 'off';
  2092. preheat_chamber_target_override: number | null;
  2093. status: 'pending' | 'printing' | 'completed' | 'failed' | 'skipped' | 'cancelled';
  2094. started_at: string | null;
  2095. completed_at: string | null;
  2096. error_message: string | null;
  2097. created_at: string;
  2098. archive_name?: string | null;
  2099. archive_thumbnail?: string | null;
  2100. // True when the linked archive has been soft-deleted; archive_name /
  2101. // archive_thumbnail / downstream metadata are left null in that case so
  2102. // the UI doesn't 404-storm the now-missing endpoints (#1348 follow-up).
  2103. archive_deleted?: boolean;
  2104. library_file_name?: string | null;
  2105. library_file_thumbnail?: string | null;
  2106. printer_name?: string | null;
  2107. print_time_seconds?: number | null; // Estimated print time from archive or library file
  2108. filament_used_grams?: number | null; // Estimated print weight from archive or library file
  2109. filament_type?: string | null; // e.g. "PLA", "PETG"
  2110. filament_color?: string | null; // Hex RGBA from the slicer
  2111. bed_type?: string | null; // Build plate type for this print (per-plate accurate, #1281)
  2112. // User tracking (Issue #206)
  2113. created_by_id?: number | null;
  2114. created_by_username?: string | null;
  2115. // Batch grouping
  2116. batch_id?: number | null;
  2117. batch_name?: string | null;
  2118. // Shortest-job-first scheduling
  2119. been_jumped?: boolean;
  2120. // Auto-print G-code injection
  2121. gcode_injection?: boolean;
  2122. cleanup_library_after_dispatch?: boolean;
  2123. }
  2124. export interface PrintBatch {
  2125. id: number;
  2126. name: string;
  2127. archive_id: number | null;
  2128. library_file_id: number | null;
  2129. quantity: number;
  2130. status: string;
  2131. created_at: string;
  2132. created_by_id: number | null;
  2133. created_by_username: string | null;
  2134. pending_count: number;
  2135. printing_count: number;
  2136. completed_count: number;
  2137. failed_count: number;
  2138. cancelled_count: number;
  2139. }
  2140. export interface PrintQueueItemCreate {
  2141. printer_id?: number | null; // null = unassigned
  2142. target_model?: string | null; // Target printer model (mutually exclusive with printer_id)
  2143. target_location?: string | null; // Target location filter (only used with target_model)
  2144. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; force_color_match?: boolean }> | null;
  2145. archive_id?: number | null;
  2146. library_file_id?: number | null;
  2147. scheduled_time?: string | null;
  2148. require_previous_success?: boolean;
  2149. auto_off_after?: boolean;
  2150. manual_start?: boolean; // Requires manual trigger to start (staged)
  2151. insert_at_top?: boolean; // Insert ahead of other pending items in the same queue scope
  2152. insert_position?: number | null; // 1-indexed insertion position for priority queueing
  2153. // PrintModal "Print Anyway" on the deficit warning — persisted so the
  2154. // scheduler doesn't immediately re-flag this item (#1698-followup).
  2155. skip_filament_check?: boolean;
  2156. ams_mapping?: number[] | null; // AMS slot mapping for multi-color prints
  2157. plate_id?: number | null; // Plate ID for multi-plate 3MF files
  2158. // Print options
  2159. bed_levelling?: CalibrationMode;
  2160. flow_cali?: CalibrationMode;
  2161. vibration_cali?: boolean;
  2162. layer_inspect?: boolean;
  2163. timelapse?: boolean;
  2164. use_ams?: boolean;
  2165. nozzle_offset_cali?: CalibrationMode;
  2166. preheat_override?: 'inherit' | 'on' | 'off';
  2167. preheat_chamber_target_override?: number | null;
  2168. // Auto-print G-code injection
  2169. gcode_injection?: boolean;
  2170. // Batch: create multiple copies (creates a batch if > 1)
  2171. quantity?: number;
  2172. // Existing batch to add this item into (multi-plate auto-batch flow).
  2173. batch_id?: number | null;
  2174. // Project to associate the resulting archive with
  2175. project_id?: number;
  2176. // Delete transient uploaded library file after scheduler creates the archive
  2177. cleanup_library_after_dispatch?: boolean;
  2178. }
  2179. export interface PrintBatchCreate {
  2180. name: string;
  2181. archive_id?: number | null;
  2182. library_file_id?: number | null;
  2183. /** When set, the listed pending items are assigned to the new batch
  2184. * (manual "Group as batch"). When omitted/empty, an empty batch is
  2185. * returned so the client can pass batch_id on subsequent addToQueue calls. */
  2186. item_ids?: number[];
  2187. }
  2188. export interface PrintQueueItemUpdate {
  2189. printer_id?: number | null; // null = unassign
  2190. target_model?: string | null; // Target printer model (mutually exclusive with printer_id)
  2191. target_location?: string | null; // Target location filter (only used with target_model)
  2192. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; force_color_match?: boolean }> | null;
  2193. position?: number;
  2194. scheduled_time?: string | null;
  2195. require_previous_success?: boolean;
  2196. auto_off_after?: boolean;
  2197. manual_start?: boolean;
  2198. ams_mapping?: number[];
  2199. plate_id?: number | null; // Plate ID for multi-plate 3MF files
  2200. // Print options
  2201. bed_levelling?: CalibrationMode;
  2202. flow_cali?: CalibrationMode;
  2203. vibration_cali?: boolean;
  2204. layer_inspect?: boolean;
  2205. timelapse?: boolean;
  2206. use_ams?: boolean;
  2207. nozzle_offset_cali?: CalibrationMode;
  2208. preheat_override?: 'inherit' | 'on' | 'off';
  2209. preheat_chamber_target_override?: number | null;
  2210. // Auto-print G-code injection
  2211. gcode_injection?: boolean;
  2212. }
  2213. export interface PrintQueueBulkUpdate {
  2214. item_ids: number[];
  2215. printer_id?: number | null;
  2216. scheduled_time?: string | null;
  2217. require_previous_success?: boolean;
  2218. auto_off_after?: boolean;
  2219. manual_start?: boolean;
  2220. // Print options
  2221. bed_levelling?: CalibrationMode;
  2222. flow_cali?: CalibrationMode;
  2223. vibration_cali?: boolean;
  2224. layer_inspect?: boolean;
  2225. timelapse?: boolean;
  2226. use_ams?: boolean;
  2227. nozzle_offset_cali?: CalibrationMode;
  2228. preheat_override?: 'inherit' | 'on' | 'off';
  2229. preheat_chamber_target_override?: number | null;
  2230. // Auto-print G-code injection
  2231. gcode_injection?: boolean;
  2232. }
  2233. export interface PrintQueueBulkUpdateResponse {
  2234. updated_count: number;
  2235. skipped_count: number;
  2236. message: string;
  2237. }
  2238. // MQTT Logging types
  2239. export interface MQTTLogEntry {
  2240. timestamp: string;
  2241. topic: string;
  2242. direction: 'in' | 'out';
  2243. payload: Record<string, unknown>;
  2244. }
  2245. export interface MQTTLogsResponse {
  2246. logging_enabled: boolean;
  2247. logs: MQTTLogEntry[];
  2248. }
  2249. // K-Profile types
  2250. export interface KProfile {
  2251. slot_id: number;
  2252. extruder_id: number;
  2253. nozzle_id: string;
  2254. nozzle_diameter: string;
  2255. filament_id: string;
  2256. name: string;
  2257. k_value: string;
  2258. n_coef: string;
  2259. ams_id: number;
  2260. tray_id: number;
  2261. setting_id: string | null;
  2262. }
  2263. export interface KProfileCreate {
  2264. slot_id?: number; // Storage slot, 0 for new profiles
  2265. extruder_id?: number;
  2266. nozzle_id: string;
  2267. nozzle_diameter: string;
  2268. filament_id: string;
  2269. name: string;
  2270. k_value: string;
  2271. n_coef?: string;
  2272. ams_id?: number;
  2273. tray_id?: number;
  2274. setting_id?: string | null;
  2275. }
  2276. export interface KProfileDelete {
  2277. slot_id: number; // cali_idx - calibration index to delete
  2278. extruder_id: number;
  2279. nozzle_id: string; // e.g., "HH00-0.4"
  2280. nozzle_diameter: string; // e.g., "0.4"
  2281. filament_id: string; // Bambu filament identifier
  2282. setting_id?: string | null; // Setting ID (for X1C series)
  2283. }
  2284. export interface KProfilesResponse {
  2285. profiles: KProfile[];
  2286. nozzle_diameter: string;
  2287. }
  2288. export interface KProfileNote {
  2289. setting_id: string;
  2290. note: string;
  2291. }
  2292. export interface KProfileNotesResponse {
  2293. notes: Record<string, string>; // setting_id -> note
  2294. }
  2295. // Slot Preset Mapping
  2296. export interface SlotPresetMapping {
  2297. ams_id: number;
  2298. tray_id: number;
  2299. preset_id: string;
  2300. preset_name: string;
  2301. }
  2302. // Filament types
  2303. export interface Filament {
  2304. id: number;
  2305. name: string;
  2306. type: string; // PLA, PETG, ABS, etc.
  2307. brand: string | null;
  2308. color: string | null;
  2309. color_hex: string | null;
  2310. cost_per_kg: number;
  2311. spool_weight_g: number;
  2312. currency: string;
  2313. density: number | null;
  2314. print_temp_min: number | null;
  2315. print_temp_max: number | null;
  2316. bed_temp_min: number | null;
  2317. bed_temp_max: number | null;
  2318. created_at: string;
  2319. updated_at: string;
  2320. }
  2321. // Notification Provider types
  2322. export type ProviderType = 'callmebot' | 'ntfy' | 'pushover' | 'telegram' | 'email' | 'discord' | 'webhook' | 'homeassistant' | 'bark';
  2323. export interface NotificationProvider {
  2324. id: number;
  2325. name: string;
  2326. provider_type: ProviderType;
  2327. enabled: boolean;
  2328. config: Record<string, unknown>;
  2329. // Print lifecycle events
  2330. on_print_start: boolean;
  2331. on_print_complete: boolean;
  2332. on_print_failed: boolean;
  2333. on_print_stopped: boolean;
  2334. on_print_progress: boolean;
  2335. on_print_missing_spool_assignment: boolean;
  2336. // Printer status events
  2337. on_printer_offline: boolean;
  2338. on_printer_error: boolean;
  2339. on_ai_failure_detection: boolean;
  2340. on_filament_low: boolean;
  2341. on_maintenance_due: boolean;
  2342. // AMS environmental alarms (regular AMS)
  2343. on_ams_humidity_high: boolean;
  2344. on_ams_temperature_high: boolean;
  2345. // AMS-HT environmental alarms
  2346. on_ams_ht_humidity_high: boolean;
  2347. on_ams_ht_temperature_high: boolean;
  2348. // Build plate detection
  2349. on_plate_not_empty: boolean;
  2350. on_plate_clear_required: boolean;
  2351. // Bed cooled
  2352. on_bed_cooled: boolean;
  2353. // First layer complete
  2354. on_first_layer_complete: boolean;
  2355. // Inventory stock alerts
  2356. on_stock_reorder_alert: boolean;
  2357. on_stock_break_alert: boolean;
  2358. // Print queue events
  2359. on_queue_job_added: boolean;
  2360. on_queue_job_assigned: boolean;
  2361. on_queue_job_started: boolean;
  2362. on_queue_job_waiting: boolean;
  2363. on_queue_job_skipped: boolean;
  2364. on_queue_job_failed: boolean;
  2365. on_queue_completed: boolean;
  2366. // Quiet hours
  2367. quiet_hours_enabled: boolean;
  2368. quiet_hours_start: string | null;
  2369. quiet_hours_end: string | null;
  2370. // Daily digest
  2371. daily_digest_enabled: boolean;
  2372. daily_digest_time: string | null;
  2373. // Printer filter
  2374. printer_id: number | null;
  2375. // Status tracking
  2376. last_success: string | null;
  2377. last_error: string | null;
  2378. last_error_at: string | null;
  2379. // Timestamps
  2380. created_at: string;
  2381. updated_at: string;
  2382. }
  2383. export interface NotificationProviderCreate {
  2384. name: string;
  2385. provider_type: ProviderType;
  2386. enabled?: boolean;
  2387. config: Record<string, unknown>;
  2388. // Print lifecycle events
  2389. on_print_start?: boolean;
  2390. on_print_complete?: boolean;
  2391. on_print_failed?: boolean;
  2392. on_print_stopped?: boolean;
  2393. on_print_progress?: boolean;
  2394. on_print_missing_spool_assignment?: boolean;
  2395. // Printer status events
  2396. on_printer_offline?: boolean;
  2397. on_printer_error?: boolean;
  2398. on_ai_failure_detection?: boolean;
  2399. on_filament_low?: boolean;
  2400. on_maintenance_due?: boolean;
  2401. // AMS environmental alarms (regular AMS)
  2402. on_ams_humidity_high?: boolean;
  2403. on_ams_temperature_high?: boolean;
  2404. // AMS-HT environmental alarms
  2405. on_ams_ht_humidity_high?: boolean;
  2406. on_ams_ht_temperature_high?: boolean;
  2407. // Build plate detection
  2408. on_plate_not_empty?: boolean;
  2409. on_plate_clear_required?: boolean;
  2410. // Bed cooled
  2411. on_bed_cooled?: boolean;
  2412. // First layer complete
  2413. on_first_layer_complete?: boolean;
  2414. // Inventory stock alerts
  2415. on_stock_reorder_alert?: boolean;
  2416. on_stock_break_alert?: boolean;
  2417. // Print queue events
  2418. on_queue_job_added?: boolean;
  2419. on_queue_job_assigned?: boolean;
  2420. on_queue_job_started?: boolean;
  2421. on_queue_job_waiting?: boolean;
  2422. on_queue_job_skipped?: boolean;
  2423. on_queue_job_failed?: boolean;
  2424. on_queue_completed?: boolean;
  2425. // Quiet hours
  2426. quiet_hours_enabled?: boolean;
  2427. quiet_hours_start?: string | null;
  2428. quiet_hours_end?: string | null;
  2429. // Daily digest
  2430. daily_digest_enabled?: boolean;
  2431. daily_digest_time?: string | null;
  2432. // Printer filter
  2433. printer_id?: number | null;
  2434. }
  2435. export interface NotificationProviderUpdate {
  2436. name?: string;
  2437. provider_type?: ProviderType;
  2438. enabled?: boolean;
  2439. config?: Record<string, unknown>;
  2440. // Print lifecycle events
  2441. on_print_start?: boolean;
  2442. on_print_complete?: boolean;
  2443. on_print_failed?: boolean;
  2444. on_print_stopped?: boolean;
  2445. on_print_progress?: boolean;
  2446. on_print_missing_spool_assignment?: boolean;
  2447. // Printer status events
  2448. on_printer_offline?: boolean;
  2449. on_printer_error?: boolean;
  2450. on_ai_failure_detection?: boolean;
  2451. on_filament_low?: boolean;
  2452. on_maintenance_due?: boolean;
  2453. // AMS environmental alarms (regular AMS)
  2454. on_ams_humidity_high?: boolean;
  2455. on_ams_temperature_high?: boolean;
  2456. // AMS-HT environmental alarms
  2457. on_ams_ht_humidity_high?: boolean;
  2458. on_ams_ht_temperature_high?: boolean;
  2459. // Build plate detection
  2460. on_plate_not_empty?: boolean;
  2461. on_plate_clear_required?: boolean;
  2462. // Bed cooled
  2463. on_bed_cooled?: boolean;
  2464. // First layer complete
  2465. on_first_layer_complete?: boolean;
  2466. // Inventory stock alerts
  2467. on_stock_reorder_alert?: boolean;
  2468. on_stock_break_alert?: boolean;
  2469. // Print queue events
  2470. on_queue_job_added?: boolean;
  2471. on_queue_job_assigned?: boolean;
  2472. on_queue_job_started?: boolean;
  2473. on_queue_job_waiting?: boolean;
  2474. on_queue_job_skipped?: boolean;
  2475. on_queue_job_failed?: boolean;
  2476. on_queue_completed?: boolean;
  2477. // Quiet hours
  2478. quiet_hours_enabled?: boolean;
  2479. quiet_hours_start?: string | null;
  2480. quiet_hours_end?: string | null;
  2481. // Daily digest
  2482. daily_digest_enabled?: boolean;
  2483. daily_digest_time?: string | null;
  2484. // Printer filter
  2485. printer_id?: number | null;
  2486. }
  2487. // GitHub Backup types
  2488. export type ScheduleType = 'hourly' | 'daily' | 'weekly';
  2489. export type GitProviderType = 'github' | 'gitea' | 'forgejo' | 'gitlab';
  2490. /** How many cloud accounts a backup would collect presets from. Counts only —
  2491. * with auth enabled the accounts belong to individual users, so the backup
  2492. * administrator sees how many, never whose. */
  2493. export interface CloudAccountCounts {
  2494. bambu: number;
  2495. orca: number;
  2496. }
  2497. export interface GitHubBackupConfig {
  2498. id: number;
  2499. repository_url: string;
  2500. has_token: boolean;
  2501. branch: string;
  2502. provider: GitProviderType;
  2503. allow_insecure_http: boolean;
  2504. schedule_enabled: boolean;
  2505. schedule_type: ScheduleType;
  2506. backup_kprofiles: boolean;
  2507. backup_cloud_profiles: boolean;
  2508. backup_settings: boolean;
  2509. backup_spools: boolean;
  2510. backup_archives: boolean;
  2511. enabled: boolean;
  2512. last_backup_at: string | null;
  2513. last_backup_status: string | null;
  2514. last_backup_message: string | null;
  2515. last_backup_commit_sha: string | null;
  2516. next_scheduled_run: string | null;
  2517. created_at: string;
  2518. updated_at: string;
  2519. }
  2520. export interface GitHubBackupConfigCreate {
  2521. repository_url: string;
  2522. access_token: string;
  2523. branch?: string;
  2524. provider?: GitProviderType;
  2525. allow_insecure_http?: boolean;
  2526. schedule_enabled?: boolean;
  2527. schedule_type?: ScheduleType;
  2528. backup_kprofiles?: boolean;
  2529. backup_cloud_profiles?: boolean;
  2530. backup_settings?: boolean;
  2531. backup_spools?: boolean;
  2532. backup_archives?: boolean;
  2533. enabled?: boolean;
  2534. }
  2535. export interface GitHubBackupLog {
  2536. id: number;
  2537. config_id: number;
  2538. started_at: string;
  2539. completed_at: string | null;
  2540. status: string;
  2541. trigger: string;
  2542. commit_sha: string | null;
  2543. files_changed: number;
  2544. error_message: string | null;
  2545. }
  2546. export interface GitHubBackupStatus {
  2547. configured: boolean;
  2548. enabled: boolean;
  2549. is_running: boolean;
  2550. progress: string | null;
  2551. last_backup_at: string | null;
  2552. last_backup_status: string | null;
  2553. next_scheduled_run: string | null;
  2554. }
  2555. export interface LocalBackupStatus {
  2556. enabled: boolean;
  2557. schedule: string;
  2558. time: string;
  2559. retention: number;
  2560. path: string;
  2561. default_path: string;
  2562. is_running: boolean;
  2563. last_backup_at: string | null;
  2564. last_status: string | null;
  2565. last_message: string | null;
  2566. next_run: string | null;
  2567. timezone: string;
  2568. }
  2569. export interface LocalBackupFile {
  2570. filename: string;
  2571. size: number;
  2572. created_at: string;
  2573. }
  2574. /** Result of writing a probe file into the configured backup directory (#2544). */
  2575. export interface LocalBackupPathCheck {
  2576. writable: boolean;
  2577. path: string;
  2578. /** 'ok' | 'sandboxed' | 'read_only' | 'permission_denied' | 'no_space' | 'not_a_directory' | 'missing' | 'error' */
  2579. code: string;
  2580. /** Raw OS error, shown as-is under the translated explanation. */
  2581. detail: string | null;
  2582. /** Copy-pasteable fix (systemd drop-in, compose snippet) — not translated. */
  2583. remedy: string | null;
  2584. message: string;
  2585. /** 'container_ephemeral' — writable, but the backups die with the container. */
  2586. warning: string | null;
  2587. }
  2588. export interface ObicoDetectionEvent {
  2589. printer_id: number;
  2590. task_name: string;
  2591. timestamp: string;
  2592. current_p: number;
  2593. score: number;
  2594. class: 'safe' | 'warning' | 'failure';
  2595. detections: number;
  2596. }
  2597. export interface ObicoStatus {
  2598. is_running: boolean;
  2599. last_error: string | null;
  2600. per_printer: Record<string, { class: string; frame_count: number; score: number }>;
  2601. thresholds: { low: number; high: number };
  2602. history: ObicoDetectionEvent[];
  2603. enabled: boolean;
  2604. ml_url: string;
  2605. sensitivity: 'low' | 'medium' | 'high';
  2606. action: 'notify' | 'pause' | 'pause_and_off';
  2607. poll_interval: number;
  2608. external_url_configured: boolean;
  2609. }
  2610. // Lightweight subset served under printers:read for the printer-card badge (#1546)
  2611. export interface ObicoPrinterStatus {
  2612. enabled: boolean;
  2613. // null = all printers are monitored
  2614. monitored_printers: number[] | null;
  2615. per_printer: Record<string, { class: string; frame_count: number; score: number }>;
  2616. // null = no error, or the viewer lacks settings:read (error strings can embed config URLs)
  2617. last_error: string | null;
  2618. }
  2619. export interface ObicoTestConnection {
  2620. ok: boolean;
  2621. status_code: number | null;
  2622. body: string | null;
  2623. error: string | null;
  2624. // Whether the ML API accepted the token. null = not determined (the health
  2625. // check failed first, or the token probe itself errored).
  2626. auth_ok: boolean | null;
  2627. }
  2628. export interface GitHubTestConnectionResponse {
  2629. success: boolean;
  2630. message: string;
  2631. repo_name: string | null;
  2632. permissions: Record<string, boolean> | null;
  2633. // true = confirmed private, false = confirmed public/internal,
  2634. // null = could not determine. Backend rejects save unless true.
  2635. is_private: boolean | null;
  2636. }
  2637. export interface GitHubBackupTriggerResponse {
  2638. success: boolean;
  2639. message: string;
  2640. log_id: number | null;
  2641. commit_sha: string | null;
  2642. files_changed: number;
  2643. }
  2644. export interface NotificationTestRequest {
  2645. provider_type: ProviderType;
  2646. config: Record<string, unknown>;
  2647. }
  2648. export interface NotificationTestResponse {
  2649. success: boolean;
  2650. message: string;
  2651. }
  2652. // Provider-specific config types for reference
  2653. export interface CallMeBotConfig {
  2654. phone: string;
  2655. apikey: string;
  2656. }
  2657. export interface NtfyConfig {
  2658. server?: string;
  2659. topic: string;
  2660. auth_token?: string | null;
  2661. }
  2662. export interface PushoverConfig {
  2663. user_key: string;
  2664. app_token: string;
  2665. priority?: number;
  2666. }
  2667. export interface TelegramConfig {
  2668. bot_token: string;
  2669. chat_id: string;
  2670. }
  2671. export interface EmailConfig {
  2672. smtp_server: string;
  2673. smtp_port?: number;
  2674. username: string;
  2675. password: string;
  2676. from_email: string;
  2677. to_email: string;
  2678. use_tls?: boolean;
  2679. }
  2680. // Notification Template types
  2681. export interface NotificationTemplate {
  2682. id: number;
  2683. event_type: string;
  2684. name: string;
  2685. title_template: string;
  2686. body_template: string;
  2687. is_default: boolean;
  2688. created_at: string;
  2689. updated_at: string;
  2690. }
  2691. export interface NotificationTemplateUpdate {
  2692. title_template?: string;
  2693. body_template?: string;
  2694. }
  2695. export interface EventVariablesResponse {
  2696. event_type: string;
  2697. event_name: string;
  2698. variables: string[];
  2699. }
  2700. export interface TemplatePreviewRequest {
  2701. event_type: string;
  2702. title_template: string;
  2703. body_template: string;
  2704. }
  2705. export interface TemplatePreviewResponse {
  2706. title: string;
  2707. body: string;
  2708. }
  2709. // Notification Log types
  2710. export interface NotificationLogEntry {
  2711. id: number;
  2712. provider_id: number;
  2713. provider_name: string | null;
  2714. provider_type: string | null;
  2715. event_type: string;
  2716. title: string;
  2717. message: string;
  2718. success: boolean;
  2719. error_message: string | null;
  2720. printer_id: number | null;
  2721. printer_name: string | null;
  2722. created_at: string;
  2723. }
  2724. export interface NotificationLogStats {
  2725. total: number;
  2726. success_count: number;
  2727. failure_count: number;
  2728. by_event_type: Record<string, number>;
  2729. by_provider: Record<string, number>;
  2730. }
  2731. // Spoolman types
  2732. export interface SpoolmanStatus {
  2733. enabled: boolean;
  2734. connected: boolean;
  2735. url: string | null;
  2736. }
  2737. export interface SkippedSpool {
  2738. location: string;
  2739. reason: string;
  2740. filament_type: string | null;
  2741. color: string | null;
  2742. }
  2743. export interface SpoolmanSyncResult {
  2744. success: boolean;
  2745. synced_count: number;
  2746. skipped_count: number;
  2747. skipped: SkippedSpool[];
  2748. errors: string[];
  2749. }
  2750. export interface UnlinkedSpool {
  2751. id: number;
  2752. filament_name: string | null;
  2753. filament_vendor: string | null;
  2754. filament_material: string | null;
  2755. filament_color_hex: string | null;
  2756. remaining_weight: number | null;
  2757. location: string | null;
  2758. }
  2759. export interface LinkedSpoolInfo {
  2760. id: number;
  2761. remaining_weight: number | null;
  2762. filament_weight: number | null;
  2763. }
  2764. export interface LinkedSpoolsMap {
  2765. linked: Record<string, LinkedSpoolInfo>; // tag (uppercase) -> spool info
  2766. }
  2767. export interface SpoolmanVendor {
  2768. id: number;
  2769. name: string;
  2770. }
  2771. export interface SpoolmanFilamentEntry {
  2772. id: number;
  2773. name: string;
  2774. material: string | null;
  2775. color_hex: string | null;
  2776. color_name: string | null;
  2777. weight: number | null;
  2778. spool_weight: number | null;
  2779. vendor: SpoolmanVendor | null;
  2780. }
  2781. // Inventory types
  2782. // Label printing (#809). Mirror of backend.app.services.label_renderer.TemplateName.
  2783. export type SpoolLabelTemplate =
  2784. | 'ams_holder_74x33'
  2785. | 'ams_holder_75x55'
  2786. | 'box_40x30'
  2787. | 'box_62x29'
  2788. | 'avery_5160'
  2789. | 'avery_l7160';
  2790. export interface InventorySpool {
  2791. id: number;
  2792. material: string;
  2793. subtype: string | null;
  2794. color_name: string | null;
  2795. // True when color_name was synthesised from subtype because Spoolman has no
  2796. // stored value (Spoolman-backed inventory only). The edit form uses this to
  2797. // leave the input blank, so the user doesn't round-trip the synth value
  2798. // back to Spoolman as if it were a real user-set color_name (#1319).
  2799. color_name_is_synthesized?: boolean;
  2800. rgba: string | null;
  2801. // Multi-colour gradient stops (#1154): comma-separated 6/8-char hex.
  2802. extra_colors: string | null;
  2803. // Visual effect overlay: sparkle | wood | marble | glow | matte.
  2804. effect_type: string | null;
  2805. brand: string | null;
  2806. label_weight: number;
  2807. core_weight: number;
  2808. core_weight_catalog_id: number | null;
  2809. weight_used: number;
  2810. // Anchor for the resettable "Total Consumed" display (#1390). The
  2811. // counter shown on the Inventory page is `weight_used - weight_used_baseline`;
  2812. // remaining is still `label_weight - weight_used`, so "Reset usage to 0"
  2813. // zeroes the counter without disturbing remaining. Optional for back-compat
  2814. // with rows from a pre-migration DB snapshot — default to 0.
  2815. weight_used_baseline?: number;
  2816. slicer_filament: string | null;
  2817. slicer_filament_name: string | null;
  2818. nozzle_temp_min: number | null;
  2819. nozzle_temp_max: number | null;
  2820. note: string | null;
  2821. added_full: boolean | null;
  2822. last_used: string | null;
  2823. encode_time: string | null;
  2824. tag_uid: string | null;
  2825. tray_uuid: string | null;
  2826. data_origin: string | null;
  2827. tag_type: string | null;
  2828. archived_at: string | null;
  2829. created_at: string;
  2830. updated_at: string;
  2831. cost_per_kg: number | null;
  2832. last_scale_weight: number | null;
  2833. last_weighed_at: string | null;
  2834. // User-defined category + per-spool low-stock threshold override (#729).
  2835. category: string | null;
  2836. low_stock_threshold_pct: number | null;
  2837. k_profiles?: SpoolKProfile[];
  2838. storage_location?: string | null;
  2839. location_id?: number | null;
  2840. }
  2841. export interface SpoolmanBulkCreateResult {
  2842. created: InventorySpool[];
  2843. requested_count: number;
  2844. failed_count: number;
  2845. }
  2846. // ── CSV import/export (#1576) ──────────────────────────────────────────────
  2847. /** One row's outcome from the import preview / real import. */
  2848. export interface CsvImportRow {
  2849. row_number: number;
  2850. status: 'valid' | 'error' | 'skipped';
  2851. reason: string | null;
  2852. material: string | null;
  2853. brand: string | null;
  2854. color_name: string | null;
  2855. rgba: string | null;
  2856. /** rgba/extra_colors/effect_type were filled from the Color Catalog. */
  2857. resolved_color: boolean;
  2858. /** The catalog match came from a different material's variant (no exact
  2859. * material match). Shown as a warning in the preview. */
  2860. cross_material_color: boolean;
  2861. /** An active spool with the same material+brand+color already exists.
  2862. * Informational only — the import still creates the row. */
  2863. duplicate_of_existing: boolean;
  2864. }
  2865. /** Dry-run preview: per-row classification, no rows written. */
  2866. export interface CsvImportPreview {
  2867. columns: string[];
  2868. total: number;
  2869. valid_count: number;
  2870. error_count: number;
  2871. skipped_count: number;
  2872. rows: CsvImportRow[];
  2873. warnings: string[];
  2874. }
  2875. /** Summary returned after a real (non-dry-run) import. */
  2876. export interface CsvImportResult {
  2877. created: number;
  2878. skipped: number;
  2879. errors: number;
  2880. error_rows: CsvImportRow[];
  2881. }
  2882. export interface SpoolUsageRecord {
  2883. id: number;
  2884. spool_id: number;
  2885. printer_id: number | null;
  2886. print_name: string | null;
  2887. weight_used: number;
  2888. percent_used: number;
  2889. status: string;
  2890. cost: number | null;
  2891. created_at: string;
  2892. }
  2893. export interface SpoolKProfile {
  2894. id: number;
  2895. spool_id: number;
  2896. printer_id: number;
  2897. extruder: number;
  2898. nozzle_diameter: string;
  2899. nozzle_type: string | null;
  2900. k_value: number;
  2901. name: string | null;
  2902. cali_idx: number | null;
  2903. setting_id: string | null;
  2904. created_at: string;
  2905. }
  2906. export interface SpoolKProfileInput {
  2907. printer_id: number;
  2908. extruder?: number;
  2909. nozzle_diameter?: string;
  2910. nozzle_type?: string | null;
  2911. k_value: number;
  2912. name?: string | null;
  2913. cali_idx?: number | null;
  2914. setting_id?: string | null;
  2915. }
  2916. export interface SpoolAssignment {
  2917. id: number;
  2918. spool_id: number;
  2919. printer_id: number;
  2920. printer_name: string | null;
  2921. ams_id: number;
  2922. tray_id: number;
  2923. fingerprint_color: string | null;
  2924. fingerprint_type: string | null;
  2925. spool?: InventorySpool | null;
  2926. configured: boolean;
  2927. pending_config?: boolean; // Slot was empty at assign time; will configure on insert
  2928. created_at: string;
  2929. ams_label?: string | null; // User-defined friendly name for the AMS unit
  2930. }
  2931. export interface FilamentSkuSettings {
  2932. id: number;
  2933. material: string;
  2934. subtype: string | null;
  2935. brand: string | null;
  2936. color_name: string | null;
  2937. lead_time_days: number;
  2938. safety_margin_value: number;
  2939. safety_margin_unit: 'days' | 'g';
  2940. alerts_snoozed: boolean;
  2941. }
  2942. export interface ShoppingListItem {
  2943. id: number;
  2944. material: string;
  2945. subtype: string | null;
  2946. brand: string | null;
  2947. color_name: string | null;
  2948. quantity_spools: number;
  2949. note: string | null;
  2950. status: 'pending' | 'purchased' | 'received';
  2951. purchased_at: string | null;
  2952. added_at: string;
  2953. }
  2954. export interface ShoppingListItemCreate {
  2955. material: string;
  2956. subtype: string | null;
  2957. brand: string | null;
  2958. color_name: string | null;
  2959. quantity_spools: number;
  2960. note?: string | null;
  2961. }
  2962. // Update types
  2963. export interface VersionInfo {
  2964. version: string;
  2965. repo: string;
  2966. }
  2967. export interface UpdateCheckResult {
  2968. update_available: boolean;
  2969. current_version: string;
  2970. latest_version: string | null;
  2971. release_name?: string;
  2972. release_notes?: string;
  2973. release_url?: string;
  2974. published_at?: string;
  2975. error?: string;
  2976. message?: string;
  2977. is_docker?: boolean;
  2978. is_ha_addon?: boolean;
  2979. is_windows_installer?: boolean;
  2980. update_method?: 'docker' | 'git' | 'ha_addon' | 'windows_installer';
  2981. installer_download_url?: string | null;
  2982. }
  2983. export interface UpdateStatus {
  2984. status: 'idle' | 'checking' | 'downloading' | 'installing' | 'complete' | 'error';
  2985. progress: number;
  2986. message: string;
  2987. error: string | null;
  2988. }
  2989. // Maintenance types
  2990. export interface MaintenanceType {
  2991. id: number;
  2992. name: string;
  2993. description: string | null;
  2994. default_interval_hours: number;
  2995. interval_type: 'hours' | 'days'; // "hours" = print hours, "days" = calendar days
  2996. icon: string | null;
  2997. wiki_url: string | null; // Documentation link
  2998. is_system: boolean;
  2999. created_at: string;
  3000. }
  3001. export interface MaintenanceTypeCreate {
  3002. name: string;
  3003. description?: string | null;
  3004. default_interval_hours?: number;
  3005. interval_type?: 'hours' | 'days';
  3006. icon?: string | null;
  3007. wiki_url?: string | null;
  3008. }
  3009. export interface MaintenanceStatus {
  3010. id: number;
  3011. printer_id: number;
  3012. printer_name: string;
  3013. printer_model: string | null;
  3014. maintenance_type_id: number;
  3015. maintenance_type_name: string;
  3016. maintenance_type_icon: string | null;
  3017. maintenance_type_wiki_url: string | null; // Custom wiki URL from type
  3018. enabled: boolean;
  3019. interval_hours: number; // For hours type: print hours; for days type: number of days
  3020. interval_type: 'hours' | 'days';
  3021. current_hours: number;
  3022. hours_since_maintenance: number;
  3023. hours_until_due: number;
  3024. days_since_maintenance: number | null; // For days type
  3025. days_until_due: number | null; // For days type
  3026. is_due: boolean;
  3027. is_warning: boolean;
  3028. last_performed_at: string | null;
  3029. }
  3030. export interface PrinterMaintenanceOverview {
  3031. printer_id: number;
  3032. printer_name: string;
  3033. printer_model: string | null;
  3034. total_print_hours: number;
  3035. maintenance_items: MaintenanceStatus[];
  3036. due_count: number;
  3037. warning_count: number;
  3038. }
  3039. export interface MaintenanceHistory {
  3040. id: number;
  3041. printer_maintenance_id: number;
  3042. performed_at: string;
  3043. hours_at_maintenance: number;
  3044. notes: string | null;
  3045. }
  3046. export interface MaintenanceSummary {
  3047. total_due: number;
  3048. total_warning: number;
  3049. printers_with_issues: Array<{
  3050. printer_id: number;
  3051. printer_name: string;
  3052. due_count: number;
  3053. warning_count: number;
  3054. }>;
  3055. }
  3056. // External Links (sidebar)
  3057. export interface ExternalLink {
  3058. id: number;
  3059. name: string;
  3060. url: string;
  3061. icon: string;
  3062. open_in_new_tab: boolean;
  3063. custom_icon: string | null;
  3064. sort_order: number;
  3065. created_at: string;
  3066. updated_at: string;
  3067. }
  3068. export interface ExternalLinkCreate {
  3069. name: string;
  3070. url: string;
  3071. icon: string;
  3072. open_in_new_tab?: boolean;
  3073. }
  3074. export interface ExternalLinkUpdate {
  3075. name?: string;
  3076. url?: string;
  3077. icon?: string;
  3078. open_in_new_tab?: boolean;
  3079. }
  3080. // Permission type - all available permissions
  3081. export type Permission =
  3082. | 'printers:read' | 'printers:create' | 'printers:update' | 'printers:delete' | 'printers:control' | 'printers:files' | 'printers:ams_rfid' | 'printers:clear_plate'
  3083. | 'archives:read' | 'archives:read_own' | 'archives:read_all' | 'archives:create'
  3084. | 'archives:update_own' | 'archives:update_all' | 'archives:delete_own' | 'archives:delete_all'
  3085. | 'archives:reprint_own' | 'archives:reprint_all' | 'archives:purge'
  3086. | 'queue:read' | 'queue:read_own' | 'queue:read_all' | 'queue:create'
  3087. | 'queue:update_own' | 'queue:update_all' | 'queue:delete_own' | 'queue:delete_all'
  3088. | 'queue:reorder'
  3089. | 'library:read' | 'library:read_own' | 'library:read_all' | 'library:upload'
  3090. | 'library:update_own' | 'library:update_all' | 'library:delete_own' | 'library:delete_all'
  3091. | 'library:purge'
  3092. | 'projects:read' | 'projects:create' | 'projects:update' | 'projects:delete'
  3093. | 'filaments:read' | 'filaments:create' | 'filaments:update' | 'filaments:delete'
  3094. | 'inventory:read' | 'inventory:create' | 'inventory:update' | 'inventory:delete' | 'inventory:view_assignments'
  3095. | 'inventory:forecast_read' | 'inventory:forecast_write'
  3096. | 'smart_plugs:read' | 'smart_plugs:create' | 'smart_plugs:update' | 'smart_plugs:delete' | 'smart_plugs:control'
  3097. | 'camera:view'
  3098. | 'maintenance:read' | 'maintenance:create' | 'maintenance:update' | 'maintenance:delete'
  3099. | 'kprofiles:read' | 'kprofiles:create' | 'kprofiles:update' | 'kprofiles:delete'
  3100. | 'notifications:read' | 'notifications:create' | 'notifications:update' | 'notifications:delete' | 'notifications:user_email'
  3101. | 'notification_templates:read' | 'notification_templates:update'
  3102. | 'external_links:read' | 'external_links:create' | 'external_links:update' | 'external_links:delete'
  3103. | 'discovery:scan'
  3104. | 'firmware:read' | 'firmware:update'
  3105. | 'ams_history:read'
  3106. | 'stats:read' | 'stats:filter_by_user'
  3107. | 'system:read'
  3108. | 'settings:read' | 'settings:update' | 'settings:backup' | 'settings:restore'
  3109. | 'github:backup' | 'github:restore'
  3110. | 'cloud:auth' | 'orca_cloud:auth'
  3111. | 'makerworld:view' | 'makerworld:import'
  3112. | 'api_keys:read' | 'api_keys:create' | 'api_keys:update' | 'api_keys:delete'
  3113. | 'users:read' | 'users:create' | 'users:update' | 'users:delete'
  3114. | 'groups:read' | 'groups:create' | 'groups:update' | 'groups:delete'
  3115. | 'pipelines:read' | 'pipelines:write' | 'pipelines:run'
  3116. | 'websocket:connect';
  3117. // Group types
  3118. export interface GroupBrief {
  3119. id: number;
  3120. name: string;
  3121. }
  3122. export interface Group {
  3123. id: number;
  3124. name: string;
  3125. description: string | null;
  3126. permissions: Permission[];
  3127. is_system: boolean;
  3128. user_count: number;
  3129. created_at: string;
  3130. updated_at: string;
  3131. }
  3132. export interface GroupDetail extends Group {
  3133. users: Array<{ id: number; username: string; is_active: boolean }>;
  3134. }
  3135. export interface GroupCreate {
  3136. name: string;
  3137. description?: string;
  3138. permissions: Permission[];
  3139. }
  3140. export interface GroupUpdate {
  3141. name?: string;
  3142. description?: string;
  3143. permissions?: Permission[];
  3144. }
  3145. export interface PermissionInfo {
  3146. value: Permission;
  3147. label: string;
  3148. }
  3149. export interface PermissionCategory {
  3150. name: string;
  3151. permissions: PermissionInfo[];
  3152. }
  3153. export interface PermissionsListResponse {
  3154. categories: PermissionCategory[];
  3155. all_permissions: Permission[];
  3156. }
  3157. // User email notification preferences
  3158. export interface UserEmailPreferences {
  3159. notify_print_start: boolean;
  3160. notify_print_complete: boolean;
  3161. notify_print_failed: boolean;
  3162. notify_print_stopped: boolean;
  3163. }
  3164. // Auth types
  3165. export interface LoginRequest {
  3166. username: string;
  3167. password: string;
  3168. }
  3169. export interface LoginResponse {
  3170. access_token?: string;
  3171. token_type?: string;
  3172. user?: UserResponse;
  3173. /** Set when 2FA verification is required before a full token is issued. */
  3174. requires_2fa?: boolean;
  3175. pre_auth_token?: string;
  3176. two_fa_methods?: string[];
  3177. }
  3178. export interface UserResponse {
  3179. id: number;
  3180. username: string;
  3181. email?: string;
  3182. role: string; // Deprecated, kept for backward compatibility
  3183. is_active: boolean;
  3184. is_admin: boolean; // Computed from role and group membership
  3185. auth_source: string; // "local" or "ldap"
  3186. groups: GroupBrief[];
  3187. permissions: Permission[]; // All permissions from groups
  3188. created_at: string;
  3189. }
  3190. export interface UserCreate {
  3191. username: string;
  3192. password?: string; // Optional when advanced auth is enabled
  3193. email?: string;
  3194. role: string;
  3195. group_ids?: number[];
  3196. }
  3197. export interface UserUpdate {
  3198. username?: string;
  3199. password?: string;
  3200. email?: string;
  3201. role?: string;
  3202. is_active?: boolean;
  3203. group_ids?: number[];
  3204. }
  3205. export interface SetupRequest {
  3206. auth_enabled: boolean;
  3207. admin_username?: string;
  3208. admin_password?: string;
  3209. }
  3210. export interface ForgotPasswordRequest {
  3211. email: string;
  3212. }
  3213. export interface ForgotPasswordResponse {
  3214. message: string;
  3215. }
  3216. export interface ResetPasswordRequest {
  3217. user_id: number;
  3218. }
  3219. export interface ResetPasswordResponse {
  3220. message: string;
  3221. }
  3222. export interface SMTPSettings {
  3223. smtp_host: string;
  3224. smtp_port: number;
  3225. smtp_username?: string;
  3226. smtp_password?: string;
  3227. smtp_security: 'starttls' | 'ssl' | 'none';
  3228. smtp_auth_enabled: boolean;
  3229. smtp_from_email: string;
  3230. smtp_from_name: string;
  3231. }
  3232. // 2FA / MFA interfaces
  3233. export interface TwoFAStatus {
  3234. totp_enabled: boolean;
  3235. email_otp_enabled: boolean;
  3236. backup_codes_remaining: number;
  3237. }
  3238. export interface TOTPSetupResponse {
  3239. secret: string;
  3240. qr_code_b64: string;
  3241. issuer: string;
  3242. }
  3243. export interface TOTPEnableResponse {
  3244. message: string;
  3245. backup_codes: string[];
  3246. }
  3247. export interface BackupCodesResponse {
  3248. backup_codes: string[];
  3249. message: string;
  3250. }
  3251. export interface TwoFAVerifyRequest {
  3252. pre_auth_token: string;
  3253. code: string;
  3254. method: 'totp' | 'email' | 'backup';
  3255. }
  3256. /**
  3257. * A URL that is known to be same-origin (a relative path starting with ``/``).
  3258. *
  3259. * Branded so that producers of same-origin URLs (e.g. ``api.oidcProviderIconUrl``)
  3260. * can be distinguished from arbitrary strings at the type level. The brand
  3261. * is compile-time only; at runtime these are plain strings.
  3262. *
  3263. * Purpose: CSP-safe image sources for ``<img src=...>``. The strict
  3264. * ``img-src 'self' data: blob:`` CSP rejects anything that isn't same-origin,
  3265. * so callers that demand a ``SameOriginUrl`` get a compile-time guarantee
  3266. * that no external URL slips through.
  3267. */
  3268. export type SameOriginUrl = string & { readonly __brand: 'SameOriginUrl' };
  3269. // OIDC interfaces
  3270. export interface OIDCProvider {
  3271. id: number;
  3272. name: string;
  3273. issuer_url: string;
  3274. client_id: string;
  3275. scopes: string;
  3276. is_enabled: boolean;
  3277. auto_create_users: boolean;
  3278. auto_link_existing_accounts: boolean;
  3279. email_claim: string;
  3280. require_email_verified: boolean;
  3281. icon_url?: string | null;
  3282. default_group_id?: number | null;
  3283. // True when the backend has cached icon bytes for this provider.
  3284. // Login page / admin preview consume this via the proxy URL
  3285. // /api/v1/auth/oidc/providers/{id}/icon (#1333) so the SPA never
  3286. // hotlinks the external icon URL — that would require loosening
  3287. // the strict img-src CSP. Required, not optional: the backend always
  3288. // includes this field in the response (Pydantic default-False is
  3289. // populated unconditionally in the route handler).
  3290. has_icon: boolean;
  3291. // #1589: when true, the LoginPage redirects unauthenticated visitors
  3292. // straight to this provider on mount. At most one provider may carry this.
  3293. is_autologin: boolean;
  3294. }
  3295. export interface OIDCProviderCreate {
  3296. name: string;
  3297. issuer_url: string;
  3298. client_id: string;
  3299. client_secret: string;
  3300. scopes?: string;
  3301. is_enabled?: boolean;
  3302. auto_create_users?: boolean;
  3303. auto_link_existing_accounts?: boolean;
  3304. email_claim?: string;
  3305. require_email_verified?: boolean;
  3306. icon_url?: string | null;
  3307. default_group_id?: number | null;
  3308. is_autologin?: boolean; // #1589
  3309. }
  3310. export interface OIDCLink {
  3311. id: number;
  3312. provider_id: number;
  3313. provider_name: string;
  3314. provider_email?: string | null;
  3315. created_at: string;
  3316. }
  3317. export interface TestSMTPRequest {
  3318. test_recipient: string;
  3319. }
  3320. export interface TestSMTPResponse {
  3321. success: boolean;
  3322. message: string;
  3323. }
  3324. export interface AdvancedAuthStatus {
  3325. advanced_auth_enabled: boolean;
  3326. smtp_configured: boolean;
  3327. // #1589: false hides the username/password form on the LoginPage; the env
  3328. // var BAMBUDDY_LOCAL_LOGIN=true on the server flips this back to true so
  3329. // the recovery path remains visible.
  3330. local_login_enabled: boolean;
  3331. // #1589: when set, LoginPage redirects to this provider's authorize URL
  3332. // on mount unless ?fallback=local is in the URL or the redirect times out.
  3333. autologin_provider_id: number | null;
  3334. }
  3335. export interface LDAPStatus {
  3336. ldap_enabled: boolean;
  3337. ldap_configured: boolean;
  3338. }
  3339. export interface EncryptionRowCounts {
  3340. oidc_providers: number;
  3341. user_totp: number;
  3342. }
  3343. export interface EncryptionStatus {
  3344. key_configured: boolean;
  3345. key_source: 'env' | 'file' | 'generated' | 'none';
  3346. legacy_plaintext_rows: EncryptionRowCounts;
  3347. encrypted_rows: EncryptionRowCounts;
  3348. decryption_broken: boolean;
  3349. // B2: count of rows skipped during the last legacy re-encryption migration.
  3350. // Surfaced via a yellow secondary banner in SecurityStatusCard.
  3351. migration_error_count: number;
  3352. }
  3353. export interface LDAPTestResponse {
  3354. success: boolean;
  3355. message: string;
  3356. }
  3357. export interface LDAPSearchResult {
  3358. username: string;
  3359. email: string | null;
  3360. display_name: string | null;
  3361. dn: string;
  3362. already_provisioned: boolean;
  3363. }
  3364. export interface SetupResponse {
  3365. auth_enabled: boolean;
  3366. admin_created?: boolean;
  3367. }
  3368. export interface AuthStatus {
  3369. auth_enabled: boolean;
  3370. requires_setup: boolean;
  3371. }
  3372. // API functions
  3373. export const api = {
  3374. // Authentication
  3375. getAuthStatus: () => request<AuthStatus>('/auth/status'),
  3376. setupAuth: (data: SetupRequest) =>
  3377. request<SetupResponse>('/auth/setup', {
  3378. method: 'POST',
  3379. body: JSON.stringify(data),
  3380. }),
  3381. login: (data: LoginRequest) =>
  3382. request<LoginResponse>('/auth/login', {
  3383. method: 'POST',
  3384. body: JSON.stringify(data),
  3385. }),
  3386. logout: () =>
  3387. request<{ message: string }>('/auth/logout', {
  3388. method: 'POST',
  3389. }),
  3390. getCurrentUser: () => request<UserResponse>('/auth/me'),
  3391. disableAuth: () =>
  3392. request<{ message: string; auth_enabled: boolean }>('/auth/disable', {
  3393. method: 'POST',
  3394. }),
  3395. // Advanced Authentication
  3396. testSMTP: (data: TestSMTPRequest) =>
  3397. request<TestSMTPResponse>('/auth/smtp/test', {
  3398. method: 'POST',
  3399. body: JSON.stringify(data),
  3400. }),
  3401. getSMTPSettings: () => request<SMTPSettings | null>('/auth/smtp'),
  3402. saveSMTPSettings: (data: SMTPSettings) =>
  3403. request<{ message: string }>('/auth/smtp', {
  3404. method: 'POST',
  3405. body: JSON.stringify(data),
  3406. }),
  3407. enableAdvancedAuth: () =>
  3408. request<{ message: string; advanced_auth_enabled: boolean }>('/auth/advanced-auth/enable', {
  3409. method: 'POST',
  3410. }),
  3411. disableAdvancedAuth: () =>
  3412. request<{ message: string; advanced_auth_enabled: boolean }>('/auth/advanced-auth/disable', {
  3413. method: 'POST',
  3414. }),
  3415. getAdvancedAuthStatus: () => request<AdvancedAuthStatus>('/auth/advanced-auth/status'),
  3416. // LDAP Authentication
  3417. getLDAPStatus: () => request<LDAPStatus>('/auth/ldap/status'),
  3418. getEncryptionStatus: () => request<EncryptionStatus>('/auth/encryption-status'),
  3419. testLDAP: () =>
  3420. request<LDAPTestResponse>('/auth/ldap/test', {
  3421. method: 'POST',
  3422. }),
  3423. searchLDAPDirectory: (q: string) =>
  3424. request<LDAPSearchResult[]>(`/auth/ldap/search?q=${encodeURIComponent(q)}`),
  3425. provisionLDAPUser: (username: string) =>
  3426. request<UserResponse>('/auth/ldap/provision', {
  3427. method: 'POST',
  3428. body: JSON.stringify({ username }),
  3429. }),
  3430. forgotPassword: (data: ForgotPasswordRequest) =>
  3431. request<ForgotPasswordResponse>('/auth/forgot-password', {
  3432. method: 'POST',
  3433. body: JSON.stringify(data),
  3434. }),
  3435. // H-6: Confirm password reset using the token from the emailed link
  3436. forgotPasswordConfirm: (token: string, newPassword: string) =>
  3437. request<ForgotPasswordResponse>('/auth/forgot-password/confirm', {
  3438. method: 'POST',
  3439. body: JSON.stringify({ token, new_password: newPassword }),
  3440. }),
  3441. resetUserPassword: (data: ResetPasswordRequest) =>
  3442. request<ResetPasswordResponse>('/auth/reset-password', {
  3443. method: 'POST',
  3444. body: JSON.stringify(data),
  3445. }),
  3446. // 2FA - status
  3447. get2FAStatus: () => request<TwoFAStatus>('/auth/2fa/status'),
  3448. // 2FA - TOTP
  3449. setupTOTP: () => request<TOTPSetupResponse>('/auth/2fa/totp/setup', { method: 'POST' }),
  3450. enableTOTP: (code: string) =>
  3451. request<TOTPEnableResponse>('/auth/2fa/totp/enable', {
  3452. method: 'POST',
  3453. body: JSON.stringify({ code }),
  3454. }),
  3455. disableTOTP: (code: string) =>
  3456. request<{ message: string }>('/auth/2fa/totp/disable', {
  3457. method: 'POST',
  3458. body: JSON.stringify({ code }),
  3459. }),
  3460. regenerateBackupCodes: (code: string) =>
  3461. request<BackupCodesResponse>('/auth/2fa/totp/regenerate-backup-codes', {
  3462. method: 'POST',
  3463. body: JSON.stringify({ code }),
  3464. }),
  3465. // 2FA - Email OTP
  3466. // Step 1: send a verification code to the user's email (proof of possession)
  3467. enableEmailOTP: () =>
  3468. request<{ message: string; setup_token: string }>('/auth/2fa/email/enable', { method: 'POST' }),
  3469. // Step 2: confirm with the code received by email
  3470. confirmEnableEmailOTP: (setup_token: string, code: string) =>
  3471. request<{ message: string }>('/auth/2fa/email/enable/confirm', {
  3472. method: 'POST',
  3473. body: JSON.stringify({ setup_token, code }),
  3474. }),
  3475. // Disable requires account password for re-auth
  3476. disableEmailOTP: (password: string) =>
  3477. request<{ message: string }>('/auth/2fa/email/disable', {
  3478. method: 'POST',
  3479. body: JSON.stringify({ password }),
  3480. }),
  3481. sendEmailOTP: (preAuthToken: string) =>
  3482. request<{ message: string; pre_auth_token?: string }>('/auth/2fa/email/send', {
  3483. method: 'POST',
  3484. body: JSON.stringify({ pre_auth_token: preAuthToken }),
  3485. }),
  3486. // 2FA - verify (completes login)
  3487. verify2FA: (data: TwoFAVerifyRequest) =>
  3488. request<LoginResponse>('/auth/2fa/verify', {
  3489. method: 'POST',
  3490. body: JSON.stringify(data),
  3491. }),
  3492. // 2FA - admin
  3493. admin2FADisable: (userId: number) =>
  3494. request<{ message: string }>(`/auth/2fa/admin/${userId}`, { method: 'DELETE' }),
  3495. // OIDC providers (public list)
  3496. getOIDCProviders: () => request<OIDCProvider[]>('/auth/oidc/providers'),
  3497. // OIDC providers (admin)
  3498. getOIDCProvidersAll: () => request<OIDCProvider[]>('/auth/oidc/providers/all'),
  3499. createOIDCProvider: (data: OIDCProviderCreate) =>
  3500. request<OIDCProvider>('/auth/oidc/providers', {
  3501. method: 'POST',
  3502. body: JSON.stringify(data),
  3503. }),
  3504. updateOIDCProvider: (id: number, data: Partial<OIDCProviderCreate>) =>
  3505. request<OIDCProvider>(`/auth/oidc/providers/${id}`, {
  3506. method: 'PUT',
  3507. body: JSON.stringify(data),
  3508. }),
  3509. deleteOIDCProvider: (id: number) =>
  3510. request<{ message: string }>(`/auth/oidc/providers/${id}`, { method: 'DELETE' }),
  3511. // OIDC provider icon proxy (#1333) — same-origin path so the strict
  3512. // img-src CSP stays in force. Returns a SameOriginUrl-branded string
  3513. // so a future caller can't accidentally substitute an attacker-
  3514. // controlled URL where this is consumed.
  3515. oidcProviderIconUrl: (id: number): SameOriginUrl =>
  3516. `/api/v1/auth/oidc/providers/${id}/icon` as SameOriginUrl,
  3517. deleteOIDCProviderIcon: (id: number) =>
  3518. request<void>(`/auth/oidc/providers/${id}/icon`, { method: 'DELETE' }),
  3519. refreshOIDCProviderIcon: (id: number) =>
  3520. request<OIDCProvider>(`/auth/oidc/providers/${id}/icon/refresh`, { method: 'POST' }),
  3521. // OIDC authorize URL
  3522. getOIDCAuthorizeUrl: (providerId: number) =>
  3523. request<{ auth_url: string }>(`/auth/oidc/authorize/${providerId}`),
  3524. // OIDC exchange token for JWT
  3525. exchangeOIDCToken: (oidcToken: string) =>
  3526. request<LoginResponse>('/auth/oidc/exchange', {
  3527. method: 'POST',
  3528. body: JSON.stringify({ oidc_token: oidcToken }),
  3529. }),
  3530. // OIDC links for current user
  3531. getOIDCLinks: () => request<OIDCLink[]>('/auth/oidc/links'),
  3532. deleteOIDCLink: (providerId: number) =>
  3533. request<{ message: string }>(`/auth/oidc/links/${providerId}`, { method: 'DELETE' }),
  3534. // Users
  3535. getUsers: () => request<UserResponse[]>('/users/'),
  3536. getUser: (id: number) => request<UserResponse>(`/users/${id}`),
  3537. createUser: (data: UserCreate) =>
  3538. request<UserResponse>('/users/', {
  3539. method: 'POST',
  3540. body: JSON.stringify(data),
  3541. }),
  3542. updateUser: (id: number, data: UserUpdate) =>
  3543. request<UserResponse>(`/users/${id}`, {
  3544. method: 'PATCH',
  3545. body: JSON.stringify(data),
  3546. }),
  3547. deleteUser: (id: number, deleteItems: boolean = false) =>
  3548. request<void>(`/users/${id}?delete_items=${deleteItems}`, {
  3549. method: 'DELETE',
  3550. }),
  3551. getUserItemsCount: (id: number) =>
  3552. request<{ archives: number; queue_items: number; library_files: number }>(`/users/${id}/items-count`),
  3553. changePassword: (currentPassword: string, newPassword: string) =>
  3554. request<{ message: string }>('/users/me/change-password', {
  3555. method: 'POST',
  3556. body: JSON.stringify({ current_password: currentPassword, new_password: newPassword }),
  3557. }),
  3558. // User Email Notifications
  3559. getUserEmailPreferences: () =>
  3560. request<UserEmailPreferences>('/user-notifications/preferences'),
  3561. updateUserEmailPreferences: (data: UserEmailPreferences) =>
  3562. request<UserEmailPreferences>('/user-notifications/preferences', {
  3563. method: 'PUT',
  3564. body: JSON.stringify(data),
  3565. }),
  3566. // Groups
  3567. getPermissions: () => request<PermissionsListResponse>('/groups/permissions'),
  3568. getGroups: () => request<Group[]>('/groups/'),
  3569. getGroup: (id: number) => request<GroupDetail>(`/groups/${id}`),
  3570. createGroup: (data: GroupCreate) =>
  3571. request<Group>('/groups/', {
  3572. method: 'POST',
  3573. body: JSON.stringify(data),
  3574. }),
  3575. updateGroup: (id: number, data: GroupUpdate) =>
  3576. request<Group>(`/groups/${id}`, {
  3577. method: 'PATCH',
  3578. body: JSON.stringify(data),
  3579. }),
  3580. deleteGroup: (id: number) =>
  3581. request<void>(`/groups/${id}`, {
  3582. method: 'DELETE',
  3583. }),
  3584. addUserToGroup: (groupId: number, userId: number) =>
  3585. request<void>(`/groups/${groupId}/users/${userId}`, {
  3586. method: 'POST',
  3587. }),
  3588. removeUserFromGroup: (groupId: number, userId: number) =>
  3589. request<void>(`/groups/${groupId}/users/${userId}`, {
  3590. method: 'DELETE',
  3591. }),
  3592. // Printers
  3593. getPrinters: () => request<Printer[]>('/printers/'),
  3594. getPrinter: (id: number) => request<Printer>(`/printers/${id}`),
  3595. createPrinter: (data: PrinterCreate) =>
  3596. request<Printer>('/printers/', {
  3597. method: 'POST',
  3598. body: JSON.stringify(data),
  3599. }),
  3600. updatePrinter: (id: number, data: Partial<PrinterCreate>) =>
  3601. request<Printer>(`/printers/${id}`, {
  3602. method: 'PATCH',
  3603. body: JSON.stringify(data),
  3604. }),
  3605. deletePrinter: (id: number, deleteArchives: boolean = true) =>
  3606. request<{ status: string; archives_deleted: boolean }>(
  3607. `/printers/${id}?delete_archives=${deleteArchives}`,
  3608. { method: 'DELETE' }
  3609. ),
  3610. getDeveloperModeWarnings: () =>
  3611. request<{ printer_id: number; name: string }[]>('/printers/developer-mode-warnings'),
  3612. getAvailableFilaments: (model: string, location?: string) => {
  3613. const params = new URLSearchParams({ model });
  3614. if (location) params.set('location', location);
  3615. return request<Array<{ type: string; color: string; tray_info_idx: string; tray_sub_brands: string; extruder_id: number | null }>>(`/printers/available-filaments?${params}`);
  3616. },
  3617. getPrinterStatus: (id: number) =>
  3618. request<PrinterStatus>(`/printers/${id}/status`),
  3619. refreshPrinterStatus: (id: number) =>
  3620. request<{ status: string }>(`/printers/${id}/refresh-status`, {
  3621. method: 'POST',
  3622. }),
  3623. connectPrinter: (id: number) =>
  3624. request<{ connected: boolean }>(`/printers/${id}/connect`, {
  3625. method: 'POST',
  3626. }),
  3627. disconnectPrinter: (id: number) =>
  3628. request<{ connected: boolean }>(`/printers/${id}/disconnect`, {
  3629. method: 'POST',
  3630. }),
  3631. testExternalCamera: (printerId: number, url: string, cameraType: string) =>
  3632. // `coalesced` is true when the frame came from a capture that was already
  3633. // running (Obico polling, a snapshot) rather than a connection this test
  3634. // opened — a single-reader camera is shared rather than opened twice, so
  3635. // the result is real but says nothing about reaching the camera just now.
  3636. request<{ success: boolean; error?: string; resolution?: string; coalesced?: boolean }>(
  3637. `/printers/${printerId}/camera/external/test?url=${encodeURIComponent(url)}&camera_type=${encodeURIComponent(cameraType)}`,
  3638. { method: 'POST' }
  3639. ),
  3640. // Print Control
  3641. stopPrint: (printerId: number) =>
  3642. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/stop`, {
  3643. method: 'POST',
  3644. }),
  3645. pausePrint: (printerId: number) =>
  3646. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/pause`, {
  3647. method: 'POST',
  3648. }),
  3649. resumePrint: (printerId: number) =>
  3650. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/resume`, {
  3651. method: 'POST',
  3652. }),
  3653. clearPlate: (printerId: number) =>
  3654. request<{ success: boolean; message: string }>(`/printers/${printerId}/clear-plate`, {
  3655. method: 'POST',
  3656. }),
  3657. // Get current print user (for reprint tracking - Issue #206)
  3658. getCurrentPrintUser: (printerId: number) =>
  3659. request<{ user_id?: number; username?: string }>(`/printers/${printerId}/current-print-user`),
  3660. // Print Speed Control
  3661. setPrintSpeed: (printerId: number, mode: number) =>
  3662. request<{ success: boolean; message: string }>(`/printers/${printerId}/print-speed?mode=${mode}`, {
  3663. method: 'POST',
  3664. }),
  3665. setNozzleTemperature: (printerId: number, target: number, nozzle: number = 0) =>
  3666. request<{ success: boolean; message: string }>(
  3667. `/printers/${printerId}/temperature/nozzle?target=${target}&nozzle=${nozzle}`,
  3668. { method: 'POST' }
  3669. ),
  3670. setBedTemperature: (printerId: number, target: number) =>
  3671. request<{ success: boolean; message: string }>(`/printers/${printerId}/temperature/bed?target=${target}`, {
  3672. method: 'POST',
  3673. }),
  3674. setChamberTemperature: (printerId: number, target: number) =>
  3675. request<{ success: boolean; message: string }>(`/printers/${printerId}/temperature/chamber?target=${target}`, {
  3676. method: 'POST',
  3677. }),
  3678. setFanSpeed: (printerId: number, fan: 'part' | 'aux' | 'aux2' | 'chamber', speed: number) =>
  3679. request<{ success: boolean; message: string }>(`/printers/${printerId}/fan-speed?fan=${fan}&speed=${speed}`, {
  3680. method: 'POST',
  3681. }),
  3682. selectExtruder: (printerId: number, extruder: number) =>
  3683. request<{ success: boolean; message: string }>(`/printers/${printerId}/select-extruder?extruder=${extruder}`, {
  3684. method: 'POST',
  3685. }),
  3686. setAirductMode: (printerId: number, mode: 'cooling' | 'heating') =>
  3687. request<{ success: boolean; message: string }>(`/printers/${printerId}/airduct-mode?mode=${mode}`, {
  3688. method: 'POST',
  3689. }),
  3690. // Bed (Z-axis) jog
  3691. bedJog: (printerId: number, distance: number) =>
  3692. request<{ success: boolean; message: string }>(
  3693. `/printers/${printerId}/bed-jog?distance=${distance}`,
  3694. { method: 'POST' }
  3695. ),
  3696. xyJog: (printerId: number, x: number, y: number) =>
  3697. request<{ success: boolean; message: string }>(
  3698. `/printers/${printerId}/xy-jog?x=${x}&y=${y}`,
  3699. { method: 'POST' }
  3700. ),
  3701. extruderJog: (printerId: number, distance: number) =>
  3702. request<{ success: boolean; message: string }>(
  3703. `/printers/${printerId}/extruder-jog?distance=${distance}`,
  3704. { method: 'POST' }
  3705. ),
  3706. homeAxes: (printerId: number, axes: 'z' | 'xy' | 'all' = 'z') =>
  3707. request<{ success: boolean; message: string }>(
  3708. `/printers/${printerId}/home-axes?axes=${axes}`,
  3709. { method: 'POST' }
  3710. ),
  3711. // Chamber Light Control
  3712. setChamberLight: (printerId: number, on: boolean) =>
  3713. request<{ success: boolean; message: string }>(`/printers/${printerId}/chamber-light?on=${on}`, {
  3714. method: 'POST',
  3715. }),
  3716. // AMS Drying Control
  3717. startDrying: (printerId: number, amsId: number, temp: number, duration: number, filament: string = '', rotateTray: boolean = false) =>
  3718. request<{ status: string; ams_id: number; temp: number; duration: number }>(
  3719. `/printers/${printerId}/drying/start?ams_id=${amsId}&temp=${temp}&duration=${duration}&filament=${encodeURIComponent(filament)}&rotate_tray=${rotateTray}`,
  3720. { method: 'POST' }
  3721. ),
  3722. stopDrying: (printerId: number, amsId: number) =>
  3723. request<{ status: string; ams_id: number }>(
  3724. `/printers/${printerId}/drying/stop?ams_id=${amsId}`,
  3725. { method: 'POST' }
  3726. ),
  3727. // AMS Filament Backup (auto-switch to a backup spool when one runs out)
  3728. setAmsFilamentBackup: (printerId: number, enabled: boolean) =>
  3729. request<{ success: boolean; ams_filament_backup: boolean }>(
  3730. `/printers/${printerId}/ams-backup?enabled=${enabled}`,
  3731. { method: 'POST' }
  3732. ),
  3733. // Per-globalTrayId remaining grams for this printer's inventory-bound slots
  3734. // (#1766). Drives the client-side "Prefer Lowest Remaining Filament" sort
  3735. // when computing the AMS mapping; mirrors backend `_build_inventory_remain_overrides`
  3736. // so internal and Spoolman modes both work uniformly.
  3737. getInventoryRemain: (printerId: number) =>
  3738. request<{ inventory_remain_g: Record<string, number> }>(
  3739. `/printers/${printerId}/inventory-remain`,
  3740. ),
  3741. // Skip Objects
  3742. getPrintableObjects: (printerId: number) =>
  3743. request<{
  3744. objects: Array<{ id: number; name: string; x: number | null; y: number | null; skipped: boolean }>;
  3745. total: number;
  3746. skipped_count: number;
  3747. is_printing: boolean;
  3748. bbox_all: [number, number, number, number] | null;
  3749. }>(`/printers/${printerId}/print/objects`),
  3750. skipObjects: (printerId: number, objectIds: number[]) =>
  3751. request<{ success: boolean; message: string; skipped_objects: number[] }>(
  3752. `/printers/${printerId}/print/skip-objects`,
  3753. {
  3754. method: 'POST',
  3755. body: JSON.stringify(objectIds),
  3756. }
  3757. ),
  3758. // HMS Errors
  3759. clearHMSErrors: (printerId: number) =>
  3760. request<{ success: boolean; message: string }>(`/printers/${printerId}/hms/clear`, { method: 'POST' }),
  3761. executeHMSAction: (printerId: number, data: HMSActionBody) =>
  3762. request<{ success: boolean; message: string }>(`/printers/${printerId}/hms/execute-action`, {
  3763. method: 'POST',
  3764. body: JSON.stringify(data),
  3765. }),
  3766. // AMS Control
  3767. refreshAmsSlot: (printerId: number, amsId: number, slotId: number) =>
  3768. request<{ success: boolean; message: string }>(
  3769. `/printers/${printerId}/ams/${amsId}/slot/${slotId}/refresh`,
  3770. { method: 'POST' }
  3771. ),
  3772. // Load filament from a tray. trayId: 0-15 for AMS (amsId*4+slotId), 254 for external spool.
  3773. loadAmsTray: (printerId: number, trayId: number) =>
  3774. request<{ success: boolean; message: string }>(
  3775. `/printers/${printerId}/ams/load?tray_id=${trayId}`,
  3776. { method: 'POST' }
  3777. ),
  3778. // Unload the currently loaded filament.
  3779. unloadAms: (printerId: number) =>
  3780. request<{ success: boolean; message: string }>(
  3781. `/printers/${printerId}/ams/unload`,
  3782. { method: 'POST' }
  3783. ),
  3784. // MQTT Debug Logging
  3785. enableMQTTLogging: (printerId: number) =>
  3786. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/enable`, {
  3787. method: 'POST',
  3788. }),
  3789. disableMQTTLogging: (printerId: number) =>
  3790. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/disable`, {
  3791. method: 'POST',
  3792. }),
  3793. getMQTTLogs: (printerId: number) =>
  3794. request<MQTTLogsResponse>(`/printers/${printerId}/logging`),
  3795. clearMQTTLogs: (printerId: number) =>
  3796. request<{ status: string }>(`/printers/${printerId}/logging`, {
  3797. method: 'DELETE',
  3798. }),
  3799. // Printer File Manager
  3800. getPrinterFiles: (printerId: number, path = '/') =>
  3801. request<{
  3802. path: string;
  3803. files: Array<{
  3804. name: string;
  3805. is_directory: boolean;
  3806. size: number;
  3807. path: string;
  3808. mtime?: string;
  3809. }>;
  3810. }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`),
  3811. getPrinterFileDownloadUrl: (printerId: number, path: string) =>
  3812. `${API_BASE}/printers/${printerId}/files/download?path=${encodeURIComponent(path)}`,
  3813. getPrinterFileGcodeUrl: (printerId: number, path: string) =>
  3814. `${API_BASE}/printers/${printerId}/files/gcode?path=${encodeURIComponent(path)}`,
  3815. getPrinterFilePlates: (printerId: number, path: string) =>
  3816. request<{
  3817. printer_id: number;
  3818. path: string;
  3819. filename: string;
  3820. plates: Array<{
  3821. index: number;
  3822. name: string | null;
  3823. objects: string[];
  3824. has_thumbnail: boolean;
  3825. thumbnail_url: string | null;
  3826. print_time_seconds: number | null;
  3827. filament_used_grams: number | null;
  3828. filaments: Array<{
  3829. slot_id: number;
  3830. type: string;
  3831. color: string;
  3832. used_grams: number;
  3833. used_meters: number;
  3834. }>;
  3835. }>;
  3836. is_multi_plate: boolean;
  3837. }>(`/printers/${printerId}/files/plates?path=${encodeURIComponent(path)}`),
  3838. getPrinterFilePlateThumbnail: (printerId: number, plateIndex: number, path: string) =>
  3839. withStreamToken(`${API_BASE}/printers/${printerId}/files/plate-thumbnail/${plateIndex}?path=${encodeURIComponent(path)}`),
  3840. downloadPrinterFile: async (printerId: number, path: string): Promise<void> => {
  3841. const headers: Record<string, string> = {};
  3842. if (authToken) {
  3843. headers['Authorization'] = `Bearer ${authToken}`;
  3844. }
  3845. const response = await fetch(
  3846. `${API_BASE}/printers/${printerId}/files/download?path=${encodeURIComponent(path)}`,
  3847. { headers }
  3848. );
  3849. if (!response.ok) {
  3850. const error = await response.json().catch(() => ({}));
  3851. throw new Error(error.detail || `HTTP ${response.status}`);
  3852. }
  3853. const disposition = response.headers.get('Content-Disposition');
  3854. const filename = parseContentDispositionFilename(disposition) || path.split('/').pop() || 'download';
  3855. const blob = await response.blob();
  3856. const url = window.URL.createObjectURL(blob);
  3857. const a = document.createElement('a');
  3858. a.href = url;
  3859. a.download = filename;
  3860. document.body.appendChild(a);
  3861. a.click();
  3862. document.body.removeChild(a);
  3863. window.URL.revokeObjectURL(url);
  3864. },
  3865. downloadPrinterFilesAsZip: async (printerId: number, paths: string[]): Promise<Blob> => {
  3866. const headers: Record<string, string> = { 'Content-Type': 'application/json' };
  3867. if (authToken) {
  3868. headers['Authorization'] = `Bearer ${authToken}`;
  3869. }
  3870. const response = await fetch(`${API_BASE}/printers/${printerId}/files/download-zip`, {
  3871. method: 'POST',
  3872. headers,
  3873. body: JSON.stringify({ paths }),
  3874. });
  3875. if (!response.ok) {
  3876. const error = await response.json().catch(() => ({}));
  3877. throw new Error(error.detail || `HTTP ${response.status}`);
  3878. }
  3879. return response.blob();
  3880. },
  3881. deletePrinterFile: (printerId: number, path: string) =>
  3882. request<{ status: string; path: string }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`, {
  3883. method: 'DELETE',
  3884. }),
  3885. getPrinterStorage: (printerId: number) =>
  3886. request<{ used_bytes: number | null; free_bytes: number | null }>(`/printers/${printerId}/storage`),
  3887. // Archives
  3888. getArchives: (printerId?: number, projectId?: number, limit = 10000, offset = 0, dateFrom?: string, dateTo?: string) => {
  3889. const params = new URLSearchParams();
  3890. if (printerId) params.set('printer_id', String(printerId));
  3891. if (projectId) params.set('project_id', String(projectId));
  3892. params.set('limit', String(limit));
  3893. params.set('offset', String(offset));
  3894. if (dateFrom) params.set('date_from', dateFrom);
  3895. if (dateTo) params.set('date_to', dateTo);
  3896. return request<Archive[]>(`/archives/?${params}`);
  3897. },
  3898. getArchivesSlim: (dateFrom?: string, dateTo?: string, createdById?: number) => {
  3899. const params = new URLSearchParams();
  3900. if (dateFrom) params.set('date_from', dateFrom);
  3901. if (dateTo) params.set('date_to', dateTo);
  3902. if (createdById !== undefined) params.set('created_by_id', String(createdById));
  3903. const qs = params.toString();
  3904. return request<ArchiveSlim[]>(`/archives/slim${qs ? `?${qs}` : ''}`);
  3905. },
  3906. getArchive: (id: number) => request<Archive>(`/archives/${id}`),
  3907. getArchiveRuns: (id: number) => request<PrintLogResponse>(`/archives/${id}/runs`),
  3908. /**
  3909. * Pre-flight for the delete-confirm modal (#1734). Returns the number of
  3910. * related queue items that will be removed along with the archive AND how
  3911. * many are currently printing (server 409s on delete if > 0).
  3912. */
  3913. getArchiveDeleteImpact: (id: number) =>
  3914. request<{ related_queue_items: number; currently_printing: number }>(
  3915. `/archives/${id}/delete-impact`
  3916. ),
  3917. searchArchives: (query: string, options?: {
  3918. printerId?: number;
  3919. projectId?: number;
  3920. status?: string;
  3921. limit?: number;
  3922. offset?: number;
  3923. }) => {
  3924. const params = new URLSearchParams();
  3925. params.set('q', query);
  3926. if (options?.printerId) params.set('printer_id', String(options.printerId));
  3927. if (options?.projectId) params.set('project_id', String(options.projectId));
  3928. if (options?.status) params.set('status', options.status);
  3929. if (options?.limit) params.set('limit', String(options.limit));
  3930. if (options?.offset) params.set('offset', String(options.offset));
  3931. return request<Archive[]>(`/archives/search?${params}`);
  3932. },
  3933. rebuildSearchIndex: () => request<{ message: string }>('/archives/search/rebuild-index', { method: 'POST' }),
  3934. getNo3MFWarning: () => request<{ has_fallback: boolean }>('/archives/no-3mf-warning'),
  3935. updateArchive: (id: number, data: {
  3936. printer_id?: number | null;
  3937. project_id?: number | null;
  3938. print_name?: string;
  3939. is_favorite?: boolean;
  3940. tags?: string;
  3941. notes?: string;
  3942. cost?: number;
  3943. failure_reason?: string | null;
  3944. status?: string;
  3945. quantity?: number;
  3946. external_url?: string | null;
  3947. }) =>
  3948. request<Archive>(`/archives/${id}`, {
  3949. method: 'PATCH',
  3950. body: JSON.stringify(data),
  3951. }),
  3952. toggleFavorite: (id: number) =>
  3953. request<Archive>(`/archives/${id}/favorite`, { method: 'POST' }),
  3954. // Soft-deletes by default (#1343): files removed from disk, row hidden
  3955. // from listings, but its filament / time / cost / energy contribution
  3956. // stays in Quick Stats. Pass purgeStats=true to hard-delete and drop the
  3957. // row from statistics too.
  3958. deleteArchive: (id: number, purgeStats: boolean = false) =>
  3959. request<void>(`/archives/${id}${purgeStats ? '?purge_stats=true' : ''}`, { method: 'DELETE' }),
  3960. // ========== Archive auto-purge (#1008 follow-up) ==========
  3961. previewArchivePurge: (olderThanDays: number, purgeStats: boolean = false) =>
  3962. request<ArchivePurgePreview>(
  3963. `/archives/purge/preview?older_than_days=${olderThanDays}&purge_stats=${purgeStats}`,
  3964. ),
  3965. // #1390: purgeStats=false (default) soft-deletes each old archive — Quick Stats
  3966. // preserved, files removed from disk, row hidden via deleted_at. true matches
  3967. // the single-archive delete's `?purge_stats=true` semantics (hard-deletes the
  3968. // linked PrintLogEntry rows so the contribution drops from /stats too).
  3969. executeArchivePurge: (olderThanDays: number, purgeStats: boolean = false) =>
  3970. request<{ deleted: number; purge_stats: boolean }>('/archives/purge', {
  3971. method: 'POST',
  3972. body: JSON.stringify({ older_than_days: olderThanDays, purge_stats: purgeStats }),
  3973. }),
  3974. getArchivePurgeSettings: () =>
  3975. request<ArchivePurgeSettings>('/archives/purge/settings'),
  3976. updateArchivePurgeSettings: (body: ArchivePurgeSettings) =>
  3977. request<ArchivePurgeSettings>('/archives/purge/settings', {
  3978. method: 'PUT',
  3979. body: JSON.stringify(body),
  3980. }),
  3981. getArchiveStats: (options?: { dateFrom?: string; dateTo?: string; createdById?: number }) => {
  3982. const params = new URLSearchParams();
  3983. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  3984. if (options?.dateTo) params.set('date_to', options.dateTo);
  3985. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  3986. const qs = params.toString();
  3987. return request<ArchiveStats>(`/archives/stats${qs ? `?${qs}` : ''}`);
  3988. },
  3989. // Tag management
  3990. getTags: () => request<TagInfo[]>('/archives/tags'),
  3991. renameTag: (oldName: string, newName: string) =>
  3992. request<{ affected: number }>(`/archives/tags/${encodeURIComponent(oldName)}`, {
  3993. method: 'PUT',
  3994. body: JSON.stringify({ new_name: newName }),
  3995. }),
  3996. deleteTag: (name: string) =>
  3997. request<{ affected: number }>(`/archives/tags/${encodeURIComponent(name)}`, {
  3998. method: 'DELETE',
  3999. }),
  4000. recalculateCosts: () =>
  4001. request<{ message: string; updated: number }>('/archives/recalculate-costs', { method: 'POST' }),
  4002. getFailureAnalysis: (options?: { days?: number; dateFrom?: string; dateTo?: string; printerId?: number; projectId?: number; createdById?: number }) => {
  4003. const params = new URLSearchParams();
  4004. if (options?.days) params.set('days', String(options.days));
  4005. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  4006. if (options?.dateTo) params.set('date_to', options.dateTo);
  4007. if (options?.printerId) params.set('printer_id', String(options.printerId));
  4008. if (options?.projectId) params.set('project_id', String(options.projectId));
  4009. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  4010. const qs = params.toString();
  4011. return request<FailureAnalysis>(`/archives/analysis/failures${qs ? `?${qs}` : ''}`);
  4012. },
  4013. compareArchives: (archiveIds: number[]) =>
  4014. request<ArchiveComparison>(`/archives/compare?archive_ids=${archiveIds.join(',')}`),
  4015. findSimilarArchives: (archiveId: number, limit = 10) =>
  4016. request<SimilarArchive[]>(`/archives/${archiveId}/similar?limit=${limit}`),
  4017. exportArchives: async (options?: {
  4018. format?: 'csv' | 'xlsx';
  4019. fields?: string[];
  4020. printerId?: number;
  4021. projectId?: number;
  4022. status?: string;
  4023. dateFrom?: string;
  4024. dateTo?: string;
  4025. search?: string;
  4026. }): Promise<{ blob: Blob; filename: string }> => {
  4027. const params = new URLSearchParams();
  4028. if (options?.format) params.set('format', options.format);
  4029. if (options?.fields) params.set('fields', options.fields.join(','));
  4030. if (options?.printerId) params.set('printer_id', String(options.printerId));
  4031. if (options?.projectId) params.set('project_id', String(options.projectId));
  4032. if (options?.status) params.set('status', options.status);
  4033. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  4034. if (options?.dateTo) params.set('date_to', options.dateTo);
  4035. if (options?.search) params.set('search', options.search);
  4036. const headers: Record<string, string> = {};
  4037. if (authToken) {
  4038. headers['Authorization'] = `Bearer ${authToken}`;
  4039. }
  4040. const response = await fetch(`${API_BASE}/archives/export?${params}`, { headers });
  4041. if (!response.ok) {
  4042. const error = await response.json().catch(() => ({}));
  4043. throw new Error(error.detail || `HTTP ${response.status}`);
  4044. }
  4045. const contentDisposition = response.headers.get('Content-Disposition');
  4046. let filename = options?.format === 'xlsx' ? 'archives_export.xlsx' : 'archives_export.csv';
  4047. if (contentDisposition) {
  4048. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  4049. if (match) filename = match[1];
  4050. }
  4051. const blob = await response.blob();
  4052. return { blob, filename };
  4053. },
  4054. exportStats: async (options?: {
  4055. format?: 'csv' | 'xlsx';
  4056. days?: number;
  4057. printerId?: number;
  4058. projectId?: number;
  4059. createdById?: number;
  4060. }): Promise<{ blob: Blob; filename: string }> => {
  4061. const params = new URLSearchParams();
  4062. if (options?.format) params.set('format', options.format);
  4063. if (options?.days) params.set('days', String(options.days));
  4064. if (options?.printerId) params.set('printer_id', String(options.printerId));
  4065. if (options?.projectId) params.set('project_id', String(options.projectId));
  4066. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  4067. const headers: Record<string, string> = {};
  4068. if (authToken) {
  4069. headers['Authorization'] = `Bearer ${authToken}`;
  4070. }
  4071. const response = await fetch(`${API_BASE}/archives/stats/export?${params}`, { headers });
  4072. if (!response.ok) {
  4073. const error = await response.json().catch(() => ({}));
  4074. throw new Error(error.detail || `HTTP ${response.status}`);
  4075. }
  4076. const contentDisposition = response.headers.get('Content-Disposition');
  4077. let filename = options?.format === 'xlsx' ? 'stats_export.xlsx' : 'stats_export.csv';
  4078. if (contentDisposition) {
  4079. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  4080. if (match) filename = match[1];
  4081. }
  4082. const blob = await response.blob();
  4083. return { blob, filename };
  4084. },
  4085. getArchiveDuplicates: (id: number) =>
  4086. request<{ duplicates: ArchiveDuplicate[]; count: number }>(`/archives/${id}/duplicates`),
  4087. backfillContentHashes: () =>
  4088. request<{ updated: number; errors: Array<{ id: number; error: string }> }>('/archives/backfill-hashes', {
  4089. method: 'POST',
  4090. }),
  4091. getArchiveThumbnail: (id: number) => withStreamToken(`${API_BASE}/archives/${id}/thumbnail?v=${Date.now()}`),
  4092. getArchivePlateThumbnail: (id: number, plateIndex: number) =>
  4093. withStreamToken(`${API_BASE}/archives/${id}/plate-thumbnail/${plateIndex}`),
  4094. getArchiveDownload: (id: number) => `${API_BASE}/archives/${id}/download`,
  4095. downloadArchive: async (id: number, filename?: string): Promise<void> => {
  4096. const headers: Record<string, string> = {};
  4097. if (authToken) {
  4098. headers['Authorization'] = `Bearer ${authToken}`;
  4099. }
  4100. const response = await fetch(`${API_BASE}/archives/${id}/download`, { headers });
  4101. if (!response.ok) {
  4102. const error = await response.json().catch(() => ({}));
  4103. throw new Error(error.detail || `HTTP ${response.status}`);
  4104. }
  4105. const disposition = response.headers.get('Content-Disposition');
  4106. const downloadFilename = parseContentDispositionFilename(disposition) || filename || `archive_${id}.3mf`;
  4107. const blob = await response.blob();
  4108. const url = window.URL.createObjectURL(blob);
  4109. const a = document.createElement('a');
  4110. a.href = url;
  4111. a.download = downloadFilename;
  4112. document.body.appendChild(a);
  4113. a.click();
  4114. document.body.removeChild(a);
  4115. window.URL.revokeObjectURL(url);
  4116. },
  4117. getArchiveGcode: (id: number) => `${API_BASE}/archives/${id}/gcode`,
  4118. getArchivePlatePreview: (id: number) => withStreamToken(`${API_BASE}/archives/${id}/plate-preview`),
  4119. getArchiveTimelapse: (id: number) => withStreamToken(`${API_BASE}/archives/${id}/timelapse?v=${Date.now()}`),
  4120. scanArchiveTimelapse: (id: number) =>
  4121. request<{
  4122. status: string;
  4123. message: string;
  4124. filename?: string;
  4125. available_files?: Array<{ name: string; path: string; size: number; mtime: string | null }>;
  4126. }>(`/archives/${id}/timelapse/scan`, {
  4127. method: 'POST',
  4128. }),
  4129. selectArchiveTimelapse: (id: number, filename: string) =>
  4130. request<{ status: string; message: string; filename: string }>(
  4131. `/archives/${id}/timelapse/select?filename=${encodeURIComponent(filename)}`,
  4132. { method: 'POST' }
  4133. ),
  4134. deleteArchiveTimelapse: (id: number) =>
  4135. request<{ status: string }>(`/archives/${id}/timelapse`, {
  4136. method: 'DELETE',
  4137. }),
  4138. uploadArchiveTimelapse: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  4139. const formData = new FormData();
  4140. formData.append('file', file);
  4141. const headers: Record<string, string> = {};
  4142. if (authToken) {
  4143. headers['Authorization'] = `Bearer ${authToken}`;
  4144. }
  4145. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/upload`, {
  4146. method: 'POST',
  4147. headers,
  4148. body: formData,
  4149. });
  4150. if (!response.ok) {
  4151. const error = await response.json().catch(() => ({}));
  4152. throw new Error(error.detail || `HTTP ${response.status}`);
  4153. }
  4154. return response.json();
  4155. },
  4156. // Timelapse Editor
  4157. getTimelapseInfo: (archiveId: number) =>
  4158. request<{
  4159. duration: number;
  4160. width: number;
  4161. height: number;
  4162. fps: number;
  4163. codec: string;
  4164. file_size: number;
  4165. has_audio: boolean;
  4166. }>(`/archives/${archiveId}/timelapse/info`),
  4167. getTimelapseThumbnails: (archiveId: number, count: number = 10) =>
  4168. request<{
  4169. thumbnails: string[];
  4170. timestamps: number[];
  4171. }>(`/archives/${archiveId}/timelapse/thumbnails?count=${count}`),
  4172. processTimelapse: async (
  4173. archiveId: number,
  4174. params: {
  4175. trimStart?: number;
  4176. trimEnd?: number;
  4177. speed?: number;
  4178. saveMode: 'replace' | 'new';
  4179. outputFilename?: string;
  4180. },
  4181. audioFile?: File
  4182. ): Promise<{ status: string; output_path: string | null; message: string }> => {
  4183. const formData = new FormData();
  4184. formData.append('trim_start', String(params.trimStart ?? 0));
  4185. if (params.trimEnd !== undefined) {
  4186. formData.append('trim_end', String(params.trimEnd));
  4187. }
  4188. formData.append('speed', String(params.speed ?? 1));
  4189. formData.append('save_mode', params.saveMode);
  4190. if (params.outputFilename) {
  4191. formData.append('output_filename', params.outputFilename);
  4192. }
  4193. if (audioFile) {
  4194. formData.append('audio', audioFile);
  4195. }
  4196. const headers: Record<string, string> = {};
  4197. if (authToken) {
  4198. headers['Authorization'] = `Bearer ${authToken}`;
  4199. }
  4200. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/process`, {
  4201. method: 'POST',
  4202. headers,
  4203. body: formData,
  4204. });
  4205. if (!response.ok) {
  4206. const error = await response.json().catch(() => ({}));
  4207. throw new Error(error.detail || `HTTP ${response.status}`);
  4208. }
  4209. return response.json();
  4210. },
  4211. // Photos
  4212. getArchivePhotoUrl: (archiveId: number, filename: string) =>
  4213. withStreamToken(`${API_BASE}/archives/${archiveId}/photos/${encodeURIComponent(filename)}`),
  4214. uploadArchivePhoto: async (archiveId: number, file: File): Promise<{ status: string; filename: string; photos: string[] }> => {
  4215. const formData = new FormData();
  4216. formData.append('file', file);
  4217. const headers: Record<string, string> = {};
  4218. if (authToken) {
  4219. headers['Authorization'] = `Bearer ${authToken}`;
  4220. }
  4221. const response = await fetch(`${API_BASE}/archives/${archiveId}/photos`, {
  4222. headers,
  4223. method: 'POST',
  4224. body: formData,
  4225. });
  4226. if (!response.ok) {
  4227. const error = await response.json().catch(() => ({}));
  4228. throw new Error(error.detail || `HTTP ${response.status}`);
  4229. }
  4230. return response.json();
  4231. },
  4232. deleteArchivePhoto: (archiveId: number, filename: string) =>
  4233. request<{ status: string; photos: string[] | null }>(`/archives/${archiveId}/photos/${encodeURIComponent(filename)}`, {
  4234. method: 'DELETE',
  4235. }),
  4236. // Source 3MF (original slicer project file)
  4237. getSource3mfDownloadUrl: (archiveId: number) =>
  4238. `${API_BASE}/archives/${archiveId}/source`,
  4239. downloadSource3mf: async (archiveId: number): Promise<void> => {
  4240. const headers: Record<string, string> = {};
  4241. if (authToken) {
  4242. headers['Authorization'] = `Bearer ${authToken}`;
  4243. }
  4244. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, { headers });
  4245. if (!response.ok) {
  4246. const error = await response.json().catch(() => ({}));
  4247. throw new Error(error.detail || `HTTP ${response.status}`);
  4248. }
  4249. const disposition = response.headers.get('Content-Disposition');
  4250. const filename = parseContentDispositionFilename(disposition) || `source_${archiveId}.3mf`;
  4251. const blob = await response.blob();
  4252. const url = window.URL.createObjectURL(blob);
  4253. const a = document.createElement('a');
  4254. a.href = url;
  4255. a.download = filename;
  4256. document.body.appendChild(a);
  4257. a.click();
  4258. document.body.removeChild(a);
  4259. window.URL.revokeObjectURL(url);
  4260. },
  4261. getSource3mfForSlicer: (archiveId: number, filename: string) => {
  4262. // Sanitize: slicers url_decode() the entire URL, so / \ ? # in filenames break path routing
  4263. const safe = filename.replace(/[/\\?#]/g, '_');
  4264. return `${API_BASE}/archives/${archiveId}/source/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  4265. },
  4266. createSourceSlicerToken: (archiveId: number) =>
  4267. request<{ token: string }>(`/archives/${archiveId}/source-slicer-token`, { method: 'POST' }),
  4268. getSourceSlicerDownloadUrl: (archiveId: number, token: string, filename: string) => {
  4269. const safe = filename.replace(/[/\\?#]/g, '_');
  4270. return `${API_BASE}/archives/${archiveId}/source-dl/${token}/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  4271. },
  4272. uploadSource3mf: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  4273. const formData = new FormData();
  4274. formData.append('file', file);
  4275. const headers: Record<string, string> = {};
  4276. if (authToken) {
  4277. headers['Authorization'] = `Bearer ${authToken}`;
  4278. }
  4279. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, {
  4280. method: 'POST',
  4281. headers,
  4282. body: formData,
  4283. });
  4284. if (!response.ok) {
  4285. const error = await response.json().catch(() => ({}));
  4286. throw new Error(error.detail || `HTTP ${response.status}`);
  4287. }
  4288. return response.json();
  4289. },
  4290. deleteSource3mf: (archiveId: number) =>
  4291. request<{ status: string }>(`/archives/${archiveId}/source`, {
  4292. method: 'DELETE',
  4293. }),
  4294. // F3D (Fusion 360 design file)
  4295. getF3dDownloadUrl: (archiveId: number) =>
  4296. `${API_BASE}/archives/${archiveId}/f3d`,
  4297. downloadF3d: async (archiveId: number): Promise<void> => {
  4298. const headers: Record<string, string> = {};
  4299. if (authToken) {
  4300. headers['Authorization'] = `Bearer ${authToken}`;
  4301. }
  4302. const response = await fetch(`${API_BASE}/archives/${archiveId}/f3d`, { headers });
  4303. if (!response.ok) {
  4304. const error = await response.json().catch(() => ({}));
  4305. throw new Error(error.detail || `HTTP ${response.status}`);
  4306. }
  4307. const disposition = response.headers.get('Content-Disposition');
  4308. const filename = parseContentDispositionFilename(disposition) || `archive_${archiveId}.f3d`;
  4309. const blob = await response.blob();
  4310. const url = window.URL.createObjectURL(blob);
  4311. const a = document.createElement('a');
  4312. a.href = url;
  4313. a.download = filename;
  4314. document.body.appendChild(a);
  4315. a.click();
  4316. document.body.removeChild(a);
  4317. window.URL.revokeObjectURL(url);
  4318. },
  4319. uploadF3d: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  4320. const formData = new FormData();
  4321. formData.append('file', file);
  4322. const headers: Record<string, string> = {};
  4323. if (authToken) {
  4324. headers['Authorization'] = `Bearer ${authToken}`;
  4325. }
  4326. const response = await fetch(`${API_BASE}/archives/${archiveId}/f3d`, {
  4327. method: 'POST',
  4328. headers,
  4329. body: formData,
  4330. });
  4331. if (!response.ok) {
  4332. const error = await response.json().catch(() => ({}));
  4333. throw new Error(error.detail || `HTTP ${response.status}`);
  4334. }
  4335. return response.json();
  4336. },
  4337. deleteF3d: (archiveId: number) =>
  4338. request<{ status: string }>(`/archives/${archiveId}/f3d`, {
  4339. method: 'DELETE',
  4340. }),
  4341. // QR Code
  4342. getArchiveQRCodeUrl: (archiveId: number, size = 200) =>
  4343. withStreamToken(`${API_BASE}/archives/${archiveId}/qrcode?size=${size}`),
  4344. getArchiveCapabilities: (id: number) =>
  4345. request<{
  4346. has_model: boolean;
  4347. has_gcode: boolean;
  4348. has_source: boolean;
  4349. build_volume: { x: number; y: number; z: number };
  4350. filament_colors: string[];
  4351. }>(`/archives/${id}/capabilities`),
  4352. // Project Page
  4353. getArchiveProjectPage: (id: number) =>
  4354. request<{
  4355. title: string | null;
  4356. description: string | null;
  4357. designer: string | null;
  4358. designer_user_id: string | null;
  4359. license: string | null;
  4360. copyright: string | null;
  4361. creation_date: string | null;
  4362. modification_date: string | null;
  4363. origin: string | null;
  4364. profile_title: string | null;
  4365. profile_description: string | null;
  4366. profile_cover: string | null;
  4367. profile_user_id: string | null;
  4368. profile_user_name: string | null;
  4369. design_model_id: string | null;
  4370. design_profile_id: string | null;
  4371. design_region: string | null;
  4372. model_pictures: Array<{ name: string; path: string; url: string }>;
  4373. profile_pictures: Array<{ name: string; path: string; url: string }>;
  4374. thumbnails: Array<{ name: string; path: string; url: string }>;
  4375. }>(`/archives/${id}/project-page`),
  4376. updateArchiveProjectPage: (id: number, data: {
  4377. title?: string;
  4378. description?: string;
  4379. designer?: string;
  4380. license?: string;
  4381. copyright?: string;
  4382. profile_title?: string;
  4383. profile_description?: string;
  4384. }) =>
  4385. request(`/archives/${id}/project-page`, {
  4386. method: 'PATCH',
  4387. body: JSON.stringify(data),
  4388. }),
  4389. getArchiveProjectImageUrl: (archiveId: number, imagePath: string) =>
  4390. withStreamToken(`${API_BASE}/archives/${archiveId}/project-image/${encodeURIComponent(imagePath)}`),
  4391. getArchiveForSlicer: (id: number, filename: string) => {
  4392. const safe = filename.replace(/[/\\?#]/g, '_');
  4393. return `${API_BASE}/archives/${id}/file/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  4394. },
  4395. createArchiveSlicerToken: (archiveId: number) =>
  4396. request<{ token: string }>(`/archives/${archiveId}/slicer-token`, { method: 'POST' }),
  4397. getArchiveSlicerDownloadUrl: (archiveId: number, token: string, filename: string) => {
  4398. const safe = filename.replace(/[/\\?#]/g, '_');
  4399. return `${API_BASE}/archives/${archiveId}/dl/${token}/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  4400. },
  4401. getArchivePlates: (archiveId: number) =>
  4402. request<ArchivePlatesResponse>(`/archives/${archiveId}/plates`),
  4403. getArchiveFilamentRequirements: (
  4404. archiveId: number,
  4405. plateId?: number,
  4406. requestId?: string,
  4407. /** Ask for one entry per project slot instead of only the slots this
  4408. * plate consumes. The slice modal needs it: its filament list is
  4409. * positional, so a source whose only used slot is 4 must still present
  4410. * four rows or the user's pick is bound to slot 1 (#2712). Print-time
  4411. * AMS matching must NOT set this — it wants the used-only list. */
  4412. fullSlots?: boolean,
  4413. ) => {
  4414. const qs = new URLSearchParams();
  4415. if (plateId !== undefined) qs.set('plate_id', String(plateId));
  4416. if (requestId) qs.set('request_id', requestId);
  4417. if (fullSlots) qs.set('full_slots', 'true');
  4418. return request<{
  4419. archive_id: number;
  4420. filename: string;
  4421. plate_id: number | null;
  4422. filaments: Array<{
  4423. slot_id: number;
  4424. type: string;
  4425. color: string;
  4426. used_grams: number;
  4427. used_meters: number;
  4428. used_in_plate?: boolean;
  4429. }>;
  4430. }>(`/archives/${archiveId}/filament-requirements${qs.toString() ? `?${qs}` : ''}`);
  4431. },
  4432. uploadArchive: async (file: File, printerId?: number): Promise<Archive> => {
  4433. const formData = new FormData();
  4434. formData.append('file', file);
  4435. const url = printerId
  4436. ? `${API_BASE}/archives/upload?printer_id=${printerId}`
  4437. : `${API_BASE}/archives/upload`;
  4438. const headers: Record<string, string> = {};
  4439. if (authToken) {
  4440. headers['Authorization'] = `Bearer ${authToken}`;
  4441. }
  4442. const response = await fetch(url, {
  4443. method: 'POST',
  4444. headers,
  4445. body: formData,
  4446. });
  4447. if (!response.ok) {
  4448. const error = await response.json().catch(() => ({}));
  4449. throw new Error(error.detail || `HTTP ${response.status}`);
  4450. }
  4451. return response.json();
  4452. },
  4453. uploadArchivesBulk: async (files: File[], printerId?: number): Promise<BulkUploadResult> => {
  4454. const formData = new FormData();
  4455. files.forEach((file) => formData.append('files', file));
  4456. const url = printerId
  4457. ? `${API_BASE}/archives/upload-bulk?printer_id=${printerId}`
  4458. : `${API_BASE}/archives/upload-bulk`;
  4459. const headers: Record<string, string> = {};
  4460. if (authToken) {
  4461. headers['Authorization'] = `Bearer ${authToken}`;
  4462. }
  4463. const response = await fetch(url, {
  4464. method: 'POST',
  4465. headers,
  4466. body: formData,
  4467. });
  4468. if (!response.ok) {
  4469. const error = await response.json().catch(() => ({}));
  4470. throw new Error(error.detail || `HTTP ${response.status}`);
  4471. }
  4472. return response.json();
  4473. },
  4474. // Print Log
  4475. getPrintLog: (params?: {
  4476. search?: string;
  4477. printerId?: number;
  4478. username?: string;
  4479. status?: string;
  4480. dateFrom?: string;
  4481. dateTo?: string;
  4482. limit?: number;
  4483. offset?: number;
  4484. }) => {
  4485. const searchParams = new URLSearchParams();
  4486. if (params?.search) searchParams.set('search', params.search);
  4487. if (params?.printerId) searchParams.set('printer_id', String(params.printerId));
  4488. if (params?.username) searchParams.set('created_by_username', params.username);
  4489. if (params?.status) searchParams.set('status', params.status);
  4490. if (params?.dateFrom) searchParams.set('date_from', params.dateFrom);
  4491. if (params?.dateTo) searchParams.set('date_to', params.dateTo);
  4492. if (params?.limit) searchParams.set('limit', String(params.limit));
  4493. if (params?.offset !== undefined) searchParams.set('offset', String(params.offset));
  4494. return request<PrintLogResponse>(`/print-log/?${searchParams}`);
  4495. },
  4496. getPrintLogThumbnail: (id: number) => withStreamToken(`${API_BASE}/print-log/${id}/thumbnail`),
  4497. clearPrintLog: () =>
  4498. request<{ deleted: number }>('/print-log/', { method: 'DELETE' }),
  4499. deletePrintLogEntry: (id: number) =>
  4500. request<{ status: string; id: number }>(`/print-log/${id}`, { method: 'DELETE' }),
  4501. // Edit failure_reason / status on a single Print Log row (#1687 part 4).
  4502. // Distinct from updateArchive: archives describe the model, log entries
  4503. // describe a single print event. Orphan entries (no archive_id) have no
  4504. // archive to reach through and this is the only path to classify them.
  4505. updatePrintLogEntry: (
  4506. id: number,
  4507. body: { failure_reason?: string | null; status?: string },
  4508. ) =>
  4509. request<PrintLogEntry>(`/print-log/${id}`, {
  4510. method: 'PATCH',
  4511. body: JSON.stringify(body),
  4512. }),
  4513. // Settings
  4514. getSettings: () => request<AppSettings>('/settings/'),
  4515. getDefaultSidebarOrder: () => request<{ default_sidebar_order: string }>('/settings/default-sidebar-order'),
  4516. // Public subset of settings for UI rendering — no settings:read required.
  4517. // Used by pages whose users may not have SETTINGS_READ (e.g. operators with
  4518. // only printers:clear_plate). Keep in sync with _UI_PREFERENCE_FIELDS in
  4519. // backend/app/api/routes/settings.py.
  4520. getUiPreferences: () =>
  4521. request<{
  4522. require_plate_clear?: boolean;
  4523. check_printer_firmware?: boolean;
  4524. camera_view_mode?: 'window' | 'embedded';
  4525. time_format?: 'system' | '12h' | '24h';
  4526. date_format?: string;
  4527. drying_presets?: string;
  4528. ams_humidity_thresholds?: string;
  4529. ams_humidity_good?: number;
  4530. ams_humidity_fair?: number;
  4531. ams_temp_good?: number;
  4532. ams_temp_fair?: number;
  4533. bed_cooled_threshold?: number;
  4534. nozzle_temp_presets?: string;
  4535. bed_temp_presets?: string;
  4536. chamber_temp_presets?: string;
  4537. fan_speed_presets?: string;
  4538. }>('/settings/ui-preferences'),
  4539. updateSettings: (data: AppSettingsUpdate) =>
  4540. request<AppSettings>('/settings/', {
  4541. method: 'PUT',
  4542. body: JSON.stringify(data),
  4543. }),
  4544. getMQTTStatus: () => request<MQTTStatus>('/settings/mqtt/status'),
  4545. resetSettings: () =>
  4546. request<AppSettings>('/settings/reset', { method: 'POST' }),
  4547. exportBackup: async (): Promise<{ blob: Blob; filename: string }> => {
  4548. // New simplified backup - complete database + all files
  4549. const url = `${API_BASE}/settings/backup`;
  4550. const headers: Record<string, string> = {};
  4551. if (authToken) {
  4552. headers['Authorization'] = `Bearer ${authToken}`;
  4553. }
  4554. const response = await fetch(url, { headers });
  4555. // Check for errors
  4556. if (!response.ok) {
  4557. const errorText = await response.text();
  4558. throw new Error(errorText || `Backup failed with status ${response.status}`);
  4559. }
  4560. // Get filename from Content-Disposition header
  4561. const contentDisposition = response.headers.get('Content-Disposition');
  4562. let filename = 'bambuddy-backup.zip';
  4563. if (contentDisposition) {
  4564. const match = contentDisposition.match(/filename=([^;]+)/);
  4565. if (match) filename = match[1].trim().replace(/^"(.*)"$/, '$1');
  4566. }
  4567. const blob = await response.blob();
  4568. return { blob, filename };
  4569. },
  4570. importBackup: async (file: File) => {
  4571. // New simplified restore - replaces database + all directories
  4572. const formData = new FormData();
  4573. formData.append('file', file);
  4574. const url = `${API_BASE}/settings/restore`;
  4575. const headers: Record<string, string> = {};
  4576. if (authToken) {
  4577. headers['Authorization'] = `Bearer ${authToken}`;
  4578. }
  4579. const response = await fetch(url, {
  4580. method: 'POST',
  4581. headers,
  4582. body: formData,
  4583. });
  4584. return response.json() as Promise<{
  4585. success: boolean;
  4586. message: string;
  4587. }>;
  4588. },
  4589. checkFfmpeg: () =>
  4590. request<{ installed: boolean; path: string | null }>('/settings/check-ffmpeg'),
  4591. getNetworkInterfaces: () =>
  4592. request<{ interfaces: NetworkInterface[] }>('/settings/network-interfaces'),
  4593. // Cloud
  4594. getCloudStatus: () => request<CloudAuthStatus>('/cloud/status'),
  4595. cloudLogin: (email: string, password: string, region = 'global') =>
  4596. request<CloudLoginResponse>('/cloud/login', {
  4597. method: 'POST',
  4598. body: JSON.stringify({ email, password, region }),
  4599. }),
  4600. cloudVerify: (email: string, code: string, tfaKey?: string, region: string = 'global') =>
  4601. request<CloudLoginResponse>('/cloud/verify', {
  4602. method: 'POST',
  4603. body: JSON.stringify({ email, code, tfa_key: tfaKey, region }),
  4604. }),
  4605. cloudSetToken: (access_token: string, region: string = 'global') =>
  4606. request<CloudAuthStatus>('/cloud/token', {
  4607. method: 'POST',
  4608. body: JSON.stringify({ access_token, region }),
  4609. }),
  4610. cloudLogout: () =>
  4611. request<{ success: boolean }>('/cloud/logout', { method: 'POST' }),
  4612. // Orca Cloud — RFC 8628 device pairing. deviceStart() returns a short
  4613. // user_code + verification link; the user approves it in their Orca Cloud
  4614. // settings while the frontend polls devicePoll() every `interval` seconds
  4615. // until the status flips to 'complete' (or a terminal deny/expire).
  4616. orcaCloudDeviceStart: () =>
  4617. request<OrcaDeviceStartResponse>('/orca-cloud/device/start', {
  4618. method: 'POST',
  4619. }),
  4620. orcaCloudDevicePoll: () =>
  4621. request<OrcaDevicePollResponse>('/orca-cloud/device/poll', {
  4622. method: 'POST',
  4623. }),
  4624. orcaCloudStatus: () =>
  4625. request<OrcaAuthStatusResponse>('/orca-cloud/status'),
  4626. orcaCloudLogout: () =>
  4627. request<{ success: boolean }>('/orca-cloud/logout', { method: 'POST' }),
  4628. orcaCloudListProfiles: () =>
  4629. request<OrcaProfileListResponse>('/orca-cloud/profiles'),
  4630. orcaCloudGetProfile: (id: string) =>
  4631. request<OrcaProfileDetail>(`/orca-cloud/profiles/${id}`),
  4632. getCloudSettings: (version = '02.04.00.70') =>
  4633. request<SlicerSettingsResponse>(`/cloud/settings?version=${version}`),
  4634. getBuiltinFilaments: () =>
  4635. request<BuiltinFilament[]>('/cloud/builtin-filaments'),
  4636. getFilamentIdMap: () =>
  4637. request<Record<string, string>>('/cloud/filament-id-map'),
  4638. /** Material-disambiguated hex→name lookup. Same hex can map to different
  4639. * catalog names depending on material (e.g. #000000 is "Charcoal" in PLA
  4640. * Matte but "Black" in PLA Basic). The flat ``/inventory/colors/map``
  4641. * collapses these to the first hit; this endpoint preserves the material
  4642. * context. Returns ``{color_name: null}`` when the hex isn't in the
  4643. * catalog at all. #1718. */
  4644. getColorByMaterial: (hex: string, material?: string) => {
  4645. const params = new URLSearchParams({ hex });
  4646. if (material) params.set('material', material);
  4647. return request<{ color_name: string | null }>(
  4648. `/inventory/colors/by-material?${params.toString()}`,
  4649. );
  4650. },
  4651. // MakerWorld URL-paste import flow.
  4652. getMakerworldStatus: () =>
  4653. request<MakerworldStatus>('/makerworld/status'),
  4654. resolveMakerworldUrl: (url: string) =>
  4655. request<MakerworldResolvedModel>('/makerworld/resolve', {
  4656. method: 'POST',
  4657. body: JSON.stringify({ url }),
  4658. }),
  4659. getMakerworldRecentImports: (limit = 10) =>
  4660. request<MakerworldRecentImport[]>(`/makerworld/recent-imports?limit=${limit}`),
  4661. importMakerworldInstance: (
  4662. model_id: number,
  4663. instance_id: number | null,
  4664. profile_id?: number | null,
  4665. folder_id?: number | null,
  4666. ) =>
  4667. request<MakerworldImportResponse>('/makerworld/import', {
  4668. method: 'POST',
  4669. body: JSON.stringify({
  4670. model_id,
  4671. instance_id: instance_id ?? null,
  4672. profile_id: profile_id ?? null,
  4673. folder_id: folder_id ?? null,
  4674. }),
  4675. }),
  4676. getCloudSettingDetail: (settingId: string) =>
  4677. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`),
  4678. createCloudSetting: (data: SlicerSettingCreate) =>
  4679. request<SlicerSettingDetail>('/cloud/settings', {
  4680. method: 'POST',
  4681. body: JSON.stringify(data),
  4682. }),
  4683. updateCloudSetting: (settingId: string, data: SlicerSettingUpdate) =>
  4684. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`, {
  4685. method: 'PUT',
  4686. body: JSON.stringify(data),
  4687. }),
  4688. deleteCloudSetting: (settingId: string) =>
  4689. request<SlicerSettingDeleteResponse>(`/cloud/settings/${settingId}`, {
  4690. method: 'DELETE',
  4691. }),
  4692. getCloudDevices: () => request<CloudDevice[]>('/cloud/devices'),
  4693. getCloudFields: (presetType: 'filament' | 'print' | 'process' | 'printer') =>
  4694. request<FieldDefinitionsResponse>(`/cloud/fields/${presetType}`),
  4695. getAllCloudFields: () =>
  4696. request<Record<string, FieldDefinitionsResponse>>('/cloud/fields'),
  4697. getFilamentInfo: (settingIds: string[]) =>
  4698. request<Record<string, { name: string; k: number | null }>>('/cloud/filament-info', {
  4699. method: 'POST',
  4700. body: JSON.stringify(settingIds),
  4701. }),
  4702. // Smart Plugs
  4703. getSmartPlugs: () => request<SmartPlug[]>('/smart-plugs/'),
  4704. getSmartPlug: (id: number) => request<SmartPlug>(`/smart-plugs/${id}`),
  4705. getSmartPlugByPrinter: (printerId: number) => request<SmartPlug | null>(`/smart-plugs/by-printer/${printerId}`),
  4706. getScriptPlugsByPrinter: (printerId: number) => request<SmartPlug[]>(`/smart-plugs/by-printer/${printerId}/scripts`),
  4707. createSmartPlug: (data: SmartPlugCreate) =>
  4708. request<SmartPlug>('/smart-plugs/', {
  4709. method: 'POST',
  4710. body: JSON.stringify(data),
  4711. }),
  4712. updateSmartPlug: (id: number, data: SmartPlugUpdate) =>
  4713. request<SmartPlug>(`/smart-plugs/${id}`, {
  4714. method: 'PATCH',
  4715. body: JSON.stringify(data),
  4716. }),
  4717. deleteSmartPlug: (id: number) =>
  4718. request<void>(`/smart-plugs/${id}`, { method: 'DELETE' }),
  4719. controlSmartPlug: (id: number, action: 'on' | 'off' | 'toggle') =>
  4720. request<{ success: boolean; action: string }>(`/smart-plugs/${id}/control`, {
  4721. method: 'POST',
  4722. body: JSON.stringify({ action }),
  4723. }),
  4724. getSmartPlugStatus: (id: number) =>
  4725. request<SmartPlugStatus>(`/smart-plugs/${id}/status`),
  4726. testSmartPlugConnection: (ip_address: string, username?: string | null, password?: string | null) =>
  4727. request<SmartPlugTestResult>('/smart-plugs/test-connection', {
  4728. method: 'POST',
  4729. body: JSON.stringify({ ip_address, username, password }),
  4730. }),
  4731. // Tasmota Discovery (auto-detects network)
  4732. startTasmotaScan: () =>
  4733. request<TasmotaScanStatus>('/smart-plugs/discover/scan', { method: 'POST' }),
  4734. getTasmotaScanStatus: () =>
  4735. request<TasmotaScanStatus>('/smart-plugs/discover/status'),
  4736. stopTasmotaScan: () =>
  4737. request<TasmotaScanStatus>('/smart-plugs/discover/stop', { method: 'POST' }),
  4738. getDiscoveredTasmotaDevices: () =>
  4739. request<DiscoveredTasmotaDevice[]>('/smart-plugs/discover/devices'),
  4740. // Home Assistant Integration
  4741. testHAConnection: (url: string, token: string) =>
  4742. request<HATestConnectionResult>('/smart-plugs/ha/test-connection', {
  4743. method: 'POST',
  4744. body: JSON.stringify({ url, token }),
  4745. }),
  4746. getHAEntities: (search?: string) => {
  4747. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  4748. return request<HAEntity[]>(`/smart-plugs/ha/entities${params}`);
  4749. },
  4750. getHASensorEntities: () =>
  4751. request<HASensorEntity[]>('/smart-plugs/ha/sensors'),
  4752. // REST smart plug
  4753. testRESTConnection: (url: string, method: string = 'GET', headers?: string | null) =>
  4754. request<{ success: boolean; error: string | null }>('/smart-plugs/rest/test-connection', {
  4755. method: 'POST',
  4756. body: JSON.stringify({ url, method, headers }),
  4757. }),
  4758. // Print Queue
  4759. getQueue: (printerId?: number, status?: string, targetModel?: string) => {
  4760. const params = new URLSearchParams();
  4761. if (printerId) params.set('printer_id', String(printerId));
  4762. if (status) params.set('status', status);
  4763. if (targetModel) params.set('target_model', targetModel);
  4764. return request<PrintQueueItem[]>(`/queue/?${params}`);
  4765. },
  4766. getQueueItem: (id: number) => request<PrintQueueItem>(`/queue/${id}`),
  4767. addToQueue: (data: PrintQueueItemCreate) =>
  4768. request<PrintQueueItem>('/queue/', {
  4769. method: 'POST',
  4770. body: JSON.stringify(data),
  4771. }),
  4772. updateQueueItem: (id: number, data: PrintQueueItemUpdate) =>
  4773. request<PrintQueueItem>(`/queue/${id}`, {
  4774. method: 'PATCH',
  4775. body: JSON.stringify(data),
  4776. }),
  4777. removeFromQueue: (id: number) =>
  4778. request<{ message: string }>(`/queue/${id}`, { method: 'DELETE' }),
  4779. reorderQueue: (items: { id: number; position: number }[]) =>
  4780. request<{ message: string }>('/queue/reorder', {
  4781. method: 'POST',
  4782. body: JSON.stringify({ items }),
  4783. }),
  4784. cancelQueueItem: (id: number) =>
  4785. request<{ message: string }>(`/queue/${id}/cancel`, { method: 'POST' }),
  4786. stopQueueItem: (id: number) =>
  4787. request<{ message: string }>(`/queue/${id}/stop`, { method: 'POST' }),
  4788. /**
  4789. * Start a staged queue item. The backend re-checks live filament deficit
  4790. * for the assigned spool and, when short, returns 409 with a structured
  4791. * payload so the caller can confirm and retry. Pass `skipFilamentCheck`
  4792. * after the user confirms "Print Anyway" (#1496).
  4793. */
  4794. startQueueItem: (id: number, opts?: { skipFilamentCheck?: boolean }) => {
  4795. const qs = opts?.skipFilamentCheck ? '?skip_filament_check=true' : '';
  4796. return request<PrintQueueItem>(`/queue/${id}/start${qs}`, { method: 'POST' });
  4797. },
  4798. /**
  4799. * Clear the `require_previous_success` gate for a printer after the user
  4800. * resolves the failure. Acknowledges any failed/aborted predecessors and
  4801. * restores skipped items whose error_message matches the gate string
  4802. * back to pending. Returns counts so the UI can render a precise toast.
  4803. */
  4804. resumeQueueAfterFailure: (printerId: number) =>
  4805. request<{ acknowledged: number; restored: number }>(
  4806. `/queue/printer/${printerId}/resume`,
  4807. { method: 'POST' },
  4808. ),
  4809. bulkUpdateQueue: (data: PrintQueueBulkUpdate) =>
  4810. request<PrintQueueBulkUpdateResponse>('/queue/bulk', {
  4811. method: 'PATCH',
  4812. body: JSON.stringify(data),
  4813. }),
  4814. // Batches
  4815. getBatches: (status?: string) => {
  4816. const params = status ? `?status=${status}` : '';
  4817. return request<PrintBatch[]>(`/queue/batches${params}`);
  4818. },
  4819. getBatch: (id: number) => request<PrintBatch>(`/queue/batches/${id}`),
  4820. cancelBatch: (id: number) =>
  4821. request<{ message: string }>(`/queue/batches/${id}`, { method: 'DELETE' }),
  4822. createBatch: (data: PrintBatchCreate) =>
  4823. request<PrintBatch>('/queue/batches', {
  4824. method: 'POST',
  4825. body: JSON.stringify(data),
  4826. }),
  4827. ungroupBatch: (id: number) =>
  4828. request<{ ungrouped_count: number; message: string }>(
  4829. `/queue/batches/${id}/ungroup`,
  4830. { method: 'POST' },
  4831. ),
  4832. // K-Profiles
  4833. getKProfiles: (printerId: number, nozzleDiameter = '0.4') =>
  4834. request<KProfilesResponse>(`/printers/${printerId}/kprofiles/?nozzle_diameter=${nozzleDiameter}`),
  4835. setKProfile: (printerId: number, profile: KProfileCreate) =>
  4836. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/`, {
  4837. method: 'POST',
  4838. body: JSON.stringify(profile),
  4839. }),
  4840. deleteKProfile: (printerId: number, profile: KProfileDelete) =>
  4841. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/`, {
  4842. method: 'DELETE',
  4843. body: JSON.stringify(profile),
  4844. }),
  4845. setKProfilesBatch: (printerId: number, profiles: KProfileCreate[]) =>
  4846. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/batch`, {
  4847. method: 'POST',
  4848. body: JSON.stringify(profiles),
  4849. }),
  4850. // K-Profile Notes (stored locally, not on printer)
  4851. getKProfileNotes: (printerId: number) =>
  4852. request<KProfileNotesResponse>(`/printers/${printerId}/kprofiles/notes`),
  4853. setKProfileNote: (printerId: number, settingId: string, note: string) =>
  4854. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/notes`, {
  4855. method: 'PUT',
  4856. body: JSON.stringify({ setting_id: settingId, note }),
  4857. }),
  4858. deleteKProfileNote: (printerId: number, settingId: string) =>
  4859. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/notes/${encodeURIComponent(settingId)}`, {
  4860. method: 'DELETE',
  4861. }),
  4862. // Slot Preset Mappings
  4863. getSlotPresets: (printerId: number) =>
  4864. request<Record<number, SlotPresetMapping>>(`/printers/${printerId}/slot-presets`),
  4865. getSlotPreset: (printerId: number, amsId: number, trayId: number) =>
  4866. request<SlotPresetMapping | null>(`/printers/${printerId}/slot-presets/${amsId}/${trayId}`),
  4867. saveSlotPreset: (printerId: number, amsId: number, trayId: number, presetId: string, presetName: string, presetSource = 'cloud') =>
  4868. request<SlotPresetMapping>(`/printers/${printerId}/slot-presets/${amsId}/${trayId}?preset_id=${encodeURIComponent(presetId)}&preset_name=${encodeURIComponent(presetName)}&preset_source=${encodeURIComponent(presetSource)}`, {
  4869. method: 'PUT',
  4870. }),
  4871. deleteSlotPreset: (printerId: number, amsId: number, trayId: number) =>
  4872. request<{ success: boolean }>(`/printers/${printerId}/slot-presets/${amsId}/${trayId}`, {
  4873. method: 'DELETE',
  4874. }),
  4875. // AMS Labels (user-defined friendly names)
  4876. getAmsLabels: (printerId: number) =>
  4877. request<Record<number, string>>(`/printers/${printerId}/ams-labels`),
  4878. saveAmsLabel: (printerId: number, amsId: number, label: string, amsSerial = '') =>
  4879. request<{ ams_id: number; label: string }>(
  4880. `/printers/${printerId}/ams-labels/${amsId}`,
  4881. {
  4882. method: 'PUT',
  4883. body: JSON.stringify({ label, ams_serial: amsSerial }),
  4884. }
  4885. ),
  4886. deleteAmsLabel: (printerId: number, amsId: number, amsSerial = '') =>
  4887. request<{ success: boolean }>(`/printers/${printerId}/ams-labels/${amsId}?ams_serial=${encodeURIComponent(amsSerial)}`, {
  4888. method: 'DELETE',
  4889. }),
  4890. configureAmsSlot: (
  4891. printerId: number,
  4892. amsId: number,
  4893. trayId: number,
  4894. config: {
  4895. tray_info_idx: string;
  4896. tray_type: string;
  4897. tray_sub_brands: string;
  4898. tray_color: string;
  4899. nozzle_temp_min: number;
  4900. nozzle_temp_max: number;
  4901. cali_idx: number;
  4902. nozzle_diameter: string;
  4903. setting_id?: string;
  4904. kprofile_filament_id?: string;
  4905. kprofile_setting_id?: string;
  4906. k_value?: number;
  4907. }
  4908. ) => {
  4909. const params = new URLSearchParams({
  4910. tray_info_idx: config.tray_info_idx,
  4911. tray_type: config.tray_type,
  4912. tray_sub_brands: config.tray_sub_brands,
  4913. tray_color: config.tray_color,
  4914. nozzle_temp_min: config.nozzle_temp_min.toString(),
  4915. nozzle_temp_max: config.nozzle_temp_max.toString(),
  4916. cali_idx: config.cali_idx.toString(),
  4917. nozzle_diameter: config.nozzle_diameter,
  4918. });
  4919. if (config.setting_id) {
  4920. params.set('setting_id', config.setting_id);
  4921. }
  4922. if (config.kprofile_filament_id) {
  4923. params.set('kprofile_filament_id', config.kprofile_filament_id);
  4924. }
  4925. if (config.kprofile_setting_id) {
  4926. params.set('kprofile_setting_id', config.kprofile_setting_id);
  4927. }
  4928. if (config.k_value !== undefined && config.k_value > 0) {
  4929. params.set('k_value', config.k_value.toString());
  4930. }
  4931. return request<{ success: boolean; message: string }>(
  4932. `/printers/${printerId}/slots/${amsId}/${trayId}/configure?${params}`,
  4933. { method: 'POST' }
  4934. );
  4935. },
  4936. resetAmsSlot: (printerId: number, amsId: number, trayId: number) =>
  4937. request<{ success: boolean; message: string }>(
  4938. `/printers/${printerId}/ams/${amsId}/tray/${trayId}/reset`,
  4939. { method: 'POST' }
  4940. ),
  4941. // Filament Catalog (material types with cost/temp data)
  4942. listFilaments: () => request<Filament[]>('/filament-catalog/'),
  4943. getFilament: (id: number) => request<Filament>(`/filament-catalog/${id}`),
  4944. getFilamentsByType: (type: string) => request<Filament[]>(`/filament-catalog/by-type/${type}`),
  4945. // Notification Providers
  4946. getNotificationProviders: () => request<NotificationProvider[]>('/notifications/'),
  4947. getNotificationProvider: (id: number) => request<NotificationProvider>(`/notifications/${id}`),
  4948. createNotificationProvider: (data: NotificationProviderCreate) =>
  4949. request<NotificationProvider>('/notifications/', {
  4950. method: 'POST',
  4951. body: JSON.stringify(data),
  4952. }),
  4953. updateNotificationProvider: (id: number, data: NotificationProviderUpdate) =>
  4954. request<NotificationProvider>(`/notifications/${id}`, {
  4955. method: 'PATCH',
  4956. body: JSON.stringify(data),
  4957. }),
  4958. deleteNotificationProvider: (id: number) =>
  4959. request<{ message: string }>(`/notifications/${id}`, { method: 'DELETE' }),
  4960. testNotificationProvider: (id: number) =>
  4961. request<NotificationTestResponse>(`/notifications/${id}/test`, { method: 'POST' }),
  4962. testNotificationConfig: (data: NotificationTestRequest) =>
  4963. request<NotificationTestResponse>('/notifications/test-config', {
  4964. method: 'POST',
  4965. body: JSON.stringify(data),
  4966. }),
  4967. testAllNotificationProviders: () =>
  4968. request<{
  4969. tested: number;
  4970. success: number;
  4971. failed: number;
  4972. results: Array<{
  4973. provider_id: number;
  4974. provider_name: string;
  4975. provider_type: string;
  4976. success: boolean;
  4977. message: string;
  4978. }>;
  4979. }>('/notifications/test-all', { method: 'POST' }),
  4980. // Notification Templates
  4981. getNotificationTemplates: () => request<NotificationTemplate[]>('/notification-templates'),
  4982. getNotificationTemplate: (id: number) => request<NotificationTemplate>(`/notification-templates/${id}`),
  4983. updateNotificationTemplate: (id: number, data: NotificationTemplateUpdate) =>
  4984. request<NotificationTemplate>(`/notification-templates/${id}`, {
  4985. method: 'PUT',
  4986. body: JSON.stringify(data),
  4987. }),
  4988. resetNotificationTemplate: (id: number) =>
  4989. request<NotificationTemplate>(`/notification-templates/${id}/reset`, {
  4990. method: 'POST',
  4991. }),
  4992. getTemplateVariables: () => request<EventVariablesResponse[]>('/notification-templates/variables'),
  4993. previewTemplate: (data: TemplatePreviewRequest) =>
  4994. request<TemplatePreviewResponse>('/notification-templates/preview', {
  4995. method: 'POST',
  4996. body: JSON.stringify(data),
  4997. }),
  4998. // Notification Logs
  4999. getNotificationLogs: (params?: {
  5000. limit?: number;
  5001. offset?: number;
  5002. provider_id?: number;
  5003. event_type?: string;
  5004. success?: boolean;
  5005. days?: number;
  5006. }) => {
  5007. const searchParams = new URLSearchParams();
  5008. if (params?.limit) searchParams.set('limit', String(params.limit));
  5009. if (params?.offset) searchParams.set('offset', String(params.offset));
  5010. if (params?.provider_id) searchParams.set('provider_id', String(params.provider_id));
  5011. if (params?.event_type) searchParams.set('event_type', params.event_type);
  5012. if (params?.success !== undefined) searchParams.set('success', String(params.success));
  5013. if (params?.days) searchParams.set('days', String(params.days));
  5014. return request<NotificationLogEntry[]>(`/notifications/logs?${searchParams}`);
  5015. },
  5016. getNotificationLogStats: (days = 7) =>
  5017. request<NotificationLogStats>(`/notifications/logs/stats?days=${days}`),
  5018. clearNotificationLogs: (olderThanDays = 30) =>
  5019. request<{ deleted: number; message: string }>(
  5020. `/notifications/logs?older_than_days=${olderThanDays}`,
  5021. { method: 'DELETE' }
  5022. ),
  5023. // Spoolman Integration
  5024. getSpoolmanStatus: () => request<SpoolmanStatus>('/spoolman/status'),
  5025. connectSpoolman: () =>
  5026. request<{ success: boolean; message: string }>('/spoolman/connect', {
  5027. method: 'POST',
  5028. }),
  5029. disconnectSpoolman: () =>
  5030. request<{ success: boolean; message: string }>('/spoolman/disconnect', {
  5031. method: 'POST',
  5032. }),
  5033. syncPrinterAms: (printerId: number) =>
  5034. request<SpoolmanSyncResult>(`/spoolman/sync/${printerId}`, {
  5035. method: 'POST',
  5036. }),
  5037. syncAllPrintersAms: () =>
  5038. request<SpoolmanSyncResult>('/spoolman/sync-all', {
  5039. method: 'POST',
  5040. }),
  5041. getSpoolmanSpools: () =>
  5042. request<{ spools: unknown[] }>('/spoolman/spools'),
  5043. /** @deprecated Use getSpoolmanInventoryFilaments() — this endpoint has no SSRF guard */
  5044. getSpoolmanFilaments: () =>
  5045. request<{ filaments: unknown[] }>('/spoolman/filaments'),
  5046. getSpoolmanInventoryFilaments: () =>
  5047. request<SpoolmanFilamentEntry[]>('/spoolman/inventory/filaments'),
  5048. patchSpoolmanFilament: (
  5049. filamentId: number,
  5050. data: { name?: string; spool_weight?: number | null; keep_existing_spools?: boolean },
  5051. ) =>
  5052. request<SpoolmanFilamentEntry>(`/spoolman/inventory/filaments/${filamentId}`, {
  5053. method: 'PATCH',
  5054. body: JSON.stringify(data),
  5055. }),
  5056. getUnlinkedSpools: () =>
  5057. request<UnlinkedSpool[]>('/spoolman/spools/unlinked'),
  5058. getLinkedSpools: () =>
  5059. request<LinkedSpoolsMap>('/spoolman/spools/linked'),
  5060. linkSpool: (
  5061. spoolId: number,
  5062. context: {
  5063. spoolTag: string;
  5064. printerId: number;
  5065. amsId: number;
  5066. trayId: number;
  5067. }
  5068. ) =>
  5069. request<{ success: boolean; message: string }>(`/spoolman/spools/${spoolId}/link`, {
  5070. method: 'POST',
  5071. body: JSON.stringify({
  5072. spool_tag: context.spoolTag,
  5073. printer_id: context.printerId,
  5074. ams_id: context.amsId,
  5075. tray_id: context.trayId,
  5076. }),
  5077. }),
  5078. unlinkSpool: (spoolId: number) =>
  5079. request<{ success: boolean; message: string }>(`/spoolman/spools/${spoolId}/unlink`, {
  5080. method: 'POST',
  5081. }),
  5082. createSpoolmanSpoolFromSlot: (data: { printer_id: number; ams_id: number; tray_id: number }) =>
  5083. request<{ success: boolean; spool_id: number | null }>(`/spoolman/spools/from-slot`, {
  5084. method: 'POST',
  5085. body: JSON.stringify(data),
  5086. }),
  5087. createSpoolFromSlot: (data: { printer_id: number; ams_id: number; tray_id: number }) =>
  5088. request<InventorySpool>(`/inventory/spools/from-slot`, {
  5089. method: 'POST',
  5090. body: JSON.stringify(data),
  5091. }),
  5092. getSpoolmanSettings: () =>
  5093. request<{ spoolman_enabled: string; spoolman_url: string; spoolman_sync_mode: string; spoolman_disable_weight_sync: string; spoolman_report_partial_usage: string; auto_add_unknown_rfid: string; }>('/settings/spoolman'),
  5094. updateSpoolmanSettings: (data: { spoolman_enabled?: string; spoolman_url?: string; spoolman_sync_mode?: string; spoolman_disable_weight_sync?: string; spoolman_report_partial_usage?: string; auto_add_unknown_rfid?: string; }) =>
  5095. request<{ spoolman_enabled: string; spoolman_url: string; spoolman_sync_mode: string; spoolman_disable_weight_sync: string; spoolman_report_partial_usage: string; auto_add_unknown_rfid: string; }>('/settings/spoolman', {
  5096. method: 'PUT',
  5097. body: JSON.stringify(data),
  5098. }),
  5099. // Inventory
  5100. getSpools: (includeArchived = false) =>
  5101. request<InventorySpool[]>(`/inventory/spools?include_archived=${includeArchived}`),
  5102. getSpool: (id: number) => request<InventorySpool>(`/inventory/spools/${id}`),
  5103. createSpool: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>) =>
  5104. request<InventorySpool>('/inventory/spools', {
  5105. method: 'POST',
  5106. body: JSON.stringify(data),
  5107. }),
  5108. bulkCreateSpools: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>, quantity: number) =>
  5109. request<InventorySpool[]>('/inventory/spools/bulk', {
  5110. method: 'POST',
  5111. body: JSON.stringify({ spool: data, quantity }),
  5112. }),
  5113. // ── CSV import/export (#1576) ────────────────────────────────────────────
  5114. // dry_run=true → preview (no write); omitted → real import. Both share one
  5115. // multipart upload helper; see `uploadSpoolsCsv` below.
  5116. importSpoolsCsvPreview: (file: File): Promise<CsvImportPreview> => uploadSpoolsCsv<CsvImportPreview>(file, true),
  5117. importSpoolsCsv: (file: File): Promise<CsvImportResult> => uploadSpoolsCsv<CsvImportResult>(file, false),
  5118. exportSpoolsCsv: async (): Promise<void> => {
  5119. const headers: Record<string, string> = {};
  5120. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  5121. const response = await fetch(`${API_BASE}/inventory/spools/export`, { headers });
  5122. if (!response.ok) {
  5123. const error = await response.json().catch(() => ({}));
  5124. throw new Error(error.detail || `HTTP ${response.status}`);
  5125. }
  5126. const disposition = response.headers.get('Content-Disposition');
  5127. const filename = parseContentDispositionFilename(disposition) || 'bambuddy_inventory.csv';
  5128. const blob = await response.blob();
  5129. const url = window.URL.createObjectURL(blob);
  5130. const a = document.createElement('a');
  5131. a.href = url;
  5132. a.download = filename;
  5133. document.body.appendChild(a);
  5134. a.click();
  5135. document.body.removeChild(a);
  5136. window.URL.revokeObjectURL(url);
  5137. },
  5138. updateSpool: (id: number, data: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  5139. request<InventorySpool>(`/inventory/spools/${id}`, {
  5140. method: 'PATCH',
  5141. body: JSON.stringify(data),
  5142. }),
  5143. deleteSpool: (id: number) =>
  5144. request<{ status: string }>(`/inventory/spools/${id}`, { method: 'DELETE' }),
  5145. archiveSpool: (id: number) =>
  5146. request<InventorySpool>(`/inventory/spools/${id}/archive`, { method: 'POST' }),
  5147. restoreSpool: (id: number) =>
  5148. request<InventorySpool>(`/inventory/spools/${id}/restore`, { method: 'POST' }),
  5149. resetSpoolConsumedCounter: (id: number) =>
  5150. request<InventorySpool>(`/inventory/spools/${id}/reset-consumed-counter`, { method: 'POST' }),
  5151. bulkResetSpoolConsumedCounter: (spoolIds: number[]) =>
  5152. request<{ reset: number }>(`/inventory/spools/reset-consumed-counter-bulk`, {
  5153. method: 'POST',
  5154. body: JSON.stringify({ spool_ids: spoolIds }),
  5155. }),
  5156. bulkUpdateSpools: (ids: number[], update: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  5157. request<{ updated: number; not_found: number[] }>(`/inventory/spools/bulk-update`, {
  5158. method: 'POST',
  5159. body: JSON.stringify({ ids, update }),
  5160. }),
  5161. bulkDeleteSpools: (ids: number[]) =>
  5162. request<{ deleted: number; not_found: number[] }>(`/inventory/spools/bulk-delete`, {
  5163. method: 'POST',
  5164. body: JSON.stringify({ ids }),
  5165. }),
  5166. bulkArchiveSpools: (ids: number[]) =>
  5167. request<{ archived: number; already_archived: number[]; not_found: number[] }>(`/inventory/spools/bulk-archive`, {
  5168. method: 'POST',
  5169. body: JSON.stringify({ ids }),
  5170. }),
  5171. bulkRestoreSpools: (ids: number[]) =>
  5172. request<{ restored: number; already_active: number[]; not_found: number[] }>(`/inventory/spools/bulk-restore`, {
  5173. method: 'POST',
  5174. body: JSON.stringify({ ids }),
  5175. }),
  5176. getSpoolKProfiles: (spoolId: number) =>
  5177. request<SpoolKProfile[]>(`/inventory/spools/${spoolId}/k-profiles`),
  5178. saveSpoolKProfiles: (spoolId: number, profiles: SpoolKProfileInput[]) =>
  5179. request<SpoolKProfile[]>(`/inventory/spools/${spoolId}/k-profiles`, {
  5180. method: 'PUT',
  5181. body: JSON.stringify(profiles),
  5182. }),
  5183. getAssignments: (printerId?: number) =>
  5184. request<SpoolAssignment[]>(`/inventory/assignments${printerId ? `?printer_id=${printerId}` : ''}`),
  5185. assignSpool: (data: { spool_id: number; printer_id: number; ams_id: number; tray_id: number }) =>
  5186. request<SpoolAssignment>('/inventory/assignments', {
  5187. method: 'POST',
  5188. body: JSON.stringify(data),
  5189. }),
  5190. unassignSpool: (printerId: number, amsId: number, trayId: number) =>
  5191. request<{ status: string }>(`/inventory/assignments/${printerId}/${amsId}/${trayId}`, { method: 'DELETE' }),
  5192. // ── Spool label printing (#809) ──────────────────────────────────────────
  5193. // Both endpoints return application/pdf. Frontend opens the resulting Blob
  5194. // in a new tab so the user can print or save from the browser's PDF viewer.
  5195. printSpoolLabels: async (data: { spool_ids: number[]; template: SpoolLabelTemplate; monochrome?: boolean }): Promise<Blob> => {
  5196. const headers: Record<string, string> = { 'Content-Type': 'application/json' };
  5197. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  5198. const response = await fetch(`${API_BASE}/inventory/labels`, {
  5199. method: 'POST',
  5200. headers,
  5201. body: JSON.stringify(data),
  5202. });
  5203. if (!response.ok) {
  5204. const error = await response.json().catch(() => ({}));
  5205. throw new Error(error.detail || `HTTP ${response.status}`);
  5206. }
  5207. return response.blob();
  5208. },
  5209. printSpoolmanSpoolLabels: async (data: { spool_ids: number[]; template: SpoolLabelTemplate; monochrome?: boolean }): Promise<Blob> => {
  5210. const headers: Record<string, string> = { 'Content-Type': 'application/json' };
  5211. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  5212. const response = await fetch(`${API_BASE}/spoolman/labels`, {
  5213. method: 'POST',
  5214. headers,
  5215. body: JSON.stringify(data),
  5216. });
  5217. if (!response.ok) {
  5218. const error = await response.json().catch(() => ({}));
  5219. throw new Error(error.detail || `HTTP ${response.status}`);
  5220. }
  5221. return response.blob();
  5222. },
  5223. getSpoolCatalog: () =>
  5224. request<SpoolCatalogEntry[]>('/inventory/catalog'),
  5225. addCatalogEntry: (data: { name: string; weight: number }) =>
  5226. request<SpoolCatalogEntry>('/inventory/catalog', { method: 'POST', body: JSON.stringify(data) }),
  5227. updateCatalogEntry: (id: number, data: { name: string; weight: number }) =>
  5228. request<SpoolCatalogEntry>(`/inventory/catalog/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  5229. deleteCatalogEntry: (id: number) =>
  5230. request<{ status: string }>(`/inventory/catalog/${id}`, { method: 'DELETE' }),
  5231. bulkDeleteCatalogEntries: (ids: number[]) =>
  5232. request<{ deleted: number }>('/inventory/catalog/bulk-delete', { method: 'POST', body: JSON.stringify({ ids }) }),
  5233. resetSpoolCatalog: () =>
  5234. request<{ status: string }>('/inventory/catalog/reset', { method: 'POST' }),
  5235. getLocations: () =>
  5236. request<StorageLocation[]>('/inventory/locations'),
  5237. createLocation: (data: { name: string; identifier?: string | null }) =>
  5238. request<StorageLocation>('/inventory/locations', { method: 'POST', body: JSON.stringify(data) }),
  5239. updateLocation: (id: number, data: { name?: string; identifier?: string | null }) =>
  5240. request<StorageLocation>(`/inventory/locations/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  5241. deleteLocation: (id: number) =>
  5242. request<{ status: string }>(`/inventory/locations/${id}`, { method: 'DELETE' }),
  5243. getColorCatalog: () =>
  5244. request<ColorCatalogEntry[]>('/inventory/colors'),
  5245. getColorNameMap: () =>
  5246. request<{ colors: Record<string, string> }>('/inventory/colors/map'),
  5247. addColorEntry: (data: {
  5248. manufacturer: string;
  5249. color_name: string;
  5250. hex_color: string;
  5251. material: string | null;
  5252. extra_colors?: string | null;
  5253. effect_type?: string | null;
  5254. }) =>
  5255. request<ColorCatalogEntry>('/inventory/colors', { method: 'POST', body: JSON.stringify(data) }),
  5256. updateColorEntry: (
  5257. id: number,
  5258. data: {
  5259. manufacturer: string;
  5260. color_name: string;
  5261. hex_color: string;
  5262. material: string | null;
  5263. extra_colors?: string | null;
  5264. effect_type?: string | null;
  5265. },
  5266. ) => request<ColorCatalogEntry>(`/inventory/colors/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  5267. deleteColorEntry: (id: number) =>
  5268. request<{ status: string }>(`/inventory/colors/${id}`, { method: 'DELETE' }),
  5269. bulkDeleteColorEntries: (ids: number[]) =>
  5270. request<{ deleted: number }>('/inventory/colors/bulk-delete', { method: 'POST', body: JSON.stringify({ ids }) }),
  5271. resetColorCatalog: () =>
  5272. request<{ status: string }>('/inventory/colors/reset', { method: 'POST' }),
  5273. lookupColor: (manufacturer: string, colorName: string, material?: string) =>
  5274. request<ColorLookupResult>(`/inventory/colors/lookup?manufacturer=${encodeURIComponent(manufacturer)}&color_name=${encodeURIComponent(colorName)}${material ? `&material=${encodeURIComponent(material)}` : ''}`),
  5275. searchColors: (manufacturer?: string, material?: string) =>
  5276. request<ColorCatalogEntry[]>(`/inventory/colors/search?${manufacturer ? `manufacturer=${encodeURIComponent(manufacturer)}` : ''}${manufacturer && material ? '&' : ''}${material ? `material=${encodeURIComponent(material)}` : ''}`),
  5277. linkTagToSpool: (spoolId: number, data: { tag_uid?: string; tray_uuid?: string; tag_type?: string; data_origin?: string }) =>
  5278. request<InventorySpool>(`/inventory/spools/${spoolId}/link-tag`, {
  5279. method: 'PATCH',
  5280. body: JSON.stringify(data),
  5281. }),
  5282. getSpoolUsageHistory: (spoolId: number, limit = 50) =>
  5283. request<SpoolUsageRecord[]>(`/inventory/spools/${spoolId}/usage?limit=${limit}`),
  5284. getAllUsageHistory: (limit = 100, printerId?: number) =>
  5285. request<SpoolUsageRecord[]>(`/inventory/usage?limit=${limit}${printerId ? `&printer_id=${printerId}` : ''}`),
  5286. clearSpoolUsageHistory: (spoolId: number) =>
  5287. request<{ status: string }>(`/inventory/spools/${spoolId}/usage`, { method: 'DELETE' }),
  5288. syncWeightsFromAms: () =>
  5289. request<{ synced: number; skipped: number }>('/inventory/sync-ams-weights', { method: 'POST' }),
  5290. getSkuSettings: () =>
  5291. request<FilamentSkuSettings[]>('/inventory/sku-settings'),
  5292. upsertSkuSettings: (data: Omit<FilamentSkuSettings, 'id'>) =>
  5293. request<FilamentSkuSettings>('/inventory/sku-settings', {
  5294. method: 'POST',
  5295. body: JSON.stringify(data),
  5296. }),
  5297. getShoppingList: () =>
  5298. request<ShoppingListItem[]>('/inventory/shopping-list'),
  5299. addToShoppingList: (data: ShoppingListItemCreate) =>
  5300. request<ShoppingListItem>('/inventory/shopping-list', {
  5301. method: 'POST',
  5302. body: JSON.stringify(data),
  5303. }),
  5304. removeFromShoppingList: (id: number) =>
  5305. request<{ status: string }>(`/inventory/shopping-list/${id}`, { method: 'DELETE' }),
  5306. clearShoppingList: () =>
  5307. request<{ deleted: number }>('/inventory/shopping-list', { method: 'DELETE' }),
  5308. updateShoppingListStatus: (id: number, status: 'pending' | 'purchased' | 'received') =>
  5309. request<ShoppingListItem>(`/inventory/shopping-list/${id}/status`, {
  5310. method: 'PATCH',
  5311. body: JSON.stringify({ status }),
  5312. }),
  5313. getFilamentPresets: () =>
  5314. request<SlicerSetting[]>('/cloud/filaments'),
  5315. // Spoolman Inventory proxy (unified UI when Spoolman is enabled)
  5316. getSpoolmanInventorySpools: (includeArchived = false) =>
  5317. request<InventorySpool[]>(`/spoolman/inventory/spools?include_archived=${includeArchived}`),
  5318. getSpoolmanInventorySpool: (id: number) =>
  5319. request<InventorySpool>(`/spoolman/inventory/spools/${id}`),
  5320. createSpoolmanInventorySpool: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>) =>
  5321. request<InventorySpool>('/spoolman/inventory/spools', {
  5322. method: 'POST',
  5323. body: JSON.stringify(data),
  5324. }),
  5325. bulkCreateSpoolmanInventorySpools: (
  5326. data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>,
  5327. quantity: number,
  5328. ) =>
  5329. request<SpoolmanBulkCreateResult | InventorySpool[]>('/spoolman/inventory/spools/bulk', {
  5330. method: 'POST',
  5331. body: JSON.stringify({ spool: data, quantity }),
  5332. }),
  5333. updateSpoolmanInventorySpool: (
  5334. id: number,
  5335. data: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>,
  5336. ) =>
  5337. request<InventorySpool>(`/spoolman/inventory/spools/${id}`, {
  5338. method: 'PATCH',
  5339. body: JSON.stringify(data),
  5340. }),
  5341. deleteSpoolmanInventorySpool: (id: number) =>
  5342. request<{ status: string }>(`/spoolman/inventory/spools/${id}`, { method: 'DELETE' }),
  5343. archiveSpoolmanInventorySpool: (id: number) =>
  5344. request<InventorySpool>(`/spoolman/inventory/spools/${id}/archive`, { method: 'POST' }),
  5345. restoreSpoolmanInventorySpool: (id: number) =>
  5346. request<InventorySpool>(`/spoolman/inventory/spools/${id}/restore`, { method: 'POST' }),
  5347. resetSpoolmanInventorySpoolConsumedCounter: (id: number) =>
  5348. request<InventorySpool>(`/spoolman/inventory/spools/${id}/reset-consumed-counter`, { method: 'POST' }),
  5349. bulkResetSpoolmanInventorySpoolConsumedCounter: (spoolIds: number[]) =>
  5350. request<{ reset: number }>(`/spoolman/inventory/spools/reset-consumed-counter-bulk`, {
  5351. method: 'POST',
  5352. body: JSON.stringify({ spool_ids: spoolIds }),
  5353. }),
  5354. bulkUpdateSpoolmanInventorySpools: (ids: number[], update: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  5355. request<{ updated: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-update`, {
  5356. method: 'POST',
  5357. body: JSON.stringify({ ids, update }),
  5358. }),
  5359. bulkDeleteSpoolmanInventorySpools: (ids: number[]) =>
  5360. request<{ deleted: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-delete`, {
  5361. method: 'POST',
  5362. body: JSON.stringify({ ids }),
  5363. }),
  5364. bulkArchiveSpoolmanInventorySpools: (ids: number[]) =>
  5365. request<{ archived: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-archive`, {
  5366. method: 'POST',
  5367. body: JSON.stringify({ ids }),
  5368. }),
  5369. bulkRestoreSpoolmanInventorySpools: (ids: number[]) =>
  5370. request<{ restored: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-restore`, {
  5371. method: 'POST',
  5372. body: JSON.stringify({ ids }),
  5373. }),
  5374. linkTagToSpoolmanSpool: (spoolId: number, data: { tag_uid?: string; tray_uuid?: string }) =>
  5375. request<InventorySpool>(`/spoolman/inventory/spools/${spoolId}/tag`, {
  5376. method: 'PATCH',
  5377. body: JSON.stringify(data),
  5378. }),
  5379. syncSpoolmanSpoolWeight: (spoolId: number, weightGrams: number) =>
  5380. request<{ status: string; weight_used: number }>(`/spoolman/inventory/spools/${spoolId}/weight`, {
  5381. method: 'PATCH',
  5382. body: JSON.stringify({ weight_grams: weightGrams }),
  5383. }),
  5384. assignSpoolmanSlot: (data: { spoolman_spool_id: number; printer_id: number; ams_id: number; tray_id: number }) =>
  5385. request<InventorySpool>('/spoolman/inventory/slot-assignments', {
  5386. method: 'POST',
  5387. body: JSON.stringify(data),
  5388. }),
  5389. unassignSpoolmanSlot: (spoolmanSpoolId: number) =>
  5390. request<InventorySpool>(`/spoolman/inventory/slot-assignments/${spoolmanSpoolId}`, { method: 'DELETE' }),
  5391. getSpoolmanSlotAssignment: (printerId: number, amsId: number, trayId: number) =>
  5392. request<InventorySpool | null>(
  5393. `/spoolman/inventory/slot-assignments?printer_id=${printerId}&ams_id=${amsId}&tray_id=${trayId}`,
  5394. ),
  5395. getSpoolmanSlotAssignments: (printerId?: number) =>
  5396. request<Array<{
  5397. printer_id: number;
  5398. printer_name: string | null;
  5399. ams_id: number;
  5400. tray_id: number;
  5401. spoolman_spool_id: number;
  5402. ams_label: string | null;
  5403. }>>(
  5404. printerId !== undefined
  5405. ? `/spoolman/inventory/slot-assignments/all?printer_id=${printerId}`
  5406. : '/spoolman/inventory/slot-assignments/all',
  5407. ),
  5408. syncSpoolmanAmsWeights: () =>
  5409. request<{ synced: number; skipped: number }>('/spoolman/inventory/sync-ams-weights', { method: 'POST' }),
  5410. getSpoolmanKProfiles: (spoolId: number) =>
  5411. request<SpoolKProfile[]>(`/spoolman/inventory/spools/${spoolId}/k-profiles`),
  5412. saveSpoolmanKProfiles: (spoolId: number, profiles: SpoolKProfileInput[]) =>
  5413. request<SpoolKProfile[]>(`/spoolman/inventory/spools/${spoolId}/k-profiles`, {
  5414. method: 'PUT',
  5415. body: JSON.stringify(profiles),
  5416. }),
  5417. // Updates
  5418. getVersion: () => request<VersionInfo>('/updates/version'),
  5419. checkForUpdates: () => request<UpdateCheckResult>('/updates/check'),
  5420. applyUpdate: () =>
  5421. request<{ success: boolean; message: string; status?: UpdateStatus; is_docker?: boolean; is_ha_addon?: boolean; is_windows_installer?: boolean }>('/updates/apply', {
  5422. method: 'POST',
  5423. }),
  5424. getUpdateStatus: () => request<UpdateStatus>('/updates/status'),
  5425. // Maintenance
  5426. getMaintenanceTypes: () => request<MaintenanceType[]>('/maintenance/types'),
  5427. createMaintenanceType: (data: MaintenanceTypeCreate) =>
  5428. request<MaintenanceType>('/maintenance/types', {
  5429. method: 'POST',
  5430. body: JSON.stringify(data),
  5431. }),
  5432. updateMaintenanceType: (id: number, data: Partial<MaintenanceTypeCreate>) =>
  5433. request<MaintenanceType>(`/maintenance/types/${id}`, {
  5434. method: 'PATCH',
  5435. body: JSON.stringify(data),
  5436. }),
  5437. deleteMaintenanceType: (id: number) =>
  5438. request<{ status: string }>(`/maintenance/types/${id}`, { method: 'DELETE' }),
  5439. restoreDefaultMaintenanceTypes: () =>
  5440. request<{ restored: number }>(`/maintenance/types/restore-defaults`, { method: 'POST' }),
  5441. getMaintenanceOverview: () => request<PrinterMaintenanceOverview[]>('/maintenance/overview'),
  5442. getPrinterMaintenance: (printerId: number) =>
  5443. request<PrinterMaintenanceOverview>(`/maintenance/printers/${printerId}`),
  5444. updateMaintenanceItem: (itemId: number, data: { custom_interval_hours?: number | null; custom_interval_type?: 'hours' | 'days' | null; enabled?: boolean }) =>
  5445. request<MaintenanceStatus>(`/maintenance/items/${itemId}`, {
  5446. method: 'PATCH',
  5447. body: JSON.stringify(data),
  5448. }),
  5449. performMaintenance: (itemId: number, notes?: string) =>
  5450. request<MaintenanceStatus>(`/maintenance/items/${itemId}/perform`, {
  5451. method: 'POST',
  5452. body: JSON.stringify({ notes }),
  5453. }),
  5454. getMaintenanceHistory: (itemId: number) =>
  5455. request<MaintenanceHistory[]>(`/maintenance/items/${itemId}/history`),
  5456. getMaintenanceSummary: () => request<MaintenanceSummary>('/maintenance/summary'),
  5457. setPrinterHours: (printerId: number, totalHours: number) =>
  5458. request<{ printer_id: number; total_hours: number; archive_hours: number; offset_hours: number }>(
  5459. `/maintenance/printers/${printerId}/hours?total_hours=${totalHours}`,
  5460. { method: 'PATCH' }
  5461. ),
  5462. assignMaintenanceType: (printerId: number, typeId: number) =>
  5463. request<MaintenanceStatus>(`/maintenance/printers/${printerId}/assign/${typeId}`, {
  5464. method: 'POST',
  5465. }),
  5466. removeMaintenanceItem: (itemId: number) =>
  5467. request<{ status: string }>(`/maintenance/items/${itemId}`, {
  5468. method: 'DELETE',
  5469. }),
  5470. // Camera
  5471. getCameraStreamToken: () =>
  5472. request<{ token: string }>('/printers/camera/stream-token', { method: 'POST' }),
  5473. // WebSocket auth (GHSA-r2qv follow-up) — mint a short-lived token for
  5474. // the /ws connection. Browsers can't attach Authorization headers to a
  5475. // WebSocket handshake, so the token rides in the ?token= query param.
  5476. getWebSocketToken: () =>
  5477. request<{ token: string }>('/auth/ws-token', { method: 'POST' }),
  5478. // Long-lived camera tokens (#1108, #2531)
  5479. createLongLivedCameraToken: (payload: {
  5480. name: string;
  5481. expires_in_days: number;
  5482. scope?: LongLivedTokenScope;
  5483. }) =>
  5484. request<LongLivedCameraToken>('/auth/tokens', {
  5485. method: 'POST',
  5486. body: JSON.stringify({ scope: 'camera_stream', ...payload }),
  5487. }),
  5488. listMyLongLivedCameraTokens: () =>
  5489. request<LongLivedCameraToken[]>('/auth/tokens'),
  5490. listAllLongLivedCameraTokens: () =>
  5491. request<LongLivedCameraToken[]>('/auth/tokens/all'),
  5492. listLongLivedCameraTokensForUser: (userId: number) =>
  5493. request<LongLivedCameraToken[]>(`/auth/tokens?user_id=${userId}`),
  5494. revokeLongLivedCameraToken: (tokenId: number) =>
  5495. request<void>(`/auth/tokens/${tokenId}`, { method: 'DELETE' }),
  5496. // Token-authenticated Cam Wall feed (#2531). `token` is omitted only when
  5497. // auth is disabled, where the backend gate is a no-op anyway.
  5498. getCamWallPrinters: (token?: string) =>
  5499. request<CamWallPrinter[]>(
  5500. token ? `/camwall/printers?token=${encodeURIComponent(token)}` : '/camwall/printers',
  5501. ),
  5502. // Token-authenticated streaming-overlay feed (#2613). OBS (or any embed with
  5503. // no login session) loads /overlay/{id}?token=... and this backs it. `token`
  5504. // is omitted only when auth is disabled, where the backend gate is a no-op.
  5505. getOverlayStatus: (printerId: number, token?: string) =>
  5506. request<OverlayStatus>(
  5507. token
  5508. ? `/printers/${printerId}/overlay-status?token=${encodeURIComponent(token)}`
  5509. : `/printers/${printerId}/overlay-status`,
  5510. ),
  5511. getCameraStreamUrl: (printerId: number, fps = 10) =>
  5512. withStreamToken(`${API_BASE}/printers/${printerId}/camera/stream?fps=${fps}`),
  5513. getCameraSnapshotUrl: (printerId: number) =>
  5514. withStreamToken(`${API_BASE}/printers/${printerId}/camera/snapshot`),
  5515. testCameraConnection: (printerId: number) =>
  5516. request<{ success: boolean; message?: string; error?: string }>(`/printers/${printerId}/camera/test`),
  5517. getCameraStatus: (printerId: number) =>
  5518. request<{ active: boolean; stalled: boolean }>(`/printers/${printerId}/camera/status`),
  5519. diagnoseCamera: (printerId: number) =>
  5520. request<CameraDiagnoseResult>(`/printers/${printerId}/camera/diagnose`, { method: 'POST' }),
  5521. diagnosePrinter: (printerId: number) =>
  5522. request<PrinterDiagnosticResult>(`/printers/${printerId}/diagnostic`),
  5523. diagnoseConnection: (body: {
  5524. ip_address: string;
  5525. serial_number?: string;
  5526. access_code?: string;
  5527. }) =>
  5528. request<PrinterDiagnosticResult>('/printers/diagnostic', {
  5529. method: 'POST',
  5530. body: JSON.stringify(body),
  5531. }),
  5532. // Plate Detection - Multi-reference calibration (stores up to 5 references per printer)
  5533. checkPlateEmpty: (printerId: number, options?: { useExternal?: boolean; includeDebugImage?: boolean }) => {
  5534. const params = new URLSearchParams();
  5535. // Only forward use_external when the caller explicitly sets it. Omitted →
  5536. // backend derives the default from the printer's external_camera_enabled
  5537. // setting so calibration and runtime checks use the same camera (#1359).
  5538. if (options?.useExternal !== undefined) {
  5539. params.set('use_external', String(options.useExternal));
  5540. }
  5541. params.set('include_debug_image', String(options?.includeDebugImage ?? false));
  5542. return request<PlateDetectionResult>(
  5543. `/printers/${printerId}/camera/check-plate?${params.toString()}`
  5544. );
  5545. },
  5546. getPlateDetectionStatus: (printerId: number) => {
  5547. return request<PlateDetectionStatus & { chamber_light?: boolean }>(
  5548. `/printers/${printerId}/camera/plate-detection/status`
  5549. );
  5550. },
  5551. calibratePlateDetection: (printerId: number, options?: { label?: string; useExternal?: boolean }) => {
  5552. const params = new URLSearchParams();
  5553. if (options?.label) params.set('label', options.label);
  5554. if (options?.useExternal !== undefined) {
  5555. params.set('use_external', String(options.useExternal));
  5556. }
  5557. return request<CalibrationResult & { index: number }>(
  5558. `/printers/${printerId}/camera/plate-detection/calibrate?${params.toString()}`,
  5559. { method: 'POST' }
  5560. );
  5561. },
  5562. deletePlateCalibration: (printerId: number) => {
  5563. return request<CalibrationResult>(
  5564. `/printers/${printerId}/camera/plate-detection/calibrate`,
  5565. { method: 'DELETE' }
  5566. );
  5567. },
  5568. getPlateReferences: (printerId: number) => {
  5569. return request<{
  5570. references: PlateReference[];
  5571. max_references: number;
  5572. }>(`/printers/${printerId}/camera/plate-detection/references`);
  5573. },
  5574. getPlateReferenceThumbnailUrl: (printerId: number, index: number) =>
  5575. withStreamToken(`${API_BASE}/printers/${printerId}/camera/plate-detection/references/${index}/thumbnail`),
  5576. updatePlateReferenceLabel: (printerId: number, index: number, label: string) => {
  5577. const params = new URLSearchParams();
  5578. params.set('label', label);
  5579. return request<{ success: boolean; index: number; label: string }>(
  5580. `/printers/${printerId}/camera/plate-detection/references/${index}?${params.toString()}`,
  5581. { method: 'PUT' }
  5582. );
  5583. },
  5584. deletePlateReference: (printerId: number, index: number) => {
  5585. return request<{ success: boolean; message: string }>(
  5586. `/printers/${printerId}/camera/plate-detection/references/${index}`,
  5587. { method: 'DELETE' }
  5588. );
  5589. },
  5590. // External Links
  5591. getExternalLinks: () => request<ExternalLink[]>('/external-links/'),
  5592. getExternalLink: (id: number) => request<ExternalLink>(`/external-links/${id}`),
  5593. createExternalLink: (data: ExternalLinkCreate) =>
  5594. request<ExternalLink>('/external-links/', {
  5595. method: 'POST',
  5596. body: JSON.stringify(data),
  5597. }),
  5598. updateExternalLink: (id: number, data: ExternalLinkUpdate) =>
  5599. request<ExternalLink>(`/external-links/${id}`, {
  5600. method: 'PATCH',
  5601. body: JSON.stringify(data),
  5602. }),
  5603. deleteExternalLink: (id: number) =>
  5604. request<{ message: string }>(`/external-links/${id}`, { method: 'DELETE' }),
  5605. reorderExternalLinks: (ids: number[]) =>
  5606. request<ExternalLink[]>('/external-links/reorder', {
  5607. method: 'PUT',
  5608. body: JSON.stringify({ ids }),
  5609. }),
  5610. uploadExternalLinkIcon: async (id: number, file: File): Promise<ExternalLink> => {
  5611. const formData = new FormData();
  5612. formData.append('file', file);
  5613. const headers: Record<string, string> = {};
  5614. if (authToken) {
  5615. headers['Authorization'] = `Bearer ${authToken}`;
  5616. }
  5617. const response = await fetch(`${API_BASE}/external-links/${id}/icon`, {
  5618. method: 'POST',
  5619. headers,
  5620. body: formData,
  5621. });
  5622. if (!response.ok) {
  5623. const error = await response.json().catch(() => ({}));
  5624. throw new Error(error.detail || `HTTP ${response.status}`);
  5625. }
  5626. return response.json();
  5627. },
  5628. deleteExternalLinkIcon: (id: number) =>
  5629. request<ExternalLink>(`/external-links/${id}/icon`, { method: 'DELETE' }),
  5630. getExternalLinkIconUrl: (id: number) => withStreamToken(`${API_BASE}/external-links/${id}/icon`),
  5631. // Projects
  5632. getProjects: (status?: string) => {
  5633. const params = new URLSearchParams();
  5634. if (status) params.set('status', status);
  5635. return request<ProjectListItem[]>(`/projects/?${params}`);
  5636. },
  5637. getProject: (id: number) => request<Project>(`/projects/${id}`),
  5638. createProject: (data: ProjectCreate) =>
  5639. request<Project>('/projects/', {
  5640. method: 'POST',
  5641. body: JSON.stringify(data),
  5642. }),
  5643. updateProject: (id: number, data: ProjectUpdate) =>
  5644. request<Project>(`/projects/${id}`, {
  5645. method: 'PATCH',
  5646. body: JSON.stringify(data),
  5647. }),
  5648. deleteProject: (id: number) =>
  5649. request<{ message: string }>(`/projects/${id}`, { method: 'DELETE' }),
  5650. getProjectArchives: (id: number, limit = 100, offset = 0) =>
  5651. request<Archive[]>(`/projects/${id}/archives?limit=${limit}&offset=${offset}`),
  5652. // Completed-run counts per library file (#1897); files with 0 runs are omitted
  5653. getProjectFileProgress: (id: number) =>
  5654. request<ProjectFileProgress[]>(`/projects/${id}/file-progress`),
  5655. addArchivesToProject: (projectId: number, archiveIds: number[]) =>
  5656. request<{ message: string }>(`/projects/${projectId}/add-archives`, {
  5657. method: 'POST',
  5658. body: JSON.stringify({ archive_ids: archiveIds }),
  5659. }),
  5660. removeArchivesFromProject: (projectId: number, archiveIds: number[]) =>
  5661. request<{ message: string }>(`/projects/${projectId}/remove-archives`, {
  5662. method: 'POST',
  5663. body: JSON.stringify({ archive_ids: archiveIds }),
  5664. }),
  5665. addQueueItemsToProject: (projectId: number, queueItemIds: number[]) =>
  5666. request<{ message: string }>(`/projects/${projectId}/add-queue`, {
  5667. method: 'POST',
  5668. body: JSON.stringify({ queue_item_ids: queueItemIds }),
  5669. }),
  5670. // Project Attachments
  5671. uploadProjectAttachment: async (projectId: number, file: File): Promise<{
  5672. status: string;
  5673. filename: string;
  5674. original_name: string;
  5675. attachments: ProjectAttachment[];
  5676. }> => {
  5677. const formData = new FormData();
  5678. formData.append('file', file);
  5679. const headers: Record<string, string> = {};
  5680. if (authToken) {
  5681. headers['Authorization'] = `Bearer ${authToken}`;
  5682. }
  5683. const response = await fetch(`${API_BASE}/projects/${projectId}/attachments`, {
  5684. method: 'POST',
  5685. headers,
  5686. body: formData,
  5687. });
  5688. if (!response.ok) {
  5689. const error = await response.json().catch(() => ({}));
  5690. throw new Error(error.detail || `HTTP ${response.status}`);
  5691. }
  5692. return response.json();
  5693. },
  5694. getProjectAttachmentUrl: (projectId: number, filename: string) =>
  5695. `${API_BASE}/projects/${projectId}/attachments/${encodeURIComponent(filename)}`,
  5696. deleteProjectAttachment: (projectId: number, filename: string) =>
  5697. request<{ status: string; message: string; attachments: ProjectAttachment[] | null }>(
  5698. `/projects/${projectId}/attachments/${encodeURIComponent(filename)}`,
  5699. { method: 'DELETE' }
  5700. ),
  5701. // #1155: Cover image
  5702. // Browsers can't attach `Authorization: Bearer ...` to `<img src>`, so we
  5703. // append the stream-token query string the same way archive thumbnails do.
  5704. getProjectCoverImageUrl: (projectId: number) =>
  5705. withStreamToken(`${API_BASE}/projects/${projectId}/cover-image`),
  5706. uploadProjectCoverImage: async (
  5707. projectId: number,
  5708. file: File
  5709. ): Promise<{ status: string; filename: string; size: number }> => {
  5710. const formData = new FormData();
  5711. formData.append('file', file);
  5712. const headers: Record<string, string> = {};
  5713. if (authToken) {
  5714. headers['Authorization'] = `Bearer ${authToken}`;
  5715. }
  5716. const response = await fetch(`${API_BASE}/projects/${projectId}/cover-image`, {
  5717. method: 'POST',
  5718. headers,
  5719. body: formData,
  5720. });
  5721. if (!response.ok) {
  5722. const error = await response.json().catch(() => ({}));
  5723. throw new Error(error.detail || `HTTP ${response.status}`);
  5724. }
  5725. return response.json();
  5726. },
  5727. deleteProjectCoverImage: (projectId: number) =>
  5728. request<{ status: string }>(`/projects/${projectId}/cover-image`, { method: 'DELETE' }),
  5729. // BOM (Bill of Materials)
  5730. getProjectBOM: (projectId: number) =>
  5731. request<BOMItem[]>(`/projects/${projectId}/bom`),
  5732. createBOMItem: (projectId: number, data: BOMItemCreate) =>
  5733. request<BOMItem>(`/projects/${projectId}/bom`, {
  5734. method: 'POST',
  5735. body: JSON.stringify(data),
  5736. }),
  5737. updateBOMItem: (projectId: number, itemId: number, data: BOMItemUpdate) =>
  5738. request<BOMItem>(`/projects/${projectId}/bom/${itemId}`, {
  5739. method: 'PATCH',
  5740. body: JSON.stringify(data),
  5741. }),
  5742. deleteBOMItem: (projectId: number, itemId: number) =>
  5743. request<{ status: string; message: string }>(`/projects/${projectId}/bom/${itemId}`, {
  5744. method: 'DELETE',
  5745. }),
  5746. // Templates
  5747. getTemplates: () => request<ProjectListItem[]>('/projects/templates/'),
  5748. createTemplateFromProject: (projectId: number) =>
  5749. request<Project>(`/projects/${projectId}/create-template`, { method: 'POST' }),
  5750. createProjectFromTemplate: (templateId: number, name?: string) =>
  5751. request<Project>(`/projects/from-template/${templateId}${name ? `?name=${encodeURIComponent(name)}` : ''}`, {
  5752. method: 'POST',
  5753. }),
  5754. // Timeline
  5755. getProjectTimeline: (projectId: number, limit = 50) =>
  5756. request<TimelineEvent[]>(`/projects/${projectId}/timeline?limit=${limit}`),
  5757. // Project Export/Import
  5758. exportProjectJson: (projectId: number) =>
  5759. request<ProjectExport>(`/projects/${projectId}/export?format=json`),
  5760. importProject: (data: ProjectImport) =>
  5761. request<Project>('/projects/import', {
  5762. method: 'POST',
  5763. body: JSON.stringify(data),
  5764. }),
  5765. importProjectFile: async (file: File): Promise<Project> => {
  5766. const formData = new FormData();
  5767. formData.append('file', file);
  5768. const headers: Record<string, string> = {};
  5769. if (authToken) {
  5770. headers['Authorization'] = `Bearer ${authToken}`;
  5771. }
  5772. const response = await fetch(`${API_BASE}/projects/import/file`, {
  5773. method: 'POST',
  5774. headers,
  5775. body: formData,
  5776. });
  5777. if (!response.ok) {
  5778. const error = await response.json().catch(() => ({}));
  5779. throw new Error(error.detail || `HTTP ${response.status}`);
  5780. }
  5781. return response.json();
  5782. },
  5783. exportProjectZip: async (projectId: number): Promise<{ blob: Blob; filename: string }> => {
  5784. const headers: Record<string, string> = {};
  5785. if (authToken) {
  5786. headers['Authorization'] = `Bearer ${authToken}`;
  5787. }
  5788. const response = await fetch(`${API_BASE}/projects/${projectId}/export`, {
  5789. headers,
  5790. });
  5791. if (!response.ok) {
  5792. const error = await response.json().catch(() => ({}));
  5793. throw new Error(error.detail || `HTTP ${response.status}`);
  5794. }
  5795. const contentDisposition = response.headers.get('Content-Disposition');
  5796. const filename = parseContentDispositionFilename(contentDisposition) || `project_${projectId}.zip`;
  5797. const blob = await response.blob();
  5798. return { blob, filename };
  5799. },
  5800. // API Keys
  5801. getAPIKeys: () => request<APIKey[]>('/api-keys/'),
  5802. createAPIKey: (data: APIKeyCreate) =>
  5803. request<APIKeyCreateResponse>('/api-keys/', {
  5804. method: 'POST',
  5805. body: JSON.stringify(data),
  5806. }),
  5807. updateAPIKey: (id: number, data: APIKeyUpdate) =>
  5808. request<APIKey>(`/api-keys/${id}`, {
  5809. method: 'PATCH',
  5810. body: JSON.stringify(data),
  5811. }),
  5812. deleteAPIKey: (id: number) =>
  5813. request<{ message: string }>(`/api-keys/${id}`, { method: 'DELETE' }),
  5814. // AMS History
  5815. getAMSHistory: (printerId: number, amsId: number, hours = 24) =>
  5816. request<AMSHistoryResponse>(`/ams-history/${printerId}/${amsId}?hours=${hours}`),
  5817. // Printer heater (nozzle / bed / chamber) sensor history
  5818. getPrinterSensorHistory: (printerId: number, hours = 24, kinds?: string[]) => {
  5819. const params = new URLSearchParams({ hours: String(hours) });
  5820. if (kinds && kinds.length > 0) params.set('kinds', kinds.join(','));
  5821. return request<PrinterSensorHistoryResponse>(`/printer-sensor-history/${printerId}?${params.toString()}`);
  5822. },
  5823. // System Info
  5824. getSystemInfo: () => request<SystemInfo>('/system/info'),
  5825. getSystemHealth: () => request<SystemHealthResult>('/system/health'),
  5826. getStorageUsage: (options?: { refresh?: boolean }) => {
  5827. const params = new URLSearchParams();
  5828. if (options?.refresh) {
  5829. params.set('refresh', 'true');
  5830. }
  5831. const query = params.toString();
  5832. return request<StorageUsageResponse>(`/system/storage-usage${query ? `?${query}` : ''}`);
  5833. },
  5834. // Library (File Manager)
  5835. getLibraryFolders: () => request<LibraryFolderTree[]>('/library/folders'),
  5836. createLibraryFolder: (data: LibraryFolderCreate) =>
  5837. request<LibraryFolder>('/library/folders', {
  5838. method: 'POST',
  5839. body: JSON.stringify(data),
  5840. }),
  5841. updateLibraryFolder: (id: number, data: LibraryFolderUpdate) =>
  5842. request<LibraryFolder>(`/library/folders/${id}`, {
  5843. method: 'PUT',
  5844. body: JSON.stringify(data),
  5845. }),
  5846. deleteLibraryFolder: (id: number) =>
  5847. request<{ status: string; message: string }>(`/library/folders/${id}`, { method: 'DELETE' }),
  5848. createExternalFolder: (data: ExternalFolderCreate) =>
  5849. request<LibraryFolder>('/library/folders/external', {
  5850. method: 'POST',
  5851. body: JSON.stringify(data),
  5852. }),
  5853. scanExternalFolder: (folderId: number) =>
  5854. request<{ status: string; added: number; removed: number }>(`/library/folders/${folderId}/scan`, {
  5855. method: 'POST',
  5856. }),
  5857. getLibraryFoldersByProject: (projectId: number) =>
  5858. request<LibraryFolder[]>(`/library/folders/by-project/${projectId}`),
  5859. getLibraryFoldersByArchive: (archiveId: number) =>
  5860. request<LibraryFolder[]>(`/library/folders/by-archive/${archiveId}`),
  5861. getLibraryFiles: (
  5862. folderId?: number | null,
  5863. includeRoot = true,
  5864. projectId?: number,
  5865. scope?: 'internal' | 'external',
  5866. recursive = false,
  5867. tagIds: number[] = [],
  5868. ) => {
  5869. const params = new URLSearchParams();
  5870. if (folderId !== undefined && folderId !== null) {
  5871. params.set('folder_id', String(folderId));
  5872. }
  5873. if (projectId !== undefined) {
  5874. params.set('project_id', String(projectId));
  5875. }
  5876. params.set('include_root', String(includeRoot));
  5877. if (scope === 'internal') params.set('internal_only', 'true');
  5878. else if (scope === 'external') params.set('external_only', 'true');
  5879. // recursive=true expands the folder_id filter to include every descendant
  5880. // folder (#1268). Only meaningful when folder_id is set; ignored server-side
  5881. // otherwise. Off by default so non-search callers keep folder-scoped behavior.
  5882. if (recursive) params.set('recursive', 'true');
  5883. // Tag filter (#1268). Repeated ?tag_ids=N&tag_ids=M form for AND semantics
  5884. // — backend joins the association table and HAVING COUNT(DISTINCT) matches
  5885. // the array length. Tag filter intentionally bypasses folder scoping
  5886. // server-side (cross-cutting design decision).
  5887. for (const tagId of tagIds) {
  5888. params.append('tag_ids', String(tagId));
  5889. }
  5890. return request<LibraryFileListItem[]>(`/library/files?${params}`);
  5891. },
  5892. getLibraryFolderReadme: (folderId: number) =>
  5893. request<{ filename: string; content: string; truncated: boolean }>(
  5894. `/library/folders/${folderId}/readme`,
  5895. ),
  5896. // ============ Library tag catalog (#1268) ============
  5897. getLibraryTags: () =>
  5898. request<LibraryTag[]>('/library/tags'),
  5899. createLibraryTag: (name: string) =>
  5900. request<LibraryTag>('/library/tags', {
  5901. method: 'POST',
  5902. body: JSON.stringify({ name }),
  5903. }),
  5904. updateLibraryTag: (id: number, name: string) =>
  5905. request<LibraryTag>(`/library/tags/${id}`, {
  5906. method: 'PATCH',
  5907. body: JSON.stringify({ name }),
  5908. }),
  5909. deleteLibraryTag: (id: number) =>
  5910. request<void>(`/library/tags/${id}`, { method: 'DELETE' }),
  5911. bulkAssignLibraryTags: (
  5912. fileIds: number[],
  5913. tagIds: number[],
  5914. action: 'add' | 'remove' | 'replace',
  5915. ) =>
  5916. request<LibraryTagBulkAssignResult>('/library/tags/bulk-assign', {
  5917. method: 'POST',
  5918. body: JSON.stringify({ file_ids: fileIds, tag_ids: tagIds, action }),
  5919. }),
  5920. getLibraryFile: (id: number) => request<LibraryFile>(`/library/files/${id}`),
  5921. uploadLibraryFile: async (
  5922. file: File,
  5923. folderId?: number | null,
  5924. generateStlThumbnails: boolean = true
  5925. ): Promise<LibraryFileUploadResponse> => {
  5926. const formData = new FormData();
  5927. formData.append('file', file);
  5928. const params = new URLSearchParams();
  5929. if (folderId) params.set('folder_id', String(folderId));
  5930. params.set('generate_stl_thumbnails', String(generateStlThumbnails));
  5931. const headers: Record<string, string> = {};
  5932. if (authToken) {
  5933. headers['Authorization'] = `Bearer ${authToken}`;
  5934. }
  5935. const response = await fetch(`${API_BASE}/library/files?${params}`, {
  5936. method: 'POST',
  5937. headers,
  5938. body: formData,
  5939. });
  5940. if (!response.ok) {
  5941. const error = await response.json().catch(() => ({}));
  5942. throw new Error(error.detail || `HTTP ${response.status}`);
  5943. }
  5944. return response.json();
  5945. },
  5946. extractZipFile: async (
  5947. file: File,
  5948. folderId?: number | null,
  5949. preserveStructure: boolean = true,
  5950. createFolderFromZip: boolean = false,
  5951. generateStlThumbnails: boolean = true
  5952. ): Promise<ZipExtractResponse> => {
  5953. const formData = new FormData();
  5954. formData.append('file', file);
  5955. const params = new URLSearchParams();
  5956. if (folderId) params.set('folder_id', String(folderId));
  5957. params.set('preserve_structure', String(preserveStructure));
  5958. params.set('create_folder_from_zip', String(createFolderFromZip));
  5959. params.set('generate_stl_thumbnails', String(generateStlThumbnails));
  5960. const headers: Record<string, string> = {};
  5961. if (authToken) {
  5962. headers['Authorization'] = `Bearer ${authToken}`;
  5963. }
  5964. const response = await fetch(`${API_BASE}/library/files/extract-zip?${params}`, {
  5965. method: 'POST',
  5966. headers,
  5967. body: formData,
  5968. });
  5969. if (!response.ok) {
  5970. const error = await response.json().catch(() => ({}));
  5971. throw new Error(error.detail || `HTTP ${response.status}`);
  5972. }
  5973. return response.json();
  5974. },
  5975. updateLibraryFile: (id: number, data: LibraryFileUpdate) =>
  5976. request<LibraryFile>(`/library/files/${id}`, {
  5977. method: 'PUT',
  5978. body: JSON.stringify(data),
  5979. }),
  5980. deleteLibraryFile: (id: number) =>
  5981. request<{ status: string; message: string; trashed: boolean }>(`/library/files/${id}`, { method: 'DELETE' }),
  5982. // ========== Library Trash (#1008) ==========
  5983. previewLibraryPurge: (olderThanDays: number, includeNeverPrinted: boolean = true) =>
  5984. request<LibraryPurgePreview>(
  5985. `/library/purge/preview?older_than_days=${olderThanDays}&include_never_printed=${includeNeverPrinted}`,
  5986. ),
  5987. executeLibraryPurge: (olderThanDays: number, includeNeverPrinted: boolean = true) =>
  5988. request<{ moved_to_trash: number }>('/library/purge', {
  5989. method: 'POST',
  5990. body: JSON.stringify({ older_than_days: olderThanDays, include_never_printed: includeNeverPrinted }),
  5991. }),
  5992. listLibraryTrash: (limit: number = 100, offset: number = 0) =>
  5993. request<LibraryTrashListResponse>(`/library/trash?limit=${limit}&offset=${offset}`),
  5994. restoreLibraryTrash: (fileId: number) =>
  5995. request<{ status: string; id: number }>(`/library/trash/${fileId}/restore`, { method: 'POST' }),
  5996. hardDeleteLibraryTrash: (fileId: number) =>
  5997. request<{ status: string }>(`/library/trash/${fileId}`, { method: 'DELETE' }),
  5998. emptyLibraryTrash: () => request<{ deleted: number }>('/library/trash', { method: 'DELETE' }),
  5999. getLibraryTrashSettings: () =>
  6000. request<LibraryTrashSettings>('/library/trash/settings'),
  6001. updateLibraryTrashSettings: (body: LibraryTrashSettings) =>
  6002. request<LibraryTrashSettings>('/library/trash/settings', {
  6003. method: 'PUT',
  6004. body: JSON.stringify(body),
  6005. }),
  6006. getLibraryFileDownloadUrl: (id: number) => `${API_BASE}/library/files/${id}/download`,
  6007. createLibrarySlicerToken: (fileId: number) =>
  6008. request<{ token: string }>(`/library/files/${fileId}/slicer-token`, { method: 'POST' }),
  6009. getLibrarySlicerDownloadUrl: (fileId: number, token: string, filename: string) =>
  6010. `${API_BASE}/library/files/${fileId}/dl/${token}/${encodeURIComponent(buildSlicerUrlFilename(filename))}`,
  6011. downloadLibraryFile: async (id: number, filename?: string): Promise<void> => {
  6012. const headers: Record<string, string> = {};
  6013. if (authToken) {
  6014. headers['Authorization'] = `Bearer ${authToken}`;
  6015. }
  6016. const response = await fetch(`${API_BASE}/library/files/${id}/download`, { headers });
  6017. if (!response.ok) {
  6018. const error = await response.json().catch(() => ({}));
  6019. throw new Error(error.detail || `HTTP ${response.status}`);
  6020. }
  6021. const disposition = response.headers.get('Content-Disposition');
  6022. const downloadFilename = parseContentDispositionFilename(disposition) || filename || `file_${id}`;
  6023. const blob = await response.blob();
  6024. const url = window.URL.createObjectURL(blob);
  6025. const a = document.createElement('a');
  6026. a.href = url;
  6027. a.download = downloadFilename;
  6028. document.body.appendChild(a);
  6029. a.click();
  6030. document.body.removeChild(a);
  6031. window.URL.revokeObjectURL(url);
  6032. },
  6033. getLibraryFileThumbnailUrl: (id: number) => withStreamToken(`${API_BASE}/library/files/${id}/thumbnail`),
  6034. getLibraryFilePlateThumbnail: (id: number, plateIndex: number) =>
  6035. withStreamToken(`${API_BASE}/library/files/${id}/plate-thumbnail/${plateIndex}`),
  6036. getLibraryFileGcodeUrl: (id: number) => `${API_BASE}/library/files/${id}/gcode`,
  6037. moveLibraryFiles: (fileIds: number[], folderId: number | null) =>
  6038. request<{ status: string; moved: number }>('/library/files/move', {
  6039. method: 'POST',
  6040. body: JSON.stringify({ file_ids: fileIds, folder_id: folderId }),
  6041. }),
  6042. bulkDeleteLibrary: (fileIds: number[], folderIds: number[]) =>
  6043. request<{ deleted_files: number; deleted_folders: number }>('/library/bulk-delete', {
  6044. method: 'POST',
  6045. body: JSON.stringify({ file_ids: fileIds, folder_ids: folderIds }),
  6046. }),
  6047. getLibraryStats: () => request<LibraryStats>('/library/stats'),
  6048. batchGenerateStlThumbnails: (options: {
  6049. file_ids?: number[];
  6050. folder_id?: number;
  6051. all_missing?: boolean;
  6052. }) =>
  6053. request<BatchThumbnailResponse>('/library/generate-stl-thumbnails', {
  6054. method: 'POST',
  6055. body: JSON.stringify(options),
  6056. }),
  6057. addLibraryFilesToQueue: (fileIds: number[]) =>
  6058. request<AddToQueueResponse>('/library/files/add-to-queue', {
  6059. method: 'POST',
  6060. body: JSON.stringify({ file_ids: fileIds }),
  6061. }),
  6062. getLibraryFilePlates: (fileId: number) =>
  6063. request<LibraryFilePlatesResponse>(`/library/files/${fileId}/plates`),
  6064. getLibraryFileFilamentRequirements: (
  6065. fileId: number,
  6066. plateId?: number,
  6067. requestId?: string,
  6068. /** Ask for one entry per project slot instead of only the slots this
  6069. * plate consumes. The slice modal needs it: its filament list is
  6070. * positional, so a source whose only used slot is 4 must still present
  6071. * four rows or the user's pick is bound to slot 1 (#2712). Print-time
  6072. * AMS matching must NOT set this — it wants the used-only list. */
  6073. fullSlots?: boolean,
  6074. ) => {
  6075. const qs = new URLSearchParams();
  6076. if (plateId !== undefined) qs.set('plate_id', String(plateId));
  6077. if (requestId) qs.set('request_id', requestId);
  6078. if (fullSlots) qs.set('full_slots', 'true');
  6079. return request<{
  6080. file_id: number;
  6081. filename: string;
  6082. filaments: Array<{
  6083. slot_id: number;
  6084. type: string;
  6085. color: string;
  6086. used_grams: number;
  6087. used_meters: number;
  6088. used_in_plate?: boolean;
  6089. }>;
  6090. }>(`/library/files/${fileId}/filament-requirements${qs.toString() ? `?${qs}` : ''}`);
  6091. },
  6092. /** Poll the sidecar's per-request progress snapshot via the Bambuddy
  6093. * proxy. Used by the SliceModal's filament-discovery path so the inline
  6094. * spinner + persistent toast can show "Generating G-code (45%)" while
  6095. * the preview slice runs. Returns null on 404 (sidecar doesn't yet
  6096. * have an entry — early race window — or it expired) so the poller
  6097. * can keep trying. */
  6098. getPreviewSliceProgress: async (requestId: string): Promise<SliceJobProgress | null> => {
  6099. try {
  6100. return await request<SliceJobProgress>(`/slicer/preview-progress/${encodeURIComponent(requestId)}`);
  6101. } catch {
  6102. return null;
  6103. }
  6104. },
  6105. // GitHub Backup
  6106. getGitHubBackupConfig: () =>
  6107. request<GitHubBackupConfig | null>('/github-backup/config'),
  6108. getGitHubBackupCloudAccounts: () =>
  6109. request<CloudAccountCounts>('/github-backup/cloud-accounts'),
  6110. saveGitHubBackupConfig: (config: GitHubBackupConfigCreate) =>
  6111. request<GitHubBackupConfig>('/github-backup/config', {
  6112. method: 'POST',
  6113. body: JSON.stringify(config),
  6114. }),
  6115. updateGitHubBackupConfig: (config: Partial<GitHubBackupConfigCreate>) =>
  6116. request<GitHubBackupConfig>('/github-backup/config', {
  6117. method: 'PATCH',
  6118. body: JSON.stringify(config),
  6119. }),
  6120. deleteGitHubBackupConfig: () =>
  6121. request<{ message: string }>('/github-backup/config', { method: 'DELETE' }),
  6122. testGitHubConnection: (repoUrl: string, token: string, provider: GitProviderType = 'github') =>
  6123. request<GitHubTestConnectionResponse>(
  6124. `/github-backup/test?repo_url=${encodeURIComponent(repoUrl)}&token=${encodeURIComponent(token)}&provider=${encodeURIComponent(provider)}`,
  6125. { method: 'POST' }
  6126. ),
  6127. testGitHubStoredConnection: () =>
  6128. request<GitHubTestConnectionResponse>('/github-backup/test-stored', { method: 'POST' }),
  6129. triggerGitHubBackup: () =>
  6130. request<GitHubBackupTriggerResponse>('/github-backup/run', { method: 'POST' }),
  6131. getGitHubBackupStatus: () =>
  6132. request<GitHubBackupStatus>('/github-backup/status'),
  6133. getGitHubBackupLogs: (limit: number = 50) =>
  6134. request<GitHubBackupLog[]>(`/github-backup/logs?limit=${limit}`),
  6135. clearGitHubBackupLogs: (keepLast: number = 10) =>
  6136. request<{ deleted: number; message: string }>(`/github-backup/logs?keep_last=${keepLast}`, { method: 'DELETE' }),
  6137. // Scheduled local backups
  6138. getLocalBackupStatus: () =>
  6139. request<LocalBackupStatus>('/local-backup/status'),
  6140. triggerLocalBackup: () =>
  6141. request<{ success: boolean; message: string; filename?: string }>('/local-backup/run', { method: 'POST' }),
  6142. checkLocalBackupPath: () =>
  6143. request<LocalBackupPathCheck>('/local-backup/path-check'),
  6144. getLocalBackups: () =>
  6145. request<LocalBackupFile[]>('/local-backup/backups'),
  6146. downloadLocalBackup: async (filename: string): Promise<{ blob: Blob; filename: string }> => {
  6147. const response = await fetch(`${API_BASE}/local-backup/backups/${encodeURIComponent(filename)}/download`, {
  6148. headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {},
  6149. });
  6150. if (!response.ok) throw new Error('Download failed');
  6151. const blob = await response.blob();
  6152. return { blob, filename };
  6153. },
  6154. restoreLocalBackup: (filename: string) =>
  6155. request<{ success: boolean; message: string }>(`/local-backup/backups/${encodeURIComponent(filename)}/restore`, { method: 'POST' }),
  6156. deleteLocalBackup: (filename: string) =>
  6157. request<{ success: boolean; message: string }>(`/local-backup/backups/${encodeURIComponent(filename)}`, { method: 'DELETE' }),
  6158. // Obico AI failure detection
  6159. getObicoStatus: () =>
  6160. request<ObicoStatus>('/obico/status'),
  6161. getObicoPrinterStatus: () =>
  6162. request<ObicoPrinterStatus>('/obico/printer-status'),
  6163. // `token` is sent as-is, so an empty string tests with no token at all.
  6164. // Omitting the argument makes the backend fall back to the saved token.
  6165. testObicoConnection: (url: string, token?: string) =>
  6166. request<ObicoTestConnection>('/obico/test-connection', {
  6167. method: 'POST',
  6168. body: JSON.stringify(token === undefined ? { url } : { url, token }),
  6169. }),
  6170. // Slicer API — slice in the background. Both endpoints return 202 + a
  6171. // job_id; poll /slice-jobs/{id} until status is `completed` or `failed`.
  6172. sliceLibraryFile: (fileId: number, body: SliceRequest) =>
  6173. request<SliceJobEnqueueResponse>(`/library/files/${fileId}/slice`, {
  6174. method: 'POST',
  6175. body: JSON.stringify(body),
  6176. }),
  6177. sliceArchive: (archiveId: number, body: SliceRequest) =>
  6178. request<SliceJobEnqueueResponse>(`/archives/${archiveId}/slice`, {
  6179. method: 'POST',
  6180. body: JSON.stringify(body),
  6181. }),
  6182. getSliceJob: (jobId: number) =>
  6183. request<SliceJobState>(`/slice-jobs/${jobId}`),
  6184. // Unified slicer-preset listing — cloud + local + standard, deduped by name.
  6185. // Used by the SliceModal; see UnifiedPresetsResponse for the shape and
  6186. // backend/app/api/routes/slicer_presets.py for the priority rules.
  6187. // `refresh` bypasses the in-process cloud and bundled-preset caches on the
  6188. // backend; the SliceModal's Refresh button passes true so a preset deleted
  6189. // in Bambu Studio or Bambu Handy shows up without the 5-min TTL wait.
  6190. getSlicerPresets: (options?: { refresh?: boolean }) =>
  6191. request<UnifiedPresetsResponse>(
  6192. options?.refresh ? '/slicer/presets?refresh=true' : '/slicer/presets',
  6193. ),
  6194. // Slicer Pipelines (#1425) — preset bundles the SliceModal can apply in
  6195. // one click. CRUD is gated on PIPELINES_READ / PIPELINES_WRITE.
  6196. listSlicerPipelines: () =>
  6197. request<SlicerPipelinesListResponse>('/slicer-pipelines/'),
  6198. getSlicerPipeline: (id: number) =>
  6199. request<SlicerPipeline>(`/slicer-pipelines/${id}`),
  6200. createSlicerPipeline: (data: SlicerPipelineCreateRequest) =>
  6201. request<SlicerPipeline>('/slicer-pipelines/', {
  6202. method: 'POST',
  6203. body: JSON.stringify(data),
  6204. }),
  6205. updateSlicerPipeline: (id: number, data: SlicerPipelineUpdateRequest) =>
  6206. request<SlicerPipeline>(`/slicer-pipelines/${id}`, {
  6207. method: 'PUT',
  6208. body: JSON.stringify(data),
  6209. }),
  6210. deleteSlicerPipeline: (id: number) =>
  6211. request<void>(`/slicer-pipelines/${id}`, { method: 'DELETE' }),
  6212. checkPipelineEligibility: (
  6213. pipelineId: number,
  6214. source: { kind: 'libraryFile'; id: number } | { kind: 'archive'; id: number },
  6215. ) =>
  6216. request<PipelineEligibilityReport>(`/slicer-pipelines/${pipelineId}/check-eligibility`, {
  6217. method: 'POST',
  6218. body: JSON.stringify(
  6219. source.kind === 'libraryFile'
  6220. ? { source_library_file_id: source.id }
  6221. : { source_archive_id: source.id },
  6222. ),
  6223. }),
  6224. runPipeline: (
  6225. pipelineId: number,
  6226. source: { kind: 'libraryFile'; id: number } | { kind: 'archive'; id: number },
  6227. force = false,
  6228. copies = 1,
  6229. ) =>
  6230. request<PipelineRun>(`/slicer-pipelines/${pipelineId}/run`, {
  6231. method: 'POST',
  6232. body: JSON.stringify({
  6233. ...(source.kind === 'libraryFile'
  6234. ? { source_library_file_id: source.id }
  6235. : { source_archive_id: source.id }),
  6236. force,
  6237. copies,
  6238. }),
  6239. }),
  6240. listPipelineRuns: (pipelineId: number, limit = 5) =>
  6241. request<PipelineRunListResponse>(
  6242. `/slicer-pipelines/${pipelineId}/runs?limit=${limit}`,
  6243. ),
  6244. // Dashboard list across all pipelines (#1425 PR C).
  6245. listAllPipelineRuns: (params: {
  6246. limit?: number;
  6247. offset?: number;
  6248. pipelineId?: number;
  6249. status?: string;
  6250. targetPrinterId?: number;
  6251. targetModelClass?: string;
  6252. } = {}) => {
  6253. const search = new URLSearchParams();
  6254. if (params.limit) search.set('limit', String(params.limit));
  6255. if (params.offset) search.set('offset', String(params.offset));
  6256. if (params.pipelineId) search.set('pipeline_id', String(params.pipelineId));
  6257. if (params.status) search.set('status', params.status);
  6258. if (params.targetPrinterId) search.set('target_printer_id', String(params.targetPrinterId));
  6259. if (params.targetModelClass) search.set('target_model_class', params.targetModelClass);
  6260. const q = search.toString();
  6261. return request<PipelineRunListResponse>(
  6262. `/pipeline-runs${q ? '?' + q : ''}`,
  6263. );
  6264. },
  6265. // Clear terminal pipeline runs (#1425 PR C polish). Deletes all runs in
  6266. // a terminal state (completed/failed/cancelled/partial_failure); in-flight
  6267. // runs are preserved.
  6268. clearTerminalPipelineRuns: () =>
  6269. request<{ deleted: number }>('/pipeline-runs/clear', { method: 'POST' }),
  6270. getPipelineRun: (runId: number) =>
  6271. request<PipelineRun>(`/pipeline-runs/${runId}`),
  6272. cancelPipelineRun: (runId: number) =>
  6273. request<PipelineRun>(`/pipeline-runs/${runId}/cancel`, { method: 'POST' }),
  6274. retryFailedPipelineRun: (runId: number) =>
  6275. request<PipelineRun>(`/pipeline-runs/${runId}/retry-failed`, { method: 'POST' }),
  6276. // Canonical Bambu printer-model registry — "Bambu Lab <model>" → short code.
  6277. // Single source of truth shared with backend (PRINTER_MODEL_MAP); the
  6278. // SliceModal uses this to classify cloud / standard presets by their
  6279. // `@BBL <code>` suffix against the selected printer-preset name (#1325).
  6280. getSlicerPrinterModels: () =>
  6281. request<Record<string, string>>('/slicer/printer-models'),
  6282. // Local Presets (OrcaSlicer imports)
  6283. getLocalPresets: () =>
  6284. request<LocalPresetsResponse>('/local-presets/'),
  6285. getLocalPresetDetail: (id: number) =>
  6286. request<LocalPresetDetail>(`/local-presets/${id}`),
  6287. importLocalPresets: (formData: FormData) =>
  6288. fetch(`${API_BASE}/local-presets/import`, {
  6289. method: 'POST',
  6290. headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {},
  6291. body: formData,
  6292. }).then(async (res) => {
  6293. if (!res.ok) {
  6294. const err = await res.json().catch(() => ({}));
  6295. throw new Error(err.detail || `HTTP ${res.status}`);
  6296. }
  6297. return res.json() as Promise<ImportResponse>;
  6298. }),
  6299. createLocalPreset: (data: { name: string; preset_type: string; setting: Record<string, unknown> }) =>
  6300. request<LocalPreset>('/local-presets/', {
  6301. method: 'POST',
  6302. body: JSON.stringify(data),
  6303. }),
  6304. updateLocalPreset: (id: number, data: { name?: string; setting?: Record<string, unknown> }) =>
  6305. request<LocalPreset>(`/local-presets/${id}`, {
  6306. method: 'PUT',
  6307. body: JSON.stringify(data),
  6308. }),
  6309. deleteLocalPreset: (id: number) =>
  6310. request<{ success: boolean }>(`/local-presets/${id}`, { method: 'DELETE' }),
  6311. refreshBaseProfileCache: () =>
  6312. request<{ refreshed: number; failed: number; total: number }>('/local-presets/base-cache/refresh', { method: 'POST' }),
  6313. };
  6314. // AMS History types
  6315. export interface AMSHistoryPoint {
  6316. recorded_at: string;
  6317. humidity: number | null;
  6318. humidity_raw: number | null;
  6319. temperature: number | null;
  6320. }
  6321. export interface AMSHistoryResponse {
  6322. printer_id: number;
  6323. ams_id: number;
  6324. data: AMSHistoryPoint[];
  6325. min_humidity: number | null;
  6326. max_humidity: number | null;
  6327. avg_humidity: number | null;
  6328. min_temperature: number | null;
  6329. max_temperature: number | null;
  6330. avg_temperature: number | null;
  6331. }
  6332. export type HeaterSensorKind = 'nozzle' | 'nozzle_2' | 'bed' | 'chamber';
  6333. export interface HeaterHistoryPoint {
  6334. recorded_at: string;
  6335. value: number | null;
  6336. target: number | null;
  6337. }
  6338. export interface HeaterSeries {
  6339. sensor_kind: HeaterSensorKind;
  6340. data: HeaterHistoryPoint[];
  6341. min_value: number | null;
  6342. max_value: number | null;
  6343. avg_value: number | null;
  6344. }
  6345. export interface PrinterSensorHistoryResponse {
  6346. printer_id: number;
  6347. series: HeaterSeries[];
  6348. }
  6349. // System Info types
  6350. export interface SystemInfo {
  6351. app: {
  6352. version: string;
  6353. base_dir: string;
  6354. archive_dir: string;
  6355. };
  6356. database: {
  6357. engine: string;
  6358. version: string;
  6359. archives: number;
  6360. archives_completed: number;
  6361. archives_failed: number;
  6362. archives_printing: number;
  6363. printers: number;
  6364. filaments: number;
  6365. projects: number;
  6366. smart_plugs: number;
  6367. total_print_time_seconds: number;
  6368. total_print_time_formatted: string;
  6369. total_filament_grams: number;
  6370. total_filament_kg: number;
  6371. };
  6372. printers: {
  6373. total: number;
  6374. connected: number;
  6375. connected_list: Array<{
  6376. id: number;
  6377. name: string;
  6378. state: string;
  6379. model: string;
  6380. }>;
  6381. };
  6382. storage: {
  6383. archive_size_bytes: number;
  6384. archive_size_formatted: string;
  6385. database_size_bytes: number;
  6386. database_size_formatted: string;
  6387. disk_total_bytes: number;
  6388. disk_total_formatted: string;
  6389. disk_used_bytes: number;
  6390. disk_used_formatted: string;
  6391. disk_free_bytes: number;
  6392. disk_free_formatted: string;
  6393. disk_percent_used: number;
  6394. };
  6395. system: {
  6396. platform: string;
  6397. platform_release: string;
  6398. platform_version: string;
  6399. architecture: string;
  6400. hostname: string;
  6401. python_version: string;
  6402. uptime_seconds: number;
  6403. uptime_formatted: string;
  6404. boot_time: string;
  6405. };
  6406. memory: {
  6407. total_bytes: number;
  6408. total_formatted: string;
  6409. available_bytes: number;
  6410. available_formatted: string;
  6411. used_bytes: number;
  6412. used_formatted: string;
  6413. percent_used: number;
  6414. };
  6415. cpu: {
  6416. count: number;
  6417. count_logical: number;
  6418. percent: number;
  6419. };
  6420. }
  6421. export interface StorageUsageCategory {
  6422. key: string;
  6423. label: string;
  6424. bytes: number;
  6425. formatted: string;
  6426. percent_of_total: number;
  6427. }
  6428. export interface StorageUsageOtherItem {
  6429. bucket: string;
  6430. label: string;
  6431. kind: 'system' | 'data';
  6432. deletable: boolean;
  6433. bytes: number;
  6434. formatted: string;
  6435. percent_of_total: number;
  6436. }
  6437. export interface StorageUsageResponse {
  6438. roots: string[];
  6439. total_bytes: number;
  6440. total_formatted: string;
  6441. categories: StorageUsageCategory[];
  6442. other_breakdown: StorageUsageOtherItem[];
  6443. scan_errors: number;
  6444. generated_at: string;
  6445. cache: {
  6446. hit: boolean;
  6447. age_seconds: number;
  6448. max_age_seconds: number;
  6449. };
  6450. }
  6451. // Library (File Manager) types
  6452. export interface LibraryFolderTree {
  6453. id: number;
  6454. name: string;
  6455. parent_id: number | null;
  6456. project_id: number | null;
  6457. archive_id: number | null;
  6458. project_name: string | null;
  6459. archive_name: string | null;
  6460. is_external: boolean;
  6461. external_path: string | null;
  6462. external_readonly: boolean;
  6463. file_count: number;
  6464. // max(folder.updated_at, max(immediate-child file.updated_at)). Used by
  6465. // the File Manager folder tree's "sort by recent activity" mode (#1770).
  6466. latest_activity_at: string | null;
  6467. children: LibraryFolderTree[];
  6468. }
  6469. export interface LibraryFolder {
  6470. id: number;
  6471. name: string;
  6472. parent_id: number | null;
  6473. project_id: number | null;
  6474. archive_id: number | null;
  6475. project_name: string | null;
  6476. archive_name: string | null;
  6477. is_external: boolean;
  6478. external_path: string | null;
  6479. external_readonly: boolean;
  6480. external_show_hidden: boolean;
  6481. file_count: number;
  6482. latest_activity_at: string | null;
  6483. created_at: string;
  6484. updated_at: string;
  6485. }
  6486. export interface LibraryFolderCreate {
  6487. name: string;
  6488. parent_id?: number | null;
  6489. project_id?: number | null;
  6490. archive_id?: number | null;
  6491. }
  6492. export interface ExternalFolderCreate {
  6493. name: string;
  6494. external_path: string;
  6495. readonly?: boolean;
  6496. show_hidden?: boolean;
  6497. parent_id?: number | null;
  6498. }
  6499. export interface LibraryFolderUpdate {
  6500. name?: string;
  6501. parent_id?: number | null;
  6502. project_id?: number | null; // 0 to unlink
  6503. archive_id?: number | null; // 0 to unlink
  6504. }
  6505. export interface LibraryFileDuplicate {
  6506. id: number;
  6507. filename: string;
  6508. folder_id: number | null;
  6509. folder_name: string | null;
  6510. created_at: string;
  6511. }
  6512. export interface LibraryFile {
  6513. id: number;
  6514. folder_id: number | null;
  6515. folder_name: string | null;
  6516. project_id: number | null;
  6517. project_name: string | null;
  6518. is_external: boolean;
  6519. filename: string;
  6520. file_path: string;
  6521. file_type: string;
  6522. file_size: number;
  6523. file_hash: string | null;
  6524. thumbnail_path: string | null;
  6525. metadata: Record<string, unknown> | null;
  6526. print_count: number;
  6527. last_printed_at: string | null;
  6528. notes: string | null;
  6529. duplicates: LibraryFileDuplicate[] | null;
  6530. duplicate_count: number;
  6531. // User tracking (Issue #206)
  6532. created_by_id: number | null;
  6533. created_by_username: string | null;
  6534. created_at: string;
  6535. updated_at: string;
  6536. // Metadata fields
  6537. print_name: string | null;
  6538. print_time_seconds: number | null;
  6539. filament_used_grams: number | null;
  6540. sliced_for_model: string | null;
  6541. }
  6542. export interface LibraryTagSummary {
  6543. id: number;
  6544. name: string;
  6545. }
  6546. export interface LibraryFileListItem {
  6547. id: number;
  6548. folder_id: number | null;
  6549. is_external: boolean;
  6550. filename: string;
  6551. file_type: string;
  6552. file_size: number;
  6553. thumbnail_path: string | null;
  6554. print_count: number;
  6555. duplicate_count: number;
  6556. // User tracking (Issue #206)
  6557. created_by_id: number | null;
  6558. created_by_username: string | null;
  6559. created_at: string;
  6560. // Real on-disk modification time (#2680). Null for managed uploads; the date
  6561. // sort and "Modified" column use `fs_modified_at ?? created_at`.
  6562. fs_modified_at: string | null;
  6563. print_name: string | null;
  6564. print_time_seconds: number | null;
  6565. filament_used_grams: number | null;
  6566. sliced_for_model: string | null;
  6567. // Tags assigned to this file (#1268). The backend always emits an empty
  6568. // array when a file has no tags, but the field is typed optional so any
  6569. // legacy code path (or mock) that constructs a LibraryFileListItem without
  6570. // it doesn't crash the renderer. Read sites use `file.tags ?? []`.
  6571. tags?: LibraryTagSummary[];
  6572. }
  6573. // Library tag catalog (#1268)
  6574. export interface LibraryTag {
  6575. id: number;
  6576. name: string;
  6577. file_count: number;
  6578. created_at: string;
  6579. updated_at: string;
  6580. }
  6581. export interface LibraryTagBulkAssignResult {
  6582. files_updated: number;
  6583. associations_added: number;
  6584. associations_removed: number;
  6585. }
  6586. export interface LibraryFileUpdate {
  6587. filename?: string;
  6588. folder_id?: number | null;
  6589. project_id?: number | null;
  6590. notes?: string | null;
  6591. }
  6592. // Library trash (#1008)
  6593. export interface LibraryTrashItem {
  6594. id: number;
  6595. filename: string;
  6596. file_size: number;
  6597. thumbnail_path: string | null;
  6598. folder_id: number | null;
  6599. folder_name: string | null;
  6600. created_by_id: number | null;
  6601. created_by_username: string | null;
  6602. deleted_at: string;
  6603. auto_purge_at: string;
  6604. }
  6605. export interface LibraryTrashListResponse {
  6606. items: LibraryTrashItem[];
  6607. total: number;
  6608. retention_days: number;
  6609. }
  6610. export interface LibraryPurgePreview {
  6611. count: number;
  6612. total_bytes: number;
  6613. sample_filenames: string[];
  6614. older_than_days: number;
  6615. include_never_printed: boolean;
  6616. }
  6617. export interface LibraryTrashSettings {
  6618. retention_days: number;
  6619. auto_purge_enabled: boolean;
  6620. auto_purge_days: number;
  6621. auto_purge_include_never_printed: boolean;
  6622. }
  6623. export interface ArchivePurgePreview {
  6624. count: number;
  6625. total_bytes: number;
  6626. sample_filenames: string[];
  6627. older_than_days: number;
  6628. }
  6629. export interface ArchivePurgeSettings {
  6630. enabled: boolean;
  6631. days: number;
  6632. // #1390: when true, bulk-deletes the linked PrintLogEntry rows so the
  6633. // contribution drops from Quick Stats too. Default false — soft-delete,
  6634. // Quick Stats preserved.
  6635. purge_stats: boolean;
  6636. }
  6637. export interface LibraryFileUploadResponse {
  6638. id: number;
  6639. filename: string;
  6640. file_type: string;
  6641. file_size: number;
  6642. thumbnail_path: string | null;
  6643. duplicate_of: number | null;
  6644. metadata: Record<string, unknown> | null;
  6645. }
  6646. export interface LibraryStats {
  6647. total_files: number;
  6648. total_folders: number;
  6649. total_size_bytes: number;
  6650. files_by_type: Record<string, number>;
  6651. total_prints: number;
  6652. disk_free_bytes: number;
  6653. disk_total_bytes: number;
  6654. disk_used_bytes: number;
  6655. }
  6656. export interface ZipExtractResult {
  6657. filename: string;
  6658. file_id: number;
  6659. folder_id: number | null;
  6660. }
  6661. export interface ZipExtractError {
  6662. filename: string;
  6663. error: string;
  6664. }
  6665. export interface ZipExtractResponse {
  6666. extracted: number;
  6667. folders_created: number;
  6668. files: ZipExtractResult[];
  6669. errors: ZipExtractError[];
  6670. }
  6671. // STL Thumbnail Generation types
  6672. export interface BatchThumbnailResult {
  6673. file_id: number;
  6674. filename: string;
  6675. success: boolean;
  6676. error?: string | null;
  6677. }
  6678. export interface BatchThumbnailResponse {
  6679. processed: number;
  6680. succeeded: number;
  6681. failed: number;
  6682. results: BatchThumbnailResult[];
  6683. }
  6684. // Library Queue types
  6685. export interface AddToQueueResult {
  6686. file_id: number;
  6687. filename: string;
  6688. queue_item_id: number;
  6689. archive_id: number;
  6690. }
  6691. export interface AddToQueueError {
  6692. file_id: number;
  6693. filename: string;
  6694. error: string;
  6695. }
  6696. export interface AddToQueueResponse {
  6697. added: AddToQueueResult[];
  6698. errors: AddToQueueError[];
  6699. }
  6700. // Discovery types
  6701. export interface DiscoveredPrinter {
  6702. serial: string;
  6703. name: string;
  6704. ip_address: string;
  6705. model: string | null;
  6706. discovered_at: string | null;
  6707. }
  6708. export interface DiscoveryStatus {
  6709. running: boolean;
  6710. }
  6711. export interface DiscoveryInfo {
  6712. is_docker: boolean;
  6713. ssdp_running: boolean;
  6714. scan_running: boolean;
  6715. subnets: string[];
  6716. }
  6717. export interface SubnetScanStatus {
  6718. running: boolean;
  6719. scanned: number;
  6720. total: number;
  6721. }
  6722. // Discovery API
  6723. export const discoveryApi = {
  6724. getInfo: () => request<DiscoveryInfo>('/discovery/info'),
  6725. getStatus: () => request<DiscoveryStatus>('/discovery/status'),
  6726. startDiscovery: (duration: number = 10) =>
  6727. request<DiscoveryStatus>(`/discovery/start?duration=${duration}`, { method: 'POST' }),
  6728. stopDiscovery: () =>
  6729. request<DiscoveryStatus>('/discovery/stop', { method: 'POST' }),
  6730. getDiscoveredPrinters: () =>
  6731. request<DiscoveredPrinter[]>('/discovery/printers'),
  6732. // Subnet scanning (for Docker environments)
  6733. startSubnetScan: (subnet: string, timeout: number = 1.0) =>
  6734. request<SubnetScanStatus>('/discovery/scan', {
  6735. method: 'POST',
  6736. body: JSON.stringify({ subnet, timeout }),
  6737. }),
  6738. getScanStatus: () => request<SubnetScanStatus>('/discovery/scan/status'),
  6739. stopSubnetScan: () =>
  6740. request<SubnetScanStatus>('/discovery/scan/stop', { method: 'POST' }),
  6741. };
  6742. // Virtual Printer types
  6743. // Canonical wire values: `archive`, `review`, `queue`, `proxy`. The legacy
  6744. // `immediate` (→ archive) and `print_queue` (→ queue) names are still
  6745. // accepted by the backend so older API clients keep working, but new code
  6746. // should send the canonical names.
  6747. export type VirtualPrinterMode = 'archive' | 'review' | 'queue' | 'proxy' | 'immediate' | 'print_queue';
  6748. export interface VirtualPrinterProxyStatus {
  6749. running: boolean;
  6750. target_host: string;
  6751. ftp_port: number;
  6752. mqtt_port: number;
  6753. ftp_connections: number;
  6754. mqtt_connections: number;
  6755. }
  6756. export interface VirtualPrinterStatus {
  6757. enabled: boolean;
  6758. running: boolean;
  6759. mode: VirtualPrinterMode;
  6760. name: string;
  6761. serial: string;
  6762. model: string;
  6763. model_name: string;
  6764. pending_files: number;
  6765. target_printer_ip?: string; // For proxy mode
  6766. proxy?: VirtualPrinterProxyStatus; // For proxy mode
  6767. }
  6768. export interface VirtualPrinterSettings {
  6769. enabled: boolean;
  6770. access_code_set: boolean;
  6771. mode: VirtualPrinterMode;
  6772. model: string;
  6773. target_printer_id: number | null; // For proxy mode
  6774. remote_interface_ip: string | null; // For SSDP proxy across networks
  6775. tailscale_disabled: boolean;
  6776. archive_name_source: 'metadata' | 'filename'; // Source for archive's display name
  6777. status: VirtualPrinterStatus;
  6778. }
  6779. export interface NetworkInterface {
  6780. name: string;
  6781. ip: string;
  6782. netmask: string;
  6783. subnet: string;
  6784. is_alias?: boolean;
  6785. label?: string;
  6786. }
  6787. export interface VirtualPrinterModels {
  6788. models: Record<string, string>; // SSDP code -> display name
  6789. default: string;
  6790. }
  6791. export interface PendingUpload {
  6792. id: number;
  6793. filename: string;
  6794. // Resolved name the review card should show — mirrors what archive_print
  6795. // will eventually write to PrintArchive.print_name (#1152 follow-up). Falls
  6796. // back to the stripped filename stem when the 3MF has no embedded title or
  6797. // the operator has chosen the "filename" archive-name source.
  6798. display_name: string;
  6799. file_size: number;
  6800. source_ip: string | null;
  6801. status: string;
  6802. tags: string | null;
  6803. notes: string | null;
  6804. project_id: number | null;
  6805. uploaded_at: string;
  6806. }
  6807. // Virtual Printer API
  6808. export const virtualPrinterApi = {
  6809. getSettings: () => request<VirtualPrinterSettings>('/settings/virtual-printer'),
  6810. getModels: () => request<VirtualPrinterModels>('/settings/virtual-printer/models'),
  6811. updateSettings: (data: {
  6812. enabled?: boolean;
  6813. access_code?: string;
  6814. mode?: 'archive' | 'review' | 'queue' | 'proxy';
  6815. model?: string;
  6816. target_printer_id?: number;
  6817. remote_interface_ip?: string;
  6818. tailscale_disabled?: boolean;
  6819. archive_name_source?: 'metadata' | 'filename';
  6820. }) => {
  6821. const params = new URLSearchParams();
  6822. if (data.enabled !== undefined) params.set('enabled', String(data.enabled));
  6823. if (data.access_code !== undefined) params.set('access_code', data.access_code);
  6824. if (data.mode !== undefined) params.set('mode', data.mode);
  6825. if (data.model !== undefined) params.set('model', data.model);
  6826. if (data.target_printer_id !== undefined) params.set('target_printer_id', String(data.target_printer_id));
  6827. if (data.remote_interface_ip !== undefined) params.set('remote_interface_ip', data.remote_interface_ip);
  6828. if (data.tailscale_disabled !== undefined) params.set('tailscale_disabled', String(data.tailscale_disabled));
  6829. if (data.archive_name_source !== undefined) params.set('archive_name_source', data.archive_name_source);
  6830. return request<VirtualPrinterSettings>(`/settings/virtual-printer?${params.toString()}`, {
  6831. method: 'PUT',
  6832. });
  6833. },
  6834. };
  6835. // Multi Virtual Printer API
  6836. export interface VirtualPrinterConfig {
  6837. id: number;
  6838. name: string;
  6839. enabled: boolean;
  6840. mode: VirtualPrinterMode;
  6841. model: string | null;
  6842. model_name: string | null;
  6843. access_code_set: boolean;
  6844. serial: string;
  6845. target_printer_id: number | null;
  6846. auto_dispatch: boolean;
  6847. queue_force_color_match: boolean;
  6848. save_ams_mapping: boolean;
  6849. gcode_injection: boolean;
  6850. tailscale_disabled: boolean;
  6851. bind_ip: string | null;
  6852. remote_interface_ip: string | null;
  6853. position: number;
  6854. status: { running: boolean; pending_files: number; proxy?: VirtualPrinterProxyStatus };
  6855. }
  6856. export interface VirtualPrinterListResponse {
  6857. printers: VirtualPrinterConfig[];
  6858. models: Record<string, string>;
  6859. }
  6860. export const multiVirtualPrinterApi = {
  6861. list: () => request<VirtualPrinterListResponse>('/virtual-printers'),
  6862. get: (id: number) => request<VirtualPrinterConfig>(`/virtual-printers/${id}`),
  6863. create: (data: {
  6864. name?: string;
  6865. enabled?: boolean;
  6866. mode?: string;
  6867. model?: string;
  6868. access_code?: string;
  6869. target_printer_id?: number;
  6870. auto_dispatch?: boolean;
  6871. queue_force_color_match?: boolean;
  6872. save_ams_mapping?: boolean;
  6873. gcode_injection?: boolean;
  6874. bind_ip?: string;
  6875. remote_interface_ip?: string;
  6876. }) =>
  6877. request<VirtualPrinterConfig>('/virtual-printers', {
  6878. method: 'POST',
  6879. body: JSON.stringify(data),
  6880. }),
  6881. update: (id: number, data: {
  6882. name?: string;
  6883. enabled?: boolean;
  6884. mode?: string;
  6885. model?: string;
  6886. access_code?: string;
  6887. target_printer_id?: number;
  6888. auto_dispatch?: boolean;
  6889. queue_force_color_match?: boolean;
  6890. save_ams_mapping?: boolean;
  6891. gcode_injection?: boolean;
  6892. tailscale_disabled?: boolean;
  6893. bind_ip?: string;
  6894. remote_interface_ip?: string;
  6895. }) =>
  6896. request<VirtualPrinterConfig>(`/virtual-printers/${id}`, {
  6897. method: 'PUT',
  6898. body: JSON.stringify(data),
  6899. }),
  6900. remove: (id: number) =>
  6901. request<{ detail: string; id: number }>(`/virtual-printers/${id}`, {
  6902. method: 'DELETE',
  6903. }),
  6904. getTailscaleStatus: () =>
  6905. request<TailscaleStatusResponse>('/virtual-printers/tailscale-status'),
  6906. getCaCertificate: () =>
  6907. request<VPCaCertificate>('/virtual-printers/ca-certificate'),
  6908. diagnose: (id: number) =>
  6909. request<VPDiagnosticResult>(`/virtual-printers/${id}/diagnostic`),
  6910. };
  6911. /** The shared CA certificate every virtual printer presents — imported once
  6912. * into the slicer's trust store. Only the public certificate is returned. */
  6913. export interface VPCaCertificate {
  6914. pem: string;
  6915. fingerprint_sha256: string;
  6916. not_valid_after: string;
  6917. }
  6918. export type VPDiagnosticStatus = 'pass' | 'fail' | 'warn' | 'skip';
  6919. export interface VPDiagnosticCheck {
  6920. id:
  6921. | 'enabled'
  6922. | 'running'
  6923. | 'bind_interface'
  6924. | 'access_code'
  6925. | 'target_printer'
  6926. | 'port_ftps'
  6927. | 'port_mqtt'
  6928. | 'port_bind'
  6929. | 'certificate';
  6930. status: VPDiagnosticStatus;
  6931. params: Record<string, string | number>;
  6932. }
  6933. export interface VPDiagnosticResult {
  6934. vp_id: number;
  6935. vp_name: string;
  6936. mode: string;
  6937. overall: 'ok' | 'warnings' | 'problems';
  6938. checks: VPDiagnosticCheck[];
  6939. }
  6940. export interface TailscaleStatusResponse {
  6941. available: boolean;
  6942. fqdn: string;
  6943. hostname: string;
  6944. tailnet_name: string;
  6945. tailscale_ips: string[];
  6946. error: string | null;
  6947. }
  6948. // Pending Uploads API
  6949. export const pendingUploadsApi = {
  6950. list: () => request<PendingUpload[]>('/pending-uploads/'),
  6951. getCount: () => request<{ count: number }>('/pending-uploads/count'),
  6952. get: (id: number) => request<PendingUpload>(`/pending-uploads/${id}`),
  6953. archive: (id: number, data?: { tags?: string; notes?: string; project_id?: number }) =>
  6954. request<{ id: number; print_name: string; filename: string }>(`/pending-uploads/${id}/archive`, {
  6955. method: 'POST',
  6956. body: JSON.stringify(data || {}),
  6957. }),
  6958. discard: (id: number) =>
  6959. request<{ success: boolean }>(`/pending-uploads/${id}`, { method: 'DELETE' }),
  6960. archiveAll: () =>
  6961. request<{ archived: number; failed: number }>('/pending-uploads/archive-all', { method: 'POST' }),
  6962. discardAll: () =>
  6963. request<{ discarded: number }>('/pending-uploads/discard-all', { method: 'DELETE' }),
  6964. };
  6965. // Firmware API Types
  6966. export interface AvailableFirmwareVersion {
  6967. version: string;
  6968. file_available: boolean;
  6969. download_url: string | null;
  6970. release_notes: string | null;
  6971. release_time: string | null;
  6972. }
  6973. export interface FirmwareUpdateInfo {
  6974. printer_id: number;
  6975. printer_name: string;
  6976. model: string | null;
  6977. current_version: string | null;
  6978. latest_version: string | null;
  6979. update_available: boolean;
  6980. download_url: string | null;
  6981. release_notes: string | null;
  6982. available_versions: AvailableFirmwareVersion[];
  6983. }
  6984. export interface FirmwareUploadPrepare {
  6985. can_proceed: boolean;
  6986. sd_card_present: boolean;
  6987. sd_card_free_space: number;
  6988. firmware_size: number;
  6989. space_sufficient: boolean;
  6990. update_available: boolean;
  6991. current_version: string | null;
  6992. latest_version: string | null;
  6993. target_version: string | null;
  6994. firmware_filename: string | null;
  6995. errors: string[];
  6996. }
  6997. export interface FirmwareUploadStatus {
  6998. status: 'idle' | 'preparing' | 'downloading' | 'uploading' | 'complete' | 'error';
  6999. progress: number;
  7000. message: string;
  7001. error: string | null;
  7002. firmware_filename: string | null;
  7003. firmware_version: string | null;
  7004. }
  7005. // Firmware API
  7006. export const firmwareApi = {
  7007. checkUpdates: () =>
  7008. request<{ updates: FirmwareUpdateInfo[]; updates_available: number }>('/firmware/updates'),
  7009. checkPrinterUpdate: (printerId: number) =>
  7010. request<FirmwareUpdateInfo>(`/firmware/updates/${printerId}`),
  7011. prepareUpload: (printerId: number, version?: string) =>
  7012. request<FirmwareUploadPrepare>(
  7013. `/firmware/updates/${printerId}/prepare${version ? `?version=${encodeURIComponent(version)}` : ''}`,
  7014. ),
  7015. startUpload: (printerId: number, version?: string) =>
  7016. request<{ started: boolean; message: string }>(
  7017. `/firmware/updates/${printerId}/upload${version ? `?version=${encodeURIComponent(version)}` : ''}`,
  7018. { method: 'POST' },
  7019. ),
  7020. getUploadStatus: (printerId: number) =>
  7021. request<FirmwareUploadStatus>(`/firmware/updates/${printerId}/upload/status`),
  7022. };
  7023. // Support types
  7024. export interface DebugLoggingState {
  7025. enabled: boolean;
  7026. enabled_at: string | null;
  7027. duration_seconds: number | null;
  7028. }
  7029. export interface LogEntry {
  7030. timestamp: string;
  7031. level: string;
  7032. logger_name: string;
  7033. message: string;
  7034. }
  7035. export interface LogsResponse {
  7036. entries: LogEntry[];
  7037. total_in_file: number;
  7038. filtered_count: number;
  7039. }
  7040. // Support API
  7041. export const supportApi = {
  7042. getDebugLoggingState: () =>
  7043. request<DebugLoggingState>('/support/debug-logging'),
  7044. setDebugLogging: (enabled: boolean) =>
  7045. request<DebugLoggingState>('/support/debug-logging', {
  7046. method: 'POST',
  7047. body: JSON.stringify({ enabled }),
  7048. }),
  7049. downloadSupportBundle: async () => {
  7050. const headers: Record<string, string> = {};
  7051. if (authToken) {
  7052. headers['Authorization'] = `Bearer ${authToken}`;
  7053. }
  7054. const response = await fetch(`${API_BASE}/support/bundle`, { headers });
  7055. if (!response.ok) {
  7056. const error = await response.json().catch(() => ({}));
  7057. throw new Error(error.detail || `HTTP ${response.status}`);
  7058. }
  7059. // Get filename from Content-Disposition header or use default
  7060. const disposition = response.headers.get('Content-Disposition');
  7061. const filename = parseContentDispositionFilename(disposition) || 'bambuddy-support.zip';
  7062. // Download the blob
  7063. const blob = await response.blob();
  7064. const url = window.URL.createObjectURL(blob);
  7065. const a = document.createElement('a');
  7066. a.href = url;
  7067. a.download = filename;
  7068. document.body.appendChild(a);
  7069. a.click();
  7070. document.body.removeChild(a);
  7071. window.URL.revokeObjectURL(url);
  7072. },
  7073. getLogs: (params?: { limit?: number; level?: string; search?: string }) => {
  7074. const searchParams = new URLSearchParams();
  7075. if (params?.limit) searchParams.set('limit', params.limit.toString());
  7076. if (params?.level) searchParams.set('level', params.level);
  7077. if (params?.search) searchParams.set('search', params.search);
  7078. const query = searchParams.toString();
  7079. return request<LogsResponse>(`/support/logs${query ? `?${query}` : ''}`);
  7080. },
  7081. clearLogs: () =>
  7082. request<{ message: string }>('/support/logs', { method: 'DELETE' }),
  7083. };
  7084. // SpoolBuddy types
  7085. export interface SpoolBuddyDevice {
  7086. id: number;
  7087. device_id: string;
  7088. hostname: string;
  7089. ip_address: string;
  7090. backend_url?: string | null;
  7091. firmware_version: string | null;
  7092. has_nfc: boolean;
  7093. has_scale: boolean;
  7094. tare_offset: number;
  7095. calibration_factor: number;
  7096. nfc_reader_type: string | null;
  7097. nfc_connection: string | null;
  7098. display_brightness: number;
  7099. display_blank_timeout: number;
  7100. has_backlight: boolean;
  7101. last_calibrated_at: string | null;
  7102. last_seen: string | null;
  7103. pending_command: string | null;
  7104. nfc_ok: boolean;
  7105. scale_ok: boolean;
  7106. uptime_s: number;
  7107. update_status: string | null;
  7108. update_message: string | null;
  7109. system_stats: {
  7110. os?: { os?: string; kernel?: string; arch?: string; python?: string };
  7111. cpu_temp_c?: number;
  7112. cpu_count?: number;
  7113. load_avg?: number[];
  7114. memory?: { total_mb?: number; available_mb?: number; used_mb?: number; percent?: number };
  7115. disk?: { total_gb?: number; used_gb?: number; free_gb?: number; percent?: number };
  7116. system_uptime_s?: number;
  7117. } | null;
  7118. online: boolean;
  7119. }
  7120. export interface DaemonUpdateCheck {
  7121. current_version: string;
  7122. latest_version: string | null;
  7123. update_available: boolean;
  7124. }
  7125. // SpoolBuddy API
  7126. export const spoolbuddyApi = {
  7127. getDevices: () =>
  7128. request<SpoolBuddyDevice[]>('/spoolbuddy/devices'),
  7129. deleteDevice: (deviceId: string) =>
  7130. request<{ status: string; device_id: string }>(`/spoolbuddy/devices/${deviceId}`, {
  7131. method: 'DELETE',
  7132. }),
  7133. tare: (deviceId: string) =>
  7134. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/calibration/tare`, {
  7135. method: 'POST',
  7136. body: '{}',
  7137. }),
  7138. getCalibration: (deviceId: string) =>
  7139. request<{ tare_offset: number; calibration_factor: number }>(`/spoolbuddy/devices/${deviceId}/calibration`),
  7140. setCalibrationFactor: (deviceId: string, knownWeightGrams: number, rawAdc: number, tareRawAdc?: number) =>
  7141. request<{ tare_offset: number; calibration_factor: number }>(`/spoolbuddy/devices/${deviceId}/calibration/set-factor`, {
  7142. method: 'POST',
  7143. body: JSON.stringify({ known_weight_grams: knownWeightGrams, raw_adc: rawAdc, tare_raw_adc: tareRawAdc }),
  7144. }),
  7145. updateSpoolWeight: (spoolId: number, weightGrams: number) =>
  7146. request<{ status: string; weight_used: number }>('/spoolbuddy/scale/update-spool-weight', {
  7147. method: 'POST',
  7148. body: JSON.stringify({ spool_id: spoolId, weight_grams: weightGrams }),
  7149. }),
  7150. updateDisplay: (deviceId: string, brightness: number, blankTimeout: number) =>
  7151. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/display`, {
  7152. method: 'PUT',
  7153. body: JSON.stringify({ brightness, blank_timeout: blankTimeout }),
  7154. }),
  7155. updateSystemConfig: (deviceId: string, backendUrl: string, apiKey?: string) =>
  7156. request<{ status: string; message: string }>(`/spoolbuddy/devices/${deviceId}/system/config`, {
  7157. method: 'POST',
  7158. body: JSON.stringify({ backend_url: backendUrl, ...(apiKey ? { api_key: apiKey } : {}) }),
  7159. }),
  7160. checkDaemonUpdate: (deviceId: string) =>
  7161. request<DaemonUpdateCheck>(`/spoolbuddy/devices/${deviceId}/update-check`),
  7162. triggerUpdate: (deviceId: string) =>
  7163. request<{ status: string; message: string }>(`/spoolbuddy/devices/${deviceId}/update`, {
  7164. method: 'POST',
  7165. body: '{}',
  7166. }),
  7167. getSSHPublicKey: () =>
  7168. request<{ public_key: string }>('/spoolbuddy/ssh/public-key'),
  7169. writeTag: (deviceId: string, spoolId: number) =>
  7170. request<{ status: string; warnings?: string[] }>('/spoolbuddy/nfc/write-tag', {
  7171. method: 'POST',
  7172. body: JSON.stringify({ device_id: deviceId, spool_id: spoolId }),
  7173. }),
  7174. cancelWrite: (deviceId: string) =>
  7175. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/cancel-write`, {
  7176. method: 'POST',
  7177. body: '{}',
  7178. }),
  7179. systemCommand: (deviceId: string, command: 'reboot' | 'shutdown' | 'restart_daemon' | 'restart_browser') =>
  7180. request<{ status: string; command: string }>(`/spoolbuddy/devices/${deviceId}/system/command`, {
  7181. method: 'POST',
  7182. body: JSON.stringify({ command }),
  7183. }),
  7184. queueDiagnostics: (deviceId: string, type: 'nfc' | 'scale' | 'read_tag') =>
  7185. request<{ status: string; diagnostic: string; message: string }>(
  7186. `/spoolbuddy/diagnostics/${deviceId}/run?diagnostic=${type}`,
  7187. { method: 'POST', body: '{}' }
  7188. ),
  7189. getDiagnosticResult: (deviceId: string, type: 'nfc' | 'scale' | 'read_tag') =>
  7190. request<{ diagnostic: string; success: boolean; output: string; exit_code: number }>(
  7191. `/spoolbuddy/diagnostics/${deviceId}/result?diagnostic=${type}`,
  7192. { method: 'GET' }
  7193. ),
  7194. };
  7195. export interface BugReportRequest {
  7196. description: string;
  7197. email?: string;
  7198. screenshot_base64?: string;
  7199. include_support_info?: boolean;
  7200. debug_logs?: string;
  7201. }
  7202. export interface BugReportResponse {
  7203. success: boolean;
  7204. message: string;
  7205. issue_url?: string;
  7206. issue_number?: number;
  7207. }
  7208. export const bugReportApi = {
  7209. submit: (data: BugReportRequest) =>
  7210. request<BugReportResponse>('/bug-report/submit', {
  7211. method: 'POST',
  7212. body: JSON.stringify(data),
  7213. }),
  7214. startLogging: () =>
  7215. request<{ started: boolean; was_debug: boolean }>('/bug-report/start-logging', {
  7216. method: 'POST',
  7217. }),
  7218. stopLogging: (wasDebug: boolean) =>
  7219. request<{ logs: string }>(`/bug-report/stop-logging?was_debug=${wasDebug}`, {
  7220. method: 'POST',
  7221. }),
  7222. };
  7223. export interface SponsorPromptCheckResponse {
  7224. show: boolean;
  7225. milestone?: string;
  7226. family?: 'prints' | 'cost' | 'archives' | 'anniversary' | 'version-update';
  7227. threshold?: number;
  7228. payload?: Record<string, unknown>;
  7229. }
  7230. export const sponsorPromptApi = {
  7231. check: () => request<SponsorPromptCheckResponse>('/sponsor-prompt/check'),
  7232. dismiss: (milestone: string) =>
  7233. request<void>('/sponsor-prompt/dismiss', {
  7234. method: 'POST',
  7235. body: JSON.stringify({ milestone }),
  7236. }),
  7237. };