client.ts 313 KB

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