client.ts 263 KB

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