client.ts 340 KB

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