client.ts 259 KB

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