📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
refactor: remove bad or unnecessary types, antipatterns and redux sagas
Blue Mouse1c9395c14c26
diff --git a/web/app/App.tsx b/web/app/App.tsxindex 42546dfa3..028e43490 100644--- a/web/app/App.tsx+++ b/web/app/App.tsx@@ -14,12 +14,13 @@ import Footer from 'components/Footer'import { Toaster } from 'sonner'import { getAccessToken } from 'utils/accessToken'import { authActions } from 'redux/reducers/auth'-import sagaActions from 'redux/sagas/actions'import { StateType, useAppDispatch } from 'redux/store'-import { isBrowser } from 'redux/constants'+import { isBrowser, isSelfhosted } from 'redux/constants'import routesPath from 'utils/routes'import { getPageMeta } from 'utils/server'-import { authMe } from './api'+import { authMe, getGeneralStats, getInstalledExtensions, getLastPost, getPaymentMetainfo } from './api'+import UIActions from 'redux/reducers/ui'+import { logout, shouldShowLowEventsBanner } from 'utils/auth'interface AppProps {ssrTheme: 'dark' | 'light'@@ -44,15 +45,43 @@ const App = ({ ssrTheme, ssrAuthenticated }: AppProps) => {(async () => {if (accessToken && !reduxAuthenticated) {try {- const me = await authMe()- dispatch(authActions.authSuccessful(me))+ const { user, totalMonthlyEvents } = await authMe()+ dispatch(authActions.authSuccessful(user))++ if (shouldShowLowEventsBanner(totalMonthlyEvents, user.maxEventsCount)) {+ dispatch(UIActions.setShowNoEventsLeftBanner(true))+ }++ if (!isSelfhosted) {+ const extensions = await getInstalledExtensions()+ dispatch(UIActions.setExtensions(extensions))+ }} catch (reason) {dispatch(authActions.logout())- dispatch(sagaActions.logout(false, false))+ logout()console.error(`[ERROR] Error while getting user: ${reason}`)}}+ if (!isSelfhosted) {+ const [metainfo, lastBlogPost, generalStats] = await Promise.all([+ getPaymentMetainfo(),+ getLastPost(),+ getGeneralStats(),+ ])+ dispatch(UIActions.setMetainfo(metainfo))+ dispatch(UIActions.setLastBlogPost(lastBlogPost))+ dispatch(UIActions.setGeneralStats(generalStats))+ }++ // yield put(sagaActions.loadMetainfo())++ // const lastBlogPost: {+ // title: string+ // handle: string+ // } = yield call(getLastPost)+ // yield put(UIActions.setLastBlogPost(lastBlogPost))+dispatch(authActions.finishLoading())})()}, [reduxAuthenticated]) // eslint-disable-linediff --git a/web/app/api/index.ts b/web/app/api/index.tsindex 8488b3f53..dcb84cdb5 100644--- a/web/app/api/index.ts+++ b/web/app/api/index.ts@@ -7,19 +7,19 @@ import _isEmpty from 'lodash/isEmpty'import _isArray from 'lodash/isArray'import { authActions } from 'redux/reducers/auth'-import sagaActions from 'redux/sagas/actions'import { getAccessToken, removeAccessToken, setAccessToken } from 'utils/accessToken'import { getRefreshToken, removeRefreshToken } from 'utils/refreshToken'import { DEFAULT_ALERTS_TAKE, API_URL, DEFAULT_MONITORS_TAKE } from 'redux/constants'-import { IUser } from 'redux/models/IUser'-import { IAuth } from 'redux/models/IAuth'-import { IProject, IOverall, ILiveStats } from 'redux/models/IProject'-import { IAlerts } from 'redux/models/IAlerts'-import { ISubscribers } from 'redux/models/ISubscribers'-import { IFilter, IProjectViewCustomEvent } from 'pages/Project/View/interfaces/traffic'+import { User } from 'redux/models/User'+import { Auth } from 'redux/models/Auth'+import { Project, Overall, LiveStats } from 'redux/models/Project'+import { Alerts } from 'redux/models/Alerts'+import { Subscriber } from 'redux/models/Subscriber'+import { Filter, ProjectViewCustomEvent } from 'pages/Project/View/interfaces/traffic'import { AIResponse } from 'pages/Project/View/interfaces/ai'import { Monitor, MonitorOverall } from 'redux/models/Uptime'import { Role } from 'redux/models/Organisation'+import { logout } from 'utils/auth'const api = axios.create({baseURL: API_URL,@@ -42,7 +42,7 @@ const refreshAuthLogic = (failedRequest: { response: AxiosResponse }) =>}).catch((error) => {store.dispatch(authActions.logout())- store.dispatch(sagaActions.logout(true, false))+ logout()return Promise.reject(error)})@@ -68,7 +68,14 @@ api.interceptors.request.use(export const authMe = () =>api.get('user/me')- .then((response): IUser => response.data)+ .then(+ (+ response,+ ): {+ user: User+ totalMonthlyEvents: number+ } => response.data,+ ).catch((error) => {throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message})@@ -100,7 +107,7 @@ export const logoutAllApi = () =>export const login = (credentials: { email: string; password: string }) =>api.post('v1/auth/login', credentials)- .then((response): IAuth => response.data)+ .then((response): Auth => response.data).catch((error) => {throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message})@@ -108,7 +115,7 @@ export const login = (credentials: { email: string; password: string }) =>export const signup = (data: { email: string; password: string; refCode?: string }) =>api.post('v1/auth/register', data)- .then((response): IAuth => response.data)+ .then((response): Auth => response.data).catch((error) => {const errorsArray = error.response.data.messageif (_isArray(errorsArray)) {@@ -129,10 +136,10 @@ export const deleteUser = (deletionFeedback?: string) =>throw new Error(JSON.stringify(error.response.data))})-export const changeUserDetails = (data: IUser) =>+export const changeUserDetails = (data: User) =>api.put('/user', data)- .then((response): IUser => response.data)+ .then((response): User => response.data).catch((error) => {const errorsArray = error.response.data.messageif (_isArray(errorsArray)) {@@ -144,7 +151,7 @@ export const changeUserDetails = (data: IUser) =>export const setShowLiveVisitorsInTitle = (show: boolean) =>api.put('/user/live-visitors', { show })- .then((response): Partial<IUser> => response.data)+ .then((response): Partial<User> => response.data).catch((error) => {const errorsArray = error.response.data.messageif (_isArray(errorsArray)) {@@ -156,7 +163,7 @@ export const setShowLiveVisitorsInTitle = (show: boolean) =>export const generateRefCode = () =>api.post('/user/generate-ref-code')- .then((response): Partial<IUser> => response.data)+ .then((response): Partial<User> => response.data).catch((error) => {const errorsArray = error.response.data.messageif (_isArray(errorsArray)) {@@ -168,7 +175,7 @@ export const generateRefCode = () =>export const getPayoutsInfo = () =>api.get('/user/payouts/info')- .then((response): Partial<IUser> => response.data)+ .then((response): Partial<User> => response.data).catch((error) => {const errorsArray = error.response.data.messageif (_isArray(errorsArray)) {@@ -180,7 +187,7 @@ export const getPayoutsInfo = () =>export const getReferrals = () =>api.get('/user/referrals')- .then((response): Partial<IUser> => response.data)+ .then((response): Partial<User> => response.data).catch((error) => {const errorsArray = error.response.data.messageif (_isArray(errorsArray)) {@@ -256,10 +263,9 @@ export const getProjects = (take: number = 0, skip: number = 0, search?: string)(response,): {- results: IProject[]+ results: Project[]total: numberpage_total: number- totalMonthlyEvents: number} => response.data,).catch((error) => {@@ -385,7 +391,7 @@ export const getProject = (pid: string, password?: string) =>'x-password': password,},})- .then((response): IProject => response.data)+ .then((response): Project => response.data).catch((error) => {throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message})@@ -393,15 +399,15 @@ export const getProject = (pid: string, password?: string) =>export const createProject = (data: { name: string; organisationId?: string; isCaptcha?: boolean }) =>api.post('/project', data)- .then((response): IProject => response.data)+ .then((response): Project => response.data).catch((error) => {throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message})-export const updateProject = (id: string, data: Partial<IProject>) =>+export const updateProject = (id: string, data: Partial<Project>) =>api.put(`/project/${id}`, data)- .then((response): IProject => response.data)+ .then((response): Project => response.data).catch((error) => {throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message})@@ -442,8 +448,8 @@ export const getProjectData = (pid: string,tb: string = 'hour',period: string = '1d',- filters: IFilter[] = [],- metrics: IProjectViewCustomEvent[] = [],+ filters: Filter[] = [],+ metrics: ProjectViewCustomEvent[] = [],from: string = '',to: string = '',timezone: string = '',@@ -737,8 +743,8 @@ export const createProjectView = (pid: string,name: string,type: 'traffic' | 'performance',- filters: IFilter[],- customEvents: Partial<IProjectViewCustomEvent>[],+ filters: Filter[],+ customEvents: Partial<ProjectViewCustomEvent>[],) =>api.post(`project/${pid}/views`, { name, type, filters, customEvents })@@ -751,8 +757,8 @@ export const updateProjectView = (pid: string,viewId: string,name: string,- filters: IFilter[],- customEvents: Partial<IProjectViewCustomEvent>[],+ filters: Filter[],+ customEvents: Partial<ProjectViewCustomEvent>[],) =>api.patch(`project/${pid}/views/${viewId}`, { name, filters, customEvents })@@ -808,7 +814,7 @@ export const getOverallStats = (},},)- .then((response): IOverall => response.data)+ .then((response): Overall => response.data).catch((error) => {throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message})@@ -834,7 +840,7 @@ export const getPerformanceOverallStats = (},},)- .then((response): IOverall => response.data)+ .then((response): Overall => response.data).catch((error) => {throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message})@@ -853,12 +859,12 @@ export const getOverallStatsCaptcha = (',',)}]&period=${period}&from=${from}&to=${to}&timezone=${timezone}&filters=${JSON.stringify(filters)}`,)- .then((response): IOverall => response.data)+ .then((response): Overall => response.data).catch((error) => {throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message})-export const getLiveVisitors = (pids: string[], password?: string): Promise<ILiveStats> =>+export const getLiveVisitors = (pids: string[], password?: string): Promise<LiveStats> =>api.get(`log/hb?pids=[${_map(pids, (pid) => `"${pid}"`).join(',')}]`, {headers: {@@ -887,7 +893,7 @@ export const shareProject = () =>api.post(`/project/${pid}/share`, data)- .then((response): IProject => response.data)+ .then((response): Project => response.data).catch((error) => {throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message})@@ -991,7 +997,7 @@ export const getInstalledExtensions = (limit = 100, offset = 0) =>throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message})-export interface IGetLiveVisitorsInfo {+export interface GetLiveVisitorsInfo {psid: stringdv: stringbr: string@@ -1006,7 +1012,7 @@ export const getLiveVisitorsInfo = (pid: string, password?: string) =>'x-password': password,},})- .then((response): IGetLiveVisitorsInfo[] => response.data)+ .then((response): GetLiveVisitorsInfo[] => response.data).catch((error) => {throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message})@@ -1026,7 +1032,7 @@ export const getProjectAlerts = (projectId: string, take: number = DEFAULT_ALERT(response,): {- results: IAlerts[]+ results: Alerts[]total: numberpage_total: number} => response.data,@@ -1038,25 +1044,25 @@ export const getProjectAlerts = (projectId: string, take: number = DEFAULT_ALERTexport const getAlert = (alertId: string) =>api.get(`/alert/${alertId}`)- .then((response): IAlerts => response.data)+ .then((response): Alerts => response.data).catch((error) => {throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message})-export interface ICreateAlert extends Omit<IAlerts, 'id' | 'lastTrigger' | 'lastTriggered' | 'created'> {}+export interface CreateAlert extends Omit<Alerts, 'id' | 'lastTrigger' | 'lastTriggered' | 'created'> {}-export const createAlert = (data: ICreateAlert) =>+export const createAlert = (data: CreateAlert) =>api.post('alert', data)- .then((response): IAlerts => response.data)+ .then((response): Alerts => response.data).catch((error) => {throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message})-export const updateAlert = (id: string, data: Partial<IAlerts>) =>+export const updateAlert = (id: string, data: Partial<Alerts>) =>api.put(`alert/${id}`, data)- .then((response): IAlerts => response.data)+ .then((response): Alerts => response.data).catch((error) => {throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message})@@ -1069,11 +1075,11 @@ export const deleteAlert = (id: string) =>throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message})-export interface ICreateMonitor extends Omit<Monitor, 'id' | 'createdAt' | 'updatedAt'> {}+export interface CreateMonitor extends Omit<Monitor, 'id' | 'createdAt' | 'updatedAt'> {}-export const getAllMonitors = (take: number = DEFAULT_MONITORS_TAKE, skip: number = 0) =>+export const getProjectMonitors = (projectId: string, take: number = DEFAULT_MONITORS_TAKE, skip: number = 0) =>api- .get(`project/monitors?take=${take}&skip=${skip}`)+ .get(`project/${projectId}/monitors?take=${take}&skip=${skip}`).then((response,@@ -1087,18 +1093,10 @@ export const getAllMonitors = (take: number = DEFAULT_MONITORS_TAKE, skip: numbethrow _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message})-export const getProjectMonitors = (projectId: string, take: number = DEFAULT_MONITORS_TAKE, skip: number = 0) =>+export const getProjectMonitor = (projectId: string, monitorId: string) =>api- .get(`project/${projectId}/monitors?take=${take}&skip=${skip}`)- .then(- (- response,- ): {- results: Monitor[]- total: number- page_total: number- } => response.data,- )+ .get(`/project/${projectId}/monitor/${monitorId}`)+ .then((response): Monitor => response.data).catch((error) => {throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message})@@ -1152,7 +1150,7 @@ export const getMonitorStats = (throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message})-export const createMonitor = (pid: string, data: ICreateMonitor) =>+export const createMonitor = (pid: string, data: CreateMonitor) =>api.post(`project/${pid}/monitor`, data).then((response): Monitor => response.data)@@ -1193,7 +1191,7 @@ export const addSubscriber = () =>api.post(`project/${id}/subscribers`, data)- .then((response): ISubscribers => response.data)+ .then((response): Subscriber => response.data).catch((error) => {throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message})@@ -1229,7 +1227,7 @@ export const getSubscribers = (id: string, offset: number, limit: number) =>(response,): {- subscribers: ISubscribers[]+ subscribers: Subscriber[]count: number} => response.data,)@@ -1246,7 +1244,7 @@ export const updateSubscriber = () =>api.patch(`project/${id}/subscribers/${subscriberId}`, data)- .then((response): ISubscribers => response.data)+ .then((response): Subscriber => response.data).catch((error) => {throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message})@@ -1326,7 +1324,15 @@ export const generateSSOAuthURL = (provider: string) =>.post('v1/auth/sso/generate', {provider,})- .then((response): unknown => response.data)+ .then(+ (+ response,+ ): {+ uuid: string+ auth_url: string+ expires_in: number+ } => response.data,+ ).catch((error) => {throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message})@@ -1334,7 +1340,16 @@ export const generateSSOAuthURL = (provider: string) =>export const getJWTBySSOHash = (hash: string, provider: string, refCode?: string) =>api.post('v1/auth/sso/hash', { hash, provider, refCode })- .then((response): unknown => response.data)+ .then(+ (+ response,+ ): {+ accessToken: string+ refreshToken: string+ user: User+ totalMonthlyEvents: number+ } => response.data,+ ).catch((error) => {throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message})diff --git a/web/app/components/DashboardLockedBanner.tsx b/web/app/components/DashboardLockedBanner.tsxindex 10b6bdf3d..06bef4d17 100644--- a/web/app/components/DashboardLockedBanner.tsx+++ b/web/app/components/DashboardLockedBanner.tsx@@ -3,7 +3,7 @@ import { LockClosedIcon } from '@heroicons/react/24/outline'import { useSelector } from 'react-redux'import { StateType } from 'redux/store'import { useTranslation } from 'react-i18next'-import { DashboardBlockReason } from 'redux/models/IUser'+import { DashboardBlockReason } from 'redux/models/User'import Modal from 'ui/Modal'const DashboardLockedBanner = () => {diff --git a/web/app/components/Footer/index.tsx b/web/app/components/Footer/index.tsxindex 915561aad..a1e0cc1c4 100644--- a/web/app/components/Footer/index.tsx+++ b/web/app/components/Footer/index.tsx@@ -216,7 +216,7 @@ interface FooterProps {showDBIPMessage?: boolean}-const Footer = ({ authenticated, showDBIPMessage }: FooterProps): JSX.Element => {+const Footer = ({ authenticated, showDBIPMessage }: FooterProps) => {const {t,i18n: { language },diff --git a/web/app/components/GithubAuth.tsx b/web/app/components/GithubAuth.tsxindex 40b9b0196..2d33f22f0 100644--- a/web/app/components/GithubAuth.tsx+++ b/web/app/components/GithubAuth.tsx@@ -4,39 +4,24 @@ import { useSelector } from 'react-redux'import cx from 'clsx'import Button from 'ui/Button'-import { StateType, useAppDispatch } from 'redux/store/index'+import { StateType } from 'redux/store/index'import GithubDarkSVG from 'ui/icons/GithubDark'import GithubLightSVG from 'ui/icons/GithubLight'-import { SSO_PROVIDERS, isBrowser } from 'redux/constants'-import sagaActions from 'redux/sagas/actions'+import { isBrowser } from 'redux/constants'-interface IGoogleAuth {- setIsLoading: (isLoading: boolean) => void+interface GoogleAuthProps {ssrTheme: string- callback?: any- dontRemember?: booleanisMiniButton?: booleanclassName?: string+ onClick: () => void+ disabled?: boolean}-const GithubAuth: React.FC<IGoogleAuth> = ({- setIsLoading,- dontRemember,- callback = () => {},- isMiniButton,- className,- ssrTheme,-}) => {+const GithubAuth = ({ isMiniButton, className, ssrTheme, onClick, disabled }: GoogleAuthProps) => {const { t } = useTranslation()- const dispatch = useAppDispatch()const reduxTheme = useSelector((state: StateType) => state.ui.theme.theme)const theme = isBrowser ? reduxTheme : ssrTheme- const googleLogin = async () => {- setIsLoading(true)- dispatch(sagaActions.authSSO(SSO_PROVIDERS.GITHUB, Boolean(dontRemember), t, callback))- }-if (isMiniButton) {return (<Button@@ -45,11 +30,12 @@ const GithubAuth: React.FC<IGoogleAuth> = ({className,'bg-transparent ring-1 ring-slate-300 hover:bg-slate-100 dark:ring-slate-700 dark:hover:bg-slate-800/60',)}- onClick={googleLogin}+ onClick={onClick}secondaryregular+ disabled={disabled}>- {theme === 'dark' ? <GithubLightSVG className='h-5 w-5' /> : <GithubDarkSVG className='h-5 w-5' />}+ {theme === 'dark' ? <GithubLightSVG className='size-5' /> : <GithubDarkSVG className='size-5' />}</Button>)}@@ -60,12 +46,13 @@ const GithubAuth: React.FC<IGoogleAuth> = ({className,'flex items-center justify-center border-indigo-100 dark:border-slate-700/50 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700',)}- onClick={googleLogin}+ onClick={onClick}secondaryregular+ disabled={disabled}><>- {theme === 'dark' ? <GithubLightSVG className='mr-2 h-5 w-5' /> : <GithubDarkSVG className='mr-2 h-5 w-5' />}+ {theme === 'dark' ? <GithubLightSVG className='mr-2 size-5' /> : <GithubDarkSVG className='mr-2 size-5' />}{t('auth.common.github')}</></Button>diff --git a/web/app/components/GoogleAuth.tsx b/web/app/components/GoogleAuth.tsxindex c138ac28d..7f6a18f4b 100644--- a/web/app/components/GoogleAuth.tsx+++ b/web/app/components/GoogleAuth.tsx@@ -4,33 +4,17 @@ import cx from 'clsx'import Button from 'ui/Button'import GoogleGSVG from 'ui/icons/GoogleG'-import { SSO_PROVIDERS } from 'redux/constants'-import sagaActions from 'redux/sagas/actions'-import { useAppDispatch } from 'redux/store'-interface IGoogleAuth {- setIsLoading: (isLoading: boolean) => void- callback?: any- dontRemember?: boolean+interface GoogleAuthProps {+ onClick: () => voidisMiniButton?: booleanclassName?: string+ disabled?: boolean}-const GoogleAuth: React.FC<IGoogleAuth> = ({- setIsLoading,- dontRemember,- callback = () => {},- isMiniButton,- className,-}) => {- const dispatch = useAppDispatch()+const GoogleAuth = ({ onClick, isMiniButton, className, disabled }: GoogleAuthProps) => {const { t } = useTranslation()- const googleLogin = async () => {- setIsLoading(true)- dispatch(sagaActions.authSSO(SSO_PROVIDERS.GOOGLE, Boolean(dontRemember), t, callback))- }-if (isMiniButton) {return (<Button@@ -39,11 +23,12 @@ const GoogleAuth: React.FC<IGoogleAuth> = ({className,'bg-transparent ring-1 ring-slate-300 hover:bg-slate-100 dark:ring-slate-700 dark:hover:bg-slate-800/60',)}- onClick={googleLogin}+ onClick={onClick}+ disabled={disabled}secondaryregular>- <GoogleGSVG className='h-5 w-5' />+ <GoogleGSVG className='size-5' /></Button>)}@@ -54,12 +39,13 @@ const GoogleAuth: React.FC<IGoogleAuth> = ({className,'flex items-center justify-center border-indigo-100 dark:border-slate-700/50 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700',)}- onClick={googleLogin}+ onClick={onClick}secondaryregular+ disabled={disabled}><>- <GoogleGSVG className='mr-2 h-5 w-5' />+ <GoogleGSVG className='mr-2 size-5' />{t('auth.common.google')}</></Button>diff --git a/web/app/components/Header/index.tsx b/web/app/components/Header/index.tsxindex 02a710288..322dd54c2 100644--- a/web/app/components/Header/index.tsx+++ b/web/app/components/Header/index.tsx@@ -2,7 +2,7 @@import React, { memo, Fragment, useMemo, useState } from 'react'import { Link } from '@remix-run/react'-import { useDispatch, useSelector } from 'react-redux'+import { useSelector } from 'react-redux'import { useTranslation } from 'react-i18next'import i18next from 'i18next'import {@@ -40,7 +40,6 @@ import cx, { clsx } from 'clsx'import routes from 'utils/routes'import { authActions } from 'redux/reducers/auth'-import sagaActions from 'redux/sagas/actions'import UIActions from 'redux/reducers/ui'import {whitelist,@@ -54,8 +53,9 @@ import {} from 'redux/constants'import Dropdown from 'ui/Dropdown'import Flag from 'ui/Flag'-import { IUser } from 'redux/models/IUser'+import { User } from 'redux/models/User'import { useAppDispatch, StateType } from 'redux/store'+import { logout } from 'utils/auth'dayjs.extend(utc)dayjs.extend(duration)@@ -271,7 +271,7 @@ const ProfileMenu = ({onLanguageChange,language,}: {- user: IUser+ user: UserlogoutHandler: () => voidonLanguageChange: (l: string) => voidlanguage: string@@ -485,7 +485,7 @@ const AuthedHeader = ({colourBackground,openMenu,}: {- user: IUser+ user: UserswitchTheme: (thm?: string) => voidtheme: stringonLanguageChange: (lng: string) => void@@ -494,7 +494,7 @@ const AuthedHeader = ({logoutHandler: () => voidcolourBackground: booleanopenMenu: () => void-}): JSX.Element => {+}) => {const {t,i18n: { language },@@ -791,20 +791,19 @@ const NotAuthedHeader = ({)}-interface IHeader {+interface HeaderProps {ssrTheme: 'dark' | 'light'authenticated: booleanrefPage?: booleantransparent?: boolean}-const Header: React.FC<IHeader> = ({ ssrTheme, authenticated, refPage, transparent }): JSX.Element => {+const Header = ({ ssrTheme, authenticated, refPage, transparent }: HeaderProps) => {const {t,i18n: { language },} = useTranslation('common')const dispatch = useAppDispatch()- const _dispatch = useDispatch()const { user } = useSelector((state: StateType) => state.auth)const reduxTheme = useSelector((state: StateType) => state.ui.theme.theme)const [mobileMenuOpen, setMobileMenuOpen] = useState(false)@@ -849,7 +848,7 @@ const Header: React.FC<IHeader> = ({ ssrTheme, authenticated, refPage, transpareconst logoutHandler = () => {setMobileMenuOpen(false)dispatch(authActions.logout())- _dispatch(sagaActions.logout(false, false))+ logout()}const switchTheme = (_theme?: string) => {diff --git a/web/app/components/marketing/ComparisonTable.tsx b/web/app/components/marketing/ComparisonTable.tsxindex eabb1eb49..afca3dbce 100644--- a/web/app/components/marketing/ComparisonTable.tsx+++ b/web/app/components/marketing/ComparisonTable.tsx@@ -89,11 +89,11 @@ const COMPETITOR_FEATURE_TABLE: {},}-interface IComparisonTable {+interface ComparisonTableProps {className?: string}-export const ComparisonTable = ({ className }: IComparisonTable) => {+export const ComparisonTable = ({ className }: ComparisonTableProps) => {const { t } = useTranslation('common')return (diff --git a/web/app/components/marketing/DitchGoogle.tsx b/web/app/components/marketing/DitchGoogle.tsxindex 25affd302..4b1238118 100644--- a/web/app/components/marketing/DitchGoogle.tsx+++ b/web/app/components/marketing/DitchGoogle.tsx@@ -3,9 +3,8 @@ import { ArrowRightIcon } from '@heroicons/react/20/solid'import { Trans, useTranslation } from 'react-i18next'import routes from 'utils/routes'-import React from 'react'-interface IDitchGoogle {+interface DitchGoogleProps {screenshot: {light: stringdark: string@@ -13,7 +12,7 @@ interface IDitchGoogle {theme: 'dark' | 'light'}-export const DitchGoogle = ({ screenshot: { light, dark }, theme }: IDitchGoogle) => {+export const DitchGoogle = ({ screenshot: { light, dark }, theme }: DitchGoogleProps) => {const { t } = useTranslation('common')return (diff --git a/web/app/components/marketing/Lines.tsx b/web/app/components/marketing/Lines.tsxindex cb2ced2c6..2755faa66 100644--- a/web/app/components/marketing/Lines.tsx+++ b/web/app/components/marketing/Lines.tsx@@ -1,6 +1,6 @@import React from 'react'-export const Lines = (): JSX.Element => (+export const Lines = () => (<div className='pointer-events-none relative'><div className='absolute right-[-48rem] top-[32rem] h-px w-[800%] rotate-6 bg-gradient-to-l from-slate-600 opacity-10 dark:from-slate-400' /><div className='absolute -left-60 top-[22.26rem] ml-[-0.5px] h-96 w-[2px] rotate-[96deg] rounded-full bg-gradient-to-t from-emerald-600 opacity-50 dark:from-emerald-700 xl:top-[23.5rem]' />diff --git a/web/app/components/marketing/Pricing.tsx b/web/app/components/marketing/Pricing.tsxindex 2377c9c04..5b70d5950 100644--- a/web/app/components/marketing/Pricing.tsx+++ b/web/app/components/marketing/Pricing.tsx@@ -26,12 +26,12 @@ import {TRIAL_DAYS,} from 'redux/constants'import { authActions } from 'redux/reducers/auth'-import sagaActions from 'redux/sagas/actions'import { authMe, previewSubscriptionUpdate, changeSubscriptionPlan } from 'api'import routes from 'utils/routes'import { AppDispatch, StateType } from 'redux/store'import Loader from 'ui/Loader'import { Badge } from 'ui/Badge'+import { logout } from 'utils/auth'const getPaidFeatures = (t: any, tier: any) => {return [@@ -47,12 +47,12 @@ const getPaidFeatures = (t: any, tier: any) => {]}-interface IPricing {+interface PricingProps {authenticated: booleanisBillingPage?: boolean}-const Pricing = ({ authenticated, isBillingPage }: IPricing) => {+const Pricing = ({ authenticated, isBillingPage }: PricingProps) => {const {t,i18n: { language },@@ -107,13 +107,13 @@ const Pricing = ({ authenticated, isBillingPage }: IPricing) => {// giving some time to the API to process tier upgrate via Paddle webhooksetTimeout(async () => {try {- const me = await authMe()+ const { user } = await authMe()- dispatch(authActions.authSuccessful(me))+ dispatch(authActions.authSuccessful(user))dispatch(authActions.finishLoading())} catch (reason) {dispatch(authActions.logout())- dispatch(sagaActions.logout(false, false))+ logout()console.error(`[ERROR] Error while getting user after subscription update: ${reason}`)}@@ -202,13 +202,13 @@ const Pricing = ({ authenticated, isBillingPage }: IPricing) => {await changeSubscriptionPlan(newPlanId as number)try {- const me = await authMe()+ const { user } = await authMe()- dispatch(authActions.authSuccessful(me))+ dispatch(authActions.authSuccessful(user))dispatch(authActions.finishLoading())} catch (reason) {dispatch(authActions.logout())- dispatch(sagaActions.logout(false, false))+ logout()console.error(`[ERROR] Error while getting user after subscription update: ${reason}`)}diff --git a/web/app/modals/Forecast.tsx b/web/app/modals/Forecast.tsxindex 521034c84..44c7a6692 100644--- a/web/app/modals/Forecast.tsx+++ b/web/app/modals/Forecast.tsx@@ -12,7 +12,7 @@ import { Bars3BottomRightIcon, ChartBarIcon } from '@heroicons/react/24/outline'const DEFAULT_PERIOD = '3'-interface IForecast {+interface ForecastProps {onClose: () => voidonSubmit: (type: 'chart' | 'details',@@ -25,7 +25,7 @@ interface IForecast {tb: string}-const Forecast = ({ onClose, onSubmit, isOpened, activeTB, tb }: IForecast): JSX.Element => {+const Forecast = ({ onClose, onSubmit, isOpened, activeTB, tb }: ForecastProps) => {const { t } = useTranslation('common')const [period, setPeriod] = useState(DEFAULT_PERIOD)const [error, setError] = useState<string | null>(null)diff --git a/web/app/modals/NewFunnel.tsx b/web/app/modals/NewFunnel.tsxindex d04d19cd7..0ad74c499 100644--- a/web/app/modals/NewFunnel.tsx+++ b/web/app/modals/NewFunnel.tsx@@ -11,18 +11,18 @@ import Input from 'ui/Input'import Combobox from 'ui/Combobox'import { MIN_FUNNEL_STEPS, MAX_FUNNEL_STEPS } from 'redux/constants'import { getFilters } from 'api'-import { IFunnel } from 'redux/models/IProject'-import { IProjectForShared } from 'redux/models/ISharedProject'+import { Funnel } from 'redux/models/Project'+import { ProjectForShared } from 'redux/models/SharedProject'-interface INewFunnel {- project: IProjectForShared+interface NewFunnelProps {+ project: ProjectForSharedonClose: () => voidonSubmit: (name: string, steps: string[]) => Promise<void>isOpened: booleanpid: stringloading: booleanallowedToManage: boolean- funnel?: IFunnel+ funnel?: FunnelprojectPassword?: string}@@ -38,7 +38,7 @@ const NewFunnel = ({project,projectPassword,allowedToManage,-}: INewFunnel): JSX.Element => {+}: NewFunnelProps) => {const { t } = useTranslation('common')const [name, setName] = useState(funnel?.name || '')const [steps, setSteps] = useState<any[]>(funnel?.steps || INITIAL_FUNNEL_STEPS)diff --git a/web/app/modals/PaidFeature.tsx b/web/app/modals/PaidFeature.tsxindex 1fd8227b5..666e87267 100644--- a/web/app/modals/PaidFeature.tsx+++ b/web/app/modals/PaidFeature.tsx@@ -5,12 +5,12 @@ import { useTranslation } from 'react-i18next'import Modal from 'ui/Modal'import routes from 'utils/routes'-interface IPaidFeature {+interface PaidFeatureProps {onClose: () => voidisOpened: boolean}-const PaidFeature = ({ onClose, isOpened }: IPaidFeature): JSX.Element => {+const PaidFeature = ({ onClose, isOpened }: PaidFeatureProps) => {const { t } = useTranslation('common')const navigate = useNavigate()diff --git a/web/app/modals/TrackingSnippet.tsx b/web/app/modals/TrackingSnippet.tsxindex 15c447a31..83f28bc7f 100644--- a/web/app/modals/TrackingSnippet.tsx+++ b/web/app/modals/TrackingSnippet.tsx@@ -8,7 +8,7 @@ import { API_URL, isSelfhosted } from 'redux/constants'const API_URL_WITHOUT_TRAILING_SLASH = API_URL.endsWith('/') ? API_URL.slice(0, -1) : API_URL-interface ITrackingSnippet {+interface TrackingSnippetProps {onClose: () => voidisOpened: booleanpid: string@@ -54,7 +54,7 @@ const getSnippet = (pid: string) => {const SCRIPT_DOCS_URL = 'https://docs.swetrix.com/install-script'-const TrackingSnippet = ({ onClose, isOpened, pid }: ITrackingSnippet): JSX.Element => {+const TrackingSnippet = ({ onClose, isOpened, pid }: TrackingSnippetProps) => {const { t } = useTranslation('common')const snippet = getSnippet(pid)diff --git a/web/app/modals/ViewProjectHotkeys.tsx b/web/app/modals/ViewProjectHotkeys.tsxindex cc8299451..287d7ba75 100644--- a/web/app/modals/ViewProjectHotkeys.tsx+++ b/web/app/modals/ViewProjectHotkeys.tsx@@ -6,12 +6,12 @@ import _map from 'lodash/map'import Modal from 'ui/Modal'import { Badge } from 'ui/Badge'-interface IViewProjectHotkeys {+interface ViewProjectHotkeysProps {onClose: () => voidisOpened: boolean}-interface IHotkeysList {+interface HotkeysListProps {title: stringhotkeys: { [key: string]: string }}@@ -49,7 +49,7 @@ const getHotkeys = (t: TFunction) => ({},})-const HotkeysList = ({ title, hotkeys }: IHotkeysList) => (+const HotkeysList = ({ title, hotkeys }: HotkeysListProps) => (<div className='mt-2 first:mt-0'><table className='min-w-full divide-y divide-gray-300 dark:divide-gray-700'><thead>@@ -74,7 +74,7 @@ const HotkeysList = ({ title, hotkeys }: IHotkeysList) => (</div>)-const ViewProjectHotkeys = ({ onClose, isOpened }: IViewProjectHotkeys): JSX.Element => {+const ViewProjectHotkeys = ({ onClose, isOpened }: ViewProjectHotkeysProps) => {const { t } = useTranslation('common')const hotkeys = useMemo(() => getHotkeys(t), [t])diff --git a/web/app/pages/About/index.tsx b/web/app/pages/About/index.tsxindex 5c6382104..704f9412d 100644--- a/web/app/pages/About/index.tsx+++ b/web/app/pages/About/index.tsx@@ -1,11 +1,10 @@-/* eslint-disable */import React from 'react'import _map from 'lodash/map'import { CONTACT_EMAIL, GITHUB_URL } from 'redux/constants'const socialIcons: {- [key: string]: JSX.Element+ [key: string]: React.ReactNode} = {LinkedIn: (<img@@ -35,7 +34,7 @@ const socialIcons: {),}-interface ITeammate {+interface TeammateProps {photo: stringname: stringrole: string@@ -45,7 +44,7 @@ interface ITeammate {desc: string}-const Teammate = ({ photo, name, role, socials, desc }: ITeammate): JSX.Element => (+const Teammate = ({ photo, name, role, socials, desc }: TeammateProps) => (<div className='flex flex-col py-6 md:flex-row md:gap-x-8'><div className='flex justify-center md:w-2/5'><img@@ -123,7 +122,7 @@ const team = [},] as const-const About = (): JSX.Element => (+const About = () => (<div><div className='min-h-min-footer bg-gray-50 dark:bg-slate-900'><div className='mx-auto max-w-7xl whitespace-pre-line px-4 pb-16 pt-12 sm:px-6 lg:px-8'>diff --git a/web/app/pages/Auth/CheckYourInbox/CheckYourInbox.tsx b/web/app/pages/Auth/CheckYourInbox/CheckYourInbox.tsxindex 970411a84..1d8f09068 100644--- a/web/app/pages/Auth/CheckYourInbox/CheckYourInbox.tsx+++ b/web/app/pages/Auth/CheckYourInbox/CheckYourInbox.tsx@@ -2,21 +2,20 @@ import React, { useMemo, useEffect } from 'react'import { useNavigate } from '@remix-run/react'import { useTranslation, Trans } from 'react-i18next'import { EnvelopeIcon } from '@heroicons/react/24/outline'-import { useSelector, useDispatch } from 'react-redux'+import { useSelector } from 'react-redux'import Loader from 'ui/Loader'import { withAuthentication } from 'hoc/protected'import { authActions } from 'redux/reducers/auth'-import sagaActions from 'redux/sagas/actions'import { StateType, useAppDispatch } from 'redux/store'import routes from 'utils/routes'+import { logout } from 'utils/auth'const CheckYourInbox = () => {const { t } = useTranslation('common')const { loading, user } = useSelector((state: StateType) => state.auth)const navigate = useNavigate()const dispatch = useAppDispatch()- const _dispatch = useDispatch()const message = useMemo(() => {return t('auth.confirm.linkSent', { email: user?.email })@@ -68,7 +67,7 @@ const CheckYourInbox = () => {className='cursor-pointer font-medium text-indigo-600 hover:underline dark:text-indigo-400'onClick={() => {dispatch(authActions.logout())- _dispatch(sagaActions.logout(false, false))+ logout()}}/>),diff --git a/web/app/pages/Auth/Signin/Signin.tsx b/web/app/pages/Auth/Signin/Signin.tsxindex a3324e1e6..43cdacb0f 100644--- a/web/app/pages/Auth/Signin/Signin.tsx+++ b/web/app/pages/Auth/Signin/Signin.tsx@@ -1,7 +1,8 @@import React, { useState, useEffect, memo } from 'react'-import { Link } from '@remix-run/react'+import { Link, useNavigate, useSearchParams } from '@remix-run/react'import { useTranslation, Trans } from 'react-i18next'import _keys from 'lodash/keys'+import _omit from 'lodash/omit'import _isEmpty from 'lodash/isEmpty'import _isString from 'lodash/isString'import { toast } from 'sonner'@@ -14,13 +15,17 @@ import Input from 'ui/Input'import Button from 'ui/Button'import Checkbox from 'ui/Checkbox'import { isValidEmail, isValidPassword, MIN_PASSWORD_CHARS } from 'utils/validator'-import { isSelfhosted, TRIAL_DAYS } from 'redux/constants'-import { submit2FA } from 'api'+import { isSelfhosted, REFERRAL_COOKIE, TRIAL_DAYS } from 'redux/constants'+import { generateSSOAuthURL, getInstalledExtensions, getJWTBySSOHash, login, submit2FA } from 'api'import { setAccessToken, removeAccessToken } from 'utils/accessToken'import { setRefreshToken, removeRefreshToken } from 'utils/refreshToken'import { useAppDispatch } from 'redux/store'import { authActions } from 'redux/reducers/auth'-import sagaActions from 'redux/sagas/actions'+import { delay, openBrowserWindow } from 'utils/generic'+import { deleteCookie, getCookie } from 'utils/cookie'+import { shouldShowLowEventsBanner } from 'utils/auth'+import UIActions from 'redux/reducers/ui'+import { SSOProvider } from 'redux/models/Auth'interface SigninForm {email: string@@ -32,8 +37,12 @@ interface SigninProps {ssrTheme: string}+const HASH_CHECK_FREQUENCY = 1000+const Signin = ({ ssrTheme }: SigninProps) => {const dispatch = useAppDispatch()+ const navigate = useNavigate()+ const [searchParams] = useSearchParams()const { t } = useTranslation('common')const [form, setForm] = useState<SigninForm>({email: '',@@ -47,7 +56,7 @@ const Signin = ({ ssrTheme }: SigninProps) => {}>({})const [beenSubmitted, setBeenSubmitted] = useState(false)const [isLoading, setIsLoading] = useState(false)- const [isTwoFARequired, setIsTwoFARequired] = useState(false)+ const [isTwoFARequired, setIsTwoFARequired] = useState(searchParams.get('show_2fa_screen') === 'true')const [twoFACode, setTwoFACode] = useState('')const [twoFACodeError, setTwoFACodeError] = useState<string | null>(null)@@ -83,17 +92,125 @@ const Signin = ({ ssrTheme }: SigninProps) => {setTwoFACodeError(null)}- const loginCallback = (result: boolean, twoFARequired: boolean) => {- if (!result) {+ const onSsoLogin = async (provider: SSOProvider) => {+ const authWindow = openBrowserWindow('')++ if (!authWindow) {+ toast.error(t('apiNotifications.socialisationAuthGenericError'))+ setIsLoading(false)+ return+ }++ try {+ const { uuid, auth_url: authUrl, expires_in: expiresIn } = await generateSSOAuthURL(provider)++ authWindow.location = authUrl++ // Closing the authorisation window after the session expires+ setTimeout(authWindow.close, expiresIn)++ const refCode = getCookie(REFERRAL_COOKIE) as string++ // eslint-disable-next-line no-constant-condition+ while (true) {+ await delay(HASH_CHECK_FREQUENCY)++ try {+ const { accessToken, refreshToken, user, totalMonthlyEvents } = await getJWTBySSOHash(uuid, provider, refCode)+ authWindow.close()++ if (refCode) {+ deleteCookie(REFERRAL_COOKIE)+ }++ if (user.isTwoFactorAuthenticationEnabled) {+ setAccessToken(accessToken, true)+ setRefreshToken(refreshToken)+ dispatch(authActions.mergeUser(user))+ setIsTwoFARequired(true)+ setIsLoading(false)+ return+ }++ dispatch(authActions.authSuccessful(user))+ setAccessToken(accessToken, false)+ setRefreshToken(refreshToken)++ if (shouldShowLowEventsBanner(totalMonthlyEvents, user.maxEventsCount)) {+ dispatch(UIActions.setShowNoEventsLeftBanner(true))+ }++ await loadExtensions()++ dispatch(authActions.finishLoading())++ navigate(routes.dashboard)++ return+ } catch (reason) {+ // Authentication is not finished yet+ }++ if (authWindow.closed) {+ setIsLoading(false)+ return+ }+ }+ } catch (reason) {+ toast.error(typeof reason === 'string' ? reason : t('apiNotifications.socialisationGenericError'))setIsLoading(false)- setIsTwoFARequired(twoFARequired)+ return}}- const onSubmit = (data: SigninForm) => {- if (!isLoading) {- setIsLoading(true)- dispatch(sagaActions.loginAsync(data, loginCallback))+ const loadExtensions = async () => {+ if (isSelfhosted) {+ return+ }++ const extensions = await getInstalledExtensions()+ dispatch(UIActions.setExtensions(extensions))+ }++ const onSubmit = async (data: SigninForm) => {+ if (isLoading) {+ return+ }++ setIsLoading(true)++ try {+ const { dontRemember } = data++ const { user, accessToken, refreshToken, totalMonthlyEvents } = await login(_omit(data, ['dontRemember']))++ dispatch(authActions.setDontRemember(dontRemember))++ if (user.isTwoFactorAuthenticationEnabled) {+ setAccessToken(accessToken, true)+ setRefreshToken(refreshToken, true)+ dispatch(authActions.mergeUser(user))+ setIsTwoFARequired(true)+ setIsLoading(false)+ return+ }++ dispatch(authActions.authSuccessful(user))+ setAccessToken(accessToken, dontRemember)+ setRefreshToken(refreshToken)++ if (shouldShowLowEventsBanner(totalMonthlyEvents, user.maxEventsCount)) {+ dispatch(UIActions.setShowNoEventsLeftBanner(true))+ }++ await loadExtensions()++ setIsLoading(false)+ } catch (reason) {+ toast.error(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))+ setIsLoading(false)+ } finally {+ dispatch(authActions.finishLoading())}}@@ -110,6 +227,7 @@ const Signin = ({ ssrTheme }: SigninProps) => {removeRefreshToken()setAccessToken(accessToken)setRefreshToken(refreshToken)+ await loadExtensions()dispatch(authActions.authSuccessful(user))} catch (reason) {if (_isString(reason)) {@@ -253,13 +371,8 @@ const Signin = ({ ssrTheme }: SigninProps) => {</div></div><div className='mt-6 grid grid-cols-2 gap-4'>- <GoogleAuth setIsLoading={setIsLoading} callback={loginCallback} dontRemember={false} />- <GithubAuth- setIsLoading={setIsLoading}- callback={loginCallback}- dontRemember={false}- ssrTheme={ssrTheme}- />+ <GoogleAuth onClick={() => onSsoLogin('google')} disabled={isLoading} />+ <GithubAuth onClick={() => onSsoLogin('github')} ssrTheme={ssrTheme} disabled={isLoading} /></div></div>)}diff --git a/web/app/pages/Auth/Signup/Signup.tsx b/web/app/pages/Auth/Signup/Signup.tsxindex 1eee9dad3..460e9b501 100644--- a/web/app/pages/Auth/Signup/Signup.tsx+++ b/web/app/pages/Auth/Signup/Signup.tsx@@ -6,7 +6,7 @@ import _keys from 'lodash/keys'import _omit from 'lodash/omit'import _isEmpty from 'lodash/isEmpty'-import { getAccessToken } from 'utils/accessToken'+import { getAccessToken, setAccessToken } from 'utils/accessToken'import GoogleAuth from 'components/GoogleAuth'import GithubAuth from 'components/GithubAuth'import routes from 'utils/routes'@@ -15,11 +15,19 @@ import Checkbox from 'ui/Checkbox'import Tooltip from 'ui/Tooltip'import Button from 'ui/Button'import { isValidEmail, isValidPassword, MIN_PASSWORD_CHARS, MAX_PASSWORD_CHARS } from 'utils/validator'-import { HAVE_I_BEEN_PWNED_URL, TRIAL_DAYS } from 'redux/constants'+import { HAVE_I_BEEN_PWNED_URL, REFERRAL_COOKIE, TRIAL_DAYS } from 'redux/constants'import { trackCustom } from 'utils/analytics'import { StateType, useAppDispatch } from 'redux/store'-import sagaActions from 'redux/sagas/actions'import { useSelector } from 'react-redux'+import { delay, openBrowserWindow } from 'utils/generic'+import { toast } from 'sonner'+import { generateSSOAuthURL, getJWTBySSOHash, signup } from 'api'+import { deleteCookie, getCookie } from 'utils/cookie'+import { authActions } from 'redux/reducers/auth'+import { setRefreshToken } from 'utils/refreshToken'+import { shouldShowLowEventsBanner } from 'utils/auth'+import UIActions from 'redux/reducers/ui'+import { SSOProvider } from 'redux/models/Auth'interface SignupForm {email: string@@ -30,11 +38,13 @@ interface SignupForm {checkIfLeaked: boolean}-interface ISignup {+interface SignupProps {ssrTheme: string}-const Signup = ({ ssrTheme }: ISignup) => {+const HASH_CHECK_FREQUENCY = 1000++const Signup = ({ ssrTheme }: SignupProps) => {const dispatch = useAppDispatch()const { authenticated: reduxAuthenticated, loading } = useSelector((state: StateType) => state.auth)const { t } = useTranslation('common')@@ -104,21 +114,111 @@ const Signup = ({ ssrTheme }: ISignup) => {// eslint-disable-next-line react-hooks/exhaustive-deps}, [authenticated, beenSubmitted])- const signUpCallback = (result: any) => {- if (result) {+ const onSubmit = async (data: SignupForm) => {+ if (isLoading) {+ return+ }++ setIsLoading(true)++ try {+ const { dontRemember } = data++ const refCode = getCookie(REFERRAL_COOKIE)++ const { user, accessToken, refreshToken } = await signup({+ ..._omit(data, ['dontRemember']),+ refCode: refCode || undefined,+ })++ if (refCode) {+ deleteCookie(REFERRAL_COOKIE)+ }++ dispatch(authActions.authSuccessful(user))+ dispatch(authActions.setDontRemember(dontRemember))+ setAccessToken(accessToken, dontRemember)+ setRefreshToken(refreshToken)+ setIsLoading(false)+trackCustom('SIGNUP', {from: 'Signup page',})navigate(routes.confirm_email)- } else {+ } catch (reason) {+ toast.error(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))setIsLoading(false)+ } finally {+ dispatch(authActions.finishLoading())}}- const onSubmit = (data: SignupForm) => {- if (!isLoading) {- setIsLoading(true)- dispatch(sagaActions.signupAsync(_omit(data, 'tos'), t, signUpCallback))+ const onSsoLogin = async (provider: SSOProvider) => {+ const authWindow = openBrowserWindow('')++ if (!authWindow) {+ toast.error(t('apiNotifications.socialisationAuthGenericError'))+ setIsLoading(false)+ return+ }++ try {+ const { uuid, auth_url: authUrl, expires_in: expiresIn } = await generateSSOAuthURL(provider)++ authWindow.location = authUrl++ // Closing the authorisation window after the session expires+ setTimeout(authWindow.close, expiresIn)++ const refCode = getCookie(REFERRAL_COOKIE) as string++ // eslint-disable-next-line no-constant-condition+ while (true) {+ await delay(HASH_CHECK_FREQUENCY)++ try {+ const { accessToken, refreshToken, user, totalMonthlyEvents } = await getJWTBySSOHash(uuid, provider, refCode)+ authWindow.close()++ if (refCode) {+ deleteCookie(REFERRAL_COOKIE)+ }++ if (user.isTwoFactorAuthenticationEnabled) {+ setAccessToken(accessToken, true)+ setRefreshToken(refreshToken)+ dispatch(authActions.mergeUser(user))+ navigate(`${routes.signin}?show_2fa_screen=true`)+ setIsLoading(false)+ return+ }++ dispatch(authActions.authSuccessful(user))+ setAccessToken(accessToken, false)+ setRefreshToken(refreshToken)++ if (shouldShowLowEventsBanner(totalMonthlyEvents, user.maxEventsCount)) {+ dispatch(UIActions.setShowNoEventsLeftBanner(true))+ }++ dispatch(authActions.finishLoading())++ navigate(routes.dashboard)++ return+ } catch (reason) {+ // Authentication is not finished yet+ }++ if (authWindow.closed) {+ setIsLoading(false)+ return+ }+ }+ } catch (reason) {+ toast.error(typeof reason === 'string' ? reason : t('apiNotifications.socialisationGenericError'))+ setIsLoading(false)+ return}}@@ -272,13 +372,8 @@ const Signup = ({ ssrTheme }: ISignup) => {</div></div><div className='mt-6 grid grid-cols-2 gap-4'>- <GoogleAuth setIsLoading={setIsLoading} callback={signUpCallback} dontRemember={false} />- <GithubAuth- setIsLoading={setIsLoading}- callback={signUpCallback}- dontRemember={false}- ssrTheme={ssrTheme}- />+ <GoogleAuth onClick={() => onSsoLogin('google')} disabled={isLoading} />+ <GithubAuth onClick={() => onSsoLogin('github')} ssrTheme={ssrTheme} disabled={isLoading} /></div></div></div>diff --git a/web/app/pages/Auth/VerifyEmail/index.tsx b/web/app/pages/Auth/VerifyEmail/index.tsxindex 4e8d3215e..d4ddaa458 100644--- a/web/app/pages/Auth/VerifyEmail/index.tsx+++ b/web/app/pages/Auth/VerifyEmail/index.tsx@@ -4,11 +4,11 @@ import { useParams, Link } from '@remix-run/react'import { useTranslation } from 'react-i18next'import { CheckCircleIcon, XCircleIcon } from '@heroicons/react/24/solid'import _isString from 'lodash/isString'-import _isArray from 'lodash/isArray'-import sagaActions from 'redux/sagas/actions'import Loader from 'ui/Loader'import routes from 'utils/routes'+import { verifyEmail } from 'api'+import { authActions } from 'redux/reducers/auth'const VerifyEmail = () => {const { t } = useTranslation('common')@@ -26,27 +26,19 @@ const VerifyEmail = () => {return}- dispatch(- sagaActions.emailVerifyAsync(- {- id,- },- () => {- setLoading(false)- },- (verifyError: any) => {- if (_isArray(verifyError)) {- setError(verifyError[0])- } else if (_isString(verifyError)) {- setError(verifyError)- } else {- setError(verifyError?.message || t('auth.verification.invalid'))- }+ const verify = async () => {+ try {+ await verifyEmail({ id })+ dispatch(authActions.mergeUser({ isActive: true }))+ } catch (reason: any) {+ setError(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))+ } finally {+ dispatch(authActions.finishLoading())+ setLoading(false)+ }+ }- setLoading(false)- },- ),- )+ verify()}, [id]) // eslint-disable-lineif (loading) {diff --git a/web/app/pages/Billing/index.tsx b/web/app/pages/Billing/index.tsxindex 89f81d082..9134bc79d 100644--- a/web/app/pages/Billing/index.tsx+++ b/web/app/pages/Billing/index.tsx@@ -1,6 +1,6 @@import React, { memo, useMemo, useState, useEffect } from 'react'import { useTranslation, Trans } from 'react-i18next'-import { useSelector, useDispatch } from 'react-redux'+import { useSelector } from 'react-redux'import dayjs from 'dayjs'import utc from 'dayjs/plugin/utc'import duration from 'dayjs/plugin/duration'@@ -18,7 +18,6 @@ import {import { loadScript } from 'utils/generic'import Loader from 'ui/Loader'import { useAppDispatch, StateType } from 'redux/store'-import sagaActions from 'redux/sagas/actions'import { withAuthentication, auth } from 'hoc/protected'import Modal from 'ui/Modal'import Button from 'ui/Button'@@ -27,25 +26,38 @@ import Tooltip from 'ui/Tooltip'import UIActions from 'redux/reducers/ui'import Pricing from '../../components/marketing/Pricing'import DashboardLockedBanner from 'components/DashboardLockedBanner'+import { UsageInfo } from 'redux/models/Usageinfo'+import { getUsageInfo } from 'api'+import { toast } from 'sonner'dayjs.extend(utc)dayjs.extend(duration)-interface IBilling {+interface BillingProps {ssrAuthenticated: booleanssrTheme: 'dark' | 'light'}-const Billing = ({ ssrAuthenticated, ssrTheme }: IBilling) => {+const Billing = ({ ssrAuthenticated, ssrTheme }: BillingProps) => {const [isCancelSubModalOpened, setIsCancelSubModalOpened] = useState(false)- const { metainfo, usageinfo } = useSelector((state: StateType) => state.ui.misc)- const { user, loading } = useSelector((state: StateType) => state.auth)+ const { metainfo } = useSelector((state: StateType) => state.ui.misc)+ const { user, loading: authLoading } = useSelector((state: StateType) => state.auth)const { theme: reduxTheme } = useSelector((state: StateType) => state.ui.theme)const theme = isBrowser ? reduxTheme : ssrThemeconst paddleLoaded = useSelector((state: StateType) => state.ui.misc.paddleLoaded)const reduxAuthenticated = useSelector((state: StateType) => state.auth.authenticated)- const dispatch = useDispatch()- const _dispatch = useAppDispatch()+ const [usageInfo, setUsageInfo] = useState<UsageInfo>({+ total: 0,+ traffic: 0,+ errors: 0,+ customEvents: 0,+ captcha: 0,+ trafficPerc: 0,+ errorsPerc: 0,+ customEventsPerc: 0,+ captchaPerc: 0,+ })+ const dispatch = useAppDispatch()const {t,i18n: { language },@@ -65,7 +77,10 @@ const Billing = ({ ssrAuthenticated, ssrTheme }: IBilling) => {const isSubscriber = user.planCode !== 'none' && user.planCode !== 'trial' && user.planCode !== 'free'const isTrial = planCode === 'trial'const isNoSub = planCode === 'none'- const totalUsage = _round((usageinfo.total / maxEventsCount) * 100, 2) || 0++ const totalUsage = _round((usageInfo.total / maxEventsCount) * 100, 2) || 0++ const [isLoading, setIsLoading] = useState(true)// Paddle (payment processor) set-upuseEffect(() => {@@ -76,7 +91,7 @@ const Billing = ({ ssrAuthenticated, ssrTheme }: IBilling) => {loadScript(PADDLE_JS_URL)const eventCallback = (data: any) => {- _dispatch(UIActions.setPaddleLastEvent(data))+ dispatch(UIActions.setPaddleLastEvent(data))}// eslint-disable-next-line no-use-before-defineconst interval = setInterval(paddleSetup, 200)@@ -95,9 +110,30 @@ const Billing = ({ ssrAuthenticated, ssrTheme }: IBilling) => {}}, [paddleLoaded]) // eslint-disable-line+ const loadUsageInfo = async () => {+ if (!isLoading) {+ return+ }++ try {+ const result = await getUsageInfo()+ setUsageInfo(result)+ } catch (reason: any) {+ toast.error(typeof reason === 'string' ? reason : t('apiNotifications.failedToLoadUsageInfo'))+ } finally {+ setIsLoading(false)+ }+ }+useEffect(() => {- dispatch(sagaActions.loadUsageinfo())- }, [dispatch])+ if (authLoading) {+ return+ }++ loadUsageInfo()++ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [authLoading])const isTrialEnded = useMemo(() => {if (!trialEndDate) {@@ -269,7 +305,7 @@ const Billing = ({ ssrAuthenticated, ssrTheme }: IBilling) => {</div>)}- {loading ? (+ {isLoading ? (<Loader />) : (<div className='mt-8 flex flex-col'>@@ -298,13 +334,13 @@ const Billing = ({ ssrAuthenticated, ssrTheme }: IBilling) => {{t('billing.planUsageDesc')}</p>- {loading ? (+ {isLoading ? (<Loader />) : (<div className='mt-2 text-lg tracking-tight text-gray-900 dark:text-gray-50'><p className='mb-1 text-base font-medium tracking-tight text-gray-900 dark:text-gray-50'>{t('billing.xofy', {- x: usageinfo.total || 0,+ x: usageInfo.total || 0,y: maxEventsCount || 0,})}</p>@@ -314,7 +350,7 @@ const Billing = ({ ssrAuthenticated, ssrTheme }: IBilling) => {<div><p>{t('billing.usageOverview', {- tracked: usageinfo.total || 0,+ tracked: usageInfo.total || 0,trackedPerc: totalUsage || 0,maxEvents: maxEventsCount || 0,})}@@ -322,26 +358,26 @@ const Billing = ({ ssrAuthenticated, ssrTheme }: IBilling) => {<ul className='mt-2 list-inside list-disc'><li className='marker:text-blue-600 dark:marker:text-blue-800'>{t('billing.pageviews', {- quantity: usageinfo.traffic || 0,- percentage: usageinfo.trafficPerc || 0,+ quantity: usageInfo.traffic || 0,+ percentage: usageInfo.trafficPerc || 0,})}</li><li className='marker:text-fuchsia-600 dark:marker:text-fuchsia-800'>{t('billing.customEvents', {- quantity: usageinfo.customEvents || 0,- percentage: usageinfo.customEventsPerc || 0,+ quantity: usageInfo.customEvents || 0,+ percentage: usageInfo.customEventsPerc || 0,})}</li><li className='marker:text-lime-600 dark:marker:text-lime-800'>{t('billing.captcha', {- quantity: usageinfo.captcha || 0,- percentage: usageinfo.captchaPerc || 0,+ quantity: usageInfo.captcha || 0,+ percentage: usageInfo.captchaPerc || 0,})}</li><li className='marker:text-red-600 dark:marker:text-red-800'>{t('billing.errors', {- quantity: usageinfo.errors || 0,- percentage: usageinfo.errorsPerc || 0,+ quantity: usageInfo.errors || 0,+ percentage: usageInfo.errorsPerc || 0,})}</li></ul>@@ -353,17 +389,17 @@ const Billing = ({ ssrAuthenticated, ssrTheme }: IBilling) => {className='w-[85vw] max-w-[25rem]'progress={[{- value: usageinfo.traffic === 0 ? 0 : (usageinfo.traffic / maxEventsCount) * 100,+ value: usageInfo.traffic === 0 ? 0 : (usageInfo.traffic / maxEventsCount) * 100,lightColour: '#2563eb',darkColour: '#1d4ed8',},{- value: usageinfo.customEvents === 0 ? 0 : (usageinfo.customEvents / maxEventsCount) * 100,+ value: usageInfo.customEvents === 0 ? 0 : (usageInfo.customEvents / maxEventsCount) * 100,lightColour: '#c026d3',darkColour: '#a21caf',},{- value: usageinfo.captcha === 0 ? 0 : (usageinfo.captcha / maxEventsCount) * 100,+ value: usageInfo.captcha === 0 ? 0 : (usageInfo.captcha / maxEventsCount) * 100,lightColour: '#65a30d',darkColour: '#4d7c0f',},diff --git a/web/app/pages/Blog/Post.tsx b/web/app/pages/Blog/Post.tsxindex 67fd33fab..647634429 100644--- a/web/app/pages/Blog/Post.tsx+++ b/web/app/pages/Blog/Post.tsx@@ -3,7 +3,7 @@ import { Link, useLoaderData, useLocation } from '@remix-run/react'import NotFound from 'pages/NotFound'import { trackPageview } from 'utils/analytics'-interface IPost {+interface Post {slug: stringtitle?: stringhtml: string@@ -16,7 +16,7 @@ interface IPost {export default function PostSlug() {const location = useLocation()- const post = useLoaderData() as IPost+ const post = useLoaderData() as PostuseEffect(() => {const meta = post.authordiff --git a/web/app/pages/Captcha/Settings/CaptchaSettings.tsx b/web/app/pages/Captcha/Settings/CaptchaSettings.tsxindex 737a35bf2..893de2cb3 100644--- a/web/app/pages/Captcha/Settings/CaptchaSettings.tsx+++ b/web/app/pages/Captcha/Settings/CaptchaSettings.tsx@@ -31,7 +31,7 @@ import Checkbox from 'ui/Checkbox'import Modal from 'ui/Modal'import { trackCustom } from 'utils/analytics'import routes from 'utils/routes'-import { ICaptchaProject } from 'redux/models/IProject'+import { CaptchaProject } from 'redux/models/Project'import { useRequiredParams } from 'hooks/useRequiredParams'import { useSelector } from 'react-redux'import { StateType } from 'redux/store'@@ -40,8 +40,7 @@ const MAX_NAME_LENGTH = 50const MAX_ORIGINS_LENGTH = 300const MAX_IPBLACKLIST_LENGTH = 300-// add to interface IProject new fields isCaptcha-interface IForm extends Partial<ICaptchaProject> {+interface Form extends Partial<CaptchaProject> {isCaptcha?: booleanid: stringname: string@@ -53,7 +52,7 @@ interface CaptchaSettingsProps {isSettings: boolean}-const CaptchaSettings = ({ isSettings }: CaptchaSettingsProps): JSX.Element => {+const CaptchaSettings = ({ isSettings }: CaptchaSettingsProps) => {const { loading: authLoading } = useSelector((state: StateType) => state.auth)const { t } = useTranslation('common')@@ -61,7 +60,7 @@ const CaptchaSettings = ({ isSettings }: CaptchaSettingsProps): JSX.Element => {id: string}>()const navigate = useNavigate()- const [form, setForm] = useState<IForm>({+ const [form, setForm] = useState<Form>({name: '',id,public: false,@@ -83,7 +82,7 @@ const CaptchaSettings = ({ isSettings }: CaptchaSettingsProps): JSX.Element => {const [captchaSecretKey, setCaptchaSecretKey] = useState<string | null>(null)const [showRegenerateSecret, setShowRegenerateSecret] = useState(false)- const [project, setProject] = useState<ICaptchaProject | null>(null)+ const [project, setProject] = useState<CaptchaProject | null>(null)const [isLoading, setIsLoading] = useState(false)const [error, setError] = useState<string | null>(null)@@ -94,7 +93,7 @@ const CaptchaSettings = ({ isSettings }: CaptchaSettingsProps): JSX.Element => {setIsLoading(true)try {- const result = (await getProject(projectId)) as ICaptchaProject+ const result = (await getProject(projectId)) as CaptchaProjectsetProject(result)setCaptchaSecretKey(result.captchaSecretKey)setForm({@@ -119,11 +118,11 @@ const CaptchaSettings = ({ isSettings }: CaptchaSettingsProps): JSX.Element => {// eslint-disable-next-line react-hooks/exhaustive-deps}, [authLoading, id])- const onSubmit = async (data: IForm) => {+ const onSubmit = async (data: Form) => {if (!projectSaving) {setProjectSaving(true)try {- const formalisedData: IForm = {+ const formalisedData: Form = {...data,origins: _isEmpty(data.origins)? null@@ -140,7 +139,7 @@ const CaptchaSettings = ({ isSettings }: CaptchaSettingsProps): JSX.Element => {ipBlacklist: _isEmpty(data.ipBlacklist) ? null : _split(data.ipBlacklist as string, ','),}if (isSettings) {- await updateProject(id, formalisedData as ICaptchaProject)+ await updateProject(id, formalisedData as CaptchaProject)toast.success(t('project.settings.updated'))} else {await createProject({diff --git a/web/app/pages/Captcha/View/ViewCaptcha.tsx b/web/app/pages/Captcha/View/ViewCaptcha.tsxindex 3ac14aa08..0ca63cc63 100644--- a/web/app/pages/Captcha/View/ViewCaptcha.tsx+++ b/web/app/pages/Captcha/View/ViewCaptcha.tsx@@ -40,7 +40,7 @@ import {isBrowser,ThemeType,} from 'redux/constants'-import { ICaptchaProject, IProject } from 'redux/models/IProject'+import { CaptchaProject, Project } from 'redux/models/Project'import Loader from 'ui/Loader'import Dropdown from 'ui/Dropdown'import Checkbox from 'ui/Checkbox'@@ -99,7 +99,7 @@ const ViewCaptcha = ({ ssrTheme }: ViewCaptchaProps) => {const { id } = useRequiredParams<{ id: string }>()const navigate = useNavigate()- const [project, setProject] = useState<ICaptchaProject | null>(null)+ const [project, setProject] = useState<CaptchaProject | null>(null)const [areFiltersParsed, setAreFiltersParsed] = useState(false)const [areTimeBucketParsed, setAreTimeBucketParsed] = useState(false)@@ -150,7 +150,7 @@ const ViewCaptcha = ({ ssrTheme }: ViewCaptchaProps) => {const _theme = isBrowser ? theme : ssrTheme- const { name } = project as IProject+ const { name } = project as ProjectuseEffect(() => {let pageTitle = name@@ -518,7 +518,7 @@ const ViewCaptcha = ({ ssrTheme }: ViewCaptchaProps) => {if (_isEmpty(result)) {onErrorLoading()} else {- setProject(result as ICaptchaProject)+ setProject(result as CaptchaProject)}}).catch((reason) => {diff --git a/web/app/pages/Captcha/View/components/NoEvents.tsx b/web/app/pages/Captcha/View/components/NoEvents.tsxindex 7359d83f2..451252736 100644--- a/web/app/pages/Captcha/View/components/NoEvents.tsx+++ b/web/app/pages/Captcha/View/components/NoEvents.tsx@@ -4,14 +4,14 @@ import _isEmpty from 'lodash/isEmpty'import Button from 'ui/Button'import { DOCS_CAPTCHA_URL } from 'redux/constants'-import { IFilter } from 'pages/Project/View/interfaces/traffic'+import { Filter } from 'pages/Project/View/interfaces/traffic'-interface INoEvents {- filters: IFilter[]+interface NoEventsProps {+ filters: Filter[]resetFilters: () => void}-const NoEvents = ({ filters, resetFilters }: INoEvents): JSX.Element => {+const NoEvents = ({ filters, resetFilters }: NoEventsProps) => {const { t } = useTranslation('common')return (diff --git a/web/app/pages/Changelog/index.tsx b/web/app/pages/Changelog/index.tsxindex ba306faa7..e1448a0ed 100644--- a/web/app/pages/Changelog/index.tsx+++ b/web/app/pages/Changelog/index.tsx@@ -419,7 +419,7 @@ const changelog = [},]-const Changelog = (): JSX.Element => {+const Changelog = () => {const { t } = useTranslation('common')return (diff --git a/web/app/pages/Contact/index.tsx b/web/app/pages/Contact/index.tsxindex 2f077af6a..72f40d249 100644--- a/web/app/pages/Contact/index.tsx+++ b/web/app/pages/Contact/index.tsx@@ -5,13 +5,13 @@ import { ArrowTopRightOnSquareIcon } from '@heroicons/react/24/outline'import { CONTACT_EMAIL, TWITTER_URL, TWITTER_USERNAME, DISCORD_URL, DOCS_URL, BOOK_A_CALL_URL } from 'redux/constants'-interface IPanel {+interface PanelProps {href: stringtitle: stringdescription: string}-const Panel = ({ href, title, description }: IPanel) => (+const Panel = ({ href, title, description }: PanelProps) => (<ahref={href}target='_blank'@@ -24,7 +24,7 @@ const Panel = ({ href, title, description }: IPanel) => (</a>)-const Contact = (): JSX.Element => {+const Contact = () => {const { t } = useTranslation('common')return (diff --git a/web/app/pages/Dashboard/Dashboard.tsx b/web/app/pages/Dashboard/Dashboard.tsxindex fb0f93a6c..0a79ce11e 100644--- a/web/app/pages/Dashboard/Dashboard.tsx+++ b/web/app/pages/Dashboard/Dashboard.tsx@@ -23,7 +23,7 @@ import { StateType } from 'redux/store'import { ProjectCard } from './ProjectCard'import { NoProjects } from './NoProjects'import { AddProject } from './AddProject'-import { IOverall, IProject } from 'redux/models/IProject'+import { Overall, Project } from 'redux/models/Project'import { getProjects, getLiveVisitors, getOverallStats, getOverallStatsCaptcha } from 'api'const Dashboard = () => {@@ -33,13 +33,13 @@ const Dashboard = () => {const [isSearchActive, setIsSearchActive] = useState(false)const [showActivateEmailModal, setShowActivateEmailModal] = useState(false)- const [projects, setProjects] = useState<IProject[]>([])+ const [projects, setProjects] = useState<Project[]>([])const [paginationTotal, setPaginationTotal] = useState(0)const [page, setPage] = useState(1)const [isLoading, setIsLoading] = useState<boolean | null>(null)const [error, setError] = useState<string | null>(null)const [liveStats, setLiveStats] = useState<Record<string, number>>({})- const [overallStats, setOverallStats] = useState<IOverall>({})+ const [overallStats, setOverallStats] = useState<Overall>({})const pageAmount = Math.ceil(paginationTotal / ENTRIES_PER_PAGE_DASHBOARD)@@ -88,8 +88,8 @@ const Dashboard = () => {const projectIds = projects.map((p) => p.id)const stats = await getLiveVisitors(projectIds)setLiveStats(stats)- } catch (error) {- console.error('Failed to fetch live visitors:', error)+ } catch (reason) {+ console.error('Failed to fetch live visitors:', reason)}}@@ -99,8 +99,8 @@ const Dashboard = () => {try {const stats = await getOverallStats(projectIds, '7d')setOverallStats(stats)- } catch (error) {- console.error('Failed to fetch overall stats:', error)+ } catch (reason) {+ console.error('Failed to fetch overall stats:', reason)}}@@ -110,8 +110,8 @@ const Dashboard = () => {try {const stats = await getOverallStatsCaptcha(projectIds, '7d')setOverallStats(stats)- } catch (error) {- console.error('Failed to fetch overall stats:', error)+ } catch (reason) {+ console.error('Failed to fetch overall stats:', reason)}}diff --git a/web/app/pages/Dashboard/ProjectCard.tsx b/web/app/pages/Dashboard/ProjectCard.tsxindex 6745cbeeb..684eaa2a8 100644--- a/web/app/pages/Dashboard/ProjectCard.tsx+++ b/web/app/pages/Dashboard/ProjectCard.tsx@@ -17,15 +17,15 @@ import { nFormatter, calculateRelativePercentage } from 'utils/generic'import { acceptProjectShare } from 'api'-import { IOverallObject, IProject } from 'redux/models/IProject'+import { OverallObject, Project } from 'redux/models/Project'import { useSelector } from 'react-redux'import { StateType, useAppDispatch } from 'redux/store'import { authActions } from 'redux/reducers/auth'interface ProjectCardProps {live?: string | number- overallStats?: IOverallObject- project: IProject+ overallStats?: OverallObject+ project: Project}interface MiniCardProps {diff --git a/web/app/pages/ErrorTracking/index.tsx b/web/app/pages/ErrorTracking/index.tsxindex 741e9a293..db43dd357 100644--- a/web/app/pages/ErrorTracking/index.tsx+++ b/web/app/pages/ErrorTracking/index.tsx@@ -19,19 +19,19 @@ import Header from 'components/Header'import Pricing from '../../components/marketing/Pricing'import { DitchGoogle } from 'components/marketing/DitchGoogle'-const Lines = (): JSX.Element => (+const Lines = () => (<div className='pointer-events-none relative'><div className='absolute right-[-48rem] top-[32rem] h-px w-[800%] rotate-6 bg-gradient-to-l from-slate-600 opacity-10 dark:from-slate-400' /><div className='absolute -left-60 top-[22.26rem] ml-[-0.5px] h-96 w-[2px] rotate-[96deg] rounded-full bg-gradient-to-t from-red-600 opacity-50 dark:from-red-700 xl:top-[23.5rem]' /></div>)-interface IErrorTracking {+interface ErrorTrackingProps {ssrTheme: 'dark' | 'light'ssrAuthenticated: boolean}-const ErrorTracking: React.FC<IErrorTracking> = ({ ssrTheme, ssrAuthenticated }): JSX.Element => {+const ErrorTracking = ({ ssrTheme, ssrAuthenticated }: ErrorTrackingProps) => {const { t } = useTranslation('common')const reduxTheme = useSelector((state: StateType) => state.ui.theme.theme)const { authenticated: reduxAuthenticated, loading } = useSelector((state: StateType) => state.auth)diff --git a/web/app/pages/Imprint/index.tsx b/web/app/pages/Imprint/index.tsxindex e5fcb9728..883fc9dc1 100644--- a/web/app/pages/Imprint/index.tsx+++ b/web/app/pages/Imprint/index.tsx@@ -3,7 +3,7 @@ import React from 'react'import { CONTACT_EMAIL } from 'redux/constants'-const Imprint = (): JSX.Element => {+const Imprint = () => {return (<div className='min-h-min-footer bg-gray-50 dark:bg-slate-900'><div className='mx-auto w-11/12 px-4 pb-16 pt-12 sm:px-6 md:w-4/5 lg:px-8'>diff --git a/web/app/pages/NotFound/index.tsx b/web/app/pages/NotFound/index.tsxindex 0d0de07b5..0c567ab7e 100644--- a/web/app/pages/NotFound/index.tsx+++ b/web/app/pages/NotFound/index.tsx@@ -7,7 +7,7 @@ import { isSelfhosted } from 'redux/constants'const CONTACT_US_URL = `https://swetrix.com${routes.contact}`-const NotFound = (): JSX.Element => {+const NotFound = () => {const { t } = useTranslation('common')return (diff --git a/web/app/pages/OpenStartup/index.tsx b/web/app/pages/OpenStartup/index.tsxindex 9547ee47b..6a04e3a01 100644--- a/web/app/pages/OpenStartup/index.tsx+++ b/web/app/pages/OpenStartup/index.tsx@@ -1,6 +1,5 @@-/* eslint-disable */+/* eslint-disable no-useless-escape */import React, { useEffect } from 'react'-import _map from 'lodash/map'import bb, { bar, line } from 'billboard.js'import { useTranslation, Trans } from 'react-i18next'import { Link } from '@remix-run/react'@@ -361,7 +360,7 @@ const getSettings = () => {}}-const OpenStartup = (): JSX.Element => {+const OpenStartup = () => {const { t }: any = useTranslation('common')const { stats } = useSelector((state: StateType) => state.ui.misc)diff --git a/web/app/pages/Organisations/Settings/People.tsx b/web/app/pages/Organisations/Settings/People.tsxindex e96a96cd4..ed1fe393f 100644--- a/web/app/pages/Organisations/Settings/People.tsx+++ b/web/app/pages/Organisations/Settings/People.tsx@@ -150,7 +150,7 @@ interface PeopleProps {reloadOrganisation: () => Promise<void>}-const People = ({ organisation, reloadOrganisation }: PeopleProps): JSX.Element => {+const People = ({ organisation, reloadOrganisation }: PeopleProps) => {const [showModal, setShowModal] = useState(false)const { t } = useTranslation('common')const [form, setForm] = useState<{diff --git a/web/app/pages/Organisations/Settings/Projects.tsx b/web/app/pages/Organisations/Settings/Projects.tsxindex e3d6b1cca..39fbbc932 100644--- a/web/app/pages/Organisations/Settings/Projects.tsx+++ b/web/app/pages/Organisations/Settings/Projects.tsx@@ -19,10 +19,10 @@ import routes from 'utils/routes'import Loader from 'ui/Loader'import Pagination from 'ui/Pagination'import useDebounce from 'hooks/useDebounce'-import { IProject } from 'redux/models/IProject'+import { Project } from 'redux/models/Project'interface SelectAProjectProps {- onSelect: (project: IProject) => void+ onSelect: (project: Project) => void}const PAGINATION_ENTRIES = 5@@ -33,7 +33,7 @@ const SelectAProject = ({ onSelect }: SelectAProjectProps) => {const [currentPage, setCurrentPage] = useState(1)const [search, setSearch] = useState('')const [isLoading, setIsLoading] = useState(false)- const [projects, setProjects] = useState<IProject[]>([])+ const [projects, setProjects] = useState<Project[]>([])const [total, setTotal] = useState(0)const debouncedSearch = useDebounce(search, 500)@@ -172,7 +172,7 @@ interface ProjectsProps {reloadOrganisation: () => Promise<void>}-export const Projects = ({ organisation, reloadOrganisation }: ProjectsProps): JSX.Element => {+export const Projects = ({ organisation, reloadOrganisation }: ProjectsProps) => {const { t } = useTranslation('common')const [showDeleteModal, setShowDeleteModal] = useState(false)diff --git a/web/app/pages/Performance/index.tsx b/web/app/pages/Performance/index.tsxindex eb4f5efc4..eee477418 100644--- a/web/app/pages/Performance/index.tsx+++ b/web/app/pages/Performance/index.tsx@@ -19,19 +19,19 @@ import Header from 'components/Header'import Pricing from '../../components/marketing/Pricing'import { DitchGoogle } from 'components/marketing/DitchGoogle'-const Lines = (): JSX.Element => (+const Lines = () => (<div className='pointer-events-none relative'><div className='absolute right-[-48rem] top-[32rem] h-px w-[800%] rotate-6 bg-gradient-to-l from-slate-600 opacity-10 dark:from-slate-400' /><div className='absolute -left-60 top-[22.26rem] ml-[-0.5px] h-96 w-[2px] rotate-[96deg] rounded-full bg-gradient-to-t from-orange-600 opacity-50 dark:from-orange-700 xl:top-[23.5rem]' /></div>)-interface IPerformance {+interface PerformanceProps {ssrTheme: 'dark' | 'light'ssrAuthenticated: boolean}-const Performance: React.FC<IPerformance> = ({ ssrTheme, ssrAuthenticated }): JSX.Element => {+const Performance = ({ ssrTheme, ssrAuthenticated }: PerformanceProps) => {const { t } = useTranslation('common')const reduxTheme = useSelector((state: StateType) => state.ui.theme.theme)const { authenticated: reduxAuthenticated, loading } = useSelector((state: StateType) => state.auth)diff --git a/web/app/pages/Press/index.tsx b/web/app/pages/Press/index.tsxindex d1ac59457..9160cb155 100644--- a/web/app/pages/Press/index.tsx+++ b/web/app/pages/Press/index.tsx@@ -8,7 +8,7 @@ import routes from 'utils/routes'const FONT_INTER_URL = 'https://rsms.me/inter/'const FONT_NAME = 'Inter'-interface ILogoComponent {+interface LogoComponentProps {description: stringlogoPNG: stringlogoSVG?: string@@ -20,7 +20,7 @@ const LogoComponent = ({logoSVG,logoPNG,textColor = 'text-gray-900 dark:text-gray-50',-}: ILogoComponent): JSX.Element => (+}: LogoComponentProps) => (<p><b className={`font-bold tracking-tight ${textColor}`}>{description}</b><img className='mb-2 mt-5 h-16 sm:h-20' src={logoSVG || logoPNG} alt={description} />@@ -48,7 +48,7 @@ const LogoComponent = ({</p>)-const Press = (): JSX.Element => {+const Press = () => {const { t } = useTranslation('common')return (diff --git a/web/app/pages/Privacy/index.tsx b/web/app/pages/Privacy/index.tsxindex 3ba194387..2cda5d6dc 100644--- a/web/app/pages/Privacy/index.tsx+++ b/web/app/pages/Privacy/index.tsx@@ -48,7 +48,7 @@ const serviceProviders: {},]-const Features = (): JSX.Element => {+const Features = () => {return (<div className='bg-gray-50 dark:bg-slate-900'><div className='mx-auto w-11/12 px-4 pb-16 pt-12 sm:px-6 md:w-4/5 lg:px-8'>diff --git a/web/app/pages/Project/Alerts/Settings/ProjectAlertsSettings.tsx b/web/app/pages/Project/Alerts/Settings/ProjectAlertsSettings.tsxindex 91df14671..942e6e0f9 100644--- a/web/app/pages/Project/Alerts/Settings/ProjectAlertsSettings.tsx+++ b/web/app/pages/Project/Alerts/Settings/ProjectAlertsSettings.tsx@@ -18,11 +18,11 @@ import Button from 'ui/Button'import Checkbox from 'ui/Checkbox'import Modal from 'ui/Modal'import { PROJECT_TABS, QUERY_CONDITION, QUERY_METRIC, QUERY_TIME } from 'redux/constants'-import { createAlert, updateAlert, deleteAlert, ICreateAlert, getAlert } from 'api'+import { createAlert, updateAlert, deleteAlert, CreateAlert, getAlert } from 'api'import { withAuthentication, auth } from 'hoc/protected'import routes from 'utils/routes'import Select from 'ui/Select'-import { IAlerts } from 'redux/models/IAlerts'+import { Alerts } from 'redux/models/Alerts'import { StateType } from 'redux/store'import { useSelector } from 'react-redux'import { useRequiredParams } from 'hooks/useRequiredParams'@@ -40,7 +40,7 @@ const ProjectAlertsSettings = ({ isSettings }: ProjectAlertsSettingsProps) => {const navigate = useNavigate()const { id, pid } = useRequiredParams<{ id: string; pid: string }>()const { t } = useTranslation('common')- const [form, setForm] = useState<Partial<IAlerts>>({+ const [form, setForm] = useState<Partial<Alerts>>({pid,name: '',queryTime: QUERY_TIME.LAST_1_HOUR,@@ -56,7 +56,7 @@ const ProjectAlertsSettings = ({ isSettings }: ProjectAlertsSettingsProps) => {const [beenSubmitted, setBeenSubmitted] = useState(false)const [showModal, setShowModal] = useState(false)- const [alert, setAlert] = useState<IAlerts | null>(null)+ const [alert, setAlert] = useState<Alerts | null>(null)const [isLoading, setIsLoading] = useState<boolean | null>(null)const [error, setError] = useState<string | null>(null)@@ -194,7 +194,7 @@ const ProjectAlertsSettings = ({ isSettings }: ProjectAlertsSettingsProps) => {setValidated(valid)}- const onSubmit = (data: Partial<IAlerts>) => {+ const onSubmit = (data: Partial<Alerts>) => {if (isSettings) {updateAlert(id as string, data).then((res) => {@@ -206,7 +206,7 @@ const ProjectAlertsSettings = ({ isSettings }: ProjectAlertsSettingsProps) => {toast.error(reason.message || reason || 'Something went wrong')})} else {- createAlert(data as ICreateAlert)+ createAlert(data as CreateAlert).then((res) => {navigate(`/projects/${pid}?tab=${PROJECT_TABS.alerts}`)toast.success(t('alertsSettings.alertCreated'))diff --git a/web/app/pages/Project/Alerts/View/ProjectAlertsView.tsx b/web/app/pages/Project/Alerts/View/ProjectAlertsView.tsxindex b36e056d5..32e3560c6 100644--- a/web/app/pages/Project/Alerts/View/ProjectAlertsView.tsx+++ b/web/app/pages/Project/Alerts/View/ProjectAlertsView.tsx@@ -26,7 +26,7 @@ import PaidFeature from 'modals/PaidFeature'import { QUERY_METRIC, PLAN_LIMITS, DEFAULT_ALERTS_TAKE } from 'redux/constants'import { deleteAlert as deleteAlertApi, getProjectAlerts } from 'api'import { StateType } from 'redux/store'-import { IAlerts } from 'redux/models/IAlerts'+import { Alerts } from 'redux/models/Alerts'import Loader from 'ui/Loader'import Pagination from 'ui/Pagination'@@ -63,7 +63,7 @@ const NoNotificationChannelSet = () => {)}-interface IAlertCard {+interface AlertCardProps {id: stringname: stringqueryMetric: string | number@@ -81,7 +81,7 @@ const AlertCard = ({openAlert,deleteAlert,queryMetricTMapping,-}: IAlertCard): JSX.Element => {+}: AlertCardProps) => {const {t,i18n: { language },@@ -151,12 +151,12 @@ const AlertCard = ({)}-interface IAddAlert {+interface AddAlertProps {handleNewAlert: () => voidisLimitReached: boolean}-const AddAlert = ({ handleNewAlert, isLimitReached }: IAddAlert): JSX.Element => {+const AddAlert = ({ handleNewAlert, isLimitReached }: AddAlertProps) => {const { t } = useTranslation()return (@@ -178,18 +178,18 @@ const AddAlert = ({ handleNewAlert, isLimitReached }: IAddAlert): JSX.Element =>)}-interface IProjectAlerts {+interface ProjectAlertsProps {projectId: string}-const ProjectAlerts = ({ projectId }: IProjectAlerts): JSX.Element => {+const ProjectAlerts = ({ projectId }: ProjectAlertsProps) => {const { t } = useTranslation()const { user, authenticated } = useSelector((state: StateType) => state.auth)const [isPaidFeatureOpened, setIsPaidFeatureOpened] = useState(false)const [isLoading, setIsLoading] = useState<boolean | null>(null)const [total, setTotal] = useState(0)- const [alerts, setAlerts] = useState<IAlerts[]>([])+ const [alerts, setAlerts] = useState<Alerts[]>([])const [page, setPage] = useState(1)const [error, setError] = useState<string | null>(null)diff --git a/web/app/pages/Project/ConfirmShare/index.tsx b/web/app/pages/Project/ConfirmShare/index.tsxindex 99c42dbcb..8f4aacb69 100644--- a/web/app/pages/Project/ConfirmShare/index.tsx+++ b/web/app/pages/Project/ConfirmShare/index.tsx@@ -1,17 +1,15 @@import { useState, useEffect } from 'react'-import { useDispatch } from 'react-redux'import { useParams, Link } from '@remix-run/react'import { useTranslation } from 'react-i18next'import { CheckCircleIcon, XCircleIcon } from '@heroicons/react/24/solid'import _split from 'lodash/split'-import sagaActions from 'redux/sagas/actions'import Loader from 'ui/Loader'import routes from 'utils/routes'+import { verifyShare } from 'api'const ConfirmShare = () => {const { t } = useTranslation('common')- const dispatch = useDispatch()const { id } = useParams()const [loading, setLoading] = useState(true)const [error, setError] = useState('')@@ -26,16 +24,17 @@ const ConfirmShare = () => {return}- dispatch(- sagaActions.shareVerifyAsync(- { path, id },- () => setLoading(false),- (verifyError) => {- setError(verifyError)- setLoading(false)- },- ),- )+ const verify = async () => {+ try {+ await verifyShare({ path, id })+ } catch (reason: any) {+ setError(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))+ } finally {+ setLoading(false)+ }+ }++ verify()}, [id]) // eslint-disable-lineif (loading) {diff --git a/web/app/pages/Project/New/index.tsx b/web/app/pages/Project/New/index.tsxindex 693fd9870..05bb048c1 100644--- a/web/app/pages/Project/New/index.tsx+++ b/web/app/pages/Project/New/index.tsx@@ -9,7 +9,7 @@ import _keys from 'lodash/keys'import { withAuthentication, auth } from 'hoc/protected'import { isSelfhosted, TITLE_SUFFIX } from 'redux/constants'-import { IProject } from 'redux/models/IProject'+import { Project } from 'redux/models/Project'import { createProject } from 'api'import Input from 'ui/Input'import Button from 'ui/Button'@@ -29,7 +29,7 @@ const NewProject = () => {const { t } = useTranslation('common')const navigate = useNavigate()- const [form, setForm] = useState<Partial<IProject>>({+ const [form, setForm] = useState<Partial<Project>>({name: '',organisationId: undefined,})@@ -64,7 +64,7 @@ const NewProject = () => {}}, [user, navigate, dispatch, t, loading])- const onSubmit = async (data: Partial<IProject>) => {+ const onSubmit = async (data: Partial<Project>) => {if (!projectSaving) {setProjectSaving(true)try {diff --git a/web/app/pages/Project/ProjectProtectedPassword/index.tsx b/web/app/pages/Project/ProjectProtectedPassword/index.tsxindex 2ae63aada..f88cf2cb4 100644--- a/web/app/pages/Project/ProjectProtectedPassword/index.tsx+++ b/web/app/pages/Project/ProjectProtectedPassword/index.tsx@@ -16,7 +16,7 @@ import Header from 'components/Header'import Footer from 'components/Footer'import { useRequiredParams } from 'hooks/useRequiredParams'-interface IProjectProtectedPasswordForm {+interface ProjectProtectedPasswordForm {password: string}@@ -30,7 +30,7 @@ interface ProjectProtectedPasswordProps {const ProjectProtectedPassword = ({ ssrTheme, embedded, isAuth }: ProjectProtectedPasswordProps) => {const { t } = useTranslation('common')- const [form, setForm] = useState<IProjectProtectedPasswordForm>({+ const [form, setForm] = useState<ProjectProtectedPasswordForm>({password: '',})const [validated, setValidated] = useState(false)@@ -66,7 +66,7 @@ const ProjectProtectedPassword = ({ ssrTheme, embedded, isAuth }: ProjectProtectvalidate()}, [form]) // eslint-disable-line- const onSubmit = async (data: IProjectProtectedPasswordForm) => {+ const onSubmit = async (data: ProjectProtectedPasswordForm) => {if (!isLoading) {setIsLoading(true)await checkPassword(id, data.password)diff --git a/web/app/pages/Project/Settings/Emails/ConfirmReportsShare/index.tsx b/web/app/pages/Project/Settings/Emails/ConfirmReportsShare/index.tsxindex 9eaefb3b4..49c531704 100644--- a/web/app/pages/Project/Settings/Emails/ConfirmReportsShare/index.tsx+++ b/web/app/pages/Project/Settings/Emails/ConfirmReportsShare/index.tsx@@ -8,7 +8,7 @@ import Loader from 'ui/Loader'import { confirmSubscriberInvite } from 'api'import routes from 'utils/routes'-const ConfirmReportsShare = (): JSX.Element => {+const ConfirmReportsShare = () => {const { t } = useTranslation('common')const { id } = useParams()const [loading, setLoading] = useState(true)diff --git a/web/app/pages/Project/Settings/Emails/Emails.tsx b/web/app/pages/Project/Settings/Emails/Emails.tsxindex 2d3f5861a..3cc28a90e 100644--- a/web/app/pages/Project/Settings/Emails/Emails.tsx+++ b/web/app/pages/Project/Settings/Emails/Emails.tsx@@ -21,7 +21,7 @@ import Modal from 'ui/Modal'import Loader from 'ui/Loader'import cx from 'clsx'import { Badge } from 'ui/Badge'-import { ISubscribers } from 'redux/models/ISubscribers'+import { Subscriber } from 'redux/models/Subscriber'interface ModalMessageProps {handleInput: (e: React.ChangeEvent<HTMLInputElement>) => void@@ -134,7 +134,7 @@ interface EmailListProps {reportFrequency: string}onRemove: () => void- setEmails: (value: ISubscribers[] | ((prevVar: ISubscribers[]) => ISubscribers[])) => void+ setEmails: (value: Subscriber[] | ((prevVar: Subscriber[]) => Subscriber[])) => void}const EmailList = ({ data, onRemove, setEmails }: EmailListProps) => {@@ -254,7 +254,7 @@ const NoSubscribers = () => {)}-const Emails = ({ projectId }: { projectId: string }): JSX.Element => {+const Emails = ({ projectId }: { projectId: string }) => {const [showModal, setShowModal] = useState(false)const { t } = useTranslation('common')const [form, setForm] = useState<{@@ -270,7 +270,7 @@ const Emails = ({ projectId }: { projectId: string }): JSX.Element => {reportFrequency?: string}>({})const [validated, setValidated] = useState(false)- const [emails, setEmails] = useState<ISubscribers[]>([])+ const [emails, setEmails] = useState<Subscriber[]>([])const [loading, setLoading] = useState(true)const [pagination, setPagination] = useState({page: 1,@@ -280,7 +280,7 @@ const Emails = ({ projectId }: { projectId: string }): JSX.Element => {const [showDeleteModal, setShowDeleteModal] = useState(false)const [isDeleting, setIsDeleting] = useState(false)- const [emailToRemove, setEmailToRemove] = useState<ISubscribers | null>(null)+ const [emailToRemove, setEmailToRemove] = useState<Subscriber | null>(null)const getSubcribersAsync = async () => {try {diff --git a/web/app/pages/Project/Settings/People/People.tsx b/web/app/pages/Project/Settings/People/People.tsxindex 0f69add56..396ca1c26 100644--- a/web/app/pages/Project/Settings/People/People.tsx+++ b/web/app/pages/Project/Settings/People/People.tsx@@ -18,7 +18,7 @@ import Modal from 'ui/Modal'import PaidFeature from 'modals/PaidFeature'import { roles, INVITATION_EXPIRES_IN } from 'redux/constants'import useOnClickOutside from 'hooks/useOnClickOutside'-import { IProject, IShareOwnerProject } from 'redux/models/IProject'+import { Project, ShareOwnerProject } from 'redux/models/Project'import { Role } from 'redux/models/Organisation'import { useSelector } from 'react-redux'import { StateType } from 'redux/store'@@ -36,7 +36,7 @@ const NoPeople = () => {}interface UsersListProps {- data: IShareOwnerProject+ data: ShareOwnerProjectonRemove: () => voidlanguage: stringauthedUserEmail: string | undefined@@ -140,7 +140,7 @@ const UsersList = ({ data, onRemove, language, authedUserEmail }: UsersListProps}interface PeopleProps {- project: IProject+ project: Project}const People = ({ project }: PeopleProps) => {@@ -168,7 +168,7 @@ const People = ({ project }: PeopleProps) => {const [showDeleteModal, setShowDeleteModal] = useState(false)const [isDeleting, setIsDeleting] = useState(false)- const [memberToRemove, setMemberToRemove] = useState<IShareOwnerProject | null>(null)+ const [memberToRemove, setMemberToRemove] = useState<ShareOwnerProject | null>(null)const { id, name, share } = project@@ -248,7 +248,7 @@ const People = ({ project }: PeopleProps) => {setErrors({})}- const onRemove = async (member: IShareOwnerProject) => {+ const onRemove = async (member: ShareOwnerProject) => {if (isDeleting) {return}diff --git a/web/app/pages/Project/Settings/ProjectSettings.tsx b/web/app/pages/Project/Settings/ProjectSettings.tsxindex 2a5ea749b..4ea2923af 100644--- a/web/app/pages/Project/Settings/ProjectSettings.tsx+++ b/web/app/pages/Project/Settings/ProjectSettings.tsx@@ -19,7 +19,7 @@ import { TrashIcon, XCircleIcon } from '@heroicons/react/24/outline'import { withAuthentication, auth } from 'hoc/protected'import { isSelfhosted, TITLE_SUFFIX, FILTERS_PANELS_ORDER, isBrowser } from 'redux/constants'-import { IProject } from 'redux/models/IProject'+import { Project } from 'redux/models/Project'import {updateProject,deleteProject,@@ -247,7 +247,7 @@ const ModalMessage = ({)}-interface IForm extends Partial<IProject> {+interface Form extends Partial<Project> {origins: string | nullipBlacklist: string | null}@@ -264,8 +264,8 @@ const ProjectSettings = () => {const navigate = useNavigate()const { requestOrigin } = useLoaderData<{ requestOrigin: string | null }>()- const [project, setProject] = useState<IProject | null>(null)- const [form, setForm] = useState<IForm>({+ const [project, setProject] = useState<Project | null>(null)+ const [form, setForm] = useState<Form>({name: '',id,public: false,@@ -372,7 +372,7 @@ const ProjectSettings = () => {// eslint-disable-next-line react-hooks/exhaustive-deps}, [authLoading, id])- const onSubmit = async (data: IForm) => {+ const onSubmit = async (data: Form) => {if (!isSaving) {setIsSaving(true)try {@@ -392,7 +392,7 @@ const ProjectSettings = () => {}),ipBlacklist: _isEmpty(data.ipBlacklist) ? null : _split(data.ipBlacklist, ','),}- await updateProject(id, formalisedData as Partial<IProject>)+ await updateProject(id, formalisedData as Partial<Project>)toast.success(t('project.settings.updated'))} catch (reason: any) {toast.error(reason)diff --git a/web/app/pages/Project/View/Panels.tsx b/web/app/pages/Project/View/Panels.tsxindex 21a1484a1..dab064ca2 100644--- a/web/app/pages/Project/View/Panels.tsx+++ b/web/app/pages/Project/View/Panels.tsx@@ -40,14 +40,14 @@ import Modal from 'ui/Modal'import Button from 'ui/Button'import Chart from 'ui/Chart'import { PROJECT_TABS } from 'redux/constants'-import { IEntry } from 'redux/models/IEntry'+import { Entry } from 'redux/models/Entry'import InteractiveMap from './components/InteractiveMap'import UserFlow from './components/UserFlow'import { iconClassName } from './ViewProject.helpers'import Spin from 'ui/icons/Spin'import { useTranslation } from 'react-i18next'import CustomEventsDropdown from './components/CustomEventsDropdown'-import { ICustoms, IFilter, IProperties } from './interfaces/traffic'+import { Customs, Filter, Properties } from './interfaces/traffic'const ENTRIES_PER_PANEL = 5const ENTRIES_PER_CUSTOM_EVENTS_PANEL = 6@@ -97,8 +97,8 @@ const removeDuplicates = (arr: any[], keys: string[]) => {return uniqueObjects}-interface IPanelContainer {- name: string | JSX.Element+interface PanelContainerProps {+ name: React.ReactNodechildren?: React.ReactNodenoSwitch?: booleanicon?: React.ReactNode@@ -124,7 +124,7 @@ const PanelContainer = ({activeTab,isCustomContent,onExpandClick = () => {},-}: IPanelContainer): JSX.Element => (+}: PanelContainerProps) => (<divclassName={cx('relative max-h-96 min-h-72 overflow-hidden rounded-lg bg-white px-4 pt-5 shadow dark:border dark:border-slate-800/50 dark:bg-slate-800/25 sm:px-6 sm:pt-6',@@ -295,26 +295,26 @@ const getPieOptions = (customs: any, uniques: number, t: any) => {}}-interface IMetadata {- customs: ICustoms- properties: IProperties+interface MetadataProps {+ customs: Customs+ properties: PropertieschartData: any- filters: IFilter[]+ filters: Filter[]onFilter: (column: string, filter: any, isExclusive?: boolean) => Promise<void>getCustomEventMetadata: (event: string) => Promise<any>getPropertyMetadata: (property: string) => Promise<any>customTabs: any}-interface ICustomEvents extends IMetadata {+interface CustomEventsProps extends MetadataProps {setActiveTab: React.Dispatch<React.SetStateAction<'customEv' | 'properties'>>}-interface IPageProperties extends IMetadata {+interface PagePropertiesProps extends MetadataProps {setActiveTab: React.Dispatch<React.SetStateAction<'customEv' | 'properties'>>}-interface ISortRows {+interface SortRows {label: stringsortByAscend: booleansortByDescend: boolean@@ -340,7 +340,7 @@ interface KVTableProps {const KVTable = ({ listId, data, displayKeyAsHeader, onClick }: KVTableProps) => {const { t } = useTranslation('common')- const [sort, setSort] = useState<ISortRows>({+ const [sort, setSort] = useState<SortRows>({label: 'quantity',sortByAscend: false,sortByDescend: false,@@ -515,7 +515,7 @@ const CustomEvents = ({customTabs = [],getCustomEventMetadata,setActiveTab,-}: ICustomEvents) => {+}: CustomEventsProps) => {const { t } = useTranslation('common')const [page, setPage] = useState(0)const [detailsOpened, setDetailsOpened] = useState(false)@@ -536,7 +536,7 @@ const CustomEvents = ({const totalPages = useMemo(() => _ceil(_size(keys) / ENTRIES_PER_CUSTOM_EVENTS_PANEL), [keys])const canGoPrev = () => page > 0const canGoNext = () => page < _floor((_size(keys) - 1) / ENTRIES_PER_CUSTOM_EVENTS_PANEL)- const [sort, setSort] = useState<ISortRows>({+ const [sort, setSort] = useState<SortRows>({label: 'quantity',sortByAscend: false,sortByDescend: false,@@ -972,14 +972,14 @@ const PageProperties = ({filters,getPropertyMetadata,setActiveTab,-}: IPageProperties) => {+}: PagePropertiesProps) => {const { t } = useTranslation('common')const [page, setPage] = useState(0)const [detailsOpened, setDetailsOpened] = useState(false)const [activeProperties, setActiveProperties] = useState<any>({})const [loadingDetails, setLoadingDetails] = useState<any>({})const [details, setDetails] = useState<any>({})- const [processedProperties, setProcessedProperties] = useState<IProperties>(properties)+ const [processedProperties, setProcessedProperties] = useState<Properties>(properties)const currentIndex = page * ENTRIES_PER_CUSTOM_EVENTS_PANELconst keys = _keys(processedProperties)const keysToDisplay = useMemo(@@ -992,7 +992,7 @@ const PageProperties = ({const totalPages = useMemo(() => _ceil(_size(keys) / ENTRIES_PER_CUSTOM_EVENTS_PANEL), [keys])const canGoPrev = () => page > 0const canGoNext = () => page < _floor((_size(keys) - 1) / ENTRIES_PER_CUSTOM_EVENTS_PANEL)- const [sort, setSort] = useState<ISortRows>({+ const [sort, setSort] = useState<SortRows>({label: 'quantity',sortByAscend: false,sortByDescend: false,@@ -1359,7 +1359,7 @@ const PageProperties = ({)}-const Metadata = (props: IMetadata) => {+const Metadata = (props: MetadataProps) => {const [activeTab, setActiveTab] = useState<'customEv' | 'properties'>('customEv')if (activeTab === 'customEv') {@@ -1369,10 +1369,10 @@ const Metadata = (props: IMetadata) => {return <PageProperties {...props} setActiveTab={setActiveTab} />}-interface IPanel {- name: string | JSX.Element- data: IEntry[]- rowMapper?: (row: any) => string | JSX.Element+interface PanelProps {+ name: React.ReactNode+ data: Entry[]+ rowMapper?: (row: any) => React.ReactNodevalueMapper?: (value: number) => numbercapitalize?: booleanlinkContent?: boolean@@ -1389,14 +1389,14 @@ interface IPanel {timezone?: string | nullactiveTab?: stringonFragmentChange?: (arg: number) => void- filters?: IFilter[]+ filters?: Filter[]projectPassword?: string}const Panel = ({name,data,- rowMapper = (row: IEntry): string => row.name,+ rowMapper = (row: Entry): string => row.name,valueMapper = (value: number): number => value,capitalize,linkContent,@@ -1415,7 +1415,7 @@ const Panel = ({onFragmentChange = () => {},filters,projectPassword,-}: IPanel): JSX.Element => {+}: PanelProps) => {const { t } = useTranslation('common')const [page, setPage] = useState(0)const currentIndex = page * ENTRIES_PER_PANELdiff --git a/web/app/pages/Project/View/ViewProject.helpers.tsx b/web/app/pages/Project/View/ViewProject.helpers.tsxindex cafb55cb9..a97a11a09 100644--- a/web/app/pages/Project/View/ViewProject.helpers.tsx+++ b/web/app/pages/Project/View/ViewProject.helpers.tsx@@ -44,10 +44,10 @@ import {PROJECT_TABS,isSelfhosted,} from 'redux/constants'-import { IEntry } from 'redux/models/IEntry'+import { Entry } from 'redux/models/Entry'import { getTimeFromSeconds, getStringFromTime, sumArrays, nFormatter } from 'utils/generic'import countries from 'utils/isoCountries'-import { IAnalyticsFunnel } from 'redux/models/IProject'+import { AnalyticsFunnel } from 'redux/models/Project'const getAvg = (arr: any) => {const total = _reduce(arr, (acc, c) => acc + c, 0)@@ -164,7 +164,7 @@ const onCSVExportClick = (const total = _reduce(rowData[item], (acc, { count }) => acc + count, 0)- const csvData = _map(rowData[item], (entry: IEntry) => {+ const csvData = _map(rowData[item], (entry: Entry) => {const perc = _round((entry.count / total) * 100 || 0, 2)if (item === 'cc') {@@ -1062,7 +1062,7 @@ const getSettingsError = (}}-const getSettingsFunnels = (funnel: IAnalyticsFunnel[], totalPageviews: number, t: typeof i18next.t): ChartOptions => {+const getSettingsFunnels = (funnel: AnalyticsFunnel[], totalPageviews: number, t: typeof i18next.t): ChartOptions => {const values = _map(funnel, (step) => {if (_startsWith(step.value, '/')) {return t('project.visitPage', { page: step.value })diff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsxindex 71a3e2154..18d88e4e6 100644--- a/web/app/pages/Project/View/ViewProject.tsx+++ b/web/app/pages/Project/View/ViewProject.tsx@@ -96,14 +96,14 @@ import {BROWSER_LOGO_MAP,OS_LOGO_MAP,OS_LOGO_MAP_DARK,- ITBPeriodPairs,+ TBPeriodPairsProps,ERROR_PANELS_ORDER,ERROR_PERIOD_PAIRS,FUNNELS_PERIOD_PAIRS,ThemeType,} from 'redux/constants'-import { IProject, IFunnel, IAnalyticsFunnel, IOverallObject, IOverallPerformanceObject } from 'redux/models/IProject'-import { ICountryEntry } from 'redux/models/IEntry'+import { Project, Funnel, AnalyticsFunnel, OverallObject, OverallPerformanceObject } from 'redux/models/Project'+import { CountryEntry } from 'redux/models/Entry'import Loader from 'ui/Loader'import Dropdown from 'ui/Dropdown'import Checkbox from 'ui/Checkbox'@@ -179,7 +179,7 @@ import ProjectAlertsView from '../Alerts/View'import Uptime from '../uptime/View'import UTMDropdown from './components/UTMDropdown'import TBPeriodSelector from './components/TBPeriodSelector'-import { ISession } from './interfaces/session'+import { Session } from './interfaces/session'import { Sessions } from './components/Sessions'import { Pageflow } from './components/Pageflow'import { SessionDetails } from './components/SessionDetails'@@ -189,19 +189,19 @@ import LockedDashboard from './components/LockedDashboard'import WaitingForAnEvent from './components/WaitingForAnEvent'import { ErrorChart } from './components/ErrorChart'import { ErrorDetails } from './components/ErrorDetails'-import { IError } from './interfaces/error'+import { SwetrixError } from './interfaces/error'import NoErrorDetails from './components/NoErrorDetails'import WaitingForAnError from './components/WaitingForAnError'import NoSessionDetails from './components/NoSessionDetails'import {- ICustoms,- IFilter,- ITrafficMeta,- IParams,- IProjectView,- IProjectViewCustomEvent,- IProperties,- ITrafficLogResponse,+ Customs,+ Filter,+ TrafficMeta,+ Params,+ ProjectView,+ ProjectViewCustomEvent,+ Properties,+ TrafficLogResponse,} from './interfaces/traffic'import { trackCustom } from 'utils/analytics'import {@@ -238,8 +238,8 @@ interface ViewProjectContextType {isLoading: booleantimeBucket: stringperiod: string- activePeriod: ITBPeriodPairs | undefined- periodPairs: ITBPeriodPairs[]+ activePeriod: TBPeriodPairsProps | undefined+ periodPairs: TBPeriodPairsProps[]timeFormat: '12-hour' | '24-hour'size: ReturnType<typeof useSize>[1]allowedToManage: boolean@@ -248,7 +248,7 @@ interface ViewProjectContextType {setDateRange: Dispatch<SetStateAction<Date[] | null>>updatePeriod: (newPeriod: { period: string; label?: string }) => voidupdateTimebucket: (newTimebucket: string) => void- setPeriodPairs: Dispatch<SetStateAction<ITBPeriodPairs[]>>+ setPeriodPairs: Dispatch<SetStateAction<TBPeriodPairsProps[]>>// RefsrefCalendar: React.MutableRefObject<any>@@ -309,7 +309,7 @@ const ViewProject = () => {const _theme = isBrowser ? theme : ssrTheme- const [periodPairs, setPeriodPairs] = useState<ITBPeriodPairs[]>(tbPeriodPairs(t, undefined, undefined, language))+ const [periodPairs, setPeriodPairs] = useState<TBPeriodPairsProps[]>(tbPeriodPairs(t, undefined, undefined, language))const [customExportTypes, setCustomExportTypes] = useState<any[]>([])const [customPanelTabs, setCustomPanelTabs] = useState<any[]>([])@@ -324,7 +324,7 @@ const ViewProject = () => {const [searchParams, setSearchParams] = useSearchParams()- const [project, setProject] = useState<IProject | null>(null)+ const [project, setProject] = useState<Project | null>(null)const [liveVisitors, setLiveVisitors] = useState<number>(0)const projectPassword = useMemo(@@ -338,15 +338,15 @@ const ViewProject = () => {const [areTimeBucketParsed, setAreTimeBucketParsed] = useState(false)const [panelsData, setPanelsData] = useState<{- types: (keyof IParams)[]- data: IParams- customs: ICustoms- properties: IProperties- meta?: ITrafficMeta[]+ types: (keyof Params)[]+ data: Params+ customs: Customs+ properties: Properties+ meta?: TrafficMeta[]// @ts-expect-error}>({})- const [overall, setOverall] = useState<Partial<IOverallObject>>({})- const [overallPerformance, setOverallPerformance] = useState<Partial<IOverallPerformanceObject>>({})+ const [overall, setOverall] = useState<Partial<OverallObject>>({})+ const [overallPerformance, setOverallPerformance] = useState<Partial<OverallPerformanceObject>>({})const [isPanelsDataEmpty, setIsPanelsDataEmpty] = useState(false)const [isForecastOpened, setIsForecastOpened] = useState(false)const [isNewFunnelOpened, setIsNewFunnelOpened] = useState(false)@@ -384,16 +384,16 @@ const ViewProject = () => {() => !_some({ ...activeChartMetrics, ...activeChartMetricsCustomEvents }, (value) => value),[activeChartMetrics, activeChartMetricsCustomEvents],)- const [customMetrics, setCustomMetrics] = useState<IProjectViewCustomEvent[]>([])- const [filters, setFilters] = useState<IFilter[]>([])- const [filtersPerf, setFiltersPerf] = useState<IFilter[]>([])- const [filtersSessions, setFiltersSessions] = useState<IFilter[]>([])+ const [customMetrics, setCustomMetrics] = useState<ProjectViewCustomEvent[]>([])+ const [filters, setFilters] = useState<Filter[]>([])+ const [filtersPerf, setFiltersPerf] = useState<Filter[]>([])+ const [filtersSessions, setFiltersSessions] = useState<Filter[]>([])const [areFiltersSessionsParsed, setAreFiltersSessionsParsed] = useState(false)- const [filtersErrors, setFiltersErrors] = useState<IFilter[]>([])+ const [filtersErrors, setFiltersErrors] = useState<Filter[]>([])const [areFiltersErrorsParsed, setAreFiltersErrorsParsed] = useState(false)- const [filtersSubError, setFiltersSubError] = useState<IFilter[]>([])+ const [filtersSubError, setFiltersSubError] = useState<Filter[]>([])const [areFiltersSubErrorParsed, setAreFiltersSubErrorParsed] = useState(false)const tnMapping = typeNameMapping(t)@@ -434,15 +434,15 @@ const ViewProject = () => {const [errorStatusUpdating, setErrorStatusUpdating] = useState(false)const [activeEID, setActiveEID] = useState<string | null>(null)- const [activeFunnel, setActiveFunnel] = useState<IFunnel | null>(null)- const [funnelToEdit, setFunnelToEdit] = useState<IFunnel | undefined>(undefined)+ const [activeFunnel, setActiveFunnel] = useState<Funnel | null>(null)+ const [funnelToEdit, setFunnelToEdit] = useState<Funnel | undefined>(undefined)const [funnelActionLoading, setFunnelActionLoading] = useState(false)// null -> not loaded yet- const [projectViews, setProjectViews] = useState<IProjectView[]>([])+ const [projectViews, setProjectViews] = useState<ProjectView[]>([])const [projectViewsLoading, setProjectViewsLoading] = useState<boolean | null>(null) // // null - not loaded, true - loading, false - loadedconst [projectViewDeleting, setProjectViewDeleting] = useState(false)- const [projectViewToUpdate, setProjectViewToUpdate] = useState<IProjectView | undefined>()+ const [projectViewToUpdate, setProjectViewToUpdate] = useState<ProjectView | undefined>()// AI stuffconst [forecasedChartData, setForecasedChartData] = useState({})@@ -647,8 +647,8 @@ const ViewProject = () => {)const [dateRangeCompare, setDateRangeCompare] = useState<null | Date[]>(null)const [dataChartCompare, setDataChartCompare] = useState<any>({})- const [overallCompare, setOverallCompare] = useState<Partial<IOverallObject>>({})- const [overallPerformanceCompare, setOverallPerformanceCompare] = useState<Partial<IOverallPerformanceObject>>({})+ const [overallCompare, setOverallCompare] = useState<Partial<OverallObject>>({})+ const [overallPerformanceCompare, setOverallPerformanceCompare] = useState<Partial<OverallPerformanceObject>>({})const [dataChartPerfCompare, setDataChartPerfCompare] = useState<any>({})const maxRangeCompare = useMemo(() => {if (!isActiveCompare) {@@ -1183,8 +1183,8 @@ const ViewProject = () => {const loadAnalytics = async (forced = false,- newFilters: IFilter[] | null = null,- newMetrics: IProjectViewCustomEvent[] | null = null,+ newFilters: Filter[] | null = null,+ newMetrics: ProjectViewCustomEvent[] | null = null,) => {if (!forced && (authLoading || _isEmpty(project) || dataLoading)) {return@@ -1192,11 +1192,11 @@ const ViewProject = () => {setDataLoading(true)try {- let data: ITrafficLogResponse & {- overall?: IOverallObject+ let data: TrafficLogResponse & {+ overall?: OverallObject}- let dataCompare: ITrafficLogResponse & {- overall?: IOverallObject+ let dataCompare: TrafficLogResponse & {+ overall?: OverallObject}let key = ''let keyCompare = ''@@ -1631,7 +1631,7 @@ const ViewProject = () => {try {const skip = typeof forcedSkip === 'number' ? forcedSkip : sessionsSkip- let dataSessions: { sessions: ISession[]; appliedFilters: any[] }+ let dataSessions: { sessions: Session[]; appliedFilters: any[] }let fromlet to@@ -1696,7 +1696,7 @@ const ViewProject = () => {try {const skip = typeof forcedSkip === 'number' ? forcedSkip : errorsSkip- let dataErrors: { errors: IError[]; appliedFilters: any[] }+ let dataErrors: { errors: SwetrixError[]; appliedFilters: any[] }let fromlet to@@ -2035,7 +2035,7 @@ const ViewProject = () => {let keytry {- let dataFunnel: { funnel: IAnalyticsFunnel[]; totalPageviews: number }+ let dataFunnel: { funnel: AnalyticsFunnel[]; totalPageviews: number }let fromlet to@@ -2118,7 +2118,7 @@ const ViewProject = () => {const columnSessions = `${column}_sess`const columnErrors = `${column}_err`const columnSubErrors = `${column}_subErr`- let filtersToUpdate: IFilter[] = []+ let filtersToUpdate: Filter[] = []switch (activeTab) {case PROJECT_TABS.performance:@@ -2196,7 +2196,7 @@ const ViewProject = () => {}}- const onFilterSearch = (items: IFilter[], override: boolean): void => {+ const onFilterSearch = (items: Filter[], override: boolean): void => {switch (activeTab) {case PROJECT_TABS.performance:handleNavigationParams(@@ -2243,7 +2243,7 @@ const ViewProject = () => {resetErrors()}- const onCustomMetric = (metrics: IProjectViewCustomEvent[]) => {+ const onCustomMetric = (metrics: ProjectViewCustomEvent[]) => {if (activeTab !== PROJECT_TABS.traffic) {return}@@ -2252,7 +2252,7 @@ const ViewProject = () => {loadAnalytics(true, null, metrics)}- const onRemoveCustomMetric = (metricId: IProjectViewCustomEvent['id']) => {+ const onRemoveCustomMetric = (metricId: ProjectViewCustomEvent['id']) => {if (activeTab !== PROJECT_TABS.traffic) {return}@@ -2273,10 +2273,7 @@ const ViewProject = () => {}const onChangeExclusive = (column: string, filter: string, isExclusive: boolean) => {- const updateFilters = (- filters: IFilter[],- setFilters: React.Dispatch<React.SetStateAction<IFilter[]>>,- ): IFilter[] => {+ const updateFilters = (filters: Filter[], setFilters: React.Dispatch<React.SetStateAction<Filter[]>>): Filter[] => {const newFilters = filters.map((f) => (f.column === column && f.filter === filter ? { ...f, isExclusive } : f))if (JSON.stringify(newFilters) !== JSON.stringify(filters)) {setFilters(newFilters)@@ -2284,7 +2281,7 @@ const ViewProject = () => {return newFilters}- let newFilters: IFilter[]+ let newFilters: Filter[]switch (activeTab) {case PROJECT_TABS.performance:@@ -3626,7 +3623,7 @@ const ViewProject = () => {)}}keyExtractor={(item) => item.id}- onSelect={(item: IProjectView, e) => {+ onSelect={(item: ProjectView, e) => {// @ts-expect-errorif (item.createView) {e?.stopPropagation()@@ -4056,7 +4053,7 @@ const ViewProject = () => {)}{activeTab === PROJECT_TABS.funnels && !activeFunnel && !_isEmpty(project.funnels) && (<FunnelsList- openFunnelSettings={(funnel?: IFunnel) => {+ openFunnelSettings={(funnel?: Funnel) => {if (funnel) {setFunnelToEdit(funnel)setIsNewFunnelOpened(true)@@ -4252,7 +4249,7 @@ const ViewProject = () => {if (type === 'cc') {const ccPanelName = tnMapping[countryActiveTab]- const rowMapper = (entry: ICountryEntry) => {+ const rowMapper = (entry: CountryEntry) => {const { name: entryName, cc } = entryif (cc) {@@ -4555,7 +4552,7 @@ const ViewProject = () => {if (type === 'cc') {const ccPanelName = tnMapping[countryActiveTab]- const rowMapper = (entry: ICountryEntry) => {+ const rowMapper = (entry: CountryEntry) => {const { name: entryName, cc } = entryif (cc) {@@ -4860,7 +4857,7 @@ const ViewProject = () => {if (type === 'cc') {const ccPanelName = tnMapping[countryActiveTab]- const rowMapper = (entry: ICountryEntry) => {+ const rowMapper = (entry: CountryEntry) => {const { name: entryName, cc } = entryif (cc) {diff --git a/web/app/pages/Project/View/components/AddAViewModal.tsx b/web/app/pages/Project/View/components/AddAViewModal.tsxindex 64e7f4e1c..1f771bfcc 100644--- a/web/app/pages/Project/View/components/AddAViewModal.tsx+++ b/web/app/pages/Project/View/components/AddAViewModal.tsx@@ -17,21 +17,21 @@ import { getFilters, createProjectView, updateProjectView } from 'api'import { Filter } from './Filters'import Input from 'ui/Input'import {- IFilter,- IProjectView,- IProjectViewCustomEvent,+ Filter as FilterType,+ ProjectView,+ ProjectViewCustomEvent,ProjectViewCustomEventMetaValueType,} from '../interfaces/traffic'import { XMarkIcon } from '@heroicons/react/24/outline'-interface IAddAViewModal {+interface AddAViewModalProps {projectPassword?: stringonSubmit: () => voidpid: stringshowModal: booleansetShowModal: (show: boolean) => voidtnMapping: Record<string, string>- defaultView?: IProjectView+ defaultView?: ProjectView}const getLabelToTypeMap = (t: any): Record<string, string> =>@@ -54,15 +54,15 @@ const InlineButton = ({ text, onClick }: { text: string; onClick: () => void })</button>)-interface IEditMetric {- metric: Partial<IProjectViewCustomEvent>- onChange: (key: keyof IProjectViewCustomEvent, value: any) => void+interface EditMetricProps {+ metric: Partial<ProjectViewCustomEvent>+ onChange: (key: keyof ProjectViewCustomEvent, value: any) => voiderrors: AddAViewModalErrorssetErrors: React.Dispatch<React.SetStateAction<AddAViewModalErrors>>onDelete: () => void}-const EditMetric = ({ metric, onChange, onDelete, errors, setErrors }: IEditMetric) => {+const EditMetric = ({ metric, onChange, onDelete, errors, setErrors }: EditMetricProps) => {const { t } = useTranslation('common')const customEventTypes = useMemo(@@ -180,7 +180,7 @@ const EditMetric = ({ metric, onChange, onDelete, errors, setErrors }: IEditMetr)}-const EMPTY_CUSTOM_EVENT: Partial<IProjectViewCustomEvent> = {+const EMPTY_CUSTOM_EVENT: Partial<ProjectViewCustomEvent> = {customEventName: '',metaKey: '',metaValue: '',@@ -189,7 +189,7 @@ const EMPTY_CUSTOM_EVENT: Partial<IProjectViewCustomEvent> = {interface AddAViewModalErrors {name?: string- [key: `${string}_${keyof IProjectViewCustomEvent}`]: string | undefined+ [key: `${string}_${keyof ProjectViewCustomEvent}`]: string | undefined}const MAX_METRICS_IN_VIEW = 3@@ -202,7 +202,7 @@ const AddAViewModal = ({tnMapping,projectPassword,defaultView,-}: IAddAViewModal) => {+}: AddAViewModalProps) => {const {t,i18n: { language },@@ -210,8 +210,8 @@ const AddAViewModal = ({const [name, setName] = useState(defaultView?.name || '')const [filterType, setFilterType] = useState('')const [searchList, setSearchList] = useState<any[]>([])- const [activeFilters, setActiveFilters] = useState<IFilter[]>(defaultView?.filters || [])- const [customEvents, setCustomEvents] = useState<Partial<IProjectViewCustomEvent>[]>(defaultView?.customEvents || [])+ const [activeFilters, setActiveFilters] = useState<FilterType[]>(defaultView?.filters || [])+ const [customEvents, setCustomEvents] = useState<Partial<ProjectViewCustomEvent>[]>(defaultView?.customEvents || [])const [isViewSubmitting, setIsViewSubmitting] = useState(false)const [errors, setErrors] = useState<AddAViewModalErrors>({})diff --git a/web/app/pages/Project/View/components/CCRow.tsx b/web/app/pages/Project/View/components/CCRow.tsxindex 5639cc731..485c26ff9 100644--- a/web/app/pages/Project/View/components/CCRow.tsx+++ b/web/app/pages/Project/View/components/CCRow.tsx@@ -3,7 +3,7 @@ import _fill from 'lodash/fill'import countries from 'utils/isoCountries'import Flag from 'ui/Flag'-interface ICCRow {+interface CCRowProps {cc: stringname?: stringlanguage: string@@ -11,7 +11,7 @@ interface ICCRow {spaces?: number}-const CCRow = ({ cc, name, language, size = 21, spaces = 2 }: ICCRow): JSX.Element => (+const CCRow = ({ cc, name, language, size = 21, spaces = 2 }: CCRowProps) => (<><Flag className='rounded-sm' country={cc} size={size} alt='' aria-hidden='true' /><spandiff --git a/web/app/pages/Project/View/components/CountryDropdown.tsx b/web/app/pages/Project/View/components/CountryDropdown.tsxindex 3281cb142..eae50404b 100644--- a/web/app/pages/Project/View/components/CountryDropdown.tsx+++ b/web/app/pages/Project/View/components/CountryDropdown.tsx@@ -4,7 +4,7 @@ import { useTranslation } from 'react-i18next'import OutsideClickHandler from 'react-outside-click-handler'import { ChevronDownIcon, ChevronUpIcon, XMarkIcon } from '@heroicons/react/24/outline'-interface ICountryDropdown {+interface CountryDropdownProps {onSelect: anytitle: string}@@ -24,7 +24,7 @@ const OPTIONS = [},]-const CountryDropdown = ({ onSelect, title }: ICountryDropdown): JSX.Element => {+const CountryDropdown = ({ onSelect, title }: CountryDropdownProps) => {const { t } = useTranslation()const [show, setShow] = useState(false)diff --git a/web/app/pages/Project/View/components/CustomEventsDropdown.tsx b/web/app/pages/Project/View/components/CustomEventsDropdown.tsxindex 0d0a9d585..cc426cf68 100644--- a/web/app/pages/Project/View/components/CustomEventsDropdown.tsx+++ b/web/app/pages/Project/View/components/CustomEventsDropdown.tsx@@ -4,7 +4,7 @@ import { useTranslation } from 'react-i18next'import OutsideClickHandler from 'react-outside-click-handler'import { ChevronDownIcon, ChevronUpIcon, XMarkIcon } from '@heroicons/react/24/outline'-interface ICustomEventsDropdown {+interface CustomEventsDropdownProps {onSelect: anytitle: string}@@ -20,7 +20,7 @@ const OPTIONS = [},]-const CustomEventsDropdown = ({ onSelect, title }: ICustomEventsDropdown): JSX.Element => {+const CustomEventsDropdown = ({ onSelect, title }: CustomEventsDropdownProps) => {const { t } = useTranslation()const [show, setShow] = useState(false)diff --git a/web/app/pages/Project/View/components/CustomMetrics.tsx b/web/app/pages/Project/View/components/CustomMetrics.tsxindex db0c294b2..7daf320d9 100644--- a/web/app/pages/Project/View/components/CustomMetrics.tsx+++ b/web/app/pages/Project/View/components/CustomMetrics.tsx@@ -4,14 +4,14 @@ import _isEmpty from 'lodash/isEmpty'import _map from 'lodash/map'import { useTranslation } from 'react-i18next'-import { IProjectViewCustomEvent } from '../interfaces/traffic'+import { ProjectViewCustomEvent } from '../interfaces/traffic'-interface ICustomMetric {- metric: IProjectViewCustomEvent+interface CustomMetricProps {+ metric: ProjectViewCustomEventonRemove: () => void}-const CustomMetric = ({ metric, onRemove }: ICustomMetric): JSX.Element => {+const CustomMetric = ({ metric, onRemove }: CustomMetricProps) => {const { t } = useTranslation('common')const displayValue = useMemo(() => {@@ -65,13 +65,13 @@ const CustomMetric = ({ metric, onRemove }: ICustomMetric): JSX.Element => {)}-interface IFilters {- metrics: IProjectViewCustomEvent[]- onRemoveMetric: (id: IProjectViewCustomEvent['id']) => void+interface FiltersProps {+ metrics: ProjectViewCustomEvent[]+ onRemoveMetric: (id: ProjectViewCustomEvent['id']) => voidresetMetrics: () => void}-const CustomMetrics = ({ metrics, onRemoveMetric, resetMetrics }: IFilters) => {+const CustomMetrics = ({ metrics, onRemoveMetric, resetMetrics }: FiltersProps) => {if (_isEmpty(metrics)) {return null}diff --git a/web/app/pages/Project/View/components/ErrorChart.tsx b/web/app/pages/Project/View/components/ErrorChart.tsxindex 517e75250..ff5709a21 100644--- a/web/app/pages/Project/View/components/ErrorChart.tsx+++ b/web/app/pages/Project/View/components/ErrorChart.tsx@@ -2,7 +2,7 @@ import { useEffect } from 'react'import bb from 'billboard.js'import { getSettingsError } from '../ViewProject.helpers'-interface IErrorChart {+interface ErrorChartProps {chart?: {x: string[]occurrences: number[]@@ -14,7 +14,7 @@ interface IErrorChart {dataNames: any}-export const ErrorChart = ({ chart, timeBucket, timeFormat, rotateXAxis, chartType, dataNames }: IErrorChart) => {+export const ErrorChart = ({ chart, timeBucket, timeFormat, rotateXAxis, chartType, dataNames }: ErrorChartProps) => {useEffect(() => {// @ts-ignoreconst bbSettings: bb.ChartOptions = getSettingsError(diff --git a/web/app/pages/Project/View/components/ErrorDetails.tsx b/web/app/pages/Project/View/components/ErrorDetails.tsxindex 9d92ed65f..d486ee8e7 100644--- a/web/app/pages/Project/View/components/ErrorDetails.tsx+++ b/web/app/pages/Project/View/components/ErrorDetails.tsx@@ -1,15 +1,15 @@import React, { useMemo } from 'react'import { useTranslation } from 'react-i18next'-import { IErrorDetails } from '../interfaces/error'+import { SwetrixErrorDetails } from '../interfaces/error'import { MetricCard } from './MetricCards'import { getRelativeDateIfPossible } from 'utils/date'import Tooltip from 'ui/Tooltip'-interface IErrorDetailsComponent {- details: IErrorDetails+interface ErrorDetailsProps {+ details: SwetrixErrorDetails}-export const ErrorDetails = ({ details }: IErrorDetailsComponent) => {+export const ErrorDetails = ({ details }: ErrorDetailsProps) => {const {t,i18n: { language },diff --git a/web/app/pages/Project/View/components/Errors.tsx b/web/app/pages/Project/View/components/Errors.tsxindex 2fe85af66..7a7ce4692 100644--- a/web/app/pages/Project/View/components/Errors.tsx+++ b/web/app/pages/Project/View/components/Errors.tsx@@ -6,32 +6,31 @@ import _map from 'lodash/map'import cx from 'clsx'import { ChevronRightIcon } from '@heroicons/react/24/outline'import Loader from 'ui/Loader'-import { IError } from '../interfaces/error'+import { SwetrixError } from '../interfaces/error'import { getRelativeDateIfPossible } from 'utils/date'import { Badge } from 'ui/Badge'-interface IErrors {- errors: IError[]+interface ErrorsProps {+ errors: SwetrixError[]onClick: (psid: string) => void}-interface IErrorItem {- error: IError+interface ErrorItemProps {+ error: SwetrixErroronClick: (psid: string) => void- className?: string}-interface ISeparator {+interface SeparatorProps {className?: string}-const Separator = ({ className }: ISeparator) => (+const Separator = ({ className }: SeparatorProps) => (<svg viewBox='0 0 2 2' className={cx('h-0.5 w-0.5 flex-none fill-gray-400', className)}><circle cx={1} cy={1} r={1} /></svg>)-const ErrorItem = ({ error, onClick, className }: IErrorItem) => {+const ErrorItem = ({ error, onClick }: ErrorItemProps) => {const {t,i18n: { language },@@ -121,7 +120,7 @@ const ErrorItem = ({ error, onClick, className }: IErrorItem) => {)}-export const Errors: React.FC<IErrors> = ({ errors, onClick }) => {+export const Errors = ({ errors, onClick }: ErrorsProps) => {return (<ClientOnlyfallback={@@ -132,13 +131,8 @@ export const Errors: React.FC<IErrors> = ({ errors, onClick }) => {>{() => (<ul className='mt-4'>- {_map(errors, (error, index) => (- <ErrorItem- key={error.eid}- error={error}- onClick={onClick}- className={`${index === 0 && 'rounded-t-md'} ${index === errors.length - 1 && 'rounded-b-md'}`}- />+ {_map(errors, (error) => (+ <ErrorItem key={error.eid} error={error} onClick={onClick} />))}</ul>)}diff --git a/web/app/pages/Project/View/components/Filters.tsx b/web/app/pages/Project/View/components/Filters.tsxindex 6409a0a4a..2c50c2d10 100644--- a/web/app/pages/Project/View/components/Filters.tsx+++ b/web/app/pages/Project/View/components/Filters.tsx@@ -11,7 +11,7 @@ import { useTranslation } from 'react-i18next'import countries from 'utils/isoCountries'import { getLocaleDisplayName } from 'utils/generic'-interface IFilter {+interface FilterProps {column: stringfilter: stringisExclusive: boolean@@ -33,7 +33,7 @@ export const Filter = ({tnMapping,canChangeExclusive,removable,-}: IFilter): JSX.Element => {+}: FilterProps) => {const {t,i18n: { language },@@ -111,7 +111,7 @@ export const Filter = ({)}-interface IFilters {+interface FiltersProps {filters: {column: stringfilter: string@@ -125,7 +125,7 @@ interface IFilters {resetFilters: () => void}-const Filters = ({ filters, onRemoveFilter, onChangeExclusive, tnMapping, resetFilters }: IFilters) => {+const Filters = ({ filters, onRemoveFilter, onChangeExclusive, tnMapping, resetFilters }: FiltersProps) => {if (_isEmpty(filters)) {return null}diff --git a/web/app/pages/Project/View/components/FunnelsList.tsx b/web/app/pages/Project/View/components/FunnelsList.tsxindex 3f4e5a0a8..232431d94 100644--- a/web/app/pages/Project/View/components/FunnelsList.tsx+++ b/web/app/pages/Project/View/components/FunnelsList.tsx@@ -3,29 +3,29 @@ import _map from 'lodash/map'import cx from 'clsx'import { useTranslation } from 'react-i18next'import { AdjustmentsVerticalIcon, PlusCircleIcon, TrashIcon } from '@heroicons/react/24/outline'-import { IFunnel } from 'redux/models/IProject'+import { Funnel } from 'redux/models/Project'-interface IFunnelsList {+interface FunnelsListProps {funnels?: any[]- openFunnelSettings: (funnel?: IFunnel) => void- openFunnel: (funnel: IFunnel) => void+ openFunnelSettings: (funnel?: Funnel) => void+ openFunnel: (funnel: Funnel) => voiddeleteFunnel: (id: string) => voidloading: booleanauthenticated: booleanallowedToManage: boolean}-interface IFunnelCard {- funnel: IFunnel- openFunnelSettings: (funnel: IFunnel) => void- openFunnel: (funnel: IFunnel) => void+interface FunnelCardProps {+ funnel: Funnel+ openFunnelSettings: (funnel: Funnel) => void+ openFunnel: (funnel: Funnel) => voiddeleteFunnel: (id: string) => voidloading: booleanallowedToManage: boolean}-interface IAddFunnel {- openFunnelSettings: (funnel?: IFunnel) => void+interface AddFunnelProps {+ openFunnelSettings: (funnel?: Funnel) => void}const FunnelCard = ({@@ -35,7 +35,7 @@ const FunnelCard = ({deleteFunnel,loading,allowedToManage,-}: IFunnelCard): JSX.Element => {+}: FunnelCardProps) => {const { t } = useTranslation()return (@@ -80,7 +80,7 @@ const FunnelCard = ({)}-const AddFunnel = ({ openFunnelSettings }: IAddFunnel): JSX.Element => {+const AddFunnel = ({ openFunnelSettings }: AddFunnelProps) => {const { t } = useTranslation()const onClick = () => {@@ -110,7 +110,7 @@ const FunnelsList = ({loading,authenticated,allowedToManage,-}: IFunnelsList): JSX.Element => (+}: FunnelsListProps) => (<ul className='mt-4 grid grid-cols-1 gap-x-6 gap-y-3 lg:grid-cols-3 lg:gap-y-6'>{_map(funnels, (funnel) => (<FunnelCarddiff --git a/web/app/pages/Project/View/components/InteractiveMap.tsx b/web/app/pages/Project/View/components/InteractiveMap.tsxindex 29e44eef0..b4a6a8071 100644--- a/web/app/pages/Project/View/components/InteractiveMap.tsx+++ b/web/app/pages/Project/View/components/InteractiveMap.tsx@@ -7,40 +7,40 @@ import countries from 'utils/isoCountries'import { PROJECT_TABS } from 'redux/constants'import { getTimeFromSeconds, getStringFromTime, nFormatter } from 'utils/generic'-import { IEntry } from 'redux/models/IEntry'+import { Entry } from 'redux/models/Entry'import countriesList from 'utils/countries'import { useSearchParams } from '@remix-run/react'-interface IInteractiveMap {- data: IEntry[]+interface InteractiveMapProps {+ data: Entry[]onClickCountry: (country: string) => voidtotal: number}-interface ICursorPosition {+interface CursorPosition {pageX: numberpageY: number}-interface IDataHover {+interface DataHover {countries: stringdata: number}-interface ICountryMap {+interface CountryMap {[key: string]: number}-const InteractiveMap = ({ data, onClickCountry, total }: IInteractiveMap) => {+const InteractiveMap = ({ data, onClickCountry, total }: InteractiveMapProps) => {const {t,i18n: { language },} = useTranslation('common')const [searchParams] = useSearchParams()const [hoverShow, setHoverShow] = useState(false)- const [dataHover, setDataHover] = useState<IDataHover>({} as IDataHover)- const [cursorPosition, setCursorPosition] = useState<ICursorPosition>({} as ICursorPosition)- const countryMap: ICountryMap = useMemo(+ const [dataHover, setDataHover] = useState<DataHover>({} as DataHover)+ const [cursorPosition, setCursorPosition] = useState<CursorPosition>({} as CursorPosition)+ const countryMap: CountryMap = useMemo(() => _reduce(data, (prev, curr) => ({ ...prev, [curr.cc || curr.name]: curr.count }), {}),[data],)diff --git a/web/app/pages/Project/View/components/LiveVisitorsDropdown.tsx b/web/app/pages/Project/View/components/LiveVisitorsDropdown.tsxindex a17136f55..e3fe66b4c 100644--- a/web/app/pages/Project/View/components/LiveVisitorsDropdown.tsx+++ b/web/app/pages/Project/View/components/LiveVisitorsDropdown.tsx@@ -4,24 +4,24 @@ import { useTranslation } from 'react-i18next'import OutsideClickHandler from 'react-outside-click-handler'import { ChevronDownIcon, ChevronUpIcon, XMarkIcon } from '@heroicons/react/24/outline'-import { getLiveVisitorsInfo, IGetLiveVisitorsInfo } from 'api'+import { getLiveVisitorsInfo, GetLiveVisitorsInfo } from 'api'import PulsatingCircle from 'ui/icons/PulsatingCircle'import Flag from 'ui/Flag'import { useViewProjectContext } from '../ViewProject'import { Link } from '@remix-run/react'import { PROJECT_TABS } from 'redux/constants'-interface ILiveVisitorsDropdown {+interface LiveVisitorsDropdownProps {live: number | stringonSessionSelect: (psid: string) => void}-const LiveVisitorsDropdown = ({ live, onSessionSelect }: ILiveVisitorsDropdown): JSX.Element => {+const LiveVisitorsDropdown = ({ live, onSessionSelect }: LiveVisitorsDropdownProps) => {const { projectId, projectPassword } = useViewProjectContext()const { t } = useTranslation()const [show, setShow] = useState(false)const [loading, setLoading] = useState(true)- const [liveInfo, setLiveInfo] = useState<IGetLiveVisitorsInfo[]>([])+ const [liveInfo, setLiveInfo] = useState<GetLiveVisitorsInfo[]>([])const getLiveVisitors = async () => {try {diff --git a/web/app/pages/Project/View/components/LockedDashboard.tsx b/web/app/pages/Project/View/components/LockedDashboard.tsxindex 39bdb4afb..1e816f90f 100644--- a/web/app/pages/Project/View/components/LockedDashboard.tsx+++ b/web/app/pages/Project/View/components/LockedDashboard.tsx@@ -1,17 +1,17 @@import React, { useMemo } from 'react'import { LockClosedIcon } from '@heroicons/react/24/outline'import { Link } from '@remix-run/react'-import { IUser, DashboardBlockReason } from 'redux/models/IUser'-import { IProjectForShared } from 'redux/models/ISharedProject'+import { User, DashboardBlockReason } from 'redux/models/User'+import { ProjectForShared } from 'redux/models/SharedProject'import { useTranslation } from 'react-i18next'import routes from 'utils/routes'-interface ILockedDashboard {- user?: IUser- project: IProjectForShared+interface LockedDashboardProps {+ user?: User+ project: ProjectForShared}-const LockedDashboard = ({ user, project }: ILockedDashboard) => {+const LockedDashboard = ({ user, project }: LockedDashboardProps) => {const { t } = useTranslation('common')const message = useMemo(() => {diff --git a/web/app/pages/Project/View/components/MetricCards.tsx b/web/app/pages/Project/View/components/MetricCards.tsxindex ad52d8f7b..247f14f72 100644--- a/web/app/pages/Project/View/components/MetricCards.tsx+++ b/web/app/pages/Project/View/components/MetricCards.tsx@@ -7,12 +7,12 @@ import _isEmpty from 'lodash/isEmpty'import _isNumber from 'lodash/isNumber'import _map from 'lodash/map'import { nFormatter, getStringFromTime, getTimeFromSeconds } from 'utils/generic'-import { IOverallObject, IOverallPerformanceObject } from 'redux/models/IProject'+import { OverallObject, OverallPerformanceObject } from 'redux/models/Project'import { ChevronDownIcon, ChevronUpIcon, XMarkIcon } from '@heroicons/react/24/outline'import { Badge } from 'ui/Badge'import { MonitorOverallObject } from 'redux/models/Uptime'-interface IMetricCard {+interface MetricCardProps {label: stringvalue: string | number | undefined | nullgoodChangeDirection?: 'up' | 'down'@@ -26,7 +26,7 @@ interface IMetricCard {}}-const ChangeBadge = ({ change, type, goodChangeDirection, valueMapper }: Partial<IMetricCard>) => {+const ChangeBadge = ({ change, type, goodChangeDirection, valueMapper }: Partial<MetricCardProps>) => {if (!_isNumber(change)) {return null}@@ -62,7 +62,7 @@ const ChangeBadge = ({ change, type, goodChangeDirection, valueMapper }: Partial}}-export const MetricCard: React.FC<IMetricCard> = ({+export const MetricCard: React.FC<MetricCardProps> = ({label,value,change,@@ -90,7 +90,7 @@ export const MetricCard: React.FC<IMetricCard> = ({</div>)-interface IMetricCardSelect {+interface MetricCardSelectProps {values: {label: stringvalue: string | number | undefined | null@@ -104,7 +104,7 @@ interface IMetricCardSelect {}}-export const MetricCardSelect: React.FC<IMetricCardSelect> = ({ values, valueMapper, selectLabel, classes }) => {+export const MetricCardSelect = ({ values, valueMapper, selectLabel, classes }: MetricCardSelectProps) => {const [selected, setSelected] = useState(0)const [show, setShow] = useState(false)@@ -153,13 +153,13 @@ export const MetricCardSelect: React.FC<IMetricCardSelect> = ({ values, valueMap)}-interface IMetricCards {- overall: Partial<IOverallObject>- overallCompare?: Partial<IOverallObject>+interface MetricCardsProps {+ overall: Partial<OverallObject>+ overallCompare?: Partial<OverallObject>activePeriodCompare?: string}-export const MetricCards = memo(({ overall, overallCompare, activePeriodCompare }: IMetricCards) => {+export const MetricCards = memo(({ overall, overallCompare, activePeriodCompare }: MetricCardsProps) => {const { t } = useTranslation('common')let uniqueChange = overall.uniqueChange@@ -226,11 +226,11 @@ export const MetricCards = memo(({ overall, overallCompare, activePeriodCompare)})-interface IMetricCardsUptime {+interface MetricCardsUptimeProps {overall: MonitorOverallObject}-export const MetricCardsUptime = memo(({ overall }: IMetricCardsUptime) => {+export const MetricCardsUptime = memo(({ overall }: MetricCardsUptimeProps) => {const { t } = useTranslation()return (@@ -266,14 +266,14 @@ export const MetricCardsUptime = memo(({ overall }: IMetricCardsUptime) => {)})-interface IPerformanceMetricCards {- overall: Partial<IOverallPerformanceObject>- overallCompare?: Partial<IOverallPerformanceObject>+interface PerformanceMetricCardsProps {+ overall: Partial<OverallPerformanceObject>+ overallCompare?: Partial<OverallPerformanceObject>activePeriodCompare?: string}export const PerformanceMetricCards = memo(- ({ overall, overallCompare, activePeriodCompare }: IPerformanceMetricCards) => {+ ({ overall, overallCompare, activePeriodCompare }: PerformanceMetricCardsProps) => {const { t } = useTranslation('common')let frontendChange = overall.frontendChangediff --git a/web/app/pages/Project/View/components/NoEvents.tsx b/web/app/pages/Project/View/components/NoEvents.tsxindex 4cac39f19..e013f835a 100644--- a/web/app/pages/Project/View/components/NoEvents.tsx+++ b/web/app/pages/Project/View/components/NoEvents.tsx@@ -3,14 +3,14 @@ import { useTranslation } from 'react-i18next'import _isEmpty from 'lodash/isEmpty'import Button from 'ui/Button'-import { IFilter } from '../interfaces/traffic'+import { Filter } from '../interfaces/traffic'-interface INoEvents {- filters: IFilter[]+interface NoEventsProps {+ filters: Filter[]resetFilters: () => void}-const NoEvents = ({ filters, resetFilters }: INoEvents): JSX.Element => {+const NoEvents = ({ filters, resetFilters }: NoEventsProps) => {const { t } = useTranslation('common')return (diff --git a/web/app/pages/Project/View/components/Pageflow.tsx b/web/app/pages/Project/View/components/Pageflow.tsxindex 0f271f1c1..12c54c325 100644--- a/web/app/pages/Project/View/components/Pageflow.tsx+++ b/web/app/pages/Project/View/components/Pageflow.tsx@@ -4,17 +4,17 @@ import _map from 'lodash/map'import _toUpper from 'lodash/toUpper'import { Trans, useTranslation } from 'react-i18next'-interface IMetadata {+interface Metadata {key: stringvalue: string}-interface IPageflow {+interface PageflowProps {pages: {type: 'pageview' | 'event'value: stringcreated: string- metadata?: IMetadata[]+ metadata?: Metadata[]}[]timeFormat: '12-hour' | '24-hour'}@@ -25,7 +25,7 @@ const KeyValue = ({ evKey, evValue }: { evKey: string; evValue: string }) => (</li>)-const TransValue = ({ metadata, children }: { metadata?: IMetadata[]; children: React.ReactNode }) => (+const TransValue = ({ metadata, children }: { metadata?: Metadata[]; children: React.ReactNode }) => (<div className='ml-1 text-gray-900 dark:text-gray-50'><p className='font-medium'>{children}</p>{metadata ? (@@ -38,7 +38,7 @@ const TransValue = ({ metadata, children }: { metadata?: IMetadata[]; children:</div>)-export const Pageflow = ({ pages, timeFormat }: IPageflow) => {+export const Pageflow = ({ pages, timeFormat }: PageflowProps) => {const {t,i18n: { language },diff --git a/web/app/pages/Project/View/components/RefRow.tsx b/web/app/pages/Project/View/components/RefRow.tsxindex 2cb947b13..40c3de2da 100644--- a/web/app/pages/Project/View/components/RefRow.tsx+++ b/web/app/pages/Project/View/components/RefRow.tsx@@ -1,6 +1,6 @@import { memo, useMemo } from 'react'-const RefRow = ({ rowName }: { rowName: string }): JSX.Element => {+const RefRow = ({ rowName }: { rowName: string }) => {const { isUrl, url } = useMemo(() => {try {const urlObj = new URL(rowName)diff --git a/web/app/pages/Project/View/components/SearchFilters.tsx b/web/app/pages/Project/View/components/SearchFilters.tsxindex 4863f1aa6..3cea095b0 100644--- a/web/app/pages/Project/View/components/SearchFilters.tsx+++ b/web/app/pages/Project/View/components/SearchFilters.tsx@@ -13,16 +13,16 @@ import { FILTERS_PANELS_ORDER, ERRORS_FILTERS_PANELS_ORDER } from 'redux/constanimport countries from 'utils/isoCountries'import { getFilters, getErrorsFilters } from 'api'import { Filter } from './Filters'-import { IFilter } from '../interfaces/traffic'+import { Filter as FilterType } from '../interfaces/traffic'-interface ISearchFilters {+interface SearchFiltersProps {projectPassword?: string- setProjectFilter: (filters: IFilter[], override: boolean) => void+ setProjectFilter: (filters: FilterType[], override: boolean) => voidpid: stringshowModal: booleansetShowModal: (show: boolean) => voidtnMapping: Record<string, string>- filters: IFilter[]+ filters: FilterType[]type: 'traffic' | 'errors'}@@ -35,14 +35,14 @@ const SearchFilters = ({filters,projectPassword,type,-}: ISearchFilters) => {+}: SearchFiltersProps) => {const {t,i18n: { language },} = useTranslation('common')const [filterType, setFilterType] = useState('')const [searchList, setSearchList] = useState<any[]>([])- const [activeFilters, setActiveFilters] = useState<IFilter[]>([])+ const [activeFilters, setActiveFilters] = useState<FilterType[]>([])const [override, setOverride] = useState(false)const getFiltersList = useCallback(diff --git a/web/app/pages/Project/View/components/SessionChart.tsx b/web/app/pages/Project/View/components/SessionChart.tsxindex 807459820..ce8e452f7 100644--- a/web/app/pages/Project/View/components/SessionChart.tsx+++ b/web/app/pages/Project/View/components/SessionChart.tsx@@ -2,7 +2,7 @@ import React, { useEffect } from 'react'import bb from 'billboard.js'import { getSettingsSession } from '../ViewProject.helpers'-interface ISessionChart {+interface SessionChartProps {chart?: {x: string[]visits: number[]@@ -14,7 +14,14 @@ interface ISessionChart {dataNames: any}-export const SessionChart = ({ chart, timeBucket, timeFormat, rotateXAxis, chartType, dataNames }: ISessionChart) => {+export const SessionChart = ({+ chart,+ timeBucket,+ timeFormat,+ rotateXAxis,+ chartType,+ dataNames,+}: SessionChartProps) => {// const [bbChart, setBBChart] = useState<bb.Chart | null>(null)useEffect(() => {diff --git a/web/app/pages/Project/View/components/SessionDetails.tsx b/web/app/pages/Project/View/components/SessionDetails.tsxindex 7e80e2894..f7b0be298 100644--- a/web/app/pages/Project/View/components/SessionDetails.tsx+++ b/web/app/pages/Project/View/components/SessionDetails.tsx@@ -4,15 +4,15 @@ import _capitalize from 'lodash/capitalize'import _size from 'lodash/size'import _truncate from 'lodash/truncate'import { getLocaleDisplayName, getStringFromTime, getTimeFromSeconds } from 'utils/generic'-import { ISessionDetails } from '../interfaces/session'+import { SessionDetails as Details } from '../interfaces/session'import { MetricCard, MetricCardSelect } from './MetricCards'import CCRow from './CCRow'-interface ISessionDetailsComponent {- details: ISessionDetails+interface SessionDetailsProps {+ details: Details}-export const SessionDetails = ({ details }: ISessionDetailsComponent) => {+export const SessionDetails = ({ details }: SessionDetailsProps) => {const {t,i18n: { language },diff --git a/web/app/pages/Project/View/components/Sessions.tsx b/web/app/pages/Project/View/components/Sessions.tsxindex 64fdb96a7..26fdedbfb 100644--- a/web/app/pages/Project/View/components/Sessions.tsx+++ b/web/app/pages/Project/View/components/Sessions.tsx@@ -5,17 +5,17 @@ import { useTranslation } from 'react-i18next'import _map from 'lodash/map'import { ChevronRightIcon } from '@heroicons/react/24/outline'import Loader from 'ui/Loader'-import { ISession } from '../interfaces/session'+import { Session as SessionType } from '../interfaces/session'import CCRow from './CCRow'-interface ISessions {- sessions: ISession[]+interface SessionsProps {+ sessions: SessionType[]onClick: (psid: string) => voidtimeFormat: '12-hour' | '24-hour'}-interface ISessionComponent {- session: ISession+interface SessionProps {+ session: SessionTypeonClick: (psid: string) => voidtimeFormat: '12-hour' | '24-hour'}@@ -26,7 +26,7 @@ const Separator = () => (</svg>)-const Session = ({ session, onClick, timeFormat }: ISessionComponent) => {+const Session = ({ session, onClick, timeFormat }: SessionProps) => {const {t,i18n: { language },@@ -87,7 +87,7 @@ const Session = ({ session, onClick, timeFormat }: ISessionComponent) => {)}-export const Sessions: React.FC<ISessions> = ({ sessions, onClick, timeFormat }) => {+export const Sessions: React.FC<SessionsProps> = ({ sessions, onClick, timeFormat }) => {return (<ClientOnlyfallback={diff --git a/web/app/pages/Project/View/components/TBPeriodSelector.tsx b/web/app/pages/Project/View/components/TBPeriodSelector.tsxindex bcb9f896c..c6d3da489 100644--- a/web/app/pages/Project/View/components/TBPeriodSelector.tsx+++ b/web/app/pages/Project/View/components/TBPeriodSelector.tsx@@ -8,7 +8,7 @@ import _includes from 'lodash/includes'import cx from 'clsx'import { ALL_PERIODS } from 'redux/constants'-interface ITBPeriodSelector {+interface TBPeriodSelectorProps {title: string | number | React.ReactNodeitems: any[]/* (function): A function that is called when an item is selected. */@@ -30,7 +30,7 @@ const TBPeriodSelector = ({updateTimebucket,timeBucket,classes,-}: ITBPeriodSelector): JSX.Element => {+}: TBPeriodSelectorProps) => {const { t } = useTranslation('common')const periods = useMemo(() => {diff --git a/web/app/pages/Project/View/components/UTMDropdown.tsx b/web/app/pages/Project/View/components/UTMDropdown.tsxindex d71927557..0662f42b2 100644--- a/web/app/pages/Project/View/components/UTMDropdown.tsx+++ b/web/app/pages/Project/View/components/UTMDropdown.tsx@@ -4,7 +4,7 @@ import { useTranslation } from 'react-i18next'import OutsideClickHandler from 'react-outside-click-handler'import { ChevronDownIcon, ChevronUpIcon, XMarkIcon } from '@heroicons/react/24/outline'-interface IUTMDropdown {+interface UTMDropdownProps {onSelect: anytitle: string}@@ -32,7 +32,7 @@ const OPTIONS = [},]-const UTMDropdown = ({ onSelect, title }: IUTMDropdown): JSX.Element => {+const UTMDropdown = ({ onSelect, title }: UTMDropdownProps) => {const { t } = useTranslation()const [show, setShow] = useState(false)diff --git a/web/app/pages/Project/View/components/UserFlow.tsx b/web/app/pages/Project/View/components/UserFlow.tsxindex 1c66c6a26..425641a4f 100644--- a/web/app/pages/Project/View/components/UserFlow.tsx+++ b/web/app/pages/Project/View/components/UserFlow.tsx@@ -4,12 +4,12 @@ import { ResponsiveSankey } from '@nivo/sankey'import { connect } from 'react-redux'import { StateType, AppDispatch } from 'redux/store'import UIActions from 'redux/reducers/ui'-import { IUserFlow } from 'redux/models/IUserFlow'+import { IUserFlow } from 'redux/models/UserFlow'import _isEmpty from 'lodash/isEmpty'import { getUserFlowCacheKey } from 'redux/constants'import { getUserFlow } from 'api'import Loader from 'ui/Loader'-import { IFilter } from '../interfaces/traffic'+import { Filter } from '../interfaces/traffic'import { useTranslation } from 'react-i18next'const mapStateToProps = (state: StateType) => ({@@ -57,7 +57,7 @@ interface UserFlowProps {isReversed?: booleansetUserFlowAscending: (data: IUserFlow, id: string, pd: string, fltr: any) => voidsetUserFlowDescending: (data: IUserFlow, id: string, pd: string, fltr: any) => void- filters: IFilter[]+ filters: Filter[]setReversed: () => voidprojectPassword?: string}diff --git a/web/app/pages/Project/View/components/WaitingForAnEvent.tsx b/web/app/pages/Project/View/components/WaitingForAnEvent.tsxindex d7b75424a..245c5a678 100644--- a/web/app/pages/Project/View/components/WaitingForAnEvent.tsx+++ b/web/app/pages/Project/View/components/WaitingForAnEvent.tsx@@ -1,20 +1,20 @@import React, { useState } from 'react'import { Link } from '@remix-run/react'-import { IUser } from 'redux/models/IUser'-import { IProjectForShared } from 'redux/models/ISharedProject'+import { User } from 'redux/models/User'+import { ProjectForShared } from 'redux/models/SharedProject'import { useTranslation, Trans } from 'react-i18next'import routes from 'utils/routes'import PulsatingCircle from 'ui/icons/PulsatingCircle'import TrackingSnippet from 'modals/TrackingSnippet'-interface IWaitingForAnEvent {- user?: IUser- project: IProjectForShared+interface WaitingForAnEventProps {+ user?: User+ project: ProjectForShared}const TROUBLESHOOTING_URL = 'https://docs.swetrix.com/troubleshooting'-const WaitingForAnEvent = ({ project }: IWaitingForAnEvent) => {+const WaitingForAnEvent = ({ project }: WaitingForAnEventProps) => {const { t } = useTranslation('common')const [isModalOpened, setIsModalOpened] = useState(false)diff --git a/web/app/pages/Project/View/interfaces/ai.tsx b/web/app/pages/Project/View/interfaces/ai.tsxindex 0864b2938..5b0745a6a 100644--- a/web/app/pages/Project/View/interfaces/ai.tsx+++ b/web/app/pages/Project/View/interfaces/ai.tsx@@ -1,4 +1,4 @@-import { IParams } from './traffic'+import { Params } from './traffic'interface AIProperty {[key: string]: number@@ -24,11 +24,11 @@ export interface AIResponse {}export interface AIProcessedResponse {- next_1_hour?: IParams- next_4_hour?: IParams- next_8_hour?: IParams- next_12_hour?: IParams- next_24_hour?: IParams- next_72_hour?: IParams- next_168_hour?: IParams+ next_1_hour?: Params+ next_4_hour?: Params+ next_8_hour?: Params+ next_12_hour?: Params+ next_24_hour?: Params+ next_72_hour?: Params+ next_168_hour?: Params}diff --git a/web/app/pages/Project/View/interfaces/error.tsx b/web/app/pages/Project/View/interfaces/error.tsxindex b3103fe01..cac013e4c 100644--- a/web/app/pages/Project/View/interfaces/error.tsx+++ b/web/app/pages/Project/View/interfaces/error.tsx@@ -1,4 +1,4 @@-export interface IError {+export interface SwetrixError {eid: stringname: stringmessage: string@@ -8,7 +8,7 @@ export interface IError {status: 'active' | 'regressed' | 'fixed'}-export interface IErrorDetails extends IError {+export interface SwetrixErrorDetails extends SwetrixError {colno: numberlineno: numberfirst_seen: stringdiff --git a/web/app/pages/Project/View/interfaces/session.tsx b/web/app/pages/Project/View/interfaces/session.tsxindex 5bf892db3..77fdc4aa2 100644--- a/web/app/pages/Project/View/interfaces/session.tsx+++ b/web/app/pages/Project/View/interfaces/session.tsx@@ -1,4 +1,4 @@-export interface ISession {+export interface Session {psid: stringcc: string | nullos: string | null@@ -8,7 +8,7 @@ export interface ISession {active: 1 | 0}-export interface ISessionDetails {+export interface SessionDetails {cc: string | nullos: string | nullosv: string | nulldiff --git a/web/app/pages/Project/View/interfaces/traffic.tsx b/web/app/pages/Project/View/interfaces/traffic.tsxindex 955ee0b58..0d9192414 100644--- a/web/app/pages/Project/View/interfaces/traffic.tsx+++ b/web/app/pages/Project/View/interfaces/traffic.tsx@@ -1,4 +1,4 @@-export interface IFilter {+export interface Filter {column: stringfilter: stringisExclusive: boolean@@ -10,7 +10,7 @@ export enum ProjectViewCustomEventMetaValueType {FLOAT = 'float',}-export interface IProjectViewCustomEvent {+export interface ProjectViewCustomEvent {id: stringcustomEventName: stringmetaKey?: string@@ -19,52 +19,52 @@ export interface IProjectViewCustomEvent {metaValueType: ProjectViewCustomEventMetaValueType}-export interface IProjectView {+export interface ProjectView {id: stringname: string- filters?: IFilter[]- customEvents?: IProjectViewCustomEvent[]+ filters?: Filter[]+ customEvents?: ProjectViewCustomEvent[]}-interface IParam {+interface Param {name: stringcount: number}-export interface IParams {- [key: string]: IParam[]+export interface Params {+ [key: string]: Param[]}-export interface ICustoms {+export interface Customs {[key: string]: number}-export interface IProperties {+export interface Properties {[key: string]: number}-interface IMetric {+interface Metric {sum: numberavg: number}-export interface ITrafficMeta {+export interface TrafficMeta {key: string- current: IMetric- previous: IMetric+ current: Metric+ previous: Metric}-export interface ITrafficLogResponse {- params?: IParams+export interface TrafficLogResponse {+ params?: Paramschart?: {x: string[]visits: number[]uniques: number[]sdur: number[]}- customs: ICustoms- properties: IProperties- appliedFilters?: IFilter[]+ customs: Customs+ properties: Properties+ appliedFilters?: Filter[]timeBucket?: string[]- meta?: ITrafficMeta[]+ meta?: TrafficMeta[]}diff --git a/web/app/pages/Project/View/utils/filters.tsx b/web/app/pages/Project/View/utils/filters.tsxindex 27c0ff7ee..4d864874c 100644--- a/web/app/pages/Project/View/utils/filters.tsx+++ b/web/app/pages/Project/View/utils/filters.tsx@@ -1,5 +1,5 @@import React from 'react'-import { IFilter } from '../interfaces/traffic'+import { Filter } from '../interfaces/traffic'import _includes from 'lodash/includes'import _replace from 'lodash/replace'import _startsWith from 'lodash/startsWith'@@ -78,13 +78,8 @@ export const isFilterValid = (filter: string, checkDynamicFilters = false) => {return false}-const applyFilters = (- items: IFilter[],- suffix: string,- searchParams: URLSearchParams,- override: boolean,-): IFilter[] => {- const filtersToLoad: IFilter[] = []+const applyFilters = (items: Filter[], suffix: string, searchParams: URLSearchParams, override: boolean): Filter[] => {+ const filtersToLoad: Filter[] = []items.forEach((item) => {if (!item.filter) return@@ -104,13 +99,13 @@ const applyFilters = (}export const handleNavigationParams = (- items: IFilter[],+ items: Filter[],suffix: string,searchParams: URLSearchParams,setSearchParams: React.Dispatch<React.SetStateAction<URLSearchParams>>,override: boolean,- stateSetter: React.Dispatch<React.SetStateAction<IFilter[]>>,- loader: (forceReload: boolean, filters: IFilter[]) => void,+ stateSetter: React.Dispatch<React.SetStateAction<Filter[]>>,+ loader: (forceReload: boolean, filters: Filter[]) => void,): void => {const filters = applyFilters(items, suffix, searchParams, override)setSearchParams(searchParams)@@ -121,15 +116,15 @@ export const handleNavigationParams = (export const updateFilterState = (searchParams: URLSearchParams,setSearchParams: React.Dispatch<React.SetStateAction<URLSearchParams>>,- filters: IFilter[],- newFiltersStateSetter: React.Dispatch<React.SetStateAction<IFilter[]>>,+ filters: Filter[],+ newFiltersStateSetter: React.Dispatch<React.SetStateAction<Filter[]>>,column: string,columnSuffix: string,filter: any,isExclusive: boolean,) => {const existingFilterIndex = filters.findIndex((f) => f.filter === filter)- let updatedFilters: IFilter[]+ let updatedFilters: Filter[]if (existingFilterIndex > -1) {updatedFilters = filters.filter((_, index) => index !== existingFilterIndex)@@ -150,11 +145,11 @@ export const updateFilterState = (export const parseFiltersFromUrl = (keySuffix: string,searchParams: URLSearchParams,- setFilters: React.Dispatch<React.SetStateAction<IFilter[]>>,+ setFilters: React.Dispatch<React.SetStateAction<Filter[]>>,setParsedFlag: React.Dispatch<React.SetStateAction<boolean>>,) => {try {- const initialFilters: IFilter[] = []+ const initialFilters: Filter[] = []searchParams.forEach((value, key) => {if (!_includes(key, keySuffix)) returndiff --git a/web/app/pages/Project/uptime/Settings.tsx b/web/app/pages/Project/uptime/Settings.tsxindex 3902073f2..2a8cc6d1d 100644--- a/web/app/pages/Project/uptime/Settings.tsx+++ b/web/app/pages/Project/uptime/Settings.tsx@@ -1,36 +1,33 @@-import React, { ChangeEvent, ChangeEventHandler, useEffect, useId, useMemo, useState } from 'react'-import { useNavigate, useLocation } from '@remix-run/react'+import React, { ChangeEvent, ChangeEventHandler, useEffect, useId, useState } from 'react'+import { Link, useNavigate } from '@remix-run/react'import { useTranslation } from 'react-i18next'-import { ExclamationTriangleIcon } from '@heroicons/react/24/outline'+import { ExclamationTriangleIcon, XCircleIcon } from '@heroicons/react/24/outline'import _isEmpty from 'lodash/isEmpty'import _size from 'lodash/size'-import _replace from 'lodash/replace'import _join from 'lodash/join'import _split from 'lodash/split'-import _find from 'lodash/find'import _includes from 'lodash/includes'import _isNaN from 'lodash/isNaN'import _map from 'lodash/map'import _keys from 'lodash/keys'-import _filter from 'lodash/filter'import { clsx as cx } from 'clsx'import Input from 'ui/Input'import Button from 'ui/Button'import Modal from 'ui/Modal'import { PROJECT_TABS } from 'redux/constants'-import { createMonitor, updateMonitor, deleteMonitor, ICreateMonitor } from 'api'+import { createMonitor, updateMonitor, deleteMonitor, CreateMonitor, getProjectMonitor } from 'api'import { withAuthentication, auth } from 'hoc/protected'import routes from 'utils/routes'import { Monitor } from 'redux/models/Uptime'-import { useDispatch, useSelector } from 'react-redux'+import { useSelector } from 'react-redux'import { toast } from 'sonner'import { StateType } from 'redux/store'-import UIActions from 'redux/reducers/ui'import { useRequiredParams } from 'hooks/useRequiredParams'import Select from 'ui/Select'import { formatTime } from 'utils/date'import { isValidUrl } from 'utils/validator'+import Loader from 'ui/Loader'const MONITOR_TYPES = ['HTTP']@@ -130,7 +127,7 @@ const IntervalSelector = ({ value, onChange, label, hint, name }: IntervalSelectreturn (<option- className='mt-4 text-sm lg:mt-0 lg:-rotate-90 lg:text-center'+ className='mt-4 text-sm text-gray-700 dark:text-gray-200 lg:mt-0 lg:-rotate-90 lg:text-center'key={interval}value={index}label={displayName}@@ -144,21 +141,19 @@ const IntervalSelector = ({ value, onChange, label, hint, name }: IntervalSelectconst MAX_RETRIES = 100-const UptimeSettings = (): JSX.Element => {- const { monitors, total } = useSelector((state: StateType) => state.ui.monitors)+interface UptimeSettingsProps {+ isSettings?: boolean+}- const dispatch = useDispatch()+const UptimeSettings = ({ isSettings }: UptimeSettingsProps) => {+ const { loading: authLoading } = useSelector((state: StateType) => state.auth)const navigate = useNavigate()const { id, pid } = useRequiredParams<{ id: string; pid: string }>()- const { pathname } = useLocation()const {t,i18n: { language },} = useTranslation('common')- const isSettings =- !_isEmpty(id) && _replace(_replace(routes.uptime_settings, ':id', id as string), ':pid', pid as string) === pathname- const monitor = useMemo(() => _find(monitors, { id }), [monitors, id])const [form, setForm] = useState<Partial<Omit<Monitor, 'acceptedStatusCodes'>> & {acceptedStatusCodes: string@@ -182,17 +177,43 @@ const UptimeSettings = (): JSX.Element => {const [beenSubmitted, setBeenSubmitted] = useState(false)const [showModal, setShowModal] = useState(false)- const setMonitors = (monitors: Monitor[]) => dispatch(UIActions.setMonitors(monitors))- const setMonitorsTotal = (total: number) => dispatch(UIActions.setMonitorsTotal({ total }))+ const [isLoading, setIsLoading] = useState<boolean | null>(null)+ const [error, setError] = useState<string | null>(null)- useEffect(() => {- if (!_isEmpty(monitor)) {+ const loadMonitor = async (projectId: string, monitorId: string) => {+ if (!isSettings) {+ setIsLoading(false)+ return+ }++ if (isLoading) {+ return+ }++ setIsLoading(true)++ try {+ const result = await getProjectMonitor(projectId, monitorId)setForm({- ...monitor,- acceptedStatusCodes: _join(monitor.acceptedStatusCodes, ','),+ ...result,+ acceptedStatusCodes: _join(result.acceptedStatusCodes, ','),})+ } catch (reason: any) {+ setError(reason)+ } finally {+ setIsLoading(false)+ }+ }++ useEffect(() => {+ if (authLoading) {+ return}- }, [monitor])++ loadMonitor(pid, id)++ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [authLoading, pid, id])const validate = () => {const allErrors: {@@ -253,18 +274,15 @@ const UptimeSettings = (): JSX.Element => {updateMonitor(pid, id, data).then((res) => {navigate(`/projects/${pid}?tab=${PROJECT_TABS.uptime}`)- setMonitors([..._filter(monitors, (a) => a.id !== id), res])toast.success(t('monitor.monitorUpdated'))}).catch((err) => {toast.error(err.message || err || 'Something went wrong')})} else {- createMonitor(pid, data as ICreateMonitor)+ createMonitor(pid, data as CreateMonitor).then((res) => {navigate(`/projects/${pid}?tab=${PROJECT_TABS.uptime}`)- setMonitors([...monitors, res])- setMonitorsTotal(total + 1)toast.success(t('monitor.monitorCreated'))}).catch((err) => {@@ -281,8 +299,6 @@ const UptimeSettings = (): JSX.Element => {deleteMonitor(pid, id).then(() => {- setMonitors(_filter(monitors, (a) => a.id !== id))- setMonitorsTotal(total - 1)navigate(`/projects/${pid}?tab=${PROJECT_TABS.uptime}`)toast.success(t('monitor.monitorDeleted'))})@@ -291,10 +307,6 @@ const UptimeSettings = (): JSX.Element => {})}- const onCancel = () => {- navigate(`/projects/${pid}?tab=${PROJECT_TABS.uptime}`)- }-useEffect(() => {validate()}, [form]) // eslint-disable-line@@ -327,6 +339,51 @@ const UptimeSettings = (): JSX.Element => {}): t('monitor.create')+ if (isLoading || isLoading === null) {+ return (+ <div className='flex min-h-min-footer flex-col bg-gray-50 px-4 py-6 dark:bg-slate-900 sm:px-6 lg:px-8'>+ <Loader />+ </div>+ )+ }++ if (error && !isLoading) {+ return (+ <div className='min-h-page bg-gray-50 px-4 py-16 dark:bg-slate-900 sm:px-6 sm:py-24 md:grid md:place-items-center lg:px-8'>+ <div className='mx-auto max-w-max'>+ <main className='sm:flex'>+ <XCircleIcon className='h-12 w-12 text-red-400' aria-hidden='true' />+ <div className='sm:ml-6'>+ <div className='max-w-prose sm:border-l sm:border-gray-200 sm:pl-6'>+ <h1 className='text-4xl font-extrabold tracking-tight text-gray-900 dark:text-gray-50 sm:text-5xl'>+ {t('apiNotifications.somethingWentWrong')}+ </h1>+ <p className='mt-4 text-2xl font-medium tracking-tight text-gray-700 dark:text-gray-200'>+ {t('apiNotifications.errorCode', { error })}+ </p>+ </div>+ <div className='mt-8 flex space-x-3 sm:border-l sm:border-transparent sm:pl-6'>+ <button+ type='button'+ onClick={() => window.location.reload()}+ className='inline-flex items-center rounded-md border border-transparent bg-indigo-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2'+ >+ {t('dashboard.reloadPage')}+ </button>+ <Link+ to={routes.contact}+ className='inline-flex items-center rounded-md border border-transparent bg-indigo-100 px-4 py-2 text-sm font-medium text-indigo-700 hover:bg-indigo-200 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700 dark:focus:ring-gray-50'+ >+ {t('notFoundPage.support')}+ </Link>+ </div>+ </div>+ </main>+ </div>+ </div>+ )+ }+return (<divclassName={cx('flex min-h-min-footer flex-col bg-gray-50 px-4 py-6 dark:bg-slate-900 sm:px-6 lg:px-8', {@@ -422,7 +479,9 @@ const UptimeSettings = (): JSX.Element => {<div className='flex items-center justify-between'><ButtonclassName='mr-2 border-indigo-100 dark:border-slate-700/50 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700'- onClick={onCancel}+ as={Link}+ // @ts-expect-error+ to={`/projects/${pid}?tab=${PROJECT_TABS.uptime}`}secondaryregular>@@ -437,7 +496,9 @@ const UptimeSettings = (): JSX.Element => {<div className='mt-5 flex items-center justify-between'><ButtonclassName='mr-2 border-indigo-100 dark:border-slate-700/50 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700'- onClick={onCancel}+ as={Link}+ // @ts-expect-error+ to={`/projects/${pid}?tab=${PROJECT_TABS.uptime}`}secondaryregular>diff --git a/web/app/pages/Project/uptime/View.tsx b/web/app/pages/Project/uptime/View.tsxindex 4c654eceb..313fe7eb8 100644--- a/web/app/pages/Project/uptime/View.tsx+++ b/web/app/pages/Project/uptime/View.tsx@@ -8,7 +8,7 @@ import _replace from 'lodash/replace'import _filter from 'lodash/filter'import { Link, useNavigate } from '@remix-run/react'import { useTranslation } from 'react-i18next'-import { useDispatch, useSelector } from 'react-redux'+import { useSelector } from 'react-redux'import {CurrencyDollarIcon,AdjustmentsVerticalIcon,@@ -17,6 +17,7 @@ import {ClockIcon,ArrowPathIcon,ChevronLeftIcon,+ XCircleIcon,} from '@heroicons/react/24/outline'import { toast } from 'sonner'@@ -24,8 +25,7 @@ import routes from 'utils/routes'import Button from 'ui/Button'import Modal from 'ui/Modal'import PaidFeature from 'modals/PaidFeature'-import { PLAN_LIMITS, tbPeriodPairs, UPTIME_PERIOD_PAIRS } from 'redux/constants'-import UIActions from 'redux/reducers/ui'+import { DEFAULT_MONITORS_TAKE, PLAN_LIMITS, tbPeriodPairs, UPTIME_PERIOD_PAIRS } from 'redux/constants'import { deleteMonitor as deleteMonitorApi, getMonitorOverallStats, getMonitorStats, getProjectMonitors } from 'api'import { StateType } from 'redux/store'import { Monitor, MonitorOverallObject } from 'redux/models/Uptime'@@ -34,21 +34,17 @@ import { getFormatDate, getSettingsUptime } from '../View/ViewProject.helpers'import TBPeriodSelector from '../View/components/TBPeriodSelector'import { MetricCardsUptime } from '../View/components/MetricCards'import NoMonitorEvents from './components/NoMonitorDetails'+import Loader from 'ui/Loader'+import Pagination from 'ui/Pagination'-// const Separator = () => (-// <svg viewBox='0 0 2 2' className='h-0.5 w-0.5 flex-none fill-gray-400'>-// <circle cx={1} cy={1} r={1} />-// </svg>-// )--interface IMonitorCard {+interface MonitorCardProps {monitor: MonitordeleteMonitor: (id: string) => voidonClick: (monitor: Monitor) => voidallowedToManage: boolean}-const MonitorCard = ({ monitor, deleteMonitor, onClick, allowedToManage }: IMonitorCard): JSX.Element => {+const MonitorCard = ({ monitor, deleteMonitor, onClick, allowedToManage }: MonitorCardProps) => {const { t } = useTranslation()const [showDeleteModal, setShowDeleteModal] = useState(false)@@ -114,7 +110,7 @@ interface AddMonitorProps {isLimitReached: boolean}-const AddMonitor = ({ handleNewMonitor, isLimitReached }: AddMonitorProps): JSX.Element => {+const AddMonitor = ({ handleNewMonitor, isLimitReached }: AddMonitorProps) => {const { t } = useTranslation()return (@@ -136,10 +132,10 @@ const AddMonitor = ({ handleNewMonitor, isLimitReached }: AddMonitorProps): JSX.)}-const Uptime = (): JSX.Element => {+const Uptime = () => {const {projectId,- isLoading,+ isLoading: isProjectLoading,dateRange,timeBucket,period,@@ -160,8 +156,6 @@ const Uptime = (): JSX.Element => {t,i18n: { language },} = useTranslation()- const dispatch = useDispatch()- const { loading, total, monitors } = useSelector((state: StateType) => state.ui.monitors)const { user, authenticated } = useSelector((state: StateType) => state.auth)const [isPaidFeatureOpened, setIsPaidFeatureOpened] = useState(false)const [activeMonitor, setActiveMonitor] = useState<{@@ -174,30 +168,39 @@ const Uptime = (): JSX.Element => {const rotateXAxis = useMemo(() => size.width > 0 && size.width < 500, [size])+ const [isLoading, setIsLoading] = useState<boolean | null>(null)+ const [total, setTotal] = useState(0)+ const [monitors, setMonitors] = useState<Monitor[]>([])+ const [page, setPage] = useState(1)+ const [error, setError] = useState<string | null>(null)+const limits = PLAN_LIMITS[user?.planCode] || PLAN_LIMITS.trialconst isLimitReached = authenticated && total >= limits?.maxMonitors- const [projectMonitors, setProjectMonitors] = useState<Monitor[]>([])- const [monitorFilterLoaded, setMonitorFilterLoaded] = useState(false)+ const pageAmount = Math.ceil(total / DEFAULT_MONITORS_TAKE)- useEffect(() => {- if (loading || !_isEmpty(projectMonitors) || monitorFilterLoaded) {+ const loadMonitors = async (take: number, skip: number, search?: string) => {+ if (isLoading) {return}+ setIsLoading(true)- const filteredMonitors = _filter(monitors, (monitor) => monitor.projectId === projectId)-- if (!_isEmpty(filteredMonitors)) {- setProjectMonitors(filteredMonitors)- setMonitorFilterLoaded(true)- return+ try {+ const result = await getProjectMonitors(projectId, take, skip)+ setMonitors(result.results)+ setTotal(result.total)+ } catch (reason: any) {+ setError(reason)+ } finally {+ setIsLoading(false)}+ }- getProjectMonitors(projectId).then(({ results }) => {- setProjectMonitors(results)- setMonitorFilterLoaded(true)- })- }, [projectId, monitors, loading, projectMonitors, monitorFilterLoaded])+ useEffect(() => {+ loadMonitors(DEFAULT_MONITORS_TAKE, (page - 1) * DEFAULT_MONITORS_TAKE)++ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [page])const handleNewMonitor = () => {if (isLimitReached) {@@ -216,12 +219,6 @@ const Uptime = (): JSX.Element => {const onDelete = async (id: string) => {try {await deleteMonitorApi(projectId, id)- dispatch(UIActions.setMonitors(_filter(monitors, (a) => a.id !== id)))- dispatch(- UIActions.setMonitorsTotal({- total: total - 1,- }),- )toast.success(t('monitor.monitorDeleted'))} catch (reason: any) {toast.error(reason?.response?.data?.message || reason?.message || 'Something went wrong')@@ -237,7 +234,7 @@ const Uptime = (): JSX.Element => {const loadMonitorData = useCallback(async (monitor: Monitor) => {- if (!monitorFilterLoaded || isMonitorLoading || !projectId || isLoading) {+ if (isMonitorLoading || !projectId || isProjectLoading) {return}@@ -301,8 +298,7 @@ const Uptime = (): JSX.Element => {timezone,period,dateRange,- isLoading,- monitorFilterLoaded,+ isProjectLoading,isMonitorLoading,projectId,timeBucket,@@ -319,6 +315,51 @@ const Uptime = (): JSX.Element => {// eslint-disable-next-line react-hooks/exhaustive-deps}, [period, dateRange, timeBucket])+ if (error && isLoading === false) {+ return (+ <div className='bg-gray-50 px-4 py-16 dark:bg-slate-900 sm:px-6 sm:py-24 md:grid md:place-items-center lg:px-8'>+ <div className='mx-auto max-w-max'>+ <main className='sm:flex'>+ <XCircleIcon className='h-12 w-12 text-red-400' aria-hidden='true' />+ <div className='sm:ml-6'>+ <div className='max-w-prose sm:border-l sm:border-gray-200 sm:pl-6'>+ <h1 className='text-4xl font-extrabold tracking-tight text-gray-900 dark:text-gray-50 sm:text-5xl'>+ {t('apiNotifications.somethingWentWrong')}+ </h1>+ <p className='mt-4 text-2xl font-medium tracking-tight text-gray-700 dark:text-gray-200'>+ {t('apiNotifications.errorCode', { error })}+ </p>+ </div>+ <div className='mt-8 flex space-x-3 sm:border-l sm:border-transparent sm:pl-6'>+ <button+ type='button'+ onClick={() => window.location.reload()}+ className='inline-flex items-center rounded-md border border-transparent bg-indigo-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2'+ >+ {t('dashboard.reloadPage')}+ </button>+ <Link+ to={routes.contact}+ className='inline-flex items-center rounded-md border border-transparent bg-indigo-100 px-4 py-2 text-sm font-medium text-indigo-700 hover:bg-indigo-200 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700 dark:focus:ring-gray-50'+ >+ {t('notFoundPage.support')}+ </Link>+ </div>+ </div>+ </main>+ </div>+ </div>+ )+ }++ if (isLoading || isLoading === null) {+ return (+ <div className='mt-4'>+ <Loader />+ </div>+ )+ }+if (activeMonitor) {return (<>@@ -336,7 +377,7 @@ const Uptime = (): JSX.Element => {className={cx('relative rounded-md bg-gray-50 p-2 text-sm font-medium hover:bg-white hover:shadow-sm focus:z-10 focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500 dark:bg-slate-900 dark:hover:bg-slate-800 focus:dark:border-gray-200 focus:dark:ring-gray-200',{- 'cursor-not-allowed opacity-50': isLoading || isMonitorLoading,+ 'cursor-not-allowed opacity-50': isProjectLoading || isMonitorLoading,},)}>@@ -404,8 +445,7 @@ const Uptime = (): JSX.Element => {return (<div><div className='mt-4'>- {(loading || !monitorFilterLoaded) && <div>{t('common.loading')}</div>}- {!loading && monitorFilterLoaded && _isEmpty(projectMonitors) && (+ {_isEmpty(monitors) ? (<div className='mt-5 rounded-xl bg-gray-700 p-5'><div className='flex items-center text-gray-50'><ClockIcon className='mr-2 h-8 w-8' />@@ -434,10 +474,9 @@ const Uptime = (): JSX.Element => {</Link>)}</div>- )}- {!loading && monitorFilterLoaded && !_isEmpty(projectMonitors) && (+ ) : (<ul className='mt-4 grid grid-cols-1 gap-x-6 gap-y-3 lg:grid-cols-3 lg:gap-y-6'>- {_map(projectMonitors, (monitor) => (+ {_map(monitors, (monitor) => (<MonitorCardallowedToManage={allowedToManage}key={monitor.id}@@ -449,6 +488,16 @@ const Uptime = (): JSX.Element => {<AddMonitor handleNewMonitor={handleNewMonitor} isLimitReached={isLimitReached} /></ul>)}+ {pageAmount > 1 ? (+ <Pagination+ className='mt-4'+ page={page}+ pageAmount={pageAmount}+ setPage={setPage}+ total={total}+ pageSize={DEFAULT_MONITORS_TAKE}+ />+ ) : null}</div><PaidFeature isOpened={isPaidFeatureOpened} onClose={() => setIsPaidFeatureOpened(false)} /></div>diff --git a/web/app/pages/ReferralPage/index.tsx b/web/app/pages/ReferralPage/index.tsxindex c8e1b0d57..b9a825100 100644--- a/web/app/pages/ReferralPage/index.tsx+++ b/web/app/pages/ReferralPage/index.tsx@@ -11,11 +11,11 @@ import { Lines } from 'components/marketing/Lines'import { isBrowser, REFERRAL_COOKIE_DAYS, REFERRAL_DISCOUNT } from 'redux/constants'-interface IReferralPage {+interface ReferralPageProps {ssrTheme: 'dark' | 'light'}-const ReferralPage = ({ ssrTheme }: IReferralPage): JSX.Element => {+const ReferralPage = ({ ssrTheme }: ReferralPageProps) => {const { t } = useTranslation('common')const reduxTheme = useSelector((state: StateType) => state.ui.theme.theme)const theme = isBrowser ? reduxTheme : ssrThemediff --git a/web/app/pages/Terms/index.tsx b/web/app/pages/Terms/index.tsxindex b7346915b..c4a4d78d0 100644--- a/web/app/pages/Terms/index.tsx+++ b/web/app/pages/Terms/index.tsx@@ -3,7 +3,7 @@ import React from 'react'import { CONTACT_EMAIL } from 'redux/constants'-const Terms = (): JSX.Element => {+const Terms = () => {return (<div className='bg-gray-50 dark:bg-slate-900'><div className='mx-auto w-11/12 px-4 pb-16 pt-12 sm:px-6 md:w-4/5 lg:px-8'>diff --git a/web/app/pages/Unsubscribe/index.tsx b/web/app/pages/Unsubscribe/index.tsxindex 7b384a564..f3b998698 100644--- a/web/app/pages/Unsubscribe/index.tsx+++ b/web/app/pages/Unsubscribe/index.tsx@@ -10,11 +10,11 @@ import { unsubscribeFromEmailReports, unsubscribeFromEmailReports3rdParty } fromimport Loader from 'ui/Loader'import routes from 'utils/routes'-interface IUnsubscribe {+interface UnsubscribeProps {type: 'user-reports' | '3rdparty'}-const Unsubscribe = ({ type }: IUnsubscribe): JSX.Element => {+const Unsubscribe = ({ type }: UnsubscribeProps) => {const { t } = useTranslation('common')const { token } = useParams()const { authenticated } = useSelector((state: StateType) => state.auth)diff --git a/web/app/pages/UserSettings/UserSettings.tsx b/web/app/pages/UserSettings/UserSettings.tsxindex e26a575c1..c932c2e22 100644--- a/web/app/pages/UserSettings/UserSettings.tsx+++ b/web/app/pages/UserSettings/UserSettings.tsx@@ -37,7 +37,7 @@ import {TimeFormat,isSelfhosted,} from 'redux/constants'-import { IUser } from 'redux/models/IUser'+import { User } from 'redux/models/User'import { withAuthentication, auth } from 'hoc/protected'import Input from 'ui/Input'import Button from 'ui/Button'@@ -58,6 +58,9 @@ import {generateApiKey,deleteApiKey, // setTheme,receiveLoginNotification,+ setShowLiveVisitorsInTitle,+ changeUserDetails,+ deleteUser,} from 'api'import ProjectList from './components/ProjectList'import TwoFA from './components/TwoFA'@@ -70,10 +73,10 @@ import NoOrganisations from './components/NoOrganisations'import { useSelector } from 'react-redux'import { StateType, useAppDispatch } from 'redux/store'import { authActions } from 'redux/reducers/auth'-import sagaActions from 'redux/sagas/actions'import { removeRefreshToken } from 'utils/refreshToken'import { removeAccessToken } from 'utils/accessToken'import UIActions from 'redux/reducers/ui'+import { logout } from 'utils/auth'dayjs.extend(utc)@@ -126,7 +129,7 @@ const getTabs = (t: typeof i18next.t) => {]}-interface IForm extends Partial<IUser> {+interface Form extends Partial<User> {repeat: stringpassword: stringemail: string@@ -139,7 +142,7 @@ const UserSettings = () => {const navigate = useNavigate()const { t } = useTranslation('common')const [activeTab, setActiveTab] = useState(TAB_MAPPING.ACCOUNT)- const [form, setForm] = useState<IForm>({+ const [form, setForm] = useState<Form>({email: user.email || '',password: '',repeat: '',@@ -194,7 +197,7 @@ const UserSettings = () => {setValidated(valid)}- const onSubmit = (data: any, callback: (isSuccess: boolean) => void = () => {}) => {+ const onSubmit = async (data: any, callback: (isSuccess: boolean) => void = () => {}) => {delete data.repeat// eslint-disable-next-line no-restricted-syntax@@ -204,15 +207,16 @@ const UserSettings = () => {}}- dispatch(- sagaActions.updateUserProfileAsync(data, (isSuccess: boolean) => {- if (isSuccess) {- toast.success(t('profileSettings.updated'))- } else {- toast.error(t('apiNotifications.somethingWentWrong'))- }- }),- )+ try {+ const result = await changeUserDetails(data)+ dispatch(authActions.setUser(result))+ toast.success(t('profileSettings.updated'))+ } catch (reason: any) {+ toast.error(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))+ } finally {+ callback(true)+ dispatch(authActions.finishLoading())+ }}const logoutLocal = () => {@@ -223,7 +227,7 @@ const UserSettings = () => {const logoutAll = () => {dispatch(authActions.logout())- dispatch(sagaActions.logout(false, true))+ logout(true)}useEffect(() => {@@ -296,25 +300,22 @@ const UserSettings = () => {}}- const handleShowLiveVisitorsSave = (checked: boolean) => {+ const handleShowLiveVisitorsSave = async (checked: boolean) => {if (settingUpdating) {return}setSettingUpdating(true)- dispatch(- sagaActions.updateShowLiveVisitorsInTitle(checked, (isSuccess: boolean) => {- setSettingUpdating(false)-- if (isSuccess) {- toast.success(t('profileSettings.updated'))- return- }-- toast.error(t('apiNotifications.somethingWentWrong'))- }),- )+ try {+ await setShowLiveVisitorsInTitle(checked)+ dispatch(authActions.mergeUser({ showLiveVisitorsInTitle: checked }))+ toast.success(t('profileSettings.updated'))+ } catch (reason: any) {+ toast.error(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))+ } finally {+ setSettingUpdating(false)+ }}const handleReceiveLoginNotifications = async (checked: boolean) => {@@ -377,20 +378,20 @@ const UserSettings = () => {return null}- const onAccountDelete = () => {- dispatch(- sagaActions.deleteAccountAsync(- (error: string) => toast.error(error),- () => {- trackCustom('ACCOUNT_DELETED', {- reason_stated: deletionFeedback ? 'true' : 'false',- })- navigate(routes.main)- },- deletionFeedback,- t,- ),- )+ const onAccountDelete = async () => {+ try {+ await deleteUser(deletionFeedback)+ dispatch(authActions.logout())+ toast.success(t('apiNotifications.accountDeleted'))+ trackCustom('ACCOUNT_DELETED', {+ reason_stated: deletionFeedback ? 'true' : 'false',+ })+ navigate(routes.main)+ } catch (reason: any) {+ toast.error(t(`apiNotifications.${reason}`, 'apiNotifications.somethingWentWrong'))+ } finally {+ dispatch(authActions.finishLoading())+ }}const onExport = async (exportedAt: string) => {diff --git a/web/app/pages/UserSettings/components/Integrations.tsx b/web/app/pages/UserSettings/components/Integrations.tsxindex 862f0d742..3895b0b3e 100644--- a/web/app/pages/UserSettings/components/Integrations.tsx+++ b/web/app/pages/UserSettings/components/Integrations.tsx@@ -12,7 +12,7 @@ import Telegram from 'ui/icons/Telegram'import Slack from 'ui/icons/Slack'import Discord from 'ui/icons/Discord'import { removeTgIntegration } from 'api'-import { IUser } from 'redux/models/IUser'+import { User } from 'redux/models/User'import { StateType, useAppDispatch } from 'redux/store'import { useSelector } from 'react-redux'import { authActions } from 'redux/reducers/auth'@@ -52,7 +52,7 @@ const SLACK_WEBHOOKS_HELP = 'https://api.slack.com/messaging/webhooks'const DISCORD_WEBHOOKS_HELP = 'https://support.discord.com/hc/en-us/articles/228383668-Intro-to-Webhooks'interface IntegrationsProps {- handleIntegrationSave: (data: Partial<IUser>, cb: (isSuccess: boolean) => void) => void+ handleIntegrationSave: (data: Partial<User>, cb: (isSuccess: boolean) => void) => void}const Integrations = ({ handleIntegrationSave }: IntegrationsProps) => {diff --git a/web/app/pages/UserSettings/components/ProjectList.tsx b/web/app/pages/UserSettings/components/ProjectList.tsxindex 0f63bbec3..0a4a744b3 100644--- a/web/app/pages/UserSettings/components/ProjectList.tsx+++ b/web/app/pages/UserSettings/components/ProjectList.tsx@@ -8,13 +8,13 @@ import _filter from 'lodash/filter'import Button from 'ui/Button'import Modal from 'ui/Modal'import { rejectProjectShare, acceptProjectShare } from 'api'-import { ISharedProject } from 'redux/models/ISharedProject'+import { SharedProject } from 'redux/models/SharedProject'import { StateType, useAppDispatch } from 'redux/store'import { authActions } from 'redux/reducers/auth'import { useSelector } from 'react-redux'interface ProjectListProps {- item: ISharedProject+ item: SharedProject}const ProjectList = ({ item }: ProjectListProps) => {diff --git a/web/app/pages/UserSettings/components/Socialisations.tsx b/web/app/pages/UserSettings/components/Socialisations.tsxindex 3142dba60..9a8ad8f59 100644--- a/web/app/pages/UserSettings/components/Socialisations.tsx+++ b/web/app/pages/UserSettings/components/Socialisations.tsx@@ -8,11 +8,13 @@ import Button from 'ui/Button'import Google from 'ui/icons/GoogleG'import GithubDark from 'ui/icons/GithubDark'import GithubLight from 'ui/icons/GithubLight'-import { IUser } from 'redux/models/IUser'+import { User } from 'redux/models/User'import { SSO_PROVIDERS } from 'redux/constants'import { StateType, useAppDispatch } from 'redux/store'-import sagaActions from 'redux/sagas/actions'import { useSelector } from 'react-redux'+import { authMe, generateSSOAuthURL, linkBySSOHash, unlinkSSO } from 'api'+import { authActions } from 'redux/reducers/auth'+import { delay, openBrowserWindow } from 'utils/generic'const AVAILABLE_SSO_PROVIDERS = [{@@ -34,7 +36,7 @@ const AVAILABLE_SSO_PROVIDERS = [},]-const getStatusByUser = (user: IUser, socialisation: string) => {+const getStatusByUser = (user: User, socialisation: string) => {if (socialisation === SSO_PROVIDERS.GOOGLE) {const connected = user.googleIdconst unlinkable = !user.registeredWithGoogle@@ -50,6 +52,8 @@ const getStatusByUser = (user: IUser, socialisation: string) => {return [false, false]}+const HASH_CHECK_FREQUENCY = 1000 // 1 second+const Socialisations = () => {const { user } = useSelector((state: StateType) => state.auth)const { theme } = useSelector((state: StateType) => state.ui.theme)@@ -57,32 +61,70 @@ const Socialisations = () => {const { t } = useTranslation('common')const [isLoading, setIsLoading] = useState(false)- const linkSSO = (provider: string) => {+ const linkSSO = async (provider: string) => {setIsLoading(true)- dispatch(- sagaActions.linkSSO(- t,- () => {+ const authWindow = openBrowserWindow('')++ if (!authWindow) {+ toast.error(t('apiNotifications.socialisationGenericError'))+ setIsLoading(false)+ return+ }++ try {+ const { uuid, auth_url: authUrl, expires_in: expiresIn } = await generateSSOAuthURL(provider)++ authWindow.location = authUrl++ // Closing the authorisation window after the session expires+ setTimeout(authWindow.close, expiresIn)++ // eslint-disable-next-line no-constant-condition+ while (true) {+ await delay(HASH_CHECK_FREQUENCY)++ try {+ await linkBySSOHash(uuid, provider)+ authWindow.close()++ const { user } = await authMe()+ dispatch(authActions.authSuccessful(user))++ toast.success(t('apiNotifications.socialAccountLinked'))+setIsLoading(false)- },- provider,- ),- )+ return+ } catch (reason) {+ // Authentication is not finished yet+ }++ if (authWindow.closed) {+ setIsLoading(false)+ return+ }+ }+ } catch (reason) {+ toast.error(typeof reason === 'string' ? reason : t('apiNotifications.socialisationGenericError'))+ setIsLoading(false)+ return+ }}- const unlinkSSO = (provider: string) => {+ const onUnlinkSSO = async (provider: string) => {setIsLoading(true)- dispatch(- sagaActions.unlinkSSO(- t,- () => {- setIsLoading(false)- },- provider,- ),- )+ try {+ await unlinkSSO(provider)+ const { user } = await authMe()+ dispatch(authActions.authSuccessful(user))++ toast.success(t('apiNotifications.socialAccountUninked'))+ } catch (reason) {+ toast.error(typeof reason === 'string' ? reason : t('apiNotifications.socialisationUnlinkGenericError'))+ } finally {+ setIsLoading(false)+ }}return (@@ -133,7 +175,7 @@ const Socialisations = () => {)}{connected && unlinkable && (- <Button onClick={() => unlinkSSO(key)} loading={isLoading} small danger>+ <Button onClick={() => onUnlinkSSO(key)} loading={isLoading} small danger>{t('common.unlink')}</Button>)}diff --git a/web/app/redux/constants/index.ts b/web/app/redux/constants/index.tsindex a0f4778f6..d7141ef2a 100644--- a/web/app/redux/constants/index.ts+++ b/web/app/redux/constants/index.ts@@ -43,7 +43,7 @@ export const KEY_FOR_ALL_TIME = 'all'export const ALL_PERIODS = ['minute', 'hour', 'day', 'month', 'year']-export interface ITBPeriodPairs {+export interface TBPeriodPairsProps {label: stringperiod: stringtbs: string[]@@ -57,7 +57,7 @@ export const tbPeriodPairs = (tbs?: string[] | null,dates?: Date[],language?: string,-): ITBPeriodPairs[] => [+): TBPeriodPairsProps[] => [{label: t('project.thisHour'),period: '1h',@@ -132,7 +132,7 @@ export const captchaTbPeriodPairs = (tbs?: string[] | null,dates?: Date[],language?: string,-): ITBPeriodPairs[] => [+): TBPeriodPairsProps[] => [{label: t('project.thisHour'),period: '1h',@@ -235,7 +235,7 @@ export const PERIOD_PAIRS_COMPARE = {DISABLE: 'disable',} as const-interface IStringObject {+interface StringObject {[key: string]: string}@@ -261,7 +261,7 @@ export const timeBucketToDays: {{ lt: 732, tb: ['month'] }, // 24 months]-export const tbsFormatMapper: IStringObject = {+export const tbsFormatMapper: StringObject = {minute: '%I:%M %p',hour: '%I %p',day: '%d %b',@@ -269,7 +269,7 @@ export const tbsFormatMapper: IStringObject = {year: '%Y',}-export const tbsFormatMapperTooltip: IStringObject = {+export const tbsFormatMapperTooltip: StringObject = {minute: '%I:%M %p',hour: '%d %b %I %p',day: '%d %b',@@ -277,7 +277,7 @@ export const tbsFormatMapperTooltip: IStringObject = {year: '%Y',}-export const tbsFormatMapperTooltip24h: IStringObject = {+export const tbsFormatMapperTooltip24h: StringObject = {minute: '%H:%M',hour: '%d %b %H:%M',day: '%d %b',@@ -285,7 +285,7 @@ export const tbsFormatMapperTooltip24h: IStringObject = {year: '%Y',}-export const tbsFormatMapper24h: IStringObject = {+export const tbsFormatMapper24h: StringObject = {minute: '%H:%M',hour: '%H:%M',day: '%d %b',@@ -293,7 +293,7 @@ export const tbsFormatMapper24h: IStringObject = {year: '%Y',}-export const TimeFormat: IStringObject = {+export const TimeFormat: StringObject = {'12-hour': '12-hour','24-hour': '24-hour',}@@ -459,21 +459,21 @@ export const whitelistWithCC = {de: 'de-DE',}export const defaultLanguage = 'en'-export const languages: IStringObject = {+export const languages: StringObject = {en: 'English',uk: 'Українська',pl: 'Polski',de: 'Deutsch',}-export const languageFlag: IStringObject = {+export const languageFlag: StringObject = {en: 'GB',uk: 'UA',pl: 'PL',de: 'DE',}-export const paddleLanguageMapping: IStringObject = {+export const paddleLanguageMapping: StringObject = {uk: 'en',}@@ -505,21 +505,21 @@ export const PROJECT_TABS = (isSelfhosted ? SELFHOSTED_PROJECT_TABS : PRODUCTION_PROJECT_TABS) as typeof PRODUCTION_PROJECT_TABS-export const QUERY_METRIC: IStringObject = {+export const QUERY_METRIC: StringObject = {PAGE_VIEWS: 'page_views',UNIQUE_PAGE_VIEWS: 'unique_page_views',ONLINE_USERS: 'online_users',CUSTOM_EVENTS: 'custom_events',}-export const QUERY_CONDITION: IStringObject = {+export const QUERY_CONDITION: StringObject = {GREATER_THAN: 'greater_than',GREATER_EQUAL_THAN: 'greater_equal_than',LESS_THAN: 'less_than',LESS_EQUAL_THAN: 'less_equal_than',}-export const QUERY_TIME: IStringObject = {+export const QUERY_TIME: StringObject = {LAST_15_MINUTES: 'last_15_minutes',LAST_30_MINUTES: 'last_30_minutes',LAST_1_HOUR: 'last_1_hour',@@ -531,11 +531,6 @@ export const QUERY_TIME: IStringObject = {export const INVITATION_EXPIRES_IN = 48 // hoursexport const ENTRIES_PER_PAGE_DASHBOARD = 11-export const THEME_TYPE: IStringObject = {- classic: 'classic',- christmas: 'christmas',-}-export const DEFAULT_ALERTS_TAKE = 100export const DEFAULT_MONITORS_TAKE = 100diff --git a/web/app/redux/models/IAlerts.ts b/web/app/redux/models/Alerts.tssimilarity index 93%rename from web/app/redux/models/IAlerts.tsrename to web/app/redux/models/Alerts.tsindex 74e6d99af..831dd7f02 100644--- a/web/app/redux/models/IAlerts.ts+++ b/web/app/redux/models/Alerts.ts@@ -1,6 +1,6 @@import { QUERY_METRIC, QUERY_CONDITION, QUERY_TIME } from '../constants'-export interface IAlerts {+export interface Alerts {id: stringname: stringactive: booleandiff --git a/web/app/redux/models/Auth.ts b/web/app/redux/models/Auth.tsnew file mode 100644index 000000000..9a75e524c--- /dev/null+++ b/web/app/redux/models/Auth.ts@@ -0,0 +1,10 @@+import { User } from './User'++export interface Auth {+ refreshToken: string+ accessToken: string+ user: User+ totalMonthlyEvents: number+}++export type SSOProvider = 'google' | 'github'diff --git a/web/app/redux/models/Entry.ts b/web/app/redux/models/Entry.tsnew file mode 100644index 000000000..1acbf8b05--- /dev/null+++ b/web/app/redux/models/Entry.ts@@ -0,0 +1,9 @@+export interface Entry {+ name: string+ count: number+ cc?: string+}++export interface CountryEntry extends Entry {+ cc: string+}diff --git a/web/app/redux/models/IAuth.ts b/web/app/redux/models/IAuth.tsdeleted file mode 100644index 3b2dda1e7..000000000--- a/web/app/redux/models/IAuth.ts+++ /dev/null@@ -1,7 +0,0 @@-import { IUser } from './IUser'--export interface IAuth {- refresh_token: string- access_token: string- user: IUser-}diff --git a/web/app/redux/models/IEntry.ts b/web/app/redux/models/IEntry.tsdeleted file mode 100644index fdb336d4e..000000000--- a/web/app/redux/models/IEntry.ts+++ /dev/null@@ -1,9 +0,0 @@-export interface IEntry {- name: string- count: number- cc?: string-}--export interface ICountryEntry extends IEntry {- cc: string-}diff --git a/web/app/redux/models/ISharedProject.ts b/web/app/redux/models/ISharedProject.tsdeleted file mode 100644index 094789a17..000000000--- a/web/app/redux/models/ISharedProject.ts+++ /dev/null@@ -1,15 +0,0 @@-import { IProject } from './IProject'--export interface IProjectForShared extends IProject {- shared?: boolean-}--export interface ISharedProject {- id: string- confirmed: boolean- role: string- created: string- updated: string- project: IProjectForShared- uiHidden: boolean-}diff --git a/web/app/redux/models/IMetainfo.ts b/web/app/redux/models/Metainfo.tssimilarity index 80%rename from web/app/redux/models/IMetainfo.tsrename to web/app/redux/models/Metainfo.tsindex bc9489999..8fe6f0087 100644--- a/web/app/redux/models/IMetainfo.ts+++ b/web/app/redux/models/Metainfo.ts@@ -1,4 +1,4 @@-export interface IMetainfo {+export interface Metainfo {country: string | nullregion: string | nullcity: string | nulldiff --git a/web/app/redux/models/IProject.ts b/web/app/redux/models/Project.tssimilarity index 74%rename from web/app/redux/models/IProject.tsrename to web/app/redux/models/Project.tsindex b5360358a..27a43695e 100644--- a/web/app/redux/models/IProject.ts+++ b/web/app/redux/models/Project.ts@@ -1,15 +1,15 @@import { Organisation, Role } from './Organisation'-interface _IOverallPeriodStats {+interface OverallPeriodStats {all: numberunique?: numberbounceRate?: numbersdur?: number}-export interface IOverallObject {- current: _IOverallPeriodStats- previous: _IOverallPeriodStats+export interface OverallObject {+ current: OverallPeriodStats+ previous: OverallPeriodStatschange: numberuniqueChange?: numberbounceRateChange?: number@@ -17,11 +17,11 @@ export interface IOverallObject {customEVFilterApplied?: boolean}-export interface IOverall {- [key: string]: IOverallObject+export interface Overall {+ [key: string]: OverallObject}-export interface IOverallPerformanceObject {+export interface OverallPerformanceObject {current: {frontend: numberbackend: number@@ -42,11 +42,11 @@ interface UserShareProject {id: string}-export interface ILiveStats {+export interface LiveStats {[key: string]: number}-export interface IShareOwnerProject {+export interface ShareOwnerProject {id: stringconfirmed: booleanrole: string@@ -55,14 +55,14 @@ export interface IShareOwnerProject {user: UserShareProject}-export interface IFunnel {+export interface Funnel {id: stringname: stringsteps: string[]created: string}-export interface IAnalyticsFunnel {+export interface AnalyticsFunnel {value: stringevents: numbereventsPerc: number@@ -71,7 +71,7 @@ export interface IAnalyticsFunnel {dropoffPercStep: number}-export interface IProject {+export interface Project {id: stringname: stringorigins: string[] | string | null@@ -83,10 +83,10 @@ export interface IProject {isCaptchaEnabled: booleancaptchaSecretKey: string | nullcreated: string- share?: IShareOwnerProject[]- overall: IOverallObject+ share?: ShareOwnerProject[]+ overall: OverallObjectuiHidden: boolean- funnels: IFunnel[]+ funnels: Funnel[]isPublic?: booleanisTransferring?: booleanisPasswordProtected?: boolean@@ -101,7 +101,7 @@ export interface IProject {role?: Role}-export interface ICaptchaProject extends IProject {+export interface CaptchaProject extends Project {isCaptchaProject: trueisCaptchaEnabled: true}diff --git a/web/app/redux/models/SharedProject.ts b/web/app/redux/models/SharedProject.tsnew file mode 100644index 000000000..319d9ab4c--- /dev/null+++ b/web/app/redux/models/SharedProject.ts@@ -0,0 +1,15 @@+import { Project } from './Project'++export interface ProjectForShared extends Project {+ shared?: boolean+}++export interface SharedProject {+ id: string+ confirmed: boolean+ role: string+ created: string+ updated: string+ project: ProjectForShared+ uiHidden: boolean+}diff --git a/web/app/redux/models/IStats.ts b/web/app/redux/models/Stats.tssimilarity index 67%rename from web/app/redux/models/IStats.tsrename to web/app/redux/models/Stats.tsindex 5ca470ba2..81145139a 100644--- a/web/app/redux/models/IStats.ts+++ b/web/app/redux/models/Stats.ts@@ -1,4 +1,4 @@-export interface IStats {+export interface Stats {users: numberprojects: numberevents: numberdiff --git a/web/app/redux/models/ISubscribers.ts b/web/app/redux/models/Subscriber.tssimilarity index 89%rename from web/app/redux/models/ISubscribers.tsrename to web/app/redux/models/Subscriber.tsindex 513104fa2..69f3d48f8 100644--- a/web/app/redux/models/ISubscribers.ts+++ b/web/app/redux/models/Subscriber.ts@@ -1,6 +1,6 @@import { reportFrequencies } from '../constants'-export interface ISubscribers {+export interface Subscriber {userId: stringprojectId: stringprojectName: stringdiff --git a/web/app/redux/models/IUsageinfo.ts b/web/app/redux/models/Usageinfo.tssimilarity index 86%rename from web/app/redux/models/IUsageinfo.tsrename to web/app/redux/models/Usageinfo.tsindex 61a144805..66a1b56cf 100644--- a/web/app/redux/models/IUsageinfo.ts+++ b/web/app/redux/models/Usageinfo.ts@@ -1,4 +1,4 @@-export interface IUsageInfo {+export interface UsageInfo {total: numbertraffic: numbercustomEvents: numberdiff --git a/web/app/redux/models/IUser.ts b/web/app/redux/models/User.tssimilarity index 94%rename from web/app/redux/models/IUser.tsrename to web/app/redux/models/User.tsindex 04bd1dc31..46c3ec0d8 100644--- a/web/app/redux/models/IUser.ts+++ b/web/app/redux/models/User.ts@@ -1,4 +1,4 @@-import { ISharedProject } from './ISharedProject'+import { SharedProject } from './SharedProject'import { OrganisationMembership } from './Organisation'export enum DashboardBlockReason {@@ -22,7 +22,7 @@ enum PlanCode {'10m' = '10m',}-export interface IUser {+export interface User {id: stringroles: string[]planCode: PlanCode@@ -52,7 +52,7 @@ export interface IUser {telegramChatId: string | nullisTelegramChatIdConfirmed: booleantimeFormat: string- sharedProjects: ISharedProject[]+ sharedProjects: SharedProject[]registeredWithGoogle: booleangoogleId: string | nullgithubId: number | nulldiff --git a/web/app/redux/models/IUserFlow.ts b/web/app/redux/models/UserFlow.tssimilarity index 100%rename from web/app/redux/models/IUserFlow.tsrename to web/app/redux/models/UserFlow.tsdiff --git a/web/app/redux/reducers/auth.ts b/web/app/redux/reducers/auth.tsindex 2d774b6b2..66e2f3a45 100644--- a/web/app/redux/reducers/auth.ts+++ b/web/app/redux/reducers/auth.ts@@ -1,9 +1,9 @@import { createSlice, PayloadAction } from '@reduxjs/toolkit'-import { IUser } from '../models/IUser'+import { User } from '../models/User'import { FREE_TIER_KEY, isSelfhosted } from '../constants'interface AuthState {- user: IUser+ user: Userauthenticated: booleanloading: booleandontRemember: boolean@@ -11,7 +11,7 @@ interface AuthState {}const initialState: AuthState = {- user: {} as IUser,+ user: {} as User,authenticated: false,loading: true,dontRemember: false,@@ -26,23 +26,23 @@ const authSlice = createSlice({finishLoading: (state) => {state.loading = false},- authSuccessful: (state, { payload }: PayloadAction<IUser>) => {+ authSuccessful: (state, { payload }: PayloadAction<User>) => {state.user = payloadstate.authenticated = truestate.isPaidTierUsed = isSelfhosted || ((payload?.planCode && payload.planCode !== FREE_TIER_KEY) as boolean)},logout: (state) => {- state.user = {} as IUser+ state.user = {} as Userstate.authenticated = falsestate.isPaidTierUsed = isSelfhosted},setDontRemember: (state, { payload }: PayloadAction<boolean>) => {state.dontRemember = payload},- mergeUser: (state, { payload }: PayloadAction<Partial<IUser>>) => {+ mergeUser: (state, { payload }: PayloadAction<Partial<User>>) => {state.user = { ...state.user, ...payload }},- setUser: (state, { payload }: PayloadAction<IUser>) => {+ setUser: (state, { payload }: PayloadAction<User>) => {state.user = payload},},diff --git a/web/app/redux/reducers/ui/cache.ts b/web/app/redux/reducers/ui/cache.tsindex 73f2908ed..6911932ed 100644--- a/web/app/redux/reducers/ui/cache.ts+++ b/web/app/redux/reducers/ui/cache.ts@@ -10,7 +10,7 @@ import {getUserFlowCacheKey,isBrowser,} from 'redux/constants'-import { IUserFlow } from 'redux/models/IUserFlow'+import { IUserFlow } from 'redux/models/UserFlow'import { filterInvalidViewPrefs } from 'pages/Project/View/utils/filters'const getInitialViewPrefs = (LS_VIEW: string) => {@@ -29,7 +29,7 @@ const getInitialViewPrefs = (LS_VIEW: string) => {return {}}-interface IInitialState {+interface InitialState {analytics: anyanalyticsPerf: anyfunnels: any@@ -53,7 +53,7 @@ interface IInitialState {referralStatistics: any}-const initialState: IInitialState = {+const initialState: InitialState = {analytics: {},analyticsPerf: {},funnels: {},diff --git a/web/app/redux/reducers/ui/index.ts b/web/app/redux/reducers/ui/index.tsindex f57cdbe04..55f9bcd0d 100644--- a/web/app/redux/reducers/ui/index.ts+++ b/web/app/redux/reducers/ui/index.ts@@ -2,14 +2,12 @@ import { cacheActions } from './cache'import { miscActions } from './misc'import { projectsActions } from './projects'import { themeActions } from './theme'-import { monitorActions } from './monitors'const UIActions = {...cacheActions,...miscActions,...projectsActions,...themeActions,- ...monitorActions,}export default UIActionsdiff --git a/web/app/redux/reducers/ui/misc.ts b/web/app/redux/reducers/ui/misc.tsindex efad16766..af1386f1c 100644--- a/web/app/redux/reducers/ui/misc.ts+++ b/web/app/redux/reducers/ui/misc.ts@@ -2,15 +2,12 @@ import { createSlice, PayloadAction } from '@reduxjs/toolkit'import { LOW_EVENTS_WARNING } from 'redux/constants'import { setCookie } from 'utils/cookie'import { secondsTillNextMonth } from 'utils/generic'-import { IStats } from 'redux/models/IStats'-import { IMetainfo } from 'redux/models/IMetainfo'-import { IUsageInfo } from 'redux/models/IUsageinfo'+import { Stats } from 'redux/models/Stats'+import { Metainfo } from 'redux/models/Metainfo'-interface IInitialState {- stats: IStats- metainfo: IMetainfo- usageinfo: IUsageInfo- usageinfoLoaded: boolean+interface InitialState {+ stats: Stats+ metainfo: MetainfopaddleLoaded: booleanpaddle: anyshowNoEventsLeftBanner: boolean@@ -18,7 +15,7 @@ interface IInitialState {extensions: any[]}-const initialState: IInitialState = {+const initialState: InitialState = {stats: {users: 0,projects: 0,@@ -31,18 +28,6 @@ const initialState: IInitialState = {symbol: '$',code: 'USD',},- usageinfo: {- total: 0,- traffic: 0,- errors: 0,- customEvents: 0,- captcha: 0,- trafficPerc: 0,- errorsPerc: 0,- customEventsPerc: 0,- captchaPerc: 0,- },- usageinfoLoaded: false,paddleLoaded: false,paddle: {},showNoEventsLeftBanner: false,@@ -54,7 +39,7 @@ const miscSlice = createSlice({name: 'misc',initialState,reducers: {- setGeneralStats(state, { payload }: PayloadAction<IStats>) {+ setGeneralStats(state, { payload }: PayloadAction<Stats>) {state.stats = payload},setPaddleLastEvent(state, { payload }: PayloadAction<any>) {@@ -71,13 +56,9 @@ const miscSlice = createSlice({setExtensions(state, { payload }: PayloadAction<any[]>) {state.extensions = payload},- setMetainfo(state, { payload }: PayloadAction<IMetainfo>) {+ setMetainfo(state, { payload }: PayloadAction<Metainfo>) {state.metainfo = payload},- setUsageinfo(state, { payload }: PayloadAction<IUsageInfo>) {- state.usageinfoLoaded = true- state.usageinfo = payload- },setLastBlogPost(state, { payload }: PayloadAction<any>) {state.lastBlogPost = payload},diff --git a/web/app/redux/reducers/ui/monitors.ts b/web/app/redux/reducers/ui/monitors.tsdeleted file mode 100644index 4cc66f043..000000000--- a/web/app/redux/reducers/ui/monitors.ts+++ /dev/null@@ -1,37 +0,0 @@-import { createSlice, PayloadAction } from '@reduxjs/toolkit'-import { Monitor } from 'redux/models/Uptime'--interface IInitialState {- monitors: Monitor[]- total: number- pageTotal: number- loading: boolean-}--const initialState: IInitialState = {- monitors: [],- total: 0,- pageTotal: 0,- loading: false,-}--const monitorsSlice = createSlice({- name: 'monitors',- initialState,- reducers: {- setMonitors(state, action: PayloadAction<Monitor[]>) {- state.monitors = action.payload- },- setMonitorsTotal(state, { payload }: PayloadAction<{ total: number; pageTotal?: number }>) {- state.total = payload.total- state.pageTotal = payload.pageTotal || state.pageTotal- },- setMonitorsLoading(state, { payload }: PayloadAction<boolean>) {- state.loading = payload- },- },-})--export const monitorActions = monitorsSlice.actions--export default monitorsSlice.reducerdiff --git a/web/app/redux/reducers/ui/projects.ts b/web/app/redux/reducers/ui/projects.tsindex 5770e833a..bf7471888 100644--- a/web/app/redux/reducers/ui/projects.ts+++ b/web/app/redux/reducers/ui/projects.ts@@ -3,14 +3,12 @@ import { PROJECTS_PROTECTED } from 'redux/constants'import { setItem, getItem } from 'utils/localstorage'interface InitialState {- totalMonthlyEvents: number | nullpassword: {[key: string]: string}}const initialState: InitialState = {- totalMonthlyEvents: null,password: getItem(PROJECTS_PROTECTED) || {},}@@ -18,9 +16,6 @@ const projectsSlice = createSlice({name: 'projects',initialState,reducers: {- setTotalMonthlyEvents(state, { payload }: PayloadAction<number>) {- state.totalMonthlyEvents = payload- },setProjectPassword: (state, { payload }: PayloadAction<{ id: string; password: string }>) => {const { id, password } = payloaddiff --git a/web/app/redux/reducers/ui/theme.ts b/web/app/redux/reducers/ui/theme.tsindex fdfc90584..7ee7c9a8e 100644--- a/web/app/redux/reducers/ui/theme.ts+++ b/web/app/redux/reducers/ui/theme.ts@@ -1,7 +1,7 @@import { createSlice, PayloadAction } from '@reduxjs/toolkit'import _includes from 'lodash/includes'import { setCookie, getCookie } from 'utils/cookie'-import { isBrowser, LS_THEME_SETTING, SUPPORTED_THEMES, THEME_TYPE, ThemeType } from 'redux/constants'+import { isBrowser, LS_THEME_SETTING, SUPPORTED_THEMES, ThemeType } from 'redux/constants'const setThemeToDOM = (theme: string) => {if (!isBrowser) {@@ -54,15 +54,13 @@ const getInitialTheme = (): ThemeType => {return 'light' // light theme as the default}-interface IInitialState {+interface InitialState {theme: ThemeType- type: string}-const getInitialState = (): IInitialState => {+const getInitialState = (): InitialState => {return {theme: getInitialTheme(),- type: THEME_TYPE.classic,}}@@ -74,9 +72,6 @@ const themeSlice = createSlice({setTheme(payload)state.theme = payload},- setThemeType(state, { payload }: PayloadAction<string>) {- state.type = payload- },},})diff --git a/web/app/redux/sagas/actions/index.ts b/web/app/redux/sagas/actions/index.tsdeleted file mode 100644index cc3c65871..000000000--- a/web/app/redux/sagas/actions/index.ts+++ /dev/null@@ -1,178 +0,0 @@-/* eslint-disable no-unused-vars */-import types from 'redux/sagas/actions/types'-import type i18next from 'i18next'-import { removeAccessToken } from 'utils/accessToken'-import { removeItem } from 'utils/localstorage'-import { LS_VIEW_PREFS_SETTING, LS_CAPTCHA_VIEW_PREFS_SETTING } from 'redux/constants'-import { IUser } from '../../models/IUser'--const loadMetainfo = () => ({- type: types.LOAD_METAINFO,-})--const loadUsageinfo = () => ({- type: types.LOAD_USAGEINFO,-})--const loadExtensions = () => ({- type: types.LOAD_EXTENSIONS,-})--const loadMonitors = (take?: number, skip?: number) => ({- type: types.LOAD_MONITORS,- payload: { take, skip },-})--const loginAsync = (- credentials: {- email: string- password: string- dontRemember: boolean- },- callback: (isSuccess: boolean, isTwoFactorAuthenticationEnabled: boolean) => void = () => {},-) => ({- type: types.LOGIN_ASYNC,- payload: {- credentials,- callback,- },-})--// currently only google is supported, in future we should provide a variable specifying the provider-const authSSO = (- provider: string,- dontRemember: boolean,- // @ts-expect-error- t: typeof i18next.t = () => '',- callback: (res: any) => void = () => {},-) => ({- type: types.AUTH_SSO,- payload: {- dontRemember,- callback,- t,- provider,- },-})--// currently only google is supported, in future we should provide a variable specifying the provider-// @ts-expect-error-const linkSSO = (t: typeof i18next.t = () => '', callback: (res: any) => void = () => {}, provider = 'google') => ({- type: types.LINK_SSO,- payload: {- callback,- t,- provider,- },-})--// currently only google is supported, in future we should provide a variable specifying the provider-// @ts-expect-error-const unlinkSSO = (t: typeof i18next.t = () => '', callback: (res: any) => void = () => {}, provider = 'google') => ({- type: types.UNLINK_SSO,- payload: {- callback,- t,- provider,- },-})--const signupAsync = (- data: {- email: string- password: string- },- t?: (string: string) => {},- callback = (res: any) => {},-) => ({- type: types.SIGNUP_ASYNC,- payload: {- data,- callback,- t,- },-})--const emailVerifyAsync = (- data: {- id: string- },- successfulCallback?: () => void,- errorCallback?: (e: string) => void,-) => ({- type: types.EMAIL_VERIFY_ASYNC,- payload: { data, successfulCallback, errorCallback },-})--const updateUserProfileAsync = (data: Partial<IUser>, callback = (item: any) => {}) => ({- type: types.UPDATE_USER_PROFILE_ASYNC,- payload: { data, callback },-})--const deleteAccountAsync = (- errorCallback?: (e: string) => {},- successCallback?: (str?: string) => void,- deletionFeedback?: string,- t?: (str: string) => {},-) => {- return {- type: types.DELETE_ACCOUNT_ASYNC,- payload: {- errorCallback,- successCallback,- t,- deletionFeedback,- },- }-}--const shareVerifyAsync = (- data: {- id: string- path: string- },- successfulCallback?: () => void,- errorCallback?: (error: string) => void,-) => ({- type: types.SHARE_VERIFY_ASYNC,- payload: { data, successfulCallback, errorCallback },-})--const logout = (basedOn401Error: boolean, isLogoutAll: boolean) => {- removeAccessToken()- removeItem(LS_VIEW_PREFS_SETTING)- removeItem(LS_CAPTCHA_VIEW_PREFS_SETTING)-- return {- type: types.LOGOUT,- payload: { basedOn401Error, isLogoutAll },- }-}--const updateShowLiveVisitorsInTitle = (show: boolean, callback: (isSuccess: boolean) => void) => ({- type: types.UPDATE_SHOW_LIVE_VISITORS_IN_TITLE,- payload: {- show,- callback,- },-})--const sagaActions = {- loadExtensions,- loginAsync,- authSSO,- signupAsync,- emailVerifyAsync,- updateUserProfileAsync,- deleteAccountAsync,- logout,- shareVerifyAsync,- linkSSO,- unlinkSSO,- loadMetainfo,- loadUsageinfo,- updateShowLiveVisitorsInTitle,- loadMonitors,-}--export default sagaActionsdiff --git a/web/app/redux/sagas/actions/types.ts b/web/app/redux/sagas/actions/types.tsdeleted file mode 100644index 44cb33b33..000000000--- a/web/app/redux/sagas/actions/types.ts+++ /dev/null@@ -1,19 +0,0 @@-const sagaTypes = Object.freeze({- LOAD_EXTENSIONS: 'LOAD_EXTENSIONS',- LOAD_METAINFO: 'LOAD_METAINFO',- LOAD_USAGEINFO: 'LOAD_USAGEINFO',- LOAD_MONITORS: 'LOAD_MONITORS',- LOGIN_ASYNC: 'LOGIN_ASYNC',- SIGNUP_ASYNC: 'SIGNUP_ASYNC',- EMAIL_VERIFY_ASYNC: 'EMAIL_VERIFY_ASYNC',- UPDATE_USER_PROFILE_ASYNC: 'UPDATE_USER_PROFILE_ASYNC',- UPDATE_SHOW_LIVE_VISITORS_IN_TITLE: 'UPDATE_SHOW_LIVE_VISITORS_IN_TITLE',- DELETE_ACCOUNT_ASYNC: 'DELETE_ACCOUNT_ASYNC',- SHARE_VERIFY_ASYNC: 'SHARE_VERIFY_ASYNC',- LOGOUT: 'LOGOUT',- AUTH_SSO: 'AUTH_SSO',- LINK_SSO: 'LINK_SSO',- UNLINK_SSO: 'UNLINK_SSO',-})--export default sagaTypesdiff --git a/web/app/redux/sagas/auth/watchers/index.ts b/web/app/redux/sagas/auth/watchers/index.tsdeleted file mode 100644index 01a95c647..000000000--- a/web/app/redux/sagas/auth/watchers/index.ts+++ /dev/null@@ -1,77 +0,0 @@-import { takeLatest, all, call } from 'redux-saga/effects'-import signIn from '../workers/signin'-import signUp from '../workers/signup'-import logout from '../workers/logout'-import verifyEmail from '../workers/verifyEmail'-import updateUserProfile from '../workers/updateUserProfile'-import deleteUserAccount from '../workers/deleteUserAccount'-import ssoAuth from '../workers/sso_auth'-import ssoLink from '../workers/sso_link'-import ssoUnlink from '../workers/sso_unlink'-import updateShowLiveVisitorsInTitle from '../workers/update_show_live_visitors_in_title'-import sagaTypes from '../../actions/types'--function* watchLogin() {- // @ts-ignore- yield takeLatest(sagaTypes.LOGIN_ASYNC, signIn)-}--function* watchVerifyEmail() {- // @ts-ignore- yield takeLatest(sagaTypes.EMAIL_VERIFY_ASYNC, verifyEmail)-}--function* watchSignup() {- // @ts-ignore- yield takeLatest(sagaTypes.SIGNUP_ASYNC, signUp)-}--function* watchLogout() {- // @ts-ignore- yield takeLatest(sagaTypes.LOGOUT, logout)-}--function* watchUpdateUserProfile() {- // @ts-ignore- yield takeLatest(sagaTypes.UPDATE_USER_PROFILE_ASYNC, updateUserProfile)-}--function* watchDeleteUserProfile() {- // @ts-ignore- yield takeLatest(sagaTypes.DELETE_ACCOUNT_ASYNC, deleteUserAccount)-}--function* watchAuthSSO() {- // @ts-ignore- yield takeLatest(sagaTypes.AUTH_SSO, ssoAuth)-}--function* watchLinkSSO() {- // @ts-ignore- yield takeLatest(sagaTypes.LINK_SSO, ssoLink)-}--function* watchUnlinkSSO() {- // @ts-ignore- yield takeLatest(sagaTypes.UNLINK_SSO, ssoUnlink)-}--function* watchUpdateShowLiveVisitorsInTitle() {- // @ts-ignore- yield takeLatest(sagaTypes.UPDATE_SHOW_LIVE_VISITORS_IN_TITLE, updateShowLiveVisitorsInTitle)-}--export default function* watchAuth() {- yield all([- call(watchLogin),- call(watchSignup),- call(watchVerifyEmail),- call(watchUpdateUserProfile),- call(watchDeleteUserProfile),- call(watchLogout),- call(watchAuthSSO),- call(watchLinkSSO),- call(watchUnlinkSSO),- call(watchUpdateShowLiveVisitorsInTitle),- ])-}diff --git a/web/app/redux/sagas/auth/workers/deleteUserAccount.ts b/web/app/redux/sagas/auth/workers/deleteUserAccount.tsdeleted file mode 100644index a6bf246d2..000000000--- a/web/app/redux/sagas/auth/workers/deleteUserAccount.ts+++ /dev/null@@ -1,38 +0,0 @@-import { call, put } from 'redux-saga/effects'-import type i18next from 'i18next'-import { toast } from 'sonner'--import { authActions } from 'redux/reducers/auth'-const { deleteUser } = require('api')--export default function* deleteUserAccountWorker({- payload: { errorCallback, successCallback, t, deletionFeedback },-}: {- payload: {- errorCallback: (error: any) => void- successCallback: () => void- t: typeof i18next.t- deletionFeedback: string- }-}) {- try {- yield call(deleteUser, deletionFeedback)- yield call(successCallback)- yield put(authActions.logout())- toast.success(t('apiNotifications.accountDeleted'))- } catch (reason) {- let message-- try {- // @ts-ignore- message = JSON.parse(reason.message).message || 'somethingWentWrong'- } catch {- message = 'somethingWentWrong'- }-- // @ts-ignore- errorCallback(t([`apiNotifications.${message}`, 'apiNotifications.somethingWentWrong']))- } finally {- yield put(authActions.finishLoading())- }-}diff --git a/web/app/redux/sagas/auth/workers/logout.ts b/web/app/redux/sagas/auth/workers/logout.tsdeleted file mode 100644index 277bd960a..000000000--- a/web/app/redux/sagas/auth/workers/logout.ts+++ /dev/null@@ -1,31 +0,0 @@-import { call, put } from 'redux-saga/effects'--import UIActions from 'redux/reducers/ui'-import { getRefreshToken, removeRefreshToken } from 'utils/refreshToken'-import { IStats } from '../../../models/IStats'-const { getGeneralStats, logoutApi, logoutAllApi } = require('api')--export default function* logoutWorker({- payload: { basedOn401Error, isLogoutAll },-}: {- payload: { basedOn401Error: boolean; isLogoutAll: boolean }-}) {- try {- const refreshToken = getRefreshToken()-- if (isLogoutAll) {- yield call(logoutAllApi)- } else {- yield call(logoutApi, refreshToken)- }-- removeRefreshToken()-- if (!basedOn401Error) {- const stats: IStats = yield call(getGeneralStats)- yield put(UIActions.setGeneralStats(stats))- }- } catch (reason) {- console.error('Error while getting general stats data: ', reason)- }-}diff --git a/web/app/redux/sagas/auth/workers/signin.ts b/web/app/redux/sagas/auth/workers/signin.tsdeleted file mode 100644index 397b1f1c0..000000000--- a/web/app/redux/sagas/auth/workers/signin.ts+++ /dev/null@@ -1,53 +0,0 @@-import { call, put } from 'redux-saga/effects'-import _isObject from 'lodash/isPlainObject'-import _omit from 'lodash/omit'-import { toast } from 'sonner'-import { authActions } from 'redux/reducers/auth'--import UIActions from 'redux/reducers/ui'-import { setAccessToken } from 'utils/accessToken'-import { setRefreshToken } from 'utils/refreshToken'-import sagaActions from '../../actions/index'-const { login } = require('api')--interface ISigninWorker {- payload: {- credentials: {- email: string- password: string- dontRemember: boolean- }- callback: (isSuccess: boolean, isTwoFactorAuthenticationEnabled: boolean) => void- }-}--export default function* singinWorker({ payload: { credentials, callback } }: ISigninWorker) {- try {- const { dontRemember } = credentials- const { user, accessToken, refreshToken } = yield call(login, _omit(credentials, ['dontRemember']))-- yield put(authActions.setDontRemember(dontRemember))-- if (user.isTwoFactorAuthenticationEnabled) {- yield call(setAccessToken, accessToken, true)- yield call(setRefreshToken, refreshToken, true)- yield put(authActions.mergeUser(user))- callback(false, true)- return- }-- yield put(authActions.authSuccessful(user))- yield call(setAccessToken, accessToken, dontRemember)- yield call(setRefreshToken, refreshToken)- yield put(UIActions.setThemeType(user.theme))- yield put(sagaActions.loadMonitors())- callback(true, false)- } catch (reason: any) {- const err = _isObject(reason) ? reason.message : reason-- toast.error(err || 'apiNotifications.somethingWentWrong')- callback(false, false)- } finally {- yield put(authActions.finishLoading())- }-}diff --git a/web/app/redux/sagas/auth/workers/signup.ts b/web/app/redux/sagas/auth/workers/signup.tsdeleted file mode 100644index 2a655f8f1..000000000--- a/web/app/redux/sagas/auth/workers/signup.ts+++ /dev/null@@ -1,59 +0,0 @@-import { call, put } from 'redux-saga/effects'-import { authActions } from 'redux/reducers/auth'-import { toast } from 'sonner'--import { setAccessToken } from 'utils/accessToken'-import { setRefreshToken } from 'utils/refreshToken'-import { getCookie, deleteCookie } from 'utils/cookie'-import { REFERRAL_COOKIE } from 'redux/constants'-import sagaActions from '../../actions'-const { signup } = require('api')--export default function* signupWorder({- payload: { data: rawData, callback },-}: {- payload: {- data: {- email: string- password: string- repeat: string- dontRemember: boolean- checkIfLeaked: boolean- }- callback: (isSuccess: boolean) => void- }-}) {- try {- const { dontRemember } = rawData- const refCode = getCookie(REFERRAL_COOKIE)- const {- user,- accessToken,- refreshToken, // theme,- // @ts-ignore- } = yield call(signup, {- email: rawData.email,- password: rawData.password,- checkIfLeaked: rawData.checkIfLeaked,- refCode,- })-- if (refCode) {- deleteCookie(REFERRAL_COOKIE)- }-- yield put(authActions.authSuccessful(user))- yield call(setAccessToken, accessToken, dontRemember)- yield call(setRefreshToken, refreshToken)- yield put(authActions.setDontRemember(dontRemember))- yield put(sagaActions.loadMonitors())- callback(true)- } catch (reason: any) {- const message = reason.message || (typeof reason === 'string' ? reason : reason[0])-- toast.error(message)- callback(false)- } finally {- yield put(authActions.finishLoading())- }-}diff --git a/web/app/redux/sagas/auth/workers/sso_auth.ts b/web/app/redux/sagas/auth/workers/sso_auth.tsdeleted file mode 100644index 448be71f7..000000000--- a/web/app/redux/sagas/auth/workers/sso_auth.ts+++ /dev/null@@ -1,88 +0,0 @@-import { call, put, delay } from 'redux-saga/effects'-import type i18next from 'i18next'-import { toast } from 'sonner'--import { authActions } from 'redux/reducers/auth'-import { setAccessToken } from 'utils/accessToken'-import { setRefreshToken } from 'utils/refreshToken'-import { openBrowserWindow } from 'utils/generic'-import { getCookie, deleteCookie } from 'utils/cookie'-import { REFERRAL_COOKIE } from 'redux/constants'-import sagaActions from '../../actions/index'-const { getJWTBySSOHash, generateSSOAuthURL } = require('api')--const AUTH_WINDOW_WIDTH = 600-const AUTH_WINDOW_HEIGHT = 800--const HASH_CHECK_FREQUENCY = 1000 // 1 second--interface ISSOAuth {- payload: {- callback: (isSuccess: boolean, is2FA: boolean) => void- dontRemember: boolean- t: typeof i18next.t- provider: string- }-}--export default function* ssoAuth({ payload: { callback, dontRemember, t, provider } }: ISSOAuth) {- const authWindow = openBrowserWindow('', AUTH_WINDOW_WIDTH, AUTH_WINDOW_HEIGHT)-- if (!authWindow) {- toast.error(t('apiNotifications.socialisationAuthGenericError'))- callback(false, false)- return- }-- try {- const { uuid, auth_url: authUrl, expires_in: expiresIn } = yield call(generateSSOAuthURL, provider)-- // Set the URL of the authentification browser window- authWindow.location = authUrl-- // Closing the authorisation window after the session expires- setTimeout(authWindow.close, expiresIn)-- const refCode = getCookie(REFERRAL_COOKIE)-- while (true) {- yield delay(HASH_CHECK_FREQUENCY)-- try {- const { accessToken, refreshToken, user } = yield call(getJWTBySSOHash, uuid, provider, refCode)- authWindow.close()-- if (refCode) {- deleteCookie(REFERRAL_COOKIE)- }-- yield put(authActions.setDontRemember(dontRemember))-- if (user.isTwoFactorAuthenticationEnabled) {- yield call(setAccessToken, accessToken, true)- yield call(setRefreshToken, refreshToken)- yield put(authActions.mergeUser(user))- callback(false, true)- return- }-- yield put(authActions.authSuccessful(user))- yield call(setAccessToken, accessToken, dontRemember)- yield call(setRefreshToken, refreshToken)- yield put(sagaActions.loadMonitors())- yield put(authActions.finishLoading())- callback(true, false)- return- } catch (reason) {- // Authentication is not finished yet- }- if (authWindow.closed) {- callback(false, false)- return- }- }- } catch (reason) {- toast.error(t('apiNotifications.socialisationAuthGenericError'))- callback(false, false)- }-}diff --git a/web/app/redux/sagas/auth/workers/sso_link.ts b/web/app/redux/sagas/auth/workers/sso_link.tsdeleted file mode 100644index b58411602..000000000--- a/web/app/redux/sagas/auth/workers/sso_link.ts+++ /dev/null@@ -1,67 +0,0 @@-import type i18next from 'i18next'-import { call, put, delay } from 'redux-saga/effects'-import { toast } from 'sonner'--import { authActions } from 'redux/reducers/auth'-import { openBrowserWindow } from 'utils/generic'-const { linkBySSOHash, generateSSOAuthURL, authMe } = require('api')--const AUTH_WINDOW_WIDTH = 600-const AUTH_WINDOW_HEIGHT = 800--const HASH_CHECK_FREQUENCY = 1000 // 1 second--interface ISSOLink {- payload: {- callback: (isSuccess: boolean) => void- t: typeof i18next.t- provider: string- }-}--export default function* ssoLink({ payload: { callback, t, provider } }: ISSOLink) {- const authWindow = openBrowserWindow('', AUTH_WINDOW_WIDTH, AUTH_WINDOW_HEIGHT)-- if (!authWindow) {- toast.error(t('apiNotifications.socialisationGenericError'))- callback(false)- return- }-- try {- const { uuid, auth_url: authUrl, expires_in: expiresIn } = yield call(generateSSOAuthURL, provider)-- // Set the URL of the authentification browser window- authWindow.location = authUrl-- // Closing the authorisation window after the session expires- setTimeout(authWindow.close, expiresIn)-- while (true) {- yield delay(HASH_CHECK_FREQUENCY)-- try {- yield call(linkBySSOHash, uuid, provider)- authWindow.close()-- // @ts-ignore- const user = yield call(authMe)- yield put(authActions.authSuccessful(user))-- toast.success(t('apiNotifications.socialAccountLinked'))-- callback(true)- return- } catch (reason) {- // Authentication is not finished yet- }- if (authWindow.closed) {- callback(false)- return- }- }- } catch (reason) {- toast.error(t('apiNotifications.socialisationGenericError'))- callback(false)- }-}diff --git a/web/app/redux/sagas/auth/workers/sso_unlink.ts b/web/app/redux/sagas/auth/workers/sso_unlink.tsdeleted file mode 100644index 39058f559..000000000--- a/web/app/redux/sagas/auth/workers/sso_unlink.ts+++ /dev/null@@ -1,38 +0,0 @@-import type i18next from 'i18next'-import { call, put } from 'redux-saga/effects'-import _values from 'lodash/values'-import _includes from 'lodash/includes'-import { toast } from 'sonner'--import { authActions } from 'redux/reducers/auth'-import { SSO_PROVIDERS } from 'redux/constants'-const { unlinkSSO, authMe } = require('api')--interface ISSOUnlink {- payload: {- provider: string- t: typeof i18next.t- callback: (isSuccess: boolean) => void- }-}--export default function* ssoUnlink({ payload: { provider, t, callback } }: ISSOUnlink) {- if (!_includes(_values(SSO_PROVIDERS), provider)) {- callback(false)- return- }-- try {- yield call(unlinkSSO, provider)-- // @ts-ignore- const user = yield call(authMe)- yield put(authActions.authSuccessful(user))-- toast.success(t('apiNotifications.socialAccountUninked'))- callback(true)- } catch (reason) {- toast.error(t('apiNotifications.socialisationUnlinkGenericError'))- callback(false)- }-}diff --git a/web/app/redux/sagas/auth/workers/updateUserProfile.ts b/web/app/redux/sagas/auth/workers/updateUserProfile.tsdeleted file mode 100644index 5cbbeefde..000000000--- a/web/app/redux/sagas/auth/workers/updateUserProfile.ts+++ /dev/null@@ -1,28 +0,0 @@-import { call, put } from 'redux-saga/effects'-import { toast } from 'sonner'--import { authActions } from 'redux/reducers/auth'-import { IUser } from '../../../models/IUser'-const { changeUserDetails } = require('api')--export default function* updateUserProfileWorker({- payload: { data, callback },-}: {- payload: {- data: IUser- callback: (isSuccess: boolean) => void- }-}) {- let isSuccess = false- try {- const user: IUser = yield call(changeUserDetails, data)-- yield put(authActions.setUser(user))- isSuccess = true- } catch (reason: any) {- toast.error(reason?.message || (typeof reason === 'string' ? reason : reason[0]))- } finally {- yield put(authActions.finishLoading())- callback(isSuccess)- }-}diff --git a/web/app/redux/sagas/auth/workers/update_show_live_visitors_in_title.ts b/web/app/redux/sagas/auth/workers/update_show_live_visitors_in_title.tsdeleted file mode 100644index f587c3de8..000000000--- a/web/app/redux/sagas/auth/workers/update_show_live_visitors_in_title.ts+++ /dev/null@@ -1,26 +0,0 @@-import { call, put } from 'redux-saga/effects'-import { toast } from 'sonner'--import { authActions } from 'redux/reducers/auth'-import { IUser } from '../../../models/IUser'-const { setShowLiveVisitorsInTitle } = require('api')--interface IPayload {- show: boolean- callback: (isSuccess: boolean) => void-}--export default function* updateShowLiveVisitorsInTitle({ payload: { show, callback } }: { payload: IPayload }) {- let isSuccess = false-- try {- const user: Partial<IUser> = yield call(setShowLiveVisitorsInTitle, show)-- yield put(authActions.mergeUser(user))- isSuccess = true- } catch (reason: any) {- toast.error(reason?.message || (typeof reason === 'string' ? reason : reason[0]))- } finally {- callback(isSuccess)- }-}diff --git a/web/app/redux/sagas/auth/workers/verifyEmail.ts b/web/app/redux/sagas/auth/workers/verifyEmail.tsdeleted file mode 100644index 4c40340ca..000000000--- a/web/app/redux/sagas/auth/workers/verifyEmail.ts+++ /dev/null@@ -1,27 +0,0 @@-import { call, put } from 'redux-saga/effects'--import { authActions } from 'redux/reducers/auth'-const { verifyEmail } = require('api')--export default function* verifyEmailWorker({- payload: { data, successfulCallback, errorCallback },-}: {- payload: {- data: {- id: string- }- successfulCallback: () => void- errorCallback: (error: any) => void- }-}) {- try {- // @ts-ignore- yield call(verifyEmail, data)- yield put(authActions.mergeUser({ isActive: true }))- successfulCallback()- } catch (reason) {- errorCallback(reason)- } finally {- yield put(authActions.finishLoading())- }-}diff --git a/web/app/redux/sagas/index.ts b/web/app/redux/sagas/index.tsdeleted file mode 100644index b5d975cf0..000000000--- a/web/app/redux/sagas/index.ts+++ /dev/null@@ -1,8 +0,0 @@-import { fork } from 'redux-saga/effects'-import watchAuth from './auth/watchers'-import mainUISaga from './ui'--export default function* rootSaga() {- yield fork(watchAuth)- yield fork(mainUISaga)-}diff --git a/web/app/redux/sagas/ui/index.ts b/web/app/redux/sagas/ui/index.tsdeleted file mode 100644index c91977700..000000000--- a/web/app/redux/sagas/ui/index.ts+++ /dev/null@@ -1,25 +0,0 @@-import { takeEvery, fork, takeLatest } from 'redux-saga/effects'-import sagaTypes from '../actions/types'-import initialise from './initialise'-import generalStats from './worker_general_stats'-import isEventsAvailable from './worker_is_events_available'-import shareVerify from './share_verify'-import loadExtensions from './load_extensions'-import loadMetainfo from './load_metainfo'-import loadUsageinfo from './load_usageinfo'-import loadMonitors from './load_monitors'--function* mainUISaga() {- yield fork(initialise)- yield fork(isEventsAvailable)- yield fork(generalStats)- yield takeEvery(sagaTypes.LOAD_METAINFO, loadMetainfo)- yield takeEvery(sagaTypes.LOAD_USAGEINFO, loadUsageinfo)- yield takeEvery(sagaTypes.LOAD_EXTENSIONS, loadExtensions)- // @ts-expect-error- yield takeLatest(sagaTypes.SHARE_VERIFY_ASYNC, shareVerify)- // @ts-expect-error- yield takeLatest(sagaTypes.LOAD_MONITORS, loadMonitors)-}--export default mainUISagadiff --git a/web/app/redux/sagas/ui/initialise.ts b/web/app/redux/sagas/ui/initialise.tsdeleted file mode 100644index eb4505780..000000000--- a/web/app/redux/sagas/ui/initialise.ts+++ /dev/null@@ -1,32 +0,0 @@-import { put, call } from 'redux-saga/effects'--import { getAccessToken } from 'utils/accessToken'-import { getRefreshToken } from 'utils/refreshToken'-import UIActions from 'redux/reducers/ui'-import { isSelfhosted } from 'redux/constants'-import sagaActions from '../actions'-const { getLastPost } = require('api')--export default function* initialise() {- try {- const token: string = yield call(getAccessToken)- const refreshToken: string = yield call(getRefreshToken)-- if (token && refreshToken) {- yield put(sagaActions.loadExtensions())- yield put(sagaActions.loadMonitors())- }-- if (!isSelfhosted) {- yield put(sagaActions.loadMetainfo())-- const lastBlogPost: {- title: string- handle: string- } = yield call(getLastPost)- yield put(UIActions.setLastBlogPost(lastBlogPost))- }- } catch (reason) {- console.error('An error occured whilst initialising:', reason)- }-}diff --git a/web/app/redux/sagas/ui/load_extensions.ts b/web/app/redux/sagas/ui/load_extensions.tsdeleted file mode 100644index 384c8b7ae..000000000--- a/web/app/redux/sagas/ui/load_extensions.ts+++ /dev/null@@ -1,20 +0,0 @@-import { put, call } from 'redux-saga/effects'--import UIActions from 'redux/reducers/ui'-import { isSelfhosted } from 'redux/constants'-const { getInstalledExtensions } = require('api')--export default function* loadExtensions() {- if (isSelfhosted) {- return- }-- try {- const { extensions } = yield call(getInstalledExtensions)-- yield put(UIActions.setExtensions(extensions))- } catch (reason: unknown) {- const { message } = reason as { message: string }- console.error('failed to load extensions:', message)- }-}diff --git a/web/app/redux/sagas/ui/load_metainfo.ts b/web/app/redux/sagas/ui/load_metainfo.tsdeleted file mode 100644index 4c51bb2cd..000000000--- a/web/app/redux/sagas/ui/load_metainfo.ts+++ /dev/null@@ -1,21 +0,0 @@-import { put, call } from 'redux-saga/effects'--import UIActions from 'redux/reducers/ui'-import { isSelfhosted } from 'redux/constants'-import { IMetainfo } from 'redux/models/IMetainfo'-const { getPaymentMetainfo } = require('api')--export default function* loadMetainfo() {- if (isSelfhosted) {- return- }-- try {- const metainfo: IMetainfo = yield call(getPaymentMetainfo)-- yield put(UIActions.setMetainfo(metainfo))- } catch (reason: unknown) {- const { message } = reason as { message: string }- console.error('failed to load metainfo:', message)- }-}diff --git a/web/app/redux/sagas/ui/load_monitors.ts b/web/app/redux/sagas/ui/load_monitors.tsdeleted file mode 100644index 84c168a74..000000000--- a/web/app/redux/sagas/ui/load_monitors.ts+++ /dev/null@@ -1,33 +0,0 @@-import { put, call } from 'redux-saga/effects'-import { toast } from 'sonner'-import _isString from 'lodash/isString'-import UIActions from 'redux/reducers/ui'-import { DEFAULT_MONITORS_TAKE, isSelfhosted } from 'redux/constants'-const { getAllMonitors } = require('api')--export default function* loadMonitors({ payload: { take = DEFAULT_MONITORS_TAKE, skip = 0 } }) {- if (isSelfhosted) {- yield put(UIActions.setMonitorsLoading(false))- return- }-- try {- yield put(UIActions.setMonitorsLoading(true))- const { results, total, page_total: pageTotal } = yield call(getAllMonitors, take, skip)-- yield put(UIActions.setMonitors(results))- yield put(- UIActions.setMonitorsTotal({- total,- pageTotal,- }),- )- } catch (reason: unknown) {- const { message } = reason as { message: string }- if (_isString(message)) {- toast.error(message)- }- } finally {- yield put(UIActions.setMonitorsLoading(false))- }-}diff --git a/web/app/redux/sagas/ui/load_usageinfo.ts b/web/app/redux/sagas/ui/load_usageinfo.tsdeleted file mode 100644index 11a45d4ec..000000000--- a/web/app/redux/sagas/ui/load_usageinfo.ts+++ /dev/null@@ -1,27 +0,0 @@-import { put, call, select } from 'redux-saga/effects'--import UIActions from 'redux/reducers/ui'-import { isSelfhosted } from 'redux/constants'-import { IUsageInfo } from 'redux/models/IUsageinfo'-const { getUsageInfo } = require('api')--export default function* loadUsageinfo() {- if (isSelfhosted) {- return- }-- const isUsageinfoLoaded: boolean = yield select((state) => state.ui.misc.usageinfoLoaded)-- if (isUsageinfoLoaded) {- return- }-- try {- const info: IUsageInfo = yield call(getUsageInfo)-- yield put(UIActions.setUsageinfo(info))- } catch (reason: unknown) {- const { message } = reason as { message: string }- console.error('failed to load usageinfo:', message)- }-}diff --git a/web/app/redux/sagas/ui/share_verify.ts b/web/app/redux/sagas/ui/share_verify.tsdeleted file mode 100644index 3acb67ddb..000000000--- a/web/app/redux/sagas/ui/share_verify.ts+++ /dev/null@@ -1,22 +0,0 @@-import { call } from 'redux-saga/effects'-const { verifyShare } = require('api')--export default function* shareVerify({- payload: { data, successfulCallback, errorCallback },-}: {- payload: {- data: {- path: string- id: string- }- successfulCallback: () => void- errorCallback: (error: any) => void- }-}) {- try {- yield call(verifyShare, data)- successfulCallback()- } catch (reason) {- errorCallback(reason)- }-}diff --git a/web/app/redux/sagas/ui/worker_general_stats.ts b/web/app/redux/sagas/ui/worker_general_stats.tsdeleted file mode 100644index 55a0fd4fe..000000000--- a/web/app/redux/sagas/ui/worker_general_stats.ts+++ /dev/null@@ -1,27 +0,0 @@-import { put, call, delay } from 'redux-saga/effects'--import UIActions from 'redux/reducers/ui'-import { isSelfhosted } from 'redux/constants'-import { IStats } from 'redux/models/IStats'-const { getGeneralStats } = require('api')--const RETRY_INTERVAL = 10000 // 10 seconds--export default function* generalStats() {- if (isSelfhosted) {- return- }-- while (true) {- try {- const stats: IStats = yield call(getGeneralStats)-- yield put(UIActions.setGeneralStats(stats))- return- } catch (reason) {- console.error('Error while getting general stats data:', reason)- }-- yield delay(RETRY_INTERVAL)- }-}diff --git a/web/app/redux/sagas/ui/worker_is_events_available.ts b/web/app/redux/sagas/ui/worker_is_events_available.tsdeleted file mode 100644index de2ae3299..000000000--- a/web/app/redux/sagas/ui/worker_is_events_available.ts+++ /dev/null@@ -1,51 +0,0 @@-import { put, delay, select } from 'redux-saga/effects'-import _isNull from 'lodash/isNull'--import UIActions from 'redux/reducers/ui'-import { SHOW_BANNER_AT_PERC, LOW_EVENTS_WARNING } from 'redux/constants'-import { getCookie } from 'utils/cookie'--const NOT_AUTHED_INTERVAL = 1000 // 1 second-const NO_DATA_YET = 1000 // 1 second-const DATA_REQUEST_ATTEMPTS = 20--export default function* checkEventsAvailable() {- const lowEvents = getCookie(LOW_EVENTS_WARNING)-- if (lowEvents) {- return- }-- let dataRequests = 0-- while (true) {- if (dataRequests > DATA_REQUEST_ATTEMPTS) {- return- }-- const isAuthenticated: boolean = yield select((state) => state.auth.authenticated)-- if (!isAuthenticated) {- yield delay(NOT_AUTHED_INTERVAL)- continue- }-- const totalMonthlyEvents: number | null = yield select((state) => state.ui.projects.totalMonthlyEvents)-- if (_isNull(totalMonthlyEvents)) {- dataRequests++- yield delay(NO_DATA_YET)- continue- }-- const maxEventsCount: number = yield select((state) => state.auth.user.maxEventsCount)-- const eventsUsedPercentage = (totalMonthlyEvents * 100) / maxEventsCount-- if (eventsUsedPercentage >= SHOW_BANNER_AT_PERC) {- yield put(UIActions.setShowNoEventsLeftBanner(true))- }-- return- }-}diff --git a/web/app/redux/store/index.ts b/web/app/redux/store/index.tsindex f32cbb05a..4d7a424b3 100644--- a/web/app/redux/store/index.ts+++ b/web/app/redux/store/index.ts@@ -1,14 +1,11 @@import { combineReducers, configureStore } from '@reduxjs/toolkit'-import createSagaMiddleware from 'redux-saga'import { useDispatch } from 'react-redux'import { isDevelopment } from 'redux/constants'-import rootSaga from '../sagas'import authSlice from '../reducers/auth'import miscSlice from '../reducers/ui/misc'import projectsSlice from '../reducers/ui/projects'import themeSlice from '../reducers/ui/theme'import cacheSlice from '../reducers/ui/cache'-import monitorsSlice from '../reducers/ui/monitors'const rootReducer = combineReducers({auth: authSlice,@@ -17,20 +14,15 @@ const rootReducer = combineReducers({projects: projectsSlice,theme: themeSlice,cache: cacheSlice,- monitors: monitorsSlice,}),})-const sagaMiddleware = createSagaMiddleware()-export const store = configureStore({reducer: rootReducer,- middleware: [sagaMiddleware],+ middleware: [],devTools: isDevelopment,})-sagaMiddleware.run(rootSaga)-export type AppDispatch = typeof store.dispatchexport const useAppDispatch: () => AppDispatch = useDispatchexport type StateType = ReturnType<typeof store.getState>diff --git a/web/app/routes/index.tsx b/web/app/routes/index.tsxindex 1fa579309..40c153817 100644--- a/web/app/routes/index.tsx+++ b/web/app/routes/index.tsx@@ -155,7 +155,7 @@ const Problem = () => {)}-interface IFeedback {+interface FeedbackProps {name: stringtitle: stringfeedback: React.ReactNode@@ -163,7 +163,7 @@ interface IFeedback {photoUrl: string}-const Feedback = ({ name, title, feedback, logoUrl, photoUrl }: IFeedback) => (+const Feedback = ({ name, title, feedback, logoUrl, photoUrl }: FeedbackProps) => (<section className='relative isolate z-10 bg-white px-6 py-24 dark:bg-slate-900 sm:py-32 lg:px-8'><div className='absolute inset-0 -z-10 bg-[radial-gradient(45rem_50rem_at_top,theme(colors.indigo.100),white)] opacity-20 blur-3xl dark:bg-[radial-gradient(45rem_50rem_at_top,theme(colors.indigo.400),theme(colors.slate.900))]' /><div className='absolute inset-y-0 right-1/2 -z-10 mr-16 w-[200%] origin-bottom-left skew-x-[-30deg] border-r-2 border-slate-900/10 bg-white dark:border-slate-50/50 dark:bg-slate-900 sm:mr-28 lg:mr-0 xl:mr-16 xl:origin-center' />diff --git a/web/app/routes/projects.$pid.uptime.settings.$id.tsx b/web/app/routes/projects.$pid.uptime.settings.$id.tsxindex 72d65c067..ab8163631 100644--- a/web/app/routes/projects.$pid.uptime.settings.$id.tsx+++ b/web/app/routes/projects.$pid.uptime.settings.$id.tsx@@ -1,5 +1,5 @@import UptimeSettings from 'pages/Project/uptime/Settings'export default function Index() {- return <UptimeSettings />+ return <UptimeSettings isSettings />}diff --git a/web/app/ui/Badge.tsx b/web/app/ui/Badge.tsxindex 74eb34203..c740dabff 100644--- a/web/app/ui/Badge.tsx+++ b/web/app/ui/Badge.tsx@@ -7,7 +7,7 @@ export interface BadgeProps {colour?: 'red' | 'yellow' | 'green' | 'indigo' | 'slate' | 'sky'}-export const Badge = ({ label, className, colour }: BadgeProps): JSX.Element => (+export const Badge = ({ label, className, colour }: BadgeProps) => (<spanclassName={cx('inline-flex items-center rounded-md px-2 py-1 text-xs font-medium ring-1 ring-inset', className, {'bg-slate-50 text-slate-600 ring-slate-500/10 dark:bg-slate-400/10 dark:text-slate-400 dark:ring-slate-400/20':diff --git a/web/app/ui/Beta.tsx b/web/app/ui/Beta.tsxindex c94f6f7b3..f58b0e8f2 100644--- a/web/app/ui/Beta.tsx+++ b/web/app/ui/Beta.tsx@@ -4,11 +4,11 @@ import { useTranslation } from 'react-i18next'import Tooltip from './Tooltip'import { Badge } from './Badge'-interface IBeta {+interface BetaProps {className?: string}-const Beta = ({ className }: IBeta): JSX.Element => {+const Beta = ({ className }: BetaProps) => {const { t } = useTranslation('common')return (diff --git a/web/app/ui/Button.tsx b/web/app/ui/Button.tsxindex ce45e8e66..31cb597a4 100644--- a/web/app/ui/Button.tsx+++ b/web/app/ui/Button.tsx@@ -4,7 +4,7 @@ import { Button as HeadlessButton } from '@headlessui/react'import cx from 'clsx'import Spin from './icons/Spin'-interface IButton extends React.ComponentPropsWithoutRef<typeof HeadlessButton> {+interface ButtonProps extends React.ComponentPropsWithoutRef<typeof HeadlessButton> {text?: stringchildren?: React.ReactNodeprimary?: boolean@@ -43,7 +43,7 @@ const Button = ({focus = true,disabled,...props-}: IButton) => (+}: ButtonProps) => (<HeadlessButton{...props}disabled={disabled || loading}diff --git a/web/app/ui/Chart.tsx b/web/app/ui/Chart.tsxindex 1de8ea6d9..183f2036b 100644--- a/web/app/ui/Chart.tsx+++ b/web/app/ui/Chart.tsx@@ -4,14 +4,14 @@ import 'billboard.js/dist/theme/datalab.css'import 'billboard.js/dist/billboard.css'// Define the prop types for the component-interface IChart {+interface ChartProps {// (string): The ID of the chart container.current: string// (object): The chart options.options: any}-const Chart = ({ current, options }: IChart): JSX.Element => {+const Chart = ({ current, options }: ChartProps) => {let chartInstance: any = {}// Destroy the chart instancediff --git a/web/app/ui/Checkbox.tsx b/web/app/ui/Checkbox.tsxindex d4215a32a..e4b5c983a 100644--- a/web/app/ui/Checkbox.tsx+++ b/web/app/ui/Checkbox.tsx@@ -3,9 +3,9 @@ import { Checkbox as HeadlessCheckbox, Description, Field, Label } from '@headleimport { CheckIcon } from '@heroicons/react/24/outline'import cx from 'clsx'-interface ICheckbox {- label: string | JSX.Element- hint?: string | JSX.Element+interface CheckboxProps {+ label: React.ReactNode+ hint?: React.ReactNodename?: stringclassName?: stringonChange?: (checked: boolean) => void@@ -14,16 +14,7 @@ interface ICheckbox {disabled?: boolean}-const Checkbox = ({- label,- hint,- name,- className,- onChange,- checked,- hintClassName,- disabled,-}: ICheckbox): JSX.Element => (+const Checkbox = ({ label, hint, name, className, onChange, checked, hintClassName, disabled }: CheckboxProps) => (<Field className={className} disabled={disabled}><div className='flex items-center gap-2'><HeadlessCheckboxdiff --git a/web/app/ui/Combobox.tsx b/web/app/ui/Combobox.tsxindex 2b81d0a8a..de8d6faea 100644--- a/web/app/ui/Combobox.tsx+++ b/web/app/ui/Combobox.tsx@@ -9,7 +9,7 @@ import _filter from 'lodash/filter'import _toLower from 'lodash/toLower'import _includes from 'lodash/includes'-interface ISelect {+interface SelectProps {title?: stringclassName?: stringbuttonClassName?: string@@ -31,7 +31,7 @@ const Combobox = ({buttonClassName,placeholder,disabled,-}: ISelect): JSX.Element => {+}: SelectProps) => {const { t } = useTranslation('common')const [query, setQuery] = useState('')diff --git a/web/app/ui/Dropdown.tsx b/web/app/ui/Dropdown.tsxindex c2f47f90e..392deedfe 100644--- a/web/app/ui/Dropdown.tsx+++ b/web/app/ui/Dropdown.tsx@@ -7,7 +7,7 @@ import _map from 'lodash/map'import _isEmpty from 'lodash/isEmpty'import Spin from './icons/Spin'-interface IDropdown<T> {+interface DropdownProps<T> {title: string | number | React.ReactNodedesc?: string | number | React.ReactNodeclassName?: string@@ -19,7 +19,7 @@ interface IDropdown<T> {buttonClassName?: stringselectItemClassName?: stringmenuItemsClassName?: string- header?: string | JSX.Element+ header?: React.ReactNodechevron?: 'regular' | 'mini'headless?: booleandisabled?: boolean@@ -45,7 +45,7 @@ function Dropdown<T>({disabled,onClick,loading,-}: IDropdown<T>): JSX.Element {+}: DropdownProps<T>) {return (<Menu as='div' className={cx('relative inline-block text-left', className)}>{({ open, close }) => (diff --git a/web/app/ui/Flag.tsx b/web/app/ui/Flag.tsxindex b31772a25..251ff268e 100644--- a/web/app/ui/Flag.tsx+++ b/web/app/ui/Flag.tsx@@ -2,7 +2,7 @@ import React from 'react'import _toLower from 'lodash/toLower'import _includes from 'lodash/includes'-interface IFlag extends React.HTMLAttributes<HTMLImageElement> {+interface FlagProps extends React.HTMLAttributes<HTMLImageElement> {country: stringsize?: numberalt?: string@@ -12,7 +12,7 @@ const FLAGS_PREFIX_PATH = '/assets/flags'const MISSING_FLAGS = ['t1']-const Flag = ({ country, size = 24, alt, ...props }: IFlag): JSX.Element => {+const Flag = ({ country, size = 24, alt, ...props }: FlagProps) => {const countryLower = _toLower(country)if (_includes(MISSING_FLAGS, countryLower)) {diff --git a/web/app/ui/Highlighted.tsx b/web/app/ui/Highlighted.tsxindex e50c9d26f..fdb7b07be 100644--- a/web/app/ui/Highlighted.tsx+++ b/web/app/ui/Highlighted.tsx@@ -1,10 +1,10 @@import React from 'react'-interface IHighlighted {+interface HighlightedProps {children: React.ReactNode}-const Highlighted = ({ children }: IHighlighted) => (+const Highlighted = ({ children }: HighlightedProps) => (<span className='rounded bg-slate-200 px-1 text-gray-900 dark:bg-slate-700 dark:text-gray-50'>{children}</span>)diff --git a/web/app/ui/Input.tsx b/web/app/ui/Input.tsxindex 55a35c995..8d009b3ef 100644--- a/web/app/ui/Input.tsx+++ b/web/app/ui/Input.tsx@@ -4,9 +4,9 @@ import cx from 'clsx'import _isEmpty from 'lodash/isEmpty'import Beta from 'ui/Beta'-interface IInput {- label?: string | JSX.Element- hint?: string | JSX.Element+interface InputProps {+ label?: React.ReactNode+ hint?: React.ReactNodeclassName?: stringerror?: string | null | booleandisabled?: boolean@@ -29,7 +29,7 @@ const Input = ({classes,hintPosition = 'bottom',...rest-}: IInput & React.InputHTMLAttributes<HTMLInputElement>): JSX.Element => {+}: InputProps & React.InputHTMLAttributes<HTMLInputElement>) => {const isError = !_isEmpty(error)const type = rest.type || 'text'diff --git a/web/app/ui/Modal.tsx b/web/app/ui/Modal.tsxindex 44563a939..bb8d62671 100644--- a/web/app/ui/Modal.tsx+++ b/web/app/ui/Modal.tsx@@ -11,7 +11,7 @@ import {import Beta from 'ui/Beta'import Spin from './icons/Spin'-interface IModal {+interface ModalProps {className?: stringtype?: 'error' | 'success' | 'info' | 'warning' | 'confirmed'title?: string@@ -24,7 +24,7 @@ interface IModal {submitDisabled?: booleansubmitType?: 'regular' | 'danger'size?: 'regular' | 'large'- customButtons?: JSX.Element+ customButtons?: React.ReactNodeisBeta?: booleanisLoading?: booleanoverflowVisible?: boolean@@ -47,7 +47,7 @@ const Modal = ({isLoading,submitDisabled,overflowVisible,-}: IModal): JSX.Element => (+}: ModalProps) => (<Transition show={isOpened} as={Fragment}><Dialogas='div'diff --git a/web/app/ui/MultiSelect.tsx b/web/app/ui/MultiSelect.tsxindex 859daa890..b982b095f 100644--- a/web/app/ui/MultiSelect.tsx+++ b/web/app/ui/MultiSelect.tsx@@ -5,7 +5,7 @@ import _map from 'lodash/map'import _includes from 'lodash/includes'import _isEmpty from 'lodash/isEmpty'-interface IMultiSelect {+interface MultiSelectProps {className?: stringonRemove: (item: any) => voidonSelect: (item: any) => void@@ -33,7 +33,7 @@ const MultiSelect = ({itemExtractor,searchPlaseholder = 'Search...',onSearch,-}: IMultiSelect) => {+}: MultiSelectProps) => {const [selected, setSelected] = useState(false)return (diff --git a/web/app/ui/Pagination.tsx b/web/app/ui/Pagination.tsxindex b9b8106a7..66db7c404 100644--- a/web/app/ui/Pagination.tsx+++ b/web/app/ui/Pagination.tsx@@ -5,7 +5,7 @@ import cx from 'clsx'import { useTranslation } from 'react-i18next'import { usePagination, DOTS } from 'hooks/usePagination'-interface IPagination {+interface PaginationProps {page: numbersetPage: (item: number) => voidpageAmount: number@@ -14,7 +14,7 @@ interface IPagination {pageSize?: number}-const Pagination = ({ page, setPage, pageAmount, total, className, pageSize }: IPagination): JSX.Element => {+const Pagination = ({ page, setPage, pageAmount, total, className, pageSize }: PaginationProps) => {const { t } = useTranslation('common')const paginationRange = usePagination(total, page, 1, pageSize)diff --git a/web/app/ui/Select.tsx b/web/app/ui/Select.tsxindex e00272758..3c7155e0f 100644--- a/web/app/ui/Select.tsx+++ b/web/app/ui/Select.tsx@@ -12,7 +12,7 @@ import {import { CheckIcon, ChevronUpDownIcon } from '@heroicons/react/24/solid'import _map from 'lodash/map'-interface ISelect<T> {+interface SelectProps<T> {title?: stringlabel?: stringhint?: string | React.ReactNode@@ -42,7 +42,7 @@ function Select<T>({buttonClassName,capitalise,labelClassName,-}: ISelect<T>): React.ReactNode {+}: SelectProps<T>) {return (// @ts-expect-error<Listbox id={id || ''} value={title} onChange={onSelect}>diff --git a/web/app/ui/Textarea.tsx b/web/app/ui/Textarea.tsxindex 21db20ae3..71ade41f2 100644--- a/web/app/ui/Textarea.tsx+++ b/web/app/ui/Textarea.tsx@@ -3,7 +3,7 @@ import { Description, Field, Label, Textarea as HeadlessTextarea } from '@headleimport cx from 'clsx'import _isEmpty from 'lodash/isEmpty'-interface ITextarea {+interface TextareaProps {value: string | numberlabel?: stringhint?: string@@ -29,7 +29,7 @@ const Textarea = ({disabled,readOnly,rows = 4,-}: ITextarea) => {+}: TextareaProps) => {const isError = !_isEmpty(error)return (diff --git a/web/app/ui/TimezonePicker.tsx b/web/app/ui/TimezonePicker.tsxindex 4c1cc146e..138bb187d 100644--- a/web/app/ui/TimezonePicker.tsx+++ b/web/app/ui/TimezonePicker.tsx@@ -37,7 +37,7 @@ const options = _reduce([],).sort((a, b) => a.offset - b.offset)-interface ITimezoneSelect {+interface TimezoneSelectProps {value:| string| {@@ -47,7 +47,7 @@ interface ITimezoneSelect {onChange: (item: string) => void}-const TimezoneSelect = ({ value, onChange }: ITimezoneSelect): JSX.Element => {+const TimezoneSelect = ({ value, onChange }: TimezoneSelectProps) => {const { t } = useTranslation('common')const labelExtractor = (option: { label: string }) => option?.labelconst keyExtractor = (option: { value: string }) => option?.valuediff --git a/web/app/ui/Tooltip.tsx b/web/app/ui/Tooltip.tsxindex d4cd88bb7..a5cde8c42 100644--- a/web/app/ui/Tooltip.tsx+++ b/web/app/ui/Tooltip.tsx@@ -34,7 +34,7 @@ TooltipContent.displayName = TooltipPrimitive.Content.displayNameinterface TooltipProps {text: string | number | React.ReactNodeclassName?: string- tooltipNode?: JSX.Element+ tooltipNode?: React.ReactNode}const Tooltip = ({ text, className, tooltipNode }: TooltipProps) => (diff --git a/web/app/ui/icons/BackgroundSvg.tsx b/web/app/ui/icons/BackgroundSvg.tsxindex f8e20c4f5..0be36b934 100644--- a/web/app/ui/icons/BackgroundSvg.tsx+++ b/web/app/ui/icons/BackgroundSvg.tsx@@ -1,14 +1,14 @@import React from 'react'import cx from 'clsx'-interface IBackgroundSvg {+interface BackgroundSvgProps {className?: stringtype: 'shapes' | 'circle' | 'semicircle' | 'twolinecircle' | 'threecircle' | 'twolinecircle2'- children?: JSX.Element+ children?: React.ReactNodetheme: 'dark' | 'light'}-const BackgroundSvg: React.FC<IBackgroundSvg> = ({ className, type, children, theme }): JSX.Element => {+const BackgroundSvg = ({ className, type, children, theme }: BackgroundSvgProps) => {if (type === 'shapes') {return (<svgdiff --git a/web/app/ui/icons/BarChart.tsx b/web/app/ui/icons/BarChart.tsxindex b60f6e318..38bc20d75 100644--- a/web/app/ui/icons/BarChart.tsx+++ b/web/app/ui/icons/BarChart.tsx@@ -1,11 +1,11 @@import React from 'react'import cx from 'clsx'-interface IBarChart {+interface BarChartProps {className?: string}-const BarChart = ({ className }: IBarChart): JSX.Element => (+const BarChart = ({ className }: BarChartProps) => (<svg className={cx('fill-gray-700 dark:fill-gray-50', className)} viewBox='0 0 448 512'>{/* Font Awesome Free 6.4.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2023 Fonticons, Inc. */}<pathdiff --git a/web/app/ui/icons/Discord.tsx b/web/app/ui/icons/Discord.tsxindex 2703405ea..a378779b1 100644--- a/web/app/ui/icons/Discord.tsx+++ b/web/app/ui/icons/Discord.tsx@@ -1,6 +1,6 @@import React from 'react'-const Discord = ({ className }: { className?: string }): JSX.Element => (+const Discord = ({ className }: { className?: string }) => (<svg className={className} viewBox='0 0 127.14 96.36'><title>Discord</title><pathdiff --git a/web/app/ui/icons/GithubDark.tsx b/web/app/ui/icons/GithubDark.tsxindex 212480c32..8fd01ebd8 100644--- a/web/app/ui/icons/GithubDark.tsx+++ b/web/app/ui/icons/GithubDark.tsx@@ -1,6 +1,6 @@import React from 'react'-const GithubDarkSVG = ({ className }: { className?: string }): JSX.Element => (+const GithubDarkSVG = ({ className }: { className?: string }) => (<svg className={className} viewBox='0 0 100 100'><pathfillRule='evenodd'diff --git a/web/app/ui/icons/GithubLight.tsx b/web/app/ui/icons/GithubLight.tsxindex 0f301a43a..e228bac5c 100644--- a/web/app/ui/icons/GithubLight.tsx+++ b/web/app/ui/icons/GithubLight.tsx@@ -1,6 +1,6 @@import React from 'react'-const GithubLightSVG = ({ className }: { className?: string }): JSX.Element => (+const GithubLightSVG = ({ className }: { className?: string }) => (<svg className={className} viewBox='0 0 100 100'><pathfillRule='evenodd'diff --git a/web/app/ui/icons/GoogleG.tsx b/web/app/ui/icons/GoogleG.tsxindex 738badf66..a1685e33e 100644--- a/web/app/ui/icons/GoogleG.tsx+++ b/web/app/ui/icons/GoogleG.tsx@@ -1,6 +1,6 @@import React from 'react'-const GoogleGSVG = ({ className }: { className?: string }): JSX.Element => (+const GoogleGSVG = ({ className }: { className?: string }) => (<svg className={className} viewBox='0 0 186.69 190.5'><g transform='translate(1184.583 765.171)'><pathdiff --git a/web/app/ui/icons/LineChart.tsx b/web/app/ui/icons/LineChart.tsxindex 751a20800..dcd2da5f1 100644--- a/web/app/ui/icons/LineChart.tsx+++ b/web/app/ui/icons/LineChart.tsx@@ -1,11 +1,11 @@import React from 'react'import cx from 'clsx'-interface ILineChart {+interface LineChartProps {className?: string}-const LineChart = ({ className }: ILineChart): JSX.Element => (+const LineChart = ({ className }: LineChartProps) => (<svg className={cx('fill-gray-700 dark:fill-gray-50', className)} viewBox='0 0 512 512'>{/* Font Awesome Free 6.4.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2023 Fonticons, Inc. */}<path d='M64 64c0-17.7-14.3-32-32-32S0 46.3 0 64V400c0 44.2 35.8 80 80 80H480c17.7 0 32-14.3 32-32s-14.3-32-32-32H80c-8.8 0-16-7.2-16-16V64zm406.6 86.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L320 210.7l-57.4-57.4c-12.5-12.5-32.8-12.5-45.3 0l-112 112c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0L240 221.3l57.4 57.4c12.5 12.5 32.8 12.5 45.3 0l128-128z' />diff --git a/web/app/ui/icons/PulsatingCircle.tsx b/web/app/ui/icons/PulsatingCircle.tsxindex b323ffec1..050d9caee 100644--- a/web/app/ui/icons/PulsatingCircle.tsx+++ b/web/app/ui/icons/PulsatingCircle.tsx@@ -16,12 +16,12 @@ const types = {},}-interface IPulsatingCircle {+interface PulsatingCircleProps {className?: stringtype: 'small' | 'big' | 'giant'}-const PulsatingCircle = ({ className, type = 'small' }: IPulsatingCircle): JSX.Element => (+const PulsatingCircle = ({ className, type = 'small' }: PulsatingCircleProps) => (<span className={cx('flex items-center justify-center', types[type]?.pulse, className)}><span className={cx('absolute inline-flex animate-ping-slow rounded-full bg-green-400', types[type]?.pulse)} /><span className={cx('relative inline-flex rounded-full bg-green-500', types[type]?.base)} />diff --git a/web/app/ui/icons/Robot.tsx b/web/app/ui/icons/Robot.tsxindex b1cdf7aac..42faf369e 100644--- a/web/app/ui/icons/Robot.tsx+++ b/web/app/ui/icons/Robot.tsx@@ -1,13 +1,13 @@import React from 'react'import cx from 'clsx'-interface IRobot {+interface RobotProps {className?: stringcontainerClassName?: stringtheme: 'dark' | 'light'}-const Robot: React.FC<IRobot> = ({ className, containerClassName, theme }): JSX.Element => {+const Robot = ({ className, containerClassName, theme }: RobotProps) => {const cn = cx(className, {'fill-text-gray-700': theme === 'dark','fill-white': theme === 'light',diff --git a/web/app/ui/icons/Slack.tsx b/web/app/ui/icons/Slack.tsxindex 465263484..0f588d56c 100644--- a/web/app/ui/icons/Slack.tsx+++ b/web/app/ui/icons/Slack.tsx@@ -1,6 +1,6 @@import React from 'react'-const Slack = ({ className }: { className?: string }): JSX.Element => (+const Slack = ({ className }: { className?: string }) => (<svg className={className} viewBox='0 0 127 127'><title>Slack</title><pathdiff --git a/web/app/ui/icons/Sort.tsx b/web/app/ui/icons/Sort.tsxindex b7136e8bb..a99b0d942 100644--- a/web/app/ui/icons/Sort.tsx+++ b/web/app/ui/icons/Sort.tsx@@ -2,13 +2,13 @@ import React from 'react'import { ChevronUpDownIcon, ChevronUpIcon, ChevronDownIcon } from '@heroicons/react/24/outline'import cx from 'clsx'-interface ISort {+interface SortProps {sortByAscend?: booleansortByDescend?: booleanclassName?: string}-const Sort: React.FC<ISort> = ({ sortByAscend, sortByDescend, className }: ISort): JSX.Element => {+const Sort = ({ sortByAscend, sortByDescend, className }: SortProps) => {if (sortByAscend) {return <ChevronUpIcon className={cx(className, 'h-4 w-4')} />}diff --git a/web/app/ui/icons/Spin.tsx b/web/app/ui/icons/Spin.tsxindex d7b6dee8f..433771adc 100644--- a/web/app/ui/icons/Spin.tsx+++ b/web/app/ui/icons/Spin.tsx@@ -1,12 +1,12 @@import React from 'react'import cx from 'clsx'-interface ISpin {+interface SpinProps {className?: stringalwaysLight?: boolean}-const Spin = ({ className, alwaysLight }: ISpin): JSX.Element => (+const Spin = ({ className, alwaysLight }: SpinProps) => (<svgclassName={cx('-ml-1 mr-2 h-4 w-4 animate-spin text-slate-900 dark:text-white',diff --git a/web/app/ui/icons/Telegram.tsx b/web/app/ui/icons/Telegram.tsxindex 73ea38f89..d621e1215 100644--- a/web/app/ui/icons/Telegram.tsx+++ b/web/app/ui/icons/Telegram.tsx@@ -1,6 +1,6 @@import React from 'react'-const Telegram = ({ className }: { className?: string }): JSX.Element => (+const Telegram = ({ className }: { className?: string }) => (<svg className={className} viewBox='0 0 1000 1000'><title>Telegram</title><defs>diff --git a/web/app/utils/accessToken.ts b/web/app/utils/accessToken.tsindex 8796ca484..4375d8ad1 100644--- a/web/app/utils/accessToken.ts+++ b/web/app/utils/accessToken.ts@@ -20,7 +20,7 @@ export const getAccessToken = () => {return accessToken}-export const setAccessToken = (token: string, temporary: boolean = false) => {+export const setAccessToken = (token: string, temporary = false) => {if (!isBrowser) {return null}diff --git a/web/app/utils/auth.ts b/web/app/utils/auth.tsnew file mode 100644index 000000000..b40bbe0f4--- /dev/null+++ b/web/app/utils/auth.ts@@ -0,0 +1,47 @@+import {+ isSelfhosted,+ LOW_EVENTS_WARNING,+ LS_CAPTCHA_VIEW_PREFS_SETTING,+ LS_VIEW_PREFS_SETTING,+ SHOW_BANNER_AT_PERC,+} from 'redux/constants'+import { logoutAllApi, logoutApi } from 'api'+import { getCookie } from './cookie'+import { getRefreshToken, removeRefreshToken } from './refreshToken'+import { removeAccessToken } from './accessToken'+import { removeItem } from './localstorage'++export const shouldShowLowEventsBanner = (totalMonthlyEvents: number, maxEventsCount: number) => {+ if (isSelfhosted) {+ return false+ }++ const lowEvents = getCookie(LOW_EVENTS_WARNING)++ if (lowEvents) {+ return false+ }++ const eventsUsedPercentage = (totalMonthlyEvents * 100) / maxEventsCount++ return eventsUsedPercentage >= SHOW_BANNER_AT_PERC+}++export const logout = async (invalidateAllSessions?: boolean) => {+ const refreshToken = getRefreshToken()++ try {+ if (invalidateAllSessions) {+ await logoutAllApi()+ } else {+ await logoutApi(refreshToken)+ }+ } catch (reason) {+ console.error('Failed to invalidate refresh token', reason)+ }++ removeAccessToken()+ removeItem(LS_VIEW_PREFS_SETTING)+ removeItem(LS_CAPTCHA_VIEW_PREFS_SETTING)+ removeRefreshToken()+}diff --git a/web/app/utils/generic.ts b/web/app/utils/generic.tsindex c24048d95..ff83bbe6c 100644--- a/web/app/utils/generic.ts+++ b/web/app/utils/generic.ts@@ -87,7 +87,7 @@ export const sumArrays = (...arrays: any): number[] => {})}-export const openBrowserWindow = (url: string, width: number, height: number) => {+export const openBrowserWindow = (url: string, width = 600, height = 800) => {return window.open(url,'',@@ -133,3 +133,5 @@ export const getLocaleDisplayName = (locale: string, language: string): string =return locale}}++export const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))diff --git a/web/app/utils/getPosts.ts b/web/app/utils/getPosts.tsindex 7f7ae2114..417d734b8 100644--- a/web/app/utils/getPosts.ts+++ b/web/app/utils/getPosts.ts@@ -18,7 +18,7 @@ renderer.link = ({ href, text }: Tokens.Link) => {export const getSlugFromFilename = (filename: string) => filename.substring(11)export const getDateFromFilename = (filename: string) => filename.substring(0, 10)-interface IPost {+interface GetPost {slug: stringtitle?: stringhtml: string@@ -29,7 +29,7 @@ interface IPost {nickname?: string}-export async function getPost(slug: string, category?: string): Promise<IPost | null> {+export async function getPost(slug: string, category?: string): Promise<GetPost | null> {let post: any = nullif (category) {diff --git a/web/app/utils/server.ts b/web/app/utils/server.tsindex b102b0cb5..a720d219c 100644--- a/web/app/utils/server.ts+++ b/web/app/utils/server.ts@@ -69,15 +69,15 @@ export function isWWW(url: URL): boolean {return _startsWith(url.hostname, 'www.')}-interface IPageMeta {+interface GetPageMeta {title: stringprefixLessTitle: string}-export const getPageMeta = (t: typeof i18next.t, url?: string, _pathname?: string): IPageMeta => {+export const getPageMeta = (t: typeof i18next.t, url?: string, _pathname?: string): GetPageMeta => {const DEFAULT_RESULT = {title: t('titles.main'),- } as Partial<IPageMeta>+ } as Partial<GetPageMeta>if (!url && !_pathname) {return {@@ -264,5 +264,5 @@ export const getPageMeta = (t: typeof i18next.t, url?: string, _pathname?: strinresult.prefixLessTitle = result.titleresult.title += ` ${TITLE_SUFFIX}`- return result as IPageMeta+ return result as GetPageMeta}diff --git a/web/package-lock.json b/web/package-lock.jsonindex cabda994f..752ef041a 100644--- a/web/package-lock.json+++ b/web/package-lock.json@@ -49,7 +49,6 @@"react-qr-code": "^2.0.15","react-redux": "^9.1.2","redux": "^5.0.1",- "redux-saga": "^1.3.0","remix-i18next": "^6.4.1","remix-sitemap": "^3.2.0","remix-utils": "^7.7.0",@@ -63,7 +62,6 @@"@remix-run/dev": "^2.13.1","@remix-run/eslint-config": "^2.13.1","@tailwindcss/typography": "^0.5.15",- "@types/debug": "^4.1.12","@types/lodash": "^4.17.13","@types/node": "^22.9.0","@types/react": "^18.3.12",@@ -1773,50 +1771,6 @@"react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0"}},- "node_modules/@redux-saga/core": {- "version": "1.3.0",- "license": "MIT",- "dependencies": {- "@babel/runtime": "^7.6.3",- "@redux-saga/deferred": "^1.2.1",- "@redux-saga/delay-p": "^1.2.1",- "@redux-saga/is": "^1.1.3",- "@redux-saga/symbols": "^1.1.3",- "@redux-saga/types": "^1.2.1",- "typescript-tuple": "^2.2.1"- },- "funding": {- "type": "opencollective",- "url": "https://opencollective.com/redux-saga"- }- },- "node_modules/@redux-saga/deferred": {- "version": "1.2.1",- "license": "MIT"- },- "node_modules/@redux-saga/delay-p": {- "version": "1.2.1",- "license": "MIT",- "dependencies": {- "@redux-saga/symbols": "^1.1.3"- }- },- "node_modules/@redux-saga/is": {- "version": "1.1.3",- "license": "MIT",- "dependencies": {- "@redux-saga/symbols": "^1.1.3",- "@redux-saga/types": "^1.2.1"- }- },- "node_modules/@redux-saga/symbols": {- "version": "1.1.3",- "license": "MIT"- },- "node_modules/@redux-saga/types": {- "version": "1.2.1",- "license": "MIT"- },"node_modules/@reduxjs/toolkit": {"version": "1.9.7","license": "MIT",@@ -10109,13 +10063,6 @@"version": "5.0.1","license": "MIT"},- "node_modules/redux-saga": {- "version": "1.3.0",- "license": "MIT",- "dependencies": {- "@redux-saga/core": "^1.3.0"- }- },"node_modules/reflect.getprototypeof": {"version": "1.0.6","dev": true,@@ -11612,24 +11559,6 @@"node": ">=14.17"}},- "node_modules/typescript-compare": {- "version": "0.0.2",- "license": "MIT",- "dependencies": {- "typescript-logic": "^0.0.0"- }- },- "node_modules/typescript-logic": {- "version": "0.0.0",- "license": "MIT"- },- "node_modules/typescript-tuple": {- "version": "2.2.1",- "license": "MIT",- "dependencies": {- "typescript-compare": "^0.0.2"- }- },"node_modules/ua-parser-js": {"version": "1.0.39","resolved": "https://registry.npmjs.org/ua-parser-js/-/ua-parser-js-1.0.39.tgz",diff --git a/web/package.json b/web/package.jsonindex e35cc0701..e29974520 100644--- a/web/package.json+++ b/web/package.json@@ -62,7 +62,6 @@"react-qr-code": "^2.0.15","react-redux": "^9.1.2","redux": "^5.0.1",- "redux-saga": "^1.3.0","remix-i18next": "^6.4.1","remix-sitemap": "^3.2.0","remix-utils": "^7.7.0",@@ -137,7 +136,6 @@"@remix-run/dev": "^2.13.1","@remix-run/eslint-config": "^2.13.1","@tailwindcss/typography": "^0.5.15",- "@types/debug": "^4.1.12","@types/lodash": "^4.17.13","@types/node": "^22.9.0","@types/react": "^18.3.12",diff --git a/web/public/locales/en.json b/web/public/locales/en.jsonindex 5900356c5..cb545e947 100644--- a/web/public/locales/en.json+++ b/web/public/locales/en.json@@ -63,7 +63,8 @@"orgUserRemoveError": "Error occurred while removing the user from the organisation","orgSettingsUpdated": "Organisation settings have been updated","projectAssigned": "The project has been assigned to the organisation",- "projectAssignError": "Failed to assign the project to the organisation"+ "projectAssignError": "Failed to assign the project to the organisation",+ "failedToLoadUsageInfo": "Failed to load usage info"},"common": {"features": "Features",