client.ts 350 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792
  1. import type { KProfileWriteResult } from '../utils/kprofileWrite';
  2. import type { BambuCatalogColor } from '../utils/colors';
  3. import type { ArchivePlatesResponse, LibraryFilePlatesResponse } from '../types/plates';
  4. import { batched, byField, byId } from './batch';
  5. const API_BASE = '/api/v1';
  6. export class ApiError extends Error {
  7. status: number;
  8. /** Stable error code from a structured backend detail (`{code, message}`).
  9. * Frontend uses this to look up an i18n key instead of showing the raw
  10. * English fallback. Null when the backend returned a plain-string detail. */
  11. code: string | null;
  12. /** Full structured detail object when the backend returned `{code, ...}`
  13. * with additional fields (e.g. the deficit list for 409s on queue
  14. * start, #1496). Null for plain-string or array-shaped details. */
  15. detail: Record<string, unknown> | null;
  16. constructor(
  17. message: string,
  18. status: number,
  19. code: string | null = null,
  20. detail: Record<string, unknown> | null = null,
  21. ) {
  22. super(message);
  23. this.name = 'ApiError';
  24. this.status = status;
  25. this.code = code;
  26. this.detail = detail;
  27. }
  28. }
  29. // Auth token storage
  30. // By default tokens are stored in sessionStorage (tab-scoped, cleared on close).
  31. // When the token originates from the ?token= URL param (kiosk bootstrap), it is
  32. // additionally persisted in localStorage so the kiosk survives page reloads.
  33. // 'persistent' also writes to localStorage so the token survives tab close
  34. // (used by Remember Me and the ?token= kiosk bootstrap).
  35. let authToken: string | null =
  36. sessionStorage.getItem('auth_token') ?? localStorage.getItem('auth_token');
  37. export type TokenPersistence = 'session' | 'persistent';
  38. export function setAuthToken(token: string | null, persistence: TokenPersistence = 'session') {
  39. authToken = token;
  40. try {
  41. if (token) {
  42. sessionStorage.setItem('auth_token', token);
  43. } else {
  44. sessionStorage.removeItem('auth_token');
  45. }
  46. } catch (err) {
  47. // Storage unavailable (quota exceeded, private mode): in-memory token still works for this tab.
  48. console.warn('setAuthToken: sessionStorage unavailable, token kept in-memory only', err);
  49. }
  50. try {
  51. if (!token) {
  52. localStorage.removeItem('auth_token');
  53. } else if (persistence === 'persistent') {
  54. localStorage.setItem('auth_token', token);
  55. }
  56. } catch (err) {
  57. console.warn('setAuthToken: localStorage operation failed', err);
  58. }
  59. }
  60. export function getAuthToken(): string | null {
  61. return authToken;
  62. }
  63. // Query-param tokens for <img>/<video> src URLs, which can't carry an
  64. // Authorization header. There are two, and which one a URL takes is decided
  65. // by what the URL points at, not by convenience:
  66. //
  67. // streamToken — live camera only. Minting one costs camera:view.
  68. // mediaToken — thumbnails, previews, timelapses, covers, icons. Minted by
  69. // any signed-in user and carries their identity, so those
  70. // routes can apply the same ownership rules as everywhere else.
  71. //
  72. // Before #3025 the stream token served both, which meant a user could not see
  73. // a library thumbnail without also being granted the live feed of the room the
  74. // printer sits in — and, because a stream token names nobody, those routes had
  75. // no identity to scope by and served any row to any holder.
  76. let streamToken: string | null = null;
  77. let mediaToken: string | null = null;
  78. export function setStreamToken(token: string | null) {
  79. streamToken = token;
  80. }
  81. export function getStreamToken(): string | null {
  82. return streamToken;
  83. }
  84. export function setMediaToken(token: string | null) {
  85. mediaToken = token;
  86. }
  87. export function getMediaToken(): string | null {
  88. return mediaToken;
  89. }
  90. /** Append the camera stream token to a URL if available (live camera only). */
  91. export function withStreamToken(url: string): string {
  92. if (!streamToken) return url;
  93. const sep = url.includes('?') ? '&' : '?';
  94. return `${url}${sep}token=${encodeURIComponent(streamToken)}`;
  95. }
  96. /** Append the media token to a URL if available (for <img>/<video> src). */
  97. export function withMediaToken(url: string): string {
  98. if (!mediaToken) return url;
  99. const sep = url.includes('?') ? '&' : '?';
  100. return `${url}${sep}token=${encodeURIComponent(mediaToken)}`;
  101. }
  102. function parseContentDispositionFilename(header: string | null): string | null {
  103. if (!header) return null;
  104. // RFC 5987: filename*=utf-8''percent-encoded-name
  105. const rfc5987Match = header.match(/filename\*=(?:UTF-8|utf-8)''(.+?)(?:;|$)/);
  106. if (rfc5987Match) {
  107. try { return decodeURIComponent(rfc5987Match[1]); } catch { /* fall through */ }
  108. }
  109. // Standard: filename="name" or filename=name
  110. const standardMatch = header.match(/filename="?([^";\n]+)"?/);
  111. return standardMatch?.[1] || null;
  112. }
  113. function buildSlicerUrlFilename(filename: string): string {
  114. const safe = filename.replace(/[/\\?#]/g, '_');
  115. return safe.toLowerCase().endsWith('.3mf') ? safe : `${safe}.3mf`;
  116. }
  117. /** POST JSON and return the response body as a Blob (label PDFs and images). */
  118. async function postForBlob(endpoint: string, data: unknown, signal?: AbortSignal): Promise<Blob> {
  119. const headers: Record<string, string> = { 'Content-Type': 'application/json' };
  120. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  121. const response = await fetch(`${API_BASE}${endpoint}`, {
  122. method: 'POST',
  123. headers,
  124. body: JSON.stringify(data),
  125. signal,
  126. });
  127. if (!response.ok) {
  128. const error = await response.json().catch(() => ({}));
  129. throw new Error(typeof error.detail === 'string' ? error.detail : `HTTP ${response.status}`);
  130. }
  131. return response.blob();
  132. }
  133. async function request<T>(
  134. endpoint: string,
  135. options: RequestInit = {}
  136. ): Promise<T> {
  137. const headers: Record<string, string> = {
  138. 'Content-Type': 'application/json',
  139. ...options.headers as Record<string, string>,
  140. };
  141. // Add auth token if available
  142. if (authToken) {
  143. headers['Authorization'] = `Bearer ${authToken}`;
  144. }
  145. const response = await fetch(`${API_BASE}${endpoint}`, {
  146. ...options,
  147. cache: 'no-store', // Prevent browser caching of API responses
  148. credentials: 'include', // Required for HttpOnly cookies (e.g. 2fa_challenge)
  149. headers,
  150. });
  151. if (!response.ok) {
  152. const error = await response.json().catch(() => ({}));
  153. const detail = error.detail;
  154. let message: string;
  155. let code: string | null = null;
  156. if (typeof detail === 'string') {
  157. message = detail;
  158. } else if (Array.isArray(detail)) {
  159. // FastAPI 422 shape: each entry has `msg` like "Value error, <real msg>".
  160. // Strip the prefix and join. Fall back to raw JSON if every entry has an
  161. // empty msg (defensive — shouldn't happen with stock Pydantic, but the
  162. // previous fallback masked the real cause as a bare "HTTP 422" toast).
  163. const joined = detail
  164. .map((e: { msg?: string }) => (e.msg ?? '').replace(/^Value error,\s*/i, ''))
  165. .filter(Boolean)
  166. .join('; ');
  167. message = joined || JSON.stringify(detail) || `HTTP ${response.status}`;
  168. } else if (detail && typeof detail === 'object') {
  169. // Structured detail `{code, message, ...}` — frontend uses the code
  170. // to pick an i18n key, message is the English fallback, any extra
  171. // fields land on ApiError.detail (e.g. `deficit` for #1496).
  172. code = typeof detail.code === 'string' ? detail.code : null;
  173. message = typeof detail.message === 'string' ? detail.message : `HTTP ${response.status}`;
  174. } else {
  175. message = `HTTP ${response.status}`;
  176. }
  177. const structuredDetail = detail && typeof detail === 'object' && !Array.isArray(detail)
  178. ? (detail as Record<string, unknown>)
  179. : null;
  180. // Handle 401 Unauthorized - only clear token if it's actually invalid
  181. // Don't clear on "Authentication required" which might be a timing issue
  182. if (response.status === 401) {
  183. const invalidTokenMessages = [
  184. 'Could not validate credentials',
  185. 'Token has expired',
  186. 'User not found or inactive',
  187. 'Invalid API key',
  188. 'API key has expired',
  189. ];
  190. if (invalidTokenMessages.some(m => message.includes(m))) {
  191. setAuthToken(null);
  192. // Notify AuthContext so the protected route guard re-evaluates and
  193. // redirects to /login on the same tab — without this, AuthContext.user
  194. // stays cached and the tab silently fails every request until a manual
  195. // refresh remounts AuthProvider (#1698, reported by @TCL987).
  196. if (typeof window !== 'undefined') {
  197. window.dispatchEvent(new CustomEvent('auth:expired'));
  198. }
  199. }
  200. }
  201. throw new ApiError(message, response.status, code, structuredDetail);
  202. }
  203. // Handle empty responses (204 No Content, etc.)
  204. const contentLength = response.headers.get('content-length');
  205. if (response.status === 204 || contentLength === '0') {
  206. return undefined as T;
  207. }
  208. return await response.json();
  209. }
  210. /** Upload a CSV to the spool import endpoint (#1576). Multipart, so it bypasses
  211. * `request<T>()` (which sends JSON): the browser must set the form-data
  212. * boundary itself. `dryRun` toggles preview-only vs. real import. */
  213. async function uploadSpoolsCsv<T>(file: File, dryRun: boolean): Promise<T> {
  214. const form = new FormData();
  215. form.append('file', file);
  216. const headers: Record<string, string> = {};
  217. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  218. const response = await fetch(`${API_BASE}/inventory/spools/import${dryRun ? '?dry_run=true' : ''}`, {
  219. method: 'POST',
  220. headers,
  221. body: form,
  222. });
  223. if (!response.ok) {
  224. const error = await response.json().catch(() => ({}));
  225. // detail may be a plain string or a structured {code, message} object
  226. // (e.g. the 413 too-large response). Surface the human message either way.
  227. const detail = error?.detail;
  228. const message = typeof detail === 'string' ? detail : detail?.message;
  229. throw new Error(message || `HTTP ${response.status}`);
  230. }
  231. return response.json();
  232. }
  233. // Camera diagnostic result (#1395 follow-up). Returned by
  234. // POST /printers/{id}/camera/diagnose; the frontend modal renders one
  235. // row per stage and looks up the summary code in i18n for the user-
  236. // facing remediation hint.
  237. export interface CameraDiagnoseStage {
  238. name: 'tcp_reachable' | 'first_frame' | 'live_stream_active';
  239. status: 'ok' | 'failed' | 'skipped';
  240. duration_ms: number;
  241. code: string | null;
  242. }
  243. export interface CameraDiagnoseResult {
  244. printer_id: number;
  245. protocol: 'rtsp' | 'chamber_image';
  246. port: number;
  247. // 'default' = historical X1/H2 tuning. Anything else = this model has
  248. // an override entry in backend/app/services/camera_profiles.py.
  249. profile: string;
  250. overall_status: 'ok' | 'failed';
  251. stages: CameraDiagnoseStage[];
  252. // i18n key under `camera.diagnose.summary.*`.
  253. summary_code: string;
  254. }
  255. // Connection diagnostic (GET /printers/{id}/diagnostic and
  256. // POST /printers/diagnostic). Each check's `id` + `status` resolve a
  257. // localized title/fix under `diagnostic.check.*`; `params` interpolate it.
  258. export type DiagnosticStatus = 'pass' | 'fail' | 'warn' | 'skip';
  259. export interface DiagnosticCheck {
  260. id:
  261. | 'port_mqtt'
  262. | 'port_ftps'
  263. | 'port_rtsps'
  264. | 'network_mode'
  265. | 'subnet'
  266. | 'mqtt_auth'
  267. | 'developer_mode';
  268. status: DiagnosticStatus;
  269. params: Record<string, string | number>;
  270. }
  271. export interface PrinterDiagnosticResult {
  272. printer_id: number | null;
  273. ip_address: string;
  274. overall: 'ok' | 'warnings' | 'problems';
  275. checks: DiagnosticCheck[];
  276. }
  277. // --- Log-health scan: self-service triage on the System page + bug reporter.
  278. // The backend matches recent logs against a curated known-issue catalog;
  279. // human-readable cause/fix text is rendered from i18n keys keyed by signature_id.
  280. export type LogFindingSeverity = 'error' | 'warning';
  281. export type LogFindingCategory = 'layer8' | 'environment' | 'bug';
  282. export interface LogFinding {
  283. signature_id: string;
  284. severity: LogFindingSeverity;
  285. category: LogFindingCategory;
  286. wiki_anchor: string;
  287. count: number;
  288. first_seen: string;
  289. last_seen: string;
  290. sample: string;
  291. }
  292. export interface SystemHealthResult {
  293. findings: LogFinding[];
  294. scanned_entries: number;
  295. log_available: boolean;
  296. summary: {
  297. total: number;
  298. layer8: number;
  299. environment: number;
  300. bug: number;
  301. };
  302. }
  303. // Long-lived camera tokens (#1108). The `token` field is populated only on the
  304. // create response — listing endpoints set it to null because the plaintext
  305. // value is shown to the user exactly once.
  306. //
  307. // 'camera_stream' reaches the video endpoints only. 'camwall' additionally
  308. // reaches the read-only Cam Wall feed, which names the printers (#2531), so it
  309. // is a separate scope rather than a widening of tokens already in the wild.
  310. export type LongLivedTokenScope = 'camera_stream' | 'camwall' | 'overlay';
  311. export interface LongLivedCameraToken {
  312. id: number;
  313. user_id: number;
  314. name: string;
  315. scope: LongLivedTokenScope;
  316. lookup_prefix: string;
  317. created_at: string;
  318. expires_at: string;
  319. last_used_at: string | null;
  320. token: string | null;
  321. }
  322. // An external application that signs users in with their Bambuddy account.
  323. // `client_secret` is present only in the create / rotate responses.
  324. export interface ConnectedApp {
  325. id: number;
  326. name: string;
  327. client_id: string;
  328. redirect_uri: string;
  329. enabled: boolean;
  330. created_at: string;
  331. last_used_at: string | null;
  332. client_secret?: string;
  333. }
  334. export interface ConnectAuthorizeInfo {
  335. app_name: string;
  336. username: string;
  337. already_granted: boolean;
  338. }
  339. // One row of the token-authenticated Cam Wall feed (#2531). Deliberately
  340. // smaller than PrinterStatus: no serial, no IP, no print filename — a kiosk URL
  341. // is not a secret, so the payload behind it must not be either.
  342. export interface CamWallPrinter {
  343. id: number;
  344. name: string;
  345. camera_rotation: number;
  346. connected: boolean;
  347. state: string | null;
  348. progress: number | null;
  349. remaining_time: number | null;
  350. layer_num: number | null;
  351. total_layers: number | null;
  352. hms_errors: HMSError[];
  353. }
  354. // Streaming-overlay feed (#2613). The subset of print state the /overlay page
  355. // draws for one printer, served behind an `overlay`-scoped token so OBS embeds
  356. // with no login session can read it. Unlike CamWallPrinter this names the file
  357. // being printed (the overlay shows the part on screen).
  358. export interface OverlayStatus {
  359. id: number;
  360. name: string;
  361. model: string | null;
  362. camera_rotation: number;
  363. connected: boolean;
  364. state: string | null;
  365. current_print: string | null;
  366. gcode_file: string | null;
  367. progress: number | null;
  368. remaining_time: number | null;
  369. layer_num: number | null;
  370. total_layers: number | null;
  371. stg_cur_name: string | null;
  372. // Nozzle / bed / chamber readings for the overlay's temperature fields
  373. // (#1422). Only the keys a viewer is shown; chamber is absent on models
  374. // without a real sensor.
  375. temperatures: Record<string, number>;
  376. time_format: 'system' | '12h' | '24h';
  377. }
  378. // Printer types
  379. // Printer locations (groups) and their appearance (#2962). `id` is null for a
  380. // location only printers carry, with no row of its own yet.
  381. export interface PrinterLocation {
  382. id: number | null;
  383. name: string;
  384. icon: string | null;
  385. color: string | null;
  386. printer_count: number;
  387. }
  388. export interface PrinterLocationUpdate {
  389. name: string;
  390. new_name?: string;
  391. icon?: string | null;
  392. color?: string | null;
  393. }
  394. export interface WLEDPresets {
  395. idle: number | null;
  396. prepare: number | null;
  397. printing: number | null;
  398. paused: number | null;
  399. finished: number | null;
  400. error: number | null;
  401. queue_waiting: number | null;
  402. filament_problem: number | null;
  403. hms_error: number | null;
  404. offline: number | null;
  405. }
  406. export interface WLEDConfig {
  407. enabled: boolean;
  408. base_url: string | null;
  409. presets: WLEDPresets;
  410. finished_timeout_seconds: number | null;
  411. }
  412. export interface WLEDPreset {
  413. id: number;
  414. name: string;
  415. }
  416. export interface WLEDConnectionInfo {
  417. name: string | null;
  418. version: string | null;
  419. }
  420. export interface Printer {
  421. id: number;
  422. name: string;
  423. serial_number: string;
  424. ip_address: string;
  425. // Optional because the backend only returns access_code when the caller has
  426. // PRINTERS_UPDATE — Admin / Operator JWTs or auth-disabled mode. Viewers and
  427. // API keys receive a Printer without this field.
  428. access_code?: string;
  429. model: string | null;
  430. location: string | null; // Group/location name
  431. nozzle_count: number; // 1 or 2, auto-detected from MQTT
  432. // Model is sold with both Standard and High Flow nozzles, so a K-profile's
  433. // flow type is a real choice. Derived from the model, not the nozzle count —
  434. // only the A-series has a single variant.
  435. supports_nozzle_flow_type: boolean;
  436. is_active: boolean;
  437. auto_archive: boolean;
  438. external_camera_url: string | null;
  439. external_camera_type: string | null; // "mjpeg", "rtsp", "snapshot"
  440. external_camera_enabled: boolean;
  441. external_camera_snapshot_url: string | null; // optional single-frame override (#1177)
  442. camera_rotation: number; // 0, 90, 180, 270 degrees
  443. camera_light_auto: boolean; // picked for the chamber light when camera_light_mode is 'selected' (#1655)
  444. plate_detection_enabled: boolean; // Check plate before print
  445. plate_detection_roi?: PlateDetectionROI; // ROI for plate detection
  446. wear_cost_per_hour: number | null; // Wear cost per printing hour (#694)
  447. wled_config: WLEDConfig | null;
  448. created_at: string;
  449. updated_at: string;
  450. }
  451. export interface HMSError {
  452. code: string;
  453. attr: number; // Attribute value for constructing wiki URL
  454. module: number;
  455. // Bambu's alert level: 1 error (task stopped), 2 warning (task paused),
  456. // 3 notification, 0 invalid (#2728).
  457. severity: number;
  458. actions?: string[]; // List of user-facing action keys (e.g. "CHECK_FILAMENT")
  459. job_id?: string; // Optional job ID for actions that require it (e.g. "CHECK_ASSISTANT")
  460. // Canonical hex identifier the firmware matches against — 8 chars for
  461. // print_error-sourced faults, 16 chars for hms[]-array-sourced faults. Send
  462. // this back as HmsActionBody.print_error so we don't truncate the 64-bit
  463. // identifier into the silent-rejection short code (#1830).
  464. full_code?: string;
  465. // The backend's catalogue sentence for this fault (#2926), from the table
  466. // generated out of Bambu Studio for this printer model (#2728). English only.
  467. // Null when Bambu publishes no text for the code. The frontend has no table of
  468. // its own: this field decides both the text and whether the fault counts.
  469. description?: string | null;
  470. }
  471. export interface HMSActionBody {
  472. print_error: string; // HMS error code (e.g. "05000070")
  473. action: string; // "HMS action to execute (e.g. 'resume_after_error')"
  474. job_id: string | null; // Optional job ID for context (if applicable)
  475. }
  476. export interface AMSTray {
  477. id: number;
  478. tray_color: string | null;
  479. tray_type: string | null;
  480. tray_sub_brands: string | null; // Full name like "PLA Basic", "PETG HF"
  481. tray_id_name: string | null; // Bambu filament ID like "A00-Y2" (can decode to color)
  482. tray_info_idx: string | null; // Filament preset ID like "GFA00" - maps to cloud setting_id
  483. remain: number;
  484. k: number | null; // Pressure advance value (from tray or K-profile lookup)
  485. cali_idx: number | null; // Calibration index for K-profile lookup
  486. tag_uid: string | null; // RFID tag UID (any tag)
  487. tray_uuid: string | null; // Bambu Lab spool UUID (32-char hex, only valid for Bambu Lab spools)
  488. nozzle_temp_min: number | null; // Min nozzle temperature
  489. nozzle_temp_max: number | null; // Max nozzle temperature
  490. drying_temp: number | null; // RFID-recommended drying temp
  491. drying_time: number | null; // RFID-recommended drying time (hours)
  492. state: number | null; // AMS tray state: 9=empty, 10=spool present not loaded, 11=loaded
  493. exists?: boolean | null; // Firmware tray_exist_bits: spool physically present (non-RFID → "?" not "Empty", #2527)
  494. }
  495. export interface AMSUnit {
  496. id: number;
  497. humidity: number | null;
  498. temp: number | null;
  499. is_ams_ht: boolean; // True for AMS-HT (single spool), False for regular AMS (4 spools)
  500. tray: AMSTray[];
  501. serial_number: string; // AMS unit serial number (from MQTT sn field)
  502. sw_ver: string; // AMS firmware version (from get_version info.module ams/* entry)
  503. dry_time: number; // Minutes remaining (0 = not drying, >0 = drying active)
  504. dry_countdown_stalled?: boolean; // Timer set but countdown not ticking (never started or paused)
  505. dry_status: number; // 0=Off, 1=Checking, 2=Drying, 3=Cooling, 4=Stopping, 5=Error
  506. dry_sub_status: number; // 0=Off, 1=Heating, 2=Dehumidify
  507. dry_sf_reason: number[]; // Cannot-dry reasons (1=InsufficientPower, 8=NeedPluginPower)
  508. dry_target_temp: number | null; // Active-cycle target °C (Bambu does not echo)
  509. dry_filament: string | null; // Active-cycle filament name we sent
  510. module_type: string; // "ams", "ams_f1", "n3f", "n3s", "n10a" (H3C AMS 3H)
  511. ams_type?: number | null; // Bambu Studio's AMS type (utils/trayIds AmsType), 6 = AMS 3H
  512. // The AMS 3H dryer: its two slots (tray ids 0-8) and that zone's humidity (%) and temperature.
  513. dryer_slots?: number[];
  514. dryer_humidity?: number | null;
  515. dryer_temp?: number | null;
  516. }
  517. export interface ScheduledDrying {
  518. id: number;
  519. printer_id: number;
  520. ams_id: number;
  521. temp: number;
  522. duration_hours: number;
  523. filament: string;
  524. rotate_tray: boolean;
  525. start_after: string | null; // UTC ISO with Z suffix, like the queue routes
  526. status: string;
  527. waiting_reason: string | null;
  528. error_message: string | null;
  529. // Why a failed run failed (screen_only / unsupported / did_not_start); null on
  530. // rows that failed before codes existed, which show error_message instead.
  531. error_code?: string | null;
  532. created_at: string;
  533. started_at: string | null;
  534. completed_at: string | null;
  535. }
  536. export interface NozzleInfo {
  537. // Two vocabularies live in this field, by printer generation. Legacy
  538. // printers (X1/P1) report the nozzle MATERIAL -- "stainless_steel",
  539. // "hardened_steel". H2-series report a FLOW code -- "HH01" (high flow),
  540. // "HS01" (standard); measured on an H2D. utils/nozzleFlow reads only the
  541. // latter and treats anything else as "unknown", which is what makes the
  542. // material spelling harmless here.
  543. nozzle_type: string;
  544. nozzle_diameter: string; // e.g., "0.4"
  545. }
  546. export interface NozzleRackSlot {
  547. id: number;
  548. nozzle_type: string;
  549. nozzle_diameter: string;
  550. wear: number | null;
  551. print_time_s?: number | null; // H2C: seconds this nozzle has printed (#1908); null when not reported
  552. stat: number | null; // Nozzle status (e.g. mounted/docked)
  553. max_temp: number;
  554. serial_number: string;
  555. filament_color: string; // RGBA hex ("00000000" = no filament)
  556. filament_id: string;
  557. filament_type: string; // Material type (e.g. "PLA", "PETG")
  558. addr_id?: number | null; // H3C: home rack position 0-8 (the mounted hotend reports id 0)
  559. }
  560. export interface PrintOptions {
  561. // Core AI detectors
  562. spaghetti_detector: boolean;
  563. print_halt: boolean;
  564. halt_print_sensitivity: string; // "low", "medium", "high" - spaghetti sensitivity
  565. first_layer_inspector: boolean;
  566. printing_monitor: boolean;
  567. buildplate_marker_detector: boolean;
  568. allow_skip_parts: boolean;
  569. // Additional AI detectors (decoded from cfg bitmask)
  570. nozzle_clumping_detector: boolean;
  571. nozzle_clumping_sensitivity: string; // "low", "medium", "high"
  572. pileup_detector: boolean;
  573. pileup_sensitivity: string; // "low", "medium", "high"
  574. airprint_detector: boolean;
  575. airprint_sensitivity: string; // "low", "medium", "high"
  576. auto_recovery_step_loss: boolean;
  577. filament_tangle_detect: boolean;
  578. }
  579. export interface FilaSwitchState {
  580. installed: boolean;
  581. // Raw wire arrays, ordered **In-B first, then In-A** (BambuStudio's SwitchPos
  582. // enum). in[] values are snow-encoded (bits 8-15 = AMS id, bits 0-7 = slot,
  583. // -1 = empty); out[] values are the extruder each *outlet* terminates at, or
  584. // 0xE when unset. Neither array says which inlet is currently routed to which
  585. // outlet — that pairing is not reported. For per-AMS side information use
  586. // PrinterStatus.ams_switch_inlet instead.
  587. in_slots: number[];
  588. out_extruders: number[];
  589. stat: number;
  590. info: number;
  591. // Whether every AMS is bound to one of the switch's two inlets. Until it is,
  592. // the switch cannot route a load anywhere and the printer has to be set up
  593. // first ("Manual AMS Setup" on its screen).
  594. ready: boolean;
  595. }
  596. // Which AMS slot one hotend is currently fed from. ams_id/slot_id are null when
  597. // the hotend holds nothing. Keyed by extruder id ('0' = right, '1' = left).
  598. // tray_now cannot answer this — it is one value for the whole printer, so on a
  599. // dual-nozzle machine it names only one of the two loaded hotends.
  600. export interface ExtruderSlot {
  601. ams_id: number | null;
  602. slot_id: number | null;
  603. has_filament: boolean;
  604. }
  605. // Which FTS inlet an AMS is plumbed into: 'A' | 'B'.
  606. export type FtsInlet = 'A' | 'B';
  607. // A video device the server can see, for a USB camera (GET /printers/usb-cameras).
  608. export interface UsbCamera {
  609. device: string;
  610. name: string;
  611. capabilities: string[];
  612. driver?: string;
  613. formats?: string[];
  614. }
  615. export interface PrinterStatus {
  616. id: number;
  617. name: string;
  618. connected: boolean;
  619. state: string | null;
  620. current_print: string | null;
  621. subtask_name: string | null;
  622. current_archive_id: number | null;
  623. current_plate_id: number | null;
  624. gcode_file: string | null;
  625. progress: number | null;
  626. remaining_time: number | null;
  627. layer_num: number | null;
  628. total_layers: number | null;
  629. temperatures: {
  630. bed?: number;
  631. bed_target?: number;
  632. bed_heating?: boolean; // Actual heater state from MQTT
  633. nozzle?: number;
  634. nozzle_target?: number;
  635. nozzle_heating?: boolean; // Actual heater state from MQTT
  636. nozzle_2?: number; // Second nozzle for H2 series (dual nozzle)
  637. nozzle_2_target?: number;
  638. nozzle_2_heating?: boolean; // Actual heater state from MQTT
  639. chamber?: number;
  640. chamber_target?: number;
  641. chamber_heating?: boolean; // Actual heater state from MQTT
  642. } | null;
  643. cover_url: string | null;
  644. hms_errors: HMSError[];
  645. // Live updates send null when no AMS is attached; the REST status sends [].
  646. ams: AMSUnit[] | null;
  647. ams_exists: boolean;
  648. vt_tray: AMSTray[]; // Virtual tray / external spool(s)
  649. store_to_sdcard: boolean; // Store sent files on SD card
  650. timelapse: boolean; // Timelapse recording active
  651. ipcam: boolean; // Live view enabled
  652. wifi_signal: number | null; // WiFi signal strength in dBm
  653. wired_network: boolean; // Ethernet connection detected
  654. door_open: boolean; // Enclosure door open (models with a door sensor: X1/X1C/X1E/X2D/P2S/H2*)
  655. // Indexed by EXTRUDER id: [0] is the right hotend, [1] the left. Measured
  656. // on an H2D with 0.4 left / 0.6 right. Read it through the helpers in
  657. // utils/amsHelpers rather than indexing it directly.
  658. nozzles: NozzleInfo[];
  659. nozzle_rack: NozzleRackSlot[]; // H2C 6-nozzle tool-changer rack
  660. print_options: PrintOptions | null; // AI detection and print options
  661. // Calibration stage tracking
  662. stg_cur: number; // Current stage number (-1 = not calibrating)
  663. stg_cur_name: string | null; // Human-readable current stage name
  664. stg: number[]; // List of stage numbers in calibration sequence
  665. // Air conditioning mode (0=cooling, 1=heating)
  666. airduct_mode: number;
  667. // Print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  668. speed_level: number;
  669. // Chamber light on/off
  670. chamber_light: boolean;
  671. // Active extruder for dual nozzle (0=right, 1=left)
  672. active_extruder: number;
  673. // AMS mapping - which AMS is connected to which nozzle
  674. // Format: [ams_id_for_nozzle0, ams_id_for_nozzle1, ...] where -1 means no AMS
  675. ams_mapping: number[];
  676. // Per-AMS extruder mapping - extracted from each AMS unit's info field
  677. // Format: {ams_id: extruder_id} where extruder 0=right, 1=left
  678. // Note: JSON keys are always strings
  679. ams_extruder_map: Record<string, number>;
  680. // Filament Track Switch accessory — null when not installed. When present,
  681. // AMS slots aren't tied to a specific extruder; the FTS routes any slot to
  682. // either extruder, so per-extruder slot filtering must be skipped.
  683. fila_switch: FilaSwitchState | null;
  684. // Per-AMS FTS inlet binding, {ams_id: 'A' | 'B'}, as set on the printer's
  685. // "Manual AMS Setup" screen. Empty unless a switch is installed. An AMS with
  686. // an entry here reaches BOTH nozzles through the switch, which is why it has
  687. // no ams_extruder_map entry and must not be badged left or right.
  688. ams_switch_inlet: Record<string, FtsInlet>;
  689. // Which AMS slot each hotend is fed from, keyed by extruder id as a string.
  690. // Empty on printers that don't report it (everything but the H2/X2 series).
  691. extruder_slots: Record<string, ExtruderSlot>;
  692. // Currently loaded tray (global tray ID, 255 = no filament loaded, 254 = external spool)
  693. tray_now: number;
  694. // The trays this print has drawn from, in order: [global tray ID, layer of the
  695. // switch]. A tray outside the job's AMS mapping is a backup spool the printer
  696. // switched to (AMS Filament Backup). Reset at the start of each print.
  697. tray_change_log?: [number, number][];
  698. // Runout / filament-replacement guidance (#2587). Populated only while PAUSED.
  699. // Global tray IDs (ams_id*4+slot, 28-36 = H3C AMS 3H, 128-135 = AMS-HT, 254 = external; utils/trayIds), matching
  700. // the same numbering as tray_now so the AMS graphic can highlight them.
  701. // expected_tray = the slot the firmware now expects filament in (null = idle,
  702. // not paused, or unresolvable → "check the printer").
  703. // previous_tray = the slot that ran out (null = unknown).
  704. expected_tray: number | null;
  705. previous_tray: number | null;
  706. // AMS status for filament change tracking (0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration)
  707. ams_status_main: number;
  708. // AMS sub-status for filament change step (when main=1): 4=retraction, 6=load verification, 7=purge
  709. ams_status_sub: number;
  710. // mc_print_sub_stage - filament change step indicator used by OrcaSlicer/BambuStudio
  711. mc_print_sub_stage: number;
  712. // Timestamp of last AMS data update (for RFID refresh detection)
  713. last_ams_update: number;
  714. // Number of printable objects in current print (for skip objects feature)
  715. printable_objects_count: number;
  716. // The next pause the slicer put into the running print (#2984). minutes is
  717. // null while the printer reports no time left yet.
  718. next_pause?: { layer: number; minutes: number | null } | null;
  719. // Fan speeds (0-100 percentage, null if not available for this model)
  720. cooling_fan_speed: number | null; // Part cooling fan
  721. big_fan1_speed: number | null; // Auxiliary fan
  722. big_fan2_speed: number | null; // Chamber/exhaust fan
  723. heatbreak_fan_speed: number | null; // Hotend heatbreak fan
  724. // Left auxiliary part cooling fan (optional P2S/X2D accessory, M106 P10).
  725. // null = not installed / not reported by this model.
  726. left_aux_fan_speed: number | null;
  727. // Chamber exhaust fan present (P2S/X2D External Exhaust Fan kit, airduct part 3).
  728. exhaust_fan_present: boolean;
  729. firmware_version: string | null; // Firmware version from MQTT
  730. // Developer LAN mode: true = enabled, false = disabled, null = unknown
  731. developer_mode: boolean | null;
  732. // AMS Filament Backup ("auto-switch" to a backup spool when one runs out).
  733. // true = ON, false = OFF, null = unknown / unsupported (A1 family).
  734. ams_filament_backup: boolean | null;
  735. // Queue: printer is awaiting user ack that the build plate was cleared after a
  736. // finished/failed print. Persisted across restarts (#961).
  737. awaiting_plate_clear: boolean;
  738. // AMS drying support
  739. supports_drying: boolean;
  740. // The AMS can dry, but only from the printer's own screen (P1 series, #2533).
  741. drying_screen_only?: boolean;
  742. // Active chamber heater (responds to M141). True only for H2C/H2D/H2DPro/H2S/X2D.
  743. supports_chamber_heater?: boolean;
  744. }
  745. export interface PrinterCreate {
  746. name: string;
  747. serial_number: string;
  748. ip_address: string;
  749. access_code: string;
  750. model?: string;
  751. location?: string | null;
  752. auto_archive?: boolean;
  753. // Maintenance Mode flag (#1476). Backend already gates MQTT, queue dispatch,
  754. // scheduler, metrics and the print picker on this; toggling via PATCH
  755. // /printers/{id} disconnects or reconnects MQTT accordingly.
  756. is_active?: boolean;
  757. external_camera_url?: string | null;
  758. external_camera_type?: string | null;
  759. external_camera_enabled?: boolean;
  760. external_camera_snapshot_url?: string | null;
  761. camera_rotation?: number;
  762. camera_light_auto?: boolean;
  763. plate_detection_enabled?: boolean;
  764. plate_detection_roi?: PlateDetectionROI;
  765. wear_cost_per_hour?: number | null;
  766. wled_config?: WLEDConfig | null;
  767. }
  768. // Plate Detection
  769. export interface PlateDetectionROI {
  770. x: number; // X start % (0.0-1.0)
  771. y: number; // Y start % (0.0-1.0)
  772. w: number; // Width % (0.0-1.0)
  773. h: number; // Height % (0.0-1.0)
  774. }
  775. export interface PlateDetectionResult {
  776. is_empty: boolean;
  777. confidence: number;
  778. difference_percent: number;
  779. message: string;
  780. has_debug_image: boolean;
  781. debug_image_url?: string;
  782. needs_calibration: boolean;
  783. light_warning?: boolean;
  784. reference_count?: number;
  785. max_references?: number;
  786. roi?: PlateDetectionROI;
  787. }
  788. export interface PlateDetectionStatus {
  789. available: boolean;
  790. calibrated: boolean;
  791. reference_count: number;
  792. max_references: number;
  793. message: string;
  794. }
  795. export interface CalibrationResult {
  796. success: boolean;
  797. message: string;
  798. }
  799. export interface PlateReference {
  800. index: number;
  801. label: string;
  802. timestamp: string;
  803. has_image: boolean;
  804. thumbnail_url: string;
  805. }
  806. // Archive types
  807. export interface ArchiveDuplicate {
  808. id: number;
  809. print_name: string | null;
  810. created_at: string;
  811. match_type: 'exact' | 'similar'; // 'exact' = hash match, 'similar' = name match
  812. }
  813. export interface ArchivePrinterMediaFile {
  814. name: string;
  815. path: string;
  816. size: number;
  817. mtime: string | null;
  818. kind: 'timelapse' | 'ipcam';
  819. }
  820. export interface ArchivePrinterMedia {
  821. archive_id: number;
  822. printer_id: number | null;
  823. local_timelapse: { name: string; size: number } | null;
  824. remote_files: ArchivePrinterMediaFile[];
  825. warnings: Array<'printer_missing' | 'timelapse_unavailable' | 'ipcam_unavailable' | 'printer_files_forbidden'>;
  826. }
  827. /** A timelapse editor re-encode, run in the background. */
  828. export interface TimelapseJob {
  829. status: 'running' | 'completed' | 'failed' | 'cancelled';
  830. /** Share done, 0 to 1; null before ffmpeg's first report. */
  831. progress: number | null;
  832. output_path: string | null;
  833. message: string | null;
  834. error: string | null;
  835. }
  836. /** How a post-print outcome verdict reached the archive (#1898). */
  837. export type VerdictSource = 'dialog' | 'link' | 'plate_clear' | 'printer_card' | 'api' | 'reaction';
  838. export interface Archive {
  839. id: number;
  840. printer_id: number | null;
  841. project_id: number | null;
  842. project_name: string | null;
  843. filename: string;
  844. file_path: string;
  845. file_size: number;
  846. content_hash: string | null;
  847. thumbnail_path: string | null;
  848. timelapse_path: string | null;
  849. source_3mf_path: string | null;
  850. f3d_path: string | null;
  851. duplicates: ArchiveDuplicate[] | null;
  852. duplicate_count: number;
  853. duplicate_sequence: number; // 0 = original, 1+ = nth duplicate
  854. original_archive_id: number | null; // ID of the first/original archive
  855. object_count: number | null;
  856. print_name: string | null;
  857. plate_id: number | null; // Selected plate of a multi-plate 3MF (#2603)
  858. print_time_seconds: number | null;
  859. actual_time_seconds: number | null; // Computed from started_at/completed_at
  860. time_accuracy: number | null; // Percentage: 100 = perfect, >100 = faster than estimated
  861. time_estimate_seconds?: number | null; // The latest print's plate estimate, what time_accuracy compares with
  862. filament_used_grams: number | null;
  863. filament_type: string | null;
  864. filament_color: string | null;
  865. layer_height: number | null;
  866. total_layers: number | null;
  867. nozzle_diameter: number | null;
  868. bed_temperature: number | null;
  869. bed_type: string | null; // Build plate type from 3MF (e.g. "Cool Plate", "Textured PEI Plate")
  870. nozzle_temperature: number | null;
  871. sliced_for_model: string | null; // Printer model this file was sliced for
  872. status: string;
  873. started_at: string | null;
  874. completed_at: string | null;
  875. extra_data: Record<string, unknown> | null;
  876. makerworld_url: string | null;
  877. designer: string | null;
  878. external_url: string | null;
  879. is_favorite: boolean;
  880. tags: string | null;
  881. notes: string | null;
  882. cost: number | null;
  883. photos: string[] | null;
  884. failure_reason: string | null;
  885. // Post-print outcome confirmation (#1898)
  886. user_verdict: 'good' | 'reject' | null;
  887. // How the verdict arrived; 'reaction' is written by the Telegram reaction
  888. // handler (#3046) and is labelled here so it reads correctly once that lands.
  889. user_verdict_source: VerdictSource | null;
  890. user_verdict_at: string | null;
  891. confirm_requested: boolean;
  892. // The run whose outcome this shows, when it shows one run of the archive
  893. // (a plate printed on its own) rather than its latest (#1898).
  894. run_id?: number | null;
  895. // The latest print of the archive (among those the caller may see), whose
  896. // figures the per-print fields show (archive redesign).
  897. latest_run_id?: number | null;
  898. // How many videos its prints have; timelapse_path is the latest print's only.
  899. timelapse_count?: number;
  900. quantity: number;
  901. energy_kwh: number | null;
  902. energy_cost: number | null;
  903. wear_cost: number | null; // Printer wear (#694)
  904. created_at: string;
  905. // User tracking (Issue #206)
  906. created_by_id: number | null;
  907. created_by_username: string | null;
  908. // Per-archive run aggregates from PrintLogEntry (#1378)
  909. run_count: number;
  910. last_run_at: string | null;
  911. total_filament_actual_grams: number | null;
  912. successful_run_count: number;
  913. failed_run_count: number;
  914. }
  915. export interface ArchiveSlim {
  916. printer_id: number | null;
  917. print_name: string | null;
  918. print_time_seconds: number | null;
  919. actual_time_seconds: number | null;
  920. filament_used_grams: number | null;
  921. filament_type: string | null;
  922. filament_color: string | null;
  923. status: string;
  924. started_at: string | null;
  925. completed_at: string | null;
  926. cost: number | null;
  927. energy_kwh: number | null;
  928. energy_cost: number | null;
  929. wear_cost: number | null; // Printer wear (#694)
  930. quantity: number;
  931. created_at: string;
  932. }
  933. export interface PrintLogEntry {
  934. id: number;
  935. archive_id: number | null;
  936. print_name: string | null;
  937. plate_id?: number | null;
  938. printer_name: string | null;
  939. printer_id: number | null;
  940. status: string;
  941. started_at: string | null;
  942. completed_at: string | null;
  943. duration_seconds: number | null;
  944. filament_type: string | null;
  945. filament_color: string | null;
  946. filament_used_grams: number | null;
  947. cost: number | null;
  948. energy_kwh: number | null;
  949. energy_cost: number | null;
  950. wear_cost: number | null; // Printer wear (#694)
  951. failure_reason: string | null;
  952. user_verdict?: 'good' | 'reject' | null;
  953. user_verdict_source?: string | null;
  954. confirm_requested?: boolean | null;
  955. duration_unmeasured?: boolean | null;
  956. quantity?: number | null;
  957. // This print's own (archive redesign): note, finish photos, video.
  958. notes?: string | null;
  959. photos?: string[] | null;
  960. timelapse_path?: string | null;
  961. // The slicer's estimate for the plate it printed; in an archive's runs list.
  962. estimate_seconds?: number | null;
  963. estimate_grams?: number | null;
  964. thumbnail_path: string | null;
  965. created_by_id: number | null;
  966. created_by_username: string | null;
  967. created_at: string;
  968. }
  969. export interface PrintLogResponse {
  970. items: PrintLogEntry[];
  971. total: number;
  972. // The print log only: archives of its prints that were deleted.
  973. deleted_archive_ids?: number[];
  974. }
  975. export interface ArchiveStats {
  976. total_prints: number;
  977. successful_prints: number;
  978. failed_prints: number;
  979. cancelled_prints: number;
  980. total_print_time_hours: number;
  981. total_filament_grams: number;
  982. total_cost: number;
  983. prints_by_filament_type: Record<string, number>;
  984. prints_by_printer: Record<string, number>;
  985. // Name each printer id was last recorded under in the print log, so history
  986. // belonging to a deleted printer keeps its label.
  987. printer_names?: Record<string, string>;
  988. average_time_accuracy: number | null;
  989. time_accuracy_by_printer: Record<string, number> | null;
  990. total_energy_kwh: number;
  991. total_energy_cost: number;
  992. total_wear_cost: number; // Printer wear (#694)
  993. // True when a date-filtered total-consumption query is running on incomplete
  994. // snapshot history (e.g. right after upgrade, before hourly snapshots have
  995. // a baseline). UI should explain why the number may undercount.
  996. energy_data_warming_up?: boolean;
  997. }
  998. export interface TagInfo {
  999. name: string;
  1000. count: number;
  1001. }
  1002. export interface FailureAnalysis {
  1003. period_days: number;
  1004. total_prints: number;
  1005. failed_prints: number;
  1006. failure_rate: number;
  1007. // Quality dimension (#1898): completed prints the user rejected. Optional
  1008. // so a frontend build against an older backend degrades gracefully.
  1009. rejected_prints?: number;
  1010. yield_rate?: number;
  1011. rejects_by_reason?: Record<string, number>;
  1012. failures_by_reason: Record<string, number>;
  1013. failures_by_filament: Record<string, number>;
  1014. failures_by_printer: Record<string, number>;
  1015. failures_by_hour: Record<number, number>;
  1016. recent_failures: Array<{
  1017. id: number;
  1018. print_name: string;
  1019. failure_reason: string | null;
  1020. filament_type: string | null;
  1021. printer_id: number | null;
  1022. created_at: string | null;
  1023. }>;
  1024. trend: Array<{
  1025. week_start: string;
  1026. total_prints: number;
  1027. failed_prints: number;
  1028. failure_rate: number;
  1029. }>;
  1030. }
  1031. /**
  1032. * Send the browser's zone with calendar dates: the server reads a date as a
  1033. * day in it, else in its own TZ, which shifted every day for a browser away
  1034. * from the server (DB-C12). Only when a date is set.
  1035. */
  1036. function addDayZone(params: URLSearchParams): void {
  1037. if (!params.has('date_from') && !params.has('date_to')) return;
  1038. try {
  1039. const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
  1040. if (zone) params.set('tz', zone);
  1041. } catch {
  1042. // No Intl zone: the server's TZ applies.
  1043. }
  1044. }
  1045. export interface BulkUploadResult {
  1046. uploaded: number;
  1047. failed: number;
  1048. /** `index` is the file's position in the request. */
  1049. results: Array<{ index: number; filename: string; id: number; status: string }>;
  1050. errors: Array<{ index: number; filename: string; error: string }>;
  1051. }
  1052. // Archive Comparison types
  1053. export interface ComparisonArchiveInfo {
  1054. id: number;
  1055. print_name: string;
  1056. status: string;
  1057. created_at: string | null;
  1058. printer_id: number | null;
  1059. project_name: string | null;
  1060. }
  1061. export interface ComparisonField {
  1062. field: string;
  1063. label: string;
  1064. unit: string | null;
  1065. values: (string | number | null)[];
  1066. raw_values: (string | number | null)[];
  1067. has_difference: boolean;
  1068. }
  1069. export interface SuccessCorrelationInsight {
  1070. field: string;
  1071. label: string;
  1072. insight: string;
  1073. success_avg?: number;
  1074. failed_avg?: number;
  1075. success_values?: string[];
  1076. failed_values?: string[];
  1077. }
  1078. export interface SuccessCorrelation {
  1079. has_both_outcomes: boolean;
  1080. message?: string;
  1081. successful_count?: number;
  1082. failed_count?: number;
  1083. insights?: SuccessCorrelationInsight[];
  1084. }
  1085. export interface ArchiveComparison {
  1086. archives: ComparisonArchiveInfo[];
  1087. comparison: ComparisonField[];
  1088. differences: ComparisonField[];
  1089. success_correlation: SuccessCorrelation;
  1090. }
  1091. // Project types
  1092. export interface ProjectStats {
  1093. total_archives: number;
  1094. total_items: number; // Sum of quantities (total items printed)
  1095. completed_prints: number; // Sum of quantities for completed prints (parts)
  1096. failed_prints: number;
  1097. queued_prints: number;
  1098. in_progress_prints: number;
  1099. total_print_time_hours: number;
  1100. total_filament_grams: number;
  1101. progress_percent: number | null; // Plates progress (total_archives / target_count)
  1102. parts_progress_percent: number | null; // Parts progress (completed_prints / target_parts_count)
  1103. estimated_cost: number;
  1104. total_energy_kwh: number;
  1105. total_energy_cost: number;
  1106. total_wear_cost: number; // Printer wear (#694)
  1107. remaining_prints: number | null; // Remaining plates
  1108. remaining_parts: number | null; // Remaining parts
  1109. bom_total_items: number;
  1110. bom_completed_items: number;
  1111. bom_cost: number;
  1112. }
  1113. // A sub-project as listed on its parent's page. The figures cover the child's
  1114. // own subtree, so the listed rows add up to the parent's roll-up minus the
  1115. // parent's own prints (#1264).
  1116. export interface ProjectChildPreview {
  1117. id: number;
  1118. name: string;
  1119. color: string | null;
  1120. status: string;
  1121. progress_percent: number | null;
  1122. descendant_count: number;
  1123. total_archives: number;
  1124. completed_prints: number;
  1125. total_print_time_hours: number;
  1126. total_filament_grams: number;
  1127. total_cost: number; // Filament + energy + BOM, matching the parent's cost card
  1128. }
  1129. export interface Project {
  1130. id: number;
  1131. name: string;
  1132. description: string | null;
  1133. color: string | null;
  1134. status: string; // active, completed, archived
  1135. target_count: number | null; // Target number of plates/print jobs
  1136. target_parts_count: number | null; // Target number of parts/objects
  1137. target_sets: number | null; // Copies-per-file target (#1897)
  1138. notes: string | null;
  1139. attachments: ProjectAttachment[] | null;
  1140. tags: string | null;
  1141. due_date: string | null;
  1142. priority: string; // low, normal, high, urgent
  1143. budget: number | null;
  1144. is_template: boolean;
  1145. template_source_id: number | null;
  1146. parent_id: number | null;
  1147. parent_name: string | null;
  1148. children: ProjectChildPreview[];
  1149. descendant_count: number; // Sub-projects at any depth beneath this one (#1264)
  1150. created_at: string;
  1151. updated_at: string;
  1152. stats?: ProjectStats;
  1153. // This project's numbers combined with every sub-project's. Null when there
  1154. // are none, since it would only repeat `stats` (#1264).
  1155. rollup_stats?: ProjectStats | null;
  1156. url: string | null; // External link rendered next to project name on the card (#1155)
  1157. cover_image_filename: string | null; // Filename within project attachments dir (#1155)
  1158. }
  1159. export interface ProjectAttachment {
  1160. filename: string;
  1161. original_name: string;
  1162. size: number;
  1163. uploaded_at: string;
  1164. }
  1165. // Completed-run count for one library file inside a project (#1897)
  1166. export interface ProjectFileProgress {
  1167. file_id: number;
  1168. completed_count: number;
  1169. }
  1170. export interface ArchivePreview {
  1171. id: number;
  1172. print_name: string | null;
  1173. thumbnail_path: string | null;
  1174. status: string;
  1175. filament_type: string | null;
  1176. filament_color: string | null;
  1177. }
  1178. export interface ProjectListItem {
  1179. id: number;
  1180. name: string;
  1181. description: string | null;
  1182. color: string | null;
  1183. status: string;
  1184. target_count: number | null; // Target number of plates/print jobs
  1185. target_parts_count: number | null; // Target number of parts/objects
  1186. target_sets: number | null; // #1897 — the shared edit dialog seeds itself from this
  1187. budget: number | null;
  1188. tags: string | null; // #2536 — the shared edit dialog seeds itself from this
  1189. due_date: string | null; // #2536
  1190. priority: string; // #2536
  1191. created_at: string;
  1192. archive_count: number; // Number of print jobs (plates)
  1193. total_items: number; // Sum of quantities (total items printed, including failed)
  1194. completed_count: number; // Sum of quantities for completed prints only (parts)
  1195. failed_count: number; // Sum of quantities for failed prints
  1196. queue_count: number;
  1197. progress_percent: number | null; // Plates progress
  1198. parent_id: number | null; // #1264 — set when this is a sub-project
  1199. child_count: number; // #1264 — direct sub-projects only
  1200. archives: ArchivePreview[];
  1201. url: string | null; // #1155
  1202. cover_image_filename: string | null; // #1155
  1203. }
  1204. export interface ProjectCreate {
  1205. name: string;
  1206. description?: string;
  1207. color?: string;
  1208. target_count?: number;
  1209. target_parts_count?: number;
  1210. target_sets?: number;
  1211. notes?: string;
  1212. tags?: string;
  1213. due_date?: string;
  1214. priority?: string;
  1215. budget?: number | null;
  1216. parent_id?: number;
  1217. url?: string | null; // #1155
  1218. }
  1219. export interface ProjectUpdate {
  1220. name?: string;
  1221. description?: string;
  1222. color?: string;
  1223. status?: string;
  1224. target_count?: number;
  1225. target_parts_count?: number;
  1226. target_sets?: number | null; // #1897 — explicit null clears the copies-per-file target
  1227. notes?: string;
  1228. tags?: string | null; // #2536 — explicit null clears the tags
  1229. due_date?: string | null; // #2536 — explicit null clears the due date
  1230. priority?: string;
  1231. budget?: number | null;
  1232. parent_id?: number;
  1233. url?: string | null; // #1155 — explicit null clears the URL
  1234. }
  1235. // BOM Types - Tracks sourced/purchased parts (hardware, electronics, etc.)
  1236. export interface BOMItem {
  1237. id: number;
  1238. project_id: number;
  1239. name: string;
  1240. quantity_needed: number;
  1241. quantity_acquired: number;
  1242. unit_price: number | null;
  1243. sourcing_url: string | null;
  1244. archive_id: number | null;
  1245. archive_name: string | null;
  1246. stl_filename: string | null;
  1247. remarks: string | null;
  1248. sort_order: number;
  1249. is_complete: boolean;
  1250. created_at: string;
  1251. updated_at: string;
  1252. }
  1253. export interface BOMItemCreate {
  1254. name: string;
  1255. quantity_needed?: number;
  1256. unit_price?: number;
  1257. sourcing_url?: string;
  1258. archive_id?: number;
  1259. stl_filename?: string;
  1260. remarks?: string;
  1261. }
  1262. export interface BOMItemUpdate {
  1263. name?: string;
  1264. quantity_needed?: number;
  1265. quantity_acquired?: number;
  1266. unit_price?: number;
  1267. sourcing_url?: string;
  1268. archive_id?: number;
  1269. stl_filename?: string;
  1270. remarks?: string;
  1271. }
  1272. // Project Export/Import Types
  1273. export interface BOMItemExport {
  1274. name: string;
  1275. quantity_needed: number;
  1276. quantity_acquired: number;
  1277. unit_price: number | null;
  1278. sourcing_url: string | null;
  1279. stl_filename: string | null;
  1280. remarks: string | null;
  1281. }
  1282. export interface LinkedFolderExport {
  1283. name: string;
  1284. }
  1285. export interface ProjectExport {
  1286. name: string;
  1287. description: string | null;
  1288. color: string | null;
  1289. status: string;
  1290. target_count: number | null;
  1291. target_parts_count: number | null;
  1292. target_sets: number | null; // #1897
  1293. notes: string | null;
  1294. tags: string | null;
  1295. due_date: string | null;
  1296. priority: string;
  1297. budget: number | null;
  1298. bom_items: BOMItemExport[];
  1299. linked_folders: LinkedFolderExport[];
  1300. }
  1301. export interface ProjectImport {
  1302. name: string;
  1303. description?: string;
  1304. color?: string;
  1305. status?: string;
  1306. target_count?: number;
  1307. target_parts_count?: number;
  1308. target_sets?: number; // #1897
  1309. notes?: string;
  1310. tags?: string;
  1311. due_date?: string;
  1312. priority?: string;
  1313. budget?: number | null;
  1314. bom_items?: BOMItemExport[];
  1315. linked_folders?: LinkedFolderExport[];
  1316. }
  1317. // Timeline Types
  1318. export interface TimelineEvent {
  1319. event_type: string;
  1320. timestamp: string;
  1321. title: string;
  1322. description: string | null;
  1323. metadata: Record<string, unknown> | null;
  1324. }
  1325. // API Key types
  1326. export interface APIKey {
  1327. id: number;
  1328. name: string;
  1329. key_prefix: string;
  1330. user_id: number | null; // Owner; null on legacy keys created before per-user ownership (#1182)
  1331. can_queue: boolean;
  1332. can_control_printer: boolean;
  1333. can_read_status: boolean;
  1334. can_manage_library: boolean;
  1335. can_manage_inventory: boolean;
  1336. can_manage_maintenance: boolean;
  1337. can_manage_archives: boolean;
  1338. can_manage_projects: boolean;
  1339. can_access_cloud: boolean;
  1340. can_update_energy_cost: boolean;
  1341. can_send_notifications: boolean;
  1342. printer_ids: number[] | null;
  1343. enabled: boolean;
  1344. last_used: string | null;
  1345. created_at: string;
  1346. expires_at: string | null;
  1347. }
  1348. export interface APIKeyCreate {
  1349. name: string;
  1350. can_queue?: boolean;
  1351. can_control_printer?: boolean;
  1352. can_read_status?: boolean;
  1353. can_manage_library?: boolean;
  1354. can_manage_inventory?: boolean;
  1355. can_manage_maintenance?: boolean;
  1356. can_manage_archives?: boolean;
  1357. can_manage_projects?: boolean;
  1358. can_access_cloud?: boolean;
  1359. can_update_energy_cost?: boolean;
  1360. can_send_notifications?: boolean;
  1361. printer_ids?: number[] | null;
  1362. expires_at?: string | null;
  1363. }
  1364. export interface APIKeyCreateResponse extends APIKey {
  1365. key: string; // Full key, only shown on creation
  1366. }
  1367. /**
  1368. * Tri-state calibration option (BambuStudio parity): "off" never runs it,
  1369. * "on" forces it every print, "auto" lets the printer skip it if it was done
  1370. * recently. Used by bed_levelling, flow_cali, and nozzle_offset_cali.
  1371. */
  1372. export type CalibrationMode = 'off' | 'on' | 'auto';
  1373. // Settings types
  1374. export interface AppSettings {
  1375. auto_archive: boolean;
  1376. save_thumbnails: boolean;
  1377. capture_finish_photo: boolean;
  1378. finish_photo_restore_plate: boolean;
  1379. default_filament_cost: number;
  1380. currency: string;
  1381. energy_cost_per_kwh: number;
  1382. energy_tracking_mode: 'print' | 'total';
  1383. // Where the electricity price comes from (#1251). With 'homeassistant',
  1384. // energy_cost_per_kwh holds the sensor's last reading and is read-only.
  1385. energy_price_source: 'fixed' | 'homeassistant';
  1386. energy_price_ha_entity: string;
  1387. check_updates: boolean;
  1388. check_printer_firmware: boolean;
  1389. include_beta_updates: boolean;
  1390. // Announcements from the Bambuddy maintainers (a signed file on GitHub).
  1391. announcements_enabled?: boolean;
  1392. announcements_all_users?: boolean;
  1393. // #1589: false hides the local username/password form on the login page;
  1394. // BAMBUDDY_LOCAL_LOGIN=true on the server flips the reported value back to
  1395. // true so the env-var recovery path is visible to the SPA.
  1396. local_login_enabled: boolean;
  1397. language: string;
  1398. notification_language: string;
  1399. // AMS threshold settings
  1400. ams_humidity_good: number; // <= this is green
  1401. ams_humidity_fair: number; // <= this is orange, > is red
  1402. ams_temp_good: number; // <= this is green/blue
  1403. ams_temp_fair: number; // <= this is orange, > is red
  1404. // Separate from the display band (#2905). null = unset, which the backend
  1405. // resolves to ams_temp_fair so existing installs are unaffected.
  1406. ams_temp_alarm: number | null;
  1407. ams_history_retention_days: number; // days to keep AMS sensor history
  1408. printer_sensor_history_retention_days?: number; // days to keep printer heater history
  1409. // Queue auto-drying settings
  1410. queue_drying_enabled: boolean; // Auto-dry AMS between queued prints
  1411. queue_drying_block: boolean; // Block queue until drying completes
  1412. ambient_drying_enabled: boolean; // Auto-dry idle printers based on humidity regardless of queue
  1413. ambient_drying_sustained_minutes: number; // Minutes humidity must stay above threshold before ambient auto-dry starts (0 = instant)
  1414. print_drying_enabled: boolean; // Continue drying while a print is running on capable hardware
  1415. drying_presets: string; // JSON blob of drying presets per filament type
  1416. ams_humidity_thresholds: string; // JSON blob of per-filament humidity thresholds (#1605)
  1417. gcode_snippets: string; // JSON: per-model G-code injection snippets
  1418. // Scheduled local backup
  1419. local_backup_enabled: boolean;
  1420. local_backup_schedule: string;
  1421. local_backup_time: string;
  1422. local_backup_retention: number;
  1423. local_backup_path: string;
  1424. // Print modal settings
  1425. per_printer_mapping_expanded: boolean; // Whether custom mapping is expanded by default in print modal
  1426. // Date/time format settings
  1427. date_format: 'system' | 'us' | 'eu' | 'iso';
  1428. time_format: 'system' | '12h' | '24h';
  1429. // Filament tracking
  1430. disable_filament_warnings: boolean; // Disable filament warnings (print insufficiency and assignment mismatch)
  1431. prefer_lowest_filament: boolean; // When multiple spools match, prefer lowest remaining filament
  1432. 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
  1433. 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
  1434. spoolman_url: string;
  1435. // Default printer
  1436. default_printer_id: number | null;
  1437. pipeline_max_copies: number;
  1438. // Dark mode theme settings
  1439. dark_style: 'classic' | 'glow' | 'vibrant';
  1440. dark_background: 'neutral' | 'warm' | 'cool' | 'oled' | 'slate' | 'forest';
  1441. dark_accent: 'green' | 'teal' | 'blue' | 'orange' | 'purple' | 'red';
  1442. // Light mode theme settings
  1443. light_style: 'classic' | 'glow' | 'vibrant';
  1444. light_background: 'neutral' | 'warm' | 'cool';
  1445. light_accent: 'green' | 'teal' | 'blue' | 'orange' | 'purple' | 'red';
  1446. // FTP retry settings
  1447. ftp_retry_enabled: boolean;
  1448. ftp_retry_count: number;
  1449. ftp_retry_delay: number;
  1450. ftp_timeout: number;
  1451. // MQTT relay settings
  1452. mqtt_enabled: boolean;
  1453. mqtt_broker: string;
  1454. mqtt_port: number;
  1455. mqtt_username: string;
  1456. mqtt_password: string;
  1457. mqtt_topic_prefix: string;
  1458. mqtt_use_tls: boolean;
  1459. // External URL for notifications
  1460. external_url: string;
  1461. // Directory holding docker-compose.yml, shown in the update instructions (#2664)
  1462. docker_compose_dir: string;
  1463. // Home Assistant integration
  1464. ha_enabled: boolean;
  1465. ha_url: string;
  1466. ha_token: string;
  1467. ha_url_from_env: boolean;
  1468. ha_token_from_env: boolean;
  1469. ha_env_managed: boolean;
  1470. // File Manager / Library settings
  1471. library_disk_warning_gb: number;
  1472. // Camera view settings
  1473. camera_view_mode: 'window' | 'embedded';
  1474. // Chamber light while the camera is in use (#1655)
  1475. camera_light_mode: 'off' | 'all' | 'selected';
  1476. camera_light_delay: number; // seconds a snapshot waits after the light came on
  1477. // Preferred slicer (server-side API / sidecar)
  1478. preferred_slicer: 'bambu_studio' | 'orcaslicer';
  1479. // Desktop "Open in Slicer" override (#1329). Null inherits from
  1480. // preferred_slicer so existing installs behave identically.
  1481. open_in_slicer: 'bambu_studio' | 'orcaslicer' | null;
  1482. // Where slicing runs, independent of which slicer binary the sidecar drives.
  1483. // Only 'sidecar' is implemented today; see lib/sliceEngines.ts.
  1484. slice_engine: 'sidecar' | 'browser';
  1485. // Use the slicer-API sidecar for slicing (in-app modal) vs desktop URI scheme
  1486. use_slicer_api: boolean;
  1487. // Per-install sidecar URLs. Empty string falls back to the env defaults.
  1488. orcaslicer_api_url: string;
  1489. bambu_studio_api_url: string;
  1490. // Minutes of silence from the sidecar before a slice is abandoned. Bounds
  1491. // stalls, not total slicing time — a model that keeps reporting progress
  1492. // runs to completion however long it takes.
  1493. slicer_stall_timeout_minutes: number;
  1494. // Prometheus metrics
  1495. prometheus_enabled: boolean;
  1496. prometheus_token: string;
  1497. // Bed cooled threshold
  1498. bed_cooled_threshold: number;
  1499. // Minutes before a slicer pause to send the pause heads-up (#2984)
  1500. pause_warning_minutes: number;
  1501. // Inventory low stock threshold
  1502. low_stock_threshold: number;
  1503. // Session policy (#1706) — admin-set ceiling, hours, [1, 720]
  1504. session_max_hours: number;
  1505. // User email notifications toggle
  1506. user_notifications_enabled: boolean;
  1507. // Default print options
  1508. default_bed_levelling: CalibrationMode;
  1509. default_flow_cali: CalibrationMode;
  1510. default_vibration_cali: boolean;
  1511. default_layer_inspect: boolean;
  1512. default_timelapse: boolean;
  1513. default_nozzle_offset_cali: CalibrationMode;
  1514. // Default for the per-job "ask for outcome afterwards" toggle (#1898)
  1515. default_confirm_outcome: boolean;
  1516. // Also ask for prints Bambuddy archived but did not dispatch (#1898)
  1517. confirm_outcome_external_prints: boolean;
  1518. // Count unanswered outcome prompts as "good" when the plate is released (#1898)
  1519. confirm_default_good_on_plate_clear: boolean;
  1520. // Staggered batch start defaults
  1521. stagger_group_size: number;
  1522. stagger_interval_minutes: number;
  1523. // Finance budget reset window
  1524. billing_enabled: boolean;
  1525. printer_kill_switch_enabled: boolean;
  1526. finance_budget_reset_day: number;
  1527. finance_budget_reset_timezone: string;
  1528. // Plate-clear confirmation
  1529. require_plate_clear: boolean;
  1530. // Shortest job first scheduling
  1531. queue_shortest_first: boolean;
  1532. // How many printers the queue may upload to at once (#2555). 1 restores the
  1533. // old strictly-serial behaviour, where every printer waited out every other
  1534. // printer's transfer.
  1535. queue_max_concurrent_uploads: number;
  1536. // Preheat / heat-soak before queued prints (#1468). Master toggle is the
  1537. // default for new queue items; per-item PrintQueueItem.preheat_override can
  1538. // flip the decision per print. Chamber target derives from the loaded AMS
  1539. // filament types via preheat_filament_targets (JSON map of type → °C, max
  1540. // across loaded slots); the per-item override field bypasses derivation.
  1541. preheat_enabled: boolean;
  1542. preheat_filament_targets: string;
  1543. preheat_max_wait_seconds: number;
  1544. preheat_soak_seconds: number;
  1545. queue_keep_bed_warm: boolean;
  1546. queue_keep_warm_bed_temp: number;
  1547. queue_keep_warm_max_minutes: number;
  1548. // User-configurable presets for the printer-card popovers (JSON arrays of 3 ints).
  1549. // Empty string = use built-in defaults.
  1550. nozzle_temp_presets: string;
  1551. bed_temp_presets: string;
  1552. chamber_temp_presets: string;
  1553. fan_speed_presets: string;
  1554. // Default sidebar order (admin-set for all users)
  1555. default_sidebar_order: string;
  1556. // LDAP authentication
  1557. ldap_enabled: boolean;
  1558. ldap_server_url: string;
  1559. ldap_bind_dn: string;
  1560. ldap_bind_password: string;
  1561. ldap_search_base: string;
  1562. ldap_user_filter: string;
  1563. ldap_security: string;
  1564. ldap_group_mapping: string;
  1565. ldap_auto_provision: boolean;
  1566. ldap_default_group: string;
  1567. obico_enabled: boolean;
  1568. obico_ml_url: string;
  1569. bambuddy_internal_url: string;
  1570. obico_ml_token: string;
  1571. obico_sensitivity: 'low' | 'medium' | 'high';
  1572. obico_action: 'notify' | 'pause' | 'pause_and_off';
  1573. obico_poll_interval: number;
  1574. obico_enabled_printers: string;
  1575. octoeverywhere_enabled: boolean;
  1576. octoeverywhere_api_key: string;
  1577. octoeverywhere_api_key_configured: boolean;
  1578. octoeverywhere_confidence: OctoEverywhereConfidence;
  1579. octoeverywhere_action: 'notify' | 'pause' | 'pause_and_off';
  1580. octoeverywhere_enabled_printers: string;
  1581. octoeverywhere_poll_interval: number;
  1582. // Inventory forecasting global lead time
  1583. forecast_global_lead_time_days: number;
  1584. location_sensor_poll_interval: number;
  1585. // JSON map of sensor category → {alertAbove, alertBelow, notifyOnAlert},
  1586. // seeding new storage-location sensor bindings. Empty = built-in defaults.
  1587. // Server-backed so two admins seed the same alert rules and a restore
  1588. // brings them back; see utils/locationSensorDefaults.ts.
  1589. location_sensor_alert_defaults: string;
  1590. }
  1591. export type AppSettingsUpdate = Partial<Omit<AppSettings, 'octoeverywhere_api_key_configured'>>;
  1592. // Settings as a page sees them: everything from GET /settings for a user who
  1593. // may read it, otherwise the subset /settings/ui-preferences and
  1594. // /settings/ui-flags serve, which reports G-code snippets only as set or not.
  1595. export type UiSettings = Partial<AppSettings> & { has_gcode_snippets?: boolean };
  1596. // MQTT relay status
  1597. export interface MQTTStatus {
  1598. enabled: boolean;
  1599. connected: boolean;
  1600. broker: string;
  1601. port: number;
  1602. topic_prefix: string;
  1603. }
  1604. // Cloud types
  1605. export interface CloudAuthStatus {
  1606. is_authenticated: boolean;
  1607. email: string | null;
  1608. region?: 'global' | 'china' | null;
  1609. /** A token is stored but Bambu no longer accepts it — tell the user why the login form is back. */
  1610. sign_in_expired?: boolean;
  1611. }
  1612. export interface CloudLoginResponse {
  1613. success: boolean;
  1614. needs_verification: boolean;
  1615. message: string;
  1616. verification_type?: 'email' | 'totp' | null;
  1617. tfa_key?: string | null;
  1618. /**
  1619. * Machine-readable cause of a failure. 'captcha' means Bambu's anti-abuse
  1620. * layer is challenging this network and no credential will be accepted until
  1621. * it clears — the UI must explain that in place rather than toast `message`.
  1622. */
  1623. reason?: 'captcha' | string | null;
  1624. }
  1625. // Orca Cloud types — paste-flow PKCE handshake against auth.orcaslicer.com.
  1626. // See backend/app/services/orca_cloud.py for the deep dive on why this
  1627. // flow is paste-based rather than callback-based.
  1628. export interface OrcaDeviceStartResponse {
  1629. user_code: string;
  1630. verification_uri: string;
  1631. verification_uri_complete: string;
  1632. interval: number;
  1633. expires_in: number;
  1634. }
  1635. export type OrcaDevicePollStatus =
  1636. | 'authorization_pending'
  1637. | 'slow_down'
  1638. | 'access_denied'
  1639. | 'expired_token'
  1640. | 'complete';
  1641. export interface OrcaDevicePollResponse {
  1642. status: OrcaDevicePollStatus;
  1643. connected: boolean;
  1644. email: string | null;
  1645. user_id: string | null;
  1646. }
  1647. export interface OrcaAuthStatusResponse {
  1648. connected: boolean;
  1649. email: string | null;
  1650. user_id: string | null;
  1651. }
  1652. // Orca profiles are shaped to match Bambu Cloud's SlicerSetting on the wire
  1653. // so the frontend can use the same visual components for both surfaces (cards,
  1654. // grouped sections, filter bar). Backend handles the source-specific
  1655. // transformation in routes/orca_cloud.py::_orca_to_setting.
  1656. export interface OrcaProfileMeta {
  1657. setting_id: string;
  1658. name: string;
  1659. type: string;
  1660. version: string | null;
  1661. user_id: string | null;
  1662. updated_time: string | null;
  1663. is_custom: boolean;
  1664. }
  1665. export interface OrcaProfileListResponse {
  1666. filament: OrcaProfileMeta[];
  1667. printer: OrcaProfileMeta[];
  1668. process: OrcaProfileMeta[];
  1669. }
  1670. export interface OrcaProfileDetail {
  1671. setting_id: string;
  1672. name: string;
  1673. type: string;
  1674. version: string | null;
  1675. base_id: string | null;
  1676. update_time: string | null;
  1677. setting: Record<string, unknown>;
  1678. }
  1679. // MakerWorld integration. Full metadata/instance shapes come back as
  1680. // Record<string, unknown> — MakerWorld's API adds fields over time, so we
  1681. // pass them through verbatim rather than maintaining a brittle mirror.
  1682. export interface MakerworldStatus {
  1683. has_cloud_token: boolean;
  1684. can_download: boolean;
  1685. /** A token is stored but Bambu rejected it — downloads will fail until the user signs in again. */
  1686. sign_in_expired?: boolean;
  1687. }
  1688. export interface MakerworldResolvedModel {
  1689. model_id: number;
  1690. profile_id: number | null;
  1691. design: Record<string, unknown>;
  1692. instances: Array<Record<string, unknown>>;
  1693. already_imported_library_ids: number[];
  1694. }
  1695. export interface MakerworldImportResponse {
  1696. library_file_id: number;
  1697. filename: string;
  1698. folder_id: number | null;
  1699. profile_id: number | null;
  1700. was_existing: boolean;
  1701. }
  1702. export interface MakerworldRecentImport {
  1703. library_file_id: number;
  1704. filename: string;
  1705. folder_id: number | null;
  1706. thumbnail_path: string | null;
  1707. source_url: string | null;
  1708. created_at: string;
  1709. }
  1710. // Manyfold integration (#1471): a self-hosted model library, browsed and
  1711. // searched, with single files imported into the library.
  1712. export interface ManyfoldConfig {
  1713. url: string;
  1714. client_id: string;
  1715. /** The secret itself is never returned. */
  1716. has_client_secret: boolean;
  1717. configured: boolean;
  1718. }
  1719. export interface ManyfoldConfigInput {
  1720. url: string;
  1721. client_id: string;
  1722. /** Empty or left out keeps the stored secret. */
  1723. client_secret?: string;
  1724. }
  1725. export interface ManyfoldStatus {
  1726. configured: boolean;
  1727. url: string;
  1728. }
  1729. export interface ManyfoldModelSummary {
  1730. id: string;
  1731. name: string;
  1732. }
  1733. export interface ManyfoldModelList {
  1734. total: number;
  1735. page: number;
  1736. has_next: boolean;
  1737. has_previous: boolean;
  1738. models: ManyfoldModelSummary[];
  1739. }
  1740. export interface ManyfoldFile {
  1741. id: string;
  1742. name: string;
  1743. mime: string;
  1744. importable: boolean;
  1745. /** Set while the file imported earlier is still in the library. */
  1746. library_file: { id: number; filename: string; folder_id: number | null } | null;
  1747. }
  1748. export interface ManyfoldModel {
  1749. id: string;
  1750. name: string;
  1751. caption: string | null;
  1752. description: string | null;
  1753. license: string | null;
  1754. tags: string[];
  1755. url: string;
  1756. has_preview: boolean;
  1757. files: ManyfoldFile[];
  1758. }
  1759. export interface ManyfoldImportResponse {
  1760. library_file_id: number;
  1761. filename: string;
  1762. folder_id: number | null;
  1763. was_existing: boolean;
  1764. }
  1765. export interface SlicerSetting {
  1766. setting_id: string;
  1767. name: string;
  1768. type: string;
  1769. version: string | null;
  1770. user_id: string | null;
  1771. updated_time: string | null;
  1772. is_custom: boolean;
  1773. // The id Bambu Studio puts in an AMS slot for the preset; not derivable
  1774. // from setting_id for every preset (#3387). Absent from older backends.
  1775. filament_id?: string | null;
  1776. }
  1777. export interface SpoolCatalogEntry {
  1778. id: number;
  1779. name: string;
  1780. weight: number;
  1781. is_default: boolean;
  1782. }
  1783. export interface StorageLocation {
  1784. id: number;
  1785. name: string;
  1786. identifier: string | null;
  1787. spool_count: number;
  1788. created_at: string;
  1789. updated_at: string;
  1790. }
  1791. export interface ColorCatalogEntry {
  1792. id: number;
  1793. manufacturer: string;
  1794. color_name: string;
  1795. hex_color: string;
  1796. material: string | null;
  1797. is_default: boolean;
  1798. // #1154: optional multi-colour gradient stops + visual effect.
  1799. extra_colors?: string | null;
  1800. effect_type?: string | null;
  1801. }
  1802. export interface SlicerSettingsResponse {
  1803. filament: SlicerSetting[];
  1804. printer: SlicerSetting[];
  1805. process: SlicerSetting[];
  1806. }
  1807. export interface SlicerSettingDetail {
  1808. message?: string | null;
  1809. code?: string | null;
  1810. error?: string | null;
  1811. public: boolean;
  1812. version?: string | null;
  1813. type: string;
  1814. name: string;
  1815. update_time?: string | null;
  1816. nickname?: string | null;
  1817. base_id?: string | null;
  1818. setting: Record<string, unknown>;
  1819. filament_id?: string | null;
  1820. setting_id?: string | null;
  1821. }
  1822. export interface SlicerSettingCreate {
  1823. type: string; // 'filament', 'print', or 'printer'
  1824. name: string;
  1825. base_id: string;
  1826. setting: Record<string, unknown>;
  1827. }
  1828. export interface SlicerSettingUpdate {
  1829. name?: string;
  1830. setting?: Record<string, unknown>;
  1831. }
  1832. export interface SlicerSettingDeleteResponse {
  1833. success: boolean;
  1834. message: string;
  1835. }
  1836. // Built-in filament fallback (static table from backend)
  1837. export interface BuiltinFilament {
  1838. filament_id: string;
  1839. name: string;
  1840. }
  1841. // Slice request/response — POST /library/files/{id}/slice and /archives/{id}/slice
  1842. //
  1843. // Two preset shapes are accepted per slot:
  1844. // - Legacy bare integer ids (`*_preset_id`) — pre-cloud-tier clients.
  1845. // - Source-aware refs (`*_preset: PresetRef`) — new SliceModal that picks
  1846. // across cloud / local / standard tiers. Source-aware refs win when both
  1847. // are present in the same payload.
  1848. export type PresetSource = 'orca_cloud' | 'cloud' | 'local' | 'standard';
  1849. export interface PresetRef {
  1850. source: PresetSource;
  1851. id: string;
  1852. }
  1853. /**
  1854. * Why a preset's effective values are unavailable.
  1855. *
  1856. * `sidecar_outdated` is the one that matters in practice: an install pulls its
  1857. * sidecar as `SIDECAR_TAG:-latest` regardless of which Bambuddy channel it is
  1858. * on, so a user can perfectly well be running a current Bambuddy against a
  1859. * sidecar that predates this endpoint. That has a one-line fix, and saying so
  1860. * beats a generic "could not read the values".
  1861. */
  1862. export type SlicerPresetValuesReason =
  1863. | 'ok'
  1864. | 'sidecar_outdated'
  1865. | 'sidecar_unavailable'
  1866. | 'not_configured'
  1867. | 'preset_unresolved';
  1868. export interface SlicerPresetValues {
  1869. /** False when the sidecar could not supply values; `values` is then empty. */
  1870. resolved: boolean;
  1871. /** Flattened key -> value map, in the string forms a process preset stores. */
  1872. values: Record<string, string | string[]>;
  1873. reason: SlicerPresetValuesReason;
  1874. }
  1875. export interface SliceRequest {
  1876. printer_preset_id?: number;
  1877. process_preset_id?: number;
  1878. filament_preset_id?: number;
  1879. printer_preset?: PresetRef;
  1880. process_preset?: PresetRef;
  1881. filament_preset?: PresetRef;
  1882. // Multi-color: one PresetRef per plate slot, in plate order. Always
  1883. // preferred over the singular `filament_preset` when both are sent; the
  1884. // backend validator promotes a singular into a one-element list when this
  1885. // is omitted, so legacy single-color clients keep working unchanged.
  1886. filament_presets?: PresetRef[];
  1887. // Per-slot filament colour as `#RRGGBB` / `#RRGGBBAA`, same plate order as
  1888. // `filament_presets` (#2977). Neither slicer stores a colour on a filament
  1889. // *preset* -- it is a per-project property -- so without this every sliced
  1890. // file records the CLI's built-in #00AE42 and the print dialog reports a
  1891. // colour mismatch against whatever is loaded in the AMS. An empty string in
  1892. // any position hands that slot back to the backend's fallback chain (the
  1893. // preset's own default_filament_colour, then the source plate's colour).
  1894. filament_colours?: string[];
  1895. plate?: number;
  1896. export_3mf?: boolean;
  1897. // Build-plate override (#1337). When omitted, the slicer uses the process
  1898. // preset's curr_bed_type as-is. A name from BambuStudio / OrcaSlicer's
  1899. // enum: "Cool Plate", "Engineering Plate", "High Temp Plate" (Smooth PEI),
  1900. // "Textured PEI Plate", "Supertack Plate", or OrcaSlicer's "Textured Cool
  1901. // Plate" (refused when Bambu Studio slices); the backend refuses others (#3359).
  1902. bed_type?: string | null;
  1903. // "Slice as designed" (#2611). 3MF only: slice using the file's embedded
  1904. // project_settings.config (the designer's own wall count, infill, etc.)
  1905. // instead of the picked profile triplet. The preset refs above are still
  1906. // required by the backend validator but go unused on this path.
  1907. use_embedded_settings?: boolean;
  1908. // Process settings the user edited in the slice modal's settings panel,
  1909. // already serialised into the string forms a process preset stores ("1" for
  1910. // a bool, "20%" for a percent, a list for the per-extruder vectors). Patched
  1911. // onto the resolved process JSON after the designer's carried tweaks, so an
  1912. // explicit choice here wins. Omitted when the panel is untouched.
  1913. process_overrides?: Record<string, string | string[]>;
  1914. // Design settings carried from the source 3MF (#2622) — a list of keys the
  1915. // file flags as changed from the system preset, not values.
  1916. design_overrides?: string[];
  1917. // Layout passes the slicer runs before slicing (#2548), both off by
  1918. // default because they move or rotate the objects the user laid out.
  1919. // Unlike the fields above these are CLI actions rather than profile
  1920. // values, so they apply on the embedded-settings path too.
  1921. auto_orient?: boolean;
  1922. auto_arrange?: boolean;
  1923. }
  1924. // GET /api/v1/slicer/presets — unified listing across cloud / local / standard.
  1925. export type SlicerCloudStatus = 'ok' | 'not_authenticated' | 'expired' | 'unreachable';
  1926. export interface UnifiedPreset {
  1927. id: string;
  1928. name: string;
  1929. source: PresetSource;
  1930. // Populated for the filament slot only — used by the SliceModal multi-color
  1931. // pre-pick to score presets against each plate slot's required (type,
  1932. // colour). Optional because the bundled / standard tier rarely carries a
  1933. // colour (colour is a runtime spool attribute on Bambu) and older API
  1934. // responses pre-date these fields entirely.
  1935. filament_type?: string | null;
  1936. filament_colour?: string | null;
  1937. // Printer-preset names a process / filament preset declares itself
  1938. // compatible with. Populated for the local tier (the slicer's own
  1939. // `compatible_printers`); null for cloud / standard. The SliceModal filters
  1940. // the process / filament dropdowns by the selected printer using this when
  1941. // present (#1325).
  1942. compatible_printers?: string[] | null;
  1943. // Printer presets only: the preset it was saved from, for the local and
  1944. // OrcaSlicer Cloud tiers (#3250).
  1945. inherits?: string | null;
  1946. }
  1947. export interface UnifiedPresetsBySlot {
  1948. printer: UnifiedPreset[];
  1949. process: UnifiedPreset[];
  1950. filament: UnifiedPreset[];
  1951. }
  1952. // What is loaded in each connected printer, for the SliceModal's
  1953. // "only connected printers" / "only loaded spools" filters (#3172).
  1954. export interface LoadedSpoolPreset {
  1955. preset_id: string;
  1956. preset_name: string;
  1957. preset_source: string;
  1958. tray_info_idx?: string | null;
  1959. }
  1960. export interface LoadedSpoolTray {
  1961. ams_id: number;
  1962. tray_id: number;
  1963. tray_type: string | null;
  1964. tray_sub_brands: string | null;
  1965. tray_color: string | null;
  1966. tray_info_idx: string | null;
  1967. exists: boolean | null;
  1968. state: number | null;
  1969. saved_preset: LoadedSpoolPreset | null;
  1970. }
  1971. export interface LoadedSpoolUnit {
  1972. id: number;
  1973. is_ams_ht: boolean;
  1974. trays: LoadedSpoolTray[];
  1975. }
  1976. export interface LoadedSpoolPrinter {
  1977. id: number;
  1978. name: string;
  1979. model: string | null;
  1980. ams: LoadedSpoolUnit[];
  1981. // Holders with a spool in them; external_holders counts all of them (two
  1982. // on a dual-nozzle printer, labelled left and right).
  1983. external: LoadedSpoolTray[];
  1984. external_holders: number;
  1985. }
  1986. export interface LoadedSpoolsResponse {
  1987. printers: LoadedSpoolPrinter[];
  1988. }
  1989. export interface UnifiedPresetsResponse {
  1990. // Priority order: local > orca_cloud > cloud > standard. No cross-tier
  1991. // dedup (apart from stock_aliases below) — every tier surfaces its full
  1992. // list so the user can pick from any source. The order drives auto-pick + visual group rendering only.
  1993. orca_cloud: UnifiedPresetsBySlot;
  1994. cloud: UnifiedPresetsBySlot;
  1995. local: UnifiedPresetsBySlot;
  1996. standard: UnifiedPresetsBySlot;
  1997. cloud_status: SlicerCloudStatus;
  1998. orca_cloud_status: SlicerCloudStatus;
  1999. // Standard presets that Bambu Cloud's stock list also has are left out of
  2000. // the standard tier (#3386); each "standard:<id>" maps to its cloud twin.
  2001. stock_aliases?: Record<string, PresetRef>;
  2002. }
  2003. // Slicer Pipelines (#1425) — named bundles of preset slots the SliceModal
  2004. // can apply in one click. PR A surfaces only the bundle; target_* and
  2005. // fanout_strategy round-trip from the backend but the UI doesn't yet expose
  2006. // them (they come alive in PR B / PR C).
  2007. export interface SlicerPipeline {
  2008. id: number;
  2009. name: string;
  2010. description: string | null;
  2011. printer_preset: PresetRef;
  2012. process_preset: PresetRef;
  2013. filament_presets: PresetRef[];
  2014. bed_type: string | null;
  2015. target_kind: 'specific_printer' | 'printer_class';
  2016. target_printer_id: number | null;
  2017. target_model_class: string | null;
  2018. fanout_strategy: 'max_parallel' | 'fill_one_first' | 'round_robin';
  2019. created_by: number | null;
  2020. created_at: string;
  2021. updated_at: string;
  2022. }
  2023. export interface SlicerPipelineCreateRequest {
  2024. name: string;
  2025. description?: string | null;
  2026. printer_preset: PresetRef;
  2027. process_preset: PresetRef;
  2028. filament_presets: PresetRef[];
  2029. bed_type?: string | null;
  2030. }
  2031. export type SlicerPipelineUpdateRequest = Partial<SlicerPipelineCreateRequest> & {
  2032. target_kind?: 'specific_printer' | 'printer_class';
  2033. // ``target_printer_id: 0`` means "clear the target" — the backend maps that
  2034. // to null. Use null in TypeScript for the same intent.
  2035. target_printer_id?: number | null;
  2036. target_model_class?: string | null;
  2037. fanout_strategy?: 'max_parallel' | 'fill_one_first' | 'round_robin';
  2038. };
  2039. export interface SlicerPipelinesListResponse {
  2040. pipelines: SlicerPipeline[];
  2041. }
  2042. // Slicer Pipeline runs (#1425 PR B + PR C)
  2043. export type PipelineEligibilityKind =
  2044. | 'printer_not_set'
  2045. | 'printer_not_found'
  2046. | 'printer_disabled'
  2047. | 'printer_offline'
  2048. | 'filament_type_mismatch'
  2049. | 'filament_color_mismatch'
  2050. | 'ams_slot_missing'
  2051. | 'filament_unverified'
  2052. | 'no_class_matches'
  2053. | 'class_not_set';
  2054. export interface PipelineEligibilityIssue {
  2055. kind: PipelineEligibilityKind;
  2056. slot_index: number | null;
  2057. expected: string | null;
  2058. actual: string | null;
  2059. }
  2060. export interface PipelinePerPrinterReport {
  2061. printer_id: number;
  2062. printer_name: string;
  2063. ok: boolean;
  2064. issues: PipelineEligibilityIssue[];
  2065. }
  2066. export interface PipelineEligibilityReport {
  2067. ok: boolean;
  2068. target_kind: 'specific_printer' | 'printer_class';
  2069. target_printer_id: number | null;
  2070. target_printer_name: string | null;
  2071. target_model_class: string | null;
  2072. issues: PipelineEligibilityIssue[];
  2073. printer_reports: PipelinePerPrinterReport[];
  2074. }
  2075. export interface PipelineJob {
  2076. id: number;
  2077. pipeline_run_id: number;
  2078. copy_index: number;
  2079. assigned_printer_id: number | null;
  2080. assigned_printer_name: string | null;
  2081. queue_entry_id: number | null;
  2082. status:
  2083. | 'pending'
  2084. | 'awaiting_printer'
  2085. | 'queued'
  2086. | 'printing'
  2087. | 'completed'
  2088. | 'failed'
  2089. | 'cancelled'
  2090. | 'unknown';
  2091. error_message: string | null;
  2092. dispatched_at: string | null;
  2093. completed_at: string | null;
  2094. }
  2095. export interface PipelineRun {
  2096. id: number;
  2097. pipeline_id: number | null;
  2098. pipeline_name: string | null;
  2099. source_library_file_id: number | null;
  2100. source_archive_id: number | null;
  2101. source_filename: string | null;
  2102. parent_run_id: number | null;
  2103. copies: number;
  2104. copies_completed: number;
  2105. copies_failed: number;
  2106. copies_cancelled: number;
  2107. copies_in_progress: number;
  2108. status:
  2109. | 'queued'
  2110. | 'slicing'
  2111. | 'dispatching'
  2112. | 'in_progress'
  2113. | 'completed'
  2114. | 'failed'
  2115. | 'partial_failure'
  2116. | 'cancelled';
  2117. slice_job_id: number | null;
  2118. sliced_library_file_id: number | null;
  2119. eligibility_overridden: boolean;
  2120. error_message: string | null;
  2121. created_by: number | null;
  2122. created_at: string;
  2123. started_at: string | null;
  2124. completed_at: string | null;
  2125. jobs: PipelineJob[];
  2126. target_kind: 'specific_printer' | 'printer_class' | null;
  2127. target_printer_id: number | null;
  2128. target_model_class: string | null;
  2129. fanout_strategy: 'max_parallel' | 'fill_one_first' | 'round_robin' | null;
  2130. }
  2131. export interface PipelineRunListResponse {
  2132. runs: PipelineRun[];
  2133. total: number;
  2134. }
  2135. export interface SliceResponse {
  2136. library_file_id: number;
  2137. name: string;
  2138. print_time_seconds: number;
  2139. filament_used_g: number;
  2140. filament_used_mm: number;
  2141. used_embedded_settings: boolean;
  2142. /** Why the result could not be written to the external folder the source
  2143. * lives in, and so went to managed storage instead. Null on every normal
  2144. * slice. Surfaced to the user — a file filed somewhere they aren't looking
  2145. * with no signal is what made #2810 invisible from the UI. */
  2146. external_write_fallback?: string | null;
  2147. }
  2148. export interface SliceArchiveResponse {
  2149. archive_id: number;
  2150. name: string;
  2151. print_time_seconds: number;
  2152. filament_used_g: number;
  2153. filament_used_mm: number;
  2154. used_embedded_settings: boolean;
  2155. }
  2156. // Background slice-job lifecycle. POST /slice returns 202 + this shape;
  2157. // the frontend polls /slice-jobs/{id} until status is terminal.
  2158. export type SliceJobStatus = 'pending' | 'running' | 'completed' | 'failed';
  2159. export interface SliceJobEnqueueResponse {
  2160. job_id: number;
  2161. status: SliceJobStatus;
  2162. status_url: string;
  2163. }
  2164. export interface SliceJobProgress {
  2165. /** Stage label emitted by the slicer ("Generating G-code", "Slicing finished"). */
  2166. stage: string;
  2167. total_percent: number;
  2168. plate_percent: number;
  2169. /** 1-indexed plate position; 0 means "all plates" / final completion. */
  2170. plate_index: number;
  2171. plate_count: number;
  2172. updated_at: number;
  2173. /** When the backend is in the cross-class slice-all loop (#1493), each
  2174. * per-plate sub-slice's progress is augmented with the loop position
  2175. * so the toast can show "Plate 2 of 5 — Generating G-code 47%". The
  2176. * fields are absent on a single-plate slice. */
  2177. multi_plate_index?: number;
  2178. multi_plate_count?: number;
  2179. }
  2180. export interface SliceJobState {
  2181. job_id: number;
  2182. status: SliceJobStatus;
  2183. kind: 'library_file' | 'archive';
  2184. source_id: number;
  2185. source_name: string;
  2186. created_at: string;
  2187. started_at: string | null;
  2188. completed_at: string | null;
  2189. /** Live progress fed by the sidecar's --pipe channel; null until the
  2190. * slicer emits its first frame (early "Initializing" phase) or when
  2191. * the sidecar doesn't support progress. */
  2192. progress: SliceJobProgress | null;
  2193. result?: SliceResponse | SliceArchiveResponse;
  2194. error_status?: number;
  2195. error_detail?: string;
  2196. }
  2197. // Local preset types (OrcaSlicer imports)
  2198. export interface LocalPreset {
  2199. id: number;
  2200. name: string;
  2201. preset_type: string;
  2202. source: string;
  2203. filament_type: string | null;
  2204. filament_vendor: string | null;
  2205. nozzle_temp_min: number | null;
  2206. nozzle_temp_max: number | null;
  2207. pressure_advance: string | null;
  2208. default_filament_colour: string | null;
  2209. filament_cost: string | null;
  2210. filament_density: string | null;
  2211. compatible_printers: string | null;
  2212. inherits: string | null;
  2213. version: string | null;
  2214. created_at: string;
  2215. updated_at: string;
  2216. }
  2217. export interface LocalPresetDetail extends LocalPreset {
  2218. setting: Record<string, unknown>;
  2219. }
  2220. export interface LocalPresetsResponse {
  2221. filament: LocalPreset[];
  2222. printer: LocalPreset[];
  2223. process: LocalPreset[];
  2224. }
  2225. export interface ImportResponse {
  2226. success: boolean;
  2227. imported: number;
  2228. skipped: number;
  2229. errors: string[];
  2230. }
  2231. export interface FieldOption {
  2232. value: string;
  2233. label: string;
  2234. }
  2235. export interface FieldDefinition {
  2236. key: string;
  2237. label: string;
  2238. type: 'text' | 'number' | 'boolean' | 'select';
  2239. category: string;
  2240. description?: string;
  2241. options?: FieldOption[];
  2242. unit?: string;
  2243. min?: number;
  2244. max?: number;
  2245. step?: number;
  2246. }
  2247. export interface FieldDefinitionsResponse {
  2248. version: string;
  2249. description: string;
  2250. fields: FieldDefinition[];
  2251. }
  2252. export interface CloudDevice {
  2253. dev_id: string;
  2254. name: string;
  2255. dev_model_name: string | null;
  2256. dev_product_name: string | null;
  2257. online: boolean;
  2258. }
  2259. // Smart Plug types
  2260. export interface SmartPlug {
  2261. id: number;
  2262. name: string;
  2263. plug_type: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  2264. ip_address: string | null; // Required for Tasmota
  2265. ha_entity_id: string | null; // Required for Home Assistant (e.g., "switch.printer_plug", "script.turn_on_printer")
  2266. // Home Assistant energy sensor entities (optional)
  2267. ha_power_entity: string | null;
  2268. ha_energy_today_entity: string | null;
  2269. ha_energy_total_entity: string | null;
  2270. // MQTT fields (required when plug_type="mqtt")
  2271. // Legacy field - kept for backward compatibility
  2272. mqtt_topic: string | null; // Deprecated, use mqtt_power_topic
  2273. mqtt_multiplier: number; // Deprecated, use mqtt_power_multiplier
  2274. // Power monitoring
  2275. mqtt_power_topic: string | null; // Topic for power data
  2276. mqtt_power_path: string | null; // e.g., "power_l1" or "data.power"
  2277. mqtt_power_multiplier: number; // Unit conversion for power
  2278. // Energy monitoring
  2279. mqtt_energy_topic: string | null; // Topic for energy data
  2280. mqtt_energy_path: string | null; // e.g., "energy_l1"
  2281. mqtt_energy_multiplier: number; // Unit conversion for energy
  2282. // State monitoring
  2283. mqtt_state_topic: string | null; // Topic for state data
  2284. mqtt_state_path: string | null; // e.g., "state_l1" for ON/OFF
  2285. mqtt_state_on_value: string | null; // What value means "ON" (e.g., "ON", "true", "1")
  2286. // REST/Webhook fields (required when plug_type="rest")
  2287. rest_on_url: string | null;
  2288. rest_on_body: string | null;
  2289. rest_off_url: string | null;
  2290. rest_off_body: string | null;
  2291. rest_method: string | null;
  2292. rest_headers: string | null;
  2293. rest_status_url: string | null;
  2294. rest_status_path: string | null;
  2295. rest_status_on_value: string | null;
  2296. rest_power_url: string | null;
  2297. rest_power_path: string | null;
  2298. rest_power_multiplier: number;
  2299. rest_energy_url: string | null;
  2300. rest_energy_path: string | null;
  2301. rest_energy_multiplier: number;
  2302. // Lifetime counter, separate from the daily one (#2539). A Shelly reports only
  2303. // this; Today and Yesterday are derived from its hourly snapshots.
  2304. rest_energy_total_path: string | null;
  2305. rest_energy_total_multiplier: number;
  2306. printer_id: number | null;
  2307. // #2629: only a plug that really feeds the printer may mark it offline when
  2308. // switched off. Accessory plugs follow the print cycle without powering it.
  2309. controls_printer_power: boolean;
  2310. enabled: boolean;
  2311. auto_on: boolean;
  2312. auto_off: boolean;
  2313. auto_off_persistent: boolean;
  2314. off_delay_mode: 'time' | 'temperature';
  2315. off_delay_minutes: number;
  2316. off_temp_threshold: number;
  2317. // #1349: auto-off after AMS drying completes.
  2318. auto_off_after_drying: boolean;
  2319. off_delay_after_drying_minutes: number;
  2320. username: string | null;
  2321. password: string | null;
  2322. // Power alerts
  2323. power_alert_enabled: boolean;
  2324. power_alert_high: number | null;
  2325. power_alert_low: number | null;
  2326. power_alert_last_triggered: string | null;
  2327. // Schedule
  2328. schedule_enabled: boolean;
  2329. schedule_on_time: string | null;
  2330. schedule_off_time: string | null;
  2331. // Visibility options
  2332. show_in_switchbar: boolean;
  2333. show_on_printer_card: boolean; // For scripts: show on printer card
  2334. // Status
  2335. last_state: string | null;
  2336. last_checked: string | null;
  2337. auto_off_executed: boolean; // True when auto-off was triggered after print
  2338. created_at: string;
  2339. updated_at: string;
  2340. }
  2341. export interface SmartPlugCreate {
  2342. name: string;
  2343. plug_type?: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  2344. ip_address?: string | null; // Required for Tasmota
  2345. ha_entity_id?: string | null; // Required for Home Assistant
  2346. // Home Assistant energy sensor entities (optional)
  2347. ha_power_entity?: string | null;
  2348. ha_energy_today_entity?: string | null;
  2349. ha_energy_total_entity?: string | null;
  2350. // MQTT fields (required when plug_type="mqtt")
  2351. // Legacy fields - kept for backward compatibility
  2352. mqtt_topic?: string | null;
  2353. mqtt_multiplier?: number;
  2354. // Power monitoring
  2355. mqtt_power_topic?: string | null;
  2356. mqtt_power_path?: string | null;
  2357. mqtt_power_multiplier?: number;
  2358. // Energy monitoring
  2359. mqtt_energy_topic?: string | null;
  2360. mqtt_energy_path?: string | null;
  2361. mqtt_energy_multiplier?: number;
  2362. // State monitoring
  2363. mqtt_state_topic?: string | null;
  2364. mqtt_state_path?: string | null;
  2365. mqtt_state_on_value?: string | null;
  2366. // REST fields
  2367. rest_on_url?: string | null;
  2368. rest_on_body?: string | null;
  2369. rest_off_url?: string | null;
  2370. rest_off_body?: string | null;
  2371. rest_method?: string | null;
  2372. rest_headers?: string | null;
  2373. rest_status_url?: string | null;
  2374. rest_status_path?: string | null;
  2375. rest_status_on_value?: string | null;
  2376. rest_power_url?: string | null;
  2377. rest_power_path?: string | null;
  2378. rest_power_multiplier?: number;
  2379. rest_energy_url?: string | null;
  2380. rest_energy_path?: string | null;
  2381. rest_energy_multiplier?: number;
  2382. rest_energy_total_path?: string | null;
  2383. rest_energy_total_multiplier?: number;
  2384. printer_id?: number | null;
  2385. // #2629
  2386. controls_printer_power?: boolean;
  2387. enabled?: boolean;
  2388. auto_on?: boolean;
  2389. auto_off?: boolean;
  2390. auto_off_persistent?: boolean;
  2391. off_delay_mode?: 'time' | 'temperature';
  2392. off_delay_minutes?: number;
  2393. off_temp_threshold?: number;
  2394. // #1349
  2395. auto_off_after_drying?: boolean;
  2396. off_delay_after_drying_minutes?: number;
  2397. username?: string | null;
  2398. password?: string | null;
  2399. // Power alerts
  2400. power_alert_enabled?: boolean;
  2401. power_alert_high?: number | null;
  2402. power_alert_low?: number | null;
  2403. // Schedule
  2404. schedule_enabled?: boolean;
  2405. schedule_on_time?: string | null;
  2406. schedule_off_time?: string | null;
  2407. // Visibility options
  2408. show_in_switchbar?: boolean;
  2409. show_on_printer_card?: boolean;
  2410. }
  2411. export interface SmartPlugUpdate {
  2412. name?: string;
  2413. plug_type?: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  2414. ip_address?: string | null;
  2415. ha_entity_id?: string | null;
  2416. // Home Assistant energy sensor entities (optional)
  2417. ha_power_entity?: string | null;
  2418. ha_energy_today_entity?: string | null;
  2419. ha_energy_total_entity?: string | null;
  2420. // MQTT fields (legacy)
  2421. mqtt_topic?: string | null;
  2422. mqtt_multiplier?: number;
  2423. // MQTT power fields
  2424. mqtt_power_topic?: string | null;
  2425. mqtt_power_path?: string | null;
  2426. mqtt_power_multiplier?: number;
  2427. // MQTT energy fields
  2428. mqtt_energy_topic?: string | null;
  2429. mqtt_energy_path?: string | null;
  2430. mqtt_energy_multiplier?: number;
  2431. // MQTT state fields
  2432. mqtt_state_topic?: string | null;
  2433. mqtt_state_path?: string | null;
  2434. mqtt_state_on_value?: string | null;
  2435. // REST fields
  2436. rest_on_url?: string | null;
  2437. rest_on_body?: string | null;
  2438. rest_off_url?: string | null;
  2439. rest_off_body?: string | null;
  2440. rest_method?: string | null;
  2441. rest_headers?: string | null;
  2442. rest_status_url?: string | null;
  2443. rest_status_path?: string | null;
  2444. rest_status_on_value?: string | null;
  2445. rest_power_url?: string | null;
  2446. rest_power_path?: string | null;
  2447. rest_power_multiplier?: number;
  2448. rest_energy_url?: string | null;
  2449. rest_energy_path?: string | null;
  2450. rest_energy_multiplier?: number;
  2451. rest_energy_total_path?: string | null;
  2452. rest_energy_total_multiplier?: number;
  2453. printer_id?: number | null;
  2454. // #2629
  2455. controls_printer_power?: boolean;
  2456. enabled?: boolean;
  2457. auto_on?: boolean;
  2458. auto_off?: boolean;
  2459. auto_off_persistent?: boolean;
  2460. off_delay_mode?: 'time' | 'temperature';
  2461. off_delay_minutes?: number;
  2462. off_temp_threshold?: number;
  2463. // #1349
  2464. auto_off_after_drying?: boolean;
  2465. off_delay_after_drying_minutes?: number;
  2466. username?: string | null;
  2467. password?: string | null;
  2468. // Power alerts
  2469. power_alert_enabled?: boolean;
  2470. power_alert_high?: number | null;
  2471. power_alert_low?: number | null;
  2472. // Schedule
  2473. schedule_enabled?: boolean;
  2474. schedule_on_time?: string | null;
  2475. schedule_off_time?: string | null;
  2476. // Visibility options
  2477. show_in_switchbar?: boolean;
  2478. show_on_printer_card?: boolean;
  2479. }
  2480. // Home Assistant entity for smart plug selection
  2481. export interface HAEntity {
  2482. entity_id: string;
  2483. friendly_name: string;
  2484. state: string | null;
  2485. domain: string; // "switch", "light", "input_boolean", "script"
  2486. }
  2487. // Home Assistant sensor entity for energy monitoring
  2488. export interface HASensorEntity {
  2489. entity_id: string;
  2490. friendly_name: string;
  2491. state: string | null;
  2492. unit_of_measurement: string | null; // "W", "kW", "kWh", "Wh"
  2493. }
  2494. export interface HATestConnectionResult {
  2495. success: boolean;
  2496. message: string | null;
  2497. error: string | null;
  2498. }
  2499. // A Home Assistant entity bound to a printer for display on its card (#1148, #448).
  2500. // Read-only: unlike a SmartPlug there is nothing here to switch.
  2501. export interface PrinterHASensor {
  2502. id: number;
  2503. printer_id: number;
  2504. name: string;
  2505. entity_id: string;
  2506. kind: 'binary' | 'numeric';
  2507. device_class: string | null; // HA's own class: "door", "temperature", ...
  2508. unit: string | null; // numeric sensors only
  2509. // What counts as needing attention. Binary sensors use alert_state, numeric
  2510. // ones the thresholds; all null means the sensor is display-only.
  2511. alert_state: 'on' | 'off' | null;
  2512. alert_above: number | null;
  2513. alert_below: number | null;
  2514. block_print: boolean; // hold the printer's queue while alerting
  2515. notify_on_alert: boolean;
  2516. show_on_printer_card: boolean;
  2517. sort_order: number;
  2518. last_state: string | null;
  2519. last_changed: string | null;
  2520. last_checked: string | null;
  2521. created_at: string;
  2522. updated_at: string;
  2523. }
  2524. export interface PrinterHASensorReading {
  2525. id: number;
  2526. name: string;
  2527. entity_id: string;
  2528. kind: 'binary' | 'numeric';
  2529. device_class: string | null;
  2530. unit: string | null;
  2531. state: string | null; // null when unreadable or not yet polled
  2532. value: number | null; // numeric sensors only
  2533. alerting: boolean;
  2534. block_print: boolean;
  2535. reachable: boolean;
  2536. last_changed: string | null;
  2537. }
  2538. export interface PrinterHASensorCreate {
  2539. printer_id: number;
  2540. name: string;
  2541. entity_id: string;
  2542. kind: 'binary' | 'numeric';
  2543. device_class?: string | null;
  2544. unit?: string | null;
  2545. alert_state?: 'on' | 'off' | null;
  2546. alert_above?: number | null;
  2547. alert_below?: number | null;
  2548. block_print?: boolean;
  2549. notify_on_alert?: boolean;
  2550. show_on_printer_card?: boolean;
  2551. sort_order?: number;
  2552. }
  2553. export type PrinterHASensorUpdate = Partial<Omit<PrinterHASensorCreate, 'printer_id'>>;
  2554. export interface LocationHASensor {
  2555. id: number;
  2556. location_id: number;
  2557. name: string;
  2558. entity_id: string;
  2559. kind: 'binary' | 'numeric';
  2560. device_class: string | null;
  2561. unit: string | null;
  2562. alert_state: 'on' | 'off' | null;
  2563. alert_above: number | null;
  2564. alert_below: number | null;
  2565. notify_on_alert: boolean;
  2566. show_on_card: boolean;
  2567. sort_order: number;
  2568. last_state: string | null;
  2569. last_changed: string | null;
  2570. last_checked: string | null;
  2571. created_at: string;
  2572. updated_at: string;
  2573. }
  2574. export interface LocationHASensorReading {
  2575. id: number;
  2576. name: string;
  2577. entity_id: string;
  2578. kind: 'binary' | 'numeric';
  2579. device_class: string | null;
  2580. unit: string | null;
  2581. state: string | null;
  2582. value: number | null;
  2583. alerting: boolean;
  2584. reachable: boolean;
  2585. alert_state: string | null;
  2586. alert_above: number | null;
  2587. alert_below: number | null;
  2588. last_changed: string | null;
  2589. show_on_card: boolean;
  2590. }
  2591. export interface LocationHASensorCreate {
  2592. location_id: number;
  2593. name: string;
  2594. entity_id: string;
  2595. kind: 'binary' | 'numeric';
  2596. device_class?: string | null;
  2597. unit?: string | null;
  2598. alert_state?: 'on' | 'off' | null;
  2599. alert_above?: number | null;
  2600. alert_below?: number | null;
  2601. notify_on_alert?: boolean;
  2602. show_on_card?: boolean;
  2603. sort_order?: number;
  2604. }
  2605. export type LocationHASensorUpdate = Partial<Omit<LocationHASensorCreate, 'location_id'>>;
  2606. // An entity offered by the binding picker.
  2607. export interface HADisplayEntity {
  2608. entity_id: string;
  2609. friendly_name: string;
  2610. state: string | null;
  2611. domain: string; // "binary_sensor" | "sensor"
  2612. device_class: string | null;
  2613. unit_of_measurement: string | null;
  2614. }
  2615. export interface SmartPlugEnergy {
  2616. power: number | null; // Current watts
  2617. voltage: number | null; // Volts
  2618. current: number | null; // Amps
  2619. today: number | null; // kWh used today
  2620. yesterday: number | null; // kWh used yesterday
  2621. total: number | null; // Total kWh
  2622. factor: number | null; // Power factor (0-1)
  2623. apparent_power: number | null; // VA
  2624. reactive_power: number | null; // VAr
  2625. }
  2626. export interface SmartPlugStatus {
  2627. state: string | null;
  2628. reachable: boolean;
  2629. device_name: string | null;
  2630. energy: SmartPlugEnergy | null;
  2631. }
  2632. export interface SmartPlugTestResult {
  2633. success: boolean;
  2634. state: string | null;
  2635. device_name: string | null;
  2636. }
  2637. // Tasmota Discovery types
  2638. export interface TasmotaScanStatus {
  2639. running: boolean;
  2640. scanned: number;
  2641. total: number;
  2642. }
  2643. export interface DiscoveredTasmotaDevice {
  2644. ip_address: string;
  2645. name: string;
  2646. module: number | null;
  2647. state: string | null;
  2648. discovered_at: string | null;
  2649. }
  2650. // Print Queue types
  2651. export interface PrintQueueItem {
  2652. id: number;
  2653. printer_id: number | null; // null = unassigned
  2654. target_model: string | null; // Target printer model for model-based assignment
  2655. target_location: string | null; // Target location filter for model-based assignment
  2656. required_filament_types: string[] | null; // Required filament types for model-based assignment
  2657. waiting_reason: string | null; // Why this job hasn't started yet (empty once it can)
  2658. // Cross-model alternatives (#671), in priority order. Empty for ordinary
  2659. // items. Present until dispatch resolves one, after which library_file_id and
  2660. // target_model name the candidate that actually ran.
  2661. variants?: Array<{
  2662. library_file_id: number;
  2663. filename: string;
  2664. target_model: string;
  2665. position: number;
  2666. }>;
  2667. // Either archive_id OR library_file_id must be set (archive created at print start)
  2668. archive_id: number | null;
  2669. library_file_id: number | null;
  2670. cost_center_id: number | null;
  2671. estimated_cost: number | null;
  2672. position: number;
  2673. scheduled_time: string | null;
  2674. require_previous_success: boolean;
  2675. auto_off_after: boolean;
  2676. manual_start: boolean; // Requires manual trigger to start (staged)
  2677. // Set by the dispatch scheduler when the assigned spool can't satisfy
  2678. // any required slot's grams (#1496). Surfaced on the queue row as a
  2679. // "filament short" badge; cleared on a successful ▶ click (live recheck).
  2680. filament_short: boolean;
  2681. // Persistent "Print Anyway" acknowledgement — once true the scheduler
  2682. // skips the deficit check for this item (#1698-followup). Set by the
  2683. // start route when skip_filament_check=true, or at queue creation if
  2684. // PrintModal's deficit warning was acknowledged.
  2685. skip_filament_check: boolean;
  2686. // True when the source archive carries the slicer's own live-resolved
  2687. // AMS-slot pick (extra_data.slicer_ams_mapping) — a reprint reuses that
  2688. // exact physical spool instead of re-deriving one from type/color.
  2689. archive_has_slicer_ams_mapping: boolean;
  2690. // A virtual printer's job not printed yet: the slicer's AMS pick it keeps
  2691. // for its archive, when made against this row's printer.
  2692. slicer_ams_mapping?: number[] | null;
  2693. ams_mapping: number[] | null; // AMS slot mapping for multi-color prints
  2694. 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
  2695. plate_id: number | null; // Plate ID for multi-plate 3MF files
  2696. // Print options
  2697. bed_levelling: CalibrationMode;
  2698. flow_cali: CalibrationMode;
  2699. vibration_cali: boolean;
  2700. layer_inspect: boolean;
  2701. timelapse: boolean;
  2702. use_ams: boolean;
  2703. nozzle_offset_cali: CalibrationMode;
  2704. // Ask for a post-print outcome verdict when this job completes (#1898)
  2705. confirm_outcome: boolean;
  2706. preheat_override: 'inherit' | 'on' | 'off';
  2707. preheat_chamber_target_override: number | null;
  2708. status: 'pending' | 'printing' | 'completed' | 'failed' | 'skipped' | 'cancelled';
  2709. started_at: string | null;
  2710. completed_at: string | null;
  2711. error_message: string | null;
  2712. created_at: string;
  2713. archive_name?: string | null;
  2714. archive_thumbnail?: string | null;
  2715. // True when the linked archive has been soft-deleted; archive_name /
  2716. // archive_thumbnail / downstream metadata are left null in that case so
  2717. // the UI doesn't 404-storm the now-missing endpoints (#1348 follow-up).
  2718. archive_deleted?: boolean;
  2719. library_file_name?: string | null;
  2720. library_file_thumbnail?: string | null;
  2721. printer_name?: string | null;
  2722. print_time_seconds?: number | null; // Estimated print time from archive or library file
  2723. filament_used_grams?: number | null; // Estimated print weight from archive or library file
  2724. filament_type?: string | null; // e.g. "PLA", "PETG"
  2725. filament_color?: string | null; // Hex RGBA from the slicer
  2726. bed_type?: string | null; // Build plate type for this print (per-plate accurate, #1281)
  2727. // User tracking (Issue #206)
  2728. created_by_id?: number | null;
  2729. created_by_username?: string | null;
  2730. // Batch grouping
  2731. batch_id?: number | null;
  2732. batch_name?: string | null;
  2733. // Shortest-job-first scheduling
  2734. been_jumped?: boolean;
  2735. // Auto-print G-code injection
  2736. gcode_injection?: boolean;
  2737. cleanup_library_after_dispatch?: boolean;
  2738. /** Which rack position each filament group prints from, on a nozzle-rack
  2739. * machine (#1784): `{ [group_id]: 1-based position }`. Re-checked against
  2740. * the live rack at dispatch; omit to have the dispatcher assign them. */
  2741. nozzle_rack_choice?: Record<number, number> | null;
  2742. /** Slots sent with a spool of another colour than the file asks for
  2743. * (#3279). Worked out when the job is sent; null when every slot got its
  2744. * colour or nothing could be compared. */
  2745. color_substitutions?: ColorSubstitution[] | null;
  2746. }
  2747. /** One slot printed in another colour than the file asked for (#3279). */
  2748. export interface ColorSubstitution {
  2749. slot_id: number;
  2750. type: string;
  2751. /** `#RRGGBB` the file asks for, after overrides. */
  2752. wanted: string;
  2753. /** `#RRGGBB` of the spool the slot was sent with. */
  2754. got: string;
  2755. tray: number;
  2756. }
  2757. export interface PrintBatchPlateTarget {
  2758. plate_id: number | null;
  2759. plate_name?: string | null;
  2760. quantity_target: number;
  2761. sort_order?: number;
  2762. }
  2763. export interface PrintBatchPlateProgress {
  2764. plate_id: number | null;
  2765. plate_name: string | null;
  2766. quantity_target: number;
  2767. dispatched: number;
  2768. remaining: number;
  2769. pending_count: number;
  2770. printing_count: number;
  2771. completed_count: number;
  2772. failed_count: number;
  2773. cancelled_count: number;
  2774. skipped_count: number;
  2775. /** Measured from finished runs; null until one has produced a cost. */
  2776. actual_cost: number | null;
  2777. estimated_remaining_cost: number | null;
  2778. filament_used_grams: number | null;
  2779. print_time_seconds: number;
  2780. /** False when this plate owes runs but has no queue item left to clone
  2781. * their configuration from, so queueing it could only fail (#2960). */
  2782. can_dispatch: boolean;
  2783. }
  2784. export interface PrintBatch {
  2785. id: number;
  2786. name: string;
  2787. archive_id: number | null;
  2788. library_file_id: number | null;
  2789. quantity: number;
  2790. status: string;
  2791. created_at: string;
  2792. completed_at: string | null;
  2793. created_by_id: number | null;
  2794. created_by_username: string | null;
  2795. project_id: number | null;
  2796. due_date: string | null;
  2797. notes: string | null;
  2798. /** Set when an integration (e.g. a shop connector) created the batch. */
  2799. external_source: string | null;
  2800. external_ref: string | null;
  2801. pending_count: number;
  2802. printing_count: number;
  2803. completed_count: number;
  2804. failed_count: number;
  2805. cancelled_count: number;
  2806. skipped_count: number;
  2807. /** False for batches created before per-plate targets existed (#342):
  2808. * they report progress but owe nothing and cannot be dispatched from. */
  2809. has_targets: boolean;
  2810. target_count: number;
  2811. remaining_count: number;
  2812. /** Of remaining_count, how many runs can actually be queued (#2960). */
  2813. dispatchable_count: number;
  2814. actual_cost: number | null;
  2815. estimated_remaining_cost: number | null;
  2816. filament_used_grams: number | null;
  2817. print_time_seconds: number;
  2818. plates: PrintBatchPlateProgress[];
  2819. }
  2820. export interface PrintQueueItemCreate {
  2821. printer_id?: number | null; // null = unassigned
  2822. target_model?: string | null; // Target printer model (mutually exclusive with printer_id)
  2823. target_location?: string | null; // Target location filter (only used with target_model)
  2824. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; tray_info_idx?: string; force_color_match?: boolean }> | null;
  2825. archive_id?: number | null;
  2826. library_file_id?: number | null;
  2827. scheduled_time?: string | null;
  2828. require_previous_success?: boolean;
  2829. auto_off_after?: boolean;
  2830. manual_start?: boolean; // Requires manual trigger to start (staged)
  2831. insert_at_top?: boolean; // Insert ahead of other pending items (one queue order across all printers, #3200)
  2832. insert_position?: number | null; // 1-indexed insertion position for priority queueing
  2833. // PrintModal "Print Anyway" on the deficit warning — persisted so the
  2834. // scheduler doesn't immediately re-flag this item (#1698-followup).
  2835. skip_filament_check?: boolean;
  2836. ams_mapping?: number[] | null; // AMS slot mapping for multi-color prints
  2837. plate_id?: number | null; // Plate ID for multi-plate 3MF files
  2838. // Print options
  2839. bed_levelling?: CalibrationMode;
  2840. flow_cali?: CalibrationMode;
  2841. vibration_cali?: boolean;
  2842. layer_inspect?: boolean;
  2843. timelapse?: boolean;
  2844. use_ams?: boolean;
  2845. nozzle_offset_cali?: CalibrationMode;
  2846. // Ask for a post-print outcome verdict when this job completes (#1898)
  2847. confirm_outcome?: boolean;
  2848. preheat_override?: 'inherit' | 'on' | 'off';
  2849. preheat_chamber_target_override?: number | null;
  2850. // Auto-print G-code injection
  2851. gcode_injection?: boolean;
  2852. // Batch: create multiple copies (creates a batch if > 1)
  2853. quantity?: number;
  2854. // Existing batch to add this item into (multi-plate auto-batch flow).
  2855. batch_id?: number | null;
  2856. // Project to associate the resulting archive with
  2857. project_id?: number;
  2858. cost_center_id?: number | null;
  2859. estimated_cost?: number | null;
  2860. // Delete transient uploaded library file after scheduler creates the archive
  2861. cleanup_library_after_dispatch?: boolean;
  2862. // Cross-model alternatives (#671): several sliced files, one job, whichever
  2863. // printer frees up first. Mutually exclusive with printer_id (a named printer
  2864. // defeats the point) and with archive_id/library_file_id (these ARE the files).
  2865. // Order is priority — index 0 wins when several printers are idle at once.
  2866. variants?: QueueVariantCreate[];
  2867. /** Which rack position each filament group prints from, on a nozzle-rack
  2868. * machine (#1784): `{ [group_id]: 1-based position }`. Re-checked against
  2869. * the live rack at dispatch; omit to have the dispatcher assign them. */
  2870. nozzle_rack_choice?: Record<number, number> | null;
  2871. }
  2872. /** One candidate file for a cross-model queue item (#671). */
  2873. export interface QueueVariantCreate {
  2874. library_file_id: number;
  2875. /** Read from the file's own sliced_for_model unless it declares none. */
  2876. target_model?: string | null;
  2877. plate_id?: number | null;
  2878. ams_mapping?: number[] | null;
  2879. nozzle_mapping?: number[] | null;
  2880. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; tray_info_idx?: string; force_color_match?: boolean }> | null;
  2881. }
  2882. export interface PrintBatchCreate {
  2883. name: string;
  2884. archive_id?: number | null;
  2885. library_file_id?: number | null;
  2886. /** When set, the listed pending items are assigned to the new batch
  2887. * (manual "Group as batch"). When omitted/empty, an empty batch is
  2888. * returned so the client can pass batch_id on subsequent addToQueue calls. */
  2889. item_ids?: number[];
  2890. /** Per-plate targets. Omitting them creates a plain grouping batch. */
  2891. plates?: PrintBatchPlateTarget[];
  2892. project_id?: number | null;
  2893. due_date?: string | null;
  2894. notes?: string | null;
  2895. }
  2896. export interface PrintBatchUpdate {
  2897. name?: string;
  2898. status?: 'active' | 'cancelled';
  2899. /** Replaces the full target set — a plate omitted here is removed. */
  2900. plates?: PrintBatchPlateTarget[];
  2901. project_id?: number | null;
  2902. due_date?: string | null;
  2903. notes?: string | null;
  2904. }
  2905. export interface PrintBatchDispatchRequest {
  2906. plate_id?: number | null;
  2907. only_plate?: boolean;
  2908. /** Cap on items created across all plates; omit to queue everything owed. */
  2909. limit?: number;
  2910. }
  2911. export interface PrintQueueItemUpdate {
  2912. printer_id?: number | null; // null = unassign
  2913. // A deliberate filament substitution in the mapping (#2799); see PrintModal.
  2914. skip_filament_check?: boolean;
  2915. target_model?: string | null; // Target printer model (mutually exclusive with printer_id)
  2916. target_location?: string | null; // Target location filter (only used with target_model)
  2917. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; tray_info_idx?: string; force_color_match?: boolean }> | null;
  2918. position?: number;
  2919. scheduled_time?: string | null;
  2920. require_previous_success?: boolean;
  2921. auto_off_after?: boolean;
  2922. manual_start?: boolean;
  2923. ams_mapping?: number[];
  2924. plate_id?: number | null; // Plate ID for multi-plate 3MF files
  2925. // Print options
  2926. bed_levelling?: CalibrationMode;
  2927. flow_cali?: CalibrationMode;
  2928. vibration_cali?: boolean;
  2929. layer_inspect?: boolean;
  2930. timelapse?: boolean;
  2931. use_ams?: boolean;
  2932. nozzle_offset_cali?: CalibrationMode;
  2933. // Ask for a post-print outcome verdict when this job completes (#1898)
  2934. confirm_outcome?: boolean;
  2935. preheat_override?: 'inherit' | 'on' | 'off';
  2936. preheat_chamber_target_override?: number | null;
  2937. // Auto-print G-code injection
  2938. gcode_injection?: boolean;
  2939. cost_center_id?: number | null;
  2940. estimated_cost?: number | null;
  2941. /** Which rack position each filament group prints from, on a nozzle-rack
  2942. * machine (#1784): `{ [group_id]: 1-based position }`. Re-checked against
  2943. * the live rack at dispatch; omit to have the dispatcher assign them. */
  2944. nozzle_rack_choice?: Record<number, number> | null;
  2945. }
  2946. export interface PrintQueueBulkUpdate {
  2947. item_ids: number[];
  2948. printer_id?: number | null;
  2949. scheduled_time?: string | null;
  2950. require_previous_success?: boolean;
  2951. auto_off_after?: boolean;
  2952. manual_start?: boolean;
  2953. // Print options
  2954. bed_levelling?: CalibrationMode;
  2955. flow_cali?: CalibrationMode;
  2956. vibration_cali?: boolean;
  2957. layer_inspect?: boolean;
  2958. timelapse?: boolean;
  2959. use_ams?: boolean;
  2960. nozzle_offset_cali?: CalibrationMode;
  2961. // Ask for a post-print outcome verdict when this job completes (#1898)
  2962. confirm_outcome?: boolean;
  2963. preheat_override?: 'inherit' | 'on' | 'off';
  2964. preheat_chamber_target_override?: number | null;
  2965. // Auto-print G-code injection
  2966. gcode_injection?: boolean;
  2967. cost_center_id?: number | null;
  2968. estimated_cost?: number | null;
  2969. }
  2970. export interface PrintQueueBulkUpdateResponse {
  2971. updated_count: number;
  2972. skipped_count: number;
  2973. message: string;
  2974. }
  2975. // MQTT Logging types
  2976. export interface MQTTLogEntry {
  2977. timestamp: string;
  2978. topic: string;
  2979. direction: 'in' | 'out';
  2980. payload: Record<string, unknown>;
  2981. }
  2982. export interface MQTTLogsResponse {
  2983. logging_enabled: boolean;
  2984. logs: MQTTLogEntry[];
  2985. }
  2986. // K-Profile types
  2987. export interface KProfile {
  2988. slot_id: number;
  2989. extruder_id: number;
  2990. nozzle_id: string;
  2991. nozzle_diameter: string;
  2992. filament_id: string;
  2993. name: string;
  2994. k_value: string;
  2995. n_coef: string;
  2996. ams_id: number;
  2997. tray_id: number;
  2998. setting_id: string | null;
  2999. }
  3000. export interface KProfileCreate {
  3001. slot_id?: number; // Storage slot, 0 for new profiles
  3002. extruder_id?: number;
  3003. nozzle_id: string;
  3004. nozzle_diameter: string;
  3005. filament_id: string;
  3006. name: string;
  3007. k_value: string;
  3008. n_coef?: string;
  3009. ams_id?: number;
  3010. tray_id?: number;
  3011. setting_id?: string | null;
  3012. }
  3013. export interface KProfileDelete {
  3014. slot_id: number; // cali_idx - calibration index to delete
  3015. extruder_id: number;
  3016. nozzle_id: string; // e.g., "HH00-0.4"
  3017. nozzle_diameter: string; // e.g., "0.4"
  3018. filament_id: string; // Bambu filament identifier
  3019. setting_id?: string | null; // Setting ID (for X1C series)
  3020. }
  3021. export interface KProfilesResponse {
  3022. profiles: KProfile[];
  3023. nozzle_diameter: string;
  3024. }
  3025. export interface KProfileNote {
  3026. setting_id: string;
  3027. note: string;
  3028. }
  3029. export interface KProfileNotesResponse {
  3030. notes: Record<string, string>; // setting_id -> note
  3031. }
  3032. // Slot Preset Mapping
  3033. export interface SlotPresetMapping {
  3034. ams_id: number;
  3035. tray_id: number;
  3036. preset_id: string;
  3037. preset_name: string;
  3038. // Filament id the slot was configured with alongside this preset; null for
  3039. // rows that predate it or whose writer did not know it (#3216).
  3040. tray_info_idx?: string | null;
  3041. }
  3042. // Filament types
  3043. export interface Filament {
  3044. id: number;
  3045. name: string;
  3046. type: string; // PLA, PETG, ABS, etc.
  3047. brand: string | null;
  3048. color: string | null;
  3049. color_hex: string | null;
  3050. cost_per_kg: number;
  3051. spool_weight_g: number;
  3052. currency: string;
  3053. density: number | null;
  3054. print_temp_min: number | null;
  3055. print_temp_max: number | null;
  3056. bed_temp_min: number | null;
  3057. bed_temp_max: number | null;
  3058. created_at: string;
  3059. updated_at: string;
  3060. }
  3061. // Notification Provider types
  3062. export type ProviderType = 'callmebot' | 'ntfy' | 'pushover' | 'telegram' | 'email' | 'discord' | 'webhook' | 'homeassistant' | 'bark' | 'gotify' | 'notify';
  3063. // How a Telegram provider collects the outcome verdict (#3046)
  3064. export type TelegramVerdictMode = 'buttons' | 'reactions' | 'both';
  3065. export interface NotificationProvider {
  3066. id: number;
  3067. name: string;
  3068. provider_type: ProviderType;
  3069. enabled: boolean;
  3070. config: Record<string, unknown>;
  3071. attach_photo: boolean;
  3072. // Print lifecycle events
  3073. on_print_start: boolean;
  3074. on_print_complete: boolean;
  3075. on_print_failed: boolean;
  3076. on_print_stopped: boolean;
  3077. on_print_progress: boolean;
  3078. on_print_missing_spool_assignment: boolean;
  3079. on_billing_charge_failed: boolean;
  3080. // Printer status events
  3081. on_printer_offline: boolean;
  3082. on_printer_error: boolean;
  3083. on_ai_failure_detection: boolean;
  3084. on_filament_low: boolean;
  3085. on_maintenance_due: boolean;
  3086. // AMS environmental alarms (regular AMS)
  3087. on_ams_humidity_high: boolean;
  3088. on_ams_temperature_high: boolean;
  3089. on_ams_drying_suspended: boolean;
  3090. // AMS-HT environmental alarms
  3091. on_ams_ht_humidity_high: boolean;
  3092. on_ams_ht_temperature_high: boolean;
  3093. // Build plate detection
  3094. on_plate_not_empty: boolean;
  3095. on_plate_clear_required: boolean;
  3096. // Post-print outcome confirmation (#1898)
  3097. on_print_confirm_request: boolean;
  3098. telegram_verdict_mode: TelegramVerdictMode;
  3099. // Bed cooled
  3100. on_bed_cooled: boolean;
  3101. on_ha_sensor_alert: boolean;
  3102. on_location_ha_sensor_alert: boolean;
  3103. // First layer complete
  3104. on_first_layer_complete: boolean;
  3105. on_print_pause_upcoming: boolean;
  3106. on_app_message: boolean;
  3107. // Inventory stock alerts
  3108. on_stock_reorder_alert: boolean;
  3109. on_stock_break_alert: boolean;
  3110. // Print queue events
  3111. on_queue_job_added: boolean;
  3112. on_queue_job_assigned: boolean;
  3113. on_queue_job_started: boolean;
  3114. on_queue_job_waiting: boolean;
  3115. on_queue_job_skipped: boolean;
  3116. on_queue_job_failed: boolean;
  3117. on_queue_completed: boolean;
  3118. // Quiet hours
  3119. quiet_hours_enabled: boolean;
  3120. quiet_hours_start: string | null;
  3121. quiet_hours_end: string | null;
  3122. // Daily digest
  3123. daily_digest_enabled: boolean;
  3124. daily_digest_time: string | null;
  3125. // Printer filter
  3126. printer_id: number | null;
  3127. // Status tracking
  3128. last_success: string | null;
  3129. last_error: string | null;
  3130. last_error_at: string | null;
  3131. // Timestamps
  3132. created_at: string;
  3133. updated_at: string;
  3134. }
  3135. export interface NotificationProviderCreate {
  3136. name: string;
  3137. provider_type: ProviderType;
  3138. enabled?: boolean;
  3139. config: Record<string, unknown>;
  3140. attach_photo?: boolean;
  3141. // Print lifecycle events
  3142. on_print_start?: boolean;
  3143. on_print_complete?: boolean;
  3144. on_print_failed?: boolean;
  3145. on_print_stopped?: boolean;
  3146. on_print_progress?: boolean;
  3147. on_print_missing_spool_assignment?: boolean;
  3148. on_billing_charge_failed?: boolean;
  3149. // Printer status events
  3150. on_printer_offline?: boolean;
  3151. on_printer_error?: boolean;
  3152. on_ai_failure_detection?: boolean;
  3153. on_filament_low?: boolean;
  3154. on_maintenance_due?: boolean;
  3155. // AMS environmental alarms (regular AMS)
  3156. on_ams_humidity_high?: boolean;
  3157. on_ams_temperature_high?: boolean;
  3158. on_ams_drying_suspended?: boolean;
  3159. // AMS-HT environmental alarms
  3160. on_ams_ht_humidity_high?: boolean;
  3161. on_ams_ht_temperature_high?: boolean;
  3162. // Build plate detection
  3163. on_plate_not_empty?: boolean;
  3164. on_plate_clear_required?: boolean;
  3165. // Post-print outcome confirmation (#1898)
  3166. on_print_confirm_request?: boolean;
  3167. telegram_verdict_mode?: TelegramVerdictMode;
  3168. // Bed cooled
  3169. on_bed_cooled?: boolean;
  3170. on_ha_sensor_alert?: boolean;
  3171. on_location_ha_sensor_alert?: boolean;
  3172. // First layer complete
  3173. on_first_layer_complete?: boolean;
  3174. on_print_pause_upcoming?: boolean;
  3175. on_app_message?: boolean;
  3176. // Inventory stock alerts
  3177. on_stock_reorder_alert?: boolean;
  3178. on_stock_break_alert?: boolean;
  3179. // Print queue events
  3180. on_queue_job_added?: boolean;
  3181. on_queue_job_assigned?: boolean;
  3182. on_queue_job_started?: boolean;
  3183. on_queue_job_waiting?: boolean;
  3184. on_queue_job_skipped?: boolean;
  3185. on_queue_job_failed?: boolean;
  3186. on_queue_completed?: boolean;
  3187. // Quiet hours
  3188. quiet_hours_enabled?: boolean;
  3189. quiet_hours_start?: string | null;
  3190. quiet_hours_end?: string | null;
  3191. // Daily digest
  3192. daily_digest_enabled?: boolean;
  3193. daily_digest_time?: string | null;
  3194. // Printer filter
  3195. printer_id?: number | null;
  3196. }
  3197. export interface NotificationProviderUpdate {
  3198. name?: string;
  3199. provider_type?: ProviderType;
  3200. enabled?: boolean;
  3201. config?: Record<string, unknown>;
  3202. attach_photo?: boolean;
  3203. // Print lifecycle events
  3204. on_print_start?: boolean;
  3205. on_print_complete?: boolean;
  3206. on_print_failed?: boolean;
  3207. on_print_stopped?: boolean;
  3208. on_print_progress?: boolean;
  3209. on_print_missing_spool_assignment?: boolean;
  3210. on_billing_charge_failed?: boolean;
  3211. // Printer status events
  3212. on_printer_offline?: boolean;
  3213. on_printer_error?: boolean;
  3214. on_ai_failure_detection?: boolean;
  3215. on_filament_low?: boolean;
  3216. on_maintenance_due?: boolean;
  3217. // AMS environmental alarms (regular AMS)
  3218. on_ams_humidity_high?: boolean;
  3219. on_ams_temperature_high?: boolean;
  3220. on_ams_drying_suspended?: boolean;
  3221. // AMS-HT environmental alarms
  3222. on_ams_ht_humidity_high?: boolean;
  3223. on_ams_ht_temperature_high?: boolean;
  3224. // Build plate detection
  3225. on_plate_not_empty?: boolean;
  3226. on_plate_clear_required?: boolean;
  3227. // Post-print outcome confirmation (#1898)
  3228. on_print_confirm_request?: boolean;
  3229. telegram_verdict_mode?: TelegramVerdictMode;
  3230. // Bed cooled
  3231. on_bed_cooled?: boolean;
  3232. on_ha_sensor_alert?: boolean;
  3233. on_location_ha_sensor_alert?: boolean;
  3234. // First layer complete
  3235. on_first_layer_complete?: boolean;
  3236. on_print_pause_upcoming?: boolean;
  3237. on_app_message?: boolean;
  3238. // Inventory stock alerts
  3239. on_stock_reorder_alert?: boolean;
  3240. on_stock_break_alert?: boolean;
  3241. // Print queue events
  3242. on_queue_job_added?: boolean;
  3243. on_queue_job_assigned?: boolean;
  3244. on_queue_job_started?: boolean;
  3245. on_queue_job_waiting?: boolean;
  3246. on_queue_job_skipped?: boolean;
  3247. on_queue_job_failed?: boolean;
  3248. on_queue_completed?: boolean;
  3249. // Quiet hours
  3250. quiet_hours_enabled?: boolean;
  3251. quiet_hours_start?: string | null;
  3252. quiet_hours_end?: string | null;
  3253. // Daily digest
  3254. daily_digest_enabled?: boolean;
  3255. daily_digest_time?: string | null;
  3256. // Printer filter
  3257. printer_id?: number | null;
  3258. }
  3259. // GitHub Backup types
  3260. export type ScheduleType = 'hourly' | 'daily' | 'weekly';
  3261. export type GitProviderType = 'github' | 'gitea' | 'forgejo' | 'gitlab';
  3262. /** How many cloud accounts a backup would collect presets from. Counts only —
  3263. * with auth enabled the accounts belong to individual users, so the backup
  3264. * administrator sees how many, never whose. */
  3265. export interface CloudAccountCounts {
  3266. bambu: number;
  3267. orca: number;
  3268. }
  3269. export interface GitHubBackupConfig {
  3270. id: number;
  3271. repository_url: string;
  3272. has_token: boolean;
  3273. branch: string;
  3274. provider: GitProviderType;
  3275. allow_insecure_http: boolean;
  3276. schedule_enabled: boolean;
  3277. schedule_type: ScheduleType;
  3278. backup_kprofiles: boolean;
  3279. backup_cloud_profiles: boolean;
  3280. backup_settings: boolean;
  3281. backup_spools: boolean;
  3282. backup_archives: boolean;
  3283. enabled: boolean;
  3284. last_backup_at: string | null;
  3285. last_backup_status: string | null;
  3286. last_backup_message: string | null;
  3287. last_backup_commit_sha: string | null;
  3288. next_scheduled_run: string | null;
  3289. created_at: string;
  3290. updated_at: string;
  3291. }
  3292. export interface GitHubBackupConfigCreate {
  3293. repository_url: string;
  3294. access_token: string;
  3295. branch?: string;
  3296. provider?: GitProviderType;
  3297. allow_insecure_http?: boolean;
  3298. schedule_enabled?: boolean;
  3299. schedule_type?: ScheduleType;
  3300. backup_kprofiles?: boolean;
  3301. backup_cloud_profiles?: boolean;
  3302. backup_settings?: boolean;
  3303. backup_spools?: boolean;
  3304. backup_archives?: boolean;
  3305. enabled?: boolean;
  3306. }
  3307. export interface GitHubBackupLog {
  3308. id: number;
  3309. config_id: number;
  3310. started_at: string;
  3311. completed_at: string | null;
  3312. status: string;
  3313. trigger: string;
  3314. commit_sha: string | null;
  3315. files_changed: number;
  3316. error_message: string | null;
  3317. }
  3318. export interface GitHubBackupStatus {
  3319. configured: boolean;
  3320. enabled: boolean;
  3321. is_running: boolean;
  3322. restore_running: boolean;
  3323. progress: string | null;
  3324. last_backup_at: string | null;
  3325. last_backup_status: string | null;
  3326. next_scheduled_run: string | null;
  3327. }
  3328. // Restore from a Git backup (#2656). Cloud profiles are absent deliberately —
  3329. // the backup collector never writes them, so there is nothing to restore.
  3330. export type RestoreCategory = 'kprofiles' | 'settings' | 'spools' | 'archives';
  3331. export interface GitHubCommitInfo {
  3332. sha: string;
  3333. message: string;
  3334. author: string;
  3335. date: string;
  3336. }
  3337. export interface GitHubCommitListResponse {
  3338. success: boolean;
  3339. message: string;
  3340. branch: string;
  3341. commits: GitHubCommitInfo[];
  3342. }
  3343. /**
  3344. * Values the server interpolates into a translated note or preview detail.
  3345. * Kept to strings and numbers on purpose — anything richer would have to be
  3346. * formatted server-side and could not be translated.
  3347. */
  3348. export type GitHubRestoreParams = Record<string, string | number>;
  3349. export interface GitHubRestorePreviewCategory {
  3350. category: RestoreCategory;
  3351. available: boolean;
  3352. item_count: number;
  3353. /** English rendering. Used as i18next's defaultValue, never shown on its own. */
  3354. detail: string | null;
  3355. /** Key under backup.restoreFromGit.details, or null when there is no caveat. */
  3356. detail_code: string | null;
  3357. detail_params: GitHubRestoreParams;
  3358. }
  3359. export interface GitHubRestorePreview {
  3360. success: boolean;
  3361. message: string;
  3362. ref: string;
  3363. commit: GitHubCommitInfo | null;
  3364. metadata_version: string | null;
  3365. categories: GitHubRestorePreviewCategory[];
  3366. }
  3367. export interface GitHubRestoreRequest {
  3368. ref?: string;
  3369. categories: RestoreCategory[];
  3370. overwrite_existing?: boolean;
  3371. }
  3372. /**
  3373. * One tally note, as a translation code plus its parameters (#2656).
  3374. *
  3375. * Same contract as {@link LocalBackupPathCheck} one card down: the server picks
  3376. * the code and supplies typed params, and the client renders
  3377. * ``t(`backup.restoreFromGit.notes.${code}`, { ...params, defaultValue: message })``.
  3378. * A code the client does not know yet falls back to the English `message`
  3379. * rather than showing the raw key.
  3380. */
  3381. export interface GitHubRestoreNote {
  3382. code: string;
  3383. params: GitHubRestoreParams;
  3384. message: string;
  3385. }
  3386. export interface GitHubRestoreCategoryResult {
  3387. restored: number;
  3388. skipped: number;
  3389. failed: number;
  3390. notes: GitHubRestoreNote[];
  3391. }
  3392. export interface GitHubRestoreResponse {
  3393. success: boolean;
  3394. message: string;
  3395. log_id: number | null;
  3396. ref: string | null;
  3397. results: Record<string, GitHubRestoreCategoryResult>;
  3398. }
  3399. export interface LocalBackupStatus {
  3400. enabled: boolean;
  3401. schedule: string;
  3402. time: string;
  3403. retention: number;
  3404. path: string;
  3405. default_path: string;
  3406. is_running: boolean;
  3407. last_backup_at: string | null;
  3408. last_status: string | null;
  3409. last_message: string | null;
  3410. next_run: string | null;
  3411. timezone: string;
  3412. }
  3413. export interface LocalBackupFile {
  3414. filename: string;
  3415. size: number;
  3416. created_at: string;
  3417. }
  3418. /** Result of writing a probe file into the configured backup directory (#2544). */
  3419. export interface LocalBackupPathCheck {
  3420. writable: boolean;
  3421. path: string;
  3422. /** 'ok' | 'sandboxed' | 'read_only' | 'permission_denied' | 'no_space' | 'not_a_directory' | 'missing' | 'error' */
  3423. code: string;
  3424. /** Raw OS error, shown as-is under the translated explanation. */
  3425. detail: string | null;
  3426. /** Copy-pasteable fix (systemd drop-in, compose snippet) — not translated. */
  3427. remedy: string | null;
  3428. message: string;
  3429. /** 'container_ephemeral' — writable, but the backups die with the container. */
  3430. warning: string | null;
  3431. }
  3432. export interface ObicoDetectionEvent {
  3433. printer_id: number;
  3434. task_name: string;
  3435. timestamp: string;
  3436. current_p: number;
  3437. score: number;
  3438. class: 'safe' | 'warning' | 'failure';
  3439. detections: number;
  3440. }
  3441. export interface ObicoStatus {
  3442. is_running: boolean;
  3443. last_error: string | null;
  3444. per_printer: Record<string, { class: string; frame_count: number; score: number }>;
  3445. thresholds: { low: number; high: number; pause?: number };
  3446. history: ObicoDetectionEvent[];
  3447. enabled: boolean;
  3448. ml_url: string;
  3449. sensitivity: 'low' | 'medium' | 'high';
  3450. action: 'notify' | 'pause' | 'pause_and_off';
  3451. poll_interval: number;
  3452. external_url_configured: boolean;
  3453. }
  3454. // Lightweight subset served under printers:read for the printer-card badge (#1546)
  3455. export interface ObicoPrinterStatus {
  3456. enabled: boolean;
  3457. // null = all printers are monitored
  3458. monitored_printers: number[] | null;
  3459. per_printer: Record<string, { class: string; frame_count: number; score: number }>;
  3460. // null = no error, or the viewer lacks settings:read (error strings can embed config URLs)
  3461. last_error: string | null;
  3462. }
  3463. export interface ObicoTestConnection {
  3464. ok: boolean;
  3465. status_code: number | null;
  3466. body: string | null;
  3467. error: string | null;
  3468. // Whether the ML API accepted the token. null = not determined (the health
  3469. // check failed first, or the token probe itself errored).
  3470. auth_ok: boolean | null;
  3471. }
  3472. // How sure Gadget must be before suggesting a warning or pause (API levels 1-5).
  3473. export type OctoEverywhereConfidence = 'lowest' | 'low' | 'medium' | 'high' | 'highest';
  3474. export interface OctoEverywhereDetection {
  3475. class: 'safe' | 'warning' | 'failure' | 'error' | 'unknown';
  3476. print_quality: number | null;
  3477. frame_count: number;
  3478. error?: string | null;
  3479. error_code: string | null;
  3480. }
  3481. export interface OctoEverywhereDetectionEvent {
  3482. timestamp: string;
  3483. printer_id: number;
  3484. class: OctoEverywhereDetection['class'];
  3485. print_quality: number | null;
  3486. }
  3487. export interface OctoEverywhereStatus {
  3488. enabled: boolean;
  3489. api_key_configured: boolean;
  3490. confidence: OctoEverywhereConfidence;
  3491. action: 'notify' | 'pause' | 'pause_and_off';
  3492. poll_interval: number;
  3493. is_running: boolean;
  3494. last_error: string | null;
  3495. last_error_code: string | null;
  3496. per_printer: Record<string, OctoEverywhereDetection>;
  3497. history: OctoEverywhereDetectionEvent[];
  3498. notifications: { configured: boolean; uncovered_printers: number[] };
  3499. }
  3500. export interface OctoEverywherePrinterStatus {
  3501. enabled: boolean;
  3502. // null = all printers are monitored
  3503. monitored_printers: number[] | null;
  3504. per_printer: Record<string, OctoEverywhereDetection>;
  3505. last_error: string | null;
  3506. last_error_code: string | null;
  3507. }
  3508. export interface OctoEverywhereTestConnection {
  3509. ok: boolean;
  3510. status_code: number | null;
  3511. error: string | null;
  3512. error_code: string | null;
  3513. }
  3514. export interface GitHubTestConnectionResponse {
  3515. success: boolean;
  3516. message: string;
  3517. repo_name: string | null;
  3518. permissions: Record<string, boolean> | null;
  3519. // true = confirmed private, false = confirmed public/internal,
  3520. // null = could not determine. Backend rejects save unless true.
  3521. is_private: boolean | null;
  3522. }
  3523. export interface GitHubBackupTriggerResponse {
  3524. success: boolean;
  3525. message: string;
  3526. log_id: number | null;
  3527. commit_sha: string | null;
  3528. files_changed: number;
  3529. }
  3530. export interface NotificationTestRequest {
  3531. provider_type: ProviderType;
  3532. config: Record<string, unknown>;
  3533. attach_photo?: boolean;
  3534. /** The saved provider being edited: its stored secrets fill in the placeholders. */
  3535. provider_id?: number;
  3536. }
  3537. export interface NotificationTestResponse {
  3538. success: boolean;
  3539. message: string;
  3540. }
  3541. // Provider-specific config types for reference
  3542. export interface CallMeBotConfig {
  3543. phone: string;
  3544. apikey: string;
  3545. }
  3546. export interface NtfyConfig {
  3547. server?: string;
  3548. topic: string;
  3549. auth_token?: string | null;
  3550. }
  3551. export interface PushoverConfig {
  3552. user_key: string;
  3553. app_token: string;
  3554. priority?: number;
  3555. }
  3556. export interface NotifyConfig {
  3557. device_id: string;
  3558. token: string;
  3559. icon_url?: string;
  3560. group_type?: string;
  3561. live_activities?: boolean;
  3562. lock_screen_widgets?: boolean;
  3563. live_activity_privacy?: boolean;
  3564. live_activity_stage?: boolean;
  3565. live_activity_style?: 'bar' | 'segments' | 'none';
  3566. live_activity_metrics?: ('progress' | 'eta' | 'layers' | 'nozzle' | 'bed' | 'chamber')[];
  3567. live_activity_button_url?: string;
  3568. live_activity_symbol?: string;
  3569. live_activity_tint?: string;
  3570. time_sensitive?: boolean;
  3571. }
  3572. export interface TelegramConfig {
  3573. bot_token: string;
  3574. chat_id: string;
  3575. }
  3576. export interface EmailConfig {
  3577. smtp_server: string;
  3578. smtp_port?: number;
  3579. username: string;
  3580. password: string;
  3581. from_email: string;
  3582. to_email: string;
  3583. use_tls?: boolean;
  3584. }
  3585. // Notification Template types
  3586. export interface NotificationTemplate {
  3587. id: number;
  3588. event_type: string;
  3589. name: string;
  3590. title_template: string;
  3591. body_template: string;
  3592. is_default: boolean;
  3593. created_at: string;
  3594. updated_at: string;
  3595. }
  3596. export interface NotificationTemplateUpdate {
  3597. title_template?: string;
  3598. body_template?: string;
  3599. }
  3600. export interface EventVariablesResponse {
  3601. event_type: string;
  3602. event_name: string;
  3603. variables: string[];
  3604. supports_photo: boolean;
  3605. }
  3606. export interface TemplatePreviewRequest {
  3607. event_type: string;
  3608. title_template: string;
  3609. body_template: string;
  3610. }
  3611. export interface TemplatePreviewResponse {
  3612. title: string;
  3613. body: string;
  3614. }
  3615. // Notification Log types
  3616. export interface NotificationLogEntry {
  3617. id: number;
  3618. provider_id: number;
  3619. provider_name: string | null;
  3620. provider_type: string | null;
  3621. event_type: string;
  3622. title: string;
  3623. message: string;
  3624. success: boolean;
  3625. error_message: string | null;
  3626. printer_id: number | null;
  3627. printer_name: string | null;
  3628. created_at: string;
  3629. }
  3630. export interface NotificationLogStats {
  3631. total: number;
  3632. success_count: number;
  3633. failure_count: number;
  3634. by_event_type: Record<string, number>;
  3635. by_provider: Record<string, number>;
  3636. }
  3637. // Spoolman types
  3638. export interface SpoolmanStatus {
  3639. enabled: boolean;
  3640. connected: boolean;
  3641. url: string | null;
  3642. native_tags?: boolean; // Spoolman 0.27+ links tags natively
  3643. }
  3644. export interface SpoolmanTagMigrationReport {
  3645. dry_run: boolean;
  3646. moved: number[];
  3647. already: number;
  3648. slot_ids: number;
  3649. conflicts: Array<{ spool_id: number; tag: string; holder: number }>; // holder -1: a filament holds the tag
  3650. }
  3651. export interface SkippedSpool {
  3652. location: string;
  3653. reason: string;
  3654. filament_type: string | null;
  3655. color: string | null;
  3656. }
  3657. export interface SpoolmanSyncResult {
  3658. success: boolean;
  3659. synced_count: number;
  3660. skipped_count: number;
  3661. skipped: SkippedSpool[];
  3662. errors: string[];
  3663. }
  3664. export interface UnlinkedSpool {
  3665. id: number;
  3666. filament_name: string | null;
  3667. filament_vendor: string | null;
  3668. filament_material: string | null;
  3669. filament_color_hex: string | null;
  3670. remaining_weight: number | null;
  3671. location: string | null;
  3672. }
  3673. export interface LinkedSpoolInfo {
  3674. id: number;
  3675. remaining_weight: number | null;
  3676. filament_weight: number | null;
  3677. }
  3678. export interface LinkedSpoolsMap {
  3679. linked: Record<string, LinkedSpoolInfo>; // tag (uppercase) -> spool info
  3680. }
  3681. export interface SpoolmanVendor {
  3682. id: number;
  3683. name: string;
  3684. }
  3685. export interface SpoolmanFilamentEntry {
  3686. id: number;
  3687. name: string;
  3688. material: string | null;
  3689. color_hex: string | null;
  3690. color_name: string | null;
  3691. weight: number | null;
  3692. spool_weight: number | null;
  3693. vendor: SpoolmanVendor | null;
  3694. }
  3695. // Inventory types
  3696. // Label printing (#809). Mirror of backend.app.services.label_renderer.TemplateName.
  3697. export type SpoolLabelTemplate =
  3698. | 'ams_holder_74x33'
  3699. | 'ams_holder_75x55'
  3700. | 'box_40x30'
  3701. | 'box_62x29'
  3702. | 'avery_5160'
  3703. | 'avery_l7160';
  3704. // Mirror of backend.app.services.label_renderer.LabelField, in print order (#2981).
  3705. export const SPOOL_LABEL_FIELDS = [
  3706. 'brand',
  3707. 'material',
  3708. 'hex',
  3709. 'name',
  3710. 'location',
  3711. 'material_number',
  3712. 'temps',
  3713. 'weight',
  3714. 'note',
  3715. 'added',
  3716. 'qr',
  3717. 'spool_id',
  3718. ] as const;
  3719. export type SpoolLabelField = (typeof SPOOL_LABEL_FIELDS)[number];
  3720. // Mirror of DEFAULT_LABEL_FIELDS: what a label carried before fields were selectable.
  3721. export const DEFAULT_SPOOL_LABEL_FIELDS: SpoolLabelField[] = [
  3722. 'brand',
  3723. 'material',
  3724. 'hex',
  3725. 'name',
  3726. 'location',
  3727. 'qr',
  3728. 'spool_id',
  3729. ];
  3730. // A sheet of identical labels in a grid, in millimetres (#3296). Mirror of
  3731. // backend.app.schemas.label_template.SheetLayoutSpec.
  3732. export type LabelPageSize = 'a4' | 'letter';
  3733. export interface LabelSheetLayout {
  3734. page: LabelPageSize;
  3735. label_w_mm: number;
  3736. label_h_mm: number;
  3737. cols: number;
  3738. rows: number;
  3739. top_mm: number;
  3740. left_mm: number;
  3741. col_gap_mm: number;
  3742. row_gap_mm: number;
  3743. }
  3744. // A custom sheet saved under a name, shared by everyone on the install.
  3745. export interface SavedLabelTemplate {
  3746. id: number;
  3747. name: string;
  3748. layout: LabelSheetLayout;
  3749. created_at: string;
  3750. updated_at: string;
  3751. }
  3752. // A built-in template, or "custom" with the sheet itself in ``layout``.
  3753. export type SpoolLabelRequestTemplate = SpoolLabelTemplate | 'custom';
  3754. export interface PrintSpoolLabelsRequest {
  3755. spool_ids: number[];
  3756. template: SpoolLabelRequestTemplate;
  3757. layout?: LabelSheetLayout;
  3758. monochrome: boolean;
  3759. starting_position: number;
  3760. fields?: SpoolLabelField[];
  3761. format?: 'pdf' | 'png';
  3762. dpi?: 203 | 300 | 600;
  3763. }
  3764. export interface PreviewSpoolLabelRequest {
  3765. spool_id: number;
  3766. template: SpoolLabelRequestTemplate;
  3767. layout?: LabelSheetLayout;
  3768. monochrome: boolean;
  3769. fields: SpoolLabelField[];
  3770. }
  3771. export interface InventorySpool {
  3772. id: number;
  3773. material: string;
  3774. subtype: string | null;
  3775. color_name: string | null;
  3776. // True when color_name was synthesised from subtype because Spoolman has no
  3777. // stored value (Spoolman-backed inventory only). The edit form uses this to
  3778. // leave the input blank, so the user doesn't round-trip the synth value
  3779. // back to Spoolman as if it were a real user-set color_name (#1319).
  3780. color_name_is_synthesized?: boolean;
  3781. rgba: string | null;
  3782. // Multi-colour gradient stops (#1154): comma-separated 6/8-char hex.
  3783. extra_colors: string | null;
  3784. // Visual effect overlay: sparkle | wood | marble | glow | matte.
  3785. effect_type: string | null;
  3786. brand: string | null;
  3787. label_weight: number;
  3788. core_weight: number;
  3789. // Spoolman-backed inventory only: true when the spool has no tare of its
  3790. // own and core_weight is the filament type's. Absent for local spools (#2908).
  3791. core_weight_is_inherited?: boolean;
  3792. core_weight_catalog_id: number | null;
  3793. weight_used: number;
  3794. // Anchor for the resettable "Total Consumed" display (#1390). The
  3795. // counter shown on the Inventory page is `weight_used - weight_used_baseline`;
  3796. // remaining is still `label_weight - weight_used`, so "Reset usage to 0"
  3797. // zeroes the counter without disturbing remaining. Optional for back-compat
  3798. // with rows from a pre-migration DB snapshot — default to 0.
  3799. weight_used_baseline?: number;
  3800. slicer_filament: string | null;
  3801. slicer_filament_name: string | null;
  3802. nozzle_temp_min: number | null;
  3803. nozzle_temp_max: number | null;
  3804. note: string | null;
  3805. added_full: boolean | null;
  3806. last_used: string | null;
  3807. // Spoolman mode: when the spool was first printed with (#3407).
  3808. first_used?: string | null;
  3809. // Last drying (#2863): stamped when an AMS drying run of at least half its
  3810. // length ends, or set by hand. Temperature and hours are null when unknown.
  3811. last_dried_at?: string | null;
  3812. last_dried_temp?: number | null;
  3813. last_dried_hours?: number | null;
  3814. encode_time: string | null;
  3815. tag_uid: string | null;
  3816. tray_uuid: string | null;
  3817. data_origin: string | null;
  3818. tag_type: string | null;
  3819. archived_at: string | null;
  3820. created_at: string;
  3821. updated_at: string;
  3822. cost_per_kg: number | null;
  3823. // Spoolman mode: what prints are charged per kg, the spool's own price or
  3824. // else its filament's. Display only; the form edits cost_per_kg.
  3825. effective_cost_per_kg?: number | null;
  3826. last_scale_weight: number | null;
  3827. last_weighed_at: string | null;
  3828. // User-defined category + per-spool low-stock threshold override (#729).
  3829. category: string | null;
  3830. low_stock_threshold_pct: number | null;
  3831. // Internal material / article number (#2870) — the purchasing identifier
  3832. // shared by all spools of the same product.
  3833. material_number: string | null;
  3834. k_profiles?: SpoolKProfile[];
  3835. storage_location?: string | null;
  3836. location_id?: number | null;
  3837. // Supplier assignments (#2988). Absent in Spoolman mode — Spoolman's
  3838. // vendor is the manufacturer, not the seller, so there is no mapping.
  3839. suppliers?: SpoolSupplierLink[];
  3840. }
  3841. // ── Suppliers (#2988) ──────────────────────────────────────────────────────
  3842. /** Where filament is bought — distinct from brand (who made it). */
  3843. export interface Supplier {
  3844. id: number;
  3845. name: string;
  3846. website: string | null;
  3847. customer_number: string | null;
  3848. note: string | null;
  3849. /** Spools referencing this supplier; a referenced supplier cannot be deleted. */
  3850. spool_count: number;
  3851. created_at: string;
  3852. updated_at: string;
  3853. }
  3854. export interface SupplierInput {
  3855. name: string;
  3856. website?: string | null;
  3857. customer_number?: string | null;
  3858. note?: string | null;
  3859. }
  3860. /** One spool-to-supplier assignment as written by the spool dialog. */
  3861. export interface SpoolSupplierLinkInput {
  3862. supplier_id: number;
  3863. /** The supplier's own article number — NOT the internal material number. */
  3864. supplier_article_number?: string | null;
  3865. /** Quoted price for comparison — never the cost basis (spool.cost_per_kg). */
  3866. quoted_price_per_kg?: number | null;
  3867. /** Marks where this concrete spool was actually bought. */
  3868. is_purchase_source?: boolean;
  3869. }
  3870. export interface SpoolSupplierLink {
  3871. id: number;
  3872. supplier_id: number;
  3873. supplier_name: string;
  3874. supplier_article_number: string | null;
  3875. quoted_price_per_kg: number | null;
  3876. is_purchase_source: boolean;
  3877. }
  3878. /** Per-supplier inventory aggregate (#2988), purchase-source spools only. */
  3879. export interface SupplierStats {
  3880. supplier_id: number;
  3881. supplier_name: string;
  3882. spool_count: number;
  3883. remaining_g: number;
  3884. consumed_g: number;
  3885. cost: number;
  3886. }
  3887. /** Per-material-number inventory aggregate (#2870). */
  3888. export interface MaterialNumberStats {
  3889. material_number: string;
  3890. spool_count: number;
  3891. remaining_g: number;
  3892. consumed_g: number;
  3893. cost: number;
  3894. }
  3895. export interface SpoolmanBulkCreateResult {
  3896. created: InventorySpool[];
  3897. requested_count: number;
  3898. failed_count: number;
  3899. }
  3900. // ── CSV import/export (#1576) ──────────────────────────────────────────────
  3901. /** One row's outcome from the import preview / real import. */
  3902. export interface CsvImportRow {
  3903. row_number: number;
  3904. status: 'valid' | 'error' | 'skipped';
  3905. /** The id the spool is created with (#3520); null gets the next free one. */
  3906. keeps_id?: number | null;
  3907. reason: string | null;
  3908. material: string | null;
  3909. brand: string | null;
  3910. color_name: string | null;
  3911. rgba: string | null;
  3912. /** rgba/extra_colors/effect_type were filled from the Color Catalog. */
  3913. resolved_color: boolean;
  3914. /** The catalog match came from a different material's variant (no exact
  3915. * material match). Shown as a warning in the preview. */
  3916. cross_material_color: boolean;
  3917. /** An active spool with the same material+brand+color already exists.
  3918. * Informational only — the import still creates the row. */
  3919. duplicate_of_existing: boolean;
  3920. }
  3921. /** Dry-run preview: per-row classification, no rows written. */
  3922. export interface CsvImportPreview {
  3923. columns: string[];
  3924. total: number;
  3925. valid_count: number;
  3926. error_count: number;
  3927. skipped_count: number;
  3928. rows: CsvImportRow[];
  3929. warnings: string[];
  3930. }
  3931. /** Summary returned after a real (non-dry-run) import. */
  3932. export interface CsvImportResult {
  3933. created: number;
  3934. skipped: number;
  3935. errors: number;
  3936. error_rows: CsvImportRow[];
  3937. }
  3938. export interface SpoolUsageRecord {
  3939. id: number;
  3940. // null: the spool was deleted, its usage kept
  3941. spool_id: number | null;
  3942. // Spoolman mode: the Spoolman spool charged (#3407); spool_id is null then.
  3943. spoolman_spool_id?: number | null;
  3944. printer_id: number | null;
  3945. print_name: string | null;
  3946. weight_used: number;
  3947. percent_used: number;
  3948. status: string;
  3949. cost: number | null;
  3950. created_at: string;
  3951. }
  3952. export interface SpoolKProfile {
  3953. id: number;
  3954. spool_id: number;
  3955. printer_id: number;
  3956. extruder: number;
  3957. nozzle_diameter: string;
  3958. nozzle_type: string | null;
  3959. k_value: number;
  3960. name: string | null;
  3961. cali_idx: number | null;
  3962. setting_id: string | null;
  3963. created_at: string;
  3964. }
  3965. export interface SpoolKProfileInput {
  3966. printer_id: number;
  3967. extruder?: number;
  3968. nozzle_diameter?: string;
  3969. nozzle_type?: string | null;
  3970. k_value: number;
  3971. name?: string | null;
  3972. cali_idx?: number | null;
  3973. setting_id?: string | null;
  3974. }
  3975. /**
  3976. * One per-printer-model override of a spool's slicer filament preset.
  3977. *
  3978. * A cloud or Orca preset is bound to a printer model ("@BBL X1C"), so the
  3979. * spool's single `slicer_filament` is wrong as soon as the spool is used on a
  3980. * second model. `nozzle_diameter` is "" for the model's own default and a bare
  3981. * decimal ("0.2") for a per-hotend exception; the backend resolves
  3982. * exact (model, diameter) -> (model, "") -> the spool's own preset.
  3983. */
  3984. export interface SlotSpoolDefaults {
  3985. slicer_filament: string | null;
  3986. slicer_filament_name: string | null;
  3987. cali_idx: number | null;
  3988. k_value: number | null;
  3989. profile_name: string | null;
  3990. extruder: number | null;
  3991. nozzle_diameter: string;
  3992. }
  3993. export interface SpoolFilamentPresetInput {
  3994. printer_model: string;
  3995. nozzle_diameter: string;
  3996. slicer_filament: string | null;
  3997. slicer_filament_name: string | null;
  3998. }
  3999. export interface SpoolFilamentPreset extends SpoolFilamentPresetInput {
  4000. id: number;
  4001. spool_id: number;
  4002. created_at: string;
  4003. }
  4004. /**
  4005. * What a new spool of one product starts with (#1326): the slicer preset, the
  4006. * per-model preset overrides and the K profiles. `color_name` "" is the
  4007. * default for every colour of the product; one with a colour wins over it per
  4008. * preset and per hotend. Shared by both inventory modes.
  4009. */
  4010. export interface ProfileDefaultKey {
  4011. brand: string;
  4012. material: string;
  4013. subtype: string;
  4014. color_name: string;
  4015. }
  4016. export interface ProfileDefaultInput extends ProfileDefaultKey {
  4017. slicer_filament: string | null;
  4018. slicer_filament_name: string | null;
  4019. presets: SpoolFilamentPresetInput[];
  4020. k_profiles: SpoolKProfileInput[];
  4021. }
  4022. export interface ProfileDefault extends ProfileDefaultInput {
  4023. id: number;
  4024. updated_at: string;
  4025. }
  4026. /** Both levels of a product's default merged, as a create applies them. */
  4027. export interface ResolvedProfileDefault {
  4028. slicer_filament: string | null;
  4029. slicer_filament_name: string | null;
  4030. presets: SpoolFilamentPresetInput[];
  4031. k_profiles: SpoolKProfileInput[];
  4032. default_ids: number[];
  4033. }
  4034. /** One inventory-bound AMS slot, as returned by `/printers/{id}/inventory-remain`. */
  4035. export interface SlotMaterial {
  4036. ams_id: number;
  4037. tray_id: number;
  4038. global_tray_id: number;
  4039. /** Opaque grouping key from the backend. Two slots back each other up under
  4040. * AMS Filament Backup only when both `material_key` and `extruder` match.
  4041. * Never parse it — the format belongs to the backend's identity rule. */
  4042. material_key: string;
  4043. remaining_g: number;
  4044. /** 0 = right / single nozzle, 1 = left. */
  4045. extruder: number;
  4046. /** How the bound spool should be *named* — display only, never matched on.
  4047. * The printer has no brand field and reports no sub-brand for a
  4048. * third-party spool, so this is the only place a slot's real identity
  4049. * exists. Null when the binding resolves to a spool we cannot describe. */
  4050. spool?: SlotSpoolIdentity | null;
  4051. /** Per-kg rate a print off this spool is charged at; null when unpriced,
  4052. * which is charged at the default rate. Optional for an older backend. */
  4053. cost_per_kg?: number | null;
  4054. }
  4055. /** Display identity of an inventory-bound slot. See `SlotMaterial.spool`. */
  4056. export interface SlotSpoolIdentity {
  4057. brand: string | null;
  4058. material: string | null;
  4059. subtype: string | null;
  4060. color_name: string | null;
  4061. rgba: string | null;
  4062. /** Comma-separated hex stops for a multi-colour spool, and the effect
  4063. * overlay — the two things a tray record cannot carry, so a slot swatch
  4064. * can be drawn the way the inventory row draws it (#3159).
  4065. *
  4066. * Optional rather than required: the backend sends both keys on every
  4067. * binding, but a frontend running against an older one gets neither, and
  4068. * every reader here already falls back to a solid swatch. */
  4069. extra_colors?: string | null;
  4070. effect_type?: string | null;
  4071. }
  4072. export interface InventoryRemainResponse {
  4073. /** Currently-loaded, inventory-bound slots only — drives the prefer-lowest sort. */
  4074. inventory_remain_g: Record<string, number>;
  4075. /** Every inventory binding on the printer, with identity + extruder side. */
  4076. slot_materials: SlotMaterial[];
  4077. }
  4078. export interface SpoolAssignment {
  4079. id: number;
  4080. spool_id: number;
  4081. printer_id: number;
  4082. printer_name: string | null;
  4083. ams_id: number;
  4084. tray_id: number;
  4085. fingerprint_color: string | null;
  4086. fingerprint_type: string | null;
  4087. spool?: InventorySpool | null;
  4088. configured: boolean;
  4089. pending_config?: boolean; // Slot was empty at assign time; will configure on insert
  4090. created_at: string;
  4091. ams_label?: string | null; // User-defined friendly name for the AMS unit
  4092. printer_model?: string | null; // names a rack printer's external inputs "Ext-n" (utils/trayIds)
  4093. }
  4094. export interface FilamentSkuSettings {
  4095. id: number;
  4096. material: string;
  4097. subtype: string | null;
  4098. brand: string | null;
  4099. color_name: string | null;
  4100. lead_time_days: number;
  4101. safety_margin_value: number;
  4102. safety_margin_unit: 'days' | 'g';
  4103. alerts_snoozed: boolean;
  4104. }
  4105. export interface ShoppingListItem {
  4106. id: number;
  4107. material: string;
  4108. subtype: string | null;
  4109. brand: string | null;
  4110. color_name: string | null;
  4111. quantity_spools: number;
  4112. note: string | null;
  4113. status: 'pending' | 'purchased' | 'received';
  4114. purchased_at: string | null;
  4115. added_at: string;
  4116. }
  4117. export interface ShoppingListItemCreate {
  4118. material: string;
  4119. subtype: string | null;
  4120. brand: string | null;
  4121. color_name: string | null;
  4122. quantity_spools: number;
  4123. note?: string | null;
  4124. }
  4125. // Update types
  4126. export interface VersionInfo {
  4127. version: string;
  4128. repo: string;
  4129. }
  4130. export interface UpdateCheckResult {
  4131. update_available: boolean;
  4132. current_version: string;
  4133. latest_version: string | null;
  4134. release_name?: string;
  4135. release_notes?: string;
  4136. release_url?: string;
  4137. published_at?: string;
  4138. error?: string;
  4139. message?: string;
  4140. is_docker?: boolean;
  4141. is_ha_addon?: boolean;
  4142. is_windows_installer?: boolean;
  4143. update_method?: 'docker' | 'git' | 'ha_addon' | 'windows_installer';
  4144. installer_download_url?: string | null;
  4145. // Best-effort guess at the compose directory (#2664). Prefill only — the
  4146. // value the user saved lives on AppSettings.docker_compose_dir, so clearing
  4147. // that field falls back to this guess instead of resurrecting the old value.
  4148. compose_dir_detected?: string | null;
  4149. }
  4150. export interface UpdateStatus {
  4151. status: 'idle' | 'checking' | 'downloading' | 'installing' | 'complete' | 'error';
  4152. progress: number;
  4153. message: string;
  4154. error: string | null;
  4155. }
  4156. // Maintenance types
  4157. export interface MaintenanceType {
  4158. id: number;
  4159. name: string;
  4160. description: string | null;
  4161. default_interval_hours: number;
  4162. interval_type: 'hours' | 'days'; // "hours" = print hours, "days" = calendar days
  4163. icon: string | null;
  4164. wiki_url: string | null; // Documentation link
  4165. is_system: boolean;
  4166. created_at: string;
  4167. }
  4168. export interface MaintenanceTypeCreate {
  4169. name: string;
  4170. description?: string | null;
  4171. default_interval_hours?: number;
  4172. interval_type?: 'hours' | 'days';
  4173. icon?: string | null;
  4174. wiki_url?: string | null;
  4175. }
  4176. export interface MaintenanceStatus {
  4177. id: number;
  4178. printer_id: number;
  4179. printer_name: string;
  4180. printer_model: string | null;
  4181. maintenance_type_id: number;
  4182. maintenance_type_name: string;
  4183. maintenance_type_icon: string | null;
  4184. maintenance_type_wiki_url: string | null; // Custom wiki URL from type
  4185. enabled: boolean;
  4186. interval_hours: number; // For hours type: print hours; for days type: number of days
  4187. interval_type: 'hours' | 'days';
  4188. current_hours: number;
  4189. hours_since_maintenance: number;
  4190. hours_until_due: number;
  4191. days_since_maintenance: number | null; // For days type
  4192. days_until_due: number | null; // For days type
  4193. is_due: boolean;
  4194. is_warning: boolean;
  4195. last_performed_at: string | null;
  4196. }
  4197. export interface PrinterMaintenanceOverview {
  4198. printer_id: number;
  4199. printer_name: string;
  4200. printer_model: string | null;
  4201. total_print_hours: number;
  4202. maintenance_items: MaintenanceStatus[];
  4203. due_count: number;
  4204. warning_count: number;
  4205. }
  4206. // External Links (sidebar)
  4207. export interface ExternalLink {
  4208. id: number;
  4209. name: string;
  4210. url: string;
  4211. icon: string;
  4212. open_in_new_tab: boolean;
  4213. custom_icon: string | null;
  4214. sort_order: number;
  4215. created_at: string;
  4216. updated_at: string;
  4217. /** Count reported by the app the link points to, while it keeps reporting. */
  4218. badge_count?: number | null;
  4219. }
  4220. export interface ExternalLinkCreate {
  4221. name: string;
  4222. url: string;
  4223. icon: string;
  4224. open_in_new_tab?: boolean;
  4225. }
  4226. export interface ExternalLinkUpdate {
  4227. name?: string;
  4228. url?: string;
  4229. icon?: string;
  4230. open_in_new_tab?: boolean;
  4231. }
  4232. // Finance types
  4233. export interface CostCenterSummary {
  4234. id: number;
  4235. name: string;
  4236. is_private: boolean;
  4237. owner_user_id: number | null;
  4238. is_active: boolean;
  4239. total_balance: number;
  4240. total_budget: number | null;
  4241. monthly_budget: number | null;
  4242. budget_mode: 'none' | 'total' | 'monthly';
  4243. budget_limit: number | null;
  4244. budget_used: number | null;
  4245. budget_available: number | null;
  4246. can_print: boolean;
  4247. }
  4248. export interface CostCenterCreateRequest {
  4249. name: string;
  4250. total_budget?: number | null;
  4251. monthly_budget?: number | null;
  4252. is_active?: boolean;
  4253. }
  4254. export interface CostCenterBudgetUpdateRequest {
  4255. total_budget?: number | null;
  4256. monthly_budget?: number | null;
  4257. }
  4258. export interface CostCenterUpdateRequest {
  4259. name?: string;
  4260. is_active?: boolean;
  4261. }
  4262. export interface CostCenterMemberRequest {
  4263. user_id: number;
  4264. can_print?: boolean;
  4265. }
  4266. export interface CostCenterMemberResponse {
  4267. id: number;
  4268. cost_center_id: number;
  4269. user_id: number;
  4270. can_print: boolean;
  4271. created_at: string;
  4272. }
  4273. export interface CostCenterDetail extends CostCenterSummary {
  4274. members: CostCenterMemberResponse[];
  4275. }
  4276. export interface WalletBalance {
  4277. user_id: number;
  4278. balance: number;
  4279. currency: string;
  4280. updated_at: string | null;
  4281. }
  4282. export type WalletTransactionType = 'print_charge' | 'deposit' | 'withdraw' | 'manual_adjustment';
  4283. export interface WalletTransaction {
  4284. id: number;
  4285. user_id: number | null; // null once the user is deleted
  4286. cost_center_id: number | null;
  4287. transaction_type: WalletTransactionType;
  4288. amount: number;
  4289. balance_after: number | null;
  4290. description: string | null;
  4291. created_by_user_id: number | null;
  4292. print_run_id: string | null;
  4293. print_archive_id: number | null;
  4294. print_queue_id: number | null;
  4295. created_at: string;
  4296. }
  4297. export interface WalletTransactionListResponse {
  4298. items: WalletTransaction[];
  4299. total: number;
  4300. limit: number;
  4301. offset: number;
  4302. }
  4303. export interface WalletAdjustmentRequest {
  4304. amount: number;
  4305. description?: string;
  4306. cost_center_id?: number | null;
  4307. }
  4308. export interface WalletAdjustmentResponse {
  4309. transaction: WalletTransaction;
  4310. balance: WalletBalance;
  4311. }
  4312. export interface TransactionEditRequest {
  4313. user_id?: number | null;
  4314. cost_center_id?: number | null;
  4315. amount?: number | null;
  4316. description?: string | null;
  4317. }
  4318. export interface ManualPrintRequest {
  4319. user_id: number;
  4320. cost_center_id: number;
  4321. amount: number;
  4322. description?: string | null;
  4323. created_at?: string | null;
  4324. }
  4325. // Permission type - all available permissions
  4326. export type Permission =
  4327. | 'printers:read' | 'printers:create' | 'printers:update' | 'printers:delete' | 'printers:control' | 'printers:files' | 'printers:ams_rfid' | 'printers:clear_plate'
  4328. | 'archives:read' | 'archives:read_own' | 'archives:read_all' | 'archives:create'
  4329. | 'archives:update_own' | 'archives:update_all' | 'archives:delete_own' | 'archives:delete_all'
  4330. | 'archives:reprint_own' | 'archives:reprint_all' | 'archives:purge'
  4331. | 'queue:read' | 'queue:read_own' | 'queue:read_all' | 'queue:create'
  4332. | 'queue:update_own' | 'queue:update_all' | 'queue:delete_own' | 'queue:delete_all'
  4333. | 'queue:reorder' | 'queue:start_unreviewed'
  4334. | 'library:read' | 'library:read_own' | 'library:read_all' | 'library:upload'
  4335. | 'library:update_own' | 'library:update_all' | 'library:delete_own' | 'library:delete_all'
  4336. | 'library:purge'
  4337. | 'projects:read' | 'projects:create' | 'projects:update' | 'projects:delete'
  4338. | 'filaments:read' | 'filaments:create' | 'filaments:update' | 'filaments:delete'
  4339. | 'inventory:read' | 'inventory:create' | 'inventory:update' | 'inventory:delete' | 'inventory:view_assignments'
  4340. | 'inventory:forecast_read' | 'inventory:forecast_write'
  4341. | 'smart_plugs:read' | 'smart_plugs:create' | 'smart_plugs:update' | 'smart_plugs:delete' | 'smart_plugs:control'
  4342. | 'camera:view'
  4343. | 'maintenance:read' | 'maintenance:create' | 'maintenance:update' | 'maintenance:delete'
  4344. | 'kprofiles:read' | 'kprofiles:create' | 'kprofiles:update' | 'kprofiles:delete'
  4345. | 'notifications:read' | 'notifications:create' | 'notifications:update' | 'notifications:delete' | 'notifications:user_email'
  4346. | 'notification_templates:read' | 'notification_templates:update'
  4347. | 'external_links:read' | 'external_links:create' | 'external_links:update' | 'external_links:delete'
  4348. | 'discovery:scan'
  4349. | 'firmware:read' | 'firmware:update'
  4350. | 'ams_history:read'
  4351. | 'cost_centers:read_own' | 'cost_centers:read_all' | 'cost_centers:modify' | 'cost_centers:create'
  4352. | 'stats:read' | 'stats:filter_by_user'
  4353. | 'system:read'
  4354. | 'settings:read' | 'settings:update' | 'settings:backup' | 'settings:restore'
  4355. | 'github:backup' | 'github:restore'
  4356. | 'cloud:auth' | 'orca_cloud:auth'
  4357. | 'makerworld:view' | 'makerworld:import'
  4358. | 'manyfold:view' | 'manyfold:import'
  4359. | 'api_keys:read' | 'api_keys:create' | 'api_keys:update' | 'api_keys:delete'
  4360. | 'users:read' | 'users:read_slim' | 'users:create' | 'users:update' | 'users:delete'
  4361. | 'groups:read' | 'groups:create' | 'groups:update' | 'groups:delete'
  4362. | 'pipelines:read' | 'pipelines:write' | 'pipelines:run'
  4363. | 'websocket:connect';
  4364. // Group types
  4365. export interface GroupBrief {
  4366. id: number;
  4367. name: string;
  4368. }
  4369. export interface Group {
  4370. id: number;
  4371. name: string;
  4372. description: string | null;
  4373. permissions: Permission[];
  4374. is_system: boolean;
  4375. /** Members only see the printers in printer_ids plus every printer in locations (#1727) */
  4376. restrict_printers: boolean;
  4377. printer_ids: number[];
  4378. /** Matched against Printer.location, so printers added there later are included */
  4379. locations: string[];
  4380. user_count: number;
  4381. created_at: string;
  4382. updated_at: string;
  4383. }
  4384. export interface GroupDetail extends Group {
  4385. users: Array<{ id: number; username: string; is_active: boolean }>;
  4386. }
  4387. export interface GroupCreate {
  4388. name: string;
  4389. description?: string;
  4390. permissions: Permission[];
  4391. restrict_printers?: boolean;
  4392. printer_ids?: number[];
  4393. locations?: string[];
  4394. }
  4395. export interface GroupUpdate {
  4396. name?: string;
  4397. description?: string;
  4398. permissions?: Permission[];
  4399. restrict_printers?: boolean;
  4400. printer_ids?: number[];
  4401. locations?: string[];
  4402. }
  4403. export interface PermissionInfo {
  4404. value: Permission;
  4405. label: string;
  4406. }
  4407. export interface PermissionCategory {
  4408. name: string;
  4409. permissions: PermissionInfo[];
  4410. }
  4411. export interface PermissionsListResponse {
  4412. categories: PermissionCategory[];
  4413. all_permissions: Permission[];
  4414. }
  4415. // User email notification preferences
  4416. export interface UserEmailPreferences {
  4417. notify_print_start: boolean;
  4418. notify_print_complete: boolean;
  4419. notify_print_failed: boolean;
  4420. notify_print_stopped: boolean;
  4421. }
  4422. // Auth types
  4423. export interface LoginRequest {
  4424. username: string;
  4425. password: string;
  4426. }
  4427. export interface LoginResponse {
  4428. access_token?: string;
  4429. token_type?: string;
  4430. user?: UserResponse;
  4431. /** Set when 2FA verification is required before a full token is issued. */
  4432. requires_2fa?: boolean;
  4433. pre_auth_token?: string;
  4434. two_fa_methods?: string[];
  4435. }
  4436. export interface UserResponse {
  4437. id: number;
  4438. username: string;
  4439. email?: string;
  4440. role: string; // Deprecated, kept for backward compatibility
  4441. is_active: boolean;
  4442. is_admin: boolean; // Computed from role and group membership
  4443. auth_source: string; // "local" or "ldap"
  4444. groups: GroupBrief[];
  4445. permissions: Permission[]; // All permissions from groups
  4446. created_at: string;
  4447. }
  4448. /**
  4449. * Just enough to label an owner id (#1894). Backed by GET /users/slim, which
  4450. * is readable with `users:read_slim` as well as the admin-level `users:read`
  4451. * -- use it anywhere a screen only needs to turn a `created_by_id` into a
  4452. * name, so operators are not forced into the full listing to get one.
  4453. */
  4454. export interface UserSlim {
  4455. id: number;
  4456. username: string;
  4457. }
  4458. export interface UserCreate {
  4459. username: string;
  4460. password?: string; // Optional when advanced auth is enabled
  4461. email?: string;
  4462. role: string;
  4463. group_ids?: number[];
  4464. }
  4465. export interface UserUpdate {
  4466. username?: string;
  4467. password?: string;
  4468. email?: string;
  4469. role?: string;
  4470. is_active?: boolean;
  4471. group_ids?: number[];
  4472. }
  4473. export interface SetupRequest {
  4474. auth_enabled: boolean;
  4475. admin_username?: string;
  4476. admin_password?: string;
  4477. }
  4478. export interface ForgotPasswordRequest {
  4479. email: string;
  4480. }
  4481. export interface ForgotPasswordResponse {
  4482. message: string;
  4483. }
  4484. export interface ResetPasswordRequest {
  4485. user_id: number;
  4486. }
  4487. export interface ResetPasswordResponse {
  4488. message: string;
  4489. }
  4490. export interface SMTPSettings {
  4491. smtp_host: string;
  4492. smtp_port: number;
  4493. smtp_username?: string;
  4494. smtp_password?: string;
  4495. smtp_security: 'starttls' | 'ssl' | 'none';
  4496. smtp_auth_enabled: boolean;
  4497. smtp_from_email: string;
  4498. smtp_from_name: string;
  4499. }
  4500. // 2FA / MFA interfaces
  4501. export interface TwoFAStatus {
  4502. totp_enabled: boolean;
  4503. email_otp_enabled: boolean;
  4504. backup_codes_remaining: number;
  4505. }
  4506. export interface TOTPSetupResponse {
  4507. secret: string;
  4508. qr_code_b64: string;
  4509. issuer: string;
  4510. }
  4511. export interface TOTPEnableResponse {
  4512. message: string;
  4513. backup_codes: string[];
  4514. }
  4515. export interface BackupCodesResponse {
  4516. backup_codes: string[];
  4517. message: string;
  4518. }
  4519. export interface TwoFAVerifyRequest {
  4520. pre_auth_token: string;
  4521. code: string;
  4522. method: 'totp' | 'email' | 'backup';
  4523. }
  4524. /**
  4525. * A URL that is known to be same-origin (a relative path starting with ``/``).
  4526. *
  4527. * Branded so that producers of same-origin URLs (e.g. ``api.oidcProviderIconUrl``)
  4528. * can be distinguished from arbitrary strings at the type level. The brand
  4529. * is compile-time only; at runtime these are plain strings.
  4530. *
  4531. * Purpose: CSP-safe image sources for ``<img src=...>``. The strict
  4532. * ``img-src 'self' data: blob:`` CSP rejects anything that isn't same-origin,
  4533. * so callers that demand a ``SameOriginUrl`` get a compile-time guarantee
  4534. * that no external URL slips through.
  4535. */
  4536. export type SameOriginUrl = string & { readonly __brand: 'SameOriginUrl' };
  4537. // OIDC interfaces
  4538. /** What the unauthenticated GET /auth/oidc/providers returns (#3107): only
  4539. * what the login page renders. The full provider, group sync config
  4540. * included, needs the admin-only /auth/oidc/providers/all. */
  4541. export interface OIDCProviderPublic {
  4542. id: number;
  4543. name: string;
  4544. has_icon: boolean;
  4545. is_autologin: boolean;
  4546. }
  4547. export interface OIDCProvider {
  4548. id: number;
  4549. name: string;
  4550. issuer_url: string;
  4551. client_id: string;
  4552. scopes: string;
  4553. is_enabled: boolean;
  4554. auto_create_users: boolean;
  4555. auto_link_existing_accounts: boolean;
  4556. email_claim: string;
  4557. require_email_verified: boolean;
  4558. // #3107 — group sync. Empty mapping = sync off (default).
  4559. group_claim?: string;
  4560. group_mapping?: Record<string, string>;
  4561. icon_url?: string | null;
  4562. default_group_id?: number | null;
  4563. // True when the backend has cached icon bytes for this provider.
  4564. // Login page / admin preview consume this via the proxy URL
  4565. // /api/v1/auth/oidc/providers/{id}/icon (#1333) so the SPA never
  4566. // hotlinks the external icon URL — that would require loosening
  4567. // the strict img-src CSP. Required, not optional: the backend always
  4568. // includes this field in the response (Pydantic default-False is
  4569. // populated unconditionally in the route handler).
  4570. has_icon: boolean;
  4571. // #1589: when true, the LoginPage redirects unauthenticated visitors
  4572. // straight to this provider on mount. At most one provider may carry this.
  4573. is_autologin: boolean;
  4574. // #2593: defined by BAMBUDDY_OIDC_* and rewritten from the environment on
  4575. // every boot. The API answers 409 to any write, so the settings UI must not
  4576. // offer edit/delete controls that cannot succeed. Optional so a response
  4577. // from an older backend still type-checks.
  4578. is_env_managed?: boolean;
  4579. }
  4580. export interface OIDCProviderCreate {
  4581. name: string;
  4582. issuer_url: string;
  4583. client_id: string;
  4584. client_secret: string;
  4585. scopes?: string;
  4586. is_enabled?: boolean;
  4587. auto_create_users?: boolean;
  4588. auto_link_existing_accounts?: boolean;
  4589. email_claim?: string;
  4590. require_email_verified?: boolean;
  4591. // #3107 — group sync. Omit both to leave them unchanged on update.
  4592. group_claim?: string;
  4593. group_mapping?: Record<string, string>;
  4594. icon_url?: string | null;
  4595. default_group_id?: number | null;
  4596. is_autologin?: boolean; // #1589
  4597. }
  4598. export interface OIDCLink {
  4599. id: number;
  4600. provider_id: number;
  4601. provider_name: string;
  4602. provider_email?: string | null;
  4603. created_at: string;
  4604. }
  4605. export interface TestSMTPRequest {
  4606. test_recipient: string;
  4607. // The form's settings, tested before they are saved. An empty password
  4608. // keeps the saved one.
  4609. smtp?: SMTPSettings;
  4610. }
  4611. export interface TestSMTPResponse {
  4612. success: boolean;
  4613. message: string;
  4614. }
  4615. export interface AdvancedAuthStatus {
  4616. advanced_auth_enabled: boolean;
  4617. smtp_configured: boolean;
  4618. // #1589: false hides the username/password form on the LoginPage; the env
  4619. // var BAMBUDDY_LOCAL_LOGIN=true on the server flips this back to true so
  4620. // the recovery path remains visible.
  4621. local_login_enabled: boolean;
  4622. // #1589: when set, LoginPage redirects to this provider's authorize URL
  4623. // on mount unless ?fallback=local is in the URL or the redirect times out.
  4624. autologin_provider_id: number | null;
  4625. }
  4626. export interface LDAPStatus {
  4627. ldap_enabled: boolean;
  4628. ldap_configured: boolean;
  4629. }
  4630. export interface EncryptionRowCounts {
  4631. oidc_providers: number;
  4632. user_totp: number;
  4633. }
  4634. export interface EncryptionStatus {
  4635. key_configured: boolean;
  4636. key_source: 'env' | 'file' | 'generated' | 'none';
  4637. legacy_plaintext_rows: EncryptionRowCounts;
  4638. encrypted_rows: EncryptionRowCounts;
  4639. decryption_broken: boolean;
  4640. // B2: count of rows skipped during the last legacy re-encryption migration.
  4641. // Surfaced via a yellow secondary banner in SecurityStatusCard.
  4642. migration_error_count: number;
  4643. }
  4644. export interface LDAPTestRequest {
  4645. ldap_server_url?: string;
  4646. ldap_bind_dn?: string;
  4647. ldap_bind_password?: string;
  4648. ldap_search_base?: string;
  4649. ldap_user_filter?: string;
  4650. ldap_security?: string;
  4651. }
  4652. export interface LDAPTestResponse {
  4653. success: boolean;
  4654. message: string;
  4655. }
  4656. export interface LDAPSearchResult {
  4657. username: string;
  4658. email: string | null;
  4659. display_name: string | null;
  4660. dn: string;
  4661. already_provisioned: boolean;
  4662. }
  4663. export interface SetupResponse {
  4664. auth_enabled: boolean;
  4665. admin_created?: boolean;
  4666. }
  4667. export interface AuthStatus {
  4668. auth_enabled: boolean;
  4669. requires_setup: boolean;
  4670. }
  4671. // API functions
  4672. export interface QueueHistoryFilters {
  4673. printerId?: number | null;
  4674. status?: string;
  4675. location?: string;
  4676. }
  4677. export interface QueueHistoryParams extends QueueHistoryFilters {
  4678. sortBy?: 'date' | 'name' | 'printer';
  4679. // Flips the default order: newest first by date, A to Z by name or printer.
  4680. reverse?: boolean;
  4681. limit?: number;
  4682. offset?: number;
  4683. }
  4684. export interface QueueHistoryPage {
  4685. // The page in display order, then any other runs of the batches on it.
  4686. items: PrintQueueItem[];
  4687. total: number;
  4688. locations: string[];
  4689. }
  4690. function queueHistorySearch(params: QueueHistoryParams): URLSearchParams {
  4691. const search = new URLSearchParams();
  4692. if (params.printerId) search.set('printer_id', String(params.printerId));
  4693. if (params.status) search.set('status', params.status);
  4694. if (params.location) search.set('location', params.location);
  4695. if (params.sortBy) search.set('sort_by', params.sortBy);
  4696. if (params.reverse) search.set('reverse', 'true');
  4697. if (params.limit !== undefined) search.set('limit', String(params.limit));
  4698. if (params.offset) search.set('offset', String(params.offset));
  4699. return search;
  4700. }
  4701. // Per-printer reads that a page showing every printer makes once per printer,
  4702. // coalesced into one bulk request per few milliseconds (see ./batch). Each
  4703. // keeps its single-printer request for a lone id.
  4704. const idsParam = (ids: number[]) => `ids=${ids.join(',')}`;
  4705. const printerStatusBatch = batched(
  4706. (id) => request<PrinterStatus>(`/printers/${id}/status`),
  4707. async (ids) => byField(await request<PrinterStatus[]>(`/bulk/printer-statuses?${idsParam(ids)}`), (s) => s.id),
  4708. );
  4709. const slotPresetsBatch = batched(
  4710. (id) => request<Record<number, SlotPresetMapping>>(`/printers/${id}/slot-presets`),
  4711. async (ids) => byId(await request<Record<string, Record<number, SlotPresetMapping>>>(`/bulk/slot-presets?${idsParam(ids)}`)),
  4712. );
  4713. const amsLabelsBatch = batched(
  4714. (id) => request<Record<number, string>>(`/printers/${id}/ams-labels`),
  4715. async (ids) => byId(await request<Record<string, Record<number, string>>>(`/bulk/ams-labels?${idsParam(ids)}`)),
  4716. );
  4717. type PrinterCardPlugs = { plug: SmartPlug | null; scripts: SmartPlug[] };
  4718. const cardPlugs = async (ids: number[]) =>
  4719. byId(await request<Record<string, PrinterCardPlugs>>(`/bulk/card-plugs?${idsParam(ids)}`));
  4720. const smartPlugBatch = batched(
  4721. (id) => request<SmartPlug | null>(`/smart-plugs/by-printer/${id}`),
  4722. async (ids) => new Map([...(await cardPlugs(ids))].map(([id, plugs]) => [id, plugs.plug])),
  4723. );
  4724. const scriptPlugsBatch = batched(
  4725. (id) => request<SmartPlug[]>(`/smart-plugs/by-printer/${id}/scripts`),
  4726. async (ids) => new Map([...(await cardPlugs(ids))].map(([id, plugs]) => [id, plugs.scripts])),
  4727. );
  4728. const haSensorReadingsBatch = batched(
  4729. (id) => request<PrinterHASensorReading[]>(`/ha-sensors/by-printer/${id}/readings`),
  4730. async (ids) => byId(await request<Record<string, PrinterHASensorReading[]>>(`/bulk/ha-sensor-readings?${idsParam(ids)}`)),
  4731. );
  4732. const firmwareUpdateBatch = batched(
  4733. (id) => request<FirmwareUpdateInfo>(`/firmware/updates/${id}`),
  4734. async (ids) =>
  4735. byField(await request<FirmwareUpdateInfo[]>(`/bulk/firmware-updates?${idsParam(ids)}`), (u) => u.printer_id),
  4736. );
  4737. // One batcher per status asked for: the bulk route takes a single status list.
  4738. const printerQueueBatches = new Map<string, (id: number) => Promise<PrintQueueItem[]>>();
  4739. const printerQueueBatch = (status: string) => {
  4740. let batch = printerQueueBatches.get(status);
  4741. if (!batch) {
  4742. batch = batched(
  4743. (id) => request<PrintQueueItem[]>(`/queue/?printer_id=${id}&status=${encodeURIComponent(status)}`),
  4744. async (ids) =>
  4745. byId(
  4746. await request<Record<string, PrintQueueItem[]>>(
  4747. `/bulk/printer-queues?${idsParam(ids)}&status=${encodeURIComponent(status)}`,
  4748. ),
  4749. ),
  4750. );
  4751. printerQueueBatches.set(status, batch);
  4752. }
  4753. return batch;
  4754. };
  4755. const foldersByArchiveBatch = batched(
  4756. (id) => request<LibraryFolder[]>(`/library/folders/by-archive/${id}`),
  4757. async (ids) => byId(await request<Record<string, LibraryFolder[]>>(`/bulk/archive-folders?${idsParam(ids)}`)),
  4758. );
  4759. export const api = {
  4760. // Overlay branding
  4761. getOverlayLogo: async (token: string | null, signal?: AbortSignal): Promise<Blob | null> => {
  4762. const endpoint = token ? `/overlay-branding/logo?token=${encodeURIComponent(token)}` : '/settings/overlay-logo';
  4763. const response = await fetch(`${API_BASE}${endpoint}`, {
  4764. signal, cache: 'no-store',
  4765. headers: !token && authToken ? { Authorization: `Bearer ${authToken}` } : {},
  4766. });
  4767. if (response.status === 404) return null;
  4768. if (!response.ok) throw new Error(`HTTP ${response.status}`);
  4769. return response.blob();
  4770. },
  4771. uploadOverlayLogo: async (file: File): Promise<void> => {
  4772. const body = new FormData();
  4773. body.append('file', file);
  4774. const response = await fetch(`${API_BASE}/settings/overlay-logo`, {
  4775. method: 'POST', body,
  4776. headers: authToken ? { Authorization: `Bearer ${authToken}` } : {},
  4777. });
  4778. if (!response.ok) {
  4779. const error = await response.json().catch(() => ({}));
  4780. const detail = error?.detail;
  4781. const message = typeof detail === 'string' ? detail : detail?.message;
  4782. throw new Error(typeof message === 'string' && message ? message : `HTTP ${response.status}`);
  4783. }
  4784. },
  4785. deleteOverlayLogo: () => request<{ status: string }>('/settings/overlay-logo', { method: 'DELETE' }),
  4786. // Authentication
  4787. getAuthStatus: () => request<AuthStatus>('/auth/status'),
  4788. setupAuth: (data: SetupRequest) =>
  4789. request<SetupResponse>('/auth/setup', {
  4790. method: 'POST',
  4791. body: JSON.stringify(data),
  4792. }),
  4793. login: (data: LoginRequest) =>
  4794. request<LoginResponse>('/auth/login', {
  4795. method: 'POST',
  4796. body: JSON.stringify(data),
  4797. }),
  4798. logout: () =>
  4799. request<{ message: string }>('/auth/logout', {
  4800. method: 'POST',
  4801. }),
  4802. getCurrentUser: () => request<UserResponse>('/auth/me'),
  4803. disableAuth: () =>
  4804. request<{ message: string; auth_enabled: boolean }>('/auth/disable', {
  4805. method: 'POST',
  4806. }),
  4807. // Advanced Authentication
  4808. testSMTP: (data: TestSMTPRequest) =>
  4809. request<TestSMTPResponse>('/auth/smtp/test', {
  4810. method: 'POST',
  4811. body: JSON.stringify(data),
  4812. }),
  4813. getSMTPSettings: () => request<SMTPSettings | null>('/auth/smtp'),
  4814. saveSMTPSettings: (data: SMTPSettings) =>
  4815. request<{ message: string }>('/auth/smtp', {
  4816. method: 'POST',
  4817. body: JSON.stringify(data),
  4818. }),
  4819. enableAdvancedAuth: () =>
  4820. request<{ message: string; advanced_auth_enabled: boolean }>('/auth/advanced-auth/enable', {
  4821. method: 'POST',
  4822. }),
  4823. disableAdvancedAuth: () =>
  4824. request<{ message: string; advanced_auth_enabled: boolean }>('/auth/advanced-auth/disable', {
  4825. method: 'POST',
  4826. }),
  4827. getAdvancedAuthStatus: () => request<AdvancedAuthStatus>('/auth/advanced-auth/status'),
  4828. // LDAP Authentication
  4829. getLDAPStatus: () => request<LDAPStatus>('/auth/ldap/status'),
  4830. getEncryptionStatus: () => request<EncryptionStatus>('/auth/encryption-status'),
  4831. // form: the settings being edited, tested before they are saved. An empty
  4832. // bind password keeps the saved one.
  4833. testLDAP: (form?: LDAPTestRequest) =>
  4834. request<LDAPTestResponse>('/auth/ldap/test', {
  4835. method: 'POST',
  4836. ...(form ? { body: JSON.stringify(form) } : {}),
  4837. }),
  4838. searchLDAPDirectory: (q: string) =>
  4839. request<LDAPSearchResult[]>(`/auth/ldap/search?q=${encodeURIComponent(q)}`),
  4840. provisionLDAPUser: (username: string) =>
  4841. request<UserResponse>('/auth/ldap/provision', {
  4842. method: 'POST',
  4843. body: JSON.stringify({ username }),
  4844. }),
  4845. forgotPassword: (data: ForgotPasswordRequest) =>
  4846. request<ForgotPasswordResponse>('/auth/forgot-password', {
  4847. method: 'POST',
  4848. body: JSON.stringify(data),
  4849. }),
  4850. // H-6: Confirm password reset using the token from the emailed link
  4851. forgotPasswordConfirm: (token: string, newPassword: string) =>
  4852. request<ForgotPasswordResponse>('/auth/forgot-password/confirm', {
  4853. method: 'POST',
  4854. body: JSON.stringify({ token, new_password: newPassword }),
  4855. }),
  4856. resetUserPassword: (data: ResetPasswordRequest) =>
  4857. request<ResetPasswordResponse>('/auth/reset-password', {
  4858. method: 'POST',
  4859. body: JSON.stringify(data),
  4860. }),
  4861. // 2FA - status
  4862. get2FAStatus: () => request<TwoFAStatus>('/auth/2fa/status'),
  4863. // 2FA - TOTP
  4864. setupTOTP: () => request<TOTPSetupResponse>('/auth/2fa/totp/setup', { method: 'POST' }),
  4865. enableTOTP: (code: string) =>
  4866. request<TOTPEnableResponse>('/auth/2fa/totp/enable', {
  4867. method: 'POST',
  4868. body: JSON.stringify({ code }),
  4869. }),
  4870. disableTOTP: (code: string) =>
  4871. request<{ message: string }>('/auth/2fa/totp/disable', {
  4872. method: 'POST',
  4873. body: JSON.stringify({ code }),
  4874. }),
  4875. regenerateBackupCodes: (code: string) =>
  4876. request<BackupCodesResponse>('/auth/2fa/totp/regenerate-backup-codes', {
  4877. method: 'POST',
  4878. body: JSON.stringify({ code }),
  4879. }),
  4880. // 2FA - Email OTP
  4881. // Step 1: send a verification code to the user's email (proof of possession)
  4882. enableEmailOTP: () =>
  4883. request<{ message: string; setup_token: string }>('/auth/2fa/email/enable', { method: 'POST' }),
  4884. // Step 2: confirm with the code received by email
  4885. confirmEnableEmailOTP: (setup_token: string, code: string) =>
  4886. request<{ message: string }>('/auth/2fa/email/enable/confirm', {
  4887. method: 'POST',
  4888. body: JSON.stringify({ setup_token, code }),
  4889. }),
  4890. // Disable requires account password for re-auth
  4891. disableEmailOTP: (password: string) =>
  4892. request<{ message: string }>('/auth/2fa/email/disable', {
  4893. method: 'POST',
  4894. body: JSON.stringify({ password }),
  4895. }),
  4896. sendEmailOTP: (preAuthToken: string) =>
  4897. request<{ message: string; pre_auth_token?: string }>('/auth/2fa/email/send', {
  4898. method: 'POST',
  4899. body: JSON.stringify({ pre_auth_token: preAuthToken }),
  4900. }),
  4901. // 2FA - verify (completes login)
  4902. verify2FA: (data: TwoFAVerifyRequest) =>
  4903. request<LoginResponse>('/auth/2fa/verify', {
  4904. method: 'POST',
  4905. body: JSON.stringify(data),
  4906. }),
  4907. // 2FA - admin
  4908. // adminPassword: the calling admin's own password; null for an admin
  4909. // without one (LDAP / OIDC accounts usually), whom the route does not ask.
  4910. admin2FADisable: (userId: number, adminPassword: string | null) =>
  4911. request<{ message: string; had_2fa: boolean }>(`/auth/2fa/admin/${userId}`, {
  4912. method: 'DELETE',
  4913. body: JSON.stringify({ admin_password: adminPassword }),
  4914. }),
  4915. // OIDC providers (public list)
  4916. getOIDCProviders: () => request<OIDCProviderPublic[]>('/auth/oidc/providers'),
  4917. // OIDC providers (admin)
  4918. getOIDCProvidersAll: () => request<OIDCProvider[]>('/auth/oidc/providers/all'),
  4919. createOIDCProvider: (data: OIDCProviderCreate) =>
  4920. request<OIDCProvider>('/auth/oidc/providers', {
  4921. method: 'POST',
  4922. body: JSON.stringify(data),
  4923. }),
  4924. updateOIDCProvider: (id: number, data: Partial<OIDCProviderCreate>) =>
  4925. request<OIDCProvider>(`/auth/oidc/providers/${id}`, {
  4926. method: 'PUT',
  4927. body: JSON.stringify(data),
  4928. }),
  4929. deleteOIDCProvider: (id: number) =>
  4930. request<{ message: string }>(`/auth/oidc/providers/${id}`, { method: 'DELETE' }),
  4931. // OIDC provider icon proxy (#1333) — same-origin path so the strict
  4932. // img-src CSP stays in force. Returns a SameOriginUrl-branded string
  4933. // so a future caller can't accidentally substitute an attacker-
  4934. // controlled URL where this is consumed.
  4935. oidcProviderIconUrl: (id: number): SameOriginUrl =>
  4936. `/api/v1/auth/oidc/providers/${id}/icon` as SameOriginUrl,
  4937. deleteOIDCProviderIcon: (id: number) =>
  4938. request<void>(`/auth/oidc/providers/${id}/icon`, { method: 'DELETE' }),
  4939. refreshOIDCProviderIcon: (id: number) =>
  4940. request<OIDCProvider>(`/auth/oidc/providers/${id}/icon/refresh`, { method: 'POST' }),
  4941. // OIDC authorize URL
  4942. getOIDCAuthorizeUrl: (providerId: number) =>
  4943. request<{ auth_url: string }>(`/auth/oidc/authorize/${providerId}`),
  4944. // OIDC exchange token for JWT
  4945. exchangeOIDCToken: (oidcToken: string) =>
  4946. request<LoginResponse>('/auth/oidc/exchange', {
  4947. method: 'POST',
  4948. body: JSON.stringify({ oidc_token: oidcToken }),
  4949. }),
  4950. // OIDC links for current user
  4951. getOIDCLinks: () => request<OIDCLink[]>('/auth/oidc/links'),
  4952. deleteOIDCLink: (providerId: number) =>
  4953. request<{ message: string }>(`/auth/oidc/links/${providerId}`, { method: 'DELETE' }),
  4954. // Users
  4955. getUsers: () => request<UserResponse[]>('/users/'),
  4956. getUsersSlim: () => request<UserSlim[]>('/users/slim'),
  4957. createUser: (data: UserCreate) =>
  4958. request<UserResponse>('/users/', {
  4959. method: 'POST',
  4960. body: JSON.stringify(data),
  4961. }),
  4962. updateUser: (id: number, data: UserUpdate) =>
  4963. request<UserResponse>(`/users/${id}`, {
  4964. method: 'PATCH',
  4965. body: JSON.stringify(data),
  4966. }),
  4967. deleteUser: (id: number, deleteItems: boolean = false) =>
  4968. request<void>(`/users/${id}?delete_items=${deleteItems}`, {
  4969. method: 'DELETE',
  4970. }),
  4971. getUserItemsCount: (id: number) =>
  4972. request<{ archives: number; queue_items: number; library_files: number }>(`/users/${id}/items-count`),
  4973. changePassword: (currentPassword: string, newPassword: string) =>
  4974. request<{ message: string }>('/users/me/change-password', {
  4975. method: 'POST',
  4976. body: JSON.stringify({ current_password: currentPassword, new_password: newPassword }),
  4977. }),
  4978. // User Email Notifications
  4979. getUserEmailPreferences: () =>
  4980. request<UserEmailPreferences>('/user-notifications/preferences'),
  4981. updateUserEmailPreferences: (data: UserEmailPreferences) =>
  4982. request<UserEmailPreferences>('/user-notifications/preferences', {
  4983. method: 'PUT',
  4984. body: JSON.stringify(data),
  4985. }),
  4986. // Groups
  4987. getPermissions: () => request<PermissionsListResponse>('/groups/permissions'),
  4988. getGroups: () => request<Group[]>('/groups/'),
  4989. getGroup: (id: number) => request<GroupDetail>(`/groups/${id}`),
  4990. createGroup: (data: GroupCreate) =>
  4991. request<Group>('/groups/', {
  4992. method: 'POST',
  4993. body: JSON.stringify(data),
  4994. }),
  4995. updateGroup: (id: number, data: GroupUpdate) =>
  4996. request<Group>(`/groups/${id}`, {
  4997. method: 'PATCH',
  4998. body: JSON.stringify(data),
  4999. }),
  5000. deleteGroup: (id: number) =>
  5001. request<void>(`/groups/${id}`, {
  5002. method: 'DELETE',
  5003. }),
  5004. // Printers
  5005. getPrinters: () => request<Printer[]>('/printers/'),
  5006. getPrinter: (id: number) => request<Printer>(`/printers/${id}`),
  5007. createPrinter: (data: PrinterCreate) =>
  5008. request<Printer>('/printers/', {
  5009. method: 'POST',
  5010. body: JSON.stringify(data),
  5011. }),
  5012. updatePrinter: (id: number, data: Partial<PrinterCreate>) =>
  5013. request<Printer>(`/printers/${id}`, {
  5014. method: 'PATCH',
  5015. body: JSON.stringify(data),
  5016. }),
  5017. getWledPresets: (id: number, baseUrl: string) =>
  5018. request<WLEDPreset[]>(`/printers/${id}/wled/presets`, {
  5019. method: 'POST',
  5020. body: JSON.stringify({ base_url: baseUrl }),
  5021. }),
  5022. testWledConnection: (id: number, baseUrl: string) =>
  5023. request<WLEDConnectionInfo>(`/printers/${id}/wled/test-connection`, {
  5024. method: 'POST',
  5025. body: JSON.stringify({ base_url: baseUrl }),
  5026. }),
  5027. testWledPreset: (id: number, baseUrl: string, presetId: number) =>
  5028. request<{ success: boolean }>(`/printers/${id}/wled/test-preset`, {
  5029. method: 'POST',
  5030. body: JSON.stringify({ base_url: baseUrl, preset_id: presetId }),
  5031. }),
  5032. deletePrinter: (id: number, deleteArchives: boolean = true) =>
  5033. request<{ status: string; archives_deleted: boolean }>(
  5034. `/printers/${id}?delete_archives=${deleteArchives}`,
  5035. { method: 'DELETE' }
  5036. ),
  5037. getDeveloperModeWarnings: () =>
  5038. request<{ printer_id: number; name: string }[]>('/printers/developer-mode-warnings'),
  5039. getAvailableFilaments: (model: string, location?: string) => {
  5040. const params = new URLSearchParams({ model });
  5041. if (location) params.set('location', location);
  5042. return request<Array<{ type: string; color: string; tray_info_idx: string; tray_sub_brands: string; extruder_id: number | null }>>(`/printers/available-filaments?${params}`);
  5043. },
  5044. getPrinterLocations: () => request<PrinterLocation[]>('/printer-locations/'),
  5045. createPrinterLocation: (data: { name: string; icon?: string | null; color?: string | null }) =>
  5046. request<PrinterLocation>('/printer-locations/', { method: 'POST', body: JSON.stringify(data) }),
  5047. updatePrinterLocation: (data: PrinterLocationUpdate) =>
  5048. request<PrinterLocation>('/printer-locations/', { method: 'PATCH', body: JSON.stringify(data) }),
  5049. deletePrinterLocations: (names: string[]) =>
  5050. request<{ deleted: number; printers_ungrouped: number }>('/printer-locations/delete', {
  5051. method: 'POST',
  5052. body: JSON.stringify({ names }),
  5053. }),
  5054. assignPrinterLocation: (printerIds: number[], location: string | null) =>
  5055. request<{ moved: number }>('/printer-locations/assign', {
  5056. method: 'POST',
  5057. body: JSON.stringify({ printer_ids: printerIds, location }),
  5058. }),
  5059. getPrinterStatus: (id: number) => printerStatusBatch(id),
  5060. refreshPrinterStatus: (id: number) =>
  5061. request<{ status: string }>(`/printers/${id}/refresh-status`, {
  5062. method: 'POST',
  5063. }),
  5064. connectPrinter: (id: number) =>
  5065. request<{ connected: boolean }>(`/printers/${id}/connect`, {
  5066. method: 'POST',
  5067. }),
  5068. getUsbCameras: () => request<{ cameras: UsbCamera[] }>('/printers/usb-cameras'),
  5069. testExternalCamera: (printerId: number, url: string, cameraType: string) =>
  5070. // `coalesced` is true when the frame came from a capture that was already
  5071. // running (Obico polling, a snapshot) rather than a connection this test
  5072. // opened — a single-reader camera is shared rather than opened twice, so
  5073. // the result is real but says nothing about reaching the camera just now.
  5074. // `live_view` is true when the tested camera is the one a viewer is
  5075. // watching: the answer comes from the live frame, not a test of its own.
  5076. // In the body: the URL may carry the camera login, and a query string
  5077. // ends up in the server's access log.
  5078. request<{ success: boolean; error?: string; resolution?: string; coalesced?: boolean; live_view?: boolean }>(
  5079. `/printers/${printerId}/camera/external/test`,
  5080. { method: 'POST', body: JSON.stringify({ url, camera_type: cameraType }) }
  5081. ),
  5082. // Print Control
  5083. stopPrint: (printerId: number) =>
  5084. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/stop`, {
  5085. method: 'POST',
  5086. }),
  5087. pausePrint: (printerId: number) =>
  5088. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/pause`, {
  5089. method: 'POST',
  5090. }),
  5091. resumePrint: (printerId: number) =>
  5092. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/resume`, {
  5093. method: 'POST',
  5094. }),
  5095. clearPlate: (printerId: number) =>
  5096. request<{ success: boolean; message: string }>(`/printers/${printerId}/clear-plate`, {
  5097. method: 'POST',
  5098. }),
  5099. // Get current print user (for reprint tracking - Issue #206)
  5100. getCurrentPrintUser: (printerId: number) =>
  5101. request<{ user_id?: number; username?: string }>(`/printers/${printerId}/current-print-user`),
  5102. // Print Speed Control
  5103. setPrintSpeed: (printerId: number, mode: number) =>
  5104. request<{ success: boolean; message: string }>(`/printers/${printerId}/print-speed?mode=${mode}`, {
  5105. method: 'POST',
  5106. }),
  5107. setNozzleTemperature: (printerId: number, target: number, nozzle: number = 0) =>
  5108. request<{ success: boolean; message: string }>(
  5109. `/printers/${printerId}/temperature/nozzle?target=${target}&nozzle=${nozzle}`,
  5110. { method: 'POST' }
  5111. ),
  5112. setBedTemperature: (printerId: number, target: number) =>
  5113. request<{ success: boolean; message: string }>(`/printers/${printerId}/temperature/bed?target=${target}`, {
  5114. method: 'POST',
  5115. }),
  5116. setChamberTemperature: (printerId: number, target: number) =>
  5117. request<{ success: boolean; message: string }>(`/printers/${printerId}/temperature/chamber?target=${target}`, {
  5118. method: 'POST',
  5119. }),
  5120. setFanSpeed: (printerId: number, fan: 'part' | 'aux' | 'aux2' | 'chamber', speed: number) =>
  5121. request<{ success: boolean; message: string }>(`/printers/${printerId}/fan-speed?fan=${fan}&speed=${speed}`, {
  5122. method: 'POST',
  5123. }),
  5124. selectExtruder: (printerId: number, extruder: number) =>
  5125. request<{ success: boolean; message: string }>(`/printers/${printerId}/select-extruder?extruder=${extruder}`, {
  5126. method: 'POST',
  5127. }),
  5128. setAirductMode: (printerId: number, mode: 'cooling' | 'heating') =>
  5129. request<{ success: boolean; message: string }>(`/printers/${printerId}/airduct-mode?mode=${mode}`, {
  5130. method: 'POST',
  5131. }),
  5132. // Bed (Z-axis) jog
  5133. bedJog: (printerId: number, distance: number) =>
  5134. request<{ success: boolean; message: string }>(
  5135. `/printers/${printerId}/bed-jog?distance=${distance}`,
  5136. { method: 'POST' }
  5137. ),
  5138. xyJog: (printerId: number, x: number, y: number) =>
  5139. request<{ success: boolean; message: string }>(
  5140. `/printers/${printerId}/xy-jog?x=${x}&y=${y}`,
  5141. { method: 'POST' }
  5142. ),
  5143. extruderJog: (printerId: number, distance: number) =>
  5144. request<{ success: boolean; message: string }>(
  5145. `/printers/${printerId}/extruder-jog?distance=${distance}`,
  5146. { method: 'POST' }
  5147. ),
  5148. homeAxes: (printerId: number, axes: 'z' | 'xy' | 'all' = 'z') =>
  5149. request<{ success: boolean; message: string }>(
  5150. `/printers/${printerId}/home-axes?axes=${axes}`,
  5151. { method: 'POST' }
  5152. ),
  5153. // Chamber Light Control
  5154. setChamberLight: (printerId: number, on: boolean) =>
  5155. request<{ success: boolean; message: string }>(`/printers/${printerId}/chamber-light?on=${on}`, {
  5156. method: 'POST',
  5157. }),
  5158. // AMS Drying Control
  5159. startDrying: (printerId: number, amsId: number, temp: number, duration: number, filament: string = '', rotateTray: boolean = false) =>
  5160. request<{ status: string; ams_id: number; temp: number; duration: number }>(
  5161. `/printers/${printerId}/drying/start?ams_id=${amsId}&temp=${temp}&duration=${duration}&filament=${encodeURIComponent(filament)}&rotate_tray=${rotateTray}`,
  5162. { method: 'POST' }
  5163. ),
  5164. stopDrying: (printerId: number, amsId: number) =>
  5165. request<{ status: string; ams_id: number }>(
  5166. `/printers/${printerId}/drying/stop?ams_id=${amsId}`,
  5167. { method: 'POST' }
  5168. ),
  5169. // Scheduled (delayed) drying runs (#2638)
  5170. createScheduledDrying: (data: {
  5171. printer_id: number;
  5172. ams_id: number;
  5173. temp: number;
  5174. duration_hours: number;
  5175. filament?: string;
  5176. rotate_tray?: boolean;
  5177. start_after: string | null;
  5178. }) =>
  5179. request<ScheduledDrying>('/scheduled-dryings', {
  5180. method: 'POST',
  5181. body: JSON.stringify(data),
  5182. }),
  5183. // Omit printerId for the whole fleet in one request; the printer cards share
  5184. // that single query rather than each polling for its own id.
  5185. listScheduledDryings: (printerId?: number) =>
  5186. request<ScheduledDrying[]>(
  5187. printerId === undefined ? '/scheduled-dryings' : `/scheduled-dryings?printer_id=${printerId}`
  5188. ),
  5189. cancelScheduledDrying: (id: number) =>
  5190. request<{ status: string; id: number }>(`/scheduled-dryings/${id}`, { method: 'DELETE' }),
  5191. // AMS Filament Backup (auto-switch to a backup spool when one runs out)
  5192. setAmsFilamentBackup: (printerId: number, enabled: boolean) =>
  5193. request<{ success: boolean; ams_filament_backup: boolean }>(
  5194. `/printers/${printerId}/ams-backup?enabled=${enabled}`,
  5195. { method: 'POST' }
  5196. ),
  5197. // Per-globalTrayId remaining grams for this printer's inventory-bound slots
  5198. // (#1766). Drives the client-side "Prefer Lowest Remaining Filament" sort
  5199. // when computing the AMS mapping; mirrors backend `_build_inventory_remain_overrides`
  5200. // so internal and Spoolman modes both work uniformly.
  5201. getInventoryRemain: (printerId: number) =>
  5202. request<InventoryRemainResponse>(
  5203. `/printers/${printerId}/inventory-remain`,
  5204. ),
  5205. // Skip Objects
  5206. getPrintableObjects: (printerId: number) =>
  5207. request<{
  5208. objects: Array<{ id: number; name: string; x: number | null; y: number | null; skipped: boolean }>;
  5209. total: number;
  5210. skipped_count: number;
  5211. is_printing: boolean;
  5212. bbox_all: [number, number, number, number] | null;
  5213. }>(`/printers/${printerId}/print/objects`),
  5214. skipObjects: (printerId: number, objectIds: number[]) =>
  5215. request<{ success: boolean; message: string; skipped_objects: number[] }>(
  5216. `/printers/${printerId}/print/skip-objects`,
  5217. {
  5218. method: 'POST',
  5219. body: JSON.stringify(objectIds),
  5220. }
  5221. ),
  5222. // HMS Errors
  5223. clearHMSErrors: (printerId: number) =>
  5224. request<{ success: boolean; message: string }>(`/printers/${printerId}/hms/clear`, { method: 'POST' }),
  5225. executeHMSAction: (printerId: number, data: HMSActionBody) =>
  5226. request<{ success: boolean; message: string }>(`/printers/${printerId}/hms/execute-action`, {
  5227. method: 'POST',
  5228. body: JSON.stringify(data),
  5229. }),
  5230. // AMS Control
  5231. refreshAmsSlot: (printerId: number, amsId: number, slotId: number) =>
  5232. request<{ success: boolean; message: string }>(
  5233. `/printers/${printerId}/ams/${amsId}/slot/${slotId}/refresh`,
  5234. { method: 'POST' }
  5235. ),
  5236. // Load filament from a tray. trayId: 0-15 for AMS (amsId*4+slotId), 28-36 for the H3C AMS 3H, 128-135 for an
  5237. // AMS-HT (its unit id), 254 for external spool.
  5238. // extruderId (0 = right, 1 = left) names the hotend to feed. Pass it only on a
  5239. // printer with a Filament Track Switch — there the AMS is bound to a switch
  5240. // inlet rather than a hotend, so the firmware cannot work the target out and
  5241. // drops the command. Omit it everywhere else, as BambuStudio does.
  5242. loadAmsTray: (printerId: number, trayId: number, extruderId?: number) =>
  5243. request<{ success: boolean; message: string }>(
  5244. `/printers/${printerId}/ams/load?tray_id=${trayId}` +
  5245. (extruderId !== undefined ? `&extruder_id=${extruderId}` : ''),
  5246. { method: 'POST' }
  5247. ),
  5248. // Unload filament. trayId names the slot to unload, which is what tells a
  5249. // dual-nozzle printer which of its two hotends to act on; omit it to unload
  5250. // whatever the printer's single tray_now field names.
  5251. unloadAms: (printerId: number, trayId?: number) =>
  5252. request<{ success: boolean; message: string }>(
  5253. `/printers/${printerId}/ams/unload` + (trayId !== undefined ? `?tray_id=${trayId}` : ''),
  5254. { method: 'POST' }
  5255. ),
  5256. // MQTT Debug Logging
  5257. enableMQTTLogging: (printerId: number) =>
  5258. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/enable`, {
  5259. method: 'POST',
  5260. }),
  5261. disableMQTTLogging: (printerId: number) =>
  5262. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/disable`, {
  5263. method: 'POST',
  5264. }),
  5265. getMQTTLogs: (printerId: number) =>
  5266. request<MQTTLogsResponse>(`/printers/${printerId}/logging`),
  5267. clearMQTTLogs: (printerId: number) =>
  5268. request<{ status: string }>(`/printers/${printerId}/logging`, {
  5269. method: 'DELETE',
  5270. }),
  5271. // Printer File Manager
  5272. getPrinterFiles: (printerId: number, path = '/') =>
  5273. request<{
  5274. path: string;
  5275. files: Array<{
  5276. name: string;
  5277. is_directory: boolean;
  5278. size: number;
  5279. path: string;
  5280. mtime?: string;
  5281. }>;
  5282. warnings: Array<'printer_unavailable' | 'listing_timed_out'>;
  5283. }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`),
  5284. getPrinterFileDownloadUrl: (printerId: number, path: string) =>
  5285. `${API_BASE}/printers/${printerId}/files/download?path=${encodeURIComponent(path)}`,
  5286. getPrinterFileGcodeUrl: (printerId: number, path: string) =>
  5287. `${API_BASE}/printers/${printerId}/files/gcode?path=${encodeURIComponent(path)}`,
  5288. getPrinterFilePlates: (printerId: number, path: string) =>
  5289. request<{
  5290. printer_id: number;
  5291. path: string;
  5292. filename: string;
  5293. plates: Array<{
  5294. index: number;
  5295. name: string | null;
  5296. objects: string[];
  5297. has_thumbnail: boolean;
  5298. thumbnail_url: string | null;
  5299. print_time_seconds: number | null;
  5300. filament_used_grams: number | null;
  5301. filaments: Array<{
  5302. slot_id: number;
  5303. type: string;
  5304. color: string;
  5305. used_grams: number;
  5306. used_meters: number;
  5307. }>;
  5308. }>;
  5309. is_multi_plate: boolean;
  5310. }>(`/printers/${printerId}/files/plates?path=${encodeURIComponent(path)}`),
  5311. getPrinterFilePlateThumbnail: (printerId: number, plateIndex: number, path: string) =>
  5312. withMediaToken(`${API_BASE}/printers/${printerId}/files/plate-thumbnail/${plateIndex}?path=${encodeURIComponent(path)}`),
  5313. downloadPrinterFilesAsZip: async (
  5314. printerId: number,
  5315. paths: string[],
  5316. sizes: Record<string, number>,
  5317. filename = 'printer-files.zip',
  5318. asZip = true,
  5319. signal?: AbortSignal,
  5320. onProgress?: (completed: number, total: number) => void,
  5321. ): Promise<{ requested: number; successful: number; failed: number }> => {
  5322. type JobStatus = {
  5323. job_id: string;
  5324. state: 'queued' | 'preparing' | 'ready' | 'failed' | 'cancelled';
  5325. requested: number;
  5326. successful: number;
  5327. failed: number;
  5328. token: string | null;
  5329. message: string | null;
  5330. };
  5331. let jobId: string | null = null;
  5332. try {
  5333. if (signal?.aborted) throw new DOMException('Download cancelled', 'AbortError');
  5334. let status = await request<JobStatus>(`/printers/${printerId}/files/download-job`, {
  5335. method: 'POST',
  5336. body: JSON.stringify({ paths, sizes, filename, as_zip: asZip }),
  5337. signal,
  5338. });
  5339. jobId = status.job_id;
  5340. let polls = 0;
  5341. while (status.state === 'queued' || status.state === 'preparing') {
  5342. onProgress?.(status.successful + status.failed, status.requested);
  5343. // Small selections finish in the first seconds, so poll quickly there.
  5344. // A large one runs for up to half an hour, where half-second polling is
  5345. // thousands of requests that each re-check the caller's credentials.
  5346. const delay = polls < 10 ? 500 : 2000;
  5347. polls += 1;
  5348. await new Promise<void>((resolve, reject) => {
  5349. if (signal?.aborted) {
  5350. reject(new DOMException('Download cancelled', 'AbortError'));
  5351. return;
  5352. }
  5353. const onAbort = () => {
  5354. window.clearTimeout(timer);
  5355. reject(new DOMException('Download cancelled', 'AbortError'));
  5356. };
  5357. const timer = window.setTimeout(() => {
  5358. signal?.removeEventListener('abort', onAbort);
  5359. resolve();
  5360. }, delay);
  5361. signal?.addEventListener('abort', onAbort, { once: true });
  5362. });
  5363. status = await request<JobStatus>(`/printers/${printerId}/files/download-jobs/${jobId}`, { signal });
  5364. }
  5365. onProgress?.(status.successful + status.failed, status.requested);
  5366. if (status.state !== 'ready' || !status.token) {
  5367. throw new Error(status.message || (status.state === 'cancelled'
  5368. ? 'Download cancelled'
  5369. : 'Printer download preparation failed'));
  5370. }
  5371. const link = document.createElement('a');
  5372. link.href = `${API_BASE}/printers/${printerId}/files/dl/${encodeURIComponent(status.token)}/${encodeURIComponent(filename)}`;
  5373. link.download = filename;
  5374. document.body.appendChild(link);
  5375. link.click();
  5376. link.remove();
  5377. return {
  5378. requested: status.requested,
  5379. successful: status.successful,
  5380. failed: status.failed,
  5381. };
  5382. } catch (error) {
  5383. if (jobId) {
  5384. await request(`/printers/${printerId}/files/download-jobs/${jobId}`, { method: 'DELETE' }).catch(() => undefined);
  5385. }
  5386. throw error;
  5387. }
  5388. },
  5389. deletePrinterFile: (printerId: number, path: string) =>
  5390. request<{ status: string; path: string }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`, {
  5391. method: 'DELETE',
  5392. }),
  5393. getPrinterStorage: (printerId: number) =>
  5394. request<{ used_bytes: number | null; free_bytes: number | null }>(`/printers/${printerId}/storage`),
  5395. // Archives
  5396. getArchives: (printerId?: number, projectId?: number, limit = 10000, offset = 0, dateFrom?: string, dateTo?: string) => {
  5397. const params = new URLSearchParams();
  5398. if (printerId) params.set('printer_id', String(printerId));
  5399. if (projectId) params.set('project_id', String(projectId));
  5400. params.set('limit', String(limit));
  5401. params.set('offset', String(offset));
  5402. if (dateFrom) params.set('date_from', dateFrom);
  5403. if (dateTo) params.set('date_to', dateTo);
  5404. addDayZone(params);
  5405. return request<Archive[]>(`/archives/?${params}`);
  5406. },
  5407. // Latest archive of every printer in one request, for the printer cards.
  5408. getLastArchivePerPrinter: () => request<Archive[]>('/archives/last-per-printer'),
  5409. getArchivesSlim: (dateFrom?: string, dateTo?: string, createdById?: number) => {
  5410. const params = new URLSearchParams();
  5411. if (dateFrom) params.set('date_from', dateFrom);
  5412. if (dateTo) params.set('date_to', dateTo);
  5413. addDayZone(params);
  5414. if (createdById !== undefined) params.set('created_by_id', String(createdById));
  5415. const qs = params.toString();
  5416. return request<ArchiveSlim[]>(`/archives/slim${qs ? `?${qs}` : ''}`);
  5417. },
  5418. getArchive: (id: number, runId?: number | null) =>
  5419. request<Archive>(`/archives/${id}${runId != null ? `?run_id=${runId}` : ''}`),
  5420. getArchiveRuns: (id: number) => request<PrintLogResponse>(`/archives/${id}/runs`),
  5421. // The prints of the archives the caller sees that ended between two days
  5422. // (archive redesign P4: the calendar), in id order.
  5423. getArchivePrints: (params: { dateFrom: string; dateTo: string; printerId?: number; limit?: number; offset?: number }) => {
  5424. const search = new URLSearchParams({ date_from: params.dateFrom, date_to: params.dateTo });
  5425. if (params.printerId) search.set('printer_id', String(params.printerId));
  5426. if (params.limit) search.set('limit', String(params.limit));
  5427. if (params.offset) search.set('offset', String(params.offset));
  5428. addDayZone(search);
  5429. return request<PrintLogResponse>(`/archives/prints?${search}`);
  5430. },
  5431. /**
  5432. * Pre-flight for the delete-confirm modal (#1734). Returns the number of
  5433. * related queue items that will be removed along with the archive AND how
  5434. * many are currently printing (server 409s on delete if > 0).
  5435. */
  5436. getArchiveDeleteImpact: (id: number) =>
  5437. request<{ related_queue_items: number; currently_printing: number }>(
  5438. `/archives/${id}/delete-impact`
  5439. ),
  5440. getNo3MFWarning: () =>
  5441. request<{
  5442. has_fallback: boolean;
  5443. reason:
  5444. | 'ftps_cooloff'
  5445. | 'ftp_transfer_failed'
  5446. | 'internal_storage'
  5447. | 'no_external_storage'
  5448. | 'internal_history'
  5449. | null;
  5450. }>(
  5451. '/archives/no-3mf-warning',
  5452. ),
  5453. updateArchive: (id: number, data: {
  5454. printer_id?: number | null;
  5455. project_id?: number | null;
  5456. print_name?: string;
  5457. is_favorite?: boolean;
  5458. tags?: string;
  5459. notes?: string;
  5460. cost?: number;
  5461. failure_reason?: string | null;
  5462. status?: string;
  5463. quantity?: number;
  5464. external_url?: string | null;
  5465. filament_used_grams?: number | null;
  5466. // Post-print outcome verdict (#1898); null clears it
  5467. user_verdict?: 'good' | 'reject' | null;
  5468. // Which surface answered. The backend only accepts the sources a client
  5469. // can honestly claim and defaults to 'api' when none is given.
  5470. user_verdict_source?: 'dialog' | 'printer_card';
  5471. // The run the verdict / outcome is for; omitted means the latest run.
  5472. run_id?: number;
  5473. }) =>
  5474. request<Archive>(`/archives/${id}`, {
  5475. method: 'PATCH',
  5476. body: JSON.stringify(data),
  5477. }),
  5478. toggleFavorite: (id: number) =>
  5479. request<Archive>(`/archives/${id}/favorite`, { method: 'POST' }),
  5480. // Soft-deletes by default (#1343): files removed from disk, row hidden
  5481. // from listings, but its filament / time / cost / energy contribution
  5482. // stays in Quick Stats. Pass purgeStats=true to hard-delete and drop the
  5483. // row from statistics too.
  5484. deleteArchive: (id: number, purgeStats: boolean = false) =>
  5485. request<void>(`/archives/${id}${purgeStats ? '?purge_stats=true' : ''}`, { method: 'DELETE' }),
  5486. // ========== Archive auto-purge (#1008 follow-up) ==========
  5487. previewArchivePurge: (olderThanDays: number, purgeStats: boolean = false) =>
  5488. request<ArchivePurgePreview>(
  5489. `/archives/purge/preview?older_than_days=${olderThanDays}&purge_stats=${purgeStats}`,
  5490. ),
  5491. // #1390: purgeStats=false (default) soft-deletes each old archive — Quick Stats
  5492. // preserved, files removed from disk, row hidden via deleted_at. true matches
  5493. // the single-archive delete's `?purge_stats=true` semantics (hard-deletes the
  5494. // linked PrintLogEntry rows so the contribution drops from /stats too).
  5495. executeArchivePurge: (olderThanDays: number, purgeStats: boolean = false) =>
  5496. request<{ deleted: number; purge_stats: boolean }>('/archives/purge', {
  5497. method: 'POST',
  5498. body: JSON.stringify({ older_than_days: olderThanDays, purge_stats: purgeStats }),
  5499. }),
  5500. // Archives of one file merge into the oldest (archive redesign P2).
  5501. previewArchiveMerge: () => request<ArchiveMergePreview>('/archives/merge-preview'),
  5502. /** How many duplicate groups there are; cheap, for offering the merge. */
  5503. getArchiveMergeCount: () => request<{ groups: number }>('/archives/merge-count'),
  5504. mergeArchives: (survivorIds: number[]) =>
  5505. request<ArchiveMergeResult>('/archives/merge', {
  5506. method: 'POST',
  5507. body: JSON.stringify({ survivor_ids: survivorIds }),
  5508. }),
  5509. getArchivePurgeSettings: () =>
  5510. request<ArchivePurgeSettings>('/archives/purge/settings'),
  5511. updateArchivePurgeSettings: (body: ArchivePurgeSettings) =>
  5512. request<ArchivePurgeSettings>('/archives/purge/settings', {
  5513. method: 'PUT',
  5514. body: JSON.stringify(body),
  5515. }),
  5516. getArchiveStats: (options?: { dateFrom?: string; dateTo?: string; createdById?: number }) => {
  5517. const params = new URLSearchParams();
  5518. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  5519. if (options?.dateTo) params.set('date_to', options.dateTo);
  5520. addDayZone(params);
  5521. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  5522. const qs = params.toString();
  5523. return request<ArchiveStats>(`/archives/stats${qs ? `?${qs}` : ''}`);
  5524. },
  5525. // Tag management
  5526. getTags: () => request<TagInfo[]>('/archives/tags'),
  5527. renameTag: (oldName: string, newName: string) =>
  5528. request<{ affected: number }>(`/archives/tags/${encodeURIComponent(oldName)}`, {
  5529. method: 'PUT',
  5530. body: JSON.stringify({ new_name: newName }),
  5531. }),
  5532. deleteTag: (name: string) =>
  5533. request<{ affected: number }>(`/archives/tags/${encodeURIComponent(name)}`, {
  5534. method: 'DELETE',
  5535. }),
  5536. recalculateCosts: () =>
  5537. request<{
  5538. message: string;
  5539. updated: number;
  5540. preserved: number;
  5541. usage_repriced: number;
  5542. spoolman_unreachable: number;
  5543. }>('/archives/recalculate-costs', { method: 'POST' }),
  5544. getFailureAnalysis: (options?: { days?: number; dateFrom?: string; dateTo?: string; printerId?: number; projectId?: number; createdById?: number }) => {
  5545. const params = new URLSearchParams();
  5546. if (options?.days) params.set('days', String(options.days));
  5547. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  5548. if (options?.dateTo) params.set('date_to', options.dateTo);
  5549. addDayZone(params);
  5550. if (options?.printerId) params.set('printer_id', String(options.printerId));
  5551. if (options?.projectId) params.set('project_id', String(options.projectId));
  5552. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  5553. const qs = params.toString();
  5554. return request<FailureAnalysis>(`/archives/analysis/failures${qs ? `?${qs}` : ''}`);
  5555. },
  5556. compareArchives: (archiveIds: number[]) =>
  5557. request<ArchiveComparison>(`/archives/compare?archive_ids=${archiveIds.join(',')}`),
  5558. exportArchives: async (options?: {
  5559. format?: 'csv' | 'xlsx';
  5560. fields?: string[];
  5561. printerId?: number;
  5562. projectId?: number;
  5563. status?: string;
  5564. dateFrom?: string;
  5565. dateTo?: string;
  5566. search?: string;
  5567. }): Promise<{ blob: Blob; filename: string }> => {
  5568. const params = new URLSearchParams();
  5569. if (options?.format) params.set('format', options.format);
  5570. if (options?.fields) params.set('fields', options.fields.join(','));
  5571. if (options?.printerId) params.set('printer_id', String(options.printerId));
  5572. if (options?.projectId) params.set('project_id', String(options.projectId));
  5573. if (options?.status) params.set('status', options.status);
  5574. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  5575. if (options?.dateTo) params.set('date_to', options.dateTo);
  5576. addDayZone(params);
  5577. if (options?.search) params.set('search', options.search);
  5578. const headers: Record<string, string> = {};
  5579. if (authToken) {
  5580. headers['Authorization'] = `Bearer ${authToken}`;
  5581. }
  5582. const response = await fetch(`${API_BASE}/archives/export?${params}`, { headers });
  5583. if (!response.ok) {
  5584. const error = await response.json().catch(() => ({}));
  5585. throw new Error(error.detail || `HTTP ${response.status}`);
  5586. }
  5587. const contentDisposition = response.headers.get('Content-Disposition');
  5588. let filename = options?.format === 'xlsx' ? 'archives_export.xlsx' : 'archives_export.csv';
  5589. if (contentDisposition) {
  5590. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  5591. if (match) filename = match[1];
  5592. }
  5593. const blob = await response.blob();
  5594. return { blob, filename };
  5595. },
  5596. exportStats: async (options?: {
  5597. format?: 'csv' | 'xlsx';
  5598. days?: number;
  5599. printerId?: number;
  5600. projectId?: number;
  5601. createdById?: number;
  5602. }): Promise<{ blob: Blob; filename: string }> => {
  5603. const params = new URLSearchParams();
  5604. if (options?.format) params.set('format', options.format);
  5605. if (options?.days) params.set('days', String(options.days));
  5606. if (options?.printerId) params.set('printer_id', String(options.printerId));
  5607. if (options?.projectId) params.set('project_id', String(options.projectId));
  5608. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  5609. const headers: Record<string, string> = {};
  5610. if (authToken) {
  5611. headers['Authorization'] = `Bearer ${authToken}`;
  5612. }
  5613. const response = await fetch(`${API_BASE}/archives/stats/export?${params}`, { headers });
  5614. if (!response.ok) {
  5615. const error = await response.json().catch(() => ({}));
  5616. throw new Error(error.detail || `HTTP ${response.status}`);
  5617. }
  5618. const contentDisposition = response.headers.get('Content-Disposition');
  5619. let filename = options?.format === 'xlsx' ? 'stats_export.xlsx' : 'stats_export.csv';
  5620. if (contentDisposition) {
  5621. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  5622. if (match) filename = match[1];
  5623. }
  5624. const blob = await response.blob();
  5625. return { blob, filename };
  5626. },
  5627. getArchiveThumbnail: (id: number) => withMediaToken(`${API_BASE}/archives/${id}/thumbnail?v=${Date.now()}`),
  5628. getArchivePlateThumbnail: (id: number, plateIndex: number) =>
  5629. withMediaToken(`${API_BASE}/archives/${id}/plate-thumbnail/${plateIndex}`),
  5630. getArchiveDownload: (id: number) => `${API_BASE}/archives/${id}/download`,
  5631. downloadArchive: async (id: number, filename?: string): Promise<void> => {
  5632. const headers: Record<string, string> = {};
  5633. if (authToken) {
  5634. headers['Authorization'] = `Bearer ${authToken}`;
  5635. }
  5636. const response = await fetch(`${API_BASE}/archives/${id}/download`, { headers });
  5637. if (!response.ok) {
  5638. const error = await response.json().catch(() => ({}));
  5639. throw new Error(error.detail || `HTTP ${response.status}`);
  5640. }
  5641. const disposition = response.headers.get('Content-Disposition');
  5642. const downloadFilename = parseContentDispositionFilename(disposition) || filename || `archive_${id}.3mf`;
  5643. const blob = await response.blob();
  5644. const url = window.URL.createObjectURL(blob);
  5645. const a = document.createElement('a');
  5646. a.href = url;
  5647. a.download = downloadFilename;
  5648. document.body.appendChild(a);
  5649. a.click();
  5650. document.body.removeChild(a);
  5651. window.URL.revokeObjectURL(url);
  5652. },
  5653. getArchiveGcode: (id: number) => `${API_BASE}/archives/${id}/gcode`,
  5654. getArchiveTimelapse: (id: number) => withMediaToken(`${API_BASE}/archives/${id}/timelapse?v=${Date.now()}`),
  5655. getArchiveRunTimelapse: (id: number, runId: number) =>
  5656. withMediaToken(`${API_BASE}/archives/${id}/runs/${runId}/timelapse?v=${Date.now()}`),
  5657. downloadArchiveTimelapse: async (id: number, filename: string): Promise<void> => {
  5658. const prepared = await request<{ token: string; filename: string }>(
  5659. `/archives/${id}/media-download-token`,
  5660. { method: 'POST' },
  5661. );
  5662. const link = document.createElement('a');
  5663. link.href = `${API_BASE}/archives/${id}/media/dl/${encodeURIComponent(prepared.token)}/${encodeURIComponent(filename)}`;
  5664. link.download = filename;
  5665. document.body.appendChild(link);
  5666. link.click();
  5667. link.remove();
  5668. },
  5669. getArchivePrinterMedia: (id: number) =>
  5670. request<ArchivePrinterMedia>(`/archives/${id}/printer-media`),
  5671. scanArchiveTimelapse: (id: number) =>
  5672. request<{
  5673. status: string;
  5674. message: string;
  5675. filename?: string;
  5676. available_files?: Array<{ name: string; path: string; size: number; mtime: string | null }>;
  5677. }>(`/archives/${id}/timelapse/scan`, {
  5678. method: 'POST',
  5679. }),
  5680. selectArchiveTimelapse: (id: number, filename: string) =>
  5681. request<{ status: string; message: string; filename: string }>(
  5682. `/archives/${id}/timelapse/select?filename=${encodeURIComponent(filename)}`,
  5683. { method: 'POST' }
  5684. ),
  5685. deleteArchiveTimelapse: (id: number) =>
  5686. request<{ status: string }>(`/archives/${id}/timelapse`, {
  5687. method: 'DELETE',
  5688. }),
  5689. uploadArchiveTimelapse: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  5690. const formData = new FormData();
  5691. formData.append('file', file);
  5692. const headers: Record<string, string> = {};
  5693. if (authToken) {
  5694. headers['Authorization'] = `Bearer ${authToken}`;
  5695. }
  5696. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/upload`, {
  5697. method: 'POST',
  5698. headers,
  5699. body: formData,
  5700. });
  5701. if (!response.ok) {
  5702. const error = await response.json().catch(() => ({}));
  5703. throw new Error(error.detail || `HTTP ${response.status}`);
  5704. }
  5705. return response.json();
  5706. },
  5707. // Timelapse Editor
  5708. getTimelapseInfo: (archiveId: number) =>
  5709. request<{
  5710. duration: number;
  5711. width: number;
  5712. height: number;
  5713. fps: number;
  5714. codec: string;
  5715. file_size: number;
  5716. has_audio: boolean;
  5717. }>(`/archives/${archiveId}/timelapse/info`),
  5718. getTimelapseThumbnails: (archiveId: number, count: number = 10) =>
  5719. request<{
  5720. thumbnails: string[];
  5721. timestamps: number[];
  5722. }>(`/archives/${archiveId}/timelapse/thumbnails?count=${count}`),
  5723. processTimelapse: async (
  5724. archiveId: number,
  5725. params: {
  5726. trimStart?: number;
  5727. trimEnd?: number;
  5728. speed?: number;
  5729. /** Music volume, 0 to 1. */
  5730. audioVolume?: number;
  5731. saveMode: 'replace' | 'new';
  5732. outputFilename?: string;
  5733. },
  5734. audioFile?: File
  5735. ): Promise<TimelapseJob> => {
  5736. const formData = new FormData();
  5737. formData.append('trim_start', String(params.trimStart ?? 0));
  5738. if (params.trimEnd !== undefined) {
  5739. formData.append('trim_end', String(params.trimEnd));
  5740. }
  5741. formData.append('speed', String(params.speed ?? 1));
  5742. if (params.audioVolume !== undefined) {
  5743. formData.append('audio_volume', String(params.audioVolume));
  5744. }
  5745. formData.append('save_mode', params.saveMode);
  5746. if (params.outputFilename) {
  5747. formData.append('output_filename', params.outputFilename);
  5748. }
  5749. if (audioFile) {
  5750. formData.append('audio', audioFile);
  5751. }
  5752. const headers: Record<string, string> = {};
  5753. if (authToken) {
  5754. headers['Authorization'] = `Bearer ${authToken}`;
  5755. }
  5756. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/process`, {
  5757. method: 'POST',
  5758. headers,
  5759. body: formData,
  5760. });
  5761. if (!response.ok) {
  5762. const error = await response.json().catch(() => ({}));
  5763. throw new Error(error.detail || `HTTP ${response.status}`);
  5764. }
  5765. return response.json();
  5766. },
  5767. // The archive's running or last re-encode; null when there has been none.
  5768. getTimelapseJob: async (archiveId: number): Promise<TimelapseJob | null> => {
  5769. try {
  5770. return await request<TimelapseJob>(`/archives/${archiveId}/timelapse/job`);
  5771. } catch (error) {
  5772. if (error instanceof ApiError && error.status === 404) return null;
  5773. throw error;
  5774. }
  5775. },
  5776. cancelTimelapseJob: (archiveId: number) =>
  5777. request<TimelapseJob>(`/archives/${archiveId}/timelapse/job`, { method: 'DELETE' }),
  5778. // Photos
  5779. getArchivePhotoUrl: (archiveId: number, filename: string) =>
  5780. withMediaToken(`${API_BASE}/archives/${archiveId}/photos/${encodeURIComponent(filename)}`),
  5781. uploadArchivePhoto: async (archiveId: number, file: File): Promise<{ status: string; filename: string; photos: string[] }> => {
  5782. const formData = new FormData();
  5783. formData.append('file', file);
  5784. const headers: Record<string, string> = {};
  5785. if (authToken) {
  5786. headers['Authorization'] = `Bearer ${authToken}`;
  5787. }
  5788. const response = await fetch(`${API_BASE}/archives/${archiveId}/photos`, {
  5789. headers,
  5790. method: 'POST',
  5791. body: formData,
  5792. });
  5793. if (!response.ok) {
  5794. const error = await response.json().catch(() => ({}));
  5795. throw new Error(error.detail || `HTTP ${response.status}`);
  5796. }
  5797. return response.json();
  5798. },
  5799. deleteArchivePhoto: (archiveId: number, filename: string) =>
  5800. request<{ status: string; photos: string[] | null }>(`/archives/${archiveId}/photos/${encodeURIComponent(filename)}`, {
  5801. method: 'DELETE',
  5802. }),
  5803. // Source 3MF (original slicer project file)
  5804. getSource3mfDownloadUrl: (archiveId: number) =>
  5805. `${API_BASE}/archives/${archiveId}/source`,
  5806. downloadSource3mf: async (archiveId: number): Promise<void> => {
  5807. const headers: Record<string, string> = {};
  5808. if (authToken) {
  5809. headers['Authorization'] = `Bearer ${authToken}`;
  5810. }
  5811. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, { headers });
  5812. if (!response.ok) {
  5813. const error = await response.json().catch(() => ({}));
  5814. throw new Error(error.detail || `HTTP ${response.status}`);
  5815. }
  5816. const disposition = response.headers.get('Content-Disposition');
  5817. const filename = parseContentDispositionFilename(disposition) || `source_${archiveId}.3mf`;
  5818. const blob = await response.blob();
  5819. const url = window.URL.createObjectURL(blob);
  5820. const a = document.createElement('a');
  5821. a.href = url;
  5822. a.download = filename;
  5823. document.body.appendChild(a);
  5824. a.click();
  5825. document.body.removeChild(a);
  5826. window.URL.revokeObjectURL(url);
  5827. },
  5828. getSource3mfForSlicer: (archiveId: number, filename: string) => {
  5829. // Sanitize: slicers url_decode() the entire URL, so / \ ? # in filenames break path routing
  5830. const safe = filename.replace(/[/\\?#]/g, '_');
  5831. return `${API_BASE}/archives/${archiveId}/source/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  5832. },
  5833. createSourceSlicerToken: (archiveId: number) =>
  5834. request<{ token: string }>(`/archives/${archiveId}/source-slicer-token`, { method: 'POST' }),
  5835. getSourceSlicerDownloadUrl: (archiveId: number, token: string, filename: string) => {
  5836. const safe = filename.replace(/[/\\?#]/g, '_');
  5837. return `${API_BASE}/archives/${archiveId}/source-dl/${token}/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  5838. },
  5839. uploadSource3mf: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  5840. const formData = new FormData();
  5841. formData.append('file', file);
  5842. const headers: Record<string, string> = {};
  5843. if (authToken) {
  5844. headers['Authorization'] = `Bearer ${authToken}`;
  5845. }
  5846. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, {
  5847. method: 'POST',
  5848. headers,
  5849. body: formData,
  5850. });
  5851. if (!response.ok) {
  5852. const error = await response.json().catch(() => ({}));
  5853. throw new Error(error.detail || `HTTP ${response.status}`);
  5854. }
  5855. return response.json();
  5856. },
  5857. deleteSource3mf: (archiveId: number) =>
  5858. request<{ status: string }>(`/archives/${archiveId}/source`, {
  5859. method: 'DELETE',
  5860. }),
  5861. // F3D (Fusion 360 design file)
  5862. downloadF3d: async (archiveId: number): Promise<void> => {
  5863. const headers: Record<string, string> = {};
  5864. if (authToken) {
  5865. headers['Authorization'] = `Bearer ${authToken}`;
  5866. }
  5867. const response = await fetch(`${API_BASE}/archives/${archiveId}/f3d`, { headers });
  5868. if (!response.ok) {
  5869. const error = await response.json().catch(() => ({}));
  5870. throw new Error(error.detail || `HTTP ${response.status}`);
  5871. }
  5872. const disposition = response.headers.get('Content-Disposition');
  5873. const filename = parseContentDispositionFilename(disposition) || `archive_${archiveId}.f3d`;
  5874. const blob = await response.blob();
  5875. const url = window.URL.createObjectURL(blob);
  5876. const a = document.createElement('a');
  5877. a.href = url;
  5878. a.download = filename;
  5879. document.body.appendChild(a);
  5880. a.click();
  5881. document.body.removeChild(a);
  5882. window.URL.revokeObjectURL(url);
  5883. },
  5884. uploadF3d: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  5885. const formData = new FormData();
  5886. formData.append('file', file);
  5887. const headers: Record<string, string> = {};
  5888. if (authToken) {
  5889. headers['Authorization'] = `Bearer ${authToken}`;
  5890. }
  5891. const response = await fetch(`${API_BASE}/archives/${archiveId}/f3d`, {
  5892. method: 'POST',
  5893. headers,
  5894. body: formData,
  5895. });
  5896. if (!response.ok) {
  5897. const error = await response.json().catch(() => ({}));
  5898. throw new Error(error.detail || `HTTP ${response.status}`);
  5899. }
  5900. return response.json();
  5901. },
  5902. deleteF3d: (archiveId: number) =>
  5903. request<{ status: string }>(`/archives/${archiveId}/f3d`, {
  5904. method: 'DELETE',
  5905. }),
  5906. // QR Code
  5907. getArchiveQRCodeUrl: (archiveId: number, size = 200) =>
  5908. withMediaToken(`${API_BASE}/archives/${archiveId}/qrcode?size=${size}`),
  5909. getArchiveCapabilities: (id: number) =>
  5910. request<{
  5911. has_model: boolean;
  5912. has_gcode: boolean;
  5913. has_source: boolean;
  5914. build_volume: { x: number; y: number; z: number };
  5915. filament_colors: string[];
  5916. }>(`/archives/${id}/capabilities`),
  5917. // Project Page
  5918. getArchiveProjectPage: (id: number) =>
  5919. request<{
  5920. title: string | null;
  5921. description: string | null;
  5922. designer: string | null;
  5923. designer_user_id: string | null;
  5924. license: string | null;
  5925. copyright: string | null;
  5926. creation_date: string | null;
  5927. modification_date: string | null;
  5928. origin: string | null;
  5929. profile_title: string | null;
  5930. profile_description: string | null;
  5931. profile_cover: string | null;
  5932. profile_user_id: string | null;
  5933. profile_user_name: string | null;
  5934. design_model_id: string | null;
  5935. design_profile_id: string | null;
  5936. design_region: string | null;
  5937. model_pictures: Array<{ name: string; path: string; url: string }>;
  5938. profile_pictures: Array<{ name: string; path: string; url: string }>;
  5939. thumbnails: Array<{ name: string; path: string; url: string }>;
  5940. }>(`/archives/${id}/project-page`),
  5941. updateArchiveProjectPage: (id: number, data: {
  5942. title?: string;
  5943. description?: string;
  5944. designer?: string;
  5945. license?: string;
  5946. copyright?: string;
  5947. profile_title?: string;
  5948. profile_description?: string;
  5949. }) =>
  5950. request(`/archives/${id}/project-page`, {
  5951. method: 'PATCH',
  5952. body: JSON.stringify(data),
  5953. }),
  5954. getArchiveForSlicer: (id: number, filename: string) => {
  5955. const safe = filename.replace(/[/\\?#]/g, '_');
  5956. return `${API_BASE}/archives/${id}/file/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  5957. },
  5958. createArchiveSlicerToken: (archiveId: number) =>
  5959. request<{ token: string }>(`/archives/${archiveId}/slicer-token`, { method: 'POST' }),
  5960. getArchiveSlicerDownloadUrl: (archiveId: number, token: string, filename: string) => {
  5961. const safe = filename.replace(/[/\\?#]/g, '_');
  5962. return `${API_BASE}/archives/${archiveId}/dl/${token}/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  5963. },
  5964. getArchivePlates: (archiveId: number) =>
  5965. request<ArchivePlatesResponse>(`/archives/${archiveId}/plates`),
  5966. getArchiveFilamentRequirements: (
  5967. archiveId: number,
  5968. plateId?: number,
  5969. requestId?: string,
  5970. /** Ask for one entry per project slot instead of only the slots this
  5971. * plate consumes. The slice modal needs it: its filament list is
  5972. * positional, so a source whose only used slot is 4 must still present
  5973. * four rows or the user's pick is bound to slot 1 (#2712). Print-time
  5974. * AMS matching must NOT set this — it wants the used-only list. */
  5975. fullSlots?: boolean,
  5976. ) => {
  5977. const qs = new URLSearchParams();
  5978. if (plateId !== undefined) qs.set('plate_id', String(plateId));
  5979. if (requestId) qs.set('request_id', requestId);
  5980. if (fullSlots) qs.set('full_slots', 'true');
  5981. return request<{
  5982. archive_id: number;
  5983. filename: string;
  5984. plate_id: number | null;
  5985. filaments: Array<{
  5986. slot_id: number;
  5987. type: string;
  5988. color: string;
  5989. used_grams: number;
  5990. used_meters: number;
  5991. used_in_plate?: boolean;
  5992. }>;
  5993. }>(`/archives/${archiveId}/filament-requirements${qs.toString() ? `?${qs}` : ''}`);
  5994. },
  5995. uploadArchivesBulk: async (files: File[], printerId?: number): Promise<BulkUploadResult> => {
  5996. const formData = new FormData();
  5997. files.forEach((file) => formData.append('files', file));
  5998. const url = printerId
  5999. ? `${API_BASE}/archives/upload-bulk?printer_id=${printerId}`
  6000. : `${API_BASE}/archives/upload-bulk`;
  6001. const headers: Record<string, string> = {};
  6002. if (authToken) {
  6003. headers['Authorization'] = `Bearer ${authToken}`;
  6004. }
  6005. const response = await fetch(url, {
  6006. method: 'POST',
  6007. headers,
  6008. body: formData,
  6009. });
  6010. if (!response.ok) {
  6011. const error = await response.json().catch(() => ({}));
  6012. throw new Error(error.detail || `HTTP ${response.status}`);
  6013. }
  6014. return response.json();
  6015. },
  6016. // Print Log
  6017. getPrintLog: (params?: {
  6018. search?: string;
  6019. printerId?: number;
  6020. username?: string;
  6021. status?: string;
  6022. dateFrom?: string;
  6023. dateTo?: string;
  6024. limit?: number;
  6025. offset?: number;
  6026. // Sorting is server-side because paging is: ordering only the rows the
  6027. // client holds would sort one page, not the log (#2636).
  6028. sortBy?: string;
  6029. sortDir?: 'asc' | 'desc';
  6030. }) => {
  6031. const searchParams = new URLSearchParams();
  6032. if (params?.search) searchParams.set('search', params.search);
  6033. if (params?.printerId) searchParams.set('printer_id', String(params.printerId));
  6034. if (params?.username) searchParams.set('created_by_username', params.username);
  6035. if (params?.status) searchParams.set('status', params.status);
  6036. if (params?.dateFrom) searchParams.set('date_from', params.dateFrom);
  6037. if (params?.dateTo) searchParams.set('date_to', params.dateTo);
  6038. if (params?.limit) searchParams.set('limit', String(params.limit));
  6039. if (params?.offset !== undefined) searchParams.set('offset', String(params.offset));
  6040. if (params?.sortBy) searchParams.set('sort_by', params.sortBy);
  6041. if (params?.sortDir) searchParams.set('sort_dir', params.sortDir);
  6042. return request<PrintLogResponse>(`/print-log/?${searchParams}`);
  6043. },
  6044. getPrintLogThumbnail: (id: number) => withMediaToken(`${API_BASE}/print-log/${id}/thumbnail`),
  6045. clearPrintLog: () =>
  6046. request<{ deleted: number }>('/print-log/', { method: 'DELETE' }),
  6047. deletePrintLogEntry: (id: number) =>
  6048. request<{ status: string; id: number }>(`/print-log/${id}`, { method: 'DELETE' }),
  6049. // Edit failure_reason / status on a single Print Log row (#1687 part 4).
  6050. // Distinct from updateArchive: archives describe the model, log entries
  6051. // describe a single print event. Orphan entries (no archive_id) have no
  6052. // archive to reach through and this is the only path to classify them.
  6053. updatePrintLogEntry: (
  6054. id: number,
  6055. body: { failure_reason?: string | null; status?: string; notes?: string | null },
  6056. ) =>
  6057. request<PrintLogEntry>(`/print-log/${id}`, {
  6058. method: 'PATCH',
  6059. body: JSON.stringify(body),
  6060. }),
  6061. // Settings
  6062. getSettings: () => request<AppSettings>('/settings/'),
  6063. getDefaultSidebarOrder: () => request<{ default_sidebar_order: string }>('/settings/default-sidebar-order'),
  6064. // Public subset of settings for UI rendering — no settings:read required.
  6065. // Used by pages whose users may not have SETTINGS_READ (e.g. operators with
  6066. // only printers:clear_plate). Keep in sync with _UI_PREFERENCE_FIELDS in
  6067. // backend/app/api/routes/settings.py.
  6068. getUiPreferences: () =>
  6069. request<{
  6070. require_plate_clear?: boolean;
  6071. check_printer_firmware?: boolean;
  6072. camera_view_mode?: 'window' | 'embedded';
  6073. time_format?: 'system' | '12h' | '24h';
  6074. date_format?: string;
  6075. drying_presets?: string;
  6076. ams_humidity_thresholds?: string;
  6077. ams_humidity_good?: number;
  6078. ams_humidity_fair?: number;
  6079. ams_temp_good?: number;
  6080. ams_temp_fair?: number;
  6081. bed_cooled_threshold?: number;
  6082. nozzle_temp_presets?: string;
  6083. bed_temp_presets?: string;
  6084. chamber_temp_presets?: string;
  6085. fan_speed_presets?: string;
  6086. }>('/settings/ui-preferences'),
  6087. // Install configuration the app shell needs, for any signed-in user. Separate
  6088. // from getUiPreferences: that endpoint is public because its fields are
  6089. // defaults shipped with the app, while these describe how this deployment is
  6090. // configured. Neither requires settings:read -- which is the point, since a
  6091. // non-admin reading GET /settings gets a 403 and every gate that consults it
  6092. // silently takes its fallback (#3023). Keep in sync with _UI_FLAG_FIELDS in
  6093. // backend/app/api/routes/settings.py.
  6094. getUiFlags: () => request<UiSettings>('/settings/ui-flags'),
  6095. // The two above together: what a page needs from the settings when its user
  6096. // may not read GET /settings. See useUiSettings.
  6097. getUiSettings: async (): Promise<UiSettings> => {
  6098. const [preferences, flags] = await Promise.all([api.getUiPreferences(), api.getUiFlags()]);
  6099. return { ...(preferences as UiSettings), ...flags };
  6100. },
  6101. updateSettings: (data: AppSettingsUpdate) =>
  6102. request<AppSettings>('/settings/', {
  6103. method: 'PUT',
  6104. body: JSON.stringify(data),
  6105. }),
  6106. getMQTTStatus: () => request<MQTTStatus>('/settings/mqtt/status'),
  6107. exportBackup: async (): Promise<{ blob: Blob; filename: string }> => {
  6108. // New simplified backup - complete database + all files
  6109. const url = `${API_BASE}/settings/backup`;
  6110. const headers: Record<string, string> = {};
  6111. if (authToken) {
  6112. headers['Authorization'] = `Bearer ${authToken}`;
  6113. }
  6114. const response = await fetch(url, { headers });
  6115. // Check for errors
  6116. if (!response.ok) {
  6117. const errorText = await response.text();
  6118. throw new Error(errorText || `Backup failed with status ${response.status}`);
  6119. }
  6120. // Get filename from Content-Disposition header
  6121. const contentDisposition = response.headers.get('Content-Disposition');
  6122. let filename = 'bambuddy-backup.zip';
  6123. if (contentDisposition) {
  6124. const match = contentDisposition.match(/filename=([^;]+)/);
  6125. if (match) filename = match[1].trim().replace(/^"(.*)"$/, '$1');
  6126. }
  6127. const blob = await response.blob();
  6128. return { blob, filename };
  6129. },
  6130. importBackup: async (file: File) => {
  6131. // New simplified restore - replaces database + all directories
  6132. const formData = new FormData();
  6133. formData.append('file', file);
  6134. const url = `${API_BASE}/settings/restore`;
  6135. const headers: Record<string, string> = {};
  6136. if (authToken) {
  6137. headers['Authorization'] = `Bearer ${authToken}`;
  6138. }
  6139. const response = await fetch(url, {
  6140. method: 'POST',
  6141. headers,
  6142. body: formData,
  6143. });
  6144. const data = (await response.json().catch(() => null)) as {
  6145. success?: boolean;
  6146. message?: string;
  6147. detail?: string;
  6148. } | null;
  6149. // A refused restore is an HTTPException, so the body is {detail}, not
  6150. // {success, message}. Returning it unmapped made `success` undefined and
  6151. // `message` undefined too — the modal then raised an empty error toast,
  6152. // which is the one case where the reason matters most (e.g. a backup this
  6153. // version cannot import names the columns and both versions).
  6154. if (!response.ok) {
  6155. return { success: false, message: data?.detail ?? data?.message ?? '' };
  6156. }
  6157. return (data ?? { success: false, message: '' }) as {
  6158. success: boolean;
  6159. message: string;
  6160. };
  6161. },
  6162. checkFfmpeg: () =>
  6163. request<{ installed: boolean; path: string | null }>('/settings/check-ffmpeg'),
  6164. getNetworkInterfaces: () =>
  6165. request<{ interfaces: NetworkInterface[] }>('/settings/network-interfaces'),
  6166. // Cloud
  6167. getCloudStatus: () => request<CloudAuthStatus>('/cloud/status'),
  6168. cloudLogin: (email: string, password: string, region = 'global') =>
  6169. request<CloudLoginResponse>('/cloud/login', {
  6170. method: 'POST',
  6171. body: JSON.stringify({ email, password, region }),
  6172. }),
  6173. cloudVerify: (email: string, code: string, tfaKey?: string, region: string = 'global') =>
  6174. request<CloudLoginResponse>('/cloud/verify', {
  6175. method: 'POST',
  6176. body: JSON.stringify({ email, code, tfa_key: tfaKey, region }),
  6177. }),
  6178. cloudSetToken: (access_token: string, region: string = 'global') =>
  6179. request<CloudAuthStatus>('/cloud/token', {
  6180. method: 'POST',
  6181. body: JSON.stringify({ access_token, region }),
  6182. }),
  6183. cloudLogout: () =>
  6184. request<{ success: boolean }>('/cloud/logout', { method: 'POST' }),
  6185. // Orca Cloud — RFC 8628 device pairing. deviceStart() returns a short
  6186. // user_code + verification link; the user approves it in their Orca Cloud
  6187. // settings while the frontend polls devicePoll() every `interval` seconds
  6188. // until the status flips to 'complete' (or a terminal deny/expire).
  6189. orcaCloudDeviceStart: () =>
  6190. request<OrcaDeviceStartResponse>('/orca-cloud/device/start', {
  6191. method: 'POST',
  6192. }),
  6193. orcaCloudDevicePoll: () =>
  6194. request<OrcaDevicePollResponse>('/orca-cloud/device/poll', {
  6195. method: 'POST',
  6196. }),
  6197. orcaCloudStatus: () =>
  6198. request<OrcaAuthStatusResponse>('/orca-cloud/status'),
  6199. orcaCloudLogout: () =>
  6200. request<{ success: boolean }>('/orca-cloud/logout', { method: 'POST' }),
  6201. orcaCloudListProfiles: () =>
  6202. request<OrcaProfileListResponse>('/orca-cloud/profiles'),
  6203. orcaCloudGetProfile: (id: string) =>
  6204. request<OrcaProfileDetail>(`/orca-cloud/profiles/${id}`),
  6205. getCloudSettings: (version = '02.04.00.70') =>
  6206. request<SlicerSettingsResponse>(`/cloud/settings?version=${version}`),
  6207. getBuiltinFilaments: () =>
  6208. request<BuiltinFilament[]>('/cloud/builtin-filaments'),
  6209. getFilamentIdMap: () =>
  6210. request<Record<string, string>>('/cloud/filament-id-map'),
  6211. /** Material-disambiguated hex→name lookup. Same hex can map to different
  6212. * catalog names depending on material (e.g. #000000 is "Charcoal" in PLA
  6213. * Matte but "Black" in PLA Basic). The flat ``/inventory/colors/map``
  6214. * collapses these to the first hit; this endpoint preserves the material
  6215. * context. Returns ``{color_name: null}`` when the hex isn't in the
  6216. * catalog at all. #1718. */
  6217. getColorByMaterial: (hex: string, material?: string) => {
  6218. const params = new URLSearchParams({ hex });
  6219. if (material) params.set('material', material);
  6220. return request<{ color_name: string | null }>(
  6221. `/inventory/colors/by-material?${params.toString()}`,
  6222. );
  6223. },
  6224. // MakerWorld URL-paste import flow.
  6225. getMakerworldStatus: () =>
  6226. request<MakerworldStatus>('/makerworld/status'),
  6227. resolveMakerworldUrl: (url: string) =>
  6228. request<MakerworldResolvedModel>('/makerworld/resolve', {
  6229. method: 'POST',
  6230. body: JSON.stringify({ url }),
  6231. }),
  6232. getMakerworldRecentImports: (limit = 10) =>
  6233. request<MakerworldRecentImport[]>(`/makerworld/recent-imports?limit=${limit}`),
  6234. importMakerworldInstance: (
  6235. model_id: number,
  6236. instance_id: number | null,
  6237. profile_id?: number | null,
  6238. folder_id?: number | null,
  6239. ) =>
  6240. request<MakerworldImportResponse>('/makerworld/import', {
  6241. method: 'POST',
  6242. body: JSON.stringify({
  6243. model_id,
  6244. instance_id: instance_id ?? null,
  6245. profile_id: profile_id ?? null,
  6246. folder_id: folder_id ?? null,
  6247. }),
  6248. }),
  6249. // Manyfold (#1471).
  6250. getManyfoldConfig: () => request<ManyfoldConfig>('/manyfold/config'),
  6251. updateManyfoldConfig: (data: ManyfoldConfigInput) =>
  6252. request<ManyfoldConfig>('/manyfold/config', { method: 'PUT', body: JSON.stringify(data) }),
  6253. deleteManyfoldConfig: () => request<void>('/manyfold/config', { method: 'DELETE' }),
  6254. testManyfoldConfig: (data: ManyfoldConfigInput) =>
  6255. request<{ model_count: number }>('/manyfold/config/test', { method: 'POST', body: JSON.stringify(data) }),
  6256. getManyfoldStatus: () => request<ManyfoldStatus>('/manyfold/status'),
  6257. listManyfoldModels: (query: string, page: number) => {
  6258. const params = new URLSearchParams({ page: String(page) });
  6259. if (query) params.set('q', query);
  6260. return request<ManyfoldModelList>(`/manyfold/models?${params.toString()}`);
  6261. },
  6262. getManyfoldModel: (modelId: string) =>
  6263. request<ManyfoldModel>(`/manyfold/models/${encodeURIComponent(modelId)}`),
  6264. /** The model's preview, or null when it has none. Fetched rather than used
  6265. * as an <img src>: a failing protected <img> makes the app renew its media
  6266. * token, and models without a preview answer 404. */
  6267. getManyfoldPreview: async (modelId: string): Promise<Blob | null> => {
  6268. const headers: Record<string, string> = {};
  6269. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  6270. const response = await fetch(`${API_BASE}/manyfold/models/${encodeURIComponent(modelId)}/preview`, { headers });
  6271. if (!response.ok) return null;
  6272. return response.blob();
  6273. },
  6274. importManyfoldFile: (modelId: string, fileId: string, folderId: number | null) =>
  6275. request<ManyfoldImportResponse>('/manyfold/import', {
  6276. method: 'POST',
  6277. body: JSON.stringify({ model_id: modelId, file_id: fileId, folder_id: folderId }),
  6278. }),
  6279. getCloudSettingDetail: (settingId: string) =>
  6280. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`),
  6281. createCloudSetting: (data: SlicerSettingCreate) =>
  6282. request<SlicerSettingDetail>('/cloud/settings', {
  6283. method: 'POST',
  6284. body: JSON.stringify(data),
  6285. }),
  6286. updateCloudSetting: (settingId: string, data: SlicerSettingUpdate) =>
  6287. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`, {
  6288. method: 'PUT',
  6289. body: JSON.stringify(data),
  6290. }),
  6291. deleteCloudSetting: (settingId: string) =>
  6292. request<SlicerSettingDeleteResponse>(`/cloud/settings/${settingId}`, {
  6293. method: 'DELETE',
  6294. }),
  6295. getCloudFields: (presetType: 'filament' | 'print' | 'process' | 'printer') =>
  6296. request<FieldDefinitionsResponse>(`/cloud/fields/${presetType}`),
  6297. getFilamentInfo: (settingIds: string[]) =>
  6298. request<Record<string, { name: string; k: number | null }>>('/cloud/filament-info', {
  6299. method: 'POST',
  6300. body: JSON.stringify(settingIds),
  6301. }),
  6302. // Smart Plugs
  6303. getSmartPlugs: () => request<SmartPlug[]>('/smart-plugs/'),
  6304. getSmartPlugByPrinter: (printerId: number) => smartPlugBatch(printerId),
  6305. getScriptPlugsByPrinter: (printerId: number) => scriptPlugsBatch(printerId),
  6306. createSmartPlug: (data: SmartPlugCreate) =>
  6307. request<SmartPlug>('/smart-plugs/', {
  6308. method: 'POST',
  6309. body: JSON.stringify(data),
  6310. }),
  6311. updateSmartPlug: (id: number, data: SmartPlugUpdate) =>
  6312. request<SmartPlug>(`/smart-plugs/${id}`, {
  6313. method: 'PATCH',
  6314. body: JSON.stringify(data),
  6315. }),
  6316. deleteSmartPlug: (id: number) =>
  6317. request<void>(`/smart-plugs/${id}`, { method: 'DELETE' }),
  6318. controlSmartPlug: (id: number, action: 'on' | 'off' | 'toggle') =>
  6319. request<{ success: boolean; action: string }>(`/smart-plugs/${id}/control`, {
  6320. method: 'POST',
  6321. body: JSON.stringify({ action }),
  6322. }),
  6323. getSmartPlugStatus: (id: number) =>
  6324. request<SmartPlugStatus>(`/smart-plugs/${id}/status`),
  6325. // plug_id: the saved plug being edited, whose stored password fills in the placeholder.
  6326. testSmartPlugConnection: (ip_address: string, username?: string | null, password?: string | null, plug_id?: number) =>
  6327. request<SmartPlugTestResult>('/smart-plugs/test-connection', {
  6328. method: 'POST',
  6329. body: JSON.stringify({ ip_address, username, password, plug_id }),
  6330. }),
  6331. // Tasmota Discovery (auto-detects network)
  6332. startTasmotaScan: () =>
  6333. request<TasmotaScanStatus>('/smart-plugs/discover/scan', { method: 'POST' }),
  6334. getTasmotaScanStatus: () =>
  6335. request<TasmotaScanStatus>('/smart-plugs/discover/status'),
  6336. stopTasmotaScan: () =>
  6337. request<TasmotaScanStatus>('/smart-plugs/discover/stop', { method: 'POST' }),
  6338. getDiscoveredTasmotaDevices: () =>
  6339. request<DiscoveredTasmotaDevice[]>('/smart-plugs/discover/devices'),
  6340. // Home Assistant Integration
  6341. testHAConnection: (url: string, token: string) =>
  6342. request<HATestConnectionResult>('/smart-plugs/ha/test-connection', {
  6343. method: 'POST',
  6344. body: JSON.stringify({ url, token }),
  6345. }),
  6346. getHAEntities: (search?: string) => {
  6347. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  6348. return request<HAEntity[]>(`/smart-plugs/ha/entities${params}`);
  6349. },
  6350. getHASensorEntities: () =>
  6351. request<HASensorEntity[]>('/smart-plugs/ha/sensors'),
  6352. // Home Assistant sensors bound to a printer (#1148, #448)
  6353. getHASensors: (printerId?: number) =>
  6354. request<PrinterHASensor[]>(`/ha-sensors/${printerId ? `?printer_id=${printerId}` : ''}`),
  6355. getHASensorReadings: (printerId: number) => haSensorReadingsBatch(printerId),
  6356. getBindableHAEntities: (search?: string) => {
  6357. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  6358. return request<HADisplayEntity[]>(`/ha-sensors/entities${params}`);
  6359. },
  6360. createHASensor: (data: PrinterHASensorCreate) =>
  6361. request<PrinterHASensor>('/ha-sensors/', { method: 'POST', body: JSON.stringify(data) }),
  6362. updateHASensor: (id: number, data: PrinterHASensorUpdate) =>
  6363. request<PrinterHASensor>(`/ha-sensors/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  6364. deleteHASensor: (id: number) =>
  6365. request<{ message: string }>(`/ha-sensors/${id}`, { method: 'DELETE' }),
  6366. getLocationHASensors: (locationId?: number) =>
  6367. request<LocationHASensor[]>(`/location-ha-sensors/${locationId ? `?location_id=${locationId}` : ''}`),
  6368. getLocationHASensorReadings: (locationId: number, showOnCard = true) =>
  6369. request<LocationHASensorReading[]>(
  6370. `/location-ha-sensors/by-location/${locationId}/readings?show_on_card=${showOnCard}`
  6371. ),
  6372. getBindableLocationHAEntities: (search?: string) => {
  6373. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  6374. return request<HADisplayEntity[]>(`/location-ha-sensors/entities${params}`);
  6375. },
  6376. createLocationHASensor: (data: LocationHASensorCreate) =>
  6377. request<LocationHASensor>('/location-ha-sensors/', { method: 'POST', body: JSON.stringify(data) }),
  6378. updateLocationHASensor: (id: number, data: LocationHASensorUpdate) =>
  6379. request<LocationHASensor>(`/location-ha-sensors/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  6380. deleteLocationHASensor: (id: number) =>
  6381. request<{ message: string }>(`/location-ha-sensors/${id}`, { method: 'DELETE' }),
  6382. // REST smart plug
  6383. // plug_id: the saved plug being edited, whose stored headers fill in the placeholder.
  6384. testRESTConnection: (url: string, method: string = 'GET', headers?: string | null, plug_id?: number) =>
  6385. request<{ success: boolean; error: string | null }>('/smart-plugs/rest/test-connection', {
  6386. method: 'POST',
  6387. body: JSON.stringify({ url, method, headers, plug_id }),
  6388. }),
  6389. // Print Queue
  6390. getQueue: (printerId?: number, status?: string, targetModel?: string) => {
  6391. const params = new URLSearchParams();
  6392. if (printerId) params.set('printer_id', String(printerId));
  6393. if (status) params.set('status', status);
  6394. if (targetModel) params.set('target_model', targetModel);
  6395. return request<PrintQueueItem[]>(`/queue/?${params}`);
  6396. },
  6397. // History (completed / failed / skipped / cancelled), one page at a time.
  6398. getQueueHistory: (params: QueueHistoryParams) =>
  6399. request<QueueHistoryPage>(`/queue/history?${queueHistorySearch(params)}`),
  6400. // Removes the history matching the same filters, server-side.
  6401. clearQueueHistory: (params: QueueHistoryFilters) =>
  6402. request<{ cleared: number; kept: number }>(`/queue/history/clear?${queueHistorySearch(params)}`, {
  6403. method: 'POST',
  6404. }),
  6405. // One printer's queue as GET /queue/?printer_id= returns it: its own jobs
  6406. // plus the "Any <model>" jobs for its model. Batched across printer cards.
  6407. getPrinterQueue: (printerId: number, status: string) => printerQueueBatch(status)(printerId),
  6408. addToQueue: (data: PrintQueueItemCreate) =>
  6409. request<PrintQueueItem>('/queue/', {
  6410. method: 'POST',
  6411. body: JSON.stringify(data),
  6412. }),
  6413. updateQueueItem: (id: number, data: PrintQueueItemUpdate) =>
  6414. request<PrintQueueItem>(`/queue/${id}`, {
  6415. method: 'PATCH',
  6416. body: JSON.stringify(data),
  6417. }),
  6418. /** `deleted` is false when the item was kept as cancelled instead: it is the
  6419. * last run a batch order could re-queue its plate from (#2960). */
  6420. removeFromQueue: (id: number) =>
  6421. request<{ message: string; deleted: boolean }>(`/queue/${id}`, { method: 'DELETE' }),
  6422. reorderQueue: (items: { id: number; position: number }[]) =>
  6423. request<{ message: string }>('/queue/reorder', {
  6424. method: 'POST',
  6425. body: JSON.stringify({ items }),
  6426. }),
  6427. cancelQueueItem: (id: number) =>
  6428. request<{ message: string }>(`/queue/${id}/cancel`, { method: 'POST' }),
  6429. stopQueueItem: (id: number) =>
  6430. request<{ message: string }>(`/queue/${id}/stop`, { method: 'POST' }),
  6431. /**
  6432. * Start a staged queue item. The backend re-checks live filament deficit
  6433. * for the assigned spool and, when short, returns 409 with a structured
  6434. * payload so the caller can confirm and retry. Pass `skipFilamentCheck`
  6435. * after the user confirms "Print Anyway" (#1496).
  6436. */
  6437. startQueueItem: (id: number, opts?: { skipFilamentCheck?: boolean }) => {
  6438. const qs = opts?.skipFilamentCheck ? '?skip_filament_check=true' : '';
  6439. return request<PrintQueueItem>(`/queue/${id}/start${qs}`, { method: 'POST' });
  6440. },
  6441. /**
  6442. * Clear the `require_previous_success` gate for a printer after the user
  6443. * resolves the failure. Acknowledges any failed/aborted predecessors and
  6444. * restores skipped items whose error_message matches the gate string
  6445. * back to pending. Returns counts so the UI can render a precise toast.
  6446. */
  6447. // A job for any printer of a model waits when the last print failed on every
  6448. // free one; this clears the gate on the model's printers.
  6449. resumeModelQueueAfterFailure: (model: string) =>
  6450. request<{ acknowledged: number; printers: number }>(
  6451. `/queue/model/${encodeURIComponent(model)}/resume`,
  6452. { method: 'POST' },
  6453. ),
  6454. resumeQueueAfterFailure: (printerId: number) =>
  6455. request<{ acknowledged: number; restored: number }>(
  6456. `/queue/printer/${printerId}/resume`,
  6457. { method: 'POST' },
  6458. ),
  6459. bulkUpdateQueue: (data: PrintQueueBulkUpdate) =>
  6460. request<PrintQueueBulkUpdateResponse>('/queue/bulk', {
  6461. method: 'PATCH',
  6462. body: JSON.stringify(data),
  6463. }),
  6464. // Batches
  6465. getBatches: (status?: string) => {
  6466. const params = status ? `?status=${status}` : '';
  6467. return request<PrintBatch[]>(`/queue/batches${params}`);
  6468. },
  6469. cancelBatch: (id: number) =>
  6470. request<{ message: string }>(`/queue/batches/${id}`, { method: 'DELETE' }),
  6471. createBatch: (data: PrintBatchCreate) =>
  6472. request<PrintBatch>('/queue/batches', {
  6473. method: 'POST',
  6474. body: JSON.stringify(data),
  6475. }),
  6476. dispatchBatch: (id: number, data: PrintBatchDispatchRequest = {}) =>
  6477. request<PrintBatch>(`/queue/batches/${id}/dispatch`, {
  6478. method: 'POST',
  6479. body: JSON.stringify(data),
  6480. }),
  6481. ungroupBatch: (id: number) =>
  6482. request<{ ungrouped_count: number; message: string }>(
  6483. `/queue/batches/${id}/ungroup`,
  6484. { method: 'POST' },
  6485. ),
  6486. // K-Profiles
  6487. getKProfiles: (printerId: number, nozzleDiameter = '0.4') =>
  6488. request<KProfilesResponse>(`/printers/${printerId}/kprofiles/?nozzle_diameter=${nozzleDiameter}`),
  6489. setKProfile: (printerId: number, profile: KProfileCreate) =>
  6490. request<KProfileWriteResult>(`/printers/${printerId}/kprofiles/`, {
  6491. method: 'POST',
  6492. body: JSON.stringify(profile),
  6493. }),
  6494. deleteKProfile: (printerId: number, profile: KProfileDelete) =>
  6495. request<KProfileWriteResult>(`/printers/${printerId}/kprofiles/`, {
  6496. method: 'DELETE',
  6497. body: JSON.stringify(profile),
  6498. }),
  6499. setKProfilesBatch: (printerId: number, profiles: KProfileCreate[]) =>
  6500. request<KProfileWriteResult>(`/printers/${printerId}/kprofiles/batch`, {
  6501. method: 'POST',
  6502. body: JSON.stringify(profiles),
  6503. }),
  6504. // Finance
  6505. getMyBalance: () => request<WalletBalance>('/finance/me/balance'),
  6506. getMyTransactions: (limit = 50, offset = 0) =>
  6507. request<WalletTransactionListResponse>(`/finance/me/transactions?limit=${limit}&offset=${offset}`),
  6508. getAllTransactions: (limit = 50, offset = 0, userId?: number) => {
  6509. const params = new URLSearchParams();
  6510. params.set('limit', String(limit));
  6511. params.set('offset', String(offset));
  6512. if (userId !== undefined) params.set('user_id', String(userId));
  6513. return request<WalletTransactionListResponse>(`/finance/transactions?${params.toString()}`);
  6514. },
  6515. deleteTransaction: (transactionId: number) =>
  6516. request<{ status: string }>(`/finance/transactions/${transactionId}`, {
  6517. method: 'DELETE',
  6518. }),
  6519. editTransaction: (transactionId: number, data: TransactionEditRequest) =>
  6520. request<WalletTransaction>(`/finance/transactions/${transactionId}`, {
  6521. method: 'PATCH',
  6522. body: JSON.stringify(data),
  6523. }),
  6524. createManualPrint: (data: ManualPrintRequest) =>
  6525. request<WalletTransaction>('/finance/transactions/manual', {
  6526. method: 'POST',
  6527. body: JSON.stringify(data),
  6528. }),
  6529. getMyCostCenters: () => request<CostCenterSummary[]>('/finance/cost-centers/mine'),
  6530. listCostCenters: (includeInactive = false) =>
  6531. request<CostCenterSummary[]>(`/finance/cost-centers?include_inactive=${includeInactive ? 'true' : 'false'}`),
  6532. createCostCenter: (data: CostCenterCreateRequest) =>
  6533. request<CostCenterSummary>('/finance/cost-centers', {
  6534. method: 'POST',
  6535. body: JSON.stringify(data),
  6536. }),
  6537. updateCostCenter: (costCenterId: number, data: CostCenterUpdateRequest) =>
  6538. request<CostCenterSummary>(`/finance/cost-centers/${costCenterId}`, {
  6539. method: 'PATCH',
  6540. body: JSON.stringify(data),
  6541. }),
  6542. updateCostCenterBudgets: (costCenterId: number, data: CostCenterBudgetUpdateRequest) =>
  6543. request<CostCenterSummary>(`/finance/cost-centers/${costCenterId}/budgets`, {
  6544. method: 'PATCH',
  6545. body: JSON.stringify(data),
  6546. }),
  6547. deleteCostCenter: (costCenterId: number) =>
  6548. request<{ status: string }>(`/finance/cost-centers/${costCenterId}`, {
  6549. method: 'DELETE',
  6550. }),
  6551. getCostCenter: (costCenterId: number) =>
  6552. request<CostCenterDetail>(`/finance/cost-centers/${costCenterId}`),
  6553. upsertCostCenterMember: (costCenterId: number, data: CostCenterMemberRequest) =>
  6554. request<CostCenterMemberResponse>(`/finance/cost-centers/${costCenterId}/members`, {
  6555. method: 'POST',
  6556. body: JSON.stringify(data),
  6557. }),
  6558. removeCostCenterMember: (costCenterId: number, userId: number) =>
  6559. request<{ status: string }>(`/finance/cost-centers/${costCenterId}/members/${userId}`, {
  6560. method: 'DELETE',
  6561. }),
  6562. depositUserBalance: (userId: number, data: WalletAdjustmentRequest) =>
  6563. request<WalletAdjustmentResponse>(`/finance/users/${userId}/deposit`, {
  6564. method: 'POST',
  6565. body: JSON.stringify(data),
  6566. }),
  6567. withdrawUserBalance: (userId: number, data: WalletAdjustmentRequest) =>
  6568. request<WalletAdjustmentResponse>(`/finance/users/${userId}/withdraw`, {
  6569. method: 'POST',
  6570. body: JSON.stringify(data),
  6571. }),
  6572. rebuildBalanceLedger: () =>
  6573. request<{ status: string }>('/finance/rebuild-balance-ledger', {
  6574. method: 'POST',
  6575. }),
  6576. // K-Profile Notes (stored locally, not on printer)
  6577. getKProfileNotes: (printerId: number) =>
  6578. request<KProfileNotesResponse>(`/printers/${printerId}/kprofiles/notes`),
  6579. setKProfileNote: (printerId: number, settingId: string, note: string) =>
  6580. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/notes`, {
  6581. method: 'PUT',
  6582. body: JSON.stringify({ setting_id: settingId, note }),
  6583. }),
  6584. // Slot Preset Mappings
  6585. getSlotPresets: (printerId: number) => slotPresetsBatch(printerId),
  6586. saveSlotPreset: (printerId: number, amsId: number, trayId: number, presetId: string, presetName: string, presetSource = 'cloud', trayInfoIdx?: string) =>
  6587. request<SlotPresetMapping>(`/printers/${printerId}/slot-presets/${amsId}/${trayId}?preset_id=${encodeURIComponent(presetId)}&preset_name=${encodeURIComponent(presetName)}&preset_source=${encodeURIComponent(presetSource)}${trayInfoIdx ? `&tray_info_idx=${encodeURIComponent(trayInfoIdx)}` : ''}`, {
  6588. method: 'PUT',
  6589. }),
  6590. // AMS Labels (user-defined friendly names)
  6591. getAmsLabels: (printerId: number) => amsLabelsBatch(printerId),
  6592. saveAmsLabel: (printerId: number, amsId: number, label: string, amsSerial = '') =>
  6593. request<{ ams_id: number; label: string }>(
  6594. `/printers/${printerId}/ams-labels/${amsId}`,
  6595. {
  6596. method: 'PUT',
  6597. body: JSON.stringify({ label, ams_serial: amsSerial }),
  6598. }
  6599. ),
  6600. deleteAmsLabel: (printerId: number, amsId: number, amsSerial = '') =>
  6601. request<{ success: boolean }>(`/printers/${printerId}/ams-labels/${amsId}?ams_serial=${encodeURIComponent(amsSerial)}`, {
  6602. method: 'DELETE',
  6603. }),
  6604. configureAmsSlot: (
  6605. printerId: number,
  6606. amsId: number,
  6607. trayId: number,
  6608. config: {
  6609. tray_info_idx: string;
  6610. tray_type: string;
  6611. tray_sub_brands: string;
  6612. tray_color: string;
  6613. nozzle_temp_min: number;
  6614. nozzle_temp_max: number;
  6615. cali_idx: number;
  6616. nozzle_diameter: string;
  6617. setting_id?: string;
  6618. kprofile_filament_id?: string;
  6619. kprofile_setting_id?: string;
  6620. k_value?: number;
  6621. // Orca Cloud profile the slot is set to; the backend looks up its
  6622. // filament id when tray_info_idx is empty (#3216).
  6623. orca_profile_id?: string;
  6624. }
  6625. ) => {
  6626. const params = new URLSearchParams({
  6627. tray_info_idx: config.tray_info_idx,
  6628. tray_type: config.tray_type,
  6629. tray_sub_brands: config.tray_sub_brands,
  6630. tray_color: config.tray_color,
  6631. nozzle_temp_min: config.nozzle_temp_min.toString(),
  6632. nozzle_temp_max: config.nozzle_temp_max.toString(),
  6633. cali_idx: config.cali_idx.toString(),
  6634. nozzle_diameter: config.nozzle_diameter,
  6635. });
  6636. if (config.setting_id) {
  6637. params.set('setting_id', config.setting_id);
  6638. }
  6639. if (config.kprofile_filament_id) {
  6640. params.set('kprofile_filament_id', config.kprofile_filament_id);
  6641. }
  6642. if (config.kprofile_setting_id) {
  6643. params.set('kprofile_setting_id', config.kprofile_setting_id);
  6644. }
  6645. if (config.k_value !== undefined && config.k_value > 0) {
  6646. params.set('k_value', config.k_value.toString());
  6647. }
  6648. if (config.orca_profile_id) {
  6649. params.set('orca_profile_id', config.orca_profile_id);
  6650. }
  6651. return request<{
  6652. success: boolean;
  6653. message: string;
  6654. // The filament id the slot was actually given.
  6655. tray_info_idx?: string;
  6656. // Why an Orca profile went out as the generic for its material, or "".
  6657. orca_fallback_reason?: '' | 'no_filament_id' | 'lookup_failed' | 'no_permission';
  6658. /** A manual K value could not be sent; the filament setting was. */
  6659. k_value_unsent?: boolean;
  6660. }>(
  6661. `/printers/${printerId}/slots/${amsId}/${trayId}/configure?${params}`,
  6662. { method: 'POST' }
  6663. );
  6664. },
  6665. resetAmsSlot: (printerId: number, amsId: number, trayId: number) =>
  6666. request<{ success: boolean; message: string }>(
  6667. `/printers/${printerId}/ams/${amsId}/tray/${trayId}/reset`,
  6668. { method: 'POST' }
  6669. ),
  6670. // Notification Providers
  6671. getNotificationProviders: () => request<NotificationProvider[]>('/notifications/'),
  6672. createNotificationProvider: (data: NotificationProviderCreate) =>
  6673. request<NotificationProvider>('/notifications/', {
  6674. method: 'POST',
  6675. body: JSON.stringify(data),
  6676. }),
  6677. updateNotificationProvider: (id: number, data: NotificationProviderUpdate) =>
  6678. request<NotificationProvider>(`/notifications/${id}`, {
  6679. method: 'PATCH',
  6680. body: JSON.stringify(data),
  6681. }),
  6682. deleteNotificationProvider: (id: number) =>
  6683. request<{ message: string }>(`/notifications/${id}`, { method: 'DELETE' }),
  6684. testNotificationProvider: (id: number) =>
  6685. request<NotificationTestResponse>(`/notifications/${id}/test`, { method: 'POST' }),
  6686. testNotificationConfig: (data: NotificationTestRequest) =>
  6687. request<NotificationTestResponse>('/notifications/test-config', {
  6688. method: 'POST',
  6689. body: JSON.stringify(data),
  6690. }),
  6691. testAllNotificationProviders: () =>
  6692. request<{
  6693. tested: number;
  6694. success: number;
  6695. failed: number;
  6696. results: Array<{
  6697. provider_id: number;
  6698. provider_name: string;
  6699. provider_type: string;
  6700. success: boolean;
  6701. message: string;
  6702. }>;
  6703. }>('/notifications/test-all', { method: 'POST' }),
  6704. // Notification Templates
  6705. getNotificationTemplates: () => request<NotificationTemplate[]>('/notification-templates'),
  6706. updateNotificationTemplate: (id: number, data: NotificationTemplateUpdate) =>
  6707. request<NotificationTemplate>(`/notification-templates/${id}`, {
  6708. method: 'PUT',
  6709. body: JSON.stringify(data),
  6710. }),
  6711. resetNotificationTemplate: (id: number) =>
  6712. request<NotificationTemplate>(`/notification-templates/${id}/reset`, {
  6713. method: 'POST',
  6714. }),
  6715. getTemplateVariables: () => request<EventVariablesResponse[]>('/notification-templates/variables'),
  6716. previewTemplate: (data: TemplatePreviewRequest) =>
  6717. request<TemplatePreviewResponse>('/notification-templates/preview', {
  6718. method: 'POST',
  6719. body: JSON.stringify(data),
  6720. }),
  6721. // Notification Logs
  6722. getNotificationLogs: (params?: {
  6723. limit?: number;
  6724. offset?: number;
  6725. provider_id?: number;
  6726. event_type?: string;
  6727. success?: boolean;
  6728. days?: number;
  6729. }) => {
  6730. const searchParams = new URLSearchParams();
  6731. if (params?.limit) searchParams.set('limit', String(params.limit));
  6732. if (params?.offset) searchParams.set('offset', String(params.offset));
  6733. if (params?.provider_id) searchParams.set('provider_id', String(params.provider_id));
  6734. if (params?.event_type) searchParams.set('event_type', params.event_type);
  6735. if (params?.success !== undefined) searchParams.set('success', String(params.success));
  6736. if (params?.days) searchParams.set('days', String(params.days));
  6737. return request<NotificationLogEntry[]>(`/notifications/logs?${searchParams}`);
  6738. },
  6739. getNotificationLogStats: (days = 7) =>
  6740. request<NotificationLogStats>(`/notifications/logs/stats?days=${days}`),
  6741. clearNotificationLogs: (olderThanDays = 30) =>
  6742. request<{ deleted: number; message: string }>(
  6743. `/notifications/logs?older_than_days=${olderThanDays}`,
  6744. { method: 'DELETE' }
  6745. ),
  6746. // Spoolman Integration
  6747. getSpoolmanStatus: () => request<SpoolmanStatus>('/spoolman/status'),
  6748. migrateSpoolmanTags: (dryRun: boolean) =>
  6749. request<SpoolmanTagMigrationReport>(`/spoolman/inventory/tags/migrate?dry_run=${dryRun}`, {
  6750. method: 'POST',
  6751. }),
  6752. connectSpoolman: () =>
  6753. request<{ success: boolean; message: string }>('/spoolman/connect', {
  6754. method: 'POST',
  6755. }),
  6756. syncPrinterAms: (printerId: number) =>
  6757. request<SpoolmanSyncResult>(`/spoolman/sync/${printerId}`, {
  6758. method: 'POST',
  6759. }),
  6760. syncAllPrintersAms: () =>
  6761. request<SpoolmanSyncResult>('/spoolman/sync-all', {
  6762. method: 'POST',
  6763. }),
  6764. getSpoolmanInventoryFilaments: () =>
  6765. request<SpoolmanFilamentEntry[]>('/spoolman/inventory/filaments'),
  6766. getUnlinkedSpools: () =>
  6767. request<UnlinkedSpool[]>('/spoolman/spools/unlinked'),
  6768. getLinkedSpools: () =>
  6769. request<LinkedSpoolsMap>('/spoolman/spools/linked'),
  6770. linkSpool: (
  6771. spoolId: number,
  6772. context: {
  6773. spoolTag: string;
  6774. printerId: number;
  6775. amsId: number;
  6776. trayId: number;
  6777. }
  6778. ) =>
  6779. request<{ success: boolean; message: string }>(`/spoolman/spools/${spoolId}/link`, {
  6780. method: 'POST',
  6781. body: JSON.stringify({
  6782. spool_tag: context.spoolTag,
  6783. printer_id: context.printerId,
  6784. ams_id: context.amsId,
  6785. tray_id: context.trayId,
  6786. }),
  6787. }),
  6788. unlinkSpool: (spoolId: number) =>
  6789. request<{ success: boolean; message: string }>(`/spoolman/spools/${spoolId}/unlink`, {
  6790. method: 'POST',
  6791. }),
  6792. createSpoolmanSpoolFromSlot: (data: { printer_id: number; ams_id: number; tray_id: number }) =>
  6793. request<{ success: boolean; spool_id: number | null }>(`/spoolman/spools/from-slot`, {
  6794. method: 'POST',
  6795. body: JSON.stringify(data),
  6796. }),
  6797. createSpoolFromSlot: (data: { printer_id: number; ams_id: number; tray_id: number }) =>
  6798. request<InventorySpool>(`/inventory/spools/from-slot`, {
  6799. method: 'POST',
  6800. body: JSON.stringify(data),
  6801. }),
  6802. getSpoolmanSettings: () =>
  6803. 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'),
  6804. 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; }) =>
  6805. 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', {
  6806. method: 'PUT',
  6807. body: JSON.stringify(data),
  6808. }),
  6809. // Inventory
  6810. getSpools: (includeArchived = false) =>
  6811. request<InventorySpool[]>(`/inventory/spools?include_archived=${includeArchived}`),
  6812. getSpool: (id: number) => request<InventorySpool>(`/inventory/spools/${id}`),
  6813. createSpool: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>) =>
  6814. request<InventorySpool>('/inventory/spools', {
  6815. method: 'POST',
  6816. body: JSON.stringify(data),
  6817. }),
  6818. bulkCreateSpools: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>, quantity: number) =>
  6819. request<InventorySpool[]>('/inventory/spools/bulk', {
  6820. method: 'POST',
  6821. body: JSON.stringify({ spool: data, quantity }),
  6822. }),
  6823. // ── CSV import/export (#1576) ────────────────────────────────────────────
  6824. // dry_run=true → preview (no write); omitted → real import. Both share one
  6825. // multipart upload helper; see `uploadSpoolsCsv` below.
  6826. importSpoolsCsvPreview: (file: File): Promise<CsvImportPreview> => uploadSpoolsCsv<CsvImportPreview>(file, true),
  6827. importSpoolsCsv: (file: File): Promise<CsvImportResult> => uploadSpoolsCsv<CsvImportResult>(file, false),
  6828. exportSpoolsCsv: async (): Promise<void> => {
  6829. const headers: Record<string, string> = {};
  6830. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  6831. const response = await fetch(`${API_BASE}/inventory/spools/export`, { headers });
  6832. if (!response.ok) {
  6833. const error = await response.json().catch(() => ({}));
  6834. throw new Error(error.detail || `HTTP ${response.status}`);
  6835. }
  6836. const disposition = response.headers.get('Content-Disposition');
  6837. const filename = parseContentDispositionFilename(disposition) || 'bambuddy_inventory.csv';
  6838. const blob = await response.blob();
  6839. const url = window.URL.createObjectURL(blob);
  6840. const a = document.createElement('a');
  6841. a.href = url;
  6842. a.download = filename;
  6843. document.body.appendChild(a);
  6844. a.click();
  6845. document.body.removeChild(a);
  6846. window.URL.revokeObjectURL(url);
  6847. },
  6848. updateSpool: (id: number, data: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  6849. request<InventorySpool>(`/inventory/spools/${id}`, {
  6850. method: 'PATCH',
  6851. body: JSON.stringify(data),
  6852. }),
  6853. deleteSpool: (id: number) =>
  6854. request<{ status: string }>(`/inventory/spools/${id}`, { method: 'DELETE' }),
  6855. archiveSpool: (id: number) =>
  6856. request<InventorySpool>(`/inventory/spools/${id}/archive`, { method: 'POST' }),
  6857. restoreSpool: (id: number) =>
  6858. request<InventorySpool>(`/inventory/spools/${id}/restore`, { method: 'POST' }),
  6859. resetSpoolConsumedCounter: (id: number) =>
  6860. request<InventorySpool>(`/inventory/spools/${id}/reset-consumed-counter`, { method: 'POST' }),
  6861. bulkResetSpoolConsumedCounter: (spoolIds: number[]) =>
  6862. request<{ reset: number; not_found?: number[]; errors?: Array<{ id: number; status: number; detail: string }> }>(`/inventory/spools/reset-consumed-counter-bulk`, {
  6863. method: 'POST',
  6864. body: JSON.stringify({ spool_ids: spoolIds }),
  6865. }),
  6866. bulkUpdateSpools: (ids: number[], update: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  6867. request<{ updated: number; not_found: number[] }>(`/inventory/spools/bulk-update`, {
  6868. method: 'POST',
  6869. body: JSON.stringify({ ids, update }),
  6870. }),
  6871. bulkDeleteSpools: (ids: number[]) =>
  6872. request<{ deleted: number; not_found: number[] }>(`/inventory/spools/bulk-delete`, {
  6873. method: 'POST',
  6874. body: JSON.stringify({ ids }),
  6875. }),
  6876. bulkArchiveSpools: (ids: number[]) =>
  6877. request<{ archived: number; already_archived: number[]; not_found: number[] }>(`/inventory/spools/bulk-archive`, {
  6878. method: 'POST',
  6879. body: JSON.stringify({ ids }),
  6880. }),
  6881. bulkRestoreSpools: (ids: number[]) =>
  6882. request<{ restored: number; already_active: number[]; not_found: number[] }>(`/inventory/spools/bulk-restore`, {
  6883. method: 'POST',
  6884. body: JSON.stringify({ ids }),
  6885. }),
  6886. getSpoolKProfiles: (spoolId: number) =>
  6887. request<SpoolKProfile[]>(`/inventory/spools/${spoolId}/k-profiles`),
  6888. saveSpoolKProfiles: (spoolId: number, profiles: SpoolKProfileInput[]) =>
  6889. request<SpoolKProfile[]>(`/inventory/spools/${spoolId}/k-profiles`, {
  6890. method: 'PUT',
  6891. body: JSON.stringify(profiles),
  6892. }),
  6893. /**
  6894. * What the spool assigned to this slot is configured to use *here* -- its
  6895. * per-printer-model filament preset and the K profile for this slot's hotend.
  6896. * Nulls when the slot holds no known spool.
  6897. */
  6898. getSlotSpoolDefaults: (printerId: number, amsId: number, trayId: number) =>
  6899. request<SlotSpoolDefaults>(`/printers/${printerId}/slots/${amsId}/${trayId}/spool-defaults`),
  6900. getSpoolFilamentPresets: (spoolId: number) =>
  6901. request<SpoolFilamentPreset[]>(`/inventory/spools/${spoolId}/filament-presets`),
  6902. saveSpoolFilamentPresets: (spoolId: number, presets: SpoolFilamentPresetInput[]) =>
  6903. request<SpoolFilamentPreset[]>(`/inventory/spools/${spoolId}/filament-presets`, {
  6904. method: 'PUT',
  6905. body: JSON.stringify(presets),
  6906. }),
  6907. getProfileDefaults: () => request<ProfileDefault[]>('/inventory/profile-defaults'),
  6908. resolveProfileDefault: (key: ProfileDefaultKey) => {
  6909. const params = new URLSearchParams({
  6910. brand: key.brand,
  6911. material: key.material,
  6912. subtype: key.subtype,
  6913. color_name: key.color_name,
  6914. });
  6915. return request<ResolvedProfileDefault | null>(`/inventory/profile-defaults/resolve?${params}`);
  6916. },
  6917. saveProfileDefault: (data: ProfileDefaultInput) =>
  6918. request<ProfileDefault>('/inventory/profile-defaults', {
  6919. method: 'PUT',
  6920. body: JSON.stringify(data),
  6921. }),
  6922. deleteProfileDefault: (defaultId: number) =>
  6923. request<{ status: string }>(`/inventory/profile-defaults/${defaultId}`, { method: 'DELETE' }),
  6924. /** Fills in what active spools of the default's product lack; the inventory mode picks the route. */
  6925. applyProfileDefault: (defaultId: number, spoolmanMode: boolean) =>
  6926. request<{ updated: number }>(
  6927. spoolmanMode
  6928. ? `/spoolman/inventory/profile-defaults/${defaultId}/apply`
  6929. : `/inventory/profile-defaults/${defaultId}/apply`,
  6930. { method: 'POST' },
  6931. ),
  6932. getAssignments: (printerId?: number) =>
  6933. request<SpoolAssignment[]>(`/inventory/assignments${printerId ? `?printer_id=${printerId}` : ''}`),
  6934. // move: the spool also leaves any other slot it is in, in the same
  6935. // transaction (#1574) -- for a scanned spool, the one in the user's hand.
  6936. assignSpool: (data: { spool_id: number; printer_id: number; ams_id: number; tray_id: number; move?: boolean }) =>
  6937. request<SpoolAssignment>('/inventory/assignments', {
  6938. method: 'POST',
  6939. body: JSON.stringify(data),
  6940. }),
  6941. unassignSpool: (printerId: number, amsId: number, trayId: number) =>
  6942. request<{ status: string }>(`/inventory/assignments/${printerId}/${amsId}/${trayId}`, { method: 'DELETE' }),
  6943. // ── Spool label printing (#809) ──────────────────────────────────────────
  6944. // The print endpoints return a PDF, a PNG, or a ZIP of PNGs (#2981); the
  6945. // preview endpoints one PNG. Callers get the Blob and decide what to do.
  6946. printSpoolLabels: (data: PrintSpoolLabelsRequest): Promise<Blob> =>
  6947. postForBlob('/inventory/labels', data),
  6948. printSpoolmanSpoolLabels: (data: PrintSpoolLabelsRequest): Promise<Blob> =>
  6949. postForBlob('/spoolman/labels', data),
  6950. previewSpoolLabel: (data: PreviewSpoolLabelRequest, signal?: AbortSignal): Promise<Blob> =>
  6951. postForBlob('/inventory/labels/preview', data, signal),
  6952. previewSpoolmanSpoolLabel: (data: PreviewSpoolLabelRequest, signal?: AbortSignal): Promise<Blob> =>
  6953. postForBlob('/spoolman/labels/preview', data, signal),
  6954. getLabelTemplates: () => request<SavedLabelTemplate[]>('/label-templates'),
  6955. createLabelTemplate: (data: { name: string; layout: LabelSheetLayout }) =>
  6956. request<SavedLabelTemplate>('/label-templates', { method: 'POST', body: JSON.stringify(data) }),
  6957. updateLabelTemplate: (id: number, data: { name: string; layout: LabelSheetLayout }) =>
  6958. request<SavedLabelTemplate>(`/label-templates/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  6959. deleteLabelTemplate: (id: number) => request<void>(`/label-templates/${id}`, { method: 'DELETE' }),
  6960. getSpoolCatalog: () =>
  6961. request<SpoolCatalogEntry[]>('/inventory/catalog'),
  6962. addCatalogEntry: (data: { name: string; weight: number }) =>
  6963. request<SpoolCatalogEntry>('/inventory/catalog', { method: 'POST', body: JSON.stringify(data) }),
  6964. updateCatalogEntry: (id: number, data: { name: string; weight: number }) =>
  6965. request<SpoolCatalogEntry>(`/inventory/catalog/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  6966. deleteCatalogEntry: (id: number) =>
  6967. request<{ status: string }>(`/inventory/catalog/${id}`, { method: 'DELETE' }),
  6968. bulkDeleteCatalogEntries: (ids: number[]) =>
  6969. request<{ deleted: number }>('/inventory/catalog/bulk-delete', { method: 'POST', body: JSON.stringify({ ids }) }),
  6970. resetSpoolCatalog: () =>
  6971. request<{ status: string }>('/inventory/catalog/reset', { method: 'POST' }),
  6972. // ── Suppliers (#2988) — inventory master data, Locations pattern ─────────
  6973. getSuppliers: () =>
  6974. request<Supplier[]>('/inventory/suppliers'),
  6975. createSupplier: (data: SupplierInput) =>
  6976. request<Supplier>('/inventory/suppliers', { method: 'POST', body: JSON.stringify(data) }),
  6977. updateSupplier: (id: number, data: Partial<SupplierInput>) =>
  6978. request<Supplier>(`/inventory/suppliers/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  6979. deleteSupplier: (id: number) =>
  6980. request<{ status: string }>(`/inventory/suppliers/${id}`, { method: 'DELETE' }),
  6981. setSpoolSuppliers: (spoolId: number, links: SpoolSupplierLinkInput[]) =>
  6982. request<SpoolSupplierLink[]>(`/inventory/spools/${spoolId}/suppliers`, {
  6983. method: 'PUT',
  6984. body: JSON.stringify(links),
  6985. }),
  6986. // Spoolman parity: the assignment rows live Bambuddy-side, keyed by the
  6987. // remote spool id — same request/response shape as the built-in inventory.
  6988. setSpoolmanSpoolSuppliers: (spoolmanSpoolId: number, links: SpoolSupplierLinkInput[]) =>
  6989. request<SpoolSupplierLink[]>(`/spoolman/inventory/spools/${spoolmanSpoolId}/suppliers`, {
  6990. method: 'PUT',
  6991. body: JSON.stringify(links),
  6992. }),
  6993. // date_from/date_to scope the usage half only, so the widget can follow the
  6994. // dashboard timeframe; stock stays point-in-time.
  6995. getSupplierStats: (dateFrom?: string, dateTo?: string) => {
  6996. const params = new URLSearchParams();
  6997. if (dateFrom) params.set('date_from', dateFrom);
  6998. if (dateTo) params.set('date_to', dateTo);
  6999. addDayZone(params);
  7000. const qs = params.toString();
  7001. return request<SupplierStats[]>(`/inventory/stats/suppliers${qs ? `?${qs}` : ''}`);
  7002. },
  7003. getLocations: () =>
  7004. request<StorageLocation[]>('/inventory/locations'),
  7005. createLocation: (data: { name: string; identifier?: string | null }) =>
  7006. request<StorageLocation>('/inventory/locations', { method: 'POST', body: JSON.stringify(data) }),
  7007. updateLocation: (id: number, data: { name?: string; identifier?: string | null }) =>
  7008. request<StorageLocation>(`/inventory/locations/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  7009. deleteLocation: (id: number) =>
  7010. request<{ status: string }>(`/inventory/locations/${id}`, { method: 'DELETE' }),
  7011. getColorCatalog: () =>
  7012. request<ColorCatalogEntry[]>('/inventory/colors'),
  7013. /** Flat hex→name map, plus the names collapsing it loses. ``by_material`` is
  7014. * keyed ``"<material>|<hex>"`` and only carries entries that differ from the
  7015. * flat answer (e.g. ``"pla matte|ffffff" -> "Ivory White"`` where the flat
  7016. * map says "Jade White"). #2875. */
  7017. getColorNameMap: () =>
  7018. request<{
  7019. colors: Record<string, string>;
  7020. by_material?: Record<string, string>;
  7021. bambu?: BambuCatalogColor[];
  7022. preset_materials?: Record<string, string>;
  7023. }>('/inventory/colors/map'),
  7024. addColorEntry: (data: {
  7025. manufacturer: string;
  7026. color_name: string;
  7027. hex_color: string;
  7028. material: string | null;
  7029. extra_colors?: string | null;
  7030. effect_type?: string | null;
  7031. }) =>
  7032. request<ColorCatalogEntry>('/inventory/colors', { method: 'POST', body: JSON.stringify(data) }),
  7033. updateColorEntry: (
  7034. id: number,
  7035. data: {
  7036. manufacturer: string;
  7037. color_name: string;
  7038. hex_color: string;
  7039. material: string | null;
  7040. extra_colors?: string | null;
  7041. effect_type?: string | null;
  7042. },
  7043. ) => request<ColorCatalogEntry>(`/inventory/colors/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  7044. deleteColorEntry: (id: number) =>
  7045. request<{ status: string }>(`/inventory/colors/${id}`, { method: 'DELETE' }),
  7046. bulkDeleteColorEntries: (ids: number[]) =>
  7047. request<{ deleted: number }>('/inventory/colors/bulk-delete', { method: 'POST', body: JSON.stringify({ ids }) }),
  7048. resetColorCatalog: () =>
  7049. request<{ status: string }>('/inventory/colors/reset', { method: 'POST' }),
  7050. searchColors: (manufacturer?: string, material?: string) =>
  7051. request<ColorCatalogEntry[]>(`/inventory/colors/search?${manufacturer ? `manufacturer=${encodeURIComponent(manufacturer)}` : ''}${manufacturer && material ? '&' : ''}${material ? `material=${encodeURIComponent(material)}` : ''}`),
  7052. linkTagToSpool: (spoolId: number, data: { tag_uid?: string; tray_uuid?: string; tag_type?: string; data_origin?: string }) =>
  7053. request<InventorySpool>(`/inventory/spools/${spoolId}/link-tag`, {
  7054. method: 'PATCH',
  7055. body: JSON.stringify(data),
  7056. }),
  7057. // Per-material-number inventory aggregate (#2870). The date range narrows
  7058. // the usage half only — stock is point-in-time.
  7059. getMaterialNumberStats: (options?: { dateFrom?: string; dateTo?: string }) => {
  7060. const params = new URLSearchParams();
  7061. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  7062. if (options?.dateTo) params.set('date_to', options.dateTo);
  7063. addDayZone(params);
  7064. const qs = params.toString();
  7065. return request<MaterialNumberStats[]>(`/inventory/stats/material-numbers${qs ? `?${qs}` : ''}`);
  7066. },
  7067. getSpoolUsageHistory: (spoolId: number, limit = 50) =>
  7068. request<SpoolUsageRecord[]>(`/inventory/spools/${spoolId}/usage?limit=${limit}`),
  7069. // One inventory's at a time: ``spoolman`` for the Spoolman spools' (#3407).
  7070. getAllUsageHistory: (limit = 100, printerId?: number, spoolman = false) =>
  7071. request<SpoolUsageRecord[]>(
  7072. `/inventory/usage?limit=${limit}${printerId ? `&printer_id=${printerId}` : ''}${spoolman ? '&spoolman=true' : ''}`,
  7073. ),
  7074. getSpoolmanSpoolUsageHistory: (spoolId: number, limit = 50) =>
  7075. request<SpoolUsageRecord[]>(`/spoolman/inventory/spools/${spoolId}/usage?limit=${limit}`),
  7076. clearSpoolmanSpoolUsageHistory: (spoolId: number) =>
  7077. request<{ status: string }>(`/spoolman/inventory/spools/${spoolId}/usage`, { method: 'DELETE' }),
  7078. clearSpoolUsageHistory: (spoolId: number) =>
  7079. request<{ status: string }>(`/inventory/spools/${spoolId}/usage`, { method: 'DELETE' }),
  7080. syncWeightsFromAms: () =>
  7081. request<{ synced: number; skipped: number; printing?: number }>('/inventory/sync-ams-weights', { method: 'POST' }),
  7082. getSkuSettings: () =>
  7083. request<FilamentSkuSettings[]>('/inventory/sku-settings'),
  7084. upsertSkuSettings: (data: Omit<FilamentSkuSettings, 'id'>) =>
  7085. request<FilamentSkuSettings>('/inventory/sku-settings', {
  7086. method: 'POST',
  7087. body: JSON.stringify(data),
  7088. }),
  7089. getShoppingList: () =>
  7090. request<ShoppingListItem[]>('/inventory/shopping-list'),
  7091. addToShoppingList: (data: ShoppingListItemCreate) =>
  7092. request<ShoppingListItem>('/inventory/shopping-list', {
  7093. method: 'POST',
  7094. body: JSON.stringify(data),
  7095. }),
  7096. removeFromShoppingList: (id: number) =>
  7097. request<{ status: string }>(`/inventory/shopping-list/${id}`, { method: 'DELETE' }),
  7098. clearShoppingList: () =>
  7099. request<{ deleted: number }>('/inventory/shopping-list', { method: 'DELETE' }),
  7100. updateShoppingListStatus: (id: number, status: 'pending' | 'purchased' | 'received') =>
  7101. request<ShoppingListItem>(`/inventory/shopping-list/${id}/status`, {
  7102. method: 'PATCH',
  7103. body: JSON.stringify({ status }),
  7104. }),
  7105. getFilamentPresets: () =>
  7106. request<SlicerSetting[]>('/cloud/filaments'),
  7107. // Spoolman Inventory proxy (unified UI when Spoolman is enabled)
  7108. getSpoolmanInventorySpools: (includeArchived = false) =>
  7109. request<InventorySpool[]>(`/spoolman/inventory/spools?include_archived=${includeArchived}`),
  7110. getSpoolmanInventorySpool: (id: number) =>
  7111. request<InventorySpool>(`/spoolman/inventory/spools/${id}`),
  7112. createSpoolmanInventorySpool: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>) =>
  7113. request<InventorySpool>('/spoolman/inventory/spools', {
  7114. method: 'POST',
  7115. body: JSON.stringify(data),
  7116. }),
  7117. bulkCreateSpoolmanInventorySpools: (
  7118. data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>,
  7119. quantity: number,
  7120. ) =>
  7121. request<SpoolmanBulkCreateResult | InventorySpool[]>('/spoolman/inventory/spools/bulk', {
  7122. method: 'POST',
  7123. body: JSON.stringify({ spool: data, quantity }),
  7124. }),
  7125. updateSpoolmanInventorySpool: (
  7126. id: number,
  7127. data: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>,
  7128. ) =>
  7129. request<InventorySpool>(`/spoolman/inventory/spools/${id}`, {
  7130. method: 'PATCH',
  7131. body: JSON.stringify(data),
  7132. }),
  7133. deleteSpoolmanInventorySpool: (id: number) =>
  7134. request<{ status: string }>(`/spoolman/inventory/spools/${id}`, { method: 'DELETE' }),
  7135. archiveSpoolmanInventorySpool: (id: number) =>
  7136. request<InventorySpool>(`/spoolman/inventory/spools/${id}/archive`, { method: 'POST' }),
  7137. restoreSpoolmanInventorySpool: (id: number) =>
  7138. request<InventorySpool>(`/spoolman/inventory/spools/${id}/restore`, { method: 'POST' }),
  7139. resetSpoolmanInventorySpoolConsumedCounter: (id: number) =>
  7140. request<InventorySpool>(`/spoolman/inventory/spools/${id}/reset-consumed-counter`, { method: 'POST' }),
  7141. bulkResetSpoolmanInventorySpoolConsumedCounter: (spoolIds: number[]) =>
  7142. request<{ reset: number; not_found?: number[]; errors?: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/reset-consumed-counter-bulk`, {
  7143. method: 'POST',
  7144. body: JSON.stringify({ spool_ids: spoolIds }),
  7145. }),
  7146. bulkUpdateSpoolmanInventorySpools: (ids: number[], update: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  7147. request<{ updated: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-update`, {
  7148. method: 'POST',
  7149. body: JSON.stringify({ ids, update }),
  7150. }),
  7151. bulkDeleteSpoolmanInventorySpools: (ids: number[]) =>
  7152. request<{ deleted: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-delete`, {
  7153. method: 'POST',
  7154. body: JSON.stringify({ ids }),
  7155. }),
  7156. bulkArchiveSpoolmanInventorySpools: (ids: number[]) =>
  7157. request<{ archived: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-archive`, {
  7158. method: 'POST',
  7159. body: JSON.stringify({ ids }),
  7160. }),
  7161. bulkRestoreSpoolmanInventorySpools: (ids: number[]) =>
  7162. request<{ restored: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-restore`, {
  7163. method: 'POST',
  7164. body: JSON.stringify({ ids }),
  7165. }),
  7166. linkTagToSpoolmanSpool: (spoolId: number, data: { tag_uid?: string; tray_uuid?: string }) =>
  7167. request<InventorySpool>(`/spoolman/inventory/spools/${spoolId}/tag`, {
  7168. method: 'PATCH',
  7169. body: JSON.stringify(data),
  7170. }),
  7171. syncSpoolmanSpoolWeight: (spoolId: number, weightGrams: number) =>
  7172. request<{ status: string; weight_used: number }>(`/spoolman/inventory/spools/${spoolId}/weight`, {
  7173. method: 'PATCH',
  7174. body: JSON.stringify({ weight_grams: weightGrams }),
  7175. }),
  7176. // move: as assignSpool's (#1574).
  7177. assignSpoolmanSlot: (data: { spoolman_spool_id: number; printer_id: number; ams_id: number; tray_id: number; move?: boolean }) =>
  7178. request<InventorySpool>('/spoolman/inventory/slot-assignments', {
  7179. method: 'POST',
  7180. body: JSON.stringify(data),
  7181. }),
  7182. unassignSpoolmanSlot: (spoolmanSpoolId: number) =>
  7183. request<InventorySpool>(`/spoolman/inventory/slot-assignments/${spoolmanSpoolId}`, { method: 'DELETE' }),
  7184. getSpoolmanSlotAssignments: (printerId?: number) =>
  7185. request<Array<{
  7186. printer_id: number;
  7187. printer_name: string | null;
  7188. ams_id: number;
  7189. tray_id: number;
  7190. spoolman_spool_id: number;
  7191. ams_label: string | null;
  7192. printer_model?: string | null;
  7193. }>>(
  7194. printerId !== undefined
  7195. ? `/spoolman/inventory/slot-assignments/all?printer_id=${printerId}`
  7196. : '/spoolman/inventory/slot-assignments/all',
  7197. ),
  7198. syncSpoolmanAmsWeights: () =>
  7199. request<{ synced: number; skipped: number; printing?: number }>('/spoolman/inventory/sync-ams-weights', { method: 'POST' }),
  7200. saveSpoolmanKProfiles: (spoolId: number, profiles: SpoolKProfileInput[]) =>
  7201. request<SpoolKProfile[]>(`/spoolman/inventory/spools/${spoolId}/k-profiles`, {
  7202. method: 'PUT',
  7203. body: JSON.stringify(profiles),
  7204. }),
  7205. getSpoolmanFilamentPresets: (spoolId: number) =>
  7206. request<SpoolFilamentPreset[]>(`/spoolman/inventory/spools/${spoolId}/filament-presets`),
  7207. saveSpoolmanFilamentPresets: (spoolId: number, presets: SpoolFilamentPresetInput[]) =>
  7208. request<SpoolFilamentPreset[]>(`/spoolman/inventory/spools/${spoolId}/filament-presets`, {
  7209. method: 'PUT',
  7210. body: JSON.stringify(presets),
  7211. }),
  7212. // Updates
  7213. getVersion: () => request<VersionInfo>('/updates/version'),
  7214. checkForUpdates: () => request<UpdateCheckResult>('/updates/check'),
  7215. applyUpdate: () =>
  7216. request<{ success: boolean; message: string; status?: UpdateStatus; is_docker?: boolean; is_ha_addon?: boolean; is_windows_installer?: boolean }>('/updates/apply', {
  7217. method: 'POST',
  7218. }),
  7219. getUpdateStatus: () => request<UpdateStatus>('/updates/status'),
  7220. // Maintenance
  7221. getMaintenanceTypes: () => request<MaintenanceType[]>('/maintenance/types'),
  7222. createMaintenanceType: (data: MaintenanceTypeCreate) =>
  7223. request<MaintenanceType>('/maintenance/types', {
  7224. method: 'POST',
  7225. body: JSON.stringify(data),
  7226. }),
  7227. updateMaintenanceType: (id: number, data: Partial<MaintenanceTypeCreate>) =>
  7228. request<MaintenanceType>(`/maintenance/types/${id}`, {
  7229. method: 'PATCH',
  7230. body: JSON.stringify(data),
  7231. }),
  7232. deleteMaintenanceType: (id: number) =>
  7233. request<{ status: string }>(`/maintenance/types/${id}`, { method: 'DELETE' }),
  7234. restoreDefaultMaintenanceTypes: () =>
  7235. request<{ restored: number }>(`/maintenance/types/restore-defaults`, { method: 'POST' }),
  7236. getMaintenanceOverview: () => request<PrinterMaintenanceOverview[]>('/maintenance/overview'),
  7237. updateMaintenanceItem: (itemId: number, data: { custom_interval_hours?: number | null; custom_interval_type?: 'hours' | 'days' | null; enabled?: boolean }) =>
  7238. request<MaintenanceStatus>(`/maintenance/items/${itemId}`, {
  7239. method: 'PATCH',
  7240. body: JSON.stringify(data),
  7241. }),
  7242. performMaintenance: (itemId: number, notes?: string) =>
  7243. request<MaintenanceStatus>(`/maintenance/items/${itemId}/perform`, {
  7244. method: 'POST',
  7245. body: JSON.stringify({ notes }),
  7246. }),
  7247. setPrinterHours: (printerId: number, totalHours: number) =>
  7248. request<{ printer_id: number; total_hours: number; archive_hours: number; offset_hours: number }>(
  7249. `/maintenance/printers/${printerId}/hours?total_hours=${totalHours}`,
  7250. { method: 'PATCH' }
  7251. ),
  7252. assignMaintenanceType: (printerId: number, typeId: number) =>
  7253. request<MaintenanceStatus>(`/maintenance/printers/${printerId}/assign/${typeId}`, {
  7254. method: 'POST',
  7255. }),
  7256. removeMaintenanceItem: (itemId: number) =>
  7257. request<{ status: string }>(`/maintenance/items/${itemId}`, {
  7258. method: 'DELETE',
  7259. }),
  7260. // Camera
  7261. getCameraStreamToken: () =>
  7262. request<{ token: string }>('/printers/camera/stream-token', { method: 'POST' }),
  7263. // Media token (#3025) — the credential for thumbnails, plate previews,
  7264. // timelapses, cover images and link icons. Minted behind plain auth rather
  7265. // than camera:view, and identified, so those routes gate on the resource's
  7266. // own permission and ownership instead of on the camera.
  7267. getMediaToken: () => request<{ token: string }>('/auth/media-token', { method: 'POST' }),
  7268. // WebSocket auth (GHSA-r2qv follow-up) — mint a short-lived token for
  7269. // the /ws connection. Browsers can't attach Authorization headers to a
  7270. // WebSocket handshake, so the token rides in the ?token= query param.
  7271. getWebSocketToken: () =>
  7272. request<{ token: string }>('/auth/ws-token', { method: 'POST' }),
  7273. // Connected apps: sign-in to external applications with Bambuddy
  7274. listConnectedApps: () => request<ConnectedApp[]>('/connect/apps'),
  7275. createConnectedApp: (payload: { name: string; redirect_uri: string }) =>
  7276. request<ConnectedApp>('/connect/apps', { method: 'POST', body: JSON.stringify(payload) }),
  7277. updateConnectedApp: (id: number, payload: { name?: string; redirect_uri?: string; enabled?: boolean }) =>
  7278. request<ConnectedApp>(`/connect/apps/${id}`, { method: 'PATCH', body: JSON.stringify(payload) }),
  7279. rotateConnectedAppSecret: (id: number) =>
  7280. request<ConnectedApp>(`/connect/apps/${id}/rotate-secret`, { method: 'POST' }),
  7281. deleteConnectedApp: (id: number) => request<void>(`/connect/apps/${id}`, { method: 'DELETE' }),
  7282. getConnectAuthorizeInfo: (clientId: string, redirectUri: string) =>
  7283. request<ConnectAuthorizeInfo>(
  7284. `/connect/authorize/info?client_id=${encodeURIComponent(clientId)}&redirect_uri=${encodeURIComponent(redirectUri)}`,
  7285. ),
  7286. connectAuthorize: (payload: {
  7287. client_id: string;
  7288. redirect_uri: string;
  7289. code_challenge: string;
  7290. code_challenge_method: 'S256';
  7291. }) =>
  7292. request<{ code: string; redirect_uri: string }>('/connect/authorize', {
  7293. method: 'POST',
  7294. body: JSON.stringify(payload),
  7295. }),
  7296. // Long-lived camera tokens (#1108, #2531)
  7297. createLongLivedCameraToken: (payload: {
  7298. name: string;
  7299. expires_in_days: number;
  7300. scope?: LongLivedTokenScope;
  7301. }) =>
  7302. request<LongLivedCameraToken>('/auth/tokens', {
  7303. method: 'POST',
  7304. body: JSON.stringify({ scope: 'camera_stream', ...payload }),
  7305. }),
  7306. listMyLongLivedCameraTokens: () =>
  7307. request<LongLivedCameraToken[]>('/auth/tokens'),
  7308. listAllLongLivedCameraTokens: () =>
  7309. request<LongLivedCameraToken[]>('/auth/tokens/all'),
  7310. revokeLongLivedCameraToken: (tokenId: number) =>
  7311. request<void>(`/auth/tokens/${tokenId}`, { method: 'DELETE' }),
  7312. // Token-authenticated Cam Wall feed (#2531). `token` is omitted only when
  7313. // auth is disabled, where the backend gate is a no-op anyway.
  7314. getCamWallPrinters: (token?: string) =>
  7315. request<CamWallPrinter[]>(
  7316. token ? `/camwall/printers?token=${encodeURIComponent(token)}` : '/camwall/printers',
  7317. ),
  7318. // Token-authenticated streaming-overlay feed (#2613). OBS (or any embed with
  7319. // no login session) loads /overlay/{id}?token=... and this backs it. `token`
  7320. // is omitted only when auth is disabled, where the backend gate is a no-op.
  7321. getOverlayStatus: (printerId: number, token?: string) =>
  7322. request<OverlayStatus>(
  7323. token
  7324. ? `/printers/${printerId}/overlay-status?token=${encodeURIComponent(token)}`
  7325. : `/printers/${printerId}/overlay-status`,
  7326. ),
  7327. getCameraStatus: (printerId: number) =>
  7328. request<{ active: boolean; stalled: boolean }>(`/printers/${printerId}/camera/status`),
  7329. diagnoseCamera: (printerId: number) =>
  7330. request<CameraDiagnoseResult>(`/printers/${printerId}/camera/diagnose`, { method: 'POST' }),
  7331. diagnosePrinter: (printerId: number) =>
  7332. request<PrinterDiagnosticResult>(`/printers/${printerId}/diagnostic`),
  7333. diagnoseConnection: (body: {
  7334. ip_address: string;
  7335. serial_number?: string;
  7336. access_code?: string;
  7337. }) =>
  7338. request<PrinterDiagnosticResult>('/printers/diagnostic', {
  7339. method: 'POST',
  7340. body: JSON.stringify(body),
  7341. }),
  7342. // Plate Detection - Multi-reference calibration (stores up to 5 references per printer)
  7343. checkPlateEmpty: (printerId: number, options?: { useExternal?: boolean; includeDebugImage?: boolean }) => {
  7344. const params = new URLSearchParams();
  7345. // Only forward use_external when the caller explicitly sets it. Omitted →
  7346. // backend derives the default from the printer's external_camera_enabled
  7347. // setting so calibration and runtime checks use the same camera (#1359).
  7348. if (options?.useExternal !== undefined) {
  7349. params.set('use_external', String(options.useExternal));
  7350. }
  7351. params.set('include_debug_image', String(options?.includeDebugImage ?? false));
  7352. return request<PlateDetectionResult>(
  7353. `/printers/${printerId}/camera/check-plate?${params.toString()}`
  7354. );
  7355. },
  7356. calibratePlateDetection: (printerId: number, options?: { label?: string; useExternal?: boolean }) => {
  7357. const params = new URLSearchParams();
  7358. if (options?.label) params.set('label', options.label);
  7359. if (options?.useExternal !== undefined) {
  7360. params.set('use_external', String(options.useExternal));
  7361. }
  7362. return request<CalibrationResult & { index: number }>(
  7363. `/printers/${printerId}/camera/plate-detection/calibrate?${params.toString()}`,
  7364. { method: 'POST' }
  7365. );
  7366. },
  7367. getPlateReferences: (printerId: number) => {
  7368. return request<{
  7369. references: PlateReference[];
  7370. max_references: number;
  7371. }>(`/printers/${printerId}/camera/plate-detection/references`);
  7372. },
  7373. getPlateReferenceThumbnailUrl: (printerId: number, index: number) =>
  7374. withStreamToken(`${API_BASE}/printers/${printerId}/camera/plate-detection/references/${index}/thumbnail`),
  7375. updatePlateReferenceLabel: (printerId: number, index: number, label: string) => {
  7376. const params = new URLSearchParams();
  7377. params.set('label', label);
  7378. return request<{ success: boolean; index: number; label: string }>(
  7379. `/printers/${printerId}/camera/plate-detection/references/${index}?${params.toString()}`,
  7380. { method: 'PUT' }
  7381. );
  7382. },
  7383. deletePlateReference: (printerId: number, index: number) => {
  7384. return request<{ success: boolean; message: string }>(
  7385. `/printers/${printerId}/camera/plate-detection/references/${index}`,
  7386. { method: 'DELETE' }
  7387. );
  7388. },
  7389. // External Links
  7390. getExternalLinks: () => request<ExternalLink[]>('/external-links/'),
  7391. getExternalLink: (id: number) => request<ExternalLink>(`/external-links/${id}`),
  7392. createExternalLink: (data: ExternalLinkCreate) =>
  7393. request<ExternalLink>('/external-links/', {
  7394. method: 'POST',
  7395. body: JSON.stringify(data),
  7396. }),
  7397. updateExternalLink: (id: number, data: ExternalLinkUpdate) =>
  7398. request<ExternalLink>(`/external-links/${id}`, {
  7399. method: 'PATCH',
  7400. body: JSON.stringify(data),
  7401. }),
  7402. deleteExternalLink: (id: number) =>
  7403. request<{ message: string }>(`/external-links/${id}`, { method: 'DELETE' }),
  7404. uploadExternalLinkIcon: async (id: number, file: File): Promise<ExternalLink> => {
  7405. const formData = new FormData();
  7406. formData.append('file', file);
  7407. const headers: Record<string, string> = {};
  7408. if (authToken) {
  7409. headers['Authorization'] = `Bearer ${authToken}`;
  7410. }
  7411. const response = await fetch(`${API_BASE}/external-links/${id}/icon`, {
  7412. method: 'POST',
  7413. headers,
  7414. body: formData,
  7415. });
  7416. if (!response.ok) {
  7417. const error = await response.json().catch(() => ({}));
  7418. throw new Error(error.detail || `HTTP ${response.status}`);
  7419. }
  7420. return response.json();
  7421. },
  7422. deleteExternalLinkIcon: (id: number) =>
  7423. request<ExternalLink>(`/external-links/${id}/icon`, { method: 'DELETE' }),
  7424. getExternalLinkIconUrl: (id: number) => withMediaToken(`${API_BASE}/external-links/${id}/icon`),
  7425. // Projects
  7426. getProjects: (status?: string) => {
  7427. const params = new URLSearchParams();
  7428. if (status) params.set('status', status);
  7429. return request<ProjectListItem[]>(`/projects/?${params}`);
  7430. },
  7431. getProject: (id: number) => request<Project>(`/projects/${id}`),
  7432. createProject: (data: ProjectCreate) =>
  7433. request<Project>('/projects/', {
  7434. method: 'POST',
  7435. body: JSON.stringify(data),
  7436. }),
  7437. updateProject: (id: number, data: ProjectUpdate) =>
  7438. request<Project>(`/projects/${id}`, {
  7439. method: 'PATCH',
  7440. body: JSON.stringify(data),
  7441. }),
  7442. deleteProject: (id: number) =>
  7443. request<{ message: string }>(`/projects/${id}`, { method: 'DELETE' }),
  7444. getProjectArchives: (id: number, limit = 100, offset = 0) =>
  7445. request<Archive[]>(`/projects/${id}/archives?limit=${limit}&offset=${offset}`),
  7446. // Completed-run counts per library file (#1897); files with 0 runs are omitted
  7447. getProjectFileProgress: (id: number) =>
  7448. request<ProjectFileProgress[]>(`/projects/${id}/file-progress`),
  7449. addArchivesToProject: (projectId: number, archiveIds: number[]) =>
  7450. request<{ message: string; count: number }>(`/projects/${projectId}/add-archives`, {
  7451. method: 'POST',
  7452. body: JSON.stringify({ archive_ids: archiveIds }),
  7453. }),
  7454. // #1155: Cover image
  7455. // Browsers can't attach `Authorization: Bearer ...` to `<img src>`, so we
  7456. // append the stream-token query string the same way archive thumbnails do.
  7457. // `version` cache-busts the browser copy after a re-upload. It has to go on
  7458. // before the token does: callers used to append their own `?v=` to the
  7459. // returned URL, which already ended in `?token=…`, so the second `?` landed
  7460. // inside the token value and the image 401'd whenever auth was enabled.
  7461. getProjectCoverImageUrl: (projectId: number, version?: string | number) =>
  7462. withMediaToken(
  7463. `${API_BASE}/projects/${projectId}/cover-image${
  7464. version === undefined ? '' : `?v=${encodeURIComponent(String(version))}`
  7465. }`
  7466. ),
  7467. uploadProjectCoverImage: async (
  7468. projectId: number,
  7469. file: File
  7470. ): Promise<{ status: string; filename: string; size: number }> => {
  7471. const formData = new FormData();
  7472. formData.append('file', file);
  7473. const headers: Record<string, string> = {};
  7474. if (authToken) {
  7475. headers['Authorization'] = `Bearer ${authToken}`;
  7476. }
  7477. const response = await fetch(`${API_BASE}/projects/${projectId}/cover-image`, {
  7478. method: 'POST',
  7479. headers,
  7480. body: formData,
  7481. });
  7482. if (!response.ok) {
  7483. const error = await response.json().catch(() => ({}));
  7484. throw new Error(error.detail || `HTTP ${response.status}`);
  7485. }
  7486. return response.json();
  7487. },
  7488. deleteProjectCoverImage: (projectId: number) =>
  7489. request<{ status: string }>(`/projects/${projectId}/cover-image`, { method: 'DELETE' }),
  7490. // BOM (Bill of Materials)
  7491. getProjectBOM: (projectId: number) =>
  7492. request<BOMItem[]>(`/projects/${projectId}/bom`),
  7493. createBOMItem: (projectId: number, data: BOMItemCreate) =>
  7494. request<BOMItem>(`/projects/${projectId}/bom`, {
  7495. method: 'POST',
  7496. body: JSON.stringify(data),
  7497. }),
  7498. updateBOMItem: (projectId: number, itemId: number, data: BOMItemUpdate) =>
  7499. request<BOMItem>(`/projects/${projectId}/bom/${itemId}`, {
  7500. method: 'PATCH',
  7501. body: JSON.stringify(data),
  7502. }),
  7503. deleteBOMItem: (projectId: number, itemId: number) =>
  7504. request<{ status: string; message: string }>(`/projects/${projectId}/bom/${itemId}`, {
  7505. method: 'DELETE',
  7506. }),
  7507. // Templates
  7508. getTemplates: () => request<ProjectListItem[]>('/projects/templates/'),
  7509. createTemplateFromProject: (projectId: number) =>
  7510. request<Project>(`/projects/${projectId}/create-template`, { method: 'POST' }),
  7511. createProjectFromTemplate: (templateId: number, name?: string) =>
  7512. request<Project>(`/projects/from-template/${templateId}${name ? `?name=${encodeURIComponent(name)}` : ''}`, {
  7513. method: 'POST',
  7514. }),
  7515. // Timeline
  7516. getProjectTimeline: (projectId: number, limit = 50) =>
  7517. request<TimelineEvent[]>(`/projects/${projectId}/timeline?limit=${limit}`),
  7518. // Project Export/Import
  7519. exportProjectJson: (projectId: number) =>
  7520. request<ProjectExport>(`/projects/${projectId}/export?format=json`),
  7521. importProject: (data: ProjectImport) =>
  7522. request<Project>('/projects/import', {
  7523. method: 'POST',
  7524. body: JSON.stringify(data),
  7525. }),
  7526. importProjectFile: async (file: File): Promise<Project> => {
  7527. const formData = new FormData();
  7528. formData.append('file', file);
  7529. const headers: Record<string, string> = {};
  7530. if (authToken) {
  7531. headers['Authorization'] = `Bearer ${authToken}`;
  7532. }
  7533. const response = await fetch(`${API_BASE}/projects/import/file`, {
  7534. method: 'POST',
  7535. headers,
  7536. body: formData,
  7537. });
  7538. if (!response.ok) {
  7539. const error = await response.json().catch(() => ({}));
  7540. throw new Error(error.detail || `HTTP ${response.status}`);
  7541. }
  7542. return response.json();
  7543. },
  7544. exportProjectZip: async (projectId: number): Promise<{ blob: Blob; filename: string }> => {
  7545. const headers: Record<string, string> = {};
  7546. if (authToken) {
  7547. headers['Authorization'] = `Bearer ${authToken}`;
  7548. }
  7549. const response = await fetch(`${API_BASE}/projects/${projectId}/export`, {
  7550. headers,
  7551. });
  7552. if (!response.ok) {
  7553. const error = await response.json().catch(() => ({}));
  7554. throw new Error(error.detail || `HTTP ${response.status}`);
  7555. }
  7556. const contentDisposition = response.headers.get('Content-Disposition');
  7557. const filename = parseContentDispositionFilename(contentDisposition) || `project_${projectId}.zip`;
  7558. const blob = await response.blob();
  7559. return { blob, filename };
  7560. },
  7561. // API Keys
  7562. getAPIKeys: () => request<APIKey[]>('/api-keys/'),
  7563. createAPIKey: (data: APIKeyCreate) =>
  7564. request<APIKeyCreateResponse>('/api-keys/', {
  7565. method: 'POST',
  7566. body: JSON.stringify(data),
  7567. }),
  7568. deleteAPIKey: (id: number) =>
  7569. request<{ message: string }>(`/api-keys/${id}`, { method: 'DELETE' }),
  7570. // AMS History
  7571. getAMSHistory: (printerId: number, amsId: number, hours = 24) =>
  7572. request<AMSHistoryResponse>(`/ams-history/${printerId}/${amsId}?hours=${hours}`),
  7573. // Printer heater (nozzle / bed / chamber) sensor history
  7574. getPrinterSensorHistory: (printerId: number, hours = 24, kinds?: string[]) => {
  7575. const params = new URLSearchParams({ hours: String(hours) });
  7576. if (kinds && kinds.length > 0) params.set('kinds', kinds.join(','));
  7577. return request<PrinterSensorHistoryResponse>(`/printer-sensor-history/${printerId}?${params.toString()}`);
  7578. },
  7579. // System Info
  7580. getSystemInfo: () => request<SystemInfo>('/system/info'),
  7581. getSystemHealth: () => request<SystemHealthResult>('/system/health'),
  7582. getStorageUsage: (options?: { refresh?: boolean }) => {
  7583. const params = new URLSearchParams();
  7584. if (options?.refresh) {
  7585. params.set('refresh', 'true');
  7586. }
  7587. const query = params.toString();
  7588. return request<StorageUsageResponse>(`/system/storage-usage${query ? `?${query}` : ''}`);
  7589. },
  7590. // Library (File Manager)
  7591. getLibraryFolders: () => request<LibraryFolderTree[]>('/library/folders'),
  7592. createLibraryFolder: (data: LibraryFolderCreate) =>
  7593. request<LibraryFolder>('/library/folders', {
  7594. method: 'POST',
  7595. body: JSON.stringify(data),
  7596. }),
  7597. updateLibraryFolder: (id: number, data: LibraryFolderUpdate) =>
  7598. request<LibraryFolder>(`/library/folders/${id}`, {
  7599. method: 'PUT',
  7600. body: JSON.stringify(data),
  7601. }),
  7602. deleteLibraryFolder: (id: number) =>
  7603. request<{ status: string; message: string }>(`/library/folders/${id}`, { method: 'DELETE' }),
  7604. createExternalFolder: (data: ExternalFolderCreate) =>
  7605. request<LibraryFolder>('/library/folders/external', {
  7606. method: 'POST',
  7607. body: JSON.stringify(data),
  7608. }),
  7609. scanExternalFolder: (folderId: number) =>
  7610. request<{ status: string; added: number; removed: number }>(`/library/folders/${folderId}/scan`, {
  7611. method: 'POST',
  7612. }),
  7613. getLibraryFoldersByProject: (projectId: number) =>
  7614. request<LibraryFolder[]>(`/library/folders/by-project/${projectId}`),
  7615. getLibraryFoldersByArchive: (archiveId: number) => foldersByArchiveBatch(archiveId),
  7616. getLibraryFiles: (
  7617. folderId?: number | null,
  7618. includeRoot = true,
  7619. projectId?: number,
  7620. scope?: 'internal' | 'external',
  7621. recursive = false,
  7622. tagIds: number[] = [],
  7623. ) => {
  7624. const params = new URLSearchParams();
  7625. if (folderId !== undefined && folderId !== null) {
  7626. params.set('folder_id', String(folderId));
  7627. }
  7628. if (projectId !== undefined) {
  7629. params.set('project_id', String(projectId));
  7630. }
  7631. params.set('include_root', String(includeRoot));
  7632. if (scope === 'internal') params.set('internal_only', 'true');
  7633. else if (scope === 'external') params.set('external_only', 'true');
  7634. // recursive=true expands the folder_id filter to include every descendant
  7635. // folder (#1268). Only meaningful when folder_id is set; ignored server-side
  7636. // otherwise. Off by default so non-search callers keep folder-scoped behavior.
  7637. if (recursive) params.set('recursive', 'true');
  7638. // Tag filter (#1268). Repeated ?tag_ids=N&tag_ids=M form for AND semantics
  7639. // — backend joins the association table and HAVING COUNT(DISTINCT) matches
  7640. // the array length. Tag filter intentionally bypasses folder scoping
  7641. // server-side (cross-cutting design decision).
  7642. for (const tagId of tagIds) {
  7643. params.append('tag_ids', String(tagId));
  7644. }
  7645. return request<LibraryFileListItem[]>(`/library/files?${params}`);
  7646. },
  7647. getLibraryFolderReadme: (folderId: number) =>
  7648. request<{ filename: string; content: string; truncated: boolean }>(
  7649. `/library/folders/${folderId}/readme`,
  7650. ),
  7651. // ============ Library tag catalog (#1268) ============
  7652. getLibraryTags: () =>
  7653. request<LibraryTag[]>('/library/tags'),
  7654. createLibraryTag: (name: string) =>
  7655. request<LibraryTag>('/library/tags', {
  7656. method: 'POST',
  7657. body: JSON.stringify({ name }),
  7658. }),
  7659. updateLibraryTag: (id: number, name: string) =>
  7660. request<LibraryTag>(`/library/tags/${id}`, {
  7661. method: 'PATCH',
  7662. body: JSON.stringify({ name }),
  7663. }),
  7664. deleteLibraryTag: (id: number) =>
  7665. request<void>(`/library/tags/${id}`, { method: 'DELETE' }),
  7666. bulkAssignLibraryTags: (
  7667. fileIds: number[],
  7668. tagIds: number[],
  7669. action: 'add' | 'remove' | 'replace',
  7670. ) =>
  7671. request<LibraryTagBulkAssignResult>('/library/tags/bulk-assign', {
  7672. method: 'POST',
  7673. body: JSON.stringify({ file_ids: fileIds, tag_ids: tagIds, action }),
  7674. }),
  7675. // ============ Variant groups (#671 / #2570) ============
  7676. // "These files are the same job sliced for different printers." Consumed from
  7677. // both ends: the queue picks a printer and needs the matching file, the File
  7678. // Manager's print action has the printer and needs the same match.
  7679. createVariantGroup: (
  7680. members: { library_file_id: number; target_model?: string }[],
  7681. name?: string,
  7682. ) =>
  7683. request<VariantGroup>('/library/variant-groups', {
  7684. method: 'POST',
  7685. body: JSON.stringify({ members, ...(name ? { name } : {}) }),
  7686. }),
  7687. getVariantGroup: (groupId: number) =>
  7688. request<VariantGroup>(`/library/variant-groups/${groupId}`),
  7689. getLibraryFile: (id: number) => request<LibraryFile>(`/library/files/${id}`),
  7690. uploadLibraryFile: async (
  7691. file: File,
  7692. folderId?: number | null,
  7693. generateStlThumbnails: boolean = true
  7694. ): Promise<LibraryFileUploadResponse> => {
  7695. const formData = new FormData();
  7696. formData.append('file', file);
  7697. const params = new URLSearchParams();
  7698. if (folderId) params.set('folder_id', String(folderId));
  7699. params.set('generate_stl_thumbnails', String(generateStlThumbnails));
  7700. const headers: Record<string, string> = {};
  7701. if (authToken) {
  7702. headers['Authorization'] = `Bearer ${authToken}`;
  7703. }
  7704. const response = await fetch(`${API_BASE}/library/files?${params}`, {
  7705. method: 'POST',
  7706. headers,
  7707. body: formData,
  7708. });
  7709. if (!response.ok) {
  7710. const error = await response.json().catch(() => ({}));
  7711. throw new Error(error.detail || `HTTP ${response.status}`);
  7712. }
  7713. return response.json();
  7714. },
  7715. extractZipFile: async (
  7716. file: File,
  7717. folderId?: number | null,
  7718. preserveStructure: boolean = true,
  7719. createFolderFromZip: boolean = false,
  7720. generateStlThumbnails: boolean = true
  7721. ): Promise<ZipExtractResponse> => {
  7722. const formData = new FormData();
  7723. formData.append('file', file);
  7724. const params = new URLSearchParams();
  7725. if (folderId) params.set('folder_id', String(folderId));
  7726. params.set('preserve_structure', String(preserveStructure));
  7727. params.set('create_folder_from_zip', String(createFolderFromZip));
  7728. params.set('generate_stl_thumbnails', String(generateStlThumbnails));
  7729. const headers: Record<string, string> = {};
  7730. if (authToken) {
  7731. headers['Authorization'] = `Bearer ${authToken}`;
  7732. }
  7733. const response = await fetch(`${API_BASE}/library/files/extract-zip?${params}`, {
  7734. method: 'POST',
  7735. headers,
  7736. body: formData,
  7737. });
  7738. if (!response.ok) {
  7739. const error = await response.json().catch(() => ({}));
  7740. throw new Error(error.detail || `HTTP ${response.status}`);
  7741. }
  7742. return response.json();
  7743. },
  7744. updateLibraryFile: (id: number, data: LibraryFileUpdate) =>
  7745. request<LibraryFile>(`/library/files/${id}`, {
  7746. method: 'PUT',
  7747. body: JSON.stringify(data),
  7748. }),
  7749. deleteLibraryFile: (id: number) =>
  7750. request<{ status: string; message: string; trashed: boolean }>(`/library/files/${id}`, { method: 'DELETE' }),
  7751. // ========== Library Trash (#1008) ==========
  7752. previewLibraryPurge: (olderThanDays: number, includeNeverPrinted: boolean = true) =>
  7753. request<LibraryPurgePreview>(
  7754. `/library/purge/preview?older_than_days=${olderThanDays}&include_never_printed=${includeNeverPrinted}`,
  7755. ),
  7756. executeLibraryPurge: (olderThanDays: number, includeNeverPrinted: boolean = true) =>
  7757. request<{ moved_to_trash: number }>('/library/purge', {
  7758. method: 'POST',
  7759. body: JSON.stringify({ older_than_days: olderThanDays, include_never_printed: includeNeverPrinted }),
  7760. }),
  7761. listLibraryTrash: (limit: number = 100, offset: number = 0) =>
  7762. request<LibraryTrashListResponse>(`/library/trash?limit=${limit}&offset=${offset}`),
  7763. restoreLibraryTrash: (fileId: number) =>
  7764. request<{ status: string; id: number }>(`/library/trash/${fileId}/restore`, { method: 'POST' }),
  7765. hardDeleteLibraryTrash: (fileId: number) =>
  7766. request<{ status: string }>(`/library/trash/${fileId}`, { method: 'DELETE' }),
  7767. emptyLibraryTrash: () => request<{ deleted: number }>('/library/trash', { method: 'DELETE' }),
  7768. getLibraryTrashSettings: () =>
  7769. request<LibraryTrashSettings>('/library/trash/settings'),
  7770. updateLibraryTrashSettings: (body: LibraryTrashSettings) =>
  7771. request<LibraryTrashSettings>('/library/trash/settings', {
  7772. method: 'PUT',
  7773. body: JSON.stringify(body),
  7774. }),
  7775. getLibraryFileDownloadUrl: (id: number) => `${API_BASE}/library/files/${id}/download`,
  7776. createLibrarySlicerToken: (fileId: number) =>
  7777. request<{ token: string }>(`/library/files/${fileId}/slicer-token`, { method: 'POST' }),
  7778. getLibrarySlicerDownloadUrl: (fileId: number, token: string, filename: string) =>
  7779. `${API_BASE}/library/files/${fileId}/dl/${token}/${encodeURIComponent(buildSlicerUrlFilename(filename))}`,
  7780. downloadLibraryFile: async (id: number, filename?: string): Promise<void> => {
  7781. const headers: Record<string, string> = {};
  7782. if (authToken) {
  7783. headers['Authorization'] = `Bearer ${authToken}`;
  7784. }
  7785. const response = await fetch(`${API_BASE}/library/files/${id}/download`, { headers });
  7786. if (!response.ok) {
  7787. const error = await response.json().catch(() => ({}));
  7788. throw new Error(error.detail || `HTTP ${response.status}`);
  7789. }
  7790. const disposition = response.headers.get('Content-Disposition');
  7791. const downloadFilename = parseContentDispositionFilename(disposition) || filename || `file_${id}`;
  7792. const blob = await response.blob();
  7793. const url = window.URL.createObjectURL(blob);
  7794. const a = document.createElement('a');
  7795. a.href = url;
  7796. a.download = downloadFilename;
  7797. document.body.appendChild(a);
  7798. a.click();
  7799. document.body.removeChild(a);
  7800. window.URL.revokeObjectURL(url);
  7801. },
  7802. getLibraryFileThumbnailUrl: (id: number) => withMediaToken(`${API_BASE}/library/files/${id}/thumbnail`),
  7803. // Client-rendered preview thumbnail upload (#2976). STEP/PDF/spreadsheet
  7804. // previews render in the browser; the first render is posted back so the
  7805. // grid gets a thumbnail without a server-side renderer for those formats.
  7806. uploadLibraryPreviewThumbnail: async (fileId: number, thumbnail: Blob): Promise<{ updated: boolean }> => {
  7807. const formData = new FormData();
  7808. formData.append('thumbnail', thumbnail, 'preview.png');
  7809. const headers: Record<string, string> = {};
  7810. if (authToken) {
  7811. headers['Authorization'] = `Bearer ${authToken}`;
  7812. }
  7813. const response = await fetch(`${API_BASE}/library/files/${fileId}/preview-thumbnail`, {
  7814. method: 'POST',
  7815. headers,
  7816. body: formData,
  7817. });
  7818. if (!response.ok) {
  7819. const error = await response.json().catch(() => ({}));
  7820. throw new Error(error.detail || `HTTP ${response.status}`);
  7821. }
  7822. return response.json();
  7823. },
  7824. getLibraryFilePlateThumbnail: (id: number, plateIndex: number) =>
  7825. withMediaToken(`${API_BASE}/library/files/${id}/plate-thumbnail/${plateIndex}`),
  7826. // Photos of the printed result (#3077) — same shape as the archive photo API.
  7827. getLibraryFilePhotoUrl: (fileId: number, filename: string) =>
  7828. withMediaToken(`${API_BASE}/library/files/${fileId}/photos/${encodeURIComponent(filename)}`),
  7829. uploadLibraryFilePhoto: async (fileId: number, file: File): Promise<{ status: string; filename: string; photos: string[] }> => {
  7830. const formData = new FormData();
  7831. formData.append('file', file);
  7832. const headers: Record<string, string> = {};
  7833. if (authToken) {
  7834. headers['Authorization'] = `Bearer ${authToken}`;
  7835. }
  7836. const response = await fetch(`${API_BASE}/library/files/${fileId}/photos`, {
  7837. method: 'POST',
  7838. headers,
  7839. body: formData,
  7840. });
  7841. if (!response.ok) {
  7842. const error = await response.json().catch(() => ({}));
  7843. throw new Error(error.detail || `HTTP ${response.status}`);
  7844. }
  7845. return response.json();
  7846. },
  7847. deleteLibraryFilePhoto: (fileId: number, filename: string) =>
  7848. request<{ status: string; photos: string[] }>(`/library/files/${fileId}/photos/${encodeURIComponent(filename)}`, {
  7849. method: 'DELETE',
  7850. }),
  7851. getLibraryFileGcodeUrl: (id: number) => `${API_BASE}/library/files/${id}/gcode`,
  7852. moveLibraryFiles: (fileIds: number[], folderId: number | null) =>
  7853. request<{ status: string; moved: number }>('/library/files/move', {
  7854. method: 'POST',
  7855. body: JSON.stringify({ file_ids: fileIds, folder_id: folderId }),
  7856. }),
  7857. bulkDeleteLibrary: (fileIds: number[], folderIds: number[]) =>
  7858. request<{ deleted_files: number; deleted_folders: number }>('/library/bulk-delete', {
  7859. method: 'POST',
  7860. body: JSON.stringify({ file_ids: fileIds, folder_ids: folderIds }),
  7861. }),
  7862. getLibraryStats: () => request<LibraryStats>('/library/stats'),
  7863. batchGenerateStlThumbnails: (options: {
  7864. file_ids?: number[];
  7865. folder_id?: number;
  7866. all_missing?: boolean;
  7867. }) =>
  7868. request<BatchThumbnailResponse>('/library/generate-stl-thumbnails', {
  7869. method: 'POST',
  7870. body: JSON.stringify(options),
  7871. }),
  7872. combineLibraryFiles: (items: { file_id: number; copies: number }[], filename: string, folderId: number | null) =>
  7873. request<LibraryFileUploadResponse>('/library/files/combine', {
  7874. method: 'POST',
  7875. body: JSON.stringify({ items, filename, folder_id: folderId }),
  7876. }),
  7877. getLibraryFilePlates: (fileId: number) =>
  7878. request<LibraryFilePlatesResponse>(`/library/files/${fileId}/plates`),
  7879. getLibraryFileFilamentRequirements: (
  7880. fileId: number,
  7881. plateId?: number,
  7882. requestId?: string,
  7883. /** Ask for one entry per project slot instead of only the slots this
  7884. * plate consumes. The slice modal needs it: its filament list is
  7885. * positional, so a source whose only used slot is 4 must still present
  7886. * four rows or the user's pick is bound to slot 1 (#2712). Print-time
  7887. * AMS matching must NOT set this — it wants the used-only list. */
  7888. fullSlots?: boolean,
  7889. ) => {
  7890. const qs = new URLSearchParams();
  7891. if (plateId !== undefined) qs.set('plate_id', String(plateId));
  7892. if (requestId) qs.set('request_id', requestId);
  7893. if (fullSlots) qs.set('full_slots', 'true');
  7894. return request<{
  7895. file_id: number;
  7896. filename: string;
  7897. filaments: Array<{
  7898. slot_id: number;
  7899. type: string;
  7900. color: string;
  7901. used_grams: number;
  7902. used_meters: number;
  7903. used_in_plate?: boolean;
  7904. }>;
  7905. }>(`/library/files/${fileId}/filament-requirements${qs.toString() ? `?${qs}` : ''}`);
  7906. },
  7907. /** Poll the sidecar's per-request progress snapshot via the Bambuddy
  7908. * proxy. Used by the SliceModal's filament-discovery path so the inline
  7909. * spinner + persistent toast can show "Generating G-code (45%)" while
  7910. * the preview slice runs. Returns null on 404 (sidecar doesn't yet
  7911. * have an entry — early race window — or it expired) so the poller
  7912. * can keep trying. */
  7913. getPreviewSliceProgress: async (requestId: string): Promise<SliceJobProgress | null> => {
  7914. try {
  7915. return await request<SliceJobProgress>(`/slicer/preview-progress/${encodeURIComponent(requestId)}`);
  7916. } catch {
  7917. return null;
  7918. }
  7919. },
  7920. // GitHub Backup
  7921. getGitHubBackupConfig: () =>
  7922. request<GitHubBackupConfig | null>('/github-backup/config'),
  7923. getGitHubBackupCloudAccounts: () =>
  7924. request<CloudAccountCounts>('/github-backup/cloud-accounts'),
  7925. saveGitHubBackupConfig: (config: GitHubBackupConfigCreate) =>
  7926. request<GitHubBackupConfig>('/github-backup/config', {
  7927. method: 'POST',
  7928. body: JSON.stringify(config),
  7929. }),
  7930. updateGitHubBackupConfig: (config: Partial<GitHubBackupConfigCreate>) =>
  7931. request<GitHubBackupConfig>('/github-backup/config', {
  7932. method: 'PATCH',
  7933. body: JSON.stringify(config),
  7934. }),
  7935. testGitHubConnection: (repoUrl: string, token: string, provider: GitProviderType = 'github') =>
  7936. request<GitHubTestConnectionResponse>('/github-backup/test', {
  7937. method: 'POST',
  7938. body: JSON.stringify({ repo_url: repoUrl, token, provider }),
  7939. }),
  7940. testGitHubStoredConnection: () =>
  7941. request<GitHubTestConnectionResponse>('/github-backup/test-stored', { method: 'POST' }),
  7942. triggerGitHubBackup: () =>
  7943. request<GitHubBackupTriggerResponse>('/github-backup/run', { method: 'POST' }),
  7944. getGitHubBackupStatus: () =>
  7945. request<GitHubBackupStatus>('/github-backup/status'),
  7946. getGitHubBackupLogs: (limit: number = 50) =>
  7947. request<GitHubBackupLog[]>(`/github-backup/logs?limit=${limit}`),
  7948. clearGitHubBackupLogs: (keepLast: number = 10) =>
  7949. request<{ deleted: number; message: string }>(`/github-backup/logs?keep_last=${keepLast}`, { method: 'DELETE' }),
  7950. // Restore from a Git backup (#2656)
  7951. getGitHubBackupCommits: (limit: number = 20) =>
  7952. request<GitHubCommitListResponse>(`/github-backup/commits?limit=${limit}`),
  7953. getGitHubRestorePreview: (ref: string = 'HEAD') =>
  7954. request<GitHubRestorePreview>(`/github-backup/restore/preview?ref=${encodeURIComponent(ref)}`),
  7955. restoreFromGitHub: (payload: GitHubRestoreRequest) =>
  7956. request<GitHubRestoreResponse>('/github-backup/restore', {
  7957. method: 'POST',
  7958. body: JSON.stringify(payload),
  7959. }),
  7960. // Scheduled local backups
  7961. getLocalBackupStatus: () =>
  7962. request<LocalBackupStatus>('/local-backup/status'),
  7963. triggerLocalBackup: () =>
  7964. request<{ success: boolean; message: string; filename?: string }>('/local-backup/run', { method: 'POST' }),
  7965. checkLocalBackupPath: () =>
  7966. request<LocalBackupPathCheck>('/local-backup/path-check'),
  7967. getLocalBackups: () =>
  7968. request<LocalBackupFile[]>('/local-backup/backups'),
  7969. downloadLocalBackup: async (filename: string): Promise<{ blob: Blob; filename: string }> => {
  7970. const response = await fetch(`${API_BASE}/local-backup/backups/${encodeURIComponent(filename)}/download`, {
  7971. headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {},
  7972. });
  7973. if (!response.ok) throw new Error('Download failed');
  7974. const blob = await response.blob();
  7975. return { blob, filename };
  7976. },
  7977. restoreLocalBackup: (filename: string) =>
  7978. request<{ success: boolean; message: string }>(`/local-backup/backups/${encodeURIComponent(filename)}/restore`, { method: 'POST' }),
  7979. deleteLocalBackup: (filename: string) =>
  7980. request<{ success: boolean; message: string }>(`/local-backup/backups/${encodeURIComponent(filename)}`, { method: 'DELETE' }),
  7981. // Obico AI failure detection
  7982. getObicoStatus: () =>
  7983. request<ObicoStatus>('/obico/status'),
  7984. getObicoPrinterStatus: () =>
  7985. request<ObicoPrinterStatus>('/obico/printer-status'),
  7986. // `token` is sent as-is, so an empty string tests with no token at all.
  7987. // Omitting the argument makes the backend fall back to the saved token.
  7988. testObicoConnection: (url: string, token?: string) =>
  7989. request<ObicoTestConnection>('/obico/test-connection', {
  7990. method: 'POST',
  7991. body: JSON.stringify(token === undefined ? { url } : { url, token }),
  7992. }),
  7993. // OctoEverywhere AI failure detection
  7994. getOctoEverywhereStatus: () =>
  7995. request<OctoEverywhereStatus>('/octoeverywhere/status'),
  7996. getOctoEverywherePrinterStatus: () =>
  7997. request<OctoEverywherePrinterStatus>('/octoeverywhere/printer-status'),
  7998. // An omitted key uses the saved key; an explicit empty key is rejected.
  7999. testOctoEverywhereConnection: (apiKey?: string, confidence?: OctoEverywhereConfidence) =>
  8000. request<OctoEverywhereTestConnection>('/octoeverywhere/test-connection', {
  8001. method: 'POST',
  8002. body: JSON.stringify({ api_key: apiKey, confidence }),
  8003. }),
  8004. // Slicer API — slice in the background. Both endpoints return 202 + a
  8005. // job_id; poll /slice-jobs/{id} until status is `completed` or `failed`.
  8006. sliceLibraryFile: (fileId: number, body: SliceRequest) =>
  8007. request<SliceJobEnqueueResponse>(`/library/files/${fileId}/slice`, {
  8008. method: 'POST',
  8009. body: JSON.stringify(body),
  8010. }),
  8011. sliceArchive: (archiveId: number, body: SliceRequest) =>
  8012. request<SliceJobEnqueueResponse>(`/archives/${archiveId}/slice`, {
  8013. method: 'POST',
  8014. body: JSON.stringify(body),
  8015. }),
  8016. getSliceJob: (jobId: number) =>
  8017. request<SliceJobState>(`/slice-jobs/${jobId}`),
  8018. // Unified slicer-preset listing — cloud + local + standard, deduped by name.
  8019. // Used by the SliceModal; see UnifiedPresetsResponse for the shape and
  8020. // backend/app/api/routes/slicer_presets.py for the priority rules.
  8021. // `refresh` bypasses the in-process cloud and bundled-preset caches on the
  8022. // backend; the SliceModal's Refresh button passes true so a preset deleted
  8023. // in Bambu Studio or Bambu Handy shows up without the 5-min TTL wait.
  8024. getSlicerPresets: (options?: { refresh?: boolean }) =>
  8025. request<UnifiedPresetsResponse>(
  8026. options?.refresh ? '/slicer/presets?refresh=true' : '/slicer/presets',
  8027. ),
  8028. // Slicer Pipelines (#1425) — preset bundles the SliceModal can apply in
  8029. // one click. CRUD is gated on PIPELINES_READ / PIPELINES_WRITE.
  8030. listSlicerPipelines: () =>
  8031. request<SlicerPipelinesListResponse>('/slicer-pipelines/'),
  8032. createSlicerPipeline: (data: SlicerPipelineCreateRequest) =>
  8033. request<SlicerPipeline>('/slicer-pipelines/', {
  8034. method: 'POST',
  8035. body: JSON.stringify(data),
  8036. }),
  8037. updateSlicerPipeline: (id: number, data: SlicerPipelineUpdateRequest) =>
  8038. request<SlicerPipeline>(`/slicer-pipelines/${id}`, {
  8039. method: 'PUT',
  8040. body: JSON.stringify(data),
  8041. }),
  8042. deleteSlicerPipeline: (id: number) =>
  8043. request<void>(`/slicer-pipelines/${id}`, { method: 'DELETE' }),
  8044. checkPipelineEligibility: (
  8045. pipelineId: number,
  8046. source: { kind: 'libraryFile'; id: number } | { kind: 'archive'; id: number },
  8047. ) =>
  8048. request<PipelineEligibilityReport>(`/slicer-pipelines/${pipelineId}/check-eligibility`, {
  8049. method: 'POST',
  8050. body: JSON.stringify(
  8051. source.kind === 'libraryFile'
  8052. ? { source_library_file_id: source.id }
  8053. : { source_archive_id: source.id },
  8054. ),
  8055. }),
  8056. runPipeline: (
  8057. pipelineId: number,
  8058. source: { kind: 'libraryFile'; id: number } | { kind: 'archive'; id: number },
  8059. force = false,
  8060. copies = 1,
  8061. ) =>
  8062. request<PipelineRun>(`/slicer-pipelines/${pipelineId}/run`, {
  8063. method: 'POST',
  8064. body: JSON.stringify({
  8065. ...(source.kind === 'libraryFile'
  8066. ? { source_library_file_id: source.id }
  8067. : { source_archive_id: source.id }),
  8068. force,
  8069. copies,
  8070. }),
  8071. }),
  8072. listPipelineRuns: (pipelineId: number, limit = 5) =>
  8073. request<PipelineRunListResponse>(
  8074. `/slicer-pipelines/${pipelineId}/runs?limit=${limit}`,
  8075. ),
  8076. // Dashboard list across all pipelines (#1425 PR C).
  8077. listAllPipelineRuns: (params: {
  8078. limit?: number;
  8079. offset?: number;
  8080. pipelineId?: number;
  8081. status?: string;
  8082. targetPrinterId?: number;
  8083. targetModelClass?: string;
  8084. } = {}) => {
  8085. const search = new URLSearchParams();
  8086. if (params.limit) search.set('limit', String(params.limit));
  8087. if (params.offset) search.set('offset', String(params.offset));
  8088. if (params.pipelineId) search.set('pipeline_id', String(params.pipelineId));
  8089. if (params.status) search.set('status', params.status);
  8090. if (params.targetPrinterId) search.set('target_printer_id', String(params.targetPrinterId));
  8091. if (params.targetModelClass) search.set('target_model_class', params.targetModelClass);
  8092. const q = search.toString();
  8093. return request<PipelineRunListResponse>(
  8094. `/pipeline-runs${q ? '?' + q : ''}`,
  8095. );
  8096. },
  8097. // Clear terminal pipeline runs (#1425 PR C polish). Deletes all runs in
  8098. // a terminal state (completed/failed/cancelled/partial_failure); in-flight
  8099. // runs are preserved.
  8100. clearTerminalPipelineRuns: () =>
  8101. request<{ deleted: number }>('/pipeline-runs/clear', { method: 'POST' }),
  8102. cancelPipelineRun: (runId: number) =>
  8103. request<PipelineRun>(`/pipeline-runs/${runId}/cancel`, { method: 'POST' }),
  8104. retryFailedPipelineRun: (runId: number) =>
  8105. request<PipelineRun>(`/pipeline-runs/${runId}/retry-failed`, { method: 'POST' }),
  8106. // Canonical Bambu printer-model registry — "Bambu Lab <model>" → short code.
  8107. // Single source of truth shared with backend (PRINTER_MODEL_MAP); the
  8108. // SliceModal uses this to classify cloud / standard presets by their
  8109. // `@BBL <code>` suffix against the selected printer-preset name (#1325).
  8110. getSlicerPrinterModels: () =>
  8111. request<Record<string, string>>('/slicer/printer-models'),
  8112. getSlicerLoadedSpools: () =>
  8113. request<LoadedSpoolsResponse>('/slicer/loaded-spools'),
  8114. /**
  8115. * Effective values of a process preset, with its `inherits:` chain flattened
  8116. * by the slicer sidecar. Powers the slice modal's settings panel, which would
  8117. * otherwise show the option schema's compiled-in defaults (a preset setting a
  8118. * 0.42mm line width appears as the C++ default of 0).
  8119. *
  8120. * `resolved: false` means the values could not be obtained -- sidecar offline,
  8121. * too old for the endpoint, or slicing not configured -- and the caller should
  8122. * fall back to schema defaults rather than treat it as a failure.
  8123. */
  8124. getSlicerPresetValues: (ref: PresetRef) =>
  8125. request<SlicerPresetValues>(
  8126. `/slicer/preset-values?source=${encodeURIComponent(ref.source)}&id=${encodeURIComponent(ref.id)}`,
  8127. ),
  8128. // Local Presets (OrcaSlicer imports)
  8129. getLocalPresets: () =>
  8130. request<LocalPresetsResponse>('/local-presets/'),
  8131. importLocalPresets: (formData: FormData) =>
  8132. fetch(`${API_BASE}/local-presets/import`, {
  8133. method: 'POST',
  8134. headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {},
  8135. body: formData,
  8136. }).then(async (res) => {
  8137. if (!res.ok) {
  8138. const err = await res.json().catch(() => ({}));
  8139. throw new Error(err.detail || `HTTP ${res.status}`);
  8140. }
  8141. return res.json() as Promise<ImportResponse>;
  8142. }),
  8143. deleteLocalPreset: (id: number) =>
  8144. request<{ success: boolean }>(`/local-presets/${id}`, { method: 'DELETE' }),
  8145. };
  8146. // AMS History types
  8147. export interface AMSHistoryPoint {
  8148. recorded_at: string;
  8149. humidity: number | null;
  8150. humidity_raw: number | null;
  8151. temperature: number | null;
  8152. }
  8153. export interface AMSHistoryResponse {
  8154. printer_id: number;
  8155. ams_id: number;
  8156. data: AMSHistoryPoint[];
  8157. min_humidity: number | null;
  8158. max_humidity: number | null;
  8159. avg_humidity: number | null;
  8160. min_temperature: number | null;
  8161. max_temperature: number | null;
  8162. avg_temperature: number | null;
  8163. }
  8164. export type HeaterSensorKind = 'nozzle' | 'nozzle_2' | 'bed' | 'chamber';
  8165. export interface HeaterHistoryPoint {
  8166. recorded_at: string;
  8167. value: number | null;
  8168. target: number | null;
  8169. }
  8170. export interface HeaterSeries {
  8171. sensor_kind: HeaterSensorKind;
  8172. data: HeaterHistoryPoint[];
  8173. min_value: number | null;
  8174. max_value: number | null;
  8175. avg_value: number | null;
  8176. }
  8177. export interface PrinterSensorHistoryResponse {
  8178. printer_id: number;
  8179. series: HeaterSeries[];
  8180. }
  8181. // System Info types
  8182. export interface SystemInfo {
  8183. app: {
  8184. version: string;
  8185. base_dir: string;
  8186. archive_dir: string;
  8187. };
  8188. database: {
  8189. engine: string;
  8190. version: string;
  8191. archives: number;
  8192. archives_completed: number;
  8193. archives_failed: number;
  8194. archives_printing: number;
  8195. printers: number;
  8196. filaments: number;
  8197. projects: number;
  8198. smart_plugs: number;
  8199. total_print_time_seconds: number;
  8200. total_print_time_formatted: string;
  8201. total_filament_grams: number;
  8202. total_filament_kg: number;
  8203. };
  8204. printers: {
  8205. total: number;
  8206. connected: number;
  8207. connected_list: Array<{
  8208. id: number;
  8209. name: string;
  8210. state: string;
  8211. model: string;
  8212. }>;
  8213. };
  8214. storage: {
  8215. archive_size_bytes: number;
  8216. archive_size_formatted: string;
  8217. database_size_bytes: number;
  8218. database_size_formatted: string;
  8219. disk_total_bytes: number;
  8220. disk_total_formatted: string;
  8221. disk_used_bytes: number;
  8222. disk_used_formatted: string;
  8223. disk_free_bytes: number;
  8224. disk_free_formatted: string;
  8225. disk_percent_used: number;
  8226. };
  8227. system: {
  8228. platform: string;
  8229. platform_release: string;
  8230. platform_version: string;
  8231. architecture: string;
  8232. hostname: string;
  8233. python_version: string;
  8234. uptime_seconds: number;
  8235. uptime_formatted: string;
  8236. boot_time: string;
  8237. };
  8238. memory: {
  8239. total_bytes: number;
  8240. total_formatted: string;
  8241. available_bytes: number;
  8242. available_formatted: string;
  8243. used_bytes: number;
  8244. used_formatted: string;
  8245. percent_used: number;
  8246. };
  8247. cpu: {
  8248. count: number;
  8249. count_logical: number;
  8250. percent: number;
  8251. };
  8252. }
  8253. export interface StorageUsageCategory {
  8254. key: string;
  8255. label: string;
  8256. bytes: number;
  8257. formatted: string;
  8258. percent_of_total: number;
  8259. }
  8260. export interface StorageUsageOtherItem {
  8261. bucket: string;
  8262. label: string;
  8263. kind: 'system' | 'data';
  8264. deletable: boolean;
  8265. bytes: number;
  8266. formatted: string;
  8267. percent_of_total: number;
  8268. }
  8269. export interface StorageUsageResponse {
  8270. roots: string[];
  8271. total_bytes: number;
  8272. total_formatted: string;
  8273. categories: StorageUsageCategory[];
  8274. other_breakdown: StorageUsageOtherItem[];
  8275. scan_errors: number;
  8276. generated_at: string;
  8277. cache: {
  8278. hit: boolean;
  8279. age_seconds: number;
  8280. max_age_seconds: number;
  8281. };
  8282. }
  8283. // Library (File Manager) types
  8284. export interface LibraryFolderTree {
  8285. id: number;
  8286. name: string;
  8287. parent_id: number | null;
  8288. project_id: number | null;
  8289. archive_id: number | null;
  8290. project_name: string | null;
  8291. archive_name: string | null;
  8292. is_external: boolean;
  8293. external_path: string | null;
  8294. external_readonly: boolean;
  8295. file_count: number;
  8296. // max(folder.updated_at, max(immediate-child file.updated_at)). Used by
  8297. // the File Manager folder tree's "sort by recent activity" mode (#1770).
  8298. latest_activity_at: string | null;
  8299. // Ownership (#3201). can_* are for the current user: what the File
  8300. // Manager may offer on this folder. The backend enforces the same rules.
  8301. created_by_id: number | null;
  8302. shared: boolean;
  8303. can_write: boolean;
  8304. can_rename: boolean;
  8305. can_delete: boolean;
  8306. children: LibraryFolderTree[];
  8307. }
  8308. export interface LibraryFolder {
  8309. id: number;
  8310. name: string;
  8311. parent_id: number | null;
  8312. project_id: number | null;
  8313. archive_id: number | null;
  8314. project_name: string | null;
  8315. archive_name: string | null;
  8316. is_external: boolean;
  8317. external_path: string | null;
  8318. external_readonly: boolean;
  8319. external_show_hidden: boolean;
  8320. file_count: number;
  8321. latest_activity_at: string | null;
  8322. // Ownership (#3201). can_* are for the current user: what the File
  8323. // Manager may offer on this folder. The backend enforces the same rules.
  8324. created_by_id: number | null;
  8325. shared: boolean;
  8326. can_write: boolean;
  8327. can_rename: boolean;
  8328. can_delete: boolean;
  8329. created_at: string;
  8330. updated_at: string;
  8331. }
  8332. export interface LibraryFolderCreate {
  8333. name: string;
  8334. parent_id?: number | null;
  8335. project_id?: number | null;
  8336. archive_id?: number | null;
  8337. }
  8338. export interface ExternalFolderCreate {
  8339. name: string;
  8340. external_path: string;
  8341. readonly?: boolean;
  8342. show_hidden?: boolean;
  8343. parent_id?: number | null;
  8344. }
  8345. export interface LibraryFolderUpdate {
  8346. name?: string;
  8347. parent_id?: number | null;
  8348. project_id?: number | null; // 0 to unlink
  8349. archive_id?: number | null; // 0 to unlink
  8350. shared?: boolean; // library:update_all only (#3201)
  8351. }
  8352. export interface LibraryFileDuplicate {
  8353. id: number;
  8354. filename: string;
  8355. folder_id: number | null;
  8356. folder_name: string | null;
  8357. created_at: string;
  8358. }
  8359. export interface LibraryFile {
  8360. id: number;
  8361. folder_id: number | null;
  8362. folder_name: string | null;
  8363. project_id: number | null;
  8364. project_name: string | null;
  8365. is_external: boolean;
  8366. filename: string;
  8367. file_path: string;
  8368. file_type: string;
  8369. file_size: number;
  8370. file_hash: string | null;
  8371. thumbnail_path: string | null;
  8372. metadata: Record<string, unknown> | null;
  8373. print_count: number;
  8374. last_printed_at: string | null;
  8375. notes: string | null;
  8376. // User link + photos of the printed result (#3077); source_url is the
  8377. // read-only import provenance (MakerWorld).
  8378. external_url: string | null;
  8379. photos: string[];
  8380. source_url: string | null;
  8381. duplicates: LibraryFileDuplicate[] | null;
  8382. duplicate_count: number;
  8383. // User tracking (Issue #206)
  8384. created_by_id: number | null;
  8385. created_by_username: string | null;
  8386. created_at: string;
  8387. updated_at: string;
  8388. // Metadata fields
  8389. print_name: string | null;
  8390. print_time_seconds: number | null;
  8391. filament_used_grams: number | null;
  8392. sliced_for_model: string | null;
  8393. }
  8394. export interface LibraryTagSummary {
  8395. id: number;
  8396. name: string;
  8397. }
  8398. export interface LibraryFileListItem {
  8399. id: number;
  8400. folder_id: number | null;
  8401. is_external: boolean;
  8402. filename: string;
  8403. file_type: string;
  8404. file_size: number;
  8405. thumbnail_path: string | null;
  8406. print_count: number;
  8407. duplicate_count: number;
  8408. // User tracking (Issue #206)
  8409. created_by_id: number | null;
  8410. created_by_username: string | null;
  8411. created_at: string;
  8412. // Real on-disk modification time (#2680). Null for managed uploads; the date
  8413. // sort and "Modified" column use `fs_modified_at ?? created_at`.
  8414. fs_modified_at: string | null;
  8415. print_name: string | null;
  8416. print_time_seconds: number | null;
  8417. filament_used_grams: number | null;
  8418. sliced_for_model: string | null;
  8419. // Tags assigned to this file (#1268). The backend always emits an empty
  8420. // array when a file has no tags, but the field is typed optional so any
  8421. // legacy code path (or mock) that constructs a LibraryFileListItem without
  8422. // it doesn't crash the renderer. Read sites use `file.tags ?? []`.
  8423. tags?: LibraryTagSummary[];
  8424. // Variant grouping (#671 / #2570). `variant_count` is the size of the whole
  8425. // group, which may include files in other folders — never the number of
  8426. // matching rows on screen. 0 when the file is not grouped.
  8427. variant_group_id?: number | null;
  8428. variant_count?: number;
  8429. // Metadata indicators (#3077). Optional for the same reason as `tags`: older
  8430. // mocks construct list items without them. Read sites default to falsy.
  8431. external_url?: string | null;
  8432. has_notes?: boolean;
  8433. photo_count?: number;
  8434. }
  8435. // Variant groups (#671 / #2570): the same job sliced for different printers.
  8436. export interface VariantGroupMember {
  8437. library_file_id: number;
  8438. filename: string;
  8439. target_model: string;
  8440. position: number;
  8441. }
  8442. export interface VariantGroup {
  8443. id: number;
  8444. name: string;
  8445. /** In priority order — index 0 wins when several printers are free at once. */
  8446. members: VariantGroupMember[];
  8447. }
  8448. // Library tag catalog (#1268)
  8449. export interface LibraryTag {
  8450. id: number;
  8451. name: string;
  8452. file_count: number;
  8453. created_at: string;
  8454. updated_at: string;
  8455. }
  8456. export interface LibraryTagBulkAssignResult {
  8457. files_updated: number;
  8458. associations_added: number;
  8459. associations_removed: number;
  8460. }
  8461. export interface LibraryFileUpdate {
  8462. filename?: string;
  8463. folder_id?: number | null;
  8464. project_id?: number | null;
  8465. notes?: string | null;
  8466. external_url?: string | null;
  8467. }
  8468. // Library trash (#1008)
  8469. export interface LibraryTrashItem {
  8470. id: number;
  8471. filename: string;
  8472. file_size: number;
  8473. thumbnail_path: string | null;
  8474. folder_id: number | null;
  8475. folder_name: string | null;
  8476. created_by_id: number | null;
  8477. created_by_username: string | null;
  8478. deleted_at: string;
  8479. auto_purge_at: string;
  8480. }
  8481. export interface LibraryTrashListResponse {
  8482. items: LibraryTrashItem[];
  8483. total: number;
  8484. retention_days: number;
  8485. }
  8486. export interface LibraryPurgePreview {
  8487. count: number;
  8488. total_bytes: number;
  8489. sample_filenames: string[];
  8490. older_than_days: number;
  8491. include_never_printed: boolean;
  8492. }
  8493. export interface LibraryTrashSettings {
  8494. retention_days: number;
  8495. auto_purge_enabled: boolean;
  8496. auto_purge_days: number;
  8497. auto_purge_include_never_printed: boolean;
  8498. }
  8499. export interface ArchivePurgePreview {
  8500. count: number;
  8501. total_bytes: number;
  8502. sample_filenames: string[];
  8503. older_than_days: number;
  8504. }
  8505. export interface ArchiveMergeMember {
  8506. id: number;
  8507. print_name: string | null;
  8508. filename: string;
  8509. created_at: string | null;
  8510. run_count: number;
  8511. }
  8512. /** Why a group is left out: at work now, or holding files only one can keep. */
  8513. export type ArchiveMergeSkip = 'busy' | 'conflicting_files' | 'failed' | 'not_a_group';
  8514. export interface ArchiveMergeGroup {
  8515. survivor: ArchiveMergeMember;
  8516. merged: ArchiveMergeMember[];
  8517. skipped: ArchiveMergeSkip | null;
  8518. }
  8519. export interface ArchiveMergePreview {
  8520. groups: ArchiveMergeGroup[];
  8521. }
  8522. export interface ArchiveMergeResult {
  8523. merged: { survivor_id: number; merged_ids: number[] }[];
  8524. skipped: { survivor_id: number; reason: ArchiveMergeSkip }[];
  8525. }
  8526. export interface ArchivePurgeSettings {
  8527. enabled: boolean;
  8528. days: number;
  8529. // #1390: when true, bulk-deletes the linked PrintLogEntry rows so the
  8530. // contribution drops from Quick Stats too. Default false — soft-delete,
  8531. // Quick Stats preserved.
  8532. purge_stats: boolean;
  8533. }
  8534. export interface LibraryFileUploadResponse {
  8535. id: number;
  8536. filename: string;
  8537. file_type: string;
  8538. file_size: number;
  8539. thumbnail_path: string | null;
  8540. duplicate_of: number | null;
  8541. metadata: Record<string, unknown> | null;
  8542. }
  8543. export interface LibraryStats {
  8544. total_files: number;
  8545. total_folders: number;
  8546. total_size_bytes: number;
  8547. files_by_type: Record<string, number>;
  8548. total_prints: number;
  8549. disk_free_bytes: number;
  8550. disk_total_bytes: number;
  8551. disk_used_bytes: number;
  8552. }
  8553. export interface ZipExtractResult {
  8554. filename: string;
  8555. file_id: number;
  8556. folder_id: number | null;
  8557. }
  8558. export interface ZipExtractError {
  8559. filename: string;
  8560. error: string;
  8561. }
  8562. export interface ZipExtractResponse {
  8563. extracted: number;
  8564. folders_created: number;
  8565. files: ZipExtractResult[];
  8566. errors: ZipExtractError[];
  8567. }
  8568. // STL Thumbnail Generation types
  8569. export interface BatchThumbnailResult {
  8570. file_id: number;
  8571. filename: string;
  8572. success: boolean;
  8573. error?: string | null;
  8574. }
  8575. export interface BatchThumbnailResponse {
  8576. processed: number;
  8577. succeeded: number;
  8578. failed: number;
  8579. results: BatchThumbnailResult[];
  8580. }
  8581. // Discovery types
  8582. export interface DiscoveredPrinter {
  8583. serial: string;
  8584. name: string;
  8585. ip_address: string;
  8586. model: string | null;
  8587. discovered_at: string | null;
  8588. }
  8589. export interface DiscoveryStatus {
  8590. running: boolean;
  8591. }
  8592. export interface DiscoveryInfo {
  8593. is_docker: boolean;
  8594. ssdp_running: boolean;
  8595. scan_running: boolean;
  8596. subnets: string[];
  8597. }
  8598. export interface SubnetScanStatus {
  8599. running: boolean;
  8600. scanned: number;
  8601. total: number;
  8602. }
  8603. // Discovery API
  8604. export const discoveryApi = {
  8605. getInfo: () => request<DiscoveryInfo>('/discovery/info'),
  8606. startDiscovery: (duration: number = 10) =>
  8607. request<DiscoveryStatus>(`/discovery/start?duration=${duration}`, { method: 'POST' }),
  8608. stopDiscovery: () =>
  8609. request<DiscoveryStatus>('/discovery/stop', { method: 'POST' }),
  8610. getDiscoveredPrinters: () =>
  8611. request<DiscoveredPrinter[]>('/discovery/printers'),
  8612. // Subnet scanning (for Docker environments)
  8613. startSubnetScan: (subnet: string, timeout: number = 1.0) =>
  8614. request<SubnetScanStatus>('/discovery/scan', {
  8615. method: 'POST',
  8616. body: JSON.stringify({ subnet, timeout }),
  8617. }),
  8618. getScanStatus: () => request<SubnetScanStatus>('/discovery/scan/status'),
  8619. stopSubnetScan: () =>
  8620. request<SubnetScanStatus>('/discovery/scan/stop', { method: 'POST' }),
  8621. };
  8622. // Virtual Printer types
  8623. // Canonical wire values: `archive`, `review`, `queue`, `proxy`. The legacy
  8624. // `immediate` (→ archive) and `print_queue` (→ queue) names are still
  8625. // accepted by the backend so older API clients keep working, but new code
  8626. // should send the canonical names.
  8627. // 'archive' and 'immediate' are older names of 'library', 'print_queue' of 'queue'.
  8628. export type VirtualPrinterMode = 'library' | 'review' | 'queue' | 'proxy' | 'archive' | 'immediate' | 'print_queue';
  8629. export interface VirtualPrinterProxyStatus {
  8630. running: boolean;
  8631. target_host: string;
  8632. ftp_port: number;
  8633. mqtt_port: number;
  8634. ftp_connections: number;
  8635. mqtt_connections: number;
  8636. }
  8637. export interface VirtualPrinterStatus {
  8638. enabled: boolean;
  8639. running: boolean;
  8640. mode: VirtualPrinterMode;
  8641. name: string;
  8642. serial: string;
  8643. model: string;
  8644. model_name: string;
  8645. pending_files: number;
  8646. target_printer_ip?: string; // For proxy mode
  8647. proxy?: VirtualPrinterProxyStatus; // For proxy mode
  8648. }
  8649. export interface VirtualPrinterSettings {
  8650. tailscale_disabled: boolean;
  8651. archive_name_source: 'metadata' | 'filename'; // Source for archive's display name
  8652. status: VirtualPrinterStatus;
  8653. }
  8654. export interface NetworkInterface {
  8655. name: string;
  8656. ip: string;
  8657. netmask: string;
  8658. subnet: string;
  8659. is_alias?: boolean;
  8660. label?: string;
  8661. }
  8662. export interface PendingUpload {
  8663. id: number;
  8664. filename: string;
  8665. // Resolved name the review card should show — mirrors what archive_print
  8666. // will eventually write to PrintArchive.print_name (#1152 follow-up). Falls
  8667. // back to the stripped filename stem when the 3MF has no embedded title or
  8668. // the operator has chosen the "filename" archive-name source.
  8669. display_name: string;
  8670. file_size: number;
  8671. source_ip: string | null;
  8672. status: string;
  8673. tags: string | null;
  8674. notes: string | null;
  8675. project_id: number | null;
  8676. uploaded_at: string;
  8677. }
  8678. // Virtual Printer API
  8679. export const virtualPrinterApi = {
  8680. getSettings: () => request<VirtualPrinterSettings>('/settings/virtual-printer'),
  8681. updateSettings: (data: {
  8682. tailscale_disabled?: boolean;
  8683. archive_name_source?: 'metadata' | 'filename';
  8684. }) => {
  8685. const params = new URLSearchParams();
  8686. if (data.tailscale_disabled !== undefined) params.set('tailscale_disabled', String(data.tailscale_disabled));
  8687. if (data.archive_name_source !== undefined) params.set('archive_name_source', data.archive_name_source);
  8688. return request<VirtualPrinterSettings>(`/settings/virtual-printer?${params.toString()}`, {
  8689. method: 'PUT',
  8690. });
  8691. },
  8692. };
  8693. // Multi Virtual Printer API
  8694. export interface VirtualPrinterConfig {
  8695. id: number;
  8696. name: string;
  8697. enabled: boolean;
  8698. mode: VirtualPrinterMode;
  8699. model: string | null;
  8700. model_name: string | null;
  8701. access_code_set: boolean;
  8702. serial: string;
  8703. target_printer_id: number | null;
  8704. // File Manager folder uploads land in; null = the shared "Virtual Printer" folder.
  8705. library_folder_id: number | null;
  8706. // Queue mode: remove the file from the File Manager once its print starts.
  8707. queue_remove_after_print: boolean;
  8708. auto_dispatch: boolean;
  8709. queue_force_color_match: boolean;
  8710. save_ams_mapping: boolean;
  8711. gcode_injection: boolean;
  8712. tailscale_disabled: boolean;
  8713. bind_ip: string | null;
  8714. remote_interface_ip: string | null;
  8715. position: number;
  8716. status: { running: boolean; pending_files: number; proxy?: VirtualPrinterProxyStatus };
  8717. }
  8718. export interface VirtualPrinterListResponse {
  8719. printers: VirtualPrinterConfig[];
  8720. models: Record<string, string>;
  8721. // Serial family (first 3 characters) per model code: tells apart codes of one name (H2C: O1C 094, O1C2 31B).
  8722. model_serial_prefixes?: Record<string, string>;
  8723. }
  8724. export const multiVirtualPrinterApi = {
  8725. list: () => request<VirtualPrinterListResponse>('/virtual-printers'),
  8726. get: (id: number) => request<VirtualPrinterConfig>(`/virtual-printers/${id}`),
  8727. create: (data: {
  8728. name?: string;
  8729. enabled?: boolean;
  8730. mode?: string;
  8731. model?: string;
  8732. access_code?: string;
  8733. target_printer_id?: number;
  8734. auto_dispatch?: boolean;
  8735. queue_force_color_match?: boolean;
  8736. save_ams_mapping?: boolean;
  8737. gcode_injection?: boolean;
  8738. bind_ip?: string;
  8739. remote_interface_ip?: string;
  8740. }) =>
  8741. request<VirtualPrinterConfig>('/virtual-printers', {
  8742. method: 'POST',
  8743. body: JSON.stringify(data),
  8744. }),
  8745. update: (id: number, data: {
  8746. name?: string;
  8747. enabled?: boolean;
  8748. mode?: string;
  8749. model?: string;
  8750. access_code?: string;
  8751. // null clears the target (a queue VP then sends to any printer of its model).
  8752. target_printer_id?: number | null;
  8753. // null: back to the shared "Virtual Printer" folder.
  8754. library_folder_id?: number | null;
  8755. queue_remove_after_print?: boolean;
  8756. auto_dispatch?: boolean;
  8757. queue_force_color_match?: boolean;
  8758. save_ams_mapping?: boolean;
  8759. gcode_injection?: boolean;
  8760. tailscale_disabled?: boolean;
  8761. bind_ip?: string;
  8762. remote_interface_ip?: string;
  8763. }) =>
  8764. request<VirtualPrinterConfig>(`/virtual-printers/${id}`, {
  8765. method: 'PUT',
  8766. body: JSON.stringify(data),
  8767. }),
  8768. remove: (id: number) =>
  8769. request<{ detail: string; id: number }>(`/virtual-printers/${id}`, {
  8770. method: 'DELETE',
  8771. }),
  8772. getTailscaleStatus: () =>
  8773. request<TailscaleStatusResponse>('/virtual-printers/tailscale-status'),
  8774. getCaCertificate: () =>
  8775. request<VPCaCertificate>('/virtual-printers/ca-certificate'),
  8776. // A script that adds the CA to Bambu Studio and OrcaSlicer, with the CA
  8777. // written into it: 'windows' (.cmd) or 'unix' (.sh, Linux and macOS).
  8778. // The signed-in user's personal access code (#1430); renewing replaces it.
  8779. getMyAccessCode: () => request<{ code: string }>('/virtual-printers/my-access-code'),
  8780. renewMyAccessCode: () => request<{ code: string }>('/virtual-printers/my-access-code', { method: 'POST' }),
  8781. getCaCertificateInstaller: (platform: 'windows' | 'unix') =>
  8782. request<{ filename: string; content: string }>(`/virtual-printers/ca-certificate/installer/${platform}`),
  8783. diagnose: (id: number) =>
  8784. request<VPDiagnosticResult>(`/virtual-printers/${id}/diagnostic`),
  8785. };
  8786. /** The shared CA certificate every virtual printer presents — imported once
  8787. * into the slicer's trust store. Only the public certificate is returned. */
  8788. export interface VPCaCertificate {
  8789. pem: string;
  8790. fingerprint_sha256: string;
  8791. not_valid_after: string;
  8792. }
  8793. export type VPDiagnosticStatus = 'pass' | 'fail' | 'warn' | 'skip';
  8794. export interface VPDiagnosticCheck {
  8795. id:
  8796. | 'enabled'
  8797. | 'running'
  8798. | 'bind_interface'
  8799. | 'access_code'
  8800. | 'target_printer'
  8801. | 'port_ftps'
  8802. | 'port_mqtt'
  8803. | 'port_bind'
  8804. | 'certificate';
  8805. status: VPDiagnosticStatus;
  8806. params: Record<string, string | number>;
  8807. }
  8808. export interface VPDiagnosticResult {
  8809. vp_id: number;
  8810. vp_name: string;
  8811. mode: string;
  8812. overall: 'ok' | 'warnings' | 'problems';
  8813. checks: VPDiagnosticCheck[];
  8814. }
  8815. export interface TailscaleStatusResponse {
  8816. available: boolean;
  8817. fqdn: string;
  8818. hostname: string;
  8819. tailnet_name: string;
  8820. tailscale_ips: string[];
  8821. error: string | null;
  8822. }
  8823. // Pending Uploads API
  8824. export const pendingUploadsApi = {
  8825. list: () => request<PendingUpload[]>('/pending-uploads/'),
  8826. getCount: () => request<{ count: number }>('/pending-uploads/count'),
  8827. get: (id: number) => request<PendingUpload>(`/pending-uploads/${id}`),
  8828. // Approve: the file goes to its virtual printer's File Manager folder.
  8829. archive: (id: number, data?: { tags?: string; notes?: string; project_id?: number }) =>
  8830. request<{ id: number; filename: string; folder_id: number | null }>(`/pending-uploads/${id}/archive`, {
  8831. method: 'POST',
  8832. body: JSON.stringify(data || {}),
  8833. }),
  8834. discard: (id: number) =>
  8835. request<{ success: boolean }>(`/pending-uploads/${id}`, { method: 'DELETE' }),
  8836. archiveAll: () =>
  8837. request<{ stored: number; failed: number }>('/pending-uploads/archive-all', { method: 'POST' }),
  8838. discardAll: () =>
  8839. request<{ discarded: number }>('/pending-uploads/discard-all', { method: 'DELETE' }),
  8840. };
  8841. // Firmware API Types
  8842. export interface AvailableFirmwareVersion {
  8843. version: string;
  8844. file_available: boolean;
  8845. download_url: string | null;
  8846. release_notes: string | null;
  8847. release_time: string | null;
  8848. }
  8849. export interface FirmwareUpdateInfo {
  8850. printer_id: number;
  8851. printer_name: string;
  8852. model: string | null;
  8853. current_version: string | null;
  8854. latest_version: string | null;
  8855. update_available: boolean;
  8856. download_url: string | null;
  8857. release_notes: string | null;
  8858. available_versions: AvailableFirmwareVersion[];
  8859. }
  8860. export interface FirmwareUploadPrepare {
  8861. can_proceed: boolean;
  8862. sd_card_present: boolean;
  8863. sd_card_free_space: number;
  8864. firmware_size: number;
  8865. space_sufficient: boolean;
  8866. update_available: boolean;
  8867. current_version: string | null;
  8868. latest_version: string | null;
  8869. target_version: string | null;
  8870. firmware_filename: string | null;
  8871. errors: string[];
  8872. }
  8873. export interface FirmwareUploadStatus {
  8874. status: 'idle' | 'preparing' | 'downloading' | 'uploading' | 'complete' | 'error';
  8875. progress: number;
  8876. message: string;
  8877. error: string | null;
  8878. firmware_filename: string | null;
  8879. firmware_version: string | null;
  8880. }
  8881. // Firmware API
  8882. export const firmwareApi = {
  8883. checkUpdates: () =>
  8884. request<{ updates: FirmwareUpdateInfo[]; updates_available: number }>('/firmware/updates'),
  8885. checkPrinterUpdate: (printerId: number) => firmwareUpdateBatch(printerId),
  8886. prepareUpload: (printerId: number, version?: string) =>
  8887. request<FirmwareUploadPrepare>(
  8888. `/firmware/updates/${printerId}/prepare${version ? `?version=${encodeURIComponent(version)}` : ''}`,
  8889. ),
  8890. startUpload: (printerId: number, version?: string) =>
  8891. request<{ started: boolean; message: string }>(
  8892. `/firmware/updates/${printerId}/upload${version ? `?version=${encodeURIComponent(version)}` : ''}`,
  8893. { method: 'POST' },
  8894. ),
  8895. getUploadStatus: (printerId: number) =>
  8896. request<FirmwareUploadStatus>(`/firmware/updates/${printerId}/upload/status`),
  8897. };
  8898. // Support types
  8899. export interface DebugLoggingState {
  8900. enabled: boolean;
  8901. enabled_at: string | null;
  8902. duration_seconds: number | null;
  8903. }
  8904. export interface LogEntry {
  8905. timestamp: string;
  8906. level: string;
  8907. logger_name: string;
  8908. message: string;
  8909. }
  8910. export interface LogsResponse {
  8911. entries: LogEntry[];
  8912. total_in_file: number;
  8913. filtered_count: number;
  8914. }
  8915. // Support API
  8916. export const supportApi = {
  8917. getDebugLoggingState: () =>
  8918. request<DebugLoggingState>('/support/debug-logging'),
  8919. setDebugLogging: (enabled: boolean) =>
  8920. request<DebugLoggingState>('/support/debug-logging', {
  8921. method: 'POST',
  8922. body: JSON.stringify({ enabled }),
  8923. }),
  8924. downloadSupportBundle: async () => {
  8925. const headers: Record<string, string> = {};
  8926. if (authToken) {
  8927. headers['Authorization'] = `Bearer ${authToken}`;
  8928. }
  8929. const response = await fetch(`${API_BASE}/support/bundle`, { headers });
  8930. if (!response.ok) {
  8931. const error = await response.json().catch(() => ({}));
  8932. throw new Error(error.detail || `HTTP ${response.status}`);
  8933. }
  8934. // Get filename from Content-Disposition header or use default
  8935. const disposition = response.headers.get('Content-Disposition');
  8936. const filename = parseContentDispositionFilename(disposition) || 'bambuddy-support.zip';
  8937. // Download the blob
  8938. const blob = await response.blob();
  8939. const url = window.URL.createObjectURL(blob);
  8940. const a = document.createElement('a');
  8941. a.href = url;
  8942. a.download = filename;
  8943. document.body.appendChild(a);
  8944. a.click();
  8945. document.body.removeChild(a);
  8946. window.URL.revokeObjectURL(url);
  8947. },
  8948. getLogs: (params?: { limit?: number; level?: string; search?: string }) => {
  8949. const searchParams = new URLSearchParams();
  8950. if (params?.limit) searchParams.set('limit', params.limit.toString());
  8951. if (params?.level) searchParams.set('level', params.level);
  8952. if (params?.search) searchParams.set('search', params.search);
  8953. const query = searchParams.toString();
  8954. return request<LogsResponse>(`/support/logs${query ? `?${query}` : ''}`);
  8955. },
  8956. clearLogs: () =>
  8957. request<{ message: string }>('/support/logs', { method: 'DELETE' }),
  8958. };
  8959. // SpoolBuddy types
  8960. export interface SpoolBuddyDevice {
  8961. id: number;
  8962. device_id: string;
  8963. hostname: string;
  8964. ip_address: string;
  8965. backend_url?: string | null;
  8966. firmware_version: string | null;
  8967. has_nfc: boolean;
  8968. has_scale: boolean;
  8969. tare_offset: number;
  8970. calibration_factor: number;
  8971. nfc_reader_type: string | null;
  8972. nfc_connection: string | null;
  8973. display_brightness: number;
  8974. display_blank_timeout: number;
  8975. has_backlight: boolean;
  8976. last_calibrated_at: string | null;
  8977. last_seen: string | null;
  8978. pending_command: string | null;
  8979. nfc_ok: boolean;
  8980. scale_ok: boolean;
  8981. uptime_s: number;
  8982. update_status: string | null;
  8983. update_message: string | null;
  8984. system_stats: {
  8985. os?: { os?: string; kernel?: string; arch?: string; python?: string };
  8986. cpu_temp_c?: number;
  8987. cpu_count?: number;
  8988. load_avg?: number[];
  8989. memory?: { total_mb?: number; available_mb?: number; used_mb?: number; percent?: number };
  8990. disk?: { total_gb?: number; used_gb?: number; free_gb?: number; percent?: number };
  8991. system_uptime_s?: number;
  8992. } | null;
  8993. online: boolean;
  8994. }
  8995. export interface DaemonUpdateCheck {
  8996. current_version: string;
  8997. latest_version: string | null;
  8998. update_available: boolean;
  8999. }
  9000. // SpoolBuddy API
  9001. export const spoolbuddyApi = {
  9002. getDevices: () =>
  9003. request<SpoolBuddyDevice[]>('/spoolbuddy/devices'),
  9004. deleteDevice: (deviceId: string) =>
  9005. request<{ status: string; device_id: string }>(`/spoolbuddy/devices/${deviceId}`, {
  9006. method: 'DELETE',
  9007. }),
  9008. tare: (deviceId: string) =>
  9009. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/calibration/tare`, {
  9010. method: 'POST',
  9011. body: '{}',
  9012. }),
  9013. setCalibrationFactor: (deviceId: string, knownWeightGrams: number, rawAdc: number, tareRawAdc?: number) =>
  9014. request<{ tare_offset: number; calibration_factor: number }>(`/spoolbuddy/devices/${deviceId}/calibration/set-factor`, {
  9015. method: 'POST',
  9016. body: JSON.stringify({ known_weight_grams: knownWeightGrams, raw_adc: rawAdc, tare_raw_adc: tareRawAdc }),
  9017. }),
  9018. updateSpoolWeight: (spoolId: number, weightGrams: number) =>
  9019. request<{ status: string; weight_used: number }>('/spoolbuddy/scale/update-spool-weight', {
  9020. method: 'POST',
  9021. body: JSON.stringify({ spool_id: spoolId, weight_grams: weightGrams }),
  9022. }),
  9023. updateDisplay: (deviceId: string, brightness: number, blankTimeout: number) =>
  9024. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/display`, {
  9025. method: 'PUT',
  9026. body: JSON.stringify({ brightness, blank_timeout: blankTimeout }),
  9027. }),
  9028. updateSystemConfig: (deviceId: string, backendUrl: string, apiKey?: string) =>
  9029. request<{ status: string; message: string }>(`/spoolbuddy/devices/${deviceId}/system/config`, {
  9030. method: 'POST',
  9031. body: JSON.stringify({ backend_url: backendUrl, ...(apiKey ? { api_key: apiKey } : {}) }),
  9032. }),
  9033. checkDaemonUpdate: (deviceId: string) =>
  9034. request<DaemonUpdateCheck>(`/spoolbuddy/devices/${deviceId}/update-check`),
  9035. triggerUpdate: (deviceId: string) =>
  9036. request<{ status: string; message: string }>(`/spoolbuddy/devices/${deviceId}/update`, {
  9037. method: 'POST',
  9038. body: '{}',
  9039. }),
  9040. getSSHPublicKey: () =>
  9041. request<{ public_key: string }>('/spoolbuddy/ssh/public-key'),
  9042. writeTag: (deviceId: string, spoolId: number) =>
  9043. request<{ status: string; warnings?: string[] }>('/spoolbuddy/nfc/write-tag', {
  9044. method: 'POST',
  9045. body: JSON.stringify({ device_id: deviceId, spool_id: spoolId }),
  9046. }),
  9047. cancelWrite: (deviceId: string) =>
  9048. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/cancel-write`, {
  9049. method: 'POST',
  9050. body: '{}',
  9051. }),
  9052. systemCommand: (deviceId: string, command: 'reboot' | 'shutdown' | 'restart_daemon' | 'restart_browser') =>
  9053. request<{ status: string; command: string }>(`/spoolbuddy/devices/${deviceId}/system/command`, {
  9054. method: 'POST',
  9055. body: JSON.stringify({ command }),
  9056. }),
  9057. queueDiagnostics: (deviceId: string, type: 'nfc' | 'scale' | 'read_tag') =>
  9058. request<{ status: string; diagnostic: string; message: string }>(
  9059. `/spoolbuddy/diagnostics/${deviceId}/run?diagnostic=${type}`,
  9060. { method: 'POST', body: '{}' }
  9061. ),
  9062. getDiagnosticResult: (deviceId: string, type: 'nfc' | 'scale' | 'read_tag') =>
  9063. request<{ diagnostic: string; success: boolean; output: string; exit_code: number }>(
  9064. `/spoolbuddy/diagnostics/${deviceId}/result?diagnostic=${type}`,
  9065. { method: 'GET' }
  9066. ),
  9067. };
  9068. export interface BugReportRequest {
  9069. description: string;
  9070. email?: string;
  9071. screenshot_base64?: string;
  9072. include_support_info?: boolean;
  9073. debug_logs?: string;
  9074. }
  9075. export interface BugReportResponse {
  9076. success: boolean;
  9077. message: string;
  9078. issue_url?: string;
  9079. issue_number?: number;
  9080. }
  9081. export const bugReportApi = {
  9082. submit: (data: BugReportRequest) =>
  9083. request<BugReportResponse>('/bug-report/submit', {
  9084. method: 'POST',
  9085. body: JSON.stringify(data),
  9086. }),
  9087. startLogging: () =>
  9088. request<{ started: boolean; was_debug: boolean }>('/bug-report/start-logging', {
  9089. method: 'POST',
  9090. }),
  9091. stopLogging: (wasDebug: boolean) =>
  9092. request<{ logs: string }>(`/bug-report/stop-logging?was_debug=${wasDebug}`, {
  9093. method: 'POST',
  9094. }),
  9095. };
  9096. export type AnnouncementLevel = 'info' | 'important' | 'critical';
  9097. export interface AnnouncementText {
  9098. title: string;
  9099. body: string;
  9100. link_label?: string;
  9101. }
  9102. // One message from the Bambuddy maintainers. `texts` holds every language the
  9103. // message was written in; English is always there.
  9104. export interface Announcement {
  9105. id: string;
  9106. level: AnnouncementLevel;
  9107. texts: Record<string, AnnouncementText>;
  9108. link_url: string | null;
  9109. published_at: string | null;
  9110. expires_at: string | null;
  9111. // Past its expiry: kept as history, listed under "Earlier", never unread.
  9112. archived: boolean;
  9113. read: boolean;
  9114. }
  9115. // `visible` says whether this user may see announcements at all (switched on,
  9116. // and admin or "show to all users"); it keeps the sidebar entry while nothing
  9117. // is published.
  9118. export interface AnnouncementList {
  9119. visible: boolean;
  9120. announcements: Announcement[];
  9121. }
  9122. export const announcementsApi = {
  9123. list: () => request<AnnouncementList>('/announcements'),
  9124. markRead: (id: string) =>
  9125. request<void>(`/announcements/${encodeURIComponent(id)}/read`, { method: 'POST' }),
  9126. };
  9127. export interface SponsorPromptCheckResponse {
  9128. show: boolean;
  9129. milestone?: string;
  9130. family?: 'prints' | 'cost' | 'archives' | 'anniversary' | 'version-update';
  9131. threshold?: number;
  9132. payload?: Record<string, unknown>;
  9133. }
  9134. export const sponsorPromptApi = {
  9135. check: () => request<SponsorPromptCheckResponse>('/sponsor-prompt/check'),
  9136. dismiss: (milestone: string) =>
  9137. request<void>('/sponsor-prompt/dismiss', {
  9138. method: 'POST',
  9139. body: JSON.stringify({ milestone }),
  9140. }),
  9141. };