client.ts 265 KB

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