client.ts 239 KB

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