client.ts 332 KB

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