client.ts 348 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757
  1. import type { KProfileWriteResult } from '../utils/kprofileWrite';
  2. import type { BambuCatalogColor } from '../utils/colors';
  3. import type { ArchivePlatesResponse, LibraryFilePlatesResponse } from '../types/plates';
  4. import { batched, byField, byId } from './batch';
  5. const API_BASE = '/api/v1';
  6. export class ApiError extends Error {
  7. status: number;
  8. /** Stable error code from a structured backend detail (`{code, message}`).
  9. * Frontend uses this to look up an i18n key instead of showing the raw
  10. * English fallback. Null when the backend returned a plain-string detail. */
  11. code: string | null;
  12. /** Full structured detail object when the backend returned `{code, ...}`
  13. * with additional fields (e.g. the deficit list for 409s on queue
  14. * start, #1496). Null for plain-string or array-shaped details. */
  15. detail: Record<string, unknown> | null;
  16. constructor(
  17. message: string,
  18. status: number,
  19. code: string | null = null,
  20. detail: Record<string, unknown> | null = null,
  21. ) {
  22. super(message);
  23. this.name = 'ApiError';
  24. this.status = status;
  25. this.code = code;
  26. this.detail = detail;
  27. }
  28. }
  29. // Auth token storage
  30. // By default tokens are stored in sessionStorage (tab-scoped, cleared on close).
  31. // When the token originates from the ?token= URL param (kiosk bootstrap), it is
  32. // additionally persisted in localStorage so the kiosk survives page reloads.
  33. // 'persistent' also writes to localStorage so the token survives tab close
  34. // (used by Remember Me and the ?token= kiosk bootstrap).
  35. let authToken: string | null =
  36. sessionStorage.getItem('auth_token') ?? localStorage.getItem('auth_token');
  37. export type TokenPersistence = 'session' | 'persistent';
  38. export function setAuthToken(token: string | null, persistence: TokenPersistence = 'session') {
  39. authToken = token;
  40. try {
  41. if (token) {
  42. sessionStorage.setItem('auth_token', token);
  43. } else {
  44. sessionStorage.removeItem('auth_token');
  45. }
  46. } catch (err) {
  47. // Storage unavailable (quota exceeded, private mode): in-memory token still works for this tab.
  48. console.warn('setAuthToken: sessionStorage unavailable, token kept in-memory only', err);
  49. }
  50. try {
  51. if (!token) {
  52. localStorage.removeItem('auth_token');
  53. } else if (persistence === 'persistent') {
  54. localStorage.setItem('auth_token', token);
  55. }
  56. } catch (err) {
  57. console.warn('setAuthToken: localStorage operation failed', err);
  58. }
  59. }
  60. export function getAuthToken(): string | null {
  61. return authToken;
  62. }
  63. // Query-param tokens for <img>/<video> src URLs, which can't carry an
  64. // Authorization header. There are two, and which one a URL takes is decided
  65. // by what the URL points at, not by convenience:
  66. //
  67. // streamToken — live camera only. Minting one costs camera:view.
  68. // mediaToken — thumbnails, previews, timelapses, covers, icons. Minted by
  69. // any signed-in user and carries their identity, so those
  70. // routes can apply the same ownership rules as everywhere else.
  71. //
  72. // Before #3025 the stream token served both, which meant a user could not see
  73. // a library thumbnail without also being granted the live feed of the room the
  74. // printer sits in — and, because a stream token names nobody, those routes had
  75. // no identity to scope by and served any row to any holder.
  76. let streamToken: string | null = null;
  77. let mediaToken: string | null = null;
  78. export function setStreamToken(token: string | null) {
  79. streamToken = token;
  80. }
  81. export function getStreamToken(): string | null {
  82. return streamToken;
  83. }
  84. export function setMediaToken(token: string | null) {
  85. mediaToken = token;
  86. }
  87. export function getMediaToken(): string | null {
  88. return mediaToken;
  89. }
  90. /** Append the camera stream token to a URL if available (live camera only). */
  91. export function withStreamToken(url: string): string {
  92. if (!streamToken) return url;
  93. const sep = url.includes('?') ? '&' : '?';
  94. return `${url}${sep}token=${encodeURIComponent(streamToken)}`;
  95. }
  96. /** Append the media token to a URL if available (for <img>/<video> src). */
  97. export function withMediaToken(url: string): string {
  98. if (!mediaToken) return url;
  99. const sep = url.includes('?') ? '&' : '?';
  100. return `${url}${sep}token=${encodeURIComponent(mediaToken)}`;
  101. }
  102. function parseContentDispositionFilename(header: string | null): string | null {
  103. if (!header) return null;
  104. // RFC 5987: filename*=utf-8''percent-encoded-name
  105. const rfc5987Match = header.match(/filename\*=(?:UTF-8|utf-8)''(.+?)(?:;|$)/);
  106. if (rfc5987Match) {
  107. try { return decodeURIComponent(rfc5987Match[1]); } catch { /* fall through */ }
  108. }
  109. // Standard: filename="name" or filename=name
  110. const standardMatch = header.match(/filename="?([^";\n]+)"?/);
  111. return standardMatch?.[1] || null;
  112. }
  113. function buildSlicerUrlFilename(filename: string): string {
  114. const safe = filename.replace(/[/\\?#]/g, '_');
  115. return safe.toLowerCase().endsWith('.3mf') ? safe : `${safe}.3mf`;
  116. }
  117. /** POST JSON and return the response body as a Blob (label PDFs and images). */
  118. async function postForBlob(endpoint: string, data: unknown, signal?: AbortSignal): Promise<Blob> {
  119. const headers: Record<string, string> = { 'Content-Type': 'application/json' };
  120. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  121. const response = await fetch(`${API_BASE}${endpoint}`, {
  122. method: 'POST',
  123. headers,
  124. body: JSON.stringify(data),
  125. signal,
  126. });
  127. if (!response.ok) {
  128. const error = await response.json().catch(() => ({}));
  129. throw new Error(typeof error.detail === 'string' ? error.detail : `HTTP ${response.status}`);
  130. }
  131. return response.blob();
  132. }
  133. async function request<T>(
  134. endpoint: string,
  135. options: RequestInit = {}
  136. ): Promise<T> {
  137. const headers: Record<string, string> = {
  138. 'Content-Type': 'application/json',
  139. ...options.headers as Record<string, string>,
  140. };
  141. // Add auth token if available
  142. if (authToken) {
  143. headers['Authorization'] = `Bearer ${authToken}`;
  144. }
  145. const response = await fetch(`${API_BASE}${endpoint}`, {
  146. ...options,
  147. cache: 'no-store', // Prevent browser caching of API responses
  148. credentials: 'include', // Required for HttpOnly cookies (e.g. 2fa_challenge)
  149. headers,
  150. });
  151. if (!response.ok) {
  152. const error = await response.json().catch(() => ({}));
  153. const detail = error.detail;
  154. let message: string;
  155. let code: string | null = null;
  156. if (typeof detail === 'string') {
  157. message = detail;
  158. } else if (Array.isArray(detail)) {
  159. // FastAPI 422 shape: each entry has `msg` like "Value error, <real msg>".
  160. // Strip the prefix and join. Fall back to raw JSON if every entry has an
  161. // empty msg (defensive — shouldn't happen with stock Pydantic, but the
  162. // previous fallback masked the real cause as a bare "HTTP 422" toast).
  163. const joined = detail
  164. .map((e: { msg?: string }) => (e.msg ?? '').replace(/^Value error,\s*/i, ''))
  165. .filter(Boolean)
  166. .join('; ');
  167. message = joined || JSON.stringify(detail) || `HTTP ${response.status}`;
  168. } else if (detail && typeof detail === 'object') {
  169. // Structured detail `{code, message, ...}` — frontend uses the code
  170. // to pick an i18n key, message is the English fallback, any extra
  171. // fields land on ApiError.detail (e.g. `deficit` for #1496).
  172. code = typeof detail.code === 'string' ? detail.code : null;
  173. message = typeof detail.message === 'string' ? detail.message : `HTTP ${response.status}`;
  174. } else {
  175. message = `HTTP ${response.status}`;
  176. }
  177. const structuredDetail = detail && typeof detail === 'object' && !Array.isArray(detail)
  178. ? (detail as Record<string, unknown>)
  179. : null;
  180. // Handle 401 Unauthorized - only clear token if it's actually invalid
  181. // Don't clear on "Authentication required" which might be a timing issue
  182. if (response.status === 401) {
  183. const invalidTokenMessages = [
  184. 'Could not validate credentials',
  185. 'Token has expired',
  186. 'User not found or inactive',
  187. 'Invalid API key',
  188. 'API key has expired',
  189. ];
  190. if (invalidTokenMessages.some(m => message.includes(m))) {
  191. setAuthToken(null);
  192. // Notify AuthContext so the protected route guard re-evaluates and
  193. // redirects to /login on the same tab — without this, AuthContext.user
  194. // stays cached and the tab silently fails every request until a manual
  195. // refresh remounts AuthProvider (#1698, reported by @TCL987).
  196. if (typeof window !== 'undefined') {
  197. window.dispatchEvent(new CustomEvent('auth:expired'));
  198. }
  199. }
  200. }
  201. throw new ApiError(message, response.status, code, structuredDetail);
  202. }
  203. // Handle empty responses (204 No Content, etc.)
  204. const contentLength = response.headers.get('content-length');
  205. if (response.status === 204 || contentLength === '0') {
  206. return undefined as T;
  207. }
  208. return await response.json();
  209. }
  210. /** Upload a CSV to the spool import endpoint (#1576). Multipart, so it bypasses
  211. * `request<T>()` (which sends JSON): the browser must set the form-data
  212. * boundary itself. `dryRun` toggles preview-only vs. real import. */
  213. async function uploadSpoolsCsv<T>(file: File, dryRun: boolean): Promise<T> {
  214. const form = new FormData();
  215. form.append('file', file);
  216. const headers: Record<string, string> = {};
  217. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  218. const response = await fetch(`${API_BASE}/inventory/spools/import${dryRun ? '?dry_run=true' : ''}`, {
  219. method: 'POST',
  220. headers,
  221. body: form,
  222. });
  223. if (!response.ok) {
  224. const error = await response.json().catch(() => ({}));
  225. // detail may be a plain string or a structured {code, message} object
  226. // (e.g. the 413 too-large response). Surface the human message either way.
  227. const detail = error?.detail;
  228. const message = typeof detail === 'string' ? detail : detail?.message;
  229. throw new Error(message || `HTTP ${response.status}`);
  230. }
  231. return response.json();
  232. }
  233. // Camera diagnostic result (#1395 follow-up). Returned by
  234. // POST /printers/{id}/camera/diagnose; the frontend modal renders one
  235. // row per stage and looks up the summary code in i18n for the user-
  236. // facing remediation hint.
  237. export interface CameraDiagnoseStage {
  238. name: 'tcp_reachable' | 'first_frame' | 'live_stream_active';
  239. status: 'ok' | 'failed' | 'skipped';
  240. duration_ms: number;
  241. code: string | null;
  242. }
  243. export interface CameraDiagnoseResult {
  244. printer_id: number;
  245. protocol: 'rtsp' | 'chamber_image';
  246. port: number;
  247. // 'default' = historical X1/H2 tuning. Anything else = this model has
  248. // an override entry in backend/app/services/camera_profiles.py.
  249. profile: string;
  250. overall_status: 'ok' | 'failed';
  251. stages: CameraDiagnoseStage[];
  252. // i18n key under `camera.diagnose.summary.*`.
  253. summary_code: string;
  254. }
  255. // Connection diagnostic (GET /printers/{id}/diagnostic and
  256. // POST /printers/diagnostic). Each check's `id` + `status` resolve a
  257. // localized title/fix under `diagnostic.check.*`; `params` interpolate it.
  258. export type DiagnosticStatus = 'pass' | 'fail' | 'warn' | 'skip';
  259. export interface DiagnosticCheck {
  260. id:
  261. | 'port_mqtt'
  262. | 'port_ftps'
  263. | 'port_rtsps'
  264. | 'network_mode'
  265. | 'subnet'
  266. | 'mqtt_auth'
  267. | 'developer_mode';
  268. status: DiagnosticStatus;
  269. params: Record<string, string | number>;
  270. }
  271. export interface PrinterDiagnosticResult {
  272. printer_id: number | null;
  273. ip_address: string;
  274. overall: 'ok' | 'warnings' | 'problems';
  275. checks: DiagnosticCheck[];
  276. }
  277. // --- Log-health scan: self-service triage on the System page + bug reporter.
  278. // The backend matches recent logs against a curated known-issue catalog;
  279. // human-readable cause/fix text is rendered from i18n keys keyed by signature_id.
  280. export type LogFindingSeverity = 'error' | 'warning';
  281. export type LogFindingCategory = 'layer8' | 'environment' | 'bug';
  282. export interface LogFinding {
  283. signature_id: string;
  284. severity: LogFindingSeverity;
  285. category: LogFindingCategory;
  286. wiki_anchor: string;
  287. count: number;
  288. first_seen: string;
  289. last_seen: string;
  290. sample: string;
  291. }
  292. export interface SystemHealthResult {
  293. findings: LogFinding[];
  294. scanned_entries: number;
  295. log_available: boolean;
  296. summary: {
  297. total: number;
  298. layer8: number;
  299. environment: number;
  300. bug: number;
  301. };
  302. }
  303. // Long-lived camera tokens (#1108). The `token` field is populated only on the
  304. // create response — listing endpoints set it to null because the plaintext
  305. // value is shown to the user exactly once.
  306. //
  307. // 'camera_stream' reaches the video endpoints only. 'camwall' additionally
  308. // reaches the read-only Cam Wall feed, which names the printers (#2531), so it
  309. // is a separate scope rather than a widening of tokens already in the wild.
  310. export type LongLivedTokenScope = 'camera_stream' | 'camwall' | 'overlay';
  311. export interface LongLivedCameraToken {
  312. id: number;
  313. user_id: number;
  314. name: string;
  315. scope: LongLivedTokenScope;
  316. lookup_prefix: string;
  317. created_at: string;
  318. expires_at: string;
  319. last_used_at: string | null;
  320. token: string | null;
  321. }
  322. // An external application that signs users in with their Bambuddy account.
  323. // `client_secret` is present only in the create / rotate responses.
  324. export interface ConnectedApp {
  325. id: number;
  326. name: string;
  327. client_id: string;
  328. redirect_uri: string;
  329. enabled: boolean;
  330. created_at: string;
  331. last_used_at: string | null;
  332. client_secret?: string;
  333. }
  334. export interface ConnectAuthorizeInfo {
  335. app_name: string;
  336. username: string;
  337. already_granted: boolean;
  338. }
  339. // One row of the token-authenticated Cam Wall feed (#2531). Deliberately
  340. // smaller than PrinterStatus: no serial, no IP, no print filename — a kiosk URL
  341. // is not a secret, so the payload behind it must not be either.
  342. export interface CamWallPrinter {
  343. id: number;
  344. name: string;
  345. camera_rotation: number;
  346. connected: boolean;
  347. state: string | null;
  348. progress: number | null;
  349. remaining_time: number | null;
  350. layer_num: number | null;
  351. total_layers: number | null;
  352. hms_errors: HMSError[];
  353. }
  354. // Streaming-overlay feed (#2613). The subset of print state the /overlay page
  355. // draws for one printer, served behind an `overlay`-scoped token so OBS embeds
  356. // with no login session can read it. Unlike CamWallPrinter this names the file
  357. // being printed (the overlay shows the part on screen).
  358. export interface OverlayStatus {
  359. id: number;
  360. name: string;
  361. model: string | null;
  362. camera_rotation: number;
  363. connected: boolean;
  364. state: string | null;
  365. current_print: string | null;
  366. gcode_file: string | null;
  367. progress: number | null;
  368. remaining_time: number | null;
  369. layer_num: number | null;
  370. total_layers: number | null;
  371. stg_cur_name: string | null;
  372. // Nozzle / bed / chamber readings for the overlay's temperature fields
  373. // (#1422). Only the keys a viewer is shown; chamber is absent on models
  374. // without a real sensor.
  375. temperatures: Record<string, number>;
  376. time_format: 'system' | '12h' | '24h';
  377. }
  378. // Printer types
  379. // Printer locations (groups) and their appearance (#2962). `id` is null for a
  380. // location only printers carry, with no row of its own yet.
  381. export interface PrinterLocation {
  382. id: number | null;
  383. name: string;
  384. icon: string | null;
  385. color: string | null;
  386. printer_count: number;
  387. }
  388. export interface PrinterLocationUpdate {
  389. name: string;
  390. new_name?: string;
  391. icon?: string | null;
  392. color?: string | null;
  393. }
  394. export interface WLEDPresets {
  395. idle: number | null;
  396. prepare: number | null;
  397. printing: number | null;
  398. paused: number | null;
  399. finished: number | null;
  400. error: number | null;
  401. queue_waiting: number | null;
  402. filament_problem: number | null;
  403. hms_error: number | null;
  404. offline: number | null;
  405. }
  406. export interface WLEDConfig {
  407. enabled: boolean;
  408. base_url: string | null;
  409. presets: WLEDPresets;
  410. finished_timeout_seconds: number | null;
  411. }
  412. export interface WLEDPreset {
  413. id: number;
  414. name: string;
  415. }
  416. export interface WLEDConnectionInfo {
  417. name: string | null;
  418. version: string | null;
  419. }
  420. export interface Printer {
  421. id: number;
  422. name: string;
  423. serial_number: string;
  424. ip_address: string;
  425. // Optional because the backend only returns access_code when the caller has
  426. // PRINTERS_UPDATE — Admin / Operator JWTs or auth-disabled mode. Viewers and
  427. // API keys receive a Printer without this field.
  428. access_code?: string;
  429. model: string | null;
  430. location: string | null; // Group/location name
  431. nozzle_count: number; // 1 or 2, auto-detected from MQTT
  432. // Model is sold with both Standard and High Flow nozzles, so a K-profile's
  433. // flow type is a real choice. Derived from the model, not the nozzle count —
  434. // only the A-series has a single variant.
  435. supports_nozzle_flow_type: boolean;
  436. is_active: boolean;
  437. auto_archive: boolean;
  438. external_camera_url: string | null;
  439. external_camera_type: string | null; // "mjpeg", "rtsp", "snapshot"
  440. external_camera_enabled: boolean;
  441. external_camera_snapshot_url: string | null; // optional single-frame override (#1177)
  442. camera_rotation: number; // 0, 90, 180, 270 degrees
  443. camera_light_auto: boolean; // picked for the chamber light when camera_light_mode is 'selected' (#1655)
  444. plate_detection_enabled: boolean; // Check plate before print
  445. plate_detection_roi?: PlateDetectionROI; // ROI for plate detection
  446. wear_cost_per_hour: number | null; // Wear cost per printing hour (#694)
  447. wled_config: WLEDConfig | null;
  448. created_at: string;
  449. updated_at: string;
  450. }
  451. export interface HMSError {
  452. code: string;
  453. attr: number; // Attribute value for constructing wiki URL
  454. module: number;
  455. // Bambu's alert level: 1 error (task stopped), 2 warning (task paused),
  456. // 3 notification, 0 invalid (#2728).
  457. severity: number;
  458. actions?: string[]; // List of user-facing action keys (e.g. "CHECK_FILAMENT")
  459. job_id?: string; // Optional job ID for actions that require it (e.g. "CHECK_ASSISTANT")
  460. // Canonical hex identifier the firmware matches against — 8 chars for
  461. // print_error-sourced faults, 16 chars for hms[]-array-sourced faults. Send
  462. // this back as HmsActionBody.print_error so we don't truncate the 64-bit
  463. // identifier into the silent-rejection short code (#1830).
  464. full_code?: string;
  465. // The backend's catalogue sentence for this fault (#2926), from the table
  466. // generated out of Bambu Studio for this printer model (#2728). English only.
  467. // Null when Bambu publishes no text for the code. The frontend has no table of
  468. // its own: this field decides both the text and whether the fault counts.
  469. description?: string | null;
  470. }
  471. export interface HMSActionBody {
  472. print_error: string; // HMS error code (e.g. "05000070")
  473. action: string; // "HMS action to execute (e.g. 'resume_after_error')"
  474. job_id: string | null; // Optional job ID for context (if applicable)
  475. }
  476. export interface AMSTray {
  477. id: number;
  478. tray_color: string | null;
  479. tray_type: string | null;
  480. tray_sub_brands: string | null; // Full name like "PLA Basic", "PETG HF"
  481. tray_id_name: string | null; // Bambu filament ID like "A00-Y2" (can decode to color)
  482. tray_info_idx: string | null; // Filament preset ID like "GFA00" - maps to cloud setting_id
  483. remain: number;
  484. k: number | null; // Pressure advance value (from tray or K-profile lookup)
  485. cali_idx: number | null; // Calibration index for K-profile lookup
  486. tag_uid: string | null; // RFID tag UID (any tag)
  487. tray_uuid: string | null; // Bambu Lab spool UUID (32-char hex, only valid for Bambu Lab spools)
  488. nozzle_temp_min: number | null; // Min nozzle temperature
  489. nozzle_temp_max: number | null; // Max nozzle temperature
  490. drying_temp: number | null; // RFID-recommended drying temp
  491. drying_time: number | null; // RFID-recommended drying time (hours)
  492. state: number | null; // AMS tray state: 9=empty, 10=spool present not loaded, 11=loaded
  493. exists?: boolean | null; // Firmware tray_exist_bits: spool physically present (non-RFID → "?" not "Empty", #2527)
  494. }
  495. export interface AMSUnit {
  496. id: number;
  497. humidity: number | null;
  498. temp: number | null;
  499. is_ams_ht: boolean; // True for AMS-HT (single spool), False for regular AMS (4 spools)
  500. tray: AMSTray[];
  501. serial_number: string; // AMS unit serial number (from MQTT sn field)
  502. sw_ver: string; // AMS firmware version (from get_version info.module ams/* entry)
  503. dry_time: number; // Minutes remaining (0 = not drying, >0 = drying active)
  504. dry_countdown_stalled?: boolean; // Timer set but countdown not ticking (never started or paused)
  505. dry_status: number; // 0=Off, 1=Checking, 2=Drying, 3=Cooling, 4=Stopping, 5=Error
  506. dry_sub_status: number; // 0=Off, 1=Heating, 2=Dehumidify
  507. dry_sf_reason: number[]; // Cannot-dry reasons (1=InsufficientPower, 8=NeedPluginPower)
  508. dry_target_temp: number | null; // Active-cycle target °C (Bambu does not echo)
  509. dry_filament: string | null; // Active-cycle filament name we sent
  510. module_type: string; // "ams", "ams_f1", "n3f", "n3s"
  511. }
  512. export interface ScheduledDrying {
  513. id: number;
  514. printer_id: number;
  515. ams_id: number;
  516. temp: number;
  517. duration_hours: number;
  518. filament: string;
  519. rotate_tray: boolean;
  520. start_after: string | null; // UTC ISO with Z suffix, like the queue routes
  521. status: string;
  522. waiting_reason: string | null;
  523. error_message: string | null;
  524. // Why a failed run failed (screen_only / unsupported / did_not_start); null on
  525. // rows that failed before codes existed, which show error_message instead.
  526. error_code?: string | null;
  527. created_at: string;
  528. started_at: string | null;
  529. completed_at: string | null;
  530. }
  531. export interface NozzleInfo {
  532. // Two vocabularies live in this field, by printer generation. Legacy
  533. // printers (X1/P1) report the nozzle MATERIAL -- "stainless_steel",
  534. // "hardened_steel". H2-series report a FLOW code -- "HH01" (high flow),
  535. // "HS01" (standard); measured on an H2D. utils/nozzleFlow reads only the
  536. // latter and treats anything else as "unknown", which is what makes the
  537. // material spelling harmless here.
  538. nozzle_type: string;
  539. nozzle_diameter: string; // e.g., "0.4"
  540. }
  541. export interface NozzleRackSlot {
  542. id: number;
  543. nozzle_type: string;
  544. nozzle_diameter: string;
  545. wear: number | null;
  546. stat: number | null; // Nozzle status (e.g. mounted/docked)
  547. max_temp: number;
  548. serial_number: string;
  549. filament_color: string; // RGBA hex ("00000000" = no filament)
  550. filament_id: string;
  551. filament_type: string; // Material type (e.g. "PLA", "PETG")
  552. }
  553. export interface PrintOptions {
  554. // Core AI detectors
  555. spaghetti_detector: boolean;
  556. print_halt: boolean;
  557. halt_print_sensitivity: string; // "low", "medium", "high" - spaghetti sensitivity
  558. first_layer_inspector: boolean;
  559. printing_monitor: boolean;
  560. buildplate_marker_detector: boolean;
  561. allow_skip_parts: boolean;
  562. // Additional AI detectors (decoded from cfg bitmask)
  563. nozzle_clumping_detector: boolean;
  564. nozzle_clumping_sensitivity: string; // "low", "medium", "high"
  565. pileup_detector: boolean;
  566. pileup_sensitivity: string; // "low", "medium", "high"
  567. airprint_detector: boolean;
  568. airprint_sensitivity: string; // "low", "medium", "high"
  569. auto_recovery_step_loss: boolean;
  570. filament_tangle_detect: boolean;
  571. }
  572. export interface FilaSwitchState {
  573. installed: boolean;
  574. // Raw wire arrays, ordered **In-B first, then In-A** (BambuStudio's SwitchPos
  575. // enum). in[] values are snow-encoded (bits 8-15 = AMS id, bits 0-7 = slot,
  576. // -1 = empty); out[] values are the extruder each *outlet* terminates at, or
  577. // 0xE when unset. Neither array says which inlet is currently routed to which
  578. // outlet — that pairing is not reported. For per-AMS side information use
  579. // PrinterStatus.ams_switch_inlet instead.
  580. in_slots: number[];
  581. out_extruders: number[];
  582. stat: number;
  583. info: number;
  584. // Whether every AMS is bound to one of the switch's two inlets. Until it is,
  585. // the switch cannot route a load anywhere and the printer has to be set up
  586. // first ("Manual AMS Setup" on its screen).
  587. ready: boolean;
  588. }
  589. // Which AMS slot one hotend is currently fed from. ams_id/slot_id are null when
  590. // the hotend holds nothing. Keyed by extruder id ('0' = right, '1' = left).
  591. // tray_now cannot answer this — it is one value for the whole printer, so on a
  592. // dual-nozzle machine it names only one of the two loaded hotends.
  593. export interface ExtruderSlot {
  594. ams_id: number | null;
  595. slot_id: number | null;
  596. has_filament: boolean;
  597. }
  598. // Which FTS inlet an AMS is plumbed into: 'A' | 'B'.
  599. export type FtsInlet = 'A' | 'B';
  600. // A video device the server can see, for a USB camera (GET /printers/usb-cameras).
  601. export interface UsbCamera {
  602. device: string;
  603. name: string;
  604. capabilities: string[];
  605. driver?: string;
  606. formats?: string[];
  607. }
  608. export interface PrinterStatus {
  609. id: number;
  610. name: string;
  611. connected: boolean;
  612. state: string | null;
  613. current_print: string | null;
  614. subtask_name: string | null;
  615. current_archive_id: number | null;
  616. current_plate_id: number | null;
  617. gcode_file: string | null;
  618. progress: number | null;
  619. remaining_time: number | null;
  620. layer_num: number | null;
  621. total_layers: number | null;
  622. temperatures: {
  623. bed?: number;
  624. bed_target?: number;
  625. bed_heating?: boolean; // Actual heater state from MQTT
  626. nozzle?: number;
  627. nozzle_target?: number;
  628. nozzle_heating?: boolean; // Actual heater state from MQTT
  629. nozzle_2?: number; // Second nozzle for H2 series (dual nozzle)
  630. nozzle_2_target?: number;
  631. nozzle_2_heating?: boolean; // Actual heater state from MQTT
  632. chamber?: number;
  633. chamber_target?: number;
  634. chamber_heating?: boolean; // Actual heater state from MQTT
  635. } | null;
  636. cover_url: string | null;
  637. hms_errors: HMSError[];
  638. // Live updates send null when no AMS is attached; the REST status sends [].
  639. ams: AMSUnit[] | null;
  640. ams_exists: boolean;
  641. vt_tray: AMSTray[]; // Virtual tray / external spool(s)
  642. store_to_sdcard: boolean; // Store sent files on SD card
  643. timelapse: boolean; // Timelapse recording active
  644. ipcam: boolean; // Live view enabled
  645. wifi_signal: number | null; // WiFi signal strength in dBm
  646. wired_network: boolean; // Ethernet connection detected
  647. door_open: boolean; // Enclosure door open (models with a door sensor: X1/X1C/X1E/X2D/P2S/H2*)
  648. // Indexed by EXTRUDER id: [0] is the right hotend, [1] the left. Measured
  649. // on an H2D with 0.4 left / 0.6 right. Read it through the helpers in
  650. // utils/amsHelpers rather than indexing it directly.
  651. nozzles: NozzleInfo[];
  652. nozzle_rack: NozzleRackSlot[]; // H2C 6-nozzle tool-changer rack
  653. print_options: PrintOptions | null; // AI detection and print options
  654. // Calibration stage tracking
  655. stg_cur: number; // Current stage number (-1 = not calibrating)
  656. stg_cur_name: string | null; // Human-readable current stage name
  657. stg: number[]; // List of stage numbers in calibration sequence
  658. // Air conditioning mode (0=cooling, 1=heating)
  659. airduct_mode: number;
  660. // Print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  661. speed_level: number;
  662. // Chamber light on/off
  663. chamber_light: boolean;
  664. // Active extruder for dual nozzle (0=right, 1=left)
  665. active_extruder: number;
  666. // AMS mapping - which AMS is connected to which nozzle
  667. // Format: [ams_id_for_nozzle0, ams_id_for_nozzle1, ...] where -1 means no AMS
  668. ams_mapping: number[];
  669. // Per-AMS extruder mapping - extracted from each AMS unit's info field
  670. // Format: {ams_id: extruder_id} where extruder 0=right, 1=left
  671. // Note: JSON keys are always strings
  672. ams_extruder_map: Record<string, number>;
  673. // Filament Track Switch accessory — null when not installed. When present,
  674. // AMS slots aren't tied to a specific extruder; the FTS routes any slot to
  675. // either extruder, so per-extruder slot filtering must be skipped.
  676. fila_switch: FilaSwitchState | null;
  677. // Per-AMS FTS inlet binding, {ams_id: 'A' | 'B'}, as set on the printer's
  678. // "Manual AMS Setup" screen. Empty unless a switch is installed. An AMS with
  679. // an entry here reaches BOTH nozzles through the switch, which is why it has
  680. // no ams_extruder_map entry and must not be badged left or right.
  681. ams_switch_inlet: Record<string, FtsInlet>;
  682. // Which AMS slot each hotend is fed from, keyed by extruder id as a string.
  683. // Empty on printers that don't report it (everything but the H2/X2 series).
  684. extruder_slots: Record<string, ExtruderSlot>;
  685. // Currently loaded tray (global tray ID, 255 = no filament loaded, 254 = external spool)
  686. tray_now: number;
  687. // The trays this print has drawn from, in order: [global tray ID, layer of the
  688. // switch]. A tray outside the job's AMS mapping is a backup spool the printer
  689. // switched to (AMS Filament Backup). Reset at the start of each print.
  690. tray_change_log?: [number, number][];
  691. // Runout / filament-replacement guidance (#2587). Populated only while PAUSED.
  692. // Global tray IDs (ams_id*4+slot, 128-135 = AMS-HT, 254 = external), matching
  693. // the same numbering as tray_now so the AMS graphic can highlight them.
  694. // expected_tray = the slot the firmware now expects filament in (null = idle,
  695. // not paused, or unresolvable → "check the printer").
  696. // previous_tray = the slot that ran out (null = unknown).
  697. expected_tray: number | null;
  698. previous_tray: number | null;
  699. // AMS status for filament change tracking (0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration)
  700. ams_status_main: number;
  701. // AMS sub-status for filament change step (when main=1): 4=retraction, 6=load verification, 7=purge
  702. ams_status_sub: number;
  703. // mc_print_sub_stage - filament change step indicator used by OrcaSlicer/BambuStudio
  704. mc_print_sub_stage: number;
  705. // Timestamp of last AMS data update (for RFID refresh detection)
  706. last_ams_update: number;
  707. // Number of printable objects in current print (for skip objects feature)
  708. printable_objects_count: number;
  709. // The next pause the slicer put into the running print (#2984). minutes is
  710. // null while the printer reports no time left yet.
  711. next_pause?: { layer: number; minutes: number | null } | null;
  712. // Fan speeds (0-100 percentage, null if not available for this model)
  713. cooling_fan_speed: number | null; // Part cooling fan
  714. big_fan1_speed: number | null; // Auxiliary fan
  715. big_fan2_speed: number | null; // Chamber/exhaust fan
  716. heatbreak_fan_speed: number | null; // Hotend heatbreak fan
  717. // Left auxiliary part cooling fan (optional P2S/X2D accessory, M106 P10).
  718. // null = not installed / not reported by this model.
  719. left_aux_fan_speed: number | null;
  720. // Chamber exhaust fan present (P2S/X2D External Exhaust Fan kit, airduct part 3).
  721. exhaust_fan_present: boolean;
  722. firmware_version: string | null; // Firmware version from MQTT
  723. // Developer LAN mode: true = enabled, false = disabled, null = unknown
  724. developer_mode: boolean | null;
  725. // AMS Filament Backup ("auto-switch" to a backup spool when one runs out).
  726. // true = ON, false = OFF, null = unknown / unsupported (A1 family).
  727. ams_filament_backup: boolean | null;
  728. // Queue: printer is awaiting user ack that the build plate was cleared after a
  729. // finished/failed print. Persisted across restarts (#961).
  730. awaiting_plate_clear: boolean;
  731. // AMS drying support
  732. supports_drying: boolean;
  733. // The AMS can dry, but only from the printer's own screen (P1 series, #2533).
  734. drying_screen_only?: boolean;
  735. // Active chamber heater (responds to M141). True only for H2C/H2D/H2DPro/H2S/X2D.
  736. supports_chamber_heater?: boolean;
  737. }
  738. export interface PrinterCreate {
  739. name: string;
  740. serial_number: string;
  741. ip_address: string;
  742. access_code: string;
  743. model?: string;
  744. location?: string | null;
  745. auto_archive?: boolean;
  746. // Maintenance Mode flag (#1476). Backend already gates MQTT, queue dispatch,
  747. // scheduler, metrics and the print picker on this; toggling via PATCH
  748. // /printers/{id} disconnects or reconnects MQTT accordingly.
  749. is_active?: boolean;
  750. external_camera_url?: string | null;
  751. external_camera_type?: string | null;
  752. external_camera_enabled?: boolean;
  753. external_camera_snapshot_url?: string | null;
  754. camera_rotation?: number;
  755. camera_light_auto?: boolean;
  756. plate_detection_enabled?: boolean;
  757. plate_detection_roi?: PlateDetectionROI;
  758. wear_cost_per_hour?: number | null;
  759. wled_config?: WLEDConfig | null;
  760. }
  761. // Plate Detection
  762. export interface PlateDetectionROI {
  763. x: number; // X start % (0.0-1.0)
  764. y: number; // Y start % (0.0-1.0)
  765. w: number; // Width % (0.0-1.0)
  766. h: number; // Height % (0.0-1.0)
  767. }
  768. export interface PlateDetectionResult {
  769. is_empty: boolean;
  770. confidence: number;
  771. difference_percent: number;
  772. message: string;
  773. has_debug_image: boolean;
  774. debug_image_url?: string;
  775. needs_calibration: boolean;
  776. light_warning?: boolean;
  777. reference_count?: number;
  778. max_references?: number;
  779. roi?: PlateDetectionROI;
  780. }
  781. export interface PlateDetectionStatus {
  782. available: boolean;
  783. calibrated: boolean;
  784. reference_count: number;
  785. max_references: number;
  786. message: string;
  787. }
  788. export interface CalibrationResult {
  789. success: boolean;
  790. message: string;
  791. }
  792. export interface PlateReference {
  793. index: number;
  794. label: string;
  795. timestamp: string;
  796. has_image: boolean;
  797. thumbnail_url: string;
  798. }
  799. // Archive types
  800. export interface ArchiveDuplicate {
  801. id: number;
  802. print_name: string | null;
  803. created_at: string;
  804. match_type: 'exact' | 'similar'; // 'exact' = hash match, 'similar' = name match
  805. }
  806. export interface ArchivePrinterMediaFile {
  807. name: string;
  808. path: string;
  809. size: number;
  810. mtime: string | null;
  811. kind: 'timelapse' | 'ipcam';
  812. }
  813. export interface ArchivePrinterMedia {
  814. archive_id: number;
  815. printer_id: number | null;
  816. local_timelapse: { name: string; size: number } | null;
  817. remote_files: ArchivePrinterMediaFile[];
  818. warnings: Array<'printer_missing' | 'timelapse_unavailable' | 'ipcam_unavailable' | 'printer_files_forbidden'>;
  819. }
  820. /** A timelapse editor re-encode, run in the background. */
  821. export interface TimelapseJob {
  822. status: 'running' | 'completed' | 'failed' | 'cancelled';
  823. /** Share done, 0 to 1; null before ffmpeg's first report. */
  824. progress: number | null;
  825. output_path: string | null;
  826. message: string | null;
  827. error: string | null;
  828. }
  829. /** How a post-print outcome verdict reached the archive (#1898). */
  830. export type VerdictSource = 'dialog' | 'link' | 'plate_clear' | 'printer_card' | 'api' | 'reaction';
  831. export interface Archive {
  832. id: number;
  833. printer_id: number | null;
  834. project_id: number | null;
  835. project_name: string | null;
  836. filename: string;
  837. file_path: string;
  838. file_size: number;
  839. content_hash: string | null;
  840. thumbnail_path: string | null;
  841. timelapse_path: string | null;
  842. source_3mf_path: string | null;
  843. f3d_path: string | null;
  844. duplicates: ArchiveDuplicate[] | null;
  845. duplicate_count: number;
  846. duplicate_sequence: number; // 0 = original, 1+ = nth duplicate
  847. original_archive_id: number | null; // ID of the first/original archive
  848. object_count: number | null;
  849. print_name: string | null;
  850. plate_id: number | null; // Selected plate of a multi-plate 3MF (#2603)
  851. print_time_seconds: number | null;
  852. actual_time_seconds: number | null; // Computed from started_at/completed_at
  853. time_accuracy: number | null; // Percentage: 100 = perfect, >100 = faster than estimated
  854. time_estimate_seconds?: number | null; // The latest print's plate estimate, what time_accuracy compares with
  855. filament_used_grams: number | null;
  856. filament_type: string | null;
  857. filament_color: string | null;
  858. layer_height: number | null;
  859. total_layers: number | null;
  860. nozzle_diameter: number | null;
  861. bed_temperature: number | null;
  862. bed_type: string | null; // Build plate type from 3MF (e.g. "Cool Plate", "Textured PEI Plate")
  863. nozzle_temperature: number | null;
  864. sliced_for_model: string | null; // Printer model this file was sliced for
  865. status: string;
  866. started_at: string | null;
  867. completed_at: string | null;
  868. extra_data: Record<string, unknown> | null;
  869. makerworld_url: string | null;
  870. designer: string | null;
  871. external_url: string | null;
  872. is_favorite: boolean;
  873. tags: string | null;
  874. notes: string | null;
  875. cost: number | null;
  876. photos: string[] | null;
  877. failure_reason: string | null;
  878. // Post-print outcome confirmation (#1898)
  879. user_verdict: 'good' | 'reject' | null;
  880. // How the verdict arrived; 'reaction' is written by the Telegram reaction
  881. // handler (#3046) and is labelled here so it reads correctly once that lands.
  882. user_verdict_source: VerdictSource | null;
  883. user_verdict_at: string | null;
  884. confirm_requested: boolean;
  885. // The run whose outcome this shows, when it shows one run of the archive
  886. // (a plate printed on its own) rather than its latest (#1898).
  887. run_id?: number | null;
  888. // The latest print of the archive (among those the caller may see), whose
  889. // figures the per-print fields show (archive redesign).
  890. latest_run_id?: number | null;
  891. // How many videos its prints have; timelapse_path is the latest print's only.
  892. timelapse_count?: number;
  893. quantity: number;
  894. energy_kwh: number | null;
  895. energy_cost: number | null;
  896. wear_cost: number | null; // Printer wear (#694)
  897. created_at: string;
  898. // User tracking (Issue #206)
  899. created_by_id: number | null;
  900. created_by_username: string | null;
  901. // Per-archive run aggregates from PrintLogEntry (#1378)
  902. run_count: number;
  903. last_run_at: string | null;
  904. total_filament_actual_grams: number | null;
  905. successful_run_count: number;
  906. failed_run_count: number;
  907. }
  908. export interface ArchiveSlim {
  909. printer_id: number | null;
  910. print_name: string | null;
  911. print_time_seconds: number | null;
  912. actual_time_seconds: number | null;
  913. filament_used_grams: number | null;
  914. filament_type: string | null;
  915. filament_color: string | null;
  916. status: string;
  917. started_at: string | null;
  918. completed_at: string | null;
  919. cost: number | null;
  920. energy_kwh: number | null;
  921. energy_cost: number | null;
  922. wear_cost: number | null; // Printer wear (#694)
  923. quantity: number;
  924. created_at: string;
  925. }
  926. export interface PrintLogEntry {
  927. id: number;
  928. archive_id: number | null;
  929. print_name: string | null;
  930. plate_id?: number | null;
  931. printer_name: string | null;
  932. printer_id: number | null;
  933. status: string;
  934. started_at: string | null;
  935. completed_at: string | null;
  936. duration_seconds: number | null;
  937. filament_type: string | null;
  938. filament_color: string | null;
  939. filament_used_grams: number | null;
  940. cost: number | null;
  941. energy_kwh: number | null;
  942. energy_cost: number | null;
  943. wear_cost: number | null; // Printer wear (#694)
  944. failure_reason: string | null;
  945. user_verdict?: 'good' | 'reject' | null;
  946. user_verdict_source?: string | null;
  947. confirm_requested?: boolean | null;
  948. duration_unmeasured?: boolean | null;
  949. quantity?: number | null;
  950. // This print's own (archive redesign): note, finish photos, video.
  951. notes?: string | null;
  952. photos?: string[] | null;
  953. timelapse_path?: string | null;
  954. // The slicer's estimate for the plate it printed; in an archive's runs list.
  955. estimate_seconds?: number | null;
  956. estimate_grams?: number | null;
  957. thumbnail_path: string | null;
  958. created_by_id: number | null;
  959. created_by_username: string | null;
  960. created_at: string;
  961. }
  962. export interface PrintLogResponse {
  963. items: PrintLogEntry[];
  964. total: number;
  965. // The print log only: archives of its prints that were deleted.
  966. deleted_archive_ids?: number[];
  967. }
  968. export interface ArchiveStats {
  969. total_prints: number;
  970. successful_prints: number;
  971. failed_prints: number;
  972. cancelled_prints: number;
  973. total_print_time_hours: number;
  974. total_filament_grams: number;
  975. total_cost: number;
  976. prints_by_filament_type: Record<string, number>;
  977. prints_by_printer: Record<string, number>;
  978. // Name each printer id was last recorded under in the print log, so history
  979. // belonging to a deleted printer keeps its label.
  980. printer_names?: Record<string, string>;
  981. average_time_accuracy: number | null;
  982. time_accuracy_by_printer: Record<string, number> | null;
  983. total_energy_kwh: number;
  984. total_energy_cost: number;
  985. total_wear_cost: number; // Printer wear (#694)
  986. // True when a date-filtered total-consumption query is running on incomplete
  987. // snapshot history (e.g. right after upgrade, before hourly snapshots have
  988. // a baseline). UI should explain why the number may undercount.
  989. energy_data_warming_up?: boolean;
  990. }
  991. export interface TagInfo {
  992. name: string;
  993. count: number;
  994. }
  995. export interface FailureAnalysis {
  996. period_days: number;
  997. total_prints: number;
  998. failed_prints: number;
  999. failure_rate: number;
  1000. // Quality dimension (#1898): completed prints the user rejected. Optional
  1001. // so a frontend build against an older backend degrades gracefully.
  1002. rejected_prints?: number;
  1003. yield_rate?: number;
  1004. rejects_by_reason?: Record<string, number>;
  1005. failures_by_reason: Record<string, number>;
  1006. failures_by_filament: Record<string, number>;
  1007. failures_by_printer: Record<string, number>;
  1008. failures_by_hour: Record<number, number>;
  1009. recent_failures: Array<{
  1010. id: number;
  1011. print_name: string;
  1012. failure_reason: string | null;
  1013. filament_type: string | null;
  1014. printer_id: number | null;
  1015. created_at: string | null;
  1016. }>;
  1017. trend: Array<{
  1018. week_start: string;
  1019. total_prints: number;
  1020. failed_prints: number;
  1021. failure_rate: number;
  1022. }>;
  1023. }
  1024. /**
  1025. * Send the browser's zone with calendar dates: the server reads a date as a
  1026. * day in it, else in its own TZ, which shifted every day for a browser away
  1027. * from the server (DB-C12). Only when a date is set.
  1028. */
  1029. function addDayZone(params: URLSearchParams): void {
  1030. if (!params.has('date_from') && !params.has('date_to')) return;
  1031. try {
  1032. const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
  1033. if (zone) params.set('tz', zone);
  1034. } catch {
  1035. // No Intl zone: the server's TZ applies.
  1036. }
  1037. }
  1038. export interface BulkUploadResult {
  1039. uploaded: number;
  1040. failed: number;
  1041. /** `index` is the file's position in the request. */
  1042. results: Array<{ index: number; filename: string; id: number; status: string }>;
  1043. errors: Array<{ index: number; filename: string; error: string }>;
  1044. }
  1045. // Archive Comparison types
  1046. export interface ComparisonArchiveInfo {
  1047. id: number;
  1048. print_name: string;
  1049. status: string;
  1050. created_at: string | null;
  1051. printer_id: number | null;
  1052. project_name: string | null;
  1053. }
  1054. export interface ComparisonField {
  1055. field: string;
  1056. label: string;
  1057. unit: string | null;
  1058. values: (string | number | null)[];
  1059. raw_values: (string | number | null)[];
  1060. has_difference: boolean;
  1061. }
  1062. export interface SuccessCorrelationInsight {
  1063. field: string;
  1064. label: string;
  1065. insight: string;
  1066. success_avg?: number;
  1067. failed_avg?: number;
  1068. success_values?: string[];
  1069. failed_values?: string[];
  1070. }
  1071. export interface SuccessCorrelation {
  1072. has_both_outcomes: boolean;
  1073. message?: string;
  1074. successful_count?: number;
  1075. failed_count?: number;
  1076. insights?: SuccessCorrelationInsight[];
  1077. }
  1078. export interface ArchiveComparison {
  1079. archives: ComparisonArchiveInfo[];
  1080. comparison: ComparisonField[];
  1081. differences: ComparisonField[];
  1082. success_correlation: SuccessCorrelation;
  1083. }
  1084. // Project types
  1085. export interface ProjectStats {
  1086. total_archives: number;
  1087. total_items: number; // Sum of quantities (total items printed)
  1088. completed_prints: number; // Sum of quantities for completed prints (parts)
  1089. failed_prints: number;
  1090. queued_prints: number;
  1091. in_progress_prints: number;
  1092. total_print_time_hours: number;
  1093. total_filament_grams: number;
  1094. progress_percent: number | null; // Plates progress (total_archives / target_count)
  1095. parts_progress_percent: number | null; // Parts progress (completed_prints / target_parts_count)
  1096. estimated_cost: number;
  1097. total_energy_kwh: number;
  1098. total_energy_cost: number;
  1099. total_wear_cost: number; // Printer wear (#694)
  1100. remaining_prints: number | null; // Remaining plates
  1101. remaining_parts: number | null; // Remaining parts
  1102. bom_total_items: number;
  1103. bom_completed_items: number;
  1104. bom_cost: number;
  1105. }
  1106. // A sub-project as listed on its parent's page. The figures cover the child's
  1107. // own subtree, so the listed rows add up to the parent's roll-up minus the
  1108. // parent's own prints (#1264).
  1109. export interface ProjectChildPreview {
  1110. id: number;
  1111. name: string;
  1112. color: string | null;
  1113. status: string;
  1114. progress_percent: number | null;
  1115. descendant_count: number;
  1116. total_archives: number;
  1117. completed_prints: number;
  1118. total_print_time_hours: number;
  1119. total_filament_grams: number;
  1120. total_cost: number; // Filament + energy + BOM, matching the parent's cost card
  1121. }
  1122. export interface Project {
  1123. id: number;
  1124. name: string;
  1125. description: string | null;
  1126. color: string | null;
  1127. status: string; // active, completed, archived
  1128. target_count: number | null; // Target number of plates/print jobs
  1129. target_parts_count: number | null; // Target number of parts/objects
  1130. target_sets: number | null; // Copies-per-file target (#1897)
  1131. notes: string | null;
  1132. attachments: ProjectAttachment[] | null;
  1133. tags: string | null;
  1134. due_date: string | null;
  1135. priority: string; // low, normal, high, urgent
  1136. budget: number | null;
  1137. is_template: boolean;
  1138. template_source_id: number | null;
  1139. parent_id: number | null;
  1140. parent_name: string | null;
  1141. children: ProjectChildPreview[];
  1142. descendant_count: number; // Sub-projects at any depth beneath this one (#1264)
  1143. created_at: string;
  1144. updated_at: string;
  1145. stats?: ProjectStats;
  1146. // This project's numbers combined with every sub-project's. Null when there
  1147. // are none, since it would only repeat `stats` (#1264).
  1148. rollup_stats?: ProjectStats | null;
  1149. url: string | null; // External link rendered next to project name on the card (#1155)
  1150. cover_image_filename: string | null; // Filename within project attachments dir (#1155)
  1151. }
  1152. export interface ProjectAttachment {
  1153. filename: string;
  1154. original_name: string;
  1155. size: number;
  1156. uploaded_at: string;
  1157. }
  1158. // Completed-run count for one library file inside a project (#1897)
  1159. export interface ProjectFileProgress {
  1160. file_id: number;
  1161. completed_count: number;
  1162. }
  1163. export interface ArchivePreview {
  1164. id: number;
  1165. print_name: string | null;
  1166. thumbnail_path: string | null;
  1167. status: string;
  1168. filament_type: string | null;
  1169. filament_color: string | null;
  1170. }
  1171. export interface ProjectListItem {
  1172. id: number;
  1173. name: string;
  1174. description: string | null;
  1175. color: string | null;
  1176. status: string;
  1177. target_count: number | null; // Target number of plates/print jobs
  1178. target_parts_count: number | null; // Target number of parts/objects
  1179. target_sets: number | null; // #1897 — the shared edit dialog seeds itself from this
  1180. budget: number | null;
  1181. tags: string | null; // #2536 — the shared edit dialog seeds itself from this
  1182. due_date: string | null; // #2536
  1183. priority: string; // #2536
  1184. created_at: string;
  1185. archive_count: number; // Number of print jobs (plates)
  1186. total_items: number; // Sum of quantities (total items printed, including failed)
  1187. completed_count: number; // Sum of quantities for completed prints only (parts)
  1188. failed_count: number; // Sum of quantities for failed prints
  1189. queue_count: number;
  1190. progress_percent: number | null; // Plates progress
  1191. parent_id: number | null; // #1264 — set when this is a sub-project
  1192. child_count: number; // #1264 — direct sub-projects only
  1193. archives: ArchivePreview[];
  1194. url: string | null; // #1155
  1195. cover_image_filename: string | null; // #1155
  1196. }
  1197. export interface ProjectCreate {
  1198. name: string;
  1199. description?: string;
  1200. color?: string;
  1201. target_count?: number;
  1202. target_parts_count?: number;
  1203. target_sets?: number;
  1204. notes?: string;
  1205. tags?: string;
  1206. due_date?: string;
  1207. priority?: string;
  1208. budget?: number | null;
  1209. parent_id?: number;
  1210. url?: string | null; // #1155
  1211. }
  1212. export interface ProjectUpdate {
  1213. name?: string;
  1214. description?: string;
  1215. color?: string;
  1216. status?: string;
  1217. target_count?: number;
  1218. target_parts_count?: number;
  1219. target_sets?: number | null; // #1897 — explicit null clears the copies-per-file target
  1220. notes?: string;
  1221. tags?: string | null; // #2536 — explicit null clears the tags
  1222. due_date?: string | null; // #2536 — explicit null clears the due date
  1223. priority?: string;
  1224. budget?: number | null;
  1225. parent_id?: number;
  1226. url?: string | null; // #1155 — explicit null clears the URL
  1227. }
  1228. // BOM Types - Tracks sourced/purchased parts (hardware, electronics, etc.)
  1229. export interface BOMItem {
  1230. id: number;
  1231. project_id: number;
  1232. name: string;
  1233. quantity_needed: number;
  1234. quantity_acquired: number;
  1235. unit_price: number | null;
  1236. sourcing_url: string | null;
  1237. archive_id: number | null;
  1238. archive_name: string | null;
  1239. stl_filename: string | null;
  1240. remarks: string | null;
  1241. sort_order: number;
  1242. is_complete: boolean;
  1243. created_at: string;
  1244. updated_at: string;
  1245. }
  1246. export interface BOMItemCreate {
  1247. name: string;
  1248. quantity_needed?: number;
  1249. unit_price?: number;
  1250. sourcing_url?: string;
  1251. archive_id?: number;
  1252. stl_filename?: string;
  1253. remarks?: string;
  1254. }
  1255. export interface BOMItemUpdate {
  1256. name?: string;
  1257. quantity_needed?: number;
  1258. quantity_acquired?: number;
  1259. unit_price?: number;
  1260. sourcing_url?: string;
  1261. archive_id?: number;
  1262. stl_filename?: string;
  1263. remarks?: string;
  1264. }
  1265. // Project Export/Import Types
  1266. export interface BOMItemExport {
  1267. name: string;
  1268. quantity_needed: number;
  1269. quantity_acquired: number;
  1270. unit_price: number | null;
  1271. sourcing_url: string | null;
  1272. stl_filename: string | null;
  1273. remarks: string | null;
  1274. }
  1275. export interface LinkedFolderExport {
  1276. name: string;
  1277. }
  1278. export interface ProjectExport {
  1279. name: string;
  1280. description: string | null;
  1281. color: string | null;
  1282. status: string;
  1283. target_count: number | null;
  1284. target_parts_count: number | null;
  1285. target_sets: number | null; // #1897
  1286. notes: string | null;
  1287. tags: string | null;
  1288. due_date: string | null;
  1289. priority: string;
  1290. budget: number | null;
  1291. bom_items: BOMItemExport[];
  1292. linked_folders: LinkedFolderExport[];
  1293. }
  1294. export interface ProjectImport {
  1295. name: string;
  1296. description?: string;
  1297. color?: string;
  1298. status?: string;
  1299. target_count?: number;
  1300. target_parts_count?: number;
  1301. target_sets?: number; // #1897
  1302. notes?: string;
  1303. tags?: string;
  1304. due_date?: string;
  1305. priority?: string;
  1306. budget?: number | null;
  1307. bom_items?: BOMItemExport[];
  1308. linked_folders?: LinkedFolderExport[];
  1309. }
  1310. // Timeline Types
  1311. export interface TimelineEvent {
  1312. event_type: string;
  1313. timestamp: string;
  1314. title: string;
  1315. description: string | null;
  1316. metadata: Record<string, unknown> | null;
  1317. }
  1318. // API Key types
  1319. export interface APIKey {
  1320. id: number;
  1321. name: string;
  1322. key_prefix: string;
  1323. user_id: number | null; // Owner; null on legacy keys created before per-user ownership (#1182)
  1324. can_queue: boolean;
  1325. can_control_printer: boolean;
  1326. can_read_status: boolean;
  1327. can_manage_library: boolean;
  1328. can_manage_inventory: boolean;
  1329. can_manage_maintenance: boolean;
  1330. can_manage_archives: boolean;
  1331. can_manage_projects: boolean;
  1332. can_access_cloud: boolean;
  1333. can_update_energy_cost: boolean;
  1334. can_send_notifications: boolean;
  1335. printer_ids: number[] | null;
  1336. enabled: boolean;
  1337. last_used: string | null;
  1338. created_at: string;
  1339. expires_at: string | null;
  1340. }
  1341. export interface APIKeyCreate {
  1342. name: string;
  1343. can_queue?: boolean;
  1344. can_control_printer?: boolean;
  1345. can_read_status?: boolean;
  1346. can_manage_library?: boolean;
  1347. can_manage_inventory?: boolean;
  1348. can_manage_maintenance?: boolean;
  1349. can_manage_archives?: boolean;
  1350. can_manage_projects?: boolean;
  1351. can_access_cloud?: boolean;
  1352. can_update_energy_cost?: boolean;
  1353. can_send_notifications?: boolean;
  1354. printer_ids?: number[] | null;
  1355. expires_at?: string | null;
  1356. }
  1357. export interface APIKeyCreateResponse extends APIKey {
  1358. key: string; // Full key, only shown on creation
  1359. }
  1360. /**
  1361. * Tri-state calibration option (BambuStudio parity): "off" never runs it,
  1362. * "on" forces it every print, "auto" lets the printer skip it if it was done
  1363. * recently. Used by bed_levelling, flow_cali, and nozzle_offset_cali.
  1364. */
  1365. export type CalibrationMode = 'off' | 'on' | 'auto';
  1366. // Settings types
  1367. export interface AppSettings {
  1368. auto_archive: boolean;
  1369. save_thumbnails: boolean;
  1370. capture_finish_photo: boolean;
  1371. finish_photo_restore_plate: boolean;
  1372. default_filament_cost: number;
  1373. currency: string;
  1374. energy_cost_per_kwh: number;
  1375. energy_tracking_mode: 'print' | 'total';
  1376. // Where the electricity price comes from (#1251). With 'homeassistant',
  1377. // energy_cost_per_kwh holds the sensor's last reading and is read-only.
  1378. energy_price_source: 'fixed' | 'homeassistant';
  1379. energy_price_ha_entity: string;
  1380. check_updates: boolean;
  1381. check_printer_firmware: boolean;
  1382. include_beta_updates: boolean;
  1383. // Announcements from the Bambuddy maintainers (a signed file on GitHub).
  1384. announcements_enabled?: boolean;
  1385. announcements_all_users?: boolean;
  1386. // #1589: false hides the local username/password form on the login page;
  1387. // BAMBUDDY_LOCAL_LOGIN=true on the server flips the reported value back to
  1388. // true so the env-var recovery path is visible to the SPA.
  1389. local_login_enabled: boolean;
  1390. language: string;
  1391. notification_language: string;
  1392. // AMS threshold settings
  1393. ams_humidity_good: number; // <= this is green
  1394. ams_humidity_fair: number; // <= this is orange, > is red
  1395. ams_temp_good: number; // <= this is green/blue
  1396. ams_temp_fair: number; // <= this is orange, > is red
  1397. // Separate from the display band (#2905). null = unset, which the backend
  1398. // resolves to ams_temp_fair so existing installs are unaffected.
  1399. ams_temp_alarm: number | null;
  1400. ams_history_retention_days: number; // days to keep AMS sensor history
  1401. printer_sensor_history_retention_days?: number; // days to keep printer heater history
  1402. // Queue auto-drying settings
  1403. queue_drying_enabled: boolean; // Auto-dry AMS between queued prints
  1404. queue_drying_block: boolean; // Block queue until drying completes
  1405. ambient_drying_enabled: boolean; // Auto-dry idle printers based on humidity regardless of queue
  1406. ambient_drying_sustained_minutes: number; // Minutes humidity must stay above threshold before ambient auto-dry starts (0 = instant)
  1407. print_drying_enabled: boolean; // Continue drying while a print is running on capable hardware
  1408. drying_presets: string; // JSON blob of drying presets per filament type
  1409. ams_humidity_thresholds: string; // JSON blob of per-filament humidity thresholds (#1605)
  1410. gcode_snippets: string; // JSON: per-model G-code injection snippets
  1411. // Scheduled local backup
  1412. local_backup_enabled: boolean;
  1413. local_backup_schedule: string;
  1414. local_backup_time: string;
  1415. local_backup_retention: number;
  1416. local_backup_path: string;
  1417. // Print modal settings
  1418. per_printer_mapping_expanded: boolean; // Whether custom mapping is expanded by default in print modal
  1419. // Date/time format settings
  1420. date_format: 'system' | 'us' | 'eu' | 'iso';
  1421. time_format: 'system' | '12h' | '24h';
  1422. // Filament tracking
  1423. disable_filament_warnings: boolean; // Disable filament warnings (print insufficiency and assignment mismatch)
  1424. prefer_lowest_filament: boolean; // When multiple spools match, prefer lowest remaining filament
  1425. 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
  1426. 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
  1427. spoolman_url: string;
  1428. // Default printer
  1429. default_printer_id: number | null;
  1430. pipeline_max_copies: number;
  1431. // Dark mode theme settings
  1432. dark_style: 'classic' | 'glow' | 'vibrant';
  1433. dark_background: 'neutral' | 'warm' | 'cool' | 'oled' | 'slate' | 'forest';
  1434. dark_accent: 'green' | 'teal' | 'blue' | 'orange' | 'purple' | 'red';
  1435. // Light mode theme settings
  1436. light_style: 'classic' | 'glow' | 'vibrant';
  1437. light_background: 'neutral' | 'warm' | 'cool';
  1438. light_accent: 'green' | 'teal' | 'blue' | 'orange' | 'purple' | 'red';
  1439. // FTP retry settings
  1440. ftp_retry_enabled: boolean;
  1441. ftp_retry_count: number;
  1442. ftp_retry_delay: number;
  1443. ftp_timeout: number;
  1444. // MQTT relay settings
  1445. mqtt_enabled: boolean;
  1446. mqtt_broker: string;
  1447. mqtt_port: number;
  1448. mqtt_username: string;
  1449. mqtt_password: string;
  1450. mqtt_topic_prefix: string;
  1451. mqtt_use_tls: boolean;
  1452. // External URL for notifications
  1453. external_url: string;
  1454. // Directory holding docker-compose.yml, shown in the update instructions (#2664)
  1455. docker_compose_dir: string;
  1456. // Home Assistant integration
  1457. ha_enabled: boolean;
  1458. ha_url: string;
  1459. ha_token: string;
  1460. ha_url_from_env: boolean;
  1461. ha_token_from_env: boolean;
  1462. ha_env_managed: boolean;
  1463. // File Manager / Library settings
  1464. library_disk_warning_gb: number;
  1465. // Camera view settings
  1466. camera_view_mode: 'window' | 'embedded';
  1467. // Chamber light while the camera is in use (#1655)
  1468. camera_light_mode: 'off' | 'all' | 'selected';
  1469. camera_light_delay: number; // seconds a snapshot waits after the light came on
  1470. // Preferred slicer (server-side API / sidecar)
  1471. preferred_slicer: 'bambu_studio' | 'orcaslicer';
  1472. // Desktop "Open in Slicer" override (#1329). Null inherits from
  1473. // preferred_slicer so existing installs behave identically.
  1474. open_in_slicer: 'bambu_studio' | 'orcaslicer' | null;
  1475. // Where slicing runs, independent of which slicer binary the sidecar drives.
  1476. // Only 'sidecar' is implemented today; see lib/sliceEngines.ts.
  1477. slice_engine: 'sidecar' | 'browser';
  1478. // Use the slicer-API sidecar for slicing (in-app modal) vs desktop URI scheme
  1479. use_slicer_api: boolean;
  1480. // Per-install sidecar URLs. Empty string falls back to the env defaults.
  1481. orcaslicer_api_url: string;
  1482. bambu_studio_api_url: string;
  1483. // Minutes of silence from the sidecar before a slice is abandoned. Bounds
  1484. // stalls, not total slicing time — a model that keeps reporting progress
  1485. // runs to completion however long it takes.
  1486. slicer_stall_timeout_minutes: number;
  1487. // Prometheus metrics
  1488. prometheus_enabled: boolean;
  1489. prometheus_token: string;
  1490. // Bed cooled threshold
  1491. bed_cooled_threshold: number;
  1492. // Minutes before a slicer pause to send the pause heads-up (#2984)
  1493. pause_warning_minutes: number;
  1494. // Inventory low stock threshold
  1495. low_stock_threshold: number;
  1496. // Session policy (#1706) — admin-set ceiling, hours, [1, 720]
  1497. session_max_hours: number;
  1498. // User email notifications toggle
  1499. user_notifications_enabled: boolean;
  1500. // Default print options
  1501. default_bed_levelling: CalibrationMode;
  1502. default_flow_cali: CalibrationMode;
  1503. default_vibration_cali: boolean;
  1504. default_layer_inspect: boolean;
  1505. default_timelapse: boolean;
  1506. default_nozzle_offset_cali: CalibrationMode;
  1507. // Default for the per-job "ask for outcome afterwards" toggle (#1898)
  1508. default_confirm_outcome: boolean;
  1509. // Also ask for prints Bambuddy archived but did not dispatch (#1898)
  1510. confirm_outcome_external_prints: boolean;
  1511. // Count unanswered outcome prompts as "good" when the plate is released (#1898)
  1512. confirm_default_good_on_plate_clear: boolean;
  1513. // Staggered batch start defaults
  1514. stagger_group_size: number;
  1515. stagger_interval_minutes: number;
  1516. // Finance budget reset window
  1517. billing_enabled: boolean;
  1518. printer_kill_switch_enabled: boolean;
  1519. finance_budget_reset_day: number;
  1520. finance_budget_reset_timezone: string;
  1521. // Plate-clear confirmation
  1522. require_plate_clear: boolean;
  1523. // Shortest job first scheduling
  1524. queue_shortest_first: boolean;
  1525. // How many printers the queue may upload to at once (#2555). 1 restores the
  1526. // old strictly-serial behaviour, where every printer waited out every other
  1527. // printer's transfer.
  1528. queue_max_concurrent_uploads: number;
  1529. // Preheat / heat-soak before queued prints (#1468). Master toggle is the
  1530. // default for new queue items; per-item PrintQueueItem.preheat_override can
  1531. // flip the decision per print. Chamber target derives from the loaded AMS
  1532. // filament types via preheat_filament_targets (JSON map of type → °C, max
  1533. // across loaded slots); the per-item override field bypasses derivation.
  1534. preheat_enabled: boolean;
  1535. preheat_filament_targets: string;
  1536. preheat_max_wait_seconds: number;
  1537. preheat_soak_seconds: number;
  1538. queue_keep_bed_warm: boolean;
  1539. queue_keep_warm_bed_temp: number;
  1540. queue_keep_warm_max_minutes: number;
  1541. // User-configurable presets for the printer-card popovers (JSON arrays of 3 ints).
  1542. // Empty string = use built-in defaults.
  1543. nozzle_temp_presets: string;
  1544. bed_temp_presets: string;
  1545. chamber_temp_presets: string;
  1546. fan_speed_presets: string;
  1547. // Default sidebar order (admin-set for all users)
  1548. default_sidebar_order: string;
  1549. // LDAP authentication
  1550. ldap_enabled: boolean;
  1551. ldap_server_url: string;
  1552. ldap_bind_dn: string;
  1553. ldap_bind_password: string;
  1554. ldap_search_base: string;
  1555. ldap_user_filter: string;
  1556. ldap_security: string;
  1557. ldap_group_mapping: string;
  1558. ldap_auto_provision: boolean;
  1559. ldap_default_group: string;
  1560. obico_enabled: boolean;
  1561. obico_ml_url: string;
  1562. bambuddy_internal_url: string;
  1563. obico_ml_token: string;
  1564. obico_sensitivity: 'low' | 'medium' | 'high';
  1565. obico_action: 'notify' | 'pause' | 'pause_and_off';
  1566. obico_poll_interval: number;
  1567. obico_enabled_printers: string;
  1568. octoeverywhere_enabled: boolean;
  1569. octoeverywhere_api_key: string;
  1570. octoeverywhere_api_key_configured: boolean;
  1571. octoeverywhere_confidence: OctoEverywhereConfidence;
  1572. octoeverywhere_action: 'notify' | 'pause' | 'pause_and_off';
  1573. octoeverywhere_enabled_printers: string;
  1574. octoeverywhere_poll_interval: number;
  1575. // Inventory forecasting global lead time
  1576. forecast_global_lead_time_days: number;
  1577. location_sensor_poll_interval: number;
  1578. // JSON map of sensor category → {alertAbove, alertBelow, notifyOnAlert},
  1579. // seeding new storage-location sensor bindings. Empty = built-in defaults.
  1580. // Server-backed so two admins seed the same alert rules and a restore
  1581. // brings them back; see utils/locationSensorDefaults.ts.
  1582. location_sensor_alert_defaults: string;
  1583. }
  1584. export type AppSettingsUpdate = Partial<Omit<AppSettings, 'octoeverywhere_api_key_configured'>>;
  1585. // Settings as a page sees them: everything from GET /settings for a user who
  1586. // may read it, otherwise the subset /settings/ui-preferences and
  1587. // /settings/ui-flags serve, which reports G-code snippets only as set or not.
  1588. export type UiSettings = Partial<AppSettings> & { has_gcode_snippets?: boolean };
  1589. // MQTT relay status
  1590. export interface MQTTStatus {
  1591. enabled: boolean;
  1592. connected: boolean;
  1593. broker: string;
  1594. port: number;
  1595. topic_prefix: string;
  1596. }
  1597. // Cloud types
  1598. export interface CloudAuthStatus {
  1599. is_authenticated: boolean;
  1600. email: string | null;
  1601. region?: 'global' | 'china' | null;
  1602. /** A token is stored but Bambu no longer accepts it — tell the user why the login form is back. */
  1603. sign_in_expired?: boolean;
  1604. }
  1605. export interface CloudLoginResponse {
  1606. success: boolean;
  1607. needs_verification: boolean;
  1608. message: string;
  1609. verification_type?: 'email' | 'totp' | null;
  1610. tfa_key?: string | null;
  1611. /**
  1612. * Machine-readable cause of a failure. 'captcha' means Bambu's anti-abuse
  1613. * layer is challenging this network and no credential will be accepted until
  1614. * it clears — the UI must explain that in place rather than toast `message`.
  1615. */
  1616. reason?: 'captcha' | string | null;
  1617. }
  1618. // Orca Cloud types — paste-flow PKCE handshake against auth.orcaslicer.com.
  1619. // See backend/app/services/orca_cloud.py for the deep dive on why this
  1620. // flow is paste-based rather than callback-based.
  1621. export interface OrcaDeviceStartResponse {
  1622. user_code: string;
  1623. verification_uri: string;
  1624. verification_uri_complete: string;
  1625. interval: number;
  1626. expires_in: number;
  1627. }
  1628. export type OrcaDevicePollStatus =
  1629. | 'authorization_pending'
  1630. | 'slow_down'
  1631. | 'access_denied'
  1632. | 'expired_token'
  1633. | 'complete';
  1634. export interface OrcaDevicePollResponse {
  1635. status: OrcaDevicePollStatus;
  1636. connected: boolean;
  1637. email: string | null;
  1638. user_id: string | null;
  1639. }
  1640. export interface OrcaAuthStatusResponse {
  1641. connected: boolean;
  1642. email: string | null;
  1643. user_id: string | null;
  1644. }
  1645. // Orca profiles are shaped to match Bambu Cloud's SlicerSetting on the wire
  1646. // so the frontend can use the same visual components for both surfaces (cards,
  1647. // grouped sections, filter bar). Backend handles the source-specific
  1648. // transformation in routes/orca_cloud.py::_orca_to_setting.
  1649. export interface OrcaProfileMeta {
  1650. setting_id: string;
  1651. name: string;
  1652. type: string;
  1653. version: string | null;
  1654. user_id: string | null;
  1655. updated_time: string | null;
  1656. is_custom: boolean;
  1657. }
  1658. export interface OrcaProfileListResponse {
  1659. filament: OrcaProfileMeta[];
  1660. printer: OrcaProfileMeta[];
  1661. process: OrcaProfileMeta[];
  1662. }
  1663. export interface OrcaProfileDetail {
  1664. setting_id: string;
  1665. name: string;
  1666. type: string;
  1667. version: string | null;
  1668. base_id: string | null;
  1669. update_time: string | null;
  1670. setting: Record<string, unknown>;
  1671. }
  1672. // MakerWorld integration. Full metadata/instance shapes come back as
  1673. // Record<string, unknown> — MakerWorld's API adds fields over time, so we
  1674. // pass them through verbatim rather than maintaining a brittle mirror.
  1675. export interface MakerworldStatus {
  1676. has_cloud_token: boolean;
  1677. can_download: boolean;
  1678. /** A token is stored but Bambu rejected it — downloads will fail until the user signs in again. */
  1679. sign_in_expired?: boolean;
  1680. }
  1681. export interface MakerworldResolvedModel {
  1682. model_id: number;
  1683. profile_id: number | null;
  1684. design: Record<string, unknown>;
  1685. instances: Array<Record<string, unknown>>;
  1686. already_imported_library_ids: number[];
  1687. }
  1688. export interface MakerworldImportResponse {
  1689. library_file_id: number;
  1690. filename: string;
  1691. folder_id: number | null;
  1692. profile_id: number | null;
  1693. was_existing: boolean;
  1694. }
  1695. export interface MakerworldRecentImport {
  1696. library_file_id: number;
  1697. filename: string;
  1698. folder_id: number | null;
  1699. thumbnail_path: string | null;
  1700. source_url: string | null;
  1701. created_at: string;
  1702. }
  1703. // Manyfold integration (#1471): a self-hosted model library, browsed and
  1704. // searched, with single files imported into the library.
  1705. export interface ManyfoldConfig {
  1706. url: string;
  1707. client_id: string;
  1708. /** The secret itself is never returned. */
  1709. has_client_secret: boolean;
  1710. configured: boolean;
  1711. }
  1712. export interface ManyfoldConfigInput {
  1713. url: string;
  1714. client_id: string;
  1715. /** Empty or left out keeps the stored secret. */
  1716. client_secret?: string;
  1717. }
  1718. export interface ManyfoldStatus {
  1719. configured: boolean;
  1720. url: string;
  1721. }
  1722. export interface ManyfoldModelSummary {
  1723. id: string;
  1724. name: string;
  1725. }
  1726. export interface ManyfoldModelList {
  1727. total: number;
  1728. page: number;
  1729. has_next: boolean;
  1730. has_previous: boolean;
  1731. models: ManyfoldModelSummary[];
  1732. }
  1733. export interface ManyfoldFile {
  1734. id: string;
  1735. name: string;
  1736. mime: string;
  1737. importable: boolean;
  1738. /** Set while the file imported earlier is still in the library. */
  1739. library_file: { id: number; filename: string; folder_id: number | null } | null;
  1740. }
  1741. export interface ManyfoldModel {
  1742. id: string;
  1743. name: string;
  1744. caption: string | null;
  1745. description: string | null;
  1746. license: string | null;
  1747. tags: string[];
  1748. url: string;
  1749. has_preview: boolean;
  1750. files: ManyfoldFile[];
  1751. }
  1752. export interface ManyfoldImportResponse {
  1753. library_file_id: number;
  1754. filename: string;
  1755. folder_id: number | null;
  1756. was_existing: boolean;
  1757. }
  1758. export interface SlicerSetting {
  1759. setting_id: string;
  1760. name: string;
  1761. type: string;
  1762. version: string | null;
  1763. user_id: string | null;
  1764. updated_time: string | null;
  1765. is_custom: boolean;
  1766. // The id Bambu Studio puts in an AMS slot for the preset; not derivable
  1767. // from setting_id for every preset (#3387). Absent from older backends.
  1768. filament_id?: string | null;
  1769. }
  1770. export interface SpoolCatalogEntry {
  1771. id: number;
  1772. name: string;
  1773. weight: number;
  1774. is_default: boolean;
  1775. }
  1776. export interface StorageLocation {
  1777. id: number;
  1778. name: string;
  1779. identifier: string | null;
  1780. spool_count: number;
  1781. created_at: string;
  1782. updated_at: string;
  1783. }
  1784. export interface ColorCatalogEntry {
  1785. id: number;
  1786. manufacturer: string;
  1787. color_name: string;
  1788. hex_color: string;
  1789. material: string | null;
  1790. is_default: boolean;
  1791. // #1154: optional multi-colour gradient stops + visual effect.
  1792. extra_colors?: string | null;
  1793. effect_type?: string | null;
  1794. }
  1795. export interface SlicerSettingsResponse {
  1796. filament: SlicerSetting[];
  1797. printer: SlicerSetting[];
  1798. process: SlicerSetting[];
  1799. }
  1800. export interface SlicerSettingDetail {
  1801. message?: string | null;
  1802. code?: string | null;
  1803. error?: string | null;
  1804. public: boolean;
  1805. version?: string | null;
  1806. type: string;
  1807. name: string;
  1808. update_time?: string | null;
  1809. nickname?: string | null;
  1810. base_id?: string | null;
  1811. setting: Record<string, unknown>;
  1812. filament_id?: string | null;
  1813. setting_id?: string | null;
  1814. }
  1815. export interface SlicerSettingCreate {
  1816. type: string; // 'filament', 'print', or 'printer'
  1817. name: string;
  1818. base_id: string;
  1819. setting: Record<string, unknown>;
  1820. }
  1821. export interface SlicerSettingUpdate {
  1822. name?: string;
  1823. setting?: Record<string, unknown>;
  1824. }
  1825. export interface SlicerSettingDeleteResponse {
  1826. success: boolean;
  1827. message: string;
  1828. }
  1829. // Built-in filament fallback (static table from backend)
  1830. export interface BuiltinFilament {
  1831. filament_id: string;
  1832. name: string;
  1833. }
  1834. // Slice request/response — POST /library/files/{id}/slice and /archives/{id}/slice
  1835. //
  1836. // Two preset shapes are accepted per slot:
  1837. // - Legacy bare integer ids (`*_preset_id`) — pre-cloud-tier clients.
  1838. // - Source-aware refs (`*_preset: PresetRef`) — new SliceModal that picks
  1839. // across cloud / local / standard tiers. Source-aware refs win when both
  1840. // are present in the same payload.
  1841. export type PresetSource = 'orca_cloud' | 'cloud' | 'local' | 'standard';
  1842. export interface PresetRef {
  1843. source: PresetSource;
  1844. id: string;
  1845. }
  1846. /**
  1847. * Why a preset's effective values are unavailable.
  1848. *
  1849. * `sidecar_outdated` is the one that matters in practice: an install pulls its
  1850. * sidecar as `SIDECAR_TAG:-latest` regardless of which Bambuddy channel it is
  1851. * on, so a user can perfectly well be running a current Bambuddy against a
  1852. * sidecar that predates this endpoint. That has a one-line fix, and saying so
  1853. * beats a generic "could not read the values".
  1854. */
  1855. export type SlicerPresetValuesReason =
  1856. | 'ok'
  1857. | 'sidecar_outdated'
  1858. | 'sidecar_unavailable'
  1859. | 'not_configured'
  1860. | 'preset_unresolved';
  1861. export interface SlicerPresetValues {
  1862. /** False when the sidecar could not supply values; `values` is then empty. */
  1863. resolved: boolean;
  1864. /** Flattened key -> value map, in the string forms a process preset stores. */
  1865. values: Record<string, string | string[]>;
  1866. reason: SlicerPresetValuesReason;
  1867. }
  1868. export interface SliceRequest {
  1869. printer_preset_id?: number;
  1870. process_preset_id?: number;
  1871. filament_preset_id?: number;
  1872. printer_preset?: PresetRef;
  1873. process_preset?: PresetRef;
  1874. filament_preset?: PresetRef;
  1875. // Multi-color: one PresetRef per plate slot, in plate order. Always
  1876. // preferred over the singular `filament_preset` when both are sent; the
  1877. // backend validator promotes a singular into a one-element list when this
  1878. // is omitted, so legacy single-color clients keep working unchanged.
  1879. filament_presets?: PresetRef[];
  1880. // Per-slot filament colour as `#RRGGBB` / `#RRGGBBAA`, same plate order as
  1881. // `filament_presets` (#2977). Neither slicer stores a colour on a filament
  1882. // *preset* -- it is a per-project property -- so without this every sliced
  1883. // file records the CLI's built-in #00AE42 and the print dialog reports a
  1884. // colour mismatch against whatever is loaded in the AMS. An empty string in
  1885. // any position hands that slot back to the backend's fallback chain (the
  1886. // preset's own default_filament_colour, then the source plate's colour).
  1887. filament_colours?: string[];
  1888. plate?: number;
  1889. export_3mf?: boolean;
  1890. // Build-plate override (#1337). When omitted, the slicer uses the process
  1891. // preset's curr_bed_type as-is. A name from BambuStudio / OrcaSlicer's
  1892. // enum: "Cool Plate", "Engineering Plate", "High Temp Plate" (Smooth PEI),
  1893. // "Textured PEI Plate", "Supertack Plate", or OrcaSlicer's "Textured Cool
  1894. // Plate" (refused when Bambu Studio slices); the backend refuses others (#3359).
  1895. bed_type?: string | null;
  1896. // "Slice as designed" (#2611). 3MF only: slice using the file's embedded
  1897. // project_settings.config (the designer's own wall count, infill, etc.)
  1898. // instead of the picked profile triplet. The preset refs above are still
  1899. // required by the backend validator but go unused on this path.
  1900. use_embedded_settings?: boolean;
  1901. // Process settings the user edited in the slice modal's settings panel,
  1902. // already serialised into the string forms a process preset stores ("1" for
  1903. // a bool, "20%" for a percent, a list for the per-extruder vectors). Patched
  1904. // onto the resolved process JSON after the designer's carried tweaks, so an
  1905. // explicit choice here wins. Omitted when the panel is untouched.
  1906. process_overrides?: Record<string, string | string[]>;
  1907. // Design settings carried from the source 3MF (#2622) — a list of keys the
  1908. // file flags as changed from the system preset, not values.
  1909. design_overrides?: string[];
  1910. // Layout passes the slicer runs before slicing (#2548), both off by
  1911. // default because they move or rotate the objects the user laid out.
  1912. // Unlike the fields above these are CLI actions rather than profile
  1913. // values, so they apply on the embedded-settings path too.
  1914. auto_orient?: boolean;
  1915. auto_arrange?: boolean;
  1916. }
  1917. // GET /api/v1/slicer/presets — unified listing across cloud / local / standard.
  1918. export type SlicerCloudStatus = 'ok' | 'not_authenticated' | 'expired' | 'unreachable';
  1919. export interface UnifiedPreset {
  1920. id: string;
  1921. name: string;
  1922. source: PresetSource;
  1923. // Populated for the filament slot only — used by the SliceModal multi-color
  1924. // pre-pick to score presets against each plate slot's required (type,
  1925. // colour). Optional because the bundled / standard tier rarely carries a
  1926. // colour (colour is a runtime spool attribute on Bambu) and older API
  1927. // responses pre-date these fields entirely.
  1928. filament_type?: string | null;
  1929. filament_colour?: string | null;
  1930. // Printer-preset names a process / filament preset declares itself
  1931. // compatible with. Populated for the local tier (the slicer's own
  1932. // `compatible_printers`); null for cloud / standard. The SliceModal filters
  1933. // the process / filament dropdowns by the selected printer using this when
  1934. // present (#1325).
  1935. compatible_printers?: string[] | null;
  1936. // Printer presets only: the preset it was saved from, for the local and
  1937. // OrcaSlicer Cloud tiers (#3250).
  1938. inherits?: string | null;
  1939. }
  1940. export interface UnifiedPresetsBySlot {
  1941. printer: UnifiedPreset[];
  1942. process: UnifiedPreset[];
  1943. filament: UnifiedPreset[];
  1944. }
  1945. // What is loaded in each connected printer, for the SliceModal's
  1946. // "only connected printers" / "only loaded spools" filters (#3172).
  1947. export interface LoadedSpoolPreset {
  1948. preset_id: string;
  1949. preset_name: string;
  1950. preset_source: string;
  1951. tray_info_idx?: string | null;
  1952. }
  1953. export interface LoadedSpoolTray {
  1954. ams_id: number;
  1955. tray_id: number;
  1956. tray_type: string | null;
  1957. tray_sub_brands: string | null;
  1958. tray_color: string | null;
  1959. tray_info_idx: string | null;
  1960. exists: boolean | null;
  1961. state: number | null;
  1962. saved_preset: LoadedSpoolPreset | null;
  1963. }
  1964. export interface LoadedSpoolUnit {
  1965. id: number;
  1966. is_ams_ht: boolean;
  1967. trays: LoadedSpoolTray[];
  1968. }
  1969. export interface LoadedSpoolPrinter {
  1970. id: number;
  1971. name: string;
  1972. model: string | null;
  1973. ams: LoadedSpoolUnit[];
  1974. // Holders with a spool in them; external_holders counts all of them (two
  1975. // on a dual-nozzle printer, labelled left and right).
  1976. external: LoadedSpoolTray[];
  1977. external_holders: number;
  1978. }
  1979. export interface LoadedSpoolsResponse {
  1980. printers: LoadedSpoolPrinter[];
  1981. }
  1982. export interface UnifiedPresetsResponse {
  1983. // Priority order: local > orca_cloud > cloud > standard. No cross-tier
  1984. // dedup (apart from stock_aliases below) — every tier surfaces its full
  1985. // list so the user can pick from any source. The order drives auto-pick + visual group rendering only.
  1986. orca_cloud: UnifiedPresetsBySlot;
  1987. cloud: UnifiedPresetsBySlot;
  1988. local: UnifiedPresetsBySlot;
  1989. standard: UnifiedPresetsBySlot;
  1990. cloud_status: SlicerCloudStatus;
  1991. orca_cloud_status: SlicerCloudStatus;
  1992. // Standard presets that Bambu Cloud's stock list also has are left out of
  1993. // the standard tier (#3386); each "standard:<id>" maps to its cloud twin.
  1994. stock_aliases?: Record<string, PresetRef>;
  1995. }
  1996. // Slicer Pipelines (#1425) — named bundles of preset slots the SliceModal
  1997. // can apply in one click. PR A surfaces only the bundle; target_* and
  1998. // fanout_strategy round-trip from the backend but the UI doesn't yet expose
  1999. // them (they come alive in PR B / PR C).
  2000. export interface SlicerPipeline {
  2001. id: number;
  2002. name: string;
  2003. description: string | null;
  2004. printer_preset: PresetRef;
  2005. process_preset: PresetRef;
  2006. filament_presets: PresetRef[];
  2007. bed_type: string | null;
  2008. target_kind: 'specific_printer' | 'printer_class';
  2009. target_printer_id: number | null;
  2010. target_model_class: string | null;
  2011. fanout_strategy: 'max_parallel' | 'fill_one_first' | 'round_robin';
  2012. created_by: number | null;
  2013. created_at: string;
  2014. updated_at: string;
  2015. }
  2016. export interface SlicerPipelineCreateRequest {
  2017. name: string;
  2018. description?: string | null;
  2019. printer_preset: PresetRef;
  2020. process_preset: PresetRef;
  2021. filament_presets: PresetRef[];
  2022. bed_type?: string | null;
  2023. }
  2024. export type SlicerPipelineUpdateRequest = Partial<SlicerPipelineCreateRequest> & {
  2025. target_kind?: 'specific_printer' | 'printer_class';
  2026. // ``target_printer_id: 0`` means "clear the target" — the backend maps that
  2027. // to null. Use null in TypeScript for the same intent.
  2028. target_printer_id?: number | null;
  2029. target_model_class?: string | null;
  2030. fanout_strategy?: 'max_parallel' | 'fill_one_first' | 'round_robin';
  2031. };
  2032. export interface SlicerPipelinesListResponse {
  2033. pipelines: SlicerPipeline[];
  2034. }
  2035. // Slicer Pipeline runs (#1425 PR B + PR C)
  2036. export type PipelineEligibilityKind =
  2037. | 'printer_not_set'
  2038. | 'printer_not_found'
  2039. | 'printer_disabled'
  2040. | 'printer_offline'
  2041. | 'filament_type_mismatch'
  2042. | 'filament_color_mismatch'
  2043. | 'ams_slot_missing'
  2044. | 'filament_unverified'
  2045. | 'no_class_matches'
  2046. | 'class_not_set';
  2047. export interface PipelineEligibilityIssue {
  2048. kind: PipelineEligibilityKind;
  2049. slot_index: number | null;
  2050. expected: string | null;
  2051. actual: string | null;
  2052. }
  2053. export interface PipelinePerPrinterReport {
  2054. printer_id: number;
  2055. printer_name: string;
  2056. ok: boolean;
  2057. issues: PipelineEligibilityIssue[];
  2058. }
  2059. export interface PipelineEligibilityReport {
  2060. ok: boolean;
  2061. target_kind: 'specific_printer' | 'printer_class';
  2062. target_printer_id: number | null;
  2063. target_printer_name: string | null;
  2064. target_model_class: string | null;
  2065. issues: PipelineEligibilityIssue[];
  2066. printer_reports: PipelinePerPrinterReport[];
  2067. }
  2068. export interface PipelineJob {
  2069. id: number;
  2070. pipeline_run_id: number;
  2071. copy_index: number;
  2072. assigned_printer_id: number | null;
  2073. assigned_printer_name: string | null;
  2074. queue_entry_id: number | null;
  2075. status:
  2076. | 'pending'
  2077. | 'awaiting_printer'
  2078. | 'queued'
  2079. | 'printing'
  2080. | 'completed'
  2081. | 'failed'
  2082. | 'cancelled'
  2083. | 'unknown';
  2084. error_message: string | null;
  2085. dispatched_at: string | null;
  2086. completed_at: string | null;
  2087. }
  2088. export interface PipelineRun {
  2089. id: number;
  2090. pipeline_id: number | null;
  2091. pipeline_name: string | null;
  2092. source_library_file_id: number | null;
  2093. source_archive_id: number | null;
  2094. source_filename: string | null;
  2095. parent_run_id: number | null;
  2096. copies: number;
  2097. copies_completed: number;
  2098. copies_failed: number;
  2099. copies_cancelled: number;
  2100. copies_in_progress: number;
  2101. status:
  2102. | 'queued'
  2103. | 'slicing'
  2104. | 'dispatching'
  2105. | 'in_progress'
  2106. | 'completed'
  2107. | 'failed'
  2108. | 'partial_failure'
  2109. | 'cancelled';
  2110. slice_job_id: number | null;
  2111. sliced_library_file_id: number | null;
  2112. eligibility_overridden: boolean;
  2113. error_message: string | null;
  2114. created_by: number | null;
  2115. created_at: string;
  2116. started_at: string | null;
  2117. completed_at: string | null;
  2118. jobs: PipelineJob[];
  2119. target_kind: 'specific_printer' | 'printer_class' | null;
  2120. target_printer_id: number | null;
  2121. target_model_class: string | null;
  2122. fanout_strategy: 'max_parallel' | 'fill_one_first' | 'round_robin' | null;
  2123. }
  2124. export interface PipelineRunListResponse {
  2125. runs: PipelineRun[];
  2126. total: number;
  2127. }
  2128. export interface SliceResponse {
  2129. library_file_id: number;
  2130. name: string;
  2131. print_time_seconds: number;
  2132. filament_used_g: number;
  2133. filament_used_mm: number;
  2134. used_embedded_settings: boolean;
  2135. /** Why the result could not be written to the external folder the source
  2136. * lives in, and so went to managed storage instead. Null on every normal
  2137. * slice. Surfaced to the user — a file filed somewhere they aren't looking
  2138. * with no signal is what made #2810 invisible from the UI. */
  2139. external_write_fallback?: string | null;
  2140. }
  2141. export interface SliceArchiveResponse {
  2142. archive_id: number;
  2143. name: string;
  2144. print_time_seconds: number;
  2145. filament_used_g: number;
  2146. filament_used_mm: number;
  2147. used_embedded_settings: boolean;
  2148. }
  2149. // Background slice-job lifecycle. POST /slice returns 202 + this shape;
  2150. // the frontend polls /slice-jobs/{id} until status is terminal.
  2151. export type SliceJobStatus = 'pending' | 'running' | 'completed' | 'failed';
  2152. export interface SliceJobEnqueueResponse {
  2153. job_id: number;
  2154. status: SliceJobStatus;
  2155. status_url: string;
  2156. }
  2157. export interface SliceJobProgress {
  2158. /** Stage label emitted by the slicer ("Generating G-code", "Slicing finished"). */
  2159. stage: string;
  2160. total_percent: number;
  2161. plate_percent: number;
  2162. /** 1-indexed plate position; 0 means "all plates" / final completion. */
  2163. plate_index: number;
  2164. plate_count: number;
  2165. updated_at: number;
  2166. /** When the backend is in the cross-class slice-all loop (#1493), each
  2167. * per-plate sub-slice's progress is augmented with the loop position
  2168. * so the toast can show "Plate 2 of 5 — Generating G-code 47%". The
  2169. * fields are absent on a single-plate slice. */
  2170. multi_plate_index?: number;
  2171. multi_plate_count?: number;
  2172. }
  2173. export interface SliceJobState {
  2174. job_id: number;
  2175. status: SliceJobStatus;
  2176. kind: 'library_file' | 'archive';
  2177. source_id: number;
  2178. source_name: string;
  2179. created_at: string;
  2180. started_at: string | null;
  2181. completed_at: string | null;
  2182. /** Live progress fed by the sidecar's --pipe channel; null until the
  2183. * slicer emits its first frame (early "Initializing" phase) or when
  2184. * the sidecar doesn't support progress. */
  2185. progress: SliceJobProgress | null;
  2186. result?: SliceResponse | SliceArchiveResponse;
  2187. error_status?: number;
  2188. error_detail?: string;
  2189. }
  2190. // Local preset types (OrcaSlicer imports)
  2191. export interface LocalPreset {
  2192. id: number;
  2193. name: string;
  2194. preset_type: string;
  2195. source: string;
  2196. filament_type: string | null;
  2197. filament_vendor: string | null;
  2198. nozzle_temp_min: number | null;
  2199. nozzle_temp_max: number | null;
  2200. pressure_advance: string | null;
  2201. default_filament_colour: string | null;
  2202. filament_cost: string | null;
  2203. filament_density: string | null;
  2204. compatible_printers: string | null;
  2205. inherits: string | null;
  2206. version: string | null;
  2207. created_at: string;
  2208. updated_at: string;
  2209. }
  2210. export interface LocalPresetDetail extends LocalPreset {
  2211. setting: Record<string, unknown>;
  2212. }
  2213. export interface LocalPresetsResponse {
  2214. filament: LocalPreset[];
  2215. printer: LocalPreset[];
  2216. process: LocalPreset[];
  2217. }
  2218. export interface ImportResponse {
  2219. success: boolean;
  2220. imported: number;
  2221. skipped: number;
  2222. errors: string[];
  2223. }
  2224. export interface FieldOption {
  2225. value: string;
  2226. label: string;
  2227. }
  2228. export interface FieldDefinition {
  2229. key: string;
  2230. label: string;
  2231. type: 'text' | 'number' | 'boolean' | 'select';
  2232. category: string;
  2233. description?: string;
  2234. options?: FieldOption[];
  2235. unit?: string;
  2236. min?: number;
  2237. max?: number;
  2238. step?: number;
  2239. }
  2240. export interface FieldDefinitionsResponse {
  2241. version: string;
  2242. description: string;
  2243. fields: FieldDefinition[];
  2244. }
  2245. export interface CloudDevice {
  2246. dev_id: string;
  2247. name: string;
  2248. dev_model_name: string | null;
  2249. dev_product_name: string | null;
  2250. online: boolean;
  2251. }
  2252. // Smart Plug types
  2253. export interface SmartPlug {
  2254. id: number;
  2255. name: string;
  2256. plug_type: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  2257. ip_address: string | null; // Required for Tasmota
  2258. ha_entity_id: string | null; // Required for Home Assistant (e.g., "switch.printer_plug", "script.turn_on_printer")
  2259. // Home Assistant energy sensor entities (optional)
  2260. ha_power_entity: string | null;
  2261. ha_energy_today_entity: string | null;
  2262. ha_energy_total_entity: string | null;
  2263. // MQTT fields (required when plug_type="mqtt")
  2264. // Legacy field - kept for backward compatibility
  2265. mqtt_topic: string | null; // Deprecated, use mqtt_power_topic
  2266. mqtt_multiplier: number; // Deprecated, use mqtt_power_multiplier
  2267. // Power monitoring
  2268. mqtt_power_topic: string | null; // Topic for power data
  2269. mqtt_power_path: string | null; // e.g., "power_l1" or "data.power"
  2270. mqtt_power_multiplier: number; // Unit conversion for power
  2271. // Energy monitoring
  2272. mqtt_energy_topic: string | null; // Topic for energy data
  2273. mqtt_energy_path: string | null; // e.g., "energy_l1"
  2274. mqtt_energy_multiplier: number; // Unit conversion for energy
  2275. // State monitoring
  2276. mqtt_state_topic: string | null; // Topic for state data
  2277. mqtt_state_path: string | null; // e.g., "state_l1" for ON/OFF
  2278. mqtt_state_on_value: string | null; // What value means "ON" (e.g., "ON", "true", "1")
  2279. // REST/Webhook fields (required when plug_type="rest")
  2280. rest_on_url: string | null;
  2281. rest_on_body: string | null;
  2282. rest_off_url: string | null;
  2283. rest_off_body: string | null;
  2284. rest_method: string | null;
  2285. rest_headers: string | null;
  2286. rest_status_url: string | null;
  2287. rest_status_path: string | null;
  2288. rest_status_on_value: string | null;
  2289. rest_power_url: string | null;
  2290. rest_power_path: string | null;
  2291. rest_power_multiplier: number;
  2292. rest_energy_url: string | null;
  2293. rest_energy_path: string | null;
  2294. rest_energy_multiplier: number;
  2295. // Lifetime counter, separate from the daily one (#2539). A Shelly reports only
  2296. // this; Today and Yesterday are derived from its hourly snapshots.
  2297. rest_energy_total_path: string | null;
  2298. rest_energy_total_multiplier: number;
  2299. printer_id: number | null;
  2300. // #2629: only a plug that really feeds the printer may mark it offline when
  2301. // switched off. Accessory plugs follow the print cycle without powering it.
  2302. controls_printer_power: boolean;
  2303. enabled: boolean;
  2304. auto_on: boolean;
  2305. auto_off: boolean;
  2306. auto_off_persistent: boolean;
  2307. off_delay_mode: 'time' | 'temperature';
  2308. off_delay_minutes: number;
  2309. off_temp_threshold: number;
  2310. // #1349: auto-off after AMS drying completes.
  2311. auto_off_after_drying: boolean;
  2312. off_delay_after_drying_minutes: number;
  2313. username: string | null;
  2314. password: string | null;
  2315. // Power alerts
  2316. power_alert_enabled: boolean;
  2317. power_alert_high: number | null;
  2318. power_alert_low: number | null;
  2319. power_alert_last_triggered: string | null;
  2320. // Schedule
  2321. schedule_enabled: boolean;
  2322. schedule_on_time: string | null;
  2323. schedule_off_time: string | null;
  2324. // Visibility options
  2325. show_in_switchbar: boolean;
  2326. show_on_printer_card: boolean; // For scripts: show on printer card
  2327. // Status
  2328. last_state: string | null;
  2329. last_checked: string | null;
  2330. auto_off_executed: boolean; // True when auto-off was triggered after print
  2331. created_at: string;
  2332. updated_at: string;
  2333. }
  2334. export interface SmartPlugCreate {
  2335. name: string;
  2336. plug_type?: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  2337. ip_address?: string | null; // Required for Tasmota
  2338. ha_entity_id?: string | null; // Required for Home Assistant
  2339. // Home Assistant energy sensor entities (optional)
  2340. ha_power_entity?: string | null;
  2341. ha_energy_today_entity?: string | null;
  2342. ha_energy_total_entity?: string | null;
  2343. // MQTT fields (required when plug_type="mqtt")
  2344. // Legacy fields - kept for backward compatibility
  2345. mqtt_topic?: string | null;
  2346. mqtt_multiplier?: number;
  2347. // Power monitoring
  2348. mqtt_power_topic?: string | null;
  2349. mqtt_power_path?: string | null;
  2350. mqtt_power_multiplier?: number;
  2351. // Energy monitoring
  2352. mqtt_energy_topic?: string | null;
  2353. mqtt_energy_path?: string | null;
  2354. mqtt_energy_multiplier?: number;
  2355. // State monitoring
  2356. mqtt_state_topic?: string | null;
  2357. mqtt_state_path?: string | null;
  2358. mqtt_state_on_value?: string | null;
  2359. // REST fields
  2360. rest_on_url?: string | null;
  2361. rest_on_body?: string | null;
  2362. rest_off_url?: string | null;
  2363. rest_off_body?: string | null;
  2364. rest_method?: string | null;
  2365. rest_headers?: string | null;
  2366. rest_status_url?: string | null;
  2367. rest_status_path?: string | null;
  2368. rest_status_on_value?: string | null;
  2369. rest_power_url?: string | null;
  2370. rest_power_path?: string | null;
  2371. rest_power_multiplier?: number;
  2372. rest_energy_url?: string | null;
  2373. rest_energy_path?: string | null;
  2374. rest_energy_multiplier?: number;
  2375. rest_energy_total_path?: string | null;
  2376. rest_energy_total_multiplier?: number;
  2377. printer_id?: number | null;
  2378. // #2629
  2379. controls_printer_power?: boolean;
  2380. enabled?: boolean;
  2381. auto_on?: boolean;
  2382. auto_off?: boolean;
  2383. auto_off_persistent?: boolean;
  2384. off_delay_mode?: 'time' | 'temperature';
  2385. off_delay_minutes?: number;
  2386. off_temp_threshold?: number;
  2387. // #1349
  2388. auto_off_after_drying?: boolean;
  2389. off_delay_after_drying_minutes?: number;
  2390. username?: string | null;
  2391. password?: string | null;
  2392. // Power alerts
  2393. power_alert_enabled?: boolean;
  2394. power_alert_high?: number | null;
  2395. power_alert_low?: number | null;
  2396. // Schedule
  2397. schedule_enabled?: boolean;
  2398. schedule_on_time?: string | null;
  2399. schedule_off_time?: string | null;
  2400. // Visibility options
  2401. show_in_switchbar?: boolean;
  2402. show_on_printer_card?: boolean;
  2403. }
  2404. export interface SmartPlugUpdate {
  2405. name?: string;
  2406. plug_type?: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  2407. ip_address?: string | null;
  2408. ha_entity_id?: string | null;
  2409. // Home Assistant energy sensor entities (optional)
  2410. ha_power_entity?: string | null;
  2411. ha_energy_today_entity?: string | null;
  2412. ha_energy_total_entity?: string | null;
  2413. // MQTT fields (legacy)
  2414. mqtt_topic?: string | null;
  2415. mqtt_multiplier?: number;
  2416. // MQTT power fields
  2417. mqtt_power_topic?: string | null;
  2418. mqtt_power_path?: string | null;
  2419. mqtt_power_multiplier?: number;
  2420. // MQTT energy fields
  2421. mqtt_energy_topic?: string | null;
  2422. mqtt_energy_path?: string | null;
  2423. mqtt_energy_multiplier?: number;
  2424. // MQTT state fields
  2425. mqtt_state_topic?: string | null;
  2426. mqtt_state_path?: string | null;
  2427. mqtt_state_on_value?: string | null;
  2428. // REST fields
  2429. rest_on_url?: string | null;
  2430. rest_on_body?: string | null;
  2431. rest_off_url?: string | null;
  2432. rest_off_body?: string | null;
  2433. rest_method?: string | null;
  2434. rest_headers?: string | null;
  2435. rest_status_url?: string | null;
  2436. rest_status_path?: string | null;
  2437. rest_status_on_value?: string | null;
  2438. rest_power_url?: string | null;
  2439. rest_power_path?: string | null;
  2440. rest_power_multiplier?: number;
  2441. rest_energy_url?: string | null;
  2442. rest_energy_path?: string | null;
  2443. rest_energy_multiplier?: number;
  2444. rest_energy_total_path?: string | null;
  2445. rest_energy_total_multiplier?: number;
  2446. printer_id?: number | null;
  2447. // #2629
  2448. controls_printer_power?: boolean;
  2449. enabled?: boolean;
  2450. auto_on?: boolean;
  2451. auto_off?: boolean;
  2452. auto_off_persistent?: boolean;
  2453. off_delay_mode?: 'time' | 'temperature';
  2454. off_delay_minutes?: number;
  2455. off_temp_threshold?: number;
  2456. // #1349
  2457. auto_off_after_drying?: boolean;
  2458. off_delay_after_drying_minutes?: number;
  2459. username?: string | null;
  2460. password?: string | null;
  2461. // Power alerts
  2462. power_alert_enabled?: boolean;
  2463. power_alert_high?: number | null;
  2464. power_alert_low?: number | null;
  2465. // Schedule
  2466. schedule_enabled?: boolean;
  2467. schedule_on_time?: string | null;
  2468. schedule_off_time?: string | null;
  2469. // Visibility options
  2470. show_in_switchbar?: boolean;
  2471. show_on_printer_card?: boolean;
  2472. }
  2473. // Home Assistant entity for smart plug selection
  2474. export interface HAEntity {
  2475. entity_id: string;
  2476. friendly_name: string;
  2477. state: string | null;
  2478. domain: string; // "switch", "light", "input_boolean", "script"
  2479. }
  2480. // Home Assistant sensor entity for energy monitoring
  2481. export interface HASensorEntity {
  2482. entity_id: string;
  2483. friendly_name: string;
  2484. state: string | null;
  2485. unit_of_measurement: string | null; // "W", "kW", "kWh", "Wh"
  2486. }
  2487. export interface HATestConnectionResult {
  2488. success: boolean;
  2489. message: string | null;
  2490. error: string | null;
  2491. }
  2492. // A Home Assistant entity bound to a printer for display on its card (#1148, #448).
  2493. // Read-only: unlike a SmartPlug there is nothing here to switch.
  2494. export interface PrinterHASensor {
  2495. id: number;
  2496. printer_id: number;
  2497. name: string;
  2498. entity_id: string;
  2499. kind: 'binary' | 'numeric';
  2500. device_class: string | null; // HA's own class: "door", "temperature", ...
  2501. unit: string | null; // numeric sensors only
  2502. // What counts as needing attention. Binary sensors use alert_state, numeric
  2503. // ones the thresholds; all null means the sensor is display-only.
  2504. alert_state: 'on' | 'off' | null;
  2505. alert_above: number | null;
  2506. alert_below: number | null;
  2507. block_print: boolean; // hold the printer's queue while alerting
  2508. notify_on_alert: boolean;
  2509. show_on_printer_card: boolean;
  2510. sort_order: number;
  2511. last_state: string | null;
  2512. last_changed: string | null;
  2513. last_checked: string | null;
  2514. created_at: string;
  2515. updated_at: string;
  2516. }
  2517. export interface PrinterHASensorReading {
  2518. id: number;
  2519. name: string;
  2520. entity_id: string;
  2521. kind: 'binary' | 'numeric';
  2522. device_class: string | null;
  2523. unit: string | null;
  2524. state: string | null; // null when unreadable or not yet polled
  2525. value: number | null; // numeric sensors only
  2526. alerting: boolean;
  2527. block_print: boolean;
  2528. reachable: boolean;
  2529. last_changed: string | null;
  2530. }
  2531. export interface PrinterHASensorCreate {
  2532. printer_id: number;
  2533. name: string;
  2534. entity_id: string;
  2535. kind: 'binary' | 'numeric';
  2536. device_class?: string | null;
  2537. unit?: string | null;
  2538. alert_state?: 'on' | 'off' | null;
  2539. alert_above?: number | null;
  2540. alert_below?: number | null;
  2541. block_print?: boolean;
  2542. notify_on_alert?: boolean;
  2543. show_on_printer_card?: boolean;
  2544. sort_order?: number;
  2545. }
  2546. export type PrinterHASensorUpdate = Partial<Omit<PrinterHASensorCreate, 'printer_id'>>;
  2547. export interface LocationHASensor {
  2548. id: number;
  2549. location_id: number;
  2550. name: string;
  2551. entity_id: string;
  2552. kind: 'binary' | 'numeric';
  2553. device_class: string | null;
  2554. unit: string | null;
  2555. alert_state: 'on' | 'off' | null;
  2556. alert_above: number | null;
  2557. alert_below: number | null;
  2558. notify_on_alert: boolean;
  2559. show_on_card: boolean;
  2560. sort_order: number;
  2561. last_state: string | null;
  2562. last_changed: string | null;
  2563. last_checked: string | null;
  2564. created_at: string;
  2565. updated_at: string;
  2566. }
  2567. export interface LocationHASensorReading {
  2568. id: number;
  2569. name: string;
  2570. entity_id: string;
  2571. kind: 'binary' | 'numeric';
  2572. device_class: string | null;
  2573. unit: string | null;
  2574. state: string | null;
  2575. value: number | null;
  2576. alerting: boolean;
  2577. reachable: boolean;
  2578. alert_state: string | null;
  2579. alert_above: number | null;
  2580. alert_below: number | null;
  2581. last_changed: string | null;
  2582. show_on_card: boolean;
  2583. }
  2584. export interface LocationHASensorCreate {
  2585. location_id: number;
  2586. name: string;
  2587. entity_id: string;
  2588. kind: 'binary' | 'numeric';
  2589. device_class?: string | null;
  2590. unit?: string | null;
  2591. alert_state?: 'on' | 'off' | null;
  2592. alert_above?: number | null;
  2593. alert_below?: number | null;
  2594. notify_on_alert?: boolean;
  2595. show_on_card?: boolean;
  2596. sort_order?: number;
  2597. }
  2598. export type LocationHASensorUpdate = Partial<Omit<LocationHASensorCreate, 'location_id'>>;
  2599. // An entity offered by the binding picker.
  2600. export interface HADisplayEntity {
  2601. entity_id: string;
  2602. friendly_name: string;
  2603. state: string | null;
  2604. domain: string; // "binary_sensor" | "sensor"
  2605. device_class: string | null;
  2606. unit_of_measurement: string | null;
  2607. }
  2608. export interface SmartPlugEnergy {
  2609. power: number | null; // Current watts
  2610. voltage: number | null; // Volts
  2611. current: number | null; // Amps
  2612. today: number | null; // kWh used today
  2613. yesterday: number | null; // kWh used yesterday
  2614. total: number | null; // Total kWh
  2615. factor: number | null; // Power factor (0-1)
  2616. apparent_power: number | null; // VA
  2617. reactive_power: number | null; // VAr
  2618. }
  2619. export interface SmartPlugStatus {
  2620. state: string | null;
  2621. reachable: boolean;
  2622. device_name: string | null;
  2623. energy: SmartPlugEnergy | null;
  2624. }
  2625. export interface SmartPlugTestResult {
  2626. success: boolean;
  2627. state: string | null;
  2628. device_name: string | null;
  2629. }
  2630. // Tasmota Discovery types
  2631. export interface TasmotaScanStatus {
  2632. running: boolean;
  2633. scanned: number;
  2634. total: number;
  2635. }
  2636. export interface DiscoveredTasmotaDevice {
  2637. ip_address: string;
  2638. name: string;
  2639. module: number | null;
  2640. state: string | null;
  2641. discovered_at: string | null;
  2642. }
  2643. // Print Queue types
  2644. export interface PrintQueueItem {
  2645. id: number;
  2646. printer_id: number | null; // null = unassigned
  2647. target_model: string | null; // Target printer model for model-based assignment
  2648. target_location: string | null; // Target location filter for model-based assignment
  2649. required_filament_types: string[] | null; // Required filament types for model-based assignment
  2650. waiting_reason: string | null; // Why this job hasn't started yet (empty once it can)
  2651. // Cross-model alternatives (#671), in priority order. Empty for ordinary
  2652. // items. Present until dispatch resolves one, after which library_file_id and
  2653. // target_model name the candidate that actually ran.
  2654. variants?: Array<{
  2655. library_file_id: number;
  2656. filename: string;
  2657. target_model: string;
  2658. position: number;
  2659. }>;
  2660. // Either archive_id OR library_file_id must be set (archive created at print start)
  2661. archive_id: number | null;
  2662. library_file_id: number | null;
  2663. cost_center_id: number | null;
  2664. estimated_cost: number | null;
  2665. position: number;
  2666. scheduled_time: string | null;
  2667. require_previous_success: boolean;
  2668. auto_off_after: boolean;
  2669. manual_start: boolean; // Requires manual trigger to start (staged)
  2670. // Set by the dispatch scheduler when the assigned spool can't satisfy
  2671. // any required slot's grams (#1496). Surfaced on the queue row as a
  2672. // "filament short" badge; cleared on a successful ▶ click (live recheck).
  2673. filament_short: boolean;
  2674. // Persistent "Print Anyway" acknowledgement — once true the scheduler
  2675. // skips the deficit check for this item (#1698-followup). Set by the
  2676. // start route when skip_filament_check=true, or at queue creation if
  2677. // PrintModal's deficit warning was acknowledged.
  2678. skip_filament_check: boolean;
  2679. // True when the source archive carries the slicer's own live-resolved
  2680. // AMS-slot pick (extra_data.slicer_ams_mapping) — a reprint reuses that
  2681. // exact physical spool instead of re-deriving one from type/color.
  2682. archive_has_slicer_ams_mapping: boolean;
  2683. ams_mapping: number[] | null; // AMS slot mapping for multi-color prints
  2684. 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
  2685. plate_id: number | null; // Plate ID for multi-plate 3MF files
  2686. // Print options
  2687. bed_levelling: CalibrationMode;
  2688. flow_cali: CalibrationMode;
  2689. vibration_cali: boolean;
  2690. layer_inspect: boolean;
  2691. timelapse: boolean;
  2692. use_ams: boolean;
  2693. nozzle_offset_cali: CalibrationMode;
  2694. // Ask for a post-print outcome verdict when this job completes (#1898)
  2695. confirm_outcome: boolean;
  2696. preheat_override: 'inherit' | 'on' | 'off';
  2697. preheat_chamber_target_override: number | null;
  2698. status: 'pending' | 'printing' | 'completed' | 'failed' | 'skipped' | 'cancelled';
  2699. started_at: string | null;
  2700. completed_at: string | null;
  2701. error_message: string | null;
  2702. created_at: string;
  2703. archive_name?: string | null;
  2704. archive_thumbnail?: string | null;
  2705. // True when the linked archive has been soft-deleted; archive_name /
  2706. // archive_thumbnail / downstream metadata are left null in that case so
  2707. // the UI doesn't 404-storm the now-missing endpoints (#1348 follow-up).
  2708. archive_deleted?: boolean;
  2709. library_file_name?: string | null;
  2710. library_file_thumbnail?: string | null;
  2711. printer_name?: string | null;
  2712. print_time_seconds?: number | null; // Estimated print time from archive or library file
  2713. filament_used_grams?: number | null; // Estimated print weight from archive or library file
  2714. filament_type?: string | null; // e.g. "PLA", "PETG"
  2715. filament_color?: string | null; // Hex RGBA from the slicer
  2716. bed_type?: string | null; // Build plate type for this print (per-plate accurate, #1281)
  2717. // User tracking (Issue #206)
  2718. created_by_id?: number | null;
  2719. created_by_username?: string | null;
  2720. // Batch grouping
  2721. batch_id?: number | null;
  2722. batch_name?: string | null;
  2723. // Shortest-job-first scheduling
  2724. been_jumped?: boolean;
  2725. // Auto-print G-code injection
  2726. gcode_injection?: boolean;
  2727. cleanup_library_after_dispatch?: boolean;
  2728. /** Which rack position each filament group prints from, on a nozzle-rack
  2729. * machine (#1784): `{ [group_id]: 1-based position }`. Re-checked against
  2730. * the live rack at dispatch; omit to have the dispatcher assign them. */
  2731. nozzle_rack_choice?: Record<number, number> | null;
  2732. /** Slots sent with a spool of another colour than the file asks for
  2733. * (#3279). Worked out when the job is sent; null when every slot got its
  2734. * colour or nothing could be compared. */
  2735. color_substitutions?: ColorSubstitution[] | null;
  2736. }
  2737. /** One slot printed in another colour than the file asked for (#3279). */
  2738. export interface ColorSubstitution {
  2739. slot_id: number;
  2740. type: string;
  2741. /** `#RRGGBB` the file asks for, after overrides. */
  2742. wanted: string;
  2743. /** `#RRGGBB` of the spool the slot was sent with. */
  2744. got: string;
  2745. tray: number;
  2746. }
  2747. export interface PrintBatchPlateTarget {
  2748. plate_id: number | null;
  2749. plate_name?: string | null;
  2750. quantity_target: number;
  2751. sort_order?: number;
  2752. }
  2753. export interface PrintBatchPlateProgress {
  2754. plate_id: number | null;
  2755. plate_name: string | null;
  2756. quantity_target: number;
  2757. dispatched: number;
  2758. remaining: number;
  2759. pending_count: number;
  2760. printing_count: number;
  2761. completed_count: number;
  2762. failed_count: number;
  2763. cancelled_count: number;
  2764. skipped_count: number;
  2765. /** Measured from finished runs; null until one has produced a cost. */
  2766. actual_cost: number | null;
  2767. estimated_remaining_cost: number | null;
  2768. filament_used_grams: number | null;
  2769. print_time_seconds: number;
  2770. /** False when this plate owes runs but has no queue item left to clone
  2771. * their configuration from, so queueing it could only fail (#2960). */
  2772. can_dispatch: boolean;
  2773. }
  2774. export interface PrintBatch {
  2775. id: number;
  2776. name: string;
  2777. archive_id: number | null;
  2778. library_file_id: number | null;
  2779. quantity: number;
  2780. status: string;
  2781. created_at: string;
  2782. completed_at: string | null;
  2783. created_by_id: number | null;
  2784. created_by_username: string | null;
  2785. project_id: number | null;
  2786. due_date: string | null;
  2787. notes: string | null;
  2788. /** Set when an integration (e.g. a shop connector) created the batch. */
  2789. external_source: string | null;
  2790. external_ref: string | null;
  2791. pending_count: number;
  2792. printing_count: number;
  2793. completed_count: number;
  2794. failed_count: number;
  2795. cancelled_count: number;
  2796. skipped_count: number;
  2797. /** False for batches created before per-plate targets existed (#342):
  2798. * they report progress but owe nothing and cannot be dispatched from. */
  2799. has_targets: boolean;
  2800. target_count: number;
  2801. remaining_count: number;
  2802. /** Of remaining_count, how many runs can actually be queued (#2960). */
  2803. dispatchable_count: number;
  2804. actual_cost: number | null;
  2805. estimated_remaining_cost: number | null;
  2806. filament_used_grams: number | null;
  2807. print_time_seconds: number;
  2808. plates: PrintBatchPlateProgress[];
  2809. }
  2810. export interface PrintQueueItemCreate {
  2811. printer_id?: number | null; // null = unassigned
  2812. target_model?: string | null; // Target printer model (mutually exclusive with printer_id)
  2813. target_location?: string | null; // Target location filter (only used with target_model)
  2814. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; tray_info_idx?: string; force_color_match?: boolean }> | null;
  2815. archive_id?: number | null;
  2816. library_file_id?: number | null;
  2817. scheduled_time?: string | null;
  2818. require_previous_success?: boolean;
  2819. auto_off_after?: boolean;
  2820. manual_start?: boolean; // Requires manual trigger to start (staged)
  2821. insert_at_top?: boolean; // Insert ahead of other pending items (one queue order across all printers, #3200)
  2822. insert_position?: number | null; // 1-indexed insertion position for priority queueing
  2823. // PrintModal "Print Anyway" on the deficit warning — persisted so the
  2824. // scheduler doesn't immediately re-flag this item (#1698-followup).
  2825. skip_filament_check?: boolean;
  2826. ams_mapping?: number[] | null; // AMS slot mapping for multi-color prints
  2827. plate_id?: number | null; // Plate ID for multi-plate 3MF files
  2828. // Print options
  2829. bed_levelling?: CalibrationMode;
  2830. flow_cali?: CalibrationMode;
  2831. vibration_cali?: boolean;
  2832. layer_inspect?: boolean;
  2833. timelapse?: boolean;
  2834. use_ams?: boolean;
  2835. nozzle_offset_cali?: CalibrationMode;
  2836. // Ask for a post-print outcome verdict when this job completes (#1898)
  2837. confirm_outcome?: boolean;
  2838. preheat_override?: 'inherit' | 'on' | 'off';
  2839. preheat_chamber_target_override?: number | null;
  2840. // Auto-print G-code injection
  2841. gcode_injection?: boolean;
  2842. // Batch: create multiple copies (creates a batch if > 1)
  2843. quantity?: number;
  2844. // Existing batch to add this item into (multi-plate auto-batch flow).
  2845. batch_id?: number | null;
  2846. // Project to associate the resulting archive with
  2847. project_id?: number;
  2848. cost_center_id?: number | null;
  2849. estimated_cost?: number | null;
  2850. // Delete transient uploaded library file after scheduler creates the archive
  2851. cleanup_library_after_dispatch?: boolean;
  2852. // Cross-model alternatives (#671): several sliced files, one job, whichever
  2853. // printer frees up first. Mutually exclusive with printer_id (a named printer
  2854. // defeats the point) and with archive_id/library_file_id (these ARE the files).
  2855. // Order is priority — index 0 wins when several printers are idle at once.
  2856. variants?: QueueVariantCreate[];
  2857. /** Which rack position each filament group prints from, on a nozzle-rack
  2858. * machine (#1784): `{ [group_id]: 1-based position }`. Re-checked against
  2859. * the live rack at dispatch; omit to have the dispatcher assign them. */
  2860. nozzle_rack_choice?: Record<number, number> | null;
  2861. }
  2862. /** One candidate file for a cross-model queue item (#671). */
  2863. export interface QueueVariantCreate {
  2864. library_file_id: number;
  2865. /** Read from the file's own sliced_for_model unless it declares none. */
  2866. target_model?: string | null;
  2867. plate_id?: number | null;
  2868. ams_mapping?: number[] | null;
  2869. nozzle_mapping?: number[] | null;
  2870. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; tray_info_idx?: string; force_color_match?: boolean }> | null;
  2871. }
  2872. export interface PrintBatchCreate {
  2873. name: string;
  2874. archive_id?: number | null;
  2875. library_file_id?: number | null;
  2876. /** When set, the listed pending items are assigned to the new batch
  2877. * (manual "Group as batch"). When omitted/empty, an empty batch is
  2878. * returned so the client can pass batch_id on subsequent addToQueue calls. */
  2879. item_ids?: number[];
  2880. /** Per-plate targets. Omitting them creates a plain grouping batch. */
  2881. plates?: PrintBatchPlateTarget[];
  2882. project_id?: number | null;
  2883. due_date?: string | null;
  2884. notes?: string | null;
  2885. }
  2886. export interface PrintBatchUpdate {
  2887. name?: string;
  2888. status?: 'active' | 'cancelled';
  2889. /** Replaces the full target set — a plate omitted here is removed. */
  2890. plates?: PrintBatchPlateTarget[];
  2891. project_id?: number | null;
  2892. due_date?: string | null;
  2893. notes?: string | null;
  2894. }
  2895. export interface PrintBatchDispatchRequest {
  2896. plate_id?: number | null;
  2897. only_plate?: boolean;
  2898. /** Cap on items created across all plates; omit to queue everything owed. */
  2899. limit?: number;
  2900. }
  2901. export interface PrintQueueItemUpdate {
  2902. printer_id?: number | null; // null = unassign
  2903. // A deliberate filament substitution in the mapping (#2799); see PrintModal.
  2904. skip_filament_check?: boolean;
  2905. target_model?: string | null; // Target printer model (mutually exclusive with printer_id)
  2906. target_location?: string | null; // Target location filter (only used with target_model)
  2907. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; tray_info_idx?: string; force_color_match?: boolean }> | null;
  2908. position?: number;
  2909. scheduled_time?: string | null;
  2910. require_previous_success?: boolean;
  2911. auto_off_after?: boolean;
  2912. manual_start?: boolean;
  2913. ams_mapping?: number[];
  2914. plate_id?: number | null; // Plate ID for multi-plate 3MF files
  2915. // Print options
  2916. bed_levelling?: CalibrationMode;
  2917. flow_cali?: CalibrationMode;
  2918. vibration_cali?: boolean;
  2919. layer_inspect?: boolean;
  2920. timelapse?: boolean;
  2921. use_ams?: boolean;
  2922. nozzle_offset_cali?: CalibrationMode;
  2923. // Ask for a post-print outcome verdict when this job completes (#1898)
  2924. confirm_outcome?: boolean;
  2925. preheat_override?: 'inherit' | 'on' | 'off';
  2926. preheat_chamber_target_override?: number | null;
  2927. // Auto-print G-code injection
  2928. gcode_injection?: boolean;
  2929. cost_center_id?: number | null;
  2930. estimated_cost?: number | null;
  2931. /** Which rack position each filament group prints from, on a nozzle-rack
  2932. * machine (#1784): `{ [group_id]: 1-based position }`. Re-checked against
  2933. * the live rack at dispatch; omit to have the dispatcher assign them. */
  2934. nozzle_rack_choice?: Record<number, number> | null;
  2935. }
  2936. export interface PrintQueueBulkUpdate {
  2937. item_ids: number[];
  2938. printer_id?: number | null;
  2939. scheduled_time?: string | null;
  2940. require_previous_success?: boolean;
  2941. auto_off_after?: boolean;
  2942. manual_start?: boolean;
  2943. // Print options
  2944. bed_levelling?: CalibrationMode;
  2945. flow_cali?: CalibrationMode;
  2946. vibration_cali?: boolean;
  2947. layer_inspect?: boolean;
  2948. timelapse?: boolean;
  2949. use_ams?: boolean;
  2950. nozzle_offset_cali?: CalibrationMode;
  2951. // Ask for a post-print outcome verdict when this job completes (#1898)
  2952. confirm_outcome?: boolean;
  2953. preheat_override?: 'inherit' | 'on' | 'off';
  2954. preheat_chamber_target_override?: number | null;
  2955. // Auto-print G-code injection
  2956. gcode_injection?: boolean;
  2957. cost_center_id?: number | null;
  2958. estimated_cost?: number | null;
  2959. }
  2960. export interface PrintQueueBulkUpdateResponse {
  2961. updated_count: number;
  2962. skipped_count: number;
  2963. message: string;
  2964. }
  2965. // MQTT Logging types
  2966. export interface MQTTLogEntry {
  2967. timestamp: string;
  2968. topic: string;
  2969. direction: 'in' | 'out';
  2970. payload: Record<string, unknown>;
  2971. }
  2972. export interface MQTTLogsResponse {
  2973. logging_enabled: boolean;
  2974. logs: MQTTLogEntry[];
  2975. }
  2976. // K-Profile types
  2977. export interface KProfile {
  2978. slot_id: number;
  2979. extruder_id: number;
  2980. nozzle_id: string;
  2981. nozzle_diameter: string;
  2982. filament_id: string;
  2983. name: string;
  2984. k_value: string;
  2985. n_coef: string;
  2986. ams_id: number;
  2987. tray_id: number;
  2988. setting_id: string | null;
  2989. }
  2990. export interface KProfileCreate {
  2991. slot_id?: number; // Storage slot, 0 for new profiles
  2992. extruder_id?: number;
  2993. nozzle_id: string;
  2994. nozzle_diameter: string;
  2995. filament_id: string;
  2996. name: string;
  2997. k_value: string;
  2998. n_coef?: string;
  2999. ams_id?: number;
  3000. tray_id?: number;
  3001. setting_id?: string | null;
  3002. }
  3003. export interface KProfileDelete {
  3004. slot_id: number; // cali_idx - calibration index to delete
  3005. extruder_id: number;
  3006. nozzle_id: string; // e.g., "HH00-0.4"
  3007. nozzle_diameter: string; // e.g., "0.4"
  3008. filament_id: string; // Bambu filament identifier
  3009. setting_id?: string | null; // Setting ID (for X1C series)
  3010. }
  3011. export interface KProfilesResponse {
  3012. profiles: KProfile[];
  3013. nozzle_diameter: string;
  3014. }
  3015. export interface KProfileNote {
  3016. setting_id: string;
  3017. note: string;
  3018. }
  3019. export interface KProfileNotesResponse {
  3020. notes: Record<string, string>; // setting_id -> note
  3021. }
  3022. // Slot Preset Mapping
  3023. export interface SlotPresetMapping {
  3024. ams_id: number;
  3025. tray_id: number;
  3026. preset_id: string;
  3027. preset_name: string;
  3028. // Filament id the slot was configured with alongside this preset; null for
  3029. // rows that predate it or whose writer did not know it (#3216).
  3030. tray_info_idx?: string | null;
  3031. }
  3032. // Filament types
  3033. export interface Filament {
  3034. id: number;
  3035. name: string;
  3036. type: string; // PLA, PETG, ABS, etc.
  3037. brand: string | null;
  3038. color: string | null;
  3039. color_hex: string | null;
  3040. cost_per_kg: number;
  3041. spool_weight_g: number;
  3042. currency: string;
  3043. density: number | null;
  3044. print_temp_min: number | null;
  3045. print_temp_max: number | null;
  3046. bed_temp_min: number | null;
  3047. bed_temp_max: number | null;
  3048. created_at: string;
  3049. updated_at: string;
  3050. }
  3051. // Notification Provider types
  3052. export type ProviderType = 'callmebot' | 'ntfy' | 'pushover' | 'telegram' | 'email' | 'discord' | 'webhook' | 'homeassistant' | 'bark' | 'gotify' | 'notify';
  3053. // How a Telegram provider collects the outcome verdict (#3046)
  3054. export type TelegramVerdictMode = 'buttons' | 'reactions' | 'both';
  3055. export interface NotificationProvider {
  3056. id: number;
  3057. name: string;
  3058. provider_type: ProviderType;
  3059. enabled: boolean;
  3060. config: Record<string, unknown>;
  3061. attach_photo: boolean;
  3062. // Print lifecycle events
  3063. on_print_start: boolean;
  3064. on_print_complete: boolean;
  3065. on_print_failed: boolean;
  3066. on_print_stopped: boolean;
  3067. on_print_progress: boolean;
  3068. on_print_missing_spool_assignment: boolean;
  3069. on_billing_charge_failed: boolean;
  3070. // Printer status events
  3071. on_printer_offline: boolean;
  3072. on_printer_error: boolean;
  3073. on_ai_failure_detection: boolean;
  3074. on_filament_low: boolean;
  3075. on_maintenance_due: boolean;
  3076. // AMS environmental alarms (regular AMS)
  3077. on_ams_humidity_high: boolean;
  3078. on_ams_temperature_high: boolean;
  3079. on_ams_drying_suspended: boolean;
  3080. // AMS-HT environmental alarms
  3081. on_ams_ht_humidity_high: boolean;
  3082. on_ams_ht_temperature_high: boolean;
  3083. // Build plate detection
  3084. on_plate_not_empty: boolean;
  3085. on_plate_clear_required: boolean;
  3086. // Post-print outcome confirmation (#1898)
  3087. on_print_confirm_request: boolean;
  3088. telegram_verdict_mode: TelegramVerdictMode;
  3089. // Bed cooled
  3090. on_bed_cooled: boolean;
  3091. on_ha_sensor_alert: boolean;
  3092. on_location_ha_sensor_alert: boolean;
  3093. // First layer complete
  3094. on_first_layer_complete: boolean;
  3095. on_print_pause_upcoming: boolean;
  3096. on_app_message: boolean;
  3097. // Inventory stock alerts
  3098. on_stock_reorder_alert: boolean;
  3099. on_stock_break_alert: boolean;
  3100. // Print queue events
  3101. on_queue_job_added: boolean;
  3102. on_queue_job_assigned: boolean;
  3103. on_queue_job_started: boolean;
  3104. on_queue_job_waiting: boolean;
  3105. on_queue_job_skipped: boolean;
  3106. on_queue_job_failed: boolean;
  3107. on_queue_completed: boolean;
  3108. // Quiet hours
  3109. quiet_hours_enabled: boolean;
  3110. quiet_hours_start: string | null;
  3111. quiet_hours_end: string | null;
  3112. // Daily digest
  3113. daily_digest_enabled: boolean;
  3114. daily_digest_time: string | null;
  3115. // Printer filter
  3116. printer_id: number | null;
  3117. // Status tracking
  3118. last_success: string | null;
  3119. last_error: string | null;
  3120. last_error_at: string | null;
  3121. // Timestamps
  3122. created_at: string;
  3123. updated_at: string;
  3124. }
  3125. export interface NotificationProviderCreate {
  3126. name: string;
  3127. provider_type: ProviderType;
  3128. enabled?: boolean;
  3129. config: Record<string, unknown>;
  3130. attach_photo?: boolean;
  3131. // Print lifecycle events
  3132. on_print_start?: boolean;
  3133. on_print_complete?: boolean;
  3134. on_print_failed?: boolean;
  3135. on_print_stopped?: boolean;
  3136. on_print_progress?: boolean;
  3137. on_print_missing_spool_assignment?: boolean;
  3138. on_billing_charge_failed?: boolean;
  3139. // Printer status events
  3140. on_printer_offline?: boolean;
  3141. on_printer_error?: boolean;
  3142. on_ai_failure_detection?: boolean;
  3143. on_filament_low?: boolean;
  3144. on_maintenance_due?: boolean;
  3145. // AMS environmental alarms (regular AMS)
  3146. on_ams_humidity_high?: boolean;
  3147. on_ams_temperature_high?: boolean;
  3148. on_ams_drying_suspended?: boolean;
  3149. // AMS-HT environmental alarms
  3150. on_ams_ht_humidity_high?: boolean;
  3151. on_ams_ht_temperature_high?: boolean;
  3152. // Build plate detection
  3153. on_plate_not_empty?: boolean;
  3154. on_plate_clear_required?: boolean;
  3155. // Post-print outcome confirmation (#1898)
  3156. on_print_confirm_request?: boolean;
  3157. telegram_verdict_mode?: TelegramVerdictMode;
  3158. // Bed cooled
  3159. on_bed_cooled?: boolean;
  3160. on_ha_sensor_alert?: boolean;
  3161. on_location_ha_sensor_alert?: boolean;
  3162. // First layer complete
  3163. on_first_layer_complete?: boolean;
  3164. on_print_pause_upcoming?: boolean;
  3165. on_app_message?: boolean;
  3166. // Inventory stock alerts
  3167. on_stock_reorder_alert?: boolean;
  3168. on_stock_break_alert?: boolean;
  3169. // Print queue events
  3170. on_queue_job_added?: boolean;
  3171. on_queue_job_assigned?: boolean;
  3172. on_queue_job_started?: boolean;
  3173. on_queue_job_waiting?: boolean;
  3174. on_queue_job_skipped?: boolean;
  3175. on_queue_job_failed?: boolean;
  3176. on_queue_completed?: boolean;
  3177. // Quiet hours
  3178. quiet_hours_enabled?: boolean;
  3179. quiet_hours_start?: string | null;
  3180. quiet_hours_end?: string | null;
  3181. // Daily digest
  3182. daily_digest_enabled?: boolean;
  3183. daily_digest_time?: string | null;
  3184. // Printer filter
  3185. printer_id?: number | null;
  3186. }
  3187. export interface NotificationProviderUpdate {
  3188. name?: string;
  3189. provider_type?: ProviderType;
  3190. enabled?: boolean;
  3191. config?: Record<string, unknown>;
  3192. attach_photo?: boolean;
  3193. // Print lifecycle events
  3194. on_print_start?: boolean;
  3195. on_print_complete?: boolean;
  3196. on_print_failed?: boolean;
  3197. on_print_stopped?: boolean;
  3198. on_print_progress?: boolean;
  3199. on_print_missing_spool_assignment?: boolean;
  3200. on_billing_charge_failed?: boolean;
  3201. // Printer status events
  3202. on_printer_offline?: boolean;
  3203. on_printer_error?: boolean;
  3204. on_ai_failure_detection?: boolean;
  3205. on_filament_low?: boolean;
  3206. on_maintenance_due?: boolean;
  3207. // AMS environmental alarms (regular AMS)
  3208. on_ams_humidity_high?: boolean;
  3209. on_ams_temperature_high?: boolean;
  3210. on_ams_drying_suspended?: boolean;
  3211. // AMS-HT environmental alarms
  3212. on_ams_ht_humidity_high?: boolean;
  3213. on_ams_ht_temperature_high?: boolean;
  3214. // Build plate detection
  3215. on_plate_not_empty?: boolean;
  3216. on_plate_clear_required?: boolean;
  3217. // Post-print outcome confirmation (#1898)
  3218. on_print_confirm_request?: boolean;
  3219. telegram_verdict_mode?: TelegramVerdictMode;
  3220. // Bed cooled
  3221. on_bed_cooled?: boolean;
  3222. on_ha_sensor_alert?: boolean;
  3223. on_location_ha_sensor_alert?: boolean;
  3224. // First layer complete
  3225. on_first_layer_complete?: boolean;
  3226. on_print_pause_upcoming?: boolean;
  3227. on_app_message?: boolean;
  3228. // Inventory stock alerts
  3229. on_stock_reorder_alert?: boolean;
  3230. on_stock_break_alert?: boolean;
  3231. // Print queue events
  3232. on_queue_job_added?: boolean;
  3233. on_queue_job_assigned?: boolean;
  3234. on_queue_job_started?: boolean;
  3235. on_queue_job_waiting?: boolean;
  3236. on_queue_job_skipped?: boolean;
  3237. on_queue_job_failed?: boolean;
  3238. on_queue_completed?: boolean;
  3239. // Quiet hours
  3240. quiet_hours_enabled?: boolean;
  3241. quiet_hours_start?: string | null;
  3242. quiet_hours_end?: string | null;
  3243. // Daily digest
  3244. daily_digest_enabled?: boolean;
  3245. daily_digest_time?: string | null;
  3246. // Printer filter
  3247. printer_id?: number | null;
  3248. }
  3249. // GitHub Backup types
  3250. export type ScheduleType = 'hourly' | 'daily' | 'weekly';
  3251. export type GitProviderType = 'github' | 'gitea' | 'forgejo' | 'gitlab';
  3252. /** How many cloud accounts a backup would collect presets from. Counts only —
  3253. * with auth enabled the accounts belong to individual users, so the backup
  3254. * administrator sees how many, never whose. */
  3255. export interface CloudAccountCounts {
  3256. bambu: number;
  3257. orca: number;
  3258. }
  3259. export interface GitHubBackupConfig {
  3260. id: number;
  3261. repository_url: string;
  3262. has_token: boolean;
  3263. branch: string;
  3264. provider: GitProviderType;
  3265. allow_insecure_http: boolean;
  3266. schedule_enabled: boolean;
  3267. schedule_type: ScheduleType;
  3268. backup_kprofiles: boolean;
  3269. backup_cloud_profiles: boolean;
  3270. backup_settings: boolean;
  3271. backup_spools: boolean;
  3272. backup_archives: boolean;
  3273. enabled: boolean;
  3274. last_backup_at: string | null;
  3275. last_backup_status: string | null;
  3276. last_backup_message: string | null;
  3277. last_backup_commit_sha: string | null;
  3278. next_scheduled_run: string | null;
  3279. created_at: string;
  3280. updated_at: string;
  3281. }
  3282. export interface GitHubBackupConfigCreate {
  3283. repository_url: string;
  3284. access_token: string;
  3285. branch?: string;
  3286. provider?: GitProviderType;
  3287. allow_insecure_http?: boolean;
  3288. schedule_enabled?: boolean;
  3289. schedule_type?: ScheduleType;
  3290. backup_kprofiles?: boolean;
  3291. backup_cloud_profiles?: boolean;
  3292. backup_settings?: boolean;
  3293. backup_spools?: boolean;
  3294. backup_archives?: boolean;
  3295. enabled?: boolean;
  3296. }
  3297. export interface GitHubBackupLog {
  3298. id: number;
  3299. config_id: number;
  3300. started_at: string;
  3301. completed_at: string | null;
  3302. status: string;
  3303. trigger: string;
  3304. commit_sha: string | null;
  3305. files_changed: number;
  3306. error_message: string | null;
  3307. }
  3308. export interface GitHubBackupStatus {
  3309. configured: boolean;
  3310. enabled: boolean;
  3311. is_running: boolean;
  3312. restore_running: boolean;
  3313. progress: string | null;
  3314. last_backup_at: string | null;
  3315. last_backup_status: string | null;
  3316. next_scheduled_run: string | null;
  3317. }
  3318. // Restore from a Git backup (#2656). Cloud profiles are absent deliberately —
  3319. // the backup collector never writes them, so there is nothing to restore.
  3320. export type RestoreCategory = 'kprofiles' | 'settings' | 'spools' | 'archives';
  3321. export interface GitHubCommitInfo {
  3322. sha: string;
  3323. message: string;
  3324. author: string;
  3325. date: string;
  3326. }
  3327. export interface GitHubCommitListResponse {
  3328. success: boolean;
  3329. message: string;
  3330. branch: string;
  3331. commits: GitHubCommitInfo[];
  3332. }
  3333. /**
  3334. * Values the server interpolates into a translated note or preview detail.
  3335. * Kept to strings and numbers on purpose — anything richer would have to be
  3336. * formatted server-side and could not be translated.
  3337. */
  3338. export type GitHubRestoreParams = Record<string, string | number>;
  3339. export interface GitHubRestorePreviewCategory {
  3340. category: RestoreCategory;
  3341. available: boolean;
  3342. item_count: number;
  3343. /** English rendering. Used as i18next's defaultValue, never shown on its own. */
  3344. detail: string | null;
  3345. /** Key under backup.restoreFromGit.details, or null when there is no caveat. */
  3346. detail_code: string | null;
  3347. detail_params: GitHubRestoreParams;
  3348. }
  3349. export interface GitHubRestorePreview {
  3350. success: boolean;
  3351. message: string;
  3352. ref: string;
  3353. commit: GitHubCommitInfo | null;
  3354. metadata_version: string | null;
  3355. categories: GitHubRestorePreviewCategory[];
  3356. }
  3357. export interface GitHubRestoreRequest {
  3358. ref?: string;
  3359. categories: RestoreCategory[];
  3360. overwrite_existing?: boolean;
  3361. }
  3362. /**
  3363. * One tally note, as a translation code plus its parameters (#2656).
  3364. *
  3365. * Same contract as {@link LocalBackupPathCheck} one card down: the server picks
  3366. * the code and supplies typed params, and the client renders
  3367. * ``t(`backup.restoreFromGit.notes.${code}`, { ...params, defaultValue: message })``.
  3368. * A code the client does not know yet falls back to the English `message`
  3369. * rather than showing the raw key.
  3370. */
  3371. export interface GitHubRestoreNote {
  3372. code: string;
  3373. params: GitHubRestoreParams;
  3374. message: string;
  3375. }
  3376. export interface GitHubRestoreCategoryResult {
  3377. restored: number;
  3378. skipped: number;
  3379. failed: number;
  3380. notes: GitHubRestoreNote[];
  3381. }
  3382. export interface GitHubRestoreResponse {
  3383. success: boolean;
  3384. message: string;
  3385. log_id: number | null;
  3386. ref: string | null;
  3387. results: Record<string, GitHubRestoreCategoryResult>;
  3388. }
  3389. export interface LocalBackupStatus {
  3390. enabled: boolean;
  3391. schedule: string;
  3392. time: string;
  3393. retention: number;
  3394. path: string;
  3395. default_path: string;
  3396. is_running: boolean;
  3397. last_backup_at: string | null;
  3398. last_status: string | null;
  3399. last_message: string | null;
  3400. next_run: string | null;
  3401. timezone: string;
  3402. }
  3403. export interface LocalBackupFile {
  3404. filename: string;
  3405. size: number;
  3406. created_at: string;
  3407. }
  3408. /** Result of writing a probe file into the configured backup directory (#2544). */
  3409. export interface LocalBackupPathCheck {
  3410. writable: boolean;
  3411. path: string;
  3412. /** 'ok' | 'sandboxed' | 'read_only' | 'permission_denied' | 'no_space' | 'not_a_directory' | 'missing' | 'error' */
  3413. code: string;
  3414. /** Raw OS error, shown as-is under the translated explanation. */
  3415. detail: string | null;
  3416. /** Copy-pasteable fix (systemd drop-in, compose snippet) — not translated. */
  3417. remedy: string | null;
  3418. message: string;
  3419. /** 'container_ephemeral' — writable, but the backups die with the container. */
  3420. warning: string | null;
  3421. }
  3422. export interface ObicoDetectionEvent {
  3423. printer_id: number;
  3424. task_name: string;
  3425. timestamp: string;
  3426. current_p: number;
  3427. score: number;
  3428. class: 'safe' | 'warning' | 'failure';
  3429. detections: number;
  3430. }
  3431. export interface ObicoStatus {
  3432. is_running: boolean;
  3433. last_error: string | null;
  3434. per_printer: Record<string, { class: string; frame_count: number; score: number }>;
  3435. thresholds: { low: number; high: number; pause?: number };
  3436. history: ObicoDetectionEvent[];
  3437. enabled: boolean;
  3438. ml_url: string;
  3439. sensitivity: 'low' | 'medium' | 'high';
  3440. action: 'notify' | 'pause' | 'pause_and_off';
  3441. poll_interval: number;
  3442. external_url_configured: boolean;
  3443. }
  3444. // Lightweight subset served under printers:read for the printer-card badge (#1546)
  3445. export interface ObicoPrinterStatus {
  3446. enabled: boolean;
  3447. // null = all printers are monitored
  3448. monitored_printers: number[] | null;
  3449. per_printer: Record<string, { class: string; frame_count: number; score: number }>;
  3450. // null = no error, or the viewer lacks settings:read (error strings can embed config URLs)
  3451. last_error: string | null;
  3452. }
  3453. export interface ObicoTestConnection {
  3454. ok: boolean;
  3455. status_code: number | null;
  3456. body: string | null;
  3457. error: string | null;
  3458. // Whether the ML API accepted the token. null = not determined (the health
  3459. // check failed first, or the token probe itself errored).
  3460. auth_ok: boolean | null;
  3461. }
  3462. // How sure Gadget must be before suggesting a warning or pause (API levels 1-5).
  3463. export type OctoEverywhereConfidence = 'lowest' | 'low' | 'medium' | 'high' | 'highest';
  3464. export interface OctoEverywhereDetection {
  3465. class: 'safe' | 'warning' | 'failure' | 'error' | 'unknown';
  3466. print_quality: number | null;
  3467. frame_count: number;
  3468. error?: string | null;
  3469. error_code: string | null;
  3470. }
  3471. export interface OctoEverywhereDetectionEvent {
  3472. timestamp: string;
  3473. printer_id: number;
  3474. class: OctoEverywhereDetection['class'];
  3475. print_quality: number | null;
  3476. }
  3477. export interface OctoEverywhereStatus {
  3478. enabled: boolean;
  3479. api_key_configured: boolean;
  3480. confidence: OctoEverywhereConfidence;
  3481. action: 'notify' | 'pause' | 'pause_and_off';
  3482. poll_interval: number;
  3483. is_running: boolean;
  3484. last_error: string | null;
  3485. last_error_code: string | null;
  3486. per_printer: Record<string, OctoEverywhereDetection>;
  3487. history: OctoEverywhereDetectionEvent[];
  3488. notifications: { configured: boolean; uncovered_printers: number[] };
  3489. }
  3490. export interface OctoEverywherePrinterStatus {
  3491. enabled: boolean;
  3492. // null = all printers are monitored
  3493. monitored_printers: number[] | null;
  3494. per_printer: Record<string, OctoEverywhereDetection>;
  3495. last_error: string | null;
  3496. last_error_code: string | null;
  3497. }
  3498. export interface OctoEverywhereTestConnection {
  3499. ok: boolean;
  3500. status_code: number | null;
  3501. error: string | null;
  3502. error_code: string | null;
  3503. }
  3504. export interface GitHubTestConnectionResponse {
  3505. success: boolean;
  3506. message: string;
  3507. repo_name: string | null;
  3508. permissions: Record<string, boolean> | null;
  3509. // true = confirmed private, false = confirmed public/internal,
  3510. // null = could not determine. Backend rejects save unless true.
  3511. is_private: boolean | null;
  3512. }
  3513. export interface GitHubBackupTriggerResponse {
  3514. success: boolean;
  3515. message: string;
  3516. log_id: number | null;
  3517. commit_sha: string | null;
  3518. files_changed: number;
  3519. }
  3520. export interface NotificationTestRequest {
  3521. provider_type: ProviderType;
  3522. config: Record<string, unknown>;
  3523. attach_photo?: boolean;
  3524. /** The saved provider being edited: its stored secrets fill in the placeholders. */
  3525. provider_id?: number;
  3526. }
  3527. export interface NotificationTestResponse {
  3528. success: boolean;
  3529. message: string;
  3530. }
  3531. // Provider-specific config types for reference
  3532. export interface CallMeBotConfig {
  3533. phone: string;
  3534. apikey: string;
  3535. }
  3536. export interface NtfyConfig {
  3537. server?: string;
  3538. topic: string;
  3539. auth_token?: string | null;
  3540. }
  3541. export interface PushoverConfig {
  3542. user_key: string;
  3543. app_token: string;
  3544. priority?: number;
  3545. }
  3546. export interface NotifyConfig {
  3547. device_id: string;
  3548. token: string;
  3549. icon_url?: string;
  3550. group_type?: string;
  3551. live_activities?: boolean;
  3552. lock_screen_widgets?: boolean;
  3553. live_activity_privacy?: boolean;
  3554. live_activity_stage?: boolean;
  3555. live_activity_style?: 'bar' | 'segments' | 'none';
  3556. live_activity_metrics?: ('progress' | 'eta' | 'layers' | 'nozzle' | 'bed' | 'chamber')[];
  3557. live_activity_button_url?: string;
  3558. live_activity_symbol?: string;
  3559. live_activity_tint?: string;
  3560. time_sensitive?: boolean;
  3561. }
  3562. export interface TelegramConfig {
  3563. bot_token: string;
  3564. chat_id: string;
  3565. }
  3566. export interface EmailConfig {
  3567. smtp_server: string;
  3568. smtp_port?: number;
  3569. username: string;
  3570. password: string;
  3571. from_email: string;
  3572. to_email: string;
  3573. use_tls?: boolean;
  3574. }
  3575. // Notification Template types
  3576. export interface NotificationTemplate {
  3577. id: number;
  3578. event_type: string;
  3579. name: string;
  3580. title_template: string;
  3581. body_template: string;
  3582. is_default: boolean;
  3583. created_at: string;
  3584. updated_at: string;
  3585. }
  3586. export interface NotificationTemplateUpdate {
  3587. title_template?: string;
  3588. body_template?: string;
  3589. }
  3590. export interface EventVariablesResponse {
  3591. event_type: string;
  3592. event_name: string;
  3593. variables: string[];
  3594. supports_photo: boolean;
  3595. }
  3596. export interface TemplatePreviewRequest {
  3597. event_type: string;
  3598. title_template: string;
  3599. body_template: string;
  3600. }
  3601. export interface TemplatePreviewResponse {
  3602. title: string;
  3603. body: string;
  3604. }
  3605. // Notification Log types
  3606. export interface NotificationLogEntry {
  3607. id: number;
  3608. provider_id: number;
  3609. provider_name: string | null;
  3610. provider_type: string | null;
  3611. event_type: string;
  3612. title: string;
  3613. message: string;
  3614. success: boolean;
  3615. error_message: string | null;
  3616. printer_id: number | null;
  3617. printer_name: string | null;
  3618. created_at: string;
  3619. }
  3620. export interface NotificationLogStats {
  3621. total: number;
  3622. success_count: number;
  3623. failure_count: number;
  3624. by_event_type: Record<string, number>;
  3625. by_provider: Record<string, number>;
  3626. }
  3627. // Spoolman types
  3628. export interface SpoolmanStatus {
  3629. enabled: boolean;
  3630. connected: boolean;
  3631. url: string | null;
  3632. native_tags?: boolean; // Spoolman 0.27+ links tags natively
  3633. }
  3634. export interface SpoolmanTagMigrationReport {
  3635. dry_run: boolean;
  3636. moved: number[];
  3637. already: number;
  3638. slot_ids: number;
  3639. conflicts: Array<{ spool_id: number; tag: string; holder: number }>; // holder -1: a filament holds the tag
  3640. }
  3641. export interface SkippedSpool {
  3642. location: string;
  3643. reason: string;
  3644. filament_type: string | null;
  3645. color: string | null;
  3646. }
  3647. export interface SpoolmanSyncResult {
  3648. success: boolean;
  3649. synced_count: number;
  3650. skipped_count: number;
  3651. skipped: SkippedSpool[];
  3652. errors: string[];
  3653. }
  3654. export interface UnlinkedSpool {
  3655. id: number;
  3656. filament_name: string | null;
  3657. filament_vendor: string | null;
  3658. filament_material: string | null;
  3659. filament_color_hex: string | null;
  3660. remaining_weight: number | null;
  3661. location: string | null;
  3662. }
  3663. export interface LinkedSpoolInfo {
  3664. id: number;
  3665. remaining_weight: number | null;
  3666. filament_weight: number | null;
  3667. }
  3668. export interface LinkedSpoolsMap {
  3669. linked: Record<string, LinkedSpoolInfo>; // tag (uppercase) -> spool info
  3670. }
  3671. export interface SpoolmanVendor {
  3672. id: number;
  3673. name: string;
  3674. }
  3675. export interface SpoolmanFilamentEntry {
  3676. id: number;
  3677. name: string;
  3678. material: string | null;
  3679. color_hex: string | null;
  3680. color_name: string | null;
  3681. weight: number | null;
  3682. spool_weight: number | null;
  3683. vendor: SpoolmanVendor | null;
  3684. }
  3685. // Inventory types
  3686. // Label printing (#809). Mirror of backend.app.services.label_renderer.TemplateName.
  3687. export type SpoolLabelTemplate =
  3688. | 'ams_holder_74x33'
  3689. | 'ams_holder_75x55'
  3690. | 'box_40x30'
  3691. | 'box_62x29'
  3692. | 'avery_5160'
  3693. | 'avery_l7160';
  3694. // Mirror of backend.app.services.label_renderer.LabelField, in print order (#2981).
  3695. export const SPOOL_LABEL_FIELDS = [
  3696. 'brand',
  3697. 'material',
  3698. 'hex',
  3699. 'name',
  3700. 'location',
  3701. 'material_number',
  3702. 'temps',
  3703. 'weight',
  3704. 'note',
  3705. 'added',
  3706. 'qr',
  3707. 'spool_id',
  3708. ] as const;
  3709. export type SpoolLabelField = (typeof SPOOL_LABEL_FIELDS)[number];
  3710. // Mirror of DEFAULT_LABEL_FIELDS: what a label carried before fields were selectable.
  3711. export const DEFAULT_SPOOL_LABEL_FIELDS: SpoolLabelField[] = [
  3712. 'brand',
  3713. 'material',
  3714. 'hex',
  3715. 'name',
  3716. 'location',
  3717. 'qr',
  3718. 'spool_id',
  3719. ];
  3720. // A sheet of identical labels in a grid, in millimetres (#3296). Mirror of
  3721. // backend.app.schemas.label_template.SheetLayoutSpec.
  3722. export type LabelPageSize = 'a4' | 'letter';
  3723. export interface LabelSheetLayout {
  3724. page: LabelPageSize;
  3725. label_w_mm: number;
  3726. label_h_mm: number;
  3727. cols: number;
  3728. rows: number;
  3729. top_mm: number;
  3730. left_mm: number;
  3731. col_gap_mm: number;
  3732. row_gap_mm: number;
  3733. }
  3734. // A custom sheet saved under a name, shared by everyone on the install.
  3735. export interface SavedLabelTemplate {
  3736. id: number;
  3737. name: string;
  3738. layout: LabelSheetLayout;
  3739. created_at: string;
  3740. updated_at: string;
  3741. }
  3742. // A built-in template, or "custom" with the sheet itself in ``layout``.
  3743. export type SpoolLabelRequestTemplate = SpoolLabelTemplate | 'custom';
  3744. export interface PrintSpoolLabelsRequest {
  3745. spool_ids: number[];
  3746. template: SpoolLabelRequestTemplate;
  3747. layout?: LabelSheetLayout;
  3748. monochrome: boolean;
  3749. starting_position: number;
  3750. fields?: SpoolLabelField[];
  3751. format?: 'pdf' | 'png';
  3752. dpi?: 203 | 300 | 600;
  3753. }
  3754. export interface PreviewSpoolLabelRequest {
  3755. spool_id: number;
  3756. template: SpoolLabelRequestTemplate;
  3757. layout?: LabelSheetLayout;
  3758. monochrome: boolean;
  3759. fields: SpoolLabelField[];
  3760. }
  3761. export interface InventorySpool {
  3762. id: number;
  3763. material: string;
  3764. subtype: string | null;
  3765. color_name: string | null;
  3766. // True when color_name was synthesised from subtype because Spoolman has no
  3767. // stored value (Spoolman-backed inventory only). The edit form uses this to
  3768. // leave the input blank, so the user doesn't round-trip the synth value
  3769. // back to Spoolman as if it were a real user-set color_name (#1319).
  3770. color_name_is_synthesized?: boolean;
  3771. rgba: string | null;
  3772. // Multi-colour gradient stops (#1154): comma-separated 6/8-char hex.
  3773. extra_colors: string | null;
  3774. // Visual effect overlay: sparkle | wood | marble | glow | matte.
  3775. effect_type: string | null;
  3776. brand: string | null;
  3777. label_weight: number;
  3778. core_weight: number;
  3779. // Spoolman-backed inventory only: true when the spool has no tare of its
  3780. // own and core_weight is the filament type's. Absent for local spools (#2908).
  3781. core_weight_is_inherited?: boolean;
  3782. core_weight_catalog_id: number | null;
  3783. weight_used: number;
  3784. // Anchor for the resettable "Total Consumed" display (#1390). The
  3785. // counter shown on the Inventory page is `weight_used - weight_used_baseline`;
  3786. // remaining is still `label_weight - weight_used`, so "Reset usage to 0"
  3787. // zeroes the counter without disturbing remaining. Optional for back-compat
  3788. // with rows from a pre-migration DB snapshot — default to 0.
  3789. weight_used_baseline?: number;
  3790. slicer_filament: string | null;
  3791. slicer_filament_name: string | null;
  3792. nozzle_temp_min: number | null;
  3793. nozzle_temp_max: number | null;
  3794. note: string | null;
  3795. added_full: boolean | null;
  3796. last_used: string | null;
  3797. // Spoolman mode: when the spool was first printed with (#3407).
  3798. first_used?: string | null;
  3799. // Last drying (#2863): stamped when an AMS drying run of at least half its
  3800. // length ends, or set by hand. Temperature and hours are null when unknown.
  3801. last_dried_at?: string | null;
  3802. last_dried_temp?: number | null;
  3803. last_dried_hours?: number | null;
  3804. encode_time: string | null;
  3805. tag_uid: string | null;
  3806. tray_uuid: string | null;
  3807. data_origin: string | null;
  3808. tag_type: string | null;
  3809. archived_at: string | null;
  3810. created_at: string;
  3811. updated_at: string;
  3812. cost_per_kg: number | null;
  3813. // Spoolman mode: what prints are charged per kg, the spool's own price or
  3814. // else its filament's. Display only; the form edits cost_per_kg.
  3815. effective_cost_per_kg?: number | null;
  3816. last_scale_weight: number | null;
  3817. last_weighed_at: string | null;
  3818. // User-defined category + per-spool low-stock threshold override (#729).
  3819. category: string | null;
  3820. low_stock_threshold_pct: number | null;
  3821. // Internal material / article number (#2870) — the purchasing identifier
  3822. // shared by all spools of the same product.
  3823. material_number: string | null;
  3824. k_profiles?: SpoolKProfile[];
  3825. storage_location?: string | null;
  3826. location_id?: number | null;
  3827. // Supplier assignments (#2988). Absent in Spoolman mode — Spoolman's
  3828. // vendor is the manufacturer, not the seller, so there is no mapping.
  3829. suppliers?: SpoolSupplierLink[];
  3830. }
  3831. // ── Suppliers (#2988) ──────────────────────────────────────────────────────
  3832. /** Where filament is bought — distinct from brand (who made it). */
  3833. export interface Supplier {
  3834. id: number;
  3835. name: string;
  3836. website: string | null;
  3837. customer_number: string | null;
  3838. note: string | null;
  3839. /** Spools referencing this supplier; a referenced supplier cannot be deleted. */
  3840. spool_count: number;
  3841. created_at: string;
  3842. updated_at: string;
  3843. }
  3844. export interface SupplierInput {
  3845. name: string;
  3846. website?: string | null;
  3847. customer_number?: string | null;
  3848. note?: string | null;
  3849. }
  3850. /** One spool-to-supplier assignment as written by the spool dialog. */
  3851. export interface SpoolSupplierLinkInput {
  3852. supplier_id: number;
  3853. /** The supplier's own article number — NOT the internal material number. */
  3854. supplier_article_number?: string | null;
  3855. /** Quoted price for comparison — never the cost basis (spool.cost_per_kg). */
  3856. quoted_price_per_kg?: number | null;
  3857. /** Marks where this concrete spool was actually bought. */
  3858. is_purchase_source?: boolean;
  3859. }
  3860. export interface SpoolSupplierLink {
  3861. id: number;
  3862. supplier_id: number;
  3863. supplier_name: string;
  3864. supplier_article_number: string | null;
  3865. quoted_price_per_kg: number | null;
  3866. is_purchase_source: boolean;
  3867. }
  3868. /** Per-supplier inventory aggregate (#2988), purchase-source spools only. */
  3869. export interface SupplierStats {
  3870. supplier_id: number;
  3871. supplier_name: string;
  3872. spool_count: number;
  3873. remaining_g: number;
  3874. consumed_g: number;
  3875. cost: number;
  3876. }
  3877. /** Per-material-number inventory aggregate (#2870). */
  3878. export interface MaterialNumberStats {
  3879. material_number: string;
  3880. spool_count: number;
  3881. remaining_g: number;
  3882. consumed_g: number;
  3883. cost: number;
  3884. }
  3885. export interface SpoolmanBulkCreateResult {
  3886. created: InventorySpool[];
  3887. requested_count: number;
  3888. failed_count: number;
  3889. }
  3890. // ── CSV import/export (#1576) ──────────────────────────────────────────────
  3891. /** One row's outcome from the import preview / real import. */
  3892. export interface CsvImportRow {
  3893. row_number: number;
  3894. status: 'valid' | 'error' | 'skipped';
  3895. reason: string | null;
  3896. material: string | null;
  3897. brand: string | null;
  3898. color_name: string | null;
  3899. rgba: string | null;
  3900. /** rgba/extra_colors/effect_type were filled from the Color Catalog. */
  3901. resolved_color: boolean;
  3902. /** The catalog match came from a different material's variant (no exact
  3903. * material match). Shown as a warning in the preview. */
  3904. cross_material_color: boolean;
  3905. /** An active spool with the same material+brand+color already exists.
  3906. * Informational only — the import still creates the row. */
  3907. duplicate_of_existing: boolean;
  3908. }
  3909. /** Dry-run preview: per-row classification, no rows written. */
  3910. export interface CsvImportPreview {
  3911. columns: string[];
  3912. total: number;
  3913. valid_count: number;
  3914. error_count: number;
  3915. skipped_count: number;
  3916. rows: CsvImportRow[];
  3917. warnings: string[];
  3918. }
  3919. /** Summary returned after a real (non-dry-run) import. */
  3920. export interface CsvImportResult {
  3921. created: number;
  3922. skipped: number;
  3923. errors: number;
  3924. error_rows: CsvImportRow[];
  3925. }
  3926. export interface SpoolUsageRecord {
  3927. id: number;
  3928. // null: the spool was deleted, its usage kept
  3929. spool_id: number | null;
  3930. // Spoolman mode: the Spoolman spool charged (#3407); spool_id is null then.
  3931. spoolman_spool_id?: number | null;
  3932. printer_id: number | null;
  3933. print_name: string | null;
  3934. weight_used: number;
  3935. percent_used: number;
  3936. status: string;
  3937. cost: number | null;
  3938. created_at: string;
  3939. }
  3940. export interface SpoolKProfile {
  3941. id: number;
  3942. spool_id: number;
  3943. printer_id: number;
  3944. extruder: number;
  3945. nozzle_diameter: string;
  3946. nozzle_type: string | null;
  3947. k_value: number;
  3948. name: string | null;
  3949. cali_idx: number | null;
  3950. setting_id: string | null;
  3951. created_at: string;
  3952. }
  3953. export interface SpoolKProfileInput {
  3954. printer_id: number;
  3955. extruder?: number;
  3956. nozzle_diameter?: string;
  3957. nozzle_type?: string | null;
  3958. k_value: number;
  3959. name?: string | null;
  3960. cali_idx?: number | null;
  3961. setting_id?: string | null;
  3962. }
  3963. /**
  3964. * One per-printer-model override of a spool's slicer filament preset.
  3965. *
  3966. * A cloud or Orca preset is bound to a printer model ("@BBL X1C"), so the
  3967. * spool's single `slicer_filament` is wrong as soon as the spool is used on a
  3968. * second model. `nozzle_diameter` is "" for the model's own default and a bare
  3969. * decimal ("0.2") for a per-hotend exception; the backend resolves
  3970. * exact (model, diameter) -> (model, "") -> the spool's own preset.
  3971. */
  3972. export interface SlotSpoolDefaults {
  3973. slicer_filament: string | null;
  3974. slicer_filament_name: string | null;
  3975. cali_idx: number | null;
  3976. k_value: number | null;
  3977. profile_name: string | null;
  3978. extruder: number | null;
  3979. nozzle_diameter: string;
  3980. }
  3981. export interface SpoolFilamentPresetInput {
  3982. printer_model: string;
  3983. nozzle_diameter: string;
  3984. slicer_filament: string | null;
  3985. slicer_filament_name: string | null;
  3986. }
  3987. export interface SpoolFilamentPreset extends SpoolFilamentPresetInput {
  3988. id: number;
  3989. spool_id: number;
  3990. created_at: string;
  3991. }
  3992. /**
  3993. * What a new spool of one product starts with (#1326): the slicer preset, the
  3994. * per-model preset overrides and the K profiles. `color_name` "" is the
  3995. * default for every colour of the product; one with a colour wins over it per
  3996. * preset and per hotend. Shared by both inventory modes.
  3997. */
  3998. export interface ProfileDefaultKey {
  3999. brand: string;
  4000. material: string;
  4001. subtype: string;
  4002. color_name: string;
  4003. }
  4004. export interface ProfileDefaultInput extends ProfileDefaultKey {
  4005. slicer_filament: string | null;
  4006. slicer_filament_name: string | null;
  4007. presets: SpoolFilamentPresetInput[];
  4008. k_profiles: SpoolKProfileInput[];
  4009. }
  4010. export interface ProfileDefault extends ProfileDefaultInput {
  4011. id: number;
  4012. updated_at: string;
  4013. }
  4014. /** Both levels of a product's default merged, as a create applies them. */
  4015. export interface ResolvedProfileDefault {
  4016. slicer_filament: string | null;
  4017. slicer_filament_name: string | null;
  4018. presets: SpoolFilamentPresetInput[];
  4019. k_profiles: SpoolKProfileInput[];
  4020. default_ids: number[];
  4021. }
  4022. /** One inventory-bound AMS slot, as returned by `/printers/{id}/inventory-remain`. */
  4023. export interface SlotMaterial {
  4024. ams_id: number;
  4025. tray_id: number;
  4026. global_tray_id: number;
  4027. /** Opaque grouping key from the backend. Two slots back each other up under
  4028. * AMS Filament Backup only when both `material_key` and `extruder` match.
  4029. * Never parse it — the format belongs to the backend's identity rule. */
  4030. material_key: string;
  4031. remaining_g: number;
  4032. /** 0 = right / single nozzle, 1 = left. */
  4033. extruder: number;
  4034. /** How the bound spool should be *named* — display only, never matched on.
  4035. * The printer has no brand field and reports no sub-brand for a
  4036. * third-party spool, so this is the only place a slot's real identity
  4037. * exists. Null when the binding resolves to a spool we cannot describe. */
  4038. spool?: SlotSpoolIdentity | null;
  4039. /** Per-kg rate a print off this spool is charged at; null when unpriced,
  4040. * which is charged at the default rate. Optional for an older backend. */
  4041. cost_per_kg?: number | null;
  4042. }
  4043. /** Display identity of an inventory-bound slot. See `SlotMaterial.spool`. */
  4044. export interface SlotSpoolIdentity {
  4045. brand: string | null;
  4046. material: string | null;
  4047. subtype: string | null;
  4048. color_name: string | null;
  4049. rgba: string | null;
  4050. /** Comma-separated hex stops for a multi-colour spool, and the effect
  4051. * overlay — the two things a tray record cannot carry, so a slot swatch
  4052. * can be drawn the way the inventory row draws it (#3159).
  4053. *
  4054. * Optional rather than required: the backend sends both keys on every
  4055. * binding, but a frontend running against an older one gets neither, and
  4056. * every reader here already falls back to a solid swatch. */
  4057. extra_colors?: string | null;
  4058. effect_type?: string | null;
  4059. }
  4060. export interface InventoryRemainResponse {
  4061. /** Currently-loaded, inventory-bound slots only — drives the prefer-lowest sort. */
  4062. inventory_remain_g: Record<string, number>;
  4063. /** Every inventory binding on the printer, with identity + extruder side. */
  4064. slot_materials: SlotMaterial[];
  4065. }
  4066. export interface SpoolAssignment {
  4067. id: number;
  4068. spool_id: number;
  4069. printer_id: number;
  4070. printer_name: string | null;
  4071. ams_id: number;
  4072. tray_id: number;
  4073. fingerprint_color: string | null;
  4074. fingerprint_type: string | null;
  4075. spool?: InventorySpool | null;
  4076. configured: boolean;
  4077. pending_config?: boolean; // Slot was empty at assign time; will configure on insert
  4078. created_at: string;
  4079. ams_label?: string | null; // User-defined friendly name for the AMS unit
  4080. }
  4081. export interface FilamentSkuSettings {
  4082. id: number;
  4083. material: string;
  4084. subtype: string | null;
  4085. brand: string | null;
  4086. color_name: string | null;
  4087. lead_time_days: number;
  4088. safety_margin_value: number;
  4089. safety_margin_unit: 'days' | 'g';
  4090. alerts_snoozed: boolean;
  4091. }
  4092. export interface ShoppingListItem {
  4093. id: number;
  4094. material: string;
  4095. subtype: string | null;
  4096. brand: string | null;
  4097. color_name: string | null;
  4098. quantity_spools: number;
  4099. note: string | null;
  4100. status: 'pending' | 'purchased' | 'received';
  4101. purchased_at: string | null;
  4102. added_at: string;
  4103. }
  4104. export interface ShoppingListItemCreate {
  4105. material: string;
  4106. subtype: string | null;
  4107. brand: string | null;
  4108. color_name: string | null;
  4109. quantity_spools: number;
  4110. note?: string | null;
  4111. }
  4112. // Update types
  4113. export interface VersionInfo {
  4114. version: string;
  4115. repo: string;
  4116. }
  4117. export interface UpdateCheckResult {
  4118. update_available: boolean;
  4119. current_version: string;
  4120. latest_version: string | null;
  4121. release_name?: string;
  4122. release_notes?: string;
  4123. release_url?: string;
  4124. published_at?: string;
  4125. error?: string;
  4126. message?: string;
  4127. is_docker?: boolean;
  4128. is_ha_addon?: boolean;
  4129. is_windows_installer?: boolean;
  4130. update_method?: 'docker' | 'git' | 'ha_addon' | 'windows_installer';
  4131. installer_download_url?: string | null;
  4132. // Best-effort guess at the compose directory (#2664). Prefill only — the
  4133. // value the user saved lives on AppSettings.docker_compose_dir, so clearing
  4134. // that field falls back to this guess instead of resurrecting the old value.
  4135. compose_dir_detected?: string | null;
  4136. }
  4137. export interface UpdateStatus {
  4138. status: 'idle' | 'checking' | 'downloading' | 'installing' | 'complete' | 'error';
  4139. progress: number;
  4140. message: string;
  4141. error: string | null;
  4142. }
  4143. // Maintenance types
  4144. export interface MaintenanceType {
  4145. id: number;
  4146. name: string;
  4147. description: string | null;
  4148. default_interval_hours: number;
  4149. interval_type: 'hours' | 'days'; // "hours" = print hours, "days" = calendar days
  4150. icon: string | null;
  4151. wiki_url: string | null; // Documentation link
  4152. is_system: boolean;
  4153. created_at: string;
  4154. }
  4155. export interface MaintenanceTypeCreate {
  4156. name: string;
  4157. description?: string | null;
  4158. default_interval_hours?: number;
  4159. interval_type?: 'hours' | 'days';
  4160. icon?: string | null;
  4161. wiki_url?: string | null;
  4162. }
  4163. export interface MaintenanceStatus {
  4164. id: number;
  4165. printer_id: number;
  4166. printer_name: string;
  4167. printer_model: string | null;
  4168. maintenance_type_id: number;
  4169. maintenance_type_name: string;
  4170. maintenance_type_icon: string | null;
  4171. maintenance_type_wiki_url: string | null; // Custom wiki URL from type
  4172. enabled: boolean;
  4173. interval_hours: number; // For hours type: print hours; for days type: number of days
  4174. interval_type: 'hours' | 'days';
  4175. current_hours: number;
  4176. hours_since_maintenance: number;
  4177. hours_until_due: number;
  4178. days_since_maintenance: number | null; // For days type
  4179. days_until_due: number | null; // For days type
  4180. is_due: boolean;
  4181. is_warning: boolean;
  4182. last_performed_at: string | null;
  4183. }
  4184. export interface PrinterMaintenanceOverview {
  4185. printer_id: number;
  4186. printer_name: string;
  4187. printer_model: string | null;
  4188. total_print_hours: number;
  4189. maintenance_items: MaintenanceStatus[];
  4190. due_count: number;
  4191. warning_count: number;
  4192. }
  4193. // External Links (sidebar)
  4194. export interface ExternalLink {
  4195. id: number;
  4196. name: string;
  4197. url: string;
  4198. icon: string;
  4199. open_in_new_tab: boolean;
  4200. custom_icon: string | null;
  4201. sort_order: number;
  4202. created_at: string;
  4203. updated_at: string;
  4204. /** Count reported by the app the link points to, while it keeps reporting. */
  4205. badge_count?: number | null;
  4206. }
  4207. export interface ExternalLinkCreate {
  4208. name: string;
  4209. url: string;
  4210. icon: string;
  4211. open_in_new_tab?: boolean;
  4212. }
  4213. export interface ExternalLinkUpdate {
  4214. name?: string;
  4215. url?: string;
  4216. icon?: string;
  4217. open_in_new_tab?: boolean;
  4218. }
  4219. // Finance types
  4220. export interface CostCenterSummary {
  4221. id: number;
  4222. name: string;
  4223. is_private: boolean;
  4224. owner_user_id: number | null;
  4225. is_active: boolean;
  4226. total_balance: number;
  4227. total_budget: number | null;
  4228. monthly_budget: number | null;
  4229. budget_mode: 'none' | 'total' | 'monthly';
  4230. budget_limit: number | null;
  4231. budget_used: number | null;
  4232. budget_available: number | null;
  4233. can_print: boolean;
  4234. }
  4235. export interface CostCenterCreateRequest {
  4236. name: string;
  4237. total_budget?: number | null;
  4238. monthly_budget?: number | null;
  4239. is_active?: boolean;
  4240. }
  4241. export interface CostCenterBudgetUpdateRequest {
  4242. total_budget?: number | null;
  4243. monthly_budget?: number | null;
  4244. }
  4245. export interface CostCenterUpdateRequest {
  4246. name?: string;
  4247. is_active?: boolean;
  4248. }
  4249. export interface CostCenterMemberRequest {
  4250. user_id: number;
  4251. can_print?: boolean;
  4252. }
  4253. export interface CostCenterMemberResponse {
  4254. id: number;
  4255. cost_center_id: number;
  4256. user_id: number;
  4257. can_print: boolean;
  4258. created_at: string;
  4259. }
  4260. export interface CostCenterDetail extends CostCenterSummary {
  4261. members: CostCenterMemberResponse[];
  4262. }
  4263. export interface WalletBalance {
  4264. user_id: number;
  4265. balance: number;
  4266. currency: string;
  4267. updated_at: string | null;
  4268. }
  4269. export type WalletTransactionType = 'print_charge' | 'deposit' | 'withdraw' | 'manual_adjustment';
  4270. export interface WalletTransaction {
  4271. id: number;
  4272. user_id: number | null; // null once the user is deleted
  4273. cost_center_id: number | null;
  4274. transaction_type: WalletTransactionType;
  4275. amount: number;
  4276. balance_after: number | null;
  4277. description: string | null;
  4278. created_by_user_id: number | null;
  4279. print_run_id: string | null;
  4280. print_archive_id: number | null;
  4281. print_queue_id: number | null;
  4282. created_at: string;
  4283. }
  4284. export interface WalletTransactionListResponse {
  4285. items: WalletTransaction[];
  4286. total: number;
  4287. limit: number;
  4288. offset: number;
  4289. }
  4290. export interface WalletAdjustmentRequest {
  4291. amount: number;
  4292. description?: string;
  4293. cost_center_id?: number | null;
  4294. }
  4295. export interface WalletAdjustmentResponse {
  4296. transaction: WalletTransaction;
  4297. balance: WalletBalance;
  4298. }
  4299. export interface TransactionEditRequest {
  4300. user_id?: number | null;
  4301. cost_center_id?: number | null;
  4302. amount?: number | null;
  4303. description?: string | null;
  4304. }
  4305. export interface ManualPrintRequest {
  4306. user_id: number;
  4307. cost_center_id: number;
  4308. amount: number;
  4309. description?: string | null;
  4310. created_at?: string | null;
  4311. }
  4312. // Permission type - all available permissions
  4313. export type Permission =
  4314. | 'printers:read' | 'printers:create' | 'printers:update' | 'printers:delete' | 'printers:control' | 'printers:files' | 'printers:ams_rfid' | 'printers:clear_plate'
  4315. | 'archives:read' | 'archives:read_own' | 'archives:read_all' | 'archives:create'
  4316. | 'archives:update_own' | 'archives:update_all' | 'archives:delete_own' | 'archives:delete_all'
  4317. | 'archives:reprint_own' | 'archives:reprint_all' | 'archives:purge'
  4318. | 'queue:read' | 'queue:read_own' | 'queue:read_all' | 'queue:create'
  4319. | 'queue:update_own' | 'queue:update_all' | 'queue:delete_own' | 'queue:delete_all'
  4320. | 'queue:reorder' | 'queue:start_unreviewed'
  4321. | 'library:read' | 'library:read_own' | 'library:read_all' | 'library:upload'
  4322. | 'library:update_own' | 'library:update_all' | 'library:delete_own' | 'library:delete_all'
  4323. | 'library:purge'
  4324. | 'projects:read' | 'projects:create' | 'projects:update' | 'projects:delete'
  4325. | 'filaments:read' | 'filaments:create' | 'filaments:update' | 'filaments:delete'
  4326. | 'inventory:read' | 'inventory:create' | 'inventory:update' | 'inventory:delete' | 'inventory:view_assignments'
  4327. | 'inventory:forecast_read' | 'inventory:forecast_write'
  4328. | 'smart_plugs:read' | 'smart_plugs:create' | 'smart_plugs:update' | 'smart_plugs:delete' | 'smart_plugs:control'
  4329. | 'camera:view'
  4330. | 'maintenance:read' | 'maintenance:create' | 'maintenance:update' | 'maintenance:delete'
  4331. | 'kprofiles:read' | 'kprofiles:create' | 'kprofiles:update' | 'kprofiles:delete'
  4332. | 'notifications:read' | 'notifications:create' | 'notifications:update' | 'notifications:delete' | 'notifications:user_email'
  4333. | 'notification_templates:read' | 'notification_templates:update'
  4334. | 'external_links:read' | 'external_links:create' | 'external_links:update' | 'external_links:delete'
  4335. | 'discovery:scan'
  4336. | 'firmware:read' | 'firmware:update'
  4337. | 'ams_history:read'
  4338. | 'cost_centers:read_own' | 'cost_centers:read_all' | 'cost_centers:modify' | 'cost_centers:create'
  4339. | 'stats:read' | 'stats:filter_by_user'
  4340. | 'system:read'
  4341. | 'settings:read' | 'settings:update' | 'settings:backup' | 'settings:restore'
  4342. | 'github:backup' | 'github:restore'
  4343. | 'cloud:auth' | 'orca_cloud:auth'
  4344. | 'makerworld:view' | 'makerworld:import'
  4345. | 'manyfold:view' | 'manyfold:import'
  4346. | 'api_keys:read' | 'api_keys:create' | 'api_keys:update' | 'api_keys:delete'
  4347. | 'users:read' | 'users:read_slim' | 'users:create' | 'users:update' | 'users:delete'
  4348. | 'groups:read' | 'groups:create' | 'groups:update' | 'groups:delete'
  4349. | 'pipelines:read' | 'pipelines:write' | 'pipelines:run'
  4350. | 'websocket:connect';
  4351. // Group types
  4352. export interface GroupBrief {
  4353. id: number;
  4354. name: string;
  4355. }
  4356. export interface Group {
  4357. id: number;
  4358. name: string;
  4359. description: string | null;
  4360. permissions: Permission[];
  4361. is_system: boolean;
  4362. /** Members only see the printers in printer_ids plus every printer in locations (#1727) */
  4363. restrict_printers: boolean;
  4364. printer_ids: number[];
  4365. /** Matched against Printer.location, so printers added there later are included */
  4366. locations: string[];
  4367. user_count: number;
  4368. created_at: string;
  4369. updated_at: string;
  4370. }
  4371. export interface GroupDetail extends Group {
  4372. users: Array<{ id: number; username: string; is_active: boolean }>;
  4373. }
  4374. export interface GroupCreate {
  4375. name: string;
  4376. description?: string;
  4377. permissions: Permission[];
  4378. restrict_printers?: boolean;
  4379. printer_ids?: number[];
  4380. locations?: string[];
  4381. }
  4382. export interface GroupUpdate {
  4383. name?: string;
  4384. description?: string;
  4385. permissions?: Permission[];
  4386. restrict_printers?: boolean;
  4387. printer_ids?: number[];
  4388. locations?: string[];
  4389. }
  4390. export interface PermissionInfo {
  4391. value: Permission;
  4392. label: string;
  4393. }
  4394. export interface PermissionCategory {
  4395. name: string;
  4396. permissions: PermissionInfo[];
  4397. }
  4398. export interface PermissionsListResponse {
  4399. categories: PermissionCategory[];
  4400. all_permissions: Permission[];
  4401. }
  4402. // User email notification preferences
  4403. export interface UserEmailPreferences {
  4404. notify_print_start: boolean;
  4405. notify_print_complete: boolean;
  4406. notify_print_failed: boolean;
  4407. notify_print_stopped: boolean;
  4408. }
  4409. // Auth types
  4410. export interface LoginRequest {
  4411. username: string;
  4412. password: string;
  4413. }
  4414. export interface LoginResponse {
  4415. access_token?: string;
  4416. token_type?: string;
  4417. user?: UserResponse;
  4418. /** Set when 2FA verification is required before a full token is issued. */
  4419. requires_2fa?: boolean;
  4420. pre_auth_token?: string;
  4421. two_fa_methods?: string[];
  4422. }
  4423. export interface UserResponse {
  4424. id: number;
  4425. username: string;
  4426. email?: string;
  4427. role: string; // Deprecated, kept for backward compatibility
  4428. is_active: boolean;
  4429. is_admin: boolean; // Computed from role and group membership
  4430. auth_source: string; // "local" or "ldap"
  4431. groups: GroupBrief[];
  4432. permissions: Permission[]; // All permissions from groups
  4433. created_at: string;
  4434. }
  4435. /**
  4436. * Just enough to label an owner id (#1894). Backed by GET /users/slim, which
  4437. * is readable with `users:read_slim` as well as the admin-level `users:read`
  4438. * -- use it anywhere a screen only needs to turn a `created_by_id` into a
  4439. * name, so operators are not forced into the full listing to get one.
  4440. */
  4441. export interface UserSlim {
  4442. id: number;
  4443. username: string;
  4444. }
  4445. export interface UserCreate {
  4446. username: string;
  4447. password?: string; // Optional when advanced auth is enabled
  4448. email?: string;
  4449. role: string;
  4450. group_ids?: number[];
  4451. }
  4452. export interface UserUpdate {
  4453. username?: string;
  4454. password?: string;
  4455. email?: string;
  4456. role?: string;
  4457. is_active?: boolean;
  4458. group_ids?: number[];
  4459. }
  4460. export interface SetupRequest {
  4461. auth_enabled: boolean;
  4462. admin_username?: string;
  4463. admin_password?: string;
  4464. }
  4465. export interface ForgotPasswordRequest {
  4466. email: string;
  4467. }
  4468. export interface ForgotPasswordResponse {
  4469. message: string;
  4470. }
  4471. export interface ResetPasswordRequest {
  4472. user_id: number;
  4473. }
  4474. export interface ResetPasswordResponse {
  4475. message: string;
  4476. }
  4477. export interface SMTPSettings {
  4478. smtp_host: string;
  4479. smtp_port: number;
  4480. smtp_username?: string;
  4481. smtp_password?: string;
  4482. smtp_security: 'starttls' | 'ssl' | 'none';
  4483. smtp_auth_enabled: boolean;
  4484. smtp_from_email: string;
  4485. smtp_from_name: string;
  4486. }
  4487. // 2FA / MFA interfaces
  4488. export interface TwoFAStatus {
  4489. totp_enabled: boolean;
  4490. email_otp_enabled: boolean;
  4491. backup_codes_remaining: number;
  4492. }
  4493. export interface TOTPSetupResponse {
  4494. secret: string;
  4495. qr_code_b64: string;
  4496. issuer: string;
  4497. }
  4498. export interface TOTPEnableResponse {
  4499. message: string;
  4500. backup_codes: string[];
  4501. }
  4502. export interface BackupCodesResponse {
  4503. backup_codes: string[];
  4504. message: string;
  4505. }
  4506. export interface TwoFAVerifyRequest {
  4507. pre_auth_token: string;
  4508. code: string;
  4509. method: 'totp' | 'email' | 'backup';
  4510. }
  4511. /**
  4512. * A URL that is known to be same-origin (a relative path starting with ``/``).
  4513. *
  4514. * Branded so that producers of same-origin URLs (e.g. ``api.oidcProviderIconUrl``)
  4515. * can be distinguished from arbitrary strings at the type level. The brand
  4516. * is compile-time only; at runtime these are plain strings.
  4517. *
  4518. * Purpose: CSP-safe image sources for ``<img src=...>``. The strict
  4519. * ``img-src 'self' data: blob:`` CSP rejects anything that isn't same-origin,
  4520. * so callers that demand a ``SameOriginUrl`` get a compile-time guarantee
  4521. * that no external URL slips through.
  4522. */
  4523. export type SameOriginUrl = string & { readonly __brand: 'SameOriginUrl' };
  4524. // OIDC interfaces
  4525. /** What the unauthenticated GET /auth/oidc/providers returns (#3107): only
  4526. * what the login page renders. The full provider, group sync config
  4527. * included, needs the admin-only /auth/oidc/providers/all. */
  4528. export interface OIDCProviderPublic {
  4529. id: number;
  4530. name: string;
  4531. has_icon: boolean;
  4532. is_autologin: boolean;
  4533. }
  4534. export interface OIDCProvider {
  4535. id: number;
  4536. name: string;
  4537. issuer_url: string;
  4538. client_id: string;
  4539. scopes: string;
  4540. is_enabled: boolean;
  4541. auto_create_users: boolean;
  4542. auto_link_existing_accounts: boolean;
  4543. email_claim: string;
  4544. require_email_verified: boolean;
  4545. // #3107 — group sync. Empty mapping = sync off (default).
  4546. group_claim?: string;
  4547. group_mapping?: Record<string, string>;
  4548. icon_url?: string | null;
  4549. default_group_id?: number | null;
  4550. // True when the backend has cached icon bytes for this provider.
  4551. // Login page / admin preview consume this via the proxy URL
  4552. // /api/v1/auth/oidc/providers/{id}/icon (#1333) so the SPA never
  4553. // hotlinks the external icon URL — that would require loosening
  4554. // the strict img-src CSP. Required, not optional: the backend always
  4555. // includes this field in the response (Pydantic default-False is
  4556. // populated unconditionally in the route handler).
  4557. has_icon: boolean;
  4558. // #1589: when true, the LoginPage redirects unauthenticated visitors
  4559. // straight to this provider on mount. At most one provider may carry this.
  4560. is_autologin: boolean;
  4561. // #2593: defined by BAMBUDDY_OIDC_* and rewritten from the environment on
  4562. // every boot. The API answers 409 to any write, so the settings UI must not
  4563. // offer edit/delete controls that cannot succeed. Optional so a response
  4564. // from an older backend still type-checks.
  4565. is_env_managed?: boolean;
  4566. }
  4567. export interface OIDCProviderCreate {
  4568. name: string;
  4569. issuer_url: string;
  4570. client_id: string;
  4571. client_secret: string;
  4572. scopes?: string;
  4573. is_enabled?: boolean;
  4574. auto_create_users?: boolean;
  4575. auto_link_existing_accounts?: boolean;
  4576. email_claim?: string;
  4577. require_email_verified?: boolean;
  4578. // #3107 — group sync. Omit both to leave them unchanged on update.
  4579. group_claim?: string;
  4580. group_mapping?: Record<string, string>;
  4581. icon_url?: string | null;
  4582. default_group_id?: number | null;
  4583. is_autologin?: boolean; // #1589
  4584. }
  4585. export interface OIDCLink {
  4586. id: number;
  4587. provider_id: number;
  4588. provider_name: string;
  4589. provider_email?: string | null;
  4590. created_at: string;
  4591. }
  4592. export interface TestSMTPRequest {
  4593. test_recipient: string;
  4594. // The form's settings, tested before they are saved. An empty password
  4595. // keeps the saved one.
  4596. smtp?: SMTPSettings;
  4597. }
  4598. export interface TestSMTPResponse {
  4599. success: boolean;
  4600. message: string;
  4601. }
  4602. export interface AdvancedAuthStatus {
  4603. advanced_auth_enabled: boolean;
  4604. smtp_configured: boolean;
  4605. // #1589: false hides the username/password form on the LoginPage; the env
  4606. // var BAMBUDDY_LOCAL_LOGIN=true on the server flips this back to true so
  4607. // the recovery path remains visible.
  4608. local_login_enabled: boolean;
  4609. // #1589: when set, LoginPage redirects to this provider's authorize URL
  4610. // on mount unless ?fallback=local is in the URL or the redirect times out.
  4611. autologin_provider_id: number | null;
  4612. }
  4613. export interface LDAPStatus {
  4614. ldap_enabled: boolean;
  4615. ldap_configured: boolean;
  4616. }
  4617. export interface EncryptionRowCounts {
  4618. oidc_providers: number;
  4619. user_totp: number;
  4620. }
  4621. export interface EncryptionStatus {
  4622. key_configured: boolean;
  4623. key_source: 'env' | 'file' | 'generated' | 'none';
  4624. legacy_plaintext_rows: EncryptionRowCounts;
  4625. encrypted_rows: EncryptionRowCounts;
  4626. decryption_broken: boolean;
  4627. // B2: count of rows skipped during the last legacy re-encryption migration.
  4628. // Surfaced via a yellow secondary banner in SecurityStatusCard.
  4629. migration_error_count: number;
  4630. }
  4631. export interface LDAPTestRequest {
  4632. ldap_server_url?: string;
  4633. ldap_bind_dn?: string;
  4634. ldap_bind_password?: string;
  4635. ldap_search_base?: string;
  4636. ldap_user_filter?: string;
  4637. ldap_security?: string;
  4638. }
  4639. export interface LDAPTestResponse {
  4640. success: boolean;
  4641. message: string;
  4642. }
  4643. export interface LDAPSearchResult {
  4644. username: string;
  4645. email: string | null;
  4646. display_name: string | null;
  4647. dn: string;
  4648. already_provisioned: boolean;
  4649. }
  4650. export interface SetupResponse {
  4651. auth_enabled: boolean;
  4652. admin_created?: boolean;
  4653. }
  4654. export interface AuthStatus {
  4655. auth_enabled: boolean;
  4656. requires_setup: boolean;
  4657. }
  4658. // API functions
  4659. export interface QueueHistoryFilters {
  4660. printerId?: number | null;
  4661. status?: string;
  4662. location?: string;
  4663. }
  4664. export interface QueueHistoryParams extends QueueHistoryFilters {
  4665. sortBy?: 'date' | 'name' | 'printer';
  4666. // Flips the default order: newest first by date, A to Z by name or printer.
  4667. reverse?: boolean;
  4668. limit?: number;
  4669. offset?: number;
  4670. }
  4671. export interface QueueHistoryPage {
  4672. // The page in display order, then any other runs of the batches on it.
  4673. items: PrintQueueItem[];
  4674. total: number;
  4675. locations: string[];
  4676. }
  4677. function queueHistorySearch(params: QueueHistoryParams): URLSearchParams {
  4678. const search = new URLSearchParams();
  4679. if (params.printerId) search.set('printer_id', String(params.printerId));
  4680. if (params.status) search.set('status', params.status);
  4681. if (params.location) search.set('location', params.location);
  4682. if (params.sortBy) search.set('sort_by', params.sortBy);
  4683. if (params.reverse) search.set('reverse', 'true');
  4684. if (params.limit !== undefined) search.set('limit', String(params.limit));
  4685. if (params.offset) search.set('offset', String(params.offset));
  4686. return search;
  4687. }
  4688. // Per-printer reads that a page showing every printer makes once per printer,
  4689. // coalesced into one bulk request per few milliseconds (see ./batch). Each
  4690. // keeps its single-printer request for a lone id.
  4691. const idsParam = (ids: number[]) => `ids=${ids.join(',')}`;
  4692. const printerStatusBatch = batched(
  4693. (id) => request<PrinterStatus>(`/printers/${id}/status`),
  4694. async (ids) => byField(await request<PrinterStatus[]>(`/bulk/printer-statuses?${idsParam(ids)}`), (s) => s.id),
  4695. );
  4696. const slotPresetsBatch = batched(
  4697. (id) => request<Record<number, SlotPresetMapping>>(`/printers/${id}/slot-presets`),
  4698. async (ids) => byId(await request<Record<string, Record<number, SlotPresetMapping>>>(`/bulk/slot-presets?${idsParam(ids)}`)),
  4699. );
  4700. const amsLabelsBatch = batched(
  4701. (id) => request<Record<number, string>>(`/printers/${id}/ams-labels`),
  4702. async (ids) => byId(await request<Record<string, Record<number, string>>>(`/bulk/ams-labels?${idsParam(ids)}`)),
  4703. );
  4704. type PrinterCardPlugs = { plug: SmartPlug | null; scripts: SmartPlug[] };
  4705. const cardPlugs = async (ids: number[]) =>
  4706. byId(await request<Record<string, PrinterCardPlugs>>(`/bulk/card-plugs?${idsParam(ids)}`));
  4707. const smartPlugBatch = batched(
  4708. (id) => request<SmartPlug | null>(`/smart-plugs/by-printer/${id}`),
  4709. async (ids) => new Map([...(await cardPlugs(ids))].map(([id, plugs]) => [id, plugs.plug])),
  4710. );
  4711. const scriptPlugsBatch = batched(
  4712. (id) => request<SmartPlug[]>(`/smart-plugs/by-printer/${id}/scripts`),
  4713. async (ids) => new Map([...(await cardPlugs(ids))].map(([id, plugs]) => [id, plugs.scripts])),
  4714. );
  4715. const haSensorReadingsBatch = batched(
  4716. (id) => request<PrinterHASensorReading[]>(`/ha-sensors/by-printer/${id}/readings`),
  4717. async (ids) => byId(await request<Record<string, PrinterHASensorReading[]>>(`/bulk/ha-sensor-readings?${idsParam(ids)}`)),
  4718. );
  4719. const firmwareUpdateBatch = batched(
  4720. (id) => request<FirmwareUpdateInfo>(`/firmware/updates/${id}`),
  4721. async (ids) =>
  4722. byField(await request<FirmwareUpdateInfo[]>(`/bulk/firmware-updates?${idsParam(ids)}`), (u) => u.printer_id),
  4723. );
  4724. // One batcher per status asked for: the bulk route takes a single status list.
  4725. const printerQueueBatches = new Map<string, (id: number) => Promise<PrintQueueItem[]>>();
  4726. const printerQueueBatch = (status: string) => {
  4727. let batch = printerQueueBatches.get(status);
  4728. if (!batch) {
  4729. batch = batched(
  4730. (id) => request<PrintQueueItem[]>(`/queue/?printer_id=${id}&status=${encodeURIComponent(status)}`),
  4731. async (ids) =>
  4732. byId(
  4733. await request<Record<string, PrintQueueItem[]>>(
  4734. `/bulk/printer-queues?${idsParam(ids)}&status=${encodeURIComponent(status)}`,
  4735. ),
  4736. ),
  4737. );
  4738. printerQueueBatches.set(status, batch);
  4739. }
  4740. return batch;
  4741. };
  4742. const foldersByArchiveBatch = batched(
  4743. (id) => request<LibraryFolder[]>(`/library/folders/by-archive/${id}`),
  4744. async (ids) => byId(await request<Record<string, LibraryFolder[]>>(`/bulk/archive-folders?${idsParam(ids)}`)),
  4745. );
  4746. export const api = {
  4747. // Overlay branding
  4748. getOverlayLogo: async (token: string | null, signal?: AbortSignal): Promise<Blob | null> => {
  4749. const endpoint = token ? `/overlay-branding/logo?token=${encodeURIComponent(token)}` : '/settings/overlay-logo';
  4750. const response = await fetch(`${API_BASE}${endpoint}`, {
  4751. signal, cache: 'no-store',
  4752. headers: !token && authToken ? { Authorization: `Bearer ${authToken}` } : {},
  4753. });
  4754. if (response.status === 404) return null;
  4755. if (!response.ok) throw new Error(`HTTP ${response.status}`);
  4756. return response.blob();
  4757. },
  4758. uploadOverlayLogo: async (file: File): Promise<void> => {
  4759. const body = new FormData();
  4760. body.append('file', file);
  4761. const response = await fetch(`${API_BASE}/settings/overlay-logo`, {
  4762. method: 'POST', body,
  4763. headers: authToken ? { Authorization: `Bearer ${authToken}` } : {},
  4764. });
  4765. if (!response.ok) {
  4766. const error = await response.json().catch(() => ({}));
  4767. const detail = error?.detail;
  4768. const message = typeof detail === 'string' ? detail : detail?.message;
  4769. throw new Error(typeof message === 'string' && message ? message : `HTTP ${response.status}`);
  4770. }
  4771. },
  4772. deleteOverlayLogo: () => request<{ status: string }>('/settings/overlay-logo', { method: 'DELETE' }),
  4773. // Authentication
  4774. getAuthStatus: () => request<AuthStatus>('/auth/status'),
  4775. setupAuth: (data: SetupRequest) =>
  4776. request<SetupResponse>('/auth/setup', {
  4777. method: 'POST',
  4778. body: JSON.stringify(data),
  4779. }),
  4780. login: (data: LoginRequest) =>
  4781. request<LoginResponse>('/auth/login', {
  4782. method: 'POST',
  4783. body: JSON.stringify(data),
  4784. }),
  4785. logout: () =>
  4786. request<{ message: string }>('/auth/logout', {
  4787. method: 'POST',
  4788. }),
  4789. getCurrentUser: () => request<UserResponse>('/auth/me'),
  4790. disableAuth: () =>
  4791. request<{ message: string; auth_enabled: boolean }>('/auth/disable', {
  4792. method: 'POST',
  4793. }),
  4794. // Advanced Authentication
  4795. testSMTP: (data: TestSMTPRequest) =>
  4796. request<TestSMTPResponse>('/auth/smtp/test', {
  4797. method: 'POST',
  4798. body: JSON.stringify(data),
  4799. }),
  4800. getSMTPSettings: () => request<SMTPSettings | null>('/auth/smtp'),
  4801. saveSMTPSettings: (data: SMTPSettings) =>
  4802. request<{ message: string }>('/auth/smtp', {
  4803. method: 'POST',
  4804. body: JSON.stringify(data),
  4805. }),
  4806. enableAdvancedAuth: () =>
  4807. request<{ message: string; advanced_auth_enabled: boolean }>('/auth/advanced-auth/enable', {
  4808. method: 'POST',
  4809. }),
  4810. disableAdvancedAuth: () =>
  4811. request<{ message: string; advanced_auth_enabled: boolean }>('/auth/advanced-auth/disable', {
  4812. method: 'POST',
  4813. }),
  4814. getAdvancedAuthStatus: () => request<AdvancedAuthStatus>('/auth/advanced-auth/status'),
  4815. // LDAP Authentication
  4816. getLDAPStatus: () => request<LDAPStatus>('/auth/ldap/status'),
  4817. getEncryptionStatus: () => request<EncryptionStatus>('/auth/encryption-status'),
  4818. // form: the settings being edited, tested before they are saved. An empty
  4819. // bind password keeps the saved one.
  4820. testLDAP: (form?: LDAPTestRequest) =>
  4821. request<LDAPTestResponse>('/auth/ldap/test', {
  4822. method: 'POST',
  4823. ...(form ? { body: JSON.stringify(form) } : {}),
  4824. }),
  4825. searchLDAPDirectory: (q: string) =>
  4826. request<LDAPSearchResult[]>(`/auth/ldap/search?q=${encodeURIComponent(q)}`),
  4827. provisionLDAPUser: (username: string) =>
  4828. request<UserResponse>('/auth/ldap/provision', {
  4829. method: 'POST',
  4830. body: JSON.stringify({ username }),
  4831. }),
  4832. forgotPassword: (data: ForgotPasswordRequest) =>
  4833. request<ForgotPasswordResponse>('/auth/forgot-password', {
  4834. method: 'POST',
  4835. body: JSON.stringify(data),
  4836. }),
  4837. // H-6: Confirm password reset using the token from the emailed link
  4838. forgotPasswordConfirm: (token: string, newPassword: string) =>
  4839. request<ForgotPasswordResponse>('/auth/forgot-password/confirm', {
  4840. method: 'POST',
  4841. body: JSON.stringify({ token, new_password: newPassword }),
  4842. }),
  4843. resetUserPassword: (data: ResetPasswordRequest) =>
  4844. request<ResetPasswordResponse>('/auth/reset-password', {
  4845. method: 'POST',
  4846. body: JSON.stringify(data),
  4847. }),
  4848. // 2FA - status
  4849. get2FAStatus: () => request<TwoFAStatus>('/auth/2fa/status'),
  4850. // 2FA - TOTP
  4851. setupTOTP: () => request<TOTPSetupResponse>('/auth/2fa/totp/setup', { method: 'POST' }),
  4852. enableTOTP: (code: string) =>
  4853. request<TOTPEnableResponse>('/auth/2fa/totp/enable', {
  4854. method: 'POST',
  4855. body: JSON.stringify({ code }),
  4856. }),
  4857. disableTOTP: (code: string) =>
  4858. request<{ message: string }>('/auth/2fa/totp/disable', {
  4859. method: 'POST',
  4860. body: JSON.stringify({ code }),
  4861. }),
  4862. regenerateBackupCodes: (code: string) =>
  4863. request<BackupCodesResponse>('/auth/2fa/totp/regenerate-backup-codes', {
  4864. method: 'POST',
  4865. body: JSON.stringify({ code }),
  4866. }),
  4867. // 2FA - Email OTP
  4868. // Step 1: send a verification code to the user's email (proof of possession)
  4869. enableEmailOTP: () =>
  4870. request<{ message: string; setup_token: string }>('/auth/2fa/email/enable', { method: 'POST' }),
  4871. // Step 2: confirm with the code received by email
  4872. confirmEnableEmailOTP: (setup_token: string, code: string) =>
  4873. request<{ message: string }>('/auth/2fa/email/enable/confirm', {
  4874. method: 'POST',
  4875. body: JSON.stringify({ setup_token, code }),
  4876. }),
  4877. // Disable requires account password for re-auth
  4878. disableEmailOTP: (password: string) =>
  4879. request<{ message: string }>('/auth/2fa/email/disable', {
  4880. method: 'POST',
  4881. body: JSON.stringify({ password }),
  4882. }),
  4883. sendEmailOTP: (preAuthToken: string) =>
  4884. request<{ message: string; pre_auth_token?: string }>('/auth/2fa/email/send', {
  4885. method: 'POST',
  4886. body: JSON.stringify({ pre_auth_token: preAuthToken }),
  4887. }),
  4888. // 2FA - verify (completes login)
  4889. verify2FA: (data: TwoFAVerifyRequest) =>
  4890. request<LoginResponse>('/auth/2fa/verify', {
  4891. method: 'POST',
  4892. body: JSON.stringify(data),
  4893. }),
  4894. // 2FA - admin
  4895. // adminPassword: the calling admin's own password; null for an admin
  4896. // without one (LDAP / OIDC accounts usually), whom the route does not ask.
  4897. admin2FADisable: (userId: number, adminPassword: string | null) =>
  4898. request<{ message: string; had_2fa: boolean }>(`/auth/2fa/admin/${userId}`, {
  4899. method: 'DELETE',
  4900. body: JSON.stringify({ admin_password: adminPassword }),
  4901. }),
  4902. // OIDC providers (public list)
  4903. getOIDCProviders: () => request<OIDCProviderPublic[]>('/auth/oidc/providers'),
  4904. // OIDC providers (admin)
  4905. getOIDCProvidersAll: () => request<OIDCProvider[]>('/auth/oidc/providers/all'),
  4906. createOIDCProvider: (data: OIDCProviderCreate) =>
  4907. request<OIDCProvider>('/auth/oidc/providers', {
  4908. method: 'POST',
  4909. body: JSON.stringify(data),
  4910. }),
  4911. updateOIDCProvider: (id: number, data: Partial<OIDCProviderCreate>) =>
  4912. request<OIDCProvider>(`/auth/oidc/providers/${id}`, {
  4913. method: 'PUT',
  4914. body: JSON.stringify(data),
  4915. }),
  4916. deleteOIDCProvider: (id: number) =>
  4917. request<{ message: string }>(`/auth/oidc/providers/${id}`, { method: 'DELETE' }),
  4918. // OIDC provider icon proxy (#1333) — same-origin path so the strict
  4919. // img-src CSP stays in force. Returns a SameOriginUrl-branded string
  4920. // so a future caller can't accidentally substitute an attacker-
  4921. // controlled URL where this is consumed.
  4922. oidcProviderIconUrl: (id: number): SameOriginUrl =>
  4923. `/api/v1/auth/oidc/providers/${id}/icon` as SameOriginUrl,
  4924. deleteOIDCProviderIcon: (id: number) =>
  4925. request<void>(`/auth/oidc/providers/${id}/icon`, { method: 'DELETE' }),
  4926. refreshOIDCProviderIcon: (id: number) =>
  4927. request<OIDCProvider>(`/auth/oidc/providers/${id}/icon/refresh`, { method: 'POST' }),
  4928. // OIDC authorize URL
  4929. getOIDCAuthorizeUrl: (providerId: number) =>
  4930. request<{ auth_url: string }>(`/auth/oidc/authorize/${providerId}`),
  4931. // OIDC exchange token for JWT
  4932. exchangeOIDCToken: (oidcToken: string) =>
  4933. request<LoginResponse>('/auth/oidc/exchange', {
  4934. method: 'POST',
  4935. body: JSON.stringify({ oidc_token: oidcToken }),
  4936. }),
  4937. // OIDC links for current user
  4938. getOIDCLinks: () => request<OIDCLink[]>('/auth/oidc/links'),
  4939. deleteOIDCLink: (providerId: number) =>
  4940. request<{ message: string }>(`/auth/oidc/links/${providerId}`, { method: 'DELETE' }),
  4941. // Users
  4942. getUsers: () => request<UserResponse[]>('/users/'),
  4943. getUsersSlim: () => request<UserSlim[]>('/users/slim'),
  4944. createUser: (data: UserCreate) =>
  4945. request<UserResponse>('/users/', {
  4946. method: 'POST',
  4947. body: JSON.stringify(data),
  4948. }),
  4949. updateUser: (id: number, data: UserUpdate) =>
  4950. request<UserResponse>(`/users/${id}`, {
  4951. method: 'PATCH',
  4952. body: JSON.stringify(data),
  4953. }),
  4954. deleteUser: (id: number, deleteItems: boolean = false) =>
  4955. request<void>(`/users/${id}?delete_items=${deleteItems}`, {
  4956. method: 'DELETE',
  4957. }),
  4958. getUserItemsCount: (id: number) =>
  4959. request<{ archives: number; queue_items: number; library_files: number }>(`/users/${id}/items-count`),
  4960. changePassword: (currentPassword: string, newPassword: string) =>
  4961. request<{ message: string }>('/users/me/change-password', {
  4962. method: 'POST',
  4963. body: JSON.stringify({ current_password: currentPassword, new_password: newPassword }),
  4964. }),
  4965. // User Email Notifications
  4966. getUserEmailPreferences: () =>
  4967. request<UserEmailPreferences>('/user-notifications/preferences'),
  4968. updateUserEmailPreferences: (data: UserEmailPreferences) =>
  4969. request<UserEmailPreferences>('/user-notifications/preferences', {
  4970. method: 'PUT',
  4971. body: JSON.stringify(data),
  4972. }),
  4973. // Groups
  4974. getPermissions: () => request<PermissionsListResponse>('/groups/permissions'),
  4975. getGroups: () => request<Group[]>('/groups/'),
  4976. getGroup: (id: number) => request<GroupDetail>(`/groups/${id}`),
  4977. createGroup: (data: GroupCreate) =>
  4978. request<Group>('/groups/', {
  4979. method: 'POST',
  4980. body: JSON.stringify(data),
  4981. }),
  4982. updateGroup: (id: number, data: GroupUpdate) =>
  4983. request<Group>(`/groups/${id}`, {
  4984. method: 'PATCH',
  4985. body: JSON.stringify(data),
  4986. }),
  4987. deleteGroup: (id: number) =>
  4988. request<void>(`/groups/${id}`, {
  4989. method: 'DELETE',
  4990. }),
  4991. // Printers
  4992. getPrinters: () => request<Printer[]>('/printers/'),
  4993. getPrinter: (id: number) => request<Printer>(`/printers/${id}`),
  4994. createPrinter: (data: PrinterCreate) =>
  4995. request<Printer>('/printers/', {
  4996. method: 'POST',
  4997. body: JSON.stringify(data),
  4998. }),
  4999. updatePrinter: (id: number, data: Partial<PrinterCreate>) =>
  5000. request<Printer>(`/printers/${id}`, {
  5001. method: 'PATCH',
  5002. body: JSON.stringify(data),
  5003. }),
  5004. getWledPresets: (id: number, baseUrl: string) =>
  5005. request<WLEDPreset[]>(`/printers/${id}/wled/presets`, {
  5006. method: 'POST',
  5007. body: JSON.stringify({ base_url: baseUrl }),
  5008. }),
  5009. testWledConnection: (id: number, baseUrl: string) =>
  5010. request<WLEDConnectionInfo>(`/printers/${id}/wled/test-connection`, {
  5011. method: 'POST',
  5012. body: JSON.stringify({ base_url: baseUrl }),
  5013. }),
  5014. testWledPreset: (id: number, baseUrl: string, presetId: number) =>
  5015. request<{ success: boolean }>(`/printers/${id}/wled/test-preset`, {
  5016. method: 'POST',
  5017. body: JSON.stringify({ base_url: baseUrl, preset_id: presetId }),
  5018. }),
  5019. deletePrinter: (id: number, deleteArchives: boolean = true) =>
  5020. request<{ status: string; archives_deleted: boolean }>(
  5021. `/printers/${id}?delete_archives=${deleteArchives}`,
  5022. { method: 'DELETE' }
  5023. ),
  5024. getDeveloperModeWarnings: () =>
  5025. request<{ printer_id: number; name: string }[]>('/printers/developer-mode-warnings'),
  5026. getAvailableFilaments: (model: string, location?: string) => {
  5027. const params = new URLSearchParams({ model });
  5028. if (location) params.set('location', location);
  5029. return request<Array<{ type: string; color: string; tray_info_idx: string; tray_sub_brands: string; extruder_id: number | null }>>(`/printers/available-filaments?${params}`);
  5030. },
  5031. getPrinterLocations: () => request<PrinterLocation[]>('/printer-locations/'),
  5032. createPrinterLocation: (data: { name: string; icon?: string | null; color?: string | null }) =>
  5033. request<PrinterLocation>('/printer-locations/', { method: 'POST', body: JSON.stringify(data) }),
  5034. updatePrinterLocation: (data: PrinterLocationUpdate) =>
  5035. request<PrinterLocation>('/printer-locations/', { method: 'PATCH', body: JSON.stringify(data) }),
  5036. deletePrinterLocations: (names: string[]) =>
  5037. request<{ deleted: number; printers_ungrouped: number }>('/printer-locations/delete', {
  5038. method: 'POST',
  5039. body: JSON.stringify({ names }),
  5040. }),
  5041. assignPrinterLocation: (printerIds: number[], location: string | null) =>
  5042. request<{ moved: number }>('/printer-locations/assign', {
  5043. method: 'POST',
  5044. body: JSON.stringify({ printer_ids: printerIds, location }),
  5045. }),
  5046. getPrinterStatus: (id: number) => printerStatusBatch(id),
  5047. refreshPrinterStatus: (id: number) =>
  5048. request<{ status: string }>(`/printers/${id}/refresh-status`, {
  5049. method: 'POST',
  5050. }),
  5051. connectPrinter: (id: number) =>
  5052. request<{ connected: boolean }>(`/printers/${id}/connect`, {
  5053. method: 'POST',
  5054. }),
  5055. getUsbCameras: () => request<{ cameras: UsbCamera[] }>('/printers/usb-cameras'),
  5056. testExternalCamera: (printerId: number, url: string, cameraType: string) =>
  5057. // `coalesced` is true when the frame came from a capture that was already
  5058. // running (Obico polling, a snapshot) rather than a connection this test
  5059. // opened — a single-reader camera is shared rather than opened twice, so
  5060. // the result is real but says nothing about reaching the camera just now.
  5061. // `live_view` is true when the tested camera is the one a viewer is
  5062. // watching: the answer comes from the live frame, not a test of its own.
  5063. // In the body: the URL may carry the camera login, and a query string
  5064. // ends up in the server's access log.
  5065. request<{ success: boolean; error?: string; resolution?: string; coalesced?: boolean; live_view?: boolean }>(
  5066. `/printers/${printerId}/camera/external/test`,
  5067. { method: 'POST', body: JSON.stringify({ url, camera_type: cameraType }) }
  5068. ),
  5069. // Print Control
  5070. stopPrint: (printerId: number) =>
  5071. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/stop`, {
  5072. method: 'POST',
  5073. }),
  5074. pausePrint: (printerId: number) =>
  5075. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/pause`, {
  5076. method: 'POST',
  5077. }),
  5078. resumePrint: (printerId: number) =>
  5079. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/resume`, {
  5080. method: 'POST',
  5081. }),
  5082. clearPlate: (printerId: number) =>
  5083. request<{ success: boolean; message: string }>(`/printers/${printerId}/clear-plate`, {
  5084. method: 'POST',
  5085. }),
  5086. // Get current print user (for reprint tracking - Issue #206)
  5087. getCurrentPrintUser: (printerId: number) =>
  5088. request<{ user_id?: number; username?: string }>(`/printers/${printerId}/current-print-user`),
  5089. // Print Speed Control
  5090. setPrintSpeed: (printerId: number, mode: number) =>
  5091. request<{ success: boolean; message: string }>(`/printers/${printerId}/print-speed?mode=${mode}`, {
  5092. method: 'POST',
  5093. }),
  5094. setNozzleTemperature: (printerId: number, target: number, nozzle: number = 0) =>
  5095. request<{ success: boolean; message: string }>(
  5096. `/printers/${printerId}/temperature/nozzle?target=${target}&nozzle=${nozzle}`,
  5097. { method: 'POST' }
  5098. ),
  5099. setBedTemperature: (printerId: number, target: number) =>
  5100. request<{ success: boolean; message: string }>(`/printers/${printerId}/temperature/bed?target=${target}`, {
  5101. method: 'POST',
  5102. }),
  5103. setChamberTemperature: (printerId: number, target: number) =>
  5104. request<{ success: boolean; message: string }>(`/printers/${printerId}/temperature/chamber?target=${target}`, {
  5105. method: 'POST',
  5106. }),
  5107. setFanSpeed: (printerId: number, fan: 'part' | 'aux' | 'aux2' | 'chamber', speed: number) =>
  5108. request<{ success: boolean; message: string }>(`/printers/${printerId}/fan-speed?fan=${fan}&speed=${speed}`, {
  5109. method: 'POST',
  5110. }),
  5111. selectExtruder: (printerId: number, extruder: number) =>
  5112. request<{ success: boolean; message: string }>(`/printers/${printerId}/select-extruder?extruder=${extruder}`, {
  5113. method: 'POST',
  5114. }),
  5115. setAirductMode: (printerId: number, mode: 'cooling' | 'heating') =>
  5116. request<{ success: boolean; message: string }>(`/printers/${printerId}/airduct-mode?mode=${mode}`, {
  5117. method: 'POST',
  5118. }),
  5119. // Bed (Z-axis) jog
  5120. bedJog: (printerId: number, distance: number) =>
  5121. request<{ success: boolean; message: string }>(
  5122. `/printers/${printerId}/bed-jog?distance=${distance}`,
  5123. { method: 'POST' }
  5124. ),
  5125. xyJog: (printerId: number, x: number, y: number) =>
  5126. request<{ success: boolean; message: string }>(
  5127. `/printers/${printerId}/xy-jog?x=${x}&y=${y}`,
  5128. { method: 'POST' }
  5129. ),
  5130. extruderJog: (printerId: number, distance: number) =>
  5131. request<{ success: boolean; message: string }>(
  5132. `/printers/${printerId}/extruder-jog?distance=${distance}`,
  5133. { method: 'POST' }
  5134. ),
  5135. homeAxes: (printerId: number, axes: 'z' | 'xy' | 'all' = 'z') =>
  5136. request<{ success: boolean; message: string }>(
  5137. `/printers/${printerId}/home-axes?axes=${axes}`,
  5138. { method: 'POST' }
  5139. ),
  5140. // Chamber Light Control
  5141. setChamberLight: (printerId: number, on: boolean) =>
  5142. request<{ success: boolean; message: string }>(`/printers/${printerId}/chamber-light?on=${on}`, {
  5143. method: 'POST',
  5144. }),
  5145. // AMS Drying Control
  5146. startDrying: (printerId: number, amsId: number, temp: number, duration: number, filament: string = '', rotateTray: boolean = false) =>
  5147. request<{ status: string; ams_id: number; temp: number; duration: number }>(
  5148. `/printers/${printerId}/drying/start?ams_id=${amsId}&temp=${temp}&duration=${duration}&filament=${encodeURIComponent(filament)}&rotate_tray=${rotateTray}`,
  5149. { method: 'POST' }
  5150. ),
  5151. stopDrying: (printerId: number, amsId: number) =>
  5152. request<{ status: string; ams_id: number }>(
  5153. `/printers/${printerId}/drying/stop?ams_id=${amsId}`,
  5154. { method: 'POST' }
  5155. ),
  5156. // Scheduled (delayed) drying runs (#2638)
  5157. createScheduledDrying: (data: {
  5158. printer_id: number;
  5159. ams_id: number;
  5160. temp: number;
  5161. duration_hours: number;
  5162. filament?: string;
  5163. rotate_tray?: boolean;
  5164. start_after: string | null;
  5165. }) =>
  5166. request<ScheduledDrying>('/scheduled-dryings', {
  5167. method: 'POST',
  5168. body: JSON.stringify(data),
  5169. }),
  5170. // Omit printerId for the whole fleet in one request; the printer cards share
  5171. // that single query rather than each polling for its own id.
  5172. listScheduledDryings: (printerId?: number) =>
  5173. request<ScheduledDrying[]>(
  5174. printerId === undefined ? '/scheduled-dryings' : `/scheduled-dryings?printer_id=${printerId}`
  5175. ),
  5176. cancelScheduledDrying: (id: number) =>
  5177. request<{ status: string; id: number }>(`/scheduled-dryings/${id}`, { method: 'DELETE' }),
  5178. // AMS Filament Backup (auto-switch to a backup spool when one runs out)
  5179. setAmsFilamentBackup: (printerId: number, enabled: boolean) =>
  5180. request<{ success: boolean; ams_filament_backup: boolean }>(
  5181. `/printers/${printerId}/ams-backup?enabled=${enabled}`,
  5182. { method: 'POST' }
  5183. ),
  5184. // Per-globalTrayId remaining grams for this printer's inventory-bound slots
  5185. // (#1766). Drives the client-side "Prefer Lowest Remaining Filament" sort
  5186. // when computing the AMS mapping; mirrors backend `_build_inventory_remain_overrides`
  5187. // so internal and Spoolman modes both work uniformly.
  5188. getInventoryRemain: (printerId: number) =>
  5189. request<InventoryRemainResponse>(
  5190. `/printers/${printerId}/inventory-remain`,
  5191. ),
  5192. // Skip Objects
  5193. getPrintableObjects: (printerId: number) =>
  5194. request<{
  5195. objects: Array<{ id: number; name: string; x: number | null; y: number | null; skipped: boolean }>;
  5196. total: number;
  5197. skipped_count: number;
  5198. is_printing: boolean;
  5199. bbox_all: [number, number, number, number] | null;
  5200. }>(`/printers/${printerId}/print/objects`),
  5201. skipObjects: (printerId: number, objectIds: number[]) =>
  5202. request<{ success: boolean; message: string; skipped_objects: number[] }>(
  5203. `/printers/${printerId}/print/skip-objects`,
  5204. {
  5205. method: 'POST',
  5206. body: JSON.stringify(objectIds),
  5207. }
  5208. ),
  5209. // HMS Errors
  5210. clearHMSErrors: (printerId: number) =>
  5211. request<{ success: boolean; message: string }>(`/printers/${printerId}/hms/clear`, { method: 'POST' }),
  5212. executeHMSAction: (printerId: number, data: HMSActionBody) =>
  5213. request<{ success: boolean; message: string }>(`/printers/${printerId}/hms/execute-action`, {
  5214. method: 'POST',
  5215. body: JSON.stringify(data),
  5216. }),
  5217. // AMS Control
  5218. refreshAmsSlot: (printerId: number, amsId: number, slotId: number) =>
  5219. request<{ success: boolean; message: string }>(
  5220. `/printers/${printerId}/ams/${amsId}/slot/${slotId}/refresh`,
  5221. { method: 'POST' }
  5222. ),
  5223. // Load filament from a tray. trayId: 0-15 for AMS (amsId*4+slotId), 128-135 for an
  5224. // AMS-HT (its unit id), 254 for external spool.
  5225. // extruderId (0 = right, 1 = left) names the hotend to feed. Pass it only on a
  5226. // printer with a Filament Track Switch — there the AMS is bound to a switch
  5227. // inlet rather than a hotend, so the firmware cannot work the target out and
  5228. // drops the command. Omit it everywhere else, as BambuStudio does.
  5229. loadAmsTray: (printerId: number, trayId: number, extruderId?: number) =>
  5230. request<{ success: boolean; message: string }>(
  5231. `/printers/${printerId}/ams/load?tray_id=${trayId}` +
  5232. (extruderId !== undefined ? `&extruder_id=${extruderId}` : ''),
  5233. { method: 'POST' }
  5234. ),
  5235. // Unload filament. trayId names the slot to unload, which is what tells a
  5236. // dual-nozzle printer which of its two hotends to act on; omit it to unload
  5237. // whatever the printer's single tray_now field names.
  5238. unloadAms: (printerId: number, trayId?: number) =>
  5239. request<{ success: boolean; message: string }>(
  5240. `/printers/${printerId}/ams/unload` + (trayId !== undefined ? `?tray_id=${trayId}` : ''),
  5241. { method: 'POST' }
  5242. ),
  5243. // MQTT Debug Logging
  5244. enableMQTTLogging: (printerId: number) =>
  5245. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/enable`, {
  5246. method: 'POST',
  5247. }),
  5248. disableMQTTLogging: (printerId: number) =>
  5249. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/disable`, {
  5250. method: 'POST',
  5251. }),
  5252. getMQTTLogs: (printerId: number) =>
  5253. request<MQTTLogsResponse>(`/printers/${printerId}/logging`),
  5254. clearMQTTLogs: (printerId: number) =>
  5255. request<{ status: string }>(`/printers/${printerId}/logging`, {
  5256. method: 'DELETE',
  5257. }),
  5258. // Printer File Manager
  5259. getPrinterFiles: (printerId: number, path = '/') =>
  5260. request<{
  5261. path: string;
  5262. files: Array<{
  5263. name: string;
  5264. is_directory: boolean;
  5265. size: number;
  5266. path: string;
  5267. mtime?: string;
  5268. }>;
  5269. warnings: Array<'printer_unavailable' | 'listing_timed_out'>;
  5270. }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`),
  5271. getPrinterFileDownloadUrl: (printerId: number, path: string) =>
  5272. `${API_BASE}/printers/${printerId}/files/download?path=${encodeURIComponent(path)}`,
  5273. getPrinterFileGcodeUrl: (printerId: number, path: string) =>
  5274. `${API_BASE}/printers/${printerId}/files/gcode?path=${encodeURIComponent(path)}`,
  5275. getPrinterFilePlates: (printerId: number, path: string) =>
  5276. request<{
  5277. printer_id: number;
  5278. path: string;
  5279. filename: string;
  5280. plates: Array<{
  5281. index: number;
  5282. name: string | null;
  5283. objects: string[];
  5284. has_thumbnail: boolean;
  5285. thumbnail_url: string | null;
  5286. print_time_seconds: number | null;
  5287. filament_used_grams: number | null;
  5288. filaments: Array<{
  5289. slot_id: number;
  5290. type: string;
  5291. color: string;
  5292. used_grams: number;
  5293. used_meters: number;
  5294. }>;
  5295. }>;
  5296. is_multi_plate: boolean;
  5297. }>(`/printers/${printerId}/files/plates?path=${encodeURIComponent(path)}`),
  5298. getPrinterFilePlateThumbnail: (printerId: number, plateIndex: number, path: string) =>
  5299. withMediaToken(`${API_BASE}/printers/${printerId}/files/plate-thumbnail/${plateIndex}?path=${encodeURIComponent(path)}`),
  5300. downloadPrinterFilesAsZip: async (
  5301. printerId: number,
  5302. paths: string[],
  5303. sizes: Record<string, number>,
  5304. filename = 'printer-files.zip',
  5305. asZip = true,
  5306. signal?: AbortSignal,
  5307. onProgress?: (completed: number, total: number) => void,
  5308. ): Promise<{ requested: number; successful: number; failed: number }> => {
  5309. type JobStatus = {
  5310. job_id: string;
  5311. state: 'queued' | 'preparing' | 'ready' | 'failed' | 'cancelled';
  5312. requested: number;
  5313. successful: number;
  5314. failed: number;
  5315. token: string | null;
  5316. message: string | null;
  5317. };
  5318. let jobId: string | null = null;
  5319. try {
  5320. if (signal?.aborted) throw new DOMException('Download cancelled', 'AbortError');
  5321. let status = await request<JobStatus>(`/printers/${printerId}/files/download-job`, {
  5322. method: 'POST',
  5323. body: JSON.stringify({ paths, sizes, filename, as_zip: asZip }),
  5324. signal,
  5325. });
  5326. jobId = status.job_id;
  5327. let polls = 0;
  5328. while (status.state === 'queued' || status.state === 'preparing') {
  5329. onProgress?.(status.successful + status.failed, status.requested);
  5330. // Small selections finish in the first seconds, so poll quickly there.
  5331. // A large one runs for up to half an hour, where half-second polling is
  5332. // thousands of requests that each re-check the caller's credentials.
  5333. const delay = polls < 10 ? 500 : 2000;
  5334. polls += 1;
  5335. await new Promise<void>((resolve, reject) => {
  5336. if (signal?.aborted) {
  5337. reject(new DOMException('Download cancelled', 'AbortError'));
  5338. return;
  5339. }
  5340. const onAbort = () => {
  5341. window.clearTimeout(timer);
  5342. reject(new DOMException('Download cancelled', 'AbortError'));
  5343. };
  5344. const timer = window.setTimeout(() => {
  5345. signal?.removeEventListener('abort', onAbort);
  5346. resolve();
  5347. }, delay);
  5348. signal?.addEventListener('abort', onAbort, { once: true });
  5349. });
  5350. status = await request<JobStatus>(`/printers/${printerId}/files/download-jobs/${jobId}`, { signal });
  5351. }
  5352. onProgress?.(status.successful + status.failed, status.requested);
  5353. if (status.state !== 'ready' || !status.token) {
  5354. throw new Error(status.message || (status.state === 'cancelled'
  5355. ? 'Download cancelled'
  5356. : 'Printer download preparation failed'));
  5357. }
  5358. const link = document.createElement('a');
  5359. link.href = `${API_BASE}/printers/${printerId}/files/dl/${encodeURIComponent(status.token)}/${encodeURIComponent(filename)}`;
  5360. link.download = filename;
  5361. document.body.appendChild(link);
  5362. link.click();
  5363. link.remove();
  5364. return {
  5365. requested: status.requested,
  5366. successful: status.successful,
  5367. failed: status.failed,
  5368. };
  5369. } catch (error) {
  5370. if (jobId) {
  5371. await request(`/printers/${printerId}/files/download-jobs/${jobId}`, { method: 'DELETE' }).catch(() => undefined);
  5372. }
  5373. throw error;
  5374. }
  5375. },
  5376. deletePrinterFile: (printerId: number, path: string) =>
  5377. request<{ status: string; path: string }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`, {
  5378. method: 'DELETE',
  5379. }),
  5380. getPrinterStorage: (printerId: number) =>
  5381. request<{ used_bytes: number | null; free_bytes: number | null }>(`/printers/${printerId}/storage`),
  5382. // Archives
  5383. getArchives: (printerId?: number, projectId?: number, limit = 10000, offset = 0, dateFrom?: string, dateTo?: string) => {
  5384. const params = new URLSearchParams();
  5385. if (printerId) params.set('printer_id', String(printerId));
  5386. if (projectId) params.set('project_id', String(projectId));
  5387. params.set('limit', String(limit));
  5388. params.set('offset', String(offset));
  5389. if (dateFrom) params.set('date_from', dateFrom);
  5390. if (dateTo) params.set('date_to', dateTo);
  5391. addDayZone(params);
  5392. return request<Archive[]>(`/archives/?${params}`);
  5393. },
  5394. // Latest archive of every printer in one request, for the printer cards.
  5395. getLastArchivePerPrinter: () => request<Archive[]>('/archives/last-per-printer'),
  5396. getArchivesSlim: (dateFrom?: string, dateTo?: string, createdById?: number) => {
  5397. const params = new URLSearchParams();
  5398. if (dateFrom) params.set('date_from', dateFrom);
  5399. if (dateTo) params.set('date_to', dateTo);
  5400. addDayZone(params);
  5401. if (createdById !== undefined) params.set('created_by_id', String(createdById));
  5402. const qs = params.toString();
  5403. return request<ArchiveSlim[]>(`/archives/slim${qs ? `?${qs}` : ''}`);
  5404. },
  5405. getArchive: (id: number, runId?: number | null) =>
  5406. request<Archive>(`/archives/${id}${runId != null ? `?run_id=${runId}` : ''}`),
  5407. getArchiveRuns: (id: number) => request<PrintLogResponse>(`/archives/${id}/runs`),
  5408. // The prints of the archives the caller sees that ended between two days
  5409. // (archive redesign P4: the calendar), in id order.
  5410. getArchivePrints: (params: { dateFrom: string; dateTo: string; printerId?: number; limit?: number; offset?: number }) => {
  5411. const search = new URLSearchParams({ date_from: params.dateFrom, date_to: params.dateTo });
  5412. if (params.printerId) search.set('printer_id', String(params.printerId));
  5413. if (params.limit) search.set('limit', String(params.limit));
  5414. if (params.offset) search.set('offset', String(params.offset));
  5415. addDayZone(search);
  5416. return request<PrintLogResponse>(`/archives/prints?${search}`);
  5417. },
  5418. /**
  5419. * Pre-flight for the delete-confirm modal (#1734). Returns the number of
  5420. * related queue items that will be removed along with the archive AND how
  5421. * many are currently printing (server 409s on delete if > 0).
  5422. */
  5423. getArchiveDeleteImpact: (id: number) =>
  5424. request<{ related_queue_items: number; currently_printing: number }>(
  5425. `/archives/${id}/delete-impact`
  5426. ),
  5427. getNo3MFWarning: () =>
  5428. request<{
  5429. has_fallback: boolean;
  5430. reason:
  5431. | 'ftps_cooloff'
  5432. | 'ftp_transfer_failed'
  5433. | 'internal_storage'
  5434. | 'no_external_storage'
  5435. | 'internal_history'
  5436. | null;
  5437. }>(
  5438. '/archives/no-3mf-warning',
  5439. ),
  5440. updateArchive: (id: number, data: {
  5441. printer_id?: number | null;
  5442. project_id?: number | null;
  5443. print_name?: string;
  5444. is_favorite?: boolean;
  5445. tags?: string;
  5446. notes?: string;
  5447. cost?: number;
  5448. failure_reason?: string | null;
  5449. status?: string;
  5450. quantity?: number;
  5451. external_url?: string | null;
  5452. filament_used_grams?: number | null;
  5453. // Post-print outcome verdict (#1898); null clears it
  5454. user_verdict?: 'good' | 'reject' | null;
  5455. // Which surface answered. The backend only accepts the sources a client
  5456. // can honestly claim and defaults to 'api' when none is given.
  5457. user_verdict_source?: 'dialog' | 'printer_card';
  5458. // The run the verdict / outcome is for; omitted means the latest run.
  5459. run_id?: number;
  5460. }) =>
  5461. request<Archive>(`/archives/${id}`, {
  5462. method: 'PATCH',
  5463. body: JSON.stringify(data),
  5464. }),
  5465. toggleFavorite: (id: number) =>
  5466. request<Archive>(`/archives/${id}/favorite`, { method: 'POST' }),
  5467. // Soft-deletes by default (#1343): files removed from disk, row hidden
  5468. // from listings, but its filament / time / cost / energy contribution
  5469. // stays in Quick Stats. Pass purgeStats=true to hard-delete and drop the
  5470. // row from statistics too.
  5471. deleteArchive: (id: number, purgeStats: boolean = false) =>
  5472. request<void>(`/archives/${id}${purgeStats ? '?purge_stats=true' : ''}`, { method: 'DELETE' }),
  5473. // ========== Archive auto-purge (#1008 follow-up) ==========
  5474. previewArchivePurge: (olderThanDays: number, purgeStats: boolean = false) =>
  5475. request<ArchivePurgePreview>(
  5476. `/archives/purge/preview?older_than_days=${olderThanDays}&purge_stats=${purgeStats}`,
  5477. ),
  5478. // #1390: purgeStats=false (default) soft-deletes each old archive — Quick Stats
  5479. // preserved, files removed from disk, row hidden via deleted_at. true matches
  5480. // the single-archive delete's `?purge_stats=true` semantics (hard-deletes the
  5481. // linked PrintLogEntry rows so the contribution drops from /stats too).
  5482. executeArchivePurge: (olderThanDays: number, purgeStats: boolean = false) =>
  5483. request<{ deleted: number; purge_stats: boolean }>('/archives/purge', {
  5484. method: 'POST',
  5485. body: JSON.stringify({ older_than_days: olderThanDays, purge_stats: purgeStats }),
  5486. }),
  5487. // Archives of one file merge into the oldest (archive redesign P2).
  5488. previewArchiveMerge: () => request<ArchiveMergePreview>('/archives/merge-preview'),
  5489. /** How many duplicate groups there are; cheap, for offering the merge. */
  5490. getArchiveMergeCount: () => request<{ groups: number }>('/archives/merge-count'),
  5491. mergeArchives: (survivorIds: number[]) =>
  5492. request<ArchiveMergeResult>('/archives/merge', {
  5493. method: 'POST',
  5494. body: JSON.stringify({ survivor_ids: survivorIds }),
  5495. }),
  5496. getArchivePurgeSettings: () =>
  5497. request<ArchivePurgeSettings>('/archives/purge/settings'),
  5498. updateArchivePurgeSettings: (body: ArchivePurgeSettings) =>
  5499. request<ArchivePurgeSettings>('/archives/purge/settings', {
  5500. method: 'PUT',
  5501. body: JSON.stringify(body),
  5502. }),
  5503. getArchiveStats: (options?: { dateFrom?: string; dateTo?: string; createdById?: number }) => {
  5504. const params = new URLSearchParams();
  5505. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  5506. if (options?.dateTo) params.set('date_to', options.dateTo);
  5507. addDayZone(params);
  5508. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  5509. const qs = params.toString();
  5510. return request<ArchiveStats>(`/archives/stats${qs ? `?${qs}` : ''}`);
  5511. },
  5512. // Tag management
  5513. getTags: () => request<TagInfo[]>('/archives/tags'),
  5514. renameTag: (oldName: string, newName: string) =>
  5515. request<{ affected: number }>(`/archives/tags/${encodeURIComponent(oldName)}`, {
  5516. method: 'PUT',
  5517. body: JSON.stringify({ new_name: newName }),
  5518. }),
  5519. deleteTag: (name: string) =>
  5520. request<{ affected: number }>(`/archives/tags/${encodeURIComponent(name)}`, {
  5521. method: 'DELETE',
  5522. }),
  5523. recalculateCosts: () =>
  5524. request<{
  5525. message: string;
  5526. updated: number;
  5527. preserved: number;
  5528. usage_repriced: number;
  5529. spoolman_unreachable: number;
  5530. }>('/archives/recalculate-costs', { method: 'POST' }),
  5531. getFailureAnalysis: (options?: { days?: number; dateFrom?: string; dateTo?: string; printerId?: number; projectId?: number; createdById?: number }) => {
  5532. const params = new URLSearchParams();
  5533. if (options?.days) params.set('days', String(options.days));
  5534. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  5535. if (options?.dateTo) params.set('date_to', options.dateTo);
  5536. addDayZone(params);
  5537. if (options?.printerId) params.set('printer_id', String(options.printerId));
  5538. if (options?.projectId) params.set('project_id', String(options.projectId));
  5539. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  5540. const qs = params.toString();
  5541. return request<FailureAnalysis>(`/archives/analysis/failures${qs ? `?${qs}` : ''}`);
  5542. },
  5543. compareArchives: (archiveIds: number[]) =>
  5544. request<ArchiveComparison>(`/archives/compare?archive_ids=${archiveIds.join(',')}`),
  5545. exportArchives: async (options?: {
  5546. format?: 'csv' | 'xlsx';
  5547. fields?: string[];
  5548. printerId?: number;
  5549. projectId?: number;
  5550. status?: string;
  5551. dateFrom?: string;
  5552. dateTo?: string;
  5553. search?: string;
  5554. }): Promise<{ blob: Blob; filename: string }> => {
  5555. const params = new URLSearchParams();
  5556. if (options?.format) params.set('format', options.format);
  5557. if (options?.fields) params.set('fields', options.fields.join(','));
  5558. if (options?.printerId) params.set('printer_id', String(options.printerId));
  5559. if (options?.projectId) params.set('project_id', String(options.projectId));
  5560. if (options?.status) params.set('status', options.status);
  5561. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  5562. if (options?.dateTo) params.set('date_to', options.dateTo);
  5563. addDayZone(params);
  5564. if (options?.search) params.set('search', options.search);
  5565. const headers: Record<string, string> = {};
  5566. if (authToken) {
  5567. headers['Authorization'] = `Bearer ${authToken}`;
  5568. }
  5569. const response = await fetch(`${API_BASE}/archives/export?${params}`, { headers });
  5570. if (!response.ok) {
  5571. const error = await response.json().catch(() => ({}));
  5572. throw new Error(error.detail || `HTTP ${response.status}`);
  5573. }
  5574. const contentDisposition = response.headers.get('Content-Disposition');
  5575. let filename = options?.format === 'xlsx' ? 'archives_export.xlsx' : 'archives_export.csv';
  5576. if (contentDisposition) {
  5577. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  5578. if (match) filename = match[1];
  5579. }
  5580. const blob = await response.blob();
  5581. return { blob, filename };
  5582. },
  5583. exportStats: async (options?: {
  5584. format?: 'csv' | 'xlsx';
  5585. days?: number;
  5586. printerId?: number;
  5587. projectId?: number;
  5588. createdById?: number;
  5589. }): Promise<{ blob: Blob; filename: string }> => {
  5590. const params = new URLSearchParams();
  5591. if (options?.format) params.set('format', options.format);
  5592. if (options?.days) params.set('days', String(options.days));
  5593. if (options?.printerId) params.set('printer_id', String(options.printerId));
  5594. if (options?.projectId) params.set('project_id', String(options.projectId));
  5595. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  5596. const headers: Record<string, string> = {};
  5597. if (authToken) {
  5598. headers['Authorization'] = `Bearer ${authToken}`;
  5599. }
  5600. const response = await fetch(`${API_BASE}/archives/stats/export?${params}`, { headers });
  5601. if (!response.ok) {
  5602. const error = await response.json().catch(() => ({}));
  5603. throw new Error(error.detail || `HTTP ${response.status}`);
  5604. }
  5605. const contentDisposition = response.headers.get('Content-Disposition');
  5606. let filename = options?.format === 'xlsx' ? 'stats_export.xlsx' : 'stats_export.csv';
  5607. if (contentDisposition) {
  5608. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  5609. if (match) filename = match[1];
  5610. }
  5611. const blob = await response.blob();
  5612. return { blob, filename };
  5613. },
  5614. getArchiveThumbnail: (id: number) => withMediaToken(`${API_BASE}/archives/${id}/thumbnail?v=${Date.now()}`),
  5615. getArchivePlateThumbnail: (id: number, plateIndex: number) =>
  5616. withMediaToken(`${API_BASE}/archives/${id}/plate-thumbnail/${plateIndex}`),
  5617. getArchiveDownload: (id: number) => `${API_BASE}/archives/${id}/download`,
  5618. downloadArchive: async (id: number, filename?: string): Promise<void> => {
  5619. const headers: Record<string, string> = {};
  5620. if (authToken) {
  5621. headers['Authorization'] = `Bearer ${authToken}`;
  5622. }
  5623. const response = await fetch(`${API_BASE}/archives/${id}/download`, { headers });
  5624. if (!response.ok) {
  5625. const error = await response.json().catch(() => ({}));
  5626. throw new Error(error.detail || `HTTP ${response.status}`);
  5627. }
  5628. const disposition = response.headers.get('Content-Disposition');
  5629. const downloadFilename = parseContentDispositionFilename(disposition) || filename || `archive_${id}.3mf`;
  5630. const blob = await response.blob();
  5631. const url = window.URL.createObjectURL(blob);
  5632. const a = document.createElement('a');
  5633. a.href = url;
  5634. a.download = downloadFilename;
  5635. document.body.appendChild(a);
  5636. a.click();
  5637. document.body.removeChild(a);
  5638. window.URL.revokeObjectURL(url);
  5639. },
  5640. getArchiveGcode: (id: number) => `${API_BASE}/archives/${id}/gcode`,
  5641. getArchiveTimelapse: (id: number) => withMediaToken(`${API_BASE}/archives/${id}/timelapse?v=${Date.now()}`),
  5642. getArchiveRunTimelapse: (id: number, runId: number) =>
  5643. withMediaToken(`${API_BASE}/archives/${id}/runs/${runId}/timelapse?v=${Date.now()}`),
  5644. downloadArchiveTimelapse: async (id: number, filename: string): Promise<void> => {
  5645. const prepared = await request<{ token: string; filename: string }>(
  5646. `/archives/${id}/media-download-token`,
  5647. { method: 'POST' },
  5648. );
  5649. const link = document.createElement('a');
  5650. link.href = `${API_BASE}/archives/${id}/media/dl/${encodeURIComponent(prepared.token)}/${encodeURIComponent(filename)}`;
  5651. link.download = filename;
  5652. document.body.appendChild(link);
  5653. link.click();
  5654. link.remove();
  5655. },
  5656. getArchivePrinterMedia: (id: number) =>
  5657. request<ArchivePrinterMedia>(`/archives/${id}/printer-media`),
  5658. scanArchiveTimelapse: (id: number) =>
  5659. request<{
  5660. status: string;
  5661. message: string;
  5662. filename?: string;
  5663. available_files?: Array<{ name: string; path: string; size: number; mtime: string | null }>;
  5664. }>(`/archives/${id}/timelapse/scan`, {
  5665. method: 'POST',
  5666. }),
  5667. selectArchiveTimelapse: (id: number, filename: string) =>
  5668. request<{ status: string; message: string; filename: string }>(
  5669. `/archives/${id}/timelapse/select?filename=${encodeURIComponent(filename)}`,
  5670. { method: 'POST' }
  5671. ),
  5672. deleteArchiveTimelapse: (id: number) =>
  5673. request<{ status: string }>(`/archives/${id}/timelapse`, {
  5674. method: 'DELETE',
  5675. }),
  5676. uploadArchiveTimelapse: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  5677. const formData = new FormData();
  5678. formData.append('file', file);
  5679. const headers: Record<string, string> = {};
  5680. if (authToken) {
  5681. headers['Authorization'] = `Bearer ${authToken}`;
  5682. }
  5683. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/upload`, {
  5684. method: 'POST',
  5685. headers,
  5686. body: formData,
  5687. });
  5688. if (!response.ok) {
  5689. const error = await response.json().catch(() => ({}));
  5690. throw new Error(error.detail || `HTTP ${response.status}`);
  5691. }
  5692. return response.json();
  5693. },
  5694. // Timelapse Editor
  5695. getTimelapseInfo: (archiveId: number) =>
  5696. request<{
  5697. duration: number;
  5698. width: number;
  5699. height: number;
  5700. fps: number;
  5701. codec: string;
  5702. file_size: number;
  5703. has_audio: boolean;
  5704. }>(`/archives/${archiveId}/timelapse/info`),
  5705. getTimelapseThumbnails: (archiveId: number, count: number = 10) =>
  5706. request<{
  5707. thumbnails: string[];
  5708. timestamps: number[];
  5709. }>(`/archives/${archiveId}/timelapse/thumbnails?count=${count}`),
  5710. processTimelapse: async (
  5711. archiveId: number,
  5712. params: {
  5713. trimStart?: number;
  5714. trimEnd?: number;
  5715. speed?: number;
  5716. /** Music volume, 0 to 1. */
  5717. audioVolume?: number;
  5718. saveMode: 'replace' | 'new';
  5719. outputFilename?: string;
  5720. },
  5721. audioFile?: File
  5722. ): Promise<TimelapseJob> => {
  5723. const formData = new FormData();
  5724. formData.append('trim_start', String(params.trimStart ?? 0));
  5725. if (params.trimEnd !== undefined) {
  5726. formData.append('trim_end', String(params.trimEnd));
  5727. }
  5728. formData.append('speed', String(params.speed ?? 1));
  5729. if (params.audioVolume !== undefined) {
  5730. formData.append('audio_volume', String(params.audioVolume));
  5731. }
  5732. formData.append('save_mode', params.saveMode);
  5733. if (params.outputFilename) {
  5734. formData.append('output_filename', params.outputFilename);
  5735. }
  5736. if (audioFile) {
  5737. formData.append('audio', audioFile);
  5738. }
  5739. const headers: Record<string, string> = {};
  5740. if (authToken) {
  5741. headers['Authorization'] = `Bearer ${authToken}`;
  5742. }
  5743. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/process`, {
  5744. method: 'POST',
  5745. headers,
  5746. body: formData,
  5747. });
  5748. if (!response.ok) {
  5749. const error = await response.json().catch(() => ({}));
  5750. throw new Error(error.detail || `HTTP ${response.status}`);
  5751. }
  5752. return response.json();
  5753. },
  5754. // The archive's running or last re-encode; null when there has been none.
  5755. getTimelapseJob: async (archiveId: number): Promise<TimelapseJob | null> => {
  5756. try {
  5757. return await request<TimelapseJob>(`/archives/${archiveId}/timelapse/job`);
  5758. } catch (error) {
  5759. if (error instanceof ApiError && error.status === 404) return null;
  5760. throw error;
  5761. }
  5762. },
  5763. cancelTimelapseJob: (archiveId: number) =>
  5764. request<TimelapseJob>(`/archives/${archiveId}/timelapse/job`, { method: 'DELETE' }),
  5765. // Photos
  5766. getArchivePhotoUrl: (archiveId: number, filename: string) =>
  5767. withMediaToken(`${API_BASE}/archives/${archiveId}/photos/${encodeURIComponent(filename)}`),
  5768. uploadArchivePhoto: async (archiveId: number, file: File): Promise<{ status: string; filename: string; photos: string[] }> => {
  5769. const formData = new FormData();
  5770. formData.append('file', file);
  5771. const headers: Record<string, string> = {};
  5772. if (authToken) {
  5773. headers['Authorization'] = `Bearer ${authToken}`;
  5774. }
  5775. const response = await fetch(`${API_BASE}/archives/${archiveId}/photos`, {
  5776. headers,
  5777. method: 'POST',
  5778. body: formData,
  5779. });
  5780. if (!response.ok) {
  5781. const error = await response.json().catch(() => ({}));
  5782. throw new Error(error.detail || `HTTP ${response.status}`);
  5783. }
  5784. return response.json();
  5785. },
  5786. deleteArchivePhoto: (archiveId: number, filename: string) =>
  5787. request<{ status: string; photos: string[] | null }>(`/archives/${archiveId}/photos/${encodeURIComponent(filename)}`, {
  5788. method: 'DELETE',
  5789. }),
  5790. // Source 3MF (original slicer project file)
  5791. getSource3mfDownloadUrl: (archiveId: number) =>
  5792. `${API_BASE}/archives/${archiveId}/source`,
  5793. downloadSource3mf: async (archiveId: number): Promise<void> => {
  5794. const headers: Record<string, string> = {};
  5795. if (authToken) {
  5796. headers['Authorization'] = `Bearer ${authToken}`;
  5797. }
  5798. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, { headers });
  5799. if (!response.ok) {
  5800. const error = await response.json().catch(() => ({}));
  5801. throw new Error(error.detail || `HTTP ${response.status}`);
  5802. }
  5803. const disposition = response.headers.get('Content-Disposition');
  5804. const filename = parseContentDispositionFilename(disposition) || `source_${archiveId}.3mf`;
  5805. const blob = await response.blob();
  5806. const url = window.URL.createObjectURL(blob);
  5807. const a = document.createElement('a');
  5808. a.href = url;
  5809. a.download = filename;
  5810. document.body.appendChild(a);
  5811. a.click();
  5812. document.body.removeChild(a);
  5813. window.URL.revokeObjectURL(url);
  5814. },
  5815. getSource3mfForSlicer: (archiveId: number, filename: string) => {
  5816. // Sanitize: slicers url_decode() the entire URL, so / \ ? # in filenames break path routing
  5817. const safe = filename.replace(/[/\\?#]/g, '_');
  5818. return `${API_BASE}/archives/${archiveId}/source/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  5819. },
  5820. createSourceSlicerToken: (archiveId: number) =>
  5821. request<{ token: string }>(`/archives/${archiveId}/source-slicer-token`, { method: 'POST' }),
  5822. getSourceSlicerDownloadUrl: (archiveId: number, token: string, filename: string) => {
  5823. const safe = filename.replace(/[/\\?#]/g, '_');
  5824. return `${API_BASE}/archives/${archiveId}/source-dl/${token}/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  5825. },
  5826. uploadSource3mf: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  5827. const formData = new FormData();
  5828. formData.append('file', file);
  5829. const headers: Record<string, string> = {};
  5830. if (authToken) {
  5831. headers['Authorization'] = `Bearer ${authToken}`;
  5832. }
  5833. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, {
  5834. method: 'POST',
  5835. headers,
  5836. body: formData,
  5837. });
  5838. if (!response.ok) {
  5839. const error = await response.json().catch(() => ({}));
  5840. throw new Error(error.detail || `HTTP ${response.status}`);
  5841. }
  5842. return response.json();
  5843. },
  5844. deleteSource3mf: (archiveId: number) =>
  5845. request<{ status: string }>(`/archives/${archiveId}/source`, {
  5846. method: 'DELETE',
  5847. }),
  5848. // F3D (Fusion 360 design file)
  5849. downloadF3d: async (archiveId: number): Promise<void> => {
  5850. const headers: Record<string, string> = {};
  5851. if (authToken) {
  5852. headers['Authorization'] = `Bearer ${authToken}`;
  5853. }
  5854. const response = await fetch(`${API_BASE}/archives/${archiveId}/f3d`, { headers });
  5855. if (!response.ok) {
  5856. const error = await response.json().catch(() => ({}));
  5857. throw new Error(error.detail || `HTTP ${response.status}`);
  5858. }
  5859. const disposition = response.headers.get('Content-Disposition');
  5860. const filename = parseContentDispositionFilename(disposition) || `archive_${archiveId}.f3d`;
  5861. const blob = await response.blob();
  5862. const url = window.URL.createObjectURL(blob);
  5863. const a = document.createElement('a');
  5864. a.href = url;
  5865. a.download = filename;
  5866. document.body.appendChild(a);
  5867. a.click();
  5868. document.body.removeChild(a);
  5869. window.URL.revokeObjectURL(url);
  5870. },
  5871. uploadF3d: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  5872. const formData = new FormData();
  5873. formData.append('file', file);
  5874. const headers: Record<string, string> = {};
  5875. if (authToken) {
  5876. headers['Authorization'] = `Bearer ${authToken}`;
  5877. }
  5878. const response = await fetch(`${API_BASE}/archives/${archiveId}/f3d`, {
  5879. method: 'POST',
  5880. headers,
  5881. body: formData,
  5882. });
  5883. if (!response.ok) {
  5884. const error = await response.json().catch(() => ({}));
  5885. throw new Error(error.detail || `HTTP ${response.status}`);
  5886. }
  5887. return response.json();
  5888. },
  5889. deleteF3d: (archiveId: number) =>
  5890. request<{ status: string }>(`/archives/${archiveId}/f3d`, {
  5891. method: 'DELETE',
  5892. }),
  5893. // QR Code
  5894. getArchiveQRCodeUrl: (archiveId: number, size = 200) =>
  5895. withMediaToken(`${API_BASE}/archives/${archiveId}/qrcode?size=${size}`),
  5896. getArchiveCapabilities: (id: number) =>
  5897. request<{
  5898. has_model: boolean;
  5899. has_gcode: boolean;
  5900. has_source: boolean;
  5901. build_volume: { x: number; y: number; z: number };
  5902. filament_colors: string[];
  5903. }>(`/archives/${id}/capabilities`),
  5904. // Project Page
  5905. getArchiveProjectPage: (id: number) =>
  5906. request<{
  5907. title: string | null;
  5908. description: string | null;
  5909. designer: string | null;
  5910. designer_user_id: string | null;
  5911. license: string | null;
  5912. copyright: string | null;
  5913. creation_date: string | null;
  5914. modification_date: string | null;
  5915. origin: string | null;
  5916. profile_title: string | null;
  5917. profile_description: string | null;
  5918. profile_cover: string | null;
  5919. profile_user_id: string | null;
  5920. profile_user_name: string | null;
  5921. design_model_id: string | null;
  5922. design_profile_id: string | null;
  5923. design_region: string | null;
  5924. model_pictures: Array<{ name: string; path: string; url: string }>;
  5925. profile_pictures: Array<{ name: string; path: string; url: string }>;
  5926. thumbnails: Array<{ name: string; path: string; url: string }>;
  5927. }>(`/archives/${id}/project-page`),
  5928. updateArchiveProjectPage: (id: number, data: {
  5929. title?: string;
  5930. description?: string;
  5931. designer?: string;
  5932. license?: string;
  5933. copyright?: string;
  5934. profile_title?: string;
  5935. profile_description?: string;
  5936. }) =>
  5937. request(`/archives/${id}/project-page`, {
  5938. method: 'PATCH',
  5939. body: JSON.stringify(data),
  5940. }),
  5941. getArchiveForSlicer: (id: number, filename: string) => {
  5942. const safe = filename.replace(/[/\\?#]/g, '_');
  5943. return `${API_BASE}/archives/${id}/file/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  5944. },
  5945. createArchiveSlicerToken: (archiveId: number) =>
  5946. request<{ token: string }>(`/archives/${archiveId}/slicer-token`, { method: 'POST' }),
  5947. getArchiveSlicerDownloadUrl: (archiveId: number, token: string, filename: string) => {
  5948. const safe = filename.replace(/[/\\?#]/g, '_');
  5949. return `${API_BASE}/archives/${archiveId}/dl/${token}/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  5950. },
  5951. getArchivePlates: (archiveId: number) =>
  5952. request<ArchivePlatesResponse>(`/archives/${archiveId}/plates`),
  5953. getArchiveFilamentRequirements: (
  5954. archiveId: number,
  5955. plateId?: number,
  5956. requestId?: string,
  5957. /** Ask for one entry per project slot instead of only the slots this
  5958. * plate consumes. The slice modal needs it: its filament list is
  5959. * positional, so a source whose only used slot is 4 must still present
  5960. * four rows or the user's pick is bound to slot 1 (#2712). Print-time
  5961. * AMS matching must NOT set this — it wants the used-only list. */
  5962. fullSlots?: boolean,
  5963. ) => {
  5964. const qs = new URLSearchParams();
  5965. if (plateId !== undefined) qs.set('plate_id', String(plateId));
  5966. if (requestId) qs.set('request_id', requestId);
  5967. if (fullSlots) qs.set('full_slots', 'true');
  5968. return request<{
  5969. archive_id: number;
  5970. filename: string;
  5971. plate_id: number | null;
  5972. filaments: Array<{
  5973. slot_id: number;
  5974. type: string;
  5975. color: string;
  5976. used_grams: number;
  5977. used_meters: number;
  5978. used_in_plate?: boolean;
  5979. }>;
  5980. }>(`/archives/${archiveId}/filament-requirements${qs.toString() ? `?${qs}` : ''}`);
  5981. },
  5982. uploadArchivesBulk: async (files: File[], printerId?: number): Promise<BulkUploadResult> => {
  5983. const formData = new FormData();
  5984. files.forEach((file) => formData.append('files', file));
  5985. const url = printerId
  5986. ? `${API_BASE}/archives/upload-bulk?printer_id=${printerId}`
  5987. : `${API_BASE}/archives/upload-bulk`;
  5988. const headers: Record<string, string> = {};
  5989. if (authToken) {
  5990. headers['Authorization'] = `Bearer ${authToken}`;
  5991. }
  5992. const response = await fetch(url, {
  5993. method: 'POST',
  5994. headers,
  5995. body: formData,
  5996. });
  5997. if (!response.ok) {
  5998. const error = await response.json().catch(() => ({}));
  5999. throw new Error(error.detail || `HTTP ${response.status}`);
  6000. }
  6001. return response.json();
  6002. },
  6003. // Print Log
  6004. getPrintLog: (params?: {
  6005. search?: string;
  6006. printerId?: number;
  6007. username?: string;
  6008. status?: string;
  6009. dateFrom?: string;
  6010. dateTo?: string;
  6011. limit?: number;
  6012. offset?: number;
  6013. // Sorting is server-side because paging is: ordering only the rows the
  6014. // client holds would sort one page, not the log (#2636).
  6015. sortBy?: string;
  6016. sortDir?: 'asc' | 'desc';
  6017. }) => {
  6018. const searchParams = new URLSearchParams();
  6019. if (params?.search) searchParams.set('search', params.search);
  6020. if (params?.printerId) searchParams.set('printer_id', String(params.printerId));
  6021. if (params?.username) searchParams.set('created_by_username', params.username);
  6022. if (params?.status) searchParams.set('status', params.status);
  6023. if (params?.dateFrom) searchParams.set('date_from', params.dateFrom);
  6024. if (params?.dateTo) searchParams.set('date_to', params.dateTo);
  6025. if (params?.limit) searchParams.set('limit', String(params.limit));
  6026. if (params?.offset !== undefined) searchParams.set('offset', String(params.offset));
  6027. if (params?.sortBy) searchParams.set('sort_by', params.sortBy);
  6028. if (params?.sortDir) searchParams.set('sort_dir', params.sortDir);
  6029. return request<PrintLogResponse>(`/print-log/?${searchParams}`);
  6030. },
  6031. getPrintLogThumbnail: (id: number) => withMediaToken(`${API_BASE}/print-log/${id}/thumbnail`),
  6032. clearPrintLog: () =>
  6033. request<{ deleted: number }>('/print-log/', { method: 'DELETE' }),
  6034. deletePrintLogEntry: (id: number) =>
  6035. request<{ status: string; id: number }>(`/print-log/${id}`, { method: 'DELETE' }),
  6036. // Edit failure_reason / status on a single Print Log row (#1687 part 4).
  6037. // Distinct from updateArchive: archives describe the model, log entries
  6038. // describe a single print event. Orphan entries (no archive_id) have no
  6039. // archive to reach through and this is the only path to classify them.
  6040. updatePrintLogEntry: (
  6041. id: number,
  6042. body: { failure_reason?: string | null; status?: string; notes?: string | null },
  6043. ) =>
  6044. request<PrintLogEntry>(`/print-log/${id}`, {
  6045. method: 'PATCH',
  6046. body: JSON.stringify(body),
  6047. }),
  6048. // Settings
  6049. getSettings: () => request<AppSettings>('/settings/'),
  6050. getDefaultSidebarOrder: () => request<{ default_sidebar_order: string }>('/settings/default-sidebar-order'),
  6051. // Public subset of settings for UI rendering — no settings:read required.
  6052. // Used by pages whose users may not have SETTINGS_READ (e.g. operators with
  6053. // only printers:clear_plate). Keep in sync with _UI_PREFERENCE_FIELDS in
  6054. // backend/app/api/routes/settings.py.
  6055. getUiPreferences: () =>
  6056. request<{
  6057. require_plate_clear?: boolean;
  6058. check_printer_firmware?: boolean;
  6059. camera_view_mode?: 'window' | 'embedded';
  6060. time_format?: 'system' | '12h' | '24h';
  6061. date_format?: string;
  6062. drying_presets?: string;
  6063. ams_humidity_thresholds?: string;
  6064. ams_humidity_good?: number;
  6065. ams_humidity_fair?: number;
  6066. ams_temp_good?: number;
  6067. ams_temp_fair?: number;
  6068. bed_cooled_threshold?: number;
  6069. nozzle_temp_presets?: string;
  6070. bed_temp_presets?: string;
  6071. chamber_temp_presets?: string;
  6072. fan_speed_presets?: string;
  6073. }>('/settings/ui-preferences'),
  6074. // Install configuration the app shell needs, for any signed-in user. Separate
  6075. // from getUiPreferences: that endpoint is public because its fields are
  6076. // defaults shipped with the app, while these describe how this deployment is
  6077. // configured. Neither requires settings:read -- which is the point, since a
  6078. // non-admin reading GET /settings gets a 403 and every gate that consults it
  6079. // silently takes its fallback (#3023). Keep in sync with _UI_FLAG_FIELDS in
  6080. // backend/app/api/routes/settings.py.
  6081. getUiFlags: () => request<UiSettings>('/settings/ui-flags'),
  6082. // The two above together: what a page needs from the settings when its user
  6083. // may not read GET /settings. See useUiSettings.
  6084. getUiSettings: async (): Promise<UiSettings> => {
  6085. const [preferences, flags] = await Promise.all([api.getUiPreferences(), api.getUiFlags()]);
  6086. return { ...(preferences as UiSettings), ...flags };
  6087. },
  6088. updateSettings: (data: AppSettingsUpdate) =>
  6089. request<AppSettings>('/settings/', {
  6090. method: 'PUT',
  6091. body: JSON.stringify(data),
  6092. }),
  6093. getMQTTStatus: () => request<MQTTStatus>('/settings/mqtt/status'),
  6094. exportBackup: async (): Promise<{ blob: Blob; filename: string }> => {
  6095. // New simplified backup - complete database + all files
  6096. const url = `${API_BASE}/settings/backup`;
  6097. const headers: Record<string, string> = {};
  6098. if (authToken) {
  6099. headers['Authorization'] = `Bearer ${authToken}`;
  6100. }
  6101. const response = await fetch(url, { headers });
  6102. // Check for errors
  6103. if (!response.ok) {
  6104. const errorText = await response.text();
  6105. throw new Error(errorText || `Backup failed with status ${response.status}`);
  6106. }
  6107. // Get filename from Content-Disposition header
  6108. const contentDisposition = response.headers.get('Content-Disposition');
  6109. let filename = 'bambuddy-backup.zip';
  6110. if (contentDisposition) {
  6111. const match = contentDisposition.match(/filename=([^;]+)/);
  6112. if (match) filename = match[1].trim().replace(/^"(.*)"$/, '$1');
  6113. }
  6114. const blob = await response.blob();
  6115. return { blob, filename };
  6116. },
  6117. importBackup: async (file: File) => {
  6118. // New simplified restore - replaces database + all directories
  6119. const formData = new FormData();
  6120. formData.append('file', file);
  6121. const url = `${API_BASE}/settings/restore`;
  6122. const headers: Record<string, string> = {};
  6123. if (authToken) {
  6124. headers['Authorization'] = `Bearer ${authToken}`;
  6125. }
  6126. const response = await fetch(url, {
  6127. method: 'POST',
  6128. headers,
  6129. body: formData,
  6130. });
  6131. const data = (await response.json().catch(() => null)) as {
  6132. success?: boolean;
  6133. message?: string;
  6134. detail?: string;
  6135. } | null;
  6136. // A refused restore is an HTTPException, so the body is {detail}, not
  6137. // {success, message}. Returning it unmapped made `success` undefined and
  6138. // `message` undefined too — the modal then raised an empty error toast,
  6139. // which is the one case where the reason matters most (e.g. a backup this
  6140. // version cannot import names the columns and both versions).
  6141. if (!response.ok) {
  6142. return { success: false, message: data?.detail ?? data?.message ?? '' };
  6143. }
  6144. return (data ?? { success: false, message: '' }) as {
  6145. success: boolean;
  6146. message: string;
  6147. };
  6148. },
  6149. checkFfmpeg: () =>
  6150. request<{ installed: boolean; path: string | null }>('/settings/check-ffmpeg'),
  6151. getNetworkInterfaces: () =>
  6152. request<{ interfaces: NetworkInterface[] }>('/settings/network-interfaces'),
  6153. // Cloud
  6154. getCloudStatus: () => request<CloudAuthStatus>('/cloud/status'),
  6155. cloudLogin: (email: string, password: string, region = 'global') =>
  6156. request<CloudLoginResponse>('/cloud/login', {
  6157. method: 'POST',
  6158. body: JSON.stringify({ email, password, region }),
  6159. }),
  6160. cloudVerify: (email: string, code: string, tfaKey?: string, region: string = 'global') =>
  6161. request<CloudLoginResponse>('/cloud/verify', {
  6162. method: 'POST',
  6163. body: JSON.stringify({ email, code, tfa_key: tfaKey, region }),
  6164. }),
  6165. cloudSetToken: (access_token: string, region: string = 'global') =>
  6166. request<CloudAuthStatus>('/cloud/token', {
  6167. method: 'POST',
  6168. body: JSON.stringify({ access_token, region }),
  6169. }),
  6170. cloudLogout: () =>
  6171. request<{ success: boolean }>('/cloud/logout', { method: 'POST' }),
  6172. // Orca Cloud — RFC 8628 device pairing. deviceStart() returns a short
  6173. // user_code + verification link; the user approves it in their Orca Cloud
  6174. // settings while the frontend polls devicePoll() every `interval` seconds
  6175. // until the status flips to 'complete' (or a terminal deny/expire).
  6176. orcaCloudDeviceStart: () =>
  6177. request<OrcaDeviceStartResponse>('/orca-cloud/device/start', {
  6178. method: 'POST',
  6179. }),
  6180. orcaCloudDevicePoll: () =>
  6181. request<OrcaDevicePollResponse>('/orca-cloud/device/poll', {
  6182. method: 'POST',
  6183. }),
  6184. orcaCloudStatus: () =>
  6185. request<OrcaAuthStatusResponse>('/orca-cloud/status'),
  6186. orcaCloudLogout: () =>
  6187. request<{ success: boolean }>('/orca-cloud/logout', { method: 'POST' }),
  6188. orcaCloudListProfiles: () =>
  6189. request<OrcaProfileListResponse>('/orca-cloud/profiles'),
  6190. orcaCloudGetProfile: (id: string) =>
  6191. request<OrcaProfileDetail>(`/orca-cloud/profiles/${id}`),
  6192. getCloudSettings: (version = '02.04.00.70') =>
  6193. request<SlicerSettingsResponse>(`/cloud/settings?version=${version}`),
  6194. getBuiltinFilaments: () =>
  6195. request<BuiltinFilament[]>('/cloud/builtin-filaments'),
  6196. getFilamentIdMap: () =>
  6197. request<Record<string, string>>('/cloud/filament-id-map'),
  6198. /** Material-disambiguated hex→name lookup. Same hex can map to different
  6199. * catalog names depending on material (e.g. #000000 is "Charcoal" in PLA
  6200. * Matte but "Black" in PLA Basic). The flat ``/inventory/colors/map``
  6201. * collapses these to the first hit; this endpoint preserves the material
  6202. * context. Returns ``{color_name: null}`` when the hex isn't in the
  6203. * catalog at all. #1718. */
  6204. getColorByMaterial: (hex: string, material?: string) => {
  6205. const params = new URLSearchParams({ hex });
  6206. if (material) params.set('material', material);
  6207. return request<{ color_name: string | null }>(
  6208. `/inventory/colors/by-material?${params.toString()}`,
  6209. );
  6210. },
  6211. // MakerWorld URL-paste import flow.
  6212. getMakerworldStatus: () =>
  6213. request<MakerworldStatus>('/makerworld/status'),
  6214. resolveMakerworldUrl: (url: string) =>
  6215. request<MakerworldResolvedModel>('/makerworld/resolve', {
  6216. method: 'POST',
  6217. body: JSON.stringify({ url }),
  6218. }),
  6219. getMakerworldRecentImports: (limit = 10) =>
  6220. request<MakerworldRecentImport[]>(`/makerworld/recent-imports?limit=${limit}`),
  6221. importMakerworldInstance: (
  6222. model_id: number,
  6223. instance_id: number | null,
  6224. profile_id?: number | null,
  6225. folder_id?: number | null,
  6226. ) =>
  6227. request<MakerworldImportResponse>('/makerworld/import', {
  6228. method: 'POST',
  6229. body: JSON.stringify({
  6230. model_id,
  6231. instance_id: instance_id ?? null,
  6232. profile_id: profile_id ?? null,
  6233. folder_id: folder_id ?? null,
  6234. }),
  6235. }),
  6236. // Manyfold (#1471).
  6237. getManyfoldConfig: () => request<ManyfoldConfig>('/manyfold/config'),
  6238. updateManyfoldConfig: (data: ManyfoldConfigInput) =>
  6239. request<ManyfoldConfig>('/manyfold/config', { method: 'PUT', body: JSON.stringify(data) }),
  6240. deleteManyfoldConfig: () => request<void>('/manyfold/config', { method: 'DELETE' }),
  6241. testManyfoldConfig: (data: ManyfoldConfigInput) =>
  6242. request<{ model_count: number }>('/manyfold/config/test', { method: 'POST', body: JSON.stringify(data) }),
  6243. getManyfoldStatus: () => request<ManyfoldStatus>('/manyfold/status'),
  6244. listManyfoldModels: (query: string, page: number) => {
  6245. const params = new URLSearchParams({ page: String(page) });
  6246. if (query) params.set('q', query);
  6247. return request<ManyfoldModelList>(`/manyfold/models?${params.toString()}`);
  6248. },
  6249. getManyfoldModel: (modelId: string) =>
  6250. request<ManyfoldModel>(`/manyfold/models/${encodeURIComponent(modelId)}`),
  6251. /** The model's preview, or null when it has none. Fetched rather than used
  6252. * as an <img src>: a failing protected <img> makes the app renew its media
  6253. * token, and models without a preview answer 404. */
  6254. getManyfoldPreview: async (modelId: string): Promise<Blob | null> => {
  6255. const headers: Record<string, string> = {};
  6256. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  6257. const response = await fetch(`${API_BASE}/manyfold/models/${encodeURIComponent(modelId)}/preview`, { headers });
  6258. if (!response.ok) return null;
  6259. return response.blob();
  6260. },
  6261. importManyfoldFile: (modelId: string, fileId: string, folderId: number | null) =>
  6262. request<ManyfoldImportResponse>('/manyfold/import', {
  6263. method: 'POST',
  6264. body: JSON.stringify({ model_id: modelId, file_id: fileId, folder_id: folderId }),
  6265. }),
  6266. getCloudSettingDetail: (settingId: string) =>
  6267. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`),
  6268. createCloudSetting: (data: SlicerSettingCreate) =>
  6269. request<SlicerSettingDetail>('/cloud/settings', {
  6270. method: 'POST',
  6271. body: JSON.stringify(data),
  6272. }),
  6273. updateCloudSetting: (settingId: string, data: SlicerSettingUpdate) =>
  6274. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`, {
  6275. method: 'PUT',
  6276. body: JSON.stringify(data),
  6277. }),
  6278. deleteCloudSetting: (settingId: string) =>
  6279. request<SlicerSettingDeleteResponse>(`/cloud/settings/${settingId}`, {
  6280. method: 'DELETE',
  6281. }),
  6282. getCloudFields: (presetType: 'filament' | 'print' | 'process' | 'printer') =>
  6283. request<FieldDefinitionsResponse>(`/cloud/fields/${presetType}`),
  6284. getFilamentInfo: (settingIds: string[]) =>
  6285. request<Record<string, { name: string; k: number | null }>>('/cloud/filament-info', {
  6286. method: 'POST',
  6287. body: JSON.stringify(settingIds),
  6288. }),
  6289. // Smart Plugs
  6290. getSmartPlugs: () => request<SmartPlug[]>('/smart-plugs/'),
  6291. getSmartPlugByPrinter: (printerId: number) => smartPlugBatch(printerId),
  6292. getScriptPlugsByPrinter: (printerId: number) => scriptPlugsBatch(printerId),
  6293. createSmartPlug: (data: SmartPlugCreate) =>
  6294. request<SmartPlug>('/smart-plugs/', {
  6295. method: 'POST',
  6296. body: JSON.stringify(data),
  6297. }),
  6298. updateSmartPlug: (id: number, data: SmartPlugUpdate) =>
  6299. request<SmartPlug>(`/smart-plugs/${id}`, {
  6300. method: 'PATCH',
  6301. body: JSON.stringify(data),
  6302. }),
  6303. deleteSmartPlug: (id: number) =>
  6304. request<void>(`/smart-plugs/${id}`, { method: 'DELETE' }),
  6305. controlSmartPlug: (id: number, action: 'on' | 'off' | 'toggle') =>
  6306. request<{ success: boolean; action: string }>(`/smart-plugs/${id}/control`, {
  6307. method: 'POST',
  6308. body: JSON.stringify({ action }),
  6309. }),
  6310. getSmartPlugStatus: (id: number) =>
  6311. request<SmartPlugStatus>(`/smart-plugs/${id}/status`),
  6312. // plug_id: the saved plug being edited, whose stored password fills in the placeholder.
  6313. testSmartPlugConnection: (ip_address: string, username?: string | null, password?: string | null, plug_id?: number) =>
  6314. request<SmartPlugTestResult>('/smart-plugs/test-connection', {
  6315. method: 'POST',
  6316. body: JSON.stringify({ ip_address, username, password, plug_id }),
  6317. }),
  6318. // Tasmota Discovery (auto-detects network)
  6319. startTasmotaScan: () =>
  6320. request<TasmotaScanStatus>('/smart-plugs/discover/scan', { method: 'POST' }),
  6321. getTasmotaScanStatus: () =>
  6322. request<TasmotaScanStatus>('/smart-plugs/discover/status'),
  6323. stopTasmotaScan: () =>
  6324. request<TasmotaScanStatus>('/smart-plugs/discover/stop', { method: 'POST' }),
  6325. getDiscoveredTasmotaDevices: () =>
  6326. request<DiscoveredTasmotaDevice[]>('/smart-plugs/discover/devices'),
  6327. // Home Assistant Integration
  6328. testHAConnection: (url: string, token: string) =>
  6329. request<HATestConnectionResult>('/smart-plugs/ha/test-connection', {
  6330. method: 'POST',
  6331. body: JSON.stringify({ url, token }),
  6332. }),
  6333. getHAEntities: (search?: string) => {
  6334. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  6335. return request<HAEntity[]>(`/smart-plugs/ha/entities${params}`);
  6336. },
  6337. getHASensorEntities: () =>
  6338. request<HASensorEntity[]>('/smart-plugs/ha/sensors'),
  6339. // Home Assistant sensors bound to a printer (#1148, #448)
  6340. getHASensors: (printerId?: number) =>
  6341. request<PrinterHASensor[]>(`/ha-sensors/${printerId ? `?printer_id=${printerId}` : ''}`),
  6342. getHASensorReadings: (printerId: number) => haSensorReadingsBatch(printerId),
  6343. getBindableHAEntities: (search?: string) => {
  6344. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  6345. return request<HADisplayEntity[]>(`/ha-sensors/entities${params}`);
  6346. },
  6347. createHASensor: (data: PrinterHASensorCreate) =>
  6348. request<PrinterHASensor>('/ha-sensors/', { method: 'POST', body: JSON.stringify(data) }),
  6349. updateHASensor: (id: number, data: PrinterHASensorUpdate) =>
  6350. request<PrinterHASensor>(`/ha-sensors/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  6351. deleteHASensor: (id: number) =>
  6352. request<{ message: string }>(`/ha-sensors/${id}`, { method: 'DELETE' }),
  6353. getLocationHASensors: (locationId?: number) =>
  6354. request<LocationHASensor[]>(`/location-ha-sensors/${locationId ? `?location_id=${locationId}` : ''}`),
  6355. getLocationHASensorReadings: (locationId: number, showOnCard = true) =>
  6356. request<LocationHASensorReading[]>(
  6357. `/location-ha-sensors/by-location/${locationId}/readings?show_on_card=${showOnCard}`
  6358. ),
  6359. getBindableLocationHAEntities: (search?: string) => {
  6360. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  6361. return request<HADisplayEntity[]>(`/location-ha-sensors/entities${params}`);
  6362. },
  6363. createLocationHASensor: (data: LocationHASensorCreate) =>
  6364. request<LocationHASensor>('/location-ha-sensors/', { method: 'POST', body: JSON.stringify(data) }),
  6365. updateLocationHASensor: (id: number, data: LocationHASensorUpdate) =>
  6366. request<LocationHASensor>(`/location-ha-sensors/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  6367. deleteLocationHASensor: (id: number) =>
  6368. request<{ message: string }>(`/location-ha-sensors/${id}`, { method: 'DELETE' }),
  6369. // REST smart plug
  6370. // plug_id: the saved plug being edited, whose stored headers fill in the placeholder.
  6371. testRESTConnection: (url: string, method: string = 'GET', headers?: string | null, plug_id?: number) =>
  6372. request<{ success: boolean; error: string | null }>('/smart-plugs/rest/test-connection', {
  6373. method: 'POST',
  6374. body: JSON.stringify({ url, method, headers, plug_id }),
  6375. }),
  6376. // Print Queue
  6377. getQueue: (printerId?: number, status?: string, targetModel?: string) => {
  6378. const params = new URLSearchParams();
  6379. if (printerId) params.set('printer_id', String(printerId));
  6380. if (status) params.set('status', status);
  6381. if (targetModel) params.set('target_model', targetModel);
  6382. return request<PrintQueueItem[]>(`/queue/?${params}`);
  6383. },
  6384. // History (completed / failed / skipped / cancelled), one page at a time.
  6385. getQueueHistory: (params: QueueHistoryParams) =>
  6386. request<QueueHistoryPage>(`/queue/history?${queueHistorySearch(params)}`),
  6387. // Removes the history matching the same filters, server-side.
  6388. clearQueueHistory: (params: QueueHistoryFilters) =>
  6389. request<{ cleared: number; kept: number }>(`/queue/history/clear?${queueHistorySearch(params)}`, {
  6390. method: 'POST',
  6391. }),
  6392. // One printer's queue as GET /queue/?printer_id= returns it: its own jobs
  6393. // plus the "Any <model>" jobs for its model. Batched across printer cards.
  6394. getPrinterQueue: (printerId: number, status: string) => printerQueueBatch(status)(printerId),
  6395. addToQueue: (data: PrintQueueItemCreate) =>
  6396. request<PrintQueueItem>('/queue/', {
  6397. method: 'POST',
  6398. body: JSON.stringify(data),
  6399. }),
  6400. updateQueueItem: (id: number, data: PrintQueueItemUpdate) =>
  6401. request<PrintQueueItem>(`/queue/${id}`, {
  6402. method: 'PATCH',
  6403. body: JSON.stringify(data),
  6404. }),
  6405. /** `deleted` is false when the item was kept as cancelled instead: it is the
  6406. * last run a batch order could re-queue its plate from (#2960). */
  6407. removeFromQueue: (id: number) =>
  6408. request<{ message: string; deleted: boolean }>(`/queue/${id}`, { method: 'DELETE' }),
  6409. reorderQueue: (items: { id: number; position: number }[]) =>
  6410. request<{ message: string }>('/queue/reorder', {
  6411. method: 'POST',
  6412. body: JSON.stringify({ items }),
  6413. }),
  6414. cancelQueueItem: (id: number) =>
  6415. request<{ message: string }>(`/queue/${id}/cancel`, { method: 'POST' }),
  6416. stopQueueItem: (id: number) =>
  6417. request<{ message: string }>(`/queue/${id}/stop`, { method: 'POST' }),
  6418. /**
  6419. * Start a staged queue item. The backend re-checks live filament deficit
  6420. * for the assigned spool and, when short, returns 409 with a structured
  6421. * payload so the caller can confirm and retry. Pass `skipFilamentCheck`
  6422. * after the user confirms "Print Anyway" (#1496).
  6423. */
  6424. startQueueItem: (id: number, opts?: { skipFilamentCheck?: boolean }) => {
  6425. const qs = opts?.skipFilamentCheck ? '?skip_filament_check=true' : '';
  6426. return request<PrintQueueItem>(`/queue/${id}/start${qs}`, { method: 'POST' });
  6427. },
  6428. /**
  6429. * Clear the `require_previous_success` gate for a printer after the user
  6430. * resolves the failure. Acknowledges any failed/aborted predecessors and
  6431. * restores skipped items whose error_message matches the gate string
  6432. * back to pending. Returns counts so the UI can render a precise toast.
  6433. */
  6434. // A job for any printer of a model waits when the last print failed on every
  6435. // free one; this clears the gate on the model's printers.
  6436. resumeModelQueueAfterFailure: (model: string) =>
  6437. request<{ acknowledged: number; printers: number }>(
  6438. `/queue/model/${encodeURIComponent(model)}/resume`,
  6439. { method: 'POST' },
  6440. ),
  6441. resumeQueueAfterFailure: (printerId: number) =>
  6442. request<{ acknowledged: number; restored: number }>(
  6443. `/queue/printer/${printerId}/resume`,
  6444. { method: 'POST' },
  6445. ),
  6446. bulkUpdateQueue: (data: PrintQueueBulkUpdate) =>
  6447. request<PrintQueueBulkUpdateResponse>('/queue/bulk', {
  6448. method: 'PATCH',
  6449. body: JSON.stringify(data),
  6450. }),
  6451. // Batches
  6452. getBatches: (status?: string) => {
  6453. const params = status ? `?status=${status}` : '';
  6454. return request<PrintBatch[]>(`/queue/batches${params}`);
  6455. },
  6456. cancelBatch: (id: number) =>
  6457. request<{ message: string }>(`/queue/batches/${id}`, { method: 'DELETE' }),
  6458. createBatch: (data: PrintBatchCreate) =>
  6459. request<PrintBatch>('/queue/batches', {
  6460. method: 'POST',
  6461. body: JSON.stringify(data),
  6462. }),
  6463. dispatchBatch: (id: number, data: PrintBatchDispatchRequest = {}) =>
  6464. request<PrintBatch>(`/queue/batches/${id}/dispatch`, {
  6465. method: 'POST',
  6466. body: JSON.stringify(data),
  6467. }),
  6468. ungroupBatch: (id: number) =>
  6469. request<{ ungrouped_count: number; message: string }>(
  6470. `/queue/batches/${id}/ungroup`,
  6471. { method: 'POST' },
  6472. ),
  6473. // K-Profiles
  6474. getKProfiles: (printerId: number, nozzleDiameter = '0.4') =>
  6475. request<KProfilesResponse>(`/printers/${printerId}/kprofiles/?nozzle_diameter=${nozzleDiameter}`),
  6476. setKProfile: (printerId: number, profile: KProfileCreate) =>
  6477. request<KProfileWriteResult>(`/printers/${printerId}/kprofiles/`, {
  6478. method: 'POST',
  6479. body: JSON.stringify(profile),
  6480. }),
  6481. deleteKProfile: (printerId: number, profile: KProfileDelete) =>
  6482. request<KProfileWriteResult>(`/printers/${printerId}/kprofiles/`, {
  6483. method: 'DELETE',
  6484. body: JSON.stringify(profile),
  6485. }),
  6486. setKProfilesBatch: (printerId: number, profiles: KProfileCreate[]) =>
  6487. request<KProfileWriteResult>(`/printers/${printerId}/kprofiles/batch`, {
  6488. method: 'POST',
  6489. body: JSON.stringify(profiles),
  6490. }),
  6491. // Finance
  6492. getMyBalance: () => request<WalletBalance>('/finance/me/balance'),
  6493. getMyTransactions: (limit = 50, offset = 0) =>
  6494. request<WalletTransactionListResponse>(`/finance/me/transactions?limit=${limit}&offset=${offset}`),
  6495. getAllTransactions: (limit = 50, offset = 0, userId?: number) => {
  6496. const params = new URLSearchParams();
  6497. params.set('limit', String(limit));
  6498. params.set('offset', String(offset));
  6499. if (userId !== undefined) params.set('user_id', String(userId));
  6500. return request<WalletTransactionListResponse>(`/finance/transactions?${params.toString()}`);
  6501. },
  6502. deleteTransaction: (transactionId: number) =>
  6503. request<{ status: string }>(`/finance/transactions/${transactionId}`, {
  6504. method: 'DELETE',
  6505. }),
  6506. editTransaction: (transactionId: number, data: TransactionEditRequest) =>
  6507. request<WalletTransaction>(`/finance/transactions/${transactionId}`, {
  6508. method: 'PATCH',
  6509. body: JSON.stringify(data),
  6510. }),
  6511. createManualPrint: (data: ManualPrintRequest) =>
  6512. request<WalletTransaction>('/finance/transactions/manual', {
  6513. method: 'POST',
  6514. body: JSON.stringify(data),
  6515. }),
  6516. getMyCostCenters: () => request<CostCenterSummary[]>('/finance/cost-centers/mine'),
  6517. listCostCenters: (includeInactive = false) =>
  6518. request<CostCenterSummary[]>(`/finance/cost-centers?include_inactive=${includeInactive ? 'true' : 'false'}`),
  6519. createCostCenter: (data: CostCenterCreateRequest) =>
  6520. request<CostCenterSummary>('/finance/cost-centers', {
  6521. method: 'POST',
  6522. body: JSON.stringify(data),
  6523. }),
  6524. updateCostCenter: (costCenterId: number, data: CostCenterUpdateRequest) =>
  6525. request<CostCenterSummary>(`/finance/cost-centers/${costCenterId}`, {
  6526. method: 'PATCH',
  6527. body: JSON.stringify(data),
  6528. }),
  6529. updateCostCenterBudgets: (costCenterId: number, data: CostCenterBudgetUpdateRequest) =>
  6530. request<CostCenterSummary>(`/finance/cost-centers/${costCenterId}/budgets`, {
  6531. method: 'PATCH',
  6532. body: JSON.stringify(data),
  6533. }),
  6534. deleteCostCenter: (costCenterId: number) =>
  6535. request<{ status: string }>(`/finance/cost-centers/${costCenterId}`, {
  6536. method: 'DELETE',
  6537. }),
  6538. getCostCenter: (costCenterId: number) =>
  6539. request<CostCenterDetail>(`/finance/cost-centers/${costCenterId}`),
  6540. upsertCostCenterMember: (costCenterId: number, data: CostCenterMemberRequest) =>
  6541. request<CostCenterMemberResponse>(`/finance/cost-centers/${costCenterId}/members`, {
  6542. method: 'POST',
  6543. body: JSON.stringify(data),
  6544. }),
  6545. removeCostCenterMember: (costCenterId: number, userId: number) =>
  6546. request<{ status: string }>(`/finance/cost-centers/${costCenterId}/members/${userId}`, {
  6547. method: 'DELETE',
  6548. }),
  6549. depositUserBalance: (userId: number, data: WalletAdjustmentRequest) =>
  6550. request<WalletAdjustmentResponse>(`/finance/users/${userId}/deposit`, {
  6551. method: 'POST',
  6552. body: JSON.stringify(data),
  6553. }),
  6554. withdrawUserBalance: (userId: number, data: WalletAdjustmentRequest) =>
  6555. request<WalletAdjustmentResponse>(`/finance/users/${userId}/withdraw`, {
  6556. method: 'POST',
  6557. body: JSON.stringify(data),
  6558. }),
  6559. rebuildBalanceLedger: () =>
  6560. request<{ status: string }>('/finance/rebuild-balance-ledger', {
  6561. method: 'POST',
  6562. }),
  6563. // K-Profile Notes (stored locally, not on printer)
  6564. getKProfileNotes: (printerId: number) =>
  6565. request<KProfileNotesResponse>(`/printers/${printerId}/kprofiles/notes`),
  6566. setKProfileNote: (printerId: number, settingId: string, note: string) =>
  6567. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/notes`, {
  6568. method: 'PUT',
  6569. body: JSON.stringify({ setting_id: settingId, note }),
  6570. }),
  6571. // Slot Preset Mappings
  6572. getSlotPresets: (printerId: number) => slotPresetsBatch(printerId),
  6573. saveSlotPreset: (printerId: number, amsId: number, trayId: number, presetId: string, presetName: string, presetSource = 'cloud', trayInfoIdx?: string) =>
  6574. request<SlotPresetMapping>(`/printers/${printerId}/slot-presets/${amsId}/${trayId}?preset_id=${encodeURIComponent(presetId)}&preset_name=${encodeURIComponent(presetName)}&preset_source=${encodeURIComponent(presetSource)}${trayInfoIdx ? `&tray_info_idx=${encodeURIComponent(trayInfoIdx)}` : ''}`, {
  6575. method: 'PUT',
  6576. }),
  6577. // AMS Labels (user-defined friendly names)
  6578. getAmsLabels: (printerId: number) => amsLabelsBatch(printerId),
  6579. saveAmsLabel: (printerId: number, amsId: number, label: string, amsSerial = '') =>
  6580. request<{ ams_id: number; label: string }>(
  6581. `/printers/${printerId}/ams-labels/${amsId}`,
  6582. {
  6583. method: 'PUT',
  6584. body: JSON.stringify({ label, ams_serial: amsSerial }),
  6585. }
  6586. ),
  6587. deleteAmsLabel: (printerId: number, amsId: number, amsSerial = '') =>
  6588. request<{ success: boolean }>(`/printers/${printerId}/ams-labels/${amsId}?ams_serial=${encodeURIComponent(amsSerial)}`, {
  6589. method: 'DELETE',
  6590. }),
  6591. configureAmsSlot: (
  6592. printerId: number,
  6593. amsId: number,
  6594. trayId: number,
  6595. config: {
  6596. tray_info_idx: string;
  6597. tray_type: string;
  6598. tray_sub_brands: string;
  6599. tray_color: string;
  6600. nozzle_temp_min: number;
  6601. nozzle_temp_max: number;
  6602. cali_idx: number;
  6603. nozzle_diameter: string;
  6604. setting_id?: string;
  6605. kprofile_filament_id?: string;
  6606. kprofile_setting_id?: string;
  6607. k_value?: number;
  6608. // Orca Cloud profile the slot is set to; the backend looks up its
  6609. // filament id when tray_info_idx is empty (#3216).
  6610. orca_profile_id?: string;
  6611. }
  6612. ) => {
  6613. const params = new URLSearchParams({
  6614. tray_info_idx: config.tray_info_idx,
  6615. tray_type: config.tray_type,
  6616. tray_sub_brands: config.tray_sub_brands,
  6617. tray_color: config.tray_color,
  6618. nozzle_temp_min: config.nozzle_temp_min.toString(),
  6619. nozzle_temp_max: config.nozzle_temp_max.toString(),
  6620. cali_idx: config.cali_idx.toString(),
  6621. nozzle_diameter: config.nozzle_diameter,
  6622. });
  6623. if (config.setting_id) {
  6624. params.set('setting_id', config.setting_id);
  6625. }
  6626. if (config.kprofile_filament_id) {
  6627. params.set('kprofile_filament_id', config.kprofile_filament_id);
  6628. }
  6629. if (config.kprofile_setting_id) {
  6630. params.set('kprofile_setting_id', config.kprofile_setting_id);
  6631. }
  6632. if (config.k_value !== undefined && config.k_value > 0) {
  6633. params.set('k_value', config.k_value.toString());
  6634. }
  6635. if (config.orca_profile_id) {
  6636. params.set('orca_profile_id', config.orca_profile_id);
  6637. }
  6638. return request<{
  6639. success: boolean;
  6640. message: string;
  6641. // The filament id the slot was actually given.
  6642. tray_info_idx?: string;
  6643. // Why an Orca profile went out as the generic for its material, or "".
  6644. orca_fallback_reason?: '' | 'no_filament_id' | 'lookup_failed' | 'no_permission';
  6645. /** A manual K value could not be sent; the filament setting was. */
  6646. k_value_unsent?: boolean;
  6647. }>(
  6648. `/printers/${printerId}/slots/${amsId}/${trayId}/configure?${params}`,
  6649. { method: 'POST' }
  6650. );
  6651. },
  6652. resetAmsSlot: (printerId: number, amsId: number, trayId: number) =>
  6653. request<{ success: boolean; message: string }>(
  6654. `/printers/${printerId}/ams/${amsId}/tray/${trayId}/reset`,
  6655. { method: 'POST' }
  6656. ),
  6657. // Notification Providers
  6658. getNotificationProviders: () => request<NotificationProvider[]>('/notifications/'),
  6659. createNotificationProvider: (data: NotificationProviderCreate) =>
  6660. request<NotificationProvider>('/notifications/', {
  6661. method: 'POST',
  6662. body: JSON.stringify(data),
  6663. }),
  6664. updateNotificationProvider: (id: number, data: NotificationProviderUpdate) =>
  6665. request<NotificationProvider>(`/notifications/${id}`, {
  6666. method: 'PATCH',
  6667. body: JSON.stringify(data),
  6668. }),
  6669. deleteNotificationProvider: (id: number) =>
  6670. request<{ message: string }>(`/notifications/${id}`, { method: 'DELETE' }),
  6671. testNotificationProvider: (id: number) =>
  6672. request<NotificationTestResponse>(`/notifications/${id}/test`, { method: 'POST' }),
  6673. testNotificationConfig: (data: NotificationTestRequest) =>
  6674. request<NotificationTestResponse>('/notifications/test-config', {
  6675. method: 'POST',
  6676. body: JSON.stringify(data),
  6677. }),
  6678. testAllNotificationProviders: () =>
  6679. request<{
  6680. tested: number;
  6681. success: number;
  6682. failed: number;
  6683. results: Array<{
  6684. provider_id: number;
  6685. provider_name: string;
  6686. provider_type: string;
  6687. success: boolean;
  6688. message: string;
  6689. }>;
  6690. }>('/notifications/test-all', { method: 'POST' }),
  6691. // Notification Templates
  6692. getNotificationTemplates: () => request<NotificationTemplate[]>('/notification-templates'),
  6693. updateNotificationTemplate: (id: number, data: NotificationTemplateUpdate) =>
  6694. request<NotificationTemplate>(`/notification-templates/${id}`, {
  6695. method: 'PUT',
  6696. body: JSON.stringify(data),
  6697. }),
  6698. resetNotificationTemplate: (id: number) =>
  6699. request<NotificationTemplate>(`/notification-templates/${id}/reset`, {
  6700. method: 'POST',
  6701. }),
  6702. getTemplateVariables: () => request<EventVariablesResponse[]>('/notification-templates/variables'),
  6703. previewTemplate: (data: TemplatePreviewRequest) =>
  6704. request<TemplatePreviewResponse>('/notification-templates/preview', {
  6705. method: 'POST',
  6706. body: JSON.stringify(data),
  6707. }),
  6708. // Notification Logs
  6709. getNotificationLogs: (params?: {
  6710. limit?: number;
  6711. offset?: number;
  6712. provider_id?: number;
  6713. event_type?: string;
  6714. success?: boolean;
  6715. days?: number;
  6716. }) => {
  6717. const searchParams = new URLSearchParams();
  6718. if (params?.limit) searchParams.set('limit', String(params.limit));
  6719. if (params?.offset) searchParams.set('offset', String(params.offset));
  6720. if (params?.provider_id) searchParams.set('provider_id', String(params.provider_id));
  6721. if (params?.event_type) searchParams.set('event_type', params.event_type);
  6722. if (params?.success !== undefined) searchParams.set('success', String(params.success));
  6723. if (params?.days) searchParams.set('days', String(params.days));
  6724. return request<NotificationLogEntry[]>(`/notifications/logs?${searchParams}`);
  6725. },
  6726. getNotificationLogStats: (days = 7) =>
  6727. request<NotificationLogStats>(`/notifications/logs/stats?days=${days}`),
  6728. clearNotificationLogs: (olderThanDays = 30) =>
  6729. request<{ deleted: number; message: string }>(
  6730. `/notifications/logs?older_than_days=${olderThanDays}`,
  6731. { method: 'DELETE' }
  6732. ),
  6733. // Spoolman Integration
  6734. getSpoolmanStatus: () => request<SpoolmanStatus>('/spoolman/status'),
  6735. migrateSpoolmanTags: (dryRun: boolean) =>
  6736. request<SpoolmanTagMigrationReport>(`/spoolman/inventory/tags/migrate?dry_run=${dryRun}`, {
  6737. method: 'POST',
  6738. }),
  6739. connectSpoolman: () =>
  6740. request<{ success: boolean; message: string }>('/spoolman/connect', {
  6741. method: 'POST',
  6742. }),
  6743. syncPrinterAms: (printerId: number) =>
  6744. request<SpoolmanSyncResult>(`/spoolman/sync/${printerId}`, {
  6745. method: 'POST',
  6746. }),
  6747. syncAllPrintersAms: () =>
  6748. request<SpoolmanSyncResult>('/spoolman/sync-all', {
  6749. method: 'POST',
  6750. }),
  6751. getSpoolmanInventoryFilaments: () =>
  6752. request<SpoolmanFilamentEntry[]>('/spoolman/inventory/filaments'),
  6753. getUnlinkedSpools: () =>
  6754. request<UnlinkedSpool[]>('/spoolman/spools/unlinked'),
  6755. getLinkedSpools: () =>
  6756. request<LinkedSpoolsMap>('/spoolman/spools/linked'),
  6757. linkSpool: (
  6758. spoolId: number,
  6759. context: {
  6760. spoolTag: string;
  6761. printerId: number;
  6762. amsId: number;
  6763. trayId: number;
  6764. }
  6765. ) =>
  6766. request<{ success: boolean; message: string }>(`/spoolman/spools/${spoolId}/link`, {
  6767. method: 'POST',
  6768. body: JSON.stringify({
  6769. spool_tag: context.spoolTag,
  6770. printer_id: context.printerId,
  6771. ams_id: context.amsId,
  6772. tray_id: context.trayId,
  6773. }),
  6774. }),
  6775. unlinkSpool: (spoolId: number) =>
  6776. request<{ success: boolean; message: string }>(`/spoolman/spools/${spoolId}/unlink`, {
  6777. method: 'POST',
  6778. }),
  6779. createSpoolmanSpoolFromSlot: (data: { printer_id: number; ams_id: number; tray_id: number }) =>
  6780. request<{ success: boolean; spool_id: number | null }>(`/spoolman/spools/from-slot`, {
  6781. method: 'POST',
  6782. body: JSON.stringify(data),
  6783. }),
  6784. createSpoolFromSlot: (data: { printer_id: number; ams_id: number; tray_id: number }) =>
  6785. request<InventorySpool>(`/inventory/spools/from-slot`, {
  6786. method: 'POST',
  6787. body: JSON.stringify(data),
  6788. }),
  6789. getSpoolmanSettings: () =>
  6790. 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'),
  6791. 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; }) =>
  6792. 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', {
  6793. method: 'PUT',
  6794. body: JSON.stringify(data),
  6795. }),
  6796. // Inventory
  6797. getSpools: (includeArchived = false) =>
  6798. request<InventorySpool[]>(`/inventory/spools?include_archived=${includeArchived}`),
  6799. getSpool: (id: number) => request<InventorySpool>(`/inventory/spools/${id}`),
  6800. createSpool: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>) =>
  6801. request<InventorySpool>('/inventory/spools', {
  6802. method: 'POST',
  6803. body: JSON.stringify(data),
  6804. }),
  6805. bulkCreateSpools: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>, quantity: number) =>
  6806. request<InventorySpool[]>('/inventory/spools/bulk', {
  6807. method: 'POST',
  6808. body: JSON.stringify({ spool: data, quantity }),
  6809. }),
  6810. // ── CSV import/export (#1576) ────────────────────────────────────────────
  6811. // dry_run=true → preview (no write); omitted → real import. Both share one
  6812. // multipart upload helper; see `uploadSpoolsCsv` below.
  6813. importSpoolsCsvPreview: (file: File): Promise<CsvImportPreview> => uploadSpoolsCsv<CsvImportPreview>(file, true),
  6814. importSpoolsCsv: (file: File): Promise<CsvImportResult> => uploadSpoolsCsv<CsvImportResult>(file, false),
  6815. exportSpoolsCsv: async (): Promise<void> => {
  6816. const headers: Record<string, string> = {};
  6817. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  6818. const response = await fetch(`${API_BASE}/inventory/spools/export`, { headers });
  6819. if (!response.ok) {
  6820. const error = await response.json().catch(() => ({}));
  6821. throw new Error(error.detail || `HTTP ${response.status}`);
  6822. }
  6823. const disposition = response.headers.get('Content-Disposition');
  6824. const filename = parseContentDispositionFilename(disposition) || 'bambuddy_inventory.csv';
  6825. const blob = await response.blob();
  6826. const url = window.URL.createObjectURL(blob);
  6827. const a = document.createElement('a');
  6828. a.href = url;
  6829. a.download = filename;
  6830. document.body.appendChild(a);
  6831. a.click();
  6832. document.body.removeChild(a);
  6833. window.URL.revokeObjectURL(url);
  6834. },
  6835. updateSpool: (id: number, data: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  6836. request<InventorySpool>(`/inventory/spools/${id}`, {
  6837. method: 'PATCH',
  6838. body: JSON.stringify(data),
  6839. }),
  6840. deleteSpool: (id: number) =>
  6841. request<{ status: string }>(`/inventory/spools/${id}`, { method: 'DELETE' }),
  6842. archiveSpool: (id: number) =>
  6843. request<InventorySpool>(`/inventory/spools/${id}/archive`, { method: 'POST' }),
  6844. restoreSpool: (id: number) =>
  6845. request<InventorySpool>(`/inventory/spools/${id}/restore`, { method: 'POST' }),
  6846. resetSpoolConsumedCounter: (id: number) =>
  6847. request<InventorySpool>(`/inventory/spools/${id}/reset-consumed-counter`, { method: 'POST' }),
  6848. bulkResetSpoolConsumedCounter: (spoolIds: number[]) =>
  6849. request<{ reset: number; not_found?: number[]; errors?: Array<{ id: number; status: number; detail: string }> }>(`/inventory/spools/reset-consumed-counter-bulk`, {
  6850. method: 'POST',
  6851. body: JSON.stringify({ spool_ids: spoolIds }),
  6852. }),
  6853. bulkUpdateSpools: (ids: number[], update: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  6854. request<{ updated: number; not_found: number[] }>(`/inventory/spools/bulk-update`, {
  6855. method: 'POST',
  6856. body: JSON.stringify({ ids, update }),
  6857. }),
  6858. bulkDeleteSpools: (ids: number[]) =>
  6859. request<{ deleted: number; not_found: number[] }>(`/inventory/spools/bulk-delete`, {
  6860. method: 'POST',
  6861. body: JSON.stringify({ ids }),
  6862. }),
  6863. bulkArchiveSpools: (ids: number[]) =>
  6864. request<{ archived: number; already_archived: number[]; not_found: number[] }>(`/inventory/spools/bulk-archive`, {
  6865. method: 'POST',
  6866. body: JSON.stringify({ ids }),
  6867. }),
  6868. bulkRestoreSpools: (ids: number[]) =>
  6869. request<{ restored: number; already_active: number[]; not_found: number[] }>(`/inventory/spools/bulk-restore`, {
  6870. method: 'POST',
  6871. body: JSON.stringify({ ids }),
  6872. }),
  6873. getSpoolKProfiles: (spoolId: number) =>
  6874. request<SpoolKProfile[]>(`/inventory/spools/${spoolId}/k-profiles`),
  6875. saveSpoolKProfiles: (spoolId: number, profiles: SpoolKProfileInput[]) =>
  6876. request<SpoolKProfile[]>(`/inventory/spools/${spoolId}/k-profiles`, {
  6877. method: 'PUT',
  6878. body: JSON.stringify(profiles),
  6879. }),
  6880. /**
  6881. * What the spool assigned to this slot is configured to use *here* -- its
  6882. * per-printer-model filament preset and the K profile for this slot's hotend.
  6883. * Nulls when the slot holds no known spool.
  6884. */
  6885. getSlotSpoolDefaults: (printerId: number, amsId: number, trayId: number) =>
  6886. request<SlotSpoolDefaults>(`/printers/${printerId}/slots/${amsId}/${trayId}/spool-defaults`),
  6887. getSpoolFilamentPresets: (spoolId: number) =>
  6888. request<SpoolFilamentPreset[]>(`/inventory/spools/${spoolId}/filament-presets`),
  6889. saveSpoolFilamentPresets: (spoolId: number, presets: SpoolFilamentPresetInput[]) =>
  6890. request<SpoolFilamentPreset[]>(`/inventory/spools/${spoolId}/filament-presets`, {
  6891. method: 'PUT',
  6892. body: JSON.stringify(presets),
  6893. }),
  6894. getProfileDefaults: () => request<ProfileDefault[]>('/inventory/profile-defaults'),
  6895. resolveProfileDefault: (key: ProfileDefaultKey) => {
  6896. const params = new URLSearchParams({
  6897. brand: key.brand,
  6898. material: key.material,
  6899. subtype: key.subtype,
  6900. color_name: key.color_name,
  6901. });
  6902. return request<ResolvedProfileDefault | null>(`/inventory/profile-defaults/resolve?${params}`);
  6903. },
  6904. saveProfileDefault: (data: ProfileDefaultInput) =>
  6905. request<ProfileDefault>('/inventory/profile-defaults', {
  6906. method: 'PUT',
  6907. body: JSON.stringify(data),
  6908. }),
  6909. deleteProfileDefault: (defaultId: number) =>
  6910. request<{ status: string }>(`/inventory/profile-defaults/${defaultId}`, { method: 'DELETE' }),
  6911. /** Fills in what active spools of the default's product lack; the inventory mode picks the route. */
  6912. applyProfileDefault: (defaultId: number, spoolmanMode: boolean) =>
  6913. request<{ updated: number }>(
  6914. spoolmanMode
  6915. ? `/spoolman/inventory/profile-defaults/${defaultId}/apply`
  6916. : `/inventory/profile-defaults/${defaultId}/apply`,
  6917. { method: 'POST' },
  6918. ),
  6919. getAssignments: (printerId?: number) =>
  6920. request<SpoolAssignment[]>(`/inventory/assignments${printerId ? `?printer_id=${printerId}` : ''}`),
  6921. // move: the spool also leaves any other slot it is in, in the same
  6922. // transaction (#1574) -- for a scanned spool, the one in the user's hand.
  6923. assignSpool: (data: { spool_id: number; printer_id: number; ams_id: number; tray_id: number; move?: boolean }) =>
  6924. request<SpoolAssignment>('/inventory/assignments', {
  6925. method: 'POST',
  6926. body: JSON.stringify(data),
  6927. }),
  6928. unassignSpool: (printerId: number, amsId: number, trayId: number) =>
  6929. request<{ status: string }>(`/inventory/assignments/${printerId}/${amsId}/${trayId}`, { method: 'DELETE' }),
  6930. // ── Spool label printing (#809) ──────────────────────────────────────────
  6931. // The print endpoints return a PDF, a PNG, or a ZIP of PNGs (#2981); the
  6932. // preview endpoints one PNG. Callers get the Blob and decide what to do.
  6933. printSpoolLabels: (data: PrintSpoolLabelsRequest): Promise<Blob> =>
  6934. postForBlob('/inventory/labels', data),
  6935. printSpoolmanSpoolLabels: (data: PrintSpoolLabelsRequest): Promise<Blob> =>
  6936. postForBlob('/spoolman/labels', data),
  6937. previewSpoolLabel: (data: PreviewSpoolLabelRequest, signal?: AbortSignal): Promise<Blob> =>
  6938. postForBlob('/inventory/labels/preview', data, signal),
  6939. previewSpoolmanSpoolLabel: (data: PreviewSpoolLabelRequest, signal?: AbortSignal): Promise<Blob> =>
  6940. postForBlob('/spoolman/labels/preview', data, signal),
  6941. getLabelTemplates: () => request<SavedLabelTemplate[]>('/label-templates'),
  6942. createLabelTemplate: (data: { name: string; layout: LabelSheetLayout }) =>
  6943. request<SavedLabelTemplate>('/label-templates', { method: 'POST', body: JSON.stringify(data) }),
  6944. updateLabelTemplate: (id: number, data: { name: string; layout: LabelSheetLayout }) =>
  6945. request<SavedLabelTemplate>(`/label-templates/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  6946. deleteLabelTemplate: (id: number) => request<void>(`/label-templates/${id}`, { method: 'DELETE' }),
  6947. getSpoolCatalog: () =>
  6948. request<SpoolCatalogEntry[]>('/inventory/catalog'),
  6949. addCatalogEntry: (data: { name: string; weight: number }) =>
  6950. request<SpoolCatalogEntry>('/inventory/catalog', { method: 'POST', body: JSON.stringify(data) }),
  6951. updateCatalogEntry: (id: number, data: { name: string; weight: number }) =>
  6952. request<SpoolCatalogEntry>(`/inventory/catalog/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  6953. deleteCatalogEntry: (id: number) =>
  6954. request<{ status: string }>(`/inventory/catalog/${id}`, { method: 'DELETE' }),
  6955. bulkDeleteCatalogEntries: (ids: number[]) =>
  6956. request<{ deleted: number }>('/inventory/catalog/bulk-delete', { method: 'POST', body: JSON.stringify({ ids }) }),
  6957. resetSpoolCatalog: () =>
  6958. request<{ status: string }>('/inventory/catalog/reset', { method: 'POST' }),
  6959. // ── Suppliers (#2988) — inventory master data, Locations pattern ─────────
  6960. getSuppliers: () =>
  6961. request<Supplier[]>('/inventory/suppliers'),
  6962. createSupplier: (data: SupplierInput) =>
  6963. request<Supplier>('/inventory/suppliers', { method: 'POST', body: JSON.stringify(data) }),
  6964. updateSupplier: (id: number, data: Partial<SupplierInput>) =>
  6965. request<Supplier>(`/inventory/suppliers/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  6966. deleteSupplier: (id: number) =>
  6967. request<{ status: string }>(`/inventory/suppliers/${id}`, { method: 'DELETE' }),
  6968. setSpoolSuppliers: (spoolId: number, links: SpoolSupplierLinkInput[]) =>
  6969. request<SpoolSupplierLink[]>(`/inventory/spools/${spoolId}/suppliers`, {
  6970. method: 'PUT',
  6971. body: JSON.stringify(links),
  6972. }),
  6973. // Spoolman parity: the assignment rows live Bambuddy-side, keyed by the
  6974. // remote spool id — same request/response shape as the built-in inventory.
  6975. setSpoolmanSpoolSuppliers: (spoolmanSpoolId: number, links: SpoolSupplierLinkInput[]) =>
  6976. request<SpoolSupplierLink[]>(`/spoolman/inventory/spools/${spoolmanSpoolId}/suppliers`, {
  6977. method: 'PUT',
  6978. body: JSON.stringify(links),
  6979. }),
  6980. // date_from/date_to scope the usage half only, so the widget can follow the
  6981. // dashboard timeframe; stock stays point-in-time.
  6982. getSupplierStats: (dateFrom?: string, dateTo?: string) => {
  6983. const params = new URLSearchParams();
  6984. if (dateFrom) params.set('date_from', dateFrom);
  6985. if (dateTo) params.set('date_to', dateTo);
  6986. addDayZone(params);
  6987. const qs = params.toString();
  6988. return request<SupplierStats[]>(`/inventory/stats/suppliers${qs ? `?${qs}` : ''}`);
  6989. },
  6990. getLocations: () =>
  6991. request<StorageLocation[]>('/inventory/locations'),
  6992. createLocation: (data: { name: string; identifier?: string | null }) =>
  6993. request<StorageLocation>('/inventory/locations', { method: 'POST', body: JSON.stringify(data) }),
  6994. updateLocation: (id: number, data: { name?: string; identifier?: string | null }) =>
  6995. request<StorageLocation>(`/inventory/locations/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  6996. deleteLocation: (id: number) =>
  6997. request<{ status: string }>(`/inventory/locations/${id}`, { method: 'DELETE' }),
  6998. getColorCatalog: () =>
  6999. request<ColorCatalogEntry[]>('/inventory/colors'),
  7000. /** Flat hex→name map, plus the names collapsing it loses. ``by_material`` is
  7001. * keyed ``"<material>|<hex>"`` and only carries entries that differ from the
  7002. * flat answer (e.g. ``"pla matte|ffffff" -> "Ivory White"`` where the flat
  7003. * map says "Jade White"). #2875. */
  7004. getColorNameMap: () =>
  7005. request<{
  7006. colors: Record<string, string>;
  7007. by_material?: Record<string, string>;
  7008. bambu?: BambuCatalogColor[];
  7009. preset_materials?: Record<string, string>;
  7010. }>('/inventory/colors/map'),
  7011. addColorEntry: (data: {
  7012. manufacturer: string;
  7013. color_name: string;
  7014. hex_color: string;
  7015. material: string | null;
  7016. extra_colors?: string | null;
  7017. effect_type?: string | null;
  7018. }) =>
  7019. request<ColorCatalogEntry>('/inventory/colors', { method: 'POST', body: JSON.stringify(data) }),
  7020. updateColorEntry: (
  7021. id: number,
  7022. data: {
  7023. manufacturer: string;
  7024. color_name: string;
  7025. hex_color: string;
  7026. material: string | null;
  7027. extra_colors?: string | null;
  7028. effect_type?: string | null;
  7029. },
  7030. ) => request<ColorCatalogEntry>(`/inventory/colors/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  7031. deleteColorEntry: (id: number) =>
  7032. request<{ status: string }>(`/inventory/colors/${id}`, { method: 'DELETE' }),
  7033. bulkDeleteColorEntries: (ids: number[]) =>
  7034. request<{ deleted: number }>('/inventory/colors/bulk-delete', { method: 'POST', body: JSON.stringify({ ids }) }),
  7035. resetColorCatalog: () =>
  7036. request<{ status: string }>('/inventory/colors/reset', { method: 'POST' }),
  7037. searchColors: (manufacturer?: string, material?: string) =>
  7038. request<ColorCatalogEntry[]>(`/inventory/colors/search?${manufacturer ? `manufacturer=${encodeURIComponent(manufacturer)}` : ''}${manufacturer && material ? '&' : ''}${material ? `material=${encodeURIComponent(material)}` : ''}`),
  7039. linkTagToSpool: (spoolId: number, data: { tag_uid?: string; tray_uuid?: string; tag_type?: string; data_origin?: string }) =>
  7040. request<InventorySpool>(`/inventory/spools/${spoolId}/link-tag`, {
  7041. method: 'PATCH',
  7042. body: JSON.stringify(data),
  7043. }),
  7044. // Per-material-number inventory aggregate (#2870). The date range narrows
  7045. // the usage half only — stock is point-in-time.
  7046. getMaterialNumberStats: (options?: { dateFrom?: string; dateTo?: string }) => {
  7047. const params = new URLSearchParams();
  7048. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  7049. if (options?.dateTo) params.set('date_to', options.dateTo);
  7050. addDayZone(params);
  7051. const qs = params.toString();
  7052. return request<MaterialNumberStats[]>(`/inventory/stats/material-numbers${qs ? `?${qs}` : ''}`);
  7053. },
  7054. getSpoolUsageHistory: (spoolId: number, limit = 50) =>
  7055. request<SpoolUsageRecord[]>(`/inventory/spools/${spoolId}/usage?limit=${limit}`),
  7056. // One inventory's at a time: ``spoolman`` for the Spoolman spools' (#3407).
  7057. getAllUsageHistory: (limit = 100, printerId?: number, spoolman = false) =>
  7058. request<SpoolUsageRecord[]>(
  7059. `/inventory/usage?limit=${limit}${printerId ? `&printer_id=${printerId}` : ''}${spoolman ? '&spoolman=true' : ''}`,
  7060. ),
  7061. getSpoolmanSpoolUsageHistory: (spoolId: number, limit = 50) =>
  7062. request<SpoolUsageRecord[]>(`/spoolman/inventory/spools/${spoolId}/usage?limit=${limit}`),
  7063. clearSpoolmanSpoolUsageHistory: (spoolId: number) =>
  7064. request<{ status: string }>(`/spoolman/inventory/spools/${spoolId}/usage`, { method: 'DELETE' }),
  7065. clearSpoolUsageHistory: (spoolId: number) =>
  7066. request<{ status: string }>(`/inventory/spools/${spoolId}/usage`, { method: 'DELETE' }),
  7067. syncWeightsFromAms: () =>
  7068. request<{ synced: number; skipped: number; printing?: number }>('/inventory/sync-ams-weights', { method: 'POST' }),
  7069. getSkuSettings: () =>
  7070. request<FilamentSkuSettings[]>('/inventory/sku-settings'),
  7071. upsertSkuSettings: (data: Omit<FilamentSkuSettings, 'id'>) =>
  7072. request<FilamentSkuSettings>('/inventory/sku-settings', {
  7073. method: 'POST',
  7074. body: JSON.stringify(data),
  7075. }),
  7076. getShoppingList: () =>
  7077. request<ShoppingListItem[]>('/inventory/shopping-list'),
  7078. addToShoppingList: (data: ShoppingListItemCreate) =>
  7079. request<ShoppingListItem>('/inventory/shopping-list', {
  7080. method: 'POST',
  7081. body: JSON.stringify(data),
  7082. }),
  7083. removeFromShoppingList: (id: number) =>
  7084. request<{ status: string }>(`/inventory/shopping-list/${id}`, { method: 'DELETE' }),
  7085. clearShoppingList: () =>
  7086. request<{ deleted: number }>('/inventory/shopping-list', { method: 'DELETE' }),
  7087. updateShoppingListStatus: (id: number, status: 'pending' | 'purchased' | 'received') =>
  7088. request<ShoppingListItem>(`/inventory/shopping-list/${id}/status`, {
  7089. method: 'PATCH',
  7090. body: JSON.stringify({ status }),
  7091. }),
  7092. getFilamentPresets: () =>
  7093. request<SlicerSetting[]>('/cloud/filaments'),
  7094. // Spoolman Inventory proxy (unified UI when Spoolman is enabled)
  7095. getSpoolmanInventorySpools: (includeArchived = false) =>
  7096. request<InventorySpool[]>(`/spoolman/inventory/spools?include_archived=${includeArchived}`),
  7097. getSpoolmanInventorySpool: (id: number) =>
  7098. request<InventorySpool>(`/spoolman/inventory/spools/${id}`),
  7099. createSpoolmanInventorySpool: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>) =>
  7100. request<InventorySpool>('/spoolman/inventory/spools', {
  7101. method: 'POST',
  7102. body: JSON.stringify(data),
  7103. }),
  7104. bulkCreateSpoolmanInventorySpools: (
  7105. data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>,
  7106. quantity: number,
  7107. ) =>
  7108. request<SpoolmanBulkCreateResult | InventorySpool[]>('/spoolman/inventory/spools/bulk', {
  7109. method: 'POST',
  7110. body: JSON.stringify({ spool: data, quantity }),
  7111. }),
  7112. updateSpoolmanInventorySpool: (
  7113. id: number,
  7114. data: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>,
  7115. ) =>
  7116. request<InventorySpool>(`/spoolman/inventory/spools/${id}`, {
  7117. method: 'PATCH',
  7118. body: JSON.stringify(data),
  7119. }),
  7120. deleteSpoolmanInventorySpool: (id: number) =>
  7121. request<{ status: string }>(`/spoolman/inventory/spools/${id}`, { method: 'DELETE' }),
  7122. archiveSpoolmanInventorySpool: (id: number) =>
  7123. request<InventorySpool>(`/spoolman/inventory/spools/${id}/archive`, { method: 'POST' }),
  7124. restoreSpoolmanInventorySpool: (id: number) =>
  7125. request<InventorySpool>(`/spoolman/inventory/spools/${id}/restore`, { method: 'POST' }),
  7126. resetSpoolmanInventorySpoolConsumedCounter: (id: number) =>
  7127. request<InventorySpool>(`/spoolman/inventory/spools/${id}/reset-consumed-counter`, { method: 'POST' }),
  7128. bulkResetSpoolmanInventorySpoolConsumedCounter: (spoolIds: number[]) =>
  7129. request<{ reset: number; not_found?: number[]; errors?: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/reset-consumed-counter-bulk`, {
  7130. method: 'POST',
  7131. body: JSON.stringify({ spool_ids: spoolIds }),
  7132. }),
  7133. bulkUpdateSpoolmanInventorySpools: (ids: number[], update: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  7134. request<{ updated: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-update`, {
  7135. method: 'POST',
  7136. body: JSON.stringify({ ids, update }),
  7137. }),
  7138. bulkDeleteSpoolmanInventorySpools: (ids: number[]) =>
  7139. request<{ deleted: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-delete`, {
  7140. method: 'POST',
  7141. body: JSON.stringify({ ids }),
  7142. }),
  7143. bulkArchiveSpoolmanInventorySpools: (ids: number[]) =>
  7144. request<{ archived: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-archive`, {
  7145. method: 'POST',
  7146. body: JSON.stringify({ ids }),
  7147. }),
  7148. bulkRestoreSpoolmanInventorySpools: (ids: number[]) =>
  7149. request<{ restored: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-restore`, {
  7150. method: 'POST',
  7151. body: JSON.stringify({ ids }),
  7152. }),
  7153. linkTagToSpoolmanSpool: (spoolId: number, data: { tag_uid?: string; tray_uuid?: string }) =>
  7154. request<InventorySpool>(`/spoolman/inventory/spools/${spoolId}/tag`, {
  7155. method: 'PATCH',
  7156. body: JSON.stringify(data),
  7157. }),
  7158. syncSpoolmanSpoolWeight: (spoolId: number, weightGrams: number) =>
  7159. request<{ status: string; weight_used: number }>(`/spoolman/inventory/spools/${spoolId}/weight`, {
  7160. method: 'PATCH',
  7161. body: JSON.stringify({ weight_grams: weightGrams }),
  7162. }),
  7163. // move: as assignSpool's (#1574).
  7164. assignSpoolmanSlot: (data: { spoolman_spool_id: number; printer_id: number; ams_id: number; tray_id: number; move?: boolean }) =>
  7165. request<InventorySpool>('/spoolman/inventory/slot-assignments', {
  7166. method: 'POST',
  7167. body: JSON.stringify(data),
  7168. }),
  7169. unassignSpoolmanSlot: (spoolmanSpoolId: number) =>
  7170. request<InventorySpool>(`/spoolman/inventory/slot-assignments/${spoolmanSpoolId}`, { method: 'DELETE' }),
  7171. getSpoolmanSlotAssignments: (printerId?: number) =>
  7172. request<Array<{
  7173. printer_id: number;
  7174. printer_name: string | null;
  7175. ams_id: number;
  7176. tray_id: number;
  7177. spoolman_spool_id: number;
  7178. ams_label: string | null;
  7179. }>>(
  7180. printerId !== undefined
  7181. ? `/spoolman/inventory/slot-assignments/all?printer_id=${printerId}`
  7182. : '/spoolman/inventory/slot-assignments/all',
  7183. ),
  7184. syncSpoolmanAmsWeights: () =>
  7185. request<{ synced: number; skipped: number; printing?: number }>('/spoolman/inventory/sync-ams-weights', { method: 'POST' }),
  7186. saveSpoolmanKProfiles: (spoolId: number, profiles: SpoolKProfileInput[]) =>
  7187. request<SpoolKProfile[]>(`/spoolman/inventory/spools/${spoolId}/k-profiles`, {
  7188. method: 'PUT',
  7189. body: JSON.stringify(profiles),
  7190. }),
  7191. getSpoolmanFilamentPresets: (spoolId: number) =>
  7192. request<SpoolFilamentPreset[]>(`/spoolman/inventory/spools/${spoolId}/filament-presets`),
  7193. saveSpoolmanFilamentPresets: (spoolId: number, presets: SpoolFilamentPresetInput[]) =>
  7194. request<SpoolFilamentPreset[]>(`/spoolman/inventory/spools/${spoolId}/filament-presets`, {
  7195. method: 'PUT',
  7196. body: JSON.stringify(presets),
  7197. }),
  7198. // Updates
  7199. getVersion: () => request<VersionInfo>('/updates/version'),
  7200. checkForUpdates: () => request<UpdateCheckResult>('/updates/check'),
  7201. applyUpdate: () =>
  7202. request<{ success: boolean; message: string; status?: UpdateStatus; is_docker?: boolean; is_ha_addon?: boolean; is_windows_installer?: boolean }>('/updates/apply', {
  7203. method: 'POST',
  7204. }),
  7205. getUpdateStatus: () => request<UpdateStatus>('/updates/status'),
  7206. // Maintenance
  7207. getMaintenanceTypes: () => request<MaintenanceType[]>('/maintenance/types'),
  7208. createMaintenanceType: (data: MaintenanceTypeCreate) =>
  7209. request<MaintenanceType>('/maintenance/types', {
  7210. method: 'POST',
  7211. body: JSON.stringify(data),
  7212. }),
  7213. updateMaintenanceType: (id: number, data: Partial<MaintenanceTypeCreate>) =>
  7214. request<MaintenanceType>(`/maintenance/types/${id}`, {
  7215. method: 'PATCH',
  7216. body: JSON.stringify(data),
  7217. }),
  7218. deleteMaintenanceType: (id: number) =>
  7219. request<{ status: string }>(`/maintenance/types/${id}`, { method: 'DELETE' }),
  7220. restoreDefaultMaintenanceTypes: () =>
  7221. request<{ restored: number }>(`/maintenance/types/restore-defaults`, { method: 'POST' }),
  7222. getMaintenanceOverview: () => request<PrinterMaintenanceOverview[]>('/maintenance/overview'),
  7223. updateMaintenanceItem: (itemId: number, data: { custom_interval_hours?: number | null; custom_interval_type?: 'hours' | 'days' | null; enabled?: boolean }) =>
  7224. request<MaintenanceStatus>(`/maintenance/items/${itemId}`, {
  7225. method: 'PATCH',
  7226. body: JSON.stringify(data),
  7227. }),
  7228. performMaintenance: (itemId: number, notes?: string) =>
  7229. request<MaintenanceStatus>(`/maintenance/items/${itemId}/perform`, {
  7230. method: 'POST',
  7231. body: JSON.stringify({ notes }),
  7232. }),
  7233. setPrinterHours: (printerId: number, totalHours: number) =>
  7234. request<{ printer_id: number; total_hours: number; archive_hours: number; offset_hours: number }>(
  7235. `/maintenance/printers/${printerId}/hours?total_hours=${totalHours}`,
  7236. { method: 'PATCH' }
  7237. ),
  7238. assignMaintenanceType: (printerId: number, typeId: number) =>
  7239. request<MaintenanceStatus>(`/maintenance/printers/${printerId}/assign/${typeId}`, {
  7240. method: 'POST',
  7241. }),
  7242. removeMaintenanceItem: (itemId: number) =>
  7243. request<{ status: string }>(`/maintenance/items/${itemId}`, {
  7244. method: 'DELETE',
  7245. }),
  7246. // Camera
  7247. getCameraStreamToken: () =>
  7248. request<{ token: string }>('/printers/camera/stream-token', { method: 'POST' }),
  7249. // Media token (#3025) — the credential for thumbnails, plate previews,
  7250. // timelapses, cover images and link icons. Minted behind plain auth rather
  7251. // than camera:view, and identified, so those routes gate on the resource's
  7252. // own permission and ownership instead of on the camera.
  7253. getMediaToken: () => request<{ token: string }>('/auth/media-token', { method: 'POST' }),
  7254. // WebSocket auth (GHSA-r2qv follow-up) — mint a short-lived token for
  7255. // the /ws connection. Browsers can't attach Authorization headers to a
  7256. // WebSocket handshake, so the token rides in the ?token= query param.
  7257. getWebSocketToken: () =>
  7258. request<{ token: string }>('/auth/ws-token', { method: 'POST' }),
  7259. // Connected apps: sign-in to external applications with Bambuddy
  7260. listConnectedApps: () => request<ConnectedApp[]>('/connect/apps'),
  7261. createConnectedApp: (payload: { name: string; redirect_uri: string }) =>
  7262. request<ConnectedApp>('/connect/apps', { method: 'POST', body: JSON.stringify(payload) }),
  7263. updateConnectedApp: (id: number, payload: { name?: string; redirect_uri?: string; enabled?: boolean }) =>
  7264. request<ConnectedApp>(`/connect/apps/${id}`, { method: 'PATCH', body: JSON.stringify(payload) }),
  7265. rotateConnectedAppSecret: (id: number) =>
  7266. request<ConnectedApp>(`/connect/apps/${id}/rotate-secret`, { method: 'POST' }),
  7267. deleteConnectedApp: (id: number) => request<void>(`/connect/apps/${id}`, { method: 'DELETE' }),
  7268. getConnectAuthorizeInfo: (clientId: string, redirectUri: string) =>
  7269. request<ConnectAuthorizeInfo>(
  7270. `/connect/authorize/info?client_id=${encodeURIComponent(clientId)}&redirect_uri=${encodeURIComponent(redirectUri)}`,
  7271. ),
  7272. connectAuthorize: (payload: {
  7273. client_id: string;
  7274. redirect_uri: string;
  7275. code_challenge: string;
  7276. code_challenge_method: 'S256';
  7277. }) =>
  7278. request<{ code: string; redirect_uri: string }>('/connect/authorize', {
  7279. method: 'POST',
  7280. body: JSON.stringify(payload),
  7281. }),
  7282. // Long-lived camera tokens (#1108, #2531)
  7283. createLongLivedCameraToken: (payload: {
  7284. name: string;
  7285. expires_in_days: number;
  7286. scope?: LongLivedTokenScope;
  7287. }) =>
  7288. request<LongLivedCameraToken>('/auth/tokens', {
  7289. method: 'POST',
  7290. body: JSON.stringify({ scope: 'camera_stream', ...payload }),
  7291. }),
  7292. listMyLongLivedCameraTokens: () =>
  7293. request<LongLivedCameraToken[]>('/auth/tokens'),
  7294. listAllLongLivedCameraTokens: () =>
  7295. request<LongLivedCameraToken[]>('/auth/tokens/all'),
  7296. revokeLongLivedCameraToken: (tokenId: number) =>
  7297. request<void>(`/auth/tokens/${tokenId}`, { method: 'DELETE' }),
  7298. // Token-authenticated Cam Wall feed (#2531). `token` is omitted only when
  7299. // auth is disabled, where the backend gate is a no-op anyway.
  7300. getCamWallPrinters: (token?: string) =>
  7301. request<CamWallPrinter[]>(
  7302. token ? `/camwall/printers?token=${encodeURIComponent(token)}` : '/camwall/printers',
  7303. ),
  7304. // Token-authenticated streaming-overlay feed (#2613). OBS (or any embed with
  7305. // no login session) loads /overlay/{id}?token=... and this backs it. `token`
  7306. // is omitted only when auth is disabled, where the backend gate is a no-op.
  7307. getOverlayStatus: (printerId: number, token?: string) =>
  7308. request<OverlayStatus>(
  7309. token
  7310. ? `/printers/${printerId}/overlay-status?token=${encodeURIComponent(token)}`
  7311. : `/printers/${printerId}/overlay-status`,
  7312. ),
  7313. getCameraStatus: (printerId: number) =>
  7314. request<{ active: boolean; stalled: boolean }>(`/printers/${printerId}/camera/status`),
  7315. diagnoseCamera: (printerId: number) =>
  7316. request<CameraDiagnoseResult>(`/printers/${printerId}/camera/diagnose`, { method: 'POST' }),
  7317. diagnosePrinter: (printerId: number) =>
  7318. request<PrinterDiagnosticResult>(`/printers/${printerId}/diagnostic`),
  7319. diagnoseConnection: (body: {
  7320. ip_address: string;
  7321. serial_number?: string;
  7322. access_code?: string;
  7323. }) =>
  7324. request<PrinterDiagnosticResult>('/printers/diagnostic', {
  7325. method: 'POST',
  7326. body: JSON.stringify(body),
  7327. }),
  7328. // Plate Detection - Multi-reference calibration (stores up to 5 references per printer)
  7329. checkPlateEmpty: (printerId: number, options?: { useExternal?: boolean; includeDebugImage?: boolean }) => {
  7330. const params = new URLSearchParams();
  7331. // Only forward use_external when the caller explicitly sets it. Omitted →
  7332. // backend derives the default from the printer's external_camera_enabled
  7333. // setting so calibration and runtime checks use the same camera (#1359).
  7334. if (options?.useExternal !== undefined) {
  7335. params.set('use_external', String(options.useExternal));
  7336. }
  7337. params.set('include_debug_image', String(options?.includeDebugImage ?? false));
  7338. return request<PlateDetectionResult>(
  7339. `/printers/${printerId}/camera/check-plate?${params.toString()}`
  7340. );
  7341. },
  7342. calibratePlateDetection: (printerId: number, options?: { label?: string; useExternal?: boolean }) => {
  7343. const params = new URLSearchParams();
  7344. if (options?.label) params.set('label', options.label);
  7345. if (options?.useExternal !== undefined) {
  7346. params.set('use_external', String(options.useExternal));
  7347. }
  7348. return request<CalibrationResult & { index: number }>(
  7349. `/printers/${printerId}/camera/plate-detection/calibrate?${params.toString()}`,
  7350. { method: 'POST' }
  7351. );
  7352. },
  7353. getPlateReferences: (printerId: number) => {
  7354. return request<{
  7355. references: PlateReference[];
  7356. max_references: number;
  7357. }>(`/printers/${printerId}/camera/plate-detection/references`);
  7358. },
  7359. getPlateReferenceThumbnailUrl: (printerId: number, index: number) =>
  7360. withStreamToken(`${API_BASE}/printers/${printerId}/camera/plate-detection/references/${index}/thumbnail`),
  7361. updatePlateReferenceLabel: (printerId: number, index: number, label: string) => {
  7362. const params = new URLSearchParams();
  7363. params.set('label', label);
  7364. return request<{ success: boolean; index: number; label: string }>(
  7365. `/printers/${printerId}/camera/plate-detection/references/${index}?${params.toString()}`,
  7366. { method: 'PUT' }
  7367. );
  7368. },
  7369. deletePlateReference: (printerId: number, index: number) => {
  7370. return request<{ success: boolean; message: string }>(
  7371. `/printers/${printerId}/camera/plate-detection/references/${index}`,
  7372. { method: 'DELETE' }
  7373. );
  7374. },
  7375. // External Links
  7376. getExternalLinks: () => request<ExternalLink[]>('/external-links/'),
  7377. getExternalLink: (id: number) => request<ExternalLink>(`/external-links/${id}`),
  7378. createExternalLink: (data: ExternalLinkCreate) =>
  7379. request<ExternalLink>('/external-links/', {
  7380. method: 'POST',
  7381. body: JSON.stringify(data),
  7382. }),
  7383. updateExternalLink: (id: number, data: ExternalLinkUpdate) =>
  7384. request<ExternalLink>(`/external-links/${id}`, {
  7385. method: 'PATCH',
  7386. body: JSON.stringify(data),
  7387. }),
  7388. deleteExternalLink: (id: number) =>
  7389. request<{ message: string }>(`/external-links/${id}`, { method: 'DELETE' }),
  7390. uploadExternalLinkIcon: async (id: number, file: File): Promise<ExternalLink> => {
  7391. const formData = new FormData();
  7392. formData.append('file', file);
  7393. const headers: Record<string, string> = {};
  7394. if (authToken) {
  7395. headers['Authorization'] = `Bearer ${authToken}`;
  7396. }
  7397. const response = await fetch(`${API_BASE}/external-links/${id}/icon`, {
  7398. method: 'POST',
  7399. headers,
  7400. body: formData,
  7401. });
  7402. if (!response.ok) {
  7403. const error = await response.json().catch(() => ({}));
  7404. throw new Error(error.detail || `HTTP ${response.status}`);
  7405. }
  7406. return response.json();
  7407. },
  7408. deleteExternalLinkIcon: (id: number) =>
  7409. request<ExternalLink>(`/external-links/${id}/icon`, { method: 'DELETE' }),
  7410. getExternalLinkIconUrl: (id: number) => withMediaToken(`${API_BASE}/external-links/${id}/icon`),
  7411. // Projects
  7412. getProjects: (status?: string) => {
  7413. const params = new URLSearchParams();
  7414. if (status) params.set('status', status);
  7415. return request<ProjectListItem[]>(`/projects/?${params}`);
  7416. },
  7417. getProject: (id: number) => request<Project>(`/projects/${id}`),
  7418. createProject: (data: ProjectCreate) =>
  7419. request<Project>('/projects/', {
  7420. method: 'POST',
  7421. body: JSON.stringify(data),
  7422. }),
  7423. updateProject: (id: number, data: ProjectUpdate) =>
  7424. request<Project>(`/projects/${id}`, {
  7425. method: 'PATCH',
  7426. body: JSON.stringify(data),
  7427. }),
  7428. deleteProject: (id: number) =>
  7429. request<{ message: string }>(`/projects/${id}`, { method: 'DELETE' }),
  7430. getProjectArchives: (id: number, limit = 100, offset = 0) =>
  7431. request<Archive[]>(`/projects/${id}/archives?limit=${limit}&offset=${offset}`),
  7432. // Completed-run counts per library file (#1897); files with 0 runs are omitted
  7433. getProjectFileProgress: (id: number) =>
  7434. request<ProjectFileProgress[]>(`/projects/${id}/file-progress`),
  7435. addArchivesToProject: (projectId: number, archiveIds: number[]) =>
  7436. request<{ message: string; count: number }>(`/projects/${projectId}/add-archives`, {
  7437. method: 'POST',
  7438. body: JSON.stringify({ archive_ids: archiveIds }),
  7439. }),
  7440. // #1155: Cover image
  7441. // Browsers can't attach `Authorization: Bearer ...` to `<img src>`, so we
  7442. // append the stream-token query string the same way archive thumbnails do.
  7443. // `version` cache-busts the browser copy after a re-upload. It has to go on
  7444. // before the token does: callers used to append their own `?v=` to the
  7445. // returned URL, which already ended in `?token=…`, so the second `?` landed
  7446. // inside the token value and the image 401'd whenever auth was enabled.
  7447. getProjectCoverImageUrl: (projectId: number, version?: string | number) =>
  7448. withMediaToken(
  7449. `${API_BASE}/projects/${projectId}/cover-image${
  7450. version === undefined ? '' : `?v=${encodeURIComponent(String(version))}`
  7451. }`
  7452. ),
  7453. uploadProjectCoverImage: async (
  7454. projectId: number,
  7455. file: File
  7456. ): Promise<{ status: string; filename: string; size: number }> => {
  7457. const formData = new FormData();
  7458. formData.append('file', file);
  7459. const headers: Record<string, string> = {};
  7460. if (authToken) {
  7461. headers['Authorization'] = `Bearer ${authToken}`;
  7462. }
  7463. const response = await fetch(`${API_BASE}/projects/${projectId}/cover-image`, {
  7464. method: 'POST',
  7465. headers,
  7466. body: formData,
  7467. });
  7468. if (!response.ok) {
  7469. const error = await response.json().catch(() => ({}));
  7470. throw new Error(error.detail || `HTTP ${response.status}`);
  7471. }
  7472. return response.json();
  7473. },
  7474. deleteProjectCoverImage: (projectId: number) =>
  7475. request<{ status: string }>(`/projects/${projectId}/cover-image`, { method: 'DELETE' }),
  7476. // BOM (Bill of Materials)
  7477. getProjectBOM: (projectId: number) =>
  7478. request<BOMItem[]>(`/projects/${projectId}/bom`),
  7479. createBOMItem: (projectId: number, data: BOMItemCreate) =>
  7480. request<BOMItem>(`/projects/${projectId}/bom`, {
  7481. method: 'POST',
  7482. body: JSON.stringify(data),
  7483. }),
  7484. updateBOMItem: (projectId: number, itemId: number, data: BOMItemUpdate) =>
  7485. request<BOMItem>(`/projects/${projectId}/bom/${itemId}`, {
  7486. method: 'PATCH',
  7487. body: JSON.stringify(data),
  7488. }),
  7489. deleteBOMItem: (projectId: number, itemId: number) =>
  7490. request<{ status: string; message: string }>(`/projects/${projectId}/bom/${itemId}`, {
  7491. method: 'DELETE',
  7492. }),
  7493. // Templates
  7494. getTemplates: () => request<ProjectListItem[]>('/projects/templates/'),
  7495. createTemplateFromProject: (projectId: number) =>
  7496. request<Project>(`/projects/${projectId}/create-template`, { method: 'POST' }),
  7497. createProjectFromTemplate: (templateId: number, name?: string) =>
  7498. request<Project>(`/projects/from-template/${templateId}${name ? `?name=${encodeURIComponent(name)}` : ''}`, {
  7499. method: 'POST',
  7500. }),
  7501. // Timeline
  7502. getProjectTimeline: (projectId: number, limit = 50) =>
  7503. request<TimelineEvent[]>(`/projects/${projectId}/timeline?limit=${limit}`),
  7504. // Project Export/Import
  7505. exportProjectJson: (projectId: number) =>
  7506. request<ProjectExport>(`/projects/${projectId}/export?format=json`),
  7507. importProject: (data: ProjectImport) =>
  7508. request<Project>('/projects/import', {
  7509. method: 'POST',
  7510. body: JSON.stringify(data),
  7511. }),
  7512. importProjectFile: async (file: File): Promise<Project> => {
  7513. const formData = new FormData();
  7514. formData.append('file', file);
  7515. const headers: Record<string, string> = {};
  7516. if (authToken) {
  7517. headers['Authorization'] = `Bearer ${authToken}`;
  7518. }
  7519. const response = await fetch(`${API_BASE}/projects/import/file`, {
  7520. method: 'POST',
  7521. headers,
  7522. body: formData,
  7523. });
  7524. if (!response.ok) {
  7525. const error = await response.json().catch(() => ({}));
  7526. throw new Error(error.detail || `HTTP ${response.status}`);
  7527. }
  7528. return response.json();
  7529. },
  7530. exportProjectZip: async (projectId: number): Promise<{ blob: Blob; filename: string }> => {
  7531. const headers: Record<string, string> = {};
  7532. if (authToken) {
  7533. headers['Authorization'] = `Bearer ${authToken}`;
  7534. }
  7535. const response = await fetch(`${API_BASE}/projects/${projectId}/export`, {
  7536. headers,
  7537. });
  7538. if (!response.ok) {
  7539. const error = await response.json().catch(() => ({}));
  7540. throw new Error(error.detail || `HTTP ${response.status}`);
  7541. }
  7542. const contentDisposition = response.headers.get('Content-Disposition');
  7543. const filename = parseContentDispositionFilename(contentDisposition) || `project_${projectId}.zip`;
  7544. const blob = await response.blob();
  7545. return { blob, filename };
  7546. },
  7547. // API Keys
  7548. getAPIKeys: () => request<APIKey[]>('/api-keys/'),
  7549. createAPIKey: (data: APIKeyCreate) =>
  7550. request<APIKeyCreateResponse>('/api-keys/', {
  7551. method: 'POST',
  7552. body: JSON.stringify(data),
  7553. }),
  7554. deleteAPIKey: (id: number) =>
  7555. request<{ message: string }>(`/api-keys/${id}`, { method: 'DELETE' }),
  7556. // AMS History
  7557. getAMSHistory: (printerId: number, amsId: number, hours = 24) =>
  7558. request<AMSHistoryResponse>(`/ams-history/${printerId}/${amsId}?hours=${hours}`),
  7559. // Printer heater (nozzle / bed / chamber) sensor history
  7560. getPrinterSensorHistory: (printerId: number, hours = 24, kinds?: string[]) => {
  7561. const params = new URLSearchParams({ hours: String(hours) });
  7562. if (kinds && kinds.length > 0) params.set('kinds', kinds.join(','));
  7563. return request<PrinterSensorHistoryResponse>(`/printer-sensor-history/${printerId}?${params.toString()}`);
  7564. },
  7565. // System Info
  7566. getSystemInfo: () => request<SystemInfo>('/system/info'),
  7567. getSystemHealth: () => request<SystemHealthResult>('/system/health'),
  7568. getStorageUsage: (options?: { refresh?: boolean }) => {
  7569. const params = new URLSearchParams();
  7570. if (options?.refresh) {
  7571. params.set('refresh', 'true');
  7572. }
  7573. const query = params.toString();
  7574. return request<StorageUsageResponse>(`/system/storage-usage${query ? `?${query}` : ''}`);
  7575. },
  7576. // Library (File Manager)
  7577. getLibraryFolders: () => request<LibraryFolderTree[]>('/library/folders'),
  7578. createLibraryFolder: (data: LibraryFolderCreate) =>
  7579. request<LibraryFolder>('/library/folders', {
  7580. method: 'POST',
  7581. body: JSON.stringify(data),
  7582. }),
  7583. updateLibraryFolder: (id: number, data: LibraryFolderUpdate) =>
  7584. request<LibraryFolder>(`/library/folders/${id}`, {
  7585. method: 'PUT',
  7586. body: JSON.stringify(data),
  7587. }),
  7588. deleteLibraryFolder: (id: number) =>
  7589. request<{ status: string; message: string }>(`/library/folders/${id}`, { method: 'DELETE' }),
  7590. createExternalFolder: (data: ExternalFolderCreate) =>
  7591. request<LibraryFolder>('/library/folders/external', {
  7592. method: 'POST',
  7593. body: JSON.stringify(data),
  7594. }),
  7595. scanExternalFolder: (folderId: number) =>
  7596. request<{ status: string; added: number; removed: number }>(`/library/folders/${folderId}/scan`, {
  7597. method: 'POST',
  7598. }),
  7599. getLibraryFoldersByProject: (projectId: number) =>
  7600. request<LibraryFolder[]>(`/library/folders/by-project/${projectId}`),
  7601. getLibraryFoldersByArchive: (archiveId: number) => foldersByArchiveBatch(archiveId),
  7602. getLibraryFiles: (
  7603. folderId?: number | null,
  7604. includeRoot = true,
  7605. projectId?: number,
  7606. scope?: 'internal' | 'external',
  7607. recursive = false,
  7608. tagIds: number[] = [],
  7609. ) => {
  7610. const params = new URLSearchParams();
  7611. if (folderId !== undefined && folderId !== null) {
  7612. params.set('folder_id', String(folderId));
  7613. }
  7614. if (projectId !== undefined) {
  7615. params.set('project_id', String(projectId));
  7616. }
  7617. params.set('include_root', String(includeRoot));
  7618. if (scope === 'internal') params.set('internal_only', 'true');
  7619. else if (scope === 'external') params.set('external_only', 'true');
  7620. // recursive=true expands the folder_id filter to include every descendant
  7621. // folder (#1268). Only meaningful when folder_id is set; ignored server-side
  7622. // otherwise. Off by default so non-search callers keep folder-scoped behavior.
  7623. if (recursive) params.set('recursive', 'true');
  7624. // Tag filter (#1268). Repeated ?tag_ids=N&tag_ids=M form for AND semantics
  7625. // — backend joins the association table and HAVING COUNT(DISTINCT) matches
  7626. // the array length. Tag filter intentionally bypasses folder scoping
  7627. // server-side (cross-cutting design decision).
  7628. for (const tagId of tagIds) {
  7629. params.append('tag_ids', String(tagId));
  7630. }
  7631. return request<LibraryFileListItem[]>(`/library/files?${params}`);
  7632. },
  7633. getLibraryFolderReadme: (folderId: number) =>
  7634. request<{ filename: string; content: string; truncated: boolean }>(
  7635. `/library/folders/${folderId}/readme`,
  7636. ),
  7637. // ============ Library tag catalog (#1268) ============
  7638. getLibraryTags: () =>
  7639. request<LibraryTag[]>('/library/tags'),
  7640. createLibraryTag: (name: string) =>
  7641. request<LibraryTag>('/library/tags', {
  7642. method: 'POST',
  7643. body: JSON.stringify({ name }),
  7644. }),
  7645. updateLibraryTag: (id: number, name: string) =>
  7646. request<LibraryTag>(`/library/tags/${id}`, {
  7647. method: 'PATCH',
  7648. body: JSON.stringify({ name }),
  7649. }),
  7650. deleteLibraryTag: (id: number) =>
  7651. request<void>(`/library/tags/${id}`, { method: 'DELETE' }),
  7652. bulkAssignLibraryTags: (
  7653. fileIds: number[],
  7654. tagIds: number[],
  7655. action: 'add' | 'remove' | 'replace',
  7656. ) =>
  7657. request<LibraryTagBulkAssignResult>('/library/tags/bulk-assign', {
  7658. method: 'POST',
  7659. body: JSON.stringify({ file_ids: fileIds, tag_ids: tagIds, action }),
  7660. }),
  7661. // ============ Variant groups (#671 / #2570) ============
  7662. // "These files are the same job sliced for different printers." Consumed from
  7663. // both ends: the queue picks a printer and needs the matching file, the File
  7664. // Manager's print action has the printer and needs the same match.
  7665. createVariantGroup: (
  7666. members: { library_file_id: number; target_model?: string }[],
  7667. name?: string,
  7668. ) =>
  7669. request<VariantGroup>('/library/variant-groups', {
  7670. method: 'POST',
  7671. body: JSON.stringify({ members, ...(name ? { name } : {}) }),
  7672. }),
  7673. getVariantGroup: (groupId: number) =>
  7674. request<VariantGroup>(`/library/variant-groups/${groupId}`),
  7675. getLibraryFile: (id: number) => request<LibraryFile>(`/library/files/${id}`),
  7676. uploadLibraryFile: async (
  7677. file: File,
  7678. folderId?: number | null,
  7679. generateStlThumbnails: boolean = true
  7680. ): Promise<LibraryFileUploadResponse> => {
  7681. const formData = new FormData();
  7682. formData.append('file', file);
  7683. const params = new URLSearchParams();
  7684. if (folderId) params.set('folder_id', String(folderId));
  7685. params.set('generate_stl_thumbnails', String(generateStlThumbnails));
  7686. const headers: Record<string, string> = {};
  7687. if (authToken) {
  7688. headers['Authorization'] = `Bearer ${authToken}`;
  7689. }
  7690. const response = await fetch(`${API_BASE}/library/files?${params}`, {
  7691. method: 'POST',
  7692. headers,
  7693. body: formData,
  7694. });
  7695. if (!response.ok) {
  7696. const error = await response.json().catch(() => ({}));
  7697. throw new Error(error.detail || `HTTP ${response.status}`);
  7698. }
  7699. return response.json();
  7700. },
  7701. extractZipFile: async (
  7702. file: File,
  7703. folderId?: number | null,
  7704. preserveStructure: boolean = true,
  7705. createFolderFromZip: boolean = false,
  7706. generateStlThumbnails: boolean = true
  7707. ): Promise<ZipExtractResponse> => {
  7708. const formData = new FormData();
  7709. formData.append('file', file);
  7710. const params = new URLSearchParams();
  7711. if (folderId) params.set('folder_id', String(folderId));
  7712. params.set('preserve_structure', String(preserveStructure));
  7713. params.set('create_folder_from_zip', String(createFolderFromZip));
  7714. params.set('generate_stl_thumbnails', String(generateStlThumbnails));
  7715. const headers: Record<string, string> = {};
  7716. if (authToken) {
  7717. headers['Authorization'] = `Bearer ${authToken}`;
  7718. }
  7719. const response = await fetch(`${API_BASE}/library/files/extract-zip?${params}`, {
  7720. method: 'POST',
  7721. headers,
  7722. body: formData,
  7723. });
  7724. if (!response.ok) {
  7725. const error = await response.json().catch(() => ({}));
  7726. throw new Error(error.detail || `HTTP ${response.status}`);
  7727. }
  7728. return response.json();
  7729. },
  7730. updateLibraryFile: (id: number, data: LibraryFileUpdate) =>
  7731. request<LibraryFile>(`/library/files/${id}`, {
  7732. method: 'PUT',
  7733. body: JSON.stringify(data),
  7734. }),
  7735. deleteLibraryFile: (id: number) =>
  7736. request<{ status: string; message: string; trashed: boolean }>(`/library/files/${id}`, { method: 'DELETE' }),
  7737. // ========== Library Trash (#1008) ==========
  7738. previewLibraryPurge: (olderThanDays: number, includeNeverPrinted: boolean = true) =>
  7739. request<LibraryPurgePreview>(
  7740. `/library/purge/preview?older_than_days=${olderThanDays}&include_never_printed=${includeNeverPrinted}`,
  7741. ),
  7742. executeLibraryPurge: (olderThanDays: number, includeNeverPrinted: boolean = true) =>
  7743. request<{ moved_to_trash: number }>('/library/purge', {
  7744. method: 'POST',
  7745. body: JSON.stringify({ older_than_days: olderThanDays, include_never_printed: includeNeverPrinted }),
  7746. }),
  7747. listLibraryTrash: (limit: number = 100, offset: number = 0) =>
  7748. request<LibraryTrashListResponse>(`/library/trash?limit=${limit}&offset=${offset}`),
  7749. restoreLibraryTrash: (fileId: number) =>
  7750. request<{ status: string; id: number }>(`/library/trash/${fileId}/restore`, { method: 'POST' }),
  7751. hardDeleteLibraryTrash: (fileId: number) =>
  7752. request<{ status: string }>(`/library/trash/${fileId}`, { method: 'DELETE' }),
  7753. emptyLibraryTrash: () => request<{ deleted: number }>('/library/trash', { method: 'DELETE' }),
  7754. getLibraryTrashSettings: () =>
  7755. request<LibraryTrashSettings>('/library/trash/settings'),
  7756. updateLibraryTrashSettings: (body: LibraryTrashSettings) =>
  7757. request<LibraryTrashSettings>('/library/trash/settings', {
  7758. method: 'PUT',
  7759. body: JSON.stringify(body),
  7760. }),
  7761. getLibraryFileDownloadUrl: (id: number) => `${API_BASE}/library/files/${id}/download`,
  7762. createLibrarySlicerToken: (fileId: number) =>
  7763. request<{ token: string }>(`/library/files/${fileId}/slicer-token`, { method: 'POST' }),
  7764. getLibrarySlicerDownloadUrl: (fileId: number, token: string, filename: string) =>
  7765. `${API_BASE}/library/files/${fileId}/dl/${token}/${encodeURIComponent(buildSlicerUrlFilename(filename))}`,
  7766. downloadLibraryFile: async (id: number, filename?: string): Promise<void> => {
  7767. const headers: Record<string, string> = {};
  7768. if (authToken) {
  7769. headers['Authorization'] = `Bearer ${authToken}`;
  7770. }
  7771. const response = await fetch(`${API_BASE}/library/files/${id}/download`, { headers });
  7772. if (!response.ok) {
  7773. const error = await response.json().catch(() => ({}));
  7774. throw new Error(error.detail || `HTTP ${response.status}`);
  7775. }
  7776. const disposition = response.headers.get('Content-Disposition');
  7777. const downloadFilename = parseContentDispositionFilename(disposition) || filename || `file_${id}`;
  7778. const blob = await response.blob();
  7779. const url = window.URL.createObjectURL(blob);
  7780. const a = document.createElement('a');
  7781. a.href = url;
  7782. a.download = downloadFilename;
  7783. document.body.appendChild(a);
  7784. a.click();
  7785. document.body.removeChild(a);
  7786. window.URL.revokeObjectURL(url);
  7787. },
  7788. getLibraryFileThumbnailUrl: (id: number) => withMediaToken(`${API_BASE}/library/files/${id}/thumbnail`),
  7789. // Client-rendered preview thumbnail upload (#2976). STEP/PDF/spreadsheet
  7790. // previews render in the browser; the first render is posted back so the
  7791. // grid gets a thumbnail without a server-side renderer for those formats.
  7792. uploadLibraryPreviewThumbnail: async (fileId: number, thumbnail: Blob): Promise<{ updated: boolean }> => {
  7793. const formData = new FormData();
  7794. formData.append('thumbnail', thumbnail, 'preview.png');
  7795. const headers: Record<string, string> = {};
  7796. if (authToken) {
  7797. headers['Authorization'] = `Bearer ${authToken}`;
  7798. }
  7799. const response = await fetch(`${API_BASE}/library/files/${fileId}/preview-thumbnail`, {
  7800. method: 'POST',
  7801. headers,
  7802. body: formData,
  7803. });
  7804. if (!response.ok) {
  7805. const error = await response.json().catch(() => ({}));
  7806. throw new Error(error.detail || `HTTP ${response.status}`);
  7807. }
  7808. return response.json();
  7809. },
  7810. getLibraryFilePlateThumbnail: (id: number, plateIndex: number) =>
  7811. withMediaToken(`${API_BASE}/library/files/${id}/plate-thumbnail/${plateIndex}`),
  7812. // Photos of the printed result (#3077) — same shape as the archive photo API.
  7813. getLibraryFilePhotoUrl: (fileId: number, filename: string) =>
  7814. withMediaToken(`${API_BASE}/library/files/${fileId}/photos/${encodeURIComponent(filename)}`),
  7815. uploadLibraryFilePhoto: async (fileId: number, file: File): Promise<{ status: string; filename: string; photos: string[] }> => {
  7816. const formData = new FormData();
  7817. formData.append('file', file);
  7818. const headers: Record<string, string> = {};
  7819. if (authToken) {
  7820. headers['Authorization'] = `Bearer ${authToken}`;
  7821. }
  7822. const response = await fetch(`${API_BASE}/library/files/${fileId}/photos`, {
  7823. method: 'POST',
  7824. headers,
  7825. body: formData,
  7826. });
  7827. if (!response.ok) {
  7828. const error = await response.json().catch(() => ({}));
  7829. throw new Error(error.detail || `HTTP ${response.status}`);
  7830. }
  7831. return response.json();
  7832. },
  7833. deleteLibraryFilePhoto: (fileId: number, filename: string) =>
  7834. request<{ status: string; photos: string[] }>(`/library/files/${fileId}/photos/${encodeURIComponent(filename)}`, {
  7835. method: 'DELETE',
  7836. }),
  7837. getLibraryFileGcodeUrl: (id: number) => `${API_BASE}/library/files/${id}/gcode`,
  7838. moveLibraryFiles: (fileIds: number[], folderId: number | null) =>
  7839. request<{ status: string; moved: number }>('/library/files/move', {
  7840. method: 'POST',
  7841. body: JSON.stringify({ file_ids: fileIds, folder_id: folderId }),
  7842. }),
  7843. bulkDeleteLibrary: (fileIds: number[], folderIds: number[]) =>
  7844. request<{ deleted_files: number; deleted_folders: number }>('/library/bulk-delete', {
  7845. method: 'POST',
  7846. body: JSON.stringify({ file_ids: fileIds, folder_ids: folderIds }),
  7847. }),
  7848. getLibraryStats: () => request<LibraryStats>('/library/stats'),
  7849. batchGenerateStlThumbnails: (options: {
  7850. file_ids?: number[];
  7851. folder_id?: number;
  7852. all_missing?: boolean;
  7853. }) =>
  7854. request<BatchThumbnailResponse>('/library/generate-stl-thumbnails', {
  7855. method: 'POST',
  7856. body: JSON.stringify(options),
  7857. }),
  7858. combineLibraryFiles: (items: { file_id: number; copies: number }[], filename: string, folderId: number | null) =>
  7859. request<LibraryFileUploadResponse>('/library/files/combine', {
  7860. method: 'POST',
  7861. body: JSON.stringify({ items, filename, folder_id: folderId }),
  7862. }),
  7863. getLibraryFilePlates: (fileId: number) =>
  7864. request<LibraryFilePlatesResponse>(`/library/files/${fileId}/plates`),
  7865. getLibraryFileFilamentRequirements: (
  7866. fileId: number,
  7867. plateId?: number,
  7868. requestId?: string,
  7869. /** Ask for one entry per project slot instead of only the slots this
  7870. * plate consumes. The slice modal needs it: its filament list is
  7871. * positional, so a source whose only used slot is 4 must still present
  7872. * four rows or the user's pick is bound to slot 1 (#2712). Print-time
  7873. * AMS matching must NOT set this — it wants the used-only list. */
  7874. fullSlots?: boolean,
  7875. ) => {
  7876. const qs = new URLSearchParams();
  7877. if (plateId !== undefined) qs.set('plate_id', String(plateId));
  7878. if (requestId) qs.set('request_id', requestId);
  7879. if (fullSlots) qs.set('full_slots', 'true');
  7880. return request<{
  7881. file_id: number;
  7882. filename: string;
  7883. filaments: Array<{
  7884. slot_id: number;
  7885. type: string;
  7886. color: string;
  7887. used_grams: number;
  7888. used_meters: number;
  7889. used_in_plate?: boolean;
  7890. }>;
  7891. }>(`/library/files/${fileId}/filament-requirements${qs.toString() ? `?${qs}` : ''}`);
  7892. },
  7893. /** Poll the sidecar's per-request progress snapshot via the Bambuddy
  7894. * proxy. Used by the SliceModal's filament-discovery path so the inline
  7895. * spinner + persistent toast can show "Generating G-code (45%)" while
  7896. * the preview slice runs. Returns null on 404 (sidecar doesn't yet
  7897. * have an entry — early race window — or it expired) so the poller
  7898. * can keep trying. */
  7899. getPreviewSliceProgress: async (requestId: string): Promise<SliceJobProgress | null> => {
  7900. try {
  7901. return await request<SliceJobProgress>(`/slicer/preview-progress/${encodeURIComponent(requestId)}`);
  7902. } catch {
  7903. return null;
  7904. }
  7905. },
  7906. // GitHub Backup
  7907. getGitHubBackupConfig: () =>
  7908. request<GitHubBackupConfig | null>('/github-backup/config'),
  7909. getGitHubBackupCloudAccounts: () =>
  7910. request<CloudAccountCounts>('/github-backup/cloud-accounts'),
  7911. saveGitHubBackupConfig: (config: GitHubBackupConfigCreate) =>
  7912. request<GitHubBackupConfig>('/github-backup/config', {
  7913. method: 'POST',
  7914. body: JSON.stringify(config),
  7915. }),
  7916. updateGitHubBackupConfig: (config: Partial<GitHubBackupConfigCreate>) =>
  7917. request<GitHubBackupConfig>('/github-backup/config', {
  7918. method: 'PATCH',
  7919. body: JSON.stringify(config),
  7920. }),
  7921. testGitHubConnection: (repoUrl: string, token: string, provider: GitProviderType = 'github') =>
  7922. request<GitHubTestConnectionResponse>('/github-backup/test', {
  7923. method: 'POST',
  7924. body: JSON.stringify({ repo_url: repoUrl, token, provider }),
  7925. }),
  7926. testGitHubStoredConnection: () =>
  7927. request<GitHubTestConnectionResponse>('/github-backup/test-stored', { method: 'POST' }),
  7928. triggerGitHubBackup: () =>
  7929. request<GitHubBackupTriggerResponse>('/github-backup/run', { method: 'POST' }),
  7930. getGitHubBackupStatus: () =>
  7931. request<GitHubBackupStatus>('/github-backup/status'),
  7932. getGitHubBackupLogs: (limit: number = 50) =>
  7933. request<GitHubBackupLog[]>(`/github-backup/logs?limit=${limit}`),
  7934. clearGitHubBackupLogs: (keepLast: number = 10) =>
  7935. request<{ deleted: number; message: string }>(`/github-backup/logs?keep_last=${keepLast}`, { method: 'DELETE' }),
  7936. // Restore from a Git backup (#2656)
  7937. getGitHubBackupCommits: (limit: number = 20) =>
  7938. request<GitHubCommitListResponse>(`/github-backup/commits?limit=${limit}`),
  7939. getGitHubRestorePreview: (ref: string = 'HEAD') =>
  7940. request<GitHubRestorePreview>(`/github-backup/restore/preview?ref=${encodeURIComponent(ref)}`),
  7941. restoreFromGitHub: (payload: GitHubRestoreRequest) =>
  7942. request<GitHubRestoreResponse>('/github-backup/restore', {
  7943. method: 'POST',
  7944. body: JSON.stringify(payload),
  7945. }),
  7946. // Scheduled local backups
  7947. getLocalBackupStatus: () =>
  7948. request<LocalBackupStatus>('/local-backup/status'),
  7949. triggerLocalBackup: () =>
  7950. request<{ success: boolean; message: string; filename?: string }>('/local-backup/run', { method: 'POST' }),
  7951. checkLocalBackupPath: () =>
  7952. request<LocalBackupPathCheck>('/local-backup/path-check'),
  7953. getLocalBackups: () =>
  7954. request<LocalBackupFile[]>('/local-backup/backups'),
  7955. downloadLocalBackup: async (filename: string): Promise<{ blob: Blob; filename: string }> => {
  7956. const response = await fetch(`${API_BASE}/local-backup/backups/${encodeURIComponent(filename)}/download`, {
  7957. headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {},
  7958. });
  7959. if (!response.ok) throw new Error('Download failed');
  7960. const blob = await response.blob();
  7961. return { blob, filename };
  7962. },
  7963. restoreLocalBackup: (filename: string) =>
  7964. request<{ success: boolean; message: string }>(`/local-backup/backups/${encodeURIComponent(filename)}/restore`, { method: 'POST' }),
  7965. deleteLocalBackup: (filename: string) =>
  7966. request<{ success: boolean; message: string }>(`/local-backup/backups/${encodeURIComponent(filename)}`, { method: 'DELETE' }),
  7967. // Obico AI failure detection
  7968. getObicoStatus: () =>
  7969. request<ObicoStatus>('/obico/status'),
  7970. getObicoPrinterStatus: () =>
  7971. request<ObicoPrinterStatus>('/obico/printer-status'),
  7972. // `token` is sent as-is, so an empty string tests with no token at all.
  7973. // Omitting the argument makes the backend fall back to the saved token.
  7974. testObicoConnection: (url: string, token?: string) =>
  7975. request<ObicoTestConnection>('/obico/test-connection', {
  7976. method: 'POST',
  7977. body: JSON.stringify(token === undefined ? { url } : { url, token }),
  7978. }),
  7979. // OctoEverywhere AI failure detection
  7980. getOctoEverywhereStatus: () =>
  7981. request<OctoEverywhereStatus>('/octoeverywhere/status'),
  7982. getOctoEverywherePrinterStatus: () =>
  7983. request<OctoEverywherePrinterStatus>('/octoeverywhere/printer-status'),
  7984. // An omitted key uses the saved key; an explicit empty key is rejected.
  7985. testOctoEverywhereConnection: (apiKey?: string, confidence?: OctoEverywhereConfidence) =>
  7986. request<OctoEverywhereTestConnection>('/octoeverywhere/test-connection', {
  7987. method: 'POST',
  7988. body: JSON.stringify({ api_key: apiKey, confidence }),
  7989. }),
  7990. // Slicer API — slice in the background. Both endpoints return 202 + a
  7991. // job_id; poll /slice-jobs/{id} until status is `completed` or `failed`.
  7992. sliceLibraryFile: (fileId: number, body: SliceRequest) =>
  7993. request<SliceJobEnqueueResponse>(`/library/files/${fileId}/slice`, {
  7994. method: 'POST',
  7995. body: JSON.stringify(body),
  7996. }),
  7997. sliceArchive: (archiveId: number, body: SliceRequest) =>
  7998. request<SliceJobEnqueueResponse>(`/archives/${archiveId}/slice`, {
  7999. method: 'POST',
  8000. body: JSON.stringify(body),
  8001. }),
  8002. getSliceJob: (jobId: number) =>
  8003. request<SliceJobState>(`/slice-jobs/${jobId}`),
  8004. // Unified slicer-preset listing — cloud + local + standard, deduped by name.
  8005. // Used by the SliceModal; see UnifiedPresetsResponse for the shape and
  8006. // backend/app/api/routes/slicer_presets.py for the priority rules.
  8007. // `refresh` bypasses the in-process cloud and bundled-preset caches on the
  8008. // backend; the SliceModal's Refresh button passes true so a preset deleted
  8009. // in Bambu Studio or Bambu Handy shows up without the 5-min TTL wait.
  8010. getSlicerPresets: (options?: { refresh?: boolean }) =>
  8011. request<UnifiedPresetsResponse>(
  8012. options?.refresh ? '/slicer/presets?refresh=true' : '/slicer/presets',
  8013. ),
  8014. // Slicer Pipelines (#1425) — preset bundles the SliceModal can apply in
  8015. // one click. CRUD is gated on PIPELINES_READ / PIPELINES_WRITE.
  8016. listSlicerPipelines: () =>
  8017. request<SlicerPipelinesListResponse>('/slicer-pipelines/'),
  8018. createSlicerPipeline: (data: SlicerPipelineCreateRequest) =>
  8019. request<SlicerPipeline>('/slicer-pipelines/', {
  8020. method: 'POST',
  8021. body: JSON.stringify(data),
  8022. }),
  8023. updateSlicerPipeline: (id: number, data: SlicerPipelineUpdateRequest) =>
  8024. request<SlicerPipeline>(`/slicer-pipelines/${id}`, {
  8025. method: 'PUT',
  8026. body: JSON.stringify(data),
  8027. }),
  8028. deleteSlicerPipeline: (id: number) =>
  8029. request<void>(`/slicer-pipelines/${id}`, { method: 'DELETE' }),
  8030. checkPipelineEligibility: (
  8031. pipelineId: number,
  8032. source: { kind: 'libraryFile'; id: number } | { kind: 'archive'; id: number },
  8033. ) =>
  8034. request<PipelineEligibilityReport>(`/slicer-pipelines/${pipelineId}/check-eligibility`, {
  8035. method: 'POST',
  8036. body: JSON.stringify(
  8037. source.kind === 'libraryFile'
  8038. ? { source_library_file_id: source.id }
  8039. : { source_archive_id: source.id },
  8040. ),
  8041. }),
  8042. runPipeline: (
  8043. pipelineId: number,
  8044. source: { kind: 'libraryFile'; id: number } | { kind: 'archive'; id: number },
  8045. force = false,
  8046. copies = 1,
  8047. ) =>
  8048. request<PipelineRun>(`/slicer-pipelines/${pipelineId}/run`, {
  8049. method: 'POST',
  8050. body: JSON.stringify({
  8051. ...(source.kind === 'libraryFile'
  8052. ? { source_library_file_id: source.id }
  8053. : { source_archive_id: source.id }),
  8054. force,
  8055. copies,
  8056. }),
  8057. }),
  8058. listPipelineRuns: (pipelineId: number, limit = 5) =>
  8059. request<PipelineRunListResponse>(
  8060. `/slicer-pipelines/${pipelineId}/runs?limit=${limit}`,
  8061. ),
  8062. // Dashboard list across all pipelines (#1425 PR C).
  8063. listAllPipelineRuns: (params: {
  8064. limit?: number;
  8065. offset?: number;
  8066. pipelineId?: number;
  8067. status?: string;
  8068. targetPrinterId?: number;
  8069. targetModelClass?: string;
  8070. } = {}) => {
  8071. const search = new URLSearchParams();
  8072. if (params.limit) search.set('limit', String(params.limit));
  8073. if (params.offset) search.set('offset', String(params.offset));
  8074. if (params.pipelineId) search.set('pipeline_id', String(params.pipelineId));
  8075. if (params.status) search.set('status', params.status);
  8076. if (params.targetPrinterId) search.set('target_printer_id', String(params.targetPrinterId));
  8077. if (params.targetModelClass) search.set('target_model_class', params.targetModelClass);
  8078. const q = search.toString();
  8079. return request<PipelineRunListResponse>(
  8080. `/pipeline-runs${q ? '?' + q : ''}`,
  8081. );
  8082. },
  8083. // Clear terminal pipeline runs (#1425 PR C polish). Deletes all runs in
  8084. // a terminal state (completed/failed/cancelled/partial_failure); in-flight
  8085. // runs are preserved.
  8086. clearTerminalPipelineRuns: () =>
  8087. request<{ deleted: number }>('/pipeline-runs/clear', { method: 'POST' }),
  8088. cancelPipelineRun: (runId: number) =>
  8089. request<PipelineRun>(`/pipeline-runs/${runId}/cancel`, { method: 'POST' }),
  8090. retryFailedPipelineRun: (runId: number) =>
  8091. request<PipelineRun>(`/pipeline-runs/${runId}/retry-failed`, { method: 'POST' }),
  8092. // Canonical Bambu printer-model registry — "Bambu Lab <model>" → short code.
  8093. // Single source of truth shared with backend (PRINTER_MODEL_MAP); the
  8094. // SliceModal uses this to classify cloud / standard presets by their
  8095. // `@BBL <code>` suffix against the selected printer-preset name (#1325).
  8096. getSlicerPrinterModels: () =>
  8097. request<Record<string, string>>('/slicer/printer-models'),
  8098. getSlicerLoadedSpools: () =>
  8099. request<LoadedSpoolsResponse>('/slicer/loaded-spools'),
  8100. /**
  8101. * Effective values of a process preset, with its `inherits:` chain flattened
  8102. * by the slicer sidecar. Powers the slice modal's settings panel, which would
  8103. * otherwise show the option schema's compiled-in defaults (a preset setting a
  8104. * 0.42mm line width appears as the C++ default of 0).
  8105. *
  8106. * `resolved: false` means the values could not be obtained -- sidecar offline,
  8107. * too old for the endpoint, or slicing not configured -- and the caller should
  8108. * fall back to schema defaults rather than treat it as a failure.
  8109. */
  8110. getSlicerPresetValues: (ref: PresetRef) =>
  8111. request<SlicerPresetValues>(
  8112. `/slicer/preset-values?source=${encodeURIComponent(ref.source)}&id=${encodeURIComponent(ref.id)}`,
  8113. ),
  8114. // Local Presets (OrcaSlicer imports)
  8115. getLocalPresets: () =>
  8116. request<LocalPresetsResponse>('/local-presets/'),
  8117. importLocalPresets: (formData: FormData) =>
  8118. fetch(`${API_BASE}/local-presets/import`, {
  8119. method: 'POST',
  8120. headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {},
  8121. body: formData,
  8122. }).then(async (res) => {
  8123. if (!res.ok) {
  8124. const err = await res.json().catch(() => ({}));
  8125. throw new Error(err.detail || `HTTP ${res.status}`);
  8126. }
  8127. return res.json() as Promise<ImportResponse>;
  8128. }),
  8129. deleteLocalPreset: (id: number) =>
  8130. request<{ success: boolean }>(`/local-presets/${id}`, { method: 'DELETE' }),
  8131. };
  8132. // AMS History types
  8133. export interface AMSHistoryPoint {
  8134. recorded_at: string;
  8135. humidity: number | null;
  8136. humidity_raw: number | null;
  8137. temperature: number | null;
  8138. }
  8139. export interface AMSHistoryResponse {
  8140. printer_id: number;
  8141. ams_id: number;
  8142. data: AMSHistoryPoint[];
  8143. min_humidity: number | null;
  8144. max_humidity: number | null;
  8145. avg_humidity: number | null;
  8146. min_temperature: number | null;
  8147. max_temperature: number | null;
  8148. avg_temperature: number | null;
  8149. }
  8150. export type HeaterSensorKind = 'nozzle' | 'nozzle_2' | 'bed' | 'chamber';
  8151. export interface HeaterHistoryPoint {
  8152. recorded_at: string;
  8153. value: number | null;
  8154. target: number | null;
  8155. }
  8156. export interface HeaterSeries {
  8157. sensor_kind: HeaterSensorKind;
  8158. data: HeaterHistoryPoint[];
  8159. min_value: number | null;
  8160. max_value: number | null;
  8161. avg_value: number | null;
  8162. }
  8163. export interface PrinterSensorHistoryResponse {
  8164. printer_id: number;
  8165. series: HeaterSeries[];
  8166. }
  8167. // System Info types
  8168. export interface SystemInfo {
  8169. app: {
  8170. version: string;
  8171. base_dir: string;
  8172. archive_dir: string;
  8173. };
  8174. database: {
  8175. engine: string;
  8176. version: string;
  8177. archives: number;
  8178. archives_completed: number;
  8179. archives_failed: number;
  8180. archives_printing: number;
  8181. printers: number;
  8182. filaments: number;
  8183. projects: number;
  8184. smart_plugs: number;
  8185. total_print_time_seconds: number;
  8186. total_print_time_formatted: string;
  8187. total_filament_grams: number;
  8188. total_filament_kg: number;
  8189. };
  8190. printers: {
  8191. total: number;
  8192. connected: number;
  8193. connected_list: Array<{
  8194. id: number;
  8195. name: string;
  8196. state: string;
  8197. model: string;
  8198. }>;
  8199. };
  8200. storage: {
  8201. archive_size_bytes: number;
  8202. archive_size_formatted: string;
  8203. database_size_bytes: number;
  8204. database_size_formatted: string;
  8205. disk_total_bytes: number;
  8206. disk_total_formatted: string;
  8207. disk_used_bytes: number;
  8208. disk_used_formatted: string;
  8209. disk_free_bytes: number;
  8210. disk_free_formatted: string;
  8211. disk_percent_used: number;
  8212. };
  8213. system: {
  8214. platform: string;
  8215. platform_release: string;
  8216. platform_version: string;
  8217. architecture: string;
  8218. hostname: string;
  8219. python_version: string;
  8220. uptime_seconds: number;
  8221. uptime_formatted: string;
  8222. boot_time: string;
  8223. };
  8224. memory: {
  8225. total_bytes: number;
  8226. total_formatted: string;
  8227. available_bytes: number;
  8228. available_formatted: string;
  8229. used_bytes: number;
  8230. used_formatted: string;
  8231. percent_used: number;
  8232. };
  8233. cpu: {
  8234. count: number;
  8235. count_logical: number;
  8236. percent: number;
  8237. };
  8238. }
  8239. export interface StorageUsageCategory {
  8240. key: string;
  8241. label: string;
  8242. bytes: number;
  8243. formatted: string;
  8244. percent_of_total: number;
  8245. }
  8246. export interface StorageUsageOtherItem {
  8247. bucket: string;
  8248. label: string;
  8249. kind: 'system' | 'data';
  8250. deletable: boolean;
  8251. bytes: number;
  8252. formatted: string;
  8253. percent_of_total: number;
  8254. }
  8255. export interface StorageUsageResponse {
  8256. roots: string[];
  8257. total_bytes: number;
  8258. total_formatted: string;
  8259. categories: StorageUsageCategory[];
  8260. other_breakdown: StorageUsageOtherItem[];
  8261. scan_errors: number;
  8262. generated_at: string;
  8263. cache: {
  8264. hit: boolean;
  8265. age_seconds: number;
  8266. max_age_seconds: number;
  8267. };
  8268. }
  8269. // Library (File Manager) types
  8270. export interface LibraryFolderTree {
  8271. id: number;
  8272. name: string;
  8273. parent_id: number | null;
  8274. project_id: number | null;
  8275. archive_id: number | null;
  8276. project_name: string | null;
  8277. archive_name: string | null;
  8278. is_external: boolean;
  8279. external_path: string | null;
  8280. external_readonly: boolean;
  8281. file_count: number;
  8282. // max(folder.updated_at, max(immediate-child file.updated_at)). Used by
  8283. // the File Manager folder tree's "sort by recent activity" mode (#1770).
  8284. latest_activity_at: string | null;
  8285. // Ownership (#3201). can_* are for the current user: what the File
  8286. // Manager may offer on this folder. The backend enforces the same rules.
  8287. created_by_id: number | null;
  8288. shared: boolean;
  8289. can_write: boolean;
  8290. can_rename: boolean;
  8291. can_delete: boolean;
  8292. children: LibraryFolderTree[];
  8293. }
  8294. export interface LibraryFolder {
  8295. id: number;
  8296. name: string;
  8297. parent_id: number | null;
  8298. project_id: number | null;
  8299. archive_id: number | null;
  8300. project_name: string | null;
  8301. archive_name: string | null;
  8302. is_external: boolean;
  8303. external_path: string | null;
  8304. external_readonly: boolean;
  8305. external_show_hidden: boolean;
  8306. file_count: number;
  8307. latest_activity_at: string | null;
  8308. // Ownership (#3201). can_* are for the current user: what the File
  8309. // Manager may offer on this folder. The backend enforces the same rules.
  8310. created_by_id: number | null;
  8311. shared: boolean;
  8312. can_write: boolean;
  8313. can_rename: boolean;
  8314. can_delete: boolean;
  8315. created_at: string;
  8316. updated_at: string;
  8317. }
  8318. export interface LibraryFolderCreate {
  8319. name: string;
  8320. parent_id?: number | null;
  8321. project_id?: number | null;
  8322. archive_id?: number | null;
  8323. }
  8324. export interface ExternalFolderCreate {
  8325. name: string;
  8326. external_path: string;
  8327. readonly?: boolean;
  8328. show_hidden?: boolean;
  8329. parent_id?: number | null;
  8330. }
  8331. export interface LibraryFolderUpdate {
  8332. name?: string;
  8333. parent_id?: number | null;
  8334. project_id?: number | null; // 0 to unlink
  8335. archive_id?: number | null; // 0 to unlink
  8336. shared?: boolean; // library:update_all only (#3201)
  8337. }
  8338. export interface LibraryFileDuplicate {
  8339. id: number;
  8340. filename: string;
  8341. folder_id: number | null;
  8342. folder_name: string | null;
  8343. created_at: string;
  8344. }
  8345. export interface LibraryFile {
  8346. id: number;
  8347. folder_id: number | null;
  8348. folder_name: string | null;
  8349. project_id: number | null;
  8350. project_name: string | null;
  8351. is_external: boolean;
  8352. filename: string;
  8353. file_path: string;
  8354. file_type: string;
  8355. file_size: number;
  8356. file_hash: string | null;
  8357. thumbnail_path: string | null;
  8358. metadata: Record<string, unknown> | null;
  8359. print_count: number;
  8360. last_printed_at: string | null;
  8361. notes: string | null;
  8362. // User link + photos of the printed result (#3077); source_url is the
  8363. // read-only import provenance (MakerWorld).
  8364. external_url: string | null;
  8365. photos: string[];
  8366. source_url: string | null;
  8367. duplicates: LibraryFileDuplicate[] | null;
  8368. duplicate_count: number;
  8369. // User tracking (Issue #206)
  8370. created_by_id: number | null;
  8371. created_by_username: string | null;
  8372. created_at: string;
  8373. updated_at: string;
  8374. // Metadata fields
  8375. print_name: string | null;
  8376. print_time_seconds: number | null;
  8377. filament_used_grams: number | null;
  8378. sliced_for_model: string | null;
  8379. }
  8380. export interface LibraryTagSummary {
  8381. id: number;
  8382. name: string;
  8383. }
  8384. export interface LibraryFileListItem {
  8385. id: number;
  8386. folder_id: number | null;
  8387. is_external: boolean;
  8388. filename: string;
  8389. file_type: string;
  8390. file_size: number;
  8391. thumbnail_path: string | null;
  8392. print_count: number;
  8393. duplicate_count: number;
  8394. // User tracking (Issue #206)
  8395. created_by_id: number | null;
  8396. created_by_username: string | null;
  8397. created_at: string;
  8398. // Real on-disk modification time (#2680). Null for managed uploads; the date
  8399. // sort and "Modified" column use `fs_modified_at ?? created_at`.
  8400. fs_modified_at: string | null;
  8401. print_name: string | null;
  8402. print_time_seconds: number | null;
  8403. filament_used_grams: number | null;
  8404. sliced_for_model: string | null;
  8405. // Tags assigned to this file (#1268). The backend always emits an empty
  8406. // array when a file has no tags, but the field is typed optional so any
  8407. // legacy code path (or mock) that constructs a LibraryFileListItem without
  8408. // it doesn't crash the renderer. Read sites use `file.tags ?? []`.
  8409. tags?: LibraryTagSummary[];
  8410. // Variant grouping (#671 / #2570). `variant_count` is the size of the whole
  8411. // group, which may include files in other folders — never the number of
  8412. // matching rows on screen. 0 when the file is not grouped.
  8413. variant_group_id?: number | null;
  8414. variant_count?: number;
  8415. // Metadata indicators (#3077). Optional for the same reason as `tags`: older
  8416. // mocks construct list items without them. Read sites default to falsy.
  8417. external_url?: string | null;
  8418. has_notes?: boolean;
  8419. photo_count?: number;
  8420. }
  8421. // Variant groups (#671 / #2570): the same job sliced for different printers.
  8422. export interface VariantGroupMember {
  8423. library_file_id: number;
  8424. filename: string;
  8425. target_model: string;
  8426. position: number;
  8427. }
  8428. export interface VariantGroup {
  8429. id: number;
  8430. name: string;
  8431. /** In priority order — index 0 wins when several printers are free at once. */
  8432. members: VariantGroupMember[];
  8433. }
  8434. // Library tag catalog (#1268)
  8435. export interface LibraryTag {
  8436. id: number;
  8437. name: string;
  8438. file_count: number;
  8439. created_at: string;
  8440. updated_at: string;
  8441. }
  8442. export interface LibraryTagBulkAssignResult {
  8443. files_updated: number;
  8444. associations_added: number;
  8445. associations_removed: number;
  8446. }
  8447. export interface LibraryFileUpdate {
  8448. filename?: string;
  8449. folder_id?: number | null;
  8450. project_id?: number | null;
  8451. notes?: string | null;
  8452. external_url?: string | null;
  8453. }
  8454. // Library trash (#1008)
  8455. export interface LibraryTrashItem {
  8456. id: number;
  8457. filename: string;
  8458. file_size: number;
  8459. thumbnail_path: string | null;
  8460. folder_id: number | null;
  8461. folder_name: string | null;
  8462. created_by_id: number | null;
  8463. created_by_username: string | null;
  8464. deleted_at: string;
  8465. auto_purge_at: string;
  8466. }
  8467. export interface LibraryTrashListResponse {
  8468. items: LibraryTrashItem[];
  8469. total: number;
  8470. retention_days: number;
  8471. }
  8472. export interface LibraryPurgePreview {
  8473. count: number;
  8474. total_bytes: number;
  8475. sample_filenames: string[];
  8476. older_than_days: number;
  8477. include_never_printed: boolean;
  8478. }
  8479. export interface LibraryTrashSettings {
  8480. retention_days: number;
  8481. auto_purge_enabled: boolean;
  8482. auto_purge_days: number;
  8483. auto_purge_include_never_printed: boolean;
  8484. }
  8485. export interface ArchivePurgePreview {
  8486. count: number;
  8487. total_bytes: number;
  8488. sample_filenames: string[];
  8489. older_than_days: number;
  8490. }
  8491. export interface ArchiveMergeMember {
  8492. id: number;
  8493. print_name: string | null;
  8494. filename: string;
  8495. created_at: string | null;
  8496. run_count: number;
  8497. }
  8498. /** Why a group is left out: at work now, or holding files only one can keep. */
  8499. export type ArchiveMergeSkip = 'busy' | 'conflicting_files' | 'failed' | 'not_a_group';
  8500. export interface ArchiveMergeGroup {
  8501. survivor: ArchiveMergeMember;
  8502. merged: ArchiveMergeMember[];
  8503. skipped: ArchiveMergeSkip | null;
  8504. }
  8505. export interface ArchiveMergePreview {
  8506. groups: ArchiveMergeGroup[];
  8507. }
  8508. export interface ArchiveMergeResult {
  8509. merged: { survivor_id: number; merged_ids: number[] }[];
  8510. skipped: { survivor_id: number; reason: ArchiveMergeSkip }[];
  8511. }
  8512. export interface ArchivePurgeSettings {
  8513. enabled: boolean;
  8514. days: number;
  8515. // #1390: when true, bulk-deletes the linked PrintLogEntry rows so the
  8516. // contribution drops from Quick Stats too. Default false — soft-delete,
  8517. // Quick Stats preserved.
  8518. purge_stats: boolean;
  8519. }
  8520. export interface LibraryFileUploadResponse {
  8521. id: number;
  8522. filename: string;
  8523. file_type: string;
  8524. file_size: number;
  8525. thumbnail_path: string | null;
  8526. duplicate_of: number | null;
  8527. metadata: Record<string, unknown> | null;
  8528. }
  8529. export interface LibraryStats {
  8530. total_files: number;
  8531. total_folders: number;
  8532. total_size_bytes: number;
  8533. files_by_type: Record<string, number>;
  8534. total_prints: number;
  8535. disk_free_bytes: number;
  8536. disk_total_bytes: number;
  8537. disk_used_bytes: number;
  8538. }
  8539. export interface ZipExtractResult {
  8540. filename: string;
  8541. file_id: number;
  8542. folder_id: number | null;
  8543. }
  8544. export interface ZipExtractError {
  8545. filename: string;
  8546. error: string;
  8547. }
  8548. export interface ZipExtractResponse {
  8549. extracted: number;
  8550. folders_created: number;
  8551. files: ZipExtractResult[];
  8552. errors: ZipExtractError[];
  8553. }
  8554. // STL Thumbnail Generation types
  8555. export interface BatchThumbnailResult {
  8556. file_id: number;
  8557. filename: string;
  8558. success: boolean;
  8559. error?: string | null;
  8560. }
  8561. export interface BatchThumbnailResponse {
  8562. processed: number;
  8563. succeeded: number;
  8564. failed: number;
  8565. results: BatchThumbnailResult[];
  8566. }
  8567. // Discovery types
  8568. export interface DiscoveredPrinter {
  8569. serial: string;
  8570. name: string;
  8571. ip_address: string;
  8572. model: string | null;
  8573. discovered_at: string | null;
  8574. }
  8575. export interface DiscoveryStatus {
  8576. running: boolean;
  8577. }
  8578. export interface DiscoveryInfo {
  8579. is_docker: boolean;
  8580. ssdp_running: boolean;
  8581. scan_running: boolean;
  8582. subnets: string[];
  8583. }
  8584. export interface SubnetScanStatus {
  8585. running: boolean;
  8586. scanned: number;
  8587. total: number;
  8588. }
  8589. // Discovery API
  8590. export const discoveryApi = {
  8591. getInfo: () => request<DiscoveryInfo>('/discovery/info'),
  8592. startDiscovery: (duration: number = 10) =>
  8593. request<DiscoveryStatus>(`/discovery/start?duration=${duration}`, { method: 'POST' }),
  8594. stopDiscovery: () =>
  8595. request<DiscoveryStatus>('/discovery/stop', { method: 'POST' }),
  8596. getDiscoveredPrinters: () =>
  8597. request<DiscoveredPrinter[]>('/discovery/printers'),
  8598. // Subnet scanning (for Docker environments)
  8599. startSubnetScan: (subnet: string, timeout: number = 1.0) =>
  8600. request<SubnetScanStatus>('/discovery/scan', {
  8601. method: 'POST',
  8602. body: JSON.stringify({ subnet, timeout }),
  8603. }),
  8604. getScanStatus: () => request<SubnetScanStatus>('/discovery/scan/status'),
  8605. stopSubnetScan: () =>
  8606. request<SubnetScanStatus>('/discovery/scan/stop', { method: 'POST' }),
  8607. };
  8608. // Virtual Printer types
  8609. // Canonical wire values: `archive`, `review`, `queue`, `proxy`. The legacy
  8610. // `immediate` (→ archive) and `print_queue` (→ queue) names are still
  8611. // accepted by the backend so older API clients keep working, but new code
  8612. // should send the canonical names.
  8613. export type VirtualPrinterMode = 'archive' | 'review' | 'queue' | 'proxy' | 'immediate' | 'print_queue';
  8614. export interface VirtualPrinterProxyStatus {
  8615. running: boolean;
  8616. target_host: string;
  8617. ftp_port: number;
  8618. mqtt_port: number;
  8619. ftp_connections: number;
  8620. mqtt_connections: number;
  8621. }
  8622. export interface VirtualPrinterStatus {
  8623. enabled: boolean;
  8624. running: boolean;
  8625. mode: VirtualPrinterMode;
  8626. name: string;
  8627. serial: string;
  8628. model: string;
  8629. model_name: string;
  8630. pending_files: number;
  8631. target_printer_ip?: string; // For proxy mode
  8632. proxy?: VirtualPrinterProxyStatus; // For proxy mode
  8633. }
  8634. export interface VirtualPrinterSettings {
  8635. tailscale_disabled: boolean;
  8636. archive_name_source: 'metadata' | 'filename'; // Source for archive's display name
  8637. status: VirtualPrinterStatus;
  8638. }
  8639. export interface NetworkInterface {
  8640. name: string;
  8641. ip: string;
  8642. netmask: string;
  8643. subnet: string;
  8644. is_alias?: boolean;
  8645. label?: string;
  8646. }
  8647. export interface PendingUpload {
  8648. id: number;
  8649. filename: string;
  8650. // Resolved name the review card should show — mirrors what archive_print
  8651. // will eventually write to PrintArchive.print_name (#1152 follow-up). Falls
  8652. // back to the stripped filename stem when the 3MF has no embedded title or
  8653. // the operator has chosen the "filename" archive-name source.
  8654. display_name: string;
  8655. file_size: number;
  8656. source_ip: string | null;
  8657. status: string;
  8658. tags: string | null;
  8659. notes: string | null;
  8660. project_id: number | null;
  8661. uploaded_at: string;
  8662. }
  8663. // Virtual Printer API
  8664. export const virtualPrinterApi = {
  8665. getSettings: () => request<VirtualPrinterSettings>('/settings/virtual-printer'),
  8666. updateSettings: (data: {
  8667. tailscale_disabled?: boolean;
  8668. archive_name_source?: 'metadata' | 'filename';
  8669. }) => {
  8670. const params = new URLSearchParams();
  8671. if (data.tailscale_disabled !== undefined) params.set('tailscale_disabled', String(data.tailscale_disabled));
  8672. if (data.archive_name_source !== undefined) params.set('archive_name_source', data.archive_name_source);
  8673. return request<VirtualPrinterSettings>(`/settings/virtual-printer?${params.toString()}`, {
  8674. method: 'PUT',
  8675. });
  8676. },
  8677. };
  8678. // Multi Virtual Printer API
  8679. export interface VirtualPrinterConfig {
  8680. id: number;
  8681. name: string;
  8682. enabled: boolean;
  8683. mode: VirtualPrinterMode;
  8684. model: string | null;
  8685. model_name: string | null;
  8686. access_code_set: boolean;
  8687. serial: string;
  8688. target_printer_id: number | null;
  8689. auto_dispatch: boolean;
  8690. queue_force_color_match: boolean;
  8691. save_ams_mapping: boolean;
  8692. gcode_injection: boolean;
  8693. tailscale_disabled: boolean;
  8694. bind_ip: string | null;
  8695. remote_interface_ip: string | null;
  8696. position: number;
  8697. status: { running: boolean; pending_files: number; proxy?: VirtualPrinterProxyStatus };
  8698. }
  8699. export interface VirtualPrinterListResponse {
  8700. printers: VirtualPrinterConfig[];
  8701. models: Record<string, string>;
  8702. }
  8703. export const multiVirtualPrinterApi = {
  8704. list: () => request<VirtualPrinterListResponse>('/virtual-printers'),
  8705. get: (id: number) => request<VirtualPrinterConfig>(`/virtual-printers/${id}`),
  8706. create: (data: {
  8707. name?: string;
  8708. enabled?: boolean;
  8709. mode?: string;
  8710. model?: string;
  8711. access_code?: string;
  8712. target_printer_id?: number;
  8713. auto_dispatch?: boolean;
  8714. queue_force_color_match?: boolean;
  8715. save_ams_mapping?: boolean;
  8716. gcode_injection?: boolean;
  8717. bind_ip?: string;
  8718. remote_interface_ip?: string;
  8719. }) =>
  8720. request<VirtualPrinterConfig>('/virtual-printers', {
  8721. method: 'POST',
  8722. body: JSON.stringify(data),
  8723. }),
  8724. update: (id: number, data: {
  8725. name?: string;
  8726. enabled?: boolean;
  8727. mode?: string;
  8728. model?: string;
  8729. access_code?: string;
  8730. target_printer_id?: number;
  8731. auto_dispatch?: boolean;
  8732. queue_force_color_match?: boolean;
  8733. save_ams_mapping?: boolean;
  8734. gcode_injection?: boolean;
  8735. tailscale_disabled?: boolean;
  8736. bind_ip?: string;
  8737. remote_interface_ip?: string;
  8738. }) =>
  8739. request<VirtualPrinterConfig>(`/virtual-printers/${id}`, {
  8740. method: 'PUT',
  8741. body: JSON.stringify(data),
  8742. }),
  8743. remove: (id: number) =>
  8744. request<{ detail: string; id: number }>(`/virtual-printers/${id}`, {
  8745. method: 'DELETE',
  8746. }),
  8747. getTailscaleStatus: () =>
  8748. request<TailscaleStatusResponse>('/virtual-printers/tailscale-status'),
  8749. getCaCertificate: () =>
  8750. request<VPCaCertificate>('/virtual-printers/ca-certificate'),
  8751. diagnose: (id: number) =>
  8752. request<VPDiagnosticResult>(`/virtual-printers/${id}/diagnostic`),
  8753. };
  8754. /** The shared CA certificate every virtual printer presents — imported once
  8755. * into the slicer's trust store. Only the public certificate is returned. */
  8756. export interface VPCaCertificate {
  8757. pem: string;
  8758. fingerprint_sha256: string;
  8759. not_valid_after: string;
  8760. }
  8761. export type VPDiagnosticStatus = 'pass' | 'fail' | 'warn' | 'skip';
  8762. export interface VPDiagnosticCheck {
  8763. id:
  8764. | 'enabled'
  8765. | 'running'
  8766. | 'bind_interface'
  8767. | 'access_code'
  8768. | 'target_printer'
  8769. | 'port_ftps'
  8770. | 'port_mqtt'
  8771. | 'port_bind'
  8772. | 'certificate';
  8773. status: VPDiagnosticStatus;
  8774. params: Record<string, string | number>;
  8775. }
  8776. export interface VPDiagnosticResult {
  8777. vp_id: number;
  8778. vp_name: string;
  8779. mode: string;
  8780. overall: 'ok' | 'warnings' | 'problems';
  8781. checks: VPDiagnosticCheck[];
  8782. }
  8783. export interface TailscaleStatusResponse {
  8784. available: boolean;
  8785. fqdn: string;
  8786. hostname: string;
  8787. tailnet_name: string;
  8788. tailscale_ips: string[];
  8789. error: string | null;
  8790. }
  8791. // Pending Uploads API
  8792. export const pendingUploadsApi = {
  8793. list: () => request<PendingUpload[]>('/pending-uploads/'),
  8794. getCount: () => request<{ count: number }>('/pending-uploads/count'),
  8795. get: (id: number) => request<PendingUpload>(`/pending-uploads/${id}`),
  8796. archive: (id: number, data?: { tags?: string; notes?: string; project_id?: number }) =>
  8797. request<{ id: number; print_name: string; filename: string }>(`/pending-uploads/${id}/archive`, {
  8798. method: 'POST',
  8799. body: JSON.stringify(data || {}),
  8800. }),
  8801. discard: (id: number) =>
  8802. request<{ success: boolean }>(`/pending-uploads/${id}`, { method: 'DELETE' }),
  8803. archiveAll: () =>
  8804. request<{ archived: number; failed: number }>('/pending-uploads/archive-all', { method: 'POST' }),
  8805. discardAll: () =>
  8806. request<{ discarded: number }>('/pending-uploads/discard-all', { method: 'DELETE' }),
  8807. };
  8808. // Firmware API Types
  8809. export interface AvailableFirmwareVersion {
  8810. version: string;
  8811. file_available: boolean;
  8812. download_url: string | null;
  8813. release_notes: string | null;
  8814. release_time: string | null;
  8815. }
  8816. export interface FirmwareUpdateInfo {
  8817. printer_id: number;
  8818. printer_name: string;
  8819. model: string | null;
  8820. current_version: string | null;
  8821. latest_version: string | null;
  8822. update_available: boolean;
  8823. download_url: string | null;
  8824. release_notes: string | null;
  8825. available_versions: AvailableFirmwareVersion[];
  8826. }
  8827. export interface FirmwareUploadPrepare {
  8828. can_proceed: boolean;
  8829. sd_card_present: boolean;
  8830. sd_card_free_space: number;
  8831. firmware_size: number;
  8832. space_sufficient: boolean;
  8833. update_available: boolean;
  8834. current_version: string | null;
  8835. latest_version: string | null;
  8836. target_version: string | null;
  8837. firmware_filename: string | null;
  8838. errors: string[];
  8839. }
  8840. export interface FirmwareUploadStatus {
  8841. status: 'idle' | 'preparing' | 'downloading' | 'uploading' | 'complete' | 'error';
  8842. progress: number;
  8843. message: string;
  8844. error: string | null;
  8845. firmware_filename: string | null;
  8846. firmware_version: string | null;
  8847. }
  8848. // Firmware API
  8849. export const firmwareApi = {
  8850. checkUpdates: () =>
  8851. request<{ updates: FirmwareUpdateInfo[]; updates_available: number }>('/firmware/updates'),
  8852. checkPrinterUpdate: (printerId: number) => firmwareUpdateBatch(printerId),
  8853. prepareUpload: (printerId: number, version?: string) =>
  8854. request<FirmwareUploadPrepare>(
  8855. `/firmware/updates/${printerId}/prepare${version ? `?version=${encodeURIComponent(version)}` : ''}`,
  8856. ),
  8857. startUpload: (printerId: number, version?: string) =>
  8858. request<{ started: boolean; message: string }>(
  8859. `/firmware/updates/${printerId}/upload${version ? `?version=${encodeURIComponent(version)}` : ''}`,
  8860. { method: 'POST' },
  8861. ),
  8862. getUploadStatus: (printerId: number) =>
  8863. request<FirmwareUploadStatus>(`/firmware/updates/${printerId}/upload/status`),
  8864. };
  8865. // Support types
  8866. export interface DebugLoggingState {
  8867. enabled: boolean;
  8868. enabled_at: string | null;
  8869. duration_seconds: number | null;
  8870. }
  8871. export interface LogEntry {
  8872. timestamp: string;
  8873. level: string;
  8874. logger_name: string;
  8875. message: string;
  8876. }
  8877. export interface LogsResponse {
  8878. entries: LogEntry[];
  8879. total_in_file: number;
  8880. filtered_count: number;
  8881. }
  8882. // Support API
  8883. export const supportApi = {
  8884. getDebugLoggingState: () =>
  8885. request<DebugLoggingState>('/support/debug-logging'),
  8886. setDebugLogging: (enabled: boolean) =>
  8887. request<DebugLoggingState>('/support/debug-logging', {
  8888. method: 'POST',
  8889. body: JSON.stringify({ enabled }),
  8890. }),
  8891. downloadSupportBundle: async () => {
  8892. const headers: Record<string, string> = {};
  8893. if (authToken) {
  8894. headers['Authorization'] = `Bearer ${authToken}`;
  8895. }
  8896. const response = await fetch(`${API_BASE}/support/bundle`, { headers });
  8897. if (!response.ok) {
  8898. const error = await response.json().catch(() => ({}));
  8899. throw new Error(error.detail || `HTTP ${response.status}`);
  8900. }
  8901. // Get filename from Content-Disposition header or use default
  8902. const disposition = response.headers.get('Content-Disposition');
  8903. const filename = parseContentDispositionFilename(disposition) || 'bambuddy-support.zip';
  8904. // Download the blob
  8905. const blob = await response.blob();
  8906. const url = window.URL.createObjectURL(blob);
  8907. const a = document.createElement('a');
  8908. a.href = url;
  8909. a.download = filename;
  8910. document.body.appendChild(a);
  8911. a.click();
  8912. document.body.removeChild(a);
  8913. window.URL.revokeObjectURL(url);
  8914. },
  8915. getLogs: (params?: { limit?: number; level?: string; search?: string }) => {
  8916. const searchParams = new URLSearchParams();
  8917. if (params?.limit) searchParams.set('limit', params.limit.toString());
  8918. if (params?.level) searchParams.set('level', params.level);
  8919. if (params?.search) searchParams.set('search', params.search);
  8920. const query = searchParams.toString();
  8921. return request<LogsResponse>(`/support/logs${query ? `?${query}` : ''}`);
  8922. },
  8923. clearLogs: () =>
  8924. request<{ message: string }>('/support/logs', { method: 'DELETE' }),
  8925. };
  8926. // SpoolBuddy types
  8927. export interface SpoolBuddyDevice {
  8928. id: number;
  8929. device_id: string;
  8930. hostname: string;
  8931. ip_address: string;
  8932. backend_url?: string | null;
  8933. firmware_version: string | null;
  8934. has_nfc: boolean;
  8935. has_scale: boolean;
  8936. tare_offset: number;
  8937. calibration_factor: number;
  8938. nfc_reader_type: string | null;
  8939. nfc_connection: string | null;
  8940. display_brightness: number;
  8941. display_blank_timeout: number;
  8942. has_backlight: boolean;
  8943. last_calibrated_at: string | null;
  8944. last_seen: string | null;
  8945. pending_command: string | null;
  8946. nfc_ok: boolean;
  8947. scale_ok: boolean;
  8948. uptime_s: number;
  8949. update_status: string | null;
  8950. update_message: string | null;
  8951. system_stats: {
  8952. os?: { os?: string; kernel?: string; arch?: string; python?: string };
  8953. cpu_temp_c?: number;
  8954. cpu_count?: number;
  8955. load_avg?: number[];
  8956. memory?: { total_mb?: number; available_mb?: number; used_mb?: number; percent?: number };
  8957. disk?: { total_gb?: number; used_gb?: number; free_gb?: number; percent?: number };
  8958. system_uptime_s?: number;
  8959. } | null;
  8960. online: boolean;
  8961. }
  8962. export interface DaemonUpdateCheck {
  8963. current_version: string;
  8964. latest_version: string | null;
  8965. update_available: boolean;
  8966. }
  8967. // SpoolBuddy API
  8968. export const spoolbuddyApi = {
  8969. getDevices: () =>
  8970. request<SpoolBuddyDevice[]>('/spoolbuddy/devices'),
  8971. deleteDevice: (deviceId: string) =>
  8972. request<{ status: string; device_id: string }>(`/spoolbuddy/devices/${deviceId}`, {
  8973. method: 'DELETE',
  8974. }),
  8975. tare: (deviceId: string) =>
  8976. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/calibration/tare`, {
  8977. method: 'POST',
  8978. body: '{}',
  8979. }),
  8980. setCalibrationFactor: (deviceId: string, knownWeightGrams: number, rawAdc: number, tareRawAdc?: number) =>
  8981. request<{ tare_offset: number; calibration_factor: number }>(`/spoolbuddy/devices/${deviceId}/calibration/set-factor`, {
  8982. method: 'POST',
  8983. body: JSON.stringify({ known_weight_grams: knownWeightGrams, raw_adc: rawAdc, tare_raw_adc: tareRawAdc }),
  8984. }),
  8985. updateSpoolWeight: (spoolId: number, weightGrams: number) =>
  8986. request<{ status: string; weight_used: number }>('/spoolbuddy/scale/update-spool-weight', {
  8987. method: 'POST',
  8988. body: JSON.stringify({ spool_id: spoolId, weight_grams: weightGrams }),
  8989. }),
  8990. updateDisplay: (deviceId: string, brightness: number, blankTimeout: number) =>
  8991. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/display`, {
  8992. method: 'PUT',
  8993. body: JSON.stringify({ brightness, blank_timeout: blankTimeout }),
  8994. }),
  8995. updateSystemConfig: (deviceId: string, backendUrl: string, apiKey?: string) =>
  8996. request<{ status: string; message: string }>(`/spoolbuddy/devices/${deviceId}/system/config`, {
  8997. method: 'POST',
  8998. body: JSON.stringify({ backend_url: backendUrl, ...(apiKey ? { api_key: apiKey } : {}) }),
  8999. }),
  9000. checkDaemonUpdate: (deviceId: string) =>
  9001. request<DaemonUpdateCheck>(`/spoolbuddy/devices/${deviceId}/update-check`),
  9002. triggerUpdate: (deviceId: string) =>
  9003. request<{ status: string; message: string }>(`/spoolbuddy/devices/${deviceId}/update`, {
  9004. method: 'POST',
  9005. body: '{}',
  9006. }),
  9007. getSSHPublicKey: () =>
  9008. request<{ public_key: string }>('/spoolbuddy/ssh/public-key'),
  9009. writeTag: (deviceId: string, spoolId: number) =>
  9010. request<{ status: string; warnings?: string[] }>('/spoolbuddy/nfc/write-tag', {
  9011. method: 'POST',
  9012. body: JSON.stringify({ device_id: deviceId, spool_id: spoolId }),
  9013. }),
  9014. cancelWrite: (deviceId: string) =>
  9015. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/cancel-write`, {
  9016. method: 'POST',
  9017. body: '{}',
  9018. }),
  9019. systemCommand: (deviceId: string, command: 'reboot' | 'shutdown' | 'restart_daemon' | 'restart_browser') =>
  9020. request<{ status: string; command: string }>(`/spoolbuddy/devices/${deviceId}/system/command`, {
  9021. method: 'POST',
  9022. body: JSON.stringify({ command }),
  9023. }),
  9024. queueDiagnostics: (deviceId: string, type: 'nfc' | 'scale' | 'read_tag') =>
  9025. request<{ status: string; diagnostic: string; message: string }>(
  9026. `/spoolbuddy/diagnostics/${deviceId}/run?diagnostic=${type}`,
  9027. { method: 'POST', body: '{}' }
  9028. ),
  9029. getDiagnosticResult: (deviceId: string, type: 'nfc' | 'scale' | 'read_tag') =>
  9030. request<{ diagnostic: string; success: boolean; output: string; exit_code: number }>(
  9031. `/spoolbuddy/diagnostics/${deviceId}/result?diagnostic=${type}`,
  9032. { method: 'GET' }
  9033. ),
  9034. };
  9035. export interface BugReportRequest {
  9036. description: string;
  9037. email?: string;
  9038. screenshot_base64?: string;
  9039. include_support_info?: boolean;
  9040. debug_logs?: string;
  9041. }
  9042. export interface BugReportResponse {
  9043. success: boolean;
  9044. message: string;
  9045. issue_url?: string;
  9046. issue_number?: number;
  9047. }
  9048. export const bugReportApi = {
  9049. submit: (data: BugReportRequest) =>
  9050. request<BugReportResponse>('/bug-report/submit', {
  9051. method: 'POST',
  9052. body: JSON.stringify(data),
  9053. }),
  9054. startLogging: () =>
  9055. request<{ started: boolean; was_debug: boolean }>('/bug-report/start-logging', {
  9056. method: 'POST',
  9057. }),
  9058. stopLogging: (wasDebug: boolean) =>
  9059. request<{ logs: string }>(`/bug-report/stop-logging?was_debug=${wasDebug}`, {
  9060. method: 'POST',
  9061. }),
  9062. };
  9063. export type AnnouncementLevel = 'info' | 'important' | 'critical';
  9064. export interface AnnouncementText {
  9065. title: string;
  9066. body: string;
  9067. link_label?: string;
  9068. }
  9069. // One message from the Bambuddy maintainers. `texts` holds every language the
  9070. // message was written in; English is always there.
  9071. export interface Announcement {
  9072. id: string;
  9073. level: AnnouncementLevel;
  9074. texts: Record<string, AnnouncementText>;
  9075. link_url: string | null;
  9076. published_at: string | null;
  9077. expires_at: string | null;
  9078. // Past its expiry: kept as history, listed under "Earlier", never unread.
  9079. archived: boolean;
  9080. read: boolean;
  9081. }
  9082. // `visible` says whether this user may see announcements at all (switched on,
  9083. // and admin or "show to all users"); it keeps the sidebar entry while nothing
  9084. // is published.
  9085. export interface AnnouncementList {
  9086. visible: boolean;
  9087. announcements: Announcement[];
  9088. }
  9089. export const announcementsApi = {
  9090. list: () => request<AnnouncementList>('/announcements'),
  9091. markRead: (id: string) =>
  9092. request<void>(`/announcements/${encodeURIComponent(id)}/read`, { method: 'POST' }),
  9093. };
  9094. export interface SponsorPromptCheckResponse {
  9095. show: boolean;
  9096. milestone?: string;
  9097. family?: 'prints' | 'cost' | 'archives' | 'anniversary' | 'version-update';
  9098. threshold?: number;
  9099. payload?: Record<string, unknown>;
  9100. }
  9101. export const sponsorPromptApi = {
  9102. check: () => request<SponsorPromptCheckResponse>('/sponsor-prompt/check'),
  9103. dismiss: (milestone: string) =>
  9104. request<void>('/sponsor-prompt/dismiss', {
  9105. method: 'POST',
  9106. body: JSON.stringify({ milestone }),
  9107. }),
  9108. };