client.ts 244 KB

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