client.ts 219 KB

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