client.ts 270 KB

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