client.ts 293 KB

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