client.ts 173 KB

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