client.ts 350 KB

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