client.ts 353 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849
  1. import type { KProfileWriteResult } from '../utils/kprofileWrite';
  2. import type { BambuCatalogColor } from '../utils/colors';
  3. import type { ArchivePlatesResponse, LibraryFilePlatesResponse } from '../types/plates';
  4. import { batched, byField, byId } from './batch';
  5. const API_BASE = '/api/v1';
  6. export class ApiError extends Error {
  7. status: number;
  8. /** Stable error code from a structured backend detail (`{code, message}`).
  9. * Frontend uses this to look up an i18n key instead of showing the raw
  10. * English fallback. Null when the backend returned a plain-string detail. */
  11. code: string | null;
  12. /** Full structured detail object when the backend returned `{code, ...}`
  13. * with additional fields (e.g. the deficit list for 409s on queue
  14. * start, #1496). Null for plain-string or array-shaped details. */
  15. detail: Record<string, unknown> | null;
  16. constructor(
  17. message: string,
  18. status: number,
  19. code: string | null = null,
  20. detail: Record<string, unknown> | null = null,
  21. ) {
  22. super(message);
  23. this.name = 'ApiError';
  24. this.status = status;
  25. this.code = code;
  26. this.detail = detail;
  27. }
  28. }
  29. // Auth token storage
  30. // By default tokens are stored in sessionStorage (tab-scoped, cleared on close).
  31. // When the token originates from the ?token= URL param (kiosk bootstrap), it is
  32. // additionally persisted in localStorage so the kiosk survives page reloads.
  33. // 'persistent' also writes to localStorage so the token survives tab close
  34. // (used by Remember Me and the ?token= kiosk bootstrap).
  35. let authToken: string | null =
  36. sessionStorage.getItem('auth_token') ?? localStorage.getItem('auth_token');
  37. export type TokenPersistence = 'session' | 'persistent';
  38. export function setAuthToken(token: string | null, persistence: TokenPersistence = 'session') {
  39. authToken = token;
  40. try {
  41. if (token) {
  42. sessionStorage.setItem('auth_token', token);
  43. } else {
  44. sessionStorage.removeItem('auth_token');
  45. }
  46. } catch (err) {
  47. // Storage unavailable (quota exceeded, private mode): in-memory token still works for this tab.
  48. console.warn('setAuthToken: sessionStorage unavailable, token kept in-memory only', err);
  49. }
  50. try {
  51. if (!token) {
  52. localStorage.removeItem('auth_token');
  53. } else if (persistence === 'persistent') {
  54. localStorage.setItem('auth_token', token);
  55. }
  56. } catch (err) {
  57. console.warn('setAuthToken: localStorage operation failed', err);
  58. }
  59. }
  60. export function getAuthToken(): string | null {
  61. return authToken;
  62. }
  63. // Query-param tokens for <img>/<video> src URLs, which can't carry an
  64. // Authorization header. There are two, and which one a URL takes is decided
  65. // by what the URL points at, not by convenience:
  66. //
  67. // streamToken — live camera only. Minting one costs camera:view.
  68. // mediaToken — thumbnails, previews, timelapses, covers, icons. Minted by
  69. // any signed-in user and carries their identity, so those
  70. // routes can apply the same ownership rules as everywhere else.
  71. //
  72. // Before #3025 the stream token served both, which meant a user could not see
  73. // a library thumbnail without also being granted the live feed of the room the
  74. // printer sits in — and, because a stream token names nobody, those routes had
  75. // no identity to scope by and served any row to any holder.
  76. let streamToken: string | null = null;
  77. let mediaToken: string | null = null;
  78. export function setStreamToken(token: string | null) {
  79. streamToken = token;
  80. }
  81. export function getStreamToken(): string | null {
  82. return streamToken;
  83. }
  84. export function setMediaToken(token: string | null) {
  85. mediaToken = token;
  86. }
  87. export function getMediaToken(): string | null {
  88. return mediaToken;
  89. }
  90. /** Append the camera stream token to a URL if available (live camera only). */
  91. export function withStreamToken(url: string): string {
  92. if (!streamToken) return url;
  93. const sep = url.includes('?') ? '&' : '?';
  94. return `${url}${sep}token=${encodeURIComponent(streamToken)}`;
  95. }
  96. /** Append the media token to a URL if available (for <img>/<video> src). */
  97. export function withMediaToken(url: string): string {
  98. if (!mediaToken) return url;
  99. const sep = url.includes('?') ? '&' : '?';
  100. return `${url}${sep}token=${encodeURIComponent(mediaToken)}`;
  101. }
  102. function parseContentDispositionFilename(header: string | null): string | null {
  103. if (!header) return null;
  104. // RFC 5987: filename*=utf-8''percent-encoded-name
  105. const rfc5987Match = header.match(/filename\*=(?:UTF-8|utf-8)''(.+?)(?:;|$)/);
  106. if (rfc5987Match) {
  107. try { return decodeURIComponent(rfc5987Match[1]); } catch { /* fall through */ }
  108. }
  109. // Standard: filename="name" or filename=name
  110. const standardMatch = header.match(/filename="?([^";\n]+)"?/);
  111. return standardMatch?.[1] || null;
  112. }
  113. function buildSlicerUrlFilename(filename: string): string {
  114. const safe = filename.replace(/[/\\?#]/g, '_');
  115. return safe.toLowerCase().endsWith('.3mf') ? safe : `${safe}.3mf`;
  116. }
  117. /** POST JSON and return the response body as a Blob (label PDFs and images). */
  118. async function postForBlob(endpoint: string, data: unknown, signal?: AbortSignal): Promise<Blob> {
  119. const headers: Record<string, string> = { 'Content-Type': 'application/json' };
  120. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  121. const response = await fetch(`${API_BASE}${endpoint}`, {
  122. method: 'POST',
  123. headers,
  124. body: JSON.stringify(data),
  125. signal,
  126. });
  127. if (!response.ok) {
  128. const error = await response.json().catch(() => ({}));
  129. throw new Error(typeof error.detail === 'string' ? error.detail : `HTTP ${response.status}`);
  130. }
  131. return response.blob();
  132. }
  133. async function request<T>(
  134. endpoint: string,
  135. options: RequestInit = {}
  136. ): Promise<T> {
  137. const headers: Record<string, string> = {
  138. 'Content-Type': 'application/json',
  139. ...options.headers as Record<string, string>,
  140. };
  141. // Add auth token if available
  142. if (authToken) {
  143. headers['Authorization'] = `Bearer ${authToken}`;
  144. }
  145. const response = await fetch(`${API_BASE}${endpoint}`, {
  146. ...options,
  147. cache: 'no-store', // Prevent browser caching of API responses
  148. credentials: 'include', // Required for HttpOnly cookies (e.g. 2fa_challenge)
  149. headers,
  150. });
  151. if (!response.ok) {
  152. const error = await response.json().catch(() => ({}));
  153. const detail = error.detail;
  154. let message: string;
  155. let code: string | null = null;
  156. if (typeof detail === 'string') {
  157. message = detail;
  158. } else if (Array.isArray(detail)) {
  159. // FastAPI 422 shape: each entry has `msg` like "Value error, <real msg>".
  160. // Strip the prefix and join. Fall back to raw JSON if every entry has an
  161. // empty msg (defensive — shouldn't happen with stock Pydantic, but the
  162. // previous fallback masked the real cause as a bare "HTTP 422" toast).
  163. const joined = detail
  164. .map((e: { msg?: string }) => (e.msg ?? '').replace(/^Value error,\s*/i, ''))
  165. .filter(Boolean)
  166. .join('; ');
  167. message = joined || JSON.stringify(detail) || `HTTP ${response.status}`;
  168. } else if (detail && typeof detail === 'object') {
  169. // Structured detail `{code, message, ...}` — frontend uses the code
  170. // to pick an i18n key, message is the English fallback, any extra
  171. // fields land on ApiError.detail (e.g. `deficit` for #1496).
  172. code = typeof detail.code === 'string' ? detail.code : null;
  173. message = typeof detail.message === 'string' ? detail.message : `HTTP ${response.status}`;
  174. } else {
  175. message = `HTTP ${response.status}`;
  176. }
  177. const structuredDetail = detail && typeof detail === 'object' && !Array.isArray(detail)
  178. ? (detail as Record<string, unknown>)
  179. : null;
  180. // Handle 401 Unauthorized - only clear token if it's actually invalid
  181. // Don't clear on "Authentication required" which might be a timing issue
  182. if (response.status === 401) {
  183. const invalidTokenMessages = [
  184. 'Could not validate credentials',
  185. 'Token has expired',
  186. 'User not found or inactive',
  187. 'Invalid API key',
  188. 'API key has expired',
  189. ];
  190. if (invalidTokenMessages.some(m => message.includes(m))) {
  191. setAuthToken(null);
  192. // Notify AuthContext so the protected route guard re-evaluates and
  193. // redirects to /login on the same tab — without this, AuthContext.user
  194. // stays cached and the tab silently fails every request until a manual
  195. // refresh remounts AuthProvider (#1698, reported by @TCL987).
  196. if (typeof window !== 'undefined') {
  197. window.dispatchEvent(new CustomEvent('auth:expired'));
  198. }
  199. }
  200. }
  201. throw new ApiError(message, response.status, code, structuredDetail);
  202. }
  203. // Handle empty responses (204 No Content, etc.)
  204. const contentLength = response.headers.get('content-length');
  205. if (response.status === 204 || contentLength === '0') {
  206. return undefined as T;
  207. }
  208. return await response.json();
  209. }
  210. /** Upload a CSV to the spool import endpoint (#1576). Multipart, so it bypasses
  211. * `request<T>()` (which sends JSON): the browser must set the form-data
  212. * boundary itself. `dryRun` toggles preview-only vs. real import. */
  213. async function uploadSpoolsCsv<T>(file: File, dryRun: boolean): Promise<T> {
  214. const form = new FormData();
  215. form.append('file', file);
  216. const headers: Record<string, string> = {};
  217. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  218. const response = await fetch(`${API_BASE}/inventory/spools/import${dryRun ? '?dry_run=true' : ''}`, {
  219. method: 'POST',
  220. headers,
  221. body: form,
  222. });
  223. if (!response.ok) {
  224. const error = await response.json().catch(() => ({}));
  225. // detail may be a plain string or a structured {code, message} object
  226. // (e.g. the 413 too-large response). Surface the human message either way.
  227. const detail = error?.detail;
  228. const message = typeof detail === 'string' ? detail : detail?.message;
  229. throw new Error(message || `HTTP ${response.status}`);
  230. }
  231. return response.json();
  232. }
  233. // Camera diagnostic result (#1395 follow-up). Returned by
  234. // POST /printers/{id}/camera/diagnose; the frontend modal renders one
  235. // row per stage and looks up the summary code in i18n for the user-
  236. // facing remediation hint.
  237. export interface CameraDiagnoseStage {
  238. name: 'tcp_reachable' | 'first_frame' | 'live_stream_active';
  239. status: 'ok' | 'failed' | 'skipped';
  240. duration_ms: number;
  241. code: string | null;
  242. }
  243. export interface CameraDiagnoseResult {
  244. printer_id: number;
  245. protocol: 'rtsp' | 'chamber_image';
  246. port: number;
  247. // 'default' = historical X1/H2 tuning. Anything else = this model has
  248. // an override entry in backend/app/services/camera_profiles.py.
  249. profile: string;
  250. overall_status: 'ok' | 'failed';
  251. stages: CameraDiagnoseStage[];
  252. // i18n key under `camera.diagnose.summary.*`.
  253. summary_code: string;
  254. }
  255. // Connection diagnostic (GET /printers/{id}/diagnostic and
  256. // POST /printers/diagnostic). Each check's `id` + `status` resolve a
  257. // localized title/fix under `diagnostic.check.*`; `params` interpolate it.
  258. export type DiagnosticStatus = 'pass' | 'fail' | 'warn' | 'skip';
  259. export interface DiagnosticCheck {
  260. id:
  261. | 'port_mqtt'
  262. | 'port_ftps'
  263. | 'port_rtsps'
  264. | 'network_mode'
  265. | 'subnet'
  266. | 'mqtt_auth'
  267. | 'developer_mode';
  268. status: DiagnosticStatus;
  269. params: Record<string, string | number>;
  270. }
  271. export interface PrinterDiagnosticResult {
  272. printer_id: number | null;
  273. ip_address: string;
  274. overall: 'ok' | 'warnings' | 'problems';
  275. checks: DiagnosticCheck[];
  276. }
  277. // --- Log-health scan: self-service triage on the System page + bug reporter.
  278. // The backend matches recent logs against a curated known-issue catalog;
  279. // human-readable cause/fix text is rendered from i18n keys keyed by signature_id.
  280. export type LogFindingSeverity = 'error' | 'warning';
  281. export type LogFindingCategory = 'layer8' | 'environment' | 'bug';
  282. export interface LogFinding {
  283. signature_id: string;
  284. severity: LogFindingSeverity;
  285. category: LogFindingCategory;
  286. wiki_anchor: string;
  287. count: number;
  288. first_seen: string;
  289. last_seen: string;
  290. sample: string;
  291. }
  292. export interface SystemHealthResult {
  293. findings: LogFinding[];
  294. scanned_entries: number;
  295. log_available: boolean;
  296. summary: {
  297. total: number;
  298. layer8: number;
  299. environment: number;
  300. bug: number;
  301. };
  302. }
  303. // Long-lived camera tokens (#1108). The `token` field is populated only on the
  304. // create response — listing endpoints set it to null because the plaintext
  305. // value is shown to the user exactly once.
  306. //
  307. // 'camera_stream' reaches the video endpoints only. 'camwall' additionally
  308. // reaches the read-only Cam Wall feed, which names the printers (#2531), so it
  309. // is a separate scope rather than a widening of tokens already in the wild.
  310. export type LongLivedTokenScope = 'camera_stream' | 'camwall' | 'overlay';
  311. export interface LongLivedCameraToken {
  312. id: number;
  313. user_id: number;
  314. name: string;
  315. scope: LongLivedTokenScope;
  316. lookup_prefix: string;
  317. created_at: string;
  318. expires_at: string;
  319. last_used_at: string | null;
  320. token: string | null;
  321. }
  322. // An external application that signs users in with their Bambuddy account.
  323. // `client_secret` is present only in the create / rotate responses.
  324. export interface ConnectedApp {
  325. id: number;
  326. name: string;
  327. client_id: string;
  328. redirect_uri: string;
  329. enabled: boolean;
  330. created_at: string;
  331. last_used_at: string | null;
  332. client_secret?: string;
  333. }
  334. export interface ConnectAuthorizeInfo {
  335. app_name: string;
  336. username: string;
  337. already_granted: boolean;
  338. }
  339. // One row of the token-authenticated Cam Wall feed (#2531). Deliberately
  340. // smaller than PrinterStatus: no serial, no IP, no print filename — a kiosk URL
  341. // is not a secret, so the payload behind it must not be either.
  342. export interface CamWallPrinter {
  343. id: number;
  344. name: string;
  345. camera_rotation: number;
  346. connected: boolean;
  347. state: string | null;
  348. progress: number | null;
  349. remaining_time: number | null;
  350. layer_num: number | null;
  351. total_layers: number | null;
  352. hms_errors: HMSError[];
  353. }
  354. // Streaming-overlay feed (#2613). The subset of print state the /overlay page
  355. // draws for one printer, served behind an `overlay`-scoped token so OBS embeds
  356. // with no login session can read it. Unlike CamWallPrinter this names the file
  357. // being printed (the overlay shows the part on screen).
  358. export interface OverlayStatus {
  359. id: number;
  360. name: string;
  361. model: string | null;
  362. camera_rotation: number;
  363. connected: boolean;
  364. state: string | null;
  365. current_print: string | null;
  366. gcode_file: string | null;
  367. progress: number | null;
  368. remaining_time: number | null;
  369. layer_num: number | null;
  370. total_layers: number | null;
  371. stg_cur_name: string | null;
  372. // Nozzle / bed / chamber readings for the overlay's temperature fields
  373. // (#1422). Only the keys a viewer is shown; chamber is absent on models
  374. // without a real sensor.
  375. temperatures: Record<string, number>;
  376. time_format: 'system' | '12h' | '24h';
  377. }
  378. // Printer types
  379. // Printer locations (groups) and their appearance (#2962). `id` is null for a
  380. // location only printers carry, with no row of its own yet.
  381. export interface PrinterLocation {
  382. id: number | null;
  383. name: string;
  384. icon: string | null;
  385. color: string | null;
  386. printer_count: number;
  387. }
  388. export interface PrinterLocationUpdate {
  389. name: string;
  390. new_name?: string;
  391. icon?: string | null;
  392. color?: string | null;
  393. }
  394. export interface WLEDPresets {
  395. idle: number | null;
  396. prepare: number | null;
  397. printing: number | null;
  398. paused: number | null;
  399. finished: number | null;
  400. error: number | null;
  401. queue_waiting: number | null;
  402. filament_problem: number | null;
  403. hms_error: number | null;
  404. offline: number | null;
  405. }
  406. export interface WLEDConfig {
  407. enabled: boolean;
  408. base_url: string | null;
  409. presets: WLEDPresets;
  410. finished_timeout_seconds: number | null;
  411. }
  412. export interface WLEDPreset {
  413. id: number;
  414. name: string;
  415. }
  416. export interface WLEDConnectionInfo {
  417. name: string | null;
  418. version: string | null;
  419. }
  420. export interface Printer {
  421. id: number;
  422. name: string;
  423. serial_number: string;
  424. ip_address: string;
  425. // Optional because the backend only returns access_code when the caller has
  426. // PRINTERS_UPDATE — Admin / Operator JWTs or auth-disabled mode. Viewers and
  427. // API keys receive a Printer without this field.
  428. access_code?: string;
  429. model: string | null;
  430. location: string | null; // Group/location name
  431. nozzle_count: number; // 1 or 2, auto-detected from MQTT
  432. // Model is sold with both Standard and High Flow nozzles, so a K-profile's
  433. // flow type is a real choice. Derived from the model, not the nozzle count —
  434. // only the A-series has a single variant.
  435. supports_nozzle_flow_type: boolean;
  436. is_active: boolean;
  437. auto_archive: boolean;
  438. external_camera_url: string | null;
  439. external_camera_type: string | null; // "mjpeg", "rtsp", "snapshot"
  440. external_camera_enabled: boolean;
  441. external_camera_snapshot_url: string | null; // optional single-frame override (#1177)
  442. camera_rotation: number; // 0, 90, 180, 270 degrees
  443. camera_light_auto: boolean; // picked for the chamber light when camera_light_mode is 'selected' (#1655)
  444. plate_detection_enabled: boolean; // Check plate before print
  445. plate_detection_roi?: PlateDetectionROI; // ROI for plate detection
  446. wear_cost_per_hour: number | null; // Wear cost per printing hour (#694)
  447. dispatch_priority: number | null; // Place in the pick order of any-model jobs, lowest first (#2915)
  448. wled_config: WLEDConfig | null;
  449. created_at: string;
  450. updated_at: string;
  451. }
  452. export interface HMSError {
  453. code: string;
  454. attr: number; // Attribute value for constructing wiki URL
  455. module: number;
  456. // Bambu's alert level: 1 error (task stopped), 2 warning (task paused),
  457. // 3 notification, 0 invalid (#2728).
  458. severity: number;
  459. actions?: string[]; // List of user-facing action keys (e.g. "CHECK_FILAMENT")
  460. job_id?: string; // Optional job ID for actions that require it (e.g. "CHECK_ASSISTANT")
  461. // Canonical hex identifier the firmware matches against — 8 chars for
  462. // print_error-sourced faults, 16 chars for hms[]-array-sourced faults. Send
  463. // this back as HmsActionBody.print_error so we don't truncate the 64-bit
  464. // identifier into the silent-rejection short code (#1830).
  465. full_code?: string;
  466. // The backend's catalogue sentence for this fault (#2926), from the table
  467. // generated out of Bambu Studio for this printer model (#2728). English only.
  468. // Null when Bambu publishes no text for the code. The frontend has no table of
  469. // its own: this field decides both the text and whether the fault counts.
  470. description?: string | null;
  471. }
  472. export interface HMSActionBody {
  473. print_error: string; // HMS error code (e.g. "05000070")
  474. action: string; // "HMS action to execute (e.g. 'resume_after_error')"
  475. job_id: string | null; // Optional job ID for context (if applicable)
  476. }
  477. export interface AMSTray {
  478. id: number;
  479. tray_color: string | null;
  480. tray_type: string | null;
  481. tray_sub_brands: string | null; // Full name like "PLA Basic", "PETG HF"
  482. tray_id_name: string | null; // Bambu filament ID like "A00-Y2" (can decode to color)
  483. tray_info_idx: string | null; // Filament preset ID like "GFA00" - maps to cloud setting_id
  484. remain: number;
  485. k: number | null; // Pressure advance value (from tray or K-profile lookup)
  486. cali_idx: number | null; // Calibration index for K-profile lookup
  487. tag_uid: string | null; // RFID tag UID (any tag)
  488. tray_uuid: string | null; // Bambu Lab spool UUID (32-char hex, only valid for Bambu Lab spools)
  489. nozzle_temp_min: number | null; // Min nozzle temperature
  490. nozzle_temp_max: number | null; // Max nozzle temperature
  491. drying_temp: number | null; // RFID-recommended drying temp
  492. drying_time: number | null; // RFID-recommended drying time (hours)
  493. state: number | null; // AMS tray state: 9=empty, 10=spool present not loaded, 11=loaded
  494. exists?: boolean | null; // Firmware tray_exist_bits: spool physically present (non-RFID → "?" not "Empty", #2527)
  495. }
  496. export interface AMSUnit {
  497. id: number;
  498. humidity: number | null;
  499. temp: number | null;
  500. is_ams_ht: boolean; // True for AMS-HT (single spool), False for regular AMS (4 spools)
  501. tray: AMSTray[];
  502. serial_number: string; // AMS unit serial number (from MQTT sn field)
  503. sw_ver: string; // AMS firmware version (from get_version info.module ams/* entry)
  504. dry_time: number; // Minutes remaining (0 = not drying, >0 = drying active)
  505. dry_countdown_stalled?: boolean; // Timer set but countdown not ticking (never started or paused)
  506. dry_status: number; // 0=Off, 1=Checking, 2=Drying, 3=Cooling, 4=Stopping, 5=Error
  507. dry_sub_status: number; // 0=Off, 1=Heating, 2=Dehumidify
  508. dry_sf_reason: number[]; // Cannot-dry reasons (1=InsufficientPower, 8=NeedPluginPower)
  509. dry_target_temp: number | null; // Active-cycle target °C (Bambu does not echo)
  510. dry_filament: string | null; // Active-cycle filament name we sent
  511. module_type: string; // "ams", "ams_f1", "n3f", "n3s", "n10a" (H3C AMS 3H)
  512. ams_type?: number | null; // Bambu Studio's AMS type (utils/trayIds AmsType), 6 = AMS 3H
  513. // The AMS 3H dryer: its two slots (tray ids 0-8) and that zone's humidity (%) and temperature.
  514. dryer_slots?: number[];
  515. dryer_humidity?: number | null;
  516. dryer_temp?: number | null;
  517. }
  518. export interface ScheduledDrying {
  519. id: number;
  520. printer_id: number;
  521. ams_id: number;
  522. temp: number;
  523. duration_hours: number;
  524. filament: string;
  525. rotate_tray: boolean;
  526. start_after: string | null; // UTC ISO with Z suffix, like the queue routes
  527. status: string;
  528. waiting_reason: string | null;
  529. error_message: string | null;
  530. // Why a failed run failed (screen_only / unsupported / did_not_start); null on
  531. // rows that failed before codes existed, which show error_message instead.
  532. error_code?: string | null;
  533. created_at: string;
  534. started_at: string | null;
  535. completed_at: string | null;
  536. }
  537. export interface NozzleInfo {
  538. // Two vocabularies live in this field, by printer generation. Legacy
  539. // printers (X1/P1) report the nozzle MATERIAL -- "stainless_steel",
  540. // "hardened_steel". H2-series report a FLOW code -- "HH01" (high flow),
  541. // "HS01" (standard); measured on an H2D. utils/nozzleFlow reads only the
  542. // latter and treats anything else as "unknown", which is what makes the
  543. // material spelling harmless here.
  544. nozzle_type: string;
  545. nozzle_diameter: string; // e.g., "0.4"
  546. }
  547. export interface NozzleRackSlot {
  548. id: number;
  549. nozzle_type: string;
  550. nozzle_diameter: string;
  551. wear: number | null;
  552. print_time_s?: number | null; // H2C: seconds this nozzle has printed (#1908); null when not reported
  553. stat: number | null; // Nozzle status (e.g. mounted/docked)
  554. max_temp: number;
  555. serial_number: string;
  556. filament_color: string; // RGBA hex ("00000000" = no filament)
  557. filament_id: string;
  558. filament_type: string; // Material type (e.g. "PLA", "PETG")
  559. addr_id?: number | null; // H3C: home rack position 0-8 (the mounted hotend reports id 0)
  560. }
  561. export interface PrintOptions {
  562. // Core AI detectors
  563. spaghetti_detector: boolean;
  564. print_halt: boolean;
  565. halt_print_sensitivity: string; // "low", "medium", "high" - spaghetti sensitivity
  566. first_layer_inspector: boolean;
  567. printing_monitor: boolean;
  568. buildplate_marker_detector: boolean;
  569. allow_skip_parts: boolean;
  570. // Additional AI detectors (decoded from cfg bitmask)
  571. nozzle_clumping_detector: boolean;
  572. nozzle_clumping_sensitivity: string; // "low", "medium", "high"
  573. pileup_detector: boolean;
  574. pileup_sensitivity: string; // "low", "medium", "high"
  575. airprint_detector: boolean;
  576. airprint_sensitivity: string; // "low", "medium", "high"
  577. auto_recovery_step_loss: boolean;
  578. filament_tangle_detect: boolean;
  579. }
  580. export interface FilaSwitchState {
  581. installed: boolean;
  582. // Raw wire arrays, ordered **In-B first, then In-A** (BambuStudio's SwitchPos
  583. // enum). in[] values are snow-encoded (bits 8-15 = AMS id, bits 0-7 = slot,
  584. // -1 = empty); out[] values are the extruder each *outlet* terminates at, or
  585. // 0xE when unset. Neither array says which inlet is currently routed to which
  586. // outlet — that pairing is not reported. For per-AMS side information use
  587. // PrinterStatus.ams_switch_inlet instead.
  588. in_slots: number[];
  589. out_extruders: number[];
  590. stat: number;
  591. info: number;
  592. // Whether every AMS is bound to one of the switch's two inlets. Until it is,
  593. // the switch cannot route a load anywhere and the printer has to be set up
  594. // first ("Manual AMS Setup" on its screen).
  595. ready: boolean;
  596. }
  597. // Which AMS slot one hotend is currently fed from. ams_id/slot_id are null when
  598. // the hotend holds nothing. Keyed by extruder id ('0' = right, '1' = left).
  599. // tray_now cannot answer this — it is one value for the whole printer, so on a
  600. // dual-nozzle machine it names only one of the two loaded hotends.
  601. export interface ExtruderSlot {
  602. ams_id: number | null;
  603. slot_id: number | null;
  604. has_filament: boolean;
  605. }
  606. // Which FTS inlet an AMS is plumbed into: 'A' | 'B'.
  607. export type FtsInlet = 'A' | 'B';
  608. // A video device the server can see, for a USB camera (GET /printers/usb-cameras).
  609. export interface UsbCamera {
  610. device: string;
  611. name: string;
  612. capabilities: string[];
  613. driver?: string;
  614. formats?: string[];
  615. }
  616. export interface PrinterStatus {
  617. id: number;
  618. name: string;
  619. connected: boolean;
  620. state: string | null;
  621. current_print: string | null;
  622. subtask_name: string | null;
  623. current_archive_id: number | null;
  624. current_plate_id: number | null;
  625. gcode_file: string | null;
  626. progress: number | null;
  627. remaining_time: number | null;
  628. layer_num: number | null;
  629. total_layers: number | null;
  630. temperatures: {
  631. bed?: number;
  632. bed_target?: number;
  633. bed_heating?: boolean; // Actual heater state from MQTT
  634. nozzle?: number;
  635. nozzle_target?: number;
  636. nozzle_heating?: boolean; // Actual heater state from MQTT
  637. nozzle_2?: number; // Second nozzle for H2 series (dual nozzle)
  638. nozzle_2_target?: number;
  639. nozzle_2_heating?: boolean; // Actual heater state from MQTT
  640. chamber?: number;
  641. chamber_target?: number;
  642. chamber_heating?: boolean; // Actual heater state from MQTT
  643. } | null;
  644. cover_url: string | null;
  645. hms_errors: HMSError[];
  646. // Live updates send null when no AMS is attached; the REST status sends [].
  647. ams: AMSUnit[] | null;
  648. ams_exists: boolean;
  649. vt_tray: AMSTray[]; // Virtual tray / external spool(s)
  650. store_to_sdcard: boolean; // Store sent files on SD card
  651. timelapse: boolean; // Timelapse recording active
  652. ipcam: boolean; // Live view enabled
  653. wifi_signal: number | null; // WiFi signal strength in dBm
  654. wired_network: boolean; // Ethernet connection detected
  655. door_open: boolean; // Enclosure door open (models with a door sensor: X1/X1C/X1E/X2D/P2S/H2*)
  656. // Indexed by EXTRUDER id: [0] is the right hotend, [1] the left. Measured
  657. // on an H2D with 0.4 left / 0.6 right. Read it through the helpers in
  658. // utils/amsHelpers rather than indexing it directly.
  659. nozzles: NozzleInfo[];
  660. nozzle_rack: NozzleRackSlot[]; // H2C 6-nozzle tool-changer rack
  661. print_options: PrintOptions | null; // AI detection and print options
  662. // Calibration stage tracking
  663. stg_cur: number; // Current stage number (-1 = not calibrating)
  664. stg_cur_name: string | null; // Human-readable current stage name
  665. stg: number[]; // List of stage numbers in calibration sequence
  666. // Air conditioning mode (0=cooling, 1=heating)
  667. airduct_mode: number;
  668. // Print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  669. speed_level: number;
  670. // Chamber light on/off
  671. chamber_light: boolean;
  672. // Active extruder for dual nozzle (0=right, 1=left)
  673. active_extruder: number;
  674. // AMS mapping - which AMS is connected to which nozzle
  675. // Format: [ams_id_for_nozzle0, ams_id_for_nozzle1, ...] where -1 means no AMS
  676. ams_mapping: number[];
  677. // Per-AMS extruder mapping - extracted from each AMS unit's info field
  678. // Format: {ams_id: extruder_id} where extruder 0=right, 1=left
  679. // Note: JSON keys are always strings
  680. ams_extruder_map: Record<string, number>;
  681. // Filament Track Switch accessory — null when not installed. When present,
  682. // AMS slots aren't tied to a specific extruder; the FTS routes any slot to
  683. // either extruder, so per-extruder slot filtering must be skipped.
  684. fila_switch: FilaSwitchState | null;
  685. // Per-AMS FTS inlet binding, {ams_id: 'A' | 'B'}, as set on the printer's
  686. // "Manual AMS Setup" screen. Empty unless a switch is installed. An AMS with
  687. // an entry here reaches BOTH nozzles through the switch, which is why it has
  688. // no ams_extruder_map entry and must not be badged left or right.
  689. ams_switch_inlet: Record<string, FtsInlet>;
  690. // Which AMS slot each hotend is fed from, keyed by extruder id as a string.
  691. // Empty on printers that don't report it (everything but the H2/X2 series).
  692. extruder_slots: Record<string, ExtruderSlot>;
  693. // Currently loaded tray (global tray ID, 255 = no filament loaded, 254 = external spool)
  694. tray_now: number;
  695. // The trays this print has drawn from, in order: [global tray ID, layer of the
  696. // switch]. A tray outside the job's AMS mapping is a backup spool the printer
  697. // switched to (AMS Filament Backup). Reset at the start of each print.
  698. tray_change_log?: [number, number][];
  699. // Runout / filament-replacement guidance (#2587). Populated only while PAUSED.
  700. // Global tray IDs (ams_id*4+slot, 28-36 = H3C AMS 3H, 128-135 = AMS-HT, 254 = external; utils/trayIds), matching
  701. // the same numbering as tray_now so the AMS graphic can highlight them.
  702. // expected_tray = the slot the firmware now expects filament in (null = idle,
  703. // not paused, or unresolvable → "check the printer").
  704. // previous_tray = the slot that ran out (null = unknown).
  705. expected_tray: number | null;
  706. previous_tray: number | null;
  707. // AMS status for filament change tracking (0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration)
  708. ams_status_main: number;
  709. // AMS sub-status for filament change step (when main=1): 4=retraction, 6=load verification, 7=purge
  710. ams_status_sub: number;
  711. // mc_print_sub_stage - filament change step indicator used by OrcaSlicer/BambuStudio
  712. mc_print_sub_stage: number;
  713. // Timestamp of last AMS data update (for RFID refresh detection)
  714. last_ams_update: number;
  715. // Number of printable objects in current print (for skip objects feature)
  716. printable_objects_count: number;
  717. // The next pause the slicer put into the running print (#2984). minutes is
  718. // null while the printer reports no time left yet.
  719. next_pause?: { layer: number; minutes: number | null } | null;
  720. // Fan speeds (0-100 percentage, null if not available for this model)
  721. cooling_fan_speed: number | null; // Part cooling fan
  722. big_fan1_speed: number | null; // Auxiliary fan
  723. big_fan2_speed: number | null; // Chamber/exhaust fan
  724. heatbreak_fan_speed: number | null; // Hotend heatbreak fan
  725. // Left auxiliary part cooling fan (optional P2S/X2D accessory, M106 P10).
  726. // null = not installed / not reported by this model.
  727. left_aux_fan_speed: number | null;
  728. // Chamber exhaust fan present (P2S/X2D External Exhaust Fan kit, airduct part 3).
  729. exhaust_fan_present: boolean;
  730. firmware_version: string | null; // Firmware version from MQTT
  731. // Developer LAN mode: true = enabled, false = disabled, null = unknown
  732. developer_mode: boolean | null;
  733. // AMS Filament Backup ("auto-switch" to a backup spool when one runs out).
  734. // true = ON, false = OFF, null = unknown / unsupported (A1 family).
  735. ams_filament_backup: boolean | null;
  736. // Queue: printer is awaiting user ack that the build plate was cleared after a
  737. // finished/failed print. Persisted across restarts (#961).
  738. awaiting_plate_clear: boolean;
  739. // AMS drying support
  740. supports_drying: boolean;
  741. // The AMS can dry, but only from the printer's own screen (P1 series, #2533).
  742. drying_screen_only?: boolean;
  743. // Active chamber heater (responds to M141). True only for H2C/H2D/H2DPro/H2S/X2D.
  744. supports_chamber_heater?: boolean;
  745. }
  746. export interface PrinterCreate {
  747. name: string;
  748. serial_number: string;
  749. ip_address: string;
  750. access_code: string;
  751. model?: string;
  752. location?: string | null;
  753. auto_archive?: boolean;
  754. // Maintenance Mode flag (#1476). Backend already gates MQTT, queue dispatch,
  755. // scheduler, metrics and the print picker on this; toggling via PATCH
  756. // /printers/{id} disconnects or reconnects MQTT accordingly.
  757. is_active?: boolean;
  758. external_camera_url?: string | null;
  759. external_camera_type?: string | null;
  760. external_camera_enabled?: boolean;
  761. external_camera_snapshot_url?: string | null;
  762. camera_rotation?: number;
  763. camera_light_auto?: boolean;
  764. plate_detection_enabled?: boolean;
  765. plate_detection_roi?: PlateDetectionROI;
  766. wear_cost_per_hour?: number | null;
  767. dispatch_priority?: number | null;
  768. wled_config?: WLEDConfig | null;
  769. }
  770. // Plate Detection
  771. export interface PlateDetectionROI {
  772. x: number; // X start % (0.0-1.0)
  773. y: number; // Y start % (0.0-1.0)
  774. w: number; // Width % (0.0-1.0)
  775. h: number; // Height % (0.0-1.0)
  776. }
  777. export interface PlateDetectionResult {
  778. is_empty: boolean;
  779. confidence: number;
  780. difference_percent: number;
  781. message: string;
  782. has_debug_image: boolean;
  783. debug_image_url?: string;
  784. needs_calibration: boolean;
  785. light_warning?: boolean;
  786. reference_count?: number;
  787. max_references?: number;
  788. roi?: PlateDetectionROI;
  789. }
  790. export interface PlateDetectionStatus {
  791. available: boolean;
  792. calibrated: boolean;
  793. reference_count: number;
  794. max_references: number;
  795. message: string;
  796. }
  797. export interface CalibrationResult {
  798. success: boolean;
  799. message: string;
  800. }
  801. export interface PlateReference {
  802. index: number;
  803. label: string;
  804. timestamp: string;
  805. has_image: boolean;
  806. thumbnail_url: string;
  807. }
  808. // Archive types
  809. export interface ArchiveDuplicate {
  810. id: number;
  811. print_name: string | null;
  812. created_at: string;
  813. match_type: 'exact' | 'similar'; // 'exact' = hash match, 'similar' = name match
  814. }
  815. export interface ArchivePrinterMediaFile {
  816. name: string;
  817. path: string;
  818. size: number;
  819. mtime: string | null;
  820. kind: 'timelapse' | 'ipcam';
  821. }
  822. export interface ArchivePrinterMedia {
  823. archive_id: number;
  824. printer_id: number | null;
  825. local_timelapse: { name: string; size: number } | null;
  826. remote_files: ArchivePrinterMediaFile[];
  827. warnings: Array<'printer_missing' | 'timelapse_unavailable' | 'ipcam_unavailable' | 'printer_files_forbidden'>;
  828. }
  829. /** A timelapse editor re-encode, run in the background. */
  830. export interface TimelapseJob {
  831. status: 'running' | 'completed' | 'failed' | 'cancelled';
  832. /** Share done, 0 to 1; null before ffmpeg's first report. */
  833. progress: number | null;
  834. output_path: string | null;
  835. message: string | null;
  836. error: string | null;
  837. }
  838. /** How a post-print outcome verdict reached the archive (#1898). */
  839. export type VerdictSource = 'dialog' | 'link' | 'plate_clear' | 'printer_card' | 'api' | 'reaction';
  840. export interface Archive {
  841. id: number;
  842. printer_id: number | null;
  843. project_id: number | null;
  844. project_name: string | null;
  845. filename: string;
  846. file_path: string;
  847. file_size: number;
  848. content_hash: string | null;
  849. thumbnail_path: string | null;
  850. timelapse_path: string | null;
  851. source_3mf_path: string | null;
  852. f3d_path: string | null;
  853. duplicates: ArchiveDuplicate[] | null;
  854. duplicate_count: number;
  855. duplicate_sequence: number; // 0 = original, 1+ = nth duplicate
  856. original_archive_id: number | null; // ID of the first/original archive
  857. object_count: number | null;
  858. print_name: string | null;
  859. plate_id: number | null; // Selected plate of a multi-plate 3MF (#2603)
  860. print_time_seconds: number | null;
  861. actual_time_seconds: number | null; // Computed from started_at/completed_at
  862. time_accuracy: number | null; // Percentage: 100 = perfect, >100 = faster than estimated
  863. time_estimate_seconds?: number | null; // The latest print's plate estimate, what time_accuracy compares with
  864. filament_used_grams: number | null;
  865. filament_type: string | null;
  866. filament_color: string | null;
  867. layer_height: number | null;
  868. total_layers: number | null;
  869. nozzle_diameter: number | null;
  870. bed_temperature: number | null;
  871. bed_type: string | null; // Build plate type from 3MF (e.g. "Cool Plate", "Textured PEI Plate")
  872. nozzle_temperature: number | null;
  873. sliced_for_model: string | null; // Printer model this file was sliced for
  874. status: string;
  875. started_at: string | null;
  876. completed_at: string | null;
  877. extra_data: Record<string, unknown> | null;
  878. makerworld_url: string | null;
  879. designer: string | null;
  880. external_url: string | null;
  881. is_favorite: boolean;
  882. tags: string | null;
  883. notes: string | null;
  884. cost: number | null;
  885. photos: string[] | null;
  886. failure_reason: string | null;
  887. // Post-print outcome confirmation (#1898)
  888. user_verdict: 'good' | 'reject' | null;
  889. // How the verdict arrived; 'reaction' is written by the Telegram reaction
  890. // handler (#3046) and is labelled here so it reads correctly once that lands.
  891. user_verdict_source: VerdictSource | null;
  892. user_verdict_at: string | null;
  893. confirm_requested: boolean;
  894. // The run whose outcome this shows, when it shows one run of the archive
  895. // (a plate printed on its own) rather than its latest (#1898).
  896. run_id?: number | null;
  897. // The latest print of the archive (among those the caller may see), whose
  898. // figures the per-print fields show (archive redesign).
  899. latest_run_id?: number | null;
  900. // How many videos its prints have; timelapse_path is the latest print's only.
  901. timelapse_count?: number;
  902. quantity: number;
  903. energy_kwh: number | null;
  904. energy_cost: number | null;
  905. wear_cost: number | null; // Printer wear (#694)
  906. created_at: string;
  907. // User tracking (Issue #206)
  908. created_by_id: number | null;
  909. created_by_username: string | null;
  910. // Per-archive run aggregates from PrintLogEntry (#1378)
  911. run_count: number;
  912. last_run_at: string | null;
  913. total_filament_actual_grams: number | null;
  914. successful_run_count: number;
  915. failed_run_count: number;
  916. // What all its runs cost, summed as Statistics does (#3609); null where no
  917. // run has the figure. The archive's own cost and energy stay the file's and
  918. // the first run's.
  919. total_cost?: number | null;
  920. total_energy_kwh?: number | null;
  921. total_energy_cost?: number | null;
  922. total_wear_cost?: number | null;
  923. }
  924. export interface ArchiveSlim {
  925. printer_id: number | null;
  926. print_name: string | null;
  927. print_time_seconds: number | null;
  928. actual_time_seconds: number | null;
  929. filament_used_grams: number | null;
  930. filament_type: string | null;
  931. filament_color: string | null;
  932. status: string;
  933. started_at: string | null;
  934. completed_at: string | null;
  935. cost: number | null;
  936. energy_kwh: number | null;
  937. energy_cost: number | null;
  938. wear_cost: number | null; // Printer wear (#694)
  939. quantity: number;
  940. created_at: string;
  941. }
  942. export interface PrintLogEntry {
  943. id: number;
  944. archive_id: number | null;
  945. print_name: string | null;
  946. plate_id?: number | null;
  947. printer_name: string | null;
  948. printer_id: number | null;
  949. status: string;
  950. started_at: string | null;
  951. completed_at: string | null;
  952. duration_seconds: number | null;
  953. filament_type: string | null;
  954. filament_color: string | null;
  955. filament_used_grams: number | null;
  956. cost: number | null;
  957. energy_kwh: number | null;
  958. energy_cost: number | null;
  959. wear_cost: number | null; // Printer wear (#694)
  960. failure_reason: string | null;
  961. user_verdict?: 'good' | 'reject' | null;
  962. user_verdict_source?: string | null;
  963. confirm_requested?: boolean | null;
  964. duration_unmeasured?: boolean | null;
  965. quantity?: number | null;
  966. // This print's own (archive redesign): note, finish photos, video.
  967. notes?: string | null;
  968. photos?: string[] | null;
  969. timelapse_path?: string | null;
  970. // The slicer's estimate for the plate it printed; in an archive's runs list.
  971. estimate_seconds?: number | null;
  972. estimate_grams?: number | null;
  973. thumbnail_path: string | null;
  974. created_by_id: number | null;
  975. created_by_username: string | null;
  976. created_at: string;
  977. }
  978. export interface PrintLogResponse {
  979. items: PrintLogEntry[];
  980. total: number;
  981. // The print log only: archives of its prints that were deleted.
  982. deleted_archive_ids?: number[];
  983. }
  984. export interface ArchiveStats {
  985. total_prints: number;
  986. successful_prints: number;
  987. failed_prints: number;
  988. cancelled_prints: number;
  989. total_print_time_hours: number;
  990. total_filament_grams: number;
  991. total_cost: number;
  992. prints_by_filament_type: Record<string, number>;
  993. prints_by_printer: Record<string, number>;
  994. // Name each printer id was last recorded under in the print log, so history
  995. // belonging to a deleted printer keeps its label.
  996. printer_names?: Record<string, string>;
  997. average_time_accuracy: number | null;
  998. time_accuracy_by_printer: Record<string, number> | null;
  999. total_energy_kwh: number;
  1000. total_energy_cost: number;
  1001. total_wear_cost: number; // Printer wear (#694)
  1002. // True when a date-filtered total-consumption query is running on incomplete
  1003. // snapshot history (e.g. right after upgrade, before hourly snapshots have
  1004. // a baseline). UI should explain why the number may undercount.
  1005. energy_data_warming_up?: boolean;
  1006. }
  1007. export interface TagInfo {
  1008. name: string;
  1009. count: number;
  1010. }
  1011. export interface FailureAnalysis {
  1012. period_days: number;
  1013. total_prints: number;
  1014. failed_prints: number;
  1015. failure_rate: number;
  1016. // Quality dimension (#1898): completed prints the user rejected. Optional
  1017. // so a frontend build against an older backend degrades gracefully.
  1018. rejected_prints?: number;
  1019. yield_rate?: number;
  1020. rejects_by_reason?: Record<string, number>;
  1021. failures_by_reason: Record<string, number>;
  1022. failures_by_filament: Record<string, number>;
  1023. failures_by_printer: Record<string, number>;
  1024. failures_by_hour: Record<number, number>;
  1025. recent_failures: Array<{
  1026. id: number;
  1027. print_name: string;
  1028. failure_reason: string | null;
  1029. filament_type: string | null;
  1030. printer_id: number | null;
  1031. created_at: string | null;
  1032. }>;
  1033. trend: Array<{
  1034. week_start: string;
  1035. total_prints: number;
  1036. failed_prints: number;
  1037. failure_rate: number;
  1038. }>;
  1039. }
  1040. /**
  1041. * Send the browser's zone with calendar dates: the server reads a date as a
  1042. * day in it, else in its own TZ, which shifted every day for a browser away
  1043. * from the server (DB-C12). Only when a date is set.
  1044. */
  1045. function addDayZone(params: URLSearchParams): void {
  1046. if (!params.has('date_from') && !params.has('date_to')) return;
  1047. try {
  1048. const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
  1049. if (zone) params.set('tz', zone);
  1050. } catch {
  1051. // No Intl zone: the server's TZ applies.
  1052. }
  1053. }
  1054. export interface BulkUploadResult {
  1055. uploaded: number;
  1056. failed: number;
  1057. /** `index` is the file's position in the request. */
  1058. results: Array<{ index: number; filename: string; id: number; status: string }>;
  1059. errors: Array<{ index: number; filename: string; error: string }>;
  1060. }
  1061. // Archive Comparison types
  1062. export interface ComparisonArchiveInfo {
  1063. id: number;
  1064. print_name: string;
  1065. status: string;
  1066. created_at: string | null;
  1067. printer_id: number | null;
  1068. project_name: string | null;
  1069. }
  1070. export interface ComparisonField {
  1071. field: string;
  1072. label: string;
  1073. unit: string | null;
  1074. values: (string | number | null)[];
  1075. raw_values: (string | number | null)[];
  1076. has_difference: boolean;
  1077. }
  1078. export interface SuccessCorrelationInsight {
  1079. field: string;
  1080. label: string;
  1081. insight: string;
  1082. success_avg?: number;
  1083. failed_avg?: number;
  1084. success_values?: string[];
  1085. failed_values?: string[];
  1086. }
  1087. export interface SuccessCorrelation {
  1088. has_both_outcomes: boolean;
  1089. message?: string;
  1090. successful_count?: number;
  1091. failed_count?: number;
  1092. insights?: SuccessCorrelationInsight[];
  1093. }
  1094. export interface ArchiveComparison {
  1095. archives: ComparisonArchiveInfo[];
  1096. comparison: ComparisonField[];
  1097. differences: ComparisonField[];
  1098. success_correlation: SuccessCorrelation;
  1099. }
  1100. // Project types
  1101. export interface ProjectStats {
  1102. total_archives: number;
  1103. total_items: number; // Sum of quantities (total items printed)
  1104. completed_prints: number; // Sum of quantities for completed prints (parts)
  1105. failed_prints: number;
  1106. queued_prints: number;
  1107. in_progress_prints: number;
  1108. total_print_time_hours: number;
  1109. total_filament_grams: number;
  1110. progress_percent: number | null; // Plates progress (total_archives / target_count)
  1111. parts_progress_percent: number | null; // Parts progress (completed_prints / target_parts_count)
  1112. estimated_cost: number;
  1113. total_energy_kwh: number;
  1114. total_energy_cost: number;
  1115. total_wear_cost: number; // Printer wear (#694)
  1116. remaining_prints: number | null; // Remaining plates
  1117. remaining_parts: number | null; // Remaining parts
  1118. bom_total_items: number;
  1119. bom_completed_items: number;
  1120. bom_cost: number;
  1121. }
  1122. // A sub-project as listed on its parent's page. The figures cover the child's
  1123. // own subtree, so the listed rows add up to the parent's roll-up minus the
  1124. // parent's own prints (#1264).
  1125. export interface ProjectChildPreview {
  1126. id: number;
  1127. name: string;
  1128. color: string | null;
  1129. status: string;
  1130. progress_percent: number | null;
  1131. descendant_count: number;
  1132. total_archives: number;
  1133. completed_prints: number;
  1134. total_print_time_hours: number;
  1135. total_filament_grams: number;
  1136. total_cost: number; // Filament + energy + BOM, matching the parent's cost card
  1137. }
  1138. export interface Project {
  1139. id: number;
  1140. name: string;
  1141. description: string | null;
  1142. color: string | null;
  1143. status: string; // active, completed, archived
  1144. target_count: number | null; // Target number of plates/print jobs
  1145. target_parts_count: number | null; // Target number of parts/objects
  1146. target_sets: number | null; // Copies-per-file target (#1897)
  1147. notes: string | null;
  1148. attachments: ProjectAttachment[] | null;
  1149. tags: string | null;
  1150. due_date: string | null;
  1151. priority: string; // low, normal, high, urgent
  1152. budget: number | null;
  1153. is_template: boolean;
  1154. template_source_id: number | null;
  1155. parent_id: number | null;
  1156. parent_name: string | null;
  1157. children: ProjectChildPreview[];
  1158. descendant_count: number; // Sub-projects at any depth beneath this one (#1264)
  1159. created_at: string;
  1160. updated_at: string;
  1161. stats?: ProjectStats;
  1162. // This project's numbers combined with every sub-project's. Null when there
  1163. // are none, since it would only repeat `stats` (#1264).
  1164. rollup_stats?: ProjectStats | null;
  1165. url: string | null; // External link rendered next to project name on the card (#1155)
  1166. cover_image_filename: string | null; // Filename within project attachments dir (#1155)
  1167. }
  1168. export interface ProjectAttachment {
  1169. filename: string;
  1170. original_name: string;
  1171. size: number;
  1172. uploaded_at: string;
  1173. }
  1174. // Completed-run count for one library file inside a project (#1897)
  1175. export interface ProjectFileProgress {
  1176. file_id: number;
  1177. completed_count: number;
  1178. }
  1179. export interface ArchivePreview {
  1180. id: number;
  1181. print_name: string | null;
  1182. thumbnail_path: string | null;
  1183. status: string;
  1184. filament_type: string | null;
  1185. filament_color: string | null;
  1186. }
  1187. export interface ProjectListItem {
  1188. id: number;
  1189. name: string;
  1190. description: string | null;
  1191. color: string | null;
  1192. status: string;
  1193. target_count: number | null; // Target number of plates/print jobs
  1194. target_parts_count: number | null; // Target number of parts/objects
  1195. target_sets: number | null; // #1897 — the shared edit dialog seeds itself from this
  1196. budget: number | null;
  1197. tags: string | null; // #2536 — the shared edit dialog seeds itself from this
  1198. due_date: string | null; // #2536
  1199. priority: string; // #2536
  1200. created_at: string;
  1201. archive_count: number; // Number of print jobs (plates)
  1202. total_items: number; // Sum of quantities (total items printed, including failed)
  1203. completed_count: number; // Sum of quantities for completed prints only (parts)
  1204. failed_count: number; // Sum of quantities for failed prints
  1205. queue_count: number;
  1206. progress_percent: number | null; // Plates progress
  1207. parent_id: number | null; // #1264 — set when this is a sub-project
  1208. child_count: number; // #1264 — direct sub-projects only
  1209. archives: ArchivePreview[];
  1210. url: string | null; // #1155
  1211. cover_image_filename: string | null; // #1155
  1212. }
  1213. export interface ProjectCreate {
  1214. name: string;
  1215. description?: string;
  1216. color?: string;
  1217. target_count?: number;
  1218. target_parts_count?: number;
  1219. target_sets?: number;
  1220. notes?: string;
  1221. tags?: string;
  1222. due_date?: string;
  1223. priority?: string;
  1224. budget?: number | null;
  1225. parent_id?: number;
  1226. url?: string | null; // #1155
  1227. }
  1228. export interface ProjectUpdate {
  1229. name?: string;
  1230. description?: string;
  1231. color?: string;
  1232. status?: string;
  1233. target_count?: number;
  1234. target_parts_count?: number;
  1235. target_sets?: number | null; // #1897 — explicit null clears the copies-per-file target
  1236. notes?: string;
  1237. tags?: string | null; // #2536 — explicit null clears the tags
  1238. due_date?: string | null; // #2536 — explicit null clears the due date
  1239. priority?: string;
  1240. budget?: number | null;
  1241. parent_id?: number;
  1242. url?: string | null; // #1155 — explicit null clears the URL
  1243. }
  1244. // BOM Types - Tracks sourced/purchased parts (hardware, electronics, etc.)
  1245. export interface BOMItem {
  1246. id: number;
  1247. project_id: number;
  1248. name: string;
  1249. quantity_needed: number;
  1250. quantity_acquired: number;
  1251. unit_price: number | null;
  1252. sourcing_url: string | null;
  1253. archive_id: number | null;
  1254. archive_name: string | null;
  1255. stl_filename: string | null;
  1256. remarks: string | null;
  1257. sort_order: number;
  1258. is_complete: boolean;
  1259. created_at: string;
  1260. updated_at: string;
  1261. }
  1262. export interface BOMItemCreate {
  1263. name: string;
  1264. quantity_needed?: number;
  1265. unit_price?: number;
  1266. sourcing_url?: string;
  1267. archive_id?: number;
  1268. stl_filename?: string;
  1269. remarks?: string;
  1270. }
  1271. export interface BOMItemUpdate {
  1272. name?: string;
  1273. quantity_needed?: number;
  1274. quantity_acquired?: number;
  1275. unit_price?: number;
  1276. sourcing_url?: string;
  1277. archive_id?: number;
  1278. stl_filename?: string;
  1279. remarks?: string;
  1280. }
  1281. // Project Export/Import Types
  1282. export interface BOMItemExport {
  1283. name: string;
  1284. quantity_needed: number;
  1285. quantity_acquired: number;
  1286. unit_price: number | null;
  1287. sourcing_url: string | null;
  1288. stl_filename: string | null;
  1289. remarks: string | null;
  1290. }
  1291. export interface LinkedFolderExport {
  1292. name: string;
  1293. }
  1294. export interface ProjectExport {
  1295. name: string;
  1296. description: string | null;
  1297. color: string | null;
  1298. status: string;
  1299. target_count: number | null;
  1300. target_parts_count: number | null;
  1301. target_sets: number | null; // #1897
  1302. notes: string | null;
  1303. tags: string | null;
  1304. due_date: string | null;
  1305. priority: string;
  1306. budget: number | null;
  1307. bom_items: BOMItemExport[];
  1308. linked_folders: LinkedFolderExport[];
  1309. }
  1310. export interface ProjectImport {
  1311. name: string;
  1312. description?: string;
  1313. color?: string;
  1314. status?: string;
  1315. target_count?: number;
  1316. target_parts_count?: number;
  1317. target_sets?: number; // #1897
  1318. notes?: string;
  1319. tags?: string;
  1320. due_date?: string;
  1321. priority?: string;
  1322. budget?: number | null;
  1323. bom_items?: BOMItemExport[];
  1324. linked_folders?: LinkedFolderExport[];
  1325. }
  1326. // Timeline Types
  1327. export interface TimelineEvent {
  1328. event_type: string;
  1329. timestamp: string;
  1330. title: string;
  1331. description: string | null;
  1332. metadata: Record<string, unknown> | null;
  1333. }
  1334. // API Key types
  1335. export interface APIKey {
  1336. id: number;
  1337. name: string;
  1338. key_prefix: string;
  1339. user_id: number | null; // Owner; null on legacy keys created before per-user ownership (#1182)
  1340. can_queue: boolean;
  1341. can_control_printer: boolean;
  1342. can_read_status: boolean;
  1343. can_manage_library: boolean;
  1344. can_manage_inventory: boolean;
  1345. can_manage_maintenance: boolean;
  1346. can_manage_archives: boolean;
  1347. can_manage_projects: boolean;
  1348. can_access_cloud: boolean;
  1349. can_update_energy_cost: boolean;
  1350. can_send_notifications: boolean;
  1351. printer_ids: number[] | null;
  1352. enabled: boolean;
  1353. last_used: string | null;
  1354. created_at: string;
  1355. expires_at: string | null;
  1356. }
  1357. export interface APIKeyCreate {
  1358. name: string;
  1359. can_queue?: boolean;
  1360. can_control_printer?: boolean;
  1361. can_read_status?: boolean;
  1362. can_manage_library?: boolean;
  1363. can_manage_inventory?: boolean;
  1364. can_manage_maintenance?: boolean;
  1365. can_manage_archives?: boolean;
  1366. can_manage_projects?: boolean;
  1367. can_access_cloud?: boolean;
  1368. can_update_energy_cost?: boolean;
  1369. can_send_notifications?: boolean;
  1370. printer_ids?: number[] | null;
  1371. expires_at?: string | null;
  1372. }
  1373. export interface APIKeyCreateResponse extends APIKey {
  1374. key: string; // Full key, only shown on creation
  1375. }
  1376. /**
  1377. * Tri-state calibration option (BambuStudio parity): "off" never runs it,
  1378. * "on" forces it every print, "auto" lets the printer skip it if it was done
  1379. * recently. Used by bed_levelling, flow_cali, and nozzle_offset_cali.
  1380. */
  1381. export type CalibrationMode = 'off' | 'on' | 'auto';
  1382. // Settings types
  1383. export type ModelDispatchOrder = 'fewest_hours' | 'most_hours' | 'least_recently_used' | 'priority';
  1384. export interface AppSettings {
  1385. auto_archive: boolean;
  1386. save_thumbnails: boolean;
  1387. capture_finish_photo: boolean;
  1388. finish_photo_restore_plate: boolean;
  1389. default_filament_cost: number;
  1390. currency: string;
  1391. energy_cost_per_kwh: number;
  1392. energy_tracking_mode: 'print' | 'total';
  1393. // Where the electricity price comes from (#1251). With 'homeassistant',
  1394. // energy_cost_per_kwh holds the sensor's last reading and is read-only.
  1395. energy_price_source: 'fixed' | 'homeassistant';
  1396. energy_price_ha_entity: string;
  1397. check_updates: boolean;
  1398. check_printer_firmware: boolean;
  1399. include_beta_updates: boolean;
  1400. // Announcements from the Bambuddy maintainers (a signed file on GitHub).
  1401. announcements_enabled?: boolean;
  1402. announcements_all_users?: boolean;
  1403. // #1589: false hides the local username/password form on the login page;
  1404. // BAMBUDDY_LOCAL_LOGIN=true on the server flips the reported value back to
  1405. // true so the env-var recovery path is visible to the SPA.
  1406. local_login_enabled: boolean;
  1407. language: string;
  1408. notification_language: string;
  1409. // AMS threshold settings
  1410. ams_humidity_good: number; // <= this is green
  1411. ams_humidity_fair: number; // <= this is orange, > is red
  1412. ams_temp_good: number; // <= this is green/blue
  1413. ams_temp_fair: number; // <= this is orange, > is red
  1414. // Separate from the display band (#2905). null = unset, which the backend
  1415. // resolves to ams_temp_fair so existing installs are unaffected.
  1416. ams_temp_alarm: number | null;
  1417. ams_history_retention_days: number; // days to keep AMS sensor history
  1418. printer_sensor_history_retention_days?: number; // days to keep printer heater history
  1419. // Queue auto-drying settings
  1420. queue_drying_enabled: boolean; // Auto-dry AMS between queued prints
  1421. queue_drying_block: boolean; // Block queue until drying completes
  1422. ambient_drying_enabled: boolean; // Auto-dry idle printers based on humidity regardless of queue
  1423. ambient_drying_sustained_minutes: number; // Minutes humidity must stay above threshold before ambient auto-dry starts (0 = instant)
  1424. print_drying_enabled: boolean; // Continue drying while a print is running on capable hardware
  1425. drying_presets: string; // JSON blob of drying presets per filament type
  1426. ams_humidity_thresholds: string; // JSON blob of per-filament humidity thresholds (#1605)
  1427. gcode_snippets: string; // JSON: per-model G-code injection snippets
  1428. // Scheduled local backup
  1429. local_backup_enabled: boolean;
  1430. local_backup_schedule: string;
  1431. local_backup_time: string;
  1432. local_backup_retention: number;
  1433. local_backup_path: string;
  1434. // Print modal settings
  1435. per_printer_mapping_expanded: boolean; // Whether custom mapping is expanded by default in print modal
  1436. // Date/time format settings
  1437. date_format: 'system' | 'us' | 'eu' | 'iso';
  1438. time_format: 'system' | '12h' | '24h';
  1439. // Filament tracking
  1440. disable_filament_warnings: boolean; // Disable filament warnings (print insufficiency and assignment mismatch)
  1441. prefer_lowest_filament: boolean; // When multiple spools match, prefer lowest remaining filament
  1442. 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
  1443. 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
  1444. spoolman_url: string;
  1445. // Default printer
  1446. default_printer_id: number | null;
  1447. pipeline_max_copies: number;
  1448. // Dark mode theme settings
  1449. dark_style: 'classic' | 'glow' | 'vibrant';
  1450. dark_background: 'neutral' | 'warm' | 'cool' | 'oled' | 'slate' | 'forest';
  1451. dark_accent: 'green' | 'teal' | 'blue' | 'orange' | 'purple' | 'red';
  1452. // Light mode theme settings
  1453. light_style: 'classic' | 'glow' | 'vibrant';
  1454. light_background: 'neutral' | 'warm' | 'cool';
  1455. light_accent: 'green' | 'teal' | 'blue' | 'orange' | 'purple' | 'red';
  1456. // FTP retry settings
  1457. ftp_retry_enabled: boolean;
  1458. ftp_retry_count: number;
  1459. ftp_retry_delay: number;
  1460. ftp_timeout: number;
  1461. // MQTT relay settings
  1462. mqtt_enabled: boolean;
  1463. mqtt_broker: string;
  1464. mqtt_port: number;
  1465. mqtt_username: string;
  1466. mqtt_password: string;
  1467. mqtt_topic_prefix: string;
  1468. mqtt_use_tls: boolean;
  1469. // External URL for notifications
  1470. external_url: string;
  1471. // Directory holding docker-compose.yml, shown in the update instructions (#2664)
  1472. docker_compose_dir: string;
  1473. // Home Assistant integration
  1474. ha_enabled: boolean;
  1475. ha_url: string;
  1476. ha_token: string;
  1477. ha_url_from_env: boolean;
  1478. ha_token_from_env: boolean;
  1479. ha_env_managed: boolean;
  1480. // File Manager / Library settings
  1481. library_disk_warning_gb: number;
  1482. // Camera view settings
  1483. camera_view_mode: 'window' | 'embedded';
  1484. // Chamber light while the camera is in use (#1655)
  1485. camera_light_mode: 'off' | 'all' | 'selected';
  1486. camera_light_delay: number; // seconds a snapshot waits after the light came on
  1487. // Preferred slicer (server-side API / sidecar)
  1488. preferred_slicer: 'bambu_studio' | 'orcaslicer';
  1489. // Desktop "Open in Slicer" override (#1329). Null inherits from
  1490. // preferred_slicer so existing installs behave identically.
  1491. open_in_slicer: 'bambu_studio' | 'orcaslicer' | null;
  1492. // Where slicing runs, independent of which slicer binary the sidecar drives.
  1493. // Only 'sidecar' is implemented today; see lib/sliceEngines.ts.
  1494. slice_engine: 'sidecar' | 'browser';
  1495. // Use the slicer-API sidecar for slicing (in-app modal) vs desktop URI scheme
  1496. use_slicer_api: boolean;
  1497. // Per-install sidecar URLs. Empty string falls back to the env defaults.
  1498. orcaslicer_api_url: string;
  1499. bambu_studio_api_url: string;
  1500. // Minutes of silence from the sidecar before a slice is abandoned. Bounds
  1501. // stalls, not total slicing time — a model that keeps reporting progress
  1502. // runs to completion however long it takes.
  1503. slicer_stall_timeout_minutes: number;
  1504. // Prometheus metrics
  1505. prometheus_enabled: boolean;
  1506. prometheus_token: string;
  1507. // Bed cooled threshold
  1508. bed_cooled_threshold: number;
  1509. // Minutes before a slicer pause to send the pause heads-up (#2984)
  1510. pause_warning_minutes: number;
  1511. // Inventory low stock threshold
  1512. low_stock_threshold: number;
  1513. // Session policy (#1706) — admin-set ceiling, hours, [1, 720]
  1514. session_max_hours: number;
  1515. // User email notifications toggle
  1516. user_notifications_enabled: boolean;
  1517. // Default print options
  1518. default_bed_levelling: CalibrationMode;
  1519. default_flow_cali: CalibrationMode;
  1520. default_vibration_cali: boolean;
  1521. default_layer_inspect: boolean;
  1522. default_timelapse: boolean;
  1523. default_nozzle_offset_cali: CalibrationMode;
  1524. // Default for the per-job "ask for outcome afterwards" toggle (#1898)
  1525. default_confirm_outcome: boolean;
  1526. // Also ask for prints Bambuddy archived but did not dispatch (#1898)
  1527. confirm_outcome_external_prints: boolean;
  1528. // Count unanswered outcome prompts as "good" when the plate is released (#1898)
  1529. confirm_default_good_on_plate_clear: boolean;
  1530. // Staggered batch start defaults
  1531. stagger_group_size: number;
  1532. stagger_interval_minutes: number;
  1533. // Finance budget reset window
  1534. billing_enabled: boolean;
  1535. printer_kill_switch_enabled: boolean;
  1536. finance_budget_reset_day: number;
  1537. finance_budget_reset_timezone: string;
  1538. // Plate-clear confirmation
  1539. require_plate_clear: boolean;
  1540. // Shortest job first scheduling
  1541. queue_shortest_first: boolean;
  1542. // Which printer an any-model job takes when several can run it (#2915).
  1543. model_dispatch_order: ModelDispatchOrder;
  1544. // How many printers the queue may upload to at once (#2555). 1 restores the
  1545. // old strictly-serial behaviour, where every printer waited out every other
  1546. // printer's transfer.
  1547. queue_max_concurrent_uploads: number;
  1548. // Preheat / heat-soak before queued prints (#1468). Master toggle is the
  1549. // default for new queue items; per-item PrintQueueItem.preheat_override can
  1550. // flip the decision per print. Chamber target derives from the loaded AMS
  1551. // filament types via preheat_filament_targets (JSON map of type → °C, max
  1552. // across loaded slots); the per-item override field bypasses derivation.
  1553. preheat_enabled: boolean;
  1554. preheat_filament_targets: string;
  1555. preheat_max_wait_seconds: number;
  1556. preheat_soak_seconds: number;
  1557. queue_keep_bed_warm: boolean;
  1558. queue_keep_warm_bed_temp: number;
  1559. queue_keep_warm_max_minutes: number;
  1560. // User-configurable presets for the printer-card popovers (JSON arrays of 3 ints).
  1561. // Empty string = use built-in defaults.
  1562. nozzle_temp_presets: string;
  1563. bed_temp_presets: string;
  1564. chamber_temp_presets: string;
  1565. fan_speed_presets: string;
  1566. // Default sidebar order (admin-set for all users)
  1567. default_sidebar_order: string;
  1568. // LDAP authentication
  1569. ldap_enabled: boolean;
  1570. ldap_server_url: string;
  1571. ldap_bind_dn: string;
  1572. ldap_bind_password: string;
  1573. ldap_search_base: string;
  1574. ldap_user_filter: string;
  1575. ldap_security: string;
  1576. ldap_group_mapping: string;
  1577. ldap_auto_provision: boolean;
  1578. ldap_default_group: string;
  1579. obico_enabled: boolean;
  1580. obico_ml_url: string;
  1581. bambuddy_internal_url: string;
  1582. obico_ml_token: string;
  1583. obico_sensitivity: 'low' | 'medium' | 'high';
  1584. obico_action: 'notify' | 'pause' | 'pause_and_off';
  1585. obico_poll_interval: number;
  1586. obico_enabled_printers: string;
  1587. octoeverywhere_enabled: boolean;
  1588. octoeverywhere_api_key: string;
  1589. octoeverywhere_api_key_configured: boolean;
  1590. octoeverywhere_confidence: OctoEverywhereConfidence;
  1591. octoeverywhere_action: 'notify' | 'pause' | 'pause_and_off';
  1592. octoeverywhere_enabled_printers: string;
  1593. octoeverywhere_poll_interval: number;
  1594. // Inventory forecasting global lead time
  1595. forecast_global_lead_time_days: number;
  1596. location_sensor_poll_interval: number;
  1597. // JSON map of sensor category → {alertAbove, alertBelow, notifyOnAlert},
  1598. // seeding new storage-location sensor bindings. Empty = built-in defaults.
  1599. // Server-backed so two admins seed the same alert rules and a restore
  1600. // brings them back; see utils/locationSensorDefaults.ts.
  1601. location_sensor_alert_defaults: string;
  1602. }
  1603. export type AppSettingsUpdate = Partial<Omit<AppSettings, 'octoeverywhere_api_key_configured'>>;
  1604. // Settings as a page sees them: everything from GET /settings for a user who
  1605. // may read it, otherwise the subset /settings/ui-preferences and
  1606. // /settings/ui-flags serve, which reports G-code snippets only as set or not.
  1607. export type UiSettings = Partial<AppSettings> & { has_gcode_snippets?: boolean };
  1608. // MQTT relay status
  1609. export interface MQTTStatus {
  1610. enabled: boolean;
  1611. connected: boolean;
  1612. broker: string;
  1613. port: number;
  1614. topic_prefix: string;
  1615. }
  1616. // Cloud types
  1617. export interface CloudAuthStatus {
  1618. is_authenticated: boolean;
  1619. email: string | null;
  1620. region?: 'global' | 'china' | null;
  1621. /** A token is stored but Bambu no longer accepts it — tell the user why the login form is back. */
  1622. sign_in_expired?: boolean;
  1623. }
  1624. export interface CloudLoginResponse {
  1625. success: boolean;
  1626. needs_verification: boolean;
  1627. message: string;
  1628. verification_type?: 'email' | 'totp' | null;
  1629. tfa_key?: string | null;
  1630. /**
  1631. * Machine-readable cause of a failure. 'captcha' means Bambu's anti-abuse
  1632. * layer is challenging this network and no credential will be accepted until
  1633. * it clears — the UI must explain that in place rather than toast `message`.
  1634. */
  1635. reason?: 'captcha' | string | null;
  1636. }
  1637. // Orca Cloud types — paste-flow PKCE handshake against auth.orcaslicer.com.
  1638. // See backend/app/services/orca_cloud.py for the deep dive on why this
  1639. // flow is paste-based rather than callback-based.
  1640. export interface OrcaDeviceStartResponse {
  1641. user_code: string;
  1642. verification_uri: string;
  1643. verification_uri_complete: string;
  1644. interval: number;
  1645. expires_in: number;
  1646. }
  1647. export type OrcaDevicePollStatus =
  1648. | 'authorization_pending'
  1649. | 'slow_down'
  1650. | 'access_denied'
  1651. | 'expired_token'
  1652. | 'complete';
  1653. export interface OrcaDevicePollResponse {
  1654. status: OrcaDevicePollStatus;
  1655. connected: boolean;
  1656. email: string | null;
  1657. user_id: string | null;
  1658. }
  1659. export interface OrcaAuthStatusResponse {
  1660. connected: boolean;
  1661. email: string | null;
  1662. user_id: string | null;
  1663. }
  1664. // Orca profiles are shaped to match Bambu Cloud's SlicerSetting on the wire
  1665. // so the frontend can use the same visual components for both surfaces (cards,
  1666. // grouped sections, filter bar). Backend handles the source-specific
  1667. // transformation in routes/orca_cloud.py::_orca_to_setting.
  1668. export interface OrcaProfileMeta {
  1669. setting_id: string;
  1670. name: string;
  1671. type: string;
  1672. version: string | null;
  1673. user_id: string | null;
  1674. updated_time: string | null;
  1675. is_custom: boolean;
  1676. }
  1677. export interface OrcaProfileListResponse {
  1678. filament: OrcaProfileMeta[];
  1679. printer: OrcaProfileMeta[];
  1680. process: OrcaProfileMeta[];
  1681. }
  1682. export interface OrcaProfileDetail {
  1683. setting_id: string;
  1684. name: string;
  1685. type: string;
  1686. version: string | null;
  1687. base_id: string | null;
  1688. update_time: string | null;
  1689. setting: Record<string, unknown>;
  1690. }
  1691. // MakerWorld integration. Full metadata/instance shapes come back as
  1692. // Record<string, unknown> — MakerWorld's API adds fields over time, so we
  1693. // pass them through verbatim rather than maintaining a brittle mirror.
  1694. export interface MakerworldStatus {
  1695. has_cloud_token: boolean;
  1696. can_download: boolean;
  1697. /** A token is stored but Bambu rejected it — downloads will fail until the user signs in again. */
  1698. sign_in_expired?: boolean;
  1699. }
  1700. export interface MakerworldResolvedModel {
  1701. model_id: number;
  1702. profile_id: number | null;
  1703. design: Record<string, unknown>;
  1704. instances: Array<Record<string, unknown>>;
  1705. already_imported_library_ids: number[];
  1706. }
  1707. export interface MakerworldImportResponse {
  1708. library_file_id: number;
  1709. filename: string;
  1710. folder_id: number | null;
  1711. profile_id: number | null;
  1712. was_existing: boolean;
  1713. }
  1714. export interface MakerworldRecentImport {
  1715. library_file_id: number;
  1716. filename: string;
  1717. folder_id: number | null;
  1718. thumbnail_path: string | null;
  1719. source_url: string | null;
  1720. created_at: string;
  1721. }
  1722. // Manyfold integration (#1471): a self-hosted model library, browsed and
  1723. // searched, with single files imported into the library.
  1724. export interface ManyfoldConfig {
  1725. url: string;
  1726. client_id: string;
  1727. /** The secret itself is never returned. */
  1728. has_client_secret: boolean;
  1729. configured: boolean;
  1730. }
  1731. export interface ManyfoldConfigInput {
  1732. url: string;
  1733. client_id: string;
  1734. /** Empty or left out keeps the stored secret. */
  1735. client_secret?: string;
  1736. }
  1737. export interface ManyfoldStatus {
  1738. configured: boolean;
  1739. url: string;
  1740. }
  1741. export interface ManyfoldModelSummary {
  1742. id: string;
  1743. name: string;
  1744. }
  1745. export interface ManyfoldModelList {
  1746. total: number;
  1747. page: number;
  1748. has_next: boolean;
  1749. has_previous: boolean;
  1750. models: ManyfoldModelSummary[];
  1751. }
  1752. export interface ManyfoldFile {
  1753. id: string;
  1754. name: string;
  1755. mime: string;
  1756. importable: boolean;
  1757. /** Set while the file imported earlier is still in the library. */
  1758. library_file: { id: number; filename: string; folder_id: number | null } | null;
  1759. }
  1760. export interface ManyfoldModel {
  1761. id: string;
  1762. name: string;
  1763. caption: string | null;
  1764. description: string | null;
  1765. license: string | null;
  1766. tags: string[];
  1767. url: string;
  1768. has_preview: boolean;
  1769. files: ManyfoldFile[];
  1770. }
  1771. export interface ManyfoldImportResponse {
  1772. library_file_id: number;
  1773. filename: string;
  1774. folder_id: number | null;
  1775. was_existing: boolean;
  1776. }
  1777. export interface SlicerSetting {
  1778. setting_id: string;
  1779. name: string;
  1780. type: string;
  1781. version: string | null;
  1782. user_id: string | null;
  1783. updated_time: string | null;
  1784. is_custom: boolean;
  1785. // The id Bambu Studio puts in an AMS slot for the preset; not derivable
  1786. // from setting_id for every preset (#3387). Absent from older backends.
  1787. filament_id?: string | null;
  1788. }
  1789. export interface SpoolCatalogEntry {
  1790. id: number;
  1791. name: string;
  1792. weight: number;
  1793. is_default: boolean;
  1794. }
  1795. export interface StorageLocation {
  1796. id: number;
  1797. name: string;
  1798. identifier: string | null;
  1799. spool_count: number;
  1800. created_at: string;
  1801. updated_at: string;
  1802. }
  1803. export interface ColorCatalogEntry {
  1804. id: number;
  1805. manufacturer: string;
  1806. color_name: string;
  1807. hex_color: string;
  1808. material: string | null;
  1809. is_default: boolean;
  1810. // #1154: optional multi-colour gradient stops + visual effect.
  1811. extra_colors?: string | null;
  1812. effect_type?: string | null;
  1813. }
  1814. export interface SlicerSettingsResponse {
  1815. filament: SlicerSetting[];
  1816. printer: SlicerSetting[];
  1817. process: SlicerSetting[];
  1818. }
  1819. export interface SlicerSettingDetail {
  1820. message?: string | null;
  1821. code?: string | null;
  1822. error?: string | null;
  1823. public: boolean;
  1824. version?: string | null;
  1825. type: string;
  1826. name: string;
  1827. update_time?: string | null;
  1828. nickname?: string | null;
  1829. base_id?: string | null;
  1830. setting: Record<string, unknown>;
  1831. filament_id?: string | null;
  1832. setting_id?: string | null;
  1833. }
  1834. export interface SlicerSettingCreate {
  1835. type: string; // 'filament', 'print', or 'printer'
  1836. name: string;
  1837. base_id: string;
  1838. setting: Record<string, unknown>;
  1839. }
  1840. export interface SlicerSettingUpdate {
  1841. name?: string;
  1842. setting?: Record<string, unknown>;
  1843. }
  1844. export interface SlicerSettingDeleteResponse {
  1845. success: boolean;
  1846. message: string;
  1847. }
  1848. // Built-in filament fallback (static table from backend)
  1849. export interface BuiltinFilament {
  1850. filament_id: string;
  1851. name: string;
  1852. }
  1853. // Slice request/response — POST /library/files/{id}/slice and /archives/{id}/slice
  1854. //
  1855. // Two preset shapes are accepted per slot:
  1856. // - Legacy bare integer ids (`*_preset_id`) — pre-cloud-tier clients.
  1857. // - Source-aware refs (`*_preset: PresetRef`) — new SliceModal that picks
  1858. // across cloud / local / standard tiers. Source-aware refs win when both
  1859. // are present in the same payload.
  1860. export type PresetSource = 'orca_cloud' | 'cloud' | 'local' | 'standard';
  1861. export interface PresetRef {
  1862. source: PresetSource;
  1863. id: string;
  1864. }
  1865. /**
  1866. * Why a preset's effective values are unavailable.
  1867. *
  1868. * `sidecar_outdated` is the one that matters in practice: an install pulls its
  1869. * sidecar as `SIDECAR_TAG:-latest` regardless of which Bambuddy channel it is
  1870. * on, so a user can perfectly well be running a current Bambuddy against a
  1871. * sidecar that predates this endpoint. That has a one-line fix, and saying so
  1872. * beats a generic "could not read the values".
  1873. */
  1874. export type SlicerPresetValuesReason =
  1875. | 'ok'
  1876. | 'sidecar_outdated'
  1877. | 'sidecar_unavailable'
  1878. | 'not_configured'
  1879. | 'preset_unresolved';
  1880. export interface SlicerPresetValues {
  1881. /** False when the sidecar could not supply values; `values` is then empty. */
  1882. resolved: boolean;
  1883. /** Flattened key -> value map, in the string forms a process preset stores. */
  1884. values: Record<string, string | string[]>;
  1885. reason: SlicerPresetValuesReason;
  1886. }
  1887. export interface SliceRequest {
  1888. printer_preset_id?: number;
  1889. process_preset_id?: number;
  1890. filament_preset_id?: number;
  1891. printer_preset?: PresetRef;
  1892. process_preset?: PresetRef;
  1893. filament_preset?: PresetRef;
  1894. // Multi-color: one PresetRef per plate slot, in plate order. Always
  1895. // preferred over the singular `filament_preset` when both are sent; the
  1896. // backend validator promotes a singular into a one-element list when this
  1897. // is omitted, so legacy single-color clients keep working unchanged.
  1898. filament_presets?: PresetRef[];
  1899. // Per-slot filament colour as `#RRGGBB` / `#RRGGBBAA`, same plate order as
  1900. // `filament_presets` (#2977). Neither slicer stores a colour on a filament
  1901. // *preset* -- it is a per-project property -- so without this every sliced
  1902. // file records the CLI's built-in #00AE42 and the print dialog reports a
  1903. // colour mismatch against whatever is loaded in the AMS. An empty string in
  1904. // any position hands that slot back to the backend's fallback chain (the
  1905. // preset's own default_filament_colour, then the source plate's colour).
  1906. filament_colours?: string[];
  1907. plate?: number;
  1908. export_3mf?: boolean;
  1909. // Build-plate override (#1337). When omitted, the slicer uses the process
  1910. // preset's curr_bed_type as-is. A name from BambuStudio / OrcaSlicer's
  1911. // enum: "Cool Plate", "Engineering Plate", "High Temp Plate" (Smooth PEI),
  1912. // "Textured PEI Plate", "Supertack Plate", or OrcaSlicer's "Textured Cool
  1913. // Plate" (refused when Bambu Studio slices); the backend refuses others (#3359).
  1914. bed_type?: string | null;
  1915. // "Slice as designed" (#2611). 3MF only: slice using the file's embedded
  1916. // project_settings.config (the designer's own wall count, infill, etc.)
  1917. // instead of the picked profile triplet. The preset refs above are still
  1918. // required by the backend validator but go unused on this path.
  1919. use_embedded_settings?: boolean;
  1920. // Process settings the user edited in the slice modal's settings panel,
  1921. // already serialised into the string forms a process preset stores ("1" for
  1922. // a bool, "20%" for a percent, a list for the per-extruder vectors). Patched
  1923. // onto the resolved process JSON after the designer's carried tweaks, so an
  1924. // explicit choice here wins. Omitted when the panel is untouched.
  1925. process_overrides?: Record<string, string | string[]>;
  1926. // Design settings carried from the source 3MF (#2622) — a list of keys the
  1927. // file flags as changed from the system preset, not values.
  1928. design_overrides?: string[];
  1929. // Layout passes the slicer runs before slicing (#2548), both off by
  1930. // default because they move or rotate the objects the user laid out.
  1931. // Unlike the fields above these are CLI actions rather than profile
  1932. // values, so they apply on the embedded-settings path too.
  1933. auto_orient?: boolean;
  1934. auto_arrange?: boolean;
  1935. }
  1936. // GET /api/v1/slicer/presets — unified listing across cloud / local / standard.
  1937. export type SlicerCloudStatus = 'ok' | 'not_authenticated' | 'expired' | 'unreachable';
  1938. export interface UnifiedPreset {
  1939. id: string;
  1940. name: string;
  1941. source: PresetSource;
  1942. // Populated for the filament slot only — used by the SliceModal multi-color
  1943. // pre-pick to score presets against each plate slot's required (type,
  1944. // colour). Optional because the bundled / standard tier rarely carries a
  1945. // colour (colour is a runtime spool attribute on Bambu) and older API
  1946. // responses pre-date these fields entirely.
  1947. filament_type?: string | null;
  1948. filament_colour?: string | null;
  1949. // Printer-preset names a process / filament preset declares itself
  1950. // compatible with. Populated for the local tier (the slicer's own
  1951. // `compatible_printers`); null for cloud / standard. The SliceModal filters
  1952. // the process / filament dropdowns by the selected printer using this when
  1953. // present (#1325).
  1954. compatible_printers?: string[] | null;
  1955. // Printer presets only: the preset it was saved from, for the local and
  1956. // OrcaSlicer Cloud tiers (#3250).
  1957. inherits?: string | null;
  1958. }
  1959. export interface UnifiedPresetsBySlot {
  1960. printer: UnifiedPreset[];
  1961. process: UnifiedPreset[];
  1962. filament: UnifiedPreset[];
  1963. }
  1964. // What is loaded in each connected printer, for the SliceModal's
  1965. // "only connected printers" / "only loaded spools" filters (#3172).
  1966. export interface LoadedSpoolPreset {
  1967. preset_id: string;
  1968. preset_name: string;
  1969. preset_source: string;
  1970. tray_info_idx?: string | null;
  1971. }
  1972. export interface LoadedSpoolTray {
  1973. ams_id: number;
  1974. tray_id: number;
  1975. tray_type: string | null;
  1976. tray_sub_brands: string | null;
  1977. tray_color: string | null;
  1978. tray_info_idx: string | null;
  1979. exists: boolean | null;
  1980. state: number | null;
  1981. saved_preset: LoadedSpoolPreset | null;
  1982. }
  1983. export interface LoadedSpoolUnit {
  1984. id: number;
  1985. is_ams_ht: boolean;
  1986. trays: LoadedSpoolTray[];
  1987. }
  1988. export interface LoadedSpoolPrinter {
  1989. id: number;
  1990. name: string;
  1991. model: string | null;
  1992. ams: LoadedSpoolUnit[];
  1993. // Holders with a spool in them; external_holders counts all of them (two
  1994. // on a dual-nozzle printer, labelled left and right).
  1995. external: LoadedSpoolTray[];
  1996. external_holders: number;
  1997. }
  1998. export interface LoadedSpoolsResponse {
  1999. printers: LoadedSpoolPrinter[];
  2000. }
  2001. export interface UnifiedPresetsResponse {
  2002. // Priority order: local > orca_cloud > cloud > standard. No cross-tier
  2003. // dedup (apart from stock_aliases below) — every tier surfaces its full
  2004. // list so the user can pick from any source. The order drives auto-pick + visual group rendering only.
  2005. orca_cloud: UnifiedPresetsBySlot;
  2006. cloud: UnifiedPresetsBySlot;
  2007. local: UnifiedPresetsBySlot;
  2008. standard: UnifiedPresetsBySlot;
  2009. cloud_status: SlicerCloudStatus;
  2010. orca_cloud_status: SlicerCloudStatus;
  2011. // Standard presets that Bambu Cloud's stock list also has are left out of
  2012. // the standard tier (#3386); each "standard:<id>" maps to its cloud twin.
  2013. stock_aliases?: Record<string, PresetRef>;
  2014. }
  2015. // Slicer Pipelines (#1425) — named bundles of preset slots the SliceModal
  2016. // can apply in one click. PR A surfaces only the bundle; target_* and
  2017. // fanout_strategy round-trip from the backend but the UI doesn't yet expose
  2018. // them (they come alive in PR B / PR C).
  2019. export interface SlicerPipeline {
  2020. id: number;
  2021. name: string;
  2022. description: string | null;
  2023. printer_preset: PresetRef;
  2024. process_preset: PresetRef;
  2025. filament_presets: PresetRef[];
  2026. bed_type: string | null;
  2027. target_kind: 'specific_printer' | 'printer_class';
  2028. target_printer_id: number | null;
  2029. target_model_class: string | null;
  2030. fanout_strategy: 'max_parallel' | 'fill_one_first' | 'round_robin';
  2031. created_by: number | null;
  2032. created_at: string;
  2033. updated_at: string;
  2034. }
  2035. export interface SlicerPipelineCreateRequest {
  2036. name: string;
  2037. description?: string | null;
  2038. printer_preset: PresetRef;
  2039. process_preset: PresetRef;
  2040. filament_presets: PresetRef[];
  2041. bed_type?: string | null;
  2042. }
  2043. export type SlicerPipelineUpdateRequest = Partial<SlicerPipelineCreateRequest> & {
  2044. target_kind?: 'specific_printer' | 'printer_class';
  2045. // ``target_printer_id: 0`` means "clear the target" — the backend maps that
  2046. // to null. Use null in TypeScript for the same intent.
  2047. target_printer_id?: number | null;
  2048. target_model_class?: string | null;
  2049. fanout_strategy?: 'max_parallel' | 'fill_one_first' | 'round_robin';
  2050. };
  2051. export interface SlicerPipelinesListResponse {
  2052. pipelines: SlicerPipeline[];
  2053. }
  2054. // Slicer Pipeline runs (#1425 PR B + PR C)
  2055. export type PipelineEligibilityKind =
  2056. | 'printer_not_set'
  2057. | 'printer_not_found'
  2058. | 'printer_disabled'
  2059. | 'printer_offline'
  2060. | 'filament_type_mismatch'
  2061. | 'filament_color_mismatch'
  2062. | 'ams_slot_missing'
  2063. | 'filament_unverified'
  2064. | 'no_class_matches'
  2065. | 'class_not_set';
  2066. export interface PipelineEligibilityIssue {
  2067. kind: PipelineEligibilityKind;
  2068. slot_index: number | null;
  2069. expected: string | null;
  2070. actual: string | null;
  2071. }
  2072. export interface PipelinePerPrinterReport {
  2073. printer_id: number;
  2074. printer_name: string;
  2075. ok: boolean;
  2076. issues: PipelineEligibilityIssue[];
  2077. }
  2078. export interface PipelineEligibilityReport {
  2079. ok: boolean;
  2080. target_kind: 'specific_printer' | 'printer_class';
  2081. target_printer_id: number | null;
  2082. target_printer_name: string | null;
  2083. target_model_class: string | null;
  2084. issues: PipelineEligibilityIssue[];
  2085. printer_reports: PipelinePerPrinterReport[];
  2086. }
  2087. export interface PipelineJob {
  2088. id: number;
  2089. pipeline_run_id: number;
  2090. copy_index: number;
  2091. assigned_printer_id: number | null;
  2092. assigned_printer_name: string | null;
  2093. queue_entry_id: number | null;
  2094. status:
  2095. | 'pending'
  2096. | 'awaiting_printer'
  2097. | 'queued'
  2098. | 'printing'
  2099. | 'completed'
  2100. | 'failed'
  2101. | 'cancelled'
  2102. | 'unknown';
  2103. error_message: string | null;
  2104. dispatched_at: string | null;
  2105. completed_at: string | null;
  2106. }
  2107. export interface PipelineRun {
  2108. id: number;
  2109. pipeline_id: number | null;
  2110. pipeline_name: string | null;
  2111. source_library_file_id: number | null;
  2112. source_archive_id: number | null;
  2113. source_filename: string | null;
  2114. parent_run_id: number | null;
  2115. copies: number;
  2116. copies_completed: number;
  2117. copies_failed: number;
  2118. copies_cancelled: number;
  2119. copies_in_progress: number;
  2120. status:
  2121. | 'queued'
  2122. | 'slicing'
  2123. | 'dispatching'
  2124. | 'in_progress'
  2125. | 'completed'
  2126. | 'failed'
  2127. | 'partial_failure'
  2128. | 'cancelled';
  2129. slice_job_id: number | null;
  2130. sliced_library_file_id: number | null;
  2131. eligibility_overridden: boolean;
  2132. error_message: string | null;
  2133. created_by: number | null;
  2134. created_at: string;
  2135. started_at: string | null;
  2136. completed_at: string | null;
  2137. jobs: PipelineJob[];
  2138. target_kind: 'specific_printer' | 'printer_class' | null;
  2139. target_printer_id: number | null;
  2140. target_model_class: string | null;
  2141. fanout_strategy: 'max_parallel' | 'fill_one_first' | 'round_robin' | null;
  2142. }
  2143. export interface PipelineRunListResponse {
  2144. runs: PipelineRun[];
  2145. total: number;
  2146. }
  2147. export interface SliceResponse {
  2148. library_file_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. /** Why the result could not be written to the external folder the source
  2155. * lives in, and so went to managed storage instead. Null on every normal
  2156. * slice. Surfaced to the user — a file filed somewhere they aren't looking
  2157. * with no signal is what made #2810 invisible from the UI. */
  2158. external_write_fallback?: string | null;
  2159. }
  2160. export interface SliceArchiveResponse {
  2161. archive_id: number;
  2162. name: string;
  2163. print_time_seconds: number;
  2164. filament_used_g: number;
  2165. filament_used_mm: number;
  2166. used_embedded_settings: boolean;
  2167. }
  2168. // Background slice-job lifecycle. POST /slice returns 202 + this shape;
  2169. // the frontend polls /slice-jobs/{id} until status is terminal.
  2170. export type SliceJobStatus = 'pending' | 'running' | 'completed' | 'failed';
  2171. export interface SliceJobEnqueueResponse {
  2172. job_id: number;
  2173. status: SliceJobStatus;
  2174. status_url: string;
  2175. }
  2176. export interface SliceJobProgress {
  2177. /** Stage label emitted by the slicer ("Generating G-code", "Slicing finished"). */
  2178. stage: string;
  2179. total_percent: number;
  2180. plate_percent: number;
  2181. /** 1-indexed plate position; 0 means "all plates" / final completion. */
  2182. plate_index: number;
  2183. plate_count: number;
  2184. updated_at: number;
  2185. /** When the backend is in the cross-class slice-all loop (#1493), each
  2186. * per-plate sub-slice's progress is augmented with the loop position
  2187. * so the toast can show "Plate 2 of 5 — Generating G-code 47%". The
  2188. * fields are absent on a single-plate slice. */
  2189. multi_plate_index?: number;
  2190. multi_plate_count?: number;
  2191. }
  2192. export interface SliceJobState {
  2193. job_id: number;
  2194. status: SliceJobStatus;
  2195. kind: 'library_file' | 'archive';
  2196. source_id: number;
  2197. source_name: string;
  2198. created_at: string;
  2199. started_at: string | null;
  2200. completed_at: string | null;
  2201. /** Live progress fed by the sidecar's --pipe channel; null until the
  2202. * slicer emits its first frame (early "Initializing" phase) or when
  2203. * the sidecar doesn't support progress. */
  2204. progress: SliceJobProgress | null;
  2205. result?: SliceResponse | SliceArchiveResponse;
  2206. error_status?: number;
  2207. error_detail?: string;
  2208. }
  2209. // Local preset types (OrcaSlicer imports)
  2210. export interface LocalPreset {
  2211. id: number;
  2212. name: string;
  2213. preset_type: string;
  2214. source: string;
  2215. filament_type: string | null;
  2216. filament_vendor: string | null;
  2217. nozzle_temp_min: number | null;
  2218. nozzle_temp_max: number | null;
  2219. pressure_advance: string | null;
  2220. default_filament_colour: string | null;
  2221. filament_cost: string | null;
  2222. filament_density: string | null;
  2223. compatible_printers: string | null;
  2224. inherits: string | null;
  2225. version: string | null;
  2226. created_at: string;
  2227. updated_at: string;
  2228. }
  2229. export interface LocalPresetDetail extends LocalPreset {
  2230. setting: Record<string, unknown>;
  2231. }
  2232. export interface LocalPresetsResponse {
  2233. filament: LocalPreset[];
  2234. printer: LocalPreset[];
  2235. process: LocalPreset[];
  2236. }
  2237. export interface ImportResponse {
  2238. success: boolean;
  2239. imported: number;
  2240. skipped: number;
  2241. errors: string[];
  2242. }
  2243. export interface FieldOption {
  2244. value: string;
  2245. label: string;
  2246. }
  2247. export interface FieldDefinition {
  2248. key: string;
  2249. label: string;
  2250. type: 'text' | 'number' | 'boolean' | 'select';
  2251. category: string;
  2252. description?: string;
  2253. options?: FieldOption[];
  2254. unit?: string;
  2255. min?: number;
  2256. max?: number;
  2257. step?: number;
  2258. }
  2259. export interface FieldDefinitionsResponse {
  2260. version: string;
  2261. description: string;
  2262. fields: FieldDefinition[];
  2263. }
  2264. export interface CloudDevice {
  2265. dev_id: string;
  2266. name: string;
  2267. dev_model_name: string | null;
  2268. dev_product_name: string | null;
  2269. online: boolean;
  2270. }
  2271. // Smart Plug types
  2272. export interface SmartPlug {
  2273. id: number;
  2274. name: string;
  2275. plug_type: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  2276. ip_address: string | null; // Required for Tasmota
  2277. ha_entity_id: string | null; // Required for Home Assistant (e.g., "switch.printer_plug", "script.turn_on_printer")
  2278. // Home Assistant energy sensor entities (optional)
  2279. ha_power_entity: string | null;
  2280. ha_energy_today_entity: string | null;
  2281. ha_energy_total_entity: string | null;
  2282. // MQTT fields (required when plug_type="mqtt")
  2283. // Legacy field - kept for backward compatibility
  2284. mqtt_topic: string | null; // Deprecated, use mqtt_power_topic
  2285. mqtt_multiplier: number; // Deprecated, use mqtt_power_multiplier
  2286. // Power monitoring
  2287. mqtt_power_topic: string | null; // Topic for power data
  2288. mqtt_power_path: string | null; // e.g., "power_l1" or "data.power"
  2289. mqtt_power_multiplier: number; // Unit conversion for power
  2290. // Energy monitoring
  2291. mqtt_energy_topic: string | null; // Topic for energy data
  2292. mqtt_energy_path: string | null; // e.g., "energy_l1"
  2293. mqtt_energy_multiplier: number; // Unit conversion for energy
  2294. mqtt_energy_total_path: string | null; // Lifetime counter on the energy topic (#3582)
  2295. mqtt_energy_total_multiplier: number;
  2296. // State monitoring
  2297. mqtt_state_topic: string | null; // Topic for state data
  2298. mqtt_state_path: string | null; // e.g., "state_l1" for ON/OFF
  2299. mqtt_state_on_value: string | null; // What value means "ON" (e.g., "ON", "true", "1")
  2300. // REST/Webhook fields (required when plug_type="rest")
  2301. rest_on_url: string | null;
  2302. rest_on_body: string | null;
  2303. rest_off_url: string | null;
  2304. rest_off_body: string | null;
  2305. rest_method: string | null;
  2306. rest_headers: string | null;
  2307. rest_status_url: string | null;
  2308. rest_status_path: string | null;
  2309. rest_status_on_value: string | null;
  2310. rest_power_url: string | null;
  2311. rest_power_path: string | null;
  2312. rest_power_multiplier: number;
  2313. rest_energy_url: string | null;
  2314. rest_energy_path: string | null;
  2315. rest_energy_multiplier: number;
  2316. // Lifetime counter, separate from the daily one (#2539). A Shelly reports only
  2317. // this; Today and Yesterday are derived from its hourly snapshots.
  2318. rest_energy_total_path: string | null;
  2319. rest_energy_total_multiplier: number;
  2320. printer_id: number | null;
  2321. // #2629: only a plug that really feeds the printer may mark it offline when
  2322. // switched off. Accessory plugs follow the print cycle without powering it.
  2323. controls_printer_power: boolean;
  2324. enabled: boolean;
  2325. auto_on: boolean;
  2326. auto_off: boolean;
  2327. auto_off_persistent: boolean;
  2328. off_delay_mode: 'time' | 'temperature';
  2329. off_delay_minutes: number;
  2330. off_temp_threshold: number;
  2331. // #1349: auto-off after AMS drying completes.
  2332. auto_off_after_drying: boolean;
  2333. off_delay_after_drying_minutes: number;
  2334. username: string | null;
  2335. password: string | null;
  2336. // Power alerts
  2337. power_alert_enabled: boolean;
  2338. power_alert_high: number | null;
  2339. power_alert_low: number | null;
  2340. power_alert_last_triggered: string | null;
  2341. // Schedule
  2342. schedule_enabled: boolean;
  2343. schedule_on_time: string | null;
  2344. schedule_off_time: string | null;
  2345. // Visibility options
  2346. show_in_switchbar: boolean;
  2347. show_on_printer_card: boolean; // For scripts: show on printer card
  2348. // Status
  2349. last_state: string | null;
  2350. last_checked: string | null;
  2351. auto_off_executed: boolean; // True when auto-off was triggered after print
  2352. created_at: string;
  2353. updated_at: string;
  2354. }
  2355. export interface SmartPlugCreate {
  2356. name: string;
  2357. plug_type?: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  2358. ip_address?: string | null; // Required for Tasmota
  2359. ha_entity_id?: string | null; // Required for Home Assistant
  2360. // Home Assistant energy sensor entities (optional)
  2361. ha_power_entity?: string | null;
  2362. ha_energy_today_entity?: string | null;
  2363. ha_energy_total_entity?: string | null;
  2364. // MQTT fields (required when plug_type="mqtt")
  2365. // Legacy fields - kept for backward compatibility
  2366. mqtt_topic?: string | null;
  2367. mqtt_multiplier?: number;
  2368. // Power monitoring
  2369. mqtt_power_topic?: string | null;
  2370. mqtt_power_path?: string | null;
  2371. mqtt_power_multiplier?: number;
  2372. // Energy monitoring
  2373. mqtt_energy_topic?: string | null;
  2374. mqtt_energy_path?: string | null;
  2375. mqtt_energy_multiplier?: number;
  2376. mqtt_energy_total_path?: string | null;
  2377. mqtt_energy_total_multiplier?: number;
  2378. // State monitoring
  2379. mqtt_state_topic?: string | null;
  2380. mqtt_state_path?: string | null;
  2381. mqtt_state_on_value?: string | null;
  2382. // REST fields
  2383. rest_on_url?: string | null;
  2384. rest_on_body?: string | null;
  2385. rest_off_url?: string | null;
  2386. rest_off_body?: string | null;
  2387. rest_method?: string | null;
  2388. rest_headers?: string | null;
  2389. rest_status_url?: string | null;
  2390. rest_status_path?: string | null;
  2391. rest_status_on_value?: string | null;
  2392. rest_power_url?: string | null;
  2393. rest_power_path?: string | null;
  2394. rest_power_multiplier?: number;
  2395. rest_energy_url?: string | null;
  2396. rest_energy_path?: string | null;
  2397. rest_energy_multiplier?: number;
  2398. rest_energy_total_path?: string | null;
  2399. rest_energy_total_multiplier?: number;
  2400. printer_id?: number | null;
  2401. // #2629
  2402. controls_printer_power?: boolean;
  2403. enabled?: boolean;
  2404. auto_on?: boolean;
  2405. auto_off?: boolean;
  2406. auto_off_persistent?: boolean;
  2407. off_delay_mode?: 'time' | 'temperature';
  2408. off_delay_minutes?: number;
  2409. off_temp_threshold?: number;
  2410. // #1349
  2411. auto_off_after_drying?: boolean;
  2412. off_delay_after_drying_minutes?: number;
  2413. username?: string | null;
  2414. password?: string | null;
  2415. // Power alerts
  2416. power_alert_enabled?: boolean;
  2417. power_alert_high?: number | null;
  2418. power_alert_low?: number | null;
  2419. // Schedule
  2420. schedule_enabled?: boolean;
  2421. schedule_on_time?: string | null;
  2422. schedule_off_time?: string | null;
  2423. // Visibility options
  2424. show_in_switchbar?: boolean;
  2425. show_on_printer_card?: boolean;
  2426. }
  2427. export interface SmartPlugUpdate {
  2428. name?: string;
  2429. plug_type?: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  2430. ip_address?: string | null;
  2431. ha_entity_id?: string | null;
  2432. // Home Assistant energy sensor entities (optional)
  2433. ha_power_entity?: string | null;
  2434. ha_energy_today_entity?: string | null;
  2435. ha_energy_total_entity?: string | null;
  2436. // MQTT fields (legacy)
  2437. mqtt_topic?: string | null;
  2438. mqtt_multiplier?: number;
  2439. // MQTT power fields
  2440. mqtt_power_topic?: string | null;
  2441. mqtt_power_path?: string | null;
  2442. mqtt_power_multiplier?: number;
  2443. // MQTT energy fields
  2444. mqtt_energy_topic?: string | null;
  2445. mqtt_energy_path?: string | null;
  2446. mqtt_energy_multiplier?: number;
  2447. mqtt_energy_total_path?: string | null;
  2448. mqtt_energy_total_multiplier?: number;
  2449. // MQTT state fields
  2450. mqtt_state_topic?: string | null;
  2451. mqtt_state_path?: string | null;
  2452. mqtt_state_on_value?: string | null;
  2453. // REST fields
  2454. rest_on_url?: string | null;
  2455. rest_on_body?: string | null;
  2456. rest_off_url?: string | null;
  2457. rest_off_body?: string | null;
  2458. rest_method?: string | null;
  2459. rest_headers?: string | null;
  2460. rest_status_url?: string | null;
  2461. rest_status_path?: string | null;
  2462. rest_status_on_value?: string | null;
  2463. rest_power_url?: string | null;
  2464. rest_power_path?: string | null;
  2465. rest_power_multiplier?: number;
  2466. rest_energy_url?: string | null;
  2467. rest_energy_path?: string | null;
  2468. rest_energy_multiplier?: number;
  2469. rest_energy_total_path?: string | null;
  2470. rest_energy_total_multiplier?: number;
  2471. printer_id?: number | null;
  2472. // #2629
  2473. controls_printer_power?: boolean;
  2474. enabled?: boolean;
  2475. auto_on?: boolean;
  2476. auto_off?: boolean;
  2477. auto_off_persistent?: boolean;
  2478. off_delay_mode?: 'time' | 'temperature';
  2479. off_delay_minutes?: number;
  2480. off_temp_threshold?: number;
  2481. // #1349
  2482. auto_off_after_drying?: boolean;
  2483. off_delay_after_drying_minutes?: number;
  2484. username?: string | null;
  2485. password?: string | null;
  2486. // Power alerts
  2487. power_alert_enabled?: boolean;
  2488. power_alert_high?: number | null;
  2489. power_alert_low?: number | null;
  2490. // Schedule
  2491. schedule_enabled?: boolean;
  2492. schedule_on_time?: string | null;
  2493. schedule_off_time?: string | null;
  2494. // Visibility options
  2495. show_in_switchbar?: boolean;
  2496. show_on_printer_card?: boolean;
  2497. }
  2498. // Home Assistant entity for smart plug selection
  2499. export interface HAEntity {
  2500. entity_id: string;
  2501. friendly_name: string;
  2502. state: string | null;
  2503. domain: string; // "switch", "light", "input_boolean", "script"
  2504. }
  2505. // Home Assistant sensor entity for energy monitoring
  2506. export interface HASensorEntity {
  2507. entity_id: string;
  2508. friendly_name: string;
  2509. state: string | null;
  2510. unit_of_measurement: string | null; // "W", "kW", "kWh", "Wh"
  2511. }
  2512. export interface HATestConnectionResult {
  2513. success: boolean;
  2514. message: string | null;
  2515. error: string | null;
  2516. }
  2517. // A Home Assistant entity bound to a printer for display on its card (#1148, #448).
  2518. // Read-only: unlike a SmartPlug there is nothing here to switch.
  2519. export interface PrinterHASensor {
  2520. id: number;
  2521. printer_id: number;
  2522. name: string;
  2523. entity_id: string;
  2524. kind: 'binary' | 'numeric';
  2525. device_class: string | null; // HA's own class: "door", "temperature", ...
  2526. unit: string | null; // numeric sensors only
  2527. // What counts as needing attention. Binary sensors use alert_state, numeric
  2528. // ones the thresholds; all null means the sensor is display-only.
  2529. alert_state: 'on' | 'off' | null;
  2530. alert_above: number | null;
  2531. alert_below: number | null;
  2532. block_print: boolean; // hold the printer's queue while alerting
  2533. notify_on_alert: boolean;
  2534. show_on_printer_card: boolean;
  2535. sort_order: number;
  2536. last_state: string | null;
  2537. last_changed: string | null;
  2538. last_checked: string | null;
  2539. created_at: string;
  2540. updated_at: string;
  2541. }
  2542. export interface PrinterHASensorReading {
  2543. id: number;
  2544. name: string;
  2545. entity_id: string;
  2546. kind: 'binary' | 'numeric';
  2547. device_class: string | null;
  2548. unit: string | null;
  2549. state: string | null; // null when unreadable or not yet polled
  2550. value: number | null; // numeric sensors only
  2551. alerting: boolean;
  2552. block_print: boolean;
  2553. reachable: boolean;
  2554. last_changed: string | null;
  2555. }
  2556. export interface PrinterHASensorCreate {
  2557. printer_id: number;
  2558. name: string;
  2559. entity_id: string;
  2560. kind: 'binary' | 'numeric';
  2561. device_class?: string | null;
  2562. unit?: string | null;
  2563. alert_state?: 'on' | 'off' | null;
  2564. alert_above?: number | null;
  2565. alert_below?: number | null;
  2566. block_print?: boolean;
  2567. notify_on_alert?: boolean;
  2568. show_on_printer_card?: boolean;
  2569. sort_order?: number;
  2570. }
  2571. export type PrinterHASensorUpdate = Partial<Omit<PrinterHASensorCreate, 'printer_id'>>;
  2572. export interface LocationHASensor {
  2573. id: number;
  2574. location_id: number;
  2575. name: string;
  2576. entity_id: string;
  2577. kind: 'binary' | 'numeric';
  2578. device_class: string | null;
  2579. unit: string | null;
  2580. alert_state: 'on' | 'off' | null;
  2581. alert_above: number | null;
  2582. alert_below: number | null;
  2583. notify_on_alert: boolean;
  2584. show_on_card: boolean;
  2585. sort_order: number;
  2586. last_state: string | null;
  2587. last_changed: string | null;
  2588. last_checked: string | null;
  2589. created_at: string;
  2590. updated_at: string;
  2591. }
  2592. export interface LocationHASensorReading {
  2593. id: number;
  2594. name: string;
  2595. entity_id: string;
  2596. kind: 'binary' | 'numeric';
  2597. device_class: string | null;
  2598. unit: string | null;
  2599. state: string | null;
  2600. value: number | null;
  2601. alerting: boolean;
  2602. reachable: boolean;
  2603. alert_state: string | null;
  2604. alert_above: number | null;
  2605. alert_below: number | null;
  2606. last_changed: string | null;
  2607. show_on_card: boolean;
  2608. }
  2609. export interface LocationHASensorCreate {
  2610. location_id: number;
  2611. name: string;
  2612. entity_id: string;
  2613. kind: 'binary' | 'numeric';
  2614. device_class?: string | null;
  2615. unit?: string | null;
  2616. alert_state?: 'on' | 'off' | null;
  2617. alert_above?: number | null;
  2618. alert_below?: number | null;
  2619. notify_on_alert?: boolean;
  2620. show_on_card?: boolean;
  2621. sort_order?: number;
  2622. }
  2623. export type LocationHASensorUpdate = Partial<Omit<LocationHASensorCreate, 'location_id'>>;
  2624. // An entity offered by the binding picker.
  2625. export interface HADisplayEntity {
  2626. entity_id: string;
  2627. friendly_name: string;
  2628. state: string | null;
  2629. domain: string; // "binary_sensor" | "sensor"
  2630. device_class: string | null;
  2631. unit_of_measurement: string | null;
  2632. }
  2633. export interface SmartPlugEnergy {
  2634. power: number | null; // Current watts
  2635. voltage: number | null; // Volts
  2636. current: number | null; // Amps
  2637. today: number | null; // kWh used today
  2638. yesterday: number | null; // kWh used yesterday
  2639. total: number | null; // Total kWh
  2640. factor: number | null; // Power factor (0-1)
  2641. apparent_power: number | null; // VA
  2642. reactive_power: number | null; // VAr
  2643. }
  2644. export interface SmartPlugStatus {
  2645. state: string | null;
  2646. reachable: boolean;
  2647. device_name: string | null;
  2648. energy: SmartPlugEnergy | null;
  2649. }
  2650. export interface SmartPlugTestResult {
  2651. success: boolean;
  2652. state: string | null;
  2653. device_name: string | null;
  2654. }
  2655. // Tasmota Discovery types
  2656. export interface TasmotaScanStatus {
  2657. running: boolean;
  2658. scanned: number;
  2659. total: number;
  2660. }
  2661. export interface DiscoveredTasmotaDevice {
  2662. ip_address: string;
  2663. name: string;
  2664. module: number | null;
  2665. state: string | null;
  2666. discovered_at: string | null;
  2667. }
  2668. // Print Queue types
  2669. export interface PrintQueueItem {
  2670. id: number;
  2671. printer_id: number | null; // null = unassigned
  2672. target_model: string | null; // Target printer model for model-based assignment
  2673. target_location: string | null; // Target location filter for model-based assignment
  2674. required_filament_types: string[] | null; // Required filament types for model-based assignment
  2675. waiting_reason: string | null; // Why this job hasn't started yet (empty once it can)
  2676. // Cross-model alternatives (#671), in priority order. Empty for ordinary
  2677. // items. Present until dispatch resolves one, after which library_file_id and
  2678. // target_model name the candidate that actually ran.
  2679. variants?: Array<{
  2680. library_file_id: number;
  2681. filename: string;
  2682. target_model: string;
  2683. position: number;
  2684. }>;
  2685. // Either archive_id OR library_file_id must be set (archive created at print start)
  2686. archive_id: number | null;
  2687. library_file_id: number | null;
  2688. cost_center_id: number | null;
  2689. estimated_cost: number | null;
  2690. position: number;
  2691. scheduled_time: string | null;
  2692. require_previous_success: boolean;
  2693. auto_off_after: boolean;
  2694. manual_start: boolean; // Requires manual trigger to start (staged)
  2695. // Set by the dispatch scheduler when the assigned spool can't satisfy
  2696. // any required slot's grams (#1496). Surfaced on the queue row as a
  2697. // "filament short" badge; cleared on a successful ▶ click (live recheck).
  2698. filament_short: boolean;
  2699. // Persistent "Print Anyway" acknowledgement — once true the scheduler
  2700. // skips the deficit check for this item (#1698-followup). Set by the
  2701. // start route when skip_filament_check=true, or at queue creation if
  2702. // PrintModal's deficit warning was acknowledged.
  2703. skip_filament_check: boolean;
  2704. // True when the source archive carries the slicer's own live-resolved
  2705. // AMS-slot pick (extra_data.slicer_ams_mapping) — a reprint reuses that
  2706. // exact physical spool instead of re-deriving one from type/color.
  2707. archive_has_slicer_ams_mapping: boolean;
  2708. ams_mapping: number[] | null; // AMS slot mapping for multi-color prints
  2709. 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
  2710. plate_id: number | null; // Plate ID for multi-plate 3MF files
  2711. // Print options
  2712. bed_levelling: CalibrationMode;
  2713. flow_cali: CalibrationMode;
  2714. vibration_cali: boolean;
  2715. layer_inspect: boolean;
  2716. timelapse: boolean;
  2717. use_ams: boolean;
  2718. nozzle_offset_cali: CalibrationMode;
  2719. // Ask for a post-print outcome verdict when this job completes (#1898)
  2720. confirm_outcome: boolean;
  2721. preheat_override: 'inherit' | 'on' | 'off';
  2722. preheat_chamber_target_override: number | null;
  2723. status: 'pending' | 'printing' | 'completed' | 'failed' | 'skipped' | 'cancelled';
  2724. started_at: string | null;
  2725. completed_at: string | null;
  2726. error_message: string | null;
  2727. created_at: string;
  2728. archive_name?: string | null;
  2729. archive_thumbnail?: string | null;
  2730. // True when the linked archive has been soft-deleted; archive_name /
  2731. // archive_thumbnail / downstream metadata are left null in that case so
  2732. // the UI doesn't 404-storm the now-missing endpoints (#1348 follow-up).
  2733. archive_deleted?: boolean;
  2734. library_file_name?: string | null;
  2735. library_file_thumbnail?: string | null;
  2736. printer_name?: string | null;
  2737. print_time_seconds?: number | null; // Estimated print time from archive or library file
  2738. filament_used_grams?: number | null; // Estimated print weight from archive or library file
  2739. filament_type?: string | null; // e.g. "PLA", "PETG"
  2740. filament_color?: string | null; // Hex RGBA from the slicer
  2741. bed_type?: string | null; // Build plate type for this print (per-plate accurate, #1281)
  2742. // User tracking (Issue #206)
  2743. created_by_id?: number | null;
  2744. created_by_username?: string | null;
  2745. // Batch grouping
  2746. batch_id?: number | null;
  2747. batch_name?: string | null;
  2748. // Shortest-job-first scheduling
  2749. been_jumped?: boolean;
  2750. // Auto-print G-code injection
  2751. gcode_injection?: boolean;
  2752. cleanup_library_after_dispatch?: boolean;
  2753. /** Which rack position each filament group prints from, on a nozzle-rack
  2754. * machine (#1784): `{ [group_id]: 1-based position }`. Re-checked against
  2755. * the live rack at dispatch; omit to have the dispatcher assign them. */
  2756. nozzle_rack_choice?: Record<number, number> | null;
  2757. /** Slots sent with a spool of another colour than the file asks for
  2758. * (#3279). Worked out when the job is sent; null when every slot got its
  2759. * colour or nothing could be compared. */
  2760. color_substitutions?: ColorSubstitution[] | null;
  2761. }
  2762. /** One slot printed in another colour than the file asked for (#3279). */
  2763. export interface ColorSubstitution {
  2764. slot_id: number;
  2765. type: string;
  2766. /** `#RRGGBB` the file asks for, after overrides. */
  2767. wanted: string;
  2768. /** `#RRGGBB` of the spool the slot was sent with. */
  2769. got: string;
  2770. tray: number;
  2771. }
  2772. export interface PrintBatchPlateTarget {
  2773. plate_id: number | null;
  2774. plate_name?: string | null;
  2775. quantity_target: number;
  2776. sort_order?: number;
  2777. }
  2778. export interface PrintBatchPlateProgress {
  2779. plate_id: number | null;
  2780. plate_name: string | null;
  2781. quantity_target: number;
  2782. dispatched: number;
  2783. remaining: number;
  2784. pending_count: number;
  2785. printing_count: number;
  2786. completed_count: number;
  2787. failed_count: number;
  2788. cancelled_count: number;
  2789. skipped_count: number;
  2790. /** Measured from finished runs; null until one has produced a cost. */
  2791. actual_cost: number | null;
  2792. estimated_remaining_cost: number | null;
  2793. filament_used_grams: number | null;
  2794. print_time_seconds: number;
  2795. /** False when this plate owes runs but has no queue item left to clone
  2796. * their configuration from, so queueing it could only fail (#2960). */
  2797. can_dispatch: boolean;
  2798. }
  2799. export interface PrintBatch {
  2800. id: number;
  2801. name: string;
  2802. archive_id: number | null;
  2803. library_file_id: number | null;
  2804. quantity: number;
  2805. status: string;
  2806. created_at: string;
  2807. completed_at: string | null;
  2808. created_by_id: number | null;
  2809. created_by_username: string | null;
  2810. project_id: number | null;
  2811. due_date: string | null;
  2812. notes: string | null;
  2813. /** Set when an integration (e.g. a shop connector) created the batch. */
  2814. external_source: string | null;
  2815. external_ref: string | null;
  2816. pending_count: number;
  2817. printing_count: number;
  2818. completed_count: number;
  2819. failed_count: number;
  2820. cancelled_count: number;
  2821. skipped_count: number;
  2822. /** False for batches created before per-plate targets existed (#342):
  2823. * they report progress but owe nothing and cannot be dispatched from. */
  2824. has_targets: boolean;
  2825. target_count: number;
  2826. remaining_count: number;
  2827. /** Of remaining_count, how many runs can actually be queued (#2960). */
  2828. dispatchable_count: number;
  2829. actual_cost: number | null;
  2830. estimated_remaining_cost: number | null;
  2831. filament_used_grams: number | null;
  2832. print_time_seconds: number;
  2833. plates: PrintBatchPlateProgress[];
  2834. }
  2835. export interface PrintQueueItemCreate {
  2836. printer_id?: number | null; // null = unassigned
  2837. target_model?: string | null; // Target printer model (mutually exclusive with printer_id)
  2838. target_location?: string | null; // Target location filter (only used with target_model)
  2839. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; tray_info_idx?: string; force_color_match?: boolean }> | null;
  2840. archive_id?: number | null;
  2841. library_file_id?: number | null;
  2842. scheduled_time?: string | null;
  2843. require_previous_success?: boolean;
  2844. auto_off_after?: boolean;
  2845. manual_start?: boolean; // Requires manual trigger to start (staged)
  2846. insert_at_top?: boolean; // Insert ahead of other pending items (one queue order across all printers, #3200)
  2847. insert_position?: number | null; // 1-indexed insertion position for priority queueing
  2848. // PrintModal "Print Anyway" on the deficit warning — persisted so the
  2849. // scheduler doesn't immediately re-flag this item (#1698-followup).
  2850. skip_filament_check?: boolean;
  2851. ams_mapping?: number[] | null; // AMS slot mapping for multi-color prints
  2852. plate_id?: number | null; // Plate ID for multi-plate 3MF files
  2853. // Print options
  2854. bed_levelling?: CalibrationMode;
  2855. flow_cali?: CalibrationMode;
  2856. vibration_cali?: boolean;
  2857. layer_inspect?: boolean;
  2858. timelapse?: boolean;
  2859. use_ams?: boolean;
  2860. nozzle_offset_cali?: CalibrationMode;
  2861. // Ask for a post-print outcome verdict when this job completes (#1898)
  2862. confirm_outcome?: boolean;
  2863. preheat_override?: 'inherit' | 'on' | 'off';
  2864. preheat_chamber_target_override?: number | null;
  2865. // Auto-print G-code injection
  2866. gcode_injection?: boolean;
  2867. // Batch: create multiple copies (creates a batch if > 1)
  2868. quantity?: number;
  2869. // Existing batch to add this item into (multi-plate auto-batch flow).
  2870. batch_id?: number | null;
  2871. // Project to associate the resulting archive with
  2872. project_id?: number;
  2873. cost_center_id?: number | null;
  2874. estimated_cost?: number | null;
  2875. // Delete transient uploaded library file after scheduler creates the archive
  2876. cleanup_library_after_dispatch?: boolean;
  2877. // Cross-model alternatives (#671): several sliced files, one job, whichever
  2878. // printer frees up first. Mutually exclusive with printer_id (a named printer
  2879. // defeats the point) and with archive_id/library_file_id (these ARE the files).
  2880. // Order is priority — index 0 wins when several printers are idle at once.
  2881. variants?: QueueVariantCreate[];
  2882. /** Which rack position each filament group prints from, on a nozzle-rack
  2883. * machine (#1784): `{ [group_id]: 1-based position }`. Re-checked against
  2884. * the live rack at dispatch; omit to have the dispatcher assign them. */
  2885. nozzle_rack_choice?: Record<number, number> | null;
  2886. }
  2887. /** One candidate file for a cross-model queue item (#671). */
  2888. export interface QueueVariantCreate {
  2889. library_file_id: number;
  2890. /** Read from the file's own sliced_for_model unless it declares none. */
  2891. target_model?: string | null;
  2892. plate_id?: number | null;
  2893. ams_mapping?: number[] | null;
  2894. nozzle_mapping?: number[] | null;
  2895. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; tray_info_idx?: string; force_color_match?: boolean }> | null;
  2896. }
  2897. export interface PrintBatchCreate {
  2898. name: string;
  2899. archive_id?: number | null;
  2900. library_file_id?: number | null;
  2901. /** When set, the listed pending items are assigned to the new batch
  2902. * (manual "Group as batch"). When omitted/empty, an empty batch is
  2903. * returned so the client can pass batch_id on subsequent addToQueue calls. */
  2904. item_ids?: number[];
  2905. /** Per-plate targets. Omitting them creates a plain grouping batch. */
  2906. plates?: PrintBatchPlateTarget[];
  2907. project_id?: number | null;
  2908. due_date?: string | null;
  2909. notes?: string | null;
  2910. }
  2911. export interface PrintBatchUpdate {
  2912. name?: string;
  2913. status?: 'active' | 'cancelled';
  2914. /** Replaces the full target set — a plate omitted here is removed. */
  2915. plates?: PrintBatchPlateTarget[];
  2916. project_id?: number | null;
  2917. due_date?: string | null;
  2918. notes?: string | null;
  2919. }
  2920. export interface PrintBatchDispatchRequest {
  2921. plate_id?: number | null;
  2922. only_plate?: boolean;
  2923. /** Cap on items created across all plates; omit to queue everything owed. */
  2924. limit?: number;
  2925. }
  2926. export interface PrintQueueItemUpdate {
  2927. printer_id?: number | null; // null = unassign
  2928. // A deliberate filament substitution in the mapping (#2799); see PrintModal.
  2929. skip_filament_check?: boolean;
  2930. target_model?: string | null; // Target printer model (mutually exclusive with printer_id)
  2931. target_location?: string | null; // Target location filter (only used with target_model)
  2932. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; tray_info_idx?: string; force_color_match?: boolean }> | null;
  2933. position?: number;
  2934. scheduled_time?: string | null;
  2935. require_previous_success?: boolean;
  2936. auto_off_after?: boolean;
  2937. manual_start?: boolean;
  2938. ams_mapping?: number[];
  2939. plate_id?: number | null; // Plate ID for multi-plate 3MF files
  2940. // Print options
  2941. bed_levelling?: CalibrationMode;
  2942. flow_cali?: CalibrationMode;
  2943. vibration_cali?: boolean;
  2944. layer_inspect?: boolean;
  2945. timelapse?: boolean;
  2946. use_ams?: boolean;
  2947. nozzle_offset_cali?: CalibrationMode;
  2948. // Ask for a post-print outcome verdict when this job completes (#1898)
  2949. confirm_outcome?: boolean;
  2950. preheat_override?: 'inherit' | 'on' | 'off';
  2951. preheat_chamber_target_override?: number | null;
  2952. // Auto-print G-code injection
  2953. gcode_injection?: boolean;
  2954. cost_center_id?: number | null;
  2955. estimated_cost?: number | null;
  2956. /** Which rack position each filament group prints from, on a nozzle-rack
  2957. * machine (#1784): `{ [group_id]: 1-based position }`. Re-checked against
  2958. * the live rack at dispatch; omit to have the dispatcher assign them. */
  2959. nozzle_rack_choice?: Record<number, number> | null;
  2960. }
  2961. export interface PrintQueueBulkUpdate {
  2962. item_ids: number[];
  2963. printer_id?: number | null;
  2964. scheduled_time?: string | null;
  2965. require_previous_success?: boolean;
  2966. auto_off_after?: boolean;
  2967. manual_start?: boolean;
  2968. // Print options
  2969. bed_levelling?: CalibrationMode;
  2970. flow_cali?: CalibrationMode;
  2971. vibration_cali?: boolean;
  2972. layer_inspect?: boolean;
  2973. timelapse?: boolean;
  2974. use_ams?: boolean;
  2975. nozzle_offset_cali?: CalibrationMode;
  2976. // Ask for a post-print outcome verdict when this job completes (#1898)
  2977. confirm_outcome?: boolean;
  2978. preheat_override?: 'inherit' | 'on' | 'off';
  2979. preheat_chamber_target_override?: number | null;
  2980. // Auto-print G-code injection
  2981. gcode_injection?: boolean;
  2982. cost_center_id?: number | null;
  2983. estimated_cost?: number | null;
  2984. }
  2985. export interface PrintQueueBulkUpdateResponse {
  2986. updated_count: number;
  2987. skipped_count: number;
  2988. message: string;
  2989. }
  2990. // MQTT Logging types
  2991. export interface MQTTLogEntry {
  2992. timestamp: string;
  2993. topic: string;
  2994. direction: 'in' | 'out';
  2995. payload: Record<string, unknown>;
  2996. }
  2997. export interface MQTTLogsResponse {
  2998. logging_enabled: boolean;
  2999. logs: MQTTLogEntry[];
  3000. }
  3001. // K-Profile types
  3002. export interface KProfile {
  3003. slot_id: number;
  3004. extruder_id: number;
  3005. nozzle_id: string;
  3006. nozzle_diameter: string;
  3007. filament_id: string;
  3008. name: string;
  3009. k_value: string;
  3010. n_coef: string;
  3011. ams_id: number;
  3012. tray_id: number;
  3013. setting_id: string | null;
  3014. }
  3015. export interface KProfileCreate {
  3016. slot_id?: number; // Storage slot, 0 for new profiles
  3017. extruder_id?: number;
  3018. nozzle_id: string;
  3019. nozzle_diameter: string;
  3020. filament_id: string;
  3021. name: string;
  3022. k_value: string;
  3023. n_coef?: string;
  3024. ams_id?: number;
  3025. tray_id?: number;
  3026. setting_id?: string | null;
  3027. }
  3028. export interface KProfileDelete {
  3029. slot_id: number; // cali_idx - calibration index to delete
  3030. extruder_id: number;
  3031. nozzle_id: string; // e.g., "HH00-0.4"
  3032. nozzle_diameter: string; // e.g., "0.4"
  3033. filament_id: string; // Bambu filament identifier
  3034. setting_id?: string | null; // Setting ID (for X1C series)
  3035. }
  3036. export interface KProfilesResponse {
  3037. profiles: KProfile[];
  3038. nozzle_diameter: string;
  3039. }
  3040. export interface KProfileNote {
  3041. setting_id: string;
  3042. note: string;
  3043. }
  3044. export interface KProfileNotesResponse {
  3045. notes: Record<string, string>; // setting_id -> note
  3046. }
  3047. // Slot Preset Mapping
  3048. export interface SlotPresetMapping {
  3049. ams_id: number;
  3050. tray_id: number;
  3051. preset_id: string;
  3052. preset_name: string;
  3053. // Filament id the slot was configured with alongside this preset; null for
  3054. // rows that predate it or whose writer did not know it (#3216).
  3055. tray_info_idx?: string | null;
  3056. }
  3057. // Filament types
  3058. export interface Filament {
  3059. id: number;
  3060. name: string;
  3061. type: string; // PLA, PETG, ABS, etc.
  3062. brand: string | null;
  3063. color: string | null;
  3064. color_hex: string | null;
  3065. cost_per_kg: number;
  3066. spool_weight_g: number;
  3067. currency: string;
  3068. density: number | null;
  3069. print_temp_min: number | null;
  3070. print_temp_max: number | null;
  3071. bed_temp_min: number | null;
  3072. bed_temp_max: number | null;
  3073. created_at: string;
  3074. updated_at: string;
  3075. }
  3076. // Notification Provider types
  3077. export type ProviderType = 'callmebot' | 'ntfy' | 'pushover' | 'telegram' | 'email' | 'discord' | 'webhook' | 'homeassistant' | 'bark' | 'gotify' | 'notify';
  3078. // How a Telegram provider collects the outcome verdict (#3046)
  3079. export type TelegramVerdictMode = 'buttons' | 'reactions' | 'both';
  3080. export interface NotificationProvider {
  3081. id: number;
  3082. name: string;
  3083. provider_type: ProviderType;
  3084. enabled: boolean;
  3085. config: Record<string, unknown>;
  3086. attach_photo: boolean;
  3087. // Print lifecycle events
  3088. on_print_start: boolean;
  3089. on_print_complete: boolean;
  3090. on_print_failed: boolean;
  3091. on_print_stopped: boolean;
  3092. on_print_progress: boolean;
  3093. on_print_missing_spool_assignment: boolean;
  3094. on_billing_charge_failed: boolean;
  3095. // Printer status events
  3096. on_printer_offline: boolean;
  3097. on_printer_error: boolean;
  3098. on_ai_failure_detection: boolean;
  3099. on_filament_low: boolean;
  3100. on_maintenance_due: boolean;
  3101. // AMS environmental alarms (regular AMS)
  3102. on_ams_humidity_high: boolean;
  3103. on_ams_temperature_high: boolean;
  3104. on_ams_drying_suspended: boolean;
  3105. // AMS-HT environmental alarms
  3106. on_ams_ht_humidity_high: boolean;
  3107. on_ams_ht_temperature_high: boolean;
  3108. // Build plate detection
  3109. on_plate_not_empty: boolean;
  3110. on_plate_clear_required: boolean;
  3111. // Post-print outcome confirmation (#1898)
  3112. on_print_confirm_request: boolean;
  3113. telegram_verdict_mode: TelegramVerdictMode;
  3114. // Bed cooled
  3115. on_bed_cooled: boolean;
  3116. on_ha_sensor_alert: boolean;
  3117. on_location_ha_sensor_alert: boolean;
  3118. // First layer complete
  3119. on_first_layer_complete: boolean;
  3120. on_print_pause_upcoming: boolean;
  3121. on_app_message: boolean;
  3122. // Inventory stock alerts
  3123. on_stock_reorder_alert: boolean;
  3124. on_stock_break_alert: boolean;
  3125. // Print queue events
  3126. on_queue_job_added: boolean;
  3127. on_queue_job_assigned: boolean;
  3128. on_queue_job_started: boolean;
  3129. on_queue_job_waiting: boolean;
  3130. on_queue_job_skipped: boolean;
  3131. on_queue_job_failed: boolean;
  3132. on_queue_completed: boolean;
  3133. // Quiet hours
  3134. quiet_hours_enabled: boolean;
  3135. quiet_hours_start: string | null;
  3136. quiet_hours_end: string | null;
  3137. // Daily digest
  3138. daily_digest_enabled: boolean;
  3139. daily_digest_time: string | null;
  3140. // Printer filter
  3141. printer_id: number | null;
  3142. // Status tracking
  3143. last_success: string | null;
  3144. last_error: string | null;
  3145. last_error_at: string | null;
  3146. // Timestamps
  3147. created_at: string;
  3148. updated_at: string;
  3149. }
  3150. export interface NotificationProviderCreate {
  3151. name: string;
  3152. provider_type: ProviderType;
  3153. enabled?: boolean;
  3154. config: Record<string, unknown>;
  3155. attach_photo?: boolean;
  3156. // Print lifecycle events
  3157. on_print_start?: boolean;
  3158. on_print_complete?: boolean;
  3159. on_print_failed?: boolean;
  3160. on_print_stopped?: boolean;
  3161. on_print_progress?: boolean;
  3162. on_print_missing_spool_assignment?: boolean;
  3163. on_billing_charge_failed?: boolean;
  3164. // Printer status events
  3165. on_printer_offline?: boolean;
  3166. on_printer_error?: boolean;
  3167. on_ai_failure_detection?: boolean;
  3168. on_filament_low?: boolean;
  3169. on_maintenance_due?: boolean;
  3170. // AMS environmental alarms (regular AMS)
  3171. on_ams_humidity_high?: boolean;
  3172. on_ams_temperature_high?: boolean;
  3173. on_ams_drying_suspended?: boolean;
  3174. // AMS-HT environmental alarms
  3175. on_ams_ht_humidity_high?: boolean;
  3176. on_ams_ht_temperature_high?: boolean;
  3177. // Build plate detection
  3178. on_plate_not_empty?: boolean;
  3179. on_plate_clear_required?: boolean;
  3180. // Post-print outcome confirmation (#1898)
  3181. on_print_confirm_request?: boolean;
  3182. telegram_verdict_mode?: TelegramVerdictMode;
  3183. // Bed cooled
  3184. on_bed_cooled?: boolean;
  3185. on_ha_sensor_alert?: boolean;
  3186. on_location_ha_sensor_alert?: boolean;
  3187. // First layer complete
  3188. on_first_layer_complete?: boolean;
  3189. on_print_pause_upcoming?: boolean;
  3190. on_app_message?: boolean;
  3191. // Inventory stock alerts
  3192. on_stock_reorder_alert?: boolean;
  3193. on_stock_break_alert?: boolean;
  3194. // Print queue events
  3195. on_queue_job_added?: boolean;
  3196. on_queue_job_assigned?: boolean;
  3197. on_queue_job_started?: boolean;
  3198. on_queue_job_waiting?: boolean;
  3199. on_queue_job_skipped?: boolean;
  3200. on_queue_job_failed?: boolean;
  3201. on_queue_completed?: boolean;
  3202. // Quiet hours
  3203. quiet_hours_enabled?: boolean;
  3204. quiet_hours_start?: string | null;
  3205. quiet_hours_end?: string | null;
  3206. // Daily digest
  3207. daily_digest_enabled?: boolean;
  3208. daily_digest_time?: string | null;
  3209. // Printer filter
  3210. printer_id?: number | null;
  3211. }
  3212. export interface NotificationProviderUpdate {
  3213. name?: string;
  3214. provider_type?: ProviderType;
  3215. enabled?: boolean;
  3216. config?: Record<string, unknown>;
  3217. attach_photo?: boolean;
  3218. // Print lifecycle events
  3219. on_print_start?: boolean;
  3220. on_print_complete?: boolean;
  3221. on_print_failed?: boolean;
  3222. on_print_stopped?: boolean;
  3223. on_print_progress?: boolean;
  3224. on_print_missing_spool_assignment?: boolean;
  3225. on_billing_charge_failed?: boolean;
  3226. // Printer status events
  3227. on_printer_offline?: boolean;
  3228. on_printer_error?: boolean;
  3229. on_ai_failure_detection?: boolean;
  3230. on_filament_low?: boolean;
  3231. on_maintenance_due?: boolean;
  3232. // AMS environmental alarms (regular AMS)
  3233. on_ams_humidity_high?: boolean;
  3234. on_ams_temperature_high?: boolean;
  3235. on_ams_drying_suspended?: boolean;
  3236. // AMS-HT environmental alarms
  3237. on_ams_ht_humidity_high?: boolean;
  3238. on_ams_ht_temperature_high?: boolean;
  3239. // Build plate detection
  3240. on_plate_not_empty?: boolean;
  3241. on_plate_clear_required?: boolean;
  3242. // Post-print outcome confirmation (#1898)
  3243. on_print_confirm_request?: boolean;
  3244. telegram_verdict_mode?: TelegramVerdictMode;
  3245. // Bed cooled
  3246. on_bed_cooled?: boolean;
  3247. on_ha_sensor_alert?: boolean;
  3248. on_location_ha_sensor_alert?: boolean;
  3249. // First layer complete
  3250. on_first_layer_complete?: boolean;
  3251. on_print_pause_upcoming?: boolean;
  3252. on_app_message?: boolean;
  3253. // Inventory stock alerts
  3254. on_stock_reorder_alert?: boolean;
  3255. on_stock_break_alert?: boolean;
  3256. // Print queue events
  3257. on_queue_job_added?: boolean;
  3258. on_queue_job_assigned?: boolean;
  3259. on_queue_job_started?: boolean;
  3260. on_queue_job_waiting?: boolean;
  3261. on_queue_job_skipped?: boolean;
  3262. on_queue_job_failed?: boolean;
  3263. on_queue_completed?: boolean;
  3264. // Quiet hours
  3265. quiet_hours_enabled?: boolean;
  3266. quiet_hours_start?: string | null;
  3267. quiet_hours_end?: string | null;
  3268. // Daily digest
  3269. daily_digest_enabled?: boolean;
  3270. daily_digest_time?: string | null;
  3271. // Printer filter
  3272. printer_id?: number | null;
  3273. }
  3274. // GitHub Backup types
  3275. export type ScheduleType = 'hourly' | 'daily' | 'weekly';
  3276. export type GitProviderType = 'github' | 'gitea' | 'forgejo' | 'gitlab';
  3277. /** How many cloud accounts a backup would collect presets from. Counts only —
  3278. * with auth enabled the accounts belong to individual users, so the backup
  3279. * administrator sees how many, never whose. */
  3280. export interface CloudAccountCounts {
  3281. bambu: number;
  3282. orca: number;
  3283. }
  3284. export interface GitHubBackupConfig {
  3285. id: number;
  3286. repository_url: string;
  3287. has_token: boolean;
  3288. branch: string;
  3289. provider: GitProviderType;
  3290. allow_insecure_http: boolean;
  3291. schedule_enabled: boolean;
  3292. schedule_type: ScheduleType;
  3293. backup_kprofiles: boolean;
  3294. backup_cloud_profiles: boolean;
  3295. backup_settings: boolean;
  3296. backup_spools: boolean;
  3297. backup_archives: boolean;
  3298. enabled: boolean;
  3299. last_backup_at: string | null;
  3300. last_backup_status: string | null;
  3301. last_backup_message: string | null;
  3302. last_backup_commit_sha: string | null;
  3303. next_scheduled_run: string | null;
  3304. created_at: string;
  3305. updated_at: string;
  3306. }
  3307. export interface GitHubBackupConfigCreate {
  3308. repository_url: string;
  3309. access_token: string;
  3310. branch?: string;
  3311. provider?: GitProviderType;
  3312. allow_insecure_http?: boolean;
  3313. schedule_enabled?: boolean;
  3314. schedule_type?: ScheduleType;
  3315. backup_kprofiles?: boolean;
  3316. backup_cloud_profiles?: boolean;
  3317. backup_settings?: boolean;
  3318. backup_spools?: boolean;
  3319. backup_archives?: boolean;
  3320. enabled?: boolean;
  3321. }
  3322. export interface GitHubBackupLog {
  3323. id: number;
  3324. config_id: number;
  3325. started_at: string;
  3326. completed_at: string | null;
  3327. status: string;
  3328. trigger: string;
  3329. commit_sha: string | null;
  3330. files_changed: number;
  3331. error_message: string | null;
  3332. }
  3333. export interface GitHubBackupStatus {
  3334. configured: boolean;
  3335. enabled: boolean;
  3336. is_running: boolean;
  3337. restore_running: boolean;
  3338. progress: string | null;
  3339. last_backup_at: string | null;
  3340. last_backup_status: string | null;
  3341. next_scheduled_run: string | null;
  3342. }
  3343. // Restore from a Git backup (#2656). Cloud profiles are absent deliberately —
  3344. // the backup collector never writes them, so there is nothing to restore.
  3345. export type RestoreCategory = 'kprofiles' | 'settings' | 'spools' | 'archives';
  3346. export interface GitHubCommitInfo {
  3347. sha: string;
  3348. message: string;
  3349. author: string;
  3350. date: string;
  3351. }
  3352. export interface GitHubCommitListResponse {
  3353. success: boolean;
  3354. message: string;
  3355. branch: string;
  3356. commits: GitHubCommitInfo[];
  3357. }
  3358. /**
  3359. * Values the server interpolates into a translated note or preview detail.
  3360. * Kept to strings and numbers on purpose — anything richer would have to be
  3361. * formatted server-side and could not be translated.
  3362. */
  3363. export type GitHubRestoreParams = Record<string, string | number>;
  3364. export interface GitHubRestorePreviewCategory {
  3365. category: RestoreCategory;
  3366. available: boolean;
  3367. item_count: number;
  3368. /** English rendering. Used as i18next's defaultValue, never shown on its own. */
  3369. detail: string | null;
  3370. /** Key under backup.restoreFromGit.details, or null when there is no caveat. */
  3371. detail_code: string | null;
  3372. detail_params: GitHubRestoreParams;
  3373. }
  3374. export interface GitHubRestorePreview {
  3375. success: boolean;
  3376. message: string;
  3377. ref: string;
  3378. commit: GitHubCommitInfo | null;
  3379. metadata_version: string | null;
  3380. categories: GitHubRestorePreviewCategory[];
  3381. }
  3382. export interface GitHubRestoreRequest {
  3383. ref?: string;
  3384. categories: RestoreCategory[];
  3385. overwrite_existing?: boolean;
  3386. }
  3387. /**
  3388. * One tally note, as a translation code plus its parameters (#2656).
  3389. *
  3390. * Same contract as {@link LocalBackupPathCheck} one card down: the server picks
  3391. * the code and supplies typed params, and the client renders
  3392. * ``t(`backup.restoreFromGit.notes.${code}`, { ...params, defaultValue: message })``.
  3393. * A code the client does not know yet falls back to the English `message`
  3394. * rather than showing the raw key.
  3395. */
  3396. export interface GitHubRestoreNote {
  3397. code: string;
  3398. params: GitHubRestoreParams;
  3399. message: string;
  3400. }
  3401. export interface GitHubRestoreCategoryResult {
  3402. restored: number;
  3403. skipped: number;
  3404. failed: number;
  3405. notes: GitHubRestoreNote[];
  3406. }
  3407. export interface GitHubRestoreResponse {
  3408. success: boolean;
  3409. message: string;
  3410. log_id: number | null;
  3411. ref: string | null;
  3412. results: Record<string, GitHubRestoreCategoryResult>;
  3413. }
  3414. export interface LocalBackupStatus {
  3415. enabled: boolean;
  3416. schedule: string;
  3417. time: string;
  3418. retention: number;
  3419. path: string;
  3420. default_path: string;
  3421. is_running: boolean;
  3422. last_backup_at: string | null;
  3423. last_status: string | null;
  3424. last_message: string | null;
  3425. next_run: string | null;
  3426. timezone: string;
  3427. }
  3428. export interface LocalBackupFile {
  3429. filename: string;
  3430. size: number;
  3431. created_at: string;
  3432. }
  3433. /** Result of writing a probe file into the configured backup directory (#2544). */
  3434. export interface LocalBackupPathCheck {
  3435. writable: boolean;
  3436. path: string;
  3437. /** 'ok' | 'sandboxed' | 'read_only' | 'permission_denied' | 'no_space' | 'not_a_directory' | 'missing' | 'error' */
  3438. code: string;
  3439. /** Raw OS error, shown as-is under the translated explanation. */
  3440. detail: string | null;
  3441. /** Copy-pasteable fix (systemd drop-in, compose snippet) — not translated. */
  3442. remedy: string | null;
  3443. message: string;
  3444. /** 'container_ephemeral' — writable, but the backups die with the container. */
  3445. warning: string | null;
  3446. }
  3447. export interface ObicoDetectionEvent {
  3448. printer_id: number;
  3449. task_name: string;
  3450. timestamp: string;
  3451. current_p: number;
  3452. score: number;
  3453. class: 'safe' | 'warning' | 'failure';
  3454. detections: number;
  3455. }
  3456. export interface ObicoStatus {
  3457. is_running: boolean;
  3458. last_error: string | null;
  3459. per_printer: Record<string, { class: string; frame_count: number; score: number }>;
  3460. thresholds: { low: number; high: number; pause?: number };
  3461. history: ObicoDetectionEvent[];
  3462. enabled: boolean;
  3463. ml_url: string;
  3464. sensitivity: 'low' | 'medium' | 'high';
  3465. action: 'notify' | 'pause' | 'pause_and_off';
  3466. poll_interval: number;
  3467. external_url_configured: boolean;
  3468. }
  3469. // Lightweight subset served under printers:read for the printer-card badge (#1546)
  3470. export interface ObicoPrinterStatus {
  3471. enabled: boolean;
  3472. // null = all printers are monitored
  3473. monitored_printers: number[] | null;
  3474. per_printer: Record<string, { class: string; frame_count: number; score: number }>;
  3475. // null = no error, or the viewer lacks settings:read (error strings can embed config URLs)
  3476. last_error: string | null;
  3477. }
  3478. export interface ObicoTestConnection {
  3479. ok: boolean;
  3480. status_code: number | null;
  3481. body: string | null;
  3482. error: string | null;
  3483. // Whether the ML API accepted the token. null = not determined (the health
  3484. // check failed first, or the token probe itself errored).
  3485. auth_ok: boolean | null;
  3486. }
  3487. // How sure Gadget must be before suggesting a warning or pause (API levels 1-5).
  3488. export type OctoEverywhereConfidence = 'lowest' | 'low' | 'medium' | 'high' | 'highest';
  3489. export interface OctoEverywhereDetection {
  3490. class: 'safe' | 'warning' | 'failure' | 'error' | 'unknown';
  3491. print_quality: number | null;
  3492. frame_count: number;
  3493. error?: string | null;
  3494. error_code: string | null;
  3495. }
  3496. export interface OctoEverywhereDetectionEvent {
  3497. timestamp: string;
  3498. printer_id: number;
  3499. class: OctoEverywhereDetection['class'];
  3500. print_quality: number | null;
  3501. }
  3502. export interface OctoEverywhereStatus {
  3503. enabled: boolean;
  3504. api_key_configured: boolean;
  3505. confidence: OctoEverywhereConfidence;
  3506. action: 'notify' | 'pause' | 'pause_and_off';
  3507. poll_interval: number;
  3508. is_running: boolean;
  3509. last_error: string | null;
  3510. last_error_code: string | null;
  3511. per_printer: Record<string, OctoEverywhereDetection>;
  3512. history: OctoEverywhereDetectionEvent[];
  3513. notifications: { configured: boolean; uncovered_printers: number[] };
  3514. }
  3515. export interface OctoEverywherePrinterStatus {
  3516. enabled: boolean;
  3517. // null = all printers are monitored
  3518. monitored_printers: number[] | null;
  3519. per_printer: Record<string, OctoEverywhereDetection>;
  3520. last_error: string | null;
  3521. last_error_code: string | null;
  3522. }
  3523. export interface OctoEverywhereTestConnection {
  3524. ok: boolean;
  3525. status_code: number | null;
  3526. error: string | null;
  3527. error_code: string | null;
  3528. }
  3529. export interface GitHubTestConnectionResponse {
  3530. success: boolean;
  3531. message: string;
  3532. repo_name: string | null;
  3533. permissions: Record<string, boolean> | null;
  3534. // true = confirmed private, false = confirmed public/internal,
  3535. // null = could not determine. Backend rejects save unless true.
  3536. is_private: boolean | null;
  3537. }
  3538. export interface GitHubBackupTriggerResponse {
  3539. success: boolean;
  3540. message: string;
  3541. log_id: number | null;
  3542. commit_sha: string | null;
  3543. files_changed: number;
  3544. }
  3545. export interface NotificationTestRequest {
  3546. provider_type: ProviderType;
  3547. config: Record<string, unknown>;
  3548. attach_photo?: boolean;
  3549. /** The saved provider being edited: its stored secrets fill in the placeholders. */
  3550. provider_id?: number;
  3551. }
  3552. export interface NotificationTestResponse {
  3553. success: boolean;
  3554. message: string;
  3555. }
  3556. // Provider-specific config types for reference
  3557. export interface CallMeBotConfig {
  3558. phone: string;
  3559. apikey: string;
  3560. }
  3561. export interface NtfyConfig {
  3562. server?: string;
  3563. topic: string;
  3564. auth_token?: string | null;
  3565. }
  3566. export interface PushoverConfig {
  3567. user_key: string;
  3568. app_token: string;
  3569. priority?: number;
  3570. }
  3571. export interface NotifyConfig {
  3572. device_id: string;
  3573. token: string;
  3574. icon_url?: string;
  3575. group_type?: string;
  3576. live_activities?: boolean;
  3577. lock_screen_widgets?: boolean;
  3578. live_activity_privacy?: boolean;
  3579. live_activity_stage?: boolean;
  3580. live_activity_style?: 'bar' | 'segments' | 'none';
  3581. live_activity_metrics?: ('progress' | 'eta' | 'layers' | 'nozzle' | 'bed' | 'chamber')[];
  3582. live_activity_button_url?: string;
  3583. live_activity_symbol?: string;
  3584. live_activity_tint?: string;
  3585. time_sensitive?: boolean;
  3586. }
  3587. export interface TelegramConfig {
  3588. bot_token: string;
  3589. chat_id: string;
  3590. }
  3591. export interface EmailConfig {
  3592. smtp_server: string;
  3593. smtp_port?: number;
  3594. username: string;
  3595. password: string;
  3596. from_email: string;
  3597. to_email: string;
  3598. use_tls?: boolean;
  3599. }
  3600. // Notification Template types
  3601. export interface NotificationTemplate {
  3602. id: number;
  3603. event_type: string;
  3604. name: string;
  3605. title_template: string;
  3606. body_template: string;
  3607. is_default: boolean;
  3608. created_at: string;
  3609. updated_at: string;
  3610. }
  3611. export interface NotificationTemplateUpdate {
  3612. title_template?: string;
  3613. body_template?: string;
  3614. }
  3615. export interface EventVariablesResponse {
  3616. event_type: string;
  3617. event_name: string;
  3618. variables: string[];
  3619. supports_photo: boolean;
  3620. }
  3621. export interface TemplatePreviewRequest {
  3622. event_type: string;
  3623. title_template: string;
  3624. body_template: string;
  3625. }
  3626. export interface TemplatePreviewResponse {
  3627. title: string;
  3628. body: string;
  3629. }
  3630. // Notification Log types
  3631. export interface NotificationLogEntry {
  3632. id: number;
  3633. provider_id: number;
  3634. provider_name: string | null;
  3635. provider_type: string | null;
  3636. event_type: string;
  3637. title: string;
  3638. message: string;
  3639. success: boolean;
  3640. error_message: string | null;
  3641. printer_id: number | null;
  3642. printer_name: string | null;
  3643. created_at: string;
  3644. }
  3645. export interface NotificationLogStats {
  3646. total: number;
  3647. success_count: number;
  3648. failure_count: number;
  3649. by_event_type: Record<string, number>;
  3650. by_provider: Record<string, number>;
  3651. }
  3652. // Spoolman types
  3653. export interface SpoolmanStatus {
  3654. enabled: boolean;
  3655. connected: boolean;
  3656. url: string | null;
  3657. native_tags?: boolean; // Spoolman 0.27+ links tags natively
  3658. }
  3659. export interface SpoolmanTagMigrationReport {
  3660. dry_run: boolean;
  3661. moved: number[];
  3662. already: number;
  3663. slot_ids: number;
  3664. conflicts: Array<{ spool_id: number; tag: string; holder: number }>; // holder -1: a filament holds the tag
  3665. }
  3666. export interface SkippedSpool {
  3667. location: string;
  3668. reason: string;
  3669. filament_type: string | null;
  3670. color: string | null;
  3671. }
  3672. export interface SpoolmanSyncResult {
  3673. success: boolean;
  3674. synced_count: number;
  3675. skipped_count: number;
  3676. skipped: SkippedSpool[];
  3677. errors: string[];
  3678. }
  3679. export interface UnlinkedSpool {
  3680. id: number;
  3681. filament_name: string | null;
  3682. filament_vendor: string | null;
  3683. filament_material: string | null;
  3684. filament_color_hex: string | null;
  3685. remaining_weight: number | null;
  3686. location: string | null;
  3687. }
  3688. export interface LinkedSpoolInfo {
  3689. id: number;
  3690. remaining_weight: number | null;
  3691. filament_weight: number | null;
  3692. }
  3693. export interface LinkedSpoolsMap {
  3694. linked: Record<string, LinkedSpoolInfo>; // tag (uppercase) -> spool info
  3695. }
  3696. export interface SpoolmanVendor {
  3697. id: number;
  3698. name: string;
  3699. }
  3700. export interface SpoolmanFilamentEntry {
  3701. id: number;
  3702. name: string;
  3703. material: string | null;
  3704. color_hex: string | null;
  3705. color_name: string | null;
  3706. weight: number | null;
  3707. spool_weight: number | null;
  3708. vendor: SpoolmanVendor | null;
  3709. }
  3710. // Inventory types
  3711. // Label printing (#809). Mirror of backend.app.services.label_renderer.TemplateName.
  3712. export type SpoolLabelTemplate =
  3713. | 'ams_holder_74x33'
  3714. | 'ams_holder_75x55'
  3715. | 'box_40x30'
  3716. | 'box_62x29'
  3717. | 'avery_5160'
  3718. | 'avery_l7160';
  3719. // Mirror of backend.app.services.label_renderer.LabelField, in print order (#2981).
  3720. export const SPOOL_LABEL_FIELDS = [
  3721. 'brand',
  3722. 'material',
  3723. 'hex',
  3724. 'name',
  3725. 'location',
  3726. 'material_number',
  3727. 'temps',
  3728. 'weight',
  3729. 'note',
  3730. 'added',
  3731. 'qr',
  3732. 'spool_id',
  3733. ] as const;
  3734. export type SpoolLabelField = (typeof SPOOL_LABEL_FIELDS)[number];
  3735. // Mirror of DEFAULT_LABEL_FIELDS: what a label carried before fields were selectable.
  3736. export const DEFAULT_SPOOL_LABEL_FIELDS: SpoolLabelField[] = [
  3737. 'brand',
  3738. 'material',
  3739. 'hex',
  3740. 'name',
  3741. 'location',
  3742. 'qr',
  3743. 'spool_id',
  3744. ];
  3745. // A sheet of identical labels in a grid, in millimetres (#3296). Mirror of
  3746. // backend.app.schemas.label_template.SheetLayoutSpec.
  3747. export type LabelPageSize = 'a4' | 'letter';
  3748. export interface LabelSheetLayout {
  3749. page: LabelPageSize;
  3750. label_w_mm: number;
  3751. label_h_mm: number;
  3752. cols: number;
  3753. rows: number;
  3754. top_mm: number;
  3755. left_mm: number;
  3756. col_gap_mm: number;
  3757. row_gap_mm: number;
  3758. }
  3759. // A custom sheet saved under a name, shared by everyone on the install.
  3760. export interface SavedLabelTemplate {
  3761. id: number;
  3762. name: string;
  3763. layout: LabelSheetLayout;
  3764. created_at: string;
  3765. updated_at: string;
  3766. }
  3767. // A built-in template, or "custom" with the sheet itself in ``layout``.
  3768. export type SpoolLabelRequestTemplate = SpoolLabelTemplate | 'custom';
  3769. export interface PrintSpoolLabelsRequest {
  3770. spool_ids: number[];
  3771. template: SpoolLabelRequestTemplate;
  3772. layout?: LabelSheetLayout;
  3773. monochrome: boolean;
  3774. starting_position: number;
  3775. fields?: SpoolLabelField[];
  3776. format?: 'pdf' | 'png';
  3777. dpi?: 203 | 300 | 600;
  3778. }
  3779. export interface PreviewSpoolLabelRequest {
  3780. spool_id: number;
  3781. template: SpoolLabelRequestTemplate;
  3782. layout?: LabelSheetLayout;
  3783. monochrome: boolean;
  3784. fields: SpoolLabelField[];
  3785. }
  3786. export interface InventorySpool {
  3787. id: number;
  3788. material: string;
  3789. subtype: string | null;
  3790. color_name: string | null;
  3791. // True when color_name was synthesised from subtype because Spoolman has no
  3792. // stored value (Spoolman-backed inventory only). The edit form uses this to
  3793. // leave the input blank, so the user doesn't round-trip the synth value
  3794. // back to Spoolman as if it were a real user-set color_name (#1319).
  3795. color_name_is_synthesized?: boolean;
  3796. rgba: string | null;
  3797. // Multi-colour gradient stops (#1154): comma-separated 6/8-char hex.
  3798. extra_colors: string | null;
  3799. // Visual effect overlay: sparkle | wood | marble | glow | matte.
  3800. effect_type: string | null;
  3801. brand: string | null;
  3802. label_weight: number;
  3803. core_weight: number;
  3804. // Spoolman-backed inventory only: true when the spool has no tare of its
  3805. // own and core_weight is the filament type's. Absent for local spools (#2908).
  3806. core_weight_is_inherited?: boolean;
  3807. core_weight_catalog_id: number | null;
  3808. weight_used: number;
  3809. // Anchor for the resettable "Total Consumed" display (#1390). The
  3810. // counter shown on the Inventory page is `weight_used - weight_used_baseline`;
  3811. // remaining is still `label_weight - weight_used`, so "Reset usage to 0"
  3812. // zeroes the counter without disturbing remaining. Optional for back-compat
  3813. // with rows from a pre-migration DB snapshot — default to 0.
  3814. weight_used_baseline?: number;
  3815. slicer_filament: string | null;
  3816. slicer_filament_name: string | null;
  3817. nozzle_temp_min: number | null;
  3818. nozzle_temp_max: number | null;
  3819. note: string | null;
  3820. added_full: boolean | null;
  3821. last_used: string | null;
  3822. // Spoolman mode: when the spool was first printed with (#3407).
  3823. first_used?: string | null;
  3824. // Last drying (#2863): stamped when an AMS drying run of at least half its
  3825. // length ends, or set by hand. Temperature and hours are null when unknown.
  3826. last_dried_at?: string | null;
  3827. last_dried_temp?: number | null;
  3828. last_dried_hours?: number | null;
  3829. encode_time: string | null;
  3830. tag_uid: string | null;
  3831. tray_uuid: string | null;
  3832. data_origin: string | null;
  3833. tag_type: string | null;
  3834. archived_at: string | null;
  3835. created_at: string;
  3836. updated_at: string;
  3837. cost_per_kg: number | null;
  3838. // Spoolman mode: what prints are charged per kg, the spool's own price or
  3839. // else its filament's. Display only; the form edits cost_per_kg.
  3840. effective_cost_per_kg?: number | null;
  3841. last_scale_weight: number | null;
  3842. last_weighed_at: string | null;
  3843. // User-defined category + per-spool low-stock threshold override (#729).
  3844. category: string | null;
  3845. low_stock_threshold_pct: number | null;
  3846. // Internal material / article number (#2870) — the purchasing identifier
  3847. // shared by all spools of the same product.
  3848. material_number: string | null;
  3849. k_profiles?: SpoolKProfile[];
  3850. storage_location?: string | null;
  3851. location_id?: number | null;
  3852. // Supplier assignments (#2988). Absent in Spoolman mode — Spoolman's
  3853. // vendor is the manufacturer, not the seller, so there is no mapping.
  3854. suppliers?: SpoolSupplierLink[];
  3855. }
  3856. // ── Suppliers (#2988) ──────────────────────────────────────────────────────
  3857. /** Where filament is bought — distinct from brand (who made it). */
  3858. export interface Supplier {
  3859. id: number;
  3860. name: string;
  3861. website: string | null;
  3862. customer_number: string | null;
  3863. note: string | null;
  3864. /** Spools referencing this supplier; a referenced supplier cannot be deleted. */
  3865. spool_count: number;
  3866. created_at: string;
  3867. updated_at: string;
  3868. }
  3869. export interface SupplierInput {
  3870. name: string;
  3871. website?: string | null;
  3872. customer_number?: string | null;
  3873. note?: string | null;
  3874. }
  3875. /** One spool-to-supplier assignment as written by the spool dialog. */
  3876. export interface SpoolSupplierLinkInput {
  3877. supplier_id: number;
  3878. /** The supplier's own article number — NOT the internal material number. */
  3879. supplier_article_number?: string | null;
  3880. /** Quoted price for comparison — never the cost basis (spool.cost_per_kg). */
  3881. quoted_price_per_kg?: number | null;
  3882. /** Marks where this concrete spool was actually bought. */
  3883. is_purchase_source?: boolean;
  3884. }
  3885. export interface SpoolSupplierLink {
  3886. id: number;
  3887. supplier_id: number;
  3888. supplier_name: string;
  3889. supplier_article_number: string | null;
  3890. quoted_price_per_kg: number | null;
  3891. is_purchase_source: boolean;
  3892. }
  3893. /** Per-supplier inventory aggregate (#2988), purchase-source spools only. */
  3894. export interface SupplierStats {
  3895. supplier_id: number;
  3896. supplier_name: string;
  3897. spool_count: number;
  3898. remaining_g: number;
  3899. consumed_g: number;
  3900. cost: number;
  3901. }
  3902. /** Per-material-number inventory aggregate (#2870). */
  3903. export interface MaterialNumberStats {
  3904. material_number: string;
  3905. spool_count: number;
  3906. remaining_g: number;
  3907. consumed_g: number;
  3908. cost: number;
  3909. }
  3910. export interface SpoolmanBulkCreateResult {
  3911. created: InventorySpool[];
  3912. requested_count: number;
  3913. failed_count: number;
  3914. }
  3915. // ── CSV import/export (#1576) ──────────────────────────────────────────────
  3916. /** One row's outcome from the import preview / real import. */
  3917. export interface CsvImportRow {
  3918. row_number: number;
  3919. status: 'valid' | 'error' | 'skipped';
  3920. /** The id the spool is created with (#3520); null gets the next free one. */
  3921. keeps_id?: number | null;
  3922. reason: string | null;
  3923. material: string | null;
  3924. brand: string | null;
  3925. color_name: string | null;
  3926. rgba: string | null;
  3927. /** rgba/extra_colors/effect_type were filled from the Color Catalog. */
  3928. resolved_color: boolean;
  3929. /** The catalog match came from a different material's variant (no exact
  3930. * material match). Shown as a warning in the preview. */
  3931. cross_material_color: boolean;
  3932. /** An active spool with the same material+brand+color already exists.
  3933. * Informational only — the import still creates the row. */
  3934. duplicate_of_existing: boolean;
  3935. }
  3936. /** Dry-run preview: per-row classification, no rows written. */
  3937. export interface CsvImportPreview {
  3938. columns: string[];
  3939. total: number;
  3940. valid_count: number;
  3941. error_count: number;
  3942. skipped_count: number;
  3943. rows: CsvImportRow[];
  3944. warnings: string[];
  3945. }
  3946. /** Summary returned after a real (non-dry-run) import. */
  3947. export interface CsvImportResult {
  3948. created: number;
  3949. skipped: number;
  3950. errors: number;
  3951. error_rows: CsvImportRow[];
  3952. }
  3953. export interface SpoolUsageRecord {
  3954. id: number;
  3955. // null: the spool was deleted, its usage kept
  3956. spool_id: number | null;
  3957. // Spoolman mode: the Spoolman spool charged (#3407); spool_id is null then.
  3958. spoolman_spool_id?: number | null;
  3959. printer_id: number | null;
  3960. print_name: string | null;
  3961. weight_used: number;
  3962. percent_used: number;
  3963. status: string;
  3964. cost: number | null;
  3965. created_at: string;
  3966. }
  3967. export interface SpoolKProfile {
  3968. id: number;
  3969. spool_id: number;
  3970. printer_id: number;
  3971. extruder: number;
  3972. nozzle_diameter: string;
  3973. nozzle_type: string | null;
  3974. k_value: number;
  3975. name: string | null;
  3976. cali_idx: number | null;
  3977. setting_id: string | null;
  3978. created_at: string;
  3979. }
  3980. export interface SpoolKProfileInput {
  3981. printer_id: number;
  3982. extruder?: number;
  3983. nozzle_diameter?: string;
  3984. nozzle_type?: string | null;
  3985. k_value: number;
  3986. name?: string | null;
  3987. cali_idx?: number | null;
  3988. setting_id?: string | null;
  3989. }
  3990. /**
  3991. * One per-printer-model override of a spool's slicer filament preset.
  3992. *
  3993. * A cloud or Orca preset is bound to a printer model ("@BBL X1C"), so the
  3994. * spool's single `slicer_filament` is wrong as soon as the spool is used on a
  3995. * second model. `nozzle_diameter` is "" for the model's own default and a bare
  3996. * decimal ("0.2") for a per-hotend exception; the backend resolves
  3997. * exact (model, diameter) -> (model, "") -> the spool's own preset.
  3998. */
  3999. export interface SlotSpoolDefaults {
  4000. slicer_filament: string | null;
  4001. slicer_filament_name: string | null;
  4002. cali_idx: number | null;
  4003. k_value: number | null;
  4004. profile_name: string | null;
  4005. extruder: number | null;
  4006. nozzle_diameter: string;
  4007. }
  4008. export interface SpoolFilamentPresetInput {
  4009. printer_model: string;
  4010. nozzle_diameter: string;
  4011. slicer_filament: string | null;
  4012. slicer_filament_name: string | null;
  4013. }
  4014. export interface SpoolFilamentPreset extends SpoolFilamentPresetInput {
  4015. id: number;
  4016. spool_id: number;
  4017. created_at: string;
  4018. }
  4019. /**
  4020. * What a new spool of one product starts with (#1326): the slicer preset, the
  4021. * per-model preset overrides and the K profiles. `color_name` "" is the
  4022. * default for every colour of the product; one with a colour wins over it per
  4023. * preset and per hotend. Shared by both inventory modes.
  4024. */
  4025. export interface ProfileDefaultKey {
  4026. brand: string;
  4027. material: string;
  4028. subtype: string;
  4029. color_name: string;
  4030. }
  4031. export interface ProfileDefaultInput extends ProfileDefaultKey {
  4032. slicer_filament: string | null;
  4033. slicer_filament_name: string | null;
  4034. presets: SpoolFilamentPresetInput[];
  4035. k_profiles: SpoolKProfileInput[];
  4036. }
  4037. export interface ProfileDefault extends ProfileDefaultInput {
  4038. id: number;
  4039. updated_at: string;
  4040. }
  4041. /** Both levels of a product's default merged, as a create applies them. */
  4042. export interface ResolvedProfileDefault {
  4043. slicer_filament: string | null;
  4044. slicer_filament_name: string | null;
  4045. presets: SpoolFilamentPresetInput[];
  4046. k_profiles: SpoolKProfileInput[];
  4047. default_ids: number[];
  4048. }
  4049. /** One inventory-bound AMS slot, as returned by `/printers/{id}/inventory-remain`. */
  4050. export interface SlotMaterial {
  4051. ams_id: number;
  4052. tray_id: number;
  4053. global_tray_id: number;
  4054. /** Opaque grouping key from the backend. Two slots back each other up under
  4055. * AMS Filament Backup only when both `material_key` and `extruder` match.
  4056. * Never parse it — the format belongs to the backend's identity rule. */
  4057. material_key: string;
  4058. remaining_g: number;
  4059. /** 0 = right / single nozzle, 1 = left. */
  4060. extruder: number;
  4061. /** How the bound spool should be *named* — display only, never matched on.
  4062. * The printer has no brand field and reports no sub-brand for a
  4063. * third-party spool, so this is the only place a slot's real identity
  4064. * exists. Null when the binding resolves to a spool we cannot describe. */
  4065. spool?: SlotSpoolIdentity | null;
  4066. /** Per-kg rate a print off this spool is charged at; null when unpriced,
  4067. * which is charged at the default rate. Optional for an older backend. */
  4068. cost_per_kg?: number | null;
  4069. }
  4070. /** Display identity of an inventory-bound slot. See `SlotMaterial.spool`. */
  4071. export interface SlotSpoolIdentity {
  4072. brand: string | null;
  4073. material: string | null;
  4074. subtype: string | null;
  4075. color_name: string | null;
  4076. rgba: string | null;
  4077. /** Comma-separated hex stops for a multi-colour spool, and the effect
  4078. * overlay — the two things a tray record cannot carry, so a slot swatch
  4079. * can be drawn the way the inventory row draws it (#3159).
  4080. *
  4081. * Optional rather than required: the backend sends both keys on every
  4082. * binding, but a frontend running against an older one gets neither, and
  4083. * every reader here already falls back to a solid swatch. */
  4084. extra_colors?: string | null;
  4085. effect_type?: string | null;
  4086. }
  4087. export interface InventoryRemainResponse {
  4088. /** Currently-loaded, inventory-bound slots only — drives the prefer-lowest sort. */
  4089. inventory_remain_g: Record<string, number>;
  4090. /** Every inventory binding on the printer, with identity + extruder side. */
  4091. slot_materials: SlotMaterial[];
  4092. }
  4093. export interface SpoolAssignment {
  4094. id: number;
  4095. spool_id: number;
  4096. printer_id: number;
  4097. printer_name: string | null;
  4098. ams_id: number;
  4099. tray_id: number;
  4100. fingerprint_color: string | null;
  4101. fingerprint_type: string | null;
  4102. spool?: InventorySpool | null;
  4103. configured: boolean;
  4104. pending_config?: boolean; // Slot was empty at assign time; will configure on insert
  4105. created_at: string;
  4106. ams_label?: string | null; // User-defined friendly name for the AMS unit
  4107. printer_model?: string | null; // names a rack printer's external inputs "Ext-n" (utils/trayIds)
  4108. }
  4109. export interface FilamentSkuSettings {
  4110. id: number;
  4111. material: string;
  4112. subtype: string | null;
  4113. brand: string | null;
  4114. color_name: string | null;
  4115. lead_time_days: number;
  4116. safety_margin_value: number;
  4117. safety_margin_unit: 'days' | 'g';
  4118. alerts_snoozed: boolean;
  4119. }
  4120. export interface ShoppingListItem {
  4121. id: number;
  4122. material: string;
  4123. subtype: string | null;
  4124. brand: string | null;
  4125. color_name: string | null;
  4126. quantity_spools: number;
  4127. note: string | null;
  4128. status: 'pending' | 'purchased' | 'received';
  4129. purchased_at: string | null;
  4130. added_at: string;
  4131. }
  4132. export interface ShoppingListItemCreate {
  4133. material: string;
  4134. subtype: string | null;
  4135. brand: string | null;
  4136. color_name: string | null;
  4137. quantity_spools: number;
  4138. note?: string | null;
  4139. }
  4140. // Update types
  4141. export interface VersionInfo {
  4142. version: string;
  4143. repo: string;
  4144. }
  4145. export interface UpdateCheckResult {
  4146. update_available: boolean;
  4147. current_version: string;
  4148. latest_version: string | null;
  4149. release_name?: string;
  4150. release_notes?: string;
  4151. release_url?: string;
  4152. published_at?: string;
  4153. error?: string;
  4154. message?: string;
  4155. is_docker?: boolean;
  4156. is_ha_addon?: boolean;
  4157. is_windows_installer?: boolean;
  4158. update_method?: 'docker' | 'git' | 'ha_addon' | 'windows_installer';
  4159. installer_download_url?: string | null;
  4160. // Best-effort guess at the compose directory (#2664). Prefill only — the
  4161. // value the user saved lives on AppSettings.docker_compose_dir, so clearing
  4162. // that field falls back to this guess instead of resurrecting the old value.
  4163. compose_dir_detected?: string | null;
  4164. }
  4165. export interface UpdateStatus {
  4166. status: 'idle' | 'checking' | 'downloading' | 'installing' | 'complete' | 'error';
  4167. progress: number;
  4168. message: string;
  4169. error: string | null;
  4170. }
  4171. // Maintenance types
  4172. export interface MaintenanceType {
  4173. id: number;
  4174. name: string;
  4175. description: string | null;
  4176. default_interval_hours: number;
  4177. interval_type: 'hours' | 'days'; // "hours" = print hours, "days" = calendar days
  4178. icon: string | null;
  4179. wiki_url: string | null; // Documentation link
  4180. is_system: boolean;
  4181. created_at: string;
  4182. }
  4183. export interface MaintenanceTypeCreate {
  4184. name: string;
  4185. description?: string | null;
  4186. default_interval_hours?: number;
  4187. interval_type?: 'hours' | 'days';
  4188. icon?: string | null;
  4189. wiki_url?: string | null;
  4190. }
  4191. export interface MaintenanceStatus {
  4192. id: number;
  4193. printer_id: number;
  4194. printer_name: string;
  4195. printer_model: string | null;
  4196. maintenance_type_id: number;
  4197. maintenance_type_name: string;
  4198. maintenance_type_icon: string | null;
  4199. maintenance_type_wiki_url: string | null; // Custom wiki URL from type
  4200. enabled: boolean;
  4201. interval_hours: number; // For hours type: print hours; for days type: number of days
  4202. interval_type: 'hours' | 'days';
  4203. current_hours: number;
  4204. hours_since_maintenance: number;
  4205. hours_until_due: number;
  4206. days_since_maintenance: number | null; // For days type
  4207. days_until_due: number | null; // For days type
  4208. is_due: boolean;
  4209. is_warning: boolean;
  4210. last_performed_at: string | null;
  4211. }
  4212. export interface PrinterMaintenanceOverview {
  4213. printer_id: number;
  4214. printer_name: string;
  4215. printer_model: string | null;
  4216. total_print_hours: number;
  4217. maintenance_items: MaintenanceStatus[];
  4218. due_count: number;
  4219. warning_count: number;
  4220. }
  4221. // One reset in a printer's maintenance log. The names are as they were at the
  4222. // reset; the ids are null once the printer or custom task is deleted.
  4223. export interface MaintenanceLogEntry {
  4224. id: number;
  4225. printer_id: number | null;
  4226. printer_name: string;
  4227. maintenance_type_id: number | null;
  4228. maintenance_type_name: string;
  4229. hours_at_maintenance: number;
  4230. notes: string | null;
  4231. performed_by_id: number | null;
  4232. performed_by_username: string | null; // null when authentication was off
  4233. performed_at: string;
  4234. }
  4235. export interface MaintenanceLogPage {
  4236. items: MaintenanceLogEntry[];
  4237. total: number;
  4238. }
  4239. // Must match MAINTENANCE_NOTES_MAX_LENGTH in backend/app/schemas/maintenance.py.
  4240. export const MAINTENANCE_NOTES_MAX_LENGTH = 10000;
  4241. // External Links (sidebar)
  4242. export interface ExternalLink {
  4243. id: number;
  4244. name: string;
  4245. url: string;
  4246. icon: string;
  4247. open_in_new_tab: boolean;
  4248. custom_icon: string | null;
  4249. sort_order: number;
  4250. created_at: string;
  4251. updated_at: string;
  4252. /** Count reported by the app the link points to, while it keeps reporting. */
  4253. badge_count?: number | null;
  4254. }
  4255. export interface ExternalLinkCreate {
  4256. name: string;
  4257. url: string;
  4258. icon: string;
  4259. open_in_new_tab?: boolean;
  4260. }
  4261. export interface ExternalLinkUpdate {
  4262. name?: string;
  4263. url?: string;
  4264. icon?: string;
  4265. open_in_new_tab?: boolean;
  4266. }
  4267. // Finance types
  4268. export interface CostCenterSummary {
  4269. id: number;
  4270. name: string;
  4271. is_private: boolean;
  4272. owner_user_id: number | null;
  4273. is_active: boolean;
  4274. total_balance: number;
  4275. total_budget: number | null;
  4276. monthly_budget: number | null;
  4277. budget_mode: 'none' | 'total' | 'monthly';
  4278. budget_limit: number | null;
  4279. budget_used: number | null;
  4280. budget_available: number | null;
  4281. can_print: boolean;
  4282. }
  4283. export interface CostCenterCreateRequest {
  4284. name: string;
  4285. total_budget?: number | null;
  4286. monthly_budget?: number | null;
  4287. is_active?: boolean;
  4288. }
  4289. export interface CostCenterBudgetUpdateRequest {
  4290. total_budget?: number | null;
  4291. monthly_budget?: number | null;
  4292. }
  4293. export interface CostCenterUpdateRequest {
  4294. name?: string;
  4295. is_active?: boolean;
  4296. }
  4297. export interface CostCenterMemberRequest {
  4298. user_id: number;
  4299. can_print?: boolean;
  4300. }
  4301. export interface CostCenterMemberResponse {
  4302. id: number;
  4303. cost_center_id: number;
  4304. user_id: number;
  4305. can_print: boolean;
  4306. created_at: string;
  4307. }
  4308. export interface CostCenterDetail extends CostCenterSummary {
  4309. members: CostCenterMemberResponse[];
  4310. }
  4311. export interface WalletBalance {
  4312. user_id: number;
  4313. balance: number;
  4314. currency: string;
  4315. updated_at: string | null;
  4316. }
  4317. export type WalletTransactionType = 'print_charge' | 'deposit' | 'withdraw' | 'manual_adjustment';
  4318. export interface WalletTransaction {
  4319. id: number;
  4320. user_id: number | null; // null once the user is deleted
  4321. cost_center_id: number | null;
  4322. transaction_type: WalletTransactionType;
  4323. amount: number;
  4324. balance_after: number | null;
  4325. description: string | null;
  4326. created_by_user_id: number | null;
  4327. print_run_id: string | null;
  4328. print_archive_id: number | null;
  4329. print_queue_id: number | null;
  4330. created_at: string;
  4331. }
  4332. export interface WalletTransactionListResponse {
  4333. items: WalletTransaction[];
  4334. total: number;
  4335. limit: number;
  4336. offset: number;
  4337. }
  4338. export interface WalletAdjustmentRequest {
  4339. amount: number;
  4340. description?: string;
  4341. cost_center_id?: number | null;
  4342. }
  4343. export interface WalletAdjustmentResponse {
  4344. transaction: WalletTransaction;
  4345. balance: WalletBalance;
  4346. }
  4347. export interface TransactionEditRequest {
  4348. user_id?: number | null;
  4349. cost_center_id?: number | null;
  4350. amount?: number | null;
  4351. description?: string | null;
  4352. }
  4353. export interface ManualPrintRequest {
  4354. user_id: number;
  4355. cost_center_id: number;
  4356. amount: number;
  4357. description?: string | null;
  4358. created_at?: string | null;
  4359. }
  4360. // Permission type - all available permissions
  4361. export type Permission =
  4362. | 'printers:read' | 'printers:create' | 'printers:update' | 'printers:delete' | 'printers:control' | 'printers:files' | 'printers:ams_rfid' | 'printers:clear_plate'
  4363. | 'archives:read' | 'archives:read_own' | 'archives:read_all' | 'archives:create'
  4364. | 'archives:update_own' | 'archives:update_all' | 'archives:delete_own' | 'archives:delete_all'
  4365. | 'archives:reprint_own' | 'archives:reprint_all' | 'archives:purge'
  4366. | 'queue:read' | 'queue:read_own' | 'queue:read_all' | 'queue:create'
  4367. | 'queue:update_own' | 'queue:update_all' | 'queue:delete_own' | 'queue:delete_all'
  4368. | 'queue:reorder' | 'queue:start_unreviewed'
  4369. | 'library:read' | 'library:read_own' | 'library:read_all' | 'library:upload'
  4370. | 'library:update_own' | 'library:update_all' | 'library:delete_own' | 'library:delete_all'
  4371. | 'library:purge'
  4372. | 'projects:read' | 'projects:create' | 'projects:update' | 'projects:delete'
  4373. | 'filaments:read' | 'filaments:create' | 'filaments:update' | 'filaments:delete'
  4374. | 'inventory:read' | 'inventory:create' | 'inventory:update' | 'inventory:delete' | 'inventory:view_assignments'
  4375. | 'inventory:forecast_read' | 'inventory:forecast_write'
  4376. | 'smart_plugs:read' | 'smart_plugs:create' | 'smart_plugs:update' | 'smart_plugs:delete' | 'smart_plugs:control'
  4377. | 'camera:view'
  4378. | 'maintenance:read' | 'maintenance:create' | 'maintenance:update' | 'maintenance:delete'
  4379. | 'kprofiles:read' | 'kprofiles:create' | 'kprofiles:update' | 'kprofiles:delete'
  4380. | 'notifications:read' | 'notifications:create' | 'notifications:update' | 'notifications:delete' | 'notifications:user_email'
  4381. | 'notification_templates:read' | 'notification_templates:update'
  4382. | 'external_links:read' | 'external_links:create' | 'external_links:update' | 'external_links:delete'
  4383. | 'discovery:scan'
  4384. | 'firmware:read' | 'firmware:update'
  4385. | 'ams_history:read'
  4386. | 'cost_centers:read_own' | 'cost_centers:read_all' | 'cost_centers:modify' | 'cost_centers:create'
  4387. | 'stats:read' | 'stats:filter_by_user'
  4388. | 'system:read'
  4389. | 'settings:read' | 'settings:update' | 'settings:backup' | 'settings:restore'
  4390. | 'github:backup' | 'github:restore'
  4391. | 'cloud:auth' | 'orca_cloud:auth'
  4392. | 'makerworld:view' | 'makerworld:import'
  4393. | 'manyfold:view' | 'manyfold:import'
  4394. | 'api_keys:read' | 'api_keys:create' | 'api_keys:update' | 'api_keys:delete'
  4395. | 'users:read' | 'users:read_slim' | 'users:create' | 'users:update' | 'users:delete'
  4396. | 'groups:read' | 'groups:create' | 'groups:update' | 'groups:delete'
  4397. | 'pipelines:read' | 'pipelines:write' | 'pipelines:run'
  4398. | 'websocket:connect';
  4399. // Group types
  4400. export interface GroupBrief {
  4401. id: number;
  4402. name: string;
  4403. }
  4404. export interface Group {
  4405. id: number;
  4406. name: string;
  4407. description: string | null;
  4408. permissions: Permission[];
  4409. is_system: boolean;
  4410. /** Members only see the printers in printer_ids plus every printer in locations (#1727) */
  4411. restrict_printers: boolean;
  4412. printer_ids: number[];
  4413. /** Matched against Printer.location, so printers added there later are included */
  4414. locations: string[];
  4415. user_count: number;
  4416. created_at: string;
  4417. updated_at: string;
  4418. }
  4419. export interface GroupDetail extends Group {
  4420. users: Array<{ id: number; username: string; is_active: boolean }>;
  4421. }
  4422. export interface GroupCreate {
  4423. name: string;
  4424. description?: string;
  4425. permissions: Permission[];
  4426. restrict_printers?: boolean;
  4427. printer_ids?: number[];
  4428. locations?: string[];
  4429. }
  4430. export interface GroupUpdate {
  4431. name?: string;
  4432. description?: string;
  4433. permissions?: Permission[];
  4434. restrict_printers?: boolean;
  4435. printer_ids?: number[];
  4436. locations?: string[];
  4437. }
  4438. export interface PermissionInfo {
  4439. value: Permission;
  4440. label: string;
  4441. }
  4442. export interface PermissionCategory {
  4443. name: string;
  4444. permissions: PermissionInfo[];
  4445. }
  4446. export interface PermissionsListResponse {
  4447. categories: PermissionCategory[];
  4448. all_permissions: Permission[];
  4449. }
  4450. // User email notification preferences
  4451. export interface UserEmailPreferences {
  4452. notify_print_start: boolean;
  4453. notify_print_complete: boolean;
  4454. notify_print_failed: boolean;
  4455. notify_print_stopped: boolean;
  4456. }
  4457. // Auth types
  4458. export interface LoginRequest {
  4459. username: string;
  4460. password: string;
  4461. }
  4462. export interface LoginResponse {
  4463. access_token?: string;
  4464. token_type?: string;
  4465. user?: UserResponse;
  4466. /** Set when 2FA verification is required before a full token is issued. */
  4467. requires_2fa?: boolean;
  4468. pre_auth_token?: string;
  4469. two_fa_methods?: string[];
  4470. }
  4471. export interface UserResponse {
  4472. id: number;
  4473. username: string;
  4474. email?: string;
  4475. role: string; // Deprecated, kept for backward compatibility
  4476. is_active: boolean;
  4477. is_admin: boolean; // Computed from role and group membership
  4478. auth_source: string; // "local" or "ldap"
  4479. groups: GroupBrief[];
  4480. permissions: Permission[]; // All permissions from groups
  4481. created_at: string;
  4482. }
  4483. /**
  4484. * Just enough to label an owner id (#1894). Backed by GET /users/slim, which
  4485. * is readable with `users:read_slim` as well as the admin-level `users:read`
  4486. * -- use it anywhere a screen only needs to turn a `created_by_id` into a
  4487. * name, so operators are not forced into the full listing to get one.
  4488. */
  4489. export interface UserSlim {
  4490. id: number;
  4491. username: string;
  4492. }
  4493. export interface UserCreate {
  4494. username: string;
  4495. password?: string; // Optional when advanced auth is enabled
  4496. email?: string;
  4497. role: string;
  4498. group_ids?: number[];
  4499. }
  4500. export interface UserUpdate {
  4501. username?: string;
  4502. password?: string;
  4503. email?: string;
  4504. role?: string;
  4505. is_active?: boolean;
  4506. group_ids?: number[];
  4507. }
  4508. export interface SetupRequest {
  4509. auth_enabled: boolean;
  4510. admin_username?: string;
  4511. admin_password?: string;
  4512. }
  4513. export interface ForgotPasswordRequest {
  4514. email: string;
  4515. }
  4516. export interface ForgotPasswordResponse {
  4517. message: string;
  4518. }
  4519. export interface ResetPasswordRequest {
  4520. user_id: number;
  4521. }
  4522. export interface ResetPasswordResponse {
  4523. message: string;
  4524. }
  4525. export interface SMTPSettings {
  4526. smtp_host: string;
  4527. smtp_port: number;
  4528. smtp_username?: string;
  4529. smtp_password?: string;
  4530. smtp_security: 'starttls' | 'ssl' | 'none';
  4531. smtp_auth_enabled: boolean;
  4532. smtp_from_email: string;
  4533. smtp_from_name: string;
  4534. }
  4535. // 2FA / MFA interfaces
  4536. export interface TwoFAStatus {
  4537. totp_enabled: boolean;
  4538. email_otp_enabled: boolean;
  4539. backup_codes_remaining: number;
  4540. }
  4541. export interface TOTPSetupResponse {
  4542. secret: string;
  4543. qr_code_b64: string;
  4544. issuer: string;
  4545. }
  4546. export interface TOTPEnableResponse {
  4547. message: string;
  4548. backup_codes: string[];
  4549. }
  4550. export interface BackupCodesResponse {
  4551. backup_codes: string[];
  4552. message: string;
  4553. }
  4554. export interface TwoFAVerifyRequest {
  4555. pre_auth_token: string;
  4556. code: string;
  4557. method: 'totp' | 'email' | 'backup';
  4558. }
  4559. /**
  4560. * A URL that is known to be same-origin (a relative path starting with ``/``).
  4561. *
  4562. * Branded so that producers of same-origin URLs (e.g. ``api.oidcProviderIconUrl``)
  4563. * can be distinguished from arbitrary strings at the type level. The brand
  4564. * is compile-time only; at runtime these are plain strings.
  4565. *
  4566. * Purpose: CSP-safe image sources for ``<img src=...>``. The strict
  4567. * ``img-src 'self' data: blob:`` CSP rejects anything that isn't same-origin,
  4568. * so callers that demand a ``SameOriginUrl`` get a compile-time guarantee
  4569. * that no external URL slips through.
  4570. */
  4571. export type SameOriginUrl = string & { readonly __brand: 'SameOriginUrl' };
  4572. // OIDC interfaces
  4573. /** What the unauthenticated GET /auth/oidc/providers returns (#3107): only
  4574. * what the login page renders. The full provider, group sync config
  4575. * included, needs the admin-only /auth/oidc/providers/all. */
  4576. export interface OIDCProviderPublic {
  4577. id: number;
  4578. name: string;
  4579. has_icon: boolean;
  4580. is_autologin: boolean;
  4581. }
  4582. export interface OIDCProvider {
  4583. id: number;
  4584. name: string;
  4585. issuer_url: string;
  4586. client_id: string;
  4587. scopes: string;
  4588. is_enabled: boolean;
  4589. auto_create_users: boolean;
  4590. auto_link_existing_accounts: boolean;
  4591. email_claim: string;
  4592. require_email_verified: boolean;
  4593. // #3107 — group sync. Empty mapping = sync off (default).
  4594. group_claim?: string;
  4595. group_mapping?: Record<string, string>;
  4596. icon_url?: string | null;
  4597. default_group_id?: number | null;
  4598. // True when the backend has cached icon bytes for this provider.
  4599. // Login page / admin preview consume this via the proxy URL
  4600. // /api/v1/auth/oidc/providers/{id}/icon (#1333) so the SPA never
  4601. // hotlinks the external icon URL — that would require loosening
  4602. // the strict img-src CSP. Required, not optional: the backend always
  4603. // includes this field in the response (Pydantic default-False is
  4604. // populated unconditionally in the route handler).
  4605. has_icon: boolean;
  4606. // #1589: when true, the LoginPage redirects unauthenticated visitors
  4607. // straight to this provider on mount. At most one provider may carry this.
  4608. is_autologin: boolean;
  4609. // #2593: defined by BAMBUDDY_OIDC_* and rewritten from the environment on
  4610. // every boot. The API answers 409 to any write, so the settings UI must not
  4611. // offer edit/delete controls that cannot succeed. Optional so a response
  4612. // from an older backend still type-checks.
  4613. is_env_managed?: boolean;
  4614. }
  4615. export interface OIDCProviderCreate {
  4616. name: string;
  4617. issuer_url: string;
  4618. client_id: string;
  4619. client_secret: string;
  4620. scopes?: string;
  4621. is_enabled?: boolean;
  4622. auto_create_users?: boolean;
  4623. auto_link_existing_accounts?: boolean;
  4624. email_claim?: string;
  4625. require_email_verified?: boolean;
  4626. // #3107 — group sync. Omit both to leave them unchanged on update.
  4627. group_claim?: string;
  4628. group_mapping?: Record<string, string>;
  4629. icon_url?: string | null;
  4630. default_group_id?: number | null;
  4631. is_autologin?: boolean; // #1589
  4632. }
  4633. export interface OIDCLink {
  4634. id: number;
  4635. provider_id: number;
  4636. provider_name: string;
  4637. provider_email?: string | null;
  4638. created_at: string;
  4639. }
  4640. export interface TestSMTPRequest {
  4641. test_recipient: string;
  4642. // The form's settings, tested before they are saved. An empty password
  4643. // keeps the saved one.
  4644. smtp?: SMTPSettings;
  4645. }
  4646. export interface TestSMTPResponse {
  4647. success: boolean;
  4648. message: string;
  4649. }
  4650. export interface AdvancedAuthStatus {
  4651. advanced_auth_enabled: boolean;
  4652. smtp_configured: boolean;
  4653. // #1589: false hides the username/password form on the LoginPage; the env
  4654. // var BAMBUDDY_LOCAL_LOGIN=true on the server flips this back to true so
  4655. // the recovery path remains visible.
  4656. local_login_enabled: boolean;
  4657. // #1589: when set, LoginPage redirects to this provider's authorize URL
  4658. // on mount unless ?fallback=local is in the URL or the redirect times out.
  4659. autologin_provider_id: number | null;
  4660. }
  4661. export interface LDAPStatus {
  4662. ldap_enabled: boolean;
  4663. ldap_configured: boolean;
  4664. }
  4665. export interface EncryptionRowCounts {
  4666. oidc_providers: number;
  4667. user_totp: number;
  4668. }
  4669. export interface EncryptionStatus {
  4670. key_configured: boolean;
  4671. key_source: 'env' | 'file' | 'generated' | 'none';
  4672. legacy_plaintext_rows: EncryptionRowCounts;
  4673. encrypted_rows: EncryptionRowCounts;
  4674. decryption_broken: boolean;
  4675. // B2: count of rows skipped during the last legacy re-encryption migration.
  4676. // Surfaced via a yellow secondary banner in SecurityStatusCard.
  4677. migration_error_count: number;
  4678. }
  4679. export interface LDAPTestRequest {
  4680. ldap_server_url?: string;
  4681. ldap_bind_dn?: string;
  4682. ldap_bind_password?: string;
  4683. ldap_search_base?: string;
  4684. ldap_user_filter?: string;
  4685. ldap_security?: string;
  4686. }
  4687. export interface LDAPTestResponse {
  4688. success: boolean;
  4689. message: string;
  4690. }
  4691. export interface LDAPSearchResult {
  4692. username: string;
  4693. email: string | null;
  4694. display_name: string | null;
  4695. dn: string;
  4696. already_provisioned: boolean;
  4697. }
  4698. export interface SetupResponse {
  4699. auth_enabled: boolean;
  4700. admin_created?: boolean;
  4701. }
  4702. export interface AuthStatus {
  4703. auth_enabled: boolean;
  4704. requires_setup: boolean;
  4705. }
  4706. // API functions
  4707. export interface QueueHistoryFilters {
  4708. printerId?: number | null;
  4709. status?: string;
  4710. location?: string;
  4711. }
  4712. export interface QueueHistoryParams extends QueueHistoryFilters {
  4713. sortBy?: 'date' | 'name' | 'printer';
  4714. // Flips the default order: newest first by date, A to Z by name or printer.
  4715. reverse?: boolean;
  4716. limit?: number;
  4717. offset?: number;
  4718. }
  4719. export interface QueueHistoryPage {
  4720. // The page in display order, then any other runs of the batches on it.
  4721. items: PrintQueueItem[];
  4722. total: number;
  4723. locations: string[];
  4724. }
  4725. function queueHistorySearch(params: QueueHistoryParams): URLSearchParams {
  4726. const search = new URLSearchParams();
  4727. if (params.printerId) search.set('printer_id', String(params.printerId));
  4728. if (params.status) search.set('status', params.status);
  4729. if (params.location) search.set('location', params.location);
  4730. if (params.sortBy) search.set('sort_by', params.sortBy);
  4731. if (params.reverse) search.set('reverse', 'true');
  4732. if (params.limit !== undefined) search.set('limit', String(params.limit));
  4733. if (params.offset) search.set('offset', String(params.offset));
  4734. return search;
  4735. }
  4736. // Per-printer reads that a page showing every printer makes once per printer,
  4737. // coalesced into one bulk request per few milliseconds (see ./batch). Each
  4738. // keeps its single-printer request for a lone id.
  4739. const idsParam = (ids: number[]) => `ids=${ids.join(',')}`;
  4740. const printerStatusBatch = batched(
  4741. (id) => request<PrinterStatus>(`/printers/${id}/status`),
  4742. async (ids) => byField(await request<PrinterStatus[]>(`/bulk/printer-statuses?${idsParam(ids)}`), (s) => s.id),
  4743. );
  4744. const slotPresetsBatch = batched(
  4745. (id) => request<Record<number, SlotPresetMapping>>(`/printers/${id}/slot-presets`),
  4746. async (ids) => byId(await request<Record<string, Record<number, SlotPresetMapping>>>(`/bulk/slot-presets?${idsParam(ids)}`)),
  4747. );
  4748. const amsLabelsBatch = batched(
  4749. (id) => request<Record<number, string>>(`/printers/${id}/ams-labels`),
  4750. async (ids) => byId(await request<Record<string, Record<number, string>>>(`/bulk/ams-labels?${idsParam(ids)}`)),
  4751. );
  4752. type PrinterCardPlugs = { plug: SmartPlug | null; scripts: SmartPlug[] };
  4753. const cardPlugs = async (ids: number[]) =>
  4754. byId(await request<Record<string, PrinterCardPlugs>>(`/bulk/card-plugs?${idsParam(ids)}`));
  4755. const smartPlugBatch = batched(
  4756. (id) => request<SmartPlug | null>(`/smart-plugs/by-printer/${id}`),
  4757. async (ids) => new Map([...(await cardPlugs(ids))].map(([id, plugs]) => [id, plugs.plug])),
  4758. );
  4759. const scriptPlugsBatch = batched(
  4760. (id) => request<SmartPlug[]>(`/smart-plugs/by-printer/${id}/scripts`),
  4761. async (ids) => new Map([...(await cardPlugs(ids))].map(([id, plugs]) => [id, plugs.scripts])),
  4762. );
  4763. const haSensorReadingsBatch = batched(
  4764. (id) => request<PrinterHASensorReading[]>(`/ha-sensors/by-printer/${id}/readings`),
  4765. async (ids) => byId(await request<Record<string, PrinterHASensorReading[]>>(`/bulk/ha-sensor-readings?${idsParam(ids)}`)),
  4766. );
  4767. const firmwareUpdateBatch = batched(
  4768. (id) => request<FirmwareUpdateInfo>(`/firmware/updates/${id}`),
  4769. async (ids) =>
  4770. byField(await request<FirmwareUpdateInfo[]>(`/bulk/firmware-updates?${idsParam(ids)}`), (u) => u.printer_id),
  4771. );
  4772. // One batcher per status asked for: the bulk route takes a single status list.
  4773. const printerQueueBatches = new Map<string, (id: number) => Promise<PrintQueueItem[]>>();
  4774. const printerQueueBatch = (status: string) => {
  4775. let batch = printerQueueBatches.get(status);
  4776. if (!batch) {
  4777. batch = batched(
  4778. (id) => request<PrintQueueItem[]>(`/queue/?printer_id=${id}&status=${encodeURIComponent(status)}`),
  4779. async (ids) =>
  4780. byId(
  4781. await request<Record<string, PrintQueueItem[]>>(
  4782. `/bulk/printer-queues?${idsParam(ids)}&status=${encodeURIComponent(status)}`,
  4783. ),
  4784. ),
  4785. );
  4786. printerQueueBatches.set(status, batch);
  4787. }
  4788. return batch;
  4789. };
  4790. const foldersByArchiveBatch = batched(
  4791. (id) => request<LibraryFolder[]>(`/library/folders/by-archive/${id}`),
  4792. async (ids) => byId(await request<Record<string, LibraryFolder[]>>(`/bulk/archive-folders?${idsParam(ids)}`)),
  4793. );
  4794. export const api = {
  4795. // Overlay branding
  4796. getOverlayLogo: async (token: string | null, signal?: AbortSignal): Promise<Blob | null> => {
  4797. const endpoint = token ? `/overlay-branding/logo?token=${encodeURIComponent(token)}` : '/settings/overlay-logo';
  4798. const response = await fetch(`${API_BASE}${endpoint}`, {
  4799. signal, cache: 'no-store',
  4800. headers: !token && authToken ? { Authorization: `Bearer ${authToken}` } : {},
  4801. });
  4802. if (response.status === 404) return null;
  4803. if (!response.ok) throw new Error(`HTTP ${response.status}`);
  4804. return response.blob();
  4805. },
  4806. uploadOverlayLogo: async (file: File): Promise<void> => {
  4807. const body = new FormData();
  4808. body.append('file', file);
  4809. const response = await fetch(`${API_BASE}/settings/overlay-logo`, {
  4810. method: 'POST', body,
  4811. headers: authToken ? { Authorization: `Bearer ${authToken}` } : {},
  4812. });
  4813. if (!response.ok) {
  4814. const error = await response.json().catch(() => ({}));
  4815. const detail = error?.detail;
  4816. const message = typeof detail === 'string' ? detail : detail?.message;
  4817. throw new Error(typeof message === 'string' && message ? message : `HTTP ${response.status}`);
  4818. }
  4819. },
  4820. deleteOverlayLogo: () => request<{ status: string }>('/settings/overlay-logo', { method: 'DELETE' }),
  4821. // Authentication
  4822. getAuthStatus: () => request<AuthStatus>('/auth/status'),
  4823. setupAuth: (data: SetupRequest) =>
  4824. request<SetupResponse>('/auth/setup', {
  4825. method: 'POST',
  4826. body: JSON.stringify(data),
  4827. }),
  4828. login: (data: LoginRequest) =>
  4829. request<LoginResponse>('/auth/login', {
  4830. method: 'POST',
  4831. body: JSON.stringify(data),
  4832. }),
  4833. logout: () =>
  4834. request<{ message: string }>('/auth/logout', {
  4835. method: 'POST',
  4836. }),
  4837. getCurrentUser: () => request<UserResponse>('/auth/me'),
  4838. disableAuth: () =>
  4839. request<{ message: string; auth_enabled: boolean }>('/auth/disable', {
  4840. method: 'POST',
  4841. }),
  4842. // Advanced Authentication
  4843. testSMTP: (data: TestSMTPRequest) =>
  4844. request<TestSMTPResponse>('/auth/smtp/test', {
  4845. method: 'POST',
  4846. body: JSON.stringify(data),
  4847. }),
  4848. getSMTPSettings: () => request<SMTPSettings | null>('/auth/smtp'),
  4849. saveSMTPSettings: (data: SMTPSettings) =>
  4850. request<{ message: string }>('/auth/smtp', {
  4851. method: 'POST',
  4852. body: JSON.stringify(data),
  4853. }),
  4854. enableAdvancedAuth: () =>
  4855. request<{ message: string; advanced_auth_enabled: boolean }>('/auth/advanced-auth/enable', {
  4856. method: 'POST',
  4857. }),
  4858. disableAdvancedAuth: () =>
  4859. request<{ message: string; advanced_auth_enabled: boolean }>('/auth/advanced-auth/disable', {
  4860. method: 'POST',
  4861. }),
  4862. getAdvancedAuthStatus: () => request<AdvancedAuthStatus>('/auth/advanced-auth/status'),
  4863. // LDAP Authentication
  4864. getLDAPStatus: () => request<LDAPStatus>('/auth/ldap/status'),
  4865. getEncryptionStatus: () => request<EncryptionStatus>('/auth/encryption-status'),
  4866. // form: the settings being edited, tested before they are saved. An empty
  4867. // bind password keeps the saved one.
  4868. testLDAP: (form?: LDAPTestRequest) =>
  4869. request<LDAPTestResponse>('/auth/ldap/test', {
  4870. method: 'POST',
  4871. ...(form ? { body: JSON.stringify(form) } : {}),
  4872. }),
  4873. searchLDAPDirectory: (q: string) =>
  4874. request<LDAPSearchResult[]>(`/auth/ldap/search?q=${encodeURIComponent(q)}`),
  4875. provisionLDAPUser: (username: string) =>
  4876. request<UserResponse>('/auth/ldap/provision', {
  4877. method: 'POST',
  4878. body: JSON.stringify({ username }),
  4879. }),
  4880. forgotPassword: (data: ForgotPasswordRequest) =>
  4881. request<ForgotPasswordResponse>('/auth/forgot-password', {
  4882. method: 'POST',
  4883. body: JSON.stringify(data),
  4884. }),
  4885. // H-6: Confirm password reset using the token from the emailed link
  4886. forgotPasswordConfirm: (token: string, newPassword: string) =>
  4887. request<ForgotPasswordResponse>('/auth/forgot-password/confirm', {
  4888. method: 'POST',
  4889. body: JSON.stringify({ token, new_password: newPassword }),
  4890. }),
  4891. resetUserPassword: (data: ResetPasswordRequest) =>
  4892. request<ResetPasswordResponse>('/auth/reset-password', {
  4893. method: 'POST',
  4894. body: JSON.stringify(data),
  4895. }),
  4896. // 2FA - status
  4897. get2FAStatus: () => request<TwoFAStatus>('/auth/2fa/status'),
  4898. // 2FA - TOTP
  4899. setupTOTP: () => request<TOTPSetupResponse>('/auth/2fa/totp/setup', { method: 'POST' }),
  4900. enableTOTP: (code: string) =>
  4901. request<TOTPEnableResponse>('/auth/2fa/totp/enable', {
  4902. method: 'POST',
  4903. body: JSON.stringify({ code }),
  4904. }),
  4905. disableTOTP: (code: string) =>
  4906. request<{ message: string }>('/auth/2fa/totp/disable', {
  4907. method: 'POST',
  4908. body: JSON.stringify({ code }),
  4909. }),
  4910. regenerateBackupCodes: (code: string) =>
  4911. request<BackupCodesResponse>('/auth/2fa/totp/regenerate-backup-codes', {
  4912. method: 'POST',
  4913. body: JSON.stringify({ code }),
  4914. }),
  4915. // 2FA - Email OTP
  4916. // Step 1: send a verification code to the user's email (proof of possession)
  4917. enableEmailOTP: () =>
  4918. request<{ message: string; setup_token: string }>('/auth/2fa/email/enable', { method: 'POST' }),
  4919. // Step 2: confirm with the code received by email
  4920. confirmEnableEmailOTP: (setup_token: string, code: string) =>
  4921. request<{ message: string }>('/auth/2fa/email/enable/confirm', {
  4922. method: 'POST',
  4923. body: JSON.stringify({ setup_token, code }),
  4924. }),
  4925. // Disable requires account password for re-auth
  4926. disableEmailOTP: (password: string) =>
  4927. request<{ message: string }>('/auth/2fa/email/disable', {
  4928. method: 'POST',
  4929. body: JSON.stringify({ password }),
  4930. }),
  4931. sendEmailOTP: (preAuthToken: string) =>
  4932. request<{ message: string; pre_auth_token?: string }>('/auth/2fa/email/send', {
  4933. method: 'POST',
  4934. body: JSON.stringify({ pre_auth_token: preAuthToken }),
  4935. }),
  4936. // 2FA - verify (completes login)
  4937. verify2FA: (data: TwoFAVerifyRequest) =>
  4938. request<LoginResponse>('/auth/2fa/verify', {
  4939. method: 'POST',
  4940. body: JSON.stringify(data),
  4941. }),
  4942. // 2FA - admin
  4943. // adminPassword: the calling admin's own password; null for an admin
  4944. // without one (LDAP / OIDC accounts usually), whom the route does not ask.
  4945. admin2FADisable: (userId: number, adminPassword: string | null) =>
  4946. request<{ message: string; had_2fa: boolean }>(`/auth/2fa/admin/${userId}`, {
  4947. method: 'DELETE',
  4948. body: JSON.stringify({ admin_password: adminPassword }),
  4949. }),
  4950. // OIDC providers (public list)
  4951. getOIDCProviders: () => request<OIDCProviderPublic[]>('/auth/oidc/providers'),
  4952. // OIDC providers (admin)
  4953. getOIDCProvidersAll: () => request<OIDCProvider[]>('/auth/oidc/providers/all'),
  4954. createOIDCProvider: (data: OIDCProviderCreate) =>
  4955. request<OIDCProvider>('/auth/oidc/providers', {
  4956. method: 'POST',
  4957. body: JSON.stringify(data),
  4958. }),
  4959. updateOIDCProvider: (id: number, data: Partial<OIDCProviderCreate>) =>
  4960. request<OIDCProvider>(`/auth/oidc/providers/${id}`, {
  4961. method: 'PUT',
  4962. body: JSON.stringify(data),
  4963. }),
  4964. deleteOIDCProvider: (id: number) =>
  4965. request<{ message: string }>(`/auth/oidc/providers/${id}`, { method: 'DELETE' }),
  4966. // OIDC provider icon proxy (#1333) — same-origin path so the strict
  4967. // img-src CSP stays in force. Returns a SameOriginUrl-branded string
  4968. // so a future caller can't accidentally substitute an attacker-
  4969. // controlled URL where this is consumed.
  4970. oidcProviderIconUrl: (id: number): SameOriginUrl =>
  4971. `/api/v1/auth/oidc/providers/${id}/icon` as SameOriginUrl,
  4972. deleteOIDCProviderIcon: (id: number) =>
  4973. request<void>(`/auth/oidc/providers/${id}/icon`, { method: 'DELETE' }),
  4974. refreshOIDCProviderIcon: (id: number) =>
  4975. request<OIDCProvider>(`/auth/oidc/providers/${id}/icon/refresh`, { method: 'POST' }),
  4976. // OIDC authorize URL
  4977. getOIDCAuthorizeUrl: (providerId: number) =>
  4978. request<{ auth_url: string }>(`/auth/oidc/authorize/${providerId}`),
  4979. // OIDC exchange token for JWT
  4980. exchangeOIDCToken: (oidcToken: string) =>
  4981. request<LoginResponse>('/auth/oidc/exchange', {
  4982. method: 'POST',
  4983. body: JSON.stringify({ oidc_token: oidcToken }),
  4984. }),
  4985. // OIDC links for current user
  4986. getOIDCLinks: () => request<OIDCLink[]>('/auth/oidc/links'),
  4987. deleteOIDCLink: (providerId: number) =>
  4988. request<{ message: string }>(`/auth/oidc/links/${providerId}`, { method: 'DELETE' }),
  4989. // Users
  4990. getUsers: () => request<UserResponse[]>('/users/'),
  4991. getUsersSlim: () => request<UserSlim[]>('/users/slim'),
  4992. createUser: (data: UserCreate) =>
  4993. request<UserResponse>('/users/', {
  4994. method: 'POST',
  4995. body: JSON.stringify(data),
  4996. }),
  4997. updateUser: (id: number, data: UserUpdate) =>
  4998. request<UserResponse>(`/users/${id}`, {
  4999. method: 'PATCH',
  5000. body: JSON.stringify(data),
  5001. }),
  5002. deleteUser: (id: number, deleteItems: boolean = false) =>
  5003. request<void>(`/users/${id}?delete_items=${deleteItems}`, {
  5004. method: 'DELETE',
  5005. }),
  5006. getUserItemsCount: (id: number) =>
  5007. request<{ archives: number; queue_items: number; library_files: number }>(`/users/${id}/items-count`),
  5008. changePassword: (currentPassword: string, newPassword: string) =>
  5009. request<{ message: string }>('/users/me/change-password', {
  5010. method: 'POST',
  5011. body: JSON.stringify({ current_password: currentPassword, new_password: newPassword }),
  5012. }),
  5013. // User Email Notifications
  5014. getUserEmailPreferences: () =>
  5015. request<UserEmailPreferences>('/user-notifications/preferences'),
  5016. updateUserEmailPreferences: (data: UserEmailPreferences) =>
  5017. request<UserEmailPreferences>('/user-notifications/preferences', {
  5018. method: 'PUT',
  5019. body: JSON.stringify(data),
  5020. }),
  5021. // Groups
  5022. getPermissions: () => request<PermissionsListResponse>('/groups/permissions'),
  5023. getGroups: () => request<Group[]>('/groups/'),
  5024. getGroup: (id: number) => request<GroupDetail>(`/groups/${id}`),
  5025. createGroup: (data: GroupCreate) =>
  5026. request<Group>('/groups/', {
  5027. method: 'POST',
  5028. body: JSON.stringify(data),
  5029. }),
  5030. updateGroup: (id: number, data: GroupUpdate) =>
  5031. request<Group>(`/groups/${id}`, {
  5032. method: 'PATCH',
  5033. body: JSON.stringify(data),
  5034. }),
  5035. deleteGroup: (id: number) =>
  5036. request<void>(`/groups/${id}`, {
  5037. method: 'DELETE',
  5038. }),
  5039. // Printers
  5040. getPrinters: () => request<Printer[]>('/printers/'),
  5041. getPrinter: (id: number) => request<Printer>(`/printers/${id}`),
  5042. createPrinter: (data: PrinterCreate) =>
  5043. request<Printer>('/printers/', {
  5044. method: 'POST',
  5045. body: JSON.stringify(data),
  5046. }),
  5047. updatePrinter: (id: number, data: Partial<PrinterCreate>) =>
  5048. request<Printer>(`/printers/${id}`, {
  5049. method: 'PATCH',
  5050. body: JSON.stringify(data),
  5051. }),
  5052. getWledPresets: (id: number, baseUrl: string) =>
  5053. request<WLEDPreset[]>(`/printers/${id}/wled/presets`, {
  5054. method: 'POST',
  5055. body: JSON.stringify({ base_url: baseUrl }),
  5056. }),
  5057. testWledConnection: (id: number, baseUrl: string) =>
  5058. request<WLEDConnectionInfo>(`/printers/${id}/wled/test-connection`, {
  5059. method: 'POST',
  5060. body: JSON.stringify({ base_url: baseUrl }),
  5061. }),
  5062. testWledPreset: (id: number, baseUrl: string, presetId: number) =>
  5063. request<{ success: boolean }>(`/printers/${id}/wled/test-preset`, {
  5064. method: 'POST',
  5065. body: JSON.stringify({ base_url: baseUrl, preset_id: presetId }),
  5066. }),
  5067. deletePrinter: (id: number, deleteArchives: boolean = true) =>
  5068. request<{ status: string; archives_deleted: boolean }>(
  5069. `/printers/${id}?delete_archives=${deleteArchives}`,
  5070. { method: 'DELETE' }
  5071. ),
  5072. getDeveloperModeWarnings: () =>
  5073. request<{ printer_id: number; name: string }[]>('/printers/developer-mode-warnings'),
  5074. getAvailableFilaments: (model: string, location?: string) => {
  5075. const params = new URLSearchParams({ model });
  5076. if (location) params.set('location', location);
  5077. return request<Array<{ type: string; color: string; tray_info_idx: string; tray_sub_brands: string; extruder_id: number | null }>>(`/printers/available-filaments?${params}`);
  5078. },
  5079. getPrinterLocations: () => request<PrinterLocation[]>('/printer-locations/'),
  5080. createPrinterLocation: (data: { name: string; icon?: string | null; color?: string | null }) =>
  5081. request<PrinterLocation>('/printer-locations/', { method: 'POST', body: JSON.stringify(data) }),
  5082. updatePrinterLocation: (data: PrinterLocationUpdate) =>
  5083. request<PrinterLocation>('/printer-locations/', { method: 'PATCH', body: JSON.stringify(data) }),
  5084. deletePrinterLocations: (names: string[]) =>
  5085. request<{ deleted: number; printers_ungrouped: number }>('/printer-locations/delete', {
  5086. method: 'POST',
  5087. body: JSON.stringify({ names }),
  5088. }),
  5089. assignPrinterLocation: (printerIds: number[], location: string | null) =>
  5090. request<{ moved: number }>('/printer-locations/assign', {
  5091. method: 'POST',
  5092. body: JSON.stringify({ printer_ids: printerIds, location }),
  5093. }),
  5094. getPrinterStatus: (id: number) => printerStatusBatch(id),
  5095. refreshPrinterStatus: (id: number) =>
  5096. request<{ status: string }>(`/printers/${id}/refresh-status`, {
  5097. method: 'POST',
  5098. }),
  5099. connectPrinter: (id: number) =>
  5100. request<{ connected: boolean }>(`/printers/${id}/connect`, {
  5101. method: 'POST',
  5102. }),
  5103. getUsbCameras: () => request<{ cameras: UsbCamera[] }>('/printers/usb-cameras'),
  5104. testExternalCamera: (printerId: number, url: string, cameraType: string) =>
  5105. // `coalesced` is true when the frame came from a capture that was already
  5106. // running (Obico polling, a snapshot) rather than a connection this test
  5107. // opened — a single-reader camera is shared rather than opened twice, so
  5108. // the result is real but says nothing about reaching the camera just now.
  5109. // `live_view` is true when the tested camera is the one a viewer is
  5110. // watching: the answer comes from the live frame, not a test of its own.
  5111. // In the body: the URL may carry the camera login, and a query string
  5112. // ends up in the server's access log.
  5113. request<{ success: boolean; error?: string; resolution?: string; coalesced?: boolean; live_view?: boolean }>(
  5114. `/printers/${printerId}/camera/external/test`,
  5115. { method: 'POST', body: JSON.stringify({ url, camera_type: cameraType }) }
  5116. ),
  5117. // Print Control
  5118. stopPrint: (printerId: number) =>
  5119. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/stop`, {
  5120. method: 'POST',
  5121. }),
  5122. pausePrint: (printerId: number) =>
  5123. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/pause`, {
  5124. method: 'POST',
  5125. }),
  5126. resumePrint: (printerId: number) =>
  5127. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/resume`, {
  5128. method: 'POST',
  5129. }),
  5130. clearPlate: (printerId: number) =>
  5131. request<{ success: boolean; message: string }>(`/printers/${printerId}/clear-plate`, {
  5132. method: 'POST',
  5133. }),
  5134. // Get current print user (for reprint tracking - Issue #206)
  5135. getCurrentPrintUser: (printerId: number) =>
  5136. request<{ user_id?: number; username?: string }>(`/printers/${printerId}/current-print-user`),
  5137. // Print Speed Control
  5138. setPrintSpeed: (printerId: number, mode: number) =>
  5139. request<{ success: boolean; message: string }>(`/printers/${printerId}/print-speed?mode=${mode}`, {
  5140. method: 'POST',
  5141. }),
  5142. setNozzleTemperature: (printerId: number, target: number, nozzle: number = 0) =>
  5143. request<{ success: boolean; message: string }>(
  5144. `/printers/${printerId}/temperature/nozzle?target=${target}&nozzle=${nozzle}`,
  5145. { method: 'POST' }
  5146. ),
  5147. setBedTemperature: (printerId: number, target: number) =>
  5148. request<{ success: boolean; message: string }>(`/printers/${printerId}/temperature/bed?target=${target}`, {
  5149. method: 'POST',
  5150. }),
  5151. setChamberTemperature: (printerId: number, target: number) =>
  5152. request<{ success: boolean; message: string }>(`/printers/${printerId}/temperature/chamber?target=${target}`, {
  5153. method: 'POST',
  5154. }),
  5155. setFanSpeed: (printerId: number, fan: 'part' | 'aux' | 'aux2' | 'chamber', speed: number) =>
  5156. request<{ success: boolean; message: string }>(`/printers/${printerId}/fan-speed?fan=${fan}&speed=${speed}`, {
  5157. method: 'POST',
  5158. }),
  5159. selectExtruder: (printerId: number, extruder: number) =>
  5160. request<{ success: boolean; message: string }>(`/printers/${printerId}/select-extruder?extruder=${extruder}`, {
  5161. method: 'POST',
  5162. }),
  5163. setAirductMode: (printerId: number, mode: 'cooling' | 'heating') =>
  5164. request<{ success: boolean; message: string }>(`/printers/${printerId}/airduct-mode?mode=${mode}`, {
  5165. method: 'POST',
  5166. }),
  5167. // Bed (Z-axis) jog
  5168. bedJog: (printerId: number, distance: number) =>
  5169. request<{ success: boolean; message: string }>(
  5170. `/printers/${printerId}/bed-jog?distance=${distance}`,
  5171. { method: 'POST' }
  5172. ),
  5173. xyJog: (printerId: number, x: number, y: number) =>
  5174. request<{ success: boolean; message: string }>(
  5175. `/printers/${printerId}/xy-jog?x=${x}&y=${y}`,
  5176. { method: 'POST' }
  5177. ),
  5178. extruderJog: (printerId: number, distance: number) =>
  5179. request<{ success: boolean; message: string }>(
  5180. `/printers/${printerId}/extruder-jog?distance=${distance}`,
  5181. { method: 'POST' }
  5182. ),
  5183. homeAxes: (printerId: number, axes: 'z' | 'xy' | 'all' = 'z') =>
  5184. request<{ success: boolean; message: string }>(
  5185. `/printers/${printerId}/home-axes?axes=${axes}`,
  5186. { method: 'POST' }
  5187. ),
  5188. // Chamber Light Control
  5189. setChamberLight: (printerId: number, on: boolean) =>
  5190. request<{ success: boolean; message: string }>(`/printers/${printerId}/chamber-light?on=${on}`, {
  5191. method: 'POST',
  5192. }),
  5193. // AMS Drying Control
  5194. startDrying: (printerId: number, amsId: number, temp: number, duration: number, filament: string = '', rotateTray: boolean = false) =>
  5195. request<{ status: string; ams_id: number; temp: number; duration: number }>(
  5196. `/printers/${printerId}/drying/start?ams_id=${amsId}&temp=${temp}&duration=${duration}&filament=${encodeURIComponent(filament)}&rotate_tray=${rotateTray}`,
  5197. { method: 'POST' }
  5198. ),
  5199. stopDrying: (printerId: number, amsId: number) =>
  5200. request<{ status: string; ams_id: number }>(
  5201. `/printers/${printerId}/drying/stop?ams_id=${amsId}`,
  5202. { method: 'POST' }
  5203. ),
  5204. // Scheduled (delayed) drying runs (#2638)
  5205. createScheduledDrying: (data: {
  5206. printer_id: number;
  5207. ams_id: number;
  5208. temp: number;
  5209. duration_hours: number;
  5210. filament?: string;
  5211. rotate_tray?: boolean;
  5212. start_after: string | null;
  5213. }) =>
  5214. request<ScheduledDrying>('/scheduled-dryings', {
  5215. method: 'POST',
  5216. body: JSON.stringify(data),
  5217. }),
  5218. // Omit printerId for the whole fleet in one request; the printer cards share
  5219. // that single query rather than each polling for its own id.
  5220. listScheduledDryings: (printerId?: number) =>
  5221. request<ScheduledDrying[]>(
  5222. printerId === undefined ? '/scheduled-dryings' : `/scheduled-dryings?printer_id=${printerId}`
  5223. ),
  5224. cancelScheduledDrying: (id: number) =>
  5225. request<{ status: string; id: number }>(`/scheduled-dryings/${id}`, { method: 'DELETE' }),
  5226. // AMS Filament Backup (auto-switch to a backup spool when one runs out)
  5227. setAmsFilamentBackup: (printerId: number, enabled: boolean) =>
  5228. request<{ success: boolean; ams_filament_backup: boolean }>(
  5229. `/printers/${printerId}/ams-backup?enabled=${enabled}`,
  5230. { method: 'POST' }
  5231. ),
  5232. // Per-globalTrayId remaining grams for this printer's inventory-bound slots
  5233. // (#1766). Drives the client-side "Prefer Lowest Remaining Filament" sort
  5234. // when computing the AMS mapping; mirrors backend `_build_inventory_remain_overrides`
  5235. // so internal and Spoolman modes both work uniformly.
  5236. getInventoryRemain: (printerId: number) =>
  5237. request<InventoryRemainResponse>(
  5238. `/printers/${printerId}/inventory-remain`,
  5239. ),
  5240. // Skip Objects
  5241. getPrintableObjects: (printerId: number) =>
  5242. request<{
  5243. objects: Array<{ id: number; name: string; x: number | null; y: number | null; skipped: boolean }>;
  5244. total: number;
  5245. skipped_count: number;
  5246. is_printing: boolean;
  5247. bbox_all: [number, number, number, number] | null;
  5248. }>(`/printers/${printerId}/print/objects`),
  5249. skipObjects: (printerId: number, objectIds: number[]) =>
  5250. request<{ success: boolean; message: string; skipped_objects: number[] }>(
  5251. `/printers/${printerId}/print/skip-objects`,
  5252. {
  5253. method: 'POST',
  5254. body: JSON.stringify(objectIds),
  5255. }
  5256. ),
  5257. // HMS Errors
  5258. clearHMSErrors: (printerId: number) =>
  5259. request<{ success: boolean; message: string }>(`/printers/${printerId}/hms/clear`, { method: 'POST' }),
  5260. executeHMSAction: (printerId: number, data: HMSActionBody) =>
  5261. request<{ success: boolean; message: string }>(`/printers/${printerId}/hms/execute-action`, {
  5262. method: 'POST',
  5263. body: JSON.stringify(data),
  5264. }),
  5265. // AMS Control
  5266. refreshAmsSlot: (printerId: number, amsId: number, slotId: number) =>
  5267. request<{ success: boolean; message: string }>(
  5268. `/printers/${printerId}/ams/${amsId}/slot/${slotId}/refresh`,
  5269. { method: 'POST' }
  5270. ),
  5271. // Load filament from a tray. trayId: 0-15 for AMS (amsId*4+slotId), 28-36 for the H3C AMS 3H, 128-135 for an
  5272. // AMS-HT (its unit id), 254 for external spool.
  5273. // extruderId (0 = right, 1 = left) names the hotend to feed. Pass it only on a
  5274. // printer with a Filament Track Switch — there the AMS is bound to a switch
  5275. // inlet rather than a hotend, so the firmware cannot work the target out and
  5276. // drops the command. Omit it everywhere else, as BambuStudio does.
  5277. loadAmsTray: (printerId: number, trayId: number, extruderId?: number) =>
  5278. request<{ success: boolean; message: string }>(
  5279. `/printers/${printerId}/ams/load?tray_id=${trayId}` +
  5280. (extruderId !== undefined ? `&extruder_id=${extruderId}` : ''),
  5281. { method: 'POST' }
  5282. ),
  5283. // Unload filament. trayId names the slot to unload, which is what tells a
  5284. // dual-nozzle printer which of its two hotends to act on; omit it to unload
  5285. // whatever the printer's single tray_now field names.
  5286. unloadAms: (printerId: number, trayId?: number) =>
  5287. request<{ success: boolean; message: string }>(
  5288. `/printers/${printerId}/ams/unload` + (trayId !== undefined ? `?tray_id=${trayId}` : ''),
  5289. { method: 'POST' }
  5290. ),
  5291. // MQTT Debug Logging
  5292. enableMQTTLogging: (printerId: number) =>
  5293. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/enable`, {
  5294. method: 'POST',
  5295. }),
  5296. disableMQTTLogging: (printerId: number) =>
  5297. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/disable`, {
  5298. method: 'POST',
  5299. }),
  5300. getMQTTLogs: (printerId: number) =>
  5301. request<MQTTLogsResponse>(`/printers/${printerId}/logging`),
  5302. clearMQTTLogs: (printerId: number) =>
  5303. request<{ status: string }>(`/printers/${printerId}/logging`, {
  5304. method: 'DELETE',
  5305. }),
  5306. // Printer File Manager
  5307. getPrinterFiles: (printerId: number, path = '/') =>
  5308. request<{
  5309. path: string;
  5310. files: Array<{
  5311. name: string;
  5312. is_directory: boolean;
  5313. size: number;
  5314. path: string;
  5315. mtime?: string;
  5316. }>;
  5317. warnings: Array<'printer_unavailable' | 'listing_timed_out'>;
  5318. }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`),
  5319. getPrinterFileDownloadUrl: (printerId: number, path: string) =>
  5320. `${API_BASE}/printers/${printerId}/files/download?path=${encodeURIComponent(path)}`,
  5321. getPrinterFileGcodeUrl: (printerId: number, path: string) =>
  5322. `${API_BASE}/printers/${printerId}/files/gcode?path=${encodeURIComponent(path)}`,
  5323. getPrinterFilePlates: (printerId: number, path: string) =>
  5324. request<{
  5325. printer_id: number;
  5326. path: string;
  5327. filename: string;
  5328. plates: Array<{
  5329. index: number;
  5330. name: string | null;
  5331. objects: string[];
  5332. has_thumbnail: boolean;
  5333. thumbnail_url: string | null;
  5334. print_time_seconds: number | null;
  5335. filament_used_grams: number | null;
  5336. filaments: Array<{
  5337. slot_id: number;
  5338. type: string;
  5339. color: string;
  5340. used_grams: number;
  5341. used_meters: number;
  5342. }>;
  5343. }>;
  5344. is_multi_plate: boolean;
  5345. }>(`/printers/${printerId}/files/plates?path=${encodeURIComponent(path)}`),
  5346. getPrinterFilePlateThumbnail: (printerId: number, plateIndex: number, path: string) =>
  5347. withMediaToken(`${API_BASE}/printers/${printerId}/files/plate-thumbnail/${plateIndex}?path=${encodeURIComponent(path)}`),
  5348. downloadPrinterFilesAsZip: async (
  5349. printerId: number,
  5350. paths: string[],
  5351. sizes: Record<string, number>,
  5352. filename = 'printer-files.zip',
  5353. asZip = true,
  5354. signal?: AbortSignal,
  5355. onProgress?: (completed: number, total: number) => void,
  5356. ): Promise<{ requested: number; successful: number; failed: number }> => {
  5357. type JobStatus = {
  5358. job_id: string;
  5359. state: 'queued' | 'preparing' | 'ready' | 'failed' | 'cancelled';
  5360. requested: number;
  5361. successful: number;
  5362. failed: number;
  5363. token: string | null;
  5364. message: string | null;
  5365. };
  5366. let jobId: string | null = null;
  5367. try {
  5368. if (signal?.aborted) throw new DOMException('Download cancelled', 'AbortError');
  5369. let status = await request<JobStatus>(`/printers/${printerId}/files/download-job`, {
  5370. method: 'POST',
  5371. body: JSON.stringify({ paths, sizes, filename, as_zip: asZip }),
  5372. signal,
  5373. });
  5374. jobId = status.job_id;
  5375. let polls = 0;
  5376. while (status.state === 'queued' || status.state === 'preparing') {
  5377. onProgress?.(status.successful + status.failed, status.requested);
  5378. // Small selections finish in the first seconds, so poll quickly there.
  5379. // A large one runs for up to half an hour, where half-second polling is
  5380. // thousands of requests that each re-check the caller's credentials.
  5381. const delay = polls < 10 ? 500 : 2000;
  5382. polls += 1;
  5383. await new Promise<void>((resolve, reject) => {
  5384. if (signal?.aborted) {
  5385. reject(new DOMException('Download cancelled', 'AbortError'));
  5386. return;
  5387. }
  5388. const onAbort = () => {
  5389. window.clearTimeout(timer);
  5390. reject(new DOMException('Download cancelled', 'AbortError'));
  5391. };
  5392. const timer = window.setTimeout(() => {
  5393. signal?.removeEventListener('abort', onAbort);
  5394. resolve();
  5395. }, delay);
  5396. signal?.addEventListener('abort', onAbort, { once: true });
  5397. });
  5398. status = await request<JobStatus>(`/printers/${printerId}/files/download-jobs/${jobId}`, { signal });
  5399. }
  5400. onProgress?.(status.successful + status.failed, status.requested);
  5401. if (status.state !== 'ready' || !status.token) {
  5402. throw new Error(status.message || (status.state === 'cancelled'
  5403. ? 'Download cancelled'
  5404. : 'Printer download preparation failed'));
  5405. }
  5406. const link = document.createElement('a');
  5407. link.href = `${API_BASE}/printers/${printerId}/files/dl/${encodeURIComponent(status.token)}/${encodeURIComponent(filename)}`;
  5408. link.download = filename;
  5409. document.body.appendChild(link);
  5410. link.click();
  5411. link.remove();
  5412. return {
  5413. requested: status.requested,
  5414. successful: status.successful,
  5415. failed: status.failed,
  5416. };
  5417. } catch (error) {
  5418. if (jobId) {
  5419. await request(`/printers/${printerId}/files/download-jobs/${jobId}`, { method: 'DELETE' }).catch(() => undefined);
  5420. }
  5421. throw error;
  5422. }
  5423. },
  5424. deletePrinterFile: (printerId: number, path: string) =>
  5425. request<{ status: string; path: string }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`, {
  5426. method: 'DELETE',
  5427. }),
  5428. getPrinterStorage: (printerId: number) =>
  5429. request<{ used_bytes: number | null; free_bytes: number | null }>(`/printers/${printerId}/storage`),
  5430. // Archives
  5431. getArchives: (printerId?: number, projectId?: number, limit = 10000, offset = 0, dateFrom?: string, dateTo?: string) => {
  5432. const params = new URLSearchParams();
  5433. if (printerId) params.set('printer_id', String(printerId));
  5434. if (projectId) params.set('project_id', String(projectId));
  5435. params.set('limit', String(limit));
  5436. params.set('offset', String(offset));
  5437. if (dateFrom) params.set('date_from', dateFrom);
  5438. if (dateTo) params.set('date_to', dateTo);
  5439. addDayZone(params);
  5440. return request<Archive[]>(`/archives/?${params}`);
  5441. },
  5442. // Latest archive of every printer in one request, for the printer cards.
  5443. getLastArchivePerPrinter: () => request<Archive[]>('/archives/last-per-printer'),
  5444. getArchivesSlim: (dateFrom?: string, dateTo?: string, createdById?: number) => {
  5445. const params = new URLSearchParams();
  5446. if (dateFrom) params.set('date_from', dateFrom);
  5447. if (dateTo) params.set('date_to', dateTo);
  5448. addDayZone(params);
  5449. if (createdById !== undefined) params.set('created_by_id', String(createdById));
  5450. const qs = params.toString();
  5451. return request<ArchiveSlim[]>(`/archives/slim${qs ? `?${qs}` : ''}`);
  5452. },
  5453. getArchive: (id: number, runId?: number | null) =>
  5454. request<Archive>(`/archives/${id}${runId != null ? `?run_id=${runId}` : ''}`),
  5455. getArchiveRuns: (id: number) => request<PrintLogResponse>(`/archives/${id}/runs`),
  5456. // The prints of the archives the caller sees that ended between two days
  5457. // (archive redesign P4: the calendar), in id order.
  5458. getArchivePrints: (params: { dateFrom: string; dateTo: string; printerId?: number; limit?: number; offset?: number }) => {
  5459. const search = new URLSearchParams({ date_from: params.dateFrom, date_to: params.dateTo });
  5460. if (params.printerId) search.set('printer_id', String(params.printerId));
  5461. if (params.limit) search.set('limit', String(params.limit));
  5462. if (params.offset) search.set('offset', String(params.offset));
  5463. addDayZone(search);
  5464. return request<PrintLogResponse>(`/archives/prints?${search}`);
  5465. },
  5466. /**
  5467. * Pre-flight for the delete-confirm modal (#1734). Returns the number of
  5468. * related queue items that will be removed along with the archive AND how
  5469. * many are currently printing (server 409s on delete if > 0).
  5470. */
  5471. getArchiveDeleteImpact: (id: number) =>
  5472. request<{ related_queue_items: number; currently_printing: number }>(
  5473. `/archives/${id}/delete-impact`
  5474. ),
  5475. getNo3MFWarning: () =>
  5476. request<{
  5477. has_fallback: boolean;
  5478. reason:
  5479. | 'ftps_cooloff'
  5480. | 'ftp_transfer_failed'
  5481. | 'internal_storage'
  5482. | 'no_external_storage'
  5483. | 'internal_history'
  5484. | null;
  5485. }>(
  5486. '/archives/no-3mf-warning',
  5487. ),
  5488. updateArchive: (id: number, data: {
  5489. printer_id?: number | null;
  5490. project_id?: number | null;
  5491. print_name?: string;
  5492. is_favorite?: boolean;
  5493. tags?: string;
  5494. notes?: string;
  5495. cost?: number;
  5496. failure_reason?: string | null;
  5497. status?: string;
  5498. quantity?: number;
  5499. external_url?: string | null;
  5500. filament_used_grams?: number | null;
  5501. // Post-print outcome verdict (#1898); null clears it
  5502. user_verdict?: 'good' | 'reject' | null;
  5503. // Which surface answered. The backend only accepts the sources a client
  5504. // can honestly claim and defaults to 'api' when none is given.
  5505. user_verdict_source?: 'dialog' | 'printer_card';
  5506. // The run the verdict / outcome is for; omitted means the latest run.
  5507. run_id?: number;
  5508. }) =>
  5509. request<Archive>(`/archives/${id}`, {
  5510. method: 'PATCH',
  5511. body: JSON.stringify(data),
  5512. }),
  5513. toggleFavorite: (id: number) =>
  5514. request<Archive>(`/archives/${id}/favorite`, { method: 'POST' }),
  5515. // Soft-deletes by default (#1343): files removed from disk, row hidden
  5516. // from listings, but its filament / time / cost / energy contribution
  5517. // stays in Quick Stats. Pass purgeStats=true to hard-delete and drop the
  5518. // row from statistics too.
  5519. deleteArchive: (id: number, purgeStats: boolean = false) =>
  5520. request<void>(`/archives/${id}${purgeStats ? '?purge_stats=true' : ''}`, { method: 'DELETE' }),
  5521. // ========== Archive auto-purge (#1008 follow-up) ==========
  5522. previewArchivePurge: (olderThanDays: number, purgeStats: boolean = false) =>
  5523. request<ArchivePurgePreview>(
  5524. `/archives/purge/preview?older_than_days=${olderThanDays}&purge_stats=${purgeStats}`,
  5525. ),
  5526. // #1390: purgeStats=false (default) soft-deletes each old archive — Quick Stats
  5527. // preserved, files removed from disk, row hidden via deleted_at. true matches
  5528. // the single-archive delete's `?purge_stats=true` semantics (hard-deletes the
  5529. // linked PrintLogEntry rows so the contribution drops from /stats too).
  5530. executeArchivePurge: (olderThanDays: number, purgeStats: boolean = false) =>
  5531. request<{ deleted: number; purge_stats: boolean }>('/archives/purge', {
  5532. method: 'POST',
  5533. body: JSON.stringify({ older_than_days: olderThanDays, purge_stats: purgeStats }),
  5534. }),
  5535. // Archives of one file merge into the oldest (archive redesign P2).
  5536. previewArchiveMerge: () => request<ArchiveMergePreview>('/archives/merge-preview'),
  5537. /** How many duplicate groups there are; cheap, for offering the merge. */
  5538. getArchiveMergeCount: () => request<{ groups: number }>('/archives/merge-count'),
  5539. mergeArchives: (survivorIds: number[]) =>
  5540. request<ArchiveMergeResult>('/archives/merge', {
  5541. method: 'POST',
  5542. body: JSON.stringify({ survivor_ids: survivorIds }),
  5543. }),
  5544. getArchivePurgeSettings: () =>
  5545. request<ArchivePurgeSettings>('/archives/purge/settings'),
  5546. updateArchivePurgeSettings: (body: ArchivePurgeSettings) =>
  5547. request<ArchivePurgeSettings>('/archives/purge/settings', {
  5548. method: 'PUT',
  5549. body: JSON.stringify(body),
  5550. }),
  5551. getArchiveStats: (options?: { dateFrom?: string; dateTo?: string; createdById?: number }) => {
  5552. const params = new URLSearchParams();
  5553. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  5554. if (options?.dateTo) params.set('date_to', options.dateTo);
  5555. addDayZone(params);
  5556. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  5557. const qs = params.toString();
  5558. return request<ArchiveStats>(`/archives/stats${qs ? `?${qs}` : ''}`);
  5559. },
  5560. // Tag management
  5561. getTags: () => request<TagInfo[]>('/archives/tags'),
  5562. renameTag: (oldName: string, newName: string) =>
  5563. request<{ affected: number }>(`/archives/tags/${encodeURIComponent(oldName)}`, {
  5564. method: 'PUT',
  5565. body: JSON.stringify({ new_name: newName }),
  5566. }),
  5567. deleteTag: (name: string) =>
  5568. request<{ affected: number }>(`/archives/tags/${encodeURIComponent(name)}`, {
  5569. method: 'DELETE',
  5570. }),
  5571. recalculateCosts: () =>
  5572. request<{
  5573. message: string;
  5574. updated: number;
  5575. preserved: number;
  5576. usage_repriced: number;
  5577. spoolman_unreachable: number;
  5578. }>('/archives/recalculate-costs', { method: 'POST' }),
  5579. getFailureAnalysis: (options?: { days?: number; dateFrom?: string; dateTo?: string; printerId?: number; projectId?: number; createdById?: number }) => {
  5580. const params = new URLSearchParams();
  5581. if (options?.days) params.set('days', String(options.days));
  5582. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  5583. if (options?.dateTo) params.set('date_to', options.dateTo);
  5584. addDayZone(params);
  5585. if (options?.printerId) params.set('printer_id', String(options.printerId));
  5586. if (options?.projectId) params.set('project_id', String(options.projectId));
  5587. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  5588. const qs = params.toString();
  5589. return request<FailureAnalysis>(`/archives/analysis/failures${qs ? `?${qs}` : ''}`);
  5590. },
  5591. compareArchives: (archiveIds: number[]) =>
  5592. request<ArchiveComparison>(`/archives/compare?archive_ids=${archiveIds.join(',')}`),
  5593. exportArchives: async (options?: {
  5594. format?: 'csv' | 'xlsx';
  5595. fields?: string[];
  5596. printerId?: number;
  5597. projectId?: number;
  5598. status?: string;
  5599. dateFrom?: string;
  5600. dateTo?: string;
  5601. search?: string;
  5602. }): Promise<{ blob: Blob; filename: string }> => {
  5603. const params = new URLSearchParams();
  5604. if (options?.format) params.set('format', options.format);
  5605. if (options?.fields) params.set('fields', options.fields.join(','));
  5606. if (options?.printerId) params.set('printer_id', String(options.printerId));
  5607. if (options?.projectId) params.set('project_id', String(options.projectId));
  5608. if (options?.status) params.set('status', options.status);
  5609. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  5610. if (options?.dateTo) params.set('date_to', options.dateTo);
  5611. addDayZone(params);
  5612. if (options?.search) params.set('search', options.search);
  5613. const headers: Record<string, string> = {};
  5614. if (authToken) {
  5615. headers['Authorization'] = `Bearer ${authToken}`;
  5616. }
  5617. const response = await fetch(`${API_BASE}/archives/export?${params}`, { headers });
  5618. if (!response.ok) {
  5619. const error = await response.json().catch(() => ({}));
  5620. throw new Error(error.detail || `HTTP ${response.status}`);
  5621. }
  5622. const contentDisposition = response.headers.get('Content-Disposition');
  5623. let filename = options?.format === 'xlsx' ? 'archives_export.xlsx' : 'archives_export.csv';
  5624. if (contentDisposition) {
  5625. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  5626. if (match) filename = match[1];
  5627. }
  5628. const blob = await response.blob();
  5629. return { blob, filename };
  5630. },
  5631. exportStats: async (options?: {
  5632. format?: 'csv' | 'xlsx';
  5633. days?: number;
  5634. printerId?: number;
  5635. projectId?: number;
  5636. createdById?: number;
  5637. }): Promise<{ blob: Blob; filename: string }> => {
  5638. const params = new URLSearchParams();
  5639. if (options?.format) params.set('format', options.format);
  5640. if (options?.days) params.set('days', String(options.days));
  5641. if (options?.printerId) params.set('printer_id', String(options.printerId));
  5642. if (options?.projectId) params.set('project_id', String(options.projectId));
  5643. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  5644. const headers: Record<string, string> = {};
  5645. if (authToken) {
  5646. headers['Authorization'] = `Bearer ${authToken}`;
  5647. }
  5648. const response = await fetch(`${API_BASE}/archives/stats/export?${params}`, { headers });
  5649. if (!response.ok) {
  5650. const error = await response.json().catch(() => ({}));
  5651. throw new Error(error.detail || `HTTP ${response.status}`);
  5652. }
  5653. const contentDisposition = response.headers.get('Content-Disposition');
  5654. let filename = options?.format === 'xlsx' ? 'stats_export.xlsx' : 'stats_export.csv';
  5655. if (contentDisposition) {
  5656. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  5657. if (match) filename = match[1];
  5658. }
  5659. const blob = await response.blob();
  5660. return { blob, filename };
  5661. },
  5662. getArchiveThumbnail: (id: number) => withMediaToken(`${API_BASE}/archives/${id}/thumbnail?v=${Date.now()}`),
  5663. getArchivePlateThumbnail: (id: number, plateIndex: number) =>
  5664. withMediaToken(`${API_BASE}/archives/${id}/plate-thumbnail/${plateIndex}`),
  5665. getArchiveDownload: (id: number) => `${API_BASE}/archives/${id}/download`,
  5666. downloadArchive: async (id: number, filename?: string): Promise<void> => {
  5667. const headers: Record<string, string> = {};
  5668. if (authToken) {
  5669. headers['Authorization'] = `Bearer ${authToken}`;
  5670. }
  5671. const response = await fetch(`${API_BASE}/archives/${id}/download`, { headers });
  5672. if (!response.ok) {
  5673. const error = await response.json().catch(() => ({}));
  5674. throw new Error(error.detail || `HTTP ${response.status}`);
  5675. }
  5676. const disposition = response.headers.get('Content-Disposition');
  5677. const downloadFilename = parseContentDispositionFilename(disposition) || filename || `archive_${id}.3mf`;
  5678. const blob = await response.blob();
  5679. const url = window.URL.createObjectURL(blob);
  5680. const a = document.createElement('a');
  5681. a.href = url;
  5682. a.download = downloadFilename;
  5683. document.body.appendChild(a);
  5684. a.click();
  5685. document.body.removeChild(a);
  5686. window.URL.revokeObjectURL(url);
  5687. },
  5688. getArchiveGcode: (id: number) => `${API_BASE}/archives/${id}/gcode`,
  5689. getArchiveTimelapse: (id: number) => withMediaToken(`${API_BASE}/archives/${id}/timelapse?v=${Date.now()}`),
  5690. getArchiveRunTimelapse: (id: number, runId: number) =>
  5691. withMediaToken(`${API_BASE}/archives/${id}/runs/${runId}/timelapse?v=${Date.now()}`),
  5692. downloadArchiveTimelapse: async (id: number, filename: string): Promise<void> => {
  5693. const prepared = await request<{ token: string; filename: string }>(
  5694. `/archives/${id}/media-download-token`,
  5695. { method: 'POST' },
  5696. );
  5697. const link = document.createElement('a');
  5698. link.href = `${API_BASE}/archives/${id}/media/dl/${encodeURIComponent(prepared.token)}/${encodeURIComponent(filename)}`;
  5699. link.download = filename;
  5700. document.body.appendChild(link);
  5701. link.click();
  5702. link.remove();
  5703. },
  5704. getArchivePrinterMedia: (id: number) =>
  5705. request<ArchivePrinterMedia>(`/archives/${id}/printer-media`),
  5706. scanArchiveTimelapse: (id: number) =>
  5707. request<{
  5708. status: string;
  5709. message: string;
  5710. filename?: string;
  5711. available_files?: Array<{ name: string; path: string; size: number; mtime: string | null }>;
  5712. }>(`/archives/${id}/timelapse/scan`, {
  5713. method: 'POST',
  5714. }),
  5715. selectArchiveTimelapse: (id: number, filename: string) =>
  5716. request<{ status: string; message: string; filename: string }>(
  5717. `/archives/${id}/timelapse/select?filename=${encodeURIComponent(filename)}`,
  5718. { method: 'POST' }
  5719. ),
  5720. deleteArchiveTimelapse: (id: number) =>
  5721. request<{ status: string }>(`/archives/${id}/timelapse`, {
  5722. method: 'DELETE',
  5723. }),
  5724. uploadArchiveTimelapse: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  5725. const formData = new FormData();
  5726. formData.append('file', file);
  5727. const headers: Record<string, string> = {};
  5728. if (authToken) {
  5729. headers['Authorization'] = `Bearer ${authToken}`;
  5730. }
  5731. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/upload`, {
  5732. method: 'POST',
  5733. headers,
  5734. body: formData,
  5735. });
  5736. if (!response.ok) {
  5737. const error = await response.json().catch(() => ({}));
  5738. throw new Error(error.detail || `HTTP ${response.status}`);
  5739. }
  5740. return response.json();
  5741. },
  5742. // Timelapse Editor
  5743. getTimelapseInfo: (archiveId: number) =>
  5744. request<{
  5745. duration: number;
  5746. width: number;
  5747. height: number;
  5748. fps: number;
  5749. codec: string;
  5750. file_size: number;
  5751. has_audio: boolean;
  5752. }>(`/archives/${archiveId}/timelapse/info`),
  5753. getTimelapseThumbnails: (archiveId: number, count: number = 10) =>
  5754. request<{
  5755. thumbnails: string[];
  5756. timestamps: number[];
  5757. }>(`/archives/${archiveId}/timelapse/thumbnails?count=${count}`),
  5758. processTimelapse: async (
  5759. archiveId: number,
  5760. params: {
  5761. trimStart?: number;
  5762. trimEnd?: number;
  5763. speed?: number;
  5764. /** Music volume, 0 to 1. */
  5765. audioVolume?: number;
  5766. saveMode: 'replace' | 'new';
  5767. outputFilename?: string;
  5768. },
  5769. audioFile?: File
  5770. ): Promise<TimelapseJob> => {
  5771. const formData = new FormData();
  5772. formData.append('trim_start', String(params.trimStart ?? 0));
  5773. if (params.trimEnd !== undefined) {
  5774. formData.append('trim_end', String(params.trimEnd));
  5775. }
  5776. formData.append('speed', String(params.speed ?? 1));
  5777. if (params.audioVolume !== undefined) {
  5778. formData.append('audio_volume', String(params.audioVolume));
  5779. }
  5780. formData.append('save_mode', params.saveMode);
  5781. if (params.outputFilename) {
  5782. formData.append('output_filename', params.outputFilename);
  5783. }
  5784. if (audioFile) {
  5785. formData.append('audio', audioFile);
  5786. }
  5787. const headers: Record<string, string> = {};
  5788. if (authToken) {
  5789. headers['Authorization'] = `Bearer ${authToken}`;
  5790. }
  5791. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/process`, {
  5792. method: 'POST',
  5793. headers,
  5794. body: formData,
  5795. });
  5796. if (!response.ok) {
  5797. const error = await response.json().catch(() => ({}));
  5798. throw new Error(error.detail || `HTTP ${response.status}`);
  5799. }
  5800. return response.json();
  5801. },
  5802. // The archive's running or last re-encode; null when there has been none.
  5803. getTimelapseJob: async (archiveId: number): Promise<TimelapseJob | null> => {
  5804. try {
  5805. return await request<TimelapseJob>(`/archives/${archiveId}/timelapse/job`);
  5806. } catch (error) {
  5807. if (error instanceof ApiError && error.status === 404) return null;
  5808. throw error;
  5809. }
  5810. },
  5811. cancelTimelapseJob: (archiveId: number) =>
  5812. request<TimelapseJob>(`/archives/${archiveId}/timelapse/job`, { method: 'DELETE' }),
  5813. // Photos
  5814. getArchivePhotoUrl: (archiveId: number, filename: string) =>
  5815. withMediaToken(`${API_BASE}/archives/${archiveId}/photos/${encodeURIComponent(filename)}`),
  5816. uploadArchivePhoto: async (archiveId: number, file: File): Promise<{ status: string; filename: string; photos: string[] }> => {
  5817. const formData = new FormData();
  5818. formData.append('file', file);
  5819. const headers: Record<string, string> = {};
  5820. if (authToken) {
  5821. headers['Authorization'] = `Bearer ${authToken}`;
  5822. }
  5823. const response = await fetch(`${API_BASE}/archives/${archiveId}/photos`, {
  5824. headers,
  5825. method: 'POST',
  5826. body: formData,
  5827. });
  5828. if (!response.ok) {
  5829. const error = await response.json().catch(() => ({}));
  5830. throw new Error(error.detail || `HTTP ${response.status}`);
  5831. }
  5832. return response.json();
  5833. },
  5834. deleteArchivePhoto: (archiveId: number, filename: string) =>
  5835. request<{ status: string; photos: string[] | null }>(`/archives/${archiveId}/photos/${encodeURIComponent(filename)}`, {
  5836. method: 'DELETE',
  5837. }),
  5838. // Source 3MF (original slicer project file)
  5839. getSource3mfDownloadUrl: (archiveId: number) =>
  5840. `${API_BASE}/archives/${archiveId}/source`,
  5841. downloadSource3mf: async (archiveId: number): Promise<void> => {
  5842. const headers: Record<string, string> = {};
  5843. if (authToken) {
  5844. headers['Authorization'] = `Bearer ${authToken}`;
  5845. }
  5846. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, { headers });
  5847. if (!response.ok) {
  5848. const error = await response.json().catch(() => ({}));
  5849. throw new Error(error.detail || `HTTP ${response.status}`);
  5850. }
  5851. const disposition = response.headers.get('Content-Disposition');
  5852. const filename = parseContentDispositionFilename(disposition) || `source_${archiveId}.3mf`;
  5853. const blob = await response.blob();
  5854. const url = window.URL.createObjectURL(blob);
  5855. const a = document.createElement('a');
  5856. a.href = url;
  5857. a.download = filename;
  5858. document.body.appendChild(a);
  5859. a.click();
  5860. document.body.removeChild(a);
  5861. window.URL.revokeObjectURL(url);
  5862. },
  5863. getSource3mfForSlicer: (archiveId: number, filename: string) => {
  5864. // Sanitize: slicers url_decode() the entire URL, so / \ ? # in filenames break path routing
  5865. const safe = filename.replace(/[/\\?#]/g, '_');
  5866. return `${API_BASE}/archives/${archiveId}/source/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  5867. },
  5868. createSourceSlicerToken: (archiveId: number) =>
  5869. request<{ token: string }>(`/archives/${archiveId}/source-slicer-token`, { method: 'POST' }),
  5870. getSourceSlicerDownloadUrl: (archiveId: number, token: string, filename: string) => {
  5871. const safe = filename.replace(/[/\\?#]/g, '_');
  5872. return `${API_BASE}/archives/${archiveId}/source-dl/${token}/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  5873. },
  5874. uploadSource3mf: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  5875. const formData = new FormData();
  5876. formData.append('file', file);
  5877. const headers: Record<string, string> = {};
  5878. if (authToken) {
  5879. headers['Authorization'] = `Bearer ${authToken}`;
  5880. }
  5881. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, {
  5882. method: 'POST',
  5883. headers,
  5884. body: formData,
  5885. });
  5886. if (!response.ok) {
  5887. const error = await response.json().catch(() => ({}));
  5888. throw new Error(error.detail || `HTTP ${response.status}`);
  5889. }
  5890. return response.json();
  5891. },
  5892. deleteSource3mf: (archiveId: number) =>
  5893. request<{ status: string }>(`/archives/${archiveId}/source`, {
  5894. method: 'DELETE',
  5895. }),
  5896. // F3D (Fusion 360 design file)
  5897. downloadF3d: async (archiveId: number): Promise<void> => {
  5898. const headers: Record<string, string> = {};
  5899. if (authToken) {
  5900. headers['Authorization'] = `Bearer ${authToken}`;
  5901. }
  5902. const response = await fetch(`${API_BASE}/archives/${archiveId}/f3d`, { headers });
  5903. if (!response.ok) {
  5904. const error = await response.json().catch(() => ({}));
  5905. throw new Error(error.detail || `HTTP ${response.status}`);
  5906. }
  5907. const disposition = response.headers.get('Content-Disposition');
  5908. const filename = parseContentDispositionFilename(disposition) || `archive_${archiveId}.f3d`;
  5909. const blob = await response.blob();
  5910. const url = window.URL.createObjectURL(blob);
  5911. const a = document.createElement('a');
  5912. a.href = url;
  5913. a.download = filename;
  5914. document.body.appendChild(a);
  5915. a.click();
  5916. document.body.removeChild(a);
  5917. window.URL.revokeObjectURL(url);
  5918. },
  5919. uploadF3d: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  5920. const formData = new FormData();
  5921. formData.append('file', file);
  5922. const headers: Record<string, string> = {};
  5923. if (authToken) {
  5924. headers['Authorization'] = `Bearer ${authToken}`;
  5925. }
  5926. const response = await fetch(`${API_BASE}/archives/${archiveId}/f3d`, {
  5927. method: 'POST',
  5928. headers,
  5929. body: formData,
  5930. });
  5931. if (!response.ok) {
  5932. const error = await response.json().catch(() => ({}));
  5933. throw new Error(error.detail || `HTTP ${response.status}`);
  5934. }
  5935. return response.json();
  5936. },
  5937. deleteF3d: (archiveId: number) =>
  5938. request<{ status: string }>(`/archives/${archiveId}/f3d`, {
  5939. method: 'DELETE',
  5940. }),
  5941. // QR Code
  5942. getArchiveQRCodeUrl: (archiveId: number, size = 200) =>
  5943. withMediaToken(`${API_BASE}/archives/${archiveId}/qrcode?size=${size}`),
  5944. getArchiveCapabilities: (id: number) =>
  5945. request<{
  5946. has_model: boolean;
  5947. has_gcode: boolean;
  5948. has_source: boolean;
  5949. build_volume: { x: number; y: number; z: number };
  5950. filament_colors: string[];
  5951. }>(`/archives/${id}/capabilities`),
  5952. // Project Page
  5953. getArchiveProjectPage: (id: number) =>
  5954. request<{
  5955. title: string | null;
  5956. description: string | null;
  5957. designer: string | null;
  5958. designer_user_id: string | null;
  5959. license: string | null;
  5960. copyright: string | null;
  5961. creation_date: string | null;
  5962. modification_date: string | null;
  5963. origin: string | null;
  5964. profile_title: string | null;
  5965. profile_description: string | null;
  5966. profile_cover: string | null;
  5967. profile_user_id: string | null;
  5968. profile_user_name: string | null;
  5969. design_model_id: string | null;
  5970. design_profile_id: string | null;
  5971. design_region: string | null;
  5972. model_pictures: Array<{ name: string; path: string; url: string }>;
  5973. profile_pictures: Array<{ name: string; path: string; url: string }>;
  5974. thumbnails: Array<{ name: string; path: string; url: string }>;
  5975. }>(`/archives/${id}/project-page`),
  5976. updateArchiveProjectPage: (id: number, data: {
  5977. title?: string;
  5978. description?: string;
  5979. designer?: string;
  5980. license?: string;
  5981. copyright?: string;
  5982. profile_title?: string;
  5983. profile_description?: string;
  5984. }) =>
  5985. request(`/archives/${id}/project-page`, {
  5986. method: 'PATCH',
  5987. body: JSON.stringify(data),
  5988. }),
  5989. getArchiveForSlicer: (id: number, filename: string) => {
  5990. const safe = filename.replace(/[/\\?#]/g, '_');
  5991. return `${API_BASE}/archives/${id}/file/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  5992. },
  5993. createArchiveSlicerToken: (archiveId: number) =>
  5994. request<{ token: string }>(`/archives/${archiveId}/slicer-token`, { method: 'POST' }),
  5995. getArchiveSlicerDownloadUrl: (archiveId: number, token: string, filename: string) => {
  5996. const safe = filename.replace(/[/\\?#]/g, '_');
  5997. return `${API_BASE}/archives/${archiveId}/dl/${token}/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  5998. },
  5999. getArchivePlates: (archiveId: number) =>
  6000. request<ArchivePlatesResponse>(`/archives/${archiveId}/plates`),
  6001. getArchiveFilamentRequirements: (
  6002. archiveId: number,
  6003. plateId?: number,
  6004. requestId?: string,
  6005. /** Ask for one entry per project slot instead of only the slots this
  6006. * plate consumes. The slice modal needs it: its filament list is
  6007. * positional, so a source whose only used slot is 4 must still present
  6008. * four rows or the user's pick is bound to slot 1 (#2712). Print-time
  6009. * AMS matching must NOT set this — it wants the used-only list. */
  6010. fullSlots?: boolean,
  6011. ) => {
  6012. const qs = new URLSearchParams();
  6013. if (plateId !== undefined) qs.set('plate_id', String(plateId));
  6014. if (requestId) qs.set('request_id', requestId);
  6015. if (fullSlots) qs.set('full_slots', 'true');
  6016. return request<{
  6017. archive_id: number;
  6018. filename: string;
  6019. plate_id: number | null;
  6020. filaments: Array<{
  6021. slot_id: number;
  6022. type: string;
  6023. color: string;
  6024. used_grams: number;
  6025. used_meters: number;
  6026. used_in_plate?: boolean;
  6027. }>;
  6028. }>(`/archives/${archiveId}/filament-requirements${qs.toString() ? `?${qs}` : ''}`);
  6029. },
  6030. uploadArchivesBulk: async (files: File[], printerId?: number): Promise<BulkUploadResult> => {
  6031. const formData = new FormData();
  6032. files.forEach((file) => formData.append('files', file));
  6033. const url = printerId
  6034. ? `${API_BASE}/archives/upload-bulk?printer_id=${printerId}`
  6035. : `${API_BASE}/archives/upload-bulk`;
  6036. const headers: Record<string, string> = {};
  6037. if (authToken) {
  6038. headers['Authorization'] = `Bearer ${authToken}`;
  6039. }
  6040. const response = await fetch(url, {
  6041. method: 'POST',
  6042. headers,
  6043. body: formData,
  6044. });
  6045. if (!response.ok) {
  6046. const error = await response.json().catch(() => ({}));
  6047. throw new Error(error.detail || `HTTP ${response.status}`);
  6048. }
  6049. return response.json();
  6050. },
  6051. // Print Log
  6052. getPrintLog: (params?: {
  6053. search?: string;
  6054. printerId?: number;
  6055. username?: string;
  6056. status?: string;
  6057. dateFrom?: string;
  6058. dateTo?: string;
  6059. limit?: number;
  6060. offset?: number;
  6061. // Sorting is server-side because paging is: ordering only the rows the
  6062. // client holds would sort one page, not the log (#2636).
  6063. sortBy?: string;
  6064. sortDir?: 'asc' | 'desc';
  6065. }) => {
  6066. const searchParams = new URLSearchParams();
  6067. if (params?.search) searchParams.set('search', params.search);
  6068. if (params?.printerId) searchParams.set('printer_id', String(params.printerId));
  6069. if (params?.username) searchParams.set('created_by_username', params.username);
  6070. if (params?.status) searchParams.set('status', params.status);
  6071. if (params?.dateFrom) searchParams.set('date_from', params.dateFrom);
  6072. if (params?.dateTo) searchParams.set('date_to', params.dateTo);
  6073. if (params?.limit) searchParams.set('limit', String(params.limit));
  6074. if (params?.offset !== undefined) searchParams.set('offset', String(params.offset));
  6075. if (params?.sortBy) searchParams.set('sort_by', params.sortBy);
  6076. if (params?.sortDir) searchParams.set('sort_dir', params.sortDir);
  6077. return request<PrintLogResponse>(`/print-log/?${searchParams}`);
  6078. },
  6079. getPrintLogThumbnail: (id: number) => withMediaToken(`${API_BASE}/print-log/${id}/thumbnail`),
  6080. clearPrintLog: () =>
  6081. request<{ deleted: number }>('/print-log/', { method: 'DELETE' }),
  6082. deletePrintLogEntry: (id: number) =>
  6083. request<{ status: string; id: number }>(`/print-log/${id}`, { method: 'DELETE' }),
  6084. // Edit failure_reason / status on a single Print Log row (#1687 part 4).
  6085. // Distinct from updateArchive: archives describe the model, log entries
  6086. // describe a single print event. Orphan entries (no archive_id) have no
  6087. // archive to reach through and this is the only path to classify them.
  6088. updatePrintLogEntry: (
  6089. id: number,
  6090. body: { failure_reason?: string | null; status?: string; notes?: string | null },
  6091. ) =>
  6092. request<PrintLogEntry>(`/print-log/${id}`, {
  6093. method: 'PATCH',
  6094. body: JSON.stringify(body),
  6095. }),
  6096. // Settings
  6097. getSettings: () => request<AppSettings>('/settings/'),
  6098. getDefaultSidebarOrder: () => request<{ default_sidebar_order: string }>('/settings/default-sidebar-order'),
  6099. // Public subset of settings for UI rendering — no settings:read required.
  6100. // Used by pages whose users may not have SETTINGS_READ (e.g. operators with
  6101. // only printers:clear_plate). Keep in sync with _UI_PREFERENCE_FIELDS in
  6102. // backend/app/api/routes/settings.py.
  6103. getUiPreferences: () =>
  6104. request<{
  6105. require_plate_clear?: boolean;
  6106. check_printer_firmware?: boolean;
  6107. camera_view_mode?: 'window' | 'embedded';
  6108. time_format?: 'system' | '12h' | '24h';
  6109. date_format?: string;
  6110. drying_presets?: string;
  6111. ams_humidity_thresholds?: string;
  6112. ams_humidity_good?: number;
  6113. ams_humidity_fair?: number;
  6114. ams_temp_good?: number;
  6115. ams_temp_fair?: number;
  6116. bed_cooled_threshold?: number;
  6117. nozzle_temp_presets?: string;
  6118. bed_temp_presets?: string;
  6119. chamber_temp_presets?: string;
  6120. fan_speed_presets?: string;
  6121. }>('/settings/ui-preferences'),
  6122. // Install configuration the app shell needs, for any signed-in user. Separate
  6123. // from getUiPreferences: that endpoint is public because its fields are
  6124. // defaults shipped with the app, while these describe how this deployment is
  6125. // configured. Neither requires settings:read -- which is the point, since a
  6126. // non-admin reading GET /settings gets a 403 and every gate that consults it
  6127. // silently takes its fallback (#3023). Keep in sync with _UI_FLAG_FIELDS in
  6128. // backend/app/api/routes/settings.py.
  6129. getUiFlags: () => request<UiSettings>('/settings/ui-flags'),
  6130. // The two above together: what a page needs from the settings when its user
  6131. // may not read GET /settings. See useUiSettings.
  6132. getUiSettings: async (): Promise<UiSettings> => {
  6133. const [preferences, flags] = await Promise.all([api.getUiPreferences(), api.getUiFlags()]);
  6134. return { ...(preferences as UiSettings), ...flags };
  6135. },
  6136. updateSettings: (data: AppSettingsUpdate) =>
  6137. request<AppSettings>('/settings/', {
  6138. method: 'PUT',
  6139. body: JSON.stringify(data),
  6140. }),
  6141. getMQTTStatus: () => request<MQTTStatus>('/settings/mqtt/status'),
  6142. exportBackup: async (): Promise<{ blob: Blob; filename: string }> => {
  6143. // New simplified backup - complete database + all files
  6144. const url = `${API_BASE}/settings/backup`;
  6145. const headers: Record<string, string> = {};
  6146. if (authToken) {
  6147. headers['Authorization'] = `Bearer ${authToken}`;
  6148. }
  6149. const response = await fetch(url, { headers });
  6150. // Check for errors
  6151. if (!response.ok) {
  6152. const errorText = await response.text();
  6153. throw new Error(errorText || `Backup failed with status ${response.status}`);
  6154. }
  6155. // Get filename from Content-Disposition header
  6156. const contentDisposition = response.headers.get('Content-Disposition');
  6157. let filename = 'bambuddy-backup.zip';
  6158. if (contentDisposition) {
  6159. const match = contentDisposition.match(/filename=([^;]+)/);
  6160. if (match) filename = match[1].trim().replace(/^"(.*)"$/, '$1');
  6161. }
  6162. const blob = await response.blob();
  6163. return { blob, filename };
  6164. },
  6165. importBackup: async (file: File) => {
  6166. // New simplified restore - replaces database + all directories
  6167. const formData = new FormData();
  6168. formData.append('file', file);
  6169. const url = `${API_BASE}/settings/restore`;
  6170. const headers: Record<string, string> = {};
  6171. if (authToken) {
  6172. headers['Authorization'] = `Bearer ${authToken}`;
  6173. }
  6174. const response = await fetch(url, {
  6175. method: 'POST',
  6176. headers,
  6177. body: formData,
  6178. });
  6179. const data = (await response.json().catch(() => null)) as {
  6180. success?: boolean;
  6181. message?: string;
  6182. detail?: string;
  6183. } | null;
  6184. // A refused restore is an HTTPException, so the body is {detail}, not
  6185. // {success, message}. Returning it unmapped made `success` undefined and
  6186. // `message` undefined too — the modal then raised an empty error toast,
  6187. // which is the one case where the reason matters most (e.g. a backup this
  6188. // version cannot import names the columns and both versions).
  6189. if (!response.ok) {
  6190. return { success: false, message: data?.detail ?? data?.message ?? '' };
  6191. }
  6192. return (data ?? { success: false, message: '' }) as {
  6193. success: boolean;
  6194. message: string;
  6195. };
  6196. },
  6197. checkFfmpeg: () =>
  6198. request<{ installed: boolean; path: string | null }>('/settings/check-ffmpeg'),
  6199. getNetworkInterfaces: () =>
  6200. request<{ interfaces: NetworkInterface[] }>('/settings/network-interfaces'),
  6201. // Cloud
  6202. getCloudStatus: () => request<CloudAuthStatus>('/cloud/status'),
  6203. cloudLogin: (email: string, password: string, region = 'global') =>
  6204. request<CloudLoginResponse>('/cloud/login', {
  6205. method: 'POST',
  6206. body: JSON.stringify({ email, password, region }),
  6207. }),
  6208. cloudVerify: (email: string, code: string, tfaKey?: string, region: string = 'global') =>
  6209. request<CloudLoginResponse>('/cloud/verify', {
  6210. method: 'POST',
  6211. body: JSON.stringify({ email, code, tfa_key: tfaKey, region }),
  6212. }),
  6213. cloudSetToken: (access_token: string, region: string = 'global') =>
  6214. request<CloudAuthStatus>('/cloud/token', {
  6215. method: 'POST',
  6216. body: JSON.stringify({ access_token, region }),
  6217. }),
  6218. cloudLogout: () =>
  6219. request<{ success: boolean }>('/cloud/logout', { method: 'POST' }),
  6220. // Orca Cloud — RFC 8628 device pairing. deviceStart() returns a short
  6221. // user_code + verification link; the user approves it in their Orca Cloud
  6222. // settings while the frontend polls devicePoll() every `interval` seconds
  6223. // until the status flips to 'complete' (or a terminal deny/expire).
  6224. orcaCloudDeviceStart: () =>
  6225. request<OrcaDeviceStartResponse>('/orca-cloud/device/start', {
  6226. method: 'POST',
  6227. }),
  6228. orcaCloudDevicePoll: () =>
  6229. request<OrcaDevicePollResponse>('/orca-cloud/device/poll', {
  6230. method: 'POST',
  6231. }),
  6232. orcaCloudStatus: () =>
  6233. request<OrcaAuthStatusResponse>('/orca-cloud/status'),
  6234. orcaCloudLogout: () =>
  6235. request<{ success: boolean }>('/orca-cloud/logout', { method: 'POST' }),
  6236. orcaCloudListProfiles: () =>
  6237. request<OrcaProfileListResponse>('/orca-cloud/profiles'),
  6238. orcaCloudGetProfile: (id: string) =>
  6239. request<OrcaProfileDetail>(`/orca-cloud/profiles/${id}`),
  6240. getCloudSettings: (version = '02.04.00.70') =>
  6241. request<SlicerSettingsResponse>(`/cloud/settings?version=${version}`),
  6242. getBuiltinFilaments: () =>
  6243. request<BuiltinFilament[]>('/cloud/builtin-filaments'),
  6244. getFilamentIdMap: () =>
  6245. request<Record<string, string>>('/cloud/filament-id-map'),
  6246. /** Material-disambiguated hex→name lookup. Same hex can map to different
  6247. * catalog names depending on material (e.g. #000000 is "Charcoal" in PLA
  6248. * Matte but "Black" in PLA Basic). The flat ``/inventory/colors/map``
  6249. * collapses these to the first hit; this endpoint preserves the material
  6250. * context. Returns ``{color_name: null}`` when the hex isn't in the
  6251. * catalog at all. #1718. */
  6252. getColorByMaterial: (hex: string, material?: string) => {
  6253. const params = new URLSearchParams({ hex });
  6254. if (material) params.set('material', material);
  6255. return request<{ color_name: string | null }>(
  6256. `/inventory/colors/by-material?${params.toString()}`,
  6257. );
  6258. },
  6259. // MakerWorld URL-paste import flow.
  6260. getMakerworldStatus: () =>
  6261. request<MakerworldStatus>('/makerworld/status'),
  6262. resolveMakerworldUrl: (url: string) =>
  6263. request<MakerworldResolvedModel>('/makerworld/resolve', {
  6264. method: 'POST',
  6265. body: JSON.stringify({ url }),
  6266. }),
  6267. getMakerworldRecentImports: (limit = 10) =>
  6268. request<MakerworldRecentImport[]>(`/makerworld/recent-imports?limit=${limit}`),
  6269. importMakerworldInstance: (
  6270. model_id: number,
  6271. instance_id: number | null,
  6272. profile_id?: number | null,
  6273. folder_id?: number | null,
  6274. ) =>
  6275. request<MakerworldImportResponse>('/makerworld/import', {
  6276. method: 'POST',
  6277. body: JSON.stringify({
  6278. model_id,
  6279. instance_id: instance_id ?? null,
  6280. profile_id: profile_id ?? null,
  6281. folder_id: folder_id ?? null,
  6282. }),
  6283. }),
  6284. // Manyfold (#1471).
  6285. getManyfoldConfig: () => request<ManyfoldConfig>('/manyfold/config'),
  6286. updateManyfoldConfig: (data: ManyfoldConfigInput) =>
  6287. request<ManyfoldConfig>('/manyfold/config', { method: 'PUT', body: JSON.stringify(data) }),
  6288. deleteManyfoldConfig: () => request<void>('/manyfold/config', { method: 'DELETE' }),
  6289. testManyfoldConfig: (data: ManyfoldConfigInput) =>
  6290. request<{ model_count: number }>('/manyfold/config/test', { method: 'POST', body: JSON.stringify(data) }),
  6291. getManyfoldStatus: () => request<ManyfoldStatus>('/manyfold/status'),
  6292. listManyfoldModels: (query: string, page: number) => {
  6293. const params = new URLSearchParams({ page: String(page) });
  6294. if (query) params.set('q', query);
  6295. return request<ManyfoldModelList>(`/manyfold/models?${params.toString()}`);
  6296. },
  6297. getManyfoldModel: (modelId: string) =>
  6298. request<ManyfoldModel>(`/manyfold/models/${encodeURIComponent(modelId)}`),
  6299. /** The model's preview, or null when it has none. Fetched rather than used
  6300. * as an <img src>: a failing protected <img> makes the app renew its media
  6301. * token, and models without a preview answer 404. */
  6302. getManyfoldPreview: async (modelId: string): Promise<Blob | null> => {
  6303. const headers: Record<string, string> = {};
  6304. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  6305. const response = await fetch(`${API_BASE}/manyfold/models/${encodeURIComponent(modelId)}/preview`, { headers });
  6306. if (!response.ok) return null;
  6307. return response.blob();
  6308. },
  6309. importManyfoldFile: (modelId: string, fileId: string, folderId: number | null) =>
  6310. request<ManyfoldImportResponse>('/manyfold/import', {
  6311. method: 'POST',
  6312. body: JSON.stringify({ model_id: modelId, file_id: fileId, folder_id: folderId }),
  6313. }),
  6314. getCloudSettingDetail: (settingId: string) =>
  6315. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`),
  6316. createCloudSetting: (data: SlicerSettingCreate) =>
  6317. request<SlicerSettingDetail>('/cloud/settings', {
  6318. method: 'POST',
  6319. body: JSON.stringify(data),
  6320. }),
  6321. updateCloudSetting: (settingId: string, data: SlicerSettingUpdate) =>
  6322. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`, {
  6323. method: 'PUT',
  6324. body: JSON.stringify(data),
  6325. }),
  6326. deleteCloudSetting: (settingId: string) =>
  6327. request<SlicerSettingDeleteResponse>(`/cloud/settings/${settingId}`, {
  6328. method: 'DELETE',
  6329. }),
  6330. getCloudFields: (presetType: 'filament' | 'print' | 'process' | 'printer') =>
  6331. request<FieldDefinitionsResponse>(`/cloud/fields/${presetType}`),
  6332. getFilamentInfo: (settingIds: string[]) =>
  6333. request<Record<string, { name: string; k: number | null }>>('/cloud/filament-info', {
  6334. method: 'POST',
  6335. body: JSON.stringify(settingIds),
  6336. }),
  6337. // Smart Plugs
  6338. getSmartPlugs: () => request<SmartPlug[]>('/smart-plugs/'),
  6339. getSmartPlugByPrinter: (printerId: number) => smartPlugBatch(printerId),
  6340. getScriptPlugsByPrinter: (printerId: number) => scriptPlugsBatch(printerId),
  6341. createSmartPlug: (data: SmartPlugCreate) =>
  6342. request<SmartPlug>('/smart-plugs/', {
  6343. method: 'POST',
  6344. body: JSON.stringify(data),
  6345. }),
  6346. updateSmartPlug: (id: number, data: SmartPlugUpdate) =>
  6347. request<SmartPlug>(`/smart-plugs/${id}`, {
  6348. method: 'PATCH',
  6349. body: JSON.stringify(data),
  6350. }),
  6351. deleteSmartPlug: (id: number) =>
  6352. request<void>(`/smart-plugs/${id}`, { method: 'DELETE' }),
  6353. controlSmartPlug: (id: number, action: 'on' | 'off' | 'toggle') =>
  6354. request<{ success: boolean; action: string }>(`/smart-plugs/${id}/control`, {
  6355. method: 'POST',
  6356. body: JSON.stringify({ action }),
  6357. }),
  6358. getSmartPlugStatus: (id: number) =>
  6359. request<SmartPlugStatus>(`/smart-plugs/${id}/status`),
  6360. // plug_id: the saved plug being edited, whose stored password fills in the placeholder.
  6361. testSmartPlugConnection: (ip_address: string, username?: string | null, password?: string | null, plug_id?: number) =>
  6362. request<SmartPlugTestResult>('/smart-plugs/test-connection', {
  6363. method: 'POST',
  6364. body: JSON.stringify({ ip_address, username, password, plug_id }),
  6365. }),
  6366. // Tasmota Discovery (auto-detects network)
  6367. startTasmotaScan: () =>
  6368. request<TasmotaScanStatus>('/smart-plugs/discover/scan', { method: 'POST' }),
  6369. getTasmotaScanStatus: () =>
  6370. request<TasmotaScanStatus>('/smart-plugs/discover/status'),
  6371. stopTasmotaScan: () =>
  6372. request<TasmotaScanStatus>('/smart-plugs/discover/stop', { method: 'POST' }),
  6373. getDiscoveredTasmotaDevices: () =>
  6374. request<DiscoveredTasmotaDevice[]>('/smart-plugs/discover/devices'),
  6375. // Home Assistant Integration
  6376. testHAConnection: (url: string, token: string) =>
  6377. request<HATestConnectionResult>('/smart-plugs/ha/test-connection', {
  6378. method: 'POST',
  6379. body: JSON.stringify({ url, token }),
  6380. }),
  6381. getHAEntities: (search?: string) => {
  6382. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  6383. return request<HAEntity[]>(`/smart-plugs/ha/entities${params}`);
  6384. },
  6385. getHASensorEntities: () =>
  6386. request<HASensorEntity[]>('/smart-plugs/ha/sensors'),
  6387. // Home Assistant sensors bound to a printer (#1148, #448)
  6388. getHASensors: (printerId?: number) =>
  6389. request<PrinterHASensor[]>(`/ha-sensors/${printerId ? `?printer_id=${printerId}` : ''}`),
  6390. getHASensorReadings: (printerId: number) => haSensorReadingsBatch(printerId),
  6391. getBindableHAEntities: (search?: string) => {
  6392. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  6393. return request<HADisplayEntity[]>(`/ha-sensors/entities${params}`);
  6394. },
  6395. createHASensor: (data: PrinterHASensorCreate) =>
  6396. request<PrinterHASensor>('/ha-sensors/', { method: 'POST', body: JSON.stringify(data) }),
  6397. updateHASensor: (id: number, data: PrinterHASensorUpdate) =>
  6398. request<PrinterHASensor>(`/ha-sensors/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  6399. deleteHASensor: (id: number) =>
  6400. request<{ message: string }>(`/ha-sensors/${id}`, { method: 'DELETE' }),
  6401. getLocationHASensors: (locationId?: number) =>
  6402. request<LocationHASensor[]>(`/location-ha-sensors/${locationId ? `?location_id=${locationId}` : ''}`),
  6403. getLocationHASensorReadings: (locationId: number, showOnCard = true) =>
  6404. request<LocationHASensorReading[]>(
  6405. `/location-ha-sensors/by-location/${locationId}/readings?show_on_card=${showOnCard}`
  6406. ),
  6407. getBindableLocationHAEntities: (search?: string) => {
  6408. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  6409. return request<HADisplayEntity[]>(`/location-ha-sensors/entities${params}`);
  6410. },
  6411. createLocationHASensor: (data: LocationHASensorCreate) =>
  6412. request<LocationHASensor>('/location-ha-sensors/', { method: 'POST', body: JSON.stringify(data) }),
  6413. updateLocationHASensor: (id: number, data: LocationHASensorUpdate) =>
  6414. request<LocationHASensor>(`/location-ha-sensors/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  6415. deleteLocationHASensor: (id: number) =>
  6416. request<{ message: string }>(`/location-ha-sensors/${id}`, { method: 'DELETE' }),
  6417. // REST smart plug
  6418. // plug_id: the saved plug being edited, whose stored headers fill in the placeholder.
  6419. testRESTConnection: (url: string, method: string = 'GET', headers?: string | null, plug_id?: number) =>
  6420. request<{ success: boolean; error: string | null }>('/smart-plugs/rest/test-connection', {
  6421. method: 'POST',
  6422. body: JSON.stringify({ url, method, headers, plug_id }),
  6423. }),
  6424. // Print Queue
  6425. getQueue: (printerId?: number, status?: string, targetModel?: string) => {
  6426. const params = new URLSearchParams();
  6427. if (printerId) params.set('printer_id', String(printerId));
  6428. if (status) params.set('status', status);
  6429. if (targetModel) params.set('target_model', targetModel);
  6430. return request<PrintQueueItem[]>(`/queue/?${params}`);
  6431. },
  6432. // History (completed / failed / skipped / cancelled), one page at a time.
  6433. getQueueHistory: (params: QueueHistoryParams) =>
  6434. request<QueueHistoryPage>(`/queue/history?${queueHistorySearch(params)}`),
  6435. // Removes the history matching the same filters, server-side.
  6436. clearQueueHistory: (params: QueueHistoryFilters) =>
  6437. request<{ cleared: number; kept: number }>(`/queue/history/clear?${queueHistorySearch(params)}`, {
  6438. method: 'POST',
  6439. }),
  6440. // One printer's queue as GET /queue/?printer_id= returns it: its own jobs
  6441. // plus the "Any <model>" jobs for its model. Batched across printer cards.
  6442. getPrinterQueue: (printerId: number, status: string) => printerQueueBatch(status)(printerId),
  6443. addToQueue: (data: PrintQueueItemCreate) =>
  6444. request<PrintQueueItem>('/queue/', {
  6445. method: 'POST',
  6446. body: JSON.stringify(data),
  6447. }),
  6448. updateQueueItem: (id: number, data: PrintQueueItemUpdate) =>
  6449. request<PrintQueueItem>(`/queue/${id}`, {
  6450. method: 'PATCH',
  6451. body: JSON.stringify(data),
  6452. }),
  6453. /** `deleted` is false when the item was kept as cancelled instead: it is the
  6454. * last run a batch order could re-queue its plate from (#2960). */
  6455. removeFromQueue: (id: number) =>
  6456. request<{ message: string; deleted: boolean }>(`/queue/${id}`, { method: 'DELETE' }),
  6457. reorderQueue: (items: { id: number; position: number }[]) =>
  6458. request<{ message: string }>('/queue/reorder', {
  6459. method: 'POST',
  6460. body: JSON.stringify({ items }),
  6461. }),
  6462. cancelQueueItem: (id: number) =>
  6463. request<{ message: string }>(`/queue/${id}/cancel`, { method: 'POST' }),
  6464. stopQueueItem: (id: number) =>
  6465. request<{ message: string }>(`/queue/${id}/stop`, { method: 'POST' }),
  6466. /**
  6467. * Start a staged queue item. The backend re-checks live filament deficit
  6468. * for the assigned spool and, when short, returns 409 with a structured
  6469. * payload so the caller can confirm and retry. Pass `skipFilamentCheck`
  6470. * after the user confirms "Print Anyway" (#1496).
  6471. */
  6472. startQueueItem: (id: number, opts?: { skipFilamentCheck?: boolean }) => {
  6473. const qs = opts?.skipFilamentCheck ? '?skip_filament_check=true' : '';
  6474. return request<PrintQueueItem>(`/queue/${id}/start${qs}`, { method: 'POST' });
  6475. },
  6476. /**
  6477. * Clear the `require_previous_success` gate for a printer after the user
  6478. * resolves the failure. Acknowledges any failed/aborted predecessors and
  6479. * restores skipped items whose error_message matches the gate string
  6480. * back to pending. Returns counts so the UI can render a precise toast.
  6481. */
  6482. // A job for any printer of a model waits when the last print failed on every
  6483. // free one; this clears the gate on the model's printers.
  6484. resumeModelQueueAfterFailure: (model: string) =>
  6485. request<{ acknowledged: number; printers: number }>(
  6486. `/queue/model/${encodeURIComponent(model)}/resume`,
  6487. { method: 'POST' },
  6488. ),
  6489. resumeQueueAfterFailure: (printerId: number) =>
  6490. request<{ acknowledged: number; restored: number }>(
  6491. `/queue/printer/${printerId}/resume`,
  6492. { method: 'POST' },
  6493. ),
  6494. bulkUpdateQueue: (data: PrintQueueBulkUpdate) =>
  6495. request<PrintQueueBulkUpdateResponse>('/queue/bulk', {
  6496. method: 'PATCH',
  6497. body: JSON.stringify(data),
  6498. }),
  6499. // Batches
  6500. getBatches: (status?: string) => {
  6501. const params = status ? `?status=${status}` : '';
  6502. return request<PrintBatch[]>(`/queue/batches${params}`);
  6503. },
  6504. cancelBatch: (id: number) =>
  6505. request<{ message: string }>(`/queue/batches/${id}`, { method: 'DELETE' }),
  6506. createBatch: (data: PrintBatchCreate) =>
  6507. request<PrintBatch>('/queue/batches', {
  6508. method: 'POST',
  6509. body: JSON.stringify(data),
  6510. }),
  6511. dispatchBatch: (id: number, data: PrintBatchDispatchRequest = {}) =>
  6512. request<PrintBatch>(`/queue/batches/${id}/dispatch`, {
  6513. method: 'POST',
  6514. body: JSON.stringify(data),
  6515. }),
  6516. ungroupBatch: (id: number) =>
  6517. request<{ ungrouped_count: number; message: string }>(
  6518. `/queue/batches/${id}/ungroup`,
  6519. { method: 'POST' },
  6520. ),
  6521. // K-Profiles
  6522. getKProfiles: (printerId: number, nozzleDiameter = '0.4') =>
  6523. request<KProfilesResponse>(`/printers/${printerId}/kprofiles/?nozzle_diameter=${nozzleDiameter}`),
  6524. setKProfile: (printerId: number, profile: KProfileCreate) =>
  6525. request<KProfileWriteResult>(`/printers/${printerId}/kprofiles/`, {
  6526. method: 'POST',
  6527. body: JSON.stringify(profile),
  6528. }),
  6529. deleteKProfile: (printerId: number, profile: KProfileDelete) =>
  6530. request<KProfileWriteResult>(`/printers/${printerId}/kprofiles/`, {
  6531. method: 'DELETE',
  6532. body: JSON.stringify(profile),
  6533. }),
  6534. setKProfilesBatch: (printerId: number, profiles: KProfileCreate[]) =>
  6535. request<KProfileWriteResult>(`/printers/${printerId}/kprofiles/batch`, {
  6536. method: 'POST',
  6537. body: JSON.stringify(profiles),
  6538. }),
  6539. // Finance
  6540. getMyBalance: () => request<WalletBalance>('/finance/me/balance'),
  6541. getMyTransactions: (limit = 50, offset = 0) =>
  6542. request<WalletTransactionListResponse>(`/finance/me/transactions?limit=${limit}&offset=${offset}`),
  6543. getAllTransactions: (limit = 50, offset = 0, userId?: number) => {
  6544. const params = new URLSearchParams();
  6545. params.set('limit', String(limit));
  6546. params.set('offset', String(offset));
  6547. if (userId !== undefined) params.set('user_id', String(userId));
  6548. return request<WalletTransactionListResponse>(`/finance/transactions?${params.toString()}`);
  6549. },
  6550. deleteTransaction: (transactionId: number) =>
  6551. request<{ status: string }>(`/finance/transactions/${transactionId}`, {
  6552. method: 'DELETE',
  6553. }),
  6554. editTransaction: (transactionId: number, data: TransactionEditRequest) =>
  6555. request<WalletTransaction>(`/finance/transactions/${transactionId}`, {
  6556. method: 'PATCH',
  6557. body: JSON.stringify(data),
  6558. }),
  6559. createManualPrint: (data: ManualPrintRequest) =>
  6560. request<WalletTransaction>('/finance/transactions/manual', {
  6561. method: 'POST',
  6562. body: JSON.stringify(data),
  6563. }),
  6564. getMyCostCenters: () => request<CostCenterSummary[]>('/finance/cost-centers/mine'),
  6565. listCostCenters: (includeInactive = false) =>
  6566. request<CostCenterSummary[]>(`/finance/cost-centers?include_inactive=${includeInactive ? 'true' : 'false'}`),
  6567. createCostCenter: (data: CostCenterCreateRequest) =>
  6568. request<CostCenterSummary>('/finance/cost-centers', {
  6569. method: 'POST',
  6570. body: JSON.stringify(data),
  6571. }),
  6572. updateCostCenter: (costCenterId: number, data: CostCenterUpdateRequest) =>
  6573. request<CostCenterSummary>(`/finance/cost-centers/${costCenterId}`, {
  6574. method: 'PATCH',
  6575. body: JSON.stringify(data),
  6576. }),
  6577. updateCostCenterBudgets: (costCenterId: number, data: CostCenterBudgetUpdateRequest) =>
  6578. request<CostCenterSummary>(`/finance/cost-centers/${costCenterId}/budgets`, {
  6579. method: 'PATCH',
  6580. body: JSON.stringify(data),
  6581. }),
  6582. deleteCostCenter: (costCenterId: number) =>
  6583. request<{ status: string }>(`/finance/cost-centers/${costCenterId}`, {
  6584. method: 'DELETE',
  6585. }),
  6586. getCostCenter: (costCenterId: number) =>
  6587. request<CostCenterDetail>(`/finance/cost-centers/${costCenterId}`),
  6588. upsertCostCenterMember: (costCenterId: number, data: CostCenterMemberRequest) =>
  6589. request<CostCenterMemberResponse>(`/finance/cost-centers/${costCenterId}/members`, {
  6590. method: 'POST',
  6591. body: JSON.stringify(data),
  6592. }),
  6593. removeCostCenterMember: (costCenterId: number, userId: number) =>
  6594. request<{ status: string }>(`/finance/cost-centers/${costCenterId}/members/${userId}`, {
  6595. method: 'DELETE',
  6596. }),
  6597. depositUserBalance: (userId: number, data: WalletAdjustmentRequest) =>
  6598. request<WalletAdjustmentResponse>(`/finance/users/${userId}/deposit`, {
  6599. method: 'POST',
  6600. body: JSON.stringify(data),
  6601. }),
  6602. withdrawUserBalance: (userId: number, data: WalletAdjustmentRequest) =>
  6603. request<WalletAdjustmentResponse>(`/finance/users/${userId}/withdraw`, {
  6604. method: 'POST',
  6605. body: JSON.stringify(data),
  6606. }),
  6607. rebuildBalanceLedger: () =>
  6608. request<{ status: string }>('/finance/rebuild-balance-ledger', {
  6609. method: 'POST',
  6610. }),
  6611. // K-Profile Notes (stored locally, not on printer)
  6612. getKProfileNotes: (printerId: number) =>
  6613. request<KProfileNotesResponse>(`/printers/${printerId}/kprofiles/notes`),
  6614. setKProfileNote: (printerId: number, settingId: string, note: string) =>
  6615. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/notes`, {
  6616. method: 'PUT',
  6617. body: JSON.stringify({ setting_id: settingId, note }),
  6618. }),
  6619. // Slot Preset Mappings
  6620. getSlotPresets: (printerId: number) => slotPresetsBatch(printerId),
  6621. saveSlotPreset: (printerId: number, amsId: number, trayId: number, presetId: string, presetName: string, presetSource = 'cloud', trayInfoIdx?: string) =>
  6622. 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)}` : ''}`, {
  6623. method: 'PUT',
  6624. }),
  6625. // AMS Labels (user-defined friendly names)
  6626. getAmsLabels: (printerId: number) => amsLabelsBatch(printerId),
  6627. saveAmsLabel: (printerId: number, amsId: number, label: string, amsSerial = '') =>
  6628. request<{ ams_id: number; label: string }>(
  6629. `/printers/${printerId}/ams-labels/${amsId}`,
  6630. {
  6631. method: 'PUT',
  6632. body: JSON.stringify({ label, ams_serial: amsSerial }),
  6633. }
  6634. ),
  6635. deleteAmsLabel: (printerId: number, amsId: number, amsSerial = '') =>
  6636. request<{ success: boolean }>(`/printers/${printerId}/ams-labels/${amsId}?ams_serial=${encodeURIComponent(amsSerial)}`, {
  6637. method: 'DELETE',
  6638. }),
  6639. configureAmsSlot: (
  6640. printerId: number,
  6641. amsId: number,
  6642. trayId: number,
  6643. config: {
  6644. tray_info_idx: string;
  6645. tray_type: string;
  6646. tray_sub_brands: string;
  6647. tray_color: string;
  6648. nozzle_temp_min: number;
  6649. nozzle_temp_max: number;
  6650. cali_idx: number;
  6651. nozzle_diameter: string;
  6652. setting_id?: string;
  6653. kprofile_filament_id?: string;
  6654. kprofile_setting_id?: string;
  6655. k_value?: number;
  6656. // Orca Cloud profile the slot is set to; the backend looks up its
  6657. // filament id when tray_info_idx is empty (#3216).
  6658. orca_profile_id?: string;
  6659. }
  6660. ) => {
  6661. const params = new URLSearchParams({
  6662. tray_info_idx: config.tray_info_idx,
  6663. tray_type: config.tray_type,
  6664. tray_sub_brands: config.tray_sub_brands,
  6665. tray_color: config.tray_color,
  6666. nozzle_temp_min: config.nozzle_temp_min.toString(),
  6667. nozzle_temp_max: config.nozzle_temp_max.toString(),
  6668. cali_idx: config.cali_idx.toString(),
  6669. nozzle_diameter: config.nozzle_diameter,
  6670. });
  6671. if (config.setting_id) {
  6672. params.set('setting_id', config.setting_id);
  6673. }
  6674. if (config.kprofile_filament_id) {
  6675. params.set('kprofile_filament_id', config.kprofile_filament_id);
  6676. }
  6677. if (config.kprofile_setting_id) {
  6678. params.set('kprofile_setting_id', config.kprofile_setting_id);
  6679. }
  6680. if (config.k_value !== undefined && config.k_value > 0) {
  6681. params.set('k_value', config.k_value.toString());
  6682. }
  6683. if (config.orca_profile_id) {
  6684. params.set('orca_profile_id', config.orca_profile_id);
  6685. }
  6686. return request<{
  6687. success: boolean;
  6688. message: string;
  6689. // The filament id the slot was actually given.
  6690. tray_info_idx?: string;
  6691. // Why an Orca profile went out as the generic for its material, or "".
  6692. orca_fallback_reason?: '' | 'no_filament_id' | 'lookup_failed' | 'no_permission';
  6693. /** A manual K value could not be sent; the filament setting was. */
  6694. k_value_unsent?: boolean;
  6695. }>(
  6696. `/printers/${printerId}/slots/${amsId}/${trayId}/configure?${params}`,
  6697. { method: 'POST' }
  6698. );
  6699. },
  6700. resetAmsSlot: (printerId: number, amsId: number, trayId: number) =>
  6701. request<{ success: boolean; message: string }>(
  6702. `/printers/${printerId}/ams/${amsId}/tray/${trayId}/reset`,
  6703. { method: 'POST' }
  6704. ),
  6705. // Notification Providers
  6706. getNotificationProviders: () => request<NotificationProvider[]>('/notifications/'),
  6707. createNotificationProvider: (data: NotificationProviderCreate) =>
  6708. request<NotificationProvider>('/notifications/', {
  6709. method: 'POST',
  6710. body: JSON.stringify(data),
  6711. }),
  6712. updateNotificationProvider: (id: number, data: NotificationProviderUpdate) =>
  6713. request<NotificationProvider>(`/notifications/${id}`, {
  6714. method: 'PATCH',
  6715. body: JSON.stringify(data),
  6716. }),
  6717. deleteNotificationProvider: (id: number) =>
  6718. request<{ message: string }>(`/notifications/${id}`, { method: 'DELETE' }),
  6719. testNotificationProvider: (id: number) =>
  6720. request<NotificationTestResponse>(`/notifications/${id}/test`, { method: 'POST' }),
  6721. testNotificationConfig: (data: NotificationTestRequest) =>
  6722. request<NotificationTestResponse>('/notifications/test-config', {
  6723. method: 'POST',
  6724. body: JSON.stringify(data),
  6725. }),
  6726. testAllNotificationProviders: () =>
  6727. request<{
  6728. tested: number;
  6729. success: number;
  6730. failed: number;
  6731. results: Array<{
  6732. provider_id: number;
  6733. provider_name: string;
  6734. provider_type: string;
  6735. success: boolean;
  6736. message: string;
  6737. }>;
  6738. }>('/notifications/test-all', { method: 'POST' }),
  6739. // Notification Templates
  6740. getNotificationTemplates: () => request<NotificationTemplate[]>('/notification-templates'),
  6741. updateNotificationTemplate: (id: number, data: NotificationTemplateUpdate) =>
  6742. request<NotificationTemplate>(`/notification-templates/${id}`, {
  6743. method: 'PUT',
  6744. body: JSON.stringify(data),
  6745. }),
  6746. resetNotificationTemplate: (id: number) =>
  6747. request<NotificationTemplate>(`/notification-templates/${id}/reset`, {
  6748. method: 'POST',
  6749. }),
  6750. getTemplateVariables: () => request<EventVariablesResponse[]>('/notification-templates/variables'),
  6751. previewTemplate: (data: TemplatePreviewRequest) =>
  6752. request<TemplatePreviewResponse>('/notification-templates/preview', {
  6753. method: 'POST',
  6754. body: JSON.stringify(data),
  6755. }),
  6756. // Notification Logs
  6757. getNotificationLogs: (params?: {
  6758. limit?: number;
  6759. offset?: number;
  6760. provider_id?: number;
  6761. event_type?: string;
  6762. success?: boolean;
  6763. days?: number;
  6764. }) => {
  6765. const searchParams = new URLSearchParams();
  6766. if (params?.limit) searchParams.set('limit', String(params.limit));
  6767. if (params?.offset) searchParams.set('offset', String(params.offset));
  6768. if (params?.provider_id) searchParams.set('provider_id', String(params.provider_id));
  6769. if (params?.event_type) searchParams.set('event_type', params.event_type);
  6770. if (params?.success !== undefined) searchParams.set('success', String(params.success));
  6771. if (params?.days) searchParams.set('days', String(params.days));
  6772. return request<NotificationLogEntry[]>(`/notifications/logs?${searchParams}`);
  6773. },
  6774. getNotificationLogStats: (days = 7) =>
  6775. request<NotificationLogStats>(`/notifications/logs/stats?days=${days}`),
  6776. clearNotificationLogs: (olderThanDays = 30) =>
  6777. request<{ deleted: number; message: string }>(
  6778. `/notifications/logs?older_than_days=${olderThanDays}`,
  6779. { method: 'DELETE' }
  6780. ),
  6781. // Spoolman Integration
  6782. getSpoolmanStatus: () => request<SpoolmanStatus>('/spoolman/status'),
  6783. migrateSpoolmanTags: (dryRun: boolean) =>
  6784. request<SpoolmanTagMigrationReport>(`/spoolman/inventory/tags/migrate?dry_run=${dryRun}`, {
  6785. method: 'POST',
  6786. }),
  6787. connectSpoolman: () =>
  6788. request<{ success: boolean; message: string }>('/spoolman/connect', {
  6789. method: 'POST',
  6790. }),
  6791. syncPrinterAms: (printerId: number) =>
  6792. request<SpoolmanSyncResult>(`/spoolman/sync/${printerId}`, {
  6793. method: 'POST',
  6794. }),
  6795. syncAllPrintersAms: () =>
  6796. request<SpoolmanSyncResult>('/spoolman/sync-all', {
  6797. method: 'POST',
  6798. }),
  6799. getSpoolmanInventoryFilaments: () =>
  6800. request<SpoolmanFilamentEntry[]>('/spoolman/inventory/filaments'),
  6801. getUnlinkedSpools: () =>
  6802. request<UnlinkedSpool[]>('/spoolman/spools/unlinked'),
  6803. getLinkedSpools: () =>
  6804. request<LinkedSpoolsMap>('/spoolman/spools/linked'),
  6805. linkSpool: (
  6806. spoolId: number,
  6807. context: {
  6808. spoolTag: string;
  6809. printerId: number;
  6810. amsId: number;
  6811. trayId: number;
  6812. }
  6813. ) =>
  6814. request<{ success: boolean; message: string }>(`/spoolman/spools/${spoolId}/link`, {
  6815. method: 'POST',
  6816. body: JSON.stringify({
  6817. spool_tag: context.spoolTag,
  6818. printer_id: context.printerId,
  6819. ams_id: context.amsId,
  6820. tray_id: context.trayId,
  6821. }),
  6822. }),
  6823. unlinkSpool: (spoolId: number) =>
  6824. request<{ success: boolean; message: string }>(`/spoolman/spools/${spoolId}/unlink`, {
  6825. method: 'POST',
  6826. }),
  6827. createSpoolmanSpoolFromSlot: (data: { printer_id: number; ams_id: number; tray_id: number }) =>
  6828. request<{ success: boolean; spool_id: number | null }>(`/spoolman/spools/from-slot`, {
  6829. method: 'POST',
  6830. body: JSON.stringify(data),
  6831. }),
  6832. createSpoolFromSlot: (data: { printer_id: number; ams_id: number; tray_id: number }) =>
  6833. request<InventorySpool>(`/inventory/spools/from-slot`, {
  6834. method: 'POST',
  6835. body: JSON.stringify(data),
  6836. }),
  6837. getSpoolmanSettings: () =>
  6838. 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'),
  6839. 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; }) =>
  6840. 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', {
  6841. method: 'PUT',
  6842. body: JSON.stringify(data),
  6843. }),
  6844. // Inventory
  6845. getSpools: (includeArchived = false) =>
  6846. request<InventorySpool[]>(`/inventory/spools?include_archived=${includeArchived}`),
  6847. getSpool: (id: number) => request<InventorySpool>(`/inventory/spools/${id}`),
  6848. createSpool: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>) =>
  6849. request<InventorySpool>('/inventory/spools', {
  6850. method: 'POST',
  6851. body: JSON.stringify(data),
  6852. }),
  6853. bulkCreateSpools: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>, quantity: number) =>
  6854. request<InventorySpool[]>('/inventory/spools/bulk', {
  6855. method: 'POST',
  6856. body: JSON.stringify({ spool: data, quantity }),
  6857. }),
  6858. // ── CSV import/export (#1576) ────────────────────────────────────────────
  6859. // dry_run=true → preview (no write); omitted → real import. Both share one
  6860. // multipart upload helper; see `uploadSpoolsCsv` below.
  6861. importSpoolsCsvPreview: (file: File): Promise<CsvImportPreview> => uploadSpoolsCsv<CsvImportPreview>(file, true),
  6862. importSpoolsCsv: (file: File): Promise<CsvImportResult> => uploadSpoolsCsv<CsvImportResult>(file, false),
  6863. exportSpoolsCsv: async (): Promise<void> => {
  6864. const headers: Record<string, string> = {};
  6865. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  6866. const response = await fetch(`${API_BASE}/inventory/spools/export`, { headers });
  6867. if (!response.ok) {
  6868. const error = await response.json().catch(() => ({}));
  6869. throw new Error(error.detail || `HTTP ${response.status}`);
  6870. }
  6871. const disposition = response.headers.get('Content-Disposition');
  6872. const filename = parseContentDispositionFilename(disposition) || 'bambuddy_inventory.csv';
  6873. const blob = await response.blob();
  6874. const url = window.URL.createObjectURL(blob);
  6875. const a = document.createElement('a');
  6876. a.href = url;
  6877. a.download = filename;
  6878. document.body.appendChild(a);
  6879. a.click();
  6880. document.body.removeChild(a);
  6881. window.URL.revokeObjectURL(url);
  6882. },
  6883. updateSpool: (id: number, data: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  6884. request<InventorySpool>(`/inventory/spools/${id}`, {
  6885. method: 'PATCH',
  6886. body: JSON.stringify(data),
  6887. }),
  6888. deleteSpool: (id: number) =>
  6889. request<{ status: string }>(`/inventory/spools/${id}`, { method: 'DELETE' }),
  6890. archiveSpool: (id: number) =>
  6891. request<InventorySpool>(`/inventory/spools/${id}/archive`, { method: 'POST' }),
  6892. restoreSpool: (id: number) =>
  6893. request<InventorySpool>(`/inventory/spools/${id}/restore`, { method: 'POST' }),
  6894. resetSpoolConsumedCounter: (id: number) =>
  6895. request<InventorySpool>(`/inventory/spools/${id}/reset-consumed-counter`, { method: 'POST' }),
  6896. bulkResetSpoolConsumedCounter: (spoolIds: number[]) =>
  6897. request<{ reset: number; not_found?: number[]; errors?: Array<{ id: number; status: number; detail: string }> }>(`/inventory/spools/reset-consumed-counter-bulk`, {
  6898. method: 'POST',
  6899. body: JSON.stringify({ spool_ids: spoolIds }),
  6900. }),
  6901. bulkUpdateSpools: (ids: number[], update: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  6902. request<{ updated: number; not_found: number[] }>(`/inventory/spools/bulk-update`, {
  6903. method: 'POST',
  6904. body: JSON.stringify({ ids, update }),
  6905. }),
  6906. bulkDeleteSpools: (ids: number[]) =>
  6907. request<{ deleted: number; not_found: number[] }>(`/inventory/spools/bulk-delete`, {
  6908. method: 'POST',
  6909. body: JSON.stringify({ ids }),
  6910. }),
  6911. bulkArchiveSpools: (ids: number[]) =>
  6912. request<{ archived: number; already_archived: number[]; not_found: number[] }>(`/inventory/spools/bulk-archive`, {
  6913. method: 'POST',
  6914. body: JSON.stringify({ ids }),
  6915. }),
  6916. bulkRestoreSpools: (ids: number[]) =>
  6917. request<{ restored: number; already_active: number[]; not_found: number[] }>(`/inventory/spools/bulk-restore`, {
  6918. method: 'POST',
  6919. body: JSON.stringify({ ids }),
  6920. }),
  6921. getSpoolKProfiles: (spoolId: number) =>
  6922. request<SpoolKProfile[]>(`/inventory/spools/${spoolId}/k-profiles`),
  6923. saveSpoolKProfiles: (spoolId: number, profiles: SpoolKProfileInput[]) =>
  6924. request<SpoolKProfile[]>(`/inventory/spools/${spoolId}/k-profiles`, {
  6925. method: 'PUT',
  6926. body: JSON.stringify(profiles),
  6927. }),
  6928. /**
  6929. * What the spool assigned to this slot is configured to use *here* -- its
  6930. * per-printer-model filament preset and the K profile for this slot's hotend.
  6931. * Nulls when the slot holds no known spool.
  6932. */
  6933. getSlotSpoolDefaults: (printerId: number, amsId: number, trayId: number) =>
  6934. request<SlotSpoolDefaults>(`/printers/${printerId}/slots/${amsId}/${trayId}/spool-defaults`),
  6935. getSpoolFilamentPresets: (spoolId: number) =>
  6936. request<SpoolFilamentPreset[]>(`/inventory/spools/${spoolId}/filament-presets`),
  6937. saveSpoolFilamentPresets: (spoolId: number, presets: SpoolFilamentPresetInput[]) =>
  6938. request<SpoolFilamentPreset[]>(`/inventory/spools/${spoolId}/filament-presets`, {
  6939. method: 'PUT',
  6940. body: JSON.stringify(presets),
  6941. }),
  6942. getProfileDefaults: () => request<ProfileDefault[]>('/inventory/profile-defaults'),
  6943. resolveProfileDefault: (key: ProfileDefaultKey) => {
  6944. const params = new URLSearchParams({
  6945. brand: key.brand,
  6946. material: key.material,
  6947. subtype: key.subtype,
  6948. color_name: key.color_name,
  6949. });
  6950. return request<ResolvedProfileDefault | null>(`/inventory/profile-defaults/resolve?${params}`);
  6951. },
  6952. saveProfileDefault: (data: ProfileDefaultInput) =>
  6953. request<ProfileDefault>('/inventory/profile-defaults', {
  6954. method: 'PUT',
  6955. body: JSON.stringify(data),
  6956. }),
  6957. deleteProfileDefault: (defaultId: number) =>
  6958. request<{ status: string }>(`/inventory/profile-defaults/${defaultId}`, { method: 'DELETE' }),
  6959. /** Fills in what active spools of the default's product lack; the inventory mode picks the route. */
  6960. applyProfileDefault: (defaultId: number, spoolmanMode: boolean) =>
  6961. request<{ updated: number }>(
  6962. spoolmanMode
  6963. ? `/spoolman/inventory/profile-defaults/${defaultId}/apply`
  6964. : `/inventory/profile-defaults/${defaultId}/apply`,
  6965. { method: 'POST' },
  6966. ),
  6967. getAssignments: (printerId?: number) =>
  6968. request<SpoolAssignment[]>(`/inventory/assignments${printerId ? `?printer_id=${printerId}` : ''}`),
  6969. // move: the spool also leaves any other slot it is in, in the same
  6970. // transaction (#1574) -- for a scanned spool, the one in the user's hand.
  6971. assignSpool: (data: { spool_id: number; printer_id: number; ams_id: number; tray_id: number; move?: boolean }) =>
  6972. request<SpoolAssignment>('/inventory/assignments', {
  6973. method: 'POST',
  6974. body: JSON.stringify(data),
  6975. }),
  6976. unassignSpool: (printerId: number, amsId: number, trayId: number) =>
  6977. request<{ status: string }>(`/inventory/assignments/${printerId}/${amsId}/${trayId}`, { method: 'DELETE' }),
  6978. // ── Spool label printing (#809) ──────────────────────────────────────────
  6979. // The print endpoints return a PDF, a PNG, or a ZIP of PNGs (#2981); the
  6980. // preview endpoints one PNG. Callers get the Blob and decide what to do.
  6981. printSpoolLabels: (data: PrintSpoolLabelsRequest): Promise<Blob> =>
  6982. postForBlob('/inventory/labels', data),
  6983. printSpoolmanSpoolLabels: (data: PrintSpoolLabelsRequest): Promise<Blob> =>
  6984. postForBlob('/spoolman/labels', data),
  6985. previewSpoolLabel: (data: PreviewSpoolLabelRequest, signal?: AbortSignal): Promise<Blob> =>
  6986. postForBlob('/inventory/labels/preview', data, signal),
  6987. previewSpoolmanSpoolLabel: (data: PreviewSpoolLabelRequest, signal?: AbortSignal): Promise<Blob> =>
  6988. postForBlob('/spoolman/labels/preview', data, signal),
  6989. getLabelTemplates: () => request<SavedLabelTemplate[]>('/label-templates'),
  6990. createLabelTemplate: (data: { name: string; layout: LabelSheetLayout }) =>
  6991. request<SavedLabelTemplate>('/label-templates', { method: 'POST', body: JSON.stringify(data) }),
  6992. updateLabelTemplate: (id: number, data: { name: string; layout: LabelSheetLayout }) =>
  6993. request<SavedLabelTemplate>(`/label-templates/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  6994. deleteLabelTemplate: (id: number) => request<void>(`/label-templates/${id}`, { method: 'DELETE' }),
  6995. getSpoolCatalog: () =>
  6996. request<SpoolCatalogEntry[]>('/inventory/catalog'),
  6997. addCatalogEntry: (data: { name: string; weight: number }) =>
  6998. request<SpoolCatalogEntry>('/inventory/catalog', { method: 'POST', body: JSON.stringify(data) }),
  6999. updateCatalogEntry: (id: number, data: { name: string; weight: number }) =>
  7000. request<SpoolCatalogEntry>(`/inventory/catalog/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  7001. deleteCatalogEntry: (id: number) =>
  7002. request<{ status: string }>(`/inventory/catalog/${id}`, { method: 'DELETE' }),
  7003. bulkDeleteCatalogEntries: (ids: number[]) =>
  7004. request<{ deleted: number }>('/inventory/catalog/bulk-delete', { method: 'POST', body: JSON.stringify({ ids }) }),
  7005. resetSpoolCatalog: () =>
  7006. request<{ status: string }>('/inventory/catalog/reset', { method: 'POST' }),
  7007. // ── Suppliers (#2988) — inventory master data, Locations pattern ─────────
  7008. getSuppliers: () =>
  7009. request<Supplier[]>('/inventory/suppliers'),
  7010. createSupplier: (data: SupplierInput) =>
  7011. request<Supplier>('/inventory/suppliers', { method: 'POST', body: JSON.stringify(data) }),
  7012. updateSupplier: (id: number, data: Partial<SupplierInput>) =>
  7013. request<Supplier>(`/inventory/suppliers/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  7014. deleteSupplier: (id: number) =>
  7015. request<{ status: string }>(`/inventory/suppliers/${id}`, { method: 'DELETE' }),
  7016. setSpoolSuppliers: (spoolId: number, links: SpoolSupplierLinkInput[]) =>
  7017. request<SpoolSupplierLink[]>(`/inventory/spools/${spoolId}/suppliers`, {
  7018. method: 'PUT',
  7019. body: JSON.stringify(links),
  7020. }),
  7021. // Spoolman parity: the assignment rows live Bambuddy-side, keyed by the
  7022. // remote spool id — same request/response shape as the built-in inventory.
  7023. setSpoolmanSpoolSuppliers: (spoolmanSpoolId: number, links: SpoolSupplierLinkInput[]) =>
  7024. request<SpoolSupplierLink[]>(`/spoolman/inventory/spools/${spoolmanSpoolId}/suppliers`, {
  7025. method: 'PUT',
  7026. body: JSON.stringify(links),
  7027. }),
  7028. // date_from/date_to scope the usage half only, so the widget can follow the
  7029. // dashboard timeframe; stock stays point-in-time.
  7030. getSupplierStats: (dateFrom?: string, dateTo?: string) => {
  7031. const params = new URLSearchParams();
  7032. if (dateFrom) params.set('date_from', dateFrom);
  7033. if (dateTo) params.set('date_to', dateTo);
  7034. addDayZone(params);
  7035. const qs = params.toString();
  7036. return request<SupplierStats[]>(`/inventory/stats/suppliers${qs ? `?${qs}` : ''}`);
  7037. },
  7038. getLocations: () =>
  7039. request<StorageLocation[]>('/inventory/locations'),
  7040. createLocation: (data: { name: string; identifier?: string | null }) =>
  7041. request<StorageLocation>('/inventory/locations', { method: 'POST', body: JSON.stringify(data) }),
  7042. updateLocation: (id: number, data: { name?: string; identifier?: string | null }) =>
  7043. request<StorageLocation>(`/inventory/locations/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  7044. deleteLocation: (id: number) =>
  7045. request<{ status: string }>(`/inventory/locations/${id}`, { method: 'DELETE' }),
  7046. getColorCatalog: () =>
  7047. request<ColorCatalogEntry[]>('/inventory/colors'),
  7048. /** Flat hex→name map, plus the names collapsing it loses. ``by_material`` is
  7049. * keyed ``"<material>|<hex>"`` and only carries entries that differ from the
  7050. * flat answer (e.g. ``"pla matte|ffffff" -> "Ivory White"`` where the flat
  7051. * map says "Jade White"). #2875. */
  7052. getColorNameMap: () =>
  7053. request<{
  7054. colors: Record<string, string>;
  7055. by_material?: Record<string, string>;
  7056. bambu?: BambuCatalogColor[];
  7057. preset_materials?: Record<string, string>;
  7058. }>('/inventory/colors/map'),
  7059. addColorEntry: (data: {
  7060. manufacturer: string;
  7061. color_name: string;
  7062. hex_color: string;
  7063. material: string | null;
  7064. extra_colors?: string | null;
  7065. effect_type?: string | null;
  7066. }) =>
  7067. request<ColorCatalogEntry>('/inventory/colors', { method: 'POST', body: JSON.stringify(data) }),
  7068. updateColorEntry: (
  7069. id: number,
  7070. data: {
  7071. manufacturer: string;
  7072. color_name: string;
  7073. hex_color: string;
  7074. material: string | null;
  7075. extra_colors?: string | null;
  7076. effect_type?: string | null;
  7077. },
  7078. ) => request<ColorCatalogEntry>(`/inventory/colors/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  7079. deleteColorEntry: (id: number) =>
  7080. request<{ status: string }>(`/inventory/colors/${id}`, { method: 'DELETE' }),
  7081. bulkDeleteColorEntries: (ids: number[]) =>
  7082. request<{ deleted: number }>('/inventory/colors/bulk-delete', { method: 'POST', body: JSON.stringify({ ids }) }),
  7083. resetColorCatalog: () =>
  7084. request<{ status: string }>('/inventory/colors/reset', { method: 'POST' }),
  7085. searchColors: (manufacturer?: string, material?: string) =>
  7086. request<ColorCatalogEntry[]>(`/inventory/colors/search?${manufacturer ? `manufacturer=${encodeURIComponent(manufacturer)}` : ''}${manufacturer && material ? '&' : ''}${material ? `material=${encodeURIComponent(material)}` : ''}`),
  7087. linkTagToSpool: (spoolId: number, data: { tag_uid?: string; tray_uuid?: string; tag_type?: string; data_origin?: string }) =>
  7088. request<InventorySpool>(`/inventory/spools/${spoolId}/link-tag`, {
  7089. method: 'PATCH',
  7090. body: JSON.stringify(data),
  7091. }),
  7092. // Per-material-number inventory aggregate (#2870). The date range narrows
  7093. // the usage half only — stock is point-in-time.
  7094. getMaterialNumberStats: (options?: { dateFrom?: string; dateTo?: string }) => {
  7095. const params = new URLSearchParams();
  7096. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  7097. if (options?.dateTo) params.set('date_to', options.dateTo);
  7098. addDayZone(params);
  7099. const qs = params.toString();
  7100. return request<MaterialNumberStats[]>(`/inventory/stats/material-numbers${qs ? `?${qs}` : ''}`);
  7101. },
  7102. getSpoolUsageHistory: (spoolId: number, limit = 50) =>
  7103. request<SpoolUsageRecord[]>(`/inventory/spools/${spoolId}/usage?limit=${limit}`),
  7104. // One inventory's at a time: ``spoolman`` for the Spoolman spools' (#3407).
  7105. getAllUsageHistory: (limit = 100, printerId?: number, spoolman = false) =>
  7106. request<SpoolUsageRecord[]>(
  7107. `/inventory/usage?limit=${limit}${printerId ? `&printer_id=${printerId}` : ''}${spoolman ? '&spoolman=true' : ''}`,
  7108. ),
  7109. getSpoolmanSpoolUsageHistory: (spoolId: number, limit = 50) =>
  7110. request<SpoolUsageRecord[]>(`/spoolman/inventory/spools/${spoolId}/usage?limit=${limit}`),
  7111. clearSpoolmanSpoolUsageHistory: (spoolId: number) =>
  7112. request<{ status: string }>(`/spoolman/inventory/spools/${spoolId}/usage`, { method: 'DELETE' }),
  7113. clearSpoolUsageHistory: (spoolId: number) =>
  7114. request<{ status: string }>(`/inventory/spools/${spoolId}/usage`, { method: 'DELETE' }),
  7115. syncWeightsFromAms: () =>
  7116. request<{ synced: number; skipped: number; printing?: number }>('/inventory/sync-ams-weights', { method: 'POST' }),
  7117. getSkuSettings: () =>
  7118. request<FilamentSkuSettings[]>('/inventory/sku-settings'),
  7119. upsertSkuSettings: (data: Omit<FilamentSkuSettings, 'id'>) =>
  7120. request<FilamentSkuSettings>('/inventory/sku-settings', {
  7121. method: 'POST',
  7122. body: JSON.stringify(data),
  7123. }),
  7124. getShoppingList: () =>
  7125. request<ShoppingListItem[]>('/inventory/shopping-list'),
  7126. addToShoppingList: (data: ShoppingListItemCreate) =>
  7127. request<ShoppingListItem>('/inventory/shopping-list', {
  7128. method: 'POST',
  7129. body: JSON.stringify(data),
  7130. }),
  7131. removeFromShoppingList: (id: number) =>
  7132. request<{ status: string }>(`/inventory/shopping-list/${id}`, { method: 'DELETE' }),
  7133. clearShoppingList: () =>
  7134. request<{ deleted: number }>('/inventory/shopping-list', { method: 'DELETE' }),
  7135. updateShoppingListStatus: (id: number, status: 'pending' | 'purchased' | 'received') =>
  7136. request<ShoppingListItem>(`/inventory/shopping-list/${id}/status`, {
  7137. method: 'PATCH',
  7138. body: JSON.stringify({ status }),
  7139. }),
  7140. getFilamentPresets: () =>
  7141. request<SlicerSetting[]>('/cloud/filaments'),
  7142. // Spoolman Inventory proxy (unified UI when Spoolman is enabled)
  7143. getSpoolmanInventorySpools: (includeArchived = false) =>
  7144. request<InventorySpool[]>(`/spoolman/inventory/spools?include_archived=${includeArchived}`),
  7145. getSpoolmanInventorySpool: (id: number) =>
  7146. request<InventorySpool>(`/spoolman/inventory/spools/${id}`),
  7147. createSpoolmanInventorySpool: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>) =>
  7148. request<InventorySpool>('/spoolman/inventory/spools', {
  7149. method: 'POST',
  7150. body: JSON.stringify(data),
  7151. }),
  7152. bulkCreateSpoolmanInventorySpools: (
  7153. data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>,
  7154. quantity: number,
  7155. ) =>
  7156. request<SpoolmanBulkCreateResult | InventorySpool[]>('/spoolman/inventory/spools/bulk', {
  7157. method: 'POST',
  7158. body: JSON.stringify({ spool: data, quantity }),
  7159. }),
  7160. updateSpoolmanInventorySpool: (
  7161. id: number,
  7162. data: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>,
  7163. ) =>
  7164. request<InventorySpool>(`/spoolman/inventory/spools/${id}`, {
  7165. method: 'PATCH',
  7166. body: JSON.stringify(data),
  7167. }),
  7168. deleteSpoolmanInventorySpool: (id: number) =>
  7169. request<{ status: string }>(`/spoolman/inventory/spools/${id}`, { method: 'DELETE' }),
  7170. archiveSpoolmanInventorySpool: (id: number) =>
  7171. request<InventorySpool>(`/spoolman/inventory/spools/${id}/archive`, { method: 'POST' }),
  7172. restoreSpoolmanInventorySpool: (id: number) =>
  7173. request<InventorySpool>(`/spoolman/inventory/spools/${id}/restore`, { method: 'POST' }),
  7174. resetSpoolmanInventorySpoolConsumedCounter: (id: number) =>
  7175. request<InventorySpool>(`/spoolman/inventory/spools/${id}/reset-consumed-counter`, { method: 'POST' }),
  7176. bulkResetSpoolmanInventorySpoolConsumedCounter: (spoolIds: number[]) =>
  7177. request<{ reset: number; not_found?: number[]; errors?: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/reset-consumed-counter-bulk`, {
  7178. method: 'POST',
  7179. body: JSON.stringify({ spool_ids: spoolIds }),
  7180. }),
  7181. bulkUpdateSpoolmanInventorySpools: (ids: number[], update: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  7182. request<{ updated: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-update`, {
  7183. method: 'POST',
  7184. body: JSON.stringify({ ids, update }),
  7185. }),
  7186. bulkDeleteSpoolmanInventorySpools: (ids: number[]) =>
  7187. request<{ deleted: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-delete`, {
  7188. method: 'POST',
  7189. body: JSON.stringify({ ids }),
  7190. }),
  7191. bulkArchiveSpoolmanInventorySpools: (ids: number[]) =>
  7192. request<{ archived: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-archive`, {
  7193. method: 'POST',
  7194. body: JSON.stringify({ ids }),
  7195. }),
  7196. bulkRestoreSpoolmanInventorySpools: (ids: number[]) =>
  7197. request<{ restored: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-restore`, {
  7198. method: 'POST',
  7199. body: JSON.stringify({ ids }),
  7200. }),
  7201. linkTagToSpoolmanSpool: (spoolId: number, data: { tag_uid?: string; tray_uuid?: string }) =>
  7202. request<InventorySpool>(`/spoolman/inventory/spools/${spoolId}/tag`, {
  7203. method: 'PATCH',
  7204. body: JSON.stringify(data),
  7205. }),
  7206. syncSpoolmanSpoolWeight: (spoolId: number, weightGrams: number) =>
  7207. request<{ status: string; weight_used: number }>(`/spoolman/inventory/spools/${spoolId}/weight`, {
  7208. method: 'PATCH',
  7209. body: JSON.stringify({ weight_grams: weightGrams }),
  7210. }),
  7211. // move: as assignSpool's (#1574).
  7212. assignSpoolmanSlot: (data: { spoolman_spool_id: number; printer_id: number; ams_id: number; tray_id: number; move?: boolean }) =>
  7213. request<InventorySpool>('/spoolman/inventory/slot-assignments', {
  7214. method: 'POST',
  7215. body: JSON.stringify(data),
  7216. }),
  7217. unassignSpoolmanSlot: (spoolmanSpoolId: number) =>
  7218. request<InventorySpool>(`/spoolman/inventory/slot-assignments/${spoolmanSpoolId}`, { method: 'DELETE' }),
  7219. getSpoolmanSlotAssignments: (printerId?: number) =>
  7220. request<Array<{
  7221. printer_id: number;
  7222. printer_name: string | null;
  7223. ams_id: number;
  7224. tray_id: number;
  7225. spoolman_spool_id: number;
  7226. ams_label: string | null;
  7227. printer_model?: string | null;
  7228. }>>(
  7229. printerId !== undefined
  7230. ? `/spoolman/inventory/slot-assignments/all?printer_id=${printerId}`
  7231. : '/spoolman/inventory/slot-assignments/all',
  7232. ),
  7233. syncSpoolmanAmsWeights: () =>
  7234. request<{ synced: number; skipped: number; printing?: number }>('/spoolman/inventory/sync-ams-weights', { method: 'POST' }),
  7235. saveSpoolmanKProfiles: (spoolId: number, profiles: SpoolKProfileInput[]) =>
  7236. request<SpoolKProfile[]>(`/spoolman/inventory/spools/${spoolId}/k-profiles`, {
  7237. method: 'PUT',
  7238. body: JSON.stringify(profiles),
  7239. }),
  7240. getSpoolmanFilamentPresets: (spoolId: number) =>
  7241. request<SpoolFilamentPreset[]>(`/spoolman/inventory/spools/${spoolId}/filament-presets`),
  7242. saveSpoolmanFilamentPresets: (spoolId: number, presets: SpoolFilamentPresetInput[]) =>
  7243. request<SpoolFilamentPreset[]>(`/spoolman/inventory/spools/${spoolId}/filament-presets`, {
  7244. method: 'PUT',
  7245. body: JSON.stringify(presets),
  7246. }),
  7247. // Updates
  7248. getVersion: () => request<VersionInfo>('/updates/version'),
  7249. checkForUpdates: () => request<UpdateCheckResult>('/updates/check'),
  7250. applyUpdate: () =>
  7251. request<{ success: boolean; message: string; status?: UpdateStatus; is_docker?: boolean; is_ha_addon?: boolean; is_windows_installer?: boolean }>('/updates/apply', {
  7252. method: 'POST',
  7253. }),
  7254. getUpdateStatus: () => request<UpdateStatus>('/updates/status'),
  7255. // Maintenance
  7256. getMaintenanceTypes: () => request<MaintenanceType[]>('/maintenance/types'),
  7257. createMaintenanceType: (data: MaintenanceTypeCreate) =>
  7258. request<MaintenanceType>('/maintenance/types', {
  7259. method: 'POST',
  7260. body: JSON.stringify(data),
  7261. }),
  7262. updateMaintenanceType: (id: number, data: Partial<MaintenanceTypeCreate>) =>
  7263. request<MaintenanceType>(`/maintenance/types/${id}`, {
  7264. method: 'PATCH',
  7265. body: JSON.stringify(data),
  7266. }),
  7267. deleteMaintenanceType: (id: number) =>
  7268. request<{ status: string }>(`/maintenance/types/${id}`, { method: 'DELETE' }),
  7269. restoreDefaultMaintenanceTypes: () =>
  7270. request<{ restored: number }>(`/maintenance/types/restore-defaults`, { method: 'POST' }),
  7271. getMaintenanceOverview: () => request<PrinterMaintenanceOverview[]>('/maintenance/overview'),
  7272. updateMaintenanceItem: (itemId: number, data: { custom_interval_hours?: number | null; custom_interval_type?: 'hours' | 'days' | null; enabled?: boolean }) =>
  7273. request<MaintenanceStatus>(`/maintenance/items/${itemId}`, {
  7274. method: 'PATCH',
  7275. body: JSON.stringify(data),
  7276. }),
  7277. performMaintenance: (itemId: number, notes?: string) =>
  7278. request<MaintenanceStatus>(`/maintenance/items/${itemId}/perform`, {
  7279. method: 'POST',
  7280. body: JSON.stringify({ notes }),
  7281. }),
  7282. getMaintenanceLog: (printerId: number, options?: { limit?: number; offset?: number }) => {
  7283. const params = new URLSearchParams();
  7284. if (options?.limit !== undefined) params.set('limit', String(options.limit));
  7285. if (options?.offset !== undefined) params.set('offset', String(options.offset));
  7286. const query = params.toString();
  7287. return request<MaintenanceLogPage>(`/maintenance/printers/${printerId}/log${query ? `?${query}` : ''}`);
  7288. },
  7289. // One printer's log, or with no printer the whole fleet's (deleted printers included).
  7290. downloadMaintenanceLog: async (printerId?: number): Promise<void> => {
  7291. const headers: Record<string, string> = {};
  7292. if (authToken) {
  7293. headers['Authorization'] = `Bearer ${authToken}`;
  7294. }
  7295. const path = printerId === undefined ? '/maintenance/log/export' : `/maintenance/printers/${printerId}/log/export`;
  7296. const response = await fetch(`${API_BASE}${path}`, { headers });
  7297. if (!response.ok) {
  7298. const error = await response.json().catch(() => ({}));
  7299. throw new Error(error.detail || `HTTP ${response.status}`);
  7300. }
  7301. const disposition = response.headers.get('Content-Disposition');
  7302. const filename = parseContentDispositionFilename(disposition) || 'maintenance_log.csv';
  7303. const blob = await response.blob();
  7304. const url = window.URL.createObjectURL(blob);
  7305. const a = document.createElement('a');
  7306. a.href = url;
  7307. a.download = filename;
  7308. document.body.appendChild(a);
  7309. a.click();
  7310. document.body.removeChild(a);
  7311. window.URL.revokeObjectURL(url);
  7312. },
  7313. // Deletes the entries older than the given days: one printer's, or with no
  7314. // printer the whole fleet's (deleted printers included for an unscoped caller).
  7315. cleanUpMaintenanceLog: (olderThanDays: number, printerId?: number) => {
  7316. const path = printerId === undefined ? '/maintenance/log' : `/maintenance/printers/${printerId}/log`;
  7317. return request<{ deleted: number }>(`${path}?older_than_days=${olderThanDays}`, { method: 'DELETE' });
  7318. },
  7319. deleteMaintenanceLogEntry: (entryId: number) =>
  7320. request<{ status: string; id: number }>(`/maintenance/log/${entryId}`, { method: 'DELETE' }),
  7321. setPrinterHours: (printerId: number, totalHours: number) =>
  7322. request<{ printer_id: number; total_hours: number; archive_hours: number; offset_hours: number }>(
  7323. `/maintenance/printers/${printerId}/hours?total_hours=${totalHours}`,
  7324. { method: 'PATCH' }
  7325. ),
  7326. assignMaintenanceType: (printerId: number, typeId: number) =>
  7327. request<MaintenanceStatus>(`/maintenance/printers/${printerId}/assign/${typeId}`, {
  7328. method: 'POST',
  7329. }),
  7330. removeMaintenanceItem: (itemId: number) =>
  7331. request<{ status: string }>(`/maintenance/items/${itemId}`, {
  7332. method: 'DELETE',
  7333. }),
  7334. // Camera
  7335. getCameraStreamToken: () =>
  7336. request<{ token: string }>('/printers/camera/stream-token', { method: 'POST' }),
  7337. // Media token (#3025) — the credential for thumbnails, plate previews,
  7338. // timelapses, cover images and link icons. Minted behind plain auth rather
  7339. // than camera:view, and identified, so those routes gate on the resource's
  7340. // own permission and ownership instead of on the camera.
  7341. getMediaToken: () => request<{ token: string }>('/auth/media-token', { method: 'POST' }),
  7342. // WebSocket auth (GHSA-r2qv follow-up) — mint a short-lived token for
  7343. // the /ws connection. Browsers can't attach Authorization headers to a
  7344. // WebSocket handshake, so the token rides in the ?token= query param.
  7345. getWebSocketToken: () =>
  7346. request<{ token: string }>('/auth/ws-token', { method: 'POST' }),
  7347. // Connected apps: sign-in to external applications with Bambuddy
  7348. listConnectedApps: () => request<ConnectedApp[]>('/connect/apps'),
  7349. createConnectedApp: (payload: { name: string; redirect_uri: string }) =>
  7350. request<ConnectedApp>('/connect/apps', { method: 'POST', body: JSON.stringify(payload) }),
  7351. updateConnectedApp: (id: number, payload: { name?: string; redirect_uri?: string; enabled?: boolean }) =>
  7352. request<ConnectedApp>(`/connect/apps/${id}`, { method: 'PATCH', body: JSON.stringify(payload) }),
  7353. rotateConnectedAppSecret: (id: number) =>
  7354. request<ConnectedApp>(`/connect/apps/${id}/rotate-secret`, { method: 'POST' }),
  7355. deleteConnectedApp: (id: number) => request<void>(`/connect/apps/${id}`, { method: 'DELETE' }),
  7356. getConnectAuthorizeInfo: (clientId: string, redirectUri: string) =>
  7357. request<ConnectAuthorizeInfo>(
  7358. `/connect/authorize/info?client_id=${encodeURIComponent(clientId)}&redirect_uri=${encodeURIComponent(redirectUri)}`,
  7359. ),
  7360. connectAuthorize: (payload: {
  7361. client_id: string;
  7362. redirect_uri: string;
  7363. code_challenge: string;
  7364. code_challenge_method: 'S256';
  7365. }) =>
  7366. request<{ code: string; redirect_uri: string }>('/connect/authorize', {
  7367. method: 'POST',
  7368. body: JSON.stringify(payload),
  7369. }),
  7370. // Long-lived camera tokens (#1108, #2531)
  7371. createLongLivedCameraToken: (payload: {
  7372. name: string;
  7373. expires_in_days: number;
  7374. scope?: LongLivedTokenScope;
  7375. }) =>
  7376. request<LongLivedCameraToken>('/auth/tokens', {
  7377. method: 'POST',
  7378. body: JSON.stringify({ scope: 'camera_stream', ...payload }),
  7379. }),
  7380. listMyLongLivedCameraTokens: () =>
  7381. request<LongLivedCameraToken[]>('/auth/tokens'),
  7382. listAllLongLivedCameraTokens: () =>
  7383. request<LongLivedCameraToken[]>('/auth/tokens/all'),
  7384. revokeLongLivedCameraToken: (tokenId: number) =>
  7385. request<void>(`/auth/tokens/${tokenId}`, { method: 'DELETE' }),
  7386. // Token-authenticated Cam Wall feed (#2531). `token` is omitted only when
  7387. // auth is disabled, where the backend gate is a no-op anyway.
  7388. getCamWallPrinters: (token?: string) =>
  7389. request<CamWallPrinter[]>(
  7390. token ? `/camwall/printers?token=${encodeURIComponent(token)}` : '/camwall/printers',
  7391. ),
  7392. // Token-authenticated streaming-overlay feed (#2613). OBS (or any embed with
  7393. // no login session) loads /overlay/{id}?token=... and this backs it. `token`
  7394. // is omitted only when auth is disabled, where the backend gate is a no-op.
  7395. getOverlayStatus: (printerId: number, token?: string) =>
  7396. request<OverlayStatus>(
  7397. token
  7398. ? `/printers/${printerId}/overlay-status?token=${encodeURIComponent(token)}`
  7399. : `/printers/${printerId}/overlay-status`,
  7400. ),
  7401. getCameraStatus: (printerId: number) =>
  7402. request<{ active: boolean; stalled: boolean }>(`/printers/${printerId}/camera/status`),
  7403. diagnoseCamera: (printerId: number) =>
  7404. request<CameraDiagnoseResult>(`/printers/${printerId}/camera/diagnose`, { method: 'POST' }),
  7405. diagnosePrinter: (printerId: number) =>
  7406. request<PrinterDiagnosticResult>(`/printers/${printerId}/diagnostic`),
  7407. diagnoseConnection: (body: {
  7408. ip_address: string;
  7409. serial_number?: string;
  7410. access_code?: string;
  7411. }) =>
  7412. request<PrinterDiagnosticResult>('/printers/diagnostic', {
  7413. method: 'POST',
  7414. body: JSON.stringify(body),
  7415. }),
  7416. // Plate Detection - Multi-reference calibration (stores up to 5 references per printer)
  7417. checkPlateEmpty: (printerId: number, options?: { useExternal?: boolean; includeDebugImage?: boolean }) => {
  7418. const params = new URLSearchParams();
  7419. // Only forward use_external when the caller explicitly sets it. Omitted →
  7420. // backend derives the default from the printer's external_camera_enabled
  7421. // setting so calibration and runtime checks use the same camera (#1359).
  7422. if (options?.useExternal !== undefined) {
  7423. params.set('use_external', String(options.useExternal));
  7424. }
  7425. params.set('include_debug_image', String(options?.includeDebugImage ?? false));
  7426. return request<PlateDetectionResult>(
  7427. `/printers/${printerId}/camera/check-plate?${params.toString()}`
  7428. );
  7429. },
  7430. calibratePlateDetection: (printerId: number, options?: { label?: string; useExternal?: boolean }) => {
  7431. const params = new URLSearchParams();
  7432. if (options?.label) params.set('label', options.label);
  7433. if (options?.useExternal !== undefined) {
  7434. params.set('use_external', String(options.useExternal));
  7435. }
  7436. return request<CalibrationResult & { index: number }>(
  7437. `/printers/${printerId}/camera/plate-detection/calibrate?${params.toString()}`,
  7438. { method: 'POST' }
  7439. );
  7440. },
  7441. getPlateReferences: (printerId: number) => {
  7442. return request<{
  7443. references: PlateReference[];
  7444. max_references: number;
  7445. }>(`/printers/${printerId}/camera/plate-detection/references`);
  7446. },
  7447. getPlateReferenceThumbnailUrl: (printerId: number, index: number) =>
  7448. withStreamToken(`${API_BASE}/printers/${printerId}/camera/plate-detection/references/${index}/thumbnail`),
  7449. updatePlateReferenceLabel: (printerId: number, index: number, label: string) => {
  7450. const params = new URLSearchParams();
  7451. params.set('label', label);
  7452. return request<{ success: boolean; index: number; label: string }>(
  7453. `/printers/${printerId}/camera/plate-detection/references/${index}?${params.toString()}`,
  7454. { method: 'PUT' }
  7455. );
  7456. },
  7457. deletePlateReference: (printerId: number, index: number) => {
  7458. return request<{ success: boolean; message: string }>(
  7459. `/printers/${printerId}/camera/plate-detection/references/${index}`,
  7460. { method: 'DELETE' }
  7461. );
  7462. },
  7463. // External Links
  7464. getExternalLinks: () => request<ExternalLink[]>('/external-links/'),
  7465. getExternalLink: (id: number) => request<ExternalLink>(`/external-links/${id}`),
  7466. createExternalLink: (data: ExternalLinkCreate) =>
  7467. request<ExternalLink>('/external-links/', {
  7468. method: 'POST',
  7469. body: JSON.stringify(data),
  7470. }),
  7471. updateExternalLink: (id: number, data: ExternalLinkUpdate) =>
  7472. request<ExternalLink>(`/external-links/${id}`, {
  7473. method: 'PATCH',
  7474. body: JSON.stringify(data),
  7475. }),
  7476. deleteExternalLink: (id: number) =>
  7477. request<{ message: string }>(`/external-links/${id}`, { method: 'DELETE' }),
  7478. uploadExternalLinkIcon: async (id: number, file: File): Promise<ExternalLink> => {
  7479. const formData = new FormData();
  7480. formData.append('file', file);
  7481. const headers: Record<string, string> = {};
  7482. if (authToken) {
  7483. headers['Authorization'] = `Bearer ${authToken}`;
  7484. }
  7485. const response = await fetch(`${API_BASE}/external-links/${id}/icon`, {
  7486. method: 'POST',
  7487. headers,
  7488. body: formData,
  7489. });
  7490. if (!response.ok) {
  7491. const error = await response.json().catch(() => ({}));
  7492. throw new Error(error.detail || `HTTP ${response.status}`);
  7493. }
  7494. return response.json();
  7495. },
  7496. deleteExternalLinkIcon: (id: number) =>
  7497. request<ExternalLink>(`/external-links/${id}/icon`, { method: 'DELETE' }),
  7498. getExternalLinkIconUrl: (id: number) => withMediaToken(`${API_BASE}/external-links/${id}/icon`),
  7499. // Projects
  7500. getProjects: (status?: string) => {
  7501. const params = new URLSearchParams();
  7502. if (status) params.set('status', status);
  7503. return request<ProjectListItem[]>(`/projects/?${params}`);
  7504. },
  7505. getProject: (id: number) => request<Project>(`/projects/${id}`),
  7506. createProject: (data: ProjectCreate) =>
  7507. request<Project>('/projects/', {
  7508. method: 'POST',
  7509. body: JSON.stringify(data),
  7510. }),
  7511. updateProject: (id: number, data: ProjectUpdate) =>
  7512. request<Project>(`/projects/${id}`, {
  7513. method: 'PATCH',
  7514. body: JSON.stringify(data),
  7515. }),
  7516. deleteProject: (id: number) =>
  7517. request<{ message: string }>(`/projects/${id}`, { method: 'DELETE' }),
  7518. getProjectArchives: (id: number, limit = 100, offset = 0) =>
  7519. request<Archive[]>(`/projects/${id}/archives?limit=${limit}&offset=${offset}`),
  7520. // Completed-run counts per library file (#1897); files with 0 runs are omitted
  7521. getProjectFileProgress: (id: number) =>
  7522. request<ProjectFileProgress[]>(`/projects/${id}/file-progress`),
  7523. addArchivesToProject: (projectId: number, archiveIds: number[]) =>
  7524. request<{ message: string; count: number }>(`/projects/${projectId}/add-archives`, {
  7525. method: 'POST',
  7526. body: JSON.stringify({ archive_ids: archiveIds }),
  7527. }),
  7528. // #1155: Cover image
  7529. // Browsers can't attach `Authorization: Bearer ...` to `<img src>`, so we
  7530. // append the stream-token query string the same way archive thumbnails do.
  7531. // `version` cache-busts the browser copy after a re-upload. It has to go on
  7532. // before the token does: callers used to append their own `?v=` to the
  7533. // returned URL, which already ended in `?token=…`, so the second `?` landed
  7534. // inside the token value and the image 401'd whenever auth was enabled.
  7535. getProjectCoverImageUrl: (projectId: number, version?: string | number) =>
  7536. withMediaToken(
  7537. `${API_BASE}/projects/${projectId}/cover-image${
  7538. version === undefined ? '' : `?v=${encodeURIComponent(String(version))}`
  7539. }`
  7540. ),
  7541. uploadProjectCoverImage: async (
  7542. projectId: number,
  7543. file: File
  7544. ): Promise<{ status: string; filename: string; size: number }> => {
  7545. const formData = new FormData();
  7546. formData.append('file', file);
  7547. const headers: Record<string, string> = {};
  7548. if (authToken) {
  7549. headers['Authorization'] = `Bearer ${authToken}`;
  7550. }
  7551. const response = await fetch(`${API_BASE}/projects/${projectId}/cover-image`, {
  7552. method: 'POST',
  7553. headers,
  7554. body: formData,
  7555. });
  7556. if (!response.ok) {
  7557. const error = await response.json().catch(() => ({}));
  7558. throw new Error(error.detail || `HTTP ${response.status}`);
  7559. }
  7560. return response.json();
  7561. },
  7562. deleteProjectCoverImage: (projectId: number) =>
  7563. request<{ status: string }>(`/projects/${projectId}/cover-image`, { method: 'DELETE' }),
  7564. // BOM (Bill of Materials)
  7565. getProjectBOM: (projectId: number) =>
  7566. request<BOMItem[]>(`/projects/${projectId}/bom`),
  7567. createBOMItem: (projectId: number, data: BOMItemCreate) =>
  7568. request<BOMItem>(`/projects/${projectId}/bom`, {
  7569. method: 'POST',
  7570. body: JSON.stringify(data),
  7571. }),
  7572. updateBOMItem: (projectId: number, itemId: number, data: BOMItemUpdate) =>
  7573. request<BOMItem>(`/projects/${projectId}/bom/${itemId}`, {
  7574. method: 'PATCH',
  7575. body: JSON.stringify(data),
  7576. }),
  7577. deleteBOMItem: (projectId: number, itemId: number) =>
  7578. request<{ status: string; message: string }>(`/projects/${projectId}/bom/${itemId}`, {
  7579. method: 'DELETE',
  7580. }),
  7581. // Templates
  7582. getTemplates: () => request<ProjectListItem[]>('/projects/templates/'),
  7583. createTemplateFromProject: (projectId: number) =>
  7584. request<Project>(`/projects/${projectId}/create-template`, { method: 'POST' }),
  7585. createProjectFromTemplate: (templateId: number, name?: string) =>
  7586. request<Project>(`/projects/from-template/${templateId}${name ? `?name=${encodeURIComponent(name)}` : ''}`, {
  7587. method: 'POST',
  7588. }),
  7589. // Timeline
  7590. getProjectTimeline: (projectId: number, limit = 50) =>
  7591. request<TimelineEvent[]>(`/projects/${projectId}/timeline?limit=${limit}`),
  7592. // Project Export/Import
  7593. exportProjectJson: (projectId: number) =>
  7594. request<ProjectExport>(`/projects/${projectId}/export?format=json`),
  7595. importProject: (data: ProjectImport) =>
  7596. request<Project>('/projects/import', {
  7597. method: 'POST',
  7598. body: JSON.stringify(data),
  7599. }),
  7600. importProjectFile: async (file: File): Promise<Project> => {
  7601. const formData = new FormData();
  7602. formData.append('file', file);
  7603. const headers: Record<string, string> = {};
  7604. if (authToken) {
  7605. headers['Authorization'] = `Bearer ${authToken}`;
  7606. }
  7607. const response = await fetch(`${API_BASE}/projects/import/file`, {
  7608. method: 'POST',
  7609. headers,
  7610. body: formData,
  7611. });
  7612. if (!response.ok) {
  7613. const error = await response.json().catch(() => ({}));
  7614. throw new Error(error.detail || `HTTP ${response.status}`);
  7615. }
  7616. return response.json();
  7617. },
  7618. exportProjectZip: async (projectId: number): Promise<{ blob: Blob; filename: string }> => {
  7619. const headers: Record<string, string> = {};
  7620. if (authToken) {
  7621. headers['Authorization'] = `Bearer ${authToken}`;
  7622. }
  7623. const response = await fetch(`${API_BASE}/projects/${projectId}/export`, {
  7624. headers,
  7625. });
  7626. if (!response.ok) {
  7627. const error = await response.json().catch(() => ({}));
  7628. throw new Error(error.detail || `HTTP ${response.status}`);
  7629. }
  7630. const contentDisposition = response.headers.get('Content-Disposition');
  7631. const filename = parseContentDispositionFilename(contentDisposition) || `project_${projectId}.zip`;
  7632. const blob = await response.blob();
  7633. return { blob, filename };
  7634. },
  7635. // API Keys
  7636. getAPIKeys: () => request<APIKey[]>('/api-keys/'),
  7637. createAPIKey: (data: APIKeyCreate) =>
  7638. request<APIKeyCreateResponse>('/api-keys/', {
  7639. method: 'POST',
  7640. body: JSON.stringify(data),
  7641. }),
  7642. deleteAPIKey: (id: number) =>
  7643. request<{ message: string }>(`/api-keys/${id}`, { method: 'DELETE' }),
  7644. // AMS History
  7645. getAMSHistory: (printerId: number, amsId: number, hours = 24) =>
  7646. request<AMSHistoryResponse>(`/ams-history/${printerId}/${amsId}?hours=${hours}`),
  7647. // Printer heater (nozzle / bed / chamber) sensor history
  7648. getPrinterSensorHistory: (printerId: number, hours = 24, kinds?: string[]) => {
  7649. const params = new URLSearchParams({ hours: String(hours) });
  7650. if (kinds && kinds.length > 0) params.set('kinds', kinds.join(','));
  7651. return request<PrinterSensorHistoryResponse>(`/printer-sensor-history/${printerId}?${params.toString()}`);
  7652. },
  7653. // System Info
  7654. getSystemInfo: () => request<SystemInfo>('/system/info'),
  7655. getSystemHealth: () => request<SystemHealthResult>('/system/health'),
  7656. getStorageUsage: (options?: { refresh?: boolean }) => {
  7657. const params = new URLSearchParams();
  7658. if (options?.refresh) {
  7659. params.set('refresh', 'true');
  7660. }
  7661. const query = params.toString();
  7662. return request<StorageUsageResponse>(`/system/storage-usage${query ? `?${query}` : ''}`);
  7663. },
  7664. // Library (File Manager)
  7665. getLibraryFolders: () => request<LibraryFolderTree[]>('/library/folders'),
  7666. createLibraryFolder: (data: LibraryFolderCreate) =>
  7667. request<LibraryFolder>('/library/folders', {
  7668. method: 'POST',
  7669. body: JSON.stringify(data),
  7670. }),
  7671. updateLibraryFolder: (id: number, data: LibraryFolderUpdate) =>
  7672. request<LibraryFolder>(`/library/folders/${id}`, {
  7673. method: 'PUT',
  7674. body: JSON.stringify(data),
  7675. }),
  7676. deleteLibraryFolder: (id: number) =>
  7677. request<{ status: string; message: string }>(`/library/folders/${id}`, { method: 'DELETE' }),
  7678. createExternalFolder: (data: ExternalFolderCreate) =>
  7679. request<LibraryFolder>('/library/folders/external', {
  7680. method: 'POST',
  7681. body: JSON.stringify(data),
  7682. }),
  7683. scanExternalFolder: (folderId: number) =>
  7684. request<{ status: string; added: number; removed: number }>(`/library/folders/${folderId}/scan`, {
  7685. method: 'POST',
  7686. }),
  7687. getLibraryFoldersByProject: (projectId: number) =>
  7688. request<LibraryFolder[]>(`/library/folders/by-project/${projectId}`),
  7689. getLibraryFoldersByArchive: (archiveId: number) => foldersByArchiveBatch(archiveId),
  7690. getLibraryFiles: (
  7691. folderId?: number | null,
  7692. includeRoot = true,
  7693. projectId?: number,
  7694. scope?: 'internal' | 'external',
  7695. recursive = false,
  7696. tagIds: number[] = [],
  7697. ) => {
  7698. const params = new URLSearchParams();
  7699. if (folderId !== undefined && folderId !== null) {
  7700. params.set('folder_id', String(folderId));
  7701. }
  7702. if (projectId !== undefined) {
  7703. params.set('project_id', String(projectId));
  7704. }
  7705. params.set('include_root', String(includeRoot));
  7706. if (scope === 'internal') params.set('internal_only', 'true');
  7707. else if (scope === 'external') params.set('external_only', 'true');
  7708. // recursive=true expands the folder_id filter to include every descendant
  7709. // folder (#1268). Only meaningful when folder_id is set; ignored server-side
  7710. // otherwise. Off by default so non-search callers keep folder-scoped behavior.
  7711. if (recursive) params.set('recursive', 'true');
  7712. // Tag filter (#1268). Repeated ?tag_ids=N&tag_ids=M form for AND semantics
  7713. // — backend joins the association table and HAVING COUNT(DISTINCT) matches
  7714. // the array length. Tag filter intentionally bypasses folder scoping
  7715. // server-side (cross-cutting design decision).
  7716. for (const tagId of tagIds) {
  7717. params.append('tag_ids', String(tagId));
  7718. }
  7719. return request<LibraryFileListItem[]>(`/library/files?${params}`);
  7720. },
  7721. getLibraryFolderReadme: (folderId: number) =>
  7722. request<{ filename: string; content: string; truncated: boolean }>(
  7723. `/library/folders/${folderId}/readme`,
  7724. ),
  7725. // ============ Library tag catalog (#1268) ============
  7726. getLibraryTags: () =>
  7727. request<LibraryTag[]>('/library/tags'),
  7728. createLibraryTag: (name: string) =>
  7729. request<LibraryTag>('/library/tags', {
  7730. method: 'POST',
  7731. body: JSON.stringify({ name }),
  7732. }),
  7733. updateLibraryTag: (id: number, name: string) =>
  7734. request<LibraryTag>(`/library/tags/${id}`, {
  7735. method: 'PATCH',
  7736. body: JSON.stringify({ name }),
  7737. }),
  7738. deleteLibraryTag: (id: number) =>
  7739. request<void>(`/library/tags/${id}`, { method: 'DELETE' }),
  7740. bulkAssignLibraryTags: (
  7741. fileIds: number[],
  7742. tagIds: number[],
  7743. action: 'add' | 'remove' | 'replace',
  7744. ) =>
  7745. request<LibraryTagBulkAssignResult>('/library/tags/bulk-assign', {
  7746. method: 'POST',
  7747. body: JSON.stringify({ file_ids: fileIds, tag_ids: tagIds, action }),
  7748. }),
  7749. // ============ Variant groups (#671 / #2570) ============
  7750. // "These files are the same job sliced for different printers." Consumed from
  7751. // both ends: the queue picks a printer and needs the matching file, the File
  7752. // Manager's print action has the printer and needs the same match.
  7753. createVariantGroup: (
  7754. members: { library_file_id: number; target_model?: string }[],
  7755. name?: string,
  7756. ) =>
  7757. request<VariantGroup>('/library/variant-groups', {
  7758. method: 'POST',
  7759. body: JSON.stringify({ members, ...(name ? { name } : {}) }),
  7760. }),
  7761. getVariantGroup: (groupId: number) =>
  7762. request<VariantGroup>(`/library/variant-groups/${groupId}`),
  7763. getLibraryFile: (id: number) => request<LibraryFile>(`/library/files/${id}`),
  7764. uploadLibraryFile: async (
  7765. file: File,
  7766. folderId?: number | null,
  7767. generateStlThumbnails: boolean = true
  7768. ): Promise<LibraryFileUploadResponse> => {
  7769. const formData = new FormData();
  7770. formData.append('file', file);
  7771. const params = new URLSearchParams();
  7772. if (folderId) params.set('folder_id', String(folderId));
  7773. params.set('generate_stl_thumbnails', String(generateStlThumbnails));
  7774. const headers: Record<string, string> = {};
  7775. if (authToken) {
  7776. headers['Authorization'] = `Bearer ${authToken}`;
  7777. }
  7778. const response = await fetch(`${API_BASE}/library/files?${params}`, {
  7779. method: 'POST',
  7780. headers,
  7781. body: formData,
  7782. });
  7783. if (!response.ok) {
  7784. const error = await response.json().catch(() => ({}));
  7785. throw new Error(error.detail || `HTTP ${response.status}`);
  7786. }
  7787. return response.json();
  7788. },
  7789. extractZipFile: async (
  7790. file: File,
  7791. folderId?: number | null,
  7792. preserveStructure: boolean = true,
  7793. createFolderFromZip: boolean = false,
  7794. generateStlThumbnails: boolean = true
  7795. ): Promise<ZipExtractResponse> => {
  7796. const formData = new FormData();
  7797. formData.append('file', file);
  7798. const params = new URLSearchParams();
  7799. if (folderId) params.set('folder_id', String(folderId));
  7800. params.set('preserve_structure', String(preserveStructure));
  7801. params.set('create_folder_from_zip', String(createFolderFromZip));
  7802. params.set('generate_stl_thumbnails', String(generateStlThumbnails));
  7803. const headers: Record<string, string> = {};
  7804. if (authToken) {
  7805. headers['Authorization'] = `Bearer ${authToken}`;
  7806. }
  7807. const response = await fetch(`${API_BASE}/library/files/extract-zip?${params}`, {
  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. updateLibraryFile: (id: number, data: LibraryFileUpdate) =>
  7819. request<LibraryFile>(`/library/files/${id}`, {
  7820. method: 'PUT',
  7821. body: JSON.stringify(data),
  7822. }),
  7823. deleteLibraryFile: (id: number) =>
  7824. request<{ status: string; message: string; trashed: boolean }>(`/library/files/${id}`, { method: 'DELETE' }),
  7825. // ========== Library Trash (#1008) ==========
  7826. previewLibraryPurge: (olderThanDays: number, includeNeverPrinted: boolean = true) =>
  7827. request<LibraryPurgePreview>(
  7828. `/library/purge/preview?older_than_days=${olderThanDays}&include_never_printed=${includeNeverPrinted}`,
  7829. ),
  7830. executeLibraryPurge: (olderThanDays: number, includeNeverPrinted: boolean = true) =>
  7831. request<{ moved_to_trash: number }>('/library/purge', {
  7832. method: 'POST',
  7833. body: JSON.stringify({ older_than_days: olderThanDays, include_never_printed: includeNeverPrinted }),
  7834. }),
  7835. listLibraryTrash: (limit: number = 100, offset: number = 0) =>
  7836. request<LibraryTrashListResponse>(`/library/trash?limit=${limit}&offset=${offset}`),
  7837. restoreLibraryTrash: (fileId: number) =>
  7838. request<{ status: string; id: number }>(`/library/trash/${fileId}/restore`, { method: 'POST' }),
  7839. hardDeleteLibraryTrash: (fileId: number) =>
  7840. request<{ status: string }>(`/library/trash/${fileId}`, { method: 'DELETE' }),
  7841. emptyLibraryTrash: () => request<{ deleted: number }>('/library/trash', { method: 'DELETE' }),
  7842. getLibraryTrashSettings: () =>
  7843. request<LibraryTrashSettings>('/library/trash/settings'),
  7844. updateLibraryTrashSettings: (body: LibraryTrashSettings) =>
  7845. request<LibraryTrashSettings>('/library/trash/settings', {
  7846. method: 'PUT',
  7847. body: JSON.stringify(body),
  7848. }),
  7849. getLibraryFileDownloadUrl: (id: number) => `${API_BASE}/library/files/${id}/download`,
  7850. createLibrarySlicerToken: (fileId: number) =>
  7851. request<{ token: string }>(`/library/files/${fileId}/slicer-token`, { method: 'POST' }),
  7852. getLibrarySlicerDownloadUrl: (fileId: number, token: string, filename: string) =>
  7853. `${API_BASE}/library/files/${fileId}/dl/${token}/${encodeURIComponent(buildSlicerUrlFilename(filename))}`,
  7854. downloadLibraryFile: async (id: number, filename?: string): Promise<void> => {
  7855. const headers: Record<string, string> = {};
  7856. if (authToken) {
  7857. headers['Authorization'] = `Bearer ${authToken}`;
  7858. }
  7859. const response = await fetch(`${API_BASE}/library/files/${id}/download`, { headers });
  7860. if (!response.ok) {
  7861. const error = await response.json().catch(() => ({}));
  7862. throw new Error(error.detail || `HTTP ${response.status}`);
  7863. }
  7864. const disposition = response.headers.get('Content-Disposition');
  7865. const downloadFilename = parseContentDispositionFilename(disposition) || filename || `file_${id}`;
  7866. const blob = await response.blob();
  7867. const url = window.URL.createObjectURL(blob);
  7868. const a = document.createElement('a');
  7869. a.href = url;
  7870. a.download = downloadFilename;
  7871. document.body.appendChild(a);
  7872. a.click();
  7873. document.body.removeChild(a);
  7874. window.URL.revokeObjectURL(url);
  7875. },
  7876. getLibraryFileThumbnailUrl: (id: number) => withMediaToken(`${API_BASE}/library/files/${id}/thumbnail`),
  7877. // Client-rendered preview thumbnail upload (#2976). STEP/PDF/spreadsheet
  7878. // previews render in the browser; the first render is posted back so the
  7879. // grid gets a thumbnail without a server-side renderer for those formats.
  7880. uploadLibraryPreviewThumbnail: async (fileId: number, thumbnail: Blob): Promise<{ updated: boolean }> => {
  7881. const formData = new FormData();
  7882. formData.append('thumbnail', thumbnail, 'preview.png');
  7883. const headers: Record<string, string> = {};
  7884. if (authToken) {
  7885. headers['Authorization'] = `Bearer ${authToken}`;
  7886. }
  7887. const response = await fetch(`${API_BASE}/library/files/${fileId}/preview-thumbnail`, {
  7888. method: 'POST',
  7889. headers,
  7890. body: formData,
  7891. });
  7892. if (!response.ok) {
  7893. const error = await response.json().catch(() => ({}));
  7894. throw new Error(error.detail || `HTTP ${response.status}`);
  7895. }
  7896. return response.json();
  7897. },
  7898. getLibraryFilePlateThumbnail: (id: number, plateIndex: number) =>
  7899. withMediaToken(`${API_BASE}/library/files/${id}/plate-thumbnail/${plateIndex}`),
  7900. // Photos of the printed result (#3077) — same shape as the archive photo API.
  7901. getLibraryFilePhotoUrl: (fileId: number, filename: string) =>
  7902. withMediaToken(`${API_BASE}/library/files/${fileId}/photos/${encodeURIComponent(filename)}`),
  7903. uploadLibraryFilePhoto: async (fileId: number, file: File): Promise<{ status: string; filename: string; photos: string[] }> => {
  7904. const formData = new FormData();
  7905. formData.append('file', file);
  7906. const headers: Record<string, string> = {};
  7907. if (authToken) {
  7908. headers['Authorization'] = `Bearer ${authToken}`;
  7909. }
  7910. const response = await fetch(`${API_BASE}/library/files/${fileId}/photos`, {
  7911. method: 'POST',
  7912. headers,
  7913. body: formData,
  7914. });
  7915. if (!response.ok) {
  7916. const error = await response.json().catch(() => ({}));
  7917. throw new Error(error.detail || `HTTP ${response.status}`);
  7918. }
  7919. return response.json();
  7920. },
  7921. deleteLibraryFilePhoto: (fileId: number, filename: string) =>
  7922. request<{ status: string; photos: string[] }>(`/library/files/${fileId}/photos/${encodeURIComponent(filename)}`, {
  7923. method: 'DELETE',
  7924. }),
  7925. getLibraryFileGcodeUrl: (id: number) => `${API_BASE}/library/files/${id}/gcode`,
  7926. moveLibraryFiles: (fileIds: number[], folderId: number | null) =>
  7927. request<{ status: string; moved: number }>('/library/files/move', {
  7928. method: 'POST',
  7929. body: JSON.stringify({ file_ids: fileIds, folder_id: folderId }),
  7930. }),
  7931. bulkDeleteLibrary: (fileIds: number[], folderIds: number[]) =>
  7932. request<{ deleted_files: number; deleted_folders: number }>('/library/bulk-delete', {
  7933. method: 'POST',
  7934. body: JSON.stringify({ file_ids: fileIds, folder_ids: folderIds }),
  7935. }),
  7936. getLibraryStats: () => request<LibraryStats>('/library/stats'),
  7937. batchGenerateStlThumbnails: (options: {
  7938. file_ids?: number[];
  7939. folder_id?: number;
  7940. all_missing?: boolean;
  7941. }) =>
  7942. request<BatchThumbnailResponse>('/library/generate-stl-thumbnails', {
  7943. method: 'POST',
  7944. body: JSON.stringify(options),
  7945. }),
  7946. combineLibraryFiles: (items: { file_id: number; copies: number }[], filename: string, folderId: number | null) =>
  7947. request<LibraryFileUploadResponse>('/library/files/combine', {
  7948. method: 'POST',
  7949. body: JSON.stringify({ items, filename, folder_id: folderId }),
  7950. }),
  7951. getLibraryFilePlates: (fileId: number) =>
  7952. request<LibraryFilePlatesResponse>(`/library/files/${fileId}/plates`),
  7953. getLibraryFileFilamentRequirements: (
  7954. fileId: number,
  7955. plateId?: number,
  7956. requestId?: string,
  7957. /** Ask for one entry per project slot instead of only the slots this
  7958. * plate consumes. The slice modal needs it: its filament list is
  7959. * positional, so a source whose only used slot is 4 must still present
  7960. * four rows or the user's pick is bound to slot 1 (#2712). Print-time
  7961. * AMS matching must NOT set this — it wants the used-only list. */
  7962. fullSlots?: boolean,
  7963. ) => {
  7964. const qs = new URLSearchParams();
  7965. if (plateId !== undefined) qs.set('plate_id', String(plateId));
  7966. if (requestId) qs.set('request_id', requestId);
  7967. if (fullSlots) qs.set('full_slots', 'true');
  7968. return request<{
  7969. file_id: number;
  7970. filename: string;
  7971. filaments: Array<{
  7972. slot_id: number;
  7973. type: string;
  7974. color: string;
  7975. used_grams: number;
  7976. used_meters: number;
  7977. used_in_plate?: boolean;
  7978. }>;
  7979. }>(`/library/files/${fileId}/filament-requirements${qs.toString() ? `?${qs}` : ''}`);
  7980. },
  7981. /** Poll the sidecar's per-request progress snapshot via the Bambuddy
  7982. * proxy. Used by the SliceModal's filament-discovery path so the inline
  7983. * spinner + persistent toast can show "Generating G-code (45%)" while
  7984. * the preview slice runs. Returns null on 404 (sidecar doesn't yet
  7985. * have an entry — early race window — or it expired) so the poller
  7986. * can keep trying. */
  7987. getPreviewSliceProgress: async (requestId: string): Promise<SliceJobProgress | null> => {
  7988. try {
  7989. return await request<SliceJobProgress>(`/slicer/preview-progress/${encodeURIComponent(requestId)}`);
  7990. } catch {
  7991. return null;
  7992. }
  7993. },
  7994. // GitHub Backup
  7995. getGitHubBackupConfig: () =>
  7996. request<GitHubBackupConfig | null>('/github-backup/config'),
  7997. getGitHubBackupCloudAccounts: () =>
  7998. request<CloudAccountCounts>('/github-backup/cloud-accounts'),
  7999. saveGitHubBackupConfig: (config: GitHubBackupConfigCreate) =>
  8000. request<GitHubBackupConfig>('/github-backup/config', {
  8001. method: 'POST',
  8002. body: JSON.stringify(config),
  8003. }),
  8004. updateGitHubBackupConfig: (config: Partial<GitHubBackupConfigCreate>) =>
  8005. request<GitHubBackupConfig>('/github-backup/config', {
  8006. method: 'PATCH',
  8007. body: JSON.stringify(config),
  8008. }),
  8009. testGitHubConnection: (repoUrl: string, token: string, provider: GitProviderType = 'github') =>
  8010. request<GitHubTestConnectionResponse>('/github-backup/test', {
  8011. method: 'POST',
  8012. body: JSON.stringify({ repo_url: repoUrl, token, provider }),
  8013. }),
  8014. testGitHubStoredConnection: () =>
  8015. request<GitHubTestConnectionResponse>('/github-backup/test-stored', { method: 'POST' }),
  8016. triggerGitHubBackup: () =>
  8017. request<GitHubBackupTriggerResponse>('/github-backup/run', { method: 'POST' }),
  8018. getGitHubBackupStatus: () =>
  8019. request<GitHubBackupStatus>('/github-backup/status'),
  8020. getGitHubBackupLogs: (limit: number = 50) =>
  8021. request<GitHubBackupLog[]>(`/github-backup/logs?limit=${limit}`),
  8022. clearGitHubBackupLogs: (keepLast: number = 10) =>
  8023. request<{ deleted: number; message: string }>(`/github-backup/logs?keep_last=${keepLast}`, { method: 'DELETE' }),
  8024. // Restore from a Git backup (#2656)
  8025. getGitHubBackupCommits: (limit: number = 20) =>
  8026. request<GitHubCommitListResponse>(`/github-backup/commits?limit=${limit}`),
  8027. getGitHubRestorePreview: (ref: string = 'HEAD') =>
  8028. request<GitHubRestorePreview>(`/github-backup/restore/preview?ref=${encodeURIComponent(ref)}`),
  8029. restoreFromGitHub: (payload: GitHubRestoreRequest) =>
  8030. request<GitHubRestoreResponse>('/github-backup/restore', {
  8031. method: 'POST',
  8032. body: JSON.stringify(payload),
  8033. }),
  8034. // Scheduled local backups
  8035. getLocalBackupStatus: () =>
  8036. request<LocalBackupStatus>('/local-backup/status'),
  8037. triggerLocalBackup: () =>
  8038. request<{ success: boolean; message: string; filename?: string }>('/local-backup/run', { method: 'POST' }),
  8039. checkLocalBackupPath: () =>
  8040. request<LocalBackupPathCheck>('/local-backup/path-check'),
  8041. getLocalBackups: () =>
  8042. request<LocalBackupFile[]>('/local-backup/backups'),
  8043. downloadLocalBackup: async (filename: string): Promise<{ blob: Blob; filename: string }> => {
  8044. const response = await fetch(`${API_BASE}/local-backup/backups/${encodeURIComponent(filename)}/download`, {
  8045. headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {},
  8046. });
  8047. if (!response.ok) throw new Error('Download failed');
  8048. const blob = await response.blob();
  8049. return { blob, filename };
  8050. },
  8051. restoreLocalBackup: (filename: string) =>
  8052. request<{ success: boolean; message: string }>(`/local-backup/backups/${encodeURIComponent(filename)}/restore`, { method: 'POST' }),
  8053. deleteLocalBackup: (filename: string) =>
  8054. request<{ success: boolean; message: string }>(`/local-backup/backups/${encodeURIComponent(filename)}`, { method: 'DELETE' }),
  8055. // Obico AI failure detection
  8056. getObicoStatus: () =>
  8057. request<ObicoStatus>('/obico/status'),
  8058. getObicoPrinterStatus: () =>
  8059. request<ObicoPrinterStatus>('/obico/printer-status'),
  8060. // `token` is sent as-is, so an empty string tests with no token at all.
  8061. // Omitting the argument makes the backend fall back to the saved token.
  8062. testObicoConnection: (url: string, token?: string) =>
  8063. request<ObicoTestConnection>('/obico/test-connection', {
  8064. method: 'POST',
  8065. body: JSON.stringify(token === undefined ? { url } : { url, token }),
  8066. }),
  8067. // OctoEverywhere AI failure detection
  8068. getOctoEverywhereStatus: () =>
  8069. request<OctoEverywhereStatus>('/octoeverywhere/status'),
  8070. getOctoEverywherePrinterStatus: () =>
  8071. request<OctoEverywherePrinterStatus>('/octoeverywhere/printer-status'),
  8072. // An omitted key uses the saved key; an explicit empty key is rejected.
  8073. testOctoEverywhereConnection: (apiKey?: string, confidence?: OctoEverywhereConfidence) =>
  8074. request<OctoEverywhereTestConnection>('/octoeverywhere/test-connection', {
  8075. method: 'POST',
  8076. body: JSON.stringify({ api_key: apiKey, confidence }),
  8077. }),
  8078. // Slicer API — slice in the background. Both endpoints return 202 + a
  8079. // job_id; poll /slice-jobs/{id} until status is `completed` or `failed`.
  8080. sliceLibraryFile: (fileId: number, body: SliceRequest) =>
  8081. request<SliceJobEnqueueResponse>(`/library/files/${fileId}/slice`, {
  8082. method: 'POST',
  8083. body: JSON.stringify(body),
  8084. }),
  8085. sliceArchive: (archiveId: number, body: SliceRequest) =>
  8086. request<SliceJobEnqueueResponse>(`/archives/${archiveId}/slice`, {
  8087. method: 'POST',
  8088. body: JSON.stringify(body),
  8089. }),
  8090. getSliceJob: (jobId: number) =>
  8091. request<SliceJobState>(`/slice-jobs/${jobId}`),
  8092. // Unified slicer-preset listing — cloud + local + standard, deduped by name.
  8093. // Used by the SliceModal; see UnifiedPresetsResponse for the shape and
  8094. // backend/app/api/routes/slicer_presets.py for the priority rules.
  8095. // `refresh` bypasses the in-process cloud and bundled-preset caches on the
  8096. // backend; the SliceModal's Refresh button passes true so a preset deleted
  8097. // in Bambu Studio or Bambu Handy shows up without the 5-min TTL wait.
  8098. getSlicerPresets: (options?: { refresh?: boolean }) =>
  8099. request<UnifiedPresetsResponse>(
  8100. options?.refresh ? '/slicer/presets?refresh=true' : '/slicer/presets',
  8101. ),
  8102. // Slicer Pipelines (#1425) — preset bundles the SliceModal can apply in
  8103. // one click. CRUD is gated on PIPELINES_READ / PIPELINES_WRITE.
  8104. listSlicerPipelines: () =>
  8105. request<SlicerPipelinesListResponse>('/slicer-pipelines/'),
  8106. createSlicerPipeline: (data: SlicerPipelineCreateRequest) =>
  8107. request<SlicerPipeline>('/slicer-pipelines/', {
  8108. method: 'POST',
  8109. body: JSON.stringify(data),
  8110. }),
  8111. updateSlicerPipeline: (id: number, data: SlicerPipelineUpdateRequest) =>
  8112. request<SlicerPipeline>(`/slicer-pipelines/${id}`, {
  8113. method: 'PUT',
  8114. body: JSON.stringify(data),
  8115. }),
  8116. deleteSlicerPipeline: (id: number) =>
  8117. request<void>(`/slicer-pipelines/${id}`, { method: 'DELETE' }),
  8118. checkPipelineEligibility: (
  8119. pipelineId: number,
  8120. source: { kind: 'libraryFile'; id: number } | { kind: 'archive'; id: number },
  8121. ) =>
  8122. request<PipelineEligibilityReport>(`/slicer-pipelines/${pipelineId}/check-eligibility`, {
  8123. method: 'POST',
  8124. body: JSON.stringify(
  8125. source.kind === 'libraryFile'
  8126. ? { source_library_file_id: source.id }
  8127. : { source_archive_id: source.id },
  8128. ),
  8129. }),
  8130. runPipeline: (
  8131. pipelineId: number,
  8132. source: { kind: 'libraryFile'; id: number } | { kind: 'archive'; id: number },
  8133. force = false,
  8134. copies = 1,
  8135. ) =>
  8136. request<PipelineRun>(`/slicer-pipelines/${pipelineId}/run`, {
  8137. method: 'POST',
  8138. body: JSON.stringify({
  8139. ...(source.kind === 'libraryFile'
  8140. ? { source_library_file_id: source.id }
  8141. : { source_archive_id: source.id }),
  8142. force,
  8143. copies,
  8144. }),
  8145. }),
  8146. listPipelineRuns: (pipelineId: number, limit = 5) =>
  8147. request<PipelineRunListResponse>(
  8148. `/slicer-pipelines/${pipelineId}/runs?limit=${limit}`,
  8149. ),
  8150. // Dashboard list across all pipelines (#1425 PR C).
  8151. listAllPipelineRuns: (params: {
  8152. limit?: number;
  8153. offset?: number;
  8154. pipelineId?: number;
  8155. status?: string;
  8156. targetPrinterId?: number;
  8157. targetModelClass?: string;
  8158. } = {}) => {
  8159. const search = new URLSearchParams();
  8160. if (params.limit) search.set('limit', String(params.limit));
  8161. if (params.offset) search.set('offset', String(params.offset));
  8162. if (params.pipelineId) search.set('pipeline_id', String(params.pipelineId));
  8163. if (params.status) search.set('status', params.status);
  8164. if (params.targetPrinterId) search.set('target_printer_id', String(params.targetPrinterId));
  8165. if (params.targetModelClass) search.set('target_model_class', params.targetModelClass);
  8166. const q = search.toString();
  8167. return request<PipelineRunListResponse>(
  8168. `/pipeline-runs${q ? '?' + q : ''}`,
  8169. );
  8170. },
  8171. // Clear terminal pipeline runs (#1425 PR C polish). Deletes all runs in
  8172. // a terminal state (completed/failed/cancelled/partial_failure); in-flight
  8173. // runs are preserved.
  8174. clearTerminalPipelineRuns: () =>
  8175. request<{ deleted: number }>('/pipeline-runs/clear', { method: 'POST' }),
  8176. cancelPipelineRun: (runId: number) =>
  8177. request<PipelineRun>(`/pipeline-runs/${runId}/cancel`, { method: 'POST' }),
  8178. retryFailedPipelineRun: (runId: number) =>
  8179. request<PipelineRun>(`/pipeline-runs/${runId}/retry-failed`, { method: 'POST' }),
  8180. // Canonical Bambu printer-model registry — "Bambu Lab <model>" → short code.
  8181. // Single source of truth shared with backend (PRINTER_MODEL_MAP); the
  8182. // SliceModal uses this to classify cloud / standard presets by their
  8183. // `@BBL <code>` suffix against the selected printer-preset name (#1325).
  8184. getSlicerPrinterModels: () =>
  8185. request<Record<string, string>>('/slicer/printer-models'),
  8186. getSlicerLoadedSpools: () =>
  8187. request<LoadedSpoolsResponse>('/slicer/loaded-spools'),
  8188. /**
  8189. * Effective values of a process preset, with its `inherits:` chain flattened
  8190. * by the slicer sidecar. Powers the slice modal's settings panel, which would
  8191. * otherwise show the option schema's compiled-in defaults (a preset setting a
  8192. * 0.42mm line width appears as the C++ default of 0).
  8193. *
  8194. * `resolved: false` means the values could not be obtained -- sidecar offline,
  8195. * too old for the endpoint, or slicing not configured -- and the caller should
  8196. * fall back to schema defaults rather than treat it as a failure.
  8197. */
  8198. getSlicerPresetValues: (ref: PresetRef) =>
  8199. request<SlicerPresetValues>(
  8200. `/slicer/preset-values?source=${encodeURIComponent(ref.source)}&id=${encodeURIComponent(ref.id)}`,
  8201. ),
  8202. // Local Presets (OrcaSlicer imports)
  8203. getLocalPresets: () =>
  8204. request<LocalPresetsResponse>('/local-presets/'),
  8205. importLocalPresets: (formData: FormData) =>
  8206. fetch(`${API_BASE}/local-presets/import`, {
  8207. method: 'POST',
  8208. headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {},
  8209. body: formData,
  8210. }).then(async (res) => {
  8211. if (!res.ok) {
  8212. const err = await res.json().catch(() => ({}));
  8213. throw new Error(err.detail || `HTTP ${res.status}`);
  8214. }
  8215. return res.json() as Promise<ImportResponse>;
  8216. }),
  8217. deleteLocalPreset: (id: number) =>
  8218. request<{ success: boolean }>(`/local-presets/${id}`, { method: 'DELETE' }),
  8219. };
  8220. // AMS History types
  8221. export interface AMSHistoryPoint {
  8222. recorded_at: string;
  8223. humidity: number | null;
  8224. humidity_raw: number | null;
  8225. temperature: number | null;
  8226. }
  8227. export interface AMSHistoryResponse {
  8228. printer_id: number;
  8229. ams_id: number;
  8230. data: AMSHistoryPoint[];
  8231. min_humidity: number | null;
  8232. max_humidity: number | null;
  8233. avg_humidity: number | null;
  8234. min_temperature: number | null;
  8235. max_temperature: number | null;
  8236. avg_temperature: number | null;
  8237. }
  8238. export type HeaterSensorKind = 'nozzle' | 'nozzle_2' | 'bed' | 'chamber';
  8239. export interface HeaterHistoryPoint {
  8240. recorded_at: string;
  8241. value: number | null;
  8242. target: number | null;
  8243. }
  8244. export interface HeaterSeries {
  8245. sensor_kind: HeaterSensorKind;
  8246. data: HeaterHistoryPoint[];
  8247. min_value: number | null;
  8248. max_value: number | null;
  8249. avg_value: number | null;
  8250. }
  8251. export interface PrinterSensorHistoryResponse {
  8252. printer_id: number;
  8253. series: HeaterSeries[];
  8254. }
  8255. // System Info types
  8256. export interface SystemInfo {
  8257. app: {
  8258. version: string;
  8259. base_dir: string;
  8260. archive_dir: string;
  8261. };
  8262. database: {
  8263. engine: string;
  8264. version: string;
  8265. archives: number;
  8266. archives_completed: number;
  8267. archives_failed: number;
  8268. archives_printing: number;
  8269. printers: number;
  8270. filaments: number;
  8271. projects: number;
  8272. smart_plugs: number;
  8273. total_print_time_seconds: number;
  8274. total_print_time_formatted: string;
  8275. total_filament_grams: number;
  8276. total_filament_kg: number;
  8277. };
  8278. printers: {
  8279. total: number;
  8280. connected: number;
  8281. connected_list: Array<{
  8282. id: number;
  8283. name: string;
  8284. state: string;
  8285. model: string;
  8286. }>;
  8287. };
  8288. storage: {
  8289. archive_size_bytes: number;
  8290. archive_size_formatted: string;
  8291. database_size_bytes: number;
  8292. database_size_formatted: string;
  8293. disk_total_bytes: number;
  8294. disk_total_formatted: string;
  8295. disk_used_bytes: number;
  8296. disk_used_formatted: string;
  8297. disk_free_bytes: number;
  8298. disk_free_formatted: string;
  8299. disk_percent_used: number;
  8300. };
  8301. system: {
  8302. platform: string;
  8303. platform_release: string;
  8304. platform_version: string;
  8305. architecture: string;
  8306. hostname: string;
  8307. python_version: string;
  8308. uptime_seconds: number;
  8309. uptime_formatted: string;
  8310. boot_time: string;
  8311. };
  8312. memory: {
  8313. total_bytes: number;
  8314. total_formatted: string;
  8315. available_bytes: number;
  8316. available_formatted: string;
  8317. used_bytes: number;
  8318. used_formatted: string;
  8319. percent_used: number;
  8320. };
  8321. cpu: {
  8322. count: number;
  8323. count_logical: number;
  8324. percent: number;
  8325. };
  8326. }
  8327. export interface StorageUsageCategory {
  8328. key: string;
  8329. label: string;
  8330. bytes: number;
  8331. formatted: string;
  8332. percent_of_total: number;
  8333. }
  8334. export interface StorageUsageOtherItem {
  8335. bucket: string;
  8336. label: string;
  8337. kind: 'system' | 'data';
  8338. deletable: boolean;
  8339. bytes: number;
  8340. formatted: string;
  8341. percent_of_total: number;
  8342. }
  8343. export interface StorageUsageResponse {
  8344. roots: string[];
  8345. total_bytes: number;
  8346. total_formatted: string;
  8347. categories: StorageUsageCategory[];
  8348. other_breakdown: StorageUsageOtherItem[];
  8349. scan_errors: number;
  8350. generated_at: string;
  8351. cache: {
  8352. hit: boolean;
  8353. age_seconds: number;
  8354. max_age_seconds: number;
  8355. };
  8356. }
  8357. // Library (File Manager) types
  8358. export interface LibraryFolderTree {
  8359. id: number;
  8360. name: string;
  8361. parent_id: number | null;
  8362. project_id: number | null;
  8363. archive_id: number | null;
  8364. project_name: string | null;
  8365. archive_name: string | null;
  8366. is_external: boolean;
  8367. external_path: string | null;
  8368. external_readonly: boolean;
  8369. file_count: number;
  8370. // max(folder.updated_at, max(immediate-child file.updated_at)). Used by
  8371. // the File Manager folder tree's "sort by recent activity" mode (#1770).
  8372. latest_activity_at: string | null;
  8373. // Ownership (#3201). can_* are for the current user: what the File
  8374. // Manager may offer on this folder. The backend enforces the same rules.
  8375. created_by_id: number | null;
  8376. shared: boolean;
  8377. can_write: boolean;
  8378. can_rename: boolean;
  8379. can_delete: boolean;
  8380. children: LibraryFolderTree[];
  8381. }
  8382. export interface LibraryFolder {
  8383. id: number;
  8384. name: string;
  8385. parent_id: number | null;
  8386. project_id: number | null;
  8387. archive_id: number | null;
  8388. project_name: string | null;
  8389. archive_name: string | null;
  8390. is_external: boolean;
  8391. external_path: string | null;
  8392. external_readonly: boolean;
  8393. external_show_hidden: boolean;
  8394. file_count: number;
  8395. latest_activity_at: string | null;
  8396. // Ownership (#3201). can_* are for the current user: what the File
  8397. // Manager may offer on this folder. The backend enforces the same rules.
  8398. created_by_id: number | null;
  8399. shared: boolean;
  8400. can_write: boolean;
  8401. can_rename: boolean;
  8402. can_delete: boolean;
  8403. created_at: string;
  8404. updated_at: string;
  8405. }
  8406. export interface LibraryFolderCreate {
  8407. name: string;
  8408. parent_id?: number | null;
  8409. project_id?: number | null;
  8410. archive_id?: number | null;
  8411. }
  8412. export interface ExternalFolderCreate {
  8413. name: string;
  8414. external_path: string;
  8415. readonly?: boolean;
  8416. show_hidden?: boolean;
  8417. parent_id?: number | null;
  8418. }
  8419. export interface LibraryFolderUpdate {
  8420. name?: string;
  8421. parent_id?: number | null;
  8422. project_id?: number | null; // 0 to unlink
  8423. archive_id?: number | null; // 0 to unlink
  8424. shared?: boolean; // library:update_all only (#3201)
  8425. }
  8426. export interface LibraryFileDuplicate {
  8427. id: number;
  8428. filename: string;
  8429. folder_id: number | null;
  8430. folder_name: string | null;
  8431. created_at: string;
  8432. }
  8433. export interface LibraryFile {
  8434. id: number;
  8435. folder_id: number | null;
  8436. folder_name: string | null;
  8437. project_id: number | null;
  8438. project_name: string | null;
  8439. is_external: boolean;
  8440. filename: string;
  8441. file_path: string;
  8442. file_type: string;
  8443. file_size: number;
  8444. file_hash: string | null;
  8445. thumbnail_path: string | null;
  8446. metadata: Record<string, unknown> | null;
  8447. print_count: number;
  8448. last_printed_at: string | null;
  8449. notes: string | null;
  8450. // User link + photos of the printed result (#3077); source_url is the
  8451. // read-only import provenance (MakerWorld).
  8452. external_url: string | null;
  8453. photos: string[];
  8454. source_url: string | null;
  8455. duplicates: LibraryFileDuplicate[] | null;
  8456. duplicate_count: number;
  8457. // User tracking (Issue #206)
  8458. created_by_id: number | null;
  8459. created_by_username: string | null;
  8460. created_at: string;
  8461. updated_at: string;
  8462. // Metadata fields
  8463. print_name: string | null;
  8464. print_time_seconds: number | null;
  8465. filament_used_grams: number | null;
  8466. sliced_for_model: string | null;
  8467. }
  8468. export interface LibraryTagSummary {
  8469. id: number;
  8470. name: string;
  8471. }
  8472. export interface LibraryFileListItem {
  8473. id: number;
  8474. folder_id: number | null;
  8475. is_external: boolean;
  8476. filename: string;
  8477. file_type: string;
  8478. file_size: number;
  8479. thumbnail_path: string | null;
  8480. print_count: number;
  8481. duplicate_count: number;
  8482. // User tracking (Issue #206)
  8483. created_by_id: number | null;
  8484. created_by_username: string | null;
  8485. created_at: string;
  8486. // Real on-disk modification time (#2680). Null for managed uploads; the date
  8487. // sort and "Modified" column use `fs_modified_at ?? created_at`.
  8488. fs_modified_at: string | null;
  8489. print_name: string | null;
  8490. print_time_seconds: number | null;
  8491. filament_used_grams: number | null;
  8492. sliced_for_model: string | null;
  8493. // Tags assigned to this file (#1268). The backend always emits an empty
  8494. // array when a file has no tags, but the field is typed optional so any
  8495. // legacy code path (or mock) that constructs a LibraryFileListItem without
  8496. // it doesn't crash the renderer. Read sites use `file.tags ?? []`.
  8497. tags?: LibraryTagSummary[];
  8498. // Variant grouping (#671 / #2570). `variant_count` is the size of the whole
  8499. // group, which may include files in other folders — never the number of
  8500. // matching rows on screen. 0 when the file is not grouped.
  8501. variant_group_id?: number | null;
  8502. variant_count?: number;
  8503. // Metadata indicators (#3077). Optional for the same reason as `tags`: older
  8504. // mocks construct list items without them. Read sites default to falsy.
  8505. external_url?: string | null;
  8506. has_notes?: boolean;
  8507. photo_count?: number;
  8508. }
  8509. // Variant groups (#671 / #2570): the same job sliced for different printers.
  8510. export interface VariantGroupMember {
  8511. library_file_id: number;
  8512. filename: string;
  8513. target_model: string;
  8514. position: number;
  8515. }
  8516. export interface VariantGroup {
  8517. id: number;
  8518. name: string;
  8519. /** In priority order — index 0 wins when several printers are free at once. */
  8520. members: VariantGroupMember[];
  8521. }
  8522. // Library tag catalog (#1268)
  8523. export interface LibraryTag {
  8524. id: number;
  8525. name: string;
  8526. file_count: number;
  8527. created_at: string;
  8528. updated_at: string;
  8529. }
  8530. export interface LibraryTagBulkAssignResult {
  8531. files_updated: number;
  8532. associations_added: number;
  8533. associations_removed: number;
  8534. }
  8535. export interface LibraryFileUpdate {
  8536. filename?: string;
  8537. folder_id?: number | null;
  8538. project_id?: number | null;
  8539. notes?: string | null;
  8540. external_url?: string | null;
  8541. }
  8542. // Library trash (#1008)
  8543. export interface LibraryTrashItem {
  8544. id: number;
  8545. filename: string;
  8546. file_size: number;
  8547. thumbnail_path: string | null;
  8548. folder_id: number | null;
  8549. folder_name: string | null;
  8550. created_by_id: number | null;
  8551. created_by_username: string | null;
  8552. deleted_at: string;
  8553. auto_purge_at: string;
  8554. }
  8555. export interface LibraryTrashListResponse {
  8556. items: LibraryTrashItem[];
  8557. total: number;
  8558. retention_days: number;
  8559. }
  8560. export interface LibraryPurgePreview {
  8561. count: number;
  8562. total_bytes: number;
  8563. sample_filenames: string[];
  8564. older_than_days: number;
  8565. include_never_printed: boolean;
  8566. }
  8567. export interface LibraryTrashSettings {
  8568. retention_days: number;
  8569. auto_purge_enabled: boolean;
  8570. auto_purge_days: number;
  8571. auto_purge_include_never_printed: boolean;
  8572. }
  8573. export interface ArchivePurgePreview {
  8574. count: number;
  8575. total_bytes: number;
  8576. sample_filenames: string[];
  8577. older_than_days: number;
  8578. }
  8579. export interface ArchiveMergeMember {
  8580. id: number;
  8581. print_name: string | null;
  8582. filename: string;
  8583. created_at: string | null;
  8584. run_count: number;
  8585. }
  8586. /** Why a group is left out: at work now, or holding files only one can keep. */
  8587. export type ArchiveMergeSkip = 'busy' | 'conflicting_files' | 'failed' | 'not_a_group';
  8588. export interface ArchiveMergeGroup {
  8589. survivor: ArchiveMergeMember;
  8590. merged: ArchiveMergeMember[];
  8591. skipped: ArchiveMergeSkip | null;
  8592. }
  8593. export interface ArchiveMergePreview {
  8594. groups: ArchiveMergeGroup[];
  8595. }
  8596. export interface ArchiveMergeResult {
  8597. merged: { survivor_id: number; merged_ids: number[] }[];
  8598. skipped: { survivor_id: number; reason: ArchiveMergeSkip }[];
  8599. }
  8600. export interface ArchivePurgeSettings {
  8601. enabled: boolean;
  8602. days: number;
  8603. // #1390: when true, bulk-deletes the linked PrintLogEntry rows so the
  8604. // contribution drops from Quick Stats too. Default false — soft-delete,
  8605. // Quick Stats preserved.
  8606. purge_stats: boolean;
  8607. }
  8608. export interface LibraryFileUploadResponse {
  8609. id: number;
  8610. filename: string;
  8611. file_type: string;
  8612. file_size: number;
  8613. thumbnail_path: string | null;
  8614. duplicate_of: number | null;
  8615. metadata: Record<string, unknown> | null;
  8616. }
  8617. export interface LibraryStats {
  8618. total_files: number;
  8619. total_folders: number;
  8620. total_size_bytes: number;
  8621. files_by_type: Record<string, number>;
  8622. total_prints: number;
  8623. disk_free_bytes: number;
  8624. disk_total_bytes: number;
  8625. disk_used_bytes: number;
  8626. }
  8627. export interface ZipExtractResult {
  8628. filename: string;
  8629. file_id: number;
  8630. folder_id: number | null;
  8631. }
  8632. export interface ZipExtractError {
  8633. filename: string;
  8634. error: string;
  8635. }
  8636. export interface ZipExtractResponse {
  8637. extracted: number;
  8638. folders_created: number;
  8639. files: ZipExtractResult[];
  8640. errors: ZipExtractError[];
  8641. }
  8642. // STL Thumbnail Generation types
  8643. export interface BatchThumbnailResult {
  8644. file_id: number;
  8645. filename: string;
  8646. success: boolean;
  8647. error?: string | null;
  8648. }
  8649. export interface BatchThumbnailResponse {
  8650. processed: number;
  8651. succeeded: number;
  8652. failed: number;
  8653. results: BatchThumbnailResult[];
  8654. }
  8655. // Discovery types
  8656. export interface DiscoveredPrinter {
  8657. serial: string;
  8658. name: string;
  8659. ip_address: string;
  8660. model: string | null;
  8661. discovered_at: string | null;
  8662. }
  8663. export interface DiscoveryStatus {
  8664. running: boolean;
  8665. }
  8666. export interface DiscoveryInfo {
  8667. is_docker: boolean;
  8668. ssdp_running: boolean;
  8669. scan_running: boolean;
  8670. subnets: string[];
  8671. }
  8672. export interface SubnetScanStatus {
  8673. running: boolean;
  8674. scanned: number;
  8675. total: number;
  8676. }
  8677. // Discovery API
  8678. export const discoveryApi = {
  8679. getInfo: () => request<DiscoveryInfo>('/discovery/info'),
  8680. startDiscovery: (duration: number = 10) =>
  8681. request<DiscoveryStatus>(`/discovery/start?duration=${duration}`, { method: 'POST' }),
  8682. stopDiscovery: () =>
  8683. request<DiscoveryStatus>('/discovery/stop', { method: 'POST' }),
  8684. getDiscoveredPrinters: () =>
  8685. request<DiscoveredPrinter[]>('/discovery/printers'),
  8686. // Subnet scanning (for Docker environments)
  8687. startSubnetScan: (subnet: string, timeout: number = 1.0) =>
  8688. request<SubnetScanStatus>('/discovery/scan', {
  8689. method: 'POST',
  8690. body: JSON.stringify({ subnet, timeout }),
  8691. }),
  8692. getScanStatus: () => request<SubnetScanStatus>('/discovery/scan/status'),
  8693. stopSubnetScan: () =>
  8694. request<SubnetScanStatus>('/discovery/scan/stop', { method: 'POST' }),
  8695. };
  8696. // Virtual Printer types
  8697. // Canonical wire values: `archive`, `review`, `queue`, `proxy`. The legacy
  8698. // `immediate` (→ archive) and `print_queue` (→ queue) names are still
  8699. // accepted by the backend so older API clients keep working, but new code
  8700. // should send the canonical names.
  8701. export type VirtualPrinterMode = 'archive' | 'review' | 'queue' | 'proxy' | 'immediate' | 'print_queue';
  8702. export interface VirtualPrinterProxyStatus {
  8703. running: boolean;
  8704. target_host: string;
  8705. ftp_port: number;
  8706. mqtt_port: number;
  8707. ftp_connections: number;
  8708. mqtt_connections: number;
  8709. }
  8710. export interface VirtualPrinterStatus {
  8711. enabled: boolean;
  8712. running: boolean;
  8713. mode: VirtualPrinterMode;
  8714. name: string;
  8715. serial: string;
  8716. model: string;
  8717. model_name: string;
  8718. pending_files: number;
  8719. target_printer_ip?: string; // For proxy mode
  8720. proxy?: VirtualPrinterProxyStatus; // For proxy mode
  8721. }
  8722. export interface VirtualPrinterSettings {
  8723. tailscale_disabled: boolean;
  8724. archive_name_source: 'metadata' | 'filename'; // Source for archive's display name
  8725. status: VirtualPrinterStatus;
  8726. }
  8727. export interface NetworkInterface {
  8728. name: string;
  8729. ip: string;
  8730. netmask: string;
  8731. subnet: string;
  8732. is_alias?: boolean;
  8733. label?: string;
  8734. }
  8735. export interface PendingUpload {
  8736. id: number;
  8737. filename: string;
  8738. // Resolved name the review card should show — mirrors what archive_print
  8739. // will eventually write to PrintArchive.print_name (#1152 follow-up). Falls
  8740. // back to the stripped filename stem when the 3MF has no embedded title or
  8741. // the operator has chosen the "filename" archive-name source.
  8742. display_name: string;
  8743. file_size: number;
  8744. source_ip: string | null;
  8745. status: string;
  8746. tags: string | null;
  8747. notes: string | null;
  8748. project_id: number | null;
  8749. uploaded_at: string;
  8750. }
  8751. // Virtual Printer API
  8752. export const virtualPrinterApi = {
  8753. getSettings: () => request<VirtualPrinterSettings>('/settings/virtual-printer'),
  8754. updateSettings: (data: {
  8755. tailscale_disabled?: boolean;
  8756. archive_name_source?: 'metadata' | 'filename';
  8757. }) => {
  8758. const params = new URLSearchParams();
  8759. if (data.tailscale_disabled !== undefined) params.set('tailscale_disabled', String(data.tailscale_disabled));
  8760. if (data.archive_name_source !== undefined) params.set('archive_name_source', data.archive_name_source);
  8761. return request<VirtualPrinterSettings>(`/settings/virtual-printer?${params.toString()}`, {
  8762. method: 'PUT',
  8763. });
  8764. },
  8765. };
  8766. // Multi Virtual Printer API
  8767. export interface VirtualPrinterConfig {
  8768. id: number;
  8769. name: string;
  8770. enabled: boolean;
  8771. mode: VirtualPrinterMode;
  8772. model: string | null;
  8773. model_name: string | null;
  8774. access_code_set: boolean;
  8775. serial: string;
  8776. target_printer_id: number | null;
  8777. auto_dispatch: boolean;
  8778. queue_force_color_match: boolean;
  8779. save_ams_mapping: boolean;
  8780. gcode_injection: boolean;
  8781. tailscale_disabled: boolean;
  8782. bind_ip: string | null;
  8783. remote_interface_ip: string | null;
  8784. position: number;
  8785. status: { running: boolean; pending_files: number; proxy?: VirtualPrinterProxyStatus };
  8786. }
  8787. export interface VirtualPrinterListResponse {
  8788. printers: VirtualPrinterConfig[];
  8789. models: Record<string, string>;
  8790. }
  8791. export const multiVirtualPrinterApi = {
  8792. list: () => request<VirtualPrinterListResponse>('/virtual-printers'),
  8793. get: (id: number) => request<VirtualPrinterConfig>(`/virtual-printers/${id}`),
  8794. create: (data: {
  8795. name?: string;
  8796. enabled?: boolean;
  8797. mode?: string;
  8798. model?: string;
  8799. access_code?: string;
  8800. target_printer_id?: number;
  8801. auto_dispatch?: boolean;
  8802. queue_force_color_match?: boolean;
  8803. save_ams_mapping?: boolean;
  8804. gcode_injection?: boolean;
  8805. bind_ip?: string;
  8806. remote_interface_ip?: string;
  8807. }) =>
  8808. request<VirtualPrinterConfig>('/virtual-printers', {
  8809. method: 'POST',
  8810. body: JSON.stringify(data),
  8811. }),
  8812. update: (id: number, data: {
  8813. name?: string;
  8814. enabled?: boolean;
  8815. mode?: string;
  8816. model?: string;
  8817. access_code?: string;
  8818. target_printer_id?: number;
  8819. auto_dispatch?: boolean;
  8820. queue_force_color_match?: boolean;
  8821. save_ams_mapping?: boolean;
  8822. gcode_injection?: boolean;
  8823. tailscale_disabled?: boolean;
  8824. bind_ip?: string;
  8825. remote_interface_ip?: string;
  8826. }) =>
  8827. request<VirtualPrinterConfig>(`/virtual-printers/${id}`, {
  8828. method: 'PUT',
  8829. body: JSON.stringify(data),
  8830. }),
  8831. remove: (id: number) =>
  8832. request<{ detail: string; id: number }>(`/virtual-printers/${id}`, {
  8833. method: 'DELETE',
  8834. }),
  8835. getTailscaleStatus: () =>
  8836. request<TailscaleStatusResponse>('/virtual-printers/tailscale-status'),
  8837. getCaCertificate: () =>
  8838. request<VPCaCertificate>('/virtual-printers/ca-certificate'),
  8839. diagnose: (id: number) =>
  8840. request<VPDiagnosticResult>(`/virtual-printers/${id}/diagnostic`),
  8841. };
  8842. /** The shared CA certificate every virtual printer presents — imported once
  8843. * into the slicer's trust store. Only the public certificate is returned. */
  8844. export interface VPCaCertificate {
  8845. pem: string;
  8846. fingerprint_sha256: string;
  8847. not_valid_after: string;
  8848. }
  8849. export type VPDiagnosticStatus = 'pass' | 'fail' | 'warn' | 'skip';
  8850. export interface VPDiagnosticCheck {
  8851. id:
  8852. | 'enabled'
  8853. | 'running'
  8854. | 'bind_interface'
  8855. | 'access_code'
  8856. | 'target_printer'
  8857. | 'port_ftps'
  8858. | 'port_mqtt'
  8859. | 'port_bind'
  8860. | 'certificate';
  8861. status: VPDiagnosticStatus;
  8862. params: Record<string, string | number>;
  8863. }
  8864. export interface VPDiagnosticResult {
  8865. vp_id: number;
  8866. vp_name: string;
  8867. mode: string;
  8868. overall: 'ok' | 'warnings' | 'problems';
  8869. checks: VPDiagnosticCheck[];
  8870. }
  8871. export interface TailscaleStatusResponse {
  8872. available: boolean;
  8873. fqdn: string;
  8874. hostname: string;
  8875. tailnet_name: string;
  8876. tailscale_ips: string[];
  8877. error: string | null;
  8878. }
  8879. // Pending Uploads API
  8880. export const pendingUploadsApi = {
  8881. list: () => request<PendingUpload[]>('/pending-uploads/'),
  8882. getCount: () => request<{ count: number }>('/pending-uploads/count'),
  8883. get: (id: number) => request<PendingUpload>(`/pending-uploads/${id}`),
  8884. archive: (id: number, data?: { tags?: string; notes?: string; project_id?: number }) =>
  8885. request<{ id: number; print_name: string; filename: string }>(`/pending-uploads/${id}/archive`, {
  8886. method: 'POST',
  8887. body: JSON.stringify(data || {}),
  8888. }),
  8889. discard: (id: number) =>
  8890. request<{ success: boolean }>(`/pending-uploads/${id}`, { method: 'DELETE' }),
  8891. archiveAll: () =>
  8892. request<{ archived: number; failed: number }>('/pending-uploads/archive-all', { method: 'POST' }),
  8893. discardAll: () =>
  8894. request<{ discarded: number }>('/pending-uploads/discard-all', { method: 'DELETE' }),
  8895. };
  8896. // Firmware API Types
  8897. export interface AvailableFirmwareVersion {
  8898. version: string;
  8899. file_available: boolean;
  8900. download_url: string | null;
  8901. release_notes: string | null;
  8902. release_time: string | null;
  8903. }
  8904. export interface FirmwareUpdateInfo {
  8905. printer_id: number;
  8906. printer_name: string;
  8907. model: string | null;
  8908. current_version: string | null;
  8909. latest_version: string | null;
  8910. update_available: boolean;
  8911. download_url: string | null;
  8912. release_notes: string | null;
  8913. available_versions: AvailableFirmwareVersion[];
  8914. }
  8915. export interface FirmwareUploadPrepare {
  8916. can_proceed: boolean;
  8917. sd_card_present: boolean;
  8918. sd_card_free_space: number;
  8919. firmware_size: number;
  8920. space_sufficient: boolean;
  8921. update_available: boolean;
  8922. current_version: string | null;
  8923. latest_version: string | null;
  8924. target_version: string | null;
  8925. firmware_filename: string | null;
  8926. errors: string[];
  8927. }
  8928. export interface FirmwareUploadStatus {
  8929. status: 'idle' | 'preparing' | 'downloading' | 'uploading' | 'complete' | 'error';
  8930. progress: number;
  8931. message: string;
  8932. error: string | null;
  8933. firmware_filename: string | null;
  8934. firmware_version: string | null;
  8935. }
  8936. // Firmware API
  8937. export const firmwareApi = {
  8938. checkUpdates: () =>
  8939. request<{ updates: FirmwareUpdateInfo[]; updates_available: number }>('/firmware/updates'),
  8940. checkPrinterUpdate: (printerId: number) => firmwareUpdateBatch(printerId),
  8941. prepareUpload: (printerId: number, version?: string) =>
  8942. request<FirmwareUploadPrepare>(
  8943. `/firmware/updates/${printerId}/prepare${version ? `?version=${encodeURIComponent(version)}` : ''}`,
  8944. ),
  8945. startUpload: (printerId: number, version?: string) =>
  8946. request<{ started: boolean; message: string }>(
  8947. `/firmware/updates/${printerId}/upload${version ? `?version=${encodeURIComponent(version)}` : ''}`,
  8948. { method: 'POST' },
  8949. ),
  8950. getUploadStatus: (printerId: number) =>
  8951. request<FirmwareUploadStatus>(`/firmware/updates/${printerId}/upload/status`),
  8952. };
  8953. // Support types
  8954. export interface DebugLoggingState {
  8955. enabled: boolean;
  8956. enabled_at: string | null;
  8957. duration_seconds: number | null;
  8958. }
  8959. export interface LogEntry {
  8960. timestamp: string;
  8961. level: string;
  8962. logger_name: string;
  8963. message: string;
  8964. }
  8965. export interface LogsResponse {
  8966. entries: LogEntry[];
  8967. total_in_file: number;
  8968. filtered_count: number;
  8969. }
  8970. // Support API
  8971. export const supportApi = {
  8972. getDebugLoggingState: () =>
  8973. request<DebugLoggingState>('/support/debug-logging'),
  8974. setDebugLogging: (enabled: boolean) =>
  8975. request<DebugLoggingState>('/support/debug-logging', {
  8976. method: 'POST',
  8977. body: JSON.stringify({ enabled }),
  8978. }),
  8979. downloadSupportBundle: async () => {
  8980. const headers: Record<string, string> = {};
  8981. if (authToken) {
  8982. headers['Authorization'] = `Bearer ${authToken}`;
  8983. }
  8984. const response = await fetch(`${API_BASE}/support/bundle`, { headers });
  8985. if (!response.ok) {
  8986. const error = await response.json().catch(() => ({}));
  8987. throw new Error(error.detail || `HTTP ${response.status}`);
  8988. }
  8989. // Get filename from Content-Disposition header or use default
  8990. const disposition = response.headers.get('Content-Disposition');
  8991. const filename = parseContentDispositionFilename(disposition) || 'bambuddy-support.zip';
  8992. // Download the blob
  8993. const blob = await response.blob();
  8994. const url = window.URL.createObjectURL(blob);
  8995. const a = document.createElement('a');
  8996. a.href = url;
  8997. a.download = filename;
  8998. document.body.appendChild(a);
  8999. a.click();
  9000. document.body.removeChild(a);
  9001. window.URL.revokeObjectURL(url);
  9002. },
  9003. getLogs: (params?: { limit?: number; level?: string; search?: string }) => {
  9004. const searchParams = new URLSearchParams();
  9005. if (params?.limit) searchParams.set('limit', params.limit.toString());
  9006. if (params?.level) searchParams.set('level', params.level);
  9007. if (params?.search) searchParams.set('search', params.search);
  9008. const query = searchParams.toString();
  9009. return request<LogsResponse>(`/support/logs${query ? `?${query}` : ''}`);
  9010. },
  9011. clearLogs: () =>
  9012. request<{ message: string }>('/support/logs', { method: 'DELETE' }),
  9013. };
  9014. // SpoolBuddy types
  9015. export interface SpoolBuddyDevice {
  9016. id: number;
  9017. device_id: string;
  9018. hostname: string;
  9019. ip_address: string;
  9020. backend_url?: string | null;
  9021. firmware_version: string | null;
  9022. has_nfc: boolean;
  9023. has_scale: boolean;
  9024. tare_offset: number;
  9025. calibration_factor: number;
  9026. nfc_reader_type: string | null;
  9027. nfc_connection: string | null;
  9028. display_brightness: number;
  9029. display_blank_timeout: number;
  9030. has_backlight: boolean;
  9031. last_calibrated_at: string | null;
  9032. last_seen: string | null;
  9033. pending_command: string | null;
  9034. nfc_ok: boolean;
  9035. scale_ok: boolean;
  9036. uptime_s: number;
  9037. update_status: string | null;
  9038. update_message: string | null;
  9039. system_stats: {
  9040. os?: { os?: string; kernel?: string; arch?: string; python?: string };
  9041. cpu_temp_c?: number;
  9042. cpu_count?: number;
  9043. load_avg?: number[];
  9044. memory?: { total_mb?: number; available_mb?: number; used_mb?: number; percent?: number };
  9045. disk?: { total_gb?: number; used_gb?: number; free_gb?: number; percent?: number };
  9046. system_uptime_s?: number;
  9047. } | null;
  9048. online: boolean;
  9049. }
  9050. export interface DaemonUpdateCheck {
  9051. current_version: string;
  9052. latest_version: string | null;
  9053. update_available: boolean;
  9054. }
  9055. // SpoolBuddy API
  9056. export const spoolbuddyApi = {
  9057. getDevices: () =>
  9058. request<SpoolBuddyDevice[]>('/spoolbuddy/devices'),
  9059. deleteDevice: (deviceId: string) =>
  9060. request<{ status: string; device_id: string }>(`/spoolbuddy/devices/${deviceId}`, {
  9061. method: 'DELETE',
  9062. }),
  9063. tare: (deviceId: string) =>
  9064. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/calibration/tare`, {
  9065. method: 'POST',
  9066. body: '{}',
  9067. }),
  9068. setCalibrationFactor: (deviceId: string, knownWeightGrams: number, rawAdc: number, tareRawAdc?: number) =>
  9069. request<{ tare_offset: number; calibration_factor: number }>(`/spoolbuddy/devices/${deviceId}/calibration/set-factor`, {
  9070. method: 'POST',
  9071. body: JSON.stringify({ known_weight_grams: knownWeightGrams, raw_adc: rawAdc, tare_raw_adc: tareRawAdc }),
  9072. }),
  9073. updateSpoolWeight: (spoolId: number, weightGrams: number) =>
  9074. request<{ status: string; weight_used: number }>('/spoolbuddy/scale/update-spool-weight', {
  9075. method: 'POST',
  9076. body: JSON.stringify({ spool_id: spoolId, weight_grams: weightGrams }),
  9077. }),
  9078. updateDisplay: (deviceId: string, brightness: number, blankTimeout: number) =>
  9079. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/display`, {
  9080. method: 'PUT',
  9081. body: JSON.stringify({ brightness, blank_timeout: blankTimeout }),
  9082. }),
  9083. updateSystemConfig: (deviceId: string, backendUrl: string, apiKey?: string) =>
  9084. request<{ status: string; message: string }>(`/spoolbuddy/devices/${deviceId}/system/config`, {
  9085. method: 'POST',
  9086. body: JSON.stringify({ backend_url: backendUrl, ...(apiKey ? { api_key: apiKey } : {}) }),
  9087. }),
  9088. checkDaemonUpdate: (deviceId: string) =>
  9089. request<DaemonUpdateCheck>(`/spoolbuddy/devices/${deviceId}/update-check`),
  9090. triggerUpdate: (deviceId: string) =>
  9091. request<{ status: string; message: string }>(`/spoolbuddy/devices/${deviceId}/update`, {
  9092. method: 'POST',
  9093. body: '{}',
  9094. }),
  9095. getSSHPublicKey: () =>
  9096. request<{ public_key: string }>('/spoolbuddy/ssh/public-key'),
  9097. writeTag: (deviceId: string, spoolId: number) =>
  9098. request<{ status: string; warnings?: string[] }>('/spoolbuddy/nfc/write-tag', {
  9099. method: 'POST',
  9100. body: JSON.stringify({ device_id: deviceId, spool_id: spoolId }),
  9101. }),
  9102. cancelWrite: (deviceId: string) =>
  9103. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/cancel-write`, {
  9104. method: 'POST',
  9105. body: '{}',
  9106. }),
  9107. systemCommand: (deviceId: string, command: 'reboot' | 'shutdown' | 'restart_daemon' | 'restart_browser') =>
  9108. request<{ status: string; command: string }>(`/spoolbuddy/devices/${deviceId}/system/command`, {
  9109. method: 'POST',
  9110. body: JSON.stringify({ command }),
  9111. }),
  9112. queueDiagnostics: (deviceId: string, type: 'nfc' | 'scale' | 'read_tag') =>
  9113. request<{ status: string; diagnostic: string; message: string }>(
  9114. `/spoolbuddy/diagnostics/${deviceId}/run?diagnostic=${type}`,
  9115. { method: 'POST', body: '{}' }
  9116. ),
  9117. getDiagnosticResult: (deviceId: string, type: 'nfc' | 'scale' | 'read_tag') =>
  9118. request<{ diagnostic: string; success: boolean; output: string; exit_code: number }>(
  9119. `/spoolbuddy/diagnostics/${deviceId}/result?diagnostic=${type}`,
  9120. { method: 'GET' }
  9121. ),
  9122. };
  9123. export interface BugReportRequest {
  9124. description: string;
  9125. email?: string;
  9126. screenshot_base64?: string;
  9127. include_support_info?: boolean;
  9128. debug_logs?: string;
  9129. }
  9130. export interface BugReportResponse {
  9131. success: boolean;
  9132. message: string;
  9133. issue_url?: string;
  9134. issue_number?: number;
  9135. }
  9136. export const bugReportApi = {
  9137. submit: (data: BugReportRequest) =>
  9138. request<BugReportResponse>('/bug-report/submit', {
  9139. method: 'POST',
  9140. body: JSON.stringify(data),
  9141. }),
  9142. startLogging: () =>
  9143. request<{ started: boolean; was_debug: boolean }>('/bug-report/start-logging', {
  9144. method: 'POST',
  9145. }),
  9146. stopLogging: (wasDebug: boolean) =>
  9147. request<{ logs: string }>(`/bug-report/stop-logging?was_debug=${wasDebug}`, {
  9148. method: 'POST',
  9149. }),
  9150. };
  9151. export type AnnouncementLevel = 'info' | 'important' | 'critical';
  9152. export interface AnnouncementText {
  9153. title: string;
  9154. body: string;
  9155. link_label?: string;
  9156. }
  9157. // One message from the Bambuddy maintainers. `texts` holds every language the
  9158. // message was written in; English is always there.
  9159. export interface Announcement {
  9160. id: string;
  9161. level: AnnouncementLevel;
  9162. texts: Record<string, AnnouncementText>;
  9163. link_url: string | null;
  9164. published_at: string | null;
  9165. expires_at: string | null;
  9166. // Past its expiry: kept as history, listed under "Earlier", never unread.
  9167. archived: boolean;
  9168. read: boolean;
  9169. }
  9170. // `visible` says whether this user may see announcements at all (switched on,
  9171. // and admin or "show to all users"); it keeps the sidebar entry while nothing
  9172. // is published.
  9173. export interface AnnouncementList {
  9174. visible: boolean;
  9175. announcements: Announcement[];
  9176. }
  9177. export const announcementsApi = {
  9178. list: () => request<AnnouncementList>('/announcements'),
  9179. markRead: (id: string) =>
  9180. request<void>(`/announcements/${encodeURIComponent(id)}/read`, { method: 'POST' }),
  9181. };
  9182. export interface SponsorPromptCheckResponse {
  9183. show: boolean;
  9184. milestone?: string;
  9185. family?: 'prints' | 'cost' | 'archives' | 'anniversary' | 'version-update';
  9186. threshold?: number;
  9187. payload?: Record<string, unknown>;
  9188. }
  9189. export const sponsorPromptApi = {
  9190. check: () => request<SponsorPromptCheckResponse>('/sponsor-prompt/check'),
  9191. dismiss: (milestone: string) =>
  9192. request<void>('/sponsor-prompt/dismiss', {
  9193. method: 'POST',
  9194. body: JSON.stringify({ milestone }),
  9195. }),
  9196. };