client.ts 183 KB

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