client.ts 312 KB

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