client.ts 340 KB

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