client.ts 151 KB

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