client.ts 339 KB

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