client.ts 263 KB

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