client.ts 294 KB

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