client.ts 349 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775
  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. // A virtual printer's job not printed yet: the slicer's AMS pick it keeps
  2684. // for its archive, when made against this row's printer.
  2685. slicer_ams_mapping?: number[] | null;
  2686. ams_mapping: number[] | null; // AMS slot mapping for multi-color prints
  2687. 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
  2688. plate_id: number | null; // Plate ID for multi-plate 3MF files
  2689. // Print options
  2690. bed_levelling: CalibrationMode;
  2691. flow_cali: CalibrationMode;
  2692. vibration_cali: boolean;
  2693. layer_inspect: boolean;
  2694. timelapse: boolean;
  2695. use_ams: boolean;
  2696. nozzle_offset_cali: CalibrationMode;
  2697. // Ask for a post-print outcome verdict when this job completes (#1898)
  2698. confirm_outcome: boolean;
  2699. preheat_override: 'inherit' | 'on' | 'off';
  2700. preheat_chamber_target_override: number | null;
  2701. status: 'pending' | 'printing' | 'completed' | 'failed' | 'skipped' | 'cancelled';
  2702. started_at: string | null;
  2703. completed_at: string | null;
  2704. error_message: string | null;
  2705. created_at: string;
  2706. archive_name?: string | null;
  2707. archive_thumbnail?: string | null;
  2708. // True when the linked archive has been soft-deleted; archive_name /
  2709. // archive_thumbnail / downstream metadata are left null in that case so
  2710. // the UI doesn't 404-storm the now-missing endpoints (#1348 follow-up).
  2711. archive_deleted?: boolean;
  2712. library_file_name?: string | null;
  2713. library_file_thumbnail?: string | null;
  2714. printer_name?: string | null;
  2715. print_time_seconds?: number | null; // Estimated print time from archive or library file
  2716. filament_used_grams?: number | null; // Estimated print weight from archive or library file
  2717. filament_type?: string | null; // e.g. "PLA", "PETG"
  2718. filament_color?: string | null; // Hex RGBA from the slicer
  2719. bed_type?: string | null; // Build plate type for this print (per-plate accurate, #1281)
  2720. // User tracking (Issue #206)
  2721. created_by_id?: number | null;
  2722. created_by_username?: string | null;
  2723. // Batch grouping
  2724. batch_id?: number | null;
  2725. batch_name?: string | null;
  2726. // Shortest-job-first scheduling
  2727. been_jumped?: boolean;
  2728. // Auto-print G-code injection
  2729. gcode_injection?: boolean;
  2730. cleanup_library_after_dispatch?: boolean;
  2731. /** Which rack position each filament group prints from, on a nozzle-rack
  2732. * machine (#1784): `{ [group_id]: 1-based position }`. Re-checked against
  2733. * the live rack at dispatch; omit to have the dispatcher assign them. */
  2734. nozzle_rack_choice?: Record<number, number> | null;
  2735. /** Slots sent with a spool of another colour than the file asks for
  2736. * (#3279). Worked out when the job is sent; null when every slot got its
  2737. * colour or nothing could be compared. */
  2738. color_substitutions?: ColorSubstitution[] | null;
  2739. }
  2740. /** One slot printed in another colour than the file asked for (#3279). */
  2741. export interface ColorSubstitution {
  2742. slot_id: number;
  2743. type: string;
  2744. /** `#RRGGBB` the file asks for, after overrides. */
  2745. wanted: string;
  2746. /** `#RRGGBB` of the spool the slot was sent with. */
  2747. got: string;
  2748. tray: number;
  2749. }
  2750. export interface PrintBatchPlateTarget {
  2751. plate_id: number | null;
  2752. plate_name?: string | null;
  2753. quantity_target: number;
  2754. sort_order?: number;
  2755. }
  2756. export interface PrintBatchPlateProgress {
  2757. plate_id: number | null;
  2758. plate_name: string | null;
  2759. quantity_target: number;
  2760. dispatched: number;
  2761. remaining: number;
  2762. pending_count: number;
  2763. printing_count: number;
  2764. completed_count: number;
  2765. failed_count: number;
  2766. cancelled_count: number;
  2767. skipped_count: number;
  2768. /** Measured from finished runs; null until one has produced a cost. */
  2769. actual_cost: number | null;
  2770. estimated_remaining_cost: number | null;
  2771. filament_used_grams: number | null;
  2772. print_time_seconds: number;
  2773. /** False when this plate owes runs but has no queue item left to clone
  2774. * their configuration from, so queueing it could only fail (#2960). */
  2775. can_dispatch: boolean;
  2776. }
  2777. export interface PrintBatch {
  2778. id: number;
  2779. name: string;
  2780. archive_id: number | null;
  2781. library_file_id: number | null;
  2782. quantity: number;
  2783. status: string;
  2784. created_at: string;
  2785. completed_at: string | null;
  2786. created_by_id: number | null;
  2787. created_by_username: string | null;
  2788. project_id: number | null;
  2789. due_date: string | null;
  2790. notes: string | null;
  2791. /** Set when an integration (e.g. a shop connector) created the batch. */
  2792. external_source: string | null;
  2793. external_ref: string | null;
  2794. pending_count: number;
  2795. printing_count: number;
  2796. completed_count: number;
  2797. failed_count: number;
  2798. cancelled_count: number;
  2799. skipped_count: number;
  2800. /** False for batches created before per-plate targets existed (#342):
  2801. * they report progress but owe nothing and cannot be dispatched from. */
  2802. has_targets: boolean;
  2803. target_count: number;
  2804. remaining_count: number;
  2805. /** Of remaining_count, how many runs can actually be queued (#2960). */
  2806. dispatchable_count: number;
  2807. actual_cost: number | null;
  2808. estimated_remaining_cost: number | null;
  2809. filament_used_grams: number | null;
  2810. print_time_seconds: number;
  2811. plates: PrintBatchPlateProgress[];
  2812. }
  2813. export interface PrintQueueItemCreate {
  2814. printer_id?: number | null; // null = unassigned
  2815. target_model?: string | null; // Target printer model (mutually exclusive with printer_id)
  2816. target_location?: string | null; // Target location filter (only used with target_model)
  2817. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; tray_info_idx?: string; force_color_match?: boolean }> | null;
  2818. archive_id?: number | null;
  2819. library_file_id?: number | null;
  2820. scheduled_time?: string | null;
  2821. require_previous_success?: boolean;
  2822. auto_off_after?: boolean;
  2823. manual_start?: boolean; // Requires manual trigger to start (staged)
  2824. insert_at_top?: boolean; // Insert ahead of other pending items (one queue order across all printers, #3200)
  2825. insert_position?: number | null; // 1-indexed insertion position for priority queueing
  2826. // PrintModal "Print Anyway" on the deficit warning — persisted so the
  2827. // scheduler doesn't immediately re-flag this item (#1698-followup).
  2828. skip_filament_check?: boolean;
  2829. ams_mapping?: number[] | null; // AMS slot mapping for multi-color prints
  2830. plate_id?: number | null; // Plate ID for multi-plate 3MF files
  2831. // Print options
  2832. bed_levelling?: CalibrationMode;
  2833. flow_cali?: CalibrationMode;
  2834. vibration_cali?: boolean;
  2835. layer_inspect?: boolean;
  2836. timelapse?: boolean;
  2837. use_ams?: boolean;
  2838. nozzle_offset_cali?: CalibrationMode;
  2839. // Ask for a post-print outcome verdict when this job completes (#1898)
  2840. confirm_outcome?: boolean;
  2841. preheat_override?: 'inherit' | 'on' | 'off';
  2842. preheat_chamber_target_override?: number | null;
  2843. // Auto-print G-code injection
  2844. gcode_injection?: boolean;
  2845. // Batch: create multiple copies (creates a batch if > 1)
  2846. quantity?: number;
  2847. // Existing batch to add this item into (multi-plate auto-batch flow).
  2848. batch_id?: number | null;
  2849. // Project to associate the resulting archive with
  2850. project_id?: number;
  2851. cost_center_id?: number | null;
  2852. estimated_cost?: number | null;
  2853. // Delete transient uploaded library file after scheduler creates the archive
  2854. cleanup_library_after_dispatch?: boolean;
  2855. // Cross-model alternatives (#671): several sliced files, one job, whichever
  2856. // printer frees up first. Mutually exclusive with printer_id (a named printer
  2857. // defeats the point) and with archive_id/library_file_id (these ARE the files).
  2858. // Order is priority — index 0 wins when several printers are idle at once.
  2859. variants?: QueueVariantCreate[];
  2860. /** Which rack position each filament group prints from, on a nozzle-rack
  2861. * machine (#1784): `{ [group_id]: 1-based position }`. Re-checked against
  2862. * the live rack at dispatch; omit to have the dispatcher assign them. */
  2863. nozzle_rack_choice?: Record<number, number> | null;
  2864. }
  2865. /** One candidate file for a cross-model queue item (#671). */
  2866. export interface QueueVariantCreate {
  2867. library_file_id: number;
  2868. /** Read from the file's own sliced_for_model unless it declares none. */
  2869. target_model?: string | null;
  2870. plate_id?: number | null;
  2871. ams_mapping?: number[] | null;
  2872. nozzle_mapping?: number[] | null;
  2873. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; tray_info_idx?: string; force_color_match?: boolean }> | null;
  2874. }
  2875. export interface PrintBatchCreate {
  2876. name: string;
  2877. archive_id?: number | null;
  2878. library_file_id?: number | null;
  2879. /** When set, the listed pending items are assigned to the new batch
  2880. * (manual "Group as batch"). When omitted/empty, an empty batch is
  2881. * returned so the client can pass batch_id on subsequent addToQueue calls. */
  2882. item_ids?: number[];
  2883. /** Per-plate targets. Omitting them creates a plain grouping batch. */
  2884. plates?: PrintBatchPlateTarget[];
  2885. project_id?: number | null;
  2886. due_date?: string | null;
  2887. notes?: string | null;
  2888. }
  2889. export interface PrintBatchUpdate {
  2890. name?: string;
  2891. status?: 'active' | 'cancelled';
  2892. /** Replaces the full target set — a plate omitted here is removed. */
  2893. plates?: PrintBatchPlateTarget[];
  2894. project_id?: number | null;
  2895. due_date?: string | null;
  2896. notes?: string | null;
  2897. }
  2898. export interface PrintBatchDispatchRequest {
  2899. plate_id?: number | null;
  2900. only_plate?: boolean;
  2901. /** Cap on items created across all plates; omit to queue everything owed. */
  2902. limit?: number;
  2903. }
  2904. export interface PrintQueueItemUpdate {
  2905. printer_id?: number | null; // null = unassign
  2906. // A deliberate filament substitution in the mapping (#2799); see PrintModal.
  2907. skip_filament_check?: boolean;
  2908. target_model?: string | null; // Target printer model (mutually exclusive with printer_id)
  2909. target_location?: string | null; // Target location filter (only used with target_model)
  2910. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; tray_info_idx?: string; force_color_match?: boolean }> | null;
  2911. position?: number;
  2912. scheduled_time?: string | null;
  2913. require_previous_success?: boolean;
  2914. auto_off_after?: boolean;
  2915. manual_start?: boolean;
  2916. ams_mapping?: number[];
  2917. plate_id?: number | null; // Plate ID for multi-plate 3MF files
  2918. // Print options
  2919. bed_levelling?: CalibrationMode;
  2920. flow_cali?: CalibrationMode;
  2921. vibration_cali?: boolean;
  2922. layer_inspect?: boolean;
  2923. timelapse?: boolean;
  2924. use_ams?: boolean;
  2925. nozzle_offset_cali?: CalibrationMode;
  2926. // Ask for a post-print outcome verdict when this job completes (#1898)
  2927. confirm_outcome?: boolean;
  2928. preheat_override?: 'inherit' | 'on' | 'off';
  2929. preheat_chamber_target_override?: number | null;
  2930. // Auto-print G-code injection
  2931. gcode_injection?: boolean;
  2932. cost_center_id?: number | null;
  2933. estimated_cost?: number | null;
  2934. /** Which rack position each filament group prints from, on a nozzle-rack
  2935. * machine (#1784): `{ [group_id]: 1-based position }`. Re-checked against
  2936. * the live rack at dispatch; omit to have the dispatcher assign them. */
  2937. nozzle_rack_choice?: Record<number, number> | null;
  2938. }
  2939. export interface PrintQueueBulkUpdate {
  2940. item_ids: number[];
  2941. printer_id?: number | null;
  2942. scheduled_time?: string | null;
  2943. require_previous_success?: boolean;
  2944. auto_off_after?: boolean;
  2945. manual_start?: boolean;
  2946. // Print options
  2947. bed_levelling?: CalibrationMode;
  2948. flow_cali?: CalibrationMode;
  2949. vibration_cali?: boolean;
  2950. layer_inspect?: boolean;
  2951. timelapse?: boolean;
  2952. use_ams?: boolean;
  2953. nozzle_offset_cali?: CalibrationMode;
  2954. // Ask for a post-print outcome verdict when this job completes (#1898)
  2955. confirm_outcome?: boolean;
  2956. preheat_override?: 'inherit' | 'on' | 'off';
  2957. preheat_chamber_target_override?: number | null;
  2958. // Auto-print G-code injection
  2959. gcode_injection?: boolean;
  2960. cost_center_id?: number | null;
  2961. estimated_cost?: number | null;
  2962. }
  2963. export interface PrintQueueBulkUpdateResponse {
  2964. updated_count: number;
  2965. skipped_count: number;
  2966. message: string;
  2967. }
  2968. // MQTT Logging types
  2969. export interface MQTTLogEntry {
  2970. timestamp: string;
  2971. topic: string;
  2972. direction: 'in' | 'out';
  2973. payload: Record<string, unknown>;
  2974. }
  2975. export interface MQTTLogsResponse {
  2976. logging_enabled: boolean;
  2977. logs: MQTTLogEntry[];
  2978. }
  2979. // K-Profile types
  2980. export interface KProfile {
  2981. slot_id: number;
  2982. extruder_id: number;
  2983. nozzle_id: string;
  2984. nozzle_diameter: string;
  2985. filament_id: string;
  2986. name: string;
  2987. k_value: string;
  2988. n_coef: string;
  2989. ams_id: number;
  2990. tray_id: number;
  2991. setting_id: string | null;
  2992. }
  2993. export interface KProfileCreate {
  2994. slot_id?: number; // Storage slot, 0 for new profiles
  2995. extruder_id?: number;
  2996. nozzle_id: string;
  2997. nozzle_diameter: string;
  2998. filament_id: string;
  2999. name: string;
  3000. k_value: string;
  3001. n_coef?: string;
  3002. ams_id?: number;
  3003. tray_id?: number;
  3004. setting_id?: string | null;
  3005. }
  3006. export interface KProfileDelete {
  3007. slot_id: number; // cali_idx - calibration index to delete
  3008. extruder_id: number;
  3009. nozzle_id: string; // e.g., "HH00-0.4"
  3010. nozzle_diameter: string; // e.g., "0.4"
  3011. filament_id: string; // Bambu filament identifier
  3012. setting_id?: string | null; // Setting ID (for X1C series)
  3013. }
  3014. export interface KProfilesResponse {
  3015. profiles: KProfile[];
  3016. nozzle_diameter: string;
  3017. }
  3018. export interface KProfileNote {
  3019. setting_id: string;
  3020. note: string;
  3021. }
  3022. export interface KProfileNotesResponse {
  3023. notes: Record<string, string>; // setting_id -> note
  3024. }
  3025. // Slot Preset Mapping
  3026. export interface SlotPresetMapping {
  3027. ams_id: number;
  3028. tray_id: number;
  3029. preset_id: string;
  3030. preset_name: string;
  3031. // Filament id the slot was configured with alongside this preset; null for
  3032. // rows that predate it or whose writer did not know it (#3216).
  3033. tray_info_idx?: string | null;
  3034. }
  3035. // Filament types
  3036. export interface Filament {
  3037. id: number;
  3038. name: string;
  3039. type: string; // PLA, PETG, ABS, etc.
  3040. brand: string | null;
  3041. color: string | null;
  3042. color_hex: string | null;
  3043. cost_per_kg: number;
  3044. spool_weight_g: number;
  3045. currency: string;
  3046. density: number | null;
  3047. print_temp_min: number | null;
  3048. print_temp_max: number | null;
  3049. bed_temp_min: number | null;
  3050. bed_temp_max: number | null;
  3051. created_at: string;
  3052. updated_at: string;
  3053. }
  3054. // Notification Provider types
  3055. export type ProviderType = 'callmebot' | 'ntfy' | 'pushover' | 'telegram' | 'email' | 'discord' | 'webhook' | 'homeassistant' | 'bark' | 'gotify' | 'notify';
  3056. // How a Telegram provider collects the outcome verdict (#3046)
  3057. export type TelegramVerdictMode = 'buttons' | 'reactions' | 'both';
  3058. export interface NotificationProvider {
  3059. id: number;
  3060. name: string;
  3061. provider_type: ProviderType;
  3062. enabled: boolean;
  3063. config: Record<string, unknown>;
  3064. attach_photo: boolean;
  3065. // Print lifecycle events
  3066. on_print_start: boolean;
  3067. on_print_complete: boolean;
  3068. on_print_failed: boolean;
  3069. on_print_stopped: boolean;
  3070. on_print_progress: boolean;
  3071. on_print_missing_spool_assignment: boolean;
  3072. on_billing_charge_failed: boolean;
  3073. // Printer status events
  3074. on_printer_offline: boolean;
  3075. on_printer_error: boolean;
  3076. on_ai_failure_detection: boolean;
  3077. on_filament_low: boolean;
  3078. on_maintenance_due: boolean;
  3079. // AMS environmental alarms (regular AMS)
  3080. on_ams_humidity_high: boolean;
  3081. on_ams_temperature_high: boolean;
  3082. on_ams_drying_suspended: boolean;
  3083. // AMS-HT environmental alarms
  3084. on_ams_ht_humidity_high: boolean;
  3085. on_ams_ht_temperature_high: boolean;
  3086. // Build plate detection
  3087. on_plate_not_empty: boolean;
  3088. on_plate_clear_required: boolean;
  3089. // Post-print outcome confirmation (#1898)
  3090. on_print_confirm_request: boolean;
  3091. telegram_verdict_mode: TelegramVerdictMode;
  3092. // Bed cooled
  3093. on_bed_cooled: boolean;
  3094. on_ha_sensor_alert: boolean;
  3095. on_location_ha_sensor_alert: boolean;
  3096. // First layer complete
  3097. on_first_layer_complete: boolean;
  3098. on_print_pause_upcoming: boolean;
  3099. on_app_message: boolean;
  3100. // Inventory stock alerts
  3101. on_stock_reorder_alert: boolean;
  3102. on_stock_break_alert: boolean;
  3103. // Print queue events
  3104. on_queue_job_added: boolean;
  3105. on_queue_job_assigned: boolean;
  3106. on_queue_job_started: boolean;
  3107. on_queue_job_waiting: boolean;
  3108. on_queue_job_skipped: boolean;
  3109. on_queue_job_failed: boolean;
  3110. on_queue_completed: boolean;
  3111. // Quiet hours
  3112. quiet_hours_enabled: boolean;
  3113. quiet_hours_start: string | null;
  3114. quiet_hours_end: string | null;
  3115. // Daily digest
  3116. daily_digest_enabled: boolean;
  3117. daily_digest_time: string | null;
  3118. // Printer filter
  3119. printer_id: number | null;
  3120. // Status tracking
  3121. last_success: string | null;
  3122. last_error: string | null;
  3123. last_error_at: string | null;
  3124. // Timestamps
  3125. created_at: string;
  3126. updated_at: string;
  3127. }
  3128. export interface NotificationProviderCreate {
  3129. name: string;
  3130. provider_type: ProviderType;
  3131. enabled?: boolean;
  3132. config: Record<string, unknown>;
  3133. attach_photo?: boolean;
  3134. // Print lifecycle events
  3135. on_print_start?: boolean;
  3136. on_print_complete?: boolean;
  3137. on_print_failed?: boolean;
  3138. on_print_stopped?: boolean;
  3139. on_print_progress?: boolean;
  3140. on_print_missing_spool_assignment?: boolean;
  3141. on_billing_charge_failed?: boolean;
  3142. // Printer status events
  3143. on_printer_offline?: boolean;
  3144. on_printer_error?: boolean;
  3145. on_ai_failure_detection?: boolean;
  3146. on_filament_low?: boolean;
  3147. on_maintenance_due?: boolean;
  3148. // AMS environmental alarms (regular AMS)
  3149. on_ams_humidity_high?: boolean;
  3150. on_ams_temperature_high?: boolean;
  3151. on_ams_drying_suspended?: boolean;
  3152. // AMS-HT environmental alarms
  3153. on_ams_ht_humidity_high?: boolean;
  3154. on_ams_ht_temperature_high?: boolean;
  3155. // Build plate detection
  3156. on_plate_not_empty?: boolean;
  3157. on_plate_clear_required?: boolean;
  3158. // Post-print outcome confirmation (#1898)
  3159. on_print_confirm_request?: boolean;
  3160. telegram_verdict_mode?: TelegramVerdictMode;
  3161. // Bed cooled
  3162. on_bed_cooled?: boolean;
  3163. on_ha_sensor_alert?: boolean;
  3164. on_location_ha_sensor_alert?: boolean;
  3165. // First layer complete
  3166. on_first_layer_complete?: boolean;
  3167. on_print_pause_upcoming?: boolean;
  3168. on_app_message?: boolean;
  3169. // Inventory stock alerts
  3170. on_stock_reorder_alert?: boolean;
  3171. on_stock_break_alert?: boolean;
  3172. // Print queue events
  3173. on_queue_job_added?: boolean;
  3174. on_queue_job_assigned?: boolean;
  3175. on_queue_job_started?: boolean;
  3176. on_queue_job_waiting?: boolean;
  3177. on_queue_job_skipped?: boolean;
  3178. on_queue_job_failed?: boolean;
  3179. on_queue_completed?: boolean;
  3180. // Quiet hours
  3181. quiet_hours_enabled?: boolean;
  3182. quiet_hours_start?: string | null;
  3183. quiet_hours_end?: string | null;
  3184. // Daily digest
  3185. daily_digest_enabled?: boolean;
  3186. daily_digest_time?: string | null;
  3187. // Printer filter
  3188. printer_id?: number | null;
  3189. }
  3190. export interface NotificationProviderUpdate {
  3191. name?: string;
  3192. provider_type?: ProviderType;
  3193. enabled?: boolean;
  3194. config?: Record<string, unknown>;
  3195. attach_photo?: boolean;
  3196. // Print lifecycle events
  3197. on_print_start?: boolean;
  3198. on_print_complete?: boolean;
  3199. on_print_failed?: boolean;
  3200. on_print_stopped?: boolean;
  3201. on_print_progress?: boolean;
  3202. on_print_missing_spool_assignment?: boolean;
  3203. on_billing_charge_failed?: boolean;
  3204. // Printer status events
  3205. on_printer_offline?: boolean;
  3206. on_printer_error?: boolean;
  3207. on_ai_failure_detection?: boolean;
  3208. on_filament_low?: boolean;
  3209. on_maintenance_due?: boolean;
  3210. // AMS environmental alarms (regular AMS)
  3211. on_ams_humidity_high?: boolean;
  3212. on_ams_temperature_high?: boolean;
  3213. on_ams_drying_suspended?: boolean;
  3214. // AMS-HT environmental alarms
  3215. on_ams_ht_humidity_high?: boolean;
  3216. on_ams_ht_temperature_high?: boolean;
  3217. // Build plate detection
  3218. on_plate_not_empty?: boolean;
  3219. on_plate_clear_required?: boolean;
  3220. // Post-print outcome confirmation (#1898)
  3221. on_print_confirm_request?: boolean;
  3222. telegram_verdict_mode?: TelegramVerdictMode;
  3223. // Bed cooled
  3224. on_bed_cooled?: boolean;
  3225. on_ha_sensor_alert?: boolean;
  3226. on_location_ha_sensor_alert?: boolean;
  3227. // First layer complete
  3228. on_first_layer_complete?: boolean;
  3229. on_print_pause_upcoming?: boolean;
  3230. on_app_message?: boolean;
  3231. // Inventory stock alerts
  3232. on_stock_reorder_alert?: boolean;
  3233. on_stock_break_alert?: boolean;
  3234. // Print queue events
  3235. on_queue_job_added?: boolean;
  3236. on_queue_job_assigned?: boolean;
  3237. on_queue_job_started?: boolean;
  3238. on_queue_job_waiting?: boolean;
  3239. on_queue_job_skipped?: boolean;
  3240. on_queue_job_failed?: boolean;
  3241. on_queue_completed?: boolean;
  3242. // Quiet hours
  3243. quiet_hours_enabled?: boolean;
  3244. quiet_hours_start?: string | null;
  3245. quiet_hours_end?: string | null;
  3246. // Daily digest
  3247. daily_digest_enabled?: boolean;
  3248. daily_digest_time?: string | null;
  3249. // Printer filter
  3250. printer_id?: number | null;
  3251. }
  3252. // GitHub Backup types
  3253. export type ScheduleType = 'hourly' | 'daily' | 'weekly';
  3254. export type GitProviderType = 'github' | 'gitea' | 'forgejo' | 'gitlab';
  3255. /** How many cloud accounts a backup would collect presets from. Counts only —
  3256. * with auth enabled the accounts belong to individual users, so the backup
  3257. * administrator sees how many, never whose. */
  3258. export interface CloudAccountCounts {
  3259. bambu: number;
  3260. orca: number;
  3261. }
  3262. export interface GitHubBackupConfig {
  3263. id: number;
  3264. repository_url: string;
  3265. has_token: boolean;
  3266. branch: string;
  3267. provider: GitProviderType;
  3268. allow_insecure_http: boolean;
  3269. schedule_enabled: boolean;
  3270. schedule_type: ScheduleType;
  3271. backup_kprofiles: boolean;
  3272. backup_cloud_profiles: boolean;
  3273. backup_settings: boolean;
  3274. backup_spools: boolean;
  3275. backup_archives: boolean;
  3276. enabled: boolean;
  3277. last_backup_at: string | null;
  3278. last_backup_status: string | null;
  3279. last_backup_message: string | null;
  3280. last_backup_commit_sha: string | null;
  3281. next_scheduled_run: string | null;
  3282. created_at: string;
  3283. updated_at: string;
  3284. }
  3285. export interface GitHubBackupConfigCreate {
  3286. repository_url: string;
  3287. access_token: string;
  3288. branch?: string;
  3289. provider?: GitProviderType;
  3290. allow_insecure_http?: boolean;
  3291. schedule_enabled?: boolean;
  3292. schedule_type?: ScheduleType;
  3293. backup_kprofiles?: boolean;
  3294. backup_cloud_profiles?: boolean;
  3295. backup_settings?: boolean;
  3296. backup_spools?: boolean;
  3297. backup_archives?: boolean;
  3298. enabled?: boolean;
  3299. }
  3300. export interface GitHubBackupLog {
  3301. id: number;
  3302. config_id: number;
  3303. started_at: string;
  3304. completed_at: string | null;
  3305. status: string;
  3306. trigger: string;
  3307. commit_sha: string | null;
  3308. files_changed: number;
  3309. error_message: string | null;
  3310. }
  3311. export interface GitHubBackupStatus {
  3312. configured: boolean;
  3313. enabled: boolean;
  3314. is_running: boolean;
  3315. restore_running: boolean;
  3316. progress: string | null;
  3317. last_backup_at: string | null;
  3318. last_backup_status: string | null;
  3319. next_scheduled_run: string | null;
  3320. }
  3321. // Restore from a Git backup (#2656). Cloud profiles are absent deliberately —
  3322. // the backup collector never writes them, so there is nothing to restore.
  3323. export type RestoreCategory = 'kprofiles' | 'settings' | 'spools' | 'archives';
  3324. export interface GitHubCommitInfo {
  3325. sha: string;
  3326. message: string;
  3327. author: string;
  3328. date: string;
  3329. }
  3330. export interface GitHubCommitListResponse {
  3331. success: boolean;
  3332. message: string;
  3333. branch: string;
  3334. commits: GitHubCommitInfo[];
  3335. }
  3336. /**
  3337. * Values the server interpolates into a translated note or preview detail.
  3338. * Kept to strings and numbers on purpose — anything richer would have to be
  3339. * formatted server-side and could not be translated.
  3340. */
  3341. export type GitHubRestoreParams = Record<string, string | number>;
  3342. export interface GitHubRestorePreviewCategory {
  3343. category: RestoreCategory;
  3344. available: boolean;
  3345. item_count: number;
  3346. /** English rendering. Used as i18next's defaultValue, never shown on its own. */
  3347. detail: string | null;
  3348. /** Key under backup.restoreFromGit.details, or null when there is no caveat. */
  3349. detail_code: string | null;
  3350. detail_params: GitHubRestoreParams;
  3351. }
  3352. export interface GitHubRestorePreview {
  3353. success: boolean;
  3354. message: string;
  3355. ref: string;
  3356. commit: GitHubCommitInfo | null;
  3357. metadata_version: string | null;
  3358. categories: GitHubRestorePreviewCategory[];
  3359. }
  3360. export interface GitHubRestoreRequest {
  3361. ref?: string;
  3362. categories: RestoreCategory[];
  3363. overwrite_existing?: boolean;
  3364. }
  3365. /**
  3366. * One tally note, as a translation code plus its parameters (#2656).
  3367. *
  3368. * Same contract as {@link LocalBackupPathCheck} one card down: the server picks
  3369. * the code and supplies typed params, and the client renders
  3370. * ``t(`backup.restoreFromGit.notes.${code}`, { ...params, defaultValue: message })``.
  3371. * A code the client does not know yet falls back to the English `message`
  3372. * rather than showing the raw key.
  3373. */
  3374. export interface GitHubRestoreNote {
  3375. code: string;
  3376. params: GitHubRestoreParams;
  3377. message: string;
  3378. }
  3379. export interface GitHubRestoreCategoryResult {
  3380. restored: number;
  3381. skipped: number;
  3382. failed: number;
  3383. notes: GitHubRestoreNote[];
  3384. }
  3385. export interface GitHubRestoreResponse {
  3386. success: boolean;
  3387. message: string;
  3388. log_id: number | null;
  3389. ref: string | null;
  3390. results: Record<string, GitHubRestoreCategoryResult>;
  3391. }
  3392. export interface LocalBackupStatus {
  3393. enabled: boolean;
  3394. schedule: string;
  3395. time: string;
  3396. retention: number;
  3397. path: string;
  3398. default_path: string;
  3399. is_running: boolean;
  3400. last_backup_at: string | null;
  3401. last_status: string | null;
  3402. last_message: string | null;
  3403. next_run: string | null;
  3404. timezone: string;
  3405. }
  3406. export interface LocalBackupFile {
  3407. filename: string;
  3408. size: number;
  3409. created_at: string;
  3410. }
  3411. /** Result of writing a probe file into the configured backup directory (#2544). */
  3412. export interface LocalBackupPathCheck {
  3413. writable: boolean;
  3414. path: string;
  3415. /** 'ok' | 'sandboxed' | 'read_only' | 'permission_denied' | 'no_space' | 'not_a_directory' | 'missing' | 'error' */
  3416. code: string;
  3417. /** Raw OS error, shown as-is under the translated explanation. */
  3418. detail: string | null;
  3419. /** Copy-pasteable fix (systemd drop-in, compose snippet) — not translated. */
  3420. remedy: string | null;
  3421. message: string;
  3422. /** 'container_ephemeral' — writable, but the backups die with the container. */
  3423. warning: string | null;
  3424. }
  3425. export interface ObicoDetectionEvent {
  3426. printer_id: number;
  3427. task_name: string;
  3428. timestamp: string;
  3429. current_p: number;
  3430. score: number;
  3431. class: 'safe' | 'warning' | 'failure';
  3432. detections: number;
  3433. }
  3434. export interface ObicoStatus {
  3435. is_running: boolean;
  3436. last_error: string | null;
  3437. per_printer: Record<string, { class: string; frame_count: number; score: number }>;
  3438. thresholds: { low: number; high: number; pause?: number };
  3439. history: ObicoDetectionEvent[];
  3440. enabled: boolean;
  3441. ml_url: string;
  3442. sensitivity: 'low' | 'medium' | 'high';
  3443. action: 'notify' | 'pause' | 'pause_and_off';
  3444. poll_interval: number;
  3445. external_url_configured: boolean;
  3446. }
  3447. // Lightweight subset served under printers:read for the printer-card badge (#1546)
  3448. export interface ObicoPrinterStatus {
  3449. enabled: boolean;
  3450. // null = all printers are monitored
  3451. monitored_printers: number[] | null;
  3452. per_printer: Record<string, { class: string; frame_count: number; score: number }>;
  3453. // null = no error, or the viewer lacks settings:read (error strings can embed config URLs)
  3454. last_error: string | null;
  3455. }
  3456. export interface ObicoTestConnection {
  3457. ok: boolean;
  3458. status_code: number | null;
  3459. body: string | null;
  3460. error: string | null;
  3461. // Whether the ML API accepted the token. null = not determined (the health
  3462. // check failed first, or the token probe itself errored).
  3463. auth_ok: boolean | null;
  3464. }
  3465. // How sure Gadget must be before suggesting a warning or pause (API levels 1-5).
  3466. export type OctoEverywhereConfidence = 'lowest' | 'low' | 'medium' | 'high' | 'highest';
  3467. export interface OctoEverywhereDetection {
  3468. class: 'safe' | 'warning' | 'failure' | 'error' | 'unknown';
  3469. print_quality: number | null;
  3470. frame_count: number;
  3471. error?: string | null;
  3472. error_code: string | null;
  3473. }
  3474. export interface OctoEverywhereDetectionEvent {
  3475. timestamp: string;
  3476. printer_id: number;
  3477. class: OctoEverywhereDetection['class'];
  3478. print_quality: number | null;
  3479. }
  3480. export interface OctoEverywhereStatus {
  3481. enabled: boolean;
  3482. api_key_configured: boolean;
  3483. confidence: OctoEverywhereConfidence;
  3484. action: 'notify' | 'pause' | 'pause_and_off';
  3485. poll_interval: number;
  3486. is_running: boolean;
  3487. last_error: string | null;
  3488. last_error_code: string | null;
  3489. per_printer: Record<string, OctoEverywhereDetection>;
  3490. history: OctoEverywhereDetectionEvent[];
  3491. notifications: { configured: boolean; uncovered_printers: number[] };
  3492. }
  3493. export interface OctoEverywherePrinterStatus {
  3494. enabled: boolean;
  3495. // null = all printers are monitored
  3496. monitored_printers: number[] | null;
  3497. per_printer: Record<string, OctoEverywhereDetection>;
  3498. last_error: string | null;
  3499. last_error_code: string | null;
  3500. }
  3501. export interface OctoEverywhereTestConnection {
  3502. ok: boolean;
  3503. status_code: number | null;
  3504. error: string | null;
  3505. error_code: string | null;
  3506. }
  3507. export interface GitHubTestConnectionResponse {
  3508. success: boolean;
  3509. message: string;
  3510. repo_name: string | null;
  3511. permissions: Record<string, boolean> | null;
  3512. // true = confirmed private, false = confirmed public/internal,
  3513. // null = could not determine. Backend rejects save unless true.
  3514. is_private: boolean | null;
  3515. }
  3516. export interface GitHubBackupTriggerResponse {
  3517. success: boolean;
  3518. message: string;
  3519. log_id: number | null;
  3520. commit_sha: string | null;
  3521. files_changed: number;
  3522. }
  3523. export interface NotificationTestRequest {
  3524. provider_type: ProviderType;
  3525. config: Record<string, unknown>;
  3526. attach_photo?: boolean;
  3527. /** The saved provider being edited: its stored secrets fill in the placeholders. */
  3528. provider_id?: number;
  3529. }
  3530. export interface NotificationTestResponse {
  3531. success: boolean;
  3532. message: string;
  3533. }
  3534. // Provider-specific config types for reference
  3535. export interface CallMeBotConfig {
  3536. phone: string;
  3537. apikey: string;
  3538. }
  3539. export interface NtfyConfig {
  3540. server?: string;
  3541. topic: string;
  3542. auth_token?: string | null;
  3543. }
  3544. export interface PushoverConfig {
  3545. user_key: string;
  3546. app_token: string;
  3547. priority?: number;
  3548. }
  3549. export interface NotifyConfig {
  3550. device_id: string;
  3551. token: string;
  3552. icon_url?: string;
  3553. group_type?: string;
  3554. live_activities?: boolean;
  3555. lock_screen_widgets?: boolean;
  3556. live_activity_privacy?: boolean;
  3557. live_activity_stage?: boolean;
  3558. live_activity_style?: 'bar' | 'segments' | 'none';
  3559. live_activity_metrics?: ('progress' | 'eta' | 'layers' | 'nozzle' | 'bed' | 'chamber')[];
  3560. live_activity_button_url?: string;
  3561. live_activity_symbol?: string;
  3562. live_activity_tint?: string;
  3563. time_sensitive?: boolean;
  3564. }
  3565. export interface TelegramConfig {
  3566. bot_token: string;
  3567. chat_id: string;
  3568. }
  3569. export interface EmailConfig {
  3570. smtp_server: string;
  3571. smtp_port?: number;
  3572. username: string;
  3573. password: string;
  3574. from_email: string;
  3575. to_email: string;
  3576. use_tls?: boolean;
  3577. }
  3578. // Notification Template types
  3579. export interface NotificationTemplate {
  3580. id: number;
  3581. event_type: string;
  3582. name: string;
  3583. title_template: string;
  3584. body_template: string;
  3585. is_default: boolean;
  3586. created_at: string;
  3587. updated_at: string;
  3588. }
  3589. export interface NotificationTemplateUpdate {
  3590. title_template?: string;
  3591. body_template?: string;
  3592. }
  3593. export interface EventVariablesResponse {
  3594. event_type: string;
  3595. event_name: string;
  3596. variables: string[];
  3597. supports_photo: boolean;
  3598. }
  3599. export interface TemplatePreviewRequest {
  3600. event_type: string;
  3601. title_template: string;
  3602. body_template: string;
  3603. }
  3604. export interface TemplatePreviewResponse {
  3605. title: string;
  3606. body: string;
  3607. }
  3608. // Notification Log types
  3609. export interface NotificationLogEntry {
  3610. id: number;
  3611. provider_id: number;
  3612. provider_name: string | null;
  3613. provider_type: string | null;
  3614. event_type: string;
  3615. title: string;
  3616. message: string;
  3617. success: boolean;
  3618. error_message: string | null;
  3619. printer_id: number | null;
  3620. printer_name: string | null;
  3621. created_at: string;
  3622. }
  3623. export interface NotificationLogStats {
  3624. total: number;
  3625. success_count: number;
  3626. failure_count: number;
  3627. by_event_type: Record<string, number>;
  3628. by_provider: Record<string, number>;
  3629. }
  3630. // Spoolman types
  3631. export interface SpoolmanStatus {
  3632. enabled: boolean;
  3633. connected: boolean;
  3634. url: string | null;
  3635. native_tags?: boolean; // Spoolman 0.27+ links tags natively
  3636. }
  3637. export interface SpoolmanTagMigrationReport {
  3638. dry_run: boolean;
  3639. moved: number[];
  3640. already: number;
  3641. slot_ids: number;
  3642. conflicts: Array<{ spool_id: number; tag: string; holder: number }>; // holder -1: a filament holds the tag
  3643. }
  3644. export interface SkippedSpool {
  3645. location: string;
  3646. reason: string;
  3647. filament_type: string | null;
  3648. color: string | null;
  3649. }
  3650. export interface SpoolmanSyncResult {
  3651. success: boolean;
  3652. synced_count: number;
  3653. skipped_count: number;
  3654. skipped: SkippedSpool[];
  3655. errors: string[];
  3656. }
  3657. export interface UnlinkedSpool {
  3658. id: number;
  3659. filament_name: string | null;
  3660. filament_vendor: string | null;
  3661. filament_material: string | null;
  3662. filament_color_hex: string | null;
  3663. remaining_weight: number | null;
  3664. location: string | null;
  3665. }
  3666. export interface LinkedSpoolInfo {
  3667. id: number;
  3668. remaining_weight: number | null;
  3669. filament_weight: number | null;
  3670. }
  3671. export interface LinkedSpoolsMap {
  3672. linked: Record<string, LinkedSpoolInfo>; // tag (uppercase) -> spool info
  3673. }
  3674. export interface SpoolmanVendor {
  3675. id: number;
  3676. name: string;
  3677. }
  3678. export interface SpoolmanFilamentEntry {
  3679. id: number;
  3680. name: string;
  3681. material: string | null;
  3682. color_hex: string | null;
  3683. color_name: string | null;
  3684. weight: number | null;
  3685. spool_weight: number | null;
  3686. vendor: SpoolmanVendor | null;
  3687. }
  3688. // Inventory types
  3689. // Label printing (#809). Mirror of backend.app.services.label_renderer.TemplateName.
  3690. export type SpoolLabelTemplate =
  3691. | 'ams_holder_74x33'
  3692. | 'ams_holder_75x55'
  3693. | 'box_40x30'
  3694. | 'box_62x29'
  3695. | 'avery_5160'
  3696. | 'avery_l7160';
  3697. // Mirror of backend.app.services.label_renderer.LabelField, in print order (#2981).
  3698. export const SPOOL_LABEL_FIELDS = [
  3699. 'brand',
  3700. 'material',
  3701. 'hex',
  3702. 'name',
  3703. 'location',
  3704. 'material_number',
  3705. 'temps',
  3706. 'weight',
  3707. 'note',
  3708. 'added',
  3709. 'qr',
  3710. 'spool_id',
  3711. ] as const;
  3712. export type SpoolLabelField = (typeof SPOOL_LABEL_FIELDS)[number];
  3713. // Mirror of DEFAULT_LABEL_FIELDS: what a label carried before fields were selectable.
  3714. export const DEFAULT_SPOOL_LABEL_FIELDS: SpoolLabelField[] = [
  3715. 'brand',
  3716. 'material',
  3717. 'hex',
  3718. 'name',
  3719. 'location',
  3720. 'qr',
  3721. 'spool_id',
  3722. ];
  3723. // A sheet of identical labels in a grid, in millimetres (#3296). Mirror of
  3724. // backend.app.schemas.label_template.SheetLayoutSpec.
  3725. export type LabelPageSize = 'a4' | 'letter';
  3726. export interface LabelSheetLayout {
  3727. page: LabelPageSize;
  3728. label_w_mm: number;
  3729. label_h_mm: number;
  3730. cols: number;
  3731. rows: number;
  3732. top_mm: number;
  3733. left_mm: number;
  3734. col_gap_mm: number;
  3735. row_gap_mm: number;
  3736. }
  3737. // A custom sheet saved under a name, shared by everyone on the install.
  3738. export interface SavedLabelTemplate {
  3739. id: number;
  3740. name: string;
  3741. layout: LabelSheetLayout;
  3742. created_at: string;
  3743. updated_at: string;
  3744. }
  3745. // A built-in template, or "custom" with the sheet itself in ``layout``.
  3746. export type SpoolLabelRequestTemplate = SpoolLabelTemplate | 'custom';
  3747. export interface PrintSpoolLabelsRequest {
  3748. spool_ids: number[];
  3749. template: SpoolLabelRequestTemplate;
  3750. layout?: LabelSheetLayout;
  3751. monochrome: boolean;
  3752. starting_position: number;
  3753. fields?: SpoolLabelField[];
  3754. format?: 'pdf' | 'png';
  3755. dpi?: 203 | 300 | 600;
  3756. }
  3757. export interface PreviewSpoolLabelRequest {
  3758. spool_id: number;
  3759. template: SpoolLabelRequestTemplate;
  3760. layout?: LabelSheetLayout;
  3761. monochrome: boolean;
  3762. fields: SpoolLabelField[];
  3763. }
  3764. export interface InventorySpool {
  3765. id: number;
  3766. material: string;
  3767. subtype: string | null;
  3768. color_name: string | null;
  3769. // True when color_name was synthesised from subtype because Spoolman has no
  3770. // stored value (Spoolman-backed inventory only). The edit form uses this to
  3771. // leave the input blank, so the user doesn't round-trip the synth value
  3772. // back to Spoolman as if it were a real user-set color_name (#1319).
  3773. color_name_is_synthesized?: boolean;
  3774. rgba: string | null;
  3775. // Multi-colour gradient stops (#1154): comma-separated 6/8-char hex.
  3776. extra_colors: string | null;
  3777. // Visual effect overlay: sparkle | wood | marble | glow | matte.
  3778. effect_type: string | null;
  3779. brand: string | null;
  3780. label_weight: number;
  3781. core_weight: number;
  3782. // Spoolman-backed inventory only: true when the spool has no tare of its
  3783. // own and core_weight is the filament type's. Absent for local spools (#2908).
  3784. core_weight_is_inherited?: boolean;
  3785. core_weight_catalog_id: number | null;
  3786. weight_used: number;
  3787. // Anchor for the resettable "Total Consumed" display (#1390). The
  3788. // counter shown on the Inventory page is `weight_used - weight_used_baseline`;
  3789. // remaining is still `label_weight - weight_used`, so "Reset usage to 0"
  3790. // zeroes the counter without disturbing remaining. Optional for back-compat
  3791. // with rows from a pre-migration DB snapshot — default to 0.
  3792. weight_used_baseline?: number;
  3793. slicer_filament: string | null;
  3794. slicer_filament_name: string | null;
  3795. nozzle_temp_min: number | null;
  3796. nozzle_temp_max: number | null;
  3797. note: string | null;
  3798. added_full: boolean | null;
  3799. last_used: string | null;
  3800. // Spoolman mode: when the spool was first printed with (#3407).
  3801. first_used?: string | null;
  3802. // Last drying (#2863): stamped when an AMS drying run of at least half its
  3803. // length ends, or set by hand. Temperature and hours are null when unknown.
  3804. last_dried_at?: string | null;
  3805. last_dried_temp?: number | null;
  3806. last_dried_hours?: number | null;
  3807. encode_time: string | null;
  3808. tag_uid: string | null;
  3809. tray_uuid: string | null;
  3810. data_origin: string | null;
  3811. tag_type: string | null;
  3812. archived_at: string | null;
  3813. created_at: string;
  3814. updated_at: string;
  3815. cost_per_kg: number | null;
  3816. // Spoolman mode: what prints are charged per kg, the spool's own price or
  3817. // else its filament's. Display only; the form edits cost_per_kg.
  3818. effective_cost_per_kg?: number | null;
  3819. last_scale_weight: number | null;
  3820. last_weighed_at: string | null;
  3821. // User-defined category + per-spool low-stock threshold override (#729).
  3822. category: string | null;
  3823. low_stock_threshold_pct: number | null;
  3824. // Internal material / article number (#2870) — the purchasing identifier
  3825. // shared by all spools of the same product.
  3826. material_number: string | null;
  3827. k_profiles?: SpoolKProfile[];
  3828. storage_location?: string | null;
  3829. location_id?: number | null;
  3830. // Supplier assignments (#2988). Absent in Spoolman mode — Spoolman's
  3831. // vendor is the manufacturer, not the seller, so there is no mapping.
  3832. suppliers?: SpoolSupplierLink[];
  3833. }
  3834. // ── Suppliers (#2988) ──────────────────────────────────────────────────────
  3835. /** Where filament is bought — distinct from brand (who made it). */
  3836. export interface Supplier {
  3837. id: number;
  3838. name: string;
  3839. website: string | null;
  3840. customer_number: string | null;
  3841. note: string | null;
  3842. /** Spools referencing this supplier; a referenced supplier cannot be deleted. */
  3843. spool_count: number;
  3844. created_at: string;
  3845. updated_at: string;
  3846. }
  3847. export interface SupplierInput {
  3848. name: string;
  3849. website?: string | null;
  3850. customer_number?: string | null;
  3851. note?: string | null;
  3852. }
  3853. /** One spool-to-supplier assignment as written by the spool dialog. */
  3854. export interface SpoolSupplierLinkInput {
  3855. supplier_id: number;
  3856. /** The supplier's own article number — NOT the internal material number. */
  3857. supplier_article_number?: string | null;
  3858. /** Quoted price for comparison — never the cost basis (spool.cost_per_kg). */
  3859. quoted_price_per_kg?: number | null;
  3860. /** Marks where this concrete spool was actually bought. */
  3861. is_purchase_source?: boolean;
  3862. }
  3863. export interface SpoolSupplierLink {
  3864. id: number;
  3865. supplier_id: number;
  3866. supplier_name: string;
  3867. supplier_article_number: string | null;
  3868. quoted_price_per_kg: number | null;
  3869. is_purchase_source: boolean;
  3870. }
  3871. /** Per-supplier inventory aggregate (#2988), purchase-source spools only. */
  3872. export interface SupplierStats {
  3873. supplier_id: number;
  3874. supplier_name: string;
  3875. spool_count: number;
  3876. remaining_g: number;
  3877. consumed_g: number;
  3878. cost: number;
  3879. }
  3880. /** Per-material-number inventory aggregate (#2870). */
  3881. export interface MaterialNumberStats {
  3882. material_number: string;
  3883. spool_count: number;
  3884. remaining_g: number;
  3885. consumed_g: number;
  3886. cost: number;
  3887. }
  3888. export interface SpoolmanBulkCreateResult {
  3889. created: InventorySpool[];
  3890. requested_count: number;
  3891. failed_count: number;
  3892. }
  3893. // ── CSV import/export (#1576) ──────────────────────────────────────────────
  3894. /** One row's outcome from the import preview / real import. */
  3895. export interface CsvImportRow {
  3896. row_number: number;
  3897. status: 'valid' | 'error' | 'skipped';
  3898. reason: string | null;
  3899. material: string | null;
  3900. brand: string | null;
  3901. color_name: string | null;
  3902. rgba: string | null;
  3903. /** rgba/extra_colors/effect_type were filled from the Color Catalog. */
  3904. resolved_color: boolean;
  3905. /** The catalog match came from a different material's variant (no exact
  3906. * material match). Shown as a warning in the preview. */
  3907. cross_material_color: boolean;
  3908. /** An active spool with the same material+brand+color already exists.
  3909. * Informational only — the import still creates the row. */
  3910. duplicate_of_existing: boolean;
  3911. }
  3912. /** Dry-run preview: per-row classification, no rows written. */
  3913. export interface CsvImportPreview {
  3914. columns: string[];
  3915. total: number;
  3916. valid_count: number;
  3917. error_count: number;
  3918. skipped_count: number;
  3919. rows: CsvImportRow[];
  3920. warnings: string[];
  3921. }
  3922. /** Summary returned after a real (non-dry-run) import. */
  3923. export interface CsvImportResult {
  3924. created: number;
  3925. skipped: number;
  3926. errors: number;
  3927. error_rows: CsvImportRow[];
  3928. }
  3929. export interface SpoolUsageRecord {
  3930. id: number;
  3931. // null: the spool was deleted, its usage kept
  3932. spool_id: number | null;
  3933. // Spoolman mode: the Spoolman spool charged (#3407); spool_id is null then.
  3934. spoolman_spool_id?: number | null;
  3935. printer_id: number | null;
  3936. print_name: string | null;
  3937. weight_used: number;
  3938. percent_used: number;
  3939. status: string;
  3940. cost: number | null;
  3941. created_at: string;
  3942. }
  3943. export interface SpoolKProfile {
  3944. id: number;
  3945. spool_id: number;
  3946. printer_id: number;
  3947. extruder: number;
  3948. nozzle_diameter: string;
  3949. nozzle_type: string | null;
  3950. k_value: number;
  3951. name: string | null;
  3952. cali_idx: number | null;
  3953. setting_id: string | null;
  3954. created_at: string;
  3955. }
  3956. export interface SpoolKProfileInput {
  3957. printer_id: number;
  3958. extruder?: number;
  3959. nozzle_diameter?: string;
  3960. nozzle_type?: string | null;
  3961. k_value: number;
  3962. name?: string | null;
  3963. cali_idx?: number | null;
  3964. setting_id?: string | null;
  3965. }
  3966. /**
  3967. * One per-printer-model override of a spool's slicer filament preset.
  3968. *
  3969. * A cloud or Orca preset is bound to a printer model ("@BBL X1C"), so the
  3970. * spool's single `slicer_filament` is wrong as soon as the spool is used on a
  3971. * second model. `nozzle_diameter` is "" for the model's own default and a bare
  3972. * decimal ("0.2") for a per-hotend exception; the backend resolves
  3973. * exact (model, diameter) -> (model, "") -> the spool's own preset.
  3974. */
  3975. export interface SlotSpoolDefaults {
  3976. slicer_filament: string | null;
  3977. slicer_filament_name: string | null;
  3978. cali_idx: number | null;
  3979. k_value: number | null;
  3980. profile_name: string | null;
  3981. extruder: number | null;
  3982. nozzle_diameter: string;
  3983. }
  3984. export interface SpoolFilamentPresetInput {
  3985. printer_model: string;
  3986. nozzle_diameter: string;
  3987. slicer_filament: string | null;
  3988. slicer_filament_name: string | null;
  3989. }
  3990. export interface SpoolFilamentPreset extends SpoolFilamentPresetInput {
  3991. id: number;
  3992. spool_id: number;
  3993. created_at: string;
  3994. }
  3995. /**
  3996. * What a new spool of one product starts with (#1326): the slicer preset, the
  3997. * per-model preset overrides and the K profiles. `color_name` "" is the
  3998. * default for every colour of the product; one with a colour wins over it per
  3999. * preset and per hotend. Shared by both inventory modes.
  4000. */
  4001. export interface ProfileDefaultKey {
  4002. brand: string;
  4003. material: string;
  4004. subtype: string;
  4005. color_name: string;
  4006. }
  4007. export interface ProfileDefaultInput extends ProfileDefaultKey {
  4008. slicer_filament: string | null;
  4009. slicer_filament_name: string | null;
  4010. presets: SpoolFilamentPresetInput[];
  4011. k_profiles: SpoolKProfileInput[];
  4012. }
  4013. export interface ProfileDefault extends ProfileDefaultInput {
  4014. id: number;
  4015. updated_at: string;
  4016. }
  4017. /** Both levels of a product's default merged, as a create applies them. */
  4018. export interface ResolvedProfileDefault {
  4019. slicer_filament: string | null;
  4020. slicer_filament_name: string | null;
  4021. presets: SpoolFilamentPresetInput[];
  4022. k_profiles: SpoolKProfileInput[];
  4023. default_ids: number[];
  4024. }
  4025. /** One inventory-bound AMS slot, as returned by `/printers/{id}/inventory-remain`. */
  4026. export interface SlotMaterial {
  4027. ams_id: number;
  4028. tray_id: number;
  4029. global_tray_id: number;
  4030. /** Opaque grouping key from the backend. Two slots back each other up under
  4031. * AMS Filament Backup only when both `material_key` and `extruder` match.
  4032. * Never parse it — the format belongs to the backend's identity rule. */
  4033. material_key: string;
  4034. remaining_g: number;
  4035. /** 0 = right / single nozzle, 1 = left. */
  4036. extruder: number;
  4037. /** How the bound spool should be *named* — display only, never matched on.
  4038. * The printer has no brand field and reports no sub-brand for a
  4039. * third-party spool, so this is the only place a slot's real identity
  4040. * exists. Null when the binding resolves to a spool we cannot describe. */
  4041. spool?: SlotSpoolIdentity | null;
  4042. /** Per-kg rate a print off this spool is charged at; null when unpriced,
  4043. * which is charged at the default rate. Optional for an older backend. */
  4044. cost_per_kg?: number | null;
  4045. }
  4046. /** Display identity of an inventory-bound slot. See `SlotMaterial.spool`. */
  4047. export interface SlotSpoolIdentity {
  4048. brand: string | null;
  4049. material: string | null;
  4050. subtype: string | null;
  4051. color_name: string | null;
  4052. rgba: string | null;
  4053. /** Comma-separated hex stops for a multi-colour spool, and the effect
  4054. * overlay — the two things a tray record cannot carry, so a slot swatch
  4055. * can be drawn the way the inventory row draws it (#3159).
  4056. *
  4057. * Optional rather than required: the backend sends both keys on every
  4058. * binding, but a frontend running against an older one gets neither, and
  4059. * every reader here already falls back to a solid swatch. */
  4060. extra_colors?: string | null;
  4061. effect_type?: string | null;
  4062. }
  4063. export interface InventoryRemainResponse {
  4064. /** Currently-loaded, inventory-bound slots only — drives the prefer-lowest sort. */
  4065. inventory_remain_g: Record<string, number>;
  4066. /** Every inventory binding on the printer, with identity + extruder side. */
  4067. slot_materials: SlotMaterial[];
  4068. }
  4069. export interface SpoolAssignment {
  4070. id: number;
  4071. spool_id: number;
  4072. printer_id: number;
  4073. printer_name: string | null;
  4074. ams_id: number;
  4075. tray_id: number;
  4076. fingerprint_color: string | null;
  4077. fingerprint_type: string | null;
  4078. spool?: InventorySpool | null;
  4079. configured: boolean;
  4080. pending_config?: boolean; // Slot was empty at assign time; will configure on insert
  4081. created_at: string;
  4082. ams_label?: string | null; // User-defined friendly name for the AMS unit
  4083. }
  4084. export interface FilamentSkuSettings {
  4085. id: number;
  4086. material: string;
  4087. subtype: string | null;
  4088. brand: string | null;
  4089. color_name: string | null;
  4090. lead_time_days: number;
  4091. safety_margin_value: number;
  4092. safety_margin_unit: 'days' | 'g';
  4093. alerts_snoozed: boolean;
  4094. }
  4095. export interface ShoppingListItem {
  4096. id: number;
  4097. material: string;
  4098. subtype: string | null;
  4099. brand: string | null;
  4100. color_name: string | null;
  4101. quantity_spools: number;
  4102. note: string | null;
  4103. status: 'pending' | 'purchased' | 'received';
  4104. purchased_at: string | null;
  4105. added_at: string;
  4106. }
  4107. export interface ShoppingListItemCreate {
  4108. material: string;
  4109. subtype: string | null;
  4110. brand: string | null;
  4111. color_name: string | null;
  4112. quantity_spools: number;
  4113. note?: string | null;
  4114. }
  4115. // Update types
  4116. export interface VersionInfo {
  4117. version: string;
  4118. repo: string;
  4119. }
  4120. export interface UpdateCheckResult {
  4121. update_available: boolean;
  4122. current_version: string;
  4123. latest_version: string | null;
  4124. release_name?: string;
  4125. release_notes?: string;
  4126. release_url?: string;
  4127. published_at?: string;
  4128. error?: string;
  4129. message?: string;
  4130. is_docker?: boolean;
  4131. is_ha_addon?: boolean;
  4132. is_windows_installer?: boolean;
  4133. update_method?: 'docker' | 'git' | 'ha_addon' | 'windows_installer';
  4134. installer_download_url?: string | null;
  4135. // Best-effort guess at the compose directory (#2664). Prefill only — the
  4136. // value the user saved lives on AppSettings.docker_compose_dir, so clearing
  4137. // that field falls back to this guess instead of resurrecting the old value.
  4138. compose_dir_detected?: string | null;
  4139. }
  4140. export interface UpdateStatus {
  4141. status: 'idle' | 'checking' | 'downloading' | 'installing' | 'complete' | 'error';
  4142. progress: number;
  4143. message: string;
  4144. error: string | null;
  4145. }
  4146. // Maintenance types
  4147. export interface MaintenanceType {
  4148. id: number;
  4149. name: string;
  4150. description: string | null;
  4151. default_interval_hours: number;
  4152. interval_type: 'hours' | 'days'; // "hours" = print hours, "days" = calendar days
  4153. icon: string | null;
  4154. wiki_url: string | null; // Documentation link
  4155. is_system: boolean;
  4156. created_at: string;
  4157. }
  4158. export interface MaintenanceTypeCreate {
  4159. name: string;
  4160. description?: string | null;
  4161. default_interval_hours?: number;
  4162. interval_type?: 'hours' | 'days';
  4163. icon?: string | null;
  4164. wiki_url?: string | null;
  4165. }
  4166. export interface MaintenanceStatus {
  4167. id: number;
  4168. printer_id: number;
  4169. printer_name: string;
  4170. printer_model: string | null;
  4171. maintenance_type_id: number;
  4172. maintenance_type_name: string;
  4173. maintenance_type_icon: string | null;
  4174. maintenance_type_wiki_url: string | null; // Custom wiki URL from type
  4175. enabled: boolean;
  4176. interval_hours: number; // For hours type: print hours; for days type: number of days
  4177. interval_type: 'hours' | 'days';
  4178. current_hours: number;
  4179. hours_since_maintenance: number;
  4180. hours_until_due: number;
  4181. days_since_maintenance: number | null; // For days type
  4182. days_until_due: number | null; // For days type
  4183. is_due: boolean;
  4184. is_warning: boolean;
  4185. last_performed_at: string | null;
  4186. }
  4187. export interface PrinterMaintenanceOverview {
  4188. printer_id: number;
  4189. printer_name: string;
  4190. printer_model: string | null;
  4191. total_print_hours: number;
  4192. maintenance_items: MaintenanceStatus[];
  4193. due_count: number;
  4194. warning_count: number;
  4195. }
  4196. // External Links (sidebar)
  4197. export interface ExternalLink {
  4198. id: number;
  4199. name: string;
  4200. url: string;
  4201. icon: string;
  4202. open_in_new_tab: boolean;
  4203. custom_icon: string | null;
  4204. sort_order: number;
  4205. created_at: string;
  4206. updated_at: string;
  4207. /** Count reported by the app the link points to, while it keeps reporting. */
  4208. badge_count?: number | null;
  4209. }
  4210. export interface ExternalLinkCreate {
  4211. name: string;
  4212. url: string;
  4213. icon: string;
  4214. open_in_new_tab?: boolean;
  4215. }
  4216. export interface ExternalLinkUpdate {
  4217. name?: string;
  4218. url?: string;
  4219. icon?: string;
  4220. open_in_new_tab?: boolean;
  4221. }
  4222. // Finance types
  4223. export interface CostCenterSummary {
  4224. id: number;
  4225. name: string;
  4226. is_private: boolean;
  4227. owner_user_id: number | null;
  4228. is_active: boolean;
  4229. total_balance: number;
  4230. total_budget: number | null;
  4231. monthly_budget: number | null;
  4232. budget_mode: 'none' | 'total' | 'monthly';
  4233. budget_limit: number | null;
  4234. budget_used: number | null;
  4235. budget_available: number | null;
  4236. can_print: boolean;
  4237. }
  4238. export interface CostCenterCreateRequest {
  4239. name: string;
  4240. total_budget?: number | null;
  4241. monthly_budget?: number | null;
  4242. is_active?: boolean;
  4243. }
  4244. export interface CostCenterBudgetUpdateRequest {
  4245. total_budget?: number | null;
  4246. monthly_budget?: number | null;
  4247. }
  4248. export interface CostCenterUpdateRequest {
  4249. name?: string;
  4250. is_active?: boolean;
  4251. }
  4252. export interface CostCenterMemberRequest {
  4253. user_id: number;
  4254. can_print?: boolean;
  4255. }
  4256. export interface CostCenterMemberResponse {
  4257. id: number;
  4258. cost_center_id: number;
  4259. user_id: number;
  4260. can_print: boolean;
  4261. created_at: string;
  4262. }
  4263. export interface CostCenterDetail extends CostCenterSummary {
  4264. members: CostCenterMemberResponse[];
  4265. }
  4266. export interface WalletBalance {
  4267. user_id: number;
  4268. balance: number;
  4269. currency: string;
  4270. updated_at: string | null;
  4271. }
  4272. export type WalletTransactionType = 'print_charge' | 'deposit' | 'withdraw' | 'manual_adjustment';
  4273. export interface WalletTransaction {
  4274. id: number;
  4275. user_id: number | null; // null once the user is deleted
  4276. cost_center_id: number | null;
  4277. transaction_type: WalletTransactionType;
  4278. amount: number;
  4279. balance_after: number | null;
  4280. description: string | null;
  4281. created_by_user_id: number | null;
  4282. print_run_id: string | null;
  4283. print_archive_id: number | null;
  4284. print_queue_id: number | null;
  4285. created_at: string;
  4286. }
  4287. export interface WalletTransactionListResponse {
  4288. items: WalletTransaction[];
  4289. total: number;
  4290. limit: number;
  4291. offset: number;
  4292. }
  4293. export interface WalletAdjustmentRequest {
  4294. amount: number;
  4295. description?: string;
  4296. cost_center_id?: number | null;
  4297. }
  4298. export interface WalletAdjustmentResponse {
  4299. transaction: WalletTransaction;
  4300. balance: WalletBalance;
  4301. }
  4302. export interface TransactionEditRequest {
  4303. user_id?: number | null;
  4304. cost_center_id?: number | null;
  4305. amount?: number | null;
  4306. description?: string | null;
  4307. }
  4308. export interface ManualPrintRequest {
  4309. user_id: number;
  4310. cost_center_id: number;
  4311. amount: number;
  4312. description?: string | null;
  4313. created_at?: string | null;
  4314. }
  4315. // Permission type - all available permissions
  4316. export type Permission =
  4317. | 'printers:read' | 'printers:create' | 'printers:update' | 'printers:delete' | 'printers:control' | 'printers:files' | 'printers:ams_rfid' | 'printers:clear_plate'
  4318. | 'archives:read' | 'archives:read_own' | 'archives:read_all' | 'archives:create'
  4319. | 'archives:update_own' | 'archives:update_all' | 'archives:delete_own' | 'archives:delete_all'
  4320. | 'archives:reprint_own' | 'archives:reprint_all' | 'archives:purge'
  4321. | 'queue:read' | 'queue:read_own' | 'queue:read_all' | 'queue:create'
  4322. | 'queue:update_own' | 'queue:update_all' | 'queue:delete_own' | 'queue:delete_all'
  4323. | 'queue:reorder' | 'queue:start_unreviewed'
  4324. | 'library:read' | 'library:read_own' | 'library:read_all' | 'library:upload'
  4325. | 'library:update_own' | 'library:update_all' | 'library:delete_own' | 'library:delete_all'
  4326. | 'library:purge'
  4327. | 'projects:read' | 'projects:create' | 'projects:update' | 'projects:delete'
  4328. | 'filaments:read' | 'filaments:create' | 'filaments:update' | 'filaments:delete'
  4329. | 'inventory:read' | 'inventory:create' | 'inventory:update' | 'inventory:delete' | 'inventory:view_assignments'
  4330. | 'inventory:forecast_read' | 'inventory:forecast_write'
  4331. | 'smart_plugs:read' | 'smart_plugs:create' | 'smart_plugs:update' | 'smart_plugs:delete' | 'smart_plugs:control'
  4332. | 'camera:view'
  4333. | 'maintenance:read' | 'maintenance:create' | 'maintenance:update' | 'maintenance:delete'
  4334. | 'kprofiles:read' | 'kprofiles:create' | 'kprofiles:update' | 'kprofiles:delete'
  4335. | 'notifications:read' | 'notifications:create' | 'notifications:update' | 'notifications:delete' | 'notifications:user_email'
  4336. | 'notification_templates:read' | 'notification_templates:update'
  4337. | 'external_links:read' | 'external_links:create' | 'external_links:update' | 'external_links:delete'
  4338. | 'discovery:scan'
  4339. | 'firmware:read' | 'firmware:update'
  4340. | 'ams_history:read'
  4341. | 'cost_centers:read_own' | 'cost_centers:read_all' | 'cost_centers:modify' | 'cost_centers:create'
  4342. | 'stats:read' | 'stats:filter_by_user'
  4343. | 'system:read'
  4344. | 'settings:read' | 'settings:update' | 'settings:backup' | 'settings:restore'
  4345. | 'github:backup' | 'github:restore'
  4346. | 'cloud:auth' | 'orca_cloud:auth'
  4347. | 'makerworld:view' | 'makerworld:import'
  4348. | 'manyfold:view' | 'manyfold:import'
  4349. | 'api_keys:read' | 'api_keys:create' | 'api_keys:update' | 'api_keys:delete'
  4350. | 'users:read' | 'users:read_slim' | 'users:create' | 'users:update' | 'users:delete'
  4351. | 'groups:read' | 'groups:create' | 'groups:update' | 'groups:delete'
  4352. | 'pipelines:read' | 'pipelines:write' | 'pipelines:run'
  4353. | 'websocket:connect';
  4354. // Group types
  4355. export interface GroupBrief {
  4356. id: number;
  4357. name: string;
  4358. }
  4359. export interface Group {
  4360. id: number;
  4361. name: string;
  4362. description: string | null;
  4363. permissions: Permission[];
  4364. is_system: boolean;
  4365. /** Members only see the printers in printer_ids plus every printer in locations (#1727) */
  4366. restrict_printers: boolean;
  4367. printer_ids: number[];
  4368. /** Matched against Printer.location, so printers added there later are included */
  4369. locations: string[];
  4370. user_count: number;
  4371. created_at: string;
  4372. updated_at: string;
  4373. }
  4374. export interface GroupDetail extends Group {
  4375. users: Array<{ id: number; username: string; is_active: boolean }>;
  4376. }
  4377. export interface GroupCreate {
  4378. name: string;
  4379. description?: string;
  4380. permissions: Permission[];
  4381. restrict_printers?: boolean;
  4382. printer_ids?: number[];
  4383. locations?: string[];
  4384. }
  4385. export interface GroupUpdate {
  4386. name?: string;
  4387. description?: string;
  4388. permissions?: Permission[];
  4389. restrict_printers?: boolean;
  4390. printer_ids?: number[];
  4391. locations?: string[];
  4392. }
  4393. export interface PermissionInfo {
  4394. value: Permission;
  4395. label: string;
  4396. }
  4397. export interface PermissionCategory {
  4398. name: string;
  4399. permissions: PermissionInfo[];
  4400. }
  4401. export interface PermissionsListResponse {
  4402. categories: PermissionCategory[];
  4403. all_permissions: Permission[];
  4404. }
  4405. // User email notification preferences
  4406. export interface UserEmailPreferences {
  4407. notify_print_start: boolean;
  4408. notify_print_complete: boolean;
  4409. notify_print_failed: boolean;
  4410. notify_print_stopped: boolean;
  4411. }
  4412. // Auth types
  4413. export interface LoginRequest {
  4414. username: string;
  4415. password: string;
  4416. }
  4417. export interface LoginResponse {
  4418. access_token?: string;
  4419. token_type?: string;
  4420. user?: UserResponse;
  4421. /** Set when 2FA verification is required before a full token is issued. */
  4422. requires_2fa?: boolean;
  4423. pre_auth_token?: string;
  4424. two_fa_methods?: string[];
  4425. }
  4426. export interface UserResponse {
  4427. id: number;
  4428. username: string;
  4429. email?: string;
  4430. role: string; // Deprecated, kept for backward compatibility
  4431. is_active: boolean;
  4432. is_admin: boolean; // Computed from role and group membership
  4433. auth_source: string; // "local" or "ldap"
  4434. groups: GroupBrief[];
  4435. permissions: Permission[]; // All permissions from groups
  4436. created_at: string;
  4437. }
  4438. /**
  4439. * Just enough to label an owner id (#1894). Backed by GET /users/slim, which
  4440. * is readable with `users:read_slim` as well as the admin-level `users:read`
  4441. * -- use it anywhere a screen only needs to turn a `created_by_id` into a
  4442. * name, so operators are not forced into the full listing to get one.
  4443. */
  4444. export interface UserSlim {
  4445. id: number;
  4446. username: string;
  4447. }
  4448. export interface UserCreate {
  4449. username: string;
  4450. password?: string; // Optional when advanced auth is enabled
  4451. email?: string;
  4452. role: string;
  4453. group_ids?: number[];
  4454. }
  4455. export interface UserUpdate {
  4456. username?: string;
  4457. password?: string;
  4458. email?: string;
  4459. role?: string;
  4460. is_active?: boolean;
  4461. group_ids?: number[];
  4462. }
  4463. export interface SetupRequest {
  4464. auth_enabled: boolean;
  4465. admin_username?: string;
  4466. admin_password?: string;
  4467. }
  4468. export interface ForgotPasswordRequest {
  4469. email: string;
  4470. }
  4471. export interface ForgotPasswordResponse {
  4472. message: string;
  4473. }
  4474. export interface ResetPasswordRequest {
  4475. user_id: number;
  4476. }
  4477. export interface ResetPasswordResponse {
  4478. message: string;
  4479. }
  4480. export interface SMTPSettings {
  4481. smtp_host: string;
  4482. smtp_port: number;
  4483. smtp_username?: string;
  4484. smtp_password?: string;
  4485. smtp_security: 'starttls' | 'ssl' | 'none';
  4486. smtp_auth_enabled: boolean;
  4487. smtp_from_email: string;
  4488. smtp_from_name: string;
  4489. }
  4490. // 2FA / MFA interfaces
  4491. export interface TwoFAStatus {
  4492. totp_enabled: boolean;
  4493. email_otp_enabled: boolean;
  4494. backup_codes_remaining: number;
  4495. }
  4496. export interface TOTPSetupResponse {
  4497. secret: string;
  4498. qr_code_b64: string;
  4499. issuer: string;
  4500. }
  4501. export interface TOTPEnableResponse {
  4502. message: string;
  4503. backup_codes: string[];
  4504. }
  4505. export interface BackupCodesResponse {
  4506. backup_codes: string[];
  4507. message: string;
  4508. }
  4509. export interface TwoFAVerifyRequest {
  4510. pre_auth_token: string;
  4511. code: string;
  4512. method: 'totp' | 'email' | 'backup';
  4513. }
  4514. /**
  4515. * A URL that is known to be same-origin (a relative path starting with ``/``).
  4516. *
  4517. * Branded so that producers of same-origin URLs (e.g. ``api.oidcProviderIconUrl``)
  4518. * can be distinguished from arbitrary strings at the type level. The brand
  4519. * is compile-time only; at runtime these are plain strings.
  4520. *
  4521. * Purpose: CSP-safe image sources for ``<img src=...>``. The strict
  4522. * ``img-src 'self' data: blob:`` CSP rejects anything that isn't same-origin,
  4523. * so callers that demand a ``SameOriginUrl`` get a compile-time guarantee
  4524. * that no external URL slips through.
  4525. */
  4526. export type SameOriginUrl = string & { readonly __brand: 'SameOriginUrl' };
  4527. // OIDC interfaces
  4528. /** What the unauthenticated GET /auth/oidc/providers returns (#3107): only
  4529. * what the login page renders. The full provider, group sync config
  4530. * included, needs the admin-only /auth/oidc/providers/all. */
  4531. export interface OIDCProviderPublic {
  4532. id: number;
  4533. name: string;
  4534. has_icon: boolean;
  4535. is_autologin: boolean;
  4536. }
  4537. export interface OIDCProvider {
  4538. id: number;
  4539. name: string;
  4540. issuer_url: string;
  4541. client_id: string;
  4542. scopes: string;
  4543. is_enabled: boolean;
  4544. auto_create_users: boolean;
  4545. auto_link_existing_accounts: boolean;
  4546. email_claim: string;
  4547. require_email_verified: boolean;
  4548. // #3107 — group sync. Empty mapping = sync off (default).
  4549. group_claim?: string;
  4550. group_mapping?: Record<string, string>;
  4551. icon_url?: string | null;
  4552. default_group_id?: number | null;
  4553. // True when the backend has cached icon bytes for this provider.
  4554. // Login page / admin preview consume this via the proxy URL
  4555. // /api/v1/auth/oidc/providers/{id}/icon (#1333) so the SPA never
  4556. // hotlinks the external icon URL — that would require loosening
  4557. // the strict img-src CSP. Required, not optional: the backend always
  4558. // includes this field in the response (Pydantic default-False is
  4559. // populated unconditionally in the route handler).
  4560. has_icon: boolean;
  4561. // #1589: when true, the LoginPage redirects unauthenticated visitors
  4562. // straight to this provider on mount. At most one provider may carry this.
  4563. is_autologin: boolean;
  4564. // #2593: defined by BAMBUDDY_OIDC_* and rewritten from the environment on
  4565. // every boot. The API answers 409 to any write, so the settings UI must not
  4566. // offer edit/delete controls that cannot succeed. Optional so a response
  4567. // from an older backend still type-checks.
  4568. is_env_managed?: boolean;
  4569. }
  4570. export interface OIDCProviderCreate {
  4571. name: string;
  4572. issuer_url: string;
  4573. client_id: string;
  4574. client_secret: string;
  4575. scopes?: string;
  4576. is_enabled?: boolean;
  4577. auto_create_users?: boolean;
  4578. auto_link_existing_accounts?: boolean;
  4579. email_claim?: string;
  4580. require_email_verified?: boolean;
  4581. // #3107 — group sync. Omit both to leave them unchanged on update.
  4582. group_claim?: string;
  4583. group_mapping?: Record<string, string>;
  4584. icon_url?: string | null;
  4585. default_group_id?: number | null;
  4586. is_autologin?: boolean; // #1589
  4587. }
  4588. export interface OIDCLink {
  4589. id: number;
  4590. provider_id: number;
  4591. provider_name: string;
  4592. provider_email?: string | null;
  4593. created_at: string;
  4594. }
  4595. export interface TestSMTPRequest {
  4596. test_recipient: string;
  4597. // The form's settings, tested before they are saved. An empty password
  4598. // keeps the saved one.
  4599. smtp?: SMTPSettings;
  4600. }
  4601. export interface TestSMTPResponse {
  4602. success: boolean;
  4603. message: string;
  4604. }
  4605. export interface AdvancedAuthStatus {
  4606. advanced_auth_enabled: boolean;
  4607. smtp_configured: boolean;
  4608. // #1589: false hides the username/password form on the LoginPage; the env
  4609. // var BAMBUDDY_LOCAL_LOGIN=true on the server flips this back to true so
  4610. // the recovery path remains visible.
  4611. local_login_enabled: boolean;
  4612. // #1589: when set, LoginPage redirects to this provider's authorize URL
  4613. // on mount unless ?fallback=local is in the URL or the redirect times out.
  4614. autologin_provider_id: number | null;
  4615. }
  4616. export interface LDAPStatus {
  4617. ldap_enabled: boolean;
  4618. ldap_configured: boolean;
  4619. }
  4620. export interface EncryptionRowCounts {
  4621. oidc_providers: number;
  4622. user_totp: number;
  4623. }
  4624. export interface EncryptionStatus {
  4625. key_configured: boolean;
  4626. key_source: 'env' | 'file' | 'generated' | 'none';
  4627. legacy_plaintext_rows: EncryptionRowCounts;
  4628. encrypted_rows: EncryptionRowCounts;
  4629. decryption_broken: boolean;
  4630. // B2: count of rows skipped during the last legacy re-encryption migration.
  4631. // Surfaced via a yellow secondary banner in SecurityStatusCard.
  4632. migration_error_count: number;
  4633. }
  4634. export interface LDAPTestRequest {
  4635. ldap_server_url?: string;
  4636. ldap_bind_dn?: string;
  4637. ldap_bind_password?: string;
  4638. ldap_search_base?: string;
  4639. ldap_user_filter?: string;
  4640. ldap_security?: string;
  4641. }
  4642. export interface LDAPTestResponse {
  4643. success: boolean;
  4644. message: string;
  4645. }
  4646. export interface LDAPSearchResult {
  4647. username: string;
  4648. email: string | null;
  4649. display_name: string | null;
  4650. dn: string;
  4651. already_provisioned: boolean;
  4652. }
  4653. export interface SetupResponse {
  4654. auth_enabled: boolean;
  4655. admin_created?: boolean;
  4656. }
  4657. export interface AuthStatus {
  4658. auth_enabled: boolean;
  4659. requires_setup: boolean;
  4660. }
  4661. // API functions
  4662. export interface QueueHistoryFilters {
  4663. printerId?: number | null;
  4664. status?: string;
  4665. location?: string;
  4666. }
  4667. export interface QueueHistoryParams extends QueueHistoryFilters {
  4668. sortBy?: 'date' | 'name' | 'printer';
  4669. // Flips the default order: newest first by date, A to Z by name or printer.
  4670. reverse?: boolean;
  4671. limit?: number;
  4672. offset?: number;
  4673. }
  4674. export interface QueueHistoryPage {
  4675. // The page in display order, then any other runs of the batches on it.
  4676. items: PrintQueueItem[];
  4677. total: number;
  4678. locations: string[];
  4679. }
  4680. function queueHistorySearch(params: QueueHistoryParams): URLSearchParams {
  4681. const search = new URLSearchParams();
  4682. if (params.printerId) search.set('printer_id', String(params.printerId));
  4683. if (params.status) search.set('status', params.status);
  4684. if (params.location) search.set('location', params.location);
  4685. if (params.sortBy) search.set('sort_by', params.sortBy);
  4686. if (params.reverse) search.set('reverse', 'true');
  4687. if (params.limit !== undefined) search.set('limit', String(params.limit));
  4688. if (params.offset) search.set('offset', String(params.offset));
  4689. return search;
  4690. }
  4691. // Per-printer reads that a page showing every printer makes once per printer,
  4692. // coalesced into one bulk request per few milliseconds (see ./batch). Each
  4693. // keeps its single-printer request for a lone id.
  4694. const idsParam = (ids: number[]) => `ids=${ids.join(',')}`;
  4695. const printerStatusBatch = batched(
  4696. (id) => request<PrinterStatus>(`/printers/${id}/status`),
  4697. async (ids) => byField(await request<PrinterStatus[]>(`/bulk/printer-statuses?${idsParam(ids)}`), (s) => s.id),
  4698. );
  4699. const slotPresetsBatch = batched(
  4700. (id) => request<Record<number, SlotPresetMapping>>(`/printers/${id}/slot-presets`),
  4701. async (ids) => byId(await request<Record<string, Record<number, SlotPresetMapping>>>(`/bulk/slot-presets?${idsParam(ids)}`)),
  4702. );
  4703. const amsLabelsBatch = batched(
  4704. (id) => request<Record<number, string>>(`/printers/${id}/ams-labels`),
  4705. async (ids) => byId(await request<Record<string, Record<number, string>>>(`/bulk/ams-labels?${idsParam(ids)}`)),
  4706. );
  4707. type PrinterCardPlugs = { plug: SmartPlug | null; scripts: SmartPlug[] };
  4708. const cardPlugs = async (ids: number[]) =>
  4709. byId(await request<Record<string, PrinterCardPlugs>>(`/bulk/card-plugs?${idsParam(ids)}`));
  4710. const smartPlugBatch = batched(
  4711. (id) => request<SmartPlug | null>(`/smart-plugs/by-printer/${id}`),
  4712. async (ids) => new Map([...(await cardPlugs(ids))].map(([id, plugs]) => [id, plugs.plug])),
  4713. );
  4714. const scriptPlugsBatch = batched(
  4715. (id) => request<SmartPlug[]>(`/smart-plugs/by-printer/${id}/scripts`),
  4716. async (ids) => new Map([...(await cardPlugs(ids))].map(([id, plugs]) => [id, plugs.scripts])),
  4717. );
  4718. const haSensorReadingsBatch = batched(
  4719. (id) => request<PrinterHASensorReading[]>(`/ha-sensors/by-printer/${id}/readings`),
  4720. async (ids) => byId(await request<Record<string, PrinterHASensorReading[]>>(`/bulk/ha-sensor-readings?${idsParam(ids)}`)),
  4721. );
  4722. const firmwareUpdateBatch = batched(
  4723. (id) => request<FirmwareUpdateInfo>(`/firmware/updates/${id}`),
  4724. async (ids) =>
  4725. byField(await request<FirmwareUpdateInfo[]>(`/bulk/firmware-updates?${idsParam(ids)}`), (u) => u.printer_id),
  4726. );
  4727. // One batcher per status asked for: the bulk route takes a single status list.
  4728. const printerQueueBatches = new Map<string, (id: number) => Promise<PrintQueueItem[]>>();
  4729. const printerQueueBatch = (status: string) => {
  4730. let batch = printerQueueBatches.get(status);
  4731. if (!batch) {
  4732. batch = batched(
  4733. (id) => request<PrintQueueItem[]>(`/queue/?printer_id=${id}&status=${encodeURIComponent(status)}`),
  4734. async (ids) =>
  4735. byId(
  4736. await request<Record<string, PrintQueueItem[]>>(
  4737. `/bulk/printer-queues?${idsParam(ids)}&status=${encodeURIComponent(status)}`,
  4738. ),
  4739. ),
  4740. );
  4741. printerQueueBatches.set(status, batch);
  4742. }
  4743. return batch;
  4744. };
  4745. const foldersByArchiveBatch = batched(
  4746. (id) => request<LibraryFolder[]>(`/library/folders/by-archive/${id}`),
  4747. async (ids) => byId(await request<Record<string, LibraryFolder[]>>(`/bulk/archive-folders?${idsParam(ids)}`)),
  4748. );
  4749. export const api = {
  4750. // Overlay branding
  4751. getOverlayLogo: async (token: string | null, signal?: AbortSignal): Promise<Blob | null> => {
  4752. const endpoint = token ? `/overlay-branding/logo?token=${encodeURIComponent(token)}` : '/settings/overlay-logo';
  4753. const response = await fetch(`${API_BASE}${endpoint}`, {
  4754. signal, cache: 'no-store',
  4755. headers: !token && authToken ? { Authorization: `Bearer ${authToken}` } : {},
  4756. });
  4757. if (response.status === 404) return null;
  4758. if (!response.ok) throw new Error(`HTTP ${response.status}`);
  4759. return response.blob();
  4760. },
  4761. uploadOverlayLogo: async (file: File): Promise<void> => {
  4762. const body = new FormData();
  4763. body.append('file', file);
  4764. const response = await fetch(`${API_BASE}/settings/overlay-logo`, {
  4765. method: 'POST', body,
  4766. headers: authToken ? { Authorization: `Bearer ${authToken}` } : {},
  4767. });
  4768. if (!response.ok) {
  4769. const error = await response.json().catch(() => ({}));
  4770. const detail = error?.detail;
  4771. const message = typeof detail === 'string' ? detail : detail?.message;
  4772. throw new Error(typeof message === 'string' && message ? message : `HTTP ${response.status}`);
  4773. }
  4774. },
  4775. deleteOverlayLogo: () => request<{ status: string }>('/settings/overlay-logo', { method: 'DELETE' }),
  4776. // Authentication
  4777. getAuthStatus: () => request<AuthStatus>('/auth/status'),
  4778. setupAuth: (data: SetupRequest) =>
  4779. request<SetupResponse>('/auth/setup', {
  4780. method: 'POST',
  4781. body: JSON.stringify(data),
  4782. }),
  4783. login: (data: LoginRequest) =>
  4784. request<LoginResponse>('/auth/login', {
  4785. method: 'POST',
  4786. body: JSON.stringify(data),
  4787. }),
  4788. logout: () =>
  4789. request<{ message: string }>('/auth/logout', {
  4790. method: 'POST',
  4791. }),
  4792. getCurrentUser: () => request<UserResponse>('/auth/me'),
  4793. disableAuth: () =>
  4794. request<{ message: string; auth_enabled: boolean }>('/auth/disable', {
  4795. method: 'POST',
  4796. }),
  4797. // Advanced Authentication
  4798. testSMTP: (data: TestSMTPRequest) =>
  4799. request<TestSMTPResponse>('/auth/smtp/test', {
  4800. method: 'POST',
  4801. body: JSON.stringify(data),
  4802. }),
  4803. getSMTPSettings: () => request<SMTPSettings | null>('/auth/smtp'),
  4804. saveSMTPSettings: (data: SMTPSettings) =>
  4805. request<{ message: string }>('/auth/smtp', {
  4806. method: 'POST',
  4807. body: JSON.stringify(data),
  4808. }),
  4809. enableAdvancedAuth: () =>
  4810. request<{ message: string; advanced_auth_enabled: boolean }>('/auth/advanced-auth/enable', {
  4811. method: 'POST',
  4812. }),
  4813. disableAdvancedAuth: () =>
  4814. request<{ message: string; advanced_auth_enabled: boolean }>('/auth/advanced-auth/disable', {
  4815. method: 'POST',
  4816. }),
  4817. getAdvancedAuthStatus: () => request<AdvancedAuthStatus>('/auth/advanced-auth/status'),
  4818. // LDAP Authentication
  4819. getLDAPStatus: () => request<LDAPStatus>('/auth/ldap/status'),
  4820. getEncryptionStatus: () => request<EncryptionStatus>('/auth/encryption-status'),
  4821. // form: the settings being edited, tested before they are saved. An empty
  4822. // bind password keeps the saved one.
  4823. testLDAP: (form?: LDAPTestRequest) =>
  4824. request<LDAPTestResponse>('/auth/ldap/test', {
  4825. method: 'POST',
  4826. ...(form ? { body: JSON.stringify(form) } : {}),
  4827. }),
  4828. searchLDAPDirectory: (q: string) =>
  4829. request<LDAPSearchResult[]>(`/auth/ldap/search?q=${encodeURIComponent(q)}`),
  4830. provisionLDAPUser: (username: string) =>
  4831. request<UserResponse>('/auth/ldap/provision', {
  4832. method: 'POST',
  4833. body: JSON.stringify({ username }),
  4834. }),
  4835. forgotPassword: (data: ForgotPasswordRequest) =>
  4836. request<ForgotPasswordResponse>('/auth/forgot-password', {
  4837. method: 'POST',
  4838. body: JSON.stringify(data),
  4839. }),
  4840. // H-6: Confirm password reset using the token from the emailed link
  4841. forgotPasswordConfirm: (token: string, newPassword: string) =>
  4842. request<ForgotPasswordResponse>('/auth/forgot-password/confirm', {
  4843. method: 'POST',
  4844. body: JSON.stringify({ token, new_password: newPassword }),
  4845. }),
  4846. resetUserPassword: (data: ResetPasswordRequest) =>
  4847. request<ResetPasswordResponse>('/auth/reset-password', {
  4848. method: 'POST',
  4849. body: JSON.stringify(data),
  4850. }),
  4851. // 2FA - status
  4852. get2FAStatus: () => request<TwoFAStatus>('/auth/2fa/status'),
  4853. // 2FA - TOTP
  4854. setupTOTP: () => request<TOTPSetupResponse>('/auth/2fa/totp/setup', { method: 'POST' }),
  4855. enableTOTP: (code: string) =>
  4856. request<TOTPEnableResponse>('/auth/2fa/totp/enable', {
  4857. method: 'POST',
  4858. body: JSON.stringify({ code }),
  4859. }),
  4860. disableTOTP: (code: string) =>
  4861. request<{ message: string }>('/auth/2fa/totp/disable', {
  4862. method: 'POST',
  4863. body: JSON.stringify({ code }),
  4864. }),
  4865. regenerateBackupCodes: (code: string) =>
  4866. request<BackupCodesResponse>('/auth/2fa/totp/regenerate-backup-codes', {
  4867. method: 'POST',
  4868. body: JSON.stringify({ code }),
  4869. }),
  4870. // 2FA - Email OTP
  4871. // Step 1: send a verification code to the user's email (proof of possession)
  4872. enableEmailOTP: () =>
  4873. request<{ message: string; setup_token: string }>('/auth/2fa/email/enable', { method: 'POST' }),
  4874. // Step 2: confirm with the code received by email
  4875. confirmEnableEmailOTP: (setup_token: string, code: string) =>
  4876. request<{ message: string }>('/auth/2fa/email/enable/confirm', {
  4877. method: 'POST',
  4878. body: JSON.stringify({ setup_token, code }),
  4879. }),
  4880. // Disable requires account password for re-auth
  4881. disableEmailOTP: (password: string) =>
  4882. request<{ message: string }>('/auth/2fa/email/disable', {
  4883. method: 'POST',
  4884. body: JSON.stringify({ password }),
  4885. }),
  4886. sendEmailOTP: (preAuthToken: string) =>
  4887. request<{ message: string; pre_auth_token?: string }>('/auth/2fa/email/send', {
  4888. method: 'POST',
  4889. body: JSON.stringify({ pre_auth_token: preAuthToken }),
  4890. }),
  4891. // 2FA - verify (completes login)
  4892. verify2FA: (data: TwoFAVerifyRequest) =>
  4893. request<LoginResponse>('/auth/2fa/verify', {
  4894. method: 'POST',
  4895. body: JSON.stringify(data),
  4896. }),
  4897. // 2FA - admin
  4898. // adminPassword: the calling admin's own password; null for an admin
  4899. // without one (LDAP / OIDC accounts usually), whom the route does not ask.
  4900. admin2FADisable: (userId: number, adminPassword: string | null) =>
  4901. request<{ message: string; had_2fa: boolean }>(`/auth/2fa/admin/${userId}`, {
  4902. method: 'DELETE',
  4903. body: JSON.stringify({ admin_password: adminPassword }),
  4904. }),
  4905. // OIDC providers (public list)
  4906. getOIDCProviders: () => request<OIDCProviderPublic[]>('/auth/oidc/providers'),
  4907. // OIDC providers (admin)
  4908. getOIDCProvidersAll: () => request<OIDCProvider[]>('/auth/oidc/providers/all'),
  4909. createOIDCProvider: (data: OIDCProviderCreate) =>
  4910. request<OIDCProvider>('/auth/oidc/providers', {
  4911. method: 'POST',
  4912. body: JSON.stringify(data),
  4913. }),
  4914. updateOIDCProvider: (id: number, data: Partial<OIDCProviderCreate>) =>
  4915. request<OIDCProvider>(`/auth/oidc/providers/${id}`, {
  4916. method: 'PUT',
  4917. body: JSON.stringify(data),
  4918. }),
  4919. deleteOIDCProvider: (id: number) =>
  4920. request<{ message: string }>(`/auth/oidc/providers/${id}`, { method: 'DELETE' }),
  4921. // OIDC provider icon proxy (#1333) — same-origin path so the strict
  4922. // img-src CSP stays in force. Returns a SameOriginUrl-branded string
  4923. // so a future caller can't accidentally substitute an attacker-
  4924. // controlled URL where this is consumed.
  4925. oidcProviderIconUrl: (id: number): SameOriginUrl =>
  4926. `/api/v1/auth/oidc/providers/${id}/icon` as SameOriginUrl,
  4927. deleteOIDCProviderIcon: (id: number) =>
  4928. request<void>(`/auth/oidc/providers/${id}/icon`, { method: 'DELETE' }),
  4929. refreshOIDCProviderIcon: (id: number) =>
  4930. request<OIDCProvider>(`/auth/oidc/providers/${id}/icon/refresh`, { method: 'POST' }),
  4931. // OIDC authorize URL
  4932. getOIDCAuthorizeUrl: (providerId: number) =>
  4933. request<{ auth_url: string }>(`/auth/oidc/authorize/${providerId}`),
  4934. // OIDC exchange token for JWT
  4935. exchangeOIDCToken: (oidcToken: string) =>
  4936. request<LoginResponse>('/auth/oidc/exchange', {
  4937. method: 'POST',
  4938. body: JSON.stringify({ oidc_token: oidcToken }),
  4939. }),
  4940. // OIDC links for current user
  4941. getOIDCLinks: () => request<OIDCLink[]>('/auth/oidc/links'),
  4942. deleteOIDCLink: (providerId: number) =>
  4943. request<{ message: string }>(`/auth/oidc/links/${providerId}`, { method: 'DELETE' }),
  4944. // Users
  4945. getUsers: () => request<UserResponse[]>('/users/'),
  4946. getUsersSlim: () => request<UserSlim[]>('/users/slim'),
  4947. createUser: (data: UserCreate) =>
  4948. request<UserResponse>('/users/', {
  4949. method: 'POST',
  4950. body: JSON.stringify(data),
  4951. }),
  4952. updateUser: (id: number, data: UserUpdate) =>
  4953. request<UserResponse>(`/users/${id}`, {
  4954. method: 'PATCH',
  4955. body: JSON.stringify(data),
  4956. }),
  4957. deleteUser: (id: number, deleteItems: boolean = false) =>
  4958. request<void>(`/users/${id}?delete_items=${deleteItems}`, {
  4959. method: 'DELETE',
  4960. }),
  4961. getUserItemsCount: (id: number) =>
  4962. request<{ archives: number; queue_items: number; library_files: number }>(`/users/${id}/items-count`),
  4963. changePassword: (currentPassword: string, newPassword: string) =>
  4964. request<{ message: string }>('/users/me/change-password', {
  4965. method: 'POST',
  4966. body: JSON.stringify({ current_password: currentPassword, new_password: newPassword }),
  4967. }),
  4968. // User Email Notifications
  4969. getUserEmailPreferences: () =>
  4970. request<UserEmailPreferences>('/user-notifications/preferences'),
  4971. updateUserEmailPreferences: (data: UserEmailPreferences) =>
  4972. request<UserEmailPreferences>('/user-notifications/preferences', {
  4973. method: 'PUT',
  4974. body: JSON.stringify(data),
  4975. }),
  4976. // Groups
  4977. getPermissions: () => request<PermissionsListResponse>('/groups/permissions'),
  4978. getGroups: () => request<Group[]>('/groups/'),
  4979. getGroup: (id: number) => request<GroupDetail>(`/groups/${id}`),
  4980. createGroup: (data: GroupCreate) =>
  4981. request<Group>('/groups/', {
  4982. method: 'POST',
  4983. body: JSON.stringify(data),
  4984. }),
  4985. updateGroup: (id: number, data: GroupUpdate) =>
  4986. request<Group>(`/groups/${id}`, {
  4987. method: 'PATCH',
  4988. body: JSON.stringify(data),
  4989. }),
  4990. deleteGroup: (id: number) =>
  4991. request<void>(`/groups/${id}`, {
  4992. method: 'DELETE',
  4993. }),
  4994. // Printers
  4995. getPrinters: () => request<Printer[]>('/printers/'),
  4996. getPrinter: (id: number) => request<Printer>(`/printers/${id}`),
  4997. createPrinter: (data: PrinterCreate) =>
  4998. request<Printer>('/printers/', {
  4999. method: 'POST',
  5000. body: JSON.stringify(data),
  5001. }),
  5002. updatePrinter: (id: number, data: Partial<PrinterCreate>) =>
  5003. request<Printer>(`/printers/${id}`, {
  5004. method: 'PATCH',
  5005. body: JSON.stringify(data),
  5006. }),
  5007. getWledPresets: (id: number, baseUrl: string) =>
  5008. request<WLEDPreset[]>(`/printers/${id}/wled/presets`, {
  5009. method: 'POST',
  5010. body: JSON.stringify({ base_url: baseUrl }),
  5011. }),
  5012. testWledConnection: (id: number, baseUrl: string) =>
  5013. request<WLEDConnectionInfo>(`/printers/${id}/wled/test-connection`, {
  5014. method: 'POST',
  5015. body: JSON.stringify({ base_url: baseUrl }),
  5016. }),
  5017. testWledPreset: (id: number, baseUrl: string, presetId: number) =>
  5018. request<{ success: boolean }>(`/printers/${id}/wled/test-preset`, {
  5019. method: 'POST',
  5020. body: JSON.stringify({ base_url: baseUrl, preset_id: presetId }),
  5021. }),
  5022. deletePrinter: (id: number, deleteArchives: boolean = true) =>
  5023. request<{ status: string; archives_deleted: boolean }>(
  5024. `/printers/${id}?delete_archives=${deleteArchives}`,
  5025. { method: 'DELETE' }
  5026. ),
  5027. getDeveloperModeWarnings: () =>
  5028. request<{ printer_id: number; name: string }[]>('/printers/developer-mode-warnings'),
  5029. getAvailableFilaments: (model: string, location?: string) => {
  5030. const params = new URLSearchParams({ model });
  5031. if (location) params.set('location', location);
  5032. return request<Array<{ type: string; color: string; tray_info_idx: string; tray_sub_brands: string; extruder_id: number | null }>>(`/printers/available-filaments?${params}`);
  5033. },
  5034. getPrinterLocations: () => request<PrinterLocation[]>('/printer-locations/'),
  5035. createPrinterLocation: (data: { name: string; icon?: string | null; color?: string | null }) =>
  5036. request<PrinterLocation>('/printer-locations/', { method: 'POST', body: JSON.stringify(data) }),
  5037. updatePrinterLocation: (data: PrinterLocationUpdate) =>
  5038. request<PrinterLocation>('/printer-locations/', { method: 'PATCH', body: JSON.stringify(data) }),
  5039. deletePrinterLocations: (names: string[]) =>
  5040. request<{ deleted: number; printers_ungrouped: number }>('/printer-locations/delete', {
  5041. method: 'POST',
  5042. body: JSON.stringify({ names }),
  5043. }),
  5044. assignPrinterLocation: (printerIds: number[], location: string | null) =>
  5045. request<{ moved: number }>('/printer-locations/assign', {
  5046. method: 'POST',
  5047. body: JSON.stringify({ printer_ids: printerIds, location }),
  5048. }),
  5049. getPrinterStatus: (id: number) => printerStatusBatch(id),
  5050. refreshPrinterStatus: (id: number) =>
  5051. request<{ status: string }>(`/printers/${id}/refresh-status`, {
  5052. method: 'POST',
  5053. }),
  5054. connectPrinter: (id: number) =>
  5055. request<{ connected: boolean }>(`/printers/${id}/connect`, {
  5056. method: 'POST',
  5057. }),
  5058. getUsbCameras: () => request<{ cameras: UsbCamera[] }>('/printers/usb-cameras'),
  5059. testExternalCamera: (printerId: number, url: string, cameraType: string) =>
  5060. // `coalesced` is true when the frame came from a capture that was already
  5061. // running (Obico polling, a snapshot) rather than a connection this test
  5062. // opened — a single-reader camera is shared rather than opened twice, so
  5063. // the result is real but says nothing about reaching the camera just now.
  5064. // `live_view` is true when the tested camera is the one a viewer is
  5065. // watching: the answer comes from the live frame, not a test of its own.
  5066. // In the body: the URL may carry the camera login, and a query string
  5067. // ends up in the server's access log.
  5068. request<{ success: boolean; error?: string; resolution?: string; coalesced?: boolean; live_view?: boolean }>(
  5069. `/printers/${printerId}/camera/external/test`,
  5070. { method: 'POST', body: JSON.stringify({ url, camera_type: cameraType }) }
  5071. ),
  5072. // Print Control
  5073. stopPrint: (printerId: number) =>
  5074. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/stop`, {
  5075. method: 'POST',
  5076. }),
  5077. pausePrint: (printerId: number) =>
  5078. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/pause`, {
  5079. method: 'POST',
  5080. }),
  5081. resumePrint: (printerId: number) =>
  5082. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/resume`, {
  5083. method: 'POST',
  5084. }),
  5085. clearPlate: (printerId: number) =>
  5086. request<{ success: boolean; message: string }>(`/printers/${printerId}/clear-plate`, {
  5087. method: 'POST',
  5088. }),
  5089. // Get current print user (for reprint tracking - Issue #206)
  5090. getCurrentPrintUser: (printerId: number) =>
  5091. request<{ user_id?: number; username?: string }>(`/printers/${printerId}/current-print-user`),
  5092. // Print Speed Control
  5093. setPrintSpeed: (printerId: number, mode: number) =>
  5094. request<{ success: boolean; message: string }>(`/printers/${printerId}/print-speed?mode=${mode}`, {
  5095. method: 'POST',
  5096. }),
  5097. setNozzleTemperature: (printerId: number, target: number, nozzle: number = 0) =>
  5098. request<{ success: boolean; message: string }>(
  5099. `/printers/${printerId}/temperature/nozzle?target=${target}&nozzle=${nozzle}`,
  5100. { method: 'POST' }
  5101. ),
  5102. setBedTemperature: (printerId: number, target: number) =>
  5103. request<{ success: boolean; message: string }>(`/printers/${printerId}/temperature/bed?target=${target}`, {
  5104. method: 'POST',
  5105. }),
  5106. setChamberTemperature: (printerId: number, target: number) =>
  5107. request<{ success: boolean; message: string }>(`/printers/${printerId}/temperature/chamber?target=${target}`, {
  5108. method: 'POST',
  5109. }),
  5110. setFanSpeed: (printerId: number, fan: 'part' | 'aux' | 'aux2' | 'chamber', speed: number) =>
  5111. request<{ success: boolean; message: string }>(`/printers/${printerId}/fan-speed?fan=${fan}&speed=${speed}`, {
  5112. method: 'POST',
  5113. }),
  5114. selectExtruder: (printerId: number, extruder: number) =>
  5115. request<{ success: boolean; message: string }>(`/printers/${printerId}/select-extruder?extruder=${extruder}`, {
  5116. method: 'POST',
  5117. }),
  5118. setAirductMode: (printerId: number, mode: 'cooling' | 'heating') =>
  5119. request<{ success: boolean; message: string }>(`/printers/${printerId}/airduct-mode?mode=${mode}`, {
  5120. method: 'POST',
  5121. }),
  5122. // Bed (Z-axis) jog
  5123. bedJog: (printerId: number, distance: number) =>
  5124. request<{ success: boolean; message: string }>(
  5125. `/printers/${printerId}/bed-jog?distance=${distance}`,
  5126. { method: 'POST' }
  5127. ),
  5128. xyJog: (printerId: number, x: number, y: number) =>
  5129. request<{ success: boolean; message: string }>(
  5130. `/printers/${printerId}/xy-jog?x=${x}&y=${y}`,
  5131. { method: 'POST' }
  5132. ),
  5133. extruderJog: (printerId: number, distance: number) =>
  5134. request<{ success: boolean; message: string }>(
  5135. `/printers/${printerId}/extruder-jog?distance=${distance}`,
  5136. { method: 'POST' }
  5137. ),
  5138. homeAxes: (printerId: number, axes: 'z' | 'xy' | 'all' = 'z') =>
  5139. request<{ success: boolean; message: string }>(
  5140. `/printers/${printerId}/home-axes?axes=${axes}`,
  5141. { method: 'POST' }
  5142. ),
  5143. // Chamber Light Control
  5144. setChamberLight: (printerId: number, on: boolean) =>
  5145. request<{ success: boolean; message: string }>(`/printers/${printerId}/chamber-light?on=${on}`, {
  5146. method: 'POST',
  5147. }),
  5148. // AMS Drying Control
  5149. startDrying: (printerId: number, amsId: number, temp: number, duration: number, filament: string = '', rotateTray: boolean = false) =>
  5150. request<{ status: string; ams_id: number; temp: number; duration: number }>(
  5151. `/printers/${printerId}/drying/start?ams_id=${amsId}&temp=${temp}&duration=${duration}&filament=${encodeURIComponent(filament)}&rotate_tray=${rotateTray}`,
  5152. { method: 'POST' }
  5153. ),
  5154. stopDrying: (printerId: number, amsId: number) =>
  5155. request<{ status: string; ams_id: number }>(
  5156. `/printers/${printerId}/drying/stop?ams_id=${amsId}`,
  5157. { method: 'POST' }
  5158. ),
  5159. // Scheduled (delayed) drying runs (#2638)
  5160. createScheduledDrying: (data: {
  5161. printer_id: number;
  5162. ams_id: number;
  5163. temp: number;
  5164. duration_hours: number;
  5165. filament?: string;
  5166. rotate_tray?: boolean;
  5167. start_after: string | null;
  5168. }) =>
  5169. request<ScheduledDrying>('/scheduled-dryings', {
  5170. method: 'POST',
  5171. body: JSON.stringify(data),
  5172. }),
  5173. // Omit printerId for the whole fleet in one request; the printer cards share
  5174. // that single query rather than each polling for its own id.
  5175. listScheduledDryings: (printerId?: number) =>
  5176. request<ScheduledDrying[]>(
  5177. printerId === undefined ? '/scheduled-dryings' : `/scheduled-dryings?printer_id=${printerId}`
  5178. ),
  5179. cancelScheduledDrying: (id: number) =>
  5180. request<{ status: string; id: number }>(`/scheduled-dryings/${id}`, { method: 'DELETE' }),
  5181. // AMS Filament Backup (auto-switch to a backup spool when one runs out)
  5182. setAmsFilamentBackup: (printerId: number, enabled: boolean) =>
  5183. request<{ success: boolean; ams_filament_backup: boolean }>(
  5184. `/printers/${printerId}/ams-backup?enabled=${enabled}`,
  5185. { method: 'POST' }
  5186. ),
  5187. // Per-globalTrayId remaining grams for this printer's inventory-bound slots
  5188. // (#1766). Drives the client-side "Prefer Lowest Remaining Filament" sort
  5189. // when computing the AMS mapping; mirrors backend `_build_inventory_remain_overrides`
  5190. // so internal and Spoolman modes both work uniformly.
  5191. getInventoryRemain: (printerId: number) =>
  5192. request<InventoryRemainResponse>(
  5193. `/printers/${printerId}/inventory-remain`,
  5194. ),
  5195. // Skip Objects
  5196. getPrintableObjects: (printerId: number) =>
  5197. request<{
  5198. objects: Array<{ id: number; name: string; x: number | null; y: number | null; skipped: boolean }>;
  5199. total: number;
  5200. skipped_count: number;
  5201. is_printing: boolean;
  5202. bbox_all: [number, number, number, number] | null;
  5203. }>(`/printers/${printerId}/print/objects`),
  5204. skipObjects: (printerId: number, objectIds: number[]) =>
  5205. request<{ success: boolean; message: string; skipped_objects: number[] }>(
  5206. `/printers/${printerId}/print/skip-objects`,
  5207. {
  5208. method: 'POST',
  5209. body: JSON.stringify(objectIds),
  5210. }
  5211. ),
  5212. // HMS Errors
  5213. clearHMSErrors: (printerId: number) =>
  5214. request<{ success: boolean; message: string }>(`/printers/${printerId}/hms/clear`, { method: 'POST' }),
  5215. executeHMSAction: (printerId: number, data: HMSActionBody) =>
  5216. request<{ success: boolean; message: string }>(`/printers/${printerId}/hms/execute-action`, {
  5217. method: 'POST',
  5218. body: JSON.stringify(data),
  5219. }),
  5220. // AMS Control
  5221. refreshAmsSlot: (printerId: number, amsId: number, slotId: number) =>
  5222. request<{ success: boolean; message: string }>(
  5223. `/printers/${printerId}/ams/${amsId}/slot/${slotId}/refresh`,
  5224. { method: 'POST' }
  5225. ),
  5226. // Load filament from a tray. trayId: 0-15 for AMS (amsId*4+slotId), 128-135 for an
  5227. // AMS-HT (its unit id), 254 for external spool.
  5228. // extruderId (0 = right, 1 = left) names the hotend to feed. Pass it only on a
  5229. // printer with a Filament Track Switch — there the AMS is bound to a switch
  5230. // inlet rather than a hotend, so the firmware cannot work the target out and
  5231. // drops the command. Omit it everywhere else, as BambuStudio does.
  5232. loadAmsTray: (printerId: number, trayId: number, extruderId?: number) =>
  5233. request<{ success: boolean; message: string }>(
  5234. `/printers/${printerId}/ams/load?tray_id=${trayId}` +
  5235. (extruderId !== undefined ? `&extruder_id=${extruderId}` : ''),
  5236. { method: 'POST' }
  5237. ),
  5238. // Unload filament. trayId names the slot to unload, which is what tells a
  5239. // dual-nozzle printer which of its two hotends to act on; omit it to unload
  5240. // whatever the printer's single tray_now field names.
  5241. unloadAms: (printerId: number, trayId?: number) =>
  5242. request<{ success: boolean; message: string }>(
  5243. `/printers/${printerId}/ams/unload` + (trayId !== undefined ? `?tray_id=${trayId}` : ''),
  5244. { method: 'POST' }
  5245. ),
  5246. // MQTT Debug Logging
  5247. enableMQTTLogging: (printerId: number) =>
  5248. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/enable`, {
  5249. method: 'POST',
  5250. }),
  5251. disableMQTTLogging: (printerId: number) =>
  5252. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/disable`, {
  5253. method: 'POST',
  5254. }),
  5255. getMQTTLogs: (printerId: number) =>
  5256. request<MQTTLogsResponse>(`/printers/${printerId}/logging`),
  5257. clearMQTTLogs: (printerId: number) =>
  5258. request<{ status: string }>(`/printers/${printerId}/logging`, {
  5259. method: 'DELETE',
  5260. }),
  5261. // Printer File Manager
  5262. getPrinterFiles: (printerId: number, path = '/') =>
  5263. request<{
  5264. path: string;
  5265. files: Array<{
  5266. name: string;
  5267. is_directory: boolean;
  5268. size: number;
  5269. path: string;
  5270. mtime?: string;
  5271. }>;
  5272. warnings: Array<'printer_unavailable' | 'listing_timed_out'>;
  5273. }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`),
  5274. getPrinterFileDownloadUrl: (printerId: number, path: string) =>
  5275. `${API_BASE}/printers/${printerId}/files/download?path=${encodeURIComponent(path)}`,
  5276. getPrinterFileGcodeUrl: (printerId: number, path: string) =>
  5277. `${API_BASE}/printers/${printerId}/files/gcode?path=${encodeURIComponent(path)}`,
  5278. getPrinterFilePlates: (printerId: number, path: string) =>
  5279. request<{
  5280. printer_id: number;
  5281. path: string;
  5282. filename: string;
  5283. plates: Array<{
  5284. index: number;
  5285. name: string | null;
  5286. objects: string[];
  5287. has_thumbnail: boolean;
  5288. thumbnail_url: string | null;
  5289. print_time_seconds: number | null;
  5290. filament_used_grams: number | null;
  5291. filaments: Array<{
  5292. slot_id: number;
  5293. type: string;
  5294. color: string;
  5295. used_grams: number;
  5296. used_meters: number;
  5297. }>;
  5298. }>;
  5299. is_multi_plate: boolean;
  5300. }>(`/printers/${printerId}/files/plates?path=${encodeURIComponent(path)}`),
  5301. getPrinterFilePlateThumbnail: (printerId: number, plateIndex: number, path: string) =>
  5302. withMediaToken(`${API_BASE}/printers/${printerId}/files/plate-thumbnail/${plateIndex}?path=${encodeURIComponent(path)}`),
  5303. downloadPrinterFilesAsZip: async (
  5304. printerId: number,
  5305. paths: string[],
  5306. sizes: Record<string, number>,
  5307. filename = 'printer-files.zip',
  5308. asZip = true,
  5309. signal?: AbortSignal,
  5310. onProgress?: (completed: number, total: number) => void,
  5311. ): Promise<{ requested: number; successful: number; failed: number }> => {
  5312. type JobStatus = {
  5313. job_id: string;
  5314. state: 'queued' | 'preparing' | 'ready' | 'failed' | 'cancelled';
  5315. requested: number;
  5316. successful: number;
  5317. failed: number;
  5318. token: string | null;
  5319. message: string | null;
  5320. };
  5321. let jobId: string | null = null;
  5322. try {
  5323. if (signal?.aborted) throw new DOMException('Download cancelled', 'AbortError');
  5324. let status = await request<JobStatus>(`/printers/${printerId}/files/download-job`, {
  5325. method: 'POST',
  5326. body: JSON.stringify({ paths, sizes, filename, as_zip: asZip }),
  5327. signal,
  5328. });
  5329. jobId = status.job_id;
  5330. let polls = 0;
  5331. while (status.state === 'queued' || status.state === 'preparing') {
  5332. onProgress?.(status.successful + status.failed, status.requested);
  5333. // Small selections finish in the first seconds, so poll quickly there.
  5334. // A large one runs for up to half an hour, where half-second polling is
  5335. // thousands of requests that each re-check the caller's credentials.
  5336. const delay = polls < 10 ? 500 : 2000;
  5337. polls += 1;
  5338. await new Promise<void>((resolve, reject) => {
  5339. if (signal?.aborted) {
  5340. reject(new DOMException('Download cancelled', 'AbortError'));
  5341. return;
  5342. }
  5343. const onAbort = () => {
  5344. window.clearTimeout(timer);
  5345. reject(new DOMException('Download cancelled', 'AbortError'));
  5346. };
  5347. const timer = window.setTimeout(() => {
  5348. signal?.removeEventListener('abort', onAbort);
  5349. resolve();
  5350. }, delay);
  5351. signal?.addEventListener('abort', onAbort, { once: true });
  5352. });
  5353. status = await request<JobStatus>(`/printers/${printerId}/files/download-jobs/${jobId}`, { signal });
  5354. }
  5355. onProgress?.(status.successful + status.failed, status.requested);
  5356. if (status.state !== 'ready' || !status.token) {
  5357. throw new Error(status.message || (status.state === 'cancelled'
  5358. ? 'Download cancelled'
  5359. : 'Printer download preparation failed'));
  5360. }
  5361. const link = document.createElement('a');
  5362. link.href = `${API_BASE}/printers/${printerId}/files/dl/${encodeURIComponent(status.token)}/${encodeURIComponent(filename)}`;
  5363. link.download = filename;
  5364. document.body.appendChild(link);
  5365. link.click();
  5366. link.remove();
  5367. return {
  5368. requested: status.requested,
  5369. successful: status.successful,
  5370. failed: status.failed,
  5371. };
  5372. } catch (error) {
  5373. if (jobId) {
  5374. await request(`/printers/${printerId}/files/download-jobs/${jobId}`, { method: 'DELETE' }).catch(() => undefined);
  5375. }
  5376. throw error;
  5377. }
  5378. },
  5379. deletePrinterFile: (printerId: number, path: string) =>
  5380. request<{ status: string; path: string }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`, {
  5381. method: 'DELETE',
  5382. }),
  5383. getPrinterStorage: (printerId: number) =>
  5384. request<{ used_bytes: number | null; free_bytes: number | null }>(`/printers/${printerId}/storage`),
  5385. // Archives
  5386. getArchives: (printerId?: number, projectId?: number, limit = 10000, offset = 0, dateFrom?: string, dateTo?: string) => {
  5387. const params = new URLSearchParams();
  5388. if (printerId) params.set('printer_id', String(printerId));
  5389. if (projectId) params.set('project_id', String(projectId));
  5390. params.set('limit', String(limit));
  5391. params.set('offset', String(offset));
  5392. if (dateFrom) params.set('date_from', dateFrom);
  5393. if (dateTo) params.set('date_to', dateTo);
  5394. addDayZone(params);
  5395. return request<Archive[]>(`/archives/?${params}`);
  5396. },
  5397. // Latest archive of every printer in one request, for the printer cards.
  5398. getLastArchivePerPrinter: () => request<Archive[]>('/archives/last-per-printer'),
  5399. getArchivesSlim: (dateFrom?: string, dateTo?: string, createdById?: number) => {
  5400. const params = new URLSearchParams();
  5401. if (dateFrom) params.set('date_from', dateFrom);
  5402. if (dateTo) params.set('date_to', dateTo);
  5403. addDayZone(params);
  5404. if (createdById !== undefined) params.set('created_by_id', String(createdById));
  5405. const qs = params.toString();
  5406. return request<ArchiveSlim[]>(`/archives/slim${qs ? `?${qs}` : ''}`);
  5407. },
  5408. getArchive: (id: number, runId?: number | null) =>
  5409. request<Archive>(`/archives/${id}${runId != null ? `?run_id=${runId}` : ''}`),
  5410. getArchiveRuns: (id: number) => request<PrintLogResponse>(`/archives/${id}/runs`),
  5411. // The prints of the archives the caller sees that ended between two days
  5412. // (archive redesign P4: the calendar), in id order.
  5413. getArchivePrints: (params: { dateFrom: string; dateTo: string; printerId?: number; limit?: number; offset?: number }) => {
  5414. const search = new URLSearchParams({ date_from: params.dateFrom, date_to: params.dateTo });
  5415. if (params.printerId) search.set('printer_id', String(params.printerId));
  5416. if (params.limit) search.set('limit', String(params.limit));
  5417. if (params.offset) search.set('offset', String(params.offset));
  5418. addDayZone(search);
  5419. return request<PrintLogResponse>(`/archives/prints?${search}`);
  5420. },
  5421. /**
  5422. * Pre-flight for the delete-confirm modal (#1734). Returns the number of
  5423. * related queue items that will be removed along with the archive AND how
  5424. * many are currently printing (server 409s on delete if > 0).
  5425. */
  5426. getArchiveDeleteImpact: (id: number) =>
  5427. request<{ related_queue_items: number; currently_printing: number }>(
  5428. `/archives/${id}/delete-impact`
  5429. ),
  5430. getNo3MFWarning: () =>
  5431. request<{
  5432. has_fallback: boolean;
  5433. reason:
  5434. | 'ftps_cooloff'
  5435. | 'ftp_transfer_failed'
  5436. | 'internal_storage'
  5437. | 'no_external_storage'
  5438. | 'internal_history'
  5439. | null;
  5440. }>(
  5441. '/archives/no-3mf-warning',
  5442. ),
  5443. updateArchive: (id: number, data: {
  5444. printer_id?: number | null;
  5445. project_id?: number | null;
  5446. print_name?: string;
  5447. is_favorite?: boolean;
  5448. tags?: string;
  5449. notes?: string;
  5450. cost?: number;
  5451. failure_reason?: string | null;
  5452. status?: string;
  5453. quantity?: number;
  5454. external_url?: string | null;
  5455. filament_used_grams?: number | null;
  5456. // Post-print outcome verdict (#1898); null clears it
  5457. user_verdict?: 'good' | 'reject' | null;
  5458. // Which surface answered. The backend only accepts the sources a client
  5459. // can honestly claim and defaults to 'api' when none is given.
  5460. user_verdict_source?: 'dialog' | 'printer_card';
  5461. // The run the verdict / outcome is for; omitted means the latest run.
  5462. run_id?: number;
  5463. }) =>
  5464. request<Archive>(`/archives/${id}`, {
  5465. method: 'PATCH',
  5466. body: JSON.stringify(data),
  5467. }),
  5468. toggleFavorite: (id: number) =>
  5469. request<Archive>(`/archives/${id}/favorite`, { method: 'POST' }),
  5470. // Soft-deletes by default (#1343): files removed from disk, row hidden
  5471. // from listings, but its filament / time / cost / energy contribution
  5472. // stays in Quick Stats. Pass purgeStats=true to hard-delete and drop the
  5473. // row from statistics too.
  5474. deleteArchive: (id: number, purgeStats: boolean = false) =>
  5475. request<void>(`/archives/${id}${purgeStats ? '?purge_stats=true' : ''}`, { method: 'DELETE' }),
  5476. // ========== Archive auto-purge (#1008 follow-up) ==========
  5477. previewArchivePurge: (olderThanDays: number, purgeStats: boolean = false) =>
  5478. request<ArchivePurgePreview>(
  5479. `/archives/purge/preview?older_than_days=${olderThanDays}&purge_stats=${purgeStats}`,
  5480. ),
  5481. // #1390: purgeStats=false (default) soft-deletes each old archive — Quick Stats
  5482. // preserved, files removed from disk, row hidden via deleted_at. true matches
  5483. // the single-archive delete's `?purge_stats=true` semantics (hard-deletes the
  5484. // linked PrintLogEntry rows so the contribution drops from /stats too).
  5485. executeArchivePurge: (olderThanDays: number, purgeStats: boolean = false) =>
  5486. request<{ deleted: number; purge_stats: boolean }>('/archives/purge', {
  5487. method: 'POST',
  5488. body: JSON.stringify({ older_than_days: olderThanDays, purge_stats: purgeStats }),
  5489. }),
  5490. // Archives of one file merge into the oldest (archive redesign P2).
  5491. previewArchiveMerge: () => request<ArchiveMergePreview>('/archives/merge-preview'),
  5492. /** How many duplicate groups there are; cheap, for offering the merge. */
  5493. getArchiveMergeCount: () => request<{ groups: number }>('/archives/merge-count'),
  5494. mergeArchives: (survivorIds: number[]) =>
  5495. request<ArchiveMergeResult>('/archives/merge', {
  5496. method: 'POST',
  5497. body: JSON.stringify({ survivor_ids: survivorIds }),
  5498. }),
  5499. getArchivePurgeSettings: () =>
  5500. request<ArchivePurgeSettings>('/archives/purge/settings'),
  5501. updateArchivePurgeSettings: (body: ArchivePurgeSettings) =>
  5502. request<ArchivePurgeSettings>('/archives/purge/settings', {
  5503. method: 'PUT',
  5504. body: JSON.stringify(body),
  5505. }),
  5506. getArchiveStats: (options?: { dateFrom?: string; dateTo?: string; createdById?: number }) => {
  5507. const params = new URLSearchParams();
  5508. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  5509. if (options?.dateTo) params.set('date_to', options.dateTo);
  5510. addDayZone(params);
  5511. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  5512. const qs = params.toString();
  5513. return request<ArchiveStats>(`/archives/stats${qs ? `?${qs}` : ''}`);
  5514. },
  5515. // Tag management
  5516. getTags: () => request<TagInfo[]>('/archives/tags'),
  5517. renameTag: (oldName: string, newName: string) =>
  5518. request<{ affected: number }>(`/archives/tags/${encodeURIComponent(oldName)}`, {
  5519. method: 'PUT',
  5520. body: JSON.stringify({ new_name: newName }),
  5521. }),
  5522. deleteTag: (name: string) =>
  5523. request<{ affected: number }>(`/archives/tags/${encodeURIComponent(name)}`, {
  5524. method: 'DELETE',
  5525. }),
  5526. recalculateCosts: () =>
  5527. request<{
  5528. message: string;
  5529. updated: number;
  5530. preserved: number;
  5531. usage_repriced: number;
  5532. spoolman_unreachable: number;
  5533. }>('/archives/recalculate-costs', { method: 'POST' }),
  5534. getFailureAnalysis: (options?: { days?: number; dateFrom?: string; dateTo?: string; printerId?: number; projectId?: number; createdById?: number }) => {
  5535. const params = new URLSearchParams();
  5536. if (options?.days) params.set('days', String(options.days));
  5537. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  5538. if (options?.dateTo) params.set('date_to', options.dateTo);
  5539. addDayZone(params);
  5540. if (options?.printerId) params.set('printer_id', String(options.printerId));
  5541. if (options?.projectId) params.set('project_id', String(options.projectId));
  5542. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  5543. const qs = params.toString();
  5544. return request<FailureAnalysis>(`/archives/analysis/failures${qs ? `?${qs}` : ''}`);
  5545. },
  5546. compareArchives: (archiveIds: number[]) =>
  5547. request<ArchiveComparison>(`/archives/compare?archive_ids=${archiveIds.join(',')}`),
  5548. exportArchives: async (options?: {
  5549. format?: 'csv' | 'xlsx';
  5550. fields?: string[];
  5551. printerId?: number;
  5552. projectId?: number;
  5553. status?: string;
  5554. dateFrom?: string;
  5555. dateTo?: string;
  5556. search?: string;
  5557. }): Promise<{ blob: Blob; filename: string }> => {
  5558. const params = new URLSearchParams();
  5559. if (options?.format) params.set('format', options.format);
  5560. if (options?.fields) params.set('fields', options.fields.join(','));
  5561. if (options?.printerId) params.set('printer_id', String(options.printerId));
  5562. if (options?.projectId) params.set('project_id', String(options.projectId));
  5563. if (options?.status) params.set('status', options.status);
  5564. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  5565. if (options?.dateTo) params.set('date_to', options.dateTo);
  5566. addDayZone(params);
  5567. if (options?.search) params.set('search', options.search);
  5568. const headers: Record<string, string> = {};
  5569. if (authToken) {
  5570. headers['Authorization'] = `Bearer ${authToken}`;
  5571. }
  5572. const response = await fetch(`${API_BASE}/archives/export?${params}`, { headers });
  5573. if (!response.ok) {
  5574. const error = await response.json().catch(() => ({}));
  5575. throw new Error(error.detail || `HTTP ${response.status}`);
  5576. }
  5577. const contentDisposition = response.headers.get('Content-Disposition');
  5578. let filename = options?.format === 'xlsx' ? 'archives_export.xlsx' : 'archives_export.csv';
  5579. if (contentDisposition) {
  5580. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  5581. if (match) filename = match[1];
  5582. }
  5583. const blob = await response.blob();
  5584. return { blob, filename };
  5585. },
  5586. exportStats: async (options?: {
  5587. format?: 'csv' | 'xlsx';
  5588. days?: number;
  5589. printerId?: number;
  5590. projectId?: number;
  5591. createdById?: number;
  5592. }): Promise<{ blob: Blob; filename: string }> => {
  5593. const params = new URLSearchParams();
  5594. if (options?.format) params.set('format', options.format);
  5595. if (options?.days) params.set('days', String(options.days));
  5596. if (options?.printerId) params.set('printer_id', String(options.printerId));
  5597. if (options?.projectId) params.set('project_id', String(options.projectId));
  5598. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  5599. const headers: Record<string, string> = {};
  5600. if (authToken) {
  5601. headers['Authorization'] = `Bearer ${authToken}`;
  5602. }
  5603. const response = await fetch(`${API_BASE}/archives/stats/export?${params}`, { headers });
  5604. if (!response.ok) {
  5605. const error = await response.json().catch(() => ({}));
  5606. throw new Error(error.detail || `HTTP ${response.status}`);
  5607. }
  5608. const contentDisposition = response.headers.get('Content-Disposition');
  5609. let filename = options?.format === 'xlsx' ? 'stats_export.xlsx' : 'stats_export.csv';
  5610. if (contentDisposition) {
  5611. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  5612. if (match) filename = match[1];
  5613. }
  5614. const blob = await response.blob();
  5615. return { blob, filename };
  5616. },
  5617. getArchiveThumbnail: (id: number) => withMediaToken(`${API_BASE}/archives/${id}/thumbnail?v=${Date.now()}`),
  5618. getArchivePlateThumbnail: (id: number, plateIndex: number) =>
  5619. withMediaToken(`${API_BASE}/archives/${id}/plate-thumbnail/${plateIndex}`),
  5620. getArchiveDownload: (id: number) => `${API_BASE}/archives/${id}/download`,
  5621. downloadArchive: async (id: number, filename?: string): Promise<void> => {
  5622. const headers: Record<string, string> = {};
  5623. if (authToken) {
  5624. headers['Authorization'] = `Bearer ${authToken}`;
  5625. }
  5626. const response = await fetch(`${API_BASE}/archives/${id}/download`, { headers });
  5627. if (!response.ok) {
  5628. const error = await response.json().catch(() => ({}));
  5629. throw new Error(error.detail || `HTTP ${response.status}`);
  5630. }
  5631. const disposition = response.headers.get('Content-Disposition');
  5632. const downloadFilename = parseContentDispositionFilename(disposition) || filename || `archive_${id}.3mf`;
  5633. const blob = await response.blob();
  5634. const url = window.URL.createObjectURL(blob);
  5635. const a = document.createElement('a');
  5636. a.href = url;
  5637. a.download = downloadFilename;
  5638. document.body.appendChild(a);
  5639. a.click();
  5640. document.body.removeChild(a);
  5641. window.URL.revokeObjectURL(url);
  5642. },
  5643. getArchiveGcode: (id: number) => `${API_BASE}/archives/${id}/gcode`,
  5644. getArchiveTimelapse: (id: number) => withMediaToken(`${API_BASE}/archives/${id}/timelapse?v=${Date.now()}`),
  5645. getArchiveRunTimelapse: (id: number, runId: number) =>
  5646. withMediaToken(`${API_BASE}/archives/${id}/runs/${runId}/timelapse?v=${Date.now()}`),
  5647. downloadArchiveTimelapse: async (id: number, filename: string): Promise<void> => {
  5648. const prepared = await request<{ token: string; filename: string }>(
  5649. `/archives/${id}/media-download-token`,
  5650. { method: 'POST' },
  5651. );
  5652. const link = document.createElement('a');
  5653. link.href = `${API_BASE}/archives/${id}/media/dl/${encodeURIComponent(prepared.token)}/${encodeURIComponent(filename)}`;
  5654. link.download = filename;
  5655. document.body.appendChild(link);
  5656. link.click();
  5657. link.remove();
  5658. },
  5659. getArchivePrinterMedia: (id: number) =>
  5660. request<ArchivePrinterMedia>(`/archives/${id}/printer-media`),
  5661. scanArchiveTimelapse: (id: number) =>
  5662. request<{
  5663. status: string;
  5664. message: string;
  5665. filename?: string;
  5666. available_files?: Array<{ name: string; path: string; size: number; mtime: string | null }>;
  5667. }>(`/archives/${id}/timelapse/scan`, {
  5668. method: 'POST',
  5669. }),
  5670. selectArchiveTimelapse: (id: number, filename: string) =>
  5671. request<{ status: string; message: string; filename: string }>(
  5672. `/archives/${id}/timelapse/select?filename=${encodeURIComponent(filename)}`,
  5673. { method: 'POST' }
  5674. ),
  5675. deleteArchiveTimelapse: (id: number) =>
  5676. request<{ status: string }>(`/archives/${id}/timelapse`, {
  5677. method: 'DELETE',
  5678. }),
  5679. uploadArchiveTimelapse: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  5680. const formData = new FormData();
  5681. formData.append('file', file);
  5682. const headers: Record<string, string> = {};
  5683. if (authToken) {
  5684. headers['Authorization'] = `Bearer ${authToken}`;
  5685. }
  5686. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/upload`, {
  5687. method: 'POST',
  5688. headers,
  5689. body: formData,
  5690. });
  5691. if (!response.ok) {
  5692. const error = await response.json().catch(() => ({}));
  5693. throw new Error(error.detail || `HTTP ${response.status}`);
  5694. }
  5695. return response.json();
  5696. },
  5697. // Timelapse Editor
  5698. getTimelapseInfo: (archiveId: number) =>
  5699. request<{
  5700. duration: number;
  5701. width: number;
  5702. height: number;
  5703. fps: number;
  5704. codec: string;
  5705. file_size: number;
  5706. has_audio: boolean;
  5707. }>(`/archives/${archiveId}/timelapse/info`),
  5708. getTimelapseThumbnails: (archiveId: number, count: number = 10) =>
  5709. request<{
  5710. thumbnails: string[];
  5711. timestamps: number[];
  5712. }>(`/archives/${archiveId}/timelapse/thumbnails?count=${count}`),
  5713. processTimelapse: async (
  5714. archiveId: number,
  5715. params: {
  5716. trimStart?: number;
  5717. trimEnd?: number;
  5718. speed?: number;
  5719. /** Music volume, 0 to 1. */
  5720. audioVolume?: number;
  5721. saveMode: 'replace' | 'new';
  5722. outputFilename?: string;
  5723. },
  5724. audioFile?: File
  5725. ): Promise<TimelapseJob> => {
  5726. const formData = new FormData();
  5727. formData.append('trim_start', String(params.trimStart ?? 0));
  5728. if (params.trimEnd !== undefined) {
  5729. formData.append('trim_end', String(params.trimEnd));
  5730. }
  5731. formData.append('speed', String(params.speed ?? 1));
  5732. if (params.audioVolume !== undefined) {
  5733. formData.append('audio_volume', String(params.audioVolume));
  5734. }
  5735. formData.append('save_mode', params.saveMode);
  5736. if (params.outputFilename) {
  5737. formData.append('output_filename', params.outputFilename);
  5738. }
  5739. if (audioFile) {
  5740. formData.append('audio', audioFile);
  5741. }
  5742. const headers: Record<string, string> = {};
  5743. if (authToken) {
  5744. headers['Authorization'] = `Bearer ${authToken}`;
  5745. }
  5746. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/process`, {
  5747. method: 'POST',
  5748. headers,
  5749. body: formData,
  5750. });
  5751. if (!response.ok) {
  5752. const error = await response.json().catch(() => ({}));
  5753. throw new Error(error.detail || `HTTP ${response.status}`);
  5754. }
  5755. return response.json();
  5756. },
  5757. // The archive's running or last re-encode; null when there has been none.
  5758. getTimelapseJob: async (archiveId: number): Promise<TimelapseJob | null> => {
  5759. try {
  5760. return await request<TimelapseJob>(`/archives/${archiveId}/timelapse/job`);
  5761. } catch (error) {
  5762. if (error instanceof ApiError && error.status === 404) return null;
  5763. throw error;
  5764. }
  5765. },
  5766. cancelTimelapseJob: (archiveId: number) =>
  5767. request<TimelapseJob>(`/archives/${archiveId}/timelapse/job`, { method: 'DELETE' }),
  5768. // Photos
  5769. getArchivePhotoUrl: (archiveId: number, filename: string) =>
  5770. withMediaToken(`${API_BASE}/archives/${archiveId}/photos/${encodeURIComponent(filename)}`),
  5771. uploadArchivePhoto: async (archiveId: number, file: File): Promise<{ status: string; filename: string; photos: string[] }> => {
  5772. const formData = new FormData();
  5773. formData.append('file', file);
  5774. const headers: Record<string, string> = {};
  5775. if (authToken) {
  5776. headers['Authorization'] = `Bearer ${authToken}`;
  5777. }
  5778. const response = await fetch(`${API_BASE}/archives/${archiveId}/photos`, {
  5779. headers,
  5780. method: 'POST',
  5781. body: formData,
  5782. });
  5783. if (!response.ok) {
  5784. const error = await response.json().catch(() => ({}));
  5785. throw new Error(error.detail || `HTTP ${response.status}`);
  5786. }
  5787. return response.json();
  5788. },
  5789. deleteArchivePhoto: (archiveId: number, filename: string) =>
  5790. request<{ status: string; photos: string[] | null }>(`/archives/${archiveId}/photos/${encodeURIComponent(filename)}`, {
  5791. method: 'DELETE',
  5792. }),
  5793. // Source 3MF (original slicer project file)
  5794. getSource3mfDownloadUrl: (archiveId: number) =>
  5795. `${API_BASE}/archives/${archiveId}/source`,
  5796. downloadSource3mf: async (archiveId: number): Promise<void> => {
  5797. const headers: Record<string, string> = {};
  5798. if (authToken) {
  5799. headers['Authorization'] = `Bearer ${authToken}`;
  5800. }
  5801. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, { headers });
  5802. if (!response.ok) {
  5803. const error = await response.json().catch(() => ({}));
  5804. throw new Error(error.detail || `HTTP ${response.status}`);
  5805. }
  5806. const disposition = response.headers.get('Content-Disposition');
  5807. const filename = parseContentDispositionFilename(disposition) || `source_${archiveId}.3mf`;
  5808. const blob = await response.blob();
  5809. const url = window.URL.createObjectURL(blob);
  5810. const a = document.createElement('a');
  5811. a.href = url;
  5812. a.download = filename;
  5813. document.body.appendChild(a);
  5814. a.click();
  5815. document.body.removeChild(a);
  5816. window.URL.revokeObjectURL(url);
  5817. },
  5818. getSource3mfForSlicer: (archiveId: number, filename: string) => {
  5819. // Sanitize: slicers url_decode() the entire URL, so / \ ? # in filenames break path routing
  5820. const safe = filename.replace(/[/\\?#]/g, '_');
  5821. return `${API_BASE}/archives/${archiveId}/source/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  5822. },
  5823. createSourceSlicerToken: (archiveId: number) =>
  5824. request<{ token: string }>(`/archives/${archiveId}/source-slicer-token`, { method: 'POST' }),
  5825. getSourceSlicerDownloadUrl: (archiveId: number, token: string, filename: string) => {
  5826. const safe = filename.replace(/[/\\?#]/g, '_');
  5827. return `${API_BASE}/archives/${archiveId}/source-dl/${token}/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  5828. },
  5829. uploadSource3mf: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  5830. const formData = new FormData();
  5831. formData.append('file', file);
  5832. const headers: Record<string, string> = {};
  5833. if (authToken) {
  5834. headers['Authorization'] = `Bearer ${authToken}`;
  5835. }
  5836. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, {
  5837. method: 'POST',
  5838. headers,
  5839. body: formData,
  5840. });
  5841. if (!response.ok) {
  5842. const error = await response.json().catch(() => ({}));
  5843. throw new Error(error.detail || `HTTP ${response.status}`);
  5844. }
  5845. return response.json();
  5846. },
  5847. deleteSource3mf: (archiveId: number) =>
  5848. request<{ status: string }>(`/archives/${archiveId}/source`, {
  5849. method: 'DELETE',
  5850. }),
  5851. // F3D (Fusion 360 design file)
  5852. downloadF3d: async (archiveId: number): Promise<void> => {
  5853. const headers: Record<string, string> = {};
  5854. if (authToken) {
  5855. headers['Authorization'] = `Bearer ${authToken}`;
  5856. }
  5857. const response = await fetch(`${API_BASE}/archives/${archiveId}/f3d`, { headers });
  5858. if (!response.ok) {
  5859. const error = await response.json().catch(() => ({}));
  5860. throw new Error(error.detail || `HTTP ${response.status}`);
  5861. }
  5862. const disposition = response.headers.get('Content-Disposition');
  5863. const filename = parseContentDispositionFilename(disposition) || `archive_${archiveId}.f3d`;
  5864. const blob = await response.blob();
  5865. const url = window.URL.createObjectURL(blob);
  5866. const a = document.createElement('a');
  5867. a.href = url;
  5868. a.download = filename;
  5869. document.body.appendChild(a);
  5870. a.click();
  5871. document.body.removeChild(a);
  5872. window.URL.revokeObjectURL(url);
  5873. },
  5874. uploadF3d: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  5875. const formData = new FormData();
  5876. formData.append('file', file);
  5877. const headers: Record<string, string> = {};
  5878. if (authToken) {
  5879. headers['Authorization'] = `Bearer ${authToken}`;
  5880. }
  5881. const response = await fetch(`${API_BASE}/archives/${archiveId}/f3d`, {
  5882. method: 'POST',
  5883. headers,
  5884. body: formData,
  5885. });
  5886. if (!response.ok) {
  5887. const error = await response.json().catch(() => ({}));
  5888. throw new Error(error.detail || `HTTP ${response.status}`);
  5889. }
  5890. return response.json();
  5891. },
  5892. deleteF3d: (archiveId: number) =>
  5893. request<{ status: string }>(`/archives/${archiveId}/f3d`, {
  5894. method: 'DELETE',
  5895. }),
  5896. // QR Code
  5897. getArchiveQRCodeUrl: (archiveId: number, size = 200) =>
  5898. withMediaToken(`${API_BASE}/archives/${archiveId}/qrcode?size=${size}`),
  5899. getArchiveCapabilities: (id: number) =>
  5900. request<{
  5901. has_model: boolean;
  5902. has_gcode: boolean;
  5903. has_source: boolean;
  5904. build_volume: { x: number; y: number; z: number };
  5905. filament_colors: string[];
  5906. }>(`/archives/${id}/capabilities`),
  5907. // Project Page
  5908. getArchiveProjectPage: (id: number) =>
  5909. request<{
  5910. title: string | null;
  5911. description: string | null;
  5912. designer: string | null;
  5913. designer_user_id: string | null;
  5914. license: string | null;
  5915. copyright: string | null;
  5916. creation_date: string | null;
  5917. modification_date: string | null;
  5918. origin: string | null;
  5919. profile_title: string | null;
  5920. profile_description: string | null;
  5921. profile_cover: string | null;
  5922. profile_user_id: string | null;
  5923. profile_user_name: string | null;
  5924. design_model_id: string | null;
  5925. design_profile_id: string | null;
  5926. design_region: string | null;
  5927. model_pictures: Array<{ name: string; path: string; url: string }>;
  5928. profile_pictures: Array<{ name: string; path: string; url: string }>;
  5929. thumbnails: Array<{ name: string; path: string; url: string }>;
  5930. }>(`/archives/${id}/project-page`),
  5931. updateArchiveProjectPage: (id: number, data: {
  5932. title?: string;
  5933. description?: string;
  5934. designer?: string;
  5935. license?: string;
  5936. copyright?: string;
  5937. profile_title?: string;
  5938. profile_description?: string;
  5939. }) =>
  5940. request(`/archives/${id}/project-page`, {
  5941. method: 'PATCH',
  5942. body: JSON.stringify(data),
  5943. }),
  5944. getArchiveForSlicer: (id: number, filename: string) => {
  5945. const safe = filename.replace(/[/\\?#]/g, '_');
  5946. return `${API_BASE}/archives/${id}/file/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  5947. },
  5948. createArchiveSlicerToken: (archiveId: number) =>
  5949. request<{ token: string }>(`/archives/${archiveId}/slicer-token`, { method: 'POST' }),
  5950. getArchiveSlicerDownloadUrl: (archiveId: number, token: string, filename: string) => {
  5951. const safe = filename.replace(/[/\\?#]/g, '_');
  5952. return `${API_BASE}/archives/${archiveId}/dl/${token}/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  5953. },
  5954. getArchivePlates: (archiveId: number) =>
  5955. request<ArchivePlatesResponse>(`/archives/${archiveId}/plates`),
  5956. getArchiveFilamentRequirements: (
  5957. archiveId: number,
  5958. plateId?: number,
  5959. requestId?: string,
  5960. /** Ask for one entry per project slot instead of only the slots this
  5961. * plate consumes. The slice modal needs it: its filament list is
  5962. * positional, so a source whose only used slot is 4 must still present
  5963. * four rows or the user's pick is bound to slot 1 (#2712). Print-time
  5964. * AMS matching must NOT set this — it wants the used-only list. */
  5965. fullSlots?: boolean,
  5966. ) => {
  5967. const qs = new URLSearchParams();
  5968. if (plateId !== undefined) qs.set('plate_id', String(plateId));
  5969. if (requestId) qs.set('request_id', requestId);
  5970. if (fullSlots) qs.set('full_slots', 'true');
  5971. return request<{
  5972. archive_id: number;
  5973. filename: string;
  5974. plate_id: number | null;
  5975. filaments: Array<{
  5976. slot_id: number;
  5977. type: string;
  5978. color: string;
  5979. used_grams: number;
  5980. used_meters: number;
  5981. used_in_plate?: boolean;
  5982. }>;
  5983. }>(`/archives/${archiveId}/filament-requirements${qs.toString() ? `?${qs}` : ''}`);
  5984. },
  5985. uploadArchivesBulk: async (files: File[], printerId?: number): Promise<BulkUploadResult> => {
  5986. const formData = new FormData();
  5987. files.forEach((file) => formData.append('files', file));
  5988. const url = printerId
  5989. ? `${API_BASE}/archives/upload-bulk?printer_id=${printerId}`
  5990. : `${API_BASE}/archives/upload-bulk`;
  5991. const headers: Record<string, string> = {};
  5992. if (authToken) {
  5993. headers['Authorization'] = `Bearer ${authToken}`;
  5994. }
  5995. const response = await fetch(url, {
  5996. method: 'POST',
  5997. headers,
  5998. body: formData,
  5999. });
  6000. if (!response.ok) {
  6001. const error = await response.json().catch(() => ({}));
  6002. throw new Error(error.detail || `HTTP ${response.status}`);
  6003. }
  6004. return response.json();
  6005. },
  6006. // Print Log
  6007. getPrintLog: (params?: {
  6008. search?: string;
  6009. printerId?: number;
  6010. username?: string;
  6011. status?: string;
  6012. dateFrom?: string;
  6013. dateTo?: string;
  6014. limit?: number;
  6015. offset?: number;
  6016. // Sorting is server-side because paging is: ordering only the rows the
  6017. // client holds would sort one page, not the log (#2636).
  6018. sortBy?: string;
  6019. sortDir?: 'asc' | 'desc';
  6020. }) => {
  6021. const searchParams = new URLSearchParams();
  6022. if (params?.search) searchParams.set('search', params.search);
  6023. if (params?.printerId) searchParams.set('printer_id', String(params.printerId));
  6024. if (params?.username) searchParams.set('created_by_username', params.username);
  6025. if (params?.status) searchParams.set('status', params.status);
  6026. if (params?.dateFrom) searchParams.set('date_from', params.dateFrom);
  6027. if (params?.dateTo) searchParams.set('date_to', params.dateTo);
  6028. if (params?.limit) searchParams.set('limit', String(params.limit));
  6029. if (params?.offset !== undefined) searchParams.set('offset', String(params.offset));
  6030. if (params?.sortBy) searchParams.set('sort_by', params.sortBy);
  6031. if (params?.sortDir) searchParams.set('sort_dir', params.sortDir);
  6032. return request<PrintLogResponse>(`/print-log/?${searchParams}`);
  6033. },
  6034. getPrintLogThumbnail: (id: number) => withMediaToken(`${API_BASE}/print-log/${id}/thumbnail`),
  6035. clearPrintLog: () =>
  6036. request<{ deleted: number }>('/print-log/', { method: 'DELETE' }),
  6037. deletePrintLogEntry: (id: number) =>
  6038. request<{ status: string; id: number }>(`/print-log/${id}`, { method: 'DELETE' }),
  6039. // Edit failure_reason / status on a single Print Log row (#1687 part 4).
  6040. // Distinct from updateArchive: archives describe the model, log entries
  6041. // describe a single print event. Orphan entries (no archive_id) have no
  6042. // archive to reach through and this is the only path to classify them.
  6043. updatePrintLogEntry: (
  6044. id: number,
  6045. body: { failure_reason?: string | null; status?: string; notes?: string | null },
  6046. ) =>
  6047. request<PrintLogEntry>(`/print-log/${id}`, {
  6048. method: 'PATCH',
  6049. body: JSON.stringify(body),
  6050. }),
  6051. // Settings
  6052. getSettings: () => request<AppSettings>('/settings/'),
  6053. getDefaultSidebarOrder: () => request<{ default_sidebar_order: string }>('/settings/default-sidebar-order'),
  6054. // Public subset of settings for UI rendering — no settings:read required.
  6055. // Used by pages whose users may not have SETTINGS_READ (e.g. operators with
  6056. // only printers:clear_plate). Keep in sync with _UI_PREFERENCE_FIELDS in
  6057. // backend/app/api/routes/settings.py.
  6058. getUiPreferences: () =>
  6059. request<{
  6060. require_plate_clear?: boolean;
  6061. check_printer_firmware?: boolean;
  6062. camera_view_mode?: 'window' | 'embedded';
  6063. time_format?: 'system' | '12h' | '24h';
  6064. date_format?: string;
  6065. drying_presets?: string;
  6066. ams_humidity_thresholds?: string;
  6067. ams_humidity_good?: number;
  6068. ams_humidity_fair?: number;
  6069. ams_temp_good?: number;
  6070. ams_temp_fair?: number;
  6071. bed_cooled_threshold?: number;
  6072. nozzle_temp_presets?: string;
  6073. bed_temp_presets?: string;
  6074. chamber_temp_presets?: string;
  6075. fan_speed_presets?: string;
  6076. }>('/settings/ui-preferences'),
  6077. // Install configuration the app shell needs, for any signed-in user. Separate
  6078. // from getUiPreferences: that endpoint is public because its fields are
  6079. // defaults shipped with the app, while these describe how this deployment is
  6080. // configured. Neither requires settings:read -- which is the point, since a
  6081. // non-admin reading GET /settings gets a 403 and every gate that consults it
  6082. // silently takes its fallback (#3023). Keep in sync with _UI_FLAG_FIELDS in
  6083. // backend/app/api/routes/settings.py.
  6084. getUiFlags: () => request<UiSettings>('/settings/ui-flags'),
  6085. // The two above together: what a page needs from the settings when its user
  6086. // may not read GET /settings. See useUiSettings.
  6087. getUiSettings: async (): Promise<UiSettings> => {
  6088. const [preferences, flags] = await Promise.all([api.getUiPreferences(), api.getUiFlags()]);
  6089. return { ...(preferences as UiSettings), ...flags };
  6090. },
  6091. updateSettings: (data: AppSettingsUpdate) =>
  6092. request<AppSettings>('/settings/', {
  6093. method: 'PUT',
  6094. body: JSON.stringify(data),
  6095. }),
  6096. getMQTTStatus: () => request<MQTTStatus>('/settings/mqtt/status'),
  6097. exportBackup: async (): Promise<{ blob: Blob; filename: string }> => {
  6098. // New simplified backup - complete database + all files
  6099. const url = `${API_BASE}/settings/backup`;
  6100. const headers: Record<string, string> = {};
  6101. if (authToken) {
  6102. headers['Authorization'] = `Bearer ${authToken}`;
  6103. }
  6104. const response = await fetch(url, { headers });
  6105. // Check for errors
  6106. if (!response.ok) {
  6107. const errorText = await response.text();
  6108. throw new Error(errorText || `Backup failed with status ${response.status}`);
  6109. }
  6110. // Get filename from Content-Disposition header
  6111. const contentDisposition = response.headers.get('Content-Disposition');
  6112. let filename = 'bambuddy-backup.zip';
  6113. if (contentDisposition) {
  6114. const match = contentDisposition.match(/filename=([^;]+)/);
  6115. if (match) filename = match[1].trim().replace(/^"(.*)"$/, '$1');
  6116. }
  6117. const blob = await response.blob();
  6118. return { blob, filename };
  6119. },
  6120. importBackup: async (file: File) => {
  6121. // New simplified restore - replaces database + all directories
  6122. const formData = new FormData();
  6123. formData.append('file', file);
  6124. const url = `${API_BASE}/settings/restore`;
  6125. const headers: Record<string, string> = {};
  6126. if (authToken) {
  6127. headers['Authorization'] = `Bearer ${authToken}`;
  6128. }
  6129. const response = await fetch(url, {
  6130. method: 'POST',
  6131. headers,
  6132. body: formData,
  6133. });
  6134. const data = (await response.json().catch(() => null)) as {
  6135. success?: boolean;
  6136. message?: string;
  6137. detail?: string;
  6138. } | null;
  6139. // A refused restore is an HTTPException, so the body is {detail}, not
  6140. // {success, message}. Returning it unmapped made `success` undefined and
  6141. // `message` undefined too — the modal then raised an empty error toast,
  6142. // which is the one case where the reason matters most (e.g. a backup this
  6143. // version cannot import names the columns and both versions).
  6144. if (!response.ok) {
  6145. return { success: false, message: data?.detail ?? data?.message ?? '' };
  6146. }
  6147. return (data ?? { success: false, message: '' }) as {
  6148. success: boolean;
  6149. message: string;
  6150. };
  6151. },
  6152. checkFfmpeg: () =>
  6153. request<{ installed: boolean; path: string | null }>('/settings/check-ffmpeg'),
  6154. getNetworkInterfaces: () =>
  6155. request<{ interfaces: NetworkInterface[] }>('/settings/network-interfaces'),
  6156. // Cloud
  6157. getCloudStatus: () => request<CloudAuthStatus>('/cloud/status'),
  6158. cloudLogin: (email: string, password: string, region = 'global') =>
  6159. request<CloudLoginResponse>('/cloud/login', {
  6160. method: 'POST',
  6161. body: JSON.stringify({ email, password, region }),
  6162. }),
  6163. cloudVerify: (email: string, code: string, tfaKey?: string, region: string = 'global') =>
  6164. request<CloudLoginResponse>('/cloud/verify', {
  6165. method: 'POST',
  6166. body: JSON.stringify({ email, code, tfa_key: tfaKey, region }),
  6167. }),
  6168. cloudSetToken: (access_token: string, region: string = 'global') =>
  6169. request<CloudAuthStatus>('/cloud/token', {
  6170. method: 'POST',
  6171. body: JSON.stringify({ access_token, region }),
  6172. }),
  6173. cloudLogout: () =>
  6174. request<{ success: boolean }>('/cloud/logout', { method: 'POST' }),
  6175. // Orca Cloud — RFC 8628 device pairing. deviceStart() returns a short
  6176. // user_code + verification link; the user approves it in their Orca Cloud
  6177. // settings while the frontend polls devicePoll() every `interval` seconds
  6178. // until the status flips to 'complete' (or a terminal deny/expire).
  6179. orcaCloudDeviceStart: () =>
  6180. request<OrcaDeviceStartResponse>('/orca-cloud/device/start', {
  6181. method: 'POST',
  6182. }),
  6183. orcaCloudDevicePoll: () =>
  6184. request<OrcaDevicePollResponse>('/orca-cloud/device/poll', {
  6185. method: 'POST',
  6186. }),
  6187. orcaCloudStatus: () =>
  6188. request<OrcaAuthStatusResponse>('/orca-cloud/status'),
  6189. orcaCloudLogout: () =>
  6190. request<{ success: boolean }>('/orca-cloud/logout', { method: 'POST' }),
  6191. orcaCloudListProfiles: () =>
  6192. request<OrcaProfileListResponse>('/orca-cloud/profiles'),
  6193. orcaCloudGetProfile: (id: string) =>
  6194. request<OrcaProfileDetail>(`/orca-cloud/profiles/${id}`),
  6195. getCloudSettings: (version = '02.04.00.70') =>
  6196. request<SlicerSettingsResponse>(`/cloud/settings?version=${version}`),
  6197. getBuiltinFilaments: () =>
  6198. request<BuiltinFilament[]>('/cloud/builtin-filaments'),
  6199. getFilamentIdMap: () =>
  6200. request<Record<string, string>>('/cloud/filament-id-map'),
  6201. /** Material-disambiguated hex→name lookup. Same hex can map to different
  6202. * catalog names depending on material (e.g. #000000 is "Charcoal" in PLA
  6203. * Matte but "Black" in PLA Basic). The flat ``/inventory/colors/map``
  6204. * collapses these to the first hit; this endpoint preserves the material
  6205. * context. Returns ``{color_name: null}`` when the hex isn't in the
  6206. * catalog at all. #1718. */
  6207. getColorByMaterial: (hex: string, material?: string) => {
  6208. const params = new URLSearchParams({ hex });
  6209. if (material) params.set('material', material);
  6210. return request<{ color_name: string | null }>(
  6211. `/inventory/colors/by-material?${params.toString()}`,
  6212. );
  6213. },
  6214. // MakerWorld URL-paste import flow.
  6215. getMakerworldStatus: () =>
  6216. request<MakerworldStatus>('/makerworld/status'),
  6217. resolveMakerworldUrl: (url: string) =>
  6218. request<MakerworldResolvedModel>('/makerworld/resolve', {
  6219. method: 'POST',
  6220. body: JSON.stringify({ url }),
  6221. }),
  6222. getMakerworldRecentImports: (limit = 10) =>
  6223. request<MakerworldRecentImport[]>(`/makerworld/recent-imports?limit=${limit}`),
  6224. importMakerworldInstance: (
  6225. model_id: number,
  6226. instance_id: number | null,
  6227. profile_id?: number | null,
  6228. folder_id?: number | null,
  6229. ) =>
  6230. request<MakerworldImportResponse>('/makerworld/import', {
  6231. method: 'POST',
  6232. body: JSON.stringify({
  6233. model_id,
  6234. instance_id: instance_id ?? null,
  6235. profile_id: profile_id ?? null,
  6236. folder_id: folder_id ?? null,
  6237. }),
  6238. }),
  6239. // Manyfold (#1471).
  6240. getManyfoldConfig: () => request<ManyfoldConfig>('/manyfold/config'),
  6241. updateManyfoldConfig: (data: ManyfoldConfigInput) =>
  6242. request<ManyfoldConfig>('/manyfold/config', { method: 'PUT', body: JSON.stringify(data) }),
  6243. deleteManyfoldConfig: () => request<void>('/manyfold/config', { method: 'DELETE' }),
  6244. testManyfoldConfig: (data: ManyfoldConfigInput) =>
  6245. request<{ model_count: number }>('/manyfold/config/test', { method: 'POST', body: JSON.stringify(data) }),
  6246. getManyfoldStatus: () => request<ManyfoldStatus>('/manyfold/status'),
  6247. listManyfoldModels: (query: string, page: number) => {
  6248. const params = new URLSearchParams({ page: String(page) });
  6249. if (query) params.set('q', query);
  6250. return request<ManyfoldModelList>(`/manyfold/models?${params.toString()}`);
  6251. },
  6252. getManyfoldModel: (modelId: string) =>
  6253. request<ManyfoldModel>(`/manyfold/models/${encodeURIComponent(modelId)}`),
  6254. /** The model's preview, or null when it has none. Fetched rather than used
  6255. * as an <img src>: a failing protected <img> makes the app renew its media
  6256. * token, and models without a preview answer 404. */
  6257. getManyfoldPreview: async (modelId: string): Promise<Blob | null> => {
  6258. const headers: Record<string, string> = {};
  6259. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  6260. const response = await fetch(`${API_BASE}/manyfold/models/${encodeURIComponent(modelId)}/preview`, { headers });
  6261. if (!response.ok) return null;
  6262. return response.blob();
  6263. },
  6264. importManyfoldFile: (modelId: string, fileId: string, folderId: number | null) =>
  6265. request<ManyfoldImportResponse>('/manyfold/import', {
  6266. method: 'POST',
  6267. body: JSON.stringify({ model_id: modelId, file_id: fileId, folder_id: folderId }),
  6268. }),
  6269. getCloudSettingDetail: (settingId: string) =>
  6270. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`),
  6271. createCloudSetting: (data: SlicerSettingCreate) =>
  6272. request<SlicerSettingDetail>('/cloud/settings', {
  6273. method: 'POST',
  6274. body: JSON.stringify(data),
  6275. }),
  6276. updateCloudSetting: (settingId: string, data: SlicerSettingUpdate) =>
  6277. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`, {
  6278. method: 'PUT',
  6279. body: JSON.stringify(data),
  6280. }),
  6281. deleteCloudSetting: (settingId: string) =>
  6282. request<SlicerSettingDeleteResponse>(`/cloud/settings/${settingId}`, {
  6283. method: 'DELETE',
  6284. }),
  6285. getCloudFields: (presetType: 'filament' | 'print' | 'process' | 'printer') =>
  6286. request<FieldDefinitionsResponse>(`/cloud/fields/${presetType}`),
  6287. getFilamentInfo: (settingIds: string[]) =>
  6288. request<Record<string, { name: string; k: number | null }>>('/cloud/filament-info', {
  6289. method: 'POST',
  6290. body: JSON.stringify(settingIds),
  6291. }),
  6292. // Smart Plugs
  6293. getSmartPlugs: () => request<SmartPlug[]>('/smart-plugs/'),
  6294. getSmartPlugByPrinter: (printerId: number) => smartPlugBatch(printerId),
  6295. getScriptPlugsByPrinter: (printerId: number) => scriptPlugsBatch(printerId),
  6296. createSmartPlug: (data: SmartPlugCreate) =>
  6297. request<SmartPlug>('/smart-plugs/', {
  6298. method: 'POST',
  6299. body: JSON.stringify(data),
  6300. }),
  6301. updateSmartPlug: (id: number, data: SmartPlugUpdate) =>
  6302. request<SmartPlug>(`/smart-plugs/${id}`, {
  6303. method: 'PATCH',
  6304. body: JSON.stringify(data),
  6305. }),
  6306. deleteSmartPlug: (id: number) =>
  6307. request<void>(`/smart-plugs/${id}`, { method: 'DELETE' }),
  6308. controlSmartPlug: (id: number, action: 'on' | 'off' | 'toggle') =>
  6309. request<{ success: boolean; action: string }>(`/smart-plugs/${id}/control`, {
  6310. method: 'POST',
  6311. body: JSON.stringify({ action }),
  6312. }),
  6313. getSmartPlugStatus: (id: number) =>
  6314. request<SmartPlugStatus>(`/smart-plugs/${id}/status`),
  6315. // plug_id: the saved plug being edited, whose stored password fills in the placeholder.
  6316. testSmartPlugConnection: (ip_address: string, username?: string | null, password?: string | null, plug_id?: number) =>
  6317. request<SmartPlugTestResult>('/smart-plugs/test-connection', {
  6318. method: 'POST',
  6319. body: JSON.stringify({ ip_address, username, password, plug_id }),
  6320. }),
  6321. // Tasmota Discovery (auto-detects network)
  6322. startTasmotaScan: () =>
  6323. request<TasmotaScanStatus>('/smart-plugs/discover/scan', { method: 'POST' }),
  6324. getTasmotaScanStatus: () =>
  6325. request<TasmotaScanStatus>('/smart-plugs/discover/status'),
  6326. stopTasmotaScan: () =>
  6327. request<TasmotaScanStatus>('/smart-plugs/discover/stop', { method: 'POST' }),
  6328. getDiscoveredTasmotaDevices: () =>
  6329. request<DiscoveredTasmotaDevice[]>('/smart-plugs/discover/devices'),
  6330. // Home Assistant Integration
  6331. testHAConnection: (url: string, token: string) =>
  6332. request<HATestConnectionResult>('/smart-plugs/ha/test-connection', {
  6333. method: 'POST',
  6334. body: JSON.stringify({ url, token }),
  6335. }),
  6336. getHAEntities: (search?: string) => {
  6337. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  6338. return request<HAEntity[]>(`/smart-plugs/ha/entities${params}`);
  6339. },
  6340. getHASensorEntities: () =>
  6341. request<HASensorEntity[]>('/smart-plugs/ha/sensors'),
  6342. // Home Assistant sensors bound to a printer (#1148, #448)
  6343. getHASensors: (printerId?: number) =>
  6344. request<PrinterHASensor[]>(`/ha-sensors/${printerId ? `?printer_id=${printerId}` : ''}`),
  6345. getHASensorReadings: (printerId: number) => haSensorReadingsBatch(printerId),
  6346. getBindableHAEntities: (search?: string) => {
  6347. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  6348. return request<HADisplayEntity[]>(`/ha-sensors/entities${params}`);
  6349. },
  6350. createHASensor: (data: PrinterHASensorCreate) =>
  6351. request<PrinterHASensor>('/ha-sensors/', { method: 'POST', body: JSON.stringify(data) }),
  6352. updateHASensor: (id: number, data: PrinterHASensorUpdate) =>
  6353. request<PrinterHASensor>(`/ha-sensors/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  6354. deleteHASensor: (id: number) =>
  6355. request<{ message: string }>(`/ha-sensors/${id}`, { method: 'DELETE' }),
  6356. getLocationHASensors: (locationId?: number) =>
  6357. request<LocationHASensor[]>(`/location-ha-sensors/${locationId ? `?location_id=${locationId}` : ''}`),
  6358. getLocationHASensorReadings: (locationId: number, showOnCard = true) =>
  6359. request<LocationHASensorReading[]>(
  6360. `/location-ha-sensors/by-location/${locationId}/readings?show_on_card=${showOnCard}`
  6361. ),
  6362. getBindableLocationHAEntities: (search?: string) => {
  6363. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  6364. return request<HADisplayEntity[]>(`/location-ha-sensors/entities${params}`);
  6365. },
  6366. createLocationHASensor: (data: LocationHASensorCreate) =>
  6367. request<LocationHASensor>('/location-ha-sensors/', { method: 'POST', body: JSON.stringify(data) }),
  6368. updateLocationHASensor: (id: number, data: LocationHASensorUpdate) =>
  6369. request<LocationHASensor>(`/location-ha-sensors/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  6370. deleteLocationHASensor: (id: number) =>
  6371. request<{ message: string }>(`/location-ha-sensors/${id}`, { method: 'DELETE' }),
  6372. // REST smart plug
  6373. // plug_id: the saved plug being edited, whose stored headers fill in the placeholder.
  6374. testRESTConnection: (url: string, method: string = 'GET', headers?: string | null, plug_id?: number) =>
  6375. request<{ success: boolean; error: string | null }>('/smart-plugs/rest/test-connection', {
  6376. method: 'POST',
  6377. body: JSON.stringify({ url, method, headers, plug_id }),
  6378. }),
  6379. // Print Queue
  6380. getQueue: (printerId?: number, status?: string, targetModel?: string) => {
  6381. const params = new URLSearchParams();
  6382. if (printerId) params.set('printer_id', String(printerId));
  6383. if (status) params.set('status', status);
  6384. if (targetModel) params.set('target_model', targetModel);
  6385. return request<PrintQueueItem[]>(`/queue/?${params}`);
  6386. },
  6387. // History (completed / failed / skipped / cancelled), one page at a time.
  6388. getQueueHistory: (params: QueueHistoryParams) =>
  6389. request<QueueHistoryPage>(`/queue/history?${queueHistorySearch(params)}`),
  6390. // Removes the history matching the same filters, server-side.
  6391. clearQueueHistory: (params: QueueHistoryFilters) =>
  6392. request<{ cleared: number; kept: number }>(`/queue/history/clear?${queueHistorySearch(params)}`, {
  6393. method: 'POST',
  6394. }),
  6395. // One printer's queue as GET /queue/?printer_id= returns it: its own jobs
  6396. // plus the "Any <model>" jobs for its model. Batched across printer cards.
  6397. getPrinterQueue: (printerId: number, status: string) => printerQueueBatch(status)(printerId),
  6398. addToQueue: (data: PrintQueueItemCreate) =>
  6399. request<PrintQueueItem>('/queue/', {
  6400. method: 'POST',
  6401. body: JSON.stringify(data),
  6402. }),
  6403. updateQueueItem: (id: number, data: PrintQueueItemUpdate) =>
  6404. request<PrintQueueItem>(`/queue/${id}`, {
  6405. method: 'PATCH',
  6406. body: JSON.stringify(data),
  6407. }),
  6408. /** `deleted` is false when the item was kept as cancelled instead: it is the
  6409. * last run a batch order could re-queue its plate from (#2960). */
  6410. removeFromQueue: (id: number) =>
  6411. request<{ message: string; deleted: boolean }>(`/queue/${id}`, { method: 'DELETE' }),
  6412. reorderQueue: (items: { id: number; position: number }[]) =>
  6413. request<{ message: string }>('/queue/reorder', {
  6414. method: 'POST',
  6415. body: JSON.stringify({ items }),
  6416. }),
  6417. cancelQueueItem: (id: number) =>
  6418. request<{ message: string }>(`/queue/${id}/cancel`, { method: 'POST' }),
  6419. stopQueueItem: (id: number) =>
  6420. request<{ message: string }>(`/queue/${id}/stop`, { method: 'POST' }),
  6421. /**
  6422. * Start a staged queue item. The backend re-checks live filament deficit
  6423. * for the assigned spool and, when short, returns 409 with a structured
  6424. * payload so the caller can confirm and retry. Pass `skipFilamentCheck`
  6425. * after the user confirms "Print Anyway" (#1496).
  6426. */
  6427. startQueueItem: (id: number, opts?: { skipFilamentCheck?: boolean }) => {
  6428. const qs = opts?.skipFilamentCheck ? '?skip_filament_check=true' : '';
  6429. return request<PrintQueueItem>(`/queue/${id}/start${qs}`, { method: 'POST' });
  6430. },
  6431. /**
  6432. * Clear the `require_previous_success` gate for a printer after the user
  6433. * resolves the failure. Acknowledges any failed/aborted predecessors and
  6434. * restores skipped items whose error_message matches the gate string
  6435. * back to pending. Returns counts so the UI can render a precise toast.
  6436. */
  6437. // A job for any printer of a model waits when the last print failed on every
  6438. // free one; this clears the gate on the model's printers.
  6439. resumeModelQueueAfterFailure: (model: string) =>
  6440. request<{ acknowledged: number; printers: number }>(
  6441. `/queue/model/${encodeURIComponent(model)}/resume`,
  6442. { method: 'POST' },
  6443. ),
  6444. resumeQueueAfterFailure: (printerId: number) =>
  6445. request<{ acknowledged: number; restored: number }>(
  6446. `/queue/printer/${printerId}/resume`,
  6447. { method: 'POST' },
  6448. ),
  6449. bulkUpdateQueue: (data: PrintQueueBulkUpdate) =>
  6450. request<PrintQueueBulkUpdateResponse>('/queue/bulk', {
  6451. method: 'PATCH',
  6452. body: JSON.stringify(data),
  6453. }),
  6454. // Batches
  6455. getBatches: (status?: string) => {
  6456. const params = status ? `?status=${status}` : '';
  6457. return request<PrintBatch[]>(`/queue/batches${params}`);
  6458. },
  6459. cancelBatch: (id: number) =>
  6460. request<{ message: string }>(`/queue/batches/${id}`, { method: 'DELETE' }),
  6461. createBatch: (data: PrintBatchCreate) =>
  6462. request<PrintBatch>('/queue/batches', {
  6463. method: 'POST',
  6464. body: JSON.stringify(data),
  6465. }),
  6466. dispatchBatch: (id: number, data: PrintBatchDispatchRequest = {}) =>
  6467. request<PrintBatch>(`/queue/batches/${id}/dispatch`, {
  6468. method: 'POST',
  6469. body: JSON.stringify(data),
  6470. }),
  6471. ungroupBatch: (id: number) =>
  6472. request<{ ungrouped_count: number; message: string }>(
  6473. `/queue/batches/${id}/ungroup`,
  6474. { method: 'POST' },
  6475. ),
  6476. // K-Profiles
  6477. getKProfiles: (printerId: number, nozzleDiameter = '0.4') =>
  6478. request<KProfilesResponse>(`/printers/${printerId}/kprofiles/?nozzle_diameter=${nozzleDiameter}`),
  6479. setKProfile: (printerId: number, profile: KProfileCreate) =>
  6480. request<KProfileWriteResult>(`/printers/${printerId}/kprofiles/`, {
  6481. method: 'POST',
  6482. body: JSON.stringify(profile),
  6483. }),
  6484. deleteKProfile: (printerId: number, profile: KProfileDelete) =>
  6485. request<KProfileWriteResult>(`/printers/${printerId}/kprofiles/`, {
  6486. method: 'DELETE',
  6487. body: JSON.stringify(profile),
  6488. }),
  6489. setKProfilesBatch: (printerId: number, profiles: KProfileCreate[]) =>
  6490. request<KProfileWriteResult>(`/printers/${printerId}/kprofiles/batch`, {
  6491. method: 'POST',
  6492. body: JSON.stringify(profiles),
  6493. }),
  6494. // Finance
  6495. getMyBalance: () => request<WalletBalance>('/finance/me/balance'),
  6496. getMyTransactions: (limit = 50, offset = 0) =>
  6497. request<WalletTransactionListResponse>(`/finance/me/transactions?limit=${limit}&offset=${offset}`),
  6498. getAllTransactions: (limit = 50, offset = 0, userId?: number) => {
  6499. const params = new URLSearchParams();
  6500. params.set('limit', String(limit));
  6501. params.set('offset', String(offset));
  6502. if (userId !== undefined) params.set('user_id', String(userId));
  6503. return request<WalletTransactionListResponse>(`/finance/transactions?${params.toString()}`);
  6504. },
  6505. deleteTransaction: (transactionId: number) =>
  6506. request<{ status: string }>(`/finance/transactions/${transactionId}`, {
  6507. method: 'DELETE',
  6508. }),
  6509. editTransaction: (transactionId: number, data: TransactionEditRequest) =>
  6510. request<WalletTransaction>(`/finance/transactions/${transactionId}`, {
  6511. method: 'PATCH',
  6512. body: JSON.stringify(data),
  6513. }),
  6514. createManualPrint: (data: ManualPrintRequest) =>
  6515. request<WalletTransaction>('/finance/transactions/manual', {
  6516. method: 'POST',
  6517. body: JSON.stringify(data),
  6518. }),
  6519. getMyCostCenters: () => request<CostCenterSummary[]>('/finance/cost-centers/mine'),
  6520. listCostCenters: (includeInactive = false) =>
  6521. request<CostCenterSummary[]>(`/finance/cost-centers?include_inactive=${includeInactive ? 'true' : 'false'}`),
  6522. createCostCenter: (data: CostCenterCreateRequest) =>
  6523. request<CostCenterSummary>('/finance/cost-centers', {
  6524. method: 'POST',
  6525. body: JSON.stringify(data),
  6526. }),
  6527. updateCostCenter: (costCenterId: number, data: CostCenterUpdateRequest) =>
  6528. request<CostCenterSummary>(`/finance/cost-centers/${costCenterId}`, {
  6529. method: 'PATCH',
  6530. body: JSON.stringify(data),
  6531. }),
  6532. updateCostCenterBudgets: (costCenterId: number, data: CostCenterBudgetUpdateRequest) =>
  6533. request<CostCenterSummary>(`/finance/cost-centers/${costCenterId}/budgets`, {
  6534. method: 'PATCH',
  6535. body: JSON.stringify(data),
  6536. }),
  6537. deleteCostCenter: (costCenterId: number) =>
  6538. request<{ status: string }>(`/finance/cost-centers/${costCenterId}`, {
  6539. method: 'DELETE',
  6540. }),
  6541. getCostCenter: (costCenterId: number) =>
  6542. request<CostCenterDetail>(`/finance/cost-centers/${costCenterId}`),
  6543. upsertCostCenterMember: (costCenterId: number, data: CostCenterMemberRequest) =>
  6544. request<CostCenterMemberResponse>(`/finance/cost-centers/${costCenterId}/members`, {
  6545. method: 'POST',
  6546. body: JSON.stringify(data),
  6547. }),
  6548. removeCostCenterMember: (costCenterId: number, userId: number) =>
  6549. request<{ status: string }>(`/finance/cost-centers/${costCenterId}/members/${userId}`, {
  6550. method: 'DELETE',
  6551. }),
  6552. depositUserBalance: (userId: number, data: WalletAdjustmentRequest) =>
  6553. request<WalletAdjustmentResponse>(`/finance/users/${userId}/deposit`, {
  6554. method: 'POST',
  6555. body: JSON.stringify(data),
  6556. }),
  6557. withdrawUserBalance: (userId: number, data: WalletAdjustmentRequest) =>
  6558. request<WalletAdjustmentResponse>(`/finance/users/${userId}/withdraw`, {
  6559. method: 'POST',
  6560. body: JSON.stringify(data),
  6561. }),
  6562. rebuildBalanceLedger: () =>
  6563. request<{ status: string }>('/finance/rebuild-balance-ledger', {
  6564. method: 'POST',
  6565. }),
  6566. // K-Profile Notes (stored locally, not on printer)
  6567. getKProfileNotes: (printerId: number) =>
  6568. request<KProfileNotesResponse>(`/printers/${printerId}/kprofiles/notes`),
  6569. setKProfileNote: (printerId: number, settingId: string, note: string) =>
  6570. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/notes`, {
  6571. method: 'PUT',
  6572. body: JSON.stringify({ setting_id: settingId, note }),
  6573. }),
  6574. // Slot Preset Mappings
  6575. getSlotPresets: (printerId: number) => slotPresetsBatch(printerId),
  6576. saveSlotPreset: (printerId: number, amsId: number, trayId: number, presetId: string, presetName: string, presetSource = 'cloud', trayInfoIdx?: string) =>
  6577. 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)}` : ''}`, {
  6578. method: 'PUT',
  6579. }),
  6580. // AMS Labels (user-defined friendly names)
  6581. getAmsLabels: (printerId: number) => amsLabelsBatch(printerId),
  6582. saveAmsLabel: (printerId: number, amsId: number, label: string, amsSerial = '') =>
  6583. request<{ ams_id: number; label: string }>(
  6584. `/printers/${printerId}/ams-labels/${amsId}`,
  6585. {
  6586. method: 'PUT',
  6587. body: JSON.stringify({ label, ams_serial: amsSerial }),
  6588. }
  6589. ),
  6590. deleteAmsLabel: (printerId: number, amsId: number, amsSerial = '') =>
  6591. request<{ success: boolean }>(`/printers/${printerId}/ams-labels/${amsId}?ams_serial=${encodeURIComponent(amsSerial)}`, {
  6592. method: 'DELETE',
  6593. }),
  6594. configureAmsSlot: (
  6595. printerId: number,
  6596. amsId: number,
  6597. trayId: number,
  6598. config: {
  6599. tray_info_idx: string;
  6600. tray_type: string;
  6601. tray_sub_brands: string;
  6602. tray_color: string;
  6603. nozzle_temp_min: number;
  6604. nozzle_temp_max: number;
  6605. cali_idx: number;
  6606. nozzle_diameter: string;
  6607. setting_id?: string;
  6608. kprofile_filament_id?: string;
  6609. kprofile_setting_id?: string;
  6610. k_value?: number;
  6611. // Orca Cloud profile the slot is set to; the backend looks up its
  6612. // filament id when tray_info_idx is empty (#3216).
  6613. orca_profile_id?: string;
  6614. }
  6615. ) => {
  6616. const params = new URLSearchParams({
  6617. tray_info_idx: config.tray_info_idx,
  6618. tray_type: config.tray_type,
  6619. tray_sub_brands: config.tray_sub_brands,
  6620. tray_color: config.tray_color,
  6621. nozzle_temp_min: config.nozzle_temp_min.toString(),
  6622. nozzle_temp_max: config.nozzle_temp_max.toString(),
  6623. cali_idx: config.cali_idx.toString(),
  6624. nozzle_diameter: config.nozzle_diameter,
  6625. });
  6626. if (config.setting_id) {
  6627. params.set('setting_id', config.setting_id);
  6628. }
  6629. if (config.kprofile_filament_id) {
  6630. params.set('kprofile_filament_id', config.kprofile_filament_id);
  6631. }
  6632. if (config.kprofile_setting_id) {
  6633. params.set('kprofile_setting_id', config.kprofile_setting_id);
  6634. }
  6635. if (config.k_value !== undefined && config.k_value > 0) {
  6636. params.set('k_value', config.k_value.toString());
  6637. }
  6638. if (config.orca_profile_id) {
  6639. params.set('orca_profile_id', config.orca_profile_id);
  6640. }
  6641. return request<{
  6642. success: boolean;
  6643. message: string;
  6644. // The filament id the slot was actually given.
  6645. tray_info_idx?: string;
  6646. // Why an Orca profile went out as the generic for its material, or "".
  6647. orca_fallback_reason?: '' | 'no_filament_id' | 'lookup_failed' | 'no_permission';
  6648. /** A manual K value could not be sent; the filament setting was. */
  6649. k_value_unsent?: boolean;
  6650. }>(
  6651. `/printers/${printerId}/slots/${amsId}/${trayId}/configure?${params}`,
  6652. { method: 'POST' }
  6653. );
  6654. },
  6655. resetAmsSlot: (printerId: number, amsId: number, trayId: number) =>
  6656. request<{ success: boolean; message: string }>(
  6657. `/printers/${printerId}/ams/${amsId}/tray/${trayId}/reset`,
  6658. { method: 'POST' }
  6659. ),
  6660. // Notification Providers
  6661. getNotificationProviders: () => request<NotificationProvider[]>('/notifications/'),
  6662. createNotificationProvider: (data: NotificationProviderCreate) =>
  6663. request<NotificationProvider>('/notifications/', {
  6664. method: 'POST',
  6665. body: JSON.stringify(data),
  6666. }),
  6667. updateNotificationProvider: (id: number, data: NotificationProviderUpdate) =>
  6668. request<NotificationProvider>(`/notifications/${id}`, {
  6669. method: 'PATCH',
  6670. body: JSON.stringify(data),
  6671. }),
  6672. deleteNotificationProvider: (id: number) =>
  6673. request<{ message: string }>(`/notifications/${id}`, { method: 'DELETE' }),
  6674. testNotificationProvider: (id: number) =>
  6675. request<NotificationTestResponse>(`/notifications/${id}/test`, { method: 'POST' }),
  6676. testNotificationConfig: (data: NotificationTestRequest) =>
  6677. request<NotificationTestResponse>('/notifications/test-config', {
  6678. method: 'POST',
  6679. body: JSON.stringify(data),
  6680. }),
  6681. testAllNotificationProviders: () =>
  6682. request<{
  6683. tested: number;
  6684. success: number;
  6685. failed: number;
  6686. results: Array<{
  6687. provider_id: number;
  6688. provider_name: string;
  6689. provider_type: string;
  6690. success: boolean;
  6691. message: string;
  6692. }>;
  6693. }>('/notifications/test-all', { method: 'POST' }),
  6694. // Notification Templates
  6695. getNotificationTemplates: () => request<NotificationTemplate[]>('/notification-templates'),
  6696. updateNotificationTemplate: (id: number, data: NotificationTemplateUpdate) =>
  6697. request<NotificationTemplate>(`/notification-templates/${id}`, {
  6698. method: 'PUT',
  6699. body: JSON.stringify(data),
  6700. }),
  6701. resetNotificationTemplate: (id: number) =>
  6702. request<NotificationTemplate>(`/notification-templates/${id}/reset`, {
  6703. method: 'POST',
  6704. }),
  6705. getTemplateVariables: () => request<EventVariablesResponse[]>('/notification-templates/variables'),
  6706. previewTemplate: (data: TemplatePreviewRequest) =>
  6707. request<TemplatePreviewResponse>('/notification-templates/preview', {
  6708. method: 'POST',
  6709. body: JSON.stringify(data),
  6710. }),
  6711. // Notification Logs
  6712. getNotificationLogs: (params?: {
  6713. limit?: number;
  6714. offset?: number;
  6715. provider_id?: number;
  6716. event_type?: string;
  6717. success?: boolean;
  6718. days?: number;
  6719. }) => {
  6720. const searchParams = new URLSearchParams();
  6721. if (params?.limit) searchParams.set('limit', String(params.limit));
  6722. if (params?.offset) searchParams.set('offset', String(params.offset));
  6723. if (params?.provider_id) searchParams.set('provider_id', String(params.provider_id));
  6724. if (params?.event_type) searchParams.set('event_type', params.event_type);
  6725. if (params?.success !== undefined) searchParams.set('success', String(params.success));
  6726. if (params?.days) searchParams.set('days', String(params.days));
  6727. return request<NotificationLogEntry[]>(`/notifications/logs?${searchParams}`);
  6728. },
  6729. getNotificationLogStats: (days = 7) =>
  6730. request<NotificationLogStats>(`/notifications/logs/stats?days=${days}`),
  6731. clearNotificationLogs: (olderThanDays = 30) =>
  6732. request<{ deleted: number; message: string }>(
  6733. `/notifications/logs?older_than_days=${olderThanDays}`,
  6734. { method: 'DELETE' }
  6735. ),
  6736. // Spoolman Integration
  6737. getSpoolmanStatus: () => request<SpoolmanStatus>('/spoolman/status'),
  6738. migrateSpoolmanTags: (dryRun: boolean) =>
  6739. request<SpoolmanTagMigrationReport>(`/spoolman/inventory/tags/migrate?dry_run=${dryRun}`, {
  6740. method: 'POST',
  6741. }),
  6742. connectSpoolman: () =>
  6743. request<{ success: boolean; message: string }>('/spoolman/connect', {
  6744. method: 'POST',
  6745. }),
  6746. syncPrinterAms: (printerId: number) =>
  6747. request<SpoolmanSyncResult>(`/spoolman/sync/${printerId}`, {
  6748. method: 'POST',
  6749. }),
  6750. syncAllPrintersAms: () =>
  6751. request<SpoolmanSyncResult>('/spoolman/sync-all', {
  6752. method: 'POST',
  6753. }),
  6754. getSpoolmanInventoryFilaments: () =>
  6755. request<SpoolmanFilamentEntry[]>('/spoolman/inventory/filaments'),
  6756. getUnlinkedSpools: () =>
  6757. request<UnlinkedSpool[]>('/spoolman/spools/unlinked'),
  6758. getLinkedSpools: () =>
  6759. request<LinkedSpoolsMap>('/spoolman/spools/linked'),
  6760. linkSpool: (
  6761. spoolId: number,
  6762. context: {
  6763. spoolTag: string;
  6764. printerId: number;
  6765. amsId: number;
  6766. trayId: number;
  6767. }
  6768. ) =>
  6769. request<{ success: boolean; message: string }>(`/spoolman/spools/${spoolId}/link`, {
  6770. method: 'POST',
  6771. body: JSON.stringify({
  6772. spool_tag: context.spoolTag,
  6773. printer_id: context.printerId,
  6774. ams_id: context.amsId,
  6775. tray_id: context.trayId,
  6776. }),
  6777. }),
  6778. unlinkSpool: (spoolId: number) =>
  6779. request<{ success: boolean; message: string }>(`/spoolman/spools/${spoolId}/unlink`, {
  6780. method: 'POST',
  6781. }),
  6782. createSpoolmanSpoolFromSlot: (data: { printer_id: number; ams_id: number; tray_id: number }) =>
  6783. request<{ success: boolean; spool_id: number | null }>(`/spoolman/spools/from-slot`, {
  6784. method: 'POST',
  6785. body: JSON.stringify(data),
  6786. }),
  6787. createSpoolFromSlot: (data: { printer_id: number; ams_id: number; tray_id: number }) =>
  6788. request<InventorySpool>(`/inventory/spools/from-slot`, {
  6789. method: 'POST',
  6790. body: JSON.stringify(data),
  6791. }),
  6792. getSpoolmanSettings: () =>
  6793. 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'),
  6794. 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; }) =>
  6795. 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', {
  6796. method: 'PUT',
  6797. body: JSON.stringify(data),
  6798. }),
  6799. // Inventory
  6800. getSpools: (includeArchived = false) =>
  6801. request<InventorySpool[]>(`/inventory/spools?include_archived=${includeArchived}`),
  6802. getSpool: (id: number) => request<InventorySpool>(`/inventory/spools/${id}`),
  6803. createSpool: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>) =>
  6804. request<InventorySpool>('/inventory/spools', {
  6805. method: 'POST',
  6806. body: JSON.stringify(data),
  6807. }),
  6808. bulkCreateSpools: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>, quantity: number) =>
  6809. request<InventorySpool[]>('/inventory/spools/bulk', {
  6810. method: 'POST',
  6811. body: JSON.stringify({ spool: data, quantity }),
  6812. }),
  6813. // ── CSV import/export (#1576) ────────────────────────────────────────────
  6814. // dry_run=true → preview (no write); omitted → real import. Both share one
  6815. // multipart upload helper; see `uploadSpoolsCsv` below.
  6816. importSpoolsCsvPreview: (file: File): Promise<CsvImportPreview> => uploadSpoolsCsv<CsvImportPreview>(file, true),
  6817. importSpoolsCsv: (file: File): Promise<CsvImportResult> => uploadSpoolsCsv<CsvImportResult>(file, false),
  6818. exportSpoolsCsv: async (): Promise<void> => {
  6819. const headers: Record<string, string> = {};
  6820. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  6821. const response = await fetch(`${API_BASE}/inventory/spools/export`, { headers });
  6822. if (!response.ok) {
  6823. const error = await response.json().catch(() => ({}));
  6824. throw new Error(error.detail || `HTTP ${response.status}`);
  6825. }
  6826. const disposition = response.headers.get('Content-Disposition');
  6827. const filename = parseContentDispositionFilename(disposition) || 'bambuddy_inventory.csv';
  6828. const blob = await response.blob();
  6829. const url = window.URL.createObjectURL(blob);
  6830. const a = document.createElement('a');
  6831. a.href = url;
  6832. a.download = filename;
  6833. document.body.appendChild(a);
  6834. a.click();
  6835. document.body.removeChild(a);
  6836. window.URL.revokeObjectURL(url);
  6837. },
  6838. updateSpool: (id: number, data: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  6839. request<InventorySpool>(`/inventory/spools/${id}`, {
  6840. method: 'PATCH',
  6841. body: JSON.stringify(data),
  6842. }),
  6843. deleteSpool: (id: number) =>
  6844. request<{ status: string }>(`/inventory/spools/${id}`, { method: 'DELETE' }),
  6845. archiveSpool: (id: number) =>
  6846. request<InventorySpool>(`/inventory/spools/${id}/archive`, { method: 'POST' }),
  6847. restoreSpool: (id: number) =>
  6848. request<InventorySpool>(`/inventory/spools/${id}/restore`, { method: 'POST' }),
  6849. resetSpoolConsumedCounter: (id: number) =>
  6850. request<InventorySpool>(`/inventory/spools/${id}/reset-consumed-counter`, { method: 'POST' }),
  6851. bulkResetSpoolConsumedCounter: (spoolIds: number[]) =>
  6852. request<{ reset: number; not_found?: number[]; errors?: Array<{ id: number; status: number; detail: string }> }>(`/inventory/spools/reset-consumed-counter-bulk`, {
  6853. method: 'POST',
  6854. body: JSON.stringify({ spool_ids: spoolIds }),
  6855. }),
  6856. bulkUpdateSpools: (ids: number[], update: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  6857. request<{ updated: number; not_found: number[] }>(`/inventory/spools/bulk-update`, {
  6858. method: 'POST',
  6859. body: JSON.stringify({ ids, update }),
  6860. }),
  6861. bulkDeleteSpools: (ids: number[]) =>
  6862. request<{ deleted: number; not_found: number[] }>(`/inventory/spools/bulk-delete`, {
  6863. method: 'POST',
  6864. body: JSON.stringify({ ids }),
  6865. }),
  6866. bulkArchiveSpools: (ids: number[]) =>
  6867. request<{ archived: number; already_archived: number[]; not_found: number[] }>(`/inventory/spools/bulk-archive`, {
  6868. method: 'POST',
  6869. body: JSON.stringify({ ids }),
  6870. }),
  6871. bulkRestoreSpools: (ids: number[]) =>
  6872. request<{ restored: number; already_active: number[]; not_found: number[] }>(`/inventory/spools/bulk-restore`, {
  6873. method: 'POST',
  6874. body: JSON.stringify({ ids }),
  6875. }),
  6876. getSpoolKProfiles: (spoolId: number) =>
  6877. request<SpoolKProfile[]>(`/inventory/spools/${spoolId}/k-profiles`),
  6878. saveSpoolKProfiles: (spoolId: number, profiles: SpoolKProfileInput[]) =>
  6879. request<SpoolKProfile[]>(`/inventory/spools/${spoolId}/k-profiles`, {
  6880. method: 'PUT',
  6881. body: JSON.stringify(profiles),
  6882. }),
  6883. /**
  6884. * What the spool assigned to this slot is configured to use *here* -- its
  6885. * per-printer-model filament preset and the K profile for this slot's hotend.
  6886. * Nulls when the slot holds no known spool.
  6887. */
  6888. getSlotSpoolDefaults: (printerId: number, amsId: number, trayId: number) =>
  6889. request<SlotSpoolDefaults>(`/printers/${printerId}/slots/${amsId}/${trayId}/spool-defaults`),
  6890. getSpoolFilamentPresets: (spoolId: number) =>
  6891. request<SpoolFilamentPreset[]>(`/inventory/spools/${spoolId}/filament-presets`),
  6892. saveSpoolFilamentPresets: (spoolId: number, presets: SpoolFilamentPresetInput[]) =>
  6893. request<SpoolFilamentPreset[]>(`/inventory/spools/${spoolId}/filament-presets`, {
  6894. method: 'PUT',
  6895. body: JSON.stringify(presets),
  6896. }),
  6897. getProfileDefaults: () => request<ProfileDefault[]>('/inventory/profile-defaults'),
  6898. resolveProfileDefault: (key: ProfileDefaultKey) => {
  6899. const params = new URLSearchParams({
  6900. brand: key.brand,
  6901. material: key.material,
  6902. subtype: key.subtype,
  6903. color_name: key.color_name,
  6904. });
  6905. return request<ResolvedProfileDefault | null>(`/inventory/profile-defaults/resolve?${params}`);
  6906. },
  6907. saveProfileDefault: (data: ProfileDefaultInput) =>
  6908. request<ProfileDefault>('/inventory/profile-defaults', {
  6909. method: 'PUT',
  6910. body: JSON.stringify(data),
  6911. }),
  6912. deleteProfileDefault: (defaultId: number) =>
  6913. request<{ status: string }>(`/inventory/profile-defaults/${defaultId}`, { method: 'DELETE' }),
  6914. /** Fills in what active spools of the default's product lack; the inventory mode picks the route. */
  6915. applyProfileDefault: (defaultId: number, spoolmanMode: boolean) =>
  6916. request<{ updated: number }>(
  6917. spoolmanMode
  6918. ? `/spoolman/inventory/profile-defaults/${defaultId}/apply`
  6919. : `/inventory/profile-defaults/${defaultId}/apply`,
  6920. { method: 'POST' },
  6921. ),
  6922. getAssignments: (printerId?: number) =>
  6923. request<SpoolAssignment[]>(`/inventory/assignments${printerId ? `?printer_id=${printerId}` : ''}`),
  6924. // move: the spool also leaves any other slot it is in, in the same
  6925. // transaction (#1574) -- for a scanned spool, the one in the user's hand.
  6926. assignSpool: (data: { spool_id: number; printer_id: number; ams_id: number; tray_id: number; move?: boolean }) =>
  6927. request<SpoolAssignment>('/inventory/assignments', {
  6928. method: 'POST',
  6929. body: JSON.stringify(data),
  6930. }),
  6931. unassignSpool: (printerId: number, amsId: number, trayId: number) =>
  6932. request<{ status: string }>(`/inventory/assignments/${printerId}/${amsId}/${trayId}`, { method: 'DELETE' }),
  6933. // ── Spool label printing (#809) ──────────────────────────────────────────
  6934. // The print endpoints return a PDF, a PNG, or a ZIP of PNGs (#2981); the
  6935. // preview endpoints one PNG. Callers get the Blob and decide what to do.
  6936. printSpoolLabels: (data: PrintSpoolLabelsRequest): Promise<Blob> =>
  6937. postForBlob('/inventory/labels', data),
  6938. printSpoolmanSpoolLabels: (data: PrintSpoolLabelsRequest): Promise<Blob> =>
  6939. postForBlob('/spoolman/labels', data),
  6940. previewSpoolLabel: (data: PreviewSpoolLabelRequest, signal?: AbortSignal): Promise<Blob> =>
  6941. postForBlob('/inventory/labels/preview', data, signal),
  6942. previewSpoolmanSpoolLabel: (data: PreviewSpoolLabelRequest, signal?: AbortSignal): Promise<Blob> =>
  6943. postForBlob('/spoolman/labels/preview', data, signal),
  6944. getLabelTemplates: () => request<SavedLabelTemplate[]>('/label-templates'),
  6945. createLabelTemplate: (data: { name: string; layout: LabelSheetLayout }) =>
  6946. request<SavedLabelTemplate>('/label-templates', { method: 'POST', body: JSON.stringify(data) }),
  6947. updateLabelTemplate: (id: number, data: { name: string; layout: LabelSheetLayout }) =>
  6948. request<SavedLabelTemplate>(`/label-templates/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  6949. deleteLabelTemplate: (id: number) => request<void>(`/label-templates/${id}`, { method: 'DELETE' }),
  6950. getSpoolCatalog: () =>
  6951. request<SpoolCatalogEntry[]>('/inventory/catalog'),
  6952. addCatalogEntry: (data: { name: string; weight: number }) =>
  6953. request<SpoolCatalogEntry>('/inventory/catalog', { method: 'POST', body: JSON.stringify(data) }),
  6954. updateCatalogEntry: (id: number, data: { name: string; weight: number }) =>
  6955. request<SpoolCatalogEntry>(`/inventory/catalog/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  6956. deleteCatalogEntry: (id: number) =>
  6957. request<{ status: string }>(`/inventory/catalog/${id}`, { method: 'DELETE' }),
  6958. bulkDeleteCatalogEntries: (ids: number[]) =>
  6959. request<{ deleted: number }>('/inventory/catalog/bulk-delete', { method: 'POST', body: JSON.stringify({ ids }) }),
  6960. resetSpoolCatalog: () =>
  6961. request<{ status: string }>('/inventory/catalog/reset', { method: 'POST' }),
  6962. // ── Suppliers (#2988) — inventory master data, Locations pattern ─────────
  6963. getSuppliers: () =>
  6964. request<Supplier[]>('/inventory/suppliers'),
  6965. createSupplier: (data: SupplierInput) =>
  6966. request<Supplier>('/inventory/suppliers', { method: 'POST', body: JSON.stringify(data) }),
  6967. updateSupplier: (id: number, data: Partial<SupplierInput>) =>
  6968. request<Supplier>(`/inventory/suppliers/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  6969. deleteSupplier: (id: number) =>
  6970. request<{ status: string }>(`/inventory/suppliers/${id}`, { method: 'DELETE' }),
  6971. setSpoolSuppliers: (spoolId: number, links: SpoolSupplierLinkInput[]) =>
  6972. request<SpoolSupplierLink[]>(`/inventory/spools/${spoolId}/suppliers`, {
  6973. method: 'PUT',
  6974. body: JSON.stringify(links),
  6975. }),
  6976. // Spoolman parity: the assignment rows live Bambuddy-side, keyed by the
  6977. // remote spool id — same request/response shape as the built-in inventory.
  6978. setSpoolmanSpoolSuppliers: (spoolmanSpoolId: number, links: SpoolSupplierLinkInput[]) =>
  6979. request<SpoolSupplierLink[]>(`/spoolman/inventory/spools/${spoolmanSpoolId}/suppliers`, {
  6980. method: 'PUT',
  6981. body: JSON.stringify(links),
  6982. }),
  6983. // date_from/date_to scope the usage half only, so the widget can follow the
  6984. // dashboard timeframe; stock stays point-in-time.
  6985. getSupplierStats: (dateFrom?: string, dateTo?: string) => {
  6986. const params = new URLSearchParams();
  6987. if (dateFrom) params.set('date_from', dateFrom);
  6988. if (dateTo) params.set('date_to', dateTo);
  6989. addDayZone(params);
  6990. const qs = params.toString();
  6991. return request<SupplierStats[]>(`/inventory/stats/suppliers${qs ? `?${qs}` : ''}`);
  6992. },
  6993. getLocations: () =>
  6994. request<StorageLocation[]>('/inventory/locations'),
  6995. createLocation: (data: { name: string; identifier?: string | null }) =>
  6996. request<StorageLocation>('/inventory/locations', { method: 'POST', body: JSON.stringify(data) }),
  6997. updateLocation: (id: number, data: { name?: string; identifier?: string | null }) =>
  6998. request<StorageLocation>(`/inventory/locations/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  6999. deleteLocation: (id: number) =>
  7000. request<{ status: string }>(`/inventory/locations/${id}`, { method: 'DELETE' }),
  7001. getColorCatalog: () =>
  7002. request<ColorCatalogEntry[]>('/inventory/colors'),
  7003. /** Flat hex→name map, plus the names collapsing it loses. ``by_material`` is
  7004. * keyed ``"<material>|<hex>"`` and only carries entries that differ from the
  7005. * flat answer (e.g. ``"pla matte|ffffff" -> "Ivory White"`` where the flat
  7006. * map says "Jade White"). #2875. */
  7007. getColorNameMap: () =>
  7008. request<{
  7009. colors: Record<string, string>;
  7010. by_material?: Record<string, string>;
  7011. bambu?: BambuCatalogColor[];
  7012. preset_materials?: Record<string, string>;
  7013. }>('/inventory/colors/map'),
  7014. addColorEntry: (data: {
  7015. manufacturer: string;
  7016. color_name: string;
  7017. hex_color: string;
  7018. material: string | null;
  7019. extra_colors?: string | null;
  7020. effect_type?: string | null;
  7021. }) =>
  7022. request<ColorCatalogEntry>('/inventory/colors', { method: 'POST', body: JSON.stringify(data) }),
  7023. updateColorEntry: (
  7024. id: number,
  7025. data: {
  7026. manufacturer: string;
  7027. color_name: string;
  7028. hex_color: string;
  7029. material: string | null;
  7030. extra_colors?: string | null;
  7031. effect_type?: string | null;
  7032. },
  7033. ) => request<ColorCatalogEntry>(`/inventory/colors/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  7034. deleteColorEntry: (id: number) =>
  7035. request<{ status: string }>(`/inventory/colors/${id}`, { method: 'DELETE' }),
  7036. bulkDeleteColorEntries: (ids: number[]) =>
  7037. request<{ deleted: number }>('/inventory/colors/bulk-delete', { method: 'POST', body: JSON.stringify({ ids }) }),
  7038. resetColorCatalog: () =>
  7039. request<{ status: string }>('/inventory/colors/reset', { method: 'POST' }),
  7040. searchColors: (manufacturer?: string, material?: string) =>
  7041. request<ColorCatalogEntry[]>(`/inventory/colors/search?${manufacturer ? `manufacturer=${encodeURIComponent(manufacturer)}` : ''}${manufacturer && material ? '&' : ''}${material ? `material=${encodeURIComponent(material)}` : ''}`),
  7042. linkTagToSpool: (spoolId: number, data: { tag_uid?: string; tray_uuid?: string; tag_type?: string; data_origin?: string }) =>
  7043. request<InventorySpool>(`/inventory/spools/${spoolId}/link-tag`, {
  7044. method: 'PATCH',
  7045. body: JSON.stringify(data),
  7046. }),
  7047. // Per-material-number inventory aggregate (#2870). The date range narrows
  7048. // the usage half only — stock is point-in-time.
  7049. getMaterialNumberStats: (options?: { dateFrom?: string; dateTo?: string }) => {
  7050. const params = new URLSearchParams();
  7051. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  7052. if (options?.dateTo) params.set('date_to', options.dateTo);
  7053. addDayZone(params);
  7054. const qs = params.toString();
  7055. return request<MaterialNumberStats[]>(`/inventory/stats/material-numbers${qs ? `?${qs}` : ''}`);
  7056. },
  7057. getSpoolUsageHistory: (spoolId: number, limit = 50) =>
  7058. request<SpoolUsageRecord[]>(`/inventory/spools/${spoolId}/usage?limit=${limit}`),
  7059. // One inventory's at a time: ``spoolman`` for the Spoolman spools' (#3407).
  7060. getAllUsageHistory: (limit = 100, printerId?: number, spoolman = false) =>
  7061. request<SpoolUsageRecord[]>(
  7062. `/inventory/usage?limit=${limit}${printerId ? `&printer_id=${printerId}` : ''}${spoolman ? '&spoolman=true' : ''}`,
  7063. ),
  7064. getSpoolmanSpoolUsageHistory: (spoolId: number, limit = 50) =>
  7065. request<SpoolUsageRecord[]>(`/spoolman/inventory/spools/${spoolId}/usage?limit=${limit}`),
  7066. clearSpoolmanSpoolUsageHistory: (spoolId: number) =>
  7067. request<{ status: string }>(`/spoolman/inventory/spools/${spoolId}/usage`, { method: 'DELETE' }),
  7068. clearSpoolUsageHistory: (spoolId: number) =>
  7069. request<{ status: string }>(`/inventory/spools/${spoolId}/usage`, { method: 'DELETE' }),
  7070. syncWeightsFromAms: () =>
  7071. request<{ synced: number; skipped: number; printing?: number }>('/inventory/sync-ams-weights', { method: 'POST' }),
  7072. getSkuSettings: () =>
  7073. request<FilamentSkuSettings[]>('/inventory/sku-settings'),
  7074. upsertSkuSettings: (data: Omit<FilamentSkuSettings, 'id'>) =>
  7075. request<FilamentSkuSettings>('/inventory/sku-settings', {
  7076. method: 'POST',
  7077. body: JSON.stringify(data),
  7078. }),
  7079. getShoppingList: () =>
  7080. request<ShoppingListItem[]>('/inventory/shopping-list'),
  7081. addToShoppingList: (data: ShoppingListItemCreate) =>
  7082. request<ShoppingListItem>('/inventory/shopping-list', {
  7083. method: 'POST',
  7084. body: JSON.stringify(data),
  7085. }),
  7086. removeFromShoppingList: (id: number) =>
  7087. request<{ status: string }>(`/inventory/shopping-list/${id}`, { method: 'DELETE' }),
  7088. clearShoppingList: () =>
  7089. request<{ deleted: number }>('/inventory/shopping-list', { method: 'DELETE' }),
  7090. updateShoppingListStatus: (id: number, status: 'pending' | 'purchased' | 'received') =>
  7091. request<ShoppingListItem>(`/inventory/shopping-list/${id}/status`, {
  7092. method: 'PATCH',
  7093. body: JSON.stringify({ status }),
  7094. }),
  7095. getFilamentPresets: () =>
  7096. request<SlicerSetting[]>('/cloud/filaments'),
  7097. // Spoolman Inventory proxy (unified UI when Spoolman is enabled)
  7098. getSpoolmanInventorySpools: (includeArchived = false) =>
  7099. request<InventorySpool[]>(`/spoolman/inventory/spools?include_archived=${includeArchived}`),
  7100. getSpoolmanInventorySpool: (id: number) =>
  7101. request<InventorySpool>(`/spoolman/inventory/spools/${id}`),
  7102. createSpoolmanInventorySpool: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>) =>
  7103. request<InventorySpool>('/spoolman/inventory/spools', {
  7104. method: 'POST',
  7105. body: JSON.stringify(data),
  7106. }),
  7107. bulkCreateSpoolmanInventorySpools: (
  7108. data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>,
  7109. quantity: number,
  7110. ) =>
  7111. request<SpoolmanBulkCreateResult | InventorySpool[]>('/spoolman/inventory/spools/bulk', {
  7112. method: 'POST',
  7113. body: JSON.stringify({ spool: data, quantity }),
  7114. }),
  7115. updateSpoolmanInventorySpool: (
  7116. id: number,
  7117. data: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>,
  7118. ) =>
  7119. request<InventorySpool>(`/spoolman/inventory/spools/${id}`, {
  7120. method: 'PATCH',
  7121. body: JSON.stringify(data),
  7122. }),
  7123. deleteSpoolmanInventorySpool: (id: number) =>
  7124. request<{ status: string }>(`/spoolman/inventory/spools/${id}`, { method: 'DELETE' }),
  7125. archiveSpoolmanInventorySpool: (id: number) =>
  7126. request<InventorySpool>(`/spoolman/inventory/spools/${id}/archive`, { method: 'POST' }),
  7127. restoreSpoolmanInventorySpool: (id: number) =>
  7128. request<InventorySpool>(`/spoolman/inventory/spools/${id}/restore`, { method: 'POST' }),
  7129. resetSpoolmanInventorySpoolConsumedCounter: (id: number) =>
  7130. request<InventorySpool>(`/spoolman/inventory/spools/${id}/reset-consumed-counter`, { method: 'POST' }),
  7131. bulkResetSpoolmanInventorySpoolConsumedCounter: (spoolIds: number[]) =>
  7132. request<{ reset: number; not_found?: number[]; errors?: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/reset-consumed-counter-bulk`, {
  7133. method: 'POST',
  7134. body: JSON.stringify({ spool_ids: spoolIds }),
  7135. }),
  7136. bulkUpdateSpoolmanInventorySpools: (ids: number[], update: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  7137. request<{ updated: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-update`, {
  7138. method: 'POST',
  7139. body: JSON.stringify({ ids, update }),
  7140. }),
  7141. bulkDeleteSpoolmanInventorySpools: (ids: number[]) =>
  7142. request<{ deleted: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-delete`, {
  7143. method: 'POST',
  7144. body: JSON.stringify({ ids }),
  7145. }),
  7146. bulkArchiveSpoolmanInventorySpools: (ids: number[]) =>
  7147. request<{ archived: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-archive`, {
  7148. method: 'POST',
  7149. body: JSON.stringify({ ids }),
  7150. }),
  7151. bulkRestoreSpoolmanInventorySpools: (ids: number[]) =>
  7152. request<{ restored: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-restore`, {
  7153. method: 'POST',
  7154. body: JSON.stringify({ ids }),
  7155. }),
  7156. linkTagToSpoolmanSpool: (spoolId: number, data: { tag_uid?: string; tray_uuid?: string }) =>
  7157. request<InventorySpool>(`/spoolman/inventory/spools/${spoolId}/tag`, {
  7158. method: 'PATCH',
  7159. body: JSON.stringify(data),
  7160. }),
  7161. syncSpoolmanSpoolWeight: (spoolId: number, weightGrams: number) =>
  7162. request<{ status: string; weight_used: number }>(`/spoolman/inventory/spools/${spoolId}/weight`, {
  7163. method: 'PATCH',
  7164. body: JSON.stringify({ weight_grams: weightGrams }),
  7165. }),
  7166. // move: as assignSpool's (#1574).
  7167. assignSpoolmanSlot: (data: { spoolman_spool_id: number; printer_id: number; ams_id: number; tray_id: number; move?: boolean }) =>
  7168. request<InventorySpool>('/spoolman/inventory/slot-assignments', {
  7169. method: 'POST',
  7170. body: JSON.stringify(data),
  7171. }),
  7172. unassignSpoolmanSlot: (spoolmanSpoolId: number) =>
  7173. request<InventorySpool>(`/spoolman/inventory/slot-assignments/${spoolmanSpoolId}`, { method: 'DELETE' }),
  7174. getSpoolmanSlotAssignments: (printerId?: number) =>
  7175. request<Array<{
  7176. printer_id: number;
  7177. printer_name: string | null;
  7178. ams_id: number;
  7179. tray_id: number;
  7180. spoolman_spool_id: number;
  7181. ams_label: string | null;
  7182. }>>(
  7183. printerId !== undefined
  7184. ? `/spoolman/inventory/slot-assignments/all?printer_id=${printerId}`
  7185. : '/spoolman/inventory/slot-assignments/all',
  7186. ),
  7187. syncSpoolmanAmsWeights: () =>
  7188. request<{ synced: number; skipped: number; printing?: number }>('/spoolman/inventory/sync-ams-weights', { method: 'POST' }),
  7189. saveSpoolmanKProfiles: (spoolId: number, profiles: SpoolKProfileInput[]) =>
  7190. request<SpoolKProfile[]>(`/spoolman/inventory/spools/${spoolId}/k-profiles`, {
  7191. method: 'PUT',
  7192. body: JSON.stringify(profiles),
  7193. }),
  7194. getSpoolmanFilamentPresets: (spoolId: number) =>
  7195. request<SpoolFilamentPreset[]>(`/spoolman/inventory/spools/${spoolId}/filament-presets`),
  7196. saveSpoolmanFilamentPresets: (spoolId: number, presets: SpoolFilamentPresetInput[]) =>
  7197. request<SpoolFilamentPreset[]>(`/spoolman/inventory/spools/${spoolId}/filament-presets`, {
  7198. method: 'PUT',
  7199. body: JSON.stringify(presets),
  7200. }),
  7201. // Updates
  7202. getVersion: () => request<VersionInfo>('/updates/version'),
  7203. checkForUpdates: () => request<UpdateCheckResult>('/updates/check'),
  7204. applyUpdate: () =>
  7205. request<{ success: boolean; message: string; status?: UpdateStatus; is_docker?: boolean; is_ha_addon?: boolean; is_windows_installer?: boolean }>('/updates/apply', {
  7206. method: 'POST',
  7207. }),
  7208. getUpdateStatus: () => request<UpdateStatus>('/updates/status'),
  7209. // Maintenance
  7210. getMaintenanceTypes: () => request<MaintenanceType[]>('/maintenance/types'),
  7211. createMaintenanceType: (data: MaintenanceTypeCreate) =>
  7212. request<MaintenanceType>('/maintenance/types', {
  7213. method: 'POST',
  7214. body: JSON.stringify(data),
  7215. }),
  7216. updateMaintenanceType: (id: number, data: Partial<MaintenanceTypeCreate>) =>
  7217. request<MaintenanceType>(`/maintenance/types/${id}`, {
  7218. method: 'PATCH',
  7219. body: JSON.stringify(data),
  7220. }),
  7221. deleteMaintenanceType: (id: number) =>
  7222. request<{ status: string }>(`/maintenance/types/${id}`, { method: 'DELETE' }),
  7223. restoreDefaultMaintenanceTypes: () =>
  7224. request<{ restored: number }>(`/maintenance/types/restore-defaults`, { method: 'POST' }),
  7225. getMaintenanceOverview: () => request<PrinterMaintenanceOverview[]>('/maintenance/overview'),
  7226. updateMaintenanceItem: (itemId: number, data: { custom_interval_hours?: number | null; custom_interval_type?: 'hours' | 'days' | null; enabled?: boolean }) =>
  7227. request<MaintenanceStatus>(`/maintenance/items/${itemId}`, {
  7228. method: 'PATCH',
  7229. body: JSON.stringify(data),
  7230. }),
  7231. performMaintenance: (itemId: number, notes?: string) =>
  7232. request<MaintenanceStatus>(`/maintenance/items/${itemId}/perform`, {
  7233. method: 'POST',
  7234. body: JSON.stringify({ notes }),
  7235. }),
  7236. setPrinterHours: (printerId: number, totalHours: number) =>
  7237. request<{ printer_id: number; total_hours: number; archive_hours: number; offset_hours: number }>(
  7238. `/maintenance/printers/${printerId}/hours?total_hours=${totalHours}`,
  7239. { method: 'PATCH' }
  7240. ),
  7241. assignMaintenanceType: (printerId: number, typeId: number) =>
  7242. request<MaintenanceStatus>(`/maintenance/printers/${printerId}/assign/${typeId}`, {
  7243. method: 'POST',
  7244. }),
  7245. removeMaintenanceItem: (itemId: number) =>
  7246. request<{ status: string }>(`/maintenance/items/${itemId}`, {
  7247. method: 'DELETE',
  7248. }),
  7249. // Camera
  7250. getCameraStreamToken: () =>
  7251. request<{ token: string }>('/printers/camera/stream-token', { method: 'POST' }),
  7252. // Media token (#3025) — the credential for thumbnails, plate previews,
  7253. // timelapses, cover images and link icons. Minted behind plain auth rather
  7254. // than camera:view, and identified, so those routes gate on the resource's
  7255. // own permission and ownership instead of on the camera.
  7256. getMediaToken: () => request<{ token: string }>('/auth/media-token', { method: 'POST' }),
  7257. // WebSocket auth (GHSA-r2qv follow-up) — mint a short-lived token for
  7258. // the /ws connection. Browsers can't attach Authorization headers to a
  7259. // WebSocket handshake, so the token rides in the ?token= query param.
  7260. getWebSocketToken: () =>
  7261. request<{ token: string }>('/auth/ws-token', { method: 'POST' }),
  7262. // Connected apps: sign-in to external applications with Bambuddy
  7263. listConnectedApps: () => request<ConnectedApp[]>('/connect/apps'),
  7264. createConnectedApp: (payload: { name: string; redirect_uri: string }) =>
  7265. request<ConnectedApp>('/connect/apps', { method: 'POST', body: JSON.stringify(payload) }),
  7266. updateConnectedApp: (id: number, payload: { name?: string; redirect_uri?: string; enabled?: boolean }) =>
  7267. request<ConnectedApp>(`/connect/apps/${id}`, { method: 'PATCH', body: JSON.stringify(payload) }),
  7268. rotateConnectedAppSecret: (id: number) =>
  7269. request<ConnectedApp>(`/connect/apps/${id}/rotate-secret`, { method: 'POST' }),
  7270. deleteConnectedApp: (id: number) => request<void>(`/connect/apps/${id}`, { method: 'DELETE' }),
  7271. getConnectAuthorizeInfo: (clientId: string, redirectUri: string) =>
  7272. request<ConnectAuthorizeInfo>(
  7273. `/connect/authorize/info?client_id=${encodeURIComponent(clientId)}&redirect_uri=${encodeURIComponent(redirectUri)}`,
  7274. ),
  7275. connectAuthorize: (payload: {
  7276. client_id: string;
  7277. redirect_uri: string;
  7278. code_challenge: string;
  7279. code_challenge_method: 'S256';
  7280. }) =>
  7281. request<{ code: string; redirect_uri: string }>('/connect/authorize', {
  7282. method: 'POST',
  7283. body: JSON.stringify(payload),
  7284. }),
  7285. // Long-lived camera tokens (#1108, #2531)
  7286. createLongLivedCameraToken: (payload: {
  7287. name: string;
  7288. expires_in_days: number;
  7289. scope?: LongLivedTokenScope;
  7290. }) =>
  7291. request<LongLivedCameraToken>('/auth/tokens', {
  7292. method: 'POST',
  7293. body: JSON.stringify({ scope: 'camera_stream', ...payload }),
  7294. }),
  7295. listMyLongLivedCameraTokens: () =>
  7296. request<LongLivedCameraToken[]>('/auth/tokens'),
  7297. listAllLongLivedCameraTokens: () =>
  7298. request<LongLivedCameraToken[]>('/auth/tokens/all'),
  7299. revokeLongLivedCameraToken: (tokenId: number) =>
  7300. request<void>(`/auth/tokens/${tokenId}`, { method: 'DELETE' }),
  7301. // Token-authenticated Cam Wall feed (#2531). `token` is omitted only when
  7302. // auth is disabled, where the backend gate is a no-op anyway.
  7303. getCamWallPrinters: (token?: string) =>
  7304. request<CamWallPrinter[]>(
  7305. token ? `/camwall/printers?token=${encodeURIComponent(token)}` : '/camwall/printers',
  7306. ),
  7307. // Token-authenticated streaming-overlay feed (#2613). OBS (or any embed with
  7308. // no login session) loads /overlay/{id}?token=... and this backs it. `token`
  7309. // is omitted only when auth is disabled, where the backend gate is a no-op.
  7310. getOverlayStatus: (printerId: number, token?: string) =>
  7311. request<OverlayStatus>(
  7312. token
  7313. ? `/printers/${printerId}/overlay-status?token=${encodeURIComponent(token)}`
  7314. : `/printers/${printerId}/overlay-status`,
  7315. ),
  7316. getCameraStatus: (printerId: number) =>
  7317. request<{ active: boolean; stalled: boolean }>(`/printers/${printerId}/camera/status`),
  7318. diagnoseCamera: (printerId: number) =>
  7319. request<CameraDiagnoseResult>(`/printers/${printerId}/camera/diagnose`, { method: 'POST' }),
  7320. diagnosePrinter: (printerId: number) =>
  7321. request<PrinterDiagnosticResult>(`/printers/${printerId}/diagnostic`),
  7322. diagnoseConnection: (body: {
  7323. ip_address: string;
  7324. serial_number?: string;
  7325. access_code?: string;
  7326. }) =>
  7327. request<PrinterDiagnosticResult>('/printers/diagnostic', {
  7328. method: 'POST',
  7329. body: JSON.stringify(body),
  7330. }),
  7331. // Plate Detection - Multi-reference calibration (stores up to 5 references per printer)
  7332. checkPlateEmpty: (printerId: number, options?: { useExternal?: boolean; includeDebugImage?: boolean }) => {
  7333. const params = new URLSearchParams();
  7334. // Only forward use_external when the caller explicitly sets it. Omitted →
  7335. // backend derives the default from the printer's external_camera_enabled
  7336. // setting so calibration and runtime checks use the same camera (#1359).
  7337. if (options?.useExternal !== undefined) {
  7338. params.set('use_external', String(options.useExternal));
  7339. }
  7340. params.set('include_debug_image', String(options?.includeDebugImage ?? false));
  7341. return request<PlateDetectionResult>(
  7342. `/printers/${printerId}/camera/check-plate?${params.toString()}`
  7343. );
  7344. },
  7345. calibratePlateDetection: (printerId: number, options?: { label?: string; useExternal?: boolean }) => {
  7346. const params = new URLSearchParams();
  7347. if (options?.label) params.set('label', options.label);
  7348. if (options?.useExternal !== undefined) {
  7349. params.set('use_external', String(options.useExternal));
  7350. }
  7351. return request<CalibrationResult & { index: number }>(
  7352. `/printers/${printerId}/camera/plate-detection/calibrate?${params.toString()}`,
  7353. { method: 'POST' }
  7354. );
  7355. },
  7356. getPlateReferences: (printerId: number) => {
  7357. return request<{
  7358. references: PlateReference[];
  7359. max_references: number;
  7360. }>(`/printers/${printerId}/camera/plate-detection/references`);
  7361. },
  7362. getPlateReferenceThumbnailUrl: (printerId: number, index: number) =>
  7363. withStreamToken(`${API_BASE}/printers/${printerId}/camera/plate-detection/references/${index}/thumbnail`),
  7364. updatePlateReferenceLabel: (printerId: number, index: number, label: string) => {
  7365. const params = new URLSearchParams();
  7366. params.set('label', label);
  7367. return request<{ success: boolean; index: number; label: string }>(
  7368. `/printers/${printerId}/camera/plate-detection/references/${index}?${params.toString()}`,
  7369. { method: 'PUT' }
  7370. );
  7371. },
  7372. deletePlateReference: (printerId: number, index: number) => {
  7373. return request<{ success: boolean; message: string }>(
  7374. `/printers/${printerId}/camera/plate-detection/references/${index}`,
  7375. { method: 'DELETE' }
  7376. );
  7377. },
  7378. // External Links
  7379. getExternalLinks: () => request<ExternalLink[]>('/external-links/'),
  7380. getExternalLink: (id: number) => request<ExternalLink>(`/external-links/${id}`),
  7381. createExternalLink: (data: ExternalLinkCreate) =>
  7382. request<ExternalLink>('/external-links/', {
  7383. method: 'POST',
  7384. body: JSON.stringify(data),
  7385. }),
  7386. updateExternalLink: (id: number, data: ExternalLinkUpdate) =>
  7387. request<ExternalLink>(`/external-links/${id}`, {
  7388. method: 'PATCH',
  7389. body: JSON.stringify(data),
  7390. }),
  7391. deleteExternalLink: (id: number) =>
  7392. request<{ message: string }>(`/external-links/${id}`, { method: 'DELETE' }),
  7393. uploadExternalLinkIcon: async (id: number, file: File): Promise<ExternalLink> => {
  7394. const formData = new FormData();
  7395. formData.append('file', file);
  7396. const headers: Record<string, string> = {};
  7397. if (authToken) {
  7398. headers['Authorization'] = `Bearer ${authToken}`;
  7399. }
  7400. const response = await fetch(`${API_BASE}/external-links/${id}/icon`, {
  7401. method: 'POST',
  7402. headers,
  7403. body: formData,
  7404. });
  7405. if (!response.ok) {
  7406. const error = await response.json().catch(() => ({}));
  7407. throw new Error(error.detail || `HTTP ${response.status}`);
  7408. }
  7409. return response.json();
  7410. },
  7411. deleteExternalLinkIcon: (id: number) =>
  7412. request<ExternalLink>(`/external-links/${id}/icon`, { method: 'DELETE' }),
  7413. getExternalLinkIconUrl: (id: number) => withMediaToken(`${API_BASE}/external-links/${id}/icon`),
  7414. // Projects
  7415. getProjects: (status?: string) => {
  7416. const params = new URLSearchParams();
  7417. if (status) params.set('status', status);
  7418. return request<ProjectListItem[]>(`/projects/?${params}`);
  7419. },
  7420. getProject: (id: number) => request<Project>(`/projects/${id}`),
  7421. createProject: (data: ProjectCreate) =>
  7422. request<Project>('/projects/', {
  7423. method: 'POST',
  7424. body: JSON.stringify(data),
  7425. }),
  7426. updateProject: (id: number, data: ProjectUpdate) =>
  7427. request<Project>(`/projects/${id}`, {
  7428. method: 'PATCH',
  7429. body: JSON.stringify(data),
  7430. }),
  7431. deleteProject: (id: number) =>
  7432. request<{ message: string }>(`/projects/${id}`, { method: 'DELETE' }),
  7433. getProjectArchives: (id: number, limit = 100, offset = 0) =>
  7434. request<Archive[]>(`/projects/${id}/archives?limit=${limit}&offset=${offset}`),
  7435. // Completed-run counts per library file (#1897); files with 0 runs are omitted
  7436. getProjectFileProgress: (id: number) =>
  7437. request<ProjectFileProgress[]>(`/projects/${id}/file-progress`),
  7438. addArchivesToProject: (projectId: number, archiveIds: number[]) =>
  7439. request<{ message: string; count: number }>(`/projects/${projectId}/add-archives`, {
  7440. method: 'POST',
  7441. body: JSON.stringify({ archive_ids: archiveIds }),
  7442. }),
  7443. // #1155: Cover image
  7444. // Browsers can't attach `Authorization: Bearer ...` to `<img src>`, so we
  7445. // append the stream-token query string the same way archive thumbnails do.
  7446. // `version` cache-busts the browser copy after a re-upload. It has to go on
  7447. // before the token does: callers used to append their own `?v=` to the
  7448. // returned URL, which already ended in `?token=…`, so the second `?` landed
  7449. // inside the token value and the image 401'd whenever auth was enabled.
  7450. getProjectCoverImageUrl: (projectId: number, version?: string | number) =>
  7451. withMediaToken(
  7452. `${API_BASE}/projects/${projectId}/cover-image${
  7453. version === undefined ? '' : `?v=${encodeURIComponent(String(version))}`
  7454. }`
  7455. ),
  7456. uploadProjectCoverImage: async (
  7457. projectId: number,
  7458. file: File
  7459. ): Promise<{ status: string; filename: string; size: number }> => {
  7460. const formData = new FormData();
  7461. formData.append('file', file);
  7462. const headers: Record<string, string> = {};
  7463. if (authToken) {
  7464. headers['Authorization'] = `Bearer ${authToken}`;
  7465. }
  7466. const response = await fetch(`${API_BASE}/projects/${projectId}/cover-image`, {
  7467. method: 'POST',
  7468. headers,
  7469. body: formData,
  7470. });
  7471. if (!response.ok) {
  7472. const error = await response.json().catch(() => ({}));
  7473. throw new Error(error.detail || `HTTP ${response.status}`);
  7474. }
  7475. return response.json();
  7476. },
  7477. deleteProjectCoverImage: (projectId: number) =>
  7478. request<{ status: string }>(`/projects/${projectId}/cover-image`, { method: 'DELETE' }),
  7479. // BOM (Bill of Materials)
  7480. getProjectBOM: (projectId: number) =>
  7481. request<BOMItem[]>(`/projects/${projectId}/bom`),
  7482. createBOMItem: (projectId: number, data: BOMItemCreate) =>
  7483. request<BOMItem>(`/projects/${projectId}/bom`, {
  7484. method: 'POST',
  7485. body: JSON.stringify(data),
  7486. }),
  7487. updateBOMItem: (projectId: number, itemId: number, data: BOMItemUpdate) =>
  7488. request<BOMItem>(`/projects/${projectId}/bom/${itemId}`, {
  7489. method: 'PATCH',
  7490. body: JSON.stringify(data),
  7491. }),
  7492. deleteBOMItem: (projectId: number, itemId: number) =>
  7493. request<{ status: string; message: string }>(`/projects/${projectId}/bom/${itemId}`, {
  7494. method: 'DELETE',
  7495. }),
  7496. // Templates
  7497. getTemplates: () => request<ProjectListItem[]>('/projects/templates/'),
  7498. createTemplateFromProject: (projectId: number) =>
  7499. request<Project>(`/projects/${projectId}/create-template`, { method: 'POST' }),
  7500. createProjectFromTemplate: (templateId: number, name?: string) =>
  7501. request<Project>(`/projects/from-template/${templateId}${name ? `?name=${encodeURIComponent(name)}` : ''}`, {
  7502. method: 'POST',
  7503. }),
  7504. // Timeline
  7505. getProjectTimeline: (projectId: number, limit = 50) =>
  7506. request<TimelineEvent[]>(`/projects/${projectId}/timeline?limit=${limit}`),
  7507. // Project Export/Import
  7508. exportProjectJson: (projectId: number) =>
  7509. request<ProjectExport>(`/projects/${projectId}/export?format=json`),
  7510. importProject: (data: ProjectImport) =>
  7511. request<Project>('/projects/import', {
  7512. method: 'POST',
  7513. body: JSON.stringify(data),
  7514. }),
  7515. importProjectFile: async (file: File): Promise<Project> => {
  7516. const formData = new FormData();
  7517. formData.append('file', file);
  7518. const headers: Record<string, string> = {};
  7519. if (authToken) {
  7520. headers['Authorization'] = `Bearer ${authToken}`;
  7521. }
  7522. const response = await fetch(`${API_BASE}/projects/import/file`, {
  7523. method: 'POST',
  7524. headers,
  7525. body: formData,
  7526. });
  7527. if (!response.ok) {
  7528. const error = await response.json().catch(() => ({}));
  7529. throw new Error(error.detail || `HTTP ${response.status}`);
  7530. }
  7531. return response.json();
  7532. },
  7533. exportProjectZip: async (projectId: number): Promise<{ blob: Blob; filename: string }> => {
  7534. const headers: Record<string, string> = {};
  7535. if (authToken) {
  7536. headers['Authorization'] = `Bearer ${authToken}`;
  7537. }
  7538. const response = await fetch(`${API_BASE}/projects/${projectId}/export`, {
  7539. headers,
  7540. });
  7541. if (!response.ok) {
  7542. const error = await response.json().catch(() => ({}));
  7543. throw new Error(error.detail || `HTTP ${response.status}`);
  7544. }
  7545. const contentDisposition = response.headers.get('Content-Disposition');
  7546. const filename = parseContentDispositionFilename(contentDisposition) || `project_${projectId}.zip`;
  7547. const blob = await response.blob();
  7548. return { blob, filename };
  7549. },
  7550. // API Keys
  7551. getAPIKeys: () => request<APIKey[]>('/api-keys/'),
  7552. createAPIKey: (data: APIKeyCreate) =>
  7553. request<APIKeyCreateResponse>('/api-keys/', {
  7554. method: 'POST',
  7555. body: JSON.stringify(data),
  7556. }),
  7557. deleteAPIKey: (id: number) =>
  7558. request<{ message: string }>(`/api-keys/${id}`, { method: 'DELETE' }),
  7559. // AMS History
  7560. getAMSHistory: (printerId: number, amsId: number, hours = 24) =>
  7561. request<AMSHistoryResponse>(`/ams-history/${printerId}/${amsId}?hours=${hours}`),
  7562. // Printer heater (nozzle / bed / chamber) sensor history
  7563. getPrinterSensorHistory: (printerId: number, hours = 24, kinds?: string[]) => {
  7564. const params = new URLSearchParams({ hours: String(hours) });
  7565. if (kinds && kinds.length > 0) params.set('kinds', kinds.join(','));
  7566. return request<PrinterSensorHistoryResponse>(`/printer-sensor-history/${printerId}?${params.toString()}`);
  7567. },
  7568. // System Info
  7569. getSystemInfo: () => request<SystemInfo>('/system/info'),
  7570. getSystemHealth: () => request<SystemHealthResult>('/system/health'),
  7571. getStorageUsage: (options?: { refresh?: boolean }) => {
  7572. const params = new URLSearchParams();
  7573. if (options?.refresh) {
  7574. params.set('refresh', 'true');
  7575. }
  7576. const query = params.toString();
  7577. return request<StorageUsageResponse>(`/system/storage-usage${query ? `?${query}` : ''}`);
  7578. },
  7579. // Library (File Manager)
  7580. getLibraryFolders: () => request<LibraryFolderTree[]>('/library/folders'),
  7581. createLibraryFolder: (data: LibraryFolderCreate) =>
  7582. request<LibraryFolder>('/library/folders', {
  7583. method: 'POST',
  7584. body: JSON.stringify(data),
  7585. }),
  7586. updateLibraryFolder: (id: number, data: LibraryFolderUpdate) =>
  7587. request<LibraryFolder>(`/library/folders/${id}`, {
  7588. method: 'PUT',
  7589. body: JSON.stringify(data),
  7590. }),
  7591. deleteLibraryFolder: (id: number) =>
  7592. request<{ status: string; message: string }>(`/library/folders/${id}`, { method: 'DELETE' }),
  7593. createExternalFolder: (data: ExternalFolderCreate) =>
  7594. request<LibraryFolder>('/library/folders/external', {
  7595. method: 'POST',
  7596. body: JSON.stringify(data),
  7597. }),
  7598. scanExternalFolder: (folderId: number) =>
  7599. request<{ status: string; added: number; removed: number }>(`/library/folders/${folderId}/scan`, {
  7600. method: 'POST',
  7601. }),
  7602. getLibraryFoldersByProject: (projectId: number) =>
  7603. request<LibraryFolder[]>(`/library/folders/by-project/${projectId}`),
  7604. getLibraryFoldersByArchive: (archiveId: number) => foldersByArchiveBatch(archiveId),
  7605. getLibraryFiles: (
  7606. folderId?: number | null,
  7607. includeRoot = true,
  7608. projectId?: number,
  7609. scope?: 'internal' | 'external',
  7610. recursive = false,
  7611. tagIds: number[] = [],
  7612. ) => {
  7613. const params = new URLSearchParams();
  7614. if (folderId !== undefined && folderId !== null) {
  7615. params.set('folder_id', String(folderId));
  7616. }
  7617. if (projectId !== undefined) {
  7618. params.set('project_id', String(projectId));
  7619. }
  7620. params.set('include_root', String(includeRoot));
  7621. if (scope === 'internal') params.set('internal_only', 'true');
  7622. else if (scope === 'external') params.set('external_only', 'true');
  7623. // recursive=true expands the folder_id filter to include every descendant
  7624. // folder (#1268). Only meaningful when folder_id is set; ignored server-side
  7625. // otherwise. Off by default so non-search callers keep folder-scoped behavior.
  7626. if (recursive) params.set('recursive', 'true');
  7627. // Tag filter (#1268). Repeated ?tag_ids=N&tag_ids=M form for AND semantics
  7628. // — backend joins the association table and HAVING COUNT(DISTINCT) matches
  7629. // the array length. Tag filter intentionally bypasses folder scoping
  7630. // server-side (cross-cutting design decision).
  7631. for (const tagId of tagIds) {
  7632. params.append('tag_ids', String(tagId));
  7633. }
  7634. return request<LibraryFileListItem[]>(`/library/files?${params}`);
  7635. },
  7636. getLibraryFolderReadme: (folderId: number) =>
  7637. request<{ filename: string; content: string; truncated: boolean }>(
  7638. `/library/folders/${folderId}/readme`,
  7639. ),
  7640. // ============ Library tag catalog (#1268) ============
  7641. getLibraryTags: () =>
  7642. request<LibraryTag[]>('/library/tags'),
  7643. createLibraryTag: (name: string) =>
  7644. request<LibraryTag>('/library/tags', {
  7645. method: 'POST',
  7646. body: JSON.stringify({ name }),
  7647. }),
  7648. updateLibraryTag: (id: number, name: string) =>
  7649. request<LibraryTag>(`/library/tags/${id}`, {
  7650. method: 'PATCH',
  7651. body: JSON.stringify({ name }),
  7652. }),
  7653. deleteLibraryTag: (id: number) =>
  7654. request<void>(`/library/tags/${id}`, { method: 'DELETE' }),
  7655. bulkAssignLibraryTags: (
  7656. fileIds: number[],
  7657. tagIds: number[],
  7658. action: 'add' | 'remove' | 'replace',
  7659. ) =>
  7660. request<LibraryTagBulkAssignResult>('/library/tags/bulk-assign', {
  7661. method: 'POST',
  7662. body: JSON.stringify({ file_ids: fileIds, tag_ids: tagIds, action }),
  7663. }),
  7664. // ============ Variant groups (#671 / #2570) ============
  7665. // "These files are the same job sliced for different printers." Consumed from
  7666. // both ends: the queue picks a printer and needs the matching file, the File
  7667. // Manager's print action has the printer and needs the same match.
  7668. createVariantGroup: (
  7669. members: { library_file_id: number; target_model?: string }[],
  7670. name?: string,
  7671. ) =>
  7672. request<VariantGroup>('/library/variant-groups', {
  7673. method: 'POST',
  7674. body: JSON.stringify({ members, ...(name ? { name } : {}) }),
  7675. }),
  7676. getVariantGroup: (groupId: number) =>
  7677. request<VariantGroup>(`/library/variant-groups/${groupId}`),
  7678. getLibraryFile: (id: number) => request<LibraryFile>(`/library/files/${id}`),
  7679. uploadLibraryFile: async (
  7680. file: File,
  7681. folderId?: number | null,
  7682. generateStlThumbnails: boolean = true
  7683. ): Promise<LibraryFileUploadResponse> => {
  7684. const formData = new FormData();
  7685. formData.append('file', file);
  7686. const params = new URLSearchParams();
  7687. if (folderId) params.set('folder_id', String(folderId));
  7688. params.set('generate_stl_thumbnails', String(generateStlThumbnails));
  7689. const headers: Record<string, string> = {};
  7690. if (authToken) {
  7691. headers['Authorization'] = `Bearer ${authToken}`;
  7692. }
  7693. const response = await fetch(`${API_BASE}/library/files?${params}`, {
  7694. method: 'POST',
  7695. headers,
  7696. body: formData,
  7697. });
  7698. if (!response.ok) {
  7699. const error = await response.json().catch(() => ({}));
  7700. throw new Error(error.detail || `HTTP ${response.status}`);
  7701. }
  7702. return response.json();
  7703. },
  7704. extractZipFile: async (
  7705. file: File,
  7706. folderId?: number | null,
  7707. preserveStructure: boolean = true,
  7708. createFolderFromZip: boolean = false,
  7709. generateStlThumbnails: boolean = true
  7710. ): Promise<ZipExtractResponse> => {
  7711. const formData = new FormData();
  7712. formData.append('file', file);
  7713. const params = new URLSearchParams();
  7714. if (folderId) params.set('folder_id', String(folderId));
  7715. params.set('preserve_structure', String(preserveStructure));
  7716. params.set('create_folder_from_zip', String(createFolderFromZip));
  7717. params.set('generate_stl_thumbnails', String(generateStlThumbnails));
  7718. const headers: Record<string, string> = {};
  7719. if (authToken) {
  7720. headers['Authorization'] = `Bearer ${authToken}`;
  7721. }
  7722. const response = await fetch(`${API_BASE}/library/files/extract-zip?${params}`, {
  7723. method: 'POST',
  7724. headers,
  7725. body: formData,
  7726. });
  7727. if (!response.ok) {
  7728. const error = await response.json().catch(() => ({}));
  7729. throw new Error(error.detail || `HTTP ${response.status}`);
  7730. }
  7731. return response.json();
  7732. },
  7733. updateLibraryFile: (id: number, data: LibraryFileUpdate) =>
  7734. request<LibraryFile>(`/library/files/${id}`, {
  7735. method: 'PUT',
  7736. body: JSON.stringify(data),
  7737. }),
  7738. deleteLibraryFile: (id: number) =>
  7739. request<{ status: string; message: string; trashed: boolean }>(`/library/files/${id}`, { method: 'DELETE' }),
  7740. // ========== Library Trash (#1008) ==========
  7741. previewLibraryPurge: (olderThanDays: number, includeNeverPrinted: boolean = true) =>
  7742. request<LibraryPurgePreview>(
  7743. `/library/purge/preview?older_than_days=${olderThanDays}&include_never_printed=${includeNeverPrinted}`,
  7744. ),
  7745. executeLibraryPurge: (olderThanDays: number, includeNeverPrinted: boolean = true) =>
  7746. request<{ moved_to_trash: number }>('/library/purge', {
  7747. method: 'POST',
  7748. body: JSON.stringify({ older_than_days: olderThanDays, include_never_printed: includeNeverPrinted }),
  7749. }),
  7750. listLibraryTrash: (limit: number = 100, offset: number = 0) =>
  7751. request<LibraryTrashListResponse>(`/library/trash?limit=${limit}&offset=${offset}`),
  7752. restoreLibraryTrash: (fileId: number) =>
  7753. request<{ status: string; id: number }>(`/library/trash/${fileId}/restore`, { method: 'POST' }),
  7754. hardDeleteLibraryTrash: (fileId: number) =>
  7755. request<{ status: string }>(`/library/trash/${fileId}`, { method: 'DELETE' }),
  7756. emptyLibraryTrash: () => request<{ deleted: number }>('/library/trash', { method: 'DELETE' }),
  7757. getLibraryTrashSettings: () =>
  7758. request<LibraryTrashSettings>('/library/trash/settings'),
  7759. updateLibraryTrashSettings: (body: LibraryTrashSettings) =>
  7760. request<LibraryTrashSettings>('/library/trash/settings', {
  7761. method: 'PUT',
  7762. body: JSON.stringify(body),
  7763. }),
  7764. getLibraryFileDownloadUrl: (id: number) => `${API_BASE}/library/files/${id}/download`,
  7765. createLibrarySlicerToken: (fileId: number) =>
  7766. request<{ token: string }>(`/library/files/${fileId}/slicer-token`, { method: 'POST' }),
  7767. getLibrarySlicerDownloadUrl: (fileId: number, token: string, filename: string) =>
  7768. `${API_BASE}/library/files/${fileId}/dl/${token}/${encodeURIComponent(buildSlicerUrlFilename(filename))}`,
  7769. downloadLibraryFile: async (id: number, filename?: string): Promise<void> => {
  7770. const headers: Record<string, string> = {};
  7771. if (authToken) {
  7772. headers['Authorization'] = `Bearer ${authToken}`;
  7773. }
  7774. const response = await fetch(`${API_BASE}/library/files/${id}/download`, { headers });
  7775. if (!response.ok) {
  7776. const error = await response.json().catch(() => ({}));
  7777. throw new Error(error.detail || `HTTP ${response.status}`);
  7778. }
  7779. const disposition = response.headers.get('Content-Disposition');
  7780. const downloadFilename = parseContentDispositionFilename(disposition) || filename || `file_${id}`;
  7781. const blob = await response.blob();
  7782. const url = window.URL.createObjectURL(blob);
  7783. const a = document.createElement('a');
  7784. a.href = url;
  7785. a.download = downloadFilename;
  7786. document.body.appendChild(a);
  7787. a.click();
  7788. document.body.removeChild(a);
  7789. window.URL.revokeObjectURL(url);
  7790. },
  7791. getLibraryFileThumbnailUrl: (id: number) => withMediaToken(`${API_BASE}/library/files/${id}/thumbnail`),
  7792. // Client-rendered preview thumbnail upload (#2976). STEP/PDF/spreadsheet
  7793. // previews render in the browser; the first render is posted back so the
  7794. // grid gets a thumbnail without a server-side renderer for those formats.
  7795. uploadLibraryPreviewThumbnail: async (fileId: number, thumbnail: Blob): Promise<{ updated: boolean }> => {
  7796. const formData = new FormData();
  7797. formData.append('thumbnail', thumbnail, 'preview.png');
  7798. const headers: Record<string, string> = {};
  7799. if (authToken) {
  7800. headers['Authorization'] = `Bearer ${authToken}`;
  7801. }
  7802. const response = await fetch(`${API_BASE}/library/files/${fileId}/preview-thumbnail`, {
  7803. method: 'POST',
  7804. headers,
  7805. body: formData,
  7806. });
  7807. if (!response.ok) {
  7808. const error = await response.json().catch(() => ({}));
  7809. throw new Error(error.detail || `HTTP ${response.status}`);
  7810. }
  7811. return response.json();
  7812. },
  7813. getLibraryFilePlateThumbnail: (id: number, plateIndex: number) =>
  7814. withMediaToken(`${API_BASE}/library/files/${id}/plate-thumbnail/${plateIndex}`),
  7815. // Photos of the printed result (#3077) — same shape as the archive photo API.
  7816. getLibraryFilePhotoUrl: (fileId: number, filename: string) =>
  7817. withMediaToken(`${API_BASE}/library/files/${fileId}/photos/${encodeURIComponent(filename)}`),
  7818. uploadLibraryFilePhoto: async (fileId: number, file: File): Promise<{ status: string; filename: string; photos: string[] }> => {
  7819. const formData = new FormData();
  7820. formData.append('file', file);
  7821. const headers: Record<string, string> = {};
  7822. if (authToken) {
  7823. headers['Authorization'] = `Bearer ${authToken}`;
  7824. }
  7825. const response = await fetch(`${API_BASE}/library/files/${fileId}/photos`, {
  7826. method: 'POST',
  7827. headers,
  7828. body: formData,
  7829. });
  7830. if (!response.ok) {
  7831. const error = await response.json().catch(() => ({}));
  7832. throw new Error(error.detail || `HTTP ${response.status}`);
  7833. }
  7834. return response.json();
  7835. },
  7836. deleteLibraryFilePhoto: (fileId: number, filename: string) =>
  7837. request<{ status: string; photos: string[] }>(`/library/files/${fileId}/photos/${encodeURIComponent(filename)}`, {
  7838. method: 'DELETE',
  7839. }),
  7840. getLibraryFileGcodeUrl: (id: number) => `${API_BASE}/library/files/${id}/gcode`,
  7841. moveLibraryFiles: (fileIds: number[], folderId: number | null) =>
  7842. request<{ status: string; moved: number }>('/library/files/move', {
  7843. method: 'POST',
  7844. body: JSON.stringify({ file_ids: fileIds, folder_id: folderId }),
  7845. }),
  7846. bulkDeleteLibrary: (fileIds: number[], folderIds: number[]) =>
  7847. request<{ deleted_files: number; deleted_folders: number }>('/library/bulk-delete', {
  7848. method: 'POST',
  7849. body: JSON.stringify({ file_ids: fileIds, folder_ids: folderIds }),
  7850. }),
  7851. getLibraryStats: () => request<LibraryStats>('/library/stats'),
  7852. batchGenerateStlThumbnails: (options: {
  7853. file_ids?: number[];
  7854. folder_id?: number;
  7855. all_missing?: boolean;
  7856. }) =>
  7857. request<BatchThumbnailResponse>('/library/generate-stl-thumbnails', {
  7858. method: 'POST',
  7859. body: JSON.stringify(options),
  7860. }),
  7861. combineLibraryFiles: (items: { file_id: number; copies: number }[], filename: string, folderId: number | null) =>
  7862. request<LibraryFileUploadResponse>('/library/files/combine', {
  7863. method: 'POST',
  7864. body: JSON.stringify({ items, filename, folder_id: folderId }),
  7865. }),
  7866. getLibraryFilePlates: (fileId: number) =>
  7867. request<LibraryFilePlatesResponse>(`/library/files/${fileId}/plates`),
  7868. getLibraryFileFilamentRequirements: (
  7869. fileId: number,
  7870. plateId?: number,
  7871. requestId?: string,
  7872. /** Ask for one entry per project slot instead of only the slots this
  7873. * plate consumes. The slice modal needs it: its filament list is
  7874. * positional, so a source whose only used slot is 4 must still present
  7875. * four rows or the user's pick is bound to slot 1 (#2712). Print-time
  7876. * AMS matching must NOT set this — it wants the used-only list. */
  7877. fullSlots?: boolean,
  7878. ) => {
  7879. const qs = new URLSearchParams();
  7880. if (plateId !== undefined) qs.set('plate_id', String(plateId));
  7881. if (requestId) qs.set('request_id', requestId);
  7882. if (fullSlots) qs.set('full_slots', 'true');
  7883. return request<{
  7884. file_id: number;
  7885. filename: string;
  7886. filaments: Array<{
  7887. slot_id: number;
  7888. type: string;
  7889. color: string;
  7890. used_grams: number;
  7891. used_meters: number;
  7892. used_in_plate?: boolean;
  7893. }>;
  7894. }>(`/library/files/${fileId}/filament-requirements${qs.toString() ? `?${qs}` : ''}`);
  7895. },
  7896. /** Poll the sidecar's per-request progress snapshot via the Bambuddy
  7897. * proxy. Used by the SliceModal's filament-discovery path so the inline
  7898. * spinner + persistent toast can show "Generating G-code (45%)" while
  7899. * the preview slice runs. Returns null on 404 (sidecar doesn't yet
  7900. * have an entry — early race window — or it expired) so the poller
  7901. * can keep trying. */
  7902. getPreviewSliceProgress: async (requestId: string): Promise<SliceJobProgress | null> => {
  7903. try {
  7904. return await request<SliceJobProgress>(`/slicer/preview-progress/${encodeURIComponent(requestId)}`);
  7905. } catch {
  7906. return null;
  7907. }
  7908. },
  7909. // GitHub Backup
  7910. getGitHubBackupConfig: () =>
  7911. request<GitHubBackupConfig | null>('/github-backup/config'),
  7912. getGitHubBackupCloudAccounts: () =>
  7913. request<CloudAccountCounts>('/github-backup/cloud-accounts'),
  7914. saveGitHubBackupConfig: (config: GitHubBackupConfigCreate) =>
  7915. request<GitHubBackupConfig>('/github-backup/config', {
  7916. method: 'POST',
  7917. body: JSON.stringify(config),
  7918. }),
  7919. updateGitHubBackupConfig: (config: Partial<GitHubBackupConfigCreate>) =>
  7920. request<GitHubBackupConfig>('/github-backup/config', {
  7921. method: 'PATCH',
  7922. body: JSON.stringify(config),
  7923. }),
  7924. testGitHubConnection: (repoUrl: string, token: string, provider: GitProviderType = 'github') =>
  7925. request<GitHubTestConnectionResponse>('/github-backup/test', {
  7926. method: 'POST',
  7927. body: JSON.stringify({ repo_url: repoUrl, token, provider }),
  7928. }),
  7929. testGitHubStoredConnection: () =>
  7930. request<GitHubTestConnectionResponse>('/github-backup/test-stored', { method: 'POST' }),
  7931. triggerGitHubBackup: () =>
  7932. request<GitHubBackupTriggerResponse>('/github-backup/run', { method: 'POST' }),
  7933. getGitHubBackupStatus: () =>
  7934. request<GitHubBackupStatus>('/github-backup/status'),
  7935. getGitHubBackupLogs: (limit: number = 50) =>
  7936. request<GitHubBackupLog[]>(`/github-backup/logs?limit=${limit}`),
  7937. clearGitHubBackupLogs: (keepLast: number = 10) =>
  7938. request<{ deleted: number; message: string }>(`/github-backup/logs?keep_last=${keepLast}`, { method: 'DELETE' }),
  7939. // Restore from a Git backup (#2656)
  7940. getGitHubBackupCommits: (limit: number = 20) =>
  7941. request<GitHubCommitListResponse>(`/github-backup/commits?limit=${limit}`),
  7942. getGitHubRestorePreview: (ref: string = 'HEAD') =>
  7943. request<GitHubRestorePreview>(`/github-backup/restore/preview?ref=${encodeURIComponent(ref)}`),
  7944. restoreFromGitHub: (payload: GitHubRestoreRequest) =>
  7945. request<GitHubRestoreResponse>('/github-backup/restore', {
  7946. method: 'POST',
  7947. body: JSON.stringify(payload),
  7948. }),
  7949. // Scheduled local backups
  7950. getLocalBackupStatus: () =>
  7951. request<LocalBackupStatus>('/local-backup/status'),
  7952. triggerLocalBackup: () =>
  7953. request<{ success: boolean; message: string; filename?: string }>('/local-backup/run', { method: 'POST' }),
  7954. checkLocalBackupPath: () =>
  7955. request<LocalBackupPathCheck>('/local-backup/path-check'),
  7956. getLocalBackups: () =>
  7957. request<LocalBackupFile[]>('/local-backup/backups'),
  7958. downloadLocalBackup: async (filename: string): Promise<{ blob: Blob; filename: string }> => {
  7959. const response = await fetch(`${API_BASE}/local-backup/backups/${encodeURIComponent(filename)}/download`, {
  7960. headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {},
  7961. });
  7962. if (!response.ok) throw new Error('Download failed');
  7963. const blob = await response.blob();
  7964. return { blob, filename };
  7965. },
  7966. restoreLocalBackup: (filename: string) =>
  7967. request<{ success: boolean; message: string }>(`/local-backup/backups/${encodeURIComponent(filename)}/restore`, { method: 'POST' }),
  7968. deleteLocalBackup: (filename: string) =>
  7969. request<{ success: boolean; message: string }>(`/local-backup/backups/${encodeURIComponent(filename)}`, { method: 'DELETE' }),
  7970. // Obico AI failure detection
  7971. getObicoStatus: () =>
  7972. request<ObicoStatus>('/obico/status'),
  7973. getObicoPrinterStatus: () =>
  7974. request<ObicoPrinterStatus>('/obico/printer-status'),
  7975. // `token` is sent as-is, so an empty string tests with no token at all.
  7976. // Omitting the argument makes the backend fall back to the saved token.
  7977. testObicoConnection: (url: string, token?: string) =>
  7978. request<ObicoTestConnection>('/obico/test-connection', {
  7979. method: 'POST',
  7980. body: JSON.stringify(token === undefined ? { url } : { url, token }),
  7981. }),
  7982. // OctoEverywhere AI failure detection
  7983. getOctoEverywhereStatus: () =>
  7984. request<OctoEverywhereStatus>('/octoeverywhere/status'),
  7985. getOctoEverywherePrinterStatus: () =>
  7986. request<OctoEverywherePrinterStatus>('/octoeverywhere/printer-status'),
  7987. // An omitted key uses the saved key; an explicit empty key is rejected.
  7988. testOctoEverywhereConnection: (apiKey?: string, confidence?: OctoEverywhereConfidence) =>
  7989. request<OctoEverywhereTestConnection>('/octoeverywhere/test-connection', {
  7990. method: 'POST',
  7991. body: JSON.stringify({ api_key: apiKey, confidence }),
  7992. }),
  7993. // Slicer API — slice in the background. Both endpoints return 202 + a
  7994. // job_id; poll /slice-jobs/{id} until status is `completed` or `failed`.
  7995. sliceLibraryFile: (fileId: number, body: SliceRequest) =>
  7996. request<SliceJobEnqueueResponse>(`/library/files/${fileId}/slice`, {
  7997. method: 'POST',
  7998. body: JSON.stringify(body),
  7999. }),
  8000. sliceArchive: (archiveId: number, body: SliceRequest) =>
  8001. request<SliceJobEnqueueResponse>(`/archives/${archiveId}/slice`, {
  8002. method: 'POST',
  8003. body: JSON.stringify(body),
  8004. }),
  8005. getSliceJob: (jobId: number) =>
  8006. request<SliceJobState>(`/slice-jobs/${jobId}`),
  8007. // Unified slicer-preset listing — cloud + local + standard, deduped by name.
  8008. // Used by the SliceModal; see UnifiedPresetsResponse for the shape and
  8009. // backend/app/api/routes/slicer_presets.py for the priority rules.
  8010. // `refresh` bypasses the in-process cloud and bundled-preset caches on the
  8011. // backend; the SliceModal's Refresh button passes true so a preset deleted
  8012. // in Bambu Studio or Bambu Handy shows up without the 5-min TTL wait.
  8013. getSlicerPresets: (options?: { refresh?: boolean }) =>
  8014. request<UnifiedPresetsResponse>(
  8015. options?.refresh ? '/slicer/presets?refresh=true' : '/slicer/presets',
  8016. ),
  8017. // Slicer Pipelines (#1425) — preset bundles the SliceModal can apply in
  8018. // one click. CRUD is gated on PIPELINES_READ / PIPELINES_WRITE.
  8019. listSlicerPipelines: () =>
  8020. request<SlicerPipelinesListResponse>('/slicer-pipelines/'),
  8021. createSlicerPipeline: (data: SlicerPipelineCreateRequest) =>
  8022. request<SlicerPipeline>('/slicer-pipelines/', {
  8023. method: 'POST',
  8024. body: JSON.stringify(data),
  8025. }),
  8026. updateSlicerPipeline: (id: number, data: SlicerPipelineUpdateRequest) =>
  8027. request<SlicerPipeline>(`/slicer-pipelines/${id}`, {
  8028. method: 'PUT',
  8029. body: JSON.stringify(data),
  8030. }),
  8031. deleteSlicerPipeline: (id: number) =>
  8032. request<void>(`/slicer-pipelines/${id}`, { method: 'DELETE' }),
  8033. checkPipelineEligibility: (
  8034. pipelineId: number,
  8035. source: { kind: 'libraryFile'; id: number } | { kind: 'archive'; id: number },
  8036. ) =>
  8037. request<PipelineEligibilityReport>(`/slicer-pipelines/${pipelineId}/check-eligibility`, {
  8038. method: 'POST',
  8039. body: JSON.stringify(
  8040. source.kind === 'libraryFile'
  8041. ? { source_library_file_id: source.id }
  8042. : { source_archive_id: source.id },
  8043. ),
  8044. }),
  8045. runPipeline: (
  8046. pipelineId: number,
  8047. source: { kind: 'libraryFile'; id: number } | { kind: 'archive'; id: number },
  8048. force = false,
  8049. copies = 1,
  8050. ) =>
  8051. request<PipelineRun>(`/slicer-pipelines/${pipelineId}/run`, {
  8052. method: 'POST',
  8053. body: JSON.stringify({
  8054. ...(source.kind === 'libraryFile'
  8055. ? { source_library_file_id: source.id }
  8056. : { source_archive_id: source.id }),
  8057. force,
  8058. copies,
  8059. }),
  8060. }),
  8061. listPipelineRuns: (pipelineId: number, limit = 5) =>
  8062. request<PipelineRunListResponse>(
  8063. `/slicer-pipelines/${pipelineId}/runs?limit=${limit}`,
  8064. ),
  8065. // Dashboard list across all pipelines (#1425 PR C).
  8066. listAllPipelineRuns: (params: {
  8067. limit?: number;
  8068. offset?: number;
  8069. pipelineId?: number;
  8070. status?: string;
  8071. targetPrinterId?: number;
  8072. targetModelClass?: string;
  8073. } = {}) => {
  8074. const search = new URLSearchParams();
  8075. if (params.limit) search.set('limit', String(params.limit));
  8076. if (params.offset) search.set('offset', String(params.offset));
  8077. if (params.pipelineId) search.set('pipeline_id', String(params.pipelineId));
  8078. if (params.status) search.set('status', params.status);
  8079. if (params.targetPrinterId) search.set('target_printer_id', String(params.targetPrinterId));
  8080. if (params.targetModelClass) search.set('target_model_class', params.targetModelClass);
  8081. const q = search.toString();
  8082. return request<PipelineRunListResponse>(
  8083. `/pipeline-runs${q ? '?' + q : ''}`,
  8084. );
  8085. },
  8086. // Clear terminal pipeline runs (#1425 PR C polish). Deletes all runs in
  8087. // a terminal state (completed/failed/cancelled/partial_failure); in-flight
  8088. // runs are preserved.
  8089. clearTerminalPipelineRuns: () =>
  8090. request<{ deleted: number }>('/pipeline-runs/clear', { method: 'POST' }),
  8091. cancelPipelineRun: (runId: number) =>
  8092. request<PipelineRun>(`/pipeline-runs/${runId}/cancel`, { method: 'POST' }),
  8093. retryFailedPipelineRun: (runId: number) =>
  8094. request<PipelineRun>(`/pipeline-runs/${runId}/retry-failed`, { method: 'POST' }),
  8095. // Canonical Bambu printer-model registry — "Bambu Lab <model>" → short code.
  8096. // Single source of truth shared with backend (PRINTER_MODEL_MAP); the
  8097. // SliceModal uses this to classify cloud / standard presets by their
  8098. // `@BBL <code>` suffix against the selected printer-preset name (#1325).
  8099. getSlicerPrinterModels: () =>
  8100. request<Record<string, string>>('/slicer/printer-models'),
  8101. getSlicerLoadedSpools: () =>
  8102. request<LoadedSpoolsResponse>('/slicer/loaded-spools'),
  8103. /**
  8104. * Effective values of a process preset, with its `inherits:` chain flattened
  8105. * by the slicer sidecar. Powers the slice modal's settings panel, which would
  8106. * otherwise show the option schema's compiled-in defaults (a preset setting a
  8107. * 0.42mm line width appears as the C++ default of 0).
  8108. *
  8109. * `resolved: false` means the values could not be obtained -- sidecar offline,
  8110. * too old for the endpoint, or slicing not configured -- and the caller should
  8111. * fall back to schema defaults rather than treat it as a failure.
  8112. */
  8113. getSlicerPresetValues: (ref: PresetRef) =>
  8114. request<SlicerPresetValues>(
  8115. `/slicer/preset-values?source=${encodeURIComponent(ref.source)}&id=${encodeURIComponent(ref.id)}`,
  8116. ),
  8117. // Local Presets (OrcaSlicer imports)
  8118. getLocalPresets: () =>
  8119. request<LocalPresetsResponse>('/local-presets/'),
  8120. importLocalPresets: (formData: FormData) =>
  8121. fetch(`${API_BASE}/local-presets/import`, {
  8122. method: 'POST',
  8123. headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {},
  8124. body: formData,
  8125. }).then(async (res) => {
  8126. if (!res.ok) {
  8127. const err = await res.json().catch(() => ({}));
  8128. throw new Error(err.detail || `HTTP ${res.status}`);
  8129. }
  8130. return res.json() as Promise<ImportResponse>;
  8131. }),
  8132. deleteLocalPreset: (id: number) =>
  8133. request<{ success: boolean }>(`/local-presets/${id}`, { method: 'DELETE' }),
  8134. };
  8135. // AMS History types
  8136. export interface AMSHistoryPoint {
  8137. recorded_at: string;
  8138. humidity: number | null;
  8139. humidity_raw: number | null;
  8140. temperature: number | null;
  8141. }
  8142. export interface AMSHistoryResponse {
  8143. printer_id: number;
  8144. ams_id: number;
  8145. data: AMSHistoryPoint[];
  8146. min_humidity: number | null;
  8147. max_humidity: number | null;
  8148. avg_humidity: number | null;
  8149. min_temperature: number | null;
  8150. max_temperature: number | null;
  8151. avg_temperature: number | null;
  8152. }
  8153. export type HeaterSensorKind = 'nozzle' | 'nozzle_2' | 'bed' | 'chamber';
  8154. export interface HeaterHistoryPoint {
  8155. recorded_at: string;
  8156. value: number | null;
  8157. target: number | null;
  8158. }
  8159. export interface HeaterSeries {
  8160. sensor_kind: HeaterSensorKind;
  8161. data: HeaterHistoryPoint[];
  8162. min_value: number | null;
  8163. max_value: number | null;
  8164. avg_value: number | null;
  8165. }
  8166. export interface PrinterSensorHistoryResponse {
  8167. printer_id: number;
  8168. series: HeaterSeries[];
  8169. }
  8170. // System Info types
  8171. export interface SystemInfo {
  8172. app: {
  8173. version: string;
  8174. base_dir: string;
  8175. archive_dir: string;
  8176. };
  8177. database: {
  8178. engine: string;
  8179. version: string;
  8180. archives: number;
  8181. archives_completed: number;
  8182. archives_failed: number;
  8183. archives_printing: number;
  8184. printers: number;
  8185. filaments: number;
  8186. projects: number;
  8187. smart_plugs: number;
  8188. total_print_time_seconds: number;
  8189. total_print_time_formatted: string;
  8190. total_filament_grams: number;
  8191. total_filament_kg: number;
  8192. };
  8193. printers: {
  8194. total: number;
  8195. connected: number;
  8196. connected_list: Array<{
  8197. id: number;
  8198. name: string;
  8199. state: string;
  8200. model: string;
  8201. }>;
  8202. };
  8203. storage: {
  8204. archive_size_bytes: number;
  8205. archive_size_formatted: string;
  8206. database_size_bytes: number;
  8207. database_size_formatted: string;
  8208. disk_total_bytes: number;
  8209. disk_total_formatted: string;
  8210. disk_used_bytes: number;
  8211. disk_used_formatted: string;
  8212. disk_free_bytes: number;
  8213. disk_free_formatted: string;
  8214. disk_percent_used: number;
  8215. };
  8216. system: {
  8217. platform: string;
  8218. platform_release: string;
  8219. platform_version: string;
  8220. architecture: string;
  8221. hostname: string;
  8222. python_version: string;
  8223. uptime_seconds: number;
  8224. uptime_formatted: string;
  8225. boot_time: string;
  8226. };
  8227. memory: {
  8228. total_bytes: number;
  8229. total_formatted: string;
  8230. available_bytes: number;
  8231. available_formatted: string;
  8232. used_bytes: number;
  8233. used_formatted: string;
  8234. percent_used: number;
  8235. };
  8236. cpu: {
  8237. count: number;
  8238. count_logical: number;
  8239. percent: number;
  8240. };
  8241. }
  8242. export interface StorageUsageCategory {
  8243. key: string;
  8244. label: string;
  8245. bytes: number;
  8246. formatted: string;
  8247. percent_of_total: number;
  8248. }
  8249. export interface StorageUsageOtherItem {
  8250. bucket: string;
  8251. label: string;
  8252. kind: 'system' | 'data';
  8253. deletable: boolean;
  8254. bytes: number;
  8255. formatted: string;
  8256. percent_of_total: number;
  8257. }
  8258. export interface StorageUsageResponse {
  8259. roots: string[];
  8260. total_bytes: number;
  8261. total_formatted: string;
  8262. categories: StorageUsageCategory[];
  8263. other_breakdown: StorageUsageOtherItem[];
  8264. scan_errors: number;
  8265. generated_at: string;
  8266. cache: {
  8267. hit: boolean;
  8268. age_seconds: number;
  8269. max_age_seconds: number;
  8270. };
  8271. }
  8272. // Library (File Manager) types
  8273. export interface LibraryFolderTree {
  8274. id: number;
  8275. name: string;
  8276. parent_id: number | null;
  8277. project_id: number | null;
  8278. archive_id: number | null;
  8279. project_name: string | null;
  8280. archive_name: string | null;
  8281. is_external: boolean;
  8282. external_path: string | null;
  8283. external_readonly: boolean;
  8284. file_count: number;
  8285. // max(folder.updated_at, max(immediate-child file.updated_at)). Used by
  8286. // the File Manager folder tree's "sort by recent activity" mode (#1770).
  8287. latest_activity_at: string | null;
  8288. // Ownership (#3201). can_* are for the current user: what the File
  8289. // Manager may offer on this folder. The backend enforces the same rules.
  8290. created_by_id: number | null;
  8291. shared: boolean;
  8292. can_write: boolean;
  8293. can_rename: boolean;
  8294. can_delete: boolean;
  8295. children: LibraryFolderTree[];
  8296. }
  8297. export interface LibraryFolder {
  8298. id: number;
  8299. name: string;
  8300. parent_id: number | null;
  8301. project_id: number | null;
  8302. archive_id: number | null;
  8303. project_name: string | null;
  8304. archive_name: string | null;
  8305. is_external: boolean;
  8306. external_path: string | null;
  8307. external_readonly: boolean;
  8308. external_show_hidden: boolean;
  8309. file_count: number;
  8310. latest_activity_at: string | null;
  8311. // Ownership (#3201). can_* are for the current user: what the File
  8312. // Manager may offer on this folder. The backend enforces the same rules.
  8313. created_by_id: number | null;
  8314. shared: boolean;
  8315. can_write: boolean;
  8316. can_rename: boolean;
  8317. can_delete: boolean;
  8318. created_at: string;
  8319. updated_at: string;
  8320. }
  8321. export interface LibraryFolderCreate {
  8322. name: string;
  8323. parent_id?: number | null;
  8324. project_id?: number | null;
  8325. archive_id?: number | null;
  8326. }
  8327. export interface ExternalFolderCreate {
  8328. name: string;
  8329. external_path: string;
  8330. readonly?: boolean;
  8331. show_hidden?: boolean;
  8332. parent_id?: number | null;
  8333. }
  8334. export interface LibraryFolderUpdate {
  8335. name?: string;
  8336. parent_id?: number | null;
  8337. project_id?: number | null; // 0 to unlink
  8338. archive_id?: number | null; // 0 to unlink
  8339. shared?: boolean; // library:update_all only (#3201)
  8340. }
  8341. export interface LibraryFileDuplicate {
  8342. id: number;
  8343. filename: string;
  8344. folder_id: number | null;
  8345. folder_name: string | null;
  8346. created_at: string;
  8347. }
  8348. export interface LibraryFile {
  8349. id: number;
  8350. folder_id: number | null;
  8351. folder_name: string | null;
  8352. project_id: number | null;
  8353. project_name: string | null;
  8354. is_external: boolean;
  8355. filename: string;
  8356. file_path: string;
  8357. file_type: string;
  8358. file_size: number;
  8359. file_hash: string | null;
  8360. thumbnail_path: string | null;
  8361. metadata: Record<string, unknown> | null;
  8362. print_count: number;
  8363. last_printed_at: string | null;
  8364. notes: string | null;
  8365. // User link + photos of the printed result (#3077); source_url is the
  8366. // read-only import provenance (MakerWorld).
  8367. external_url: string | null;
  8368. photos: string[];
  8369. source_url: string | null;
  8370. duplicates: LibraryFileDuplicate[] | null;
  8371. duplicate_count: number;
  8372. // User tracking (Issue #206)
  8373. created_by_id: number | null;
  8374. created_by_username: string | null;
  8375. created_at: string;
  8376. updated_at: string;
  8377. // Metadata fields
  8378. print_name: string | null;
  8379. print_time_seconds: number | null;
  8380. filament_used_grams: number | null;
  8381. sliced_for_model: string | null;
  8382. }
  8383. export interface LibraryTagSummary {
  8384. id: number;
  8385. name: string;
  8386. }
  8387. export interface LibraryFileListItem {
  8388. id: number;
  8389. folder_id: number | null;
  8390. is_external: boolean;
  8391. filename: string;
  8392. file_type: string;
  8393. file_size: number;
  8394. thumbnail_path: string | null;
  8395. print_count: number;
  8396. duplicate_count: number;
  8397. // User tracking (Issue #206)
  8398. created_by_id: number | null;
  8399. created_by_username: string | null;
  8400. created_at: string;
  8401. // Real on-disk modification time (#2680). Null for managed uploads; the date
  8402. // sort and "Modified" column use `fs_modified_at ?? created_at`.
  8403. fs_modified_at: string | null;
  8404. print_name: string | null;
  8405. print_time_seconds: number | null;
  8406. filament_used_grams: number | null;
  8407. sliced_for_model: string | null;
  8408. // Tags assigned to this file (#1268). The backend always emits an empty
  8409. // array when a file has no tags, but the field is typed optional so any
  8410. // legacy code path (or mock) that constructs a LibraryFileListItem without
  8411. // it doesn't crash the renderer. Read sites use `file.tags ?? []`.
  8412. tags?: LibraryTagSummary[];
  8413. // Variant grouping (#671 / #2570). `variant_count` is the size of the whole
  8414. // group, which may include files in other folders — never the number of
  8415. // matching rows on screen. 0 when the file is not grouped.
  8416. variant_group_id?: number | null;
  8417. variant_count?: number;
  8418. // Metadata indicators (#3077). Optional for the same reason as `tags`: older
  8419. // mocks construct list items without them. Read sites default to falsy.
  8420. external_url?: string | null;
  8421. has_notes?: boolean;
  8422. photo_count?: number;
  8423. }
  8424. // Variant groups (#671 / #2570): the same job sliced for different printers.
  8425. export interface VariantGroupMember {
  8426. library_file_id: number;
  8427. filename: string;
  8428. target_model: string;
  8429. position: number;
  8430. }
  8431. export interface VariantGroup {
  8432. id: number;
  8433. name: string;
  8434. /** In priority order — index 0 wins when several printers are free at once. */
  8435. members: VariantGroupMember[];
  8436. }
  8437. // Library tag catalog (#1268)
  8438. export interface LibraryTag {
  8439. id: number;
  8440. name: string;
  8441. file_count: number;
  8442. created_at: string;
  8443. updated_at: string;
  8444. }
  8445. export interface LibraryTagBulkAssignResult {
  8446. files_updated: number;
  8447. associations_added: number;
  8448. associations_removed: number;
  8449. }
  8450. export interface LibraryFileUpdate {
  8451. filename?: string;
  8452. folder_id?: number | null;
  8453. project_id?: number | null;
  8454. notes?: string | null;
  8455. external_url?: string | null;
  8456. }
  8457. // Library trash (#1008)
  8458. export interface LibraryTrashItem {
  8459. id: number;
  8460. filename: string;
  8461. file_size: number;
  8462. thumbnail_path: string | null;
  8463. folder_id: number | null;
  8464. folder_name: string | null;
  8465. created_by_id: number | null;
  8466. created_by_username: string | null;
  8467. deleted_at: string;
  8468. auto_purge_at: string;
  8469. }
  8470. export interface LibraryTrashListResponse {
  8471. items: LibraryTrashItem[];
  8472. total: number;
  8473. retention_days: number;
  8474. }
  8475. export interface LibraryPurgePreview {
  8476. count: number;
  8477. total_bytes: number;
  8478. sample_filenames: string[];
  8479. older_than_days: number;
  8480. include_never_printed: boolean;
  8481. }
  8482. export interface LibraryTrashSettings {
  8483. retention_days: number;
  8484. auto_purge_enabled: boolean;
  8485. auto_purge_days: number;
  8486. auto_purge_include_never_printed: boolean;
  8487. }
  8488. export interface ArchivePurgePreview {
  8489. count: number;
  8490. total_bytes: number;
  8491. sample_filenames: string[];
  8492. older_than_days: number;
  8493. }
  8494. export interface ArchiveMergeMember {
  8495. id: number;
  8496. print_name: string | null;
  8497. filename: string;
  8498. created_at: string | null;
  8499. run_count: number;
  8500. }
  8501. /** Why a group is left out: at work now, or holding files only one can keep. */
  8502. export type ArchiveMergeSkip = 'busy' | 'conflicting_files' | 'failed' | 'not_a_group';
  8503. export interface ArchiveMergeGroup {
  8504. survivor: ArchiveMergeMember;
  8505. merged: ArchiveMergeMember[];
  8506. skipped: ArchiveMergeSkip | null;
  8507. }
  8508. export interface ArchiveMergePreview {
  8509. groups: ArchiveMergeGroup[];
  8510. }
  8511. export interface ArchiveMergeResult {
  8512. merged: { survivor_id: number; merged_ids: number[] }[];
  8513. skipped: { survivor_id: number; reason: ArchiveMergeSkip }[];
  8514. }
  8515. export interface ArchivePurgeSettings {
  8516. enabled: boolean;
  8517. days: number;
  8518. // #1390: when true, bulk-deletes the linked PrintLogEntry rows so the
  8519. // contribution drops from Quick Stats too. Default false — soft-delete,
  8520. // Quick Stats preserved.
  8521. purge_stats: boolean;
  8522. }
  8523. export interface LibraryFileUploadResponse {
  8524. id: number;
  8525. filename: string;
  8526. file_type: string;
  8527. file_size: number;
  8528. thumbnail_path: string | null;
  8529. duplicate_of: number | null;
  8530. metadata: Record<string, unknown> | null;
  8531. }
  8532. export interface LibraryStats {
  8533. total_files: number;
  8534. total_folders: number;
  8535. total_size_bytes: number;
  8536. files_by_type: Record<string, number>;
  8537. total_prints: number;
  8538. disk_free_bytes: number;
  8539. disk_total_bytes: number;
  8540. disk_used_bytes: number;
  8541. }
  8542. export interface ZipExtractResult {
  8543. filename: string;
  8544. file_id: number;
  8545. folder_id: number | null;
  8546. }
  8547. export interface ZipExtractError {
  8548. filename: string;
  8549. error: string;
  8550. }
  8551. export interface ZipExtractResponse {
  8552. extracted: number;
  8553. folders_created: number;
  8554. files: ZipExtractResult[];
  8555. errors: ZipExtractError[];
  8556. }
  8557. // STL Thumbnail Generation types
  8558. export interface BatchThumbnailResult {
  8559. file_id: number;
  8560. filename: string;
  8561. success: boolean;
  8562. error?: string | null;
  8563. }
  8564. export interface BatchThumbnailResponse {
  8565. processed: number;
  8566. succeeded: number;
  8567. failed: number;
  8568. results: BatchThumbnailResult[];
  8569. }
  8570. // Discovery types
  8571. export interface DiscoveredPrinter {
  8572. serial: string;
  8573. name: string;
  8574. ip_address: string;
  8575. model: string | null;
  8576. discovered_at: string | null;
  8577. }
  8578. export interface DiscoveryStatus {
  8579. running: boolean;
  8580. }
  8581. export interface DiscoveryInfo {
  8582. is_docker: boolean;
  8583. ssdp_running: boolean;
  8584. scan_running: boolean;
  8585. subnets: string[];
  8586. }
  8587. export interface SubnetScanStatus {
  8588. running: boolean;
  8589. scanned: number;
  8590. total: number;
  8591. }
  8592. // Discovery API
  8593. export const discoveryApi = {
  8594. getInfo: () => request<DiscoveryInfo>('/discovery/info'),
  8595. startDiscovery: (duration: number = 10) =>
  8596. request<DiscoveryStatus>(`/discovery/start?duration=${duration}`, { method: 'POST' }),
  8597. stopDiscovery: () =>
  8598. request<DiscoveryStatus>('/discovery/stop', { method: 'POST' }),
  8599. getDiscoveredPrinters: () =>
  8600. request<DiscoveredPrinter[]>('/discovery/printers'),
  8601. // Subnet scanning (for Docker environments)
  8602. startSubnetScan: (subnet: string, timeout: number = 1.0) =>
  8603. request<SubnetScanStatus>('/discovery/scan', {
  8604. method: 'POST',
  8605. body: JSON.stringify({ subnet, timeout }),
  8606. }),
  8607. getScanStatus: () => request<SubnetScanStatus>('/discovery/scan/status'),
  8608. stopSubnetScan: () =>
  8609. request<SubnetScanStatus>('/discovery/scan/stop', { method: 'POST' }),
  8610. };
  8611. // Virtual Printer types
  8612. // Canonical wire values: `archive`, `review`, `queue`, `proxy`. The legacy
  8613. // `immediate` (→ archive) and `print_queue` (→ queue) names are still
  8614. // accepted by the backend so older API clients keep working, but new code
  8615. // should send the canonical names.
  8616. // 'archive' and 'immediate' are older names of 'library', 'print_queue' of 'queue'.
  8617. export type VirtualPrinterMode = 'library' | 'review' | 'queue' | 'proxy' | 'archive' | 'immediate' | 'print_queue';
  8618. export interface VirtualPrinterProxyStatus {
  8619. running: boolean;
  8620. target_host: string;
  8621. ftp_port: number;
  8622. mqtt_port: number;
  8623. ftp_connections: number;
  8624. mqtt_connections: number;
  8625. }
  8626. export interface VirtualPrinterStatus {
  8627. enabled: boolean;
  8628. running: boolean;
  8629. mode: VirtualPrinterMode;
  8630. name: string;
  8631. serial: string;
  8632. model: string;
  8633. model_name: string;
  8634. pending_files: number;
  8635. target_printer_ip?: string; // For proxy mode
  8636. proxy?: VirtualPrinterProxyStatus; // For proxy mode
  8637. }
  8638. export interface VirtualPrinterSettings {
  8639. tailscale_disabled: boolean;
  8640. archive_name_source: 'metadata' | 'filename'; // Source for archive's display name
  8641. status: VirtualPrinterStatus;
  8642. }
  8643. export interface NetworkInterface {
  8644. name: string;
  8645. ip: string;
  8646. netmask: string;
  8647. subnet: string;
  8648. is_alias?: boolean;
  8649. label?: string;
  8650. }
  8651. export interface PendingUpload {
  8652. id: number;
  8653. filename: string;
  8654. // Resolved name the review card should show — mirrors what archive_print
  8655. // will eventually write to PrintArchive.print_name (#1152 follow-up). Falls
  8656. // back to the stripped filename stem when the 3MF has no embedded title or
  8657. // the operator has chosen the "filename" archive-name source.
  8658. display_name: string;
  8659. file_size: number;
  8660. source_ip: string | null;
  8661. status: string;
  8662. tags: string | null;
  8663. notes: string | null;
  8664. project_id: number | null;
  8665. uploaded_at: string;
  8666. }
  8667. // Virtual Printer API
  8668. export const virtualPrinterApi = {
  8669. getSettings: () => request<VirtualPrinterSettings>('/settings/virtual-printer'),
  8670. updateSettings: (data: {
  8671. tailscale_disabled?: boolean;
  8672. archive_name_source?: 'metadata' | 'filename';
  8673. }) => {
  8674. const params = new URLSearchParams();
  8675. if (data.tailscale_disabled !== undefined) params.set('tailscale_disabled', String(data.tailscale_disabled));
  8676. if (data.archive_name_source !== undefined) params.set('archive_name_source', data.archive_name_source);
  8677. return request<VirtualPrinterSettings>(`/settings/virtual-printer?${params.toString()}`, {
  8678. method: 'PUT',
  8679. });
  8680. },
  8681. };
  8682. // Multi Virtual Printer API
  8683. export interface VirtualPrinterConfig {
  8684. id: number;
  8685. name: string;
  8686. enabled: boolean;
  8687. mode: VirtualPrinterMode;
  8688. model: string | null;
  8689. model_name: string | null;
  8690. access_code_set: boolean;
  8691. serial: string;
  8692. target_printer_id: number | null;
  8693. // File Manager folder uploads land in; null = the shared "Virtual Printer" folder.
  8694. library_folder_id: number | null;
  8695. // Queue mode: remove the file from the File Manager once its print starts.
  8696. queue_remove_after_print: boolean;
  8697. auto_dispatch: boolean;
  8698. queue_force_color_match: boolean;
  8699. save_ams_mapping: boolean;
  8700. gcode_injection: boolean;
  8701. tailscale_disabled: boolean;
  8702. bind_ip: string | null;
  8703. remote_interface_ip: string | null;
  8704. position: number;
  8705. status: { running: boolean; pending_files: number; proxy?: VirtualPrinterProxyStatus };
  8706. }
  8707. export interface VirtualPrinterListResponse {
  8708. printers: VirtualPrinterConfig[];
  8709. models: Record<string, string>;
  8710. }
  8711. export const multiVirtualPrinterApi = {
  8712. list: () => request<VirtualPrinterListResponse>('/virtual-printers'),
  8713. get: (id: number) => request<VirtualPrinterConfig>(`/virtual-printers/${id}`),
  8714. create: (data: {
  8715. name?: string;
  8716. enabled?: boolean;
  8717. mode?: string;
  8718. model?: string;
  8719. access_code?: string;
  8720. target_printer_id?: number;
  8721. auto_dispatch?: boolean;
  8722. queue_force_color_match?: boolean;
  8723. save_ams_mapping?: boolean;
  8724. gcode_injection?: boolean;
  8725. bind_ip?: string;
  8726. remote_interface_ip?: string;
  8727. }) =>
  8728. request<VirtualPrinterConfig>('/virtual-printers', {
  8729. method: 'POST',
  8730. body: JSON.stringify(data),
  8731. }),
  8732. update: (id: number, data: {
  8733. name?: string;
  8734. enabled?: boolean;
  8735. mode?: string;
  8736. model?: string;
  8737. access_code?: string;
  8738. // null clears the target (a queue VP then sends to any printer of its model).
  8739. target_printer_id?: number | null;
  8740. // null: back to the shared "Virtual Printer" folder.
  8741. library_folder_id?: number | null;
  8742. queue_remove_after_print?: boolean;
  8743. auto_dispatch?: boolean;
  8744. queue_force_color_match?: boolean;
  8745. save_ams_mapping?: boolean;
  8746. gcode_injection?: boolean;
  8747. tailscale_disabled?: boolean;
  8748. bind_ip?: string;
  8749. remote_interface_ip?: string;
  8750. }) =>
  8751. request<VirtualPrinterConfig>(`/virtual-printers/${id}`, {
  8752. method: 'PUT',
  8753. body: JSON.stringify(data),
  8754. }),
  8755. remove: (id: number) =>
  8756. request<{ detail: string; id: number }>(`/virtual-printers/${id}`, {
  8757. method: 'DELETE',
  8758. }),
  8759. getTailscaleStatus: () =>
  8760. request<TailscaleStatusResponse>('/virtual-printers/tailscale-status'),
  8761. getCaCertificate: () =>
  8762. request<VPCaCertificate>('/virtual-printers/ca-certificate'),
  8763. // A script that adds the CA to Bambu Studio and OrcaSlicer, with the CA
  8764. // written into it: 'windows' (.cmd) or 'unix' (.sh, Linux and macOS).
  8765. getCaCertificateInstaller: (platform: 'windows' | 'unix') =>
  8766. request<{ filename: string; content: string }>(`/virtual-printers/ca-certificate/installer/${platform}`),
  8767. diagnose: (id: number) =>
  8768. request<VPDiagnosticResult>(`/virtual-printers/${id}/diagnostic`),
  8769. };
  8770. /** The shared CA certificate every virtual printer presents — imported once
  8771. * into the slicer's trust store. Only the public certificate is returned. */
  8772. export interface VPCaCertificate {
  8773. pem: string;
  8774. fingerprint_sha256: string;
  8775. not_valid_after: string;
  8776. }
  8777. export type VPDiagnosticStatus = 'pass' | 'fail' | 'warn' | 'skip';
  8778. export interface VPDiagnosticCheck {
  8779. id:
  8780. | 'enabled'
  8781. | 'running'
  8782. | 'bind_interface'
  8783. | 'access_code'
  8784. | 'target_printer'
  8785. | 'port_ftps'
  8786. | 'port_mqtt'
  8787. | 'port_bind'
  8788. | 'certificate';
  8789. status: VPDiagnosticStatus;
  8790. params: Record<string, string | number>;
  8791. }
  8792. export interface VPDiagnosticResult {
  8793. vp_id: number;
  8794. vp_name: string;
  8795. mode: string;
  8796. overall: 'ok' | 'warnings' | 'problems';
  8797. checks: VPDiagnosticCheck[];
  8798. }
  8799. export interface TailscaleStatusResponse {
  8800. available: boolean;
  8801. fqdn: string;
  8802. hostname: string;
  8803. tailnet_name: string;
  8804. tailscale_ips: string[];
  8805. error: string | null;
  8806. }
  8807. // Pending Uploads API
  8808. export const pendingUploadsApi = {
  8809. list: () => request<PendingUpload[]>('/pending-uploads/'),
  8810. getCount: () => request<{ count: number }>('/pending-uploads/count'),
  8811. get: (id: number) => request<PendingUpload>(`/pending-uploads/${id}`),
  8812. // Approve: the file goes to its virtual printer's File Manager folder.
  8813. archive: (id: number, data?: { tags?: string; notes?: string; project_id?: number }) =>
  8814. request<{ id: number; filename: string; folder_id: number | null }>(`/pending-uploads/${id}/archive`, {
  8815. method: 'POST',
  8816. body: JSON.stringify(data || {}),
  8817. }),
  8818. discard: (id: number) =>
  8819. request<{ success: boolean }>(`/pending-uploads/${id}`, { method: 'DELETE' }),
  8820. archiveAll: () =>
  8821. request<{ stored: number; failed: number }>('/pending-uploads/archive-all', { method: 'POST' }),
  8822. discardAll: () =>
  8823. request<{ discarded: number }>('/pending-uploads/discard-all', { method: 'DELETE' }),
  8824. };
  8825. // Firmware API Types
  8826. export interface AvailableFirmwareVersion {
  8827. version: string;
  8828. file_available: boolean;
  8829. download_url: string | null;
  8830. release_notes: string | null;
  8831. release_time: string | null;
  8832. }
  8833. export interface FirmwareUpdateInfo {
  8834. printer_id: number;
  8835. printer_name: string;
  8836. model: string | null;
  8837. current_version: string | null;
  8838. latest_version: string | null;
  8839. update_available: boolean;
  8840. download_url: string | null;
  8841. release_notes: string | null;
  8842. available_versions: AvailableFirmwareVersion[];
  8843. }
  8844. export interface FirmwareUploadPrepare {
  8845. can_proceed: boolean;
  8846. sd_card_present: boolean;
  8847. sd_card_free_space: number;
  8848. firmware_size: number;
  8849. space_sufficient: boolean;
  8850. update_available: boolean;
  8851. current_version: string | null;
  8852. latest_version: string | null;
  8853. target_version: string | null;
  8854. firmware_filename: string | null;
  8855. errors: string[];
  8856. }
  8857. export interface FirmwareUploadStatus {
  8858. status: 'idle' | 'preparing' | 'downloading' | 'uploading' | 'complete' | 'error';
  8859. progress: number;
  8860. message: string;
  8861. error: string | null;
  8862. firmware_filename: string | null;
  8863. firmware_version: string | null;
  8864. }
  8865. // Firmware API
  8866. export const firmwareApi = {
  8867. checkUpdates: () =>
  8868. request<{ updates: FirmwareUpdateInfo[]; updates_available: number }>('/firmware/updates'),
  8869. checkPrinterUpdate: (printerId: number) => firmwareUpdateBatch(printerId),
  8870. prepareUpload: (printerId: number, version?: string) =>
  8871. request<FirmwareUploadPrepare>(
  8872. `/firmware/updates/${printerId}/prepare${version ? `?version=${encodeURIComponent(version)}` : ''}`,
  8873. ),
  8874. startUpload: (printerId: number, version?: string) =>
  8875. request<{ started: boolean; message: string }>(
  8876. `/firmware/updates/${printerId}/upload${version ? `?version=${encodeURIComponent(version)}` : ''}`,
  8877. { method: 'POST' },
  8878. ),
  8879. getUploadStatus: (printerId: number) =>
  8880. request<FirmwareUploadStatus>(`/firmware/updates/${printerId}/upload/status`),
  8881. };
  8882. // Support types
  8883. export interface DebugLoggingState {
  8884. enabled: boolean;
  8885. enabled_at: string | null;
  8886. duration_seconds: number | null;
  8887. }
  8888. export interface LogEntry {
  8889. timestamp: string;
  8890. level: string;
  8891. logger_name: string;
  8892. message: string;
  8893. }
  8894. export interface LogsResponse {
  8895. entries: LogEntry[];
  8896. total_in_file: number;
  8897. filtered_count: number;
  8898. }
  8899. // Support API
  8900. export const supportApi = {
  8901. getDebugLoggingState: () =>
  8902. request<DebugLoggingState>('/support/debug-logging'),
  8903. setDebugLogging: (enabled: boolean) =>
  8904. request<DebugLoggingState>('/support/debug-logging', {
  8905. method: 'POST',
  8906. body: JSON.stringify({ enabled }),
  8907. }),
  8908. downloadSupportBundle: async () => {
  8909. const headers: Record<string, string> = {};
  8910. if (authToken) {
  8911. headers['Authorization'] = `Bearer ${authToken}`;
  8912. }
  8913. const response = await fetch(`${API_BASE}/support/bundle`, { headers });
  8914. if (!response.ok) {
  8915. const error = await response.json().catch(() => ({}));
  8916. throw new Error(error.detail || `HTTP ${response.status}`);
  8917. }
  8918. // Get filename from Content-Disposition header or use default
  8919. const disposition = response.headers.get('Content-Disposition');
  8920. const filename = parseContentDispositionFilename(disposition) || 'bambuddy-support.zip';
  8921. // Download the blob
  8922. const blob = await response.blob();
  8923. const url = window.URL.createObjectURL(blob);
  8924. const a = document.createElement('a');
  8925. a.href = url;
  8926. a.download = filename;
  8927. document.body.appendChild(a);
  8928. a.click();
  8929. document.body.removeChild(a);
  8930. window.URL.revokeObjectURL(url);
  8931. },
  8932. getLogs: (params?: { limit?: number; level?: string; search?: string }) => {
  8933. const searchParams = new URLSearchParams();
  8934. if (params?.limit) searchParams.set('limit', params.limit.toString());
  8935. if (params?.level) searchParams.set('level', params.level);
  8936. if (params?.search) searchParams.set('search', params.search);
  8937. const query = searchParams.toString();
  8938. return request<LogsResponse>(`/support/logs${query ? `?${query}` : ''}`);
  8939. },
  8940. clearLogs: () =>
  8941. request<{ message: string }>('/support/logs', { method: 'DELETE' }),
  8942. };
  8943. // SpoolBuddy types
  8944. export interface SpoolBuddyDevice {
  8945. id: number;
  8946. device_id: string;
  8947. hostname: string;
  8948. ip_address: string;
  8949. backend_url?: string | null;
  8950. firmware_version: string | null;
  8951. has_nfc: boolean;
  8952. has_scale: boolean;
  8953. tare_offset: number;
  8954. calibration_factor: number;
  8955. nfc_reader_type: string | null;
  8956. nfc_connection: string | null;
  8957. display_brightness: number;
  8958. display_blank_timeout: number;
  8959. has_backlight: boolean;
  8960. last_calibrated_at: string | null;
  8961. last_seen: string | null;
  8962. pending_command: string | null;
  8963. nfc_ok: boolean;
  8964. scale_ok: boolean;
  8965. uptime_s: number;
  8966. update_status: string | null;
  8967. update_message: string | null;
  8968. system_stats: {
  8969. os?: { os?: string; kernel?: string; arch?: string; python?: string };
  8970. cpu_temp_c?: number;
  8971. cpu_count?: number;
  8972. load_avg?: number[];
  8973. memory?: { total_mb?: number; available_mb?: number; used_mb?: number; percent?: number };
  8974. disk?: { total_gb?: number; used_gb?: number; free_gb?: number; percent?: number };
  8975. system_uptime_s?: number;
  8976. } | null;
  8977. online: boolean;
  8978. }
  8979. export interface DaemonUpdateCheck {
  8980. current_version: string;
  8981. latest_version: string | null;
  8982. update_available: boolean;
  8983. }
  8984. // SpoolBuddy API
  8985. export const spoolbuddyApi = {
  8986. getDevices: () =>
  8987. request<SpoolBuddyDevice[]>('/spoolbuddy/devices'),
  8988. deleteDevice: (deviceId: string) =>
  8989. request<{ status: string; device_id: string }>(`/spoolbuddy/devices/${deviceId}`, {
  8990. method: 'DELETE',
  8991. }),
  8992. tare: (deviceId: string) =>
  8993. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/calibration/tare`, {
  8994. method: 'POST',
  8995. body: '{}',
  8996. }),
  8997. setCalibrationFactor: (deviceId: string, knownWeightGrams: number, rawAdc: number, tareRawAdc?: number) =>
  8998. request<{ tare_offset: number; calibration_factor: number }>(`/spoolbuddy/devices/${deviceId}/calibration/set-factor`, {
  8999. method: 'POST',
  9000. body: JSON.stringify({ known_weight_grams: knownWeightGrams, raw_adc: rawAdc, tare_raw_adc: tareRawAdc }),
  9001. }),
  9002. updateSpoolWeight: (spoolId: number, weightGrams: number) =>
  9003. request<{ status: string; weight_used: number }>('/spoolbuddy/scale/update-spool-weight', {
  9004. method: 'POST',
  9005. body: JSON.stringify({ spool_id: spoolId, weight_grams: weightGrams }),
  9006. }),
  9007. updateDisplay: (deviceId: string, brightness: number, blankTimeout: number) =>
  9008. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/display`, {
  9009. method: 'PUT',
  9010. body: JSON.stringify({ brightness, blank_timeout: blankTimeout }),
  9011. }),
  9012. updateSystemConfig: (deviceId: string, backendUrl: string, apiKey?: string) =>
  9013. request<{ status: string; message: string }>(`/spoolbuddy/devices/${deviceId}/system/config`, {
  9014. method: 'POST',
  9015. body: JSON.stringify({ backend_url: backendUrl, ...(apiKey ? { api_key: apiKey } : {}) }),
  9016. }),
  9017. checkDaemonUpdate: (deviceId: string) =>
  9018. request<DaemonUpdateCheck>(`/spoolbuddy/devices/${deviceId}/update-check`),
  9019. triggerUpdate: (deviceId: string) =>
  9020. request<{ status: string; message: string }>(`/spoolbuddy/devices/${deviceId}/update`, {
  9021. method: 'POST',
  9022. body: '{}',
  9023. }),
  9024. getSSHPublicKey: () =>
  9025. request<{ public_key: string }>('/spoolbuddy/ssh/public-key'),
  9026. writeTag: (deviceId: string, spoolId: number) =>
  9027. request<{ status: string; warnings?: string[] }>('/spoolbuddy/nfc/write-tag', {
  9028. method: 'POST',
  9029. body: JSON.stringify({ device_id: deviceId, spool_id: spoolId }),
  9030. }),
  9031. cancelWrite: (deviceId: string) =>
  9032. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/cancel-write`, {
  9033. method: 'POST',
  9034. body: '{}',
  9035. }),
  9036. systemCommand: (deviceId: string, command: 'reboot' | 'shutdown' | 'restart_daemon' | 'restart_browser') =>
  9037. request<{ status: string; command: string }>(`/spoolbuddy/devices/${deviceId}/system/command`, {
  9038. method: 'POST',
  9039. body: JSON.stringify({ command }),
  9040. }),
  9041. queueDiagnostics: (deviceId: string, type: 'nfc' | 'scale' | 'read_tag') =>
  9042. request<{ status: string; diagnostic: string; message: string }>(
  9043. `/spoolbuddy/diagnostics/${deviceId}/run?diagnostic=${type}`,
  9044. { method: 'POST', body: '{}' }
  9045. ),
  9046. getDiagnosticResult: (deviceId: string, type: 'nfc' | 'scale' | 'read_tag') =>
  9047. request<{ diagnostic: string; success: boolean; output: string; exit_code: number }>(
  9048. `/spoolbuddy/diagnostics/${deviceId}/result?diagnostic=${type}`,
  9049. { method: 'GET' }
  9050. ),
  9051. };
  9052. export interface BugReportRequest {
  9053. description: string;
  9054. email?: string;
  9055. screenshot_base64?: string;
  9056. include_support_info?: boolean;
  9057. debug_logs?: string;
  9058. }
  9059. export interface BugReportResponse {
  9060. success: boolean;
  9061. message: string;
  9062. issue_url?: string;
  9063. issue_number?: number;
  9064. }
  9065. export const bugReportApi = {
  9066. submit: (data: BugReportRequest) =>
  9067. request<BugReportResponse>('/bug-report/submit', {
  9068. method: 'POST',
  9069. body: JSON.stringify(data),
  9070. }),
  9071. startLogging: () =>
  9072. request<{ started: boolean; was_debug: boolean }>('/bug-report/start-logging', {
  9073. method: 'POST',
  9074. }),
  9075. stopLogging: (wasDebug: boolean) =>
  9076. request<{ logs: string }>(`/bug-report/stop-logging?was_debug=${wasDebug}`, {
  9077. method: 'POST',
  9078. }),
  9079. };
  9080. export type AnnouncementLevel = 'info' | 'important' | 'critical';
  9081. export interface AnnouncementText {
  9082. title: string;
  9083. body: string;
  9084. link_label?: string;
  9085. }
  9086. // One message from the Bambuddy maintainers. `texts` holds every language the
  9087. // message was written in; English is always there.
  9088. export interface Announcement {
  9089. id: string;
  9090. level: AnnouncementLevel;
  9091. texts: Record<string, AnnouncementText>;
  9092. link_url: string | null;
  9093. published_at: string | null;
  9094. expires_at: string | null;
  9095. // Past its expiry: kept as history, listed under "Earlier", never unread.
  9096. archived: boolean;
  9097. read: boolean;
  9098. }
  9099. // `visible` says whether this user may see announcements at all (switched on,
  9100. // and admin or "show to all users"); it keeps the sidebar entry while nothing
  9101. // is published.
  9102. export interface AnnouncementList {
  9103. visible: boolean;
  9104. announcements: Announcement[];
  9105. }
  9106. export const announcementsApi = {
  9107. list: () => request<AnnouncementList>('/announcements'),
  9108. markRead: (id: string) =>
  9109. request<void>(`/announcements/${encodeURIComponent(id)}/read`, { method: 'POST' }),
  9110. };
  9111. export interface SponsorPromptCheckResponse {
  9112. show: boolean;
  9113. milestone?: string;
  9114. family?: 'prints' | 'cost' | 'archives' | 'anniversary' | 'version-update';
  9115. threshold?: number;
  9116. payload?: Record<string, unknown>;
  9117. }
  9118. export const sponsorPromptApi = {
  9119. check: () => request<SponsorPromptCheckResponse>('/sponsor-prompt/check'),
  9120. dismiss: (milestone: string) =>
  9121. request<void>('/sponsor-prompt/dismiss', {
  9122. method: 'POST',
  9123. body: JSON.stringify({ milestone }),
  9124. }),
  9125. };