client.ts 293 KB

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