client.ts 331 KB

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