client.ts 341 KB

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