client.ts 268 KB

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