client.ts 341 KB

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