client.ts 240 KB

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