client.ts 320 KB

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