client.ts 347 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708
  1. import type { KProfileWriteResult } from '../utils/kprofileWrite';
  2. import type { BambuCatalogColor } from '../utils/colors';
  3. import type { ArchivePlatesResponse, LibraryFilePlatesResponse } from '../types/plates';
  4. import { batched, byField, byId } from './batch';
  5. const API_BASE = '/api/v1';
  6. export class ApiError extends Error {
  7. status: number;
  8. /** Stable error code from a structured backend detail (`{code, message}`).
  9. * Frontend uses this to look up an i18n key instead of showing the raw
  10. * English fallback. Null when the backend returned a plain-string detail. */
  11. code: string | null;
  12. /** Full structured detail object when the backend returned `{code, ...}`
  13. * with additional fields (e.g. the deficit list for 409s on queue
  14. * start, #1496). Null for plain-string or array-shaped details. */
  15. detail: Record<string, unknown> | null;
  16. constructor(
  17. message: string,
  18. status: number,
  19. code: string | null = null,
  20. detail: Record<string, unknown> | null = null,
  21. ) {
  22. super(message);
  23. this.name = 'ApiError';
  24. this.status = status;
  25. this.code = code;
  26. this.detail = detail;
  27. }
  28. }
  29. // Auth token storage
  30. // By default tokens are stored in sessionStorage (tab-scoped, cleared on close).
  31. // When the token originates from the ?token= URL param (kiosk bootstrap), it is
  32. // additionally persisted in localStorage so the kiosk survives page reloads.
  33. // 'persistent' also writes to localStorage so the token survives tab close
  34. // (used by Remember Me and the ?token= kiosk bootstrap).
  35. let authToken: string | null =
  36. sessionStorage.getItem('auth_token') ?? localStorage.getItem('auth_token');
  37. export type TokenPersistence = 'session' | 'persistent';
  38. export function setAuthToken(token: string | null, persistence: TokenPersistence = 'session') {
  39. authToken = token;
  40. try {
  41. if (token) {
  42. sessionStorage.setItem('auth_token', token);
  43. } else {
  44. sessionStorage.removeItem('auth_token');
  45. }
  46. } catch (err) {
  47. // Storage unavailable (quota exceeded, private mode): in-memory token still works for this tab.
  48. console.warn('setAuthToken: sessionStorage unavailable, token kept in-memory only', err);
  49. }
  50. try {
  51. if (!token) {
  52. localStorage.removeItem('auth_token');
  53. } else if (persistence === 'persistent') {
  54. localStorage.setItem('auth_token', token);
  55. }
  56. } catch (err) {
  57. console.warn('setAuthToken: localStorage operation failed', err);
  58. }
  59. }
  60. export function getAuthToken(): string | null {
  61. return authToken;
  62. }
  63. // Query-param tokens for <img>/<video> src URLs, which can't carry an
  64. // Authorization header. There are two, and which one a URL takes is decided
  65. // by what the URL points at, not by convenience:
  66. //
  67. // streamToken — live camera only. Minting one costs camera:view.
  68. // mediaToken — thumbnails, previews, timelapses, covers, icons. Minted by
  69. // any signed-in user and carries their identity, so those
  70. // routes can apply the same ownership rules as everywhere else.
  71. //
  72. // Before #3025 the stream token served both, which meant a user could not see
  73. // a library thumbnail without also being granted the live feed of the room the
  74. // printer sits in — and, because a stream token names nobody, those routes had
  75. // no identity to scope by and served any row to any holder.
  76. let streamToken: string | null = null;
  77. let mediaToken: string | null = null;
  78. export function setStreamToken(token: string | null) {
  79. streamToken = token;
  80. }
  81. export function getStreamToken(): string | null {
  82. return streamToken;
  83. }
  84. export function setMediaToken(token: string | null) {
  85. mediaToken = token;
  86. }
  87. export function getMediaToken(): string | null {
  88. return mediaToken;
  89. }
  90. /** Append the camera stream token to a URL if available (live camera only). */
  91. export function withStreamToken(url: string): string {
  92. if (!streamToken) return url;
  93. const sep = url.includes('?') ? '&' : '?';
  94. return `${url}${sep}token=${encodeURIComponent(streamToken)}`;
  95. }
  96. /** Append the media token to a URL if available (for <img>/<video> src). */
  97. export function withMediaToken(url: string): string {
  98. if (!mediaToken) return url;
  99. const sep = url.includes('?') ? '&' : '?';
  100. return `${url}${sep}token=${encodeURIComponent(mediaToken)}`;
  101. }
  102. function parseContentDispositionFilename(header: string | null): string | null {
  103. if (!header) return null;
  104. // RFC 5987: filename*=utf-8''percent-encoded-name
  105. const rfc5987Match = header.match(/filename\*=(?:UTF-8|utf-8)''(.+?)(?:;|$)/);
  106. if (rfc5987Match) {
  107. try { return decodeURIComponent(rfc5987Match[1]); } catch { /* fall through */ }
  108. }
  109. // Standard: filename="name" or filename=name
  110. const standardMatch = header.match(/filename="?([^";\n]+)"?/);
  111. return standardMatch?.[1] || null;
  112. }
  113. function buildSlicerUrlFilename(filename: string): string {
  114. const safe = filename.replace(/[/\\?#]/g, '_');
  115. return safe.toLowerCase().endsWith('.3mf') ? safe : `${safe}.3mf`;
  116. }
  117. /** POST JSON and return the response body as a Blob (label PDFs and images). */
  118. async function postForBlob(endpoint: string, data: unknown, signal?: AbortSignal): Promise<Blob> {
  119. const headers: Record<string, string> = { 'Content-Type': 'application/json' };
  120. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  121. const response = await fetch(`${API_BASE}${endpoint}`, {
  122. method: 'POST',
  123. headers,
  124. body: JSON.stringify(data),
  125. signal,
  126. });
  127. if (!response.ok) {
  128. const error = await response.json().catch(() => ({}));
  129. throw new Error(typeof error.detail === 'string' ? error.detail : `HTTP ${response.status}`);
  130. }
  131. return response.blob();
  132. }
  133. async function request<T>(
  134. endpoint: string,
  135. options: RequestInit = {}
  136. ): Promise<T> {
  137. const headers: Record<string, string> = {
  138. 'Content-Type': 'application/json',
  139. ...options.headers as Record<string, string>,
  140. };
  141. // Add auth token if available
  142. if (authToken) {
  143. headers['Authorization'] = `Bearer ${authToken}`;
  144. }
  145. const response = await fetch(`${API_BASE}${endpoint}`, {
  146. ...options,
  147. cache: 'no-store', // Prevent browser caching of API responses
  148. credentials: 'include', // Required for HttpOnly cookies (e.g. 2fa_challenge)
  149. headers,
  150. });
  151. if (!response.ok) {
  152. const error = await response.json().catch(() => ({}));
  153. const detail = error.detail;
  154. let message: string;
  155. let code: string | null = null;
  156. if (typeof detail === 'string') {
  157. message = detail;
  158. } else if (Array.isArray(detail)) {
  159. // FastAPI 422 shape: each entry has `msg` like "Value error, <real msg>".
  160. // Strip the prefix and join. Fall back to raw JSON if every entry has an
  161. // empty msg (defensive — shouldn't happen with stock Pydantic, but the
  162. // previous fallback masked the real cause as a bare "HTTP 422" toast).
  163. const joined = detail
  164. .map((e: { msg?: string }) => (e.msg ?? '').replace(/^Value error,\s*/i, ''))
  165. .filter(Boolean)
  166. .join('; ');
  167. message = joined || JSON.stringify(detail) || `HTTP ${response.status}`;
  168. } else if (detail && typeof detail === 'object') {
  169. // Structured detail `{code, message, ...}` — frontend uses the code
  170. // to pick an i18n key, message is the English fallback, any extra
  171. // fields land on ApiError.detail (e.g. `deficit` for #1496).
  172. code = typeof detail.code === 'string' ? detail.code : null;
  173. message = typeof detail.message === 'string' ? detail.message : `HTTP ${response.status}`;
  174. } else {
  175. message = `HTTP ${response.status}`;
  176. }
  177. const structuredDetail = detail && typeof detail === 'object' && !Array.isArray(detail)
  178. ? (detail as Record<string, unknown>)
  179. : null;
  180. // Handle 401 Unauthorized - only clear token if it's actually invalid
  181. // Don't clear on "Authentication required" which might be a timing issue
  182. if (response.status === 401) {
  183. const invalidTokenMessages = [
  184. 'Could not validate credentials',
  185. 'Token has expired',
  186. 'User not found or inactive',
  187. 'Invalid API key',
  188. 'API key has expired',
  189. ];
  190. if (invalidTokenMessages.some(m => message.includes(m))) {
  191. setAuthToken(null);
  192. // Notify AuthContext so the protected route guard re-evaluates and
  193. // redirects to /login on the same tab — without this, AuthContext.user
  194. // stays cached and the tab silently fails every request until a manual
  195. // refresh remounts AuthProvider (#1698, reported by @TCL987).
  196. if (typeof window !== 'undefined') {
  197. window.dispatchEvent(new CustomEvent('auth:expired'));
  198. }
  199. }
  200. }
  201. throw new ApiError(message, response.status, code, structuredDetail);
  202. }
  203. // Handle empty responses (204 No Content, etc.)
  204. const contentLength = response.headers.get('content-length');
  205. if (response.status === 204 || contentLength === '0') {
  206. return undefined as T;
  207. }
  208. return await response.json();
  209. }
  210. /** Upload a CSV to the spool import endpoint (#1576). Multipart, so it bypasses
  211. * `request<T>()` (which sends JSON): the browser must set the form-data
  212. * boundary itself. `dryRun` toggles preview-only vs. real import. */
  213. async function uploadSpoolsCsv<T>(file: File, dryRun: boolean): Promise<T> {
  214. const form = new FormData();
  215. form.append('file', file);
  216. const headers: Record<string, string> = {};
  217. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  218. const response = await fetch(`${API_BASE}/inventory/spools/import${dryRun ? '?dry_run=true' : ''}`, {
  219. method: 'POST',
  220. headers,
  221. body: form,
  222. });
  223. if (!response.ok) {
  224. const error = await response.json().catch(() => ({}));
  225. // detail may be a plain string or a structured {code, message} object
  226. // (e.g. the 413 too-large response). Surface the human message either way.
  227. const detail = error?.detail;
  228. const message = typeof detail === 'string' ? detail : detail?.message;
  229. throw new Error(message || `HTTP ${response.status}`);
  230. }
  231. return response.json();
  232. }
  233. // Camera diagnostic result (#1395 follow-up). Returned by
  234. // POST /printers/{id}/camera/diagnose; the frontend modal renders one
  235. // row per stage and looks up the summary code in i18n for the user-
  236. // facing remediation hint.
  237. export interface CameraDiagnoseStage {
  238. name: 'tcp_reachable' | 'first_frame' | 'live_stream_active';
  239. status: 'ok' | 'failed' | 'skipped';
  240. duration_ms: number;
  241. code: string | null;
  242. }
  243. export interface CameraDiagnoseResult {
  244. printer_id: number;
  245. protocol: 'rtsp' | 'chamber_image';
  246. port: number;
  247. // 'default' = historical X1/H2 tuning. Anything else = this model has
  248. // an override entry in backend/app/services/camera_profiles.py.
  249. profile: string;
  250. overall_status: 'ok' | 'failed';
  251. stages: CameraDiagnoseStage[];
  252. // i18n key under `camera.diagnose.summary.*`.
  253. summary_code: string;
  254. }
  255. // Connection diagnostic (GET /printers/{id}/diagnostic and
  256. // POST /printers/diagnostic). Each check's `id` + `status` resolve a
  257. // localized title/fix under `diagnostic.check.*`; `params` interpolate it.
  258. export type DiagnosticStatus = 'pass' | 'fail' | 'warn' | 'skip';
  259. export interface DiagnosticCheck {
  260. id:
  261. | 'port_mqtt'
  262. | 'port_ftps'
  263. | 'port_rtsps'
  264. | 'network_mode'
  265. | 'subnet'
  266. | 'mqtt_auth'
  267. | 'developer_mode';
  268. status: DiagnosticStatus;
  269. params: Record<string, string | number>;
  270. }
  271. export interface PrinterDiagnosticResult {
  272. printer_id: number | null;
  273. ip_address: string;
  274. overall: 'ok' | 'warnings' | 'problems';
  275. checks: DiagnosticCheck[];
  276. }
  277. // --- Log-health scan: self-service triage on the System page + bug reporter.
  278. // The backend matches recent logs against a curated known-issue catalog;
  279. // human-readable cause/fix text is rendered from i18n keys keyed by signature_id.
  280. export type LogFindingSeverity = 'error' | 'warning';
  281. export type LogFindingCategory = 'layer8' | 'environment' | 'bug';
  282. export interface LogFinding {
  283. signature_id: string;
  284. severity: LogFindingSeverity;
  285. category: LogFindingCategory;
  286. wiki_anchor: string;
  287. count: number;
  288. first_seen: string;
  289. last_seen: string;
  290. sample: string;
  291. }
  292. export interface SystemHealthResult {
  293. findings: LogFinding[];
  294. scanned_entries: number;
  295. log_available: boolean;
  296. summary: {
  297. total: number;
  298. layer8: number;
  299. environment: number;
  300. bug: number;
  301. };
  302. }
  303. // Long-lived camera tokens (#1108). The `token` field is populated only on the
  304. // create response — listing endpoints set it to null because the plaintext
  305. // value is shown to the user exactly once.
  306. //
  307. // 'camera_stream' reaches the video endpoints only. 'camwall' additionally
  308. // reaches the read-only Cam Wall feed, which names the printers (#2531), so it
  309. // is a separate scope rather than a widening of tokens already in the wild.
  310. export type LongLivedTokenScope = 'camera_stream' | 'camwall' | 'overlay';
  311. export interface LongLivedCameraToken {
  312. id: number;
  313. user_id: number;
  314. name: string;
  315. scope: LongLivedTokenScope;
  316. lookup_prefix: string;
  317. created_at: string;
  318. expires_at: string;
  319. last_used_at: string | null;
  320. token: string | null;
  321. }
  322. // An external application that signs users in with their Bambuddy account.
  323. // `client_secret` is present only in the create / rotate responses.
  324. export interface ConnectedApp {
  325. id: number;
  326. name: string;
  327. client_id: string;
  328. redirect_uri: string;
  329. enabled: boolean;
  330. created_at: string;
  331. last_used_at: string | null;
  332. client_secret?: string;
  333. }
  334. export interface ConnectAuthorizeInfo {
  335. app_name: string;
  336. username: string;
  337. already_granted: boolean;
  338. }
  339. // One row of the token-authenticated Cam Wall feed (#2531). Deliberately
  340. // smaller than PrinterStatus: no serial, no IP, no print filename — a kiosk URL
  341. // is not a secret, so the payload behind it must not be either.
  342. export interface CamWallPrinter {
  343. id: number;
  344. name: string;
  345. camera_rotation: number;
  346. connected: boolean;
  347. state: string | null;
  348. progress: number | null;
  349. remaining_time: number | null;
  350. layer_num: number | null;
  351. total_layers: number | null;
  352. hms_errors: HMSError[];
  353. }
  354. // Streaming-overlay feed (#2613). The subset of print state the /overlay page
  355. // draws for one printer, served behind an `overlay`-scoped token so OBS embeds
  356. // with no login session can read it. Unlike CamWallPrinter this names the file
  357. // being printed (the overlay shows the part on screen).
  358. export interface OverlayStatus {
  359. id: number;
  360. name: string;
  361. model: string | null;
  362. camera_rotation: number;
  363. connected: boolean;
  364. state: string | null;
  365. current_print: string | null;
  366. gcode_file: string | null;
  367. progress: number | null;
  368. remaining_time: number | null;
  369. layer_num: number | null;
  370. total_layers: number | null;
  371. stg_cur_name: string | null;
  372. // Nozzle / bed / chamber readings for the overlay's temperature fields
  373. // (#1422). Only the keys a viewer is shown; chamber is absent on models
  374. // without a real sensor.
  375. temperatures: Record<string, number>;
  376. time_format: 'system' | '12h' | '24h';
  377. }
  378. // Printer types
  379. // Printer locations (groups) and their appearance (#2962). `id` is null for a
  380. // location only printers carry, with no row of its own yet.
  381. export interface PrinterLocation {
  382. id: number | null;
  383. name: string;
  384. icon: string | null;
  385. color: string | null;
  386. printer_count: number;
  387. }
  388. export interface PrinterLocationUpdate {
  389. name: string;
  390. new_name?: string;
  391. icon?: string | null;
  392. color?: string | null;
  393. }
  394. export interface Printer {
  395. id: number;
  396. name: string;
  397. serial_number: string;
  398. ip_address: string;
  399. // Optional because the backend only returns access_code when the caller has
  400. // PRINTERS_UPDATE — Admin / Operator JWTs or auth-disabled mode. Viewers and
  401. // API keys receive a Printer without this field.
  402. access_code?: string;
  403. model: string | null;
  404. location: string | null; // Group/location name
  405. nozzle_count: number; // 1 or 2, auto-detected from MQTT
  406. // Model is sold with both Standard and High Flow nozzles, so a K-profile's
  407. // flow type is a real choice. Derived from the model, not the nozzle count —
  408. // only the A-series has a single variant.
  409. supports_nozzle_flow_type: boolean;
  410. is_active: boolean;
  411. auto_archive: boolean;
  412. external_camera_url: string | null;
  413. external_camera_type: string | null; // "mjpeg", "rtsp", "snapshot"
  414. external_camera_enabled: boolean;
  415. external_camera_snapshot_url: string | null; // optional single-frame override (#1177)
  416. camera_rotation: number; // 0, 90, 180, 270 degrees
  417. camera_light_auto: boolean; // picked for the chamber light when camera_light_mode is 'selected' (#1655)
  418. plate_detection_enabled: boolean; // Check plate before print
  419. plate_detection_roi?: PlateDetectionROI; // ROI for plate detection
  420. wear_cost_per_hour: number | null; // Wear cost per printing hour (#694)
  421. created_at: string;
  422. updated_at: string;
  423. }
  424. export interface HMSError {
  425. code: string;
  426. attr: number; // Attribute value for constructing wiki URL
  427. module: number;
  428. // Bambu's alert level: 1 error (task stopped), 2 warning (task paused),
  429. // 3 notification, 0 invalid (#2728).
  430. severity: number;
  431. actions?: string[]; // List of user-facing action keys (e.g. "CHECK_FILAMENT")
  432. job_id?: string; // Optional job ID for actions that require it (e.g. "CHECK_ASSISTANT")
  433. // Canonical hex identifier the firmware matches against — 8 chars for
  434. // print_error-sourced faults, 16 chars for hms[]-array-sourced faults. Send
  435. // this back as HmsActionBody.print_error so we don't truncate the 64-bit
  436. // identifier into the silent-rejection short code (#1830).
  437. full_code?: string;
  438. // The backend's catalogue sentence for this fault (#2926), from the table
  439. // generated out of Bambu Studio for this printer model (#2728). English only.
  440. // Null when Bambu publishes no text for the code. The frontend has no table of
  441. // its own: this field decides both the text and whether the fault counts.
  442. description?: string | null;
  443. }
  444. export interface HMSActionBody {
  445. print_error: string; // HMS error code (e.g. "05000070")
  446. action: string; // "HMS action to execute (e.g. 'resume_after_error')"
  447. job_id: string | null; // Optional job ID for context (if applicable)
  448. }
  449. export interface AMSTray {
  450. id: number;
  451. tray_color: string | null;
  452. tray_type: string | null;
  453. tray_sub_brands: string | null; // Full name like "PLA Basic", "PETG HF"
  454. tray_id_name: string | null; // Bambu filament ID like "A00-Y2" (can decode to color)
  455. tray_info_idx: string | null; // Filament preset ID like "GFA00" - maps to cloud setting_id
  456. remain: number;
  457. k: number | null; // Pressure advance value (from tray or K-profile lookup)
  458. cali_idx: number | null; // Calibration index for K-profile lookup
  459. tag_uid: string | null; // RFID tag UID (any tag)
  460. tray_uuid: string | null; // Bambu Lab spool UUID (32-char hex, only valid for Bambu Lab spools)
  461. nozzle_temp_min: number | null; // Min nozzle temperature
  462. nozzle_temp_max: number | null; // Max nozzle temperature
  463. drying_temp: number | null; // RFID-recommended drying temp
  464. drying_time: number | null; // RFID-recommended drying time (hours)
  465. state: number | null; // AMS tray state: 9=empty, 10=spool present not loaded, 11=loaded
  466. exists?: boolean | null; // Firmware tray_exist_bits: spool physically present (non-RFID → "?" not "Empty", #2527)
  467. }
  468. export interface AMSUnit {
  469. id: number;
  470. humidity: number | null;
  471. temp: number | null;
  472. is_ams_ht: boolean; // True for AMS-HT (single spool), False for regular AMS (4 spools)
  473. tray: AMSTray[];
  474. serial_number: string; // AMS unit serial number (from MQTT sn field)
  475. sw_ver: string; // AMS firmware version (from get_version info.module ams/* entry)
  476. dry_time: number; // Minutes remaining (0 = not drying, >0 = drying active)
  477. dry_countdown_stalled?: boolean; // Timer set but countdown not ticking (never started or paused)
  478. dry_status: number; // 0=Off, 1=Checking, 2=Drying, 3=Cooling, 4=Stopping, 5=Error
  479. dry_sub_status: number; // 0=Off, 1=Heating, 2=Dehumidify
  480. dry_sf_reason: number[]; // Cannot-dry reasons (1=InsufficientPower, 8=NeedPluginPower)
  481. dry_target_temp: number | null; // Active-cycle target °C (Bambu does not echo)
  482. dry_filament: string | null; // Active-cycle filament name we sent
  483. module_type: string; // "ams", "ams_f1", "n3f", "n3s"
  484. }
  485. export interface ScheduledDrying {
  486. id: number;
  487. printer_id: number;
  488. ams_id: number;
  489. temp: number;
  490. duration_hours: number;
  491. filament: string;
  492. rotate_tray: boolean;
  493. start_after: string | null; // UTC ISO with Z suffix, like the queue routes
  494. status: string;
  495. waiting_reason: string | null;
  496. error_message: string | null;
  497. // Why a failed run failed (screen_only / unsupported / did_not_start); null on
  498. // rows that failed before codes existed, which show error_message instead.
  499. error_code?: string | null;
  500. created_at: string;
  501. started_at: string | null;
  502. completed_at: string | null;
  503. }
  504. export interface NozzleInfo {
  505. // Two vocabularies live in this field, by printer generation. Legacy
  506. // printers (X1/P1) report the nozzle MATERIAL -- "stainless_steel",
  507. // "hardened_steel". H2-series report a FLOW code -- "HH01" (high flow),
  508. // "HS01" (standard); measured on an H2D. utils/nozzleFlow reads only the
  509. // latter and treats anything else as "unknown", which is what makes the
  510. // material spelling harmless here.
  511. nozzle_type: string;
  512. nozzle_diameter: string; // e.g., "0.4"
  513. }
  514. export interface NozzleRackSlot {
  515. id: number;
  516. nozzle_type: string;
  517. nozzle_diameter: string;
  518. wear: number | null;
  519. stat: number | null; // Nozzle status (e.g. mounted/docked)
  520. max_temp: number;
  521. serial_number: string;
  522. filament_color: string; // RGBA hex ("00000000" = no filament)
  523. filament_id: string;
  524. filament_type: string; // Material type (e.g. "PLA", "PETG")
  525. }
  526. export interface PrintOptions {
  527. // Core AI detectors
  528. spaghetti_detector: boolean;
  529. print_halt: boolean;
  530. halt_print_sensitivity: string; // "low", "medium", "high" - spaghetti sensitivity
  531. first_layer_inspector: boolean;
  532. printing_monitor: boolean;
  533. buildplate_marker_detector: boolean;
  534. allow_skip_parts: boolean;
  535. // Additional AI detectors (decoded from cfg bitmask)
  536. nozzle_clumping_detector: boolean;
  537. nozzle_clumping_sensitivity: string; // "low", "medium", "high"
  538. pileup_detector: boolean;
  539. pileup_sensitivity: string; // "low", "medium", "high"
  540. airprint_detector: boolean;
  541. airprint_sensitivity: string; // "low", "medium", "high"
  542. auto_recovery_step_loss: boolean;
  543. filament_tangle_detect: boolean;
  544. }
  545. export interface FilaSwitchState {
  546. installed: boolean;
  547. // Raw wire arrays, ordered **In-B first, then In-A** (BambuStudio's SwitchPos
  548. // enum). in[] values are snow-encoded (bits 8-15 = AMS id, bits 0-7 = slot,
  549. // -1 = empty); out[] values are the extruder each *outlet* terminates at, or
  550. // 0xE when unset. Neither array says which inlet is currently routed to which
  551. // outlet — that pairing is not reported. For per-AMS side information use
  552. // PrinterStatus.ams_switch_inlet instead.
  553. in_slots: number[];
  554. out_extruders: number[];
  555. stat: number;
  556. info: number;
  557. // Whether every AMS is bound to one of the switch's two inlets. Until it is,
  558. // the switch cannot route a load anywhere and the printer has to be set up
  559. // first ("Manual AMS Setup" on its screen).
  560. ready: boolean;
  561. }
  562. // Which AMS slot one hotend is currently fed from. ams_id/slot_id are null when
  563. // the hotend holds nothing. Keyed by extruder id ('0' = right, '1' = left).
  564. // tray_now cannot answer this — it is one value for the whole printer, so on a
  565. // dual-nozzle machine it names only one of the two loaded hotends.
  566. export interface ExtruderSlot {
  567. ams_id: number | null;
  568. slot_id: number | null;
  569. has_filament: boolean;
  570. }
  571. // Which FTS inlet an AMS is plumbed into: 'A' | 'B'.
  572. export type FtsInlet = 'A' | 'B';
  573. // A video device the server can see, for a USB camera (GET /printers/usb-cameras).
  574. export interface UsbCamera {
  575. device: string;
  576. name: string;
  577. capabilities: string[];
  578. driver?: string;
  579. formats?: string[];
  580. }
  581. export interface PrinterStatus {
  582. id: number;
  583. name: string;
  584. connected: boolean;
  585. state: string | null;
  586. current_print: string | null;
  587. subtask_name: string | null;
  588. current_archive_id: number | null;
  589. current_plate_id: number | null;
  590. gcode_file: string | null;
  591. progress: number | null;
  592. remaining_time: number | null;
  593. layer_num: number | null;
  594. total_layers: number | null;
  595. temperatures: {
  596. bed?: number;
  597. bed_target?: number;
  598. bed_heating?: boolean; // Actual heater state from MQTT
  599. nozzle?: number;
  600. nozzle_target?: number;
  601. nozzle_heating?: boolean; // Actual heater state from MQTT
  602. nozzle_2?: number; // Second nozzle for H2 series (dual nozzle)
  603. nozzle_2_target?: number;
  604. nozzle_2_heating?: boolean; // Actual heater state from MQTT
  605. chamber?: number;
  606. chamber_target?: number;
  607. chamber_heating?: boolean; // Actual heater state from MQTT
  608. } | null;
  609. cover_url: string | null;
  610. hms_errors: HMSError[];
  611. // Live updates send null when no AMS is attached; the REST status sends [].
  612. ams: AMSUnit[] | null;
  613. ams_exists: boolean;
  614. vt_tray: AMSTray[]; // Virtual tray / external spool(s)
  615. store_to_sdcard: boolean; // Store sent files on SD card
  616. timelapse: boolean; // Timelapse recording active
  617. ipcam: boolean; // Live view enabled
  618. wifi_signal: number | null; // WiFi signal strength in dBm
  619. wired_network: boolean; // Ethernet connection detected
  620. door_open: boolean; // Enclosure door open (models with a door sensor: X1/X1C/X1E/X2D/P2S/H2*)
  621. // Indexed by EXTRUDER id: [0] is the right hotend, [1] the left. Measured
  622. // on an H2D with 0.4 left / 0.6 right. Read it through the helpers in
  623. // utils/amsHelpers rather than indexing it directly.
  624. nozzles: NozzleInfo[];
  625. nozzle_rack: NozzleRackSlot[]; // H2C 6-nozzle tool-changer rack
  626. print_options: PrintOptions | null; // AI detection and print options
  627. // Calibration stage tracking
  628. stg_cur: number; // Current stage number (-1 = not calibrating)
  629. stg_cur_name: string | null; // Human-readable current stage name
  630. stg: number[]; // List of stage numbers in calibration sequence
  631. // Air conditioning mode (0=cooling, 1=heating)
  632. airduct_mode: number;
  633. // Print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  634. speed_level: number;
  635. // Chamber light on/off
  636. chamber_light: boolean;
  637. // Active extruder for dual nozzle (0=right, 1=left)
  638. active_extruder: number;
  639. // AMS mapping - which AMS is connected to which nozzle
  640. // Format: [ams_id_for_nozzle0, ams_id_for_nozzle1, ...] where -1 means no AMS
  641. ams_mapping: number[];
  642. // Per-AMS extruder mapping - extracted from each AMS unit's info field
  643. // Format: {ams_id: extruder_id} where extruder 0=right, 1=left
  644. // Note: JSON keys are always strings
  645. ams_extruder_map: Record<string, number>;
  646. // Filament Track Switch accessory — null when not installed. When present,
  647. // AMS slots aren't tied to a specific extruder; the FTS routes any slot to
  648. // either extruder, so per-extruder slot filtering must be skipped.
  649. fila_switch: FilaSwitchState | null;
  650. // Per-AMS FTS inlet binding, {ams_id: 'A' | 'B'}, as set on the printer's
  651. // "Manual AMS Setup" screen. Empty unless a switch is installed. An AMS with
  652. // an entry here reaches BOTH nozzles through the switch, which is why it has
  653. // no ams_extruder_map entry and must not be badged left or right.
  654. ams_switch_inlet: Record<string, FtsInlet>;
  655. // Which AMS slot each hotend is fed from, keyed by extruder id as a string.
  656. // Empty on printers that don't report it (everything but the H2/X2 series).
  657. extruder_slots: Record<string, ExtruderSlot>;
  658. // Currently loaded tray (global tray ID, 255 = no filament loaded, 254 = external spool)
  659. tray_now: number;
  660. // The trays this print has drawn from, in order: [global tray ID, layer of the
  661. // switch]. A tray outside the job's AMS mapping is a backup spool the printer
  662. // switched to (AMS Filament Backup). Reset at the start of each print.
  663. tray_change_log?: [number, number][];
  664. // Runout / filament-replacement guidance (#2587). Populated only while PAUSED.
  665. // Global tray IDs (ams_id*4+slot, 128-135 = AMS-HT, 254 = external), matching
  666. // the same numbering as tray_now so the AMS graphic can highlight them.
  667. // expected_tray = the slot the firmware now expects filament in (null = idle,
  668. // not paused, or unresolvable → "check the printer").
  669. // previous_tray = the slot that ran out (null = unknown).
  670. expected_tray: number | null;
  671. previous_tray: number | null;
  672. // AMS status for filament change tracking (0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration)
  673. ams_status_main: number;
  674. // AMS sub-status for filament change step (when main=1): 4=retraction, 6=load verification, 7=purge
  675. ams_status_sub: number;
  676. // mc_print_sub_stage - filament change step indicator used by OrcaSlicer/BambuStudio
  677. mc_print_sub_stage: number;
  678. // Timestamp of last AMS data update (for RFID refresh detection)
  679. last_ams_update: number;
  680. // Number of printable objects in current print (for skip objects feature)
  681. printable_objects_count: number;
  682. // The next pause the slicer put into the running print (#2984). minutes is
  683. // null while the printer reports no time left yet.
  684. next_pause?: { layer: number; minutes: number | null } | null;
  685. // Fan speeds (0-100 percentage, null if not available for this model)
  686. cooling_fan_speed: number | null; // Part cooling fan
  687. big_fan1_speed: number | null; // Auxiliary fan
  688. big_fan2_speed: number | null; // Chamber/exhaust fan
  689. heatbreak_fan_speed: number | null; // Hotend heatbreak fan
  690. // Left auxiliary part cooling fan (optional P2S/X2D accessory, M106 P10).
  691. // null = not installed / not reported by this model.
  692. left_aux_fan_speed: number | null;
  693. // Chamber exhaust fan present (P2S/X2D External Exhaust Fan kit, airduct part 3).
  694. exhaust_fan_present: boolean;
  695. firmware_version: string | null; // Firmware version from MQTT
  696. // Developer LAN mode: true = enabled, false = disabled, null = unknown
  697. developer_mode: boolean | null;
  698. // AMS Filament Backup ("auto-switch" to a backup spool when one runs out).
  699. // true = ON, false = OFF, null = unknown / unsupported (A1 family).
  700. ams_filament_backup: boolean | null;
  701. // Queue: printer is awaiting user ack that the build plate was cleared after a
  702. // finished/failed print. Persisted across restarts (#961).
  703. awaiting_plate_clear: boolean;
  704. // AMS drying support
  705. supports_drying: boolean;
  706. // The AMS can dry, but only from the printer's own screen (P1 series, #2533).
  707. drying_screen_only?: boolean;
  708. // Active chamber heater (responds to M141). True only for H2C/H2D/H2DPro/H2S/X2D.
  709. supports_chamber_heater?: boolean;
  710. }
  711. export interface PrinterCreate {
  712. name: string;
  713. serial_number: string;
  714. ip_address: string;
  715. access_code: string;
  716. model?: string;
  717. location?: string | null;
  718. auto_archive?: boolean;
  719. // Maintenance Mode flag (#1476). Backend already gates MQTT, queue dispatch,
  720. // scheduler, metrics and the print picker on this; toggling via PATCH
  721. // /printers/{id} disconnects or reconnects MQTT accordingly.
  722. is_active?: boolean;
  723. external_camera_url?: string | null;
  724. external_camera_type?: string | null;
  725. external_camera_enabled?: boolean;
  726. external_camera_snapshot_url?: string | null;
  727. camera_rotation?: number;
  728. camera_light_auto?: boolean;
  729. plate_detection_enabled?: boolean;
  730. plate_detection_roi?: PlateDetectionROI;
  731. wear_cost_per_hour?: number | null;
  732. }
  733. // Plate Detection
  734. export interface PlateDetectionROI {
  735. x: number; // X start % (0.0-1.0)
  736. y: number; // Y start % (0.0-1.0)
  737. w: number; // Width % (0.0-1.0)
  738. h: number; // Height % (0.0-1.0)
  739. }
  740. export interface PlateDetectionResult {
  741. is_empty: boolean;
  742. confidence: number;
  743. difference_percent: number;
  744. message: string;
  745. has_debug_image: boolean;
  746. debug_image_url?: string;
  747. needs_calibration: boolean;
  748. light_warning?: boolean;
  749. reference_count?: number;
  750. max_references?: number;
  751. roi?: PlateDetectionROI;
  752. }
  753. export interface PlateDetectionStatus {
  754. available: boolean;
  755. calibrated: boolean;
  756. reference_count: number;
  757. max_references: number;
  758. message: string;
  759. }
  760. export interface CalibrationResult {
  761. success: boolean;
  762. message: string;
  763. }
  764. export interface PlateReference {
  765. index: number;
  766. label: string;
  767. timestamp: string;
  768. has_image: boolean;
  769. thumbnail_url: string;
  770. }
  771. // Archive types
  772. export interface ArchiveDuplicate {
  773. id: number;
  774. print_name: string | null;
  775. created_at: string;
  776. match_type: 'exact' | 'similar'; // 'exact' = hash match, 'similar' = name match
  777. }
  778. export interface ArchivePrinterMediaFile {
  779. name: string;
  780. path: string;
  781. size: number;
  782. mtime: string | null;
  783. kind: 'timelapse' | 'ipcam';
  784. }
  785. export interface ArchivePrinterMedia {
  786. archive_id: number;
  787. printer_id: number | null;
  788. local_timelapse: { name: string; size: number } | null;
  789. remote_files: ArchivePrinterMediaFile[];
  790. warnings: Array<'printer_missing' | 'timelapse_unavailable' | 'ipcam_unavailable' | 'printer_files_forbidden'>;
  791. }
  792. /** A timelapse editor re-encode, run in the background. */
  793. export interface TimelapseJob {
  794. status: 'running' | 'completed' | 'failed' | 'cancelled';
  795. /** Share done, 0 to 1; null before ffmpeg's first report. */
  796. progress: number | null;
  797. output_path: string | null;
  798. message: string | null;
  799. error: string | null;
  800. }
  801. /** How a post-print outcome verdict reached the archive (#1898). */
  802. export type VerdictSource = 'dialog' | 'link' | 'plate_clear' | 'printer_card' | 'api' | 'reaction';
  803. export interface Archive {
  804. id: number;
  805. printer_id: number | null;
  806. project_id: number | null;
  807. project_name: string | null;
  808. filename: string;
  809. file_path: string;
  810. file_size: number;
  811. content_hash: string | null;
  812. thumbnail_path: string | null;
  813. timelapse_path: string | null;
  814. source_3mf_path: string | null;
  815. f3d_path: string | null;
  816. duplicates: ArchiveDuplicate[] | null;
  817. duplicate_count: number;
  818. duplicate_sequence: number; // 0 = original, 1+ = nth duplicate
  819. original_archive_id: number | null; // ID of the first/original archive
  820. object_count: number | null;
  821. print_name: string | null;
  822. plate_id: number | null; // Selected plate of a multi-plate 3MF (#2603)
  823. print_time_seconds: number | null;
  824. actual_time_seconds: number | null; // Computed from started_at/completed_at
  825. time_accuracy: number | null; // Percentage: 100 = perfect, >100 = faster than estimated
  826. time_estimate_seconds?: number | null; // The latest print's plate estimate, what time_accuracy compares with
  827. filament_used_grams: number | null;
  828. filament_type: string | null;
  829. filament_color: string | null;
  830. layer_height: number | null;
  831. total_layers: number | null;
  832. nozzle_diameter: number | null;
  833. bed_temperature: number | null;
  834. bed_type: string | null; // Build plate type from 3MF (e.g. "Cool Plate", "Textured PEI Plate")
  835. nozzle_temperature: number | null;
  836. sliced_for_model: string | null; // Printer model this file was sliced for
  837. status: string;
  838. started_at: string | null;
  839. completed_at: string | null;
  840. extra_data: Record<string, unknown> | null;
  841. makerworld_url: string | null;
  842. designer: string | null;
  843. external_url: string | null;
  844. is_favorite: boolean;
  845. tags: string | null;
  846. notes: string | null;
  847. cost: number | null;
  848. photos: string[] | null;
  849. failure_reason: string | null;
  850. // Post-print outcome confirmation (#1898)
  851. user_verdict: 'good' | 'reject' | null;
  852. // How the verdict arrived; 'reaction' is written by the Telegram reaction
  853. // handler (#3046) and is labelled here so it reads correctly once that lands.
  854. user_verdict_source: VerdictSource | null;
  855. user_verdict_at: string | null;
  856. confirm_requested: boolean;
  857. // The run whose outcome this shows, when it shows one run of the archive
  858. // (a plate printed on its own) rather than its latest (#1898).
  859. run_id?: number | null;
  860. // The latest print of the archive (among those the caller may see), whose
  861. // figures the per-print fields show (archive redesign).
  862. latest_run_id?: number | null;
  863. quantity: number;
  864. energy_kwh: number | null;
  865. energy_cost: number | null;
  866. wear_cost: number | null; // Printer wear (#694)
  867. created_at: string;
  868. // User tracking (Issue #206)
  869. created_by_id: number | null;
  870. created_by_username: string | null;
  871. // Per-archive run aggregates from PrintLogEntry (#1378)
  872. run_count: number;
  873. last_run_at: string | null;
  874. total_filament_actual_grams: number | null;
  875. successful_run_count: number;
  876. failed_run_count: number;
  877. }
  878. export interface ArchiveSlim {
  879. printer_id: number | null;
  880. print_name: string | null;
  881. print_time_seconds: number | null;
  882. actual_time_seconds: number | null;
  883. filament_used_grams: number | null;
  884. filament_type: string | null;
  885. filament_color: string | null;
  886. status: string;
  887. started_at: string | null;
  888. completed_at: string | null;
  889. cost: number | null;
  890. energy_kwh: number | null;
  891. energy_cost: number | null;
  892. wear_cost: number | null; // Printer wear (#694)
  893. quantity: number;
  894. created_at: string;
  895. }
  896. export interface PrintLogEntry {
  897. id: number;
  898. archive_id: number | null;
  899. print_name: string | null;
  900. plate_id?: number | null;
  901. printer_name: string | null;
  902. printer_id: number | null;
  903. status: string;
  904. started_at: string | null;
  905. completed_at: string | null;
  906. duration_seconds: number | null;
  907. filament_type: string | null;
  908. filament_color: string | null;
  909. filament_used_grams: number | null;
  910. cost: number | null;
  911. energy_kwh: number | null;
  912. energy_cost: number | null;
  913. wear_cost: number | null; // Printer wear (#694)
  914. failure_reason: string | null;
  915. user_verdict?: 'good' | 'reject' | null;
  916. user_verdict_source?: string | null;
  917. confirm_requested?: boolean | null;
  918. duration_unmeasured?: boolean | null;
  919. quantity?: number | null;
  920. // This print's own (archive redesign): note, finish photos, video.
  921. notes?: string | null;
  922. photos?: string[] | null;
  923. timelapse_path?: string | null;
  924. // The slicer's estimate for the plate it printed; in an archive's runs list.
  925. estimate_seconds?: number | null;
  926. estimate_grams?: number | null;
  927. thumbnail_path: string | null;
  928. created_by_id: number | null;
  929. created_by_username: string | null;
  930. created_at: string;
  931. }
  932. export interface PrintLogResponse {
  933. items: PrintLogEntry[];
  934. total: number;
  935. // The print log only: archives of its prints that were deleted.
  936. deleted_archive_ids?: number[];
  937. }
  938. export interface ArchiveStats {
  939. total_prints: number;
  940. successful_prints: number;
  941. failed_prints: number;
  942. cancelled_prints: number;
  943. total_print_time_hours: number;
  944. total_filament_grams: number;
  945. total_cost: number;
  946. prints_by_filament_type: Record<string, number>;
  947. prints_by_printer: Record<string, number>;
  948. // Name each printer id was last recorded under in the print log, so history
  949. // belonging to a deleted printer keeps its label.
  950. printer_names?: Record<string, string>;
  951. average_time_accuracy: number | null;
  952. time_accuracy_by_printer: Record<string, number> | null;
  953. total_energy_kwh: number;
  954. total_energy_cost: number;
  955. total_wear_cost: number; // Printer wear (#694)
  956. // True when a date-filtered total-consumption query is running on incomplete
  957. // snapshot history (e.g. right after upgrade, before hourly snapshots have
  958. // a baseline). UI should explain why the number may undercount.
  959. energy_data_warming_up?: boolean;
  960. }
  961. export interface TagInfo {
  962. name: string;
  963. count: number;
  964. }
  965. export interface FailureAnalysis {
  966. period_days: number;
  967. total_prints: number;
  968. failed_prints: number;
  969. failure_rate: number;
  970. // Quality dimension (#1898): completed prints the user rejected. Optional
  971. // so a frontend build against an older backend degrades gracefully.
  972. rejected_prints?: number;
  973. yield_rate?: number;
  974. rejects_by_reason?: Record<string, number>;
  975. failures_by_reason: Record<string, number>;
  976. failures_by_filament: Record<string, number>;
  977. failures_by_printer: Record<string, number>;
  978. failures_by_hour: Record<number, number>;
  979. recent_failures: Array<{
  980. id: number;
  981. print_name: string;
  982. failure_reason: string | null;
  983. filament_type: string | null;
  984. printer_id: number | null;
  985. created_at: string | null;
  986. }>;
  987. trend: Array<{
  988. week_start: string;
  989. total_prints: number;
  990. failed_prints: number;
  991. failure_rate: number;
  992. }>;
  993. }
  994. /**
  995. * Send the browser's zone with calendar dates: the server reads a date as a
  996. * day in it, else in its own TZ, which shifted every day for a browser away
  997. * from the server (DB-C12). Only when a date is set.
  998. */
  999. function addDayZone(params: URLSearchParams): void {
  1000. if (!params.has('date_from') && !params.has('date_to')) return;
  1001. try {
  1002. const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
  1003. if (zone) params.set('tz', zone);
  1004. } catch {
  1005. // No Intl zone: the server's TZ applies.
  1006. }
  1007. }
  1008. export interface BulkUploadResult {
  1009. uploaded: number;
  1010. failed: number;
  1011. /** `index` is the file's position in the request. */
  1012. results: Array<{ index: number; filename: string; id: number; status: string }>;
  1013. errors: Array<{ index: number; filename: string; error: string }>;
  1014. }
  1015. // Archive Comparison types
  1016. export interface ComparisonArchiveInfo {
  1017. id: number;
  1018. print_name: string;
  1019. status: string;
  1020. created_at: string | null;
  1021. printer_id: number | null;
  1022. project_name: string | null;
  1023. }
  1024. export interface ComparisonField {
  1025. field: string;
  1026. label: string;
  1027. unit: string | null;
  1028. values: (string | number | null)[];
  1029. raw_values: (string | number | null)[];
  1030. has_difference: boolean;
  1031. }
  1032. export interface SuccessCorrelationInsight {
  1033. field: string;
  1034. label: string;
  1035. insight: string;
  1036. success_avg?: number;
  1037. failed_avg?: number;
  1038. success_values?: string[];
  1039. failed_values?: string[];
  1040. }
  1041. export interface SuccessCorrelation {
  1042. has_both_outcomes: boolean;
  1043. message?: string;
  1044. successful_count?: number;
  1045. failed_count?: number;
  1046. insights?: SuccessCorrelationInsight[];
  1047. }
  1048. export interface ArchiveComparison {
  1049. archives: ComparisonArchiveInfo[];
  1050. comparison: ComparisonField[];
  1051. differences: ComparisonField[];
  1052. success_correlation: SuccessCorrelation;
  1053. }
  1054. // Project types
  1055. export interface ProjectStats {
  1056. total_archives: number;
  1057. total_items: number; // Sum of quantities (total items printed)
  1058. completed_prints: number; // Sum of quantities for completed prints (parts)
  1059. failed_prints: number;
  1060. queued_prints: number;
  1061. in_progress_prints: number;
  1062. total_print_time_hours: number;
  1063. total_filament_grams: number;
  1064. progress_percent: number | null; // Plates progress (total_archives / target_count)
  1065. parts_progress_percent: number | null; // Parts progress (completed_prints / target_parts_count)
  1066. estimated_cost: number;
  1067. total_energy_kwh: number;
  1068. total_energy_cost: number;
  1069. total_wear_cost: number; // Printer wear (#694)
  1070. remaining_prints: number | null; // Remaining plates
  1071. remaining_parts: number | null; // Remaining parts
  1072. bom_total_items: number;
  1073. bom_completed_items: number;
  1074. bom_cost: number;
  1075. }
  1076. // A sub-project as listed on its parent's page. The figures cover the child's
  1077. // own subtree, so the listed rows add up to the parent's roll-up minus the
  1078. // parent's own prints (#1264).
  1079. export interface ProjectChildPreview {
  1080. id: number;
  1081. name: string;
  1082. color: string | null;
  1083. status: string;
  1084. progress_percent: number | null;
  1085. descendant_count: number;
  1086. total_archives: number;
  1087. completed_prints: number;
  1088. total_print_time_hours: number;
  1089. total_filament_grams: number;
  1090. total_cost: number; // Filament + energy + BOM, matching the parent's cost card
  1091. }
  1092. export interface Project {
  1093. id: number;
  1094. name: string;
  1095. description: string | null;
  1096. color: string | null;
  1097. status: string; // active, completed, archived
  1098. target_count: number | null; // Target number of plates/print jobs
  1099. target_parts_count: number | null; // Target number of parts/objects
  1100. target_sets: number | null; // Copies-per-file target (#1897)
  1101. notes: string | null;
  1102. attachments: ProjectAttachment[] | null;
  1103. tags: string | null;
  1104. due_date: string | null;
  1105. priority: string; // low, normal, high, urgent
  1106. budget: number | null;
  1107. is_template: boolean;
  1108. template_source_id: number | null;
  1109. parent_id: number | null;
  1110. parent_name: string | null;
  1111. children: ProjectChildPreview[];
  1112. descendant_count: number; // Sub-projects at any depth beneath this one (#1264)
  1113. created_at: string;
  1114. updated_at: string;
  1115. stats?: ProjectStats;
  1116. // This project's numbers combined with every sub-project's. Null when there
  1117. // are none, since it would only repeat `stats` (#1264).
  1118. rollup_stats?: ProjectStats | null;
  1119. url: string | null; // External link rendered next to project name on the card (#1155)
  1120. cover_image_filename: string | null; // Filename within project attachments dir (#1155)
  1121. }
  1122. export interface ProjectAttachment {
  1123. filename: string;
  1124. original_name: string;
  1125. size: number;
  1126. uploaded_at: string;
  1127. }
  1128. // Completed-run count for one library file inside a project (#1897)
  1129. export interface ProjectFileProgress {
  1130. file_id: number;
  1131. completed_count: number;
  1132. }
  1133. export interface ArchivePreview {
  1134. id: number;
  1135. print_name: string | null;
  1136. thumbnail_path: string | null;
  1137. status: string;
  1138. filament_type: string | null;
  1139. filament_color: string | null;
  1140. }
  1141. export interface ProjectListItem {
  1142. id: number;
  1143. name: string;
  1144. description: string | null;
  1145. color: string | null;
  1146. status: string;
  1147. target_count: number | null; // Target number of plates/print jobs
  1148. target_parts_count: number | null; // Target number of parts/objects
  1149. target_sets: number | null; // #1897 — the shared edit dialog seeds itself from this
  1150. budget: number | null;
  1151. tags: string | null; // #2536 — the shared edit dialog seeds itself from this
  1152. due_date: string | null; // #2536
  1153. priority: string; // #2536
  1154. created_at: string;
  1155. archive_count: number; // Number of print jobs (plates)
  1156. total_items: number; // Sum of quantities (total items printed, including failed)
  1157. completed_count: number; // Sum of quantities for completed prints only (parts)
  1158. failed_count: number; // Sum of quantities for failed prints
  1159. queue_count: number;
  1160. progress_percent: number | null; // Plates progress
  1161. parent_id: number | null; // #1264 — set when this is a sub-project
  1162. child_count: number; // #1264 — direct sub-projects only
  1163. archives: ArchivePreview[];
  1164. url: string | null; // #1155
  1165. cover_image_filename: string | null; // #1155
  1166. }
  1167. export interface ProjectCreate {
  1168. name: string;
  1169. description?: string;
  1170. color?: string;
  1171. target_count?: number;
  1172. target_parts_count?: number;
  1173. target_sets?: number;
  1174. notes?: string;
  1175. tags?: string;
  1176. due_date?: string;
  1177. priority?: string;
  1178. budget?: number | null;
  1179. parent_id?: number;
  1180. url?: string | null; // #1155
  1181. }
  1182. export interface ProjectUpdate {
  1183. name?: string;
  1184. description?: string;
  1185. color?: string;
  1186. status?: string;
  1187. target_count?: number;
  1188. target_parts_count?: number;
  1189. target_sets?: number | null; // #1897 — explicit null clears the copies-per-file target
  1190. notes?: string;
  1191. tags?: string | null; // #2536 — explicit null clears the tags
  1192. due_date?: string | null; // #2536 — explicit null clears the due date
  1193. priority?: string;
  1194. budget?: number | null;
  1195. parent_id?: number;
  1196. url?: string | null; // #1155 — explicit null clears the URL
  1197. }
  1198. // BOM Types - Tracks sourced/purchased parts (hardware, electronics, etc.)
  1199. export interface BOMItem {
  1200. id: number;
  1201. project_id: number;
  1202. name: string;
  1203. quantity_needed: number;
  1204. quantity_acquired: number;
  1205. unit_price: number | null;
  1206. sourcing_url: string | null;
  1207. archive_id: number | null;
  1208. archive_name: string | null;
  1209. stl_filename: string | null;
  1210. remarks: string | null;
  1211. sort_order: number;
  1212. is_complete: boolean;
  1213. created_at: string;
  1214. updated_at: string;
  1215. }
  1216. export interface BOMItemCreate {
  1217. name: string;
  1218. quantity_needed?: number;
  1219. unit_price?: number;
  1220. sourcing_url?: string;
  1221. archive_id?: number;
  1222. stl_filename?: string;
  1223. remarks?: string;
  1224. }
  1225. export interface BOMItemUpdate {
  1226. name?: string;
  1227. quantity_needed?: number;
  1228. quantity_acquired?: number;
  1229. unit_price?: number;
  1230. sourcing_url?: string;
  1231. archive_id?: number;
  1232. stl_filename?: string;
  1233. remarks?: string;
  1234. }
  1235. // Project Export/Import Types
  1236. export interface BOMItemExport {
  1237. name: string;
  1238. quantity_needed: number;
  1239. quantity_acquired: number;
  1240. unit_price: number | null;
  1241. sourcing_url: string | null;
  1242. stl_filename: string | null;
  1243. remarks: string | null;
  1244. }
  1245. export interface LinkedFolderExport {
  1246. name: string;
  1247. }
  1248. export interface ProjectExport {
  1249. name: string;
  1250. description: string | null;
  1251. color: string | null;
  1252. status: string;
  1253. target_count: number | null;
  1254. target_parts_count: number | null;
  1255. target_sets: number | null; // #1897
  1256. notes: string | null;
  1257. tags: string | null;
  1258. due_date: string | null;
  1259. priority: string;
  1260. budget: number | null;
  1261. bom_items: BOMItemExport[];
  1262. linked_folders: LinkedFolderExport[];
  1263. }
  1264. export interface ProjectImport {
  1265. name: string;
  1266. description?: string;
  1267. color?: string;
  1268. status?: string;
  1269. target_count?: number;
  1270. target_parts_count?: number;
  1271. target_sets?: number; // #1897
  1272. notes?: string;
  1273. tags?: string;
  1274. due_date?: string;
  1275. priority?: string;
  1276. budget?: number | null;
  1277. bom_items?: BOMItemExport[];
  1278. linked_folders?: LinkedFolderExport[];
  1279. }
  1280. // Timeline Types
  1281. export interface TimelineEvent {
  1282. event_type: string;
  1283. timestamp: string;
  1284. title: string;
  1285. description: string | null;
  1286. metadata: Record<string, unknown> | null;
  1287. }
  1288. // API Key types
  1289. export interface APIKey {
  1290. id: number;
  1291. name: string;
  1292. key_prefix: string;
  1293. user_id: number | null; // Owner; null on legacy keys created before per-user ownership (#1182)
  1294. can_queue: boolean;
  1295. can_control_printer: boolean;
  1296. can_read_status: boolean;
  1297. can_manage_library: boolean;
  1298. can_manage_inventory: boolean;
  1299. can_manage_maintenance: boolean;
  1300. can_manage_archives: boolean;
  1301. can_manage_projects: boolean;
  1302. can_access_cloud: boolean;
  1303. can_update_energy_cost: boolean;
  1304. can_send_notifications: boolean;
  1305. printer_ids: number[] | null;
  1306. enabled: boolean;
  1307. last_used: string | null;
  1308. created_at: string;
  1309. expires_at: string | null;
  1310. }
  1311. export interface APIKeyCreate {
  1312. name: string;
  1313. can_queue?: boolean;
  1314. can_control_printer?: boolean;
  1315. can_read_status?: boolean;
  1316. can_manage_library?: boolean;
  1317. can_manage_inventory?: boolean;
  1318. can_manage_maintenance?: boolean;
  1319. can_manage_archives?: boolean;
  1320. can_manage_projects?: boolean;
  1321. can_access_cloud?: boolean;
  1322. can_update_energy_cost?: boolean;
  1323. can_send_notifications?: boolean;
  1324. printer_ids?: number[] | null;
  1325. expires_at?: string | null;
  1326. }
  1327. export interface APIKeyCreateResponse extends APIKey {
  1328. key: string; // Full key, only shown on creation
  1329. }
  1330. /**
  1331. * Tri-state calibration option (BambuStudio parity): "off" never runs it,
  1332. * "on" forces it every print, "auto" lets the printer skip it if it was done
  1333. * recently. Used by bed_levelling, flow_cali, and nozzle_offset_cali.
  1334. */
  1335. export type CalibrationMode = 'off' | 'on' | 'auto';
  1336. // Settings types
  1337. export interface AppSettings {
  1338. auto_archive: boolean;
  1339. save_thumbnails: boolean;
  1340. capture_finish_photo: boolean;
  1341. finish_photo_restore_plate: boolean;
  1342. default_filament_cost: number;
  1343. currency: string;
  1344. energy_cost_per_kwh: number;
  1345. energy_tracking_mode: 'print' | 'total';
  1346. // Where the electricity price comes from (#1251). With 'homeassistant',
  1347. // energy_cost_per_kwh holds the sensor's last reading and is read-only.
  1348. energy_price_source: 'fixed' | 'homeassistant';
  1349. energy_price_ha_entity: string;
  1350. check_updates: boolean;
  1351. check_printer_firmware: boolean;
  1352. include_beta_updates: boolean;
  1353. // Announcements from the Bambuddy maintainers (a signed file on GitHub).
  1354. announcements_enabled?: boolean;
  1355. announcements_all_users?: boolean;
  1356. // #1589: false hides the local username/password form on the login page;
  1357. // BAMBUDDY_LOCAL_LOGIN=true on the server flips the reported value back to
  1358. // true so the env-var recovery path is visible to the SPA.
  1359. local_login_enabled: boolean;
  1360. language: string;
  1361. notification_language: string;
  1362. // AMS threshold settings
  1363. ams_humidity_good: number; // <= this is green
  1364. ams_humidity_fair: number; // <= this is orange, > is red
  1365. ams_temp_good: number; // <= this is green/blue
  1366. ams_temp_fair: number; // <= this is orange, > is red
  1367. // Separate from the display band (#2905). null = unset, which the backend
  1368. // resolves to ams_temp_fair so existing installs are unaffected.
  1369. ams_temp_alarm: number | null;
  1370. ams_history_retention_days: number; // days to keep AMS sensor history
  1371. printer_sensor_history_retention_days?: number; // days to keep printer heater history
  1372. // Queue auto-drying settings
  1373. queue_drying_enabled: boolean; // Auto-dry AMS between queued prints
  1374. queue_drying_block: boolean; // Block queue until drying completes
  1375. ambient_drying_enabled: boolean; // Auto-dry idle printers based on humidity regardless of queue
  1376. ambient_drying_sustained_minutes: number; // Minutes humidity must stay above threshold before ambient auto-dry starts (0 = instant)
  1377. print_drying_enabled: boolean; // Continue drying while a print is running on capable hardware
  1378. drying_presets: string; // JSON blob of drying presets per filament type
  1379. ams_humidity_thresholds: string; // JSON blob of per-filament humidity thresholds (#1605)
  1380. gcode_snippets: string; // JSON: per-model G-code injection snippets
  1381. // Scheduled local backup
  1382. local_backup_enabled: boolean;
  1383. local_backup_schedule: string;
  1384. local_backup_time: string;
  1385. local_backup_retention: number;
  1386. local_backup_path: string;
  1387. // Print modal settings
  1388. per_printer_mapping_expanded: boolean; // Whether custom mapping is expanded by default in print modal
  1389. // Date/time format settings
  1390. date_format: 'system' | 'us' | 'eu' | 'iso';
  1391. time_format: 'system' | '12h' | '24h';
  1392. // Filament tracking
  1393. disable_filament_warnings: boolean; // Disable filament warnings (print insufficiency and assignment mismatch)
  1394. prefer_lowest_filament: boolean; // When multiple spools match, prefer lowest remaining filament
  1395. 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
  1396. 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
  1397. spoolman_url: string;
  1398. // Default printer
  1399. default_printer_id: number | null;
  1400. pipeline_max_copies: number;
  1401. // Dark mode theme settings
  1402. dark_style: 'classic' | 'glow' | 'vibrant';
  1403. dark_background: 'neutral' | 'warm' | 'cool' | 'oled' | 'slate' | 'forest';
  1404. dark_accent: 'green' | 'teal' | 'blue' | 'orange' | 'purple' | 'red';
  1405. // Light mode theme settings
  1406. light_style: 'classic' | 'glow' | 'vibrant';
  1407. light_background: 'neutral' | 'warm' | 'cool';
  1408. light_accent: 'green' | 'teal' | 'blue' | 'orange' | 'purple' | 'red';
  1409. // FTP retry settings
  1410. ftp_retry_enabled: boolean;
  1411. ftp_retry_count: number;
  1412. ftp_retry_delay: number;
  1413. ftp_timeout: number;
  1414. // MQTT relay settings
  1415. mqtt_enabled: boolean;
  1416. mqtt_broker: string;
  1417. mqtt_port: number;
  1418. mqtt_username: string;
  1419. mqtt_password: string;
  1420. mqtt_topic_prefix: string;
  1421. mqtt_use_tls: boolean;
  1422. // External URL for notifications
  1423. external_url: string;
  1424. // Directory holding docker-compose.yml, shown in the update instructions (#2664)
  1425. docker_compose_dir: string;
  1426. // Home Assistant integration
  1427. ha_enabled: boolean;
  1428. ha_url: string;
  1429. ha_token: string;
  1430. ha_url_from_env: boolean;
  1431. ha_token_from_env: boolean;
  1432. ha_env_managed: boolean;
  1433. // File Manager / Library settings
  1434. library_disk_warning_gb: number;
  1435. // Camera view settings
  1436. camera_view_mode: 'window' | 'embedded';
  1437. // Chamber light while the camera is in use (#1655)
  1438. camera_light_mode: 'off' | 'all' | 'selected';
  1439. camera_light_delay: number; // seconds a snapshot waits after the light came on
  1440. // Preferred slicer (server-side API / sidecar)
  1441. preferred_slicer: 'bambu_studio' | 'orcaslicer';
  1442. // Desktop "Open in Slicer" override (#1329). Null inherits from
  1443. // preferred_slicer so existing installs behave identically.
  1444. open_in_slicer: 'bambu_studio' | 'orcaslicer' | null;
  1445. // Where slicing runs, independent of which slicer binary the sidecar drives.
  1446. // Only 'sidecar' is implemented today; see lib/sliceEngines.ts.
  1447. slice_engine: 'sidecar' | 'browser';
  1448. // Use the slicer-API sidecar for slicing (in-app modal) vs desktop URI scheme
  1449. use_slicer_api: boolean;
  1450. // Per-install sidecar URLs. Empty string falls back to the env defaults.
  1451. orcaslicer_api_url: string;
  1452. bambu_studio_api_url: string;
  1453. // Minutes of silence from the sidecar before a slice is abandoned. Bounds
  1454. // stalls, not total slicing time — a model that keeps reporting progress
  1455. // runs to completion however long it takes.
  1456. slicer_stall_timeout_minutes: number;
  1457. // Prometheus metrics
  1458. prometheus_enabled: boolean;
  1459. prometheus_token: string;
  1460. // Bed cooled threshold
  1461. bed_cooled_threshold: number;
  1462. // Minutes before a slicer pause to send the pause heads-up (#2984)
  1463. pause_warning_minutes: number;
  1464. // Inventory low stock threshold
  1465. low_stock_threshold: number;
  1466. // Session policy (#1706) — admin-set ceiling, hours, [1, 720]
  1467. session_max_hours: number;
  1468. // User email notifications toggle
  1469. user_notifications_enabled: boolean;
  1470. // Default print options
  1471. default_bed_levelling: CalibrationMode;
  1472. default_flow_cali: CalibrationMode;
  1473. default_vibration_cali: boolean;
  1474. default_layer_inspect: boolean;
  1475. default_timelapse: boolean;
  1476. default_nozzle_offset_cali: CalibrationMode;
  1477. // Default for the per-job "ask for outcome afterwards" toggle (#1898)
  1478. default_confirm_outcome: boolean;
  1479. // Also ask for prints Bambuddy archived but did not dispatch (#1898)
  1480. confirm_outcome_external_prints: boolean;
  1481. // Count unanswered outcome prompts as "good" when the plate is released (#1898)
  1482. confirm_default_good_on_plate_clear: boolean;
  1483. // Staggered batch start defaults
  1484. stagger_group_size: number;
  1485. stagger_interval_minutes: number;
  1486. // Finance budget reset window
  1487. billing_enabled: boolean;
  1488. printer_kill_switch_enabled: boolean;
  1489. finance_budget_reset_day: number;
  1490. finance_budget_reset_timezone: string;
  1491. // Plate-clear confirmation
  1492. require_plate_clear: boolean;
  1493. // Shortest job first scheduling
  1494. queue_shortest_first: boolean;
  1495. // How many printers the queue may upload to at once (#2555). 1 restores the
  1496. // old strictly-serial behaviour, where every printer waited out every other
  1497. // printer's transfer.
  1498. queue_max_concurrent_uploads: number;
  1499. // Preheat / heat-soak before queued prints (#1468). Master toggle is the
  1500. // default for new queue items; per-item PrintQueueItem.preheat_override can
  1501. // flip the decision per print. Chamber target derives from the loaded AMS
  1502. // filament types via preheat_filament_targets (JSON map of type → °C, max
  1503. // across loaded slots); the per-item override field bypasses derivation.
  1504. preheat_enabled: boolean;
  1505. preheat_filament_targets: string;
  1506. preheat_max_wait_seconds: number;
  1507. preheat_soak_seconds: number;
  1508. queue_keep_bed_warm: boolean;
  1509. queue_keep_warm_bed_temp: number;
  1510. queue_keep_warm_max_minutes: number;
  1511. // User-configurable presets for the printer-card popovers (JSON arrays of 3 ints).
  1512. // Empty string = use built-in defaults.
  1513. nozzle_temp_presets: string;
  1514. bed_temp_presets: string;
  1515. chamber_temp_presets: string;
  1516. fan_speed_presets: string;
  1517. // Default sidebar order (admin-set for all users)
  1518. default_sidebar_order: string;
  1519. // LDAP authentication
  1520. ldap_enabled: boolean;
  1521. ldap_server_url: string;
  1522. ldap_bind_dn: string;
  1523. ldap_bind_password: string;
  1524. ldap_search_base: string;
  1525. ldap_user_filter: string;
  1526. ldap_security: string;
  1527. ldap_group_mapping: string;
  1528. ldap_auto_provision: boolean;
  1529. ldap_default_group: string;
  1530. obico_enabled: boolean;
  1531. obico_ml_url: string;
  1532. bambuddy_internal_url: string;
  1533. obico_ml_token: string;
  1534. obico_sensitivity: 'low' | 'medium' | 'high';
  1535. obico_action: 'notify' | 'pause' | 'pause_and_off';
  1536. obico_poll_interval: number;
  1537. obico_enabled_printers: string;
  1538. octoeverywhere_enabled: boolean;
  1539. octoeverywhere_api_key: string;
  1540. octoeverywhere_api_key_configured: boolean;
  1541. octoeverywhere_confidence: OctoEverywhereConfidence;
  1542. octoeverywhere_action: 'notify' | 'pause' | 'pause_and_off';
  1543. octoeverywhere_enabled_printers: string;
  1544. octoeverywhere_poll_interval: number;
  1545. // Inventory forecasting global lead time
  1546. forecast_global_lead_time_days: number;
  1547. location_sensor_poll_interval: number;
  1548. // JSON map of sensor category → {alertAbove, alertBelow, notifyOnAlert},
  1549. // seeding new storage-location sensor bindings. Empty = built-in defaults.
  1550. // Server-backed so two admins seed the same alert rules and a restore
  1551. // brings them back; see utils/locationSensorDefaults.ts.
  1552. location_sensor_alert_defaults: string;
  1553. }
  1554. export type AppSettingsUpdate = Partial<Omit<AppSettings, 'octoeverywhere_api_key_configured'>>;
  1555. // Settings as a page sees them: everything from GET /settings for a user who
  1556. // may read it, otherwise the subset /settings/ui-preferences and
  1557. // /settings/ui-flags serve, which reports G-code snippets only as set or not.
  1558. export type UiSettings = Partial<AppSettings> & { has_gcode_snippets?: boolean };
  1559. // MQTT relay status
  1560. export interface MQTTStatus {
  1561. enabled: boolean;
  1562. connected: boolean;
  1563. broker: string;
  1564. port: number;
  1565. topic_prefix: string;
  1566. }
  1567. // Cloud types
  1568. export interface CloudAuthStatus {
  1569. is_authenticated: boolean;
  1570. email: string | null;
  1571. region?: 'global' | 'china' | null;
  1572. /** A token is stored but Bambu no longer accepts it — tell the user why the login form is back. */
  1573. sign_in_expired?: boolean;
  1574. }
  1575. export interface CloudLoginResponse {
  1576. success: boolean;
  1577. needs_verification: boolean;
  1578. message: string;
  1579. verification_type?: 'email' | 'totp' | null;
  1580. tfa_key?: string | null;
  1581. /**
  1582. * Machine-readable cause of a failure. 'captcha' means Bambu's anti-abuse
  1583. * layer is challenging this network and no credential will be accepted until
  1584. * it clears — the UI must explain that in place rather than toast `message`.
  1585. */
  1586. reason?: 'captcha' | string | null;
  1587. }
  1588. // Orca Cloud types — paste-flow PKCE handshake against auth.orcaslicer.com.
  1589. // See backend/app/services/orca_cloud.py for the deep dive on why this
  1590. // flow is paste-based rather than callback-based.
  1591. export interface OrcaDeviceStartResponse {
  1592. user_code: string;
  1593. verification_uri: string;
  1594. verification_uri_complete: string;
  1595. interval: number;
  1596. expires_in: number;
  1597. }
  1598. export type OrcaDevicePollStatus =
  1599. | 'authorization_pending'
  1600. | 'slow_down'
  1601. | 'access_denied'
  1602. | 'expired_token'
  1603. | 'complete';
  1604. export interface OrcaDevicePollResponse {
  1605. status: OrcaDevicePollStatus;
  1606. connected: boolean;
  1607. email: string | null;
  1608. user_id: string | null;
  1609. }
  1610. export interface OrcaAuthStatusResponse {
  1611. connected: boolean;
  1612. email: string | null;
  1613. user_id: string | null;
  1614. }
  1615. // Orca profiles are shaped to match Bambu Cloud's SlicerSetting on the wire
  1616. // so the frontend can use the same visual components for both surfaces (cards,
  1617. // grouped sections, filter bar). Backend handles the source-specific
  1618. // transformation in routes/orca_cloud.py::_orca_to_setting.
  1619. export interface OrcaProfileMeta {
  1620. setting_id: string;
  1621. name: string;
  1622. type: string;
  1623. version: string | null;
  1624. user_id: string | null;
  1625. updated_time: string | null;
  1626. is_custom: boolean;
  1627. }
  1628. export interface OrcaProfileListResponse {
  1629. filament: OrcaProfileMeta[];
  1630. printer: OrcaProfileMeta[];
  1631. process: OrcaProfileMeta[];
  1632. }
  1633. export interface OrcaProfileDetail {
  1634. setting_id: string;
  1635. name: string;
  1636. type: string;
  1637. version: string | null;
  1638. base_id: string | null;
  1639. update_time: string | null;
  1640. setting: Record<string, unknown>;
  1641. }
  1642. // MakerWorld integration. Full metadata/instance shapes come back as
  1643. // Record<string, unknown> — MakerWorld's API adds fields over time, so we
  1644. // pass them through verbatim rather than maintaining a brittle mirror.
  1645. export interface MakerworldStatus {
  1646. has_cloud_token: boolean;
  1647. can_download: boolean;
  1648. /** A token is stored but Bambu rejected it — downloads will fail until the user signs in again. */
  1649. sign_in_expired?: boolean;
  1650. }
  1651. export interface MakerworldResolvedModel {
  1652. model_id: number;
  1653. profile_id: number | null;
  1654. design: Record<string, unknown>;
  1655. instances: Array<Record<string, unknown>>;
  1656. already_imported_library_ids: number[];
  1657. }
  1658. export interface MakerworldImportResponse {
  1659. library_file_id: number;
  1660. filename: string;
  1661. folder_id: number | null;
  1662. profile_id: number | null;
  1663. was_existing: boolean;
  1664. }
  1665. export interface MakerworldRecentImport {
  1666. library_file_id: number;
  1667. filename: string;
  1668. folder_id: number | null;
  1669. thumbnail_path: string | null;
  1670. source_url: string | null;
  1671. created_at: string;
  1672. }
  1673. // Manyfold integration (#1471): a self-hosted model library, browsed and
  1674. // searched, with single files imported into the library.
  1675. export interface ManyfoldConfig {
  1676. url: string;
  1677. client_id: string;
  1678. /** The secret itself is never returned. */
  1679. has_client_secret: boolean;
  1680. configured: boolean;
  1681. }
  1682. export interface ManyfoldConfigInput {
  1683. url: string;
  1684. client_id: string;
  1685. /** Empty or left out keeps the stored secret. */
  1686. client_secret?: string;
  1687. }
  1688. export interface ManyfoldStatus {
  1689. configured: boolean;
  1690. url: string;
  1691. }
  1692. export interface ManyfoldModelSummary {
  1693. id: string;
  1694. name: string;
  1695. }
  1696. export interface ManyfoldModelList {
  1697. total: number;
  1698. page: number;
  1699. has_next: boolean;
  1700. has_previous: boolean;
  1701. models: ManyfoldModelSummary[];
  1702. }
  1703. export interface ManyfoldFile {
  1704. id: string;
  1705. name: string;
  1706. mime: string;
  1707. importable: boolean;
  1708. /** Set while the file imported earlier is still in the library. */
  1709. library_file: { id: number; filename: string; folder_id: number | null } | null;
  1710. }
  1711. export interface ManyfoldModel {
  1712. id: string;
  1713. name: string;
  1714. caption: string | null;
  1715. description: string | null;
  1716. license: string | null;
  1717. tags: string[];
  1718. url: string;
  1719. has_preview: boolean;
  1720. files: ManyfoldFile[];
  1721. }
  1722. export interface ManyfoldImportResponse {
  1723. library_file_id: number;
  1724. filename: string;
  1725. folder_id: number | null;
  1726. was_existing: boolean;
  1727. }
  1728. export interface SlicerSetting {
  1729. setting_id: string;
  1730. name: string;
  1731. type: string;
  1732. version: string | null;
  1733. user_id: string | null;
  1734. updated_time: string | null;
  1735. is_custom: boolean;
  1736. // The id Bambu Studio puts in an AMS slot for the preset; not derivable
  1737. // from setting_id for every preset (#3387). Absent from older backends.
  1738. filament_id?: string | null;
  1739. }
  1740. export interface SpoolCatalogEntry {
  1741. id: number;
  1742. name: string;
  1743. weight: number;
  1744. is_default: boolean;
  1745. }
  1746. export interface StorageLocation {
  1747. id: number;
  1748. name: string;
  1749. identifier: string | null;
  1750. spool_count: number;
  1751. created_at: string;
  1752. updated_at: string;
  1753. }
  1754. export interface ColorCatalogEntry {
  1755. id: number;
  1756. manufacturer: string;
  1757. color_name: string;
  1758. hex_color: string;
  1759. material: string | null;
  1760. is_default: boolean;
  1761. // #1154: optional multi-colour gradient stops + visual effect.
  1762. extra_colors?: string | null;
  1763. effect_type?: string | null;
  1764. }
  1765. export interface SlicerSettingsResponse {
  1766. filament: SlicerSetting[];
  1767. printer: SlicerSetting[];
  1768. process: SlicerSetting[];
  1769. }
  1770. export interface SlicerSettingDetail {
  1771. message?: string | null;
  1772. code?: string | null;
  1773. error?: string | null;
  1774. public: boolean;
  1775. version?: string | null;
  1776. type: string;
  1777. name: string;
  1778. update_time?: string | null;
  1779. nickname?: string | null;
  1780. base_id?: string | null;
  1781. setting: Record<string, unknown>;
  1782. filament_id?: string | null;
  1783. setting_id?: string | null;
  1784. }
  1785. export interface SlicerSettingCreate {
  1786. type: string; // 'filament', 'print', or 'printer'
  1787. name: string;
  1788. base_id: string;
  1789. setting: Record<string, unknown>;
  1790. }
  1791. export interface SlicerSettingUpdate {
  1792. name?: string;
  1793. setting?: Record<string, unknown>;
  1794. }
  1795. export interface SlicerSettingDeleteResponse {
  1796. success: boolean;
  1797. message: string;
  1798. }
  1799. // Built-in filament fallback (static table from backend)
  1800. export interface BuiltinFilament {
  1801. filament_id: string;
  1802. name: string;
  1803. }
  1804. // Slice request/response — POST /library/files/{id}/slice and /archives/{id}/slice
  1805. //
  1806. // Two preset shapes are accepted per slot:
  1807. // - Legacy bare integer ids (`*_preset_id`) — pre-cloud-tier clients.
  1808. // - Source-aware refs (`*_preset: PresetRef`) — new SliceModal that picks
  1809. // across cloud / local / standard tiers. Source-aware refs win when both
  1810. // are present in the same payload.
  1811. export type PresetSource = 'orca_cloud' | 'cloud' | 'local' | 'standard';
  1812. export interface PresetRef {
  1813. source: PresetSource;
  1814. id: string;
  1815. }
  1816. /**
  1817. * Why a preset's effective values are unavailable.
  1818. *
  1819. * `sidecar_outdated` is the one that matters in practice: an install pulls its
  1820. * sidecar as `SIDECAR_TAG:-latest` regardless of which Bambuddy channel it is
  1821. * on, so a user can perfectly well be running a current Bambuddy against a
  1822. * sidecar that predates this endpoint. That has a one-line fix, and saying so
  1823. * beats a generic "could not read the values".
  1824. */
  1825. export type SlicerPresetValuesReason =
  1826. | 'ok'
  1827. | 'sidecar_outdated'
  1828. | 'sidecar_unavailable'
  1829. | 'not_configured'
  1830. | 'preset_unresolved';
  1831. export interface SlicerPresetValues {
  1832. /** False when the sidecar could not supply values; `values` is then empty. */
  1833. resolved: boolean;
  1834. /** Flattened key -> value map, in the string forms a process preset stores. */
  1835. values: Record<string, string | string[]>;
  1836. reason: SlicerPresetValuesReason;
  1837. }
  1838. export interface SliceRequest {
  1839. printer_preset_id?: number;
  1840. process_preset_id?: number;
  1841. filament_preset_id?: number;
  1842. printer_preset?: PresetRef;
  1843. process_preset?: PresetRef;
  1844. filament_preset?: PresetRef;
  1845. // Multi-color: one PresetRef per plate slot, in plate order. Always
  1846. // preferred over the singular `filament_preset` when both are sent; the
  1847. // backend validator promotes a singular into a one-element list when this
  1848. // is omitted, so legacy single-color clients keep working unchanged.
  1849. filament_presets?: PresetRef[];
  1850. // Per-slot filament colour as `#RRGGBB` / `#RRGGBBAA`, same plate order as
  1851. // `filament_presets` (#2977). Neither slicer stores a colour on a filament
  1852. // *preset* -- it is a per-project property -- so without this every sliced
  1853. // file records the CLI's built-in #00AE42 and the print dialog reports a
  1854. // colour mismatch against whatever is loaded in the AMS. An empty string in
  1855. // any position hands that slot back to the backend's fallback chain (the
  1856. // preset's own default_filament_colour, then the source plate's colour).
  1857. filament_colours?: string[];
  1858. plate?: number;
  1859. export_3mf?: boolean;
  1860. // Build-plate override (#1337). When omitted, the slicer uses the process
  1861. // preset's curr_bed_type as-is. A name from BambuStudio / OrcaSlicer's
  1862. // enum: "Cool Plate", "Engineering Plate", "High Temp Plate" (Smooth PEI),
  1863. // "Textured PEI Plate", "Supertack Plate", or OrcaSlicer's "Textured Cool
  1864. // Plate" (refused when Bambu Studio slices); the backend refuses others (#3359).
  1865. bed_type?: string | null;
  1866. // "Slice as designed" (#2611). 3MF only: slice using the file's embedded
  1867. // project_settings.config (the designer's own wall count, infill, etc.)
  1868. // instead of the picked profile triplet. The preset refs above are still
  1869. // required by the backend validator but go unused on this path.
  1870. use_embedded_settings?: boolean;
  1871. // Process settings the user edited in the slice modal's settings panel,
  1872. // already serialised into the string forms a process preset stores ("1" for
  1873. // a bool, "20%" for a percent, a list for the per-extruder vectors). Patched
  1874. // onto the resolved process JSON after the designer's carried tweaks, so an
  1875. // explicit choice here wins. Omitted when the panel is untouched.
  1876. process_overrides?: Record<string, string | string[]>;
  1877. // Design settings carried from the source 3MF (#2622) — a list of keys the
  1878. // file flags as changed from the system preset, not values.
  1879. design_overrides?: string[];
  1880. // Layout passes the slicer runs before slicing (#2548), both off by
  1881. // default because they move or rotate the objects the user laid out.
  1882. // Unlike the fields above these are CLI actions rather than profile
  1883. // values, so they apply on the embedded-settings path too.
  1884. auto_orient?: boolean;
  1885. auto_arrange?: boolean;
  1886. }
  1887. // GET /api/v1/slicer/presets — unified listing across cloud / local / standard.
  1888. export type SlicerCloudStatus = 'ok' | 'not_authenticated' | 'expired' | 'unreachable';
  1889. export interface UnifiedPreset {
  1890. id: string;
  1891. name: string;
  1892. source: PresetSource;
  1893. // Populated for the filament slot only — used by the SliceModal multi-color
  1894. // pre-pick to score presets against each plate slot's required (type,
  1895. // colour). Optional because the bundled / standard tier rarely carries a
  1896. // colour (colour is a runtime spool attribute on Bambu) and older API
  1897. // responses pre-date these fields entirely.
  1898. filament_type?: string | null;
  1899. filament_colour?: string | null;
  1900. // Printer-preset names a process / filament preset declares itself
  1901. // compatible with. Populated for the local tier (the slicer's own
  1902. // `compatible_printers`); null for cloud / standard. The SliceModal filters
  1903. // the process / filament dropdowns by the selected printer using this when
  1904. // present (#1325).
  1905. compatible_printers?: string[] | null;
  1906. // Printer presets only: the preset it was saved from, for the local and
  1907. // OrcaSlicer Cloud tiers (#3250).
  1908. inherits?: string | null;
  1909. }
  1910. export interface UnifiedPresetsBySlot {
  1911. printer: UnifiedPreset[];
  1912. process: UnifiedPreset[];
  1913. filament: UnifiedPreset[];
  1914. }
  1915. // What is loaded in each connected printer, for the SliceModal's
  1916. // "only connected printers" / "only loaded spools" filters (#3172).
  1917. export interface LoadedSpoolPreset {
  1918. preset_id: string;
  1919. preset_name: string;
  1920. preset_source: string;
  1921. tray_info_idx?: string | null;
  1922. }
  1923. export interface LoadedSpoolTray {
  1924. ams_id: number;
  1925. tray_id: number;
  1926. tray_type: string | null;
  1927. tray_sub_brands: string | null;
  1928. tray_color: string | null;
  1929. tray_info_idx: string | null;
  1930. exists: boolean | null;
  1931. state: number | null;
  1932. saved_preset: LoadedSpoolPreset | null;
  1933. }
  1934. export interface LoadedSpoolUnit {
  1935. id: number;
  1936. is_ams_ht: boolean;
  1937. trays: LoadedSpoolTray[];
  1938. }
  1939. export interface LoadedSpoolPrinter {
  1940. id: number;
  1941. name: string;
  1942. model: string | null;
  1943. ams: LoadedSpoolUnit[];
  1944. // Holders with a spool in them; external_holders counts all of them (two
  1945. // on a dual-nozzle printer, labelled left and right).
  1946. external: LoadedSpoolTray[];
  1947. external_holders: number;
  1948. }
  1949. export interface LoadedSpoolsResponse {
  1950. printers: LoadedSpoolPrinter[];
  1951. }
  1952. export interface UnifiedPresetsResponse {
  1953. // Priority order: local > orca_cloud > cloud > standard. No cross-tier
  1954. // dedup (apart from stock_aliases below) — every tier surfaces its full
  1955. // list so the user can pick from any source. The order drives auto-pick + visual group rendering only.
  1956. orca_cloud: UnifiedPresetsBySlot;
  1957. cloud: UnifiedPresetsBySlot;
  1958. local: UnifiedPresetsBySlot;
  1959. standard: UnifiedPresetsBySlot;
  1960. cloud_status: SlicerCloudStatus;
  1961. orca_cloud_status: SlicerCloudStatus;
  1962. // Standard presets that Bambu Cloud's stock list also has are left out of
  1963. // the standard tier (#3386); each "standard:<id>" maps to its cloud twin.
  1964. stock_aliases?: Record<string, PresetRef>;
  1965. }
  1966. // Slicer Pipelines (#1425) — named bundles of preset slots the SliceModal
  1967. // can apply in one click. PR A surfaces only the bundle; target_* and
  1968. // fanout_strategy round-trip from the backend but the UI doesn't yet expose
  1969. // them (they come alive in PR B / PR C).
  1970. export interface SlicerPipeline {
  1971. id: number;
  1972. name: string;
  1973. description: string | null;
  1974. printer_preset: PresetRef;
  1975. process_preset: PresetRef;
  1976. filament_presets: PresetRef[];
  1977. bed_type: string | null;
  1978. target_kind: 'specific_printer' | 'printer_class';
  1979. target_printer_id: number | null;
  1980. target_model_class: string | null;
  1981. fanout_strategy: 'max_parallel' | 'fill_one_first' | 'round_robin';
  1982. created_by: number | null;
  1983. created_at: string;
  1984. updated_at: string;
  1985. }
  1986. export interface SlicerPipelineCreateRequest {
  1987. name: string;
  1988. description?: string | null;
  1989. printer_preset: PresetRef;
  1990. process_preset: PresetRef;
  1991. filament_presets: PresetRef[];
  1992. bed_type?: string | null;
  1993. }
  1994. export type SlicerPipelineUpdateRequest = Partial<SlicerPipelineCreateRequest> & {
  1995. target_kind?: 'specific_printer' | 'printer_class';
  1996. // ``target_printer_id: 0`` means "clear the target" — the backend maps that
  1997. // to null. Use null in TypeScript for the same intent.
  1998. target_printer_id?: number | null;
  1999. target_model_class?: string | null;
  2000. fanout_strategy?: 'max_parallel' | 'fill_one_first' | 'round_robin';
  2001. };
  2002. export interface SlicerPipelinesListResponse {
  2003. pipelines: SlicerPipeline[];
  2004. }
  2005. // Slicer Pipeline runs (#1425 PR B + PR C)
  2006. export type PipelineEligibilityKind =
  2007. | 'printer_not_set'
  2008. | 'printer_not_found'
  2009. | 'printer_disabled'
  2010. | 'printer_offline'
  2011. | 'filament_type_mismatch'
  2012. | 'filament_color_mismatch'
  2013. | 'ams_slot_missing'
  2014. | 'filament_unverified'
  2015. | 'no_class_matches'
  2016. | 'class_not_set';
  2017. export interface PipelineEligibilityIssue {
  2018. kind: PipelineEligibilityKind;
  2019. slot_index: number | null;
  2020. expected: string | null;
  2021. actual: string | null;
  2022. }
  2023. export interface PipelinePerPrinterReport {
  2024. printer_id: number;
  2025. printer_name: string;
  2026. ok: boolean;
  2027. issues: PipelineEligibilityIssue[];
  2028. }
  2029. export interface PipelineEligibilityReport {
  2030. ok: boolean;
  2031. target_kind: 'specific_printer' | 'printer_class';
  2032. target_printer_id: number | null;
  2033. target_printer_name: string | null;
  2034. target_model_class: string | null;
  2035. issues: PipelineEligibilityIssue[];
  2036. printer_reports: PipelinePerPrinterReport[];
  2037. }
  2038. export interface PipelineJob {
  2039. id: number;
  2040. pipeline_run_id: number;
  2041. copy_index: number;
  2042. assigned_printer_id: number | null;
  2043. assigned_printer_name: string | null;
  2044. queue_entry_id: number | null;
  2045. status:
  2046. | 'pending'
  2047. | 'awaiting_printer'
  2048. | 'queued'
  2049. | 'printing'
  2050. | 'completed'
  2051. | 'failed'
  2052. | 'cancelled'
  2053. | 'unknown';
  2054. error_message: string | null;
  2055. dispatched_at: string | null;
  2056. completed_at: string | null;
  2057. }
  2058. export interface PipelineRun {
  2059. id: number;
  2060. pipeline_id: number | null;
  2061. pipeline_name: string | null;
  2062. source_library_file_id: number | null;
  2063. source_archive_id: number | null;
  2064. source_filename: string | null;
  2065. parent_run_id: number | null;
  2066. copies: number;
  2067. copies_completed: number;
  2068. copies_failed: number;
  2069. copies_cancelled: number;
  2070. copies_in_progress: number;
  2071. status:
  2072. | 'queued'
  2073. | 'slicing'
  2074. | 'dispatching'
  2075. | 'in_progress'
  2076. | 'completed'
  2077. | 'failed'
  2078. | 'partial_failure'
  2079. | 'cancelled';
  2080. slice_job_id: number | null;
  2081. sliced_library_file_id: number | null;
  2082. eligibility_overridden: boolean;
  2083. error_message: string | null;
  2084. created_by: number | null;
  2085. created_at: string;
  2086. started_at: string | null;
  2087. completed_at: string | null;
  2088. jobs: PipelineJob[];
  2089. target_kind: 'specific_printer' | 'printer_class' | null;
  2090. target_printer_id: number | null;
  2091. target_model_class: string | null;
  2092. fanout_strategy: 'max_parallel' | 'fill_one_first' | 'round_robin' | null;
  2093. }
  2094. export interface PipelineRunListResponse {
  2095. runs: PipelineRun[];
  2096. total: number;
  2097. }
  2098. export interface SliceResponse {
  2099. library_file_id: number;
  2100. name: string;
  2101. print_time_seconds: number;
  2102. filament_used_g: number;
  2103. filament_used_mm: number;
  2104. used_embedded_settings: boolean;
  2105. /** Why the result could not be written to the external folder the source
  2106. * lives in, and so went to managed storage instead. Null on every normal
  2107. * slice. Surfaced to the user — a file filed somewhere they aren't looking
  2108. * with no signal is what made #2810 invisible from the UI. */
  2109. external_write_fallback?: string | null;
  2110. }
  2111. export interface SliceArchiveResponse {
  2112. archive_id: number;
  2113. name: string;
  2114. print_time_seconds: number;
  2115. filament_used_g: number;
  2116. filament_used_mm: number;
  2117. used_embedded_settings: boolean;
  2118. }
  2119. // Background slice-job lifecycle. POST /slice returns 202 + this shape;
  2120. // the frontend polls /slice-jobs/{id} until status is terminal.
  2121. export type SliceJobStatus = 'pending' | 'running' | 'completed' | 'failed';
  2122. export interface SliceJobEnqueueResponse {
  2123. job_id: number;
  2124. status: SliceJobStatus;
  2125. status_url: string;
  2126. }
  2127. export interface SliceJobProgress {
  2128. /** Stage label emitted by the slicer ("Generating G-code", "Slicing finished"). */
  2129. stage: string;
  2130. total_percent: number;
  2131. plate_percent: number;
  2132. /** 1-indexed plate position; 0 means "all plates" / final completion. */
  2133. plate_index: number;
  2134. plate_count: number;
  2135. updated_at: number;
  2136. /** When the backend is in the cross-class slice-all loop (#1493), each
  2137. * per-plate sub-slice's progress is augmented with the loop position
  2138. * so the toast can show "Plate 2 of 5 — Generating G-code 47%". The
  2139. * fields are absent on a single-plate slice. */
  2140. multi_plate_index?: number;
  2141. multi_plate_count?: number;
  2142. }
  2143. export interface SliceJobState {
  2144. job_id: number;
  2145. status: SliceJobStatus;
  2146. kind: 'library_file' | 'archive';
  2147. source_id: number;
  2148. source_name: string;
  2149. created_at: string;
  2150. started_at: string | null;
  2151. completed_at: string | null;
  2152. /** Live progress fed by the sidecar's --pipe channel; null until the
  2153. * slicer emits its first frame (early "Initializing" phase) or when
  2154. * the sidecar doesn't support progress. */
  2155. progress: SliceJobProgress | null;
  2156. result?: SliceResponse | SliceArchiveResponse;
  2157. error_status?: number;
  2158. error_detail?: string;
  2159. }
  2160. // Local preset types (OrcaSlicer imports)
  2161. export interface LocalPreset {
  2162. id: number;
  2163. name: string;
  2164. preset_type: string;
  2165. source: string;
  2166. filament_type: string | null;
  2167. filament_vendor: string | null;
  2168. nozzle_temp_min: number | null;
  2169. nozzle_temp_max: number | null;
  2170. pressure_advance: string | null;
  2171. default_filament_colour: string | null;
  2172. filament_cost: string | null;
  2173. filament_density: string | null;
  2174. compatible_printers: string | null;
  2175. inherits: string | null;
  2176. version: string | null;
  2177. created_at: string;
  2178. updated_at: string;
  2179. }
  2180. export interface LocalPresetDetail extends LocalPreset {
  2181. setting: Record<string, unknown>;
  2182. }
  2183. export interface LocalPresetsResponse {
  2184. filament: LocalPreset[];
  2185. printer: LocalPreset[];
  2186. process: LocalPreset[];
  2187. }
  2188. export interface ImportResponse {
  2189. success: boolean;
  2190. imported: number;
  2191. skipped: number;
  2192. errors: string[];
  2193. }
  2194. export interface FieldOption {
  2195. value: string;
  2196. label: string;
  2197. }
  2198. export interface FieldDefinition {
  2199. key: string;
  2200. label: string;
  2201. type: 'text' | 'number' | 'boolean' | 'select';
  2202. category: string;
  2203. description?: string;
  2204. options?: FieldOption[];
  2205. unit?: string;
  2206. min?: number;
  2207. max?: number;
  2208. step?: number;
  2209. }
  2210. export interface FieldDefinitionsResponse {
  2211. version: string;
  2212. description: string;
  2213. fields: FieldDefinition[];
  2214. }
  2215. export interface CloudDevice {
  2216. dev_id: string;
  2217. name: string;
  2218. dev_model_name: string | null;
  2219. dev_product_name: string | null;
  2220. online: boolean;
  2221. }
  2222. // Smart Plug types
  2223. export interface SmartPlug {
  2224. id: number;
  2225. name: string;
  2226. plug_type: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  2227. ip_address: string | null; // Required for Tasmota
  2228. ha_entity_id: string | null; // Required for Home Assistant (e.g., "switch.printer_plug", "script.turn_on_printer")
  2229. // Home Assistant energy sensor entities (optional)
  2230. ha_power_entity: string | null;
  2231. ha_energy_today_entity: string | null;
  2232. ha_energy_total_entity: string | null;
  2233. // MQTT fields (required when plug_type="mqtt")
  2234. // Legacy field - kept for backward compatibility
  2235. mqtt_topic: string | null; // Deprecated, use mqtt_power_topic
  2236. mqtt_multiplier: number; // Deprecated, use mqtt_power_multiplier
  2237. // Power monitoring
  2238. mqtt_power_topic: string | null; // Topic for power data
  2239. mqtt_power_path: string | null; // e.g., "power_l1" or "data.power"
  2240. mqtt_power_multiplier: number; // Unit conversion for power
  2241. // Energy monitoring
  2242. mqtt_energy_topic: string | null; // Topic for energy data
  2243. mqtt_energy_path: string | null; // e.g., "energy_l1"
  2244. mqtt_energy_multiplier: number; // Unit conversion for energy
  2245. // State monitoring
  2246. mqtt_state_topic: string | null; // Topic for state data
  2247. mqtt_state_path: string | null; // e.g., "state_l1" for ON/OFF
  2248. mqtt_state_on_value: string | null; // What value means "ON" (e.g., "ON", "true", "1")
  2249. // REST/Webhook fields (required when plug_type="rest")
  2250. rest_on_url: string | null;
  2251. rest_on_body: string | null;
  2252. rest_off_url: string | null;
  2253. rest_off_body: string | null;
  2254. rest_method: string | null;
  2255. rest_headers: string | null;
  2256. rest_status_url: string | null;
  2257. rest_status_path: string | null;
  2258. rest_status_on_value: string | null;
  2259. rest_power_url: string | null;
  2260. rest_power_path: string | null;
  2261. rest_power_multiplier: number;
  2262. rest_energy_url: string | null;
  2263. rest_energy_path: string | null;
  2264. rest_energy_multiplier: number;
  2265. // Lifetime counter, separate from the daily one (#2539). A Shelly reports only
  2266. // this; Today and Yesterday are derived from its hourly snapshots.
  2267. rest_energy_total_path: string | null;
  2268. rest_energy_total_multiplier: number;
  2269. printer_id: number | null;
  2270. // #2629: only a plug that really feeds the printer may mark it offline when
  2271. // switched off. Accessory plugs follow the print cycle without powering it.
  2272. controls_printer_power: boolean;
  2273. enabled: boolean;
  2274. auto_on: boolean;
  2275. auto_off: boolean;
  2276. auto_off_persistent: boolean;
  2277. off_delay_mode: 'time' | 'temperature';
  2278. off_delay_minutes: number;
  2279. off_temp_threshold: number;
  2280. // #1349: auto-off after AMS drying completes.
  2281. auto_off_after_drying: boolean;
  2282. off_delay_after_drying_minutes: number;
  2283. username: string | null;
  2284. password: string | null;
  2285. // Power alerts
  2286. power_alert_enabled: boolean;
  2287. power_alert_high: number | null;
  2288. power_alert_low: number | null;
  2289. power_alert_last_triggered: string | null;
  2290. // Schedule
  2291. schedule_enabled: boolean;
  2292. schedule_on_time: string | null;
  2293. schedule_off_time: string | null;
  2294. // Visibility options
  2295. show_in_switchbar: boolean;
  2296. show_on_printer_card: boolean; // For scripts: show on printer card
  2297. // Status
  2298. last_state: string | null;
  2299. last_checked: string | null;
  2300. auto_off_executed: boolean; // True when auto-off was triggered after print
  2301. created_at: string;
  2302. updated_at: string;
  2303. }
  2304. export interface SmartPlugCreate {
  2305. name: string;
  2306. plug_type?: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  2307. ip_address?: string | null; // Required for Tasmota
  2308. ha_entity_id?: string | null; // Required for Home Assistant
  2309. // Home Assistant energy sensor entities (optional)
  2310. ha_power_entity?: string | null;
  2311. ha_energy_today_entity?: string | null;
  2312. ha_energy_total_entity?: string | null;
  2313. // MQTT fields (required when plug_type="mqtt")
  2314. // Legacy fields - kept for backward compatibility
  2315. mqtt_topic?: string | null;
  2316. mqtt_multiplier?: number;
  2317. // Power monitoring
  2318. mqtt_power_topic?: string | null;
  2319. mqtt_power_path?: string | null;
  2320. mqtt_power_multiplier?: number;
  2321. // Energy monitoring
  2322. mqtt_energy_topic?: string | null;
  2323. mqtt_energy_path?: string | null;
  2324. mqtt_energy_multiplier?: number;
  2325. // State monitoring
  2326. mqtt_state_topic?: string | null;
  2327. mqtt_state_path?: string | null;
  2328. mqtt_state_on_value?: string | null;
  2329. // REST fields
  2330. rest_on_url?: string | null;
  2331. rest_on_body?: string | null;
  2332. rest_off_url?: string | null;
  2333. rest_off_body?: string | null;
  2334. rest_method?: string | null;
  2335. rest_headers?: string | null;
  2336. rest_status_url?: string | null;
  2337. rest_status_path?: string | null;
  2338. rest_status_on_value?: string | null;
  2339. rest_power_url?: string | null;
  2340. rest_power_path?: string | null;
  2341. rest_power_multiplier?: number;
  2342. rest_energy_url?: string | null;
  2343. rest_energy_path?: string | null;
  2344. rest_energy_multiplier?: number;
  2345. rest_energy_total_path?: string | null;
  2346. rest_energy_total_multiplier?: number;
  2347. printer_id?: number | null;
  2348. // #2629
  2349. controls_printer_power?: boolean;
  2350. enabled?: boolean;
  2351. auto_on?: boolean;
  2352. auto_off?: boolean;
  2353. auto_off_persistent?: boolean;
  2354. off_delay_mode?: 'time' | 'temperature';
  2355. off_delay_minutes?: number;
  2356. off_temp_threshold?: number;
  2357. // #1349
  2358. auto_off_after_drying?: boolean;
  2359. off_delay_after_drying_minutes?: number;
  2360. username?: string | null;
  2361. password?: string | null;
  2362. // Power alerts
  2363. power_alert_enabled?: boolean;
  2364. power_alert_high?: number | null;
  2365. power_alert_low?: number | null;
  2366. // Schedule
  2367. schedule_enabled?: boolean;
  2368. schedule_on_time?: string | null;
  2369. schedule_off_time?: string | null;
  2370. // Visibility options
  2371. show_in_switchbar?: boolean;
  2372. show_on_printer_card?: boolean;
  2373. }
  2374. export interface SmartPlugUpdate {
  2375. name?: string;
  2376. plug_type?: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  2377. ip_address?: string | null;
  2378. ha_entity_id?: string | null;
  2379. // Home Assistant energy sensor entities (optional)
  2380. ha_power_entity?: string | null;
  2381. ha_energy_today_entity?: string | null;
  2382. ha_energy_total_entity?: string | null;
  2383. // MQTT fields (legacy)
  2384. mqtt_topic?: string | null;
  2385. mqtt_multiplier?: number;
  2386. // MQTT power fields
  2387. mqtt_power_topic?: string | null;
  2388. mqtt_power_path?: string | null;
  2389. mqtt_power_multiplier?: number;
  2390. // MQTT energy fields
  2391. mqtt_energy_topic?: string | null;
  2392. mqtt_energy_path?: string | null;
  2393. mqtt_energy_multiplier?: number;
  2394. // MQTT state fields
  2395. mqtt_state_topic?: string | null;
  2396. mqtt_state_path?: string | null;
  2397. mqtt_state_on_value?: string | null;
  2398. // REST fields
  2399. rest_on_url?: string | null;
  2400. rest_on_body?: string | null;
  2401. rest_off_url?: string | null;
  2402. rest_off_body?: string | null;
  2403. rest_method?: string | null;
  2404. rest_headers?: string | null;
  2405. rest_status_url?: string | null;
  2406. rest_status_path?: string | null;
  2407. rest_status_on_value?: string | null;
  2408. rest_power_url?: string | null;
  2409. rest_power_path?: string | null;
  2410. rest_power_multiplier?: number;
  2411. rest_energy_url?: string | null;
  2412. rest_energy_path?: string | null;
  2413. rest_energy_multiplier?: number;
  2414. rest_energy_total_path?: string | null;
  2415. rest_energy_total_multiplier?: number;
  2416. printer_id?: number | null;
  2417. // #2629
  2418. controls_printer_power?: boolean;
  2419. enabled?: boolean;
  2420. auto_on?: boolean;
  2421. auto_off?: boolean;
  2422. auto_off_persistent?: boolean;
  2423. off_delay_mode?: 'time' | 'temperature';
  2424. off_delay_minutes?: number;
  2425. off_temp_threshold?: number;
  2426. // #1349
  2427. auto_off_after_drying?: boolean;
  2428. off_delay_after_drying_minutes?: number;
  2429. username?: string | null;
  2430. password?: string | null;
  2431. // Power alerts
  2432. power_alert_enabled?: boolean;
  2433. power_alert_high?: number | null;
  2434. power_alert_low?: number | null;
  2435. // Schedule
  2436. schedule_enabled?: boolean;
  2437. schedule_on_time?: string | null;
  2438. schedule_off_time?: string | null;
  2439. // Visibility options
  2440. show_in_switchbar?: boolean;
  2441. show_on_printer_card?: boolean;
  2442. }
  2443. // Home Assistant entity for smart plug selection
  2444. export interface HAEntity {
  2445. entity_id: string;
  2446. friendly_name: string;
  2447. state: string | null;
  2448. domain: string; // "switch", "light", "input_boolean", "script"
  2449. }
  2450. // Home Assistant sensor entity for energy monitoring
  2451. export interface HASensorEntity {
  2452. entity_id: string;
  2453. friendly_name: string;
  2454. state: string | null;
  2455. unit_of_measurement: string | null; // "W", "kW", "kWh", "Wh"
  2456. }
  2457. export interface HATestConnectionResult {
  2458. success: boolean;
  2459. message: string | null;
  2460. error: string | null;
  2461. }
  2462. // A Home Assistant entity bound to a printer for display on its card (#1148, #448).
  2463. // Read-only: unlike a SmartPlug there is nothing here to switch.
  2464. export interface PrinterHASensor {
  2465. id: number;
  2466. printer_id: number;
  2467. name: string;
  2468. entity_id: string;
  2469. kind: 'binary' | 'numeric';
  2470. device_class: string | null; // HA's own class: "door", "temperature", ...
  2471. unit: string | null; // numeric sensors only
  2472. // What counts as needing attention. Binary sensors use alert_state, numeric
  2473. // ones the thresholds; all null means the sensor is display-only.
  2474. alert_state: 'on' | 'off' | null;
  2475. alert_above: number | null;
  2476. alert_below: number | null;
  2477. block_print: boolean; // hold the printer's queue while alerting
  2478. notify_on_alert: boolean;
  2479. show_on_printer_card: boolean;
  2480. sort_order: number;
  2481. last_state: string | null;
  2482. last_changed: string | null;
  2483. last_checked: string | null;
  2484. created_at: string;
  2485. updated_at: string;
  2486. }
  2487. export interface PrinterHASensorReading {
  2488. id: number;
  2489. name: string;
  2490. entity_id: string;
  2491. kind: 'binary' | 'numeric';
  2492. device_class: string | null;
  2493. unit: string | null;
  2494. state: string | null; // null when unreadable or not yet polled
  2495. value: number | null; // numeric sensors only
  2496. alerting: boolean;
  2497. block_print: boolean;
  2498. reachable: boolean;
  2499. last_changed: string | null;
  2500. }
  2501. export interface PrinterHASensorCreate {
  2502. printer_id: number;
  2503. name: string;
  2504. entity_id: string;
  2505. kind: 'binary' | 'numeric';
  2506. device_class?: string | null;
  2507. unit?: string | null;
  2508. alert_state?: 'on' | 'off' | null;
  2509. alert_above?: number | null;
  2510. alert_below?: number | null;
  2511. block_print?: boolean;
  2512. notify_on_alert?: boolean;
  2513. show_on_printer_card?: boolean;
  2514. sort_order?: number;
  2515. }
  2516. export type PrinterHASensorUpdate = Partial<Omit<PrinterHASensorCreate, 'printer_id'>>;
  2517. export interface LocationHASensor {
  2518. id: number;
  2519. location_id: number;
  2520. name: string;
  2521. entity_id: string;
  2522. kind: 'binary' | 'numeric';
  2523. device_class: string | null;
  2524. unit: string | null;
  2525. alert_state: 'on' | 'off' | null;
  2526. alert_above: number | null;
  2527. alert_below: number | null;
  2528. notify_on_alert: boolean;
  2529. show_on_card: boolean;
  2530. sort_order: number;
  2531. last_state: string | null;
  2532. last_changed: string | null;
  2533. last_checked: string | null;
  2534. created_at: string;
  2535. updated_at: string;
  2536. }
  2537. export interface LocationHASensorReading {
  2538. id: number;
  2539. name: string;
  2540. entity_id: string;
  2541. kind: 'binary' | 'numeric';
  2542. device_class: string | null;
  2543. unit: string | null;
  2544. state: string | null;
  2545. value: number | null;
  2546. alerting: boolean;
  2547. reachable: boolean;
  2548. alert_state: string | null;
  2549. alert_above: number | null;
  2550. alert_below: number | null;
  2551. last_changed: string | null;
  2552. show_on_card: boolean;
  2553. }
  2554. export interface LocationHASensorCreate {
  2555. location_id: number;
  2556. name: string;
  2557. entity_id: string;
  2558. kind: 'binary' | 'numeric';
  2559. device_class?: string | null;
  2560. unit?: string | null;
  2561. alert_state?: 'on' | 'off' | null;
  2562. alert_above?: number | null;
  2563. alert_below?: number | null;
  2564. notify_on_alert?: boolean;
  2565. show_on_card?: boolean;
  2566. sort_order?: number;
  2567. }
  2568. export type LocationHASensorUpdate = Partial<Omit<LocationHASensorCreate, 'location_id'>>;
  2569. // An entity offered by the binding picker.
  2570. export interface HADisplayEntity {
  2571. entity_id: string;
  2572. friendly_name: string;
  2573. state: string | null;
  2574. domain: string; // "binary_sensor" | "sensor"
  2575. device_class: string | null;
  2576. unit_of_measurement: string | null;
  2577. }
  2578. export interface SmartPlugEnergy {
  2579. power: number | null; // Current watts
  2580. voltage: number | null; // Volts
  2581. current: number | null; // Amps
  2582. today: number | null; // kWh used today
  2583. yesterday: number | null; // kWh used yesterday
  2584. total: number | null; // Total kWh
  2585. factor: number | null; // Power factor (0-1)
  2586. apparent_power: number | null; // VA
  2587. reactive_power: number | null; // VAr
  2588. }
  2589. export interface SmartPlugStatus {
  2590. state: string | null;
  2591. reachable: boolean;
  2592. device_name: string | null;
  2593. energy: SmartPlugEnergy | null;
  2594. }
  2595. export interface SmartPlugTestResult {
  2596. success: boolean;
  2597. state: string | null;
  2598. device_name: string | null;
  2599. }
  2600. // Tasmota Discovery types
  2601. export interface TasmotaScanStatus {
  2602. running: boolean;
  2603. scanned: number;
  2604. total: number;
  2605. }
  2606. export interface DiscoveredTasmotaDevice {
  2607. ip_address: string;
  2608. name: string;
  2609. module: number | null;
  2610. state: string | null;
  2611. discovered_at: string | null;
  2612. }
  2613. // Print Queue types
  2614. export interface PrintQueueItem {
  2615. id: number;
  2616. printer_id: number | null; // null = unassigned
  2617. target_model: string | null; // Target printer model for model-based assignment
  2618. target_location: string | null; // Target location filter for model-based assignment
  2619. required_filament_types: string[] | null; // Required filament types for model-based assignment
  2620. waiting_reason: string | null; // Why this job hasn't started yet (empty once it can)
  2621. // Cross-model alternatives (#671), in priority order. Empty for ordinary
  2622. // items. Present until dispatch resolves one, after which library_file_id and
  2623. // target_model name the candidate that actually ran.
  2624. variants?: Array<{
  2625. library_file_id: number;
  2626. filename: string;
  2627. target_model: string;
  2628. position: number;
  2629. }>;
  2630. // Either archive_id OR library_file_id must be set (archive created at print start)
  2631. archive_id: number | null;
  2632. library_file_id: number | null;
  2633. cost_center_id: number | null;
  2634. estimated_cost: number | null;
  2635. position: number;
  2636. scheduled_time: string | null;
  2637. require_previous_success: boolean;
  2638. auto_off_after: boolean;
  2639. manual_start: boolean; // Requires manual trigger to start (staged)
  2640. // Set by the dispatch scheduler when the assigned spool can't satisfy
  2641. // any required slot's grams (#1496). Surfaced on the queue row as a
  2642. // "filament short" badge; cleared on a successful ▶ click (live recheck).
  2643. filament_short: boolean;
  2644. // Persistent "Print Anyway" acknowledgement — once true the scheduler
  2645. // skips the deficit check for this item (#1698-followup). Set by the
  2646. // start route when skip_filament_check=true, or at queue creation if
  2647. // PrintModal's deficit warning was acknowledged.
  2648. skip_filament_check: boolean;
  2649. // True when the source archive carries the slicer's own live-resolved
  2650. // AMS-slot pick (extra_data.slicer_ams_mapping) — a reprint reuses that
  2651. // exact physical spool instead of re-deriving one from type/color.
  2652. archive_has_slicer_ams_mapping: boolean;
  2653. ams_mapping: number[] | null; // AMS slot mapping for multi-color prints
  2654. 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
  2655. plate_id: number | null; // Plate ID for multi-plate 3MF files
  2656. // Print options
  2657. bed_levelling: CalibrationMode;
  2658. flow_cali: CalibrationMode;
  2659. vibration_cali: boolean;
  2660. layer_inspect: boolean;
  2661. timelapse: boolean;
  2662. use_ams: boolean;
  2663. nozzle_offset_cali: CalibrationMode;
  2664. // Ask for a post-print outcome verdict when this job completes (#1898)
  2665. confirm_outcome: boolean;
  2666. preheat_override: 'inherit' | 'on' | 'off';
  2667. preheat_chamber_target_override: number | null;
  2668. status: 'pending' | 'printing' | 'completed' | 'failed' | 'skipped' | 'cancelled';
  2669. started_at: string | null;
  2670. completed_at: string | null;
  2671. error_message: string | null;
  2672. created_at: string;
  2673. archive_name?: string | null;
  2674. archive_thumbnail?: string | null;
  2675. // True when the linked archive has been soft-deleted; archive_name /
  2676. // archive_thumbnail / downstream metadata are left null in that case so
  2677. // the UI doesn't 404-storm the now-missing endpoints (#1348 follow-up).
  2678. archive_deleted?: boolean;
  2679. library_file_name?: string | null;
  2680. library_file_thumbnail?: string | null;
  2681. printer_name?: string | null;
  2682. print_time_seconds?: number | null; // Estimated print time from archive or library file
  2683. filament_used_grams?: number | null; // Estimated print weight from archive or library file
  2684. filament_type?: string | null; // e.g. "PLA", "PETG"
  2685. filament_color?: string | null; // Hex RGBA from the slicer
  2686. bed_type?: string | null; // Build plate type for this print (per-plate accurate, #1281)
  2687. // User tracking (Issue #206)
  2688. created_by_id?: number | null;
  2689. created_by_username?: string | null;
  2690. // Batch grouping
  2691. batch_id?: number | null;
  2692. batch_name?: string | null;
  2693. // Shortest-job-first scheduling
  2694. been_jumped?: boolean;
  2695. // Auto-print G-code injection
  2696. gcode_injection?: boolean;
  2697. cleanup_library_after_dispatch?: boolean;
  2698. /** Which rack position each filament group prints from, on a nozzle-rack
  2699. * machine (#1784): `{ [group_id]: 1-based position }`. Re-checked against
  2700. * the live rack at dispatch; omit to have the dispatcher assign them. */
  2701. nozzle_rack_choice?: Record<number, number> | null;
  2702. /** Slots sent with a spool of another colour than the file asks for
  2703. * (#3279). Worked out when the job is sent; null when every slot got its
  2704. * colour or nothing could be compared. */
  2705. color_substitutions?: ColorSubstitution[] | null;
  2706. }
  2707. /** One slot printed in another colour than the file asked for (#3279). */
  2708. export interface ColorSubstitution {
  2709. slot_id: number;
  2710. type: string;
  2711. /** `#RRGGBB` the file asks for, after overrides. */
  2712. wanted: string;
  2713. /** `#RRGGBB` of the spool the slot was sent with. */
  2714. got: string;
  2715. tray: number;
  2716. }
  2717. export interface PrintBatchPlateTarget {
  2718. plate_id: number | null;
  2719. plate_name?: string | null;
  2720. quantity_target: number;
  2721. sort_order?: number;
  2722. }
  2723. export interface PrintBatchPlateProgress {
  2724. plate_id: number | null;
  2725. plate_name: string | null;
  2726. quantity_target: number;
  2727. dispatched: number;
  2728. remaining: number;
  2729. pending_count: number;
  2730. printing_count: number;
  2731. completed_count: number;
  2732. failed_count: number;
  2733. cancelled_count: number;
  2734. skipped_count: number;
  2735. /** Measured from finished runs; null until one has produced a cost. */
  2736. actual_cost: number | null;
  2737. estimated_remaining_cost: number | null;
  2738. filament_used_grams: number | null;
  2739. print_time_seconds: number;
  2740. /** False when this plate owes runs but has no queue item left to clone
  2741. * their configuration from, so queueing it could only fail (#2960). */
  2742. can_dispatch: boolean;
  2743. }
  2744. export interface PrintBatch {
  2745. id: number;
  2746. name: string;
  2747. archive_id: number | null;
  2748. library_file_id: number | null;
  2749. quantity: number;
  2750. status: string;
  2751. created_at: string;
  2752. completed_at: string | null;
  2753. created_by_id: number | null;
  2754. created_by_username: string | null;
  2755. project_id: number | null;
  2756. due_date: string | null;
  2757. notes: string | null;
  2758. /** Set when an integration (e.g. a shop connector) created the batch. */
  2759. external_source: string | null;
  2760. external_ref: string | null;
  2761. pending_count: number;
  2762. printing_count: number;
  2763. completed_count: number;
  2764. failed_count: number;
  2765. cancelled_count: number;
  2766. skipped_count: number;
  2767. /** False for batches created before per-plate targets existed (#342):
  2768. * they report progress but owe nothing and cannot be dispatched from. */
  2769. has_targets: boolean;
  2770. target_count: number;
  2771. remaining_count: number;
  2772. /** Of remaining_count, how many runs can actually be queued (#2960). */
  2773. dispatchable_count: number;
  2774. actual_cost: number | null;
  2775. estimated_remaining_cost: number | null;
  2776. filament_used_grams: number | null;
  2777. print_time_seconds: number;
  2778. plates: PrintBatchPlateProgress[];
  2779. }
  2780. export interface PrintQueueItemCreate {
  2781. printer_id?: number | null; // null = unassigned
  2782. target_model?: string | null; // Target printer model (mutually exclusive with printer_id)
  2783. target_location?: string | null; // Target location filter (only used with target_model)
  2784. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; tray_info_idx?: string; force_color_match?: boolean }> | null;
  2785. archive_id?: number | null;
  2786. library_file_id?: number | null;
  2787. scheduled_time?: string | null;
  2788. require_previous_success?: boolean;
  2789. auto_off_after?: boolean;
  2790. manual_start?: boolean; // Requires manual trigger to start (staged)
  2791. insert_at_top?: boolean; // Insert ahead of other pending items (one queue order across all printers, #3200)
  2792. insert_position?: number | null; // 1-indexed insertion position for priority queueing
  2793. // PrintModal "Print Anyway" on the deficit warning — persisted so the
  2794. // scheduler doesn't immediately re-flag this item (#1698-followup).
  2795. skip_filament_check?: boolean;
  2796. ams_mapping?: number[] | null; // AMS slot mapping for multi-color prints
  2797. plate_id?: number | null; // Plate ID for multi-plate 3MF files
  2798. // Print options
  2799. bed_levelling?: CalibrationMode;
  2800. flow_cali?: CalibrationMode;
  2801. vibration_cali?: boolean;
  2802. layer_inspect?: boolean;
  2803. timelapse?: boolean;
  2804. use_ams?: boolean;
  2805. nozzle_offset_cali?: CalibrationMode;
  2806. // Ask for a post-print outcome verdict when this job completes (#1898)
  2807. confirm_outcome?: boolean;
  2808. preheat_override?: 'inherit' | 'on' | 'off';
  2809. preheat_chamber_target_override?: number | null;
  2810. // Auto-print G-code injection
  2811. gcode_injection?: boolean;
  2812. // Batch: create multiple copies (creates a batch if > 1)
  2813. quantity?: number;
  2814. // Existing batch to add this item into (multi-plate auto-batch flow).
  2815. batch_id?: number | null;
  2816. // Project to associate the resulting archive with
  2817. project_id?: number;
  2818. cost_center_id?: number | null;
  2819. estimated_cost?: number | null;
  2820. // Delete transient uploaded library file after scheduler creates the archive
  2821. cleanup_library_after_dispatch?: boolean;
  2822. // Cross-model alternatives (#671): several sliced files, one job, whichever
  2823. // printer frees up first. Mutually exclusive with printer_id (a named printer
  2824. // defeats the point) and with archive_id/library_file_id (these ARE the files).
  2825. // Order is priority — index 0 wins when several printers are idle at once.
  2826. variants?: QueueVariantCreate[];
  2827. /** Which rack position each filament group prints from, on a nozzle-rack
  2828. * machine (#1784): `{ [group_id]: 1-based position }`. Re-checked against
  2829. * the live rack at dispatch; omit to have the dispatcher assign them. */
  2830. nozzle_rack_choice?: Record<number, number> | null;
  2831. }
  2832. /** One candidate file for a cross-model queue item (#671). */
  2833. export interface QueueVariantCreate {
  2834. library_file_id: number;
  2835. /** Read from the file's own sliced_for_model unless it declares none. */
  2836. target_model?: string | null;
  2837. plate_id?: number | null;
  2838. ams_mapping?: number[] | null;
  2839. nozzle_mapping?: number[] | null;
  2840. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; tray_info_idx?: string; force_color_match?: boolean }> | null;
  2841. }
  2842. export interface PrintBatchCreate {
  2843. name: string;
  2844. archive_id?: number | null;
  2845. library_file_id?: number | null;
  2846. /** When set, the listed pending items are assigned to the new batch
  2847. * (manual "Group as batch"). When omitted/empty, an empty batch is
  2848. * returned so the client can pass batch_id on subsequent addToQueue calls. */
  2849. item_ids?: number[];
  2850. /** Per-plate targets. Omitting them creates a plain grouping batch. */
  2851. plates?: PrintBatchPlateTarget[];
  2852. project_id?: number | null;
  2853. due_date?: string | null;
  2854. notes?: string | null;
  2855. }
  2856. export interface PrintBatchUpdate {
  2857. name?: string;
  2858. status?: 'active' | 'cancelled';
  2859. /** Replaces the full target set — a plate omitted here is removed. */
  2860. plates?: PrintBatchPlateTarget[];
  2861. project_id?: number | null;
  2862. due_date?: string | null;
  2863. notes?: string | null;
  2864. }
  2865. export interface PrintBatchDispatchRequest {
  2866. plate_id?: number | null;
  2867. only_plate?: boolean;
  2868. /** Cap on items created across all plates; omit to queue everything owed. */
  2869. limit?: number;
  2870. }
  2871. export interface PrintQueueItemUpdate {
  2872. printer_id?: number | null; // null = unassign
  2873. // A deliberate filament substitution in the mapping (#2799); see PrintModal.
  2874. skip_filament_check?: boolean;
  2875. target_model?: string | null; // Target printer model (mutually exclusive with printer_id)
  2876. target_location?: string | null; // Target location filter (only used with target_model)
  2877. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; tray_info_idx?: string; force_color_match?: boolean }> | null;
  2878. position?: number;
  2879. scheduled_time?: string | null;
  2880. require_previous_success?: boolean;
  2881. auto_off_after?: boolean;
  2882. manual_start?: boolean;
  2883. ams_mapping?: number[];
  2884. plate_id?: number | null; // Plate ID for multi-plate 3MF files
  2885. // Print options
  2886. bed_levelling?: CalibrationMode;
  2887. flow_cali?: CalibrationMode;
  2888. vibration_cali?: boolean;
  2889. layer_inspect?: boolean;
  2890. timelapse?: boolean;
  2891. use_ams?: boolean;
  2892. nozzle_offset_cali?: CalibrationMode;
  2893. // Ask for a post-print outcome verdict when this job completes (#1898)
  2894. confirm_outcome?: boolean;
  2895. preheat_override?: 'inherit' | 'on' | 'off';
  2896. preheat_chamber_target_override?: number | null;
  2897. // Auto-print G-code injection
  2898. gcode_injection?: boolean;
  2899. cost_center_id?: number | null;
  2900. estimated_cost?: number | null;
  2901. /** Which rack position each filament group prints from, on a nozzle-rack
  2902. * machine (#1784): `{ [group_id]: 1-based position }`. Re-checked against
  2903. * the live rack at dispatch; omit to have the dispatcher assign them. */
  2904. nozzle_rack_choice?: Record<number, number> | null;
  2905. }
  2906. export interface PrintQueueBulkUpdate {
  2907. item_ids: number[];
  2908. printer_id?: number | null;
  2909. scheduled_time?: string | null;
  2910. require_previous_success?: boolean;
  2911. auto_off_after?: boolean;
  2912. manual_start?: boolean;
  2913. // Print options
  2914. bed_levelling?: CalibrationMode;
  2915. flow_cali?: CalibrationMode;
  2916. vibration_cali?: boolean;
  2917. layer_inspect?: boolean;
  2918. timelapse?: boolean;
  2919. use_ams?: boolean;
  2920. nozzle_offset_cali?: CalibrationMode;
  2921. // Ask for a post-print outcome verdict when this job completes (#1898)
  2922. confirm_outcome?: boolean;
  2923. preheat_override?: 'inherit' | 'on' | 'off';
  2924. preheat_chamber_target_override?: number | null;
  2925. // Auto-print G-code injection
  2926. gcode_injection?: boolean;
  2927. cost_center_id?: number | null;
  2928. estimated_cost?: number | null;
  2929. }
  2930. export interface PrintQueueBulkUpdateResponse {
  2931. updated_count: number;
  2932. skipped_count: number;
  2933. message: string;
  2934. }
  2935. // MQTT Logging types
  2936. export interface MQTTLogEntry {
  2937. timestamp: string;
  2938. topic: string;
  2939. direction: 'in' | 'out';
  2940. payload: Record<string, unknown>;
  2941. }
  2942. export interface MQTTLogsResponse {
  2943. logging_enabled: boolean;
  2944. logs: MQTTLogEntry[];
  2945. }
  2946. // K-Profile types
  2947. export interface KProfile {
  2948. slot_id: number;
  2949. extruder_id: number;
  2950. nozzle_id: string;
  2951. nozzle_diameter: string;
  2952. filament_id: string;
  2953. name: string;
  2954. k_value: string;
  2955. n_coef: string;
  2956. ams_id: number;
  2957. tray_id: number;
  2958. setting_id: string | null;
  2959. }
  2960. export interface KProfileCreate {
  2961. slot_id?: number; // Storage slot, 0 for new profiles
  2962. extruder_id?: number;
  2963. nozzle_id: string;
  2964. nozzle_diameter: string;
  2965. filament_id: string;
  2966. name: string;
  2967. k_value: string;
  2968. n_coef?: string;
  2969. ams_id?: number;
  2970. tray_id?: number;
  2971. setting_id?: string | null;
  2972. }
  2973. export interface KProfileDelete {
  2974. slot_id: number; // cali_idx - calibration index to delete
  2975. extruder_id: number;
  2976. nozzle_id: string; // e.g., "HH00-0.4"
  2977. nozzle_diameter: string; // e.g., "0.4"
  2978. filament_id: string; // Bambu filament identifier
  2979. setting_id?: string | null; // Setting ID (for X1C series)
  2980. }
  2981. export interface KProfilesResponse {
  2982. profiles: KProfile[];
  2983. nozzle_diameter: string;
  2984. }
  2985. export interface KProfileNote {
  2986. setting_id: string;
  2987. note: string;
  2988. }
  2989. export interface KProfileNotesResponse {
  2990. notes: Record<string, string>; // setting_id -> note
  2991. }
  2992. // Slot Preset Mapping
  2993. export interface SlotPresetMapping {
  2994. ams_id: number;
  2995. tray_id: number;
  2996. preset_id: string;
  2997. preset_name: string;
  2998. // Filament id the slot was configured with alongside this preset; null for
  2999. // rows that predate it or whose writer did not know it (#3216).
  3000. tray_info_idx?: string | null;
  3001. }
  3002. // Filament types
  3003. export interface Filament {
  3004. id: number;
  3005. name: string;
  3006. type: string; // PLA, PETG, ABS, etc.
  3007. brand: string | null;
  3008. color: string | null;
  3009. color_hex: string | null;
  3010. cost_per_kg: number;
  3011. spool_weight_g: number;
  3012. currency: string;
  3013. density: number | null;
  3014. print_temp_min: number | null;
  3015. print_temp_max: number | null;
  3016. bed_temp_min: number | null;
  3017. bed_temp_max: number | null;
  3018. created_at: string;
  3019. updated_at: string;
  3020. }
  3021. // Notification Provider types
  3022. export type ProviderType = 'callmebot' | 'ntfy' | 'pushover' | 'telegram' | 'email' | 'discord' | 'webhook' | 'homeassistant' | 'bark' | 'gotify' | 'notify';
  3023. // How a Telegram provider collects the outcome verdict (#3046)
  3024. export type TelegramVerdictMode = 'buttons' | 'reactions' | 'both';
  3025. export interface NotificationProvider {
  3026. id: number;
  3027. name: string;
  3028. provider_type: ProviderType;
  3029. enabled: boolean;
  3030. config: Record<string, unknown>;
  3031. attach_photo: boolean;
  3032. // Print lifecycle events
  3033. on_print_start: boolean;
  3034. on_print_complete: boolean;
  3035. on_print_failed: boolean;
  3036. on_print_stopped: boolean;
  3037. on_print_progress: boolean;
  3038. on_print_missing_spool_assignment: boolean;
  3039. on_billing_charge_failed: boolean;
  3040. // Printer status events
  3041. on_printer_offline: boolean;
  3042. on_printer_error: boolean;
  3043. on_ai_failure_detection: boolean;
  3044. on_filament_low: boolean;
  3045. on_maintenance_due: boolean;
  3046. // AMS environmental alarms (regular AMS)
  3047. on_ams_humidity_high: boolean;
  3048. on_ams_temperature_high: boolean;
  3049. on_ams_drying_suspended: boolean;
  3050. // AMS-HT environmental alarms
  3051. on_ams_ht_humidity_high: boolean;
  3052. on_ams_ht_temperature_high: boolean;
  3053. // Build plate detection
  3054. on_plate_not_empty: boolean;
  3055. on_plate_clear_required: boolean;
  3056. // Post-print outcome confirmation (#1898)
  3057. on_print_confirm_request: boolean;
  3058. telegram_verdict_mode: TelegramVerdictMode;
  3059. // Bed cooled
  3060. on_bed_cooled: boolean;
  3061. on_ha_sensor_alert: boolean;
  3062. on_location_ha_sensor_alert: boolean;
  3063. // First layer complete
  3064. on_first_layer_complete: boolean;
  3065. on_print_pause_upcoming: boolean;
  3066. on_app_message: boolean;
  3067. // Inventory stock alerts
  3068. on_stock_reorder_alert: boolean;
  3069. on_stock_break_alert: boolean;
  3070. // Print queue events
  3071. on_queue_job_added: boolean;
  3072. on_queue_job_assigned: boolean;
  3073. on_queue_job_started: boolean;
  3074. on_queue_job_waiting: boolean;
  3075. on_queue_job_skipped: boolean;
  3076. on_queue_job_failed: boolean;
  3077. on_queue_completed: boolean;
  3078. // Quiet hours
  3079. quiet_hours_enabled: boolean;
  3080. quiet_hours_start: string | null;
  3081. quiet_hours_end: string | null;
  3082. // Daily digest
  3083. daily_digest_enabled: boolean;
  3084. daily_digest_time: string | null;
  3085. // Printer filter
  3086. printer_id: number | null;
  3087. // Status tracking
  3088. last_success: string | null;
  3089. last_error: string | null;
  3090. last_error_at: string | null;
  3091. // Timestamps
  3092. created_at: string;
  3093. updated_at: string;
  3094. }
  3095. export interface NotificationProviderCreate {
  3096. name: string;
  3097. provider_type: ProviderType;
  3098. enabled?: boolean;
  3099. config: Record<string, unknown>;
  3100. attach_photo?: boolean;
  3101. // Print lifecycle events
  3102. on_print_start?: boolean;
  3103. on_print_complete?: boolean;
  3104. on_print_failed?: boolean;
  3105. on_print_stopped?: boolean;
  3106. on_print_progress?: boolean;
  3107. on_print_missing_spool_assignment?: boolean;
  3108. on_billing_charge_failed?: boolean;
  3109. // Printer status events
  3110. on_printer_offline?: boolean;
  3111. on_printer_error?: boolean;
  3112. on_ai_failure_detection?: boolean;
  3113. on_filament_low?: boolean;
  3114. on_maintenance_due?: boolean;
  3115. // AMS environmental alarms (regular AMS)
  3116. on_ams_humidity_high?: boolean;
  3117. on_ams_temperature_high?: boolean;
  3118. on_ams_drying_suspended?: boolean;
  3119. // AMS-HT environmental alarms
  3120. on_ams_ht_humidity_high?: boolean;
  3121. on_ams_ht_temperature_high?: boolean;
  3122. // Build plate detection
  3123. on_plate_not_empty?: boolean;
  3124. on_plate_clear_required?: boolean;
  3125. // Post-print outcome confirmation (#1898)
  3126. on_print_confirm_request?: boolean;
  3127. telegram_verdict_mode?: TelegramVerdictMode;
  3128. // Bed cooled
  3129. on_bed_cooled?: boolean;
  3130. on_ha_sensor_alert?: boolean;
  3131. on_location_ha_sensor_alert?: boolean;
  3132. // First layer complete
  3133. on_first_layer_complete?: boolean;
  3134. on_print_pause_upcoming?: boolean;
  3135. on_app_message?: boolean;
  3136. // Inventory stock alerts
  3137. on_stock_reorder_alert?: boolean;
  3138. on_stock_break_alert?: boolean;
  3139. // Print queue events
  3140. on_queue_job_added?: boolean;
  3141. on_queue_job_assigned?: boolean;
  3142. on_queue_job_started?: boolean;
  3143. on_queue_job_waiting?: boolean;
  3144. on_queue_job_skipped?: boolean;
  3145. on_queue_job_failed?: boolean;
  3146. on_queue_completed?: boolean;
  3147. // Quiet hours
  3148. quiet_hours_enabled?: boolean;
  3149. quiet_hours_start?: string | null;
  3150. quiet_hours_end?: string | null;
  3151. // Daily digest
  3152. daily_digest_enabled?: boolean;
  3153. daily_digest_time?: string | null;
  3154. // Printer filter
  3155. printer_id?: number | null;
  3156. }
  3157. export interface NotificationProviderUpdate {
  3158. name?: string;
  3159. provider_type?: ProviderType;
  3160. enabled?: boolean;
  3161. config?: Record<string, unknown>;
  3162. attach_photo?: boolean;
  3163. // Print lifecycle events
  3164. on_print_start?: boolean;
  3165. on_print_complete?: boolean;
  3166. on_print_failed?: boolean;
  3167. on_print_stopped?: boolean;
  3168. on_print_progress?: boolean;
  3169. on_print_missing_spool_assignment?: boolean;
  3170. on_billing_charge_failed?: boolean;
  3171. // Printer status events
  3172. on_printer_offline?: boolean;
  3173. on_printer_error?: boolean;
  3174. on_ai_failure_detection?: boolean;
  3175. on_filament_low?: boolean;
  3176. on_maintenance_due?: boolean;
  3177. // AMS environmental alarms (regular AMS)
  3178. on_ams_humidity_high?: boolean;
  3179. on_ams_temperature_high?: boolean;
  3180. on_ams_drying_suspended?: boolean;
  3181. // AMS-HT environmental alarms
  3182. on_ams_ht_humidity_high?: boolean;
  3183. on_ams_ht_temperature_high?: boolean;
  3184. // Build plate detection
  3185. on_plate_not_empty?: boolean;
  3186. on_plate_clear_required?: boolean;
  3187. // Post-print outcome confirmation (#1898)
  3188. on_print_confirm_request?: boolean;
  3189. telegram_verdict_mode?: TelegramVerdictMode;
  3190. // Bed cooled
  3191. on_bed_cooled?: boolean;
  3192. on_ha_sensor_alert?: boolean;
  3193. on_location_ha_sensor_alert?: boolean;
  3194. // First layer complete
  3195. on_first_layer_complete?: boolean;
  3196. on_print_pause_upcoming?: boolean;
  3197. on_app_message?: boolean;
  3198. // Inventory stock alerts
  3199. on_stock_reorder_alert?: boolean;
  3200. on_stock_break_alert?: boolean;
  3201. // Print queue events
  3202. on_queue_job_added?: boolean;
  3203. on_queue_job_assigned?: boolean;
  3204. on_queue_job_started?: boolean;
  3205. on_queue_job_waiting?: boolean;
  3206. on_queue_job_skipped?: boolean;
  3207. on_queue_job_failed?: boolean;
  3208. on_queue_completed?: boolean;
  3209. // Quiet hours
  3210. quiet_hours_enabled?: boolean;
  3211. quiet_hours_start?: string | null;
  3212. quiet_hours_end?: string | null;
  3213. // Daily digest
  3214. daily_digest_enabled?: boolean;
  3215. daily_digest_time?: string | null;
  3216. // Printer filter
  3217. printer_id?: number | null;
  3218. }
  3219. // GitHub Backup types
  3220. export type ScheduleType = 'hourly' | 'daily' | 'weekly';
  3221. export type GitProviderType = 'github' | 'gitea' | 'forgejo' | 'gitlab';
  3222. /** How many cloud accounts a backup would collect presets from. Counts only —
  3223. * with auth enabled the accounts belong to individual users, so the backup
  3224. * administrator sees how many, never whose. */
  3225. export interface CloudAccountCounts {
  3226. bambu: number;
  3227. orca: number;
  3228. }
  3229. export interface GitHubBackupConfig {
  3230. id: number;
  3231. repository_url: string;
  3232. has_token: boolean;
  3233. branch: string;
  3234. provider: GitProviderType;
  3235. allow_insecure_http: boolean;
  3236. schedule_enabled: boolean;
  3237. schedule_type: ScheduleType;
  3238. backup_kprofiles: boolean;
  3239. backup_cloud_profiles: boolean;
  3240. backup_settings: boolean;
  3241. backup_spools: boolean;
  3242. backup_archives: boolean;
  3243. enabled: boolean;
  3244. last_backup_at: string | null;
  3245. last_backup_status: string | null;
  3246. last_backup_message: string | null;
  3247. last_backup_commit_sha: string | null;
  3248. next_scheduled_run: string | null;
  3249. created_at: string;
  3250. updated_at: string;
  3251. }
  3252. export interface GitHubBackupConfigCreate {
  3253. repository_url: string;
  3254. access_token: string;
  3255. branch?: string;
  3256. provider?: GitProviderType;
  3257. allow_insecure_http?: boolean;
  3258. schedule_enabled?: boolean;
  3259. schedule_type?: ScheduleType;
  3260. backup_kprofiles?: boolean;
  3261. backup_cloud_profiles?: boolean;
  3262. backup_settings?: boolean;
  3263. backup_spools?: boolean;
  3264. backup_archives?: boolean;
  3265. enabled?: boolean;
  3266. }
  3267. export interface GitHubBackupLog {
  3268. id: number;
  3269. config_id: number;
  3270. started_at: string;
  3271. completed_at: string | null;
  3272. status: string;
  3273. trigger: string;
  3274. commit_sha: string | null;
  3275. files_changed: number;
  3276. error_message: string | null;
  3277. }
  3278. export interface GitHubBackupStatus {
  3279. configured: boolean;
  3280. enabled: boolean;
  3281. is_running: boolean;
  3282. restore_running: boolean;
  3283. progress: string | null;
  3284. last_backup_at: string | null;
  3285. last_backup_status: string | null;
  3286. next_scheduled_run: string | null;
  3287. }
  3288. // Restore from a Git backup (#2656). Cloud profiles are absent deliberately —
  3289. // the backup collector never writes them, so there is nothing to restore.
  3290. export type RestoreCategory = 'kprofiles' | 'settings' | 'spools' | 'archives';
  3291. export interface GitHubCommitInfo {
  3292. sha: string;
  3293. message: string;
  3294. author: string;
  3295. date: string;
  3296. }
  3297. export interface GitHubCommitListResponse {
  3298. success: boolean;
  3299. message: string;
  3300. branch: string;
  3301. commits: GitHubCommitInfo[];
  3302. }
  3303. /**
  3304. * Values the server interpolates into a translated note or preview detail.
  3305. * Kept to strings and numbers on purpose — anything richer would have to be
  3306. * formatted server-side and could not be translated.
  3307. */
  3308. export type GitHubRestoreParams = Record<string, string | number>;
  3309. export interface GitHubRestorePreviewCategory {
  3310. category: RestoreCategory;
  3311. available: boolean;
  3312. item_count: number;
  3313. /** English rendering. Used as i18next's defaultValue, never shown on its own. */
  3314. detail: string | null;
  3315. /** Key under backup.restoreFromGit.details, or null when there is no caveat. */
  3316. detail_code: string | null;
  3317. detail_params: GitHubRestoreParams;
  3318. }
  3319. export interface GitHubRestorePreview {
  3320. success: boolean;
  3321. message: string;
  3322. ref: string;
  3323. commit: GitHubCommitInfo | null;
  3324. metadata_version: string | null;
  3325. categories: GitHubRestorePreviewCategory[];
  3326. }
  3327. export interface GitHubRestoreRequest {
  3328. ref?: string;
  3329. categories: RestoreCategory[];
  3330. overwrite_existing?: boolean;
  3331. }
  3332. /**
  3333. * One tally note, as a translation code plus its parameters (#2656).
  3334. *
  3335. * Same contract as {@link LocalBackupPathCheck} one card down: the server picks
  3336. * the code and supplies typed params, and the client renders
  3337. * ``t(`backup.restoreFromGit.notes.${code}`, { ...params, defaultValue: message })``.
  3338. * A code the client does not know yet falls back to the English `message`
  3339. * rather than showing the raw key.
  3340. */
  3341. export interface GitHubRestoreNote {
  3342. code: string;
  3343. params: GitHubRestoreParams;
  3344. message: string;
  3345. }
  3346. export interface GitHubRestoreCategoryResult {
  3347. restored: number;
  3348. skipped: number;
  3349. failed: number;
  3350. notes: GitHubRestoreNote[];
  3351. }
  3352. export interface GitHubRestoreResponse {
  3353. success: boolean;
  3354. message: string;
  3355. log_id: number | null;
  3356. ref: string | null;
  3357. results: Record<string, GitHubRestoreCategoryResult>;
  3358. }
  3359. export interface LocalBackupStatus {
  3360. enabled: boolean;
  3361. schedule: string;
  3362. time: string;
  3363. retention: number;
  3364. path: string;
  3365. default_path: string;
  3366. is_running: boolean;
  3367. last_backup_at: string | null;
  3368. last_status: string | null;
  3369. last_message: string | null;
  3370. next_run: string | null;
  3371. timezone: string;
  3372. }
  3373. export interface LocalBackupFile {
  3374. filename: string;
  3375. size: number;
  3376. created_at: string;
  3377. }
  3378. /** Result of writing a probe file into the configured backup directory (#2544). */
  3379. export interface LocalBackupPathCheck {
  3380. writable: boolean;
  3381. path: string;
  3382. /** 'ok' | 'sandboxed' | 'read_only' | 'permission_denied' | 'no_space' | 'not_a_directory' | 'missing' | 'error' */
  3383. code: string;
  3384. /** Raw OS error, shown as-is under the translated explanation. */
  3385. detail: string | null;
  3386. /** Copy-pasteable fix (systemd drop-in, compose snippet) — not translated. */
  3387. remedy: string | null;
  3388. message: string;
  3389. /** 'container_ephemeral' — writable, but the backups die with the container. */
  3390. warning: string | null;
  3391. }
  3392. export interface ObicoDetectionEvent {
  3393. printer_id: number;
  3394. task_name: string;
  3395. timestamp: string;
  3396. current_p: number;
  3397. score: number;
  3398. class: 'safe' | 'warning' | 'failure';
  3399. detections: number;
  3400. }
  3401. export interface ObicoStatus {
  3402. is_running: boolean;
  3403. last_error: string | null;
  3404. per_printer: Record<string, { class: string; frame_count: number; score: number }>;
  3405. thresholds: { low: number; high: number };
  3406. history: ObicoDetectionEvent[];
  3407. enabled: boolean;
  3408. ml_url: string;
  3409. sensitivity: 'low' | 'medium' | 'high';
  3410. action: 'notify' | 'pause' | 'pause_and_off';
  3411. poll_interval: number;
  3412. external_url_configured: boolean;
  3413. }
  3414. // Lightweight subset served under printers:read for the printer-card badge (#1546)
  3415. export interface ObicoPrinterStatus {
  3416. enabled: boolean;
  3417. // null = all printers are monitored
  3418. monitored_printers: number[] | null;
  3419. per_printer: Record<string, { class: string; frame_count: number; score: number }>;
  3420. // null = no error, or the viewer lacks settings:read (error strings can embed config URLs)
  3421. last_error: string | null;
  3422. }
  3423. export interface ObicoTestConnection {
  3424. ok: boolean;
  3425. status_code: number | null;
  3426. body: string | null;
  3427. error: string | null;
  3428. // Whether the ML API accepted the token. null = not determined (the health
  3429. // check failed first, or the token probe itself errored).
  3430. auth_ok: boolean | null;
  3431. }
  3432. // How sure Gadget must be before suggesting a warning or pause (API levels 1-5).
  3433. export type OctoEverywhereConfidence = 'lowest' | 'low' | 'medium' | 'high' | 'highest';
  3434. export interface OctoEverywhereDetection {
  3435. class: 'safe' | 'warning' | 'failure' | 'error' | 'unknown';
  3436. print_quality: number | null;
  3437. frame_count: number;
  3438. error?: string | null;
  3439. error_code: string | null;
  3440. }
  3441. export interface OctoEverywhereDetectionEvent {
  3442. timestamp: string;
  3443. printer_id: number;
  3444. class: OctoEverywhereDetection['class'];
  3445. print_quality: number | null;
  3446. }
  3447. export interface OctoEverywhereStatus {
  3448. enabled: boolean;
  3449. api_key_configured: boolean;
  3450. confidence: OctoEverywhereConfidence;
  3451. action: 'notify' | 'pause' | 'pause_and_off';
  3452. poll_interval: number;
  3453. is_running: boolean;
  3454. last_error: string | null;
  3455. last_error_code: string | null;
  3456. per_printer: Record<string, OctoEverywhereDetection>;
  3457. history: OctoEverywhereDetectionEvent[];
  3458. notifications: { configured: boolean; uncovered_printers: number[] };
  3459. }
  3460. export interface OctoEverywherePrinterStatus {
  3461. enabled: boolean;
  3462. // null = all printers are monitored
  3463. monitored_printers: number[] | null;
  3464. per_printer: Record<string, OctoEverywhereDetection>;
  3465. last_error: string | null;
  3466. last_error_code: string | null;
  3467. }
  3468. export interface OctoEverywhereTestConnection {
  3469. ok: boolean;
  3470. status_code: number | null;
  3471. error: string | null;
  3472. error_code: string | null;
  3473. }
  3474. export interface GitHubTestConnectionResponse {
  3475. success: boolean;
  3476. message: string;
  3477. repo_name: string | null;
  3478. permissions: Record<string, boolean> | null;
  3479. // true = confirmed private, false = confirmed public/internal,
  3480. // null = could not determine. Backend rejects save unless true.
  3481. is_private: boolean | null;
  3482. }
  3483. export interface GitHubBackupTriggerResponse {
  3484. success: boolean;
  3485. message: string;
  3486. log_id: number | null;
  3487. commit_sha: string | null;
  3488. files_changed: number;
  3489. }
  3490. export interface NotificationTestRequest {
  3491. provider_type: ProviderType;
  3492. config: Record<string, unknown>;
  3493. attach_photo?: boolean;
  3494. /** The saved provider being edited: its stored secrets fill in the placeholders. */
  3495. provider_id?: number;
  3496. }
  3497. export interface NotificationTestResponse {
  3498. success: boolean;
  3499. message: string;
  3500. }
  3501. // Provider-specific config types for reference
  3502. export interface CallMeBotConfig {
  3503. phone: string;
  3504. apikey: string;
  3505. }
  3506. export interface NtfyConfig {
  3507. server?: string;
  3508. topic: string;
  3509. auth_token?: string | null;
  3510. }
  3511. export interface PushoverConfig {
  3512. user_key: string;
  3513. app_token: string;
  3514. priority?: number;
  3515. }
  3516. export interface NotifyConfig {
  3517. device_id: string;
  3518. token: string;
  3519. icon_url?: string;
  3520. group_type?: string;
  3521. live_activities?: boolean;
  3522. lock_screen_widgets?: boolean;
  3523. live_activity_privacy?: boolean;
  3524. live_activity_stage?: boolean;
  3525. live_activity_style?: 'bar' | 'segments' | 'none';
  3526. live_activity_metrics?: ('progress' | 'eta' | 'layers' | 'nozzle' | 'bed' | 'chamber')[];
  3527. live_activity_button_url?: string;
  3528. live_activity_symbol?: string;
  3529. live_activity_tint?: string;
  3530. time_sensitive?: boolean;
  3531. }
  3532. export interface TelegramConfig {
  3533. bot_token: string;
  3534. chat_id: string;
  3535. }
  3536. export interface EmailConfig {
  3537. smtp_server: string;
  3538. smtp_port?: number;
  3539. username: string;
  3540. password: string;
  3541. from_email: string;
  3542. to_email: string;
  3543. use_tls?: boolean;
  3544. }
  3545. // Notification Template types
  3546. export interface NotificationTemplate {
  3547. id: number;
  3548. event_type: string;
  3549. name: string;
  3550. title_template: string;
  3551. body_template: string;
  3552. is_default: boolean;
  3553. created_at: string;
  3554. updated_at: string;
  3555. }
  3556. export interface NotificationTemplateUpdate {
  3557. title_template?: string;
  3558. body_template?: string;
  3559. }
  3560. export interface EventVariablesResponse {
  3561. event_type: string;
  3562. event_name: string;
  3563. variables: string[];
  3564. supports_photo: boolean;
  3565. }
  3566. export interface TemplatePreviewRequest {
  3567. event_type: string;
  3568. title_template: string;
  3569. body_template: string;
  3570. }
  3571. export interface TemplatePreviewResponse {
  3572. title: string;
  3573. body: string;
  3574. }
  3575. // Notification Log types
  3576. export interface NotificationLogEntry {
  3577. id: number;
  3578. provider_id: number;
  3579. provider_name: string | null;
  3580. provider_type: string | null;
  3581. event_type: string;
  3582. title: string;
  3583. message: string;
  3584. success: boolean;
  3585. error_message: string | null;
  3586. printer_id: number | null;
  3587. printer_name: string | null;
  3588. created_at: string;
  3589. }
  3590. export interface NotificationLogStats {
  3591. total: number;
  3592. success_count: number;
  3593. failure_count: number;
  3594. by_event_type: Record<string, number>;
  3595. by_provider: Record<string, number>;
  3596. }
  3597. // Spoolman types
  3598. export interface SpoolmanStatus {
  3599. enabled: boolean;
  3600. connected: boolean;
  3601. url: string | null;
  3602. native_tags?: boolean; // Spoolman 0.27+ links tags natively
  3603. }
  3604. export interface SpoolmanTagMigrationReport {
  3605. dry_run: boolean;
  3606. moved: number[];
  3607. already: number;
  3608. slot_ids: number;
  3609. conflicts: Array<{ spool_id: number; tag: string; holder: number }>; // holder -1: a filament holds the tag
  3610. }
  3611. export interface SkippedSpool {
  3612. location: string;
  3613. reason: string;
  3614. filament_type: string | null;
  3615. color: string | null;
  3616. }
  3617. export interface SpoolmanSyncResult {
  3618. success: boolean;
  3619. synced_count: number;
  3620. skipped_count: number;
  3621. skipped: SkippedSpool[];
  3622. errors: string[];
  3623. }
  3624. export interface UnlinkedSpool {
  3625. id: number;
  3626. filament_name: string | null;
  3627. filament_vendor: string | null;
  3628. filament_material: string | null;
  3629. filament_color_hex: string | null;
  3630. remaining_weight: number | null;
  3631. location: string | null;
  3632. }
  3633. export interface LinkedSpoolInfo {
  3634. id: number;
  3635. remaining_weight: number | null;
  3636. filament_weight: number | null;
  3637. }
  3638. export interface LinkedSpoolsMap {
  3639. linked: Record<string, LinkedSpoolInfo>; // tag (uppercase) -> spool info
  3640. }
  3641. export interface SpoolmanVendor {
  3642. id: number;
  3643. name: string;
  3644. }
  3645. export interface SpoolmanFilamentEntry {
  3646. id: number;
  3647. name: string;
  3648. material: string | null;
  3649. color_hex: string | null;
  3650. color_name: string | null;
  3651. weight: number | null;
  3652. spool_weight: number | null;
  3653. vendor: SpoolmanVendor | null;
  3654. }
  3655. // Inventory types
  3656. // Label printing (#809). Mirror of backend.app.services.label_renderer.TemplateName.
  3657. export type SpoolLabelTemplate =
  3658. | 'ams_holder_74x33'
  3659. | 'ams_holder_75x55'
  3660. | 'box_40x30'
  3661. | 'box_62x29'
  3662. | 'avery_5160'
  3663. | 'avery_l7160';
  3664. // Mirror of backend.app.services.label_renderer.LabelField, in print order (#2981).
  3665. export const SPOOL_LABEL_FIELDS = [
  3666. 'brand',
  3667. 'material',
  3668. 'hex',
  3669. 'name',
  3670. 'location',
  3671. 'material_number',
  3672. 'temps',
  3673. 'weight',
  3674. 'note',
  3675. 'added',
  3676. 'qr',
  3677. 'spool_id',
  3678. ] as const;
  3679. export type SpoolLabelField = (typeof SPOOL_LABEL_FIELDS)[number];
  3680. // Mirror of DEFAULT_LABEL_FIELDS: what a label carried before fields were selectable.
  3681. export const DEFAULT_SPOOL_LABEL_FIELDS: SpoolLabelField[] = [
  3682. 'brand',
  3683. 'material',
  3684. 'hex',
  3685. 'name',
  3686. 'location',
  3687. 'qr',
  3688. 'spool_id',
  3689. ];
  3690. // A sheet of identical labels in a grid, in millimetres (#3296). Mirror of
  3691. // backend.app.schemas.label_template.SheetLayoutSpec.
  3692. export type LabelPageSize = 'a4' | 'letter';
  3693. export interface LabelSheetLayout {
  3694. page: LabelPageSize;
  3695. label_w_mm: number;
  3696. label_h_mm: number;
  3697. cols: number;
  3698. rows: number;
  3699. top_mm: number;
  3700. left_mm: number;
  3701. col_gap_mm: number;
  3702. row_gap_mm: number;
  3703. }
  3704. // A custom sheet saved under a name, shared by everyone on the install.
  3705. export interface SavedLabelTemplate {
  3706. id: number;
  3707. name: string;
  3708. layout: LabelSheetLayout;
  3709. created_at: string;
  3710. updated_at: string;
  3711. }
  3712. // A built-in template, or "custom" with the sheet itself in ``layout``.
  3713. export type SpoolLabelRequestTemplate = SpoolLabelTemplate | 'custom';
  3714. export interface PrintSpoolLabelsRequest {
  3715. spool_ids: number[];
  3716. template: SpoolLabelRequestTemplate;
  3717. layout?: LabelSheetLayout;
  3718. monochrome: boolean;
  3719. starting_position: number;
  3720. fields?: SpoolLabelField[];
  3721. format?: 'pdf' | 'png';
  3722. dpi?: 203 | 300 | 600;
  3723. }
  3724. export interface PreviewSpoolLabelRequest {
  3725. spool_id: number;
  3726. template: SpoolLabelRequestTemplate;
  3727. layout?: LabelSheetLayout;
  3728. monochrome: boolean;
  3729. fields: SpoolLabelField[];
  3730. }
  3731. export interface InventorySpool {
  3732. id: number;
  3733. material: string;
  3734. subtype: string | null;
  3735. color_name: string | null;
  3736. // True when color_name was synthesised from subtype because Spoolman has no
  3737. // stored value (Spoolman-backed inventory only). The edit form uses this to
  3738. // leave the input blank, so the user doesn't round-trip the synth value
  3739. // back to Spoolman as if it were a real user-set color_name (#1319).
  3740. color_name_is_synthesized?: boolean;
  3741. rgba: string | null;
  3742. // Multi-colour gradient stops (#1154): comma-separated 6/8-char hex.
  3743. extra_colors: string | null;
  3744. // Visual effect overlay: sparkle | wood | marble | glow | matte.
  3745. effect_type: string | null;
  3746. brand: string | null;
  3747. label_weight: number;
  3748. core_weight: number;
  3749. // Spoolman-backed inventory only: true when the spool has no tare of its
  3750. // own and core_weight is the filament type's. Absent for local spools (#2908).
  3751. core_weight_is_inherited?: boolean;
  3752. core_weight_catalog_id: number | null;
  3753. weight_used: number;
  3754. // Anchor for the resettable "Total Consumed" display (#1390). The
  3755. // counter shown on the Inventory page is `weight_used - weight_used_baseline`;
  3756. // remaining is still `label_weight - weight_used`, so "Reset usage to 0"
  3757. // zeroes the counter without disturbing remaining. Optional for back-compat
  3758. // with rows from a pre-migration DB snapshot — default to 0.
  3759. weight_used_baseline?: number;
  3760. slicer_filament: string | null;
  3761. slicer_filament_name: string | null;
  3762. nozzle_temp_min: number | null;
  3763. nozzle_temp_max: number | null;
  3764. note: string | null;
  3765. added_full: boolean | null;
  3766. last_used: string | null;
  3767. // Spoolman mode: when the spool was first printed with (#3407).
  3768. first_used?: string | null;
  3769. // Last drying (#2863): stamped when an AMS drying run of at least half its
  3770. // length ends, or set by hand. Temperature and hours are null when unknown.
  3771. last_dried_at?: string | null;
  3772. last_dried_temp?: number | null;
  3773. last_dried_hours?: number | null;
  3774. encode_time: string | null;
  3775. tag_uid: string | null;
  3776. tray_uuid: string | null;
  3777. data_origin: string | null;
  3778. tag_type: string | null;
  3779. archived_at: string | null;
  3780. created_at: string;
  3781. updated_at: string;
  3782. cost_per_kg: number | null;
  3783. // Spoolman mode: what prints are charged per kg, the spool's own price or
  3784. // else its filament's. Display only; the form edits cost_per_kg.
  3785. effective_cost_per_kg?: number | null;
  3786. last_scale_weight: number | null;
  3787. last_weighed_at: string | null;
  3788. // User-defined category + per-spool low-stock threshold override (#729).
  3789. category: string | null;
  3790. low_stock_threshold_pct: number | null;
  3791. // Internal material / article number (#2870) — the purchasing identifier
  3792. // shared by all spools of the same product.
  3793. material_number: string | null;
  3794. k_profiles?: SpoolKProfile[];
  3795. storage_location?: string | null;
  3796. location_id?: number | null;
  3797. // Supplier assignments (#2988). Absent in Spoolman mode — Spoolman's
  3798. // vendor is the manufacturer, not the seller, so there is no mapping.
  3799. suppliers?: SpoolSupplierLink[];
  3800. }
  3801. // ── Suppliers (#2988) ──────────────────────────────────────────────────────
  3802. /** Where filament is bought — distinct from brand (who made it). */
  3803. export interface Supplier {
  3804. id: number;
  3805. name: string;
  3806. website: string | null;
  3807. customer_number: string | null;
  3808. note: string | null;
  3809. /** Spools referencing this supplier; a referenced supplier cannot be deleted. */
  3810. spool_count: number;
  3811. created_at: string;
  3812. updated_at: string;
  3813. }
  3814. export interface SupplierInput {
  3815. name: string;
  3816. website?: string | null;
  3817. customer_number?: string | null;
  3818. note?: string | null;
  3819. }
  3820. /** One spool-to-supplier assignment as written by the spool dialog. */
  3821. export interface SpoolSupplierLinkInput {
  3822. supplier_id: number;
  3823. /** The supplier's own article number — NOT the internal material number. */
  3824. supplier_article_number?: string | null;
  3825. /** Quoted price for comparison — never the cost basis (spool.cost_per_kg). */
  3826. quoted_price_per_kg?: number | null;
  3827. /** Marks where this concrete spool was actually bought. */
  3828. is_purchase_source?: boolean;
  3829. }
  3830. export interface SpoolSupplierLink {
  3831. id: number;
  3832. supplier_id: number;
  3833. supplier_name: string;
  3834. supplier_article_number: string | null;
  3835. quoted_price_per_kg: number | null;
  3836. is_purchase_source: boolean;
  3837. }
  3838. /** Per-supplier inventory aggregate (#2988), purchase-source spools only. */
  3839. export interface SupplierStats {
  3840. supplier_id: number;
  3841. supplier_name: string;
  3842. spool_count: number;
  3843. remaining_g: number;
  3844. consumed_g: number;
  3845. cost: number;
  3846. }
  3847. /** Per-material-number inventory aggregate (#2870). */
  3848. export interface MaterialNumberStats {
  3849. material_number: string;
  3850. spool_count: number;
  3851. remaining_g: number;
  3852. consumed_g: number;
  3853. cost: number;
  3854. }
  3855. export interface SpoolmanBulkCreateResult {
  3856. created: InventorySpool[];
  3857. requested_count: number;
  3858. failed_count: number;
  3859. }
  3860. // ── CSV import/export (#1576) ──────────────────────────────────────────────
  3861. /** One row's outcome from the import preview / real import. */
  3862. export interface CsvImportRow {
  3863. row_number: number;
  3864. status: 'valid' | 'error' | 'skipped';
  3865. reason: string | null;
  3866. material: string | null;
  3867. brand: string | null;
  3868. color_name: string | null;
  3869. rgba: string | null;
  3870. /** rgba/extra_colors/effect_type were filled from the Color Catalog. */
  3871. resolved_color: boolean;
  3872. /** The catalog match came from a different material's variant (no exact
  3873. * material match). Shown as a warning in the preview. */
  3874. cross_material_color: boolean;
  3875. /** An active spool with the same material+brand+color already exists.
  3876. * Informational only — the import still creates the row. */
  3877. duplicate_of_existing: boolean;
  3878. }
  3879. /** Dry-run preview: per-row classification, no rows written. */
  3880. export interface CsvImportPreview {
  3881. columns: string[];
  3882. total: number;
  3883. valid_count: number;
  3884. error_count: number;
  3885. skipped_count: number;
  3886. rows: CsvImportRow[];
  3887. warnings: string[];
  3888. }
  3889. /** Summary returned after a real (non-dry-run) import. */
  3890. export interface CsvImportResult {
  3891. created: number;
  3892. skipped: number;
  3893. errors: number;
  3894. error_rows: CsvImportRow[];
  3895. }
  3896. export interface SpoolUsageRecord {
  3897. id: number;
  3898. // null: the spool was deleted, its usage kept
  3899. spool_id: number | null;
  3900. // Spoolman mode: the Spoolman spool charged (#3407); spool_id is null then.
  3901. spoolman_spool_id?: number | null;
  3902. printer_id: number | null;
  3903. print_name: string | null;
  3904. weight_used: number;
  3905. percent_used: number;
  3906. status: string;
  3907. cost: number | null;
  3908. created_at: string;
  3909. }
  3910. export interface SpoolKProfile {
  3911. id: number;
  3912. spool_id: number;
  3913. printer_id: number;
  3914. extruder: number;
  3915. nozzle_diameter: string;
  3916. nozzle_type: string | null;
  3917. k_value: number;
  3918. name: string | null;
  3919. cali_idx: number | null;
  3920. setting_id: string | null;
  3921. created_at: string;
  3922. }
  3923. export interface SpoolKProfileInput {
  3924. printer_id: number;
  3925. extruder?: number;
  3926. nozzle_diameter?: string;
  3927. nozzle_type?: string | null;
  3928. k_value: number;
  3929. name?: string | null;
  3930. cali_idx?: number | null;
  3931. setting_id?: string | null;
  3932. }
  3933. /**
  3934. * One per-printer-model override of a spool's slicer filament preset.
  3935. *
  3936. * A cloud or Orca preset is bound to a printer model ("@BBL X1C"), so the
  3937. * spool's single `slicer_filament` is wrong as soon as the spool is used on a
  3938. * second model. `nozzle_diameter` is "" for the model's own default and a bare
  3939. * decimal ("0.2") for a per-hotend exception; the backend resolves
  3940. * exact (model, diameter) -> (model, "") -> the spool's own preset.
  3941. */
  3942. export interface SlotSpoolDefaults {
  3943. slicer_filament: string | null;
  3944. slicer_filament_name: string | null;
  3945. cali_idx: number | null;
  3946. k_value: number | null;
  3947. profile_name: string | null;
  3948. extruder: number | null;
  3949. nozzle_diameter: string;
  3950. }
  3951. export interface SpoolFilamentPresetInput {
  3952. printer_model: string;
  3953. nozzle_diameter: string;
  3954. slicer_filament: string | null;
  3955. slicer_filament_name: string | null;
  3956. }
  3957. export interface SpoolFilamentPreset extends SpoolFilamentPresetInput {
  3958. id: number;
  3959. spool_id: number;
  3960. created_at: string;
  3961. }
  3962. /**
  3963. * What a new spool of one product starts with (#1326): the slicer preset, the
  3964. * per-model preset overrides and the K profiles. `color_name` "" is the
  3965. * default for every colour of the product; one with a colour wins over it per
  3966. * preset and per hotend. Shared by both inventory modes.
  3967. */
  3968. export interface ProfileDefaultKey {
  3969. brand: string;
  3970. material: string;
  3971. subtype: string;
  3972. color_name: string;
  3973. }
  3974. export interface ProfileDefaultInput extends ProfileDefaultKey {
  3975. slicer_filament: string | null;
  3976. slicer_filament_name: string | null;
  3977. presets: SpoolFilamentPresetInput[];
  3978. k_profiles: SpoolKProfileInput[];
  3979. }
  3980. export interface ProfileDefault extends ProfileDefaultInput {
  3981. id: number;
  3982. updated_at: string;
  3983. }
  3984. /** Both levels of a product's default merged, as a create applies them. */
  3985. export interface ResolvedProfileDefault {
  3986. slicer_filament: string | null;
  3987. slicer_filament_name: string | null;
  3988. presets: SpoolFilamentPresetInput[];
  3989. k_profiles: SpoolKProfileInput[];
  3990. default_ids: number[];
  3991. }
  3992. /** One inventory-bound AMS slot, as returned by `/printers/{id}/inventory-remain`. */
  3993. export interface SlotMaterial {
  3994. ams_id: number;
  3995. tray_id: number;
  3996. global_tray_id: number;
  3997. /** Opaque grouping key from the backend. Two slots back each other up under
  3998. * AMS Filament Backup only when both `material_key` and `extruder` match.
  3999. * Never parse it — the format belongs to the backend's identity rule. */
  4000. material_key: string;
  4001. remaining_g: number;
  4002. /** 0 = right / single nozzle, 1 = left. */
  4003. extruder: number;
  4004. /** How the bound spool should be *named* — display only, never matched on.
  4005. * The printer has no brand field and reports no sub-brand for a
  4006. * third-party spool, so this is the only place a slot's real identity
  4007. * exists. Null when the binding resolves to a spool we cannot describe. */
  4008. spool?: SlotSpoolIdentity | null;
  4009. /** Per-kg rate a print off this spool is charged at; null when unpriced,
  4010. * which is charged at the default rate. Optional for an older backend. */
  4011. cost_per_kg?: number | null;
  4012. }
  4013. /** Display identity of an inventory-bound slot. See `SlotMaterial.spool`. */
  4014. export interface SlotSpoolIdentity {
  4015. brand: string | null;
  4016. material: string | null;
  4017. subtype: string | null;
  4018. color_name: string | null;
  4019. rgba: string | null;
  4020. /** Comma-separated hex stops for a multi-colour spool, and the effect
  4021. * overlay — the two things a tray record cannot carry, so a slot swatch
  4022. * can be drawn the way the inventory row draws it (#3159).
  4023. *
  4024. * Optional rather than required: the backend sends both keys on every
  4025. * binding, but a frontend running against an older one gets neither, and
  4026. * every reader here already falls back to a solid swatch. */
  4027. extra_colors?: string | null;
  4028. effect_type?: string | null;
  4029. }
  4030. export interface InventoryRemainResponse {
  4031. /** Currently-loaded, inventory-bound slots only — drives the prefer-lowest sort. */
  4032. inventory_remain_g: Record<string, number>;
  4033. /** Every inventory binding on the printer, with identity + extruder side. */
  4034. slot_materials: SlotMaterial[];
  4035. }
  4036. export interface SpoolAssignment {
  4037. id: number;
  4038. spool_id: number;
  4039. printer_id: number;
  4040. printer_name: string | null;
  4041. ams_id: number;
  4042. tray_id: number;
  4043. fingerprint_color: string | null;
  4044. fingerprint_type: string | null;
  4045. spool?: InventorySpool | null;
  4046. configured: boolean;
  4047. pending_config?: boolean; // Slot was empty at assign time; will configure on insert
  4048. created_at: string;
  4049. ams_label?: string | null; // User-defined friendly name for the AMS unit
  4050. }
  4051. export interface FilamentSkuSettings {
  4052. id: number;
  4053. material: string;
  4054. subtype: string | null;
  4055. brand: string | null;
  4056. color_name: string | null;
  4057. lead_time_days: number;
  4058. safety_margin_value: number;
  4059. safety_margin_unit: 'days' | 'g';
  4060. alerts_snoozed: boolean;
  4061. }
  4062. export interface ShoppingListItem {
  4063. id: number;
  4064. material: string;
  4065. subtype: string | null;
  4066. brand: string | null;
  4067. color_name: string | null;
  4068. quantity_spools: number;
  4069. note: string | null;
  4070. status: 'pending' | 'purchased' | 'received';
  4071. purchased_at: string | null;
  4072. added_at: string;
  4073. }
  4074. export interface ShoppingListItemCreate {
  4075. material: string;
  4076. subtype: string | null;
  4077. brand: string | null;
  4078. color_name: string | null;
  4079. quantity_spools: number;
  4080. note?: string | null;
  4081. }
  4082. // Update types
  4083. export interface VersionInfo {
  4084. version: string;
  4085. repo: string;
  4086. }
  4087. export interface UpdateCheckResult {
  4088. update_available: boolean;
  4089. current_version: string;
  4090. latest_version: string | null;
  4091. release_name?: string;
  4092. release_notes?: string;
  4093. release_url?: string;
  4094. published_at?: string;
  4095. error?: string;
  4096. message?: string;
  4097. is_docker?: boolean;
  4098. is_ha_addon?: boolean;
  4099. is_windows_installer?: boolean;
  4100. update_method?: 'docker' | 'git' | 'ha_addon' | 'windows_installer';
  4101. installer_download_url?: string | null;
  4102. // Best-effort guess at the compose directory (#2664). Prefill only — the
  4103. // value the user saved lives on AppSettings.docker_compose_dir, so clearing
  4104. // that field falls back to this guess instead of resurrecting the old value.
  4105. compose_dir_detected?: string | null;
  4106. }
  4107. export interface UpdateStatus {
  4108. status: 'idle' | 'checking' | 'downloading' | 'installing' | 'complete' | 'error';
  4109. progress: number;
  4110. message: string;
  4111. error: string | null;
  4112. }
  4113. // Maintenance types
  4114. export interface MaintenanceType {
  4115. id: number;
  4116. name: string;
  4117. description: string | null;
  4118. default_interval_hours: number;
  4119. interval_type: 'hours' | 'days'; // "hours" = print hours, "days" = calendar days
  4120. icon: string | null;
  4121. wiki_url: string | null; // Documentation link
  4122. is_system: boolean;
  4123. created_at: string;
  4124. }
  4125. export interface MaintenanceTypeCreate {
  4126. name: string;
  4127. description?: string | null;
  4128. default_interval_hours?: number;
  4129. interval_type?: 'hours' | 'days';
  4130. icon?: string | null;
  4131. wiki_url?: string | null;
  4132. }
  4133. export interface MaintenanceStatus {
  4134. id: number;
  4135. printer_id: number;
  4136. printer_name: string;
  4137. printer_model: string | null;
  4138. maintenance_type_id: number;
  4139. maintenance_type_name: string;
  4140. maintenance_type_icon: string | null;
  4141. maintenance_type_wiki_url: string | null; // Custom wiki URL from type
  4142. enabled: boolean;
  4143. interval_hours: number; // For hours type: print hours; for days type: number of days
  4144. interval_type: 'hours' | 'days';
  4145. current_hours: number;
  4146. hours_since_maintenance: number;
  4147. hours_until_due: number;
  4148. days_since_maintenance: number | null; // For days type
  4149. days_until_due: number | null; // For days type
  4150. is_due: boolean;
  4151. is_warning: boolean;
  4152. last_performed_at: string | null;
  4153. }
  4154. export interface PrinterMaintenanceOverview {
  4155. printer_id: number;
  4156. printer_name: string;
  4157. printer_model: string | null;
  4158. total_print_hours: number;
  4159. maintenance_items: MaintenanceStatus[];
  4160. due_count: number;
  4161. warning_count: number;
  4162. }
  4163. // External Links (sidebar)
  4164. export interface ExternalLink {
  4165. id: number;
  4166. name: string;
  4167. url: string;
  4168. icon: string;
  4169. open_in_new_tab: boolean;
  4170. custom_icon: string | null;
  4171. sort_order: number;
  4172. created_at: string;
  4173. updated_at: string;
  4174. /** Count reported by the app the link points to, while it keeps reporting. */
  4175. badge_count?: number | null;
  4176. }
  4177. export interface ExternalLinkCreate {
  4178. name: string;
  4179. url: string;
  4180. icon: string;
  4181. open_in_new_tab?: boolean;
  4182. }
  4183. export interface ExternalLinkUpdate {
  4184. name?: string;
  4185. url?: string;
  4186. icon?: string;
  4187. open_in_new_tab?: boolean;
  4188. }
  4189. // Finance types
  4190. export interface CostCenterSummary {
  4191. id: number;
  4192. name: string;
  4193. is_private: boolean;
  4194. owner_user_id: number | null;
  4195. is_active: boolean;
  4196. total_balance: number;
  4197. total_budget: number | null;
  4198. monthly_budget: number | null;
  4199. budget_mode: 'none' | 'total' | 'monthly';
  4200. budget_limit: number | null;
  4201. budget_used: number | null;
  4202. budget_available: number | null;
  4203. can_print: boolean;
  4204. }
  4205. export interface CostCenterCreateRequest {
  4206. name: string;
  4207. total_budget?: number | null;
  4208. monthly_budget?: number | null;
  4209. is_active?: boolean;
  4210. }
  4211. export interface CostCenterBudgetUpdateRequest {
  4212. total_budget?: number | null;
  4213. monthly_budget?: number | null;
  4214. }
  4215. export interface CostCenterUpdateRequest {
  4216. name?: string;
  4217. is_active?: boolean;
  4218. }
  4219. export interface CostCenterMemberRequest {
  4220. user_id: number;
  4221. can_print?: boolean;
  4222. }
  4223. export interface CostCenterMemberResponse {
  4224. id: number;
  4225. cost_center_id: number;
  4226. user_id: number;
  4227. can_print: boolean;
  4228. created_at: string;
  4229. }
  4230. export interface CostCenterDetail extends CostCenterSummary {
  4231. members: CostCenterMemberResponse[];
  4232. }
  4233. export interface WalletBalance {
  4234. user_id: number;
  4235. balance: number;
  4236. currency: string;
  4237. updated_at: string | null;
  4238. }
  4239. export type WalletTransactionType = 'print_charge' | 'deposit' | 'withdraw' | 'manual_adjustment';
  4240. export interface WalletTransaction {
  4241. id: number;
  4242. user_id: number | null; // null once the user is deleted
  4243. cost_center_id: number | null;
  4244. transaction_type: WalletTransactionType;
  4245. amount: number;
  4246. balance_after: number | null;
  4247. description: string | null;
  4248. created_by_user_id: number | null;
  4249. print_run_id: string | null;
  4250. print_archive_id: number | null;
  4251. print_queue_id: number | null;
  4252. created_at: string;
  4253. }
  4254. export interface WalletTransactionListResponse {
  4255. items: WalletTransaction[];
  4256. total: number;
  4257. limit: number;
  4258. offset: number;
  4259. }
  4260. export interface WalletAdjustmentRequest {
  4261. amount: number;
  4262. description?: string;
  4263. cost_center_id?: number | null;
  4264. }
  4265. export interface WalletAdjustmentResponse {
  4266. transaction: WalletTransaction;
  4267. balance: WalletBalance;
  4268. }
  4269. export interface TransactionEditRequest {
  4270. user_id?: number | null;
  4271. cost_center_id?: number | null;
  4272. amount?: number | null;
  4273. description?: string | null;
  4274. }
  4275. export interface ManualPrintRequest {
  4276. user_id: number;
  4277. cost_center_id: number;
  4278. amount: number;
  4279. description?: string | null;
  4280. created_at?: string | null;
  4281. }
  4282. // Permission type - all available permissions
  4283. export type Permission =
  4284. | 'printers:read' | 'printers:create' | 'printers:update' | 'printers:delete' | 'printers:control' | 'printers:files' | 'printers:ams_rfid' | 'printers:clear_plate'
  4285. | 'archives:read' | 'archives:read_own' | 'archives:read_all' | 'archives:create'
  4286. | 'archives:update_own' | 'archives:update_all' | 'archives:delete_own' | 'archives:delete_all'
  4287. | 'archives:reprint_own' | 'archives:reprint_all' | 'archives:purge'
  4288. | 'queue:read' | 'queue:read_own' | 'queue:read_all' | 'queue:create'
  4289. | 'queue:update_own' | 'queue:update_all' | 'queue:delete_own' | 'queue:delete_all'
  4290. | 'queue:reorder' | 'queue:start_unreviewed'
  4291. | 'library:read' | 'library:read_own' | 'library:read_all' | 'library:upload'
  4292. | 'library:update_own' | 'library:update_all' | 'library:delete_own' | 'library:delete_all'
  4293. | 'library:purge'
  4294. | 'projects:read' | 'projects:create' | 'projects:update' | 'projects:delete'
  4295. | 'filaments:read' | 'filaments:create' | 'filaments:update' | 'filaments:delete'
  4296. | 'inventory:read' | 'inventory:create' | 'inventory:update' | 'inventory:delete' | 'inventory:view_assignments'
  4297. | 'inventory:forecast_read' | 'inventory:forecast_write'
  4298. | 'smart_plugs:read' | 'smart_plugs:create' | 'smart_plugs:update' | 'smart_plugs:delete' | 'smart_plugs:control'
  4299. | 'camera:view'
  4300. | 'maintenance:read' | 'maintenance:create' | 'maintenance:update' | 'maintenance:delete'
  4301. | 'kprofiles:read' | 'kprofiles:create' | 'kprofiles:update' | 'kprofiles:delete'
  4302. | 'notifications:read' | 'notifications:create' | 'notifications:update' | 'notifications:delete' | 'notifications:user_email'
  4303. | 'notification_templates:read' | 'notification_templates:update'
  4304. | 'external_links:read' | 'external_links:create' | 'external_links:update' | 'external_links:delete'
  4305. | 'discovery:scan'
  4306. | 'firmware:read' | 'firmware:update'
  4307. | 'ams_history:read'
  4308. | 'cost_centers:read_own' | 'cost_centers:read_all' | 'cost_centers:modify' | 'cost_centers:create'
  4309. | 'stats:read' | 'stats:filter_by_user'
  4310. | 'system:read'
  4311. | 'settings:read' | 'settings:update' | 'settings:backup' | 'settings:restore'
  4312. | 'github:backup' | 'github:restore'
  4313. | 'cloud:auth' | 'orca_cloud:auth'
  4314. | 'makerworld:view' | 'makerworld:import'
  4315. | 'manyfold:view' | 'manyfold:import'
  4316. | 'api_keys:read' | 'api_keys:create' | 'api_keys:update' | 'api_keys:delete'
  4317. | 'users:read' | 'users:read_slim' | 'users:create' | 'users:update' | 'users:delete'
  4318. | 'groups:read' | 'groups:create' | 'groups:update' | 'groups:delete'
  4319. | 'pipelines:read' | 'pipelines:write' | 'pipelines:run'
  4320. | 'websocket:connect';
  4321. // Group types
  4322. export interface GroupBrief {
  4323. id: number;
  4324. name: string;
  4325. }
  4326. export interface Group {
  4327. id: number;
  4328. name: string;
  4329. description: string | null;
  4330. permissions: Permission[];
  4331. is_system: boolean;
  4332. /** Members only see the printers in printer_ids plus every printer in locations (#1727) */
  4333. restrict_printers: boolean;
  4334. printer_ids: number[];
  4335. /** Matched against Printer.location, so printers added there later are included */
  4336. locations: string[];
  4337. user_count: number;
  4338. created_at: string;
  4339. updated_at: string;
  4340. }
  4341. export interface GroupDetail extends Group {
  4342. users: Array<{ id: number; username: string; is_active: boolean }>;
  4343. }
  4344. export interface GroupCreate {
  4345. name: string;
  4346. description?: string;
  4347. permissions: Permission[];
  4348. restrict_printers?: boolean;
  4349. printer_ids?: number[];
  4350. locations?: string[];
  4351. }
  4352. export interface GroupUpdate {
  4353. name?: string;
  4354. description?: string;
  4355. permissions?: Permission[];
  4356. restrict_printers?: boolean;
  4357. printer_ids?: number[];
  4358. locations?: string[];
  4359. }
  4360. export interface PermissionInfo {
  4361. value: Permission;
  4362. label: string;
  4363. }
  4364. export interface PermissionCategory {
  4365. name: string;
  4366. permissions: PermissionInfo[];
  4367. }
  4368. export interface PermissionsListResponse {
  4369. categories: PermissionCategory[];
  4370. all_permissions: Permission[];
  4371. }
  4372. // User email notification preferences
  4373. export interface UserEmailPreferences {
  4374. notify_print_start: boolean;
  4375. notify_print_complete: boolean;
  4376. notify_print_failed: boolean;
  4377. notify_print_stopped: boolean;
  4378. }
  4379. // Auth types
  4380. export interface LoginRequest {
  4381. username: string;
  4382. password: string;
  4383. }
  4384. export interface LoginResponse {
  4385. access_token?: string;
  4386. token_type?: string;
  4387. user?: UserResponse;
  4388. /** Set when 2FA verification is required before a full token is issued. */
  4389. requires_2fa?: boolean;
  4390. pre_auth_token?: string;
  4391. two_fa_methods?: string[];
  4392. }
  4393. export interface UserResponse {
  4394. id: number;
  4395. username: string;
  4396. email?: string;
  4397. role: string; // Deprecated, kept for backward compatibility
  4398. is_active: boolean;
  4399. is_admin: boolean; // Computed from role and group membership
  4400. auth_source: string; // "local" or "ldap"
  4401. groups: GroupBrief[];
  4402. permissions: Permission[]; // All permissions from groups
  4403. created_at: string;
  4404. }
  4405. /**
  4406. * Just enough to label an owner id (#1894). Backed by GET /users/slim, which
  4407. * is readable with `users:read_slim` as well as the admin-level `users:read`
  4408. * -- use it anywhere a screen only needs to turn a `created_by_id` into a
  4409. * name, so operators are not forced into the full listing to get one.
  4410. */
  4411. export interface UserSlim {
  4412. id: number;
  4413. username: string;
  4414. }
  4415. export interface UserCreate {
  4416. username: string;
  4417. password?: string; // Optional when advanced auth is enabled
  4418. email?: string;
  4419. role: string;
  4420. group_ids?: number[];
  4421. }
  4422. export interface UserUpdate {
  4423. username?: string;
  4424. password?: string;
  4425. email?: string;
  4426. role?: string;
  4427. is_active?: boolean;
  4428. group_ids?: number[];
  4429. }
  4430. export interface SetupRequest {
  4431. auth_enabled: boolean;
  4432. admin_username?: string;
  4433. admin_password?: string;
  4434. }
  4435. export interface ForgotPasswordRequest {
  4436. email: string;
  4437. }
  4438. export interface ForgotPasswordResponse {
  4439. message: string;
  4440. }
  4441. export interface ResetPasswordRequest {
  4442. user_id: number;
  4443. }
  4444. export interface ResetPasswordResponse {
  4445. message: string;
  4446. }
  4447. export interface SMTPSettings {
  4448. smtp_host: string;
  4449. smtp_port: number;
  4450. smtp_username?: string;
  4451. smtp_password?: string;
  4452. smtp_security: 'starttls' | 'ssl' | 'none';
  4453. smtp_auth_enabled: boolean;
  4454. smtp_from_email: string;
  4455. smtp_from_name: string;
  4456. }
  4457. // 2FA / MFA interfaces
  4458. export interface TwoFAStatus {
  4459. totp_enabled: boolean;
  4460. email_otp_enabled: boolean;
  4461. backup_codes_remaining: number;
  4462. }
  4463. export interface TOTPSetupResponse {
  4464. secret: string;
  4465. qr_code_b64: string;
  4466. issuer: string;
  4467. }
  4468. export interface TOTPEnableResponse {
  4469. message: string;
  4470. backup_codes: string[];
  4471. }
  4472. export interface BackupCodesResponse {
  4473. backup_codes: string[];
  4474. message: string;
  4475. }
  4476. export interface TwoFAVerifyRequest {
  4477. pre_auth_token: string;
  4478. code: string;
  4479. method: 'totp' | 'email' | 'backup';
  4480. }
  4481. /**
  4482. * A URL that is known to be same-origin (a relative path starting with ``/``).
  4483. *
  4484. * Branded so that producers of same-origin URLs (e.g. ``api.oidcProviderIconUrl``)
  4485. * can be distinguished from arbitrary strings at the type level. The brand
  4486. * is compile-time only; at runtime these are plain strings.
  4487. *
  4488. * Purpose: CSP-safe image sources for ``<img src=...>``. The strict
  4489. * ``img-src 'self' data: blob:`` CSP rejects anything that isn't same-origin,
  4490. * so callers that demand a ``SameOriginUrl`` get a compile-time guarantee
  4491. * that no external URL slips through.
  4492. */
  4493. export type SameOriginUrl = string & { readonly __brand: 'SameOriginUrl' };
  4494. // OIDC interfaces
  4495. /** What the unauthenticated GET /auth/oidc/providers returns (#3107): only
  4496. * what the login page renders. The full provider, group sync config
  4497. * included, needs the admin-only /auth/oidc/providers/all. */
  4498. export interface OIDCProviderPublic {
  4499. id: number;
  4500. name: string;
  4501. has_icon: boolean;
  4502. is_autologin: boolean;
  4503. }
  4504. export interface OIDCProvider {
  4505. id: number;
  4506. name: string;
  4507. issuer_url: string;
  4508. client_id: string;
  4509. scopes: string;
  4510. is_enabled: boolean;
  4511. auto_create_users: boolean;
  4512. auto_link_existing_accounts: boolean;
  4513. email_claim: string;
  4514. require_email_verified: boolean;
  4515. // #3107 — group sync. Empty mapping = sync off (default).
  4516. group_claim?: string;
  4517. group_mapping?: Record<string, string>;
  4518. icon_url?: string | null;
  4519. default_group_id?: number | null;
  4520. // True when the backend has cached icon bytes for this provider.
  4521. // Login page / admin preview consume this via the proxy URL
  4522. // /api/v1/auth/oidc/providers/{id}/icon (#1333) so the SPA never
  4523. // hotlinks the external icon URL — that would require loosening
  4524. // the strict img-src CSP. Required, not optional: the backend always
  4525. // includes this field in the response (Pydantic default-False is
  4526. // populated unconditionally in the route handler).
  4527. has_icon: boolean;
  4528. // #1589: when true, the LoginPage redirects unauthenticated visitors
  4529. // straight to this provider on mount. At most one provider may carry this.
  4530. is_autologin: boolean;
  4531. // #2593: defined by BAMBUDDY_OIDC_* and rewritten from the environment on
  4532. // every boot. The API answers 409 to any write, so the settings UI must not
  4533. // offer edit/delete controls that cannot succeed. Optional so a response
  4534. // from an older backend still type-checks.
  4535. is_env_managed?: boolean;
  4536. }
  4537. export interface OIDCProviderCreate {
  4538. name: string;
  4539. issuer_url: string;
  4540. client_id: string;
  4541. client_secret: string;
  4542. scopes?: string;
  4543. is_enabled?: boolean;
  4544. auto_create_users?: boolean;
  4545. auto_link_existing_accounts?: boolean;
  4546. email_claim?: string;
  4547. require_email_verified?: boolean;
  4548. // #3107 — group sync. Omit both to leave them unchanged on update.
  4549. group_claim?: string;
  4550. group_mapping?: Record<string, string>;
  4551. icon_url?: string | null;
  4552. default_group_id?: number | null;
  4553. is_autologin?: boolean; // #1589
  4554. }
  4555. export interface OIDCLink {
  4556. id: number;
  4557. provider_id: number;
  4558. provider_name: string;
  4559. provider_email?: string | null;
  4560. created_at: string;
  4561. }
  4562. export interface TestSMTPRequest {
  4563. test_recipient: string;
  4564. // The form's settings, tested before they are saved. An empty password
  4565. // keeps the saved one.
  4566. smtp?: SMTPSettings;
  4567. }
  4568. export interface TestSMTPResponse {
  4569. success: boolean;
  4570. message: string;
  4571. }
  4572. export interface AdvancedAuthStatus {
  4573. advanced_auth_enabled: boolean;
  4574. smtp_configured: boolean;
  4575. // #1589: false hides the username/password form on the LoginPage; the env
  4576. // var BAMBUDDY_LOCAL_LOGIN=true on the server flips this back to true so
  4577. // the recovery path remains visible.
  4578. local_login_enabled: boolean;
  4579. // #1589: when set, LoginPage redirects to this provider's authorize URL
  4580. // on mount unless ?fallback=local is in the URL or the redirect times out.
  4581. autologin_provider_id: number | null;
  4582. }
  4583. export interface LDAPStatus {
  4584. ldap_enabled: boolean;
  4585. ldap_configured: boolean;
  4586. }
  4587. export interface EncryptionRowCounts {
  4588. oidc_providers: number;
  4589. user_totp: number;
  4590. }
  4591. export interface EncryptionStatus {
  4592. key_configured: boolean;
  4593. key_source: 'env' | 'file' | 'generated' | 'none';
  4594. legacy_plaintext_rows: EncryptionRowCounts;
  4595. encrypted_rows: EncryptionRowCounts;
  4596. decryption_broken: boolean;
  4597. // B2: count of rows skipped during the last legacy re-encryption migration.
  4598. // Surfaced via a yellow secondary banner in SecurityStatusCard.
  4599. migration_error_count: number;
  4600. }
  4601. export interface LDAPTestRequest {
  4602. ldap_server_url?: string;
  4603. ldap_bind_dn?: string;
  4604. ldap_bind_password?: string;
  4605. ldap_search_base?: string;
  4606. ldap_user_filter?: string;
  4607. ldap_security?: string;
  4608. }
  4609. export interface LDAPTestResponse {
  4610. success: boolean;
  4611. message: string;
  4612. }
  4613. export interface LDAPSearchResult {
  4614. username: string;
  4615. email: string | null;
  4616. display_name: string | null;
  4617. dn: string;
  4618. already_provisioned: boolean;
  4619. }
  4620. export interface SetupResponse {
  4621. auth_enabled: boolean;
  4622. admin_created?: boolean;
  4623. }
  4624. export interface AuthStatus {
  4625. auth_enabled: boolean;
  4626. requires_setup: boolean;
  4627. }
  4628. // API functions
  4629. export interface QueueHistoryFilters {
  4630. printerId?: number | null;
  4631. status?: string;
  4632. location?: string;
  4633. }
  4634. export interface QueueHistoryParams extends QueueHistoryFilters {
  4635. sortBy?: 'date' | 'name' | 'printer';
  4636. // Flips the default order: newest first by date, A to Z by name or printer.
  4637. reverse?: boolean;
  4638. limit?: number;
  4639. offset?: number;
  4640. }
  4641. export interface QueueHistoryPage {
  4642. // The page in display order, then any other runs of the batches on it.
  4643. items: PrintQueueItem[];
  4644. total: number;
  4645. locations: string[];
  4646. }
  4647. function queueHistorySearch(params: QueueHistoryParams): URLSearchParams {
  4648. const search = new URLSearchParams();
  4649. if (params.printerId) search.set('printer_id', String(params.printerId));
  4650. if (params.status) search.set('status', params.status);
  4651. if (params.location) search.set('location', params.location);
  4652. if (params.sortBy) search.set('sort_by', params.sortBy);
  4653. if (params.reverse) search.set('reverse', 'true');
  4654. if (params.limit !== undefined) search.set('limit', String(params.limit));
  4655. if (params.offset) search.set('offset', String(params.offset));
  4656. return search;
  4657. }
  4658. // Per-printer reads that a page showing every printer makes once per printer,
  4659. // coalesced into one bulk request per few milliseconds (see ./batch). Each
  4660. // keeps its single-printer request for a lone id.
  4661. const idsParam = (ids: number[]) => `ids=${ids.join(',')}`;
  4662. const printerStatusBatch = batched(
  4663. (id) => request<PrinterStatus>(`/printers/${id}/status`),
  4664. async (ids) => byField(await request<PrinterStatus[]>(`/bulk/printer-statuses?${idsParam(ids)}`), (s) => s.id),
  4665. );
  4666. const slotPresetsBatch = batched(
  4667. (id) => request<Record<number, SlotPresetMapping>>(`/printers/${id}/slot-presets`),
  4668. async (ids) => byId(await request<Record<string, Record<number, SlotPresetMapping>>>(`/bulk/slot-presets?${idsParam(ids)}`)),
  4669. );
  4670. const amsLabelsBatch = batched(
  4671. (id) => request<Record<number, string>>(`/printers/${id}/ams-labels`),
  4672. async (ids) => byId(await request<Record<string, Record<number, string>>>(`/bulk/ams-labels?${idsParam(ids)}`)),
  4673. );
  4674. type PrinterCardPlugs = { plug: SmartPlug | null; scripts: SmartPlug[] };
  4675. const cardPlugs = async (ids: number[]) =>
  4676. byId(await request<Record<string, PrinterCardPlugs>>(`/bulk/card-plugs?${idsParam(ids)}`));
  4677. const smartPlugBatch = batched(
  4678. (id) => request<SmartPlug | null>(`/smart-plugs/by-printer/${id}`),
  4679. async (ids) => new Map([...(await cardPlugs(ids))].map(([id, plugs]) => [id, plugs.plug])),
  4680. );
  4681. const scriptPlugsBatch = batched(
  4682. (id) => request<SmartPlug[]>(`/smart-plugs/by-printer/${id}/scripts`),
  4683. async (ids) => new Map([...(await cardPlugs(ids))].map(([id, plugs]) => [id, plugs.scripts])),
  4684. );
  4685. const haSensorReadingsBatch = batched(
  4686. (id) => request<PrinterHASensorReading[]>(`/ha-sensors/by-printer/${id}/readings`),
  4687. async (ids) => byId(await request<Record<string, PrinterHASensorReading[]>>(`/bulk/ha-sensor-readings?${idsParam(ids)}`)),
  4688. );
  4689. const firmwareUpdateBatch = batched(
  4690. (id) => request<FirmwareUpdateInfo>(`/firmware/updates/${id}`),
  4691. async (ids) =>
  4692. byField(await request<FirmwareUpdateInfo[]>(`/bulk/firmware-updates?${idsParam(ids)}`), (u) => u.printer_id),
  4693. );
  4694. // One batcher per status asked for: the bulk route takes a single status list.
  4695. const printerQueueBatches = new Map<string, (id: number) => Promise<PrintQueueItem[]>>();
  4696. const printerQueueBatch = (status: string) => {
  4697. let batch = printerQueueBatches.get(status);
  4698. if (!batch) {
  4699. batch = batched(
  4700. (id) => request<PrintQueueItem[]>(`/queue/?printer_id=${id}&status=${encodeURIComponent(status)}`),
  4701. async (ids) =>
  4702. byId(
  4703. await request<Record<string, PrintQueueItem[]>>(
  4704. `/bulk/printer-queues?${idsParam(ids)}&status=${encodeURIComponent(status)}`,
  4705. ),
  4706. ),
  4707. );
  4708. printerQueueBatches.set(status, batch);
  4709. }
  4710. return batch;
  4711. };
  4712. const foldersByArchiveBatch = batched(
  4713. (id) => request<LibraryFolder[]>(`/library/folders/by-archive/${id}`),
  4714. async (ids) => byId(await request<Record<string, LibraryFolder[]>>(`/bulk/archive-folders?${idsParam(ids)}`)),
  4715. );
  4716. export const api = {
  4717. // Overlay branding
  4718. getOverlayLogo: async (token: string | null, signal?: AbortSignal): Promise<Blob | null> => {
  4719. const endpoint = token ? `/overlay-branding/logo?token=${encodeURIComponent(token)}` : '/settings/overlay-logo';
  4720. const response = await fetch(`${API_BASE}${endpoint}`, {
  4721. signal, cache: 'no-store',
  4722. headers: !token && authToken ? { Authorization: `Bearer ${authToken}` } : {},
  4723. });
  4724. if (response.status === 404) return null;
  4725. if (!response.ok) throw new Error(`HTTP ${response.status}`);
  4726. return response.blob();
  4727. },
  4728. uploadOverlayLogo: async (file: File): Promise<void> => {
  4729. const body = new FormData();
  4730. body.append('file', file);
  4731. const response = await fetch(`${API_BASE}/settings/overlay-logo`, {
  4732. method: 'POST', body,
  4733. headers: authToken ? { Authorization: `Bearer ${authToken}` } : {},
  4734. });
  4735. if (!response.ok) {
  4736. const error = await response.json().catch(() => ({}));
  4737. const detail = error?.detail;
  4738. const message = typeof detail === 'string' ? detail : detail?.message;
  4739. throw new Error(typeof message === 'string' && message ? message : `HTTP ${response.status}`);
  4740. }
  4741. },
  4742. deleteOverlayLogo: () => request<{ status: string }>('/settings/overlay-logo', { method: 'DELETE' }),
  4743. // Authentication
  4744. getAuthStatus: () => request<AuthStatus>('/auth/status'),
  4745. setupAuth: (data: SetupRequest) =>
  4746. request<SetupResponse>('/auth/setup', {
  4747. method: 'POST',
  4748. body: JSON.stringify(data),
  4749. }),
  4750. login: (data: LoginRequest) =>
  4751. request<LoginResponse>('/auth/login', {
  4752. method: 'POST',
  4753. body: JSON.stringify(data),
  4754. }),
  4755. logout: () =>
  4756. request<{ message: string }>('/auth/logout', {
  4757. method: 'POST',
  4758. }),
  4759. getCurrentUser: () => request<UserResponse>('/auth/me'),
  4760. disableAuth: () =>
  4761. request<{ message: string; auth_enabled: boolean }>('/auth/disable', {
  4762. method: 'POST',
  4763. }),
  4764. // Advanced Authentication
  4765. testSMTP: (data: TestSMTPRequest) =>
  4766. request<TestSMTPResponse>('/auth/smtp/test', {
  4767. method: 'POST',
  4768. body: JSON.stringify(data),
  4769. }),
  4770. getSMTPSettings: () => request<SMTPSettings | null>('/auth/smtp'),
  4771. saveSMTPSettings: (data: SMTPSettings) =>
  4772. request<{ message: string }>('/auth/smtp', {
  4773. method: 'POST',
  4774. body: JSON.stringify(data),
  4775. }),
  4776. enableAdvancedAuth: () =>
  4777. request<{ message: string; advanced_auth_enabled: boolean }>('/auth/advanced-auth/enable', {
  4778. method: 'POST',
  4779. }),
  4780. disableAdvancedAuth: () =>
  4781. request<{ message: string; advanced_auth_enabled: boolean }>('/auth/advanced-auth/disable', {
  4782. method: 'POST',
  4783. }),
  4784. getAdvancedAuthStatus: () => request<AdvancedAuthStatus>('/auth/advanced-auth/status'),
  4785. // LDAP Authentication
  4786. getLDAPStatus: () => request<LDAPStatus>('/auth/ldap/status'),
  4787. getEncryptionStatus: () => request<EncryptionStatus>('/auth/encryption-status'),
  4788. // form: the settings being edited, tested before they are saved. An empty
  4789. // bind password keeps the saved one.
  4790. testLDAP: (form?: LDAPTestRequest) =>
  4791. request<LDAPTestResponse>('/auth/ldap/test', {
  4792. method: 'POST',
  4793. ...(form ? { body: JSON.stringify(form) } : {}),
  4794. }),
  4795. searchLDAPDirectory: (q: string) =>
  4796. request<LDAPSearchResult[]>(`/auth/ldap/search?q=${encodeURIComponent(q)}`),
  4797. provisionLDAPUser: (username: string) =>
  4798. request<UserResponse>('/auth/ldap/provision', {
  4799. method: 'POST',
  4800. body: JSON.stringify({ username }),
  4801. }),
  4802. forgotPassword: (data: ForgotPasswordRequest) =>
  4803. request<ForgotPasswordResponse>('/auth/forgot-password', {
  4804. method: 'POST',
  4805. body: JSON.stringify(data),
  4806. }),
  4807. // H-6: Confirm password reset using the token from the emailed link
  4808. forgotPasswordConfirm: (token: string, newPassword: string) =>
  4809. request<ForgotPasswordResponse>('/auth/forgot-password/confirm', {
  4810. method: 'POST',
  4811. body: JSON.stringify({ token, new_password: newPassword }),
  4812. }),
  4813. resetUserPassword: (data: ResetPasswordRequest) =>
  4814. request<ResetPasswordResponse>('/auth/reset-password', {
  4815. method: 'POST',
  4816. body: JSON.stringify(data),
  4817. }),
  4818. // 2FA - status
  4819. get2FAStatus: () => request<TwoFAStatus>('/auth/2fa/status'),
  4820. // 2FA - TOTP
  4821. setupTOTP: () => request<TOTPSetupResponse>('/auth/2fa/totp/setup', { method: 'POST' }),
  4822. enableTOTP: (code: string) =>
  4823. request<TOTPEnableResponse>('/auth/2fa/totp/enable', {
  4824. method: 'POST',
  4825. body: JSON.stringify({ code }),
  4826. }),
  4827. disableTOTP: (code: string) =>
  4828. request<{ message: string }>('/auth/2fa/totp/disable', {
  4829. method: 'POST',
  4830. body: JSON.stringify({ code }),
  4831. }),
  4832. regenerateBackupCodes: (code: string) =>
  4833. request<BackupCodesResponse>('/auth/2fa/totp/regenerate-backup-codes', {
  4834. method: 'POST',
  4835. body: JSON.stringify({ code }),
  4836. }),
  4837. // 2FA - Email OTP
  4838. // Step 1: send a verification code to the user's email (proof of possession)
  4839. enableEmailOTP: () =>
  4840. request<{ message: string; setup_token: string }>('/auth/2fa/email/enable', { method: 'POST' }),
  4841. // Step 2: confirm with the code received by email
  4842. confirmEnableEmailOTP: (setup_token: string, code: string) =>
  4843. request<{ message: string }>('/auth/2fa/email/enable/confirm', {
  4844. method: 'POST',
  4845. body: JSON.stringify({ setup_token, code }),
  4846. }),
  4847. // Disable requires account password for re-auth
  4848. disableEmailOTP: (password: string) =>
  4849. request<{ message: string }>('/auth/2fa/email/disable', {
  4850. method: 'POST',
  4851. body: JSON.stringify({ password }),
  4852. }),
  4853. sendEmailOTP: (preAuthToken: string) =>
  4854. request<{ message: string; pre_auth_token?: string }>('/auth/2fa/email/send', {
  4855. method: 'POST',
  4856. body: JSON.stringify({ pre_auth_token: preAuthToken }),
  4857. }),
  4858. // 2FA - verify (completes login)
  4859. verify2FA: (data: TwoFAVerifyRequest) =>
  4860. request<LoginResponse>('/auth/2fa/verify', {
  4861. method: 'POST',
  4862. body: JSON.stringify(data),
  4863. }),
  4864. // 2FA - admin
  4865. // adminPassword: the calling admin's own password; null for an admin
  4866. // without one (LDAP / OIDC accounts usually), whom the route does not ask.
  4867. admin2FADisable: (userId: number, adminPassword: string | null) =>
  4868. request<{ message: string; had_2fa: boolean }>(`/auth/2fa/admin/${userId}`, {
  4869. method: 'DELETE',
  4870. body: JSON.stringify({ admin_password: adminPassword }),
  4871. }),
  4872. // OIDC providers (public list)
  4873. getOIDCProviders: () => request<OIDCProviderPublic[]>('/auth/oidc/providers'),
  4874. // OIDC providers (admin)
  4875. getOIDCProvidersAll: () => request<OIDCProvider[]>('/auth/oidc/providers/all'),
  4876. createOIDCProvider: (data: OIDCProviderCreate) =>
  4877. request<OIDCProvider>('/auth/oidc/providers', {
  4878. method: 'POST',
  4879. body: JSON.stringify(data),
  4880. }),
  4881. updateOIDCProvider: (id: number, data: Partial<OIDCProviderCreate>) =>
  4882. request<OIDCProvider>(`/auth/oidc/providers/${id}`, {
  4883. method: 'PUT',
  4884. body: JSON.stringify(data),
  4885. }),
  4886. deleteOIDCProvider: (id: number) =>
  4887. request<{ message: string }>(`/auth/oidc/providers/${id}`, { method: 'DELETE' }),
  4888. // OIDC provider icon proxy (#1333) — same-origin path so the strict
  4889. // img-src CSP stays in force. Returns a SameOriginUrl-branded string
  4890. // so a future caller can't accidentally substitute an attacker-
  4891. // controlled URL where this is consumed.
  4892. oidcProviderIconUrl: (id: number): SameOriginUrl =>
  4893. `/api/v1/auth/oidc/providers/${id}/icon` as SameOriginUrl,
  4894. deleteOIDCProviderIcon: (id: number) =>
  4895. request<void>(`/auth/oidc/providers/${id}/icon`, { method: 'DELETE' }),
  4896. refreshOIDCProviderIcon: (id: number) =>
  4897. request<OIDCProvider>(`/auth/oidc/providers/${id}/icon/refresh`, { method: 'POST' }),
  4898. // OIDC authorize URL
  4899. getOIDCAuthorizeUrl: (providerId: number) =>
  4900. request<{ auth_url: string }>(`/auth/oidc/authorize/${providerId}`),
  4901. // OIDC exchange token for JWT
  4902. exchangeOIDCToken: (oidcToken: string) =>
  4903. request<LoginResponse>('/auth/oidc/exchange', {
  4904. method: 'POST',
  4905. body: JSON.stringify({ oidc_token: oidcToken }),
  4906. }),
  4907. // OIDC links for current user
  4908. getOIDCLinks: () => request<OIDCLink[]>('/auth/oidc/links'),
  4909. deleteOIDCLink: (providerId: number) =>
  4910. request<{ message: string }>(`/auth/oidc/links/${providerId}`, { method: 'DELETE' }),
  4911. // Users
  4912. getUsers: () => request<UserResponse[]>('/users/'),
  4913. getUsersSlim: () => request<UserSlim[]>('/users/slim'),
  4914. createUser: (data: UserCreate) =>
  4915. request<UserResponse>('/users/', {
  4916. method: 'POST',
  4917. body: JSON.stringify(data),
  4918. }),
  4919. updateUser: (id: number, data: UserUpdate) =>
  4920. request<UserResponse>(`/users/${id}`, {
  4921. method: 'PATCH',
  4922. body: JSON.stringify(data),
  4923. }),
  4924. deleteUser: (id: number, deleteItems: boolean = false) =>
  4925. request<void>(`/users/${id}?delete_items=${deleteItems}`, {
  4926. method: 'DELETE',
  4927. }),
  4928. getUserItemsCount: (id: number) =>
  4929. request<{ archives: number; queue_items: number; library_files: number }>(`/users/${id}/items-count`),
  4930. changePassword: (currentPassword: string, newPassword: string) =>
  4931. request<{ message: string }>('/users/me/change-password', {
  4932. method: 'POST',
  4933. body: JSON.stringify({ current_password: currentPassword, new_password: newPassword }),
  4934. }),
  4935. // User Email Notifications
  4936. getUserEmailPreferences: () =>
  4937. request<UserEmailPreferences>('/user-notifications/preferences'),
  4938. updateUserEmailPreferences: (data: UserEmailPreferences) =>
  4939. request<UserEmailPreferences>('/user-notifications/preferences', {
  4940. method: 'PUT',
  4941. body: JSON.stringify(data),
  4942. }),
  4943. // Groups
  4944. getPermissions: () => request<PermissionsListResponse>('/groups/permissions'),
  4945. getGroups: () => request<Group[]>('/groups/'),
  4946. getGroup: (id: number) => request<GroupDetail>(`/groups/${id}`),
  4947. createGroup: (data: GroupCreate) =>
  4948. request<Group>('/groups/', {
  4949. method: 'POST',
  4950. body: JSON.stringify(data),
  4951. }),
  4952. updateGroup: (id: number, data: GroupUpdate) =>
  4953. request<Group>(`/groups/${id}`, {
  4954. method: 'PATCH',
  4955. body: JSON.stringify(data),
  4956. }),
  4957. deleteGroup: (id: number) =>
  4958. request<void>(`/groups/${id}`, {
  4959. method: 'DELETE',
  4960. }),
  4961. // Printers
  4962. getPrinters: () => request<Printer[]>('/printers/'),
  4963. getPrinter: (id: number) => request<Printer>(`/printers/${id}`),
  4964. createPrinter: (data: PrinterCreate) =>
  4965. request<Printer>('/printers/', {
  4966. method: 'POST',
  4967. body: JSON.stringify(data),
  4968. }),
  4969. updatePrinter: (id: number, data: Partial<PrinterCreate>) =>
  4970. request<Printer>(`/printers/${id}`, {
  4971. method: 'PATCH',
  4972. body: JSON.stringify(data),
  4973. }),
  4974. deletePrinter: (id: number, deleteArchives: boolean = true) =>
  4975. request<{ status: string; archives_deleted: boolean }>(
  4976. `/printers/${id}?delete_archives=${deleteArchives}`,
  4977. { method: 'DELETE' }
  4978. ),
  4979. getDeveloperModeWarnings: () =>
  4980. request<{ printer_id: number; name: string }[]>('/printers/developer-mode-warnings'),
  4981. getAvailableFilaments: (model: string, location?: string) => {
  4982. const params = new URLSearchParams({ model });
  4983. if (location) params.set('location', location);
  4984. return request<Array<{ type: string; color: string; tray_info_idx: string; tray_sub_brands: string; extruder_id: number | null }>>(`/printers/available-filaments?${params}`);
  4985. },
  4986. getPrinterLocations: () => request<PrinterLocation[]>('/printer-locations/'),
  4987. createPrinterLocation: (data: { name: string; icon?: string | null; color?: string | null }) =>
  4988. request<PrinterLocation>('/printer-locations/', { method: 'POST', body: JSON.stringify(data) }),
  4989. updatePrinterLocation: (data: PrinterLocationUpdate) =>
  4990. request<PrinterLocation>('/printer-locations/', { method: 'PATCH', body: JSON.stringify(data) }),
  4991. deletePrinterLocations: (names: string[]) =>
  4992. request<{ deleted: number; printers_ungrouped: number }>('/printer-locations/delete', {
  4993. method: 'POST',
  4994. body: JSON.stringify({ names }),
  4995. }),
  4996. assignPrinterLocation: (printerIds: number[], location: string | null) =>
  4997. request<{ moved: number }>('/printer-locations/assign', {
  4998. method: 'POST',
  4999. body: JSON.stringify({ printer_ids: printerIds, location }),
  5000. }),
  5001. getPrinterStatus: (id: number) => printerStatusBatch(id),
  5002. refreshPrinterStatus: (id: number) =>
  5003. request<{ status: string }>(`/printers/${id}/refresh-status`, {
  5004. method: 'POST',
  5005. }),
  5006. connectPrinter: (id: number) =>
  5007. request<{ connected: boolean }>(`/printers/${id}/connect`, {
  5008. method: 'POST',
  5009. }),
  5010. getUsbCameras: () => request<{ cameras: UsbCamera[] }>('/printers/usb-cameras'),
  5011. testExternalCamera: (printerId: number, url: string, cameraType: string) =>
  5012. // `coalesced` is true when the frame came from a capture that was already
  5013. // running (Obico polling, a snapshot) rather than a connection this test
  5014. // opened — a single-reader camera is shared rather than opened twice, so
  5015. // the result is real but says nothing about reaching the camera just now.
  5016. // `live_view` is true when the tested camera is the one a viewer is
  5017. // watching: the answer comes from the live frame, not a test of its own.
  5018. // In the body: the URL may carry the camera login, and a query string
  5019. // ends up in the server's access log.
  5020. request<{ success: boolean; error?: string; resolution?: string; coalesced?: boolean; live_view?: boolean }>(
  5021. `/printers/${printerId}/camera/external/test`,
  5022. { method: 'POST', body: JSON.stringify({ url, camera_type: cameraType }) }
  5023. ),
  5024. // Print Control
  5025. stopPrint: (printerId: number) =>
  5026. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/stop`, {
  5027. method: 'POST',
  5028. }),
  5029. pausePrint: (printerId: number) =>
  5030. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/pause`, {
  5031. method: 'POST',
  5032. }),
  5033. resumePrint: (printerId: number) =>
  5034. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/resume`, {
  5035. method: 'POST',
  5036. }),
  5037. clearPlate: (printerId: number) =>
  5038. request<{ success: boolean; message: string }>(`/printers/${printerId}/clear-plate`, {
  5039. method: 'POST',
  5040. }),
  5041. // Get current print user (for reprint tracking - Issue #206)
  5042. getCurrentPrintUser: (printerId: number) =>
  5043. request<{ user_id?: number; username?: string }>(`/printers/${printerId}/current-print-user`),
  5044. // Print Speed Control
  5045. setPrintSpeed: (printerId: number, mode: number) =>
  5046. request<{ success: boolean; message: string }>(`/printers/${printerId}/print-speed?mode=${mode}`, {
  5047. method: 'POST',
  5048. }),
  5049. setNozzleTemperature: (printerId: number, target: number, nozzle: number = 0) =>
  5050. request<{ success: boolean; message: string }>(
  5051. `/printers/${printerId}/temperature/nozzle?target=${target}&nozzle=${nozzle}`,
  5052. { method: 'POST' }
  5053. ),
  5054. setBedTemperature: (printerId: number, target: number) =>
  5055. request<{ success: boolean; message: string }>(`/printers/${printerId}/temperature/bed?target=${target}`, {
  5056. method: 'POST',
  5057. }),
  5058. setChamberTemperature: (printerId: number, target: number) =>
  5059. request<{ success: boolean; message: string }>(`/printers/${printerId}/temperature/chamber?target=${target}`, {
  5060. method: 'POST',
  5061. }),
  5062. setFanSpeed: (printerId: number, fan: 'part' | 'aux' | 'aux2' | 'chamber', speed: number) =>
  5063. request<{ success: boolean; message: string }>(`/printers/${printerId}/fan-speed?fan=${fan}&speed=${speed}`, {
  5064. method: 'POST',
  5065. }),
  5066. selectExtruder: (printerId: number, extruder: number) =>
  5067. request<{ success: boolean; message: string }>(`/printers/${printerId}/select-extruder?extruder=${extruder}`, {
  5068. method: 'POST',
  5069. }),
  5070. setAirductMode: (printerId: number, mode: 'cooling' | 'heating') =>
  5071. request<{ success: boolean; message: string }>(`/printers/${printerId}/airduct-mode?mode=${mode}`, {
  5072. method: 'POST',
  5073. }),
  5074. // Bed (Z-axis) jog
  5075. bedJog: (printerId: number, distance: number) =>
  5076. request<{ success: boolean; message: string }>(
  5077. `/printers/${printerId}/bed-jog?distance=${distance}`,
  5078. { method: 'POST' }
  5079. ),
  5080. xyJog: (printerId: number, x: number, y: number) =>
  5081. request<{ success: boolean; message: string }>(
  5082. `/printers/${printerId}/xy-jog?x=${x}&y=${y}`,
  5083. { method: 'POST' }
  5084. ),
  5085. extruderJog: (printerId: number, distance: number) =>
  5086. request<{ success: boolean; message: string }>(
  5087. `/printers/${printerId}/extruder-jog?distance=${distance}`,
  5088. { method: 'POST' }
  5089. ),
  5090. homeAxes: (printerId: number, axes: 'z' | 'xy' | 'all' = 'z') =>
  5091. request<{ success: boolean; message: string }>(
  5092. `/printers/${printerId}/home-axes?axes=${axes}`,
  5093. { method: 'POST' }
  5094. ),
  5095. // Chamber Light Control
  5096. setChamberLight: (printerId: number, on: boolean) =>
  5097. request<{ success: boolean; message: string }>(`/printers/${printerId}/chamber-light?on=${on}`, {
  5098. method: 'POST',
  5099. }),
  5100. // AMS Drying Control
  5101. startDrying: (printerId: number, amsId: number, temp: number, duration: number, filament: string = '', rotateTray: boolean = false) =>
  5102. request<{ status: string; ams_id: number; temp: number; duration: number }>(
  5103. `/printers/${printerId}/drying/start?ams_id=${amsId}&temp=${temp}&duration=${duration}&filament=${encodeURIComponent(filament)}&rotate_tray=${rotateTray}`,
  5104. { method: 'POST' }
  5105. ),
  5106. stopDrying: (printerId: number, amsId: number) =>
  5107. request<{ status: string; ams_id: number }>(
  5108. `/printers/${printerId}/drying/stop?ams_id=${amsId}`,
  5109. { method: 'POST' }
  5110. ),
  5111. // Scheduled (delayed) drying runs (#2638)
  5112. createScheduledDrying: (data: {
  5113. printer_id: number;
  5114. ams_id: number;
  5115. temp: number;
  5116. duration_hours: number;
  5117. filament?: string;
  5118. rotate_tray?: boolean;
  5119. start_after: string | null;
  5120. }) =>
  5121. request<ScheduledDrying>('/scheduled-dryings', {
  5122. method: 'POST',
  5123. body: JSON.stringify(data),
  5124. }),
  5125. // Omit printerId for the whole fleet in one request; the printer cards share
  5126. // that single query rather than each polling for its own id.
  5127. listScheduledDryings: (printerId?: number) =>
  5128. request<ScheduledDrying[]>(
  5129. printerId === undefined ? '/scheduled-dryings' : `/scheduled-dryings?printer_id=${printerId}`
  5130. ),
  5131. cancelScheduledDrying: (id: number) =>
  5132. request<{ status: string; id: number }>(`/scheduled-dryings/${id}`, { method: 'DELETE' }),
  5133. // AMS Filament Backup (auto-switch to a backup spool when one runs out)
  5134. setAmsFilamentBackup: (printerId: number, enabled: boolean) =>
  5135. request<{ success: boolean; ams_filament_backup: boolean }>(
  5136. `/printers/${printerId}/ams-backup?enabled=${enabled}`,
  5137. { method: 'POST' }
  5138. ),
  5139. // Per-globalTrayId remaining grams for this printer's inventory-bound slots
  5140. // (#1766). Drives the client-side "Prefer Lowest Remaining Filament" sort
  5141. // when computing the AMS mapping; mirrors backend `_build_inventory_remain_overrides`
  5142. // so internal and Spoolman modes both work uniformly.
  5143. getInventoryRemain: (printerId: number) =>
  5144. request<InventoryRemainResponse>(
  5145. `/printers/${printerId}/inventory-remain`,
  5146. ),
  5147. // Skip Objects
  5148. getPrintableObjects: (printerId: number) =>
  5149. request<{
  5150. objects: Array<{ id: number; name: string; x: number | null; y: number | null; skipped: boolean }>;
  5151. total: number;
  5152. skipped_count: number;
  5153. is_printing: boolean;
  5154. bbox_all: [number, number, number, number] | null;
  5155. }>(`/printers/${printerId}/print/objects`),
  5156. skipObjects: (printerId: number, objectIds: number[]) =>
  5157. request<{ success: boolean; message: string; skipped_objects: number[] }>(
  5158. `/printers/${printerId}/print/skip-objects`,
  5159. {
  5160. method: 'POST',
  5161. body: JSON.stringify(objectIds),
  5162. }
  5163. ),
  5164. // HMS Errors
  5165. clearHMSErrors: (printerId: number) =>
  5166. request<{ success: boolean; message: string }>(`/printers/${printerId}/hms/clear`, { method: 'POST' }),
  5167. executeHMSAction: (printerId: number, data: HMSActionBody) =>
  5168. request<{ success: boolean; message: string }>(`/printers/${printerId}/hms/execute-action`, {
  5169. method: 'POST',
  5170. body: JSON.stringify(data),
  5171. }),
  5172. // AMS Control
  5173. refreshAmsSlot: (printerId: number, amsId: number, slotId: number) =>
  5174. request<{ success: boolean; message: string }>(
  5175. `/printers/${printerId}/ams/${amsId}/slot/${slotId}/refresh`,
  5176. { method: 'POST' }
  5177. ),
  5178. // Load filament from a tray. trayId: 0-15 for AMS (amsId*4+slotId), 128-135 for an
  5179. // AMS-HT (its unit id), 254 for external spool.
  5180. // extruderId (0 = right, 1 = left) names the hotend to feed. Pass it only on a
  5181. // printer with a Filament Track Switch — there the AMS is bound to a switch
  5182. // inlet rather than a hotend, so the firmware cannot work the target out and
  5183. // drops the command. Omit it everywhere else, as BambuStudio does.
  5184. loadAmsTray: (printerId: number, trayId: number, extruderId?: number) =>
  5185. request<{ success: boolean; message: string }>(
  5186. `/printers/${printerId}/ams/load?tray_id=${trayId}` +
  5187. (extruderId !== undefined ? `&extruder_id=${extruderId}` : ''),
  5188. { method: 'POST' }
  5189. ),
  5190. // Unload filament. trayId names the slot to unload, which is what tells a
  5191. // dual-nozzle printer which of its two hotends to act on; omit it to unload
  5192. // whatever the printer's single tray_now field names.
  5193. unloadAms: (printerId: number, trayId?: number) =>
  5194. request<{ success: boolean; message: string }>(
  5195. `/printers/${printerId}/ams/unload` + (trayId !== undefined ? `?tray_id=${trayId}` : ''),
  5196. { method: 'POST' }
  5197. ),
  5198. // MQTT Debug Logging
  5199. enableMQTTLogging: (printerId: number) =>
  5200. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/enable`, {
  5201. method: 'POST',
  5202. }),
  5203. disableMQTTLogging: (printerId: number) =>
  5204. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/disable`, {
  5205. method: 'POST',
  5206. }),
  5207. getMQTTLogs: (printerId: number) =>
  5208. request<MQTTLogsResponse>(`/printers/${printerId}/logging`),
  5209. clearMQTTLogs: (printerId: number) =>
  5210. request<{ status: string }>(`/printers/${printerId}/logging`, {
  5211. method: 'DELETE',
  5212. }),
  5213. // Printer File Manager
  5214. getPrinterFiles: (printerId: number, path = '/') =>
  5215. request<{
  5216. path: string;
  5217. files: Array<{
  5218. name: string;
  5219. is_directory: boolean;
  5220. size: number;
  5221. path: string;
  5222. mtime?: string;
  5223. }>;
  5224. warnings: Array<'printer_unavailable' | 'listing_timed_out'>;
  5225. }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`),
  5226. getPrinterFileDownloadUrl: (printerId: number, path: string) =>
  5227. `${API_BASE}/printers/${printerId}/files/download?path=${encodeURIComponent(path)}`,
  5228. getPrinterFileGcodeUrl: (printerId: number, path: string) =>
  5229. `${API_BASE}/printers/${printerId}/files/gcode?path=${encodeURIComponent(path)}`,
  5230. getPrinterFilePlates: (printerId: number, path: string) =>
  5231. request<{
  5232. printer_id: number;
  5233. path: string;
  5234. filename: string;
  5235. plates: Array<{
  5236. index: number;
  5237. name: string | null;
  5238. objects: string[];
  5239. has_thumbnail: boolean;
  5240. thumbnail_url: string | null;
  5241. print_time_seconds: number | null;
  5242. filament_used_grams: number | null;
  5243. filaments: Array<{
  5244. slot_id: number;
  5245. type: string;
  5246. color: string;
  5247. used_grams: number;
  5248. used_meters: number;
  5249. }>;
  5250. }>;
  5251. is_multi_plate: boolean;
  5252. }>(`/printers/${printerId}/files/plates?path=${encodeURIComponent(path)}`),
  5253. getPrinterFilePlateThumbnail: (printerId: number, plateIndex: number, path: string) =>
  5254. withMediaToken(`${API_BASE}/printers/${printerId}/files/plate-thumbnail/${plateIndex}?path=${encodeURIComponent(path)}`),
  5255. downloadPrinterFilesAsZip: async (
  5256. printerId: number,
  5257. paths: string[],
  5258. sizes: Record<string, number>,
  5259. filename = 'printer-files.zip',
  5260. asZip = true,
  5261. signal?: AbortSignal,
  5262. onProgress?: (completed: number, total: number) => void,
  5263. ): Promise<{ requested: number; successful: number; failed: number }> => {
  5264. type JobStatus = {
  5265. job_id: string;
  5266. state: 'queued' | 'preparing' | 'ready' | 'failed' | 'cancelled';
  5267. requested: number;
  5268. successful: number;
  5269. failed: number;
  5270. token: string | null;
  5271. message: string | null;
  5272. };
  5273. let jobId: string | null = null;
  5274. try {
  5275. if (signal?.aborted) throw new DOMException('Download cancelled', 'AbortError');
  5276. let status = await request<JobStatus>(`/printers/${printerId}/files/download-job`, {
  5277. method: 'POST',
  5278. body: JSON.stringify({ paths, sizes, filename, as_zip: asZip }),
  5279. signal,
  5280. });
  5281. jobId = status.job_id;
  5282. let polls = 0;
  5283. while (status.state === 'queued' || status.state === 'preparing') {
  5284. onProgress?.(status.successful + status.failed, status.requested);
  5285. // Small selections finish in the first seconds, so poll quickly there.
  5286. // A large one runs for up to half an hour, where half-second polling is
  5287. // thousands of requests that each re-check the caller's credentials.
  5288. const delay = polls < 10 ? 500 : 2000;
  5289. polls += 1;
  5290. await new Promise<void>((resolve, reject) => {
  5291. if (signal?.aborted) {
  5292. reject(new DOMException('Download cancelled', 'AbortError'));
  5293. return;
  5294. }
  5295. const onAbort = () => {
  5296. window.clearTimeout(timer);
  5297. reject(new DOMException('Download cancelled', 'AbortError'));
  5298. };
  5299. const timer = window.setTimeout(() => {
  5300. signal?.removeEventListener('abort', onAbort);
  5301. resolve();
  5302. }, delay);
  5303. signal?.addEventListener('abort', onAbort, { once: true });
  5304. });
  5305. status = await request<JobStatus>(`/printers/${printerId}/files/download-jobs/${jobId}`, { signal });
  5306. }
  5307. onProgress?.(status.successful + status.failed, status.requested);
  5308. if (status.state !== 'ready' || !status.token) {
  5309. throw new Error(status.message || (status.state === 'cancelled'
  5310. ? 'Download cancelled'
  5311. : 'Printer download preparation failed'));
  5312. }
  5313. const link = document.createElement('a');
  5314. link.href = `${API_BASE}/printers/${printerId}/files/dl/${encodeURIComponent(status.token)}/${encodeURIComponent(filename)}`;
  5315. link.download = filename;
  5316. document.body.appendChild(link);
  5317. link.click();
  5318. link.remove();
  5319. return {
  5320. requested: status.requested,
  5321. successful: status.successful,
  5322. failed: status.failed,
  5323. };
  5324. } catch (error) {
  5325. if (jobId) {
  5326. await request(`/printers/${printerId}/files/download-jobs/${jobId}`, { method: 'DELETE' }).catch(() => undefined);
  5327. }
  5328. throw error;
  5329. }
  5330. },
  5331. deletePrinterFile: (printerId: number, path: string) =>
  5332. request<{ status: string; path: string }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`, {
  5333. method: 'DELETE',
  5334. }),
  5335. getPrinterStorage: (printerId: number) =>
  5336. request<{ used_bytes: number | null; free_bytes: number | null }>(`/printers/${printerId}/storage`),
  5337. // Archives
  5338. getArchives: (printerId?: number, projectId?: number, limit = 10000, offset = 0, dateFrom?: string, dateTo?: string) => {
  5339. const params = new URLSearchParams();
  5340. if (printerId) params.set('printer_id', String(printerId));
  5341. if (projectId) params.set('project_id', String(projectId));
  5342. params.set('limit', String(limit));
  5343. params.set('offset', String(offset));
  5344. if (dateFrom) params.set('date_from', dateFrom);
  5345. if (dateTo) params.set('date_to', dateTo);
  5346. addDayZone(params);
  5347. return request<Archive[]>(`/archives/?${params}`);
  5348. },
  5349. // Latest archive of every printer in one request, for the printer cards.
  5350. getLastArchivePerPrinter: () => request<Archive[]>('/archives/last-per-printer'),
  5351. getArchivesSlim: (dateFrom?: string, dateTo?: string, createdById?: number) => {
  5352. const params = new URLSearchParams();
  5353. if (dateFrom) params.set('date_from', dateFrom);
  5354. if (dateTo) params.set('date_to', dateTo);
  5355. addDayZone(params);
  5356. if (createdById !== undefined) params.set('created_by_id', String(createdById));
  5357. const qs = params.toString();
  5358. return request<ArchiveSlim[]>(`/archives/slim${qs ? `?${qs}` : ''}`);
  5359. },
  5360. getArchive: (id: number, runId?: number | null) =>
  5361. request<Archive>(`/archives/${id}${runId != null ? `?run_id=${runId}` : ''}`),
  5362. getArchiveRuns: (id: number) => request<PrintLogResponse>(`/archives/${id}/runs`),
  5363. // The prints of the archives the caller sees that ended between two days
  5364. // (archive redesign P4: the calendar), in id order.
  5365. getArchivePrints: (params: { dateFrom: string; dateTo: string; printerId?: number; limit?: number; offset?: number }) => {
  5366. const search = new URLSearchParams({ date_from: params.dateFrom, date_to: params.dateTo });
  5367. if (params.printerId) search.set('printer_id', String(params.printerId));
  5368. if (params.limit) search.set('limit', String(params.limit));
  5369. if (params.offset) search.set('offset', String(params.offset));
  5370. addDayZone(search);
  5371. return request<PrintLogResponse>(`/archives/prints?${search}`);
  5372. },
  5373. /**
  5374. * Pre-flight for the delete-confirm modal (#1734). Returns the number of
  5375. * related queue items that will be removed along with the archive AND how
  5376. * many are currently printing (server 409s on delete if > 0).
  5377. */
  5378. getArchiveDeleteImpact: (id: number) =>
  5379. request<{ related_queue_items: number; currently_printing: number }>(
  5380. `/archives/${id}/delete-impact`
  5381. ),
  5382. getNo3MFWarning: () =>
  5383. request<{
  5384. has_fallback: boolean;
  5385. reason:
  5386. | 'ftps_cooloff'
  5387. | 'ftp_transfer_failed'
  5388. | 'internal_storage'
  5389. | 'no_external_storage'
  5390. | 'internal_history'
  5391. | null;
  5392. }>(
  5393. '/archives/no-3mf-warning',
  5394. ),
  5395. updateArchive: (id: number, data: {
  5396. printer_id?: number | null;
  5397. project_id?: number | null;
  5398. print_name?: string;
  5399. is_favorite?: boolean;
  5400. tags?: string;
  5401. notes?: string;
  5402. cost?: number;
  5403. failure_reason?: string | null;
  5404. status?: string;
  5405. quantity?: number;
  5406. external_url?: string | null;
  5407. filament_used_grams?: number | null;
  5408. // Post-print outcome verdict (#1898); null clears it
  5409. user_verdict?: 'good' | 'reject' | null;
  5410. // Which surface answered. The backend only accepts the sources a client
  5411. // can honestly claim and defaults to 'api' when none is given.
  5412. user_verdict_source?: 'dialog' | 'printer_card';
  5413. // The run the verdict / outcome is for; omitted means the latest run.
  5414. run_id?: number;
  5415. }) =>
  5416. request<Archive>(`/archives/${id}`, {
  5417. method: 'PATCH',
  5418. body: JSON.stringify(data),
  5419. }),
  5420. toggleFavorite: (id: number) =>
  5421. request<Archive>(`/archives/${id}/favorite`, { method: 'POST' }),
  5422. // Soft-deletes by default (#1343): files removed from disk, row hidden
  5423. // from listings, but its filament / time / cost / energy contribution
  5424. // stays in Quick Stats. Pass purgeStats=true to hard-delete and drop the
  5425. // row from statistics too.
  5426. deleteArchive: (id: number, purgeStats: boolean = false) =>
  5427. request<void>(`/archives/${id}${purgeStats ? '?purge_stats=true' : ''}`, { method: 'DELETE' }),
  5428. // ========== Archive auto-purge (#1008 follow-up) ==========
  5429. previewArchivePurge: (olderThanDays: number, purgeStats: boolean = false) =>
  5430. request<ArchivePurgePreview>(
  5431. `/archives/purge/preview?older_than_days=${olderThanDays}&purge_stats=${purgeStats}`,
  5432. ),
  5433. // #1390: purgeStats=false (default) soft-deletes each old archive — Quick Stats
  5434. // preserved, files removed from disk, row hidden via deleted_at. true matches
  5435. // the single-archive delete's `?purge_stats=true` semantics (hard-deletes the
  5436. // linked PrintLogEntry rows so the contribution drops from /stats too).
  5437. executeArchivePurge: (olderThanDays: number, purgeStats: boolean = false) =>
  5438. request<{ deleted: number; purge_stats: boolean }>('/archives/purge', {
  5439. method: 'POST',
  5440. body: JSON.stringify({ older_than_days: olderThanDays, purge_stats: purgeStats }),
  5441. }),
  5442. // Archives of one file merge into the oldest (archive redesign P2).
  5443. previewArchiveMerge: () => request<ArchiveMergePreview>('/archives/merge-preview'),
  5444. /** How many duplicate groups there are; cheap, for offering the merge. */
  5445. getArchiveMergeCount: () => request<{ groups: number }>('/archives/merge-count'),
  5446. mergeArchives: (survivorIds: number[]) =>
  5447. request<ArchiveMergeResult>('/archives/merge', {
  5448. method: 'POST',
  5449. body: JSON.stringify({ survivor_ids: survivorIds }),
  5450. }),
  5451. getArchivePurgeSettings: () =>
  5452. request<ArchivePurgeSettings>('/archives/purge/settings'),
  5453. updateArchivePurgeSettings: (body: ArchivePurgeSettings) =>
  5454. request<ArchivePurgeSettings>('/archives/purge/settings', {
  5455. method: 'PUT',
  5456. body: JSON.stringify(body),
  5457. }),
  5458. getArchiveStats: (options?: { dateFrom?: string; dateTo?: string; createdById?: number }) => {
  5459. const params = new URLSearchParams();
  5460. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  5461. if (options?.dateTo) params.set('date_to', options.dateTo);
  5462. addDayZone(params);
  5463. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  5464. const qs = params.toString();
  5465. return request<ArchiveStats>(`/archives/stats${qs ? `?${qs}` : ''}`);
  5466. },
  5467. // Tag management
  5468. getTags: () => request<TagInfo[]>('/archives/tags'),
  5469. renameTag: (oldName: string, newName: string) =>
  5470. request<{ affected: number }>(`/archives/tags/${encodeURIComponent(oldName)}`, {
  5471. method: 'PUT',
  5472. body: JSON.stringify({ new_name: newName }),
  5473. }),
  5474. deleteTag: (name: string) =>
  5475. request<{ affected: number }>(`/archives/tags/${encodeURIComponent(name)}`, {
  5476. method: 'DELETE',
  5477. }),
  5478. recalculateCosts: () =>
  5479. request<{
  5480. message: string;
  5481. updated: number;
  5482. preserved: number;
  5483. usage_repriced: number;
  5484. spoolman_unreachable: number;
  5485. }>('/archives/recalculate-costs', { method: 'POST' }),
  5486. getFailureAnalysis: (options?: { days?: number; dateFrom?: string; dateTo?: string; printerId?: number; projectId?: number; createdById?: number }) => {
  5487. const params = new URLSearchParams();
  5488. if (options?.days) params.set('days', String(options.days));
  5489. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  5490. if (options?.dateTo) params.set('date_to', options.dateTo);
  5491. addDayZone(params);
  5492. if (options?.printerId) params.set('printer_id', String(options.printerId));
  5493. if (options?.projectId) params.set('project_id', String(options.projectId));
  5494. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  5495. const qs = params.toString();
  5496. return request<FailureAnalysis>(`/archives/analysis/failures${qs ? `?${qs}` : ''}`);
  5497. },
  5498. compareArchives: (archiveIds: number[]) =>
  5499. request<ArchiveComparison>(`/archives/compare?archive_ids=${archiveIds.join(',')}`),
  5500. exportArchives: async (options?: {
  5501. format?: 'csv' | 'xlsx';
  5502. fields?: string[];
  5503. printerId?: number;
  5504. projectId?: number;
  5505. status?: string;
  5506. dateFrom?: string;
  5507. dateTo?: string;
  5508. search?: string;
  5509. }): Promise<{ blob: Blob; filename: string }> => {
  5510. const params = new URLSearchParams();
  5511. if (options?.format) params.set('format', options.format);
  5512. if (options?.fields) params.set('fields', options.fields.join(','));
  5513. if (options?.printerId) params.set('printer_id', String(options.printerId));
  5514. if (options?.projectId) params.set('project_id', String(options.projectId));
  5515. if (options?.status) params.set('status', options.status);
  5516. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  5517. if (options?.dateTo) params.set('date_to', options.dateTo);
  5518. addDayZone(params);
  5519. if (options?.search) params.set('search', options.search);
  5520. const headers: Record<string, string> = {};
  5521. if (authToken) {
  5522. headers['Authorization'] = `Bearer ${authToken}`;
  5523. }
  5524. const response = await fetch(`${API_BASE}/archives/export?${params}`, { headers });
  5525. if (!response.ok) {
  5526. const error = await response.json().catch(() => ({}));
  5527. throw new Error(error.detail || `HTTP ${response.status}`);
  5528. }
  5529. const contentDisposition = response.headers.get('Content-Disposition');
  5530. let filename = options?.format === 'xlsx' ? 'archives_export.xlsx' : 'archives_export.csv';
  5531. if (contentDisposition) {
  5532. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  5533. if (match) filename = match[1];
  5534. }
  5535. const blob = await response.blob();
  5536. return { blob, filename };
  5537. },
  5538. exportStats: async (options?: {
  5539. format?: 'csv' | 'xlsx';
  5540. days?: number;
  5541. printerId?: number;
  5542. projectId?: number;
  5543. createdById?: number;
  5544. }): Promise<{ blob: Blob; filename: string }> => {
  5545. const params = new URLSearchParams();
  5546. if (options?.format) params.set('format', options.format);
  5547. if (options?.days) params.set('days', String(options.days));
  5548. if (options?.printerId) params.set('printer_id', String(options.printerId));
  5549. if (options?.projectId) params.set('project_id', String(options.projectId));
  5550. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  5551. const headers: Record<string, string> = {};
  5552. if (authToken) {
  5553. headers['Authorization'] = `Bearer ${authToken}`;
  5554. }
  5555. const response = await fetch(`${API_BASE}/archives/stats/export?${params}`, { headers });
  5556. if (!response.ok) {
  5557. const error = await response.json().catch(() => ({}));
  5558. throw new Error(error.detail || `HTTP ${response.status}`);
  5559. }
  5560. const contentDisposition = response.headers.get('Content-Disposition');
  5561. let filename = options?.format === 'xlsx' ? 'stats_export.xlsx' : 'stats_export.csv';
  5562. if (contentDisposition) {
  5563. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  5564. if (match) filename = match[1];
  5565. }
  5566. const blob = await response.blob();
  5567. return { blob, filename };
  5568. },
  5569. getArchiveThumbnail: (id: number) => withMediaToken(`${API_BASE}/archives/${id}/thumbnail?v=${Date.now()}`),
  5570. getArchivePlateThumbnail: (id: number, plateIndex: number) =>
  5571. withMediaToken(`${API_BASE}/archives/${id}/plate-thumbnail/${plateIndex}`),
  5572. getArchiveDownload: (id: number) => `${API_BASE}/archives/${id}/download`,
  5573. downloadArchive: async (id: number, filename?: string): Promise<void> => {
  5574. const headers: Record<string, string> = {};
  5575. if (authToken) {
  5576. headers['Authorization'] = `Bearer ${authToken}`;
  5577. }
  5578. const response = await fetch(`${API_BASE}/archives/${id}/download`, { headers });
  5579. if (!response.ok) {
  5580. const error = await response.json().catch(() => ({}));
  5581. throw new Error(error.detail || `HTTP ${response.status}`);
  5582. }
  5583. const disposition = response.headers.get('Content-Disposition');
  5584. const downloadFilename = parseContentDispositionFilename(disposition) || filename || `archive_${id}.3mf`;
  5585. const blob = await response.blob();
  5586. const url = window.URL.createObjectURL(blob);
  5587. const a = document.createElement('a');
  5588. a.href = url;
  5589. a.download = downloadFilename;
  5590. document.body.appendChild(a);
  5591. a.click();
  5592. document.body.removeChild(a);
  5593. window.URL.revokeObjectURL(url);
  5594. },
  5595. getArchiveGcode: (id: number) => `${API_BASE}/archives/${id}/gcode`,
  5596. getArchiveTimelapse: (id: number) => withMediaToken(`${API_BASE}/archives/${id}/timelapse?v=${Date.now()}`),
  5597. getArchiveRunTimelapse: (id: number, runId: number) =>
  5598. withMediaToken(`${API_BASE}/archives/${id}/runs/${runId}/timelapse?v=${Date.now()}`),
  5599. downloadArchiveTimelapse: async (id: number, filename: string): Promise<void> => {
  5600. const prepared = await request<{ token: string; filename: string }>(
  5601. `/archives/${id}/media-download-token`,
  5602. { method: 'POST' },
  5603. );
  5604. const link = document.createElement('a');
  5605. link.href = `${API_BASE}/archives/${id}/media/dl/${encodeURIComponent(prepared.token)}/${encodeURIComponent(filename)}`;
  5606. link.download = filename;
  5607. document.body.appendChild(link);
  5608. link.click();
  5609. link.remove();
  5610. },
  5611. getArchivePrinterMedia: (id: number) =>
  5612. request<ArchivePrinterMedia>(`/archives/${id}/printer-media`),
  5613. scanArchiveTimelapse: (id: number) =>
  5614. request<{
  5615. status: string;
  5616. message: string;
  5617. filename?: string;
  5618. available_files?: Array<{ name: string; path: string; size: number; mtime: string | null }>;
  5619. }>(`/archives/${id}/timelapse/scan`, {
  5620. method: 'POST',
  5621. }),
  5622. selectArchiveTimelapse: (id: number, filename: string) =>
  5623. request<{ status: string; message: string; filename: string }>(
  5624. `/archives/${id}/timelapse/select?filename=${encodeURIComponent(filename)}`,
  5625. { method: 'POST' }
  5626. ),
  5627. deleteArchiveTimelapse: (id: number) =>
  5628. request<{ status: string }>(`/archives/${id}/timelapse`, {
  5629. method: 'DELETE',
  5630. }),
  5631. uploadArchiveTimelapse: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  5632. const formData = new FormData();
  5633. formData.append('file', file);
  5634. const headers: Record<string, string> = {};
  5635. if (authToken) {
  5636. headers['Authorization'] = `Bearer ${authToken}`;
  5637. }
  5638. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/upload`, {
  5639. method: 'POST',
  5640. headers,
  5641. body: formData,
  5642. });
  5643. if (!response.ok) {
  5644. const error = await response.json().catch(() => ({}));
  5645. throw new Error(error.detail || `HTTP ${response.status}`);
  5646. }
  5647. return response.json();
  5648. },
  5649. // Timelapse Editor
  5650. getTimelapseInfo: (archiveId: number) =>
  5651. request<{
  5652. duration: number;
  5653. width: number;
  5654. height: number;
  5655. fps: number;
  5656. codec: string;
  5657. file_size: number;
  5658. has_audio: boolean;
  5659. }>(`/archives/${archiveId}/timelapse/info`),
  5660. getTimelapseThumbnails: (archiveId: number, count: number = 10) =>
  5661. request<{
  5662. thumbnails: string[];
  5663. timestamps: number[];
  5664. }>(`/archives/${archiveId}/timelapse/thumbnails?count=${count}`),
  5665. processTimelapse: async (
  5666. archiveId: number,
  5667. params: {
  5668. trimStart?: number;
  5669. trimEnd?: number;
  5670. speed?: number;
  5671. /** Music volume, 0 to 1. */
  5672. audioVolume?: number;
  5673. saveMode: 'replace' | 'new';
  5674. outputFilename?: string;
  5675. },
  5676. audioFile?: File
  5677. ): Promise<TimelapseJob> => {
  5678. const formData = new FormData();
  5679. formData.append('trim_start', String(params.trimStart ?? 0));
  5680. if (params.trimEnd !== undefined) {
  5681. formData.append('trim_end', String(params.trimEnd));
  5682. }
  5683. formData.append('speed', String(params.speed ?? 1));
  5684. if (params.audioVolume !== undefined) {
  5685. formData.append('audio_volume', String(params.audioVolume));
  5686. }
  5687. formData.append('save_mode', params.saveMode);
  5688. if (params.outputFilename) {
  5689. formData.append('output_filename', params.outputFilename);
  5690. }
  5691. if (audioFile) {
  5692. formData.append('audio', audioFile);
  5693. }
  5694. const headers: Record<string, string> = {};
  5695. if (authToken) {
  5696. headers['Authorization'] = `Bearer ${authToken}`;
  5697. }
  5698. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/process`, {
  5699. method: 'POST',
  5700. headers,
  5701. body: formData,
  5702. });
  5703. if (!response.ok) {
  5704. const error = await response.json().catch(() => ({}));
  5705. throw new Error(error.detail || `HTTP ${response.status}`);
  5706. }
  5707. return response.json();
  5708. },
  5709. // The archive's running or last re-encode; null when there has been none.
  5710. getTimelapseJob: async (archiveId: number): Promise<TimelapseJob | null> => {
  5711. try {
  5712. return await request<TimelapseJob>(`/archives/${archiveId}/timelapse/job`);
  5713. } catch (error) {
  5714. if (error instanceof ApiError && error.status === 404) return null;
  5715. throw error;
  5716. }
  5717. },
  5718. cancelTimelapseJob: (archiveId: number) =>
  5719. request<TimelapseJob>(`/archives/${archiveId}/timelapse/job`, { method: 'DELETE' }),
  5720. // Photos
  5721. getArchivePhotoUrl: (archiveId: number, filename: string) =>
  5722. withMediaToken(`${API_BASE}/archives/${archiveId}/photos/${encodeURIComponent(filename)}`),
  5723. uploadArchivePhoto: async (archiveId: number, file: File): Promise<{ status: string; filename: string; photos: string[] }> => {
  5724. const formData = new FormData();
  5725. formData.append('file', file);
  5726. const headers: Record<string, string> = {};
  5727. if (authToken) {
  5728. headers['Authorization'] = `Bearer ${authToken}`;
  5729. }
  5730. const response = await fetch(`${API_BASE}/archives/${archiveId}/photos`, {
  5731. headers,
  5732. method: 'POST',
  5733. body: formData,
  5734. });
  5735. if (!response.ok) {
  5736. const error = await response.json().catch(() => ({}));
  5737. throw new Error(error.detail || `HTTP ${response.status}`);
  5738. }
  5739. return response.json();
  5740. },
  5741. deleteArchivePhoto: (archiveId: number, filename: string) =>
  5742. request<{ status: string; photos: string[] | null }>(`/archives/${archiveId}/photos/${encodeURIComponent(filename)}`, {
  5743. method: 'DELETE',
  5744. }),
  5745. // Source 3MF (original slicer project file)
  5746. getSource3mfDownloadUrl: (archiveId: number) =>
  5747. `${API_BASE}/archives/${archiveId}/source`,
  5748. downloadSource3mf: async (archiveId: number): Promise<void> => {
  5749. const headers: Record<string, string> = {};
  5750. if (authToken) {
  5751. headers['Authorization'] = `Bearer ${authToken}`;
  5752. }
  5753. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, { headers });
  5754. if (!response.ok) {
  5755. const error = await response.json().catch(() => ({}));
  5756. throw new Error(error.detail || `HTTP ${response.status}`);
  5757. }
  5758. const disposition = response.headers.get('Content-Disposition');
  5759. const filename = parseContentDispositionFilename(disposition) || `source_${archiveId}.3mf`;
  5760. const blob = await response.blob();
  5761. const url = window.URL.createObjectURL(blob);
  5762. const a = document.createElement('a');
  5763. a.href = url;
  5764. a.download = filename;
  5765. document.body.appendChild(a);
  5766. a.click();
  5767. document.body.removeChild(a);
  5768. window.URL.revokeObjectURL(url);
  5769. },
  5770. getSource3mfForSlicer: (archiveId: number, filename: string) => {
  5771. // Sanitize: slicers url_decode() the entire URL, so / \ ? # in filenames break path routing
  5772. const safe = filename.replace(/[/\\?#]/g, '_');
  5773. return `${API_BASE}/archives/${archiveId}/source/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  5774. },
  5775. createSourceSlicerToken: (archiveId: number) =>
  5776. request<{ token: string }>(`/archives/${archiveId}/source-slicer-token`, { method: 'POST' }),
  5777. getSourceSlicerDownloadUrl: (archiveId: number, token: string, filename: string) => {
  5778. const safe = filename.replace(/[/\\?#]/g, '_');
  5779. return `${API_BASE}/archives/${archiveId}/source-dl/${token}/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  5780. },
  5781. uploadSource3mf: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  5782. const formData = new FormData();
  5783. formData.append('file', file);
  5784. const headers: Record<string, string> = {};
  5785. if (authToken) {
  5786. headers['Authorization'] = `Bearer ${authToken}`;
  5787. }
  5788. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, {
  5789. method: 'POST',
  5790. headers,
  5791. body: formData,
  5792. });
  5793. if (!response.ok) {
  5794. const error = await response.json().catch(() => ({}));
  5795. throw new Error(error.detail || `HTTP ${response.status}`);
  5796. }
  5797. return response.json();
  5798. },
  5799. deleteSource3mf: (archiveId: number) =>
  5800. request<{ status: string }>(`/archives/${archiveId}/source`, {
  5801. method: 'DELETE',
  5802. }),
  5803. // F3D (Fusion 360 design file)
  5804. downloadF3d: async (archiveId: number): Promise<void> => {
  5805. const headers: Record<string, string> = {};
  5806. if (authToken) {
  5807. headers['Authorization'] = `Bearer ${authToken}`;
  5808. }
  5809. const response = await fetch(`${API_BASE}/archives/${archiveId}/f3d`, { headers });
  5810. if (!response.ok) {
  5811. const error = await response.json().catch(() => ({}));
  5812. throw new Error(error.detail || `HTTP ${response.status}`);
  5813. }
  5814. const disposition = response.headers.get('Content-Disposition');
  5815. const filename = parseContentDispositionFilename(disposition) || `archive_${archiveId}.f3d`;
  5816. const blob = await response.blob();
  5817. const url = window.URL.createObjectURL(blob);
  5818. const a = document.createElement('a');
  5819. a.href = url;
  5820. a.download = filename;
  5821. document.body.appendChild(a);
  5822. a.click();
  5823. document.body.removeChild(a);
  5824. window.URL.revokeObjectURL(url);
  5825. },
  5826. uploadF3d: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  5827. const formData = new FormData();
  5828. formData.append('file', file);
  5829. const headers: Record<string, string> = {};
  5830. if (authToken) {
  5831. headers['Authorization'] = `Bearer ${authToken}`;
  5832. }
  5833. const response = await fetch(`${API_BASE}/archives/${archiveId}/f3d`, {
  5834. method: 'POST',
  5835. headers,
  5836. body: formData,
  5837. });
  5838. if (!response.ok) {
  5839. const error = await response.json().catch(() => ({}));
  5840. throw new Error(error.detail || `HTTP ${response.status}`);
  5841. }
  5842. return response.json();
  5843. },
  5844. deleteF3d: (archiveId: number) =>
  5845. request<{ status: string }>(`/archives/${archiveId}/f3d`, {
  5846. method: 'DELETE',
  5847. }),
  5848. // QR Code
  5849. getArchiveQRCodeUrl: (archiveId: number, size = 200) =>
  5850. withMediaToken(`${API_BASE}/archives/${archiveId}/qrcode?size=${size}`),
  5851. getArchiveCapabilities: (id: number) =>
  5852. request<{
  5853. has_model: boolean;
  5854. has_gcode: boolean;
  5855. has_source: boolean;
  5856. build_volume: { x: number; y: number; z: number };
  5857. filament_colors: string[];
  5858. }>(`/archives/${id}/capabilities`),
  5859. // Project Page
  5860. getArchiveProjectPage: (id: number) =>
  5861. request<{
  5862. title: string | null;
  5863. description: string | null;
  5864. designer: string | null;
  5865. designer_user_id: string | null;
  5866. license: string | null;
  5867. copyright: string | null;
  5868. creation_date: string | null;
  5869. modification_date: string | null;
  5870. origin: string | null;
  5871. profile_title: string | null;
  5872. profile_description: string | null;
  5873. profile_cover: string | null;
  5874. profile_user_id: string | null;
  5875. profile_user_name: string | null;
  5876. design_model_id: string | null;
  5877. design_profile_id: string | null;
  5878. design_region: string | null;
  5879. model_pictures: Array<{ name: string; path: string; url: string }>;
  5880. profile_pictures: Array<{ name: string; path: string; url: string }>;
  5881. thumbnails: Array<{ name: string; path: string; url: string }>;
  5882. }>(`/archives/${id}/project-page`),
  5883. updateArchiveProjectPage: (id: number, data: {
  5884. title?: string;
  5885. description?: string;
  5886. designer?: string;
  5887. license?: string;
  5888. copyright?: string;
  5889. profile_title?: string;
  5890. profile_description?: string;
  5891. }) =>
  5892. request(`/archives/${id}/project-page`, {
  5893. method: 'PATCH',
  5894. body: JSON.stringify(data),
  5895. }),
  5896. getArchiveForSlicer: (id: number, filename: string) => {
  5897. const safe = filename.replace(/[/\\?#]/g, '_');
  5898. return `${API_BASE}/archives/${id}/file/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  5899. },
  5900. createArchiveSlicerToken: (archiveId: number) =>
  5901. request<{ token: string }>(`/archives/${archiveId}/slicer-token`, { method: 'POST' }),
  5902. getArchiveSlicerDownloadUrl: (archiveId: number, token: string, filename: string) => {
  5903. const safe = filename.replace(/[/\\?#]/g, '_');
  5904. return `${API_BASE}/archives/${archiveId}/dl/${token}/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  5905. },
  5906. getArchivePlates: (archiveId: number) =>
  5907. request<ArchivePlatesResponse>(`/archives/${archiveId}/plates`),
  5908. getArchiveFilamentRequirements: (
  5909. archiveId: number,
  5910. plateId?: number,
  5911. requestId?: string,
  5912. /** Ask for one entry per project slot instead of only the slots this
  5913. * plate consumes. The slice modal needs it: its filament list is
  5914. * positional, so a source whose only used slot is 4 must still present
  5915. * four rows or the user's pick is bound to slot 1 (#2712). Print-time
  5916. * AMS matching must NOT set this — it wants the used-only list. */
  5917. fullSlots?: boolean,
  5918. ) => {
  5919. const qs = new URLSearchParams();
  5920. if (plateId !== undefined) qs.set('plate_id', String(plateId));
  5921. if (requestId) qs.set('request_id', requestId);
  5922. if (fullSlots) qs.set('full_slots', 'true');
  5923. return request<{
  5924. archive_id: number;
  5925. filename: string;
  5926. plate_id: number | null;
  5927. filaments: Array<{
  5928. slot_id: number;
  5929. type: string;
  5930. color: string;
  5931. used_grams: number;
  5932. used_meters: number;
  5933. used_in_plate?: boolean;
  5934. }>;
  5935. }>(`/archives/${archiveId}/filament-requirements${qs.toString() ? `?${qs}` : ''}`);
  5936. },
  5937. uploadArchivesBulk: async (files: File[], printerId?: number): Promise<BulkUploadResult> => {
  5938. const formData = new FormData();
  5939. files.forEach((file) => formData.append('files', file));
  5940. const url = printerId
  5941. ? `${API_BASE}/archives/upload-bulk?printer_id=${printerId}`
  5942. : `${API_BASE}/archives/upload-bulk`;
  5943. const headers: Record<string, string> = {};
  5944. if (authToken) {
  5945. headers['Authorization'] = `Bearer ${authToken}`;
  5946. }
  5947. const response = await fetch(url, {
  5948. method: 'POST',
  5949. headers,
  5950. body: formData,
  5951. });
  5952. if (!response.ok) {
  5953. const error = await response.json().catch(() => ({}));
  5954. throw new Error(error.detail || `HTTP ${response.status}`);
  5955. }
  5956. return response.json();
  5957. },
  5958. // Print Log
  5959. getPrintLog: (params?: {
  5960. search?: string;
  5961. printerId?: number;
  5962. username?: string;
  5963. status?: string;
  5964. dateFrom?: string;
  5965. dateTo?: string;
  5966. limit?: number;
  5967. offset?: number;
  5968. // Sorting is server-side because paging is: ordering only the rows the
  5969. // client holds would sort one page, not the log (#2636).
  5970. sortBy?: string;
  5971. sortDir?: 'asc' | 'desc';
  5972. }) => {
  5973. const searchParams = new URLSearchParams();
  5974. if (params?.search) searchParams.set('search', params.search);
  5975. if (params?.printerId) searchParams.set('printer_id', String(params.printerId));
  5976. if (params?.username) searchParams.set('created_by_username', params.username);
  5977. if (params?.status) searchParams.set('status', params.status);
  5978. if (params?.dateFrom) searchParams.set('date_from', params.dateFrom);
  5979. if (params?.dateTo) searchParams.set('date_to', params.dateTo);
  5980. if (params?.limit) searchParams.set('limit', String(params.limit));
  5981. if (params?.offset !== undefined) searchParams.set('offset', String(params.offset));
  5982. if (params?.sortBy) searchParams.set('sort_by', params.sortBy);
  5983. if (params?.sortDir) searchParams.set('sort_dir', params.sortDir);
  5984. return request<PrintLogResponse>(`/print-log/?${searchParams}`);
  5985. },
  5986. getPrintLogThumbnail: (id: number) => withMediaToken(`${API_BASE}/print-log/${id}/thumbnail`),
  5987. clearPrintLog: () =>
  5988. request<{ deleted: number }>('/print-log/', { method: 'DELETE' }),
  5989. deletePrintLogEntry: (id: number) =>
  5990. request<{ status: string; id: number }>(`/print-log/${id}`, { method: 'DELETE' }),
  5991. // Edit failure_reason / status on a single Print Log row (#1687 part 4).
  5992. // Distinct from updateArchive: archives describe the model, log entries
  5993. // describe a single print event. Orphan entries (no archive_id) have no
  5994. // archive to reach through and this is the only path to classify them.
  5995. updatePrintLogEntry: (
  5996. id: number,
  5997. body: { failure_reason?: string | null; status?: string; notes?: string | null },
  5998. ) =>
  5999. request<PrintLogEntry>(`/print-log/${id}`, {
  6000. method: 'PATCH',
  6001. body: JSON.stringify(body),
  6002. }),
  6003. // Settings
  6004. getSettings: () => request<AppSettings>('/settings/'),
  6005. getDefaultSidebarOrder: () => request<{ default_sidebar_order: string }>('/settings/default-sidebar-order'),
  6006. // Public subset of settings for UI rendering — no settings:read required.
  6007. // Used by pages whose users may not have SETTINGS_READ (e.g. operators with
  6008. // only printers:clear_plate). Keep in sync with _UI_PREFERENCE_FIELDS in
  6009. // backend/app/api/routes/settings.py.
  6010. getUiPreferences: () =>
  6011. request<{
  6012. require_plate_clear?: boolean;
  6013. check_printer_firmware?: boolean;
  6014. camera_view_mode?: 'window' | 'embedded';
  6015. time_format?: 'system' | '12h' | '24h';
  6016. date_format?: string;
  6017. drying_presets?: string;
  6018. ams_humidity_thresholds?: string;
  6019. ams_humidity_good?: number;
  6020. ams_humidity_fair?: number;
  6021. ams_temp_good?: number;
  6022. ams_temp_fair?: number;
  6023. bed_cooled_threshold?: number;
  6024. nozzle_temp_presets?: string;
  6025. bed_temp_presets?: string;
  6026. chamber_temp_presets?: string;
  6027. fan_speed_presets?: string;
  6028. }>('/settings/ui-preferences'),
  6029. // Install configuration the app shell needs, for any signed-in user. Separate
  6030. // from getUiPreferences: that endpoint is public because its fields are
  6031. // defaults shipped with the app, while these describe how this deployment is
  6032. // configured. Neither requires settings:read -- which is the point, since a
  6033. // non-admin reading GET /settings gets a 403 and every gate that consults it
  6034. // silently takes its fallback (#3023). Keep in sync with _UI_FLAG_FIELDS in
  6035. // backend/app/api/routes/settings.py.
  6036. getUiFlags: () => request<UiSettings>('/settings/ui-flags'),
  6037. // The two above together: what a page needs from the settings when its user
  6038. // may not read GET /settings. See useUiSettings.
  6039. getUiSettings: async (): Promise<UiSettings> => {
  6040. const [preferences, flags] = await Promise.all([api.getUiPreferences(), api.getUiFlags()]);
  6041. return { ...(preferences as UiSettings), ...flags };
  6042. },
  6043. updateSettings: (data: AppSettingsUpdate) =>
  6044. request<AppSettings>('/settings/', {
  6045. method: 'PUT',
  6046. body: JSON.stringify(data),
  6047. }),
  6048. getMQTTStatus: () => request<MQTTStatus>('/settings/mqtt/status'),
  6049. exportBackup: async (): Promise<{ blob: Blob; filename: string }> => {
  6050. // New simplified backup - complete database + all files
  6051. const url = `${API_BASE}/settings/backup`;
  6052. const headers: Record<string, string> = {};
  6053. if (authToken) {
  6054. headers['Authorization'] = `Bearer ${authToken}`;
  6055. }
  6056. const response = await fetch(url, { headers });
  6057. // Check for errors
  6058. if (!response.ok) {
  6059. const errorText = await response.text();
  6060. throw new Error(errorText || `Backup failed with status ${response.status}`);
  6061. }
  6062. // Get filename from Content-Disposition header
  6063. const contentDisposition = response.headers.get('Content-Disposition');
  6064. let filename = 'bambuddy-backup.zip';
  6065. if (contentDisposition) {
  6066. const match = contentDisposition.match(/filename=([^;]+)/);
  6067. if (match) filename = match[1].trim().replace(/^"(.*)"$/, '$1');
  6068. }
  6069. const blob = await response.blob();
  6070. return { blob, filename };
  6071. },
  6072. importBackup: async (file: File) => {
  6073. // New simplified restore - replaces database + all directories
  6074. const formData = new FormData();
  6075. formData.append('file', file);
  6076. const url = `${API_BASE}/settings/restore`;
  6077. const headers: Record<string, string> = {};
  6078. if (authToken) {
  6079. headers['Authorization'] = `Bearer ${authToken}`;
  6080. }
  6081. const response = await fetch(url, {
  6082. method: 'POST',
  6083. headers,
  6084. body: formData,
  6085. });
  6086. const data = (await response.json().catch(() => null)) as {
  6087. success?: boolean;
  6088. message?: string;
  6089. detail?: string;
  6090. } | null;
  6091. // A refused restore is an HTTPException, so the body is {detail}, not
  6092. // {success, message}. Returning it unmapped made `success` undefined and
  6093. // `message` undefined too — the modal then raised an empty error toast,
  6094. // which is the one case where the reason matters most (e.g. a backup this
  6095. // version cannot import names the columns and both versions).
  6096. if (!response.ok) {
  6097. return { success: false, message: data?.detail ?? data?.message ?? '' };
  6098. }
  6099. return (data ?? { success: false, message: '' }) as {
  6100. success: boolean;
  6101. message: string;
  6102. };
  6103. },
  6104. checkFfmpeg: () =>
  6105. request<{ installed: boolean; path: string | null }>('/settings/check-ffmpeg'),
  6106. getNetworkInterfaces: () =>
  6107. request<{ interfaces: NetworkInterface[] }>('/settings/network-interfaces'),
  6108. // Cloud
  6109. getCloudStatus: () => request<CloudAuthStatus>('/cloud/status'),
  6110. cloudLogin: (email: string, password: string, region = 'global') =>
  6111. request<CloudLoginResponse>('/cloud/login', {
  6112. method: 'POST',
  6113. body: JSON.stringify({ email, password, region }),
  6114. }),
  6115. cloudVerify: (email: string, code: string, tfaKey?: string, region: string = 'global') =>
  6116. request<CloudLoginResponse>('/cloud/verify', {
  6117. method: 'POST',
  6118. body: JSON.stringify({ email, code, tfa_key: tfaKey, region }),
  6119. }),
  6120. cloudSetToken: (access_token: string, region: string = 'global') =>
  6121. request<CloudAuthStatus>('/cloud/token', {
  6122. method: 'POST',
  6123. body: JSON.stringify({ access_token, region }),
  6124. }),
  6125. cloudLogout: () =>
  6126. request<{ success: boolean }>('/cloud/logout', { method: 'POST' }),
  6127. // Orca Cloud — RFC 8628 device pairing. deviceStart() returns a short
  6128. // user_code + verification link; the user approves it in their Orca Cloud
  6129. // settings while the frontend polls devicePoll() every `interval` seconds
  6130. // until the status flips to 'complete' (or a terminal deny/expire).
  6131. orcaCloudDeviceStart: () =>
  6132. request<OrcaDeviceStartResponse>('/orca-cloud/device/start', {
  6133. method: 'POST',
  6134. }),
  6135. orcaCloudDevicePoll: () =>
  6136. request<OrcaDevicePollResponse>('/orca-cloud/device/poll', {
  6137. method: 'POST',
  6138. }),
  6139. orcaCloudStatus: () =>
  6140. request<OrcaAuthStatusResponse>('/orca-cloud/status'),
  6141. orcaCloudLogout: () =>
  6142. request<{ success: boolean }>('/orca-cloud/logout', { method: 'POST' }),
  6143. orcaCloudListProfiles: () =>
  6144. request<OrcaProfileListResponse>('/orca-cloud/profiles'),
  6145. orcaCloudGetProfile: (id: string) =>
  6146. request<OrcaProfileDetail>(`/orca-cloud/profiles/${id}`),
  6147. getCloudSettings: (version = '02.04.00.70') =>
  6148. request<SlicerSettingsResponse>(`/cloud/settings?version=${version}`),
  6149. getBuiltinFilaments: () =>
  6150. request<BuiltinFilament[]>('/cloud/builtin-filaments'),
  6151. getFilamentIdMap: () =>
  6152. request<Record<string, string>>('/cloud/filament-id-map'),
  6153. /** Material-disambiguated hex→name lookup. Same hex can map to different
  6154. * catalog names depending on material (e.g. #000000 is "Charcoal" in PLA
  6155. * Matte but "Black" in PLA Basic). The flat ``/inventory/colors/map``
  6156. * collapses these to the first hit; this endpoint preserves the material
  6157. * context. Returns ``{color_name: null}`` when the hex isn't in the
  6158. * catalog at all. #1718. */
  6159. getColorByMaterial: (hex: string, material?: string) => {
  6160. const params = new URLSearchParams({ hex });
  6161. if (material) params.set('material', material);
  6162. return request<{ color_name: string | null }>(
  6163. `/inventory/colors/by-material?${params.toString()}`,
  6164. );
  6165. },
  6166. // MakerWorld URL-paste import flow.
  6167. getMakerworldStatus: () =>
  6168. request<MakerworldStatus>('/makerworld/status'),
  6169. resolveMakerworldUrl: (url: string) =>
  6170. request<MakerworldResolvedModel>('/makerworld/resolve', {
  6171. method: 'POST',
  6172. body: JSON.stringify({ url }),
  6173. }),
  6174. getMakerworldRecentImports: (limit = 10) =>
  6175. request<MakerworldRecentImport[]>(`/makerworld/recent-imports?limit=${limit}`),
  6176. importMakerworldInstance: (
  6177. model_id: number,
  6178. instance_id: number | null,
  6179. profile_id?: number | null,
  6180. folder_id?: number | null,
  6181. ) =>
  6182. request<MakerworldImportResponse>('/makerworld/import', {
  6183. method: 'POST',
  6184. body: JSON.stringify({
  6185. model_id,
  6186. instance_id: instance_id ?? null,
  6187. profile_id: profile_id ?? null,
  6188. folder_id: folder_id ?? null,
  6189. }),
  6190. }),
  6191. // Manyfold (#1471).
  6192. getManyfoldConfig: () => request<ManyfoldConfig>('/manyfold/config'),
  6193. updateManyfoldConfig: (data: ManyfoldConfigInput) =>
  6194. request<ManyfoldConfig>('/manyfold/config', { method: 'PUT', body: JSON.stringify(data) }),
  6195. deleteManyfoldConfig: () => request<void>('/manyfold/config', { method: 'DELETE' }),
  6196. testManyfoldConfig: (data: ManyfoldConfigInput) =>
  6197. request<{ model_count: number }>('/manyfold/config/test', { method: 'POST', body: JSON.stringify(data) }),
  6198. getManyfoldStatus: () => request<ManyfoldStatus>('/manyfold/status'),
  6199. listManyfoldModels: (query: string, page: number) => {
  6200. const params = new URLSearchParams({ page: String(page) });
  6201. if (query) params.set('q', query);
  6202. return request<ManyfoldModelList>(`/manyfold/models?${params.toString()}`);
  6203. },
  6204. getManyfoldModel: (modelId: string) =>
  6205. request<ManyfoldModel>(`/manyfold/models/${encodeURIComponent(modelId)}`),
  6206. /** The model's preview, or null when it has none. Fetched rather than used
  6207. * as an <img src>: a failing protected <img> makes the app renew its media
  6208. * token, and models without a preview answer 404. */
  6209. getManyfoldPreview: async (modelId: string): Promise<Blob | null> => {
  6210. const headers: Record<string, string> = {};
  6211. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  6212. const response = await fetch(`${API_BASE}/manyfold/models/${encodeURIComponent(modelId)}/preview`, { headers });
  6213. if (!response.ok) return null;
  6214. return response.blob();
  6215. },
  6216. importManyfoldFile: (modelId: string, fileId: string, folderId: number | null) =>
  6217. request<ManyfoldImportResponse>('/manyfold/import', {
  6218. method: 'POST',
  6219. body: JSON.stringify({ model_id: modelId, file_id: fileId, folder_id: folderId }),
  6220. }),
  6221. getCloudSettingDetail: (settingId: string) =>
  6222. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`),
  6223. createCloudSetting: (data: SlicerSettingCreate) =>
  6224. request<SlicerSettingDetail>('/cloud/settings', {
  6225. method: 'POST',
  6226. body: JSON.stringify(data),
  6227. }),
  6228. updateCloudSetting: (settingId: string, data: SlicerSettingUpdate) =>
  6229. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`, {
  6230. method: 'PUT',
  6231. body: JSON.stringify(data),
  6232. }),
  6233. deleteCloudSetting: (settingId: string) =>
  6234. request<SlicerSettingDeleteResponse>(`/cloud/settings/${settingId}`, {
  6235. method: 'DELETE',
  6236. }),
  6237. getCloudFields: (presetType: 'filament' | 'print' | 'process' | 'printer') =>
  6238. request<FieldDefinitionsResponse>(`/cloud/fields/${presetType}`),
  6239. getFilamentInfo: (settingIds: string[]) =>
  6240. request<Record<string, { name: string; k: number | null }>>('/cloud/filament-info', {
  6241. method: 'POST',
  6242. body: JSON.stringify(settingIds),
  6243. }),
  6244. // Smart Plugs
  6245. getSmartPlugs: () => request<SmartPlug[]>('/smart-plugs/'),
  6246. getSmartPlugByPrinter: (printerId: number) => smartPlugBatch(printerId),
  6247. getScriptPlugsByPrinter: (printerId: number) => scriptPlugsBatch(printerId),
  6248. createSmartPlug: (data: SmartPlugCreate) =>
  6249. request<SmartPlug>('/smart-plugs/', {
  6250. method: 'POST',
  6251. body: JSON.stringify(data),
  6252. }),
  6253. updateSmartPlug: (id: number, data: SmartPlugUpdate) =>
  6254. request<SmartPlug>(`/smart-plugs/${id}`, {
  6255. method: 'PATCH',
  6256. body: JSON.stringify(data),
  6257. }),
  6258. deleteSmartPlug: (id: number) =>
  6259. request<void>(`/smart-plugs/${id}`, { method: 'DELETE' }),
  6260. controlSmartPlug: (id: number, action: 'on' | 'off' | 'toggle') =>
  6261. request<{ success: boolean; action: string }>(`/smart-plugs/${id}/control`, {
  6262. method: 'POST',
  6263. body: JSON.stringify({ action }),
  6264. }),
  6265. getSmartPlugStatus: (id: number) =>
  6266. request<SmartPlugStatus>(`/smart-plugs/${id}/status`),
  6267. // plug_id: the saved plug being edited, whose stored password fills in the placeholder.
  6268. testSmartPlugConnection: (ip_address: string, username?: string | null, password?: string | null, plug_id?: number) =>
  6269. request<SmartPlugTestResult>('/smart-plugs/test-connection', {
  6270. method: 'POST',
  6271. body: JSON.stringify({ ip_address, username, password, plug_id }),
  6272. }),
  6273. // Tasmota Discovery (auto-detects network)
  6274. startTasmotaScan: () =>
  6275. request<TasmotaScanStatus>('/smart-plugs/discover/scan', { method: 'POST' }),
  6276. getTasmotaScanStatus: () =>
  6277. request<TasmotaScanStatus>('/smart-plugs/discover/status'),
  6278. stopTasmotaScan: () =>
  6279. request<TasmotaScanStatus>('/smart-plugs/discover/stop', { method: 'POST' }),
  6280. getDiscoveredTasmotaDevices: () =>
  6281. request<DiscoveredTasmotaDevice[]>('/smart-plugs/discover/devices'),
  6282. // Home Assistant Integration
  6283. testHAConnection: (url: string, token: string) =>
  6284. request<HATestConnectionResult>('/smart-plugs/ha/test-connection', {
  6285. method: 'POST',
  6286. body: JSON.stringify({ url, token }),
  6287. }),
  6288. getHAEntities: (search?: string) => {
  6289. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  6290. return request<HAEntity[]>(`/smart-plugs/ha/entities${params}`);
  6291. },
  6292. getHASensorEntities: () =>
  6293. request<HASensorEntity[]>('/smart-plugs/ha/sensors'),
  6294. // Home Assistant sensors bound to a printer (#1148, #448)
  6295. getHASensors: (printerId?: number) =>
  6296. request<PrinterHASensor[]>(`/ha-sensors/${printerId ? `?printer_id=${printerId}` : ''}`),
  6297. getHASensorReadings: (printerId: number) => haSensorReadingsBatch(printerId),
  6298. getBindableHAEntities: (search?: string) => {
  6299. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  6300. return request<HADisplayEntity[]>(`/ha-sensors/entities${params}`);
  6301. },
  6302. createHASensor: (data: PrinterHASensorCreate) =>
  6303. request<PrinterHASensor>('/ha-sensors/', { method: 'POST', body: JSON.stringify(data) }),
  6304. updateHASensor: (id: number, data: PrinterHASensorUpdate) =>
  6305. request<PrinterHASensor>(`/ha-sensors/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  6306. deleteHASensor: (id: number) =>
  6307. request<{ message: string }>(`/ha-sensors/${id}`, { method: 'DELETE' }),
  6308. getLocationHASensors: (locationId?: number) =>
  6309. request<LocationHASensor[]>(`/location-ha-sensors/${locationId ? `?location_id=${locationId}` : ''}`),
  6310. getLocationHASensorReadings: (locationId: number, showOnCard = true) =>
  6311. request<LocationHASensorReading[]>(
  6312. `/location-ha-sensors/by-location/${locationId}/readings?show_on_card=${showOnCard}`
  6313. ),
  6314. getBindableLocationHAEntities: (search?: string) => {
  6315. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  6316. return request<HADisplayEntity[]>(`/location-ha-sensors/entities${params}`);
  6317. },
  6318. createLocationHASensor: (data: LocationHASensorCreate) =>
  6319. request<LocationHASensor>('/location-ha-sensors/', { method: 'POST', body: JSON.stringify(data) }),
  6320. updateLocationHASensor: (id: number, data: LocationHASensorUpdate) =>
  6321. request<LocationHASensor>(`/location-ha-sensors/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  6322. deleteLocationHASensor: (id: number) =>
  6323. request<{ message: string }>(`/location-ha-sensors/${id}`, { method: 'DELETE' }),
  6324. // REST smart plug
  6325. // plug_id: the saved plug being edited, whose stored headers fill in the placeholder.
  6326. testRESTConnection: (url: string, method: string = 'GET', headers?: string | null, plug_id?: number) =>
  6327. request<{ success: boolean; error: string | null }>('/smart-plugs/rest/test-connection', {
  6328. method: 'POST',
  6329. body: JSON.stringify({ url, method, headers, plug_id }),
  6330. }),
  6331. // Print Queue
  6332. getQueue: (printerId?: number, status?: string, targetModel?: string) => {
  6333. const params = new URLSearchParams();
  6334. if (printerId) params.set('printer_id', String(printerId));
  6335. if (status) params.set('status', status);
  6336. if (targetModel) params.set('target_model', targetModel);
  6337. return request<PrintQueueItem[]>(`/queue/?${params}`);
  6338. },
  6339. // History (completed / failed / skipped / cancelled), one page at a time.
  6340. getQueueHistory: (params: QueueHistoryParams) =>
  6341. request<QueueHistoryPage>(`/queue/history?${queueHistorySearch(params)}`),
  6342. // Removes the history matching the same filters, server-side.
  6343. clearQueueHistory: (params: QueueHistoryFilters) =>
  6344. request<{ cleared: number; kept: number }>(`/queue/history/clear?${queueHistorySearch(params)}`, {
  6345. method: 'POST',
  6346. }),
  6347. // One printer's queue as GET /queue/?printer_id= returns it: its own jobs
  6348. // plus the "Any <model>" jobs for its model. Batched across printer cards.
  6349. getPrinterQueue: (printerId: number, status: string) => printerQueueBatch(status)(printerId),
  6350. addToQueue: (data: PrintQueueItemCreate) =>
  6351. request<PrintQueueItem>('/queue/', {
  6352. method: 'POST',
  6353. body: JSON.stringify(data),
  6354. }),
  6355. updateQueueItem: (id: number, data: PrintQueueItemUpdate) =>
  6356. request<PrintQueueItem>(`/queue/${id}`, {
  6357. method: 'PATCH',
  6358. body: JSON.stringify(data),
  6359. }),
  6360. /** `deleted` is false when the item was kept as cancelled instead: it is the
  6361. * last run a batch order could re-queue its plate from (#2960). */
  6362. removeFromQueue: (id: number) =>
  6363. request<{ message: string; deleted: boolean }>(`/queue/${id}`, { method: 'DELETE' }),
  6364. reorderQueue: (items: { id: number; position: number }[]) =>
  6365. request<{ message: string }>('/queue/reorder', {
  6366. method: 'POST',
  6367. body: JSON.stringify({ items }),
  6368. }),
  6369. cancelQueueItem: (id: number) =>
  6370. request<{ message: string }>(`/queue/${id}/cancel`, { method: 'POST' }),
  6371. stopQueueItem: (id: number) =>
  6372. request<{ message: string }>(`/queue/${id}/stop`, { method: 'POST' }),
  6373. /**
  6374. * Start a staged queue item. The backend re-checks live filament deficit
  6375. * for the assigned spool and, when short, returns 409 with a structured
  6376. * payload so the caller can confirm and retry. Pass `skipFilamentCheck`
  6377. * after the user confirms "Print Anyway" (#1496).
  6378. */
  6379. startQueueItem: (id: number, opts?: { skipFilamentCheck?: boolean }) => {
  6380. const qs = opts?.skipFilamentCheck ? '?skip_filament_check=true' : '';
  6381. return request<PrintQueueItem>(`/queue/${id}/start${qs}`, { method: 'POST' });
  6382. },
  6383. /**
  6384. * Clear the `require_previous_success` gate for a printer after the user
  6385. * resolves the failure. Acknowledges any failed/aborted predecessors and
  6386. * restores skipped items whose error_message matches the gate string
  6387. * back to pending. Returns counts so the UI can render a precise toast.
  6388. */
  6389. // A job for any printer of a model waits when the last print failed on every
  6390. // free one; this clears the gate on the model's printers.
  6391. resumeModelQueueAfterFailure: (model: string) =>
  6392. request<{ acknowledged: number; printers: number }>(
  6393. `/queue/model/${encodeURIComponent(model)}/resume`,
  6394. { method: 'POST' },
  6395. ),
  6396. resumeQueueAfterFailure: (printerId: number) =>
  6397. request<{ acknowledged: number; restored: number }>(
  6398. `/queue/printer/${printerId}/resume`,
  6399. { method: 'POST' },
  6400. ),
  6401. bulkUpdateQueue: (data: PrintQueueBulkUpdate) =>
  6402. request<PrintQueueBulkUpdateResponse>('/queue/bulk', {
  6403. method: 'PATCH',
  6404. body: JSON.stringify(data),
  6405. }),
  6406. // Batches
  6407. getBatches: (status?: string) => {
  6408. const params = status ? `?status=${status}` : '';
  6409. return request<PrintBatch[]>(`/queue/batches${params}`);
  6410. },
  6411. cancelBatch: (id: number) =>
  6412. request<{ message: string }>(`/queue/batches/${id}`, { method: 'DELETE' }),
  6413. createBatch: (data: PrintBatchCreate) =>
  6414. request<PrintBatch>('/queue/batches', {
  6415. method: 'POST',
  6416. body: JSON.stringify(data),
  6417. }),
  6418. dispatchBatch: (id: number, data: PrintBatchDispatchRequest = {}) =>
  6419. request<PrintBatch>(`/queue/batches/${id}/dispatch`, {
  6420. method: 'POST',
  6421. body: JSON.stringify(data),
  6422. }),
  6423. ungroupBatch: (id: number) =>
  6424. request<{ ungrouped_count: number; message: string }>(
  6425. `/queue/batches/${id}/ungroup`,
  6426. { method: 'POST' },
  6427. ),
  6428. // K-Profiles
  6429. getKProfiles: (printerId: number, nozzleDiameter = '0.4') =>
  6430. request<KProfilesResponse>(`/printers/${printerId}/kprofiles/?nozzle_diameter=${nozzleDiameter}`),
  6431. setKProfile: (printerId: number, profile: KProfileCreate) =>
  6432. request<KProfileWriteResult>(`/printers/${printerId}/kprofiles/`, {
  6433. method: 'POST',
  6434. body: JSON.stringify(profile),
  6435. }),
  6436. deleteKProfile: (printerId: number, profile: KProfileDelete) =>
  6437. request<KProfileWriteResult>(`/printers/${printerId}/kprofiles/`, {
  6438. method: 'DELETE',
  6439. body: JSON.stringify(profile),
  6440. }),
  6441. setKProfilesBatch: (printerId: number, profiles: KProfileCreate[]) =>
  6442. request<KProfileWriteResult>(`/printers/${printerId}/kprofiles/batch`, {
  6443. method: 'POST',
  6444. body: JSON.stringify(profiles),
  6445. }),
  6446. // Finance
  6447. getMyBalance: () => request<WalletBalance>('/finance/me/balance'),
  6448. getMyTransactions: (limit = 50, offset = 0) =>
  6449. request<WalletTransactionListResponse>(`/finance/me/transactions?limit=${limit}&offset=${offset}`),
  6450. getAllTransactions: (limit = 50, offset = 0, userId?: number) => {
  6451. const params = new URLSearchParams();
  6452. params.set('limit', String(limit));
  6453. params.set('offset', String(offset));
  6454. if (userId !== undefined) params.set('user_id', String(userId));
  6455. return request<WalletTransactionListResponse>(`/finance/transactions?${params.toString()}`);
  6456. },
  6457. deleteTransaction: (transactionId: number) =>
  6458. request<{ status: string }>(`/finance/transactions/${transactionId}`, {
  6459. method: 'DELETE',
  6460. }),
  6461. editTransaction: (transactionId: number, data: TransactionEditRequest) =>
  6462. request<WalletTransaction>(`/finance/transactions/${transactionId}`, {
  6463. method: 'PATCH',
  6464. body: JSON.stringify(data),
  6465. }),
  6466. createManualPrint: (data: ManualPrintRequest) =>
  6467. request<WalletTransaction>('/finance/transactions/manual', {
  6468. method: 'POST',
  6469. body: JSON.stringify(data),
  6470. }),
  6471. getMyCostCenters: () => request<CostCenterSummary[]>('/finance/cost-centers/mine'),
  6472. listCostCenters: (includeInactive = false) =>
  6473. request<CostCenterSummary[]>(`/finance/cost-centers?include_inactive=${includeInactive ? 'true' : 'false'}`),
  6474. createCostCenter: (data: CostCenterCreateRequest) =>
  6475. request<CostCenterSummary>('/finance/cost-centers', {
  6476. method: 'POST',
  6477. body: JSON.stringify(data),
  6478. }),
  6479. updateCostCenter: (costCenterId: number, data: CostCenterUpdateRequest) =>
  6480. request<CostCenterSummary>(`/finance/cost-centers/${costCenterId}`, {
  6481. method: 'PATCH',
  6482. body: JSON.stringify(data),
  6483. }),
  6484. updateCostCenterBudgets: (costCenterId: number, data: CostCenterBudgetUpdateRequest) =>
  6485. request<CostCenterSummary>(`/finance/cost-centers/${costCenterId}/budgets`, {
  6486. method: 'PATCH',
  6487. body: JSON.stringify(data),
  6488. }),
  6489. deleteCostCenter: (costCenterId: number) =>
  6490. request<{ status: string }>(`/finance/cost-centers/${costCenterId}`, {
  6491. method: 'DELETE',
  6492. }),
  6493. getCostCenter: (costCenterId: number) =>
  6494. request<CostCenterDetail>(`/finance/cost-centers/${costCenterId}`),
  6495. upsertCostCenterMember: (costCenterId: number, data: CostCenterMemberRequest) =>
  6496. request<CostCenterMemberResponse>(`/finance/cost-centers/${costCenterId}/members`, {
  6497. method: 'POST',
  6498. body: JSON.stringify(data),
  6499. }),
  6500. removeCostCenterMember: (costCenterId: number, userId: number) =>
  6501. request<{ status: string }>(`/finance/cost-centers/${costCenterId}/members/${userId}`, {
  6502. method: 'DELETE',
  6503. }),
  6504. depositUserBalance: (userId: number, data: WalletAdjustmentRequest) =>
  6505. request<WalletAdjustmentResponse>(`/finance/users/${userId}/deposit`, {
  6506. method: 'POST',
  6507. body: JSON.stringify(data),
  6508. }),
  6509. withdrawUserBalance: (userId: number, data: WalletAdjustmentRequest) =>
  6510. request<WalletAdjustmentResponse>(`/finance/users/${userId}/withdraw`, {
  6511. method: 'POST',
  6512. body: JSON.stringify(data),
  6513. }),
  6514. rebuildBalanceLedger: () =>
  6515. request<{ status: string }>('/finance/rebuild-balance-ledger', {
  6516. method: 'POST',
  6517. }),
  6518. // K-Profile Notes (stored locally, not on printer)
  6519. getKProfileNotes: (printerId: number) =>
  6520. request<KProfileNotesResponse>(`/printers/${printerId}/kprofiles/notes`),
  6521. setKProfileNote: (printerId: number, settingId: string, note: string) =>
  6522. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/notes`, {
  6523. method: 'PUT',
  6524. body: JSON.stringify({ setting_id: settingId, note }),
  6525. }),
  6526. // Slot Preset Mappings
  6527. getSlotPresets: (printerId: number) => slotPresetsBatch(printerId),
  6528. saveSlotPreset: (printerId: number, amsId: number, trayId: number, presetId: string, presetName: string, presetSource = 'cloud', trayInfoIdx?: string) =>
  6529. 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)}` : ''}`, {
  6530. method: 'PUT',
  6531. }),
  6532. // AMS Labels (user-defined friendly names)
  6533. getAmsLabels: (printerId: number) => amsLabelsBatch(printerId),
  6534. saveAmsLabel: (printerId: number, amsId: number, label: string, amsSerial = '') =>
  6535. request<{ ams_id: number; label: string }>(
  6536. `/printers/${printerId}/ams-labels/${amsId}`,
  6537. {
  6538. method: 'PUT',
  6539. body: JSON.stringify({ label, ams_serial: amsSerial }),
  6540. }
  6541. ),
  6542. deleteAmsLabel: (printerId: number, amsId: number, amsSerial = '') =>
  6543. request<{ success: boolean }>(`/printers/${printerId}/ams-labels/${amsId}?ams_serial=${encodeURIComponent(amsSerial)}`, {
  6544. method: 'DELETE',
  6545. }),
  6546. configureAmsSlot: (
  6547. printerId: number,
  6548. amsId: number,
  6549. trayId: number,
  6550. config: {
  6551. tray_info_idx: string;
  6552. tray_type: string;
  6553. tray_sub_brands: string;
  6554. tray_color: string;
  6555. nozzle_temp_min: number;
  6556. nozzle_temp_max: number;
  6557. cali_idx: number;
  6558. nozzle_diameter: string;
  6559. setting_id?: string;
  6560. kprofile_filament_id?: string;
  6561. kprofile_setting_id?: string;
  6562. k_value?: number;
  6563. // Orca Cloud profile the slot is set to; the backend looks up its
  6564. // filament id when tray_info_idx is empty (#3216).
  6565. orca_profile_id?: string;
  6566. }
  6567. ) => {
  6568. const params = new URLSearchParams({
  6569. tray_info_idx: config.tray_info_idx,
  6570. tray_type: config.tray_type,
  6571. tray_sub_brands: config.tray_sub_brands,
  6572. tray_color: config.tray_color,
  6573. nozzle_temp_min: config.nozzle_temp_min.toString(),
  6574. nozzle_temp_max: config.nozzle_temp_max.toString(),
  6575. cali_idx: config.cali_idx.toString(),
  6576. nozzle_diameter: config.nozzle_diameter,
  6577. });
  6578. if (config.setting_id) {
  6579. params.set('setting_id', config.setting_id);
  6580. }
  6581. if (config.kprofile_filament_id) {
  6582. params.set('kprofile_filament_id', config.kprofile_filament_id);
  6583. }
  6584. if (config.kprofile_setting_id) {
  6585. params.set('kprofile_setting_id', config.kprofile_setting_id);
  6586. }
  6587. if (config.k_value !== undefined && config.k_value > 0) {
  6588. params.set('k_value', config.k_value.toString());
  6589. }
  6590. if (config.orca_profile_id) {
  6591. params.set('orca_profile_id', config.orca_profile_id);
  6592. }
  6593. return request<{
  6594. success: boolean;
  6595. message: string;
  6596. // The filament id the slot was actually given.
  6597. tray_info_idx?: string;
  6598. // Why an Orca profile went out as the generic for its material, or "".
  6599. orca_fallback_reason?: '' | 'no_filament_id' | 'lookup_failed' | 'no_permission';
  6600. /** A manual K value could not be sent; the filament setting was. */
  6601. k_value_unsent?: boolean;
  6602. }>(
  6603. `/printers/${printerId}/slots/${amsId}/${trayId}/configure?${params}`,
  6604. { method: 'POST' }
  6605. );
  6606. },
  6607. resetAmsSlot: (printerId: number, amsId: number, trayId: number) =>
  6608. request<{ success: boolean; message: string }>(
  6609. `/printers/${printerId}/ams/${amsId}/tray/${trayId}/reset`,
  6610. { method: 'POST' }
  6611. ),
  6612. // Notification Providers
  6613. getNotificationProviders: () => request<NotificationProvider[]>('/notifications/'),
  6614. createNotificationProvider: (data: NotificationProviderCreate) =>
  6615. request<NotificationProvider>('/notifications/', {
  6616. method: 'POST',
  6617. body: JSON.stringify(data),
  6618. }),
  6619. updateNotificationProvider: (id: number, data: NotificationProviderUpdate) =>
  6620. request<NotificationProvider>(`/notifications/${id}`, {
  6621. method: 'PATCH',
  6622. body: JSON.stringify(data),
  6623. }),
  6624. deleteNotificationProvider: (id: number) =>
  6625. request<{ message: string }>(`/notifications/${id}`, { method: 'DELETE' }),
  6626. testNotificationProvider: (id: number) =>
  6627. request<NotificationTestResponse>(`/notifications/${id}/test`, { method: 'POST' }),
  6628. testNotificationConfig: (data: NotificationTestRequest) =>
  6629. request<NotificationTestResponse>('/notifications/test-config', {
  6630. method: 'POST',
  6631. body: JSON.stringify(data),
  6632. }),
  6633. testAllNotificationProviders: () =>
  6634. request<{
  6635. tested: number;
  6636. success: number;
  6637. failed: number;
  6638. results: Array<{
  6639. provider_id: number;
  6640. provider_name: string;
  6641. provider_type: string;
  6642. success: boolean;
  6643. message: string;
  6644. }>;
  6645. }>('/notifications/test-all', { method: 'POST' }),
  6646. // Notification Templates
  6647. getNotificationTemplates: () => request<NotificationTemplate[]>('/notification-templates'),
  6648. updateNotificationTemplate: (id: number, data: NotificationTemplateUpdate) =>
  6649. request<NotificationTemplate>(`/notification-templates/${id}`, {
  6650. method: 'PUT',
  6651. body: JSON.stringify(data),
  6652. }),
  6653. resetNotificationTemplate: (id: number) =>
  6654. request<NotificationTemplate>(`/notification-templates/${id}/reset`, {
  6655. method: 'POST',
  6656. }),
  6657. getTemplateVariables: () => request<EventVariablesResponse[]>('/notification-templates/variables'),
  6658. previewTemplate: (data: TemplatePreviewRequest) =>
  6659. request<TemplatePreviewResponse>('/notification-templates/preview', {
  6660. method: 'POST',
  6661. body: JSON.stringify(data),
  6662. }),
  6663. // Notification Logs
  6664. getNotificationLogs: (params?: {
  6665. limit?: number;
  6666. offset?: number;
  6667. provider_id?: number;
  6668. event_type?: string;
  6669. success?: boolean;
  6670. days?: number;
  6671. }) => {
  6672. const searchParams = new URLSearchParams();
  6673. if (params?.limit) searchParams.set('limit', String(params.limit));
  6674. if (params?.offset) searchParams.set('offset', String(params.offset));
  6675. if (params?.provider_id) searchParams.set('provider_id', String(params.provider_id));
  6676. if (params?.event_type) searchParams.set('event_type', params.event_type);
  6677. if (params?.success !== undefined) searchParams.set('success', String(params.success));
  6678. if (params?.days) searchParams.set('days', String(params.days));
  6679. return request<NotificationLogEntry[]>(`/notifications/logs?${searchParams}`);
  6680. },
  6681. getNotificationLogStats: (days = 7) =>
  6682. request<NotificationLogStats>(`/notifications/logs/stats?days=${days}`),
  6683. clearNotificationLogs: (olderThanDays = 30) =>
  6684. request<{ deleted: number; message: string }>(
  6685. `/notifications/logs?older_than_days=${olderThanDays}`,
  6686. { method: 'DELETE' }
  6687. ),
  6688. // Spoolman Integration
  6689. getSpoolmanStatus: () => request<SpoolmanStatus>('/spoolman/status'),
  6690. migrateSpoolmanTags: (dryRun: boolean) =>
  6691. request<SpoolmanTagMigrationReport>(`/spoolman/inventory/tags/migrate?dry_run=${dryRun}`, {
  6692. method: 'POST',
  6693. }),
  6694. connectSpoolman: () =>
  6695. request<{ success: boolean; message: string }>('/spoolman/connect', {
  6696. method: 'POST',
  6697. }),
  6698. syncPrinterAms: (printerId: number) =>
  6699. request<SpoolmanSyncResult>(`/spoolman/sync/${printerId}`, {
  6700. method: 'POST',
  6701. }),
  6702. syncAllPrintersAms: () =>
  6703. request<SpoolmanSyncResult>('/spoolman/sync-all', {
  6704. method: 'POST',
  6705. }),
  6706. getSpoolmanInventoryFilaments: () =>
  6707. request<SpoolmanFilamentEntry[]>('/spoolman/inventory/filaments'),
  6708. getUnlinkedSpools: () =>
  6709. request<UnlinkedSpool[]>('/spoolman/spools/unlinked'),
  6710. getLinkedSpools: () =>
  6711. request<LinkedSpoolsMap>('/spoolman/spools/linked'),
  6712. linkSpool: (
  6713. spoolId: number,
  6714. context: {
  6715. spoolTag: string;
  6716. printerId: number;
  6717. amsId: number;
  6718. trayId: number;
  6719. }
  6720. ) =>
  6721. request<{ success: boolean; message: string }>(`/spoolman/spools/${spoolId}/link`, {
  6722. method: 'POST',
  6723. body: JSON.stringify({
  6724. spool_tag: context.spoolTag,
  6725. printer_id: context.printerId,
  6726. ams_id: context.amsId,
  6727. tray_id: context.trayId,
  6728. }),
  6729. }),
  6730. unlinkSpool: (spoolId: number) =>
  6731. request<{ success: boolean; message: string }>(`/spoolman/spools/${spoolId}/unlink`, {
  6732. method: 'POST',
  6733. }),
  6734. createSpoolmanSpoolFromSlot: (data: { printer_id: number; ams_id: number; tray_id: number }) =>
  6735. request<{ success: boolean; spool_id: number | null }>(`/spoolman/spools/from-slot`, {
  6736. method: 'POST',
  6737. body: JSON.stringify(data),
  6738. }),
  6739. createSpoolFromSlot: (data: { printer_id: number; ams_id: number; tray_id: number }) =>
  6740. request<InventorySpool>(`/inventory/spools/from-slot`, {
  6741. method: 'POST',
  6742. body: JSON.stringify(data),
  6743. }),
  6744. getSpoolmanSettings: () =>
  6745. 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'),
  6746. 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; }) =>
  6747. 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', {
  6748. method: 'PUT',
  6749. body: JSON.stringify(data),
  6750. }),
  6751. // Inventory
  6752. getSpools: (includeArchived = false) =>
  6753. request<InventorySpool[]>(`/inventory/spools?include_archived=${includeArchived}`),
  6754. getSpool: (id: number) => request<InventorySpool>(`/inventory/spools/${id}`),
  6755. createSpool: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>) =>
  6756. request<InventorySpool>('/inventory/spools', {
  6757. method: 'POST',
  6758. body: JSON.stringify(data),
  6759. }),
  6760. bulkCreateSpools: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>, quantity: number) =>
  6761. request<InventorySpool[]>('/inventory/spools/bulk', {
  6762. method: 'POST',
  6763. body: JSON.stringify({ spool: data, quantity }),
  6764. }),
  6765. // ── CSV import/export (#1576) ────────────────────────────────────────────
  6766. // dry_run=true → preview (no write); omitted → real import. Both share one
  6767. // multipart upload helper; see `uploadSpoolsCsv` below.
  6768. importSpoolsCsvPreview: (file: File): Promise<CsvImportPreview> => uploadSpoolsCsv<CsvImportPreview>(file, true),
  6769. importSpoolsCsv: (file: File): Promise<CsvImportResult> => uploadSpoolsCsv<CsvImportResult>(file, false),
  6770. exportSpoolsCsv: async (): Promise<void> => {
  6771. const headers: Record<string, string> = {};
  6772. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  6773. const response = await fetch(`${API_BASE}/inventory/spools/export`, { headers });
  6774. if (!response.ok) {
  6775. const error = await response.json().catch(() => ({}));
  6776. throw new Error(error.detail || `HTTP ${response.status}`);
  6777. }
  6778. const disposition = response.headers.get('Content-Disposition');
  6779. const filename = parseContentDispositionFilename(disposition) || 'bambuddy_inventory.csv';
  6780. const blob = await response.blob();
  6781. const url = window.URL.createObjectURL(blob);
  6782. const a = document.createElement('a');
  6783. a.href = url;
  6784. a.download = filename;
  6785. document.body.appendChild(a);
  6786. a.click();
  6787. document.body.removeChild(a);
  6788. window.URL.revokeObjectURL(url);
  6789. },
  6790. updateSpool: (id: number, data: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  6791. request<InventorySpool>(`/inventory/spools/${id}`, {
  6792. method: 'PATCH',
  6793. body: JSON.stringify(data),
  6794. }),
  6795. deleteSpool: (id: number) =>
  6796. request<{ status: string }>(`/inventory/spools/${id}`, { method: 'DELETE' }),
  6797. archiveSpool: (id: number) =>
  6798. request<InventorySpool>(`/inventory/spools/${id}/archive`, { method: 'POST' }),
  6799. restoreSpool: (id: number) =>
  6800. request<InventorySpool>(`/inventory/spools/${id}/restore`, { method: 'POST' }),
  6801. resetSpoolConsumedCounter: (id: number) =>
  6802. request<InventorySpool>(`/inventory/spools/${id}/reset-consumed-counter`, { method: 'POST' }),
  6803. bulkResetSpoolConsumedCounter: (spoolIds: number[]) =>
  6804. request<{ reset: number; not_found?: number[]; errors?: Array<{ id: number; status: number; detail: string }> }>(`/inventory/spools/reset-consumed-counter-bulk`, {
  6805. method: 'POST',
  6806. body: JSON.stringify({ spool_ids: spoolIds }),
  6807. }),
  6808. bulkUpdateSpools: (ids: number[], update: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  6809. request<{ updated: number; not_found: number[] }>(`/inventory/spools/bulk-update`, {
  6810. method: 'POST',
  6811. body: JSON.stringify({ ids, update }),
  6812. }),
  6813. bulkDeleteSpools: (ids: number[]) =>
  6814. request<{ deleted: number; not_found: number[] }>(`/inventory/spools/bulk-delete`, {
  6815. method: 'POST',
  6816. body: JSON.stringify({ ids }),
  6817. }),
  6818. bulkArchiveSpools: (ids: number[]) =>
  6819. request<{ archived: number; already_archived: number[]; not_found: number[] }>(`/inventory/spools/bulk-archive`, {
  6820. method: 'POST',
  6821. body: JSON.stringify({ ids }),
  6822. }),
  6823. bulkRestoreSpools: (ids: number[]) =>
  6824. request<{ restored: number; already_active: number[]; not_found: number[] }>(`/inventory/spools/bulk-restore`, {
  6825. method: 'POST',
  6826. body: JSON.stringify({ ids }),
  6827. }),
  6828. getSpoolKProfiles: (spoolId: number) =>
  6829. request<SpoolKProfile[]>(`/inventory/spools/${spoolId}/k-profiles`),
  6830. saveSpoolKProfiles: (spoolId: number, profiles: SpoolKProfileInput[]) =>
  6831. request<SpoolKProfile[]>(`/inventory/spools/${spoolId}/k-profiles`, {
  6832. method: 'PUT',
  6833. body: JSON.stringify(profiles),
  6834. }),
  6835. /**
  6836. * What the spool assigned to this slot is configured to use *here* -- its
  6837. * per-printer-model filament preset and the K profile for this slot's hotend.
  6838. * Nulls when the slot holds no known spool.
  6839. */
  6840. getSlotSpoolDefaults: (printerId: number, amsId: number, trayId: number) =>
  6841. request<SlotSpoolDefaults>(`/printers/${printerId}/slots/${amsId}/${trayId}/spool-defaults`),
  6842. getSpoolFilamentPresets: (spoolId: number) =>
  6843. request<SpoolFilamentPreset[]>(`/inventory/spools/${spoolId}/filament-presets`),
  6844. saveSpoolFilamentPresets: (spoolId: number, presets: SpoolFilamentPresetInput[]) =>
  6845. request<SpoolFilamentPreset[]>(`/inventory/spools/${spoolId}/filament-presets`, {
  6846. method: 'PUT',
  6847. body: JSON.stringify(presets),
  6848. }),
  6849. getProfileDefaults: () => request<ProfileDefault[]>('/inventory/profile-defaults'),
  6850. resolveProfileDefault: (key: ProfileDefaultKey) => {
  6851. const params = new URLSearchParams({
  6852. brand: key.brand,
  6853. material: key.material,
  6854. subtype: key.subtype,
  6855. color_name: key.color_name,
  6856. });
  6857. return request<ResolvedProfileDefault | null>(`/inventory/profile-defaults/resolve?${params}`);
  6858. },
  6859. saveProfileDefault: (data: ProfileDefaultInput) =>
  6860. request<ProfileDefault>('/inventory/profile-defaults', {
  6861. method: 'PUT',
  6862. body: JSON.stringify(data),
  6863. }),
  6864. deleteProfileDefault: (defaultId: number) =>
  6865. request<{ status: string }>(`/inventory/profile-defaults/${defaultId}`, { method: 'DELETE' }),
  6866. /** Fills in what active spools of the default's product lack; the inventory mode picks the route. */
  6867. applyProfileDefault: (defaultId: number, spoolmanMode: boolean) =>
  6868. request<{ updated: number }>(
  6869. spoolmanMode
  6870. ? `/spoolman/inventory/profile-defaults/${defaultId}/apply`
  6871. : `/inventory/profile-defaults/${defaultId}/apply`,
  6872. { method: 'POST' },
  6873. ),
  6874. getAssignments: (printerId?: number) =>
  6875. request<SpoolAssignment[]>(`/inventory/assignments${printerId ? `?printer_id=${printerId}` : ''}`),
  6876. // move: the spool also leaves any other slot it is in, in the same
  6877. // transaction (#1574) -- for a scanned spool, the one in the user's hand.
  6878. assignSpool: (data: { spool_id: number; printer_id: number; ams_id: number; tray_id: number; move?: boolean }) =>
  6879. request<SpoolAssignment>('/inventory/assignments', {
  6880. method: 'POST',
  6881. body: JSON.stringify(data),
  6882. }),
  6883. unassignSpool: (printerId: number, amsId: number, trayId: number) =>
  6884. request<{ status: string }>(`/inventory/assignments/${printerId}/${amsId}/${trayId}`, { method: 'DELETE' }),
  6885. // ── Spool label printing (#809) ──────────────────────────────────────────
  6886. // The print endpoints return a PDF, a PNG, or a ZIP of PNGs (#2981); the
  6887. // preview endpoints one PNG. Callers get the Blob and decide what to do.
  6888. printSpoolLabels: (data: PrintSpoolLabelsRequest): Promise<Blob> =>
  6889. postForBlob('/inventory/labels', data),
  6890. printSpoolmanSpoolLabels: (data: PrintSpoolLabelsRequest): Promise<Blob> =>
  6891. postForBlob('/spoolman/labels', data),
  6892. previewSpoolLabel: (data: PreviewSpoolLabelRequest, signal?: AbortSignal): Promise<Blob> =>
  6893. postForBlob('/inventory/labels/preview', data, signal),
  6894. previewSpoolmanSpoolLabel: (data: PreviewSpoolLabelRequest, signal?: AbortSignal): Promise<Blob> =>
  6895. postForBlob('/spoolman/labels/preview', data, signal),
  6896. getLabelTemplates: () => request<SavedLabelTemplate[]>('/label-templates'),
  6897. createLabelTemplate: (data: { name: string; layout: LabelSheetLayout }) =>
  6898. request<SavedLabelTemplate>('/label-templates', { method: 'POST', body: JSON.stringify(data) }),
  6899. updateLabelTemplate: (id: number, data: { name: string; layout: LabelSheetLayout }) =>
  6900. request<SavedLabelTemplate>(`/label-templates/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  6901. deleteLabelTemplate: (id: number) => request<void>(`/label-templates/${id}`, { method: 'DELETE' }),
  6902. getSpoolCatalog: () =>
  6903. request<SpoolCatalogEntry[]>('/inventory/catalog'),
  6904. addCatalogEntry: (data: { name: string; weight: number }) =>
  6905. request<SpoolCatalogEntry>('/inventory/catalog', { method: 'POST', body: JSON.stringify(data) }),
  6906. updateCatalogEntry: (id: number, data: { name: string; weight: number }) =>
  6907. request<SpoolCatalogEntry>(`/inventory/catalog/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  6908. deleteCatalogEntry: (id: number) =>
  6909. request<{ status: string }>(`/inventory/catalog/${id}`, { method: 'DELETE' }),
  6910. bulkDeleteCatalogEntries: (ids: number[]) =>
  6911. request<{ deleted: number }>('/inventory/catalog/bulk-delete', { method: 'POST', body: JSON.stringify({ ids }) }),
  6912. resetSpoolCatalog: () =>
  6913. request<{ status: string }>('/inventory/catalog/reset', { method: 'POST' }),
  6914. // ── Suppliers (#2988) — inventory master data, Locations pattern ─────────
  6915. getSuppliers: () =>
  6916. request<Supplier[]>('/inventory/suppliers'),
  6917. createSupplier: (data: SupplierInput) =>
  6918. request<Supplier>('/inventory/suppliers', { method: 'POST', body: JSON.stringify(data) }),
  6919. updateSupplier: (id: number, data: Partial<SupplierInput>) =>
  6920. request<Supplier>(`/inventory/suppliers/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  6921. deleteSupplier: (id: number) =>
  6922. request<{ status: string }>(`/inventory/suppliers/${id}`, { method: 'DELETE' }),
  6923. setSpoolSuppliers: (spoolId: number, links: SpoolSupplierLinkInput[]) =>
  6924. request<SpoolSupplierLink[]>(`/inventory/spools/${spoolId}/suppliers`, {
  6925. method: 'PUT',
  6926. body: JSON.stringify(links),
  6927. }),
  6928. // Spoolman parity: the assignment rows live Bambuddy-side, keyed by the
  6929. // remote spool id — same request/response shape as the built-in inventory.
  6930. setSpoolmanSpoolSuppliers: (spoolmanSpoolId: number, links: SpoolSupplierLinkInput[]) =>
  6931. request<SpoolSupplierLink[]>(`/spoolman/inventory/spools/${spoolmanSpoolId}/suppliers`, {
  6932. method: 'PUT',
  6933. body: JSON.stringify(links),
  6934. }),
  6935. // date_from/date_to scope the usage half only, so the widget can follow the
  6936. // dashboard timeframe; stock stays point-in-time.
  6937. getSupplierStats: (dateFrom?: string, dateTo?: string) => {
  6938. const params = new URLSearchParams();
  6939. if (dateFrom) params.set('date_from', dateFrom);
  6940. if (dateTo) params.set('date_to', dateTo);
  6941. addDayZone(params);
  6942. const qs = params.toString();
  6943. return request<SupplierStats[]>(`/inventory/stats/suppliers${qs ? `?${qs}` : ''}`);
  6944. },
  6945. getLocations: () =>
  6946. request<StorageLocation[]>('/inventory/locations'),
  6947. createLocation: (data: { name: string; identifier?: string | null }) =>
  6948. request<StorageLocation>('/inventory/locations', { method: 'POST', body: JSON.stringify(data) }),
  6949. updateLocation: (id: number, data: { name?: string; identifier?: string | null }) =>
  6950. request<StorageLocation>(`/inventory/locations/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  6951. deleteLocation: (id: number) =>
  6952. request<{ status: string }>(`/inventory/locations/${id}`, { method: 'DELETE' }),
  6953. getColorCatalog: () =>
  6954. request<ColorCatalogEntry[]>('/inventory/colors'),
  6955. /** Flat hex→name map, plus the names collapsing it loses. ``by_material`` is
  6956. * keyed ``"<material>|<hex>"`` and only carries entries that differ from the
  6957. * flat answer (e.g. ``"pla matte|ffffff" -> "Ivory White"`` where the flat
  6958. * map says "Jade White"). #2875. */
  6959. getColorNameMap: () =>
  6960. request<{
  6961. colors: Record<string, string>;
  6962. by_material?: Record<string, string>;
  6963. bambu?: BambuCatalogColor[];
  6964. preset_materials?: Record<string, string>;
  6965. }>('/inventory/colors/map'),
  6966. addColorEntry: (data: {
  6967. manufacturer: string;
  6968. color_name: string;
  6969. hex_color: string;
  6970. material: string | null;
  6971. extra_colors?: string | null;
  6972. effect_type?: string | null;
  6973. }) =>
  6974. request<ColorCatalogEntry>('/inventory/colors', { method: 'POST', body: JSON.stringify(data) }),
  6975. updateColorEntry: (
  6976. id: number,
  6977. data: {
  6978. manufacturer: string;
  6979. color_name: string;
  6980. hex_color: string;
  6981. material: string | null;
  6982. extra_colors?: string | null;
  6983. effect_type?: string | null;
  6984. },
  6985. ) => request<ColorCatalogEntry>(`/inventory/colors/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  6986. deleteColorEntry: (id: number) =>
  6987. request<{ status: string }>(`/inventory/colors/${id}`, { method: 'DELETE' }),
  6988. bulkDeleteColorEntries: (ids: number[]) =>
  6989. request<{ deleted: number }>('/inventory/colors/bulk-delete', { method: 'POST', body: JSON.stringify({ ids }) }),
  6990. resetColorCatalog: () =>
  6991. request<{ status: string }>('/inventory/colors/reset', { method: 'POST' }),
  6992. searchColors: (manufacturer?: string, material?: string) =>
  6993. request<ColorCatalogEntry[]>(`/inventory/colors/search?${manufacturer ? `manufacturer=${encodeURIComponent(manufacturer)}` : ''}${manufacturer && material ? '&' : ''}${material ? `material=${encodeURIComponent(material)}` : ''}`),
  6994. linkTagToSpool: (spoolId: number, data: { tag_uid?: string; tray_uuid?: string; tag_type?: string; data_origin?: string }) =>
  6995. request<InventorySpool>(`/inventory/spools/${spoolId}/link-tag`, {
  6996. method: 'PATCH',
  6997. body: JSON.stringify(data),
  6998. }),
  6999. // Per-material-number inventory aggregate (#2870). The date range narrows
  7000. // the usage half only — stock is point-in-time.
  7001. getMaterialNumberStats: (options?: { dateFrom?: string; dateTo?: string }) => {
  7002. const params = new URLSearchParams();
  7003. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  7004. if (options?.dateTo) params.set('date_to', options.dateTo);
  7005. addDayZone(params);
  7006. const qs = params.toString();
  7007. return request<MaterialNumberStats[]>(`/inventory/stats/material-numbers${qs ? `?${qs}` : ''}`);
  7008. },
  7009. getSpoolUsageHistory: (spoolId: number, limit = 50) =>
  7010. request<SpoolUsageRecord[]>(`/inventory/spools/${spoolId}/usage?limit=${limit}`),
  7011. // One inventory's at a time: ``spoolman`` for the Spoolman spools' (#3407).
  7012. getAllUsageHistory: (limit = 100, printerId?: number, spoolman = false) =>
  7013. request<SpoolUsageRecord[]>(
  7014. `/inventory/usage?limit=${limit}${printerId ? `&printer_id=${printerId}` : ''}${spoolman ? '&spoolman=true' : ''}`,
  7015. ),
  7016. getSpoolmanSpoolUsageHistory: (spoolId: number, limit = 50) =>
  7017. request<SpoolUsageRecord[]>(`/spoolman/inventory/spools/${spoolId}/usage?limit=${limit}`),
  7018. clearSpoolmanSpoolUsageHistory: (spoolId: number) =>
  7019. request<{ status: string }>(`/spoolman/inventory/spools/${spoolId}/usage`, { method: 'DELETE' }),
  7020. clearSpoolUsageHistory: (spoolId: number) =>
  7021. request<{ status: string }>(`/inventory/spools/${spoolId}/usage`, { method: 'DELETE' }),
  7022. syncWeightsFromAms: () =>
  7023. request<{ synced: number; skipped: number; printing?: number }>('/inventory/sync-ams-weights', { method: 'POST' }),
  7024. getSkuSettings: () =>
  7025. request<FilamentSkuSettings[]>('/inventory/sku-settings'),
  7026. upsertSkuSettings: (data: Omit<FilamentSkuSettings, 'id'>) =>
  7027. request<FilamentSkuSettings>('/inventory/sku-settings', {
  7028. method: 'POST',
  7029. body: JSON.stringify(data),
  7030. }),
  7031. getShoppingList: () =>
  7032. request<ShoppingListItem[]>('/inventory/shopping-list'),
  7033. addToShoppingList: (data: ShoppingListItemCreate) =>
  7034. request<ShoppingListItem>('/inventory/shopping-list', {
  7035. method: 'POST',
  7036. body: JSON.stringify(data),
  7037. }),
  7038. removeFromShoppingList: (id: number) =>
  7039. request<{ status: string }>(`/inventory/shopping-list/${id}`, { method: 'DELETE' }),
  7040. clearShoppingList: () =>
  7041. request<{ deleted: number }>('/inventory/shopping-list', { method: 'DELETE' }),
  7042. updateShoppingListStatus: (id: number, status: 'pending' | 'purchased' | 'received') =>
  7043. request<ShoppingListItem>(`/inventory/shopping-list/${id}/status`, {
  7044. method: 'PATCH',
  7045. body: JSON.stringify({ status }),
  7046. }),
  7047. getFilamentPresets: () =>
  7048. request<SlicerSetting[]>('/cloud/filaments'),
  7049. // Spoolman Inventory proxy (unified UI when Spoolman is enabled)
  7050. getSpoolmanInventorySpools: (includeArchived = false) =>
  7051. request<InventorySpool[]>(`/spoolman/inventory/spools?include_archived=${includeArchived}`),
  7052. getSpoolmanInventorySpool: (id: number) =>
  7053. request<InventorySpool>(`/spoolman/inventory/spools/${id}`),
  7054. createSpoolmanInventorySpool: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>) =>
  7055. request<InventorySpool>('/spoolman/inventory/spools', {
  7056. method: 'POST',
  7057. body: JSON.stringify(data),
  7058. }),
  7059. bulkCreateSpoolmanInventorySpools: (
  7060. data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>,
  7061. quantity: number,
  7062. ) =>
  7063. request<SpoolmanBulkCreateResult | InventorySpool[]>('/spoolman/inventory/spools/bulk', {
  7064. method: 'POST',
  7065. body: JSON.stringify({ spool: data, quantity }),
  7066. }),
  7067. updateSpoolmanInventorySpool: (
  7068. id: number,
  7069. data: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>,
  7070. ) =>
  7071. request<InventorySpool>(`/spoolman/inventory/spools/${id}`, {
  7072. method: 'PATCH',
  7073. body: JSON.stringify(data),
  7074. }),
  7075. deleteSpoolmanInventorySpool: (id: number) =>
  7076. request<{ status: string }>(`/spoolman/inventory/spools/${id}`, { method: 'DELETE' }),
  7077. archiveSpoolmanInventorySpool: (id: number) =>
  7078. request<InventorySpool>(`/spoolman/inventory/spools/${id}/archive`, { method: 'POST' }),
  7079. restoreSpoolmanInventorySpool: (id: number) =>
  7080. request<InventorySpool>(`/spoolman/inventory/spools/${id}/restore`, { method: 'POST' }),
  7081. resetSpoolmanInventorySpoolConsumedCounter: (id: number) =>
  7082. request<InventorySpool>(`/spoolman/inventory/spools/${id}/reset-consumed-counter`, { method: 'POST' }),
  7083. bulkResetSpoolmanInventorySpoolConsumedCounter: (spoolIds: number[]) =>
  7084. request<{ reset: number; not_found?: number[]; errors?: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/reset-consumed-counter-bulk`, {
  7085. method: 'POST',
  7086. body: JSON.stringify({ spool_ids: spoolIds }),
  7087. }),
  7088. bulkUpdateSpoolmanInventorySpools: (ids: number[], update: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  7089. request<{ updated: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-update`, {
  7090. method: 'POST',
  7091. body: JSON.stringify({ ids, update }),
  7092. }),
  7093. bulkDeleteSpoolmanInventorySpools: (ids: number[]) =>
  7094. request<{ deleted: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-delete`, {
  7095. method: 'POST',
  7096. body: JSON.stringify({ ids }),
  7097. }),
  7098. bulkArchiveSpoolmanInventorySpools: (ids: number[]) =>
  7099. request<{ archived: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-archive`, {
  7100. method: 'POST',
  7101. body: JSON.stringify({ ids }),
  7102. }),
  7103. bulkRestoreSpoolmanInventorySpools: (ids: number[]) =>
  7104. request<{ restored: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-restore`, {
  7105. method: 'POST',
  7106. body: JSON.stringify({ ids }),
  7107. }),
  7108. linkTagToSpoolmanSpool: (spoolId: number, data: { tag_uid?: string; tray_uuid?: string }) =>
  7109. request<InventorySpool>(`/spoolman/inventory/spools/${spoolId}/tag`, {
  7110. method: 'PATCH',
  7111. body: JSON.stringify(data),
  7112. }),
  7113. syncSpoolmanSpoolWeight: (spoolId: number, weightGrams: number) =>
  7114. request<{ status: string; weight_used: number }>(`/spoolman/inventory/spools/${spoolId}/weight`, {
  7115. method: 'PATCH',
  7116. body: JSON.stringify({ weight_grams: weightGrams }),
  7117. }),
  7118. // move: as assignSpool's (#1574).
  7119. assignSpoolmanSlot: (data: { spoolman_spool_id: number; printer_id: number; ams_id: number; tray_id: number; move?: boolean }) =>
  7120. request<InventorySpool>('/spoolman/inventory/slot-assignments', {
  7121. method: 'POST',
  7122. body: JSON.stringify(data),
  7123. }),
  7124. unassignSpoolmanSlot: (spoolmanSpoolId: number) =>
  7125. request<InventorySpool>(`/spoolman/inventory/slot-assignments/${spoolmanSpoolId}`, { method: 'DELETE' }),
  7126. getSpoolmanSlotAssignments: (printerId?: number) =>
  7127. request<Array<{
  7128. printer_id: number;
  7129. printer_name: string | null;
  7130. ams_id: number;
  7131. tray_id: number;
  7132. spoolman_spool_id: number;
  7133. ams_label: string | null;
  7134. }>>(
  7135. printerId !== undefined
  7136. ? `/spoolman/inventory/slot-assignments/all?printer_id=${printerId}`
  7137. : '/spoolman/inventory/slot-assignments/all',
  7138. ),
  7139. syncSpoolmanAmsWeights: () =>
  7140. request<{ synced: number; skipped: number; printing?: number }>('/spoolman/inventory/sync-ams-weights', { method: 'POST' }),
  7141. saveSpoolmanKProfiles: (spoolId: number, profiles: SpoolKProfileInput[]) =>
  7142. request<SpoolKProfile[]>(`/spoolman/inventory/spools/${spoolId}/k-profiles`, {
  7143. method: 'PUT',
  7144. body: JSON.stringify(profiles),
  7145. }),
  7146. getSpoolmanFilamentPresets: (spoolId: number) =>
  7147. request<SpoolFilamentPreset[]>(`/spoolman/inventory/spools/${spoolId}/filament-presets`),
  7148. saveSpoolmanFilamentPresets: (spoolId: number, presets: SpoolFilamentPresetInput[]) =>
  7149. request<SpoolFilamentPreset[]>(`/spoolman/inventory/spools/${spoolId}/filament-presets`, {
  7150. method: 'PUT',
  7151. body: JSON.stringify(presets),
  7152. }),
  7153. // Updates
  7154. getVersion: () => request<VersionInfo>('/updates/version'),
  7155. checkForUpdates: () => request<UpdateCheckResult>('/updates/check'),
  7156. applyUpdate: () =>
  7157. request<{ success: boolean; message: string; status?: UpdateStatus; is_docker?: boolean; is_ha_addon?: boolean; is_windows_installer?: boolean }>('/updates/apply', {
  7158. method: 'POST',
  7159. }),
  7160. getUpdateStatus: () => request<UpdateStatus>('/updates/status'),
  7161. // Maintenance
  7162. getMaintenanceTypes: () => request<MaintenanceType[]>('/maintenance/types'),
  7163. createMaintenanceType: (data: MaintenanceTypeCreate) =>
  7164. request<MaintenanceType>('/maintenance/types', {
  7165. method: 'POST',
  7166. body: JSON.stringify(data),
  7167. }),
  7168. updateMaintenanceType: (id: number, data: Partial<MaintenanceTypeCreate>) =>
  7169. request<MaintenanceType>(`/maintenance/types/${id}`, {
  7170. method: 'PATCH',
  7171. body: JSON.stringify(data),
  7172. }),
  7173. deleteMaintenanceType: (id: number) =>
  7174. request<{ status: string }>(`/maintenance/types/${id}`, { method: 'DELETE' }),
  7175. restoreDefaultMaintenanceTypes: () =>
  7176. request<{ restored: number }>(`/maintenance/types/restore-defaults`, { method: 'POST' }),
  7177. getMaintenanceOverview: () => request<PrinterMaintenanceOverview[]>('/maintenance/overview'),
  7178. updateMaintenanceItem: (itemId: number, data: { custom_interval_hours?: number | null; custom_interval_type?: 'hours' | 'days' | null; enabled?: boolean }) =>
  7179. request<MaintenanceStatus>(`/maintenance/items/${itemId}`, {
  7180. method: 'PATCH',
  7181. body: JSON.stringify(data),
  7182. }),
  7183. performMaintenance: (itemId: number, notes?: string) =>
  7184. request<MaintenanceStatus>(`/maintenance/items/${itemId}/perform`, {
  7185. method: 'POST',
  7186. body: JSON.stringify({ notes }),
  7187. }),
  7188. setPrinterHours: (printerId: number, totalHours: number) =>
  7189. request<{ printer_id: number; total_hours: number; archive_hours: number; offset_hours: number }>(
  7190. `/maintenance/printers/${printerId}/hours?total_hours=${totalHours}`,
  7191. { method: 'PATCH' }
  7192. ),
  7193. assignMaintenanceType: (printerId: number, typeId: number) =>
  7194. request<MaintenanceStatus>(`/maintenance/printers/${printerId}/assign/${typeId}`, {
  7195. method: 'POST',
  7196. }),
  7197. removeMaintenanceItem: (itemId: number) =>
  7198. request<{ status: string }>(`/maintenance/items/${itemId}`, {
  7199. method: 'DELETE',
  7200. }),
  7201. // Camera
  7202. getCameraStreamToken: () =>
  7203. request<{ token: string }>('/printers/camera/stream-token', { method: 'POST' }),
  7204. // Media token (#3025) — the credential for thumbnails, plate previews,
  7205. // timelapses, cover images and link icons. Minted behind plain auth rather
  7206. // than camera:view, and identified, so those routes gate on the resource's
  7207. // own permission and ownership instead of on the camera.
  7208. getMediaToken: () => request<{ token: string }>('/auth/media-token', { method: 'POST' }),
  7209. // WebSocket auth (GHSA-r2qv follow-up) — mint a short-lived token for
  7210. // the /ws connection. Browsers can't attach Authorization headers to a
  7211. // WebSocket handshake, so the token rides in the ?token= query param.
  7212. getWebSocketToken: () =>
  7213. request<{ token: string }>('/auth/ws-token', { method: 'POST' }),
  7214. // Connected apps: sign-in to external applications with Bambuddy
  7215. listConnectedApps: () => request<ConnectedApp[]>('/connect/apps'),
  7216. createConnectedApp: (payload: { name: string; redirect_uri: string }) =>
  7217. request<ConnectedApp>('/connect/apps', { method: 'POST', body: JSON.stringify(payload) }),
  7218. updateConnectedApp: (id: number, payload: { name?: string; redirect_uri?: string; enabled?: boolean }) =>
  7219. request<ConnectedApp>(`/connect/apps/${id}`, { method: 'PATCH', body: JSON.stringify(payload) }),
  7220. rotateConnectedAppSecret: (id: number) =>
  7221. request<ConnectedApp>(`/connect/apps/${id}/rotate-secret`, { method: 'POST' }),
  7222. deleteConnectedApp: (id: number) => request<void>(`/connect/apps/${id}`, { method: 'DELETE' }),
  7223. getConnectAuthorizeInfo: (clientId: string, redirectUri: string) =>
  7224. request<ConnectAuthorizeInfo>(
  7225. `/connect/authorize/info?client_id=${encodeURIComponent(clientId)}&redirect_uri=${encodeURIComponent(redirectUri)}`,
  7226. ),
  7227. connectAuthorize: (payload: {
  7228. client_id: string;
  7229. redirect_uri: string;
  7230. code_challenge: string;
  7231. code_challenge_method: 'S256';
  7232. }) =>
  7233. request<{ code: string; redirect_uri: string }>('/connect/authorize', {
  7234. method: 'POST',
  7235. body: JSON.stringify(payload),
  7236. }),
  7237. // Long-lived camera tokens (#1108, #2531)
  7238. createLongLivedCameraToken: (payload: {
  7239. name: string;
  7240. expires_in_days: number;
  7241. scope?: LongLivedTokenScope;
  7242. }) =>
  7243. request<LongLivedCameraToken>('/auth/tokens', {
  7244. method: 'POST',
  7245. body: JSON.stringify({ scope: 'camera_stream', ...payload }),
  7246. }),
  7247. listMyLongLivedCameraTokens: () =>
  7248. request<LongLivedCameraToken[]>('/auth/tokens'),
  7249. listAllLongLivedCameraTokens: () =>
  7250. request<LongLivedCameraToken[]>('/auth/tokens/all'),
  7251. revokeLongLivedCameraToken: (tokenId: number) =>
  7252. request<void>(`/auth/tokens/${tokenId}`, { method: 'DELETE' }),
  7253. // Token-authenticated Cam Wall feed (#2531). `token` is omitted only when
  7254. // auth is disabled, where the backend gate is a no-op anyway.
  7255. getCamWallPrinters: (token?: string) =>
  7256. request<CamWallPrinter[]>(
  7257. token ? `/camwall/printers?token=${encodeURIComponent(token)}` : '/camwall/printers',
  7258. ),
  7259. // Token-authenticated streaming-overlay feed (#2613). OBS (or any embed with
  7260. // no login session) loads /overlay/{id}?token=... and this backs it. `token`
  7261. // is omitted only when auth is disabled, where the backend gate is a no-op.
  7262. getOverlayStatus: (printerId: number, token?: string) =>
  7263. request<OverlayStatus>(
  7264. token
  7265. ? `/printers/${printerId}/overlay-status?token=${encodeURIComponent(token)}`
  7266. : `/printers/${printerId}/overlay-status`,
  7267. ),
  7268. getCameraStatus: (printerId: number) =>
  7269. request<{ active: boolean; stalled: boolean }>(`/printers/${printerId}/camera/status`),
  7270. diagnoseCamera: (printerId: number) =>
  7271. request<CameraDiagnoseResult>(`/printers/${printerId}/camera/diagnose`, { method: 'POST' }),
  7272. diagnosePrinter: (printerId: number) =>
  7273. request<PrinterDiagnosticResult>(`/printers/${printerId}/diagnostic`),
  7274. diagnoseConnection: (body: {
  7275. ip_address: string;
  7276. serial_number?: string;
  7277. access_code?: string;
  7278. }) =>
  7279. request<PrinterDiagnosticResult>('/printers/diagnostic', {
  7280. method: 'POST',
  7281. body: JSON.stringify(body),
  7282. }),
  7283. // Plate Detection - Multi-reference calibration (stores up to 5 references per printer)
  7284. checkPlateEmpty: (printerId: number, options?: { useExternal?: boolean; includeDebugImage?: boolean }) => {
  7285. const params = new URLSearchParams();
  7286. // Only forward use_external when the caller explicitly sets it. Omitted →
  7287. // backend derives the default from the printer's external_camera_enabled
  7288. // setting so calibration and runtime checks use the same camera (#1359).
  7289. if (options?.useExternal !== undefined) {
  7290. params.set('use_external', String(options.useExternal));
  7291. }
  7292. params.set('include_debug_image', String(options?.includeDebugImage ?? false));
  7293. return request<PlateDetectionResult>(
  7294. `/printers/${printerId}/camera/check-plate?${params.toString()}`
  7295. );
  7296. },
  7297. calibratePlateDetection: (printerId: number, options?: { label?: string; useExternal?: boolean }) => {
  7298. const params = new URLSearchParams();
  7299. if (options?.label) params.set('label', options.label);
  7300. if (options?.useExternal !== undefined) {
  7301. params.set('use_external', String(options.useExternal));
  7302. }
  7303. return request<CalibrationResult & { index: number }>(
  7304. `/printers/${printerId}/camera/plate-detection/calibrate?${params.toString()}`,
  7305. { method: 'POST' }
  7306. );
  7307. },
  7308. getPlateReferences: (printerId: number) => {
  7309. return request<{
  7310. references: PlateReference[];
  7311. max_references: number;
  7312. }>(`/printers/${printerId}/camera/plate-detection/references`);
  7313. },
  7314. getPlateReferenceThumbnailUrl: (printerId: number, index: number) =>
  7315. withStreamToken(`${API_BASE}/printers/${printerId}/camera/plate-detection/references/${index}/thumbnail`),
  7316. updatePlateReferenceLabel: (printerId: number, index: number, label: string) => {
  7317. const params = new URLSearchParams();
  7318. params.set('label', label);
  7319. return request<{ success: boolean; index: number; label: string }>(
  7320. `/printers/${printerId}/camera/plate-detection/references/${index}?${params.toString()}`,
  7321. { method: 'PUT' }
  7322. );
  7323. },
  7324. deletePlateReference: (printerId: number, index: number) => {
  7325. return request<{ success: boolean; message: string }>(
  7326. `/printers/${printerId}/camera/plate-detection/references/${index}`,
  7327. { method: 'DELETE' }
  7328. );
  7329. },
  7330. // External Links
  7331. getExternalLinks: () => request<ExternalLink[]>('/external-links/'),
  7332. getExternalLink: (id: number) => request<ExternalLink>(`/external-links/${id}`),
  7333. createExternalLink: (data: ExternalLinkCreate) =>
  7334. request<ExternalLink>('/external-links/', {
  7335. method: 'POST',
  7336. body: JSON.stringify(data),
  7337. }),
  7338. updateExternalLink: (id: number, data: ExternalLinkUpdate) =>
  7339. request<ExternalLink>(`/external-links/${id}`, {
  7340. method: 'PATCH',
  7341. body: JSON.stringify(data),
  7342. }),
  7343. deleteExternalLink: (id: number) =>
  7344. request<{ message: string }>(`/external-links/${id}`, { method: 'DELETE' }),
  7345. uploadExternalLinkIcon: async (id: number, file: File): Promise<ExternalLink> => {
  7346. const formData = new FormData();
  7347. formData.append('file', file);
  7348. const headers: Record<string, string> = {};
  7349. if (authToken) {
  7350. headers['Authorization'] = `Bearer ${authToken}`;
  7351. }
  7352. const response = await fetch(`${API_BASE}/external-links/${id}/icon`, {
  7353. method: 'POST',
  7354. headers,
  7355. body: formData,
  7356. });
  7357. if (!response.ok) {
  7358. const error = await response.json().catch(() => ({}));
  7359. throw new Error(error.detail || `HTTP ${response.status}`);
  7360. }
  7361. return response.json();
  7362. },
  7363. deleteExternalLinkIcon: (id: number) =>
  7364. request<ExternalLink>(`/external-links/${id}/icon`, { method: 'DELETE' }),
  7365. getExternalLinkIconUrl: (id: number) => withMediaToken(`${API_BASE}/external-links/${id}/icon`),
  7366. // Projects
  7367. getProjects: (status?: string) => {
  7368. const params = new URLSearchParams();
  7369. if (status) params.set('status', status);
  7370. return request<ProjectListItem[]>(`/projects/?${params}`);
  7371. },
  7372. getProject: (id: number) => request<Project>(`/projects/${id}`),
  7373. createProject: (data: ProjectCreate) =>
  7374. request<Project>('/projects/', {
  7375. method: 'POST',
  7376. body: JSON.stringify(data),
  7377. }),
  7378. updateProject: (id: number, data: ProjectUpdate) =>
  7379. request<Project>(`/projects/${id}`, {
  7380. method: 'PATCH',
  7381. body: JSON.stringify(data),
  7382. }),
  7383. deleteProject: (id: number) =>
  7384. request<{ message: string }>(`/projects/${id}`, { method: 'DELETE' }),
  7385. getProjectArchives: (id: number, limit = 100, offset = 0) =>
  7386. request<Archive[]>(`/projects/${id}/archives?limit=${limit}&offset=${offset}`),
  7387. // Completed-run counts per library file (#1897); files with 0 runs are omitted
  7388. getProjectFileProgress: (id: number) =>
  7389. request<ProjectFileProgress[]>(`/projects/${id}/file-progress`),
  7390. addArchivesToProject: (projectId: number, archiveIds: number[]) =>
  7391. request<{ message: string; count: number }>(`/projects/${projectId}/add-archives`, {
  7392. method: 'POST',
  7393. body: JSON.stringify({ archive_ids: archiveIds }),
  7394. }),
  7395. // #1155: Cover image
  7396. // Browsers can't attach `Authorization: Bearer ...` to `<img src>`, so we
  7397. // append the stream-token query string the same way archive thumbnails do.
  7398. // `version` cache-busts the browser copy after a re-upload. It has to go on
  7399. // before the token does: callers used to append their own `?v=` to the
  7400. // returned URL, which already ended in `?token=…`, so the second `?` landed
  7401. // inside the token value and the image 401'd whenever auth was enabled.
  7402. getProjectCoverImageUrl: (projectId: number, version?: string | number) =>
  7403. withMediaToken(
  7404. `${API_BASE}/projects/${projectId}/cover-image${
  7405. version === undefined ? '' : `?v=${encodeURIComponent(String(version))}`
  7406. }`
  7407. ),
  7408. uploadProjectCoverImage: async (
  7409. projectId: number,
  7410. file: File
  7411. ): Promise<{ status: string; filename: string; size: number }> => {
  7412. const formData = new FormData();
  7413. formData.append('file', file);
  7414. const headers: Record<string, string> = {};
  7415. if (authToken) {
  7416. headers['Authorization'] = `Bearer ${authToken}`;
  7417. }
  7418. const response = await fetch(`${API_BASE}/projects/${projectId}/cover-image`, {
  7419. method: 'POST',
  7420. headers,
  7421. body: formData,
  7422. });
  7423. if (!response.ok) {
  7424. const error = await response.json().catch(() => ({}));
  7425. throw new Error(error.detail || `HTTP ${response.status}`);
  7426. }
  7427. return response.json();
  7428. },
  7429. deleteProjectCoverImage: (projectId: number) =>
  7430. request<{ status: string }>(`/projects/${projectId}/cover-image`, { method: 'DELETE' }),
  7431. // BOM (Bill of Materials)
  7432. getProjectBOM: (projectId: number) =>
  7433. request<BOMItem[]>(`/projects/${projectId}/bom`),
  7434. createBOMItem: (projectId: number, data: BOMItemCreate) =>
  7435. request<BOMItem>(`/projects/${projectId}/bom`, {
  7436. method: 'POST',
  7437. body: JSON.stringify(data),
  7438. }),
  7439. updateBOMItem: (projectId: number, itemId: number, data: BOMItemUpdate) =>
  7440. request<BOMItem>(`/projects/${projectId}/bom/${itemId}`, {
  7441. method: 'PATCH',
  7442. body: JSON.stringify(data),
  7443. }),
  7444. deleteBOMItem: (projectId: number, itemId: number) =>
  7445. request<{ status: string; message: string }>(`/projects/${projectId}/bom/${itemId}`, {
  7446. method: 'DELETE',
  7447. }),
  7448. // Templates
  7449. getTemplates: () => request<ProjectListItem[]>('/projects/templates/'),
  7450. createTemplateFromProject: (projectId: number) =>
  7451. request<Project>(`/projects/${projectId}/create-template`, { method: 'POST' }),
  7452. createProjectFromTemplate: (templateId: number, name?: string) =>
  7453. request<Project>(`/projects/from-template/${templateId}${name ? `?name=${encodeURIComponent(name)}` : ''}`, {
  7454. method: 'POST',
  7455. }),
  7456. // Timeline
  7457. getProjectTimeline: (projectId: number, limit = 50) =>
  7458. request<TimelineEvent[]>(`/projects/${projectId}/timeline?limit=${limit}`),
  7459. // Project Export/Import
  7460. exportProjectJson: (projectId: number) =>
  7461. request<ProjectExport>(`/projects/${projectId}/export?format=json`),
  7462. importProject: (data: ProjectImport) =>
  7463. request<Project>('/projects/import', {
  7464. method: 'POST',
  7465. body: JSON.stringify(data),
  7466. }),
  7467. importProjectFile: async (file: File): Promise<Project> => {
  7468. const formData = new FormData();
  7469. formData.append('file', file);
  7470. const headers: Record<string, string> = {};
  7471. if (authToken) {
  7472. headers['Authorization'] = `Bearer ${authToken}`;
  7473. }
  7474. const response = await fetch(`${API_BASE}/projects/import/file`, {
  7475. method: 'POST',
  7476. headers,
  7477. body: formData,
  7478. });
  7479. if (!response.ok) {
  7480. const error = await response.json().catch(() => ({}));
  7481. throw new Error(error.detail || `HTTP ${response.status}`);
  7482. }
  7483. return response.json();
  7484. },
  7485. exportProjectZip: async (projectId: number): Promise<{ blob: Blob; filename: string }> => {
  7486. const headers: Record<string, string> = {};
  7487. if (authToken) {
  7488. headers['Authorization'] = `Bearer ${authToken}`;
  7489. }
  7490. const response = await fetch(`${API_BASE}/projects/${projectId}/export`, {
  7491. headers,
  7492. });
  7493. if (!response.ok) {
  7494. const error = await response.json().catch(() => ({}));
  7495. throw new Error(error.detail || `HTTP ${response.status}`);
  7496. }
  7497. const contentDisposition = response.headers.get('Content-Disposition');
  7498. const filename = parseContentDispositionFilename(contentDisposition) || `project_${projectId}.zip`;
  7499. const blob = await response.blob();
  7500. return { blob, filename };
  7501. },
  7502. // API Keys
  7503. getAPIKeys: () => request<APIKey[]>('/api-keys/'),
  7504. createAPIKey: (data: APIKeyCreate) =>
  7505. request<APIKeyCreateResponse>('/api-keys/', {
  7506. method: 'POST',
  7507. body: JSON.stringify(data),
  7508. }),
  7509. deleteAPIKey: (id: number) =>
  7510. request<{ message: string }>(`/api-keys/${id}`, { method: 'DELETE' }),
  7511. // AMS History
  7512. getAMSHistory: (printerId: number, amsId: number, hours = 24) =>
  7513. request<AMSHistoryResponse>(`/ams-history/${printerId}/${amsId}?hours=${hours}`),
  7514. // Printer heater (nozzle / bed / chamber) sensor history
  7515. getPrinterSensorHistory: (printerId: number, hours = 24, kinds?: string[]) => {
  7516. const params = new URLSearchParams({ hours: String(hours) });
  7517. if (kinds && kinds.length > 0) params.set('kinds', kinds.join(','));
  7518. return request<PrinterSensorHistoryResponse>(`/printer-sensor-history/${printerId}?${params.toString()}`);
  7519. },
  7520. // System Info
  7521. getSystemInfo: () => request<SystemInfo>('/system/info'),
  7522. getSystemHealth: () => request<SystemHealthResult>('/system/health'),
  7523. getStorageUsage: (options?: { refresh?: boolean }) => {
  7524. const params = new URLSearchParams();
  7525. if (options?.refresh) {
  7526. params.set('refresh', 'true');
  7527. }
  7528. const query = params.toString();
  7529. return request<StorageUsageResponse>(`/system/storage-usage${query ? `?${query}` : ''}`);
  7530. },
  7531. // Library (File Manager)
  7532. getLibraryFolders: () => request<LibraryFolderTree[]>('/library/folders'),
  7533. createLibraryFolder: (data: LibraryFolderCreate) =>
  7534. request<LibraryFolder>('/library/folders', {
  7535. method: 'POST',
  7536. body: JSON.stringify(data),
  7537. }),
  7538. updateLibraryFolder: (id: number, data: LibraryFolderUpdate) =>
  7539. request<LibraryFolder>(`/library/folders/${id}`, {
  7540. method: 'PUT',
  7541. body: JSON.stringify(data),
  7542. }),
  7543. deleteLibraryFolder: (id: number) =>
  7544. request<{ status: string; message: string }>(`/library/folders/${id}`, { method: 'DELETE' }),
  7545. createExternalFolder: (data: ExternalFolderCreate) =>
  7546. request<LibraryFolder>('/library/folders/external', {
  7547. method: 'POST',
  7548. body: JSON.stringify(data),
  7549. }),
  7550. scanExternalFolder: (folderId: number) =>
  7551. request<{ status: string; added: number; removed: number }>(`/library/folders/${folderId}/scan`, {
  7552. method: 'POST',
  7553. }),
  7554. getLibraryFoldersByProject: (projectId: number) =>
  7555. request<LibraryFolder[]>(`/library/folders/by-project/${projectId}`),
  7556. getLibraryFoldersByArchive: (archiveId: number) => foldersByArchiveBatch(archiveId),
  7557. getLibraryFiles: (
  7558. folderId?: number | null,
  7559. includeRoot = true,
  7560. projectId?: number,
  7561. scope?: 'internal' | 'external',
  7562. recursive = false,
  7563. tagIds: number[] = [],
  7564. ) => {
  7565. const params = new URLSearchParams();
  7566. if (folderId !== undefined && folderId !== null) {
  7567. params.set('folder_id', String(folderId));
  7568. }
  7569. if (projectId !== undefined) {
  7570. params.set('project_id', String(projectId));
  7571. }
  7572. params.set('include_root', String(includeRoot));
  7573. if (scope === 'internal') params.set('internal_only', 'true');
  7574. else if (scope === 'external') params.set('external_only', 'true');
  7575. // recursive=true expands the folder_id filter to include every descendant
  7576. // folder (#1268). Only meaningful when folder_id is set; ignored server-side
  7577. // otherwise. Off by default so non-search callers keep folder-scoped behavior.
  7578. if (recursive) params.set('recursive', 'true');
  7579. // Tag filter (#1268). Repeated ?tag_ids=N&tag_ids=M form for AND semantics
  7580. // — backend joins the association table and HAVING COUNT(DISTINCT) matches
  7581. // the array length. Tag filter intentionally bypasses folder scoping
  7582. // server-side (cross-cutting design decision).
  7583. for (const tagId of tagIds) {
  7584. params.append('tag_ids', String(tagId));
  7585. }
  7586. return request<LibraryFileListItem[]>(`/library/files?${params}`);
  7587. },
  7588. getLibraryFolderReadme: (folderId: number) =>
  7589. request<{ filename: string; content: string; truncated: boolean }>(
  7590. `/library/folders/${folderId}/readme`,
  7591. ),
  7592. // ============ Library tag catalog (#1268) ============
  7593. getLibraryTags: () =>
  7594. request<LibraryTag[]>('/library/tags'),
  7595. createLibraryTag: (name: string) =>
  7596. request<LibraryTag>('/library/tags', {
  7597. method: 'POST',
  7598. body: JSON.stringify({ name }),
  7599. }),
  7600. updateLibraryTag: (id: number, name: string) =>
  7601. request<LibraryTag>(`/library/tags/${id}`, {
  7602. method: 'PATCH',
  7603. body: JSON.stringify({ name }),
  7604. }),
  7605. deleteLibraryTag: (id: number) =>
  7606. request<void>(`/library/tags/${id}`, { method: 'DELETE' }),
  7607. bulkAssignLibraryTags: (
  7608. fileIds: number[],
  7609. tagIds: number[],
  7610. action: 'add' | 'remove' | 'replace',
  7611. ) =>
  7612. request<LibraryTagBulkAssignResult>('/library/tags/bulk-assign', {
  7613. method: 'POST',
  7614. body: JSON.stringify({ file_ids: fileIds, tag_ids: tagIds, action }),
  7615. }),
  7616. // ============ Variant groups (#671 / #2570) ============
  7617. // "These files are the same job sliced for different printers." Consumed from
  7618. // both ends: the queue picks a printer and needs the matching file, the File
  7619. // Manager's print action has the printer and needs the same match.
  7620. createVariantGroup: (
  7621. members: { library_file_id: number; target_model?: string }[],
  7622. name?: string,
  7623. ) =>
  7624. request<VariantGroup>('/library/variant-groups', {
  7625. method: 'POST',
  7626. body: JSON.stringify({ members, ...(name ? { name } : {}) }),
  7627. }),
  7628. getVariantGroup: (groupId: number) =>
  7629. request<VariantGroup>(`/library/variant-groups/${groupId}`),
  7630. getLibraryFile: (id: number) => request<LibraryFile>(`/library/files/${id}`),
  7631. uploadLibraryFile: async (
  7632. file: File,
  7633. folderId?: number | null,
  7634. generateStlThumbnails: boolean = true
  7635. ): Promise<LibraryFileUploadResponse> => {
  7636. const formData = new FormData();
  7637. formData.append('file', file);
  7638. const params = new URLSearchParams();
  7639. if (folderId) params.set('folder_id', String(folderId));
  7640. params.set('generate_stl_thumbnails', String(generateStlThumbnails));
  7641. const headers: Record<string, string> = {};
  7642. if (authToken) {
  7643. headers['Authorization'] = `Bearer ${authToken}`;
  7644. }
  7645. const response = await fetch(`${API_BASE}/library/files?${params}`, {
  7646. method: 'POST',
  7647. headers,
  7648. body: formData,
  7649. });
  7650. if (!response.ok) {
  7651. const error = await response.json().catch(() => ({}));
  7652. throw new Error(error.detail || `HTTP ${response.status}`);
  7653. }
  7654. return response.json();
  7655. },
  7656. extractZipFile: async (
  7657. file: File,
  7658. folderId?: number | null,
  7659. preserveStructure: boolean = true,
  7660. createFolderFromZip: boolean = false,
  7661. generateStlThumbnails: boolean = true
  7662. ): Promise<ZipExtractResponse> => {
  7663. const formData = new FormData();
  7664. formData.append('file', file);
  7665. const params = new URLSearchParams();
  7666. if (folderId) params.set('folder_id', String(folderId));
  7667. params.set('preserve_structure', String(preserveStructure));
  7668. params.set('create_folder_from_zip', String(createFolderFromZip));
  7669. params.set('generate_stl_thumbnails', String(generateStlThumbnails));
  7670. const headers: Record<string, string> = {};
  7671. if (authToken) {
  7672. headers['Authorization'] = `Bearer ${authToken}`;
  7673. }
  7674. const response = await fetch(`${API_BASE}/library/files/extract-zip?${params}`, {
  7675. method: 'POST',
  7676. headers,
  7677. body: formData,
  7678. });
  7679. if (!response.ok) {
  7680. const error = await response.json().catch(() => ({}));
  7681. throw new Error(error.detail || `HTTP ${response.status}`);
  7682. }
  7683. return response.json();
  7684. },
  7685. updateLibraryFile: (id: number, data: LibraryFileUpdate) =>
  7686. request<LibraryFile>(`/library/files/${id}`, {
  7687. method: 'PUT',
  7688. body: JSON.stringify(data),
  7689. }),
  7690. deleteLibraryFile: (id: number) =>
  7691. request<{ status: string; message: string; trashed: boolean }>(`/library/files/${id}`, { method: 'DELETE' }),
  7692. // ========== Library Trash (#1008) ==========
  7693. previewLibraryPurge: (olderThanDays: number, includeNeverPrinted: boolean = true) =>
  7694. request<LibraryPurgePreview>(
  7695. `/library/purge/preview?older_than_days=${olderThanDays}&include_never_printed=${includeNeverPrinted}`,
  7696. ),
  7697. executeLibraryPurge: (olderThanDays: number, includeNeverPrinted: boolean = true) =>
  7698. request<{ moved_to_trash: number }>('/library/purge', {
  7699. method: 'POST',
  7700. body: JSON.stringify({ older_than_days: olderThanDays, include_never_printed: includeNeverPrinted }),
  7701. }),
  7702. listLibraryTrash: (limit: number = 100, offset: number = 0) =>
  7703. request<LibraryTrashListResponse>(`/library/trash?limit=${limit}&offset=${offset}`),
  7704. restoreLibraryTrash: (fileId: number) =>
  7705. request<{ status: string; id: number }>(`/library/trash/${fileId}/restore`, { method: 'POST' }),
  7706. hardDeleteLibraryTrash: (fileId: number) =>
  7707. request<{ status: string }>(`/library/trash/${fileId}`, { method: 'DELETE' }),
  7708. emptyLibraryTrash: () => request<{ deleted: number }>('/library/trash', { method: 'DELETE' }),
  7709. getLibraryTrashSettings: () =>
  7710. request<LibraryTrashSettings>('/library/trash/settings'),
  7711. updateLibraryTrashSettings: (body: LibraryTrashSettings) =>
  7712. request<LibraryTrashSettings>('/library/trash/settings', {
  7713. method: 'PUT',
  7714. body: JSON.stringify(body),
  7715. }),
  7716. getLibraryFileDownloadUrl: (id: number) => `${API_BASE}/library/files/${id}/download`,
  7717. createLibrarySlicerToken: (fileId: number) =>
  7718. request<{ token: string }>(`/library/files/${fileId}/slicer-token`, { method: 'POST' }),
  7719. getLibrarySlicerDownloadUrl: (fileId: number, token: string, filename: string) =>
  7720. `${API_BASE}/library/files/${fileId}/dl/${token}/${encodeURIComponent(buildSlicerUrlFilename(filename))}`,
  7721. downloadLibraryFile: async (id: number, filename?: string): Promise<void> => {
  7722. const headers: Record<string, string> = {};
  7723. if (authToken) {
  7724. headers['Authorization'] = `Bearer ${authToken}`;
  7725. }
  7726. const response = await fetch(`${API_BASE}/library/files/${id}/download`, { headers });
  7727. if (!response.ok) {
  7728. const error = await response.json().catch(() => ({}));
  7729. throw new Error(error.detail || `HTTP ${response.status}`);
  7730. }
  7731. const disposition = response.headers.get('Content-Disposition');
  7732. const downloadFilename = parseContentDispositionFilename(disposition) || filename || `file_${id}`;
  7733. const blob = await response.blob();
  7734. const url = window.URL.createObjectURL(blob);
  7735. const a = document.createElement('a');
  7736. a.href = url;
  7737. a.download = downloadFilename;
  7738. document.body.appendChild(a);
  7739. a.click();
  7740. document.body.removeChild(a);
  7741. window.URL.revokeObjectURL(url);
  7742. },
  7743. getLibraryFileThumbnailUrl: (id: number) => withMediaToken(`${API_BASE}/library/files/${id}/thumbnail`),
  7744. // Client-rendered preview thumbnail upload (#2976). STEP/PDF/spreadsheet
  7745. // previews render in the browser; the first render is posted back so the
  7746. // grid gets a thumbnail without a server-side renderer for those formats.
  7747. uploadLibraryPreviewThumbnail: async (fileId: number, thumbnail: Blob): Promise<{ updated: boolean }> => {
  7748. const formData = new FormData();
  7749. formData.append('thumbnail', thumbnail, 'preview.png');
  7750. const headers: Record<string, string> = {};
  7751. if (authToken) {
  7752. headers['Authorization'] = `Bearer ${authToken}`;
  7753. }
  7754. const response = await fetch(`${API_BASE}/library/files/${fileId}/preview-thumbnail`, {
  7755. method: 'POST',
  7756. headers,
  7757. body: formData,
  7758. });
  7759. if (!response.ok) {
  7760. const error = await response.json().catch(() => ({}));
  7761. throw new Error(error.detail || `HTTP ${response.status}`);
  7762. }
  7763. return response.json();
  7764. },
  7765. getLibraryFilePlateThumbnail: (id: number, plateIndex: number) =>
  7766. withMediaToken(`${API_BASE}/library/files/${id}/plate-thumbnail/${plateIndex}`),
  7767. // Photos of the printed result (#3077) — same shape as the archive photo API.
  7768. getLibraryFilePhotoUrl: (fileId: number, filename: string) =>
  7769. withMediaToken(`${API_BASE}/library/files/${fileId}/photos/${encodeURIComponent(filename)}`),
  7770. uploadLibraryFilePhoto: async (fileId: number, file: File): Promise<{ status: string; filename: string; photos: string[] }> => {
  7771. const formData = new FormData();
  7772. formData.append('file', file);
  7773. const headers: Record<string, string> = {};
  7774. if (authToken) {
  7775. headers['Authorization'] = `Bearer ${authToken}`;
  7776. }
  7777. const response = await fetch(`${API_BASE}/library/files/${fileId}/photos`, {
  7778. method: 'POST',
  7779. headers,
  7780. body: formData,
  7781. });
  7782. if (!response.ok) {
  7783. const error = await response.json().catch(() => ({}));
  7784. throw new Error(error.detail || `HTTP ${response.status}`);
  7785. }
  7786. return response.json();
  7787. },
  7788. deleteLibraryFilePhoto: (fileId: number, filename: string) =>
  7789. request<{ status: string; photos: string[] }>(`/library/files/${fileId}/photos/${encodeURIComponent(filename)}`, {
  7790. method: 'DELETE',
  7791. }),
  7792. getLibraryFileGcodeUrl: (id: number) => `${API_BASE}/library/files/${id}/gcode`,
  7793. moveLibraryFiles: (fileIds: number[], folderId: number | null) =>
  7794. request<{ status: string; moved: number }>('/library/files/move', {
  7795. method: 'POST',
  7796. body: JSON.stringify({ file_ids: fileIds, folder_id: folderId }),
  7797. }),
  7798. bulkDeleteLibrary: (fileIds: number[], folderIds: number[]) =>
  7799. request<{ deleted_files: number; deleted_folders: number }>('/library/bulk-delete', {
  7800. method: 'POST',
  7801. body: JSON.stringify({ file_ids: fileIds, folder_ids: folderIds }),
  7802. }),
  7803. getLibraryStats: () => request<LibraryStats>('/library/stats'),
  7804. batchGenerateStlThumbnails: (options: {
  7805. file_ids?: number[];
  7806. folder_id?: number;
  7807. all_missing?: boolean;
  7808. }) =>
  7809. request<BatchThumbnailResponse>('/library/generate-stl-thumbnails', {
  7810. method: 'POST',
  7811. body: JSON.stringify(options),
  7812. }),
  7813. combineLibraryFiles: (items: { file_id: number; copies: number }[], filename: string, folderId: number | null) =>
  7814. request<LibraryFileUploadResponse>('/library/files/combine', {
  7815. method: 'POST',
  7816. body: JSON.stringify({ items, filename, folder_id: folderId }),
  7817. }),
  7818. getLibraryFilePlates: (fileId: number) =>
  7819. request<LibraryFilePlatesResponse>(`/library/files/${fileId}/plates`),
  7820. getLibraryFileFilamentRequirements: (
  7821. fileId: number,
  7822. plateId?: number,
  7823. requestId?: string,
  7824. /** Ask for one entry per project slot instead of only the slots this
  7825. * plate consumes. The slice modal needs it: its filament list is
  7826. * positional, so a source whose only used slot is 4 must still present
  7827. * four rows or the user's pick is bound to slot 1 (#2712). Print-time
  7828. * AMS matching must NOT set this — it wants the used-only list. */
  7829. fullSlots?: boolean,
  7830. ) => {
  7831. const qs = new URLSearchParams();
  7832. if (plateId !== undefined) qs.set('plate_id', String(plateId));
  7833. if (requestId) qs.set('request_id', requestId);
  7834. if (fullSlots) qs.set('full_slots', 'true');
  7835. return request<{
  7836. file_id: number;
  7837. filename: string;
  7838. filaments: Array<{
  7839. slot_id: number;
  7840. type: string;
  7841. color: string;
  7842. used_grams: number;
  7843. used_meters: number;
  7844. used_in_plate?: boolean;
  7845. }>;
  7846. }>(`/library/files/${fileId}/filament-requirements${qs.toString() ? `?${qs}` : ''}`);
  7847. },
  7848. /** Poll the sidecar's per-request progress snapshot via the Bambuddy
  7849. * proxy. Used by the SliceModal's filament-discovery path so the inline
  7850. * spinner + persistent toast can show "Generating G-code (45%)" while
  7851. * the preview slice runs. Returns null on 404 (sidecar doesn't yet
  7852. * have an entry — early race window — or it expired) so the poller
  7853. * can keep trying. */
  7854. getPreviewSliceProgress: async (requestId: string): Promise<SliceJobProgress | null> => {
  7855. try {
  7856. return await request<SliceJobProgress>(`/slicer/preview-progress/${encodeURIComponent(requestId)}`);
  7857. } catch {
  7858. return null;
  7859. }
  7860. },
  7861. // GitHub Backup
  7862. getGitHubBackupConfig: () =>
  7863. request<GitHubBackupConfig | null>('/github-backup/config'),
  7864. getGitHubBackupCloudAccounts: () =>
  7865. request<CloudAccountCounts>('/github-backup/cloud-accounts'),
  7866. saveGitHubBackupConfig: (config: GitHubBackupConfigCreate) =>
  7867. request<GitHubBackupConfig>('/github-backup/config', {
  7868. method: 'POST',
  7869. body: JSON.stringify(config),
  7870. }),
  7871. updateGitHubBackupConfig: (config: Partial<GitHubBackupConfigCreate>) =>
  7872. request<GitHubBackupConfig>('/github-backup/config', {
  7873. method: 'PATCH',
  7874. body: JSON.stringify(config),
  7875. }),
  7876. testGitHubConnection: (repoUrl: string, token: string, provider: GitProviderType = 'github') =>
  7877. request<GitHubTestConnectionResponse>('/github-backup/test', {
  7878. method: 'POST',
  7879. body: JSON.stringify({ repo_url: repoUrl, token, provider }),
  7880. }),
  7881. testGitHubStoredConnection: () =>
  7882. request<GitHubTestConnectionResponse>('/github-backup/test-stored', { method: 'POST' }),
  7883. triggerGitHubBackup: () =>
  7884. request<GitHubBackupTriggerResponse>('/github-backup/run', { method: 'POST' }),
  7885. getGitHubBackupStatus: () =>
  7886. request<GitHubBackupStatus>('/github-backup/status'),
  7887. getGitHubBackupLogs: (limit: number = 50) =>
  7888. request<GitHubBackupLog[]>(`/github-backup/logs?limit=${limit}`),
  7889. clearGitHubBackupLogs: (keepLast: number = 10) =>
  7890. request<{ deleted: number; message: string }>(`/github-backup/logs?keep_last=${keepLast}`, { method: 'DELETE' }),
  7891. // Restore from a Git backup (#2656)
  7892. getGitHubBackupCommits: (limit: number = 20) =>
  7893. request<GitHubCommitListResponse>(`/github-backup/commits?limit=${limit}`),
  7894. getGitHubRestorePreview: (ref: string = 'HEAD') =>
  7895. request<GitHubRestorePreview>(`/github-backup/restore/preview?ref=${encodeURIComponent(ref)}`),
  7896. restoreFromGitHub: (payload: GitHubRestoreRequest) =>
  7897. request<GitHubRestoreResponse>('/github-backup/restore', {
  7898. method: 'POST',
  7899. body: JSON.stringify(payload),
  7900. }),
  7901. // Scheduled local backups
  7902. getLocalBackupStatus: () =>
  7903. request<LocalBackupStatus>('/local-backup/status'),
  7904. triggerLocalBackup: () =>
  7905. request<{ success: boolean; message: string; filename?: string }>('/local-backup/run', { method: 'POST' }),
  7906. checkLocalBackupPath: () =>
  7907. request<LocalBackupPathCheck>('/local-backup/path-check'),
  7908. getLocalBackups: () =>
  7909. request<LocalBackupFile[]>('/local-backup/backups'),
  7910. downloadLocalBackup: async (filename: string): Promise<{ blob: Blob; filename: string }> => {
  7911. const response = await fetch(`${API_BASE}/local-backup/backups/${encodeURIComponent(filename)}/download`, {
  7912. headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {},
  7913. });
  7914. if (!response.ok) throw new Error('Download failed');
  7915. const blob = await response.blob();
  7916. return { blob, filename };
  7917. },
  7918. restoreLocalBackup: (filename: string) =>
  7919. request<{ success: boolean; message: string }>(`/local-backup/backups/${encodeURIComponent(filename)}/restore`, { method: 'POST' }),
  7920. deleteLocalBackup: (filename: string) =>
  7921. request<{ success: boolean; message: string }>(`/local-backup/backups/${encodeURIComponent(filename)}`, { method: 'DELETE' }),
  7922. // Obico AI failure detection
  7923. getObicoStatus: () =>
  7924. request<ObicoStatus>('/obico/status'),
  7925. getObicoPrinterStatus: () =>
  7926. request<ObicoPrinterStatus>('/obico/printer-status'),
  7927. // `token` is sent as-is, so an empty string tests with no token at all.
  7928. // Omitting the argument makes the backend fall back to the saved token.
  7929. testObicoConnection: (url: string, token?: string) =>
  7930. request<ObicoTestConnection>('/obico/test-connection', {
  7931. method: 'POST',
  7932. body: JSON.stringify(token === undefined ? { url } : { url, token }),
  7933. }),
  7934. // OctoEverywhere AI failure detection
  7935. getOctoEverywhereStatus: () =>
  7936. request<OctoEverywhereStatus>('/octoeverywhere/status'),
  7937. getOctoEverywherePrinterStatus: () =>
  7938. request<OctoEverywherePrinterStatus>('/octoeverywhere/printer-status'),
  7939. // An omitted key uses the saved key; an explicit empty key is rejected.
  7940. testOctoEverywhereConnection: (apiKey?: string, confidence?: OctoEverywhereConfidence) =>
  7941. request<OctoEverywhereTestConnection>('/octoeverywhere/test-connection', {
  7942. method: 'POST',
  7943. body: JSON.stringify({ api_key: apiKey, confidence }),
  7944. }),
  7945. // Slicer API — slice in the background. Both endpoints return 202 + a
  7946. // job_id; poll /slice-jobs/{id} until status is `completed` or `failed`.
  7947. sliceLibraryFile: (fileId: number, body: SliceRequest) =>
  7948. request<SliceJobEnqueueResponse>(`/library/files/${fileId}/slice`, {
  7949. method: 'POST',
  7950. body: JSON.stringify(body),
  7951. }),
  7952. sliceArchive: (archiveId: number, body: SliceRequest) =>
  7953. request<SliceJobEnqueueResponse>(`/archives/${archiveId}/slice`, {
  7954. method: 'POST',
  7955. body: JSON.stringify(body),
  7956. }),
  7957. getSliceJob: (jobId: number) =>
  7958. request<SliceJobState>(`/slice-jobs/${jobId}`),
  7959. // Unified slicer-preset listing — cloud + local + standard, deduped by name.
  7960. // Used by the SliceModal; see UnifiedPresetsResponse for the shape and
  7961. // backend/app/api/routes/slicer_presets.py for the priority rules.
  7962. // `refresh` bypasses the in-process cloud and bundled-preset caches on the
  7963. // backend; the SliceModal's Refresh button passes true so a preset deleted
  7964. // in Bambu Studio or Bambu Handy shows up without the 5-min TTL wait.
  7965. getSlicerPresets: (options?: { refresh?: boolean }) =>
  7966. request<UnifiedPresetsResponse>(
  7967. options?.refresh ? '/slicer/presets?refresh=true' : '/slicer/presets',
  7968. ),
  7969. // Slicer Pipelines (#1425) — preset bundles the SliceModal can apply in
  7970. // one click. CRUD is gated on PIPELINES_READ / PIPELINES_WRITE.
  7971. listSlicerPipelines: () =>
  7972. request<SlicerPipelinesListResponse>('/slicer-pipelines/'),
  7973. createSlicerPipeline: (data: SlicerPipelineCreateRequest) =>
  7974. request<SlicerPipeline>('/slicer-pipelines/', {
  7975. method: 'POST',
  7976. body: JSON.stringify(data),
  7977. }),
  7978. updateSlicerPipeline: (id: number, data: SlicerPipelineUpdateRequest) =>
  7979. request<SlicerPipeline>(`/slicer-pipelines/${id}`, {
  7980. method: 'PUT',
  7981. body: JSON.stringify(data),
  7982. }),
  7983. deleteSlicerPipeline: (id: number) =>
  7984. request<void>(`/slicer-pipelines/${id}`, { method: 'DELETE' }),
  7985. checkPipelineEligibility: (
  7986. pipelineId: number,
  7987. source: { kind: 'libraryFile'; id: number } | { kind: 'archive'; id: number },
  7988. ) =>
  7989. request<PipelineEligibilityReport>(`/slicer-pipelines/${pipelineId}/check-eligibility`, {
  7990. method: 'POST',
  7991. body: JSON.stringify(
  7992. source.kind === 'libraryFile'
  7993. ? { source_library_file_id: source.id }
  7994. : { source_archive_id: source.id },
  7995. ),
  7996. }),
  7997. runPipeline: (
  7998. pipelineId: number,
  7999. source: { kind: 'libraryFile'; id: number } | { kind: 'archive'; id: number },
  8000. force = false,
  8001. copies = 1,
  8002. ) =>
  8003. request<PipelineRun>(`/slicer-pipelines/${pipelineId}/run`, {
  8004. method: 'POST',
  8005. body: JSON.stringify({
  8006. ...(source.kind === 'libraryFile'
  8007. ? { source_library_file_id: source.id }
  8008. : { source_archive_id: source.id }),
  8009. force,
  8010. copies,
  8011. }),
  8012. }),
  8013. listPipelineRuns: (pipelineId: number, limit = 5) =>
  8014. request<PipelineRunListResponse>(
  8015. `/slicer-pipelines/${pipelineId}/runs?limit=${limit}`,
  8016. ),
  8017. // Dashboard list across all pipelines (#1425 PR C).
  8018. listAllPipelineRuns: (params: {
  8019. limit?: number;
  8020. offset?: number;
  8021. pipelineId?: number;
  8022. status?: string;
  8023. targetPrinterId?: number;
  8024. targetModelClass?: string;
  8025. } = {}) => {
  8026. const search = new URLSearchParams();
  8027. if (params.limit) search.set('limit', String(params.limit));
  8028. if (params.offset) search.set('offset', String(params.offset));
  8029. if (params.pipelineId) search.set('pipeline_id', String(params.pipelineId));
  8030. if (params.status) search.set('status', params.status);
  8031. if (params.targetPrinterId) search.set('target_printer_id', String(params.targetPrinterId));
  8032. if (params.targetModelClass) search.set('target_model_class', params.targetModelClass);
  8033. const q = search.toString();
  8034. return request<PipelineRunListResponse>(
  8035. `/pipeline-runs${q ? '?' + q : ''}`,
  8036. );
  8037. },
  8038. // Clear terminal pipeline runs (#1425 PR C polish). Deletes all runs in
  8039. // a terminal state (completed/failed/cancelled/partial_failure); in-flight
  8040. // runs are preserved.
  8041. clearTerminalPipelineRuns: () =>
  8042. request<{ deleted: number }>('/pipeline-runs/clear', { method: 'POST' }),
  8043. cancelPipelineRun: (runId: number) =>
  8044. request<PipelineRun>(`/pipeline-runs/${runId}/cancel`, { method: 'POST' }),
  8045. retryFailedPipelineRun: (runId: number) =>
  8046. request<PipelineRun>(`/pipeline-runs/${runId}/retry-failed`, { method: 'POST' }),
  8047. // Canonical Bambu printer-model registry — "Bambu Lab <model>" → short code.
  8048. // Single source of truth shared with backend (PRINTER_MODEL_MAP); the
  8049. // SliceModal uses this to classify cloud / standard presets by their
  8050. // `@BBL <code>` suffix against the selected printer-preset name (#1325).
  8051. getSlicerPrinterModels: () =>
  8052. request<Record<string, string>>('/slicer/printer-models'),
  8053. getSlicerLoadedSpools: () =>
  8054. request<LoadedSpoolsResponse>('/slicer/loaded-spools'),
  8055. /**
  8056. * Effective values of a process preset, with its `inherits:` chain flattened
  8057. * by the slicer sidecar. Powers the slice modal's settings panel, which would
  8058. * otherwise show the option schema's compiled-in defaults (a preset setting a
  8059. * 0.42mm line width appears as the C++ default of 0).
  8060. *
  8061. * `resolved: false` means the values could not be obtained -- sidecar offline,
  8062. * too old for the endpoint, or slicing not configured -- and the caller should
  8063. * fall back to schema defaults rather than treat it as a failure.
  8064. */
  8065. getSlicerPresetValues: (ref: PresetRef) =>
  8066. request<SlicerPresetValues>(
  8067. `/slicer/preset-values?source=${encodeURIComponent(ref.source)}&id=${encodeURIComponent(ref.id)}`,
  8068. ),
  8069. // Local Presets (OrcaSlicer imports)
  8070. getLocalPresets: () =>
  8071. request<LocalPresetsResponse>('/local-presets/'),
  8072. importLocalPresets: (formData: FormData) =>
  8073. fetch(`${API_BASE}/local-presets/import`, {
  8074. method: 'POST',
  8075. headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {},
  8076. body: formData,
  8077. }).then(async (res) => {
  8078. if (!res.ok) {
  8079. const err = await res.json().catch(() => ({}));
  8080. throw new Error(err.detail || `HTTP ${res.status}`);
  8081. }
  8082. return res.json() as Promise<ImportResponse>;
  8083. }),
  8084. deleteLocalPreset: (id: number) =>
  8085. request<{ success: boolean }>(`/local-presets/${id}`, { method: 'DELETE' }),
  8086. };
  8087. // AMS History types
  8088. export interface AMSHistoryPoint {
  8089. recorded_at: string;
  8090. humidity: number | null;
  8091. humidity_raw: number | null;
  8092. temperature: number | null;
  8093. }
  8094. export interface AMSHistoryResponse {
  8095. printer_id: number;
  8096. ams_id: number;
  8097. data: AMSHistoryPoint[];
  8098. min_humidity: number | null;
  8099. max_humidity: number | null;
  8100. avg_humidity: number | null;
  8101. min_temperature: number | null;
  8102. max_temperature: number | null;
  8103. avg_temperature: number | null;
  8104. }
  8105. export type HeaterSensorKind = 'nozzle' | 'nozzle_2' | 'bed' | 'chamber';
  8106. export interface HeaterHistoryPoint {
  8107. recorded_at: string;
  8108. value: number | null;
  8109. target: number | null;
  8110. }
  8111. export interface HeaterSeries {
  8112. sensor_kind: HeaterSensorKind;
  8113. data: HeaterHistoryPoint[];
  8114. min_value: number | null;
  8115. max_value: number | null;
  8116. avg_value: number | null;
  8117. }
  8118. export interface PrinterSensorHistoryResponse {
  8119. printer_id: number;
  8120. series: HeaterSeries[];
  8121. }
  8122. // System Info types
  8123. export interface SystemInfo {
  8124. app: {
  8125. version: string;
  8126. base_dir: string;
  8127. archive_dir: string;
  8128. };
  8129. database: {
  8130. engine: string;
  8131. version: string;
  8132. archives: number;
  8133. archives_completed: number;
  8134. archives_failed: number;
  8135. archives_printing: number;
  8136. printers: number;
  8137. filaments: number;
  8138. projects: number;
  8139. smart_plugs: number;
  8140. total_print_time_seconds: number;
  8141. total_print_time_formatted: string;
  8142. total_filament_grams: number;
  8143. total_filament_kg: number;
  8144. };
  8145. printers: {
  8146. total: number;
  8147. connected: number;
  8148. connected_list: Array<{
  8149. id: number;
  8150. name: string;
  8151. state: string;
  8152. model: string;
  8153. }>;
  8154. };
  8155. storage: {
  8156. archive_size_bytes: number;
  8157. archive_size_formatted: string;
  8158. database_size_bytes: number;
  8159. database_size_formatted: string;
  8160. disk_total_bytes: number;
  8161. disk_total_formatted: string;
  8162. disk_used_bytes: number;
  8163. disk_used_formatted: string;
  8164. disk_free_bytes: number;
  8165. disk_free_formatted: string;
  8166. disk_percent_used: number;
  8167. };
  8168. system: {
  8169. platform: string;
  8170. platform_release: string;
  8171. platform_version: string;
  8172. architecture: string;
  8173. hostname: string;
  8174. python_version: string;
  8175. uptime_seconds: number;
  8176. uptime_formatted: string;
  8177. boot_time: string;
  8178. };
  8179. memory: {
  8180. total_bytes: number;
  8181. total_formatted: string;
  8182. available_bytes: number;
  8183. available_formatted: string;
  8184. used_bytes: number;
  8185. used_formatted: string;
  8186. percent_used: number;
  8187. };
  8188. cpu: {
  8189. count: number;
  8190. count_logical: number;
  8191. percent: number;
  8192. };
  8193. }
  8194. export interface StorageUsageCategory {
  8195. key: string;
  8196. label: string;
  8197. bytes: number;
  8198. formatted: string;
  8199. percent_of_total: number;
  8200. }
  8201. export interface StorageUsageOtherItem {
  8202. bucket: string;
  8203. label: string;
  8204. kind: 'system' | 'data';
  8205. deletable: boolean;
  8206. bytes: number;
  8207. formatted: string;
  8208. percent_of_total: number;
  8209. }
  8210. export interface StorageUsageResponse {
  8211. roots: string[];
  8212. total_bytes: number;
  8213. total_formatted: string;
  8214. categories: StorageUsageCategory[];
  8215. other_breakdown: StorageUsageOtherItem[];
  8216. scan_errors: number;
  8217. generated_at: string;
  8218. cache: {
  8219. hit: boolean;
  8220. age_seconds: number;
  8221. max_age_seconds: number;
  8222. };
  8223. }
  8224. // Library (File Manager) types
  8225. export interface LibraryFolderTree {
  8226. id: number;
  8227. name: string;
  8228. parent_id: number | null;
  8229. project_id: number | null;
  8230. archive_id: number | null;
  8231. project_name: string | null;
  8232. archive_name: string | null;
  8233. is_external: boolean;
  8234. external_path: string | null;
  8235. external_readonly: boolean;
  8236. file_count: number;
  8237. // max(folder.updated_at, max(immediate-child file.updated_at)). Used by
  8238. // the File Manager folder tree's "sort by recent activity" mode (#1770).
  8239. latest_activity_at: string | null;
  8240. // Ownership (#3201). can_* are for the current user: what the File
  8241. // Manager may offer on this folder. The backend enforces the same rules.
  8242. created_by_id: number | null;
  8243. shared: boolean;
  8244. can_write: boolean;
  8245. can_rename: boolean;
  8246. can_delete: boolean;
  8247. children: LibraryFolderTree[];
  8248. }
  8249. export interface LibraryFolder {
  8250. id: number;
  8251. name: string;
  8252. parent_id: number | null;
  8253. project_id: number | null;
  8254. archive_id: number | null;
  8255. project_name: string | null;
  8256. archive_name: string | null;
  8257. is_external: boolean;
  8258. external_path: string | null;
  8259. external_readonly: boolean;
  8260. external_show_hidden: boolean;
  8261. file_count: number;
  8262. latest_activity_at: string | null;
  8263. // Ownership (#3201). can_* are for the current user: what the File
  8264. // Manager may offer on this folder. The backend enforces the same rules.
  8265. created_by_id: number | null;
  8266. shared: boolean;
  8267. can_write: boolean;
  8268. can_rename: boolean;
  8269. can_delete: boolean;
  8270. created_at: string;
  8271. updated_at: string;
  8272. }
  8273. export interface LibraryFolderCreate {
  8274. name: string;
  8275. parent_id?: number | null;
  8276. project_id?: number | null;
  8277. archive_id?: number | null;
  8278. }
  8279. export interface ExternalFolderCreate {
  8280. name: string;
  8281. external_path: string;
  8282. readonly?: boolean;
  8283. show_hidden?: boolean;
  8284. parent_id?: number | null;
  8285. }
  8286. export interface LibraryFolderUpdate {
  8287. name?: string;
  8288. parent_id?: number | null;
  8289. project_id?: number | null; // 0 to unlink
  8290. archive_id?: number | null; // 0 to unlink
  8291. shared?: boolean; // library:update_all only (#3201)
  8292. }
  8293. export interface LibraryFileDuplicate {
  8294. id: number;
  8295. filename: string;
  8296. folder_id: number | null;
  8297. folder_name: string | null;
  8298. created_at: string;
  8299. }
  8300. export interface LibraryFile {
  8301. id: number;
  8302. folder_id: number | null;
  8303. folder_name: string | null;
  8304. project_id: number | null;
  8305. project_name: string | null;
  8306. is_external: boolean;
  8307. filename: string;
  8308. file_path: string;
  8309. file_type: string;
  8310. file_size: number;
  8311. file_hash: string | null;
  8312. thumbnail_path: string | null;
  8313. metadata: Record<string, unknown> | null;
  8314. print_count: number;
  8315. last_printed_at: string | null;
  8316. notes: string | null;
  8317. // User link + photos of the printed result (#3077); source_url is the
  8318. // read-only import provenance (MakerWorld).
  8319. external_url: string | null;
  8320. photos: string[];
  8321. source_url: string | null;
  8322. duplicates: LibraryFileDuplicate[] | null;
  8323. duplicate_count: number;
  8324. // User tracking (Issue #206)
  8325. created_by_id: number | null;
  8326. created_by_username: string | null;
  8327. created_at: string;
  8328. updated_at: string;
  8329. // Metadata fields
  8330. print_name: string | null;
  8331. print_time_seconds: number | null;
  8332. filament_used_grams: number | null;
  8333. sliced_for_model: string | null;
  8334. }
  8335. export interface LibraryTagSummary {
  8336. id: number;
  8337. name: string;
  8338. }
  8339. export interface LibraryFileListItem {
  8340. id: number;
  8341. folder_id: number | null;
  8342. is_external: boolean;
  8343. filename: string;
  8344. file_type: string;
  8345. file_size: number;
  8346. thumbnail_path: string | null;
  8347. print_count: number;
  8348. duplicate_count: number;
  8349. // User tracking (Issue #206)
  8350. created_by_id: number | null;
  8351. created_by_username: string | null;
  8352. created_at: string;
  8353. // Real on-disk modification time (#2680). Null for managed uploads; the date
  8354. // sort and "Modified" column use `fs_modified_at ?? created_at`.
  8355. fs_modified_at: string | null;
  8356. print_name: string | null;
  8357. print_time_seconds: number | null;
  8358. filament_used_grams: number | null;
  8359. sliced_for_model: string | null;
  8360. // Tags assigned to this file (#1268). The backend always emits an empty
  8361. // array when a file has no tags, but the field is typed optional so any
  8362. // legacy code path (or mock) that constructs a LibraryFileListItem without
  8363. // it doesn't crash the renderer. Read sites use `file.tags ?? []`.
  8364. tags?: LibraryTagSummary[];
  8365. // Variant grouping (#671 / #2570). `variant_count` is the size of the whole
  8366. // group, which may include files in other folders — never the number of
  8367. // matching rows on screen. 0 when the file is not grouped.
  8368. variant_group_id?: number | null;
  8369. variant_count?: number;
  8370. // Metadata indicators (#3077). Optional for the same reason as `tags`: older
  8371. // mocks construct list items without them. Read sites default to falsy.
  8372. external_url?: string | null;
  8373. has_notes?: boolean;
  8374. photo_count?: number;
  8375. }
  8376. // Variant groups (#671 / #2570): the same job sliced for different printers.
  8377. export interface VariantGroupMember {
  8378. library_file_id: number;
  8379. filename: string;
  8380. target_model: string;
  8381. position: number;
  8382. }
  8383. export interface VariantGroup {
  8384. id: number;
  8385. name: string;
  8386. /** In priority order — index 0 wins when several printers are free at once. */
  8387. members: VariantGroupMember[];
  8388. }
  8389. // Library tag catalog (#1268)
  8390. export interface LibraryTag {
  8391. id: number;
  8392. name: string;
  8393. file_count: number;
  8394. created_at: string;
  8395. updated_at: string;
  8396. }
  8397. export interface LibraryTagBulkAssignResult {
  8398. files_updated: number;
  8399. associations_added: number;
  8400. associations_removed: number;
  8401. }
  8402. export interface LibraryFileUpdate {
  8403. filename?: string;
  8404. folder_id?: number | null;
  8405. project_id?: number | null;
  8406. notes?: string | null;
  8407. external_url?: string | null;
  8408. }
  8409. // Library trash (#1008)
  8410. export interface LibraryTrashItem {
  8411. id: number;
  8412. filename: string;
  8413. file_size: number;
  8414. thumbnail_path: string | null;
  8415. folder_id: number | null;
  8416. folder_name: string | null;
  8417. created_by_id: number | null;
  8418. created_by_username: string | null;
  8419. deleted_at: string;
  8420. auto_purge_at: string;
  8421. }
  8422. export interface LibraryTrashListResponse {
  8423. items: LibraryTrashItem[];
  8424. total: number;
  8425. retention_days: number;
  8426. }
  8427. export interface LibraryPurgePreview {
  8428. count: number;
  8429. total_bytes: number;
  8430. sample_filenames: string[];
  8431. older_than_days: number;
  8432. include_never_printed: boolean;
  8433. }
  8434. export interface LibraryTrashSettings {
  8435. retention_days: number;
  8436. auto_purge_enabled: boolean;
  8437. auto_purge_days: number;
  8438. auto_purge_include_never_printed: boolean;
  8439. }
  8440. export interface ArchivePurgePreview {
  8441. count: number;
  8442. total_bytes: number;
  8443. sample_filenames: string[];
  8444. older_than_days: number;
  8445. }
  8446. export interface ArchiveMergeMember {
  8447. id: number;
  8448. print_name: string | null;
  8449. filename: string;
  8450. created_at: string | null;
  8451. run_count: number;
  8452. }
  8453. /** Why a group is left out: at work now, or holding files only one can keep. */
  8454. export type ArchiveMergeSkip = 'busy' | 'conflicting_files' | 'failed' | 'not_a_group';
  8455. export interface ArchiveMergeGroup {
  8456. survivor: ArchiveMergeMember;
  8457. merged: ArchiveMergeMember[];
  8458. skipped: ArchiveMergeSkip | null;
  8459. }
  8460. export interface ArchiveMergePreview {
  8461. groups: ArchiveMergeGroup[];
  8462. }
  8463. export interface ArchiveMergeResult {
  8464. merged: { survivor_id: number; merged_ids: number[] }[];
  8465. skipped: { survivor_id: number; reason: ArchiveMergeSkip }[];
  8466. }
  8467. export interface ArchivePurgeSettings {
  8468. enabled: boolean;
  8469. days: number;
  8470. // #1390: when true, bulk-deletes the linked PrintLogEntry rows so the
  8471. // contribution drops from Quick Stats too. Default false — soft-delete,
  8472. // Quick Stats preserved.
  8473. purge_stats: boolean;
  8474. }
  8475. export interface LibraryFileUploadResponse {
  8476. id: number;
  8477. filename: string;
  8478. file_type: string;
  8479. file_size: number;
  8480. thumbnail_path: string | null;
  8481. duplicate_of: number | null;
  8482. metadata: Record<string, unknown> | null;
  8483. }
  8484. export interface LibraryStats {
  8485. total_files: number;
  8486. total_folders: number;
  8487. total_size_bytes: number;
  8488. files_by_type: Record<string, number>;
  8489. total_prints: number;
  8490. disk_free_bytes: number;
  8491. disk_total_bytes: number;
  8492. disk_used_bytes: number;
  8493. }
  8494. export interface ZipExtractResult {
  8495. filename: string;
  8496. file_id: number;
  8497. folder_id: number | null;
  8498. }
  8499. export interface ZipExtractError {
  8500. filename: string;
  8501. error: string;
  8502. }
  8503. export interface ZipExtractResponse {
  8504. extracted: number;
  8505. folders_created: number;
  8506. files: ZipExtractResult[];
  8507. errors: ZipExtractError[];
  8508. }
  8509. // STL Thumbnail Generation types
  8510. export interface BatchThumbnailResult {
  8511. file_id: number;
  8512. filename: string;
  8513. success: boolean;
  8514. error?: string | null;
  8515. }
  8516. export interface BatchThumbnailResponse {
  8517. processed: number;
  8518. succeeded: number;
  8519. failed: number;
  8520. results: BatchThumbnailResult[];
  8521. }
  8522. // Discovery types
  8523. export interface DiscoveredPrinter {
  8524. serial: string;
  8525. name: string;
  8526. ip_address: string;
  8527. model: string | null;
  8528. discovered_at: string | null;
  8529. }
  8530. export interface DiscoveryStatus {
  8531. running: boolean;
  8532. }
  8533. export interface DiscoveryInfo {
  8534. is_docker: boolean;
  8535. ssdp_running: boolean;
  8536. scan_running: boolean;
  8537. subnets: string[];
  8538. }
  8539. export interface SubnetScanStatus {
  8540. running: boolean;
  8541. scanned: number;
  8542. total: number;
  8543. }
  8544. // Discovery API
  8545. export const discoveryApi = {
  8546. getInfo: () => request<DiscoveryInfo>('/discovery/info'),
  8547. startDiscovery: (duration: number = 10) =>
  8548. request<DiscoveryStatus>(`/discovery/start?duration=${duration}`, { method: 'POST' }),
  8549. stopDiscovery: () =>
  8550. request<DiscoveryStatus>('/discovery/stop', { method: 'POST' }),
  8551. getDiscoveredPrinters: () =>
  8552. request<DiscoveredPrinter[]>('/discovery/printers'),
  8553. // Subnet scanning (for Docker environments)
  8554. startSubnetScan: (subnet: string, timeout: number = 1.0) =>
  8555. request<SubnetScanStatus>('/discovery/scan', {
  8556. method: 'POST',
  8557. body: JSON.stringify({ subnet, timeout }),
  8558. }),
  8559. getScanStatus: () => request<SubnetScanStatus>('/discovery/scan/status'),
  8560. stopSubnetScan: () =>
  8561. request<SubnetScanStatus>('/discovery/scan/stop', { method: 'POST' }),
  8562. };
  8563. // Virtual Printer types
  8564. // Canonical wire values: `archive`, `review`, `queue`, `proxy`. The legacy
  8565. // `immediate` (→ archive) and `print_queue` (→ queue) names are still
  8566. // accepted by the backend so older API clients keep working, but new code
  8567. // should send the canonical names.
  8568. export type VirtualPrinterMode = 'archive' | 'review' | 'queue' | 'proxy' | 'immediate' | 'print_queue';
  8569. export interface VirtualPrinterProxyStatus {
  8570. running: boolean;
  8571. target_host: string;
  8572. ftp_port: number;
  8573. mqtt_port: number;
  8574. ftp_connections: number;
  8575. mqtt_connections: number;
  8576. }
  8577. export interface VirtualPrinterStatus {
  8578. enabled: boolean;
  8579. running: boolean;
  8580. mode: VirtualPrinterMode;
  8581. name: string;
  8582. serial: string;
  8583. model: string;
  8584. model_name: string;
  8585. pending_files: number;
  8586. target_printer_ip?: string; // For proxy mode
  8587. proxy?: VirtualPrinterProxyStatus; // For proxy mode
  8588. }
  8589. export interface VirtualPrinterSettings {
  8590. tailscale_disabled: boolean;
  8591. archive_name_source: 'metadata' | 'filename'; // Source for archive's display name
  8592. status: VirtualPrinterStatus;
  8593. }
  8594. export interface NetworkInterface {
  8595. name: string;
  8596. ip: string;
  8597. netmask: string;
  8598. subnet: string;
  8599. is_alias?: boolean;
  8600. label?: string;
  8601. }
  8602. export interface PendingUpload {
  8603. id: number;
  8604. filename: string;
  8605. // Resolved name the review card should show — mirrors what archive_print
  8606. // will eventually write to PrintArchive.print_name (#1152 follow-up). Falls
  8607. // back to the stripped filename stem when the 3MF has no embedded title or
  8608. // the operator has chosen the "filename" archive-name source.
  8609. display_name: string;
  8610. file_size: number;
  8611. source_ip: string | null;
  8612. status: string;
  8613. tags: string | null;
  8614. notes: string | null;
  8615. project_id: number | null;
  8616. uploaded_at: string;
  8617. }
  8618. // Virtual Printer API
  8619. export const virtualPrinterApi = {
  8620. getSettings: () => request<VirtualPrinterSettings>('/settings/virtual-printer'),
  8621. updateSettings: (data: {
  8622. tailscale_disabled?: boolean;
  8623. archive_name_source?: 'metadata' | 'filename';
  8624. }) => {
  8625. const params = new URLSearchParams();
  8626. if (data.tailscale_disabled !== undefined) params.set('tailscale_disabled', String(data.tailscale_disabled));
  8627. if (data.archive_name_source !== undefined) params.set('archive_name_source', data.archive_name_source);
  8628. return request<VirtualPrinterSettings>(`/settings/virtual-printer?${params.toString()}`, {
  8629. method: 'PUT',
  8630. });
  8631. },
  8632. };
  8633. // Multi Virtual Printer API
  8634. export interface VirtualPrinterConfig {
  8635. id: number;
  8636. name: string;
  8637. enabled: boolean;
  8638. mode: VirtualPrinterMode;
  8639. model: string | null;
  8640. model_name: string | null;
  8641. access_code_set: boolean;
  8642. serial: string;
  8643. target_printer_id: number | null;
  8644. auto_dispatch: boolean;
  8645. queue_force_color_match: boolean;
  8646. save_ams_mapping: boolean;
  8647. gcode_injection: boolean;
  8648. tailscale_disabled: boolean;
  8649. bind_ip: string | null;
  8650. remote_interface_ip: string | null;
  8651. position: number;
  8652. status: { running: boolean; pending_files: number; proxy?: VirtualPrinterProxyStatus };
  8653. }
  8654. export interface VirtualPrinterListResponse {
  8655. printers: VirtualPrinterConfig[];
  8656. models: Record<string, string>;
  8657. }
  8658. export const multiVirtualPrinterApi = {
  8659. list: () => request<VirtualPrinterListResponse>('/virtual-printers'),
  8660. get: (id: number) => request<VirtualPrinterConfig>(`/virtual-printers/${id}`),
  8661. create: (data: {
  8662. name?: string;
  8663. enabled?: boolean;
  8664. mode?: string;
  8665. model?: string;
  8666. access_code?: string;
  8667. target_printer_id?: number;
  8668. auto_dispatch?: boolean;
  8669. queue_force_color_match?: boolean;
  8670. save_ams_mapping?: boolean;
  8671. gcode_injection?: boolean;
  8672. bind_ip?: string;
  8673. remote_interface_ip?: string;
  8674. }) =>
  8675. request<VirtualPrinterConfig>('/virtual-printers', {
  8676. method: 'POST',
  8677. body: JSON.stringify(data),
  8678. }),
  8679. update: (id: number, data: {
  8680. name?: string;
  8681. enabled?: boolean;
  8682. mode?: string;
  8683. model?: string;
  8684. access_code?: string;
  8685. target_printer_id?: number;
  8686. auto_dispatch?: boolean;
  8687. queue_force_color_match?: boolean;
  8688. save_ams_mapping?: boolean;
  8689. gcode_injection?: boolean;
  8690. tailscale_disabled?: boolean;
  8691. bind_ip?: string;
  8692. remote_interface_ip?: string;
  8693. }) =>
  8694. request<VirtualPrinterConfig>(`/virtual-printers/${id}`, {
  8695. method: 'PUT',
  8696. body: JSON.stringify(data),
  8697. }),
  8698. remove: (id: number) =>
  8699. request<{ detail: string; id: number }>(`/virtual-printers/${id}`, {
  8700. method: 'DELETE',
  8701. }),
  8702. getTailscaleStatus: () =>
  8703. request<TailscaleStatusResponse>('/virtual-printers/tailscale-status'),
  8704. getCaCertificate: () =>
  8705. request<VPCaCertificate>('/virtual-printers/ca-certificate'),
  8706. diagnose: (id: number) =>
  8707. request<VPDiagnosticResult>(`/virtual-printers/${id}/diagnostic`),
  8708. };
  8709. /** The shared CA certificate every virtual printer presents — imported once
  8710. * into the slicer's trust store. Only the public certificate is returned. */
  8711. export interface VPCaCertificate {
  8712. pem: string;
  8713. fingerprint_sha256: string;
  8714. not_valid_after: string;
  8715. }
  8716. export type VPDiagnosticStatus = 'pass' | 'fail' | 'warn' | 'skip';
  8717. export interface VPDiagnosticCheck {
  8718. id:
  8719. | 'enabled'
  8720. | 'running'
  8721. | 'bind_interface'
  8722. | 'access_code'
  8723. | 'target_printer'
  8724. | 'port_ftps'
  8725. | 'port_mqtt'
  8726. | 'port_bind'
  8727. | 'certificate';
  8728. status: VPDiagnosticStatus;
  8729. params: Record<string, string | number>;
  8730. }
  8731. export interface VPDiagnosticResult {
  8732. vp_id: number;
  8733. vp_name: string;
  8734. mode: string;
  8735. overall: 'ok' | 'warnings' | 'problems';
  8736. checks: VPDiagnosticCheck[];
  8737. }
  8738. export interface TailscaleStatusResponse {
  8739. available: boolean;
  8740. fqdn: string;
  8741. hostname: string;
  8742. tailnet_name: string;
  8743. tailscale_ips: string[];
  8744. error: string | null;
  8745. }
  8746. // Pending Uploads API
  8747. export const pendingUploadsApi = {
  8748. list: () => request<PendingUpload[]>('/pending-uploads/'),
  8749. getCount: () => request<{ count: number }>('/pending-uploads/count'),
  8750. get: (id: number) => request<PendingUpload>(`/pending-uploads/${id}`),
  8751. archive: (id: number, data?: { tags?: string; notes?: string; project_id?: number }) =>
  8752. request<{ id: number; print_name: string; filename: string }>(`/pending-uploads/${id}/archive`, {
  8753. method: 'POST',
  8754. body: JSON.stringify(data || {}),
  8755. }),
  8756. discard: (id: number) =>
  8757. request<{ success: boolean }>(`/pending-uploads/${id}`, { method: 'DELETE' }),
  8758. archiveAll: () =>
  8759. request<{ archived: number; failed: number }>('/pending-uploads/archive-all', { method: 'POST' }),
  8760. discardAll: () =>
  8761. request<{ discarded: number }>('/pending-uploads/discard-all', { method: 'DELETE' }),
  8762. };
  8763. // Firmware API Types
  8764. export interface AvailableFirmwareVersion {
  8765. version: string;
  8766. file_available: boolean;
  8767. download_url: string | null;
  8768. release_notes: string | null;
  8769. release_time: string | null;
  8770. }
  8771. export interface FirmwareUpdateInfo {
  8772. printer_id: number;
  8773. printer_name: string;
  8774. model: string | null;
  8775. current_version: string | null;
  8776. latest_version: string | null;
  8777. update_available: boolean;
  8778. download_url: string | null;
  8779. release_notes: string | null;
  8780. available_versions: AvailableFirmwareVersion[];
  8781. }
  8782. export interface FirmwareUploadPrepare {
  8783. can_proceed: boolean;
  8784. sd_card_present: boolean;
  8785. sd_card_free_space: number;
  8786. firmware_size: number;
  8787. space_sufficient: boolean;
  8788. update_available: boolean;
  8789. current_version: string | null;
  8790. latest_version: string | null;
  8791. target_version: string | null;
  8792. firmware_filename: string | null;
  8793. errors: string[];
  8794. }
  8795. export interface FirmwareUploadStatus {
  8796. status: 'idle' | 'preparing' | 'downloading' | 'uploading' | 'complete' | 'error';
  8797. progress: number;
  8798. message: string;
  8799. error: string | null;
  8800. firmware_filename: string | null;
  8801. firmware_version: string | null;
  8802. }
  8803. // Firmware API
  8804. export const firmwareApi = {
  8805. checkUpdates: () =>
  8806. request<{ updates: FirmwareUpdateInfo[]; updates_available: number }>('/firmware/updates'),
  8807. checkPrinterUpdate: (printerId: number) => firmwareUpdateBatch(printerId),
  8808. prepareUpload: (printerId: number, version?: string) =>
  8809. request<FirmwareUploadPrepare>(
  8810. `/firmware/updates/${printerId}/prepare${version ? `?version=${encodeURIComponent(version)}` : ''}`,
  8811. ),
  8812. startUpload: (printerId: number, version?: string) =>
  8813. request<{ started: boolean; message: string }>(
  8814. `/firmware/updates/${printerId}/upload${version ? `?version=${encodeURIComponent(version)}` : ''}`,
  8815. { method: 'POST' },
  8816. ),
  8817. getUploadStatus: (printerId: number) =>
  8818. request<FirmwareUploadStatus>(`/firmware/updates/${printerId}/upload/status`),
  8819. };
  8820. // Support types
  8821. export interface DebugLoggingState {
  8822. enabled: boolean;
  8823. enabled_at: string | null;
  8824. duration_seconds: number | null;
  8825. }
  8826. export interface LogEntry {
  8827. timestamp: string;
  8828. level: string;
  8829. logger_name: string;
  8830. message: string;
  8831. }
  8832. export interface LogsResponse {
  8833. entries: LogEntry[];
  8834. total_in_file: number;
  8835. filtered_count: number;
  8836. }
  8837. // Support API
  8838. export const supportApi = {
  8839. getDebugLoggingState: () =>
  8840. request<DebugLoggingState>('/support/debug-logging'),
  8841. setDebugLogging: (enabled: boolean) =>
  8842. request<DebugLoggingState>('/support/debug-logging', {
  8843. method: 'POST',
  8844. body: JSON.stringify({ enabled }),
  8845. }),
  8846. downloadSupportBundle: async () => {
  8847. const headers: Record<string, string> = {};
  8848. if (authToken) {
  8849. headers['Authorization'] = `Bearer ${authToken}`;
  8850. }
  8851. const response = await fetch(`${API_BASE}/support/bundle`, { headers });
  8852. if (!response.ok) {
  8853. const error = await response.json().catch(() => ({}));
  8854. throw new Error(error.detail || `HTTP ${response.status}`);
  8855. }
  8856. // Get filename from Content-Disposition header or use default
  8857. const disposition = response.headers.get('Content-Disposition');
  8858. const filename = parseContentDispositionFilename(disposition) || 'bambuddy-support.zip';
  8859. // Download the blob
  8860. const blob = await response.blob();
  8861. const url = window.URL.createObjectURL(blob);
  8862. const a = document.createElement('a');
  8863. a.href = url;
  8864. a.download = filename;
  8865. document.body.appendChild(a);
  8866. a.click();
  8867. document.body.removeChild(a);
  8868. window.URL.revokeObjectURL(url);
  8869. },
  8870. getLogs: (params?: { limit?: number; level?: string; search?: string }) => {
  8871. const searchParams = new URLSearchParams();
  8872. if (params?.limit) searchParams.set('limit', params.limit.toString());
  8873. if (params?.level) searchParams.set('level', params.level);
  8874. if (params?.search) searchParams.set('search', params.search);
  8875. const query = searchParams.toString();
  8876. return request<LogsResponse>(`/support/logs${query ? `?${query}` : ''}`);
  8877. },
  8878. clearLogs: () =>
  8879. request<{ message: string }>('/support/logs', { method: 'DELETE' }),
  8880. };
  8881. // SpoolBuddy types
  8882. export interface SpoolBuddyDevice {
  8883. id: number;
  8884. device_id: string;
  8885. hostname: string;
  8886. ip_address: string;
  8887. backend_url?: string | null;
  8888. firmware_version: string | null;
  8889. has_nfc: boolean;
  8890. has_scale: boolean;
  8891. tare_offset: number;
  8892. calibration_factor: number;
  8893. nfc_reader_type: string | null;
  8894. nfc_connection: string | null;
  8895. display_brightness: number;
  8896. display_blank_timeout: number;
  8897. has_backlight: boolean;
  8898. last_calibrated_at: string | null;
  8899. last_seen: string | null;
  8900. pending_command: string | null;
  8901. nfc_ok: boolean;
  8902. scale_ok: boolean;
  8903. uptime_s: number;
  8904. update_status: string | null;
  8905. update_message: string | null;
  8906. system_stats: {
  8907. os?: { os?: string; kernel?: string; arch?: string; python?: string };
  8908. cpu_temp_c?: number;
  8909. cpu_count?: number;
  8910. load_avg?: number[];
  8911. memory?: { total_mb?: number; available_mb?: number; used_mb?: number; percent?: number };
  8912. disk?: { total_gb?: number; used_gb?: number; free_gb?: number; percent?: number };
  8913. system_uptime_s?: number;
  8914. } | null;
  8915. online: boolean;
  8916. }
  8917. export interface DaemonUpdateCheck {
  8918. current_version: string;
  8919. latest_version: string | null;
  8920. update_available: boolean;
  8921. }
  8922. // SpoolBuddy API
  8923. export const spoolbuddyApi = {
  8924. getDevices: () =>
  8925. request<SpoolBuddyDevice[]>('/spoolbuddy/devices'),
  8926. deleteDevice: (deviceId: string) =>
  8927. request<{ status: string; device_id: string }>(`/spoolbuddy/devices/${deviceId}`, {
  8928. method: 'DELETE',
  8929. }),
  8930. tare: (deviceId: string) =>
  8931. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/calibration/tare`, {
  8932. method: 'POST',
  8933. body: '{}',
  8934. }),
  8935. setCalibrationFactor: (deviceId: string, knownWeightGrams: number, rawAdc: number, tareRawAdc?: number) =>
  8936. request<{ tare_offset: number; calibration_factor: number }>(`/spoolbuddy/devices/${deviceId}/calibration/set-factor`, {
  8937. method: 'POST',
  8938. body: JSON.stringify({ known_weight_grams: knownWeightGrams, raw_adc: rawAdc, tare_raw_adc: tareRawAdc }),
  8939. }),
  8940. updateSpoolWeight: (spoolId: number, weightGrams: number) =>
  8941. request<{ status: string; weight_used: number }>('/spoolbuddy/scale/update-spool-weight', {
  8942. method: 'POST',
  8943. body: JSON.stringify({ spool_id: spoolId, weight_grams: weightGrams }),
  8944. }),
  8945. updateDisplay: (deviceId: string, brightness: number, blankTimeout: number) =>
  8946. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/display`, {
  8947. method: 'PUT',
  8948. body: JSON.stringify({ brightness, blank_timeout: blankTimeout }),
  8949. }),
  8950. updateSystemConfig: (deviceId: string, backendUrl: string, apiKey?: string) =>
  8951. request<{ status: string; message: string }>(`/spoolbuddy/devices/${deviceId}/system/config`, {
  8952. method: 'POST',
  8953. body: JSON.stringify({ backend_url: backendUrl, ...(apiKey ? { api_key: apiKey } : {}) }),
  8954. }),
  8955. checkDaemonUpdate: (deviceId: string) =>
  8956. request<DaemonUpdateCheck>(`/spoolbuddy/devices/${deviceId}/update-check`),
  8957. triggerUpdate: (deviceId: string) =>
  8958. request<{ status: string; message: string }>(`/spoolbuddy/devices/${deviceId}/update`, {
  8959. method: 'POST',
  8960. body: '{}',
  8961. }),
  8962. getSSHPublicKey: () =>
  8963. request<{ public_key: string }>('/spoolbuddy/ssh/public-key'),
  8964. writeTag: (deviceId: string, spoolId: number) =>
  8965. request<{ status: string; warnings?: string[] }>('/spoolbuddy/nfc/write-tag', {
  8966. method: 'POST',
  8967. body: JSON.stringify({ device_id: deviceId, spool_id: spoolId }),
  8968. }),
  8969. cancelWrite: (deviceId: string) =>
  8970. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/cancel-write`, {
  8971. method: 'POST',
  8972. body: '{}',
  8973. }),
  8974. systemCommand: (deviceId: string, command: 'reboot' | 'shutdown' | 'restart_daemon' | 'restart_browser') =>
  8975. request<{ status: string; command: string }>(`/spoolbuddy/devices/${deviceId}/system/command`, {
  8976. method: 'POST',
  8977. body: JSON.stringify({ command }),
  8978. }),
  8979. queueDiagnostics: (deviceId: string, type: 'nfc' | 'scale' | 'read_tag') =>
  8980. request<{ status: string; diagnostic: string; message: string }>(
  8981. `/spoolbuddy/diagnostics/${deviceId}/run?diagnostic=${type}`,
  8982. { method: 'POST', body: '{}' }
  8983. ),
  8984. getDiagnosticResult: (deviceId: string, type: 'nfc' | 'scale' | 'read_tag') =>
  8985. request<{ diagnostic: string; success: boolean; output: string; exit_code: number }>(
  8986. `/spoolbuddy/diagnostics/${deviceId}/result?diagnostic=${type}`,
  8987. { method: 'GET' }
  8988. ),
  8989. };
  8990. export interface BugReportRequest {
  8991. description: string;
  8992. email?: string;
  8993. screenshot_base64?: string;
  8994. include_support_info?: boolean;
  8995. debug_logs?: string;
  8996. }
  8997. export interface BugReportResponse {
  8998. success: boolean;
  8999. message: string;
  9000. issue_url?: string;
  9001. issue_number?: number;
  9002. }
  9003. export const bugReportApi = {
  9004. submit: (data: BugReportRequest) =>
  9005. request<BugReportResponse>('/bug-report/submit', {
  9006. method: 'POST',
  9007. body: JSON.stringify(data),
  9008. }),
  9009. startLogging: () =>
  9010. request<{ started: boolean; was_debug: boolean }>('/bug-report/start-logging', {
  9011. method: 'POST',
  9012. }),
  9013. stopLogging: (wasDebug: boolean) =>
  9014. request<{ logs: string }>(`/bug-report/stop-logging?was_debug=${wasDebug}`, {
  9015. method: 'POST',
  9016. }),
  9017. };
  9018. export type AnnouncementLevel = 'info' | 'important' | 'critical';
  9019. export interface AnnouncementText {
  9020. title: string;
  9021. body: string;
  9022. link_label?: string;
  9023. }
  9024. // One message from the Bambuddy maintainers. `texts` holds every language the
  9025. // message was written in; English is always there.
  9026. export interface Announcement {
  9027. id: string;
  9028. level: AnnouncementLevel;
  9029. texts: Record<string, AnnouncementText>;
  9030. link_url: string | null;
  9031. published_at: string | null;
  9032. expires_at: string | null;
  9033. // Past its expiry: kept as history, listed under "Earlier", never unread.
  9034. archived: boolean;
  9035. read: boolean;
  9036. }
  9037. // `visible` says whether this user may see announcements at all (switched on,
  9038. // and admin or "show to all users"); it keeps the sidebar entry while nothing
  9039. // is published.
  9040. export interface AnnouncementList {
  9041. visible: boolean;
  9042. announcements: Announcement[];
  9043. }
  9044. export const announcementsApi = {
  9045. list: () => request<AnnouncementList>('/announcements'),
  9046. markRead: (id: string) =>
  9047. request<void>(`/announcements/${encodeURIComponent(id)}/read`, { method: 'POST' }),
  9048. };
  9049. export interface SponsorPromptCheckResponse {
  9050. show: boolean;
  9051. milestone?: string;
  9052. family?: 'prints' | 'cost' | 'archives' | 'anniversary' | 'version-update';
  9053. threshold?: number;
  9054. payload?: Record<string, unknown>;
  9055. }
  9056. export const sponsorPromptApi = {
  9057. check: () => request<SponsorPromptCheckResponse>('/sponsor-prompt/check'),
  9058. dismiss: (milestone: string) =>
  9059. request<void>('/sponsor-prompt/dismiss', {
  9060. method: 'POST',
  9061. body: JSON.stringify({ milestone }),
  9062. }),
  9063. };