client.ts 284 KB

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