client.ts 301 KB

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