client.ts 169 KB

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