client.ts 230 KB

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