client.ts 165 KB

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