client.ts 349 KB

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