client.ts 221 KB

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