client.ts 265 KB

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