client.ts 336 KB

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