client.ts 295 KB

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