client.ts 320 KB

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