client.ts 349 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765
  1. import type { KProfileWriteResult } from '../utils/kprofileWrite';
  2. import type { BambuCatalogColor } from '../utils/colors';
  3. import type { ArchivePlatesResponse, LibraryFilePlatesResponse } from '../types/plates';
  4. import { batched, byField, byId } from './batch';
  5. const API_BASE = '/api/v1';
  6. export class ApiError extends Error {
  7. status: number;
  8. /** Stable error code from a structured backend detail (`{code, message}`).
  9. * Frontend uses this to look up an i18n key instead of showing the raw
  10. * English fallback. Null when the backend returned a plain-string detail. */
  11. code: string | null;
  12. /** Full structured detail object when the backend returned `{code, ...}`
  13. * with additional fields (e.g. the deficit list for 409s on queue
  14. * start, #1496). Null for plain-string or array-shaped details. */
  15. detail: Record<string, unknown> | null;
  16. constructor(
  17. message: string,
  18. status: number,
  19. code: string | null = null,
  20. detail: Record<string, unknown> | null = null,
  21. ) {
  22. super(message);
  23. this.name = 'ApiError';
  24. this.status = status;
  25. this.code = code;
  26. this.detail = detail;
  27. }
  28. }
  29. // Auth token storage
  30. // By default tokens are stored in sessionStorage (tab-scoped, cleared on close).
  31. // When the token originates from the ?token= URL param (kiosk bootstrap), it is
  32. // additionally persisted in localStorage so the kiosk survives page reloads.
  33. // 'persistent' also writes to localStorage so the token survives tab close
  34. // (used by Remember Me and the ?token= kiosk bootstrap).
  35. let authToken: string | null =
  36. sessionStorage.getItem('auth_token') ?? localStorage.getItem('auth_token');
  37. export type TokenPersistence = 'session' | 'persistent';
  38. export function setAuthToken(token: string | null, persistence: TokenPersistence = 'session') {
  39. authToken = token;
  40. try {
  41. if (token) {
  42. sessionStorage.setItem('auth_token', token);
  43. } else {
  44. sessionStorage.removeItem('auth_token');
  45. }
  46. } catch (err) {
  47. // Storage unavailable (quota exceeded, private mode): in-memory token still works for this tab.
  48. console.warn('setAuthToken: sessionStorage unavailable, token kept in-memory only', err);
  49. }
  50. try {
  51. if (!token) {
  52. localStorage.removeItem('auth_token');
  53. } else if (persistence === 'persistent') {
  54. localStorage.setItem('auth_token', token);
  55. }
  56. } catch (err) {
  57. console.warn('setAuthToken: localStorage operation failed', err);
  58. }
  59. }
  60. export function getAuthToken(): string | null {
  61. return authToken;
  62. }
  63. // Query-param tokens for <img>/<video> src URLs, which can't carry an
  64. // Authorization header. There are two, and which one a URL takes is decided
  65. // by what the URL points at, not by convenience:
  66. //
  67. // streamToken — live camera only. Minting one costs camera:view.
  68. // mediaToken — thumbnails, previews, timelapses, covers, icons. Minted by
  69. // any signed-in user and carries their identity, so those
  70. // routes can apply the same ownership rules as everywhere else.
  71. //
  72. // Before #3025 the stream token served both, which meant a user could not see
  73. // a library thumbnail without also being granted the live feed of the room the
  74. // printer sits in — and, because a stream token names nobody, those routes had
  75. // no identity to scope by and served any row to any holder.
  76. let streamToken: string | null = null;
  77. let mediaToken: string | null = null;
  78. export function setStreamToken(token: string | null) {
  79. streamToken = token;
  80. }
  81. export function getStreamToken(): string | null {
  82. return streamToken;
  83. }
  84. export function setMediaToken(token: string | null) {
  85. mediaToken = token;
  86. }
  87. export function getMediaToken(): string | null {
  88. return mediaToken;
  89. }
  90. /** Append the camera stream token to a URL if available (live camera only). */
  91. export function withStreamToken(url: string): string {
  92. if (!streamToken) return url;
  93. const sep = url.includes('?') ? '&' : '?';
  94. return `${url}${sep}token=${encodeURIComponent(streamToken)}`;
  95. }
  96. /** Append the media token to a URL if available (for <img>/<video> src). */
  97. export function withMediaToken(url: string): string {
  98. if (!mediaToken) return url;
  99. const sep = url.includes('?') ? '&' : '?';
  100. return `${url}${sep}token=${encodeURIComponent(mediaToken)}`;
  101. }
  102. function parseContentDispositionFilename(header: string | null): string | null {
  103. if (!header) return null;
  104. // RFC 5987: filename*=utf-8''percent-encoded-name
  105. const rfc5987Match = header.match(/filename\*=(?:UTF-8|utf-8)''(.+?)(?:;|$)/);
  106. if (rfc5987Match) {
  107. try { return decodeURIComponent(rfc5987Match[1]); } catch { /* fall through */ }
  108. }
  109. // Standard: filename="name" or filename=name
  110. const standardMatch = header.match(/filename="?([^";\n]+)"?/);
  111. return standardMatch?.[1] || null;
  112. }
  113. function buildSlicerUrlFilename(filename: string): string {
  114. const safe = filename.replace(/[/\\?#]/g, '_');
  115. return safe.toLowerCase().endsWith('.3mf') ? safe : `${safe}.3mf`;
  116. }
  117. /** POST JSON and return the response body as a Blob (label PDFs and images). */
  118. async function postForBlob(endpoint: string, data: unknown, signal?: AbortSignal): Promise<Blob> {
  119. const headers: Record<string, string> = { 'Content-Type': 'application/json' };
  120. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  121. const response = await fetch(`${API_BASE}${endpoint}`, {
  122. method: 'POST',
  123. headers,
  124. body: JSON.stringify(data),
  125. signal,
  126. });
  127. if (!response.ok) {
  128. const error = await response.json().catch(() => ({}));
  129. throw new Error(typeof error.detail === 'string' ? error.detail : `HTTP ${response.status}`);
  130. }
  131. return response.blob();
  132. }
  133. async function request<T>(
  134. endpoint: string,
  135. options: RequestInit = {}
  136. ): Promise<T> {
  137. const headers: Record<string, string> = {
  138. 'Content-Type': 'application/json',
  139. ...options.headers as Record<string, string>,
  140. };
  141. // Add auth token if available
  142. if (authToken) {
  143. headers['Authorization'] = `Bearer ${authToken}`;
  144. }
  145. const response = await fetch(`${API_BASE}${endpoint}`, {
  146. ...options,
  147. cache: 'no-store', // Prevent browser caching of API responses
  148. credentials: 'include', // Required for HttpOnly cookies (e.g. 2fa_challenge)
  149. headers,
  150. });
  151. if (!response.ok) {
  152. const error = await response.json().catch(() => ({}));
  153. const detail = error.detail;
  154. let message: string;
  155. let code: string | null = null;
  156. if (typeof detail === 'string') {
  157. message = detail;
  158. } else if (Array.isArray(detail)) {
  159. // FastAPI 422 shape: each entry has `msg` like "Value error, <real msg>".
  160. // Strip the prefix and join. Fall back to raw JSON if every entry has an
  161. // empty msg (defensive — shouldn't happen with stock Pydantic, but the
  162. // previous fallback masked the real cause as a bare "HTTP 422" toast).
  163. const joined = detail
  164. .map((e: { msg?: string }) => (e.msg ?? '').replace(/^Value error,\s*/i, ''))
  165. .filter(Boolean)
  166. .join('; ');
  167. message = joined || JSON.stringify(detail) || `HTTP ${response.status}`;
  168. } else if (detail && typeof detail === 'object') {
  169. // Structured detail `{code, message, ...}` — frontend uses the code
  170. // to pick an i18n key, message is the English fallback, any extra
  171. // fields land on ApiError.detail (e.g. `deficit` for #1496).
  172. code = typeof detail.code === 'string' ? detail.code : null;
  173. message = typeof detail.message === 'string' ? detail.message : `HTTP ${response.status}`;
  174. } else {
  175. message = `HTTP ${response.status}`;
  176. }
  177. const structuredDetail = detail && typeof detail === 'object' && !Array.isArray(detail)
  178. ? (detail as Record<string, unknown>)
  179. : null;
  180. // Handle 401 Unauthorized - only clear token if it's actually invalid
  181. // Don't clear on "Authentication required" which might be a timing issue
  182. if (response.status === 401) {
  183. const invalidTokenMessages = [
  184. 'Could not validate credentials',
  185. 'Token has expired',
  186. 'User not found or inactive',
  187. 'Invalid API key',
  188. 'API key has expired',
  189. ];
  190. if (invalidTokenMessages.some(m => message.includes(m))) {
  191. setAuthToken(null);
  192. // Notify AuthContext so the protected route guard re-evaluates and
  193. // redirects to /login on the same tab — without this, AuthContext.user
  194. // stays cached and the tab silently fails every request until a manual
  195. // refresh remounts AuthProvider (#1698, reported by @TCL987).
  196. if (typeof window !== 'undefined') {
  197. window.dispatchEvent(new CustomEvent('auth:expired'));
  198. }
  199. }
  200. }
  201. throw new ApiError(message, response.status, code, structuredDetail);
  202. }
  203. // Handle empty responses (204 No Content, etc.)
  204. const contentLength = response.headers.get('content-length');
  205. if (response.status === 204 || contentLength === '0') {
  206. return undefined as T;
  207. }
  208. return await response.json();
  209. }
  210. /** Upload a CSV to the spool import endpoint (#1576). Multipart, so it bypasses
  211. * `request<T>()` (which sends JSON): the browser must set the form-data
  212. * boundary itself. `dryRun` toggles preview-only vs. real import. */
  213. async function uploadSpoolsCsv<T>(file: File, dryRun: boolean): Promise<T> {
  214. const form = new FormData();
  215. form.append('file', file);
  216. const headers: Record<string, string> = {};
  217. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  218. const response = await fetch(`${API_BASE}/inventory/spools/import${dryRun ? '?dry_run=true' : ''}`, {
  219. method: 'POST',
  220. headers,
  221. body: form,
  222. });
  223. if (!response.ok) {
  224. const error = await response.json().catch(() => ({}));
  225. // detail may be a plain string or a structured {code, message} object
  226. // (e.g. the 413 too-large response). Surface the human message either way.
  227. const detail = error?.detail;
  228. const message = typeof detail === 'string' ? detail : detail?.message;
  229. throw new Error(message || `HTTP ${response.status}`);
  230. }
  231. return response.json();
  232. }
  233. // Camera diagnostic result (#1395 follow-up). Returned by
  234. // POST /printers/{id}/camera/diagnose; the frontend modal renders one
  235. // row per stage and looks up the summary code in i18n for the user-
  236. // facing remediation hint.
  237. export interface CameraDiagnoseStage {
  238. name: 'tcp_reachable' | 'first_frame' | 'live_stream_active';
  239. status: 'ok' | 'failed' | 'skipped';
  240. duration_ms: number;
  241. code: string | null;
  242. }
  243. export interface CameraDiagnoseResult {
  244. printer_id: number;
  245. protocol: 'rtsp' | 'chamber_image';
  246. port: number;
  247. // 'default' = historical X1/H2 tuning. Anything else = this model has
  248. // an override entry in backend/app/services/camera_profiles.py.
  249. profile: string;
  250. overall_status: 'ok' | 'failed';
  251. stages: CameraDiagnoseStage[];
  252. // i18n key under `camera.diagnose.summary.*`.
  253. summary_code: string;
  254. }
  255. // Connection diagnostic (GET /printers/{id}/diagnostic and
  256. // POST /printers/diagnostic). Each check's `id` + `status` resolve a
  257. // localized title/fix under `diagnostic.check.*`; `params` interpolate it.
  258. export type DiagnosticStatus = 'pass' | 'fail' | 'warn' | 'skip';
  259. export interface DiagnosticCheck {
  260. id:
  261. | 'port_mqtt'
  262. | 'port_ftps'
  263. | 'port_rtsps'
  264. | 'network_mode'
  265. | 'subnet'
  266. | 'mqtt_auth'
  267. | 'developer_mode';
  268. status: DiagnosticStatus;
  269. params: Record<string, string | number>;
  270. }
  271. export interface PrinterDiagnosticResult {
  272. printer_id: number | null;
  273. ip_address: string;
  274. overall: 'ok' | 'warnings' | 'problems';
  275. checks: DiagnosticCheck[];
  276. }
  277. // --- Log-health scan: self-service triage on the System page + bug reporter.
  278. // The backend matches recent logs against a curated known-issue catalog;
  279. // human-readable cause/fix text is rendered from i18n keys keyed by signature_id.
  280. export type LogFindingSeverity = 'error' | 'warning';
  281. export type LogFindingCategory = 'layer8' | 'environment' | 'bug';
  282. export interface LogFinding {
  283. signature_id: string;
  284. severity: LogFindingSeverity;
  285. category: LogFindingCategory;
  286. wiki_anchor: string;
  287. count: number;
  288. first_seen: string;
  289. last_seen: string;
  290. sample: string;
  291. }
  292. export interface SystemHealthResult {
  293. findings: LogFinding[];
  294. scanned_entries: number;
  295. log_available: boolean;
  296. summary: {
  297. total: number;
  298. layer8: number;
  299. environment: number;
  300. bug: number;
  301. };
  302. }
  303. // Long-lived camera tokens (#1108). The `token` field is populated only on the
  304. // create response — listing endpoints set it to null because the plaintext
  305. // value is shown to the user exactly once.
  306. //
  307. // 'camera_stream' reaches the video endpoints only. 'camwall' additionally
  308. // reaches the read-only Cam Wall feed, which names the printers (#2531), so it
  309. // is a separate scope rather than a widening of tokens already in the wild.
  310. export type LongLivedTokenScope = 'camera_stream' | 'camwall' | 'overlay';
  311. export interface LongLivedCameraToken {
  312. id: number;
  313. user_id: number;
  314. name: string;
  315. scope: LongLivedTokenScope;
  316. lookup_prefix: string;
  317. created_at: string;
  318. expires_at: string;
  319. last_used_at: string | null;
  320. token: string | null;
  321. }
  322. // An external application that signs users in with their Bambuddy account.
  323. // `client_secret` is present only in the create / rotate responses.
  324. export interface ConnectedApp {
  325. id: number;
  326. name: string;
  327. client_id: string;
  328. redirect_uri: string;
  329. enabled: boolean;
  330. created_at: string;
  331. last_used_at: string | null;
  332. client_secret?: string;
  333. }
  334. export interface ConnectAuthorizeInfo {
  335. app_name: string;
  336. username: string;
  337. already_granted: boolean;
  338. }
  339. // One row of the token-authenticated Cam Wall feed (#2531). Deliberately
  340. // smaller than PrinterStatus: no serial, no IP, no print filename — a kiosk URL
  341. // is not a secret, so the payload behind it must not be either.
  342. export interface CamWallPrinter {
  343. id: number;
  344. name: string;
  345. camera_rotation: number;
  346. connected: boolean;
  347. state: string | null;
  348. progress: number | null;
  349. remaining_time: number | null;
  350. layer_num: number | null;
  351. total_layers: number | null;
  352. hms_errors: HMSError[];
  353. }
  354. // Streaming-overlay feed (#2613). The subset of print state the /overlay page
  355. // draws for one printer, served behind an `overlay`-scoped token so OBS embeds
  356. // with no login session can read it. Unlike CamWallPrinter this names the file
  357. // being printed (the overlay shows the part on screen).
  358. export interface OverlayStatus {
  359. id: number;
  360. name: string;
  361. model: string | null;
  362. camera_rotation: number;
  363. connected: boolean;
  364. state: string | null;
  365. current_print: string | null;
  366. gcode_file: string | null;
  367. progress: number | null;
  368. remaining_time: number | null;
  369. layer_num: number | null;
  370. total_layers: number | null;
  371. stg_cur_name: string | null;
  372. // Nozzle / bed / chamber readings for the overlay's temperature fields
  373. // (#1422). Only the keys a viewer is shown; chamber is absent on models
  374. // without a real sensor.
  375. temperatures: Record<string, number>;
  376. time_format: 'system' | '12h' | '24h';
  377. }
  378. // Printer types
  379. // Printer locations (groups) and their appearance (#2962). `id` is null for a
  380. // location only printers carry, with no row of its own yet.
  381. export interface PrinterLocation {
  382. id: number | null;
  383. name: string;
  384. icon: string | null;
  385. color: string | null;
  386. printer_count: number;
  387. }
  388. export interface PrinterLocationUpdate {
  389. name: string;
  390. new_name?: string;
  391. icon?: string | null;
  392. color?: string | null;
  393. }
  394. export interface WLEDPresets {
  395. idle: number | null;
  396. prepare: number | null;
  397. printing: number | null;
  398. paused: number | null;
  399. finished: number | null;
  400. error: number | null;
  401. queue_waiting: number | null;
  402. filament_problem: number | null;
  403. hms_error: number | null;
  404. offline: number | null;
  405. }
  406. export interface WLEDConfig {
  407. enabled: boolean;
  408. base_url: string | null;
  409. presets: WLEDPresets;
  410. finished_timeout_seconds: number | null;
  411. }
  412. export interface WLEDPreset {
  413. id: number;
  414. name: string;
  415. }
  416. export interface WLEDConnectionInfo {
  417. name: string | null;
  418. version: string | null;
  419. }
  420. export interface Printer {
  421. id: number;
  422. name: string;
  423. serial_number: string;
  424. ip_address: string;
  425. // Optional because the backend only returns access_code when the caller has
  426. // PRINTERS_UPDATE — Admin / Operator JWTs or auth-disabled mode. Viewers and
  427. // API keys receive a Printer without this field.
  428. access_code?: string;
  429. model: string | null;
  430. location: string | null; // Group/location name
  431. nozzle_count: number; // 1 or 2, auto-detected from MQTT
  432. // Model is sold with both Standard and High Flow nozzles, so a K-profile's
  433. // flow type is a real choice. Derived from the model, not the nozzle count —
  434. // only the A-series has a single variant.
  435. supports_nozzle_flow_type: boolean;
  436. is_active: boolean;
  437. auto_archive: boolean;
  438. external_camera_url: string | null;
  439. external_camera_type: string | null; // "mjpeg", "rtsp", "snapshot"
  440. external_camera_enabled: boolean;
  441. external_camera_snapshot_url: string | null; // optional single-frame override (#1177)
  442. camera_rotation: number; // 0, 90, 180, 270 degrees
  443. camera_light_auto: boolean; // picked for the chamber light when camera_light_mode is 'selected' (#1655)
  444. plate_detection_enabled: boolean; // Check plate before print
  445. plate_detection_roi?: PlateDetectionROI; // ROI for plate detection
  446. wear_cost_per_hour: number | null; // Wear cost per printing hour (#694)
  447. wled_config: WLEDConfig | null;
  448. created_at: string;
  449. updated_at: string;
  450. }
  451. export interface HMSError {
  452. code: string;
  453. attr: number; // Attribute value for constructing wiki URL
  454. module: number;
  455. // Bambu's alert level: 1 error (task stopped), 2 warning (task paused),
  456. // 3 notification, 0 invalid (#2728).
  457. severity: number;
  458. actions?: string[]; // List of user-facing action keys (e.g. "CHECK_FILAMENT")
  459. job_id?: string; // Optional job ID for actions that require it (e.g. "CHECK_ASSISTANT")
  460. // Canonical hex identifier the firmware matches against — 8 chars for
  461. // print_error-sourced faults, 16 chars for hms[]-array-sourced faults. Send
  462. // this back as HmsActionBody.print_error so we don't truncate the 64-bit
  463. // identifier into the silent-rejection short code (#1830).
  464. full_code?: string;
  465. // The backend's catalogue sentence for this fault (#2926), from the table
  466. // generated out of Bambu Studio for this printer model (#2728). English only.
  467. // Null when Bambu publishes no text for the code. The frontend has no table of
  468. // its own: this field decides both the text and whether the fault counts.
  469. description?: string | null;
  470. }
  471. export interface HMSActionBody {
  472. print_error: string; // HMS error code (e.g. "05000070")
  473. action: string; // "HMS action to execute (e.g. 'resume_after_error')"
  474. job_id: string | null; // Optional job ID for context (if applicable)
  475. }
  476. export interface AMSTray {
  477. id: number;
  478. tray_color: string | null;
  479. tray_type: string | null;
  480. tray_sub_brands: string | null; // Full name like "PLA Basic", "PETG HF"
  481. tray_id_name: string | null; // Bambu filament ID like "A00-Y2" (can decode to color)
  482. tray_info_idx: string | null; // Filament preset ID like "GFA00" - maps to cloud setting_id
  483. remain: number;
  484. k: number | null; // Pressure advance value (from tray or K-profile lookup)
  485. cali_idx: number | null; // Calibration index for K-profile lookup
  486. tag_uid: string | null; // RFID tag UID (any tag)
  487. tray_uuid: string | null; // Bambu Lab spool UUID (32-char hex, only valid for Bambu Lab spools)
  488. nozzle_temp_min: number | null; // Min nozzle temperature
  489. nozzle_temp_max: number | null; // Max nozzle temperature
  490. drying_temp: number | null; // RFID-recommended drying temp
  491. drying_time: number | null; // RFID-recommended drying time (hours)
  492. state: number | null; // AMS tray state: 9=empty, 10=spool present not loaded, 11=loaded
  493. exists?: boolean | null; // Firmware tray_exist_bits: spool physically present (non-RFID → "?" not "Empty", #2527)
  494. }
  495. export interface AMSUnit {
  496. id: number;
  497. humidity: number | null;
  498. temp: number | null;
  499. is_ams_ht: boolean; // True for AMS-HT (single spool), False for regular AMS (4 spools)
  500. tray: AMSTray[];
  501. serial_number: string; // AMS unit serial number (from MQTT sn field)
  502. sw_ver: string; // AMS firmware version (from get_version info.module ams/* entry)
  503. dry_time: number; // Minutes remaining (0 = not drying, >0 = drying active)
  504. dry_countdown_stalled?: boolean; // Timer set but countdown not ticking (never started or paused)
  505. dry_status: number; // 0=Off, 1=Checking, 2=Drying, 3=Cooling, 4=Stopping, 5=Error
  506. dry_sub_status: number; // 0=Off, 1=Heating, 2=Dehumidify
  507. dry_sf_reason: number[]; // Cannot-dry reasons (1=InsufficientPower, 8=NeedPluginPower)
  508. dry_target_temp: number | null; // Active-cycle target °C (Bambu does not echo)
  509. dry_filament: string | null; // Active-cycle filament name we sent
  510. module_type: string; // "ams", "ams_f1", "n3f", "n3s", "n10a" (H3C AMS 3H)
  511. ams_type?: number | null; // Bambu Studio's AMS type (utils/trayIds AmsType), 6 = AMS 3H
  512. // The AMS 3H dryer: its two slots (tray ids 0-8) and that zone's humidity (%) and temperature.
  513. dryer_slots?: number[];
  514. dryer_humidity?: number | null;
  515. dryer_temp?: number | null;
  516. }
  517. export interface ScheduledDrying {
  518. id: number;
  519. printer_id: number;
  520. ams_id: number;
  521. temp: number;
  522. duration_hours: number;
  523. filament: string;
  524. rotate_tray: boolean;
  525. start_after: string | null; // UTC ISO with Z suffix, like the queue routes
  526. status: string;
  527. waiting_reason: string | null;
  528. error_message: string | null;
  529. // Why a failed run failed (screen_only / unsupported / did_not_start); null on
  530. // rows that failed before codes existed, which show error_message instead.
  531. error_code?: string | null;
  532. created_at: string;
  533. started_at: string | null;
  534. completed_at: string | null;
  535. }
  536. export interface NozzleInfo {
  537. // Two vocabularies live in this field, by printer generation. Legacy
  538. // printers (X1/P1) report the nozzle MATERIAL -- "stainless_steel",
  539. // "hardened_steel". H2-series report a FLOW code -- "HH01" (high flow),
  540. // "HS01" (standard); measured on an H2D. utils/nozzleFlow reads only the
  541. // latter and treats anything else as "unknown", which is what makes the
  542. // material spelling harmless here.
  543. nozzle_type: string;
  544. nozzle_diameter: string; // e.g., "0.4"
  545. }
  546. export interface NozzleRackSlot {
  547. id: number;
  548. nozzle_type: string;
  549. nozzle_diameter: string;
  550. wear: number | null;
  551. stat: number | null; // Nozzle status (e.g. mounted/docked)
  552. max_temp: number;
  553. serial_number: string;
  554. filament_color: string; // RGBA hex ("00000000" = no filament)
  555. filament_id: string;
  556. filament_type: string; // Material type (e.g. "PLA", "PETG")
  557. addr_id?: number | null; // H3C: home rack position 0-8 (the mounted hotend reports id 0)
  558. }
  559. export interface PrintOptions {
  560. // Core AI detectors
  561. spaghetti_detector: boolean;
  562. print_halt: boolean;
  563. halt_print_sensitivity: string; // "low", "medium", "high" - spaghetti sensitivity
  564. first_layer_inspector: boolean;
  565. printing_monitor: boolean;
  566. buildplate_marker_detector: boolean;
  567. allow_skip_parts: boolean;
  568. // Additional AI detectors (decoded from cfg bitmask)
  569. nozzle_clumping_detector: boolean;
  570. nozzle_clumping_sensitivity: string; // "low", "medium", "high"
  571. pileup_detector: boolean;
  572. pileup_sensitivity: string; // "low", "medium", "high"
  573. airprint_detector: boolean;
  574. airprint_sensitivity: string; // "low", "medium", "high"
  575. auto_recovery_step_loss: boolean;
  576. filament_tangle_detect: boolean;
  577. }
  578. export interface FilaSwitchState {
  579. installed: boolean;
  580. // Raw wire arrays, ordered **In-B first, then In-A** (BambuStudio's SwitchPos
  581. // enum). in[] values are snow-encoded (bits 8-15 = AMS id, bits 0-7 = slot,
  582. // -1 = empty); out[] values are the extruder each *outlet* terminates at, or
  583. // 0xE when unset. Neither array says which inlet is currently routed to which
  584. // outlet — that pairing is not reported. For per-AMS side information use
  585. // PrinterStatus.ams_switch_inlet instead.
  586. in_slots: number[];
  587. out_extruders: number[];
  588. stat: number;
  589. info: number;
  590. // Whether every AMS is bound to one of the switch's two inlets. Until it is,
  591. // the switch cannot route a load anywhere and the printer has to be set up
  592. // first ("Manual AMS Setup" on its screen).
  593. ready: boolean;
  594. }
  595. // Which AMS slot one hotend is currently fed from. ams_id/slot_id are null when
  596. // the hotend holds nothing. Keyed by extruder id ('0' = right, '1' = left).
  597. // tray_now cannot answer this — it is one value for the whole printer, so on a
  598. // dual-nozzle machine it names only one of the two loaded hotends.
  599. export interface ExtruderSlot {
  600. ams_id: number | null;
  601. slot_id: number | null;
  602. has_filament: boolean;
  603. }
  604. // Which FTS inlet an AMS is plumbed into: 'A' | 'B'.
  605. export type FtsInlet = 'A' | 'B';
  606. // A video device the server can see, for a USB camera (GET /printers/usb-cameras).
  607. export interface UsbCamera {
  608. device: string;
  609. name: string;
  610. capabilities: string[];
  611. driver?: string;
  612. formats?: string[];
  613. }
  614. export interface PrinterStatus {
  615. id: number;
  616. name: string;
  617. connected: boolean;
  618. state: string | null;
  619. current_print: string | null;
  620. subtask_name: string | null;
  621. current_archive_id: number | null;
  622. current_plate_id: number | null;
  623. gcode_file: string | null;
  624. progress: number | null;
  625. remaining_time: number | null;
  626. layer_num: number | null;
  627. total_layers: number | null;
  628. temperatures: {
  629. bed?: number;
  630. bed_target?: number;
  631. bed_heating?: boolean; // Actual heater state from MQTT
  632. nozzle?: number;
  633. nozzle_target?: number;
  634. nozzle_heating?: boolean; // Actual heater state from MQTT
  635. nozzle_2?: number; // Second nozzle for H2 series (dual nozzle)
  636. nozzle_2_target?: number;
  637. nozzle_2_heating?: boolean; // Actual heater state from MQTT
  638. chamber?: number;
  639. chamber_target?: number;
  640. chamber_heating?: boolean; // Actual heater state from MQTT
  641. } | null;
  642. cover_url: string | null;
  643. hms_errors: HMSError[];
  644. // Live updates send null when no AMS is attached; the REST status sends [].
  645. ams: AMSUnit[] | null;
  646. ams_exists: boolean;
  647. vt_tray: AMSTray[]; // Virtual tray / external spool(s)
  648. store_to_sdcard: boolean; // Store sent files on SD card
  649. timelapse: boolean; // Timelapse recording active
  650. ipcam: boolean; // Live view enabled
  651. wifi_signal: number | null; // WiFi signal strength in dBm
  652. wired_network: boolean; // Ethernet connection detected
  653. door_open: boolean; // Enclosure door open (models with a door sensor: X1/X1C/X1E/X2D/P2S/H2*)
  654. // Indexed by EXTRUDER id: [0] is the right hotend, [1] the left. Measured
  655. // on an H2D with 0.4 left / 0.6 right. Read it through the helpers in
  656. // utils/amsHelpers rather than indexing it directly.
  657. nozzles: NozzleInfo[];
  658. nozzle_rack: NozzleRackSlot[]; // H2C 6-nozzle tool-changer rack
  659. print_options: PrintOptions | null; // AI detection and print options
  660. // Calibration stage tracking
  661. stg_cur: number; // Current stage number (-1 = not calibrating)
  662. stg_cur_name: string | null; // Human-readable current stage name
  663. stg: number[]; // List of stage numbers in calibration sequence
  664. // Air conditioning mode (0=cooling, 1=heating)
  665. airduct_mode: number;
  666. // Print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  667. speed_level: number;
  668. // Chamber light on/off
  669. chamber_light: boolean;
  670. // Active extruder for dual nozzle (0=right, 1=left)
  671. active_extruder: number;
  672. // AMS mapping - which AMS is connected to which nozzle
  673. // Format: [ams_id_for_nozzle0, ams_id_for_nozzle1, ...] where -1 means no AMS
  674. ams_mapping: number[];
  675. // Per-AMS extruder mapping - extracted from each AMS unit's info field
  676. // Format: {ams_id: extruder_id} where extruder 0=right, 1=left
  677. // Note: JSON keys are always strings
  678. ams_extruder_map: Record<string, number>;
  679. // Filament Track Switch accessory — null when not installed. When present,
  680. // AMS slots aren't tied to a specific extruder; the FTS routes any slot to
  681. // either extruder, so per-extruder slot filtering must be skipped.
  682. fila_switch: FilaSwitchState | null;
  683. // Per-AMS FTS inlet binding, {ams_id: 'A' | 'B'}, as set on the printer's
  684. // "Manual AMS Setup" screen. Empty unless a switch is installed. An AMS with
  685. // an entry here reaches BOTH nozzles through the switch, which is why it has
  686. // no ams_extruder_map entry and must not be badged left or right.
  687. ams_switch_inlet: Record<string, FtsInlet>;
  688. // Which AMS slot each hotend is fed from, keyed by extruder id as a string.
  689. // Empty on printers that don't report it (everything but the H2/X2 series).
  690. extruder_slots: Record<string, ExtruderSlot>;
  691. // Currently loaded tray (global tray ID, 255 = no filament loaded, 254 = external spool)
  692. tray_now: number;
  693. // The trays this print has drawn from, in order: [global tray ID, layer of the
  694. // switch]. A tray outside the job's AMS mapping is a backup spool the printer
  695. // switched to (AMS Filament Backup). Reset at the start of each print.
  696. tray_change_log?: [number, number][];
  697. // Runout / filament-replacement guidance (#2587). Populated only while PAUSED.
  698. // Global tray IDs (ams_id*4+slot, 28-36 = H3C AMS 3H, 128-135 = AMS-HT, 254 = external; utils/trayIds), matching
  699. // the same numbering as tray_now so the AMS graphic can highlight them.
  700. // expected_tray = the slot the firmware now expects filament in (null = idle,
  701. // not paused, or unresolvable → "check the printer").
  702. // previous_tray = the slot that ran out (null = unknown).
  703. expected_tray: number | null;
  704. previous_tray: number | null;
  705. // AMS status for filament change tracking (0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration)
  706. ams_status_main: number;
  707. // AMS sub-status for filament change step (when main=1): 4=retraction, 6=load verification, 7=purge
  708. ams_status_sub: number;
  709. // mc_print_sub_stage - filament change step indicator used by OrcaSlicer/BambuStudio
  710. mc_print_sub_stage: number;
  711. // Timestamp of last AMS data update (for RFID refresh detection)
  712. last_ams_update: number;
  713. // Number of printable objects in current print (for skip objects feature)
  714. printable_objects_count: number;
  715. // The next pause the slicer put into the running print (#2984). minutes is
  716. // null while the printer reports no time left yet.
  717. next_pause?: { layer: number; minutes: number | null } | null;
  718. // Fan speeds (0-100 percentage, null if not available for this model)
  719. cooling_fan_speed: number | null; // Part cooling fan
  720. big_fan1_speed: number | null; // Auxiliary fan
  721. big_fan2_speed: number | null; // Chamber/exhaust fan
  722. heatbreak_fan_speed: number | null; // Hotend heatbreak fan
  723. // Left auxiliary part cooling fan (optional P2S/X2D accessory, M106 P10).
  724. // null = not installed / not reported by this model.
  725. left_aux_fan_speed: number | null;
  726. // Chamber exhaust fan present (P2S/X2D External Exhaust Fan kit, airduct part 3).
  727. exhaust_fan_present: boolean;
  728. firmware_version: string | null; // Firmware version from MQTT
  729. // Developer LAN mode: true = enabled, false = disabled, null = unknown
  730. developer_mode: boolean | null;
  731. // AMS Filament Backup ("auto-switch" to a backup spool when one runs out).
  732. // true = ON, false = OFF, null = unknown / unsupported (A1 family).
  733. ams_filament_backup: boolean | null;
  734. // Queue: printer is awaiting user ack that the build plate was cleared after a
  735. // finished/failed print. Persisted across restarts (#961).
  736. awaiting_plate_clear: boolean;
  737. // AMS drying support
  738. supports_drying: boolean;
  739. // The AMS can dry, but only from the printer's own screen (P1 series, #2533).
  740. drying_screen_only?: boolean;
  741. // Active chamber heater (responds to M141). True only for H2C/H2D/H2DPro/H2S/X2D.
  742. supports_chamber_heater?: boolean;
  743. }
  744. export interface PrinterCreate {
  745. name: string;
  746. serial_number: string;
  747. ip_address: string;
  748. access_code: string;
  749. model?: string;
  750. location?: string | null;
  751. auto_archive?: boolean;
  752. // Maintenance Mode flag (#1476). Backend already gates MQTT, queue dispatch,
  753. // scheduler, metrics and the print picker on this; toggling via PATCH
  754. // /printers/{id} disconnects or reconnects MQTT accordingly.
  755. is_active?: boolean;
  756. external_camera_url?: string | null;
  757. external_camera_type?: string | null;
  758. external_camera_enabled?: boolean;
  759. external_camera_snapshot_url?: string | null;
  760. camera_rotation?: number;
  761. camera_light_auto?: boolean;
  762. plate_detection_enabled?: boolean;
  763. plate_detection_roi?: PlateDetectionROI;
  764. wear_cost_per_hour?: number | null;
  765. wled_config?: WLEDConfig | null;
  766. }
  767. // Plate Detection
  768. export interface PlateDetectionROI {
  769. x: number; // X start % (0.0-1.0)
  770. y: number; // Y start % (0.0-1.0)
  771. w: number; // Width % (0.0-1.0)
  772. h: number; // Height % (0.0-1.0)
  773. }
  774. export interface PlateDetectionResult {
  775. is_empty: boolean;
  776. confidence: number;
  777. difference_percent: number;
  778. message: string;
  779. has_debug_image: boolean;
  780. debug_image_url?: string;
  781. needs_calibration: boolean;
  782. light_warning?: boolean;
  783. reference_count?: number;
  784. max_references?: number;
  785. roi?: PlateDetectionROI;
  786. }
  787. export interface PlateDetectionStatus {
  788. available: boolean;
  789. calibrated: boolean;
  790. reference_count: number;
  791. max_references: number;
  792. message: string;
  793. }
  794. export interface CalibrationResult {
  795. success: boolean;
  796. message: string;
  797. }
  798. export interface PlateReference {
  799. index: number;
  800. label: string;
  801. timestamp: string;
  802. has_image: boolean;
  803. thumbnail_url: string;
  804. }
  805. // Archive types
  806. export interface ArchiveDuplicate {
  807. id: number;
  808. print_name: string | null;
  809. created_at: string;
  810. match_type: 'exact' | 'similar'; // 'exact' = hash match, 'similar' = name match
  811. }
  812. export interface ArchivePrinterMediaFile {
  813. name: string;
  814. path: string;
  815. size: number;
  816. mtime: string | null;
  817. kind: 'timelapse' | 'ipcam';
  818. }
  819. export interface ArchivePrinterMedia {
  820. archive_id: number;
  821. printer_id: number | null;
  822. local_timelapse: { name: string; size: number } | null;
  823. remote_files: ArchivePrinterMediaFile[];
  824. warnings: Array<'printer_missing' | 'timelapse_unavailable' | 'ipcam_unavailable' | 'printer_files_forbidden'>;
  825. }
  826. /** A timelapse editor re-encode, run in the background. */
  827. export interface TimelapseJob {
  828. status: 'running' | 'completed' | 'failed' | 'cancelled';
  829. /** Share done, 0 to 1; null before ffmpeg's first report. */
  830. progress: number | null;
  831. output_path: string | null;
  832. message: string | null;
  833. error: string | null;
  834. }
  835. /** How a post-print outcome verdict reached the archive (#1898). */
  836. export type VerdictSource = 'dialog' | 'link' | 'plate_clear' | 'printer_card' | 'api' | 'reaction';
  837. export interface Archive {
  838. id: number;
  839. printer_id: number | null;
  840. project_id: number | null;
  841. project_name: string | null;
  842. filename: string;
  843. file_path: string;
  844. file_size: number;
  845. content_hash: string | null;
  846. thumbnail_path: string | null;
  847. timelapse_path: string | null;
  848. source_3mf_path: string | null;
  849. f3d_path: string | null;
  850. duplicates: ArchiveDuplicate[] | null;
  851. duplicate_count: number;
  852. duplicate_sequence: number; // 0 = original, 1+ = nth duplicate
  853. original_archive_id: number | null; // ID of the first/original archive
  854. object_count: number | null;
  855. print_name: string | null;
  856. plate_id: number | null; // Selected plate of a multi-plate 3MF (#2603)
  857. print_time_seconds: number | null;
  858. actual_time_seconds: number | null; // Computed from started_at/completed_at
  859. time_accuracy: number | null; // Percentage: 100 = perfect, >100 = faster than estimated
  860. time_estimate_seconds?: number | null; // The latest print's plate estimate, what time_accuracy compares with
  861. filament_used_grams: number | null;
  862. filament_type: string | null;
  863. filament_color: string | null;
  864. layer_height: number | null;
  865. total_layers: number | null;
  866. nozzle_diameter: number | null;
  867. bed_temperature: number | null;
  868. bed_type: string | null; // Build plate type from 3MF (e.g. "Cool Plate", "Textured PEI Plate")
  869. nozzle_temperature: number | null;
  870. sliced_for_model: string | null; // Printer model this file was sliced for
  871. status: string;
  872. started_at: string | null;
  873. completed_at: string | null;
  874. extra_data: Record<string, unknown> | null;
  875. makerworld_url: string | null;
  876. designer: string | null;
  877. external_url: string | null;
  878. is_favorite: boolean;
  879. tags: string | null;
  880. notes: string | null;
  881. cost: number | null;
  882. photos: string[] | null;
  883. failure_reason: string | null;
  884. // Post-print outcome confirmation (#1898)
  885. user_verdict: 'good' | 'reject' | null;
  886. // How the verdict arrived; 'reaction' is written by the Telegram reaction
  887. // handler (#3046) and is labelled here so it reads correctly once that lands.
  888. user_verdict_source: VerdictSource | null;
  889. user_verdict_at: string | null;
  890. confirm_requested: boolean;
  891. // The run whose outcome this shows, when it shows one run of the archive
  892. // (a plate printed on its own) rather than its latest (#1898).
  893. run_id?: number | null;
  894. // The latest print of the archive (among those the caller may see), whose
  895. // figures the per-print fields show (archive redesign).
  896. latest_run_id?: number | null;
  897. // How many videos its prints have; timelapse_path is the latest print's only.
  898. timelapse_count?: number;
  899. quantity: number;
  900. energy_kwh: number | null;
  901. energy_cost: number | null;
  902. wear_cost: number | null; // Printer wear (#694)
  903. created_at: string;
  904. // User tracking (Issue #206)
  905. created_by_id: number | null;
  906. created_by_username: string | null;
  907. // Per-archive run aggregates from PrintLogEntry (#1378)
  908. run_count: number;
  909. last_run_at: string | null;
  910. total_filament_actual_grams: number | null;
  911. successful_run_count: number;
  912. failed_run_count: number;
  913. }
  914. export interface ArchiveSlim {
  915. printer_id: number | null;
  916. print_name: string | null;
  917. print_time_seconds: number | null;
  918. actual_time_seconds: number | null;
  919. filament_used_grams: number | null;
  920. filament_type: string | null;
  921. filament_color: string | null;
  922. status: string;
  923. started_at: string | null;
  924. completed_at: string | null;
  925. cost: number | null;
  926. energy_kwh: number | null;
  927. energy_cost: number | null;
  928. wear_cost: number | null; // Printer wear (#694)
  929. quantity: number;
  930. created_at: string;
  931. }
  932. export interface PrintLogEntry {
  933. id: number;
  934. archive_id: number | null;
  935. print_name: string | null;
  936. plate_id?: number | null;
  937. printer_name: string | null;
  938. printer_id: number | null;
  939. status: string;
  940. started_at: string | null;
  941. completed_at: string | null;
  942. duration_seconds: number | null;
  943. filament_type: string | null;
  944. filament_color: string | null;
  945. filament_used_grams: number | null;
  946. cost: number | null;
  947. energy_kwh: number | null;
  948. energy_cost: number | null;
  949. wear_cost: number | null; // Printer wear (#694)
  950. failure_reason: string | null;
  951. user_verdict?: 'good' | 'reject' | null;
  952. user_verdict_source?: string | null;
  953. confirm_requested?: boolean | null;
  954. duration_unmeasured?: boolean | null;
  955. quantity?: number | null;
  956. // This print's own (archive redesign): note, finish photos, video.
  957. notes?: string | null;
  958. photos?: string[] | null;
  959. timelapse_path?: string | null;
  960. // The slicer's estimate for the plate it printed; in an archive's runs list.
  961. estimate_seconds?: number | null;
  962. estimate_grams?: number | null;
  963. thumbnail_path: string | null;
  964. created_by_id: number | null;
  965. created_by_username: string | null;
  966. created_at: string;
  967. }
  968. export interface PrintLogResponse {
  969. items: PrintLogEntry[];
  970. total: number;
  971. // The print log only: archives of its prints that were deleted.
  972. deleted_archive_ids?: number[];
  973. }
  974. export interface ArchiveStats {
  975. total_prints: number;
  976. successful_prints: number;
  977. failed_prints: number;
  978. cancelled_prints: number;
  979. total_print_time_hours: number;
  980. total_filament_grams: number;
  981. total_cost: number;
  982. prints_by_filament_type: Record<string, number>;
  983. prints_by_printer: Record<string, number>;
  984. // Name each printer id was last recorded under in the print log, so history
  985. // belonging to a deleted printer keeps its label.
  986. printer_names?: Record<string, string>;
  987. average_time_accuracy: number | null;
  988. time_accuracy_by_printer: Record<string, number> | null;
  989. total_energy_kwh: number;
  990. total_energy_cost: number;
  991. total_wear_cost: number; // Printer wear (#694)
  992. // True when a date-filtered total-consumption query is running on incomplete
  993. // snapshot history (e.g. right after upgrade, before hourly snapshots have
  994. // a baseline). UI should explain why the number may undercount.
  995. energy_data_warming_up?: boolean;
  996. }
  997. export interface TagInfo {
  998. name: string;
  999. count: number;
  1000. }
  1001. export interface FailureAnalysis {
  1002. period_days: number;
  1003. total_prints: number;
  1004. failed_prints: number;
  1005. failure_rate: number;
  1006. // Quality dimension (#1898): completed prints the user rejected. Optional
  1007. // so a frontend build against an older backend degrades gracefully.
  1008. rejected_prints?: number;
  1009. yield_rate?: number;
  1010. rejects_by_reason?: Record<string, number>;
  1011. failures_by_reason: Record<string, number>;
  1012. failures_by_filament: Record<string, number>;
  1013. failures_by_printer: Record<string, number>;
  1014. failures_by_hour: Record<number, number>;
  1015. recent_failures: Array<{
  1016. id: number;
  1017. print_name: string;
  1018. failure_reason: string | null;
  1019. filament_type: string | null;
  1020. printer_id: number | null;
  1021. created_at: string | null;
  1022. }>;
  1023. trend: Array<{
  1024. week_start: string;
  1025. total_prints: number;
  1026. failed_prints: number;
  1027. failure_rate: number;
  1028. }>;
  1029. }
  1030. /**
  1031. * Send the browser's zone with calendar dates: the server reads a date as a
  1032. * day in it, else in its own TZ, which shifted every day for a browser away
  1033. * from the server (DB-C12). Only when a date is set.
  1034. */
  1035. function addDayZone(params: URLSearchParams): void {
  1036. if (!params.has('date_from') && !params.has('date_to')) return;
  1037. try {
  1038. const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
  1039. if (zone) params.set('tz', zone);
  1040. } catch {
  1041. // No Intl zone: the server's TZ applies.
  1042. }
  1043. }
  1044. export interface BulkUploadResult {
  1045. uploaded: number;
  1046. failed: number;
  1047. /** `index` is the file's position in the request. */
  1048. results: Array<{ index: number; filename: string; id: number; status: string }>;
  1049. errors: Array<{ index: number; filename: string; error: string }>;
  1050. }
  1051. // Archive Comparison types
  1052. export interface ComparisonArchiveInfo {
  1053. id: number;
  1054. print_name: string;
  1055. status: string;
  1056. created_at: string | null;
  1057. printer_id: number | null;
  1058. project_name: string | null;
  1059. }
  1060. export interface ComparisonField {
  1061. field: string;
  1062. label: string;
  1063. unit: string | null;
  1064. values: (string | number | null)[];
  1065. raw_values: (string | number | null)[];
  1066. has_difference: boolean;
  1067. }
  1068. export interface SuccessCorrelationInsight {
  1069. field: string;
  1070. label: string;
  1071. insight: string;
  1072. success_avg?: number;
  1073. failed_avg?: number;
  1074. success_values?: string[];
  1075. failed_values?: string[];
  1076. }
  1077. export interface SuccessCorrelation {
  1078. has_both_outcomes: boolean;
  1079. message?: string;
  1080. successful_count?: number;
  1081. failed_count?: number;
  1082. insights?: SuccessCorrelationInsight[];
  1083. }
  1084. export interface ArchiveComparison {
  1085. archives: ComparisonArchiveInfo[];
  1086. comparison: ComparisonField[];
  1087. differences: ComparisonField[];
  1088. success_correlation: SuccessCorrelation;
  1089. }
  1090. // Project types
  1091. export interface ProjectStats {
  1092. total_archives: number;
  1093. total_items: number; // Sum of quantities (total items printed)
  1094. completed_prints: number; // Sum of quantities for completed prints (parts)
  1095. failed_prints: number;
  1096. queued_prints: number;
  1097. in_progress_prints: number;
  1098. total_print_time_hours: number;
  1099. total_filament_grams: number;
  1100. progress_percent: number | null; // Plates progress (total_archives / target_count)
  1101. parts_progress_percent: number | null; // Parts progress (completed_prints / target_parts_count)
  1102. estimated_cost: number;
  1103. total_energy_kwh: number;
  1104. total_energy_cost: number;
  1105. total_wear_cost: number; // Printer wear (#694)
  1106. remaining_prints: number | null; // Remaining plates
  1107. remaining_parts: number | null; // Remaining parts
  1108. bom_total_items: number;
  1109. bom_completed_items: number;
  1110. bom_cost: number;
  1111. }
  1112. // A sub-project as listed on its parent's page. The figures cover the child's
  1113. // own subtree, so the listed rows add up to the parent's roll-up minus the
  1114. // parent's own prints (#1264).
  1115. export interface ProjectChildPreview {
  1116. id: number;
  1117. name: string;
  1118. color: string | null;
  1119. status: string;
  1120. progress_percent: number | null;
  1121. descendant_count: number;
  1122. total_archives: number;
  1123. completed_prints: number;
  1124. total_print_time_hours: number;
  1125. total_filament_grams: number;
  1126. total_cost: number; // Filament + energy + BOM, matching the parent's cost card
  1127. }
  1128. export interface Project {
  1129. id: number;
  1130. name: string;
  1131. description: string | null;
  1132. color: string | null;
  1133. status: string; // active, completed, archived
  1134. target_count: number | null; // Target number of plates/print jobs
  1135. target_parts_count: number | null; // Target number of parts/objects
  1136. target_sets: number | null; // Copies-per-file target (#1897)
  1137. notes: string | null;
  1138. attachments: ProjectAttachment[] | null;
  1139. tags: string | null;
  1140. due_date: string | null;
  1141. priority: string; // low, normal, high, urgent
  1142. budget: number | null;
  1143. is_template: boolean;
  1144. template_source_id: number | null;
  1145. parent_id: number | null;
  1146. parent_name: string | null;
  1147. children: ProjectChildPreview[];
  1148. descendant_count: number; // Sub-projects at any depth beneath this one (#1264)
  1149. created_at: string;
  1150. updated_at: string;
  1151. stats?: ProjectStats;
  1152. // This project's numbers combined with every sub-project's. Null when there
  1153. // are none, since it would only repeat `stats` (#1264).
  1154. rollup_stats?: ProjectStats | null;
  1155. url: string | null; // External link rendered next to project name on the card (#1155)
  1156. cover_image_filename: string | null; // Filename within project attachments dir (#1155)
  1157. }
  1158. export interface ProjectAttachment {
  1159. filename: string;
  1160. original_name: string;
  1161. size: number;
  1162. uploaded_at: string;
  1163. }
  1164. // Completed-run count for one library file inside a project (#1897)
  1165. export interface ProjectFileProgress {
  1166. file_id: number;
  1167. completed_count: number;
  1168. }
  1169. export interface ArchivePreview {
  1170. id: number;
  1171. print_name: string | null;
  1172. thumbnail_path: string | null;
  1173. status: string;
  1174. filament_type: string | null;
  1175. filament_color: string | null;
  1176. }
  1177. export interface ProjectListItem {
  1178. id: number;
  1179. name: string;
  1180. description: string | null;
  1181. color: string | null;
  1182. status: string;
  1183. target_count: number | null; // Target number of plates/print jobs
  1184. target_parts_count: number | null; // Target number of parts/objects
  1185. target_sets: number | null; // #1897 — the shared edit dialog seeds itself from this
  1186. budget: number | null;
  1187. tags: string | null; // #2536 — the shared edit dialog seeds itself from this
  1188. due_date: string | null; // #2536
  1189. priority: string; // #2536
  1190. created_at: string;
  1191. archive_count: number; // Number of print jobs (plates)
  1192. total_items: number; // Sum of quantities (total items printed, including failed)
  1193. completed_count: number; // Sum of quantities for completed prints only (parts)
  1194. failed_count: number; // Sum of quantities for failed prints
  1195. queue_count: number;
  1196. progress_percent: number | null; // Plates progress
  1197. parent_id: number | null; // #1264 — set when this is a sub-project
  1198. child_count: number; // #1264 — direct sub-projects only
  1199. archives: ArchivePreview[];
  1200. url: string | null; // #1155
  1201. cover_image_filename: string | null; // #1155
  1202. }
  1203. export interface ProjectCreate {
  1204. name: string;
  1205. description?: string;
  1206. color?: string;
  1207. target_count?: number;
  1208. target_parts_count?: number;
  1209. target_sets?: number;
  1210. notes?: string;
  1211. tags?: string;
  1212. due_date?: string;
  1213. priority?: string;
  1214. budget?: number | null;
  1215. parent_id?: number;
  1216. url?: string | null; // #1155
  1217. }
  1218. export interface ProjectUpdate {
  1219. name?: string;
  1220. description?: string;
  1221. color?: string;
  1222. status?: string;
  1223. target_count?: number;
  1224. target_parts_count?: number;
  1225. target_sets?: number | null; // #1897 — explicit null clears the copies-per-file target
  1226. notes?: string;
  1227. tags?: string | null; // #2536 — explicit null clears the tags
  1228. due_date?: string | null; // #2536 — explicit null clears the due date
  1229. priority?: string;
  1230. budget?: number | null;
  1231. parent_id?: number;
  1232. url?: string | null; // #1155 — explicit null clears the URL
  1233. }
  1234. // BOM Types - Tracks sourced/purchased parts (hardware, electronics, etc.)
  1235. export interface BOMItem {
  1236. id: number;
  1237. project_id: number;
  1238. name: string;
  1239. quantity_needed: number;
  1240. quantity_acquired: number;
  1241. unit_price: number | null;
  1242. sourcing_url: string | null;
  1243. archive_id: number | null;
  1244. archive_name: string | null;
  1245. stl_filename: string | null;
  1246. remarks: string | null;
  1247. sort_order: number;
  1248. is_complete: boolean;
  1249. created_at: string;
  1250. updated_at: string;
  1251. }
  1252. export interface BOMItemCreate {
  1253. name: string;
  1254. quantity_needed?: number;
  1255. unit_price?: number;
  1256. sourcing_url?: string;
  1257. archive_id?: number;
  1258. stl_filename?: string;
  1259. remarks?: string;
  1260. }
  1261. export interface BOMItemUpdate {
  1262. name?: string;
  1263. quantity_needed?: number;
  1264. quantity_acquired?: number;
  1265. unit_price?: number;
  1266. sourcing_url?: string;
  1267. archive_id?: number;
  1268. stl_filename?: string;
  1269. remarks?: string;
  1270. }
  1271. // Project Export/Import Types
  1272. export interface BOMItemExport {
  1273. name: string;
  1274. quantity_needed: number;
  1275. quantity_acquired: number;
  1276. unit_price: number | null;
  1277. sourcing_url: string | null;
  1278. stl_filename: string | null;
  1279. remarks: string | null;
  1280. }
  1281. export interface LinkedFolderExport {
  1282. name: string;
  1283. }
  1284. export interface ProjectExport {
  1285. name: string;
  1286. description: string | null;
  1287. color: string | null;
  1288. status: string;
  1289. target_count: number | null;
  1290. target_parts_count: number | null;
  1291. target_sets: number | null; // #1897
  1292. notes: string | null;
  1293. tags: string | null;
  1294. due_date: string | null;
  1295. priority: string;
  1296. budget: number | null;
  1297. bom_items: BOMItemExport[];
  1298. linked_folders: LinkedFolderExport[];
  1299. }
  1300. export interface ProjectImport {
  1301. name: string;
  1302. description?: string;
  1303. color?: string;
  1304. status?: string;
  1305. target_count?: number;
  1306. target_parts_count?: number;
  1307. target_sets?: number; // #1897
  1308. notes?: string;
  1309. tags?: string;
  1310. due_date?: string;
  1311. priority?: string;
  1312. budget?: number | null;
  1313. bom_items?: BOMItemExport[];
  1314. linked_folders?: LinkedFolderExport[];
  1315. }
  1316. // Timeline Types
  1317. export interface TimelineEvent {
  1318. event_type: string;
  1319. timestamp: string;
  1320. title: string;
  1321. description: string | null;
  1322. metadata: Record<string, unknown> | null;
  1323. }
  1324. // API Key types
  1325. export interface APIKey {
  1326. id: number;
  1327. name: string;
  1328. key_prefix: string;
  1329. user_id: number | null; // Owner; null on legacy keys created before per-user ownership (#1182)
  1330. can_queue: boolean;
  1331. can_control_printer: boolean;
  1332. can_read_status: boolean;
  1333. can_manage_library: boolean;
  1334. can_manage_inventory: boolean;
  1335. can_manage_maintenance: boolean;
  1336. can_manage_archives: boolean;
  1337. can_manage_projects: boolean;
  1338. can_access_cloud: boolean;
  1339. can_update_energy_cost: boolean;
  1340. can_send_notifications: boolean;
  1341. printer_ids: number[] | null;
  1342. enabled: boolean;
  1343. last_used: string | null;
  1344. created_at: string;
  1345. expires_at: string | null;
  1346. }
  1347. export interface APIKeyCreate {
  1348. name: string;
  1349. can_queue?: boolean;
  1350. can_control_printer?: boolean;
  1351. can_read_status?: boolean;
  1352. can_manage_library?: boolean;
  1353. can_manage_inventory?: boolean;
  1354. can_manage_maintenance?: boolean;
  1355. can_manage_archives?: boolean;
  1356. can_manage_projects?: boolean;
  1357. can_access_cloud?: boolean;
  1358. can_update_energy_cost?: boolean;
  1359. can_send_notifications?: boolean;
  1360. printer_ids?: number[] | null;
  1361. expires_at?: string | null;
  1362. }
  1363. export interface APIKeyCreateResponse extends APIKey {
  1364. key: string; // Full key, only shown on creation
  1365. }
  1366. /**
  1367. * Tri-state calibration option (BambuStudio parity): "off" never runs it,
  1368. * "on" forces it every print, "auto" lets the printer skip it if it was done
  1369. * recently. Used by bed_levelling, flow_cali, and nozzle_offset_cali.
  1370. */
  1371. export type CalibrationMode = 'off' | 'on' | 'auto';
  1372. // Settings types
  1373. export interface AppSettings {
  1374. auto_archive: boolean;
  1375. save_thumbnails: boolean;
  1376. capture_finish_photo: boolean;
  1377. finish_photo_restore_plate: boolean;
  1378. default_filament_cost: number;
  1379. currency: string;
  1380. energy_cost_per_kwh: number;
  1381. energy_tracking_mode: 'print' | 'total';
  1382. // Where the electricity price comes from (#1251). With 'homeassistant',
  1383. // energy_cost_per_kwh holds the sensor's last reading and is read-only.
  1384. energy_price_source: 'fixed' | 'homeassistant';
  1385. energy_price_ha_entity: string;
  1386. check_updates: boolean;
  1387. check_printer_firmware: boolean;
  1388. include_beta_updates: boolean;
  1389. // Announcements from the Bambuddy maintainers (a signed file on GitHub).
  1390. announcements_enabled?: boolean;
  1391. announcements_all_users?: boolean;
  1392. // #1589: false hides the local username/password form on the login page;
  1393. // BAMBUDDY_LOCAL_LOGIN=true on the server flips the reported value back to
  1394. // true so the env-var recovery path is visible to the SPA.
  1395. local_login_enabled: boolean;
  1396. language: string;
  1397. notification_language: string;
  1398. // AMS threshold settings
  1399. ams_humidity_good: number; // <= this is green
  1400. ams_humidity_fair: number; // <= this is orange, > is red
  1401. ams_temp_good: number; // <= this is green/blue
  1402. ams_temp_fair: number; // <= this is orange, > is red
  1403. // Separate from the display band (#2905). null = unset, which the backend
  1404. // resolves to ams_temp_fair so existing installs are unaffected.
  1405. ams_temp_alarm: number | null;
  1406. ams_history_retention_days: number; // days to keep AMS sensor history
  1407. printer_sensor_history_retention_days?: number; // days to keep printer heater history
  1408. // Queue auto-drying settings
  1409. queue_drying_enabled: boolean; // Auto-dry AMS between queued prints
  1410. queue_drying_block: boolean; // Block queue until drying completes
  1411. ambient_drying_enabled: boolean; // Auto-dry idle printers based on humidity regardless of queue
  1412. ambient_drying_sustained_minutes: number; // Minutes humidity must stay above threshold before ambient auto-dry starts (0 = instant)
  1413. print_drying_enabled: boolean; // Continue drying while a print is running on capable hardware
  1414. drying_presets: string; // JSON blob of drying presets per filament type
  1415. ams_humidity_thresholds: string; // JSON blob of per-filament humidity thresholds (#1605)
  1416. gcode_snippets: string; // JSON: per-model G-code injection snippets
  1417. // Scheduled local backup
  1418. local_backup_enabled: boolean;
  1419. local_backup_schedule: string;
  1420. local_backup_time: string;
  1421. local_backup_retention: number;
  1422. local_backup_path: string;
  1423. // Print modal settings
  1424. per_printer_mapping_expanded: boolean; // Whether custom mapping is expanded by default in print modal
  1425. // Date/time format settings
  1426. date_format: 'system' | 'us' | 'eu' | 'iso';
  1427. time_format: 'system' | '12h' | '24h';
  1428. // Filament tracking
  1429. disable_filament_warnings: boolean; // Disable filament warnings (print insufficiency and assignment mismatch)
  1430. prefer_lowest_filament: boolean; // When multiple spools match, prefer lowest remaining filament
  1431. 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
  1432. 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
  1433. spoolman_url: string;
  1434. // Default printer
  1435. default_printer_id: number | null;
  1436. pipeline_max_copies: number;
  1437. // Dark mode theme settings
  1438. dark_style: 'classic' | 'glow' | 'vibrant';
  1439. dark_background: 'neutral' | 'warm' | 'cool' | 'oled' | 'slate' | 'forest';
  1440. dark_accent: 'green' | 'teal' | 'blue' | 'orange' | 'purple' | 'red';
  1441. // Light mode theme settings
  1442. light_style: 'classic' | 'glow' | 'vibrant';
  1443. light_background: 'neutral' | 'warm' | 'cool';
  1444. light_accent: 'green' | 'teal' | 'blue' | 'orange' | 'purple' | 'red';
  1445. // FTP retry settings
  1446. ftp_retry_enabled: boolean;
  1447. ftp_retry_count: number;
  1448. ftp_retry_delay: number;
  1449. ftp_timeout: number;
  1450. // MQTT relay settings
  1451. mqtt_enabled: boolean;
  1452. mqtt_broker: string;
  1453. mqtt_port: number;
  1454. mqtt_username: string;
  1455. mqtt_password: string;
  1456. mqtt_topic_prefix: string;
  1457. mqtt_use_tls: boolean;
  1458. // External URL for notifications
  1459. external_url: string;
  1460. // Directory holding docker-compose.yml, shown in the update instructions (#2664)
  1461. docker_compose_dir: string;
  1462. // Home Assistant integration
  1463. ha_enabled: boolean;
  1464. ha_url: string;
  1465. ha_token: string;
  1466. ha_url_from_env: boolean;
  1467. ha_token_from_env: boolean;
  1468. ha_env_managed: boolean;
  1469. // File Manager / Library settings
  1470. library_disk_warning_gb: number;
  1471. // Camera view settings
  1472. camera_view_mode: 'window' | 'embedded';
  1473. // Chamber light while the camera is in use (#1655)
  1474. camera_light_mode: 'off' | 'all' | 'selected';
  1475. camera_light_delay: number; // seconds a snapshot waits after the light came on
  1476. // Preferred slicer (server-side API / sidecar)
  1477. preferred_slicer: 'bambu_studio' | 'orcaslicer';
  1478. // Desktop "Open in Slicer" override (#1329). Null inherits from
  1479. // preferred_slicer so existing installs behave identically.
  1480. open_in_slicer: 'bambu_studio' | 'orcaslicer' | null;
  1481. // Where slicing runs, independent of which slicer binary the sidecar drives.
  1482. // Only 'sidecar' is implemented today; see lib/sliceEngines.ts.
  1483. slice_engine: 'sidecar' | 'browser';
  1484. // Use the slicer-API sidecar for slicing (in-app modal) vs desktop URI scheme
  1485. use_slicer_api: boolean;
  1486. // Per-install sidecar URLs. Empty string falls back to the env defaults.
  1487. orcaslicer_api_url: string;
  1488. bambu_studio_api_url: string;
  1489. // Minutes of silence from the sidecar before a slice is abandoned. Bounds
  1490. // stalls, not total slicing time — a model that keeps reporting progress
  1491. // runs to completion however long it takes.
  1492. slicer_stall_timeout_minutes: number;
  1493. // Prometheus metrics
  1494. prometheus_enabled: boolean;
  1495. prometheus_token: string;
  1496. // Bed cooled threshold
  1497. bed_cooled_threshold: number;
  1498. // Minutes before a slicer pause to send the pause heads-up (#2984)
  1499. pause_warning_minutes: number;
  1500. // Inventory low stock threshold
  1501. low_stock_threshold: number;
  1502. // Session policy (#1706) — admin-set ceiling, hours, [1, 720]
  1503. session_max_hours: number;
  1504. // User email notifications toggle
  1505. user_notifications_enabled: boolean;
  1506. // Default print options
  1507. default_bed_levelling: CalibrationMode;
  1508. default_flow_cali: CalibrationMode;
  1509. default_vibration_cali: boolean;
  1510. default_layer_inspect: boolean;
  1511. default_timelapse: boolean;
  1512. default_nozzle_offset_cali: CalibrationMode;
  1513. // Default for the per-job "ask for outcome afterwards" toggle (#1898)
  1514. default_confirm_outcome: boolean;
  1515. // Also ask for prints Bambuddy archived but did not dispatch (#1898)
  1516. confirm_outcome_external_prints: boolean;
  1517. // Count unanswered outcome prompts as "good" when the plate is released (#1898)
  1518. confirm_default_good_on_plate_clear: boolean;
  1519. // Staggered batch start defaults
  1520. stagger_group_size: number;
  1521. stagger_interval_minutes: number;
  1522. // Finance budget reset window
  1523. billing_enabled: boolean;
  1524. printer_kill_switch_enabled: boolean;
  1525. finance_budget_reset_day: number;
  1526. finance_budget_reset_timezone: string;
  1527. // Plate-clear confirmation
  1528. require_plate_clear: boolean;
  1529. // Shortest job first scheduling
  1530. queue_shortest_first: boolean;
  1531. // How many printers the queue may upload to at once (#2555). 1 restores the
  1532. // old strictly-serial behaviour, where every printer waited out every other
  1533. // printer's transfer.
  1534. queue_max_concurrent_uploads: number;
  1535. // Preheat / heat-soak before queued prints (#1468). Master toggle is the
  1536. // default for new queue items; per-item PrintQueueItem.preheat_override can
  1537. // flip the decision per print. Chamber target derives from the loaded AMS
  1538. // filament types via preheat_filament_targets (JSON map of type → °C, max
  1539. // across loaded slots); the per-item override field bypasses derivation.
  1540. preheat_enabled: boolean;
  1541. preheat_filament_targets: string;
  1542. preheat_max_wait_seconds: number;
  1543. preheat_soak_seconds: number;
  1544. queue_keep_bed_warm: boolean;
  1545. queue_keep_warm_bed_temp: number;
  1546. queue_keep_warm_max_minutes: number;
  1547. // User-configurable presets for the printer-card popovers (JSON arrays of 3 ints).
  1548. // Empty string = use built-in defaults.
  1549. nozzle_temp_presets: string;
  1550. bed_temp_presets: string;
  1551. chamber_temp_presets: string;
  1552. fan_speed_presets: string;
  1553. // Default sidebar order (admin-set for all users)
  1554. default_sidebar_order: string;
  1555. // LDAP authentication
  1556. ldap_enabled: boolean;
  1557. ldap_server_url: string;
  1558. ldap_bind_dn: string;
  1559. ldap_bind_password: string;
  1560. ldap_search_base: string;
  1561. ldap_user_filter: string;
  1562. ldap_security: string;
  1563. ldap_group_mapping: string;
  1564. ldap_auto_provision: boolean;
  1565. ldap_default_group: string;
  1566. obico_enabled: boolean;
  1567. obico_ml_url: string;
  1568. bambuddy_internal_url: string;
  1569. obico_ml_token: string;
  1570. obico_sensitivity: 'low' | 'medium' | 'high';
  1571. obico_action: 'notify' | 'pause' | 'pause_and_off';
  1572. obico_poll_interval: number;
  1573. obico_enabled_printers: string;
  1574. octoeverywhere_enabled: boolean;
  1575. octoeverywhere_api_key: string;
  1576. octoeverywhere_api_key_configured: boolean;
  1577. octoeverywhere_confidence: OctoEverywhereConfidence;
  1578. octoeverywhere_action: 'notify' | 'pause' | 'pause_and_off';
  1579. octoeverywhere_enabled_printers: string;
  1580. octoeverywhere_poll_interval: number;
  1581. // Inventory forecasting global lead time
  1582. forecast_global_lead_time_days: number;
  1583. location_sensor_poll_interval: number;
  1584. // JSON map of sensor category → {alertAbove, alertBelow, notifyOnAlert},
  1585. // seeding new storage-location sensor bindings. Empty = built-in defaults.
  1586. // Server-backed so two admins seed the same alert rules and a restore
  1587. // brings them back; see utils/locationSensorDefaults.ts.
  1588. location_sensor_alert_defaults: string;
  1589. }
  1590. export type AppSettingsUpdate = Partial<Omit<AppSettings, 'octoeverywhere_api_key_configured'>>;
  1591. // Settings as a page sees them: everything from GET /settings for a user who
  1592. // may read it, otherwise the subset /settings/ui-preferences and
  1593. // /settings/ui-flags serve, which reports G-code snippets only as set or not.
  1594. export type UiSettings = Partial<AppSettings> & { has_gcode_snippets?: boolean };
  1595. // MQTT relay status
  1596. export interface MQTTStatus {
  1597. enabled: boolean;
  1598. connected: boolean;
  1599. broker: string;
  1600. port: number;
  1601. topic_prefix: string;
  1602. }
  1603. // Cloud types
  1604. export interface CloudAuthStatus {
  1605. is_authenticated: boolean;
  1606. email: string | null;
  1607. region?: 'global' | 'china' | null;
  1608. /** A token is stored but Bambu no longer accepts it — tell the user why the login form is back. */
  1609. sign_in_expired?: boolean;
  1610. }
  1611. export interface CloudLoginResponse {
  1612. success: boolean;
  1613. needs_verification: boolean;
  1614. message: string;
  1615. verification_type?: 'email' | 'totp' | null;
  1616. tfa_key?: string | null;
  1617. /**
  1618. * Machine-readable cause of a failure. 'captcha' means Bambu's anti-abuse
  1619. * layer is challenging this network and no credential will be accepted until
  1620. * it clears — the UI must explain that in place rather than toast `message`.
  1621. */
  1622. reason?: 'captcha' | string | null;
  1623. }
  1624. // Orca Cloud types — paste-flow PKCE handshake against auth.orcaslicer.com.
  1625. // See backend/app/services/orca_cloud.py for the deep dive on why this
  1626. // flow is paste-based rather than callback-based.
  1627. export interface OrcaDeviceStartResponse {
  1628. user_code: string;
  1629. verification_uri: string;
  1630. verification_uri_complete: string;
  1631. interval: number;
  1632. expires_in: number;
  1633. }
  1634. export type OrcaDevicePollStatus =
  1635. | 'authorization_pending'
  1636. | 'slow_down'
  1637. | 'access_denied'
  1638. | 'expired_token'
  1639. | 'complete';
  1640. export interface OrcaDevicePollResponse {
  1641. status: OrcaDevicePollStatus;
  1642. connected: boolean;
  1643. email: string | null;
  1644. user_id: string | null;
  1645. }
  1646. export interface OrcaAuthStatusResponse {
  1647. connected: boolean;
  1648. email: string | null;
  1649. user_id: string | null;
  1650. }
  1651. // Orca profiles are shaped to match Bambu Cloud's SlicerSetting on the wire
  1652. // so the frontend can use the same visual components for both surfaces (cards,
  1653. // grouped sections, filter bar). Backend handles the source-specific
  1654. // transformation in routes/orca_cloud.py::_orca_to_setting.
  1655. export interface OrcaProfileMeta {
  1656. setting_id: string;
  1657. name: string;
  1658. type: string;
  1659. version: string | null;
  1660. user_id: string | null;
  1661. updated_time: string | null;
  1662. is_custom: boolean;
  1663. }
  1664. export interface OrcaProfileListResponse {
  1665. filament: OrcaProfileMeta[];
  1666. printer: OrcaProfileMeta[];
  1667. process: OrcaProfileMeta[];
  1668. }
  1669. export interface OrcaProfileDetail {
  1670. setting_id: string;
  1671. name: string;
  1672. type: string;
  1673. version: string | null;
  1674. base_id: string | null;
  1675. update_time: string | null;
  1676. setting: Record<string, unknown>;
  1677. }
  1678. // MakerWorld integration. Full metadata/instance shapes come back as
  1679. // Record<string, unknown> — MakerWorld's API adds fields over time, so we
  1680. // pass them through verbatim rather than maintaining a brittle mirror.
  1681. export interface MakerworldStatus {
  1682. has_cloud_token: boolean;
  1683. can_download: boolean;
  1684. /** A token is stored but Bambu rejected it — downloads will fail until the user signs in again. */
  1685. sign_in_expired?: boolean;
  1686. }
  1687. export interface MakerworldResolvedModel {
  1688. model_id: number;
  1689. profile_id: number | null;
  1690. design: Record<string, unknown>;
  1691. instances: Array<Record<string, unknown>>;
  1692. already_imported_library_ids: number[];
  1693. }
  1694. export interface MakerworldImportResponse {
  1695. library_file_id: number;
  1696. filename: string;
  1697. folder_id: number | null;
  1698. profile_id: number | null;
  1699. was_existing: boolean;
  1700. }
  1701. export interface MakerworldRecentImport {
  1702. library_file_id: number;
  1703. filename: string;
  1704. folder_id: number | null;
  1705. thumbnail_path: string | null;
  1706. source_url: string | null;
  1707. created_at: string;
  1708. }
  1709. // Manyfold integration (#1471): a self-hosted model library, browsed and
  1710. // searched, with single files imported into the library.
  1711. export interface ManyfoldConfig {
  1712. url: string;
  1713. client_id: string;
  1714. /** The secret itself is never returned. */
  1715. has_client_secret: boolean;
  1716. configured: boolean;
  1717. }
  1718. export interface ManyfoldConfigInput {
  1719. url: string;
  1720. client_id: string;
  1721. /** Empty or left out keeps the stored secret. */
  1722. client_secret?: string;
  1723. }
  1724. export interface ManyfoldStatus {
  1725. configured: boolean;
  1726. url: string;
  1727. }
  1728. export interface ManyfoldModelSummary {
  1729. id: string;
  1730. name: string;
  1731. }
  1732. export interface ManyfoldModelList {
  1733. total: number;
  1734. page: number;
  1735. has_next: boolean;
  1736. has_previous: boolean;
  1737. models: ManyfoldModelSummary[];
  1738. }
  1739. export interface ManyfoldFile {
  1740. id: string;
  1741. name: string;
  1742. mime: string;
  1743. importable: boolean;
  1744. /** Set while the file imported earlier is still in the library. */
  1745. library_file: { id: number; filename: string; folder_id: number | null } | null;
  1746. }
  1747. export interface ManyfoldModel {
  1748. id: string;
  1749. name: string;
  1750. caption: string | null;
  1751. description: string | null;
  1752. license: string | null;
  1753. tags: string[];
  1754. url: string;
  1755. has_preview: boolean;
  1756. files: ManyfoldFile[];
  1757. }
  1758. export interface ManyfoldImportResponse {
  1759. library_file_id: number;
  1760. filename: string;
  1761. folder_id: number | null;
  1762. was_existing: boolean;
  1763. }
  1764. export interface SlicerSetting {
  1765. setting_id: string;
  1766. name: string;
  1767. type: string;
  1768. version: string | null;
  1769. user_id: string | null;
  1770. updated_time: string | null;
  1771. is_custom: boolean;
  1772. // The id Bambu Studio puts in an AMS slot for the preset; not derivable
  1773. // from setting_id for every preset (#3387). Absent from older backends.
  1774. filament_id?: string | null;
  1775. }
  1776. export interface SpoolCatalogEntry {
  1777. id: number;
  1778. name: string;
  1779. weight: number;
  1780. is_default: boolean;
  1781. }
  1782. export interface StorageLocation {
  1783. id: number;
  1784. name: string;
  1785. identifier: string | null;
  1786. spool_count: number;
  1787. created_at: string;
  1788. updated_at: string;
  1789. }
  1790. export interface ColorCatalogEntry {
  1791. id: number;
  1792. manufacturer: string;
  1793. color_name: string;
  1794. hex_color: string;
  1795. material: string | null;
  1796. is_default: boolean;
  1797. // #1154: optional multi-colour gradient stops + visual effect.
  1798. extra_colors?: string | null;
  1799. effect_type?: string | null;
  1800. }
  1801. export interface SlicerSettingsResponse {
  1802. filament: SlicerSetting[];
  1803. printer: SlicerSetting[];
  1804. process: SlicerSetting[];
  1805. }
  1806. export interface SlicerSettingDetail {
  1807. message?: string | null;
  1808. code?: string | null;
  1809. error?: string | null;
  1810. public: boolean;
  1811. version?: string | null;
  1812. type: string;
  1813. name: string;
  1814. update_time?: string | null;
  1815. nickname?: string | null;
  1816. base_id?: string | null;
  1817. setting: Record<string, unknown>;
  1818. filament_id?: string | null;
  1819. setting_id?: string | null;
  1820. }
  1821. export interface SlicerSettingCreate {
  1822. type: string; // 'filament', 'print', or 'printer'
  1823. name: string;
  1824. base_id: string;
  1825. setting: Record<string, unknown>;
  1826. }
  1827. export interface SlicerSettingUpdate {
  1828. name?: string;
  1829. setting?: Record<string, unknown>;
  1830. }
  1831. export interface SlicerSettingDeleteResponse {
  1832. success: boolean;
  1833. message: string;
  1834. }
  1835. // Built-in filament fallback (static table from backend)
  1836. export interface BuiltinFilament {
  1837. filament_id: string;
  1838. name: string;
  1839. }
  1840. // Slice request/response — POST /library/files/{id}/slice and /archives/{id}/slice
  1841. //
  1842. // Two preset shapes are accepted per slot:
  1843. // - Legacy bare integer ids (`*_preset_id`) — pre-cloud-tier clients.
  1844. // - Source-aware refs (`*_preset: PresetRef`) — new SliceModal that picks
  1845. // across cloud / local / standard tiers. Source-aware refs win when both
  1846. // are present in the same payload.
  1847. export type PresetSource = 'orca_cloud' | 'cloud' | 'local' | 'standard';
  1848. export interface PresetRef {
  1849. source: PresetSource;
  1850. id: string;
  1851. }
  1852. /**
  1853. * Why a preset's effective values are unavailable.
  1854. *
  1855. * `sidecar_outdated` is the one that matters in practice: an install pulls its
  1856. * sidecar as `SIDECAR_TAG:-latest` regardless of which Bambuddy channel it is
  1857. * on, so a user can perfectly well be running a current Bambuddy against a
  1858. * sidecar that predates this endpoint. That has a one-line fix, and saying so
  1859. * beats a generic "could not read the values".
  1860. */
  1861. export type SlicerPresetValuesReason =
  1862. | 'ok'
  1863. | 'sidecar_outdated'
  1864. | 'sidecar_unavailable'
  1865. | 'not_configured'
  1866. | 'preset_unresolved';
  1867. export interface SlicerPresetValues {
  1868. /** False when the sidecar could not supply values; `values` is then empty. */
  1869. resolved: boolean;
  1870. /** Flattened key -> value map, in the string forms a process preset stores. */
  1871. values: Record<string, string | string[]>;
  1872. reason: SlicerPresetValuesReason;
  1873. }
  1874. export interface SliceRequest {
  1875. printer_preset_id?: number;
  1876. process_preset_id?: number;
  1877. filament_preset_id?: number;
  1878. printer_preset?: PresetRef;
  1879. process_preset?: PresetRef;
  1880. filament_preset?: PresetRef;
  1881. // Multi-color: one PresetRef per plate slot, in plate order. Always
  1882. // preferred over the singular `filament_preset` when both are sent; the
  1883. // backend validator promotes a singular into a one-element list when this
  1884. // is omitted, so legacy single-color clients keep working unchanged.
  1885. filament_presets?: PresetRef[];
  1886. // Per-slot filament colour as `#RRGGBB` / `#RRGGBBAA`, same plate order as
  1887. // `filament_presets` (#2977). Neither slicer stores a colour on a filament
  1888. // *preset* -- it is a per-project property -- so without this every sliced
  1889. // file records the CLI's built-in #00AE42 and the print dialog reports a
  1890. // colour mismatch against whatever is loaded in the AMS. An empty string in
  1891. // any position hands that slot back to the backend's fallback chain (the
  1892. // preset's own default_filament_colour, then the source plate's colour).
  1893. filament_colours?: string[];
  1894. plate?: number;
  1895. export_3mf?: boolean;
  1896. // Build-plate override (#1337). When omitted, the slicer uses the process
  1897. // preset's curr_bed_type as-is. A name from BambuStudio / OrcaSlicer's
  1898. // enum: "Cool Plate", "Engineering Plate", "High Temp Plate" (Smooth PEI),
  1899. // "Textured PEI Plate", "Supertack Plate", or OrcaSlicer's "Textured Cool
  1900. // Plate" (refused when Bambu Studio slices); the backend refuses others (#3359).
  1901. bed_type?: string | null;
  1902. // "Slice as designed" (#2611). 3MF only: slice using the file's embedded
  1903. // project_settings.config (the designer's own wall count, infill, etc.)
  1904. // instead of the picked profile triplet. The preset refs above are still
  1905. // required by the backend validator but go unused on this path.
  1906. use_embedded_settings?: boolean;
  1907. // Process settings the user edited in the slice modal's settings panel,
  1908. // already serialised into the string forms a process preset stores ("1" for
  1909. // a bool, "20%" for a percent, a list for the per-extruder vectors). Patched
  1910. // onto the resolved process JSON after the designer's carried tweaks, so an
  1911. // explicit choice here wins. Omitted when the panel is untouched.
  1912. process_overrides?: Record<string, string | string[]>;
  1913. // Design settings carried from the source 3MF (#2622) — a list of keys the
  1914. // file flags as changed from the system preset, not values.
  1915. design_overrides?: string[];
  1916. // Layout passes the slicer runs before slicing (#2548), both off by
  1917. // default because they move or rotate the objects the user laid out.
  1918. // Unlike the fields above these are CLI actions rather than profile
  1919. // values, so they apply on the embedded-settings path too.
  1920. auto_orient?: boolean;
  1921. auto_arrange?: boolean;
  1922. }
  1923. // GET /api/v1/slicer/presets — unified listing across cloud / local / standard.
  1924. export type SlicerCloudStatus = 'ok' | 'not_authenticated' | 'expired' | 'unreachable';
  1925. export interface UnifiedPreset {
  1926. id: string;
  1927. name: string;
  1928. source: PresetSource;
  1929. // Populated for the filament slot only — used by the SliceModal multi-color
  1930. // pre-pick to score presets against each plate slot's required (type,
  1931. // colour). Optional because the bundled / standard tier rarely carries a
  1932. // colour (colour is a runtime spool attribute on Bambu) and older API
  1933. // responses pre-date these fields entirely.
  1934. filament_type?: string | null;
  1935. filament_colour?: string | null;
  1936. // Printer-preset names a process / filament preset declares itself
  1937. // compatible with. Populated for the local tier (the slicer's own
  1938. // `compatible_printers`); null for cloud / standard. The SliceModal filters
  1939. // the process / filament dropdowns by the selected printer using this when
  1940. // present (#1325).
  1941. compatible_printers?: string[] | null;
  1942. // Printer presets only: the preset it was saved from, for the local and
  1943. // OrcaSlicer Cloud tiers (#3250).
  1944. inherits?: string | null;
  1945. }
  1946. export interface UnifiedPresetsBySlot {
  1947. printer: UnifiedPreset[];
  1948. process: UnifiedPreset[];
  1949. filament: UnifiedPreset[];
  1950. }
  1951. // What is loaded in each connected printer, for the SliceModal's
  1952. // "only connected printers" / "only loaded spools" filters (#3172).
  1953. export interface LoadedSpoolPreset {
  1954. preset_id: string;
  1955. preset_name: string;
  1956. preset_source: string;
  1957. tray_info_idx?: string | null;
  1958. }
  1959. export interface LoadedSpoolTray {
  1960. ams_id: number;
  1961. tray_id: number;
  1962. tray_type: string | null;
  1963. tray_sub_brands: string | null;
  1964. tray_color: string | null;
  1965. tray_info_idx: string | null;
  1966. exists: boolean | null;
  1967. state: number | null;
  1968. saved_preset: LoadedSpoolPreset | null;
  1969. }
  1970. export interface LoadedSpoolUnit {
  1971. id: number;
  1972. is_ams_ht: boolean;
  1973. trays: LoadedSpoolTray[];
  1974. }
  1975. export interface LoadedSpoolPrinter {
  1976. id: number;
  1977. name: string;
  1978. model: string | null;
  1979. ams: LoadedSpoolUnit[];
  1980. // Holders with a spool in them; external_holders counts all of them (two
  1981. // on a dual-nozzle printer, labelled left and right).
  1982. external: LoadedSpoolTray[];
  1983. external_holders: number;
  1984. }
  1985. export interface LoadedSpoolsResponse {
  1986. printers: LoadedSpoolPrinter[];
  1987. }
  1988. export interface UnifiedPresetsResponse {
  1989. // Priority order: local > orca_cloud > cloud > standard. No cross-tier
  1990. // dedup (apart from stock_aliases below) — every tier surfaces its full
  1991. // list so the user can pick from any source. The order drives auto-pick + visual group rendering only.
  1992. orca_cloud: UnifiedPresetsBySlot;
  1993. cloud: UnifiedPresetsBySlot;
  1994. local: UnifiedPresetsBySlot;
  1995. standard: UnifiedPresetsBySlot;
  1996. cloud_status: SlicerCloudStatus;
  1997. orca_cloud_status: SlicerCloudStatus;
  1998. // Standard presets that Bambu Cloud's stock list also has are left out of
  1999. // the standard tier (#3386); each "standard:<id>" maps to its cloud twin.
  2000. stock_aliases?: Record<string, PresetRef>;
  2001. }
  2002. // Slicer Pipelines (#1425) — named bundles of preset slots the SliceModal
  2003. // can apply in one click. PR A surfaces only the bundle; target_* and
  2004. // fanout_strategy round-trip from the backend but the UI doesn't yet expose
  2005. // them (they come alive in PR B / PR C).
  2006. export interface SlicerPipeline {
  2007. id: number;
  2008. name: string;
  2009. description: string | null;
  2010. printer_preset: PresetRef;
  2011. process_preset: PresetRef;
  2012. filament_presets: PresetRef[];
  2013. bed_type: string | null;
  2014. target_kind: 'specific_printer' | 'printer_class';
  2015. target_printer_id: number | null;
  2016. target_model_class: string | null;
  2017. fanout_strategy: 'max_parallel' | 'fill_one_first' | 'round_robin';
  2018. created_by: number | null;
  2019. created_at: string;
  2020. updated_at: string;
  2021. }
  2022. export interface SlicerPipelineCreateRequest {
  2023. name: string;
  2024. description?: string | null;
  2025. printer_preset: PresetRef;
  2026. process_preset: PresetRef;
  2027. filament_presets: PresetRef[];
  2028. bed_type?: string | null;
  2029. }
  2030. export type SlicerPipelineUpdateRequest = Partial<SlicerPipelineCreateRequest> & {
  2031. target_kind?: 'specific_printer' | 'printer_class';
  2032. // ``target_printer_id: 0`` means "clear the target" — the backend maps that
  2033. // to null. Use null in TypeScript for the same intent.
  2034. target_printer_id?: number | null;
  2035. target_model_class?: string | null;
  2036. fanout_strategy?: 'max_parallel' | 'fill_one_first' | 'round_robin';
  2037. };
  2038. export interface SlicerPipelinesListResponse {
  2039. pipelines: SlicerPipeline[];
  2040. }
  2041. // Slicer Pipeline runs (#1425 PR B + PR C)
  2042. export type PipelineEligibilityKind =
  2043. | 'printer_not_set'
  2044. | 'printer_not_found'
  2045. | 'printer_disabled'
  2046. | 'printer_offline'
  2047. | 'filament_type_mismatch'
  2048. | 'filament_color_mismatch'
  2049. | 'ams_slot_missing'
  2050. | 'filament_unverified'
  2051. | 'no_class_matches'
  2052. | 'class_not_set';
  2053. export interface PipelineEligibilityIssue {
  2054. kind: PipelineEligibilityKind;
  2055. slot_index: number | null;
  2056. expected: string | null;
  2057. actual: string | null;
  2058. }
  2059. export interface PipelinePerPrinterReport {
  2060. printer_id: number;
  2061. printer_name: string;
  2062. ok: boolean;
  2063. issues: PipelineEligibilityIssue[];
  2064. }
  2065. export interface PipelineEligibilityReport {
  2066. ok: boolean;
  2067. target_kind: 'specific_printer' | 'printer_class';
  2068. target_printer_id: number | null;
  2069. target_printer_name: string | null;
  2070. target_model_class: string | null;
  2071. issues: PipelineEligibilityIssue[];
  2072. printer_reports: PipelinePerPrinterReport[];
  2073. }
  2074. export interface PipelineJob {
  2075. id: number;
  2076. pipeline_run_id: number;
  2077. copy_index: number;
  2078. assigned_printer_id: number | null;
  2079. assigned_printer_name: string | null;
  2080. queue_entry_id: number | null;
  2081. status:
  2082. | 'pending'
  2083. | 'awaiting_printer'
  2084. | 'queued'
  2085. | 'printing'
  2086. | 'completed'
  2087. | 'failed'
  2088. | 'cancelled'
  2089. | 'unknown';
  2090. error_message: string | null;
  2091. dispatched_at: string | null;
  2092. completed_at: string | null;
  2093. }
  2094. export interface PipelineRun {
  2095. id: number;
  2096. pipeline_id: number | null;
  2097. pipeline_name: string | null;
  2098. source_library_file_id: number | null;
  2099. source_archive_id: number | null;
  2100. source_filename: string | null;
  2101. parent_run_id: number | null;
  2102. copies: number;
  2103. copies_completed: number;
  2104. copies_failed: number;
  2105. copies_cancelled: number;
  2106. copies_in_progress: number;
  2107. status:
  2108. | 'queued'
  2109. | 'slicing'
  2110. | 'dispatching'
  2111. | 'in_progress'
  2112. | 'completed'
  2113. | 'failed'
  2114. | 'partial_failure'
  2115. | 'cancelled';
  2116. slice_job_id: number | null;
  2117. sliced_library_file_id: number | null;
  2118. eligibility_overridden: boolean;
  2119. error_message: string | null;
  2120. created_by: number | null;
  2121. created_at: string;
  2122. started_at: string | null;
  2123. completed_at: string | null;
  2124. jobs: PipelineJob[];
  2125. target_kind: 'specific_printer' | 'printer_class' | null;
  2126. target_printer_id: number | null;
  2127. target_model_class: string | null;
  2128. fanout_strategy: 'max_parallel' | 'fill_one_first' | 'round_robin' | null;
  2129. }
  2130. export interface PipelineRunListResponse {
  2131. runs: PipelineRun[];
  2132. total: number;
  2133. }
  2134. export interface SliceResponse {
  2135. library_file_id: number;
  2136. name: string;
  2137. print_time_seconds: number;
  2138. filament_used_g: number;
  2139. filament_used_mm: number;
  2140. used_embedded_settings: boolean;
  2141. /** Why the result could not be written to the external folder the source
  2142. * lives in, and so went to managed storage instead. Null on every normal
  2143. * slice. Surfaced to the user — a file filed somewhere they aren't looking
  2144. * with no signal is what made #2810 invisible from the UI. */
  2145. external_write_fallback?: string | null;
  2146. }
  2147. export interface SliceArchiveResponse {
  2148. archive_id: number;
  2149. name: string;
  2150. print_time_seconds: number;
  2151. filament_used_g: number;
  2152. filament_used_mm: number;
  2153. used_embedded_settings: boolean;
  2154. }
  2155. // Background slice-job lifecycle. POST /slice returns 202 + this shape;
  2156. // the frontend polls /slice-jobs/{id} until status is terminal.
  2157. export type SliceJobStatus = 'pending' | 'running' | 'completed' | 'failed';
  2158. export interface SliceJobEnqueueResponse {
  2159. job_id: number;
  2160. status: SliceJobStatus;
  2161. status_url: string;
  2162. }
  2163. export interface SliceJobProgress {
  2164. /** Stage label emitted by the slicer ("Generating G-code", "Slicing finished"). */
  2165. stage: string;
  2166. total_percent: number;
  2167. plate_percent: number;
  2168. /** 1-indexed plate position; 0 means "all plates" / final completion. */
  2169. plate_index: number;
  2170. plate_count: number;
  2171. updated_at: number;
  2172. /** When the backend is in the cross-class slice-all loop (#1493), each
  2173. * per-plate sub-slice's progress is augmented with the loop position
  2174. * so the toast can show "Plate 2 of 5 — Generating G-code 47%". The
  2175. * fields are absent on a single-plate slice. */
  2176. multi_plate_index?: number;
  2177. multi_plate_count?: number;
  2178. }
  2179. export interface SliceJobState {
  2180. job_id: number;
  2181. status: SliceJobStatus;
  2182. kind: 'library_file' | 'archive';
  2183. source_id: number;
  2184. source_name: string;
  2185. created_at: string;
  2186. started_at: string | null;
  2187. completed_at: string | null;
  2188. /** Live progress fed by the sidecar's --pipe channel; null until the
  2189. * slicer emits its first frame (early "Initializing" phase) or when
  2190. * the sidecar doesn't support progress. */
  2191. progress: SliceJobProgress | null;
  2192. result?: SliceResponse | SliceArchiveResponse;
  2193. error_status?: number;
  2194. error_detail?: string;
  2195. }
  2196. // Local preset types (OrcaSlicer imports)
  2197. export interface LocalPreset {
  2198. id: number;
  2199. name: string;
  2200. preset_type: string;
  2201. source: string;
  2202. filament_type: string | null;
  2203. filament_vendor: string | null;
  2204. nozzle_temp_min: number | null;
  2205. nozzle_temp_max: number | null;
  2206. pressure_advance: string | null;
  2207. default_filament_colour: string | null;
  2208. filament_cost: string | null;
  2209. filament_density: string | null;
  2210. compatible_printers: string | null;
  2211. inherits: string | null;
  2212. version: string | null;
  2213. created_at: string;
  2214. updated_at: string;
  2215. }
  2216. export interface LocalPresetDetail extends LocalPreset {
  2217. setting: Record<string, unknown>;
  2218. }
  2219. export interface LocalPresetsResponse {
  2220. filament: LocalPreset[];
  2221. printer: LocalPreset[];
  2222. process: LocalPreset[];
  2223. }
  2224. export interface ImportResponse {
  2225. success: boolean;
  2226. imported: number;
  2227. skipped: number;
  2228. errors: string[];
  2229. }
  2230. export interface FieldOption {
  2231. value: string;
  2232. label: string;
  2233. }
  2234. export interface FieldDefinition {
  2235. key: string;
  2236. label: string;
  2237. type: 'text' | 'number' | 'boolean' | 'select';
  2238. category: string;
  2239. description?: string;
  2240. options?: FieldOption[];
  2241. unit?: string;
  2242. min?: number;
  2243. max?: number;
  2244. step?: number;
  2245. }
  2246. export interface FieldDefinitionsResponse {
  2247. version: string;
  2248. description: string;
  2249. fields: FieldDefinition[];
  2250. }
  2251. export interface CloudDevice {
  2252. dev_id: string;
  2253. name: string;
  2254. dev_model_name: string | null;
  2255. dev_product_name: string | null;
  2256. online: boolean;
  2257. }
  2258. // Smart Plug types
  2259. export interface SmartPlug {
  2260. id: number;
  2261. name: string;
  2262. plug_type: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  2263. ip_address: string | null; // Required for Tasmota
  2264. ha_entity_id: string | null; // Required for Home Assistant (e.g., "switch.printer_plug", "script.turn_on_printer")
  2265. // Home Assistant energy sensor entities (optional)
  2266. ha_power_entity: string | null;
  2267. ha_energy_today_entity: string | null;
  2268. ha_energy_total_entity: string | null;
  2269. // MQTT fields (required when plug_type="mqtt")
  2270. // Legacy field - kept for backward compatibility
  2271. mqtt_topic: string | null; // Deprecated, use mqtt_power_topic
  2272. mqtt_multiplier: number; // Deprecated, use mqtt_power_multiplier
  2273. // Power monitoring
  2274. mqtt_power_topic: string | null; // Topic for power data
  2275. mqtt_power_path: string | null; // e.g., "power_l1" or "data.power"
  2276. mqtt_power_multiplier: number; // Unit conversion for power
  2277. // Energy monitoring
  2278. mqtt_energy_topic: string | null; // Topic for energy data
  2279. mqtt_energy_path: string | null; // e.g., "energy_l1"
  2280. mqtt_energy_multiplier: number; // Unit conversion for energy
  2281. // State monitoring
  2282. mqtt_state_topic: string | null; // Topic for state data
  2283. mqtt_state_path: string | null; // e.g., "state_l1" for ON/OFF
  2284. mqtt_state_on_value: string | null; // What value means "ON" (e.g., "ON", "true", "1")
  2285. // REST/Webhook fields (required when plug_type="rest")
  2286. rest_on_url: string | null;
  2287. rest_on_body: string | null;
  2288. rest_off_url: string | null;
  2289. rest_off_body: string | null;
  2290. rest_method: string | null;
  2291. rest_headers: string | null;
  2292. rest_status_url: string | null;
  2293. rest_status_path: string | null;
  2294. rest_status_on_value: string | null;
  2295. rest_power_url: string | null;
  2296. rest_power_path: string | null;
  2297. rest_power_multiplier: number;
  2298. rest_energy_url: string | null;
  2299. rest_energy_path: string | null;
  2300. rest_energy_multiplier: number;
  2301. // Lifetime counter, separate from the daily one (#2539). A Shelly reports only
  2302. // this; Today and Yesterday are derived from its hourly snapshots.
  2303. rest_energy_total_path: string | null;
  2304. rest_energy_total_multiplier: number;
  2305. printer_id: number | null;
  2306. // #2629: only a plug that really feeds the printer may mark it offline when
  2307. // switched off. Accessory plugs follow the print cycle without powering it.
  2308. controls_printer_power: boolean;
  2309. enabled: boolean;
  2310. auto_on: boolean;
  2311. auto_off: boolean;
  2312. auto_off_persistent: boolean;
  2313. off_delay_mode: 'time' | 'temperature';
  2314. off_delay_minutes: number;
  2315. off_temp_threshold: number;
  2316. // #1349: auto-off after AMS drying completes.
  2317. auto_off_after_drying: boolean;
  2318. off_delay_after_drying_minutes: number;
  2319. username: string | null;
  2320. password: string | null;
  2321. // Power alerts
  2322. power_alert_enabled: boolean;
  2323. power_alert_high: number | null;
  2324. power_alert_low: number | null;
  2325. power_alert_last_triggered: string | null;
  2326. // Schedule
  2327. schedule_enabled: boolean;
  2328. schedule_on_time: string | null;
  2329. schedule_off_time: string | null;
  2330. // Visibility options
  2331. show_in_switchbar: boolean;
  2332. show_on_printer_card: boolean; // For scripts: show on printer card
  2333. // Status
  2334. last_state: string | null;
  2335. last_checked: string | null;
  2336. auto_off_executed: boolean; // True when auto-off was triggered after print
  2337. created_at: string;
  2338. updated_at: string;
  2339. }
  2340. export interface SmartPlugCreate {
  2341. name: string;
  2342. plug_type?: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  2343. ip_address?: string | null; // Required for Tasmota
  2344. ha_entity_id?: string | null; // Required for Home Assistant
  2345. // Home Assistant energy sensor entities (optional)
  2346. ha_power_entity?: string | null;
  2347. ha_energy_today_entity?: string | null;
  2348. ha_energy_total_entity?: string | null;
  2349. // MQTT fields (required when plug_type="mqtt")
  2350. // Legacy fields - kept for backward compatibility
  2351. mqtt_topic?: string | null;
  2352. mqtt_multiplier?: number;
  2353. // Power monitoring
  2354. mqtt_power_topic?: string | null;
  2355. mqtt_power_path?: string | null;
  2356. mqtt_power_multiplier?: number;
  2357. // Energy monitoring
  2358. mqtt_energy_topic?: string | null;
  2359. mqtt_energy_path?: string | null;
  2360. mqtt_energy_multiplier?: number;
  2361. // State monitoring
  2362. mqtt_state_topic?: string | null;
  2363. mqtt_state_path?: string | null;
  2364. mqtt_state_on_value?: string | null;
  2365. // REST fields
  2366. rest_on_url?: string | null;
  2367. rest_on_body?: string | null;
  2368. rest_off_url?: string | null;
  2369. rest_off_body?: string | null;
  2370. rest_method?: string | null;
  2371. rest_headers?: string | null;
  2372. rest_status_url?: string | null;
  2373. rest_status_path?: string | null;
  2374. rest_status_on_value?: string | null;
  2375. rest_power_url?: string | null;
  2376. rest_power_path?: string | null;
  2377. rest_power_multiplier?: number;
  2378. rest_energy_url?: string | null;
  2379. rest_energy_path?: string | null;
  2380. rest_energy_multiplier?: number;
  2381. rest_energy_total_path?: string | null;
  2382. rest_energy_total_multiplier?: number;
  2383. printer_id?: number | null;
  2384. // #2629
  2385. controls_printer_power?: boolean;
  2386. enabled?: boolean;
  2387. auto_on?: boolean;
  2388. auto_off?: boolean;
  2389. auto_off_persistent?: boolean;
  2390. off_delay_mode?: 'time' | 'temperature';
  2391. off_delay_minutes?: number;
  2392. off_temp_threshold?: number;
  2393. // #1349
  2394. auto_off_after_drying?: boolean;
  2395. off_delay_after_drying_minutes?: number;
  2396. username?: string | null;
  2397. password?: string | null;
  2398. // Power alerts
  2399. power_alert_enabled?: boolean;
  2400. power_alert_high?: number | null;
  2401. power_alert_low?: number | null;
  2402. // Schedule
  2403. schedule_enabled?: boolean;
  2404. schedule_on_time?: string | null;
  2405. schedule_off_time?: string | null;
  2406. // Visibility options
  2407. show_in_switchbar?: boolean;
  2408. show_on_printer_card?: boolean;
  2409. }
  2410. export interface SmartPlugUpdate {
  2411. name?: string;
  2412. plug_type?: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  2413. ip_address?: string | null;
  2414. ha_entity_id?: string | null;
  2415. // Home Assistant energy sensor entities (optional)
  2416. ha_power_entity?: string | null;
  2417. ha_energy_today_entity?: string | null;
  2418. ha_energy_total_entity?: string | null;
  2419. // MQTT fields (legacy)
  2420. mqtt_topic?: string | null;
  2421. mqtt_multiplier?: number;
  2422. // MQTT power fields
  2423. mqtt_power_topic?: string | null;
  2424. mqtt_power_path?: string | null;
  2425. mqtt_power_multiplier?: number;
  2426. // MQTT energy fields
  2427. mqtt_energy_topic?: string | null;
  2428. mqtt_energy_path?: string | null;
  2429. mqtt_energy_multiplier?: number;
  2430. // MQTT state fields
  2431. mqtt_state_topic?: string | null;
  2432. mqtt_state_path?: string | null;
  2433. mqtt_state_on_value?: string | null;
  2434. // REST fields
  2435. rest_on_url?: string | null;
  2436. rest_on_body?: string | null;
  2437. rest_off_url?: string | null;
  2438. rest_off_body?: string | null;
  2439. rest_method?: string | null;
  2440. rest_headers?: string | null;
  2441. rest_status_url?: string | null;
  2442. rest_status_path?: string | null;
  2443. rest_status_on_value?: string | null;
  2444. rest_power_url?: string | null;
  2445. rest_power_path?: string | null;
  2446. rest_power_multiplier?: number;
  2447. rest_energy_url?: string | null;
  2448. rest_energy_path?: string | null;
  2449. rest_energy_multiplier?: number;
  2450. rest_energy_total_path?: string | null;
  2451. rest_energy_total_multiplier?: number;
  2452. printer_id?: number | null;
  2453. // #2629
  2454. controls_printer_power?: boolean;
  2455. enabled?: boolean;
  2456. auto_on?: boolean;
  2457. auto_off?: boolean;
  2458. auto_off_persistent?: boolean;
  2459. off_delay_mode?: 'time' | 'temperature';
  2460. off_delay_minutes?: number;
  2461. off_temp_threshold?: number;
  2462. // #1349
  2463. auto_off_after_drying?: boolean;
  2464. off_delay_after_drying_minutes?: number;
  2465. username?: string | null;
  2466. password?: string | null;
  2467. // Power alerts
  2468. power_alert_enabled?: boolean;
  2469. power_alert_high?: number | null;
  2470. power_alert_low?: number | null;
  2471. // Schedule
  2472. schedule_enabled?: boolean;
  2473. schedule_on_time?: string | null;
  2474. schedule_off_time?: string | null;
  2475. // Visibility options
  2476. show_in_switchbar?: boolean;
  2477. show_on_printer_card?: boolean;
  2478. }
  2479. // Home Assistant entity for smart plug selection
  2480. export interface HAEntity {
  2481. entity_id: string;
  2482. friendly_name: string;
  2483. state: string | null;
  2484. domain: string; // "switch", "light", "input_boolean", "script"
  2485. }
  2486. // Home Assistant sensor entity for energy monitoring
  2487. export interface HASensorEntity {
  2488. entity_id: string;
  2489. friendly_name: string;
  2490. state: string | null;
  2491. unit_of_measurement: string | null; // "W", "kW", "kWh", "Wh"
  2492. }
  2493. export interface HATestConnectionResult {
  2494. success: boolean;
  2495. message: string | null;
  2496. error: string | null;
  2497. }
  2498. // A Home Assistant entity bound to a printer for display on its card (#1148, #448).
  2499. // Read-only: unlike a SmartPlug there is nothing here to switch.
  2500. export interface PrinterHASensor {
  2501. id: number;
  2502. printer_id: number;
  2503. name: string;
  2504. entity_id: string;
  2505. kind: 'binary' | 'numeric';
  2506. device_class: string | null; // HA's own class: "door", "temperature", ...
  2507. unit: string | null; // numeric sensors only
  2508. // What counts as needing attention. Binary sensors use alert_state, numeric
  2509. // ones the thresholds; all null means the sensor is display-only.
  2510. alert_state: 'on' | 'off' | null;
  2511. alert_above: number | null;
  2512. alert_below: number | null;
  2513. block_print: boolean; // hold the printer's queue while alerting
  2514. notify_on_alert: boolean;
  2515. show_on_printer_card: boolean;
  2516. sort_order: number;
  2517. last_state: string | null;
  2518. last_changed: string | null;
  2519. last_checked: string | null;
  2520. created_at: string;
  2521. updated_at: string;
  2522. }
  2523. export interface PrinterHASensorReading {
  2524. id: number;
  2525. name: string;
  2526. entity_id: string;
  2527. kind: 'binary' | 'numeric';
  2528. device_class: string | null;
  2529. unit: string | null;
  2530. state: string | null; // null when unreadable or not yet polled
  2531. value: number | null; // numeric sensors only
  2532. alerting: boolean;
  2533. block_print: boolean;
  2534. reachable: boolean;
  2535. last_changed: string | null;
  2536. }
  2537. export interface PrinterHASensorCreate {
  2538. printer_id: number;
  2539. name: string;
  2540. entity_id: string;
  2541. kind: 'binary' | 'numeric';
  2542. device_class?: string | null;
  2543. unit?: string | null;
  2544. alert_state?: 'on' | 'off' | null;
  2545. alert_above?: number | null;
  2546. alert_below?: number | null;
  2547. block_print?: boolean;
  2548. notify_on_alert?: boolean;
  2549. show_on_printer_card?: boolean;
  2550. sort_order?: number;
  2551. }
  2552. export type PrinterHASensorUpdate = Partial<Omit<PrinterHASensorCreate, 'printer_id'>>;
  2553. export interface LocationHASensor {
  2554. id: number;
  2555. location_id: number;
  2556. name: string;
  2557. entity_id: string;
  2558. kind: 'binary' | 'numeric';
  2559. device_class: string | null;
  2560. unit: string | null;
  2561. alert_state: 'on' | 'off' | null;
  2562. alert_above: number | null;
  2563. alert_below: number | null;
  2564. notify_on_alert: boolean;
  2565. show_on_card: boolean;
  2566. sort_order: number;
  2567. last_state: string | null;
  2568. last_changed: string | null;
  2569. last_checked: string | null;
  2570. created_at: string;
  2571. updated_at: string;
  2572. }
  2573. export interface LocationHASensorReading {
  2574. id: number;
  2575. name: string;
  2576. entity_id: string;
  2577. kind: 'binary' | 'numeric';
  2578. device_class: string | null;
  2579. unit: string | null;
  2580. state: string | null;
  2581. value: number | null;
  2582. alerting: boolean;
  2583. reachable: boolean;
  2584. alert_state: string | null;
  2585. alert_above: number | null;
  2586. alert_below: number | null;
  2587. last_changed: string | null;
  2588. show_on_card: boolean;
  2589. }
  2590. export interface LocationHASensorCreate {
  2591. location_id: number;
  2592. name: string;
  2593. entity_id: string;
  2594. kind: 'binary' | 'numeric';
  2595. device_class?: string | null;
  2596. unit?: string | null;
  2597. alert_state?: 'on' | 'off' | null;
  2598. alert_above?: number | null;
  2599. alert_below?: number | null;
  2600. notify_on_alert?: boolean;
  2601. show_on_card?: boolean;
  2602. sort_order?: number;
  2603. }
  2604. export type LocationHASensorUpdate = Partial<Omit<LocationHASensorCreate, 'location_id'>>;
  2605. // An entity offered by the binding picker.
  2606. export interface HADisplayEntity {
  2607. entity_id: string;
  2608. friendly_name: string;
  2609. state: string | null;
  2610. domain: string; // "binary_sensor" | "sensor"
  2611. device_class: string | null;
  2612. unit_of_measurement: string | null;
  2613. }
  2614. export interface SmartPlugEnergy {
  2615. power: number | null; // Current watts
  2616. voltage: number | null; // Volts
  2617. current: number | null; // Amps
  2618. today: number | null; // kWh used today
  2619. yesterday: number | null; // kWh used yesterday
  2620. total: number | null; // Total kWh
  2621. factor: number | null; // Power factor (0-1)
  2622. apparent_power: number | null; // VA
  2623. reactive_power: number | null; // VAr
  2624. }
  2625. export interface SmartPlugStatus {
  2626. state: string | null;
  2627. reachable: boolean;
  2628. device_name: string | null;
  2629. energy: SmartPlugEnergy | null;
  2630. }
  2631. export interface SmartPlugTestResult {
  2632. success: boolean;
  2633. state: string | null;
  2634. device_name: string | null;
  2635. }
  2636. // Tasmota Discovery types
  2637. export interface TasmotaScanStatus {
  2638. running: boolean;
  2639. scanned: number;
  2640. total: number;
  2641. }
  2642. export interface DiscoveredTasmotaDevice {
  2643. ip_address: string;
  2644. name: string;
  2645. module: number | null;
  2646. state: string | null;
  2647. discovered_at: string | null;
  2648. }
  2649. // Print Queue types
  2650. export interface PrintQueueItem {
  2651. id: number;
  2652. printer_id: number | null; // null = unassigned
  2653. target_model: string | null; // Target printer model for model-based assignment
  2654. target_location: string | null; // Target location filter for model-based assignment
  2655. required_filament_types: string[] | null; // Required filament types for model-based assignment
  2656. waiting_reason: string | null; // Why this job hasn't started yet (empty once it can)
  2657. // Cross-model alternatives (#671), in priority order. Empty for ordinary
  2658. // items. Present until dispatch resolves one, after which library_file_id and
  2659. // target_model name the candidate that actually ran.
  2660. variants?: Array<{
  2661. library_file_id: number;
  2662. filename: string;
  2663. target_model: string;
  2664. position: number;
  2665. }>;
  2666. // Either archive_id OR library_file_id must be set (archive created at print start)
  2667. archive_id: number | null;
  2668. library_file_id: number | null;
  2669. cost_center_id: number | null;
  2670. estimated_cost: number | null;
  2671. position: number;
  2672. scheduled_time: string | null;
  2673. require_previous_success: boolean;
  2674. auto_off_after: boolean;
  2675. manual_start: boolean; // Requires manual trigger to start (staged)
  2676. // Set by the dispatch scheduler when the assigned spool can't satisfy
  2677. // any required slot's grams (#1496). Surfaced on the queue row as a
  2678. // "filament short" badge; cleared on a successful ▶ click (live recheck).
  2679. filament_short: boolean;
  2680. // Persistent "Print Anyway" acknowledgement — once true the scheduler
  2681. // skips the deficit check for this item (#1698-followup). Set by the
  2682. // start route when skip_filament_check=true, or at queue creation if
  2683. // PrintModal's deficit warning was acknowledged.
  2684. skip_filament_check: boolean;
  2685. // True when the source archive carries the slicer's own live-resolved
  2686. // AMS-slot pick (extra_data.slicer_ams_mapping) — a reprint reuses that
  2687. // exact physical spool instead of re-deriving one from type/color.
  2688. archive_has_slicer_ams_mapping: boolean;
  2689. ams_mapping: number[] | null; // AMS slot mapping for multi-color prints
  2690. 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
  2691. plate_id: number | null; // Plate ID for multi-plate 3MF files
  2692. // Print options
  2693. bed_levelling: CalibrationMode;
  2694. flow_cali: CalibrationMode;
  2695. vibration_cali: boolean;
  2696. layer_inspect: boolean;
  2697. timelapse: boolean;
  2698. use_ams: boolean;
  2699. nozzle_offset_cali: CalibrationMode;
  2700. // Ask for a post-print outcome verdict when this job completes (#1898)
  2701. confirm_outcome: boolean;
  2702. preheat_override: 'inherit' | 'on' | 'off';
  2703. preheat_chamber_target_override: number | null;
  2704. status: 'pending' | 'printing' | 'completed' | 'failed' | 'skipped' | 'cancelled';
  2705. started_at: string | null;
  2706. completed_at: string | null;
  2707. error_message: string | null;
  2708. created_at: string;
  2709. archive_name?: string | null;
  2710. archive_thumbnail?: string | null;
  2711. // True when the linked archive has been soft-deleted; archive_name /
  2712. // archive_thumbnail / downstream metadata are left null in that case so
  2713. // the UI doesn't 404-storm the now-missing endpoints (#1348 follow-up).
  2714. archive_deleted?: boolean;
  2715. library_file_name?: string | null;
  2716. library_file_thumbnail?: string | null;
  2717. printer_name?: string | null;
  2718. print_time_seconds?: number | null; // Estimated print time from archive or library file
  2719. filament_used_grams?: number | null; // Estimated print weight from archive or library file
  2720. filament_type?: string | null; // e.g. "PLA", "PETG"
  2721. filament_color?: string | null; // Hex RGBA from the slicer
  2722. bed_type?: string | null; // Build plate type for this print (per-plate accurate, #1281)
  2723. // User tracking (Issue #206)
  2724. created_by_id?: number | null;
  2725. created_by_username?: string | null;
  2726. // Batch grouping
  2727. batch_id?: number | null;
  2728. batch_name?: string | null;
  2729. // Shortest-job-first scheduling
  2730. been_jumped?: boolean;
  2731. // Auto-print G-code injection
  2732. gcode_injection?: boolean;
  2733. cleanup_library_after_dispatch?: boolean;
  2734. /** Which rack position each filament group prints from, on a nozzle-rack
  2735. * machine (#1784): `{ [group_id]: 1-based position }`. Re-checked against
  2736. * the live rack at dispatch; omit to have the dispatcher assign them. */
  2737. nozzle_rack_choice?: Record<number, number> | null;
  2738. /** Slots sent with a spool of another colour than the file asks for
  2739. * (#3279). Worked out when the job is sent; null when every slot got its
  2740. * colour or nothing could be compared. */
  2741. color_substitutions?: ColorSubstitution[] | null;
  2742. }
  2743. /** One slot printed in another colour than the file asked for (#3279). */
  2744. export interface ColorSubstitution {
  2745. slot_id: number;
  2746. type: string;
  2747. /** `#RRGGBB` the file asks for, after overrides. */
  2748. wanted: string;
  2749. /** `#RRGGBB` of the spool the slot was sent with. */
  2750. got: string;
  2751. tray: number;
  2752. }
  2753. export interface PrintBatchPlateTarget {
  2754. plate_id: number | null;
  2755. plate_name?: string | null;
  2756. quantity_target: number;
  2757. sort_order?: number;
  2758. }
  2759. export interface PrintBatchPlateProgress {
  2760. plate_id: number | null;
  2761. plate_name: string | null;
  2762. quantity_target: number;
  2763. dispatched: number;
  2764. remaining: number;
  2765. pending_count: number;
  2766. printing_count: number;
  2767. completed_count: number;
  2768. failed_count: number;
  2769. cancelled_count: number;
  2770. skipped_count: number;
  2771. /** Measured from finished runs; null until one has produced a cost. */
  2772. actual_cost: number | null;
  2773. estimated_remaining_cost: number | null;
  2774. filament_used_grams: number | null;
  2775. print_time_seconds: number;
  2776. /** False when this plate owes runs but has no queue item left to clone
  2777. * their configuration from, so queueing it could only fail (#2960). */
  2778. can_dispatch: boolean;
  2779. }
  2780. export interface PrintBatch {
  2781. id: number;
  2782. name: string;
  2783. archive_id: number | null;
  2784. library_file_id: number | null;
  2785. quantity: number;
  2786. status: string;
  2787. created_at: string;
  2788. completed_at: string | null;
  2789. created_by_id: number | null;
  2790. created_by_username: string | null;
  2791. project_id: number | null;
  2792. due_date: string | null;
  2793. notes: string | null;
  2794. /** Set when an integration (e.g. a shop connector) created the batch. */
  2795. external_source: string | null;
  2796. external_ref: string | null;
  2797. pending_count: number;
  2798. printing_count: number;
  2799. completed_count: number;
  2800. failed_count: number;
  2801. cancelled_count: number;
  2802. skipped_count: number;
  2803. /** False for batches created before per-plate targets existed (#342):
  2804. * they report progress but owe nothing and cannot be dispatched from. */
  2805. has_targets: boolean;
  2806. target_count: number;
  2807. remaining_count: number;
  2808. /** Of remaining_count, how many runs can actually be queued (#2960). */
  2809. dispatchable_count: number;
  2810. actual_cost: number | null;
  2811. estimated_remaining_cost: number | null;
  2812. filament_used_grams: number | null;
  2813. print_time_seconds: number;
  2814. plates: PrintBatchPlateProgress[];
  2815. }
  2816. export interface PrintQueueItemCreate {
  2817. printer_id?: number | null; // null = unassigned
  2818. target_model?: string | null; // Target printer model (mutually exclusive with printer_id)
  2819. target_location?: string | null; // Target location filter (only used with target_model)
  2820. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; tray_info_idx?: string; force_color_match?: boolean }> | null;
  2821. archive_id?: number | null;
  2822. library_file_id?: number | null;
  2823. scheduled_time?: string | null;
  2824. require_previous_success?: boolean;
  2825. auto_off_after?: boolean;
  2826. manual_start?: boolean; // Requires manual trigger to start (staged)
  2827. insert_at_top?: boolean; // Insert ahead of other pending items (one queue order across all printers, #3200)
  2828. insert_position?: number | null; // 1-indexed insertion position for priority queueing
  2829. // PrintModal "Print Anyway" on the deficit warning — persisted so the
  2830. // scheduler doesn't immediately re-flag this item (#1698-followup).
  2831. skip_filament_check?: boolean;
  2832. ams_mapping?: number[] | null; // AMS slot mapping for multi-color prints
  2833. plate_id?: number | null; // Plate ID for multi-plate 3MF files
  2834. // Print options
  2835. bed_levelling?: CalibrationMode;
  2836. flow_cali?: CalibrationMode;
  2837. vibration_cali?: boolean;
  2838. layer_inspect?: boolean;
  2839. timelapse?: boolean;
  2840. use_ams?: boolean;
  2841. nozzle_offset_cali?: CalibrationMode;
  2842. // Ask for a post-print outcome verdict when this job completes (#1898)
  2843. confirm_outcome?: boolean;
  2844. preheat_override?: 'inherit' | 'on' | 'off';
  2845. preheat_chamber_target_override?: number | null;
  2846. // Auto-print G-code injection
  2847. gcode_injection?: boolean;
  2848. // Batch: create multiple copies (creates a batch if > 1)
  2849. quantity?: number;
  2850. // Existing batch to add this item into (multi-plate auto-batch flow).
  2851. batch_id?: number | null;
  2852. // Project to associate the resulting archive with
  2853. project_id?: number;
  2854. cost_center_id?: number | null;
  2855. estimated_cost?: number | null;
  2856. // Delete transient uploaded library file after scheduler creates the archive
  2857. cleanup_library_after_dispatch?: boolean;
  2858. // Cross-model alternatives (#671): several sliced files, one job, whichever
  2859. // printer frees up first. Mutually exclusive with printer_id (a named printer
  2860. // defeats the point) and with archive_id/library_file_id (these ARE the files).
  2861. // Order is priority — index 0 wins when several printers are idle at once.
  2862. variants?: QueueVariantCreate[];
  2863. /** Which rack position each filament group prints from, on a nozzle-rack
  2864. * machine (#1784): `{ [group_id]: 1-based position }`. Re-checked against
  2865. * the live rack at dispatch; omit to have the dispatcher assign them. */
  2866. nozzle_rack_choice?: Record<number, number> | null;
  2867. }
  2868. /** One candidate file for a cross-model queue item (#671). */
  2869. export interface QueueVariantCreate {
  2870. library_file_id: number;
  2871. /** Read from the file's own sliced_for_model unless it declares none. */
  2872. target_model?: string | null;
  2873. plate_id?: number | null;
  2874. ams_mapping?: number[] | null;
  2875. nozzle_mapping?: number[] | null;
  2876. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; tray_info_idx?: string; force_color_match?: boolean }> | null;
  2877. }
  2878. export interface PrintBatchCreate {
  2879. name: string;
  2880. archive_id?: number | null;
  2881. library_file_id?: number | null;
  2882. /** When set, the listed pending items are assigned to the new batch
  2883. * (manual "Group as batch"). When omitted/empty, an empty batch is
  2884. * returned so the client can pass batch_id on subsequent addToQueue calls. */
  2885. item_ids?: number[];
  2886. /** Per-plate targets. Omitting them creates a plain grouping batch. */
  2887. plates?: PrintBatchPlateTarget[];
  2888. project_id?: number | null;
  2889. due_date?: string | null;
  2890. notes?: string | null;
  2891. }
  2892. export interface PrintBatchUpdate {
  2893. name?: string;
  2894. status?: 'active' | 'cancelled';
  2895. /** Replaces the full target set — a plate omitted here is removed. */
  2896. plates?: PrintBatchPlateTarget[];
  2897. project_id?: number | null;
  2898. due_date?: string | null;
  2899. notes?: string | null;
  2900. }
  2901. export interface PrintBatchDispatchRequest {
  2902. plate_id?: number | null;
  2903. only_plate?: boolean;
  2904. /** Cap on items created across all plates; omit to queue everything owed. */
  2905. limit?: number;
  2906. }
  2907. export interface PrintQueueItemUpdate {
  2908. printer_id?: number | null; // null = unassign
  2909. // A deliberate filament substitution in the mapping (#2799); see PrintModal.
  2910. skip_filament_check?: boolean;
  2911. target_model?: string | null; // Target printer model (mutually exclusive with printer_id)
  2912. target_location?: string | null; // Target location filter (only used with target_model)
  2913. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; tray_info_idx?: string; force_color_match?: boolean }> | null;
  2914. position?: number;
  2915. scheduled_time?: string | null;
  2916. require_previous_success?: boolean;
  2917. auto_off_after?: boolean;
  2918. manual_start?: boolean;
  2919. ams_mapping?: number[];
  2920. plate_id?: number | null; // Plate ID for multi-plate 3MF files
  2921. // Print options
  2922. bed_levelling?: CalibrationMode;
  2923. flow_cali?: CalibrationMode;
  2924. vibration_cali?: boolean;
  2925. layer_inspect?: boolean;
  2926. timelapse?: boolean;
  2927. use_ams?: boolean;
  2928. nozzle_offset_cali?: CalibrationMode;
  2929. // Ask for a post-print outcome verdict when this job completes (#1898)
  2930. confirm_outcome?: boolean;
  2931. preheat_override?: 'inherit' | 'on' | 'off';
  2932. preheat_chamber_target_override?: number | null;
  2933. // Auto-print G-code injection
  2934. gcode_injection?: boolean;
  2935. cost_center_id?: number | null;
  2936. estimated_cost?: number | null;
  2937. /** Which rack position each filament group prints from, on a nozzle-rack
  2938. * machine (#1784): `{ [group_id]: 1-based position }`. Re-checked against
  2939. * the live rack at dispatch; omit to have the dispatcher assign them. */
  2940. nozzle_rack_choice?: Record<number, number> | null;
  2941. }
  2942. export interface PrintQueueBulkUpdate {
  2943. item_ids: number[];
  2944. printer_id?: number | null;
  2945. scheduled_time?: string | null;
  2946. require_previous_success?: boolean;
  2947. auto_off_after?: boolean;
  2948. manual_start?: boolean;
  2949. // Print options
  2950. bed_levelling?: CalibrationMode;
  2951. flow_cali?: CalibrationMode;
  2952. vibration_cali?: boolean;
  2953. layer_inspect?: boolean;
  2954. timelapse?: boolean;
  2955. use_ams?: boolean;
  2956. nozzle_offset_cali?: CalibrationMode;
  2957. // Ask for a post-print outcome verdict when this job completes (#1898)
  2958. confirm_outcome?: boolean;
  2959. preheat_override?: 'inherit' | 'on' | 'off';
  2960. preheat_chamber_target_override?: number | null;
  2961. // Auto-print G-code injection
  2962. gcode_injection?: boolean;
  2963. cost_center_id?: number | null;
  2964. estimated_cost?: number | null;
  2965. }
  2966. export interface PrintQueueBulkUpdateResponse {
  2967. updated_count: number;
  2968. skipped_count: number;
  2969. message: string;
  2970. }
  2971. // MQTT Logging types
  2972. export interface MQTTLogEntry {
  2973. timestamp: string;
  2974. topic: string;
  2975. direction: 'in' | 'out';
  2976. payload: Record<string, unknown>;
  2977. }
  2978. export interface MQTTLogsResponse {
  2979. logging_enabled: boolean;
  2980. logs: MQTTLogEntry[];
  2981. }
  2982. // K-Profile types
  2983. export interface KProfile {
  2984. slot_id: number;
  2985. extruder_id: number;
  2986. nozzle_id: string;
  2987. nozzle_diameter: string;
  2988. filament_id: string;
  2989. name: string;
  2990. k_value: string;
  2991. n_coef: string;
  2992. ams_id: number;
  2993. tray_id: number;
  2994. setting_id: string | null;
  2995. }
  2996. export interface KProfileCreate {
  2997. slot_id?: number; // Storage slot, 0 for new profiles
  2998. extruder_id?: number;
  2999. nozzle_id: string;
  3000. nozzle_diameter: string;
  3001. filament_id: string;
  3002. name: string;
  3003. k_value: string;
  3004. n_coef?: string;
  3005. ams_id?: number;
  3006. tray_id?: number;
  3007. setting_id?: string | null;
  3008. }
  3009. export interface KProfileDelete {
  3010. slot_id: number; // cali_idx - calibration index to delete
  3011. extruder_id: number;
  3012. nozzle_id: string; // e.g., "HH00-0.4"
  3013. nozzle_diameter: string; // e.g., "0.4"
  3014. filament_id: string; // Bambu filament identifier
  3015. setting_id?: string | null; // Setting ID (for X1C series)
  3016. }
  3017. export interface KProfilesResponse {
  3018. profiles: KProfile[];
  3019. nozzle_diameter: string;
  3020. }
  3021. export interface KProfileNote {
  3022. setting_id: string;
  3023. note: string;
  3024. }
  3025. export interface KProfileNotesResponse {
  3026. notes: Record<string, string>; // setting_id -> note
  3027. }
  3028. // Slot Preset Mapping
  3029. export interface SlotPresetMapping {
  3030. ams_id: number;
  3031. tray_id: number;
  3032. preset_id: string;
  3033. preset_name: string;
  3034. // Filament id the slot was configured with alongside this preset; null for
  3035. // rows that predate it or whose writer did not know it (#3216).
  3036. tray_info_idx?: string | null;
  3037. }
  3038. // Filament types
  3039. export interface Filament {
  3040. id: number;
  3041. name: string;
  3042. type: string; // PLA, PETG, ABS, etc.
  3043. brand: string | null;
  3044. color: string | null;
  3045. color_hex: string | null;
  3046. cost_per_kg: number;
  3047. spool_weight_g: number;
  3048. currency: string;
  3049. density: number | null;
  3050. print_temp_min: number | null;
  3051. print_temp_max: number | null;
  3052. bed_temp_min: number | null;
  3053. bed_temp_max: number | null;
  3054. created_at: string;
  3055. updated_at: string;
  3056. }
  3057. // Notification Provider types
  3058. export type ProviderType = 'callmebot' | 'ntfy' | 'pushover' | 'telegram' | 'email' | 'discord' | 'webhook' | 'homeassistant' | 'bark' | 'gotify' | 'notify';
  3059. // How a Telegram provider collects the outcome verdict (#3046)
  3060. export type TelegramVerdictMode = 'buttons' | 'reactions' | 'both';
  3061. export interface NotificationProvider {
  3062. id: number;
  3063. name: string;
  3064. provider_type: ProviderType;
  3065. enabled: boolean;
  3066. config: Record<string, unknown>;
  3067. attach_photo: boolean;
  3068. // Print lifecycle events
  3069. on_print_start: boolean;
  3070. on_print_complete: boolean;
  3071. on_print_failed: boolean;
  3072. on_print_stopped: boolean;
  3073. on_print_progress: boolean;
  3074. on_print_missing_spool_assignment: boolean;
  3075. on_billing_charge_failed: boolean;
  3076. // Printer status events
  3077. on_printer_offline: boolean;
  3078. on_printer_error: boolean;
  3079. on_ai_failure_detection: boolean;
  3080. on_filament_low: boolean;
  3081. on_maintenance_due: boolean;
  3082. // AMS environmental alarms (regular AMS)
  3083. on_ams_humidity_high: boolean;
  3084. on_ams_temperature_high: boolean;
  3085. on_ams_drying_suspended: boolean;
  3086. // AMS-HT environmental alarms
  3087. on_ams_ht_humidity_high: boolean;
  3088. on_ams_ht_temperature_high: boolean;
  3089. // Build plate detection
  3090. on_plate_not_empty: boolean;
  3091. on_plate_clear_required: boolean;
  3092. // Post-print outcome confirmation (#1898)
  3093. on_print_confirm_request: boolean;
  3094. telegram_verdict_mode: TelegramVerdictMode;
  3095. // Bed cooled
  3096. on_bed_cooled: boolean;
  3097. on_ha_sensor_alert: boolean;
  3098. on_location_ha_sensor_alert: boolean;
  3099. // First layer complete
  3100. on_first_layer_complete: boolean;
  3101. on_print_pause_upcoming: boolean;
  3102. on_app_message: boolean;
  3103. // Inventory stock alerts
  3104. on_stock_reorder_alert: boolean;
  3105. on_stock_break_alert: boolean;
  3106. // Print queue events
  3107. on_queue_job_added: boolean;
  3108. on_queue_job_assigned: boolean;
  3109. on_queue_job_started: boolean;
  3110. on_queue_job_waiting: boolean;
  3111. on_queue_job_skipped: boolean;
  3112. on_queue_job_failed: boolean;
  3113. on_queue_completed: boolean;
  3114. // Quiet hours
  3115. quiet_hours_enabled: boolean;
  3116. quiet_hours_start: string | null;
  3117. quiet_hours_end: string | null;
  3118. // Daily digest
  3119. daily_digest_enabled: boolean;
  3120. daily_digest_time: string | null;
  3121. // Printer filter
  3122. printer_id: number | null;
  3123. // Status tracking
  3124. last_success: string | null;
  3125. last_error: string | null;
  3126. last_error_at: string | null;
  3127. // Timestamps
  3128. created_at: string;
  3129. updated_at: string;
  3130. }
  3131. export interface NotificationProviderCreate {
  3132. name: string;
  3133. provider_type: ProviderType;
  3134. enabled?: boolean;
  3135. config: Record<string, unknown>;
  3136. attach_photo?: boolean;
  3137. // Print lifecycle events
  3138. on_print_start?: boolean;
  3139. on_print_complete?: boolean;
  3140. on_print_failed?: boolean;
  3141. on_print_stopped?: boolean;
  3142. on_print_progress?: boolean;
  3143. on_print_missing_spool_assignment?: boolean;
  3144. on_billing_charge_failed?: boolean;
  3145. // Printer status events
  3146. on_printer_offline?: boolean;
  3147. on_printer_error?: boolean;
  3148. on_ai_failure_detection?: boolean;
  3149. on_filament_low?: boolean;
  3150. on_maintenance_due?: boolean;
  3151. // AMS environmental alarms (regular AMS)
  3152. on_ams_humidity_high?: boolean;
  3153. on_ams_temperature_high?: boolean;
  3154. on_ams_drying_suspended?: boolean;
  3155. // AMS-HT environmental alarms
  3156. on_ams_ht_humidity_high?: boolean;
  3157. on_ams_ht_temperature_high?: boolean;
  3158. // Build plate detection
  3159. on_plate_not_empty?: boolean;
  3160. on_plate_clear_required?: boolean;
  3161. // Post-print outcome confirmation (#1898)
  3162. on_print_confirm_request?: boolean;
  3163. telegram_verdict_mode?: TelegramVerdictMode;
  3164. // Bed cooled
  3165. on_bed_cooled?: boolean;
  3166. on_ha_sensor_alert?: boolean;
  3167. on_location_ha_sensor_alert?: boolean;
  3168. // First layer complete
  3169. on_first_layer_complete?: boolean;
  3170. on_print_pause_upcoming?: boolean;
  3171. on_app_message?: boolean;
  3172. // Inventory stock alerts
  3173. on_stock_reorder_alert?: boolean;
  3174. on_stock_break_alert?: boolean;
  3175. // Print queue events
  3176. on_queue_job_added?: boolean;
  3177. on_queue_job_assigned?: boolean;
  3178. on_queue_job_started?: boolean;
  3179. on_queue_job_waiting?: boolean;
  3180. on_queue_job_skipped?: boolean;
  3181. on_queue_job_failed?: boolean;
  3182. on_queue_completed?: boolean;
  3183. // Quiet hours
  3184. quiet_hours_enabled?: boolean;
  3185. quiet_hours_start?: string | null;
  3186. quiet_hours_end?: string | null;
  3187. // Daily digest
  3188. daily_digest_enabled?: boolean;
  3189. daily_digest_time?: string | null;
  3190. // Printer filter
  3191. printer_id?: number | null;
  3192. }
  3193. export interface NotificationProviderUpdate {
  3194. name?: string;
  3195. provider_type?: ProviderType;
  3196. enabled?: boolean;
  3197. config?: Record<string, unknown>;
  3198. attach_photo?: boolean;
  3199. // Print lifecycle events
  3200. on_print_start?: boolean;
  3201. on_print_complete?: boolean;
  3202. on_print_failed?: boolean;
  3203. on_print_stopped?: boolean;
  3204. on_print_progress?: boolean;
  3205. on_print_missing_spool_assignment?: boolean;
  3206. on_billing_charge_failed?: boolean;
  3207. // Printer status events
  3208. on_printer_offline?: boolean;
  3209. on_printer_error?: boolean;
  3210. on_ai_failure_detection?: boolean;
  3211. on_filament_low?: boolean;
  3212. on_maintenance_due?: boolean;
  3213. // AMS environmental alarms (regular AMS)
  3214. on_ams_humidity_high?: boolean;
  3215. on_ams_temperature_high?: boolean;
  3216. on_ams_drying_suspended?: boolean;
  3217. // AMS-HT environmental alarms
  3218. on_ams_ht_humidity_high?: boolean;
  3219. on_ams_ht_temperature_high?: boolean;
  3220. // Build plate detection
  3221. on_plate_not_empty?: boolean;
  3222. on_plate_clear_required?: boolean;
  3223. // Post-print outcome confirmation (#1898)
  3224. on_print_confirm_request?: boolean;
  3225. telegram_verdict_mode?: TelegramVerdictMode;
  3226. // Bed cooled
  3227. on_bed_cooled?: boolean;
  3228. on_ha_sensor_alert?: boolean;
  3229. on_location_ha_sensor_alert?: boolean;
  3230. // First layer complete
  3231. on_first_layer_complete?: boolean;
  3232. on_print_pause_upcoming?: boolean;
  3233. on_app_message?: boolean;
  3234. // Inventory stock alerts
  3235. on_stock_reorder_alert?: boolean;
  3236. on_stock_break_alert?: boolean;
  3237. // Print queue events
  3238. on_queue_job_added?: boolean;
  3239. on_queue_job_assigned?: boolean;
  3240. on_queue_job_started?: boolean;
  3241. on_queue_job_waiting?: boolean;
  3242. on_queue_job_skipped?: boolean;
  3243. on_queue_job_failed?: boolean;
  3244. on_queue_completed?: boolean;
  3245. // Quiet hours
  3246. quiet_hours_enabled?: boolean;
  3247. quiet_hours_start?: string | null;
  3248. quiet_hours_end?: string | null;
  3249. // Daily digest
  3250. daily_digest_enabled?: boolean;
  3251. daily_digest_time?: string | null;
  3252. // Printer filter
  3253. printer_id?: number | null;
  3254. }
  3255. // GitHub Backup types
  3256. export type ScheduleType = 'hourly' | 'daily' | 'weekly';
  3257. export type GitProviderType = 'github' | 'gitea' | 'forgejo' | 'gitlab';
  3258. /** How many cloud accounts a backup would collect presets from. Counts only —
  3259. * with auth enabled the accounts belong to individual users, so the backup
  3260. * administrator sees how many, never whose. */
  3261. export interface CloudAccountCounts {
  3262. bambu: number;
  3263. orca: number;
  3264. }
  3265. export interface GitHubBackupConfig {
  3266. id: number;
  3267. repository_url: string;
  3268. has_token: boolean;
  3269. branch: string;
  3270. provider: GitProviderType;
  3271. allow_insecure_http: boolean;
  3272. schedule_enabled: boolean;
  3273. schedule_type: ScheduleType;
  3274. backup_kprofiles: boolean;
  3275. backup_cloud_profiles: boolean;
  3276. backup_settings: boolean;
  3277. backup_spools: boolean;
  3278. backup_archives: boolean;
  3279. enabled: boolean;
  3280. last_backup_at: string | null;
  3281. last_backup_status: string | null;
  3282. last_backup_message: string | null;
  3283. last_backup_commit_sha: string | null;
  3284. next_scheduled_run: string | null;
  3285. created_at: string;
  3286. updated_at: string;
  3287. }
  3288. export interface GitHubBackupConfigCreate {
  3289. repository_url: string;
  3290. access_token: string;
  3291. branch?: string;
  3292. provider?: GitProviderType;
  3293. allow_insecure_http?: boolean;
  3294. schedule_enabled?: boolean;
  3295. schedule_type?: ScheduleType;
  3296. backup_kprofiles?: boolean;
  3297. backup_cloud_profiles?: boolean;
  3298. backup_settings?: boolean;
  3299. backup_spools?: boolean;
  3300. backup_archives?: boolean;
  3301. enabled?: boolean;
  3302. }
  3303. export interface GitHubBackupLog {
  3304. id: number;
  3305. config_id: number;
  3306. started_at: string;
  3307. completed_at: string | null;
  3308. status: string;
  3309. trigger: string;
  3310. commit_sha: string | null;
  3311. files_changed: number;
  3312. error_message: string | null;
  3313. }
  3314. export interface GitHubBackupStatus {
  3315. configured: boolean;
  3316. enabled: boolean;
  3317. is_running: boolean;
  3318. restore_running: boolean;
  3319. progress: string | null;
  3320. last_backup_at: string | null;
  3321. last_backup_status: string | null;
  3322. next_scheduled_run: string | null;
  3323. }
  3324. // Restore from a Git backup (#2656). Cloud profiles are absent deliberately —
  3325. // the backup collector never writes them, so there is nothing to restore.
  3326. export type RestoreCategory = 'kprofiles' | 'settings' | 'spools' | 'archives';
  3327. export interface GitHubCommitInfo {
  3328. sha: string;
  3329. message: string;
  3330. author: string;
  3331. date: string;
  3332. }
  3333. export interface GitHubCommitListResponse {
  3334. success: boolean;
  3335. message: string;
  3336. branch: string;
  3337. commits: GitHubCommitInfo[];
  3338. }
  3339. /**
  3340. * Values the server interpolates into a translated note or preview detail.
  3341. * Kept to strings and numbers on purpose — anything richer would have to be
  3342. * formatted server-side and could not be translated.
  3343. */
  3344. export type GitHubRestoreParams = Record<string, string | number>;
  3345. export interface GitHubRestorePreviewCategory {
  3346. category: RestoreCategory;
  3347. available: boolean;
  3348. item_count: number;
  3349. /** English rendering. Used as i18next's defaultValue, never shown on its own. */
  3350. detail: string | null;
  3351. /** Key under backup.restoreFromGit.details, or null when there is no caveat. */
  3352. detail_code: string | null;
  3353. detail_params: GitHubRestoreParams;
  3354. }
  3355. export interface GitHubRestorePreview {
  3356. success: boolean;
  3357. message: string;
  3358. ref: string;
  3359. commit: GitHubCommitInfo | null;
  3360. metadata_version: string | null;
  3361. categories: GitHubRestorePreviewCategory[];
  3362. }
  3363. export interface GitHubRestoreRequest {
  3364. ref?: string;
  3365. categories: RestoreCategory[];
  3366. overwrite_existing?: boolean;
  3367. }
  3368. /**
  3369. * One tally note, as a translation code plus its parameters (#2656).
  3370. *
  3371. * Same contract as {@link LocalBackupPathCheck} one card down: the server picks
  3372. * the code and supplies typed params, and the client renders
  3373. * ``t(`backup.restoreFromGit.notes.${code}`, { ...params, defaultValue: message })``.
  3374. * A code the client does not know yet falls back to the English `message`
  3375. * rather than showing the raw key.
  3376. */
  3377. export interface GitHubRestoreNote {
  3378. code: string;
  3379. params: GitHubRestoreParams;
  3380. message: string;
  3381. }
  3382. export interface GitHubRestoreCategoryResult {
  3383. restored: number;
  3384. skipped: number;
  3385. failed: number;
  3386. notes: GitHubRestoreNote[];
  3387. }
  3388. export interface GitHubRestoreResponse {
  3389. success: boolean;
  3390. message: string;
  3391. log_id: number | null;
  3392. ref: string | null;
  3393. results: Record<string, GitHubRestoreCategoryResult>;
  3394. }
  3395. export interface LocalBackupStatus {
  3396. enabled: boolean;
  3397. schedule: string;
  3398. time: string;
  3399. retention: number;
  3400. path: string;
  3401. default_path: string;
  3402. is_running: boolean;
  3403. last_backup_at: string | null;
  3404. last_status: string | null;
  3405. last_message: string | null;
  3406. next_run: string | null;
  3407. timezone: string;
  3408. }
  3409. export interface LocalBackupFile {
  3410. filename: string;
  3411. size: number;
  3412. created_at: string;
  3413. }
  3414. /** Result of writing a probe file into the configured backup directory (#2544). */
  3415. export interface LocalBackupPathCheck {
  3416. writable: boolean;
  3417. path: string;
  3418. /** 'ok' | 'sandboxed' | 'read_only' | 'permission_denied' | 'no_space' | 'not_a_directory' | 'missing' | 'error' */
  3419. code: string;
  3420. /** Raw OS error, shown as-is under the translated explanation. */
  3421. detail: string | null;
  3422. /** Copy-pasteable fix (systemd drop-in, compose snippet) — not translated. */
  3423. remedy: string | null;
  3424. message: string;
  3425. /** 'container_ephemeral' — writable, but the backups die with the container. */
  3426. warning: string | null;
  3427. }
  3428. export interface ObicoDetectionEvent {
  3429. printer_id: number;
  3430. task_name: string;
  3431. timestamp: string;
  3432. current_p: number;
  3433. score: number;
  3434. class: 'safe' | 'warning' | 'failure';
  3435. detections: number;
  3436. }
  3437. export interface ObicoStatus {
  3438. is_running: boolean;
  3439. last_error: string | null;
  3440. per_printer: Record<string, { class: string; frame_count: number; score: number }>;
  3441. thresholds: { low: number; high: number; pause?: number };
  3442. history: ObicoDetectionEvent[];
  3443. enabled: boolean;
  3444. ml_url: string;
  3445. sensitivity: 'low' | 'medium' | 'high';
  3446. action: 'notify' | 'pause' | 'pause_and_off';
  3447. poll_interval: number;
  3448. external_url_configured: boolean;
  3449. }
  3450. // Lightweight subset served under printers:read for the printer-card badge (#1546)
  3451. export interface ObicoPrinterStatus {
  3452. enabled: boolean;
  3453. // null = all printers are monitored
  3454. monitored_printers: number[] | null;
  3455. per_printer: Record<string, { class: string; frame_count: number; score: number }>;
  3456. // null = no error, or the viewer lacks settings:read (error strings can embed config URLs)
  3457. last_error: string | null;
  3458. }
  3459. export interface ObicoTestConnection {
  3460. ok: boolean;
  3461. status_code: number | null;
  3462. body: string | null;
  3463. error: string | null;
  3464. // Whether the ML API accepted the token. null = not determined (the health
  3465. // check failed first, or the token probe itself errored).
  3466. auth_ok: boolean | null;
  3467. }
  3468. // How sure Gadget must be before suggesting a warning or pause (API levels 1-5).
  3469. export type OctoEverywhereConfidence = 'lowest' | 'low' | 'medium' | 'high' | 'highest';
  3470. export interface OctoEverywhereDetection {
  3471. class: 'safe' | 'warning' | 'failure' | 'error' | 'unknown';
  3472. print_quality: number | null;
  3473. frame_count: number;
  3474. error?: string | null;
  3475. error_code: string | null;
  3476. }
  3477. export interface OctoEverywhereDetectionEvent {
  3478. timestamp: string;
  3479. printer_id: number;
  3480. class: OctoEverywhereDetection['class'];
  3481. print_quality: number | null;
  3482. }
  3483. export interface OctoEverywhereStatus {
  3484. enabled: boolean;
  3485. api_key_configured: boolean;
  3486. confidence: OctoEverywhereConfidence;
  3487. action: 'notify' | 'pause' | 'pause_and_off';
  3488. poll_interval: number;
  3489. is_running: boolean;
  3490. last_error: string | null;
  3491. last_error_code: string | null;
  3492. per_printer: Record<string, OctoEverywhereDetection>;
  3493. history: OctoEverywhereDetectionEvent[];
  3494. notifications: { configured: boolean; uncovered_printers: number[] };
  3495. }
  3496. export interface OctoEverywherePrinterStatus {
  3497. enabled: boolean;
  3498. // null = all printers are monitored
  3499. monitored_printers: number[] | null;
  3500. per_printer: Record<string, OctoEverywhereDetection>;
  3501. last_error: string | null;
  3502. last_error_code: string | null;
  3503. }
  3504. export interface OctoEverywhereTestConnection {
  3505. ok: boolean;
  3506. status_code: number | null;
  3507. error: string | null;
  3508. error_code: string | null;
  3509. }
  3510. export interface GitHubTestConnectionResponse {
  3511. success: boolean;
  3512. message: string;
  3513. repo_name: string | null;
  3514. permissions: Record<string, boolean> | null;
  3515. // true = confirmed private, false = confirmed public/internal,
  3516. // null = could not determine. Backend rejects save unless true.
  3517. is_private: boolean | null;
  3518. }
  3519. export interface GitHubBackupTriggerResponse {
  3520. success: boolean;
  3521. message: string;
  3522. log_id: number | null;
  3523. commit_sha: string | null;
  3524. files_changed: number;
  3525. }
  3526. export interface NotificationTestRequest {
  3527. provider_type: ProviderType;
  3528. config: Record<string, unknown>;
  3529. attach_photo?: boolean;
  3530. /** The saved provider being edited: its stored secrets fill in the placeholders. */
  3531. provider_id?: number;
  3532. }
  3533. export interface NotificationTestResponse {
  3534. success: boolean;
  3535. message: string;
  3536. }
  3537. // Provider-specific config types for reference
  3538. export interface CallMeBotConfig {
  3539. phone: string;
  3540. apikey: string;
  3541. }
  3542. export interface NtfyConfig {
  3543. server?: string;
  3544. topic: string;
  3545. auth_token?: string | null;
  3546. }
  3547. export interface PushoverConfig {
  3548. user_key: string;
  3549. app_token: string;
  3550. priority?: number;
  3551. }
  3552. export interface NotifyConfig {
  3553. device_id: string;
  3554. token: string;
  3555. icon_url?: string;
  3556. group_type?: string;
  3557. live_activities?: boolean;
  3558. lock_screen_widgets?: boolean;
  3559. live_activity_privacy?: boolean;
  3560. live_activity_stage?: boolean;
  3561. live_activity_style?: 'bar' | 'segments' | 'none';
  3562. live_activity_metrics?: ('progress' | 'eta' | 'layers' | 'nozzle' | 'bed' | 'chamber')[];
  3563. live_activity_button_url?: string;
  3564. live_activity_symbol?: string;
  3565. live_activity_tint?: string;
  3566. time_sensitive?: boolean;
  3567. }
  3568. export interface TelegramConfig {
  3569. bot_token: string;
  3570. chat_id: string;
  3571. }
  3572. export interface EmailConfig {
  3573. smtp_server: string;
  3574. smtp_port?: number;
  3575. username: string;
  3576. password: string;
  3577. from_email: string;
  3578. to_email: string;
  3579. use_tls?: boolean;
  3580. }
  3581. // Notification Template types
  3582. export interface NotificationTemplate {
  3583. id: number;
  3584. event_type: string;
  3585. name: string;
  3586. title_template: string;
  3587. body_template: string;
  3588. is_default: boolean;
  3589. created_at: string;
  3590. updated_at: string;
  3591. }
  3592. export interface NotificationTemplateUpdate {
  3593. title_template?: string;
  3594. body_template?: string;
  3595. }
  3596. export interface EventVariablesResponse {
  3597. event_type: string;
  3598. event_name: string;
  3599. variables: string[];
  3600. supports_photo: boolean;
  3601. }
  3602. export interface TemplatePreviewRequest {
  3603. event_type: string;
  3604. title_template: string;
  3605. body_template: string;
  3606. }
  3607. export interface TemplatePreviewResponse {
  3608. title: string;
  3609. body: string;
  3610. }
  3611. // Notification Log types
  3612. export interface NotificationLogEntry {
  3613. id: number;
  3614. provider_id: number;
  3615. provider_name: string | null;
  3616. provider_type: string | null;
  3617. event_type: string;
  3618. title: string;
  3619. message: string;
  3620. success: boolean;
  3621. error_message: string | null;
  3622. printer_id: number | null;
  3623. printer_name: string | null;
  3624. created_at: string;
  3625. }
  3626. export interface NotificationLogStats {
  3627. total: number;
  3628. success_count: number;
  3629. failure_count: number;
  3630. by_event_type: Record<string, number>;
  3631. by_provider: Record<string, number>;
  3632. }
  3633. // Spoolman types
  3634. export interface SpoolmanStatus {
  3635. enabled: boolean;
  3636. connected: boolean;
  3637. url: string | null;
  3638. native_tags?: boolean; // Spoolman 0.27+ links tags natively
  3639. }
  3640. export interface SpoolmanTagMigrationReport {
  3641. dry_run: boolean;
  3642. moved: number[];
  3643. already: number;
  3644. slot_ids: number;
  3645. conflicts: Array<{ spool_id: number; tag: string; holder: number }>; // holder -1: a filament holds the tag
  3646. }
  3647. export interface SkippedSpool {
  3648. location: string;
  3649. reason: string;
  3650. filament_type: string | null;
  3651. color: string | null;
  3652. }
  3653. export interface SpoolmanSyncResult {
  3654. success: boolean;
  3655. synced_count: number;
  3656. skipped_count: number;
  3657. skipped: SkippedSpool[];
  3658. errors: string[];
  3659. }
  3660. export interface UnlinkedSpool {
  3661. id: number;
  3662. filament_name: string | null;
  3663. filament_vendor: string | null;
  3664. filament_material: string | null;
  3665. filament_color_hex: string | null;
  3666. remaining_weight: number | null;
  3667. location: string | null;
  3668. }
  3669. export interface LinkedSpoolInfo {
  3670. id: number;
  3671. remaining_weight: number | null;
  3672. filament_weight: number | null;
  3673. }
  3674. export interface LinkedSpoolsMap {
  3675. linked: Record<string, LinkedSpoolInfo>; // tag (uppercase) -> spool info
  3676. }
  3677. export interface SpoolmanVendor {
  3678. id: number;
  3679. name: string;
  3680. }
  3681. export interface SpoolmanFilamentEntry {
  3682. id: number;
  3683. name: string;
  3684. material: string | null;
  3685. color_hex: string | null;
  3686. color_name: string | null;
  3687. weight: number | null;
  3688. spool_weight: number | null;
  3689. vendor: SpoolmanVendor | null;
  3690. }
  3691. // Inventory types
  3692. // Label printing (#809). Mirror of backend.app.services.label_renderer.TemplateName.
  3693. export type SpoolLabelTemplate =
  3694. | 'ams_holder_74x33'
  3695. | 'ams_holder_75x55'
  3696. | 'box_40x30'
  3697. | 'box_62x29'
  3698. | 'avery_5160'
  3699. | 'avery_l7160';
  3700. // Mirror of backend.app.services.label_renderer.LabelField, in print order (#2981).
  3701. export const SPOOL_LABEL_FIELDS = [
  3702. 'brand',
  3703. 'material',
  3704. 'hex',
  3705. 'name',
  3706. 'location',
  3707. 'material_number',
  3708. 'temps',
  3709. 'weight',
  3710. 'note',
  3711. 'added',
  3712. 'qr',
  3713. 'spool_id',
  3714. ] as const;
  3715. export type SpoolLabelField = (typeof SPOOL_LABEL_FIELDS)[number];
  3716. // Mirror of DEFAULT_LABEL_FIELDS: what a label carried before fields were selectable.
  3717. export const DEFAULT_SPOOL_LABEL_FIELDS: SpoolLabelField[] = [
  3718. 'brand',
  3719. 'material',
  3720. 'hex',
  3721. 'name',
  3722. 'location',
  3723. 'qr',
  3724. 'spool_id',
  3725. ];
  3726. // A sheet of identical labels in a grid, in millimetres (#3296). Mirror of
  3727. // backend.app.schemas.label_template.SheetLayoutSpec.
  3728. export type LabelPageSize = 'a4' | 'letter';
  3729. export interface LabelSheetLayout {
  3730. page: LabelPageSize;
  3731. label_w_mm: number;
  3732. label_h_mm: number;
  3733. cols: number;
  3734. rows: number;
  3735. top_mm: number;
  3736. left_mm: number;
  3737. col_gap_mm: number;
  3738. row_gap_mm: number;
  3739. }
  3740. // A custom sheet saved under a name, shared by everyone on the install.
  3741. export interface SavedLabelTemplate {
  3742. id: number;
  3743. name: string;
  3744. layout: LabelSheetLayout;
  3745. created_at: string;
  3746. updated_at: string;
  3747. }
  3748. // A built-in template, or "custom" with the sheet itself in ``layout``.
  3749. export type SpoolLabelRequestTemplate = SpoolLabelTemplate | 'custom';
  3750. export interface PrintSpoolLabelsRequest {
  3751. spool_ids: number[];
  3752. template: SpoolLabelRequestTemplate;
  3753. layout?: LabelSheetLayout;
  3754. monochrome: boolean;
  3755. starting_position: number;
  3756. fields?: SpoolLabelField[];
  3757. format?: 'pdf' | 'png';
  3758. dpi?: 203 | 300 | 600;
  3759. }
  3760. export interface PreviewSpoolLabelRequest {
  3761. spool_id: number;
  3762. template: SpoolLabelRequestTemplate;
  3763. layout?: LabelSheetLayout;
  3764. monochrome: boolean;
  3765. fields: SpoolLabelField[];
  3766. }
  3767. export interface InventorySpool {
  3768. id: number;
  3769. material: string;
  3770. subtype: string | null;
  3771. color_name: string | null;
  3772. // True when color_name was synthesised from subtype because Spoolman has no
  3773. // stored value (Spoolman-backed inventory only). The edit form uses this to
  3774. // leave the input blank, so the user doesn't round-trip the synth value
  3775. // back to Spoolman as if it were a real user-set color_name (#1319).
  3776. color_name_is_synthesized?: boolean;
  3777. rgba: string | null;
  3778. // Multi-colour gradient stops (#1154): comma-separated 6/8-char hex.
  3779. extra_colors: string | null;
  3780. // Visual effect overlay: sparkle | wood | marble | glow | matte.
  3781. effect_type: string | null;
  3782. brand: string | null;
  3783. label_weight: number;
  3784. core_weight: number;
  3785. // Spoolman-backed inventory only: true when the spool has no tare of its
  3786. // own and core_weight is the filament type's. Absent for local spools (#2908).
  3787. core_weight_is_inherited?: boolean;
  3788. core_weight_catalog_id: number | null;
  3789. weight_used: number;
  3790. // Anchor for the resettable "Total Consumed" display (#1390). The
  3791. // counter shown on the Inventory page is `weight_used - weight_used_baseline`;
  3792. // remaining is still `label_weight - weight_used`, so "Reset usage to 0"
  3793. // zeroes the counter without disturbing remaining. Optional for back-compat
  3794. // with rows from a pre-migration DB snapshot — default to 0.
  3795. weight_used_baseline?: number;
  3796. slicer_filament: string | null;
  3797. slicer_filament_name: string | null;
  3798. nozzle_temp_min: number | null;
  3799. nozzle_temp_max: number | null;
  3800. note: string | null;
  3801. added_full: boolean | null;
  3802. last_used: string | null;
  3803. // Spoolman mode: when the spool was first printed with (#3407).
  3804. first_used?: string | null;
  3805. // Last drying (#2863): stamped when an AMS drying run of at least half its
  3806. // length ends, or set by hand. Temperature and hours are null when unknown.
  3807. last_dried_at?: string | null;
  3808. last_dried_temp?: number | null;
  3809. last_dried_hours?: number | null;
  3810. encode_time: string | null;
  3811. tag_uid: string | null;
  3812. tray_uuid: string | null;
  3813. data_origin: string | null;
  3814. tag_type: string | null;
  3815. archived_at: string | null;
  3816. created_at: string;
  3817. updated_at: string;
  3818. cost_per_kg: number | null;
  3819. // Spoolman mode: what prints are charged per kg, the spool's own price or
  3820. // else its filament's. Display only; the form edits cost_per_kg.
  3821. effective_cost_per_kg?: number | null;
  3822. last_scale_weight: number | null;
  3823. last_weighed_at: string | null;
  3824. // User-defined category + per-spool low-stock threshold override (#729).
  3825. category: string | null;
  3826. low_stock_threshold_pct: number | null;
  3827. // Internal material / article number (#2870) — the purchasing identifier
  3828. // shared by all spools of the same product.
  3829. material_number: string | null;
  3830. k_profiles?: SpoolKProfile[];
  3831. storage_location?: string | null;
  3832. location_id?: number | null;
  3833. // Supplier assignments (#2988). Absent in Spoolman mode — Spoolman's
  3834. // vendor is the manufacturer, not the seller, so there is no mapping.
  3835. suppliers?: SpoolSupplierLink[];
  3836. }
  3837. // ── Suppliers (#2988) ──────────────────────────────────────────────────────
  3838. /** Where filament is bought — distinct from brand (who made it). */
  3839. export interface Supplier {
  3840. id: number;
  3841. name: string;
  3842. website: string | null;
  3843. customer_number: string | null;
  3844. note: string | null;
  3845. /** Spools referencing this supplier; a referenced supplier cannot be deleted. */
  3846. spool_count: number;
  3847. created_at: string;
  3848. updated_at: string;
  3849. }
  3850. export interface SupplierInput {
  3851. name: string;
  3852. website?: string | null;
  3853. customer_number?: string | null;
  3854. note?: string | null;
  3855. }
  3856. /** One spool-to-supplier assignment as written by the spool dialog. */
  3857. export interface SpoolSupplierLinkInput {
  3858. supplier_id: number;
  3859. /** The supplier's own article number — NOT the internal material number. */
  3860. supplier_article_number?: string | null;
  3861. /** Quoted price for comparison — never the cost basis (spool.cost_per_kg). */
  3862. quoted_price_per_kg?: number | null;
  3863. /** Marks where this concrete spool was actually bought. */
  3864. is_purchase_source?: boolean;
  3865. }
  3866. export interface SpoolSupplierLink {
  3867. id: number;
  3868. supplier_id: number;
  3869. supplier_name: string;
  3870. supplier_article_number: string | null;
  3871. quoted_price_per_kg: number | null;
  3872. is_purchase_source: boolean;
  3873. }
  3874. /** Per-supplier inventory aggregate (#2988), purchase-source spools only. */
  3875. export interface SupplierStats {
  3876. supplier_id: number;
  3877. supplier_name: string;
  3878. spool_count: number;
  3879. remaining_g: number;
  3880. consumed_g: number;
  3881. cost: number;
  3882. }
  3883. /** Per-material-number inventory aggregate (#2870). */
  3884. export interface MaterialNumberStats {
  3885. material_number: string;
  3886. spool_count: number;
  3887. remaining_g: number;
  3888. consumed_g: number;
  3889. cost: number;
  3890. }
  3891. export interface SpoolmanBulkCreateResult {
  3892. created: InventorySpool[];
  3893. requested_count: number;
  3894. failed_count: number;
  3895. }
  3896. // ── CSV import/export (#1576) ──────────────────────────────────────────────
  3897. /** One row's outcome from the import preview / real import. */
  3898. export interface CsvImportRow {
  3899. row_number: number;
  3900. status: 'valid' | 'error' | 'skipped';
  3901. reason: string | null;
  3902. material: string | null;
  3903. brand: string | null;
  3904. color_name: string | null;
  3905. rgba: string | null;
  3906. /** rgba/extra_colors/effect_type were filled from the Color Catalog. */
  3907. resolved_color: boolean;
  3908. /** The catalog match came from a different material's variant (no exact
  3909. * material match). Shown as a warning in the preview. */
  3910. cross_material_color: boolean;
  3911. /** An active spool with the same material+brand+color already exists.
  3912. * Informational only — the import still creates the row. */
  3913. duplicate_of_existing: boolean;
  3914. }
  3915. /** Dry-run preview: per-row classification, no rows written. */
  3916. export interface CsvImportPreview {
  3917. columns: string[];
  3918. total: number;
  3919. valid_count: number;
  3920. error_count: number;
  3921. skipped_count: number;
  3922. rows: CsvImportRow[];
  3923. warnings: string[];
  3924. }
  3925. /** Summary returned after a real (non-dry-run) import. */
  3926. export interface CsvImportResult {
  3927. created: number;
  3928. skipped: number;
  3929. errors: number;
  3930. error_rows: CsvImportRow[];
  3931. }
  3932. export interface SpoolUsageRecord {
  3933. id: number;
  3934. // null: the spool was deleted, its usage kept
  3935. spool_id: number | null;
  3936. // Spoolman mode: the Spoolman spool charged (#3407); spool_id is null then.
  3937. spoolman_spool_id?: number | null;
  3938. printer_id: number | null;
  3939. print_name: string | null;
  3940. weight_used: number;
  3941. percent_used: number;
  3942. status: string;
  3943. cost: number | null;
  3944. created_at: string;
  3945. }
  3946. export interface SpoolKProfile {
  3947. id: number;
  3948. spool_id: number;
  3949. printer_id: number;
  3950. extruder: number;
  3951. nozzle_diameter: string;
  3952. nozzle_type: string | null;
  3953. k_value: number;
  3954. name: string | null;
  3955. cali_idx: number | null;
  3956. setting_id: string | null;
  3957. created_at: string;
  3958. }
  3959. export interface SpoolKProfileInput {
  3960. printer_id: number;
  3961. extruder?: number;
  3962. nozzle_diameter?: string;
  3963. nozzle_type?: string | null;
  3964. k_value: number;
  3965. name?: string | null;
  3966. cali_idx?: number | null;
  3967. setting_id?: string | null;
  3968. }
  3969. /**
  3970. * One per-printer-model override of a spool's slicer filament preset.
  3971. *
  3972. * A cloud or Orca preset is bound to a printer model ("@BBL X1C"), so the
  3973. * spool's single `slicer_filament` is wrong as soon as the spool is used on a
  3974. * second model. `nozzle_diameter` is "" for the model's own default and a bare
  3975. * decimal ("0.2") for a per-hotend exception; the backend resolves
  3976. * exact (model, diameter) -> (model, "") -> the spool's own preset.
  3977. */
  3978. export interface SlotSpoolDefaults {
  3979. slicer_filament: string | null;
  3980. slicer_filament_name: string | null;
  3981. cali_idx: number | null;
  3982. k_value: number | null;
  3983. profile_name: string | null;
  3984. extruder: number | null;
  3985. nozzle_diameter: string;
  3986. }
  3987. export interface SpoolFilamentPresetInput {
  3988. printer_model: string;
  3989. nozzle_diameter: string;
  3990. slicer_filament: string | null;
  3991. slicer_filament_name: string | null;
  3992. }
  3993. export interface SpoolFilamentPreset extends SpoolFilamentPresetInput {
  3994. id: number;
  3995. spool_id: number;
  3996. created_at: string;
  3997. }
  3998. /**
  3999. * What a new spool of one product starts with (#1326): the slicer preset, the
  4000. * per-model preset overrides and the K profiles. `color_name` "" is the
  4001. * default for every colour of the product; one with a colour wins over it per
  4002. * preset and per hotend. Shared by both inventory modes.
  4003. */
  4004. export interface ProfileDefaultKey {
  4005. brand: string;
  4006. material: string;
  4007. subtype: string;
  4008. color_name: string;
  4009. }
  4010. export interface ProfileDefaultInput extends ProfileDefaultKey {
  4011. slicer_filament: string | null;
  4012. slicer_filament_name: string | null;
  4013. presets: SpoolFilamentPresetInput[];
  4014. k_profiles: SpoolKProfileInput[];
  4015. }
  4016. export interface ProfileDefault extends ProfileDefaultInput {
  4017. id: number;
  4018. updated_at: string;
  4019. }
  4020. /** Both levels of a product's default merged, as a create applies them. */
  4021. export interface ResolvedProfileDefault {
  4022. slicer_filament: string | null;
  4023. slicer_filament_name: string | null;
  4024. presets: SpoolFilamentPresetInput[];
  4025. k_profiles: SpoolKProfileInput[];
  4026. default_ids: number[];
  4027. }
  4028. /** One inventory-bound AMS slot, as returned by `/printers/{id}/inventory-remain`. */
  4029. export interface SlotMaterial {
  4030. ams_id: number;
  4031. tray_id: number;
  4032. global_tray_id: number;
  4033. /** Opaque grouping key from the backend. Two slots back each other up under
  4034. * AMS Filament Backup only when both `material_key` and `extruder` match.
  4035. * Never parse it — the format belongs to the backend's identity rule. */
  4036. material_key: string;
  4037. remaining_g: number;
  4038. /** 0 = right / single nozzle, 1 = left. */
  4039. extruder: number;
  4040. /** How the bound spool should be *named* — display only, never matched on.
  4041. * The printer has no brand field and reports no sub-brand for a
  4042. * third-party spool, so this is the only place a slot's real identity
  4043. * exists. Null when the binding resolves to a spool we cannot describe. */
  4044. spool?: SlotSpoolIdentity | null;
  4045. /** Per-kg rate a print off this spool is charged at; null when unpriced,
  4046. * which is charged at the default rate. Optional for an older backend. */
  4047. cost_per_kg?: number | null;
  4048. }
  4049. /** Display identity of an inventory-bound slot. See `SlotMaterial.spool`. */
  4050. export interface SlotSpoolIdentity {
  4051. brand: string | null;
  4052. material: string | null;
  4053. subtype: string | null;
  4054. color_name: string | null;
  4055. rgba: string | null;
  4056. /** Comma-separated hex stops for a multi-colour spool, and the effect
  4057. * overlay — the two things a tray record cannot carry, so a slot swatch
  4058. * can be drawn the way the inventory row draws it (#3159).
  4059. *
  4060. * Optional rather than required: the backend sends both keys on every
  4061. * binding, but a frontend running against an older one gets neither, and
  4062. * every reader here already falls back to a solid swatch. */
  4063. extra_colors?: string | null;
  4064. effect_type?: string | null;
  4065. }
  4066. export interface InventoryRemainResponse {
  4067. /** Currently-loaded, inventory-bound slots only — drives the prefer-lowest sort. */
  4068. inventory_remain_g: Record<string, number>;
  4069. /** Every inventory binding on the printer, with identity + extruder side. */
  4070. slot_materials: SlotMaterial[];
  4071. }
  4072. export interface SpoolAssignment {
  4073. id: number;
  4074. spool_id: number;
  4075. printer_id: number;
  4076. printer_name: string | null;
  4077. ams_id: number;
  4078. tray_id: number;
  4079. fingerprint_color: string | null;
  4080. fingerprint_type: string | null;
  4081. spool?: InventorySpool | null;
  4082. configured: boolean;
  4083. pending_config?: boolean; // Slot was empty at assign time; will configure on insert
  4084. created_at: string;
  4085. ams_label?: string | null; // User-defined friendly name for the AMS unit
  4086. printer_model?: string | null; // names a rack printer's external inputs "Ext-n" (utils/trayIds)
  4087. }
  4088. export interface FilamentSkuSettings {
  4089. id: number;
  4090. material: string;
  4091. subtype: string | null;
  4092. brand: string | null;
  4093. color_name: string | null;
  4094. lead_time_days: number;
  4095. safety_margin_value: number;
  4096. safety_margin_unit: 'days' | 'g';
  4097. alerts_snoozed: boolean;
  4098. }
  4099. export interface ShoppingListItem {
  4100. id: number;
  4101. material: string;
  4102. subtype: string | null;
  4103. brand: string | null;
  4104. color_name: string | null;
  4105. quantity_spools: number;
  4106. note: string | null;
  4107. status: 'pending' | 'purchased' | 'received';
  4108. purchased_at: string | null;
  4109. added_at: string;
  4110. }
  4111. export interface ShoppingListItemCreate {
  4112. material: string;
  4113. subtype: string | null;
  4114. brand: string | null;
  4115. color_name: string | null;
  4116. quantity_spools: number;
  4117. note?: string | null;
  4118. }
  4119. // Update types
  4120. export interface VersionInfo {
  4121. version: string;
  4122. repo: string;
  4123. }
  4124. export interface UpdateCheckResult {
  4125. update_available: boolean;
  4126. current_version: string;
  4127. latest_version: string | null;
  4128. release_name?: string;
  4129. release_notes?: string;
  4130. release_url?: string;
  4131. published_at?: string;
  4132. error?: string;
  4133. message?: string;
  4134. is_docker?: boolean;
  4135. is_ha_addon?: boolean;
  4136. is_windows_installer?: boolean;
  4137. update_method?: 'docker' | 'git' | 'ha_addon' | 'windows_installer';
  4138. installer_download_url?: string | null;
  4139. // Best-effort guess at the compose directory (#2664). Prefill only — the
  4140. // value the user saved lives on AppSettings.docker_compose_dir, so clearing
  4141. // that field falls back to this guess instead of resurrecting the old value.
  4142. compose_dir_detected?: string | null;
  4143. }
  4144. export interface UpdateStatus {
  4145. status: 'idle' | 'checking' | 'downloading' | 'installing' | 'complete' | 'error';
  4146. progress: number;
  4147. message: string;
  4148. error: string | null;
  4149. }
  4150. // Maintenance types
  4151. export interface MaintenanceType {
  4152. id: number;
  4153. name: string;
  4154. description: string | null;
  4155. default_interval_hours: number;
  4156. interval_type: 'hours' | 'days'; // "hours" = print hours, "days" = calendar days
  4157. icon: string | null;
  4158. wiki_url: string | null; // Documentation link
  4159. is_system: boolean;
  4160. created_at: string;
  4161. }
  4162. export interface MaintenanceTypeCreate {
  4163. name: string;
  4164. description?: string | null;
  4165. default_interval_hours?: number;
  4166. interval_type?: 'hours' | 'days';
  4167. icon?: string | null;
  4168. wiki_url?: string | null;
  4169. }
  4170. export interface MaintenanceStatus {
  4171. id: number;
  4172. printer_id: number;
  4173. printer_name: string;
  4174. printer_model: string | null;
  4175. maintenance_type_id: number;
  4176. maintenance_type_name: string;
  4177. maintenance_type_icon: string | null;
  4178. maintenance_type_wiki_url: string | null; // Custom wiki URL from type
  4179. enabled: boolean;
  4180. interval_hours: number; // For hours type: print hours; for days type: number of days
  4181. interval_type: 'hours' | 'days';
  4182. current_hours: number;
  4183. hours_since_maintenance: number;
  4184. hours_until_due: number;
  4185. days_since_maintenance: number | null; // For days type
  4186. days_until_due: number | null; // For days type
  4187. is_due: boolean;
  4188. is_warning: boolean;
  4189. last_performed_at: string | null;
  4190. }
  4191. export interface PrinterMaintenanceOverview {
  4192. printer_id: number;
  4193. printer_name: string;
  4194. printer_model: string | null;
  4195. total_print_hours: number;
  4196. maintenance_items: MaintenanceStatus[];
  4197. due_count: number;
  4198. warning_count: number;
  4199. }
  4200. // External Links (sidebar)
  4201. export interface ExternalLink {
  4202. id: number;
  4203. name: string;
  4204. url: string;
  4205. icon: string;
  4206. open_in_new_tab: boolean;
  4207. custom_icon: string | null;
  4208. sort_order: number;
  4209. created_at: string;
  4210. updated_at: string;
  4211. /** Count reported by the app the link points to, while it keeps reporting. */
  4212. badge_count?: number | null;
  4213. }
  4214. export interface ExternalLinkCreate {
  4215. name: string;
  4216. url: string;
  4217. icon: string;
  4218. open_in_new_tab?: boolean;
  4219. }
  4220. export interface ExternalLinkUpdate {
  4221. name?: string;
  4222. url?: string;
  4223. icon?: string;
  4224. open_in_new_tab?: boolean;
  4225. }
  4226. // Finance types
  4227. export interface CostCenterSummary {
  4228. id: number;
  4229. name: string;
  4230. is_private: boolean;
  4231. owner_user_id: number | null;
  4232. is_active: boolean;
  4233. total_balance: number;
  4234. total_budget: number | null;
  4235. monthly_budget: number | null;
  4236. budget_mode: 'none' | 'total' | 'monthly';
  4237. budget_limit: number | null;
  4238. budget_used: number | null;
  4239. budget_available: number | null;
  4240. can_print: boolean;
  4241. }
  4242. export interface CostCenterCreateRequest {
  4243. name: string;
  4244. total_budget?: number | null;
  4245. monthly_budget?: number | null;
  4246. is_active?: boolean;
  4247. }
  4248. export interface CostCenterBudgetUpdateRequest {
  4249. total_budget?: number | null;
  4250. monthly_budget?: number | null;
  4251. }
  4252. export interface CostCenterUpdateRequest {
  4253. name?: string;
  4254. is_active?: boolean;
  4255. }
  4256. export interface CostCenterMemberRequest {
  4257. user_id: number;
  4258. can_print?: boolean;
  4259. }
  4260. export interface CostCenterMemberResponse {
  4261. id: number;
  4262. cost_center_id: number;
  4263. user_id: number;
  4264. can_print: boolean;
  4265. created_at: string;
  4266. }
  4267. export interface CostCenterDetail extends CostCenterSummary {
  4268. members: CostCenterMemberResponse[];
  4269. }
  4270. export interface WalletBalance {
  4271. user_id: number;
  4272. balance: number;
  4273. currency: string;
  4274. updated_at: string | null;
  4275. }
  4276. export type WalletTransactionType = 'print_charge' | 'deposit' | 'withdraw' | 'manual_adjustment';
  4277. export interface WalletTransaction {
  4278. id: number;
  4279. user_id: number | null; // null once the user is deleted
  4280. cost_center_id: number | null;
  4281. transaction_type: WalletTransactionType;
  4282. amount: number;
  4283. balance_after: number | null;
  4284. description: string | null;
  4285. created_by_user_id: number | null;
  4286. print_run_id: string | null;
  4287. print_archive_id: number | null;
  4288. print_queue_id: number | null;
  4289. created_at: string;
  4290. }
  4291. export interface WalletTransactionListResponse {
  4292. items: WalletTransaction[];
  4293. total: number;
  4294. limit: number;
  4295. offset: number;
  4296. }
  4297. export interface WalletAdjustmentRequest {
  4298. amount: number;
  4299. description?: string;
  4300. cost_center_id?: number | null;
  4301. }
  4302. export interface WalletAdjustmentResponse {
  4303. transaction: WalletTransaction;
  4304. balance: WalletBalance;
  4305. }
  4306. export interface TransactionEditRequest {
  4307. user_id?: number | null;
  4308. cost_center_id?: number | null;
  4309. amount?: number | null;
  4310. description?: string | null;
  4311. }
  4312. export interface ManualPrintRequest {
  4313. user_id: number;
  4314. cost_center_id: number;
  4315. amount: number;
  4316. description?: string | null;
  4317. created_at?: string | null;
  4318. }
  4319. // Permission type - all available permissions
  4320. export type Permission =
  4321. | 'printers:read' | 'printers:create' | 'printers:update' | 'printers:delete' | 'printers:control' | 'printers:files' | 'printers:ams_rfid' | 'printers:clear_plate'
  4322. | 'archives:read' | 'archives:read_own' | 'archives:read_all' | 'archives:create'
  4323. | 'archives:update_own' | 'archives:update_all' | 'archives:delete_own' | 'archives:delete_all'
  4324. | 'archives:reprint_own' | 'archives:reprint_all' | 'archives:purge'
  4325. | 'queue:read' | 'queue:read_own' | 'queue:read_all' | 'queue:create'
  4326. | 'queue:update_own' | 'queue:update_all' | 'queue:delete_own' | 'queue:delete_all'
  4327. | 'queue:reorder' | 'queue:start_unreviewed'
  4328. | 'library:read' | 'library:read_own' | 'library:read_all' | 'library:upload'
  4329. | 'library:update_own' | 'library:update_all' | 'library:delete_own' | 'library:delete_all'
  4330. | 'library:purge'
  4331. | 'projects:read' | 'projects:create' | 'projects:update' | 'projects:delete'
  4332. | 'filaments:read' | 'filaments:create' | 'filaments:update' | 'filaments:delete'
  4333. | 'inventory:read' | 'inventory:create' | 'inventory:update' | 'inventory:delete' | 'inventory:view_assignments'
  4334. | 'inventory:forecast_read' | 'inventory:forecast_write'
  4335. | 'smart_plugs:read' | 'smart_plugs:create' | 'smart_plugs:update' | 'smart_plugs:delete' | 'smart_plugs:control'
  4336. | 'camera:view'
  4337. | 'maintenance:read' | 'maintenance:create' | 'maintenance:update' | 'maintenance:delete'
  4338. | 'kprofiles:read' | 'kprofiles:create' | 'kprofiles:update' | 'kprofiles:delete'
  4339. | 'notifications:read' | 'notifications:create' | 'notifications:update' | 'notifications:delete' | 'notifications:user_email'
  4340. | 'notification_templates:read' | 'notification_templates:update'
  4341. | 'external_links:read' | 'external_links:create' | 'external_links:update' | 'external_links:delete'
  4342. | 'discovery:scan'
  4343. | 'firmware:read' | 'firmware:update'
  4344. | 'ams_history:read'
  4345. | 'cost_centers:read_own' | 'cost_centers:read_all' | 'cost_centers:modify' | 'cost_centers:create'
  4346. | 'stats:read' | 'stats:filter_by_user'
  4347. | 'system:read'
  4348. | 'settings:read' | 'settings:update' | 'settings:backup' | 'settings:restore'
  4349. | 'github:backup' | 'github:restore'
  4350. | 'cloud:auth' | 'orca_cloud:auth'
  4351. | 'makerworld:view' | 'makerworld:import'
  4352. | 'manyfold:view' | 'manyfold:import'
  4353. | 'api_keys:read' | 'api_keys:create' | 'api_keys:update' | 'api_keys:delete'
  4354. | 'users:read' | 'users:read_slim' | 'users:create' | 'users:update' | 'users:delete'
  4355. | 'groups:read' | 'groups:create' | 'groups:update' | 'groups:delete'
  4356. | 'pipelines:read' | 'pipelines:write' | 'pipelines:run'
  4357. | 'websocket:connect';
  4358. // Group types
  4359. export interface GroupBrief {
  4360. id: number;
  4361. name: string;
  4362. }
  4363. export interface Group {
  4364. id: number;
  4365. name: string;
  4366. description: string | null;
  4367. permissions: Permission[];
  4368. is_system: boolean;
  4369. /** Members only see the printers in printer_ids plus every printer in locations (#1727) */
  4370. restrict_printers: boolean;
  4371. printer_ids: number[];
  4372. /** Matched against Printer.location, so printers added there later are included */
  4373. locations: string[];
  4374. user_count: number;
  4375. created_at: string;
  4376. updated_at: string;
  4377. }
  4378. export interface GroupDetail extends Group {
  4379. users: Array<{ id: number; username: string; is_active: boolean }>;
  4380. }
  4381. export interface GroupCreate {
  4382. name: string;
  4383. description?: string;
  4384. permissions: Permission[];
  4385. restrict_printers?: boolean;
  4386. printer_ids?: number[];
  4387. locations?: string[];
  4388. }
  4389. export interface GroupUpdate {
  4390. name?: string;
  4391. description?: string;
  4392. permissions?: Permission[];
  4393. restrict_printers?: boolean;
  4394. printer_ids?: number[];
  4395. locations?: string[];
  4396. }
  4397. export interface PermissionInfo {
  4398. value: Permission;
  4399. label: string;
  4400. }
  4401. export interface PermissionCategory {
  4402. name: string;
  4403. permissions: PermissionInfo[];
  4404. }
  4405. export interface PermissionsListResponse {
  4406. categories: PermissionCategory[];
  4407. all_permissions: Permission[];
  4408. }
  4409. // User email notification preferences
  4410. export interface UserEmailPreferences {
  4411. notify_print_start: boolean;
  4412. notify_print_complete: boolean;
  4413. notify_print_failed: boolean;
  4414. notify_print_stopped: boolean;
  4415. }
  4416. // Auth types
  4417. export interface LoginRequest {
  4418. username: string;
  4419. password: string;
  4420. }
  4421. export interface LoginResponse {
  4422. access_token?: string;
  4423. token_type?: string;
  4424. user?: UserResponse;
  4425. /** Set when 2FA verification is required before a full token is issued. */
  4426. requires_2fa?: boolean;
  4427. pre_auth_token?: string;
  4428. two_fa_methods?: string[];
  4429. }
  4430. export interface UserResponse {
  4431. id: number;
  4432. username: string;
  4433. email?: string;
  4434. role: string; // Deprecated, kept for backward compatibility
  4435. is_active: boolean;
  4436. is_admin: boolean; // Computed from role and group membership
  4437. auth_source: string; // "local" or "ldap"
  4438. groups: GroupBrief[];
  4439. permissions: Permission[]; // All permissions from groups
  4440. created_at: string;
  4441. }
  4442. /**
  4443. * Just enough to label an owner id (#1894). Backed by GET /users/slim, which
  4444. * is readable with `users:read_slim` as well as the admin-level `users:read`
  4445. * -- use it anywhere a screen only needs to turn a `created_by_id` into a
  4446. * name, so operators are not forced into the full listing to get one.
  4447. */
  4448. export interface UserSlim {
  4449. id: number;
  4450. username: string;
  4451. }
  4452. export interface UserCreate {
  4453. username: string;
  4454. password?: string; // Optional when advanced auth is enabled
  4455. email?: string;
  4456. role: string;
  4457. group_ids?: number[];
  4458. }
  4459. export interface UserUpdate {
  4460. username?: string;
  4461. password?: string;
  4462. email?: string;
  4463. role?: string;
  4464. is_active?: boolean;
  4465. group_ids?: number[];
  4466. }
  4467. export interface SetupRequest {
  4468. auth_enabled: boolean;
  4469. admin_username?: string;
  4470. admin_password?: string;
  4471. }
  4472. export interface ForgotPasswordRequest {
  4473. email: string;
  4474. }
  4475. export interface ForgotPasswordResponse {
  4476. message: string;
  4477. }
  4478. export interface ResetPasswordRequest {
  4479. user_id: number;
  4480. }
  4481. export interface ResetPasswordResponse {
  4482. message: string;
  4483. }
  4484. export interface SMTPSettings {
  4485. smtp_host: string;
  4486. smtp_port: number;
  4487. smtp_username?: string;
  4488. smtp_password?: string;
  4489. smtp_security: 'starttls' | 'ssl' | 'none';
  4490. smtp_auth_enabled: boolean;
  4491. smtp_from_email: string;
  4492. smtp_from_name: string;
  4493. }
  4494. // 2FA / MFA interfaces
  4495. export interface TwoFAStatus {
  4496. totp_enabled: boolean;
  4497. email_otp_enabled: boolean;
  4498. backup_codes_remaining: number;
  4499. }
  4500. export interface TOTPSetupResponse {
  4501. secret: string;
  4502. qr_code_b64: string;
  4503. issuer: string;
  4504. }
  4505. export interface TOTPEnableResponse {
  4506. message: string;
  4507. backup_codes: string[];
  4508. }
  4509. export interface BackupCodesResponse {
  4510. backup_codes: string[];
  4511. message: string;
  4512. }
  4513. export interface TwoFAVerifyRequest {
  4514. pre_auth_token: string;
  4515. code: string;
  4516. method: 'totp' | 'email' | 'backup';
  4517. }
  4518. /**
  4519. * A URL that is known to be same-origin (a relative path starting with ``/``).
  4520. *
  4521. * Branded so that producers of same-origin URLs (e.g. ``api.oidcProviderIconUrl``)
  4522. * can be distinguished from arbitrary strings at the type level. The brand
  4523. * is compile-time only; at runtime these are plain strings.
  4524. *
  4525. * Purpose: CSP-safe image sources for ``<img src=...>``. The strict
  4526. * ``img-src 'self' data: blob:`` CSP rejects anything that isn't same-origin,
  4527. * so callers that demand a ``SameOriginUrl`` get a compile-time guarantee
  4528. * that no external URL slips through.
  4529. */
  4530. export type SameOriginUrl = string & { readonly __brand: 'SameOriginUrl' };
  4531. // OIDC interfaces
  4532. /** What the unauthenticated GET /auth/oidc/providers returns (#3107): only
  4533. * what the login page renders. The full provider, group sync config
  4534. * included, needs the admin-only /auth/oidc/providers/all. */
  4535. export interface OIDCProviderPublic {
  4536. id: number;
  4537. name: string;
  4538. has_icon: boolean;
  4539. is_autologin: boolean;
  4540. }
  4541. export interface OIDCProvider {
  4542. id: number;
  4543. name: string;
  4544. issuer_url: string;
  4545. client_id: string;
  4546. scopes: string;
  4547. is_enabled: boolean;
  4548. auto_create_users: boolean;
  4549. auto_link_existing_accounts: boolean;
  4550. email_claim: string;
  4551. require_email_verified: boolean;
  4552. // #3107 — group sync. Empty mapping = sync off (default).
  4553. group_claim?: string;
  4554. group_mapping?: Record<string, string>;
  4555. icon_url?: string | null;
  4556. default_group_id?: number | null;
  4557. // True when the backend has cached icon bytes for this provider.
  4558. // Login page / admin preview consume this via the proxy URL
  4559. // /api/v1/auth/oidc/providers/{id}/icon (#1333) so the SPA never
  4560. // hotlinks the external icon URL — that would require loosening
  4561. // the strict img-src CSP. Required, not optional: the backend always
  4562. // includes this field in the response (Pydantic default-False is
  4563. // populated unconditionally in the route handler).
  4564. has_icon: boolean;
  4565. // #1589: when true, the LoginPage redirects unauthenticated visitors
  4566. // straight to this provider on mount. At most one provider may carry this.
  4567. is_autologin: boolean;
  4568. // #2593: defined by BAMBUDDY_OIDC_* and rewritten from the environment on
  4569. // every boot. The API answers 409 to any write, so the settings UI must not
  4570. // offer edit/delete controls that cannot succeed. Optional so a response
  4571. // from an older backend still type-checks.
  4572. is_env_managed?: boolean;
  4573. }
  4574. export interface OIDCProviderCreate {
  4575. name: string;
  4576. issuer_url: string;
  4577. client_id: string;
  4578. client_secret: string;
  4579. scopes?: string;
  4580. is_enabled?: boolean;
  4581. auto_create_users?: boolean;
  4582. auto_link_existing_accounts?: boolean;
  4583. email_claim?: string;
  4584. require_email_verified?: boolean;
  4585. // #3107 — group sync. Omit both to leave them unchanged on update.
  4586. group_claim?: string;
  4587. group_mapping?: Record<string, string>;
  4588. icon_url?: string | null;
  4589. default_group_id?: number | null;
  4590. is_autologin?: boolean; // #1589
  4591. }
  4592. export interface OIDCLink {
  4593. id: number;
  4594. provider_id: number;
  4595. provider_name: string;
  4596. provider_email?: string | null;
  4597. created_at: string;
  4598. }
  4599. export interface TestSMTPRequest {
  4600. test_recipient: string;
  4601. // The form's settings, tested before they are saved. An empty password
  4602. // keeps the saved one.
  4603. smtp?: SMTPSettings;
  4604. }
  4605. export interface TestSMTPResponse {
  4606. success: boolean;
  4607. message: string;
  4608. }
  4609. export interface AdvancedAuthStatus {
  4610. advanced_auth_enabled: boolean;
  4611. smtp_configured: boolean;
  4612. // #1589: false hides the username/password form on the LoginPage; the env
  4613. // var BAMBUDDY_LOCAL_LOGIN=true on the server flips this back to true so
  4614. // the recovery path remains visible.
  4615. local_login_enabled: boolean;
  4616. // #1589: when set, LoginPage redirects to this provider's authorize URL
  4617. // on mount unless ?fallback=local is in the URL or the redirect times out.
  4618. autologin_provider_id: number | null;
  4619. }
  4620. export interface LDAPStatus {
  4621. ldap_enabled: boolean;
  4622. ldap_configured: boolean;
  4623. }
  4624. export interface EncryptionRowCounts {
  4625. oidc_providers: number;
  4626. user_totp: number;
  4627. }
  4628. export interface EncryptionStatus {
  4629. key_configured: boolean;
  4630. key_source: 'env' | 'file' | 'generated' | 'none';
  4631. legacy_plaintext_rows: EncryptionRowCounts;
  4632. encrypted_rows: EncryptionRowCounts;
  4633. decryption_broken: boolean;
  4634. // B2: count of rows skipped during the last legacy re-encryption migration.
  4635. // Surfaced via a yellow secondary banner in SecurityStatusCard.
  4636. migration_error_count: number;
  4637. }
  4638. export interface LDAPTestRequest {
  4639. ldap_server_url?: string;
  4640. ldap_bind_dn?: string;
  4641. ldap_bind_password?: string;
  4642. ldap_search_base?: string;
  4643. ldap_user_filter?: string;
  4644. ldap_security?: string;
  4645. }
  4646. export interface LDAPTestResponse {
  4647. success: boolean;
  4648. message: string;
  4649. }
  4650. export interface LDAPSearchResult {
  4651. username: string;
  4652. email: string | null;
  4653. display_name: string | null;
  4654. dn: string;
  4655. already_provisioned: boolean;
  4656. }
  4657. export interface SetupResponse {
  4658. auth_enabled: boolean;
  4659. admin_created?: boolean;
  4660. }
  4661. export interface AuthStatus {
  4662. auth_enabled: boolean;
  4663. requires_setup: boolean;
  4664. }
  4665. // API functions
  4666. export interface QueueHistoryFilters {
  4667. printerId?: number | null;
  4668. status?: string;
  4669. location?: string;
  4670. }
  4671. export interface QueueHistoryParams extends QueueHistoryFilters {
  4672. sortBy?: 'date' | 'name' | 'printer';
  4673. // Flips the default order: newest first by date, A to Z by name or printer.
  4674. reverse?: boolean;
  4675. limit?: number;
  4676. offset?: number;
  4677. }
  4678. export interface QueueHistoryPage {
  4679. // The page in display order, then any other runs of the batches on it.
  4680. items: PrintQueueItem[];
  4681. total: number;
  4682. locations: string[];
  4683. }
  4684. function queueHistorySearch(params: QueueHistoryParams): URLSearchParams {
  4685. const search = new URLSearchParams();
  4686. if (params.printerId) search.set('printer_id', String(params.printerId));
  4687. if (params.status) search.set('status', params.status);
  4688. if (params.location) search.set('location', params.location);
  4689. if (params.sortBy) search.set('sort_by', params.sortBy);
  4690. if (params.reverse) search.set('reverse', 'true');
  4691. if (params.limit !== undefined) search.set('limit', String(params.limit));
  4692. if (params.offset) search.set('offset', String(params.offset));
  4693. return search;
  4694. }
  4695. // Per-printer reads that a page showing every printer makes once per printer,
  4696. // coalesced into one bulk request per few milliseconds (see ./batch). Each
  4697. // keeps its single-printer request for a lone id.
  4698. const idsParam = (ids: number[]) => `ids=${ids.join(',')}`;
  4699. const printerStatusBatch = batched(
  4700. (id) => request<PrinterStatus>(`/printers/${id}/status`),
  4701. async (ids) => byField(await request<PrinterStatus[]>(`/bulk/printer-statuses?${idsParam(ids)}`), (s) => s.id),
  4702. );
  4703. const slotPresetsBatch = batched(
  4704. (id) => request<Record<number, SlotPresetMapping>>(`/printers/${id}/slot-presets`),
  4705. async (ids) => byId(await request<Record<string, Record<number, SlotPresetMapping>>>(`/bulk/slot-presets?${idsParam(ids)}`)),
  4706. );
  4707. const amsLabelsBatch = batched(
  4708. (id) => request<Record<number, string>>(`/printers/${id}/ams-labels`),
  4709. async (ids) => byId(await request<Record<string, Record<number, string>>>(`/bulk/ams-labels?${idsParam(ids)}`)),
  4710. );
  4711. type PrinterCardPlugs = { plug: SmartPlug | null; scripts: SmartPlug[] };
  4712. const cardPlugs = async (ids: number[]) =>
  4713. byId(await request<Record<string, PrinterCardPlugs>>(`/bulk/card-plugs?${idsParam(ids)}`));
  4714. const smartPlugBatch = batched(
  4715. (id) => request<SmartPlug | null>(`/smart-plugs/by-printer/${id}`),
  4716. async (ids) => new Map([...(await cardPlugs(ids))].map(([id, plugs]) => [id, plugs.plug])),
  4717. );
  4718. const scriptPlugsBatch = batched(
  4719. (id) => request<SmartPlug[]>(`/smart-plugs/by-printer/${id}/scripts`),
  4720. async (ids) => new Map([...(await cardPlugs(ids))].map(([id, plugs]) => [id, plugs.scripts])),
  4721. );
  4722. const haSensorReadingsBatch = batched(
  4723. (id) => request<PrinterHASensorReading[]>(`/ha-sensors/by-printer/${id}/readings`),
  4724. async (ids) => byId(await request<Record<string, PrinterHASensorReading[]>>(`/bulk/ha-sensor-readings?${idsParam(ids)}`)),
  4725. );
  4726. const firmwareUpdateBatch = batched(
  4727. (id) => request<FirmwareUpdateInfo>(`/firmware/updates/${id}`),
  4728. async (ids) =>
  4729. byField(await request<FirmwareUpdateInfo[]>(`/bulk/firmware-updates?${idsParam(ids)}`), (u) => u.printer_id),
  4730. );
  4731. // One batcher per status asked for: the bulk route takes a single status list.
  4732. const printerQueueBatches = new Map<string, (id: number) => Promise<PrintQueueItem[]>>();
  4733. const printerQueueBatch = (status: string) => {
  4734. let batch = printerQueueBatches.get(status);
  4735. if (!batch) {
  4736. batch = batched(
  4737. (id) => request<PrintQueueItem[]>(`/queue/?printer_id=${id}&status=${encodeURIComponent(status)}`),
  4738. async (ids) =>
  4739. byId(
  4740. await request<Record<string, PrintQueueItem[]>>(
  4741. `/bulk/printer-queues?${idsParam(ids)}&status=${encodeURIComponent(status)}`,
  4742. ),
  4743. ),
  4744. );
  4745. printerQueueBatches.set(status, batch);
  4746. }
  4747. return batch;
  4748. };
  4749. const foldersByArchiveBatch = batched(
  4750. (id) => request<LibraryFolder[]>(`/library/folders/by-archive/${id}`),
  4751. async (ids) => byId(await request<Record<string, LibraryFolder[]>>(`/bulk/archive-folders?${idsParam(ids)}`)),
  4752. );
  4753. export const api = {
  4754. // Overlay branding
  4755. getOverlayLogo: async (token: string | null, signal?: AbortSignal): Promise<Blob | null> => {
  4756. const endpoint = token ? `/overlay-branding/logo?token=${encodeURIComponent(token)}` : '/settings/overlay-logo';
  4757. const response = await fetch(`${API_BASE}${endpoint}`, {
  4758. signal, cache: 'no-store',
  4759. headers: !token && authToken ? { Authorization: `Bearer ${authToken}` } : {},
  4760. });
  4761. if (response.status === 404) return null;
  4762. if (!response.ok) throw new Error(`HTTP ${response.status}`);
  4763. return response.blob();
  4764. },
  4765. uploadOverlayLogo: async (file: File): Promise<void> => {
  4766. const body = new FormData();
  4767. body.append('file', file);
  4768. const response = await fetch(`${API_BASE}/settings/overlay-logo`, {
  4769. method: 'POST', body,
  4770. headers: authToken ? { Authorization: `Bearer ${authToken}` } : {},
  4771. });
  4772. if (!response.ok) {
  4773. const error = await response.json().catch(() => ({}));
  4774. const detail = error?.detail;
  4775. const message = typeof detail === 'string' ? detail : detail?.message;
  4776. throw new Error(typeof message === 'string' && message ? message : `HTTP ${response.status}`);
  4777. }
  4778. },
  4779. deleteOverlayLogo: () => request<{ status: string }>('/settings/overlay-logo', { method: 'DELETE' }),
  4780. // Authentication
  4781. getAuthStatus: () => request<AuthStatus>('/auth/status'),
  4782. setupAuth: (data: SetupRequest) =>
  4783. request<SetupResponse>('/auth/setup', {
  4784. method: 'POST',
  4785. body: JSON.stringify(data),
  4786. }),
  4787. login: (data: LoginRequest) =>
  4788. request<LoginResponse>('/auth/login', {
  4789. method: 'POST',
  4790. body: JSON.stringify(data),
  4791. }),
  4792. logout: () =>
  4793. request<{ message: string }>('/auth/logout', {
  4794. method: 'POST',
  4795. }),
  4796. getCurrentUser: () => request<UserResponse>('/auth/me'),
  4797. disableAuth: () =>
  4798. request<{ message: string; auth_enabled: boolean }>('/auth/disable', {
  4799. method: 'POST',
  4800. }),
  4801. // Advanced Authentication
  4802. testSMTP: (data: TestSMTPRequest) =>
  4803. request<TestSMTPResponse>('/auth/smtp/test', {
  4804. method: 'POST',
  4805. body: JSON.stringify(data),
  4806. }),
  4807. getSMTPSettings: () => request<SMTPSettings | null>('/auth/smtp'),
  4808. saveSMTPSettings: (data: SMTPSettings) =>
  4809. request<{ message: string }>('/auth/smtp', {
  4810. method: 'POST',
  4811. body: JSON.stringify(data),
  4812. }),
  4813. enableAdvancedAuth: () =>
  4814. request<{ message: string; advanced_auth_enabled: boolean }>('/auth/advanced-auth/enable', {
  4815. method: 'POST',
  4816. }),
  4817. disableAdvancedAuth: () =>
  4818. request<{ message: string; advanced_auth_enabled: boolean }>('/auth/advanced-auth/disable', {
  4819. method: 'POST',
  4820. }),
  4821. getAdvancedAuthStatus: () => request<AdvancedAuthStatus>('/auth/advanced-auth/status'),
  4822. // LDAP Authentication
  4823. getLDAPStatus: () => request<LDAPStatus>('/auth/ldap/status'),
  4824. getEncryptionStatus: () => request<EncryptionStatus>('/auth/encryption-status'),
  4825. // form: the settings being edited, tested before they are saved. An empty
  4826. // bind password keeps the saved one.
  4827. testLDAP: (form?: LDAPTestRequest) =>
  4828. request<LDAPTestResponse>('/auth/ldap/test', {
  4829. method: 'POST',
  4830. ...(form ? { body: JSON.stringify(form) } : {}),
  4831. }),
  4832. searchLDAPDirectory: (q: string) =>
  4833. request<LDAPSearchResult[]>(`/auth/ldap/search?q=${encodeURIComponent(q)}`),
  4834. provisionLDAPUser: (username: string) =>
  4835. request<UserResponse>('/auth/ldap/provision', {
  4836. method: 'POST',
  4837. body: JSON.stringify({ username }),
  4838. }),
  4839. forgotPassword: (data: ForgotPasswordRequest) =>
  4840. request<ForgotPasswordResponse>('/auth/forgot-password', {
  4841. method: 'POST',
  4842. body: JSON.stringify(data),
  4843. }),
  4844. // H-6: Confirm password reset using the token from the emailed link
  4845. forgotPasswordConfirm: (token: string, newPassword: string) =>
  4846. request<ForgotPasswordResponse>('/auth/forgot-password/confirm', {
  4847. method: 'POST',
  4848. body: JSON.stringify({ token, new_password: newPassword }),
  4849. }),
  4850. resetUserPassword: (data: ResetPasswordRequest) =>
  4851. request<ResetPasswordResponse>('/auth/reset-password', {
  4852. method: 'POST',
  4853. body: JSON.stringify(data),
  4854. }),
  4855. // 2FA - status
  4856. get2FAStatus: () => request<TwoFAStatus>('/auth/2fa/status'),
  4857. // 2FA - TOTP
  4858. setupTOTP: () => request<TOTPSetupResponse>('/auth/2fa/totp/setup', { method: 'POST' }),
  4859. enableTOTP: (code: string) =>
  4860. request<TOTPEnableResponse>('/auth/2fa/totp/enable', {
  4861. method: 'POST',
  4862. body: JSON.stringify({ code }),
  4863. }),
  4864. disableTOTP: (code: string) =>
  4865. request<{ message: string }>('/auth/2fa/totp/disable', {
  4866. method: 'POST',
  4867. body: JSON.stringify({ code }),
  4868. }),
  4869. regenerateBackupCodes: (code: string) =>
  4870. request<BackupCodesResponse>('/auth/2fa/totp/regenerate-backup-codes', {
  4871. method: 'POST',
  4872. body: JSON.stringify({ code }),
  4873. }),
  4874. // 2FA - Email OTP
  4875. // Step 1: send a verification code to the user's email (proof of possession)
  4876. enableEmailOTP: () =>
  4877. request<{ message: string; setup_token: string }>('/auth/2fa/email/enable', { method: 'POST' }),
  4878. // Step 2: confirm with the code received by email
  4879. confirmEnableEmailOTP: (setup_token: string, code: string) =>
  4880. request<{ message: string }>('/auth/2fa/email/enable/confirm', {
  4881. method: 'POST',
  4882. body: JSON.stringify({ setup_token, code }),
  4883. }),
  4884. // Disable requires account password for re-auth
  4885. disableEmailOTP: (password: string) =>
  4886. request<{ message: string }>('/auth/2fa/email/disable', {
  4887. method: 'POST',
  4888. body: JSON.stringify({ password }),
  4889. }),
  4890. sendEmailOTP: (preAuthToken: string) =>
  4891. request<{ message: string; pre_auth_token?: string }>('/auth/2fa/email/send', {
  4892. method: 'POST',
  4893. body: JSON.stringify({ pre_auth_token: preAuthToken }),
  4894. }),
  4895. // 2FA - verify (completes login)
  4896. verify2FA: (data: TwoFAVerifyRequest) =>
  4897. request<LoginResponse>('/auth/2fa/verify', {
  4898. method: 'POST',
  4899. body: JSON.stringify(data),
  4900. }),
  4901. // 2FA - admin
  4902. // adminPassword: the calling admin's own password; null for an admin
  4903. // without one (LDAP / OIDC accounts usually), whom the route does not ask.
  4904. admin2FADisable: (userId: number, adminPassword: string | null) =>
  4905. request<{ message: string; had_2fa: boolean }>(`/auth/2fa/admin/${userId}`, {
  4906. method: 'DELETE',
  4907. body: JSON.stringify({ admin_password: adminPassword }),
  4908. }),
  4909. // OIDC providers (public list)
  4910. getOIDCProviders: () => request<OIDCProviderPublic[]>('/auth/oidc/providers'),
  4911. // OIDC providers (admin)
  4912. getOIDCProvidersAll: () => request<OIDCProvider[]>('/auth/oidc/providers/all'),
  4913. createOIDCProvider: (data: OIDCProviderCreate) =>
  4914. request<OIDCProvider>('/auth/oidc/providers', {
  4915. method: 'POST',
  4916. body: JSON.stringify(data),
  4917. }),
  4918. updateOIDCProvider: (id: number, data: Partial<OIDCProviderCreate>) =>
  4919. request<OIDCProvider>(`/auth/oidc/providers/${id}`, {
  4920. method: 'PUT',
  4921. body: JSON.stringify(data),
  4922. }),
  4923. deleteOIDCProvider: (id: number) =>
  4924. request<{ message: string }>(`/auth/oidc/providers/${id}`, { method: 'DELETE' }),
  4925. // OIDC provider icon proxy (#1333) — same-origin path so the strict
  4926. // img-src CSP stays in force. Returns a SameOriginUrl-branded string
  4927. // so a future caller can't accidentally substitute an attacker-
  4928. // controlled URL where this is consumed.
  4929. oidcProviderIconUrl: (id: number): SameOriginUrl =>
  4930. `/api/v1/auth/oidc/providers/${id}/icon` as SameOriginUrl,
  4931. deleteOIDCProviderIcon: (id: number) =>
  4932. request<void>(`/auth/oidc/providers/${id}/icon`, { method: 'DELETE' }),
  4933. refreshOIDCProviderIcon: (id: number) =>
  4934. request<OIDCProvider>(`/auth/oidc/providers/${id}/icon/refresh`, { method: 'POST' }),
  4935. // OIDC authorize URL
  4936. getOIDCAuthorizeUrl: (providerId: number) =>
  4937. request<{ auth_url: string }>(`/auth/oidc/authorize/${providerId}`),
  4938. // OIDC exchange token for JWT
  4939. exchangeOIDCToken: (oidcToken: string) =>
  4940. request<LoginResponse>('/auth/oidc/exchange', {
  4941. method: 'POST',
  4942. body: JSON.stringify({ oidc_token: oidcToken }),
  4943. }),
  4944. // OIDC links for current user
  4945. getOIDCLinks: () => request<OIDCLink[]>('/auth/oidc/links'),
  4946. deleteOIDCLink: (providerId: number) =>
  4947. request<{ message: string }>(`/auth/oidc/links/${providerId}`, { method: 'DELETE' }),
  4948. // Users
  4949. getUsers: () => request<UserResponse[]>('/users/'),
  4950. getUsersSlim: () => request<UserSlim[]>('/users/slim'),
  4951. createUser: (data: UserCreate) =>
  4952. request<UserResponse>('/users/', {
  4953. method: 'POST',
  4954. body: JSON.stringify(data),
  4955. }),
  4956. updateUser: (id: number, data: UserUpdate) =>
  4957. request<UserResponse>(`/users/${id}`, {
  4958. method: 'PATCH',
  4959. body: JSON.stringify(data),
  4960. }),
  4961. deleteUser: (id: number, deleteItems: boolean = false) =>
  4962. request<void>(`/users/${id}?delete_items=${deleteItems}`, {
  4963. method: 'DELETE',
  4964. }),
  4965. getUserItemsCount: (id: number) =>
  4966. request<{ archives: number; queue_items: number; library_files: number }>(`/users/${id}/items-count`),
  4967. changePassword: (currentPassword: string, newPassword: string) =>
  4968. request<{ message: string }>('/users/me/change-password', {
  4969. method: 'POST',
  4970. body: JSON.stringify({ current_password: currentPassword, new_password: newPassword }),
  4971. }),
  4972. // User Email Notifications
  4973. getUserEmailPreferences: () =>
  4974. request<UserEmailPreferences>('/user-notifications/preferences'),
  4975. updateUserEmailPreferences: (data: UserEmailPreferences) =>
  4976. request<UserEmailPreferences>('/user-notifications/preferences', {
  4977. method: 'PUT',
  4978. body: JSON.stringify(data),
  4979. }),
  4980. // Groups
  4981. getPermissions: () => request<PermissionsListResponse>('/groups/permissions'),
  4982. getGroups: () => request<Group[]>('/groups/'),
  4983. getGroup: (id: number) => request<GroupDetail>(`/groups/${id}`),
  4984. createGroup: (data: GroupCreate) =>
  4985. request<Group>('/groups/', {
  4986. method: 'POST',
  4987. body: JSON.stringify(data),
  4988. }),
  4989. updateGroup: (id: number, data: GroupUpdate) =>
  4990. request<Group>(`/groups/${id}`, {
  4991. method: 'PATCH',
  4992. body: JSON.stringify(data),
  4993. }),
  4994. deleteGroup: (id: number) =>
  4995. request<void>(`/groups/${id}`, {
  4996. method: 'DELETE',
  4997. }),
  4998. // Printers
  4999. getPrinters: () => request<Printer[]>('/printers/'),
  5000. getPrinter: (id: number) => request<Printer>(`/printers/${id}`),
  5001. createPrinter: (data: PrinterCreate) =>
  5002. request<Printer>('/printers/', {
  5003. method: 'POST',
  5004. body: JSON.stringify(data),
  5005. }),
  5006. updatePrinter: (id: number, data: Partial<PrinterCreate>) =>
  5007. request<Printer>(`/printers/${id}`, {
  5008. method: 'PATCH',
  5009. body: JSON.stringify(data),
  5010. }),
  5011. getWledPresets: (id: number, baseUrl: string) =>
  5012. request<WLEDPreset[]>(`/printers/${id}/wled/presets`, {
  5013. method: 'POST',
  5014. body: JSON.stringify({ base_url: baseUrl }),
  5015. }),
  5016. testWledConnection: (id: number, baseUrl: string) =>
  5017. request<WLEDConnectionInfo>(`/printers/${id}/wled/test-connection`, {
  5018. method: 'POST',
  5019. body: JSON.stringify({ base_url: baseUrl }),
  5020. }),
  5021. testWledPreset: (id: number, baseUrl: string, presetId: number) =>
  5022. request<{ success: boolean }>(`/printers/${id}/wled/test-preset`, {
  5023. method: 'POST',
  5024. body: JSON.stringify({ base_url: baseUrl, preset_id: presetId }),
  5025. }),
  5026. deletePrinter: (id: number, deleteArchives: boolean = true) =>
  5027. request<{ status: string; archives_deleted: boolean }>(
  5028. `/printers/${id}?delete_archives=${deleteArchives}`,
  5029. { method: 'DELETE' }
  5030. ),
  5031. getDeveloperModeWarnings: () =>
  5032. request<{ printer_id: number; name: string }[]>('/printers/developer-mode-warnings'),
  5033. getAvailableFilaments: (model: string, location?: string) => {
  5034. const params = new URLSearchParams({ model });
  5035. if (location) params.set('location', location);
  5036. return request<Array<{ type: string; color: string; tray_info_idx: string; tray_sub_brands: string; extruder_id: number | null }>>(`/printers/available-filaments?${params}`);
  5037. },
  5038. getPrinterLocations: () => request<PrinterLocation[]>('/printer-locations/'),
  5039. createPrinterLocation: (data: { name: string; icon?: string | null; color?: string | null }) =>
  5040. request<PrinterLocation>('/printer-locations/', { method: 'POST', body: JSON.stringify(data) }),
  5041. updatePrinterLocation: (data: PrinterLocationUpdate) =>
  5042. request<PrinterLocation>('/printer-locations/', { method: 'PATCH', body: JSON.stringify(data) }),
  5043. deletePrinterLocations: (names: string[]) =>
  5044. request<{ deleted: number; printers_ungrouped: number }>('/printer-locations/delete', {
  5045. method: 'POST',
  5046. body: JSON.stringify({ names }),
  5047. }),
  5048. assignPrinterLocation: (printerIds: number[], location: string | null) =>
  5049. request<{ moved: number }>('/printer-locations/assign', {
  5050. method: 'POST',
  5051. body: JSON.stringify({ printer_ids: printerIds, location }),
  5052. }),
  5053. getPrinterStatus: (id: number) => printerStatusBatch(id),
  5054. refreshPrinterStatus: (id: number) =>
  5055. request<{ status: string }>(`/printers/${id}/refresh-status`, {
  5056. method: 'POST',
  5057. }),
  5058. connectPrinter: (id: number) =>
  5059. request<{ connected: boolean }>(`/printers/${id}/connect`, {
  5060. method: 'POST',
  5061. }),
  5062. getUsbCameras: () => request<{ cameras: UsbCamera[] }>('/printers/usb-cameras'),
  5063. testExternalCamera: (printerId: number, url: string, cameraType: string) =>
  5064. // `coalesced` is true when the frame came from a capture that was already
  5065. // running (Obico polling, a snapshot) rather than a connection this test
  5066. // opened — a single-reader camera is shared rather than opened twice, so
  5067. // the result is real but says nothing about reaching the camera just now.
  5068. // `live_view` is true when the tested camera is the one a viewer is
  5069. // watching: the answer comes from the live frame, not a test of its own.
  5070. // In the body: the URL may carry the camera login, and a query string
  5071. // ends up in the server's access log.
  5072. request<{ success: boolean; error?: string; resolution?: string; coalesced?: boolean; live_view?: boolean }>(
  5073. `/printers/${printerId}/camera/external/test`,
  5074. { method: 'POST', body: JSON.stringify({ url, camera_type: cameraType }) }
  5075. ),
  5076. // Print Control
  5077. stopPrint: (printerId: number) =>
  5078. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/stop`, {
  5079. method: 'POST',
  5080. }),
  5081. pausePrint: (printerId: number) =>
  5082. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/pause`, {
  5083. method: 'POST',
  5084. }),
  5085. resumePrint: (printerId: number) =>
  5086. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/resume`, {
  5087. method: 'POST',
  5088. }),
  5089. clearPlate: (printerId: number) =>
  5090. request<{ success: boolean; message: string }>(`/printers/${printerId}/clear-plate`, {
  5091. method: 'POST',
  5092. }),
  5093. // Get current print user (for reprint tracking - Issue #206)
  5094. getCurrentPrintUser: (printerId: number) =>
  5095. request<{ user_id?: number; username?: string }>(`/printers/${printerId}/current-print-user`),
  5096. // Print Speed Control
  5097. setPrintSpeed: (printerId: number, mode: number) =>
  5098. request<{ success: boolean; message: string }>(`/printers/${printerId}/print-speed?mode=${mode}`, {
  5099. method: 'POST',
  5100. }),
  5101. setNozzleTemperature: (printerId: number, target: number, nozzle: number = 0) =>
  5102. request<{ success: boolean; message: string }>(
  5103. `/printers/${printerId}/temperature/nozzle?target=${target}&nozzle=${nozzle}`,
  5104. { method: 'POST' }
  5105. ),
  5106. setBedTemperature: (printerId: number, target: number) =>
  5107. request<{ success: boolean; message: string }>(`/printers/${printerId}/temperature/bed?target=${target}`, {
  5108. method: 'POST',
  5109. }),
  5110. setChamberTemperature: (printerId: number, target: number) =>
  5111. request<{ success: boolean; message: string }>(`/printers/${printerId}/temperature/chamber?target=${target}`, {
  5112. method: 'POST',
  5113. }),
  5114. setFanSpeed: (printerId: number, fan: 'part' | 'aux' | 'aux2' | 'chamber', speed: number) =>
  5115. request<{ success: boolean; message: string }>(`/printers/${printerId}/fan-speed?fan=${fan}&speed=${speed}`, {
  5116. method: 'POST',
  5117. }),
  5118. selectExtruder: (printerId: number, extruder: number) =>
  5119. request<{ success: boolean; message: string }>(`/printers/${printerId}/select-extruder?extruder=${extruder}`, {
  5120. method: 'POST',
  5121. }),
  5122. setAirductMode: (printerId: number, mode: 'cooling' | 'heating') =>
  5123. request<{ success: boolean; message: string }>(`/printers/${printerId}/airduct-mode?mode=${mode}`, {
  5124. method: 'POST',
  5125. }),
  5126. // Bed (Z-axis) jog
  5127. bedJog: (printerId: number, distance: number) =>
  5128. request<{ success: boolean; message: string }>(
  5129. `/printers/${printerId}/bed-jog?distance=${distance}`,
  5130. { method: 'POST' }
  5131. ),
  5132. xyJog: (printerId: number, x: number, y: number) =>
  5133. request<{ success: boolean; message: string }>(
  5134. `/printers/${printerId}/xy-jog?x=${x}&y=${y}`,
  5135. { method: 'POST' }
  5136. ),
  5137. extruderJog: (printerId: number, distance: number) =>
  5138. request<{ success: boolean; message: string }>(
  5139. `/printers/${printerId}/extruder-jog?distance=${distance}`,
  5140. { method: 'POST' }
  5141. ),
  5142. homeAxes: (printerId: number, axes: 'z' | 'xy' | 'all' = 'z') =>
  5143. request<{ success: boolean; message: string }>(
  5144. `/printers/${printerId}/home-axes?axes=${axes}`,
  5145. { method: 'POST' }
  5146. ),
  5147. // Chamber Light Control
  5148. setChamberLight: (printerId: number, on: boolean) =>
  5149. request<{ success: boolean; message: string }>(`/printers/${printerId}/chamber-light?on=${on}`, {
  5150. method: 'POST',
  5151. }),
  5152. // AMS Drying Control
  5153. startDrying: (printerId: number, amsId: number, temp: number, duration: number, filament: string = '', rotateTray: boolean = false) =>
  5154. request<{ status: string; ams_id: number; temp: number; duration: number }>(
  5155. `/printers/${printerId}/drying/start?ams_id=${amsId}&temp=${temp}&duration=${duration}&filament=${encodeURIComponent(filament)}&rotate_tray=${rotateTray}`,
  5156. { method: 'POST' }
  5157. ),
  5158. stopDrying: (printerId: number, amsId: number) =>
  5159. request<{ status: string; ams_id: number }>(
  5160. `/printers/${printerId}/drying/stop?ams_id=${amsId}`,
  5161. { method: 'POST' }
  5162. ),
  5163. // Scheduled (delayed) drying runs (#2638)
  5164. createScheduledDrying: (data: {
  5165. printer_id: number;
  5166. ams_id: number;
  5167. temp: number;
  5168. duration_hours: number;
  5169. filament?: string;
  5170. rotate_tray?: boolean;
  5171. start_after: string | null;
  5172. }) =>
  5173. request<ScheduledDrying>('/scheduled-dryings', {
  5174. method: 'POST',
  5175. body: JSON.stringify(data),
  5176. }),
  5177. // Omit printerId for the whole fleet in one request; the printer cards share
  5178. // that single query rather than each polling for its own id.
  5179. listScheduledDryings: (printerId?: number) =>
  5180. request<ScheduledDrying[]>(
  5181. printerId === undefined ? '/scheduled-dryings' : `/scheduled-dryings?printer_id=${printerId}`
  5182. ),
  5183. cancelScheduledDrying: (id: number) =>
  5184. request<{ status: string; id: number }>(`/scheduled-dryings/${id}`, { method: 'DELETE' }),
  5185. // AMS Filament Backup (auto-switch to a backup spool when one runs out)
  5186. setAmsFilamentBackup: (printerId: number, enabled: boolean) =>
  5187. request<{ success: boolean; ams_filament_backup: boolean }>(
  5188. `/printers/${printerId}/ams-backup?enabled=${enabled}`,
  5189. { method: 'POST' }
  5190. ),
  5191. // Per-globalTrayId remaining grams for this printer's inventory-bound slots
  5192. // (#1766). Drives the client-side "Prefer Lowest Remaining Filament" sort
  5193. // when computing the AMS mapping; mirrors backend `_build_inventory_remain_overrides`
  5194. // so internal and Spoolman modes both work uniformly.
  5195. getInventoryRemain: (printerId: number) =>
  5196. request<InventoryRemainResponse>(
  5197. `/printers/${printerId}/inventory-remain`,
  5198. ),
  5199. // Skip Objects
  5200. getPrintableObjects: (printerId: number) =>
  5201. request<{
  5202. objects: Array<{ id: number; name: string; x: number | null; y: number | null; skipped: boolean }>;
  5203. total: number;
  5204. skipped_count: number;
  5205. is_printing: boolean;
  5206. bbox_all: [number, number, number, number] | null;
  5207. }>(`/printers/${printerId}/print/objects`),
  5208. skipObjects: (printerId: number, objectIds: number[]) =>
  5209. request<{ success: boolean; message: string; skipped_objects: number[] }>(
  5210. `/printers/${printerId}/print/skip-objects`,
  5211. {
  5212. method: 'POST',
  5213. body: JSON.stringify(objectIds),
  5214. }
  5215. ),
  5216. // HMS Errors
  5217. clearHMSErrors: (printerId: number) =>
  5218. request<{ success: boolean; message: string }>(`/printers/${printerId}/hms/clear`, { method: 'POST' }),
  5219. executeHMSAction: (printerId: number, data: HMSActionBody) =>
  5220. request<{ success: boolean; message: string }>(`/printers/${printerId}/hms/execute-action`, {
  5221. method: 'POST',
  5222. body: JSON.stringify(data),
  5223. }),
  5224. // AMS Control
  5225. refreshAmsSlot: (printerId: number, amsId: number, slotId: number) =>
  5226. request<{ success: boolean; message: string }>(
  5227. `/printers/${printerId}/ams/${amsId}/slot/${slotId}/refresh`,
  5228. { method: 'POST' }
  5229. ),
  5230. // Load filament from a tray. trayId: 0-15 for AMS (amsId*4+slotId), 28-36 for the H3C AMS 3H, 128-135 for an
  5231. // AMS-HT (its unit id), 254 for external spool.
  5232. // extruderId (0 = right, 1 = left) names the hotend to feed. Pass it only on a
  5233. // printer with a Filament Track Switch — there the AMS is bound to a switch
  5234. // inlet rather than a hotend, so the firmware cannot work the target out and
  5235. // drops the command. Omit it everywhere else, as BambuStudio does.
  5236. loadAmsTray: (printerId: number, trayId: number, extruderId?: number) =>
  5237. request<{ success: boolean; message: string }>(
  5238. `/printers/${printerId}/ams/load?tray_id=${trayId}` +
  5239. (extruderId !== undefined ? `&extruder_id=${extruderId}` : ''),
  5240. { method: 'POST' }
  5241. ),
  5242. // Unload filament. trayId names the slot to unload, which is what tells a
  5243. // dual-nozzle printer which of its two hotends to act on; omit it to unload
  5244. // whatever the printer's single tray_now field names.
  5245. unloadAms: (printerId: number, trayId?: number) =>
  5246. request<{ success: boolean; message: string }>(
  5247. `/printers/${printerId}/ams/unload` + (trayId !== undefined ? `?tray_id=${trayId}` : ''),
  5248. { method: 'POST' }
  5249. ),
  5250. // MQTT Debug Logging
  5251. enableMQTTLogging: (printerId: number) =>
  5252. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/enable`, {
  5253. method: 'POST',
  5254. }),
  5255. disableMQTTLogging: (printerId: number) =>
  5256. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/disable`, {
  5257. method: 'POST',
  5258. }),
  5259. getMQTTLogs: (printerId: number) =>
  5260. request<MQTTLogsResponse>(`/printers/${printerId}/logging`),
  5261. clearMQTTLogs: (printerId: number) =>
  5262. request<{ status: string }>(`/printers/${printerId}/logging`, {
  5263. method: 'DELETE',
  5264. }),
  5265. // Printer File Manager
  5266. getPrinterFiles: (printerId: number, path = '/') =>
  5267. request<{
  5268. path: string;
  5269. files: Array<{
  5270. name: string;
  5271. is_directory: boolean;
  5272. size: number;
  5273. path: string;
  5274. mtime?: string;
  5275. }>;
  5276. warnings: Array<'printer_unavailable' | 'listing_timed_out'>;
  5277. }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`),
  5278. getPrinterFileDownloadUrl: (printerId: number, path: string) =>
  5279. `${API_BASE}/printers/${printerId}/files/download?path=${encodeURIComponent(path)}`,
  5280. getPrinterFileGcodeUrl: (printerId: number, path: string) =>
  5281. `${API_BASE}/printers/${printerId}/files/gcode?path=${encodeURIComponent(path)}`,
  5282. getPrinterFilePlates: (printerId: number, path: string) =>
  5283. request<{
  5284. printer_id: number;
  5285. path: string;
  5286. filename: string;
  5287. plates: Array<{
  5288. index: number;
  5289. name: string | null;
  5290. objects: string[];
  5291. has_thumbnail: boolean;
  5292. thumbnail_url: string | null;
  5293. print_time_seconds: number | null;
  5294. filament_used_grams: number | null;
  5295. filaments: Array<{
  5296. slot_id: number;
  5297. type: string;
  5298. color: string;
  5299. used_grams: number;
  5300. used_meters: number;
  5301. }>;
  5302. }>;
  5303. is_multi_plate: boolean;
  5304. }>(`/printers/${printerId}/files/plates?path=${encodeURIComponent(path)}`),
  5305. getPrinterFilePlateThumbnail: (printerId: number, plateIndex: number, path: string) =>
  5306. withMediaToken(`${API_BASE}/printers/${printerId}/files/plate-thumbnail/${plateIndex}?path=${encodeURIComponent(path)}`),
  5307. downloadPrinterFilesAsZip: async (
  5308. printerId: number,
  5309. paths: string[],
  5310. sizes: Record<string, number>,
  5311. filename = 'printer-files.zip',
  5312. asZip = true,
  5313. signal?: AbortSignal,
  5314. onProgress?: (completed: number, total: number) => void,
  5315. ): Promise<{ requested: number; successful: number; failed: number }> => {
  5316. type JobStatus = {
  5317. job_id: string;
  5318. state: 'queued' | 'preparing' | 'ready' | 'failed' | 'cancelled';
  5319. requested: number;
  5320. successful: number;
  5321. failed: number;
  5322. token: string | null;
  5323. message: string | null;
  5324. };
  5325. let jobId: string | null = null;
  5326. try {
  5327. if (signal?.aborted) throw new DOMException('Download cancelled', 'AbortError');
  5328. let status = await request<JobStatus>(`/printers/${printerId}/files/download-job`, {
  5329. method: 'POST',
  5330. body: JSON.stringify({ paths, sizes, filename, as_zip: asZip }),
  5331. signal,
  5332. });
  5333. jobId = status.job_id;
  5334. let polls = 0;
  5335. while (status.state === 'queued' || status.state === 'preparing') {
  5336. onProgress?.(status.successful + status.failed, status.requested);
  5337. // Small selections finish in the first seconds, so poll quickly there.
  5338. // A large one runs for up to half an hour, where half-second polling is
  5339. // thousands of requests that each re-check the caller's credentials.
  5340. const delay = polls < 10 ? 500 : 2000;
  5341. polls += 1;
  5342. await new Promise<void>((resolve, reject) => {
  5343. if (signal?.aborted) {
  5344. reject(new DOMException('Download cancelled', 'AbortError'));
  5345. return;
  5346. }
  5347. const onAbort = () => {
  5348. window.clearTimeout(timer);
  5349. reject(new DOMException('Download cancelled', 'AbortError'));
  5350. };
  5351. const timer = window.setTimeout(() => {
  5352. signal?.removeEventListener('abort', onAbort);
  5353. resolve();
  5354. }, delay);
  5355. signal?.addEventListener('abort', onAbort, { once: true });
  5356. });
  5357. status = await request<JobStatus>(`/printers/${printerId}/files/download-jobs/${jobId}`, { signal });
  5358. }
  5359. onProgress?.(status.successful + status.failed, status.requested);
  5360. if (status.state !== 'ready' || !status.token) {
  5361. throw new Error(status.message || (status.state === 'cancelled'
  5362. ? 'Download cancelled'
  5363. : 'Printer download preparation failed'));
  5364. }
  5365. const link = document.createElement('a');
  5366. link.href = `${API_BASE}/printers/${printerId}/files/dl/${encodeURIComponent(status.token)}/${encodeURIComponent(filename)}`;
  5367. link.download = filename;
  5368. document.body.appendChild(link);
  5369. link.click();
  5370. link.remove();
  5371. return {
  5372. requested: status.requested,
  5373. successful: status.successful,
  5374. failed: status.failed,
  5375. };
  5376. } catch (error) {
  5377. if (jobId) {
  5378. await request(`/printers/${printerId}/files/download-jobs/${jobId}`, { method: 'DELETE' }).catch(() => undefined);
  5379. }
  5380. throw error;
  5381. }
  5382. },
  5383. deletePrinterFile: (printerId: number, path: string) =>
  5384. request<{ status: string; path: string }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`, {
  5385. method: 'DELETE',
  5386. }),
  5387. getPrinterStorage: (printerId: number) =>
  5388. request<{ used_bytes: number | null; free_bytes: number | null }>(`/printers/${printerId}/storage`),
  5389. // Archives
  5390. getArchives: (printerId?: number, projectId?: number, limit = 10000, offset = 0, dateFrom?: string, dateTo?: string) => {
  5391. const params = new URLSearchParams();
  5392. if (printerId) params.set('printer_id', String(printerId));
  5393. if (projectId) params.set('project_id', String(projectId));
  5394. params.set('limit', String(limit));
  5395. params.set('offset', String(offset));
  5396. if (dateFrom) params.set('date_from', dateFrom);
  5397. if (dateTo) params.set('date_to', dateTo);
  5398. addDayZone(params);
  5399. return request<Archive[]>(`/archives/?${params}`);
  5400. },
  5401. // Latest archive of every printer in one request, for the printer cards.
  5402. getLastArchivePerPrinter: () => request<Archive[]>('/archives/last-per-printer'),
  5403. getArchivesSlim: (dateFrom?: string, dateTo?: string, createdById?: number) => {
  5404. const params = new URLSearchParams();
  5405. if (dateFrom) params.set('date_from', dateFrom);
  5406. if (dateTo) params.set('date_to', dateTo);
  5407. addDayZone(params);
  5408. if (createdById !== undefined) params.set('created_by_id', String(createdById));
  5409. const qs = params.toString();
  5410. return request<ArchiveSlim[]>(`/archives/slim${qs ? `?${qs}` : ''}`);
  5411. },
  5412. getArchive: (id: number, runId?: number | null) =>
  5413. request<Archive>(`/archives/${id}${runId != null ? `?run_id=${runId}` : ''}`),
  5414. getArchiveRuns: (id: number) => request<PrintLogResponse>(`/archives/${id}/runs`),
  5415. // The prints of the archives the caller sees that ended between two days
  5416. // (archive redesign P4: the calendar), in id order.
  5417. getArchivePrints: (params: { dateFrom: string; dateTo: string; printerId?: number; limit?: number; offset?: number }) => {
  5418. const search = new URLSearchParams({ date_from: params.dateFrom, date_to: params.dateTo });
  5419. if (params.printerId) search.set('printer_id', String(params.printerId));
  5420. if (params.limit) search.set('limit', String(params.limit));
  5421. if (params.offset) search.set('offset', String(params.offset));
  5422. addDayZone(search);
  5423. return request<PrintLogResponse>(`/archives/prints?${search}`);
  5424. },
  5425. /**
  5426. * Pre-flight for the delete-confirm modal (#1734). Returns the number of
  5427. * related queue items that will be removed along with the archive AND how
  5428. * many are currently printing (server 409s on delete if > 0).
  5429. */
  5430. getArchiveDeleteImpact: (id: number) =>
  5431. request<{ related_queue_items: number; currently_printing: number }>(
  5432. `/archives/${id}/delete-impact`
  5433. ),
  5434. getNo3MFWarning: () =>
  5435. request<{
  5436. has_fallback: boolean;
  5437. reason:
  5438. | 'ftps_cooloff'
  5439. | 'ftp_transfer_failed'
  5440. | 'internal_storage'
  5441. | 'no_external_storage'
  5442. | 'internal_history'
  5443. | null;
  5444. }>(
  5445. '/archives/no-3mf-warning',
  5446. ),
  5447. updateArchive: (id: number, data: {
  5448. printer_id?: number | null;
  5449. project_id?: number | null;
  5450. print_name?: string;
  5451. is_favorite?: boolean;
  5452. tags?: string;
  5453. notes?: string;
  5454. cost?: number;
  5455. failure_reason?: string | null;
  5456. status?: string;
  5457. quantity?: number;
  5458. external_url?: string | null;
  5459. filament_used_grams?: number | null;
  5460. // Post-print outcome verdict (#1898); null clears it
  5461. user_verdict?: 'good' | 'reject' | null;
  5462. // Which surface answered. The backend only accepts the sources a client
  5463. // can honestly claim and defaults to 'api' when none is given.
  5464. user_verdict_source?: 'dialog' | 'printer_card';
  5465. // The run the verdict / outcome is for; omitted means the latest run.
  5466. run_id?: number;
  5467. }) =>
  5468. request<Archive>(`/archives/${id}`, {
  5469. method: 'PATCH',
  5470. body: JSON.stringify(data),
  5471. }),
  5472. toggleFavorite: (id: number) =>
  5473. request<Archive>(`/archives/${id}/favorite`, { method: 'POST' }),
  5474. // Soft-deletes by default (#1343): files removed from disk, row hidden
  5475. // from listings, but its filament / time / cost / energy contribution
  5476. // stays in Quick Stats. Pass purgeStats=true to hard-delete and drop the
  5477. // row from statistics too.
  5478. deleteArchive: (id: number, purgeStats: boolean = false) =>
  5479. request<void>(`/archives/${id}${purgeStats ? '?purge_stats=true' : ''}`, { method: 'DELETE' }),
  5480. // ========== Archive auto-purge (#1008 follow-up) ==========
  5481. previewArchivePurge: (olderThanDays: number, purgeStats: boolean = false) =>
  5482. request<ArchivePurgePreview>(
  5483. `/archives/purge/preview?older_than_days=${olderThanDays}&purge_stats=${purgeStats}`,
  5484. ),
  5485. // #1390: purgeStats=false (default) soft-deletes each old archive — Quick Stats
  5486. // preserved, files removed from disk, row hidden via deleted_at. true matches
  5487. // the single-archive delete's `?purge_stats=true` semantics (hard-deletes the
  5488. // linked PrintLogEntry rows so the contribution drops from /stats too).
  5489. executeArchivePurge: (olderThanDays: number, purgeStats: boolean = false) =>
  5490. request<{ deleted: number; purge_stats: boolean }>('/archives/purge', {
  5491. method: 'POST',
  5492. body: JSON.stringify({ older_than_days: olderThanDays, purge_stats: purgeStats }),
  5493. }),
  5494. // Archives of one file merge into the oldest (archive redesign P2).
  5495. previewArchiveMerge: () => request<ArchiveMergePreview>('/archives/merge-preview'),
  5496. /** How many duplicate groups there are; cheap, for offering the merge. */
  5497. getArchiveMergeCount: () => request<{ groups: number }>('/archives/merge-count'),
  5498. mergeArchives: (survivorIds: number[]) =>
  5499. request<ArchiveMergeResult>('/archives/merge', {
  5500. method: 'POST',
  5501. body: JSON.stringify({ survivor_ids: survivorIds }),
  5502. }),
  5503. getArchivePurgeSettings: () =>
  5504. request<ArchivePurgeSettings>('/archives/purge/settings'),
  5505. updateArchivePurgeSettings: (body: ArchivePurgeSettings) =>
  5506. request<ArchivePurgeSettings>('/archives/purge/settings', {
  5507. method: 'PUT',
  5508. body: JSON.stringify(body),
  5509. }),
  5510. getArchiveStats: (options?: { dateFrom?: string; dateTo?: string; createdById?: number }) => {
  5511. const params = new URLSearchParams();
  5512. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  5513. if (options?.dateTo) params.set('date_to', options.dateTo);
  5514. addDayZone(params);
  5515. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  5516. const qs = params.toString();
  5517. return request<ArchiveStats>(`/archives/stats${qs ? `?${qs}` : ''}`);
  5518. },
  5519. // Tag management
  5520. getTags: () => request<TagInfo[]>('/archives/tags'),
  5521. renameTag: (oldName: string, newName: string) =>
  5522. request<{ affected: number }>(`/archives/tags/${encodeURIComponent(oldName)}`, {
  5523. method: 'PUT',
  5524. body: JSON.stringify({ new_name: newName }),
  5525. }),
  5526. deleteTag: (name: string) =>
  5527. request<{ affected: number }>(`/archives/tags/${encodeURIComponent(name)}`, {
  5528. method: 'DELETE',
  5529. }),
  5530. recalculateCosts: () =>
  5531. request<{
  5532. message: string;
  5533. updated: number;
  5534. preserved: number;
  5535. usage_repriced: number;
  5536. spoolman_unreachable: number;
  5537. }>('/archives/recalculate-costs', { method: 'POST' }),
  5538. getFailureAnalysis: (options?: { days?: number; dateFrom?: string; dateTo?: string; printerId?: number; projectId?: number; createdById?: number }) => {
  5539. const params = new URLSearchParams();
  5540. if (options?.days) params.set('days', String(options.days));
  5541. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  5542. if (options?.dateTo) params.set('date_to', options.dateTo);
  5543. addDayZone(params);
  5544. if (options?.printerId) params.set('printer_id', String(options.printerId));
  5545. if (options?.projectId) params.set('project_id', String(options.projectId));
  5546. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  5547. const qs = params.toString();
  5548. return request<FailureAnalysis>(`/archives/analysis/failures${qs ? `?${qs}` : ''}`);
  5549. },
  5550. compareArchives: (archiveIds: number[]) =>
  5551. request<ArchiveComparison>(`/archives/compare?archive_ids=${archiveIds.join(',')}`),
  5552. exportArchives: async (options?: {
  5553. format?: 'csv' | 'xlsx';
  5554. fields?: string[];
  5555. printerId?: number;
  5556. projectId?: number;
  5557. status?: string;
  5558. dateFrom?: string;
  5559. dateTo?: string;
  5560. search?: string;
  5561. }): Promise<{ blob: Blob; filename: string }> => {
  5562. const params = new URLSearchParams();
  5563. if (options?.format) params.set('format', options.format);
  5564. if (options?.fields) params.set('fields', options.fields.join(','));
  5565. if (options?.printerId) params.set('printer_id', String(options.printerId));
  5566. if (options?.projectId) params.set('project_id', String(options.projectId));
  5567. if (options?.status) params.set('status', options.status);
  5568. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  5569. if (options?.dateTo) params.set('date_to', options.dateTo);
  5570. addDayZone(params);
  5571. if (options?.search) params.set('search', options.search);
  5572. const headers: Record<string, string> = {};
  5573. if (authToken) {
  5574. headers['Authorization'] = `Bearer ${authToken}`;
  5575. }
  5576. const response = await fetch(`${API_BASE}/archives/export?${params}`, { headers });
  5577. if (!response.ok) {
  5578. const error = await response.json().catch(() => ({}));
  5579. throw new Error(error.detail || `HTTP ${response.status}`);
  5580. }
  5581. const contentDisposition = response.headers.get('Content-Disposition');
  5582. let filename = options?.format === 'xlsx' ? 'archives_export.xlsx' : 'archives_export.csv';
  5583. if (contentDisposition) {
  5584. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  5585. if (match) filename = match[1];
  5586. }
  5587. const blob = await response.blob();
  5588. return { blob, filename };
  5589. },
  5590. exportStats: async (options?: {
  5591. format?: 'csv' | 'xlsx';
  5592. days?: number;
  5593. printerId?: number;
  5594. projectId?: number;
  5595. createdById?: number;
  5596. }): Promise<{ blob: Blob; filename: string }> => {
  5597. const params = new URLSearchParams();
  5598. if (options?.format) params.set('format', options.format);
  5599. if (options?.days) params.set('days', String(options.days));
  5600. if (options?.printerId) params.set('printer_id', String(options.printerId));
  5601. if (options?.projectId) params.set('project_id', String(options.projectId));
  5602. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  5603. const headers: Record<string, string> = {};
  5604. if (authToken) {
  5605. headers['Authorization'] = `Bearer ${authToken}`;
  5606. }
  5607. const response = await fetch(`${API_BASE}/archives/stats/export?${params}`, { headers });
  5608. if (!response.ok) {
  5609. const error = await response.json().catch(() => ({}));
  5610. throw new Error(error.detail || `HTTP ${response.status}`);
  5611. }
  5612. const contentDisposition = response.headers.get('Content-Disposition');
  5613. let filename = options?.format === 'xlsx' ? 'stats_export.xlsx' : 'stats_export.csv';
  5614. if (contentDisposition) {
  5615. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  5616. if (match) filename = match[1];
  5617. }
  5618. const blob = await response.blob();
  5619. return { blob, filename };
  5620. },
  5621. getArchiveThumbnail: (id: number) => withMediaToken(`${API_BASE}/archives/${id}/thumbnail?v=${Date.now()}`),
  5622. getArchivePlateThumbnail: (id: number, plateIndex: number) =>
  5623. withMediaToken(`${API_BASE}/archives/${id}/plate-thumbnail/${plateIndex}`),
  5624. getArchiveDownload: (id: number) => `${API_BASE}/archives/${id}/download`,
  5625. downloadArchive: async (id: number, filename?: string): Promise<void> => {
  5626. const headers: Record<string, string> = {};
  5627. if (authToken) {
  5628. headers['Authorization'] = `Bearer ${authToken}`;
  5629. }
  5630. const response = await fetch(`${API_BASE}/archives/${id}/download`, { headers });
  5631. if (!response.ok) {
  5632. const error = await response.json().catch(() => ({}));
  5633. throw new Error(error.detail || `HTTP ${response.status}`);
  5634. }
  5635. const disposition = response.headers.get('Content-Disposition');
  5636. const downloadFilename = parseContentDispositionFilename(disposition) || filename || `archive_${id}.3mf`;
  5637. const blob = await response.blob();
  5638. const url = window.URL.createObjectURL(blob);
  5639. const a = document.createElement('a');
  5640. a.href = url;
  5641. a.download = downloadFilename;
  5642. document.body.appendChild(a);
  5643. a.click();
  5644. document.body.removeChild(a);
  5645. window.URL.revokeObjectURL(url);
  5646. },
  5647. getArchiveGcode: (id: number) => `${API_BASE}/archives/${id}/gcode`,
  5648. getArchiveTimelapse: (id: number) => withMediaToken(`${API_BASE}/archives/${id}/timelapse?v=${Date.now()}`),
  5649. getArchiveRunTimelapse: (id: number, runId: number) =>
  5650. withMediaToken(`${API_BASE}/archives/${id}/runs/${runId}/timelapse?v=${Date.now()}`),
  5651. downloadArchiveTimelapse: async (id: number, filename: string): Promise<void> => {
  5652. const prepared = await request<{ token: string; filename: string }>(
  5653. `/archives/${id}/media-download-token`,
  5654. { method: 'POST' },
  5655. );
  5656. const link = document.createElement('a');
  5657. link.href = `${API_BASE}/archives/${id}/media/dl/${encodeURIComponent(prepared.token)}/${encodeURIComponent(filename)}`;
  5658. link.download = filename;
  5659. document.body.appendChild(link);
  5660. link.click();
  5661. link.remove();
  5662. },
  5663. getArchivePrinterMedia: (id: number) =>
  5664. request<ArchivePrinterMedia>(`/archives/${id}/printer-media`),
  5665. scanArchiveTimelapse: (id: number) =>
  5666. request<{
  5667. status: string;
  5668. message: string;
  5669. filename?: string;
  5670. available_files?: Array<{ name: string; path: string; size: number; mtime: string | null }>;
  5671. }>(`/archives/${id}/timelapse/scan`, {
  5672. method: 'POST',
  5673. }),
  5674. selectArchiveTimelapse: (id: number, filename: string) =>
  5675. request<{ status: string; message: string; filename: string }>(
  5676. `/archives/${id}/timelapse/select?filename=${encodeURIComponent(filename)}`,
  5677. { method: 'POST' }
  5678. ),
  5679. deleteArchiveTimelapse: (id: number) =>
  5680. request<{ status: string }>(`/archives/${id}/timelapse`, {
  5681. method: 'DELETE',
  5682. }),
  5683. uploadArchiveTimelapse: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  5684. const formData = new FormData();
  5685. formData.append('file', file);
  5686. const headers: Record<string, string> = {};
  5687. if (authToken) {
  5688. headers['Authorization'] = `Bearer ${authToken}`;
  5689. }
  5690. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/upload`, {
  5691. method: 'POST',
  5692. headers,
  5693. body: formData,
  5694. });
  5695. if (!response.ok) {
  5696. const error = await response.json().catch(() => ({}));
  5697. throw new Error(error.detail || `HTTP ${response.status}`);
  5698. }
  5699. return response.json();
  5700. },
  5701. // Timelapse Editor
  5702. getTimelapseInfo: (archiveId: number) =>
  5703. request<{
  5704. duration: number;
  5705. width: number;
  5706. height: number;
  5707. fps: number;
  5708. codec: string;
  5709. file_size: number;
  5710. has_audio: boolean;
  5711. }>(`/archives/${archiveId}/timelapse/info`),
  5712. getTimelapseThumbnails: (archiveId: number, count: number = 10) =>
  5713. request<{
  5714. thumbnails: string[];
  5715. timestamps: number[];
  5716. }>(`/archives/${archiveId}/timelapse/thumbnails?count=${count}`),
  5717. processTimelapse: async (
  5718. archiveId: number,
  5719. params: {
  5720. trimStart?: number;
  5721. trimEnd?: number;
  5722. speed?: number;
  5723. /** Music volume, 0 to 1. */
  5724. audioVolume?: number;
  5725. saveMode: 'replace' | 'new';
  5726. outputFilename?: string;
  5727. },
  5728. audioFile?: File
  5729. ): Promise<TimelapseJob> => {
  5730. const formData = new FormData();
  5731. formData.append('trim_start', String(params.trimStart ?? 0));
  5732. if (params.trimEnd !== undefined) {
  5733. formData.append('trim_end', String(params.trimEnd));
  5734. }
  5735. formData.append('speed', String(params.speed ?? 1));
  5736. if (params.audioVolume !== undefined) {
  5737. formData.append('audio_volume', String(params.audioVolume));
  5738. }
  5739. formData.append('save_mode', params.saveMode);
  5740. if (params.outputFilename) {
  5741. formData.append('output_filename', params.outputFilename);
  5742. }
  5743. if (audioFile) {
  5744. formData.append('audio', audioFile);
  5745. }
  5746. const headers: Record<string, string> = {};
  5747. if (authToken) {
  5748. headers['Authorization'] = `Bearer ${authToken}`;
  5749. }
  5750. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/process`, {
  5751. method: 'POST',
  5752. headers,
  5753. body: formData,
  5754. });
  5755. if (!response.ok) {
  5756. const error = await response.json().catch(() => ({}));
  5757. throw new Error(error.detail || `HTTP ${response.status}`);
  5758. }
  5759. return response.json();
  5760. },
  5761. // The archive's running or last re-encode; null when there has been none.
  5762. getTimelapseJob: async (archiveId: number): Promise<TimelapseJob | null> => {
  5763. try {
  5764. return await request<TimelapseJob>(`/archives/${archiveId}/timelapse/job`);
  5765. } catch (error) {
  5766. if (error instanceof ApiError && error.status === 404) return null;
  5767. throw error;
  5768. }
  5769. },
  5770. cancelTimelapseJob: (archiveId: number) =>
  5771. request<TimelapseJob>(`/archives/${archiveId}/timelapse/job`, { method: 'DELETE' }),
  5772. // Photos
  5773. getArchivePhotoUrl: (archiveId: number, filename: string) =>
  5774. withMediaToken(`${API_BASE}/archives/${archiveId}/photos/${encodeURIComponent(filename)}`),
  5775. uploadArchivePhoto: async (archiveId: number, file: File): Promise<{ status: string; filename: string; photos: string[] }> => {
  5776. const formData = new FormData();
  5777. formData.append('file', file);
  5778. const headers: Record<string, string> = {};
  5779. if (authToken) {
  5780. headers['Authorization'] = `Bearer ${authToken}`;
  5781. }
  5782. const response = await fetch(`${API_BASE}/archives/${archiveId}/photos`, {
  5783. headers,
  5784. method: 'POST',
  5785. body: formData,
  5786. });
  5787. if (!response.ok) {
  5788. const error = await response.json().catch(() => ({}));
  5789. throw new Error(error.detail || `HTTP ${response.status}`);
  5790. }
  5791. return response.json();
  5792. },
  5793. deleteArchivePhoto: (archiveId: number, filename: string) =>
  5794. request<{ status: string; photos: string[] | null }>(`/archives/${archiveId}/photos/${encodeURIComponent(filename)}`, {
  5795. method: 'DELETE',
  5796. }),
  5797. // Source 3MF (original slicer project file)
  5798. getSource3mfDownloadUrl: (archiveId: number) =>
  5799. `${API_BASE}/archives/${archiveId}/source`,
  5800. downloadSource3mf: async (archiveId: number): Promise<void> => {
  5801. const headers: Record<string, string> = {};
  5802. if (authToken) {
  5803. headers['Authorization'] = `Bearer ${authToken}`;
  5804. }
  5805. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, { headers });
  5806. if (!response.ok) {
  5807. const error = await response.json().catch(() => ({}));
  5808. throw new Error(error.detail || `HTTP ${response.status}`);
  5809. }
  5810. const disposition = response.headers.get('Content-Disposition');
  5811. const filename = parseContentDispositionFilename(disposition) || `source_${archiveId}.3mf`;
  5812. const blob = await response.blob();
  5813. const url = window.URL.createObjectURL(blob);
  5814. const a = document.createElement('a');
  5815. a.href = url;
  5816. a.download = filename;
  5817. document.body.appendChild(a);
  5818. a.click();
  5819. document.body.removeChild(a);
  5820. window.URL.revokeObjectURL(url);
  5821. },
  5822. getSource3mfForSlicer: (archiveId: number, filename: string) => {
  5823. // Sanitize: slicers url_decode() the entire URL, so / \ ? # in filenames break path routing
  5824. const safe = filename.replace(/[/\\?#]/g, '_');
  5825. return `${API_BASE}/archives/${archiveId}/source/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  5826. },
  5827. createSourceSlicerToken: (archiveId: number) =>
  5828. request<{ token: string }>(`/archives/${archiveId}/source-slicer-token`, { method: 'POST' }),
  5829. getSourceSlicerDownloadUrl: (archiveId: number, token: string, filename: string) => {
  5830. const safe = filename.replace(/[/\\?#]/g, '_');
  5831. return `${API_BASE}/archives/${archiveId}/source-dl/${token}/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  5832. },
  5833. uploadSource3mf: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  5834. const formData = new FormData();
  5835. formData.append('file', file);
  5836. const headers: Record<string, string> = {};
  5837. if (authToken) {
  5838. headers['Authorization'] = `Bearer ${authToken}`;
  5839. }
  5840. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, {
  5841. method: 'POST',
  5842. headers,
  5843. body: formData,
  5844. });
  5845. if (!response.ok) {
  5846. const error = await response.json().catch(() => ({}));
  5847. throw new Error(error.detail || `HTTP ${response.status}`);
  5848. }
  5849. return response.json();
  5850. },
  5851. deleteSource3mf: (archiveId: number) =>
  5852. request<{ status: string }>(`/archives/${archiveId}/source`, {
  5853. method: 'DELETE',
  5854. }),
  5855. // F3D (Fusion 360 design file)
  5856. downloadF3d: async (archiveId: number): Promise<void> => {
  5857. const headers: Record<string, string> = {};
  5858. if (authToken) {
  5859. headers['Authorization'] = `Bearer ${authToken}`;
  5860. }
  5861. const response = await fetch(`${API_BASE}/archives/${archiveId}/f3d`, { headers });
  5862. if (!response.ok) {
  5863. const error = await response.json().catch(() => ({}));
  5864. throw new Error(error.detail || `HTTP ${response.status}`);
  5865. }
  5866. const disposition = response.headers.get('Content-Disposition');
  5867. const filename = parseContentDispositionFilename(disposition) || `archive_${archiveId}.f3d`;
  5868. const blob = await response.blob();
  5869. const url = window.URL.createObjectURL(blob);
  5870. const a = document.createElement('a');
  5871. a.href = url;
  5872. a.download = filename;
  5873. document.body.appendChild(a);
  5874. a.click();
  5875. document.body.removeChild(a);
  5876. window.URL.revokeObjectURL(url);
  5877. },
  5878. uploadF3d: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  5879. const formData = new FormData();
  5880. formData.append('file', file);
  5881. const headers: Record<string, string> = {};
  5882. if (authToken) {
  5883. headers['Authorization'] = `Bearer ${authToken}`;
  5884. }
  5885. const response = await fetch(`${API_BASE}/archives/${archiveId}/f3d`, {
  5886. method: 'POST',
  5887. headers,
  5888. body: formData,
  5889. });
  5890. if (!response.ok) {
  5891. const error = await response.json().catch(() => ({}));
  5892. throw new Error(error.detail || `HTTP ${response.status}`);
  5893. }
  5894. return response.json();
  5895. },
  5896. deleteF3d: (archiveId: number) =>
  5897. request<{ status: string }>(`/archives/${archiveId}/f3d`, {
  5898. method: 'DELETE',
  5899. }),
  5900. // QR Code
  5901. getArchiveQRCodeUrl: (archiveId: number, size = 200) =>
  5902. withMediaToken(`${API_BASE}/archives/${archiveId}/qrcode?size=${size}`),
  5903. getArchiveCapabilities: (id: number) =>
  5904. request<{
  5905. has_model: boolean;
  5906. has_gcode: boolean;
  5907. has_source: boolean;
  5908. build_volume: { x: number; y: number; z: number };
  5909. filament_colors: string[];
  5910. }>(`/archives/${id}/capabilities`),
  5911. // Project Page
  5912. getArchiveProjectPage: (id: number) =>
  5913. request<{
  5914. title: string | null;
  5915. description: string | null;
  5916. designer: string | null;
  5917. designer_user_id: string | null;
  5918. license: string | null;
  5919. copyright: string | null;
  5920. creation_date: string | null;
  5921. modification_date: string | null;
  5922. origin: string | null;
  5923. profile_title: string | null;
  5924. profile_description: string | null;
  5925. profile_cover: string | null;
  5926. profile_user_id: string | null;
  5927. profile_user_name: string | null;
  5928. design_model_id: string | null;
  5929. design_profile_id: string | null;
  5930. design_region: string | null;
  5931. model_pictures: Array<{ name: string; path: string; url: string }>;
  5932. profile_pictures: Array<{ name: string; path: string; url: string }>;
  5933. thumbnails: Array<{ name: string; path: string; url: string }>;
  5934. }>(`/archives/${id}/project-page`),
  5935. updateArchiveProjectPage: (id: number, data: {
  5936. title?: string;
  5937. description?: string;
  5938. designer?: string;
  5939. license?: string;
  5940. copyright?: string;
  5941. profile_title?: string;
  5942. profile_description?: string;
  5943. }) =>
  5944. request(`/archives/${id}/project-page`, {
  5945. method: 'PATCH',
  5946. body: JSON.stringify(data),
  5947. }),
  5948. getArchiveForSlicer: (id: number, filename: string) => {
  5949. const safe = filename.replace(/[/\\?#]/g, '_');
  5950. return `${API_BASE}/archives/${id}/file/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  5951. },
  5952. createArchiveSlicerToken: (archiveId: number) =>
  5953. request<{ token: string }>(`/archives/${archiveId}/slicer-token`, { method: 'POST' }),
  5954. getArchiveSlicerDownloadUrl: (archiveId: number, token: string, filename: string) => {
  5955. const safe = filename.replace(/[/\\?#]/g, '_');
  5956. return `${API_BASE}/archives/${archiveId}/dl/${token}/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  5957. },
  5958. getArchivePlates: (archiveId: number) =>
  5959. request<ArchivePlatesResponse>(`/archives/${archiveId}/plates`),
  5960. getArchiveFilamentRequirements: (
  5961. archiveId: number,
  5962. plateId?: number,
  5963. requestId?: string,
  5964. /** Ask for one entry per project slot instead of only the slots this
  5965. * plate consumes. The slice modal needs it: its filament list is
  5966. * positional, so a source whose only used slot is 4 must still present
  5967. * four rows or the user's pick is bound to slot 1 (#2712). Print-time
  5968. * AMS matching must NOT set this — it wants the used-only list. */
  5969. fullSlots?: boolean,
  5970. ) => {
  5971. const qs = new URLSearchParams();
  5972. if (plateId !== undefined) qs.set('plate_id', String(plateId));
  5973. if (requestId) qs.set('request_id', requestId);
  5974. if (fullSlots) qs.set('full_slots', 'true');
  5975. return request<{
  5976. archive_id: number;
  5977. filename: string;
  5978. plate_id: number | null;
  5979. filaments: Array<{
  5980. slot_id: number;
  5981. type: string;
  5982. color: string;
  5983. used_grams: number;
  5984. used_meters: number;
  5985. used_in_plate?: boolean;
  5986. }>;
  5987. }>(`/archives/${archiveId}/filament-requirements${qs.toString() ? `?${qs}` : ''}`);
  5988. },
  5989. uploadArchivesBulk: async (files: File[], printerId?: number): Promise<BulkUploadResult> => {
  5990. const formData = new FormData();
  5991. files.forEach((file) => formData.append('files', file));
  5992. const url = printerId
  5993. ? `${API_BASE}/archives/upload-bulk?printer_id=${printerId}`
  5994. : `${API_BASE}/archives/upload-bulk`;
  5995. const headers: Record<string, string> = {};
  5996. if (authToken) {
  5997. headers['Authorization'] = `Bearer ${authToken}`;
  5998. }
  5999. const response = await fetch(url, {
  6000. method: 'POST',
  6001. headers,
  6002. body: formData,
  6003. });
  6004. if (!response.ok) {
  6005. const error = await response.json().catch(() => ({}));
  6006. throw new Error(error.detail || `HTTP ${response.status}`);
  6007. }
  6008. return response.json();
  6009. },
  6010. // Print Log
  6011. getPrintLog: (params?: {
  6012. search?: string;
  6013. printerId?: number;
  6014. username?: string;
  6015. status?: string;
  6016. dateFrom?: string;
  6017. dateTo?: string;
  6018. limit?: number;
  6019. offset?: number;
  6020. // Sorting is server-side because paging is: ordering only the rows the
  6021. // client holds would sort one page, not the log (#2636).
  6022. sortBy?: string;
  6023. sortDir?: 'asc' | 'desc';
  6024. }) => {
  6025. const searchParams = new URLSearchParams();
  6026. if (params?.search) searchParams.set('search', params.search);
  6027. if (params?.printerId) searchParams.set('printer_id', String(params.printerId));
  6028. if (params?.username) searchParams.set('created_by_username', params.username);
  6029. if (params?.status) searchParams.set('status', params.status);
  6030. if (params?.dateFrom) searchParams.set('date_from', params.dateFrom);
  6031. if (params?.dateTo) searchParams.set('date_to', params.dateTo);
  6032. if (params?.limit) searchParams.set('limit', String(params.limit));
  6033. if (params?.offset !== undefined) searchParams.set('offset', String(params.offset));
  6034. if (params?.sortBy) searchParams.set('sort_by', params.sortBy);
  6035. if (params?.sortDir) searchParams.set('sort_dir', params.sortDir);
  6036. return request<PrintLogResponse>(`/print-log/?${searchParams}`);
  6037. },
  6038. getPrintLogThumbnail: (id: number) => withMediaToken(`${API_BASE}/print-log/${id}/thumbnail`),
  6039. clearPrintLog: () =>
  6040. request<{ deleted: number }>('/print-log/', { method: 'DELETE' }),
  6041. deletePrintLogEntry: (id: number) =>
  6042. request<{ status: string; id: number }>(`/print-log/${id}`, { method: 'DELETE' }),
  6043. // Edit failure_reason / status on a single Print Log row (#1687 part 4).
  6044. // Distinct from updateArchive: archives describe the model, log entries
  6045. // describe a single print event. Orphan entries (no archive_id) have no
  6046. // archive to reach through and this is the only path to classify them.
  6047. updatePrintLogEntry: (
  6048. id: number,
  6049. body: { failure_reason?: string | null; status?: string; notes?: string | null },
  6050. ) =>
  6051. request<PrintLogEntry>(`/print-log/${id}`, {
  6052. method: 'PATCH',
  6053. body: JSON.stringify(body),
  6054. }),
  6055. // Settings
  6056. getSettings: () => request<AppSettings>('/settings/'),
  6057. getDefaultSidebarOrder: () => request<{ default_sidebar_order: string }>('/settings/default-sidebar-order'),
  6058. // Public subset of settings for UI rendering — no settings:read required.
  6059. // Used by pages whose users may not have SETTINGS_READ (e.g. operators with
  6060. // only printers:clear_plate). Keep in sync with _UI_PREFERENCE_FIELDS in
  6061. // backend/app/api/routes/settings.py.
  6062. getUiPreferences: () =>
  6063. request<{
  6064. require_plate_clear?: boolean;
  6065. check_printer_firmware?: boolean;
  6066. camera_view_mode?: 'window' | 'embedded';
  6067. time_format?: 'system' | '12h' | '24h';
  6068. date_format?: string;
  6069. drying_presets?: string;
  6070. ams_humidity_thresholds?: string;
  6071. ams_humidity_good?: number;
  6072. ams_humidity_fair?: number;
  6073. ams_temp_good?: number;
  6074. ams_temp_fair?: number;
  6075. bed_cooled_threshold?: number;
  6076. nozzle_temp_presets?: string;
  6077. bed_temp_presets?: string;
  6078. chamber_temp_presets?: string;
  6079. fan_speed_presets?: string;
  6080. }>('/settings/ui-preferences'),
  6081. // Install configuration the app shell needs, for any signed-in user. Separate
  6082. // from getUiPreferences: that endpoint is public because its fields are
  6083. // defaults shipped with the app, while these describe how this deployment is
  6084. // configured. Neither requires settings:read -- which is the point, since a
  6085. // non-admin reading GET /settings gets a 403 and every gate that consults it
  6086. // silently takes its fallback (#3023). Keep in sync with _UI_FLAG_FIELDS in
  6087. // backend/app/api/routes/settings.py.
  6088. getUiFlags: () => request<UiSettings>('/settings/ui-flags'),
  6089. // The two above together: what a page needs from the settings when its user
  6090. // may not read GET /settings. See useUiSettings.
  6091. getUiSettings: async (): Promise<UiSettings> => {
  6092. const [preferences, flags] = await Promise.all([api.getUiPreferences(), api.getUiFlags()]);
  6093. return { ...(preferences as UiSettings), ...flags };
  6094. },
  6095. updateSettings: (data: AppSettingsUpdate) =>
  6096. request<AppSettings>('/settings/', {
  6097. method: 'PUT',
  6098. body: JSON.stringify(data),
  6099. }),
  6100. getMQTTStatus: () => request<MQTTStatus>('/settings/mqtt/status'),
  6101. exportBackup: async (): Promise<{ blob: Blob; filename: string }> => {
  6102. // New simplified backup - complete database + all files
  6103. const url = `${API_BASE}/settings/backup`;
  6104. const headers: Record<string, string> = {};
  6105. if (authToken) {
  6106. headers['Authorization'] = `Bearer ${authToken}`;
  6107. }
  6108. const response = await fetch(url, { headers });
  6109. // Check for errors
  6110. if (!response.ok) {
  6111. const errorText = await response.text();
  6112. throw new Error(errorText || `Backup failed with status ${response.status}`);
  6113. }
  6114. // Get filename from Content-Disposition header
  6115. const contentDisposition = response.headers.get('Content-Disposition');
  6116. let filename = 'bambuddy-backup.zip';
  6117. if (contentDisposition) {
  6118. const match = contentDisposition.match(/filename=([^;]+)/);
  6119. if (match) filename = match[1].trim().replace(/^"(.*)"$/, '$1');
  6120. }
  6121. const blob = await response.blob();
  6122. return { blob, filename };
  6123. },
  6124. importBackup: async (file: File) => {
  6125. // New simplified restore - replaces database + all directories
  6126. const formData = new FormData();
  6127. formData.append('file', file);
  6128. const url = `${API_BASE}/settings/restore`;
  6129. const headers: Record<string, string> = {};
  6130. if (authToken) {
  6131. headers['Authorization'] = `Bearer ${authToken}`;
  6132. }
  6133. const response = await fetch(url, {
  6134. method: 'POST',
  6135. headers,
  6136. body: formData,
  6137. });
  6138. const data = (await response.json().catch(() => null)) as {
  6139. success?: boolean;
  6140. message?: string;
  6141. detail?: string;
  6142. } | null;
  6143. // A refused restore is an HTTPException, so the body is {detail}, not
  6144. // {success, message}. Returning it unmapped made `success` undefined and
  6145. // `message` undefined too — the modal then raised an empty error toast,
  6146. // which is the one case where the reason matters most (e.g. a backup this
  6147. // version cannot import names the columns and both versions).
  6148. if (!response.ok) {
  6149. return { success: false, message: data?.detail ?? data?.message ?? '' };
  6150. }
  6151. return (data ?? { success: false, message: '' }) as {
  6152. success: boolean;
  6153. message: string;
  6154. };
  6155. },
  6156. checkFfmpeg: () =>
  6157. request<{ installed: boolean; path: string | null }>('/settings/check-ffmpeg'),
  6158. getNetworkInterfaces: () =>
  6159. request<{ interfaces: NetworkInterface[] }>('/settings/network-interfaces'),
  6160. // Cloud
  6161. getCloudStatus: () => request<CloudAuthStatus>('/cloud/status'),
  6162. cloudLogin: (email: string, password: string, region = 'global') =>
  6163. request<CloudLoginResponse>('/cloud/login', {
  6164. method: 'POST',
  6165. body: JSON.stringify({ email, password, region }),
  6166. }),
  6167. cloudVerify: (email: string, code: string, tfaKey?: string, region: string = 'global') =>
  6168. request<CloudLoginResponse>('/cloud/verify', {
  6169. method: 'POST',
  6170. body: JSON.stringify({ email, code, tfa_key: tfaKey, region }),
  6171. }),
  6172. cloudSetToken: (access_token: string, region: string = 'global') =>
  6173. request<CloudAuthStatus>('/cloud/token', {
  6174. method: 'POST',
  6175. body: JSON.stringify({ access_token, region }),
  6176. }),
  6177. cloudLogout: () =>
  6178. request<{ success: boolean }>('/cloud/logout', { method: 'POST' }),
  6179. // Orca Cloud — RFC 8628 device pairing. deviceStart() returns a short
  6180. // user_code + verification link; the user approves it in their Orca Cloud
  6181. // settings while the frontend polls devicePoll() every `interval` seconds
  6182. // until the status flips to 'complete' (or a terminal deny/expire).
  6183. orcaCloudDeviceStart: () =>
  6184. request<OrcaDeviceStartResponse>('/orca-cloud/device/start', {
  6185. method: 'POST',
  6186. }),
  6187. orcaCloudDevicePoll: () =>
  6188. request<OrcaDevicePollResponse>('/orca-cloud/device/poll', {
  6189. method: 'POST',
  6190. }),
  6191. orcaCloudStatus: () =>
  6192. request<OrcaAuthStatusResponse>('/orca-cloud/status'),
  6193. orcaCloudLogout: () =>
  6194. request<{ success: boolean }>('/orca-cloud/logout', { method: 'POST' }),
  6195. orcaCloudListProfiles: () =>
  6196. request<OrcaProfileListResponse>('/orca-cloud/profiles'),
  6197. orcaCloudGetProfile: (id: string) =>
  6198. request<OrcaProfileDetail>(`/orca-cloud/profiles/${id}`),
  6199. getCloudSettings: (version = '02.04.00.70') =>
  6200. request<SlicerSettingsResponse>(`/cloud/settings?version=${version}`),
  6201. getBuiltinFilaments: () =>
  6202. request<BuiltinFilament[]>('/cloud/builtin-filaments'),
  6203. getFilamentIdMap: () =>
  6204. request<Record<string, string>>('/cloud/filament-id-map'),
  6205. /** Material-disambiguated hex→name lookup. Same hex can map to different
  6206. * catalog names depending on material (e.g. #000000 is "Charcoal" in PLA
  6207. * Matte but "Black" in PLA Basic). The flat ``/inventory/colors/map``
  6208. * collapses these to the first hit; this endpoint preserves the material
  6209. * context. Returns ``{color_name: null}`` when the hex isn't in the
  6210. * catalog at all. #1718. */
  6211. getColorByMaterial: (hex: string, material?: string) => {
  6212. const params = new URLSearchParams({ hex });
  6213. if (material) params.set('material', material);
  6214. return request<{ color_name: string | null }>(
  6215. `/inventory/colors/by-material?${params.toString()}`,
  6216. );
  6217. },
  6218. // MakerWorld URL-paste import flow.
  6219. getMakerworldStatus: () =>
  6220. request<MakerworldStatus>('/makerworld/status'),
  6221. resolveMakerworldUrl: (url: string) =>
  6222. request<MakerworldResolvedModel>('/makerworld/resolve', {
  6223. method: 'POST',
  6224. body: JSON.stringify({ url }),
  6225. }),
  6226. getMakerworldRecentImports: (limit = 10) =>
  6227. request<MakerworldRecentImport[]>(`/makerworld/recent-imports?limit=${limit}`),
  6228. importMakerworldInstance: (
  6229. model_id: number,
  6230. instance_id: number | null,
  6231. profile_id?: number | null,
  6232. folder_id?: number | null,
  6233. ) =>
  6234. request<MakerworldImportResponse>('/makerworld/import', {
  6235. method: 'POST',
  6236. body: JSON.stringify({
  6237. model_id,
  6238. instance_id: instance_id ?? null,
  6239. profile_id: profile_id ?? null,
  6240. folder_id: folder_id ?? null,
  6241. }),
  6242. }),
  6243. // Manyfold (#1471).
  6244. getManyfoldConfig: () => request<ManyfoldConfig>('/manyfold/config'),
  6245. updateManyfoldConfig: (data: ManyfoldConfigInput) =>
  6246. request<ManyfoldConfig>('/manyfold/config', { method: 'PUT', body: JSON.stringify(data) }),
  6247. deleteManyfoldConfig: () => request<void>('/manyfold/config', { method: 'DELETE' }),
  6248. testManyfoldConfig: (data: ManyfoldConfigInput) =>
  6249. request<{ model_count: number }>('/manyfold/config/test', { method: 'POST', body: JSON.stringify(data) }),
  6250. getManyfoldStatus: () => request<ManyfoldStatus>('/manyfold/status'),
  6251. listManyfoldModels: (query: string, page: number) => {
  6252. const params = new URLSearchParams({ page: String(page) });
  6253. if (query) params.set('q', query);
  6254. return request<ManyfoldModelList>(`/manyfold/models?${params.toString()}`);
  6255. },
  6256. getManyfoldModel: (modelId: string) =>
  6257. request<ManyfoldModel>(`/manyfold/models/${encodeURIComponent(modelId)}`),
  6258. /** The model's preview, or null when it has none. Fetched rather than used
  6259. * as an <img src>: a failing protected <img> makes the app renew its media
  6260. * token, and models without a preview answer 404. */
  6261. getManyfoldPreview: async (modelId: string): Promise<Blob | null> => {
  6262. const headers: Record<string, string> = {};
  6263. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  6264. const response = await fetch(`${API_BASE}/manyfold/models/${encodeURIComponent(modelId)}/preview`, { headers });
  6265. if (!response.ok) return null;
  6266. return response.blob();
  6267. },
  6268. importManyfoldFile: (modelId: string, fileId: string, folderId: number | null) =>
  6269. request<ManyfoldImportResponse>('/manyfold/import', {
  6270. method: 'POST',
  6271. body: JSON.stringify({ model_id: modelId, file_id: fileId, folder_id: folderId }),
  6272. }),
  6273. getCloudSettingDetail: (settingId: string) =>
  6274. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`),
  6275. createCloudSetting: (data: SlicerSettingCreate) =>
  6276. request<SlicerSettingDetail>('/cloud/settings', {
  6277. method: 'POST',
  6278. body: JSON.stringify(data),
  6279. }),
  6280. updateCloudSetting: (settingId: string, data: SlicerSettingUpdate) =>
  6281. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`, {
  6282. method: 'PUT',
  6283. body: JSON.stringify(data),
  6284. }),
  6285. deleteCloudSetting: (settingId: string) =>
  6286. request<SlicerSettingDeleteResponse>(`/cloud/settings/${settingId}`, {
  6287. method: 'DELETE',
  6288. }),
  6289. getCloudFields: (presetType: 'filament' | 'print' | 'process' | 'printer') =>
  6290. request<FieldDefinitionsResponse>(`/cloud/fields/${presetType}`),
  6291. getFilamentInfo: (settingIds: string[]) =>
  6292. request<Record<string, { name: string; k: number | null }>>('/cloud/filament-info', {
  6293. method: 'POST',
  6294. body: JSON.stringify(settingIds),
  6295. }),
  6296. // Smart Plugs
  6297. getSmartPlugs: () => request<SmartPlug[]>('/smart-plugs/'),
  6298. getSmartPlugByPrinter: (printerId: number) => smartPlugBatch(printerId),
  6299. getScriptPlugsByPrinter: (printerId: number) => scriptPlugsBatch(printerId),
  6300. createSmartPlug: (data: SmartPlugCreate) =>
  6301. request<SmartPlug>('/smart-plugs/', {
  6302. method: 'POST',
  6303. body: JSON.stringify(data),
  6304. }),
  6305. updateSmartPlug: (id: number, data: SmartPlugUpdate) =>
  6306. request<SmartPlug>(`/smart-plugs/${id}`, {
  6307. method: 'PATCH',
  6308. body: JSON.stringify(data),
  6309. }),
  6310. deleteSmartPlug: (id: number) =>
  6311. request<void>(`/smart-plugs/${id}`, { method: 'DELETE' }),
  6312. controlSmartPlug: (id: number, action: 'on' | 'off' | 'toggle') =>
  6313. request<{ success: boolean; action: string }>(`/smart-plugs/${id}/control`, {
  6314. method: 'POST',
  6315. body: JSON.stringify({ action }),
  6316. }),
  6317. getSmartPlugStatus: (id: number) =>
  6318. request<SmartPlugStatus>(`/smart-plugs/${id}/status`),
  6319. // plug_id: the saved plug being edited, whose stored password fills in the placeholder.
  6320. testSmartPlugConnection: (ip_address: string, username?: string | null, password?: string | null, plug_id?: number) =>
  6321. request<SmartPlugTestResult>('/smart-plugs/test-connection', {
  6322. method: 'POST',
  6323. body: JSON.stringify({ ip_address, username, password, plug_id }),
  6324. }),
  6325. // Tasmota Discovery (auto-detects network)
  6326. startTasmotaScan: () =>
  6327. request<TasmotaScanStatus>('/smart-plugs/discover/scan', { method: 'POST' }),
  6328. getTasmotaScanStatus: () =>
  6329. request<TasmotaScanStatus>('/smart-plugs/discover/status'),
  6330. stopTasmotaScan: () =>
  6331. request<TasmotaScanStatus>('/smart-plugs/discover/stop', { method: 'POST' }),
  6332. getDiscoveredTasmotaDevices: () =>
  6333. request<DiscoveredTasmotaDevice[]>('/smart-plugs/discover/devices'),
  6334. // Home Assistant Integration
  6335. testHAConnection: (url: string, token: string) =>
  6336. request<HATestConnectionResult>('/smart-plugs/ha/test-connection', {
  6337. method: 'POST',
  6338. body: JSON.stringify({ url, token }),
  6339. }),
  6340. getHAEntities: (search?: string) => {
  6341. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  6342. return request<HAEntity[]>(`/smart-plugs/ha/entities${params}`);
  6343. },
  6344. getHASensorEntities: () =>
  6345. request<HASensorEntity[]>('/smart-plugs/ha/sensors'),
  6346. // Home Assistant sensors bound to a printer (#1148, #448)
  6347. getHASensors: (printerId?: number) =>
  6348. request<PrinterHASensor[]>(`/ha-sensors/${printerId ? `?printer_id=${printerId}` : ''}`),
  6349. getHASensorReadings: (printerId: number) => haSensorReadingsBatch(printerId),
  6350. getBindableHAEntities: (search?: string) => {
  6351. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  6352. return request<HADisplayEntity[]>(`/ha-sensors/entities${params}`);
  6353. },
  6354. createHASensor: (data: PrinterHASensorCreate) =>
  6355. request<PrinterHASensor>('/ha-sensors/', { method: 'POST', body: JSON.stringify(data) }),
  6356. updateHASensor: (id: number, data: PrinterHASensorUpdate) =>
  6357. request<PrinterHASensor>(`/ha-sensors/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  6358. deleteHASensor: (id: number) =>
  6359. request<{ message: string }>(`/ha-sensors/${id}`, { method: 'DELETE' }),
  6360. getLocationHASensors: (locationId?: number) =>
  6361. request<LocationHASensor[]>(`/location-ha-sensors/${locationId ? `?location_id=${locationId}` : ''}`),
  6362. getLocationHASensorReadings: (locationId: number, showOnCard = true) =>
  6363. request<LocationHASensorReading[]>(
  6364. `/location-ha-sensors/by-location/${locationId}/readings?show_on_card=${showOnCard}`
  6365. ),
  6366. getBindableLocationHAEntities: (search?: string) => {
  6367. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  6368. return request<HADisplayEntity[]>(`/location-ha-sensors/entities${params}`);
  6369. },
  6370. createLocationHASensor: (data: LocationHASensorCreate) =>
  6371. request<LocationHASensor>('/location-ha-sensors/', { method: 'POST', body: JSON.stringify(data) }),
  6372. updateLocationHASensor: (id: number, data: LocationHASensorUpdate) =>
  6373. request<LocationHASensor>(`/location-ha-sensors/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  6374. deleteLocationHASensor: (id: number) =>
  6375. request<{ message: string }>(`/location-ha-sensors/${id}`, { method: 'DELETE' }),
  6376. // REST smart plug
  6377. // plug_id: the saved plug being edited, whose stored headers fill in the placeholder.
  6378. testRESTConnection: (url: string, method: string = 'GET', headers?: string | null, plug_id?: number) =>
  6379. request<{ success: boolean; error: string | null }>('/smart-plugs/rest/test-connection', {
  6380. method: 'POST',
  6381. body: JSON.stringify({ url, method, headers, plug_id }),
  6382. }),
  6383. // Print Queue
  6384. getQueue: (printerId?: number, status?: string, targetModel?: string) => {
  6385. const params = new URLSearchParams();
  6386. if (printerId) params.set('printer_id', String(printerId));
  6387. if (status) params.set('status', status);
  6388. if (targetModel) params.set('target_model', targetModel);
  6389. return request<PrintQueueItem[]>(`/queue/?${params}`);
  6390. },
  6391. // History (completed / failed / skipped / cancelled), one page at a time.
  6392. getQueueHistory: (params: QueueHistoryParams) =>
  6393. request<QueueHistoryPage>(`/queue/history?${queueHistorySearch(params)}`),
  6394. // Removes the history matching the same filters, server-side.
  6395. clearQueueHistory: (params: QueueHistoryFilters) =>
  6396. request<{ cleared: number; kept: number }>(`/queue/history/clear?${queueHistorySearch(params)}`, {
  6397. method: 'POST',
  6398. }),
  6399. // One printer's queue as GET /queue/?printer_id= returns it: its own jobs
  6400. // plus the "Any <model>" jobs for its model. Batched across printer cards.
  6401. getPrinterQueue: (printerId: number, status: string) => printerQueueBatch(status)(printerId),
  6402. addToQueue: (data: PrintQueueItemCreate) =>
  6403. request<PrintQueueItem>('/queue/', {
  6404. method: 'POST',
  6405. body: JSON.stringify(data),
  6406. }),
  6407. updateQueueItem: (id: number, data: PrintQueueItemUpdate) =>
  6408. request<PrintQueueItem>(`/queue/${id}`, {
  6409. method: 'PATCH',
  6410. body: JSON.stringify(data),
  6411. }),
  6412. /** `deleted` is false when the item was kept as cancelled instead: it is the
  6413. * last run a batch order could re-queue its plate from (#2960). */
  6414. removeFromQueue: (id: number) =>
  6415. request<{ message: string; deleted: boolean }>(`/queue/${id}`, { method: 'DELETE' }),
  6416. reorderQueue: (items: { id: number; position: number }[]) =>
  6417. request<{ message: string }>('/queue/reorder', {
  6418. method: 'POST',
  6419. body: JSON.stringify({ items }),
  6420. }),
  6421. cancelQueueItem: (id: number) =>
  6422. request<{ message: string }>(`/queue/${id}/cancel`, { method: 'POST' }),
  6423. stopQueueItem: (id: number) =>
  6424. request<{ message: string }>(`/queue/${id}/stop`, { method: 'POST' }),
  6425. /**
  6426. * Start a staged queue item. The backend re-checks live filament deficit
  6427. * for the assigned spool and, when short, returns 409 with a structured
  6428. * payload so the caller can confirm and retry. Pass `skipFilamentCheck`
  6429. * after the user confirms "Print Anyway" (#1496).
  6430. */
  6431. startQueueItem: (id: number, opts?: { skipFilamentCheck?: boolean }) => {
  6432. const qs = opts?.skipFilamentCheck ? '?skip_filament_check=true' : '';
  6433. return request<PrintQueueItem>(`/queue/${id}/start${qs}`, { method: 'POST' });
  6434. },
  6435. /**
  6436. * Clear the `require_previous_success` gate for a printer after the user
  6437. * resolves the failure. Acknowledges any failed/aborted predecessors and
  6438. * restores skipped items whose error_message matches the gate string
  6439. * back to pending. Returns counts so the UI can render a precise toast.
  6440. */
  6441. // A job for any printer of a model waits when the last print failed on every
  6442. // free one; this clears the gate on the model's printers.
  6443. resumeModelQueueAfterFailure: (model: string) =>
  6444. request<{ acknowledged: number; printers: number }>(
  6445. `/queue/model/${encodeURIComponent(model)}/resume`,
  6446. { method: 'POST' },
  6447. ),
  6448. resumeQueueAfterFailure: (printerId: number) =>
  6449. request<{ acknowledged: number; restored: number }>(
  6450. `/queue/printer/${printerId}/resume`,
  6451. { method: 'POST' },
  6452. ),
  6453. bulkUpdateQueue: (data: PrintQueueBulkUpdate) =>
  6454. request<PrintQueueBulkUpdateResponse>('/queue/bulk', {
  6455. method: 'PATCH',
  6456. body: JSON.stringify(data),
  6457. }),
  6458. // Batches
  6459. getBatches: (status?: string) => {
  6460. const params = status ? `?status=${status}` : '';
  6461. return request<PrintBatch[]>(`/queue/batches${params}`);
  6462. },
  6463. cancelBatch: (id: number) =>
  6464. request<{ message: string }>(`/queue/batches/${id}`, { method: 'DELETE' }),
  6465. createBatch: (data: PrintBatchCreate) =>
  6466. request<PrintBatch>('/queue/batches', {
  6467. method: 'POST',
  6468. body: JSON.stringify(data),
  6469. }),
  6470. dispatchBatch: (id: number, data: PrintBatchDispatchRequest = {}) =>
  6471. request<PrintBatch>(`/queue/batches/${id}/dispatch`, {
  6472. method: 'POST',
  6473. body: JSON.stringify(data),
  6474. }),
  6475. ungroupBatch: (id: number) =>
  6476. request<{ ungrouped_count: number; message: string }>(
  6477. `/queue/batches/${id}/ungroup`,
  6478. { method: 'POST' },
  6479. ),
  6480. // K-Profiles
  6481. getKProfiles: (printerId: number, nozzleDiameter = '0.4') =>
  6482. request<KProfilesResponse>(`/printers/${printerId}/kprofiles/?nozzle_diameter=${nozzleDiameter}`),
  6483. setKProfile: (printerId: number, profile: KProfileCreate) =>
  6484. request<KProfileWriteResult>(`/printers/${printerId}/kprofiles/`, {
  6485. method: 'POST',
  6486. body: JSON.stringify(profile),
  6487. }),
  6488. deleteKProfile: (printerId: number, profile: KProfileDelete) =>
  6489. request<KProfileWriteResult>(`/printers/${printerId}/kprofiles/`, {
  6490. method: 'DELETE',
  6491. body: JSON.stringify(profile),
  6492. }),
  6493. setKProfilesBatch: (printerId: number, profiles: KProfileCreate[]) =>
  6494. request<KProfileWriteResult>(`/printers/${printerId}/kprofiles/batch`, {
  6495. method: 'POST',
  6496. body: JSON.stringify(profiles),
  6497. }),
  6498. // Finance
  6499. getMyBalance: () => request<WalletBalance>('/finance/me/balance'),
  6500. getMyTransactions: (limit = 50, offset = 0) =>
  6501. request<WalletTransactionListResponse>(`/finance/me/transactions?limit=${limit}&offset=${offset}`),
  6502. getAllTransactions: (limit = 50, offset = 0, userId?: number) => {
  6503. const params = new URLSearchParams();
  6504. params.set('limit', String(limit));
  6505. params.set('offset', String(offset));
  6506. if (userId !== undefined) params.set('user_id', String(userId));
  6507. return request<WalletTransactionListResponse>(`/finance/transactions?${params.toString()}`);
  6508. },
  6509. deleteTransaction: (transactionId: number) =>
  6510. request<{ status: string }>(`/finance/transactions/${transactionId}`, {
  6511. method: 'DELETE',
  6512. }),
  6513. editTransaction: (transactionId: number, data: TransactionEditRequest) =>
  6514. request<WalletTransaction>(`/finance/transactions/${transactionId}`, {
  6515. method: 'PATCH',
  6516. body: JSON.stringify(data),
  6517. }),
  6518. createManualPrint: (data: ManualPrintRequest) =>
  6519. request<WalletTransaction>('/finance/transactions/manual', {
  6520. method: 'POST',
  6521. body: JSON.stringify(data),
  6522. }),
  6523. getMyCostCenters: () => request<CostCenterSummary[]>('/finance/cost-centers/mine'),
  6524. listCostCenters: (includeInactive = false) =>
  6525. request<CostCenterSummary[]>(`/finance/cost-centers?include_inactive=${includeInactive ? 'true' : 'false'}`),
  6526. createCostCenter: (data: CostCenterCreateRequest) =>
  6527. request<CostCenterSummary>('/finance/cost-centers', {
  6528. method: 'POST',
  6529. body: JSON.stringify(data),
  6530. }),
  6531. updateCostCenter: (costCenterId: number, data: CostCenterUpdateRequest) =>
  6532. request<CostCenterSummary>(`/finance/cost-centers/${costCenterId}`, {
  6533. method: 'PATCH',
  6534. body: JSON.stringify(data),
  6535. }),
  6536. updateCostCenterBudgets: (costCenterId: number, data: CostCenterBudgetUpdateRequest) =>
  6537. request<CostCenterSummary>(`/finance/cost-centers/${costCenterId}/budgets`, {
  6538. method: 'PATCH',
  6539. body: JSON.stringify(data),
  6540. }),
  6541. deleteCostCenter: (costCenterId: number) =>
  6542. request<{ status: string }>(`/finance/cost-centers/${costCenterId}`, {
  6543. method: 'DELETE',
  6544. }),
  6545. getCostCenter: (costCenterId: number) =>
  6546. request<CostCenterDetail>(`/finance/cost-centers/${costCenterId}`),
  6547. upsertCostCenterMember: (costCenterId: number, data: CostCenterMemberRequest) =>
  6548. request<CostCenterMemberResponse>(`/finance/cost-centers/${costCenterId}/members`, {
  6549. method: 'POST',
  6550. body: JSON.stringify(data),
  6551. }),
  6552. removeCostCenterMember: (costCenterId: number, userId: number) =>
  6553. request<{ status: string }>(`/finance/cost-centers/${costCenterId}/members/${userId}`, {
  6554. method: 'DELETE',
  6555. }),
  6556. depositUserBalance: (userId: number, data: WalletAdjustmentRequest) =>
  6557. request<WalletAdjustmentResponse>(`/finance/users/${userId}/deposit`, {
  6558. method: 'POST',
  6559. body: JSON.stringify(data),
  6560. }),
  6561. withdrawUserBalance: (userId: number, data: WalletAdjustmentRequest) =>
  6562. request<WalletAdjustmentResponse>(`/finance/users/${userId}/withdraw`, {
  6563. method: 'POST',
  6564. body: JSON.stringify(data),
  6565. }),
  6566. rebuildBalanceLedger: () =>
  6567. request<{ status: string }>('/finance/rebuild-balance-ledger', {
  6568. method: 'POST',
  6569. }),
  6570. // K-Profile Notes (stored locally, not on printer)
  6571. getKProfileNotes: (printerId: number) =>
  6572. request<KProfileNotesResponse>(`/printers/${printerId}/kprofiles/notes`),
  6573. setKProfileNote: (printerId: number, settingId: string, note: string) =>
  6574. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/notes`, {
  6575. method: 'PUT',
  6576. body: JSON.stringify({ setting_id: settingId, note }),
  6577. }),
  6578. // Slot Preset Mappings
  6579. getSlotPresets: (printerId: number) => slotPresetsBatch(printerId),
  6580. saveSlotPreset: (printerId: number, amsId: number, trayId: number, presetId: string, presetName: string, presetSource = 'cloud', trayInfoIdx?: string) =>
  6581. 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)}` : ''}`, {
  6582. method: 'PUT',
  6583. }),
  6584. // AMS Labels (user-defined friendly names)
  6585. getAmsLabels: (printerId: number) => amsLabelsBatch(printerId),
  6586. saveAmsLabel: (printerId: number, amsId: number, label: string, amsSerial = '') =>
  6587. request<{ ams_id: number; label: string }>(
  6588. `/printers/${printerId}/ams-labels/${amsId}`,
  6589. {
  6590. method: 'PUT',
  6591. body: JSON.stringify({ label, ams_serial: amsSerial }),
  6592. }
  6593. ),
  6594. deleteAmsLabel: (printerId: number, amsId: number, amsSerial = '') =>
  6595. request<{ success: boolean }>(`/printers/${printerId}/ams-labels/${amsId}?ams_serial=${encodeURIComponent(amsSerial)}`, {
  6596. method: 'DELETE',
  6597. }),
  6598. configureAmsSlot: (
  6599. printerId: number,
  6600. amsId: number,
  6601. trayId: number,
  6602. config: {
  6603. tray_info_idx: string;
  6604. tray_type: string;
  6605. tray_sub_brands: string;
  6606. tray_color: string;
  6607. nozzle_temp_min: number;
  6608. nozzle_temp_max: number;
  6609. cali_idx: number;
  6610. nozzle_diameter: string;
  6611. setting_id?: string;
  6612. kprofile_filament_id?: string;
  6613. kprofile_setting_id?: string;
  6614. k_value?: number;
  6615. // Orca Cloud profile the slot is set to; the backend looks up its
  6616. // filament id when tray_info_idx is empty (#3216).
  6617. orca_profile_id?: string;
  6618. }
  6619. ) => {
  6620. const params = new URLSearchParams({
  6621. tray_info_idx: config.tray_info_idx,
  6622. tray_type: config.tray_type,
  6623. tray_sub_brands: config.tray_sub_brands,
  6624. tray_color: config.tray_color,
  6625. nozzle_temp_min: config.nozzle_temp_min.toString(),
  6626. nozzle_temp_max: config.nozzle_temp_max.toString(),
  6627. cali_idx: config.cali_idx.toString(),
  6628. nozzle_diameter: config.nozzle_diameter,
  6629. });
  6630. if (config.setting_id) {
  6631. params.set('setting_id', config.setting_id);
  6632. }
  6633. if (config.kprofile_filament_id) {
  6634. params.set('kprofile_filament_id', config.kprofile_filament_id);
  6635. }
  6636. if (config.kprofile_setting_id) {
  6637. params.set('kprofile_setting_id', config.kprofile_setting_id);
  6638. }
  6639. if (config.k_value !== undefined && config.k_value > 0) {
  6640. params.set('k_value', config.k_value.toString());
  6641. }
  6642. if (config.orca_profile_id) {
  6643. params.set('orca_profile_id', config.orca_profile_id);
  6644. }
  6645. return request<{
  6646. success: boolean;
  6647. message: string;
  6648. // The filament id the slot was actually given.
  6649. tray_info_idx?: string;
  6650. // Why an Orca profile went out as the generic for its material, or "".
  6651. orca_fallback_reason?: '' | 'no_filament_id' | 'lookup_failed' | 'no_permission';
  6652. /** A manual K value could not be sent; the filament setting was. */
  6653. k_value_unsent?: boolean;
  6654. }>(
  6655. `/printers/${printerId}/slots/${amsId}/${trayId}/configure?${params}`,
  6656. { method: 'POST' }
  6657. );
  6658. },
  6659. resetAmsSlot: (printerId: number, amsId: number, trayId: number) =>
  6660. request<{ success: boolean; message: string }>(
  6661. `/printers/${printerId}/ams/${amsId}/tray/${trayId}/reset`,
  6662. { method: 'POST' }
  6663. ),
  6664. // Notification Providers
  6665. getNotificationProviders: () => request<NotificationProvider[]>('/notifications/'),
  6666. createNotificationProvider: (data: NotificationProviderCreate) =>
  6667. request<NotificationProvider>('/notifications/', {
  6668. method: 'POST',
  6669. body: JSON.stringify(data),
  6670. }),
  6671. updateNotificationProvider: (id: number, data: NotificationProviderUpdate) =>
  6672. request<NotificationProvider>(`/notifications/${id}`, {
  6673. method: 'PATCH',
  6674. body: JSON.stringify(data),
  6675. }),
  6676. deleteNotificationProvider: (id: number) =>
  6677. request<{ message: string }>(`/notifications/${id}`, { method: 'DELETE' }),
  6678. testNotificationProvider: (id: number) =>
  6679. request<NotificationTestResponse>(`/notifications/${id}/test`, { method: 'POST' }),
  6680. testNotificationConfig: (data: NotificationTestRequest) =>
  6681. request<NotificationTestResponse>('/notifications/test-config', {
  6682. method: 'POST',
  6683. body: JSON.stringify(data),
  6684. }),
  6685. testAllNotificationProviders: () =>
  6686. request<{
  6687. tested: number;
  6688. success: number;
  6689. failed: number;
  6690. results: Array<{
  6691. provider_id: number;
  6692. provider_name: string;
  6693. provider_type: string;
  6694. success: boolean;
  6695. message: string;
  6696. }>;
  6697. }>('/notifications/test-all', { method: 'POST' }),
  6698. // Notification Templates
  6699. getNotificationTemplates: () => request<NotificationTemplate[]>('/notification-templates'),
  6700. updateNotificationTemplate: (id: number, data: NotificationTemplateUpdate) =>
  6701. request<NotificationTemplate>(`/notification-templates/${id}`, {
  6702. method: 'PUT',
  6703. body: JSON.stringify(data),
  6704. }),
  6705. resetNotificationTemplate: (id: number) =>
  6706. request<NotificationTemplate>(`/notification-templates/${id}/reset`, {
  6707. method: 'POST',
  6708. }),
  6709. getTemplateVariables: () => request<EventVariablesResponse[]>('/notification-templates/variables'),
  6710. previewTemplate: (data: TemplatePreviewRequest) =>
  6711. request<TemplatePreviewResponse>('/notification-templates/preview', {
  6712. method: 'POST',
  6713. body: JSON.stringify(data),
  6714. }),
  6715. // Notification Logs
  6716. getNotificationLogs: (params?: {
  6717. limit?: number;
  6718. offset?: number;
  6719. provider_id?: number;
  6720. event_type?: string;
  6721. success?: boolean;
  6722. days?: number;
  6723. }) => {
  6724. const searchParams = new URLSearchParams();
  6725. if (params?.limit) searchParams.set('limit', String(params.limit));
  6726. if (params?.offset) searchParams.set('offset', String(params.offset));
  6727. if (params?.provider_id) searchParams.set('provider_id', String(params.provider_id));
  6728. if (params?.event_type) searchParams.set('event_type', params.event_type);
  6729. if (params?.success !== undefined) searchParams.set('success', String(params.success));
  6730. if (params?.days) searchParams.set('days', String(params.days));
  6731. return request<NotificationLogEntry[]>(`/notifications/logs?${searchParams}`);
  6732. },
  6733. getNotificationLogStats: (days = 7) =>
  6734. request<NotificationLogStats>(`/notifications/logs/stats?days=${days}`),
  6735. clearNotificationLogs: (olderThanDays = 30) =>
  6736. request<{ deleted: number; message: string }>(
  6737. `/notifications/logs?older_than_days=${olderThanDays}`,
  6738. { method: 'DELETE' }
  6739. ),
  6740. // Spoolman Integration
  6741. getSpoolmanStatus: () => request<SpoolmanStatus>('/spoolman/status'),
  6742. migrateSpoolmanTags: (dryRun: boolean) =>
  6743. request<SpoolmanTagMigrationReport>(`/spoolman/inventory/tags/migrate?dry_run=${dryRun}`, {
  6744. method: 'POST',
  6745. }),
  6746. connectSpoolman: () =>
  6747. request<{ success: boolean; message: string }>('/spoolman/connect', {
  6748. method: 'POST',
  6749. }),
  6750. syncPrinterAms: (printerId: number) =>
  6751. request<SpoolmanSyncResult>(`/spoolman/sync/${printerId}`, {
  6752. method: 'POST',
  6753. }),
  6754. syncAllPrintersAms: () =>
  6755. request<SpoolmanSyncResult>('/spoolman/sync-all', {
  6756. method: 'POST',
  6757. }),
  6758. getSpoolmanInventoryFilaments: () =>
  6759. request<SpoolmanFilamentEntry[]>('/spoolman/inventory/filaments'),
  6760. getUnlinkedSpools: () =>
  6761. request<UnlinkedSpool[]>('/spoolman/spools/unlinked'),
  6762. getLinkedSpools: () =>
  6763. request<LinkedSpoolsMap>('/spoolman/spools/linked'),
  6764. linkSpool: (
  6765. spoolId: number,
  6766. context: {
  6767. spoolTag: string;
  6768. printerId: number;
  6769. amsId: number;
  6770. trayId: number;
  6771. }
  6772. ) =>
  6773. request<{ success: boolean; message: string }>(`/spoolman/spools/${spoolId}/link`, {
  6774. method: 'POST',
  6775. body: JSON.stringify({
  6776. spool_tag: context.spoolTag,
  6777. printer_id: context.printerId,
  6778. ams_id: context.amsId,
  6779. tray_id: context.trayId,
  6780. }),
  6781. }),
  6782. unlinkSpool: (spoolId: number) =>
  6783. request<{ success: boolean; message: string }>(`/spoolman/spools/${spoolId}/unlink`, {
  6784. method: 'POST',
  6785. }),
  6786. createSpoolmanSpoolFromSlot: (data: { printer_id: number; ams_id: number; tray_id: number }) =>
  6787. request<{ success: boolean; spool_id: number | null }>(`/spoolman/spools/from-slot`, {
  6788. method: 'POST',
  6789. body: JSON.stringify(data),
  6790. }),
  6791. createSpoolFromSlot: (data: { printer_id: number; ams_id: number; tray_id: number }) =>
  6792. request<InventorySpool>(`/inventory/spools/from-slot`, {
  6793. method: 'POST',
  6794. body: JSON.stringify(data),
  6795. }),
  6796. getSpoolmanSettings: () =>
  6797. 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'),
  6798. 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; }) =>
  6799. 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', {
  6800. method: 'PUT',
  6801. body: JSON.stringify(data),
  6802. }),
  6803. // Inventory
  6804. getSpools: (includeArchived = false) =>
  6805. request<InventorySpool[]>(`/inventory/spools?include_archived=${includeArchived}`),
  6806. getSpool: (id: number) => request<InventorySpool>(`/inventory/spools/${id}`),
  6807. createSpool: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>) =>
  6808. request<InventorySpool>('/inventory/spools', {
  6809. method: 'POST',
  6810. body: JSON.stringify(data),
  6811. }),
  6812. bulkCreateSpools: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>, quantity: number) =>
  6813. request<InventorySpool[]>('/inventory/spools/bulk', {
  6814. method: 'POST',
  6815. body: JSON.stringify({ spool: data, quantity }),
  6816. }),
  6817. // ── CSV import/export (#1576) ────────────────────────────────────────────
  6818. // dry_run=true → preview (no write); omitted → real import. Both share one
  6819. // multipart upload helper; see `uploadSpoolsCsv` below.
  6820. importSpoolsCsvPreview: (file: File): Promise<CsvImportPreview> => uploadSpoolsCsv<CsvImportPreview>(file, true),
  6821. importSpoolsCsv: (file: File): Promise<CsvImportResult> => uploadSpoolsCsv<CsvImportResult>(file, false),
  6822. exportSpoolsCsv: async (): Promise<void> => {
  6823. const headers: Record<string, string> = {};
  6824. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  6825. const response = await fetch(`${API_BASE}/inventory/spools/export`, { headers });
  6826. if (!response.ok) {
  6827. const error = await response.json().catch(() => ({}));
  6828. throw new Error(error.detail || `HTTP ${response.status}`);
  6829. }
  6830. const disposition = response.headers.get('Content-Disposition');
  6831. const filename = parseContentDispositionFilename(disposition) || 'bambuddy_inventory.csv';
  6832. const blob = await response.blob();
  6833. const url = window.URL.createObjectURL(blob);
  6834. const a = document.createElement('a');
  6835. a.href = url;
  6836. a.download = filename;
  6837. document.body.appendChild(a);
  6838. a.click();
  6839. document.body.removeChild(a);
  6840. window.URL.revokeObjectURL(url);
  6841. },
  6842. updateSpool: (id: number, data: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  6843. request<InventorySpool>(`/inventory/spools/${id}`, {
  6844. method: 'PATCH',
  6845. body: JSON.stringify(data),
  6846. }),
  6847. deleteSpool: (id: number) =>
  6848. request<{ status: string }>(`/inventory/spools/${id}`, { method: 'DELETE' }),
  6849. archiveSpool: (id: number) =>
  6850. request<InventorySpool>(`/inventory/spools/${id}/archive`, { method: 'POST' }),
  6851. restoreSpool: (id: number) =>
  6852. request<InventorySpool>(`/inventory/spools/${id}/restore`, { method: 'POST' }),
  6853. resetSpoolConsumedCounter: (id: number) =>
  6854. request<InventorySpool>(`/inventory/spools/${id}/reset-consumed-counter`, { method: 'POST' }),
  6855. bulkResetSpoolConsumedCounter: (spoolIds: number[]) =>
  6856. request<{ reset: number; not_found?: number[]; errors?: Array<{ id: number; status: number; detail: string }> }>(`/inventory/spools/reset-consumed-counter-bulk`, {
  6857. method: 'POST',
  6858. body: JSON.stringify({ spool_ids: spoolIds }),
  6859. }),
  6860. bulkUpdateSpools: (ids: number[], update: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  6861. request<{ updated: number; not_found: number[] }>(`/inventory/spools/bulk-update`, {
  6862. method: 'POST',
  6863. body: JSON.stringify({ ids, update }),
  6864. }),
  6865. bulkDeleteSpools: (ids: number[]) =>
  6866. request<{ deleted: number; not_found: number[] }>(`/inventory/spools/bulk-delete`, {
  6867. method: 'POST',
  6868. body: JSON.stringify({ ids }),
  6869. }),
  6870. bulkArchiveSpools: (ids: number[]) =>
  6871. request<{ archived: number; already_archived: number[]; not_found: number[] }>(`/inventory/spools/bulk-archive`, {
  6872. method: 'POST',
  6873. body: JSON.stringify({ ids }),
  6874. }),
  6875. bulkRestoreSpools: (ids: number[]) =>
  6876. request<{ restored: number; already_active: number[]; not_found: number[] }>(`/inventory/spools/bulk-restore`, {
  6877. method: 'POST',
  6878. body: JSON.stringify({ ids }),
  6879. }),
  6880. getSpoolKProfiles: (spoolId: number) =>
  6881. request<SpoolKProfile[]>(`/inventory/spools/${spoolId}/k-profiles`),
  6882. saveSpoolKProfiles: (spoolId: number, profiles: SpoolKProfileInput[]) =>
  6883. request<SpoolKProfile[]>(`/inventory/spools/${spoolId}/k-profiles`, {
  6884. method: 'PUT',
  6885. body: JSON.stringify(profiles),
  6886. }),
  6887. /**
  6888. * What the spool assigned to this slot is configured to use *here* -- its
  6889. * per-printer-model filament preset and the K profile for this slot's hotend.
  6890. * Nulls when the slot holds no known spool.
  6891. */
  6892. getSlotSpoolDefaults: (printerId: number, amsId: number, trayId: number) =>
  6893. request<SlotSpoolDefaults>(`/printers/${printerId}/slots/${amsId}/${trayId}/spool-defaults`),
  6894. getSpoolFilamentPresets: (spoolId: number) =>
  6895. request<SpoolFilamentPreset[]>(`/inventory/spools/${spoolId}/filament-presets`),
  6896. saveSpoolFilamentPresets: (spoolId: number, presets: SpoolFilamentPresetInput[]) =>
  6897. request<SpoolFilamentPreset[]>(`/inventory/spools/${spoolId}/filament-presets`, {
  6898. method: 'PUT',
  6899. body: JSON.stringify(presets),
  6900. }),
  6901. getProfileDefaults: () => request<ProfileDefault[]>('/inventory/profile-defaults'),
  6902. resolveProfileDefault: (key: ProfileDefaultKey) => {
  6903. const params = new URLSearchParams({
  6904. brand: key.brand,
  6905. material: key.material,
  6906. subtype: key.subtype,
  6907. color_name: key.color_name,
  6908. });
  6909. return request<ResolvedProfileDefault | null>(`/inventory/profile-defaults/resolve?${params}`);
  6910. },
  6911. saveProfileDefault: (data: ProfileDefaultInput) =>
  6912. request<ProfileDefault>('/inventory/profile-defaults', {
  6913. method: 'PUT',
  6914. body: JSON.stringify(data),
  6915. }),
  6916. deleteProfileDefault: (defaultId: number) =>
  6917. request<{ status: string }>(`/inventory/profile-defaults/${defaultId}`, { method: 'DELETE' }),
  6918. /** Fills in what active spools of the default's product lack; the inventory mode picks the route. */
  6919. applyProfileDefault: (defaultId: number, spoolmanMode: boolean) =>
  6920. request<{ updated: number }>(
  6921. spoolmanMode
  6922. ? `/spoolman/inventory/profile-defaults/${defaultId}/apply`
  6923. : `/inventory/profile-defaults/${defaultId}/apply`,
  6924. { method: 'POST' },
  6925. ),
  6926. getAssignments: (printerId?: number) =>
  6927. request<SpoolAssignment[]>(`/inventory/assignments${printerId ? `?printer_id=${printerId}` : ''}`),
  6928. // move: the spool also leaves any other slot it is in, in the same
  6929. // transaction (#1574) -- for a scanned spool, the one in the user's hand.
  6930. assignSpool: (data: { spool_id: number; printer_id: number; ams_id: number; tray_id: number; move?: boolean }) =>
  6931. request<SpoolAssignment>('/inventory/assignments', {
  6932. method: 'POST',
  6933. body: JSON.stringify(data),
  6934. }),
  6935. unassignSpool: (printerId: number, amsId: number, trayId: number) =>
  6936. request<{ status: string }>(`/inventory/assignments/${printerId}/${amsId}/${trayId}`, { method: 'DELETE' }),
  6937. // ── Spool label printing (#809) ──────────────────────────────────────────
  6938. // The print endpoints return a PDF, a PNG, or a ZIP of PNGs (#2981); the
  6939. // preview endpoints one PNG. Callers get the Blob and decide what to do.
  6940. printSpoolLabels: (data: PrintSpoolLabelsRequest): Promise<Blob> =>
  6941. postForBlob('/inventory/labels', data),
  6942. printSpoolmanSpoolLabels: (data: PrintSpoolLabelsRequest): Promise<Blob> =>
  6943. postForBlob('/spoolman/labels', data),
  6944. previewSpoolLabel: (data: PreviewSpoolLabelRequest, signal?: AbortSignal): Promise<Blob> =>
  6945. postForBlob('/inventory/labels/preview', data, signal),
  6946. previewSpoolmanSpoolLabel: (data: PreviewSpoolLabelRequest, signal?: AbortSignal): Promise<Blob> =>
  6947. postForBlob('/spoolman/labels/preview', data, signal),
  6948. getLabelTemplates: () => request<SavedLabelTemplate[]>('/label-templates'),
  6949. createLabelTemplate: (data: { name: string; layout: LabelSheetLayout }) =>
  6950. request<SavedLabelTemplate>('/label-templates', { method: 'POST', body: JSON.stringify(data) }),
  6951. updateLabelTemplate: (id: number, data: { name: string; layout: LabelSheetLayout }) =>
  6952. request<SavedLabelTemplate>(`/label-templates/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  6953. deleteLabelTemplate: (id: number) => request<void>(`/label-templates/${id}`, { method: 'DELETE' }),
  6954. getSpoolCatalog: () =>
  6955. request<SpoolCatalogEntry[]>('/inventory/catalog'),
  6956. addCatalogEntry: (data: { name: string; weight: number }) =>
  6957. request<SpoolCatalogEntry>('/inventory/catalog', { method: 'POST', body: JSON.stringify(data) }),
  6958. updateCatalogEntry: (id: number, data: { name: string; weight: number }) =>
  6959. request<SpoolCatalogEntry>(`/inventory/catalog/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  6960. deleteCatalogEntry: (id: number) =>
  6961. request<{ status: string }>(`/inventory/catalog/${id}`, { method: 'DELETE' }),
  6962. bulkDeleteCatalogEntries: (ids: number[]) =>
  6963. request<{ deleted: number }>('/inventory/catalog/bulk-delete', { method: 'POST', body: JSON.stringify({ ids }) }),
  6964. resetSpoolCatalog: () =>
  6965. request<{ status: string }>('/inventory/catalog/reset', { method: 'POST' }),
  6966. // ── Suppliers (#2988) — inventory master data, Locations pattern ─────────
  6967. getSuppliers: () =>
  6968. request<Supplier[]>('/inventory/suppliers'),
  6969. createSupplier: (data: SupplierInput) =>
  6970. request<Supplier>('/inventory/suppliers', { method: 'POST', body: JSON.stringify(data) }),
  6971. updateSupplier: (id: number, data: Partial<SupplierInput>) =>
  6972. request<Supplier>(`/inventory/suppliers/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  6973. deleteSupplier: (id: number) =>
  6974. request<{ status: string }>(`/inventory/suppliers/${id}`, { method: 'DELETE' }),
  6975. setSpoolSuppliers: (spoolId: number, links: SpoolSupplierLinkInput[]) =>
  6976. request<SpoolSupplierLink[]>(`/inventory/spools/${spoolId}/suppliers`, {
  6977. method: 'PUT',
  6978. body: JSON.stringify(links),
  6979. }),
  6980. // Spoolman parity: the assignment rows live Bambuddy-side, keyed by the
  6981. // remote spool id — same request/response shape as the built-in inventory.
  6982. setSpoolmanSpoolSuppliers: (spoolmanSpoolId: number, links: SpoolSupplierLinkInput[]) =>
  6983. request<SpoolSupplierLink[]>(`/spoolman/inventory/spools/${spoolmanSpoolId}/suppliers`, {
  6984. method: 'PUT',
  6985. body: JSON.stringify(links),
  6986. }),
  6987. // date_from/date_to scope the usage half only, so the widget can follow the
  6988. // dashboard timeframe; stock stays point-in-time.
  6989. getSupplierStats: (dateFrom?: string, dateTo?: string) => {
  6990. const params = new URLSearchParams();
  6991. if (dateFrom) params.set('date_from', dateFrom);
  6992. if (dateTo) params.set('date_to', dateTo);
  6993. addDayZone(params);
  6994. const qs = params.toString();
  6995. return request<SupplierStats[]>(`/inventory/stats/suppliers${qs ? `?${qs}` : ''}`);
  6996. },
  6997. getLocations: () =>
  6998. request<StorageLocation[]>('/inventory/locations'),
  6999. createLocation: (data: { name: string; identifier?: string | null }) =>
  7000. request<StorageLocation>('/inventory/locations', { method: 'POST', body: JSON.stringify(data) }),
  7001. updateLocation: (id: number, data: { name?: string; identifier?: string | null }) =>
  7002. request<StorageLocation>(`/inventory/locations/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  7003. deleteLocation: (id: number) =>
  7004. request<{ status: string }>(`/inventory/locations/${id}`, { method: 'DELETE' }),
  7005. getColorCatalog: () =>
  7006. request<ColorCatalogEntry[]>('/inventory/colors'),
  7007. /** Flat hex→name map, plus the names collapsing it loses. ``by_material`` is
  7008. * keyed ``"<material>|<hex>"`` and only carries entries that differ from the
  7009. * flat answer (e.g. ``"pla matte|ffffff" -> "Ivory White"`` where the flat
  7010. * map says "Jade White"). #2875. */
  7011. getColorNameMap: () =>
  7012. request<{
  7013. colors: Record<string, string>;
  7014. by_material?: Record<string, string>;
  7015. bambu?: BambuCatalogColor[];
  7016. preset_materials?: Record<string, string>;
  7017. }>('/inventory/colors/map'),
  7018. addColorEntry: (data: {
  7019. manufacturer: string;
  7020. color_name: string;
  7021. hex_color: string;
  7022. material: string | null;
  7023. extra_colors?: string | null;
  7024. effect_type?: string | null;
  7025. }) =>
  7026. request<ColorCatalogEntry>('/inventory/colors', { method: 'POST', body: JSON.stringify(data) }),
  7027. updateColorEntry: (
  7028. id: number,
  7029. data: {
  7030. manufacturer: string;
  7031. color_name: string;
  7032. hex_color: string;
  7033. material: string | null;
  7034. extra_colors?: string | null;
  7035. effect_type?: string | null;
  7036. },
  7037. ) => request<ColorCatalogEntry>(`/inventory/colors/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  7038. deleteColorEntry: (id: number) =>
  7039. request<{ status: string }>(`/inventory/colors/${id}`, { method: 'DELETE' }),
  7040. bulkDeleteColorEntries: (ids: number[]) =>
  7041. request<{ deleted: number }>('/inventory/colors/bulk-delete', { method: 'POST', body: JSON.stringify({ ids }) }),
  7042. resetColorCatalog: () =>
  7043. request<{ status: string }>('/inventory/colors/reset', { method: 'POST' }),
  7044. searchColors: (manufacturer?: string, material?: string) =>
  7045. request<ColorCatalogEntry[]>(`/inventory/colors/search?${manufacturer ? `manufacturer=${encodeURIComponent(manufacturer)}` : ''}${manufacturer && material ? '&' : ''}${material ? `material=${encodeURIComponent(material)}` : ''}`),
  7046. linkTagToSpool: (spoolId: number, data: { tag_uid?: string; tray_uuid?: string; tag_type?: string; data_origin?: string }) =>
  7047. request<InventorySpool>(`/inventory/spools/${spoolId}/link-tag`, {
  7048. method: 'PATCH',
  7049. body: JSON.stringify(data),
  7050. }),
  7051. // Per-material-number inventory aggregate (#2870). The date range narrows
  7052. // the usage half only — stock is point-in-time.
  7053. getMaterialNumberStats: (options?: { dateFrom?: string; dateTo?: string }) => {
  7054. const params = new URLSearchParams();
  7055. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  7056. if (options?.dateTo) params.set('date_to', options.dateTo);
  7057. addDayZone(params);
  7058. const qs = params.toString();
  7059. return request<MaterialNumberStats[]>(`/inventory/stats/material-numbers${qs ? `?${qs}` : ''}`);
  7060. },
  7061. getSpoolUsageHistory: (spoolId: number, limit = 50) =>
  7062. request<SpoolUsageRecord[]>(`/inventory/spools/${spoolId}/usage?limit=${limit}`),
  7063. // One inventory's at a time: ``spoolman`` for the Spoolman spools' (#3407).
  7064. getAllUsageHistory: (limit = 100, printerId?: number, spoolman = false) =>
  7065. request<SpoolUsageRecord[]>(
  7066. `/inventory/usage?limit=${limit}${printerId ? `&printer_id=${printerId}` : ''}${spoolman ? '&spoolman=true' : ''}`,
  7067. ),
  7068. getSpoolmanSpoolUsageHistory: (spoolId: number, limit = 50) =>
  7069. request<SpoolUsageRecord[]>(`/spoolman/inventory/spools/${spoolId}/usage?limit=${limit}`),
  7070. clearSpoolmanSpoolUsageHistory: (spoolId: number) =>
  7071. request<{ status: string }>(`/spoolman/inventory/spools/${spoolId}/usage`, { method: 'DELETE' }),
  7072. clearSpoolUsageHistory: (spoolId: number) =>
  7073. request<{ status: string }>(`/inventory/spools/${spoolId}/usage`, { method: 'DELETE' }),
  7074. syncWeightsFromAms: () =>
  7075. request<{ synced: number; skipped: number; printing?: number }>('/inventory/sync-ams-weights', { method: 'POST' }),
  7076. getSkuSettings: () =>
  7077. request<FilamentSkuSettings[]>('/inventory/sku-settings'),
  7078. upsertSkuSettings: (data: Omit<FilamentSkuSettings, 'id'>) =>
  7079. request<FilamentSkuSettings>('/inventory/sku-settings', {
  7080. method: 'POST',
  7081. body: JSON.stringify(data),
  7082. }),
  7083. getShoppingList: () =>
  7084. request<ShoppingListItem[]>('/inventory/shopping-list'),
  7085. addToShoppingList: (data: ShoppingListItemCreate) =>
  7086. request<ShoppingListItem>('/inventory/shopping-list', {
  7087. method: 'POST',
  7088. body: JSON.stringify(data),
  7089. }),
  7090. removeFromShoppingList: (id: number) =>
  7091. request<{ status: string }>(`/inventory/shopping-list/${id}`, { method: 'DELETE' }),
  7092. clearShoppingList: () =>
  7093. request<{ deleted: number }>('/inventory/shopping-list', { method: 'DELETE' }),
  7094. updateShoppingListStatus: (id: number, status: 'pending' | 'purchased' | 'received') =>
  7095. request<ShoppingListItem>(`/inventory/shopping-list/${id}/status`, {
  7096. method: 'PATCH',
  7097. body: JSON.stringify({ status }),
  7098. }),
  7099. getFilamentPresets: () =>
  7100. request<SlicerSetting[]>('/cloud/filaments'),
  7101. // Spoolman Inventory proxy (unified UI when Spoolman is enabled)
  7102. getSpoolmanInventorySpools: (includeArchived = false) =>
  7103. request<InventorySpool[]>(`/spoolman/inventory/spools?include_archived=${includeArchived}`),
  7104. getSpoolmanInventorySpool: (id: number) =>
  7105. request<InventorySpool>(`/spoolman/inventory/spools/${id}`),
  7106. createSpoolmanInventorySpool: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>) =>
  7107. request<InventorySpool>('/spoolman/inventory/spools', {
  7108. method: 'POST',
  7109. body: JSON.stringify(data),
  7110. }),
  7111. bulkCreateSpoolmanInventorySpools: (
  7112. data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>,
  7113. quantity: number,
  7114. ) =>
  7115. request<SpoolmanBulkCreateResult | InventorySpool[]>('/spoolman/inventory/spools/bulk', {
  7116. method: 'POST',
  7117. body: JSON.stringify({ spool: data, quantity }),
  7118. }),
  7119. updateSpoolmanInventorySpool: (
  7120. id: number,
  7121. data: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>,
  7122. ) =>
  7123. request<InventorySpool>(`/spoolman/inventory/spools/${id}`, {
  7124. method: 'PATCH',
  7125. body: JSON.stringify(data),
  7126. }),
  7127. deleteSpoolmanInventorySpool: (id: number) =>
  7128. request<{ status: string }>(`/spoolman/inventory/spools/${id}`, { method: 'DELETE' }),
  7129. archiveSpoolmanInventorySpool: (id: number) =>
  7130. request<InventorySpool>(`/spoolman/inventory/spools/${id}/archive`, { method: 'POST' }),
  7131. restoreSpoolmanInventorySpool: (id: number) =>
  7132. request<InventorySpool>(`/spoolman/inventory/spools/${id}/restore`, { method: 'POST' }),
  7133. resetSpoolmanInventorySpoolConsumedCounter: (id: number) =>
  7134. request<InventorySpool>(`/spoolman/inventory/spools/${id}/reset-consumed-counter`, { method: 'POST' }),
  7135. bulkResetSpoolmanInventorySpoolConsumedCounter: (spoolIds: number[]) =>
  7136. request<{ reset: number; not_found?: number[]; errors?: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/reset-consumed-counter-bulk`, {
  7137. method: 'POST',
  7138. body: JSON.stringify({ spool_ids: spoolIds }),
  7139. }),
  7140. bulkUpdateSpoolmanInventorySpools: (ids: number[], update: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  7141. request<{ updated: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-update`, {
  7142. method: 'POST',
  7143. body: JSON.stringify({ ids, update }),
  7144. }),
  7145. bulkDeleteSpoolmanInventorySpools: (ids: number[]) =>
  7146. request<{ deleted: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-delete`, {
  7147. method: 'POST',
  7148. body: JSON.stringify({ ids }),
  7149. }),
  7150. bulkArchiveSpoolmanInventorySpools: (ids: number[]) =>
  7151. request<{ archived: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-archive`, {
  7152. method: 'POST',
  7153. body: JSON.stringify({ ids }),
  7154. }),
  7155. bulkRestoreSpoolmanInventorySpools: (ids: number[]) =>
  7156. request<{ restored: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-restore`, {
  7157. method: 'POST',
  7158. body: JSON.stringify({ ids }),
  7159. }),
  7160. linkTagToSpoolmanSpool: (spoolId: number, data: { tag_uid?: string; tray_uuid?: string }) =>
  7161. request<InventorySpool>(`/spoolman/inventory/spools/${spoolId}/tag`, {
  7162. method: 'PATCH',
  7163. body: JSON.stringify(data),
  7164. }),
  7165. syncSpoolmanSpoolWeight: (spoolId: number, weightGrams: number) =>
  7166. request<{ status: string; weight_used: number }>(`/spoolman/inventory/spools/${spoolId}/weight`, {
  7167. method: 'PATCH',
  7168. body: JSON.stringify({ weight_grams: weightGrams }),
  7169. }),
  7170. // move: as assignSpool's (#1574).
  7171. assignSpoolmanSlot: (data: { spoolman_spool_id: number; printer_id: number; ams_id: number; tray_id: number; move?: boolean }) =>
  7172. request<InventorySpool>('/spoolman/inventory/slot-assignments', {
  7173. method: 'POST',
  7174. body: JSON.stringify(data),
  7175. }),
  7176. unassignSpoolmanSlot: (spoolmanSpoolId: number) =>
  7177. request<InventorySpool>(`/spoolman/inventory/slot-assignments/${spoolmanSpoolId}`, { method: 'DELETE' }),
  7178. getSpoolmanSlotAssignments: (printerId?: number) =>
  7179. request<Array<{
  7180. printer_id: number;
  7181. printer_name: string | null;
  7182. ams_id: number;
  7183. tray_id: number;
  7184. spoolman_spool_id: number;
  7185. ams_label: string | null;
  7186. printer_model?: string | null;
  7187. }>>(
  7188. printerId !== undefined
  7189. ? `/spoolman/inventory/slot-assignments/all?printer_id=${printerId}`
  7190. : '/spoolman/inventory/slot-assignments/all',
  7191. ),
  7192. syncSpoolmanAmsWeights: () =>
  7193. request<{ synced: number; skipped: number; printing?: number }>('/spoolman/inventory/sync-ams-weights', { method: 'POST' }),
  7194. saveSpoolmanKProfiles: (spoolId: number, profiles: SpoolKProfileInput[]) =>
  7195. request<SpoolKProfile[]>(`/spoolman/inventory/spools/${spoolId}/k-profiles`, {
  7196. method: 'PUT',
  7197. body: JSON.stringify(profiles),
  7198. }),
  7199. getSpoolmanFilamentPresets: (spoolId: number) =>
  7200. request<SpoolFilamentPreset[]>(`/spoolman/inventory/spools/${spoolId}/filament-presets`),
  7201. saveSpoolmanFilamentPresets: (spoolId: number, presets: SpoolFilamentPresetInput[]) =>
  7202. request<SpoolFilamentPreset[]>(`/spoolman/inventory/spools/${spoolId}/filament-presets`, {
  7203. method: 'PUT',
  7204. body: JSON.stringify(presets),
  7205. }),
  7206. // Updates
  7207. getVersion: () => request<VersionInfo>('/updates/version'),
  7208. checkForUpdates: () => request<UpdateCheckResult>('/updates/check'),
  7209. applyUpdate: () =>
  7210. request<{ success: boolean; message: string; status?: UpdateStatus; is_docker?: boolean; is_ha_addon?: boolean; is_windows_installer?: boolean }>('/updates/apply', {
  7211. method: 'POST',
  7212. }),
  7213. getUpdateStatus: () => request<UpdateStatus>('/updates/status'),
  7214. // Maintenance
  7215. getMaintenanceTypes: () => request<MaintenanceType[]>('/maintenance/types'),
  7216. createMaintenanceType: (data: MaintenanceTypeCreate) =>
  7217. request<MaintenanceType>('/maintenance/types', {
  7218. method: 'POST',
  7219. body: JSON.stringify(data),
  7220. }),
  7221. updateMaintenanceType: (id: number, data: Partial<MaintenanceTypeCreate>) =>
  7222. request<MaintenanceType>(`/maintenance/types/${id}`, {
  7223. method: 'PATCH',
  7224. body: JSON.stringify(data),
  7225. }),
  7226. deleteMaintenanceType: (id: number) =>
  7227. request<{ status: string }>(`/maintenance/types/${id}`, { method: 'DELETE' }),
  7228. restoreDefaultMaintenanceTypes: () =>
  7229. request<{ restored: number }>(`/maintenance/types/restore-defaults`, { method: 'POST' }),
  7230. getMaintenanceOverview: () => request<PrinterMaintenanceOverview[]>('/maintenance/overview'),
  7231. updateMaintenanceItem: (itemId: number, data: { custom_interval_hours?: number | null; custom_interval_type?: 'hours' | 'days' | null; enabled?: boolean }) =>
  7232. request<MaintenanceStatus>(`/maintenance/items/${itemId}`, {
  7233. method: 'PATCH',
  7234. body: JSON.stringify(data),
  7235. }),
  7236. performMaintenance: (itemId: number, notes?: string) =>
  7237. request<MaintenanceStatus>(`/maintenance/items/${itemId}/perform`, {
  7238. method: 'POST',
  7239. body: JSON.stringify({ notes }),
  7240. }),
  7241. setPrinterHours: (printerId: number, totalHours: number) =>
  7242. request<{ printer_id: number; total_hours: number; archive_hours: number; offset_hours: number }>(
  7243. `/maintenance/printers/${printerId}/hours?total_hours=${totalHours}`,
  7244. { method: 'PATCH' }
  7245. ),
  7246. assignMaintenanceType: (printerId: number, typeId: number) =>
  7247. request<MaintenanceStatus>(`/maintenance/printers/${printerId}/assign/${typeId}`, {
  7248. method: 'POST',
  7249. }),
  7250. removeMaintenanceItem: (itemId: number) =>
  7251. request<{ status: string }>(`/maintenance/items/${itemId}`, {
  7252. method: 'DELETE',
  7253. }),
  7254. // Camera
  7255. getCameraStreamToken: () =>
  7256. request<{ token: string }>('/printers/camera/stream-token', { method: 'POST' }),
  7257. // Media token (#3025) — the credential for thumbnails, plate previews,
  7258. // timelapses, cover images and link icons. Minted behind plain auth rather
  7259. // than camera:view, and identified, so those routes gate on the resource's
  7260. // own permission and ownership instead of on the camera.
  7261. getMediaToken: () => request<{ token: string }>('/auth/media-token', { method: 'POST' }),
  7262. // WebSocket auth (GHSA-r2qv follow-up) — mint a short-lived token for
  7263. // the /ws connection. Browsers can't attach Authorization headers to a
  7264. // WebSocket handshake, so the token rides in the ?token= query param.
  7265. getWebSocketToken: () =>
  7266. request<{ token: string }>('/auth/ws-token', { method: 'POST' }),
  7267. // Connected apps: sign-in to external applications with Bambuddy
  7268. listConnectedApps: () => request<ConnectedApp[]>('/connect/apps'),
  7269. createConnectedApp: (payload: { name: string; redirect_uri: string }) =>
  7270. request<ConnectedApp>('/connect/apps', { method: 'POST', body: JSON.stringify(payload) }),
  7271. updateConnectedApp: (id: number, payload: { name?: string; redirect_uri?: string; enabled?: boolean }) =>
  7272. request<ConnectedApp>(`/connect/apps/${id}`, { method: 'PATCH', body: JSON.stringify(payload) }),
  7273. rotateConnectedAppSecret: (id: number) =>
  7274. request<ConnectedApp>(`/connect/apps/${id}/rotate-secret`, { method: 'POST' }),
  7275. deleteConnectedApp: (id: number) => request<void>(`/connect/apps/${id}`, { method: 'DELETE' }),
  7276. getConnectAuthorizeInfo: (clientId: string, redirectUri: string) =>
  7277. request<ConnectAuthorizeInfo>(
  7278. `/connect/authorize/info?client_id=${encodeURIComponent(clientId)}&redirect_uri=${encodeURIComponent(redirectUri)}`,
  7279. ),
  7280. connectAuthorize: (payload: {
  7281. client_id: string;
  7282. redirect_uri: string;
  7283. code_challenge: string;
  7284. code_challenge_method: 'S256';
  7285. }) =>
  7286. request<{ code: string; redirect_uri: string }>('/connect/authorize', {
  7287. method: 'POST',
  7288. body: JSON.stringify(payload),
  7289. }),
  7290. // Long-lived camera tokens (#1108, #2531)
  7291. createLongLivedCameraToken: (payload: {
  7292. name: string;
  7293. expires_in_days: number;
  7294. scope?: LongLivedTokenScope;
  7295. }) =>
  7296. request<LongLivedCameraToken>('/auth/tokens', {
  7297. method: 'POST',
  7298. body: JSON.stringify({ scope: 'camera_stream', ...payload }),
  7299. }),
  7300. listMyLongLivedCameraTokens: () =>
  7301. request<LongLivedCameraToken[]>('/auth/tokens'),
  7302. listAllLongLivedCameraTokens: () =>
  7303. request<LongLivedCameraToken[]>('/auth/tokens/all'),
  7304. revokeLongLivedCameraToken: (tokenId: number) =>
  7305. request<void>(`/auth/tokens/${tokenId}`, { method: 'DELETE' }),
  7306. // Token-authenticated Cam Wall feed (#2531). `token` is omitted only when
  7307. // auth is disabled, where the backend gate is a no-op anyway.
  7308. getCamWallPrinters: (token?: string) =>
  7309. request<CamWallPrinter[]>(
  7310. token ? `/camwall/printers?token=${encodeURIComponent(token)}` : '/camwall/printers',
  7311. ),
  7312. // Token-authenticated streaming-overlay feed (#2613). OBS (or any embed with
  7313. // no login session) loads /overlay/{id}?token=... and this backs it. `token`
  7314. // is omitted only when auth is disabled, where the backend gate is a no-op.
  7315. getOverlayStatus: (printerId: number, token?: string) =>
  7316. request<OverlayStatus>(
  7317. token
  7318. ? `/printers/${printerId}/overlay-status?token=${encodeURIComponent(token)}`
  7319. : `/printers/${printerId}/overlay-status`,
  7320. ),
  7321. getCameraStatus: (printerId: number) =>
  7322. request<{ active: boolean; stalled: boolean }>(`/printers/${printerId}/camera/status`),
  7323. diagnoseCamera: (printerId: number) =>
  7324. request<CameraDiagnoseResult>(`/printers/${printerId}/camera/diagnose`, { method: 'POST' }),
  7325. diagnosePrinter: (printerId: number) =>
  7326. request<PrinterDiagnosticResult>(`/printers/${printerId}/diagnostic`),
  7327. diagnoseConnection: (body: {
  7328. ip_address: string;
  7329. serial_number?: string;
  7330. access_code?: string;
  7331. }) =>
  7332. request<PrinterDiagnosticResult>('/printers/diagnostic', {
  7333. method: 'POST',
  7334. body: JSON.stringify(body),
  7335. }),
  7336. // Plate Detection - Multi-reference calibration (stores up to 5 references per printer)
  7337. checkPlateEmpty: (printerId: number, options?: { useExternal?: boolean; includeDebugImage?: boolean }) => {
  7338. const params = new URLSearchParams();
  7339. // Only forward use_external when the caller explicitly sets it. Omitted →
  7340. // backend derives the default from the printer's external_camera_enabled
  7341. // setting so calibration and runtime checks use the same camera (#1359).
  7342. if (options?.useExternal !== undefined) {
  7343. params.set('use_external', String(options.useExternal));
  7344. }
  7345. params.set('include_debug_image', String(options?.includeDebugImage ?? false));
  7346. return request<PlateDetectionResult>(
  7347. `/printers/${printerId}/camera/check-plate?${params.toString()}`
  7348. );
  7349. },
  7350. calibratePlateDetection: (printerId: number, options?: { label?: string; useExternal?: boolean }) => {
  7351. const params = new URLSearchParams();
  7352. if (options?.label) params.set('label', options.label);
  7353. if (options?.useExternal !== undefined) {
  7354. params.set('use_external', String(options.useExternal));
  7355. }
  7356. return request<CalibrationResult & { index: number }>(
  7357. `/printers/${printerId}/camera/plate-detection/calibrate?${params.toString()}`,
  7358. { method: 'POST' }
  7359. );
  7360. },
  7361. getPlateReferences: (printerId: number) => {
  7362. return request<{
  7363. references: PlateReference[];
  7364. max_references: number;
  7365. }>(`/printers/${printerId}/camera/plate-detection/references`);
  7366. },
  7367. getPlateReferenceThumbnailUrl: (printerId: number, index: number) =>
  7368. withStreamToken(`${API_BASE}/printers/${printerId}/camera/plate-detection/references/${index}/thumbnail`),
  7369. updatePlateReferenceLabel: (printerId: number, index: number, label: string) => {
  7370. const params = new URLSearchParams();
  7371. params.set('label', label);
  7372. return request<{ success: boolean; index: number; label: string }>(
  7373. `/printers/${printerId}/camera/plate-detection/references/${index}?${params.toString()}`,
  7374. { method: 'PUT' }
  7375. );
  7376. },
  7377. deletePlateReference: (printerId: number, index: number) => {
  7378. return request<{ success: boolean; message: string }>(
  7379. `/printers/${printerId}/camera/plate-detection/references/${index}`,
  7380. { method: 'DELETE' }
  7381. );
  7382. },
  7383. // External Links
  7384. getExternalLinks: () => request<ExternalLink[]>('/external-links/'),
  7385. getExternalLink: (id: number) => request<ExternalLink>(`/external-links/${id}`),
  7386. createExternalLink: (data: ExternalLinkCreate) =>
  7387. request<ExternalLink>('/external-links/', {
  7388. method: 'POST',
  7389. body: JSON.stringify(data),
  7390. }),
  7391. updateExternalLink: (id: number, data: ExternalLinkUpdate) =>
  7392. request<ExternalLink>(`/external-links/${id}`, {
  7393. method: 'PATCH',
  7394. body: JSON.stringify(data),
  7395. }),
  7396. deleteExternalLink: (id: number) =>
  7397. request<{ message: string }>(`/external-links/${id}`, { method: 'DELETE' }),
  7398. uploadExternalLinkIcon: async (id: number, file: File): Promise<ExternalLink> => {
  7399. const formData = new FormData();
  7400. formData.append('file', file);
  7401. const headers: Record<string, string> = {};
  7402. if (authToken) {
  7403. headers['Authorization'] = `Bearer ${authToken}`;
  7404. }
  7405. const response = await fetch(`${API_BASE}/external-links/${id}/icon`, {
  7406. method: 'POST',
  7407. headers,
  7408. body: formData,
  7409. });
  7410. if (!response.ok) {
  7411. const error = await response.json().catch(() => ({}));
  7412. throw new Error(error.detail || `HTTP ${response.status}`);
  7413. }
  7414. return response.json();
  7415. },
  7416. deleteExternalLinkIcon: (id: number) =>
  7417. request<ExternalLink>(`/external-links/${id}/icon`, { method: 'DELETE' }),
  7418. getExternalLinkIconUrl: (id: number) => withMediaToken(`${API_BASE}/external-links/${id}/icon`),
  7419. // Projects
  7420. getProjects: (status?: string) => {
  7421. const params = new URLSearchParams();
  7422. if (status) params.set('status', status);
  7423. return request<ProjectListItem[]>(`/projects/?${params}`);
  7424. },
  7425. getProject: (id: number) => request<Project>(`/projects/${id}`),
  7426. createProject: (data: ProjectCreate) =>
  7427. request<Project>('/projects/', {
  7428. method: 'POST',
  7429. body: JSON.stringify(data),
  7430. }),
  7431. updateProject: (id: number, data: ProjectUpdate) =>
  7432. request<Project>(`/projects/${id}`, {
  7433. method: 'PATCH',
  7434. body: JSON.stringify(data),
  7435. }),
  7436. deleteProject: (id: number) =>
  7437. request<{ message: string }>(`/projects/${id}`, { method: 'DELETE' }),
  7438. getProjectArchives: (id: number, limit = 100, offset = 0) =>
  7439. request<Archive[]>(`/projects/${id}/archives?limit=${limit}&offset=${offset}`),
  7440. // Completed-run counts per library file (#1897); files with 0 runs are omitted
  7441. getProjectFileProgress: (id: number) =>
  7442. request<ProjectFileProgress[]>(`/projects/${id}/file-progress`),
  7443. addArchivesToProject: (projectId: number, archiveIds: number[]) =>
  7444. request<{ message: string; count: number }>(`/projects/${projectId}/add-archives`, {
  7445. method: 'POST',
  7446. body: JSON.stringify({ archive_ids: archiveIds }),
  7447. }),
  7448. // #1155: Cover image
  7449. // Browsers can't attach `Authorization: Bearer ...` to `<img src>`, so we
  7450. // append the stream-token query string the same way archive thumbnails do.
  7451. // `version` cache-busts the browser copy after a re-upload. It has to go on
  7452. // before the token does: callers used to append their own `?v=` to the
  7453. // returned URL, which already ended in `?token=…`, so the second `?` landed
  7454. // inside the token value and the image 401'd whenever auth was enabled.
  7455. getProjectCoverImageUrl: (projectId: number, version?: string | number) =>
  7456. withMediaToken(
  7457. `${API_BASE}/projects/${projectId}/cover-image${
  7458. version === undefined ? '' : `?v=${encodeURIComponent(String(version))}`
  7459. }`
  7460. ),
  7461. uploadProjectCoverImage: async (
  7462. projectId: number,
  7463. file: File
  7464. ): Promise<{ status: string; filename: string; size: number }> => {
  7465. const formData = new FormData();
  7466. formData.append('file', file);
  7467. const headers: Record<string, string> = {};
  7468. if (authToken) {
  7469. headers['Authorization'] = `Bearer ${authToken}`;
  7470. }
  7471. const response = await fetch(`${API_BASE}/projects/${projectId}/cover-image`, {
  7472. method: 'POST',
  7473. headers,
  7474. body: formData,
  7475. });
  7476. if (!response.ok) {
  7477. const error = await response.json().catch(() => ({}));
  7478. throw new Error(error.detail || `HTTP ${response.status}`);
  7479. }
  7480. return response.json();
  7481. },
  7482. deleteProjectCoverImage: (projectId: number) =>
  7483. request<{ status: string }>(`/projects/${projectId}/cover-image`, { method: 'DELETE' }),
  7484. // BOM (Bill of Materials)
  7485. getProjectBOM: (projectId: number) =>
  7486. request<BOMItem[]>(`/projects/${projectId}/bom`),
  7487. createBOMItem: (projectId: number, data: BOMItemCreate) =>
  7488. request<BOMItem>(`/projects/${projectId}/bom`, {
  7489. method: 'POST',
  7490. body: JSON.stringify(data),
  7491. }),
  7492. updateBOMItem: (projectId: number, itemId: number, data: BOMItemUpdate) =>
  7493. request<BOMItem>(`/projects/${projectId}/bom/${itemId}`, {
  7494. method: 'PATCH',
  7495. body: JSON.stringify(data),
  7496. }),
  7497. deleteBOMItem: (projectId: number, itemId: number) =>
  7498. request<{ status: string; message: string }>(`/projects/${projectId}/bom/${itemId}`, {
  7499. method: 'DELETE',
  7500. }),
  7501. // Templates
  7502. getTemplates: () => request<ProjectListItem[]>('/projects/templates/'),
  7503. createTemplateFromProject: (projectId: number) =>
  7504. request<Project>(`/projects/${projectId}/create-template`, { method: 'POST' }),
  7505. createProjectFromTemplate: (templateId: number, name?: string) =>
  7506. request<Project>(`/projects/from-template/${templateId}${name ? `?name=${encodeURIComponent(name)}` : ''}`, {
  7507. method: 'POST',
  7508. }),
  7509. // Timeline
  7510. getProjectTimeline: (projectId: number, limit = 50) =>
  7511. request<TimelineEvent[]>(`/projects/${projectId}/timeline?limit=${limit}`),
  7512. // Project Export/Import
  7513. exportProjectJson: (projectId: number) =>
  7514. request<ProjectExport>(`/projects/${projectId}/export?format=json`),
  7515. importProject: (data: ProjectImport) =>
  7516. request<Project>('/projects/import', {
  7517. method: 'POST',
  7518. body: JSON.stringify(data),
  7519. }),
  7520. importProjectFile: async (file: File): Promise<Project> => {
  7521. const formData = new FormData();
  7522. formData.append('file', file);
  7523. const headers: Record<string, string> = {};
  7524. if (authToken) {
  7525. headers['Authorization'] = `Bearer ${authToken}`;
  7526. }
  7527. const response = await fetch(`${API_BASE}/projects/import/file`, {
  7528. method: 'POST',
  7529. headers,
  7530. body: formData,
  7531. });
  7532. if (!response.ok) {
  7533. const error = await response.json().catch(() => ({}));
  7534. throw new Error(error.detail || `HTTP ${response.status}`);
  7535. }
  7536. return response.json();
  7537. },
  7538. exportProjectZip: async (projectId: number): Promise<{ blob: Blob; filename: string }> => {
  7539. const headers: Record<string, string> = {};
  7540. if (authToken) {
  7541. headers['Authorization'] = `Bearer ${authToken}`;
  7542. }
  7543. const response = await fetch(`${API_BASE}/projects/${projectId}/export`, {
  7544. headers,
  7545. });
  7546. if (!response.ok) {
  7547. const error = await response.json().catch(() => ({}));
  7548. throw new Error(error.detail || `HTTP ${response.status}`);
  7549. }
  7550. const contentDisposition = response.headers.get('Content-Disposition');
  7551. const filename = parseContentDispositionFilename(contentDisposition) || `project_${projectId}.zip`;
  7552. const blob = await response.blob();
  7553. return { blob, filename };
  7554. },
  7555. // API Keys
  7556. getAPIKeys: () => request<APIKey[]>('/api-keys/'),
  7557. createAPIKey: (data: APIKeyCreate) =>
  7558. request<APIKeyCreateResponse>('/api-keys/', {
  7559. method: 'POST',
  7560. body: JSON.stringify(data),
  7561. }),
  7562. deleteAPIKey: (id: number) =>
  7563. request<{ message: string }>(`/api-keys/${id}`, { method: 'DELETE' }),
  7564. // AMS History
  7565. getAMSHistory: (printerId: number, amsId: number, hours = 24) =>
  7566. request<AMSHistoryResponse>(`/ams-history/${printerId}/${amsId}?hours=${hours}`),
  7567. // Printer heater (nozzle / bed / chamber) sensor history
  7568. getPrinterSensorHistory: (printerId: number, hours = 24, kinds?: string[]) => {
  7569. const params = new URLSearchParams({ hours: String(hours) });
  7570. if (kinds && kinds.length > 0) params.set('kinds', kinds.join(','));
  7571. return request<PrinterSensorHistoryResponse>(`/printer-sensor-history/${printerId}?${params.toString()}`);
  7572. },
  7573. // System Info
  7574. getSystemInfo: () => request<SystemInfo>('/system/info'),
  7575. getSystemHealth: () => request<SystemHealthResult>('/system/health'),
  7576. getStorageUsage: (options?: { refresh?: boolean }) => {
  7577. const params = new URLSearchParams();
  7578. if (options?.refresh) {
  7579. params.set('refresh', 'true');
  7580. }
  7581. const query = params.toString();
  7582. return request<StorageUsageResponse>(`/system/storage-usage${query ? `?${query}` : ''}`);
  7583. },
  7584. // Library (File Manager)
  7585. getLibraryFolders: () => request<LibraryFolderTree[]>('/library/folders'),
  7586. createLibraryFolder: (data: LibraryFolderCreate) =>
  7587. request<LibraryFolder>('/library/folders', {
  7588. method: 'POST',
  7589. body: JSON.stringify(data),
  7590. }),
  7591. updateLibraryFolder: (id: number, data: LibraryFolderUpdate) =>
  7592. request<LibraryFolder>(`/library/folders/${id}`, {
  7593. method: 'PUT',
  7594. body: JSON.stringify(data),
  7595. }),
  7596. deleteLibraryFolder: (id: number) =>
  7597. request<{ status: string; message: string }>(`/library/folders/${id}`, { method: 'DELETE' }),
  7598. createExternalFolder: (data: ExternalFolderCreate) =>
  7599. request<LibraryFolder>('/library/folders/external', {
  7600. method: 'POST',
  7601. body: JSON.stringify(data),
  7602. }),
  7603. scanExternalFolder: (folderId: number) =>
  7604. request<{ status: string; added: number; removed: number }>(`/library/folders/${folderId}/scan`, {
  7605. method: 'POST',
  7606. }),
  7607. getLibraryFoldersByProject: (projectId: number) =>
  7608. request<LibraryFolder[]>(`/library/folders/by-project/${projectId}`),
  7609. getLibraryFoldersByArchive: (archiveId: number) => foldersByArchiveBatch(archiveId),
  7610. getLibraryFiles: (
  7611. folderId?: number | null,
  7612. includeRoot = true,
  7613. projectId?: number,
  7614. scope?: 'internal' | 'external',
  7615. recursive = false,
  7616. tagIds: number[] = [],
  7617. ) => {
  7618. const params = new URLSearchParams();
  7619. if (folderId !== undefined && folderId !== null) {
  7620. params.set('folder_id', String(folderId));
  7621. }
  7622. if (projectId !== undefined) {
  7623. params.set('project_id', String(projectId));
  7624. }
  7625. params.set('include_root', String(includeRoot));
  7626. if (scope === 'internal') params.set('internal_only', 'true');
  7627. else if (scope === 'external') params.set('external_only', 'true');
  7628. // recursive=true expands the folder_id filter to include every descendant
  7629. // folder (#1268). Only meaningful when folder_id is set; ignored server-side
  7630. // otherwise. Off by default so non-search callers keep folder-scoped behavior.
  7631. if (recursive) params.set('recursive', 'true');
  7632. // Tag filter (#1268). Repeated ?tag_ids=N&tag_ids=M form for AND semantics
  7633. // — backend joins the association table and HAVING COUNT(DISTINCT) matches
  7634. // the array length. Tag filter intentionally bypasses folder scoping
  7635. // server-side (cross-cutting design decision).
  7636. for (const tagId of tagIds) {
  7637. params.append('tag_ids', String(tagId));
  7638. }
  7639. return request<LibraryFileListItem[]>(`/library/files?${params}`);
  7640. },
  7641. getLibraryFolderReadme: (folderId: number) =>
  7642. request<{ filename: string; content: string; truncated: boolean }>(
  7643. `/library/folders/${folderId}/readme`,
  7644. ),
  7645. // ============ Library tag catalog (#1268) ============
  7646. getLibraryTags: () =>
  7647. request<LibraryTag[]>('/library/tags'),
  7648. createLibraryTag: (name: string) =>
  7649. request<LibraryTag>('/library/tags', {
  7650. method: 'POST',
  7651. body: JSON.stringify({ name }),
  7652. }),
  7653. updateLibraryTag: (id: number, name: string) =>
  7654. request<LibraryTag>(`/library/tags/${id}`, {
  7655. method: 'PATCH',
  7656. body: JSON.stringify({ name }),
  7657. }),
  7658. deleteLibraryTag: (id: number) =>
  7659. request<void>(`/library/tags/${id}`, { method: 'DELETE' }),
  7660. bulkAssignLibraryTags: (
  7661. fileIds: number[],
  7662. tagIds: number[],
  7663. action: 'add' | 'remove' | 'replace',
  7664. ) =>
  7665. request<LibraryTagBulkAssignResult>('/library/tags/bulk-assign', {
  7666. method: 'POST',
  7667. body: JSON.stringify({ file_ids: fileIds, tag_ids: tagIds, action }),
  7668. }),
  7669. // ============ Variant groups (#671 / #2570) ============
  7670. // "These files are the same job sliced for different printers." Consumed from
  7671. // both ends: the queue picks a printer and needs the matching file, the File
  7672. // Manager's print action has the printer and needs the same match.
  7673. createVariantGroup: (
  7674. members: { library_file_id: number; target_model?: string }[],
  7675. name?: string,
  7676. ) =>
  7677. request<VariantGroup>('/library/variant-groups', {
  7678. method: 'POST',
  7679. body: JSON.stringify({ members, ...(name ? { name } : {}) }),
  7680. }),
  7681. getVariantGroup: (groupId: number) =>
  7682. request<VariantGroup>(`/library/variant-groups/${groupId}`),
  7683. getLibraryFile: (id: number) => request<LibraryFile>(`/library/files/${id}`),
  7684. uploadLibraryFile: async (
  7685. file: File,
  7686. folderId?: number | null,
  7687. generateStlThumbnails: boolean = true
  7688. ): Promise<LibraryFileUploadResponse> => {
  7689. const formData = new FormData();
  7690. formData.append('file', file);
  7691. const params = new URLSearchParams();
  7692. if (folderId) params.set('folder_id', String(folderId));
  7693. params.set('generate_stl_thumbnails', String(generateStlThumbnails));
  7694. const headers: Record<string, string> = {};
  7695. if (authToken) {
  7696. headers['Authorization'] = `Bearer ${authToken}`;
  7697. }
  7698. const response = await fetch(`${API_BASE}/library/files?${params}`, {
  7699. method: 'POST',
  7700. headers,
  7701. body: formData,
  7702. });
  7703. if (!response.ok) {
  7704. const error = await response.json().catch(() => ({}));
  7705. throw new Error(error.detail || `HTTP ${response.status}`);
  7706. }
  7707. return response.json();
  7708. },
  7709. extractZipFile: async (
  7710. file: File,
  7711. folderId?: number | null,
  7712. preserveStructure: boolean = true,
  7713. createFolderFromZip: boolean = false,
  7714. generateStlThumbnails: boolean = true
  7715. ): Promise<ZipExtractResponse> => {
  7716. const formData = new FormData();
  7717. formData.append('file', file);
  7718. const params = new URLSearchParams();
  7719. if (folderId) params.set('folder_id', String(folderId));
  7720. params.set('preserve_structure', String(preserveStructure));
  7721. params.set('create_folder_from_zip', String(createFolderFromZip));
  7722. params.set('generate_stl_thumbnails', String(generateStlThumbnails));
  7723. const headers: Record<string, string> = {};
  7724. if (authToken) {
  7725. headers['Authorization'] = `Bearer ${authToken}`;
  7726. }
  7727. const response = await fetch(`${API_BASE}/library/files/extract-zip?${params}`, {
  7728. method: 'POST',
  7729. headers,
  7730. body: formData,
  7731. });
  7732. if (!response.ok) {
  7733. const error = await response.json().catch(() => ({}));
  7734. throw new Error(error.detail || `HTTP ${response.status}`);
  7735. }
  7736. return response.json();
  7737. },
  7738. updateLibraryFile: (id: number, data: LibraryFileUpdate) =>
  7739. request<LibraryFile>(`/library/files/${id}`, {
  7740. method: 'PUT',
  7741. body: JSON.stringify(data),
  7742. }),
  7743. deleteLibraryFile: (id: number) =>
  7744. request<{ status: string; message: string; trashed: boolean }>(`/library/files/${id}`, { method: 'DELETE' }),
  7745. // ========== Library Trash (#1008) ==========
  7746. previewLibraryPurge: (olderThanDays: number, includeNeverPrinted: boolean = true) =>
  7747. request<LibraryPurgePreview>(
  7748. `/library/purge/preview?older_than_days=${olderThanDays}&include_never_printed=${includeNeverPrinted}`,
  7749. ),
  7750. executeLibraryPurge: (olderThanDays: number, includeNeverPrinted: boolean = true) =>
  7751. request<{ moved_to_trash: number }>('/library/purge', {
  7752. method: 'POST',
  7753. body: JSON.stringify({ older_than_days: olderThanDays, include_never_printed: includeNeverPrinted }),
  7754. }),
  7755. listLibraryTrash: (limit: number = 100, offset: number = 0) =>
  7756. request<LibraryTrashListResponse>(`/library/trash?limit=${limit}&offset=${offset}`),
  7757. restoreLibraryTrash: (fileId: number) =>
  7758. request<{ status: string; id: number }>(`/library/trash/${fileId}/restore`, { method: 'POST' }),
  7759. hardDeleteLibraryTrash: (fileId: number) =>
  7760. request<{ status: string }>(`/library/trash/${fileId}`, { method: 'DELETE' }),
  7761. emptyLibraryTrash: () => request<{ deleted: number }>('/library/trash', { method: 'DELETE' }),
  7762. getLibraryTrashSettings: () =>
  7763. request<LibraryTrashSettings>('/library/trash/settings'),
  7764. updateLibraryTrashSettings: (body: LibraryTrashSettings) =>
  7765. request<LibraryTrashSettings>('/library/trash/settings', {
  7766. method: 'PUT',
  7767. body: JSON.stringify(body),
  7768. }),
  7769. getLibraryFileDownloadUrl: (id: number) => `${API_BASE}/library/files/${id}/download`,
  7770. createLibrarySlicerToken: (fileId: number) =>
  7771. request<{ token: string }>(`/library/files/${fileId}/slicer-token`, { method: 'POST' }),
  7772. getLibrarySlicerDownloadUrl: (fileId: number, token: string, filename: string) =>
  7773. `${API_BASE}/library/files/${fileId}/dl/${token}/${encodeURIComponent(buildSlicerUrlFilename(filename))}`,
  7774. downloadLibraryFile: async (id: number, filename?: string): Promise<void> => {
  7775. const headers: Record<string, string> = {};
  7776. if (authToken) {
  7777. headers['Authorization'] = `Bearer ${authToken}`;
  7778. }
  7779. const response = await fetch(`${API_BASE}/library/files/${id}/download`, { headers });
  7780. if (!response.ok) {
  7781. const error = await response.json().catch(() => ({}));
  7782. throw new Error(error.detail || `HTTP ${response.status}`);
  7783. }
  7784. const disposition = response.headers.get('Content-Disposition');
  7785. const downloadFilename = parseContentDispositionFilename(disposition) || filename || `file_${id}`;
  7786. const blob = await response.blob();
  7787. const url = window.URL.createObjectURL(blob);
  7788. const a = document.createElement('a');
  7789. a.href = url;
  7790. a.download = downloadFilename;
  7791. document.body.appendChild(a);
  7792. a.click();
  7793. document.body.removeChild(a);
  7794. window.URL.revokeObjectURL(url);
  7795. },
  7796. getLibraryFileThumbnailUrl: (id: number) => withMediaToken(`${API_BASE}/library/files/${id}/thumbnail`),
  7797. // Client-rendered preview thumbnail upload (#2976). STEP/PDF/spreadsheet
  7798. // previews render in the browser; the first render is posted back so the
  7799. // grid gets a thumbnail without a server-side renderer for those formats.
  7800. uploadLibraryPreviewThumbnail: async (fileId: number, thumbnail: Blob): Promise<{ updated: boolean }> => {
  7801. const formData = new FormData();
  7802. formData.append('thumbnail', thumbnail, 'preview.png');
  7803. const headers: Record<string, string> = {};
  7804. if (authToken) {
  7805. headers['Authorization'] = `Bearer ${authToken}`;
  7806. }
  7807. const response = await fetch(`${API_BASE}/library/files/${fileId}/preview-thumbnail`, {
  7808. method: 'POST',
  7809. headers,
  7810. body: formData,
  7811. });
  7812. if (!response.ok) {
  7813. const error = await response.json().catch(() => ({}));
  7814. throw new Error(error.detail || `HTTP ${response.status}`);
  7815. }
  7816. return response.json();
  7817. },
  7818. getLibraryFilePlateThumbnail: (id: number, plateIndex: number) =>
  7819. withMediaToken(`${API_BASE}/library/files/${id}/plate-thumbnail/${plateIndex}`),
  7820. // Photos of the printed result (#3077) — same shape as the archive photo API.
  7821. getLibraryFilePhotoUrl: (fileId: number, filename: string) =>
  7822. withMediaToken(`${API_BASE}/library/files/${fileId}/photos/${encodeURIComponent(filename)}`),
  7823. uploadLibraryFilePhoto: async (fileId: number, file: File): Promise<{ status: string; filename: string; photos: string[] }> => {
  7824. const formData = new FormData();
  7825. formData.append('file', file);
  7826. const headers: Record<string, string> = {};
  7827. if (authToken) {
  7828. headers['Authorization'] = `Bearer ${authToken}`;
  7829. }
  7830. const response = await fetch(`${API_BASE}/library/files/${fileId}/photos`, {
  7831. method: 'POST',
  7832. headers,
  7833. body: formData,
  7834. });
  7835. if (!response.ok) {
  7836. const error = await response.json().catch(() => ({}));
  7837. throw new Error(error.detail || `HTTP ${response.status}`);
  7838. }
  7839. return response.json();
  7840. },
  7841. deleteLibraryFilePhoto: (fileId: number, filename: string) =>
  7842. request<{ status: string; photos: string[] }>(`/library/files/${fileId}/photos/${encodeURIComponent(filename)}`, {
  7843. method: 'DELETE',
  7844. }),
  7845. getLibraryFileGcodeUrl: (id: number) => `${API_BASE}/library/files/${id}/gcode`,
  7846. moveLibraryFiles: (fileIds: number[], folderId: number | null) =>
  7847. request<{ status: string; moved: number }>('/library/files/move', {
  7848. method: 'POST',
  7849. body: JSON.stringify({ file_ids: fileIds, folder_id: folderId }),
  7850. }),
  7851. bulkDeleteLibrary: (fileIds: number[], folderIds: number[]) =>
  7852. request<{ deleted_files: number; deleted_folders: number }>('/library/bulk-delete', {
  7853. method: 'POST',
  7854. body: JSON.stringify({ file_ids: fileIds, folder_ids: folderIds }),
  7855. }),
  7856. getLibraryStats: () => request<LibraryStats>('/library/stats'),
  7857. batchGenerateStlThumbnails: (options: {
  7858. file_ids?: number[];
  7859. folder_id?: number;
  7860. all_missing?: boolean;
  7861. }) =>
  7862. request<BatchThumbnailResponse>('/library/generate-stl-thumbnails', {
  7863. method: 'POST',
  7864. body: JSON.stringify(options),
  7865. }),
  7866. combineLibraryFiles: (items: { file_id: number; copies: number }[], filename: string, folderId: number | null) =>
  7867. request<LibraryFileUploadResponse>('/library/files/combine', {
  7868. method: 'POST',
  7869. body: JSON.stringify({ items, filename, folder_id: folderId }),
  7870. }),
  7871. getLibraryFilePlates: (fileId: number) =>
  7872. request<LibraryFilePlatesResponse>(`/library/files/${fileId}/plates`),
  7873. getLibraryFileFilamentRequirements: (
  7874. fileId: number,
  7875. plateId?: number,
  7876. requestId?: string,
  7877. /** Ask for one entry per project slot instead of only the slots this
  7878. * plate consumes. The slice modal needs it: its filament list is
  7879. * positional, so a source whose only used slot is 4 must still present
  7880. * four rows or the user's pick is bound to slot 1 (#2712). Print-time
  7881. * AMS matching must NOT set this — it wants the used-only list. */
  7882. fullSlots?: boolean,
  7883. ) => {
  7884. const qs = new URLSearchParams();
  7885. if (plateId !== undefined) qs.set('plate_id', String(plateId));
  7886. if (requestId) qs.set('request_id', requestId);
  7887. if (fullSlots) qs.set('full_slots', 'true');
  7888. return request<{
  7889. file_id: number;
  7890. filename: string;
  7891. filaments: Array<{
  7892. slot_id: number;
  7893. type: string;
  7894. color: string;
  7895. used_grams: number;
  7896. used_meters: number;
  7897. used_in_plate?: boolean;
  7898. }>;
  7899. }>(`/library/files/${fileId}/filament-requirements${qs.toString() ? `?${qs}` : ''}`);
  7900. },
  7901. /** Poll the sidecar's per-request progress snapshot via the Bambuddy
  7902. * proxy. Used by the SliceModal's filament-discovery path so the inline
  7903. * spinner + persistent toast can show "Generating G-code (45%)" while
  7904. * the preview slice runs. Returns null on 404 (sidecar doesn't yet
  7905. * have an entry — early race window — or it expired) so the poller
  7906. * can keep trying. */
  7907. getPreviewSliceProgress: async (requestId: string): Promise<SliceJobProgress | null> => {
  7908. try {
  7909. return await request<SliceJobProgress>(`/slicer/preview-progress/${encodeURIComponent(requestId)}`);
  7910. } catch {
  7911. return null;
  7912. }
  7913. },
  7914. // GitHub Backup
  7915. getGitHubBackupConfig: () =>
  7916. request<GitHubBackupConfig | null>('/github-backup/config'),
  7917. getGitHubBackupCloudAccounts: () =>
  7918. request<CloudAccountCounts>('/github-backup/cloud-accounts'),
  7919. saveGitHubBackupConfig: (config: GitHubBackupConfigCreate) =>
  7920. request<GitHubBackupConfig>('/github-backup/config', {
  7921. method: 'POST',
  7922. body: JSON.stringify(config),
  7923. }),
  7924. updateGitHubBackupConfig: (config: Partial<GitHubBackupConfigCreate>) =>
  7925. request<GitHubBackupConfig>('/github-backup/config', {
  7926. method: 'PATCH',
  7927. body: JSON.stringify(config),
  7928. }),
  7929. testGitHubConnection: (repoUrl: string, token: string, provider: GitProviderType = 'github') =>
  7930. request<GitHubTestConnectionResponse>('/github-backup/test', {
  7931. method: 'POST',
  7932. body: JSON.stringify({ repo_url: repoUrl, token, provider }),
  7933. }),
  7934. testGitHubStoredConnection: () =>
  7935. request<GitHubTestConnectionResponse>('/github-backup/test-stored', { method: 'POST' }),
  7936. triggerGitHubBackup: () =>
  7937. request<GitHubBackupTriggerResponse>('/github-backup/run', { method: 'POST' }),
  7938. getGitHubBackupStatus: () =>
  7939. request<GitHubBackupStatus>('/github-backup/status'),
  7940. getGitHubBackupLogs: (limit: number = 50) =>
  7941. request<GitHubBackupLog[]>(`/github-backup/logs?limit=${limit}`),
  7942. clearGitHubBackupLogs: (keepLast: number = 10) =>
  7943. request<{ deleted: number; message: string }>(`/github-backup/logs?keep_last=${keepLast}`, { method: 'DELETE' }),
  7944. // Restore from a Git backup (#2656)
  7945. getGitHubBackupCommits: (limit: number = 20) =>
  7946. request<GitHubCommitListResponse>(`/github-backup/commits?limit=${limit}`),
  7947. getGitHubRestorePreview: (ref: string = 'HEAD') =>
  7948. request<GitHubRestorePreview>(`/github-backup/restore/preview?ref=${encodeURIComponent(ref)}`),
  7949. restoreFromGitHub: (payload: GitHubRestoreRequest) =>
  7950. request<GitHubRestoreResponse>('/github-backup/restore', {
  7951. method: 'POST',
  7952. body: JSON.stringify(payload),
  7953. }),
  7954. // Scheduled local backups
  7955. getLocalBackupStatus: () =>
  7956. request<LocalBackupStatus>('/local-backup/status'),
  7957. triggerLocalBackup: () =>
  7958. request<{ success: boolean; message: string; filename?: string }>('/local-backup/run', { method: 'POST' }),
  7959. checkLocalBackupPath: () =>
  7960. request<LocalBackupPathCheck>('/local-backup/path-check'),
  7961. getLocalBackups: () =>
  7962. request<LocalBackupFile[]>('/local-backup/backups'),
  7963. downloadLocalBackup: async (filename: string): Promise<{ blob: Blob; filename: string }> => {
  7964. const response = await fetch(`${API_BASE}/local-backup/backups/${encodeURIComponent(filename)}/download`, {
  7965. headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {},
  7966. });
  7967. if (!response.ok) throw new Error('Download failed');
  7968. const blob = await response.blob();
  7969. return { blob, filename };
  7970. },
  7971. restoreLocalBackup: (filename: string) =>
  7972. request<{ success: boolean; message: string }>(`/local-backup/backups/${encodeURIComponent(filename)}/restore`, { method: 'POST' }),
  7973. deleteLocalBackup: (filename: string) =>
  7974. request<{ success: boolean; message: string }>(`/local-backup/backups/${encodeURIComponent(filename)}`, { method: 'DELETE' }),
  7975. // Obico AI failure detection
  7976. getObicoStatus: () =>
  7977. request<ObicoStatus>('/obico/status'),
  7978. getObicoPrinterStatus: () =>
  7979. request<ObicoPrinterStatus>('/obico/printer-status'),
  7980. // `token` is sent as-is, so an empty string tests with no token at all.
  7981. // Omitting the argument makes the backend fall back to the saved token.
  7982. testObicoConnection: (url: string, token?: string) =>
  7983. request<ObicoTestConnection>('/obico/test-connection', {
  7984. method: 'POST',
  7985. body: JSON.stringify(token === undefined ? { url } : { url, token }),
  7986. }),
  7987. // OctoEverywhere AI failure detection
  7988. getOctoEverywhereStatus: () =>
  7989. request<OctoEverywhereStatus>('/octoeverywhere/status'),
  7990. getOctoEverywherePrinterStatus: () =>
  7991. request<OctoEverywherePrinterStatus>('/octoeverywhere/printer-status'),
  7992. // An omitted key uses the saved key; an explicit empty key is rejected.
  7993. testOctoEverywhereConnection: (apiKey?: string, confidence?: OctoEverywhereConfidence) =>
  7994. request<OctoEverywhereTestConnection>('/octoeverywhere/test-connection', {
  7995. method: 'POST',
  7996. body: JSON.stringify({ api_key: apiKey, confidence }),
  7997. }),
  7998. // Slicer API — slice in the background. Both endpoints return 202 + a
  7999. // job_id; poll /slice-jobs/{id} until status is `completed` or `failed`.
  8000. sliceLibraryFile: (fileId: number, body: SliceRequest) =>
  8001. request<SliceJobEnqueueResponse>(`/library/files/${fileId}/slice`, {
  8002. method: 'POST',
  8003. body: JSON.stringify(body),
  8004. }),
  8005. sliceArchive: (archiveId: number, body: SliceRequest) =>
  8006. request<SliceJobEnqueueResponse>(`/archives/${archiveId}/slice`, {
  8007. method: 'POST',
  8008. body: JSON.stringify(body),
  8009. }),
  8010. getSliceJob: (jobId: number) =>
  8011. request<SliceJobState>(`/slice-jobs/${jobId}`),
  8012. // Unified slicer-preset listing — cloud + local + standard, deduped by name.
  8013. // Used by the SliceModal; see UnifiedPresetsResponse for the shape and
  8014. // backend/app/api/routes/slicer_presets.py for the priority rules.
  8015. // `refresh` bypasses the in-process cloud and bundled-preset caches on the
  8016. // backend; the SliceModal's Refresh button passes true so a preset deleted
  8017. // in Bambu Studio or Bambu Handy shows up without the 5-min TTL wait.
  8018. getSlicerPresets: (options?: { refresh?: boolean }) =>
  8019. request<UnifiedPresetsResponse>(
  8020. options?.refresh ? '/slicer/presets?refresh=true' : '/slicer/presets',
  8021. ),
  8022. // Slicer Pipelines (#1425) — preset bundles the SliceModal can apply in
  8023. // one click. CRUD is gated on PIPELINES_READ / PIPELINES_WRITE.
  8024. listSlicerPipelines: () =>
  8025. request<SlicerPipelinesListResponse>('/slicer-pipelines/'),
  8026. createSlicerPipeline: (data: SlicerPipelineCreateRequest) =>
  8027. request<SlicerPipeline>('/slicer-pipelines/', {
  8028. method: 'POST',
  8029. body: JSON.stringify(data),
  8030. }),
  8031. updateSlicerPipeline: (id: number, data: SlicerPipelineUpdateRequest) =>
  8032. request<SlicerPipeline>(`/slicer-pipelines/${id}`, {
  8033. method: 'PUT',
  8034. body: JSON.stringify(data),
  8035. }),
  8036. deleteSlicerPipeline: (id: number) =>
  8037. request<void>(`/slicer-pipelines/${id}`, { method: 'DELETE' }),
  8038. checkPipelineEligibility: (
  8039. pipelineId: number,
  8040. source: { kind: 'libraryFile'; id: number } | { kind: 'archive'; id: number },
  8041. ) =>
  8042. request<PipelineEligibilityReport>(`/slicer-pipelines/${pipelineId}/check-eligibility`, {
  8043. method: 'POST',
  8044. body: JSON.stringify(
  8045. source.kind === 'libraryFile'
  8046. ? { source_library_file_id: source.id }
  8047. : { source_archive_id: source.id },
  8048. ),
  8049. }),
  8050. runPipeline: (
  8051. pipelineId: number,
  8052. source: { kind: 'libraryFile'; id: number } | { kind: 'archive'; id: number },
  8053. force = false,
  8054. copies = 1,
  8055. ) =>
  8056. request<PipelineRun>(`/slicer-pipelines/${pipelineId}/run`, {
  8057. method: 'POST',
  8058. body: JSON.stringify({
  8059. ...(source.kind === 'libraryFile'
  8060. ? { source_library_file_id: source.id }
  8061. : { source_archive_id: source.id }),
  8062. force,
  8063. copies,
  8064. }),
  8065. }),
  8066. listPipelineRuns: (pipelineId: number, limit = 5) =>
  8067. request<PipelineRunListResponse>(
  8068. `/slicer-pipelines/${pipelineId}/runs?limit=${limit}`,
  8069. ),
  8070. // Dashboard list across all pipelines (#1425 PR C).
  8071. listAllPipelineRuns: (params: {
  8072. limit?: number;
  8073. offset?: number;
  8074. pipelineId?: number;
  8075. status?: string;
  8076. targetPrinterId?: number;
  8077. targetModelClass?: string;
  8078. } = {}) => {
  8079. const search = new URLSearchParams();
  8080. if (params.limit) search.set('limit', String(params.limit));
  8081. if (params.offset) search.set('offset', String(params.offset));
  8082. if (params.pipelineId) search.set('pipeline_id', String(params.pipelineId));
  8083. if (params.status) search.set('status', params.status);
  8084. if (params.targetPrinterId) search.set('target_printer_id', String(params.targetPrinterId));
  8085. if (params.targetModelClass) search.set('target_model_class', params.targetModelClass);
  8086. const q = search.toString();
  8087. return request<PipelineRunListResponse>(
  8088. `/pipeline-runs${q ? '?' + q : ''}`,
  8089. );
  8090. },
  8091. // Clear terminal pipeline runs (#1425 PR C polish). Deletes all runs in
  8092. // a terminal state (completed/failed/cancelled/partial_failure); in-flight
  8093. // runs are preserved.
  8094. clearTerminalPipelineRuns: () =>
  8095. request<{ deleted: number }>('/pipeline-runs/clear', { method: 'POST' }),
  8096. cancelPipelineRun: (runId: number) =>
  8097. request<PipelineRun>(`/pipeline-runs/${runId}/cancel`, { method: 'POST' }),
  8098. retryFailedPipelineRun: (runId: number) =>
  8099. request<PipelineRun>(`/pipeline-runs/${runId}/retry-failed`, { method: 'POST' }),
  8100. // Canonical Bambu printer-model registry — "Bambu Lab <model>" → short code.
  8101. // Single source of truth shared with backend (PRINTER_MODEL_MAP); the
  8102. // SliceModal uses this to classify cloud / standard presets by their
  8103. // `@BBL <code>` suffix against the selected printer-preset name (#1325).
  8104. getSlicerPrinterModels: () =>
  8105. request<Record<string, string>>('/slicer/printer-models'),
  8106. getSlicerLoadedSpools: () =>
  8107. request<LoadedSpoolsResponse>('/slicer/loaded-spools'),
  8108. /**
  8109. * Effective values of a process preset, with its `inherits:` chain flattened
  8110. * by the slicer sidecar. Powers the slice modal's settings panel, which would
  8111. * otherwise show the option schema's compiled-in defaults (a preset setting a
  8112. * 0.42mm line width appears as the C++ default of 0).
  8113. *
  8114. * `resolved: false` means the values could not be obtained -- sidecar offline,
  8115. * too old for the endpoint, or slicing not configured -- and the caller should
  8116. * fall back to schema defaults rather than treat it as a failure.
  8117. */
  8118. getSlicerPresetValues: (ref: PresetRef) =>
  8119. request<SlicerPresetValues>(
  8120. `/slicer/preset-values?source=${encodeURIComponent(ref.source)}&id=${encodeURIComponent(ref.id)}`,
  8121. ),
  8122. // Local Presets (OrcaSlicer imports)
  8123. getLocalPresets: () =>
  8124. request<LocalPresetsResponse>('/local-presets/'),
  8125. importLocalPresets: (formData: FormData) =>
  8126. fetch(`${API_BASE}/local-presets/import`, {
  8127. method: 'POST',
  8128. headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {},
  8129. body: formData,
  8130. }).then(async (res) => {
  8131. if (!res.ok) {
  8132. const err = await res.json().catch(() => ({}));
  8133. throw new Error(err.detail || `HTTP ${res.status}`);
  8134. }
  8135. return res.json() as Promise<ImportResponse>;
  8136. }),
  8137. deleteLocalPreset: (id: number) =>
  8138. request<{ success: boolean }>(`/local-presets/${id}`, { method: 'DELETE' }),
  8139. };
  8140. // AMS History types
  8141. export interface AMSHistoryPoint {
  8142. recorded_at: string;
  8143. humidity: number | null;
  8144. humidity_raw: number | null;
  8145. temperature: number | null;
  8146. }
  8147. export interface AMSHistoryResponse {
  8148. printer_id: number;
  8149. ams_id: number;
  8150. data: AMSHistoryPoint[];
  8151. min_humidity: number | null;
  8152. max_humidity: number | null;
  8153. avg_humidity: number | null;
  8154. min_temperature: number | null;
  8155. max_temperature: number | null;
  8156. avg_temperature: number | null;
  8157. }
  8158. export type HeaterSensorKind = 'nozzle' | 'nozzle_2' | 'bed' | 'chamber';
  8159. export interface HeaterHistoryPoint {
  8160. recorded_at: string;
  8161. value: number | null;
  8162. target: number | null;
  8163. }
  8164. export interface HeaterSeries {
  8165. sensor_kind: HeaterSensorKind;
  8166. data: HeaterHistoryPoint[];
  8167. min_value: number | null;
  8168. max_value: number | null;
  8169. avg_value: number | null;
  8170. }
  8171. export interface PrinterSensorHistoryResponse {
  8172. printer_id: number;
  8173. series: HeaterSeries[];
  8174. }
  8175. // System Info types
  8176. export interface SystemInfo {
  8177. app: {
  8178. version: string;
  8179. base_dir: string;
  8180. archive_dir: string;
  8181. };
  8182. database: {
  8183. engine: string;
  8184. version: string;
  8185. archives: number;
  8186. archives_completed: number;
  8187. archives_failed: number;
  8188. archives_printing: number;
  8189. printers: number;
  8190. filaments: number;
  8191. projects: number;
  8192. smart_plugs: number;
  8193. total_print_time_seconds: number;
  8194. total_print_time_formatted: string;
  8195. total_filament_grams: number;
  8196. total_filament_kg: number;
  8197. };
  8198. printers: {
  8199. total: number;
  8200. connected: number;
  8201. connected_list: Array<{
  8202. id: number;
  8203. name: string;
  8204. state: string;
  8205. model: string;
  8206. }>;
  8207. };
  8208. storage: {
  8209. archive_size_bytes: number;
  8210. archive_size_formatted: string;
  8211. database_size_bytes: number;
  8212. database_size_formatted: string;
  8213. disk_total_bytes: number;
  8214. disk_total_formatted: string;
  8215. disk_used_bytes: number;
  8216. disk_used_formatted: string;
  8217. disk_free_bytes: number;
  8218. disk_free_formatted: string;
  8219. disk_percent_used: number;
  8220. };
  8221. system: {
  8222. platform: string;
  8223. platform_release: string;
  8224. platform_version: string;
  8225. architecture: string;
  8226. hostname: string;
  8227. python_version: string;
  8228. uptime_seconds: number;
  8229. uptime_formatted: string;
  8230. boot_time: string;
  8231. };
  8232. memory: {
  8233. total_bytes: number;
  8234. total_formatted: string;
  8235. available_bytes: number;
  8236. available_formatted: string;
  8237. used_bytes: number;
  8238. used_formatted: string;
  8239. percent_used: number;
  8240. };
  8241. cpu: {
  8242. count: number;
  8243. count_logical: number;
  8244. percent: number;
  8245. };
  8246. }
  8247. export interface StorageUsageCategory {
  8248. key: string;
  8249. label: string;
  8250. bytes: number;
  8251. formatted: string;
  8252. percent_of_total: number;
  8253. }
  8254. export interface StorageUsageOtherItem {
  8255. bucket: string;
  8256. label: string;
  8257. kind: 'system' | 'data';
  8258. deletable: boolean;
  8259. bytes: number;
  8260. formatted: string;
  8261. percent_of_total: number;
  8262. }
  8263. export interface StorageUsageResponse {
  8264. roots: string[];
  8265. total_bytes: number;
  8266. total_formatted: string;
  8267. categories: StorageUsageCategory[];
  8268. other_breakdown: StorageUsageOtherItem[];
  8269. scan_errors: number;
  8270. generated_at: string;
  8271. cache: {
  8272. hit: boolean;
  8273. age_seconds: number;
  8274. max_age_seconds: number;
  8275. };
  8276. }
  8277. // Library (File Manager) types
  8278. export interface LibraryFolderTree {
  8279. id: number;
  8280. name: string;
  8281. parent_id: number | null;
  8282. project_id: number | null;
  8283. archive_id: number | null;
  8284. project_name: string | null;
  8285. archive_name: string | null;
  8286. is_external: boolean;
  8287. external_path: string | null;
  8288. external_readonly: boolean;
  8289. file_count: number;
  8290. // max(folder.updated_at, max(immediate-child file.updated_at)). Used by
  8291. // the File Manager folder tree's "sort by recent activity" mode (#1770).
  8292. latest_activity_at: string | null;
  8293. // Ownership (#3201). can_* are for the current user: what the File
  8294. // Manager may offer on this folder. The backend enforces the same rules.
  8295. created_by_id: number | null;
  8296. shared: boolean;
  8297. can_write: boolean;
  8298. can_rename: boolean;
  8299. can_delete: boolean;
  8300. children: LibraryFolderTree[];
  8301. }
  8302. export interface LibraryFolder {
  8303. id: number;
  8304. name: string;
  8305. parent_id: number | null;
  8306. project_id: number | null;
  8307. archive_id: number | null;
  8308. project_name: string | null;
  8309. archive_name: string | null;
  8310. is_external: boolean;
  8311. external_path: string | null;
  8312. external_readonly: boolean;
  8313. external_show_hidden: boolean;
  8314. file_count: number;
  8315. latest_activity_at: string | null;
  8316. // Ownership (#3201). can_* are for the current user: what the File
  8317. // Manager may offer on this folder. The backend enforces the same rules.
  8318. created_by_id: number | null;
  8319. shared: boolean;
  8320. can_write: boolean;
  8321. can_rename: boolean;
  8322. can_delete: boolean;
  8323. created_at: string;
  8324. updated_at: string;
  8325. }
  8326. export interface LibraryFolderCreate {
  8327. name: string;
  8328. parent_id?: number | null;
  8329. project_id?: number | null;
  8330. archive_id?: number | null;
  8331. }
  8332. export interface ExternalFolderCreate {
  8333. name: string;
  8334. external_path: string;
  8335. readonly?: boolean;
  8336. show_hidden?: boolean;
  8337. parent_id?: number | null;
  8338. }
  8339. export interface LibraryFolderUpdate {
  8340. name?: string;
  8341. parent_id?: number | null;
  8342. project_id?: number | null; // 0 to unlink
  8343. archive_id?: number | null; // 0 to unlink
  8344. shared?: boolean; // library:update_all only (#3201)
  8345. }
  8346. export interface LibraryFileDuplicate {
  8347. id: number;
  8348. filename: string;
  8349. folder_id: number | null;
  8350. folder_name: string | null;
  8351. created_at: string;
  8352. }
  8353. export interface LibraryFile {
  8354. id: number;
  8355. folder_id: number | null;
  8356. folder_name: string | null;
  8357. project_id: number | null;
  8358. project_name: string | null;
  8359. is_external: boolean;
  8360. filename: string;
  8361. file_path: string;
  8362. file_type: string;
  8363. file_size: number;
  8364. file_hash: string | null;
  8365. thumbnail_path: string | null;
  8366. metadata: Record<string, unknown> | null;
  8367. print_count: number;
  8368. last_printed_at: string | null;
  8369. notes: string | null;
  8370. // User link + photos of the printed result (#3077); source_url is the
  8371. // read-only import provenance (MakerWorld).
  8372. external_url: string | null;
  8373. photos: string[];
  8374. source_url: string | null;
  8375. duplicates: LibraryFileDuplicate[] | null;
  8376. duplicate_count: number;
  8377. // User tracking (Issue #206)
  8378. created_by_id: number | null;
  8379. created_by_username: string | null;
  8380. created_at: string;
  8381. updated_at: string;
  8382. // Metadata fields
  8383. print_name: string | null;
  8384. print_time_seconds: number | null;
  8385. filament_used_grams: number | null;
  8386. sliced_for_model: string | null;
  8387. }
  8388. export interface LibraryTagSummary {
  8389. id: number;
  8390. name: string;
  8391. }
  8392. export interface LibraryFileListItem {
  8393. id: number;
  8394. folder_id: number | null;
  8395. is_external: boolean;
  8396. filename: string;
  8397. file_type: string;
  8398. file_size: number;
  8399. thumbnail_path: string | null;
  8400. print_count: number;
  8401. duplicate_count: number;
  8402. // User tracking (Issue #206)
  8403. created_by_id: number | null;
  8404. created_by_username: string | null;
  8405. created_at: string;
  8406. // Real on-disk modification time (#2680). Null for managed uploads; the date
  8407. // sort and "Modified" column use `fs_modified_at ?? created_at`.
  8408. fs_modified_at: string | null;
  8409. print_name: string | null;
  8410. print_time_seconds: number | null;
  8411. filament_used_grams: number | null;
  8412. sliced_for_model: string | null;
  8413. // Tags assigned to this file (#1268). The backend always emits an empty
  8414. // array when a file has no tags, but the field is typed optional so any
  8415. // legacy code path (or mock) that constructs a LibraryFileListItem without
  8416. // it doesn't crash the renderer. Read sites use `file.tags ?? []`.
  8417. tags?: LibraryTagSummary[];
  8418. // Variant grouping (#671 / #2570). `variant_count` is the size of the whole
  8419. // group, which may include files in other folders — never the number of
  8420. // matching rows on screen. 0 when the file is not grouped.
  8421. variant_group_id?: number | null;
  8422. variant_count?: number;
  8423. // Metadata indicators (#3077). Optional for the same reason as `tags`: older
  8424. // mocks construct list items without them. Read sites default to falsy.
  8425. external_url?: string | null;
  8426. has_notes?: boolean;
  8427. photo_count?: number;
  8428. }
  8429. // Variant groups (#671 / #2570): the same job sliced for different printers.
  8430. export interface VariantGroupMember {
  8431. library_file_id: number;
  8432. filename: string;
  8433. target_model: string;
  8434. position: number;
  8435. }
  8436. export interface VariantGroup {
  8437. id: number;
  8438. name: string;
  8439. /** In priority order — index 0 wins when several printers are free at once. */
  8440. members: VariantGroupMember[];
  8441. }
  8442. // Library tag catalog (#1268)
  8443. export interface LibraryTag {
  8444. id: number;
  8445. name: string;
  8446. file_count: number;
  8447. created_at: string;
  8448. updated_at: string;
  8449. }
  8450. export interface LibraryTagBulkAssignResult {
  8451. files_updated: number;
  8452. associations_added: number;
  8453. associations_removed: number;
  8454. }
  8455. export interface LibraryFileUpdate {
  8456. filename?: string;
  8457. folder_id?: number | null;
  8458. project_id?: number | null;
  8459. notes?: string | null;
  8460. external_url?: string | null;
  8461. }
  8462. // Library trash (#1008)
  8463. export interface LibraryTrashItem {
  8464. id: number;
  8465. filename: string;
  8466. file_size: number;
  8467. thumbnail_path: string | null;
  8468. folder_id: number | null;
  8469. folder_name: string | null;
  8470. created_by_id: number | null;
  8471. created_by_username: string | null;
  8472. deleted_at: string;
  8473. auto_purge_at: string;
  8474. }
  8475. export interface LibraryTrashListResponse {
  8476. items: LibraryTrashItem[];
  8477. total: number;
  8478. retention_days: number;
  8479. }
  8480. export interface LibraryPurgePreview {
  8481. count: number;
  8482. total_bytes: number;
  8483. sample_filenames: string[];
  8484. older_than_days: number;
  8485. include_never_printed: boolean;
  8486. }
  8487. export interface LibraryTrashSettings {
  8488. retention_days: number;
  8489. auto_purge_enabled: boolean;
  8490. auto_purge_days: number;
  8491. auto_purge_include_never_printed: boolean;
  8492. }
  8493. export interface ArchivePurgePreview {
  8494. count: number;
  8495. total_bytes: number;
  8496. sample_filenames: string[];
  8497. older_than_days: number;
  8498. }
  8499. export interface ArchiveMergeMember {
  8500. id: number;
  8501. print_name: string | null;
  8502. filename: string;
  8503. created_at: string | null;
  8504. run_count: number;
  8505. }
  8506. /** Why a group is left out: at work now, or holding files only one can keep. */
  8507. export type ArchiveMergeSkip = 'busy' | 'conflicting_files' | 'failed' | 'not_a_group';
  8508. export interface ArchiveMergeGroup {
  8509. survivor: ArchiveMergeMember;
  8510. merged: ArchiveMergeMember[];
  8511. skipped: ArchiveMergeSkip | null;
  8512. }
  8513. export interface ArchiveMergePreview {
  8514. groups: ArchiveMergeGroup[];
  8515. }
  8516. export interface ArchiveMergeResult {
  8517. merged: { survivor_id: number; merged_ids: number[] }[];
  8518. skipped: { survivor_id: number; reason: ArchiveMergeSkip }[];
  8519. }
  8520. export interface ArchivePurgeSettings {
  8521. enabled: boolean;
  8522. days: number;
  8523. // #1390: when true, bulk-deletes the linked PrintLogEntry rows so the
  8524. // contribution drops from Quick Stats too. Default false — soft-delete,
  8525. // Quick Stats preserved.
  8526. purge_stats: boolean;
  8527. }
  8528. export interface LibraryFileUploadResponse {
  8529. id: number;
  8530. filename: string;
  8531. file_type: string;
  8532. file_size: number;
  8533. thumbnail_path: string | null;
  8534. duplicate_of: number | null;
  8535. metadata: Record<string, unknown> | null;
  8536. }
  8537. export interface LibraryStats {
  8538. total_files: number;
  8539. total_folders: number;
  8540. total_size_bytes: number;
  8541. files_by_type: Record<string, number>;
  8542. total_prints: number;
  8543. disk_free_bytes: number;
  8544. disk_total_bytes: number;
  8545. disk_used_bytes: number;
  8546. }
  8547. export interface ZipExtractResult {
  8548. filename: string;
  8549. file_id: number;
  8550. folder_id: number | null;
  8551. }
  8552. export interface ZipExtractError {
  8553. filename: string;
  8554. error: string;
  8555. }
  8556. export interface ZipExtractResponse {
  8557. extracted: number;
  8558. folders_created: number;
  8559. files: ZipExtractResult[];
  8560. errors: ZipExtractError[];
  8561. }
  8562. // STL Thumbnail Generation types
  8563. export interface BatchThumbnailResult {
  8564. file_id: number;
  8565. filename: string;
  8566. success: boolean;
  8567. error?: string | null;
  8568. }
  8569. export interface BatchThumbnailResponse {
  8570. processed: number;
  8571. succeeded: number;
  8572. failed: number;
  8573. results: BatchThumbnailResult[];
  8574. }
  8575. // Discovery types
  8576. export interface DiscoveredPrinter {
  8577. serial: string;
  8578. name: string;
  8579. ip_address: string;
  8580. model: string | null;
  8581. discovered_at: string | null;
  8582. }
  8583. export interface DiscoveryStatus {
  8584. running: boolean;
  8585. }
  8586. export interface DiscoveryInfo {
  8587. is_docker: boolean;
  8588. ssdp_running: boolean;
  8589. scan_running: boolean;
  8590. subnets: string[];
  8591. }
  8592. export interface SubnetScanStatus {
  8593. running: boolean;
  8594. scanned: number;
  8595. total: number;
  8596. }
  8597. // Discovery API
  8598. export const discoveryApi = {
  8599. getInfo: () => request<DiscoveryInfo>('/discovery/info'),
  8600. startDiscovery: (duration: number = 10) =>
  8601. request<DiscoveryStatus>(`/discovery/start?duration=${duration}`, { method: 'POST' }),
  8602. stopDiscovery: () =>
  8603. request<DiscoveryStatus>('/discovery/stop', { method: 'POST' }),
  8604. getDiscoveredPrinters: () =>
  8605. request<DiscoveredPrinter[]>('/discovery/printers'),
  8606. // Subnet scanning (for Docker environments)
  8607. startSubnetScan: (subnet: string, timeout: number = 1.0) =>
  8608. request<SubnetScanStatus>('/discovery/scan', {
  8609. method: 'POST',
  8610. body: JSON.stringify({ subnet, timeout }),
  8611. }),
  8612. getScanStatus: () => request<SubnetScanStatus>('/discovery/scan/status'),
  8613. stopSubnetScan: () =>
  8614. request<SubnetScanStatus>('/discovery/scan/stop', { method: 'POST' }),
  8615. };
  8616. // Virtual Printer types
  8617. // Canonical wire values: `archive`, `review`, `queue`, `proxy`. The legacy
  8618. // `immediate` (→ archive) and `print_queue` (→ queue) names are still
  8619. // accepted by the backend so older API clients keep working, but new code
  8620. // should send the canonical names.
  8621. export type VirtualPrinterMode = 'archive' | 'review' | 'queue' | 'proxy' | 'immediate' | 'print_queue';
  8622. export interface VirtualPrinterProxyStatus {
  8623. running: boolean;
  8624. target_host: string;
  8625. ftp_port: number;
  8626. mqtt_port: number;
  8627. ftp_connections: number;
  8628. mqtt_connections: number;
  8629. }
  8630. export interface VirtualPrinterStatus {
  8631. enabled: boolean;
  8632. running: boolean;
  8633. mode: VirtualPrinterMode;
  8634. name: string;
  8635. serial: string;
  8636. model: string;
  8637. model_name: string;
  8638. pending_files: number;
  8639. target_printer_ip?: string; // For proxy mode
  8640. proxy?: VirtualPrinterProxyStatus; // For proxy mode
  8641. }
  8642. export interface VirtualPrinterSettings {
  8643. tailscale_disabled: boolean;
  8644. archive_name_source: 'metadata' | 'filename'; // Source for archive's display name
  8645. status: VirtualPrinterStatus;
  8646. }
  8647. export interface NetworkInterface {
  8648. name: string;
  8649. ip: string;
  8650. netmask: string;
  8651. subnet: string;
  8652. is_alias?: boolean;
  8653. label?: string;
  8654. }
  8655. export interface PendingUpload {
  8656. id: number;
  8657. filename: string;
  8658. // Resolved name the review card should show — mirrors what archive_print
  8659. // will eventually write to PrintArchive.print_name (#1152 follow-up). Falls
  8660. // back to the stripped filename stem when the 3MF has no embedded title or
  8661. // the operator has chosen the "filename" archive-name source.
  8662. display_name: string;
  8663. file_size: number;
  8664. source_ip: string | null;
  8665. status: string;
  8666. tags: string | null;
  8667. notes: string | null;
  8668. project_id: number | null;
  8669. uploaded_at: string;
  8670. }
  8671. // Virtual Printer API
  8672. export const virtualPrinterApi = {
  8673. getSettings: () => request<VirtualPrinterSettings>('/settings/virtual-printer'),
  8674. updateSettings: (data: {
  8675. tailscale_disabled?: boolean;
  8676. archive_name_source?: 'metadata' | 'filename';
  8677. }) => {
  8678. const params = new URLSearchParams();
  8679. if (data.tailscale_disabled !== undefined) params.set('tailscale_disabled', String(data.tailscale_disabled));
  8680. if (data.archive_name_source !== undefined) params.set('archive_name_source', data.archive_name_source);
  8681. return request<VirtualPrinterSettings>(`/settings/virtual-printer?${params.toString()}`, {
  8682. method: 'PUT',
  8683. });
  8684. },
  8685. };
  8686. // Multi Virtual Printer API
  8687. export interface VirtualPrinterConfig {
  8688. id: number;
  8689. name: string;
  8690. enabled: boolean;
  8691. mode: VirtualPrinterMode;
  8692. model: string | null;
  8693. model_name: string | null;
  8694. access_code_set: boolean;
  8695. serial: string;
  8696. target_printer_id: number | null;
  8697. auto_dispatch: boolean;
  8698. queue_force_color_match: boolean;
  8699. save_ams_mapping: boolean;
  8700. gcode_injection: boolean;
  8701. tailscale_disabled: boolean;
  8702. bind_ip: string | null;
  8703. remote_interface_ip: string | null;
  8704. position: number;
  8705. status: { running: boolean; pending_files: number; proxy?: VirtualPrinterProxyStatus };
  8706. }
  8707. export interface VirtualPrinterListResponse {
  8708. printers: VirtualPrinterConfig[];
  8709. models: Record<string, string>;
  8710. }
  8711. export const multiVirtualPrinterApi = {
  8712. list: () => request<VirtualPrinterListResponse>('/virtual-printers'),
  8713. get: (id: number) => request<VirtualPrinterConfig>(`/virtual-printers/${id}`),
  8714. create: (data: {
  8715. name?: string;
  8716. enabled?: boolean;
  8717. mode?: string;
  8718. model?: string;
  8719. access_code?: string;
  8720. target_printer_id?: number;
  8721. auto_dispatch?: boolean;
  8722. queue_force_color_match?: boolean;
  8723. save_ams_mapping?: boolean;
  8724. gcode_injection?: boolean;
  8725. bind_ip?: string;
  8726. remote_interface_ip?: string;
  8727. }) =>
  8728. request<VirtualPrinterConfig>('/virtual-printers', {
  8729. method: 'POST',
  8730. body: JSON.stringify(data),
  8731. }),
  8732. update: (id: number, data: {
  8733. name?: string;
  8734. enabled?: boolean;
  8735. mode?: string;
  8736. model?: string;
  8737. access_code?: string;
  8738. target_printer_id?: number;
  8739. auto_dispatch?: boolean;
  8740. queue_force_color_match?: boolean;
  8741. save_ams_mapping?: boolean;
  8742. gcode_injection?: boolean;
  8743. tailscale_disabled?: boolean;
  8744. bind_ip?: string;
  8745. remote_interface_ip?: string;
  8746. }) =>
  8747. request<VirtualPrinterConfig>(`/virtual-printers/${id}`, {
  8748. method: 'PUT',
  8749. body: JSON.stringify(data),
  8750. }),
  8751. remove: (id: number) =>
  8752. request<{ detail: string; id: number }>(`/virtual-printers/${id}`, {
  8753. method: 'DELETE',
  8754. }),
  8755. getTailscaleStatus: () =>
  8756. request<TailscaleStatusResponse>('/virtual-printers/tailscale-status'),
  8757. getCaCertificate: () =>
  8758. request<VPCaCertificate>('/virtual-printers/ca-certificate'),
  8759. diagnose: (id: number) =>
  8760. request<VPDiagnosticResult>(`/virtual-printers/${id}/diagnostic`),
  8761. };
  8762. /** The shared CA certificate every virtual printer presents — imported once
  8763. * into the slicer's trust store. Only the public certificate is returned. */
  8764. export interface VPCaCertificate {
  8765. pem: string;
  8766. fingerprint_sha256: string;
  8767. not_valid_after: string;
  8768. }
  8769. export type VPDiagnosticStatus = 'pass' | 'fail' | 'warn' | 'skip';
  8770. export interface VPDiagnosticCheck {
  8771. id:
  8772. | 'enabled'
  8773. | 'running'
  8774. | 'bind_interface'
  8775. | 'access_code'
  8776. | 'target_printer'
  8777. | 'port_ftps'
  8778. | 'port_mqtt'
  8779. | 'port_bind'
  8780. | 'certificate';
  8781. status: VPDiagnosticStatus;
  8782. params: Record<string, string | number>;
  8783. }
  8784. export interface VPDiagnosticResult {
  8785. vp_id: number;
  8786. vp_name: string;
  8787. mode: string;
  8788. overall: 'ok' | 'warnings' | 'problems';
  8789. checks: VPDiagnosticCheck[];
  8790. }
  8791. export interface TailscaleStatusResponse {
  8792. available: boolean;
  8793. fqdn: string;
  8794. hostname: string;
  8795. tailnet_name: string;
  8796. tailscale_ips: string[];
  8797. error: string | null;
  8798. }
  8799. // Pending Uploads API
  8800. export const pendingUploadsApi = {
  8801. list: () => request<PendingUpload[]>('/pending-uploads/'),
  8802. getCount: () => request<{ count: number }>('/pending-uploads/count'),
  8803. get: (id: number) => request<PendingUpload>(`/pending-uploads/${id}`),
  8804. archive: (id: number, data?: { tags?: string; notes?: string; project_id?: number }) =>
  8805. request<{ id: number; print_name: string; filename: string }>(`/pending-uploads/${id}/archive`, {
  8806. method: 'POST',
  8807. body: JSON.stringify(data || {}),
  8808. }),
  8809. discard: (id: number) =>
  8810. request<{ success: boolean }>(`/pending-uploads/${id}`, { method: 'DELETE' }),
  8811. archiveAll: () =>
  8812. request<{ archived: number; failed: number }>('/pending-uploads/archive-all', { method: 'POST' }),
  8813. discardAll: () =>
  8814. request<{ discarded: number }>('/pending-uploads/discard-all', { method: 'DELETE' }),
  8815. };
  8816. // Firmware API Types
  8817. export interface AvailableFirmwareVersion {
  8818. version: string;
  8819. file_available: boolean;
  8820. download_url: string | null;
  8821. release_notes: string | null;
  8822. release_time: string | null;
  8823. }
  8824. export interface FirmwareUpdateInfo {
  8825. printer_id: number;
  8826. printer_name: string;
  8827. model: string | null;
  8828. current_version: string | null;
  8829. latest_version: string | null;
  8830. update_available: boolean;
  8831. download_url: string | null;
  8832. release_notes: string | null;
  8833. available_versions: AvailableFirmwareVersion[];
  8834. }
  8835. export interface FirmwareUploadPrepare {
  8836. can_proceed: boolean;
  8837. sd_card_present: boolean;
  8838. sd_card_free_space: number;
  8839. firmware_size: number;
  8840. space_sufficient: boolean;
  8841. update_available: boolean;
  8842. current_version: string | null;
  8843. latest_version: string | null;
  8844. target_version: string | null;
  8845. firmware_filename: string | null;
  8846. errors: string[];
  8847. }
  8848. export interface FirmwareUploadStatus {
  8849. status: 'idle' | 'preparing' | 'downloading' | 'uploading' | 'complete' | 'error';
  8850. progress: number;
  8851. message: string;
  8852. error: string | null;
  8853. firmware_filename: string | null;
  8854. firmware_version: string | null;
  8855. }
  8856. // Firmware API
  8857. export const firmwareApi = {
  8858. checkUpdates: () =>
  8859. request<{ updates: FirmwareUpdateInfo[]; updates_available: number }>('/firmware/updates'),
  8860. checkPrinterUpdate: (printerId: number) => firmwareUpdateBatch(printerId),
  8861. prepareUpload: (printerId: number, version?: string) =>
  8862. request<FirmwareUploadPrepare>(
  8863. `/firmware/updates/${printerId}/prepare${version ? `?version=${encodeURIComponent(version)}` : ''}`,
  8864. ),
  8865. startUpload: (printerId: number, version?: string) =>
  8866. request<{ started: boolean; message: string }>(
  8867. `/firmware/updates/${printerId}/upload${version ? `?version=${encodeURIComponent(version)}` : ''}`,
  8868. { method: 'POST' },
  8869. ),
  8870. getUploadStatus: (printerId: number) =>
  8871. request<FirmwareUploadStatus>(`/firmware/updates/${printerId}/upload/status`),
  8872. };
  8873. // Support types
  8874. export interface DebugLoggingState {
  8875. enabled: boolean;
  8876. enabled_at: string | null;
  8877. duration_seconds: number | null;
  8878. }
  8879. export interface LogEntry {
  8880. timestamp: string;
  8881. level: string;
  8882. logger_name: string;
  8883. message: string;
  8884. }
  8885. export interface LogsResponse {
  8886. entries: LogEntry[];
  8887. total_in_file: number;
  8888. filtered_count: number;
  8889. }
  8890. // Support API
  8891. export const supportApi = {
  8892. getDebugLoggingState: () =>
  8893. request<DebugLoggingState>('/support/debug-logging'),
  8894. setDebugLogging: (enabled: boolean) =>
  8895. request<DebugLoggingState>('/support/debug-logging', {
  8896. method: 'POST',
  8897. body: JSON.stringify({ enabled }),
  8898. }),
  8899. downloadSupportBundle: async () => {
  8900. const headers: Record<string, string> = {};
  8901. if (authToken) {
  8902. headers['Authorization'] = `Bearer ${authToken}`;
  8903. }
  8904. const response = await fetch(`${API_BASE}/support/bundle`, { headers });
  8905. if (!response.ok) {
  8906. const error = await response.json().catch(() => ({}));
  8907. throw new Error(error.detail || `HTTP ${response.status}`);
  8908. }
  8909. // Get filename from Content-Disposition header or use default
  8910. const disposition = response.headers.get('Content-Disposition');
  8911. const filename = parseContentDispositionFilename(disposition) || 'bambuddy-support.zip';
  8912. // Download the blob
  8913. const blob = await response.blob();
  8914. const url = window.URL.createObjectURL(blob);
  8915. const a = document.createElement('a');
  8916. a.href = url;
  8917. a.download = filename;
  8918. document.body.appendChild(a);
  8919. a.click();
  8920. document.body.removeChild(a);
  8921. window.URL.revokeObjectURL(url);
  8922. },
  8923. getLogs: (params?: { limit?: number; level?: string; search?: string }) => {
  8924. const searchParams = new URLSearchParams();
  8925. if (params?.limit) searchParams.set('limit', params.limit.toString());
  8926. if (params?.level) searchParams.set('level', params.level);
  8927. if (params?.search) searchParams.set('search', params.search);
  8928. const query = searchParams.toString();
  8929. return request<LogsResponse>(`/support/logs${query ? `?${query}` : ''}`);
  8930. },
  8931. clearLogs: () =>
  8932. request<{ message: string }>('/support/logs', { method: 'DELETE' }),
  8933. };
  8934. // SpoolBuddy types
  8935. export interface SpoolBuddyDevice {
  8936. id: number;
  8937. device_id: string;
  8938. hostname: string;
  8939. ip_address: string;
  8940. backend_url?: string | null;
  8941. firmware_version: string | null;
  8942. has_nfc: boolean;
  8943. has_scale: boolean;
  8944. tare_offset: number;
  8945. calibration_factor: number;
  8946. nfc_reader_type: string | null;
  8947. nfc_connection: string | null;
  8948. display_brightness: number;
  8949. display_blank_timeout: number;
  8950. has_backlight: boolean;
  8951. last_calibrated_at: string | null;
  8952. last_seen: string | null;
  8953. pending_command: string | null;
  8954. nfc_ok: boolean;
  8955. scale_ok: boolean;
  8956. uptime_s: number;
  8957. update_status: string | null;
  8958. update_message: string | null;
  8959. system_stats: {
  8960. os?: { os?: string; kernel?: string; arch?: string; python?: string };
  8961. cpu_temp_c?: number;
  8962. cpu_count?: number;
  8963. load_avg?: number[];
  8964. memory?: { total_mb?: number; available_mb?: number; used_mb?: number; percent?: number };
  8965. disk?: { total_gb?: number; used_gb?: number; free_gb?: number; percent?: number };
  8966. system_uptime_s?: number;
  8967. } | null;
  8968. online: boolean;
  8969. }
  8970. export interface DaemonUpdateCheck {
  8971. current_version: string;
  8972. latest_version: string | null;
  8973. update_available: boolean;
  8974. }
  8975. // SpoolBuddy API
  8976. export const spoolbuddyApi = {
  8977. getDevices: () =>
  8978. request<SpoolBuddyDevice[]>('/spoolbuddy/devices'),
  8979. deleteDevice: (deviceId: string) =>
  8980. request<{ status: string; device_id: string }>(`/spoolbuddy/devices/${deviceId}`, {
  8981. method: 'DELETE',
  8982. }),
  8983. tare: (deviceId: string) =>
  8984. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/calibration/tare`, {
  8985. method: 'POST',
  8986. body: '{}',
  8987. }),
  8988. setCalibrationFactor: (deviceId: string, knownWeightGrams: number, rawAdc: number, tareRawAdc?: number) =>
  8989. request<{ tare_offset: number; calibration_factor: number }>(`/spoolbuddy/devices/${deviceId}/calibration/set-factor`, {
  8990. method: 'POST',
  8991. body: JSON.stringify({ known_weight_grams: knownWeightGrams, raw_adc: rawAdc, tare_raw_adc: tareRawAdc }),
  8992. }),
  8993. updateSpoolWeight: (spoolId: number, weightGrams: number) =>
  8994. request<{ status: string; weight_used: number }>('/spoolbuddy/scale/update-spool-weight', {
  8995. method: 'POST',
  8996. body: JSON.stringify({ spool_id: spoolId, weight_grams: weightGrams }),
  8997. }),
  8998. updateDisplay: (deviceId: string, brightness: number, blankTimeout: number) =>
  8999. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/display`, {
  9000. method: 'PUT',
  9001. body: JSON.stringify({ brightness, blank_timeout: blankTimeout }),
  9002. }),
  9003. updateSystemConfig: (deviceId: string, backendUrl: string, apiKey?: string) =>
  9004. request<{ status: string; message: string }>(`/spoolbuddy/devices/${deviceId}/system/config`, {
  9005. method: 'POST',
  9006. body: JSON.stringify({ backend_url: backendUrl, ...(apiKey ? { api_key: apiKey } : {}) }),
  9007. }),
  9008. checkDaemonUpdate: (deviceId: string) =>
  9009. request<DaemonUpdateCheck>(`/spoolbuddy/devices/${deviceId}/update-check`),
  9010. triggerUpdate: (deviceId: string) =>
  9011. request<{ status: string; message: string }>(`/spoolbuddy/devices/${deviceId}/update`, {
  9012. method: 'POST',
  9013. body: '{}',
  9014. }),
  9015. getSSHPublicKey: () =>
  9016. request<{ public_key: string }>('/spoolbuddy/ssh/public-key'),
  9017. writeTag: (deviceId: string, spoolId: number) =>
  9018. request<{ status: string; warnings?: string[] }>('/spoolbuddy/nfc/write-tag', {
  9019. method: 'POST',
  9020. body: JSON.stringify({ device_id: deviceId, spool_id: spoolId }),
  9021. }),
  9022. cancelWrite: (deviceId: string) =>
  9023. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/cancel-write`, {
  9024. method: 'POST',
  9025. body: '{}',
  9026. }),
  9027. systemCommand: (deviceId: string, command: 'reboot' | 'shutdown' | 'restart_daemon' | 'restart_browser') =>
  9028. request<{ status: string; command: string }>(`/spoolbuddy/devices/${deviceId}/system/command`, {
  9029. method: 'POST',
  9030. body: JSON.stringify({ command }),
  9031. }),
  9032. queueDiagnostics: (deviceId: string, type: 'nfc' | 'scale' | 'read_tag') =>
  9033. request<{ status: string; diagnostic: string; message: string }>(
  9034. `/spoolbuddy/diagnostics/${deviceId}/run?diagnostic=${type}`,
  9035. { method: 'POST', body: '{}' }
  9036. ),
  9037. getDiagnosticResult: (deviceId: string, type: 'nfc' | 'scale' | 'read_tag') =>
  9038. request<{ diagnostic: string; success: boolean; output: string; exit_code: number }>(
  9039. `/spoolbuddy/diagnostics/${deviceId}/result?diagnostic=${type}`,
  9040. { method: 'GET' }
  9041. ),
  9042. };
  9043. export interface BugReportRequest {
  9044. description: string;
  9045. email?: string;
  9046. screenshot_base64?: string;
  9047. include_support_info?: boolean;
  9048. debug_logs?: string;
  9049. }
  9050. export interface BugReportResponse {
  9051. success: boolean;
  9052. message: string;
  9053. issue_url?: string;
  9054. issue_number?: number;
  9055. }
  9056. export const bugReportApi = {
  9057. submit: (data: BugReportRequest) =>
  9058. request<BugReportResponse>('/bug-report/submit', {
  9059. method: 'POST',
  9060. body: JSON.stringify(data),
  9061. }),
  9062. startLogging: () =>
  9063. request<{ started: boolean; was_debug: boolean }>('/bug-report/start-logging', {
  9064. method: 'POST',
  9065. }),
  9066. stopLogging: (wasDebug: boolean) =>
  9067. request<{ logs: string }>(`/bug-report/stop-logging?was_debug=${wasDebug}`, {
  9068. method: 'POST',
  9069. }),
  9070. };
  9071. export type AnnouncementLevel = 'info' | 'important' | 'critical';
  9072. export interface AnnouncementText {
  9073. title: string;
  9074. body: string;
  9075. link_label?: string;
  9076. }
  9077. // One message from the Bambuddy maintainers. `texts` holds every language the
  9078. // message was written in; English is always there.
  9079. export interface Announcement {
  9080. id: string;
  9081. level: AnnouncementLevel;
  9082. texts: Record<string, AnnouncementText>;
  9083. link_url: string | null;
  9084. published_at: string | null;
  9085. expires_at: string | null;
  9086. // Past its expiry: kept as history, listed under "Earlier", never unread.
  9087. archived: boolean;
  9088. read: boolean;
  9089. }
  9090. // `visible` says whether this user may see announcements at all (switched on,
  9091. // and admin or "show to all users"); it keeps the sidebar entry while nothing
  9092. // is published.
  9093. export interface AnnouncementList {
  9094. visible: boolean;
  9095. announcements: Announcement[];
  9096. }
  9097. export const announcementsApi = {
  9098. list: () => request<AnnouncementList>('/announcements'),
  9099. markRead: (id: string) =>
  9100. request<void>(`/announcements/${encodeURIComponent(id)}/read`, { method: 'POST' }),
  9101. };
  9102. export interface SponsorPromptCheckResponse {
  9103. show: boolean;
  9104. milestone?: string;
  9105. family?: 'prints' | 'cost' | 'archives' | 'anniversary' | 'version-update';
  9106. threshold?: number;
  9107. payload?: Record<string, unknown>;
  9108. }
  9109. export const sponsorPromptApi = {
  9110. check: () => request<SponsorPromptCheckResponse>('/sponsor-prompt/check'),
  9111. dismiss: (milestone: string) =>
  9112. request<void>('/sponsor-prompt/dismiss', {
  9113. method: 'POST',
  9114. body: JSON.stringify({ milestone }),
  9115. }),
  9116. };