client.ts 233 KB

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