client.ts 339 KB

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