client.ts 200 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090
  1. import type { ArchivePlatesResponse, LibraryFilePlatesResponse } from '../types/plates';
  2. const API_BASE = '/api/v1';
  3. // 'persistent' also writes to localStorage so the token survives tab close
  4. // (used by Remember Me and the ?token= kiosk bootstrap).
  5. let authToken: string | null =
  6. sessionStorage.getItem('auth_token') ?? localStorage.getItem('auth_token');
  7. export type TokenPersistence = 'session' | 'persistent';
  8. export function setAuthToken(token: string | null, persistence: TokenPersistence = 'session') {
  9. authToken = token;
  10. try {
  11. if (token) {
  12. sessionStorage.setItem('auth_token', token);
  13. } else {
  14. sessionStorage.removeItem('auth_token');
  15. }
  16. } catch (err) {
  17. // Storage unavailable (quota exceeded, private mode): in-memory token still works for this tab.
  18. console.warn('setAuthToken: sessionStorage unavailable, token kept in-memory only', err);
  19. }
  20. try {
  21. if (!token) {
  22. localStorage.removeItem('auth_token');
  23. } else if (persistence === 'persistent') {
  24. localStorage.setItem('auth_token', token);
  25. }
  26. } catch (err) {
  27. console.warn('setAuthToken: localStorage operation failed', err);
  28. }
  29. }
  30. export function getAuthToken(): string | null {
  31. return authToken;
  32. }
  33. // Stream token for image/video URLs loaded via <img>/<video> tags
  34. // (these can't send Authorization headers, so a query param token is used)
  35. let streamToken: string | null = null;
  36. export function setStreamToken(token: string | null) {
  37. streamToken = token;
  38. }
  39. export function getStreamToken(): string | null {
  40. return streamToken;
  41. }
  42. /** Append the stream token to a URL if available (for <img>/<video> src). */
  43. export function withStreamToken(url: string): string {
  44. if (!streamToken) return url;
  45. const sep = url.includes('?') ? '&' : '?';
  46. return `${url}${sep}token=${encodeURIComponent(streamToken)}`;
  47. }
  48. function parseContentDispositionFilename(header: string | null): string | null {
  49. if (!header) return null;
  50. // RFC 5987: filename*=utf-8''percent-encoded-name
  51. const rfc5987Match = header.match(/filename\*=(?:UTF-8|utf-8)''(.+?)(?:;|$)/);
  52. if (rfc5987Match) {
  53. try { return decodeURIComponent(rfc5987Match[1]); } catch { /* fall through */ }
  54. }
  55. // Standard: filename="name" or filename=name
  56. const standardMatch = header.match(/filename="?([^";\n]+)"?/);
  57. return standardMatch?.[1] || null;
  58. }
  59. async function request<T>(
  60. endpoint: string,
  61. options: RequestInit = {}
  62. ): Promise<T> {
  63. const headers: Record<string, string> = {
  64. 'Content-Type': 'application/json',
  65. ...options.headers as Record<string, string>,
  66. };
  67. // Add auth token if available
  68. if (authToken) {
  69. headers['Authorization'] = `Bearer ${authToken}`;
  70. }
  71. const response = await fetch(`${API_BASE}${endpoint}`, {
  72. ...options,
  73. cache: 'no-store', // Prevent browser caching of API responses
  74. credentials: 'include', // Required for HttpOnly cookies (e.g. 2fa_challenge)
  75. headers,
  76. });
  77. if (!response.ok) {
  78. const error = await response.json().catch(() => ({}));
  79. const detail = error.detail;
  80. const message = typeof detail === 'string'
  81. ? detail
  82. : (detail ? JSON.stringify(detail) : `HTTP ${response.status}`);
  83. // Handle 401 Unauthorized - only clear token if it's actually invalid
  84. // Don't clear on "Authentication required" which might be a timing issue
  85. if (response.status === 401) {
  86. const invalidTokenMessages = [
  87. 'Could not validate credentials',
  88. 'Token has expired',
  89. 'User not found or inactive',
  90. 'Invalid API key',
  91. 'API key has expired',
  92. ];
  93. if (invalidTokenMessages.some(m => message.includes(m))) {
  94. setAuthToken(null);
  95. }
  96. }
  97. throw new Error(message);
  98. }
  99. // Handle empty responses (204 No Content, etc.)
  100. const contentLength = response.headers.get('content-length');
  101. if (response.status === 204 || contentLength === '0') {
  102. return undefined as T;
  103. }
  104. return await response.json();
  105. }
  106. // Long-lived camera-stream tokens (#1108). The `token` field is populated
  107. // only on the create response — listing endpoints set it to null because
  108. // the plaintext value is shown to the user exactly once.
  109. export interface LongLivedCameraToken {
  110. id: number;
  111. user_id: number;
  112. name: string;
  113. scope: 'camera_stream';
  114. lookup_prefix: string;
  115. created_at: string;
  116. expires_at: string;
  117. last_used_at: string | null;
  118. token: string | null;
  119. }
  120. // Printer types
  121. export interface Printer {
  122. id: number;
  123. name: string;
  124. serial_number: string;
  125. ip_address: string;
  126. access_code: string;
  127. model: string | null;
  128. location: string | null; // Group/location name
  129. nozzle_count: number; // 1 or 2, auto-detected from MQTT
  130. is_active: boolean;
  131. auto_archive: boolean;
  132. external_camera_url: string | null;
  133. external_camera_type: string | null; // "mjpeg", "rtsp", "snapshot"
  134. external_camera_enabled: boolean;
  135. camera_rotation: number; // 0, 90, 180, 270 degrees
  136. plate_detection_enabled: boolean; // Check plate before print
  137. plate_detection_roi?: PlateDetectionROI; // ROI for plate detection
  138. created_at: string;
  139. updated_at: string;
  140. }
  141. export interface HMSError {
  142. code: string;
  143. attr: number; // Attribute value for constructing wiki URL
  144. module: number;
  145. severity: number; // 1=fatal, 2=serious, 3=common, 4=info
  146. }
  147. export interface AMSTray {
  148. id: number;
  149. tray_color: string | null;
  150. tray_type: string | null;
  151. tray_sub_brands: string | null; // Full name like "PLA Basic", "PETG HF"
  152. tray_id_name: string | null; // Bambu filament ID like "A00-Y2" (can decode to color)
  153. tray_info_idx: string | null; // Filament preset ID like "GFA00" - maps to cloud setting_id
  154. remain: number;
  155. k: number | null; // Pressure advance value (from tray or K-profile lookup)
  156. cali_idx: number | null; // Calibration index for K-profile lookup
  157. tag_uid: string | null; // RFID tag UID (any tag)
  158. tray_uuid: string | null; // Bambu Lab spool UUID (32-char hex, only valid for Bambu Lab spools)
  159. nozzle_temp_min: number | null; // Min nozzle temperature
  160. nozzle_temp_max: number | null; // Max nozzle temperature
  161. drying_temp: number | null; // RFID-recommended drying temp
  162. drying_time: number | null; // RFID-recommended drying time (hours)
  163. state: number | null; // AMS tray state: 9=empty, 10=spool present not loaded, 11=loaded
  164. }
  165. export interface AMSUnit {
  166. id: number;
  167. humidity: number | null;
  168. temp: number | null;
  169. is_ams_ht: boolean; // True for AMS-HT (single spool), False for regular AMS (4 spools)
  170. tray: AMSTray[];
  171. serial_number: string; // AMS unit serial number (from MQTT sn field)
  172. sw_ver: string; // AMS firmware version (from get_version info.module ams/* entry)
  173. dry_time: number; // Minutes remaining (0 = not drying, >0 = drying active)
  174. dry_status: number; // 0=Off, 1=Checking, 2=Drying, 3=Cooling, 4=Stopping, 5=Error
  175. dry_sub_status: number; // 0=Off, 1=Heating, 2=Dehumidify
  176. dry_sf_reason: number[]; // Cannot-dry reasons (1=InsufficientPower, 8=NeedPluginPower)
  177. module_type: string; // "ams", "n3f", "n3s"
  178. }
  179. export interface NozzleInfo {
  180. nozzle_type: string; // "stainless_steel" or "hardened_steel"
  181. nozzle_diameter: string; // e.g., "0.4"
  182. }
  183. export interface NozzleRackSlot {
  184. id: number;
  185. nozzle_type: string;
  186. nozzle_diameter: string;
  187. wear: number | null;
  188. stat: number | null; // Nozzle status (e.g. mounted/docked)
  189. max_temp: number;
  190. serial_number: string;
  191. filament_color: string; // RGBA hex ("00000000" = no filament)
  192. filament_id: string;
  193. filament_type: string; // Material type (e.g. "PLA", "PETG")
  194. }
  195. export interface PrintOptions {
  196. // Core AI detectors
  197. spaghetti_detector: boolean;
  198. print_halt: boolean;
  199. halt_print_sensitivity: string; // "low", "medium", "high" - spaghetti sensitivity
  200. first_layer_inspector: boolean;
  201. printing_monitor: boolean;
  202. buildplate_marker_detector: boolean;
  203. allow_skip_parts: boolean;
  204. // Additional AI detectors (decoded from cfg bitmask)
  205. nozzle_clumping_detector: boolean;
  206. nozzle_clumping_sensitivity: string; // "low", "medium", "high"
  207. pileup_detector: boolean;
  208. pileup_sensitivity: string; // "low", "medium", "high"
  209. airprint_detector: boolean;
  210. airprint_sensitivity: string; // "low", "medium", "high"
  211. auto_recovery_step_loss: boolean;
  212. filament_tangle_detect: boolean;
  213. }
  214. export interface FilaSwitchState {
  215. installed: boolean;
  216. // in[track] = currently loaded slot for that track (-1 = empty)
  217. in_slots: number[];
  218. // out[track] = extruder this track terminates at (0 = right, 1 = left)
  219. out_extruders: number[];
  220. stat: number;
  221. info: number;
  222. }
  223. export interface PrinterStatus {
  224. id: number;
  225. name: string;
  226. connected: boolean;
  227. state: string | null;
  228. current_print: string | null;
  229. subtask_name: string | null;
  230. current_archive_id: number | null;
  231. current_plate_id: number | null;
  232. gcode_file: string | null;
  233. progress: number | null;
  234. remaining_time: number | null;
  235. layer_num: number | null;
  236. total_layers: number | null;
  237. temperatures: {
  238. bed?: number;
  239. bed_target?: number;
  240. bed_heating?: boolean; // Actual heater state from MQTT
  241. nozzle?: number;
  242. nozzle_target?: number;
  243. nozzle_heating?: boolean; // Actual heater state from MQTT
  244. nozzle_2?: number; // Second nozzle for H2 series (dual nozzle)
  245. nozzle_2_target?: number;
  246. nozzle_2_heating?: boolean; // Actual heater state from MQTT
  247. chamber?: number;
  248. chamber_target?: number;
  249. chamber_heating?: boolean; // Actual heater state from MQTT
  250. } | null;
  251. cover_url: string | null;
  252. hms_errors: HMSError[];
  253. ams: AMSUnit[];
  254. ams_exists: boolean;
  255. vt_tray: AMSTray[]; // Virtual tray / external spool(s)
  256. store_to_sdcard: boolean; // Store sent files on SD card
  257. timelapse: boolean; // Timelapse recording active
  258. ipcam: boolean; // Live view enabled
  259. wifi_signal: number | null; // WiFi signal strength in dBm
  260. wired_network: boolean; // Ethernet connection detected
  261. door_open: boolean; // Enclosure door open (X1/P1S/P2S/H2*)
  262. nozzles: NozzleInfo[]; // Nozzle hardware info (index 0=left/primary, 1=right)
  263. nozzle_rack: NozzleRackSlot[]; // H2C 6-nozzle tool-changer rack
  264. print_options: PrintOptions | null; // AI detection and print options
  265. // Calibration stage tracking
  266. stg_cur: number; // Current stage number (-1 = not calibrating)
  267. stg_cur_name: string | null; // Human-readable current stage name
  268. stg: number[]; // List of stage numbers in calibration sequence
  269. // Air conditioning mode (0=cooling, 1=heating)
  270. airduct_mode: number;
  271. // Print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  272. speed_level: number;
  273. // Chamber light on/off
  274. chamber_light: boolean;
  275. // Active extruder for dual nozzle (0=right, 1=left)
  276. active_extruder: number;
  277. // AMS mapping - which AMS is connected to which nozzle
  278. // Format: [ams_id_for_nozzle0, ams_id_for_nozzle1, ...] where -1 means no AMS
  279. ams_mapping: number[];
  280. // Per-AMS extruder mapping - extracted from each AMS unit's info field
  281. // Format: {ams_id: extruder_id} where extruder 0=right, 1=left
  282. // Note: JSON keys are always strings
  283. ams_extruder_map: Record<string, number>;
  284. // Filament Track Switch accessory — null when not installed. When present,
  285. // AMS slots aren't tied to a specific extruder; the FTS routes any slot to
  286. // either extruder, so per-extruder slot filtering must be skipped.
  287. fila_switch: FilaSwitchState | null;
  288. // Currently loaded tray (global tray ID, 255 = no filament loaded, 254 = external spool)
  289. tray_now: number;
  290. // AMS status for filament change tracking (0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration)
  291. ams_status_main: number;
  292. // AMS sub-status for filament change step (when main=1): 4=retraction, 6=load verification, 7=purge
  293. ams_status_sub: number;
  294. // mc_print_sub_stage - filament change step indicator used by OrcaSlicer/BambuStudio
  295. mc_print_sub_stage: number;
  296. // Timestamp of last AMS data update (for RFID refresh detection)
  297. last_ams_update: number;
  298. // Number of printable objects in current print (for skip objects feature)
  299. printable_objects_count: number;
  300. // Fan speeds (0-100 percentage, null if not available for this model)
  301. cooling_fan_speed: number | null; // Part cooling fan
  302. big_fan1_speed: number | null; // Auxiliary fan
  303. big_fan2_speed: number | null; // Chamber/exhaust fan
  304. heatbreak_fan_speed: number | null; // Hotend heatbreak fan
  305. firmware_version: string | null; // Firmware version from MQTT
  306. // Developer LAN mode: true = enabled, false = disabled, null = unknown
  307. developer_mode: boolean | null;
  308. // Queue: printer is awaiting user ack that the build plate was cleared after a
  309. // finished/failed print. Persisted across restarts (#961).
  310. awaiting_plate_clear: boolean;
  311. // AMS drying support
  312. supports_drying: boolean;
  313. }
  314. export interface PrinterCreate {
  315. name: string;
  316. serial_number: string;
  317. ip_address: string;
  318. access_code: string;
  319. model?: string;
  320. location?: string;
  321. auto_archive?: boolean;
  322. external_camera_url?: string | null;
  323. external_camera_type?: string | null;
  324. external_camera_enabled?: boolean;
  325. camera_rotation?: number;
  326. plate_detection_enabled?: boolean;
  327. plate_detection_roi?: PlateDetectionROI;
  328. }
  329. // Plate Detection
  330. export interface PlateDetectionROI {
  331. x: number; // X start % (0.0-1.0)
  332. y: number; // Y start % (0.0-1.0)
  333. w: number; // Width % (0.0-1.0)
  334. h: number; // Height % (0.0-1.0)
  335. }
  336. export interface PlateDetectionResult {
  337. is_empty: boolean;
  338. confidence: number;
  339. difference_percent: number;
  340. message: string;
  341. has_debug_image: boolean;
  342. debug_image_url?: string;
  343. needs_calibration: boolean;
  344. light_warning?: boolean;
  345. reference_count?: number;
  346. max_references?: number;
  347. roi?: PlateDetectionROI;
  348. }
  349. export interface PlateDetectionStatus {
  350. available: boolean;
  351. calibrated: boolean;
  352. reference_count: number;
  353. max_references: number;
  354. message: string;
  355. }
  356. export interface CalibrationResult {
  357. success: boolean;
  358. message: string;
  359. }
  360. export interface PlateReference {
  361. index: number;
  362. label: string;
  363. timestamp: string;
  364. has_image: boolean;
  365. thumbnail_url: string;
  366. }
  367. // Archive types
  368. export interface ArchiveDuplicate {
  369. id: number;
  370. print_name: string | null;
  371. created_at: string;
  372. match_type: 'exact' | 'similar'; // 'exact' = hash match, 'similar' = name match
  373. }
  374. export interface Archive {
  375. id: number;
  376. printer_id: number | null;
  377. project_id: number | null;
  378. project_name: string | null;
  379. filename: string;
  380. file_path: string;
  381. file_size: number;
  382. content_hash: string | null;
  383. thumbnail_path: string | null;
  384. timelapse_path: string | null;
  385. source_3mf_path: string | null;
  386. f3d_path: string | null;
  387. duplicates: ArchiveDuplicate[] | null;
  388. duplicate_count: number;
  389. duplicate_sequence: number; // 0 = original, 1+ = nth duplicate
  390. original_archive_id: number | null; // ID of the first/original archive
  391. object_count: number | null;
  392. print_name: string | null;
  393. print_time_seconds: number | null;
  394. actual_time_seconds: number | null; // Computed from started_at/completed_at
  395. time_accuracy: number | null; // Percentage: 100 = perfect, >100 = faster than estimated
  396. filament_used_grams: number | null;
  397. filament_type: string | null;
  398. filament_color: string | null;
  399. layer_height: number | null;
  400. total_layers: number | null;
  401. nozzle_diameter: number | null;
  402. bed_temperature: number | null;
  403. nozzle_temperature: number | null;
  404. sliced_for_model: string | null; // Printer model this file was sliced for
  405. status: string;
  406. started_at: string | null;
  407. completed_at: string | null;
  408. extra_data: Record<string, unknown> | null;
  409. makerworld_url: string | null;
  410. designer: string | null;
  411. external_url: string | null;
  412. is_favorite: boolean;
  413. tags: string | null;
  414. notes: string | null;
  415. cost: number | null;
  416. photos: string[] | null;
  417. failure_reason: string | null;
  418. quantity: number;
  419. energy_kwh: number | null;
  420. energy_cost: number | null;
  421. created_at: string;
  422. // User tracking (Issue #206)
  423. created_by_id: number | null;
  424. created_by_username: string | null;
  425. }
  426. export interface ArchiveSlim {
  427. printer_id: number | null;
  428. print_name: string | null;
  429. print_time_seconds: number | null;
  430. actual_time_seconds: number | null;
  431. filament_used_grams: number | null;
  432. filament_type: string | null;
  433. filament_color: string | null;
  434. status: string;
  435. started_at: string | null;
  436. completed_at: string | null;
  437. cost: number | null;
  438. quantity: number;
  439. created_at: string;
  440. }
  441. export interface PrintLogEntry {
  442. id: number;
  443. print_name: string | null;
  444. printer_name: string | null;
  445. printer_id: number | null;
  446. status: string;
  447. started_at: string | null;
  448. completed_at: string | null;
  449. duration_seconds: number | null;
  450. filament_type: string | null;
  451. filament_color: string | null;
  452. filament_used_grams: number | null;
  453. thumbnail_path: string | null;
  454. created_by_username: string | null;
  455. created_at: string;
  456. }
  457. export interface PrintLogResponse {
  458. items: PrintLogEntry[];
  459. total: number;
  460. }
  461. export interface ArchiveStats {
  462. total_prints: number;
  463. successful_prints: number;
  464. failed_prints: number;
  465. total_print_time_hours: number;
  466. total_filament_grams: number;
  467. total_cost: number;
  468. prints_by_filament_type: Record<string, number>;
  469. prints_by_printer: Record<string, number>;
  470. average_time_accuracy: number | null;
  471. time_accuracy_by_printer: Record<string, number> | null;
  472. total_energy_kwh: number;
  473. total_energy_cost: number;
  474. // True when a date-filtered total-consumption query is running on incomplete
  475. // snapshot history (e.g. right after upgrade, before hourly snapshots have
  476. // a baseline). UI should explain why the number may undercount.
  477. energy_data_warming_up?: boolean;
  478. }
  479. export interface TagInfo {
  480. name: string;
  481. count: number;
  482. }
  483. export interface FailureAnalysis {
  484. period_days: number;
  485. total_prints: number;
  486. failed_prints: number;
  487. failure_rate: number;
  488. failures_by_reason: Record<string, number>;
  489. failures_by_filament: Record<string, number>;
  490. failures_by_printer: Record<string, number>;
  491. failures_by_hour: Record<number, number>;
  492. recent_failures: Array<{
  493. id: number;
  494. print_name: string;
  495. failure_reason: string | null;
  496. filament_type: string | null;
  497. printer_id: number | null;
  498. created_at: string | null;
  499. }>;
  500. trend: Array<{
  501. week_start: string;
  502. total_prints: number;
  503. failed_prints: number;
  504. failure_rate: number;
  505. }>;
  506. }
  507. export interface BulkUploadResult {
  508. uploaded: number;
  509. failed: number;
  510. results: Array<{ filename: string; id: number; status: string }>;
  511. errors: Array<{ filename: string; error: string }>;
  512. }
  513. // Archive Comparison types
  514. export interface ComparisonArchiveInfo {
  515. id: number;
  516. print_name: string;
  517. status: string;
  518. created_at: string | null;
  519. printer_id: number | null;
  520. project_name: string | null;
  521. }
  522. export interface ComparisonField {
  523. field: string;
  524. label: string;
  525. unit: string | null;
  526. values: (string | number | null)[];
  527. raw_values: (string | number | null)[];
  528. has_difference: boolean;
  529. }
  530. export interface SuccessCorrelationInsight {
  531. field: string;
  532. label: string;
  533. insight: string;
  534. success_avg?: number;
  535. failed_avg?: number;
  536. success_values?: string[];
  537. failed_values?: string[];
  538. }
  539. export interface SuccessCorrelation {
  540. has_both_outcomes: boolean;
  541. message?: string;
  542. successful_count?: number;
  543. failed_count?: number;
  544. insights?: SuccessCorrelationInsight[];
  545. }
  546. export interface ArchiveComparison {
  547. archives: ComparisonArchiveInfo[];
  548. comparison: ComparisonField[];
  549. differences: ComparisonField[];
  550. success_correlation: SuccessCorrelation;
  551. }
  552. export interface SimilarArchive {
  553. archive: {
  554. id: number;
  555. print_name: string;
  556. status: string;
  557. created_at: string | null;
  558. };
  559. match_reason: string;
  560. match_score: number;
  561. }
  562. // Project types
  563. export interface ProjectStats {
  564. total_archives: number;
  565. total_items: number; // Sum of quantities (total items printed)
  566. completed_prints: number; // Sum of quantities for completed prints (parts)
  567. failed_prints: number;
  568. queued_prints: number;
  569. in_progress_prints: number;
  570. total_print_time_hours: number;
  571. total_filament_grams: number;
  572. progress_percent: number | null; // Plates progress (total_archives / target_count)
  573. parts_progress_percent: number | null; // Parts progress (completed_prints / target_parts_count)
  574. estimated_cost: number;
  575. total_energy_kwh: number;
  576. total_energy_cost: number;
  577. remaining_prints: number | null; // Remaining plates
  578. remaining_parts: number | null; // Remaining parts
  579. bom_total_items: number;
  580. bom_completed_items: number;
  581. bom_cost: number;
  582. }
  583. export interface ProjectChildPreview {
  584. id: number;
  585. name: string;
  586. color: string | null;
  587. status: string;
  588. progress_percent: number | null;
  589. }
  590. export interface Project {
  591. id: number;
  592. name: string;
  593. description: string | null;
  594. color: string | null;
  595. status: string; // active, completed, archived
  596. target_count: number | null; // Target number of plates/print jobs
  597. target_parts_count: number | null; // Target number of parts/objects
  598. notes: string | null;
  599. attachments: ProjectAttachment[] | null;
  600. tags: string | null;
  601. due_date: string | null;
  602. priority: string; // low, normal, high, urgent
  603. budget: number | null;
  604. is_template: boolean;
  605. template_source_id: number | null;
  606. parent_id: number | null;
  607. parent_name: string | null;
  608. children: ProjectChildPreview[];
  609. created_at: string;
  610. updated_at: string;
  611. stats?: ProjectStats;
  612. url: string | null; // External link rendered next to project name on the card (#1155)
  613. cover_image_filename: string | null; // Filename within project attachments dir (#1155)
  614. }
  615. export interface ProjectAttachment {
  616. filename: string;
  617. original_name: string;
  618. size: number;
  619. uploaded_at: string;
  620. }
  621. export interface ArchivePreview {
  622. id: number;
  623. print_name: string | null;
  624. thumbnail_path: string | null;
  625. status: string;
  626. filament_type: string | null;
  627. filament_color: string | null;
  628. }
  629. export interface ProjectListItem {
  630. id: number;
  631. name: string;
  632. description: string | null;
  633. color: string | null;
  634. status: string;
  635. target_count: number | null; // Target number of plates/print jobs
  636. target_parts_count: number | null; // Target number of parts/objects
  637. budget: number | null;
  638. created_at: string;
  639. archive_count: number; // Number of print jobs (plates)
  640. total_items: number; // Sum of quantities (total items printed, including failed)
  641. completed_count: number; // Sum of quantities for completed prints only (parts)
  642. failed_count: number; // Sum of quantities for failed prints
  643. queue_count: number;
  644. progress_percent: number | null; // Plates progress
  645. archives: ArchivePreview[];
  646. url: string | null; // #1155
  647. cover_image_filename: string | null; // #1155
  648. }
  649. export interface ProjectCreate {
  650. name: string;
  651. description?: string;
  652. color?: string;
  653. target_count?: number;
  654. target_parts_count?: number;
  655. notes?: string;
  656. tags?: string;
  657. due_date?: string;
  658. priority?: string;
  659. budget?: number | null;
  660. parent_id?: number;
  661. url?: string | null; // #1155
  662. }
  663. export interface ProjectUpdate {
  664. name?: string;
  665. description?: string;
  666. color?: string;
  667. status?: string;
  668. target_count?: number;
  669. target_parts_count?: number;
  670. notes?: string;
  671. tags?: string;
  672. due_date?: string;
  673. priority?: string;
  674. budget?: number | null;
  675. parent_id?: number;
  676. url?: string | null; // #1155 — explicit null clears the URL
  677. }
  678. // BOM Types - Tracks sourced/purchased parts (hardware, electronics, etc.)
  679. export interface BOMItem {
  680. id: number;
  681. project_id: number;
  682. name: string;
  683. quantity_needed: number;
  684. quantity_acquired: number;
  685. unit_price: number | null;
  686. sourcing_url: string | null;
  687. archive_id: number | null;
  688. archive_name: string | null;
  689. stl_filename: string | null;
  690. remarks: string | null;
  691. sort_order: number;
  692. is_complete: boolean;
  693. created_at: string;
  694. updated_at: string;
  695. }
  696. export interface BOMItemCreate {
  697. name: string;
  698. quantity_needed?: number;
  699. unit_price?: number;
  700. sourcing_url?: string;
  701. archive_id?: number;
  702. stl_filename?: string;
  703. remarks?: string;
  704. }
  705. export interface BOMItemUpdate {
  706. name?: string;
  707. quantity_needed?: number;
  708. quantity_acquired?: number;
  709. unit_price?: number;
  710. sourcing_url?: string;
  711. archive_id?: number;
  712. stl_filename?: string;
  713. remarks?: string;
  714. }
  715. // Project Export/Import Types
  716. export interface BOMItemExport {
  717. name: string;
  718. quantity_needed: number;
  719. quantity_acquired: number;
  720. unit_price: number | null;
  721. sourcing_url: string | null;
  722. stl_filename: string | null;
  723. remarks: string | null;
  724. }
  725. export interface LinkedFolderExport {
  726. name: string;
  727. }
  728. export interface ProjectExport {
  729. name: string;
  730. description: string | null;
  731. color: string | null;
  732. status: string;
  733. target_count: number | null;
  734. target_parts_count: number | null;
  735. notes: string | null;
  736. tags: string | null;
  737. due_date: string | null;
  738. priority: string;
  739. budget: number | null;
  740. bom_items: BOMItemExport[];
  741. linked_folders: LinkedFolderExport[];
  742. }
  743. export interface ProjectImport {
  744. name: string;
  745. description?: string;
  746. color?: string;
  747. status?: string;
  748. target_count?: number;
  749. target_parts_count?: number;
  750. notes?: string;
  751. tags?: string;
  752. due_date?: string;
  753. priority?: string;
  754. budget?: number | null;
  755. bom_items?: BOMItemExport[];
  756. linked_folders?: LinkedFolderExport[];
  757. }
  758. // Timeline Types
  759. export interface TimelineEvent {
  760. event_type: string;
  761. timestamp: string;
  762. title: string;
  763. description: string | null;
  764. metadata: Record<string, unknown> | null;
  765. }
  766. // API Key types
  767. export interface APIKey {
  768. id: number;
  769. name: string;
  770. key_prefix: string;
  771. can_queue: boolean;
  772. can_control_printer: boolean;
  773. can_read_status: boolean;
  774. printer_ids: number[] | null;
  775. enabled: boolean;
  776. last_used: string | null;
  777. created_at: string;
  778. expires_at: string | null;
  779. }
  780. export interface APIKeyCreate {
  781. name: string;
  782. can_queue?: boolean;
  783. can_control_printer?: boolean;
  784. can_read_status?: boolean;
  785. printer_ids?: number[] | null;
  786. expires_at?: string | null;
  787. }
  788. export interface APIKeyCreateResponse extends APIKey {
  789. key: string; // Full key, only shown on creation
  790. }
  791. export interface APIKeyUpdate {
  792. name?: string;
  793. can_queue?: boolean;
  794. can_control_printer?: boolean;
  795. can_read_status?: boolean;
  796. printer_ids?: number[] | null;
  797. enabled?: boolean;
  798. expires_at?: string | null;
  799. }
  800. // Settings types
  801. export interface AppSettings {
  802. auto_archive: boolean;
  803. save_thumbnails: boolean;
  804. capture_finish_photo: boolean;
  805. default_filament_cost: number;
  806. currency: string;
  807. energy_cost_per_kwh: number;
  808. energy_tracking_mode: 'print' | 'total';
  809. check_updates: boolean;
  810. check_printer_firmware: boolean;
  811. include_beta_updates: boolean;
  812. language: string;
  813. notification_language: string;
  814. // AMS threshold settings
  815. ams_humidity_good: number; // <= this is green
  816. ams_humidity_fair: number; // <= this is orange, > is red
  817. ams_temp_good: number; // <= this is green/blue
  818. ams_temp_fair: number; // <= this is orange, > is red
  819. ams_history_retention_days: number; // days to keep AMS sensor history
  820. // Queue auto-drying settings
  821. queue_drying_enabled: boolean; // Auto-dry AMS between queued prints
  822. queue_drying_block: boolean; // Block queue until drying completes
  823. ambient_drying_enabled: boolean; // Auto-dry idle printers based on humidity regardless of queue
  824. drying_presets: string; // JSON blob of drying presets per filament type
  825. gcode_snippets: string; // JSON: per-model G-code injection snippets
  826. // Scheduled local backup
  827. local_backup_enabled: boolean;
  828. local_backup_schedule: string;
  829. local_backup_time: string;
  830. local_backup_retention: number;
  831. local_backup_path: string;
  832. // Print modal settings
  833. per_printer_mapping_expanded: boolean; // Whether custom mapping is expanded by default in print modal
  834. // Date/time format settings
  835. date_format: 'system' | 'us' | 'eu' | 'iso';
  836. time_format: 'system' | '12h' | '24h';
  837. // Filament tracking
  838. disable_filament_warnings: boolean; // Disable filament warnings (print insufficiency and assignment mismatch)
  839. prefer_lowest_filament: boolean; // When multiple spools match, prefer lowest remaining filament
  840. // Default printer
  841. default_printer_id: number | null;
  842. // Dark mode theme settings
  843. dark_style: 'classic' | 'glow' | 'vibrant';
  844. dark_background: 'neutral' | 'warm' | 'cool' | 'oled' | 'slate' | 'forest';
  845. dark_accent: 'green' | 'teal' | 'blue' | 'orange' | 'purple' | 'red';
  846. // Light mode theme settings
  847. light_style: 'classic' | 'glow' | 'vibrant';
  848. light_background: 'neutral' | 'warm' | 'cool';
  849. light_accent: 'green' | 'teal' | 'blue' | 'orange' | 'purple' | 'red';
  850. // FTP retry settings
  851. ftp_retry_enabled: boolean;
  852. ftp_retry_count: number;
  853. ftp_retry_delay: number;
  854. ftp_timeout: number;
  855. // MQTT relay settings
  856. mqtt_enabled: boolean;
  857. mqtt_broker: string;
  858. mqtt_port: number;
  859. mqtt_username: string;
  860. mqtt_password: string;
  861. mqtt_topic_prefix: string;
  862. mqtt_use_tls: boolean;
  863. // External URL for notifications
  864. external_url: string;
  865. // Home Assistant integration
  866. ha_enabled: boolean;
  867. ha_url: string;
  868. ha_token: string;
  869. ha_url_from_env: boolean;
  870. ha_token_from_env: boolean;
  871. ha_env_managed: boolean;
  872. // File Manager / Library settings
  873. library_archive_mode: 'always' | 'never' | 'ask';
  874. library_disk_warning_gb: number;
  875. // Camera view settings
  876. camera_view_mode: 'window' | 'embedded';
  877. // Preferred slicer
  878. preferred_slicer: 'bambu_studio' | 'orcaslicer';
  879. // Use the slicer-API sidecar for slicing (in-app modal) vs desktop URI scheme
  880. use_slicer_api: boolean;
  881. // Per-install sidecar URLs. Empty string falls back to the env defaults.
  882. orcaslicer_api_url: string;
  883. bambu_studio_api_url: string;
  884. // Prometheus metrics
  885. prometheus_enabled: boolean;
  886. prometheus_token: string;
  887. // Bed cooled threshold
  888. bed_cooled_threshold: number;
  889. // Inventory low stock threshold
  890. low_stock_threshold: number;
  891. // User email notifications toggle
  892. user_notifications_enabled: boolean;
  893. // Default print options
  894. default_bed_levelling: boolean;
  895. default_flow_cali: boolean;
  896. default_vibration_cali: boolean;
  897. default_layer_inspect: boolean;
  898. default_timelapse: boolean;
  899. // Staggered batch start defaults
  900. stagger_group_size: number;
  901. stagger_interval_minutes: number;
  902. // Plate-clear confirmation
  903. require_plate_clear: boolean;
  904. // Shortest job first scheduling
  905. queue_shortest_first: boolean;
  906. // Default sidebar order (admin-set for all users)
  907. default_sidebar_order: string;
  908. // LDAP authentication
  909. ldap_enabled: boolean;
  910. ldap_server_url: string;
  911. ldap_bind_dn: string;
  912. ldap_bind_password: string;
  913. ldap_search_base: string;
  914. ldap_user_filter: string;
  915. ldap_security: string;
  916. ldap_group_mapping: string;
  917. ldap_auto_provision: boolean;
  918. ldap_default_group: string;
  919. obico_enabled: boolean;
  920. obico_ml_url: string;
  921. obico_sensitivity: 'low' | 'medium' | 'high';
  922. obico_action: 'notify' | 'pause' | 'pause_and_off';
  923. obico_poll_interval: number;
  924. obico_enabled_printers: string;
  925. }
  926. export type AppSettingsUpdate = Partial<AppSettings>;
  927. // MQTT relay status
  928. export interface MQTTStatus {
  929. enabled: boolean;
  930. connected: boolean;
  931. broker: string;
  932. port: number;
  933. topic_prefix: string;
  934. }
  935. // Cloud types
  936. export interface CloudAuthStatus {
  937. is_authenticated: boolean;
  938. email: string | null;
  939. region?: 'global' | 'china' | null;
  940. }
  941. export interface CloudLoginResponse {
  942. success: boolean;
  943. needs_verification: boolean;
  944. message: string;
  945. verification_type?: 'email' | 'totp' | null;
  946. tfa_key?: string | null;
  947. }
  948. // MakerWorld integration. Full metadata/instance shapes come back as
  949. // Record<string, unknown> — MakerWorld's API adds fields over time, so we
  950. // pass them through verbatim rather than maintaining a brittle mirror.
  951. export interface MakerworldStatus {
  952. has_cloud_token: boolean;
  953. can_download: boolean;
  954. }
  955. export interface MakerworldResolvedModel {
  956. model_id: number;
  957. profile_id: number | null;
  958. design: Record<string, unknown>;
  959. instances: Array<Record<string, unknown>>;
  960. already_imported_library_ids: number[];
  961. }
  962. export interface MakerworldImportResponse {
  963. library_file_id: number;
  964. filename: string;
  965. folder_id: number | null;
  966. profile_id: number | null;
  967. was_existing: boolean;
  968. }
  969. export interface MakerworldRecentImport {
  970. library_file_id: number;
  971. filename: string;
  972. folder_id: number | null;
  973. thumbnail_path: string | null;
  974. source_url: string | null;
  975. created_at: string;
  976. }
  977. export interface SlicerSetting {
  978. setting_id: string;
  979. name: string;
  980. type: string;
  981. version: string | null;
  982. user_id: string | null;
  983. updated_time: string | null;
  984. is_custom: boolean;
  985. }
  986. export interface SpoolCatalogEntry {
  987. id: number;
  988. name: string;
  989. weight: number;
  990. is_default: boolean;
  991. }
  992. export interface ColorCatalogEntry {
  993. id: number;
  994. manufacturer: string;
  995. color_name: string;
  996. hex_color: string;
  997. material: string | null;
  998. is_default: boolean;
  999. // #1154: optional multi-colour gradient stops + visual effect.
  1000. extra_colors?: string | null;
  1001. effect_type?: string | null;
  1002. }
  1003. export interface ColorLookupResult {
  1004. found: boolean;
  1005. hex_color: string | null;
  1006. material: string | null;
  1007. }
  1008. export interface SlicerSettingsResponse {
  1009. filament: SlicerSetting[];
  1010. printer: SlicerSetting[];
  1011. process: SlicerSetting[];
  1012. }
  1013. export interface SlicerSettingDetail {
  1014. message?: string | null;
  1015. code?: string | null;
  1016. error?: string | null;
  1017. public: boolean;
  1018. version?: string | null;
  1019. type: string;
  1020. name: string;
  1021. update_time?: string | null;
  1022. nickname?: string | null;
  1023. base_id?: string | null;
  1024. setting: Record<string, unknown>;
  1025. filament_id?: string | null;
  1026. setting_id?: string | null;
  1027. }
  1028. export interface SlicerSettingCreate {
  1029. type: string; // 'filament', 'print', or 'printer'
  1030. name: string;
  1031. base_id: string;
  1032. setting: Record<string, unknown>;
  1033. }
  1034. export interface SlicerSettingUpdate {
  1035. name?: string;
  1036. setting?: Record<string, unknown>;
  1037. }
  1038. export interface SlicerSettingDeleteResponse {
  1039. success: boolean;
  1040. message: string;
  1041. }
  1042. // Built-in filament fallback (static table from backend)
  1043. export interface BuiltinFilament {
  1044. filament_id: string;
  1045. name: string;
  1046. }
  1047. // Slice request/response — POST /library/files/{id}/slice and /archives/{id}/slice
  1048. //
  1049. // Two preset shapes are accepted per slot:
  1050. // - Legacy bare integer ids (`*_preset_id`) — pre-cloud-tier clients.
  1051. // - Source-aware refs (`*_preset: PresetRef`) — new SliceModal that picks
  1052. // across cloud / local / standard tiers. Source-aware refs win when both
  1053. // are present in the same payload.
  1054. export type PresetSource = 'cloud' | 'local' | 'standard';
  1055. export interface PresetRef {
  1056. source: PresetSource;
  1057. id: string;
  1058. }
  1059. export interface SliceRequest {
  1060. printer_preset_id?: number;
  1061. process_preset_id?: number;
  1062. filament_preset_id?: number;
  1063. printer_preset?: PresetRef;
  1064. process_preset?: PresetRef;
  1065. filament_preset?: PresetRef;
  1066. // Multi-color: one PresetRef per plate slot, in plate order. Always
  1067. // preferred over the singular `filament_preset` when both are sent; the
  1068. // backend validator promotes a singular into a one-element list when this
  1069. // is omitted, so legacy single-color clients keep working unchanged.
  1070. filament_presets?: PresetRef[];
  1071. plate?: number;
  1072. export_3mf?: boolean;
  1073. }
  1074. // GET /api/v1/slicer/presets — unified listing across cloud / local / standard.
  1075. export type SlicerCloudStatus = 'ok' | 'not_authenticated' | 'expired' | 'unreachable';
  1076. export interface UnifiedPreset {
  1077. id: string;
  1078. name: string;
  1079. source: PresetSource;
  1080. // Populated for the filament slot only — used by the SliceModal multi-color
  1081. // pre-pick to score presets against each plate slot's required (type,
  1082. // colour). Optional because the bundled / standard tier rarely carries a
  1083. // colour (colour is a runtime spool attribute on Bambu) and older API
  1084. // responses pre-date these fields entirely.
  1085. filament_type?: string | null;
  1086. filament_colour?: string | null;
  1087. }
  1088. export interface UnifiedPresetsBySlot {
  1089. printer: UnifiedPreset[];
  1090. process: UnifiedPreset[];
  1091. filament: UnifiedPreset[];
  1092. }
  1093. export interface UnifiedPresetsResponse {
  1094. cloud: UnifiedPresetsBySlot;
  1095. local: UnifiedPresetsBySlot;
  1096. standard: UnifiedPresetsBySlot;
  1097. cloud_status: SlicerCloudStatus;
  1098. }
  1099. export interface SliceResponse {
  1100. library_file_id: number;
  1101. name: string;
  1102. print_time_seconds: number;
  1103. filament_used_g: number;
  1104. filament_used_mm: number;
  1105. used_embedded_settings: boolean;
  1106. }
  1107. export interface SliceArchiveResponse {
  1108. archive_id: number;
  1109. name: string;
  1110. print_time_seconds: number;
  1111. filament_used_g: number;
  1112. filament_used_mm: number;
  1113. used_embedded_settings: boolean;
  1114. }
  1115. // Background slice-job lifecycle. POST /slice returns 202 + this shape;
  1116. // the frontend polls /slice-jobs/{id} until status is terminal.
  1117. export type SliceJobStatus = 'pending' | 'running' | 'completed' | 'failed';
  1118. export interface SliceJobEnqueueResponse {
  1119. job_id: number;
  1120. status: SliceJobStatus;
  1121. status_url: string;
  1122. }
  1123. export interface SliceJobProgress {
  1124. /** Stage label emitted by the slicer ("Generating G-code", "Slicing finished"). */
  1125. stage: string;
  1126. total_percent: number;
  1127. plate_percent: number;
  1128. /** 1-indexed plate position; 0 means "all plates" / final completion. */
  1129. plate_index: number;
  1130. plate_count: number;
  1131. updated_at: number;
  1132. }
  1133. export interface SliceJobState {
  1134. job_id: number;
  1135. status: SliceJobStatus;
  1136. kind: 'library_file' | 'archive';
  1137. source_id: number;
  1138. source_name: string;
  1139. created_at: string;
  1140. started_at: string | null;
  1141. completed_at: string | null;
  1142. /** Live progress fed by the sidecar's --pipe channel; null until the
  1143. * slicer emits its first frame (early "Initializing" phase) or when
  1144. * the sidecar doesn't support progress. */
  1145. progress: SliceJobProgress | null;
  1146. result?: SliceResponse | SliceArchiveResponse;
  1147. error_status?: number;
  1148. error_detail?: string;
  1149. }
  1150. // Local preset types (OrcaSlicer imports)
  1151. export interface LocalPreset {
  1152. id: number;
  1153. name: string;
  1154. preset_type: string;
  1155. source: string;
  1156. filament_type: string | null;
  1157. filament_vendor: string | null;
  1158. nozzle_temp_min: number | null;
  1159. nozzle_temp_max: number | null;
  1160. pressure_advance: string | null;
  1161. default_filament_colour: string | null;
  1162. filament_cost: string | null;
  1163. filament_density: string | null;
  1164. compatible_printers: string | null;
  1165. inherits: string | null;
  1166. version: string | null;
  1167. created_at: string;
  1168. updated_at: string;
  1169. }
  1170. export interface LocalPresetDetail extends LocalPreset {
  1171. setting: Record<string, unknown>;
  1172. }
  1173. export interface LocalPresetsResponse {
  1174. filament: LocalPreset[];
  1175. printer: LocalPreset[];
  1176. process: LocalPreset[];
  1177. }
  1178. export interface ImportResponse {
  1179. success: boolean;
  1180. imported: number;
  1181. skipped: number;
  1182. errors: string[];
  1183. }
  1184. export interface FieldOption {
  1185. value: string;
  1186. label: string;
  1187. }
  1188. export interface FieldDefinition {
  1189. key: string;
  1190. label: string;
  1191. type: 'text' | 'number' | 'boolean' | 'select';
  1192. category: string;
  1193. description?: string;
  1194. options?: FieldOption[];
  1195. unit?: string;
  1196. min?: number;
  1197. max?: number;
  1198. step?: number;
  1199. }
  1200. export interface FieldDefinitionsResponse {
  1201. version: string;
  1202. description: string;
  1203. fields: FieldDefinition[];
  1204. }
  1205. export interface CloudDevice {
  1206. dev_id: string;
  1207. name: string;
  1208. dev_model_name: string | null;
  1209. dev_product_name: string | null;
  1210. online: boolean;
  1211. }
  1212. // Smart Plug types
  1213. export interface SmartPlug {
  1214. id: number;
  1215. name: string;
  1216. plug_type: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  1217. ip_address: string | null; // Required for Tasmota
  1218. ha_entity_id: string | null; // Required for Home Assistant (e.g., "switch.printer_plug", "script.turn_on_printer")
  1219. // Home Assistant energy sensor entities (optional)
  1220. ha_power_entity: string | null;
  1221. ha_energy_today_entity: string | null;
  1222. ha_energy_total_entity: string | null;
  1223. // MQTT fields (required when plug_type="mqtt")
  1224. // Legacy field - kept for backward compatibility
  1225. mqtt_topic: string | null; // Deprecated, use mqtt_power_topic
  1226. mqtt_multiplier: number; // Deprecated, use mqtt_power_multiplier
  1227. // Power monitoring
  1228. mqtt_power_topic: string | null; // Topic for power data
  1229. mqtt_power_path: string | null; // e.g., "power_l1" or "data.power"
  1230. mqtt_power_multiplier: number; // Unit conversion for power
  1231. // Energy monitoring
  1232. mqtt_energy_topic: string | null; // Topic for energy data
  1233. mqtt_energy_path: string | null; // e.g., "energy_l1"
  1234. mqtt_energy_multiplier: number; // Unit conversion for energy
  1235. // State monitoring
  1236. mqtt_state_topic: string | null; // Topic for state data
  1237. mqtt_state_path: string | null; // e.g., "state_l1" for ON/OFF
  1238. mqtt_state_on_value: string | null; // What value means "ON" (e.g., "ON", "true", "1")
  1239. // REST/Webhook fields (required when plug_type="rest")
  1240. rest_on_url: string | null;
  1241. rest_on_body: string | null;
  1242. rest_off_url: string | null;
  1243. rest_off_body: string | null;
  1244. rest_method: string | null;
  1245. rest_headers: string | null;
  1246. rest_status_url: string | null;
  1247. rest_status_path: string | null;
  1248. rest_status_on_value: string | null;
  1249. rest_power_url: string | null;
  1250. rest_power_path: string | null;
  1251. rest_power_multiplier: number;
  1252. rest_energy_url: string | null;
  1253. rest_energy_path: string | null;
  1254. rest_energy_multiplier: number;
  1255. printer_id: number | null;
  1256. enabled: boolean;
  1257. auto_on: boolean;
  1258. auto_off: boolean;
  1259. auto_off_persistent: boolean;
  1260. off_delay_mode: 'time' | 'temperature';
  1261. off_delay_minutes: number;
  1262. off_temp_threshold: number;
  1263. username: string | null;
  1264. password: string | null;
  1265. // Power alerts
  1266. power_alert_enabled: boolean;
  1267. power_alert_high: number | null;
  1268. power_alert_low: number | null;
  1269. power_alert_last_triggered: string | null;
  1270. // Schedule
  1271. schedule_enabled: boolean;
  1272. schedule_on_time: string | null;
  1273. schedule_off_time: string | null;
  1274. // Visibility options
  1275. show_in_switchbar: boolean;
  1276. show_on_printer_card: boolean; // For scripts: show on printer card
  1277. // Status
  1278. last_state: string | null;
  1279. last_checked: string | null;
  1280. auto_off_executed: boolean; // True when auto-off was triggered after print
  1281. created_at: string;
  1282. updated_at: string;
  1283. }
  1284. export interface SmartPlugCreate {
  1285. name: string;
  1286. plug_type?: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  1287. ip_address?: string | null; // Required for Tasmota
  1288. ha_entity_id?: string | null; // Required for Home Assistant
  1289. // Home Assistant energy sensor entities (optional)
  1290. ha_power_entity?: string | null;
  1291. ha_energy_today_entity?: string | null;
  1292. ha_energy_total_entity?: string | null;
  1293. // MQTT fields (required when plug_type="mqtt")
  1294. // Legacy fields - kept for backward compatibility
  1295. mqtt_topic?: string | null;
  1296. mqtt_multiplier?: number;
  1297. // Power monitoring
  1298. mqtt_power_topic?: string | null;
  1299. mqtt_power_path?: string | null;
  1300. mqtt_power_multiplier?: number;
  1301. // Energy monitoring
  1302. mqtt_energy_topic?: string | null;
  1303. mqtt_energy_path?: string | null;
  1304. mqtt_energy_multiplier?: number;
  1305. // State monitoring
  1306. mqtt_state_topic?: string | null;
  1307. mqtt_state_path?: string | null;
  1308. mqtt_state_on_value?: string | null;
  1309. // REST fields
  1310. rest_on_url?: string | null;
  1311. rest_on_body?: string | null;
  1312. rest_off_url?: string | null;
  1313. rest_off_body?: string | null;
  1314. rest_method?: string | null;
  1315. rest_headers?: string | null;
  1316. rest_status_url?: string | null;
  1317. rest_status_path?: string | null;
  1318. rest_status_on_value?: string | null;
  1319. rest_power_url?: string | null;
  1320. rest_power_path?: string | null;
  1321. rest_power_multiplier?: number;
  1322. rest_energy_url?: string | null;
  1323. rest_energy_path?: string | null;
  1324. rest_energy_multiplier?: number;
  1325. printer_id?: number | null;
  1326. enabled?: boolean;
  1327. auto_on?: boolean;
  1328. auto_off?: boolean;
  1329. auto_off_persistent?: boolean;
  1330. off_delay_mode?: 'time' | 'temperature';
  1331. off_delay_minutes?: number;
  1332. off_temp_threshold?: number;
  1333. username?: string | null;
  1334. password?: string | null;
  1335. // Power alerts
  1336. power_alert_enabled?: boolean;
  1337. power_alert_high?: number | null;
  1338. power_alert_low?: number | null;
  1339. // Schedule
  1340. schedule_enabled?: boolean;
  1341. schedule_on_time?: string | null;
  1342. schedule_off_time?: string | null;
  1343. // Visibility options
  1344. show_in_switchbar?: boolean;
  1345. show_on_printer_card?: boolean;
  1346. }
  1347. export interface SmartPlugUpdate {
  1348. name?: string;
  1349. plug_type?: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  1350. ip_address?: string | null;
  1351. ha_entity_id?: string | null;
  1352. // Home Assistant energy sensor entities (optional)
  1353. ha_power_entity?: string | null;
  1354. ha_energy_today_entity?: string | null;
  1355. ha_energy_total_entity?: string | null;
  1356. // MQTT fields (legacy)
  1357. mqtt_topic?: string | null;
  1358. mqtt_multiplier?: number;
  1359. // MQTT power fields
  1360. mqtt_power_topic?: string | null;
  1361. mqtt_power_path?: string | null;
  1362. mqtt_power_multiplier?: number;
  1363. // MQTT energy fields
  1364. mqtt_energy_topic?: string | null;
  1365. mqtt_energy_path?: string | null;
  1366. mqtt_energy_multiplier?: number;
  1367. // MQTT state fields
  1368. mqtt_state_topic?: string | null;
  1369. mqtt_state_path?: string | null;
  1370. mqtt_state_on_value?: string | null;
  1371. // REST fields
  1372. rest_on_url?: string | null;
  1373. rest_on_body?: string | null;
  1374. rest_off_url?: string | null;
  1375. rest_off_body?: string | null;
  1376. rest_method?: string | null;
  1377. rest_headers?: string | null;
  1378. rest_status_url?: string | null;
  1379. rest_status_path?: string | null;
  1380. rest_status_on_value?: string | null;
  1381. rest_power_url?: string | null;
  1382. rest_power_path?: string | null;
  1383. rest_power_multiplier?: number;
  1384. rest_energy_url?: string | null;
  1385. rest_energy_path?: string | null;
  1386. rest_energy_multiplier?: number;
  1387. printer_id?: number | null;
  1388. enabled?: boolean;
  1389. auto_on?: boolean;
  1390. auto_off?: boolean;
  1391. auto_off_persistent?: boolean;
  1392. off_delay_mode?: 'time' | 'temperature';
  1393. off_delay_minutes?: number;
  1394. off_temp_threshold?: number;
  1395. username?: string | null;
  1396. password?: string | null;
  1397. // Power alerts
  1398. power_alert_enabled?: boolean;
  1399. power_alert_high?: number | null;
  1400. power_alert_low?: number | null;
  1401. // Schedule
  1402. schedule_enabled?: boolean;
  1403. schedule_on_time?: string | null;
  1404. schedule_off_time?: string | null;
  1405. // Visibility options
  1406. show_in_switchbar?: boolean;
  1407. show_on_printer_card?: boolean;
  1408. }
  1409. // Home Assistant entity for smart plug selection
  1410. export interface HAEntity {
  1411. entity_id: string;
  1412. friendly_name: string;
  1413. state: string | null;
  1414. domain: string; // "switch", "light", "input_boolean", "script"
  1415. }
  1416. // Home Assistant sensor entity for energy monitoring
  1417. export interface HASensorEntity {
  1418. entity_id: string;
  1419. friendly_name: string;
  1420. state: string | null;
  1421. unit_of_measurement: string | null; // "W", "kW", "kWh", "Wh"
  1422. }
  1423. export interface HATestConnectionResult {
  1424. success: boolean;
  1425. message: string | null;
  1426. error: string | null;
  1427. }
  1428. export interface SmartPlugEnergy {
  1429. power: number | null; // Current watts
  1430. voltage: number | null; // Volts
  1431. current: number | null; // Amps
  1432. today: number | null; // kWh used today
  1433. yesterday: number | null; // kWh used yesterday
  1434. total: number | null; // Total kWh
  1435. factor: number | null; // Power factor (0-1)
  1436. apparent_power: number | null; // VA
  1437. reactive_power: number | null; // VAr
  1438. }
  1439. export interface SmartPlugStatus {
  1440. state: string | null;
  1441. reachable: boolean;
  1442. device_name: string | null;
  1443. energy: SmartPlugEnergy | null;
  1444. }
  1445. export interface SmartPlugTestResult {
  1446. success: boolean;
  1447. state: string | null;
  1448. device_name: string | null;
  1449. }
  1450. // Tasmota Discovery types
  1451. export interface TasmotaScanStatus {
  1452. running: boolean;
  1453. scanned: number;
  1454. total: number;
  1455. }
  1456. export interface DiscoveredTasmotaDevice {
  1457. ip_address: string;
  1458. name: string;
  1459. module: number | null;
  1460. state: string | null;
  1461. discovered_at: string | null;
  1462. }
  1463. // Print Queue types
  1464. export interface PrintQueueItem {
  1465. id: number;
  1466. printer_id: number | null; // null = unassigned
  1467. target_model: string | null; // Target printer model for model-based assignment
  1468. target_location: string | null; // Target location filter for model-based assignment
  1469. required_filament_types: string[] | null; // Required filament types for model-based assignment
  1470. waiting_reason: string | null; // Why a model-based job hasn't started yet
  1471. // Either archive_id OR library_file_id must be set (archive created at print start)
  1472. archive_id: number | null;
  1473. library_file_id: number | null;
  1474. position: number;
  1475. scheduled_time: string | null;
  1476. require_previous_success: boolean;
  1477. auto_off_after: boolean;
  1478. manual_start: boolean; // Requires manual trigger to start (staged)
  1479. ams_mapping: number[] | null; // AMS slot mapping for multi-color prints
  1480. filament_overrides: Array<{ slot_id: number; type: string; color: string; color_name?: string; force_color_match?: boolean }> | null; // Filament overrides for model-based assignment
  1481. plate_id: number | null; // Plate ID for multi-plate 3MF files
  1482. // Print options
  1483. bed_levelling: boolean;
  1484. flow_cali: boolean;
  1485. vibration_cali: boolean;
  1486. layer_inspect: boolean;
  1487. timelapse: boolean;
  1488. use_ams: boolean;
  1489. status: 'pending' | 'printing' | 'completed' | 'failed' | 'skipped' | 'cancelled';
  1490. started_at: string | null;
  1491. completed_at: string | null;
  1492. error_message: string | null;
  1493. created_at: string;
  1494. archive_name?: string | null;
  1495. archive_thumbnail?: string | null;
  1496. library_file_name?: string | null;
  1497. library_file_thumbnail?: string | null;
  1498. printer_name?: string | null;
  1499. print_time_seconds?: number | null; // Estimated print time from archive or library file
  1500. filament_used_grams?: number | null; // Estimated print weight from archive or library file
  1501. // User tracking (Issue #206)
  1502. created_by_id?: number | null;
  1503. created_by_username?: string | null;
  1504. // Batch grouping
  1505. batch_id?: number | null;
  1506. batch_name?: string | null;
  1507. // Shortest-job-first scheduling
  1508. been_jumped?: boolean;
  1509. // Auto-print G-code injection
  1510. gcode_injection?: boolean;
  1511. }
  1512. export interface PrintBatch {
  1513. id: number;
  1514. name: string;
  1515. archive_id: number | null;
  1516. library_file_id: number | null;
  1517. quantity: number;
  1518. status: string;
  1519. created_at: string;
  1520. created_by_id: number | null;
  1521. created_by_username: string | null;
  1522. pending_count: number;
  1523. printing_count: number;
  1524. completed_count: number;
  1525. failed_count: number;
  1526. cancelled_count: number;
  1527. }
  1528. export interface PrintQueueItemCreate {
  1529. printer_id?: number | null; // null = unassigned
  1530. target_model?: string | null; // Target printer model (mutually exclusive with printer_id)
  1531. target_location?: string | null; // Target location filter (only used with target_model)
  1532. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; force_color_match?: boolean }> | null;
  1533. archive_id?: number | null;
  1534. library_file_id?: number | null;
  1535. scheduled_time?: string | null;
  1536. require_previous_success?: boolean;
  1537. auto_off_after?: boolean;
  1538. manual_start?: boolean; // Requires manual trigger to start (staged)
  1539. ams_mapping?: number[] | null; // AMS slot mapping for multi-color prints
  1540. plate_id?: number | null; // Plate ID for multi-plate 3MF files
  1541. // Print options
  1542. bed_levelling?: boolean;
  1543. flow_cali?: boolean;
  1544. vibration_cali?: boolean;
  1545. layer_inspect?: boolean;
  1546. timelapse?: boolean;
  1547. use_ams?: boolean;
  1548. // Auto-print G-code injection
  1549. gcode_injection?: boolean;
  1550. // Batch: create multiple copies (creates a batch if > 1)
  1551. quantity?: number;
  1552. // Project to associate the resulting archive with
  1553. project_id?: number;
  1554. }
  1555. export interface PrintQueueItemUpdate {
  1556. printer_id?: number | null; // null = unassign
  1557. target_model?: string | null; // Target printer model (mutually exclusive with printer_id)
  1558. target_location?: string | null; // Target location filter (only used with target_model)
  1559. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; force_color_match?: boolean }> | null;
  1560. position?: number;
  1561. scheduled_time?: string | null;
  1562. require_previous_success?: boolean;
  1563. auto_off_after?: boolean;
  1564. manual_start?: boolean;
  1565. ams_mapping?: number[];
  1566. plate_id?: number | null; // Plate ID for multi-plate 3MF files
  1567. // Print options
  1568. bed_levelling?: boolean;
  1569. flow_cali?: boolean;
  1570. vibration_cali?: boolean;
  1571. layer_inspect?: boolean;
  1572. timelapse?: boolean;
  1573. use_ams?: boolean;
  1574. // Auto-print G-code injection
  1575. gcode_injection?: boolean;
  1576. }
  1577. export interface PrintQueueBulkUpdate {
  1578. item_ids: number[];
  1579. printer_id?: number | null;
  1580. scheduled_time?: string | null;
  1581. require_previous_success?: boolean;
  1582. auto_off_after?: boolean;
  1583. manual_start?: boolean;
  1584. // Print options
  1585. bed_levelling?: boolean;
  1586. flow_cali?: boolean;
  1587. vibration_cali?: boolean;
  1588. layer_inspect?: boolean;
  1589. timelapse?: boolean;
  1590. use_ams?: boolean;
  1591. // Auto-print G-code injection
  1592. gcode_injection?: boolean;
  1593. }
  1594. export interface PrintQueueBulkUpdateResponse {
  1595. updated_count: number;
  1596. skipped_count: number;
  1597. message: string;
  1598. }
  1599. // MQTT Logging types
  1600. export interface MQTTLogEntry {
  1601. timestamp: string;
  1602. topic: string;
  1603. direction: 'in' | 'out';
  1604. payload: Record<string, unknown>;
  1605. }
  1606. export interface MQTTLogsResponse {
  1607. logging_enabled: boolean;
  1608. logs: MQTTLogEntry[];
  1609. }
  1610. // K-Profile types
  1611. export interface KProfile {
  1612. slot_id: number;
  1613. extruder_id: number;
  1614. nozzle_id: string;
  1615. nozzle_diameter: string;
  1616. filament_id: string;
  1617. name: string;
  1618. k_value: string;
  1619. n_coef: string;
  1620. ams_id: number;
  1621. tray_id: number;
  1622. setting_id: string | null;
  1623. }
  1624. export interface KProfileCreate {
  1625. slot_id?: number; // Storage slot, 0 for new profiles
  1626. extruder_id?: number;
  1627. nozzle_id: string;
  1628. nozzle_diameter: string;
  1629. filament_id: string;
  1630. name: string;
  1631. k_value: string;
  1632. n_coef?: string;
  1633. ams_id?: number;
  1634. tray_id?: number;
  1635. setting_id?: string | null;
  1636. }
  1637. export interface KProfileDelete {
  1638. slot_id: number; // cali_idx - calibration index to delete
  1639. extruder_id: number;
  1640. nozzle_id: string; // e.g., "HH00-0.4"
  1641. nozzle_diameter: string; // e.g., "0.4"
  1642. filament_id: string; // Bambu filament identifier
  1643. setting_id?: string | null; // Setting ID (for X1C series)
  1644. }
  1645. export interface KProfilesResponse {
  1646. profiles: KProfile[];
  1647. nozzle_diameter: string;
  1648. }
  1649. export interface KProfileNote {
  1650. setting_id: string;
  1651. note: string;
  1652. }
  1653. export interface KProfileNotesResponse {
  1654. notes: Record<string, string>; // setting_id -> note
  1655. }
  1656. // Slot Preset Mapping
  1657. export interface SlotPresetMapping {
  1658. ams_id: number;
  1659. tray_id: number;
  1660. preset_id: string;
  1661. preset_name: string;
  1662. }
  1663. // Filament types
  1664. export interface Filament {
  1665. id: number;
  1666. name: string;
  1667. type: string; // PLA, PETG, ABS, etc.
  1668. brand: string | null;
  1669. color: string | null;
  1670. color_hex: string | null;
  1671. cost_per_kg: number;
  1672. spool_weight_g: number;
  1673. currency: string;
  1674. density: number | null;
  1675. print_temp_min: number | null;
  1676. print_temp_max: number | null;
  1677. bed_temp_min: number | null;
  1678. bed_temp_max: number | null;
  1679. created_at: string;
  1680. updated_at: string;
  1681. }
  1682. // Notification Provider types
  1683. export type ProviderType = 'callmebot' | 'ntfy' | 'pushover' | 'telegram' | 'email' | 'discord' | 'webhook' | 'homeassistant';
  1684. export interface NotificationProvider {
  1685. id: number;
  1686. name: string;
  1687. provider_type: ProviderType;
  1688. enabled: boolean;
  1689. config: Record<string, unknown>;
  1690. // Print lifecycle events
  1691. on_print_start: boolean;
  1692. on_print_complete: boolean;
  1693. on_print_failed: boolean;
  1694. on_print_stopped: boolean;
  1695. on_print_progress: boolean;
  1696. on_print_missing_spool_assignment: boolean;
  1697. // Printer status events
  1698. on_printer_offline: boolean;
  1699. on_printer_error: boolean;
  1700. on_filament_low: boolean;
  1701. on_maintenance_due: boolean;
  1702. // AMS environmental alarms (regular AMS)
  1703. on_ams_humidity_high: boolean;
  1704. on_ams_temperature_high: boolean;
  1705. // AMS-HT environmental alarms
  1706. on_ams_ht_humidity_high: boolean;
  1707. on_ams_ht_temperature_high: boolean;
  1708. // Build plate detection
  1709. on_plate_not_empty: boolean;
  1710. // Bed cooled
  1711. on_bed_cooled: boolean;
  1712. // First layer complete
  1713. on_first_layer_complete: boolean;
  1714. // Print queue events
  1715. on_queue_job_added: boolean;
  1716. on_queue_job_assigned: boolean;
  1717. on_queue_job_started: boolean;
  1718. on_queue_job_waiting: boolean;
  1719. on_queue_job_skipped: boolean;
  1720. on_queue_job_failed: boolean;
  1721. on_queue_completed: boolean;
  1722. // Quiet hours
  1723. quiet_hours_enabled: boolean;
  1724. quiet_hours_start: string | null;
  1725. quiet_hours_end: string | null;
  1726. // Daily digest
  1727. daily_digest_enabled: boolean;
  1728. daily_digest_time: string | null;
  1729. // Printer filter
  1730. printer_id: number | null;
  1731. // Status tracking
  1732. last_success: string | null;
  1733. last_error: string | null;
  1734. last_error_at: string | null;
  1735. // Timestamps
  1736. created_at: string;
  1737. updated_at: string;
  1738. }
  1739. export interface NotificationProviderCreate {
  1740. name: string;
  1741. provider_type: ProviderType;
  1742. enabled?: boolean;
  1743. config: Record<string, unknown>;
  1744. // Print lifecycle events
  1745. on_print_start?: boolean;
  1746. on_print_complete?: boolean;
  1747. on_print_failed?: boolean;
  1748. on_print_stopped?: boolean;
  1749. on_print_progress?: boolean;
  1750. on_print_missing_spool_assignment?: boolean;
  1751. // Printer status events
  1752. on_printer_offline?: boolean;
  1753. on_printer_error?: boolean;
  1754. on_filament_low?: boolean;
  1755. on_maintenance_due?: boolean;
  1756. // AMS environmental alarms (regular AMS)
  1757. on_ams_humidity_high?: boolean;
  1758. on_ams_temperature_high?: boolean;
  1759. // AMS-HT environmental alarms
  1760. on_ams_ht_humidity_high?: boolean;
  1761. on_ams_ht_temperature_high?: boolean;
  1762. // Build plate detection
  1763. on_plate_not_empty?: boolean;
  1764. // Bed cooled
  1765. on_bed_cooled?: boolean;
  1766. // First layer complete
  1767. on_first_layer_complete?: boolean;
  1768. // Print queue events
  1769. on_queue_job_added?: boolean;
  1770. on_queue_job_assigned?: boolean;
  1771. on_queue_job_started?: boolean;
  1772. on_queue_job_waiting?: boolean;
  1773. on_queue_job_skipped?: boolean;
  1774. on_queue_job_failed?: boolean;
  1775. on_queue_completed?: boolean;
  1776. // Quiet hours
  1777. quiet_hours_enabled?: boolean;
  1778. quiet_hours_start?: string | null;
  1779. quiet_hours_end?: string | null;
  1780. // Daily digest
  1781. daily_digest_enabled?: boolean;
  1782. daily_digest_time?: string | null;
  1783. // Printer filter
  1784. printer_id?: number | null;
  1785. }
  1786. export interface NotificationProviderUpdate {
  1787. name?: string;
  1788. provider_type?: ProviderType;
  1789. enabled?: boolean;
  1790. config?: Record<string, unknown>;
  1791. // Print lifecycle events
  1792. on_print_start?: boolean;
  1793. on_print_complete?: boolean;
  1794. on_print_failed?: boolean;
  1795. on_print_stopped?: boolean;
  1796. on_print_progress?: boolean;
  1797. on_print_missing_spool_assignment?: boolean;
  1798. // Printer status events
  1799. on_printer_offline?: boolean;
  1800. on_printer_error?: boolean;
  1801. on_filament_low?: boolean;
  1802. on_maintenance_due?: boolean;
  1803. // AMS environmental alarms (regular AMS)
  1804. on_ams_humidity_high?: boolean;
  1805. on_ams_temperature_high?: boolean;
  1806. // AMS-HT environmental alarms
  1807. on_ams_ht_humidity_high?: boolean;
  1808. on_ams_ht_temperature_high?: boolean;
  1809. // Build plate detection
  1810. on_plate_not_empty?: boolean;
  1811. // Bed cooled
  1812. on_bed_cooled?: boolean;
  1813. // First layer complete
  1814. on_first_layer_complete?: boolean;
  1815. // Print queue events
  1816. on_queue_job_added?: boolean;
  1817. on_queue_job_assigned?: boolean;
  1818. on_queue_job_started?: boolean;
  1819. on_queue_job_waiting?: boolean;
  1820. on_queue_job_skipped?: boolean;
  1821. on_queue_job_failed?: boolean;
  1822. on_queue_completed?: boolean;
  1823. // Quiet hours
  1824. quiet_hours_enabled?: boolean;
  1825. quiet_hours_start?: string | null;
  1826. quiet_hours_end?: string | null;
  1827. // Daily digest
  1828. daily_digest_enabled?: boolean;
  1829. daily_digest_time?: string | null;
  1830. // Printer filter
  1831. printer_id?: number | null;
  1832. }
  1833. // GitHub Backup types
  1834. export type ScheduleType = 'hourly' | 'daily' | 'weekly';
  1835. export interface GitHubBackupConfig {
  1836. id: number;
  1837. repository_url: string;
  1838. has_token: boolean;
  1839. branch: string;
  1840. schedule_enabled: boolean;
  1841. schedule_type: ScheduleType;
  1842. backup_kprofiles: boolean;
  1843. backup_cloud_profiles: boolean;
  1844. backup_settings: boolean;
  1845. backup_spools: boolean;
  1846. backup_archives: boolean;
  1847. enabled: boolean;
  1848. last_backup_at: string | null;
  1849. last_backup_status: string | null;
  1850. last_backup_message: string | null;
  1851. last_backup_commit_sha: string | null;
  1852. next_scheduled_run: string | null;
  1853. created_at: string;
  1854. updated_at: string;
  1855. }
  1856. export interface GitHubBackupConfigCreate {
  1857. repository_url: string;
  1858. access_token: string;
  1859. branch?: string;
  1860. schedule_enabled?: boolean;
  1861. schedule_type?: ScheduleType;
  1862. backup_kprofiles?: boolean;
  1863. backup_cloud_profiles?: boolean;
  1864. backup_settings?: boolean;
  1865. backup_spools?: boolean;
  1866. backup_archives?: boolean;
  1867. enabled?: boolean;
  1868. }
  1869. export interface GitHubBackupLog {
  1870. id: number;
  1871. config_id: number;
  1872. started_at: string;
  1873. completed_at: string | null;
  1874. status: string;
  1875. trigger: string;
  1876. commit_sha: string | null;
  1877. files_changed: number;
  1878. error_message: string | null;
  1879. }
  1880. export interface GitHubBackupStatus {
  1881. configured: boolean;
  1882. enabled: boolean;
  1883. is_running: boolean;
  1884. progress: string | null;
  1885. last_backup_at: string | null;
  1886. last_backup_status: string | null;
  1887. next_scheduled_run: string | null;
  1888. }
  1889. export interface LocalBackupStatus {
  1890. enabled: boolean;
  1891. schedule: string;
  1892. time: string;
  1893. retention: number;
  1894. path: string;
  1895. default_path: string;
  1896. is_running: boolean;
  1897. last_backup_at: string | null;
  1898. last_status: string | null;
  1899. last_message: string | null;
  1900. next_run: string | null;
  1901. }
  1902. export interface LocalBackupFile {
  1903. filename: string;
  1904. size: number;
  1905. created_at: string;
  1906. }
  1907. export interface ObicoDetectionEvent {
  1908. printer_id: number;
  1909. task_name: string;
  1910. timestamp: string;
  1911. current_p: number;
  1912. score: number;
  1913. class: 'safe' | 'warning' | 'failure';
  1914. detections: number;
  1915. }
  1916. export interface ObicoStatus {
  1917. is_running: boolean;
  1918. last_error: string | null;
  1919. per_printer: Record<string, { class: string; frame_count: number; score: number }>;
  1920. thresholds: { low: number; high: number };
  1921. history: ObicoDetectionEvent[];
  1922. enabled: boolean;
  1923. ml_url: string;
  1924. sensitivity: 'low' | 'medium' | 'high';
  1925. action: 'notify' | 'pause' | 'pause_and_off';
  1926. poll_interval: number;
  1927. external_url_configured: boolean;
  1928. }
  1929. export interface ObicoTestConnection {
  1930. ok: boolean;
  1931. status_code: number | null;
  1932. body: string | null;
  1933. error: string | null;
  1934. }
  1935. export interface GitHubTestConnectionResponse {
  1936. success: boolean;
  1937. message: string;
  1938. repo_name: string | null;
  1939. permissions: Record<string, boolean> | null;
  1940. }
  1941. export interface GitHubBackupTriggerResponse {
  1942. success: boolean;
  1943. message: string;
  1944. log_id: number | null;
  1945. commit_sha: string | null;
  1946. files_changed: number;
  1947. }
  1948. export interface NotificationTestRequest {
  1949. provider_type: ProviderType;
  1950. config: Record<string, unknown>;
  1951. }
  1952. export interface NotificationTestResponse {
  1953. success: boolean;
  1954. message: string;
  1955. }
  1956. export interface BackgroundDispatchResponse {
  1957. status: 'dispatched' | string;
  1958. printer_id: number;
  1959. archive_id?: number | null;
  1960. filename: string;
  1961. dispatch_job_id: number;
  1962. dispatch_position: number;
  1963. }
  1964. // Provider-specific config types for reference
  1965. export interface CallMeBotConfig {
  1966. phone: string;
  1967. apikey: string;
  1968. }
  1969. export interface NtfyConfig {
  1970. server?: string;
  1971. topic: string;
  1972. auth_token?: string | null;
  1973. }
  1974. export interface PushoverConfig {
  1975. user_key: string;
  1976. app_token: string;
  1977. priority?: number;
  1978. }
  1979. export interface TelegramConfig {
  1980. bot_token: string;
  1981. chat_id: string;
  1982. }
  1983. export interface EmailConfig {
  1984. smtp_server: string;
  1985. smtp_port?: number;
  1986. username: string;
  1987. password: string;
  1988. from_email: string;
  1989. to_email: string;
  1990. use_tls?: boolean;
  1991. }
  1992. // Notification Template types
  1993. export interface NotificationTemplate {
  1994. id: number;
  1995. event_type: string;
  1996. name: string;
  1997. title_template: string;
  1998. body_template: string;
  1999. is_default: boolean;
  2000. created_at: string;
  2001. updated_at: string;
  2002. }
  2003. export interface NotificationTemplateUpdate {
  2004. title_template?: string;
  2005. body_template?: string;
  2006. }
  2007. export interface EventVariablesResponse {
  2008. event_type: string;
  2009. event_name: string;
  2010. variables: string[];
  2011. }
  2012. export interface TemplatePreviewRequest {
  2013. event_type: string;
  2014. title_template: string;
  2015. body_template: string;
  2016. }
  2017. export interface TemplatePreviewResponse {
  2018. title: string;
  2019. body: string;
  2020. }
  2021. // Notification Log types
  2022. export interface NotificationLogEntry {
  2023. id: number;
  2024. provider_id: number;
  2025. provider_name: string | null;
  2026. provider_type: string | null;
  2027. event_type: string;
  2028. title: string;
  2029. message: string;
  2030. success: boolean;
  2031. error_message: string | null;
  2032. printer_id: number | null;
  2033. printer_name: string | null;
  2034. created_at: string;
  2035. }
  2036. export interface NotificationLogStats {
  2037. total: number;
  2038. success_count: number;
  2039. failure_count: number;
  2040. by_event_type: Record<string, number>;
  2041. by_provider: Record<string, number>;
  2042. }
  2043. // Spoolman types
  2044. export interface SpoolmanStatus {
  2045. enabled: boolean;
  2046. connected: boolean;
  2047. url: string | null;
  2048. }
  2049. export interface SkippedSpool {
  2050. location: string;
  2051. reason: string;
  2052. filament_type: string | null;
  2053. color: string | null;
  2054. }
  2055. export interface SpoolmanSyncResult {
  2056. success: boolean;
  2057. synced_count: number;
  2058. skipped_count: number;
  2059. skipped: SkippedSpool[];
  2060. errors: string[];
  2061. }
  2062. export interface UnlinkedSpool {
  2063. id: number;
  2064. filament_name: string | null;
  2065. filament_vendor: string | null;
  2066. filament_material: string | null;
  2067. filament_color_hex: string | null;
  2068. remaining_weight: number | null;
  2069. location: string | null;
  2070. }
  2071. export interface LinkedSpoolInfo {
  2072. id: number;
  2073. remaining_weight: number | null;
  2074. filament_weight: number | null;
  2075. }
  2076. export interface LinkedSpoolsMap {
  2077. linked: Record<string, LinkedSpoolInfo>; // tag (uppercase) -> spool info
  2078. }
  2079. // Inventory types
  2080. export interface InventorySpool {
  2081. id: number;
  2082. material: string;
  2083. subtype: string | null;
  2084. color_name: string | null;
  2085. rgba: string | null;
  2086. // Multi-colour gradient stops (#1154): comma-separated 6/8-char hex.
  2087. extra_colors: string | null;
  2088. // Visual effect overlay: sparkle | wood | marble | glow | matte.
  2089. effect_type: string | null;
  2090. brand: string | null;
  2091. label_weight: number;
  2092. core_weight: number;
  2093. core_weight_catalog_id: number | null;
  2094. weight_used: number;
  2095. slicer_filament: string | null;
  2096. slicer_filament_name: string | null;
  2097. nozzle_temp_min: number | null;
  2098. nozzle_temp_max: number | null;
  2099. note: string | null;
  2100. added_full: boolean | null;
  2101. last_used: string | null;
  2102. encode_time: string | null;
  2103. tag_uid: string | null;
  2104. tray_uuid: string | null;
  2105. data_origin: string | null;
  2106. tag_type: string | null;
  2107. archived_at: string | null;
  2108. created_at: string;
  2109. updated_at: string;
  2110. cost_per_kg: number | null;
  2111. last_scale_weight: number | null;
  2112. last_weighed_at: string | null;
  2113. // User-defined category + per-spool low-stock threshold override (#729).
  2114. category: string | null;
  2115. low_stock_threshold_pct: number | null;
  2116. k_profiles?: SpoolKProfile[];
  2117. }
  2118. export interface SpoolUsageRecord {
  2119. id: number;
  2120. spool_id: number;
  2121. printer_id: number | null;
  2122. print_name: string | null;
  2123. weight_used: number;
  2124. percent_used: number;
  2125. status: string;
  2126. cost: number | null;
  2127. created_at: string;
  2128. }
  2129. export interface SpoolKProfile {
  2130. id: number;
  2131. spool_id: number;
  2132. printer_id: number;
  2133. extruder: number;
  2134. nozzle_diameter: string;
  2135. nozzle_type: string | null;
  2136. k_value: number;
  2137. name: string | null;
  2138. cali_idx: number | null;
  2139. setting_id: string | null;
  2140. created_at: string;
  2141. }
  2142. export interface SpoolKProfileInput {
  2143. printer_id: number;
  2144. extruder?: number;
  2145. nozzle_diameter?: string;
  2146. nozzle_type?: string | null;
  2147. k_value: number;
  2148. name?: string | null;
  2149. cali_idx?: number | null;
  2150. setting_id?: string | null;
  2151. }
  2152. export interface SpoolAssignment {
  2153. id: number;
  2154. spool_id: number;
  2155. printer_id: number;
  2156. printer_name: string | null;
  2157. ams_id: number;
  2158. tray_id: number;
  2159. fingerprint_color: string | null;
  2160. fingerprint_type: string | null;
  2161. spool?: InventorySpool | null;
  2162. configured: boolean;
  2163. created_at: string;
  2164. ams_label?: string | null; // User-defined friendly name for the AMS unit
  2165. }
  2166. // Update types
  2167. export interface VersionInfo {
  2168. version: string;
  2169. repo: string;
  2170. }
  2171. export interface UpdateCheckResult {
  2172. update_available: boolean;
  2173. current_version: string;
  2174. latest_version: string | null;
  2175. release_name?: string;
  2176. release_notes?: string;
  2177. release_url?: string;
  2178. published_at?: string;
  2179. error?: string;
  2180. message?: string;
  2181. is_docker?: boolean;
  2182. update_method?: 'docker' | 'git';
  2183. }
  2184. export interface UpdateStatus {
  2185. status: 'idle' | 'checking' | 'downloading' | 'installing' | 'complete' | 'error';
  2186. progress: number;
  2187. message: string;
  2188. error: string | null;
  2189. }
  2190. // Maintenance types
  2191. export interface MaintenanceType {
  2192. id: number;
  2193. name: string;
  2194. description: string | null;
  2195. default_interval_hours: number;
  2196. interval_type: 'hours' | 'days'; // "hours" = print hours, "days" = calendar days
  2197. icon: string | null;
  2198. wiki_url: string | null; // Documentation link
  2199. is_system: boolean;
  2200. created_at: string;
  2201. }
  2202. export interface MaintenanceTypeCreate {
  2203. name: string;
  2204. description?: string | null;
  2205. default_interval_hours?: number;
  2206. interval_type?: 'hours' | 'days';
  2207. icon?: string | null;
  2208. wiki_url?: string | null;
  2209. }
  2210. export interface MaintenanceStatus {
  2211. id: number;
  2212. printer_id: number;
  2213. printer_name: string;
  2214. printer_model: string | null;
  2215. maintenance_type_id: number;
  2216. maintenance_type_name: string;
  2217. maintenance_type_icon: string | null;
  2218. maintenance_type_wiki_url: string | null; // Custom wiki URL from type
  2219. enabled: boolean;
  2220. interval_hours: number; // For hours type: print hours; for days type: number of days
  2221. interval_type: 'hours' | 'days';
  2222. current_hours: number;
  2223. hours_since_maintenance: number;
  2224. hours_until_due: number;
  2225. days_since_maintenance: number | null; // For days type
  2226. days_until_due: number | null; // For days type
  2227. is_due: boolean;
  2228. is_warning: boolean;
  2229. last_performed_at: string | null;
  2230. }
  2231. export interface PrinterMaintenanceOverview {
  2232. printer_id: number;
  2233. printer_name: string;
  2234. printer_model: string | null;
  2235. total_print_hours: number;
  2236. maintenance_items: MaintenanceStatus[];
  2237. due_count: number;
  2238. warning_count: number;
  2239. }
  2240. export interface MaintenanceHistory {
  2241. id: number;
  2242. printer_maintenance_id: number;
  2243. performed_at: string;
  2244. hours_at_maintenance: number;
  2245. notes: string | null;
  2246. }
  2247. export interface MaintenanceSummary {
  2248. total_due: number;
  2249. total_warning: number;
  2250. printers_with_issues: Array<{
  2251. printer_id: number;
  2252. printer_name: string;
  2253. due_count: number;
  2254. warning_count: number;
  2255. }>;
  2256. }
  2257. // External Links (sidebar)
  2258. export interface ExternalLink {
  2259. id: number;
  2260. name: string;
  2261. url: string;
  2262. icon: string;
  2263. open_in_new_tab: boolean;
  2264. custom_icon: string | null;
  2265. sort_order: number;
  2266. created_at: string;
  2267. updated_at: string;
  2268. }
  2269. export interface ExternalLinkCreate {
  2270. name: string;
  2271. url: string;
  2272. icon: string;
  2273. open_in_new_tab?: boolean;
  2274. }
  2275. export interface ExternalLinkUpdate {
  2276. name?: string;
  2277. url?: string;
  2278. icon?: string;
  2279. open_in_new_tab?: boolean;
  2280. }
  2281. // Permission type - all available permissions
  2282. export type Permission =
  2283. | 'printers:read' | 'printers:create' | 'printers:update' | 'printers:delete' | 'printers:control' | 'printers:files' | 'printers:ams_rfid' | 'printers:clear_plate'
  2284. | 'archives:read' | 'archives:create'
  2285. | 'archives:update_own' | 'archives:update_all' | 'archives:delete_own' | 'archives:delete_all'
  2286. | 'archives:reprint_own' | 'archives:reprint_all' | 'archives:purge'
  2287. | 'queue:read' | 'queue:create'
  2288. | 'queue:update_own' | 'queue:update_all' | 'queue:delete_own' | 'queue:delete_all'
  2289. | 'queue:reorder'
  2290. | 'library:read' | 'library:upload'
  2291. | 'library:update_own' | 'library:update_all' | 'library:delete_own' | 'library:delete_all'
  2292. | 'library:purge'
  2293. | 'projects:read' | 'projects:create' | 'projects:update' | 'projects:delete'
  2294. | 'filaments:read' | 'filaments:create' | 'filaments:update' | 'filaments:delete'
  2295. | 'inventory:read' | 'inventory:create' | 'inventory:update' | 'inventory:delete' | 'inventory:view_assignments'
  2296. | 'smart_plugs:read' | 'smart_plugs:create' | 'smart_plugs:update' | 'smart_plugs:delete' | 'smart_plugs:control'
  2297. | 'camera:view'
  2298. | 'maintenance:read' | 'maintenance:create' | 'maintenance:update' | 'maintenance:delete'
  2299. | 'kprofiles:read' | 'kprofiles:create' | 'kprofiles:update' | 'kprofiles:delete'
  2300. | 'notifications:read' | 'notifications:create' | 'notifications:update' | 'notifications:delete' | 'notifications:user_email'
  2301. | 'notification_templates:read' | 'notification_templates:update'
  2302. | 'external_links:read' | 'external_links:create' | 'external_links:update' | 'external_links:delete'
  2303. | 'discovery:scan'
  2304. | 'firmware:read' | 'firmware:update'
  2305. | 'ams_history:read'
  2306. | 'stats:read' | 'stats:filter_by_user'
  2307. | 'system:read'
  2308. | 'settings:read' | 'settings:update' | 'settings:backup' | 'settings:restore'
  2309. | 'github:backup' | 'github:restore'
  2310. | 'cloud:auth'
  2311. | 'makerworld:view' | 'makerworld:import'
  2312. | 'api_keys:read' | 'api_keys:create' | 'api_keys:update' | 'api_keys:delete'
  2313. | 'users:read' | 'users:create' | 'users:update' | 'users:delete'
  2314. | 'groups:read' | 'groups:create' | 'groups:update' | 'groups:delete'
  2315. | 'websocket:connect';
  2316. // Group types
  2317. export interface GroupBrief {
  2318. id: number;
  2319. name: string;
  2320. }
  2321. export interface Group {
  2322. id: number;
  2323. name: string;
  2324. description: string | null;
  2325. permissions: Permission[];
  2326. is_system: boolean;
  2327. user_count: number;
  2328. created_at: string;
  2329. updated_at: string;
  2330. }
  2331. export interface GroupDetail extends Group {
  2332. users: Array<{ id: number; username: string; is_active: boolean }>;
  2333. }
  2334. export interface GroupCreate {
  2335. name: string;
  2336. description?: string;
  2337. permissions: Permission[];
  2338. }
  2339. export interface GroupUpdate {
  2340. name?: string;
  2341. description?: string;
  2342. permissions?: Permission[];
  2343. }
  2344. export interface PermissionInfo {
  2345. value: Permission;
  2346. label: string;
  2347. }
  2348. export interface PermissionCategory {
  2349. name: string;
  2350. permissions: PermissionInfo[];
  2351. }
  2352. export interface PermissionsListResponse {
  2353. categories: PermissionCategory[];
  2354. all_permissions: Permission[];
  2355. }
  2356. // User email notification preferences
  2357. export interface UserEmailPreferences {
  2358. notify_print_start: boolean;
  2359. notify_print_complete: boolean;
  2360. notify_print_failed: boolean;
  2361. notify_print_stopped: boolean;
  2362. }
  2363. // Auth types
  2364. export interface LoginRequest {
  2365. username: string;
  2366. password: string;
  2367. }
  2368. export interface LoginResponse {
  2369. access_token?: string;
  2370. token_type?: string;
  2371. user?: UserResponse;
  2372. /** Set when 2FA verification is required before a full token is issued. */
  2373. requires_2fa?: boolean;
  2374. pre_auth_token?: string;
  2375. two_fa_methods?: string[];
  2376. }
  2377. export interface UserResponse {
  2378. id: number;
  2379. username: string;
  2380. email?: string;
  2381. role: string; // Deprecated, kept for backward compatibility
  2382. is_active: boolean;
  2383. is_admin: boolean; // Computed from role and group membership
  2384. auth_source: string; // "local" or "ldap"
  2385. groups: GroupBrief[];
  2386. permissions: Permission[]; // All permissions from groups
  2387. created_at: string;
  2388. }
  2389. export interface UserCreate {
  2390. username: string;
  2391. password?: string; // Optional when advanced auth is enabled
  2392. email?: string;
  2393. role: string;
  2394. group_ids?: number[];
  2395. }
  2396. export interface UserUpdate {
  2397. username?: string;
  2398. password?: string;
  2399. email?: string;
  2400. role?: string;
  2401. is_active?: boolean;
  2402. group_ids?: number[];
  2403. }
  2404. export interface SetupRequest {
  2405. auth_enabled: boolean;
  2406. admin_username?: string;
  2407. admin_password?: string;
  2408. }
  2409. export interface ForgotPasswordRequest {
  2410. email: string;
  2411. }
  2412. export interface ForgotPasswordResponse {
  2413. message: string;
  2414. }
  2415. export interface ResetPasswordRequest {
  2416. user_id: number;
  2417. }
  2418. export interface ResetPasswordResponse {
  2419. message: string;
  2420. }
  2421. export interface SMTPSettings {
  2422. smtp_host: string;
  2423. smtp_port: number;
  2424. smtp_username?: string;
  2425. smtp_password?: string;
  2426. smtp_security: 'starttls' | 'ssl' | 'none';
  2427. smtp_auth_enabled: boolean;
  2428. smtp_from_email: string;
  2429. smtp_from_name: string;
  2430. }
  2431. // 2FA / MFA interfaces
  2432. export interface TwoFAStatus {
  2433. totp_enabled: boolean;
  2434. email_otp_enabled: boolean;
  2435. backup_codes_remaining: number;
  2436. }
  2437. export interface TOTPSetupResponse {
  2438. secret: string;
  2439. qr_code_b64: string;
  2440. issuer: string;
  2441. }
  2442. export interface TOTPEnableResponse {
  2443. message: string;
  2444. backup_codes: string[];
  2445. }
  2446. export interface BackupCodesResponse {
  2447. backup_codes: string[];
  2448. message: string;
  2449. }
  2450. export interface TwoFAVerifyRequest {
  2451. pre_auth_token: string;
  2452. code: string;
  2453. method: 'totp' | 'email' | 'backup';
  2454. }
  2455. // OIDC interfaces
  2456. export interface OIDCProvider {
  2457. id: number;
  2458. name: string;
  2459. issuer_url: string;
  2460. client_id: string;
  2461. scopes: string;
  2462. is_enabled: boolean;
  2463. auto_create_users: boolean;
  2464. auto_link_existing_accounts: boolean;
  2465. email_claim: string;
  2466. require_email_verified: boolean;
  2467. icon_url?: string | null;
  2468. }
  2469. export interface OIDCProviderCreate {
  2470. name: string;
  2471. issuer_url: string;
  2472. client_id: string;
  2473. client_secret: string;
  2474. scopes?: string;
  2475. is_enabled?: boolean;
  2476. auto_create_users?: boolean;
  2477. auto_link_existing_accounts?: boolean;
  2478. email_claim?: string;
  2479. require_email_verified?: boolean;
  2480. icon_url?: string | null;
  2481. }
  2482. export interface OIDCLink {
  2483. id: number;
  2484. provider_id: number;
  2485. provider_name: string;
  2486. provider_email?: string | null;
  2487. created_at: string;
  2488. }
  2489. export interface TestSMTPRequest {
  2490. test_recipient: string;
  2491. }
  2492. export interface TestSMTPResponse {
  2493. success: boolean;
  2494. message: string;
  2495. }
  2496. export interface AdvancedAuthStatus {
  2497. advanced_auth_enabled: boolean;
  2498. smtp_configured: boolean;
  2499. }
  2500. export interface LDAPStatus {
  2501. ldap_enabled: boolean;
  2502. ldap_configured: boolean;
  2503. }
  2504. export interface LDAPTestResponse {
  2505. success: boolean;
  2506. message: string;
  2507. }
  2508. export interface SetupResponse {
  2509. auth_enabled: boolean;
  2510. admin_created?: boolean;
  2511. }
  2512. export interface AuthStatus {
  2513. auth_enabled: boolean;
  2514. requires_setup: boolean;
  2515. }
  2516. // API functions
  2517. export const api = {
  2518. // Authentication
  2519. getAuthStatus: () => request<AuthStatus>('/auth/status'),
  2520. setupAuth: (data: SetupRequest) =>
  2521. request<SetupResponse>('/auth/setup', {
  2522. method: 'POST',
  2523. body: JSON.stringify(data),
  2524. }),
  2525. login: (data: LoginRequest) =>
  2526. request<LoginResponse>('/auth/login', {
  2527. method: 'POST',
  2528. body: JSON.stringify(data),
  2529. }),
  2530. logout: () =>
  2531. request<{ message: string }>('/auth/logout', {
  2532. method: 'POST',
  2533. }),
  2534. getCurrentUser: () => request<UserResponse>('/auth/me'),
  2535. disableAuth: () =>
  2536. request<{ message: string; auth_enabled: boolean }>('/auth/disable', {
  2537. method: 'POST',
  2538. }),
  2539. // Advanced Authentication
  2540. testSMTP: (data: TestSMTPRequest) =>
  2541. request<TestSMTPResponse>('/auth/smtp/test', {
  2542. method: 'POST',
  2543. body: JSON.stringify(data),
  2544. }),
  2545. getSMTPSettings: () => request<SMTPSettings | null>('/auth/smtp'),
  2546. saveSMTPSettings: (data: SMTPSettings) =>
  2547. request<{ message: string }>('/auth/smtp', {
  2548. method: 'POST',
  2549. body: JSON.stringify(data),
  2550. }),
  2551. enableAdvancedAuth: () =>
  2552. request<{ message: string; advanced_auth_enabled: boolean }>('/auth/advanced-auth/enable', {
  2553. method: 'POST',
  2554. }),
  2555. disableAdvancedAuth: () =>
  2556. request<{ message: string; advanced_auth_enabled: boolean }>('/auth/advanced-auth/disable', {
  2557. method: 'POST',
  2558. }),
  2559. getAdvancedAuthStatus: () => request<AdvancedAuthStatus>('/auth/advanced-auth/status'),
  2560. // LDAP Authentication
  2561. getLDAPStatus: () => request<LDAPStatus>('/auth/ldap/status'),
  2562. testLDAP: () =>
  2563. request<LDAPTestResponse>('/auth/ldap/test', {
  2564. method: 'POST',
  2565. }),
  2566. forgotPassword: (data: ForgotPasswordRequest) =>
  2567. request<ForgotPasswordResponse>('/auth/forgot-password', {
  2568. method: 'POST',
  2569. body: JSON.stringify(data),
  2570. }),
  2571. // H-6: Confirm password reset using the token from the emailed link
  2572. forgotPasswordConfirm: (token: string, newPassword: string) =>
  2573. request<ForgotPasswordResponse>('/auth/forgot-password/confirm', {
  2574. method: 'POST',
  2575. body: JSON.stringify({ token, new_password: newPassword }),
  2576. }),
  2577. resetUserPassword: (data: ResetPasswordRequest) =>
  2578. request<ResetPasswordResponse>('/auth/reset-password', {
  2579. method: 'POST',
  2580. body: JSON.stringify(data),
  2581. }),
  2582. // 2FA - status
  2583. get2FAStatus: () => request<TwoFAStatus>('/auth/2fa/status'),
  2584. // 2FA - TOTP
  2585. setupTOTP: () => request<TOTPSetupResponse>('/auth/2fa/totp/setup', { method: 'POST' }),
  2586. enableTOTP: (code: string) =>
  2587. request<TOTPEnableResponse>('/auth/2fa/totp/enable', {
  2588. method: 'POST',
  2589. body: JSON.stringify({ code }),
  2590. }),
  2591. disableTOTP: (code: string) =>
  2592. request<{ message: string }>('/auth/2fa/totp/disable', {
  2593. method: 'POST',
  2594. body: JSON.stringify({ code }),
  2595. }),
  2596. regenerateBackupCodes: (code: string) =>
  2597. request<BackupCodesResponse>('/auth/2fa/totp/regenerate-backup-codes', {
  2598. method: 'POST',
  2599. body: JSON.stringify({ code }),
  2600. }),
  2601. // 2FA - Email OTP
  2602. // Step 1: send a verification code to the user's email (proof of possession)
  2603. enableEmailOTP: () =>
  2604. request<{ message: string; setup_token: string }>('/auth/2fa/email/enable', { method: 'POST' }),
  2605. // Step 2: confirm with the code received by email
  2606. confirmEnableEmailOTP: (setup_token: string, code: string) =>
  2607. request<{ message: string }>('/auth/2fa/email/enable/confirm', {
  2608. method: 'POST',
  2609. body: JSON.stringify({ setup_token, code }),
  2610. }),
  2611. // Disable requires account password for re-auth
  2612. disableEmailOTP: (password: string) =>
  2613. request<{ message: string }>('/auth/2fa/email/disable', {
  2614. method: 'POST',
  2615. body: JSON.stringify({ password }),
  2616. }),
  2617. sendEmailOTP: (preAuthToken: string) =>
  2618. request<{ message: string; pre_auth_token?: string }>('/auth/2fa/email/send', {
  2619. method: 'POST',
  2620. body: JSON.stringify({ pre_auth_token: preAuthToken }),
  2621. }),
  2622. // 2FA - verify (completes login)
  2623. verify2FA: (data: TwoFAVerifyRequest) =>
  2624. request<LoginResponse>('/auth/2fa/verify', {
  2625. method: 'POST',
  2626. body: JSON.stringify(data),
  2627. }),
  2628. // 2FA - admin
  2629. admin2FADisable: (userId: number) =>
  2630. request<{ message: string }>(`/auth/2fa/admin/${userId}`, { method: 'DELETE' }),
  2631. // OIDC providers (public list)
  2632. getOIDCProviders: () => request<OIDCProvider[]>('/auth/oidc/providers'),
  2633. // OIDC providers (admin)
  2634. getOIDCProvidersAll: () => request<OIDCProvider[]>('/auth/oidc/providers/all'),
  2635. createOIDCProvider: (data: OIDCProviderCreate) =>
  2636. request<OIDCProvider>('/auth/oidc/providers', {
  2637. method: 'POST',
  2638. body: JSON.stringify(data),
  2639. }),
  2640. updateOIDCProvider: (id: number, data: Partial<OIDCProviderCreate>) =>
  2641. request<OIDCProvider>(`/auth/oidc/providers/${id}`, {
  2642. method: 'PUT',
  2643. body: JSON.stringify(data),
  2644. }),
  2645. deleteOIDCProvider: (id: number) =>
  2646. request<{ message: string }>(`/auth/oidc/providers/${id}`, { method: 'DELETE' }),
  2647. // OIDC authorize URL
  2648. getOIDCAuthorizeUrl: (providerId: number) =>
  2649. request<{ auth_url: string }>(`/auth/oidc/authorize/${providerId}`),
  2650. // OIDC exchange token for JWT
  2651. exchangeOIDCToken: (oidcToken: string) =>
  2652. request<LoginResponse>('/auth/oidc/exchange', {
  2653. method: 'POST',
  2654. body: JSON.stringify({ oidc_token: oidcToken }),
  2655. }),
  2656. // OIDC links for current user
  2657. getOIDCLinks: () => request<OIDCLink[]>('/auth/oidc/links'),
  2658. deleteOIDCLink: (providerId: number) =>
  2659. request<{ message: string }>(`/auth/oidc/links/${providerId}`, { method: 'DELETE' }),
  2660. // Users
  2661. getUsers: () => request<UserResponse[]>('/users/'),
  2662. getUser: (id: number) => request<UserResponse>(`/users/${id}`),
  2663. createUser: (data: UserCreate) =>
  2664. request<UserResponse>('/users/', {
  2665. method: 'POST',
  2666. body: JSON.stringify(data),
  2667. }),
  2668. updateUser: (id: number, data: UserUpdate) =>
  2669. request<UserResponse>(`/users/${id}`, {
  2670. method: 'PATCH',
  2671. body: JSON.stringify(data),
  2672. }),
  2673. deleteUser: (id: number, deleteItems: boolean = false) =>
  2674. request<void>(`/users/${id}?delete_items=${deleteItems}`, {
  2675. method: 'DELETE',
  2676. }),
  2677. getUserItemsCount: (id: number) =>
  2678. request<{ archives: number; queue_items: number; library_files: number }>(`/users/${id}/items-count`),
  2679. changePassword: (currentPassword: string, newPassword: string) =>
  2680. request<{ message: string }>('/users/me/change-password', {
  2681. method: 'POST',
  2682. body: JSON.stringify({ current_password: currentPassword, new_password: newPassword }),
  2683. }),
  2684. // User Email Notifications
  2685. getUserEmailPreferences: () =>
  2686. request<UserEmailPreferences>('/user-notifications/preferences'),
  2687. updateUserEmailPreferences: (data: UserEmailPreferences) =>
  2688. request<UserEmailPreferences>('/user-notifications/preferences', {
  2689. method: 'PUT',
  2690. body: JSON.stringify(data),
  2691. }),
  2692. // Groups
  2693. getPermissions: () => request<PermissionsListResponse>('/groups/permissions'),
  2694. getGroups: () => request<Group[]>('/groups/'),
  2695. getGroup: (id: number) => request<GroupDetail>(`/groups/${id}`),
  2696. createGroup: (data: GroupCreate) =>
  2697. request<Group>('/groups/', {
  2698. method: 'POST',
  2699. body: JSON.stringify(data),
  2700. }),
  2701. updateGroup: (id: number, data: GroupUpdate) =>
  2702. request<Group>(`/groups/${id}`, {
  2703. method: 'PATCH',
  2704. body: JSON.stringify(data),
  2705. }),
  2706. deleteGroup: (id: number) =>
  2707. request<void>(`/groups/${id}`, {
  2708. method: 'DELETE',
  2709. }),
  2710. addUserToGroup: (groupId: number, userId: number) =>
  2711. request<void>(`/groups/${groupId}/users/${userId}`, {
  2712. method: 'POST',
  2713. }),
  2714. removeUserFromGroup: (groupId: number, userId: number) =>
  2715. request<void>(`/groups/${groupId}/users/${userId}`, {
  2716. method: 'DELETE',
  2717. }),
  2718. // Printers
  2719. getPrinters: () => request<Printer[]>('/printers/'),
  2720. getPrinter: (id: number) => request<Printer>(`/printers/${id}`),
  2721. createPrinter: (data: PrinterCreate) =>
  2722. request<Printer>('/printers/', {
  2723. method: 'POST',
  2724. body: JSON.stringify(data),
  2725. }),
  2726. updatePrinter: (id: number, data: Partial<PrinterCreate>) =>
  2727. request<Printer>(`/printers/${id}`, {
  2728. method: 'PATCH',
  2729. body: JSON.stringify(data),
  2730. }),
  2731. deletePrinter: (id: number, deleteArchives: boolean = true) =>
  2732. request<{ status: string; archives_deleted: boolean }>(
  2733. `/printers/${id}?delete_archives=${deleteArchives}`,
  2734. { method: 'DELETE' }
  2735. ),
  2736. getDeveloperModeWarnings: () =>
  2737. request<{ printer_id: number; name: string }[]>('/printers/developer-mode-warnings'),
  2738. getAvailableFilaments: (model: string, location?: string) => {
  2739. const params = new URLSearchParams({ model });
  2740. if (location) params.set('location', location);
  2741. return request<Array<{ type: string; color: string; tray_info_idx: string; tray_sub_brands: string; extruder_id: number | null }>>(`/printers/available-filaments?${params}`);
  2742. },
  2743. getPrinterStatus: (id: number) =>
  2744. request<PrinterStatus>(`/printers/${id}/status`),
  2745. refreshPrinterStatus: (id: number) =>
  2746. request<{ status: string }>(`/printers/${id}/refresh-status`, {
  2747. method: 'POST',
  2748. }),
  2749. connectPrinter: (id: number) =>
  2750. request<{ connected: boolean }>(`/printers/${id}/connect`, {
  2751. method: 'POST',
  2752. }),
  2753. disconnectPrinter: (id: number) =>
  2754. request<{ connected: boolean }>(`/printers/${id}/disconnect`, {
  2755. method: 'POST',
  2756. }),
  2757. testExternalCamera: (printerId: number, url: string, cameraType: string) =>
  2758. request<{ success: boolean; error?: string; resolution?: string }>(
  2759. `/printers/${printerId}/camera/external/test?url=${encodeURIComponent(url)}&camera_type=${encodeURIComponent(cameraType)}`,
  2760. { method: 'POST' }
  2761. ),
  2762. // Print Control
  2763. stopPrint: (printerId: number) =>
  2764. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/stop`, {
  2765. method: 'POST',
  2766. }),
  2767. pausePrint: (printerId: number) =>
  2768. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/pause`, {
  2769. method: 'POST',
  2770. }),
  2771. resumePrint: (printerId: number) =>
  2772. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/resume`, {
  2773. method: 'POST',
  2774. }),
  2775. clearPlate: (printerId: number) =>
  2776. request<{ success: boolean; message: string }>(`/printers/${printerId}/clear-plate`, {
  2777. method: 'POST',
  2778. }),
  2779. // Get current print user (for reprint tracking - Issue #206)
  2780. getCurrentPrintUser: (printerId: number) =>
  2781. request<{ user_id?: number; username?: string }>(`/printers/${printerId}/current-print-user`),
  2782. // Print Speed Control
  2783. setPrintSpeed: (printerId: number, mode: number) =>
  2784. request<{ success: boolean; message: string }>(`/printers/${printerId}/print-speed?mode=${mode}`, {
  2785. method: 'POST',
  2786. }),
  2787. setAirductMode: (printerId: number, mode: 'cooling' | 'heating') =>
  2788. request<{ success: boolean; message: string }>(`/printers/${printerId}/airduct-mode?mode=${mode}`, {
  2789. method: 'POST',
  2790. }),
  2791. // Bed (Z-axis) jog
  2792. bedJog: (printerId: number, distance: number, force: boolean = false) =>
  2793. request<{ success: boolean; message: string }>(
  2794. `/printers/${printerId}/bed-jog?distance=${distance}&force=${force}`,
  2795. { method: 'POST' }
  2796. ),
  2797. homeAxes: (printerId: number, axes: 'z' | 'xy' | 'all' = 'z') =>
  2798. request<{ success: boolean; message: string }>(
  2799. `/printers/${printerId}/home-axes?axes=${axes}`,
  2800. { method: 'POST' }
  2801. ),
  2802. // Chamber Light Control
  2803. setChamberLight: (printerId: number, on: boolean) =>
  2804. request<{ success: boolean; message: string }>(`/printers/${printerId}/chamber-light?on=${on}`, {
  2805. method: 'POST',
  2806. }),
  2807. // AMS Drying Control
  2808. startDrying: (printerId: number, amsId: number, temp: number, duration: number, filament: string = '', rotateTray: boolean = false) =>
  2809. request<{ status: string; ams_id: number; temp: number; duration: number }>(
  2810. `/printers/${printerId}/drying/start?ams_id=${amsId}&temp=${temp}&duration=${duration}&filament=${encodeURIComponent(filament)}&rotate_tray=${rotateTray}`,
  2811. { method: 'POST' }
  2812. ),
  2813. stopDrying: (printerId: number, amsId: number) =>
  2814. request<{ status: string; ams_id: number }>(
  2815. `/printers/${printerId}/drying/stop?ams_id=${amsId}`,
  2816. { method: 'POST' }
  2817. ),
  2818. // Skip Objects
  2819. getPrintableObjects: (printerId: number) =>
  2820. request<{
  2821. objects: Array<{ id: number; name: string; x: number | null; y: number | null; skipped: boolean }>;
  2822. total: number;
  2823. skipped_count: number;
  2824. is_printing: boolean;
  2825. bbox_all: [number, number, number, number] | null;
  2826. }>(`/printers/${printerId}/print/objects`),
  2827. skipObjects: (printerId: number, objectIds: number[]) =>
  2828. request<{ success: boolean; message: string; skipped_objects: number[] }>(
  2829. `/printers/${printerId}/print/skip-objects`,
  2830. {
  2831. method: 'POST',
  2832. body: JSON.stringify(objectIds),
  2833. }
  2834. ),
  2835. // HMS Errors
  2836. clearHMSErrors: (printerId: number) =>
  2837. request<{ success: boolean; message: string }>(`/printers/${printerId}/hms/clear`, { method: 'POST' }),
  2838. // AMS Control
  2839. refreshAmsSlot: (printerId: number, amsId: number, slotId: number) =>
  2840. request<{ success: boolean; message: string }>(
  2841. `/printers/${printerId}/ams/${amsId}/slot/${slotId}/refresh`,
  2842. { method: 'POST' }
  2843. ),
  2844. // MQTT Debug Logging
  2845. enableMQTTLogging: (printerId: number) =>
  2846. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/enable`, {
  2847. method: 'POST',
  2848. }),
  2849. disableMQTTLogging: (printerId: number) =>
  2850. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/disable`, {
  2851. method: 'POST',
  2852. }),
  2853. getMQTTLogs: (printerId: number) =>
  2854. request<MQTTLogsResponse>(`/printers/${printerId}/logging`),
  2855. clearMQTTLogs: (printerId: number) =>
  2856. request<{ status: string }>(`/printers/${printerId}/logging`, {
  2857. method: 'DELETE',
  2858. }),
  2859. // Printer File Manager
  2860. getPrinterFiles: (printerId: number, path = '/') =>
  2861. request<{
  2862. path: string;
  2863. files: Array<{
  2864. name: string;
  2865. is_directory: boolean;
  2866. size: number;
  2867. path: string;
  2868. mtime?: string;
  2869. }>;
  2870. }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`),
  2871. getPrinterFileDownloadUrl: (printerId: number, path: string) =>
  2872. `${API_BASE}/printers/${printerId}/files/download?path=${encodeURIComponent(path)}`,
  2873. getPrinterFileGcodeUrl: (printerId: number, path: string) =>
  2874. `${API_BASE}/printers/${printerId}/files/gcode?path=${encodeURIComponent(path)}`,
  2875. getPrinterFilePlates: (printerId: number, path: string) =>
  2876. request<{
  2877. printer_id: number;
  2878. path: string;
  2879. filename: string;
  2880. plates: Array<{
  2881. index: number;
  2882. name: string | null;
  2883. objects: string[];
  2884. has_thumbnail: boolean;
  2885. thumbnail_url: string | null;
  2886. print_time_seconds: number | null;
  2887. filament_used_grams: number | null;
  2888. filaments: Array<{
  2889. slot_id: number;
  2890. type: string;
  2891. color: string;
  2892. used_grams: number;
  2893. used_meters: number;
  2894. }>;
  2895. }>;
  2896. is_multi_plate: boolean;
  2897. }>(`/printers/${printerId}/files/plates?path=${encodeURIComponent(path)}`),
  2898. getPrinterFilePlateThumbnail: (printerId: number, plateIndex: number, path: string) =>
  2899. withStreamToken(`${API_BASE}/printers/${printerId}/files/plate-thumbnail/${plateIndex}?path=${encodeURIComponent(path)}`),
  2900. downloadPrinterFile: async (printerId: number, path: string): Promise<void> => {
  2901. const headers: Record<string, string> = {};
  2902. if (authToken) {
  2903. headers['Authorization'] = `Bearer ${authToken}`;
  2904. }
  2905. const response = await fetch(
  2906. `${API_BASE}/printers/${printerId}/files/download?path=${encodeURIComponent(path)}`,
  2907. { headers }
  2908. );
  2909. if (!response.ok) {
  2910. const error = await response.json().catch(() => ({}));
  2911. throw new Error(error.detail || `HTTP ${response.status}`);
  2912. }
  2913. const disposition = response.headers.get('Content-Disposition');
  2914. const filename = parseContentDispositionFilename(disposition) || path.split('/').pop() || 'download';
  2915. const blob = await response.blob();
  2916. const url = window.URL.createObjectURL(blob);
  2917. const a = document.createElement('a');
  2918. a.href = url;
  2919. a.download = filename;
  2920. document.body.appendChild(a);
  2921. a.click();
  2922. document.body.removeChild(a);
  2923. window.URL.revokeObjectURL(url);
  2924. },
  2925. downloadPrinterFilesAsZip: async (printerId: number, paths: string[]): Promise<Blob> => {
  2926. const headers: Record<string, string> = { 'Content-Type': 'application/json' };
  2927. if (authToken) {
  2928. headers['Authorization'] = `Bearer ${authToken}`;
  2929. }
  2930. const response = await fetch(`${API_BASE}/printers/${printerId}/files/download-zip`, {
  2931. method: 'POST',
  2932. headers,
  2933. body: JSON.stringify({ paths }),
  2934. });
  2935. if (!response.ok) {
  2936. const error = await response.json().catch(() => ({}));
  2937. throw new Error(error.detail || `HTTP ${response.status}`);
  2938. }
  2939. return response.blob();
  2940. },
  2941. deletePrinterFile: (printerId: number, path: string) =>
  2942. request<{ status: string; path: string }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`, {
  2943. method: 'DELETE',
  2944. }),
  2945. getPrinterStorage: (printerId: number) =>
  2946. request<{ used_bytes: number | null; free_bytes: number | null }>(`/printers/${printerId}/storage`),
  2947. // Archives
  2948. getArchives: (printerId?: number, projectId?: number, limit = 10000, offset = 0, dateFrom?: string, dateTo?: string) => {
  2949. const params = new URLSearchParams();
  2950. if (printerId) params.set('printer_id', String(printerId));
  2951. if (projectId) params.set('project_id', String(projectId));
  2952. params.set('limit', String(limit));
  2953. params.set('offset', String(offset));
  2954. if (dateFrom) params.set('date_from', dateFrom);
  2955. if (dateTo) params.set('date_to', dateTo);
  2956. return request<Archive[]>(`/archives/?${params}`);
  2957. },
  2958. getArchivesSlim: (dateFrom?: string, dateTo?: string, createdById?: number) => {
  2959. const params = new URLSearchParams();
  2960. if (dateFrom) params.set('date_from', dateFrom);
  2961. if (dateTo) params.set('date_to', dateTo);
  2962. if (createdById !== undefined) params.set('created_by_id', String(createdById));
  2963. const qs = params.toString();
  2964. return request<ArchiveSlim[]>(`/archives/slim${qs ? `?${qs}` : ''}`);
  2965. },
  2966. getArchive: (id: number) => request<Archive>(`/archives/${id}`),
  2967. searchArchives: (query: string, options?: {
  2968. printerId?: number;
  2969. projectId?: number;
  2970. status?: string;
  2971. limit?: number;
  2972. offset?: number;
  2973. }) => {
  2974. const params = new URLSearchParams();
  2975. params.set('q', query);
  2976. if (options?.printerId) params.set('printer_id', String(options.printerId));
  2977. if (options?.projectId) params.set('project_id', String(options.projectId));
  2978. if (options?.status) params.set('status', options.status);
  2979. if (options?.limit) params.set('limit', String(options.limit));
  2980. if (options?.offset) params.set('offset', String(options.offset));
  2981. return request<Archive[]>(`/archives/search?${params}`);
  2982. },
  2983. rebuildSearchIndex: () => request<{ message: string }>('/archives/search/rebuild-index', { method: 'POST' }),
  2984. updateArchive: (id: number, data: {
  2985. printer_id?: number | null;
  2986. project_id?: number | null;
  2987. print_name?: string;
  2988. is_favorite?: boolean;
  2989. tags?: string;
  2990. notes?: string;
  2991. cost?: number;
  2992. failure_reason?: string | null;
  2993. status?: string;
  2994. quantity?: number;
  2995. external_url?: string | null;
  2996. }) =>
  2997. request<Archive>(`/archives/${id}`, {
  2998. method: 'PATCH',
  2999. body: JSON.stringify(data),
  3000. }),
  3001. toggleFavorite: (id: number) =>
  3002. request<Archive>(`/archives/${id}/favorite`, { method: 'POST' }),
  3003. deleteArchive: (id: number) =>
  3004. request<void>(`/archives/${id}`, { method: 'DELETE' }),
  3005. // ========== Archive auto-purge (#1008 follow-up) ==========
  3006. previewArchivePurge: (olderThanDays: number) =>
  3007. request<ArchivePurgePreview>(`/archives/purge/preview?older_than_days=${olderThanDays}`),
  3008. executeArchivePurge: (olderThanDays: number) =>
  3009. request<{ deleted: number }>('/archives/purge', {
  3010. method: 'POST',
  3011. body: JSON.stringify({ older_than_days: olderThanDays }),
  3012. }),
  3013. getArchivePurgeSettings: () =>
  3014. request<ArchivePurgeSettings>('/archives/purge/settings'),
  3015. updateArchivePurgeSettings: (body: ArchivePurgeSettings) =>
  3016. request<ArchivePurgeSettings>('/archives/purge/settings', {
  3017. method: 'PUT',
  3018. body: JSON.stringify(body),
  3019. }),
  3020. getArchiveStats: (options?: { dateFrom?: string; dateTo?: string; createdById?: number }) => {
  3021. const params = new URLSearchParams();
  3022. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  3023. if (options?.dateTo) params.set('date_to', options.dateTo);
  3024. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  3025. const qs = params.toString();
  3026. return request<ArchiveStats>(`/archives/stats${qs ? `?${qs}` : ''}`);
  3027. },
  3028. // Tag management
  3029. getTags: () => request<TagInfo[]>('/archives/tags'),
  3030. renameTag: (oldName: string, newName: string) =>
  3031. request<{ affected: number }>(`/archives/tags/${encodeURIComponent(oldName)}`, {
  3032. method: 'PUT',
  3033. body: JSON.stringify({ new_name: newName }),
  3034. }),
  3035. deleteTag: (name: string) =>
  3036. request<{ affected: number }>(`/archives/tags/${encodeURIComponent(name)}`, {
  3037. method: 'DELETE',
  3038. }),
  3039. recalculateCosts: () =>
  3040. request<{ message: string; updated: number }>('/archives/recalculate-costs', { method: 'POST' }),
  3041. getFailureAnalysis: (options?: { days?: number; dateFrom?: string; dateTo?: string; printerId?: number; projectId?: number; createdById?: number }) => {
  3042. const params = new URLSearchParams();
  3043. if (options?.days) params.set('days', String(options.days));
  3044. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  3045. if (options?.dateTo) params.set('date_to', options.dateTo);
  3046. if (options?.printerId) params.set('printer_id', String(options.printerId));
  3047. if (options?.projectId) params.set('project_id', String(options.projectId));
  3048. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  3049. const qs = params.toString();
  3050. return request<FailureAnalysis>(`/archives/analysis/failures${qs ? `?${qs}` : ''}`);
  3051. },
  3052. compareArchives: (archiveIds: number[]) =>
  3053. request<ArchiveComparison>(`/archives/compare?archive_ids=${archiveIds.join(',')}`),
  3054. findSimilarArchives: (archiveId: number, limit = 10) =>
  3055. request<SimilarArchive[]>(`/archives/${archiveId}/similar?limit=${limit}`),
  3056. exportArchives: async (options?: {
  3057. format?: 'csv' | 'xlsx';
  3058. fields?: string[];
  3059. printerId?: number;
  3060. projectId?: number;
  3061. status?: string;
  3062. dateFrom?: string;
  3063. dateTo?: string;
  3064. search?: string;
  3065. }): Promise<{ blob: Blob; filename: string }> => {
  3066. const params = new URLSearchParams();
  3067. if (options?.format) params.set('format', options.format);
  3068. if (options?.fields) params.set('fields', options.fields.join(','));
  3069. if (options?.printerId) params.set('printer_id', String(options.printerId));
  3070. if (options?.projectId) params.set('project_id', String(options.projectId));
  3071. if (options?.status) params.set('status', options.status);
  3072. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  3073. if (options?.dateTo) params.set('date_to', options.dateTo);
  3074. if (options?.search) params.set('search', options.search);
  3075. const headers: Record<string, string> = {};
  3076. if (authToken) {
  3077. headers['Authorization'] = `Bearer ${authToken}`;
  3078. }
  3079. const response = await fetch(`${API_BASE}/archives/export?${params}`, { headers });
  3080. if (!response.ok) {
  3081. const error = await response.json().catch(() => ({}));
  3082. throw new Error(error.detail || `HTTP ${response.status}`);
  3083. }
  3084. const contentDisposition = response.headers.get('Content-Disposition');
  3085. let filename = options?.format === 'xlsx' ? 'archives_export.xlsx' : 'archives_export.csv';
  3086. if (contentDisposition) {
  3087. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  3088. if (match) filename = match[1];
  3089. }
  3090. const blob = await response.blob();
  3091. return { blob, filename };
  3092. },
  3093. exportStats: async (options?: {
  3094. format?: 'csv' | 'xlsx';
  3095. days?: number;
  3096. printerId?: number;
  3097. projectId?: number;
  3098. createdById?: number;
  3099. }): Promise<{ blob: Blob; filename: string }> => {
  3100. const params = new URLSearchParams();
  3101. if (options?.format) params.set('format', options.format);
  3102. if (options?.days) params.set('days', String(options.days));
  3103. if (options?.printerId) params.set('printer_id', String(options.printerId));
  3104. if (options?.projectId) params.set('project_id', String(options.projectId));
  3105. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  3106. const headers: Record<string, string> = {};
  3107. if (authToken) {
  3108. headers['Authorization'] = `Bearer ${authToken}`;
  3109. }
  3110. const response = await fetch(`${API_BASE}/archives/stats/export?${params}`, { headers });
  3111. if (!response.ok) {
  3112. const error = await response.json().catch(() => ({}));
  3113. throw new Error(error.detail || `HTTP ${response.status}`);
  3114. }
  3115. const contentDisposition = response.headers.get('Content-Disposition');
  3116. let filename = options?.format === 'xlsx' ? 'stats_export.xlsx' : 'stats_export.csv';
  3117. if (contentDisposition) {
  3118. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  3119. if (match) filename = match[1];
  3120. }
  3121. const blob = await response.blob();
  3122. return { blob, filename };
  3123. },
  3124. getArchiveDuplicates: (id: number) =>
  3125. request<{ duplicates: ArchiveDuplicate[]; count: number }>(`/archives/${id}/duplicates`),
  3126. backfillContentHashes: () =>
  3127. request<{ updated: number; errors: Array<{ id: number; error: string }> }>('/archives/backfill-hashes', {
  3128. method: 'POST',
  3129. }),
  3130. getArchiveThumbnail: (id: number) => withStreamToken(`${API_BASE}/archives/${id}/thumbnail?v=${Date.now()}`),
  3131. getArchivePlateThumbnail: (id: number, plateIndex: number) =>
  3132. withStreamToken(`${API_BASE}/archives/${id}/plate-thumbnail/${plateIndex}`),
  3133. getArchiveDownload: (id: number) => `${API_BASE}/archives/${id}/download`,
  3134. downloadArchive: async (id: number, filename?: string): Promise<void> => {
  3135. const headers: Record<string, string> = {};
  3136. if (authToken) {
  3137. headers['Authorization'] = `Bearer ${authToken}`;
  3138. }
  3139. const response = await fetch(`${API_BASE}/archives/${id}/download`, { headers });
  3140. if (!response.ok) {
  3141. const error = await response.json().catch(() => ({}));
  3142. throw new Error(error.detail || `HTTP ${response.status}`);
  3143. }
  3144. const disposition = response.headers.get('Content-Disposition');
  3145. const downloadFilename = parseContentDispositionFilename(disposition) || filename || `archive_${id}.3mf`;
  3146. const blob = await response.blob();
  3147. const url = window.URL.createObjectURL(blob);
  3148. const a = document.createElement('a');
  3149. a.href = url;
  3150. a.download = downloadFilename;
  3151. document.body.appendChild(a);
  3152. a.click();
  3153. document.body.removeChild(a);
  3154. window.URL.revokeObjectURL(url);
  3155. },
  3156. getArchiveGcode: (id: number) => `${API_BASE}/archives/${id}/gcode`,
  3157. getArchivePlatePreview: (id: number) => withStreamToken(`${API_BASE}/archives/${id}/plate-preview`),
  3158. getArchiveTimelapse: (id: number) => withStreamToken(`${API_BASE}/archives/${id}/timelapse?v=${Date.now()}`),
  3159. scanArchiveTimelapse: (id: number) =>
  3160. request<{
  3161. status: string;
  3162. message: string;
  3163. filename?: string;
  3164. available_files?: Array<{ name: string; path: string; size: number; mtime: string | null }>;
  3165. }>(`/archives/${id}/timelapse/scan`, {
  3166. method: 'POST',
  3167. }),
  3168. selectArchiveTimelapse: (id: number, filename: string) =>
  3169. request<{ status: string; message: string; filename: string }>(
  3170. `/archives/${id}/timelapse/select?filename=${encodeURIComponent(filename)}`,
  3171. { method: 'POST' }
  3172. ),
  3173. deleteArchiveTimelapse: (id: number) =>
  3174. request<{ status: string }>(`/archives/${id}/timelapse`, {
  3175. method: 'DELETE',
  3176. }),
  3177. uploadArchiveTimelapse: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  3178. const formData = new FormData();
  3179. formData.append('file', file);
  3180. const headers: Record<string, string> = {};
  3181. if (authToken) {
  3182. headers['Authorization'] = `Bearer ${authToken}`;
  3183. }
  3184. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/upload`, {
  3185. method: 'POST',
  3186. headers,
  3187. body: formData,
  3188. });
  3189. if (!response.ok) {
  3190. const error = await response.json().catch(() => ({}));
  3191. throw new Error(error.detail || `HTTP ${response.status}`);
  3192. }
  3193. return response.json();
  3194. },
  3195. // Timelapse Editor
  3196. getTimelapseInfo: (archiveId: number) =>
  3197. request<{
  3198. duration: number;
  3199. width: number;
  3200. height: number;
  3201. fps: number;
  3202. codec: string;
  3203. file_size: number;
  3204. has_audio: boolean;
  3205. }>(`/archives/${archiveId}/timelapse/info`),
  3206. getTimelapseThumbnails: (archiveId: number, count: number = 10) =>
  3207. request<{
  3208. thumbnails: string[];
  3209. timestamps: number[];
  3210. }>(`/archives/${archiveId}/timelapse/thumbnails?count=${count}`),
  3211. processTimelapse: async (
  3212. archiveId: number,
  3213. params: {
  3214. trimStart?: number;
  3215. trimEnd?: number;
  3216. speed?: number;
  3217. saveMode: 'replace' | 'new';
  3218. outputFilename?: string;
  3219. },
  3220. audioFile?: File
  3221. ): Promise<{ status: string; output_path: string | null; message: string }> => {
  3222. const formData = new FormData();
  3223. formData.append('trim_start', String(params.trimStart ?? 0));
  3224. if (params.trimEnd !== undefined) {
  3225. formData.append('trim_end', String(params.trimEnd));
  3226. }
  3227. formData.append('speed', String(params.speed ?? 1));
  3228. formData.append('save_mode', params.saveMode);
  3229. if (params.outputFilename) {
  3230. formData.append('output_filename', params.outputFilename);
  3231. }
  3232. if (audioFile) {
  3233. formData.append('audio', audioFile);
  3234. }
  3235. const headers: Record<string, string> = {};
  3236. if (authToken) {
  3237. headers['Authorization'] = `Bearer ${authToken}`;
  3238. }
  3239. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/process`, {
  3240. method: 'POST',
  3241. headers,
  3242. body: formData,
  3243. });
  3244. if (!response.ok) {
  3245. const error = await response.json().catch(() => ({}));
  3246. throw new Error(error.detail || `HTTP ${response.status}`);
  3247. }
  3248. return response.json();
  3249. },
  3250. // Photos
  3251. getArchivePhotoUrl: (archiveId: number, filename: string) =>
  3252. withStreamToken(`${API_BASE}/archives/${archiveId}/photos/${encodeURIComponent(filename)}`),
  3253. uploadArchivePhoto: async (archiveId: number, file: File): Promise<{ status: string; filename: string; photos: string[] }> => {
  3254. const formData = new FormData();
  3255. formData.append('file', file);
  3256. const headers: Record<string, string> = {};
  3257. if (authToken) {
  3258. headers['Authorization'] = `Bearer ${authToken}`;
  3259. }
  3260. const response = await fetch(`${API_BASE}/archives/${archiveId}/photos`, {
  3261. headers,
  3262. method: 'POST',
  3263. body: formData,
  3264. });
  3265. if (!response.ok) {
  3266. const error = await response.json().catch(() => ({}));
  3267. throw new Error(error.detail || `HTTP ${response.status}`);
  3268. }
  3269. return response.json();
  3270. },
  3271. deleteArchivePhoto: (archiveId: number, filename: string) =>
  3272. request<{ status: string; photos: string[] | null }>(`/archives/${archiveId}/photos/${encodeURIComponent(filename)}`, {
  3273. method: 'DELETE',
  3274. }),
  3275. // Source 3MF (original slicer project file)
  3276. getSource3mfDownloadUrl: (archiveId: number) =>
  3277. `${API_BASE}/archives/${archiveId}/source`,
  3278. downloadSource3mf: async (archiveId: number): Promise<void> => {
  3279. const headers: Record<string, string> = {};
  3280. if (authToken) {
  3281. headers['Authorization'] = `Bearer ${authToken}`;
  3282. }
  3283. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, { headers });
  3284. if (!response.ok) {
  3285. const error = await response.json().catch(() => ({}));
  3286. throw new Error(error.detail || `HTTP ${response.status}`);
  3287. }
  3288. const disposition = response.headers.get('Content-Disposition');
  3289. const filename = parseContentDispositionFilename(disposition) || `source_${archiveId}.3mf`;
  3290. const blob = await response.blob();
  3291. const url = window.URL.createObjectURL(blob);
  3292. const a = document.createElement('a');
  3293. a.href = url;
  3294. a.download = filename;
  3295. document.body.appendChild(a);
  3296. a.click();
  3297. document.body.removeChild(a);
  3298. window.URL.revokeObjectURL(url);
  3299. },
  3300. getSource3mfForSlicer: (archiveId: number, filename: string) => {
  3301. // Sanitize: slicers url_decode() the entire URL, so / \ ? # in filenames break path routing
  3302. const safe = filename.replace(/[/\\?#]/g, '_');
  3303. return `${API_BASE}/archives/${archiveId}/source/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  3304. },
  3305. createSourceSlicerToken: (archiveId: number) =>
  3306. request<{ token: string }>(`/archives/${archiveId}/source-slicer-token`, { method: 'POST' }),
  3307. getSourceSlicerDownloadUrl: (archiveId: number, token: string, filename: string) => {
  3308. const safe = filename.replace(/[/\\?#]/g, '_');
  3309. return `${API_BASE}/archives/${archiveId}/source-dl/${token}/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  3310. },
  3311. uploadSource3mf: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  3312. const formData = new FormData();
  3313. formData.append('file', file);
  3314. const headers: Record<string, string> = {};
  3315. if (authToken) {
  3316. headers['Authorization'] = `Bearer ${authToken}`;
  3317. }
  3318. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, {
  3319. method: 'POST',
  3320. headers,
  3321. body: formData,
  3322. });
  3323. if (!response.ok) {
  3324. const error = await response.json().catch(() => ({}));
  3325. throw new Error(error.detail || `HTTP ${response.status}`);
  3326. }
  3327. return response.json();
  3328. },
  3329. deleteSource3mf: (archiveId: number) =>
  3330. request<{ status: string }>(`/archives/${archiveId}/source`, {
  3331. method: 'DELETE',
  3332. }),
  3333. // F3D (Fusion 360 design file)
  3334. getF3dDownloadUrl: (archiveId: number) =>
  3335. `${API_BASE}/archives/${archiveId}/f3d`,
  3336. downloadF3d: async (archiveId: number): Promise<void> => {
  3337. const headers: Record<string, string> = {};
  3338. if (authToken) {
  3339. headers['Authorization'] = `Bearer ${authToken}`;
  3340. }
  3341. const response = await fetch(`${API_BASE}/archives/${archiveId}/f3d`, { headers });
  3342. if (!response.ok) {
  3343. const error = await response.json().catch(() => ({}));
  3344. throw new Error(error.detail || `HTTP ${response.status}`);
  3345. }
  3346. const disposition = response.headers.get('Content-Disposition');
  3347. const filename = parseContentDispositionFilename(disposition) || `archive_${archiveId}.f3d`;
  3348. const blob = await response.blob();
  3349. const url = window.URL.createObjectURL(blob);
  3350. const a = document.createElement('a');
  3351. a.href = url;
  3352. a.download = filename;
  3353. document.body.appendChild(a);
  3354. a.click();
  3355. document.body.removeChild(a);
  3356. window.URL.revokeObjectURL(url);
  3357. },
  3358. uploadF3d: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  3359. const formData = new FormData();
  3360. formData.append('file', file);
  3361. const headers: Record<string, string> = {};
  3362. if (authToken) {
  3363. headers['Authorization'] = `Bearer ${authToken}`;
  3364. }
  3365. const response = await fetch(`${API_BASE}/archives/${archiveId}/f3d`, {
  3366. method: 'POST',
  3367. headers,
  3368. body: formData,
  3369. });
  3370. if (!response.ok) {
  3371. const error = await response.json().catch(() => ({}));
  3372. throw new Error(error.detail || `HTTP ${response.status}`);
  3373. }
  3374. return response.json();
  3375. },
  3376. deleteF3d: (archiveId: number) =>
  3377. request<{ status: string }>(`/archives/${archiveId}/f3d`, {
  3378. method: 'DELETE',
  3379. }),
  3380. // QR Code
  3381. getArchiveQRCodeUrl: (archiveId: number, size = 200) =>
  3382. withStreamToken(`${API_BASE}/archives/${archiveId}/qrcode?size=${size}`),
  3383. getArchiveCapabilities: (id: number) =>
  3384. request<{
  3385. has_model: boolean;
  3386. has_gcode: boolean;
  3387. has_source: boolean;
  3388. build_volume: { x: number; y: number; z: number };
  3389. filament_colors: string[];
  3390. }>(`/archives/${id}/capabilities`),
  3391. // Project Page
  3392. getArchiveProjectPage: (id: number) =>
  3393. request<{
  3394. title: string | null;
  3395. description: string | null;
  3396. designer: string | null;
  3397. designer_user_id: string | null;
  3398. license: string | null;
  3399. copyright: string | null;
  3400. creation_date: string | null;
  3401. modification_date: string | null;
  3402. origin: string | null;
  3403. profile_title: string | null;
  3404. profile_description: string | null;
  3405. profile_cover: string | null;
  3406. profile_user_id: string | null;
  3407. profile_user_name: string | null;
  3408. design_model_id: string | null;
  3409. design_profile_id: string | null;
  3410. design_region: string | null;
  3411. model_pictures: Array<{ name: string; path: string; url: string }>;
  3412. profile_pictures: Array<{ name: string; path: string; url: string }>;
  3413. thumbnails: Array<{ name: string; path: string; url: string }>;
  3414. }>(`/archives/${id}/project-page`),
  3415. updateArchiveProjectPage: (id: number, data: {
  3416. title?: string;
  3417. description?: string;
  3418. designer?: string;
  3419. license?: string;
  3420. copyright?: string;
  3421. profile_title?: string;
  3422. profile_description?: string;
  3423. }) =>
  3424. request(`/archives/${id}/project-page`, {
  3425. method: 'PATCH',
  3426. body: JSON.stringify(data),
  3427. }),
  3428. getArchiveProjectImageUrl: (archiveId: number, imagePath: string) =>
  3429. withStreamToken(`${API_BASE}/archives/${archiveId}/project-image/${encodeURIComponent(imagePath)}`),
  3430. getArchiveForSlicer: (id: number, filename: string) => {
  3431. const safe = filename.replace(/[/\\?#]/g, '_');
  3432. return `${API_BASE}/archives/${id}/file/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  3433. },
  3434. createArchiveSlicerToken: (archiveId: number) =>
  3435. request<{ token: string }>(`/archives/${archiveId}/slicer-token`, { method: 'POST' }),
  3436. getArchiveSlicerDownloadUrl: (archiveId: number, token: string, filename: string) => {
  3437. const safe = filename.replace(/[/\\?#]/g, '_');
  3438. return `${API_BASE}/archives/${archiveId}/dl/${token}/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  3439. },
  3440. getArchivePlates: (archiveId: number) =>
  3441. request<ArchivePlatesResponse>(`/archives/${archiveId}/plates`),
  3442. getArchiveFilamentRequirements: (archiveId: number, plateId?: number, requestId?: string) => {
  3443. const qs = new URLSearchParams();
  3444. if (plateId !== undefined) qs.set('plate_id', String(plateId));
  3445. if (requestId) qs.set('request_id', requestId);
  3446. return request<{
  3447. archive_id: number;
  3448. filename: string;
  3449. plate_id: number | null;
  3450. filaments: Array<{
  3451. slot_id: number;
  3452. type: string;
  3453. color: string;
  3454. used_grams: number;
  3455. used_meters: number;
  3456. used_in_plate?: boolean;
  3457. }>;
  3458. }>(`/archives/${archiveId}/filament-requirements${qs.toString() ? `?${qs}` : ''}`);
  3459. },
  3460. reprintArchive: (
  3461. archiveId: number,
  3462. printerId: number,
  3463. options?: {
  3464. plate_id?: number;
  3465. plate_name?: string;
  3466. ams_mapping?: number[];
  3467. timelapse?: boolean;
  3468. bed_levelling?: boolean;
  3469. flow_cali?: boolean;
  3470. vibration_cali?: boolean;
  3471. layer_inspect?: boolean;
  3472. use_ams?: boolean;
  3473. }
  3474. ) =>
  3475. request<BackgroundDispatchResponse>(
  3476. `/archives/${archiveId}/reprint?printer_id=${printerId}`,
  3477. {
  3478. method: 'POST',
  3479. headers: options ? { 'Content-Type': 'application/json' } : undefined,
  3480. body: options ? JSON.stringify(options) : undefined,
  3481. }
  3482. ),
  3483. uploadArchive: async (file: File, printerId?: number): Promise<Archive> => {
  3484. const formData = new FormData();
  3485. formData.append('file', file);
  3486. const url = printerId
  3487. ? `${API_BASE}/archives/upload?printer_id=${printerId}`
  3488. : `${API_BASE}/archives/upload`;
  3489. const headers: Record<string, string> = {};
  3490. if (authToken) {
  3491. headers['Authorization'] = `Bearer ${authToken}`;
  3492. }
  3493. const response = await fetch(url, {
  3494. method: 'POST',
  3495. headers,
  3496. body: formData,
  3497. });
  3498. if (!response.ok) {
  3499. const error = await response.json().catch(() => ({}));
  3500. throw new Error(error.detail || `HTTP ${response.status}`);
  3501. }
  3502. return response.json();
  3503. },
  3504. uploadArchivesBulk: async (files: File[], printerId?: number): Promise<BulkUploadResult> => {
  3505. const formData = new FormData();
  3506. files.forEach((file) => formData.append('files', file));
  3507. const url = printerId
  3508. ? `${API_BASE}/archives/upload-bulk?printer_id=${printerId}`
  3509. : `${API_BASE}/archives/upload-bulk`;
  3510. const headers: Record<string, string> = {};
  3511. if (authToken) {
  3512. headers['Authorization'] = `Bearer ${authToken}`;
  3513. }
  3514. const response = await fetch(url, {
  3515. method: 'POST',
  3516. headers,
  3517. body: formData,
  3518. });
  3519. if (!response.ok) {
  3520. const error = await response.json().catch(() => ({}));
  3521. throw new Error(error.detail || `HTTP ${response.status}`);
  3522. }
  3523. return response.json();
  3524. },
  3525. // Print Log
  3526. getPrintLog: (params?: {
  3527. search?: string;
  3528. printerId?: number;
  3529. username?: string;
  3530. status?: string;
  3531. dateFrom?: string;
  3532. dateTo?: string;
  3533. limit?: number;
  3534. offset?: number;
  3535. }) => {
  3536. const searchParams = new URLSearchParams();
  3537. if (params?.search) searchParams.set('search', params.search);
  3538. if (params?.printerId) searchParams.set('printer_id', String(params.printerId));
  3539. if (params?.username) searchParams.set('created_by_username', params.username);
  3540. if (params?.status) searchParams.set('status', params.status);
  3541. if (params?.dateFrom) searchParams.set('date_from', params.dateFrom);
  3542. if (params?.dateTo) searchParams.set('date_to', params.dateTo);
  3543. if (params?.limit) searchParams.set('limit', String(params.limit));
  3544. if (params?.offset !== undefined) searchParams.set('offset', String(params.offset));
  3545. return request<PrintLogResponse>(`/print-log/?${searchParams}`);
  3546. },
  3547. getPrintLogThumbnail: (id: number) => withStreamToken(`${API_BASE}/print-log/${id}/thumbnail`),
  3548. clearPrintLog: () =>
  3549. request<{ deleted: number }>('/print-log/', { method: 'DELETE' }),
  3550. // Settings
  3551. getSettings: () => request<AppSettings>('/settings/'),
  3552. getDefaultSidebarOrder: () => request<{ default_sidebar_order: string }>('/settings/default-sidebar-order'),
  3553. updateSettings: (data: AppSettingsUpdate) =>
  3554. request<AppSettings>('/settings/', {
  3555. method: 'PUT',
  3556. body: JSON.stringify(data),
  3557. }),
  3558. getMQTTStatus: () => request<MQTTStatus>('/settings/mqtt/status'),
  3559. resetSettings: () =>
  3560. request<AppSettings>('/settings/reset', { method: 'POST' }),
  3561. exportBackup: async (): Promise<{ blob: Blob; filename: string }> => {
  3562. // New simplified backup - complete database + all files
  3563. const url = `${API_BASE}/settings/backup`;
  3564. const headers: Record<string, string> = {};
  3565. if (authToken) {
  3566. headers['Authorization'] = `Bearer ${authToken}`;
  3567. }
  3568. const response = await fetch(url, { headers });
  3569. // Check for errors
  3570. if (!response.ok) {
  3571. const errorText = await response.text();
  3572. throw new Error(errorText || `Backup failed with status ${response.status}`);
  3573. }
  3574. // Get filename from Content-Disposition header
  3575. const contentDisposition = response.headers.get('Content-Disposition');
  3576. let filename = 'bambuddy-backup.zip';
  3577. if (contentDisposition) {
  3578. const match = contentDisposition.match(/filename=([^;]+)/);
  3579. if (match) filename = match[1].trim().replace(/^"(.*)"$/, '$1');
  3580. }
  3581. const blob = await response.blob();
  3582. return { blob, filename };
  3583. },
  3584. importBackup: async (file: File) => {
  3585. // New simplified restore - replaces database + all directories
  3586. const formData = new FormData();
  3587. formData.append('file', file);
  3588. const url = `${API_BASE}/settings/restore`;
  3589. const headers: Record<string, string> = {};
  3590. if (authToken) {
  3591. headers['Authorization'] = `Bearer ${authToken}`;
  3592. }
  3593. const response = await fetch(url, {
  3594. method: 'POST',
  3595. headers,
  3596. body: formData,
  3597. });
  3598. return response.json() as Promise<{
  3599. success: boolean;
  3600. message: string;
  3601. }>;
  3602. },
  3603. checkFfmpeg: () =>
  3604. request<{ installed: boolean; path: string | null }>('/settings/check-ffmpeg'),
  3605. getNetworkInterfaces: () =>
  3606. request<{ interfaces: NetworkInterface[] }>('/settings/network-interfaces'),
  3607. // Cloud
  3608. getCloudStatus: () => request<CloudAuthStatus>('/cloud/status'),
  3609. cloudLogin: (email: string, password: string, region = 'global') =>
  3610. request<CloudLoginResponse>('/cloud/login', {
  3611. method: 'POST',
  3612. body: JSON.stringify({ email, password, region }),
  3613. }),
  3614. cloudVerify: (email: string, code: string, tfaKey?: string, region: string = 'global') =>
  3615. request<CloudLoginResponse>('/cloud/verify', {
  3616. method: 'POST',
  3617. body: JSON.stringify({ email, code, tfa_key: tfaKey, region }),
  3618. }),
  3619. cloudSetToken: (access_token: string, region: string = 'global') =>
  3620. request<CloudAuthStatus>('/cloud/token', {
  3621. method: 'POST',
  3622. body: JSON.stringify({ access_token, region }),
  3623. }),
  3624. cloudLogout: () =>
  3625. request<{ success: boolean }>('/cloud/logout', { method: 'POST' }),
  3626. getCloudSettings: (version = '02.04.00.70') =>
  3627. request<SlicerSettingsResponse>(`/cloud/settings?version=${version}`),
  3628. getBuiltinFilaments: () =>
  3629. request<BuiltinFilament[]>('/cloud/builtin-filaments'),
  3630. getFilamentIdMap: () =>
  3631. request<Record<string, string>>('/cloud/filament-id-map'),
  3632. // MakerWorld URL-paste import flow.
  3633. getMakerworldStatus: () =>
  3634. request<MakerworldStatus>('/makerworld/status'),
  3635. resolveMakerworldUrl: (url: string) =>
  3636. request<MakerworldResolvedModel>('/makerworld/resolve', {
  3637. method: 'POST',
  3638. body: JSON.stringify({ url }),
  3639. }),
  3640. getMakerworldRecentImports: (limit = 10) =>
  3641. request<MakerworldRecentImport[]>(`/makerworld/recent-imports?limit=${limit}`),
  3642. importMakerworldInstance: (
  3643. model_id: number,
  3644. instance_id: number | null,
  3645. profile_id?: number | null,
  3646. folder_id?: number | null,
  3647. ) =>
  3648. request<MakerworldImportResponse>('/makerworld/import', {
  3649. method: 'POST',
  3650. body: JSON.stringify({
  3651. model_id,
  3652. instance_id: instance_id ?? null,
  3653. profile_id: profile_id ?? null,
  3654. folder_id: folder_id ?? null,
  3655. }),
  3656. }),
  3657. getCloudSettingDetail: (settingId: string) =>
  3658. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`),
  3659. createCloudSetting: (data: SlicerSettingCreate) =>
  3660. request<SlicerSettingDetail>('/cloud/settings', {
  3661. method: 'POST',
  3662. body: JSON.stringify(data),
  3663. }),
  3664. updateCloudSetting: (settingId: string, data: SlicerSettingUpdate) =>
  3665. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`, {
  3666. method: 'PUT',
  3667. body: JSON.stringify(data),
  3668. }),
  3669. deleteCloudSetting: (settingId: string) =>
  3670. request<SlicerSettingDeleteResponse>(`/cloud/settings/${settingId}`, {
  3671. method: 'DELETE',
  3672. }),
  3673. getCloudDevices: () => request<CloudDevice[]>('/cloud/devices'),
  3674. getCloudFields: (presetType: 'filament' | 'print' | 'process' | 'printer') =>
  3675. request<FieldDefinitionsResponse>(`/cloud/fields/${presetType}`),
  3676. getAllCloudFields: () =>
  3677. request<Record<string, FieldDefinitionsResponse>>('/cloud/fields'),
  3678. getFilamentInfo: (settingIds: string[]) =>
  3679. request<Record<string, { name: string; k: number | null }>>('/cloud/filament-info', {
  3680. method: 'POST',
  3681. body: JSON.stringify(settingIds),
  3682. }),
  3683. // Smart Plugs
  3684. getSmartPlugs: () => request<SmartPlug[]>('/smart-plugs/'),
  3685. getSmartPlug: (id: number) => request<SmartPlug>(`/smart-plugs/${id}`),
  3686. getSmartPlugByPrinter: (printerId: number) => request<SmartPlug | null>(`/smart-plugs/by-printer/${printerId}`),
  3687. getScriptPlugsByPrinter: (printerId: number) => request<SmartPlug[]>(`/smart-plugs/by-printer/${printerId}/scripts`),
  3688. createSmartPlug: (data: SmartPlugCreate) =>
  3689. request<SmartPlug>('/smart-plugs/', {
  3690. method: 'POST',
  3691. body: JSON.stringify(data),
  3692. }),
  3693. updateSmartPlug: (id: number, data: SmartPlugUpdate) =>
  3694. request<SmartPlug>(`/smart-plugs/${id}`, {
  3695. method: 'PATCH',
  3696. body: JSON.stringify(data),
  3697. }),
  3698. deleteSmartPlug: (id: number) =>
  3699. request<void>(`/smart-plugs/${id}`, { method: 'DELETE' }),
  3700. controlSmartPlug: (id: number, action: 'on' | 'off' | 'toggle') =>
  3701. request<{ success: boolean; action: string }>(`/smart-plugs/${id}/control`, {
  3702. method: 'POST',
  3703. body: JSON.stringify({ action }),
  3704. }),
  3705. getSmartPlugStatus: (id: number) =>
  3706. request<SmartPlugStatus>(`/smart-plugs/${id}/status`),
  3707. testSmartPlugConnection: (ip_address: string, username?: string | null, password?: string | null) =>
  3708. request<SmartPlugTestResult>('/smart-plugs/test-connection', {
  3709. method: 'POST',
  3710. body: JSON.stringify({ ip_address, username, password }),
  3711. }),
  3712. // Tasmota Discovery (auto-detects network)
  3713. startTasmotaScan: () =>
  3714. request<TasmotaScanStatus>('/smart-plugs/discover/scan', { method: 'POST' }),
  3715. getTasmotaScanStatus: () =>
  3716. request<TasmotaScanStatus>('/smart-plugs/discover/status'),
  3717. stopTasmotaScan: () =>
  3718. request<TasmotaScanStatus>('/smart-plugs/discover/stop', { method: 'POST' }),
  3719. getDiscoveredTasmotaDevices: () =>
  3720. request<DiscoveredTasmotaDevice[]>('/smart-plugs/discover/devices'),
  3721. // Home Assistant Integration
  3722. testHAConnection: (url: string, token: string) =>
  3723. request<HATestConnectionResult>('/smart-plugs/ha/test-connection', {
  3724. method: 'POST',
  3725. body: JSON.stringify({ url, token }),
  3726. }),
  3727. getHAEntities: (search?: string) => {
  3728. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  3729. return request<HAEntity[]>(`/smart-plugs/ha/entities${params}`);
  3730. },
  3731. getHASensorEntities: () =>
  3732. request<HASensorEntity[]>('/smart-plugs/ha/sensors'),
  3733. // REST smart plug
  3734. testRESTConnection: (url: string, method: string = 'GET', headers?: string | null) =>
  3735. request<{ success: boolean; error: string | null }>('/smart-plugs/rest/test-connection', {
  3736. method: 'POST',
  3737. body: JSON.stringify({ url, method, headers }),
  3738. }),
  3739. // Print Queue
  3740. getQueue: (printerId?: number, status?: string, targetModel?: string) => {
  3741. const params = new URLSearchParams();
  3742. if (printerId) params.set('printer_id', String(printerId));
  3743. if (status) params.set('status', status);
  3744. if (targetModel) params.set('target_model', targetModel);
  3745. return request<PrintQueueItem[]>(`/queue/?${params}`);
  3746. },
  3747. getQueueItem: (id: number) => request<PrintQueueItem>(`/queue/${id}`),
  3748. addToQueue: (data: PrintQueueItemCreate) =>
  3749. request<PrintQueueItem>('/queue/', {
  3750. method: 'POST',
  3751. body: JSON.stringify(data),
  3752. }),
  3753. updateQueueItem: (id: number, data: PrintQueueItemUpdate) =>
  3754. request<PrintQueueItem>(`/queue/${id}`, {
  3755. method: 'PATCH',
  3756. body: JSON.stringify(data),
  3757. }),
  3758. removeFromQueue: (id: number) =>
  3759. request<{ message: string }>(`/queue/${id}`, { method: 'DELETE' }),
  3760. reorderQueue: (items: { id: number; position: number }[]) =>
  3761. request<{ message: string }>('/queue/reorder', {
  3762. method: 'POST',
  3763. body: JSON.stringify({ items }),
  3764. }),
  3765. cancelQueueItem: (id: number) =>
  3766. request<{ message: string }>(`/queue/${id}/cancel`, { method: 'POST' }),
  3767. stopQueueItem: (id: number) =>
  3768. request<{ message: string }>(`/queue/${id}/stop`, { method: 'POST' }),
  3769. startQueueItem: (id: number) =>
  3770. request<PrintQueueItem>(`/queue/${id}/start`, { method: 'POST' }),
  3771. bulkUpdateQueue: (data: PrintQueueBulkUpdate) =>
  3772. request<PrintQueueBulkUpdateResponse>('/queue/bulk', {
  3773. method: 'PATCH',
  3774. body: JSON.stringify(data),
  3775. }),
  3776. // Batches
  3777. getBatches: (status?: string) => {
  3778. const params = status ? `?status=${status}` : '';
  3779. return request<PrintBatch[]>(`/queue/batches${params}`);
  3780. },
  3781. getBatch: (id: number) => request<PrintBatch>(`/queue/batches/${id}`),
  3782. cancelBatch: (id: number) =>
  3783. request<{ message: string }>(`/queue/batches/${id}`, { method: 'DELETE' }),
  3784. // K-Profiles
  3785. getKProfiles: (printerId: number, nozzleDiameter = '0.4') =>
  3786. request<KProfilesResponse>(`/printers/${printerId}/kprofiles/?nozzle_diameter=${nozzleDiameter}`),
  3787. setKProfile: (printerId: number, profile: KProfileCreate) =>
  3788. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/`, {
  3789. method: 'POST',
  3790. body: JSON.stringify(profile),
  3791. }),
  3792. deleteKProfile: (printerId: number, profile: KProfileDelete) =>
  3793. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/`, {
  3794. method: 'DELETE',
  3795. body: JSON.stringify(profile),
  3796. }),
  3797. setKProfilesBatch: (printerId: number, profiles: KProfileCreate[]) =>
  3798. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/batch`, {
  3799. method: 'POST',
  3800. body: JSON.stringify(profiles),
  3801. }),
  3802. // K-Profile Notes (stored locally, not on printer)
  3803. getKProfileNotes: (printerId: number) =>
  3804. request<KProfileNotesResponse>(`/printers/${printerId}/kprofiles/notes`),
  3805. setKProfileNote: (printerId: number, settingId: string, note: string) =>
  3806. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/notes`, {
  3807. method: 'PUT',
  3808. body: JSON.stringify({ setting_id: settingId, note }),
  3809. }),
  3810. deleteKProfileNote: (printerId: number, settingId: string) =>
  3811. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/notes/${encodeURIComponent(settingId)}`, {
  3812. method: 'DELETE',
  3813. }),
  3814. // Slot Preset Mappings
  3815. getSlotPresets: (printerId: number) =>
  3816. request<Record<number, SlotPresetMapping>>(`/printers/${printerId}/slot-presets`),
  3817. getSlotPreset: (printerId: number, amsId: number, trayId: number) =>
  3818. request<SlotPresetMapping | null>(`/printers/${printerId}/slot-presets/${amsId}/${trayId}`),
  3819. saveSlotPreset: (printerId: number, amsId: number, trayId: number, presetId: string, presetName: string, presetSource = 'cloud') =>
  3820. request<SlotPresetMapping>(`/printers/${printerId}/slot-presets/${amsId}/${trayId}?preset_id=${encodeURIComponent(presetId)}&preset_name=${encodeURIComponent(presetName)}&preset_source=${encodeURIComponent(presetSource)}`, {
  3821. method: 'PUT',
  3822. }),
  3823. deleteSlotPreset: (printerId: number, amsId: number, trayId: number) =>
  3824. request<{ success: boolean }>(`/printers/${printerId}/slot-presets/${amsId}/${trayId}`, {
  3825. method: 'DELETE',
  3826. }),
  3827. // AMS Labels (user-defined friendly names)
  3828. getAmsLabels: (printerId: number) =>
  3829. request<Record<number, string>>(`/printers/${printerId}/ams-labels`),
  3830. saveAmsLabel: (printerId: number, amsId: number, label: string, amsSerial = '') =>
  3831. request<{ ams_id: number; label: string }>(
  3832. `/printers/${printerId}/ams-labels/${amsId}`,
  3833. {
  3834. method: 'PUT',
  3835. body: JSON.stringify({ label, ams_serial: amsSerial }),
  3836. }
  3837. ),
  3838. deleteAmsLabel: (printerId: number, amsId: number, amsSerial = '') =>
  3839. request<{ success: boolean }>(`/printers/${printerId}/ams-labels/${amsId}?ams_serial=${encodeURIComponent(amsSerial)}`, {
  3840. method: 'DELETE',
  3841. }),
  3842. configureAmsSlot: (
  3843. printerId: number,
  3844. amsId: number,
  3845. trayId: number,
  3846. config: {
  3847. tray_info_idx: string;
  3848. tray_type: string;
  3849. tray_sub_brands: string;
  3850. tray_color: string;
  3851. nozzle_temp_min: number;
  3852. nozzle_temp_max: number;
  3853. cali_idx: number;
  3854. nozzle_diameter: string;
  3855. setting_id?: string;
  3856. kprofile_filament_id?: string;
  3857. kprofile_setting_id?: string;
  3858. k_value?: number;
  3859. }
  3860. ) => {
  3861. const params = new URLSearchParams({
  3862. tray_info_idx: config.tray_info_idx,
  3863. tray_type: config.tray_type,
  3864. tray_sub_brands: config.tray_sub_brands,
  3865. tray_color: config.tray_color,
  3866. nozzle_temp_min: config.nozzle_temp_min.toString(),
  3867. nozzle_temp_max: config.nozzle_temp_max.toString(),
  3868. cali_idx: config.cali_idx.toString(),
  3869. nozzle_diameter: config.nozzle_diameter,
  3870. });
  3871. if (config.setting_id) {
  3872. params.set('setting_id', config.setting_id);
  3873. }
  3874. if (config.kprofile_filament_id) {
  3875. params.set('kprofile_filament_id', config.kprofile_filament_id);
  3876. }
  3877. if (config.kprofile_setting_id) {
  3878. params.set('kprofile_setting_id', config.kprofile_setting_id);
  3879. }
  3880. if (config.k_value !== undefined && config.k_value > 0) {
  3881. params.set('k_value', config.k_value.toString());
  3882. }
  3883. return request<{ success: boolean; message: string }>(
  3884. `/printers/${printerId}/slots/${amsId}/${trayId}/configure?${params}`,
  3885. { method: 'POST' }
  3886. );
  3887. },
  3888. resetAmsSlot: (printerId: number, amsId: number, trayId: number) =>
  3889. request<{ success: boolean; message: string }>(
  3890. `/printers/${printerId}/ams/${amsId}/tray/${trayId}/reset`,
  3891. { method: 'POST' }
  3892. ),
  3893. // Filament Catalog (material types with cost/temp data)
  3894. listFilaments: () => request<Filament[]>('/filament-catalog/'),
  3895. getFilament: (id: number) => request<Filament>(`/filament-catalog/${id}`),
  3896. getFilamentsByType: (type: string) => request<Filament[]>(`/filament-catalog/by-type/${type}`),
  3897. // Notification Providers
  3898. getNotificationProviders: () => request<NotificationProvider[]>('/notifications/'),
  3899. getNotificationProvider: (id: number) => request<NotificationProvider>(`/notifications/${id}`),
  3900. createNotificationProvider: (data: NotificationProviderCreate) =>
  3901. request<NotificationProvider>('/notifications/', {
  3902. method: 'POST',
  3903. body: JSON.stringify(data),
  3904. }),
  3905. updateNotificationProvider: (id: number, data: NotificationProviderUpdate) =>
  3906. request<NotificationProvider>(`/notifications/${id}`, {
  3907. method: 'PATCH',
  3908. body: JSON.stringify(data),
  3909. }),
  3910. deleteNotificationProvider: (id: number) =>
  3911. request<{ message: string }>(`/notifications/${id}`, { method: 'DELETE' }),
  3912. testNotificationProvider: (id: number) =>
  3913. request<NotificationTestResponse>(`/notifications/${id}/test`, { method: 'POST' }),
  3914. testNotificationConfig: (data: NotificationTestRequest) =>
  3915. request<NotificationTestResponse>('/notifications/test-config', {
  3916. method: 'POST',
  3917. body: JSON.stringify(data),
  3918. }),
  3919. testAllNotificationProviders: () =>
  3920. request<{
  3921. tested: number;
  3922. success: number;
  3923. failed: number;
  3924. results: Array<{
  3925. provider_id: number;
  3926. provider_name: string;
  3927. provider_type: string;
  3928. success: boolean;
  3929. message: string;
  3930. }>;
  3931. }>('/notifications/test-all', { method: 'POST' }),
  3932. // Notification Templates
  3933. getNotificationTemplates: () => request<NotificationTemplate[]>('/notification-templates'),
  3934. getNotificationTemplate: (id: number) => request<NotificationTemplate>(`/notification-templates/${id}`),
  3935. updateNotificationTemplate: (id: number, data: NotificationTemplateUpdate) =>
  3936. request<NotificationTemplate>(`/notification-templates/${id}`, {
  3937. method: 'PUT',
  3938. body: JSON.stringify(data),
  3939. }),
  3940. resetNotificationTemplate: (id: number) =>
  3941. request<NotificationTemplate>(`/notification-templates/${id}/reset`, {
  3942. method: 'POST',
  3943. }),
  3944. getTemplateVariables: () => request<EventVariablesResponse[]>('/notification-templates/variables'),
  3945. previewTemplate: (data: TemplatePreviewRequest) =>
  3946. request<TemplatePreviewResponse>('/notification-templates/preview', {
  3947. method: 'POST',
  3948. body: JSON.stringify(data),
  3949. }),
  3950. // Notification Logs
  3951. getNotificationLogs: (params?: {
  3952. limit?: number;
  3953. offset?: number;
  3954. provider_id?: number;
  3955. event_type?: string;
  3956. success?: boolean;
  3957. days?: number;
  3958. }) => {
  3959. const searchParams = new URLSearchParams();
  3960. if (params?.limit) searchParams.set('limit', String(params.limit));
  3961. if (params?.offset) searchParams.set('offset', String(params.offset));
  3962. if (params?.provider_id) searchParams.set('provider_id', String(params.provider_id));
  3963. if (params?.event_type) searchParams.set('event_type', params.event_type);
  3964. if (params?.success !== undefined) searchParams.set('success', String(params.success));
  3965. if (params?.days) searchParams.set('days', String(params.days));
  3966. return request<NotificationLogEntry[]>(`/notifications/logs?${searchParams}`);
  3967. },
  3968. getNotificationLogStats: (days = 7) =>
  3969. request<NotificationLogStats>(`/notifications/logs/stats?days=${days}`),
  3970. clearNotificationLogs: (olderThanDays = 30) =>
  3971. request<{ deleted: number; message: string }>(
  3972. `/notifications/logs?older_than_days=${olderThanDays}`,
  3973. { method: 'DELETE' }
  3974. ),
  3975. // Spoolman Integration
  3976. getSpoolmanStatus: () => request<SpoolmanStatus>('/spoolman/status'),
  3977. connectSpoolman: () =>
  3978. request<{ success: boolean; message: string }>('/spoolman/connect', {
  3979. method: 'POST',
  3980. }),
  3981. disconnectSpoolman: () =>
  3982. request<{ success: boolean; message: string }>('/spoolman/disconnect', {
  3983. method: 'POST',
  3984. }),
  3985. syncPrinterAms: (printerId: number) =>
  3986. request<SpoolmanSyncResult>(`/spoolman/sync/${printerId}`, {
  3987. method: 'POST',
  3988. }),
  3989. syncAllPrintersAms: () =>
  3990. request<SpoolmanSyncResult>('/spoolman/sync-all', {
  3991. method: 'POST',
  3992. }),
  3993. getSpoolmanSpools: () =>
  3994. request<{ spools: unknown[] }>('/spoolman/spools'),
  3995. getSpoolmanFilaments: () =>
  3996. request<{ filaments: unknown[] }>('/spoolman/filaments'),
  3997. getUnlinkedSpools: () =>
  3998. request<UnlinkedSpool[]>('/spoolman/spools/unlinked'),
  3999. getLinkedSpools: () =>
  4000. request<LinkedSpoolsMap>('/spoolman/spools/linked'),
  4001. linkSpool: (
  4002. spoolId: number,
  4003. context: {
  4004. spoolTag: string;
  4005. printerId: number;
  4006. amsId: number;
  4007. trayId: number;
  4008. }
  4009. ) =>
  4010. request<{ success: boolean; message: string }>(`/spoolman/spools/${spoolId}/link`, {
  4011. method: 'POST',
  4012. body: JSON.stringify({
  4013. spool_tag: context.spoolTag,
  4014. printer_id: context.printerId,
  4015. ams_id: context.amsId,
  4016. tray_id: context.trayId,
  4017. }),
  4018. }),
  4019. unlinkSpool: (spoolId: number) =>
  4020. request<{ success: boolean; message: string }>(`/spoolman/spools/${spoolId}/unlink`, {
  4021. method: 'POST',
  4022. }),
  4023. getSpoolmanSettings: () =>
  4024. request<{ spoolman_enabled: string; spoolman_url: string; spoolman_sync_mode: string; spoolman_disable_weight_sync: string; spoolman_report_partial_usage: string; }>('/settings/spoolman'),
  4025. updateSpoolmanSettings: (data: { spoolman_enabled?: string; spoolman_url?: string; spoolman_sync_mode?: string; spoolman_disable_weight_sync?: string; spoolman_report_partial_usage?: string; }) =>
  4026. request<{ spoolman_enabled: string; spoolman_url: string; spoolman_sync_mode: string; spoolman_disable_weight_sync: string; spoolman_report_partial_usage: string; }>('/settings/spoolman', {
  4027. method: 'PUT',
  4028. body: JSON.stringify(data),
  4029. }),
  4030. // Inventory
  4031. getSpools: (includeArchived = false) =>
  4032. request<InventorySpool[]>(`/inventory/spools?include_archived=${includeArchived}`),
  4033. getSpool: (id: number) => request<InventorySpool>(`/inventory/spools/${id}`),
  4034. createSpool: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>) =>
  4035. request<InventorySpool>('/inventory/spools', {
  4036. method: 'POST',
  4037. body: JSON.stringify(data),
  4038. }),
  4039. bulkCreateSpools: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>, quantity: number) =>
  4040. request<InventorySpool[]>('/inventory/spools/bulk', {
  4041. method: 'POST',
  4042. body: JSON.stringify({ spool: data, quantity }),
  4043. }),
  4044. updateSpool: (id: number, data: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  4045. request<InventorySpool>(`/inventory/spools/${id}`, {
  4046. method: 'PATCH',
  4047. body: JSON.stringify(data),
  4048. }),
  4049. deleteSpool: (id: number) =>
  4050. request<{ status: string }>(`/inventory/spools/${id}`, { method: 'DELETE' }),
  4051. archiveSpool: (id: number) =>
  4052. request<InventorySpool>(`/inventory/spools/${id}/archive`, { method: 'POST' }),
  4053. restoreSpool: (id: number) =>
  4054. request<InventorySpool>(`/inventory/spools/${id}/restore`, { method: 'POST' }),
  4055. getSpoolKProfiles: (spoolId: number) =>
  4056. request<SpoolKProfile[]>(`/inventory/spools/${spoolId}/k-profiles`),
  4057. saveSpoolKProfiles: (spoolId: number, profiles: SpoolKProfileInput[]) =>
  4058. request<SpoolKProfile[]>(`/inventory/spools/${spoolId}/k-profiles`, {
  4059. method: 'PUT',
  4060. body: JSON.stringify(profiles),
  4061. }),
  4062. getAssignments: (printerId?: number) =>
  4063. request<SpoolAssignment[]>(`/inventory/assignments${printerId ? `?printer_id=${printerId}` : ''}`),
  4064. assignSpool: (data: { spool_id: number; printer_id: number; ams_id: number; tray_id: number }) =>
  4065. request<SpoolAssignment>('/inventory/assignments', {
  4066. method: 'POST',
  4067. body: JSON.stringify(data),
  4068. }),
  4069. unassignSpool: (printerId: number, amsId: number, trayId: number) =>
  4070. request<{ status: string }>(`/inventory/assignments/${printerId}/${amsId}/${trayId}`, { method: 'DELETE' }),
  4071. getSpoolCatalog: () =>
  4072. request<SpoolCatalogEntry[]>('/inventory/catalog'),
  4073. addCatalogEntry: (data: { name: string; weight: number }) =>
  4074. request<SpoolCatalogEntry>('/inventory/catalog', { method: 'POST', body: JSON.stringify(data) }),
  4075. updateCatalogEntry: (id: number, data: { name: string; weight: number }) =>
  4076. request<SpoolCatalogEntry>(`/inventory/catalog/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  4077. deleteCatalogEntry: (id: number) =>
  4078. request<{ status: string }>(`/inventory/catalog/${id}`, { method: 'DELETE' }),
  4079. bulkDeleteCatalogEntries: (ids: number[]) =>
  4080. request<{ deleted: number }>('/inventory/catalog/bulk-delete', { method: 'POST', body: JSON.stringify({ ids }) }),
  4081. resetSpoolCatalog: () =>
  4082. request<{ status: string }>('/inventory/catalog/reset', { method: 'POST' }),
  4083. getColorCatalog: () =>
  4084. request<ColorCatalogEntry[]>('/inventory/colors'),
  4085. getColorNameMap: () =>
  4086. request<{ colors: Record<string, string> }>('/inventory/colors/map'),
  4087. addColorEntry: (data: {
  4088. manufacturer: string;
  4089. color_name: string;
  4090. hex_color: string;
  4091. material: string | null;
  4092. extra_colors?: string | null;
  4093. effect_type?: string | null;
  4094. }) =>
  4095. request<ColorCatalogEntry>('/inventory/colors', { method: 'POST', body: JSON.stringify(data) }),
  4096. updateColorEntry: (
  4097. id: number,
  4098. data: {
  4099. manufacturer: string;
  4100. color_name: string;
  4101. hex_color: string;
  4102. material: string | null;
  4103. extra_colors?: string | null;
  4104. effect_type?: string | null;
  4105. },
  4106. ) => request<ColorCatalogEntry>(`/inventory/colors/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  4107. deleteColorEntry: (id: number) =>
  4108. request<{ status: string }>(`/inventory/colors/${id}`, { method: 'DELETE' }),
  4109. bulkDeleteColorEntries: (ids: number[]) =>
  4110. request<{ deleted: number }>('/inventory/colors/bulk-delete', { method: 'POST', body: JSON.stringify({ ids }) }),
  4111. resetColorCatalog: () =>
  4112. request<{ status: string }>('/inventory/colors/reset', { method: 'POST' }),
  4113. lookupColor: (manufacturer: string, colorName: string, material?: string) =>
  4114. request<ColorLookupResult>(`/inventory/colors/lookup?manufacturer=${encodeURIComponent(manufacturer)}&color_name=${encodeURIComponent(colorName)}${material ? `&material=${encodeURIComponent(material)}` : ''}`),
  4115. searchColors: (manufacturer?: string, material?: string) =>
  4116. request<ColorCatalogEntry[]>(`/inventory/colors/search?${manufacturer ? `manufacturer=${encodeURIComponent(manufacturer)}` : ''}${manufacturer && material ? '&' : ''}${material ? `material=${encodeURIComponent(material)}` : ''}`),
  4117. linkTagToSpool: (spoolId: number, data: { tag_uid?: string; tray_uuid?: string; tag_type?: string; data_origin?: string }) =>
  4118. request<InventorySpool>(`/inventory/spools/${spoolId}/link-tag`, {
  4119. method: 'PATCH',
  4120. body: JSON.stringify(data),
  4121. }),
  4122. getSpoolUsageHistory: (spoolId: number, limit = 50) =>
  4123. request<SpoolUsageRecord[]>(`/inventory/spools/${spoolId}/usage?limit=${limit}`),
  4124. getAllUsageHistory: (limit = 100, printerId?: number) =>
  4125. request<SpoolUsageRecord[]>(`/inventory/usage?limit=${limit}${printerId ? `&printer_id=${printerId}` : ''}`),
  4126. clearSpoolUsageHistory: (spoolId: number) =>
  4127. request<{ status: string }>(`/inventory/spools/${spoolId}/usage`, { method: 'DELETE' }),
  4128. syncWeightsFromAms: () =>
  4129. request<{ synced: number; skipped: number }>('/inventory/sync-ams-weights', { method: 'POST' }),
  4130. getFilamentPresets: () =>
  4131. request<SlicerSetting[]>('/cloud/filaments'),
  4132. // Updates
  4133. getVersion: () => request<VersionInfo>('/updates/version'),
  4134. checkForUpdates: () => request<UpdateCheckResult>('/updates/check'),
  4135. applyUpdate: () =>
  4136. request<{ success: boolean; message: string; status?: UpdateStatus; is_docker?: boolean }>('/updates/apply', {
  4137. method: 'POST',
  4138. }),
  4139. getUpdateStatus: () => request<UpdateStatus>('/updates/status'),
  4140. // Maintenance
  4141. getMaintenanceTypes: () => request<MaintenanceType[]>('/maintenance/types'),
  4142. createMaintenanceType: (data: MaintenanceTypeCreate) =>
  4143. request<MaintenanceType>('/maintenance/types', {
  4144. method: 'POST',
  4145. body: JSON.stringify(data),
  4146. }),
  4147. updateMaintenanceType: (id: number, data: Partial<MaintenanceTypeCreate>) =>
  4148. request<MaintenanceType>(`/maintenance/types/${id}`, {
  4149. method: 'PATCH',
  4150. body: JSON.stringify(data),
  4151. }),
  4152. deleteMaintenanceType: (id: number) =>
  4153. request<{ status: string }>(`/maintenance/types/${id}`, { method: 'DELETE' }),
  4154. restoreDefaultMaintenanceTypes: () =>
  4155. request<{ restored: number }>(`/maintenance/types/restore-defaults`, { method: 'POST' }),
  4156. getMaintenanceOverview: () => request<PrinterMaintenanceOverview[]>('/maintenance/overview'),
  4157. getPrinterMaintenance: (printerId: number) =>
  4158. request<PrinterMaintenanceOverview>(`/maintenance/printers/${printerId}`),
  4159. updateMaintenanceItem: (itemId: number, data: { custom_interval_hours?: number | null; custom_interval_type?: 'hours' | 'days' | null; enabled?: boolean }) =>
  4160. request<MaintenanceStatus>(`/maintenance/items/${itemId}`, {
  4161. method: 'PATCH',
  4162. body: JSON.stringify(data),
  4163. }),
  4164. performMaintenance: (itemId: number, notes?: string) =>
  4165. request<MaintenanceStatus>(`/maintenance/items/${itemId}/perform`, {
  4166. method: 'POST',
  4167. body: JSON.stringify({ notes }),
  4168. }),
  4169. getMaintenanceHistory: (itemId: number) =>
  4170. request<MaintenanceHistory[]>(`/maintenance/items/${itemId}/history`),
  4171. getMaintenanceSummary: () => request<MaintenanceSummary>('/maintenance/summary'),
  4172. setPrinterHours: (printerId: number, totalHours: number) =>
  4173. request<{ printer_id: number; total_hours: number; archive_hours: number; offset_hours: number }>(
  4174. `/maintenance/printers/${printerId}/hours?total_hours=${totalHours}`,
  4175. { method: 'PATCH' }
  4176. ),
  4177. assignMaintenanceType: (printerId: number, typeId: number) =>
  4178. request<MaintenanceStatus>(`/maintenance/printers/${printerId}/assign/${typeId}`, {
  4179. method: 'POST',
  4180. }),
  4181. removeMaintenanceItem: (itemId: number) =>
  4182. request<{ status: string }>(`/maintenance/items/${itemId}`, {
  4183. method: 'DELETE',
  4184. }),
  4185. // Camera
  4186. getCameraStreamToken: () =>
  4187. request<{ token: string }>('/printers/camera/stream-token', { method: 'POST' }),
  4188. // Long-lived camera-stream tokens (#1108)
  4189. createLongLivedCameraToken: (payload: { name: string; expires_in_days: number }) =>
  4190. request<LongLivedCameraToken>('/auth/tokens', {
  4191. method: 'POST',
  4192. body: JSON.stringify({ ...payload, scope: 'camera_stream' }),
  4193. }),
  4194. listMyLongLivedCameraTokens: () =>
  4195. request<LongLivedCameraToken[]>('/auth/tokens'),
  4196. listAllLongLivedCameraTokens: () =>
  4197. request<LongLivedCameraToken[]>('/auth/tokens/all'),
  4198. listLongLivedCameraTokensForUser: (userId: number) =>
  4199. request<LongLivedCameraToken[]>(`/auth/tokens?user_id=${userId}`),
  4200. revokeLongLivedCameraToken: (tokenId: number) =>
  4201. request<void>(`/auth/tokens/${tokenId}`, { method: 'DELETE' }),
  4202. getCameraStreamUrl: (printerId: number, fps = 10) =>
  4203. withStreamToken(`${API_BASE}/printers/${printerId}/camera/stream?fps=${fps}`),
  4204. getCameraSnapshotUrl: (printerId: number) =>
  4205. withStreamToken(`${API_BASE}/printers/${printerId}/camera/snapshot`),
  4206. testCameraConnection: (printerId: number) =>
  4207. request<{ success: boolean; message?: string; error?: string }>(`/printers/${printerId}/camera/test`),
  4208. getCameraStatus: (printerId: number) =>
  4209. request<{ active: boolean; stalled: boolean }>(`/printers/${printerId}/camera/status`),
  4210. // Plate Detection - Multi-reference calibration (stores up to 5 references per printer)
  4211. checkPlateEmpty: (printerId: number, options?: { useExternal?: boolean; includeDebugImage?: boolean }) => {
  4212. const params = new URLSearchParams();
  4213. params.set('use_external', String(options?.useExternal ?? false));
  4214. params.set('include_debug_image', String(options?.includeDebugImage ?? false));
  4215. return request<PlateDetectionResult>(
  4216. `/printers/${printerId}/camera/check-plate?${params.toString()}`
  4217. );
  4218. },
  4219. getPlateDetectionStatus: (printerId: number) => {
  4220. return request<PlateDetectionStatus & { chamber_light?: boolean }>(
  4221. `/printers/${printerId}/camera/plate-detection/status`
  4222. );
  4223. },
  4224. calibratePlateDetection: (printerId: number, options?: { label?: string; useExternal?: boolean }) => {
  4225. const params = new URLSearchParams();
  4226. if (options?.label) params.set('label', options.label);
  4227. params.set('use_external', String(options?.useExternal ?? false));
  4228. return request<CalibrationResult & { index: number }>(
  4229. `/printers/${printerId}/camera/plate-detection/calibrate?${params.toString()}`,
  4230. { method: 'POST' }
  4231. );
  4232. },
  4233. deletePlateCalibration: (printerId: number) => {
  4234. return request<CalibrationResult>(
  4235. `/printers/${printerId}/camera/plate-detection/calibrate`,
  4236. { method: 'DELETE' }
  4237. );
  4238. },
  4239. getPlateReferences: (printerId: number) => {
  4240. return request<{
  4241. references: PlateReference[];
  4242. max_references: number;
  4243. }>(`/printers/${printerId}/camera/plate-detection/references`);
  4244. },
  4245. getPlateReferenceThumbnailUrl: (printerId: number, index: number) =>
  4246. withStreamToken(`${API_BASE}/printers/${printerId}/camera/plate-detection/references/${index}/thumbnail`),
  4247. updatePlateReferenceLabel: (printerId: number, index: number, label: string) => {
  4248. const params = new URLSearchParams();
  4249. params.set('label', label);
  4250. return request<{ success: boolean; index: number; label: string }>(
  4251. `/printers/${printerId}/camera/plate-detection/references/${index}?${params.toString()}`,
  4252. { method: 'PUT' }
  4253. );
  4254. },
  4255. deletePlateReference: (printerId: number, index: number) => {
  4256. return request<{ success: boolean; message: string }>(
  4257. `/printers/${printerId}/camera/plate-detection/references/${index}`,
  4258. { method: 'DELETE' }
  4259. );
  4260. },
  4261. // External Links
  4262. getExternalLinks: () => request<ExternalLink[]>('/external-links/'),
  4263. getExternalLink: (id: number) => request<ExternalLink>(`/external-links/${id}`),
  4264. createExternalLink: (data: ExternalLinkCreate) =>
  4265. request<ExternalLink>('/external-links/', {
  4266. method: 'POST',
  4267. body: JSON.stringify(data),
  4268. }),
  4269. updateExternalLink: (id: number, data: ExternalLinkUpdate) =>
  4270. request<ExternalLink>(`/external-links/${id}`, {
  4271. method: 'PATCH',
  4272. body: JSON.stringify(data),
  4273. }),
  4274. deleteExternalLink: (id: number) =>
  4275. request<{ message: string }>(`/external-links/${id}`, { method: 'DELETE' }),
  4276. reorderExternalLinks: (ids: number[]) =>
  4277. request<ExternalLink[]>('/external-links/reorder', {
  4278. method: 'PUT',
  4279. body: JSON.stringify({ ids }),
  4280. }),
  4281. uploadExternalLinkIcon: async (id: number, file: File): Promise<ExternalLink> => {
  4282. const formData = new FormData();
  4283. formData.append('file', file);
  4284. const headers: Record<string, string> = {};
  4285. if (authToken) {
  4286. headers['Authorization'] = `Bearer ${authToken}`;
  4287. }
  4288. const response = await fetch(`${API_BASE}/external-links/${id}/icon`, {
  4289. method: 'POST',
  4290. headers,
  4291. body: formData,
  4292. });
  4293. if (!response.ok) {
  4294. const error = await response.json().catch(() => ({}));
  4295. throw new Error(error.detail || `HTTP ${response.status}`);
  4296. }
  4297. return response.json();
  4298. },
  4299. deleteExternalLinkIcon: (id: number) =>
  4300. request<ExternalLink>(`/external-links/${id}/icon`, { method: 'DELETE' }),
  4301. getExternalLinkIconUrl: (id: number) => withStreamToken(`${API_BASE}/external-links/${id}/icon`),
  4302. // Projects
  4303. getProjects: (status?: string) => {
  4304. const params = new URLSearchParams();
  4305. if (status) params.set('status', status);
  4306. return request<ProjectListItem[]>(`/projects/?${params}`);
  4307. },
  4308. getProject: (id: number) => request<Project>(`/projects/${id}`),
  4309. createProject: (data: ProjectCreate) =>
  4310. request<Project>('/projects/', {
  4311. method: 'POST',
  4312. body: JSON.stringify(data),
  4313. }),
  4314. updateProject: (id: number, data: ProjectUpdate) =>
  4315. request<Project>(`/projects/${id}`, {
  4316. method: 'PATCH',
  4317. body: JSON.stringify(data),
  4318. }),
  4319. deleteProject: (id: number) =>
  4320. request<{ message: string }>(`/projects/${id}`, { method: 'DELETE' }),
  4321. getProjectArchives: (id: number, limit = 100, offset = 0) =>
  4322. request<Archive[]>(`/projects/${id}/archives?limit=${limit}&offset=${offset}`),
  4323. addArchivesToProject: (projectId: number, archiveIds: number[]) =>
  4324. request<{ message: string }>(`/projects/${projectId}/add-archives`, {
  4325. method: 'POST',
  4326. body: JSON.stringify({ archive_ids: archiveIds }),
  4327. }),
  4328. removeArchivesFromProject: (projectId: number, archiveIds: number[]) =>
  4329. request<{ message: string }>(`/projects/${projectId}/remove-archives`, {
  4330. method: 'POST',
  4331. body: JSON.stringify({ archive_ids: archiveIds }),
  4332. }),
  4333. addQueueItemsToProject: (projectId: number, queueItemIds: number[]) =>
  4334. request<{ message: string }>(`/projects/${projectId}/add-queue`, {
  4335. method: 'POST',
  4336. body: JSON.stringify({ queue_item_ids: queueItemIds }),
  4337. }),
  4338. // Project Attachments
  4339. uploadProjectAttachment: async (projectId: number, file: File): Promise<{
  4340. status: string;
  4341. filename: string;
  4342. original_name: string;
  4343. attachments: ProjectAttachment[];
  4344. }> => {
  4345. const formData = new FormData();
  4346. formData.append('file', file);
  4347. const headers: Record<string, string> = {};
  4348. if (authToken) {
  4349. headers['Authorization'] = `Bearer ${authToken}`;
  4350. }
  4351. const response = await fetch(`${API_BASE}/projects/${projectId}/attachments`, {
  4352. method: 'POST',
  4353. headers,
  4354. body: formData,
  4355. });
  4356. if (!response.ok) {
  4357. const error = await response.json().catch(() => ({}));
  4358. throw new Error(error.detail || `HTTP ${response.status}`);
  4359. }
  4360. return response.json();
  4361. },
  4362. getProjectAttachmentUrl: (projectId: number, filename: string) =>
  4363. `${API_BASE}/projects/${projectId}/attachments/${encodeURIComponent(filename)}`,
  4364. deleteProjectAttachment: (projectId: number, filename: string) =>
  4365. request<{ status: string; message: string; attachments: ProjectAttachment[] | null }>(
  4366. `/projects/${projectId}/attachments/${encodeURIComponent(filename)}`,
  4367. { method: 'DELETE' }
  4368. ),
  4369. // #1155: Cover image
  4370. // Browsers can't attach `Authorization: Bearer ...` to `<img src>`, so we
  4371. // append the stream-token query string the same way archive thumbnails do.
  4372. getProjectCoverImageUrl: (projectId: number) =>
  4373. withStreamToken(`${API_BASE}/projects/${projectId}/cover-image`),
  4374. uploadProjectCoverImage: async (
  4375. projectId: number,
  4376. file: File
  4377. ): Promise<{ status: string; filename: string; size: number }> => {
  4378. const formData = new FormData();
  4379. formData.append('file', file);
  4380. const headers: Record<string, string> = {};
  4381. if (authToken) {
  4382. headers['Authorization'] = `Bearer ${authToken}`;
  4383. }
  4384. const response = await fetch(`${API_BASE}/projects/${projectId}/cover-image`, {
  4385. method: 'POST',
  4386. headers,
  4387. body: formData,
  4388. });
  4389. if (!response.ok) {
  4390. const error = await response.json().catch(() => ({}));
  4391. throw new Error(error.detail || `HTTP ${response.status}`);
  4392. }
  4393. return response.json();
  4394. },
  4395. deleteProjectCoverImage: (projectId: number) =>
  4396. request<{ status: string }>(`/projects/${projectId}/cover-image`, { method: 'DELETE' }),
  4397. // BOM (Bill of Materials)
  4398. getProjectBOM: (projectId: number) =>
  4399. request<BOMItem[]>(`/projects/${projectId}/bom`),
  4400. createBOMItem: (projectId: number, data: BOMItemCreate) =>
  4401. request<BOMItem>(`/projects/${projectId}/bom`, {
  4402. method: 'POST',
  4403. body: JSON.stringify(data),
  4404. }),
  4405. updateBOMItem: (projectId: number, itemId: number, data: BOMItemUpdate) =>
  4406. request<BOMItem>(`/projects/${projectId}/bom/${itemId}`, {
  4407. method: 'PATCH',
  4408. body: JSON.stringify(data),
  4409. }),
  4410. deleteBOMItem: (projectId: number, itemId: number) =>
  4411. request<{ status: string; message: string }>(`/projects/${projectId}/bom/${itemId}`, {
  4412. method: 'DELETE',
  4413. }),
  4414. // Templates
  4415. getTemplates: () => request<ProjectListItem[]>('/projects/templates/'),
  4416. createTemplateFromProject: (projectId: number) =>
  4417. request<Project>(`/projects/${projectId}/create-template`, { method: 'POST' }),
  4418. createProjectFromTemplate: (templateId: number, name?: string) =>
  4419. request<Project>(`/projects/from-template/${templateId}${name ? `?name=${encodeURIComponent(name)}` : ''}`, {
  4420. method: 'POST',
  4421. }),
  4422. // Timeline
  4423. getProjectTimeline: (projectId: number, limit = 50) =>
  4424. request<TimelineEvent[]>(`/projects/${projectId}/timeline?limit=${limit}`),
  4425. // Project Export/Import
  4426. exportProjectJson: (projectId: number) =>
  4427. request<ProjectExport>(`/projects/${projectId}/export?format=json`),
  4428. importProject: (data: ProjectImport) =>
  4429. request<Project>('/projects/import', {
  4430. method: 'POST',
  4431. body: JSON.stringify(data),
  4432. }),
  4433. importProjectFile: async (file: File): Promise<Project> => {
  4434. const formData = new FormData();
  4435. formData.append('file', file);
  4436. const headers: Record<string, string> = {};
  4437. if (authToken) {
  4438. headers['Authorization'] = `Bearer ${authToken}`;
  4439. }
  4440. const response = await fetch(`${API_BASE}/projects/import/file`, {
  4441. method: 'POST',
  4442. headers,
  4443. body: formData,
  4444. });
  4445. if (!response.ok) {
  4446. const error = await response.json().catch(() => ({}));
  4447. throw new Error(error.detail || `HTTP ${response.status}`);
  4448. }
  4449. return response.json();
  4450. },
  4451. exportProjectZip: async (projectId: number): Promise<{ blob: Blob; filename: string }> => {
  4452. const headers: Record<string, string> = {};
  4453. if (authToken) {
  4454. headers['Authorization'] = `Bearer ${authToken}`;
  4455. }
  4456. const response = await fetch(`${API_BASE}/projects/${projectId}/export`, {
  4457. headers,
  4458. });
  4459. if (!response.ok) {
  4460. const error = await response.json().catch(() => ({}));
  4461. throw new Error(error.detail || `HTTP ${response.status}`);
  4462. }
  4463. const contentDisposition = response.headers.get('Content-Disposition');
  4464. const filename = parseContentDispositionFilename(contentDisposition) || `project_${projectId}.zip`;
  4465. const blob = await response.blob();
  4466. return { blob, filename };
  4467. },
  4468. // API Keys
  4469. getAPIKeys: () => request<APIKey[]>('/api-keys/'),
  4470. createAPIKey: (data: APIKeyCreate) =>
  4471. request<APIKeyCreateResponse>('/api-keys/', {
  4472. method: 'POST',
  4473. body: JSON.stringify(data),
  4474. }),
  4475. updateAPIKey: (id: number, data: APIKeyUpdate) =>
  4476. request<APIKey>(`/api-keys/${id}`, {
  4477. method: 'PATCH',
  4478. body: JSON.stringify(data),
  4479. }),
  4480. deleteAPIKey: (id: number) =>
  4481. request<{ message: string }>(`/api-keys/${id}`, { method: 'DELETE' }),
  4482. // AMS History
  4483. getAMSHistory: (printerId: number, amsId: number, hours = 24) =>
  4484. request<AMSHistoryResponse>(`/ams-history/${printerId}/${amsId}?hours=${hours}`),
  4485. // System Info
  4486. getSystemInfo: () => request<SystemInfo>('/system/info'),
  4487. getStorageUsage: (options?: { refresh?: boolean }) => {
  4488. const params = new URLSearchParams();
  4489. if (options?.refresh) {
  4490. params.set('refresh', 'true');
  4491. }
  4492. const query = params.toString();
  4493. return request<StorageUsageResponse>(`/system/storage-usage${query ? `?${query}` : ''}`);
  4494. },
  4495. // Library (File Manager)
  4496. getLibraryFolders: () => request<LibraryFolderTree[]>('/library/folders'),
  4497. createLibraryFolder: (data: LibraryFolderCreate) =>
  4498. request<LibraryFolder>('/library/folders', {
  4499. method: 'POST',
  4500. body: JSON.stringify(data),
  4501. }),
  4502. updateLibraryFolder: (id: number, data: LibraryFolderUpdate) =>
  4503. request<LibraryFolder>(`/library/folders/${id}`, {
  4504. method: 'PUT',
  4505. body: JSON.stringify(data),
  4506. }),
  4507. deleteLibraryFolder: (id: number) =>
  4508. request<{ status: string; message: string }>(`/library/folders/${id}`, { method: 'DELETE' }),
  4509. createExternalFolder: (data: ExternalFolderCreate) =>
  4510. request<LibraryFolder>('/library/folders/external', {
  4511. method: 'POST',
  4512. body: JSON.stringify(data),
  4513. }),
  4514. scanExternalFolder: (folderId: number) =>
  4515. request<{ status: string; added: number; removed: number }>(`/library/folders/${folderId}/scan`, {
  4516. method: 'POST',
  4517. }),
  4518. getLibraryFoldersByProject: (projectId: number) =>
  4519. request<LibraryFolder[]>(`/library/folders/by-project/${projectId}`),
  4520. getLibraryFoldersByArchive: (archiveId: number) =>
  4521. request<LibraryFolder[]>(`/library/folders/by-archive/${archiveId}`),
  4522. getLibraryFiles: (folderId?: number | null, includeRoot = true, projectId?: number) => {
  4523. const params = new URLSearchParams();
  4524. if (folderId !== undefined && folderId !== null) {
  4525. params.set('folder_id', String(folderId));
  4526. }
  4527. if (projectId !== undefined) {
  4528. params.set('project_id', String(projectId));
  4529. }
  4530. params.set('include_root', String(includeRoot));
  4531. return request<LibraryFileListItem[]>(`/library/files?${params}`);
  4532. },
  4533. getLibraryFile: (id: number) => request<LibraryFile>(`/library/files/${id}`),
  4534. uploadLibraryFile: async (
  4535. file: File,
  4536. folderId?: number | null,
  4537. generateStlThumbnails: boolean = true
  4538. ): Promise<LibraryFileUploadResponse> => {
  4539. const formData = new FormData();
  4540. formData.append('file', file);
  4541. const params = new URLSearchParams();
  4542. if (folderId) params.set('folder_id', String(folderId));
  4543. params.set('generate_stl_thumbnails', String(generateStlThumbnails));
  4544. const headers: Record<string, string> = {};
  4545. if (authToken) {
  4546. headers['Authorization'] = `Bearer ${authToken}`;
  4547. }
  4548. const response = await fetch(`${API_BASE}/library/files?${params}`, {
  4549. method: 'POST',
  4550. headers,
  4551. body: formData,
  4552. });
  4553. if (!response.ok) {
  4554. const error = await response.json().catch(() => ({}));
  4555. throw new Error(error.detail || `HTTP ${response.status}`);
  4556. }
  4557. return response.json();
  4558. },
  4559. extractZipFile: async (
  4560. file: File,
  4561. folderId?: number | null,
  4562. preserveStructure: boolean = true,
  4563. createFolderFromZip: boolean = false,
  4564. generateStlThumbnails: boolean = true
  4565. ): Promise<ZipExtractResponse> => {
  4566. const formData = new FormData();
  4567. formData.append('file', file);
  4568. const params = new URLSearchParams();
  4569. if (folderId) params.set('folder_id', String(folderId));
  4570. params.set('preserve_structure', String(preserveStructure));
  4571. params.set('create_folder_from_zip', String(createFolderFromZip));
  4572. params.set('generate_stl_thumbnails', String(generateStlThumbnails));
  4573. const headers: Record<string, string> = {};
  4574. if (authToken) {
  4575. headers['Authorization'] = `Bearer ${authToken}`;
  4576. }
  4577. const response = await fetch(`${API_BASE}/library/files/extract-zip?${params}`, {
  4578. method: 'POST',
  4579. headers,
  4580. body: formData,
  4581. });
  4582. if (!response.ok) {
  4583. const error = await response.json().catch(() => ({}));
  4584. throw new Error(error.detail || `HTTP ${response.status}`);
  4585. }
  4586. return response.json();
  4587. },
  4588. updateLibraryFile: (id: number, data: LibraryFileUpdate) =>
  4589. request<LibraryFile>(`/library/files/${id}`, {
  4590. method: 'PUT',
  4591. body: JSON.stringify(data),
  4592. }),
  4593. deleteLibraryFile: (id: number) =>
  4594. request<{ status: string; message: string; trashed: boolean }>(`/library/files/${id}`, { method: 'DELETE' }),
  4595. // ========== Library Trash (#1008) ==========
  4596. previewLibraryPurge: (olderThanDays: number, includeNeverPrinted: boolean = true) =>
  4597. request<LibraryPurgePreview>(
  4598. `/library/purge/preview?older_than_days=${olderThanDays}&include_never_printed=${includeNeverPrinted}`,
  4599. ),
  4600. executeLibraryPurge: (olderThanDays: number, includeNeverPrinted: boolean = true) =>
  4601. request<{ moved_to_trash: number }>('/library/purge', {
  4602. method: 'POST',
  4603. body: JSON.stringify({ older_than_days: olderThanDays, include_never_printed: includeNeverPrinted }),
  4604. }),
  4605. listLibraryTrash: (limit: number = 100, offset: number = 0) =>
  4606. request<LibraryTrashListResponse>(`/library/trash?limit=${limit}&offset=${offset}`),
  4607. restoreLibraryTrash: (fileId: number) =>
  4608. request<{ status: string; id: number }>(`/library/trash/${fileId}/restore`, { method: 'POST' }),
  4609. hardDeleteLibraryTrash: (fileId: number) =>
  4610. request<{ status: string }>(`/library/trash/${fileId}`, { method: 'DELETE' }),
  4611. emptyLibraryTrash: () => request<{ deleted: number }>('/library/trash', { method: 'DELETE' }),
  4612. getLibraryTrashSettings: () =>
  4613. request<LibraryTrashSettings>('/library/trash/settings'),
  4614. updateLibraryTrashSettings: (body: LibraryTrashSettings) =>
  4615. request<LibraryTrashSettings>('/library/trash/settings', {
  4616. method: 'PUT',
  4617. body: JSON.stringify(body),
  4618. }),
  4619. getLibraryFileDownloadUrl: (id: number) => `${API_BASE}/library/files/${id}/download`,
  4620. createLibrarySlicerToken: (fileId: number) =>
  4621. request<{ token: string }>(`/library/files/${fileId}/slicer-token`, { method: 'POST' }),
  4622. getLibrarySlicerDownloadUrl: (fileId: number, token: string, filename: string) =>
  4623. `${API_BASE}/library/files/${fileId}/dl/${token}/${encodeURIComponent(filename)}`,
  4624. downloadLibraryFile: async (id: number, filename?: string): Promise<void> => {
  4625. const headers: Record<string, string> = {};
  4626. if (authToken) {
  4627. headers['Authorization'] = `Bearer ${authToken}`;
  4628. }
  4629. const response = await fetch(`${API_BASE}/library/files/${id}/download`, { headers });
  4630. if (!response.ok) {
  4631. const error = await response.json().catch(() => ({}));
  4632. throw new Error(error.detail || `HTTP ${response.status}`);
  4633. }
  4634. const disposition = response.headers.get('Content-Disposition');
  4635. const downloadFilename = parseContentDispositionFilename(disposition) || filename || `file_${id}`;
  4636. const blob = await response.blob();
  4637. const url = window.URL.createObjectURL(blob);
  4638. const a = document.createElement('a');
  4639. a.href = url;
  4640. a.download = downloadFilename;
  4641. document.body.appendChild(a);
  4642. a.click();
  4643. document.body.removeChild(a);
  4644. window.URL.revokeObjectURL(url);
  4645. },
  4646. getLibraryFileThumbnailUrl: (id: number) => withStreamToken(`${API_BASE}/library/files/${id}/thumbnail`),
  4647. getLibraryFilePlateThumbnail: (id: number, plateIndex: number) =>
  4648. withStreamToken(`${API_BASE}/library/files/${id}/plate-thumbnail/${plateIndex}`),
  4649. getLibraryFileGcodeUrl: (id: number) => `${API_BASE}/library/files/${id}/gcode`,
  4650. moveLibraryFiles: (fileIds: number[], folderId: number | null) =>
  4651. request<{ status: string; moved: number }>('/library/files/move', {
  4652. method: 'POST',
  4653. body: JSON.stringify({ file_ids: fileIds, folder_id: folderId }),
  4654. }),
  4655. bulkDeleteLibrary: (fileIds: number[], folderIds: number[]) =>
  4656. request<{ deleted_files: number; deleted_folders: number }>('/library/bulk-delete', {
  4657. method: 'POST',
  4658. body: JSON.stringify({ file_ids: fileIds, folder_ids: folderIds }),
  4659. }),
  4660. getLibraryStats: () => request<LibraryStats>('/library/stats'),
  4661. batchGenerateStlThumbnails: (options: {
  4662. file_ids?: number[];
  4663. folder_id?: number;
  4664. all_missing?: boolean;
  4665. }) =>
  4666. request<BatchThumbnailResponse>('/library/generate-stl-thumbnails', {
  4667. method: 'POST',
  4668. body: JSON.stringify(options),
  4669. }),
  4670. addLibraryFilesToQueue: (fileIds: number[]) =>
  4671. request<AddToQueueResponse>('/library/files/add-to-queue', {
  4672. method: 'POST',
  4673. body: JSON.stringify({ file_ids: fileIds }),
  4674. }),
  4675. printLibraryFile: (
  4676. fileId: number,
  4677. printerId: number,
  4678. options?: {
  4679. plate_id?: number;
  4680. plate_name?: string;
  4681. ams_mapping?: number[];
  4682. bed_levelling?: boolean;
  4683. flow_cali?: boolean;
  4684. vibration_cali?: boolean;
  4685. layer_inspect?: boolean;
  4686. timelapse?: boolean;
  4687. use_ams?: boolean;
  4688. project_id?: number;
  4689. cleanup_library_after_dispatch?: boolean;
  4690. }
  4691. ) =>
  4692. request<BackgroundDispatchResponse>(
  4693. `/library/files/${fileId}/print?printer_id=${printerId}`,
  4694. {
  4695. method: 'POST',
  4696. body: options ? JSON.stringify(options) : undefined,
  4697. }
  4698. ),
  4699. cancelBackgroundDispatchJob: (jobId: number) =>
  4700. request<{
  4701. status: 'cancelled' | 'cancelling';
  4702. job_id: number;
  4703. source_name: string;
  4704. printer_id: number;
  4705. printer_name: string;
  4706. }>(`/background-dispatch/${jobId}`, {
  4707. method: 'DELETE',
  4708. }),
  4709. getLibraryFilePlates: (fileId: number) =>
  4710. request<LibraryFilePlatesResponse>(`/library/files/${fileId}/plates`),
  4711. getLibraryFileFilamentRequirements: (fileId: number, plateId?: number, requestId?: string) => {
  4712. const qs = new URLSearchParams();
  4713. if (plateId !== undefined) qs.set('plate_id', String(plateId));
  4714. if (requestId) qs.set('request_id', requestId);
  4715. return request<{
  4716. file_id: number;
  4717. filename: string;
  4718. filaments: Array<{
  4719. slot_id: number;
  4720. type: string;
  4721. color: string;
  4722. used_grams: number;
  4723. used_meters: number;
  4724. used_in_plate?: boolean;
  4725. }>;
  4726. }>(`/library/files/${fileId}/filament-requirements${qs.toString() ? `?${qs}` : ''}`);
  4727. },
  4728. /** Poll the sidecar's per-request progress snapshot via the Bambuddy
  4729. * proxy. Used by the SliceModal's filament-discovery path so the inline
  4730. * spinner + persistent toast can show "Generating G-code (45%)" while
  4731. * the preview slice runs. Returns null on 404 (sidecar doesn't yet
  4732. * have an entry — early race window — or it expired) so the poller
  4733. * can keep trying. */
  4734. getPreviewSliceProgress: async (requestId: string): Promise<SliceJobProgress | null> => {
  4735. try {
  4736. return await request<SliceJobProgress>(`/slicer/preview-progress/${encodeURIComponent(requestId)}`);
  4737. } catch {
  4738. return null;
  4739. }
  4740. },
  4741. // GitHub Backup
  4742. getGitHubBackupConfig: () =>
  4743. request<GitHubBackupConfig | null>('/github-backup/config'),
  4744. saveGitHubBackupConfig: (config: GitHubBackupConfigCreate) =>
  4745. request<GitHubBackupConfig>('/github-backup/config', {
  4746. method: 'POST',
  4747. body: JSON.stringify(config),
  4748. }),
  4749. updateGitHubBackupConfig: (config: Partial<GitHubBackupConfigCreate>) =>
  4750. request<GitHubBackupConfig>('/github-backup/config', {
  4751. method: 'PATCH',
  4752. body: JSON.stringify(config),
  4753. }),
  4754. deleteGitHubBackupConfig: () =>
  4755. request<{ message: string }>('/github-backup/config', { method: 'DELETE' }),
  4756. testGitHubConnection: (repoUrl: string, token: string) =>
  4757. request<GitHubTestConnectionResponse>(
  4758. `/github-backup/test?repo_url=${encodeURIComponent(repoUrl)}&token=${encodeURIComponent(token)}`,
  4759. { method: 'POST' }
  4760. ),
  4761. testGitHubStoredConnection: () =>
  4762. request<GitHubTestConnectionResponse>('/github-backup/test-stored', { method: 'POST' }),
  4763. triggerGitHubBackup: () =>
  4764. request<GitHubBackupTriggerResponse>('/github-backup/run', { method: 'POST' }),
  4765. getGitHubBackupStatus: () =>
  4766. request<GitHubBackupStatus>('/github-backup/status'),
  4767. getGitHubBackupLogs: (limit: number = 50) =>
  4768. request<GitHubBackupLog[]>(`/github-backup/logs?limit=${limit}`),
  4769. clearGitHubBackupLogs: (keepLast: number = 10) =>
  4770. request<{ deleted: number; message: string }>(`/github-backup/logs?keep_last=${keepLast}`, { method: 'DELETE' }),
  4771. // Scheduled local backups
  4772. getLocalBackupStatus: () =>
  4773. request<LocalBackupStatus>('/local-backup/status'),
  4774. triggerLocalBackup: () =>
  4775. request<{ success: boolean; message: string; filename?: string }>('/local-backup/run', { method: 'POST' }),
  4776. getLocalBackups: () =>
  4777. request<LocalBackupFile[]>('/local-backup/backups'),
  4778. downloadLocalBackup: async (filename: string): Promise<{ blob: Blob; filename: string }> => {
  4779. const response = await fetch(`${API_BASE}/local-backup/backups/${encodeURIComponent(filename)}/download`, {
  4780. headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {},
  4781. });
  4782. if (!response.ok) throw new Error('Download failed');
  4783. const blob = await response.blob();
  4784. return { blob, filename };
  4785. },
  4786. restoreLocalBackup: (filename: string) =>
  4787. request<{ success: boolean; message: string }>(`/local-backup/backups/${encodeURIComponent(filename)}/restore`, { method: 'POST' }),
  4788. deleteLocalBackup: (filename: string) =>
  4789. request<{ success: boolean; message: string }>(`/local-backup/backups/${encodeURIComponent(filename)}`, { method: 'DELETE' }),
  4790. // Obico AI failure detection
  4791. getObicoStatus: () =>
  4792. request<ObicoStatus>('/obico/status'),
  4793. testObicoConnection: (url: string) =>
  4794. request<ObicoTestConnection>('/obico/test-connection', {
  4795. method: 'POST',
  4796. body: JSON.stringify({ url }),
  4797. }),
  4798. // Slicer API — slice in the background. Both endpoints return 202 + a
  4799. // job_id; poll /slice-jobs/{id} until status is `completed` or `failed`.
  4800. sliceLibraryFile: (fileId: number, body: SliceRequest) =>
  4801. request<SliceJobEnqueueResponse>(`/library/files/${fileId}/slice`, {
  4802. method: 'POST',
  4803. body: JSON.stringify(body),
  4804. }),
  4805. sliceArchive: (archiveId: number, body: SliceRequest) =>
  4806. request<SliceJobEnqueueResponse>(`/archives/${archiveId}/slice`, {
  4807. method: 'POST',
  4808. body: JSON.stringify(body),
  4809. }),
  4810. getSliceJob: (jobId: number) =>
  4811. request<SliceJobState>(`/slice-jobs/${jobId}`),
  4812. // Unified slicer-preset listing — cloud + local + standard, deduped by name.
  4813. // Used by the SliceModal; see UnifiedPresetsResponse for the shape and
  4814. // backend/app/api/routes/slicer_presets.py for the priority rules.
  4815. getSlicerPresets: () =>
  4816. request<UnifiedPresetsResponse>('/slicer/presets'),
  4817. // Local Presets (OrcaSlicer imports)
  4818. getLocalPresets: () =>
  4819. request<LocalPresetsResponse>('/local-presets/'),
  4820. getLocalPresetDetail: (id: number) =>
  4821. request<LocalPresetDetail>(`/local-presets/${id}`),
  4822. importLocalPresets: (formData: FormData) =>
  4823. fetch(`${API_BASE}/local-presets/import`, {
  4824. method: 'POST',
  4825. headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {},
  4826. body: formData,
  4827. }).then(async (res) => {
  4828. if (!res.ok) {
  4829. const err = await res.json().catch(() => ({}));
  4830. throw new Error(err.detail || `HTTP ${res.status}`);
  4831. }
  4832. return res.json() as Promise<ImportResponse>;
  4833. }),
  4834. createLocalPreset: (data: { name: string; preset_type: string; setting: Record<string, unknown> }) =>
  4835. request<LocalPreset>('/local-presets/', {
  4836. method: 'POST',
  4837. body: JSON.stringify(data),
  4838. }),
  4839. updateLocalPreset: (id: number, data: { name?: string; setting?: Record<string, unknown> }) =>
  4840. request<LocalPreset>(`/local-presets/${id}`, {
  4841. method: 'PUT',
  4842. body: JSON.stringify(data),
  4843. }),
  4844. deleteLocalPreset: (id: number) =>
  4845. request<{ success: boolean }>(`/local-presets/${id}`, { method: 'DELETE' }),
  4846. refreshBaseProfileCache: () =>
  4847. request<{ refreshed: number; failed: number; total: number }>('/local-presets/base-cache/refresh', { method: 'POST' }),
  4848. };
  4849. // AMS History types
  4850. export interface AMSHistoryPoint {
  4851. recorded_at: string;
  4852. humidity: number | null;
  4853. humidity_raw: number | null;
  4854. temperature: number | null;
  4855. }
  4856. export interface AMSHistoryResponse {
  4857. printer_id: number;
  4858. ams_id: number;
  4859. data: AMSHistoryPoint[];
  4860. min_humidity: number | null;
  4861. max_humidity: number | null;
  4862. avg_humidity: number | null;
  4863. min_temperature: number | null;
  4864. max_temperature: number | null;
  4865. avg_temperature: number | null;
  4866. }
  4867. // System Info types
  4868. export interface SystemInfo {
  4869. app: {
  4870. version: string;
  4871. base_dir: string;
  4872. archive_dir: string;
  4873. };
  4874. database: {
  4875. engine: string;
  4876. version: string;
  4877. archives: number;
  4878. archives_completed: number;
  4879. archives_failed: number;
  4880. archives_printing: number;
  4881. printers: number;
  4882. filaments: number;
  4883. projects: number;
  4884. smart_plugs: number;
  4885. total_print_time_seconds: number;
  4886. total_print_time_formatted: string;
  4887. total_filament_grams: number;
  4888. total_filament_kg: number;
  4889. };
  4890. printers: {
  4891. total: number;
  4892. connected: number;
  4893. connected_list: Array<{
  4894. id: number;
  4895. name: string;
  4896. state: string;
  4897. model: string;
  4898. }>;
  4899. };
  4900. storage: {
  4901. archive_size_bytes: number;
  4902. archive_size_formatted: string;
  4903. database_size_bytes: number;
  4904. database_size_formatted: string;
  4905. disk_total_bytes: number;
  4906. disk_total_formatted: string;
  4907. disk_used_bytes: number;
  4908. disk_used_formatted: string;
  4909. disk_free_bytes: number;
  4910. disk_free_formatted: string;
  4911. disk_percent_used: number;
  4912. };
  4913. system: {
  4914. platform: string;
  4915. platform_release: string;
  4916. platform_version: string;
  4917. architecture: string;
  4918. hostname: string;
  4919. python_version: string;
  4920. uptime_seconds: number;
  4921. uptime_formatted: string;
  4922. boot_time: string;
  4923. };
  4924. memory: {
  4925. total_bytes: number;
  4926. total_formatted: string;
  4927. available_bytes: number;
  4928. available_formatted: string;
  4929. used_bytes: number;
  4930. used_formatted: string;
  4931. percent_used: number;
  4932. };
  4933. cpu: {
  4934. count: number;
  4935. count_logical: number;
  4936. percent: number;
  4937. };
  4938. }
  4939. export interface StorageUsageCategory {
  4940. key: string;
  4941. label: string;
  4942. bytes: number;
  4943. formatted: string;
  4944. percent_of_total: number;
  4945. }
  4946. export interface StorageUsageOtherItem {
  4947. bucket: string;
  4948. label: string;
  4949. kind: 'system' | 'data';
  4950. deletable: boolean;
  4951. bytes: number;
  4952. formatted: string;
  4953. percent_of_total: number;
  4954. }
  4955. export interface StorageUsageResponse {
  4956. roots: string[];
  4957. total_bytes: number;
  4958. total_formatted: string;
  4959. categories: StorageUsageCategory[];
  4960. other_breakdown: StorageUsageOtherItem[];
  4961. scan_errors: number;
  4962. generated_at: string;
  4963. cache: {
  4964. hit: boolean;
  4965. age_seconds: number;
  4966. max_age_seconds: number;
  4967. };
  4968. }
  4969. // Library (File Manager) types
  4970. export interface LibraryFolderTree {
  4971. id: number;
  4972. name: string;
  4973. parent_id: number | null;
  4974. project_id: number | null;
  4975. archive_id: number | null;
  4976. project_name: string | null;
  4977. archive_name: string | null;
  4978. is_external: boolean;
  4979. external_path: string | null;
  4980. external_readonly: boolean;
  4981. file_count: number;
  4982. children: LibraryFolderTree[];
  4983. }
  4984. export interface LibraryFolder {
  4985. id: number;
  4986. name: string;
  4987. parent_id: number | null;
  4988. project_id: number | null;
  4989. archive_id: number | null;
  4990. project_name: string | null;
  4991. archive_name: string | null;
  4992. is_external: boolean;
  4993. external_path: string | null;
  4994. external_readonly: boolean;
  4995. external_show_hidden: boolean;
  4996. file_count: number;
  4997. created_at: string;
  4998. updated_at: string;
  4999. }
  5000. export interface LibraryFolderCreate {
  5001. name: string;
  5002. parent_id?: number | null;
  5003. project_id?: number | null;
  5004. archive_id?: number | null;
  5005. }
  5006. export interface ExternalFolderCreate {
  5007. name: string;
  5008. external_path: string;
  5009. readonly?: boolean;
  5010. show_hidden?: boolean;
  5011. parent_id?: number | null;
  5012. }
  5013. export interface LibraryFolderUpdate {
  5014. name?: string;
  5015. parent_id?: number | null;
  5016. project_id?: number | null; // 0 to unlink
  5017. archive_id?: number | null; // 0 to unlink
  5018. }
  5019. export interface LibraryFileDuplicate {
  5020. id: number;
  5021. filename: string;
  5022. folder_id: number | null;
  5023. folder_name: string | null;
  5024. created_at: string;
  5025. }
  5026. export interface LibraryFile {
  5027. id: number;
  5028. folder_id: number | null;
  5029. folder_name: string | null;
  5030. project_id: number | null;
  5031. project_name: string | null;
  5032. is_external: boolean;
  5033. filename: string;
  5034. file_path: string;
  5035. file_type: string;
  5036. file_size: number;
  5037. file_hash: string | null;
  5038. thumbnail_path: string | null;
  5039. metadata: Record<string, unknown> | null;
  5040. print_count: number;
  5041. last_printed_at: string | null;
  5042. notes: string | null;
  5043. duplicates: LibraryFileDuplicate[] | null;
  5044. duplicate_count: number;
  5045. // User tracking (Issue #206)
  5046. created_by_id: number | null;
  5047. created_by_username: string | null;
  5048. created_at: string;
  5049. updated_at: string;
  5050. // Metadata fields
  5051. print_name: string | null;
  5052. print_time_seconds: number | null;
  5053. filament_used_grams: number | null;
  5054. sliced_for_model: string | null;
  5055. }
  5056. export interface LibraryFileListItem {
  5057. id: number;
  5058. folder_id: number | null;
  5059. is_external: boolean;
  5060. filename: string;
  5061. file_type: string;
  5062. file_size: number;
  5063. thumbnail_path: string | null;
  5064. print_count: number;
  5065. duplicate_count: number;
  5066. // User tracking (Issue #206)
  5067. created_by_id: number | null;
  5068. created_by_username: string | null;
  5069. created_at: string;
  5070. print_name: string | null;
  5071. print_time_seconds: number | null;
  5072. filament_used_grams: number | null;
  5073. sliced_for_model: string | null;
  5074. }
  5075. export interface LibraryFileUpdate {
  5076. filename?: string;
  5077. folder_id?: number | null;
  5078. project_id?: number | null;
  5079. notes?: string | null;
  5080. }
  5081. // Library trash (#1008)
  5082. export interface LibraryTrashItem {
  5083. id: number;
  5084. filename: string;
  5085. file_size: number;
  5086. thumbnail_path: string | null;
  5087. folder_id: number | null;
  5088. folder_name: string | null;
  5089. created_by_id: number | null;
  5090. created_by_username: string | null;
  5091. deleted_at: string;
  5092. auto_purge_at: string;
  5093. }
  5094. export interface LibraryTrashListResponse {
  5095. items: LibraryTrashItem[];
  5096. total: number;
  5097. retention_days: number;
  5098. }
  5099. export interface LibraryPurgePreview {
  5100. count: number;
  5101. total_bytes: number;
  5102. sample_filenames: string[];
  5103. older_than_days: number;
  5104. include_never_printed: boolean;
  5105. }
  5106. export interface LibraryTrashSettings {
  5107. retention_days: number;
  5108. auto_purge_enabled: boolean;
  5109. auto_purge_days: number;
  5110. auto_purge_include_never_printed: boolean;
  5111. }
  5112. export interface ArchivePurgePreview {
  5113. count: number;
  5114. total_bytes: number;
  5115. sample_filenames: string[];
  5116. older_than_days: number;
  5117. }
  5118. export interface ArchivePurgeSettings {
  5119. enabled: boolean;
  5120. days: number;
  5121. }
  5122. export interface LibraryFileUploadResponse {
  5123. id: number;
  5124. filename: string;
  5125. file_type: string;
  5126. file_size: number;
  5127. thumbnail_path: string | null;
  5128. duplicate_of: number | null;
  5129. metadata: Record<string, unknown> | null;
  5130. }
  5131. export interface LibraryStats {
  5132. total_files: number;
  5133. total_folders: number;
  5134. total_size_bytes: number;
  5135. files_by_type: Record<string, number>;
  5136. total_prints: number;
  5137. disk_free_bytes: number;
  5138. disk_total_bytes: number;
  5139. disk_used_bytes: number;
  5140. }
  5141. export interface ZipExtractResult {
  5142. filename: string;
  5143. file_id: number;
  5144. folder_id: number | null;
  5145. }
  5146. export interface ZipExtractError {
  5147. filename: string;
  5148. error: string;
  5149. }
  5150. export interface ZipExtractResponse {
  5151. extracted: number;
  5152. folders_created: number;
  5153. files: ZipExtractResult[];
  5154. errors: ZipExtractError[];
  5155. }
  5156. // STL Thumbnail Generation types
  5157. export interface BatchThumbnailResult {
  5158. file_id: number;
  5159. filename: string;
  5160. success: boolean;
  5161. error?: string | null;
  5162. }
  5163. export interface BatchThumbnailResponse {
  5164. processed: number;
  5165. succeeded: number;
  5166. failed: number;
  5167. results: BatchThumbnailResult[];
  5168. }
  5169. // Library Queue types
  5170. export interface AddToQueueResult {
  5171. file_id: number;
  5172. filename: string;
  5173. queue_item_id: number;
  5174. archive_id: number;
  5175. }
  5176. export interface AddToQueueError {
  5177. file_id: number;
  5178. filename: string;
  5179. error: string;
  5180. }
  5181. export interface AddToQueueResponse {
  5182. added: AddToQueueResult[];
  5183. errors: AddToQueueError[];
  5184. }
  5185. // Discovery types
  5186. export interface DiscoveredPrinter {
  5187. serial: string;
  5188. name: string;
  5189. ip_address: string;
  5190. model: string | null;
  5191. discovered_at: string | null;
  5192. }
  5193. export interface DiscoveryStatus {
  5194. running: boolean;
  5195. }
  5196. export interface DiscoveryInfo {
  5197. is_docker: boolean;
  5198. ssdp_running: boolean;
  5199. scan_running: boolean;
  5200. subnets: string[];
  5201. }
  5202. export interface SubnetScanStatus {
  5203. running: boolean;
  5204. scanned: number;
  5205. total: number;
  5206. }
  5207. // Discovery API
  5208. export const discoveryApi = {
  5209. getInfo: () => request<DiscoveryInfo>('/discovery/info'),
  5210. getStatus: () => request<DiscoveryStatus>('/discovery/status'),
  5211. startDiscovery: (duration: number = 10) =>
  5212. request<DiscoveryStatus>(`/discovery/start?duration=${duration}`, { method: 'POST' }),
  5213. stopDiscovery: () =>
  5214. request<DiscoveryStatus>('/discovery/stop', { method: 'POST' }),
  5215. getDiscoveredPrinters: () =>
  5216. request<DiscoveredPrinter[]>('/discovery/printers'),
  5217. // Subnet scanning (for Docker environments)
  5218. startSubnetScan: (subnet: string, timeout: number = 1.0) =>
  5219. request<SubnetScanStatus>('/discovery/scan', {
  5220. method: 'POST',
  5221. body: JSON.stringify({ subnet, timeout }),
  5222. }),
  5223. getScanStatus: () => request<SubnetScanStatus>('/discovery/scan/status'),
  5224. stopSubnetScan: () =>
  5225. request<SubnetScanStatus>('/discovery/scan/stop', { method: 'POST' }),
  5226. };
  5227. // Virtual Printer types
  5228. export type VirtualPrinterMode = 'immediate' | 'queue' | 'review' | 'print_queue' | 'proxy'; // 'queue' is legacy, normalized to 'review'
  5229. export interface VirtualPrinterProxyStatus {
  5230. running: boolean;
  5231. target_host: string;
  5232. ftp_port: number;
  5233. mqtt_port: number;
  5234. ftp_connections: number;
  5235. mqtt_connections: number;
  5236. }
  5237. export interface VirtualPrinterStatus {
  5238. enabled: boolean;
  5239. running: boolean;
  5240. mode: VirtualPrinterMode;
  5241. name: string;
  5242. serial: string;
  5243. model: string;
  5244. model_name: string;
  5245. pending_files: number;
  5246. target_printer_ip?: string; // For proxy mode
  5247. proxy?: VirtualPrinterProxyStatus; // For proxy mode
  5248. tailscale_fqdn?: string; // Set when Tailscale cert is active
  5249. }
  5250. export interface VirtualPrinterSettings {
  5251. enabled: boolean;
  5252. access_code_set: boolean;
  5253. mode: VirtualPrinterMode;
  5254. model: string;
  5255. target_printer_id: number | null; // For proxy mode
  5256. remote_interface_ip: string | null; // For SSDP proxy across networks
  5257. tailscale_disabled: boolean;
  5258. archive_name_source: 'metadata' | 'filename'; // Source for archive's display name
  5259. status: VirtualPrinterStatus;
  5260. }
  5261. export interface NetworkInterface {
  5262. name: string;
  5263. ip: string;
  5264. netmask: string;
  5265. subnet: string;
  5266. is_alias?: boolean;
  5267. label?: string;
  5268. }
  5269. export interface VirtualPrinterModels {
  5270. models: Record<string, string>; // SSDP code -> display name
  5271. default: string;
  5272. }
  5273. export interface PendingUpload {
  5274. id: number;
  5275. filename: string;
  5276. file_size: number;
  5277. source_ip: string | null;
  5278. status: string;
  5279. tags: string | null;
  5280. notes: string | null;
  5281. project_id: number | null;
  5282. uploaded_at: string;
  5283. }
  5284. // Virtual Printer API
  5285. export const virtualPrinterApi = {
  5286. getSettings: () => request<VirtualPrinterSettings>('/settings/virtual-printer'),
  5287. getModels: () => request<VirtualPrinterModels>('/settings/virtual-printer/models'),
  5288. updateSettings: (data: {
  5289. enabled?: boolean;
  5290. access_code?: string;
  5291. mode?: 'immediate' | 'review' | 'print_queue' | 'proxy';
  5292. model?: string;
  5293. target_printer_id?: number;
  5294. remote_interface_ip?: string;
  5295. tailscale_disabled?: boolean;
  5296. archive_name_source?: 'metadata' | 'filename';
  5297. }) => {
  5298. const params = new URLSearchParams();
  5299. if (data.enabled !== undefined) params.set('enabled', String(data.enabled));
  5300. if (data.access_code !== undefined) params.set('access_code', data.access_code);
  5301. if (data.mode !== undefined) params.set('mode', data.mode);
  5302. if (data.model !== undefined) params.set('model', data.model);
  5303. if (data.target_printer_id !== undefined) params.set('target_printer_id', String(data.target_printer_id));
  5304. if (data.remote_interface_ip !== undefined) params.set('remote_interface_ip', data.remote_interface_ip);
  5305. if (data.tailscale_disabled !== undefined) params.set('tailscale_disabled', String(data.tailscale_disabled));
  5306. if (data.archive_name_source !== undefined) params.set('archive_name_source', data.archive_name_source);
  5307. return request<VirtualPrinterSettings>(`/settings/virtual-printer?${params.toString()}`, {
  5308. method: 'PUT',
  5309. });
  5310. },
  5311. };
  5312. // Multi Virtual Printer API
  5313. export interface VirtualPrinterConfig {
  5314. id: number;
  5315. name: string;
  5316. enabled: boolean;
  5317. mode: VirtualPrinterMode;
  5318. model: string | null;
  5319. model_name: string | null;
  5320. access_code_set: boolean;
  5321. serial: string;
  5322. target_printer_id: number | null;
  5323. auto_dispatch: boolean;
  5324. tailscale_disabled: boolean;
  5325. bind_ip: string | null;
  5326. remote_interface_ip: string | null;
  5327. position: number;
  5328. status: { running: boolean; pending_files: number; proxy?: VirtualPrinterProxyStatus; tailscale_fqdn?: string };
  5329. }
  5330. export interface VirtualPrinterListResponse {
  5331. printers: VirtualPrinterConfig[];
  5332. models: Record<string, string>;
  5333. }
  5334. export const multiVirtualPrinterApi = {
  5335. list: () => request<VirtualPrinterListResponse>('/virtual-printers'),
  5336. get: (id: number) => request<VirtualPrinterConfig>(`/virtual-printers/${id}`),
  5337. create: (data: {
  5338. name?: string;
  5339. enabled?: boolean;
  5340. mode?: string;
  5341. model?: string;
  5342. access_code?: string;
  5343. target_printer_id?: number;
  5344. auto_dispatch?: boolean;
  5345. bind_ip?: string;
  5346. remote_interface_ip?: string;
  5347. }) =>
  5348. request<VirtualPrinterConfig>('/virtual-printers', {
  5349. method: 'POST',
  5350. body: JSON.stringify(data),
  5351. }),
  5352. update: (id: number, data: {
  5353. name?: string;
  5354. enabled?: boolean;
  5355. mode?: string;
  5356. model?: string;
  5357. access_code?: string;
  5358. target_printer_id?: number;
  5359. auto_dispatch?: boolean;
  5360. tailscale_disabled?: boolean;
  5361. bind_ip?: string;
  5362. remote_interface_ip?: string;
  5363. }) =>
  5364. request<VirtualPrinterConfig>(`/virtual-printers/${id}`, {
  5365. method: 'PUT',
  5366. body: JSON.stringify(data),
  5367. }),
  5368. remove: (id: number) =>
  5369. request<{ detail: string; id: number }>(`/virtual-printers/${id}`, {
  5370. method: 'DELETE',
  5371. }),
  5372. getTailscaleStatus: () =>
  5373. request<TailscaleStatusResponse>('/virtual-printers/tailscale-status'),
  5374. };
  5375. export interface TailscaleStatusResponse {
  5376. available: boolean;
  5377. fqdn: string;
  5378. hostname: string;
  5379. tailnet_name: string;
  5380. tailscale_ips: string[];
  5381. error: string | null;
  5382. }
  5383. // Pending Uploads API
  5384. export const pendingUploadsApi = {
  5385. list: () => request<PendingUpload[]>('/pending-uploads/'),
  5386. getCount: () => request<{ count: number }>('/pending-uploads/count'),
  5387. get: (id: number) => request<PendingUpload>(`/pending-uploads/${id}`),
  5388. archive: (id: number, data?: { tags?: string; notes?: string; project_id?: number }) =>
  5389. request<{ id: number; print_name: string; filename: string }>(`/pending-uploads/${id}/archive`, {
  5390. method: 'POST',
  5391. body: JSON.stringify(data || {}),
  5392. }),
  5393. discard: (id: number) =>
  5394. request<{ success: boolean }>(`/pending-uploads/${id}`, { method: 'DELETE' }),
  5395. archiveAll: () =>
  5396. request<{ archived: number; failed: number }>('/pending-uploads/archive-all', { method: 'POST' }),
  5397. discardAll: () =>
  5398. request<{ discarded: number }>('/pending-uploads/discard-all', { method: 'DELETE' }),
  5399. };
  5400. // Firmware API Types
  5401. export interface AvailableFirmwareVersion {
  5402. version: string;
  5403. file_available: boolean;
  5404. download_url: string | null;
  5405. release_notes: string | null;
  5406. release_time: string | null;
  5407. }
  5408. export interface FirmwareUpdateInfo {
  5409. printer_id: number;
  5410. printer_name: string;
  5411. model: string | null;
  5412. current_version: string | null;
  5413. latest_version: string | null;
  5414. update_available: boolean;
  5415. download_url: string | null;
  5416. release_notes: string | null;
  5417. available_versions: AvailableFirmwareVersion[];
  5418. }
  5419. export interface FirmwareUploadPrepare {
  5420. can_proceed: boolean;
  5421. sd_card_present: boolean;
  5422. sd_card_free_space: number;
  5423. firmware_size: number;
  5424. space_sufficient: boolean;
  5425. update_available: boolean;
  5426. current_version: string | null;
  5427. latest_version: string | null;
  5428. target_version: string | null;
  5429. firmware_filename: string | null;
  5430. errors: string[];
  5431. }
  5432. export interface FirmwareUploadStatus {
  5433. status: 'idle' | 'preparing' | 'downloading' | 'uploading' | 'complete' | 'error';
  5434. progress: number;
  5435. message: string;
  5436. error: string | null;
  5437. firmware_filename: string | null;
  5438. firmware_version: string | null;
  5439. }
  5440. // Firmware API
  5441. export const firmwareApi = {
  5442. checkUpdates: () =>
  5443. request<{ updates: FirmwareUpdateInfo[]; updates_available: number }>('/firmware/updates'),
  5444. checkPrinterUpdate: (printerId: number) =>
  5445. request<FirmwareUpdateInfo>(`/firmware/updates/${printerId}`),
  5446. prepareUpload: (printerId: number, version?: string) =>
  5447. request<FirmwareUploadPrepare>(
  5448. `/firmware/updates/${printerId}/prepare${version ? `?version=${encodeURIComponent(version)}` : ''}`,
  5449. ),
  5450. startUpload: (printerId: number, version?: string) =>
  5451. request<{ started: boolean; message: string }>(
  5452. `/firmware/updates/${printerId}/upload${version ? `?version=${encodeURIComponent(version)}` : ''}`,
  5453. { method: 'POST' },
  5454. ),
  5455. getUploadStatus: (printerId: number) =>
  5456. request<FirmwareUploadStatus>(`/firmware/updates/${printerId}/upload/status`),
  5457. };
  5458. // Support types
  5459. export interface DebugLoggingState {
  5460. enabled: boolean;
  5461. enabled_at: string | null;
  5462. duration_seconds: number | null;
  5463. }
  5464. export interface LogEntry {
  5465. timestamp: string;
  5466. level: string;
  5467. logger_name: string;
  5468. message: string;
  5469. }
  5470. export interface LogsResponse {
  5471. entries: LogEntry[];
  5472. total_in_file: number;
  5473. filtered_count: number;
  5474. }
  5475. // Support API
  5476. export const supportApi = {
  5477. getDebugLoggingState: () =>
  5478. request<DebugLoggingState>('/support/debug-logging'),
  5479. setDebugLogging: (enabled: boolean) =>
  5480. request<DebugLoggingState>('/support/debug-logging', {
  5481. method: 'POST',
  5482. body: JSON.stringify({ enabled }),
  5483. }),
  5484. downloadSupportBundle: async () => {
  5485. const headers: Record<string, string> = {};
  5486. if (authToken) {
  5487. headers['Authorization'] = `Bearer ${authToken}`;
  5488. }
  5489. const response = await fetch(`${API_BASE}/support/bundle`, { headers });
  5490. if (!response.ok) {
  5491. const error = await response.json().catch(() => ({}));
  5492. throw new Error(error.detail || `HTTP ${response.status}`);
  5493. }
  5494. // Get filename from Content-Disposition header or use default
  5495. const disposition = response.headers.get('Content-Disposition');
  5496. const filename = parseContentDispositionFilename(disposition) || 'bambuddy-support.zip';
  5497. // Download the blob
  5498. const blob = await response.blob();
  5499. const url = window.URL.createObjectURL(blob);
  5500. const a = document.createElement('a');
  5501. a.href = url;
  5502. a.download = filename;
  5503. document.body.appendChild(a);
  5504. a.click();
  5505. document.body.removeChild(a);
  5506. window.URL.revokeObjectURL(url);
  5507. },
  5508. getLogs: (params?: { limit?: number; level?: string; search?: string }) => {
  5509. const searchParams = new URLSearchParams();
  5510. if (params?.limit) searchParams.set('limit', params.limit.toString());
  5511. if (params?.level) searchParams.set('level', params.level);
  5512. if (params?.search) searchParams.set('search', params.search);
  5513. const query = searchParams.toString();
  5514. return request<LogsResponse>(`/support/logs${query ? `?${query}` : ''}`);
  5515. },
  5516. clearLogs: () =>
  5517. request<{ message: string }>('/support/logs', { method: 'DELETE' }),
  5518. };
  5519. // SpoolBuddy types
  5520. export interface SpoolBuddyDevice {
  5521. id: number;
  5522. device_id: string;
  5523. hostname: string;
  5524. ip_address: string;
  5525. backend_url?: string | null;
  5526. firmware_version: string | null;
  5527. has_nfc: boolean;
  5528. has_scale: boolean;
  5529. tare_offset: number;
  5530. calibration_factor: number;
  5531. nfc_reader_type: string | null;
  5532. nfc_connection: string | null;
  5533. display_brightness: number;
  5534. display_blank_timeout: number;
  5535. has_backlight: boolean;
  5536. last_calibrated_at: string | null;
  5537. last_seen: string | null;
  5538. pending_command: string | null;
  5539. nfc_ok: boolean;
  5540. scale_ok: boolean;
  5541. uptime_s: number;
  5542. update_status: string | null;
  5543. update_message: string | null;
  5544. system_stats: {
  5545. os?: { os?: string; kernel?: string; arch?: string; python?: string };
  5546. cpu_temp_c?: number;
  5547. cpu_count?: number;
  5548. load_avg?: number[];
  5549. memory?: { total_mb?: number; available_mb?: number; used_mb?: number; percent?: number };
  5550. disk?: { total_gb?: number; used_gb?: number; free_gb?: number; percent?: number };
  5551. system_uptime_s?: number;
  5552. } | null;
  5553. online: boolean;
  5554. }
  5555. export interface DaemonUpdateCheck {
  5556. current_version: string;
  5557. latest_version: string | null;
  5558. update_available: boolean;
  5559. }
  5560. // SpoolBuddy API
  5561. export const spoolbuddyApi = {
  5562. getDevices: () =>
  5563. request<SpoolBuddyDevice[]>('/spoolbuddy/devices'),
  5564. deleteDevice: (deviceId: string) =>
  5565. request<{ status: string; device_id: string }>(`/spoolbuddy/devices/${deviceId}`, {
  5566. method: 'DELETE',
  5567. }),
  5568. tare: (deviceId: string) =>
  5569. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/calibration/tare`, {
  5570. method: 'POST',
  5571. body: '{}',
  5572. }),
  5573. getCalibration: (deviceId: string) =>
  5574. request<{ tare_offset: number; calibration_factor: number }>(`/spoolbuddy/devices/${deviceId}/calibration`),
  5575. setCalibrationFactor: (deviceId: string, knownWeightGrams: number, rawAdc: number, tareRawAdc?: number) =>
  5576. request<{ tare_offset: number; calibration_factor: number }>(`/spoolbuddy/devices/${deviceId}/calibration/set-factor`, {
  5577. method: 'POST',
  5578. body: JSON.stringify({ known_weight_grams: knownWeightGrams, raw_adc: rawAdc, tare_raw_adc: tareRawAdc }),
  5579. }),
  5580. updateSpoolWeight: (spoolId: number, weightGrams: number) =>
  5581. request<{ status: string; weight_used: number }>('/spoolbuddy/scale/update-spool-weight', {
  5582. method: 'POST',
  5583. body: JSON.stringify({ spool_id: spoolId, weight_grams: weightGrams }),
  5584. }),
  5585. updateDisplay: (deviceId: string, brightness: number, blankTimeout: number) =>
  5586. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/display`, {
  5587. method: 'PUT',
  5588. body: JSON.stringify({ brightness, blank_timeout: blankTimeout }),
  5589. }),
  5590. updateSystemConfig: (deviceId: string, backendUrl: string, apiKey?: string) =>
  5591. request<{ status: string; message: string }>(`/spoolbuddy/devices/${deviceId}/system/config`, {
  5592. method: 'POST',
  5593. body: JSON.stringify({ backend_url: backendUrl, ...(apiKey ? { api_key: apiKey } : {}) }),
  5594. }),
  5595. checkDaemonUpdate: (deviceId: string) =>
  5596. request<DaemonUpdateCheck>(`/spoolbuddy/devices/${deviceId}/update-check`),
  5597. triggerUpdate: (deviceId: string) =>
  5598. request<{ status: string; message: string }>(`/spoolbuddy/devices/${deviceId}/update`, {
  5599. method: 'POST',
  5600. body: '{}',
  5601. }),
  5602. getSSHPublicKey: () =>
  5603. request<{ public_key: string }>('/spoolbuddy/ssh/public-key'),
  5604. writeTag: (deviceId: string, spoolId: number) =>
  5605. request<{ status: string }>('/spoolbuddy/nfc/write-tag', {
  5606. method: 'POST',
  5607. body: JSON.stringify({ device_id: deviceId, spool_id: spoolId }),
  5608. }),
  5609. cancelWrite: (deviceId: string) =>
  5610. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/cancel-write`, {
  5611. method: 'POST',
  5612. body: '{}',
  5613. }),
  5614. systemCommand: (deviceId: string, command: 'reboot' | 'shutdown' | 'restart_daemon' | 'restart_browser') =>
  5615. request<{ status: string; command: string }>(`/spoolbuddy/devices/${deviceId}/system/command`, {
  5616. method: 'POST',
  5617. body: JSON.stringify({ command }),
  5618. }),
  5619. queueDiagnostics: (deviceId: string, type: 'nfc' | 'scale' | 'read_tag') =>
  5620. request<{ status: string; diagnostic: string; message: string }>(
  5621. `/spoolbuddy/diagnostics/${deviceId}/run?diagnostic=${type}`,
  5622. { method: 'POST', body: '{}' }
  5623. ),
  5624. getDiagnosticResult: (deviceId: string, type: 'nfc' | 'scale' | 'read_tag') =>
  5625. request<{ diagnostic: string; success: boolean; output: string; exit_code: number }>(
  5626. `/spoolbuddy/diagnostics/${deviceId}/result?diagnostic=${type}`,
  5627. { method: 'GET' }
  5628. ),
  5629. };
  5630. export interface BugReportRequest {
  5631. description: string;
  5632. email?: string;
  5633. screenshot_base64?: string;
  5634. include_support_info?: boolean;
  5635. debug_logs?: string;
  5636. }
  5637. export interface BugReportResponse {
  5638. success: boolean;
  5639. message: string;
  5640. issue_url?: string;
  5641. issue_number?: number;
  5642. }
  5643. export const bugReportApi = {
  5644. submit: (data: BugReportRequest) =>
  5645. request<BugReportResponse>('/bug-report/submit', {
  5646. method: 'POST',
  5647. body: JSON.stringify(data),
  5648. }),
  5649. startLogging: () =>
  5650. request<{ started: boolean; was_debug: boolean }>('/bug-report/start-logging', {
  5651. method: 'POST',
  5652. }),
  5653. stopLogging: (wasDebug: boolean) =>
  5654. request<{ logs: string }>(`/bug-report/stop-logging?was_debug=${wasDebug}`, {
  5655. method: 'POST',
  5656. }),
  5657. };