client.ts 290 KB

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