client.ts 268 KB

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