client.ts 340 KB

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