client.ts 241 KB

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