client.ts 297 KB

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