client.ts 153 KB

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