client.ts 237 KB

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