client.ts 150 KB

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