client.ts 303 KB

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