client.ts 338 KB

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