client.ts 330 KB

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