client.ts 216 KB

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