client.ts 267 KB

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