client.ts 283 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128
  1. import type { ArchivePlatesResponse, LibraryFilePlatesResponse } from '../types/plates';
  2. const API_BASE = '/api/v1';
  3. export class ApiError extends Error {
  4. status: number;
  5. /** Stable error code from a structured backend detail (`{code, message}`).
  6. * Frontend uses this to look up an i18n key instead of showing the raw
  7. * English fallback. Null when the backend returned a plain-string detail. */
  8. code: string | null;
  9. /** Full structured detail object when the backend returned `{code, ...}`
  10. * with additional fields (e.g. the deficit list for 409s on queue
  11. * start, #1496). Null for plain-string or array-shaped details. */
  12. detail: Record<string, unknown> | null;
  13. constructor(
  14. message: string,
  15. status: number,
  16. code: string | null = null,
  17. detail: Record<string, unknown> | null = null,
  18. ) {
  19. super(message);
  20. this.name = 'ApiError';
  21. this.status = status;
  22. this.code = code;
  23. this.detail = detail;
  24. }
  25. }
  26. // Auth token storage
  27. // By default tokens are stored in sessionStorage (tab-scoped, cleared on close).
  28. // When the token originates from the ?token= URL param (kiosk bootstrap), it is
  29. // additionally persisted in localStorage so the kiosk survives page reloads.
  30. // 'persistent' also writes to localStorage so the token survives tab close
  31. // (used by Remember Me and the ?token= kiosk bootstrap).
  32. let authToken: string | null =
  33. sessionStorage.getItem('auth_token') ?? localStorage.getItem('auth_token');
  34. export type TokenPersistence = 'session' | 'persistent';
  35. export function setAuthToken(token: string | null, persistence: TokenPersistence = 'session') {
  36. authToken = token;
  37. try {
  38. if (token) {
  39. sessionStorage.setItem('auth_token', token);
  40. } else {
  41. sessionStorage.removeItem('auth_token');
  42. }
  43. } catch (err) {
  44. // Storage unavailable (quota exceeded, private mode): in-memory token still works for this tab.
  45. console.warn('setAuthToken: sessionStorage unavailable, token kept in-memory only', err);
  46. }
  47. try {
  48. if (!token) {
  49. localStorage.removeItem('auth_token');
  50. } else if (persistence === 'persistent') {
  51. localStorage.setItem('auth_token', token);
  52. }
  53. } catch (err) {
  54. console.warn('setAuthToken: localStorage operation failed', err);
  55. }
  56. }
  57. export function getAuthToken(): string | null {
  58. return authToken;
  59. }
  60. // Stream token for image/video URLs loaded via <img>/<video> tags
  61. // (these can't send Authorization headers, so a query param token is used)
  62. let streamToken: string | null = null;
  63. export function setStreamToken(token: string | null) {
  64. streamToken = token;
  65. }
  66. export function getStreamToken(): string | null {
  67. return streamToken;
  68. }
  69. /** Append the stream token to a URL if available (for <img>/<video> src). */
  70. export function withStreamToken(url: string): string {
  71. if (!streamToken) return url;
  72. const sep = url.includes('?') ? '&' : '?';
  73. return `${url}${sep}token=${encodeURIComponent(streamToken)}`;
  74. }
  75. function parseContentDispositionFilename(header: string | null): string | null {
  76. if (!header) return null;
  77. // RFC 5987: filename*=utf-8''percent-encoded-name
  78. const rfc5987Match = header.match(/filename\*=(?:UTF-8|utf-8)''(.+?)(?:;|$)/);
  79. if (rfc5987Match) {
  80. try { return decodeURIComponent(rfc5987Match[1]); } catch { /* fall through */ }
  81. }
  82. // Standard: filename="name" or filename=name
  83. const standardMatch = header.match(/filename="?([^";\n]+)"?/);
  84. return standardMatch?.[1] || null;
  85. }
  86. function buildSlicerUrlFilename(filename: string): string {
  87. const safe = filename.replace(/[/\\?#]/g, '_');
  88. return safe.toLowerCase().endsWith('.3mf') ? safe : `${safe}.3mf`;
  89. }
  90. async function request<T>(
  91. endpoint: string,
  92. options: RequestInit = {}
  93. ): Promise<T> {
  94. const headers: Record<string, string> = {
  95. 'Content-Type': 'application/json',
  96. ...options.headers as Record<string, string>,
  97. };
  98. // Add auth token if available
  99. if (authToken) {
  100. headers['Authorization'] = `Bearer ${authToken}`;
  101. }
  102. const response = await fetch(`${API_BASE}${endpoint}`, {
  103. ...options,
  104. cache: 'no-store', // Prevent browser caching of API responses
  105. credentials: 'include', // Required for HttpOnly cookies (e.g. 2fa_challenge)
  106. headers,
  107. });
  108. if (!response.ok) {
  109. const error = await response.json().catch(() => ({}));
  110. const detail = error.detail;
  111. let message: string;
  112. let code: string | null = null;
  113. if (typeof detail === 'string') {
  114. message = detail;
  115. } else if (Array.isArray(detail)) {
  116. // FastAPI 422 shape: each entry has `msg` like "Value error, <real msg>".
  117. // Strip the prefix and join. Fall back to raw JSON if every entry has an
  118. // empty msg (defensive — shouldn't happen with stock Pydantic, but the
  119. // previous fallback masked the real cause as a bare "HTTP 422" toast).
  120. const joined = detail
  121. .map((e: { msg?: string }) => (e.msg ?? '').replace(/^Value error,\s*/i, ''))
  122. .filter(Boolean)
  123. .join('; ');
  124. message = joined || JSON.stringify(detail) || `HTTP ${response.status}`;
  125. } else if (detail && typeof detail === 'object') {
  126. // Structured detail `{code, message, ...}` — frontend uses the code
  127. // to pick an i18n key, message is the English fallback, any extra
  128. // fields land on ApiError.detail (e.g. `deficit` for #1496).
  129. code = typeof detail.code === 'string' ? detail.code : null;
  130. message = typeof detail.message === 'string' ? detail.message : `HTTP ${response.status}`;
  131. } else {
  132. message = `HTTP ${response.status}`;
  133. }
  134. const structuredDetail = detail && typeof detail === 'object' && !Array.isArray(detail)
  135. ? (detail as Record<string, unknown>)
  136. : null;
  137. // Handle 401 Unauthorized - only clear token if it's actually invalid
  138. // Don't clear on "Authentication required" which might be a timing issue
  139. if (response.status === 401) {
  140. const invalidTokenMessages = [
  141. 'Could not validate credentials',
  142. 'Token has expired',
  143. 'User not found or inactive',
  144. 'Invalid API key',
  145. 'API key has expired',
  146. ];
  147. if (invalidTokenMessages.some(m => message.includes(m))) {
  148. setAuthToken(null);
  149. // Notify AuthContext so the protected route guard re-evaluates and
  150. // redirects to /login on the same tab — without this, AuthContext.user
  151. // stays cached and the tab silently fails every request until a manual
  152. // refresh remounts AuthProvider (#1698, reported by @TCL987).
  153. if (typeof window !== 'undefined') {
  154. window.dispatchEvent(new CustomEvent('auth:expired'));
  155. }
  156. }
  157. }
  158. throw new ApiError(message, response.status, code, structuredDetail);
  159. }
  160. // Handle empty responses (204 No Content, etc.)
  161. const contentLength = response.headers.get('content-length');
  162. if (response.status === 204 || contentLength === '0') {
  163. return undefined as T;
  164. }
  165. return await response.json();
  166. }
  167. /** Upload a CSV to the spool import endpoint (#1576). Multipart, so it bypasses
  168. * `request<T>()` (which sends JSON): the browser must set the form-data
  169. * boundary itself. `dryRun` toggles preview-only vs. real import. */
  170. async function uploadSpoolsCsv<T>(file: File, dryRun: boolean): Promise<T> {
  171. const form = new FormData();
  172. form.append('file', file);
  173. const headers: Record<string, string> = {};
  174. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  175. const response = await fetch(`${API_BASE}/inventory/spools/import${dryRun ? '?dry_run=true' : ''}`, {
  176. method: 'POST',
  177. headers,
  178. body: form,
  179. });
  180. if (!response.ok) {
  181. const error = await response.json().catch(() => ({}));
  182. // detail may be a plain string or a structured {code, message} object
  183. // (e.g. the 413 too-large response). Surface the human message either way.
  184. const detail = error?.detail;
  185. const message = typeof detail === 'string' ? detail : detail?.message;
  186. throw new Error(message || `HTTP ${response.status}`);
  187. }
  188. return response.json();
  189. }
  190. // Camera diagnostic result (#1395 follow-up). Returned by
  191. // POST /printers/{id}/camera/diagnose; the frontend modal renders one
  192. // row per stage and looks up the summary code in i18n for the user-
  193. // facing remediation hint.
  194. export interface CameraDiagnoseStage {
  195. name: 'tcp_reachable' | 'first_frame' | 'live_stream_active';
  196. status: 'ok' | 'failed' | 'skipped';
  197. duration_ms: number;
  198. code: string | null;
  199. }
  200. export interface CameraDiagnoseResult {
  201. printer_id: number;
  202. protocol: 'rtsp' | 'chamber_image';
  203. port: number;
  204. // 'default' = historical X1/H2 tuning. Anything else = this model has
  205. // an override entry in backend/app/services/camera_profiles.py.
  206. profile: string;
  207. overall_status: 'ok' | 'failed';
  208. stages: CameraDiagnoseStage[];
  209. // i18n key under `camera.diagnose.summary.*`.
  210. summary_code: string;
  211. }
  212. // Connection diagnostic (GET /printers/{id}/diagnostic and
  213. // POST /printers/diagnostic). Each check's `id` + `status` resolve a
  214. // localized title/fix under `diagnostic.check.*`; `params` interpolate it.
  215. export type DiagnosticStatus = 'pass' | 'fail' | 'warn' | 'skip';
  216. export interface DiagnosticCheck {
  217. id:
  218. | 'port_mqtt'
  219. | 'port_ftps'
  220. | 'port_rtsps'
  221. | 'network_mode'
  222. | 'subnet'
  223. | 'mqtt_auth'
  224. | 'developer_mode';
  225. status: DiagnosticStatus;
  226. params: Record<string, string | number>;
  227. }
  228. export interface PrinterDiagnosticResult {
  229. printer_id: number | null;
  230. ip_address: string;
  231. overall: 'ok' | 'warnings' | 'problems';
  232. checks: DiagnosticCheck[];
  233. }
  234. // --- Log-health scan: self-service triage on the System page + bug reporter.
  235. // The backend matches recent logs against a curated known-issue catalog;
  236. // human-readable cause/fix text is rendered from i18n keys keyed by signature_id.
  237. export type LogFindingSeverity = 'error' | 'warning';
  238. export type LogFindingCategory = 'layer8' | 'environment' | 'bug';
  239. export interface LogFinding {
  240. signature_id: string;
  241. severity: LogFindingSeverity;
  242. category: LogFindingCategory;
  243. wiki_anchor: string;
  244. count: number;
  245. first_seen: string;
  246. last_seen: string;
  247. sample: string;
  248. }
  249. export interface SystemHealthResult {
  250. findings: LogFinding[];
  251. scanned_entries: number;
  252. log_available: boolean;
  253. summary: {
  254. total: number;
  255. layer8: number;
  256. environment: number;
  257. bug: number;
  258. };
  259. }
  260. // Long-lived camera tokens (#1108). The `token` field is populated only on the
  261. // create response — listing endpoints set it to null because the plaintext
  262. // value is shown to the user exactly once.
  263. //
  264. // 'camera_stream' reaches the video endpoints only. 'camwall' additionally
  265. // reaches the read-only Cam Wall feed, which names the printers (#2531), so it
  266. // is a separate scope rather than a widening of tokens already in the wild.
  267. export type LongLivedTokenScope = 'camera_stream' | 'camwall' | 'overlay';
  268. export interface LongLivedCameraToken {
  269. id: number;
  270. user_id: number;
  271. name: string;
  272. scope: LongLivedTokenScope;
  273. lookup_prefix: string;
  274. created_at: string;
  275. expires_at: string;
  276. last_used_at: string | null;
  277. token: string | null;
  278. }
  279. // One row of the token-authenticated Cam Wall feed (#2531). Deliberately
  280. // smaller than PrinterStatus: no serial, no IP, no print filename — a kiosk URL
  281. // is not a secret, so the payload behind it must not be either.
  282. export interface CamWallPrinter {
  283. id: number;
  284. name: string;
  285. camera_rotation: number;
  286. connected: boolean;
  287. state: string | null;
  288. progress: number | null;
  289. remaining_time: number | null;
  290. layer_num: number | null;
  291. total_layers: number | null;
  292. hms_errors: HMSError[];
  293. }
  294. // Streaming-overlay feed (#2613). The subset of print state the /overlay page
  295. // draws for one printer, served behind an `overlay`-scoped token so OBS embeds
  296. // with no login session can read it. Unlike CamWallPrinter this names the file
  297. // being printed (the overlay shows the part on screen).
  298. export interface OverlayStatus {
  299. id: number;
  300. name: string;
  301. camera_rotation: number;
  302. connected: boolean;
  303. state: string | null;
  304. current_print: string | null;
  305. gcode_file: string | null;
  306. progress: number | null;
  307. remaining_time: number | null;
  308. layer_num: number | null;
  309. total_layers: number | null;
  310. stg_cur_name: string | null;
  311. // Nozzle / bed / chamber readings for the overlay's temperature fields
  312. // (#1422). Only the keys a viewer is shown; chamber is absent on models
  313. // without a real sensor.
  314. temperatures: Record<string, number>;
  315. time_format: 'system' | '12h' | '24h';
  316. }
  317. // Printer types
  318. export interface Printer {
  319. id: number;
  320. name: string;
  321. serial_number: string;
  322. ip_address: string;
  323. // Optional because the backend only returns access_code when the caller has
  324. // PRINTERS_UPDATE — Admin / Operator JWTs or auth-disabled mode. Viewers and
  325. // API keys receive a Printer without this field.
  326. access_code?: string;
  327. model: string | null;
  328. location: string | null; // Group/location name
  329. nozzle_count: number; // 1 or 2, auto-detected from MQTT
  330. // Model is sold with both Standard and High Flow nozzles, so a K-profile's
  331. // flow type is a real choice. Derived from the model, not the nozzle count —
  332. // only the A-series has a single variant.
  333. supports_nozzle_flow_type: boolean;
  334. is_active: boolean;
  335. auto_archive: boolean;
  336. external_camera_url: string | null;
  337. external_camera_type: string | null; // "mjpeg", "rtsp", "snapshot"
  338. external_camera_enabled: boolean;
  339. external_camera_snapshot_url: string | null; // optional single-frame override (#1177)
  340. camera_rotation: number; // 0, 90, 180, 270 degrees
  341. plate_detection_enabled: boolean; // Check plate before print
  342. plate_detection_roi?: PlateDetectionROI; // ROI for plate detection
  343. created_at: string;
  344. updated_at: string;
  345. }
  346. export interface HMSError {
  347. code: string;
  348. attr: number; // Attribute value for constructing wiki URL
  349. module: number;
  350. severity: number; // 1=fatal, 2=serious, 3=common, 4=info
  351. actions?: string[]; // List of user-facing action keys (e.g. "CHECK_FILAMENT")
  352. job_id?: string; // Optional job ID for actions that require it (e.g. "CHECK_ASSISTANT")
  353. // Canonical hex identifier the firmware matches against — 8 chars for
  354. // print_error-sourced faults, 16 chars for hms[]-array-sourced faults. Send
  355. // this back as HmsActionBody.print_error so we don't truncate the 64-bit
  356. // identifier into the silent-rejection short code (#1830).
  357. full_code?: string;
  358. }
  359. export interface HMSActionBody {
  360. print_error: string; // HMS error code (e.g. "05000070")
  361. action: string; // "HMS action to execute (e.g. 'resume_after_error')"
  362. job_id: string | null; // Optional job ID for context (if applicable)
  363. }
  364. export interface AMSTray {
  365. id: number;
  366. tray_color: string | null;
  367. tray_type: string | null;
  368. tray_sub_brands: string | null; // Full name like "PLA Basic", "PETG HF"
  369. tray_id_name: string | null; // Bambu filament ID like "A00-Y2" (can decode to color)
  370. tray_info_idx: string | null; // Filament preset ID like "GFA00" - maps to cloud setting_id
  371. remain: number;
  372. k: number | null; // Pressure advance value (from tray or K-profile lookup)
  373. cali_idx: number | null; // Calibration index for K-profile lookup
  374. tag_uid: string | null; // RFID tag UID (any tag)
  375. tray_uuid: string | null; // Bambu Lab spool UUID (32-char hex, only valid for Bambu Lab spools)
  376. nozzle_temp_min: number | null; // Min nozzle temperature
  377. nozzle_temp_max: number | null; // Max nozzle temperature
  378. drying_temp: number | null; // RFID-recommended drying temp
  379. drying_time: number | null; // RFID-recommended drying time (hours)
  380. state: number | null; // AMS tray state: 9=empty, 10=spool present not loaded, 11=loaded
  381. exists?: boolean | null; // Firmware tray_exist_bits: spool physically present (non-RFID → "?" not "Empty", #2527)
  382. }
  383. export interface AMSUnit {
  384. id: number;
  385. humidity: number | null;
  386. temp: number | null;
  387. is_ams_ht: boolean; // True for AMS-HT (single spool), False for regular AMS (4 spools)
  388. tray: AMSTray[];
  389. serial_number: string; // AMS unit serial number (from MQTT sn field)
  390. sw_ver: string; // AMS firmware version (from get_version info.module ams/* entry)
  391. dry_time: number; // Minutes remaining (0 = not drying, >0 = drying active)
  392. dry_status: number; // 0=Off, 1=Checking, 2=Drying, 3=Cooling, 4=Stopping, 5=Error
  393. dry_sub_status: number; // 0=Off, 1=Heating, 2=Dehumidify
  394. dry_sf_reason: number[]; // Cannot-dry reasons (1=InsufficientPower, 8=NeedPluginPower)
  395. dry_target_temp: number | null; // Active-cycle target °C (Bambu does not echo)
  396. dry_filament: string | null; // Active-cycle filament name we sent
  397. module_type: string; // "ams", "n3f", "n3s"
  398. }
  399. export interface NozzleInfo {
  400. nozzle_type: string; // "stainless_steel" or "hardened_steel"
  401. nozzle_diameter: string; // e.g., "0.4"
  402. }
  403. export interface NozzleRackSlot {
  404. id: number;
  405. nozzle_type: string;
  406. nozzle_diameter: string;
  407. wear: number | null;
  408. stat: number | null; // Nozzle status (e.g. mounted/docked)
  409. max_temp: number;
  410. serial_number: string;
  411. filament_color: string; // RGBA hex ("00000000" = no filament)
  412. filament_id: string;
  413. filament_type: string; // Material type (e.g. "PLA", "PETG")
  414. }
  415. export interface PrintOptions {
  416. // Core AI detectors
  417. spaghetti_detector: boolean;
  418. print_halt: boolean;
  419. halt_print_sensitivity: string; // "low", "medium", "high" - spaghetti sensitivity
  420. first_layer_inspector: boolean;
  421. printing_monitor: boolean;
  422. buildplate_marker_detector: boolean;
  423. allow_skip_parts: boolean;
  424. // Additional AI detectors (decoded from cfg bitmask)
  425. nozzle_clumping_detector: boolean;
  426. nozzle_clumping_sensitivity: string; // "low", "medium", "high"
  427. pileup_detector: boolean;
  428. pileup_sensitivity: string; // "low", "medium", "high"
  429. airprint_detector: boolean;
  430. airprint_sensitivity: string; // "low", "medium", "high"
  431. auto_recovery_step_loss: boolean;
  432. filament_tangle_detect: boolean;
  433. }
  434. export interface FilaSwitchState {
  435. installed: boolean;
  436. // in[track] = currently loaded slot for that track (-1 = empty)
  437. in_slots: number[];
  438. // out[track] = extruder this track terminates at (0 = right, 1 = left)
  439. out_extruders: number[];
  440. stat: number;
  441. info: number;
  442. }
  443. export interface PrinterStatus {
  444. id: number;
  445. name: string;
  446. connected: boolean;
  447. state: string | null;
  448. current_print: string | null;
  449. subtask_name: string | null;
  450. current_archive_id: number | null;
  451. current_plate_id: number | null;
  452. gcode_file: string | null;
  453. progress: number | null;
  454. remaining_time: number | null;
  455. layer_num: number | null;
  456. total_layers: number | null;
  457. temperatures: {
  458. bed?: number;
  459. bed_target?: number;
  460. bed_heating?: boolean; // Actual heater state from MQTT
  461. nozzle?: number;
  462. nozzle_target?: number;
  463. nozzle_heating?: boolean; // Actual heater state from MQTT
  464. nozzle_2?: number; // Second nozzle for H2 series (dual nozzle)
  465. nozzle_2_target?: number;
  466. nozzle_2_heating?: boolean; // Actual heater state from MQTT
  467. chamber?: number;
  468. chamber_target?: number;
  469. chamber_heating?: boolean; // Actual heater state from MQTT
  470. } | null;
  471. cover_url: string | null;
  472. hms_errors: HMSError[];
  473. ams: AMSUnit[];
  474. ams_exists: boolean;
  475. vt_tray: AMSTray[]; // Virtual tray / external spool(s)
  476. store_to_sdcard: boolean; // Store sent files on SD card
  477. timelapse: boolean; // Timelapse recording active
  478. ipcam: boolean; // Live view enabled
  479. wifi_signal: number | null; // WiFi signal strength in dBm
  480. wired_network: boolean; // Ethernet connection detected
  481. door_open: boolean; // Enclosure door open (models with a door sensor: X1/X1C/X1E/X2D/P2S/H2*)
  482. nozzles: NozzleInfo[]; // Nozzle hardware info (index 0=left/primary, 1=right)
  483. nozzle_rack: NozzleRackSlot[]; // H2C 6-nozzle tool-changer rack
  484. print_options: PrintOptions | null; // AI detection and print options
  485. // Calibration stage tracking
  486. stg_cur: number; // Current stage number (-1 = not calibrating)
  487. stg_cur_name: string | null; // Human-readable current stage name
  488. stg: number[]; // List of stage numbers in calibration sequence
  489. // Air conditioning mode (0=cooling, 1=heating)
  490. airduct_mode: number;
  491. // Print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  492. speed_level: number;
  493. // Chamber light on/off
  494. chamber_light: boolean;
  495. // Active extruder for dual nozzle (0=right, 1=left)
  496. active_extruder: number;
  497. // AMS mapping - which AMS is connected to which nozzle
  498. // Format: [ams_id_for_nozzle0, ams_id_for_nozzle1, ...] where -1 means no AMS
  499. ams_mapping: number[];
  500. // Per-AMS extruder mapping - extracted from each AMS unit's info field
  501. // Format: {ams_id: extruder_id} where extruder 0=right, 1=left
  502. // Note: JSON keys are always strings
  503. ams_extruder_map: Record<string, number>;
  504. // Filament Track Switch accessory — null when not installed. When present,
  505. // AMS slots aren't tied to a specific extruder; the FTS routes any slot to
  506. // either extruder, so per-extruder slot filtering must be skipped.
  507. fila_switch: FilaSwitchState | null;
  508. // Currently loaded tray (global tray ID, 255 = no filament loaded, 254 = external spool)
  509. tray_now: number;
  510. // Runout / filament-replacement guidance (#2587). Populated only while PAUSED.
  511. // Global tray IDs (ams_id*4+slot, 128-135 = AMS-HT, 254 = external), matching
  512. // the same numbering as tray_now so the AMS graphic can highlight them.
  513. // expected_tray = the slot the firmware now expects filament in (null = idle,
  514. // not paused, or unresolvable → "check the printer").
  515. // previous_tray = the slot that ran out (null = unknown).
  516. expected_tray: number | null;
  517. previous_tray: number | null;
  518. // AMS status for filament change tracking (0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration)
  519. ams_status_main: number;
  520. // AMS sub-status for filament change step (when main=1): 4=retraction, 6=load verification, 7=purge
  521. ams_status_sub: number;
  522. // mc_print_sub_stage - filament change step indicator used by OrcaSlicer/BambuStudio
  523. mc_print_sub_stage: number;
  524. // Timestamp of last AMS data update (for RFID refresh detection)
  525. last_ams_update: number;
  526. // Number of printable objects in current print (for skip objects feature)
  527. printable_objects_count: number;
  528. // Fan speeds (0-100 percentage, null if not available for this model)
  529. cooling_fan_speed: number | null; // Part cooling fan
  530. big_fan1_speed: number | null; // Auxiliary fan
  531. big_fan2_speed: number | null; // Chamber/exhaust fan
  532. heatbreak_fan_speed: number | null; // Hotend heatbreak fan
  533. // Left auxiliary part cooling fan (optional P2S/X2D accessory, M106 P10).
  534. // null = not installed / not reported by this model.
  535. left_aux_fan_speed: number | null;
  536. // Chamber exhaust fan present (P2S/X2D External Exhaust Fan kit, airduct part 3).
  537. exhaust_fan_present: boolean;
  538. firmware_version: string | null; // Firmware version from MQTT
  539. // Developer LAN mode: true = enabled, false = disabled, null = unknown
  540. developer_mode: boolean | null;
  541. // AMS Filament Backup ("auto-switch" to a backup spool when one runs out).
  542. // true = ON, false = OFF, null = unknown / unsupported (A1 family).
  543. ams_filament_backup: boolean | null;
  544. // Queue: printer is awaiting user ack that the build plate was cleared after a
  545. // finished/failed print. Persisted across restarts (#961).
  546. awaiting_plate_clear: boolean;
  547. // AMS drying support
  548. supports_drying: boolean;
  549. // The AMS can dry, but only from the printer's own screen (P1 series, #2533).
  550. drying_screen_only?: boolean;
  551. // Active chamber heater (responds to M141). True only for H2C/H2D/H2DPro/H2S/X2D.
  552. supports_chamber_heater?: boolean;
  553. }
  554. export interface PrinterCreate {
  555. name: string;
  556. serial_number: string;
  557. ip_address: string;
  558. access_code: string;
  559. model?: string;
  560. location?: string;
  561. auto_archive?: boolean;
  562. // Maintenance Mode flag (#1476). Backend already gates MQTT, queue dispatch,
  563. // scheduler, metrics and the print picker on this; toggling via PATCH
  564. // /printers/{id} disconnects or reconnects MQTT accordingly.
  565. is_active?: boolean;
  566. external_camera_url?: string | null;
  567. external_camera_type?: string | null;
  568. external_camera_enabled?: boolean;
  569. external_camera_snapshot_url?: string | null;
  570. camera_rotation?: number;
  571. plate_detection_enabled?: boolean;
  572. plate_detection_roi?: PlateDetectionROI;
  573. }
  574. // Plate Detection
  575. export interface PlateDetectionROI {
  576. x: number; // X start % (0.0-1.0)
  577. y: number; // Y start % (0.0-1.0)
  578. w: number; // Width % (0.0-1.0)
  579. h: number; // Height % (0.0-1.0)
  580. }
  581. export interface PlateDetectionResult {
  582. is_empty: boolean;
  583. confidence: number;
  584. difference_percent: number;
  585. message: string;
  586. has_debug_image: boolean;
  587. debug_image_url?: string;
  588. needs_calibration: boolean;
  589. light_warning?: boolean;
  590. reference_count?: number;
  591. max_references?: number;
  592. roi?: PlateDetectionROI;
  593. }
  594. export interface PlateDetectionStatus {
  595. available: boolean;
  596. calibrated: boolean;
  597. reference_count: number;
  598. max_references: number;
  599. message: string;
  600. }
  601. export interface CalibrationResult {
  602. success: boolean;
  603. message: string;
  604. }
  605. export interface PlateReference {
  606. index: number;
  607. label: string;
  608. timestamp: string;
  609. has_image: boolean;
  610. thumbnail_url: string;
  611. }
  612. // Archive types
  613. export interface ArchiveDuplicate {
  614. id: number;
  615. print_name: string | null;
  616. created_at: string;
  617. match_type: 'exact' | 'similar'; // 'exact' = hash match, 'similar' = name match
  618. }
  619. export interface Archive {
  620. id: number;
  621. printer_id: number | null;
  622. project_id: number | null;
  623. project_name: string | null;
  624. filename: string;
  625. file_path: string;
  626. file_size: number;
  627. content_hash: string | null;
  628. thumbnail_path: string | null;
  629. timelapse_path: string | null;
  630. source_3mf_path: string | null;
  631. f3d_path: string | null;
  632. duplicates: ArchiveDuplicate[] | null;
  633. duplicate_count: number;
  634. duplicate_sequence: number; // 0 = original, 1+ = nth duplicate
  635. original_archive_id: number | null; // ID of the first/original archive
  636. object_count: number | null;
  637. print_name: string | null;
  638. plate_id: number | null; // Selected plate of a multi-plate 3MF (#2603)
  639. print_time_seconds: number | null;
  640. actual_time_seconds: number | null; // Computed from started_at/completed_at
  641. time_accuracy: number | null; // Percentage: 100 = perfect, >100 = faster than estimated
  642. filament_used_grams: number | null;
  643. filament_type: string | null;
  644. filament_color: string | null;
  645. layer_height: number | null;
  646. total_layers: number | null;
  647. nozzle_diameter: number | null;
  648. bed_temperature: number | null;
  649. bed_type: string | null; // Build plate type from 3MF (e.g. "Cool Plate", "Textured PEI Plate")
  650. nozzle_temperature: number | null;
  651. sliced_for_model: string | null; // Printer model this file was sliced for
  652. status: string;
  653. started_at: string | null;
  654. completed_at: string | null;
  655. extra_data: Record<string, unknown> | null;
  656. makerworld_url: string | null;
  657. designer: string | null;
  658. external_url: string | null;
  659. is_favorite: boolean;
  660. tags: string | null;
  661. notes: string | null;
  662. cost: number | null;
  663. photos: string[] | null;
  664. failure_reason: string | null;
  665. quantity: number;
  666. energy_kwh: number | null;
  667. energy_cost: number | null;
  668. created_at: string;
  669. // User tracking (Issue #206)
  670. created_by_id: number | null;
  671. created_by_username: string | null;
  672. // Per-archive run aggregates from PrintLogEntry (#1378)
  673. run_count: number;
  674. last_run_at: string | null;
  675. total_filament_actual_grams: number | null;
  676. successful_run_count: number;
  677. failed_run_count: number;
  678. }
  679. export interface ArchiveSlim {
  680. printer_id: number | null;
  681. print_name: string | null;
  682. print_time_seconds: number | null;
  683. actual_time_seconds: number | null;
  684. filament_used_grams: number | null;
  685. filament_type: string | null;
  686. filament_color: string | null;
  687. status: string;
  688. started_at: string | null;
  689. completed_at: string | null;
  690. cost: number | null;
  691. energy_kwh: number | null;
  692. energy_cost: number | null;
  693. quantity: number;
  694. created_at: string;
  695. }
  696. export interface PrintLogEntry {
  697. id: number;
  698. archive_id: number | null;
  699. print_name: string | null;
  700. printer_name: string | null;
  701. printer_id: number | null;
  702. status: string;
  703. started_at: string | null;
  704. completed_at: string | null;
  705. duration_seconds: number | null;
  706. filament_type: string | null;
  707. filament_color: string | null;
  708. filament_used_grams: number | null;
  709. cost: number | null;
  710. energy_kwh: number | null;
  711. energy_cost: number | null;
  712. failure_reason: string | null;
  713. thumbnail_path: string | null;
  714. created_by_id: number | null;
  715. created_by_username: string | null;
  716. created_at: string;
  717. }
  718. export interface PrintLogResponse {
  719. items: PrintLogEntry[];
  720. total: number;
  721. }
  722. export interface ArchiveStats {
  723. total_prints: number;
  724. successful_prints: number;
  725. failed_prints: number;
  726. cancelled_prints: number;
  727. total_print_time_hours: number;
  728. total_filament_grams: number;
  729. total_cost: number;
  730. prints_by_filament_type: Record<string, number>;
  731. prints_by_printer: Record<string, number>;
  732. average_time_accuracy: number | null;
  733. time_accuracy_by_printer: Record<string, number> | null;
  734. total_energy_kwh: number;
  735. total_energy_cost: number;
  736. // True when a date-filtered total-consumption query is running on incomplete
  737. // snapshot history (e.g. right after upgrade, before hourly snapshots have
  738. // a baseline). UI should explain why the number may undercount.
  739. energy_data_warming_up?: boolean;
  740. }
  741. export interface TagInfo {
  742. name: string;
  743. count: number;
  744. }
  745. export interface FailureAnalysis {
  746. period_days: number;
  747. total_prints: number;
  748. failed_prints: number;
  749. failure_rate: number;
  750. failures_by_reason: Record<string, number>;
  751. failures_by_filament: Record<string, number>;
  752. failures_by_printer: Record<string, number>;
  753. failures_by_hour: Record<number, number>;
  754. recent_failures: Array<{
  755. id: number;
  756. print_name: string;
  757. failure_reason: string | null;
  758. filament_type: string | null;
  759. printer_id: number | null;
  760. created_at: string | null;
  761. }>;
  762. trend: Array<{
  763. week_start: string;
  764. total_prints: number;
  765. failed_prints: number;
  766. failure_rate: number;
  767. }>;
  768. }
  769. export interface BulkUploadResult {
  770. uploaded: number;
  771. failed: number;
  772. results: Array<{ filename: string; id: number; status: string }>;
  773. errors: Array<{ filename: string; error: string }>;
  774. }
  775. // Archive Comparison types
  776. export interface ComparisonArchiveInfo {
  777. id: number;
  778. print_name: string;
  779. status: string;
  780. created_at: string | null;
  781. printer_id: number | null;
  782. project_name: string | null;
  783. }
  784. export interface ComparisonField {
  785. field: string;
  786. label: string;
  787. unit: string | null;
  788. values: (string | number | null)[];
  789. raw_values: (string | number | null)[];
  790. has_difference: boolean;
  791. }
  792. export interface SuccessCorrelationInsight {
  793. field: string;
  794. label: string;
  795. insight: string;
  796. success_avg?: number;
  797. failed_avg?: number;
  798. success_values?: string[];
  799. failed_values?: string[];
  800. }
  801. export interface SuccessCorrelation {
  802. has_both_outcomes: boolean;
  803. message?: string;
  804. successful_count?: number;
  805. failed_count?: number;
  806. insights?: SuccessCorrelationInsight[];
  807. }
  808. export interface ArchiveComparison {
  809. archives: ComparisonArchiveInfo[];
  810. comparison: ComparisonField[];
  811. differences: ComparisonField[];
  812. success_correlation: SuccessCorrelation;
  813. }
  814. export interface SimilarArchive {
  815. archive: {
  816. id: number;
  817. print_name: string;
  818. status: string;
  819. created_at: string | null;
  820. };
  821. match_reason: string;
  822. match_score: number;
  823. }
  824. // Project types
  825. export interface ProjectStats {
  826. total_archives: number;
  827. total_items: number; // Sum of quantities (total items printed)
  828. completed_prints: number; // Sum of quantities for completed prints (parts)
  829. failed_prints: number;
  830. queued_prints: number;
  831. in_progress_prints: number;
  832. total_print_time_hours: number;
  833. total_filament_grams: number;
  834. progress_percent: number | null; // Plates progress (total_archives / target_count)
  835. parts_progress_percent: number | null; // Parts progress (completed_prints / target_parts_count)
  836. estimated_cost: number;
  837. total_energy_kwh: number;
  838. total_energy_cost: number;
  839. remaining_prints: number | null; // Remaining plates
  840. remaining_parts: number | null; // Remaining parts
  841. bom_total_items: number;
  842. bom_completed_items: number;
  843. bom_cost: number;
  844. }
  845. export interface ProjectChildPreview {
  846. id: number;
  847. name: string;
  848. color: string | null;
  849. status: string;
  850. progress_percent: number | null;
  851. }
  852. export interface Project {
  853. id: number;
  854. name: string;
  855. description: string | null;
  856. color: string | null;
  857. status: string; // active, completed, archived
  858. target_count: number | null; // Target number of plates/print jobs
  859. target_parts_count: number | null; // Target number of parts/objects
  860. target_sets: number | null; // Copies-per-file target (#1897)
  861. notes: string | null;
  862. attachments: ProjectAttachment[] | null;
  863. tags: string | null;
  864. due_date: string | null;
  865. priority: string; // low, normal, high, urgent
  866. budget: number | null;
  867. is_template: boolean;
  868. template_source_id: number | null;
  869. parent_id: number | null;
  870. parent_name: string | null;
  871. children: ProjectChildPreview[];
  872. created_at: string;
  873. updated_at: string;
  874. stats?: ProjectStats;
  875. url: string | null; // External link rendered next to project name on the card (#1155)
  876. cover_image_filename: string | null; // Filename within project attachments dir (#1155)
  877. }
  878. export interface ProjectAttachment {
  879. filename: string;
  880. original_name: string;
  881. size: number;
  882. uploaded_at: string;
  883. }
  884. // Completed-run count for one library file inside a project (#1897)
  885. export interface ProjectFileProgress {
  886. file_id: number;
  887. completed_count: number;
  888. }
  889. export interface ArchivePreview {
  890. id: number;
  891. print_name: string | null;
  892. thumbnail_path: string | null;
  893. status: string;
  894. filament_type: string | null;
  895. filament_color: string | null;
  896. }
  897. export interface ProjectListItem {
  898. id: number;
  899. name: string;
  900. description: string | null;
  901. color: string | null;
  902. status: string;
  903. target_count: number | null; // Target number of plates/print jobs
  904. target_parts_count: number | null; // Target number of parts/objects
  905. target_sets: number | null; // #1897 — the shared edit dialog seeds itself from this
  906. budget: number | null;
  907. tags: string | null; // #2536 — the shared edit dialog seeds itself from this
  908. due_date: string | null; // #2536
  909. priority: string; // #2536
  910. created_at: string;
  911. archive_count: number; // Number of print jobs (plates)
  912. total_items: number; // Sum of quantities (total items printed, including failed)
  913. completed_count: number; // Sum of quantities for completed prints only (parts)
  914. failed_count: number; // Sum of quantities for failed prints
  915. queue_count: number;
  916. progress_percent: number | null; // Plates progress
  917. archives: ArchivePreview[];
  918. url: string | null; // #1155
  919. cover_image_filename: string | null; // #1155
  920. }
  921. export interface ProjectCreate {
  922. name: string;
  923. description?: string;
  924. color?: string;
  925. target_count?: number;
  926. target_parts_count?: number;
  927. target_sets?: number;
  928. notes?: string;
  929. tags?: string;
  930. due_date?: string;
  931. priority?: string;
  932. budget?: number | null;
  933. parent_id?: number;
  934. url?: string | null; // #1155
  935. }
  936. export interface ProjectUpdate {
  937. name?: string;
  938. description?: string;
  939. color?: string;
  940. status?: string;
  941. target_count?: number;
  942. target_parts_count?: number;
  943. target_sets?: number | null; // #1897 — explicit null clears the copies-per-file target
  944. notes?: string;
  945. tags?: string | null; // #2536 — explicit null clears the tags
  946. due_date?: string | null; // #2536 — explicit null clears the due date
  947. priority?: string;
  948. budget?: number | null;
  949. parent_id?: number;
  950. url?: string | null; // #1155 — explicit null clears the URL
  951. }
  952. // BOM Types - Tracks sourced/purchased parts (hardware, electronics, etc.)
  953. export interface BOMItem {
  954. id: number;
  955. project_id: number;
  956. name: string;
  957. quantity_needed: number;
  958. quantity_acquired: number;
  959. unit_price: number | null;
  960. sourcing_url: string | null;
  961. archive_id: number | null;
  962. archive_name: string | null;
  963. stl_filename: string | null;
  964. remarks: string | null;
  965. sort_order: number;
  966. is_complete: boolean;
  967. created_at: string;
  968. updated_at: string;
  969. }
  970. export interface BOMItemCreate {
  971. name: string;
  972. quantity_needed?: number;
  973. unit_price?: number;
  974. sourcing_url?: string;
  975. archive_id?: number;
  976. stl_filename?: string;
  977. remarks?: string;
  978. }
  979. export interface BOMItemUpdate {
  980. name?: string;
  981. quantity_needed?: number;
  982. quantity_acquired?: number;
  983. unit_price?: number;
  984. sourcing_url?: string;
  985. archive_id?: number;
  986. stl_filename?: string;
  987. remarks?: string;
  988. }
  989. // Project Export/Import Types
  990. export interface BOMItemExport {
  991. name: string;
  992. quantity_needed: number;
  993. quantity_acquired: number;
  994. unit_price: number | null;
  995. sourcing_url: string | null;
  996. stl_filename: string | null;
  997. remarks: string | null;
  998. }
  999. export interface LinkedFolderExport {
  1000. name: string;
  1001. }
  1002. export interface ProjectExport {
  1003. name: string;
  1004. description: string | null;
  1005. color: string | null;
  1006. status: string;
  1007. target_count: number | null;
  1008. target_parts_count: number | null;
  1009. target_sets: number | null; // #1897
  1010. notes: string | null;
  1011. tags: string | null;
  1012. due_date: string | null;
  1013. priority: string;
  1014. budget: number | null;
  1015. bom_items: BOMItemExport[];
  1016. linked_folders: LinkedFolderExport[];
  1017. }
  1018. export interface ProjectImport {
  1019. name: string;
  1020. description?: string;
  1021. color?: string;
  1022. status?: string;
  1023. target_count?: number;
  1024. target_parts_count?: number;
  1025. target_sets?: number; // #1897
  1026. notes?: string;
  1027. tags?: string;
  1028. due_date?: string;
  1029. priority?: string;
  1030. budget?: number | null;
  1031. bom_items?: BOMItemExport[];
  1032. linked_folders?: LinkedFolderExport[];
  1033. }
  1034. // Timeline Types
  1035. export interface TimelineEvent {
  1036. event_type: string;
  1037. timestamp: string;
  1038. title: string;
  1039. description: string | null;
  1040. metadata: Record<string, unknown> | null;
  1041. }
  1042. // API Key types
  1043. export interface APIKey {
  1044. id: number;
  1045. name: string;
  1046. key_prefix: string;
  1047. user_id: number | null; // Owner; null on legacy keys created before per-user ownership (#1182)
  1048. can_queue: boolean;
  1049. can_control_printer: boolean;
  1050. can_read_status: boolean;
  1051. can_manage_library: boolean;
  1052. can_manage_inventory: boolean;
  1053. can_manage_maintenance: boolean;
  1054. can_manage_archives: boolean;
  1055. can_manage_projects: boolean;
  1056. can_access_cloud: boolean;
  1057. can_update_energy_cost: boolean;
  1058. printer_ids: number[] | null;
  1059. enabled: boolean;
  1060. last_used: string | null;
  1061. created_at: string;
  1062. expires_at: string | null;
  1063. }
  1064. export interface APIKeyCreate {
  1065. name: string;
  1066. can_queue?: boolean;
  1067. can_control_printer?: boolean;
  1068. can_read_status?: boolean;
  1069. can_manage_library?: boolean;
  1070. can_manage_inventory?: boolean;
  1071. can_manage_maintenance?: boolean;
  1072. can_manage_archives?: boolean;
  1073. can_manage_projects?: boolean;
  1074. can_access_cloud?: boolean;
  1075. can_update_energy_cost?: boolean;
  1076. printer_ids?: number[] | null;
  1077. expires_at?: string | null;
  1078. }
  1079. export interface APIKeyCreateResponse extends APIKey {
  1080. key: string; // Full key, only shown on creation
  1081. }
  1082. export interface APIKeyUpdate {
  1083. name?: string;
  1084. can_queue?: boolean;
  1085. can_control_printer?: boolean;
  1086. can_read_status?: boolean;
  1087. can_manage_library?: boolean;
  1088. can_manage_inventory?: boolean;
  1089. can_manage_maintenance?: boolean;
  1090. can_manage_archives?: boolean;
  1091. can_manage_projects?: boolean;
  1092. can_access_cloud?: boolean;
  1093. can_update_energy_cost?: boolean;
  1094. printer_ids?: number[] | null;
  1095. enabled?: boolean;
  1096. expires_at?: string | null;
  1097. }
  1098. /**
  1099. * Tri-state calibration option (BambuStudio parity): "off" never runs it,
  1100. * "on" forces it every print, "auto" lets the printer skip it if it was done
  1101. * recently. Used by bed_levelling, flow_cali, and nozzle_offset_cali.
  1102. */
  1103. export type CalibrationMode = 'off' | 'on' | 'auto';
  1104. // Settings types
  1105. export interface AppSettings {
  1106. auto_archive: boolean;
  1107. save_thumbnails: boolean;
  1108. capture_finish_photo: boolean;
  1109. finish_photo_restore_plate: boolean;
  1110. default_filament_cost: number;
  1111. currency: string;
  1112. energy_cost_per_kwh: number;
  1113. energy_tracking_mode: 'print' | 'total';
  1114. check_updates: boolean;
  1115. check_printer_firmware: boolean;
  1116. include_beta_updates: boolean;
  1117. // #1589: false hides the local username/password form on the login page;
  1118. // BAMBUDDY_LOCAL_LOGIN=true on the server flips the reported value back to
  1119. // true so the env-var recovery path is visible to the SPA.
  1120. local_login_enabled: boolean;
  1121. language: string;
  1122. notification_language: string;
  1123. // AMS threshold settings
  1124. ams_humidity_good: number; // <= this is green
  1125. ams_humidity_fair: number; // <= this is orange, > is red
  1126. ams_temp_good: number; // <= this is green/blue
  1127. ams_temp_fair: number; // <= this is orange, > is red
  1128. ams_history_retention_days: number; // days to keep AMS sensor history
  1129. // Queue auto-drying settings
  1130. queue_drying_enabled: boolean; // Auto-dry AMS between queued prints
  1131. queue_drying_block: boolean; // Block queue until drying completes
  1132. ambient_drying_enabled: boolean; // Auto-dry idle printers based on humidity regardless of queue
  1133. print_drying_enabled: boolean; // Continue drying while a print is running on capable hardware
  1134. drying_presets: string; // JSON blob of drying presets per filament type
  1135. ams_humidity_thresholds: string; // JSON blob of per-filament humidity thresholds (#1605)
  1136. gcode_snippets: string; // JSON: per-model G-code injection snippets
  1137. // Scheduled local backup
  1138. local_backup_enabled: boolean;
  1139. local_backup_schedule: string;
  1140. local_backup_time: string;
  1141. local_backup_retention: number;
  1142. local_backup_path: string;
  1143. // Print modal settings
  1144. per_printer_mapping_expanded: boolean; // Whether custom mapping is expanded by default in print modal
  1145. // Date/time format settings
  1146. date_format: 'system' | 'us' | 'eu' | 'iso';
  1147. time_format: 'system' | '12h' | '24h';
  1148. // Filament tracking
  1149. disable_filament_warnings: boolean; // Disable filament warnings (print insufficiency and assignment mismatch)
  1150. prefer_lowest_filament: boolean; // When multiple spools match, prefer lowest remaining filament
  1151. spoolman_enabled: boolean; // True when the user has switched filament tracking to Spoolman; backend includes this in the /settings/ response even though earlier consumers read it from the dedicated /settings/spoolman endpoint as a string
  1152. auto_add_unknown_rfid: boolean; // When false, the backend skips auto-creating inventory spools for unknown RFID tags and instead broadcasts an unknown_tag event for the confirmation modal
  1153. spoolman_url: string;
  1154. // Default printer
  1155. default_printer_id: number | null;
  1156. pipeline_max_copies: number;
  1157. // Dark mode theme settings
  1158. dark_style: 'classic' | 'glow' | 'vibrant';
  1159. dark_background: 'neutral' | 'warm' | 'cool' | 'oled' | 'slate' | 'forest';
  1160. dark_accent: 'green' | 'teal' | 'blue' | 'orange' | 'purple' | 'red';
  1161. // Light mode theme settings
  1162. light_style: 'classic' | 'glow' | 'vibrant';
  1163. light_background: 'neutral' | 'warm' | 'cool';
  1164. light_accent: 'green' | 'teal' | 'blue' | 'orange' | 'purple' | 'red';
  1165. // FTP retry settings
  1166. ftp_retry_enabled: boolean;
  1167. ftp_retry_count: number;
  1168. ftp_retry_delay: number;
  1169. ftp_timeout: number;
  1170. // MQTT relay settings
  1171. mqtt_enabled: boolean;
  1172. mqtt_broker: string;
  1173. mqtt_port: number;
  1174. mqtt_username: string;
  1175. mqtt_password: string;
  1176. mqtt_topic_prefix: string;
  1177. mqtt_use_tls: boolean;
  1178. // External URL for notifications
  1179. external_url: string;
  1180. // Directory holding docker-compose.yml, shown in the update instructions (#2664)
  1181. docker_compose_dir: string;
  1182. // Home Assistant integration
  1183. ha_enabled: boolean;
  1184. ha_url: string;
  1185. ha_token: string;
  1186. ha_url_from_env: boolean;
  1187. ha_token_from_env: boolean;
  1188. ha_env_managed: boolean;
  1189. // File Manager / Library settings
  1190. library_archive_mode: 'always' | 'never' | 'ask';
  1191. library_disk_warning_gb: number;
  1192. // Camera view settings
  1193. camera_view_mode: 'window' | 'embedded';
  1194. // Preferred slicer (server-side API / sidecar)
  1195. preferred_slicer: 'bambu_studio' | 'orcaslicer';
  1196. // Desktop "Open in Slicer" override (#1329). Null inherits from
  1197. // preferred_slicer so existing installs behave identically.
  1198. open_in_slicer: 'bambu_studio' | 'orcaslicer' | null;
  1199. // Use the slicer-API sidecar for slicing (in-app modal) vs desktop URI scheme
  1200. use_slicer_api: boolean;
  1201. // Per-install sidecar URLs. Empty string falls back to the env defaults.
  1202. orcaslicer_api_url: string;
  1203. bambu_studio_api_url: string;
  1204. // Minutes of silence from the sidecar before a slice is abandoned. Bounds
  1205. // stalls, not total slicing time — a model that keeps reporting progress
  1206. // runs to completion however long it takes.
  1207. slicer_stall_timeout_minutes: number;
  1208. // Prometheus metrics
  1209. prometheus_enabled: boolean;
  1210. prometheus_token: string;
  1211. // Bed cooled threshold
  1212. bed_cooled_threshold: number;
  1213. // Inventory low stock threshold
  1214. low_stock_threshold: number;
  1215. // Session policy (#1706) — admin-set ceiling, hours, [1, 720]
  1216. session_max_hours: number;
  1217. // User email notifications toggle
  1218. user_notifications_enabled: boolean;
  1219. // Default print options
  1220. default_bed_levelling: CalibrationMode;
  1221. default_flow_cali: CalibrationMode;
  1222. default_vibration_cali: boolean;
  1223. default_layer_inspect: boolean;
  1224. default_timelapse: boolean;
  1225. default_nozzle_offset_cali: CalibrationMode;
  1226. // Staggered batch start defaults
  1227. stagger_group_size: number;
  1228. stagger_interval_minutes: number;
  1229. // Plate-clear confirmation
  1230. require_plate_clear: boolean;
  1231. // Shortest job first scheduling
  1232. queue_shortest_first: boolean;
  1233. // How many printers the queue may upload to at once (#2555). 1 restores the
  1234. // old strictly-serial behaviour, where every printer waited out every other
  1235. // printer's transfer.
  1236. queue_max_concurrent_uploads: number;
  1237. // Preheat / heat-soak before queued prints (#1468). Master toggle is the
  1238. // default for new queue items; per-item PrintQueueItem.preheat_override can
  1239. // flip the decision per print. Chamber target derives from the loaded AMS
  1240. // filament types via preheat_filament_targets (JSON map of type → °C, max
  1241. // across loaded slots); the per-item override field bypasses derivation.
  1242. preheat_enabled: boolean;
  1243. preheat_filament_targets: string;
  1244. preheat_max_wait_seconds: number;
  1245. preheat_soak_seconds: number;
  1246. // User-configurable presets for the printer-card popovers (JSON arrays of 3 ints).
  1247. // Empty string = use built-in defaults.
  1248. nozzle_temp_presets: string;
  1249. bed_temp_presets: string;
  1250. chamber_temp_presets: string;
  1251. fan_speed_presets: string;
  1252. // Default sidebar order (admin-set for all users)
  1253. default_sidebar_order: string;
  1254. // LDAP authentication
  1255. ldap_enabled: boolean;
  1256. ldap_server_url: string;
  1257. ldap_bind_dn: string;
  1258. ldap_bind_password: string;
  1259. ldap_search_base: string;
  1260. ldap_user_filter: string;
  1261. ldap_security: string;
  1262. ldap_group_mapping: string;
  1263. ldap_auto_provision: boolean;
  1264. ldap_default_group: string;
  1265. obico_enabled: boolean;
  1266. obico_ml_url: string;
  1267. obico_ml_token: string;
  1268. obico_sensitivity: 'low' | 'medium' | 'high';
  1269. obico_action: 'notify' | 'pause' | 'pause_and_off';
  1270. obico_poll_interval: number;
  1271. obico_enabled_printers: string;
  1272. // Inventory forecasting global lead time
  1273. forecast_global_lead_time_days: number;
  1274. }
  1275. export type AppSettingsUpdate = Partial<AppSettings>;
  1276. // MQTT relay status
  1277. export interface MQTTStatus {
  1278. enabled: boolean;
  1279. connected: boolean;
  1280. broker: string;
  1281. port: number;
  1282. topic_prefix: string;
  1283. }
  1284. // Cloud types
  1285. export interface CloudAuthStatus {
  1286. is_authenticated: boolean;
  1287. email: string | null;
  1288. region?: 'global' | 'china' | null;
  1289. /** A token is stored but Bambu no longer accepts it — tell the user why the login form is back. */
  1290. sign_in_expired?: boolean;
  1291. }
  1292. export interface CloudLoginResponse {
  1293. success: boolean;
  1294. needs_verification: boolean;
  1295. message: string;
  1296. verification_type?: 'email' | 'totp' | null;
  1297. tfa_key?: string | null;
  1298. }
  1299. // Orca Cloud types — paste-flow PKCE handshake against auth.orcaslicer.com.
  1300. // See backend/app/services/orca_cloud.py for the deep dive on why this
  1301. // flow is paste-based rather than callback-based.
  1302. export interface OrcaDeviceStartResponse {
  1303. user_code: string;
  1304. verification_uri: string;
  1305. verification_uri_complete: string;
  1306. interval: number;
  1307. expires_in: number;
  1308. }
  1309. export type OrcaDevicePollStatus =
  1310. | 'authorization_pending'
  1311. | 'slow_down'
  1312. | 'access_denied'
  1313. | 'expired_token'
  1314. | 'complete';
  1315. export interface OrcaDevicePollResponse {
  1316. status: OrcaDevicePollStatus;
  1317. connected: boolean;
  1318. email: string | null;
  1319. user_id: string | null;
  1320. }
  1321. export interface OrcaAuthStatusResponse {
  1322. connected: boolean;
  1323. email: string | null;
  1324. user_id: string | null;
  1325. }
  1326. // Orca profiles are shaped to match Bambu Cloud's SlicerSetting on the wire
  1327. // so the frontend can use the same visual components for both surfaces (cards,
  1328. // grouped sections, filter bar). Backend handles the source-specific
  1329. // transformation in routes/orca_cloud.py::_orca_to_setting.
  1330. export interface OrcaProfileMeta {
  1331. setting_id: string;
  1332. name: string;
  1333. type: string;
  1334. version: string | null;
  1335. user_id: string | null;
  1336. updated_time: string | null;
  1337. is_custom: boolean;
  1338. }
  1339. export interface OrcaProfileListResponse {
  1340. filament: OrcaProfileMeta[];
  1341. printer: OrcaProfileMeta[];
  1342. process: OrcaProfileMeta[];
  1343. }
  1344. export interface OrcaProfileDetail {
  1345. setting_id: string;
  1346. name: string;
  1347. type: string;
  1348. version: string | null;
  1349. base_id: string | null;
  1350. update_time: string | null;
  1351. setting: Record<string, unknown>;
  1352. }
  1353. // MakerWorld integration. Full metadata/instance shapes come back as
  1354. // Record<string, unknown> — MakerWorld's API adds fields over time, so we
  1355. // pass them through verbatim rather than maintaining a brittle mirror.
  1356. export interface MakerworldStatus {
  1357. has_cloud_token: boolean;
  1358. can_download: boolean;
  1359. /** A token is stored but Bambu rejected it — downloads will fail until the user signs in again. */
  1360. sign_in_expired?: boolean;
  1361. }
  1362. export interface MakerworldResolvedModel {
  1363. model_id: number;
  1364. profile_id: number | null;
  1365. design: Record<string, unknown>;
  1366. instances: Array<Record<string, unknown>>;
  1367. already_imported_library_ids: number[];
  1368. }
  1369. export interface MakerworldImportResponse {
  1370. library_file_id: number;
  1371. filename: string;
  1372. folder_id: number | null;
  1373. profile_id: number | null;
  1374. was_existing: boolean;
  1375. }
  1376. export interface MakerworldRecentImport {
  1377. library_file_id: number;
  1378. filename: string;
  1379. folder_id: number | null;
  1380. thumbnail_path: string | null;
  1381. source_url: string | null;
  1382. created_at: string;
  1383. }
  1384. export interface SlicerSetting {
  1385. setting_id: string;
  1386. name: string;
  1387. type: string;
  1388. version: string | null;
  1389. user_id: string | null;
  1390. updated_time: string | null;
  1391. is_custom: boolean;
  1392. }
  1393. export interface SpoolCatalogEntry {
  1394. id: number;
  1395. name: string;
  1396. weight: number;
  1397. is_default: boolean;
  1398. }
  1399. export interface StorageLocation {
  1400. id: number;
  1401. name: string;
  1402. identifier: string | null;
  1403. spool_count: number;
  1404. created_at: string;
  1405. updated_at: string;
  1406. }
  1407. export interface ColorCatalogEntry {
  1408. id: number;
  1409. manufacturer: string;
  1410. color_name: string;
  1411. hex_color: string;
  1412. material: string | null;
  1413. is_default: boolean;
  1414. // #1154: optional multi-colour gradient stops + visual effect.
  1415. extra_colors?: string | null;
  1416. effect_type?: string | null;
  1417. }
  1418. export interface ColorLookupResult {
  1419. found: boolean;
  1420. hex_color: string | null;
  1421. material: string | null;
  1422. }
  1423. export interface SlicerSettingsResponse {
  1424. filament: SlicerSetting[];
  1425. printer: SlicerSetting[];
  1426. process: SlicerSetting[];
  1427. }
  1428. export interface SlicerSettingDetail {
  1429. message?: string | null;
  1430. code?: string | null;
  1431. error?: string | null;
  1432. public: boolean;
  1433. version?: string | null;
  1434. type: string;
  1435. name: string;
  1436. update_time?: string | null;
  1437. nickname?: string | null;
  1438. base_id?: string | null;
  1439. setting: Record<string, unknown>;
  1440. filament_id?: string | null;
  1441. setting_id?: string | null;
  1442. }
  1443. export interface SlicerSettingCreate {
  1444. type: string; // 'filament', 'print', or 'printer'
  1445. name: string;
  1446. base_id: string;
  1447. setting: Record<string, unknown>;
  1448. }
  1449. export interface SlicerSettingUpdate {
  1450. name?: string;
  1451. setting?: Record<string, unknown>;
  1452. }
  1453. export interface SlicerSettingDeleteResponse {
  1454. success: boolean;
  1455. message: string;
  1456. }
  1457. // Built-in filament fallback (static table from backend)
  1458. export interface BuiltinFilament {
  1459. filament_id: string;
  1460. name: string;
  1461. }
  1462. // Slice request/response — POST /library/files/{id}/slice and /archives/{id}/slice
  1463. //
  1464. // Two preset shapes are accepted per slot:
  1465. // - Legacy bare integer ids (`*_preset_id`) — pre-cloud-tier clients.
  1466. // - Source-aware refs (`*_preset: PresetRef`) — new SliceModal that picks
  1467. // across cloud / local / standard tiers. Source-aware refs win when both
  1468. // are present in the same payload.
  1469. export type PresetSource = 'orca_cloud' | 'cloud' | 'local' | 'standard';
  1470. export interface PresetRef {
  1471. source: PresetSource;
  1472. id: string;
  1473. }
  1474. export interface SliceRequest {
  1475. printer_preset_id?: number;
  1476. process_preset_id?: number;
  1477. filament_preset_id?: number;
  1478. printer_preset?: PresetRef;
  1479. process_preset?: PresetRef;
  1480. filament_preset?: PresetRef;
  1481. // Multi-color: one PresetRef per plate slot, in plate order. Always
  1482. // preferred over the singular `filament_preset` when both are sent; the
  1483. // backend validator promotes a singular into a one-element list when this
  1484. // is omitted, so legacy single-color clients keep working unchanged.
  1485. filament_presets?: PresetRef[];
  1486. plate?: number;
  1487. export_3mf?: boolean;
  1488. // Build-plate override (#1337). When omitted, the slicer uses the process
  1489. // preset's curr_bed_type as-is. Canonical values match BambuStudio /
  1490. // OrcaSlicer's enum: "Cool Plate", "Engineering Plate", "High Temp Plate",
  1491. // "Textured PEI Plate", "Smooth PEI Plate", "Cool Plate (SuperTack)",
  1492. // "Supertack Plate".
  1493. bed_type?: string | null;
  1494. // "Slice as designed" (#2611). 3MF only: slice using the file's embedded
  1495. // project_settings.config (the designer's own wall count, infill, etc.)
  1496. // instead of the picked profile triplet. The preset refs above are still
  1497. // required by the backend validator but go unused on this path.
  1498. use_embedded_settings?: boolean;
  1499. // Layout passes the slicer runs before slicing (#2548), both off by
  1500. // default because they move or rotate the objects the user laid out.
  1501. // Unlike the fields above these are CLI actions rather than profile
  1502. // values, so they apply on the embedded-settings path too.
  1503. auto_orient?: boolean;
  1504. auto_arrange?: boolean;
  1505. }
  1506. // GET /api/v1/slicer/presets — unified listing across cloud / local / standard.
  1507. export type SlicerCloudStatus = 'ok' | 'not_authenticated' | 'expired' | 'unreachable';
  1508. export interface UnifiedPreset {
  1509. id: string;
  1510. name: string;
  1511. source: PresetSource;
  1512. // Populated for the filament slot only — used by the SliceModal multi-color
  1513. // pre-pick to score presets against each plate slot's required (type,
  1514. // colour). Optional because the bundled / standard tier rarely carries a
  1515. // colour (colour is a runtime spool attribute on Bambu) and older API
  1516. // responses pre-date these fields entirely.
  1517. filament_type?: string | null;
  1518. filament_colour?: string | null;
  1519. // Printer-preset names a process / filament preset declares itself
  1520. // compatible with. Populated for the local tier (the slicer's own
  1521. // `compatible_printers`); null for cloud / standard. The SliceModal filters
  1522. // the process / filament dropdowns by the selected printer using this when
  1523. // present (#1325).
  1524. compatible_printers?: string[] | null;
  1525. }
  1526. export interface UnifiedPresetsBySlot {
  1527. printer: UnifiedPreset[];
  1528. process: UnifiedPreset[];
  1529. filament: UnifiedPreset[];
  1530. }
  1531. export interface UnifiedPresetsResponse {
  1532. // Priority order: local > orca_cloud > cloud > standard. No cross-tier
  1533. // dedup — every tier surfaces its full list so the user can pick from
  1534. // any source. The order drives auto-pick + visual group rendering only.
  1535. orca_cloud: UnifiedPresetsBySlot;
  1536. cloud: UnifiedPresetsBySlot;
  1537. local: UnifiedPresetsBySlot;
  1538. standard: UnifiedPresetsBySlot;
  1539. cloud_status: SlicerCloudStatus;
  1540. orca_cloud_status: SlicerCloudStatus;
  1541. }
  1542. // Slicer Pipelines (#1425) — named bundles of preset slots the SliceModal
  1543. // can apply in one click. PR A surfaces only the bundle; target_* and
  1544. // fanout_strategy round-trip from the backend but the UI doesn't yet expose
  1545. // them (they come alive in PR B / PR C).
  1546. export interface SlicerPipeline {
  1547. id: number;
  1548. name: string;
  1549. description: string | null;
  1550. printer_preset: PresetRef;
  1551. process_preset: PresetRef;
  1552. filament_presets: PresetRef[];
  1553. bed_type: string | null;
  1554. target_kind: 'specific_printer' | 'printer_class';
  1555. target_printer_id: number | null;
  1556. target_model_class: string | null;
  1557. fanout_strategy: 'max_parallel' | 'fill_one_first' | 'round_robin';
  1558. created_by: number | null;
  1559. created_at: string;
  1560. updated_at: string;
  1561. }
  1562. export interface SlicerPipelineCreateRequest {
  1563. name: string;
  1564. description?: string | null;
  1565. printer_preset: PresetRef;
  1566. process_preset: PresetRef;
  1567. filament_presets: PresetRef[];
  1568. bed_type?: string | null;
  1569. }
  1570. export type SlicerPipelineUpdateRequest = Partial<SlicerPipelineCreateRequest> & {
  1571. target_kind?: 'specific_printer' | 'printer_class';
  1572. // ``target_printer_id: 0`` means "clear the target" — the backend maps that
  1573. // to null. Use null in TypeScript for the same intent.
  1574. target_printer_id?: number | null;
  1575. target_model_class?: string | null;
  1576. fanout_strategy?: 'max_parallel' | 'fill_one_first' | 'round_robin';
  1577. };
  1578. export interface SlicerPipelinesListResponse {
  1579. pipelines: SlicerPipeline[];
  1580. }
  1581. // Slicer Pipeline runs (#1425 PR B + PR C)
  1582. export type PipelineEligibilityKind =
  1583. | 'printer_not_set'
  1584. | 'printer_not_found'
  1585. | 'printer_disabled'
  1586. | 'printer_offline'
  1587. | 'filament_type_mismatch'
  1588. | 'filament_color_mismatch'
  1589. | 'ams_slot_missing'
  1590. | 'filament_unverified'
  1591. | 'no_class_matches'
  1592. | 'class_not_set';
  1593. export interface PipelineEligibilityIssue {
  1594. kind: PipelineEligibilityKind;
  1595. slot_index: number | null;
  1596. expected: string | null;
  1597. actual: string | null;
  1598. }
  1599. export interface PipelinePerPrinterReport {
  1600. printer_id: number;
  1601. printer_name: string;
  1602. ok: boolean;
  1603. issues: PipelineEligibilityIssue[];
  1604. }
  1605. export interface PipelineEligibilityReport {
  1606. ok: boolean;
  1607. target_kind: 'specific_printer' | 'printer_class';
  1608. target_printer_id: number | null;
  1609. target_printer_name: string | null;
  1610. target_model_class: string | null;
  1611. issues: PipelineEligibilityIssue[];
  1612. printer_reports: PipelinePerPrinterReport[];
  1613. }
  1614. export interface PipelineJob {
  1615. id: number;
  1616. pipeline_run_id: number;
  1617. copy_index: number;
  1618. assigned_printer_id: number | null;
  1619. assigned_printer_name: string | null;
  1620. queue_entry_id: number | null;
  1621. status:
  1622. | 'pending'
  1623. | 'awaiting_printer'
  1624. | 'queued'
  1625. | 'printing'
  1626. | 'completed'
  1627. | 'failed'
  1628. | 'cancelled';
  1629. error_message: string | null;
  1630. dispatched_at: string | null;
  1631. completed_at: string | null;
  1632. }
  1633. export interface PipelineRun {
  1634. id: number;
  1635. pipeline_id: number | null;
  1636. pipeline_name: string | null;
  1637. source_library_file_id: number | null;
  1638. source_archive_id: number | null;
  1639. source_filename: string | null;
  1640. parent_run_id: number | null;
  1641. copies: number;
  1642. copies_completed: number;
  1643. copies_failed: number;
  1644. copies_cancelled: number;
  1645. copies_in_progress: number;
  1646. status:
  1647. | 'queued'
  1648. | 'slicing'
  1649. | 'dispatching'
  1650. | 'in_progress'
  1651. | 'completed'
  1652. | 'failed'
  1653. | 'partial_failure'
  1654. | 'cancelled';
  1655. slice_job_id: number | null;
  1656. sliced_library_file_id: number | null;
  1657. eligibility_overridden: boolean;
  1658. error_message: string | null;
  1659. created_by: number | null;
  1660. created_at: string;
  1661. started_at: string | null;
  1662. completed_at: string | null;
  1663. jobs: PipelineJob[];
  1664. target_kind: 'specific_printer' | 'printer_class' | null;
  1665. target_printer_id: number | null;
  1666. target_model_class: string | null;
  1667. fanout_strategy: 'max_parallel' | 'fill_one_first' | 'round_robin' | null;
  1668. }
  1669. export interface PipelineRunListResponse {
  1670. runs: PipelineRun[];
  1671. total: number;
  1672. }
  1673. export interface SliceResponse {
  1674. library_file_id: number;
  1675. name: string;
  1676. print_time_seconds: number;
  1677. filament_used_g: number;
  1678. filament_used_mm: number;
  1679. used_embedded_settings: boolean;
  1680. }
  1681. export interface SliceArchiveResponse {
  1682. archive_id: number;
  1683. name: string;
  1684. print_time_seconds: number;
  1685. filament_used_g: number;
  1686. filament_used_mm: number;
  1687. used_embedded_settings: boolean;
  1688. }
  1689. // Background slice-job lifecycle. POST /slice returns 202 + this shape;
  1690. // the frontend polls /slice-jobs/{id} until status is terminal.
  1691. export type SliceJobStatus = 'pending' | 'running' | 'completed' | 'failed';
  1692. export interface SliceJobEnqueueResponse {
  1693. job_id: number;
  1694. status: SliceJobStatus;
  1695. status_url: string;
  1696. }
  1697. export interface SliceJobProgress {
  1698. /** Stage label emitted by the slicer ("Generating G-code", "Slicing finished"). */
  1699. stage: string;
  1700. total_percent: number;
  1701. plate_percent: number;
  1702. /** 1-indexed plate position; 0 means "all plates" / final completion. */
  1703. plate_index: number;
  1704. plate_count: number;
  1705. updated_at: number;
  1706. /** When the backend is in the cross-class slice-all loop (#1493), each
  1707. * per-plate sub-slice's progress is augmented with the loop position
  1708. * so the toast can show "Plate 2 of 5 — Generating G-code 47%". The
  1709. * fields are absent on a single-plate slice. */
  1710. multi_plate_index?: number;
  1711. multi_plate_count?: number;
  1712. }
  1713. export interface SliceJobState {
  1714. job_id: number;
  1715. status: SliceJobStatus;
  1716. kind: 'library_file' | 'archive';
  1717. source_id: number;
  1718. source_name: string;
  1719. created_at: string;
  1720. started_at: string | null;
  1721. completed_at: string | null;
  1722. /** Live progress fed by the sidecar's --pipe channel; null until the
  1723. * slicer emits its first frame (early "Initializing" phase) or when
  1724. * the sidecar doesn't support progress. */
  1725. progress: SliceJobProgress | null;
  1726. result?: SliceResponse | SliceArchiveResponse;
  1727. error_status?: number;
  1728. error_detail?: string;
  1729. }
  1730. // Local preset types (OrcaSlicer imports)
  1731. export interface LocalPreset {
  1732. id: number;
  1733. name: string;
  1734. preset_type: string;
  1735. source: string;
  1736. filament_type: string | null;
  1737. filament_vendor: string | null;
  1738. nozzle_temp_min: number | null;
  1739. nozzle_temp_max: number | null;
  1740. pressure_advance: string | null;
  1741. default_filament_colour: string | null;
  1742. filament_cost: string | null;
  1743. filament_density: string | null;
  1744. compatible_printers: string | null;
  1745. inherits: string | null;
  1746. version: string | null;
  1747. created_at: string;
  1748. updated_at: string;
  1749. }
  1750. export interface LocalPresetDetail extends LocalPreset {
  1751. setting: Record<string, unknown>;
  1752. }
  1753. export interface LocalPresetsResponse {
  1754. filament: LocalPreset[];
  1755. printer: LocalPreset[];
  1756. process: LocalPreset[];
  1757. }
  1758. export interface ImportResponse {
  1759. success: boolean;
  1760. imported: number;
  1761. skipped: number;
  1762. errors: string[];
  1763. }
  1764. export interface FieldOption {
  1765. value: string;
  1766. label: string;
  1767. }
  1768. export interface FieldDefinition {
  1769. key: string;
  1770. label: string;
  1771. type: 'text' | 'number' | 'boolean' | 'select';
  1772. category: string;
  1773. description?: string;
  1774. options?: FieldOption[];
  1775. unit?: string;
  1776. min?: number;
  1777. max?: number;
  1778. step?: number;
  1779. }
  1780. export interface FieldDefinitionsResponse {
  1781. version: string;
  1782. description: string;
  1783. fields: FieldDefinition[];
  1784. }
  1785. export interface CloudDevice {
  1786. dev_id: string;
  1787. name: string;
  1788. dev_model_name: string | null;
  1789. dev_product_name: string | null;
  1790. online: boolean;
  1791. }
  1792. // Smart Plug types
  1793. export interface SmartPlug {
  1794. id: number;
  1795. name: string;
  1796. plug_type: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  1797. ip_address: string | null; // Required for Tasmota
  1798. ha_entity_id: string | null; // Required for Home Assistant (e.g., "switch.printer_plug", "script.turn_on_printer")
  1799. // Home Assistant energy sensor entities (optional)
  1800. ha_power_entity: string | null;
  1801. ha_energy_today_entity: string | null;
  1802. ha_energy_total_entity: string | null;
  1803. // MQTT fields (required when plug_type="mqtt")
  1804. // Legacy field - kept for backward compatibility
  1805. mqtt_topic: string | null; // Deprecated, use mqtt_power_topic
  1806. mqtt_multiplier: number; // Deprecated, use mqtt_power_multiplier
  1807. // Power monitoring
  1808. mqtt_power_topic: string | null; // Topic for power data
  1809. mqtt_power_path: string | null; // e.g., "power_l1" or "data.power"
  1810. mqtt_power_multiplier: number; // Unit conversion for power
  1811. // Energy monitoring
  1812. mqtt_energy_topic: string | null; // Topic for energy data
  1813. mqtt_energy_path: string | null; // e.g., "energy_l1"
  1814. mqtt_energy_multiplier: number; // Unit conversion for energy
  1815. // State monitoring
  1816. mqtt_state_topic: string | null; // Topic for state data
  1817. mqtt_state_path: string | null; // e.g., "state_l1" for ON/OFF
  1818. mqtt_state_on_value: string | null; // What value means "ON" (e.g., "ON", "true", "1")
  1819. // REST/Webhook fields (required when plug_type="rest")
  1820. rest_on_url: string | null;
  1821. rest_on_body: string | null;
  1822. rest_off_url: string | null;
  1823. rest_off_body: string | null;
  1824. rest_method: string | null;
  1825. rest_headers: string | null;
  1826. rest_status_url: string | null;
  1827. rest_status_path: string | null;
  1828. rest_status_on_value: string | null;
  1829. rest_power_url: string | null;
  1830. rest_power_path: string | null;
  1831. rest_power_multiplier: number;
  1832. rest_energy_url: string | null;
  1833. rest_energy_path: string | null;
  1834. rest_energy_multiplier: number;
  1835. // Lifetime counter, separate from the daily one (#2539). A Shelly reports only
  1836. // this; Today and Yesterday are derived from its hourly snapshots.
  1837. rest_energy_total_path: string | null;
  1838. rest_energy_total_multiplier: number;
  1839. printer_id: number | null;
  1840. // #2629: only a plug that really feeds the printer may mark it offline when
  1841. // switched off. Accessory plugs follow the print cycle without powering it.
  1842. controls_printer_power: boolean;
  1843. enabled: boolean;
  1844. auto_on: boolean;
  1845. auto_off: boolean;
  1846. auto_off_persistent: boolean;
  1847. off_delay_mode: 'time' | 'temperature';
  1848. off_delay_minutes: number;
  1849. off_temp_threshold: number;
  1850. // #1349: auto-off after AMS drying completes.
  1851. auto_off_after_drying: boolean;
  1852. off_delay_after_drying_minutes: number;
  1853. username: string | null;
  1854. password: string | null;
  1855. // Power alerts
  1856. power_alert_enabled: boolean;
  1857. power_alert_high: number | null;
  1858. power_alert_low: number | null;
  1859. power_alert_last_triggered: string | null;
  1860. // Schedule
  1861. schedule_enabled: boolean;
  1862. schedule_on_time: string | null;
  1863. schedule_off_time: string | null;
  1864. // Visibility options
  1865. show_in_switchbar: boolean;
  1866. show_on_printer_card: boolean; // For scripts: show on printer card
  1867. // Status
  1868. last_state: string | null;
  1869. last_checked: string | null;
  1870. auto_off_executed: boolean; // True when auto-off was triggered after print
  1871. created_at: string;
  1872. updated_at: string;
  1873. }
  1874. export interface SmartPlugCreate {
  1875. name: string;
  1876. plug_type?: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  1877. ip_address?: string | null; // Required for Tasmota
  1878. ha_entity_id?: string | null; // Required for Home Assistant
  1879. // Home Assistant energy sensor entities (optional)
  1880. ha_power_entity?: string | null;
  1881. ha_energy_today_entity?: string | null;
  1882. ha_energy_total_entity?: string | null;
  1883. // MQTT fields (required when plug_type="mqtt")
  1884. // Legacy fields - kept for backward compatibility
  1885. mqtt_topic?: string | null;
  1886. mqtt_multiplier?: number;
  1887. // Power monitoring
  1888. mqtt_power_topic?: string | null;
  1889. mqtt_power_path?: string | null;
  1890. mqtt_power_multiplier?: number;
  1891. // Energy monitoring
  1892. mqtt_energy_topic?: string | null;
  1893. mqtt_energy_path?: string | null;
  1894. mqtt_energy_multiplier?: number;
  1895. // State monitoring
  1896. mqtt_state_topic?: string | null;
  1897. mqtt_state_path?: string | null;
  1898. mqtt_state_on_value?: string | null;
  1899. // REST fields
  1900. rest_on_url?: string | null;
  1901. rest_on_body?: string | null;
  1902. rest_off_url?: string | null;
  1903. rest_off_body?: string | null;
  1904. rest_method?: string | null;
  1905. rest_headers?: string | null;
  1906. rest_status_url?: string | null;
  1907. rest_status_path?: string | null;
  1908. rest_status_on_value?: string | null;
  1909. rest_power_url?: string | null;
  1910. rest_power_path?: string | null;
  1911. rest_power_multiplier?: number;
  1912. rest_energy_url?: string | null;
  1913. rest_energy_path?: string | null;
  1914. rest_energy_multiplier?: number;
  1915. rest_energy_total_path?: string | null;
  1916. rest_energy_total_multiplier?: number;
  1917. printer_id?: number | null;
  1918. // #2629
  1919. controls_printer_power?: boolean;
  1920. enabled?: boolean;
  1921. auto_on?: boolean;
  1922. auto_off?: boolean;
  1923. auto_off_persistent?: boolean;
  1924. off_delay_mode?: 'time' | 'temperature';
  1925. off_delay_minutes?: number;
  1926. off_temp_threshold?: number;
  1927. // #1349
  1928. auto_off_after_drying?: boolean;
  1929. off_delay_after_drying_minutes?: number;
  1930. username?: string | null;
  1931. password?: string | null;
  1932. // Power alerts
  1933. power_alert_enabled?: boolean;
  1934. power_alert_high?: number | null;
  1935. power_alert_low?: number | null;
  1936. // Schedule
  1937. schedule_enabled?: boolean;
  1938. schedule_on_time?: string | null;
  1939. schedule_off_time?: string | null;
  1940. // Visibility options
  1941. show_in_switchbar?: boolean;
  1942. show_on_printer_card?: boolean;
  1943. }
  1944. export interface SmartPlugUpdate {
  1945. name?: string;
  1946. plug_type?: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  1947. ip_address?: string | null;
  1948. ha_entity_id?: string | null;
  1949. // Home Assistant energy sensor entities (optional)
  1950. ha_power_entity?: string | null;
  1951. ha_energy_today_entity?: string | null;
  1952. ha_energy_total_entity?: string | null;
  1953. // MQTT fields (legacy)
  1954. mqtt_topic?: string | null;
  1955. mqtt_multiplier?: number;
  1956. // MQTT power fields
  1957. mqtt_power_topic?: string | null;
  1958. mqtt_power_path?: string | null;
  1959. mqtt_power_multiplier?: number;
  1960. // MQTT energy fields
  1961. mqtt_energy_topic?: string | null;
  1962. mqtt_energy_path?: string | null;
  1963. mqtt_energy_multiplier?: number;
  1964. // MQTT state fields
  1965. mqtt_state_topic?: string | null;
  1966. mqtt_state_path?: string | null;
  1967. mqtt_state_on_value?: string | null;
  1968. // REST fields
  1969. rest_on_url?: string | null;
  1970. rest_on_body?: string | null;
  1971. rest_off_url?: string | null;
  1972. rest_off_body?: string | null;
  1973. rest_method?: string | null;
  1974. rest_headers?: string | null;
  1975. rest_status_url?: string | null;
  1976. rest_status_path?: string | null;
  1977. rest_status_on_value?: string | null;
  1978. rest_power_url?: string | null;
  1979. rest_power_path?: string | null;
  1980. rest_power_multiplier?: number;
  1981. rest_energy_url?: string | null;
  1982. rest_energy_path?: string | null;
  1983. rest_energy_multiplier?: number;
  1984. rest_energy_total_path?: string | null;
  1985. rest_energy_total_multiplier?: number;
  1986. printer_id?: number | null;
  1987. // #2629
  1988. controls_printer_power?: boolean;
  1989. enabled?: boolean;
  1990. auto_on?: boolean;
  1991. auto_off?: boolean;
  1992. auto_off_persistent?: boolean;
  1993. off_delay_mode?: 'time' | 'temperature';
  1994. off_delay_minutes?: number;
  1995. off_temp_threshold?: number;
  1996. // #1349
  1997. auto_off_after_drying?: boolean;
  1998. off_delay_after_drying_minutes?: number;
  1999. username?: string | null;
  2000. password?: string | null;
  2001. // Power alerts
  2002. power_alert_enabled?: boolean;
  2003. power_alert_high?: number | null;
  2004. power_alert_low?: number | null;
  2005. // Schedule
  2006. schedule_enabled?: boolean;
  2007. schedule_on_time?: string | null;
  2008. schedule_off_time?: string | null;
  2009. // Visibility options
  2010. show_in_switchbar?: boolean;
  2011. show_on_printer_card?: boolean;
  2012. }
  2013. // Home Assistant entity for smart plug selection
  2014. export interface HAEntity {
  2015. entity_id: string;
  2016. friendly_name: string;
  2017. state: string | null;
  2018. domain: string; // "switch", "light", "input_boolean", "script"
  2019. }
  2020. // Home Assistant sensor entity for energy monitoring
  2021. export interface HASensorEntity {
  2022. entity_id: string;
  2023. friendly_name: string;
  2024. state: string | null;
  2025. unit_of_measurement: string | null; // "W", "kW", "kWh", "Wh"
  2026. }
  2027. export interface HATestConnectionResult {
  2028. success: boolean;
  2029. message: string | null;
  2030. error: string | null;
  2031. }
  2032. // A Home Assistant entity bound to a printer for display on its card (#1148, #448).
  2033. // Read-only: unlike a SmartPlug there is nothing here to switch.
  2034. export interface PrinterHASensor {
  2035. id: number;
  2036. printer_id: number;
  2037. name: string;
  2038. entity_id: string;
  2039. kind: 'binary' | 'numeric';
  2040. device_class: string | null; // HA's own class: "door", "temperature", ...
  2041. unit: string | null; // numeric sensors only
  2042. // What counts as needing attention. Binary sensors use alert_state, numeric
  2043. // ones the thresholds; all null means the sensor is display-only.
  2044. alert_state: 'on' | 'off' | null;
  2045. alert_above: number | null;
  2046. alert_below: number | null;
  2047. block_print: boolean; // hold the printer's queue while alerting
  2048. notify_on_alert: boolean;
  2049. show_on_printer_card: boolean;
  2050. sort_order: number;
  2051. last_state: string | null;
  2052. last_changed: string | null;
  2053. last_checked: string | null;
  2054. created_at: string;
  2055. updated_at: string;
  2056. }
  2057. export interface PrinterHASensorReading {
  2058. id: number;
  2059. name: string;
  2060. entity_id: string;
  2061. kind: 'binary' | 'numeric';
  2062. device_class: string | null;
  2063. unit: string | null;
  2064. state: string | null; // null when unreadable or not yet polled
  2065. value: number | null; // numeric sensors only
  2066. alerting: boolean;
  2067. block_print: boolean;
  2068. reachable: boolean;
  2069. last_changed: string | null;
  2070. }
  2071. export interface PrinterHASensorCreate {
  2072. printer_id: number;
  2073. name: string;
  2074. entity_id: string;
  2075. kind: 'binary' | 'numeric';
  2076. device_class?: string | null;
  2077. unit?: string | null;
  2078. alert_state?: 'on' | 'off' | null;
  2079. alert_above?: number | null;
  2080. alert_below?: number | null;
  2081. block_print?: boolean;
  2082. notify_on_alert?: boolean;
  2083. show_on_printer_card?: boolean;
  2084. sort_order?: number;
  2085. }
  2086. export type PrinterHASensorUpdate = Partial<Omit<PrinterHASensorCreate, 'printer_id'>>;
  2087. // An entity offered by the binding picker.
  2088. export interface HADisplayEntity {
  2089. entity_id: string;
  2090. friendly_name: string;
  2091. state: string | null;
  2092. domain: string; // "binary_sensor" | "sensor"
  2093. device_class: string | null;
  2094. unit_of_measurement: string | null;
  2095. }
  2096. export interface SmartPlugEnergy {
  2097. power: number | null; // Current watts
  2098. voltage: number | null; // Volts
  2099. current: number | null; // Amps
  2100. today: number | null; // kWh used today
  2101. yesterday: number | null; // kWh used yesterday
  2102. total: number | null; // Total kWh
  2103. factor: number | null; // Power factor (0-1)
  2104. apparent_power: number | null; // VA
  2105. reactive_power: number | null; // VAr
  2106. }
  2107. export interface SmartPlugStatus {
  2108. state: string | null;
  2109. reachable: boolean;
  2110. device_name: string | null;
  2111. energy: SmartPlugEnergy | null;
  2112. }
  2113. export interface SmartPlugTestResult {
  2114. success: boolean;
  2115. state: string | null;
  2116. device_name: string | null;
  2117. }
  2118. // Tasmota Discovery types
  2119. export interface TasmotaScanStatus {
  2120. running: boolean;
  2121. scanned: number;
  2122. total: number;
  2123. }
  2124. export interface DiscoveredTasmotaDevice {
  2125. ip_address: string;
  2126. name: string;
  2127. module: number | null;
  2128. state: string | null;
  2129. discovered_at: string | null;
  2130. }
  2131. // Print Queue types
  2132. export interface PrintQueueItem {
  2133. id: number;
  2134. printer_id: number | null; // null = unassigned
  2135. target_model: string | null; // Target printer model for model-based assignment
  2136. target_location: string | null; // Target location filter for model-based assignment
  2137. required_filament_types: string[] | null; // Required filament types for model-based assignment
  2138. waiting_reason: string | null; // Why a model-based job hasn't started yet
  2139. // Cross-model alternatives (#671), in priority order. Empty for ordinary
  2140. // items. Present until dispatch resolves one, after which library_file_id and
  2141. // target_model name the candidate that actually ran.
  2142. variants?: Array<{
  2143. library_file_id: number;
  2144. filename: string;
  2145. target_model: string;
  2146. position: number;
  2147. }>;
  2148. // Either archive_id OR library_file_id must be set (archive created at print start)
  2149. archive_id: number | null;
  2150. library_file_id: number | null;
  2151. position: number;
  2152. scheduled_time: string | null;
  2153. require_previous_success: boolean;
  2154. auto_off_after: boolean;
  2155. manual_start: boolean; // Requires manual trigger to start (staged)
  2156. // Set by the dispatch scheduler when the assigned spool can't satisfy
  2157. // any required slot's grams (#1496). Surfaced on the queue row as a
  2158. // "filament short" badge; cleared on a successful ▶ click (live recheck).
  2159. filament_short: boolean;
  2160. // Persistent "Print Anyway" acknowledgement — once true the scheduler
  2161. // skips the deficit check for this item (#1698-followup). Set by the
  2162. // start route when skip_filament_check=true, or at queue creation if
  2163. // PrintModal's deficit warning was acknowledged.
  2164. skip_filament_check: boolean;
  2165. // True when the source archive carries the slicer's own live-resolved
  2166. // AMS-slot pick (extra_data.slicer_ams_mapping) — a reprint reuses that
  2167. // exact physical spool instead of re-deriving one from type/color.
  2168. archive_has_slicer_ams_mapping: boolean;
  2169. ams_mapping: number[] | null; // AMS slot mapping for multi-color prints
  2170. filament_overrides: Array<{ slot_id: number; type: string; color: string; color_name?: string; tray_info_idx?: string; force_color_match?: boolean }> | null; // Filament overrides for model-based assignment
  2171. plate_id: number | null; // Plate ID for multi-plate 3MF files
  2172. // Print options
  2173. bed_levelling: CalibrationMode;
  2174. flow_cali: CalibrationMode;
  2175. vibration_cali: boolean;
  2176. layer_inspect: boolean;
  2177. timelapse: boolean;
  2178. use_ams: boolean;
  2179. nozzle_offset_cali: CalibrationMode;
  2180. preheat_override: 'inherit' | 'on' | 'off';
  2181. preheat_chamber_target_override: number | null;
  2182. status: 'pending' | 'printing' | 'completed' | 'failed' | 'skipped' | 'cancelled';
  2183. started_at: string | null;
  2184. completed_at: string | null;
  2185. error_message: string | null;
  2186. created_at: string;
  2187. archive_name?: string | null;
  2188. archive_thumbnail?: string | null;
  2189. // True when the linked archive has been soft-deleted; archive_name /
  2190. // archive_thumbnail / downstream metadata are left null in that case so
  2191. // the UI doesn't 404-storm the now-missing endpoints (#1348 follow-up).
  2192. archive_deleted?: boolean;
  2193. library_file_name?: string | null;
  2194. library_file_thumbnail?: string | null;
  2195. printer_name?: string | null;
  2196. print_time_seconds?: number | null; // Estimated print time from archive or library file
  2197. filament_used_grams?: number | null; // Estimated print weight from archive or library file
  2198. filament_type?: string | null; // e.g. "PLA", "PETG"
  2199. filament_color?: string | null; // Hex RGBA from the slicer
  2200. bed_type?: string | null; // Build plate type for this print (per-plate accurate, #1281)
  2201. // User tracking (Issue #206)
  2202. created_by_id?: number | null;
  2203. created_by_username?: string | null;
  2204. // Batch grouping
  2205. batch_id?: number | null;
  2206. batch_name?: string | null;
  2207. // Shortest-job-first scheduling
  2208. been_jumped?: boolean;
  2209. // Auto-print G-code injection
  2210. gcode_injection?: boolean;
  2211. cleanup_library_after_dispatch?: boolean;
  2212. }
  2213. export interface PrintBatchPlateTarget {
  2214. plate_id: number | null;
  2215. plate_name?: string | null;
  2216. quantity_target: number;
  2217. sort_order?: number;
  2218. }
  2219. export interface PrintBatchPlateProgress {
  2220. plate_id: number | null;
  2221. plate_name: string | null;
  2222. quantity_target: number;
  2223. dispatched: number;
  2224. remaining: number;
  2225. pending_count: number;
  2226. printing_count: number;
  2227. completed_count: number;
  2228. failed_count: number;
  2229. cancelled_count: number;
  2230. skipped_count: number;
  2231. /** Measured from finished runs; null until one has produced a cost. */
  2232. actual_cost: number | null;
  2233. estimated_remaining_cost: number | null;
  2234. filament_used_grams: number | null;
  2235. print_time_seconds: number;
  2236. }
  2237. export interface PrintBatch {
  2238. id: number;
  2239. name: string;
  2240. archive_id: number | null;
  2241. library_file_id: number | null;
  2242. quantity: number;
  2243. status: string;
  2244. created_at: string;
  2245. completed_at: string | null;
  2246. created_by_id: number | null;
  2247. created_by_username: string | null;
  2248. project_id: number | null;
  2249. due_date: string | null;
  2250. notes: string | null;
  2251. pending_count: number;
  2252. printing_count: number;
  2253. completed_count: number;
  2254. failed_count: number;
  2255. cancelled_count: number;
  2256. skipped_count: number;
  2257. /** False for batches created before per-plate targets existed (#342):
  2258. * they report progress but owe nothing and cannot be dispatched from. */
  2259. has_targets: boolean;
  2260. target_count: number;
  2261. remaining_count: number;
  2262. actual_cost: number | null;
  2263. estimated_remaining_cost: number | null;
  2264. filament_used_grams: number | null;
  2265. print_time_seconds: number;
  2266. plates: PrintBatchPlateProgress[];
  2267. }
  2268. export interface PrintQueueItemCreate {
  2269. printer_id?: number | null; // null = unassigned
  2270. target_model?: string | null; // Target printer model (mutually exclusive with printer_id)
  2271. target_location?: string | null; // Target location filter (only used with target_model)
  2272. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; force_color_match?: boolean }> | null;
  2273. archive_id?: number | null;
  2274. library_file_id?: number | null;
  2275. scheduled_time?: string | null;
  2276. require_previous_success?: boolean;
  2277. auto_off_after?: boolean;
  2278. manual_start?: boolean; // Requires manual trigger to start (staged)
  2279. insert_at_top?: boolean; // Insert ahead of other pending items in the same queue scope
  2280. insert_position?: number | null; // 1-indexed insertion position for priority queueing
  2281. // PrintModal "Print Anyway" on the deficit warning — persisted so the
  2282. // scheduler doesn't immediately re-flag this item (#1698-followup).
  2283. skip_filament_check?: boolean;
  2284. ams_mapping?: number[] | null; // AMS slot mapping for multi-color prints
  2285. plate_id?: number | null; // Plate ID for multi-plate 3MF files
  2286. // Print options
  2287. bed_levelling?: CalibrationMode;
  2288. flow_cali?: CalibrationMode;
  2289. vibration_cali?: boolean;
  2290. layer_inspect?: boolean;
  2291. timelapse?: boolean;
  2292. use_ams?: boolean;
  2293. nozzle_offset_cali?: CalibrationMode;
  2294. preheat_override?: 'inherit' | 'on' | 'off';
  2295. preheat_chamber_target_override?: number | null;
  2296. // Auto-print G-code injection
  2297. gcode_injection?: boolean;
  2298. // Batch: create multiple copies (creates a batch if > 1)
  2299. quantity?: number;
  2300. // Existing batch to add this item into (multi-plate auto-batch flow).
  2301. batch_id?: number | null;
  2302. // Project to associate the resulting archive with
  2303. project_id?: number;
  2304. // Delete transient uploaded library file after scheduler creates the archive
  2305. cleanup_library_after_dispatch?: boolean;
  2306. // Cross-model alternatives (#671): several sliced files, one job, whichever
  2307. // printer frees up first. Mutually exclusive with printer_id (a named printer
  2308. // defeats the point) and with archive_id/library_file_id (these ARE the files).
  2309. // Order is priority — index 0 wins when several printers are idle at once.
  2310. variants?: QueueVariantCreate[];
  2311. }
  2312. /** One candidate file for a cross-model queue item (#671). */
  2313. export interface QueueVariantCreate {
  2314. library_file_id: number;
  2315. /** Read from the file's own sliced_for_model unless it declares none. */
  2316. target_model?: string | null;
  2317. plate_id?: number | null;
  2318. ams_mapping?: number[] | null;
  2319. nozzle_mapping?: number[] | null;
  2320. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; force_color_match?: boolean }> | null;
  2321. }
  2322. export interface PrintBatchCreate {
  2323. name: string;
  2324. archive_id?: number | null;
  2325. library_file_id?: number | null;
  2326. /** When set, the listed pending items are assigned to the new batch
  2327. * (manual "Group as batch"). When omitted/empty, an empty batch is
  2328. * returned so the client can pass batch_id on subsequent addToQueue calls. */
  2329. item_ids?: number[];
  2330. /** Per-plate targets. Omitting them creates a plain grouping batch. */
  2331. plates?: PrintBatchPlateTarget[];
  2332. project_id?: number | null;
  2333. due_date?: string | null;
  2334. notes?: string | null;
  2335. }
  2336. export interface PrintBatchUpdate {
  2337. name?: string;
  2338. status?: 'active' | 'cancelled';
  2339. /** Replaces the full target set — a plate omitted here is removed. */
  2340. plates?: PrintBatchPlateTarget[];
  2341. project_id?: number | null;
  2342. due_date?: string | null;
  2343. notes?: string | null;
  2344. }
  2345. export interface PrintBatchDispatchRequest {
  2346. plate_id?: number | null;
  2347. only_plate?: boolean;
  2348. /** Cap on items created across all plates; omit to queue everything owed. */
  2349. limit?: number;
  2350. }
  2351. export interface PrintQueueItemUpdate {
  2352. printer_id?: number | null; // null = unassign
  2353. target_model?: string | null; // Target printer model (mutually exclusive with printer_id)
  2354. target_location?: string | null; // Target location filter (only used with target_model)
  2355. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; force_color_match?: boolean }> | null;
  2356. position?: number;
  2357. scheduled_time?: string | null;
  2358. require_previous_success?: boolean;
  2359. auto_off_after?: boolean;
  2360. manual_start?: boolean;
  2361. ams_mapping?: number[];
  2362. plate_id?: number | null; // Plate ID for multi-plate 3MF files
  2363. // Print options
  2364. bed_levelling?: CalibrationMode;
  2365. flow_cali?: CalibrationMode;
  2366. vibration_cali?: boolean;
  2367. layer_inspect?: boolean;
  2368. timelapse?: boolean;
  2369. use_ams?: boolean;
  2370. nozzle_offset_cali?: CalibrationMode;
  2371. preheat_override?: 'inherit' | 'on' | 'off';
  2372. preheat_chamber_target_override?: number | null;
  2373. // Auto-print G-code injection
  2374. gcode_injection?: boolean;
  2375. }
  2376. export interface PrintQueueBulkUpdate {
  2377. item_ids: number[];
  2378. printer_id?: number | null;
  2379. scheduled_time?: string | null;
  2380. require_previous_success?: boolean;
  2381. auto_off_after?: boolean;
  2382. manual_start?: boolean;
  2383. // Print options
  2384. bed_levelling?: CalibrationMode;
  2385. flow_cali?: CalibrationMode;
  2386. vibration_cali?: boolean;
  2387. layer_inspect?: boolean;
  2388. timelapse?: boolean;
  2389. use_ams?: boolean;
  2390. nozzle_offset_cali?: CalibrationMode;
  2391. preheat_override?: 'inherit' | 'on' | 'off';
  2392. preheat_chamber_target_override?: number | null;
  2393. // Auto-print G-code injection
  2394. gcode_injection?: boolean;
  2395. }
  2396. export interface PrintQueueBulkUpdateResponse {
  2397. updated_count: number;
  2398. skipped_count: number;
  2399. message: string;
  2400. }
  2401. // MQTT Logging types
  2402. export interface MQTTLogEntry {
  2403. timestamp: string;
  2404. topic: string;
  2405. direction: 'in' | 'out';
  2406. payload: Record<string, unknown>;
  2407. }
  2408. export interface MQTTLogsResponse {
  2409. logging_enabled: boolean;
  2410. logs: MQTTLogEntry[];
  2411. }
  2412. // K-Profile types
  2413. export interface KProfile {
  2414. slot_id: number;
  2415. extruder_id: number;
  2416. nozzle_id: string;
  2417. nozzle_diameter: string;
  2418. filament_id: string;
  2419. name: string;
  2420. k_value: string;
  2421. n_coef: string;
  2422. ams_id: number;
  2423. tray_id: number;
  2424. setting_id: string | null;
  2425. }
  2426. export interface KProfileCreate {
  2427. slot_id?: number; // Storage slot, 0 for new profiles
  2428. extruder_id?: number;
  2429. nozzle_id: string;
  2430. nozzle_diameter: string;
  2431. filament_id: string;
  2432. name: string;
  2433. k_value: string;
  2434. n_coef?: string;
  2435. ams_id?: number;
  2436. tray_id?: number;
  2437. setting_id?: string | null;
  2438. }
  2439. export interface KProfileDelete {
  2440. slot_id: number; // cali_idx - calibration index to delete
  2441. extruder_id: number;
  2442. nozzle_id: string; // e.g., "HH00-0.4"
  2443. nozzle_diameter: string; // e.g., "0.4"
  2444. filament_id: string; // Bambu filament identifier
  2445. setting_id?: string | null; // Setting ID (for X1C series)
  2446. }
  2447. export interface KProfilesResponse {
  2448. profiles: KProfile[];
  2449. nozzle_diameter: string;
  2450. }
  2451. export interface KProfileNote {
  2452. setting_id: string;
  2453. note: string;
  2454. }
  2455. export interface KProfileNotesResponse {
  2456. notes: Record<string, string>; // setting_id -> note
  2457. }
  2458. // Slot Preset Mapping
  2459. export interface SlotPresetMapping {
  2460. ams_id: number;
  2461. tray_id: number;
  2462. preset_id: string;
  2463. preset_name: string;
  2464. }
  2465. // Filament types
  2466. export interface Filament {
  2467. id: number;
  2468. name: string;
  2469. type: string; // PLA, PETG, ABS, etc.
  2470. brand: string | null;
  2471. color: string | null;
  2472. color_hex: string | null;
  2473. cost_per_kg: number;
  2474. spool_weight_g: number;
  2475. currency: string;
  2476. density: number | null;
  2477. print_temp_min: number | null;
  2478. print_temp_max: number | null;
  2479. bed_temp_min: number | null;
  2480. bed_temp_max: number | null;
  2481. created_at: string;
  2482. updated_at: string;
  2483. }
  2484. // Notification Provider types
  2485. export type ProviderType = 'callmebot' | 'ntfy' | 'pushover' | 'telegram' | 'email' | 'discord' | 'webhook' | 'homeassistant' | 'bark';
  2486. export interface NotificationProvider {
  2487. id: number;
  2488. name: string;
  2489. provider_type: ProviderType;
  2490. enabled: boolean;
  2491. config: Record<string, unknown>;
  2492. // Print lifecycle events
  2493. on_print_start: boolean;
  2494. on_print_complete: boolean;
  2495. on_print_failed: boolean;
  2496. on_print_stopped: boolean;
  2497. on_print_progress: boolean;
  2498. on_print_missing_spool_assignment: boolean;
  2499. // Printer status events
  2500. on_printer_offline: boolean;
  2501. on_printer_error: boolean;
  2502. on_ai_failure_detection: boolean;
  2503. on_filament_low: boolean;
  2504. on_maintenance_due: boolean;
  2505. // AMS environmental alarms (regular AMS)
  2506. on_ams_humidity_high: boolean;
  2507. on_ams_temperature_high: boolean;
  2508. // AMS-HT environmental alarms
  2509. on_ams_ht_humidity_high: boolean;
  2510. on_ams_ht_temperature_high: boolean;
  2511. // Build plate detection
  2512. on_plate_not_empty: boolean;
  2513. on_plate_clear_required: boolean;
  2514. // Bed cooled
  2515. on_bed_cooled: boolean;
  2516. on_ha_sensor_alert: boolean;
  2517. // First layer complete
  2518. on_first_layer_complete: boolean;
  2519. // Inventory stock alerts
  2520. on_stock_reorder_alert: boolean;
  2521. on_stock_break_alert: boolean;
  2522. // Print queue events
  2523. on_queue_job_added: boolean;
  2524. on_queue_job_assigned: boolean;
  2525. on_queue_job_started: boolean;
  2526. on_queue_job_waiting: boolean;
  2527. on_queue_job_skipped: boolean;
  2528. on_queue_job_failed: boolean;
  2529. on_queue_completed: boolean;
  2530. // Quiet hours
  2531. quiet_hours_enabled: boolean;
  2532. quiet_hours_start: string | null;
  2533. quiet_hours_end: string | null;
  2534. // Daily digest
  2535. daily_digest_enabled: boolean;
  2536. daily_digest_time: string | null;
  2537. // Printer filter
  2538. printer_id: number | null;
  2539. // Status tracking
  2540. last_success: string | null;
  2541. last_error: string | null;
  2542. last_error_at: string | null;
  2543. // Timestamps
  2544. created_at: string;
  2545. updated_at: string;
  2546. }
  2547. export interface NotificationProviderCreate {
  2548. name: string;
  2549. provider_type: ProviderType;
  2550. enabled?: boolean;
  2551. config: Record<string, unknown>;
  2552. // Print lifecycle events
  2553. on_print_start?: boolean;
  2554. on_print_complete?: boolean;
  2555. on_print_failed?: boolean;
  2556. on_print_stopped?: boolean;
  2557. on_print_progress?: boolean;
  2558. on_print_missing_spool_assignment?: boolean;
  2559. // Printer status events
  2560. on_printer_offline?: boolean;
  2561. on_printer_error?: boolean;
  2562. on_ai_failure_detection?: boolean;
  2563. on_filament_low?: boolean;
  2564. on_maintenance_due?: boolean;
  2565. // AMS environmental alarms (regular AMS)
  2566. on_ams_humidity_high?: boolean;
  2567. on_ams_temperature_high?: boolean;
  2568. // AMS-HT environmental alarms
  2569. on_ams_ht_humidity_high?: boolean;
  2570. on_ams_ht_temperature_high?: boolean;
  2571. // Build plate detection
  2572. on_plate_not_empty?: boolean;
  2573. on_plate_clear_required?: boolean;
  2574. // Bed cooled
  2575. on_bed_cooled?: boolean;
  2576. on_ha_sensor_alert?: boolean;
  2577. // First layer complete
  2578. on_first_layer_complete?: boolean;
  2579. // Inventory stock alerts
  2580. on_stock_reorder_alert?: boolean;
  2581. on_stock_break_alert?: boolean;
  2582. // Print queue events
  2583. on_queue_job_added?: boolean;
  2584. on_queue_job_assigned?: boolean;
  2585. on_queue_job_started?: boolean;
  2586. on_queue_job_waiting?: boolean;
  2587. on_queue_job_skipped?: boolean;
  2588. on_queue_job_failed?: boolean;
  2589. on_queue_completed?: boolean;
  2590. // Quiet hours
  2591. quiet_hours_enabled?: boolean;
  2592. quiet_hours_start?: string | null;
  2593. quiet_hours_end?: string | null;
  2594. // Daily digest
  2595. daily_digest_enabled?: boolean;
  2596. daily_digest_time?: string | null;
  2597. // Printer filter
  2598. printer_id?: number | null;
  2599. }
  2600. export interface NotificationProviderUpdate {
  2601. name?: string;
  2602. provider_type?: ProviderType;
  2603. enabled?: boolean;
  2604. config?: Record<string, unknown>;
  2605. // Print lifecycle events
  2606. on_print_start?: boolean;
  2607. on_print_complete?: boolean;
  2608. on_print_failed?: boolean;
  2609. on_print_stopped?: boolean;
  2610. on_print_progress?: boolean;
  2611. on_print_missing_spool_assignment?: boolean;
  2612. // Printer status events
  2613. on_printer_offline?: boolean;
  2614. on_printer_error?: boolean;
  2615. on_ai_failure_detection?: boolean;
  2616. on_filament_low?: boolean;
  2617. on_maintenance_due?: boolean;
  2618. // AMS environmental alarms (regular AMS)
  2619. on_ams_humidity_high?: boolean;
  2620. on_ams_temperature_high?: boolean;
  2621. // AMS-HT environmental alarms
  2622. on_ams_ht_humidity_high?: boolean;
  2623. on_ams_ht_temperature_high?: boolean;
  2624. // Build plate detection
  2625. on_plate_not_empty?: boolean;
  2626. on_plate_clear_required?: boolean;
  2627. // Bed cooled
  2628. on_bed_cooled?: boolean;
  2629. on_ha_sensor_alert?: boolean;
  2630. // First layer complete
  2631. on_first_layer_complete?: boolean;
  2632. // Inventory stock alerts
  2633. on_stock_reorder_alert?: boolean;
  2634. on_stock_break_alert?: boolean;
  2635. // Print queue events
  2636. on_queue_job_added?: boolean;
  2637. on_queue_job_assigned?: boolean;
  2638. on_queue_job_started?: boolean;
  2639. on_queue_job_waiting?: boolean;
  2640. on_queue_job_skipped?: boolean;
  2641. on_queue_job_failed?: boolean;
  2642. on_queue_completed?: boolean;
  2643. // Quiet hours
  2644. quiet_hours_enabled?: boolean;
  2645. quiet_hours_start?: string | null;
  2646. quiet_hours_end?: string | null;
  2647. // Daily digest
  2648. daily_digest_enabled?: boolean;
  2649. daily_digest_time?: string | null;
  2650. // Printer filter
  2651. printer_id?: number | null;
  2652. }
  2653. // GitHub Backup types
  2654. export type ScheduleType = 'hourly' | 'daily' | 'weekly';
  2655. export type GitProviderType = 'github' | 'gitea' | 'forgejo' | 'gitlab';
  2656. /** How many cloud accounts a backup would collect presets from. Counts only —
  2657. * with auth enabled the accounts belong to individual users, so the backup
  2658. * administrator sees how many, never whose. */
  2659. export interface CloudAccountCounts {
  2660. bambu: number;
  2661. orca: number;
  2662. }
  2663. export interface GitHubBackupConfig {
  2664. id: number;
  2665. repository_url: string;
  2666. has_token: boolean;
  2667. branch: string;
  2668. provider: GitProviderType;
  2669. allow_insecure_http: boolean;
  2670. schedule_enabled: boolean;
  2671. schedule_type: ScheduleType;
  2672. backup_kprofiles: boolean;
  2673. backup_cloud_profiles: boolean;
  2674. backup_settings: boolean;
  2675. backup_spools: boolean;
  2676. backup_archives: boolean;
  2677. enabled: boolean;
  2678. last_backup_at: string | null;
  2679. last_backup_status: string | null;
  2680. last_backup_message: string | null;
  2681. last_backup_commit_sha: string | null;
  2682. next_scheduled_run: string | null;
  2683. created_at: string;
  2684. updated_at: string;
  2685. }
  2686. export interface GitHubBackupConfigCreate {
  2687. repository_url: string;
  2688. access_token: string;
  2689. branch?: string;
  2690. provider?: GitProviderType;
  2691. allow_insecure_http?: boolean;
  2692. schedule_enabled?: boolean;
  2693. schedule_type?: ScheduleType;
  2694. backup_kprofiles?: boolean;
  2695. backup_cloud_profiles?: boolean;
  2696. backup_settings?: boolean;
  2697. backup_spools?: boolean;
  2698. backup_archives?: boolean;
  2699. enabled?: boolean;
  2700. }
  2701. export interface GitHubBackupLog {
  2702. id: number;
  2703. config_id: number;
  2704. started_at: string;
  2705. completed_at: string | null;
  2706. status: string;
  2707. trigger: string;
  2708. commit_sha: string | null;
  2709. files_changed: number;
  2710. error_message: string | null;
  2711. }
  2712. export interface GitHubBackupStatus {
  2713. configured: boolean;
  2714. enabled: boolean;
  2715. is_running: boolean;
  2716. restore_running: boolean;
  2717. progress: string | null;
  2718. last_backup_at: string | null;
  2719. last_backup_status: string | null;
  2720. next_scheduled_run: string | null;
  2721. }
  2722. // Restore from a Git backup (#2656). Cloud profiles are absent deliberately —
  2723. // the backup collector never writes them, so there is nothing to restore.
  2724. export type RestoreCategory = 'kprofiles' | 'settings' | 'spools' | 'archives';
  2725. export interface GitHubCommitInfo {
  2726. sha: string;
  2727. message: string;
  2728. author: string;
  2729. date: string;
  2730. }
  2731. export interface GitHubCommitListResponse {
  2732. success: boolean;
  2733. message: string;
  2734. branch: string;
  2735. commits: GitHubCommitInfo[];
  2736. }
  2737. /**
  2738. * Values the server interpolates into a translated note or preview detail.
  2739. * Kept to strings and numbers on purpose — anything richer would have to be
  2740. * formatted server-side and could not be translated.
  2741. */
  2742. export type GitHubRestoreParams = Record<string, string | number>;
  2743. export interface GitHubRestorePreviewCategory {
  2744. category: RestoreCategory;
  2745. available: boolean;
  2746. item_count: number;
  2747. /** English rendering. Used as i18next's defaultValue, never shown on its own. */
  2748. detail: string | null;
  2749. /** Key under backup.restoreFromGit.details, or null when there is no caveat. */
  2750. detail_code: string | null;
  2751. detail_params: GitHubRestoreParams;
  2752. }
  2753. export interface GitHubRestorePreview {
  2754. success: boolean;
  2755. message: string;
  2756. ref: string;
  2757. commit: GitHubCommitInfo | null;
  2758. metadata_version: string | null;
  2759. categories: GitHubRestorePreviewCategory[];
  2760. }
  2761. export interface GitHubRestoreRequest {
  2762. ref?: string;
  2763. categories: RestoreCategory[];
  2764. overwrite_existing?: boolean;
  2765. }
  2766. /**
  2767. * One tally note, as a translation code plus its parameters (#2656).
  2768. *
  2769. * Same contract as {@link LocalBackupPathCheck} one card down: the server picks
  2770. * the code and supplies typed params, and the client renders
  2771. * ``t(`backup.restoreFromGit.notes.${code}`, { ...params, defaultValue: message })``.
  2772. * A code the client does not know yet falls back to the English `message`
  2773. * rather than showing the raw key.
  2774. */
  2775. export interface GitHubRestoreNote {
  2776. code: string;
  2777. params: GitHubRestoreParams;
  2778. message: string;
  2779. }
  2780. export interface GitHubRestoreCategoryResult {
  2781. restored: number;
  2782. skipped: number;
  2783. failed: number;
  2784. notes: GitHubRestoreNote[];
  2785. }
  2786. export interface GitHubRestoreResponse {
  2787. success: boolean;
  2788. message: string;
  2789. log_id: number | null;
  2790. ref: string | null;
  2791. results: Record<string, GitHubRestoreCategoryResult>;
  2792. }
  2793. export interface LocalBackupStatus {
  2794. enabled: boolean;
  2795. schedule: string;
  2796. time: string;
  2797. retention: number;
  2798. path: string;
  2799. default_path: string;
  2800. is_running: boolean;
  2801. last_backup_at: string | null;
  2802. last_status: string | null;
  2803. last_message: string | null;
  2804. next_run: string | null;
  2805. timezone: string;
  2806. }
  2807. export interface LocalBackupFile {
  2808. filename: string;
  2809. size: number;
  2810. created_at: string;
  2811. }
  2812. /** Result of writing a probe file into the configured backup directory (#2544). */
  2813. export interface LocalBackupPathCheck {
  2814. writable: boolean;
  2815. path: string;
  2816. /** 'ok' | 'sandboxed' | 'read_only' | 'permission_denied' | 'no_space' | 'not_a_directory' | 'missing' | 'error' */
  2817. code: string;
  2818. /** Raw OS error, shown as-is under the translated explanation. */
  2819. detail: string | null;
  2820. /** Copy-pasteable fix (systemd drop-in, compose snippet) — not translated. */
  2821. remedy: string | null;
  2822. message: string;
  2823. /** 'container_ephemeral' — writable, but the backups die with the container. */
  2824. warning: string | null;
  2825. }
  2826. export interface ObicoDetectionEvent {
  2827. printer_id: number;
  2828. task_name: string;
  2829. timestamp: string;
  2830. current_p: number;
  2831. score: number;
  2832. class: 'safe' | 'warning' | 'failure';
  2833. detections: number;
  2834. }
  2835. export interface ObicoStatus {
  2836. is_running: boolean;
  2837. last_error: string | null;
  2838. per_printer: Record<string, { class: string; frame_count: number; score: number }>;
  2839. thresholds: { low: number; high: number };
  2840. history: ObicoDetectionEvent[];
  2841. enabled: boolean;
  2842. ml_url: string;
  2843. sensitivity: 'low' | 'medium' | 'high';
  2844. action: 'notify' | 'pause' | 'pause_and_off';
  2845. poll_interval: number;
  2846. external_url_configured: boolean;
  2847. }
  2848. // Lightweight subset served under printers:read for the printer-card badge (#1546)
  2849. export interface ObicoPrinterStatus {
  2850. enabled: boolean;
  2851. // null = all printers are monitored
  2852. monitored_printers: number[] | null;
  2853. per_printer: Record<string, { class: string; frame_count: number; score: number }>;
  2854. // null = no error, or the viewer lacks settings:read (error strings can embed config URLs)
  2855. last_error: string | null;
  2856. }
  2857. export interface ObicoTestConnection {
  2858. ok: boolean;
  2859. status_code: number | null;
  2860. body: string | null;
  2861. error: string | null;
  2862. // Whether the ML API accepted the token. null = not determined (the health
  2863. // check failed first, or the token probe itself errored).
  2864. auth_ok: boolean | null;
  2865. }
  2866. export interface GitHubTestConnectionResponse {
  2867. success: boolean;
  2868. message: string;
  2869. repo_name: string | null;
  2870. permissions: Record<string, boolean> | null;
  2871. // true = confirmed private, false = confirmed public/internal,
  2872. // null = could not determine. Backend rejects save unless true.
  2873. is_private: boolean | null;
  2874. }
  2875. export interface GitHubBackupTriggerResponse {
  2876. success: boolean;
  2877. message: string;
  2878. log_id: number | null;
  2879. commit_sha: string | null;
  2880. files_changed: number;
  2881. }
  2882. export interface NotificationTestRequest {
  2883. provider_type: ProviderType;
  2884. config: Record<string, unknown>;
  2885. }
  2886. export interface NotificationTestResponse {
  2887. success: boolean;
  2888. message: string;
  2889. }
  2890. // Provider-specific config types for reference
  2891. export interface CallMeBotConfig {
  2892. phone: string;
  2893. apikey: string;
  2894. }
  2895. export interface NtfyConfig {
  2896. server?: string;
  2897. topic: string;
  2898. auth_token?: string | null;
  2899. }
  2900. export interface PushoverConfig {
  2901. user_key: string;
  2902. app_token: string;
  2903. priority?: number;
  2904. }
  2905. export interface TelegramConfig {
  2906. bot_token: string;
  2907. chat_id: string;
  2908. }
  2909. export interface EmailConfig {
  2910. smtp_server: string;
  2911. smtp_port?: number;
  2912. username: string;
  2913. password: string;
  2914. from_email: string;
  2915. to_email: string;
  2916. use_tls?: boolean;
  2917. }
  2918. // Notification Template types
  2919. export interface NotificationTemplate {
  2920. id: number;
  2921. event_type: string;
  2922. name: string;
  2923. title_template: string;
  2924. body_template: string;
  2925. is_default: boolean;
  2926. created_at: string;
  2927. updated_at: string;
  2928. }
  2929. export interface NotificationTemplateUpdate {
  2930. title_template?: string;
  2931. body_template?: string;
  2932. }
  2933. export interface EventVariablesResponse {
  2934. event_type: string;
  2935. event_name: string;
  2936. variables: string[];
  2937. }
  2938. export interface TemplatePreviewRequest {
  2939. event_type: string;
  2940. title_template: string;
  2941. body_template: string;
  2942. }
  2943. export interface TemplatePreviewResponse {
  2944. title: string;
  2945. body: string;
  2946. }
  2947. // Notification Log types
  2948. export interface NotificationLogEntry {
  2949. id: number;
  2950. provider_id: number;
  2951. provider_name: string | null;
  2952. provider_type: string | null;
  2953. event_type: string;
  2954. title: string;
  2955. message: string;
  2956. success: boolean;
  2957. error_message: string | null;
  2958. printer_id: number | null;
  2959. printer_name: string | null;
  2960. created_at: string;
  2961. }
  2962. export interface NotificationLogStats {
  2963. total: number;
  2964. success_count: number;
  2965. failure_count: number;
  2966. by_event_type: Record<string, number>;
  2967. by_provider: Record<string, number>;
  2968. }
  2969. // Spoolman types
  2970. export interface SpoolmanStatus {
  2971. enabled: boolean;
  2972. connected: boolean;
  2973. url: string | null;
  2974. }
  2975. export interface SkippedSpool {
  2976. location: string;
  2977. reason: string;
  2978. filament_type: string | null;
  2979. color: string | null;
  2980. }
  2981. export interface SpoolmanSyncResult {
  2982. success: boolean;
  2983. synced_count: number;
  2984. skipped_count: number;
  2985. skipped: SkippedSpool[];
  2986. errors: string[];
  2987. }
  2988. export interface UnlinkedSpool {
  2989. id: number;
  2990. filament_name: string | null;
  2991. filament_vendor: string | null;
  2992. filament_material: string | null;
  2993. filament_color_hex: string | null;
  2994. remaining_weight: number | null;
  2995. location: string | null;
  2996. }
  2997. export interface LinkedSpoolInfo {
  2998. id: number;
  2999. remaining_weight: number | null;
  3000. filament_weight: number | null;
  3001. }
  3002. export interface LinkedSpoolsMap {
  3003. linked: Record<string, LinkedSpoolInfo>; // tag (uppercase) -> spool info
  3004. }
  3005. export interface SpoolmanVendor {
  3006. id: number;
  3007. name: string;
  3008. }
  3009. export interface SpoolmanFilamentEntry {
  3010. id: number;
  3011. name: string;
  3012. material: string | null;
  3013. color_hex: string | null;
  3014. color_name: string | null;
  3015. weight: number | null;
  3016. spool_weight: number | null;
  3017. vendor: SpoolmanVendor | null;
  3018. }
  3019. // Inventory types
  3020. // Label printing (#809). Mirror of backend.app.services.label_renderer.TemplateName.
  3021. export type SpoolLabelTemplate =
  3022. | 'ams_holder_74x33'
  3023. | 'ams_holder_75x55'
  3024. | 'box_40x30'
  3025. | 'box_62x29'
  3026. | 'avery_5160'
  3027. | 'avery_l7160';
  3028. export interface InventorySpool {
  3029. id: number;
  3030. material: string;
  3031. subtype: string | null;
  3032. color_name: string | null;
  3033. // True when color_name was synthesised from subtype because Spoolman has no
  3034. // stored value (Spoolman-backed inventory only). The edit form uses this to
  3035. // leave the input blank, so the user doesn't round-trip the synth value
  3036. // back to Spoolman as if it were a real user-set color_name (#1319).
  3037. color_name_is_synthesized?: boolean;
  3038. rgba: string | null;
  3039. // Multi-colour gradient stops (#1154): comma-separated 6/8-char hex.
  3040. extra_colors: string | null;
  3041. // Visual effect overlay: sparkle | wood | marble | glow | matte.
  3042. effect_type: string | null;
  3043. brand: string | null;
  3044. label_weight: number;
  3045. core_weight: number;
  3046. core_weight_catalog_id: number | null;
  3047. weight_used: number;
  3048. // Anchor for the resettable "Total Consumed" display (#1390). The
  3049. // counter shown on the Inventory page is `weight_used - weight_used_baseline`;
  3050. // remaining is still `label_weight - weight_used`, so "Reset usage to 0"
  3051. // zeroes the counter without disturbing remaining. Optional for back-compat
  3052. // with rows from a pre-migration DB snapshot — default to 0.
  3053. weight_used_baseline?: number;
  3054. slicer_filament: string | null;
  3055. slicer_filament_name: string | null;
  3056. nozzle_temp_min: number | null;
  3057. nozzle_temp_max: number | null;
  3058. note: string | null;
  3059. added_full: boolean | null;
  3060. last_used: string | null;
  3061. encode_time: string | null;
  3062. tag_uid: string | null;
  3063. tray_uuid: string | null;
  3064. data_origin: string | null;
  3065. tag_type: string | null;
  3066. archived_at: string | null;
  3067. created_at: string;
  3068. updated_at: string;
  3069. cost_per_kg: number | null;
  3070. last_scale_weight: number | null;
  3071. last_weighed_at: string | null;
  3072. // User-defined category + per-spool low-stock threshold override (#729).
  3073. category: string | null;
  3074. low_stock_threshold_pct: number | null;
  3075. k_profiles?: SpoolKProfile[];
  3076. storage_location?: string | null;
  3077. location_id?: number | null;
  3078. }
  3079. export interface SpoolmanBulkCreateResult {
  3080. created: InventorySpool[];
  3081. requested_count: number;
  3082. failed_count: number;
  3083. }
  3084. // ── CSV import/export (#1576) ──────────────────────────────────────────────
  3085. /** One row's outcome from the import preview / real import. */
  3086. export interface CsvImportRow {
  3087. row_number: number;
  3088. status: 'valid' | 'error' | 'skipped';
  3089. reason: string | null;
  3090. material: string | null;
  3091. brand: string | null;
  3092. color_name: string | null;
  3093. rgba: string | null;
  3094. /** rgba/extra_colors/effect_type were filled from the Color Catalog. */
  3095. resolved_color: boolean;
  3096. /** The catalog match came from a different material's variant (no exact
  3097. * material match). Shown as a warning in the preview. */
  3098. cross_material_color: boolean;
  3099. /** An active spool with the same material+brand+color already exists.
  3100. * Informational only — the import still creates the row. */
  3101. duplicate_of_existing: boolean;
  3102. }
  3103. /** Dry-run preview: per-row classification, no rows written. */
  3104. export interface CsvImportPreview {
  3105. columns: string[];
  3106. total: number;
  3107. valid_count: number;
  3108. error_count: number;
  3109. skipped_count: number;
  3110. rows: CsvImportRow[];
  3111. warnings: string[];
  3112. }
  3113. /** Summary returned after a real (non-dry-run) import. */
  3114. export interface CsvImportResult {
  3115. created: number;
  3116. skipped: number;
  3117. errors: number;
  3118. error_rows: CsvImportRow[];
  3119. }
  3120. export interface SpoolUsageRecord {
  3121. id: number;
  3122. spool_id: number;
  3123. printer_id: number | null;
  3124. print_name: string | null;
  3125. weight_used: number;
  3126. percent_used: number;
  3127. status: string;
  3128. cost: number | null;
  3129. created_at: string;
  3130. }
  3131. export interface SpoolKProfile {
  3132. id: number;
  3133. spool_id: number;
  3134. printer_id: number;
  3135. extruder: number;
  3136. nozzle_diameter: string;
  3137. nozzle_type: string | null;
  3138. k_value: number;
  3139. name: string | null;
  3140. cali_idx: number | null;
  3141. setting_id: string | null;
  3142. created_at: string;
  3143. }
  3144. export interface SpoolKProfileInput {
  3145. printer_id: number;
  3146. extruder?: number;
  3147. nozzle_diameter?: string;
  3148. nozzle_type?: string | null;
  3149. k_value: number;
  3150. name?: string | null;
  3151. cali_idx?: number | null;
  3152. setting_id?: string | null;
  3153. }
  3154. export interface SpoolAssignment {
  3155. id: number;
  3156. spool_id: number;
  3157. printer_id: number;
  3158. printer_name: string | null;
  3159. ams_id: number;
  3160. tray_id: number;
  3161. fingerprint_color: string | null;
  3162. fingerprint_type: string | null;
  3163. spool?: InventorySpool | null;
  3164. configured: boolean;
  3165. pending_config?: boolean; // Slot was empty at assign time; will configure on insert
  3166. created_at: string;
  3167. ams_label?: string | null; // User-defined friendly name for the AMS unit
  3168. }
  3169. export interface FilamentSkuSettings {
  3170. id: number;
  3171. material: string;
  3172. subtype: string | null;
  3173. brand: string | null;
  3174. color_name: string | null;
  3175. lead_time_days: number;
  3176. safety_margin_value: number;
  3177. safety_margin_unit: 'days' | 'g';
  3178. alerts_snoozed: boolean;
  3179. }
  3180. export interface ShoppingListItem {
  3181. id: number;
  3182. material: string;
  3183. subtype: string | null;
  3184. brand: string | null;
  3185. color_name: string | null;
  3186. quantity_spools: number;
  3187. note: string | null;
  3188. status: 'pending' | 'purchased' | 'received';
  3189. purchased_at: string | null;
  3190. added_at: string;
  3191. }
  3192. export interface ShoppingListItemCreate {
  3193. material: string;
  3194. subtype: string | null;
  3195. brand: string | null;
  3196. color_name: string | null;
  3197. quantity_spools: number;
  3198. note?: string | null;
  3199. }
  3200. // Update types
  3201. export interface VersionInfo {
  3202. version: string;
  3203. repo: string;
  3204. }
  3205. export interface UpdateCheckResult {
  3206. update_available: boolean;
  3207. current_version: string;
  3208. latest_version: string | null;
  3209. release_name?: string;
  3210. release_notes?: string;
  3211. release_url?: string;
  3212. published_at?: string;
  3213. error?: string;
  3214. message?: string;
  3215. is_docker?: boolean;
  3216. is_ha_addon?: boolean;
  3217. is_windows_installer?: boolean;
  3218. update_method?: 'docker' | 'git' | 'ha_addon' | 'windows_installer';
  3219. installer_download_url?: string | null;
  3220. // Best-effort guess at the compose directory (#2664). Prefill only — the
  3221. // value the user saved lives on AppSettings.docker_compose_dir, so clearing
  3222. // that field falls back to this guess instead of resurrecting the old value.
  3223. compose_dir_detected?: string | null;
  3224. }
  3225. export interface UpdateStatus {
  3226. status: 'idle' | 'checking' | 'downloading' | 'installing' | 'complete' | 'error';
  3227. progress: number;
  3228. message: string;
  3229. error: string | null;
  3230. }
  3231. // Maintenance types
  3232. export interface MaintenanceType {
  3233. id: number;
  3234. name: string;
  3235. description: string | null;
  3236. default_interval_hours: number;
  3237. interval_type: 'hours' | 'days'; // "hours" = print hours, "days" = calendar days
  3238. icon: string | null;
  3239. wiki_url: string | null; // Documentation link
  3240. is_system: boolean;
  3241. created_at: string;
  3242. }
  3243. export interface MaintenanceTypeCreate {
  3244. name: string;
  3245. description?: string | null;
  3246. default_interval_hours?: number;
  3247. interval_type?: 'hours' | 'days';
  3248. icon?: string | null;
  3249. wiki_url?: string | null;
  3250. }
  3251. export interface MaintenanceStatus {
  3252. id: number;
  3253. printer_id: number;
  3254. printer_name: string;
  3255. printer_model: string | null;
  3256. maintenance_type_id: number;
  3257. maintenance_type_name: string;
  3258. maintenance_type_icon: string | null;
  3259. maintenance_type_wiki_url: string | null; // Custom wiki URL from type
  3260. enabled: boolean;
  3261. interval_hours: number; // For hours type: print hours; for days type: number of days
  3262. interval_type: 'hours' | 'days';
  3263. current_hours: number;
  3264. hours_since_maintenance: number;
  3265. hours_until_due: number;
  3266. days_since_maintenance: number | null; // For days type
  3267. days_until_due: number | null; // For days type
  3268. is_due: boolean;
  3269. is_warning: boolean;
  3270. last_performed_at: string | null;
  3271. }
  3272. export interface PrinterMaintenanceOverview {
  3273. printer_id: number;
  3274. printer_name: string;
  3275. printer_model: string | null;
  3276. total_print_hours: number;
  3277. maintenance_items: MaintenanceStatus[];
  3278. due_count: number;
  3279. warning_count: number;
  3280. }
  3281. export interface MaintenanceHistory {
  3282. id: number;
  3283. printer_maintenance_id: number;
  3284. performed_at: string;
  3285. hours_at_maintenance: number;
  3286. notes: string | null;
  3287. }
  3288. export interface MaintenanceSummary {
  3289. total_due: number;
  3290. total_warning: number;
  3291. printers_with_issues: Array<{
  3292. printer_id: number;
  3293. printer_name: string;
  3294. due_count: number;
  3295. warning_count: number;
  3296. }>;
  3297. }
  3298. // External Links (sidebar)
  3299. export interface ExternalLink {
  3300. id: number;
  3301. name: string;
  3302. url: string;
  3303. icon: string;
  3304. open_in_new_tab: boolean;
  3305. custom_icon: string | null;
  3306. sort_order: number;
  3307. created_at: string;
  3308. updated_at: string;
  3309. }
  3310. export interface ExternalLinkCreate {
  3311. name: string;
  3312. url: string;
  3313. icon: string;
  3314. open_in_new_tab?: boolean;
  3315. }
  3316. export interface ExternalLinkUpdate {
  3317. name?: string;
  3318. url?: string;
  3319. icon?: string;
  3320. open_in_new_tab?: boolean;
  3321. }
  3322. // Permission type - all available permissions
  3323. export type Permission =
  3324. | 'printers:read' | 'printers:create' | 'printers:update' | 'printers:delete' | 'printers:control' | 'printers:files' | 'printers:ams_rfid' | 'printers:clear_plate'
  3325. | 'archives:read' | 'archives:read_own' | 'archives:read_all' | 'archives:create'
  3326. | 'archives:update_own' | 'archives:update_all' | 'archives:delete_own' | 'archives:delete_all'
  3327. | 'archives:reprint_own' | 'archives:reprint_all' | 'archives:purge'
  3328. | 'queue:read' | 'queue:read_own' | 'queue:read_all' | 'queue:create'
  3329. | 'queue:update_own' | 'queue:update_all' | 'queue:delete_own' | 'queue:delete_all'
  3330. | 'queue:reorder'
  3331. | 'library:read' | 'library:read_own' | 'library:read_all' | 'library:upload'
  3332. | 'library:update_own' | 'library:update_all' | 'library:delete_own' | 'library:delete_all'
  3333. | 'library:purge'
  3334. | 'projects:read' | 'projects:create' | 'projects:update' | 'projects:delete'
  3335. | 'filaments:read' | 'filaments:create' | 'filaments:update' | 'filaments:delete'
  3336. | 'inventory:read' | 'inventory:create' | 'inventory:update' | 'inventory:delete' | 'inventory:view_assignments'
  3337. | 'inventory:forecast_read' | 'inventory:forecast_write'
  3338. | 'smart_plugs:read' | 'smart_plugs:create' | 'smart_plugs:update' | 'smart_plugs:delete' | 'smart_plugs:control'
  3339. | 'camera:view'
  3340. | 'maintenance:read' | 'maintenance:create' | 'maintenance:update' | 'maintenance:delete'
  3341. | 'kprofiles:read' | 'kprofiles:create' | 'kprofiles:update' | 'kprofiles:delete'
  3342. | 'notifications:read' | 'notifications:create' | 'notifications:update' | 'notifications:delete' | 'notifications:user_email'
  3343. | 'notification_templates:read' | 'notification_templates:update'
  3344. | 'external_links:read' | 'external_links:create' | 'external_links:update' | 'external_links:delete'
  3345. | 'discovery:scan'
  3346. | 'firmware:read' | 'firmware:update'
  3347. | 'ams_history:read'
  3348. | 'stats:read' | 'stats:filter_by_user'
  3349. | 'system:read'
  3350. | 'settings:read' | 'settings:update' | 'settings:backup' | 'settings:restore'
  3351. | 'github:backup' | 'github:restore'
  3352. | 'cloud:auth' | 'orca_cloud:auth'
  3353. | 'makerworld:view' | 'makerworld:import'
  3354. | 'api_keys:read' | 'api_keys:create' | 'api_keys:update' | 'api_keys:delete'
  3355. | 'users:read' | 'users:create' | 'users:update' | 'users:delete'
  3356. | 'groups:read' | 'groups:create' | 'groups:update' | 'groups:delete'
  3357. | 'pipelines:read' | 'pipelines:write' | 'pipelines:run'
  3358. | 'websocket:connect';
  3359. // Group types
  3360. export interface GroupBrief {
  3361. id: number;
  3362. name: string;
  3363. }
  3364. export interface Group {
  3365. id: number;
  3366. name: string;
  3367. description: string | null;
  3368. permissions: Permission[];
  3369. is_system: boolean;
  3370. user_count: number;
  3371. created_at: string;
  3372. updated_at: string;
  3373. }
  3374. export interface GroupDetail extends Group {
  3375. users: Array<{ id: number; username: string; is_active: boolean }>;
  3376. }
  3377. export interface GroupCreate {
  3378. name: string;
  3379. description?: string;
  3380. permissions: Permission[];
  3381. }
  3382. export interface GroupUpdate {
  3383. name?: string;
  3384. description?: string;
  3385. permissions?: Permission[];
  3386. }
  3387. export interface PermissionInfo {
  3388. value: Permission;
  3389. label: string;
  3390. }
  3391. export interface PermissionCategory {
  3392. name: string;
  3393. permissions: PermissionInfo[];
  3394. }
  3395. export interface PermissionsListResponse {
  3396. categories: PermissionCategory[];
  3397. all_permissions: Permission[];
  3398. }
  3399. // User email notification preferences
  3400. export interface UserEmailPreferences {
  3401. notify_print_start: boolean;
  3402. notify_print_complete: boolean;
  3403. notify_print_failed: boolean;
  3404. notify_print_stopped: boolean;
  3405. }
  3406. // Auth types
  3407. export interface LoginRequest {
  3408. username: string;
  3409. password: string;
  3410. }
  3411. export interface LoginResponse {
  3412. access_token?: string;
  3413. token_type?: string;
  3414. user?: UserResponse;
  3415. /** Set when 2FA verification is required before a full token is issued. */
  3416. requires_2fa?: boolean;
  3417. pre_auth_token?: string;
  3418. two_fa_methods?: string[];
  3419. }
  3420. export interface UserResponse {
  3421. id: number;
  3422. username: string;
  3423. email?: string;
  3424. role: string; // Deprecated, kept for backward compatibility
  3425. is_active: boolean;
  3426. is_admin: boolean; // Computed from role and group membership
  3427. auth_source: string; // "local" or "ldap"
  3428. groups: GroupBrief[];
  3429. permissions: Permission[]; // All permissions from groups
  3430. created_at: string;
  3431. }
  3432. export interface UserCreate {
  3433. username: string;
  3434. password?: string; // Optional when advanced auth is enabled
  3435. email?: string;
  3436. role: string;
  3437. group_ids?: number[];
  3438. }
  3439. export interface UserUpdate {
  3440. username?: string;
  3441. password?: string;
  3442. email?: string;
  3443. role?: string;
  3444. is_active?: boolean;
  3445. group_ids?: number[];
  3446. }
  3447. export interface SetupRequest {
  3448. auth_enabled: boolean;
  3449. admin_username?: string;
  3450. admin_password?: string;
  3451. }
  3452. export interface ForgotPasswordRequest {
  3453. email: string;
  3454. }
  3455. export interface ForgotPasswordResponse {
  3456. message: string;
  3457. }
  3458. export interface ResetPasswordRequest {
  3459. user_id: number;
  3460. }
  3461. export interface ResetPasswordResponse {
  3462. message: string;
  3463. }
  3464. export interface SMTPSettings {
  3465. smtp_host: string;
  3466. smtp_port: number;
  3467. smtp_username?: string;
  3468. smtp_password?: string;
  3469. smtp_security: 'starttls' | 'ssl' | 'none';
  3470. smtp_auth_enabled: boolean;
  3471. smtp_from_email: string;
  3472. smtp_from_name: string;
  3473. }
  3474. // 2FA / MFA interfaces
  3475. export interface TwoFAStatus {
  3476. totp_enabled: boolean;
  3477. email_otp_enabled: boolean;
  3478. backup_codes_remaining: number;
  3479. }
  3480. export interface TOTPSetupResponse {
  3481. secret: string;
  3482. qr_code_b64: string;
  3483. issuer: string;
  3484. }
  3485. export interface TOTPEnableResponse {
  3486. message: string;
  3487. backup_codes: string[];
  3488. }
  3489. export interface BackupCodesResponse {
  3490. backup_codes: string[];
  3491. message: string;
  3492. }
  3493. export interface TwoFAVerifyRequest {
  3494. pre_auth_token: string;
  3495. code: string;
  3496. method: 'totp' | 'email' | 'backup';
  3497. }
  3498. /**
  3499. * A URL that is known to be same-origin (a relative path starting with ``/``).
  3500. *
  3501. * Branded so that producers of same-origin URLs (e.g. ``api.oidcProviderIconUrl``)
  3502. * can be distinguished from arbitrary strings at the type level. The brand
  3503. * is compile-time only; at runtime these are plain strings.
  3504. *
  3505. * Purpose: CSP-safe image sources for ``<img src=...>``. The strict
  3506. * ``img-src 'self' data: blob:`` CSP rejects anything that isn't same-origin,
  3507. * so callers that demand a ``SameOriginUrl`` get a compile-time guarantee
  3508. * that no external URL slips through.
  3509. */
  3510. export type SameOriginUrl = string & { readonly __brand: 'SameOriginUrl' };
  3511. // OIDC interfaces
  3512. export interface OIDCProvider {
  3513. id: number;
  3514. name: string;
  3515. issuer_url: string;
  3516. client_id: string;
  3517. scopes: string;
  3518. is_enabled: boolean;
  3519. auto_create_users: boolean;
  3520. auto_link_existing_accounts: boolean;
  3521. email_claim: string;
  3522. require_email_verified: boolean;
  3523. icon_url?: string | null;
  3524. default_group_id?: number | null;
  3525. // True when the backend has cached icon bytes for this provider.
  3526. // Login page / admin preview consume this via the proxy URL
  3527. // /api/v1/auth/oidc/providers/{id}/icon (#1333) so the SPA never
  3528. // hotlinks the external icon URL — that would require loosening
  3529. // the strict img-src CSP. Required, not optional: the backend always
  3530. // includes this field in the response (Pydantic default-False is
  3531. // populated unconditionally in the route handler).
  3532. has_icon: boolean;
  3533. // #1589: when true, the LoginPage redirects unauthenticated visitors
  3534. // straight to this provider on mount. At most one provider may carry this.
  3535. is_autologin: boolean;
  3536. // #2593: defined by BAMBUDDY_OIDC_* and rewritten from the environment on
  3537. // every boot. The API answers 409 to any write, so the settings UI must not
  3538. // offer edit/delete controls that cannot succeed. Optional so a response
  3539. // from an older backend still type-checks.
  3540. is_env_managed?: boolean;
  3541. }
  3542. export interface OIDCProviderCreate {
  3543. name: string;
  3544. issuer_url: string;
  3545. client_id: string;
  3546. client_secret: string;
  3547. scopes?: string;
  3548. is_enabled?: boolean;
  3549. auto_create_users?: boolean;
  3550. auto_link_existing_accounts?: boolean;
  3551. email_claim?: string;
  3552. require_email_verified?: boolean;
  3553. icon_url?: string | null;
  3554. default_group_id?: number | null;
  3555. is_autologin?: boolean; // #1589
  3556. }
  3557. export interface OIDCLink {
  3558. id: number;
  3559. provider_id: number;
  3560. provider_name: string;
  3561. provider_email?: string | null;
  3562. created_at: string;
  3563. }
  3564. export interface TestSMTPRequest {
  3565. test_recipient: string;
  3566. }
  3567. export interface TestSMTPResponse {
  3568. success: boolean;
  3569. message: string;
  3570. }
  3571. export interface AdvancedAuthStatus {
  3572. advanced_auth_enabled: boolean;
  3573. smtp_configured: boolean;
  3574. // #1589: false hides the username/password form on the LoginPage; the env
  3575. // var BAMBUDDY_LOCAL_LOGIN=true on the server flips this back to true so
  3576. // the recovery path remains visible.
  3577. local_login_enabled: boolean;
  3578. // #1589: when set, LoginPage redirects to this provider's authorize URL
  3579. // on mount unless ?fallback=local is in the URL or the redirect times out.
  3580. autologin_provider_id: number | null;
  3581. }
  3582. export interface LDAPStatus {
  3583. ldap_enabled: boolean;
  3584. ldap_configured: boolean;
  3585. }
  3586. export interface EncryptionRowCounts {
  3587. oidc_providers: number;
  3588. user_totp: number;
  3589. }
  3590. export interface EncryptionStatus {
  3591. key_configured: boolean;
  3592. key_source: 'env' | 'file' | 'generated' | 'none';
  3593. legacy_plaintext_rows: EncryptionRowCounts;
  3594. encrypted_rows: EncryptionRowCounts;
  3595. decryption_broken: boolean;
  3596. // B2: count of rows skipped during the last legacy re-encryption migration.
  3597. // Surfaced via a yellow secondary banner in SecurityStatusCard.
  3598. migration_error_count: number;
  3599. }
  3600. export interface LDAPTestResponse {
  3601. success: boolean;
  3602. message: string;
  3603. }
  3604. export interface LDAPSearchResult {
  3605. username: string;
  3606. email: string | null;
  3607. display_name: string | null;
  3608. dn: string;
  3609. already_provisioned: boolean;
  3610. }
  3611. export interface SetupResponse {
  3612. auth_enabled: boolean;
  3613. admin_created?: boolean;
  3614. }
  3615. export interface AuthStatus {
  3616. auth_enabled: boolean;
  3617. requires_setup: boolean;
  3618. }
  3619. // API functions
  3620. export const api = {
  3621. // Authentication
  3622. getAuthStatus: () => request<AuthStatus>('/auth/status'),
  3623. setupAuth: (data: SetupRequest) =>
  3624. request<SetupResponse>('/auth/setup', {
  3625. method: 'POST',
  3626. body: JSON.stringify(data),
  3627. }),
  3628. login: (data: LoginRequest) =>
  3629. request<LoginResponse>('/auth/login', {
  3630. method: 'POST',
  3631. body: JSON.stringify(data),
  3632. }),
  3633. logout: () =>
  3634. request<{ message: string }>('/auth/logout', {
  3635. method: 'POST',
  3636. }),
  3637. getCurrentUser: () => request<UserResponse>('/auth/me'),
  3638. disableAuth: () =>
  3639. request<{ message: string; auth_enabled: boolean }>('/auth/disable', {
  3640. method: 'POST',
  3641. }),
  3642. // Advanced Authentication
  3643. testSMTP: (data: TestSMTPRequest) =>
  3644. request<TestSMTPResponse>('/auth/smtp/test', {
  3645. method: 'POST',
  3646. body: JSON.stringify(data),
  3647. }),
  3648. getSMTPSettings: () => request<SMTPSettings | null>('/auth/smtp'),
  3649. saveSMTPSettings: (data: SMTPSettings) =>
  3650. request<{ message: string }>('/auth/smtp', {
  3651. method: 'POST',
  3652. body: JSON.stringify(data),
  3653. }),
  3654. enableAdvancedAuth: () =>
  3655. request<{ message: string; advanced_auth_enabled: boolean }>('/auth/advanced-auth/enable', {
  3656. method: 'POST',
  3657. }),
  3658. disableAdvancedAuth: () =>
  3659. request<{ message: string; advanced_auth_enabled: boolean }>('/auth/advanced-auth/disable', {
  3660. method: 'POST',
  3661. }),
  3662. getAdvancedAuthStatus: () => request<AdvancedAuthStatus>('/auth/advanced-auth/status'),
  3663. // LDAP Authentication
  3664. getLDAPStatus: () => request<LDAPStatus>('/auth/ldap/status'),
  3665. getEncryptionStatus: () => request<EncryptionStatus>('/auth/encryption-status'),
  3666. testLDAP: () =>
  3667. request<LDAPTestResponse>('/auth/ldap/test', {
  3668. method: 'POST',
  3669. }),
  3670. searchLDAPDirectory: (q: string) =>
  3671. request<LDAPSearchResult[]>(`/auth/ldap/search?q=${encodeURIComponent(q)}`),
  3672. provisionLDAPUser: (username: string) =>
  3673. request<UserResponse>('/auth/ldap/provision', {
  3674. method: 'POST',
  3675. body: JSON.stringify({ username }),
  3676. }),
  3677. forgotPassword: (data: ForgotPasswordRequest) =>
  3678. request<ForgotPasswordResponse>('/auth/forgot-password', {
  3679. method: 'POST',
  3680. body: JSON.stringify(data),
  3681. }),
  3682. // H-6: Confirm password reset using the token from the emailed link
  3683. forgotPasswordConfirm: (token: string, newPassword: string) =>
  3684. request<ForgotPasswordResponse>('/auth/forgot-password/confirm', {
  3685. method: 'POST',
  3686. body: JSON.stringify({ token, new_password: newPassword }),
  3687. }),
  3688. resetUserPassword: (data: ResetPasswordRequest) =>
  3689. request<ResetPasswordResponse>('/auth/reset-password', {
  3690. method: 'POST',
  3691. body: JSON.stringify(data),
  3692. }),
  3693. // 2FA - status
  3694. get2FAStatus: () => request<TwoFAStatus>('/auth/2fa/status'),
  3695. // 2FA - TOTP
  3696. setupTOTP: () => request<TOTPSetupResponse>('/auth/2fa/totp/setup', { method: 'POST' }),
  3697. enableTOTP: (code: string) =>
  3698. request<TOTPEnableResponse>('/auth/2fa/totp/enable', {
  3699. method: 'POST',
  3700. body: JSON.stringify({ code }),
  3701. }),
  3702. disableTOTP: (code: string) =>
  3703. request<{ message: string }>('/auth/2fa/totp/disable', {
  3704. method: 'POST',
  3705. body: JSON.stringify({ code }),
  3706. }),
  3707. regenerateBackupCodes: (code: string) =>
  3708. request<BackupCodesResponse>('/auth/2fa/totp/regenerate-backup-codes', {
  3709. method: 'POST',
  3710. body: JSON.stringify({ code }),
  3711. }),
  3712. // 2FA - Email OTP
  3713. // Step 1: send a verification code to the user's email (proof of possession)
  3714. enableEmailOTP: () =>
  3715. request<{ message: string; setup_token: string }>('/auth/2fa/email/enable', { method: 'POST' }),
  3716. // Step 2: confirm with the code received by email
  3717. confirmEnableEmailOTP: (setup_token: string, code: string) =>
  3718. request<{ message: string }>('/auth/2fa/email/enable/confirm', {
  3719. method: 'POST',
  3720. body: JSON.stringify({ setup_token, code }),
  3721. }),
  3722. // Disable requires account password for re-auth
  3723. disableEmailOTP: (password: string) =>
  3724. request<{ message: string }>('/auth/2fa/email/disable', {
  3725. method: 'POST',
  3726. body: JSON.stringify({ password }),
  3727. }),
  3728. sendEmailOTP: (preAuthToken: string) =>
  3729. request<{ message: string; pre_auth_token?: string }>('/auth/2fa/email/send', {
  3730. method: 'POST',
  3731. body: JSON.stringify({ pre_auth_token: preAuthToken }),
  3732. }),
  3733. // 2FA - verify (completes login)
  3734. verify2FA: (data: TwoFAVerifyRequest) =>
  3735. request<LoginResponse>('/auth/2fa/verify', {
  3736. method: 'POST',
  3737. body: JSON.stringify(data),
  3738. }),
  3739. // 2FA - admin
  3740. admin2FADisable: (userId: number) =>
  3741. request<{ message: string }>(`/auth/2fa/admin/${userId}`, { method: 'DELETE' }),
  3742. // OIDC providers (public list)
  3743. getOIDCProviders: () => request<OIDCProvider[]>('/auth/oidc/providers'),
  3744. // OIDC providers (admin)
  3745. getOIDCProvidersAll: () => request<OIDCProvider[]>('/auth/oidc/providers/all'),
  3746. createOIDCProvider: (data: OIDCProviderCreate) =>
  3747. request<OIDCProvider>('/auth/oidc/providers', {
  3748. method: 'POST',
  3749. body: JSON.stringify(data),
  3750. }),
  3751. updateOIDCProvider: (id: number, data: Partial<OIDCProviderCreate>) =>
  3752. request<OIDCProvider>(`/auth/oidc/providers/${id}`, {
  3753. method: 'PUT',
  3754. body: JSON.stringify(data),
  3755. }),
  3756. deleteOIDCProvider: (id: number) =>
  3757. request<{ message: string }>(`/auth/oidc/providers/${id}`, { method: 'DELETE' }),
  3758. // OIDC provider icon proxy (#1333) — same-origin path so the strict
  3759. // img-src CSP stays in force. Returns a SameOriginUrl-branded string
  3760. // so a future caller can't accidentally substitute an attacker-
  3761. // controlled URL where this is consumed.
  3762. oidcProviderIconUrl: (id: number): SameOriginUrl =>
  3763. `/api/v1/auth/oidc/providers/${id}/icon` as SameOriginUrl,
  3764. deleteOIDCProviderIcon: (id: number) =>
  3765. request<void>(`/auth/oidc/providers/${id}/icon`, { method: 'DELETE' }),
  3766. refreshOIDCProviderIcon: (id: number) =>
  3767. request<OIDCProvider>(`/auth/oidc/providers/${id}/icon/refresh`, { method: 'POST' }),
  3768. // OIDC authorize URL
  3769. getOIDCAuthorizeUrl: (providerId: number) =>
  3770. request<{ auth_url: string }>(`/auth/oidc/authorize/${providerId}`),
  3771. // OIDC exchange token for JWT
  3772. exchangeOIDCToken: (oidcToken: string) =>
  3773. request<LoginResponse>('/auth/oidc/exchange', {
  3774. method: 'POST',
  3775. body: JSON.stringify({ oidc_token: oidcToken }),
  3776. }),
  3777. // OIDC links for current user
  3778. getOIDCLinks: () => request<OIDCLink[]>('/auth/oidc/links'),
  3779. deleteOIDCLink: (providerId: number) =>
  3780. request<{ message: string }>(`/auth/oidc/links/${providerId}`, { method: 'DELETE' }),
  3781. // Users
  3782. getUsers: () => request<UserResponse[]>('/users/'),
  3783. getUser: (id: number) => request<UserResponse>(`/users/${id}`),
  3784. createUser: (data: UserCreate) =>
  3785. request<UserResponse>('/users/', {
  3786. method: 'POST',
  3787. body: JSON.stringify(data),
  3788. }),
  3789. updateUser: (id: number, data: UserUpdate) =>
  3790. request<UserResponse>(`/users/${id}`, {
  3791. method: 'PATCH',
  3792. body: JSON.stringify(data),
  3793. }),
  3794. deleteUser: (id: number, deleteItems: boolean = false) =>
  3795. request<void>(`/users/${id}?delete_items=${deleteItems}`, {
  3796. method: 'DELETE',
  3797. }),
  3798. getUserItemsCount: (id: number) =>
  3799. request<{ archives: number; queue_items: number; library_files: number }>(`/users/${id}/items-count`),
  3800. changePassword: (currentPassword: string, newPassword: string) =>
  3801. request<{ message: string }>('/users/me/change-password', {
  3802. method: 'POST',
  3803. body: JSON.stringify({ current_password: currentPassword, new_password: newPassword }),
  3804. }),
  3805. // User Email Notifications
  3806. getUserEmailPreferences: () =>
  3807. request<UserEmailPreferences>('/user-notifications/preferences'),
  3808. updateUserEmailPreferences: (data: UserEmailPreferences) =>
  3809. request<UserEmailPreferences>('/user-notifications/preferences', {
  3810. method: 'PUT',
  3811. body: JSON.stringify(data),
  3812. }),
  3813. // Groups
  3814. getPermissions: () => request<PermissionsListResponse>('/groups/permissions'),
  3815. getGroups: () => request<Group[]>('/groups/'),
  3816. getGroup: (id: number) => request<GroupDetail>(`/groups/${id}`),
  3817. createGroup: (data: GroupCreate) =>
  3818. request<Group>('/groups/', {
  3819. method: 'POST',
  3820. body: JSON.stringify(data),
  3821. }),
  3822. updateGroup: (id: number, data: GroupUpdate) =>
  3823. request<Group>(`/groups/${id}`, {
  3824. method: 'PATCH',
  3825. body: JSON.stringify(data),
  3826. }),
  3827. deleteGroup: (id: number) =>
  3828. request<void>(`/groups/${id}`, {
  3829. method: 'DELETE',
  3830. }),
  3831. addUserToGroup: (groupId: number, userId: number) =>
  3832. request<void>(`/groups/${groupId}/users/${userId}`, {
  3833. method: 'POST',
  3834. }),
  3835. removeUserFromGroup: (groupId: number, userId: number) =>
  3836. request<void>(`/groups/${groupId}/users/${userId}`, {
  3837. method: 'DELETE',
  3838. }),
  3839. // Printers
  3840. getPrinters: () => request<Printer[]>('/printers/'),
  3841. getPrinter: (id: number) => request<Printer>(`/printers/${id}`),
  3842. createPrinter: (data: PrinterCreate) =>
  3843. request<Printer>('/printers/', {
  3844. method: 'POST',
  3845. body: JSON.stringify(data),
  3846. }),
  3847. updatePrinter: (id: number, data: Partial<PrinterCreate>) =>
  3848. request<Printer>(`/printers/${id}`, {
  3849. method: 'PATCH',
  3850. body: JSON.stringify(data),
  3851. }),
  3852. deletePrinter: (id: number, deleteArchives: boolean = true) =>
  3853. request<{ status: string; archives_deleted: boolean }>(
  3854. `/printers/${id}?delete_archives=${deleteArchives}`,
  3855. { method: 'DELETE' }
  3856. ),
  3857. getDeveloperModeWarnings: () =>
  3858. request<{ printer_id: number; name: string }[]>('/printers/developer-mode-warnings'),
  3859. getAvailableFilaments: (model: string, location?: string) => {
  3860. const params = new URLSearchParams({ model });
  3861. if (location) params.set('location', location);
  3862. return request<Array<{ type: string; color: string; tray_info_idx: string; tray_sub_brands: string; extruder_id: number | null }>>(`/printers/available-filaments?${params}`);
  3863. },
  3864. getPrinterStatus: (id: number) =>
  3865. request<PrinterStatus>(`/printers/${id}/status`),
  3866. refreshPrinterStatus: (id: number) =>
  3867. request<{ status: string }>(`/printers/${id}/refresh-status`, {
  3868. method: 'POST',
  3869. }),
  3870. connectPrinter: (id: number) =>
  3871. request<{ connected: boolean }>(`/printers/${id}/connect`, {
  3872. method: 'POST',
  3873. }),
  3874. disconnectPrinter: (id: number) =>
  3875. request<{ connected: boolean }>(`/printers/${id}/disconnect`, {
  3876. method: 'POST',
  3877. }),
  3878. testExternalCamera: (printerId: number, url: string, cameraType: string) =>
  3879. // `coalesced` is true when the frame came from a capture that was already
  3880. // running (Obico polling, a snapshot) rather than a connection this test
  3881. // opened — a single-reader camera is shared rather than opened twice, so
  3882. // the result is real but says nothing about reaching the camera just now.
  3883. request<{ success: boolean; error?: string; resolution?: string; coalesced?: boolean }>(
  3884. `/printers/${printerId}/camera/external/test?url=${encodeURIComponent(url)}&camera_type=${encodeURIComponent(cameraType)}`,
  3885. { method: 'POST' }
  3886. ),
  3887. // Print Control
  3888. stopPrint: (printerId: number) =>
  3889. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/stop`, {
  3890. method: 'POST',
  3891. }),
  3892. pausePrint: (printerId: number) =>
  3893. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/pause`, {
  3894. method: 'POST',
  3895. }),
  3896. resumePrint: (printerId: number) =>
  3897. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/resume`, {
  3898. method: 'POST',
  3899. }),
  3900. clearPlate: (printerId: number) =>
  3901. request<{ success: boolean; message: string }>(`/printers/${printerId}/clear-plate`, {
  3902. method: 'POST',
  3903. }),
  3904. // Get current print user (for reprint tracking - Issue #206)
  3905. getCurrentPrintUser: (printerId: number) =>
  3906. request<{ user_id?: number; username?: string }>(`/printers/${printerId}/current-print-user`),
  3907. // Print Speed Control
  3908. setPrintSpeed: (printerId: number, mode: number) =>
  3909. request<{ success: boolean; message: string }>(`/printers/${printerId}/print-speed?mode=${mode}`, {
  3910. method: 'POST',
  3911. }),
  3912. setNozzleTemperature: (printerId: number, target: number, nozzle: number = 0) =>
  3913. request<{ success: boolean; message: string }>(
  3914. `/printers/${printerId}/temperature/nozzle?target=${target}&nozzle=${nozzle}`,
  3915. { method: 'POST' }
  3916. ),
  3917. setBedTemperature: (printerId: number, target: number) =>
  3918. request<{ success: boolean; message: string }>(`/printers/${printerId}/temperature/bed?target=${target}`, {
  3919. method: 'POST',
  3920. }),
  3921. setChamberTemperature: (printerId: number, target: number) =>
  3922. request<{ success: boolean; message: string }>(`/printers/${printerId}/temperature/chamber?target=${target}`, {
  3923. method: 'POST',
  3924. }),
  3925. setFanSpeed: (printerId: number, fan: 'part' | 'aux' | 'aux2' | 'chamber', speed: number) =>
  3926. request<{ success: boolean; message: string }>(`/printers/${printerId}/fan-speed?fan=${fan}&speed=${speed}`, {
  3927. method: 'POST',
  3928. }),
  3929. selectExtruder: (printerId: number, extruder: number) =>
  3930. request<{ success: boolean; message: string }>(`/printers/${printerId}/select-extruder?extruder=${extruder}`, {
  3931. method: 'POST',
  3932. }),
  3933. setAirductMode: (printerId: number, mode: 'cooling' | 'heating') =>
  3934. request<{ success: boolean; message: string }>(`/printers/${printerId}/airduct-mode?mode=${mode}`, {
  3935. method: 'POST',
  3936. }),
  3937. // Bed (Z-axis) jog
  3938. bedJog: (printerId: number, distance: number) =>
  3939. request<{ success: boolean; message: string }>(
  3940. `/printers/${printerId}/bed-jog?distance=${distance}`,
  3941. { method: 'POST' }
  3942. ),
  3943. xyJog: (printerId: number, x: number, y: number) =>
  3944. request<{ success: boolean; message: string }>(
  3945. `/printers/${printerId}/xy-jog?x=${x}&y=${y}`,
  3946. { method: 'POST' }
  3947. ),
  3948. extruderJog: (printerId: number, distance: number) =>
  3949. request<{ success: boolean; message: string }>(
  3950. `/printers/${printerId}/extruder-jog?distance=${distance}`,
  3951. { method: 'POST' }
  3952. ),
  3953. homeAxes: (printerId: number, axes: 'z' | 'xy' | 'all' = 'z') =>
  3954. request<{ success: boolean; message: string }>(
  3955. `/printers/${printerId}/home-axes?axes=${axes}`,
  3956. { method: 'POST' }
  3957. ),
  3958. // Chamber Light Control
  3959. setChamberLight: (printerId: number, on: boolean) =>
  3960. request<{ success: boolean; message: string }>(`/printers/${printerId}/chamber-light?on=${on}`, {
  3961. method: 'POST',
  3962. }),
  3963. // AMS Drying Control
  3964. startDrying: (printerId: number, amsId: number, temp: number, duration: number, filament: string = '', rotateTray: boolean = false) =>
  3965. request<{ status: string; ams_id: number; temp: number; duration: number }>(
  3966. `/printers/${printerId}/drying/start?ams_id=${amsId}&temp=${temp}&duration=${duration}&filament=${encodeURIComponent(filament)}&rotate_tray=${rotateTray}`,
  3967. { method: 'POST' }
  3968. ),
  3969. stopDrying: (printerId: number, amsId: number) =>
  3970. request<{ status: string; ams_id: number }>(
  3971. `/printers/${printerId}/drying/stop?ams_id=${amsId}`,
  3972. { method: 'POST' }
  3973. ),
  3974. // AMS Filament Backup (auto-switch to a backup spool when one runs out)
  3975. setAmsFilamentBackup: (printerId: number, enabled: boolean) =>
  3976. request<{ success: boolean; ams_filament_backup: boolean }>(
  3977. `/printers/${printerId}/ams-backup?enabled=${enabled}`,
  3978. { method: 'POST' }
  3979. ),
  3980. // Per-globalTrayId remaining grams for this printer's inventory-bound slots
  3981. // (#1766). Drives the client-side "Prefer Lowest Remaining Filament" sort
  3982. // when computing the AMS mapping; mirrors backend `_build_inventory_remain_overrides`
  3983. // so internal and Spoolman modes both work uniformly.
  3984. getInventoryRemain: (printerId: number) =>
  3985. request<{ inventory_remain_g: Record<string, number> }>(
  3986. `/printers/${printerId}/inventory-remain`,
  3987. ),
  3988. // Skip Objects
  3989. getPrintableObjects: (printerId: number) =>
  3990. request<{
  3991. objects: Array<{ id: number; name: string; x: number | null; y: number | null; skipped: boolean }>;
  3992. total: number;
  3993. skipped_count: number;
  3994. is_printing: boolean;
  3995. bbox_all: [number, number, number, number] | null;
  3996. }>(`/printers/${printerId}/print/objects`),
  3997. skipObjects: (printerId: number, objectIds: number[]) =>
  3998. request<{ success: boolean; message: string; skipped_objects: number[] }>(
  3999. `/printers/${printerId}/print/skip-objects`,
  4000. {
  4001. method: 'POST',
  4002. body: JSON.stringify(objectIds),
  4003. }
  4004. ),
  4005. // HMS Errors
  4006. clearHMSErrors: (printerId: number) =>
  4007. request<{ success: boolean; message: string }>(`/printers/${printerId}/hms/clear`, { method: 'POST' }),
  4008. executeHMSAction: (printerId: number, data: HMSActionBody) =>
  4009. request<{ success: boolean; message: string }>(`/printers/${printerId}/hms/execute-action`, {
  4010. method: 'POST',
  4011. body: JSON.stringify(data),
  4012. }),
  4013. // AMS Control
  4014. refreshAmsSlot: (printerId: number, amsId: number, slotId: number) =>
  4015. request<{ success: boolean; message: string }>(
  4016. `/printers/${printerId}/ams/${amsId}/slot/${slotId}/refresh`,
  4017. { method: 'POST' }
  4018. ),
  4019. // Load filament from a tray. trayId: 0-15 for AMS (amsId*4+slotId), 254 for external spool.
  4020. loadAmsTray: (printerId: number, trayId: number) =>
  4021. request<{ success: boolean; message: string }>(
  4022. `/printers/${printerId}/ams/load?tray_id=${trayId}`,
  4023. { method: 'POST' }
  4024. ),
  4025. // Unload the currently loaded filament.
  4026. unloadAms: (printerId: number) =>
  4027. request<{ success: boolean; message: string }>(
  4028. `/printers/${printerId}/ams/unload`,
  4029. { method: 'POST' }
  4030. ),
  4031. // MQTT Debug Logging
  4032. enableMQTTLogging: (printerId: number) =>
  4033. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/enable`, {
  4034. method: 'POST',
  4035. }),
  4036. disableMQTTLogging: (printerId: number) =>
  4037. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/disable`, {
  4038. method: 'POST',
  4039. }),
  4040. getMQTTLogs: (printerId: number) =>
  4041. request<MQTTLogsResponse>(`/printers/${printerId}/logging`),
  4042. clearMQTTLogs: (printerId: number) =>
  4043. request<{ status: string }>(`/printers/${printerId}/logging`, {
  4044. method: 'DELETE',
  4045. }),
  4046. // Printer File Manager
  4047. getPrinterFiles: (printerId: number, path = '/') =>
  4048. request<{
  4049. path: string;
  4050. files: Array<{
  4051. name: string;
  4052. is_directory: boolean;
  4053. size: number;
  4054. path: string;
  4055. mtime?: string;
  4056. }>;
  4057. }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`),
  4058. getPrinterFileDownloadUrl: (printerId: number, path: string) =>
  4059. `${API_BASE}/printers/${printerId}/files/download?path=${encodeURIComponent(path)}`,
  4060. getPrinterFileGcodeUrl: (printerId: number, path: string) =>
  4061. `${API_BASE}/printers/${printerId}/files/gcode?path=${encodeURIComponent(path)}`,
  4062. getPrinterFilePlates: (printerId: number, path: string) =>
  4063. request<{
  4064. printer_id: number;
  4065. path: string;
  4066. filename: string;
  4067. plates: Array<{
  4068. index: number;
  4069. name: string | null;
  4070. objects: string[];
  4071. has_thumbnail: boolean;
  4072. thumbnail_url: string | null;
  4073. print_time_seconds: number | null;
  4074. filament_used_grams: number | null;
  4075. filaments: Array<{
  4076. slot_id: number;
  4077. type: string;
  4078. color: string;
  4079. used_grams: number;
  4080. used_meters: number;
  4081. }>;
  4082. }>;
  4083. is_multi_plate: boolean;
  4084. }>(`/printers/${printerId}/files/plates?path=${encodeURIComponent(path)}`),
  4085. getPrinterFilePlateThumbnail: (printerId: number, plateIndex: number, path: string) =>
  4086. withStreamToken(`${API_BASE}/printers/${printerId}/files/plate-thumbnail/${plateIndex}?path=${encodeURIComponent(path)}`),
  4087. downloadPrinterFile: async (printerId: number, path: string): Promise<void> => {
  4088. const headers: Record<string, string> = {};
  4089. if (authToken) {
  4090. headers['Authorization'] = `Bearer ${authToken}`;
  4091. }
  4092. const response = await fetch(
  4093. `${API_BASE}/printers/${printerId}/files/download?path=${encodeURIComponent(path)}`,
  4094. { headers }
  4095. );
  4096. if (!response.ok) {
  4097. const error = await response.json().catch(() => ({}));
  4098. throw new Error(error.detail || `HTTP ${response.status}`);
  4099. }
  4100. const disposition = response.headers.get('Content-Disposition');
  4101. const filename = parseContentDispositionFilename(disposition) || path.split('/').pop() || 'download';
  4102. const blob = await response.blob();
  4103. const url = window.URL.createObjectURL(blob);
  4104. const a = document.createElement('a');
  4105. a.href = url;
  4106. a.download = filename;
  4107. document.body.appendChild(a);
  4108. a.click();
  4109. document.body.removeChild(a);
  4110. window.URL.revokeObjectURL(url);
  4111. },
  4112. downloadPrinterFilesAsZip: async (printerId: number, paths: string[]): Promise<Blob> => {
  4113. const headers: Record<string, string> = { 'Content-Type': 'application/json' };
  4114. if (authToken) {
  4115. headers['Authorization'] = `Bearer ${authToken}`;
  4116. }
  4117. const response = await fetch(`${API_BASE}/printers/${printerId}/files/download-zip`, {
  4118. method: 'POST',
  4119. headers,
  4120. body: JSON.stringify({ paths }),
  4121. });
  4122. if (!response.ok) {
  4123. const error = await response.json().catch(() => ({}));
  4124. throw new Error(error.detail || `HTTP ${response.status}`);
  4125. }
  4126. return response.blob();
  4127. },
  4128. deletePrinterFile: (printerId: number, path: string) =>
  4129. request<{ status: string; path: string }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`, {
  4130. method: 'DELETE',
  4131. }),
  4132. getPrinterStorage: (printerId: number) =>
  4133. request<{ used_bytes: number | null; free_bytes: number | null }>(`/printers/${printerId}/storage`),
  4134. // Archives
  4135. getArchives: (printerId?: number, projectId?: number, limit = 10000, offset = 0, dateFrom?: string, dateTo?: string) => {
  4136. const params = new URLSearchParams();
  4137. if (printerId) params.set('printer_id', String(printerId));
  4138. if (projectId) params.set('project_id', String(projectId));
  4139. params.set('limit', String(limit));
  4140. params.set('offset', String(offset));
  4141. if (dateFrom) params.set('date_from', dateFrom);
  4142. if (dateTo) params.set('date_to', dateTo);
  4143. return request<Archive[]>(`/archives/?${params}`);
  4144. },
  4145. getArchivesSlim: (dateFrom?: string, dateTo?: string, createdById?: number) => {
  4146. const params = new URLSearchParams();
  4147. if (dateFrom) params.set('date_from', dateFrom);
  4148. if (dateTo) params.set('date_to', dateTo);
  4149. if (createdById !== undefined) params.set('created_by_id', String(createdById));
  4150. const qs = params.toString();
  4151. return request<ArchiveSlim[]>(`/archives/slim${qs ? `?${qs}` : ''}`);
  4152. },
  4153. getArchive: (id: number) => request<Archive>(`/archives/${id}`),
  4154. getArchiveRuns: (id: number) => request<PrintLogResponse>(`/archives/${id}/runs`),
  4155. /**
  4156. * Pre-flight for the delete-confirm modal (#1734). Returns the number of
  4157. * related queue items that will be removed along with the archive AND how
  4158. * many are currently printing (server 409s on delete if > 0).
  4159. */
  4160. getArchiveDeleteImpact: (id: number) =>
  4161. request<{ related_queue_items: number; currently_printing: number }>(
  4162. `/archives/${id}/delete-impact`
  4163. ),
  4164. searchArchives: (query: string, options?: {
  4165. printerId?: number;
  4166. projectId?: number;
  4167. status?: string;
  4168. limit?: number;
  4169. offset?: number;
  4170. }) => {
  4171. const params = new URLSearchParams();
  4172. params.set('q', query);
  4173. if (options?.printerId) params.set('printer_id', String(options.printerId));
  4174. if (options?.projectId) params.set('project_id', String(options.projectId));
  4175. if (options?.status) params.set('status', options.status);
  4176. if (options?.limit) params.set('limit', String(options.limit));
  4177. if (options?.offset) params.set('offset', String(options.offset));
  4178. return request<Archive[]>(`/archives/search?${params}`);
  4179. },
  4180. rebuildSearchIndex: () => request<{ message: string }>('/archives/search/rebuild-index', { method: 'POST' }),
  4181. getNo3MFWarning: () => request<{ has_fallback: boolean }>('/archives/no-3mf-warning'),
  4182. updateArchive: (id: number, data: {
  4183. printer_id?: number | null;
  4184. project_id?: number | null;
  4185. print_name?: string;
  4186. is_favorite?: boolean;
  4187. tags?: string;
  4188. notes?: string;
  4189. cost?: number;
  4190. failure_reason?: string | null;
  4191. status?: string;
  4192. quantity?: number;
  4193. external_url?: string | null;
  4194. }) =>
  4195. request<Archive>(`/archives/${id}`, {
  4196. method: 'PATCH',
  4197. body: JSON.stringify(data),
  4198. }),
  4199. toggleFavorite: (id: number) =>
  4200. request<Archive>(`/archives/${id}/favorite`, { method: 'POST' }),
  4201. // Soft-deletes by default (#1343): files removed from disk, row hidden
  4202. // from listings, but its filament / time / cost / energy contribution
  4203. // stays in Quick Stats. Pass purgeStats=true to hard-delete and drop the
  4204. // row from statistics too.
  4205. deleteArchive: (id: number, purgeStats: boolean = false) =>
  4206. request<void>(`/archives/${id}${purgeStats ? '?purge_stats=true' : ''}`, { method: 'DELETE' }),
  4207. // ========== Archive auto-purge (#1008 follow-up) ==========
  4208. previewArchivePurge: (olderThanDays: number, purgeStats: boolean = false) =>
  4209. request<ArchivePurgePreview>(
  4210. `/archives/purge/preview?older_than_days=${olderThanDays}&purge_stats=${purgeStats}`,
  4211. ),
  4212. // #1390: purgeStats=false (default) soft-deletes each old archive — Quick Stats
  4213. // preserved, files removed from disk, row hidden via deleted_at. true matches
  4214. // the single-archive delete's `?purge_stats=true` semantics (hard-deletes the
  4215. // linked PrintLogEntry rows so the contribution drops from /stats too).
  4216. executeArchivePurge: (olderThanDays: number, purgeStats: boolean = false) =>
  4217. request<{ deleted: number; purge_stats: boolean }>('/archives/purge', {
  4218. method: 'POST',
  4219. body: JSON.stringify({ older_than_days: olderThanDays, purge_stats: purgeStats }),
  4220. }),
  4221. getArchivePurgeSettings: () =>
  4222. request<ArchivePurgeSettings>('/archives/purge/settings'),
  4223. updateArchivePurgeSettings: (body: ArchivePurgeSettings) =>
  4224. request<ArchivePurgeSettings>('/archives/purge/settings', {
  4225. method: 'PUT',
  4226. body: JSON.stringify(body),
  4227. }),
  4228. getArchiveStats: (options?: { dateFrom?: string; dateTo?: string; createdById?: number }) => {
  4229. const params = new URLSearchParams();
  4230. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  4231. if (options?.dateTo) params.set('date_to', options.dateTo);
  4232. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  4233. const qs = params.toString();
  4234. return request<ArchiveStats>(`/archives/stats${qs ? `?${qs}` : ''}`);
  4235. },
  4236. // Tag management
  4237. getTags: () => request<TagInfo[]>('/archives/tags'),
  4238. renameTag: (oldName: string, newName: string) =>
  4239. request<{ affected: number }>(`/archives/tags/${encodeURIComponent(oldName)}`, {
  4240. method: 'PUT',
  4241. body: JSON.stringify({ new_name: newName }),
  4242. }),
  4243. deleteTag: (name: string) =>
  4244. request<{ affected: number }>(`/archives/tags/${encodeURIComponent(name)}`, {
  4245. method: 'DELETE',
  4246. }),
  4247. recalculateCosts: () =>
  4248. request<{ message: string; updated: number }>('/archives/recalculate-costs', { method: 'POST' }),
  4249. getFailureAnalysis: (options?: { days?: number; dateFrom?: string; dateTo?: string; printerId?: number; projectId?: number; createdById?: number }) => {
  4250. const params = new URLSearchParams();
  4251. if (options?.days) params.set('days', String(options.days));
  4252. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  4253. if (options?.dateTo) params.set('date_to', options.dateTo);
  4254. if (options?.printerId) params.set('printer_id', String(options.printerId));
  4255. if (options?.projectId) params.set('project_id', String(options.projectId));
  4256. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  4257. const qs = params.toString();
  4258. return request<FailureAnalysis>(`/archives/analysis/failures${qs ? `?${qs}` : ''}`);
  4259. },
  4260. compareArchives: (archiveIds: number[]) =>
  4261. request<ArchiveComparison>(`/archives/compare?archive_ids=${archiveIds.join(',')}`),
  4262. findSimilarArchives: (archiveId: number, limit = 10) =>
  4263. request<SimilarArchive[]>(`/archives/${archiveId}/similar?limit=${limit}`),
  4264. exportArchives: async (options?: {
  4265. format?: 'csv' | 'xlsx';
  4266. fields?: string[];
  4267. printerId?: number;
  4268. projectId?: number;
  4269. status?: string;
  4270. dateFrom?: string;
  4271. dateTo?: string;
  4272. search?: string;
  4273. }): Promise<{ blob: Blob; filename: string }> => {
  4274. const params = new URLSearchParams();
  4275. if (options?.format) params.set('format', options.format);
  4276. if (options?.fields) params.set('fields', options.fields.join(','));
  4277. if (options?.printerId) params.set('printer_id', String(options.printerId));
  4278. if (options?.projectId) params.set('project_id', String(options.projectId));
  4279. if (options?.status) params.set('status', options.status);
  4280. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  4281. if (options?.dateTo) params.set('date_to', options.dateTo);
  4282. if (options?.search) params.set('search', options.search);
  4283. const headers: Record<string, string> = {};
  4284. if (authToken) {
  4285. headers['Authorization'] = `Bearer ${authToken}`;
  4286. }
  4287. const response = await fetch(`${API_BASE}/archives/export?${params}`, { headers });
  4288. if (!response.ok) {
  4289. const error = await response.json().catch(() => ({}));
  4290. throw new Error(error.detail || `HTTP ${response.status}`);
  4291. }
  4292. const contentDisposition = response.headers.get('Content-Disposition');
  4293. let filename = options?.format === 'xlsx' ? 'archives_export.xlsx' : 'archives_export.csv';
  4294. if (contentDisposition) {
  4295. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  4296. if (match) filename = match[1];
  4297. }
  4298. const blob = await response.blob();
  4299. return { blob, filename };
  4300. },
  4301. exportStats: async (options?: {
  4302. format?: 'csv' | 'xlsx';
  4303. days?: number;
  4304. printerId?: number;
  4305. projectId?: number;
  4306. createdById?: number;
  4307. }): Promise<{ blob: Blob; filename: string }> => {
  4308. const params = new URLSearchParams();
  4309. if (options?.format) params.set('format', options.format);
  4310. if (options?.days) params.set('days', String(options.days));
  4311. if (options?.printerId) params.set('printer_id', String(options.printerId));
  4312. if (options?.projectId) params.set('project_id', String(options.projectId));
  4313. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  4314. const headers: Record<string, string> = {};
  4315. if (authToken) {
  4316. headers['Authorization'] = `Bearer ${authToken}`;
  4317. }
  4318. const response = await fetch(`${API_BASE}/archives/stats/export?${params}`, { headers });
  4319. if (!response.ok) {
  4320. const error = await response.json().catch(() => ({}));
  4321. throw new Error(error.detail || `HTTP ${response.status}`);
  4322. }
  4323. const contentDisposition = response.headers.get('Content-Disposition');
  4324. let filename = options?.format === 'xlsx' ? 'stats_export.xlsx' : 'stats_export.csv';
  4325. if (contentDisposition) {
  4326. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  4327. if (match) filename = match[1];
  4328. }
  4329. const blob = await response.blob();
  4330. return { blob, filename };
  4331. },
  4332. getArchiveDuplicates: (id: number) =>
  4333. request<{ duplicates: ArchiveDuplicate[]; count: number }>(`/archives/${id}/duplicates`),
  4334. backfillContentHashes: () =>
  4335. request<{ updated: number; errors: Array<{ id: number; error: string }> }>('/archives/backfill-hashes', {
  4336. method: 'POST',
  4337. }),
  4338. getArchiveThumbnail: (id: number) => withStreamToken(`${API_BASE}/archives/${id}/thumbnail?v=${Date.now()}`),
  4339. getArchivePlateThumbnail: (id: number, plateIndex: number) =>
  4340. withStreamToken(`${API_BASE}/archives/${id}/plate-thumbnail/${plateIndex}`),
  4341. getArchiveDownload: (id: number) => `${API_BASE}/archives/${id}/download`,
  4342. downloadArchive: async (id: number, filename?: string): Promise<void> => {
  4343. const headers: Record<string, string> = {};
  4344. if (authToken) {
  4345. headers['Authorization'] = `Bearer ${authToken}`;
  4346. }
  4347. const response = await fetch(`${API_BASE}/archives/${id}/download`, { headers });
  4348. if (!response.ok) {
  4349. const error = await response.json().catch(() => ({}));
  4350. throw new Error(error.detail || `HTTP ${response.status}`);
  4351. }
  4352. const disposition = response.headers.get('Content-Disposition');
  4353. const downloadFilename = parseContentDispositionFilename(disposition) || filename || `archive_${id}.3mf`;
  4354. const blob = await response.blob();
  4355. const url = window.URL.createObjectURL(blob);
  4356. const a = document.createElement('a');
  4357. a.href = url;
  4358. a.download = downloadFilename;
  4359. document.body.appendChild(a);
  4360. a.click();
  4361. document.body.removeChild(a);
  4362. window.URL.revokeObjectURL(url);
  4363. },
  4364. getArchiveGcode: (id: number) => `${API_BASE}/archives/${id}/gcode`,
  4365. getArchivePlatePreview: (id: number) => withStreamToken(`${API_BASE}/archives/${id}/plate-preview`),
  4366. getArchiveTimelapse: (id: number) => withStreamToken(`${API_BASE}/archives/${id}/timelapse?v=${Date.now()}`),
  4367. scanArchiveTimelapse: (id: number) =>
  4368. request<{
  4369. status: string;
  4370. message: string;
  4371. filename?: string;
  4372. available_files?: Array<{ name: string; path: string; size: number; mtime: string | null }>;
  4373. }>(`/archives/${id}/timelapse/scan`, {
  4374. method: 'POST',
  4375. }),
  4376. selectArchiveTimelapse: (id: number, filename: string) =>
  4377. request<{ status: string; message: string; filename: string }>(
  4378. `/archives/${id}/timelapse/select?filename=${encodeURIComponent(filename)}`,
  4379. { method: 'POST' }
  4380. ),
  4381. deleteArchiveTimelapse: (id: number) =>
  4382. request<{ status: string }>(`/archives/${id}/timelapse`, {
  4383. method: 'DELETE',
  4384. }),
  4385. uploadArchiveTimelapse: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  4386. const formData = new FormData();
  4387. formData.append('file', file);
  4388. const headers: Record<string, string> = {};
  4389. if (authToken) {
  4390. headers['Authorization'] = `Bearer ${authToken}`;
  4391. }
  4392. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/upload`, {
  4393. method: 'POST',
  4394. headers,
  4395. body: formData,
  4396. });
  4397. if (!response.ok) {
  4398. const error = await response.json().catch(() => ({}));
  4399. throw new Error(error.detail || `HTTP ${response.status}`);
  4400. }
  4401. return response.json();
  4402. },
  4403. // Timelapse Editor
  4404. getTimelapseInfo: (archiveId: number) =>
  4405. request<{
  4406. duration: number;
  4407. width: number;
  4408. height: number;
  4409. fps: number;
  4410. codec: string;
  4411. file_size: number;
  4412. has_audio: boolean;
  4413. }>(`/archives/${archiveId}/timelapse/info`),
  4414. getTimelapseThumbnails: (archiveId: number, count: number = 10) =>
  4415. request<{
  4416. thumbnails: string[];
  4417. timestamps: number[];
  4418. }>(`/archives/${archiveId}/timelapse/thumbnails?count=${count}`),
  4419. processTimelapse: async (
  4420. archiveId: number,
  4421. params: {
  4422. trimStart?: number;
  4423. trimEnd?: number;
  4424. speed?: number;
  4425. saveMode: 'replace' | 'new';
  4426. outputFilename?: string;
  4427. },
  4428. audioFile?: File
  4429. ): Promise<{ status: string; output_path: string | null; message: string }> => {
  4430. const formData = new FormData();
  4431. formData.append('trim_start', String(params.trimStart ?? 0));
  4432. if (params.trimEnd !== undefined) {
  4433. formData.append('trim_end', String(params.trimEnd));
  4434. }
  4435. formData.append('speed', String(params.speed ?? 1));
  4436. formData.append('save_mode', params.saveMode);
  4437. if (params.outputFilename) {
  4438. formData.append('output_filename', params.outputFilename);
  4439. }
  4440. if (audioFile) {
  4441. formData.append('audio', audioFile);
  4442. }
  4443. const headers: Record<string, string> = {};
  4444. if (authToken) {
  4445. headers['Authorization'] = `Bearer ${authToken}`;
  4446. }
  4447. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/process`, {
  4448. method: 'POST',
  4449. headers,
  4450. body: formData,
  4451. });
  4452. if (!response.ok) {
  4453. const error = await response.json().catch(() => ({}));
  4454. throw new Error(error.detail || `HTTP ${response.status}`);
  4455. }
  4456. return response.json();
  4457. },
  4458. // Photos
  4459. getArchivePhotoUrl: (archiveId: number, filename: string) =>
  4460. withStreamToken(`${API_BASE}/archives/${archiveId}/photos/${encodeURIComponent(filename)}`),
  4461. uploadArchivePhoto: async (archiveId: number, file: File): Promise<{ status: string; filename: string; photos: string[] }> => {
  4462. const formData = new FormData();
  4463. formData.append('file', file);
  4464. const headers: Record<string, string> = {};
  4465. if (authToken) {
  4466. headers['Authorization'] = `Bearer ${authToken}`;
  4467. }
  4468. const response = await fetch(`${API_BASE}/archives/${archiveId}/photos`, {
  4469. headers,
  4470. method: 'POST',
  4471. body: formData,
  4472. });
  4473. if (!response.ok) {
  4474. const error = await response.json().catch(() => ({}));
  4475. throw new Error(error.detail || `HTTP ${response.status}`);
  4476. }
  4477. return response.json();
  4478. },
  4479. deleteArchivePhoto: (archiveId: number, filename: string) =>
  4480. request<{ status: string; photos: string[] | null }>(`/archives/${archiveId}/photos/${encodeURIComponent(filename)}`, {
  4481. method: 'DELETE',
  4482. }),
  4483. // Source 3MF (original slicer project file)
  4484. getSource3mfDownloadUrl: (archiveId: number) =>
  4485. `${API_BASE}/archives/${archiveId}/source`,
  4486. downloadSource3mf: async (archiveId: number): Promise<void> => {
  4487. const headers: Record<string, string> = {};
  4488. if (authToken) {
  4489. headers['Authorization'] = `Bearer ${authToken}`;
  4490. }
  4491. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, { headers });
  4492. if (!response.ok) {
  4493. const error = await response.json().catch(() => ({}));
  4494. throw new Error(error.detail || `HTTP ${response.status}`);
  4495. }
  4496. const disposition = response.headers.get('Content-Disposition');
  4497. const filename = parseContentDispositionFilename(disposition) || `source_${archiveId}.3mf`;
  4498. const blob = await response.blob();
  4499. const url = window.URL.createObjectURL(blob);
  4500. const a = document.createElement('a');
  4501. a.href = url;
  4502. a.download = filename;
  4503. document.body.appendChild(a);
  4504. a.click();
  4505. document.body.removeChild(a);
  4506. window.URL.revokeObjectURL(url);
  4507. },
  4508. getSource3mfForSlicer: (archiveId: number, filename: string) => {
  4509. // Sanitize: slicers url_decode() the entire URL, so / \ ? # in filenames break path routing
  4510. const safe = filename.replace(/[/\\?#]/g, '_');
  4511. return `${API_BASE}/archives/${archiveId}/source/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  4512. },
  4513. createSourceSlicerToken: (archiveId: number) =>
  4514. request<{ token: string }>(`/archives/${archiveId}/source-slicer-token`, { method: 'POST' }),
  4515. getSourceSlicerDownloadUrl: (archiveId: number, token: string, filename: string) => {
  4516. const safe = filename.replace(/[/\\?#]/g, '_');
  4517. return `${API_BASE}/archives/${archiveId}/source-dl/${token}/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  4518. },
  4519. uploadSource3mf: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  4520. const formData = new FormData();
  4521. formData.append('file', file);
  4522. const headers: Record<string, string> = {};
  4523. if (authToken) {
  4524. headers['Authorization'] = `Bearer ${authToken}`;
  4525. }
  4526. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, {
  4527. method: 'POST',
  4528. headers,
  4529. body: formData,
  4530. });
  4531. if (!response.ok) {
  4532. const error = await response.json().catch(() => ({}));
  4533. throw new Error(error.detail || `HTTP ${response.status}`);
  4534. }
  4535. return response.json();
  4536. },
  4537. deleteSource3mf: (archiveId: number) =>
  4538. request<{ status: string }>(`/archives/${archiveId}/source`, {
  4539. method: 'DELETE',
  4540. }),
  4541. // F3D (Fusion 360 design file)
  4542. getF3dDownloadUrl: (archiveId: number) =>
  4543. `${API_BASE}/archives/${archiveId}/f3d`,
  4544. downloadF3d: async (archiveId: number): Promise<void> => {
  4545. const headers: Record<string, string> = {};
  4546. if (authToken) {
  4547. headers['Authorization'] = `Bearer ${authToken}`;
  4548. }
  4549. const response = await fetch(`${API_BASE}/archives/${archiveId}/f3d`, { headers });
  4550. if (!response.ok) {
  4551. const error = await response.json().catch(() => ({}));
  4552. throw new Error(error.detail || `HTTP ${response.status}`);
  4553. }
  4554. const disposition = response.headers.get('Content-Disposition');
  4555. const filename = parseContentDispositionFilename(disposition) || `archive_${archiveId}.f3d`;
  4556. const blob = await response.blob();
  4557. const url = window.URL.createObjectURL(blob);
  4558. const a = document.createElement('a');
  4559. a.href = url;
  4560. a.download = filename;
  4561. document.body.appendChild(a);
  4562. a.click();
  4563. document.body.removeChild(a);
  4564. window.URL.revokeObjectURL(url);
  4565. },
  4566. uploadF3d: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  4567. const formData = new FormData();
  4568. formData.append('file', file);
  4569. const headers: Record<string, string> = {};
  4570. if (authToken) {
  4571. headers['Authorization'] = `Bearer ${authToken}`;
  4572. }
  4573. const response = await fetch(`${API_BASE}/archives/${archiveId}/f3d`, {
  4574. method: 'POST',
  4575. headers,
  4576. body: formData,
  4577. });
  4578. if (!response.ok) {
  4579. const error = await response.json().catch(() => ({}));
  4580. throw new Error(error.detail || `HTTP ${response.status}`);
  4581. }
  4582. return response.json();
  4583. },
  4584. deleteF3d: (archiveId: number) =>
  4585. request<{ status: string }>(`/archives/${archiveId}/f3d`, {
  4586. method: 'DELETE',
  4587. }),
  4588. // QR Code
  4589. getArchiveQRCodeUrl: (archiveId: number, size = 200) =>
  4590. withStreamToken(`${API_BASE}/archives/${archiveId}/qrcode?size=${size}`),
  4591. getArchiveCapabilities: (id: number) =>
  4592. request<{
  4593. has_model: boolean;
  4594. has_gcode: boolean;
  4595. has_source: boolean;
  4596. build_volume: { x: number; y: number; z: number };
  4597. filament_colors: string[];
  4598. }>(`/archives/${id}/capabilities`),
  4599. // Project Page
  4600. getArchiveProjectPage: (id: number) =>
  4601. request<{
  4602. title: string | null;
  4603. description: string | null;
  4604. designer: string | null;
  4605. designer_user_id: string | null;
  4606. license: string | null;
  4607. copyright: string | null;
  4608. creation_date: string | null;
  4609. modification_date: string | null;
  4610. origin: string | null;
  4611. profile_title: string | null;
  4612. profile_description: string | null;
  4613. profile_cover: string | null;
  4614. profile_user_id: string | null;
  4615. profile_user_name: string | null;
  4616. design_model_id: string | null;
  4617. design_profile_id: string | null;
  4618. design_region: string | null;
  4619. model_pictures: Array<{ name: string; path: string; url: string }>;
  4620. profile_pictures: Array<{ name: string; path: string; url: string }>;
  4621. thumbnails: Array<{ name: string; path: string; url: string }>;
  4622. }>(`/archives/${id}/project-page`),
  4623. updateArchiveProjectPage: (id: number, data: {
  4624. title?: string;
  4625. description?: string;
  4626. designer?: string;
  4627. license?: string;
  4628. copyright?: string;
  4629. profile_title?: string;
  4630. profile_description?: string;
  4631. }) =>
  4632. request(`/archives/${id}/project-page`, {
  4633. method: 'PATCH',
  4634. body: JSON.stringify(data),
  4635. }),
  4636. getArchiveProjectImageUrl: (archiveId: number, imagePath: string) =>
  4637. withStreamToken(`${API_BASE}/archives/${archiveId}/project-image/${encodeURIComponent(imagePath)}`),
  4638. getArchiveForSlicer: (id: number, filename: string) => {
  4639. const safe = filename.replace(/[/\\?#]/g, '_');
  4640. return `${API_BASE}/archives/${id}/file/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  4641. },
  4642. createArchiveSlicerToken: (archiveId: number) =>
  4643. request<{ token: string }>(`/archives/${archiveId}/slicer-token`, { method: 'POST' }),
  4644. getArchiveSlicerDownloadUrl: (archiveId: number, token: string, filename: string) => {
  4645. const safe = filename.replace(/[/\\?#]/g, '_');
  4646. return `${API_BASE}/archives/${archiveId}/dl/${token}/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  4647. },
  4648. getArchivePlates: (archiveId: number) =>
  4649. request<ArchivePlatesResponse>(`/archives/${archiveId}/plates`),
  4650. getArchiveFilamentRequirements: (
  4651. archiveId: number,
  4652. plateId?: number,
  4653. requestId?: string,
  4654. /** Ask for one entry per project slot instead of only the slots this
  4655. * plate consumes. The slice modal needs it: its filament list is
  4656. * positional, so a source whose only used slot is 4 must still present
  4657. * four rows or the user's pick is bound to slot 1 (#2712). Print-time
  4658. * AMS matching must NOT set this — it wants the used-only list. */
  4659. fullSlots?: boolean,
  4660. ) => {
  4661. const qs = new URLSearchParams();
  4662. if (plateId !== undefined) qs.set('plate_id', String(plateId));
  4663. if (requestId) qs.set('request_id', requestId);
  4664. if (fullSlots) qs.set('full_slots', 'true');
  4665. return request<{
  4666. archive_id: number;
  4667. filename: string;
  4668. plate_id: number | null;
  4669. filaments: Array<{
  4670. slot_id: number;
  4671. type: string;
  4672. color: string;
  4673. used_grams: number;
  4674. used_meters: number;
  4675. used_in_plate?: boolean;
  4676. }>;
  4677. }>(`/archives/${archiveId}/filament-requirements${qs.toString() ? `?${qs}` : ''}`);
  4678. },
  4679. uploadArchive: async (file: File, printerId?: number): Promise<Archive> => {
  4680. const formData = new FormData();
  4681. formData.append('file', file);
  4682. const url = printerId
  4683. ? `${API_BASE}/archives/upload?printer_id=${printerId}`
  4684. : `${API_BASE}/archives/upload`;
  4685. const headers: Record<string, string> = {};
  4686. if (authToken) {
  4687. headers['Authorization'] = `Bearer ${authToken}`;
  4688. }
  4689. const response = await fetch(url, {
  4690. method: 'POST',
  4691. headers,
  4692. body: formData,
  4693. });
  4694. if (!response.ok) {
  4695. const error = await response.json().catch(() => ({}));
  4696. throw new Error(error.detail || `HTTP ${response.status}`);
  4697. }
  4698. return response.json();
  4699. },
  4700. uploadArchivesBulk: async (files: File[], printerId?: number): Promise<BulkUploadResult> => {
  4701. const formData = new FormData();
  4702. files.forEach((file) => formData.append('files', file));
  4703. const url = printerId
  4704. ? `${API_BASE}/archives/upload-bulk?printer_id=${printerId}`
  4705. : `${API_BASE}/archives/upload-bulk`;
  4706. const headers: Record<string, string> = {};
  4707. if (authToken) {
  4708. headers['Authorization'] = `Bearer ${authToken}`;
  4709. }
  4710. const response = await fetch(url, {
  4711. method: 'POST',
  4712. headers,
  4713. body: formData,
  4714. });
  4715. if (!response.ok) {
  4716. const error = await response.json().catch(() => ({}));
  4717. throw new Error(error.detail || `HTTP ${response.status}`);
  4718. }
  4719. return response.json();
  4720. },
  4721. // Print Log
  4722. getPrintLog: (params?: {
  4723. search?: string;
  4724. printerId?: number;
  4725. username?: string;
  4726. status?: string;
  4727. dateFrom?: string;
  4728. dateTo?: string;
  4729. limit?: number;
  4730. offset?: number;
  4731. // Sorting is server-side because paging is: ordering only the rows the
  4732. // client holds would sort one page, not the log (#2636).
  4733. sortBy?: string;
  4734. sortDir?: 'asc' | 'desc';
  4735. }) => {
  4736. const searchParams = new URLSearchParams();
  4737. if (params?.search) searchParams.set('search', params.search);
  4738. if (params?.printerId) searchParams.set('printer_id', String(params.printerId));
  4739. if (params?.username) searchParams.set('created_by_username', params.username);
  4740. if (params?.status) searchParams.set('status', params.status);
  4741. if (params?.dateFrom) searchParams.set('date_from', params.dateFrom);
  4742. if (params?.dateTo) searchParams.set('date_to', params.dateTo);
  4743. if (params?.limit) searchParams.set('limit', String(params.limit));
  4744. if (params?.offset !== undefined) searchParams.set('offset', String(params.offset));
  4745. if (params?.sortBy) searchParams.set('sort_by', params.sortBy);
  4746. if (params?.sortDir) searchParams.set('sort_dir', params.sortDir);
  4747. return request<PrintLogResponse>(`/print-log/?${searchParams}`);
  4748. },
  4749. getPrintLogThumbnail: (id: number) => withStreamToken(`${API_BASE}/print-log/${id}/thumbnail`),
  4750. clearPrintLog: () =>
  4751. request<{ deleted: number }>('/print-log/', { method: 'DELETE' }),
  4752. deletePrintLogEntry: (id: number) =>
  4753. request<{ status: string; id: number }>(`/print-log/${id}`, { method: 'DELETE' }),
  4754. // Edit failure_reason / status on a single Print Log row (#1687 part 4).
  4755. // Distinct from updateArchive: archives describe the model, log entries
  4756. // describe a single print event. Orphan entries (no archive_id) have no
  4757. // archive to reach through and this is the only path to classify them.
  4758. updatePrintLogEntry: (
  4759. id: number,
  4760. body: { failure_reason?: string | null; status?: string },
  4761. ) =>
  4762. request<PrintLogEntry>(`/print-log/${id}`, {
  4763. method: 'PATCH',
  4764. body: JSON.stringify(body),
  4765. }),
  4766. // Settings
  4767. getSettings: () => request<AppSettings>('/settings/'),
  4768. getDefaultSidebarOrder: () => request<{ default_sidebar_order: string }>('/settings/default-sidebar-order'),
  4769. // Public subset of settings for UI rendering — no settings:read required.
  4770. // Used by pages whose users may not have SETTINGS_READ (e.g. operators with
  4771. // only printers:clear_plate). Keep in sync with _UI_PREFERENCE_FIELDS in
  4772. // backend/app/api/routes/settings.py.
  4773. getUiPreferences: () =>
  4774. request<{
  4775. require_plate_clear?: boolean;
  4776. check_printer_firmware?: boolean;
  4777. camera_view_mode?: 'window' | 'embedded';
  4778. time_format?: 'system' | '12h' | '24h';
  4779. date_format?: string;
  4780. drying_presets?: string;
  4781. ams_humidity_thresholds?: string;
  4782. ams_humidity_good?: number;
  4783. ams_humidity_fair?: number;
  4784. ams_temp_good?: number;
  4785. ams_temp_fair?: number;
  4786. bed_cooled_threshold?: number;
  4787. nozzle_temp_presets?: string;
  4788. bed_temp_presets?: string;
  4789. chamber_temp_presets?: string;
  4790. fan_speed_presets?: string;
  4791. }>('/settings/ui-preferences'),
  4792. updateSettings: (data: AppSettingsUpdate) =>
  4793. request<AppSettings>('/settings/', {
  4794. method: 'PUT',
  4795. body: JSON.stringify(data),
  4796. }),
  4797. getMQTTStatus: () => request<MQTTStatus>('/settings/mqtt/status'),
  4798. resetSettings: () =>
  4799. request<AppSettings>('/settings/reset', { method: 'POST' }),
  4800. exportBackup: async (): Promise<{ blob: Blob; filename: string }> => {
  4801. // New simplified backup - complete database + all files
  4802. const url = `${API_BASE}/settings/backup`;
  4803. const headers: Record<string, string> = {};
  4804. if (authToken) {
  4805. headers['Authorization'] = `Bearer ${authToken}`;
  4806. }
  4807. const response = await fetch(url, { headers });
  4808. // Check for errors
  4809. if (!response.ok) {
  4810. const errorText = await response.text();
  4811. throw new Error(errorText || `Backup failed with status ${response.status}`);
  4812. }
  4813. // Get filename from Content-Disposition header
  4814. const contentDisposition = response.headers.get('Content-Disposition');
  4815. let filename = 'bambuddy-backup.zip';
  4816. if (contentDisposition) {
  4817. const match = contentDisposition.match(/filename=([^;]+)/);
  4818. if (match) filename = match[1].trim().replace(/^"(.*)"$/, '$1');
  4819. }
  4820. const blob = await response.blob();
  4821. return { blob, filename };
  4822. },
  4823. importBackup: async (file: File) => {
  4824. // New simplified restore - replaces database + all directories
  4825. const formData = new FormData();
  4826. formData.append('file', file);
  4827. const url = `${API_BASE}/settings/restore`;
  4828. const headers: Record<string, string> = {};
  4829. if (authToken) {
  4830. headers['Authorization'] = `Bearer ${authToken}`;
  4831. }
  4832. const response = await fetch(url, {
  4833. method: 'POST',
  4834. headers,
  4835. body: formData,
  4836. });
  4837. return response.json() as Promise<{
  4838. success: boolean;
  4839. message: string;
  4840. }>;
  4841. },
  4842. checkFfmpeg: () =>
  4843. request<{ installed: boolean; path: string | null }>('/settings/check-ffmpeg'),
  4844. getNetworkInterfaces: () =>
  4845. request<{ interfaces: NetworkInterface[] }>('/settings/network-interfaces'),
  4846. // Cloud
  4847. getCloudStatus: () => request<CloudAuthStatus>('/cloud/status'),
  4848. cloudLogin: (email: string, password: string, region = 'global') =>
  4849. request<CloudLoginResponse>('/cloud/login', {
  4850. method: 'POST',
  4851. body: JSON.stringify({ email, password, region }),
  4852. }),
  4853. cloudVerify: (email: string, code: string, tfaKey?: string, region: string = 'global') =>
  4854. request<CloudLoginResponse>('/cloud/verify', {
  4855. method: 'POST',
  4856. body: JSON.stringify({ email, code, tfa_key: tfaKey, region }),
  4857. }),
  4858. cloudSetToken: (access_token: string, region: string = 'global') =>
  4859. request<CloudAuthStatus>('/cloud/token', {
  4860. method: 'POST',
  4861. body: JSON.stringify({ access_token, region }),
  4862. }),
  4863. cloudLogout: () =>
  4864. request<{ success: boolean }>('/cloud/logout', { method: 'POST' }),
  4865. // Orca Cloud — RFC 8628 device pairing. deviceStart() returns a short
  4866. // user_code + verification link; the user approves it in their Orca Cloud
  4867. // settings while the frontend polls devicePoll() every `interval` seconds
  4868. // until the status flips to 'complete' (or a terminal deny/expire).
  4869. orcaCloudDeviceStart: () =>
  4870. request<OrcaDeviceStartResponse>('/orca-cloud/device/start', {
  4871. method: 'POST',
  4872. }),
  4873. orcaCloudDevicePoll: () =>
  4874. request<OrcaDevicePollResponse>('/orca-cloud/device/poll', {
  4875. method: 'POST',
  4876. }),
  4877. orcaCloudStatus: () =>
  4878. request<OrcaAuthStatusResponse>('/orca-cloud/status'),
  4879. orcaCloudLogout: () =>
  4880. request<{ success: boolean }>('/orca-cloud/logout', { method: 'POST' }),
  4881. orcaCloudListProfiles: () =>
  4882. request<OrcaProfileListResponse>('/orca-cloud/profiles'),
  4883. orcaCloudGetProfile: (id: string) =>
  4884. request<OrcaProfileDetail>(`/orca-cloud/profiles/${id}`),
  4885. getCloudSettings: (version = '02.04.00.70') =>
  4886. request<SlicerSettingsResponse>(`/cloud/settings?version=${version}`),
  4887. getBuiltinFilaments: () =>
  4888. request<BuiltinFilament[]>('/cloud/builtin-filaments'),
  4889. getFilamentIdMap: () =>
  4890. request<Record<string, string>>('/cloud/filament-id-map'),
  4891. /** Material-disambiguated hex→name lookup. Same hex can map to different
  4892. * catalog names depending on material (e.g. #000000 is "Charcoal" in PLA
  4893. * Matte but "Black" in PLA Basic). The flat ``/inventory/colors/map``
  4894. * collapses these to the first hit; this endpoint preserves the material
  4895. * context. Returns ``{color_name: null}`` when the hex isn't in the
  4896. * catalog at all. #1718. */
  4897. getColorByMaterial: (hex: string, material?: string) => {
  4898. const params = new URLSearchParams({ hex });
  4899. if (material) params.set('material', material);
  4900. return request<{ color_name: string | null }>(
  4901. `/inventory/colors/by-material?${params.toString()}`,
  4902. );
  4903. },
  4904. // MakerWorld URL-paste import flow.
  4905. getMakerworldStatus: () =>
  4906. request<MakerworldStatus>('/makerworld/status'),
  4907. resolveMakerworldUrl: (url: string) =>
  4908. request<MakerworldResolvedModel>('/makerworld/resolve', {
  4909. method: 'POST',
  4910. body: JSON.stringify({ url }),
  4911. }),
  4912. getMakerworldRecentImports: (limit = 10) =>
  4913. request<MakerworldRecentImport[]>(`/makerworld/recent-imports?limit=${limit}`),
  4914. importMakerworldInstance: (
  4915. model_id: number,
  4916. instance_id: number | null,
  4917. profile_id?: number | null,
  4918. folder_id?: number | null,
  4919. ) =>
  4920. request<MakerworldImportResponse>('/makerworld/import', {
  4921. method: 'POST',
  4922. body: JSON.stringify({
  4923. model_id,
  4924. instance_id: instance_id ?? null,
  4925. profile_id: profile_id ?? null,
  4926. folder_id: folder_id ?? null,
  4927. }),
  4928. }),
  4929. getCloudSettingDetail: (settingId: string) =>
  4930. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`),
  4931. createCloudSetting: (data: SlicerSettingCreate) =>
  4932. request<SlicerSettingDetail>('/cloud/settings', {
  4933. method: 'POST',
  4934. body: JSON.stringify(data),
  4935. }),
  4936. updateCloudSetting: (settingId: string, data: SlicerSettingUpdate) =>
  4937. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`, {
  4938. method: 'PUT',
  4939. body: JSON.stringify(data),
  4940. }),
  4941. deleteCloudSetting: (settingId: string) =>
  4942. request<SlicerSettingDeleteResponse>(`/cloud/settings/${settingId}`, {
  4943. method: 'DELETE',
  4944. }),
  4945. getCloudDevices: () => request<CloudDevice[]>('/cloud/devices'),
  4946. getCloudFields: (presetType: 'filament' | 'print' | 'process' | 'printer') =>
  4947. request<FieldDefinitionsResponse>(`/cloud/fields/${presetType}`),
  4948. getAllCloudFields: () =>
  4949. request<Record<string, FieldDefinitionsResponse>>('/cloud/fields'),
  4950. getFilamentInfo: (settingIds: string[]) =>
  4951. request<Record<string, { name: string; k: number | null }>>('/cloud/filament-info', {
  4952. method: 'POST',
  4953. body: JSON.stringify(settingIds),
  4954. }),
  4955. // Smart Plugs
  4956. getSmartPlugs: () => request<SmartPlug[]>('/smart-plugs/'),
  4957. getSmartPlug: (id: number) => request<SmartPlug>(`/smart-plugs/${id}`),
  4958. getSmartPlugByPrinter: (printerId: number) => request<SmartPlug | null>(`/smart-plugs/by-printer/${printerId}`),
  4959. getScriptPlugsByPrinter: (printerId: number) => request<SmartPlug[]>(`/smart-plugs/by-printer/${printerId}/scripts`),
  4960. createSmartPlug: (data: SmartPlugCreate) =>
  4961. request<SmartPlug>('/smart-plugs/', {
  4962. method: 'POST',
  4963. body: JSON.stringify(data),
  4964. }),
  4965. updateSmartPlug: (id: number, data: SmartPlugUpdate) =>
  4966. request<SmartPlug>(`/smart-plugs/${id}`, {
  4967. method: 'PATCH',
  4968. body: JSON.stringify(data),
  4969. }),
  4970. deleteSmartPlug: (id: number) =>
  4971. request<void>(`/smart-plugs/${id}`, { method: 'DELETE' }),
  4972. controlSmartPlug: (id: number, action: 'on' | 'off' | 'toggle') =>
  4973. request<{ success: boolean; action: string }>(`/smart-plugs/${id}/control`, {
  4974. method: 'POST',
  4975. body: JSON.stringify({ action }),
  4976. }),
  4977. getSmartPlugStatus: (id: number) =>
  4978. request<SmartPlugStatus>(`/smart-plugs/${id}/status`),
  4979. testSmartPlugConnection: (ip_address: string, username?: string | null, password?: string | null) =>
  4980. request<SmartPlugTestResult>('/smart-plugs/test-connection', {
  4981. method: 'POST',
  4982. body: JSON.stringify({ ip_address, username, password }),
  4983. }),
  4984. // Tasmota Discovery (auto-detects network)
  4985. startTasmotaScan: () =>
  4986. request<TasmotaScanStatus>('/smart-plugs/discover/scan', { method: 'POST' }),
  4987. getTasmotaScanStatus: () =>
  4988. request<TasmotaScanStatus>('/smart-plugs/discover/status'),
  4989. stopTasmotaScan: () =>
  4990. request<TasmotaScanStatus>('/smart-plugs/discover/stop', { method: 'POST' }),
  4991. getDiscoveredTasmotaDevices: () =>
  4992. request<DiscoveredTasmotaDevice[]>('/smart-plugs/discover/devices'),
  4993. // Home Assistant Integration
  4994. testHAConnection: (url: string, token: string) =>
  4995. request<HATestConnectionResult>('/smart-plugs/ha/test-connection', {
  4996. method: 'POST',
  4997. body: JSON.stringify({ url, token }),
  4998. }),
  4999. getHAEntities: (search?: string) => {
  5000. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  5001. return request<HAEntity[]>(`/smart-plugs/ha/entities${params}`);
  5002. },
  5003. getHASensorEntities: () =>
  5004. request<HASensorEntity[]>('/smart-plugs/ha/sensors'),
  5005. // Home Assistant sensors bound to a printer (#1148, #448)
  5006. getHASensors: (printerId?: number) =>
  5007. request<PrinterHASensor[]>(`/ha-sensors/${printerId ? `?printer_id=${printerId}` : ''}`),
  5008. getHASensorReadings: (printerId: number) =>
  5009. request<PrinterHASensorReading[]>(`/ha-sensors/by-printer/${printerId}/readings`),
  5010. getBindableHAEntities: (search?: string) => {
  5011. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  5012. return request<HADisplayEntity[]>(`/ha-sensors/entities${params}`);
  5013. },
  5014. createHASensor: (data: PrinterHASensorCreate) =>
  5015. request<PrinterHASensor>('/ha-sensors/', { method: 'POST', body: JSON.stringify(data) }),
  5016. updateHASensor: (id: number, data: PrinterHASensorUpdate) =>
  5017. request<PrinterHASensor>(`/ha-sensors/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  5018. deleteHASensor: (id: number) =>
  5019. request<{ message: string }>(`/ha-sensors/${id}`, { method: 'DELETE' }),
  5020. // REST smart plug
  5021. testRESTConnection: (url: string, method: string = 'GET', headers?: string | null) =>
  5022. request<{ success: boolean; error: string | null }>('/smart-plugs/rest/test-connection', {
  5023. method: 'POST',
  5024. body: JSON.stringify({ url, method, headers }),
  5025. }),
  5026. // Print Queue
  5027. getQueue: (printerId?: number, status?: string, targetModel?: string) => {
  5028. const params = new URLSearchParams();
  5029. if (printerId) params.set('printer_id', String(printerId));
  5030. if (status) params.set('status', status);
  5031. if (targetModel) params.set('target_model', targetModel);
  5032. return request<PrintQueueItem[]>(`/queue/?${params}`);
  5033. },
  5034. getQueueItem: (id: number) => request<PrintQueueItem>(`/queue/${id}`),
  5035. addToQueue: (data: PrintQueueItemCreate) =>
  5036. request<PrintQueueItem>('/queue/', {
  5037. method: 'POST',
  5038. body: JSON.stringify(data),
  5039. }),
  5040. updateQueueItem: (id: number, data: PrintQueueItemUpdate) =>
  5041. request<PrintQueueItem>(`/queue/${id}`, {
  5042. method: 'PATCH',
  5043. body: JSON.stringify(data),
  5044. }),
  5045. removeFromQueue: (id: number) =>
  5046. request<{ message: string }>(`/queue/${id}`, { method: 'DELETE' }),
  5047. reorderQueue: (items: { id: number; position: number }[]) =>
  5048. request<{ message: string }>('/queue/reorder', {
  5049. method: 'POST',
  5050. body: JSON.stringify({ items }),
  5051. }),
  5052. cancelQueueItem: (id: number) =>
  5053. request<{ message: string }>(`/queue/${id}/cancel`, { method: 'POST' }),
  5054. stopQueueItem: (id: number) =>
  5055. request<{ message: string }>(`/queue/${id}/stop`, { method: 'POST' }),
  5056. /**
  5057. * Start a staged queue item. The backend re-checks live filament deficit
  5058. * for the assigned spool and, when short, returns 409 with a structured
  5059. * payload so the caller can confirm and retry. Pass `skipFilamentCheck`
  5060. * after the user confirms "Print Anyway" (#1496).
  5061. */
  5062. startQueueItem: (id: number, opts?: { skipFilamentCheck?: boolean }) => {
  5063. const qs = opts?.skipFilamentCheck ? '?skip_filament_check=true' : '';
  5064. return request<PrintQueueItem>(`/queue/${id}/start${qs}`, { method: 'POST' });
  5065. },
  5066. /**
  5067. * Clear the `require_previous_success` gate for a printer after the user
  5068. * resolves the failure. Acknowledges any failed/aborted predecessors and
  5069. * restores skipped items whose error_message matches the gate string
  5070. * back to pending. Returns counts so the UI can render a precise toast.
  5071. */
  5072. resumeQueueAfterFailure: (printerId: number) =>
  5073. request<{ acknowledged: number; restored: number }>(
  5074. `/queue/printer/${printerId}/resume`,
  5075. { method: 'POST' },
  5076. ),
  5077. bulkUpdateQueue: (data: PrintQueueBulkUpdate) =>
  5078. request<PrintQueueBulkUpdateResponse>('/queue/bulk', {
  5079. method: 'PATCH',
  5080. body: JSON.stringify(data),
  5081. }),
  5082. // Batches
  5083. getBatches: (status?: string) => {
  5084. const params = status ? `?status=${status}` : '';
  5085. return request<PrintBatch[]>(`/queue/batches${params}`);
  5086. },
  5087. getBatch: (id: number) => request<PrintBatch>(`/queue/batches/${id}`),
  5088. cancelBatch: (id: number) =>
  5089. request<{ message: string }>(`/queue/batches/${id}`, { method: 'DELETE' }),
  5090. createBatch: (data: PrintBatchCreate) =>
  5091. request<PrintBatch>('/queue/batches', {
  5092. method: 'POST',
  5093. body: JSON.stringify(data),
  5094. }),
  5095. updateBatch: (id: number, data: PrintBatchUpdate) =>
  5096. request<PrintBatch>(`/queue/batches/${id}`, {
  5097. method: 'PATCH',
  5098. body: JSON.stringify(data),
  5099. }),
  5100. dispatchBatch: (id: number, data: PrintBatchDispatchRequest = {}) =>
  5101. request<PrintBatch>(`/queue/batches/${id}/dispatch`, {
  5102. method: 'POST',
  5103. body: JSON.stringify(data),
  5104. }),
  5105. ungroupBatch: (id: number) =>
  5106. request<{ ungrouped_count: number; message: string }>(
  5107. `/queue/batches/${id}/ungroup`,
  5108. { method: 'POST' },
  5109. ),
  5110. // K-Profiles
  5111. getKProfiles: (printerId: number, nozzleDiameter = '0.4') =>
  5112. request<KProfilesResponse>(`/printers/${printerId}/kprofiles/?nozzle_diameter=${nozzleDiameter}`),
  5113. setKProfile: (printerId: number, profile: KProfileCreate) =>
  5114. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/`, {
  5115. method: 'POST',
  5116. body: JSON.stringify(profile),
  5117. }),
  5118. deleteKProfile: (printerId: number, profile: KProfileDelete) =>
  5119. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/`, {
  5120. method: 'DELETE',
  5121. body: JSON.stringify(profile),
  5122. }),
  5123. setKProfilesBatch: (printerId: number, profiles: KProfileCreate[]) =>
  5124. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/batch`, {
  5125. method: 'POST',
  5126. body: JSON.stringify(profiles),
  5127. }),
  5128. // K-Profile Notes (stored locally, not on printer)
  5129. getKProfileNotes: (printerId: number) =>
  5130. request<KProfileNotesResponse>(`/printers/${printerId}/kprofiles/notes`),
  5131. setKProfileNote: (printerId: number, settingId: string, note: string) =>
  5132. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/notes`, {
  5133. method: 'PUT',
  5134. body: JSON.stringify({ setting_id: settingId, note }),
  5135. }),
  5136. deleteKProfileNote: (printerId: number, settingId: string) =>
  5137. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/notes/${encodeURIComponent(settingId)}`, {
  5138. method: 'DELETE',
  5139. }),
  5140. // Slot Preset Mappings
  5141. getSlotPresets: (printerId: number) =>
  5142. request<Record<number, SlotPresetMapping>>(`/printers/${printerId}/slot-presets`),
  5143. getSlotPreset: (printerId: number, amsId: number, trayId: number) =>
  5144. request<SlotPresetMapping | null>(`/printers/${printerId}/slot-presets/${amsId}/${trayId}`),
  5145. saveSlotPreset: (printerId: number, amsId: number, trayId: number, presetId: string, presetName: string, presetSource = 'cloud') =>
  5146. request<SlotPresetMapping>(`/printers/${printerId}/slot-presets/${amsId}/${trayId}?preset_id=${encodeURIComponent(presetId)}&preset_name=${encodeURIComponent(presetName)}&preset_source=${encodeURIComponent(presetSource)}`, {
  5147. method: 'PUT',
  5148. }),
  5149. deleteSlotPreset: (printerId: number, amsId: number, trayId: number) =>
  5150. request<{ success: boolean }>(`/printers/${printerId}/slot-presets/${amsId}/${trayId}`, {
  5151. method: 'DELETE',
  5152. }),
  5153. // AMS Labels (user-defined friendly names)
  5154. getAmsLabels: (printerId: number) =>
  5155. request<Record<number, string>>(`/printers/${printerId}/ams-labels`),
  5156. saveAmsLabel: (printerId: number, amsId: number, label: string, amsSerial = '') =>
  5157. request<{ ams_id: number; label: string }>(
  5158. `/printers/${printerId}/ams-labels/${amsId}`,
  5159. {
  5160. method: 'PUT',
  5161. body: JSON.stringify({ label, ams_serial: amsSerial }),
  5162. }
  5163. ),
  5164. deleteAmsLabel: (printerId: number, amsId: number, amsSerial = '') =>
  5165. request<{ success: boolean }>(`/printers/${printerId}/ams-labels/${amsId}?ams_serial=${encodeURIComponent(amsSerial)}`, {
  5166. method: 'DELETE',
  5167. }),
  5168. configureAmsSlot: (
  5169. printerId: number,
  5170. amsId: number,
  5171. trayId: number,
  5172. config: {
  5173. tray_info_idx: string;
  5174. tray_type: string;
  5175. tray_sub_brands: string;
  5176. tray_color: string;
  5177. nozzle_temp_min: number;
  5178. nozzle_temp_max: number;
  5179. cali_idx: number;
  5180. nozzle_diameter: string;
  5181. setting_id?: string;
  5182. kprofile_filament_id?: string;
  5183. kprofile_setting_id?: string;
  5184. k_value?: number;
  5185. }
  5186. ) => {
  5187. const params = new URLSearchParams({
  5188. tray_info_idx: config.tray_info_idx,
  5189. tray_type: config.tray_type,
  5190. tray_sub_brands: config.tray_sub_brands,
  5191. tray_color: config.tray_color,
  5192. nozzle_temp_min: config.nozzle_temp_min.toString(),
  5193. nozzle_temp_max: config.nozzle_temp_max.toString(),
  5194. cali_idx: config.cali_idx.toString(),
  5195. nozzle_diameter: config.nozzle_diameter,
  5196. });
  5197. if (config.setting_id) {
  5198. params.set('setting_id', config.setting_id);
  5199. }
  5200. if (config.kprofile_filament_id) {
  5201. params.set('kprofile_filament_id', config.kprofile_filament_id);
  5202. }
  5203. if (config.kprofile_setting_id) {
  5204. params.set('kprofile_setting_id', config.kprofile_setting_id);
  5205. }
  5206. if (config.k_value !== undefined && config.k_value > 0) {
  5207. params.set('k_value', config.k_value.toString());
  5208. }
  5209. return request<{ success: boolean; message: string }>(
  5210. `/printers/${printerId}/slots/${amsId}/${trayId}/configure?${params}`,
  5211. { method: 'POST' }
  5212. );
  5213. },
  5214. resetAmsSlot: (printerId: number, amsId: number, trayId: number) =>
  5215. request<{ success: boolean; message: string }>(
  5216. `/printers/${printerId}/ams/${amsId}/tray/${trayId}/reset`,
  5217. { method: 'POST' }
  5218. ),
  5219. // Filament Catalog (material types with cost/temp data)
  5220. listFilaments: () => request<Filament[]>('/filament-catalog/'),
  5221. getFilament: (id: number) => request<Filament>(`/filament-catalog/${id}`),
  5222. getFilamentsByType: (type: string) => request<Filament[]>(`/filament-catalog/by-type/${type}`),
  5223. // Notification Providers
  5224. getNotificationProviders: () => request<NotificationProvider[]>('/notifications/'),
  5225. getNotificationProvider: (id: number) => request<NotificationProvider>(`/notifications/${id}`),
  5226. createNotificationProvider: (data: NotificationProviderCreate) =>
  5227. request<NotificationProvider>('/notifications/', {
  5228. method: 'POST',
  5229. body: JSON.stringify(data),
  5230. }),
  5231. updateNotificationProvider: (id: number, data: NotificationProviderUpdate) =>
  5232. request<NotificationProvider>(`/notifications/${id}`, {
  5233. method: 'PATCH',
  5234. body: JSON.stringify(data),
  5235. }),
  5236. deleteNotificationProvider: (id: number) =>
  5237. request<{ message: string }>(`/notifications/${id}`, { method: 'DELETE' }),
  5238. testNotificationProvider: (id: number) =>
  5239. request<NotificationTestResponse>(`/notifications/${id}/test`, { method: 'POST' }),
  5240. testNotificationConfig: (data: NotificationTestRequest) =>
  5241. request<NotificationTestResponse>('/notifications/test-config', {
  5242. method: 'POST',
  5243. body: JSON.stringify(data),
  5244. }),
  5245. testAllNotificationProviders: () =>
  5246. request<{
  5247. tested: number;
  5248. success: number;
  5249. failed: number;
  5250. results: Array<{
  5251. provider_id: number;
  5252. provider_name: string;
  5253. provider_type: string;
  5254. success: boolean;
  5255. message: string;
  5256. }>;
  5257. }>('/notifications/test-all', { method: 'POST' }),
  5258. // Notification Templates
  5259. getNotificationTemplates: () => request<NotificationTemplate[]>('/notification-templates'),
  5260. getNotificationTemplate: (id: number) => request<NotificationTemplate>(`/notification-templates/${id}`),
  5261. updateNotificationTemplate: (id: number, data: NotificationTemplateUpdate) =>
  5262. request<NotificationTemplate>(`/notification-templates/${id}`, {
  5263. method: 'PUT',
  5264. body: JSON.stringify(data),
  5265. }),
  5266. resetNotificationTemplate: (id: number) =>
  5267. request<NotificationTemplate>(`/notification-templates/${id}/reset`, {
  5268. method: 'POST',
  5269. }),
  5270. getTemplateVariables: () => request<EventVariablesResponse[]>('/notification-templates/variables'),
  5271. previewTemplate: (data: TemplatePreviewRequest) =>
  5272. request<TemplatePreviewResponse>('/notification-templates/preview', {
  5273. method: 'POST',
  5274. body: JSON.stringify(data),
  5275. }),
  5276. // Notification Logs
  5277. getNotificationLogs: (params?: {
  5278. limit?: number;
  5279. offset?: number;
  5280. provider_id?: number;
  5281. event_type?: string;
  5282. success?: boolean;
  5283. days?: number;
  5284. }) => {
  5285. const searchParams = new URLSearchParams();
  5286. if (params?.limit) searchParams.set('limit', String(params.limit));
  5287. if (params?.offset) searchParams.set('offset', String(params.offset));
  5288. if (params?.provider_id) searchParams.set('provider_id', String(params.provider_id));
  5289. if (params?.event_type) searchParams.set('event_type', params.event_type);
  5290. if (params?.success !== undefined) searchParams.set('success', String(params.success));
  5291. if (params?.days) searchParams.set('days', String(params.days));
  5292. return request<NotificationLogEntry[]>(`/notifications/logs?${searchParams}`);
  5293. },
  5294. getNotificationLogStats: (days = 7) =>
  5295. request<NotificationLogStats>(`/notifications/logs/stats?days=${days}`),
  5296. clearNotificationLogs: (olderThanDays = 30) =>
  5297. request<{ deleted: number; message: string }>(
  5298. `/notifications/logs?older_than_days=${olderThanDays}`,
  5299. { method: 'DELETE' }
  5300. ),
  5301. // Spoolman Integration
  5302. getSpoolmanStatus: () => request<SpoolmanStatus>('/spoolman/status'),
  5303. connectSpoolman: () =>
  5304. request<{ success: boolean; message: string }>('/spoolman/connect', {
  5305. method: 'POST',
  5306. }),
  5307. disconnectSpoolman: () =>
  5308. request<{ success: boolean; message: string }>('/spoolman/disconnect', {
  5309. method: 'POST',
  5310. }),
  5311. syncPrinterAms: (printerId: number) =>
  5312. request<SpoolmanSyncResult>(`/spoolman/sync/${printerId}`, {
  5313. method: 'POST',
  5314. }),
  5315. syncAllPrintersAms: () =>
  5316. request<SpoolmanSyncResult>('/spoolman/sync-all', {
  5317. method: 'POST',
  5318. }),
  5319. getSpoolmanSpools: () =>
  5320. request<{ spools: unknown[] }>('/spoolman/spools'),
  5321. /** @deprecated Use getSpoolmanInventoryFilaments() — this endpoint has no SSRF guard */
  5322. getSpoolmanFilaments: () =>
  5323. request<{ filaments: unknown[] }>('/spoolman/filaments'),
  5324. getSpoolmanInventoryFilaments: () =>
  5325. request<SpoolmanFilamentEntry[]>('/spoolman/inventory/filaments'),
  5326. patchSpoolmanFilament: (
  5327. filamentId: number,
  5328. data: { name?: string; spool_weight?: number | null; keep_existing_spools?: boolean },
  5329. ) =>
  5330. request<SpoolmanFilamentEntry>(`/spoolman/inventory/filaments/${filamentId}`, {
  5331. method: 'PATCH',
  5332. body: JSON.stringify(data),
  5333. }),
  5334. getUnlinkedSpools: () =>
  5335. request<UnlinkedSpool[]>('/spoolman/spools/unlinked'),
  5336. getLinkedSpools: () =>
  5337. request<LinkedSpoolsMap>('/spoolman/spools/linked'),
  5338. linkSpool: (
  5339. spoolId: number,
  5340. context: {
  5341. spoolTag: string;
  5342. printerId: number;
  5343. amsId: number;
  5344. trayId: number;
  5345. }
  5346. ) =>
  5347. request<{ success: boolean; message: string }>(`/spoolman/spools/${spoolId}/link`, {
  5348. method: 'POST',
  5349. body: JSON.stringify({
  5350. spool_tag: context.spoolTag,
  5351. printer_id: context.printerId,
  5352. ams_id: context.amsId,
  5353. tray_id: context.trayId,
  5354. }),
  5355. }),
  5356. unlinkSpool: (spoolId: number) =>
  5357. request<{ success: boolean; message: string }>(`/spoolman/spools/${spoolId}/unlink`, {
  5358. method: 'POST',
  5359. }),
  5360. createSpoolmanSpoolFromSlot: (data: { printer_id: number; ams_id: number; tray_id: number }) =>
  5361. request<{ success: boolean; spool_id: number | null }>(`/spoolman/spools/from-slot`, {
  5362. method: 'POST',
  5363. body: JSON.stringify(data),
  5364. }),
  5365. createSpoolFromSlot: (data: { printer_id: number; ams_id: number; tray_id: number }) =>
  5366. request<InventorySpool>(`/inventory/spools/from-slot`, {
  5367. method: 'POST',
  5368. body: JSON.stringify(data),
  5369. }),
  5370. getSpoolmanSettings: () =>
  5371. request<{ spoolman_enabled: string; spoolman_url: string; spoolman_sync_mode: string; spoolman_disable_weight_sync: string; spoolman_report_partial_usage: string; auto_add_unknown_rfid: string; }>('/settings/spoolman'),
  5372. updateSpoolmanSettings: (data: { spoolman_enabled?: string; spoolman_url?: string; spoolman_sync_mode?: string; spoolman_disable_weight_sync?: string; spoolman_report_partial_usage?: string; auto_add_unknown_rfid?: string; }) =>
  5373. request<{ spoolman_enabled: string; spoolman_url: string; spoolman_sync_mode: string; spoolman_disable_weight_sync: string; spoolman_report_partial_usage: string; auto_add_unknown_rfid: string; }>('/settings/spoolman', {
  5374. method: 'PUT',
  5375. body: JSON.stringify(data),
  5376. }),
  5377. // Inventory
  5378. getSpools: (includeArchived = false) =>
  5379. request<InventorySpool[]>(`/inventory/spools?include_archived=${includeArchived}`),
  5380. getSpool: (id: number) => request<InventorySpool>(`/inventory/spools/${id}`),
  5381. createSpool: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>) =>
  5382. request<InventorySpool>('/inventory/spools', {
  5383. method: 'POST',
  5384. body: JSON.stringify(data),
  5385. }),
  5386. bulkCreateSpools: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>, quantity: number) =>
  5387. request<InventorySpool[]>('/inventory/spools/bulk', {
  5388. method: 'POST',
  5389. body: JSON.stringify({ spool: data, quantity }),
  5390. }),
  5391. // ── CSV import/export (#1576) ────────────────────────────────────────────
  5392. // dry_run=true → preview (no write); omitted → real import. Both share one
  5393. // multipart upload helper; see `uploadSpoolsCsv` below.
  5394. importSpoolsCsvPreview: (file: File): Promise<CsvImportPreview> => uploadSpoolsCsv<CsvImportPreview>(file, true),
  5395. importSpoolsCsv: (file: File): Promise<CsvImportResult> => uploadSpoolsCsv<CsvImportResult>(file, false),
  5396. exportSpoolsCsv: async (): Promise<void> => {
  5397. const headers: Record<string, string> = {};
  5398. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  5399. const response = await fetch(`${API_BASE}/inventory/spools/export`, { headers });
  5400. if (!response.ok) {
  5401. const error = await response.json().catch(() => ({}));
  5402. throw new Error(error.detail || `HTTP ${response.status}`);
  5403. }
  5404. const disposition = response.headers.get('Content-Disposition');
  5405. const filename = parseContentDispositionFilename(disposition) || 'bambuddy_inventory.csv';
  5406. const blob = await response.blob();
  5407. const url = window.URL.createObjectURL(blob);
  5408. const a = document.createElement('a');
  5409. a.href = url;
  5410. a.download = filename;
  5411. document.body.appendChild(a);
  5412. a.click();
  5413. document.body.removeChild(a);
  5414. window.URL.revokeObjectURL(url);
  5415. },
  5416. updateSpool: (id: number, data: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  5417. request<InventorySpool>(`/inventory/spools/${id}`, {
  5418. method: 'PATCH',
  5419. body: JSON.stringify(data),
  5420. }),
  5421. deleteSpool: (id: number) =>
  5422. request<{ status: string }>(`/inventory/spools/${id}`, { method: 'DELETE' }),
  5423. archiveSpool: (id: number) =>
  5424. request<InventorySpool>(`/inventory/spools/${id}/archive`, { method: 'POST' }),
  5425. restoreSpool: (id: number) =>
  5426. request<InventorySpool>(`/inventory/spools/${id}/restore`, { method: 'POST' }),
  5427. resetSpoolConsumedCounter: (id: number) =>
  5428. request<InventorySpool>(`/inventory/spools/${id}/reset-consumed-counter`, { method: 'POST' }),
  5429. bulkResetSpoolConsumedCounter: (spoolIds: number[]) =>
  5430. request<{ reset: number }>(`/inventory/spools/reset-consumed-counter-bulk`, {
  5431. method: 'POST',
  5432. body: JSON.stringify({ spool_ids: spoolIds }),
  5433. }),
  5434. bulkUpdateSpools: (ids: number[], update: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  5435. request<{ updated: number; not_found: number[] }>(`/inventory/spools/bulk-update`, {
  5436. method: 'POST',
  5437. body: JSON.stringify({ ids, update }),
  5438. }),
  5439. bulkDeleteSpools: (ids: number[]) =>
  5440. request<{ deleted: number; not_found: number[] }>(`/inventory/spools/bulk-delete`, {
  5441. method: 'POST',
  5442. body: JSON.stringify({ ids }),
  5443. }),
  5444. bulkArchiveSpools: (ids: number[]) =>
  5445. request<{ archived: number; already_archived: number[]; not_found: number[] }>(`/inventory/spools/bulk-archive`, {
  5446. method: 'POST',
  5447. body: JSON.stringify({ ids }),
  5448. }),
  5449. bulkRestoreSpools: (ids: number[]) =>
  5450. request<{ restored: number; already_active: number[]; not_found: number[] }>(`/inventory/spools/bulk-restore`, {
  5451. method: 'POST',
  5452. body: JSON.stringify({ ids }),
  5453. }),
  5454. getSpoolKProfiles: (spoolId: number) =>
  5455. request<SpoolKProfile[]>(`/inventory/spools/${spoolId}/k-profiles`),
  5456. saveSpoolKProfiles: (spoolId: number, profiles: SpoolKProfileInput[]) =>
  5457. request<SpoolKProfile[]>(`/inventory/spools/${spoolId}/k-profiles`, {
  5458. method: 'PUT',
  5459. body: JSON.stringify(profiles),
  5460. }),
  5461. getAssignments: (printerId?: number) =>
  5462. request<SpoolAssignment[]>(`/inventory/assignments${printerId ? `?printer_id=${printerId}` : ''}`),
  5463. assignSpool: (data: { spool_id: number; printer_id: number; ams_id: number; tray_id: number }) =>
  5464. request<SpoolAssignment>('/inventory/assignments', {
  5465. method: 'POST',
  5466. body: JSON.stringify(data),
  5467. }),
  5468. unassignSpool: (printerId: number, amsId: number, trayId: number) =>
  5469. request<{ status: string }>(`/inventory/assignments/${printerId}/${amsId}/${trayId}`, { method: 'DELETE' }),
  5470. // ── Spool label printing (#809) ──────────────────────────────────────────
  5471. // Both endpoints return application/pdf. Frontend opens the resulting Blob
  5472. // in a new tab so the user can print or save from the browser's PDF viewer.
  5473. printSpoolLabels: async (data: { spool_ids: number[]; template: SpoolLabelTemplate; monochrome?: boolean }): Promise<Blob> => {
  5474. const headers: Record<string, string> = { 'Content-Type': 'application/json' };
  5475. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  5476. const response = await fetch(`${API_BASE}/inventory/labels`, {
  5477. method: 'POST',
  5478. headers,
  5479. body: JSON.stringify(data),
  5480. });
  5481. if (!response.ok) {
  5482. const error = await response.json().catch(() => ({}));
  5483. throw new Error(error.detail || `HTTP ${response.status}`);
  5484. }
  5485. return response.blob();
  5486. },
  5487. printSpoolmanSpoolLabels: async (data: { spool_ids: number[]; template: SpoolLabelTemplate; monochrome?: boolean }): Promise<Blob> => {
  5488. const headers: Record<string, string> = { 'Content-Type': 'application/json' };
  5489. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  5490. const response = await fetch(`${API_BASE}/spoolman/labels`, {
  5491. method: 'POST',
  5492. headers,
  5493. body: JSON.stringify(data),
  5494. });
  5495. if (!response.ok) {
  5496. const error = await response.json().catch(() => ({}));
  5497. throw new Error(error.detail || `HTTP ${response.status}`);
  5498. }
  5499. return response.blob();
  5500. },
  5501. getSpoolCatalog: () =>
  5502. request<SpoolCatalogEntry[]>('/inventory/catalog'),
  5503. addCatalogEntry: (data: { name: string; weight: number }) =>
  5504. request<SpoolCatalogEntry>('/inventory/catalog', { method: 'POST', body: JSON.stringify(data) }),
  5505. updateCatalogEntry: (id: number, data: { name: string; weight: number }) =>
  5506. request<SpoolCatalogEntry>(`/inventory/catalog/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  5507. deleteCatalogEntry: (id: number) =>
  5508. request<{ status: string }>(`/inventory/catalog/${id}`, { method: 'DELETE' }),
  5509. bulkDeleteCatalogEntries: (ids: number[]) =>
  5510. request<{ deleted: number }>('/inventory/catalog/bulk-delete', { method: 'POST', body: JSON.stringify({ ids }) }),
  5511. resetSpoolCatalog: () =>
  5512. request<{ status: string }>('/inventory/catalog/reset', { method: 'POST' }),
  5513. getLocations: () =>
  5514. request<StorageLocation[]>('/inventory/locations'),
  5515. createLocation: (data: { name: string; identifier?: string | null }) =>
  5516. request<StorageLocation>('/inventory/locations', { method: 'POST', body: JSON.stringify(data) }),
  5517. updateLocation: (id: number, data: { name?: string; identifier?: string | null }) =>
  5518. request<StorageLocation>(`/inventory/locations/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  5519. deleteLocation: (id: number) =>
  5520. request<{ status: string }>(`/inventory/locations/${id}`, { method: 'DELETE' }),
  5521. getColorCatalog: () =>
  5522. request<ColorCatalogEntry[]>('/inventory/colors'),
  5523. getColorNameMap: () =>
  5524. request<{ colors: Record<string, string> }>('/inventory/colors/map'),
  5525. addColorEntry: (data: {
  5526. manufacturer: string;
  5527. color_name: string;
  5528. hex_color: string;
  5529. material: string | null;
  5530. extra_colors?: string | null;
  5531. effect_type?: string | null;
  5532. }) =>
  5533. request<ColorCatalogEntry>('/inventory/colors', { method: 'POST', body: JSON.stringify(data) }),
  5534. updateColorEntry: (
  5535. id: number,
  5536. data: {
  5537. manufacturer: string;
  5538. color_name: string;
  5539. hex_color: string;
  5540. material: string | null;
  5541. extra_colors?: string | null;
  5542. effect_type?: string | null;
  5543. },
  5544. ) => request<ColorCatalogEntry>(`/inventory/colors/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  5545. deleteColorEntry: (id: number) =>
  5546. request<{ status: string }>(`/inventory/colors/${id}`, { method: 'DELETE' }),
  5547. bulkDeleteColorEntries: (ids: number[]) =>
  5548. request<{ deleted: number }>('/inventory/colors/bulk-delete', { method: 'POST', body: JSON.stringify({ ids }) }),
  5549. resetColorCatalog: () =>
  5550. request<{ status: string }>('/inventory/colors/reset', { method: 'POST' }),
  5551. lookupColor: (manufacturer: string, colorName: string, material?: string) =>
  5552. request<ColorLookupResult>(`/inventory/colors/lookup?manufacturer=${encodeURIComponent(manufacturer)}&color_name=${encodeURIComponent(colorName)}${material ? `&material=${encodeURIComponent(material)}` : ''}`),
  5553. searchColors: (manufacturer?: string, material?: string) =>
  5554. request<ColorCatalogEntry[]>(`/inventory/colors/search?${manufacturer ? `manufacturer=${encodeURIComponent(manufacturer)}` : ''}${manufacturer && material ? '&' : ''}${material ? `material=${encodeURIComponent(material)}` : ''}`),
  5555. linkTagToSpool: (spoolId: number, data: { tag_uid?: string; tray_uuid?: string; tag_type?: string; data_origin?: string }) =>
  5556. request<InventorySpool>(`/inventory/spools/${spoolId}/link-tag`, {
  5557. method: 'PATCH',
  5558. body: JSON.stringify(data),
  5559. }),
  5560. getSpoolUsageHistory: (spoolId: number, limit = 50) =>
  5561. request<SpoolUsageRecord[]>(`/inventory/spools/${spoolId}/usage?limit=${limit}`),
  5562. getAllUsageHistory: (limit = 100, printerId?: number) =>
  5563. request<SpoolUsageRecord[]>(`/inventory/usage?limit=${limit}${printerId ? `&printer_id=${printerId}` : ''}`),
  5564. clearSpoolUsageHistory: (spoolId: number) =>
  5565. request<{ status: string }>(`/inventory/spools/${spoolId}/usage`, { method: 'DELETE' }),
  5566. syncWeightsFromAms: () =>
  5567. request<{ synced: number; skipped: number }>('/inventory/sync-ams-weights', { method: 'POST' }),
  5568. getSkuSettings: () =>
  5569. request<FilamentSkuSettings[]>('/inventory/sku-settings'),
  5570. upsertSkuSettings: (data: Omit<FilamentSkuSettings, 'id'>) =>
  5571. request<FilamentSkuSettings>('/inventory/sku-settings', {
  5572. method: 'POST',
  5573. body: JSON.stringify(data),
  5574. }),
  5575. getShoppingList: () =>
  5576. request<ShoppingListItem[]>('/inventory/shopping-list'),
  5577. addToShoppingList: (data: ShoppingListItemCreate) =>
  5578. request<ShoppingListItem>('/inventory/shopping-list', {
  5579. method: 'POST',
  5580. body: JSON.stringify(data),
  5581. }),
  5582. removeFromShoppingList: (id: number) =>
  5583. request<{ status: string }>(`/inventory/shopping-list/${id}`, { method: 'DELETE' }),
  5584. clearShoppingList: () =>
  5585. request<{ deleted: number }>('/inventory/shopping-list', { method: 'DELETE' }),
  5586. updateShoppingListStatus: (id: number, status: 'pending' | 'purchased' | 'received') =>
  5587. request<ShoppingListItem>(`/inventory/shopping-list/${id}/status`, {
  5588. method: 'PATCH',
  5589. body: JSON.stringify({ status }),
  5590. }),
  5591. getFilamentPresets: () =>
  5592. request<SlicerSetting[]>('/cloud/filaments'),
  5593. // Spoolman Inventory proxy (unified UI when Spoolman is enabled)
  5594. getSpoolmanInventorySpools: (includeArchived = false) =>
  5595. request<InventorySpool[]>(`/spoolman/inventory/spools?include_archived=${includeArchived}`),
  5596. getSpoolmanInventorySpool: (id: number) =>
  5597. request<InventorySpool>(`/spoolman/inventory/spools/${id}`),
  5598. createSpoolmanInventorySpool: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>) =>
  5599. request<InventorySpool>('/spoolman/inventory/spools', {
  5600. method: 'POST',
  5601. body: JSON.stringify(data),
  5602. }),
  5603. bulkCreateSpoolmanInventorySpools: (
  5604. data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>,
  5605. quantity: number,
  5606. ) =>
  5607. request<SpoolmanBulkCreateResult | InventorySpool[]>('/spoolman/inventory/spools/bulk', {
  5608. method: 'POST',
  5609. body: JSON.stringify({ spool: data, quantity }),
  5610. }),
  5611. updateSpoolmanInventorySpool: (
  5612. id: number,
  5613. data: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>,
  5614. ) =>
  5615. request<InventorySpool>(`/spoolman/inventory/spools/${id}`, {
  5616. method: 'PATCH',
  5617. body: JSON.stringify(data),
  5618. }),
  5619. deleteSpoolmanInventorySpool: (id: number) =>
  5620. request<{ status: string }>(`/spoolman/inventory/spools/${id}`, { method: 'DELETE' }),
  5621. archiveSpoolmanInventorySpool: (id: number) =>
  5622. request<InventorySpool>(`/spoolman/inventory/spools/${id}/archive`, { method: 'POST' }),
  5623. restoreSpoolmanInventorySpool: (id: number) =>
  5624. request<InventorySpool>(`/spoolman/inventory/spools/${id}/restore`, { method: 'POST' }),
  5625. resetSpoolmanInventorySpoolConsumedCounter: (id: number) =>
  5626. request<InventorySpool>(`/spoolman/inventory/spools/${id}/reset-consumed-counter`, { method: 'POST' }),
  5627. bulkResetSpoolmanInventorySpoolConsumedCounter: (spoolIds: number[]) =>
  5628. request<{ reset: number }>(`/spoolman/inventory/spools/reset-consumed-counter-bulk`, {
  5629. method: 'POST',
  5630. body: JSON.stringify({ spool_ids: spoolIds }),
  5631. }),
  5632. bulkUpdateSpoolmanInventorySpools: (ids: number[], update: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  5633. request<{ updated: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-update`, {
  5634. method: 'POST',
  5635. body: JSON.stringify({ ids, update }),
  5636. }),
  5637. bulkDeleteSpoolmanInventorySpools: (ids: number[]) =>
  5638. request<{ deleted: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-delete`, {
  5639. method: 'POST',
  5640. body: JSON.stringify({ ids }),
  5641. }),
  5642. bulkArchiveSpoolmanInventorySpools: (ids: number[]) =>
  5643. request<{ archived: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-archive`, {
  5644. method: 'POST',
  5645. body: JSON.stringify({ ids }),
  5646. }),
  5647. bulkRestoreSpoolmanInventorySpools: (ids: number[]) =>
  5648. request<{ restored: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-restore`, {
  5649. method: 'POST',
  5650. body: JSON.stringify({ ids }),
  5651. }),
  5652. linkTagToSpoolmanSpool: (spoolId: number, data: { tag_uid?: string; tray_uuid?: string }) =>
  5653. request<InventorySpool>(`/spoolman/inventory/spools/${spoolId}/tag`, {
  5654. method: 'PATCH',
  5655. body: JSON.stringify(data),
  5656. }),
  5657. syncSpoolmanSpoolWeight: (spoolId: number, weightGrams: number) =>
  5658. request<{ status: string; weight_used: number }>(`/spoolman/inventory/spools/${spoolId}/weight`, {
  5659. method: 'PATCH',
  5660. body: JSON.stringify({ weight_grams: weightGrams }),
  5661. }),
  5662. assignSpoolmanSlot: (data: { spoolman_spool_id: number; printer_id: number; ams_id: number; tray_id: number }) =>
  5663. request<InventorySpool>('/spoolman/inventory/slot-assignments', {
  5664. method: 'POST',
  5665. body: JSON.stringify(data),
  5666. }),
  5667. unassignSpoolmanSlot: (spoolmanSpoolId: number) =>
  5668. request<InventorySpool>(`/spoolman/inventory/slot-assignments/${spoolmanSpoolId}`, { method: 'DELETE' }),
  5669. getSpoolmanSlotAssignment: (printerId: number, amsId: number, trayId: number) =>
  5670. request<InventorySpool | null>(
  5671. `/spoolman/inventory/slot-assignments?printer_id=${printerId}&ams_id=${amsId}&tray_id=${trayId}`,
  5672. ),
  5673. getSpoolmanSlotAssignments: (printerId?: number) =>
  5674. request<Array<{
  5675. printer_id: number;
  5676. printer_name: string | null;
  5677. ams_id: number;
  5678. tray_id: number;
  5679. spoolman_spool_id: number;
  5680. ams_label: string | null;
  5681. }>>(
  5682. printerId !== undefined
  5683. ? `/spoolman/inventory/slot-assignments/all?printer_id=${printerId}`
  5684. : '/spoolman/inventory/slot-assignments/all',
  5685. ),
  5686. syncSpoolmanAmsWeights: () =>
  5687. request<{ synced: number; skipped: number }>('/spoolman/inventory/sync-ams-weights', { method: 'POST' }),
  5688. getSpoolmanKProfiles: (spoolId: number) =>
  5689. request<SpoolKProfile[]>(`/spoolman/inventory/spools/${spoolId}/k-profiles`),
  5690. saveSpoolmanKProfiles: (spoolId: number, profiles: SpoolKProfileInput[]) =>
  5691. request<SpoolKProfile[]>(`/spoolman/inventory/spools/${spoolId}/k-profiles`, {
  5692. method: 'PUT',
  5693. body: JSON.stringify(profiles),
  5694. }),
  5695. // Updates
  5696. getVersion: () => request<VersionInfo>('/updates/version'),
  5697. checkForUpdates: () => request<UpdateCheckResult>('/updates/check'),
  5698. applyUpdate: () =>
  5699. request<{ success: boolean; message: string; status?: UpdateStatus; is_docker?: boolean; is_ha_addon?: boolean; is_windows_installer?: boolean }>('/updates/apply', {
  5700. method: 'POST',
  5701. }),
  5702. getUpdateStatus: () => request<UpdateStatus>('/updates/status'),
  5703. // Maintenance
  5704. getMaintenanceTypes: () => request<MaintenanceType[]>('/maintenance/types'),
  5705. createMaintenanceType: (data: MaintenanceTypeCreate) =>
  5706. request<MaintenanceType>('/maintenance/types', {
  5707. method: 'POST',
  5708. body: JSON.stringify(data),
  5709. }),
  5710. updateMaintenanceType: (id: number, data: Partial<MaintenanceTypeCreate>) =>
  5711. request<MaintenanceType>(`/maintenance/types/${id}`, {
  5712. method: 'PATCH',
  5713. body: JSON.stringify(data),
  5714. }),
  5715. deleteMaintenanceType: (id: number) =>
  5716. request<{ status: string }>(`/maintenance/types/${id}`, { method: 'DELETE' }),
  5717. restoreDefaultMaintenanceTypes: () =>
  5718. request<{ restored: number }>(`/maintenance/types/restore-defaults`, { method: 'POST' }),
  5719. getMaintenanceOverview: () => request<PrinterMaintenanceOverview[]>('/maintenance/overview'),
  5720. getPrinterMaintenance: (printerId: number) =>
  5721. request<PrinterMaintenanceOverview>(`/maintenance/printers/${printerId}`),
  5722. updateMaintenanceItem: (itemId: number, data: { custom_interval_hours?: number | null; custom_interval_type?: 'hours' | 'days' | null; enabled?: boolean }) =>
  5723. request<MaintenanceStatus>(`/maintenance/items/${itemId}`, {
  5724. method: 'PATCH',
  5725. body: JSON.stringify(data),
  5726. }),
  5727. performMaintenance: (itemId: number, notes?: string) =>
  5728. request<MaintenanceStatus>(`/maintenance/items/${itemId}/perform`, {
  5729. method: 'POST',
  5730. body: JSON.stringify({ notes }),
  5731. }),
  5732. getMaintenanceHistory: (itemId: number) =>
  5733. request<MaintenanceHistory[]>(`/maintenance/items/${itemId}/history`),
  5734. getMaintenanceSummary: () => request<MaintenanceSummary>('/maintenance/summary'),
  5735. setPrinterHours: (printerId: number, totalHours: number) =>
  5736. request<{ printer_id: number; total_hours: number; archive_hours: number; offset_hours: number }>(
  5737. `/maintenance/printers/${printerId}/hours?total_hours=${totalHours}`,
  5738. { method: 'PATCH' }
  5739. ),
  5740. assignMaintenanceType: (printerId: number, typeId: number) =>
  5741. request<MaintenanceStatus>(`/maintenance/printers/${printerId}/assign/${typeId}`, {
  5742. method: 'POST',
  5743. }),
  5744. removeMaintenanceItem: (itemId: number) =>
  5745. request<{ status: string }>(`/maintenance/items/${itemId}`, {
  5746. method: 'DELETE',
  5747. }),
  5748. // Camera
  5749. getCameraStreamToken: () =>
  5750. request<{ token: string }>('/printers/camera/stream-token', { method: 'POST' }),
  5751. // WebSocket auth (GHSA-r2qv follow-up) — mint a short-lived token for
  5752. // the /ws connection. Browsers can't attach Authorization headers to a
  5753. // WebSocket handshake, so the token rides in the ?token= query param.
  5754. getWebSocketToken: () =>
  5755. request<{ token: string }>('/auth/ws-token', { method: 'POST' }),
  5756. // Long-lived camera tokens (#1108, #2531)
  5757. createLongLivedCameraToken: (payload: {
  5758. name: string;
  5759. expires_in_days: number;
  5760. scope?: LongLivedTokenScope;
  5761. }) =>
  5762. request<LongLivedCameraToken>('/auth/tokens', {
  5763. method: 'POST',
  5764. body: JSON.stringify({ scope: 'camera_stream', ...payload }),
  5765. }),
  5766. listMyLongLivedCameraTokens: () =>
  5767. request<LongLivedCameraToken[]>('/auth/tokens'),
  5768. listAllLongLivedCameraTokens: () =>
  5769. request<LongLivedCameraToken[]>('/auth/tokens/all'),
  5770. listLongLivedCameraTokensForUser: (userId: number) =>
  5771. request<LongLivedCameraToken[]>(`/auth/tokens?user_id=${userId}`),
  5772. revokeLongLivedCameraToken: (tokenId: number) =>
  5773. request<void>(`/auth/tokens/${tokenId}`, { method: 'DELETE' }),
  5774. // Token-authenticated Cam Wall feed (#2531). `token` is omitted only when
  5775. // auth is disabled, where the backend gate is a no-op anyway.
  5776. getCamWallPrinters: (token?: string) =>
  5777. request<CamWallPrinter[]>(
  5778. token ? `/camwall/printers?token=${encodeURIComponent(token)}` : '/camwall/printers',
  5779. ),
  5780. // Token-authenticated streaming-overlay feed (#2613). OBS (or any embed with
  5781. // no login session) loads /overlay/{id}?token=... and this backs it. `token`
  5782. // is omitted only when auth is disabled, where the backend gate is a no-op.
  5783. getOverlayStatus: (printerId: number, token?: string) =>
  5784. request<OverlayStatus>(
  5785. token
  5786. ? `/printers/${printerId}/overlay-status?token=${encodeURIComponent(token)}`
  5787. : `/printers/${printerId}/overlay-status`,
  5788. ),
  5789. getCameraStreamUrl: (printerId: number, fps = 10) =>
  5790. withStreamToken(`${API_BASE}/printers/${printerId}/camera/stream?fps=${fps}`),
  5791. getCameraSnapshotUrl: (printerId: number) =>
  5792. withStreamToken(`${API_BASE}/printers/${printerId}/camera/snapshot`),
  5793. testCameraConnection: (printerId: number) =>
  5794. request<{ success: boolean; message?: string; error?: string }>(`/printers/${printerId}/camera/test`),
  5795. getCameraStatus: (printerId: number) =>
  5796. request<{ active: boolean; stalled: boolean }>(`/printers/${printerId}/camera/status`),
  5797. diagnoseCamera: (printerId: number) =>
  5798. request<CameraDiagnoseResult>(`/printers/${printerId}/camera/diagnose`, { method: 'POST' }),
  5799. diagnosePrinter: (printerId: number) =>
  5800. request<PrinterDiagnosticResult>(`/printers/${printerId}/diagnostic`),
  5801. diagnoseConnection: (body: {
  5802. ip_address: string;
  5803. serial_number?: string;
  5804. access_code?: string;
  5805. }) =>
  5806. request<PrinterDiagnosticResult>('/printers/diagnostic', {
  5807. method: 'POST',
  5808. body: JSON.stringify(body),
  5809. }),
  5810. // Plate Detection - Multi-reference calibration (stores up to 5 references per printer)
  5811. checkPlateEmpty: (printerId: number, options?: { useExternal?: boolean; includeDebugImage?: boolean }) => {
  5812. const params = new URLSearchParams();
  5813. // Only forward use_external when the caller explicitly sets it. Omitted →
  5814. // backend derives the default from the printer's external_camera_enabled
  5815. // setting so calibration and runtime checks use the same camera (#1359).
  5816. if (options?.useExternal !== undefined) {
  5817. params.set('use_external', String(options.useExternal));
  5818. }
  5819. params.set('include_debug_image', String(options?.includeDebugImage ?? false));
  5820. return request<PlateDetectionResult>(
  5821. `/printers/${printerId}/camera/check-plate?${params.toString()}`
  5822. );
  5823. },
  5824. getPlateDetectionStatus: (printerId: number) => {
  5825. return request<PlateDetectionStatus & { chamber_light?: boolean }>(
  5826. `/printers/${printerId}/camera/plate-detection/status`
  5827. );
  5828. },
  5829. calibratePlateDetection: (printerId: number, options?: { label?: string; useExternal?: boolean }) => {
  5830. const params = new URLSearchParams();
  5831. if (options?.label) params.set('label', options.label);
  5832. if (options?.useExternal !== undefined) {
  5833. params.set('use_external', String(options.useExternal));
  5834. }
  5835. return request<CalibrationResult & { index: number }>(
  5836. `/printers/${printerId}/camera/plate-detection/calibrate?${params.toString()}`,
  5837. { method: 'POST' }
  5838. );
  5839. },
  5840. deletePlateCalibration: (printerId: number) => {
  5841. return request<CalibrationResult>(
  5842. `/printers/${printerId}/camera/plate-detection/calibrate`,
  5843. { method: 'DELETE' }
  5844. );
  5845. },
  5846. getPlateReferences: (printerId: number) => {
  5847. return request<{
  5848. references: PlateReference[];
  5849. max_references: number;
  5850. }>(`/printers/${printerId}/camera/plate-detection/references`);
  5851. },
  5852. getPlateReferenceThumbnailUrl: (printerId: number, index: number) =>
  5853. withStreamToken(`${API_BASE}/printers/${printerId}/camera/plate-detection/references/${index}/thumbnail`),
  5854. updatePlateReferenceLabel: (printerId: number, index: number, label: string) => {
  5855. const params = new URLSearchParams();
  5856. params.set('label', label);
  5857. return request<{ success: boolean; index: number; label: string }>(
  5858. `/printers/${printerId}/camera/plate-detection/references/${index}?${params.toString()}`,
  5859. { method: 'PUT' }
  5860. );
  5861. },
  5862. deletePlateReference: (printerId: number, index: number) => {
  5863. return request<{ success: boolean; message: string }>(
  5864. `/printers/${printerId}/camera/plate-detection/references/${index}`,
  5865. { method: 'DELETE' }
  5866. );
  5867. },
  5868. // External Links
  5869. getExternalLinks: () => request<ExternalLink[]>('/external-links/'),
  5870. getExternalLink: (id: number) => request<ExternalLink>(`/external-links/${id}`),
  5871. createExternalLink: (data: ExternalLinkCreate) =>
  5872. request<ExternalLink>('/external-links/', {
  5873. method: 'POST',
  5874. body: JSON.stringify(data),
  5875. }),
  5876. updateExternalLink: (id: number, data: ExternalLinkUpdate) =>
  5877. request<ExternalLink>(`/external-links/${id}`, {
  5878. method: 'PATCH',
  5879. body: JSON.stringify(data),
  5880. }),
  5881. deleteExternalLink: (id: number) =>
  5882. request<{ message: string }>(`/external-links/${id}`, { method: 'DELETE' }),
  5883. reorderExternalLinks: (ids: number[]) =>
  5884. request<ExternalLink[]>('/external-links/reorder', {
  5885. method: 'PUT',
  5886. body: JSON.stringify({ ids }),
  5887. }),
  5888. uploadExternalLinkIcon: async (id: number, file: File): Promise<ExternalLink> => {
  5889. const formData = new FormData();
  5890. formData.append('file', file);
  5891. const headers: Record<string, string> = {};
  5892. if (authToken) {
  5893. headers['Authorization'] = `Bearer ${authToken}`;
  5894. }
  5895. const response = await fetch(`${API_BASE}/external-links/${id}/icon`, {
  5896. method: 'POST',
  5897. headers,
  5898. body: formData,
  5899. });
  5900. if (!response.ok) {
  5901. const error = await response.json().catch(() => ({}));
  5902. throw new Error(error.detail || `HTTP ${response.status}`);
  5903. }
  5904. return response.json();
  5905. },
  5906. deleteExternalLinkIcon: (id: number) =>
  5907. request<ExternalLink>(`/external-links/${id}/icon`, { method: 'DELETE' }),
  5908. getExternalLinkIconUrl: (id: number) => withStreamToken(`${API_BASE}/external-links/${id}/icon`),
  5909. // Projects
  5910. getProjects: (status?: string) => {
  5911. const params = new URLSearchParams();
  5912. if (status) params.set('status', status);
  5913. return request<ProjectListItem[]>(`/projects/?${params}`);
  5914. },
  5915. getProject: (id: number) => request<Project>(`/projects/${id}`),
  5916. createProject: (data: ProjectCreate) =>
  5917. request<Project>('/projects/', {
  5918. method: 'POST',
  5919. body: JSON.stringify(data),
  5920. }),
  5921. updateProject: (id: number, data: ProjectUpdate) =>
  5922. request<Project>(`/projects/${id}`, {
  5923. method: 'PATCH',
  5924. body: JSON.stringify(data),
  5925. }),
  5926. deleteProject: (id: number) =>
  5927. request<{ message: string }>(`/projects/${id}`, { method: 'DELETE' }),
  5928. getProjectArchives: (id: number, limit = 100, offset = 0) =>
  5929. request<Archive[]>(`/projects/${id}/archives?limit=${limit}&offset=${offset}`),
  5930. // Completed-run counts per library file (#1897); files with 0 runs are omitted
  5931. getProjectFileProgress: (id: number) =>
  5932. request<ProjectFileProgress[]>(`/projects/${id}/file-progress`),
  5933. addArchivesToProject: (projectId: number, archiveIds: number[]) =>
  5934. request<{ message: string }>(`/projects/${projectId}/add-archives`, {
  5935. method: 'POST',
  5936. body: JSON.stringify({ archive_ids: archiveIds }),
  5937. }),
  5938. removeArchivesFromProject: (projectId: number, archiveIds: number[]) =>
  5939. request<{ message: string }>(`/projects/${projectId}/remove-archives`, {
  5940. method: 'POST',
  5941. body: JSON.stringify({ archive_ids: archiveIds }),
  5942. }),
  5943. addQueueItemsToProject: (projectId: number, queueItemIds: number[]) =>
  5944. request<{ message: string }>(`/projects/${projectId}/add-queue`, {
  5945. method: 'POST',
  5946. body: JSON.stringify({ queue_item_ids: queueItemIds }),
  5947. }),
  5948. // Project Attachments
  5949. uploadProjectAttachment: async (projectId: number, file: File): Promise<{
  5950. status: string;
  5951. filename: string;
  5952. original_name: string;
  5953. attachments: ProjectAttachment[];
  5954. }> => {
  5955. const formData = new FormData();
  5956. formData.append('file', file);
  5957. const headers: Record<string, string> = {};
  5958. if (authToken) {
  5959. headers['Authorization'] = `Bearer ${authToken}`;
  5960. }
  5961. const response = await fetch(`${API_BASE}/projects/${projectId}/attachments`, {
  5962. method: 'POST',
  5963. headers,
  5964. body: formData,
  5965. });
  5966. if (!response.ok) {
  5967. const error = await response.json().catch(() => ({}));
  5968. throw new Error(error.detail || `HTTP ${response.status}`);
  5969. }
  5970. return response.json();
  5971. },
  5972. getProjectAttachmentUrl: (projectId: number, filename: string) =>
  5973. `${API_BASE}/projects/${projectId}/attachments/${encodeURIComponent(filename)}`,
  5974. deleteProjectAttachment: (projectId: number, filename: string) =>
  5975. request<{ status: string; message: string; attachments: ProjectAttachment[] | null }>(
  5976. `/projects/${projectId}/attachments/${encodeURIComponent(filename)}`,
  5977. { method: 'DELETE' }
  5978. ),
  5979. // #1155: Cover image
  5980. // Browsers can't attach `Authorization: Bearer ...` to `<img src>`, so we
  5981. // append the stream-token query string the same way archive thumbnails do.
  5982. getProjectCoverImageUrl: (projectId: number) =>
  5983. withStreamToken(`${API_BASE}/projects/${projectId}/cover-image`),
  5984. uploadProjectCoverImage: async (
  5985. projectId: number,
  5986. file: File
  5987. ): Promise<{ status: string; filename: string; size: number }> => {
  5988. const formData = new FormData();
  5989. formData.append('file', file);
  5990. const headers: Record<string, string> = {};
  5991. if (authToken) {
  5992. headers['Authorization'] = `Bearer ${authToken}`;
  5993. }
  5994. const response = await fetch(`${API_BASE}/projects/${projectId}/cover-image`, {
  5995. method: 'POST',
  5996. headers,
  5997. body: formData,
  5998. });
  5999. if (!response.ok) {
  6000. const error = await response.json().catch(() => ({}));
  6001. throw new Error(error.detail || `HTTP ${response.status}`);
  6002. }
  6003. return response.json();
  6004. },
  6005. deleteProjectCoverImage: (projectId: number) =>
  6006. request<{ status: string }>(`/projects/${projectId}/cover-image`, { method: 'DELETE' }),
  6007. // BOM (Bill of Materials)
  6008. getProjectBOM: (projectId: number) =>
  6009. request<BOMItem[]>(`/projects/${projectId}/bom`),
  6010. createBOMItem: (projectId: number, data: BOMItemCreate) =>
  6011. request<BOMItem>(`/projects/${projectId}/bom`, {
  6012. method: 'POST',
  6013. body: JSON.stringify(data),
  6014. }),
  6015. updateBOMItem: (projectId: number, itemId: number, data: BOMItemUpdate) =>
  6016. request<BOMItem>(`/projects/${projectId}/bom/${itemId}`, {
  6017. method: 'PATCH',
  6018. body: JSON.stringify(data),
  6019. }),
  6020. deleteBOMItem: (projectId: number, itemId: number) =>
  6021. request<{ status: string; message: string }>(`/projects/${projectId}/bom/${itemId}`, {
  6022. method: 'DELETE',
  6023. }),
  6024. // Templates
  6025. getTemplates: () => request<ProjectListItem[]>('/projects/templates/'),
  6026. createTemplateFromProject: (projectId: number) =>
  6027. request<Project>(`/projects/${projectId}/create-template`, { method: 'POST' }),
  6028. createProjectFromTemplate: (templateId: number, name?: string) =>
  6029. request<Project>(`/projects/from-template/${templateId}${name ? `?name=${encodeURIComponent(name)}` : ''}`, {
  6030. method: 'POST',
  6031. }),
  6032. // Timeline
  6033. getProjectTimeline: (projectId: number, limit = 50) =>
  6034. request<TimelineEvent[]>(`/projects/${projectId}/timeline?limit=${limit}`),
  6035. // Project Export/Import
  6036. exportProjectJson: (projectId: number) =>
  6037. request<ProjectExport>(`/projects/${projectId}/export?format=json`),
  6038. importProject: (data: ProjectImport) =>
  6039. request<Project>('/projects/import', {
  6040. method: 'POST',
  6041. body: JSON.stringify(data),
  6042. }),
  6043. importProjectFile: async (file: File): Promise<Project> => {
  6044. const formData = new FormData();
  6045. formData.append('file', file);
  6046. const headers: Record<string, string> = {};
  6047. if (authToken) {
  6048. headers['Authorization'] = `Bearer ${authToken}`;
  6049. }
  6050. const response = await fetch(`${API_BASE}/projects/import/file`, {
  6051. method: 'POST',
  6052. headers,
  6053. body: formData,
  6054. });
  6055. if (!response.ok) {
  6056. const error = await response.json().catch(() => ({}));
  6057. throw new Error(error.detail || `HTTP ${response.status}`);
  6058. }
  6059. return response.json();
  6060. },
  6061. exportProjectZip: async (projectId: number): Promise<{ blob: Blob; filename: string }> => {
  6062. const headers: Record<string, string> = {};
  6063. if (authToken) {
  6064. headers['Authorization'] = `Bearer ${authToken}`;
  6065. }
  6066. const response = await fetch(`${API_BASE}/projects/${projectId}/export`, {
  6067. headers,
  6068. });
  6069. if (!response.ok) {
  6070. const error = await response.json().catch(() => ({}));
  6071. throw new Error(error.detail || `HTTP ${response.status}`);
  6072. }
  6073. const contentDisposition = response.headers.get('Content-Disposition');
  6074. const filename = parseContentDispositionFilename(contentDisposition) || `project_${projectId}.zip`;
  6075. const blob = await response.blob();
  6076. return { blob, filename };
  6077. },
  6078. // API Keys
  6079. getAPIKeys: () => request<APIKey[]>('/api-keys/'),
  6080. createAPIKey: (data: APIKeyCreate) =>
  6081. request<APIKeyCreateResponse>('/api-keys/', {
  6082. method: 'POST',
  6083. body: JSON.stringify(data),
  6084. }),
  6085. updateAPIKey: (id: number, data: APIKeyUpdate) =>
  6086. request<APIKey>(`/api-keys/${id}`, {
  6087. method: 'PATCH',
  6088. body: JSON.stringify(data),
  6089. }),
  6090. deleteAPIKey: (id: number) =>
  6091. request<{ message: string }>(`/api-keys/${id}`, { method: 'DELETE' }),
  6092. // AMS History
  6093. getAMSHistory: (printerId: number, amsId: number, hours = 24) =>
  6094. request<AMSHistoryResponse>(`/ams-history/${printerId}/${amsId}?hours=${hours}`),
  6095. // Printer heater (nozzle / bed / chamber) sensor history
  6096. getPrinterSensorHistory: (printerId: number, hours = 24, kinds?: string[]) => {
  6097. const params = new URLSearchParams({ hours: String(hours) });
  6098. if (kinds && kinds.length > 0) params.set('kinds', kinds.join(','));
  6099. return request<PrinterSensorHistoryResponse>(`/printer-sensor-history/${printerId}?${params.toString()}`);
  6100. },
  6101. // System Info
  6102. getSystemInfo: () => request<SystemInfo>('/system/info'),
  6103. getSystemHealth: () => request<SystemHealthResult>('/system/health'),
  6104. getStorageUsage: (options?: { refresh?: boolean }) => {
  6105. const params = new URLSearchParams();
  6106. if (options?.refresh) {
  6107. params.set('refresh', 'true');
  6108. }
  6109. const query = params.toString();
  6110. return request<StorageUsageResponse>(`/system/storage-usage${query ? `?${query}` : ''}`);
  6111. },
  6112. // Library (File Manager)
  6113. getLibraryFolders: () => request<LibraryFolderTree[]>('/library/folders'),
  6114. createLibraryFolder: (data: LibraryFolderCreate) =>
  6115. request<LibraryFolder>('/library/folders', {
  6116. method: 'POST',
  6117. body: JSON.stringify(data),
  6118. }),
  6119. updateLibraryFolder: (id: number, data: LibraryFolderUpdate) =>
  6120. request<LibraryFolder>(`/library/folders/${id}`, {
  6121. method: 'PUT',
  6122. body: JSON.stringify(data),
  6123. }),
  6124. deleteLibraryFolder: (id: number) =>
  6125. request<{ status: string; message: string }>(`/library/folders/${id}`, { method: 'DELETE' }),
  6126. createExternalFolder: (data: ExternalFolderCreate) =>
  6127. request<LibraryFolder>('/library/folders/external', {
  6128. method: 'POST',
  6129. body: JSON.stringify(data),
  6130. }),
  6131. scanExternalFolder: (folderId: number) =>
  6132. request<{ status: string; added: number; removed: number }>(`/library/folders/${folderId}/scan`, {
  6133. method: 'POST',
  6134. }),
  6135. getLibraryFoldersByProject: (projectId: number) =>
  6136. request<LibraryFolder[]>(`/library/folders/by-project/${projectId}`),
  6137. getLibraryFoldersByArchive: (archiveId: number) =>
  6138. request<LibraryFolder[]>(`/library/folders/by-archive/${archiveId}`),
  6139. getLibraryFiles: (
  6140. folderId?: number | null,
  6141. includeRoot = true,
  6142. projectId?: number,
  6143. scope?: 'internal' | 'external',
  6144. recursive = false,
  6145. tagIds: number[] = [],
  6146. ) => {
  6147. const params = new URLSearchParams();
  6148. if (folderId !== undefined && folderId !== null) {
  6149. params.set('folder_id', String(folderId));
  6150. }
  6151. if (projectId !== undefined) {
  6152. params.set('project_id', String(projectId));
  6153. }
  6154. params.set('include_root', String(includeRoot));
  6155. if (scope === 'internal') params.set('internal_only', 'true');
  6156. else if (scope === 'external') params.set('external_only', 'true');
  6157. // recursive=true expands the folder_id filter to include every descendant
  6158. // folder (#1268). Only meaningful when folder_id is set; ignored server-side
  6159. // otherwise. Off by default so non-search callers keep folder-scoped behavior.
  6160. if (recursive) params.set('recursive', 'true');
  6161. // Tag filter (#1268). Repeated ?tag_ids=N&tag_ids=M form for AND semantics
  6162. // — backend joins the association table and HAVING COUNT(DISTINCT) matches
  6163. // the array length. Tag filter intentionally bypasses folder scoping
  6164. // server-side (cross-cutting design decision).
  6165. for (const tagId of tagIds) {
  6166. params.append('tag_ids', String(tagId));
  6167. }
  6168. return request<LibraryFileListItem[]>(`/library/files?${params}`);
  6169. },
  6170. getLibraryFolderReadme: (folderId: number) =>
  6171. request<{ filename: string; content: string; truncated: boolean }>(
  6172. `/library/folders/${folderId}/readme`,
  6173. ),
  6174. // ============ Library tag catalog (#1268) ============
  6175. getLibraryTags: () =>
  6176. request<LibraryTag[]>('/library/tags'),
  6177. createLibraryTag: (name: string) =>
  6178. request<LibraryTag>('/library/tags', {
  6179. method: 'POST',
  6180. body: JSON.stringify({ name }),
  6181. }),
  6182. updateLibraryTag: (id: number, name: string) =>
  6183. request<LibraryTag>(`/library/tags/${id}`, {
  6184. method: 'PATCH',
  6185. body: JSON.stringify({ name }),
  6186. }),
  6187. deleteLibraryTag: (id: number) =>
  6188. request<void>(`/library/tags/${id}`, { method: 'DELETE' }),
  6189. bulkAssignLibraryTags: (
  6190. fileIds: number[],
  6191. tagIds: number[],
  6192. action: 'add' | 'remove' | 'replace',
  6193. ) =>
  6194. request<LibraryTagBulkAssignResult>('/library/tags/bulk-assign', {
  6195. method: 'POST',
  6196. body: JSON.stringify({ file_ids: fileIds, tag_ids: tagIds, action }),
  6197. }),
  6198. // ============ Variant groups (#671 / #2570) ============
  6199. // "These files are the same job sliced for different printers." Consumed from
  6200. // both ends: the queue picks a printer and needs the matching file, the File
  6201. // Manager's print action has the printer and needs the same match.
  6202. createVariantGroup: (
  6203. members: { library_file_id: number; target_model?: string }[],
  6204. name?: string,
  6205. ) =>
  6206. request<VariantGroup>('/library/variant-groups', {
  6207. method: 'POST',
  6208. body: JSON.stringify({ members, ...(name ? { name } : {}) }),
  6209. }),
  6210. getVariantGroup: (groupId: number) =>
  6211. request<VariantGroup>(`/library/variant-groups/${groupId}`),
  6212. /** Returns null when the file is not grouped, rather than throwing on the 404. */
  6213. getVariantGroupForFile: async (fileId: number): Promise<VariantGroup | null> => {
  6214. try {
  6215. return await request<VariantGroup>(`/library/variant-groups/by-file/${fileId}`);
  6216. } catch {
  6217. return null;
  6218. }
  6219. },
  6220. updateVariantGroup: (groupId: number, body: { name?: string; member_file_ids?: number[] }) =>
  6221. request<VariantGroup>(`/library/variant-groups/${groupId}`, {
  6222. method: 'PATCH',
  6223. body: JSON.stringify(body),
  6224. }),
  6225. addVariantGroupMember: (
  6226. groupId: number,
  6227. libraryFileId: number,
  6228. targetModel?: string,
  6229. ) =>
  6230. request<VariantGroup>(`/library/variant-groups/${groupId}/members`, {
  6231. method: 'POST',
  6232. body: JSON.stringify({
  6233. library_file_id: libraryFileId,
  6234. ...(targetModel ? { target_model: targetModel } : {}),
  6235. }),
  6236. }),
  6237. removeVariantGroupMember: (groupId: number, fileId: number) =>
  6238. request<void>(`/library/variant-groups/${groupId}/members/${fileId}`, { method: 'DELETE' }),
  6239. deleteVariantGroup: (groupId: number) =>
  6240. request<void>(`/library/variant-groups/${groupId}`, { method: 'DELETE' }),
  6241. getLibraryFile: (id: number) => request<LibraryFile>(`/library/files/${id}`),
  6242. uploadLibraryFile: async (
  6243. file: File,
  6244. folderId?: number | null,
  6245. generateStlThumbnails: boolean = true
  6246. ): Promise<LibraryFileUploadResponse> => {
  6247. const formData = new FormData();
  6248. formData.append('file', file);
  6249. const params = new URLSearchParams();
  6250. if (folderId) params.set('folder_id', String(folderId));
  6251. params.set('generate_stl_thumbnails', String(generateStlThumbnails));
  6252. const headers: Record<string, string> = {};
  6253. if (authToken) {
  6254. headers['Authorization'] = `Bearer ${authToken}`;
  6255. }
  6256. const response = await fetch(`${API_BASE}/library/files?${params}`, {
  6257. method: 'POST',
  6258. headers,
  6259. body: formData,
  6260. });
  6261. if (!response.ok) {
  6262. const error = await response.json().catch(() => ({}));
  6263. throw new Error(error.detail || `HTTP ${response.status}`);
  6264. }
  6265. return response.json();
  6266. },
  6267. extractZipFile: async (
  6268. file: File,
  6269. folderId?: number | null,
  6270. preserveStructure: boolean = true,
  6271. createFolderFromZip: boolean = false,
  6272. generateStlThumbnails: boolean = true
  6273. ): Promise<ZipExtractResponse> => {
  6274. const formData = new FormData();
  6275. formData.append('file', file);
  6276. const params = new URLSearchParams();
  6277. if (folderId) params.set('folder_id', String(folderId));
  6278. params.set('preserve_structure', String(preserveStructure));
  6279. params.set('create_folder_from_zip', String(createFolderFromZip));
  6280. params.set('generate_stl_thumbnails', String(generateStlThumbnails));
  6281. const headers: Record<string, string> = {};
  6282. if (authToken) {
  6283. headers['Authorization'] = `Bearer ${authToken}`;
  6284. }
  6285. const response = await fetch(`${API_BASE}/library/files/extract-zip?${params}`, {
  6286. method: 'POST',
  6287. headers,
  6288. body: formData,
  6289. });
  6290. if (!response.ok) {
  6291. const error = await response.json().catch(() => ({}));
  6292. throw new Error(error.detail || `HTTP ${response.status}`);
  6293. }
  6294. return response.json();
  6295. },
  6296. updateLibraryFile: (id: number, data: LibraryFileUpdate) =>
  6297. request<LibraryFile>(`/library/files/${id}`, {
  6298. method: 'PUT',
  6299. body: JSON.stringify(data),
  6300. }),
  6301. deleteLibraryFile: (id: number) =>
  6302. request<{ status: string; message: string; trashed: boolean }>(`/library/files/${id}`, { method: 'DELETE' }),
  6303. // ========== Library Trash (#1008) ==========
  6304. previewLibraryPurge: (olderThanDays: number, includeNeverPrinted: boolean = true) =>
  6305. request<LibraryPurgePreview>(
  6306. `/library/purge/preview?older_than_days=${olderThanDays}&include_never_printed=${includeNeverPrinted}`,
  6307. ),
  6308. executeLibraryPurge: (olderThanDays: number, includeNeverPrinted: boolean = true) =>
  6309. request<{ moved_to_trash: number }>('/library/purge', {
  6310. method: 'POST',
  6311. body: JSON.stringify({ older_than_days: olderThanDays, include_never_printed: includeNeverPrinted }),
  6312. }),
  6313. listLibraryTrash: (limit: number = 100, offset: number = 0) =>
  6314. request<LibraryTrashListResponse>(`/library/trash?limit=${limit}&offset=${offset}`),
  6315. restoreLibraryTrash: (fileId: number) =>
  6316. request<{ status: string; id: number }>(`/library/trash/${fileId}/restore`, { method: 'POST' }),
  6317. hardDeleteLibraryTrash: (fileId: number) =>
  6318. request<{ status: string }>(`/library/trash/${fileId}`, { method: 'DELETE' }),
  6319. emptyLibraryTrash: () => request<{ deleted: number }>('/library/trash', { method: 'DELETE' }),
  6320. getLibraryTrashSettings: () =>
  6321. request<LibraryTrashSettings>('/library/trash/settings'),
  6322. updateLibraryTrashSettings: (body: LibraryTrashSettings) =>
  6323. request<LibraryTrashSettings>('/library/trash/settings', {
  6324. method: 'PUT',
  6325. body: JSON.stringify(body),
  6326. }),
  6327. getLibraryFileDownloadUrl: (id: number) => `${API_BASE}/library/files/${id}/download`,
  6328. createLibrarySlicerToken: (fileId: number) =>
  6329. request<{ token: string }>(`/library/files/${fileId}/slicer-token`, { method: 'POST' }),
  6330. getLibrarySlicerDownloadUrl: (fileId: number, token: string, filename: string) =>
  6331. `${API_BASE}/library/files/${fileId}/dl/${token}/${encodeURIComponent(buildSlicerUrlFilename(filename))}`,
  6332. downloadLibraryFile: async (id: number, filename?: string): Promise<void> => {
  6333. const headers: Record<string, string> = {};
  6334. if (authToken) {
  6335. headers['Authorization'] = `Bearer ${authToken}`;
  6336. }
  6337. const response = await fetch(`${API_BASE}/library/files/${id}/download`, { headers });
  6338. if (!response.ok) {
  6339. const error = await response.json().catch(() => ({}));
  6340. throw new Error(error.detail || `HTTP ${response.status}`);
  6341. }
  6342. const disposition = response.headers.get('Content-Disposition');
  6343. const downloadFilename = parseContentDispositionFilename(disposition) || filename || `file_${id}`;
  6344. const blob = await response.blob();
  6345. const url = window.URL.createObjectURL(blob);
  6346. const a = document.createElement('a');
  6347. a.href = url;
  6348. a.download = downloadFilename;
  6349. document.body.appendChild(a);
  6350. a.click();
  6351. document.body.removeChild(a);
  6352. window.URL.revokeObjectURL(url);
  6353. },
  6354. getLibraryFileThumbnailUrl: (id: number) => withStreamToken(`${API_BASE}/library/files/${id}/thumbnail`),
  6355. getLibraryFilePlateThumbnail: (id: number, plateIndex: number) =>
  6356. withStreamToken(`${API_BASE}/library/files/${id}/plate-thumbnail/${plateIndex}`),
  6357. getLibraryFileGcodeUrl: (id: number) => `${API_BASE}/library/files/${id}/gcode`,
  6358. moveLibraryFiles: (fileIds: number[], folderId: number | null) =>
  6359. request<{ status: string; moved: number }>('/library/files/move', {
  6360. method: 'POST',
  6361. body: JSON.stringify({ file_ids: fileIds, folder_id: folderId }),
  6362. }),
  6363. bulkDeleteLibrary: (fileIds: number[], folderIds: number[]) =>
  6364. request<{ deleted_files: number; deleted_folders: number }>('/library/bulk-delete', {
  6365. method: 'POST',
  6366. body: JSON.stringify({ file_ids: fileIds, folder_ids: folderIds }),
  6367. }),
  6368. getLibraryStats: () => request<LibraryStats>('/library/stats'),
  6369. batchGenerateStlThumbnails: (options: {
  6370. file_ids?: number[];
  6371. folder_id?: number;
  6372. all_missing?: boolean;
  6373. }) =>
  6374. request<BatchThumbnailResponse>('/library/generate-stl-thumbnails', {
  6375. method: 'POST',
  6376. body: JSON.stringify(options),
  6377. }),
  6378. addLibraryFilesToQueue: (fileIds: number[]) =>
  6379. request<AddToQueueResponse>('/library/files/add-to-queue', {
  6380. method: 'POST',
  6381. body: JSON.stringify({ file_ids: fileIds }),
  6382. }),
  6383. getLibraryFilePlates: (fileId: number) =>
  6384. request<LibraryFilePlatesResponse>(`/library/files/${fileId}/plates`),
  6385. getLibraryFileFilamentRequirements: (
  6386. fileId: number,
  6387. plateId?: number,
  6388. requestId?: string,
  6389. /** Ask for one entry per project slot instead of only the slots this
  6390. * plate consumes. The slice modal needs it: its filament list is
  6391. * positional, so a source whose only used slot is 4 must still present
  6392. * four rows or the user's pick is bound to slot 1 (#2712). Print-time
  6393. * AMS matching must NOT set this — it wants the used-only list. */
  6394. fullSlots?: boolean,
  6395. ) => {
  6396. const qs = new URLSearchParams();
  6397. if (plateId !== undefined) qs.set('plate_id', String(plateId));
  6398. if (requestId) qs.set('request_id', requestId);
  6399. if (fullSlots) qs.set('full_slots', 'true');
  6400. return request<{
  6401. file_id: number;
  6402. filename: string;
  6403. filaments: Array<{
  6404. slot_id: number;
  6405. type: string;
  6406. color: string;
  6407. used_grams: number;
  6408. used_meters: number;
  6409. used_in_plate?: boolean;
  6410. }>;
  6411. }>(`/library/files/${fileId}/filament-requirements${qs.toString() ? `?${qs}` : ''}`);
  6412. },
  6413. /** Poll the sidecar's per-request progress snapshot via the Bambuddy
  6414. * proxy. Used by the SliceModal's filament-discovery path so the inline
  6415. * spinner + persistent toast can show "Generating G-code (45%)" while
  6416. * the preview slice runs. Returns null on 404 (sidecar doesn't yet
  6417. * have an entry — early race window — or it expired) so the poller
  6418. * can keep trying. */
  6419. getPreviewSliceProgress: async (requestId: string): Promise<SliceJobProgress | null> => {
  6420. try {
  6421. return await request<SliceJobProgress>(`/slicer/preview-progress/${encodeURIComponent(requestId)}`);
  6422. } catch {
  6423. return null;
  6424. }
  6425. },
  6426. // GitHub Backup
  6427. getGitHubBackupConfig: () =>
  6428. request<GitHubBackupConfig | null>('/github-backup/config'),
  6429. getGitHubBackupCloudAccounts: () =>
  6430. request<CloudAccountCounts>('/github-backup/cloud-accounts'),
  6431. saveGitHubBackupConfig: (config: GitHubBackupConfigCreate) =>
  6432. request<GitHubBackupConfig>('/github-backup/config', {
  6433. method: 'POST',
  6434. body: JSON.stringify(config),
  6435. }),
  6436. updateGitHubBackupConfig: (config: Partial<GitHubBackupConfigCreate>) =>
  6437. request<GitHubBackupConfig>('/github-backup/config', {
  6438. method: 'PATCH',
  6439. body: JSON.stringify(config),
  6440. }),
  6441. deleteGitHubBackupConfig: () =>
  6442. request<{ message: string }>('/github-backup/config', { method: 'DELETE' }),
  6443. testGitHubConnection: (repoUrl: string, token: string, provider: GitProviderType = 'github') =>
  6444. request<GitHubTestConnectionResponse>(
  6445. `/github-backup/test?repo_url=${encodeURIComponent(repoUrl)}&token=${encodeURIComponent(token)}&provider=${encodeURIComponent(provider)}`,
  6446. { method: 'POST' }
  6447. ),
  6448. testGitHubStoredConnection: () =>
  6449. request<GitHubTestConnectionResponse>('/github-backup/test-stored', { method: 'POST' }),
  6450. triggerGitHubBackup: () =>
  6451. request<GitHubBackupTriggerResponse>('/github-backup/run', { method: 'POST' }),
  6452. getGitHubBackupStatus: () =>
  6453. request<GitHubBackupStatus>('/github-backup/status'),
  6454. getGitHubBackupLogs: (limit: number = 50) =>
  6455. request<GitHubBackupLog[]>(`/github-backup/logs?limit=${limit}`),
  6456. clearGitHubBackupLogs: (keepLast: number = 10) =>
  6457. request<{ deleted: number; message: string }>(`/github-backup/logs?keep_last=${keepLast}`, { method: 'DELETE' }),
  6458. // Restore from a Git backup (#2656)
  6459. getGitHubBackupCommits: (limit: number = 20) =>
  6460. request<GitHubCommitListResponse>(`/github-backup/commits?limit=${limit}`),
  6461. getGitHubRestorePreview: (ref: string = 'HEAD') =>
  6462. request<GitHubRestorePreview>(`/github-backup/restore/preview?ref=${encodeURIComponent(ref)}`),
  6463. restoreFromGitHub: (payload: GitHubRestoreRequest) =>
  6464. request<GitHubRestoreResponse>('/github-backup/restore', {
  6465. method: 'POST',
  6466. body: JSON.stringify(payload),
  6467. }),
  6468. // Scheduled local backups
  6469. getLocalBackupStatus: () =>
  6470. request<LocalBackupStatus>('/local-backup/status'),
  6471. triggerLocalBackup: () =>
  6472. request<{ success: boolean; message: string; filename?: string }>('/local-backup/run', { method: 'POST' }),
  6473. checkLocalBackupPath: () =>
  6474. request<LocalBackupPathCheck>('/local-backup/path-check'),
  6475. getLocalBackups: () =>
  6476. request<LocalBackupFile[]>('/local-backup/backups'),
  6477. downloadLocalBackup: async (filename: string): Promise<{ blob: Blob; filename: string }> => {
  6478. const response = await fetch(`${API_BASE}/local-backup/backups/${encodeURIComponent(filename)}/download`, {
  6479. headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {},
  6480. });
  6481. if (!response.ok) throw new Error('Download failed');
  6482. const blob = await response.blob();
  6483. return { blob, filename };
  6484. },
  6485. restoreLocalBackup: (filename: string) =>
  6486. request<{ success: boolean; message: string }>(`/local-backup/backups/${encodeURIComponent(filename)}/restore`, { method: 'POST' }),
  6487. deleteLocalBackup: (filename: string) =>
  6488. request<{ success: boolean; message: string }>(`/local-backup/backups/${encodeURIComponent(filename)}`, { method: 'DELETE' }),
  6489. // Obico AI failure detection
  6490. getObicoStatus: () =>
  6491. request<ObicoStatus>('/obico/status'),
  6492. getObicoPrinterStatus: () =>
  6493. request<ObicoPrinterStatus>('/obico/printer-status'),
  6494. // `token` is sent as-is, so an empty string tests with no token at all.
  6495. // Omitting the argument makes the backend fall back to the saved token.
  6496. testObicoConnection: (url: string, token?: string) =>
  6497. request<ObicoTestConnection>('/obico/test-connection', {
  6498. method: 'POST',
  6499. body: JSON.stringify(token === undefined ? { url } : { url, token }),
  6500. }),
  6501. // Slicer API — slice in the background. Both endpoints return 202 + a
  6502. // job_id; poll /slice-jobs/{id} until status is `completed` or `failed`.
  6503. sliceLibraryFile: (fileId: number, body: SliceRequest) =>
  6504. request<SliceJobEnqueueResponse>(`/library/files/${fileId}/slice`, {
  6505. method: 'POST',
  6506. body: JSON.stringify(body),
  6507. }),
  6508. sliceArchive: (archiveId: number, body: SliceRequest) =>
  6509. request<SliceJobEnqueueResponse>(`/archives/${archiveId}/slice`, {
  6510. method: 'POST',
  6511. body: JSON.stringify(body),
  6512. }),
  6513. getSliceJob: (jobId: number) =>
  6514. request<SliceJobState>(`/slice-jobs/${jobId}`),
  6515. // Unified slicer-preset listing — cloud + local + standard, deduped by name.
  6516. // Used by the SliceModal; see UnifiedPresetsResponse for the shape and
  6517. // backend/app/api/routes/slicer_presets.py for the priority rules.
  6518. // `refresh` bypasses the in-process cloud and bundled-preset caches on the
  6519. // backend; the SliceModal's Refresh button passes true so a preset deleted
  6520. // in Bambu Studio or Bambu Handy shows up without the 5-min TTL wait.
  6521. getSlicerPresets: (options?: { refresh?: boolean }) =>
  6522. request<UnifiedPresetsResponse>(
  6523. options?.refresh ? '/slicer/presets?refresh=true' : '/slicer/presets',
  6524. ),
  6525. // Slicer Pipelines (#1425) — preset bundles the SliceModal can apply in
  6526. // one click. CRUD is gated on PIPELINES_READ / PIPELINES_WRITE.
  6527. listSlicerPipelines: () =>
  6528. request<SlicerPipelinesListResponse>('/slicer-pipelines/'),
  6529. getSlicerPipeline: (id: number) =>
  6530. request<SlicerPipeline>(`/slicer-pipelines/${id}`),
  6531. createSlicerPipeline: (data: SlicerPipelineCreateRequest) =>
  6532. request<SlicerPipeline>('/slicer-pipelines/', {
  6533. method: 'POST',
  6534. body: JSON.stringify(data),
  6535. }),
  6536. updateSlicerPipeline: (id: number, data: SlicerPipelineUpdateRequest) =>
  6537. request<SlicerPipeline>(`/slicer-pipelines/${id}`, {
  6538. method: 'PUT',
  6539. body: JSON.stringify(data),
  6540. }),
  6541. deleteSlicerPipeline: (id: number) =>
  6542. request<void>(`/slicer-pipelines/${id}`, { method: 'DELETE' }),
  6543. checkPipelineEligibility: (
  6544. pipelineId: number,
  6545. source: { kind: 'libraryFile'; id: number } | { kind: 'archive'; id: number },
  6546. ) =>
  6547. request<PipelineEligibilityReport>(`/slicer-pipelines/${pipelineId}/check-eligibility`, {
  6548. method: 'POST',
  6549. body: JSON.stringify(
  6550. source.kind === 'libraryFile'
  6551. ? { source_library_file_id: source.id }
  6552. : { source_archive_id: source.id },
  6553. ),
  6554. }),
  6555. runPipeline: (
  6556. pipelineId: number,
  6557. source: { kind: 'libraryFile'; id: number } | { kind: 'archive'; id: number },
  6558. force = false,
  6559. copies = 1,
  6560. ) =>
  6561. request<PipelineRun>(`/slicer-pipelines/${pipelineId}/run`, {
  6562. method: 'POST',
  6563. body: JSON.stringify({
  6564. ...(source.kind === 'libraryFile'
  6565. ? { source_library_file_id: source.id }
  6566. : { source_archive_id: source.id }),
  6567. force,
  6568. copies,
  6569. }),
  6570. }),
  6571. listPipelineRuns: (pipelineId: number, limit = 5) =>
  6572. request<PipelineRunListResponse>(
  6573. `/slicer-pipelines/${pipelineId}/runs?limit=${limit}`,
  6574. ),
  6575. // Dashboard list across all pipelines (#1425 PR C).
  6576. listAllPipelineRuns: (params: {
  6577. limit?: number;
  6578. offset?: number;
  6579. pipelineId?: number;
  6580. status?: string;
  6581. targetPrinterId?: number;
  6582. targetModelClass?: string;
  6583. } = {}) => {
  6584. const search = new URLSearchParams();
  6585. if (params.limit) search.set('limit', String(params.limit));
  6586. if (params.offset) search.set('offset', String(params.offset));
  6587. if (params.pipelineId) search.set('pipeline_id', String(params.pipelineId));
  6588. if (params.status) search.set('status', params.status);
  6589. if (params.targetPrinterId) search.set('target_printer_id', String(params.targetPrinterId));
  6590. if (params.targetModelClass) search.set('target_model_class', params.targetModelClass);
  6591. const q = search.toString();
  6592. return request<PipelineRunListResponse>(
  6593. `/pipeline-runs${q ? '?' + q : ''}`,
  6594. );
  6595. },
  6596. // Clear terminal pipeline runs (#1425 PR C polish). Deletes all runs in
  6597. // a terminal state (completed/failed/cancelled/partial_failure); in-flight
  6598. // runs are preserved.
  6599. clearTerminalPipelineRuns: () =>
  6600. request<{ deleted: number }>('/pipeline-runs/clear', { method: 'POST' }),
  6601. getPipelineRun: (runId: number) =>
  6602. request<PipelineRun>(`/pipeline-runs/${runId}`),
  6603. cancelPipelineRun: (runId: number) =>
  6604. request<PipelineRun>(`/pipeline-runs/${runId}/cancel`, { method: 'POST' }),
  6605. retryFailedPipelineRun: (runId: number) =>
  6606. request<PipelineRun>(`/pipeline-runs/${runId}/retry-failed`, { method: 'POST' }),
  6607. // Canonical Bambu printer-model registry — "Bambu Lab <model>" → short code.
  6608. // Single source of truth shared with backend (PRINTER_MODEL_MAP); the
  6609. // SliceModal uses this to classify cloud / standard presets by their
  6610. // `@BBL <code>` suffix against the selected printer-preset name (#1325).
  6611. getSlicerPrinterModels: () =>
  6612. request<Record<string, string>>('/slicer/printer-models'),
  6613. // Local Presets (OrcaSlicer imports)
  6614. getLocalPresets: () =>
  6615. request<LocalPresetsResponse>('/local-presets/'),
  6616. getLocalPresetDetail: (id: number) =>
  6617. request<LocalPresetDetail>(`/local-presets/${id}`),
  6618. importLocalPresets: (formData: FormData) =>
  6619. fetch(`${API_BASE}/local-presets/import`, {
  6620. method: 'POST',
  6621. headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {},
  6622. body: formData,
  6623. }).then(async (res) => {
  6624. if (!res.ok) {
  6625. const err = await res.json().catch(() => ({}));
  6626. throw new Error(err.detail || `HTTP ${res.status}`);
  6627. }
  6628. return res.json() as Promise<ImportResponse>;
  6629. }),
  6630. createLocalPreset: (data: { name: string; preset_type: string; setting: Record<string, unknown> }) =>
  6631. request<LocalPreset>('/local-presets/', {
  6632. method: 'POST',
  6633. body: JSON.stringify(data),
  6634. }),
  6635. updateLocalPreset: (id: number, data: { name?: string; setting?: Record<string, unknown> }) =>
  6636. request<LocalPreset>(`/local-presets/${id}`, {
  6637. method: 'PUT',
  6638. body: JSON.stringify(data),
  6639. }),
  6640. deleteLocalPreset: (id: number) =>
  6641. request<{ success: boolean }>(`/local-presets/${id}`, { method: 'DELETE' }),
  6642. refreshBaseProfileCache: () =>
  6643. request<{ refreshed: number; failed: number; total: number }>('/local-presets/base-cache/refresh', { method: 'POST' }),
  6644. };
  6645. // AMS History types
  6646. export interface AMSHistoryPoint {
  6647. recorded_at: string;
  6648. humidity: number | null;
  6649. humidity_raw: number | null;
  6650. temperature: number | null;
  6651. }
  6652. export interface AMSHistoryResponse {
  6653. printer_id: number;
  6654. ams_id: number;
  6655. data: AMSHistoryPoint[];
  6656. min_humidity: number | null;
  6657. max_humidity: number | null;
  6658. avg_humidity: number | null;
  6659. min_temperature: number | null;
  6660. max_temperature: number | null;
  6661. avg_temperature: number | null;
  6662. }
  6663. export type HeaterSensorKind = 'nozzle' | 'nozzle_2' | 'bed' | 'chamber';
  6664. export interface HeaterHistoryPoint {
  6665. recorded_at: string;
  6666. value: number | null;
  6667. target: number | null;
  6668. }
  6669. export interface HeaterSeries {
  6670. sensor_kind: HeaterSensorKind;
  6671. data: HeaterHistoryPoint[];
  6672. min_value: number | null;
  6673. max_value: number | null;
  6674. avg_value: number | null;
  6675. }
  6676. export interface PrinterSensorHistoryResponse {
  6677. printer_id: number;
  6678. series: HeaterSeries[];
  6679. }
  6680. // System Info types
  6681. export interface SystemInfo {
  6682. app: {
  6683. version: string;
  6684. base_dir: string;
  6685. archive_dir: string;
  6686. };
  6687. database: {
  6688. engine: string;
  6689. version: string;
  6690. archives: number;
  6691. archives_completed: number;
  6692. archives_failed: number;
  6693. archives_printing: number;
  6694. printers: number;
  6695. filaments: number;
  6696. projects: number;
  6697. smart_plugs: number;
  6698. total_print_time_seconds: number;
  6699. total_print_time_formatted: string;
  6700. total_filament_grams: number;
  6701. total_filament_kg: number;
  6702. };
  6703. printers: {
  6704. total: number;
  6705. connected: number;
  6706. connected_list: Array<{
  6707. id: number;
  6708. name: string;
  6709. state: string;
  6710. model: string;
  6711. }>;
  6712. };
  6713. storage: {
  6714. archive_size_bytes: number;
  6715. archive_size_formatted: string;
  6716. database_size_bytes: number;
  6717. database_size_formatted: string;
  6718. disk_total_bytes: number;
  6719. disk_total_formatted: string;
  6720. disk_used_bytes: number;
  6721. disk_used_formatted: string;
  6722. disk_free_bytes: number;
  6723. disk_free_formatted: string;
  6724. disk_percent_used: number;
  6725. };
  6726. system: {
  6727. platform: string;
  6728. platform_release: string;
  6729. platform_version: string;
  6730. architecture: string;
  6731. hostname: string;
  6732. python_version: string;
  6733. uptime_seconds: number;
  6734. uptime_formatted: string;
  6735. boot_time: string;
  6736. };
  6737. memory: {
  6738. total_bytes: number;
  6739. total_formatted: string;
  6740. available_bytes: number;
  6741. available_formatted: string;
  6742. used_bytes: number;
  6743. used_formatted: string;
  6744. percent_used: number;
  6745. };
  6746. cpu: {
  6747. count: number;
  6748. count_logical: number;
  6749. percent: number;
  6750. };
  6751. }
  6752. export interface StorageUsageCategory {
  6753. key: string;
  6754. label: string;
  6755. bytes: number;
  6756. formatted: string;
  6757. percent_of_total: number;
  6758. }
  6759. export interface StorageUsageOtherItem {
  6760. bucket: string;
  6761. label: string;
  6762. kind: 'system' | 'data';
  6763. deletable: boolean;
  6764. bytes: number;
  6765. formatted: string;
  6766. percent_of_total: number;
  6767. }
  6768. export interface StorageUsageResponse {
  6769. roots: string[];
  6770. total_bytes: number;
  6771. total_formatted: string;
  6772. categories: StorageUsageCategory[];
  6773. other_breakdown: StorageUsageOtherItem[];
  6774. scan_errors: number;
  6775. generated_at: string;
  6776. cache: {
  6777. hit: boolean;
  6778. age_seconds: number;
  6779. max_age_seconds: number;
  6780. };
  6781. }
  6782. // Library (File Manager) types
  6783. export interface LibraryFolderTree {
  6784. id: number;
  6785. name: string;
  6786. parent_id: number | null;
  6787. project_id: number | null;
  6788. archive_id: number | null;
  6789. project_name: string | null;
  6790. archive_name: string | null;
  6791. is_external: boolean;
  6792. external_path: string | null;
  6793. external_readonly: boolean;
  6794. file_count: number;
  6795. // max(folder.updated_at, max(immediate-child file.updated_at)). Used by
  6796. // the File Manager folder tree's "sort by recent activity" mode (#1770).
  6797. latest_activity_at: string | null;
  6798. children: LibraryFolderTree[];
  6799. }
  6800. export interface LibraryFolder {
  6801. id: number;
  6802. name: string;
  6803. parent_id: number | null;
  6804. project_id: number | null;
  6805. archive_id: number | null;
  6806. project_name: string | null;
  6807. archive_name: string | null;
  6808. is_external: boolean;
  6809. external_path: string | null;
  6810. external_readonly: boolean;
  6811. external_show_hidden: boolean;
  6812. file_count: number;
  6813. latest_activity_at: string | null;
  6814. created_at: string;
  6815. updated_at: string;
  6816. }
  6817. export interface LibraryFolderCreate {
  6818. name: string;
  6819. parent_id?: number | null;
  6820. project_id?: number | null;
  6821. archive_id?: number | null;
  6822. }
  6823. export interface ExternalFolderCreate {
  6824. name: string;
  6825. external_path: string;
  6826. readonly?: boolean;
  6827. show_hidden?: boolean;
  6828. parent_id?: number | null;
  6829. }
  6830. export interface LibraryFolderUpdate {
  6831. name?: string;
  6832. parent_id?: number | null;
  6833. project_id?: number | null; // 0 to unlink
  6834. archive_id?: number | null; // 0 to unlink
  6835. }
  6836. export interface LibraryFileDuplicate {
  6837. id: number;
  6838. filename: string;
  6839. folder_id: number | null;
  6840. folder_name: string | null;
  6841. created_at: string;
  6842. }
  6843. export interface LibraryFile {
  6844. id: number;
  6845. folder_id: number | null;
  6846. folder_name: string | null;
  6847. project_id: number | null;
  6848. project_name: string | null;
  6849. is_external: boolean;
  6850. filename: string;
  6851. file_path: string;
  6852. file_type: string;
  6853. file_size: number;
  6854. file_hash: string | null;
  6855. thumbnail_path: string | null;
  6856. metadata: Record<string, unknown> | null;
  6857. print_count: number;
  6858. last_printed_at: string | null;
  6859. notes: string | null;
  6860. duplicates: LibraryFileDuplicate[] | null;
  6861. duplicate_count: number;
  6862. // User tracking (Issue #206)
  6863. created_by_id: number | null;
  6864. created_by_username: string | null;
  6865. created_at: string;
  6866. updated_at: string;
  6867. // Metadata fields
  6868. print_name: string | null;
  6869. print_time_seconds: number | null;
  6870. filament_used_grams: number | null;
  6871. sliced_for_model: string | null;
  6872. }
  6873. export interface LibraryTagSummary {
  6874. id: number;
  6875. name: string;
  6876. }
  6877. export interface LibraryFileListItem {
  6878. id: number;
  6879. folder_id: number | null;
  6880. is_external: boolean;
  6881. filename: string;
  6882. file_type: string;
  6883. file_size: number;
  6884. thumbnail_path: string | null;
  6885. print_count: number;
  6886. duplicate_count: number;
  6887. // User tracking (Issue #206)
  6888. created_by_id: number | null;
  6889. created_by_username: string | null;
  6890. created_at: string;
  6891. // Real on-disk modification time (#2680). Null for managed uploads; the date
  6892. // sort and "Modified" column use `fs_modified_at ?? created_at`.
  6893. fs_modified_at: string | null;
  6894. print_name: string | null;
  6895. print_time_seconds: number | null;
  6896. filament_used_grams: number | null;
  6897. sliced_for_model: string | null;
  6898. // Tags assigned to this file (#1268). The backend always emits an empty
  6899. // array when a file has no tags, but the field is typed optional so any
  6900. // legacy code path (or mock) that constructs a LibraryFileListItem without
  6901. // it doesn't crash the renderer. Read sites use `file.tags ?? []`.
  6902. tags?: LibraryTagSummary[];
  6903. // Variant grouping (#671 / #2570). `variant_count` is the size of the whole
  6904. // group, which may include files in other folders — never the number of
  6905. // matching rows on screen. 0 when the file is not grouped.
  6906. variant_group_id?: number | null;
  6907. variant_count?: number;
  6908. }
  6909. // Variant groups (#671 / #2570): the same job sliced for different printers.
  6910. export interface VariantGroupMember {
  6911. library_file_id: number;
  6912. filename: string;
  6913. target_model: string;
  6914. position: number;
  6915. }
  6916. export interface VariantGroup {
  6917. id: number;
  6918. name: string;
  6919. /** In priority order — index 0 wins when several printers are free at once. */
  6920. members: VariantGroupMember[];
  6921. }
  6922. // Library tag catalog (#1268)
  6923. export interface LibraryTag {
  6924. id: number;
  6925. name: string;
  6926. file_count: number;
  6927. created_at: string;
  6928. updated_at: string;
  6929. }
  6930. export interface LibraryTagBulkAssignResult {
  6931. files_updated: number;
  6932. associations_added: number;
  6933. associations_removed: number;
  6934. }
  6935. export interface LibraryFileUpdate {
  6936. filename?: string;
  6937. folder_id?: number | null;
  6938. project_id?: number | null;
  6939. notes?: string | null;
  6940. }
  6941. // Library trash (#1008)
  6942. export interface LibraryTrashItem {
  6943. id: number;
  6944. filename: string;
  6945. file_size: number;
  6946. thumbnail_path: string | null;
  6947. folder_id: number | null;
  6948. folder_name: string | null;
  6949. created_by_id: number | null;
  6950. created_by_username: string | null;
  6951. deleted_at: string;
  6952. auto_purge_at: string;
  6953. }
  6954. export interface LibraryTrashListResponse {
  6955. items: LibraryTrashItem[];
  6956. total: number;
  6957. retention_days: number;
  6958. }
  6959. export interface LibraryPurgePreview {
  6960. count: number;
  6961. total_bytes: number;
  6962. sample_filenames: string[];
  6963. older_than_days: number;
  6964. include_never_printed: boolean;
  6965. }
  6966. export interface LibraryTrashSettings {
  6967. retention_days: number;
  6968. auto_purge_enabled: boolean;
  6969. auto_purge_days: number;
  6970. auto_purge_include_never_printed: boolean;
  6971. }
  6972. export interface ArchivePurgePreview {
  6973. count: number;
  6974. total_bytes: number;
  6975. sample_filenames: string[];
  6976. older_than_days: number;
  6977. }
  6978. export interface ArchivePurgeSettings {
  6979. enabled: boolean;
  6980. days: number;
  6981. // #1390: when true, bulk-deletes the linked PrintLogEntry rows so the
  6982. // contribution drops from Quick Stats too. Default false — soft-delete,
  6983. // Quick Stats preserved.
  6984. purge_stats: boolean;
  6985. }
  6986. export interface LibraryFileUploadResponse {
  6987. id: number;
  6988. filename: string;
  6989. file_type: string;
  6990. file_size: number;
  6991. thumbnail_path: string | null;
  6992. duplicate_of: number | null;
  6993. metadata: Record<string, unknown> | null;
  6994. }
  6995. export interface LibraryStats {
  6996. total_files: number;
  6997. total_folders: number;
  6998. total_size_bytes: number;
  6999. files_by_type: Record<string, number>;
  7000. total_prints: number;
  7001. disk_free_bytes: number;
  7002. disk_total_bytes: number;
  7003. disk_used_bytes: number;
  7004. }
  7005. export interface ZipExtractResult {
  7006. filename: string;
  7007. file_id: number;
  7008. folder_id: number | null;
  7009. }
  7010. export interface ZipExtractError {
  7011. filename: string;
  7012. error: string;
  7013. }
  7014. export interface ZipExtractResponse {
  7015. extracted: number;
  7016. folders_created: number;
  7017. files: ZipExtractResult[];
  7018. errors: ZipExtractError[];
  7019. }
  7020. // STL Thumbnail Generation types
  7021. export interface BatchThumbnailResult {
  7022. file_id: number;
  7023. filename: string;
  7024. success: boolean;
  7025. error?: string | null;
  7026. }
  7027. export interface BatchThumbnailResponse {
  7028. processed: number;
  7029. succeeded: number;
  7030. failed: number;
  7031. results: BatchThumbnailResult[];
  7032. }
  7033. // Library Queue types
  7034. export interface AddToQueueResult {
  7035. file_id: number;
  7036. filename: string;
  7037. queue_item_id: number;
  7038. archive_id: number;
  7039. }
  7040. export interface AddToQueueError {
  7041. file_id: number;
  7042. filename: string;
  7043. error: string;
  7044. }
  7045. export interface AddToQueueResponse {
  7046. added: AddToQueueResult[];
  7047. errors: AddToQueueError[];
  7048. }
  7049. // Discovery types
  7050. export interface DiscoveredPrinter {
  7051. serial: string;
  7052. name: string;
  7053. ip_address: string;
  7054. model: string | null;
  7055. discovered_at: string | null;
  7056. }
  7057. export interface DiscoveryStatus {
  7058. running: boolean;
  7059. }
  7060. export interface DiscoveryInfo {
  7061. is_docker: boolean;
  7062. ssdp_running: boolean;
  7063. scan_running: boolean;
  7064. subnets: string[];
  7065. }
  7066. export interface SubnetScanStatus {
  7067. running: boolean;
  7068. scanned: number;
  7069. total: number;
  7070. }
  7071. // Discovery API
  7072. export const discoveryApi = {
  7073. getInfo: () => request<DiscoveryInfo>('/discovery/info'),
  7074. getStatus: () => request<DiscoveryStatus>('/discovery/status'),
  7075. startDiscovery: (duration: number = 10) =>
  7076. request<DiscoveryStatus>(`/discovery/start?duration=${duration}`, { method: 'POST' }),
  7077. stopDiscovery: () =>
  7078. request<DiscoveryStatus>('/discovery/stop', { method: 'POST' }),
  7079. getDiscoveredPrinters: () =>
  7080. request<DiscoveredPrinter[]>('/discovery/printers'),
  7081. // Subnet scanning (for Docker environments)
  7082. startSubnetScan: (subnet: string, timeout: number = 1.0) =>
  7083. request<SubnetScanStatus>('/discovery/scan', {
  7084. method: 'POST',
  7085. body: JSON.stringify({ subnet, timeout }),
  7086. }),
  7087. getScanStatus: () => request<SubnetScanStatus>('/discovery/scan/status'),
  7088. stopSubnetScan: () =>
  7089. request<SubnetScanStatus>('/discovery/scan/stop', { method: 'POST' }),
  7090. };
  7091. // Virtual Printer types
  7092. // Canonical wire values: `archive`, `review`, `queue`, `proxy`. The legacy
  7093. // `immediate` (→ archive) and `print_queue` (→ queue) names are still
  7094. // accepted by the backend so older API clients keep working, but new code
  7095. // should send the canonical names.
  7096. export type VirtualPrinterMode = 'archive' | 'review' | 'queue' | 'proxy' | 'immediate' | 'print_queue';
  7097. export interface VirtualPrinterProxyStatus {
  7098. running: boolean;
  7099. target_host: string;
  7100. ftp_port: number;
  7101. mqtt_port: number;
  7102. ftp_connections: number;
  7103. mqtt_connections: number;
  7104. }
  7105. export interface VirtualPrinterStatus {
  7106. enabled: boolean;
  7107. running: boolean;
  7108. mode: VirtualPrinterMode;
  7109. name: string;
  7110. serial: string;
  7111. model: string;
  7112. model_name: string;
  7113. pending_files: number;
  7114. target_printer_ip?: string; // For proxy mode
  7115. proxy?: VirtualPrinterProxyStatus; // For proxy mode
  7116. }
  7117. export interface VirtualPrinterSettings {
  7118. enabled: boolean;
  7119. access_code_set: boolean;
  7120. mode: VirtualPrinterMode;
  7121. model: string;
  7122. target_printer_id: number | null; // For proxy mode
  7123. remote_interface_ip: string | null; // For SSDP proxy across networks
  7124. tailscale_disabled: boolean;
  7125. archive_name_source: 'metadata' | 'filename'; // Source for archive's display name
  7126. status: VirtualPrinterStatus;
  7127. }
  7128. export interface NetworkInterface {
  7129. name: string;
  7130. ip: string;
  7131. netmask: string;
  7132. subnet: string;
  7133. is_alias?: boolean;
  7134. label?: string;
  7135. }
  7136. export interface VirtualPrinterModels {
  7137. models: Record<string, string>; // SSDP code -> display name
  7138. default: string;
  7139. }
  7140. export interface PendingUpload {
  7141. id: number;
  7142. filename: string;
  7143. // Resolved name the review card should show — mirrors what archive_print
  7144. // will eventually write to PrintArchive.print_name (#1152 follow-up). Falls
  7145. // back to the stripped filename stem when the 3MF has no embedded title or
  7146. // the operator has chosen the "filename" archive-name source.
  7147. display_name: string;
  7148. file_size: number;
  7149. source_ip: string | null;
  7150. status: string;
  7151. tags: string | null;
  7152. notes: string | null;
  7153. project_id: number | null;
  7154. uploaded_at: string;
  7155. }
  7156. // Virtual Printer API
  7157. export const virtualPrinterApi = {
  7158. getSettings: () => request<VirtualPrinterSettings>('/settings/virtual-printer'),
  7159. getModels: () => request<VirtualPrinterModels>('/settings/virtual-printer/models'),
  7160. updateSettings: (data: {
  7161. enabled?: boolean;
  7162. access_code?: string;
  7163. mode?: 'archive' | 'review' | 'queue' | 'proxy';
  7164. model?: string;
  7165. target_printer_id?: number;
  7166. remote_interface_ip?: string;
  7167. tailscale_disabled?: boolean;
  7168. archive_name_source?: 'metadata' | 'filename';
  7169. }) => {
  7170. const params = new URLSearchParams();
  7171. if (data.enabled !== undefined) params.set('enabled', String(data.enabled));
  7172. if (data.access_code !== undefined) params.set('access_code', data.access_code);
  7173. if (data.mode !== undefined) params.set('mode', data.mode);
  7174. if (data.model !== undefined) params.set('model', data.model);
  7175. if (data.target_printer_id !== undefined) params.set('target_printer_id', String(data.target_printer_id));
  7176. if (data.remote_interface_ip !== undefined) params.set('remote_interface_ip', data.remote_interface_ip);
  7177. if (data.tailscale_disabled !== undefined) params.set('tailscale_disabled', String(data.tailscale_disabled));
  7178. if (data.archive_name_source !== undefined) params.set('archive_name_source', data.archive_name_source);
  7179. return request<VirtualPrinterSettings>(`/settings/virtual-printer?${params.toString()}`, {
  7180. method: 'PUT',
  7181. });
  7182. },
  7183. };
  7184. // Multi Virtual Printer API
  7185. export interface VirtualPrinterConfig {
  7186. id: number;
  7187. name: string;
  7188. enabled: boolean;
  7189. mode: VirtualPrinterMode;
  7190. model: string | null;
  7191. model_name: string | null;
  7192. access_code_set: boolean;
  7193. serial: string;
  7194. target_printer_id: number | null;
  7195. auto_dispatch: boolean;
  7196. queue_force_color_match: boolean;
  7197. save_ams_mapping: boolean;
  7198. gcode_injection: boolean;
  7199. tailscale_disabled: boolean;
  7200. bind_ip: string | null;
  7201. remote_interface_ip: string | null;
  7202. position: number;
  7203. status: { running: boolean; pending_files: number; proxy?: VirtualPrinterProxyStatus };
  7204. }
  7205. export interface VirtualPrinterListResponse {
  7206. printers: VirtualPrinterConfig[];
  7207. models: Record<string, string>;
  7208. }
  7209. export const multiVirtualPrinterApi = {
  7210. list: () => request<VirtualPrinterListResponse>('/virtual-printers'),
  7211. get: (id: number) => request<VirtualPrinterConfig>(`/virtual-printers/${id}`),
  7212. create: (data: {
  7213. name?: string;
  7214. enabled?: boolean;
  7215. mode?: string;
  7216. model?: string;
  7217. access_code?: string;
  7218. target_printer_id?: number;
  7219. auto_dispatch?: boolean;
  7220. queue_force_color_match?: boolean;
  7221. save_ams_mapping?: boolean;
  7222. gcode_injection?: boolean;
  7223. bind_ip?: string;
  7224. remote_interface_ip?: string;
  7225. }) =>
  7226. request<VirtualPrinterConfig>('/virtual-printers', {
  7227. method: 'POST',
  7228. body: JSON.stringify(data),
  7229. }),
  7230. update: (id: number, data: {
  7231. name?: string;
  7232. enabled?: boolean;
  7233. mode?: string;
  7234. model?: string;
  7235. access_code?: string;
  7236. target_printer_id?: number;
  7237. auto_dispatch?: boolean;
  7238. queue_force_color_match?: boolean;
  7239. save_ams_mapping?: boolean;
  7240. gcode_injection?: boolean;
  7241. tailscale_disabled?: boolean;
  7242. bind_ip?: string;
  7243. remote_interface_ip?: string;
  7244. }) =>
  7245. request<VirtualPrinterConfig>(`/virtual-printers/${id}`, {
  7246. method: 'PUT',
  7247. body: JSON.stringify(data),
  7248. }),
  7249. remove: (id: number) =>
  7250. request<{ detail: string; id: number }>(`/virtual-printers/${id}`, {
  7251. method: 'DELETE',
  7252. }),
  7253. getTailscaleStatus: () =>
  7254. request<TailscaleStatusResponse>('/virtual-printers/tailscale-status'),
  7255. getCaCertificate: () =>
  7256. request<VPCaCertificate>('/virtual-printers/ca-certificate'),
  7257. diagnose: (id: number) =>
  7258. request<VPDiagnosticResult>(`/virtual-printers/${id}/diagnostic`),
  7259. };
  7260. /** The shared CA certificate every virtual printer presents — imported once
  7261. * into the slicer's trust store. Only the public certificate is returned. */
  7262. export interface VPCaCertificate {
  7263. pem: string;
  7264. fingerprint_sha256: string;
  7265. not_valid_after: string;
  7266. }
  7267. export type VPDiagnosticStatus = 'pass' | 'fail' | 'warn' | 'skip';
  7268. export interface VPDiagnosticCheck {
  7269. id:
  7270. | 'enabled'
  7271. | 'running'
  7272. | 'bind_interface'
  7273. | 'access_code'
  7274. | 'target_printer'
  7275. | 'port_ftps'
  7276. | 'port_mqtt'
  7277. | 'port_bind'
  7278. | 'certificate';
  7279. status: VPDiagnosticStatus;
  7280. params: Record<string, string | number>;
  7281. }
  7282. export interface VPDiagnosticResult {
  7283. vp_id: number;
  7284. vp_name: string;
  7285. mode: string;
  7286. overall: 'ok' | 'warnings' | 'problems';
  7287. checks: VPDiagnosticCheck[];
  7288. }
  7289. export interface TailscaleStatusResponse {
  7290. available: boolean;
  7291. fqdn: string;
  7292. hostname: string;
  7293. tailnet_name: string;
  7294. tailscale_ips: string[];
  7295. error: string | null;
  7296. }
  7297. // Pending Uploads API
  7298. export const pendingUploadsApi = {
  7299. list: () => request<PendingUpload[]>('/pending-uploads/'),
  7300. getCount: () => request<{ count: number }>('/pending-uploads/count'),
  7301. get: (id: number) => request<PendingUpload>(`/pending-uploads/${id}`),
  7302. archive: (id: number, data?: { tags?: string; notes?: string; project_id?: number }) =>
  7303. request<{ id: number; print_name: string; filename: string }>(`/pending-uploads/${id}/archive`, {
  7304. method: 'POST',
  7305. body: JSON.stringify(data || {}),
  7306. }),
  7307. discard: (id: number) =>
  7308. request<{ success: boolean }>(`/pending-uploads/${id}`, { method: 'DELETE' }),
  7309. archiveAll: () =>
  7310. request<{ archived: number; failed: number }>('/pending-uploads/archive-all', { method: 'POST' }),
  7311. discardAll: () =>
  7312. request<{ discarded: number }>('/pending-uploads/discard-all', { method: 'DELETE' }),
  7313. };
  7314. // Firmware API Types
  7315. export interface AvailableFirmwareVersion {
  7316. version: string;
  7317. file_available: boolean;
  7318. download_url: string | null;
  7319. release_notes: string | null;
  7320. release_time: string | null;
  7321. }
  7322. export interface FirmwareUpdateInfo {
  7323. printer_id: number;
  7324. printer_name: string;
  7325. model: string | null;
  7326. current_version: string | null;
  7327. latest_version: string | null;
  7328. update_available: boolean;
  7329. download_url: string | null;
  7330. release_notes: string | null;
  7331. available_versions: AvailableFirmwareVersion[];
  7332. }
  7333. export interface FirmwareUploadPrepare {
  7334. can_proceed: boolean;
  7335. sd_card_present: boolean;
  7336. sd_card_free_space: number;
  7337. firmware_size: number;
  7338. space_sufficient: boolean;
  7339. update_available: boolean;
  7340. current_version: string | null;
  7341. latest_version: string | null;
  7342. target_version: string | null;
  7343. firmware_filename: string | null;
  7344. errors: string[];
  7345. }
  7346. export interface FirmwareUploadStatus {
  7347. status: 'idle' | 'preparing' | 'downloading' | 'uploading' | 'complete' | 'error';
  7348. progress: number;
  7349. message: string;
  7350. error: string | null;
  7351. firmware_filename: string | null;
  7352. firmware_version: string | null;
  7353. }
  7354. // Firmware API
  7355. export const firmwareApi = {
  7356. checkUpdates: () =>
  7357. request<{ updates: FirmwareUpdateInfo[]; updates_available: number }>('/firmware/updates'),
  7358. checkPrinterUpdate: (printerId: number) =>
  7359. request<FirmwareUpdateInfo>(`/firmware/updates/${printerId}`),
  7360. prepareUpload: (printerId: number, version?: string) =>
  7361. request<FirmwareUploadPrepare>(
  7362. `/firmware/updates/${printerId}/prepare${version ? `?version=${encodeURIComponent(version)}` : ''}`,
  7363. ),
  7364. startUpload: (printerId: number, version?: string) =>
  7365. request<{ started: boolean; message: string }>(
  7366. `/firmware/updates/${printerId}/upload${version ? `?version=${encodeURIComponent(version)}` : ''}`,
  7367. { method: 'POST' },
  7368. ),
  7369. getUploadStatus: (printerId: number) =>
  7370. request<FirmwareUploadStatus>(`/firmware/updates/${printerId}/upload/status`),
  7371. };
  7372. // Support types
  7373. export interface DebugLoggingState {
  7374. enabled: boolean;
  7375. enabled_at: string | null;
  7376. duration_seconds: number | null;
  7377. }
  7378. export interface LogEntry {
  7379. timestamp: string;
  7380. level: string;
  7381. logger_name: string;
  7382. message: string;
  7383. }
  7384. export interface LogsResponse {
  7385. entries: LogEntry[];
  7386. total_in_file: number;
  7387. filtered_count: number;
  7388. }
  7389. // Support API
  7390. export const supportApi = {
  7391. getDebugLoggingState: () =>
  7392. request<DebugLoggingState>('/support/debug-logging'),
  7393. setDebugLogging: (enabled: boolean) =>
  7394. request<DebugLoggingState>('/support/debug-logging', {
  7395. method: 'POST',
  7396. body: JSON.stringify({ enabled }),
  7397. }),
  7398. downloadSupportBundle: async () => {
  7399. const headers: Record<string, string> = {};
  7400. if (authToken) {
  7401. headers['Authorization'] = `Bearer ${authToken}`;
  7402. }
  7403. const response = await fetch(`${API_BASE}/support/bundle`, { headers });
  7404. if (!response.ok) {
  7405. const error = await response.json().catch(() => ({}));
  7406. throw new Error(error.detail || `HTTP ${response.status}`);
  7407. }
  7408. // Get filename from Content-Disposition header or use default
  7409. const disposition = response.headers.get('Content-Disposition');
  7410. const filename = parseContentDispositionFilename(disposition) || 'bambuddy-support.zip';
  7411. // Download the blob
  7412. const blob = await response.blob();
  7413. const url = window.URL.createObjectURL(blob);
  7414. const a = document.createElement('a');
  7415. a.href = url;
  7416. a.download = filename;
  7417. document.body.appendChild(a);
  7418. a.click();
  7419. document.body.removeChild(a);
  7420. window.URL.revokeObjectURL(url);
  7421. },
  7422. getLogs: (params?: { limit?: number; level?: string; search?: string }) => {
  7423. const searchParams = new URLSearchParams();
  7424. if (params?.limit) searchParams.set('limit', params.limit.toString());
  7425. if (params?.level) searchParams.set('level', params.level);
  7426. if (params?.search) searchParams.set('search', params.search);
  7427. const query = searchParams.toString();
  7428. return request<LogsResponse>(`/support/logs${query ? `?${query}` : ''}`);
  7429. },
  7430. clearLogs: () =>
  7431. request<{ message: string }>('/support/logs', { method: 'DELETE' }),
  7432. };
  7433. // SpoolBuddy types
  7434. export interface SpoolBuddyDevice {
  7435. id: number;
  7436. device_id: string;
  7437. hostname: string;
  7438. ip_address: string;
  7439. backend_url?: string | null;
  7440. firmware_version: string | null;
  7441. has_nfc: boolean;
  7442. has_scale: boolean;
  7443. tare_offset: number;
  7444. calibration_factor: number;
  7445. nfc_reader_type: string | null;
  7446. nfc_connection: string | null;
  7447. display_brightness: number;
  7448. display_blank_timeout: number;
  7449. has_backlight: boolean;
  7450. last_calibrated_at: string | null;
  7451. last_seen: string | null;
  7452. pending_command: string | null;
  7453. nfc_ok: boolean;
  7454. scale_ok: boolean;
  7455. uptime_s: number;
  7456. update_status: string | null;
  7457. update_message: string | null;
  7458. system_stats: {
  7459. os?: { os?: string; kernel?: string; arch?: string; python?: string };
  7460. cpu_temp_c?: number;
  7461. cpu_count?: number;
  7462. load_avg?: number[];
  7463. memory?: { total_mb?: number; available_mb?: number; used_mb?: number; percent?: number };
  7464. disk?: { total_gb?: number; used_gb?: number; free_gb?: number; percent?: number };
  7465. system_uptime_s?: number;
  7466. } | null;
  7467. online: boolean;
  7468. }
  7469. export interface DaemonUpdateCheck {
  7470. current_version: string;
  7471. latest_version: string | null;
  7472. update_available: boolean;
  7473. }
  7474. // SpoolBuddy API
  7475. export const spoolbuddyApi = {
  7476. getDevices: () =>
  7477. request<SpoolBuddyDevice[]>('/spoolbuddy/devices'),
  7478. deleteDevice: (deviceId: string) =>
  7479. request<{ status: string; device_id: string }>(`/spoolbuddy/devices/${deviceId}`, {
  7480. method: 'DELETE',
  7481. }),
  7482. tare: (deviceId: string) =>
  7483. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/calibration/tare`, {
  7484. method: 'POST',
  7485. body: '{}',
  7486. }),
  7487. getCalibration: (deviceId: string) =>
  7488. request<{ tare_offset: number; calibration_factor: number }>(`/spoolbuddy/devices/${deviceId}/calibration`),
  7489. setCalibrationFactor: (deviceId: string, knownWeightGrams: number, rawAdc: number, tareRawAdc?: number) =>
  7490. request<{ tare_offset: number; calibration_factor: number }>(`/spoolbuddy/devices/${deviceId}/calibration/set-factor`, {
  7491. method: 'POST',
  7492. body: JSON.stringify({ known_weight_grams: knownWeightGrams, raw_adc: rawAdc, tare_raw_adc: tareRawAdc }),
  7493. }),
  7494. updateSpoolWeight: (spoolId: number, weightGrams: number) =>
  7495. request<{ status: string; weight_used: number }>('/spoolbuddy/scale/update-spool-weight', {
  7496. method: 'POST',
  7497. body: JSON.stringify({ spool_id: spoolId, weight_grams: weightGrams }),
  7498. }),
  7499. updateDisplay: (deviceId: string, brightness: number, blankTimeout: number) =>
  7500. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/display`, {
  7501. method: 'PUT',
  7502. body: JSON.stringify({ brightness, blank_timeout: blankTimeout }),
  7503. }),
  7504. updateSystemConfig: (deviceId: string, backendUrl: string, apiKey?: string) =>
  7505. request<{ status: string; message: string }>(`/spoolbuddy/devices/${deviceId}/system/config`, {
  7506. method: 'POST',
  7507. body: JSON.stringify({ backend_url: backendUrl, ...(apiKey ? { api_key: apiKey } : {}) }),
  7508. }),
  7509. checkDaemonUpdate: (deviceId: string) =>
  7510. request<DaemonUpdateCheck>(`/spoolbuddy/devices/${deviceId}/update-check`),
  7511. triggerUpdate: (deviceId: string) =>
  7512. request<{ status: string; message: string }>(`/spoolbuddy/devices/${deviceId}/update`, {
  7513. method: 'POST',
  7514. body: '{}',
  7515. }),
  7516. getSSHPublicKey: () =>
  7517. request<{ public_key: string }>('/spoolbuddy/ssh/public-key'),
  7518. writeTag: (deviceId: string, spoolId: number) =>
  7519. request<{ status: string; warnings?: string[] }>('/spoolbuddy/nfc/write-tag', {
  7520. method: 'POST',
  7521. body: JSON.stringify({ device_id: deviceId, spool_id: spoolId }),
  7522. }),
  7523. cancelWrite: (deviceId: string) =>
  7524. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/cancel-write`, {
  7525. method: 'POST',
  7526. body: '{}',
  7527. }),
  7528. systemCommand: (deviceId: string, command: 'reboot' | 'shutdown' | 'restart_daemon' | 'restart_browser') =>
  7529. request<{ status: string; command: string }>(`/spoolbuddy/devices/${deviceId}/system/command`, {
  7530. method: 'POST',
  7531. body: JSON.stringify({ command }),
  7532. }),
  7533. queueDiagnostics: (deviceId: string, type: 'nfc' | 'scale' | 'read_tag') =>
  7534. request<{ status: string; diagnostic: string; message: string }>(
  7535. `/spoolbuddy/diagnostics/${deviceId}/run?diagnostic=${type}`,
  7536. { method: 'POST', body: '{}' }
  7537. ),
  7538. getDiagnosticResult: (deviceId: string, type: 'nfc' | 'scale' | 'read_tag') =>
  7539. request<{ diagnostic: string; success: boolean; output: string; exit_code: number }>(
  7540. `/spoolbuddy/diagnostics/${deviceId}/result?diagnostic=${type}`,
  7541. { method: 'GET' }
  7542. ),
  7543. };
  7544. export interface BugReportRequest {
  7545. description: string;
  7546. email?: string;
  7547. screenshot_base64?: string;
  7548. include_support_info?: boolean;
  7549. debug_logs?: string;
  7550. }
  7551. export interface BugReportResponse {
  7552. success: boolean;
  7553. message: string;
  7554. issue_url?: string;
  7555. issue_number?: number;
  7556. }
  7557. export const bugReportApi = {
  7558. submit: (data: BugReportRequest) =>
  7559. request<BugReportResponse>('/bug-report/submit', {
  7560. method: 'POST',
  7561. body: JSON.stringify(data),
  7562. }),
  7563. startLogging: () =>
  7564. request<{ started: boolean; was_debug: boolean }>('/bug-report/start-logging', {
  7565. method: 'POST',
  7566. }),
  7567. stopLogging: (wasDebug: boolean) =>
  7568. request<{ logs: string }>(`/bug-report/stop-logging?was_debug=${wasDebug}`, {
  7569. method: 'POST',
  7570. }),
  7571. };
  7572. export interface SponsorPromptCheckResponse {
  7573. show: boolean;
  7574. milestone?: string;
  7575. family?: 'prints' | 'cost' | 'archives' | 'anniversary' | 'version-update';
  7576. threshold?: number;
  7577. payload?: Record<string, unknown>;
  7578. }
  7579. export const sponsorPromptApi = {
  7580. check: () => request<SponsorPromptCheckResponse>('/sponsor-prompt/check'),
  7581. dismiss: (milestone: string) =>
  7582. request<void>('/sponsor-prompt/dismiss', {
  7583. method: 'POST',
  7584. body: JSON.stringify({ milestone }),
  7585. }),
  7586. };